text
stringlengths
54
60.6k
<commit_before>//===-- StructRetPromotion.cpp - Promote sret arguments -000000------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // TODO : Describe this pass. //===----------------------------------------------------------------------===// #define DEBUG_TYPE "sretpromotion" #include "llvm/Transforms/IPO.h" #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/Module.h" #include "llvm/CallGraphSCCPass.h" #include "llvm/Instructions.h" #include "llvm/ParamAttrsList.h" #include "llvm/Analysis/CallGraph.h" #include "llvm/Support/CallSite.h" #include "llvm/Support/CFG.h" #include "llvm/Support/Debug.h" #include "llvm/ADT/Statistic.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/Statistic.h" #include "llvm/Support/Compiler.h" using namespace llvm; STATISTIC(NumRejectedSRETUses , "Number of sret rejected due to unexpected uses"); STATISTIC(NumSRET , "Number of sret promoted"); namespace { /// SRETPromotion - This pass removes sret parameter and updates /// function to use multiple return value. /// struct VISIBILITY_HIDDEN SRETPromotion : public CallGraphSCCPass { virtual void getAnalysisUsage(AnalysisUsage &AU) const { CallGraphSCCPass::getAnalysisUsage(AU); } virtual bool runOnSCC(const std::vector<CallGraphNode *> &SCC); static char ID; // Pass identification, replacement for typeid SRETPromotion() : CallGraphSCCPass((intptr_t)&ID) {} private: bool PromoteReturn(CallGraphNode *CGN); bool isSafeToUpdateAllCallers(Function *F); Function *cloneFunctionBody(Function *F, const StructType *STy); void updateCallSites(Function *F, Function *NF); }; char SRETPromotion::ID = 0; RegisterPass<SRETPromotion> X("sretpromotion", "Promote sret arguments to multiple ret values"); } Pass *llvm::createStructRetPromotionPass() { return new SRETPromotion(); } bool SRETPromotion::runOnSCC(const std::vector<CallGraphNode *> &SCC) { bool Changed = false; for (unsigned i = 0, e = SCC.size(); i != e; ++i) Changed |= PromoteReturn(SCC[i]); return Changed; } /// PromoteReturn - This method promotes function that uses StructRet paramater /// into a function that uses mulitple return value. bool SRETPromotion::PromoteReturn(CallGraphNode *CGN) { Function *F = CGN->getFunction(); if (!F || F->isDeclaration()) return false; // Make sure that function returns struct. if (F->arg_size() == 0 || !F->hasStructRetAttr() || F->doesNotReturn()) return false; assert (F->getReturnType() == Type::VoidTy && "Invalid function return type"); Function::arg_iterator AI = F->arg_begin(); const llvm::PointerType *FArgType = dyn_cast<PointerType>(AI->getType()); assert (FArgType && "Invalid sret paramater type"); const llvm::StructType *STy = dyn_cast<StructType>(FArgType->getElementType()); assert (STy && "Invalid sret parameter element type"); // Check if it is ok to perform this promotion. if (isSafeToUpdateAllCallers(F) == false) { NumRejectedSRETUses++; return false; } NumSRET++; // [1] Replace use of sret parameter AllocaInst *TheAlloca = new AllocaInst (STy, NULL, "mrv", F->getEntryBlock().begin()); Value *NFirstArg = F->arg_begin(); NFirstArg->replaceAllUsesWith(TheAlloca); // [2] Find and replace ret instructions SmallVector<Value *,4> RetVals; for (Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI) for(BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) { Instruction *I = BI; ++BI; if (isa<ReturnInst>(I)) { RetVals.clear(); for (unsigned idx = 0; idx < STy->getNumElements(); ++idx) { SmallVector<Value*, 2> GEPIdx; GEPIdx.push_back(ConstantInt::get(Type::Int32Ty, 0)); GEPIdx.push_back(ConstantInt::get(Type::Int32Ty, idx)); Value *NGEPI = new GetElementPtrInst(TheAlloca, GEPIdx.begin(), GEPIdx.end(), "mrv.gep", I); Value *NV = new LoadInst(NGEPI, "mrv.ld", I); RetVals.push_back(NV); } ReturnInst *NR = new ReturnInst(&RetVals[0], RetVals.size(), I); I->replaceAllUsesWith(NR); I->eraseFromParent(); } } // [3] Create the new function body and insert it into the module. Function *NF = cloneFunctionBody(F, STy); // [4] Update all call sites to use new function updateCallSites(F, NF); F->eraseFromParent(); getAnalysis<CallGraph>().changeFunction(F, NF); return true; } // Check if it is ok to perform this promotion. bool SRETPromotion::isSafeToUpdateAllCallers(Function *F) { if (F->use_empty()) // No users. OK to modify signature. return true; for (Value::use_iterator FnUseI = F->use_begin(), FnUseE = F->use_end(); FnUseI != FnUseE; ++FnUseI) { CallSite CS = CallSite::get(*FnUseI); Instruction *Call = CS.getInstruction(); CallSite::arg_iterator AI = CS.arg_begin(); Value *FirstArg = *AI; if (!isa<AllocaInst>(FirstArg)) return false; // Check FirstArg's users. for (Value::use_iterator ArgI = FirstArg->use_begin(), ArgE = FirstArg->use_end(); ArgI != ArgE; ++ArgI) { // If FirstArg user is a CallInst that does not correspond to current // call site then this function F is not suitable for sret promotion. if (CallInst *CI = dyn_cast<CallInst>(ArgI)) { if (CI != Call) return false; } // If FirstArg user is a GEP whose all users are not LoadInst then // this function F is not suitable for sret promotion. else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(ArgI)) { for (Value::use_iterator GEPI = GEP->use_begin(), GEPE = GEP->use_end(); GEPI != GEPE; ++GEPI) if (!isa<LoadInst>(GEPI)) return false; } // Any other FirstArg users make this function unsuitable for sret // promotion. else return false; } } return true; } /// cloneFunctionBody - Create a new function based on F and /// insert it into module. Remove first argument. Use STy as /// the return type for new function. Function *SRETPromotion::cloneFunctionBody(Function *F, const StructType *STy) { const FunctionType *FTy = F->getFunctionType(); std::vector<const Type*> Params; // ParamAttrs - Keep track of the parameter attributes for the arguments. ParamAttrsVector ParamAttrsVec; const ParamAttrsList *PAL = F->getParamAttrs(); // Add any return attributes. if (ParameterAttributes attrs = PAL ? PAL->getParamAttrs(0) : ParamAttr::None) ParamAttrsVec.push_back(ParamAttrsWithIndex::get(0, attrs)); // Skip first argument. Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); ++I; unsigned ParamIndex = 1; // 0th parameter attribute is reserved for return type. while (I != E) { Params.push_back(I->getType()); ParameterAttributes Attrs; if (PAL) { Attrs = PAL->getParamAttrs(ParamIndex); if (ParamIndex == 1) // Skip sret attribute Attrs = Attrs ^ ParamAttr::StructRet; } if (Attrs != ParamAttr::None) ParamAttrsVec.push_back(ParamAttrsWithIndex::get(ParamIndex, Attrs)); ++I; ++ParamIndex; } FunctionType *NFTy = FunctionType::get(STy, Params, FTy->isVarArg()); Function *NF = new Function(NFTy, F->getLinkage(), F->getName()); NF->setCallingConv(F->getCallingConv()); NF->setParamAttrs(ParamAttrsList::get(ParamAttrsVec)); F->getParent()->getFunctionList().insert(F, NF); NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList()); // Replace arguments I = F->arg_begin(); E = F->arg_end(); Function::arg_iterator NI = NF->arg_begin(); ++I; while (I != E) { I->replaceAllUsesWith(NI); NI->takeName(I); ++I; ++NI; } return NF; } /// updateCallSites - Update all sites that call F to use NF. void SRETPromotion::updateCallSites(Function *F, Function *NF) { SmallVector<Value*, 16> Args; // ParamAttrs - Keep track of the parameter attributes for the arguments. ParamAttrsVector ArgAttrsVec; for (Value::use_iterator FUI = F->use_begin(), FUE = F->use_end(); FUI != FUE;) { CallSite CS = CallSite::get(*FUI); ++FUI; Instruction *Call = CS.getInstruction(); const ParamAttrsList *PAL = F->getParamAttrs(); // Add any return attributes. if (ParameterAttributes attrs = PAL ? PAL->getParamAttrs(0) : ParamAttr::None) ArgAttrsVec.push_back(ParamAttrsWithIndex::get(0, attrs)); // Copy arguments, however skip first one. CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end(); Value *FirstCArg = *AI; ++AI; unsigned ParamIndex = 1; // 0th parameter attribute is reserved for return type. while (AI != AE) { Args.push_back(*AI); ParameterAttributes Attrs; if (PAL) { Attrs = PAL->getParamAttrs(ParamIndex); if (ParamIndex == 1) // Skip sret attribute Attrs = Attrs ^ ParamAttr::StructRet; } if (Attrs != ParamAttr::None) ArgAttrsVec.push_back(ParamAttrsWithIndex::get(Args.size(), Attrs)); ++ParamIndex; ++AI; } // Build new call instruction. Instruction *New; if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) { New = new InvokeInst(NF, II->getNormalDest(), II->getUnwindDest(), Args.begin(), Args.end(), "", Call); cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv()); cast<InvokeInst>(New)->setParamAttrs(ParamAttrsList::get(ArgAttrsVec)); } else { New = new CallInst(NF, Args.begin(), Args.end(), "", Call); cast<CallInst>(New)->setCallingConv(CS.getCallingConv()); cast<CallInst>(New)->setParamAttrs(ParamAttrsList::get(ArgAttrsVec)); if (cast<CallInst>(Call)->isTailCall()) cast<CallInst>(New)->setTailCall(); } Args.clear(); ArgAttrsVec.clear(); New->takeName(Call); // Update all users of sret parameter to extract value using getresult. for (Value::use_iterator UI = FirstCArg->use_begin(), UE = FirstCArg->use_end(); UI != UE; ) { User *U2 = *UI++; CallInst *C2 = dyn_cast<CallInst>(U2); if (C2 && (C2 == Call)) continue; else if (GetElementPtrInst *UGEP = dyn_cast<GetElementPtrInst>(U2)) { ConstantInt *Idx = dyn_cast<ConstantInt>(UGEP->getOperand(2)); assert (Idx && "Unexpected getelementptr index!"); Value *GR = new GetResultInst(New, Idx->getZExtValue(), "gr", UGEP); for (Value::use_iterator GI = UGEP->use_begin(), GE = UGEP->use_end(); GI != GE; ++GI) { if (LoadInst *L = dyn_cast<LoadInst>(*GI)) { L->replaceAllUsesWith(GR); L->eraseFromParent(); } } UGEP->eraseFromParent(); } else assert( 0 && "Unexpected sret parameter use"); } Call->eraseFromParent(); } } <commit_msg>Filter nested structs<commit_after>//===-- StructRetPromotion.cpp - Promote sret arguments -000000------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // TODO : Describe this pass. //===----------------------------------------------------------------------===// #define DEBUG_TYPE "sretpromotion" #include "llvm/Transforms/IPO.h" #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/Module.h" #include "llvm/CallGraphSCCPass.h" #include "llvm/Instructions.h" #include "llvm/ParamAttrsList.h" #include "llvm/Analysis/CallGraph.h" #include "llvm/Support/CallSite.h" #include "llvm/Support/CFG.h" #include "llvm/Support/Debug.h" #include "llvm/ADT/Statistic.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/Statistic.h" #include "llvm/Support/Compiler.h" using namespace llvm; STATISTIC(NumRejectedSRETUses , "Number of sret rejected due to unexpected uses"); STATISTIC(NumSRET , "Number of sret promoted"); namespace { /// SRETPromotion - This pass removes sret parameter and updates /// function to use multiple return value. /// struct VISIBILITY_HIDDEN SRETPromotion : public CallGraphSCCPass { virtual void getAnalysisUsage(AnalysisUsage &AU) const { CallGraphSCCPass::getAnalysisUsage(AU); } virtual bool runOnSCC(const std::vector<CallGraphNode *> &SCC); static char ID; // Pass identification, replacement for typeid SRETPromotion() : CallGraphSCCPass((intptr_t)&ID) {} private: bool PromoteReturn(CallGraphNode *CGN); bool isSafeToUpdateAllCallers(Function *F); Function *cloneFunctionBody(Function *F, const StructType *STy); void updateCallSites(Function *F, Function *NF); bool nestedStructType(const StructType *STy); }; char SRETPromotion::ID = 0; RegisterPass<SRETPromotion> X("sretpromotion", "Promote sret arguments to multiple ret values"); } Pass *llvm::createStructRetPromotionPass() { return new SRETPromotion(); } bool SRETPromotion::runOnSCC(const std::vector<CallGraphNode *> &SCC) { bool Changed = false; for (unsigned i = 0, e = SCC.size(); i != e; ++i) Changed |= PromoteReturn(SCC[i]); return Changed; } /// PromoteReturn - This method promotes function that uses StructRet paramater /// into a function that uses mulitple return value. bool SRETPromotion::PromoteReturn(CallGraphNode *CGN) { Function *F = CGN->getFunction(); if (!F || F->isDeclaration()) return false; // Make sure that function returns struct. if (F->arg_size() == 0 || !F->hasStructRetAttr() || F->doesNotReturn()) return false; assert (F->getReturnType() == Type::VoidTy && "Invalid function return type"); Function::arg_iterator AI = F->arg_begin(); const llvm::PointerType *FArgType = dyn_cast<PointerType>(AI->getType()); assert (FArgType && "Invalid sret paramater type"); const llvm::StructType *STy = dyn_cast<StructType>(FArgType->getElementType()); assert (STy && "Invalid sret parameter element type"); if (nestedStructType(STy)) return false; // Check if it is ok to perform this promotion. if (isSafeToUpdateAllCallers(F) == false) { NumRejectedSRETUses++; return false; } NumSRET++; // [1] Replace use of sret parameter AllocaInst *TheAlloca = new AllocaInst (STy, NULL, "mrv", F->getEntryBlock().begin()); Value *NFirstArg = F->arg_begin(); NFirstArg->replaceAllUsesWith(TheAlloca); // [2] Find and replace ret instructions SmallVector<Value *,4> RetVals; for (Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI) for(BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) { Instruction *I = BI; ++BI; if (isa<ReturnInst>(I)) { RetVals.clear(); for (unsigned idx = 0; idx < STy->getNumElements(); ++idx) { SmallVector<Value*, 2> GEPIdx; GEPIdx.push_back(ConstantInt::get(Type::Int32Ty, 0)); GEPIdx.push_back(ConstantInt::get(Type::Int32Ty, idx)); Value *NGEPI = new GetElementPtrInst(TheAlloca, GEPIdx.begin(), GEPIdx.end(), "mrv.gep", I); Value *NV = new LoadInst(NGEPI, "mrv.ld", I); RetVals.push_back(NV); } ReturnInst *NR = new ReturnInst(&RetVals[0], RetVals.size(), I); I->replaceAllUsesWith(NR); I->eraseFromParent(); } } // [3] Create the new function body and insert it into the module. Function *NF = cloneFunctionBody(F, STy); // [4] Update all call sites to use new function updateCallSites(F, NF); F->eraseFromParent(); getAnalysis<CallGraph>().changeFunction(F, NF); return true; } // Check if it is ok to perform this promotion. bool SRETPromotion::isSafeToUpdateAllCallers(Function *F) { if (F->use_empty()) // No users. OK to modify signature. return true; for (Value::use_iterator FnUseI = F->use_begin(), FnUseE = F->use_end(); FnUseI != FnUseE; ++FnUseI) { CallSite CS = CallSite::get(*FnUseI); Instruction *Call = CS.getInstruction(); CallSite::arg_iterator AI = CS.arg_begin(); Value *FirstArg = *AI; if (!isa<AllocaInst>(FirstArg)) return false; // Check FirstArg's users. for (Value::use_iterator ArgI = FirstArg->use_begin(), ArgE = FirstArg->use_end(); ArgI != ArgE; ++ArgI) { // If FirstArg user is a CallInst that does not correspond to current // call site then this function F is not suitable for sret promotion. if (CallInst *CI = dyn_cast<CallInst>(ArgI)) { if (CI != Call) return false; } // If FirstArg user is a GEP whose all users are not LoadInst then // this function F is not suitable for sret promotion. else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(ArgI)) { for (Value::use_iterator GEPI = GEP->use_begin(), GEPE = GEP->use_end(); GEPI != GEPE; ++GEPI) if (!isa<LoadInst>(GEPI)) return false; } // Any other FirstArg users make this function unsuitable for sret // promotion. else return false; } } return true; } /// cloneFunctionBody - Create a new function based on F and /// insert it into module. Remove first argument. Use STy as /// the return type for new function. Function *SRETPromotion::cloneFunctionBody(Function *F, const StructType *STy) { const FunctionType *FTy = F->getFunctionType(); std::vector<const Type*> Params; // ParamAttrs - Keep track of the parameter attributes for the arguments. ParamAttrsVector ParamAttrsVec; const ParamAttrsList *PAL = F->getParamAttrs(); // Add any return attributes. if (ParameterAttributes attrs = PAL ? PAL->getParamAttrs(0) : ParamAttr::None) ParamAttrsVec.push_back(ParamAttrsWithIndex::get(0, attrs)); // Skip first argument. Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); ++I; unsigned ParamIndex = 1; // 0th parameter attribute is reserved for return type. while (I != E) { Params.push_back(I->getType()); ParameterAttributes Attrs; if (PAL) { Attrs = PAL->getParamAttrs(ParamIndex); if (ParamIndex == 1) // Skip sret attribute Attrs = Attrs ^ ParamAttr::StructRet; } if (Attrs != ParamAttr::None) ParamAttrsVec.push_back(ParamAttrsWithIndex::get(ParamIndex, Attrs)); ++I; ++ParamIndex; } FunctionType *NFTy = FunctionType::get(STy, Params, FTy->isVarArg()); Function *NF = new Function(NFTy, F->getLinkage(), F->getName()); NF->setCallingConv(F->getCallingConv()); NF->setParamAttrs(ParamAttrsList::get(ParamAttrsVec)); F->getParent()->getFunctionList().insert(F, NF); NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList()); // Replace arguments I = F->arg_begin(); E = F->arg_end(); Function::arg_iterator NI = NF->arg_begin(); ++I; while (I != E) { I->replaceAllUsesWith(NI); NI->takeName(I); ++I; ++NI; } return NF; } /// updateCallSites - Update all sites that call F to use NF. void SRETPromotion::updateCallSites(Function *F, Function *NF) { SmallVector<Value*, 16> Args; // ParamAttrs - Keep track of the parameter attributes for the arguments. ParamAttrsVector ArgAttrsVec; for (Value::use_iterator FUI = F->use_begin(), FUE = F->use_end(); FUI != FUE;) { CallSite CS = CallSite::get(*FUI); ++FUI; Instruction *Call = CS.getInstruction(); const ParamAttrsList *PAL = F->getParamAttrs(); // Add any return attributes. if (ParameterAttributes attrs = PAL ? PAL->getParamAttrs(0) : ParamAttr::None) ArgAttrsVec.push_back(ParamAttrsWithIndex::get(0, attrs)); // Copy arguments, however skip first one. CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end(); Value *FirstCArg = *AI; ++AI; unsigned ParamIndex = 1; // 0th parameter attribute is reserved for return type. while (AI != AE) { Args.push_back(*AI); ParameterAttributes Attrs; if (PAL) { Attrs = PAL->getParamAttrs(ParamIndex); if (ParamIndex == 1) // Skip sret attribute Attrs = Attrs ^ ParamAttr::StructRet; } if (Attrs != ParamAttr::None) ArgAttrsVec.push_back(ParamAttrsWithIndex::get(Args.size(), Attrs)); ++ParamIndex; ++AI; } // Build new call instruction. Instruction *New; if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) { New = new InvokeInst(NF, II->getNormalDest(), II->getUnwindDest(), Args.begin(), Args.end(), "", Call); cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv()); cast<InvokeInst>(New)->setParamAttrs(ParamAttrsList::get(ArgAttrsVec)); } else { New = new CallInst(NF, Args.begin(), Args.end(), "", Call); cast<CallInst>(New)->setCallingConv(CS.getCallingConv()); cast<CallInst>(New)->setParamAttrs(ParamAttrsList::get(ArgAttrsVec)); if (cast<CallInst>(Call)->isTailCall()) cast<CallInst>(New)->setTailCall(); } Args.clear(); ArgAttrsVec.clear(); New->takeName(Call); // Update all users of sret parameter to extract value using getresult. for (Value::use_iterator UI = FirstCArg->use_begin(), UE = FirstCArg->use_end(); UI != UE; ) { User *U2 = *UI++; CallInst *C2 = dyn_cast<CallInst>(U2); if (C2 && (C2 == Call)) continue; else if (GetElementPtrInst *UGEP = dyn_cast<GetElementPtrInst>(U2)) { ConstantInt *Idx = dyn_cast<ConstantInt>(UGEP->getOperand(2)); assert (Idx && "Unexpected getelementptr index!"); Value *GR = new GetResultInst(New, Idx->getZExtValue(), "gr", UGEP); for (Value::use_iterator GI = UGEP->use_begin(), GE = UGEP->use_end(); GI != GE; ++GI) { if (LoadInst *L = dyn_cast<LoadInst>(*GI)) { L->replaceAllUsesWith(GR); L->eraseFromParent(); } } UGEP->eraseFromParent(); } else assert( 0 && "Unexpected sret parameter use"); } Call->eraseFromParent(); } } /// nestedStructType - Return true if STy includes any /// other aggregate types bool SRETPromotion::nestedStructType(const StructType *STy) { unsigned Num = STy->getNumElements(); for (unsigned i = 0; i < Num; i++) { const Type *Ty = STy->getElementType(i); if (!Ty->isFirstClassType() && Ty != Type::VoidTy) return true; } return false; } <|endoftext|>
<commit_before>{ // // This macro generates a Controlbar menu: To see the output, click begin_html <a href="gif/demos.gif" >here</a> end_html // To execute an item, click with the left mouse button. // To see the HELP of a button, click on the right mouse button. gROOT->Reset(); bar = new TControlBar("vertical", "Demos"); bar->AddButton("Help on Demos",".x demoshelp.C", "Click Here For Help on Running the Demos"); bar->AddButton("browser", "new TBrowser;", "Start the ROOT Browser"); bar->AddButton("framework", ".x framework.C", "An Example of Object Oriented User Interface"); bar->AddButton("first", ".x first.C", "An Example of Slide with Root"); bar->AddButton("hsimple", ".x hsimple.C", "An Example Creating Histograms/Ntuples on File"); bar->AddButton("hsum", ".x hsum.C", "Filling Histograms and Some Graphics Options"); bar->AddButton("formula1", ".x formula1.C", "Simple Formula and Functions"); bar->AddButton("surfaces", ".x surfaces.C", "Surface Drawing Options"); bar->AddButton("fillrandom", ".x fillrandom.C","Histograms with Random Numbers from a Function"); bar->AddButton("fit1", ".x fit1.C", "A Simple Fitting Example"); bar->AddButton("multifit", ".x multifit.C", "Fitting in Subranges of Histograms"); bar->AddButton("h1draw", ".x h1draw.C", "Drawing Options for 1D Histograms"); bar->AddButton("graph", ".x graph.C", "Example of a Simple Graph"); bar->AddButton("gerrors", ".x gerrors.C", "Example of a Graph with Error Bars"); bar->AddButton("tornado", ".x tornado.C", "Examples of 3-D PolyMarkers"); bar->AddButton("shapes", ".x shapes.C", "The Geometry Shapes"); bar->AddButton("geometry", ".x geometry.C", "Creation of the NA49 Geometry File"); bar->AddButton("na49view", ".x na49view.C", "Two Views of the NA49 Detector Geometry"); bar->AddButton("file", ".x file.C", "The ROOT File Format"); bar->AddButton("fildir", ".x fildir.C", "The ROOT File, Directories and Keys"); bar->AddButton("tree", ".x tree.C", "The Tree Data Structure"); bar->AddButton("ntuple1", ".x ntuple1.C", "Ntuples and Selections"); bar->AddButton("rootmarks", ".x rootmarks.C", "Prints an Estimated ROOTMARKS for Your Machine"); bar->Show(); gROOT->SaveContext(); } <commit_msg>Use the TControlBar constructor with placement. Show use of gStyle->SetScreenFactor.<commit_after>{ // // This macro generates a Controlbar menu: To see the output, click begin_html <a href="gif/demos.gif" >here</a> end_html // To execute an item, click with the left mouse button. // To see the HELP of a button, click on the right mouse button. gROOT->Reset(); gStyle->SetScreenFactor(1); //if you have a large screen, select 1,2 or 1.4 bar = new TControlBar("vertical", "Demos",10,10); bar->AddButton("Help on Demos",".x demoshelp.C", "Click Here For Help on Running the Demos"); bar->AddButton("browser", "new TBrowser;", "Start the ROOT Browser"); bar->AddButton("framework", ".x framework.C", "An Example of Object Oriented User Interface"); bar->AddButton("first", ".x first.C", "An Example of Slide with Root"); bar->AddButton("hsimple", ".x hsimple.C", "An Example Creating Histograms/Ntuples on File"); bar->AddButton("hsum", ".x hsum.C", "Filling Histograms and Some Graphics Options"); bar->AddButton("formula1", ".x formula1.C", "Simple Formula and Functions"); bar->AddButton("surfaces", ".x surfaces.C", "Surface Drawing Options"); bar->AddButton("fillrandom", ".x fillrandom.C","Histograms with Random Numbers from a Function"); bar->AddButton("fit1", ".x fit1.C", "A Simple Fitting Example"); bar->AddButton("multifit", ".x multifit.C", "Fitting in Subranges of Histograms"); bar->AddButton("h1draw", ".x h1draw.C", "Drawing Options for 1D Histograms"); bar->AddButton("graph", ".x graph.C", "Example of a Simple Graph"); bar->AddButton("gerrors", ".x gerrors.C", "Example of a Graph with Error Bars"); bar->AddButton("tornado", ".x tornado.C", "Examples of 3-D PolyMarkers"); bar->AddButton("shapes", ".x shapes.C", "The Geometry Shapes"); bar->AddButton("geometry", ".x geometry.C", "Creation of the NA49 Geometry File"); bar->AddButton("na49view", ".x na49view.C", "Two Views of the NA49 Detector Geometry"); bar->AddButton("file", ".x file.C", "The ROOT File Format"); bar->AddButton("fildir", ".x fildir.C", "The ROOT File, Directories and Keys"); bar->AddButton("tree", ".x tree.C", "The Tree Data Structure"); bar->AddButton("ntuple1", ".x ntuple1.C", "Ntuples and Selections"); bar->AddButton("rootmarks", ".x rootmarks.C", "Prints an Estimated ROOTMARKS for Your Machine"); bar->Show(); gROOT->SaveContext(); } <|endoftext|>
<commit_before>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2013 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation. // // 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include <string> #include <utility> #include <vector> #include <gtest/gtest.h> #include "jubatus/core/fv_converter/datum.hpp" #include "../common/jsonconfig.hpp" #include "../nearest_neighbor/nearest_neighbor_factory.hpp" #include "nearest_neighbor.hpp" #include "test_util.hpp" using std::vector; using std::pair; using std::make_pair; using std::string; using jubatus::util::lang::lexical_cast; using jubatus::util::lang::shared_ptr; using jubatus::util::text::json::json; using jubatus::util::text::json::json_object; using jubatus::util::text::json::json_integer; using jubatus::util::text::json::json_string; using jubatus::util::text::json::json_float; using jubatus::core::fv_converter::datum; namespace jubatus { namespace core { namespace driver { class nearest_neighbor_test : public ::testing::TestWithParam<shared_ptr<driver::nearest_neighbor> > { protected: void SetUp() { nearest_neighbor_ = GetParam(); } void TearDown() { } shared_ptr<core::driver::nearest_neighbor> nearest_neighbor_; }; datum single_num_datum(const string& key, double value) { core::fv_converter::datum d; d.num_values_.push_back(make_pair(key, value)); return d; } datum single_str_datum(const string& key, const string& value) { core::fv_converter::datum d; d.string_values_.push_back(make_pair(key, value)); return d; } TEST_P(nearest_neighbor_test, set_row) { nearest_neighbor_->set_row("a", single_str_datum("a", "hoge")); } TEST_P(nearest_neighbor_test, similar_row_from_id) { nearest_neighbor_->set_row("a", single_str_datum("x", "hoge")); nearest_neighbor_->set_row("b", single_str_datum("y", "fuga")); vector<pair<string, float> > result = nearest_neighbor_->similar_row("a", 100); ASSERT_EQ(2, result.size()); ASSERT_EQ("a", result[0].first); ASSERT_EQ("b", result[1].first); } TEST_P(nearest_neighbor_test, similar_row_from_data) { nearest_neighbor_->set_row("a", single_str_datum("x", "hoge")); nearest_neighbor_->set_row("b", single_str_datum("y", "fuga")); vector<pair<string, float> > result = nearest_neighbor_->similar_row(single_str_datum("x", "hoge"), 100); ASSERT_EQ(2, result.size()); ASSERT_EQ("a", result[0].first); ASSERT_EQ("b", result[1].first); } TEST_P(nearest_neighbor_test, neighbor_row_from_id) { nearest_neighbor_->set_row("a", single_str_datum("x", "hoge")); nearest_neighbor_->set_row("b", single_str_datum("y", "fuga")); vector<pair<string, float> > result = nearest_neighbor_->neighbor_row_from_id("a", 100); ASSERT_EQ(2, result.size()); ASSERT_EQ("a", result[0].first); ASSERT_EQ("b", result[1].first); } TEST_P(nearest_neighbor_test, neighbor_row2_from_data) { nearest_neighbor_->set_row("a", single_str_datum("x", "hoge")); nearest_neighbor_->set_row("b", single_str_datum("y", "fuga")); vector<pair<string, float> > result = nearest_neighbor_->neighbor_row_from_data( single_str_datum("x", "hoge"), 100); ASSERT_EQ(2, result.size()); ASSERT_EQ("a", result[0].first); ASSERT_EQ("b", result[1].first); } TEST_P(nearest_neighbor_test, neighbor_row_and_similar_row) { // neighbor_row and similar_row should return the same order result const size_t num = 200; for (size_t i = 0; i < num; ++i) { const string key = lexical_cast<string>(i); datum d = single_str_datum("x" + key, "a"); d.string_values_.push_back(make_pair("y", "b")); d.string_values_.push_back(make_pair("z" + key + key, "c")); nearest_neighbor_->set_row(key, d); } for (size_t i = 0; i < num; ++i) { const string key = lexical_cast<string>(i); datum d = single_str_datum("x" + key, "a"); vector<pair<string, float> > nr_result = nearest_neighbor_->neighbor_row_from_data(d, 100); vector<pair<string, float> > sr_result = nearest_neighbor_->similar_row(d, 100); ASSERT_EQ(nr_result.size(), sr_result.size()); for (size_t j = 0; j < nr_result.size(); ++j) { ASSERT_EQ(nr_result[j].first, sr_result[j].first); } } } TEST_P(nearest_neighbor_test, clear) { for (int i = 0; i < 100; ++i) { nearest_neighbor_->set_row("a" + lexical_cast<string>(i), single_num_datum("x", i)); } { vector<pair<string, float> > result = nearest_neighbor_->neighbor_row_from_data( single_num_datum("x", 1), 100); ASSERT_EQ("a1", result[0].first); } nearest_neighbor_->clear(); { for (int i = 0; i < 100; ++i) { vector<pair<string, float> > result = nearest_neighbor_->neighbor_row_from_data( single_num_datum("a" + lexical_cast<string>(i), i), 100); ASSERT_EQ(0u, result.size()); } } } TEST_P(nearest_neighbor_test, save_load) { { core::fv_converter::datum d; d.string_values_.push_back(make_pair("k1", "val")); nearest_neighbor_->set_row("1", d); } // save to a buffer msgpack::sbuffer sbuf; msgpack::packer<msgpack::sbuffer> packer(sbuf); nearest_neighbor_->get_mixable_holder()->pack(packer); // restart the driver TearDown(); SetUp(); // unpack the buffer msgpack::unpacked unpacked; msgpack::unpack(&unpacked, sbuf.data(), sbuf.size()); nearest_neighbor_->get_mixable_holder()->unpack(unpacked.get()); vector<pair<string, float> > res = nearest_neighbor_->similar_row("1", 1); ASSERT_EQ(1u, res.size()); EXPECT_EQ("1", res[0].first); } vector<shared_ptr<driver::nearest_neighbor> > create_nearest_neighbors() { vector<shared_ptr<driver::nearest_neighbor> > method; vector<pair<string, int> > pattern; for (size_t i = 8; i < 3000; i = i << 1) { // up to 2048 pattern.push_back(make_pair("lsh", i)); pattern.push_back(make_pair("euclid_lsh", i)); pattern.push_back(make_pair("minhash", i)); } for (size_t i = 0; i < pattern.size(); ++i) { shared_ptr<core::table::column_table> table(new core::table::column_table); json jsconf(new json_object); jsconf["hash_num"] = new json_integer(pattern[i].second); common::jsonconfig::config conf(jsconf); method.push_back( shared_ptr<driver::nearest_neighbor>( new driver::nearest_neighbor( core::nearest_neighbor::create_nearest_neighbor( pattern[i].first, conf, table, ""), make_fv_converter()))); } return method; } INSTANTIATE_TEST_CASE_P(nearest_neighbor_test_instance, nearest_neighbor_test, testing::ValuesIn(create_nearest_neighbors())); } // namespace driver } // namespace core } // namespace jubatus <commit_msg>Fix nearest_neighbor_test to compile<commit_after>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2013 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation. // // 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include <string> #include <utility> #include <vector> #include <gtest/gtest.h> #include "jubatus/core/fv_converter/datum.hpp" #include "../common/jsonconfig.hpp" #include "../nearest_neighbor/nearest_neighbor_factory.hpp" #include "nearest_neighbor.hpp" #include "test_util.hpp" using std::vector; using std::pair; using std::make_pair; using std::string; using jubatus::util::lang::lexical_cast; using jubatus::util::lang::shared_ptr; using jubatus::util::text::json::json; using jubatus::util::text::json::json_object; using jubatus::util::text::json::json_integer; using jubatus::util::text::json::json_string; using jubatus::util::text::json::json_float; using jubatus::core::fv_converter::datum; namespace jubatus { namespace core { namespace driver { class nearest_neighbor_test : public ::testing::TestWithParam<shared_ptr<driver::nearest_neighbor> > { protected: void SetUp() { nearest_neighbor_ = GetParam(); } void TearDown() { } shared_ptr<core::driver::nearest_neighbor> nearest_neighbor_; }; datum single_num_datum(const string& key, double value) { core::fv_converter::datum d; d.num_values_.push_back(make_pair(key, value)); return d; } datum single_str_datum(const string& key, const string& value) { core::fv_converter::datum d; d.string_values_.push_back(make_pair(key, value)); return d; } TEST_P(nearest_neighbor_test, set_row) { nearest_neighbor_->set_row("a", single_str_datum("a", "hoge")); } TEST_P(nearest_neighbor_test, similar_row_from_id) { nearest_neighbor_->set_row("a", single_str_datum("x", "hoge")); nearest_neighbor_->set_row("b", single_str_datum("y", "fuga")); vector<pair<string, float> > result = nearest_neighbor_->similar_row("a", 100); ASSERT_EQ(2, result.size()); ASSERT_EQ("a", result[0].first); ASSERT_EQ("b", result[1].first); } TEST_P(nearest_neighbor_test, similar_row_from_data) { nearest_neighbor_->set_row("a", single_str_datum("x", "hoge")); nearest_neighbor_->set_row("b", single_str_datum("y", "fuga")); vector<pair<string, float> > result = nearest_neighbor_->similar_row(single_str_datum("x", "hoge"), 100); ASSERT_EQ(2, result.size()); ASSERT_EQ("a", result[0].first); ASSERT_EQ("b", result[1].first); } TEST_P(nearest_neighbor_test, neighbor_row_from_id) { nearest_neighbor_->set_row("a", single_str_datum("x", "hoge")); nearest_neighbor_->set_row("b", single_str_datum("y", "fuga")); vector<pair<string, float> > result = nearest_neighbor_->neighbor_row_from_id("a", 100); ASSERT_EQ(2, result.size()); ASSERT_EQ("a", result[0].first); ASSERT_EQ("b", result[1].first); } TEST_P(nearest_neighbor_test, neighbor_row2_from_data) { nearest_neighbor_->set_row("a", single_str_datum("x", "hoge")); nearest_neighbor_->set_row("b", single_str_datum("y", "fuga")); vector<pair<string, float> > result = nearest_neighbor_->neighbor_row_from_data( single_str_datum("x", "hoge"), 100); ASSERT_EQ(2, result.size()); ASSERT_EQ("a", result[0].first); ASSERT_EQ("b", result[1].first); } TEST_P(nearest_neighbor_test, neighbor_row_and_similar_row) { // neighbor_row and similar_row should return the same order result const size_t num = 200; for (size_t i = 0; i < num; ++i) { const string key = lexical_cast<string>(i); datum d = single_str_datum("x" + key, "a"); d.string_values_.push_back(make_pair("y", "b")); d.string_values_.push_back(make_pair("z" + key + key, "c")); nearest_neighbor_->set_row(key, d); } for (size_t i = 0; i < num; ++i) { const string key = lexical_cast<string>(i); datum d = single_str_datum("x" + key, "a"); vector<pair<string, float> > nr_result = nearest_neighbor_->neighbor_row_from_data(d, 100); vector<pair<string, float> > sr_result = nearest_neighbor_->similar_row(d, 100); ASSERT_EQ(nr_result.size(), sr_result.size()); for (size_t j = 0; j < nr_result.size(); ++j) { ASSERT_EQ(nr_result[j].first, sr_result[j].first); } } } TEST_P(nearest_neighbor_test, clear) { for (int i = 0; i < 100; ++i) { nearest_neighbor_->set_row("a" + lexical_cast<string>(i), single_num_datum("x", i)); } { vector<pair<string, float> > result = nearest_neighbor_->neighbor_row_from_data( single_num_datum("x", 1), 100); ASSERT_EQ("a1", result[0].first); } nearest_neighbor_->clear(); { for (int i = 0; i < 100; ++i) { vector<pair<string, float> > result = nearest_neighbor_->neighbor_row_from_data( single_num_datum("a" + lexical_cast<string>(i), i), 100); ASSERT_EQ(0u, result.size()); } } } TEST_P(nearest_neighbor_test, save_load) { { core::fv_converter::datum d; d.string_values_.push_back(make_pair("k1", "val")); nearest_neighbor_->set_row("1", d); } // save to a buffer msgpack::sbuffer sbuf; msgpack::packer<msgpack::sbuffer> packer(sbuf); nearest_neighbor_->pack(packer); // restart the driver TearDown(); SetUp(); // unpack the buffer msgpack::unpacked unpacked; msgpack::unpack(&unpacked, sbuf.data(), sbuf.size()); nearest_neighbor_->unpack(unpacked.get()); vector<pair<string, float> > res = nearest_neighbor_->similar_row("1", 1); ASSERT_EQ(1u, res.size()); EXPECT_EQ("1", res[0].first); } vector<shared_ptr<driver::nearest_neighbor> > create_nearest_neighbors() { vector<shared_ptr<driver::nearest_neighbor> > method; vector<pair<string, int> > pattern; for (size_t i = 8; i < 3000; i = i << 1) { // up to 2048 pattern.push_back(make_pair("lsh", i)); pattern.push_back(make_pair("euclid_lsh", i)); pattern.push_back(make_pair("minhash", i)); } for (size_t i = 0; i < pattern.size(); ++i) { shared_ptr<core::table::column_table> table(new core::table::column_table); json jsconf(new json_object); jsconf["hash_num"] = new json_integer(pattern[i].second); common::jsonconfig::config conf(jsconf); method.push_back( shared_ptr<driver::nearest_neighbor>( new driver::nearest_neighbor( core::nearest_neighbor::create_nearest_neighbor( pattern[i].first, conf, table, ""), make_fv_converter()))); } return method; } INSTANTIATE_TEST_CASE_P(nearest_neighbor_test_instance, nearest_neighbor_test, testing::ValuesIn(create_nearest_neighbors())); } // namespace driver } // namespace core } // namespace jubatus <|endoftext|>
<commit_before>// // Copyright (c) 2013 The ANGLE Project 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 "gmock/gmock.h" #include "gtest/gtest.h" #include "GLSLANG/ShaderLang.h" int main(int argc, char** argv) { testing::InitGoogleMock(&argc, argv); ShInitialize(); int rt = RUN_ALL_TESTS(); ShFinalize(); return rt; } <commit_msg>Moved the compiler test initialization and tear down into a gtest environement class.<commit_after>// // Copyright (c) 2013 The ANGLE Project 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 "gmock/gmock.h" #include "gtest/gtest.h" #include "GLSLANG/ShaderLang.h" class CompilerTestEnvironment : public testing::Environment { public: virtual void SetUp() { if (!ShInitialize()) { FAIL() << "Failed to initialize the compiler."; } } virtual void TearDown() { if (!ShFinalize()) { FAIL() << "Failed to finalize the compiler."; } } }; int main(int argc, char** argv) { testing::InitGoogleMock(&argc, argv); testing::AddGlobalTestEnvironment(new CompilerTestEnvironment()); int rt = RUN_ALL_TESTS(); return rt; } <|endoftext|>
<commit_before>/* OpenSceneGraph example, osgcamera. * * 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 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 <osgDB/ReadFile> #include <osgDB/WriteFile> #include <osgViewer/Viewer> #include <osgViewer/ViewerEventHandlers> #include <osgGA/TrackballManipulator> #include <osgGA/FlightManipulator> #include <osgGA/AnimationPathManipulator> #include <osgGA/GUIEventHandler> #include <osgGA/StateSetManipulator> #include <osg/PolygonMode> #include <osgUtil/Optimizer> #include <osg/Depth> #include <iostream> #include <osg/Switch> #include <osgSim/MultiSwitch> #include <osgSim/DOFTransform> #include <osg/AlphaFunc> #include <osg/BlendFunc> using namespace osg; using namespace osgGA; class SwitchDOFVisitor : public osg::NodeVisitor, public osgGA::GUIEventHandler { public: SwitchDOFVisitor(): osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN) { } SwitchDOFVisitor(const SwitchDOFVisitor& sdfv, const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY): osg::Object(sdfv, copyop), osg::Callback(sdfv, copyop), osg::NodeVisitor(sdfv, copyop), osgGA::GUIEventHandler(sdfv, copyop) {} META_Object(osg, SwitchDOFVisitor) virtual void apply(Group& node) { osgSim::MultiSwitch* pMSwitch = dynamic_cast<osgSim::MultiSwitch*>(&node); if (pMSwitch) { mSwitches.push_back(pMSwitch); } osg::NodeVisitor::apply(node); } virtual void apply(Transform& node) { osgSim::DOFTransform* pDof = dynamic_cast<osgSim::DOFTransform*>(&node); if (pDof) { mDofs.push_back(pDof); pDof->setAnimationOn(true); } osg::NodeVisitor::apply(node); } void nextSwitch() { for (size_t i=0; i < mSwitches.size(); i++) { if (mSwitches[i]->getSwitchSetList().size() > 1) { // Toggle through switchsets unsigned int nextSwitchSet = mSwitches[i]->getActiveSwitchSet(); nextSwitchSet++; if (nextSwitchSet >= mSwitches[i]->getSwitchSetList().size()) nextSwitchSet = 0; mSwitches[i]->setActiveSwitchSet(nextSwitchSet); } else if (mSwitches[i]->getSwitchSetList().size() == 1) { // If we have only one switchset, toggle values within this switchset osgSim::MultiSwitch::ValueList values = mSwitches[i]->getValueList(0); for (size_t j=0; j < values.size(); j++) { if (values[j]) { unsigned int nextValue = j+1; if (nextValue >= values.size()) nextValue = 0; mSwitches[i]->setSingleChildOn(0, nextValue); } } } } } void multiplyAnimation(float scale) { for (size_t i=0; i < mDofs.size(); i++) { mDofs[i]->setIncrementHPR(mDofs[i]->getIncrementHPR() * scale); mDofs[i]->setIncrementScale(mDofs[i]->getIncrementScale() * scale); mDofs[i]->setIncrementTranslate(mDofs[i]->getIncrementTranslate() * scale); } } bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) { osgViewer::Viewer* viewer = dynamic_cast<osgViewer::Viewer*>(&aa); if (!viewer) return false; if (ea.getHandled()) return false; if(ea.getEventType()==GUIEventAdapter::KEYDOWN) { switch( ea.getKey() ) { case osgGA::GUIEventAdapter::KEY_Right: // Toggle next switch nextSwitch(); return true; break; case osgGA::GUIEventAdapter::KEY_Up: // Increase animation speed multiplyAnimation(2); return true; break; case osgGA::GUIEventAdapter::KEY_Down: // Decrease animation speed multiplyAnimation(0.5); return true; break; } } return false; } private: std::vector<osgSim::MultiSwitch*> mSwitches; std::vector<osgSim::DOFTransform*> mDofs; }; void singleWindowSideBySideCameras(osgViewer::Viewer& viewer) { osg::GraphicsContext::WindowingSystemInterface* wsi = osg::GraphicsContext::getWindowingSystemInterface(); if (!wsi) { osg::notify(osg::NOTICE)<<"Error, no WindowSystemInterface available, cannot create windows."<<std::endl; return; } unsigned int width, height; wsi->getScreenResolution(osg::GraphicsContext::ScreenIdentifier(0), width, height); // Not fullscreen width /= 2; height /= 2; osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits; traits->x = 100; traits->y = 100; 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; } osg::Camera* master = viewer.getCamera(); // get the default settings for the camera double fovy, aspectRatio, zNear, zFar; master->getProjectionMatrixAsPerspective(fovy, aspectRatio, zNear, zFar); // reset this for the actual apsect ratio of out created window double windowAspectRatio = double(width)/double(height); master->setProjectionMatrixAsPerspective(fovy, windowAspectRatio, 1.0, 10000.0); master->setName("MasterCam"); osg::ref_ptr<osg::Camera> camera = new osg::Camera; camera->setCullMask(1); camera->setName("Left"); camera->setGraphicsContext(gc.get()); camera->setViewport(new osg::Viewport(0, 0, width/2, height)); GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT; camera->setDrawBuffer(buffer); camera->setReadBuffer(buffer); viewer.addSlave(camera.get(), osg::Matrixd::scale(1.0,0.5,1.0), osg::Matrixd()); camera = new osg::Camera; camera->setCullMask(2); camera->setName("Right"); camera->setGraphicsContext(gc.get()); camera->setViewport(new osg::Viewport(width/2, 0, width/2, height)); buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT; camera->setDrawBuffer(buffer); camera->setReadBuffer(buffer); viewer.addSlave(camera.get(), osg::Matrixd::scale(1.0,0.5,1.0), osg::Matrixd()); } int main( int argc, char **argv ) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); if (argc<2) { std::cout << argv[0] <<": requires filename argument." << std::endl; return 1; } osgViewer::Viewer viewer(arguments); std::string outputfile("output.osgt"); while (arguments.read("-o",outputfile)) {} while (arguments.read("-s")) { viewer.setThreadingModel(osgViewer::Viewer::SingleThreaded); } while (arguments.read("-g")) { viewer.setThreadingModel(osgViewer::Viewer::CullDrawThreadPerContext); } while (arguments.read("-d")) { viewer.setThreadingModel(osgViewer::Viewer::DrawThreadPerContext); } while (arguments.read("-c")) { viewer.setThreadingModel(osgViewer::Viewer::CullThreadPerCameraDrawThreadPerContext); } singleWindowSideBySideCameras(viewer); viewer.setCameraManipulator( new osgGA::TrackballManipulator() ); viewer.addEventHandler(new osgViewer::StatsHandler); viewer.addEventHandler(new osgViewer::ThreadingHandler); viewer.addEventHandler(new osgViewer::WindowSizeHandler()); viewer.addEventHandler(new osgViewer::LODScaleHandler()); viewer.addEventHandler(new osgGA::StateSetManipulator()); SwitchDOFVisitor* visit = new SwitchDOFVisitor; viewer.addEventHandler(visit); // load the scene. osg::ref_ptr<osg::Node> loadedModel = osgDB::readRefNodeFiles(arguments); if (!loadedModel) { std::cout << argv[0] <<": No data loaded." << std::endl; return 1; } osg::Group* group = new osg::Group; osg::Group* group1 = new osg::Group; group1->addChild(loadedModel); group1->setNodeMask(1); // Uncomment these lines if you like to compare the loaded model to the resulting model in a merge/diff tool //osgDB::writeNodeFile(*loadedModel.get(), "dummy1.osgt"); osgDB::writeNodeFile(*loadedModel, outputfile); osg::ref_ptr<osg::Node> convertedModel = osgDB::readRefNodeFile(outputfile); osg::Group* group2 = new osg::Group; group2->addChild(convertedModel.get()); group2->setNodeMask(2); // Activate DOF animations and collect switches loadedModel->accept(*visit); convertedModel->accept(*visit); group->addChild(group1); group->addChild(group2); viewer.setSceneData(group); viewer.setThreadingModel(osgViewer::Viewer::DrawThreadPerContext); viewer.realize(); viewer.run(); return 0; } <commit_msg>Refactored the event handler so that it contains a helper NodeVistor class rather than inherits from inappropriately using multiple inheritance.<commit_after>/* OpenSceneGraph example, osgcamera. * * 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 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 <osgDB/ReadFile> #include <osgDB/WriteFile> #include <osgViewer/Viewer> #include <osgViewer/ViewerEventHandlers> #include <osgGA/TrackballManipulator> #include <osgGA/FlightManipulator> #include <osgGA/AnimationPathManipulator> #include <osgGA/GUIEventHandler> #include <osgGA/StateSetManipulator> #include <osg/PolygonMode> #include <osgUtil/Optimizer> #include <osg/Depth> #include <iostream> #include <osg/Switch> #include <osgSim/MultiSwitch> #include <osgSim/DOFTransform> #include <osg/AlphaFunc> #include <osg/BlendFunc> using namespace osg; using namespace osgGA; class SwitchDOFHandler : public osgGA::GUIEventHandler { public: SwitchDOFHandler() { } void nextSwitch() { for (size_t i=0; i < mSwitches.size(); i++) { if (mSwitches[i]->getSwitchSetList().size() > 1) { // Toggle through switchsets unsigned int nextSwitchSet = mSwitches[i]->getActiveSwitchSet(); nextSwitchSet++; if (nextSwitchSet >= mSwitches[i]->getSwitchSetList().size()) nextSwitchSet = 0; mSwitches[i]->setActiveSwitchSet(nextSwitchSet); } else if (mSwitches[i]->getSwitchSetList().size() == 1) { // If we have only one switchset, toggle values within this switchset osgSim::MultiSwitch::ValueList values = mSwitches[i]->getValueList(0); for (size_t j=0; j < values.size(); j++) { if (values[j]) { unsigned int nextValue = j+1; if (nextValue >= values.size()) nextValue = 0; mSwitches[i]->setSingleChildOn(0, nextValue); } } } } } void multiplyAnimation(float scale) { for (size_t i=0; i < mDofs.size(); i++) { mDofs[i]->setIncrementHPR(mDofs[i]->getIncrementHPR() * scale); mDofs[i]->setIncrementScale(mDofs[i]->getIncrementScale() * scale); mDofs[i]->setIncrementTranslate(mDofs[i]->getIncrementTranslate() * scale); } } bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) { osgViewer::Viewer* viewer = dynamic_cast<osgViewer::Viewer*>(&aa); if (!viewer) return false; if (ea.getHandled()) return false; if(ea.getEventType()==GUIEventAdapter::KEYDOWN) { switch( ea.getKey() ) { case osgGA::GUIEventAdapter::KEY_Right: // Toggle next switch nextSwitch(); return true; break; case osgGA::GUIEventAdapter::KEY_Up: // Increase animation speed multiplyAnimation(2); return true; break; case osgGA::GUIEventAdapter::KEY_Down: // Decrease animation speed multiplyAnimation(0.5); return true; break; } } return false; } void collectNodesOfInterest(osg::Node* node) { CollectNodes cn(this); node->accept(cn); } private: friend class CollectNodes; class CollectNodes : public osg::NodeVisitor { public: SwitchDOFHandler* _parent; CollectNodes(SwitchDOFHandler* parent): osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN), _parent(parent) { } virtual void apply(Group& node) { osgSim::MultiSwitch* pMSwitch = dynamic_cast<osgSim::MultiSwitch*>(&node); if (pMSwitch) { _parent->mSwitches.push_back(pMSwitch); } traverse(node); } virtual void apply(Transform& node) { osgSim::DOFTransform* pDof = dynamic_cast<osgSim::DOFTransform*>(&node); if (pDof) { _parent->mDofs.push_back(pDof); pDof->setAnimationOn(true); } traverse(node); } }; std::vector< osg::ref_ptr<osgSim::MultiSwitch> > mSwitches; std::vector< osg::ref_ptr<osgSim::DOFTransform> > mDofs; }; void singleWindowSideBySideCameras(osgViewer::Viewer& viewer) { osg::GraphicsContext::WindowingSystemInterface* wsi = osg::GraphicsContext::getWindowingSystemInterface(); if (!wsi) { osg::notify(osg::NOTICE)<<"Error, no WindowSystemInterface available, cannot create windows."<<std::endl; return; } unsigned int width, height; wsi->getScreenResolution(osg::GraphicsContext::ScreenIdentifier(0), width, height); // Not fullscreen width /= 2; height /= 2; osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits; traits->x = 100; traits->y = 100; 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; } osg::Camera* master = viewer.getCamera(); // get the default settings for the camera double fovy, aspectRatio, zNear, zFar; master->getProjectionMatrixAsPerspective(fovy, aspectRatio, zNear, zFar); // reset this for the actual apsect ratio of out created window double windowAspectRatio = double(width)/double(height); master->setProjectionMatrixAsPerspective(fovy, windowAspectRatio, 1.0, 10000.0); master->setName("MasterCam"); osg::ref_ptr<osg::Camera> camera = new osg::Camera; camera->setCullMask(1); camera->setName("Left"); camera->setGraphicsContext(gc.get()); camera->setViewport(new osg::Viewport(0, 0, width/2, height)); GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT; camera->setDrawBuffer(buffer); camera->setReadBuffer(buffer); viewer.addSlave(camera.get(), osg::Matrixd::scale(1.0,0.5,1.0), osg::Matrixd()); camera = new osg::Camera; camera->setCullMask(2); camera->setName("Right"); camera->setGraphicsContext(gc.get()); camera->setViewport(new osg::Viewport(width/2, 0, width/2, height)); buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT; camera->setDrawBuffer(buffer); camera->setReadBuffer(buffer); viewer.addSlave(camera.get(), osg::Matrixd::scale(1.0,0.5,1.0), osg::Matrixd()); } int main( int argc, char **argv ) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); if (argc<2) { std::cout << argv[0] <<": requires filename argument." << std::endl; return 1; } osgViewer::Viewer viewer(arguments); std::string outputfile("output.osgt"); while (arguments.read("-o",outputfile)) {} while (arguments.read("-s")) { viewer.setThreadingModel(osgViewer::Viewer::SingleThreaded); } while (arguments.read("-g")) { viewer.setThreadingModel(osgViewer::Viewer::CullDrawThreadPerContext); } while (arguments.read("-d")) { viewer.setThreadingModel(osgViewer::Viewer::DrawThreadPerContext); } while (arguments.read("-c")) { viewer.setThreadingModel(osgViewer::Viewer::CullThreadPerCameraDrawThreadPerContext); } singleWindowSideBySideCameras(viewer); viewer.setCameraManipulator( new osgGA::TrackballManipulator() ); viewer.addEventHandler(new osgViewer::StatsHandler); viewer.addEventHandler(new osgViewer::ThreadingHandler); viewer.addEventHandler(new osgViewer::WindowSizeHandler()); viewer.addEventHandler(new osgViewer::LODScaleHandler()); viewer.addEventHandler(new osgGA::StateSetManipulator()); SwitchDOFHandler* switchOFHandler = new SwitchDOFHandler; viewer.addEventHandler(switchOFHandler); // load the scene. osg::ref_ptr<osg::Node> loadedModel = osgDB::readRefNodeFiles(arguments); if (!loadedModel) { std::cout << argv[0] <<": No data loaded." << std::endl; return 1; } osg::Group* group = new osg::Group; osg::Group* group1 = new osg::Group; group1->addChild(loadedModel); group1->setNodeMask(1); // Uncomment these lines if you like to compare the loaded model to the resulting model in a merge/diff tool //osgDB::writeNodeFile(*loadedModel.get(), "dummy1.osgt"); osgDB::writeNodeFile(*loadedModel, outputfile); osg::ref_ptr<osg::Node> convertedModel = osgDB::readRefNodeFile(outputfile); osg::Group* group2 = new osg::Group; group2->addChild(convertedModel.get()); group2->setNodeMask(2); group->addChild(group1); group->addChild(group2); // Activate DOF animations and collect switches switchOFHandler->collectNodesOfInterest(group); viewer.setSceneData(group); viewer.setThreadingModel(osgViewer::Viewer::DrawThreadPerContext); viewer.realize(); viewer.run(); return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) 2011, Peter Thorson. 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 WebSocket++ Project 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 PETER THORSON 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 "../../src/endpoint.hpp" #include "../../src/roles/client.hpp" #include "../../src/md5/md5.hpp" #include <boost/thread.hpp> #include <iostream> // PLATFORM SPECIFIC STUFF #include <unistd.h> #include <sys/resource.h> #include <time.h> int msleep(unsigned long milisec) { struct timespec req={0}; time_t sec=(int)(milisec/1000); milisec=milisec-(sec*1000); req.tv_sec=sec; req.tv_nsec=milisec*1000000L; while(nanosleep(&req,&req)==-1) continue; return 1; } // END PLATFORM SPECIFIC STUFF typedef websocketpp::endpoint<websocketpp::role::client,websocketpp::socket::plain> plain_endpoint_type; typedef plain_endpoint_type::handler_ptr plain_handler_ptr; typedef plain_endpoint_type::connection_ptr connection_ptr; class stress_client_handler : public plain_endpoint_type::handler { public: typedef stress_client_handler type; typedef plain_endpoint_type::connection_ptr connection_ptr; stress_client_handler(int num_connections) : m_connections_max(num_connections), m_connections_cur(0) { } void on_open(connection_ptr connection) { if (!m_timer) { m_timer.reset(new boost::asio::deadline_timer(connection->get_io_service(),boost::posix_time::seconds(0))); m_timer->expires_from_now(boost::posix_time::milliseconds(250)); m_timer->async_wait(boost::bind(&type::on_timer,this,connection,boost::asio::placeholders::error)); } m_connections_cur++; if (m_connections_cur == m_connections_max) { boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time(); boost::posix_time::time_period period(m_start_time,now); int ms = period.length().total_milliseconds(); std::cout << "Started " << m_connections_cur << " in " << ms << "ms" << " (" << m_connections_cur/(ms/1000.0) << "/s)" << std::endl; } } void on_message(connection_ptr connection, websocketpp::message::data_ptr msg) { m_msg_stats[websocketpp::md5_hash_hex(msg->get_payload())]++; if (m_msg_stats[websocketpp::md5_hash_hex(msg->get_payload())] == m_connections_max) { send_stats_update(connection); } connection->recycle(msg); } void on_fail(connection_ptr connection) { std::cout << "connection failed" << std::endl; } void on_timer(connection_ptr connection,const boost::system::error_code& error) { if (error) { std::cout << "on_timer error" << std::endl; return; } send_stats_update(connection); m_timer->expires_from_now(boost::posix_time::milliseconds(250)); m_timer->async_wait(boost::bind(&type::on_timer,this,connection,boost::asio::placeholders::error)); } void on_close(connection_ptr connection) { m_timer->cancel(); } boost::posix_time::ptime m_start_time; private: void send_stats_update(connection_ptr connection) { if (m_msg_stats.empty()) { return; } std::stringstream msg; msg << "{\"type\":\"acks\",\"messages\":["; std::map<std::string,size_t>::iterator it; std::map<std::string,size_t>::iterator last = m_msg_stats.end(); if (m_msg_stats.size() > 0) { last--; } for (it = m_msg_stats.begin(); it != m_msg_stats.end(); it++) { msg << "{\"" << (*it).first << "\":" << (*it).second << "}" << (it != last ? "," : ""); } msg << "]}"; connection->send(msg.str(),false); m_msg_stats.clear(); } int m_connections_max; int m_connections_cur; std::map<std::string,size_t> m_msg_stats; boost::shared_ptr<boost::asio::deadline_timer> m_timer; }; int main(int argc, char* argv[]) { std::string uri = "ws://localhost:9002/"; int num_connections = 1; int batch_size = 1; int delay_ms = 500; if (argc != 5) { std::cout << "Usage: `echo_client test_url num_connections batch_size delay_ms`" << std::endl; } else { uri = argv[1]; num_connections = atoi(argv[2]); batch_size = atoi(argv[3]); delay_ms = atoi(argv[4]); } // 12288 is max OS X limit without changing kernal settings const rlim_t ideal_size = 200+num_connections; rlim_t old_size; rlim_t old_max; struct rlimit rl; int result; result = getrlimit(RLIMIT_NOFILE, &rl); if (result == 0) { //std::cout << "System FD limits: " << rl.rlim_cur << " max: " << rl.rlim_max << std::endl; old_size = rl.rlim_cur; old_max = rl.rlim_max; if (rl.rlim_cur < ideal_size) { std::cout << "Attempting to raise system file descriptor limit from " << rl.rlim_cur << " to " << ideal_size << std::endl; rl.rlim_cur = ideal_size; if (rl.rlim_max < ideal_size) { rl.rlim_max = ideal_size; } result = setrlimit(RLIMIT_NOFILE, &rl); if (result == 0) { std::cout << "Success" << std::endl; } else if (result == EPERM) { std::cout << "Failed. This server will be limited to " << old_size << " concurrent connections. Error code: Insufficient permissions. Try running process as root. system max: " << old_max << std::endl; } else { std::cout << "Failed. This server will be limited to " << old_size << " concurrent connections. Error code: " << errno << " system max: " << old_max << std::endl; } } } try { plain_handler_ptr handler(new stress_client_handler(num_connections)); plain_endpoint_type endpoint(handler); endpoint.alog().unset_level(websocketpp::log::alevel::ALL); endpoint.elog().set_level(websocketpp::log::elevel::ALL); std::set<connection_ptr> connections; connections.insert(endpoint.connect(uri)); boost::thread t(boost::bind(&plain_endpoint_type::run, &endpoint)); std::cout << "launching " << num_connections << " connections to " << uri << " in batches of " << batch_size << std::endl; boost::dynamic_pointer_cast<stress_client_handler>(handler)->m_start_time = boost::posix_time::microsec_clock::local_time(); for (int i = 0; i < num_connections-1; i++) { if (i % batch_size == 0) { //sleep(1); msleep(delay_ms); } connections.insert(endpoint.connect(uri)); } std::cout << "complete" << std::endl; t.join(); std::cout << "done" << std::endl; } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << std::endl; } return 0; } <commit_msg>updates stress client to use wscmd instead on json<commit_after>/* * Copyright (c) 2011, Peter Thorson. 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 WebSocket++ Project 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 PETER THORSON 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 "../../src/endpoint.hpp" #include "../../src/roles/client.hpp" #include "../../src/md5/md5.hpp" #include <boost/thread.hpp> #include <iostream> // PLATFORM SPECIFIC STUFF #include <unistd.h> #include <sys/resource.h> #include <time.h> int msleep(unsigned long milisec) { struct timespec req={0}; time_t sec=(int)(milisec/1000); milisec=milisec-(sec*1000); req.tv_sec=sec; req.tv_nsec=milisec*1000000L; while(nanosleep(&req,&req)==-1) continue; return 1; } // END PLATFORM SPECIFIC STUFF typedef websocketpp::endpoint<websocketpp::role::client,websocketpp::socket::plain> plain_endpoint_type; typedef plain_endpoint_type::handler_ptr plain_handler_ptr; typedef plain_endpoint_type::connection_ptr connection_ptr; class stress_client_handler : public plain_endpoint_type::handler { public: typedef stress_client_handler type; typedef plain_endpoint_type::connection_ptr connection_ptr; stress_client_handler(int num_connections) : m_connections_max(num_connections), m_connections_cur(0) { } void on_open(connection_ptr connection) { if (!m_timer) { m_timer.reset(new boost::asio::deadline_timer(connection->get_io_service(),boost::posix_time::seconds(0))); m_timer->expires_from_now(boost::posix_time::milliseconds(250)); m_timer->async_wait(boost::bind(&type::on_timer,this,connection,boost::asio::placeholders::error)); } m_connections_cur++; if (m_connections_cur == m_connections_max) { boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time(); boost::posix_time::time_period period(m_start_time,now); int ms = period.length().total_milliseconds(); std::cout << "Started " << m_connections_cur << " in " << ms << "ms" << " (" << m_connections_cur/(ms/1000.0) << "/s)" << std::endl; } } void on_message(connection_ptr connection, websocketpp::message::data_ptr msg) { m_msg_stats[websocketpp::md5_hash_hex(msg->get_payload())]++; if (m_msg_stats[websocketpp::md5_hash_hex(msg->get_payload())] == m_connections_max) { send_stats_update(connection); } connection->recycle(msg); } void on_fail(connection_ptr connection) { std::cout << "connection failed" << std::endl; } void on_timer(connection_ptr connection,const boost::system::error_code& error) { if (error) { std::cout << "on_timer error" << std::endl; return; } send_stats_update(connection); m_timer->expires_from_now(boost::posix_time::milliseconds(250)); m_timer->async_wait(boost::bind(&type::on_timer,this,connection,boost::asio::placeholders::error)); } void on_close(connection_ptr connection) { m_timer->cancel(); } boost::posix_time::ptime m_start_time; private: void send_stats_update(connection_ptr connection) { if (m_msg_stats.empty()) { return; } // example: `ack:e3458d0aceff8b70a3e5c0afec632881=38;e3458d0aceff8b70a3e5c0afec632881=42;` std::stringstream msg; msg << "ack:"; std::map<std::string,size_t>::iterator it; for (it = m_msg_stats.begin(); it != m_msg_stats.end(); it++) { msg << (*it).first << "=" << (*it).second << ";"; } connection->send(msg.str(),false); m_msg_stats.clear(); } int m_connections_max; int m_connections_cur; std::map<std::string,size_t> m_msg_stats; boost::shared_ptr<boost::asio::deadline_timer> m_timer; }; int main(int argc, char* argv[]) { std::string uri = "ws://localhost:9002/"; int num_connections = 1; int batch_size = 1; int delay_ms = 500; if (argc != 5) { std::cout << "Usage: `echo_client test_url num_connections batch_size delay_ms`" << std::endl; } else { uri = argv[1]; num_connections = atoi(argv[2]); batch_size = atoi(argv[3]); delay_ms = atoi(argv[4]); } // 12288 is max OS X limit without changing kernal settings const rlim_t ideal_size = 200+num_connections; rlim_t old_size; rlim_t old_max; struct rlimit rl; int result; result = getrlimit(RLIMIT_NOFILE, &rl); if (result == 0) { //std::cout << "System FD limits: " << rl.rlim_cur << " max: " << rl.rlim_max << std::endl; old_size = rl.rlim_cur; old_max = rl.rlim_max; if (rl.rlim_cur < ideal_size) { std::cout << "Attempting to raise system file descriptor limit from " << rl.rlim_cur << " to " << ideal_size << std::endl; rl.rlim_cur = ideal_size; if (rl.rlim_max < ideal_size) { rl.rlim_max = ideal_size; } result = setrlimit(RLIMIT_NOFILE, &rl); if (result == 0) { std::cout << "Success" << std::endl; } else if (result == EPERM) { std::cout << "Failed. This server will be limited to " << old_size << " concurrent connections. Error code: Insufficient permissions. Try running process as root. system max: " << old_max << std::endl; } else { std::cout << "Failed. This server will be limited to " << old_size << " concurrent connections. Error code: " << errno << " system max: " << old_max << std::endl; } } } try { plain_handler_ptr handler(new stress_client_handler(num_connections)); plain_endpoint_type endpoint(handler); endpoint.alog().unset_level(websocketpp::log::alevel::ALL); endpoint.elog().set_level(websocketpp::log::elevel::ALL); std::set<connection_ptr> connections; connections.insert(endpoint.connect(uri)); boost::thread t(boost::bind(&plain_endpoint_type::run, &endpoint)); std::cout << "launching " << num_connections << " connections to " << uri << " in batches of " << batch_size << std::endl; boost::dynamic_pointer_cast<stress_client_handler>(handler)->m_start_time = boost::posix_time::microsec_clock::local_time(); for (int i = 0; i < num_connections-1; i++) { if (i % batch_size == 0) { //sleep(1); msleep(delay_ms); } connections.insert(endpoint.connect(uri)); } std::cout << "complete" << std::endl; t.join(); std::cout << "done" << std::endl; } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << std::endl; } return 0; } <|endoftext|>
<commit_before>/****************************************************************************** * This file is part of the Mula project * Copyright (c) 2011 Laszlo Papp <lpapp@kde.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "offsetcachefile.h" #include "file.h" #include "wordentry.h" #include <QtCore/QVector> #include <QtCore/QFile> #include <QtCore/QtGlobal> #include <QtCore/QDir> #include <QtCore/QDateTime> #include <QtCore/QDebug> #include <QtCore/QPair> #include <QtGui/QDesktopServices> #include <arpa/inet.h> using namespace MulaPluginStarDict; class OffsetCacheFile::Private { public: Private() : wordCount(0) , entryIndex(-1) , cacheMagicString("StarDict's Cache, Version: 0.1") , mappedData(0) { } ~Private() { } void fill(QByteArray data, int entryCount, long index); static const int pageEntryNumber = 32; QVector<quint32> wordOffset; QFile indexFile; ulong wordCount; QByteArray wordEntryBuffer; // 256 + sizeof(quint32)*2) - The length of "word_str" should be less than 256. See src/tools/DICTFILE_FORMAT. // index/date based key and value pair QPair<int, QByteArray> first; QPair<int, QByteArray> last; QPair<int, QByteArray> middle; QPair<int, QByteArray> realLast; QByteArray pageData; long entryIndex; QList<WordEntry> entries; QByteArray cacheMagicString; QFile mapFile; uchar *mappedData; }; void OffsetCacheFile::Private::fill(QByteArray data, int entryCount, long index) { entryIndex = index; ulong position = 0; for (int i = 0; i < entryCount; ++i) { entries[i].setData(data.mid(position)); position = qstrlen(data.mid(position)) + 1; entries[i].setDataOffset(ntohl(*reinterpret_cast<quint32 *>(data.mid(position).data()))); position += sizeof(quint32); entries[i].setDataSize(ntohl(*reinterpret_cast<quint32 *>(data.mid(position).data()))); position += sizeof(quint32); } } OffsetCacheFile::OffsetCacheFile() : d(new Private) { } OffsetCacheFile::~OffsetCacheFile() { } QByteArray OffsetCacheFile::readFirstOnPageKey(long pageIndex) { d->indexFile.seek(d->wordOffset.at(pageIndex)); int pageSize = d->wordOffset.at(pageIndex + 1) - d->wordOffset.at(pageIndex); d->wordEntryBuffer = d->indexFile.read(qMin(d->wordEntryBuffer.size(), pageSize)); //TODO: check returned values, deal with word entry that strlen>255. return d->wordEntryBuffer; } QByteArray OffsetCacheFile::firstOnPageKey(long pageIndex) { if (pageIndex < d->middle.first) { if (pageIndex == d->first.first) return d->first.second; return readFirstOnPageKey(pageIndex); } else if (pageIndex > d->middle.first) { if (pageIndex == d->last.first) return d->last.second; return readFirstOnPageKey(pageIndex); } else { return d->middle.second; } } QStringList OffsetCacheFile::cacheLocations(const QString& url) { QStringList result; result.append(url + ".oft"); QString cacheLocation = QDesktopServices::storageLocation(QDesktopServices::CacheLocation); QFileInfo cacheLocationFileInfo(cacheLocation); QDir cacheLocationDir; if (!cacheLocationFileInfo.exists() && cacheLocationDir.mkdir(cacheLocation) == false) return result; if (!cacheLocationFileInfo.isDir()) return result; result.append(cacheLocation + QDir::separator() + "sdcv" + QDir::separator() + QFileInfo(url).fileName() + ".oft"); return result; } bool OffsetCacheFile::loadCache(const QString& url) { foreach (const QString& cacheLocation, cacheLocations(url)) { QFileInfo fileInfoIndex(url); QFileInfo fileInfoCache(cacheLocation); if (fileInfoCache.lastModified() < fileInfoIndex.lastModified()) continue; d->mapFile.unmap(d->mappedData); d->mapFile.setFileName(cacheLocation); if( !d->mapFile.open( QIODevice::ReadOnly ) ) { qDebug() << "Failed to open file:" << cacheLocation; return -1; } d->mappedData = d->mapFile.map(0, d->mapFile.size()); if (d->mappedData == NULL) { qDebug() << Q_FUNC_INFO << QString("Mapping the file %1 failed!").arg(cacheLocation); return false; } if (d->cacheMagicString != d->mappedData) continue; memcpy(d->wordOffset.data(), d->mappedData + d->cacheMagicString.size(), d->wordOffset.size()*sizeof(d->wordOffset.at(0))); return true; } return false; } bool OffsetCacheFile::saveCache(const QString& url) { foreach (const QString& cacheLocation, cacheLocations(url)) { QFile file(cacheLocation); if( !file.open( QIODevice::WriteOnly ) ) { qDebug() << "Failed to open file for writing:" << cacheLocation; return -1; } d->mapFile.unmap(d->mappedData); d->mapFile.setFileName(cacheLocation); if( !d->mapFile.open( QIODevice::ReadOnly ) ) { qDebug() << "Failed to open file:" << cacheLocation; return -1; } d->mappedData = d->mapFile.map(0, d->mapFile.size()); if (d->mappedData == NULL) { qDebug() << Q_FUNC_INFO << QString("Mapping the file %1 failed!").arg(cacheLocation); return false; } if (file.write(d->cacheMagicString) != d->cacheMagicString.size()) continue; if (file.write(reinterpret_cast<const char*>(d->wordOffset.data()), sizeof(d->wordOffset.at(0))*d->wordOffset.size()) != d->wordOffset.at(0)*d->wordOffset.size()) continue; file.close(); qDebug() << "Save to cache" << url; return true; } return false; } bool OffsetCacheFile::load(const QString& completeFilePath, int wordCount, qulonglong fileSize) { Q_UNUSED(fileSize); d->wordCount = wordCount; qulonglong npages = (wordCount - 1) / d->pageEntryNumber + 2; d->wordOffset.resize(npages); if (!loadCache(completeFilePath)) { //map file will close after finish of block d->mapFile.setFileName(completeFilePath); if (!d->mapFile.open(QIODevice::ReadOnly)) { qDebug() << "Failed to open file:" << completeFilePath; return -1; } d->mappedData = d->mapFile.map(0, d->mapFile.size()); if (d->mappedData == NULL) { qDebug() << Q_FUNC_INFO << QString("Mapping the file %1 failed!").arg(completeFilePath); return false; } QByteArray byteArray = QByteArray::fromRawData(reinterpret_cast<const char*>(d->mappedData), d->mapFile.size()); int position = 0; int j = 0; for (int i = 0; i < wordCount; ++i) { if (i % d->pageEntryNumber == 0) { d->wordOffset[j] = position; ++j; } position += qstrlen(byteArray.mid(position)) + 1 + 2 * sizeof(quint32); } if (!saveCache(completeFilePath)) qDebug() << "Cache update failed"; } d->indexFile.setFileName(completeFilePath); if (!d->indexFile.open(QIODevice::ReadOnly)) { qDebug() << "Failed to open file:" << completeFilePath; d->wordOffset.resize(0); return false; } d->first = qMakePair(0, readFirstOnPageKey(0)); d->last = qMakePair(d->wordOffset.size() - 2, readFirstOnPageKey(d->wordOffset.size() - 2)); d->middle = qMakePair((d->wordOffset.size() - 2) / 2, readFirstOnPageKey((d->wordOffset.size() - 2) / 2)); d->realLast = qMakePair(wordCount - 1, key(wordCount - 1)); return true; } ulong OffsetCacheFile::loadPage(long pageIndex) { ulong entryCount = d->pageEntryNumber; if (pageIndex == ulong(d->wordOffset.size() - 2) && (entryCount = d->wordCount % d->pageEntryNumber) == 0) { entryCount = d->pageEntryNumber; } if (pageIndex != d->entryIndex) { d->indexFile.seek(d->wordOffset.at(pageIndex)); d->pageData = d->indexFile.read(d->wordOffset[pageIndex + 1] - d->wordOffset[pageIndex]); d->fill(d->pageData, entryCount, pageIndex); } return entryCount; } QByteArray OffsetCacheFile::key(long index) { loadPage(index / d->pageEntryNumber); ulong indexInPage = index % d->pageEntryNumber; setWordEntryOffset(d->entries.at(indexInPage).dataOffset()); setWordEntrySize(d->entries.at(indexInPage).dataSize()); return d->entries.at(indexInPage).data(); } bool OffsetCacheFile::lookup(const QByteArray& word, long &index) { bool found = false; long indexFrom; long indexTo = d->wordOffset.size() - 2; int cmpint; long indexThisIndex; if (stardictStringCompare(word, d->first.second) < 0) { index = 0; return false; } else if (stardictStringCompare(word, d->realLast.second) > 0) { index = invalidIndex; return false; } else { indexFrom = 0; indexThisIndex = 0; while (indexFrom <= indexTo) { indexThisIndex = (indexFrom + indexTo) / 2; cmpint = stardictStringCompare(word, firstOnPageKey(indexThisIndex)); if (cmpint > 0) indexFrom = indexThisIndex + 1; else if (cmpint < 0) indexTo = indexThisIndex - 1; else { found = true; break; } } if (!found) index = indexTo; //prev else index = indexThisIndex; } if (!found) { ulong netr = loadPage(index); indexFrom = 1; // Needn't search the first word anymore. indexTo = netr - 1; indexThisIndex = 0; while (indexFrom <= indexTo) { indexThisIndex = (indexFrom + indexTo) / 2; cmpint = stardictStringCompare(word, d->entries.at(indexThisIndex).data()); if (cmpint > 0) indexFrom = indexThisIndex + 1; else if (cmpint < 0) indexTo = indexThisIndex - 1; else { found = true; break; } } index *= d->pageEntryNumber; if (!found) index += indexFrom; //next else index += indexThisIndex; } else { index *= d->pageEntryNumber; } return found; } quint32 OffsetCacheFile::wordEntryOffset() const { return AbstractIndexFile::wordEntryOffset(); } void OffsetCacheFile::setWordEntryOffset(quint32 wordEntryOffset) { AbstractIndexFile::setWordEntryOffset(wordEntryOffset); } quint32 OffsetCacheFile::wordEntrySize() const { return AbstractIndexFile::wordEntrySize(); } void OffsetCacheFile::setWordEntrySize(quint32 wordEntrySize) { AbstractIndexFile::setWordEntrySize(wordEntrySize); } <commit_msg>Return false instead of "-1" in a method returning a boolean value<commit_after>/****************************************************************************** * This file is part of the Mula project * Copyright (c) 2011 Laszlo Papp <lpapp@kde.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "offsetcachefile.h" #include "file.h" #include "wordentry.h" #include <QtCore/QVector> #include <QtCore/QFile> #include <QtCore/QtGlobal> #include <QtCore/QDir> #include <QtCore/QDateTime> #include <QtCore/QDebug> #include <QtCore/QPair> #include <QtGui/QDesktopServices> #include <arpa/inet.h> using namespace MulaPluginStarDict; class OffsetCacheFile::Private { public: Private() : wordCount(0) , entryIndex(-1) , cacheMagicString("StarDict's Cache, Version: 0.1") , mappedData(0) { } ~Private() { } void fill(QByteArray data, int entryCount, long index); static const int pageEntryNumber = 32; QVector<quint32> wordOffset; QFile indexFile; ulong wordCount; QByteArray wordEntryBuffer; // 256 + sizeof(quint32)*2) - The length of "word_str" should be less than 256. See src/tools/DICTFILE_FORMAT. // index/date based key and value pair QPair<int, QByteArray> first; QPair<int, QByteArray> last; QPair<int, QByteArray> middle; QPair<int, QByteArray> realLast; QByteArray pageData; long entryIndex; QList<WordEntry> entries; QByteArray cacheMagicString; QFile mapFile; uchar *mappedData; }; void OffsetCacheFile::Private::fill(QByteArray data, int entryCount, long index) { entryIndex = index; ulong position = 0; for (int i = 0; i < entryCount; ++i) { entries[i].setData(data.mid(position)); position = qstrlen(data.mid(position)) + 1; entries[i].setDataOffset(ntohl(*reinterpret_cast<quint32 *>(data.mid(position).data()))); position += sizeof(quint32); entries[i].setDataSize(ntohl(*reinterpret_cast<quint32 *>(data.mid(position).data()))); position += sizeof(quint32); } } OffsetCacheFile::OffsetCacheFile() : d(new Private) { } OffsetCacheFile::~OffsetCacheFile() { } QByteArray OffsetCacheFile::readFirstOnPageKey(long pageIndex) { d->indexFile.seek(d->wordOffset.at(pageIndex)); int pageSize = d->wordOffset.at(pageIndex + 1) - d->wordOffset.at(pageIndex); d->wordEntryBuffer = d->indexFile.read(qMin(d->wordEntryBuffer.size(), pageSize)); //TODO: check returned values, deal with word entry that strlen>255. return d->wordEntryBuffer; } QByteArray OffsetCacheFile::firstOnPageKey(long pageIndex) { if (pageIndex < d->middle.first) { if (pageIndex == d->first.first) return d->first.second; return readFirstOnPageKey(pageIndex); } else if (pageIndex > d->middle.first) { if (pageIndex == d->last.first) return d->last.second; return readFirstOnPageKey(pageIndex); } else { return d->middle.second; } } QStringList OffsetCacheFile::cacheLocations(const QString& url) { QStringList result; result.append(url + ".oft"); QString cacheLocation = QDesktopServices::storageLocation(QDesktopServices::CacheLocation); QFileInfo cacheLocationFileInfo(cacheLocation); QDir cacheLocationDir; if (!cacheLocationFileInfo.exists() && cacheLocationDir.mkdir(cacheLocation) == false) return result; if (!cacheLocationFileInfo.isDir()) return result; result.append(cacheLocation + QDir::separator() + "sdcv" + QDir::separator() + QFileInfo(url).fileName() + ".oft"); return result; } bool OffsetCacheFile::loadCache(const QString& url) { foreach (const QString& cacheLocation, cacheLocations(url)) { QFileInfo fileInfoIndex(url); QFileInfo fileInfoCache(cacheLocation); if (fileInfoCache.lastModified() < fileInfoIndex.lastModified()) continue; d->mapFile.unmap(d->mappedData); d->mapFile.setFileName(cacheLocation); if( !d->mapFile.open( QIODevice::ReadOnly ) ) { qDebug() << "Failed to open file:" << cacheLocation; return -1; } d->mappedData = d->mapFile.map(0, d->mapFile.size()); if (d->mappedData == NULL) { qDebug() << Q_FUNC_INFO << QString("Mapping the file %1 failed!").arg(cacheLocation); return false; } if (d->cacheMagicString != d->mappedData) continue; memcpy(d->wordOffset.data(), d->mappedData + d->cacheMagicString.size(), d->wordOffset.size()*sizeof(d->wordOffset.at(0))); return true; } return false; } bool OffsetCacheFile::saveCache(const QString& url) { foreach (const QString& cacheLocation, cacheLocations(url)) { QFile file(cacheLocation); if( !file.open( QIODevice::WriteOnly ) ) { qDebug() << "Failed to open file for writing:" << cacheLocation; return false; } d->mapFile.unmap(d->mappedData); d->mapFile.setFileName(cacheLocation); if( !d->mapFile.open( QIODevice::ReadOnly ) ) { qDebug() << "Failed to open file:" << cacheLocation; return false; } d->mappedData = d->mapFile.map(0, d->mapFile.size()); if (d->mappedData == NULL) { qDebug() << Q_FUNC_INFO << QString("Mapping the file %1 failed!").arg(cacheLocation); return false; } if (file.write(d->cacheMagicString) != d->cacheMagicString.size()) continue; if (file.write(reinterpret_cast<const char*>(d->wordOffset.data()), sizeof(d->wordOffset.at(0))*d->wordOffset.size()) != d->wordOffset.at(0)*d->wordOffset.size()) continue; file.close(); qDebug() << "Save to cache" << url; return true; } return false; } bool OffsetCacheFile::load(const QString& completeFilePath, int wordCount, qulonglong fileSize) { Q_UNUSED(fileSize); d->wordCount = wordCount; qulonglong npages = (wordCount - 1) / d->pageEntryNumber + 2; d->wordOffset.resize(npages); if (!loadCache(completeFilePath)) { //map file will close after finish of block d->mapFile.setFileName(completeFilePath); if (!d->mapFile.open(QIODevice::ReadOnly)) { qDebug() << "Failed to open file:" << completeFilePath; return -1; } d->mappedData = d->mapFile.map(0, d->mapFile.size()); if (d->mappedData == NULL) { qDebug() << Q_FUNC_INFO << QString("Mapping the file %1 failed!").arg(completeFilePath); return false; } QByteArray byteArray = QByteArray::fromRawData(reinterpret_cast<const char*>(d->mappedData), d->mapFile.size()); int position = 0; int j = 0; for (int i = 0; i < wordCount; ++i) { if (i % d->pageEntryNumber == 0) { d->wordOffset[j] = position; ++j; } position += qstrlen(byteArray.mid(position)) + 1 + 2 * sizeof(quint32); } if (!saveCache(completeFilePath)) qDebug() << "Cache update failed"; } d->indexFile.setFileName(completeFilePath); if (!d->indexFile.open(QIODevice::ReadOnly)) { qDebug() << "Failed to open file:" << completeFilePath; d->wordOffset.resize(0); return false; } d->first = qMakePair(0, readFirstOnPageKey(0)); d->last = qMakePair(d->wordOffset.size() - 2, readFirstOnPageKey(d->wordOffset.size() - 2)); d->middle = qMakePair((d->wordOffset.size() - 2) / 2, readFirstOnPageKey((d->wordOffset.size() - 2) / 2)); d->realLast = qMakePair(wordCount - 1, key(wordCount - 1)); return true; } ulong OffsetCacheFile::loadPage(long pageIndex) { ulong entryCount = d->pageEntryNumber; if (pageIndex == ulong(d->wordOffset.size() - 2) && (entryCount = d->wordCount % d->pageEntryNumber) == 0) { entryCount = d->pageEntryNumber; } if (pageIndex != d->entryIndex) { d->indexFile.seek(d->wordOffset.at(pageIndex)); d->pageData = d->indexFile.read(d->wordOffset[pageIndex + 1] - d->wordOffset[pageIndex]); d->fill(d->pageData, entryCount, pageIndex); } return entryCount; } QByteArray OffsetCacheFile::key(long index) { loadPage(index / d->pageEntryNumber); ulong indexInPage = index % d->pageEntryNumber; setWordEntryOffset(d->entries.at(indexInPage).dataOffset()); setWordEntrySize(d->entries.at(indexInPage).dataSize()); return d->entries.at(indexInPage).data(); } bool OffsetCacheFile::lookup(const QByteArray& word, long &index) { bool found = false; long indexFrom; long indexTo = d->wordOffset.size() - 2; int cmpint; long indexThisIndex; if (stardictStringCompare(word, d->first.second) < 0) { index = 0; return false; } else if (stardictStringCompare(word, d->realLast.second) > 0) { index = invalidIndex; return false; } else { indexFrom = 0; indexThisIndex = 0; while (indexFrom <= indexTo) { indexThisIndex = (indexFrom + indexTo) / 2; cmpint = stardictStringCompare(word, firstOnPageKey(indexThisIndex)); if (cmpint > 0) indexFrom = indexThisIndex + 1; else if (cmpint < 0) indexTo = indexThisIndex - 1; else { found = true; break; } } if (!found) index = indexTo; //prev else index = indexThisIndex; } if (!found) { ulong netr = loadPage(index); indexFrom = 1; // Needn't search the first word anymore. indexTo = netr - 1; indexThisIndex = 0; while (indexFrom <= indexTo) { indexThisIndex = (indexFrom + indexTo) / 2; cmpint = stardictStringCompare(word, d->entries.at(indexThisIndex).data()); if (cmpint > 0) indexFrom = indexThisIndex + 1; else if (cmpint < 0) indexTo = indexThisIndex - 1; else { found = true; break; } } index *= d->pageEntryNumber; if (!found) index += indexFrom; //next else index += indexThisIndex; } else { index *= d->pageEntryNumber; } return found; } quint32 OffsetCacheFile::wordEntryOffset() const { return AbstractIndexFile::wordEntryOffset(); } void OffsetCacheFile::setWordEntryOffset(quint32 wordEntryOffset) { AbstractIndexFile::setWordEntryOffset(wordEntryOffset); } quint32 OffsetCacheFile::wordEntrySize() const { return AbstractIndexFile::wordEntrySize(); } void OffsetCacheFile::setWordEntrySize(quint32 wordEntrySize) { AbstractIndexFile::setWordEntrySize(wordEntrySize); } <|endoftext|>
<commit_before>/****************************************************************************** * This file is part of the Mula project * Copyright (c) 2011 Laszlo Papp <lpapp@kde.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "offsetcachefile.h" #include "file.h" #include "wordentry.h" #include <QtCore/QVector> #include <QtCore/QFile> #include <QtCore/QtGlobal> #include <QtCore/QDir> #include <QtCore/QDateTime> #include <QtCore/QDebug> #include <QtCore/QPair> #include <QtGui/QDesktopServices> #include <arpa/inet.h> using namespace MulaPluginStarDict; class OffsetCacheFile::Private { public: Private() : wordCount(0) , entryIndex(-1) , cacheMagicString("StarDict's Cache, Version: 0.1") , mappedData(0) { } ~Private() { } void fill(QByteArray data, int wordEntryCount, long index); static const int pageEntryNumber = 32; QVector<quint32> pageOffsetList; QFile indexFile; ulong wordCount; // The length of "word_str" should be less than 256, and then offset, size static const int wordEntrySize = 256 + sizeof(quint32)*2; // index/date based key and value pair QPair<int, QByteArray> first; QPair<int, QByteArray> last; QPair<int, QByteArray> middle; QPair<int, QByteArray> realLast; QByteArray pageData; long entryIndex; QList<WordEntry> entries; QByteArray cacheMagicString; QFile mapFile; uchar *mappedData; }; void OffsetCacheFile::Private::fill(QByteArray data, int wordEntryCount, long index) { entryIndex = index; ulong position = 0; for (int i = 0; i < wordEntryCount; ++i) { entries[i].setData(data.mid(position)); position = qstrlen(data.mid(position)) + 1; entries[i].setDataOffset(ntohl(*reinterpret_cast<quint32 *>(data.mid(position).data()))); position += sizeof(quint32); entries[i].setDataSize(ntohl(*reinterpret_cast<quint32 *>(data.mid(position).data()))); position += sizeof(quint32); } } OffsetCacheFile::OffsetCacheFile() : d(new Private) { } OffsetCacheFile::~OffsetCacheFile() { } QByteArray OffsetCacheFile::readFirstWordDataOnPage(long pageIndex) { int pageSize = d->pageOffsetList.at(pageIndex + 1) - d->pageOffsetList.at(pageIndex); int wordEntrySize = d->wordEntrySize; d->indexFile.seek(d->pageOffsetList.at(pageIndex)); return d->indexFile.read(qMin(wordEntrySize, pageSize)); //TODO: check returned values, deal with word entry that strlen>255. } QByteArray OffsetCacheFile::firstWordDataOnPage(long pageIndex) { if (pageIndex < d->middle.first) { if (pageIndex == d->first.first) return d->first.second; return readFirstWordDataOnPage(pageIndex); } else if (pageIndex > d->middle.first) { if (pageIndex == d->last.first) return d->last.second; return readFirstWordDataOnPage(pageIndex); } else { return d->middle.second; } } QStringList OffsetCacheFile::cacheLocations(const QString& completeFilePath) { QStringList result; result.append(completeFilePath + ".oft"); QString cacheLocation = QDesktopServices::storageLocation(QDesktopServices::CacheLocation); QFileInfo cacheLocationFileInfo(cacheLocation); QDir cacheLocationDir; if (!cacheLocationFileInfo.exists() && cacheLocationDir.mkdir(cacheLocation) == false) return result; if (!cacheLocationFileInfo.isDir()) return result; result.append(cacheLocation + QDir::separator() + "sdcv" + QDir::separator() + QFileInfo(completeFilePath).fileName() + ".oft"); return result; } bool OffsetCacheFile::loadCache(const QString& completeFilePath) { foreach (const QString& cacheLocation, cacheLocations(completeFilePath)) { QFileInfo fileInfoIndex(completeFilePath); QFileInfo fileInfoCache(cacheLocation); if (fileInfoCache.lastModified() < fileInfoIndex.lastModified()) continue; d->mapFile.unmap(d->mappedData); d->mapFile.setFileName(cacheLocation); if( !d->mapFile.open( QIODevice::ReadOnly ) ) { qDebug() << "Failed to open file:" << cacheLocation; return false; } d->mappedData = d->mapFile.map(0, d->mapFile.size()); if (d->mappedData == NULL) { qDebug() << Q_FUNC_INFO << QString("Mapping the file %1 failed!").arg(cacheLocation); return false; } if (d->cacheMagicString != d->mappedData) continue; memcpy(d->pageOffsetList.data(), d->mappedData + d->cacheMagicString.size(), d->pageOffsetList.size()*sizeof(d->pageOffsetList.at(0))); return true; } return false; } bool OffsetCacheFile::saveCache(const QString& completeFilePath) { foreach (const QString& cacheLocation, cacheLocations(completeFilePath)) { QFile file(cacheLocation); if( !file.open( QIODevice::WriteOnly ) ) { qDebug() << "Failed to open file for writing:" << cacheLocation; return false; } d->mapFile.unmap(d->mappedData); d->mapFile.setFileName(cacheLocation); if( !d->mapFile.open( QIODevice::ReadOnly ) ) { qDebug() << "Failed to open file:" << cacheLocation; return false; } d->mappedData = d->mapFile.map(0, d->mapFile.size()); if (d->mappedData == NULL) { qDebug() << Q_FUNC_INFO << QString("Mapping the file %1 failed!").arg(cacheLocation); return false; } if (file.write(d->cacheMagicString) != d->cacheMagicString.size()) continue; if (file.write(reinterpret_cast<const char*>(d->pageOffsetList.data()), sizeof(d->pageOffsetList.at(0))*d->pageOffsetList.size()) != d->pageOffsetList.at(0)*d->pageOffsetList.size()) continue; file.close(); qDebug() << "Save to cache" << completeFilePath; return true; } return false; } bool OffsetCacheFile::load(const QString& completeFilePath, int wordCount, qulonglong fileSize) { Q_UNUSED(fileSize); d->wordCount = wordCount; // Adding 1 is needed because the index file size is also stored // if (wordCount % d->pageEntryNumber == 0) // d->pageOffsetList.resize(wordCount / d->pageEntryNumber + 1); // else // d->pageOffsetList.resize(wordCount / d->pageEntryNumber + 2); if (!loadCache(completeFilePath)) { //map file will close after finish of block d->mapFile.unmap(d->mappedData); d->mapFile.setFileName(completeFilePath); if (!d->mapFile.open(QIODevice::ReadOnly)) { qDebug() << "Failed to open file:" << completeFilePath; return -1; } d->mappedData = d->mapFile.map(0, d->mapFile.size()); if (d->mappedData == NULL) { qDebug() << Q_FUNC_INFO << QString("Mapping the file %1 failed!").arg(completeFilePath); return false; } QByteArray byteArray = QByteArray::fromRawData(reinterpret_cast<const char*>(d->mappedData), d->mapFile.size()); int position = 0; d->pageOffsetList.clear(); for (int i = 0; i < wordCount; ++i) { if (i % d->pageEntryNumber == 0) d->pageOffsetList.append(position); position += qstrlen(byteArray.mid(position)) + 1 + 2 * sizeof(quint32); } d->pageOffsetList.append(position); if (!saveCache(completeFilePath)) qDebug() << "Cache update failed"; } d->indexFile.setFileName(completeFilePath); if (!d->indexFile.open(QIODevice::ReadOnly)) { qDebug() << "Failed to open file:" << completeFilePath; d->pageOffsetList.clear(); return false; } d->first = qMakePair(0, readFirstWordDataOnPage(0)); d->last = qMakePair(d->pageOffsetList.size() - 2, readFirstWordDataOnPage(d->pageOffsetList.size() - 2)); d->middle = qMakePair((d->pageOffsetList.size() - 2) / 2, readFirstWordDataOnPage((d->pageOffsetList.size() - 2) / 2)); d->realLast = qMakePair(wordCount - 1, key(wordCount - 1)); return true; } ulong OffsetCacheFile::loadPage(long pageIndex) { ulong wordEntryCount = d->pageEntryNumber; if (pageIndex == ulong(d->pageOffsetList.size() - 2) && (wordEntryCount = d->wordCount % d->pageEntryNumber) == 0) { wordEntryCount = d->pageEntryNumber; } if (pageIndex != d->entryIndex) { d->indexFile.seek(d->pageOffsetList.at(pageIndex)); d->pageData = d->indexFile.read(d->pageOffsetList[pageIndex + 1] - d->pageOffsetList[pageIndex]); d->fill(d->pageData, wordEntryCount, pageIndex); } return wordEntryCount; } QByteArray OffsetCacheFile::key(long index) { loadPage(index / d->pageEntryNumber); ulong indexInPage = index % d->pageEntryNumber; setWordEntryOffset(d->entries.at(indexInPage).dataOffset()); setWordEntrySize(d->entries.at(indexInPage).dataSize()); return d->entries.at(indexInPage).data(); } bool OffsetCacheFile::lookup(const QByteArray& word, long &index) { bool found = false; long indexFrom; long indexTo = d->pageOffsetList.size() - 2; int cmpint; long indexThisIndex; if (stardictStringCompare(word, d->first.second) < 0) { index = 0; return false; } else if (stardictStringCompare(word, d->realLast.second) > 0) { index = invalidIndex; return false; } else { indexFrom = 0; indexThisIndex = 0; while (indexFrom <= indexTo) { indexThisIndex = (indexFrom + indexTo) / 2; cmpint = stardictStringCompare(word, firstWordDataOnPage(indexThisIndex)); if (cmpint > 0) indexFrom = indexThisIndex + 1; else if (cmpint < 0) indexTo = indexThisIndex - 1; else { found = true; break; } } if (!found) index = indexTo; //prev else index = indexThisIndex; } if (!found) { ulong netr = loadPage(index); indexFrom = 1; // Needn't search the first word anymore. indexTo = netr - 1; indexThisIndex = 0; while (indexFrom <= indexTo) { indexThisIndex = (indexFrom + indexTo) / 2; cmpint = stardictStringCompare(word, d->entries.at(indexThisIndex).data()); if (cmpint > 0) indexFrom = indexThisIndex + 1; else if (cmpint < 0) indexTo = indexThisIndex - 1; else { found = true; break; } } index *= d->pageEntryNumber; if (!found) index += indexFrom; //next else index += indexThisIndex; } else { index *= d->pageEntryNumber; } return found; } quint32 OffsetCacheFile::wordEntryOffset() const { return AbstractIndexFile::wordEntryOffset(); } void OffsetCacheFile::setWordEntryOffset(quint32 wordEntryOffset) { AbstractIndexFile::setWordEntryOffset(wordEntryOffset); } quint32 OffsetCacheFile::wordEntrySize() const { return AbstractIndexFile::wordEntrySize(); } void OffsetCacheFile::setWordEntrySize(quint32 wordEntrySize) { AbstractIndexFile::setWordEntrySize(wordEntrySize); } <commit_msg>Do not calculate the size 1 + 2 * sizeof(quint32) in each iteration of the cycle<commit_after>/****************************************************************************** * This file is part of the Mula project * Copyright (c) 2011 Laszlo Papp <lpapp@kde.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "offsetcachefile.h" #include "file.h" #include "wordentry.h" #include <QtCore/QVector> #include <QtCore/QFile> #include <QtCore/QtGlobal> #include <QtCore/QDir> #include <QtCore/QDateTime> #include <QtCore/QDebug> #include <QtCore/QPair> #include <QtGui/QDesktopServices> #include <arpa/inet.h> using namespace MulaPluginStarDict; class OffsetCacheFile::Private { public: Private() : wordCount(0) , entryIndex(-1) , cacheMagicString("StarDict's Cache, Version: 0.1") , mappedData(0) { } ~Private() { } void fill(QByteArray data, int wordEntryCount, long index); static const int pageEntryNumber = 32; QVector<quint32> pageOffsetList; QFile indexFile; ulong wordCount; // The length of "word_str" should be less than 256, and then offset, size static const int wordEntrySize = 256 + sizeof(quint32)*2; // index/date based key and value pair QPair<int, QByteArray> first; QPair<int, QByteArray> last; QPair<int, QByteArray> middle; QPair<int, QByteArray> realLast; QByteArray pageData; long entryIndex; QList<WordEntry> entries; QByteArray cacheMagicString; QFile mapFile; uchar *mappedData; }; void OffsetCacheFile::Private::fill(QByteArray data, int wordEntryCount, long index) { entryIndex = index; ulong position = 0; for (int i = 0; i < wordEntryCount; ++i) { entries[i].setData(data.mid(position)); position = qstrlen(data.mid(position)) + 1; entries[i].setDataOffset(ntohl(*reinterpret_cast<quint32 *>(data.mid(position).data()))); position += sizeof(quint32); entries[i].setDataSize(ntohl(*reinterpret_cast<quint32 *>(data.mid(position).data()))); position += sizeof(quint32); } } OffsetCacheFile::OffsetCacheFile() : d(new Private) { } OffsetCacheFile::~OffsetCacheFile() { } QByteArray OffsetCacheFile::readFirstWordDataOnPage(long pageIndex) { int pageSize = d->pageOffsetList.at(pageIndex + 1) - d->pageOffsetList.at(pageIndex); int wordEntrySize = d->wordEntrySize; d->indexFile.seek(d->pageOffsetList.at(pageIndex)); return d->indexFile.read(qMin(wordEntrySize, pageSize)); //TODO: check returned values, deal with word entry that strlen>255. } QByteArray OffsetCacheFile::firstWordDataOnPage(long pageIndex) { if (pageIndex < d->middle.first) { if (pageIndex == d->first.first) return d->first.second; return readFirstWordDataOnPage(pageIndex); } else if (pageIndex > d->middle.first) { if (pageIndex == d->last.first) return d->last.second; return readFirstWordDataOnPage(pageIndex); } else { return d->middle.second; } } QStringList OffsetCacheFile::cacheLocations(const QString& completeFilePath) { QStringList result; result.append(completeFilePath + ".oft"); QString cacheLocation = QDesktopServices::storageLocation(QDesktopServices::CacheLocation); QFileInfo cacheLocationFileInfo(cacheLocation); QDir cacheLocationDir; if (!cacheLocationFileInfo.exists() && cacheLocationDir.mkdir(cacheLocation) == false) return result; if (!cacheLocationFileInfo.isDir()) return result; result.append(cacheLocation + QDir::separator() + "sdcv" + QDir::separator() + QFileInfo(completeFilePath).fileName() + ".oft"); return result; } bool OffsetCacheFile::loadCache(const QString& completeFilePath) { foreach (const QString& cacheLocation, cacheLocations(completeFilePath)) { QFileInfo fileInfoIndex(completeFilePath); QFileInfo fileInfoCache(cacheLocation); if (fileInfoCache.lastModified() < fileInfoIndex.lastModified()) continue; d->mapFile.unmap(d->mappedData); d->mapFile.setFileName(cacheLocation); if( !d->mapFile.open( QIODevice::ReadOnly ) ) { qDebug() << "Failed to open file:" << cacheLocation; return false; } d->mappedData = d->mapFile.map(0, d->mapFile.size()); if (d->mappedData == NULL) { qDebug() << Q_FUNC_INFO << QString("Mapping the file %1 failed!").arg(cacheLocation); return false; } if (d->cacheMagicString != d->mappedData) continue; memcpy(d->pageOffsetList.data(), d->mappedData + d->cacheMagicString.size(), d->pageOffsetList.size()*sizeof(d->pageOffsetList.at(0))); return true; } return false; } bool OffsetCacheFile::saveCache(const QString& completeFilePath) { foreach (const QString& cacheLocation, cacheLocations(completeFilePath)) { QFile file(cacheLocation); if( !file.open( QIODevice::WriteOnly ) ) { qDebug() << "Failed to open file for writing:" << cacheLocation; return false; } d->mapFile.unmap(d->mappedData); d->mapFile.setFileName(cacheLocation); if( !d->mapFile.open( QIODevice::ReadOnly ) ) { qDebug() << "Failed to open file:" << cacheLocation; return false; } d->mappedData = d->mapFile.map(0, d->mapFile.size()); if (d->mappedData == NULL) { qDebug() << Q_FUNC_INFO << QString("Mapping the file %1 failed!").arg(cacheLocation); return false; } if (file.write(d->cacheMagicString) != d->cacheMagicString.size()) continue; if (file.write(reinterpret_cast<const char*>(d->pageOffsetList.data()), sizeof(d->pageOffsetList.at(0))*d->pageOffsetList.size()) != d->pageOffsetList.at(0)*d->pageOffsetList.size()) continue; file.close(); qDebug() << "Save to cache" << completeFilePath; return true; } return false; } bool OffsetCacheFile::load(const QString& completeFilePath, int wordCount, qulonglong fileSize) { Q_UNUSED(fileSize); d->wordCount = wordCount; if (!loadCache(completeFilePath)) { //map file will close after finish of block d->mapFile.unmap(d->mappedData); d->mapFile.setFileName(completeFilePath); if (!d->mapFile.open(QIODevice::ReadOnly)) { qDebug() << "Failed to open file:" << completeFilePath; return -1; } d->mappedData = d->mapFile.map(0, d->mapFile.size()); if (d->mappedData == NULL) { qDebug() << Q_FUNC_INFO << QString("Mapping the file %1 failed!").arg(completeFilePath); return false; } QByteArray byteArray = QByteArray::fromRawData(reinterpret_cast<const char*>(d->mappedData), d->mapFile.size()); int position = 0; d->pageOffsetList.clear(); int wordTerminatorOffsetSizeLength = 1 + 2 * sizeof(quint32); for (int i = 0; i < wordCount; ++i) { if (i % d->pageEntryNumber == 0) d->pageOffsetList.append(position); position += qstrlen(byteArray.mid(position)) + wordTerminatorOffsetSizeLength; } d->pageOffsetList.append(position); if (!saveCache(completeFilePath)) qDebug() << "Cache update failed"; } d->indexFile.setFileName(completeFilePath); if (!d->indexFile.open(QIODevice::ReadOnly)) { qDebug() << "Failed to open file:" << completeFilePath; d->pageOffsetList.clear(); return false; } d->first = qMakePair(0, readFirstWordDataOnPage(0)); d->last = qMakePair(d->pageOffsetList.size() - 2, readFirstWordDataOnPage(d->pageOffsetList.size() - 2)); d->middle = qMakePair((d->pageOffsetList.size() - 2) / 2, readFirstWordDataOnPage((d->pageOffsetList.size() - 2) / 2)); d->realLast = qMakePair(wordCount - 1, key(wordCount - 1)); return true; } ulong OffsetCacheFile::loadPage(long pageIndex) { ulong wordEntryCount = d->pageEntryNumber; if (pageIndex == ulong(d->pageOffsetList.size() - 2) && (wordEntryCount = d->wordCount % d->pageEntryNumber) == 0) { wordEntryCount = d->pageEntryNumber; } if (pageIndex != d->entryIndex) { d->indexFile.seek(d->pageOffsetList.at(pageIndex)); d->pageData = d->indexFile.read(d->pageOffsetList[pageIndex + 1] - d->pageOffsetList[pageIndex]); d->fill(d->pageData, wordEntryCount, pageIndex); } return wordEntryCount; } QByteArray OffsetCacheFile::key(long index) { loadPage(index / d->pageEntryNumber); ulong indexInPage = index % d->pageEntryNumber; setWordEntryOffset(d->entries.at(indexInPage).dataOffset()); setWordEntrySize(d->entries.at(indexInPage).dataSize()); return d->entries.at(indexInPage).data(); } bool OffsetCacheFile::lookup(const QByteArray& word, long &index) { bool found = false; long indexFrom; long indexTo = d->pageOffsetList.size() - 2; int cmpint; long indexThisIndex; if (stardictStringCompare(word, d->first.second) < 0) { index = 0; return false; } else if (stardictStringCompare(word, d->realLast.second) > 0) { index = invalidIndex; return false; } else { indexFrom = 0; indexThisIndex = 0; while (indexFrom <= indexTo) { indexThisIndex = (indexFrom + indexTo) / 2; cmpint = stardictStringCompare(word, firstWordDataOnPage(indexThisIndex)); if (cmpint > 0) indexFrom = indexThisIndex + 1; else if (cmpint < 0) indexTo = indexThisIndex - 1; else { found = true; break; } } if (!found) index = indexTo; //prev else index = indexThisIndex; } if (!found) { ulong netr = loadPage(index); indexFrom = 1; // Needn't search the first word anymore. indexTo = netr - 1; indexThisIndex = 0; while (indexFrom <= indexTo) { indexThisIndex = (indexFrom + indexTo) / 2; cmpint = stardictStringCompare(word, d->entries.at(indexThisIndex).data()); if (cmpint > 0) indexFrom = indexThisIndex + 1; else if (cmpint < 0) indexTo = indexThisIndex - 1; else { found = true; break; } } index *= d->pageEntryNumber; if (!found) index += indexFrom; //next else index += indexThisIndex; } else { index *= d->pageEntryNumber; } return found; } quint32 OffsetCacheFile::wordEntryOffset() const { return AbstractIndexFile::wordEntryOffset(); } void OffsetCacheFile::setWordEntryOffset(quint32 wordEntryOffset) { AbstractIndexFile::setWordEntryOffset(wordEntryOffset); } quint32 OffsetCacheFile::wordEntrySize() const { return AbstractIndexFile::wordEntrySize(); } void OffsetCacheFile::setWordEntrySize(quint32 wordEntrySize) { AbstractIndexFile::setWordEntrySize(wordEntrySize); } <|endoftext|>
<commit_before>/* * Copyright 1999-2000,2004 The Apache Software Foundation. * * 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. */ /* * $Log$ * Revision 1.9 2004/12/21 16:02:51 cargilld * Attempt to fix various apidoc problems. * * Revision 1.8 2004/12/03 19:40:32 cargilld * Change call to resolveEntity to pass in public id so that only one call to resolveEntity is needed (a follow-on to Alberto's fix). * * Revision 1.7 2004/09/26 01:06:31 cargilld * Fix documentation generation problem. Replace <pre> with <code>. Patch from James Littlejohn. * * Revision 1.6 2004/09/08 13:56:24 peiyongz * Apache License Version 2.0 * * Revision 1.5 2004/02/15 19:37:16 amassari * Removed cause for warnings in VC 7.1 * * Revision 1.4 2004/02/13 14:28:30 cargilld * Fix for bug 26900 (remove virtual on destructor) * * Revision 1.3 2004/01/29 11:48:47 cargilld * Code cleanup changes to get rid of various compiler diagnostic messages. * * Revision 1.2 2003/11/25 18:16:38 knoaman * Documentation update. Thanks to David Cargill. * * Revision 1.1 2003/10/30 21:37:32 knoaman * Enhanced Entity Resolver Support. Thanks to David Cargill. * * * Revision 1.1 1999/11/09 01:07:44 twl * Initial checkin * */ #ifndef XMLRESOURCEIDENTIFIER_HPP #define XMLRESOURCEIDENTIFIER_HPP XERCES_CPP_NAMESPACE_BEGIN /** * <p>This class is used along with XMLEntityResolver to resolve entities. * Instead of passing publicId and systemId on the resolveEntity call, * as is done with the SAX entity resolver, an object of type XMLResourceIdentifier * is passed. By calling the getResourceIdentifierType() method the user can * determine which data members are available for inspection:</p> * * <table border='1'> * <tr> * <td>ResourceIdentifierType</td> * <td>Available Data Members</td> * </tr> * <tr> * <td>SchemaGrammar</td> * <td>schemaLocation, nameSpace & baseURI (current document)</td> * </tr> * <tr> * <td>SchemaImport</td> * <td>schemaLocation, nameSpace & baseURI (current document)</td> * </tr> * <tr> * <td>SchemaInclude</td> * <td>schemaLocation & baseURI (current document)</td> * </tr> * <tr> * <td>SchemaRedefine</td> * <td>schemaLocation & baseURI (current document)</td> * </tr> * <tr> * <td>ExternalEntity</td> * <td>systemId, publicId & baseURI (some items may be NULL)</td> * </tr> * </table> * * <p>The following resolver would provide the application * with a special character stream for the entity with the system * identifier "http://www.myhost.com/today":</p> * *<code> * #include <xercesc/util/XMLEntityResolver.hpp><br> * #include <xercesc/sax/InputSource.hpp><br> *<br> *&nbsp;class MyResolver : public XMLEntityResolver {<br> *&nbsp;&nbsp;public:<br> *&nbsp;&nbsp;&nbsp;InputSource resolveEntity (XMLResourceIdentifier* xmlri);<br> *&nbsp;&nbsp;&nbsp;...<br> *&nbsp;&nbsp;};<br> *<br> *&nbsp;&nbsp;MyResolver::resolveEntity(XMLResourceIdentifier* xmlri) {<br> *&nbsp;&nbsp;&nbsp;switch(xmlri->getResourceIdentifierType()) {<br> *&nbsp;&nbsp;&nbsp;&nbsp;case XMLResourceIdentifier::SystemId:<br> *&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if (XMLString::compareString(xmlri->getSystemId(), "http://www.myhost.com/today")) {<br> *&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;MyReader* reader = new MyReader();<br> *&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return new InputSource(reader);<br> *&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} else {<br> *&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return null;<br> *&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br> *&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;break;<br> *&nbsp;&nbsp;&nbsp;&nbsp;default:<br> *&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return null;<br> *&nbsp;&nbsp;&nbsp;}<br> *&nbsp;&nbsp;}</code> * * @see SAXParser#setXMLEntityResolver * @see InputSource#InputSource */ class XMLUTIL_EXPORT XMLResourceIdentifier { public: //@{ enum ResourceIdentifierType { SchemaGrammar = 0, SchemaImport, SchemaInclude, SchemaRedefine , ExternalEntity, UnKnown = 255 }; /** @name Constructors and Destructor */ /** Constructor */ XMLResourceIdentifier(const ResourceIdentifierType resourceIdentitiferType , const XMLCh* const systemId , const XMLCh* const nameSpace = 0 , const XMLCh* const publicId = 0 , const XMLCh* const baseURI = 0); /** Destructor */ ~XMLResourceIdentifier() { } //@} // ----------------------------------------------------------------------- // Getter methods // ----------------------------------------------------------------------- ResourceIdentifierType getResourceIdentifierType() const; const XMLCh* getPublicId() const; const XMLCh* getSystemId() const; const XMLCh* getSchemaLocation() const; const XMLCh* getBaseURI() const; const XMLCh* getNameSpace() const; //@} private : const ResourceIdentifierType fResourceIdentifierType; const XMLCh* fPublicId; const XMLCh* fSystemId; const XMLCh* fBaseURI; const XMLCh* fNameSpace; /* Unimplemented constructors and operators */ /* Copy constructor */ XMLResourceIdentifier(const XMLResourceIdentifier&); /* Assignment operator */ XMLResourceIdentifier& operator=(const XMLResourceIdentifier&); }; inline XMLResourceIdentifier::ResourceIdentifierType XMLResourceIdentifier::getResourceIdentifierType() const { return fResourceIdentifierType; } inline const XMLCh* XMLResourceIdentifier::getPublicId() const { return fPublicId; } inline const XMLCh* XMLResourceIdentifier::getSystemId() const { return fSystemId; } inline const XMLCh* XMLResourceIdentifier::getSchemaLocation() const { return fSystemId; } inline const XMLCh* XMLResourceIdentifier::getBaseURI() const { return fBaseURI; } inline const XMLCh* XMLResourceIdentifier::getNameSpace() const { return fNameSpace; } inline XMLResourceIdentifier::XMLResourceIdentifier(const ResourceIdentifierType resourceIdentifierType , const XMLCh* const systemId , const XMLCh* const nameSpace , const XMLCh* const publicId , const XMLCh* const baseURI ) : fResourceIdentifierType(resourceIdentifierType) , fSystemId(systemId) , fNameSpace(nameSpace) , fPublicId(publicId) , fBaseURI(baseURI) { } XERCES_CPP_NAMESPACE_END #endif <commit_msg>Attempt to fix various apidoc problems.<commit_after>/* * Copyright 1999-2000,2004 The Apache Software Foundation. * * 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. */ /* * $Log$ * Revision 1.10 2004/12/21 16:32:52 cargilld * Attempt to fix various apidoc problems. * * Revision 1.9 2004/12/21 16:02:51 cargilld * Attempt to fix various apidoc problems. * * Revision 1.8 2004/12/03 19:40:32 cargilld * Change call to resolveEntity to pass in public id so that only one call to resolveEntity is needed (a follow-on to Alberto's fix). * * Revision 1.7 2004/09/26 01:06:31 cargilld * Fix documentation generation problem. Replace <pre> with <code>. Patch from James Littlejohn. * * Revision 1.6 2004/09/08 13:56:24 peiyongz * Apache License Version 2.0 * * Revision 1.5 2004/02/15 19:37:16 amassari * Removed cause for warnings in VC 7.1 * * Revision 1.4 2004/02/13 14:28:30 cargilld * Fix for bug 26900 (remove virtual on destructor) * * Revision 1.3 2004/01/29 11:48:47 cargilld * Code cleanup changes to get rid of various compiler diagnostic messages. * * Revision 1.2 2003/11/25 18:16:38 knoaman * Documentation update. Thanks to David Cargill. * * Revision 1.1 2003/10/30 21:37:32 knoaman * Enhanced Entity Resolver Support. Thanks to David Cargill. * * * Revision 1.1 1999/11/09 01:07:44 twl * Initial checkin * */ #ifndef XMLRESOURCEIDENTIFIER_HPP #define XMLRESOURCEIDENTIFIER_HPP XERCES_CPP_NAMESPACE_BEGIN /** * <p>This class is used along with XMLEntityResolver to resolve entities. * Instead of passing publicId and systemId on the resolveEntity call, * as is done with the SAX entity resolver, an object of type XMLResourceIdentifier * is passed. By calling the getResourceIdentifierType() method the user can * determine which data members are available for inspection:</p> * * <table border='1'> * <tr> * <td>ResourceIdentifierType</td> * <td>Available Data Members</td> * </tr> * <tr> * <td>SchemaGrammar</td> * <td>schemaLocation, nameSpace & baseURI (current document)</td> * </tr> * <tr> * <td>SchemaImport</td> * <td>schemaLocation, nameSpace & baseURI (current document)</td> * </tr> * <tr> * <td>SchemaInclude</td> * <td>schemaLocation & baseURI (current document)</td> * </tr> * <tr> * <td>SchemaRedefine</td> * <td>schemaLocation & baseURI (current document)</td> * </tr> * <tr> * <td>ExternalEntity</td> * <td>systemId, publicId & baseURI (some items may be NULL)</td> * </tr> * </table> * * <p>The following resolver would provide the application * with a special character stream for the entity with the system * identifier "http://www.myhost.com/today":</p> * *<code> * #include <xercesc/util/XMLEntityResolver.hpp><br> * #include <xercesc/sax/InputSource.hpp><br> *<br> *&nbsp;class MyResolver : public XMLEntityResolver {<br> *&nbsp;&nbsp;public:<br> *&nbsp;&nbsp;&nbsp;InputSource resolveEntity (XMLResourceIdentifier* xmlri);<br> *&nbsp;&nbsp;&nbsp;...<br> *&nbsp;&nbsp;};<br> *<br> *&nbsp;&nbsp;MyResolver::resolveEntity(XMLResourceIdentifier* xmlri) {<br> *&nbsp;&nbsp;&nbsp;switch(xmlri->getResourceIdentifierType()) {<br> *&nbsp;&nbsp;&nbsp;&nbsp;case XMLResourceIdentifier::SystemId:<br> *&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if (XMLString::compareString(xmlri->getSystemId(), "http://www.myhost.com/today")) {<br> *&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;MyReader* reader = new MyReader();<br> *&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return new InputSource(reader);<br> *&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} else {<br> *&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return null;<br> *&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br> *&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;break;<br> *&nbsp;&nbsp;&nbsp;&nbsp;default:<br> *&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return null;<br> *&nbsp;&nbsp;&nbsp;}<br> *&nbsp;&nbsp;}</code> * * @see SAXParser#setXMLEntityResolver * @see InputSource#InputSource */ class XMLUTIL_EXPORT XMLResourceIdentifier { public: /** @name Public Contants */ //@{ enum ResourceIdentifierType { SchemaGrammar = 0, SchemaImport, SchemaInclude, SchemaRedefine , ExternalEntity, UnKnown = 255 }; //@} /** @name Constructors and Destructor */ //@{ /** Constructor */ XMLResourceIdentifier(const ResourceIdentifierType resourceIdentitiferType , const XMLCh* const systemId , const XMLCh* const nameSpace = 0 , const XMLCh* const publicId = 0 , const XMLCh* const baseURI = 0); /** Destructor */ ~XMLResourceIdentifier() { } //@} // ----------------------------------------------------------------------- // Getter methods // ----------------------------------------------------------------------- /** @name Public Methods */ //@{ ResourceIdentifierType getResourceIdentifierType() const; const XMLCh* getPublicId() const; const XMLCh* getSystemId() const; const XMLCh* getSchemaLocation() const; const XMLCh* getBaseURI() const; const XMLCh* getNameSpace() const; //@} private : const ResourceIdentifierType fResourceIdentifierType; const XMLCh* fPublicId; const XMLCh* fSystemId; const XMLCh* fBaseURI; const XMLCh* fNameSpace; /* Unimplemented constructors and operators */ /* Copy constructor */ XMLResourceIdentifier(const XMLResourceIdentifier&); /* Assignment operator */ XMLResourceIdentifier& operator=(const XMLResourceIdentifier&); }; inline XMLResourceIdentifier::ResourceIdentifierType XMLResourceIdentifier::getResourceIdentifierType() const { return fResourceIdentifierType; } inline const XMLCh* XMLResourceIdentifier::getPublicId() const { return fPublicId; } inline const XMLCh* XMLResourceIdentifier::getSystemId() const { return fSystemId; } inline const XMLCh* XMLResourceIdentifier::getSchemaLocation() const { return fSystemId; } inline const XMLCh* XMLResourceIdentifier::getBaseURI() const { return fBaseURI; } inline const XMLCh* XMLResourceIdentifier::getNameSpace() const { return fNameSpace; } inline XMLResourceIdentifier::XMLResourceIdentifier(const ResourceIdentifierType resourceIdentifierType , const XMLCh* const systemId , const XMLCh* const nameSpace , const XMLCh* const publicId , const XMLCh* const baseURI ) : fResourceIdentifierType(resourceIdentifierType) , fSystemId(systemId) , fNameSpace(nameSpace) , fPublicId(publicId) , fBaseURI(baseURI) { } XERCES_CPP_NAMESPACE_END #endif <|endoftext|>
<commit_before>/* Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved. 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. */ // Simple test for memset. // Also serves as a template for other tests. /* HIT_START * BUILD: %t %s ../../test_common.cpp * TEST: %t * HIT_END */ #include "hip/hip_runtime.h" #include "test_common.h" bool testhipMemset3D(int memsetval,int p_gpuDevice) { size_t numH = 256; size_t numW = 256; size_t depth = 10; size_t width = numW * sizeof(char); size_t sizeElements = width * numH * depth; size_t elements = numW* numH* depth; printf ("testhipMemset3D memsetval=%2x device=%d\n", memsetval, p_gpuDevice); char *A_h; bool testResult = true; hipExtent extent = make_hipExtent(width, numH, depth); hipPitchedPtr devPitchedPtr; HIPCHECK(hipMalloc3D(&devPitchedPtr, extent)); A_h = (char*)malloc(sizeElements); HIPASSERT(A_h != NULL); for (size_t i=0; i<elements; i++) { A_h[i] = 1; } HIPCHECK ( hipMemset3D( devPitchedPtr, memsetval, extent) ); hipMemcpy3DParms myparms = {0}; myparms.srcPos = make_hipPos(0,0,0); myparms.dstPos = make_hipPos(0,0,0); myparms.dstPtr = make_hipPitchedPtr(A_h, width , numW, numH); myparms.srcPtr = devPitchedPtr; myparms.extent = extent; #ifdef __HIP_PLATFORM_NVCC__ myparms.kind = hipMemcpyKindToCudaMemcpyKind(hipMemcpyDeviceToHost); #else myparms.kind = hipMemcpyDeviceToHost; #endif HIPCHECK(hipMemcpy3D(&myparms)); for (int i=0; i<elements; i++) { if (A_h[i] != memsetval) { testResult = false; printf("mismatch at index:%d computed:%02x, memsetval:%02x\n", i, (int)A_h[i], (int)memsetval); break; } } HIPCHECK(hipFree(devPitchedPtr.ptr)); free(A_h); return testResult; } int main(int argc, char *argv[]) { HipTest::parseStandardArguments(argc, argv, true); bool testResult = false; HIPCHECK(hipSetDevice(p_gpuDevice)); testResult = testhipMemset3D(memsetval, p_gpuDevice); if (testResult) { passed(); } else { exit(EXIT_FAILURE); } } <commit_msg>Add async subtest to hipMemSet3D<commit_after>/* Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved. 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. */ // Simple test for memset. // Also serves as a template for other tests. /* HIT_START * BUILD: %t %s ../../test_common.cpp * TEST: %t * HIT_END */ #include "hip/hip_runtime.h" #include "test_common.h" bool testhipMemset3D(int memsetval,int p_gpuDevice) { size_t numH = 256; size_t numW = 256; size_t depth = 10; size_t width = numW * sizeof(char); size_t sizeElements = width * numH * depth; size_t elements = numW* numH* depth; printf ("testhipMemset3D memsetval=%2x device=%d\n", memsetval, p_gpuDevice); char *A_h; bool testResult = true; hipExtent extent = make_hipExtent(width, numH, depth); hipPitchedPtr devPitchedPtr; HIPCHECK(hipMalloc3D(&devPitchedPtr, extent)); A_h = (char*)malloc(sizeElements); HIPASSERT(A_h != NULL); for (size_t i=0; i<elements; i++) { A_h[i] = 1; } HIPCHECK ( hipMemset3D( devPitchedPtr, memsetval, extent) ); hipMemcpy3DParms myparms = {0}; myparms.srcPos = make_hipPos(0,0,0); myparms.dstPos = make_hipPos(0,0,0); myparms.dstPtr = make_hipPitchedPtr(A_h, width , numW, numH); myparms.srcPtr = devPitchedPtr; myparms.extent = extent; #ifdef __HIP_PLATFORM_NVCC__ myparms.kind = hipMemcpyKindToCudaMemcpyKind(hipMemcpyDeviceToHost); #else myparms.kind = hipMemcpyDeviceToHost; #endif HIPCHECK(hipMemcpy3D(&myparms)); for (int i=0; i<elements; i++) { if (A_h[i] != memsetval) { testResult = false; printf("mismatch at index:%d computed:%02x, memsetval:%02x\n", i, (int)A_h[i], (int)memsetval); break; } } HIPCHECK(hipFree(devPitchedPtr.ptr)); free(A_h); return testResult; } bool testhipMemset3DAsync(int memsetval,int p_gpuDevice) { size_t numH = 256; size_t numW = 256; size_t depth = 10; size_t width = numW * sizeof(char); size_t sizeElements = width * numH * depth; size_t elements = numW* numH* depth; printf ("testhipMemset3D memsetval=%2x device=%d\n", memsetval, p_gpuDevice); char *A_h; bool testResult = true; hipExtent extent = make_hipExtent(width, numH, depth); hipPitchedPtr devPitchedPtr; HIPCHECK(hipMalloc3D(&devPitchedPtr, extent)); A_h = (char*)malloc(sizeElements); HIPASSERT(A_h != NULL); for (size_t i=0; i<elements; i++) { A_h[i] = 1; } hipStream_t stream; HIPCHECK(hipStreamCreate(&stream)); HIPCHECK ( hipMemset3DAsync( devPitchedPtr, memsetval, extent, stream) ); hipMemcpy3DParms myparms = {0}; myparms.srcPos = make_hipPos(0,0,0); myparms.dstPos = make_hipPos(0,0,0); myparms.dstPtr = make_hipPitchedPtr(A_h, width , numW, numH); myparms.srcPtr = devPitchedPtr; myparms.extent = extent; #ifdef __HIP_PLATFORM_NVCC__ myparms.kind = hipMemcpyKindToCudaMemcpyKind(hipMemcpyDeviceToHost); #else myparms.kind = hipMemcpyDeviceToHost; #endif HIPCHECK(hipMemcpy3D(&myparms)); for (int i=0; i<elements; i++) { if (A_h[i] != memsetval) { testResult = false; printf("mismatch at index:%d computed:%02x, memsetval:%02x\n", i, (int)A_h[i], (int)memsetval); break; } } HIPCHECK(hipFree(devPitchedPtr.ptr)); free(A_h); return testResult; } int main(int argc, char *argv[]) { HipTest::parseStandardArguments(argc, argv, true); HIPCHECK(hipSetDevice(p_gpuDevice)); bool testResult = false; testResult &= testhipMemset3D(memsetval, p_gpuDevice); testResult &= testhipMemset3DAsync(memsetval, p_gpuDevice); if (testResult) { passed(); } else { exit(EXIT_FAILURE); } } <|endoftext|>
<commit_before>/************************************************************************* * * 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: AppIconControl.cxx,v $ * $Revision: 1.10 $ * * 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. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_dbaccess.hxx" #ifndef DBAUI_APPICONCONTROL_HXX #include "AppIconControl.hxx" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _DBA_DBACCESS_HELPID_HRC_ #include "dbaccess_helpid.hrc" #endif #ifndef _DBAUI_MODULE_DBU_HXX_ #include "moduledbu.hxx" #endif #ifndef _DBU_APP_HRC_ #include "dbu_app.hrc" #endif #ifndef _IMAGE_HXX //autogen #include <vcl/image.hxx> #endif #ifndef _DBACCESS_UI_CALLBACKS_HXX_ #include "callbacks.hxx" #endif #ifndef DBAUI_APPELEMENTTYPE_HXX #include "AppElementType.hxx" #endif #include <memory> using namespace ::dbaui; //================================================================== // class OApplicationIconControl DBG_NAME(OApplicationIconControl) //================================================================== OApplicationIconControl::OApplicationIconControl(Window* _pParent) : SvtIconChoiceCtrl(_pParent,WB_ICON | WB_NOCOLUMNHEADER | WB_HIGHLIGHTFRAME | /*!WB_NOSELECTION |*/ WB_TABSTOP | WB_CLIPCHILDREN | WB_NOVSCROLL | WB_SMART_ARRANGE | WB_NOHSCROLL | WB_CENTER) ,DropTargetHelper(this) ,m_pActionListener(NULL) { DBG_CTOR(OApplicationIconControl,NULL); typedef ::std::pair< USHORT,USHORT> TUSHORTPair; typedef ::std::pair< ElementType,TUSHORTPair> TUSHORT2Pair; typedef ::std::pair< String,TUSHORT2Pair> TPair; static const TPair pTypes[] = { TPair(String(ModuleRes(RID_STR_TABLES_CONTAINER)),TUSHORT2Pair(E_TABLE,TUSHORTPair(IMG_TABLEFOLDER_TREE_L,IMG_TABLEFOLDER_TREE_LHC) )) , TPair(String(ModuleRes(RID_STR_QUERIES_CONTAINER)),TUSHORT2Pair(E_QUERY,TUSHORTPair(IMG_QUERYFOLDER_TREE_L,IMG_QUERYFOLDER_TREE_LHC)) ) , TPair(String(ModuleRes(RID_STR_FORMS_CONTAINER)),TUSHORT2Pair(E_FORM,TUSHORTPair(IMG_FORMFOLDER_TREE_L,IMG_FORMFOLDER_TREE_LHC)) ) , TPair(String(ModuleRes(RID_STR_REPORTS_CONTAINER)),TUSHORT2Pair(E_REPORT,TUSHORTPair(IMG_REPORTFOLDER_TREE_L,IMG_REPORTFOLDER_TREE_LHC)) ) }; for (size_t i=0; i < sizeof(pTypes)/sizeof(pTypes[0]); ++i) { SvxIconChoiceCtrlEntry* pEntry = InsertEntry(pTypes[i].first,Image(ModuleRes(pTypes[i].second.second.first)),Image(ModuleRes(pTypes[i].second.second.second))); if ( pEntry ) pEntry->SetUserData(new ElementType(pTypes[i].second.first)); } SetChoiceWithCursor( TRUE ); SetSelectionMode(SINGLE_SELECTION); } // ----------------------------------------------------------------------------- OApplicationIconControl::~OApplicationIconControl() { ULONG nCount = GetEntryCount(); for ( ULONG i = 0; i < nCount; ++i ) { SvxIconChoiceCtrlEntry* pEntry = GetEntry( i ); if ( pEntry ) { ::std::auto_ptr<ElementType> aType(static_cast<ElementType*>(pEntry->GetUserData())); pEntry->SetUserData(NULL); } } DBG_DTOR(OApplicationIconControl,NULL); } // ----------------------------------------------------------------------------- sal_Int8 OApplicationIconControl::AcceptDrop( const AcceptDropEvent& _rEvt ) { sal_Int8 nDropOption = DND_ACTION_NONE; if ( m_pActionListener ) { SvxIconChoiceCtrlEntry* pEntry = GetEntry(_rEvt.maPosPixel); if ( pEntry ) { SetCursor(pEntry); nDropOption = m_pActionListener->queryDrop( _rEvt, GetDataFlavorExVector() ); m_aMousePos = _rEvt.maPosPixel; } } return nDropOption; } // ----------------------------------------------------------------------------- sal_Int8 OApplicationIconControl::ExecuteDrop( const ExecuteDropEvent& _rEvt ) { if ( m_pActionListener ) return m_pActionListener->executeDrop( _rEvt ); return DND_ACTION_NONE; } <commit_msg>INTEGRATION: CWS dba30d (1.10.30); FILE MERGED 2008/06/01 21:02:33 fs 1.10.30.1: #i80943# more preparations for context menu interception, including some re-factoring<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: AppIconControl.cxx,v $ * $Revision: 1.11 $ * * 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. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_dbaccess.hxx" #ifndef DBAUI_APPICONCONTROL_HXX #include "AppIconControl.hxx" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _DBA_DBACCESS_HELPID_HRC_ #include "dbaccess_helpid.hrc" #endif #ifndef _DBAUI_MODULE_DBU_HXX_ #include "moduledbu.hxx" #endif #ifndef _DBU_APP_HRC_ #include "dbu_app.hrc" #endif #ifndef _IMAGE_HXX //autogen #include <vcl/image.hxx> #endif #ifndef _DBACCESS_UI_CALLBACKS_HXX_ #include "callbacks.hxx" #endif #ifndef DBAUI_APPELEMENTTYPE_HXX #include "AppElementType.hxx" #endif #include <memory> using namespace ::dbaui; //================================================================== // class OApplicationIconControl DBG_NAME(OApplicationIconControl) //================================================================== OApplicationIconControl::OApplicationIconControl(Window* _pParent) : SvtIconChoiceCtrl(_pParent,WB_ICON | WB_NOCOLUMNHEADER | WB_HIGHLIGHTFRAME | /*!WB_NOSELECTION |*/ WB_TABSTOP | WB_CLIPCHILDREN | WB_NOVSCROLL | WB_SMART_ARRANGE | WB_NOHSCROLL | WB_CENTER) ,DropTargetHelper(this) ,m_pActionListener(NULL) { DBG_CTOR(OApplicationIconControl,NULL); struct CategoryDescriptor { USHORT nLabelResId; ElementType eType; USHORT nImageResId; USHORT nImageResIdHC; } aCategories[] = { { RID_STR_TABLES_CONTAINER, E_TABLE, IMG_TABLEFOLDER_TREE_L, IMG_TABLEFOLDER_TREE_LHC }, { RID_STR_QUERIES_CONTAINER, E_QUERY, IMG_QUERYFOLDER_TREE_L, IMG_QUERYFOLDER_TREE_LHC }, { RID_STR_FORMS_CONTAINER, E_FORM, IMG_FORMFOLDER_TREE_L, IMG_FORMFOLDER_TREE_LHC }, { RID_STR_REPORTS_CONTAINER, E_REPORT, IMG_REPORTFOLDER_TREE_L,IMG_REPORTFOLDER_TREE_LHC } }; for ( size_t i=0; i < sizeof(aCategories)/sizeof(aCategories[0]); ++i) { SvxIconChoiceCtrlEntry* pEntry = InsertEntry( String( ModuleRes( aCategories[i].nLabelResId ) ), Image( ModuleRes( aCategories[i].nImageResId ) ), Image( ModuleRes( aCategories[i].nImageResIdHC ) ) ); if ( pEntry ) pEntry->SetUserData( new ElementType( aCategories[i].eType ) ); } SetChoiceWithCursor( TRUE ); SetSelectionMode(SINGLE_SELECTION); } // ----------------------------------------------------------------------------- OApplicationIconControl::~OApplicationIconControl() { ULONG nCount = GetEntryCount(); for ( ULONG i = 0; i < nCount; ++i ) { SvxIconChoiceCtrlEntry* pEntry = GetEntry( i ); if ( pEntry ) { ::std::auto_ptr<ElementType> aType(static_cast<ElementType*>(pEntry->GetUserData())); pEntry->SetUserData(NULL); } } DBG_DTOR(OApplicationIconControl,NULL); } // ----------------------------------------------------------------------------- sal_Int8 OApplicationIconControl::AcceptDrop( const AcceptDropEvent& _rEvt ) { sal_Int8 nDropOption = DND_ACTION_NONE; if ( m_pActionListener ) { SvxIconChoiceCtrlEntry* pEntry = GetEntry(_rEvt.maPosPixel); if ( pEntry ) { SetCursor(pEntry); nDropOption = m_pActionListener->queryDrop( _rEvt, GetDataFlavorExVector() ); m_aMousePos = _rEvt.maPosPixel; } } return nDropOption; } // ----------------------------------------------------------------------------- sal_Int8 OApplicationIconControl::ExecuteDrop( const ExecuteDropEvent& _rEvt ) { if ( m_pActionListener ) return m_pActionListener->executeDrop( _rEvt ); return DND_ACTION_NONE; } <|endoftext|>
<commit_before>/** Test harness for dealing with the most common domain names. 10535 http://swbplus.bsz-bw.de Done! 4774 http://digitool.hbz-nrw.de:1801 Done! 2977 http://www.gbv.de PDF's 1070 http://bvbr.bib-bvb.de:8991 Done! 975 http://deposit.d-nb.de HTML 772 http://d-nb.info PDF's (Images => Need to OCR this?) 520 http://www.ulb.tu-darmstadt.de (Frau Gwinner arbeitet daran?) 236 http://media.obvsg.at HTML 167 http://www.loc.gov 133 http://deposit.ddb.de 127 http://www.bibliothek.uni-regensburg.de 57 http://nbn-resolving.de 43 http://www.verlagdrkovac.de 35 http://search.ebscohost.com 25 http://idb.ub.uni-tuebingen.de 22 http://link.springer.com 18 http://heinonline.org 15 http://www.waxmann.com 13 https://www.destatis.de 10 http://www.tandfonline.com 10 http://dx.doi.org 9 http://tocs.ub.uni-mainz.de 8 http://www.onlinelibrary.wiley.com 8 http://bvbm1.bib-bvb.de 6 http://www.wvberlin.de 6 http://www.jstor.org 6 http://www.emeraldinsight.com 6 http://www.destatis.de 5 http://www.univerlag.uni-goettingen.de 5 http://www.sciencedirect.com 5 http://www.netread.com 5 http://www.gesis.org 5 http://content.ub.hu-berlin.de */ #include <iostream> #include <memory> #include <stdexcept> #include <vector> #include <cstdio> #include <cstdlib> #include <kchashdb.h> #include <strings.h> #include "Downloader.h" #include "MediaTypeUtil.h" #include "RegexMatcher.h" #include "StringUtil.h" #include "TextUtil.h" #include "util.h" void Usage() { std::cerr << "Usage: " << progname << " url output_or_db_filename [db_key]\n"; std::exit(EXIT_FAILURE); } class MatcherAndStats { std::unique_ptr<RegexMatcher> matcher_; unsigned match_count_; public: explicit MatcherAndStats(const std::string &pattern); bool matched(const std::string &url); /** \brief Returns how often matched() was called and it returned true. */ unsigned getMatchCount() const { return match_count_; } }; MatcherAndStats::MatcherAndStats(const std::string &pattern) { std::string err_msg; matcher_.reset(RegexMatcher::RegexMatcherFactory(pattern, &err_msg)); if (not matcher_) { std::cerr << progname << ": pattern failed to compile \"" << pattern << "\"!\n"; std::exit(EXIT_FAILURE); } } bool MatcherAndStats::matched(const std::string &url) { std::string err_msg; if (matcher_->matched(url, &err_msg)) { if (not err_msg.empty()) { std::cerr << progname << ": an error occurred while trying to match \"" << url << "\" with \"" << matcher_->getPattern() << "\"! (" << err_msg << ")\n"; std::exit(EXIT_FAILURE); } ++match_count_; return true; } return false; } bool WriteString(const std::string &contents, const std::string &output_filename) { FILE *output = std::fopen(output_filename.c_str(), "wb"); if (output == NULL) return false; if (std::fwrite(contents.data(), 1, contents.size(), output) != contents.size()) return false; std::fclose(output); return true; } // Here "word" simply means a sequence of characters not containing a space. std::string GetLastWordAfterSpace(const std::string &text) { const size_t last_space_pos(text.rfind(' ')); if (last_space_pos == std::string::npos) return ""; const std::string last_word(text.substr(last_space_pos + 1)); return last_word; } int Output(const std::string &output_or_db_filename, const std::string &db_key, const std::string &document) { if (not db_key.empty()) { const std::string content_type( "Content-type: " + MediaTypeUtil::GetMediaType(document, /* auto_simplify = */ false) + "\r\n\r\n"); kyotocabinet::HashDB db; db.open(output_or_db_filename, kyotocabinet::HashDB::OWRITER | kyotocabinet::HashDB::OCREATE | kyotocabinet::HashDB::OTRUNCATE); db.add(db_key, content_type + document); return 0; } else return WriteString(document, output_or_db_filename) ? 0 : -1; } int SmartDownload(std::string url, const std::string &output_or_db_filename, const std::string &db_key, MatcherAndStats * const bsz_matcher, MatcherAndStats * const idb_matcher, MatcherAndStats * const bvbr_matcher, MatcherAndStats * const bsz21_matcher) { const unsigned TIMEOUT_IN_SECS(5); // Don't wait any longer than this. if (StringUtil::IsProperSuffixOfIgnoreCase(".pdf", url) or StringUtil::IsProperSuffixOfIgnoreCase(".jpg", url) or StringUtil::IsProperSuffixOfIgnoreCase(".jpeg", url) or StringUtil::IsProperSuffixOfIgnoreCase(".txt", url)) ; // Do nothing! else if (StringUtil::IsPrefixOfIgnoreCase("http://www.bsz-bw.de/cgi-bin/ekz.cgi?", url)) { std::string html_document; int retcode; if ((retcode = Download(url, TIMEOUT_IN_SECS, &html_document)) != 0) return retcode; html_document = StringUtil::UTF8ToISO8859_15(html_document); std::string plain_text(TextUtil::ExtractText(html_document)); plain_text = StringUtil::ISO8859_15ToUTF8(plain_text); const size_t start_pos(plain_text.find("zugehörige Werke:")); if (start_pos != std::string::npos) plain_text = plain_text.substr(0, start_pos); return Output(output_or_db_filename, db_key, plain_text); } else if (StringUtil::StartsWith(url, "http://digitool.hbz-nrw.de:1801", /* ignore_case = */ true)) { const size_t pid_pos(url.rfind("pid=")); if (pid_pos == std::string::npos) return -1; const std::string pid(url.substr(pid_pos + 4)); url = "http://digitool.hbz-nrw.de:1801/webclient/DeliveryManager?pid=" + pid; std::string plain_text; int retcode; if ((retcode = Download(url, TIMEOUT_IN_SECS, &plain_text)) != 0) return retcode; std::vector<std::string> lines; StringUtil::SplitThenTrimWhite(plain_text, '\n', &lines); std::string cleaned_up_text; cleaned_up_text.reserve(plain_text.size()); for (const auto &line : lines) { if (unlikely(line == "ocr-text:")) continue; const std::string last_word(GetLastWordAfterSpace(line)); if (unlikely(last_word.empty())) { cleaned_up_text += line; } else { if (likely(TextUtil::IsUnsignedInteger(last_word) or TextUtil::IsRomanNumeral(last_word))) cleaned_up_text += line.substr(0, line.size() - last_word.size() - 1); else cleaned_up_text += line; } cleaned_up_text += '\n'; } return Output(output_or_db_filename, db_key, cleaned_up_text); } else if (bsz_matcher->matched(url)) url = url.substr(0, url.size() - 3) + "pdf"; else if (idb_matcher->matched(url)) { const size_t last_slash_pos(url.find_last_of('/')); url = "http://idb.ub.uni-tuebingen.de/cgi-bin/digi-downloadPdf.fcgi?projectname=" + url.substr(last_slash_pos + 1); } else if (bvbr_matcher->matched(url)) { std::string html; const int retcode(Download(url, TIMEOUT_IN_SECS, &html)); if (retcode != 0) return retcode; const std::string start_string("<body onload=window.location=\""); size_t start_pos(html.find(start_string)); if (start_pos == std::string::npos) return -2; start_pos += start_string.size(); const size_t end_pos(html.find('"', start_pos + 1)); if (end_pos == std::string::npos) return -3; url = "http://bvbr.bib-bvb.de:8991" + html.substr(start_pos, end_pos - start_pos); } else if (bsz21_matcher->matched(url)) { std::string html; const int retcode = Download(url, TIMEOUT_IN_SECS, &html); if (retcode != 0) return retcode; const std::string start_string("<meta content=\"https://publikationen.uni-tuebingen.de/xmlui/bitstream/"); size_t start_pos(html.find(start_string)); if (start_pos == std::string::npos) return -2; start_pos += start_string.size() - 55; const size_t end_pos(html.find('"', start_pos + 1)); if (end_pos == std::string::npos) return -3; url = html.substr(start_pos, end_pos - start_pos); } std::string document; if (Download(url, TIMEOUT_IN_SECS, &document) != 0) return -1; return Output(output_or_db_filename, db_key, document); } int main(int argc, char *argv[]) { progname = argv[0]; if (argc != 3 and argc != 4) Usage(); try { MatcherAndStats bsz_matcher("http://swbplus.bsz-bw.de/bsz.*\\.htm"); MatcherAndStats idb_matcher("http://idb.ub.uni-tuebingen.de/diglit/.+"); MatcherAndStats bvbr_matcher("http://bvbr.bib-bvb.de:8991/.+"); MatcherAndStats bsz21_matcher("http://nbn-resolving.de/urn:nbn:de:bsz:21.+"); if (SmartDownload(argv[1], argv[2], argc == 3 ? "" : argv[3], &bsz_matcher, &idb_matcher, &bvbr_matcher, &bsz21_matcher) != 0) { std::cerr << progname << ": Download failed!\n"; std::exit(EXIT_FAILURE); } } catch (const std::exception &e) { Error("Caught exception: " + std::string(e.what())); } } <commit_msg>Removed redundant WriteString() implementation.<commit_after>/** Test harness for dealing with the most common domain names. 10535 http://swbplus.bsz-bw.de Done! 4774 http://digitool.hbz-nrw.de:1801 Done! 2977 http://www.gbv.de PDF's 1070 http://bvbr.bib-bvb.de:8991 Done! 975 http://deposit.d-nb.de HTML 772 http://d-nb.info PDF's (Images => Need to OCR this?) 520 http://www.ulb.tu-darmstadt.de (Frau Gwinner arbeitet daran?) 236 http://media.obvsg.at HTML 167 http://www.loc.gov 133 http://deposit.ddb.de 127 http://www.bibliothek.uni-regensburg.de 57 http://nbn-resolving.de 43 http://www.verlagdrkovac.de 35 http://search.ebscohost.com 25 http://idb.ub.uni-tuebingen.de 22 http://link.springer.com 18 http://heinonline.org 15 http://www.waxmann.com 13 https://www.destatis.de 10 http://www.tandfonline.com 10 http://dx.doi.org 9 http://tocs.ub.uni-mainz.de 8 http://www.onlinelibrary.wiley.com 8 http://bvbm1.bib-bvb.de 6 http://www.wvberlin.de 6 http://www.jstor.org 6 http://www.emeraldinsight.com 6 http://www.destatis.de 5 http://www.univerlag.uni-goettingen.de 5 http://www.sciencedirect.com 5 http://www.netread.com 5 http://www.gesis.org 5 http://content.ub.hu-berlin.de */ #include <iostream> #include <memory> #include <stdexcept> #include <vector> #include <cstdio> #include <cstdlib> #include <kchashdb.h> #include <strings.h> #include "Downloader.h" #include "FileUtil.h" #include "MediaTypeUtil.h" #include "RegexMatcher.h" #include "StringUtil.h" #include "TextUtil.h" #include "util.h" void Usage() { std::cerr << "Usage: " << progname << " url output_or_db_filename [db_key]\n"; std::exit(EXIT_FAILURE); } class MatcherAndStats { std::unique_ptr<RegexMatcher> matcher_; unsigned match_count_; public: explicit MatcherAndStats(const std::string &pattern); bool matched(const std::string &url); /** \brief Returns how often matched() was called and it returned true. */ unsigned getMatchCount() const { return match_count_; } }; MatcherAndStats::MatcherAndStats(const std::string &pattern) { std::string err_msg; matcher_.reset(RegexMatcher::RegexMatcherFactory(pattern, &err_msg)); if (not matcher_) { std::cerr << progname << ": pattern failed to compile \"" << pattern << "\"!\n"; std::exit(EXIT_FAILURE); } } bool MatcherAndStats::matched(const std::string &url) { std::string err_msg; if (matcher_->matched(url, &err_msg)) { if (not err_msg.empty()) { std::cerr << progname << ": an error occurred while trying to match \"" << url << "\" with \"" << matcher_->getPattern() << "\"! (" << err_msg << ")\n"; std::exit(EXIT_FAILURE); } ++match_count_; return true; } return false; } // Here "word" simply means a sequence of characters not containing a space. std::string GetLastWordAfterSpace(const std::string &text) { const size_t last_space_pos(text.rfind(' ')); if (last_space_pos == std::string::npos) return ""; const std::string last_word(text.substr(last_space_pos + 1)); return last_word; } int Output(const std::string &output_or_db_filename, const std::string &db_key, const std::string &document) { if (not db_key.empty()) { const std::string content_type( "Content-type: " + MediaTypeUtil::GetMediaType(document, /* auto_simplify = */ false) + "\r\n\r\n"); kyotocabinet::HashDB db; db.open(output_or_db_filename, kyotocabinet::HashDB::OWRITER | kyotocabinet::HashDB::OCREATE | kyotocabinet::HashDB::OTRUNCATE); db.add(db_key, content_type + document); return 0; } else return WriteString(document, output_or_db_filename) ? 0 : -1; } int SmartDownload(std::string url, const std::string &output_or_db_filename, const std::string &db_key, MatcherAndStats * const bsz_matcher, MatcherAndStats * const idb_matcher, MatcherAndStats * const bvbr_matcher, MatcherAndStats * const bsz21_matcher) { const unsigned TIMEOUT_IN_SECS(5); // Don't wait any longer than this. if (StringUtil::IsProperSuffixOfIgnoreCase(".pdf", url) or StringUtil::IsProperSuffixOfIgnoreCase(".jpg", url) or StringUtil::IsProperSuffixOfIgnoreCase(".jpeg", url) or StringUtil::IsProperSuffixOfIgnoreCase(".txt", url)) ; // Do nothing! else if (StringUtil::IsPrefixOfIgnoreCase("http://www.bsz-bw.de/cgi-bin/ekz.cgi?", url)) { std::string html_document; int retcode; if ((retcode = Download(url, TIMEOUT_IN_SECS, &html_document)) != 0) return retcode; html_document = StringUtil::UTF8ToISO8859_15(html_document); std::string plain_text(TextUtil::ExtractText(html_document)); plain_text = StringUtil::ISO8859_15ToUTF8(plain_text); const size_t start_pos(plain_text.find("zugehörige Werke:")); if (start_pos != std::string::npos) plain_text = plain_text.substr(0, start_pos); return Output(output_or_db_filename, db_key, plain_text); } else if (StringUtil::StartsWith(url, "http://digitool.hbz-nrw.de:1801", /* ignore_case = */ true)) { const size_t pid_pos(url.rfind("pid=")); if (pid_pos == std::string::npos) return -1; const std::string pid(url.substr(pid_pos + 4)); url = "http://digitool.hbz-nrw.de:1801/webclient/DeliveryManager?pid=" + pid; std::string plain_text; int retcode; if ((retcode = Download(url, TIMEOUT_IN_SECS, &plain_text)) != 0) return retcode; std::vector<std::string> lines; StringUtil::SplitThenTrimWhite(plain_text, '\n', &lines); std::string cleaned_up_text; cleaned_up_text.reserve(plain_text.size()); for (const auto &line : lines) { if (unlikely(line == "ocr-text:")) continue; const std::string last_word(GetLastWordAfterSpace(line)); if (unlikely(last_word.empty())) { cleaned_up_text += line; } else { if (likely(TextUtil::IsUnsignedInteger(last_word) or TextUtil::IsRomanNumeral(last_word))) cleaned_up_text += line.substr(0, line.size() - last_word.size() - 1); else cleaned_up_text += line; } cleaned_up_text += '\n'; } return Output(output_or_db_filename, db_key, cleaned_up_text); } else if (bsz_matcher->matched(url)) url = url.substr(0, url.size() - 3) + "pdf"; else if (idb_matcher->matched(url)) { const size_t last_slash_pos(url.find_last_of('/')); url = "http://idb.ub.uni-tuebingen.de/cgi-bin/digi-downloadPdf.fcgi?projectname=" + url.substr(last_slash_pos + 1); } else if (bvbr_matcher->matched(url)) { std::string html; const int retcode(Download(url, TIMEOUT_IN_SECS, &html)); if (retcode != 0) return retcode; const std::string start_string("<body onload=window.location=\""); size_t start_pos(html.find(start_string)); if (start_pos == std::string::npos) return -2; start_pos += start_string.size(); const size_t end_pos(html.find('"', start_pos + 1)); if (end_pos == std::string::npos) return -3; url = "http://bvbr.bib-bvb.de:8991" + html.substr(start_pos, end_pos - start_pos); } else if (bsz21_matcher->matched(url)) { std::string html; const int retcode = Download(url, TIMEOUT_IN_SECS, &html); if (retcode != 0) return retcode; const std::string start_string("<meta content=\"https://publikationen.uni-tuebingen.de/xmlui/bitstream/"); size_t start_pos(html.find(start_string)); if (start_pos == std::string::npos) return -2; start_pos += start_string.size() - 55; const size_t end_pos(html.find('"', start_pos + 1)); if (end_pos == std::string::npos) return -3; url = html.substr(start_pos, end_pos - start_pos); } std::string document; if (Download(url, TIMEOUT_IN_SECS, &document) != 0) return -1; return Output(output_or_db_filename, db_key, document); } int main(int argc, char *argv[]) { progname = argv[0]; if (argc != 3 and argc != 4) Usage(); try { MatcherAndStats bsz_matcher("http://swbplus.bsz-bw.de/bsz.*\\.htm"); MatcherAndStats idb_matcher("http://idb.ub.uni-tuebingen.de/diglit/.+"); MatcherAndStats bvbr_matcher("http://bvbr.bib-bvb.de:8991/.+"); MatcherAndStats bsz21_matcher("http://nbn-resolving.de/urn:nbn:de:bsz:21.+"); if (SmartDownload(argv[1], argv[2], argc == 3 ? "" : argv[3], &bsz_matcher, &idb_matcher, &bvbr_matcher, &bsz21_matcher) != 0) { std::cerr << progname << ": Download failed!\n"; std::exit(EXIT_FAILURE); } } catch (const std::exception &e) { Error("Caught exception: " + std::string(e.what())); } } <|endoftext|>
<commit_before>#ifndef STAN_MATH_PRIM_FUN_GENERALIZED_INVERSE_HPP #define STAN_MATH_PRIM_FUN_GENERALIZED_INVERSE_HPP #include <stan/math/prim/meta.hpp> #include <stan/math/prim/err.hpp> #include <stan/math/prim/fun/Eigen.hpp> #include <stan/math/prim/fun/to_ref.hpp> #include <stan/math/prim/fun/cholesky_decompose.hpp> #include <stan/math/prim/fun/transpose.hpp> #include <stan/math/prim/fun/tcrossprod.hpp> #include <stan/math/prim/fun/crossprod.hpp> #include <stan/math/prim/fun/inverse_spd.hpp> #include <stan/math/prim/fun/mdivide_left_spd.hpp> #include <stan/math/prim/fun/mdivide_right_spd.hpp> #include <stan/math/prim/fun/inverse.hpp> namespace stan { namespace math { /** * Returns the Moore-Penrose generalized inverse of the specified matrix. * * The method is based on the Cholesky computation of the transform as specified * in * * <ul><li> Courrieu, Pierre. 2008. Fast Computation of Moore-Penrose Inverse Matrices. * <i>arXiv</i> <b>0804.4809</b> </li></ul> * * @tparam EigMat type of the matrix (must be derived from `Eigen::MatrixBase`) * * @param G specified matrix * @return Generalized inverse of the matrix (an empty matrix if the specified * matrix has size zero). * @note Because the method inverts a SPD matrix internally that interal matrix may result in small numerical issues that result in a non-SPD error. There are two * <code>generalized_inverse</code> functions, one that uses one input matrix (this one) * and another that works with an input matrix and a small jitter to the diagonal of the internal SPD * matrix. */ template <typename EigMat, require_eigen_t<EigMat>* = nullptr, require_not_vt_var<EigMat>* = nullptr> inline Eigen::Matrix<value_type_t<EigMat>, EigMat::ColsAtCompileTime, EigMat::RowsAtCompileTime> generalized_inverse(const EigMat& G) { using value_t = value_type_t<EigMat>; if (G.size() == 0) return {}; const auto n = G.rows(); const auto m = G.cols(); if (G.rows() == G.cols()) return inverse(G); const auto& G_ref = to_ref(G); if (n < m) { return transpose(mdivide_left_spd(tcrossprod(G_ref), G_ref)); } else { return transpose(mdivide_right_spd(G_ref, crossprod(G_ref))); } } /** * Returns the Moore-Penrose generalized inverse of the specified matrix. * * The method is based on the Cholesky computation of the transform as specified in * * <ul><li> Courrieu, Pierre. 2008. Fast Computation of Moore-Penrose Inverse Matrices. * <i>arXiv</i> <b>0804.4809</b> </li></ul> * * @tparam EigMat type of the matrix (must be derived from `Eigen::MatrixBase`) * * @param G specified matrix * @param a real constant * @return Generalized inverse of the matrix (an empty matrix if the specified * matrix has size zero). * @note Because the method inverts a SPD matrix internally that interal matrix may result in small numerical issues that result in a non-SPD error. There are two * <code>generalized_inverse</code> functions, one that uses one input matrix * and another (this one) that works with an input matrix and a small jitter to the diagonal of the internal SPD * matrix. */ template <typename EigMat, require_eigen_t<EigMat>* = nullptr, require_not_vt_var<EigMat>* = nullptr> inline Eigen::Matrix<value_type_t<EigMat>, EigMat::RowsAtCompileTime, EigMat::ColsAtCompileTime> generalized_inverse(const EigMat& G, const double a) { using value_t = value_type_t<EigMat>; if (G.size() == 0) return {}; const auto n = G.rows(); const auto m = G.cols(); if (G.rows() == G.cols()) return inverse(G); const auto& G_ref = to_ref(G); if (n < m) { Eigen::Matrix<value_t, Eigen::Dynamic, Eigen::Dynamic> A = tcrossprod(G_ref); A.diagonal().array() += a; return transpose(mdivide_left_spd(A, G_ref)); } else { Eigen::Matrix<value_t, Eigen::Dynamic, Eigen::Dynamic> A = crossprod(G_ref); A.diagonal().array() += a; return transpose(mdivide_right_spd(G_ref, A)); } } } // namespace math } // namespace stan #endif <commit_msg>small fix remove n, m using .rows()/.cols()<commit_after>#ifndef STAN_MATH_PRIM_FUN_GENERALIZED_INVERSE_HPP #define STAN_MATH_PRIM_FUN_GENERALIZED_INVERSE_HPP #include <stan/math/prim/meta.hpp> #include <stan/math/prim/err.hpp> #include <stan/math/prim/fun/Eigen.hpp> #include <stan/math/prim/fun/to_ref.hpp> #include <stan/math/prim/fun/cholesky_decompose.hpp> #include <stan/math/prim/fun/transpose.hpp> #include <stan/math/prim/fun/tcrossprod.hpp> #include <stan/math/prim/fun/crossprod.hpp> #include <stan/math/prim/fun/inverse_spd.hpp> #include <stan/math/prim/fun/mdivide_left_spd.hpp> #include <stan/math/prim/fun/mdivide_right_spd.hpp> #include <stan/math/prim/fun/inverse.hpp> namespace stan { namespace math { /** * Returns the Moore-Penrose generalized inverse of the specified matrix. * * The method is based on the Cholesky computation of the transform as specified * in * * <ul><li> Courrieu, Pierre. 2008. Fast Computation of Moore-Penrose Inverse Matrices. * <i>arXiv</i> <b>0804.4809</b> </li></ul> * * @tparam EigMat type of the matrix (must be derived from `Eigen::MatrixBase`) * * @param G specified matrix * @return Generalized inverse of the matrix (an empty matrix if the specified * matrix has size zero). * @note Because the method inverts a SPD matrix internally that interal matrix may result in small numerical issues that result in a non-SPD error. There are two * <code>generalized_inverse</code> functions, one that uses one input matrix (this one) * and another that works with an input matrix and a small jitter to the diagonal of the internal SPD * matrix. */ template <typename EigMat, require_eigen_t<EigMat>* = nullptr, require_not_vt_var<EigMat>* = nullptr> inline Eigen::Matrix<value_type_t<EigMat>, EigMat::ColsAtCompileTime, EigMat::RowsAtCompileTime> generalized_inverse(const EigMat& G) { using value_t = value_type_t<EigMat>; if (G.size() == 0) return {}; if (G.rows() == G.cols()) return inverse(G); const auto& G_ref = to_ref(G); if (G.rows() < G.cols()) { return transpose(mdivide_left_spd(tcrossprod(G_ref), G_ref)); } else { return transpose(mdivide_right_spd(G_ref, crossprod(G_ref))); } } /** * Returns the Moore-Penrose generalized inverse of the specified matrix. * * The method is based on the Cholesky computation of the transform as specified in * * <ul><li> Courrieu, Pierre. 2008. Fast Computation of Moore-Penrose Inverse Matrices. * <i>arXiv</i> <b>0804.4809</b> </li></ul> * * @tparam EigMat type of the matrix (must be derived from `Eigen::MatrixBase`) * * @param G specified matrix * @param a real constant * @return Generalized inverse of the matrix (an empty matrix if the specified * matrix has size zero). * @note Because the method inverts a SPD matrix internally that interal matrix may result in small numerical issues that result in a non-SPD error. There are two * <code>generalized_inverse</code> functions, one that uses one input matrix * and another (this one) that works with an input matrix and a small jitter to the diagonal of the internal SPD * matrix. */ template <typename EigMat, require_eigen_t<EigMat>* = nullptr, require_not_vt_var<EigMat>* = nullptr> inline Eigen::Matrix<value_type_t<EigMat>, EigMat::RowsAtCompileTime, EigMat::ColsAtCompileTime> generalized_inverse(const EigMat& G, const double a) { using value_t = value_type_t<EigMat>; if (G.size() == 0) return {}; if (G.rows() == G.cols()) return inverse(G); const auto& G_ref = to_ref(G); if (G.rows() < G.cols()) { Eigen::Matrix<value_t, Eigen::Dynamic, Eigen::Dynamic> A = tcrossprod(G_ref); A.diagonal().array() += a; return transpose(mdivide_left_spd(A, G_ref)); } else { Eigen::Matrix<value_t, Eigen::Dynamic, Eigen::Dynamic> A = crossprod(G_ref); A.diagonal().array() += a; return transpose(mdivide_right_spd(G_ref, A)); } } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>#ifndef STAN_MATH_PRIM_META_AS_ARRAY_OR_SCALAR_HPP #define STAN_MATH_PRIM_META_AS_ARRAY_OR_SCALAR_HPP #include <stan/math/prim/mat/fun/Eigen.hpp> #include <vector> namespace stan { namespace math { /** \ingroup type_trait * Returns specified input value. * * @tparam T Type of element. * @param v Specified value. * @return Same value. */ template <typename T> inline const T& as_array_or_scalar(const T& v) { return v; } /** \ingroup type_trait * Converts a matrix type to an array. * * @tparam T Type of scalar element. * @tparam R Row type of input matrix. * @tparam C Column type of input matrix. * @param v Specified matrix. * @return Matrix converted to an array. */ template <typename T, int R, int C> inline Eigen::ArrayWrapper<const Eigen::Matrix<T, R, C>> as_array_or_scalar( const Eigen::Matrix<T, R, C>& v) { return v.array(); } /** \ingroup type_trait * Converts a matrix type to an array. * * @tparam T Type of scalar element. * @tparam R Row type of input matrix. * @tparam C Column type of input matrix. * @param v Specified matrix. * @return Matrix converted to an array. */ template <typename T, int R, int C> inline Eigen::ArrayWrapper<const Eigen::Map<const Eigen::Matrix<T, R, C>>> as_array_or_scalar(const Eigen::Map<const Eigen::Matrix<T, R, C>>& v) { return v.array(); } /** \ingroup type_trait * Converts a std::vector type to an array. * * @tparam T Type of scalar element. * @param v Specified vector. * @return Matrix converted to an array. */ template <typename T> inline Eigen::Map<const Eigen::Array<T, Eigen::Dynamic, 1>> as_array_or_scalar( const std::vector<T>& v) { return Eigen::Map<const Eigen::Array<T, Eigen::Dynamic, 1>>(v.data(), v.size()); } } // namespace math } // namespace stan #endif <commit_msg>cleanup as_array_or_scalar<commit_after>#ifndef STAN_MATH_PRIM_META_AS_ARRAY_OR_SCALAR_HPP #define STAN_MATH_PRIM_META_AS_ARRAY_OR_SCALAR_HPP #include <stan/math/prim/mat/fun/Eigen.hpp> #include <vector> namespace stan { namespace math { /** \ingroup type_trait * Returns specified input value. * * @tparam T Type of element. * @param v Specified value. * @return Same value. */ template <typename T> inline const T& as_array_or_scalar(const T& v) { return v; } /** \ingroup type_trait * Converts a matrix type to an array. * * @tparam T Type of \c Eigen \c Matrix or expression * @param v Specified \c Eigen \c Matrix or expression. * @return Matrix converted to an array. */ template <typename T, typename = require_eigen_t<T>> inline auto as_array_or_scalar(const T& v) { return v.array(); } /** \ingroup type_trait * Converts a std::vector type to an array. * * @tparam T Type of scalar element. * @param v Specified vector. * @return Matrix converted to an array. */ template <typename T> inline Eigen::Map<const Eigen::Array<T, Eigen::Dynamic, 1>> as_array_or_scalar( const std::vector<T>& v) { return Eigen::Map<const Eigen::Array<T, Eigen::Dynamic, 1>>(v.data(), v.size()); } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include "chasky/common/strings.h" #include "chasky/core/common/register.h" #include "chasky/core/framework/graph.pb.h" #include "chasky/core/framework/function.h" #include "chasky/core/framework/node.h" #include "chasky/core/framework/graph.h" #include "chasky/core/framework/argument_def_builder.h" #include "chasky/core/framework/attr_value_util.h" namespace chasky { namespace test { using std::string; TEST(Edge, GenEdgeKey) { string node1 = "src"; string node2 = "trg"; string arg = "arg1"; string signature = "src:arg1->trg"; ASSERT_EQ(GenEdgeKey(node1, node2, arg), signature); string input = strings::Printf("%s:%s", node1.c_str(), arg.c_str()); ASSERT_EQ(GenEdgeKey(input, node2), signature); } REGISTER_FUNC_DEF( demo_func, FunctionDefBuilder() .Name("demo_func") .Input(NewArgumentDefBuilder().Name("src1").Finalize()) .Input(NewArgumentDefBuilder().Name("src2").Finalize()) .Output(NewArgumentDefBuilder().Name("output1").Finalize()) .Param(NewArgumentDefBuilder().Name("param1").Finalize()) .Attr(AttrDefBuilder().Name("attr1").Type("int32").Finalize()) .Finalize()); TEST(Node, Create) { auto sign = Function::Signature("demo_func", CH_FLOAT); NodeDef def; def.set_name("node1"); def.set_signature(sign); LOG(INFO) << "function_library:\n" << FunctionLibrary::Instance().DebugString(); LOG(INFO) << "function_def_library:\n" << FunctionDefLibrary::Instance().DebugString(); auto graph = Graph::Create(); auto node = Node::Create(def, graph.get()); ASSERT_TRUE(node != nullptr); } } // namespace test } // namespace chasky <commit_msg>add node_test.cc<commit_after>#include <gtest/gtest.h> #include "chasky/common/strings.h" #include "chasky/core/common/register.h" #include "chasky/core/framework/graph.pb.h" #include "chasky/core/framework/function.h" #include "chasky/core/framework/node.h" #include "chasky/core/framework/graph.h" #include "chasky/core/framework/argument_def_builder.h" #include "chasky/core/framework/attr_value_util.h" namespace chasky { namespace test { using std::string; TEST(Edge, GenEdgeKey) { string node1 = "src"; string node2 = "trg"; string arg = "arg1"; string signature = "src:arg1->trg"; ASSERT_EQ(GenEdgeKey(node1, node2, arg), signature); string input = strings::Printf("%s:%s", node1.c_str(), arg.c_str()); ASSERT_EQ(GenEdgeKey(input, node2), signature); } REGISTER_FUNC_DEF( demo_func, FunctionDefBuilder() .Name("demo_func") .Input(ArgumentDefBuilder().Name("src1").Type("float_mat").Finalize()) .Input(ArgumentDefBuilder().Name("src2").Type("float_mat").Finalize()) .Output( ArgumentDefBuilder().Name("output1").Type("float_mat").Finalize()) .Param(ArgumentDefBuilder().Name("param1").Type("float_mat").Finalize()) .Attr(AttrDefBuilder().Name("attr1").Type("int32").Finalize()) .Finalize()); TEST(Node, Create) { auto sign = Function::Signature("demo_func", CH_FLOAT); NodeDef def; def.set_name("node1"); def.set_signature(sign); LOG(INFO) << "function_library:\n" << FunctionLibrary::Instance().DebugString(); LOG(INFO) << "function_def_library:\n" << FunctionDefLibrary::Instance().DebugString(); auto graph = Graph::Create(); auto node = Node::Create(def, graph.get()); ASSERT_TRUE(node != nullptr); } } // namespace test } // namespace chasky <|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/browser_shutdown.h" #include <string> #include "app/resource_bundle.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/histogram.h" #include "base/path_service.h" #include "base/process_util.h" #include "base/string_util.h" #include "base/thread.h" #include "base/time.h" #include "base/waitable_event.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_thread.h" #include "chrome/browser/dom_ui/chrome_url_data_manager.h" #include "chrome/browser/first_run.h" #include "chrome/browser/jankometer.h" #include "chrome/browser/metrics/metrics_service.h" #include "chrome/browser/plugin_process_host.h" #include "chrome/browser/pref_service.h" #include "chrome/browser/renderer_host/render_process_host.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/renderer_host/render_widget_host.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "chrome/common/chrome_plugin_lib.h" #include "net/predictor_api.h" #if defined(OS_WIN) #include "chrome/browser/rlz/rlz.h" #endif using base::Time; using base::TimeDelta; namespace browser_shutdown { // Whether the browser is trying to quit (e.g., Quit chosen from menu). bool g_trying_to_quit = false; Time shutdown_started_; ShutdownType shutdown_type_ = NOT_VALID; int shutdown_num_processes_; int shutdown_num_processes_slow_; bool delete_resources_on_shutdown = true; const char kShutdownMsFile[] = "chrome_shutdown_ms.txt"; void RegisterPrefs(PrefService* local_state) { local_state->RegisterIntegerPref(prefs::kShutdownType, NOT_VALID); local_state->RegisterIntegerPref(prefs::kShutdownNumProcesses, 0); local_state->RegisterIntegerPref(prefs::kShutdownNumProcessesSlow, 0); } ShutdownType GetShutdownType() { return shutdown_type_; } void OnShutdownStarting(ShutdownType type) { if (shutdown_type_ != NOT_VALID) return; shutdown_type_ = type; // For now, we're only counting the number of renderer processes // since we can't safely count the number of plugin processes from this // thread, and we'd really like to avoid anything which might add further // delays to shutdown time. shutdown_started_ = Time::Now(); // Call FastShutdown on all of the RenderProcessHosts. This will be // a no-op in some cases, so we still need to go through the normal // shutdown path for the ones that didn't exit here. shutdown_num_processes_ = 0; shutdown_num_processes_slow_ = 0; for (RenderProcessHost::iterator i(RenderProcessHost::AllHostsIterator()); !i.IsAtEnd(); i.Advance()) { ++shutdown_num_processes_; if (!i.GetCurrentValue()->FastShutdownIfPossible()) ++shutdown_num_processes_slow_; } } FilePath GetShutdownMsPath() { FilePath shutdown_ms_file; PathService::Get(chrome::DIR_USER_DATA, &shutdown_ms_file); return shutdown_ms_file.AppendASCII(kShutdownMsFile); } void Shutdown() { // Unload plugins. This needs to happen on the IO thread. ChromeThread::PostTask( ChromeThread::IO, FROM_HERE, NewRunnableFunction(&ChromePluginLib::UnloadAllPlugins)); // WARNING: During logoff/shutdown (WM_ENDSESSION) we may not have enough // time to get here. If you have something that *must* happen on end session, // consider putting it in BrowserProcessImpl::EndSession. DCHECK(g_browser_process); // Notifies we are going away. g_browser_process->shutdown_event()->Signal(); PrefService* prefs = g_browser_process->local_state(); chrome_browser_net::SavePredictorStateForNextStartupAndTrim(prefs); MetricsService* metrics = g_browser_process->metrics_service(); if (metrics) { metrics->RecordCleanShutdown(); metrics->RecordCompletedSessionEnd(); } if (shutdown_type_ > NOT_VALID && shutdown_num_processes_ > 0) { // Record the shutdown info so that we can put it into a histogram at next // startup. prefs->SetInteger(prefs::kShutdownType, shutdown_type_); prefs->SetInteger(prefs::kShutdownNumProcesses, shutdown_num_processes_); prefs->SetInteger(prefs::kShutdownNumProcessesSlow, shutdown_num_processes_slow_); } // Check local state for the restart flag so we can restart the session below. bool restart_last_session = false; if (prefs->HasPrefPath(prefs::kRestartLastSessionOnShutdown)) { restart_last_session = prefs->GetBoolean(prefs::kRestartLastSessionOnShutdown); prefs->ClearPref(prefs::kRestartLastSessionOnShutdown); } prefs->SavePersistentPrefs(); #if defined(OS_WIN) // Cleanup any statics created by RLZ. Must be done before NotificationService // is destroyed. RLZTracker::CleanupRlz(); #endif // The jank'o'meter requires that the browser process has been destroyed // before calling UninstallJankometer(). delete g_browser_process; g_browser_process = NULL; // Uninstall Jank-O-Meter here after the IO thread is no longer running. UninstallJankometer(); if (delete_resources_on_shutdown) ResourceBundle::CleanupSharedInstance(); #if defined(OS_WIN) if (!Upgrade::IsBrowserAlreadyRunning() && shutdown_type_ != browser_shutdown::END_SESSION) { Upgrade::SwapNewChromeExeIfPresent(); } #endif if (restart_last_session) { #if !defined(OS_CHROMEOS) // Make sure to relaunch the browser with the same command line and add // Restore Last Session flag if session restore is not set. CommandLine command_line(*CommandLine::ForCurrentProcess()); if (!command_line.HasSwitch(switches::kRestoreLastSession)) command_line.AppendSwitch(switches::kRestoreLastSession); #if defined(OS_WIN) || defined(OS_LINUX) Upgrade::RelaunchChromeBrowser(command_line); #endif // defined(OS_WIN) || defined(OS_LINUX) #if defined(OS_MACOSX) command_line.AppendSwitch(switches::kActivateOnLaunch); base::LaunchApp(command_line, false, false, NULL); #endif // defined(OS_MACOSX) #else NOTIMPLEMENTED(); #endif // !defined(OS_CHROMEOS) } if (shutdown_type_ > NOT_VALID && shutdown_num_processes_ > 0) { // Measure total shutdown time as late in the process as possible // and then write it to a file to be read at startup. // We can't use prefs since all services are shutdown at this point. TimeDelta shutdown_delta = Time::Now() - shutdown_started_; std::string shutdown_ms = Int64ToString(shutdown_delta.InMilliseconds()); int len = static_cast<int>(shutdown_ms.length()) + 1; FilePath shutdown_ms_file = GetShutdownMsPath(); file_util::WriteFile(shutdown_ms_file, shutdown_ms.c_str(), len); } UnregisterURLRequestChromeJob(); } void ReadLastShutdownFile( ShutdownType type, int num_procs, int num_procs_slow) { DCHECK(ChromeThread::CurrentlyOn(ChromeThread::FILE)); FilePath shutdown_ms_file = GetShutdownMsPath(); std::string shutdown_ms_str; int64 shutdown_ms = 0; if (file_util::ReadFileToString(shutdown_ms_file, &shutdown_ms_str)) shutdown_ms = StringToInt64(shutdown_ms_str); file_util::Delete(shutdown_ms_file, false); if (type == NOT_VALID || shutdown_ms == 0 || num_procs == 0) return; const char *time_fmt = "Shutdown.%s.time"; const char *time_per_fmt = "Shutdown.%s.time_per_process"; std::string time; std::string time_per; if (type == WINDOW_CLOSE) { time = StringPrintf(time_fmt, "window_close"); time_per = StringPrintf(time_per_fmt, "window_close"); } else if (type == BROWSER_EXIT) { time = StringPrintf(time_fmt, "browser_exit"); time_per = StringPrintf(time_per_fmt, "browser_exit"); } else if (type == END_SESSION) { time = StringPrintf(time_fmt, "end_session"); time_per = StringPrintf(time_per_fmt, "end_session"); } else { NOTREACHED(); } if (time.empty()) return; // TODO(erikkay): change these to UMA histograms after a bit more testing. UMA_HISTOGRAM_TIMES(time.c_str(), TimeDelta::FromMilliseconds(shutdown_ms)); UMA_HISTOGRAM_TIMES(time_per.c_str(), TimeDelta::FromMilliseconds(shutdown_ms / num_procs)); UMA_HISTOGRAM_COUNTS_100("Shutdown.renderers.total", num_procs); UMA_HISTOGRAM_COUNTS_100("Shutdown.renderers.slow", num_procs_slow); } void ReadLastShutdownInfo() { PrefService* prefs = g_browser_process->local_state(); ShutdownType type = static_cast<ShutdownType>(prefs->GetInteger(prefs::kShutdownType)); int num_procs = prefs->GetInteger(prefs::kShutdownNumProcesses); int num_procs_slow = prefs->GetInteger(prefs::kShutdownNumProcessesSlow); // clear the prefs immediately so we don't pick them up on a future run prefs->SetInteger(prefs::kShutdownType, NOT_VALID); prefs->SetInteger(prefs::kShutdownNumProcesses, 0); prefs->SetInteger(prefs::kShutdownNumProcessesSlow, 0); // Read and delete the file on the file thread. ChromeThread::PostTask( ChromeThread::FILE, FROM_HERE, NewRunnableFunction( &ReadLastShutdownFile, type, num_procs, num_procs_slow)); } void SetTryingToQuit(bool quitting) { g_trying_to_quit = quitting; } bool IsTryingToQuit() { return g_trying_to_quit; } } // namespace browser_shutdown <commit_msg>Make sure restart due to Upgrade Notification works, even if the browser was started through ShellExecute (with a switch argument terminator).<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/browser_shutdown.h" #include <string> #include "app/resource_bundle.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/histogram.h" #include "base/path_service.h" #include "base/process_util.h" #include "base/string_util.h" #include "base/thread.h" #include "base/time.h" #include "base/waitable_event.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_thread.h" #include "chrome/browser/dom_ui/chrome_url_data_manager.h" #include "chrome/browser/first_run.h" #include "chrome/browser/jankometer.h" #include "chrome/browser/metrics/metrics_service.h" #include "chrome/browser/plugin_process_host.h" #include "chrome/browser/pref_service.h" #include "chrome/browser/renderer_host/render_process_host.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/renderer_host/render_widget_host.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "chrome/common/chrome_plugin_lib.h" #include "net/predictor_api.h" #if defined(OS_WIN) #include "chrome/browser/rlz/rlz.h" #endif using base::Time; using base::TimeDelta; namespace browser_shutdown { // Whether the browser is trying to quit (e.g., Quit chosen from menu). bool g_trying_to_quit = false; Time shutdown_started_; ShutdownType shutdown_type_ = NOT_VALID; int shutdown_num_processes_; int shutdown_num_processes_slow_; bool delete_resources_on_shutdown = true; const char kShutdownMsFile[] = "chrome_shutdown_ms.txt"; void RegisterPrefs(PrefService* local_state) { local_state->RegisterIntegerPref(prefs::kShutdownType, NOT_VALID); local_state->RegisterIntegerPref(prefs::kShutdownNumProcesses, 0); local_state->RegisterIntegerPref(prefs::kShutdownNumProcessesSlow, 0); } ShutdownType GetShutdownType() { return shutdown_type_; } void OnShutdownStarting(ShutdownType type) { if (shutdown_type_ != NOT_VALID) return; shutdown_type_ = type; // For now, we're only counting the number of renderer processes // since we can't safely count the number of plugin processes from this // thread, and we'd really like to avoid anything which might add further // delays to shutdown time. shutdown_started_ = Time::Now(); // Call FastShutdown on all of the RenderProcessHosts. This will be // a no-op in some cases, so we still need to go through the normal // shutdown path for the ones that didn't exit here. shutdown_num_processes_ = 0; shutdown_num_processes_slow_ = 0; for (RenderProcessHost::iterator i(RenderProcessHost::AllHostsIterator()); !i.IsAtEnd(); i.Advance()) { ++shutdown_num_processes_; if (!i.GetCurrentValue()->FastShutdownIfPossible()) ++shutdown_num_processes_slow_; } } FilePath GetShutdownMsPath() { FilePath shutdown_ms_file; PathService::Get(chrome::DIR_USER_DATA, &shutdown_ms_file); return shutdown_ms_file.AppendASCII(kShutdownMsFile); } void Shutdown() { // Unload plugins. This needs to happen on the IO thread. ChromeThread::PostTask( ChromeThread::IO, FROM_HERE, NewRunnableFunction(&ChromePluginLib::UnloadAllPlugins)); // WARNING: During logoff/shutdown (WM_ENDSESSION) we may not have enough // time to get here. If you have something that *must* happen on end session, // consider putting it in BrowserProcessImpl::EndSession. DCHECK(g_browser_process); // Notifies we are going away. g_browser_process->shutdown_event()->Signal(); PrefService* prefs = g_browser_process->local_state(); chrome_browser_net::SavePredictorStateForNextStartupAndTrim(prefs); MetricsService* metrics = g_browser_process->metrics_service(); if (metrics) { metrics->RecordCleanShutdown(); metrics->RecordCompletedSessionEnd(); } if (shutdown_type_ > NOT_VALID && shutdown_num_processes_ > 0) { // Record the shutdown info so that we can put it into a histogram at next // startup. prefs->SetInteger(prefs::kShutdownType, shutdown_type_); prefs->SetInteger(prefs::kShutdownNumProcesses, shutdown_num_processes_); prefs->SetInteger(prefs::kShutdownNumProcessesSlow, shutdown_num_processes_slow_); } // Check local state for the restart flag so we can restart the session below. bool restart_last_session = false; if (prefs->HasPrefPath(prefs::kRestartLastSessionOnShutdown)) { restart_last_session = prefs->GetBoolean(prefs::kRestartLastSessionOnShutdown); prefs->ClearPref(prefs::kRestartLastSessionOnShutdown); } prefs->SavePersistentPrefs(); #if defined(OS_WIN) // Cleanup any statics created by RLZ. Must be done before NotificationService // is destroyed. RLZTracker::CleanupRlz(); #endif // The jank'o'meter requires that the browser process has been destroyed // before calling UninstallJankometer(). delete g_browser_process; g_browser_process = NULL; // Uninstall Jank-O-Meter here after the IO thread is no longer running. UninstallJankometer(); if (delete_resources_on_shutdown) ResourceBundle::CleanupSharedInstance(); #if defined(OS_WIN) if (!Upgrade::IsBrowserAlreadyRunning() && shutdown_type_ != browser_shutdown::END_SESSION) { Upgrade::SwapNewChromeExeIfPresent(); } #endif if (restart_last_session) { #if !defined(OS_CHROMEOS) // Make sure to relaunch the browser with the original command line plus // the Restore Last Session flag. Note that Chrome can be launched (ie. // through ShellExecute on Windows) with a switch argument terminator at // the end (double dash, as described in b/1366444) plus a URL, // which prevents us from appending to the command line directly (issue // 46182). We therefore use GetSwitches to copy the command line (it stops // at the switch argument terminator). CommandLine old_cl(*CommandLine::ForCurrentProcess()); scoped_ptr<CommandLine> new_cl(new CommandLine(old_cl.GetProgram())); std::map<std::string, CommandLine::StringType> switches = old_cl.GetSwitches(); // Append the old switches to the new command line. for (std::map<std::string, CommandLine::StringType>::const_iterator i = switches.begin(); i != switches.end(); ++i) { CommandLine::StringType switch_value = i->second; if (!switch_value.empty()) new_cl->AppendSwitchWithValue(i->first, i->second); else new_cl->AppendSwitch(i->first); } // Ensure restore last session is set. if (!new_cl->HasSwitch(switches::kRestoreLastSession)) new_cl->AppendSwitch(switches::kRestoreLastSession); #if defined(OS_WIN) || defined(OS_LINUX) Upgrade::RelaunchChromeBrowser(*new_cl.get()); #endif // defined(OS_WIN) || defined(OS_LINUX) #if defined(OS_MACOSX) new_cl->AppendSwitch(switches::kActivateOnLaunch); base::LaunchApp(*new_cl.get(), false, false, NULL); #endif // defined(OS_MACOSX) #else NOTIMPLEMENTED(); #endif // !defined(OS_CHROMEOS) } if (shutdown_type_ > NOT_VALID && shutdown_num_processes_ > 0) { // Measure total shutdown time as late in the process as possible // and then write it to a file to be read at startup. // We can't use prefs since all services are shutdown at this point. TimeDelta shutdown_delta = Time::Now() - shutdown_started_; std::string shutdown_ms = Int64ToString(shutdown_delta.InMilliseconds()); int len = static_cast<int>(shutdown_ms.length()) + 1; FilePath shutdown_ms_file = GetShutdownMsPath(); file_util::WriteFile(shutdown_ms_file, shutdown_ms.c_str(), len); } UnregisterURLRequestChromeJob(); } void ReadLastShutdownFile( ShutdownType type, int num_procs, int num_procs_slow) { DCHECK(ChromeThread::CurrentlyOn(ChromeThread::FILE)); FilePath shutdown_ms_file = GetShutdownMsPath(); std::string shutdown_ms_str; int64 shutdown_ms = 0; if (file_util::ReadFileToString(shutdown_ms_file, &shutdown_ms_str)) shutdown_ms = StringToInt64(shutdown_ms_str); file_util::Delete(shutdown_ms_file, false); if (type == NOT_VALID || shutdown_ms == 0 || num_procs == 0) return; const char *time_fmt = "Shutdown.%s.time"; const char *time_per_fmt = "Shutdown.%s.time_per_process"; std::string time; std::string time_per; if (type == WINDOW_CLOSE) { time = StringPrintf(time_fmt, "window_close"); time_per = StringPrintf(time_per_fmt, "window_close"); } else if (type == BROWSER_EXIT) { time = StringPrintf(time_fmt, "browser_exit"); time_per = StringPrintf(time_per_fmt, "browser_exit"); } else if (type == END_SESSION) { time = StringPrintf(time_fmt, "end_session"); time_per = StringPrintf(time_per_fmt, "end_session"); } else { NOTREACHED(); } if (time.empty()) return; // TODO(erikkay): change these to UMA histograms after a bit more testing. UMA_HISTOGRAM_TIMES(time.c_str(), TimeDelta::FromMilliseconds(shutdown_ms)); UMA_HISTOGRAM_TIMES(time_per.c_str(), TimeDelta::FromMilliseconds(shutdown_ms / num_procs)); UMA_HISTOGRAM_COUNTS_100("Shutdown.renderers.total", num_procs); UMA_HISTOGRAM_COUNTS_100("Shutdown.renderers.slow", num_procs_slow); } void ReadLastShutdownInfo() { PrefService* prefs = g_browser_process->local_state(); ShutdownType type = static_cast<ShutdownType>(prefs->GetInteger(prefs::kShutdownType)); int num_procs = prefs->GetInteger(prefs::kShutdownNumProcesses); int num_procs_slow = prefs->GetInteger(prefs::kShutdownNumProcessesSlow); // clear the prefs immediately so we don't pick them up on a future run prefs->SetInteger(prefs::kShutdownType, NOT_VALID); prefs->SetInteger(prefs::kShutdownNumProcesses, 0); prefs->SetInteger(prefs::kShutdownNumProcessesSlow, 0); // Read and delete the file on the file thread. ChromeThread::PostTask( ChromeThread::FILE, FROM_HERE, NewRunnableFunction( &ReadLastShutdownFile, type, num_procs, num_procs_slow)); } void SetTryingToQuit(bool quitting) { g_trying_to_quit = quitting; } bool IsTryingToQuit() { return g_trying_to_quit; } } // namespace browser_shutdown <|endoftext|>
<commit_before>/* ============================================================================ * Copyright (c) 2012 Michael A. Jackson (BlueQuartz Software) * Copyright (c) 2012 Singanallur Venkatakrishnan (Purdue University) * 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 Singanallur Venkatakrishnan, Michael A. Jackson, the Pudue * Univeristy, BlueQuartz Software 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. * * This code was written under United States Air Force Contract number * FA8650-07-D-5800 * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ #include "SigmaXEstimation.h" #include <limits> #include "MBIRLib/Common/EIMMath.h" #include "MBIRLib/IOFilters/MRCHeader.h" #include "MBIRLib/IOFilters/MRCReader.h" namespace Detail { const float DegToRad = 0.017453292519943f; template<typename T> void calcMinMax(T* data, int total, Real_t& min, Real_t& max, Real_t& sum2) { for (int i = 0; i < total; i++) { if(data[i] > max) { max = data[i]; } if(data[i] < min) { min = data[i]; } sum2 += (data[i]); } } template<typename T> void calcAvgDeviation(T* data, int total, Real_t& dev) { dev = 0; Real_t mean = 0; for (int i = 0; i < total; i++) { mean += data[i]; } mean /= total; for (int i = 0; i < total; i++) { dev += fabs(data[i] - mean); } dev /= total; } template<typename T> void calcBFAvgDeviation(T* data, int total, Real_t& dev, double bf_offset) { dev = 0; Real_t mean = 0; for (int i = 0; i < total; i++) { Real_t temp = data[i] + bf_offset; if(temp > 0) { mean += log(data[i] + bf_offset); } } mean /= total; for (int i = 0; i < total; i++) { Real_t temp = data[i] + bf_offset; if(temp > 0) { dev += fabs(log(data[i] + bf_offset) - mean); } } dev /= total; } } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- SigmaXEstimation::SigmaXEstimation() : m_SampleThickness(100.0), m_TiltAngles(0), m_DefaultOffset(0.0), m_TargetGain(1.0), m_BfOffset(0.0), m_UseBFOffset(false), m_SigmaXEstimate(0.0) { m_XDims[0] = -1; m_XDims[1] = -1; m_YDims[0] = -1; m_YDims[1] = -1; } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- SigmaXEstimation::~SigmaXEstimation() { } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void SigmaXEstimation::execute() { MRCHeader header; ::memset(&header, 0, 1024); header.feiHeaders = NULL; MRCReader::Pointer reader = MRCReader::New(true); int err = reader->readHeader(m_InputFile, &header); if (err < 0) { FREE_FEI_HEADERS( header.feiHeaders ) notify("Error reading the MRC input file", 0, Observable::UpdateErrorMessage); setErrorCondition(-1); return; } //Make sure min/max have been set otherwise just use the dimensions of the data from the header if (m_XDims[0] < 0) { m_XDims[0] = 0; } if (m_XDims[1] < 0) { m_XDims[1] = header.nx;} if (m_YDims[0] < 0) { m_YDims[0] = 0;} if (m_YDims[1] < 0) { m_YDims[1] = header.ny;} int voxelMin[3] = { m_XDims[0], m_YDims[0], 0}; int voxelMax[3] = { m_XDims[1], m_YDims[1], 0}; Real_t sum1 = 0; // Real_t targetMin = std::numeric_limits<Real_t>::max(); // Real_t targetMax = std::numeric_limits<Real_t>::min(); // Real_t min = std::numeric_limits<Real_t>::max(); // Real_t max = std::numeric_limits<Real_t>::min(); std::vector<Real_t> sum2s(header.nz); int voxelCount = (m_XDims[1] - m_XDims[0]) * (m_YDims[1] - m_YDims[0]); float progress = 0.0; // Loop over each tilt angle to compute the Target Gain Estimation for(int i_theta = 0; i_theta < header.nz; ++i_theta) { voxelMin[2] = i_theta; voxelMax[2] = i_theta; err = reader->read(m_InputFile, voxelMin, voxelMax); // This should read the subvolume define by voxelMin and voxelMax if(err < 0) { break; } progress = (i_theta / header.nz) * 100.0f; Real_t sum2 = 0; switch(header.mode) { case 0: if(m_UseBFOffset) { Detail::calcBFAvgDeviation<uint8_t>(static_cast<uint8_t*>(reader->getDataPointer()), voxelCount, sum2, m_BfOffset); } else { Detail::calcAvgDeviation<uint8_t>(static_cast<uint8_t*>(reader->getDataPointer()), voxelCount, sum2); } break; case 1: if(m_UseBFOffset) { Detail::calcBFAvgDeviation<uint16_t>(static_cast<uint16_t*>(reader->getDataPointer()), voxelCount, sum2, m_BfOffset); } else { Detail::calcAvgDeviation<uint16_t>(static_cast<uint16_t*>(reader->getDataPointer()), voxelCount, sum2); } break; case 2: if(m_UseBFOffset) { Detail::calcBFAvgDeviation<float>(static_cast<float*>(reader->getDataPointer()), voxelCount, sum2, m_BfOffset); } else { Detail::calcAvgDeviation<float>(static_cast<float*>(reader->getDataPointer()), voxelCount, sum2); } break; case 3: break; case 4: break; case 6: if(m_UseBFOffset) { Detail::calcBFAvgDeviation<uint16_t>(static_cast<uint16_t*>(reader->getDataPointer()), voxelCount, sum2, m_BfOffset); } else { Detail::calcAvgDeviation<uint16_t>(static_cast<uint16_t*>(reader->getDataPointer()), voxelCount, sum2); } break; case 16: break; } // if (min < targetMin) { targetMin = min; } // if (max > targetMax) { targetMax = max; } sum2s[i_theta] = sum2; notify("Estimating Target Gain and Sigma X from Data. ", (int)progress, Observable::UpdateProgressValueAndMessage); } //modify it based on any knowledge they have about the tx. attenuation // Now Calculate the Sigma X estimation Real_t cosine = 0.0; for(int i_theta = 0; i_theta < m_TiltAngles.size(); ++i_theta) { //Subtract off any offset in the data sum2s[i_theta] /= m_TargetGain; cosine = cos(m_TiltAngles[i_theta] * (Detail::DegToRad)); sum1 += (sum2s[i_theta] * cosine) / (m_SampleThickness); } m_SigmaXEstimate = sum1 / header.nz; ///10.0; FREE_FEI_HEADERS( header.feiHeaders ); // std::cout << "Estimated Target Gain: " << m_TargetGainEstimate << std::endl; // std::cout << "Estimated Sigma X: " << m_SigmaXEstimate << std::endl; notify("Estimating Target Gain and Sigma X Complete ", 100, Observable::UpdateProgressValueAndMessage); } <commit_msg>Fixed major bug in SigmaX estimation with data type being incorrect. Need to release the code on the web.<commit_after>/* ============================================================================ * Copyright (c) 2012 Michael A. Jackson (BlueQuartz Software) * Copyright (c) 2012 Singanallur Venkatakrishnan (Purdue University) * 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 Singanallur Venkatakrishnan, Michael A. Jackson, the Pudue * Univeristy, BlueQuartz Software 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. * * This code was written under United States Air Force Contract number * FA8650-07-D-5800 * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ #include "SigmaXEstimation.h" #include <limits> #include "MBIRLib/Common/EIMMath.h" #include "MBIRLib/IOFilters/MRCHeader.h" #include "MBIRLib/IOFilters/MRCReader.h" namespace Detail { const float DegToRad = 0.017453292519943f; template<typename T> void calcMinMax(T* data, int total, Real_t& min, Real_t& max, Real_t& sum2) { for (int i = 0; i < total; i++) { if(data[i] > max) { max = data[i]; } if(data[i] < min) { min = data[i]; } sum2 += (data[i]); } } template<typename T> void calcAvgDeviation(T* data, int32_t total, Real_t& dev) { dev = 0; Real_t mean = 0; for (int32_t i = 0; i < total; i++) { mean += data[i]; } mean /= total; for (int32_t i = 0; i < total; i++) { dev += fabs(data[i] - mean); } dev /= total; } template<typename T> void calcBFAvgDeviation(T* data, int32_t total, Real_t& dev, double bf_offset) { dev = 0; Real_t mean = 0; for (int32_t i = 0; i < total; i++) { Real_t temp = data[i] + bf_offset; if(temp > 0) { mean += log(temp); } } mean /= total; std::cout<<"Mean value = "<<mean<<std::endl; for (int32_t i = 0; i < total; i++) { Real_t temp = data[i] + bf_offset; if(temp > 0) { dev += fabs(log(temp) - mean); } } dev /= total; std::cout<<"Mean absolute deviation = "<<dev<<std::endl; } } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- SigmaXEstimation::SigmaXEstimation() : m_SampleThickness(100.0), m_TiltAngles(0), m_DefaultOffset(0.0), m_TargetGain(1.0), m_BfOffset(0.0), m_UseBFOffset(false), m_SigmaXEstimate(0.0) { m_XDims[0] = -1; m_XDims[1] = -1; m_YDims[0] = -1; m_YDims[1] = -1; } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- SigmaXEstimation::~SigmaXEstimation() { } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void SigmaXEstimation::execute() { MRCHeader header; ::memset(&header, 0, 1024); header.feiHeaders = NULL; MRCReader::Pointer reader = MRCReader::New(true); int err = reader->readHeader(m_InputFile, &header); if (err < 0) { FREE_FEI_HEADERS( header.feiHeaders ) notify("Error reading the MRC input file", 0, Observable::UpdateErrorMessage); setErrorCondition(-1); return; } //Make sure min/max have been set otherwise just use the dimensions of the data from the header if (m_XDims[0] < 0) { m_XDims[0] = 0; } if (m_XDims[1] < 0) { m_XDims[1] = header.nx;} if (m_YDims[0] < 0) { m_YDims[0] = 0;} if (m_YDims[1] < 0) { m_YDims[1] = header.ny;} int voxelMin[3] = { m_XDims[0], m_YDims[0], 0}; int voxelMax[3] = { m_XDims[1], m_YDims[1], 0}; Real_t sum1 = 0; // Real_t targetMin = std::numeric_limits<Real_t>::max(); // Real_t targetMax = std::numeric_limits<Real_t>::min(); // Real_t min = std::numeric_limits<Real_t>::max(); // Real_t max = std::numeric_limits<Real_t>::min(); std::vector<Real_t> sum2s(header.nz); int32_t voxelCount = (m_XDims[1] - m_XDims[0]) * (m_YDims[1] - m_YDims[0]); float progress = 0.0; // Loop over each tilt angle to compute the Target Gain Estimation for(int i_theta = 0; i_theta < header.nz; ++i_theta) { voxelMin[2] = i_theta; voxelMax[2] = i_theta; err = reader->read(m_InputFile, voxelMin, voxelMax); // This should read the subvolume define by voxelMin and voxelMax if(err < 0) { break; } progress = (i_theta / header.nz) * 100.0f; Real_t sum2 = 0; switch(header.mode) { case 0: if(m_UseBFOffset) { Detail::calcBFAvgDeviation<uint8_t>(static_cast<uint8_t*>(reader->getDataPointer()), voxelCount, sum2, m_BfOffset); } else { Detail::calcAvgDeviation<uint8_t>(static_cast<uint8_t*>(reader->getDataPointer()), voxelCount, sum2); } break; case 1: if(m_UseBFOffset) { Detail::calcBFAvgDeviation<int16_t>(static_cast<int16_t*>(reader->getDataPointer()), voxelCount, sum2, m_BfOffset); } else { Detail::calcAvgDeviation<int16_t>(static_cast<int16_t*>(reader->getDataPointer()), voxelCount, sum2); } break; case 2: if(m_UseBFOffset) { Detail::calcBFAvgDeviation<float>(static_cast<float*>(reader->getDataPointer()), voxelCount, sum2, m_BfOffset); } else { Detail::calcAvgDeviation<float>(static_cast<float*>(reader->getDataPointer()), voxelCount, sum2); } break; case 3: break; case 4: break; case 6: if(m_UseBFOffset) { Detail::calcBFAvgDeviation<uint16_t>(static_cast<uint16_t*>(reader->getDataPointer()), voxelCount, sum2, m_BfOffset); } else { Detail::calcAvgDeviation<uint16_t>(static_cast<uint16_t*>(reader->getDataPointer()), voxelCount, sum2); } break; case 16: break; } // if (min < targetMin) { targetMin = min; } // if (max > targetMax) { targetMax = max; } sum2s[i_theta] = sum2; notify("Estimating Target Gain and Sigma X from Data. ", (int)progress, Observable::UpdateProgressValueAndMessage); } //modify it based on any knowledge they have about the tx. attenuation // Now Calculate the Sigma X estimation Real_t cosine = 0.0; for(int i_theta = 0; i_theta < m_TiltAngles.size(); ++i_theta) { //Subtract off any offset in the data sum2s[i_theta] /= m_TargetGain; cosine = cos(m_TiltAngles[i_theta] * (Detail::DegToRad)); sum1 += (sum2s[i_theta] * cosine) / (m_SampleThickness); } m_SigmaXEstimate = sum1 / header.nz; ///10.0; FREE_FEI_HEADERS( header.feiHeaders ); // std::cout << "Estimated Target Gain: " << m_TargetGainEstimate << std::endl; // std::cout << "Estimated Sigma X: " << m_SigmaXEstimate << std::endl; notify("Estimating Target Gain and Sigma X Complete ", 100, Observable::UpdateProgressValueAndMessage); } <|endoftext|>
<commit_before>#include "proctor/frame_hough_proposer.h" namespace pcl { namespace proctor { void FrameHoughProposer::houghVote(Entry &query, Entry &target, bin_t& bins) { // Compute the reference point for the R-table Eigen::Vector4f centroid4; compute3DCentroid(*(target.cloud), centroid4); Eigen::Vector3f centroid(centroid4[0], centroid4[1], centroid4[2]); assert(query.keypoints->size() == query.features->size()); assert(target.keypoints->size() == target.features->size()); // Figure out bin dimension Eigen::Vector4f query_min4, query_max4; getMinMax3D(*query.cloud, query_min4, query_max4); Eigen::Vector3f query_min(query_min4[0], query_min4[1], query_min4[2]); Eigen::Vector3f query_max(query_max4[0], query_max4[1], query_max4[2]); PointCloud<PrincipalCurvatures>::Ptr target_curvatures = computeCurvatures(target); PointCloud<PrincipalCurvatures>::Ptr query_curvatures = computeCurvatures(query); for (unsigned int i = 0; i < query.keypoints->size(); i++) { std::vector<int> feature_indices; std::vector<float> sqr_distances; int num_correspondences = 2; if (!pcl_isfinite (query.features->points.row(i)(0))) continue; int num_found = target.tree->nearestKSearch(*query.features, i, num_correspondences, feature_indices, sqr_distances); for (int j = 0; j < num_found; j++) { // For each one of the feature correspondences int feature_index = feature_indices[j]; // Get corresponding target keypoint, and calculate its r to its centroid in world coordinates PointNormal correspondence = target.keypoints->at(feature_index); // Since features correspond to the keypoints Eigen::Vector3f r = correspondence.getVector3fMap() - centroid; // Calculate a local frame using principal curvature Eigen::Vector3f target_normal = correspondence.getNormalVector3fMap(); target_normal.normalize(); Eigen::Vector3f query_normal = query.keypoints->at(i).getNormalVector3fMap(); query_normal.normalize(); Eigen::Vector3f query_pc = getVectorCurvatureMap(query_curvatures->at(i)); Eigen::Vector3f query_perp = query_pc - (query_pc.dot(query_normal.normalized())) * query_normal.normalized(); query_perp.normalize(); Eigen::Vector3f target_pc = getVectorCurvatureMap(target_curvatures->at(feature_index)); Eigen::Vector3f target_perp = target_pc - (target_pc.dot(target_normal.normalized())) * target_normal.normalized(); target_perp.normalize(); // In case the PrincipalCurvaturesEstimation outputs NaNs, // skip this iteration if (query_perp != query_perp || target_perp != target_perp) { continue; } Eigen::Vector3f world_x(1, 0, 0); Eigen::Vector3f world_y(0, 1, 0); Eigen::Vector3f world_z(0, 0, 1); Eigen::Matrix3f A = getTransformationBetweenFrames(world_x, world_y, target_normal, target_perp); Eigen::Matrix3f B = getTransformationBetweenFrames(world_x, world_y, query_normal, query_perp); Eigen::Matrix3f rot_transform = B.transpose() * A; //Eigen::Matrix3f other = getTransformationBetweenFrames(target_normal, target_perp, query_normal, query_perp); // Test that the target_normal goes to (1, 0, 0) assert((A * target_normal).isApprox(world_x, 0.01)); // Test that the target_normal goes to (1, 0, 0) in A space, // then when moved to B space, and returned back to world space, // it stays the same assert((B.transpose() * other * A * target_normal).isApprox(target_normal, 0.01)); // Test that the target_normal goes to (1, 0, 0) in A space, // then when rotated in A space by the difference between B and A, // then returned back to world space, is equal to the query_normal //Eigen::Vector3f test = (A.transpose() * other.transpose() * A * target_normal); assert((A.transpose() * other.transpose() * A * target_normal).isApprox(query_normal, 0.01)); assert(query_normal.isApprox(rot_transform * target_normal, 0.01)); assert(query_perp.isApprox(rot_transform * target_perp, 0.01)); // Transform r based on the difference between the normals Eigen::Vector3f transformed_r = rot_transform * r; Eigen::Vector3f centroid_est = query.keypoints->at(i).getVector3fMap() - transformed_r; Eigen::Vector3f region = query_max - query_min; Eigen::Vector3f bin_size = region / bins_; Eigen::Vector3f diff = (centroid_est - query_min); Eigen::Vector3f indices = diff.cwiseQuotient(bin_size); castVotes(indices, bins); } } } Eigen::Vector3f FrameHoughProposer::getVectorCurvatureMap(PrincipalCurvatures p) { Eigen::Vector3f principal_curvature; principal_curvature(0) = p.principal_curvature_x; principal_curvature(1) = p.principal_curvature_y; principal_curvature(2) = p.principal_curvature_z; return principal_curvature; } PointCloud<PrincipalCurvatures>::Ptr FrameHoughProposer::computeCurvatures(Entry &e) { PointCloud<PrincipalCurvatures>::Ptr curvatures (new PointCloud<PrincipalCurvatures>()); PrincipalCurvaturesEstimation<PointNormal, PointNormal, pcl::PrincipalCurvatures> curvature_estimation; curvature_estimation.setInputCloud(e.keypoints); curvature_estimation.setInputNormals(e.cloud); curvature_estimation.setSearchSurface(e.cloud); pcl::search::KdTree<pcl::PointNormal>::Ptr tree (new pcl::search::KdTree<pcl::PointNormal>); curvature_estimation.setSearchMethod(tree); curvature_estimation.setRadiusSearch(0.01); curvature_estimation.compute(*curvatures); return curvatures; } /* Builds a matrix that converts a coordinate in "from" coordinates to "to" coordinates */ Eigen::Matrix3f FrameHoughProposer::getTransformationBetweenFrames(Eigen::Vector3f x_from, Eigen::Vector3f y_from, Eigen::Vector3f x_to, Eigen::Vector3f y_to) { assert(abs(x_from.norm() - 1) < 0.0001); assert(abs(x_to.norm() - 1) < 0.0001); assert(abs(y_from.norm() - 1) < 0.0001); assert(abs(y_to.norm() - 1) < 0.0001); x_from.normalize(); y_from.normalize(); x_to.normalize(); y_to.normalize(); assert(abs(x_from.dot(y_from)) < 0.0001); assert(abs(x_to.dot(y_to)) < 0.0001); Eigen::Vector3f z_from = x_from.cross(y_from); z_from.normalize(); Eigen::Vector3f z_to = x_to.cross(y_to); z_to.normalize(); Eigen::Matrix3f rot; rot << x_from.dot(x_to), y_from.dot(x_to) , z_from.dot(x_to), x_from.dot(y_to), y_from.dot(y_to) , z_from.dot(y_to), x_from.dot(z_to), y_from.dot(z_to) , z_from.dot(z_to); return rot; } } } <commit_msg>Fix compilation of proctor in debug mode.<commit_after>#include "proctor/frame_hough_proposer.h" namespace pcl { namespace proctor { void FrameHoughProposer::houghVote(Entry &query, Entry &target, bin_t& bins) { // Compute the reference point for the R-table Eigen::Vector4f centroid4; compute3DCentroid(*(target.cloud), centroid4); Eigen::Vector3f centroid(centroid4[0], centroid4[1], centroid4[2]); assert(query.keypoints->size() == query.features->size()); assert(target.keypoints->size() == target.features->size()); // Figure out bin dimension Eigen::Vector4f query_min4, query_max4; getMinMax3D(*query.cloud, query_min4, query_max4); Eigen::Vector3f query_min(query_min4[0], query_min4[1], query_min4[2]); Eigen::Vector3f query_max(query_max4[0], query_max4[1], query_max4[2]); PointCloud<PrincipalCurvatures>::Ptr target_curvatures = computeCurvatures(target); PointCloud<PrincipalCurvatures>::Ptr query_curvatures = computeCurvatures(query); for (unsigned int i = 0; i < query.keypoints->size(); i++) { std::vector<int> feature_indices; std::vector<float> sqr_distances; int num_correspondences = 2; if (!pcl_isfinite (query.features->points.row(i)(0))) continue; int num_found = target.tree->nearestKSearch(*query.features, i, num_correspondences, feature_indices, sqr_distances); for (int j = 0; j < num_found; j++) { // For each one of the feature correspondences int feature_index = feature_indices[j]; // Get corresponding target keypoint, and calculate its r to its centroid in world coordinates PointNormal correspondence = target.keypoints->at(feature_index); // Since features correspond to the keypoints Eigen::Vector3f r = correspondence.getVector3fMap() - centroid; // Calculate a local frame using principal curvature Eigen::Vector3f target_normal = correspondence.getNormalVector3fMap(); target_normal.normalize(); Eigen::Vector3f query_normal = query.keypoints->at(i).getNormalVector3fMap(); query_normal.normalize(); Eigen::Vector3f query_pc = getVectorCurvatureMap(query_curvatures->at(i)); Eigen::Vector3f query_perp = query_pc - (query_pc.dot(query_normal.normalized())) * query_normal.normalized(); query_perp.normalize(); Eigen::Vector3f target_pc = getVectorCurvatureMap(target_curvatures->at(feature_index)); Eigen::Vector3f target_perp = target_pc - (target_pc.dot(target_normal.normalized())) * target_normal.normalized(); target_perp.normalize(); // In case the PrincipalCurvaturesEstimation outputs NaNs, // skip this iteration if (query_perp != query_perp || target_perp != target_perp) { continue; } Eigen::Vector3f world_x(1, 0, 0); Eigen::Vector3f world_y(0, 1, 0); Eigen::Vector3f world_z(0, 0, 1); Eigen::Matrix3f A = getTransformationBetweenFrames(world_x, world_y, target_normal, target_perp); Eigen::Matrix3f B = getTransformationBetweenFrames(world_x, world_y, query_normal, query_perp); Eigen::Matrix3f rot_transform = B.transpose() * A; #ifndef NDEBUG Eigen::Matrix3f other = getTransformationBetweenFrames(target_normal, target_perp, query_normal, query_perp); #endif // Test that the target_normal goes to (1, 0, 0) assert((A * target_normal).isApprox(world_x, 0.01)); // Test that the target_normal goes to (1, 0, 0) in A space, // then when moved to B space, and returned back to world space, // it stays the same assert((B.transpose() * other * A * target_normal).isApprox(target_normal, 0.01)); // Test that the target_normal goes to (1, 0, 0) in A space, // then when rotated in A space by the difference between B and A, // then returned back to world space, is equal to the query_normal //Eigen::Vector3f test = (A.transpose() * other.transpose() * A * target_normal); assert((A.transpose() * other.transpose() * A * target_normal).isApprox(query_normal, 0.01)); assert(query_normal.isApprox(rot_transform * target_normal, 0.01)); assert(query_perp.isApprox(rot_transform * target_perp, 0.01)); // Transform r based on the difference between the normals Eigen::Vector3f transformed_r = rot_transform * r; Eigen::Vector3f centroid_est = query.keypoints->at(i).getVector3fMap() - transformed_r; Eigen::Vector3f region = query_max - query_min; Eigen::Vector3f bin_size = region / bins_; Eigen::Vector3f diff = (centroid_est - query_min); Eigen::Vector3f indices = diff.cwiseQuotient(bin_size); castVotes(indices, bins); } } } Eigen::Vector3f FrameHoughProposer::getVectorCurvatureMap(PrincipalCurvatures p) { Eigen::Vector3f principal_curvature; principal_curvature(0) = p.principal_curvature_x; principal_curvature(1) = p.principal_curvature_y; principal_curvature(2) = p.principal_curvature_z; return principal_curvature; } PointCloud<PrincipalCurvatures>::Ptr FrameHoughProposer::computeCurvatures(Entry &e) { PointCloud<PrincipalCurvatures>::Ptr curvatures (new PointCloud<PrincipalCurvatures>()); PrincipalCurvaturesEstimation<PointNormal, PointNormal, pcl::PrincipalCurvatures> curvature_estimation; curvature_estimation.setInputCloud(e.keypoints); curvature_estimation.setInputNormals(e.cloud); curvature_estimation.setSearchSurface(e.cloud); pcl::search::KdTree<pcl::PointNormal>::Ptr tree (new pcl::search::KdTree<pcl::PointNormal>); curvature_estimation.setSearchMethod(tree); curvature_estimation.setRadiusSearch(0.01); curvature_estimation.compute(*curvatures); return curvatures; } /* Builds a matrix that converts a coordinate in "from" coordinates to "to" coordinates */ Eigen::Matrix3f FrameHoughProposer::getTransformationBetweenFrames(Eigen::Vector3f x_from, Eigen::Vector3f y_from, Eigen::Vector3f x_to, Eigen::Vector3f y_to) { assert(abs(x_from.norm() - 1) < 0.0001); assert(abs(x_to.norm() - 1) < 0.0001); assert(abs(y_from.norm() - 1) < 0.0001); assert(abs(y_to.norm() - 1) < 0.0001); x_from.normalize(); y_from.normalize(); x_to.normalize(); y_to.normalize(); assert(abs(x_from.dot(y_from)) < 0.0001); assert(abs(x_to.dot(y_to)) < 0.0001); Eigen::Vector3f z_from = x_from.cross(y_from); z_from.normalize(); Eigen::Vector3f z_to = x_to.cross(y_to); z_to.normalize(); Eigen::Matrix3f rot; rot << x_from.dot(x_to), y_from.dot(x_to) , z_from.dot(x_to), x_from.dot(y_to), y_from.dot(y_to) , z_from.dot(y_to), x_from.dot(z_to), y_from.dot(z_to) , z_from.dot(z_to); return rot; } } } <|endoftext|>
<commit_before>// @(#)root/proofd:$Id$ // Author: Gerardo Ganis 12/12/2005 /************************************************************************* * Copyright (C) 1995-2005, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // XrdProofPhyConn // // // // Authors: G. Ganis, CERN, 2005 // // // // XrdProofConn implementation using a simple physical connection // // (Unix or Tcp) // ////////////////////////////////////////////////////////////////////////// #include "XrdProofPhyConn.h" #include "XrdVersion.hh" #include "XrdClient/XrdClientEnv.hh" #include "XrdClient/XrdClientConnMgr.hh" #include "XrdClient/XrdClientConst.hh" #include "XrdClient/XrdClientLogConnection.hh" #include "XrdClient/XrdClientMessage.hh" #include "XrdNet/XrdNetDNS.hh" #include "XrdSec/XrdSecInterface.hh" #ifndef WIN32 #include <sys/socket.h> #include <sys/types.h> #include <pwd.h> #else #include <Winsock2.h> #endif // Tracing utils #include "XrdProofdTrace.h" #define URLTAG "["<<fUrl.Host<<":"<<fUrl.Port<<"]" //_____________________________________________________________________________ XrdProofPhyConn::XrdProofPhyConn(const char *url, int psid, char capver, XrdClientAbsUnsolMsgHandler *uh, bool tcp) : XrdProofConn(0, 'i', psid, capver, uh) { // Constructor. Open a direct connection (Unix or Tcp) to a remote // XrdProofd instance. Does not use the connection manager. XPDLOC(ALL, "PhyConn") fTcp = tcp; // Mutex fMutex = new XrdSysRecMutex(); // Initialization if (url && !Init(url)) { TRACE(XERR, "severe error occurred while" " opening a connection" << " to server "<<URLTAG); return; } } //_____________________________________________________________________________ bool XrdProofPhyConn::Init(const char *url) { // Initialization XPDLOC(ALL, "PhyConn::Init") // Save url fUrl.TakeUrl(XrdOucString(url)); // Get user fUser = fUrl.User.c_str(); if (fUser.length() <= 0) { // Use local username, if not specified #ifndef WIN32 struct passwd *pw = getpwuid(getuid()); fUser = pw ? pw->pw_name : ""; #else char lname[256]; DWORD length = sizeof (lname); ::GetUserName(lname, &length); fUser = lname; #endif } // Host and Port if (!fTcp) { fHost = XrdNetDNS::getHostName(((fUrl.Host.length() > 0) ? fUrl.Host.c_str() : "localhost")); fPort = -1; fUrl.Host = ""; fUrl.User = ""; } else { fHost = fUrl.Host.c_str(); fPort = fUrl.Port; // Check port if (fPort <= 0) { struct servent *sent = getservbyname("rootd", "tcp"); if (!sent) { TRACE(XERR, "service 'rootd' not found by getservbyname" << ": using default IANA assigned tcp port 1094"); fPort = 1094; } else { fPort = (int)ntohs(sent->s_port); // Update port in url fUrl.Port = fPort; TRACE(XERR, "getservbyname found tcp port " << fPort << " for service 'rootd'"); } } } // Run the connection attempts: the result is stored in fConnected Connect(); // We are done return fConnected; } //_____________________________________________________________________________ void XrdProofPhyConn::Connect() { // Run the connection attempts: the result is stored in fConnected XPDLOC(ALL, "PhyConn::Connect") int maxTry = -1, timeWait = -1; // Max number of tries and timeout; use current settings, if any XrdProofConn::GetRetryParam(maxTry, timeWait); maxTry = (maxTry > -1) ? maxTry : EnvGetLong(NAME_FIRSTCONNECTMAXCNT); timeWait = (timeWait > -1) ? timeWait : EnvGetLong(NAME_CONNECTTIMEOUT); int logid = -1; int i = 0; for (; (i < maxTry) && (!fConnected); i++) { // Try connection logid = TryConnect(); // We are connected to a host. Let's handshake with it. if (fConnected) { // Now the have the logical Connection ID, that we can use as streamid for // communications with the server TRACE(DBG, "new logical connection ID: "<<logid); // Get access to server if (!GetAccessToSrv()) { if (fLastErr == kXR_NotAuthorized) { // Authentication error: does not make much sense to retry Close("P"); XrdOucString msg = fLastErrMsg; msg.erase(msg.rfind(":")); TRACE(XERR, "authentication failure: " << msg); return; } else { TRACE(XERR, "access to server failed (" << fLastErrMsg << ")"); } continue; } else { // Manager call in client: no need to create or attach: just notify TRACE(DBG, "access to server granted."); break; } } // We force a physical disconnection in this special case TRACE(DBG, "disconnecting"); Close("P"); // And we wait a bit before retrying TRACE(DBG, "connection attempt failed: sleep " << timeWait << " secs"); #ifndef WIN32 sleep(timeWait); #else Sleep(timeWait * 1000); #endif } //for connect try } //_____________________________________________________________________________ int XrdProofPhyConn::TryConnect() { // Connect to remote server XPDLOC(ALL, "PhyConn::TryConnect") const char *ctype[2] = {"UNIX", "TCP"}; // Create physical connection #ifdef OLDXRCPHYCONN fPhyConn = new XrdClientPhyConnection(this); #else fPhyConn = new XrdClientPhyConnection(this, 0); #endif // Connect bool isUnix = (fTcp) ? 0 : 1; if (!(fPhyConn->Connect(fUrl, isUnix))) { TRACE(XERR, "creating "<<ctype[fTcp]<<" connection to "<<URLTAG); fLogConnID = -1; fConnected = 0; return -1; } TRACE(DBG, ctype[fTcp]<<"-connected to "<<URLTAG); // Set some vars fLogConnID = 0; fStreamid = 1; fConnected = 1; // Replies are processed asynchronously SetAsync(fUnsolMsgHandler); // We are done return fLogConnID; } //_____________________________________________________________________________ void XrdProofPhyConn::Close(const char *) { // Close the connection. // Make sure we are connected if (!fConnected) return; // Close connection if (fPhyConn) fPhyConn->Disconnect(); // Flag this action fConnected = 0; // We are done return; } //_____________________________________________________________________________ void XrdProofPhyConn::SetAsync(XrdClientAbsUnsolMsgHandler *uh) { // Set handler of unsolicited responses if (fPhyConn) fPhyConn->UnsolicitedMsgHandler = uh; } //_____________________________________________________________________________ XrdClientMessage *XrdProofPhyConn::ReadMsg() { // Pickup message from the queue return (fPhyConn ? fPhyConn->ReadMessage(fStreamid) : (XrdClientMessage *)0); } //_____________________________________________________________________________ bool XrdProofPhyConn::GetAccessToSrv() { // Gets access to the connected server. // The login and authorization steps are performed here. XPDLOC(ALL, "PhyConn::GetAccessToSrv") // Now we are connected and we ask for the kind of the server { XrdClientPhyConnLocker pcl(fPhyConn); fServerType = DoHandShake(); } switch (fServerType) { case kSTXProofd: TRACE(DBG, "found server at "<<URLTAG); // Now we can start the reader thread in the physical connection, if needed fPhyConn->StartReader(); fPhyConn->fServerType = kSTBaseXrootd; break; case kSTError: TRACE(XERR, "handShake failed with server "<<URLTAG); Close(); return 0; case kSTProofd: case kSTNone: default: TRACE(XERR, "server at "<<URLTAG<< " is unknown : protocol error"); Close(); return 0; } // Execute a login if (fPhyConn->IsLogged() != kNo) { TRACE(XERR, "client already logged-in at "<<URLTAG<<" (!): protocol error!"); return 0; } // Login return Login(); } //_____________________________________________________________________________ int XrdProofPhyConn::WriteRaw(const void *buf, int len) { // Low level write call if (fPhyConn) return fPhyConn->WriteRaw(buf, len); // No connection open return -1; } //_____________________________________________________________________________ int XrdProofPhyConn::ReadRaw(void *buf, int len) { // Low level write call if (fPhyConn) return fPhyConn->ReadRaw(buf, len); // No connection open return -1; } <commit_msg>Make sure the default port is 1093<commit_after>// @(#)root/proofd:$Id$ // Author: Gerardo Ganis 12/12/2005 /************************************************************************* * Copyright (C) 1995-2005, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // XrdProofPhyConn // // // // Authors: G. Ganis, CERN, 2005 // // // // XrdProofConn implementation using a simple physical connection // // (Unix or Tcp) // ////////////////////////////////////////////////////////////////////////// #include "XrdProofPhyConn.h" #include "XrdVersion.hh" #include "XrdClient/XrdClientEnv.hh" #include "XrdClient/XrdClientConnMgr.hh" #include "XrdClient/XrdClientConst.hh" #include "XrdClient/XrdClientLogConnection.hh" #include "XrdClient/XrdClientMessage.hh" #include "XrdNet/XrdNetDNS.hh" #include "XrdSec/XrdSecInterface.hh" #ifndef WIN32 #include <sys/socket.h> #include <sys/types.h> #include <pwd.h> #else #include <Winsock2.h> #endif // Tracing utils #include "XrdProofdTrace.h" #define URLTAG "["<<fUrl.Host<<":"<<fUrl.Port<<"]" //_____________________________________________________________________________ XrdProofPhyConn::XrdProofPhyConn(const char *url, int psid, char capver, XrdClientAbsUnsolMsgHandler *uh, bool tcp) : XrdProofConn(0, 'i', psid, capver, uh) { // Constructor. Open a direct connection (Unix or Tcp) to a remote // XrdProofd instance. Does not use the connection manager. XPDLOC(ALL, "PhyConn") fTcp = tcp; // Mutex fMutex = new XrdSysRecMutex(); // Initialization if (url && !Init(url)) { TRACE(XERR, "severe error occurred while" " opening a connection" << " to server "<<URLTAG); return; } } //_____________________________________________________________________________ bool XrdProofPhyConn::Init(const char *url) { // Initialization XPDLOC(ALL, "PhyConn::Init") // Save url fUrl.TakeUrl(XrdOucString(url)); // Get user fUser = fUrl.User.c_str(); if (fUser.length() <= 0) { // Use local username, if not specified #ifndef WIN32 struct passwd *pw = getpwuid(getuid()); fUser = pw ? pw->pw_name : ""; #else char lname[256]; DWORD length = sizeof (lname); ::GetUserName(lname, &length); fUser = lname; #endif } // Host and Port if (!fTcp) { fHost = XrdNetDNS::getHostName(((fUrl.Host.length() > 0) ? fUrl.Host.c_str() : "localhost")); fPort = -1; fUrl.Host = ""; fUrl.User = ""; } else { fHost = fUrl.Host.c_str(); fPort = fUrl.Port; // Check port if (fPort <= 0) { struct servent *sent = getservbyname("proofd", "tcp"); if (!sent) { TRACE(XERR, "service 'proofd' not found by getservbyname" << ": using default IANA assigned tcp port 1093"); fPort = 1093; } else { fPort = (int)ntohs(sent->s_port); // Update port in url fUrl.Port = fPort; TRACE(XERR, "getservbyname found tcp port " << fPort << " for service 'proofd'"); } } } // Run the connection attempts: the result is stored in fConnected Connect(); // We are done return fConnected; } //_____________________________________________________________________________ void XrdProofPhyConn::Connect() { // Run the connection attempts: the result is stored in fConnected XPDLOC(ALL, "PhyConn::Connect") int maxTry = -1, timeWait = -1; // Max number of tries and timeout; use current settings, if any XrdProofConn::GetRetryParam(maxTry, timeWait); maxTry = (maxTry > -1) ? maxTry : EnvGetLong(NAME_FIRSTCONNECTMAXCNT); timeWait = (timeWait > -1) ? timeWait : EnvGetLong(NAME_CONNECTTIMEOUT); int logid = -1; int i = 0; for (; (i < maxTry) && (!fConnected); i++) { // Try connection logid = TryConnect(); // We are connected to a host. Let's handshake with it. if (fConnected) { // Now the have the logical Connection ID, that we can use as streamid for // communications with the server TRACE(DBG, "new logical connection ID: "<<logid); // Get access to server if (!GetAccessToSrv()) { if (fLastErr == kXR_NotAuthorized) { // Authentication error: does not make much sense to retry Close("P"); XrdOucString msg = fLastErrMsg; msg.erase(msg.rfind(":")); TRACE(XERR, "authentication failure: " << msg); return; } else { TRACE(XERR, "access to server failed (" << fLastErrMsg << ")"); } continue; } else { // Manager call in client: no need to create or attach: just notify TRACE(DBG, "access to server granted."); break; } } // We force a physical disconnection in this special case TRACE(DBG, "disconnecting"); Close("P"); // And we wait a bit before retrying TRACE(DBG, "connection attempt failed: sleep " << timeWait << " secs"); #ifndef WIN32 sleep(timeWait); #else Sleep(timeWait * 1000); #endif } //for connect try } //_____________________________________________________________________________ int XrdProofPhyConn::TryConnect() { // Connect to remote server XPDLOC(ALL, "PhyConn::TryConnect") const char *ctype[2] = {"UNIX", "TCP"}; // Create physical connection #ifdef OLDXRCPHYCONN fPhyConn = new XrdClientPhyConnection(this); #else fPhyConn = new XrdClientPhyConnection(this, 0); #endif // Connect bool isUnix = (fTcp) ? 0 : 1; if (!(fPhyConn->Connect(fUrl, isUnix))) { TRACE(XERR, "creating "<<ctype[fTcp]<<" connection to "<<URLTAG); fLogConnID = -1; fConnected = 0; return -1; } TRACE(DBG, ctype[fTcp]<<"-connected to "<<URLTAG); // Set some vars fLogConnID = 0; fStreamid = 1; fConnected = 1; // Replies are processed asynchronously SetAsync(fUnsolMsgHandler); // We are done return fLogConnID; } //_____________________________________________________________________________ void XrdProofPhyConn::Close(const char *) { // Close the connection. // Make sure we are connected if (!fConnected) return; // Close connection if (fPhyConn) fPhyConn->Disconnect(); // Flag this action fConnected = 0; // We are done return; } //_____________________________________________________________________________ void XrdProofPhyConn::SetAsync(XrdClientAbsUnsolMsgHandler *uh) { // Set handler of unsolicited responses if (fPhyConn) fPhyConn->UnsolicitedMsgHandler = uh; } //_____________________________________________________________________________ XrdClientMessage *XrdProofPhyConn::ReadMsg() { // Pickup message from the queue return (fPhyConn ? fPhyConn->ReadMessage(fStreamid) : (XrdClientMessage *)0); } //_____________________________________________________________________________ bool XrdProofPhyConn::GetAccessToSrv() { // Gets access to the connected server. // The login and authorization steps are performed here. XPDLOC(ALL, "PhyConn::GetAccessToSrv") // Now we are connected and we ask for the kind of the server { XrdClientPhyConnLocker pcl(fPhyConn); fServerType = DoHandShake(); } switch (fServerType) { case kSTXProofd: TRACE(DBG, "found server at "<<URLTAG); // Now we can start the reader thread in the physical connection, if needed fPhyConn->StartReader(); fPhyConn->fServerType = kSTBaseXrootd; break; case kSTError: TRACE(XERR, "handShake failed with server "<<URLTAG); Close(); return 0; case kSTProofd: case kSTNone: default: TRACE(XERR, "server at "<<URLTAG<< " is unknown : protocol error"); Close(); return 0; } // Execute a login if (fPhyConn->IsLogged() != kNo) { TRACE(XERR, "client already logged-in at "<<URLTAG<<" (!): protocol error!"); return 0; } // Login return Login(); } //_____________________________________________________________________________ int XrdProofPhyConn::WriteRaw(const void *buf, int len) { // Low level write call if (fPhyConn) return fPhyConn->WriteRaw(buf, len); // No connection open return -1; } //_____________________________________________________________________________ int XrdProofPhyConn::ReadRaw(void *buf, int len) { // Low level write call if (fPhyConn) return fPhyConn->ReadRaw(buf, len); // No connection open return -1; } <|endoftext|>
<commit_before>// @(#)root/proofx:$Id$ // Author: Gerardo Ganis 12/12/2005 /************************************************************************* * Copyright (C) 1995-2005, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TXSocketHandler // // // // Input handler for xproofd sockets. These sockets cannot be directly // // monitored on their descriptor, because the reading activity goes via // // the reader thread. This class allows to handle this problem. // // // ////////////////////////////////////////////////////////////////////////// #include "TMonitor.h" #include "TProof.h" #include "TSlave.h" #include "TXSocketHandler.h" #include "TXHandler.h" #include "TList.h" ClassImp(TXSocketHandler) // Unique instance of the socket input handler TXSocketHandler *TXSocketHandler::fgSocketHandler = 0; //______________________________________________________________________________ Bool_t TXSocketHandler::Notify() { // Set readiness on the monitor if (gDebug > 2) TXSocket::fgPipe.DumpReadySock(); // Get the socket TXSocket *s = TXSocket::fgPipe.GetLastReady(); if (gDebug > 2) Info("Notify", "ready socket %p (%s) (input socket: %p)", s, (s ? s->GetTitle() : "***undef***"), fInputSock); // If empty, nothing to do if (!s) { Warning("Notify","socket-ready list is empty!"); return kTRUE; } // Handle this input s->fHandler->HandleInput(); // We are done return kTRUE; } //_______________________________________________________________________ TXSocketHandler *TXSocketHandler::GetSocketHandler(TFileHandler *h, TSocket *s) { // Get an instance of the input socket handler with 'h' as handler, // connected to socket 's'. // Create the instance, if not already existing if (!fgSocketHandler) fgSocketHandler = new TXSocketHandler(h, s); else if (h && s) fgSocketHandler->SetHandler(h, s); return fgSocketHandler; } <commit_msg>Add file descriptor number in debug statement<commit_after>// @(#)root/proofx:$Id$ // Author: Gerardo Ganis 12/12/2005 /************************************************************************* * Copyright (C) 1995-2005, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TXSocketHandler // // // // Input handler for xproofd sockets. These sockets cannot be directly // // monitored on their descriptor, because the reading activity goes via // // the reader thread. This class allows to handle this problem. // // // ////////////////////////////////////////////////////////////////////////// #include "TMonitor.h" #include "TProof.h" #include "TSlave.h" #include "TXSocketHandler.h" #include "TXHandler.h" #include "TList.h" ClassImp(TXSocketHandler) // Unique instance of the socket input handler TXSocketHandler *TXSocketHandler::fgSocketHandler = 0; //______________________________________________________________________________ Bool_t TXSocketHandler::Notify() { // Set readiness on the monitor if (gDebug > 2) TXSocket::fgPipe.DumpReadySock(); // Get the socket TXSocket *s = TXSocket::fgPipe.GetLastReady(); if (gDebug > 2) Info("Notify", "ready socket %p (%s) (input socket: %p) (fFileNum: %d)", s, (s ? s->GetTitle() : "***undef***"), fInputSock, fFileNum); // If empty, nothing to do if (!s) { Warning("Notify","socket-ready list is empty!"); return kTRUE; } // Handle this input s->fHandler->HandleInput(); // We are done return kTRUE; } //_______________________________________________________________________ TXSocketHandler *TXSocketHandler::GetSocketHandler(TFileHandler *h, TSocket *s) { // Get an instance of the input socket handler with 'h' as handler, // connected to socket 's'. // Create the instance, if not already existing if (!fgSocketHandler) fgSocketHandler = new TXSocketHandler(h, s); else if (h && s) fgSocketHandler->SetHandler(h, s); return fgSocketHandler; } <|endoftext|>
<commit_before>/*************************************************************************** wpeditaccount.cpp - description ------------------- begin : Fri Apr 26 2002 copyright : (C) 2002 by Gav Wood email : gav@kde.org Based on code from : (C) 2002 by Duncan Mac-Vicar Prett email : duncan@kde.org ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ // Standard Unix Includes #include <unistd.h> // QT Includes #include <qcheckbox.h> #include <qfile.h> // KDE Includes #include <kdebug.h> #include <klocale.h> #include <kurlrequester.h> #include <knuminput.h> #include <klineedit.h> #include <kmessagebox.h> #include <kconfig.h> #include <kapplication.h> #include <kstandarddirs.h> // Kopete Includes #include <addcontactpage.h> // Local Includes #include "wpaccount.h" #include "wpeditaccount.h" #include "wpprotocol.h" WPEditAccount::WPEditAccount(QWidget *parent, Kopete::Account *theAccount) : QWidget(parent), KopeteEditAccountWidget(theAccount) { setupUi(this); kDebug(14170) << "WPEditAccount::WPEditAccount(<parent>, <theAccount>)"; mProtocol = WPProtocol::protocol(); QString tmpSmbcPath = KStandardDirs::findExe("smbclient"); if(account()) { mHostName->setText(account()->accountId()); // mAutoConnect->setChecked(account()->excludeConnect()); mHostName->setReadOnly(true); KGlobal::config()->setGroup("WinPopup"); mHostCheckFreq->setValue(KGlobal::config()->readEntry("HostCheckFreq", 60)); mSmbcPath->setURL(KGlobal::config()->readEntry("SmbcPath", tmpSmbcPath)); } else { // no QT/KDE function? GF QString theHostName = QString(); char *tmp = new char[255]; if (tmp != 0) { gethostname(tmp, 255); theHostName = tmp; if (theHostName.contains('.') != 0) theHostName.remove(theHostName.indexOf('.'), theHostName.length()); theHostName = theHostName.toUpper(); } if (!theHostName.isEmpty()) mHostName->setText(theHostName); else mHostName->setText("LOCALHOST"); mHostCheckFreq->setValue(60); mSmbcPath->setURL(tmpSmbcPath); } show(); } void WPEditAccount::installSamba() { mProtocol->installSamba(); } bool WPEditAccount::validateData() { kDebug(14170) << "WPEditAccount::validateData()"; if(mHostName->text().isEmpty()) { KMessageBox::sorry(this, i18n("<qt>You must enter a valid screen name.</qt>"), i18n("WinPopup")); return false; } QFile smbc(mSmbcPath->url()); if (!smbc.exists()) { KMessageBox::sorry(this, i18n("<qt>You must enter a valid smbclient path.</qt>"), i18n("WinPopup")); return false; } return true; } void WPEditAccount::writeConfig() { KGlobal::config()->setGroup("WinPopup"); KGlobal::config()->writeEntry("SmbcPath", mSmbcPath->url()); KGlobal::config()->writeEntry("HostCheckFreq", mHostCheckFreq->text()); } Kopete::Account *WPEditAccount::apply() { kDebug(14170) << "WPEditAccount::apply()"; if(!account()) setAccount(new WPAccount(mProtocol, mHostName->text())); // account()->setExcludeConnect(mAutoConnect->isChecked()); writeConfig(); mProtocol->settingsChanged(); return account(); } #include "wpeditaccount.moc" // vim: set noet ts=4 sts=4 sw=4: // kate: tab-width 4; indent-width 4; replace-trailing-space-save on; <commit_msg>more KUrl shenanigans<commit_after>/*************************************************************************** wpeditaccount.cpp - description ------------------- begin : Fri Apr 26 2002 copyright : (C) 2002 by Gav Wood email : gav@kde.org Based on code from : (C) 2002 by Duncan Mac-Vicar Prett email : duncan@kde.org ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ // Standard Unix Includes #include <unistd.h> // QT Includes #include <qcheckbox.h> #include <qfile.h> // KDE Includes #include <kdebug.h> #include <klocale.h> #include <kurlrequester.h> #include <knuminput.h> #include <klineedit.h> #include <kmessagebox.h> #include <kconfig.h> #include <kapplication.h> #include <kstandarddirs.h> // Kopete Includes #include <addcontactpage.h> // Local Includes #include "wpaccount.h" #include "wpeditaccount.h" #include "wpprotocol.h" WPEditAccount::WPEditAccount(QWidget *parent, Kopete::Account *theAccount) : QWidget(parent), KopeteEditAccountWidget(theAccount) { setupUi(this); kDebug(14170) << "WPEditAccount::WPEditAccount(<parent>, <theAccount>)"; mProtocol = WPProtocol::protocol(); QString tmpSmbcPath = KStandardDirs::findExe("smbclient"); if(account()) { mHostName->setText(account()->accountId()); // mAutoConnect->setChecked(account()->excludeConnect()); mHostName->setReadOnly(true); KGlobal::config()->setGroup("WinPopup"); mHostCheckFreq->setValue(KGlobal::config()->readEntry("HostCheckFreq", 60)); mSmbcPath->setUrl(KGlobal::config()->readEntry("SmbcPath", tmpSmbcPath)); } else { // no QT/KDE function? GF QString theHostName = QString(); char *tmp = new char[255]; if (tmp != 0) { gethostname(tmp, 255); theHostName = tmp; if (theHostName.contains('.') != 0) theHostName.remove(theHostName.indexOf('.'), theHostName.length()); theHostName = theHostName.toUpper(); } if (!theHostName.isEmpty()) mHostName->setText(theHostName); else mHostName->setText("LOCALHOST"); mHostCheckFreq->setValue(60); mSmbcPath->setUrl(tmpSmbcPath); } show(); } void WPEditAccount::installSamba() { mProtocol->installSamba(); } bool WPEditAccount::validateData() { kDebug(14170) << "WPEditAccount::validateData()"; if(mHostName->text().isEmpty()) { KMessageBox::sorry(this, i18n("<qt>You must enter a valid screen name.</qt>"), i18n("WinPopup")); return false; } QFile smbc(mSmbcPath->url().url()); if (!smbc.exists()) { KMessageBox::sorry(this, i18n("<qt>You must enter a valid smbclient path.</qt>"), i18n("WinPopup")); return false; } return true; } void WPEditAccount::writeConfig() { KGlobal::config()->setGroup("WinPopup"); KGlobal::config()->writeEntry("SmbcPath", mSmbcPath->url().url()); KGlobal::config()->writeEntry("HostCheckFreq", mHostCheckFreq->text()); } Kopete::Account *WPEditAccount::apply() { kDebug(14170) << "WPEditAccount::apply()"; if(!account()) setAccount(new WPAccount(mProtocol, mHostName->text())); // account()->setExcludeConnect(mAutoConnect->isChecked()); writeConfig(); mProtocol->settingsChanged(); return account(); } #include "wpeditaccount.moc" // vim: set noet ts=4 sts=4 sw=4: // kate: tab-width 4; indent-width 4; replace-trailing-space-save on; <|endoftext|>
<commit_before>/* * Copyright (C) 1999-2011 Insight Software Consortium * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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. */ #ifndef otbStreamingStatisticsMapFromLabelImageFilter_hxx #define otbStreamingStatisticsMapFromLabelImageFilter_hxx #include "otbStreamingStatisticsMapFromLabelImageFilter.h" #include "itkInputDataObjectIterator.h" #include "itkImageRegionIterator.h" #include "itkProgressReporter.h" #include "otbMacro.h" #include <cmath> namespace otb { template<class TInputVectorImage, class TLabelImage> PersistentStreamingStatisticsMapFromLabelImageFilter<TInputVectorImage, TLabelImage> ::PersistentStreamingStatisticsMapFromLabelImageFilter() { // first output is a copy of the image, DataObject created by // superclass // // allocate the data objects for the outputs which are // just decorators around pixel types typename PixelValueMapObjectType::Pointer output = static_cast<PixelValueMapObjectType*>(this->MakeOutput(1).GetPointer()); this->itk::ProcessObject::SetNthOutput(1, output.GetPointer()); this->Reset(); } template<class TInputVectorImage, class TLabelImage> typename itk::DataObject::Pointer PersistentStreamingStatisticsMapFromLabelImageFilter<TInputVectorImage, TLabelImage> ::MakeOutput(DataObjectPointerArraySizeType itkNotUsed(output)) { return static_cast<itk::DataObject*>(PixelValueMapObjectType::New().GetPointer()); } template<class TInputVectorImage, class TLabelImage> void PersistentStreamingStatisticsMapFromLabelImageFilter<TInputVectorImage, TLabelImage> ::SetInputLabelImage(const LabelImageType *input) { // Process object is not const-correct so the const_cast is required here this->itk::ProcessObject::SetNthInput(1, const_cast< LabelImageType * >( input ) ); } template<class TInputVectorImage, class TLabelImage> const typename PersistentStreamingStatisticsMapFromLabelImageFilter<TInputVectorImage, TLabelImage>::LabelImageType* PersistentStreamingStatisticsMapFromLabelImageFilter<TInputVectorImage, TLabelImage> ::GetInputLabelImage() { return static_cast< const TLabelImage * > (this->itk::ProcessObject::GetInput(1)); } template<class TInputVectorImage, class TLabelImage> typename PersistentStreamingStatisticsMapFromLabelImageFilter<TInputVectorImage, TLabelImage>::PixelValueMapType PersistentStreamingStatisticsMapFromLabelImageFilter<TInputVectorImage, TLabelImage> ::GetMeanValueMap() const { return m_MeanRadiometricValue; } template<class TInputVectorImage, class TLabelImage> typename PersistentStreamingStatisticsMapFromLabelImageFilter<TInputVectorImage, TLabelImage>::PixelValueMapType PersistentStreamingStatisticsMapFromLabelImageFilter<TInputVectorImage, TLabelImage> ::GetStandardDeviationValueMap() const { return m_StDevRadiometricValue; } template<class TInputVectorImage, class TLabelImage> typename PersistentStreamingStatisticsMapFromLabelImageFilter<TInputVectorImage, TLabelImage>::PixelValueMapType PersistentStreamingStatisticsMapFromLabelImageFilter<TInputVectorImage, TLabelImage> ::GetMinValueMap() const { return m_MinRadiometricValue; } template<class TInputVectorImage, class TLabelImage> typename PersistentStreamingStatisticsMapFromLabelImageFilter<TInputVectorImage, TLabelImage>::PixelValueMapType PersistentStreamingStatisticsMapFromLabelImageFilter<TInputVectorImage, TLabelImage> ::GetMaxValueMap() const { return m_MaxRadiometricValue; } template<class TInputVectorImage, class TLabelImage> typename PersistentStreamingStatisticsMapFromLabelImageFilter<TInputVectorImage, TLabelImage>::LabelPopulationMapType PersistentStreamingStatisticsMapFromLabelImageFilter<TInputVectorImage, TLabelImage> ::GetLabelPopulationMap() const { return m_LabelPopulation; } template<class TInputVectorImage, class TLabelImage> void PersistentStreamingStatisticsMapFromLabelImageFilter<TInputVectorImage, TLabelImage> ::GenerateOutputInformation() { Superclass::GenerateOutputInformation(); if (this->GetInput()) { this->GetOutput()->CopyInformation(this->GetInput()); this->GetOutput()->SetLargestPossibleRegion(this->GetInput()->GetLargestPossibleRegion()); if (this->GetOutput()->GetRequestedRegion().GetNumberOfPixels() == 0) { this->GetOutput()->SetRequestedRegion(this->GetOutput()->GetLargestPossibleRegion()); } } } template<class TInputVectorImage, class TLabelImage> void PersistentStreamingStatisticsMapFromLabelImageFilter<TInputVectorImage, TLabelImage> ::AllocateOutputs() { // This is commented to prevent the streaming of the whole image for the first stream strip // It shall not cause any problem because the output image of this filter is not intended to be used. //InputImagePointer image = const_cast< TInputImage * >( this->GetInput() ); //this->GraftOutput( image ); // Nothing that needs to be allocated for the remaining outputs } template<class TInputVectorImage, class TLabelImage> void PersistentStreamingStatisticsMapFromLabelImageFilter<TInputVectorImage, TLabelImage> ::Synthetize() { // Update temporary accumulator AccumulatorMapType outputAcc; for (auto const& threadAccMap: m_AccumulatorMaps) { for(auto const& it: threadAccMap) { const LabelPixelType label = it.first; if (outputAcc.count(label) <= 0) { AccumulatorType newAcc(it.second); outputAcc[label] = newAcc; } else { outputAcc[label].Update(it.second); } } } // Publish output maps for(auto& it: outputAcc) { const LabelPixelType label = it.first; const double count = it.second.GetCount(); const RealVectorPixelType sum = it.second.GetSum(); const RealVectorPixelType sqSum = it.second.GetSqSum(); // Count m_LabelPopulation[label] = count; // Mean & stdev RealVectorPixelType mean (sum); RealVectorPixelType std (sqSum); for (unsigned int band = 0 ; band < mean.GetSize() ; band++) { // Mean mean[band] /= count; // Unbiased standard deviation (not sure unbiased is usefull here) const double variance = (sqSum[band] - (sum[band] * mean[band])) / (count - 1); std[band] = std::sqrt(variance); } m_MeanRadiometricValue[label] = mean; m_StDevRadiometricValue[label] = std; // Min & max m_MinRadiometricValue[label] = it.second.GetMin(); m_MaxRadiometricValue[label] = it.second.GetMax(); } } template<class TInputVectorImage, class TLabelImage> void PersistentStreamingStatisticsMapFromLabelImageFilter<TInputVectorImage, TLabelImage> ::Reset() { m_AccumulatorMaps.clear(); m_MeanRadiometricValue.clear(); m_StDevRadiometricValue.clear(); m_MinRadiometricValue.clear(); m_MaxRadiometricValue.clear(); m_LabelPopulation.clear(); m_AccumulatorMaps.resize(this->GetNumberOfThreads()); } template<class TInputVectorImage, class TLabelImage> void PersistentStreamingStatisticsMapFromLabelImageFilter<TInputVectorImage, TLabelImage> ::GenerateInputRequestedRegion() { // The Requested Regions of all the inputs are set to their Largest Possible Regions this->itk::ProcessObject::GenerateInputRequestedRegion(); // Iteration over all the inputs of the current filter (this) for( itk::InputDataObjectIterator it( this ); !it.IsAtEnd(); it++ ) { // Check whether the input is an image of the appropriate dimension // dynamic_cast of all the input images as itk::ImageBase objects // in order to pass the if ( input ) test whatever the inputImageType (vectorImage or labelImage) ImageBaseType * input = dynamic_cast< ImageBaseType *>( it.GetInput() ); if ( input ) { // Use the function object RegionCopier to copy the output region // to the input. The default region copier has default implementations // to handle the cases where the input and output are the same // dimension, the input a higher dimension than the output, and the // input a lower dimension than the output. InputImageRegionType inputRegion; this->CallCopyOutputRegionToInputRegion( inputRegion, this->GetOutput()->GetRequestedRegion() ); input->SetRequestedRegion(inputRegion); } } } template<class TInputVectorImage, class TLabelImage> void PersistentStreamingStatisticsMapFromLabelImageFilter<TInputVectorImage, TLabelImage> ::ThreadedGenerateData(const RegionType& outputRegionForThread, itk::ThreadIdType threadId ) { /** * Grab the input */ InputVectorImagePointer inputPtr = const_cast<TInputVectorImage *>(this->GetInput()); LabelImagePointer labelInputPtr = const_cast<TLabelImage *>(this->GetInputLabelImage()); itk::ImageRegionConstIterator<TInputVectorImage> inIt(inputPtr, outputRegionForThread); itk::ImageRegionConstIterator<TLabelImage> labelIt(labelInputPtr, outputRegionForThread); itk::ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels()); typename VectorImageType::PixelType value; typename LabelImageType::PixelType label; // do the work for (inIt.GoToBegin(), labelIt.GoToBegin(); !inIt.IsAtEnd() && !labelIt.IsAtEnd(); ++inIt, ++labelIt) { value = inIt.Get(); label = labelIt.Get(); // Update the accumulator if (m_AccumulatorMaps[threadId].count(label) <= 0) //add new element to the map { AccumulatorType newAcc(value); m_AccumulatorMaps[threadId][label] = newAcc; } else { m_AccumulatorMaps[threadId][label].Update(value); } progress.CompletedPixel(); } } template<class TInputVectorImage, class TLabelImage> void PersistentStreamingStatisticsMapFromLabelImageFilter<TInputVectorImage, TLabelImage> ::PrintSelf(std::ostream& os, itk::Indent indent) const { Superclass::PrintSelf(os, indent); } } // end namespace otb #endif <commit_msg>PERF: reduce copying in StreamingStatisticsMapFromLabelImageFilter<commit_after>/* * Copyright (C) 1999-2011 Insight Software Consortium * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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. */ #ifndef otbStreamingStatisticsMapFromLabelImageFilter_hxx #define otbStreamingStatisticsMapFromLabelImageFilter_hxx #include "otbStreamingStatisticsMapFromLabelImageFilter.h" #include "itkInputDataObjectIterator.h" #include "itkImageRegionIterator.h" #include "itkProgressReporter.h" #include "otbMacro.h" #include <cmath> namespace otb { template<class TInputVectorImage, class TLabelImage> PersistentStreamingStatisticsMapFromLabelImageFilter<TInputVectorImage, TLabelImage> ::PersistentStreamingStatisticsMapFromLabelImageFilter() { // first output is a copy of the image, DataObject created by // superclass // // allocate the data objects for the outputs which are // just decorators around pixel types typename PixelValueMapObjectType::Pointer output = static_cast<PixelValueMapObjectType*>(this->MakeOutput(1).GetPointer()); this->itk::ProcessObject::SetNthOutput(1, output.GetPointer()); this->Reset(); } template<class TInputVectorImage, class TLabelImage> typename itk::DataObject::Pointer PersistentStreamingStatisticsMapFromLabelImageFilter<TInputVectorImage, TLabelImage> ::MakeOutput(DataObjectPointerArraySizeType itkNotUsed(output)) { return static_cast<itk::DataObject*>(PixelValueMapObjectType::New().GetPointer()); } template<class TInputVectorImage, class TLabelImage> void PersistentStreamingStatisticsMapFromLabelImageFilter<TInputVectorImage, TLabelImage> ::SetInputLabelImage(const LabelImageType *input) { // Process object is not const-correct so the const_cast is required here this->itk::ProcessObject::SetNthInput(1, const_cast< LabelImageType * >( input ) ); } template<class TInputVectorImage, class TLabelImage> const typename PersistentStreamingStatisticsMapFromLabelImageFilter<TInputVectorImage, TLabelImage>::LabelImageType* PersistentStreamingStatisticsMapFromLabelImageFilter<TInputVectorImage, TLabelImage> ::GetInputLabelImage() { return static_cast< const TLabelImage * > (this->itk::ProcessObject::GetInput(1)); } template<class TInputVectorImage, class TLabelImage> typename PersistentStreamingStatisticsMapFromLabelImageFilter<TInputVectorImage, TLabelImage>::PixelValueMapType PersistentStreamingStatisticsMapFromLabelImageFilter<TInputVectorImage, TLabelImage> ::GetMeanValueMap() const { return m_MeanRadiometricValue; } template<class TInputVectorImage, class TLabelImage> typename PersistentStreamingStatisticsMapFromLabelImageFilter<TInputVectorImage, TLabelImage>::PixelValueMapType PersistentStreamingStatisticsMapFromLabelImageFilter<TInputVectorImage, TLabelImage> ::GetStandardDeviationValueMap() const { return m_StDevRadiometricValue; } template<class TInputVectorImage, class TLabelImage> typename PersistentStreamingStatisticsMapFromLabelImageFilter<TInputVectorImage, TLabelImage>::PixelValueMapType PersistentStreamingStatisticsMapFromLabelImageFilter<TInputVectorImage, TLabelImage> ::GetMinValueMap() const { return m_MinRadiometricValue; } template<class TInputVectorImage, class TLabelImage> typename PersistentStreamingStatisticsMapFromLabelImageFilter<TInputVectorImage, TLabelImage>::PixelValueMapType PersistentStreamingStatisticsMapFromLabelImageFilter<TInputVectorImage, TLabelImage> ::GetMaxValueMap() const { return m_MaxRadiometricValue; } template<class TInputVectorImage, class TLabelImage> typename PersistentStreamingStatisticsMapFromLabelImageFilter<TInputVectorImage, TLabelImage>::LabelPopulationMapType PersistentStreamingStatisticsMapFromLabelImageFilter<TInputVectorImage, TLabelImage> ::GetLabelPopulationMap() const { return m_LabelPopulation; } template<class TInputVectorImage, class TLabelImage> void PersistentStreamingStatisticsMapFromLabelImageFilter<TInputVectorImage, TLabelImage> ::GenerateOutputInformation() { Superclass::GenerateOutputInformation(); if (this->GetInput()) { this->GetOutput()->CopyInformation(this->GetInput()); this->GetOutput()->SetLargestPossibleRegion(this->GetInput()->GetLargestPossibleRegion()); if (this->GetOutput()->GetRequestedRegion().GetNumberOfPixels() == 0) { this->GetOutput()->SetRequestedRegion(this->GetOutput()->GetLargestPossibleRegion()); } } } template<class TInputVectorImage, class TLabelImage> void PersistentStreamingStatisticsMapFromLabelImageFilter<TInputVectorImage, TLabelImage> ::AllocateOutputs() { // This is commented to prevent the streaming of the whole image for the first stream strip // It shall not cause any problem because the output image of this filter is not intended to be used. //InputImagePointer image = const_cast< TInputImage * >( this->GetInput() ); //this->GraftOutput( image ); // Nothing that needs to be allocated for the remaining outputs } template<class TInputVectorImage, class TLabelImage> void PersistentStreamingStatisticsMapFromLabelImageFilter<TInputVectorImage, TLabelImage> ::Synthetize() { // Update temporary accumulator AccumulatorMapType outputAcc; auto endAcc = outputAcc.end(); for (auto const& threadAccMap: m_AccumulatorMaps) { for(auto const& it: threadAccMap) { const LabelPixelType label = it.first; auto itAcc = outputAcc.find(label); if (itAcc == endAcc) { outputAcc.emplace(label, AccumulatorType(it.second)); } else { itAcc->second.Update(it.second); } } } // Publish output maps for(auto& it: outputAcc) { const LabelPixelType label = it.first; const double count = it.second.GetCount(); const RealVectorPixelType sum = it.second.GetSum(); const RealVectorPixelType sqSum = it.second.GetSqSum(); // Count m_LabelPopulation[label] = count; // Mean & stdev RealVectorPixelType mean (sum); RealVectorPixelType std (sqSum); for (unsigned int band = 0 ; band < mean.GetSize() ; band++) { // Mean mean[band] /= count; // Unbiased standard deviation (not sure unbiased is usefull here) const double variance = (sqSum[band] - (sum[band] * mean[band])) / (count - 1); std[band] = std::sqrt(variance); } m_MeanRadiometricValue[label] = mean; m_StDevRadiometricValue[label] = std; // Min & max m_MinRadiometricValue[label] = it.second.GetMin(); m_MaxRadiometricValue[label] = it.second.GetMax(); } } template<class TInputVectorImage, class TLabelImage> void PersistentStreamingStatisticsMapFromLabelImageFilter<TInputVectorImage, TLabelImage> ::Reset() { m_AccumulatorMaps.clear(); m_MeanRadiometricValue.clear(); m_StDevRadiometricValue.clear(); m_MinRadiometricValue.clear(); m_MaxRadiometricValue.clear(); m_LabelPopulation.clear(); m_AccumulatorMaps.resize(this->GetNumberOfThreads()); } template<class TInputVectorImage, class TLabelImage> void PersistentStreamingStatisticsMapFromLabelImageFilter<TInputVectorImage, TLabelImage> ::GenerateInputRequestedRegion() { // The Requested Regions of all the inputs are set to their Largest Possible Regions this->itk::ProcessObject::GenerateInputRequestedRegion(); // Iteration over all the inputs of the current filter (this) for( itk::InputDataObjectIterator it( this ); !it.IsAtEnd(); it++ ) { // Check whether the input is an image of the appropriate dimension // dynamic_cast of all the input images as itk::ImageBase objects // in order to pass the if ( input ) test whatever the inputImageType (vectorImage or labelImage) ImageBaseType * input = dynamic_cast< ImageBaseType *>( it.GetInput() ); if ( input ) { // Use the function object RegionCopier to copy the output region // to the input. The default region copier has default implementations // to handle the cases where the input and output are the same // dimension, the input a higher dimension than the output, and the // input a lower dimension than the output. InputImageRegionType inputRegion; this->CallCopyOutputRegionToInputRegion( inputRegion, this->GetOutput()->GetRequestedRegion() ); input->SetRequestedRegion(inputRegion); } } } template<class TInputVectorImage, class TLabelImage> void PersistentStreamingStatisticsMapFromLabelImageFilter<TInputVectorImage, TLabelImage> ::ThreadedGenerateData(const RegionType& outputRegionForThread, itk::ThreadIdType threadId ) { /** * Grab the input */ InputVectorImagePointer inputPtr = const_cast<TInputVectorImage *>(this->GetInput()); LabelImagePointer labelInputPtr = const_cast<TLabelImage *>(this->GetInputLabelImage()); itk::ImageRegionConstIterator<TInputVectorImage> inIt(inputPtr, outputRegionForThread); itk::ImageRegionConstIterator<TLabelImage> labelIt(labelInputPtr, outputRegionForThread); itk::ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels()); auto &acc = m_AccumulatorMaps[threadId]; auto endAcc = acc.end(); // do the work for (inIt.GoToBegin(), labelIt.GoToBegin(); !inIt.IsAtEnd() && !labelIt.IsAtEnd(); ++inIt, ++labelIt) { const auto &value = inIt.Get(); auto label = labelIt.Get(); // Update the accumulator auto itAcc = acc.find(label); if (itAcc == endAcc) { acc.emplace(label, AccumulatorType(value)); } else { itAcc->second.Update(value); } progress.CompletedPixel(); } } template<class TInputVectorImage, class TLabelImage> void PersistentStreamingStatisticsMapFromLabelImageFilter<TInputVectorImage, TLabelImage> ::PrintSelf(std::ostream& os, itk::Indent indent) const { Superclass::PrintSelf(os, indent); } } // end namespace otb #endif <|endoftext|>
<commit_before>#include "config.h" #include "WebMimeRegistryImpl.h" #include "third_party/WebKit/public/platform/WebString.h" #include <wtf/text/StringHash.h> #include <wtf/text/WTFStringUtil.h> #include <wtf/HashMap.h> namespace content { WebMimeRegistryImpl::WebMimeRegistryImpl() { m_supportedMIMETypes = nullptr; m_supportedImageResourceMIMETypes = nullptr; m_supportedJavaScriptMIMETypes = nullptr; m_supportedNonImageMIMETypes = nullptr; m_mimetypeMap = nullptr; } WebMimeRegistryImpl::~WebMimeRegistryImpl() { if (m_supportedMIMETypes) delete m_supportedMIMETypes; m_supportedMIMETypes = nullptr; if (m_supportedImageResourceMIMETypes) delete m_supportedImageResourceMIMETypes; m_supportedImageResourceMIMETypes = nullptr; if (m_supportedJavaScriptMIMETypes) delete m_supportedJavaScriptMIMETypes; m_supportedJavaScriptMIMETypes = nullptr; if (m_supportedNonImageMIMETypes) delete m_supportedNonImageMIMETypes; m_supportedNonImageMIMETypes = nullptr; if (m_mimetypeMap) delete m_mimetypeMap; m_mimetypeMap = nullptr; } blink::WebMimeRegistry::SupportsType WebMimeRegistryImpl::supportsImagePrefixedMIMEType(const blink::WebString& mimeType) { return blink::WebMimeRegistry::IsNotSupported; } static WTF::String checkAndEnsureBit8String(const blink::WebString& ext) { if (ext.isNull() || ext.isEmpty()) return WTF::String(); WTF::String extension = ext; if (!extension.is8Bit()) { CString utf8String = extension.utf8(); extension = WTF::String(utf8String.data(), utf8String.length()); } return extension; } // WebMimeRegistry methods: blink::WebMimeRegistry::SupportsType WebMimeRegistryImpl::supportsMIMEType(const blink::WebString& ext) { WTF::String extension = checkAndEnsureBit8String(ext); if (extension.isEmpty()) return blink::WebMimeRegistry::IsSupported; extension = extension.lower(); if (!m_supportedMIMETypes) { m_supportedMIMETypes = new WTF::HashSet<WTF::String>(); static const char* types[] = { "text/plain", "text/html", "text/xml", "application/x-javascript", "application/xhtml+xml", "image/svg+xml", "image/jpeg", "image/png", "image/tiff", "image/ico", "image/bmp", "image/gif", "application/x-shockwave-flash", }; for (size_t i = 0; i < WTF_ARRAY_LENGTH(types); ++i) m_supportedMIMETypes->add(types[i]); } return m_supportedMIMETypes->contains(extension) ? blink::WebMimeRegistry::IsSupported : blink::WebMimeRegistry::IsNotSupported; } blink::WebMimeRegistry::SupportsType WebMimeRegistryImpl::supportsImageMIMEType(const blink::WebString& ext) { WTF::String extension = checkAndEnsureBit8String(ext); if (extension.isEmpty()) return blink::WebMimeRegistry::IsNotSupported; extension = extension.lower(); if (!m_supportedImageResourceMIMETypes) { m_supportedImageResourceMIMETypes = new WTF::HashSet<WTF::String>(); static const char* types[] = { //"image/svg+xml", "image/jpeg", "image/png", "image/tiff", //"application/x-javascript", "image/ico", "image/bmp", "image/gif", }; for (size_t i = 0; i < WTF_ARRAY_LENGTH(types); ++i) m_supportedImageResourceMIMETypes->add(types[i]); } return m_supportedImageResourceMIMETypes->contains(extension) ? blink::WebMimeRegistry::IsSupported : blink::WebMimeRegistry::IsNotSupported; } blink::WebMimeRegistry::SupportsType WebMimeRegistryImpl::supportsJavaScriptMIMEType(const blink::WebString& ext) { WTF::String extension = checkAndEnsureBit8String(ext); if (extension.isEmpty()) return blink::WebMimeRegistry::IsNotSupported; extension = extension.lower(); if (!m_supportedJavaScriptMIMETypes) { m_supportedJavaScriptMIMETypes = new WTF::HashSet<WTF::String>(); /* Mozilla 1.8 and WinIE 7 both accept text/javascript and text/ecmascript. Mozilla 1.8 accepts application/javascript, application/ecmascript, and application/x-javascript, but WinIE 7 doesn't. WinIE 7 accepts text/javascript1.1 - text/javascript1.3, text/jscript, and text/livescript, but Mozilla 1.8 doesn't. Mozilla 1.8 allows leading and trailing whitespace, but WinIE 7 doesn't. Mozilla 1.8 and WinIE 7 both accept the empty string, but neither accept a whitespace-only string. We want to accept all the values that either of these browsers accept, but not other values. */ static const char* types[] = { "text/javascript", "text/ecmascript", "application/javascript", "application/ecmascript", "application/x-javascript", "text/javascript1.1", "text/javascript1.2", "text/javascript1.3", "text/jscript", "text/livescript", }; for (size_t i = 0; i < WTF_ARRAY_LENGTH(types); ++i) m_supportedJavaScriptMIMETypes->add(types[i]); } return m_supportedJavaScriptMIMETypes->contains(extension) ? blink::WebMimeRegistry::IsSupported : blink::WebMimeRegistry::IsNotSupported; } blink::WebMimeRegistry::SupportsType WebMimeRegistryImpl::supportsMediaMIMEType( const blink::WebString&, const blink::WebString&, const blink::WebString&) { return blink::WebMimeRegistry::IsNotSupported; } bool WebMimeRegistryImpl::supportsMediaSourceMIMEType(const blink::WebString&, const blink::WebString&) { return blink::WebMimeRegistry::IsNotSupported; } blink::WebMimeRegistry::SupportsType WebMimeRegistryImpl::supportsNonImageMIMEType(const blink::WebString& ext) { WTF::String extension = checkAndEnsureBit8String(ext); if (extension.isEmpty()) return blink::WebMimeRegistry::IsNotSupported; extension = extension.lower(); if (!m_supportedNonImageMIMETypes) { m_supportedNonImageMIMETypes = new HashSet<String>(); static const char* types[] = { "text/html", "text/xml", "text/xsl", "text/plain", "text/", "application/xml", "application/xhtml+xml", "application/vnd.wap.xhtml+xml", "application/rss+xml", "application/atom+xml", "application/json", //#if ENABLE(SVG) "image/svg+xml", //#endif "application/x-ftp-directory", "multipart/x-mixed-replace", //"application/x-shockwave-flash", // Note: ADDING a new type here will probably render it as HTML. This can // result in cross-site scripting. }; //COMPILE_ASSERT(sizeof(types) / sizeof(types[0]) <= 16, "nonimage_mime_types_must_be_less_than_or_equal_to_16"); for (size_t i = 0; i < WTF_ARRAY_LENGTH(types); ++i) m_supportedNonImageMIMETypes->add(types[i]); } return m_supportedNonImageMIMETypes->contains(extension) ? blink::WebMimeRegistry::IsSupported : blink::WebMimeRegistry::IsNotSupported; } void WebMimeRegistryImpl::ensureMimeTypeMap() { if (m_mimetypeMap) return; m_mimetypeMap = new WTF::HashMap<WTF::String, WTF::String>(); //fill with initial values m_mimetypeMap->add("txt", "text/plain"); m_mimetypeMap->add("pdf", "application/pdf"); m_mimetypeMap->add("ps", "application/postscript"); m_mimetypeMap->add("html", "text/html"); m_mimetypeMap->add("htm", "text/html"); m_mimetypeMap->add("xml", "text/xml"); m_mimetypeMap->add("xsl", "text/xsl"); m_mimetypeMap->add("js", "application/x-javascript"); m_mimetypeMap->add("xhtml", "application/xhtml+xml"); m_mimetypeMap->add("rss", "application/rss+xml"); m_mimetypeMap->add("webarchive", "application/x-webarchive"); m_mimetypeMap->add("svg", "image/svg+xml"); m_mimetypeMap->add("svgz", "image/svg+xml"); m_mimetypeMap->add("jpg", "image/jpeg"); m_mimetypeMap->add("jpeg", "image/jpeg"); m_mimetypeMap->add("png", "image/png"); m_mimetypeMap->add("gif", "image/gif"); m_mimetypeMap->add("tif", "image/tiff"); m_mimetypeMap->add("tiff", "image/tiff"); m_mimetypeMap->add("ico", "image/ico"); m_mimetypeMap->add("cur", "image/ico"); m_mimetypeMap->add("bmp", "image/bmp"); m_mimetypeMap->add("wml", "text/vnd.wap.wml"); m_mimetypeMap->add("wmlc", "application/vnd.wap.wmlc"); m_mimetypeMap->add("swf", "application/x-shockwave-flash"); m_mimetypeMap->add("mp4", "video/mp4"); m_mimetypeMap->add("ogg", "video/ogg"); m_mimetypeMap->add("webm", "video/webm"); } blink::WebString WebMimeRegistryImpl::mimeTypeForExtension(const blink::WebString& ext) { ASSERT(isMainThread()); if (ext.isNull() || ext.isEmpty()) return blink::WebString(); ensureMimeTypeMap(); WTF::String extension = WTF::ensureStringToUTF8String(ext); extension = extension.lower(); WTF::String result = m_mimetypeMap->get(extension); return result; } blink::WebString WebMimeRegistryImpl::wellKnownMimeTypeForExtension(const blink::WebString& ext) { return mimeTypeForExtension(ext); } blink::WebString WebMimeRegistryImpl::mimeTypeFromFile(const blink::WebString& ext) { return blink::WebString(); } blink::WebString WebMimeRegistryImpl::extensionFormimeType(const blink::WebString& ext) { ASSERT(isMainThread()); if (ext.isNull() || ext.isEmpty()) return blink::WebString(); ensureMimeTypeMap(); for (WTF::HashMap<WTF::String, WTF::String>::iterator it = m_mimetypeMap->begin(); it != m_mimetypeMap->end(); ++it) { if (WTF::equalIgnoringCase(it->value, String(ext))) return it->key; } return blink::WebString(); } } // namespace content<commit_msg>* 加入mht支持<commit_after>#include "config.h" #include "WebMimeRegistryImpl.h" #include "third_party/WebKit/public/platform/WebString.h" #include <wtf/text/StringHash.h> #include <wtf/text/WTFStringUtil.h> #include <wtf/HashMap.h> namespace content { WebMimeRegistryImpl::WebMimeRegistryImpl() { m_supportedMIMETypes = nullptr; m_supportedImageResourceMIMETypes = nullptr; m_supportedJavaScriptMIMETypes = nullptr; m_supportedNonImageMIMETypes = nullptr; m_mimetypeMap = nullptr; } WebMimeRegistryImpl::~WebMimeRegistryImpl() { if (m_supportedMIMETypes) delete m_supportedMIMETypes; m_supportedMIMETypes = nullptr; if (m_supportedImageResourceMIMETypes) delete m_supportedImageResourceMIMETypes; m_supportedImageResourceMIMETypes = nullptr; if (m_supportedJavaScriptMIMETypes) delete m_supportedJavaScriptMIMETypes; m_supportedJavaScriptMIMETypes = nullptr; if (m_supportedNonImageMIMETypes) delete m_supportedNonImageMIMETypes; m_supportedNonImageMIMETypes = nullptr; if (m_mimetypeMap) delete m_mimetypeMap; m_mimetypeMap = nullptr; } blink::WebMimeRegistry::SupportsType WebMimeRegistryImpl::supportsImagePrefixedMIMEType(const blink::WebString& mimeType) { return blink::WebMimeRegistry::IsNotSupported; } static WTF::String checkAndEnsureBit8String(const blink::WebString& ext) { if (ext.isNull() || ext.isEmpty()) return WTF::String(); WTF::String extension = ext; if (!extension.is8Bit()) { CString utf8String = extension.utf8(); extension = WTF::String(utf8String.data(), utf8String.length()); } return extension; } // WebMimeRegistry methods: blink::WebMimeRegistry::SupportsType WebMimeRegistryImpl::supportsMIMEType(const blink::WebString& ext) { WTF::String extension = checkAndEnsureBit8String(ext); if (extension.isEmpty()) return blink::WebMimeRegistry::IsSupported; extension = extension.lower(); if (!m_supportedMIMETypes) { m_supportedMIMETypes = new WTF::HashSet<WTF::String>(); static const char* types[] = { "text/plain", "text/html", "text/xml", "multipart/related", "application/x-javascript", "application/xhtml+xml", "image/svg+xml", "image/jpeg", "image/png", "image/tiff", "image/ico", "image/bmp", "image/gif", "application/x-shockwave-flash", }; for (size_t i = 0; i < WTF_ARRAY_LENGTH(types); ++i) m_supportedMIMETypes->add(types[i]); } return m_supportedMIMETypes->contains(extension) ? blink::WebMimeRegistry::IsSupported : blink::WebMimeRegistry::IsNotSupported; } blink::WebMimeRegistry::SupportsType WebMimeRegistryImpl::supportsImageMIMEType(const blink::WebString& ext) { WTF::String extension = checkAndEnsureBit8String(ext); if (extension.isEmpty()) return blink::WebMimeRegistry::IsNotSupported; extension = extension.lower(); if (!m_supportedImageResourceMIMETypes) { m_supportedImageResourceMIMETypes = new WTF::HashSet<WTF::String>(); static const char* types[] = { //"image/svg+xml", "image/jpeg", "image/png", "image/tiff", //"application/x-javascript", "image/ico", "image/bmp", "image/gif", }; for (size_t i = 0; i < WTF_ARRAY_LENGTH(types); ++i) m_supportedImageResourceMIMETypes->add(types[i]); } return m_supportedImageResourceMIMETypes->contains(extension) ? blink::WebMimeRegistry::IsSupported : blink::WebMimeRegistry::IsNotSupported; } blink::WebMimeRegistry::SupportsType WebMimeRegistryImpl::supportsJavaScriptMIMEType(const blink::WebString& ext) { WTF::String extension = checkAndEnsureBit8String(ext); if (extension.isEmpty()) return blink::WebMimeRegistry::IsNotSupported; extension = extension.lower(); if (!m_supportedJavaScriptMIMETypes) { m_supportedJavaScriptMIMETypes = new WTF::HashSet<WTF::String>(); /* Mozilla 1.8 and WinIE 7 both accept text/javascript and text/ecmascript. Mozilla 1.8 accepts application/javascript, application/ecmascript, and application/x-javascript, but WinIE 7 doesn't. WinIE 7 accepts text/javascript1.1 - text/javascript1.3, text/jscript, and text/livescript, but Mozilla 1.8 doesn't. Mozilla 1.8 allows leading and trailing whitespace, but WinIE 7 doesn't. Mozilla 1.8 and WinIE 7 both accept the empty string, but neither accept a whitespace-only string. We want to accept all the values that either of these browsers accept, but not other values. */ static const char* types[] = { "text/javascript", "text/ecmascript", "application/javascript", "application/ecmascript", "application/x-javascript", "text/javascript1.1", "text/javascript1.2", "text/javascript1.3", "text/jscript", "text/livescript", }; for (size_t i = 0; i < WTF_ARRAY_LENGTH(types); ++i) m_supportedJavaScriptMIMETypes->add(types[i]); } return m_supportedJavaScriptMIMETypes->contains(extension) ? blink::WebMimeRegistry::IsSupported : blink::WebMimeRegistry::IsNotSupported; } blink::WebMimeRegistry::SupportsType WebMimeRegistryImpl::supportsMediaMIMEType( const blink::WebString&, const blink::WebString&, const blink::WebString&) { return blink::WebMimeRegistry::IsNotSupported; } bool WebMimeRegistryImpl::supportsMediaSourceMIMEType(const blink::WebString&, const blink::WebString&) { return blink::WebMimeRegistry::IsNotSupported; } blink::WebMimeRegistry::SupportsType WebMimeRegistryImpl::supportsNonImageMIMEType(const blink::WebString& ext) { WTF::String extension = checkAndEnsureBit8String(ext); if (extension.isEmpty()) return blink::WebMimeRegistry::IsNotSupported; extension = extension.lower(); if (!m_supportedNonImageMIMETypes) { m_supportedNonImageMIMETypes = new HashSet<String>(); static const char* types[] = { "text/html", "text/xml", "text/xsl", "text/plain", "text/", "application/xml", "application/xhtml+xml", "application/vnd.wap.xhtml+xml", "application/rss+xml", "application/atom+xml", "application/json", //#if ENABLE(SVG) "image/svg+xml", //#endif "application/x-ftp-directory", "multipart/x-mixed-replace", "multipart/related", //"application/x-shockwave-flash", // Note: ADDING a new type here will probably render it as HTML. This can // result in cross-site scripting. }; //COMPILE_ASSERT(sizeof(types) / sizeof(types[0]) <= 16, "nonimage_mime_types_must_be_less_than_or_equal_to_16"); for (size_t i = 0; i < WTF_ARRAY_LENGTH(types); ++i) m_supportedNonImageMIMETypes->add(types[i]); } return m_supportedNonImageMIMETypes->contains(extension) ? blink::WebMimeRegistry::IsSupported : blink::WebMimeRegistry::IsNotSupported; } void WebMimeRegistryImpl::ensureMimeTypeMap() { if (m_mimetypeMap) return; m_mimetypeMap = new WTF::HashMap<WTF::String, WTF::String>(); //fill with initial values m_mimetypeMap->add("txt", "text/plain"); m_mimetypeMap->add("pdf", "application/pdf"); m_mimetypeMap->add("ps", "application/postscript"); m_mimetypeMap->add("html", "text/html"); m_mimetypeMap->add("htm", "text/html"); m_mimetypeMap->add("xml", "text/xml"); m_mimetypeMap->add("xsl", "text/xsl"); m_mimetypeMap->add("js", "application/x-javascript"); m_mimetypeMap->add("xhtml", "application/xhtml+xml"); m_mimetypeMap->add("rss", "application/rss+xml"); m_mimetypeMap->add("webarchive", "application/x-webarchive"); m_mimetypeMap->add("svg", "image/svg+xml"); m_mimetypeMap->add("svgz", "image/svg+xml"); m_mimetypeMap->add("jpg", "image/jpeg"); m_mimetypeMap->add("jpeg", "image/jpeg"); m_mimetypeMap->add("png", "image/png"); m_mimetypeMap->add("gif", "image/gif"); m_mimetypeMap->add("tif", "image/tiff"); m_mimetypeMap->add("tiff", "image/tiff"); m_mimetypeMap->add("ico", "image/ico"); m_mimetypeMap->add("cur", "image/ico"); m_mimetypeMap->add("bmp", "image/bmp"); m_mimetypeMap->add("wml", "text/vnd.wap.wml"); m_mimetypeMap->add("wmlc", "application/vnd.wap.wmlc"); m_mimetypeMap->add("swf", "application/x-shockwave-flash"); m_mimetypeMap->add("mp4", "video/mp4"); m_mimetypeMap->add("ogg", "video/ogg"); m_mimetypeMap->add("webm", "video/webm"); m_mimetypeMap->add("mht", "multipart/related"); m_mimetypeMap->add("mhtml", "multipart/related"); } blink::WebString WebMimeRegistryImpl::mimeTypeForExtension(const blink::WebString& ext) { ASSERT(isMainThread()); if (ext.isNull() || ext.isEmpty()) return blink::WebString(); ensureMimeTypeMap(); WTF::String extension = WTF::ensureStringToUTF8String(ext); extension = extension.lower(); WTF::String result = m_mimetypeMap->get(extension); return result; } blink::WebString WebMimeRegistryImpl::wellKnownMimeTypeForExtension(const blink::WebString& ext) { return mimeTypeForExtension(ext); } blink::WebString WebMimeRegistryImpl::mimeTypeFromFile(const blink::WebString& ext) { return blink::WebString(); } blink::WebString WebMimeRegistryImpl::extensionFormimeType(const blink::WebString& ext) { ASSERT(isMainThread()); if (ext.isNull() || ext.isEmpty()) return blink::WebString(); ensureMimeTypeMap(); for (WTF::HashMap<WTF::String, WTF::String>::iterator it = m_mimetypeMap->begin(); it != m_mimetypeMap->end(); ++it) { if (WTF::equalIgnoringCase(it->value, String(ext))) return it->key; } return blink::WebString(); } } // namespace content<|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** 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 qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtGui> #include "mainwindow.h" #include "xbelgenerator.h" #include "xbelhandler.h" MainWindow::MainWindow() { QStringList labels; labels << tr("Title") << tr("Location"); treeWidget = new QTreeWidget; treeWidget->header()->setResizeMode(QHeaderView::Stretch); treeWidget->setHeaderLabels(labels); setCentralWidget(treeWidget); createActions(); createMenus(); statusBar()->showMessage(tr("Ready")); setWindowTitle(tr("SAX Bookmarks")); resize(480, 320); } void MainWindow::open() { #if defined(Q_OS_SYMBIAN) // Always look for bookmarks on the same drive where the application is installed to. QString bookmarksFolder = QCoreApplication::applicationFilePath().left(1); bookmarksFolder.append(":/Data/qt/saxbookmarks"); QDir::setCurrent(bookmarksFolder); #endif QString fileName = QFileDialog::getOpenFileName(this, tr("Open Bookmark File"), QDir::currentPath(), tr("XBEL Files (*.xbel *.xml)")); if (fileName.isEmpty()) return; treeWidget->clear(); XbelHandler handler(treeWidget); QXmlSimpleReader reader; reader.setContentHandler(&handler); reader.setErrorHandler(&handler); QFile file(fileName); if (!file.open(QFile::ReadOnly | QFile::Text)) { QMessageBox::warning(this, tr("SAX Bookmarks"), tr("Cannot read file %1:\n%2.") .arg(fileName) .arg(file.errorString())); return; } QXmlInputSource xmlInputSource(&file); if (reader.parse(xmlInputSource)) statusBar()->showMessage(tr("File loaded"), 2000); } void MainWindow::saveAs() { QString fileName = QFileDialog::getSaveFileName(this, tr("Save Bookmark File"), QDir::currentPath(), tr("XBEL Files (*.xbel *.xml)")); if (fileName.isEmpty()) return; QFile file(fileName); if (!file.open(QFile::WriteOnly | QFile::Text)) { QMessageBox::warning(this, tr("SAX Bookmarks"), tr("Cannot write file %1:\n%2.") .arg(fileName) .arg(file.errorString())); return; } XbelGenerator generator(treeWidget); if (generator.write(&file)) statusBar()->showMessage(tr("File saved"), 2000); } void MainWindow::about() { QMessageBox::about(this, tr("About SAX Bookmarks"), tr("The <b>SAX Bookmarks</b> example demonstrates how to use Qt's " "SAX classes to read XML documents and how to generate XML by " "hand.")); } void MainWindow::createActions() { openAct = new QAction(tr("&Open..."), this); openAct->setShortcuts(QKeySequence::Open); connect(openAct, SIGNAL(triggered()), this, SLOT(open())); saveAsAct = new QAction(tr("&Save As..."), this); saveAsAct->setShortcuts(QKeySequence::SaveAs); connect(saveAsAct, SIGNAL(triggered()), this, SLOT(saveAs())); exitAct = new QAction(tr("E&xit"), this); exitAct->setShortcuts(QKeySequence::Quit); connect(exitAct, SIGNAL(triggered()), this, SLOT(close())); aboutAct = new QAction(tr("&About"), this); connect(aboutAct, SIGNAL(triggered()), this, SLOT(about())); aboutQtAct = new QAction(tr("About &Qt"), this); connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt())); } void MainWindow::createMenus() { fileMenu = menuBar()->addMenu(tr("&File")); fileMenu->addAction(openAct); fileMenu->addAction(saveAsAct); fileMenu->addAction(exitAct); menuBar()->addSeparator(); helpMenu = menuBar()->addMenu(tr("&Help")); helpMenu->addAction(aboutAct); helpMenu->addAction(aboutQtAct); } <commit_msg>Fix for "saxbookmarks - file dialog starts in wrong directory (winscw)"<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** 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 qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtGui> #include "mainwindow.h" #include "xbelgenerator.h" #include "xbelhandler.h" MainWindow::MainWindow() { QStringList labels; labels << tr("Title") << tr("Location"); treeWidget = new QTreeWidget; treeWidget->header()->setResizeMode(QHeaderView::Stretch); treeWidget->setHeaderLabels(labels); setCentralWidget(treeWidget); createActions(); createMenus(); statusBar()->showMessage(tr("Ready")); setWindowTitle(tr("SAX Bookmarks")); resize(480, 320); } void MainWindow::open() { #if defined(Q_OS_SYMBIAN) // Look for bookmarks on the same drive where the application is installed to, // if drive is not read only. QDesktopServices::DataLocation does this check, // and returns writable drive. QString bookmarksFolder = QDesktopServices::storageLocation(QDesktopServices::DataLocation).left(1); bookmarksFolder.append(":/Data/qt/saxbookmarks"); QDir::setCurrent(bookmarksFolder); #endif QString fileName = QFileDialog::getOpenFileName(this, tr("Open Bookmark File"), QDir::currentPath(), tr("XBEL Files (*.xbel *.xml)")); if (fileName.isEmpty()) return; treeWidget->clear(); XbelHandler handler(treeWidget); QXmlSimpleReader reader; reader.setContentHandler(&handler); reader.setErrorHandler(&handler); QFile file(fileName); if (!file.open(QFile::ReadOnly | QFile::Text)) { QMessageBox::warning(this, tr("SAX Bookmarks"), tr("Cannot read file %1:\n%2.") .arg(fileName) .arg(file.errorString())); return; } QXmlInputSource xmlInputSource(&file); if (reader.parse(xmlInputSource)) statusBar()->showMessage(tr("File loaded"), 2000); } void MainWindow::saveAs() { QString fileName = QFileDialog::getSaveFileName(this, tr("Save Bookmark File"), QDir::currentPath(), tr("XBEL Files (*.xbel *.xml)")); if (fileName.isEmpty()) return; QFile file(fileName); if (!file.open(QFile::WriteOnly | QFile::Text)) { QMessageBox::warning(this, tr("SAX Bookmarks"), tr("Cannot write file %1:\n%2.") .arg(fileName) .arg(file.errorString())); return; } XbelGenerator generator(treeWidget); if (generator.write(&file)) statusBar()->showMessage(tr("File saved"), 2000); } void MainWindow::about() { QMessageBox::about(this, tr("About SAX Bookmarks"), tr("The <b>SAX Bookmarks</b> example demonstrates how to use Qt's " "SAX classes to read XML documents and how to generate XML by " "hand.")); } void MainWindow::createActions() { openAct = new QAction(tr("&Open..."), this); openAct->setShortcuts(QKeySequence::Open); connect(openAct, SIGNAL(triggered()), this, SLOT(open())); saveAsAct = new QAction(tr("&Save As..."), this); saveAsAct->setShortcuts(QKeySequence::SaveAs); connect(saveAsAct, SIGNAL(triggered()), this, SLOT(saveAs())); exitAct = new QAction(tr("E&xit"), this); exitAct->setShortcuts(QKeySequence::Quit); connect(exitAct, SIGNAL(triggered()), this, SLOT(close())); aboutAct = new QAction(tr("&About"), this); connect(aboutAct, SIGNAL(triggered()), this, SLOT(about())); aboutQtAct = new QAction(tr("About &Qt"), this); connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt())); } void MainWindow::createMenus() { fileMenu = menuBar()->addMenu(tr("&File")); fileMenu->addAction(openAct); fileMenu->addAction(saveAsAct); fileMenu->addAction(exitAct); menuBar()->addSeparator(); helpMenu = menuBar()->addMenu(tr("&Help")); helpMenu->addAction(aboutAct); helpMenu->addAction(aboutQtAct); } <|endoftext|>
<commit_before>// Copyright 2008, Google 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 Google Inc. 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. // Tests for the top plugins to catch regressions in our plugin host code, as // well as in the out of process code. Currently this tests: // Flash // Real // QuickTime // Windows Media Player // -this includes both WMP plugins. npdsplay.dll is the older one that // comes with XP. np-mswmp.dll can be downloaded from Microsoft and // needs SP2 or Vista. #include <windows.h> #include <shellapi.h> #include <shlobj.h> #include <atlbase.h> #include <comutil.h> #include <stdlib.h> #include <string.h> #include <memory.h> #include "base/file_util.h" #include "base/registry.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" #include "webkit/glue/plugins/plugin_constants_win.h" #include "webkit/glue/plugins/plugin_list.h" const char kTestCompleteCookie[] = "status"; const char kTestCompleteSuccess[] = "OK"; const int kShortWaitTimeout = 10 * 1000; const int kLongWaitTimeout = 30 * 1000; class PluginTest : public UITest { protected: virtual void SetUp() { const testing::TestInfo* const test_info = testing::UnitTest::GetInstance()->current_test_info(); if (strcmp(test_info->name(), "MediaPlayerNew") == 0) { // The installer adds our process names to the registry key below. Since // the installer might not have run on this machine, add it manually. RegKey regkey; if (regkey.Open(HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\MediaPlayer\\ShimInclusionList", KEY_WRITE)) { regkey.CreateKey(L"CHROME.EXE", KEY_READ); } launch_arguments_.AppendSwitch(kNoNativeActiveXShimSwitch); } else if (strcmp(test_info->name(), "MediaPlayerOld") == 0) { // When testing the old WMP plugin, we need to force Chrome to not load // the new plugin. launch_arguments_.AppendSwitch(kUseOldWMPPluginSwitch); launch_arguments_.AppendSwitch(kNoNativeActiveXShimSwitch); } else if (strcmp(test_info->name(), "FlashSecurity") == 0) { launch_arguments_.AppendSwitchWithValue(switches::kTestSandbox, L"security_tests.dll"); } UITest::SetUp(); } void TestPlugin(const std::wstring& test_case, int timeout) { GURL url = GetTestUrl(test_case); NavigateToURL(url); WaitForFinish(timeout); } // Generate the URL for testing a particular test. // HTML for the tests is all located in test_directory\plugin\<testcase> GURL GetTestUrl(const std::wstring &test_case) { std::wstring path; PathService::Get(chrome::DIR_TEST_DATA, &path); file_util::AppendToPath(&path, L"plugin"); file_util::AppendToPath(&path, test_case); return net::FilePathToFileURL(path); } // Waits for the test case to finish. void WaitForFinish(const int wait_time) { const int kSleepTime = 500; // 2 times per second const int kMaxIntervals = wait_time / kSleepTime; GURL url = GetTestUrl(L"done"); scoped_ptr<TabProxy> tab(GetActiveTab()); std::string done_str; for (int i = 0; i < kMaxIntervals; ++i) { Sleep(kSleepTime); // The webpage being tested has javascript which sets a cookie // which signals completion of the test. std::string cookieName = kTestCompleteCookie; tab->GetCookieByName(url, cookieName, &done_str); if (!done_str.empty()) break; } EXPECT_EQ(kTestCompleteSuccess, done_str); } }; TEST_F(PluginTest, Quicktime) { TestPlugin(L"quicktime.html", kShortWaitTimeout); } TEST_F(PluginTest, MediaPlayerNew) { TestPlugin(L"wmp_new.html", kShortWaitTimeout); } // http://crbug.com/4809 TEST_F(PluginTest, DISABLED_MediaPlayerOld) { TestPlugin(L"wmp_old.html", kLongWaitTimeout); } TEST_F(PluginTest, Real) { TestPlugin(L"real.html", kShortWaitTimeout); } TEST_F(PluginTest, Flash) { TestPlugin(L"flash.html", kShortWaitTimeout); } TEST_F(PluginTest, FlashOctetStream) { TestPlugin(L"flash-octet-stream.html", kShortWaitTimeout); } TEST_F(PluginTest, FlashSecurity) { TestPlugin(L"flash.html", kShortWaitTimeout); } // http://crbug.com/8690 TEST_F(PluginTest, DISABLED_Java) { TestPlugin(L"Java.html", kShortWaitTimeout); } TEST_F(PluginTest, Silverlight) { TestPlugin(L"silverlight.html", kShortWaitTimeout); } typedef HRESULT (__stdcall* DllRegUnregServerFunc)(); class ActiveXTest : public PluginTest { public: ActiveXTest() { dll_registered = false; } protected: void TestActiveX(const std::wstring& test_case, int timeout, bool reg_dll) { if (reg_dll) { RegisterTestControl(true); dll_registered = true; } TestPlugin(test_case, timeout); } virtual void TearDown() { PluginTest::TearDown(); if (dll_registered) RegisterTestControl(false); } void RegisterTestControl(bool register_server) { std::wstring test_control_path = browser_directory_ + L"\\activex_test_control.dll"; HMODULE h = LoadLibrary(test_control_path.c_str()); ASSERT_TRUE(h != NULL) << "Failed to load activex_test_control.dll"; const char* func_name = register_server ? "DllRegisterServer" : "DllUnregisterServer"; DllRegUnregServerFunc func = reinterpret_cast<DllRegUnregServerFunc>( GetProcAddress(h, func_name)); // This should never happen actually. ASSERT_TRUE(func != NULL) << "Failed to find reg/unreg function."; HRESULT hr = func(); const char* error_message = register_server ? "Failed to register dll." : "Failed to unregister dll"; ASSERT_TRUE(SUCCEEDED(hr)) << error_message; FreeLibrary(h); } private: bool dll_registered; }; TEST_F(ActiveXTest, EmbeddedWMP) { TestActiveX(L"activex_embedded_wmp.html", kLongWaitTimeout, false); } TEST_F(ActiveXTest, WMP) { TestActiveX(L"activex_wmp.html", kLongWaitTimeout, false); } TEST_F(ActiveXTest, CustomScripting) { TestActiveX(L"activex_custom_scripting.html", kShortWaitTimeout, true); } <commit_msg>Re-enable java plugin test (reverting 11510)<commit_after>// Copyright 2008, Google 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 Google Inc. 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. // Tests for the top plugins to catch regressions in our plugin host code, as // well as in the out of process code. Currently this tests: // Flash // Real // QuickTime // Windows Media Player // -this includes both WMP plugins. npdsplay.dll is the older one that // comes with XP. np-mswmp.dll can be downloaded from Microsoft and // needs SP2 or Vista. #include <windows.h> #include <shellapi.h> #include <shlobj.h> #include <atlbase.h> #include <comutil.h> #include <stdlib.h> #include <string.h> #include <memory.h> #include "base/file_util.h" #include "base/registry.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" #include "webkit/glue/plugins/plugin_constants_win.h" #include "webkit/glue/plugins/plugin_list.h" const char kTestCompleteCookie[] = "status"; const char kTestCompleteSuccess[] = "OK"; const int kShortWaitTimeout = 10 * 1000; const int kLongWaitTimeout = 30 * 1000; class PluginTest : public UITest { protected: virtual void SetUp() { const testing::TestInfo* const test_info = testing::UnitTest::GetInstance()->current_test_info(); if (strcmp(test_info->name(), "MediaPlayerNew") == 0) { // The installer adds our process names to the registry key below. Since // the installer might not have run on this machine, add it manually. RegKey regkey; if (regkey.Open(HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\MediaPlayer\\ShimInclusionList", KEY_WRITE)) { regkey.CreateKey(L"CHROME.EXE", KEY_READ); } launch_arguments_.AppendSwitch(kNoNativeActiveXShimSwitch); } else if (strcmp(test_info->name(), "MediaPlayerOld") == 0) { // When testing the old WMP plugin, we need to force Chrome to not load // the new plugin. launch_arguments_.AppendSwitch(kUseOldWMPPluginSwitch); launch_arguments_.AppendSwitch(kNoNativeActiveXShimSwitch); } else if (strcmp(test_info->name(), "FlashSecurity") == 0) { launch_arguments_.AppendSwitchWithValue(switches::kTestSandbox, L"security_tests.dll"); } UITest::SetUp(); } void TestPlugin(const std::wstring& test_case, int timeout) { GURL url = GetTestUrl(test_case); NavigateToURL(url); WaitForFinish(timeout); } // Generate the URL for testing a particular test. // HTML for the tests is all located in test_directory\plugin\<testcase> GURL GetTestUrl(const std::wstring &test_case) { std::wstring path; PathService::Get(chrome::DIR_TEST_DATA, &path); file_util::AppendToPath(&path, L"plugin"); file_util::AppendToPath(&path, test_case); return net::FilePathToFileURL(path); } // Waits for the test case to finish. void WaitForFinish(const int wait_time) { const int kSleepTime = 500; // 2 times per second const int kMaxIntervals = wait_time / kSleepTime; GURL url = GetTestUrl(L"done"); scoped_ptr<TabProxy> tab(GetActiveTab()); std::string done_str; for (int i = 0; i < kMaxIntervals; ++i) { Sleep(kSleepTime); // The webpage being tested has javascript which sets a cookie // which signals completion of the test. std::string cookieName = kTestCompleteCookie; tab->GetCookieByName(url, cookieName, &done_str); if (!done_str.empty()) break; } EXPECT_EQ(kTestCompleteSuccess, done_str); } }; TEST_F(PluginTest, Quicktime) { TestPlugin(L"quicktime.html", kShortWaitTimeout); } TEST_F(PluginTest, MediaPlayerNew) { TestPlugin(L"wmp_new.html", kShortWaitTimeout); } // http://crbug.com/4809 TEST_F(PluginTest, DISABLED_MediaPlayerOld) { TestPlugin(L"wmp_old.html", kLongWaitTimeout); } TEST_F(PluginTest, Real) { TestPlugin(L"real.html", kShortWaitTimeout); } TEST_F(PluginTest, Flash) { TestPlugin(L"flash.html", kShortWaitTimeout); } TEST_F(PluginTest, FlashOctetStream) { TestPlugin(L"flash-octet-stream.html", kShortWaitTimeout); } TEST_F(PluginTest, FlashSecurity) { TestPlugin(L"flash.html", kShortWaitTimeout); } TEST_F(PluginTest, Java) { TestPlugin(L"Java.html", kShortWaitTimeout); } TEST_F(PluginTest, Silverlight) { TestPlugin(L"silverlight.html", kShortWaitTimeout); } typedef HRESULT (__stdcall* DllRegUnregServerFunc)(); class ActiveXTest : public PluginTest { public: ActiveXTest() { dll_registered = false; } protected: void TestActiveX(const std::wstring& test_case, int timeout, bool reg_dll) { if (reg_dll) { RegisterTestControl(true); dll_registered = true; } TestPlugin(test_case, timeout); } virtual void TearDown() { PluginTest::TearDown(); if (dll_registered) RegisterTestControl(false); } void RegisterTestControl(bool register_server) { std::wstring test_control_path = browser_directory_ + L"\\activex_test_control.dll"; HMODULE h = LoadLibrary(test_control_path.c_str()); ASSERT_TRUE(h != NULL) << "Failed to load activex_test_control.dll"; const char* func_name = register_server ? "DllRegisterServer" : "DllUnregisterServer"; DllRegUnregServerFunc func = reinterpret_cast<DllRegUnregServerFunc>( GetProcAddress(h, func_name)); // This should never happen actually. ASSERT_TRUE(func != NULL) << "Failed to find reg/unreg function."; HRESULT hr = func(); const char* error_message = register_server ? "Failed to register dll." : "Failed to unregister dll"; ASSERT_TRUE(SUCCEEDED(hr)) << error_message; FreeLibrary(h); } private: bool dll_registered; }; TEST_F(ActiveXTest, EmbeddedWMP) { TestActiveX(L"activex_embedded_wmp.html", kLongWaitTimeout, false); } TEST_F(ActiveXTest, WMP) { TestActiveX(L"activex_wmp.html", kLongWaitTimeout, false); } TEST_F(ActiveXTest, CustomScripting) { TestActiveX(L"activex_custom_scripting.html", kShortWaitTimeout, true); } <|endoftext|>
<commit_before>/* * Software License Agreement (Apache License) * * Copyright (c) 2014, Southwest Research Institute * * 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 <ros/node_handle.h> #include <descartes_planner/sparse_planner.h> #include <descartes_trajectory/cart_trajectory_pt.h> #include <descartes_core/utils.h> #include <descartes_trajectory_test/cartesian_robot.h> #include <gtest/gtest.h> #include <descartes_core/pretty_print.hpp> #include <tuple> using namespace descartes_core; using namespace descartes_trajectory; typedef std::vector<descartes_core::TrajectoryPtPtr> Trajectory; const int NUM_DENSE_POINTS = 1000; Trajectory createTestTrajectory(); Trajectory TEST_TRAJECTORY = createTestTrajectory(); descartes_planner::SparsePlanner Planner; class ThreeDOFRobot: public descartes_trajectory_test::CartesianRobot { public: ThreeDOFRobot(): descartes_trajectory_test::CartesianRobot(0,0,3) { } virtual ~ThreeDOFRobot() { } }; class TestPoint: public descartes_trajectory::CartTrajectoryPt { public: TestPoint(const std::vector<double>& joints) { vals_.resize(joints.size()); vals_.assign(joints.begin(),joints.end()); } virtual ~TestPoint() { } virtual bool getClosestJointPose(const std::vector<double> &seed_state, const RobotModel &model, std::vector<double> &joint_pose) const { joint_pose.clear(); joint_pose.assign(vals_.begin(),vals_.end()); return true; } virtual void getJointPoses(const RobotModel &model, std::vector<std::vector<double> > &joint_poses) const { joint_poses.clear(); joint_poses.push_back(vals_); } protected: std::vector<double> vals_; }; Trajectory createTestTrajectory() { ROS_INFO_STREAM("Creating test trajectory with "<<NUM_DENSE_POINTS<<" points"); Trajectory traj; std::vector<std::tuple<double, double>>joint_bounds = {std::make_tuple(0,M_PI), std::make_tuple(-M_PI_2,M_PI_2), std::make_tuple(M_PI/8,M_PI/3)}; std::vector<double> deltas; for(auto& e:joint_bounds) { double d = (std::get<1>(e)- std::get<0>(e))/NUM_DENSE_POINTS; deltas.push_back(d); } // creating trajectory points std::vector<double> joint_vals(deltas.size(),0); traj.reserve(NUM_DENSE_POINTS); for(int i = 0 ; i < NUM_DENSE_POINTS; i++) { for(int j = 0; j < deltas.size(); j++) { joint_vals[j] = std::get<0>(joint_bounds[j]) + deltas[j]*i; } TrajectoryPtPtr tp(new TestPoint(joint_vals)); traj.push_back(tp); } return traj; } TEST(SparsePlanner, initialize) { ros::Time::init(); RobotModelConstPtr robot(new ThreeDOFRobot()); EXPECT_TRUE(Planner.initialize(robot)); } TEST(SparsePlanner, configure) { descartes_core::PlannerConfig config; Planner.getConfig(config); EXPECT_TRUE(Planner.setConfig(config)); } TEST(SparsePlanner, planPath) { ROS_INFO_STREAM("Testing planPath() with "<<NUM_DENSE_POINTS<<" points"); EXPECT_TRUE(Planner.planPath(TEST_TRAJECTORY)); } TEST(DensePlanner, getPath) { std::vector<descartes_core::TrajectoryPtPtr> path; EXPECT_TRUE(Planner.getPath(path)); EXPECT_TRUE(path.size() == NUM_DENSE_POINTS); } <commit_msg>fixed sparse planner test<commit_after>/* * Software License Agreement (Apache License) * * Copyright (c) 2014, Southwest Research Institute * * 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 <ros/node_handle.h> #include <descartes_planner/sparse_planner.h> #include <descartes_trajectory/cart_trajectory_pt.h> #include <descartes_core/utils.h> #include <descartes_trajectory_test/cartesian_robot.h> #include <gtest/gtest.h> #include <descartes_core/pretty_print.hpp> #include <tuple> using namespace descartes_core; using namespace descartes_trajectory; typedef std::vector<descartes_core::TrajectoryPtPtr> Trajectory; const int NUM_DENSE_POINTS = 1000; Trajectory createTestTrajectory(); Trajectory TEST_TRAJECTORY = createTestTrajectory(); descartes_planner::SparsePlanner Planner; class ThreeDOFRobot: public descartes_trajectory_test::CartesianRobot { public: ThreeDOFRobot(): descartes_trajectory_test::CartesianRobot(0,0,3) { } virtual ~ThreeDOFRobot() { } }; class TestPoint: public descartes_trajectory::CartTrajectoryPt { public: TestPoint(const std::vector<double>& joints) { vals_.resize(joints.size()); vals_.assign(joints.begin(),joints.end()); } virtual ~TestPoint() { } virtual bool getClosestJointPose(const std::vector<double> &seed_state, const RobotModel &model, std::vector<double> &joint_pose) const { joint_pose.clear(); joint_pose.assign(vals_.begin(),vals_.end()); return true; } virtual void getJointPoses(const RobotModel &model, std::vector<std::vector<double> > &joint_poses) const { joint_poses.clear(); joint_poses.push_back(vals_); } protected: std::vector<double> vals_; }; Trajectory createTestTrajectory() { ROS_INFO_STREAM("Creating test trajectory with "<<NUM_DENSE_POINTS<<" points"); Trajectory traj; std::vector<std::tuple<double, double>>joint_bounds = {std::make_tuple(0,M_PI), std::make_tuple(-M_PI_2,M_PI_2), std::make_tuple(M_PI/8,M_PI/3)}; std::vector<double> deltas; for(auto& e:joint_bounds) { double d = (std::get<1>(e)- std::get<0>(e))/NUM_DENSE_POINTS; deltas.push_back(d); } // creating trajectory points std::vector<double> joint_vals(deltas.size(),0); traj.reserve(NUM_DENSE_POINTS); for(int i = 0 ; i < NUM_DENSE_POINTS; i++) { for(int j = 0; j < deltas.size(); j++) { joint_vals[j] = std::get<0>(joint_bounds[j]) + deltas[j]*i; } TrajectoryPtPtr tp(new TestPoint(joint_vals)); traj.push_back(tp); } return traj; } TEST(SparsePlanner, initialize) { ros::Time::init(); RobotModelConstPtr robot(new ThreeDOFRobot()); EXPECT_TRUE(Planner.initialize(robot)); } TEST(SparsePlanner, configure) { descartes_core::PlannerConfig config; Planner.getConfig(config); EXPECT_TRUE(Planner.setConfig(config)); } TEST(SparsePlanner, planPath) { ROS_INFO_STREAM("Testing planPath() with "<<NUM_DENSE_POINTS<<" points"); EXPECT_TRUE(Planner.planPath(TEST_TRAJECTORY)); } TEST(SparsePlanner, getPath) { std::vector<descartes_core::TrajectoryPtPtr> path; EXPECT_TRUE(Planner.getPath(path)); EXPECT_TRUE(path.size() == NUM_DENSE_POINTS); } <|endoftext|>
<commit_before>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd 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 "OgreStableHeaders.h" #include "OgreViewport.h" #include "OgreLogManager.h" #include "OgreCamera.h" #include "OgreRoot.h" #include "OgreMaterialManager.h" #include "OgreRenderSystem.h" #include "OgreRenderTarget.h" #include <iomanip> namespace Ogre { OrientationMode Viewport::mDefaultOrientationMode = OR_DEGREE_0; //--------------------------------------------------------------------- Viewport::Viewport(Camera* cam, RenderTarget* target, Real left, Real top, Real width, Real height, int ZOrder) : mCamera(cam) , mTarget(target) , mRelLeft(left) , mRelTop(top) , mRelWidth(width) , mRelHeight(height) // Actual dimensions will update later , mZOrder(ZOrder) , mBackColour(ColourValue::Black) , mDepthClearValue(1) , mClearEveryFrame(true) , mClearBuffers(FBT_COLOUR | FBT_DEPTH) , mUpdated(false) , mShowOverlays(true) , mShowSkies(true) , mShowShadows(true) , mVisibilityMask(0xFFFFFFFF) , mRQSequence(0) , mMaterialSchemeName(MaterialManager::DEFAULT_SCHEME_NAME) , mIsAutoUpdated(true) , mColourBuffer(CBT_BACK) { #if OGRE_COMPILER != OGRE_COMPILER_GCCE && OGRE_PLATFORM != OGRE_PLATFORM_ANDROID LogManager::getSingleton().stream(LML_TRIVIAL) << "Creating viewport on target '" << target->getName() << "'" << ", rendering from camera '" << (cam != 0 ? cam->getName() : "NULL") << "'" << ", relative dimensions " << std::ios::fixed << std::setprecision(2) << "L: " << left << " T: " << top << " W: " << width << " H: " << height << " Z-order: " << ZOrder; #endif // Set the default orientation mode mOrientationMode = mDefaultOrientationMode; // Set the default material scheme RenderSystem* rs = Root::getSingleton().getRenderSystem(); mMaterialSchemeName = rs->_getDefaultViewportMaterialScheme(); // Calculate actual dimensions _updateDimensions(); // notify camera if(cam) cam->_notifyViewport(this); } //--------------------------------------------------------------------- Viewport::~Viewport() { ListenerList listenersCopy; std::swap(mListeners, listenersCopy); for (ListenerList::iterator i = listenersCopy.begin(); i != listenersCopy.end(); ++i) { (*i)->viewportDestroyed(this); } RenderSystem* rs = Root::getSingleton().getRenderSystem(); if ((rs) && (rs->_getViewport() == this)) { rs->_setViewport(NULL); } } //--------------------------------------------------------------------- bool Viewport::_isUpdated(void) const { return mUpdated; } //--------------------------------------------------------------------- void Viewport::_clearUpdatedFlag(void) { mUpdated = false; } //--------------------------------------------------------------------- void Viewport::_updateDimensions(void) { Real height = (Real) mTarget->getHeight(); Real width = (Real) mTarget->getWidth(); mActLeft = (int) (mRelLeft * width); mActTop = (int) (mRelTop * height); mActWidth = (int) (mRelWidth * width); mActHeight = (int) (mRelHeight * height); // This will check if the cameras getAutoAspectRatio() property is set. // If it's true its aspect ratio is fit to the current viewport // If it's false the camera remains unchanged. // This allows cameras to be used to render to many viewports, // which can have their own dimensions and aspect ratios. if (mCamera) { if (mCamera->getAutoAspectRatio()) mCamera->setAspectRatio((Real) mActWidth / (Real) mActHeight); #if OGRE_NO_VIEWPORT_ORIENTATIONMODE == 0 mCamera->setOrientationMode(mOrientationMode); #endif } #if OGRE_COMPILER != OGRE_COMPILER_GCCE LogManager::getSingleton().stream(LML_TRIVIAL) << "Viewport for camera '" << (mCamera != 0 ? mCamera->getName() : "NULL") << "'" << ", actual dimensions " << std::ios::fixed << std::setprecision(2) << "L: " << mActLeft << " T: " << mActTop << " W: " << mActWidth << " H: " << mActHeight; #endif mUpdated = true; for (ListenerList::iterator i = mListeners.begin(); i != mListeners.end(); ++i) { (*i)->viewportDimensionsChanged(this); } } //--------------------------------------------------------------------- int Viewport::getZOrder(void) const { return mZOrder; } //--------------------------------------------------------------------- RenderTarget* Viewport::getTarget(void) const { return mTarget; } //--------------------------------------------------------------------- Camera* Viewport::getCamera(void) const { return mCamera; } //--------------------------------------------------------------------- Real Viewport::getLeft(void) const { return mRelLeft; } //--------------------------------------------------------------------- Real Viewport::getTop(void) const { return mRelTop; } //--------------------------------------------------------------------- Real Viewport::getWidth(void) const { return mRelWidth; } //--------------------------------------------------------------------- Real Viewport::getHeight(void) const { return mRelHeight; } //--------------------------------------------------------------------- int Viewport::getActualLeft(void) const { return mActLeft; } //--------------------------------------------------------------------- int Viewport::getActualTop(void) const { return mActTop; } //--------------------------------------------------------------------- int Viewport::getActualWidth(void) const { return mActWidth; } //--------------------------------------------------------------------- int Viewport::getActualHeight(void) const { return mActHeight; } //--------------------------------------------------------------------- void Viewport::setDimensions(Real left, Real top, Real width, Real height) { mRelLeft = left; mRelTop = top; mRelWidth = width; mRelHeight = height; _updateDimensions(); } //--------------------------------------------------------------------- void Viewport::update(void) { if (mCamera) { // Tell Camera to render into me mCamera->_renderScene(this, mShowOverlays); } } //--------------------------------------------------------------------- void Viewport::setOrientationMode(OrientationMode orientationMode, bool setDefault) { #if OGRE_NO_VIEWPORT_ORIENTATIONMODE != 0 OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "Setting Viewport orientation mode is not supported", __FUNCTION__); #endif mOrientationMode = orientationMode; if (setDefault) { setDefaultOrientationMode(orientationMode); } if (mCamera) { mCamera->setOrientationMode(mOrientationMode); } // Update the render system config #if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS RenderSystem* rs = Root::getSingleton().getRenderSystem(); if(mOrientationMode == OR_LANDSCAPELEFT) rs->setConfigOption("Orientation", "Landscape Left"); else if(mOrientationMode == OR_LANDSCAPERIGHT) rs->setConfigOption("Orientation", "Landscape Right"); else if(mOrientationMode == OR_PORTRAIT) rs->setConfigOption("Orientation", "Portrait"); #endif } //--------------------------------------------------------------------- OrientationMode Viewport::getOrientationMode() const { #if OGRE_NO_VIEWPORT_ORIENTATIONMODE != 0 OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "Getting Viewport orientation mode is not supported", __FUNCTION__); #endif return mOrientationMode; } //--------------------------------------------------------------------- void Viewport::setDefaultOrientationMode(OrientationMode orientationMode) { #if OGRE_NO_VIEWPORT_ORIENTATIONMODE != 0 OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "Setting default Viewport orientation mode is not supported", __FUNCTION__); #endif mDefaultOrientationMode = orientationMode; } //--------------------------------------------------------------------- OrientationMode Viewport::getDefaultOrientationMode() { #if OGRE_NO_VIEWPORT_ORIENTATIONMODE != 0 OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "Getting default Viewport orientation mode is not supported", __FUNCTION__); #endif return mDefaultOrientationMode; } //--------------------------------------------------------------------- void Viewport::setBackgroundColour(const ColourValue& colour) { mBackColour = colour; } //--------------------------------------------------------------------- const ColourValue& Viewport::getBackgroundColour(void) const { return mBackColour; } //--------------------------------------------------------------------- void Viewport::setDepthClear( Real depth ) { mDepthClearValue = depth; } //--------------------------------------------------------------------- Real Viewport::getDepthClear(void) const { return mDepthClearValue; } //--------------------------------------------------------------------- void Viewport::setClearEveryFrame(bool inClear, unsigned int inBuffers) { mClearEveryFrame = inClear; mClearBuffers = inBuffers; } //--------------------------------------------------------------------- bool Viewport::getClearEveryFrame(void) const { return mClearEveryFrame; } //--------------------------------------------------------------------- unsigned int Viewport::getClearBuffers(void) const { return mClearBuffers; } //--------------------------------------------------------------------- void Viewport::clear(unsigned int buffers, const ColourValue& col, Real depth, unsigned short stencil) { RenderSystem* rs = Root::getSingleton().getRenderSystem(); if (rs) { Viewport* currentvp = rs->_getViewport(); if (currentvp && currentvp == this) rs->clearFrameBuffer(buffers, col, depth, stencil); else if (currentvp) { rs->_setViewport(this); rs->clearFrameBuffer(buffers, col, depth, stencil); rs->_setViewport(currentvp); } } } //--------------------------------------------------------------------- void Viewport::getActualDimensions(int &left, int&top, int &width, int &height) const { left = mActLeft; top = mActTop; width = mActWidth; height = mActHeight; } //--------------------------------------------------------------------- unsigned int Viewport::_getNumRenderedFaces(void) const { return mCamera ? mCamera->_getNumRenderedFaces() : 0; } //--------------------------------------------------------------------- unsigned int Viewport::_getNumRenderedBatches(void) const { return mCamera ? mCamera->_getNumRenderedBatches() : 0; } //--------------------------------------------------------------------- void Viewport::setCamera(Camera* cam) { if(mCamera) { if(mCamera->getViewport() == this) { mCamera->_notifyViewport(0); } } mCamera = cam; if (cam) { // update aspect ratio of new camera if needed. if (cam->getAutoAspectRatio()) { cam->setAspectRatio((Real) mActWidth / (Real) mActHeight); } #if OGRE_NO_VIEWPORT_ORIENTATIONMODE == 0 cam->setOrientationMode(mOrientationMode); #endif cam->_notifyViewport(this); } for (ListenerList::iterator i = mListeners.begin(); i != mListeners.end(); ++i) { (*i)->viewportCameraChanged(this); } } //--------------------------------------------------------------------- void Viewport::setAutoUpdated(bool inAutoUpdated) { mIsAutoUpdated = inAutoUpdated; } //--------------------------------------------------------------------- bool Viewport::isAutoUpdated() const { return mIsAutoUpdated; } //--------------------------------------------------------------------- void Viewport::setOverlaysEnabled(bool enabled) { mShowOverlays = enabled; } //--------------------------------------------------------------------- bool Viewport::getOverlaysEnabled(void) const { return mShowOverlays; } //--------------------------------------------------------------------- void Viewport::setSkiesEnabled(bool enabled) { mShowSkies = enabled; } //--------------------------------------------------------------------- bool Viewport::getSkiesEnabled(void) const { return mShowSkies; } //--------------------------------------------------------------------- void Viewport::setShadowsEnabled(bool enabled) { mShowShadows = enabled; } //--------------------------------------------------------------------- bool Viewport::getShadowsEnabled(void) const { return mShowShadows; } //----------------------------------------------------------------------- void Viewport::setRenderQueueInvocationSequenceName(const String& sequenceName) { mRQSequenceName = sequenceName; if (mRQSequenceName.empty()) { mRQSequence = 0; } else { mRQSequence = Root::getSingleton().getRenderQueueInvocationSequence(mRQSequenceName); } } //----------------------------------------------------------------------- const String& Viewport::getRenderQueueInvocationSequenceName(void) const { return mRQSequenceName; } //----------------------------------------------------------------------- RenderQueueInvocationSequence* Viewport::_getRenderQueueInvocationSequence(void) { return mRQSequence; } //----------------------------------------------------------------------- void Viewport::pointOrientedToScreen(const Vector2 &v, int orientationMode, Vector2 &outv) { pointOrientedToScreen(v.x, v.y, orientationMode, outv.x, outv.y); } //----------------------------------------------------------------------- void Viewport::pointOrientedToScreen(Real orientedX, Real orientedY, int orientationMode, Real &screenX, Real &screenY) { Real orX = orientedX; Real orY = orientedY; switch (orientationMode) { case 1: screenX = orY; screenY = Real(1.0) - orX; break; case 2: screenX = Real(1.0) - orX; screenY = Real(1.0) - orY; break; case 3: screenX = Real(1.0) - orY; screenY = orX; break; default: screenX = orX; screenY = orY; break; } } //----------------------------------------------------------------------- void Viewport::addListener(Listener* l) { if (std::find(mListeners.begin(), mListeners.end(), l) == mListeners.end()) mListeners.push_back(l); } //----------------------------------------------------------------------- void Viewport::removeListener(Listener* l) { ListenerList::iterator i = std::find(mListeners.begin(), mListeners.end(), l); if (i != mListeners.end()) mListeners.erase(i); } //----------------------------------------------------------------------- void Viewport::setDrawBuffer(ColourBufferType colourBuffer) { mColourBuffer = colourBuffer; } //----------------------------------------------------------------------- ColourBufferType Viewport::getDrawBuffer() const { return mColourBuffer; } //----------------------------------------------------------------------- //----------------------------------------------------------------------- void Viewport::Listener::viewportCameraChanged(Viewport*) { } //----------------------------------------------------------------------- void Viewport::Listener::viewportDimensionsChanged(Viewport*) { } //----------------------------------------------------------------------- void Viewport::Listener::viewportDestroyed(Viewport*) { } } <commit_msg>Changed: reset the reference from a camera to the last viewport only if the viewport's camera is replaced by a valid camera<commit_after>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd 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 "OgreStableHeaders.h" #include "OgreViewport.h" #include "OgreLogManager.h" #include "OgreCamera.h" #include "OgreRoot.h" #include "OgreMaterialManager.h" #include "OgreRenderSystem.h" #include "OgreRenderTarget.h" #include <iomanip> namespace Ogre { OrientationMode Viewport::mDefaultOrientationMode = OR_DEGREE_0; //--------------------------------------------------------------------- Viewport::Viewport(Camera* cam, RenderTarget* target, Real left, Real top, Real width, Real height, int ZOrder) : mCamera(cam) , mTarget(target) , mRelLeft(left) , mRelTop(top) , mRelWidth(width) , mRelHeight(height) // Actual dimensions will update later , mZOrder(ZOrder) , mBackColour(ColourValue::Black) , mDepthClearValue(1) , mClearEveryFrame(true) , mClearBuffers(FBT_COLOUR | FBT_DEPTH) , mUpdated(false) , mShowOverlays(true) , mShowSkies(true) , mShowShadows(true) , mVisibilityMask(0xFFFFFFFF) , mRQSequence(0) , mMaterialSchemeName(MaterialManager::DEFAULT_SCHEME_NAME) , mIsAutoUpdated(true) , mColourBuffer(CBT_BACK) { #if OGRE_COMPILER != OGRE_COMPILER_GCCE && OGRE_PLATFORM != OGRE_PLATFORM_ANDROID LogManager::getSingleton().stream(LML_TRIVIAL) << "Creating viewport on target '" << target->getName() << "'" << ", rendering from camera '" << (cam != 0 ? cam->getName() : "NULL") << "'" << ", relative dimensions " << std::ios::fixed << std::setprecision(2) << "L: " << left << " T: " << top << " W: " << width << " H: " << height << " Z-order: " << ZOrder; #endif // Set the default orientation mode mOrientationMode = mDefaultOrientationMode; // Set the default material scheme RenderSystem* rs = Root::getSingleton().getRenderSystem(); mMaterialSchemeName = rs->_getDefaultViewportMaterialScheme(); // Calculate actual dimensions _updateDimensions(); // notify camera if(cam) cam->_notifyViewport(this); } //--------------------------------------------------------------------- Viewport::~Viewport() { ListenerList listenersCopy; std::swap(mListeners, listenersCopy); for (ListenerList::iterator i = listenersCopy.begin(); i != listenersCopy.end(); ++i) { (*i)->viewportDestroyed(this); } RenderSystem* rs = Root::getSingleton().getRenderSystem(); if ((rs) && (rs->_getViewport() == this)) { rs->_setViewport(NULL); } } //--------------------------------------------------------------------- bool Viewport::_isUpdated(void) const { return mUpdated; } //--------------------------------------------------------------------- void Viewport::_clearUpdatedFlag(void) { mUpdated = false; } //--------------------------------------------------------------------- void Viewport::_updateDimensions(void) { Real height = (Real) mTarget->getHeight(); Real width = (Real) mTarget->getWidth(); mActLeft = (int) (mRelLeft * width); mActTop = (int) (mRelTop * height); mActWidth = (int) (mRelWidth * width); mActHeight = (int) (mRelHeight * height); // This will check if the cameras getAutoAspectRatio() property is set. // If it's true its aspect ratio is fit to the current viewport // If it's false the camera remains unchanged. // This allows cameras to be used to render to many viewports, // which can have their own dimensions and aspect ratios. if (mCamera) { if (mCamera->getAutoAspectRatio()) mCamera->setAspectRatio((Real) mActWidth / (Real) mActHeight); #if OGRE_NO_VIEWPORT_ORIENTATIONMODE == 0 mCamera->setOrientationMode(mOrientationMode); #endif } #if OGRE_COMPILER != OGRE_COMPILER_GCCE LogManager::getSingleton().stream(LML_TRIVIAL) << "Viewport for camera '" << (mCamera != 0 ? mCamera->getName() : "NULL") << "'" << ", actual dimensions " << std::ios::fixed << std::setprecision(2) << "L: " << mActLeft << " T: " << mActTop << " W: " << mActWidth << " H: " << mActHeight; #endif mUpdated = true; for (ListenerList::iterator i = mListeners.begin(); i != mListeners.end(); ++i) { (*i)->viewportDimensionsChanged(this); } } //--------------------------------------------------------------------- int Viewport::getZOrder(void) const { return mZOrder; } //--------------------------------------------------------------------- RenderTarget* Viewport::getTarget(void) const { return mTarget; } //--------------------------------------------------------------------- Camera* Viewport::getCamera(void) const { return mCamera; } //--------------------------------------------------------------------- Real Viewport::getLeft(void) const { return mRelLeft; } //--------------------------------------------------------------------- Real Viewport::getTop(void) const { return mRelTop; } //--------------------------------------------------------------------- Real Viewport::getWidth(void) const { return mRelWidth; } //--------------------------------------------------------------------- Real Viewport::getHeight(void) const { return mRelHeight; } //--------------------------------------------------------------------- int Viewport::getActualLeft(void) const { return mActLeft; } //--------------------------------------------------------------------- int Viewport::getActualTop(void) const { return mActTop; } //--------------------------------------------------------------------- int Viewport::getActualWidth(void) const { return mActWidth; } //--------------------------------------------------------------------- int Viewport::getActualHeight(void) const { return mActHeight; } //--------------------------------------------------------------------- void Viewport::setDimensions(Real left, Real top, Real width, Real height) { mRelLeft = left; mRelTop = top; mRelWidth = width; mRelHeight = height; _updateDimensions(); } //--------------------------------------------------------------------- void Viewport::update(void) { if (mCamera) { // Tell Camera to render into me mCamera->_renderScene(this, mShowOverlays); } } //--------------------------------------------------------------------- void Viewport::setOrientationMode(OrientationMode orientationMode, bool setDefault) { #if OGRE_NO_VIEWPORT_ORIENTATIONMODE != 0 OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "Setting Viewport orientation mode is not supported", __FUNCTION__); #endif mOrientationMode = orientationMode; if (setDefault) { setDefaultOrientationMode(orientationMode); } if (mCamera) { mCamera->setOrientationMode(mOrientationMode); } // Update the render system config #if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS RenderSystem* rs = Root::getSingleton().getRenderSystem(); if(mOrientationMode == OR_LANDSCAPELEFT) rs->setConfigOption("Orientation", "Landscape Left"); else if(mOrientationMode == OR_LANDSCAPERIGHT) rs->setConfigOption("Orientation", "Landscape Right"); else if(mOrientationMode == OR_PORTRAIT) rs->setConfigOption("Orientation", "Portrait"); #endif } //--------------------------------------------------------------------- OrientationMode Viewport::getOrientationMode() const { #if OGRE_NO_VIEWPORT_ORIENTATIONMODE != 0 OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "Getting Viewport orientation mode is not supported", __FUNCTION__); #endif return mOrientationMode; } //--------------------------------------------------------------------- void Viewport::setDefaultOrientationMode(OrientationMode orientationMode) { #if OGRE_NO_VIEWPORT_ORIENTATIONMODE != 0 OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "Setting default Viewport orientation mode is not supported", __FUNCTION__); #endif mDefaultOrientationMode = orientationMode; } //--------------------------------------------------------------------- OrientationMode Viewport::getDefaultOrientationMode() { #if OGRE_NO_VIEWPORT_ORIENTATIONMODE != 0 OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "Getting default Viewport orientation mode is not supported", __FUNCTION__); #endif return mDefaultOrientationMode; } //--------------------------------------------------------------------- void Viewport::setBackgroundColour(const ColourValue& colour) { mBackColour = colour; } //--------------------------------------------------------------------- const ColourValue& Viewport::getBackgroundColour(void) const { return mBackColour; } //--------------------------------------------------------------------- void Viewport::setDepthClear( Real depth ) { mDepthClearValue = depth; } //--------------------------------------------------------------------- Real Viewport::getDepthClear(void) const { return mDepthClearValue; } //--------------------------------------------------------------------- void Viewport::setClearEveryFrame(bool inClear, unsigned int inBuffers) { mClearEveryFrame = inClear; mClearBuffers = inBuffers; } //--------------------------------------------------------------------- bool Viewport::getClearEveryFrame(void) const { return mClearEveryFrame; } //--------------------------------------------------------------------- unsigned int Viewport::getClearBuffers(void) const { return mClearBuffers; } //--------------------------------------------------------------------- void Viewport::clear(unsigned int buffers, const ColourValue& col, Real depth, unsigned short stencil) { RenderSystem* rs = Root::getSingleton().getRenderSystem(); if (rs) { Viewport* currentvp = rs->_getViewport(); if (currentvp && currentvp == this) rs->clearFrameBuffer(buffers, col, depth, stencil); else if (currentvp) { rs->_setViewport(this); rs->clearFrameBuffer(buffers, col, depth, stencil); rs->_setViewport(currentvp); } } } //--------------------------------------------------------------------- void Viewport::getActualDimensions(int &left, int&top, int &width, int &height) const { left = mActLeft; top = mActTop; width = mActWidth; height = mActHeight; } //--------------------------------------------------------------------- unsigned int Viewport::_getNumRenderedFaces(void) const { return mCamera ? mCamera->_getNumRenderedFaces() : 0; } //--------------------------------------------------------------------- unsigned int Viewport::_getNumRenderedBatches(void) const { return mCamera ? mCamera->_getNumRenderedBatches() : 0; } //--------------------------------------------------------------------- void Viewport::setCamera(Camera* cam) { if (cam != NULL && mCamera != NULL && mCamera->getViewport() == this) { mCamera->_notifyViewport(NULL); } mCamera = cam; if (cam) { // update aspect ratio of new camera if needed. if (cam->getAutoAspectRatio()) { cam->setAspectRatio((Real) mActWidth / (Real) mActHeight); } #if OGRE_NO_VIEWPORT_ORIENTATIONMODE == 0 cam->setOrientationMode(mOrientationMode); #endif cam->_notifyViewport(this); } for (ListenerList::iterator i = mListeners.begin(); i != mListeners.end(); ++i) { (*i)->viewportCameraChanged(this); } } //--------------------------------------------------------------------- void Viewport::setAutoUpdated(bool inAutoUpdated) { mIsAutoUpdated = inAutoUpdated; } //--------------------------------------------------------------------- bool Viewport::isAutoUpdated() const { return mIsAutoUpdated; } //--------------------------------------------------------------------- void Viewport::setOverlaysEnabled(bool enabled) { mShowOverlays = enabled; } //--------------------------------------------------------------------- bool Viewport::getOverlaysEnabled(void) const { return mShowOverlays; } //--------------------------------------------------------------------- void Viewport::setSkiesEnabled(bool enabled) { mShowSkies = enabled; } //--------------------------------------------------------------------- bool Viewport::getSkiesEnabled(void) const { return mShowSkies; } //--------------------------------------------------------------------- void Viewport::setShadowsEnabled(bool enabled) { mShowShadows = enabled; } //--------------------------------------------------------------------- bool Viewport::getShadowsEnabled(void) const { return mShowShadows; } //----------------------------------------------------------------------- void Viewport::setRenderQueueInvocationSequenceName(const String& sequenceName) { mRQSequenceName = sequenceName; if (mRQSequenceName.empty()) { mRQSequence = 0; } else { mRQSequence = Root::getSingleton().getRenderQueueInvocationSequence(mRQSequenceName); } } //----------------------------------------------------------------------- const String& Viewport::getRenderQueueInvocationSequenceName(void) const { return mRQSequenceName; } //----------------------------------------------------------------------- RenderQueueInvocationSequence* Viewport::_getRenderQueueInvocationSequence(void) { return mRQSequence; } //----------------------------------------------------------------------- void Viewport::pointOrientedToScreen(const Vector2 &v, int orientationMode, Vector2 &outv) { pointOrientedToScreen(v.x, v.y, orientationMode, outv.x, outv.y); } //----------------------------------------------------------------------- void Viewport::pointOrientedToScreen(Real orientedX, Real orientedY, int orientationMode, Real &screenX, Real &screenY) { Real orX = orientedX; Real orY = orientedY; switch (orientationMode) { case 1: screenX = orY; screenY = Real(1.0) - orX; break; case 2: screenX = Real(1.0) - orX; screenY = Real(1.0) - orY; break; case 3: screenX = Real(1.0) - orY; screenY = orX; break; default: screenX = orX; screenY = orY; break; } } //----------------------------------------------------------------------- void Viewport::addListener(Listener* l) { if (std::find(mListeners.begin(), mListeners.end(), l) == mListeners.end()) mListeners.push_back(l); } //----------------------------------------------------------------------- void Viewport::removeListener(Listener* l) { ListenerList::iterator i = std::find(mListeners.begin(), mListeners.end(), l); if (i != mListeners.end()) mListeners.erase(i); } //----------------------------------------------------------------------- void Viewport::setDrawBuffer(ColourBufferType colourBuffer) { mColourBuffer = colourBuffer; } //----------------------------------------------------------------------- ColourBufferType Viewport::getDrawBuffer() const { return mColourBuffer; } //----------------------------------------------------------------------- //----------------------------------------------------------------------- void Viewport::Listener::viewportCameraChanged(Viewport*) { } //----------------------------------------------------------------------- void Viewport::Listener::viewportDimensionsChanged(Viewport*) { } //----------------------------------------------------------------------- void Viewport::Listener::viewportDestroyed(Viewport*) { } } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * 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. * ************************************************************************/ #include <com/sun/star/awt/XAdjustmentListener.hpp> #include <com/sun/star/awt/XActionListener.hpp> #include <com/sun/star/awt/XTextListener.hpp> #include <com/sun/star/awt/XSpinListener.hpp> #include <com/sun/star/awt/XItemListener.hpp> #include <com/sun/star/awt/XVclContainerListener.hpp> #include <plugin/plctrl.hxx> #include <vcl/syschild.hxx> #include <toolkit/helper/vclunohelper.hxx> PluginControl_Impl::PluginControl_Impl() : _pMultiplexer( NULL ) , _nX( 0 ) , _nY( 0 ) , _nWidth( 100 ) , _nHeight( 100 ) , _nFlags( WINDOW_POSSIZE_ALL ) , _bVisible( sal_False ) , _bInDesignMode( sal_False ) , _bEnable( sal_True ) { } PluginControl_Impl::~PluginControl_Impl() { } MRCListenerMultiplexerHelper* PluginControl_Impl::getMultiplexer() { if( ! _pMultiplexer ) _pMultiplexer = new MRCListenerMultiplexerHelper( this, _xPeerWindow ); return _pMultiplexer; } void PluginControl_Impl::addEventListener( const Reference< ::com::sun::star::lang::XEventListener > & l ) throw( RuntimeException, std::exception ) { _aDisposeListeners.push_back( l ); } //---- ::com::sun::star::lang::XComponent ---------------------------------------------------------------------------------- void PluginControl_Impl::removeEventListener( const Reference< ::com::sun::star::lang::XEventListener > & l ) throw( RuntimeException, std::exception ) { _aDisposeListeners.remove( l ); } //---- ::com::sun::star::lang::XComponent ---------------------------------------------------------------------------------- void PluginControl_Impl::dispose(void) throw( RuntimeException, std::exception ) { // send disposing events ::com::sun::star::lang::EventObject aEvt; if( getMultiplexer() ) getMultiplexer()->disposeAndClear(); // release context _xContext = Reference< XInterface > (); releasePeer(); } //---- ::com::sun::star::awt::XWindow ------------------------------------------------------------------------------------- void PluginControl_Impl::setPosSize( sal_Int32 nX_, sal_Int32 nY_, sal_Int32 nWidth_, sal_Int32 nHeight_, sal_Int16 nFlags ) throw( RuntimeException, std::exception ) { _nX = nX_ >=0 ? nX_ : 0; _nY = nY_ >=0 ? nY_ : 0; _nWidth = nWidth_ >=0 ? nWidth_ : 0; _nHeight = nHeight_ >=0 ? nHeight_ : 0; _nFlags = nFlags; if (_xPeerWindow.is()) _xPeerWindow->setPosSize( _nX, _nY, _nWidth, _nHeight, nFlags ); } //---- ::com::sun::star::awt::XWindow ------------------------------------------------------------------------------------- ::com::sun::star::awt::Rectangle PluginControl_Impl::getPosSize(void) throw( RuntimeException, std::exception ) { return _xPeerWindow->getPosSize(); } //---- ::com::sun::star::awt::XWindow ------------------------------------------------------------------------------------- void PluginControl_Impl::setVisible( sal_Bool bVisible ) throw( RuntimeException, std::exception ) { _bVisible = bVisible; if (_xPeerWindow.is()) _xPeerWindow->setVisible( _bVisible && !_bInDesignMode ); } //---- ::com::sun::star::awt::XWindow ------------------------------------------------------------------------------------- void PluginControl_Impl::setEnable( sal_Bool bEnable ) throw( RuntimeException, std::exception ) { _bEnable = bEnable; if (_xPeerWindow.is()) _xPeerWindow->setEnable( _bEnable ); } //---- ::com::sun::star::awt::XWindow ------------------------------------------------------------------------------------- void PluginControl_Impl::setFocus(void) throw( RuntimeException, std::exception ) { if (_xPeerWindow.is()) _xPeerWindow->setFocus(); } void PluginControl_Impl::releasePeer() { if (_xPeer.is()) { _xParentWindow->removeFocusListener( this ); _xPeerWindow->dispose(); _pSysChild = NULL; _xPeerWindow = Reference< ::com::sun::star::awt::XWindow > (); _xPeer = Reference< ::com::sun::star::awt::XWindowPeer > (); getMultiplexer()->setPeer( Reference< ::com::sun::star::awt::XWindow > () ); } } //---- ::com::sun::star::awt::XControl ------------------------------------------------------------------------------------ void PluginControl_Impl::createPeer( const Reference< ::com::sun::star::awt::XToolkit > & /*xToolkit*/, const Reference< ::com::sun::star::awt::XWindowPeer > & xParentPeer ) throw( RuntimeException, std::exception ) { if (_xPeer.is()) { OSL_FAIL( "### Peer is already set!" ); return; } _xParentPeer = xParentPeer; _xParentWindow = Reference< ::com::sun::star::awt::XWindow > ( xParentPeer, UNO_QUERY ); DBG_ASSERT( _xParentWindow.is(), "### no parent peer window!" ); Window* pImpl = VCLUnoHelper::GetWindow( xParentPeer ); if (pImpl) { _pSysChild = new SystemChildWindow( pImpl, WB_CLIPCHILDREN ); if (pImpl->HasFocus()) _pSysChild->GrabFocus(); // get peer _xPeer = Reference< ::com::sun::star::awt::XWindowPeer > ( _pSysChild->GetComponentInterface() ); _xPeerWindow = Reference< ::com::sun::star::awt::XWindow > ( _xPeer, UNO_QUERY ); // !_BOTH_ MUST BE VALID! DBG_ASSERT( (_xPeer.is() && _xPeerWindow.is()), "### no peer!" ); _xParentWindow->addFocusListener( this ); _xPeerWindow->setPosSize( _nX, _nY, _nWidth, _nHeight, _nFlags ); _xPeerWindow->setEnable( _bEnable ); _xPeerWindow->setVisible( _bVisible && !_bInDesignMode ); } else { OSL_FAIL( "### cannot get implementation of parent peer!" ); } getMultiplexer()->setPeer( _xPeerWindow ); } //---- ::com::sun::star::awt::XControl ------------------------------------------------------------------------------------ void PluginControl_Impl::setDesignMode( sal_Bool bOn ) throw( RuntimeException, std::exception ) { _bInDesignMode = bOn; if (_xPeerWindow.is()) _xPeerWindow->setVisible( _bVisible && !_bInDesignMode ); } //---- ::com::sun::star::awt::XWindow ------------------------------------------------------------------------------------- void PluginControl_Impl::addPaintListener( const Reference< ::com::sun::star::awt::XPaintListener > & l ) throw( RuntimeException, std::exception ) { getMultiplexer()->advise( ::getCppuType((const Reference< ::com::sun::star::awt::XPaintListener >*)0), l ); } //---- ::com::sun::star::awt::XWindow ------------------------------------------------------------------------------------- void PluginControl_Impl::removePaintListener( const Reference< ::com::sun::star::awt::XPaintListener > & l ) throw( RuntimeException, std::exception ) { getMultiplexer()->unadvise( ::getCppuType((const Reference< ::com::sun::star::awt::XPaintListener >*)0), l ); } //---- ::com::sun::star::awt::XWindow ------------------------------------------------------------------------------------- void PluginControl_Impl::addWindowListener( const Reference< ::com::sun::star::awt::XWindowListener > & l ) throw( RuntimeException, std::exception ) { getMultiplexer()->advise( ::getCppuType((const Reference< ::com::sun::star::awt::XWindowListener >*)0), l ); } //---- ::com::sun::star::awt::XWindow ------------------------------------------------------------------------------------- void PluginControl_Impl::removeWindowListener( const Reference< ::com::sun::star::awt::XWindowListener > & l ) throw( RuntimeException, std::exception ) { getMultiplexer()->unadvise( ::getCppuType((const Reference< ::com::sun::star::awt::XWindowListener >*)0), l ); } //---- ::com::sun::star::awt::XWindow ------------------------------------------------------------------------------------- void PluginControl_Impl::addFocusListener( const Reference< ::com::sun::star::awt::XFocusListener > & l ) throw( RuntimeException, std::exception ) { getMultiplexer()->advise( ::getCppuType((const Reference< ::com::sun::star::awt::XFocusListener >*)0), l ); } //---- ::com::sun::star::awt::XWindow ------------------------------------------------------------------------------------- void PluginControl_Impl::removeFocusListener( const Reference< ::com::sun::star::awt::XFocusListener > & l ) throw( RuntimeException, std::exception ) { getMultiplexer()->unadvise( ::getCppuType((const Reference< ::com::sun::star::awt::XFocusListener >*)0), l ); } //---- ::com::sun::star::awt::XWindow ------------------------------------------------------------------------------------- void PluginControl_Impl::addKeyListener( const Reference< ::com::sun::star::awt::XKeyListener > & l ) throw( RuntimeException, std::exception ) { getMultiplexer()->advise( ::getCppuType((const Reference< ::com::sun::star::awt::XKeyListener >*)0), l ); } //---- ::com::sun::star::awt::XWindow ------------------------------------------------------------------------------------- void PluginControl_Impl::removeKeyListener( const Reference< ::com::sun::star::awt::XKeyListener > & l ) throw( RuntimeException, std::exception ) { getMultiplexer()->unadvise( ::getCppuType((const Reference< ::com::sun::star::awt::XKeyListener >*)0), l ); } //---- ::com::sun::star::awt::XWindow ------------------------------------------------------------------------------------- void PluginControl_Impl::addMouseListener( const Reference< ::com::sun::star::awt::XMouseListener > & l ) throw( RuntimeException, std::exception ) { getMultiplexer()->advise( ::getCppuType((const Reference< ::com::sun::star::awt::XMouseListener >*)0), l ); } //---- ::com::sun::star::awt::XWindow ------------------------------------------------------------------------------------- void PluginControl_Impl::removeMouseListener( const Reference< ::com::sun::star::awt::XMouseListener > & l ) throw( RuntimeException, std::exception ) { getMultiplexer()->unadvise( ::getCppuType((const Reference< ::com::sun::star::awt::XMouseListener >*)0), l ); } //---- ::com::sun::star::awt::XWindow ------------------------------------------------------------------------------------- void PluginControl_Impl::addMouseMotionListener( const Reference< ::com::sun::star::awt::XMouseMotionListener > & l ) throw( RuntimeException, std::exception ) { getMultiplexer()->advise( ::getCppuType((const Reference< ::com::sun::star::awt::XMouseMotionListener >*)0), l ); } //---- ::com::sun::star::awt::XWindow ------------------------------------------------------------------------------------- void PluginControl_Impl::removeMouseMotionListener( const Reference< ::com::sun::star::awt::XMouseMotionListener > & l ) throw( RuntimeException, std::exception ) { getMultiplexer()->unadvise( ::getCppuType((const Reference< ::com::sun::star::awt::XMouseMotionListener >*)0), l ); } //---- ::com::sun::star::awt::XView --------------------------------------------------------------------------------------- void PluginControl_Impl::draw( sal_Int32 /*x*/, sal_Int32 /*y*/ ) throw( RuntimeException, std::exception ) { // has to be done by further implementation of control } //---- ::com::sun::star::awt::XView --------------------------------------------------------------------------------------- void PluginControl_Impl::setZoom( float /*ZoomX*/, float /*ZoomY*/ ) throw( RuntimeException, std::exception ) { // has to be done by further implementation of control } //---- ::com::sun::star::lang::XEventListener ------------------------------------------------------------------------------ void PluginControl_Impl::disposing( const ::com::sun::star::lang::EventObject & /*rSource*/ ) throw( RuntimeException, std::exception ) { } //---- ::com::sun::star::awt::XFocusListener ------------------------------------------------------------------------------ void PluginControl_Impl::focusGained( const ::com::sun::star::awt::FocusEvent & /*rEvt*/ ) throw( RuntimeException, std::exception ) { if (_xPeerWindow.is()) _xPeerWindow->setFocus(); } //---- ::com::sun::star::awt::XFocusListener ------------------------------------------------------------------------------ void PluginControl_Impl::focusLost( const ::com::sun::star::awt::FocusEvent & /*rEvt*/ ) throw( RuntimeException, std::exception ) { } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>coverity#984088 Uninitialized pointer field<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * 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. * ************************************************************************/ #include <com/sun/star/awt/XAdjustmentListener.hpp> #include <com/sun/star/awt/XActionListener.hpp> #include <com/sun/star/awt/XTextListener.hpp> #include <com/sun/star/awt/XSpinListener.hpp> #include <com/sun/star/awt/XItemListener.hpp> #include <com/sun/star/awt/XVclContainerListener.hpp> #include <plugin/plctrl.hxx> #include <vcl/syschild.hxx> #include <toolkit/helper/vclunohelper.hxx> PluginControl_Impl::PluginControl_Impl() : _pMultiplexer( NULL ) , _nX( 0 ) , _nY( 0 ) , _nWidth( 100 ) , _nHeight( 100 ) , _nFlags( WINDOW_POSSIZE_ALL ) , _bVisible(false) , _bInDesignMode(false) , _bEnable(true) , _pSysChild(NULL) { } PluginControl_Impl::~PluginControl_Impl() { } MRCListenerMultiplexerHelper* PluginControl_Impl::getMultiplexer() { if( ! _pMultiplexer ) _pMultiplexer = new MRCListenerMultiplexerHelper( this, _xPeerWindow ); return _pMultiplexer; } void PluginControl_Impl::addEventListener( const Reference< ::com::sun::star::lang::XEventListener > & l ) throw( RuntimeException, std::exception ) { _aDisposeListeners.push_back( l ); } //---- ::com::sun::star::lang::XComponent ---------------------------------------------------------------------------------- void PluginControl_Impl::removeEventListener( const Reference< ::com::sun::star::lang::XEventListener > & l ) throw( RuntimeException, std::exception ) { _aDisposeListeners.remove( l ); } //---- ::com::sun::star::lang::XComponent ---------------------------------------------------------------------------------- void PluginControl_Impl::dispose(void) throw( RuntimeException, std::exception ) { // send disposing events ::com::sun::star::lang::EventObject aEvt; if( getMultiplexer() ) getMultiplexer()->disposeAndClear(); // release context _xContext = Reference< XInterface > (); releasePeer(); } //---- ::com::sun::star::awt::XWindow ------------------------------------------------------------------------------------- void PluginControl_Impl::setPosSize( sal_Int32 nX_, sal_Int32 nY_, sal_Int32 nWidth_, sal_Int32 nHeight_, sal_Int16 nFlags ) throw( RuntimeException, std::exception ) { _nX = nX_ >=0 ? nX_ : 0; _nY = nY_ >=0 ? nY_ : 0; _nWidth = nWidth_ >=0 ? nWidth_ : 0; _nHeight = nHeight_ >=0 ? nHeight_ : 0; _nFlags = nFlags; if (_xPeerWindow.is()) _xPeerWindow->setPosSize( _nX, _nY, _nWidth, _nHeight, nFlags ); } //---- ::com::sun::star::awt::XWindow ------------------------------------------------------------------------------------- ::com::sun::star::awt::Rectangle PluginControl_Impl::getPosSize(void) throw( RuntimeException, std::exception ) { return _xPeerWindow->getPosSize(); } //---- ::com::sun::star::awt::XWindow ------------------------------------------------------------------------------------- void PluginControl_Impl::setVisible( sal_Bool bVisible ) throw( RuntimeException, std::exception ) { _bVisible = bVisible; if (_xPeerWindow.is()) _xPeerWindow->setVisible( _bVisible && !_bInDesignMode ); } //---- ::com::sun::star::awt::XWindow ------------------------------------------------------------------------------------- void PluginControl_Impl::setEnable( sal_Bool bEnable ) throw( RuntimeException, std::exception ) { _bEnable = bEnable; if (_xPeerWindow.is()) _xPeerWindow->setEnable( _bEnable ); } //---- ::com::sun::star::awt::XWindow ------------------------------------------------------------------------------------- void PluginControl_Impl::setFocus(void) throw( RuntimeException, std::exception ) { if (_xPeerWindow.is()) _xPeerWindow->setFocus(); } void PluginControl_Impl::releasePeer() { if (_xPeer.is()) { _xParentWindow->removeFocusListener( this ); _xPeerWindow->dispose(); _pSysChild = NULL; _xPeerWindow = Reference< ::com::sun::star::awt::XWindow > (); _xPeer = Reference< ::com::sun::star::awt::XWindowPeer > (); getMultiplexer()->setPeer( Reference< ::com::sun::star::awt::XWindow > () ); } } //---- ::com::sun::star::awt::XControl ------------------------------------------------------------------------------------ void PluginControl_Impl::createPeer( const Reference< ::com::sun::star::awt::XToolkit > & /*xToolkit*/, const Reference< ::com::sun::star::awt::XWindowPeer > & xParentPeer ) throw( RuntimeException, std::exception ) { if (_xPeer.is()) { OSL_FAIL( "### Peer is already set!" ); return; } _xParentPeer = xParentPeer; _xParentWindow = Reference< ::com::sun::star::awt::XWindow > ( xParentPeer, UNO_QUERY ); DBG_ASSERT( _xParentWindow.is(), "### no parent peer window!" ); Window* pImpl = VCLUnoHelper::GetWindow( xParentPeer ); if (pImpl) { _pSysChild = new SystemChildWindow( pImpl, WB_CLIPCHILDREN ); if (pImpl->HasFocus()) _pSysChild->GrabFocus(); // get peer _xPeer = Reference< ::com::sun::star::awt::XWindowPeer > ( _pSysChild->GetComponentInterface() ); _xPeerWindow = Reference< ::com::sun::star::awt::XWindow > ( _xPeer, UNO_QUERY ); // !_BOTH_ MUST BE VALID! DBG_ASSERT( (_xPeer.is() && _xPeerWindow.is()), "### no peer!" ); _xParentWindow->addFocusListener( this ); _xPeerWindow->setPosSize( _nX, _nY, _nWidth, _nHeight, _nFlags ); _xPeerWindow->setEnable( _bEnable ); _xPeerWindow->setVisible( _bVisible && !_bInDesignMode ); } else { OSL_FAIL( "### cannot get implementation of parent peer!" ); } getMultiplexer()->setPeer( _xPeerWindow ); } //---- ::com::sun::star::awt::XControl ------------------------------------------------------------------------------------ void PluginControl_Impl::setDesignMode( sal_Bool bOn ) throw( RuntimeException, std::exception ) { _bInDesignMode = bOn; if (_xPeerWindow.is()) _xPeerWindow->setVisible( _bVisible && !_bInDesignMode ); } //---- ::com::sun::star::awt::XWindow ------------------------------------------------------------------------------------- void PluginControl_Impl::addPaintListener( const Reference< ::com::sun::star::awt::XPaintListener > & l ) throw( RuntimeException, std::exception ) { getMultiplexer()->advise( ::getCppuType((const Reference< ::com::sun::star::awt::XPaintListener >*)0), l ); } //---- ::com::sun::star::awt::XWindow ------------------------------------------------------------------------------------- void PluginControl_Impl::removePaintListener( const Reference< ::com::sun::star::awt::XPaintListener > & l ) throw( RuntimeException, std::exception ) { getMultiplexer()->unadvise( ::getCppuType((const Reference< ::com::sun::star::awt::XPaintListener >*)0), l ); } //---- ::com::sun::star::awt::XWindow ------------------------------------------------------------------------------------- void PluginControl_Impl::addWindowListener( const Reference< ::com::sun::star::awt::XWindowListener > & l ) throw( RuntimeException, std::exception ) { getMultiplexer()->advise( ::getCppuType((const Reference< ::com::sun::star::awt::XWindowListener >*)0), l ); } //---- ::com::sun::star::awt::XWindow ------------------------------------------------------------------------------------- void PluginControl_Impl::removeWindowListener( const Reference< ::com::sun::star::awt::XWindowListener > & l ) throw( RuntimeException, std::exception ) { getMultiplexer()->unadvise( ::getCppuType((const Reference< ::com::sun::star::awt::XWindowListener >*)0), l ); } //---- ::com::sun::star::awt::XWindow ------------------------------------------------------------------------------------- void PluginControl_Impl::addFocusListener( const Reference< ::com::sun::star::awt::XFocusListener > & l ) throw( RuntimeException, std::exception ) { getMultiplexer()->advise( ::getCppuType((const Reference< ::com::sun::star::awt::XFocusListener >*)0), l ); } //---- ::com::sun::star::awt::XWindow ------------------------------------------------------------------------------------- void PluginControl_Impl::removeFocusListener( const Reference< ::com::sun::star::awt::XFocusListener > & l ) throw( RuntimeException, std::exception ) { getMultiplexer()->unadvise( ::getCppuType((const Reference< ::com::sun::star::awt::XFocusListener >*)0), l ); } //---- ::com::sun::star::awt::XWindow ------------------------------------------------------------------------------------- void PluginControl_Impl::addKeyListener( const Reference< ::com::sun::star::awt::XKeyListener > & l ) throw( RuntimeException, std::exception ) { getMultiplexer()->advise( ::getCppuType((const Reference< ::com::sun::star::awt::XKeyListener >*)0), l ); } //---- ::com::sun::star::awt::XWindow ------------------------------------------------------------------------------------- void PluginControl_Impl::removeKeyListener( const Reference< ::com::sun::star::awt::XKeyListener > & l ) throw( RuntimeException, std::exception ) { getMultiplexer()->unadvise( ::getCppuType((const Reference< ::com::sun::star::awt::XKeyListener >*)0), l ); } //---- ::com::sun::star::awt::XWindow ------------------------------------------------------------------------------------- void PluginControl_Impl::addMouseListener( const Reference< ::com::sun::star::awt::XMouseListener > & l ) throw( RuntimeException, std::exception ) { getMultiplexer()->advise( ::getCppuType((const Reference< ::com::sun::star::awt::XMouseListener >*)0), l ); } //---- ::com::sun::star::awt::XWindow ------------------------------------------------------------------------------------- void PluginControl_Impl::removeMouseListener( const Reference< ::com::sun::star::awt::XMouseListener > & l ) throw( RuntimeException, std::exception ) { getMultiplexer()->unadvise( ::getCppuType((const Reference< ::com::sun::star::awt::XMouseListener >*)0), l ); } //---- ::com::sun::star::awt::XWindow ------------------------------------------------------------------------------------- void PluginControl_Impl::addMouseMotionListener( const Reference< ::com::sun::star::awt::XMouseMotionListener > & l ) throw( RuntimeException, std::exception ) { getMultiplexer()->advise( ::getCppuType((const Reference< ::com::sun::star::awt::XMouseMotionListener >*)0), l ); } //---- ::com::sun::star::awt::XWindow ------------------------------------------------------------------------------------- void PluginControl_Impl::removeMouseMotionListener( const Reference< ::com::sun::star::awt::XMouseMotionListener > & l ) throw( RuntimeException, std::exception ) { getMultiplexer()->unadvise( ::getCppuType((const Reference< ::com::sun::star::awt::XMouseMotionListener >*)0), l ); } //---- ::com::sun::star::awt::XView --------------------------------------------------------------------------------------- void PluginControl_Impl::draw( sal_Int32 /*x*/, sal_Int32 /*y*/ ) throw( RuntimeException, std::exception ) { // has to be done by further implementation of control } //---- ::com::sun::star::awt::XView --------------------------------------------------------------------------------------- void PluginControl_Impl::setZoom( float /*ZoomX*/, float /*ZoomY*/ ) throw( RuntimeException, std::exception ) { // has to be done by further implementation of control } //---- ::com::sun::star::lang::XEventListener ------------------------------------------------------------------------------ void PluginControl_Impl::disposing( const ::com::sun::star::lang::EventObject & /*rSource*/ ) throw( RuntimeException, std::exception ) { } //---- ::com::sun::star::awt::XFocusListener ------------------------------------------------------------------------------ void PluginControl_Impl::focusGained( const ::com::sun::star::awt::FocusEvent & /*rEvt*/ ) throw( RuntimeException, std::exception ) { if (_xPeerWindow.is()) _xPeerWindow->setFocus(); } //---- ::com::sun::star::awt::XFocusListener ------------------------------------------------------------------------------ void PluginControl_Impl::focusLost( const ::com::sun::star::awt::FocusEvent & /*rEvt*/ ) throw( RuntimeException, std::exception ) { } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#include "kevlar/Analyzers/NeutronPhotonYield.hh" #include "messagefacility/MessageLogger/MessageLogger.h" #include "art/Framework/Principal/Handle.h" #include "nusimdata/SimulationBase/MCParticle.h" #include <iostream> #include <map> #include <string> namespace kevlar{ NeutronPhotonYield::NeutronPhotonYield(fhicl::ParameterSet const& pSet) : art::EDAnalyzer(pSet), fProducerName(pSet.get<std::string>("ProducerLabel","largeant")), fOutFileName(pSet.get<std::string>("OutFileName","NeutronPhotonYield.csv")), fCSVOut() { } NeutronPhotonYield::~NeutronPhotonYield() { if(fCSVOut.is_open()) { fCSVOut.close(); } } void NeutronPhotonYield::analyze(art::Event const & evt) { art::Handle<std::vector<simb::MCParticle> > particles; evt.getByLabel(fProducerName, particles); std::map<int,int> neutronIds; std::map<int, std::string> processes; std::map<int, double> energies; for (auto particle: *particles){ int pdg= particle.PdgCode(); if (pdg != 2112) continue; neutronIds.insert(std::make_pair(particle.TrackId(),0 )); energies[mother] = particle.E(); } for (auto particle: *particles){ int pdg = particle.PdgCode(); if(pdg == 22 ){ int mother = particle.Mother(); if(neutronIds.find(mother) == neutronIds.end()) continue; neutronIds[mother] = neutronIds[mother]+1; processes[mother] = particle.Process(); } } for(std::map<int,int>::iterator it = neutronIds.begin(); it != neutronIds.end(); ++it ) { fCSVOut<<evt.id()<<", "<<it->first<<", "<<energies[it->first]<<", "<<it->second<<", "<<processes[it->first]<<std::endl; } } void NeutronPhotonYield::beginSubRun(art::SubRun const& ) { if(fCSVOut.is_open()) { fCSVOut.close(); } fCSVOut.open(fOutFileName, std::ofstream::out | std::ofstream::app); fCSVOut<<"EventID, TrackID, Energy, #Photons, Process"<<std::endl; } void NeutronPhotonYield::endSubRun(art::SubRun const&) { if(fCSVOut.is_open()) { fCSVOut.close(); } } }<commit_msg>Bugfix<commit_after>#include "kevlar/Analyzers/NeutronPhotonYield.hh" #include "messagefacility/MessageLogger/MessageLogger.h" #include "art/Framework/Principal/Handle.h" #include "nusimdata/SimulationBase/MCParticle.h" #include <iostream> #include <map> #include <string> namespace kevlar{ NeutronPhotonYield::NeutronPhotonYield(fhicl::ParameterSet const& pSet) : art::EDAnalyzer(pSet), fProducerName(pSet.get<std::string>("ProducerLabel","largeant")), fOutFileName(pSet.get<std::string>("OutFileName","NeutronPhotonYield.csv")), fCSVOut() { } NeutronPhotonYield::~NeutronPhotonYield() { if(fCSVOut.is_open()) fCSVOut.close(); } void NeutronPhotonYield::analyze(art::Event const & evt) { art::Handle<std::vector<simb::MCParticle> > particles; evt.getByLabel(fProducerName, particles); std::map<int,int> neutronIds; std::map<int, std::string> processes; std::map<int, double> energies; for (auto particle: *particles){ if (particle.PdgCode() != 2112) continue; neutronIds.insert(std::make_pair(particle.TrackId(),0 )); energies[particle.TrackId()] = particle.E(); } for (auto particle: *particles){ if(particle.PdgCode()== 22 ){ int mother = particle.Mother(); if(neutronIds.find(mother) == neutronIds.end()) continue; neutronIds[mother] = neutronIds[mother]+1; processes[mother] = particle.Process(); } } for(std::map<int,int>::iterator it = neutronIds.begin(); it != neutronIds.end(); ++it ) fCSVOut<<evt.id()<<", "<<it->first<<", "<<energies[it->first]<<", " <<it->second<<", "<<processes[it->first]<<std::endl; } void NeutronPhotonYield::beginSubRun(art::SubRun const& ) { if(fCSVOut.is_open()) fCSVOut.close(); fCSVOut.open(fOutFileName, std::ofstream::out | std::ofstream::app); fCSVOut<<"EventID, TrackID, Energy, #Photons, Process"<<std::endl; } void NeutronPhotonYield::endSubRun(art::SubRun const&) { if(fCSVOut.is_open()) fCSVOut.close(); } }<|endoftext|>
<commit_before>#include <iostream> #include <stdio.h> #include <stdlib.h> #include <fstream> #include <sys/stat.h> #include <math.h> #include <algorithm> #include <string.h> #include <stdint.h> #include <sstream> #include <iomanip> #include <gdal_priv.h> #include <cpl_conv.h> #include <ogr_spatialref.h> using namespace std; //to compile: c++ raster_math.cpp -o raster_math -lgdal // ./dead_wood_c_stock.exe 00N_000E_biomass.tif 00N_000E_res_ecozone.tif 00N_000E_res_srtm.tif 00N_000E_res_srtm.tif test.tif > values.txt int main(int argc, char* argv[]) { //passing arguments if (argc != 2){cout << "Use <program name> <tile_id>" << endl; return 1;} string tile_id = argv[1]; // carbon pools string bgc_name = tile_id + "_bgc.tif"; string agc_name = tile_id + "_carbon.tif"; string deadc_name = tile_id + "_deadwood.tif"; string soilc_name = tile_id + "_soil.tif"; string litterc_name = tile_id + "_litter.tif"; // aux data string lossyear_name = tile_id + "_loss.tif"; string lossclass_name = tile_id + "_res_forest_model.tif"; string peatdran_name = tile_id + "_res_peatdrainage.tif"; // set output file name string out_wildfire_name = tile_id + "_wildfire.tif"; // check which files were created. Some wont be there //inline bool exists(const peatdran_name) { // struct stat buffer; // return (stat (name.c_str(), &buffer) == 0); //} //setting variables int x, y; int xsize, ysize; double GeoTransform[6]; double ulx, uly; double pixelsize; //initialize GDAL for reading GDALAllRegister(); GDALDataset *INGDAL; GDALRasterBand *INBAND; GDALDataset *INGDAL2; GDALRasterBand *INBAND2; GDALDataset *INGDAL3; GDALRasterBand *INBAND3; GDALDataset *INGDAL4; GDALRasterBand *INBAND4; GDALDataset *INGDAL5; GDALRasterBand *INBAND5; GDALDataset *INGDAL6; GDALRasterBand *INBAND6; //loss GDALDataset *INGDAL7; GDALRasterBand *INBAND7; // lossclass GDALDataset *INGDAL8; GDALRasterBand *INBAND8; // peatdran //open file and get extent and projection INGDAL = (GDALDataset *) GDALOpen(bgc_name.c_str(), GA_ReadOnly ); INBAND = INGDAL->GetRasterBand(1); xsize=INBAND->GetXSize(); ysize=INBAND->GetYSize(); INGDAL->GetGeoTransform(GeoTransform); ulx=GeoTransform[0]; uly=GeoTransform[3]; pixelsize=GeoTransform[1]; cout << xsize <<", "<< ysize <<", "<< ulx <<", "<< uly << ", "<< pixelsize << endl; INGDAL2 = (GDALDataset *) GDALOpen(agc_name.c_str(), GA_ReadOnly ); INBAND2 = INGDAL2->GetRasterBand(1); INGDAL3 = (GDALDataset *) GDALOpen(deadc_name.c_str(), GA_ReadOnly ); INBAND3 = INGDAL3->GetRasterBand(1); INGDAL4 = (GDALDataset *) GDALOpen(litterc_name.c_str(), GA_ReadOnly ); INBAND4 = INGDAL4->GetRasterBand(1); INGDAL5 = (GDALDataset *) GDALOpen(soilc_name.c_str(), GA_ReadOnly ); INBAND5 = INGDAL5->GetRasterBand(1); INGDAL6 = (GDALDataset *) GDALOpen(lossyear_name.c_str(), GA_ReadOnly ); INBAND6 = INGDAL6->GetRasterBand(1); INGDAL7 = (GDALDataset *) GDALOpen(lossclass_name.c_str(), GA_ReadOnly ); INBAND7 = INGDAL7->GetRasterBand(1); INGDAL8 = (GDALDataset *) GDALOpen(peatdran_name.c_str(), GA_ReadOnly ); INBAND8 = INGDAL8->GetRasterBand(1); //initialize GDAL for writing GDALDriver *OUTDRIVER; GDALDataset *OUTGDAL; GDALRasterBand *OUTBAND1; OGRSpatialReference oSRS; char *OUTPRJ = NULL; char **papszOptions = NULL; papszOptions = CSLSetNameValue( papszOptions, "COMPRESS", "LZW" ); OUTDRIVER = GetGDALDriverManager()->GetDriverByName("GTIFF"); if( OUTDRIVER == NULL ) {cout << "no driver" << endl; exit( 1 );}; oSRS.SetWellKnownGeogCS( "WGS84" ); oSRS.exportToWkt( &OUTPRJ ); double adfGeoTransform[6] = { ulx, pixelsize, 0, uly, 0, -1*pixelsize }; OUTGDAL = OUTDRIVER->Create( out_wildfire_name.c_str(), xsize, ysize, 1, GDT_Float32, papszOptions ); OUTGDAL->SetGeoTransform(adfGeoTransform); OUTGDAL->SetProjection(OUTPRJ); OUTBAND1 = OUTGDAL->GetRasterBand(1); OUTBAND1->SetNoDataValue(-9999); //read/write data float bgc_data[xsize]; float agc_data[xsize]; float deadc_data[xsize]; float litterc_data[xsize]; float soilc_data[xsize]; float loss_data[xsize]; float lossclass_data[xsize]; float peatdran_data[xsize]; float out_wildfire_data[xsize]; for(y=0; y<ysize; y++) { INBAND->RasterIO(GF_Read, 0, y, xsize, 1, bgc_data, xsize, 1, GDT_Float32, 0, 0); INBAND2->RasterIO(GF_Read, 0, y, xsize, 1, agc_data, xsize, 1, GDT_Float32, 0, 0); INBAND3->RasterIO(GF_Read, 0, y, xsize, 1, deadc_data, xsize, 1, GDT_Float32, 0, 0); INBAND4->RasterIO(GF_Read, 0, y, xsize, 1, litterc_data, xsize, 1, GDT_Float32, 0, 0); INBAND5->RasterIO(GF_Read, 0, y, xsize, 1, soilc_data, xsize, 1, GDT_Float32, 0, 0); INBAND6->RasterIO(GF_Read, 0, y, xsize, 1, loss_data, xsize, 1, GDT_Float32, 0, 0); INBAND7->RasterIO(GF_Read, 0, y, xsize, 1, lossclass_data, xsize, 1, GDT_Float32, 0, 0); INBAND8->RasterIO(GF_Read, 0, y, xsize, 1, peatdran_data, xsize, 1, GDT_Float32, 0, 0); for(x=0; x<xsize; x++) { if (lossclass_data[x] == 1) { //cout << "loss class data is 1: " << lossclass_data[x] <<"\n"; out_wildfire_data[x] = loss_data[x];} else { //cout << "loss class data is not 1: " << lossclass_data[x] << " \n"; out_wildfire_data[x] = -9999;} //closes for x loop } OUTBAND1->RasterIO( GF_Write, 0, y, xsize, 1, out_wildfire_data, xsize, 1, GDT_Float32, 0, 0 ); //closes for y loop } //close GDAL GDALClose(INGDAL); GDALClose((GDALDatasetH)OUTGDAL); return 0; } <commit_msg>began structure for forestry<commit_after>#include <iostream> #include <stdio.h> #include <stdlib.h> #include <fstream> #include <sys/stat.h> #include <math.h> #include <algorithm> #include <string.h> #include <stdint.h> #include <sstream> #include <iomanip> #include <gdal_priv.h> #include <cpl_conv.h> #include <ogr_spatialref.h> using namespace std; //to compile: c++ raster_math.cpp -o raster_math -lgdal // ./dead_wood_c_stock.exe 00N_000E_biomass.tif 00N_000E_res_ecozone.tif 00N_000E_res_srtm.tif 00N_000E_res_srtm.tif test.tif > values.txt int main(int argc, char* argv[]) { //passing arguments if (argc != 2){cout << "Use <program name> <tile_id>" << endl; return 1;} string tile_id = argv[1]; // carbon pools string bgc_name = tile_id + "_bgc.tif"; string agc_name = tile_id + "_carbon.tif"; string deadc_name = tile_id + "_deadwood.tif"; string soilc_name = tile_id + "_soil.tif"; string litterc_name = tile_id + "_litter.tif"; // aux data string lossyear_name = tile_id + "_loss.tif"; string lossclass_name = tile_id + "_res_forest_model.tif"; string peatdran_name = tile_id + "_res_peatdrainage.tif"; string hist_name = tile_id + "_res_hwsd_histosoles.tif"; // set output file name string out_wildfire_name = tile_id + "_wildfire.tif"; string out_forestry_name = tile_id + "_forestry.tif"; // check which files were created. Some wont be there //inline bool exists(const peatdran_name) { // struct stat buffer; // return (stat (name.c_str(), &buffer) == 0); //} //setting variables int x, y; int xsize, ysize; double GeoTransform[6]; double ulx, uly; double pixelsize; //initialize GDAL for reading GDALAllRegister(); GDALDataset *INGDAL; GDALRasterBand *INBAND; GDALDataset *INGDAL2; GDALRasterBand *INBAND2; GDALDataset *INGDAL3; GDALRasterBand *INBAND3; GDALDataset *INGDAL4; GDALRasterBand *INBAND4; GDALDataset *INGDAL5; GDALRasterBand *INBAND5; GDALDataset *INGDAL6; GDALRasterBand *INBAND6; //loss GDALDataset *INGDAL7; GDALRasterBand *INBAND7; // lossclass GDALDataset *INGDAL8; GDALRasterBand *INBAND8; // peatdran GDALDataset *INGDAL9; GDALRasterBand *INBAND9; // histosoles //open file and get extent and projection INGDAL = (GDALDataset *) GDALOpen(bgc_name.c_str(), GA_ReadOnly ); INBAND = INGDAL->GetRasterBand(1); xsize=INBAND->GetXSize(); ysize=INBAND->GetYSize(); INGDAL->GetGeoTransform(GeoTransform); ulx=GeoTransform[0]; uly=GeoTransform[3]; pixelsize=GeoTransform[1]; cout << xsize <<", "<< ysize <<", "<< ulx <<", "<< uly << ", "<< pixelsize << endl; INGDAL2 = (GDALDataset *) GDALOpen(agc_name.c_str(), GA_ReadOnly ); INBAND2 = INGDAL2->GetRasterBand(1); INGDAL3 = (GDALDataset *) GDALOpen(deadc_name.c_str(), GA_ReadOnly ); INBAND3 = INGDAL3->GetRasterBand(1); INGDAL4 = (GDALDataset *) GDALOpen(litterc_name.c_str(), GA_ReadOnly ); INBAND4 = INGDAL4->GetRasterBand(1); INGDAL5 = (GDALDataset *) GDALOpen(soilc_name.c_str(), GA_ReadOnly ); INBAND5 = INGDAL5->GetRasterBand(1); INGDAL6 = (GDALDataset *) GDALOpen(lossyear_name.c_str(), GA_ReadOnly ); INBAND6 = INGDAL6->GetRasterBand(1); INGDAL7 = (GDALDataset *) GDALOpen(lossclass_name.c_str(), GA_ReadOnly ); INBAND7 = INGDAL7->GetRasterBand(1); INGDAL8 = (GDALDataset *) GDALOpen(peatdran_name.c_str(), GA_ReadOnly ); INBAND8 = INGDAL8->GetRasterBand(1); INGDAL9 = (GDALDataset *) GDALOpen(hist_name.c_str(), GA_ReadOnly ); INBAND9 = INGDAL8->GetRasterBand(1); //initialize GDAL for writing GDALDriver *OUTDRIVER; GDALDataset *OUTGDAL; GDALRasterBand *OUTBAND1; OGRSpatialReference oSRS; char *OUTPRJ = NULL; char **papszOptions = NULL; papszOptions = CSLSetNameValue( papszOptions, "COMPRESS", "LZW" ); OUTDRIVER = GetGDALDriverManager()->GetDriverByName("GTIFF"); if( OUTDRIVER == NULL ) {cout << "no driver" << endl; exit( 1 );}; oSRS.SetWellKnownGeogCS( "WGS84" ); oSRS.exportToWkt( &OUTPRJ ); double adfGeoTransform[6] = { ulx, pixelsize, 0, uly, 0, -1*pixelsize }; OUTGDAL = OUTDRIVER->Create( out_wildfire_name.c_str(), xsize, ysize, 1, GDT_Float32, papszOptions ); OUTGDAL->SetGeoTransform(adfGeoTransform); OUTGDAL->SetProjection(OUTPRJ); OUTBAND1 = OUTGDAL->GetRasterBand(1); OUTBAND1->SetNoDataValue(-9999); OUTGDAL2 = OUTDRIVER->Create( out_forestry_name.c_str(), xsize, ysize, 1, GDT_Float32, papszOptions ); OUTGDAL2->SetGeoTransform(adfGeoTransform); OUTGDAL->SetProjection(OUTPRJ); OUTBAND2 = OUTGDAL->GetRasterBand(1); OUTBAND2->SetNoDataValue(-9999); //read/write data float bgc_data[xsize]; float agc_data[xsize]; float deadc_data[xsize]; float litterc_data[xsize]; float soilc_data[xsize]; float loss_data[xsize]; float lossclass_data[xsize]; float peatdran_data[xsize]; float hist_data[xsize]; float out_wildfire_data[xsize]; for(y=0; y<ysize; y++) { INBAND->RasterIO(GF_Read, 0, y, xsize, 1, bgc_data, xsize, 1, GDT_Float32, 0, 0); INBAND2->RasterIO(GF_Read, 0, y, xsize, 1, agc_data, xsize, 1, GDT_Float32, 0, 0); INBAND3->RasterIO(GF_Read, 0, y, xsize, 1, deadc_data, xsize, 1, GDT_Float32, 0, 0); INBAND4->RasterIO(GF_Read, 0, y, xsize, 1, litterc_data, xsize, 1, GDT_Float32, 0, 0); INBAND5->RasterIO(GF_Read, 0, y, xsize, 1, soilc_data, xsize, 1, GDT_Float32, 0, 0); INBAND6->RasterIO(GF_Read, 0, y, xsize, 1, loss_data, xsize, 1, GDT_Float32, 0, 0); INBAND7->RasterIO(GF_Read, 0, y, xsize, 1, lossclass_data, xsize, 1, GDT_Float32, 0, 0); INBAND8->RasterIO(GF_Read, 0, y, xsize, 1, peatdran_data, xsize, 1, GDT_Float32, 0, 0); INBAND9->RasterIO(GF_Read, 0, y, xsize, 1, hist_data, xsize, 1, GDT_Float32, 0, 0); for(x=0; x<xsize; x++) { if (loss_data[x] > 0) { if (peatdran_data[x] != -9999) { if (burned_data[x] != -9999) { out_wildfire_data[x] = ((agc_data[x] + bgc_data[x]) * 3.67) + (15 - loss_data[x] * peatdran_data[x]) + 917 } else { out_wildfire_data[x] = ((agc_data[x] + bgc_data[x]) * 3.67) + (15 - loss_data[x] * peatdran_data[x]) } } else { if (hist_data[x] != -9999) { if (climate_data[x] = 1) // tropics { ((agc_data[x] + bgc_data[x]) * 3.67) + (15 - loss_data[x] * 55) } if (climate_data[x] = 2) // boreal { ((agc_data[x] + bgc_data[x]) * 3.67) + (15 - loss_data[x] * 2.16) } if (climate_data[x] = 3) // temperate { ((agc_data[x] + bgc_data[x]) * 3.67) + (15 - loss_data[x] * 6.27) } } else { out_wildfire_data[x] = -9999 } } } else { out_wildfire_data[x] = -9999 } //closes for x loop } OUTBAND1->RasterIO( GF_Write, 0, y, xsize, 1, out_wildfire_data, xsize, 1, GDT_Float32, 0, 0 ); OUTBAND2->RasterIO( GF_Write, 0, y, xsize, 1, out_forestry_data, xsize, 1, GDT_Float32, 0, 0 ); //closes for y loop } //close GDAL GDALClose(INGDAL); GDALClose((GDALDatasetH)OUTGDAL); return 0; } <|endoftext|>
<commit_before> #include <memory> #include <string> #include <vector> #include "astronomy/time_scales.hpp" #include "base/file.hpp" #include "base/not_null.hpp" #include "base/pull_serializer.hpp" #include "base/push_deserializer.hpp" #include "glog/logging.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "ksp_plugin/interface.hpp" #include "ksp_plugin/plugin.hpp" #include "serialization/ksp_plugin.pb.h" #include "testing_utilities/serialization.hpp" namespace principia { namespace interface { using astronomy::operator""_TT; using astronomy::TTSecond; using astronomy::date_time::DateTime; using astronomy::date_time::operator""_DateTime; using base::not_null; using base::OFStream; using base::PullSerializer; using base::PushDeserializer; using ksp_plugin::Plugin; using quantities::Speed; using testing_utilities::ReadLinesFromBase64File; using testing_utilities::ReadLinesFromHexadecimalFile; using ::testing::AllOf; using ::testing::ElementsAre; using ::testing::Eq; using ::testing::HasSubstr; using ::testing::Not; using ::testing::NotNull; using ::testing::Pair; using ::testing::internal::CaptureStderr; using ::testing::internal::GetCapturedStderr; const char preferred_compressor[] = "gipfeli"; const char preferred_encoder[] = "base64"; class StringLogSink : google::LogSink { public: StringLogSink(google::LogSeverity const minimal_severity) : minimal_severity_(minimal_severity) { google::AddLogSink(this); } ~StringLogSink() { google::RemoveLogSink(this); } void send(google::LogSeverity const severity, char const* const full_filename, char const* const base_filename, int const line, tm const* const tm_time, const char* const message, size_t const message_len) override { absl::MutexLock lock(&mutex_); absl::StrAppend( &string_, ToString(severity, base_filename, line, tm_time, message, message_len)); } std::string& string() { return string_; } private: google::LogSeverity const minimal_severity_; absl::Mutex mutex_; std::string string_ GUARDED_BY(mutex_); }; class PluginCompatibilityTest : public testing::Test { protected: PluginCompatibilityTest() { google::SetStderrLogging(google::WARNING); } // Reads a plugin from a file containing only the "serialized_plugin = " // lines, with "serialized_plugin = " dropped. static not_null<std::unique_ptr<Plugin const>> ReadPluginFromFile( std::filesystem::path const& filename, std::string_view const compressor, std::string_view const encoder) { Plugin const* plugin = nullptr; PushDeserializer* deserializer = nullptr; auto const lines = encoder == "hexadecimal" ? ReadLinesFromHexadecimalFile(filename) : encoder == "base64" ? ReadLinesFromBase64File(filename) : std::vector<std::string>{}; CHECK(!lines.empty()); LOG(ERROR) << "Deserialization starting"; for (std::string const& line : lines) { principia__DeserializePlugin(line.c_str(), &deserializer, &plugin, compressor.data(), encoder.data()); } principia__DeserializePlugin("", &deserializer, &plugin, compressor.data(), encoder.data()); LOG(ERROR) << "Deserialization complete"; return std::unique_ptr<Plugin const>(plugin); } // Writes a plugin to a file. static void WritePluginToFile( std::filesystem::path const& filename, std::string_view const compressor, std::string_view const encoder, not_null<std::unique_ptr<Plugin const>> plugin) { OFStream file(filename); PullSerializer* serializer = nullptr; char const* b64 = nullptr; LOG(ERROR) << "Serialization starting"; for (;;) { b64 = principia__SerializePlugin(plugin.get(), &serializer, preferred_compressor, preferred_encoder); if (b64 == nullptr) { break; } file << b64 << "\n"; principia__DeleteString(&b64); } LOG(ERROR) << "Serialization complete"; Plugin const* released_plugin = plugin.release(); principia__DeletePlugin(&released_plugin); } static void WriteAndReadBack(not_null<std::unique_ptr<Plugin const>> plugin1) { // Write the plugin to a new file with the preferred format. WritePluginToFile(TEMP_DIR / "serialized_plugin.proto.b64", preferred_compressor, preferred_encoder, std::move(plugin1)); // Read the plugin from the new file to make sure that it's fine. auto plugin2 = ReadPluginFromFile(TEMP_DIR / "serialized_plugin.proto.b64", preferred_compressor, preferred_encoder); } static void CheckSaveCompatibility(std::filesystem::path const& filename, std::string_view const compressor, std::string_view const encoder) { // Read a plugin from the given file. auto plugin = ReadPluginFromFile(filename, compressor, encoder); WriteAndReadBack(std::move(plugin)); } }; TEST_F(PluginCompatibilityTest, PreCartan) { // This space for rent. } TEST_F(PluginCompatibilityTest, PreCohen) { StringLogSink log_warning(google::WARNING); CheckSaveCompatibility( SOLUTION_DIR / "ksp_plugin_test" / "saves" / "3039.proto.hex", /*compressor=*/"", /*decoder=*/"hexadecimal"); EXPECT_THAT( log_warning.string(), AllOf( HasSubstr( "pre-Cohen ContinuousTrajectory"), // Regression test for #3039. HasSubstr("pre-Cauchy"), // The save is even older. Not(HasSubstr("pre-Cartan")) // But not *that* old. )); } TEST_F(PluginCompatibilityTest, Reach) { StringLogSink log_warning(google::WARNING); not_null<std::unique_ptr<Plugin const>> plugin = ReadPluginFromFile( SOLUTION_DIR / "ksp_plugin_test" / "saves" / "3072.proto.b64", /*compressor=*/"gipfeli", /*decoder=*/"base64"); EXPECT_THAT(log_warning.string(), AllOf(HasSubstr("pre-Galileo"), Not(HasSubstr("pre-Frobenius")))); auto const test = plugin->GetVessel("f2d77873-4776-4809-9dfb-de9e7a0620a6"); EXPECT_THAT(test->name(), Eq("TEST")); EXPECT_THAT(TTSecond(test->psychohistory().front().time), Eq("1970-08-14T08:03:18"_DateTime)); EXPECT_THAT(TTSecond(test->psychohistory().back().time), Eq("1970-08-14T08:47:05"_DateTime)); EXPECT_FALSE(test->has_flight_plan()); auto const ifnity = plugin->GetVessel("29142a79-7acd-47a9-a34d-f9f2a8e1b4ed"); EXPECT_THAT(ifnity->name(), Eq("IFNITY-5.2")); EXPECT_THAT(TTSecond(ifnity->psychohistory().front().time), Eq("1970-08-14T08:03:46"_DateTime)); EXPECT_THAT(TTSecond(ifnity->psychohistory().back().time), Eq("1970-08-14T08:47:05"_DateTime)); ASSERT_TRUE(ifnity->has_flight_plan()); EXPECT_THAT(ifnity->flight_plan().number_of_manœuvres(), Eq(16)); std::vector<std::pair<DateTime, Speed>> manœuvre_ignition_tt_seconds_and_Δvs; for (int i = 0; i < ifnity->flight_plan().number_of_manœuvres(); ++i) { manœuvre_ignition_tt_seconds_and_Δvs.emplace_back( TTSecond(ifnity->flight_plan().GetManœuvre(i).initial_time()), ifnity->flight_plan().GetManœuvre(i).Δv().Norm()); } // The flight plan only covers the inner solar system (this is probably // because of #3035). // It also differs from https://youtu.be/7BDxZV7UD9I?t=439. // TODO(egg): Compute the flybys and figure out what exactly is going on in // this flight plan. EXPECT_THAT(manœuvre_ignition_tt_seconds_and_Δvs, ElementsAre(Pair("1970-08-14T09:34:49"_DateTime, 3.80488671073918022e+03 * (Metre / Second)), Pair("1970-08-15T13:59:24"_DateTime, 3.04867185471741759e-04 * (Metre / Second)), Pair("1970-12-22T07:48:21"_DateTime, 1.58521291818444873e-03 * (Metre / Second)), Pair("1971-01-08T17:36:55"_DateTime, 1.40000000034068623e-03 * (Metre / Second)), Pair("1971-07-02T17:16:00"_DateTime, 1.00000000431022681e-04 * (Metre / Second)), Pair("1971-09-06T03:27:33"_DateTime, 1.78421858738381537e-03 * (Metre / Second)), Pair("1972-02-13T22:47:26"_DateTime, 7.72606625794511597e-04 * (Metre / Second)), Pair("1972-03-25T16:30:19"_DateTime, 5.32846131747503372e-03 * (Metre / Second)), Pair("1972-12-24T04:09:32"_DateTime, 3.45000000046532824e-03 * (Metre / Second)), Pair("1973-06-04T01:59:07"_DateTime, 9.10695453328359134e-03 * (Metre / Second)), Pair("1973-07-09T06:07:17"_DateTime, 4.49510921430966881e-01 * (Metre / Second)), Pair("1973-09-10T03:59:44"_DateTime, 1.00000000431022681e-04 * (Metre / Second)), Pair("1974-11-20T17:34:27"_DateTime, 5.10549409572428781e-01 * (Metre / Second)), Pair("1975-10-07T01:29:45"_DateTime, 2.86686518692948443e-02 * (Metre / Second)), Pair("1975-12-29T21:27:13"_DateTime, 1.00404183285598275e-03 * (Metre / Second)), Pair("1977-07-28T22:47:53"_DateTime, 1.39666705839172456e-01 * (Metre / Second)))); // Make sure that we can upgrade, save, and reload. WriteAndReadBack(std::move(plugin)); } // Use for debugging saves given by users. TEST_F(PluginCompatibilityTest, DISABLED_SECULAR_Debug) { CheckSaveCompatibility( R"(P:\Public Mockingbird\Principia\Saves\2685\five-minute-scene-change-neptune.txt)", /*compressor=*/"gipfeli", /*decoder=*/"base64"); } } // namespace interface } // namespace principia <commit_msg>minimal_severity_<commit_after> #include <memory> #include <string> #include <vector> #include "astronomy/time_scales.hpp" #include "base/file.hpp" #include "base/not_null.hpp" #include "base/pull_serializer.hpp" #include "base/push_deserializer.hpp" #include "glog/logging.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "ksp_plugin/interface.hpp" #include "ksp_plugin/plugin.hpp" #include "serialization/ksp_plugin.pb.h" #include "testing_utilities/serialization.hpp" namespace principia { namespace interface { using astronomy::operator""_TT; using astronomy::TTSecond; using astronomy::date_time::DateTime; using astronomy::date_time::operator""_DateTime; using base::not_null; using base::OFStream; using base::PullSerializer; using base::PushDeserializer; using ksp_plugin::Plugin; using quantities::Speed; using testing_utilities::ReadLinesFromBase64File; using testing_utilities::ReadLinesFromHexadecimalFile; using ::testing::AllOf; using ::testing::ElementsAre; using ::testing::Eq; using ::testing::HasSubstr; using ::testing::Not; using ::testing::NotNull; using ::testing::Pair; using ::testing::internal::CaptureStderr; using ::testing::internal::GetCapturedStderr; const char preferred_compressor[] = "gipfeli"; const char preferred_encoder[] = "base64"; class StringLogSink : google::LogSink { public: StringLogSink(google::LogSeverity const minimal_severity) : minimal_severity_(minimal_severity) { google::AddLogSink(this); } ~StringLogSink() { google::RemoveLogSink(this); } void send(google::LogSeverity const severity, char const* const full_filename, char const* const base_filename, int const line, tm const* const tm_time, const char* const message, size_t const message_len) override { if (severity < minimal_severity_) { return; } absl::MutexLock lock(&mutex_); absl::StrAppend( &string_, ToString(severity, base_filename, line, tm_time, message, message_len)); } std::string& string() { return string_; } private: google::LogSeverity const minimal_severity_; absl::Mutex mutex_; std::string string_ GUARDED_BY(mutex_); }; class PluginCompatibilityTest : public testing::Test { protected: PluginCompatibilityTest() { google::SetStderrLogging(google::WARNING); } // Reads a plugin from a file containing only the "serialized_plugin = " // lines, with "serialized_plugin = " dropped. static not_null<std::unique_ptr<Plugin const>> ReadPluginFromFile( std::filesystem::path const& filename, std::string_view const compressor, std::string_view const encoder) { Plugin const* plugin = nullptr; PushDeserializer* deserializer = nullptr; auto const lines = encoder == "hexadecimal" ? ReadLinesFromHexadecimalFile(filename) : encoder == "base64" ? ReadLinesFromBase64File(filename) : std::vector<std::string>{}; CHECK(!lines.empty()); LOG(ERROR) << "Deserialization starting"; for (std::string const& line : lines) { principia__DeserializePlugin(line.c_str(), &deserializer, &plugin, compressor.data(), encoder.data()); } principia__DeserializePlugin("", &deserializer, &plugin, compressor.data(), encoder.data()); LOG(ERROR) << "Deserialization complete"; return std::unique_ptr<Plugin const>(plugin); } // Writes a plugin to a file. static void WritePluginToFile( std::filesystem::path const& filename, std::string_view const compressor, std::string_view const encoder, not_null<std::unique_ptr<Plugin const>> plugin) { OFStream file(filename); PullSerializer* serializer = nullptr; char const* b64 = nullptr; LOG(ERROR) << "Serialization starting"; for (;;) { b64 = principia__SerializePlugin(plugin.get(), &serializer, preferred_compressor, preferred_encoder); if (b64 == nullptr) { break; } file << b64 << "\n"; principia__DeleteString(&b64); } LOG(ERROR) << "Serialization complete"; Plugin const* released_plugin = plugin.release(); principia__DeletePlugin(&released_plugin); } static void WriteAndReadBack(not_null<std::unique_ptr<Plugin const>> plugin1) { // Write the plugin to a new file with the preferred format. WritePluginToFile(TEMP_DIR / "serialized_plugin.proto.b64", preferred_compressor, preferred_encoder, std::move(plugin1)); // Read the plugin from the new file to make sure that it's fine. auto plugin2 = ReadPluginFromFile(TEMP_DIR / "serialized_plugin.proto.b64", preferred_compressor, preferred_encoder); } static void CheckSaveCompatibility(std::filesystem::path const& filename, std::string_view const compressor, std::string_view const encoder) { // Read a plugin from the given file. auto plugin = ReadPluginFromFile(filename, compressor, encoder); WriteAndReadBack(std::move(plugin)); } }; TEST_F(PluginCompatibilityTest, PreCartan) { // This space for rent. } TEST_F(PluginCompatibilityTest, PreCohen) { StringLogSink log_warning(google::WARNING); CheckSaveCompatibility( SOLUTION_DIR / "ksp_plugin_test" / "saves" / "3039.proto.hex", /*compressor=*/"", /*decoder=*/"hexadecimal"); EXPECT_THAT( log_warning.string(), AllOf( HasSubstr( "pre-Cohen ContinuousTrajectory"), // Regression test for #3039. HasSubstr("pre-Cauchy"), // The save is even older. Not(HasSubstr("pre-Cartan")) // But not *that* old. )); } TEST_F(PluginCompatibilityTest, Reach) { StringLogSink log_warning(google::WARNING); not_null<std::unique_ptr<Plugin const>> plugin = ReadPluginFromFile( SOLUTION_DIR / "ksp_plugin_test" / "saves" / "3072.proto.b64", /*compressor=*/"gipfeli", /*decoder=*/"base64"); EXPECT_THAT(log_warning.string(), AllOf(HasSubstr("pre-Galileo"), Not(HasSubstr("pre-Frobenius")))); auto const test = plugin->GetVessel("f2d77873-4776-4809-9dfb-de9e7a0620a6"); EXPECT_THAT(test->name(), Eq("TEST")); EXPECT_THAT(TTSecond(test->psychohistory().front().time), Eq("1970-08-14T08:03:18"_DateTime)); EXPECT_THAT(TTSecond(test->psychohistory().back().time), Eq("1970-08-14T08:47:05"_DateTime)); EXPECT_FALSE(test->has_flight_plan()); auto const ifnity = plugin->GetVessel("29142a79-7acd-47a9-a34d-f9f2a8e1b4ed"); EXPECT_THAT(ifnity->name(), Eq("IFNITY-5.2")); EXPECT_THAT(TTSecond(ifnity->psychohistory().front().time), Eq("1970-08-14T08:03:46"_DateTime)); EXPECT_THAT(TTSecond(ifnity->psychohistory().back().time), Eq("1970-08-14T08:47:05"_DateTime)); ASSERT_TRUE(ifnity->has_flight_plan()); EXPECT_THAT(ifnity->flight_plan().number_of_manœuvres(), Eq(16)); std::vector<std::pair<DateTime, Speed>> manœuvre_ignition_tt_seconds_and_Δvs; for (int i = 0; i < ifnity->flight_plan().number_of_manœuvres(); ++i) { manœuvre_ignition_tt_seconds_and_Δvs.emplace_back( TTSecond(ifnity->flight_plan().GetManœuvre(i).initial_time()), ifnity->flight_plan().GetManœuvre(i).Δv().Norm()); } // The flight plan only covers the inner solar system (this is probably // because of #3035). // It also differs from https://youtu.be/7BDxZV7UD9I?t=439. // TODO(egg): Compute the flybys and figure out what exactly is going on in // this flight plan. EXPECT_THAT(manœuvre_ignition_tt_seconds_and_Δvs, ElementsAre(Pair("1970-08-14T09:34:49"_DateTime, 3.80488671073918022e+03 * (Metre / Second)), Pair("1970-08-15T13:59:24"_DateTime, 3.04867185471741759e-04 * (Metre / Second)), Pair("1970-12-22T07:48:21"_DateTime, 1.58521291818444873e-03 * (Metre / Second)), Pair("1971-01-08T17:36:55"_DateTime, 1.40000000034068623e-03 * (Metre / Second)), Pair("1971-07-02T17:16:00"_DateTime, 1.00000000431022681e-04 * (Metre / Second)), Pair("1971-09-06T03:27:33"_DateTime, 1.78421858738381537e-03 * (Metre / Second)), Pair("1972-02-13T22:47:26"_DateTime, 7.72606625794511597e-04 * (Metre / Second)), Pair("1972-03-25T16:30:19"_DateTime, 5.32846131747503372e-03 * (Metre / Second)), Pair("1972-12-24T04:09:32"_DateTime, 3.45000000046532824e-03 * (Metre / Second)), Pair("1973-06-04T01:59:07"_DateTime, 9.10695453328359134e-03 * (Metre / Second)), Pair("1973-07-09T06:07:17"_DateTime, 4.49510921430966881e-01 * (Metre / Second)), Pair("1973-09-10T03:59:44"_DateTime, 1.00000000431022681e-04 * (Metre / Second)), Pair("1974-11-20T17:34:27"_DateTime, 5.10549409572428781e-01 * (Metre / Second)), Pair("1975-10-07T01:29:45"_DateTime, 2.86686518692948443e-02 * (Metre / Second)), Pair("1975-12-29T21:27:13"_DateTime, 1.00404183285598275e-03 * (Metre / Second)), Pair("1977-07-28T22:47:53"_DateTime, 1.39666705839172456e-01 * (Metre / Second)))); // Make sure that we can upgrade, save, and reload. WriteAndReadBack(std::move(plugin)); } // Use for debugging saves given by users. TEST_F(PluginCompatibilityTest, DISABLED_SECULAR_Debug) { CheckSaveCompatibility( R"(P:\Public Mockingbird\Principia\Saves\2685\five-minute-scene-change-neptune.txt)", /*compressor=*/"gipfeli", /*decoder=*/"base64"); } } // namespace interface } // namespace principia <|endoftext|>
<commit_before>/*"name": "sensorflare", Author: "LPFraile <lidiapf0@gmail.com>", License: "BSD", Version: "0.0.1", Description: "Include your Particle Core on Sensorflare" File: Examplo:Publish on your Sensorflare account some variables of the code upload on your Particle core. */ //Include the Sensorflare library #include "sensorflare/sensorflare.h" //Initialize objects from the library //One object of the class "PWMOut" is initialized for //every PWM output that will be remote control SensorFlare::PWMOut pwm(A0); //One object of the class "VarPublish" is initialized for every variable //that will be published in order to access remotely from the cloud //The argument that name the variable has a maximum of 12 characters //Both methods initialized the variable that will be published as PUBLIC SensorFlare::VarPublish varTem("temperature"); SensorFlare::VarPublish varPir("pir","PUBLIC"); //Initialized the variable that will be published as PRIVATE SensorFlare::VarPublish varLight("light","PRIVATE"); // Initialize the different variables that will be used in the program int tem_pin=A3; int light_pin=A4; int pir_pin=D0; int status; int new_status; bool change; void setup() { // Call the begin() functions for every object of the classes "DigitalOut" and //"PWMout" to be wired up correct and available. pwm.begin(); //Set the extra pins that are used on the program, but are not controlled remotely pinMode(pir_pin,INPUT); } void loop() { // Temperature sensor float tem= analogRead(tem_pin); // read the value from the sensor // The returned value from the Core is going to be in the range from 0 to 4095 // Calculate the voltage from the sensor reading float voltage = (tem * 3.3) / 4095; float deg =voltage* 100; // multiply by 100 to get degrees in K float temperature = deg - 273.15; // subtract absolute zero to get degrees Celsius //Luminosity float photocell= analogRead(light_pin); // read the value from the sensor // The returned value from the Core is going to be in the range from 0 to 4095 // Calculate the voltage from the sensor reading float Vphotocell = ((photocell * 3.3) / 4095); float rl=(Vphotocell*10)/(3.3-Vphotocell);//Photoresistor value in KΩ float value=500/rl;//luminosity int light= (int) value; //Find the change of state of the PIR sensor. Recognize move new_status=digitalRead(pir_pin); if (status!=new_status){ status=new_status; change=TRUE; } //Publish every time that exist a change in the pin on which is connect the output of the PIR if (change==TRUE) { varPir.Publish(status,0);//Publish the variable at the called method time change=FALSE; } //Publish the variables every 15 seconds. varTem.Publish(temperature,15); varLight.Publish(light,15); } <commit_msg>Update senorflare-publish.cpp<commit_after>/*"name": "sensorflare", Author: "LPFraile <lidiapf0@gmail.com>", License: "BSD", Version: "0.0.1", Description: "Include your Particle Core on Sensorflare" File: Examplo:Publish on your Sensorflare account some variables of the code upload on your Particle core. */ //Include the Sensorflare library #include "sensorflare/sensorflare.h" //Initialize objects from the library //One object of the class "PWMOut" is initialized for //every PWM output that will be remote control SensorFlare::PWMOut pwm(A0); //One object of the class "VarPublish" is initialized for every variable //that will be published in order to access remotely from the cloud //The argument that name the variable has a maximum of 12 characters //Both methods initialized the variable that will be published as PUBLIC SensorFlare::VarPublish varTem("temperature"); SensorFlare::VarPublish varPir("pir","PUBLIC"); //Initialized the variable that will be published as PRIVATE SensorFlare::VarPublish varLight("light","PRIVATE"); //The variables to publish must be declared float temperature; float light; int status; // Initialize the different variables that will be used in the program int tem_pin=A3; int light_pin=A4; int pir_pin=D0; int status; int new_status; bool change; void setup() { //Call the begin() functions for every object of the classes "DigitalOut", "PWMout" //and VarPublish to be wired up correct and available. pwm.begin(); varTem.begin(temperature); varLight.begin(light); varPir.begin(status); //Set the extra pins that are used on the program, but are not controlled remotely pinMode(pir_pin,INPUT); } void loop() { // Temperature sensor float tem= analogRead(tem_pin); // read the value from the sensor // The returned value from the Core is going to be in the range from 0 to 4095 // Calculate the voltage from the sensor reading float voltage = (tem * 3.3) / 4095; float deg =voltage* 100; // multiply by 100 to get degrees in K float temperature = deg - 273.15; // subtract absolute zero to get degrees Celsius //Luminosity float photocell= analogRead(light_pin); // read the value from the sensor // The returned value from the Core is going to be in the range from 0 to 4095 // Calculate the voltage from the sensor reading float Vphotocell = ((photocell * 3.3) / 4095); float rl=(Vphotocell*10)/(3.3-Vphotocell);//Photoresistor value in KΩ float value=500/rl;//luminosity int light= (int) value; //Find the change of state of the PIR sensor. Recognize move new_status=digitalRead(pir_pin); if (status!=new_status){ status=new_status; change=TRUE; } //Publish every time that exist a change in the pin on which is connect the output of the PIR if (change==TRUE) { varPir.Publish(status,0);//Publish the variable at the called method time change=FALSE; } //Publish the variables every 15 seconds. varTem.Publish(temperature,15); varLight.Publish(light,15); } <|endoftext|>
<commit_before>#include <iostream> #include <stdlib.h> #include <boost/shared_ptr.hpp> #include <boost/noncopyable.hpp> //////////////////////////////////////////////////////////// class MyClass { public: int m_iInt; double m_dbl; MyClass() {} static void DeAlloc(MyClass* pC) { pC->~MyClass(); } }; //////////////////////////////////////////////////////////// class MyOtherClass { public: double m_dbl; int m_iInt; MyOtherClass() {} static void DeAlloc(MyOtherClass* pC) { pC->~MyOtherClass(); } }; //////////////////////////////////////////////////////////// class MyBlock : boost::noncopyable { void* m_pBlock; public: MyBlock(int iSize) { m_pBlock = malloc(iSize); } ~MyBlock() { free(m_pBlock); } operator void*() { return m_pBlock; } }; //////////////////////////////////////////////////////////// int main() { boost::shared_ptr<MyBlock> pBlock(new MyBlock(sizeof(MyClass))); boost::shared_ptr<MyClass> pMyInstance(new ((void*)*pBlock) MyClass(), &MyClass::DeAlloc); pMyInstance->m_iInt = 8; pMyInstance->m_dbl = 9.3; boost::shared_ptr<MyOtherClass> pMySecondInstance( new ((void*)*pBlock) MyOtherClass(), &MyOtherClass::DeAlloc); std::cout << pMyInstance->m_dbl << std::endl; std::cout << pMyInstance->m_iInt << std::endl; std::cout << pMySecondInstance->m_dbl << std::endl; std::cout << pMySecondInstance->m_iInt << std::endl; } //////////////////////////////////////////////////////////// <commit_msg>playing with placement new<commit_after>#include <iostream> #include <stdlib.h> #include <boost/shared_ptr.hpp> #include <boost/noncopyable.hpp> //////////////////////////////////////////////////////////// class MyClass { public: int m_iInt; double m_dbl; MyClass() {} }; //////////////////////////////////////////////////////////// class MyOtherClass { public: double m_dbl; int m_iInt; MyOtherClass() {} }; //////////////////////////////////////////////////////////// class MyBlock : boost::noncopyable { void* m_pBlock; public: MyBlock(int iSize) { m_pBlock = malloc(iSize); } ~MyBlock() { free(m_pBlock); } void* data() { return m_pBlock; } }; //////////////////////////////////////////////////////////// struct Deleter { template<typename T> void operator()(T* pT) { pT->~T(); } }; int main() { MyBlock block(sizeof(MyClass)); std::unique_ptr<MyClass, Deleter> pMyInstance(new (block.data()) MyClass()); pMyInstance->m_iInt = 8; pMyInstance->m_dbl = 9.3; std::unique_ptr<MyOtherClass, Deleter> pMySecondInstance(new (block.data()) MyOtherClass()); std::cout << pMyInstance->m_dbl << std::endl; std::cout << pMyInstance->m_iInt << std::endl; std::cout << pMySecondInstance->m_dbl << std::endl; std::cout << pMySecondInstance->m_iInt << std::endl; } //////////////////////////////////////////////////////////// <|endoftext|>
<commit_before>//============================================================================ // Name : Problem024.cpp // Author : Matthew Frost // Description : millionth lexicographic permutation of 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 //============================================================================ #include <iostream> #include <unordered_map> #include <set> #include <vector> std::set<std::vector<int>> fill(int pos, std::vector<int> digits); int main(int argc, char* argv[]) { std::vector<int> digits = {0, 1, 2}; std::set<std::vector<int>> permutations; for (int d : digits) { std::set<std::vector<int>> filled = fill(d, digits); permutations.insert(filled.begin(), filled.end()); } std::cout << "Found " << permutations.size() << " permutations" << std::endl; return 0; } std::set<std::vector<int>> fill(int pos, std::vector<int> digits) { std::set<std::vector<int>> filled; std::unordered_map<int, int> valuesPositions; std::unordered_map<int, int> positionsValues; for (int d : digits) { auto initPair = std::pair<int, int>(d, d); valuesPositions.insert(initPair); positionsValues.insert(initPair); } for (unsigned int i = 0; i < digits.size(); i++) { int valAtPos = positionsValues.find(pos)->second; int prevPos = valuesPositions.find(i)->second; positionsValues.erase(pos); positionsValues.erase(prevPos); valuesPositions.erase(i); valuesPositions.erase(valAtPos); positionsValues.insert(std::pair<int, int>(pos, i)); positionsValues.insert(std::pair<int, int>(prevPos, valAtPos)); valuesPositions.insert(std::pair<int, int>(i, pos)); valuesPositions.insert(std::pair<int, int>(valAtPos, prevPos)); std::vector<int> filledPerm; std::cout << i << " / " << pos << " \t"; //DELME for (auto p : positionsValues) { std::cout << p.second; //DELME filledPerm.push_back(p.second); } std::cout << std::endl; //DELME filled.insert(filledPerm); } return filled; } <commit_msg>not finding all permutations<commit_after>//============================================================================ // Name : Problem024.cpp // Author : Matthew Frost // Description : millionth lexicographic permutation of 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 //============================================================================ #include <iostream> #include <unordered_map> #include <set> #include <vector> std::set<std::vector<int>> fill(int pos, std::vector<int> digits); int main(int argc, char* argv[]) { std::vector<int> digits = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; std::set<std::vector<int>> permutations; for (int d : digits) { std::set<std::vector<int>> filled = fill(d, digits); permutations.insert(filled.begin(), filled.end()); } std::cout << "Found " << permutations.size() << " permutations" << std::endl; return 0; } std::set<std::vector<int>> fill(int pos, std::vector<int> digits) { std::set<std::vector<int>> filled; std::unordered_map<int, int> valuesPositions; std::unordered_map<int, int> positionsValues; for (int d : digits) { auto initPair = std::pair<int, int>(d, d); valuesPositions.insert(initPair); positionsValues.insert(initPair); } for (unsigned int i = 0; i < digits.size(); i++) { int valAtPos = positionsValues.find(pos)->second; int prevPos = valuesPositions.find(i)->second; positionsValues.erase(pos); positionsValues.erase(prevPos); valuesPositions.erase(i); valuesPositions.erase(valAtPos); positionsValues.insert(std::pair<int, int>(pos, i)); positionsValues.insert(std::pair<int, int>(prevPos, valAtPos)); valuesPositions.insert(std::pair<int, int>(i, pos)); valuesPositions.insert(std::pair<int, int>(valAtPos, prevPos)); std::vector<int> filledPerm; for (auto p : positionsValues) { filledPerm.push_back(p.second); } filled.insert(filledPerm); std::vector<int> reversed; for (int j = filledPerm.size()-1; j >= 0; j--) { reversed.push_back(filledPerm.at(j)); } filled.insert(reversed); } return filled; } <|endoftext|>
<commit_before>// // CodeGeneratorCPP.cpp // Protocol // // Created by Wahid Tanner on 10/17/14. // #include <boost/filesystem/path.hpp> #include <boost/filesystem/operations.hpp> #include <boost/filesystem/convenience.hpp> #include <boost/filesystem/fstream.hpp> #include "CodeGeneratorCPP.h" using namespace std; using namespace boost; using namespace MuddledManaged; const string Protocol::CodeGeneratorCPP::mHeaderFileExtension = ".protocol.h"; const string Protocol::CodeGeneratorCPP::mSourceFileExtension = ".protocol.cpp"; const string Protocol::CodeGeneratorCPP::mHeaderFileProlog = "// This file was generated from the Protocol compiler.\n" "// You should not edit this file directly.\n"; const string Protocol::CodeGeneratorCPP::mSourceFileProlog = "// This file was generated from the Protocol compiler.\n" "// You should not edit this file directly.\n"; Protocol::CodeGeneratorCPP::CodeGeneratorCPP () { } void Protocol::CodeGeneratorCPP::generateCode (const string & outputFolder, const ProtoModel & protoModel, const std::string & projectName) const { filesystem::path outputPath(outputFolder); filesystem::path modelPath(protoModel.name()); filesystem::path headerPath(outputPath / filesystem::change_extension(modelPath, mHeaderFileExtension)); filesystem::path sourcePath(outputPath / filesystem::change_extension(modelPath, mSourceFileExtension)); filesystem::create_directory(outputFolder); filesystem::ofstream headerFile(headerPath, ios::out | ios::trunc); CodeWriter headerFileWriter(headerFile); filesystem::ofstream sourceFile(sourcePath, ios::out | ios::trunc); CodeWriter sourceFileWriter(sourceFile); headerFileWriter.writeLine(mHeaderFileProlog); headerFileWriter.writeHeaderIncludeBlockOpening(headerIncludeBlockText(protoModel, projectName)); writeStandardIncludFileNamesToHeader(headerFileWriter); writeIncludedProtoFileNamesToHeader(headerFileWriter, protoModel); writeProtoEnumsToHeader(headerFileWriter, protoModel); writeProtoMessagesToHeader(headerFileWriter, protoModel); headerFileWriter.writeHeaderIncludeBlockClosing(); sourceFileWriter.writeLine(mSourceFileProlog); } string Protocol::CodeGeneratorCPP::headerIncludeBlockText (const ProtoModel & protoModel, const std::string & projectName) const { string text = projectName; if (!text.empty()) { text += "_"; } filesystem::path modelPath(protoModel.namePascal()); text += filesystem::basename(modelPath.filename()); text += "_h"; return text; } void Protocol::CodeGeneratorCPP::writeStandardIncludFileNamesToHeader (CodeWriter & headerFileWriter) const { headerFileWriter.writeIncludeLibrary("cstdint"); headerFileWriter.writeIncludeLibrary("string"); headerFileWriter.writeBlankLine(); } void Protocol::CodeGeneratorCPP::writeIncludedProtoFileNamesToHeader (CodeWriter & headerFileWriter, const ProtoModel & protoModel) const { auto importedProtoBegin = protoModel.importedProtoNames()->cbegin(); auto importedProtoEnd = protoModel.importedProtoNames()->cend(); bool importsFound = false; while (importedProtoBegin != importedProtoEnd) { importsFound = true; filesystem::path protoPath(*importedProtoBegin); filesystem::path headerPath(filesystem::change_extension(protoPath, mHeaderFileExtension)); headerFileWriter.writeIncludeProject(headerPath.string()); ++importedProtoBegin; } if (importsFound) { headerFileWriter.writeBlankLine(); } } void Protocol::CodeGeneratorCPP::writeProtoEnumsToHeader (CodeWriter & headerFileWriter, const ProtoModel & protoModel) const { auto protoEnumBegin = protoModel.enums()->cbegin(); auto protoEnumEnd = protoModel.enums()->cend(); while (protoEnumBegin != protoEnumEnd) { auto enumModel = *protoEnumBegin; headerFileWriter.writeEnumOpening(enumModel->namePascal()); auto enumValueBegin = enumModel->enumValues()->cbegin(); auto enumValueEnd = enumModel->enumValues()->cend(); bool firstEnumValue = true; while (enumValueBegin != enumValueEnd) { auto enumValueModel = *enumValueBegin; if (firstEnumValue) { headerFileWriter.writeEnumValueFirst(enumValueModel->name(), enumValueModel->value()); firstEnumValue = false; } else { headerFileWriter.writeEnumValueSubsequent(enumValueModel->name(), enumValueModel->value()); } ++enumValueBegin; } headerFileWriter.writeEnumClosing(); ++protoEnumBegin; } } void Protocol::CodeGeneratorCPP::writeProtoMessagesToHeader (CodeWriter & headerFileWriter, const ProtoModel & protoModel) const { auto protoMessageBegin = protoModel.messages()->cbegin(); auto protoMessageEnd = protoModel.messages()->cend(); while (protoMessageBegin != protoMessageEnd) { auto messageModel = *protoMessageBegin; writeMessageToHeader(headerFileWriter, protoModel, *messageModel, messageModel->namePascal()); ++protoMessageBegin; } } void Protocol::CodeGeneratorCPP::writeMessageToHeader (CodeWriter & headerFileWriter, const ProtoModel & protoModel, const MessageModel & messageModel, const std::string & className) const { headerFileWriter.writeClassOpening(className); headerFileWriter.writeClassPublic(); // Generate all the typedefs for nested classes first, then generate each class. bool subMessageFound = false; auto messageMessageBegin = messageModel.messages()->cbegin(); auto messageMessageEnd = messageModel.messages()->cend(); while (messageMessageBegin != messageMessageEnd) { subMessageFound = true; auto messageSubModel = *messageMessageBegin; string subClassName = className + messageSubModel->namePascal(); headerFileWriter.writeTypedef(subClassName, messageSubModel->namePascal()); ++messageMessageBegin; } if (subMessageFound) { headerFileWriter.writeBlankLine(); } messageMessageBegin = messageModel.messages()->cbegin(); messageMessageEnd = messageModel.messages()->cend(); while (messageMessageBegin != messageMessageEnd) { auto messageSubModel = *messageMessageBegin; string subClassName = className + messageSubModel->namePascal(); writeMessageToHeader(headerFileWriter, protoModel, *messageSubModel, subClassName); ++messageMessageBegin; } string methodName = className; headerFileWriter.writeClassMethodDeclaration(methodName); string methodReturn = ""; string methodParameters = "const "; methodParameters += className + " & src"; headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters); methodName = "~"; methodName += className; headerFileWriter.writeClassMethodDeclaration(methodName); methodName = "operator ="; methodReturn = className + " &"; methodParameters = "const "; methodParameters += className + " & rhs"; headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters); methodName = "swap"; methodReturn = "void"; methodParameters = className + " * other"; headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters); auto messageFieldBegin = messageModel.fields()->cbegin(); auto messageFieldEnd = messageModel.fields()->cend(); while (messageFieldBegin != messageFieldEnd) { auto messageFieldModel = *messageFieldBegin; switch (messageFieldModel->fieldCategory()) { case MessageFieldModel::FieldCategory::numericType: case MessageFieldModel::FieldCategory::enumType: { methodName = messageFieldModel->name(); string fieldType = fullTypeName(protoModel, messageFieldModel->fieldType()); methodReturn = fieldType; methodParameters = ""; headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters, true); methodName = "set"; methodName += messageFieldModel->namePascal(); methodReturn = "void"; methodParameters = fieldType + " value"; headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters); methodName = "has"; methodName += messageFieldModel->namePascal(); methodReturn = "bool"; methodParameters = ""; headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters, true); methodName = "clear"; methodName += messageFieldModel->namePascal(); methodReturn = "void"; methodParameters = ""; headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters); break; } case MessageFieldModel::FieldCategory::stringType: case MessageFieldModel::FieldCategory::bytesType: case MessageFieldModel::FieldCategory::messageType: { methodName = messageFieldModel->name(); string fieldType = fullTypeName(protoModel, messageFieldModel->fieldType()); methodReturn = "const "; methodReturn += fieldType + " &"; methodParameters = ""; headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters, true); methodName = "mutable"; methodName += messageFieldModel->namePascal(); methodReturn = fieldType + " *"; methodParameters = ""; headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters); methodName = "set"; methodName += messageFieldModel->namePascal(); methodReturn = "void"; methodParameters = "const "; methodParameters += fieldType + " & value"; headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters); methodName = "has"; methodName += messageFieldModel->namePascal(); methodReturn = "bool"; methodParameters = ""; headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters, true); methodName = "clear"; methodName += messageFieldModel->namePascal(); methodReturn = "void"; methodParameters = ""; headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters); methodName = "reset"; methodName += messageFieldModel->namePascal(); methodReturn = "void"; methodParameters = fieldType + " * value"; headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters); methodName = "release"; methodName += messageFieldModel->namePascal(); methodReturn = fieldType + " *"; methodParameters = ""; headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters); break; } default: break; } ++messageFieldBegin; } headerFileWriter.writeClassPrivate(); messageFieldBegin = messageModel.fields()->cbegin(); messageFieldEnd = messageModel.fields()->cend(); while (messageFieldBegin != messageFieldEnd) { auto messageFieldModel = *messageFieldBegin; string constantName = "m"; constantName += messageFieldModel->namePascal() + "Index"; string fieldType = "const unsigned int"; headerFileWriter.writeClassFieldDeclaration(constantName, fieldType, to_string(messageFieldModel->index()), true); ++messageFieldBegin; } headerFileWriter.writeClassClosing(); } string Protocol::CodeGeneratorCPP::fullTypeName (const ProtoModel & protoModel, const std::string & protoTypeName) const { if (protoTypeName == "bool") { return "bool"; } if (protoTypeName == "string") { return "std::string"; } if (protoTypeName == "double") { return "double"; } if (protoTypeName == "float") { return "float"; } if (protoTypeName == "int32") { return "int32_t"; } if (protoTypeName == "int64") { return "int64_t"; } if (protoTypeName == "uint32") { return "uint32_t"; } if (protoTypeName == "uint64") { return "uint64_t"; } if (protoTypeName == "sint32") { return "int32_t"; } if (protoTypeName == "sint64") { return "int64_t"; } if (protoTypeName == "fixed32") { return "int32_t"; } if (protoTypeName == "fixed64") { return "int64_t"; } if (protoTypeName == "sfixed32") { return "int32_t"; } if (protoTypeName == "sfixed64") { return "int64_t"; } if (protoTypeName == "bytes") { return "std::string"; } return ""; } <commit_msg>Added support for generating repeated field method declarations.<commit_after>// // CodeGeneratorCPP.cpp // Protocol // // Created by Wahid Tanner on 10/17/14. // #include <boost/filesystem/path.hpp> #include <boost/filesystem/operations.hpp> #include <boost/filesystem/convenience.hpp> #include <boost/filesystem/fstream.hpp> #include "CodeGeneratorCPP.h" using namespace std; using namespace boost; using namespace MuddledManaged; const string Protocol::CodeGeneratorCPP::mHeaderFileExtension = ".protocol.h"; const string Protocol::CodeGeneratorCPP::mSourceFileExtension = ".protocol.cpp"; const string Protocol::CodeGeneratorCPP::mHeaderFileProlog = "// This file was generated from the Protocol compiler.\n" "// You should not edit this file directly.\n"; const string Protocol::CodeGeneratorCPP::mSourceFileProlog = "// This file was generated from the Protocol compiler.\n" "// You should not edit this file directly.\n"; Protocol::CodeGeneratorCPP::CodeGeneratorCPP () { } void Protocol::CodeGeneratorCPP::generateCode (const string & outputFolder, const ProtoModel & protoModel, const std::string & projectName) const { filesystem::path outputPath(outputFolder); filesystem::path modelPath(protoModel.name()); filesystem::path headerPath(outputPath / filesystem::change_extension(modelPath, mHeaderFileExtension)); filesystem::path sourcePath(outputPath / filesystem::change_extension(modelPath, mSourceFileExtension)); filesystem::create_directory(outputFolder); filesystem::ofstream headerFile(headerPath, ios::out | ios::trunc); CodeWriter headerFileWriter(headerFile); filesystem::ofstream sourceFile(sourcePath, ios::out | ios::trunc); CodeWriter sourceFileWriter(sourceFile); headerFileWriter.writeLine(mHeaderFileProlog); headerFileWriter.writeHeaderIncludeBlockOpening(headerIncludeBlockText(protoModel, projectName)); writeStandardIncludFileNamesToHeader(headerFileWriter); writeIncludedProtoFileNamesToHeader(headerFileWriter, protoModel); writeProtoEnumsToHeader(headerFileWriter, protoModel); writeProtoMessagesToHeader(headerFileWriter, protoModel); headerFileWriter.writeHeaderIncludeBlockClosing(); sourceFileWriter.writeLine(mSourceFileProlog); } string Protocol::CodeGeneratorCPP::headerIncludeBlockText (const ProtoModel & protoModel, const std::string & projectName) const { string text = projectName; if (!text.empty()) { text += "_"; } filesystem::path modelPath(protoModel.namePascal()); text += filesystem::basename(modelPath.filename()); text += "_h"; return text; } void Protocol::CodeGeneratorCPP::writeStandardIncludFileNamesToHeader (CodeWriter & headerFileWriter) const { headerFileWriter.writeIncludeLibrary("cstdint"); headerFileWriter.writeIncludeLibrary("string"); headerFileWriter.writeBlankLine(); } void Protocol::CodeGeneratorCPP::writeIncludedProtoFileNamesToHeader (CodeWriter & headerFileWriter, const ProtoModel & protoModel) const { auto importedProtoBegin = protoModel.importedProtoNames()->cbegin(); auto importedProtoEnd = protoModel.importedProtoNames()->cend(); bool importsFound = false; while (importedProtoBegin != importedProtoEnd) { importsFound = true; filesystem::path protoPath(*importedProtoBegin); filesystem::path headerPath(filesystem::change_extension(protoPath, mHeaderFileExtension)); headerFileWriter.writeIncludeProject(headerPath.string()); ++importedProtoBegin; } if (importsFound) { headerFileWriter.writeBlankLine(); } } void Protocol::CodeGeneratorCPP::writeProtoEnumsToHeader (CodeWriter & headerFileWriter, const ProtoModel & protoModel) const { auto protoEnumBegin = protoModel.enums()->cbegin(); auto protoEnumEnd = protoModel.enums()->cend(); while (protoEnumBegin != protoEnumEnd) { auto enumModel = *protoEnumBegin; headerFileWriter.writeEnumOpening(enumModel->namePascal()); auto enumValueBegin = enumModel->enumValues()->cbegin(); auto enumValueEnd = enumModel->enumValues()->cend(); bool firstEnumValue = true; while (enumValueBegin != enumValueEnd) { auto enumValueModel = *enumValueBegin; if (firstEnumValue) { headerFileWriter.writeEnumValueFirst(enumValueModel->name(), enumValueModel->value()); firstEnumValue = false; } else { headerFileWriter.writeEnumValueSubsequent(enumValueModel->name(), enumValueModel->value()); } ++enumValueBegin; } headerFileWriter.writeEnumClosing(); ++protoEnumBegin; } } void Protocol::CodeGeneratorCPP::writeProtoMessagesToHeader (CodeWriter & headerFileWriter, const ProtoModel & protoModel) const { auto protoMessageBegin = protoModel.messages()->cbegin(); auto protoMessageEnd = protoModel.messages()->cend(); while (protoMessageBegin != protoMessageEnd) { auto messageModel = *protoMessageBegin; writeMessageToHeader(headerFileWriter, protoModel, *messageModel, messageModel->namePascal()); ++protoMessageBegin; } } void Protocol::CodeGeneratorCPP::writeMessageToHeader (CodeWriter & headerFileWriter, const ProtoModel & protoModel, const MessageModel & messageModel, const std::string & className) const { headerFileWriter.writeClassOpening(className); headerFileWriter.writeClassPublic(); // Generate all the typedefs for nested classes first, then generate each class. bool subMessageFound = false; auto messageMessageBegin = messageModel.messages()->cbegin(); auto messageMessageEnd = messageModel.messages()->cend(); while (messageMessageBegin != messageMessageEnd) { subMessageFound = true; auto messageSubModel = *messageMessageBegin; string subClassName = className + messageSubModel->namePascal(); headerFileWriter.writeTypedef(subClassName, messageSubModel->namePascal()); ++messageMessageBegin; } if (subMessageFound) { headerFileWriter.writeBlankLine(); } messageMessageBegin = messageModel.messages()->cbegin(); messageMessageEnd = messageModel.messages()->cend(); while (messageMessageBegin != messageMessageEnd) { auto messageSubModel = *messageMessageBegin; string subClassName = className + messageSubModel->namePascal(); writeMessageToHeader(headerFileWriter, protoModel, *messageSubModel, subClassName); ++messageMessageBegin; } string methodName = className; headerFileWriter.writeClassMethodDeclaration(methodName); string methodReturn = ""; string methodParameters = "const "; methodParameters += className + " & src"; headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters); methodName = "~"; methodName += className; headerFileWriter.writeClassMethodDeclaration(methodName); methodName = "operator ="; methodReturn = className + " &"; methodParameters = "const "; methodParameters += className + " & rhs"; headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters); methodName = "swap"; methodReturn = "void"; methodParameters = className + " * other"; headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters); auto messageFieldBegin = messageModel.fields()->cbegin(); auto messageFieldEnd = messageModel.fields()->cend(); while (messageFieldBegin != messageFieldEnd) { auto messageFieldModel = *messageFieldBegin; switch (messageFieldModel->fieldCategory()) { case MessageFieldModel::FieldCategory::numericType: case MessageFieldModel::FieldCategory::enumType: { if (messageFieldModel->requiredness() == MessageFieldModel::Requiredness::repeated) { methodName = messageFieldModel->name(); string fieldType = fullTypeName(protoModel, messageFieldModel->fieldType()); methodReturn = fieldType; methodParameters = "size_t index"; headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters, true); methodName = "size"; methodName += messageFieldModel->namePascal(); methodReturn = "size_t"; methodParameters = ""; headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters, true); methodName = "set"; methodName += messageFieldModel->namePascal(); methodReturn = "void"; methodParameters = "size_t index, "; methodParameters += fieldType + " value"; headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters); methodName = "add"; methodName += messageFieldModel->namePascal(); methodReturn = "void"; methodParameters = fieldType + " value"; headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters); methodName = "clear"; methodName += messageFieldModel->namePascal(); methodReturn = "void"; methodParameters = ""; headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters); } else { methodName = messageFieldModel->name(); string fieldType = fullTypeName(protoModel, messageFieldModel->fieldType()); methodReturn = fieldType; methodParameters = ""; headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters, true); methodName = "set"; methodName += messageFieldModel->namePascal(); methodReturn = "void"; methodParameters = fieldType + " value"; headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters); methodName = "has"; methodName += messageFieldModel->namePascal(); methodReturn = "bool"; methodParameters = ""; headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters, true); methodName = "clear"; methodName += messageFieldModel->namePascal(); methodReturn = "void"; methodParameters = ""; headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters); } break; } case MessageFieldModel::FieldCategory::stringType: case MessageFieldModel::FieldCategory::bytesType: case MessageFieldModel::FieldCategory::messageType: { if (messageFieldModel->requiredness() == MessageFieldModel::Requiredness::repeated) { methodName = messageFieldModel->name(); string fieldType = fullTypeName(protoModel, messageFieldModel->fieldType()); methodReturn = "const "; methodReturn += fieldType + " &"; methodParameters = "size_t index"; headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters, true); methodName = "size"; methodName = messageFieldModel->namePascal(); methodReturn = "size_t"; methodParameters = ""; headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters, true); methodName = "mutable"; methodName += messageFieldModel->namePascal(); methodReturn = fieldType + " *"; methodParameters = "size_t index"; headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters); methodName = "set"; methodName += messageFieldModel->namePascal(); methodReturn = "void"; methodParameters = "size_t index, "; methodParameters += "const "; methodParameters += fieldType + " & value"; headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters); methodName = "add"; methodName += messageFieldModel->namePascal(); methodReturn = "void"; methodParameters = "const "; methodParameters += fieldType + " & value"; headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters); methodName = "clear"; methodName += messageFieldModel->namePascal(); methodReturn = "void"; methodParameters = ""; headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters); methodName = "reset"; methodName += messageFieldModel->namePascal(); methodReturn = "void"; methodParameters = "size_t index, "; methodParameters = fieldType + " * value"; headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters); methodName = "release"; methodName += messageFieldModel->namePascal(); methodReturn = fieldType + " *"; methodParameters = "size_t index"; headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters); } else { methodName = messageFieldModel->name(); string fieldType = fullTypeName(protoModel, messageFieldModel->fieldType()); methodReturn = "const "; methodReturn += fieldType + " &"; methodParameters = ""; headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters, true); methodName = "mutable"; methodName += messageFieldModel->namePascal(); methodReturn = fieldType + " *"; methodParameters = ""; headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters); methodName = "set"; methodName += messageFieldModel->namePascal(); methodReturn = "void"; methodParameters = "const "; methodParameters += fieldType + " & value"; headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters); methodName = "has"; methodName += messageFieldModel->namePascal(); methodReturn = "bool"; methodParameters = ""; headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters, true); methodName = "clear"; methodName += messageFieldModel->namePascal(); methodReturn = "void"; methodParameters = ""; headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters); methodName = "reset"; methodName += messageFieldModel->namePascal(); methodReturn = "void"; methodParameters = fieldType + " * value"; headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters); methodName = "release"; methodName += messageFieldModel->namePascal(); methodReturn = fieldType + " *"; methodParameters = ""; headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters); } break; } default: break; } ++messageFieldBegin; } headerFileWriter.writeClassPrivate(); messageFieldBegin = messageModel.fields()->cbegin(); messageFieldEnd = messageModel.fields()->cend(); while (messageFieldBegin != messageFieldEnd) { auto messageFieldModel = *messageFieldBegin; string constantName = "m"; constantName += messageFieldModel->namePascal() + "Index"; string fieldType = "const unsigned int"; headerFileWriter.writeClassFieldDeclaration(constantName, fieldType, to_string(messageFieldModel->index()), true); ++messageFieldBegin; } headerFileWriter.writeClassClosing(); } string Protocol::CodeGeneratorCPP::fullTypeName (const ProtoModel & protoModel, const std::string & protoTypeName) const { if (protoTypeName == "bool") { return "bool"; } if (protoTypeName == "string") { return "std::string"; } if (protoTypeName == "double") { return "double"; } if (protoTypeName == "float") { return "float"; } if (protoTypeName == "int32") { return "int32_t"; } if (protoTypeName == "int64") { return "int64_t"; } if (protoTypeName == "uint32") { return "uint32_t"; } if (protoTypeName == "uint64") { return "uint64_t"; } if (protoTypeName == "sint32") { return "int32_t"; } if (protoTypeName == "sint64") { return "int64_t"; } if (protoTypeName == "fixed32") { return "int32_t"; } if (protoTypeName == "fixed64") { return "int64_t"; } if (protoTypeName == "sfixed32") { return "int32_t"; } if (protoTypeName == "sfixed64") { return "int64_t"; } if (protoTypeName == "bytes") { return "std::string"; } return ""; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: acceleratorexecute.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-08 16:14:13 $ * * 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 INCLUDED_SVTOOLS_ACCELERATOREXECUTE_HXX #include "acceleratorexecute.hxx" #endif //=============================================== // includes #ifndef __com_SUN_STAR_FRAME_XMODULEMANAGER_HPP_ #include <com/sun/star/frame/XModuleManager.hpp> #endif #ifndef __com_SUN_STAR_UI_XUICONFIGURATIONMANAGER_HPP_ #include <com/sun/star/ui/XUIConfigurationManager.hpp> #endif #ifndef __com_SUN_STAR_UI_XMODULEUICONFIGURATIONMANAGERSUPPLIER_HPP_ #include <com/sun/star/ui/XModuleUIConfigurationManagerSupplier.hpp> #endif #ifndef __com_SUN_STAR_UI_XUICONFIGURATIONMANAGERSUPPLIER_HPP_ #include <com/sun/star/ui/XUIConfigurationManagerSupplier.hpp> #endif #ifndef __COM_SUN_STAR_AWT_KEYMODIFIER_HPP_ #include <com/sun/star/awt/KeyModifier.hpp> #endif #ifndef __COM_SUN_STAR_UNO_SEQUENCE_HXX_ #include <com/sun/star/uno/Sequence.hxx> #endif #ifndef __COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif //=============================================== // namespace namespace svt { namespace css = ::com::sun::star; //=============================================== // definitions //----------------------------------------------- AcceleratorExecute::AcceleratorExecute() : TMutexInit ( ) , m_aAsyncCallback(LINK(this, AcceleratorExecute, impl_ts_asyncCallback)) { } //----------------------------------------------- AcceleratorExecute::AcceleratorExecute(const AcceleratorExecute& rCopy) : TMutexInit ( ) , m_aAsyncCallback(LINK(this, AcceleratorExecute, impl_ts_asyncCallback)) { // copy construction sint supported in real ... // but we need this ctor to init our async callback ... } //----------------------------------------------- AcceleratorExecute::~AcceleratorExecute() { // does nothing real } //----------------------------------------------- AcceleratorExecute* AcceleratorExecute::createAcceleratorHelper() { AcceleratorExecute* pNew = new AcceleratorExecute(); return pNew; } //----------------------------------------------- void AcceleratorExecute::init(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR, const css::uno::Reference< css::frame::XFrame >& xEnv ) { // SAFE -> ---------------------------------- ::osl::ResettableMutexGuard aLock(m_aLock); // take over the uno service manager m_xSMGR = xSMGR; // specify our internal dispatch provider // frame or desktop?! => document or global config. sal_Bool bDesktopIsUsed = sal_False; m_xDispatcher = css::uno::Reference< css::frame::XDispatchProvider >(xEnv, css::uno::UNO_QUERY); if (!m_xDispatcher.is()) { aLock.clear(); // <- SAFE ------------------------------ css::uno::Reference< css::frame::XDispatchProvider > xDispatcher( xSMGR->createInstance(::rtl::OUString::createFromAscii("com.sun.star.frame.Desktop")), css::uno::UNO_QUERY_THROW); // SAFE -> ------------------------------ aLock.reset(); m_xDispatcher = xDispatcher; bDesktopIsUsed = sal_True; } aLock.clear(); // <- SAFE ---------------------------------- // open all needed configuration objects css::uno::Reference< css::ui::XAcceleratorConfiguration > xGlobalCfg; css::uno::Reference< css::ui::XAcceleratorConfiguration > xModuleCfg; css::uno::Reference< css::ui::XAcceleratorConfiguration > xDocCfg ; // global cfg xGlobalCfg = AcceleratorExecute::st_openGlobalConfig(xSMGR); if (!bDesktopIsUsed) { // module cfg xModuleCfg = AcceleratorExecute::st_openModuleConfig(xSMGR, xEnv); // doc cfg css::uno::Reference< css::frame::XController > xController; css::uno::Reference< css::frame::XModel > xModel; xController = xEnv->getController(); if (xController.is()) xModel = xController->getModel(); if (xModel.is()) xDocCfg = AcceleratorExecute::st_openDocConfig(xModel); } // SAFE -> ------------------------------ aLock.reset(); m_xGlobalCfg = xGlobalCfg; m_xModuleCfg = xModuleCfg; m_xDocCfg = xDocCfg ; aLock.clear(); // <- SAFE ---------------------------------- } //----------------------------------------------- sal_Bool AcceleratorExecute::execute(const KeyCode& aVCLKey) { css::awt::KeyEvent aAWTKey = AcceleratorExecute::st_VCLKey2AWTKey(aVCLKey); return execute(aAWTKey); } //----------------------------------------------- sal_Bool AcceleratorExecute::execute(const css::awt::KeyEvent& aAWTKey) { ::rtl::OUString sCommand = impl_ts_findCommand(aAWTKey); // No Command found? Do nothing! User isnt interested on any error handling .-) if (!sCommand.getLength()) return sal_False; // SAFE -> ---------------------------------- ::osl::ResettableMutexGuard aLock(m_aLock); css::uno::Reference< css::frame::XDispatchProvider > xProvider = m_xDispatcher; aLock.clear(); // <- SAFE ---------------------------------- // convert command in URL structure css::uno::Reference< css::util::XURLTransformer > xParser = impl_ts_getURLParser(); css::util::URL aURL; aURL.Complete = sCommand; xParser->parseStrict(aURL); // ask for dispatch object sal_Bool bRet = sal_False; css::uno::Reference< css::frame::XDispatch > xDispatch = xProvider->queryDispatch(aURL, ::rtl::OUString(), 0); if ( bRet = xDispatch.is() ) { // <- SAFE ---------------------------------- aLock.reset(); m_lCommandQueue.push_back(TCommandQueue::value_type(aURL,xDispatch)); m_aAsyncCallback.Post(0); aLock.clear(); // <- SAFE ---------------------------------- } return bRet; } //----------------------------------------------- css::awt::KeyEvent AcceleratorExecute::st_VCLKey2AWTKey(const KeyCode& aVCLKey) { css::awt::KeyEvent aAWTKey; aAWTKey.Modifiers = 0; aAWTKey.KeyCode = (sal_Int16)aVCLKey.GetCode(); if (aVCLKey.IsShift()) aAWTKey.Modifiers |= css::awt::KeyModifier::SHIFT; if (aVCLKey.IsMod1()) aAWTKey.Modifiers |= css::awt::KeyModifier::MOD1; if (aVCLKey.IsMod2()) aAWTKey.Modifiers |= css::awt::KeyModifier::MOD2; return aAWTKey; } //----------------------------------------------- KeyCode AcceleratorExecute::st_AWTKey2VCLKey(const css::awt::KeyEvent& aAWTKey) { sal_Bool bShift = ((aAWTKey.Modifiers & css::awt::KeyModifier::SHIFT) == css::awt::KeyModifier::SHIFT ); sal_Bool bMod1 = ((aAWTKey.Modifiers & css::awt::KeyModifier::MOD1 ) == css::awt::KeyModifier::MOD1 ); sal_Bool bMod2 = ((aAWTKey.Modifiers & css::awt::KeyModifier::MOD2 ) == css::awt::KeyModifier::MOD2 ); USHORT nKey = (USHORT)aAWTKey.KeyCode; return KeyCode(nKey, bShift, bMod1, bMod2); } //----------------------------------------------- ::rtl::OUString AcceleratorExecute::impl_ts_findCommand(const css::awt::KeyEvent& aKey) { // SAFE -> ---------------------------------- ::osl::ResettableMutexGuard aLock(m_aLock); css::uno::Reference< css::ui::XAcceleratorConfiguration > xGlobalCfg = m_xGlobalCfg; css::uno::Reference< css::ui::XAcceleratorConfiguration > xModuleCfg = m_xModuleCfg; css::uno::Reference< css::ui::XAcceleratorConfiguration > xDocCfg = m_xDocCfg ; aLock.clear(); // <- SAFE ---------------------------------- ::rtl::OUString sCommand; try { if (xDocCfg.is()) sCommand = xDocCfg->getCommandByKeyEvent(aKey); if (sCommand.getLength()) return sCommand; } catch(const css::container::NoSuchElementException&) {} try { if (xModuleCfg.is()) sCommand = xModuleCfg->getCommandByKeyEvent(aKey); if (sCommand.getLength()) return sCommand; } catch(const css::container::NoSuchElementException&) {} try { if (xGlobalCfg.is()) sCommand = xGlobalCfg->getCommandByKeyEvent(aKey); if (sCommand.getLength()) return sCommand; } catch(const css::container::NoSuchElementException&) {} return ::rtl::OUString(); } //----------------------------------------------- css::uno::Reference< css::ui::XAcceleratorConfiguration > AcceleratorExecute::st_openGlobalConfig(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR) { css::uno::Reference< css::ui::XAcceleratorConfiguration > xAccCfg( xSMGR->createInstance(::rtl::OUString::createFromAscii("com.sun.star.ui.GlobalAcceleratorConfiguration")), css::uno::UNO_QUERY_THROW); return xAccCfg; } //----------------------------------------------- css::uno::Reference< css::ui::XAcceleratorConfiguration > AcceleratorExecute::st_openModuleConfig(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR , const css::uno::Reference< css::frame::XFrame >& xFrame) { css::uno::Reference< css::frame::XModuleManager > xModuleDetection( xSMGR->createInstance(::rtl::OUString::createFromAscii("com.sun.star.frame.ModuleManager")), css::uno::UNO_QUERY_THROW); ::rtl::OUString sModule; try { sModule = xModuleDetection->identify(xFrame); } catch(const css::uno::RuntimeException& exRuntime) { throw exRuntime; } catch(const css::uno::Exception&) { return css::uno::Reference< css::ui::XAcceleratorConfiguration >(); } css::uno::Reference< css::ui::XModuleUIConfigurationManagerSupplier > xUISupplier( xSMGR->createInstance(::rtl::OUString::createFromAscii("com.sun.star.ui.ModuleUIConfigurationManagerSupplier")), css::uno::UNO_QUERY_THROW); css::uno::Reference< css::ui::XUIConfigurationManager > xUIManager = xUISupplier->getUIConfigurationManager(sModule); css::uno::Reference< css::ui::XAcceleratorConfiguration > xAccCfg (xUIManager->getShortCutManager(), css::uno::UNO_QUERY_THROW); return xAccCfg; } //----------------------------------------------- css::uno::Reference< css::ui::XAcceleratorConfiguration > AcceleratorExecute::st_openDocConfig(const css::uno::Reference< css::frame::XModel >& xModel) { css::uno::Reference< css::ui::XUIConfigurationManagerSupplier > xUISupplier(xModel, css::uno::UNO_QUERY_THROW); css::uno::Reference< css::ui::XUIConfigurationManager > xUIManager = xUISupplier->getUIConfigurationManager(); css::uno::Reference< css::ui::XAcceleratorConfiguration > xAccCfg (xUIManager->getShortCutManager(), css::uno::UNO_QUERY_THROW); return xAccCfg; } //----------------------------------------------- css::uno::Reference< css::util::XURLTransformer > AcceleratorExecute::impl_ts_getURLParser() { // SAFE -> ---------------------------------- ::osl::ResettableMutexGuard aLock(m_aLock); if (m_xURLParser.is()) return m_xURLParser; css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR = m_xSMGR; aLock.clear(); // <- SAFE ---------------------------------- css::uno::Reference< css::util::XURLTransformer > xParser( xSMGR->createInstance(::rtl::OUString::createFromAscii("com.sun.star.util.URLTransformer")), css::uno::UNO_QUERY_THROW); // SAFE -> ---------------------------------- aLock.reset(); m_xURLParser = xParser; aLock.clear(); // <- SAFE ---------------------------------- return xParser; } //----------------------------------------------- IMPL_LINK(AcceleratorExecute, impl_ts_asyncCallback, void*, pVoid) { // SAFE -> ---------------------------------- ::osl::ResettableMutexGuard aLock(m_aLock); TCommandQueue::iterator pIt = m_lCommandQueue.begin(); if (pIt == m_lCommandQueue.end()) return 0; css::util::URL aURL = pIt->first; css::uno::Reference< css::frame::XDispatch > xDispatch = pIt->second; m_lCommandQueue.erase(pIt); aLock.clear(); // <- SAFE ---------------------------------- try { xDispatch->dispatch(aURL, css::uno::Sequence< css::beans::PropertyValue >()); } catch(const css::uno::RuntimeException& exRuntime) { throw exRuntime; } catch(const css::uno::Exception&) { } return 0; } } // namespace svt <commit_msg>INTEGRATION: CWS fwk31 (1.5.140); FILE MERGED 2006/01/18 07:34:46 as 1.5.140.1: #124127# async accelerator execute must work on living objects<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: acceleratorexecute.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2006-02-07 10:24: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 INCLUDED_SVTOOLS_ACCELERATOREXECUTE_HXX #include "acceleratorexecute.hxx" #endif //=============================================== // includes #ifndef __com_SUN_STAR_FRAME_XMODULEMANAGER_HPP_ #include <com/sun/star/frame/XModuleManager.hpp> #endif #ifndef __com_SUN_STAR_UI_XUICONFIGURATIONMANAGER_HPP_ #include <com/sun/star/ui/XUIConfigurationManager.hpp> #endif #ifndef __com_SUN_STAR_UI_XMODULEUICONFIGURATIONMANAGERSUPPLIER_HPP_ #include <com/sun/star/ui/XModuleUIConfigurationManagerSupplier.hpp> #endif #ifndef __com_SUN_STAR_UI_XUICONFIGURATIONMANAGERSUPPLIER_HPP_ #include <com/sun/star/ui/XUIConfigurationManagerSupplier.hpp> #endif #ifndef __COM_SUN_STAR_AWT_KEYMODIFIER_HPP_ #include <com/sun/star/awt/KeyModifier.hpp> #endif #ifndef __COM_SUN_STAR_UNO_SEQUENCE_HXX_ #include <com/sun/star/uno/Sequence.hxx> #endif #ifndef __COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif #ifndef __com_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_ #include <com/sun/star/lang/DisposedException.hpp> #endif //=============================================== // namespace namespace svt { namespace css = ::com::sun::star; //=============================================== // definitions //----------------------------------------------- class SVT_DLLPRIVATE AsyncAccelExec { public: //--------------------------------------- /** creates a new instance of this class, which can be used one times only! This instance can be forced to execute it's internal set request asynchronous. After that it deletes itself ! */ static AsyncAccelExec* createOnShotInstance(const css::uno::Reference< css::frame::XDispatch >& xDispatch, const css::util::URL& aURL ); void execAsync(); private: //--------------------------------------- /** @short allow creation of instances of this class by using our factory only! */ SVT_DLLPRIVATE AsyncAccelExec(const css::uno::Reference< css::frame::XDispatch >& xDispatch, const css::util::URL& aURL ); DECL_DLLPRIVATE_LINK(impl_ts_asyncCallback, void*); private: ::vcl::EventPoster m_aAsyncCallback; css::uno::Reference< css::frame::XDispatch > m_xDispatch; css::util::URL m_aURL; }; //----------------------------------------------- AcceleratorExecute::AcceleratorExecute() : TMutexInit ( ) , m_aAsyncCallback(LINK(this, AcceleratorExecute, impl_ts_asyncCallback)) { } //----------------------------------------------- AcceleratorExecute::AcceleratorExecute(const AcceleratorExecute& rCopy) : TMutexInit ( ) , m_aAsyncCallback(LINK(this, AcceleratorExecute, impl_ts_asyncCallback)) { // copy construction sint supported in real ... // but we need this ctor to init our async callback ... } //----------------------------------------------- AcceleratorExecute::~AcceleratorExecute() { // does nothing real } //----------------------------------------------- AcceleratorExecute* AcceleratorExecute::createAcceleratorHelper() { AcceleratorExecute* pNew = new AcceleratorExecute(); return pNew; } //----------------------------------------------- void AcceleratorExecute::init(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR, const css::uno::Reference< css::frame::XFrame >& xEnv ) { // SAFE -> ---------------------------------- ::osl::ResettableMutexGuard aLock(m_aLock); // take over the uno service manager m_xSMGR = xSMGR; // specify our internal dispatch provider // frame or desktop?! => document or global config. sal_Bool bDesktopIsUsed = sal_False; m_xDispatcher = css::uno::Reference< css::frame::XDispatchProvider >(xEnv, css::uno::UNO_QUERY); if (!m_xDispatcher.is()) { aLock.clear(); // <- SAFE ------------------------------ css::uno::Reference< css::frame::XDispatchProvider > xDispatcher( xSMGR->createInstance(::rtl::OUString::createFromAscii("com.sun.star.frame.Desktop")), css::uno::UNO_QUERY_THROW); // SAFE -> ------------------------------ aLock.reset(); m_xDispatcher = xDispatcher; bDesktopIsUsed = sal_True; } aLock.clear(); // <- SAFE ---------------------------------- // open all needed configuration objects css::uno::Reference< css::ui::XAcceleratorConfiguration > xGlobalCfg; css::uno::Reference< css::ui::XAcceleratorConfiguration > xModuleCfg; css::uno::Reference< css::ui::XAcceleratorConfiguration > xDocCfg ; // global cfg xGlobalCfg = AcceleratorExecute::st_openGlobalConfig(xSMGR); if (!bDesktopIsUsed) { // module cfg xModuleCfg = AcceleratorExecute::st_openModuleConfig(xSMGR, xEnv); // doc cfg css::uno::Reference< css::frame::XController > xController; css::uno::Reference< css::frame::XModel > xModel; xController = xEnv->getController(); if (xController.is()) xModel = xController->getModel(); if (xModel.is()) xDocCfg = AcceleratorExecute::st_openDocConfig(xModel); } // SAFE -> ------------------------------ aLock.reset(); m_xGlobalCfg = xGlobalCfg; m_xModuleCfg = xModuleCfg; m_xDocCfg = xDocCfg ; aLock.clear(); // <- SAFE ---------------------------------- } //----------------------------------------------- sal_Bool AcceleratorExecute::execute(const KeyCode& aVCLKey) { css::awt::KeyEvent aAWTKey = AcceleratorExecute::st_VCLKey2AWTKey(aVCLKey); return execute(aAWTKey); } //----------------------------------------------- sal_Bool AcceleratorExecute::execute(const css::awt::KeyEvent& aAWTKey) { ::rtl::OUString sCommand = impl_ts_findCommand(aAWTKey); // No Command found? Do nothing! User isnt interested on any error handling .-) if (!sCommand.getLength()) return sal_False; // SAFE -> ---------------------------------- ::osl::ResettableMutexGuard aLock(m_aLock); css::uno::Reference< css::frame::XDispatchProvider > xProvider = m_xDispatcher; aLock.clear(); // <- SAFE ---------------------------------- // convert command in URL structure css::uno::Reference< css::util::XURLTransformer > xParser = impl_ts_getURLParser(); css::util::URL aURL; aURL.Complete = sCommand; xParser->parseStrict(aURL); // ask for dispatch object sal_Bool bRet = sal_False; css::uno::Reference< css::frame::XDispatch > xDispatch = xProvider->queryDispatch(aURL, ::rtl::OUString(), 0); if ( bRet = xDispatch.is() ) { // Note: Such instance can be used one times only and destroy itself afterwards .-) AsyncAccelExec* pExec = AsyncAccelExec::createOnShotInstance(xDispatch, aURL); pExec->execAsync(); } return bRet; } //----------------------------------------------- css::awt::KeyEvent AcceleratorExecute::st_VCLKey2AWTKey(const KeyCode& aVCLKey) { css::awt::KeyEvent aAWTKey; aAWTKey.Modifiers = 0; aAWTKey.KeyCode = (sal_Int16)aVCLKey.GetCode(); if (aVCLKey.IsShift()) aAWTKey.Modifiers |= css::awt::KeyModifier::SHIFT; if (aVCLKey.IsMod1()) aAWTKey.Modifiers |= css::awt::KeyModifier::MOD1; if (aVCLKey.IsMod2()) aAWTKey.Modifiers |= css::awt::KeyModifier::MOD2; return aAWTKey; } //----------------------------------------------- KeyCode AcceleratorExecute::st_AWTKey2VCLKey(const css::awt::KeyEvent& aAWTKey) { sal_Bool bShift = ((aAWTKey.Modifiers & css::awt::KeyModifier::SHIFT) == css::awt::KeyModifier::SHIFT ); sal_Bool bMod1 = ((aAWTKey.Modifiers & css::awt::KeyModifier::MOD1 ) == css::awt::KeyModifier::MOD1 ); sal_Bool bMod2 = ((aAWTKey.Modifiers & css::awt::KeyModifier::MOD2 ) == css::awt::KeyModifier::MOD2 ); USHORT nKey = (USHORT)aAWTKey.KeyCode; return KeyCode(nKey, bShift, bMod1, bMod2); } //----------------------------------------------- ::rtl::OUString AcceleratorExecute::impl_ts_findCommand(const css::awt::KeyEvent& aKey) { // SAFE -> ---------------------------------- ::osl::ResettableMutexGuard aLock(m_aLock); css::uno::Reference< css::ui::XAcceleratorConfiguration > xGlobalCfg = m_xGlobalCfg; css::uno::Reference< css::ui::XAcceleratorConfiguration > xModuleCfg = m_xModuleCfg; css::uno::Reference< css::ui::XAcceleratorConfiguration > xDocCfg = m_xDocCfg ; aLock.clear(); // <- SAFE ---------------------------------- ::rtl::OUString sCommand; try { if (xDocCfg.is()) sCommand = xDocCfg->getCommandByKeyEvent(aKey); if (sCommand.getLength()) return sCommand; } catch(const css::container::NoSuchElementException&) {} try { if (xModuleCfg.is()) sCommand = xModuleCfg->getCommandByKeyEvent(aKey); if (sCommand.getLength()) return sCommand; } catch(const css::container::NoSuchElementException&) {} try { if (xGlobalCfg.is()) sCommand = xGlobalCfg->getCommandByKeyEvent(aKey); if (sCommand.getLength()) return sCommand; } catch(const css::container::NoSuchElementException&) {} return ::rtl::OUString(); } //----------------------------------------------- css::uno::Reference< css::ui::XAcceleratorConfiguration > AcceleratorExecute::st_openGlobalConfig(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR) { css::uno::Reference< css::ui::XAcceleratorConfiguration > xAccCfg( xSMGR->createInstance(::rtl::OUString::createFromAscii("com.sun.star.ui.GlobalAcceleratorConfiguration")), css::uno::UNO_QUERY_THROW); return xAccCfg; } //----------------------------------------------- css::uno::Reference< css::ui::XAcceleratorConfiguration > AcceleratorExecute::st_openModuleConfig(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR , const css::uno::Reference< css::frame::XFrame >& xFrame) { css::uno::Reference< css::frame::XModuleManager > xModuleDetection( xSMGR->createInstance(::rtl::OUString::createFromAscii("com.sun.star.frame.ModuleManager")), css::uno::UNO_QUERY_THROW); ::rtl::OUString sModule; try { sModule = xModuleDetection->identify(xFrame); } catch(const css::uno::RuntimeException& exRuntime) { throw exRuntime; } catch(const css::uno::Exception&) { return css::uno::Reference< css::ui::XAcceleratorConfiguration >(); } css::uno::Reference< css::ui::XModuleUIConfigurationManagerSupplier > xUISupplier( xSMGR->createInstance(::rtl::OUString::createFromAscii("com.sun.star.ui.ModuleUIConfigurationManagerSupplier")), css::uno::UNO_QUERY_THROW); css::uno::Reference< css::ui::XUIConfigurationManager > xUIManager = xUISupplier->getUIConfigurationManager(sModule); css::uno::Reference< css::ui::XAcceleratorConfiguration > xAccCfg (xUIManager->getShortCutManager(), css::uno::UNO_QUERY_THROW); return xAccCfg; } //----------------------------------------------- css::uno::Reference< css::ui::XAcceleratorConfiguration > AcceleratorExecute::st_openDocConfig(const css::uno::Reference< css::frame::XModel >& xModel) { css::uno::Reference< css::ui::XUIConfigurationManagerSupplier > xUISupplier(xModel, css::uno::UNO_QUERY_THROW); css::uno::Reference< css::ui::XUIConfigurationManager > xUIManager = xUISupplier->getUIConfigurationManager(); css::uno::Reference< css::ui::XAcceleratorConfiguration > xAccCfg (xUIManager->getShortCutManager(), css::uno::UNO_QUERY_THROW); return xAccCfg; } //----------------------------------------------- css::uno::Reference< css::util::XURLTransformer > AcceleratorExecute::impl_ts_getURLParser() { // SAFE -> ---------------------------------- ::osl::ResettableMutexGuard aLock(m_aLock); if (m_xURLParser.is()) return m_xURLParser; css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR = m_xSMGR; aLock.clear(); // <- SAFE ---------------------------------- css::uno::Reference< css::util::XURLTransformer > xParser( xSMGR->createInstance(::rtl::OUString::createFromAscii("com.sun.star.util.URLTransformer")), css::uno::UNO_QUERY_THROW); // SAFE -> ---------------------------------- aLock.reset(); m_xURLParser = xParser; aLock.clear(); // <- SAFE ---------------------------------- return xParser; } //----------------------------------------------- IMPL_LINK(AcceleratorExecute, impl_ts_asyncCallback, void*, pVoid) { // replaced by AsyncAccelExec! return 0; } //----------------------------------------------- AsyncAccelExec::AsyncAccelExec(const css::uno::Reference< css::frame::XDispatch >& xDispatch, const css::util::URL& aURL ) : m_aAsyncCallback(LINK(this, AsyncAccelExec, impl_ts_asyncCallback)) , m_xDispatch (xDispatch ) , m_aURL (aURL ) { } //----------------------------------------------- AsyncAccelExec* AsyncAccelExec::createOnShotInstance(const css::uno::Reference< css::frame::XDispatch >& xDispatch, const css::util::URL& aURL ) { AsyncAccelExec* pExec = new AsyncAccelExec(xDispatch, aURL); return pExec; } //----------------------------------------------- void AsyncAccelExec::execAsync() { m_aAsyncCallback.Post(0); } //----------------------------------------------- IMPL_LINK(AsyncAccelExec, impl_ts_asyncCallback, void*, pVoid) { if (! m_xDispatch.is()) return 0; try { m_xDispatch->dispatch(m_aURL, css::uno::Sequence< css::beans::PropertyValue >()); } catch(const css::lang::DisposedException&) {} catch(const css::uno::RuntimeException& exRuntime) { throw exRuntime; } catch(const css::uno::Exception&) {} delete this; return 0; } } // namespace svt <|endoftext|>
<commit_before>/* * QStationModelItem.cpp * * Created on: May 5, 2011 * Author: martinc */ #include "QStationModelGraphicsItem.h" #include <iostream> ///////////////////////////////////////////////////////////////////////////////////////////////// QStationModelGraphicsItem::QStationModelGraphicsItem( double x, double y, double spdKnots, double dirMet, double tDryC, double RH, double presOrHeight, bool isPres, int hh, int mm, double scale) : QGraphicsItem(), _x(x), _y(y), _spdKnots(spdKnots), _dirMet(dirMet), _tDryC(tDryC), _RH(RH), _presOrHeight(presOrHeight), _isPres(isPres), _hh(hh), _mm(mm), _scale(scale), _aspectRatio(1.0) { _text[N] = ""; _text[NE] = ""; _text[E] = ""; _text[SE] = ""; _text[S] = ""; _text[SW] = ""; _text[W] = ""; _text[NW] = ""; setPos(_x, _y); setAcceptedMouseButtons(Qt::LeftButton); // turn off transformations. The item will now draw with local // scale in terms of screen pixels. setFlag(QGraphicsItem::ItemIgnoresTransformations, true); setFlag(QGraphicsItem::ItemIsFocusable, true); // accept hover events setAcceptHoverEvents(true); } ///////////////////////////////////////////////////////////////////////////////////////////////// QStationModelGraphicsItem::~QStationModelGraphicsItem() { } ///////////////////////////////////////////////////////////////////////////////////////////////// void QStationModelGraphicsItem::mousePressEvent(QGraphicsSceneMouseEvent * event) { // Event handling is just stubbed out here, until we find // something useful to do with it. QGraphicsItem::mousePressEvent(event); } ///////////////////////////////////////////////////////////////////////////////////////////////// void QStationModelGraphicsItem::hoverEnterEvent(QGraphicsSceneHoverEvent * event) { // Event handling is just stubbed out here, until we find // something useful to do with it. QGraphicsItem::hoverEnterEvent(event); } ///////////////////////////////////////////////////////////////////////////////////////////////// void QStationModelGraphicsItem::hoverLeaveEvent(QGraphicsSceneHoverEvent * event) { // Event handling is just stubbed out here, until we find // something useful to do with it. QGraphicsItem::hoverEnterEvent(event); } ///////////////////////////////////////////////////////////////////////////////////////////////// QRectF QStationModelGraphicsItem::boundingRect() const { QRectF r(-_scale, -_scale, 2 * _scale, 2 * _scale); return r; } ///////////////////////////////////////////////////////////////////////////////////////////////// void QStationModelGraphicsItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { QPen oldPen = painter->pen(); painter->setPen(QPen("black")); drawWindFlag(painter); painter->setPen(QPen("blue")); drawTextFields(painter); painter->setPen(oldPen); } ///////////////////////////////////////////////////////////////////////////////////////////////// void QStationModelGraphicsItem::drawTextFields(QPainter* painter) { // get the sector and coordinate assignments for this wind direction TextSectors sectors(_dirMet, 11); // Draw each text field QString tdry = QString("%1").arg(_tDryC, 0, 'f', 1); QString rh = QString("%1").arg(_RH, 0, 'f', 1); double presOrHeight = _presOrHeight; if (_isPres) { if (_presOrHeight >= 1000.0) { presOrHeight = _presOrHeight - 1000.0; } else { if (_presOrHeight >= 900.0) { presOrHeight = _presOrHeight - 900.0; } } } QString pht = QString("%1").arg(presOrHeight, 0, 'f', 0); int t = _hh * 100 + _mm; QString time = QString("%1").arg(t, 4, 10, QChar('0')); // filled with leading 0's if (_tDryC != -999.0) drawTextField(painter, sectors, TextSectors::TDRY, tdry); if (_RH != -999.0) drawTextField(painter, sectors, TextSectors::RH, rh); if (_presOrHeight != -999.0) drawTextField(painter, sectors, TextSectors::PHT, pht); drawTextField(painter, sectors, TextSectors::TIME, time); } ///////////////////////////////////////////////////////////////////////////////////////////////// void QStationModelGraphicsItem::drawTextField(QPainter* painter, TextSectors& sectors, TextSectors::TEXT_TYPE typ, QString txt) { QRect textBox = painter->fontMetrics().boundingRect(txt); double xoffset = 0; if (sectors._hjust[typ] == TextSectors::RIGHT) { xoffset = -textBox.width(); } double yoffset = 0; if (sectors._vjust[typ] == TextSectors::TOP) { yoffset = textBox.height(); } double x = sectors._x[typ] + xoffset; double y = sectors._y[typ] + yoffset; painter->drawText(x, y, txt); } ///////////////////////////////////////////////////////////////////////////////////////////////// void QStationModelGraphicsItem::drawWindFlag(QPainter *painter) { // draw the dot at the center of the flag double dotRadius = 3; painter->drawEllipse(-dotRadius, -dotRadius, 2 * dotRadius, 2 * dotRadius); if (_spdKnots == 0.0) { // calm winds, draw double circle painter->drawEllipse(-1.5 * dotRadius, -1.5 * dotRadius, 3 * dotRadius, 3 * dotRadius); } if (_spdKnots < 0.1) { // Don't try to draw a flag when wind speed is missing or zero. return; } double barbLen = _scale; double symScale = 0.20 * barbLen; QPointF p1(0.0, 0.0); QPointF p2; double d; d = 450 - _dirMet; if (d < 0) d = d + 360; if (d >= 360) d = d - 360; xyang(p1, d, barbLen, p2); painter->drawLine(p1, p2); p1 = p2; // convert from m/s to knots. //double w = _wspd*1.94; double w = _spdKnots; double triLength = symScale / sin(60 * 3.14159 / 180); double delta; // plot the 50 symbols, which will be equilateral triangles bool did50 = 0; delta = 50; while (w >= delta) { xyang(p1, d - 120, triLength, p2); painter->drawLine(p1, p2); p1 = p2; xyang(p1, d + 120, triLength, p2); painter->drawLine(p1, p2); p1 = p2; w = w - delta; did50 = 1; } if (did50) { xyang(p1, d + 180, symScale / 3, p2); // move in along the barb painter->drawLine(p1, p2); p1 = p2; } // plot the 10 symbols, which will be full length flags delta = 10; while (w >= delta) { xyang(p1, d - 90, symScale, p2); painter->drawLine(p1, p2); p1 = p2; xyang(p1, d + 90, symScale, p2); painter->drawLine(p1, p2); p1 = p2; xyang(p1, d + 180, symScale / 2, p2); p1 = p2; w = w - delta; } // plot the 5 symbols, which will be half length flags delta = 5; while (w >= delta) { xyang(p1, d - 90, symScale / 2, p2); painter->drawLine(p1, p2); p1 = p2; xyang(p1, d + 90, symScale / 2, p2); painter->drawLine(p1, p2); p1 = p2; xyang(p1, d + 180, symScale / 2, p2); p1 = p2; w = w - delta; } } ///////////////////////////////////////////////////////////////////////////////////////////////// void QStationModelGraphicsItem::xyang(QPointF p, double angle, double length, QPointF& newP) { double d = angle * 3.14159 / 180.0; double deltaX = length * cos(d); double deltaY = length * sin(d) / _aspectRatio; newP = QPointF(p.x() + deltaX, p.y() - deltaY); } ///////////////////////////////////////////////////////////////////////////////////////////////// void QStationModelGraphicsItem::setText(TEXT_POS pos, QString text) { _text[pos] = text; } ///////////////////////////////////////////////////////////////////////////////////////////////// QStationModelGraphicsItem::TextSectors::TextSectors(double wdir, double offset) : _wdir(wdir), _offset(offset) { double dir = 450 - wdir; // make sure that the direction is between 0 and 360 while (dir < 0) { dir += 360.0; } while (dir >= 360) { dir -= 360.0; } // determine the wind flag sector _windSector = (int) (dir / 22.5); // identify the text sectors that will not interfere // with the wind sector. switch (_windSector) { case 0: case 7: case 8: case 15: assignSector(2, 5, 9, 14); setVjustification(BOTTOM, BOTTOM, TOP, TOP); break; case 1: assignSector(0, 7, 10, 13); setVjustification(TOP, BOTTOM, TOP, TOP); break; case 2: assignSector(1, 7, 9, 14); setVjustification(TOP, BOTTOM, TOP, TOP); break; case 3: case 4: case 11: case 12: assignSector(1, 6, 9, 14); setVjustification(BOTTOM, BOTTOM, TOP, TOP); break; case 5: assignSector(0, 6, 9, 14); setVjustification(BOTTOM, TOP, TOP, TOP); break; case 6: assignSector(0, 7, 10, 13); setVjustification(BOTTOM, TOP, TOP, TOP); break; case 9: assignSector(2, 5, 8, 15); setVjustification(BOTTOM, BOTTOM, BOTTOM, TOP); break; case 10: assignSector(1, 6, 9, 15); setVjustification(BOTTOM, BOTTOM, BOTTOM, TOP); break; case 13: assignSector(1, 6, 8, 14); setVjustification(BOTTOM, BOTTOM, TOP, BOTTOM); break; case 14: assignSector(2, 5, 8, 15); setVjustification(BOTTOM, BOTTOM, TOP, BOTTOM); break; } //std::cout << "wdir " << wdir << ", dir " << dir << ", wind " << _windSector << ", alt " << _sector[PHT]; //std::cout << ", tdry " << _sector[TDRY] << ", rh " << _sector[RH] << ", time " << _sector[TIME] << std::endl; _hjust[TDRY] = RIGHT; _hjust[RH] = RIGHT; _hjust[PHT] = LEFT; _hjust[TIME] = LEFT; // compute the coordinates for each text item createCoordinates(); } ///////////////////////////////////////////////////////////////////////////////////////////////// QStationModelGraphicsItem::TextSectors::~TextSectors() { } ///////////////////////////////////////////////////////////////////////////////////////////////// void QStationModelGraphicsItem::TextSectors::assignSector(int phtSector, int tdrySector, int rhSector, int timeSector) { _sector[PHT] = phtSector; _sector[TDRY] = tdrySector; _sector[RH] = rhSector; _sector[TIME] = timeSector; } ///////////////////////////////////////////////////////////////////////////////////////////////// void QStationModelGraphicsItem::TextSectors::setVjustification(TEXT_JUST phtVjust, TEXT_JUST tdryVjust, TEXT_JUST rhVjust, TEXT_JUST timeVjust) { _vjust[PHT] = phtVjust; _vjust[TDRY] = tdryVjust; _vjust[RH] = rhVjust; _vjust[TIME] = timeVjust; } ///////////////////////////////////////////////////////////////////////////////////////////////// void QStationModelGraphicsItem::TextSectors::createCoordinates() { std::vector<TEXT_TYPE> types; types.push_back(TDRY); types.push_back(RH); types.push_back(PHT); types.push_back(TIME); for (std::vector<TEXT_TYPE>::iterator i = types.begin(); i != types.end(); i++) { double angle = 22.5 * (_sector[*i] + 0.5); angle = M_PI * angle / 180.0; _x[*i] = cos(angle) * _offset; // the Y coordinate is inverted, since Y runs from top of screen to bottom of screen _y[*i] = -sin(angle) * _offset; } } <commit_msg>Zero fill the surface pressure or height to at least three characters. Round height and pressure to integer.<commit_after>/* * QStationModelItem.cpp * * Created on: May 5, 2011 * Author: martinc */ #include "QStationModelGraphicsItem.h" #include <iostream> ///////////////////////////////////////////////////////////////////////////////////////////////// QStationModelGraphicsItem::QStationModelGraphicsItem( double x, double y, double spdKnots, double dirMet, double tDryC, double RH, double presOrHeight, bool isPres, int hh, int mm, double scale) : QGraphicsItem(), _x(x), _y(y), _spdKnots(spdKnots), _dirMet(dirMet), _tDryC(tDryC), _RH(RH), _presOrHeight(presOrHeight), _isPres(isPres), _hh(hh), _mm(mm), _scale(scale), _aspectRatio(1.0) { _text[N] = ""; _text[NE] = ""; _text[E] = ""; _text[SE] = ""; _text[S] = ""; _text[SW] = ""; _text[W] = ""; _text[NW] = ""; setPos(_x, _y); setAcceptedMouseButtons(Qt::LeftButton); // turn off transformations. The item will now draw with local // scale in terms of screen pixels. setFlag(QGraphicsItem::ItemIgnoresTransformations, true); setFlag(QGraphicsItem::ItemIsFocusable, true); // accept hover events setAcceptHoverEvents(true); } ///////////////////////////////////////////////////////////////////////////////////////////////// QStationModelGraphicsItem::~QStationModelGraphicsItem() { } ///////////////////////////////////////////////////////////////////////////////////////////////// void QStationModelGraphicsItem::mousePressEvent(QGraphicsSceneMouseEvent * event) { // Event handling is just stubbed out here, until we find // something useful to do with it. QGraphicsItem::mousePressEvent(event); } ///////////////////////////////////////////////////////////////////////////////////////////////// void QStationModelGraphicsItem::hoverEnterEvent(QGraphicsSceneHoverEvent * event) { // Event handling is just stubbed out here, until we find // something useful to do with it. QGraphicsItem::hoverEnterEvent(event); } ///////////////////////////////////////////////////////////////////////////////////////////////// void QStationModelGraphicsItem::hoverLeaveEvent(QGraphicsSceneHoverEvent * event) { // Event handling is just stubbed out here, until we find // something useful to do with it. QGraphicsItem::hoverEnterEvent(event); } ///////////////////////////////////////////////////////////////////////////////////////////////// QRectF QStationModelGraphicsItem::boundingRect() const { QRectF r(-_scale, -_scale, 2 * _scale, 2 * _scale); return r; } ///////////////////////////////////////////////////////////////////////////////////////////////// void QStationModelGraphicsItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { QPen oldPen = painter->pen(); painter->setPen(QPen("black")); drawWindFlag(painter); painter->setPen(QPen("blue")); drawTextFields(painter); painter->setPen(oldPen); } ///////////////////////////////////////////////////////////////////////////////////////////////// void QStationModelGraphicsItem::drawTextFields(QPainter* painter) { // get the sector and coordinate assignments for this wind direction TextSectors sectors(_dirMet, 11); // Draw each text field QString tdry = QString("%1").arg(_tDryC, 0, 'f', 1); QString rh = QString("%1").arg(_RH, 0, 'f', 1); double presOrHeight = _presOrHeight; if (_isPres) { if (_presOrHeight >= 1000.0) { presOrHeight = _presOrHeight - 1000.0; } else { if (_presOrHeight >= 900.0) { presOrHeight = _presOrHeight - 900.0; } } } QString pht = QString("%1").arg((int)round(presOrHeight), 3, 10, QLatin1Char('0')); int t = _hh * 100 + _mm; QString time = QString("%1").arg(t, 4, 10, QChar('0')); // filled with leading 0's if (_tDryC != -999.0) drawTextField(painter, sectors, TextSectors::TDRY, tdry); if (_RH != -999.0) drawTextField(painter, sectors, TextSectors::RH, rh); if (_presOrHeight != -999.0) drawTextField(painter, sectors, TextSectors::PHT, pht); drawTextField(painter, sectors, TextSectors::TIME, time); } ///////////////////////////////////////////////////////////////////////////////////////////////// void QStationModelGraphicsItem::drawTextField(QPainter* painter, TextSectors& sectors, TextSectors::TEXT_TYPE typ, QString txt) { QRect textBox = painter->fontMetrics().boundingRect(txt); double xoffset = 0; if (sectors._hjust[typ] == TextSectors::RIGHT) { xoffset = -textBox.width(); } double yoffset = 0; if (sectors._vjust[typ] == TextSectors::TOP) { yoffset = textBox.height(); } double x = sectors._x[typ] + xoffset; double y = sectors._y[typ] + yoffset; painter->drawText(x, y, txt); } ///////////////////////////////////////////////////////////////////////////////////////////////// void QStationModelGraphicsItem::drawWindFlag(QPainter *painter) { // draw the dot at the center of the flag double dotRadius = 3; painter->drawEllipse(-dotRadius, -dotRadius, 2 * dotRadius, 2 * dotRadius); if (_spdKnots == 0.0) { // calm winds, draw double circle painter->drawEllipse(-1.5 * dotRadius, -1.5 * dotRadius, 3 * dotRadius, 3 * dotRadius); } if (_spdKnots < 0.1) { // Don't try to draw a flag when wind speed is missing or zero. return; } double barbLen = _scale; double symScale = 0.20 * barbLen; QPointF p1(0.0, 0.0); QPointF p2; double d; d = 450 - _dirMet; if (d < 0) d = d + 360; if (d >= 360) d = d - 360; xyang(p1, d, barbLen, p2); painter->drawLine(p1, p2); p1 = p2; // convert from m/s to knots. //double w = _wspd*1.94; double w = _spdKnots; double triLength = symScale / sin(60 * 3.14159 / 180); double delta; // plot the 50 symbols, which will be equilateral triangles bool did50 = 0; delta = 50; while (w >= delta) { xyang(p1, d - 120, triLength, p2); painter->drawLine(p1, p2); p1 = p2; xyang(p1, d + 120, triLength, p2); painter->drawLine(p1, p2); p1 = p2; w = w - delta; did50 = 1; } if (did50) { xyang(p1, d + 180, symScale / 3, p2); // move in along the barb painter->drawLine(p1, p2); p1 = p2; } // plot the 10 symbols, which will be full length flags delta = 10; while (w >= delta) { xyang(p1, d - 90, symScale, p2); painter->drawLine(p1, p2); p1 = p2; xyang(p1, d + 90, symScale, p2); painter->drawLine(p1, p2); p1 = p2; xyang(p1, d + 180, symScale / 2, p2); p1 = p2; w = w - delta; } // plot the 5 symbols, which will be half length flags delta = 5; while (w >= delta) { xyang(p1, d - 90, symScale / 2, p2); painter->drawLine(p1, p2); p1 = p2; xyang(p1, d + 90, symScale / 2, p2); painter->drawLine(p1, p2); p1 = p2; xyang(p1, d + 180, symScale / 2, p2); p1 = p2; w = w - delta; } } ///////////////////////////////////////////////////////////////////////////////////////////////// void QStationModelGraphicsItem::xyang(QPointF p, double angle, double length, QPointF& newP) { double d = angle * 3.14159 / 180.0; double deltaX = length * cos(d); double deltaY = length * sin(d) / _aspectRatio; newP = QPointF(p.x() + deltaX, p.y() - deltaY); } ///////////////////////////////////////////////////////////////////////////////////////////////// void QStationModelGraphicsItem::setText(TEXT_POS pos, QString text) { _text[pos] = text; } ///////////////////////////////////////////////////////////////////////////////////////////////// QStationModelGraphicsItem::TextSectors::TextSectors(double wdir, double offset) : _wdir(wdir), _offset(offset) { double dir = 450 - wdir; // make sure that the direction is between 0 and 360 while (dir < 0) { dir += 360.0; } while (dir >= 360) { dir -= 360.0; } // determine the wind flag sector _windSector = (int) (dir / 22.5); // identify the text sectors that will not interfere // with the wind sector. switch (_windSector) { case 0: case 7: case 8: case 15: assignSector(2, 5, 9, 14); setVjustification(BOTTOM, BOTTOM, TOP, TOP); break; case 1: assignSector(0, 7, 10, 13); setVjustification(TOP, BOTTOM, TOP, TOP); break; case 2: assignSector(1, 7, 9, 14); setVjustification(TOP, BOTTOM, TOP, TOP); break; case 3: case 4: case 11: case 12: assignSector(1, 6, 9, 14); setVjustification(BOTTOM, BOTTOM, TOP, TOP); break; case 5: assignSector(0, 6, 9, 14); setVjustification(BOTTOM, TOP, TOP, TOP); break; case 6: assignSector(0, 7, 10, 13); setVjustification(BOTTOM, TOP, TOP, TOP); break; case 9: assignSector(2, 5, 8, 15); setVjustification(BOTTOM, BOTTOM, BOTTOM, TOP); break; case 10: assignSector(1, 6, 9, 15); setVjustification(BOTTOM, BOTTOM, BOTTOM, TOP); break; case 13: assignSector(1, 6, 8, 14); setVjustification(BOTTOM, BOTTOM, TOP, BOTTOM); break; case 14: assignSector(2, 5, 8, 15); setVjustification(BOTTOM, BOTTOM, TOP, BOTTOM); break; } //std::cout << "wdir " << wdir << ", dir " << dir << ", wind " << _windSector << ", alt " << _sector[PHT]; //std::cout << ", tdry " << _sector[TDRY] << ", rh " << _sector[RH] << ", time " << _sector[TIME] << std::endl; _hjust[TDRY] = RIGHT; _hjust[RH] = RIGHT; _hjust[PHT] = LEFT; _hjust[TIME] = LEFT; // compute the coordinates for each text item createCoordinates(); } ///////////////////////////////////////////////////////////////////////////////////////////////// QStationModelGraphicsItem::TextSectors::~TextSectors() { } ///////////////////////////////////////////////////////////////////////////////////////////////// void QStationModelGraphicsItem::TextSectors::assignSector(int phtSector, int tdrySector, int rhSector, int timeSector) { _sector[PHT] = phtSector; _sector[TDRY] = tdrySector; _sector[RH] = rhSector; _sector[TIME] = timeSector; } ///////////////////////////////////////////////////////////////////////////////////////////////// void QStationModelGraphicsItem::TextSectors::setVjustification(TEXT_JUST phtVjust, TEXT_JUST tdryVjust, TEXT_JUST rhVjust, TEXT_JUST timeVjust) { _vjust[PHT] = phtVjust; _vjust[TDRY] = tdryVjust; _vjust[RH] = rhVjust; _vjust[TIME] = timeVjust; } ///////////////////////////////////////////////////////////////////////////////////////////////// void QStationModelGraphicsItem::TextSectors::createCoordinates() { std::vector<TEXT_TYPE> types; types.push_back(TDRY); types.push_back(RH); types.push_back(PHT); types.push_back(TIME); for (std::vector<TEXT_TYPE>::iterator i = types.begin(); i != types.end(); i++) { double angle = 22.5 * (_sector[*i] + 0.5); angle = M_PI * angle / 180.0; _x[*i] = cos(angle) * _offset; // the Y coordinate is inverted, since Y runs from top of screen to bottom of screen _y[*i] = -sin(angle) * _offset; } } <|endoftext|>
<commit_before>/* ** Copyright 2009-2013 Merethis ** ** This file is part of Centreon Broker. ** ** Centreon Broker is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Broker 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 Centreon Broker. If not, see ** <http://www.gnu.org/licenses/>. */ #include <cstdlib> #include <cstring> #include <ctime> #include <memory> #include "com/centreon/broker/exceptions/msg.hh" #include "com/centreon/broker/logging/logging.hh" #include "com/centreon/broker/neb/callbacks.hh" #include "com/centreon/broker/neb/events.hh" #include "com/centreon/broker/neb/initial.hh" #include "com/centreon/broker/neb/internal.hh" #include "com/centreon/engine/broker.hh" #include "com/centreon/engine/common.hh" #include "com/centreon/engine/nebcallbacks.hh" #include "com/centreon/engine/nebstructs.hh" #include "com/centreon/engine/objects.hh" // Internal Nagios host list. extern "C" { extern host* host_list; extern hostdependency* hostdependency_list; extern hostgroup* hostgroup_list; extern service* service_list; extern servicedependency* servicedependency_list; extern servicegroup* servicegroup_list; } using namespace com::centreon::broker; // NEB module list. extern "C" { nebmodule* neb_module_list; } /************************************** * * * Static Functions * * * **************************************/ /** * Send to the global publisher the list of custom variables. */ static void send_custom_variables_list() { // Start log message. logging::info(logging::medium) << "init: beginning custom variables dump"; // Iterate through all hosts. for (host* h(host_list); h; h = h->next) // Send all custom variables. for (customvariablesmember* cv(h->custom_variables); cv; cv = cv->next) { // Fill callback struct. nebstruct_custom_variable_data nscvd; memset(&nscvd, 0, sizeof(nscvd)); nscvd.type = NEBTYPE_HOSTCUSTOMVARIABLE_ADD; nscvd.timestamp.tv_sec = time(NULL); nscvd.var_name = cv->variable_name; nscvd.var_value = cv->variable_value; nscvd.object_ptr = h; // Callback. neb::callback_custom_variable( NEBCALLBACK_CUSTOM_VARIABLE_DATA, &nscvd); } // Iterate through all services. for (service* s(service_list); s; s = s->next) // Send all custom variables. for (customvariablesmember* cv(s->custom_variables); cv; cv = cv->next) { // Fill callback struct. nebstruct_custom_variable_data nscvd; memset(&nscvd, 0, sizeof(nscvd)); nscvd.type = NEBTYPE_SERVICECUSTOMVARIABLE_ADD; nscvd.timestamp.tv_sec = time(NULL); nscvd.var_name = cv->variable_name; nscvd.var_value = cv->variable_value; nscvd.object_ptr = s; // Callback. neb::callback_custom_variable( NEBCALLBACK_CUSTOM_VARIABLE_DATA, &nscvd); } // End log message. logging::info(logging::medium) << "init: end of custom variables dump"; return ; } /** * Send to the global publisher the list of host dependencies within Nagios. */ static void send_host_dependencies_list() { // Start log message. logging::info(logging::medium) << "init: beginning host dependencies dump"; // Loop through all dependencies. for (hostdependency* hd = hostdependency_list; hd; hd = hd->next) { misc::shared_ptr<neb::host_dependency> host_dependency( new neb::host_dependency); std::map<std::string, int>::const_iterator it; // Set host dependency parameters. if (hd->dependency_period) host_dependency->dependency_period = hd->dependency_period; if (hd->dependent_host_name) { it = neb::gl_hosts.find(hd->dependent_host_name); if (it != neb::gl_hosts.end()) host_dependency->dependent_host_id = it->second; } host_dependency->inherits_parent = hd->inherits_parent; if (hd->host_name) { it = neb::gl_hosts.find(hd->host_name); if (it != neb::gl_hosts.end()) host_dependency->host_id = it->second; } // Send host dependency event. logging::info(logging::low) << "init: host " << host_dependency->dependent_host_id << " depends on host " << host_dependency->host_id; neb::gl_publisher.write(host_dependency.staticCast<io::data>()); } // End log message. logging::info(logging::medium) << "init: end of host dependencies dump"; return ; } /** * Send to the global publisher the list of host groups within Engine. */ static void send_host_group_list() { // Start log message. logging::info(logging::medium) << "init: beginning host group dump"; // Loop through all host groups. for (hostgroup* hg(hostgroup_list); hg; hg = hg->next) { // Fill callback struct. nebstruct_group_data nsgd; memset(&nsgd, 0, sizeof(nsgd)); nsgd.type = NEBTYPE_HOSTGROUP_ADD; nsgd.object_ptr = hg; // Callback. neb::callback_group(NEBCALLBACK_GROUP_DATA, &nsgd); // Dump host group members. for (hostsmember* hgm(hg->members); hgm; hgm = hgm->next) { // Fill callback struct. nebstruct_group_member_data nsgmd; memset(&nsgmd, 0, sizeof(nsgmd)); nsgmd.type = NEBTYPE_HOSTGROUPMEMBER_ADD; nsgmd.object_ptr = hgm->host_ptr; nsgmd.group_ptr = hg; // Callback. neb::callback_group_member(NEBCALLBACK_GROUP_MEMBER_DATA, &nsgmd); } } // End log message. logging::info(logging::medium) << "init: end of host group dump"; return ; } /** * Send to the global publisher the list of hosts within Nagios. */ static void send_host_list() { // Start log message. logging::info(logging::medium) << "init: beginning host dump"; // Loop through all hosts. for (host* h(host_list); h; h = h->next) { // Fill callback struct. nebstruct_adaptive_host_data nsahd; memset(&nsahd, 0, sizeof(nsahd)); nsahd.type = NEBTYPE_HOST_ADD; nsahd.command_type = CMD_NONE; nsahd.modified_attribute = MODATTR_ALL; nsahd.modified_attributes = MODATTR_ALL; nsahd.object_ptr = h; // Callback. neb::callback_host(NEBCALLBACK_ADAPTIVE_HOST_DATA, &nsahd); } // End log message. logging::info(logging::medium) << "init: end of host dump"; return ; } /** * Send to the global publisher the list of host parents within Nagios. */ static void send_host_parents_list() { // Start log message. logging::info(logging::medium) << "init: beginning host parents dump"; try { // Loop through all hosts. for (host* h(host_list); h; h = h->next) // Loop through all parents. for (hostsmember* parent(h->parent_hosts); parent; parent = parent->next) { // Fill callback struct. nebstruct_relation_data nsrd; memset(&nsrd, 0, sizeof(nsrd)); nsrd.type = NEBTYPE_PARENT_ADD; nsrd.flags = NEBFLAG_NONE; nsrd.attr = NEBATTR_NONE; nsrd.timestamp.tv_sec = time(NULL); nsrd.hst = parent->host_ptr; nsrd.dep_hst = h; // Callback. neb::callback_relation(NEBTYPE_PARENT_ADD, &nsrd); } } catch (std::exception const& e) { logging::error(logging::high) << "init: error occurred while dumping host parents: " << e.what(); } catch (...) { logging::error(logging::high) << "init: unknown error occurred while dumping host parents"; } // End log message. logging::info(logging::medium) << "init: end of host parents dump"; return ; } /** * Send to the global publisher the list of modules loaded by Engine. */ static void send_module_list() { // Start log message. logging::info(logging::medium) << "init: beginning modules dump"; // Browse module list. for (nebmodule* nm(neb_module_list); nm; nm = nm->next) if (nm->filename) { // Fill callback struct. nebstruct_module_data nsmd; memset(&nsmd, 0, sizeof(nsmd)); nsmd.module = nm->filename; nsmd.args = nm->args; nsmd.type = NEBTYPE_MODULE_ADD; // Callback. neb::callback_module(NEBTYPE_MODULE_ADD, &nsmd); } // End log message. logging::info(logging::medium) << "init: end of modules dump"; return ; } /** * Send to the global publisher the list of service dependencies within * Nagios. */ static void send_service_dependencies_list() { // Start log message. logging::info(logging::medium) << "init: beginning service dependencies dump"; // Loop through all dependencies. for (servicedependency* sd = servicedependency_list; sd; sd = sd->next) { std::map<std::pair<std::string, std::string>, std::pair<int, int> >::const_iterator it; misc::shared_ptr<neb::service_dependency> service_dependency(new neb::service_dependency); // Search IDs. if (sd->dependent_host_name && sd->dependent_service_description) { it = neb::gl_services.find(std::make_pair<std::string, std::string>( sd->dependent_host_name, sd->dependent_service_description)); if (it != neb::gl_services.end()) { service_dependency->dependent_host_id = it->second.first; service_dependency->dependent_service_id = it->second.second; } } if (sd->dependency_period) service_dependency->dependency_period = sd->dependency_period; service_dependency->inherits_parent = sd->inherits_parent; if (sd->host_name && sd->service_description) { it = neb::gl_services.find(std::make_pair<std::string, std::string>( sd->host_name, sd->service_description)); if (it != neb::gl_services.end()) { service_dependency->host_id = it->second.first; service_dependency->service_id = it->second.second; } } // Send service dependency event. logging::info(logging::low) << "init: service (" << service_dependency->dependent_host_id << ", " << service_dependency->dependent_service_id << ") depends on service (" << service_dependency->host_id << ", " << service_dependency->service_id << ")"; neb::gl_publisher.write(service_dependency.staticCast<io::data>()); } // End log message. logging::info(logging::medium) << "init: end of service dependencies dump"; return ; } /** * Send to the global publisher the list of service groups within Engine. */ static void send_service_group_list() { // Start log message. logging::info(logging::medium) << "init: beginning service group dump"; // Loop through all service groups. for (servicegroup* sg(servicegroup_list); sg; sg = sg->next) { // Fill callback struct. nebstruct_group_data nsgd; memset(&nsgd, 0, sizeof(nsgd)); nsgd.type = NEBTYPE_SERVICEGROUP_ADD; nsgd.object_ptr = sg; // Callback. neb::callback_group(NEBCALLBACK_GROUP_DATA, &nsgd); // Dump service group members. for (servicesmember* sgm(sg->members); sgm; sgm = sgm->next) { // Fill callback struct. nebstruct_group_member_data nsgmd; memset(&nsgmd, 0, sizeof(nsgmd)); nsgmd.type = NEBTYPE_SERVICEGROUPMEMBER_ADD; nsgmd.object_ptr = sgm->service_ptr; nsgmd.group_ptr = sg; // Callback. neb::callback_group_member(NEBCALLBACK_GROUP_MEMBER_DATA, &nsgmd); } } // End log message. logging::info(logging::medium) << "init: end of service groups dump"; return ; } /** * Send to the global publisher the list of services within Nagios. */ static void send_service_list() { // Start log message. logging::info(logging::medium) << "init: beginning service dump"; // Loop through all services. for (service* s = service_list; s; s = s->next) { // Fill callback struct. nebstruct_adaptive_service_data nsasd; memset(&nsasd, 0, sizeof(nsasd)); nsasd.type = NEBTYPE_SERVICE_ADD; nsasd.command_type = CMD_NONE; nsasd.modified_attribute = MODATTR_ALL; nsasd.modified_attributes = MODATTR_ALL; nsasd.object_ptr = s; // Callback. neb::callback_service(NEBCALLBACK_ADAPTIVE_SERVICE_DATA, &nsasd); } // End log message. logging::info(logging::medium) << "init: end of services dump"; return ; } /************************************** * * * Global Functions * * * **************************************/ /** * Send initial configuration to the global publisher. */ void neb::send_initial_configuration() { send_host_list(); send_service_list(); send_custom_variables_list(); send_host_parents_list(); send_host_group_list(); send_service_group_list(); send_host_dependencies_list(); send_service_dependencies_list(); send_module_list(); return ; } <commit_msg>NEB: create initial dependencies using callbacks.<commit_after>/* ** Copyright 2009-2013 Merethis ** ** This file is part of Centreon Broker. ** ** Centreon Broker is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Broker 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 Centreon Broker. If not, see ** <http://www.gnu.org/licenses/>. */ #include <cstdlib> #include <cstring> #include <ctime> #include <memory> #include "com/centreon/broker/exceptions/msg.hh" #include "com/centreon/broker/logging/logging.hh" #include "com/centreon/broker/neb/callbacks.hh" #include "com/centreon/broker/neb/events.hh" #include "com/centreon/broker/neb/initial.hh" #include "com/centreon/broker/neb/internal.hh" #include "com/centreon/engine/broker.hh" #include "com/centreon/engine/common.hh" #include "com/centreon/engine/nebcallbacks.hh" #include "com/centreon/engine/nebstructs.hh" #include "com/centreon/engine/objects.hh" // Internal Nagios host list. extern "C" { extern host* host_list; extern hostdependency* hostdependency_list; extern hostgroup* hostgroup_list; extern service* service_list; extern servicedependency* servicedependency_list; extern servicegroup* servicegroup_list; } using namespace com::centreon::broker; // NEB module list. extern "C" { nebmodule* neb_module_list; } /************************************** * * * Static Functions * * * **************************************/ /** * Send to the global publisher the list of custom variables. */ static void send_custom_variables_list() { // Start log message. logging::info(logging::medium) << "init: beginning custom variables dump"; // Iterate through all hosts. for (host* h(host_list); h; h = h->next) // Send all custom variables. for (customvariablesmember* cv(h->custom_variables); cv; cv = cv->next) { // Fill callback struct. nebstruct_custom_variable_data nscvd; memset(&nscvd, 0, sizeof(nscvd)); nscvd.type = NEBTYPE_HOSTCUSTOMVARIABLE_ADD; nscvd.timestamp.tv_sec = time(NULL); nscvd.var_name = cv->variable_name; nscvd.var_value = cv->variable_value; nscvd.object_ptr = h; // Callback. neb::callback_custom_variable( NEBCALLBACK_CUSTOM_VARIABLE_DATA, &nscvd); } // Iterate through all services. for (service* s(service_list); s; s = s->next) // Send all custom variables. for (customvariablesmember* cv(s->custom_variables); cv; cv = cv->next) { // Fill callback struct. nebstruct_custom_variable_data nscvd; memset(&nscvd, 0, sizeof(nscvd)); nscvd.type = NEBTYPE_SERVICECUSTOMVARIABLE_ADD; nscvd.timestamp.tv_sec = time(NULL); nscvd.var_name = cv->variable_name; nscvd.var_value = cv->variable_value; nscvd.object_ptr = s; // Callback. neb::callback_custom_variable( NEBCALLBACK_CUSTOM_VARIABLE_DATA, &nscvd); } // End log message. logging::info(logging::medium) << "init: end of custom variables dump"; return ; } /** * Send to the global publisher the list of host dependencies within Nagios. */ static void send_host_dependencies_list() { // Start log message. logging::info(logging::medium) << "init: beginning host dependencies dump"; try { // Loop through all dependencies. for (hostdependency* hd(hostdependency_list); hd; hd = hd->next) { // Fill callback struct. nebstruct_relation_data nsrd; memset(&nsrd, 0, sizeof(nsrd)); nsrd.type = NEBTYPE_DEPENDENCY_ADD; nsrd.flags = NEBFLAG_NONE; nsrd.attr = NEBATTR_NONE; nsrd.timestamp.tv_sec = time(NULL); nsrd.hst = hd->master_host_ptr; nsrd.dep_hst = hd->dependent_host_ptr; nsrd.dependency_period = hd->dependency_period; nsrd.inherits_parent = hd->inherits_parent; // Callback. neb::callback_relation(NEBTYPE_DEPENDENCY_ADD, &nsrd); } } catch (std::exception const& e) { logging::error(logging::high) << "init: error occurred while dumping host dependencies: " << e.what(); } catch (...) { logging::error(logging::high) << "init: unknown error occurred while dumping host dependencies"; } // End log message. logging::info(logging::medium) << "init: end of host dependencies dump"; return ; } /** * Send to the global publisher the list of host groups within Engine. */ static void send_host_group_list() { // Start log message. logging::info(logging::medium) << "init: beginning host group dump"; // Loop through all host groups. for (hostgroup* hg(hostgroup_list); hg; hg = hg->next) { // Fill callback struct. nebstruct_group_data nsgd; memset(&nsgd, 0, sizeof(nsgd)); nsgd.type = NEBTYPE_HOSTGROUP_ADD; nsgd.object_ptr = hg; // Callback. neb::callback_group(NEBCALLBACK_GROUP_DATA, &nsgd); // Dump host group members. for (hostsmember* hgm(hg->members); hgm; hgm = hgm->next) { // Fill callback struct. nebstruct_group_member_data nsgmd; memset(&nsgmd, 0, sizeof(nsgmd)); nsgmd.type = NEBTYPE_HOSTGROUPMEMBER_ADD; nsgmd.object_ptr = hgm->host_ptr; nsgmd.group_ptr = hg; // Callback. neb::callback_group_member(NEBCALLBACK_GROUP_MEMBER_DATA, &nsgmd); } } // End log message. logging::info(logging::medium) << "init: end of host group dump"; return ; } /** * Send to the global publisher the list of hosts within Nagios. */ static void send_host_list() { // Start log message. logging::info(logging::medium) << "init: beginning host dump"; // Loop through all hosts. for (host* h(host_list); h; h = h->next) { // Fill callback struct. nebstruct_adaptive_host_data nsahd; memset(&nsahd, 0, sizeof(nsahd)); nsahd.type = NEBTYPE_HOST_ADD; nsahd.command_type = CMD_NONE; nsahd.modified_attribute = MODATTR_ALL; nsahd.modified_attributes = MODATTR_ALL; nsahd.object_ptr = h; // Callback. neb::callback_host(NEBCALLBACK_ADAPTIVE_HOST_DATA, &nsahd); } // End log message. logging::info(logging::medium) << "init: end of host dump"; return ; } /** * Send to the global publisher the list of host parents within Nagios. */ static void send_host_parents_list() { // Start log message. logging::info(logging::medium) << "init: beginning host parents dump"; try { // Loop through all hosts. for (host* h(host_list); h; h = h->next) // Loop through all parents. for (hostsmember* parent(h->parent_hosts); parent; parent = parent->next) { // Fill callback struct. nebstruct_relation_data nsrd; memset(&nsrd, 0, sizeof(nsrd)); nsrd.type = NEBTYPE_PARENT_ADD; nsrd.flags = NEBFLAG_NONE; nsrd.attr = NEBATTR_NONE; nsrd.timestamp.tv_sec = time(NULL); nsrd.hst = parent->host_ptr; nsrd.dep_hst = h; // Callback. neb::callback_relation(NEBTYPE_PARENT_ADD, &nsrd); } } catch (std::exception const& e) { logging::error(logging::high) << "init: error occurred while dumping host parents: " << e.what(); } catch (...) { logging::error(logging::high) << "init: unknown error occurred while dumping host parents"; } // End log message. logging::info(logging::medium) << "init: end of host parents dump"; return ; } /** * Send to the global publisher the list of modules loaded by Engine. */ static void send_module_list() { // Start log message. logging::info(logging::medium) << "init: beginning modules dump"; // Browse module list. for (nebmodule* nm(neb_module_list); nm; nm = nm->next) if (nm->filename) { // Fill callback struct. nebstruct_module_data nsmd; memset(&nsmd, 0, sizeof(nsmd)); nsmd.module = nm->filename; nsmd.args = nm->args; nsmd.type = NEBTYPE_MODULE_ADD; // Callback. neb::callback_module(NEBTYPE_MODULE_ADD, &nsmd); } // End log message. logging::info(logging::medium) << "init: end of modules dump"; return ; } /** * Send to the global publisher the list of service dependencies within * Nagios. */ static void send_service_dependencies_list() { // Start log message. logging::info(logging::medium) << "init: beginning service dependencies dump"; try { // Loop through all dependencies. for (servicedependency* sd(servicedependency_list); sd; sd = sd->next) { // Fill callback struct. nebstruct_relation_data nsrd; memset(&nsrd, 0, sizeof(nsrd)); nsrd.type = NEBTYPE_DEPENDENCY_ADD; nsrd.flags = NEBFLAG_NONE; nsrd.attr = NEBATTR_NONE; nsrd.timestamp.tv_sec = time(NULL); nsrd.svc = sd->master_service_ptr; nsrd.dep_svc = sd->dependent_service_ptr; nsrd.dependency_period = sd->dependency_period; nsrd.inherits_parent = sd->inherits_parent; // Callback. neb::callback_relation(NEBTYPE_DEPENDENCY_ADD, &nsrd); } } catch (std::exception const& e) { logging::error(logging::high) << "init: error occurred while dumping service dependencies: " << e.what(); } catch (...) { logging::error(logging::high) << "init: unknown error occurred " << "while dumping service dependencies"; } // End log message. logging::info(logging::medium) << "init: end of service dependencies dump"; return ; } /** * Send to the global publisher the list of service groups within Engine. */ static void send_service_group_list() { // Start log message. logging::info(logging::medium) << "init: beginning service group dump"; // Loop through all service groups. for (servicegroup* sg(servicegroup_list); sg; sg = sg->next) { // Fill callback struct. nebstruct_group_data nsgd; memset(&nsgd, 0, sizeof(nsgd)); nsgd.type = NEBTYPE_SERVICEGROUP_ADD; nsgd.object_ptr = sg; // Callback. neb::callback_group(NEBCALLBACK_GROUP_DATA, &nsgd); // Dump service group members. for (servicesmember* sgm(sg->members); sgm; sgm = sgm->next) { // Fill callback struct. nebstruct_group_member_data nsgmd; memset(&nsgmd, 0, sizeof(nsgmd)); nsgmd.type = NEBTYPE_SERVICEGROUPMEMBER_ADD; nsgmd.object_ptr = sgm->service_ptr; nsgmd.group_ptr = sg; // Callback. neb::callback_group_member(NEBCALLBACK_GROUP_MEMBER_DATA, &nsgmd); } } // End log message. logging::info(logging::medium) << "init: end of service groups dump"; return ; } /** * Send to the global publisher the list of services within Nagios. */ static void send_service_list() { // Start log message. logging::info(logging::medium) << "init: beginning service dump"; // Loop through all services. for (service* s = service_list; s; s = s->next) { // Fill callback struct. nebstruct_adaptive_service_data nsasd; memset(&nsasd, 0, sizeof(nsasd)); nsasd.type = NEBTYPE_SERVICE_ADD; nsasd.command_type = CMD_NONE; nsasd.modified_attribute = MODATTR_ALL; nsasd.modified_attributes = MODATTR_ALL; nsasd.object_ptr = s; // Callback. neb::callback_service(NEBCALLBACK_ADAPTIVE_SERVICE_DATA, &nsasd); } // End log message. logging::info(logging::medium) << "init: end of services dump"; return ; } /************************************** * * * Global Functions * * * **************************************/ /** * Send initial configuration to the global publisher. */ void neb::send_initial_configuration() { send_host_list(); send_service_list(); send_custom_variables_list(); send_host_parents_list(); send_host_group_list(); send_service_group_list(); send_host_dependencies_list(); send_service_dependencies_list(); send_module_list(); return ; } <|endoftext|>
<commit_before>#pragma once #include <WinSock2.h> #include <deque> #include <functional> #include <memory> #include <thread> #include <future> #include <condition_variable> #include <iostream> namespace common { class Copyable { protected: Copyable() noexcept = default; ~Copyable() noexcept = default; Copyable(const Copyable&) noexcept = default; Copyable(Copyable&&) noexcept = default; Copyable& operator=(const Copyable&) noexcept = default; Copyable& operator=(Copyable&&) noexcept = default; }; class UnCopyable { UnCopyable(const UnCopyable&) noexcept = delete; UnCopyable(UnCopyable&&) noexcept = delete; UnCopyable& operator=(const UnCopyable&) noexcept = delete; UnCopyable& operator=(UnCopyable&&) noexcept = delete; protected: UnCopyable() noexcept = default; ~UnCopyable() noexcept = default; }; template <typename T> class Singleton : private UnCopyable { public: static T& get_instance() noexcept { static T _ins; return _ins; } }; class WSGuarder final : private UnCopyable { public: WSGuarder() noexcept; ~WSGuarder() noexcept; }; class UniqueSocket final : private UnCopyable { SOCKET sockfd_{}; public: UniqueSocket(SOCKET fd) noexcept : sockfd_(fd) {} ~UniqueSocket() noexcept; inline operator SOCKET() const { return sockfd_; } inline operator bool() const { return sockfd_ != INVALID_SOCKET; } }; template <typename Fn, typename... Args> inline auto async(Fn&& fn, Args&&... args) { return std::async(std::launch::async, std::forward<Fn>(fn), std::forward<Args>(args)...); } class ThreadPool final : private UnCopyable { using TaskEntity = std::function<void ()>; using ThreadEntity = std::unique_ptr<std::thread>; bool running_{true}; mutable std::mutex mtx_; std::condition_variable non_empty_; std::vector<ThreadEntity> threads_; std::deque<TaskEntity> tasks_; TaskEntity fetch_task() { std::unique_lock<std::mutex> guard(mtx_); while (tasks_.empty() && running_) non_empty_.wait(guard); TaskEntity t; if (!tasks_.empty()) { t = tasks_.front(); tasks_.pop_front(); } return t; } public: ThreadPool(int thread_num = 4) noexcept { threads_.reserve(thread_num); for (int i = 0; i < thread_num; ++i) threads_.emplace_back(new std::thread([this] { while (running_) { auto t = fetch_task(); if (t) t(); } })); } ~ThreadPool() noexcept { if (running_) { { std::unique_lock<std::mutex> guard(mtx_); running_ = false; non_empty_.notify_all(); } for (auto& t : threads_) t->join(); } } template <typename Fn, typename... Args> void run_task(Fn&& fn, Args&&... args) { if (threads_.empty()) { fn(std::forward<Args>(args)...); } else { using ReturnType = typename std::result_of<Fn (Args&&...)>::type; auto task = std::make_shared<std::packaged_task<ReturnType ()>>( std::bind(std::forward<Fn>(fn), std::forward<Args>(args)...)); { std::unique_lock<std::mutex> guard(mtx_); tasks_.emplace_back([task] { (*task)(); }); } non_empty_.notify_one(); } } }; }<commit_msg>:construction: chore(unique-socket): updated the declaration of unique-socket<commit_after>#pragma once #include <WinSock2.h> #include <deque> #include <functional> #include <memory> #include <thread> #include <future> #include <condition_variable> #include <iostream> namespace common { class Copyable { protected: Copyable() noexcept = default; ~Copyable() noexcept = default; Copyable(const Copyable&) noexcept = default; Copyable(Copyable&&) noexcept = default; Copyable& operator=(const Copyable&) noexcept = default; Copyable& operator=(Copyable&&) noexcept = default; }; class UnCopyable { UnCopyable(const UnCopyable&) noexcept = delete; UnCopyable(UnCopyable&&) noexcept = delete; UnCopyable& operator=(const UnCopyable&) noexcept = delete; UnCopyable& operator=(UnCopyable&&) noexcept = delete; protected: UnCopyable() noexcept = default; ~UnCopyable() noexcept = default; }; template <typename T> class Singleton : private UnCopyable { public: static T& get_instance() noexcept { static T _ins; return _ins; } }; class WSGuarder final : private UnCopyable { public: WSGuarder() noexcept; ~WSGuarder() noexcept; }; class UniqueSocket final : private UnCopyable { SOCKET sockfd_{}; public: UniqueSocket(SOCKET fd = INVALID_SOCKET) noexcept : sockfd_(fd) {} ~UniqueSocket() noexcept; inline void reset(SOCKET fd) noexcept { sockfd_ = fd; } inline operator SOCKET() const noexcept { return sockfd_; } inline operator bool() const noexcept { return sockfd_ != INVALID_SOCKET; } }; template <typename Fn, typename... Args> inline auto async(Fn&& fn, Args&&... args) { return std::async(std::launch::async, std::forward<Fn>(fn), std::forward<Args>(args)...); } class ThreadPool final : private UnCopyable { using TaskEntity = std::function<void ()>; using ThreadEntity = std::unique_ptr<std::thread>; bool running_{true}; mutable std::mutex mtx_; std::condition_variable non_empty_; std::vector<ThreadEntity> threads_; std::deque<TaskEntity> tasks_; TaskEntity fetch_task() { std::unique_lock<std::mutex> guard(mtx_); while (tasks_.empty() && running_) non_empty_.wait(guard); TaskEntity t; if (!tasks_.empty()) { t = tasks_.front(); tasks_.pop_front(); } return t; } public: ThreadPool(int thread_num = 4) noexcept { threads_.reserve(thread_num); for (int i = 0; i < thread_num; ++i) threads_.emplace_back(new std::thread([this] { while (running_) { auto t = fetch_task(); if (t) t(); } })); } ~ThreadPool() noexcept { if (running_) { { std::unique_lock<std::mutex> guard(mtx_); running_ = false; non_empty_.notify_all(); } for (auto& t : threads_) t->join(); } } template <typename Fn, typename... Args> void run_task(Fn&& fn, Args&&... args) { if (threads_.empty()) { fn(std::forward<Args>(args)...); } else { using ReturnType = typename std::result_of<Fn (Args&&...)>::type; auto task = std::make_shared<std::packaged_task<ReturnType ()>>( std::bind(std::forward<Fn>(fn), std::forward<Args>(args)...)); { std::unique_lock<std::mutex> guard(mtx_); tasks_.emplace_back([task] { (*task)(); }); } non_empty_.notify_one(); } } }; }<|endoftext|>
<commit_before>#include "application.h" #include "Adafruit_LEDBackpack.h" #include <math.h> #define TEMP_SENSOR 0x27 #define FAN_PIN A0 #define HEAT_PIN A1 #define POT_PIN A2 #define PIR_PIN A3 Adafruit_8x8matrix matrix1; Adafruit_8x8matrix matrix2; Adafruit_8x8matrix matrix3; static const uint8_t smile[] = { 0b00111100, 0b01000010, 0b10100101, 0b10000001, 0b10100101, 0b10011001, 0b01000010, 0b00111100 }; int currentTemperature = 0; int desiredTemperature = 0; bool isHeatOn = false; bool isFanOn = false; int lastChangedPot = -20; void displayTemperature(void) { char ones = desiredTemperature % 10; char tens = (desiredTemperature / 10) % 10; matrix1.clear(); matrix1.setCursor(0, 0); matrix1.write(tens + '0'); matrix1.writeDisplay(); matrix2.clear(); matrix2.setCursor(0, 0); matrix2.write(ones + '0'); matrix2.writeDisplay(); } void saveTemperature() { uint8_t values[2] = { 0, (uint8_t)desiredTemperature }; sFLASH_WriteBuffer(values, 0x80000, 2); } void loadTemperature() { uint8_t values[2]; sFLASH_ReadBuffer(values, 0x80000, 2); desiredTemperature = values[1]; displayTemperature(); } int setTemperature(int t) { desiredTemperature = t; displayTemperature(); saveTemperature(); return desiredTemperature; } int setTemperatureFromString(String t) { // TODO more robust error handling // what if t is not a number // what if t is outside a sensible range, e.g., 55-85 return setTemperature(t.toInt()); } void setupMatrix(Adafruit_8x8matrix m) { m.clear(); m.writeDisplay(); m.setTextSize(1); m.setTextWrap(false); m.setTextColor(LED_ON); m.setRotation(0); m.setCursor(0, 0); } void setup() { Wire.begin(); matrix1.begin(0x70); matrix2.begin(0x71); matrix3.begin(0x72); setupMatrix(matrix1); setupMatrix(matrix2); setupMatrix(matrix3); Spark.function("set_temp", setTemperatureFromString); Spark.variable("current_temp", &currentTemperature, INT); Spark.variable("desired_temp", &desiredTemperature, INT); Spark.variable("is_heat_on", &isHeatOn, BOOLEAN); Spark.variable("is_fan_on", &isFanOn, BOOLEAN); loadTemperature(); pinMode(FAN_PIN, OUTPUT); pinMode(HEAT_PIN, OUTPUT); pinMode(POT_PIN, INPUT); pinMode(PIR_PIN, INPUT); Serial.begin(9600); } void loop() { static int wait = 1000; if (!wait) { wait = 1000; Wire.requestFrom(TEMP_SENSOR, 4); int humidity = (Wire.read() << 8) & 0x3f00; humidity |= Wire.read(); float percentHumidity = humidity / 163.83; Serial.print("Relative humidity is "); Serial.println(percentHumidity); int temp = (Wire.read() << 6) & 0x3fc0; temp |= Wire.read() >> 2; temp *= 165; float fTemp = temp / 16383.0 - 40.0; fTemp = fTemp * 1.8 + 32.0; // convert to fahrenheit currentTemperature = roundf(fTemp); Serial.print("Temperature is "); Serial.println(fTemp); } int pot = analogRead(POT_PIN); if (1000 == wait) { Serial.print("Potentiometer reading: "); Serial.println(pot); } // If user has adjusted the potentiometer if (fabsf(pot - lastChangedPot) > 16) { // If we're not booting up if (lastChangedPot >= 0) { setTemperature(roundf(pot * (40.0/4095.0) + 50.0)); } lastChangedPot = pot; } digitalWrite(HEAT_PIN, desiredTemperature > currentTemperature); // placeholder nonsense... probably need to attach interrupt to PIR digitalWrite(FAN_PIN, digitalRead(PIR_PIN)); --wait; } <commit_msg>Handle big pot jitter, pot is backward, serial debugging<commit_after>#include "application.h" #include "Adafruit_LEDBackpack.h" #include <math.h> #define TEMP_SENSOR 0x27 #define FAN_PIN A0 #define HEAT_PIN A1 #define POT_PIN A2 #define PIR_PIN A3 Adafruit_8x8matrix matrix1; Adafruit_8x8matrix matrix2; Adafruit_8x8matrix matrix3; static const uint8_t smile[] = { 0b00111100, 0b01000010, 0b10100101, 0b10000001, 0b10100101, 0b10011001, 0b01000010, 0b00111100 }; int currentTemperature = 0; int desiredTemperature = 0; bool isHeatOn = false; bool isFanOn = false; int lastChangedPot = -20; void displayTemperature(void) { char ones = desiredTemperature % 10; char tens = (desiredTemperature / 10) % 10; matrix1.clear(); matrix1.setCursor(0, 0); matrix1.write(tens + '0'); matrix1.writeDisplay(); matrix2.clear(); matrix2.setCursor(0, 0); matrix2.write(ones + '0'); matrix2.writeDisplay(); } void saveTemperature() { uint8_t values[2] = { 0, (uint8_t)desiredTemperature }; sFLASH_WriteBuffer(values, 0x80000, 2); } void loadTemperature() { uint8_t values[2]; sFLASH_ReadBuffer(values, 0x80000, 2); desiredTemperature = values[1]; displayTemperature(); } int setTemperature(int t) { desiredTemperature = t; displayTemperature(); saveTemperature(); return desiredTemperature; } int setTemperatureFromString(String t) { // TODO more robust error handling // what if t is not a number // what if t is outside 50-90 range Serial.print("Setting desired temp from web to "); Serial.println(t); return setTemperature(t.toInt()); } void setupMatrix(Adafruit_8x8matrix m) { m.clear(); m.writeDisplay(); m.setTextSize(1); m.setTextWrap(false); m.setTextColor(LED_ON); m.setRotation(0); m.setCursor(0, 0); } void setup() { Wire.begin(); matrix1.begin(0x70); matrix2.begin(0x71); matrix3.begin(0x72); setupMatrix(matrix1); setupMatrix(matrix2); setupMatrix(matrix3); Spark.function("set_temp", setTemperatureFromString); Spark.variable("current_temp", &currentTemperature, INT); Spark.variable("desired_temp", &desiredTemperature, INT); Spark.variable("is_heat_on", &isHeatOn, BOOLEAN); Spark.variable("is_fan_on", &isFanOn, BOOLEAN); loadTemperature(); pinMode(FAN_PIN, OUTPUT); pinMode(HEAT_PIN, OUTPUT); pinMode(POT_PIN, INPUT); pinMode(PIR_PIN, INPUT); Serial.begin(9600); } void loop() { static int wait = 1000; if (!wait) { wait = 1000; Wire.requestFrom(TEMP_SENSOR, 4); int humidity = (Wire.read() << 8) & 0x3f00; humidity |= Wire.read(); float percentHumidity = humidity / 163.83; Serial.print("Relative humidity is "); Serial.println(percentHumidity); int temp = (Wire.read() << 6) & 0x3fc0; temp |= Wire.read() >> 2; temp *= 165; float fTemp = temp / 16383.0 - 40.0; fTemp = fTemp * 1.8 + 32.0; // convert to fahrenheit currentTemperature = roundf(fTemp); Serial.print("Temperature is "); Serial.println(fTemp); } int pot = 4095 - analogRead(POT_PIN); if (1000 == wait) { Serial.print("Potentiometer reading: "); Serial.println(pot); } // If user has adjusted the potentiometer if (fabsf(pot - lastChangedPot) > 64) { // Don't set temp on boot if (lastChangedPot >= 0) { // map 0-4095 pot range to 50-90 temperature range int t = roundf(pot * (40.0/4095.0) + 50.0); setTemperature(t); Serial.print("Setting desired temp based on potentiometer to "); Serial.println(t); } lastChangedPot = pot; } digitalWrite(HEAT_PIN, desiredTemperature > currentTemperature); // placeholder nonsense... probably need to attach interrupt to PIR digitalWrite(FAN_PIN, digitalRead(PIR_PIN)); --wait; } <|endoftext|>
<commit_before>// Copyright (c) 2013-2014 Flowgrammable.org // // 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. #ifndef FREEFLOW_LIBRARY_HPP #define FREEFLOW_LIBRARY_HPP namespace freeflow { } // namespace freeflow #include "library.ipp" #endif <commit_msg>Working on Library<commit_after>// Copyright (c) 2013-2014 Flowgrammable.org // // 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. #ifndef FREEFLOW_LIBRARY_HPP #define FREEFLOW_LIBRARY_HPP #include <iostream> #include <dlfcn.h> #include <string> namespace freeflow { /* struct Plugin { void* handle; // handle for the dynamically loaded library }; struct Plugin_loader { void open(std::string lib_name); void close(Plugin lib); }; */ struct Library { std::string lib_name; void Library(); void ~Library(); void* handle; }; void Library::open() { handle = dlopen("./apps/noflow/libnoflow.so", RTLD_LAZY); if (!handle) { std::cerr << "Cannot open library: " << dlerror() << '\n'; } } #include "library.ipp" } // namespace freeflow #endif <|endoftext|>
<commit_before>#include "clientmodel.h" #include "guiconstants.h" #include "optionsmodel.h" #include "addresstablemodel.h" #include "transactiontablemodel.h" #include "alert.h" #include "main.h" #include "ui_interface.h" #include <QDateTime> #include <QTimer> static const int64_t nClientStartupTime = GetTime(); ClientModel::ClientModel(OptionsModel *optionsModel, QObject *parent) : QObject(parent), optionsModel(optionsModel), cachedNumBlocks(0), cachedNumBlocksOfPeers(0), pollTimer(0) { numBlocksAtStartup = -1; pollTimer = new QTimer(this); pollTimer->setInterval(MODEL_UPDATE_DELAY); pollTimer->start(); connect(pollTimer, SIGNAL(timeout()), this, SLOT(updateTimer())); subscribeToCoreSignals(); } ClientModel::~ClientModel() { unsubscribeFromCoreSignals(); } int ClientModel::getNumConnections() const { return vNodes.size(); } int ClientModel::getNumBlocks() const { LOCK(cs_main); return nBestHeight; } int ClientModel::getNumBlocksAtStartup() { if (numBlocksAtStartup == -1) numBlocksAtStartup = getNumBlocks(); return numBlocksAtStartup; } quint64 ClientModel::getTotalBytesRecv() const { return CNode::GetTotalBytesRecv(); } quint64 ClientModel::getTotalBytesSent() const { return CNode::GetTotalBytesSent(); } QDateTime ClientModel::getLastBlockDate() const { LOCK(cs_main); if (pindexBest) return QDateTime::fromTime_t(pindexBest->GetBlockTime()); else return QDateTime::fromTime_t(1393221600); // Genesis block's time } void ClientModel::updateTimer() { // Get required lock upfront. This avoids the GUI from getting stuck on // periodical polls if the core is holding the locks for a longer time - // for example, during a wallet rescan. TRY_LOCK(cs_main, lockMain); if(!lockMain) return; // Some quantities (such as number of blocks) change so fast that we don't want to be notified for each change. // Periodically check and update with a timer. int newNumBlocks = getNumBlocks(); int newNumBlocksOfPeers = getNumBlocksOfPeers(); /* if(cachedNumBlocks != newNumBlocks || cachedNumBlocksOfPeers != newNumBlocksOfPeers) { cachedNumBlocks = newNumBlocks; cachedNumBlocksOfPeers = newNumBlocksOfPeers; emit numBlocksChanged(newNumBlocks, newNumBlocksOfPeers); } */ emit numBlocksChanged(newNumBlocks, newNumBlocksOfPeers); emit bytesChanged(getTotalBytesRecv(), getTotalBytesSent()); } void ClientModel::updateNumBlocks() { // Get required lock upfront. This avoids the GUI from getting stuck on // periodical polls if the core is holding the locks for a longer time - // for example, during a wallet rescan. TRY_LOCK(cs_main, lockMain); if(!lockMain) return; int newNumBlocks = getNumBlocks(); int newNumBlocksOfPeers = getNumBlocksOfPeers(); emit numBlocksChanged(newNumBlocks, newNumBlocksOfPeers); emit bytesChanged(getTotalBytesRecv(), getTotalBytesSent()); } void ClientModel::updateNumConnections(int numConnections) { emit numConnectionsChanged(numConnections); } void ClientModel::updateAlert(const QString &hash, int status) { // Show error message notification for new alert if(status == CT_NEW) { uint256 hash_256; hash_256.SetHex(hash.toStdString()); CAlert alert = CAlert::getAlertByHash(hash_256); if(!alert.IsNull()) { emit error(tr("Network Alert"), QString::fromStdString(alert.strStatusBar), false); } } // Emit a numBlocksChanged when the status message changes, // so that the view recomputes and updates the status bar. emit numBlocksChanged(getNumBlocks(), getNumBlocksOfPeers()); } bool ClientModel::isTestNet() const { return fTestNet; } bool ClientModel::inInitialBlockDownload() const { return IsInitialBlockDownload(); } int ClientModel::getNumBlocksOfPeers() const { return GetNumBlocksOfPeers(); } QString ClientModel::getStatusBarWarnings() const { return QString::fromStdString(GetWarnings("statusbar")); } OptionsModel *ClientModel::getOptionsModel() { return optionsModel; } QString ClientModel::formatFullVersion() const { return QString::fromStdString(FormatFullVersion()); } QString ClientModel::formatBuildDate() const { return QString::fromStdString(CLIENT_DATE); } QString ClientModel::clientName() const { return QString::fromStdString(CLIENT_NAME); } QString ClientModel::formatClientStartupTime() const { return QDateTime::fromTime_t(nClientStartupTime).toString(); } // Handlers for core signals static void NotifyBlocksChanged(ClientModel *clientmodel) { // This notification is too frequent. Don't trigger a signal. // Don't remove it, though, as it might be useful later. QMetaObject::invokeMethod(clientmodel, "updateNumBlocks", Qt::QueuedConnection); } static void NotifyNumConnectionsChanged(ClientModel *clientmodel, int newNumConnections) { // Too noisy: OutputDebugStringF("NotifyNumConnectionsChanged %i\n", newNumConnections); QMetaObject::invokeMethod(clientmodel, "updateNumConnections", Qt::QueuedConnection, Q_ARG(int, newNumConnections)); } static void NotifyAlertChanged(ClientModel *clientmodel, const uint256 &hash, ChangeType status) { OutputDebugStringF("NotifyAlertChanged %s status=%i\n", hash.GetHex().c_str(), status); QMetaObject::invokeMethod(clientmodel, "updateAlert", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(hash.GetHex())), Q_ARG(int, status)); } void ClientModel::subscribeToCoreSignals() { // Connect signals to client uiInterface.NotifyBlocksChanged.connect(boost::bind(NotifyBlocksChanged, this)); uiInterface.NotifyNumConnectionsChanged.connect(boost::bind(NotifyNumConnectionsChanged, this, _1)); uiInterface.NotifyAlertChanged.connect(boost::bind(NotifyAlertChanged, this, _1, _2)); } void ClientModel::unsubscribeFromCoreSignals() { // Disconnect signals from client uiInterface.NotifyBlocksChanged.disconnect(boost::bind(NotifyBlocksChanged, this)); uiInterface.NotifyNumConnectionsChanged.disconnect(boost::bind(NotifyNumConnectionsChanged, this, _1)); uiInterface.NotifyAlertChanged.disconnect(boost::bind(NotifyAlertChanged, this, _1, _2)); } <commit_msg>less aggressive ui updates<commit_after>#include "clientmodel.h" #include "guiconstants.h" #include "optionsmodel.h" #include "addresstablemodel.h" #include "transactiontablemodel.h" #include "alert.h" #include "main.h" #include "ui_interface.h" #include <QDateTime> #include <QTimer> static const int64_t nClientStartupTime = GetTime(); ClientModel::ClientModel(OptionsModel *optionsModel, QObject *parent) : QObject(parent), optionsModel(optionsModel), cachedNumBlocks(0), cachedNumBlocksOfPeers(0), pollTimer(0) { numBlocksAtStartup = -1; pollTimer = new QTimer(this); pollTimer->setInterval(MODEL_UPDATE_DELAY); pollTimer->start(); connect(pollTimer, SIGNAL(timeout()), this, SLOT(updateTimer())); subscribeToCoreSignals(); } ClientModel::~ClientModel() { unsubscribeFromCoreSignals(); } int ClientModel::getNumConnections() const { return vNodes.size(); } int ClientModel::getNumBlocks() const { LOCK(cs_main); return nBestHeight; } int ClientModel::getNumBlocksAtStartup() { if (numBlocksAtStartup == -1) numBlocksAtStartup = getNumBlocks(); return numBlocksAtStartup; } quint64 ClientModel::getTotalBytesRecv() const { return CNode::GetTotalBytesRecv(); } quint64 ClientModel::getTotalBytesSent() const { return CNode::GetTotalBytesSent(); } QDateTime ClientModel::getLastBlockDate() const { LOCK(cs_main); if (pindexBest) return QDateTime::fromTime_t(pindexBest->GetBlockTime()); else return QDateTime::fromTime_t(1393221600); // Genesis block's time } void ClientModel::updateTimer() { // Get required lock upfront. This avoids the GUI from getting stuck on // periodical polls if the core is holding the locks for a longer time - // for example, during a wallet rescan. TRY_LOCK(cs_main, lockMain); if(!lockMain) return; // Some quantities (such as number of blocks) change so fast that we don't want to be notified for each change. // Periodically check and update with a timer. int newNumBlocks = getNumBlocks(); int newNumBlocksOfPeers = getNumBlocksOfPeers(); /* if(cachedNumBlocks != newNumBlocks || cachedNumBlocksOfPeers != newNumBlocksOfPeers) { cachedNumBlocks = newNumBlocks; cachedNumBlocksOfPeers = newNumBlocksOfPeers; emit numBlocksChanged(newNumBlocks, newNumBlocksOfPeers); } */ emit numBlocksChanged(newNumBlocks, newNumBlocksOfPeers); emit bytesChanged(getTotalBytesRecv(), getTotalBytesSent()); } void ClientModel::updateNumBlocks() { // Get required lock upfront. This avoids the GUI from getting stuck on // periodical polls if the core is holding the locks for a longer time - // for example, during a wallet rescan. TRY_LOCK(cs_main, lockMain); if(!lockMain) return; int newNumBlocks = getNumBlocks(); int newNumBlocksOfPeers = getNumBlocksOfPeers(); emit numBlocksChanged(newNumBlocks, newNumBlocksOfPeers); emit bytesChanged(getTotalBytesRecv(), getTotalBytesSent()); } void ClientModel::updateNumConnections(int numConnections) { emit numConnectionsChanged(numConnections); } void ClientModel::updateAlert(const QString &hash, int status) { // Show error message notification for new alert if(status == CT_NEW) { uint256 hash_256; hash_256.SetHex(hash.toStdString()); CAlert alert = CAlert::getAlertByHash(hash_256); if(!alert.IsNull()) { emit error(tr("Network Alert"), QString::fromStdString(alert.strStatusBar), false); } } // Emit a numBlocksChanged when the status message changes, // so that the view recomputes and updates the status bar. emit numBlocksChanged(getNumBlocks(), getNumBlocksOfPeers()); } bool ClientModel::isTestNet() const { return fTestNet; } bool ClientModel::inInitialBlockDownload() const { return IsInitialBlockDownload(); } int ClientModel::getNumBlocksOfPeers() const { return GetNumBlocksOfPeers(); } QString ClientModel::getStatusBarWarnings() const { return QString::fromStdString(GetWarnings("statusbar")); } OptionsModel *ClientModel::getOptionsModel() { return optionsModel; } QString ClientModel::formatFullVersion() const { return QString::fromStdString(FormatFullVersion()); } QString ClientModel::formatBuildDate() const { return QString::fromStdString(CLIENT_DATE); } QString ClientModel::clientName() const { return QString::fromStdString(CLIENT_NAME); } QString ClientModel::formatClientStartupTime() const { return QDateTime::fromTime_t(nClientStartupTime).toString(); } // Handlers for core signals static void NotifyBlocksChanged(ClientModel *clientmodel) { // This notification is too frequent. Don't trigger a signal. // Don't remove it, though, as it might be useful later. // QMetaObject::invokeMethod(clientmodel, "updateNumBlocks", Qt::QueuedConnection); } static void NotifyNumConnectionsChanged(ClientModel *clientmodel, int newNumConnections) { // Too noisy: OutputDebugStringF("NotifyNumConnectionsChanged %i\n", newNumConnections); QMetaObject::invokeMethod(clientmodel, "updateNumConnections", Qt::QueuedConnection, Q_ARG(int, newNumConnections)); } static void NotifyAlertChanged(ClientModel *clientmodel, const uint256 &hash, ChangeType status) { OutputDebugStringF("NotifyAlertChanged %s status=%i\n", hash.GetHex().c_str(), status); QMetaObject::invokeMethod(clientmodel, "updateAlert", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(hash.GetHex())), Q_ARG(int, status)); } void ClientModel::subscribeToCoreSignals() { // Connect signals to client uiInterface.NotifyBlocksChanged.connect(boost::bind(NotifyBlocksChanged, this)); uiInterface.NotifyNumConnectionsChanged.connect(boost::bind(NotifyNumConnectionsChanged, this, _1)); uiInterface.NotifyAlertChanged.connect(boost::bind(NotifyAlertChanged, this, _1, _2)); } void ClientModel::unsubscribeFromCoreSignals() { // Disconnect signals from client uiInterface.NotifyBlocksChanged.disconnect(boost::bind(NotifyBlocksChanged, this)); uiInterface.NotifyNumConnectionsChanged.disconnect(boost::bind(NotifyNumConnectionsChanged, this, _1)); uiInterface.NotifyAlertChanged.disconnect(boost::bind(NotifyAlertChanged, this, _1, _2)); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: sendreportgen.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: obo $ $Date: 2006-09-17 04:37:52 $ * * 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" #include "docrecovery.hxx" namespace svx{ namespace DocRecovery{ bool ErrorRepSendDialog::ReadParams() { return false; } bool ErrorRepSendDialog::SaveParams() { return false; } bool ErrorRepSendDialog::SendReport() { return false; } } // namespace DocRecovery } // namespace svx <commit_msg>INTEGRATION: CWS changefileheader (1.3.730); FILE MERGED 2008/03/31 14:20:03 rt 1.3.730.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: sendreportgen.cxx,v $ * $Revision: 1.4 $ * * 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. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #include "docrecovery.hxx" namespace svx{ namespace DocRecovery{ bool ErrorRepSendDialog::ReadParams() { return false; } bool ErrorRepSendDialog::SaveParams() { return false; } bool ErrorRepSendDialog::SendReport() { return false; } } // namespace DocRecovery } // namespace svx <|endoftext|>
<commit_before>#include "musicmydownloadrecordobject.h" MusicMyDownloadRecordObject::MusicMyDownloadRecordObject(QObject *parent) : MusicXmlAbstract(parent) { } void MusicMyDownloadRecordObject::writeDownloadConfig(const QStringList& names, const QStringList& paths) { if( names.isEmpty() || paths.isEmpty() ) return; if( !writeConfig( DOWNLOADINFO ) ) return; /////////////////////////////////////////////////////// m_ddom->appendChild( m_ddom->createProcessingInstruction("xml","version='1.0' encoding='UTF-8'") ); QDomElement QMusicPlayer = m_ddom->createElement("QMusicPlayer"); m_ddom->appendChild(QMusicPlayer); QDomElement download = m_ddom->createElement("download"); QMusicPlayer.appendChild(download); for(int i=0; i<names.count(); ++i) { QDomElement value = m_ddom->createElement("value"); value.setAttribute("value", names[i]); QDomText valuetext = m_ddom->createTextNode(paths[i]); value.appendChild(valuetext); download.appendChild(value); } //Write to file QTextStream out(m_file); m_ddom->save(out,4); } void MusicMyDownloadRecordObject::readDownloadConfig(QStringList &name, QStringList &path) { QDomNodeList nodelist = m_ddom->elementsByTagName("value"); for(int i=0; i<nodelist.count(); ++i) { name<<nodelist.at(i).toElement().attribute("value"); path<<nodelist.at(i).toElement().text(); } } <commit_msg>fix the download record can not be cleaned[012654]<commit_after>#include "musicmydownloadrecordobject.h" MusicMyDownloadRecordObject::MusicMyDownloadRecordObject(QObject *parent) : MusicXmlAbstract(parent) { } void MusicMyDownloadRecordObject::writeDownloadConfig(const QStringList& names, const QStringList& paths) { if( !writeConfig( DOWNLOADINFO ) ) return; /////////////////////////////////////////////////////// m_ddom->appendChild( m_ddom->createProcessingInstruction("xml","version='1.0' encoding='UTF-8'") ); QDomElement QMusicPlayer = m_ddom->createElement("QMusicPlayer"); m_ddom->appendChild(QMusicPlayer); QDomElement download = m_ddom->createElement("download"); QMusicPlayer.appendChild(download); for(int i=0; i<names.count(); ++i) { QDomElement value = m_ddom->createElement("value"); value.setAttribute("value", names[i]); QDomText valuetext = m_ddom->createTextNode(paths[i]); value.appendChild(valuetext); download.appendChild(value); } //Write to file QTextStream out(m_file); m_ddom->save(out,4); } void MusicMyDownloadRecordObject::readDownloadConfig(QStringList &name, QStringList &path) { QDomNodeList nodelist = m_ddom->elementsByTagName("value"); for(int i=0; i<nodelist.count(); ++i) { name<<nodelist.at(i).toElement().attribute("value"); path<<nodelist.at(i).toElement().text(); } } <|endoftext|>
<commit_before>#include "ROOT/RDataFrame.hxx" #include "TChain.h" #include "TEntryList.h" #include "TFile.h" #include "TROOT.h" #include "TSystem.h" #include "TTree.h" #include "gtest/gtest.h" #include <vector> // Write to disk file filename with TTree "t" with nEntries of branch "e" assuming integer values [0..nEntries). void MakeInputFile(const std::string &filename, int nEntries) { const auto treename = "t"; auto d = ROOT::RDataFrame(nEntries) .Define("e", [](ULong64_t e) { return int(e); }, {"rdfentry_"}) .Snapshot<int>(treename, filename, {"e"}); } class RMTRAII { bool fIsMT; public: RMTRAII(bool isMT) : fIsMT(isMT) { if (fIsMT) ROOT::EnableImplicitMT(); } ~RMTRAII() { if (fIsMT) ROOT::DisableImplicitMT(); } }; void TestTreeWithEntryList(bool isMT = false) { const auto nEntries = 10; const auto treename = "t"; const auto filename = "rdfentrylist.root"; MakeInputFile(filename, nEntries); RMTRAII gomt(isMT); TEntryList elist("e", "e", treename, filename); elist.Enter(0); elist.Enter(nEntries - 1); TFile f(filename); auto t = f.Get<TTree>(treename); t->SetEntryList(&elist); auto entries = ROOT::RDataFrame(*t).Take<int>("e"); EXPECT_EQ(*entries, std::vector<int>({0, nEntries - 1})); gSystem->Unlink(filename); } void TestChainWithEntryList(bool isMT = false) { const auto nEntries = 10; const auto treename = "t"; const auto file1 = "rdfentrylist1.root"; MakeInputFile(file1, nEntries); const auto file2 = "rdfentrylist2.root"; MakeInputFile(file2, nEntries); RMTRAII gomt(isMT); TEntryList elist1("e", "e", treename, file1); elist1.Enter(0); elist1.Enter(2 * nEntries - 1); TEntryList elist2("e", "e", treename, file2); elist2.Enter(0); elist2.Enter(2 * nEntries - 1); // make a TEntryList that contains two TEntryLists in its list of TEntryLists, // as required by TChain (see TEntryList's doc) TEntryList elists; elists.Add(&elist1); elists.Add(&elist2); TChain c(treename); c.Add(file1, nEntries); c.Add(file2, nEntries); c.SetEntryList(&elists); auto entries = ROOT::RDataFrame(c).Take<int>("e"); EXPECT_EQ(*entries, std::vector<int>({0, nEntries - 1, 0, nEntries - 1})); gSystem->Unlink(file1); gSystem->Unlink(file2); } TEST(RDFEntryList, Chain) { TestChainWithEntryList(); } TEST(RDFEntryList, Tree) { TestTreeWithEntryList(); } #ifdef R__USE_IMT TEST(RDFEntryList, DISABLED_ChainMT) { TestChainWithEntryList(true); } TEST(RDFEntryList, TreeMT) { TestTreeWithEntryList(true); } #endif <commit_msg>[RDF] TEntryList test: re-enable TChain MT test-case<commit_after>#include "ROOT/RDataFrame.hxx" #include "TChain.h" #include "TEntryList.h" #include "TFile.h" #include "TROOT.h" #include "TSystem.h" #include "TTree.h" #include "gtest/gtest.h" #include <vector> // Write to disk file filename with TTree "t" with nEntries of branch "e" assuming integer values [0..nEntries). void MakeInputFile(const std::string &filename, int nEntries) { const auto treename = "t"; auto d = ROOT::RDataFrame(nEntries) .Define("e", [](ULong64_t e) { return int(e); }, {"rdfentry_"}) .Snapshot<int>(treename, filename, {"e"}); } class RMTRAII { bool fIsMT; public: RMTRAII(bool isMT) : fIsMT(isMT) { if (fIsMT) ROOT::EnableImplicitMT(); } ~RMTRAII() { if (fIsMT) ROOT::DisableImplicitMT(); } }; void TestTreeWithEntryList(bool isMT = false) { const auto nEntries = 10; const auto treename = "t"; const auto filename = "rdfentrylist.root"; MakeInputFile(filename, nEntries); RMTRAII gomt(isMT); TEntryList elist("e", "e", treename, filename); elist.Enter(0); elist.Enter(nEntries - 1); TFile f(filename); auto t = f.Get<TTree>(treename); t->SetEntryList(&elist); auto entries = ROOT::RDataFrame(*t).Take<int>("e"); EXPECT_EQ(*entries, std::vector<int>({0, nEntries - 1})); gSystem->Unlink(filename); } void TestChainWithEntryList(bool isMT = false) { const auto nEntries = 10; const auto treename = "t"; const auto file1 = "rdfentrylist1.root"; const auto file2 = "rdfentrylist2.root"; MakeInputFile(file1, nEntries); MakeInputFile(file2, nEntries); RMTRAII gomt(isMT); TEntryList elist1("e", "e", treename, file1); elist1.Enter(0); elist1.Enter(nEntries - 1); TEntryList elist2("e", "e", treename, file2); elist2.Enter(0); elist2.Enter(nEntries - 1); // make a TEntryList that contains two TEntryLists in its list of TEntryLists, // as required by TChain (see TEntryList's doc) TEntryList elists; elists.Add(&elist1); elists.Add(&elist2); TChain c(treename); c.Add(file1, nEntries); c.Add(file2, nEntries); c.SetEntryList(&elists); auto entries = ROOT::RDataFrame(c).Take<int>("e"); EXPECT_EQ(*entries, std::vector<int>({0, nEntries - 1, 0, nEntries - 1})); gSystem->Unlink(file1); gSystem->Unlink(file2); } TEST(RDFEntryList, Chain) { TestChainWithEntryList(); } TEST(RDFEntryList, Tree) { TestTreeWithEntryList(); } #ifdef R__USE_IMT TEST(RDFEntryList, ChainMT) { TestChainWithEntryList(true); } TEST(RDFEntryList, TreeMT) { TestTreeWithEntryList(true); } #endif <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- * * XPLC - Cross-Platform Lightweight Components * Copyright (C) 2000, Pierre Phaneuf * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public License * as published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library 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 <stdio.h> #include <libIDL/IDL.h> class Node { public: Node* next; static Node* convertIdlToNode(IDL_tree); Node(); }; class InterfaceNode: public Node { private: IDL_tree parent; public: InterfaceNode(IDL_tree ident, IDL_tree inherit, IDL_tree body); }; Node::Node(): next(NULL) { } InterfaceNode::InterfaceNode(IDL_tree ident, IDL_tree inherit, IDL_tree body) { if(IDL_NODE_TYPE(ident) != IDLN_IDENT) { printf("InterfaceNode: ident is not an IDLN_IDENT!\n"); exit(1); } if(inherit) { if(IDL_NODE_TYPE(inherit) != IDLN_LIST) { printf("InterfaceNode: inherit is not an IDLN_LIST!\n"); exit(1); } if(IDL_LIST(inherit).next) { printf("InterfaceNode: multiple inheritance is forbidden\n"); exit(1); } parent = IDL_LIST(inherit).data; printf("parent is %s\n", IDL_NODE_TYPE_NAME(parent)); } else parent = NULL; if(body && (IDL_NODE_TYPE(body) != IDLN_LIST)) { printf("InterfaceNode: body is not an IDLN_LIST!\n"); exit(1); } if(parent) printf("interface %s: public %s\n", IDL_IDENT(ident).str, IDL_IDENT(parent).str); else printf("interface %s\n", IDL_IDENT(ident).str); } Node* Node::convertIdlToNode(IDL_tree tree) { Node* current; Node* tmp; IDL_tree ptr; if(!tree) { printf("convertIdlToNode was passed a null node!\n"); exit(1); } switch(IDL_NODE_TYPE(tree)) { case IDLN_LIST: current = convertIdlToNode(IDL_LIST(tree).data); tmp = current; ptr = IDL_LIST(tree).next; while(ptr && tmp) { tmp->next = convertIdlToNode(IDL_LIST(ptr).data); tmp = tmp->next; ptr = IDL_LIST(ptr).next; } break; case IDLN_INTERFACE: current = new InterfaceNode(IDL_INTERFACE(tree).ident, IDL_INTERFACE(tree).inheritance_spec, IDL_INTERFACE(tree).body); break; default: printf("Unknown node type (%s), aborting.\n", IDL_NODE_TYPE_NAME(tree)); exit(1); } return current; } void parse_file(const char* fn) { IDL_tree tree; Node* root; printf("parsing file %s\n", fn); IDL_parse_filename(fn, NULL, NULL, &tree, NULL, 0, IDL_WARNINGMAX); root = Node::convertIdlToNode(tree); } int main(unsigned int argc, char* argv[]) { unsigned int i; /* parse arguments */ for(i = 1; i < argc; i++) { parse_file(argv[i]); } } <commit_msg>Checkpointing changes to the non-working IDL compiler.<commit_after>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- * * XPLC - Cross-Platform Lightweight Components * Copyright (C) 2000, Pierre Phaneuf * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public License * as published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library 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 <stdio.h> #include <libIDL/IDL.h> class Node { public: Node* next; static Node* convertIdlToNode(IDL_tree); Node(); }; class InterfaceNode: public Node { private: char* name; char* parent; public: InterfaceNode(IDL_tree ident, IDL_tree inherit, IDL_tree body); }; class MethodNode: public Node { public: MethodNode(IDL_tree node); }; Node::Node(): next(NULL) { } void showprops(const char* name, IDL_tree node) { if(IDL_NODE_PROPERTIES(node)) printf("%s: %i properties\n", name, g_hash_table_size(IDL_NODE_PROPERTIES(node))); else printf("%s: no properties\n", name); } MethodNode::MethodNode(IDL_tree node) { printf("Method node: %s\n", IDL_IDENT(IDL_OP_DCL(node).ident).str); } InterfaceNode::InterfaceNode(IDL_tree ident, IDL_tree inherit, IDL_tree body): name(NULL), parent(NULL) { Node* head; Node* node; IDL_tree ptr; if(IDL_NODE_TYPE(ident) != IDLN_IDENT) { printf("InterfaceNode: ident is not an IDLN_IDENT!\n"); exit(1); } name = IDL_IDENT(ident).str; if(inherit) { if(IDL_NODE_TYPE(inherit) != IDLN_LIST) { printf("InterfaceNode: inherit is not an IDLN_LIST!\n"); exit(1); } if(IDL_LIST(inherit).next) { printf("InterfaceNode: multiple inheritance is forbidden\n"); exit(1); } if(IDL_NODE_TYPE(IDL_LIST(inherit).data) != IDLN_IDENT) { printf("InterfaceNode: parent is not an IDLN_IDENT!\n"); exit(1); } parent = IDL_IDENT(IDL_LIST(inherit).data).str; } else parent = NULL; if(body && (IDL_NODE_TYPE(body) != IDLN_LIST)) { printf("InterfaceNode: body is not an IDLN_LIST!\n"); exit(1); } if(body) { head = Node::convertIdlToNode(IDL_LIST(body).data); node = head; ptr = IDL_LIST(body).next; while(ptr) { node->next = Node::convertIdlToNode(IDL_LIST(ptr).data); ptr = IDL_LIST(ptr).next; } } if(parent) printf("interface %s: %s\n", name, parent); else printf("interface %s\n", name); } Node* Node::convertIdlToNode(IDL_tree tree) { Node* current; Node* tmp; IDL_tree ptr; if(!tree) { printf("convertIdlToNode was passed a null node!\n"); exit(1); } switch(IDL_NODE_TYPE(tree)) { case IDLN_LIST: current = convertIdlToNode(IDL_LIST(tree).data); tmp = current; ptr = IDL_LIST(tree).next; while(ptr && tmp) { tmp->next = convertIdlToNode(IDL_LIST(ptr).data); tmp = tmp->next; ptr = IDL_LIST(ptr).next; } break; case IDLN_INTERFACE: current = new InterfaceNode(IDL_INTERFACE(tree).ident, IDL_INTERFACE(tree).inheritance_spec, IDL_INTERFACE(tree).body); break; case IDLN_MODULE: printf("\"module\" keyword not supported!\n"); exit(1); break; case IDLN_ATTR_DCL: printf("attributes not supported!\n"); exit(1); break; case IDLN_OP_DCL: current = new MethodNode(tree); break; default: printf("Unknown node type (%s), aborting.\n", IDL_NODE_TYPE_NAME(tree)); exit(1); } if(!current) { printf("convertIdlToNode is returning a null node!\n"); exit(1); } return current; } void parse_file(const char* fn) { IDL_tree tree; Node* root; printf("parsing file %s\n", fn); IDL_parse_filename(fn, NULL, NULL, &tree, NULL, IDLF_PROPERTIES|IDLF_CODEFRAGS, IDL_WARNINGMAX); root = Node::convertIdlToNode(tree); } int main(unsigned int argc, char* argv[]) { unsigned int i; /* parse arguments */ for(i = 1; i < argc; i++) { parse_file(argv[i]); } } <|endoftext|>
<commit_before>// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // 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 <unordered_set> #include "rmw/impl/cpp/macros.hpp" #include "rmw_fastrtps_shared_cpp/rmw_common.hpp" #include "types/event_types.hpp" static const std::unordered_set<rmw_event_type_t> g_rmw_event_type_set{ RMW_EVENT_LIVELINESS_CHANGED, RMW_EVENT_REQUESTED_DEADLINE_MISSED, RMW_EVENT_LIVELINESS_LOST, RMW_EVENT_OFFERED_DEADLINE_MISSED }; namespace rmw_fastrtps_shared_cpp { namespace internal { bool is_event_supported(rmw_event_type_t event_type) { return g_rmw_event_type_set.count(event_type) == 1; } } // namespace internal rmw_ret_t __rmw_init_event( const char * identifier, rmw_event_t * rmw_event, const char * topic_endpoint_impl_identifier, void * data, rmw_event_type_t event_type) { RMW_CHECK_ARGUMENT_FOR_NULL(identifier, RMW_RET_INVALID_ARGUMENT); RMW_CHECK_ARGUMENT_FOR_NULL(rmw_event, RMW_RET_INVALID_ARGUMENT); RMW_CHECK_ARGUMENT_FOR_NULL(topic_endpoint_impl_identifier, RMW_RET_INVALID_ARGUMENT); RMW_CHECK_ARGUMENT_FOR_NULL(data, RMW_RET_INVALID_ARGUMENT); RMW_CHECK_TYPE_IDENTIFIERS_MATCH( topic endpoint, topic_endpoint_impl_identifier, identifier, return RMW_RET_INCORRECT_RMW_IMPLEMENTATION); if (!internal::is_event_supported(event_type)) { RMW_SET_ERROR_MSG("provided event_type is not supported by rmw_fastrtps_cpp"); return RMW_RET_UNSUPPORTED; } rmw_event->implementation_identifier = topic_endpoint_impl_identifier; rmw_event->data = data; rmw_event->event_type = event_type; return RMW_RET_OK; } } // namespace rmw_fastrtps_shared_cpp <commit_msg>Correct error message when event is not supported (#358)<commit_after>// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // 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 <unordered_set> #include "rmw/impl/cpp/macros.hpp" #include "rmw_fastrtps_shared_cpp/rmw_common.hpp" #include "types/event_types.hpp" static const std::unordered_set<rmw_event_type_t> g_rmw_event_type_set{ RMW_EVENT_LIVELINESS_CHANGED, RMW_EVENT_REQUESTED_DEADLINE_MISSED, RMW_EVENT_LIVELINESS_LOST, RMW_EVENT_OFFERED_DEADLINE_MISSED }; namespace rmw_fastrtps_shared_cpp { namespace internal { bool is_event_supported(rmw_event_type_t event_type) { return g_rmw_event_type_set.count(event_type) == 1; } } // namespace internal rmw_ret_t __rmw_init_event( const char * identifier, rmw_event_t * rmw_event, const char * topic_endpoint_impl_identifier, void * data, rmw_event_type_t event_type) { RMW_CHECK_ARGUMENT_FOR_NULL(identifier, RMW_RET_INVALID_ARGUMENT); RMW_CHECK_ARGUMENT_FOR_NULL(rmw_event, RMW_RET_INVALID_ARGUMENT); RMW_CHECK_ARGUMENT_FOR_NULL(topic_endpoint_impl_identifier, RMW_RET_INVALID_ARGUMENT); RMW_CHECK_ARGUMENT_FOR_NULL(data, RMW_RET_INVALID_ARGUMENT); RMW_CHECK_TYPE_IDENTIFIERS_MATCH( topic endpoint, topic_endpoint_impl_identifier, identifier, return RMW_RET_INCORRECT_RMW_IMPLEMENTATION); if (!internal::is_event_supported(event_type)) { RMW_SET_ERROR_MSG_WITH_FORMAT_STRING("provided event_type is not supported by %s", identifier); return RMW_RET_UNSUPPORTED; } rmw_event->implementation_identifier = topic_endpoint_impl_identifier; rmw_event->data = data; rmw_event->event_type = event_type; return RMW_RET_OK; } } // namespace rmw_fastrtps_shared_cpp <|endoftext|>
<commit_before>//===- TopDownClosure.cpp - Compute the top-down interprocedure closure ---===// // // This file implements the TDDataStructures class, which represents the // Top-down Interprocedural closure of the data structure graph over the // program. This is useful (but not strictly necessary?) for applications // like pointer analysis. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/DataStructure.h" #include "llvm/Analysis/DSGraph.h" #include "llvm/Module.h" #include "llvm/DerivedTypes.h" #include "Support/Statistic.h" namespace { RegisterAnalysis<TDDataStructures> // Register the pass Y("tddatastructure", "Top-down Data Structure Analysis"); } // run - Calculate the top down data structure graphs for each function in the // program. // bool TDDataStructures::run(Module &M) { BUDataStructures &BU = getAnalysis<BUDataStructures>(); GlobalsGraph = new DSGraph(BU.getGlobalsGraph()); // Calculate top-down from main... if (Function *F = M.getMainFunction()) calculateGraph(*F); // Next calculate the graphs for each function unreachable function... for (Module::reverse_iterator I = M.rbegin(), E = M.rend(); I != E; ++I) if (!I->isExternal()) calculateGraph(*I); GraphDone.clear(); // Free temporary memory... return false; } // releaseMemory - If the pass pipeline is done with this pass, we can release // our memory... here... // // FIXME: This should be releaseMemory and will work fine, except that LoadVN // has no way to extend the lifetime of the pass, which screws up ds-aa. // void TDDataStructures::releaseMyMemory() { for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(), E = DSInfo.end(); I != E; ++I) { I->second->getReturnNodes().erase(I->first); if (I->second->getReturnNodes().empty()) delete I->second; } // Empty map so next time memory is released, data structures are not // re-deleted. DSInfo.clear(); delete GlobalsGraph; GlobalsGraph = 0; } #if 0 /// ResolveCallSite - This method is used to link the actual arguments together /// with the formal arguments for a function call in the top-down closure. This /// method assumes that the call site arguments have been mapped into nodes /// local to the specified graph. /// void TDDataStructures::ResolveCallSite(DSGraph &Graph, const DSCallSite &CallSite) { // Resolve all of the function formal arguments... Function &F = Graph.getFunction(); Function::aiterator AI = F.abegin(); for (unsigned i = 0, e = CallSite.getNumPtrArgs(); i != e; ++i, ++AI) { // Advance the argument iterator to the first pointer argument... while (!DS::isPointerType(AI->getType())) ++AI; // TD ...Merge the formal arg scalar with the actual arg node DSNodeHandle &NodeForFormal = Graph.getNodeForValue(AI); assert(NodeForFormal.getNode() && "Pointer argument has no dest node!"); NodeForFormal.mergeWith(CallSite.getPtrArg(i)); } // Merge returned node in the caller with the "return" node in callee if (CallSite.getRetVal().getNode() && Graph.getRetNode().getNode()) Graph.getRetNode().mergeWith(CallSite.getRetVal()); } #endif DSGraph &TDDataStructures::getOrCreateDSGraph(Function &F) { DSGraph *&G = DSInfo[&F]; if (G == 0) { // Not created yet? Clone BU graph... G = new DSGraph(getAnalysis<BUDataStructures>().getDSGraph(F)); G->getAuxFunctionCalls().clear(); G->setPrintAuxCalls(); G->setGlobalsGraph(GlobalsGraph); } return *G; } /// FunctionHasCompleteArguments - This function returns true if it is safe not /// to mark arguments to the function complete. /// /// FIXME: Need to check if all callers have been found, or rather if a /// funcpointer escapes! /// static bool FunctionHasCompleteArguments(Function &F) { return F.hasInternalLinkage(); } void TDDataStructures::calculateGraph(Function &F) { // Make sure this graph has not already been calculated, and that we don't get // into an infinite loop with mutually recursive functions. // if (GraphDone.count(&F)) return; GraphDone.insert(&F); // Get the current functions graph... DSGraph &Graph = getOrCreateDSGraph(F); // Recompute the Incomplete markers and eliminate unreachable nodes. Graph.maskIncompleteMarkers(); unsigned Flags = FunctionHasCompleteArguments(F) ? DSGraph::IgnoreFormalArgs : DSGraph::MarkFormalArgs; Graph.markIncompleteNodes(Flags | DSGraph::IgnoreGlobals); Graph.removeDeadNodes(DSGraph::RemoveUnreachableGlobals); const std::vector<DSCallSite> &CallSites = Graph.getFunctionCalls(); if (CallSites.empty()) { DEBUG(std::cerr << " [TD] No callees for: " << F.getName() << "\n"); } else { // Loop over all of the call sites, building a multi-map from Callees to // DSCallSite*'s. With this map we can then loop over each callee, cloning // this graph once into it, then resolving arguments. // std::multimap<Function*, const DSCallSite*> CalleeSites; for (unsigned i = 0, e = CallSites.size(); i != e; ++i) { const DSCallSite &CS = CallSites[i]; if (CS.isDirectCall()) { if (!CS.getCalleeFunc()->isExternal()) // If it's not external CalleeSites.insert(std::make_pair(CS.getCalleeFunc(), &CS));// Keep it } else { const std::vector<GlobalValue*> &Callees = CS.getCalleeNode()->getGlobals(); // Loop over all of the functions that this call may invoke... for (unsigned c = 0, e = Callees.size(); c != e; ++c) if (Function *F = dyn_cast<Function>(Callees[c]))// If this is a fn... if (!F->isExternal()) // If it's not extern CalleeSites.insert(std::make_pair(F, &CS)); // Keep track of it! } } // Now that we have information about all of the callees, propagate the // current graph into the callees. // DEBUG(std::cerr << " [TD] Inlining '" << F.getName() << "' into " << CalleeSites.size() << " callees.\n"); // Loop over all the callees... for (std::multimap<Function*, const DSCallSite*>::iterator I = CalleeSites.begin(), E = CalleeSites.end(); I != E; ) if (I->first == &F) { // Bottom-up pass takes care of self loops! ++I; } else { // For each callee... Function &Callee = *I->first; DSGraph &CG = getOrCreateDSGraph(Callee); // Get the callee's graph... DEBUG(std::cerr << "\t [TD] Inlining into callee '" << Callee.getName() << "'\n"); // Clone our current graph into the callee... DSGraph::ScalarMapTy OldValMap; DSGraph::NodeMapTy OldNodeMap; DSGraph::ReturnNodesTy ReturnNodes; CG.cloneInto(Graph, OldValMap, ReturnNodes, OldNodeMap, DSGraph::StripModRefBits | DSGraph::KeepAllocaBit | DSGraph::DontCloneCallNodes | DSGraph::DontCloneAuxCallNodes); OldValMap.clear(); // We don't care about the ValMap ReturnNodes.clear(); // We don't care about return values either // Loop over all of the invocation sites of the callee, resolving // arguments to our graph. This loop may iterate multiple times if the // current function calls this callee multiple times with different // signatures. // for (; I != E && I->first == &Callee; ++I) { // Map call site into callee graph DSCallSite NewCS(*I->second, OldNodeMap); // Resolve the return values... NewCS.getRetVal().mergeWith(CG.getReturnNodeFor(Callee)); // Resolve all of the arguments... Function::aiterator AI = Callee.abegin(); for (unsigned i = 0, e = NewCS.getNumPtrArgs(); i != e && AI != Callee.aend(); ++i, ++AI) { // Advance the argument iterator to the first pointer argument... while (AI != Callee.aend() && !DS::isPointerType(AI->getType())) ++AI; if (AI == Callee.aend()) break; // Add the link from the argument scalar to the provided value DSNodeHandle &NH = CG.getNodeForValue(AI); assert(NH.getNode() && "Pointer argument without scalarmap entry?"); NH.mergeWith(NewCS.getPtrArg(i)); } } // Done with the nodemap... OldNodeMap.clear(); // Recompute the Incomplete markers and eliminate unreachable nodes. CG.removeTriviallyDeadNodes(); CG.maskIncompleteMarkers(); CG.markIncompleteNodes(DSGraph::MarkFormalArgs |DSGraph::IgnoreGlobals); CG.removeDeadNodes(DSGraph::RemoveUnreachableGlobals); } DEBUG(std::cerr << " [TD] Done inlining into callees for: " << F.getName() << " [" << Graph.getGraphSize() << "+" << Graph.getFunctionCalls().size() << "]\n"); // Loop over all the callees... making sure they are all resolved now... Function *LastFunc = 0; for (std::multimap<Function*, const DSCallSite*>::iterator I = CalleeSites.begin(), E = CalleeSites.end(); I != E; ++I) if (I->first != LastFunc) { // Only visit each callee once... LastFunc = I->first; calculateGraph(*I->first); } } } <commit_msg>Remove dead method<commit_after>//===- TopDownClosure.cpp - Compute the top-down interprocedure closure ---===// // // This file implements the TDDataStructures class, which represents the // Top-down Interprocedural closure of the data structure graph over the // program. This is useful (but not strictly necessary?) for applications // like pointer analysis. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/DataStructure.h" #include "llvm/Analysis/DSGraph.h" #include "llvm/Module.h" #include "llvm/DerivedTypes.h" #include "Support/Statistic.h" namespace { RegisterAnalysis<TDDataStructures> // Register the pass Y("tddatastructure", "Top-down Data Structure Analysis"); } // run - Calculate the top down data structure graphs for each function in the // program. // bool TDDataStructures::run(Module &M) { BUDataStructures &BU = getAnalysis<BUDataStructures>(); GlobalsGraph = new DSGraph(BU.getGlobalsGraph()); // Calculate top-down from main... if (Function *F = M.getMainFunction()) calculateGraph(*F); // Next calculate the graphs for each function unreachable function... for (Module::reverse_iterator I = M.rbegin(), E = M.rend(); I != E; ++I) if (!I->isExternal()) calculateGraph(*I); GraphDone.clear(); // Free temporary memory... return false; } // releaseMemory - If the pass pipeline is done with this pass, we can release // our memory... here... // // FIXME: This should be releaseMemory and will work fine, except that LoadVN // has no way to extend the lifetime of the pass, which screws up ds-aa. // void TDDataStructures::releaseMyMemory() { for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(), E = DSInfo.end(); I != E; ++I) { I->second->getReturnNodes().erase(I->first); if (I->second->getReturnNodes().empty()) delete I->second; } // Empty map so next time memory is released, data structures are not // re-deleted. DSInfo.clear(); delete GlobalsGraph; GlobalsGraph = 0; } DSGraph &TDDataStructures::getOrCreateDSGraph(Function &F) { DSGraph *&G = DSInfo[&F]; if (G == 0) { // Not created yet? Clone BU graph... G = new DSGraph(getAnalysis<BUDataStructures>().getDSGraph(F)); G->getAuxFunctionCalls().clear(); G->setPrintAuxCalls(); G->setGlobalsGraph(GlobalsGraph); } return *G; } /// FunctionHasCompleteArguments - This function returns true if it is safe not /// to mark arguments to the function complete. /// /// FIXME: Need to check if all callers have been found, or rather if a /// funcpointer escapes! /// static bool FunctionHasCompleteArguments(Function &F) { return F.hasInternalLinkage(); } void TDDataStructures::calculateGraph(Function &F) { // Make sure this graph has not already been calculated, and that we don't get // into an infinite loop with mutually recursive functions. // if (GraphDone.count(&F)) return; GraphDone.insert(&F); // Get the current functions graph... DSGraph &Graph = getOrCreateDSGraph(F); // Recompute the Incomplete markers and eliminate unreachable nodes. Graph.maskIncompleteMarkers(); unsigned Flags = FunctionHasCompleteArguments(F) ? DSGraph::IgnoreFormalArgs : DSGraph::MarkFormalArgs; Graph.markIncompleteNodes(Flags | DSGraph::IgnoreGlobals); Graph.removeDeadNodes(DSGraph::RemoveUnreachableGlobals); const std::vector<DSCallSite> &CallSites = Graph.getFunctionCalls(); if (CallSites.empty()) { DEBUG(std::cerr << " [TD] No callees for: " << F.getName() << "\n"); } else { // Loop over all of the call sites, building a multi-map from Callees to // DSCallSite*'s. With this map we can then loop over each callee, cloning // this graph once into it, then resolving arguments. // std::multimap<Function*, const DSCallSite*> CalleeSites; for (unsigned i = 0, e = CallSites.size(); i != e; ++i) { const DSCallSite &CS = CallSites[i]; if (CS.isDirectCall()) { if (!CS.getCalleeFunc()->isExternal()) // If it's not external CalleeSites.insert(std::make_pair(CS.getCalleeFunc(), &CS));// Keep it } else { const std::vector<GlobalValue*> &Callees = CS.getCalleeNode()->getGlobals(); // Loop over all of the functions that this call may invoke... for (unsigned c = 0, e = Callees.size(); c != e; ++c) if (Function *F = dyn_cast<Function>(Callees[c]))// If this is a fn... if (!F->isExternal()) // If it's not extern CalleeSites.insert(std::make_pair(F, &CS)); // Keep track of it! } } // Now that we have information about all of the callees, propagate the // current graph into the callees. // DEBUG(std::cerr << " [TD] Inlining '" << F.getName() << "' into " << CalleeSites.size() << " callees.\n"); // Loop over all the callees... for (std::multimap<Function*, const DSCallSite*>::iterator I = CalleeSites.begin(), E = CalleeSites.end(); I != E; ) if (I->first == &F) { // Bottom-up pass takes care of self loops! ++I; } else { // For each callee... Function &Callee = *I->first; DSGraph &CG = getOrCreateDSGraph(Callee); // Get the callee's graph... DEBUG(std::cerr << "\t [TD] Inlining into callee '" << Callee.getName() << "'\n"); // Clone our current graph into the callee... DSGraph::ScalarMapTy OldValMap; DSGraph::NodeMapTy OldNodeMap; DSGraph::ReturnNodesTy ReturnNodes; CG.cloneInto(Graph, OldValMap, ReturnNodes, OldNodeMap, DSGraph::StripModRefBits | DSGraph::KeepAllocaBit | DSGraph::DontCloneCallNodes | DSGraph::DontCloneAuxCallNodes); OldValMap.clear(); // We don't care about the ValMap ReturnNodes.clear(); // We don't care about return values either // Loop over all of the invocation sites of the callee, resolving // arguments to our graph. This loop may iterate multiple times if the // current function calls this callee multiple times with different // signatures. // for (; I != E && I->first == &Callee; ++I) { // Map call site into callee graph DSCallSite NewCS(*I->second, OldNodeMap); // Resolve the return values... NewCS.getRetVal().mergeWith(CG.getReturnNodeFor(Callee)); // Resolve all of the arguments... Function::aiterator AI = Callee.abegin(); for (unsigned i = 0, e = NewCS.getNumPtrArgs(); i != e && AI != Callee.aend(); ++i, ++AI) { // Advance the argument iterator to the first pointer argument... while (AI != Callee.aend() && !DS::isPointerType(AI->getType())) ++AI; if (AI == Callee.aend()) break; // Add the link from the argument scalar to the provided value DSNodeHandle &NH = CG.getNodeForValue(AI); assert(NH.getNode() && "Pointer argument without scalarmap entry?"); NH.mergeWith(NewCS.getPtrArg(i)); } } // Done with the nodemap... OldNodeMap.clear(); // Recompute the Incomplete markers and eliminate unreachable nodes. CG.removeTriviallyDeadNodes(); CG.maskIncompleteMarkers(); CG.markIncompleteNodes(DSGraph::MarkFormalArgs |DSGraph::IgnoreGlobals); CG.removeDeadNodes(DSGraph::RemoveUnreachableGlobals); } DEBUG(std::cerr << " [TD] Done inlining into callees for: " << F.getName() << " [" << Graph.getGraphSize() << "+" << Graph.getFunctionCalls().size() << "]\n"); // Loop over all the callees... making sure they are all resolved now... Function *LastFunc = 0; for (std::multimap<Function*, const DSCallSite*>::iterator I = CalleeSites.begin(), E = CalleeSites.end(); I != E; ++I) if (I->first != LastFunc) { // Only visit each callee once... LastFunc = I->first; calculateGraph(*I->first); } } } <|endoftext|>
<commit_before>/** * Copyright 2016-2017 MICRORISC s.r.o. * * 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 "LaunchUtils.h" #include "SimpleSerializer.h" #include "IqrfLogging.h" #include <vector> #include <iterator> #include <array> INIT_COMPONENT(ISerializer, SimpleSerializer) std::vector<std::string> parseTokens(DpaTask& dpaTask, std::istream& istr) { std::istream_iterator<std::string> begin(istr); std::istream_iterator<std::string> end; std::vector<std::string> vstrings(begin, end); std::size_t found; auto it = vstrings.begin(); while (it != vstrings.end()) { if (std::string::npos != (found = it->find("TIMEOUT"))) { std::string timeoutStr = *it; it = vstrings.erase(it); found = timeoutStr.find_first_of('='); if (std::string::npos != found && found < timeoutStr.size()-1) { dpaTask.setTimeout(std::stoi(timeoutStr.substr(++found, timeoutStr.size() - 1))); } else { THROW_EX(std::logic_error, "Parse error: " << NAME_PAR(token, timeoutStr)); } } else if (std::string::npos != (found = it->find("CLID"))) { std::string clientIdStr = *it; it = vstrings.erase(it); found = clientIdStr.find_first_of('='); if (std::string::npos != found && found < clientIdStr.size() - 1) { dpaTask.setClid(clientIdStr.substr(++found, clientIdStr.size() - 1)); } else { THROW_EX(std::logic_error, "Parse error: " << NAME_PAR(token, clientIdStr)); } } else it++; } return vstrings; } void parseRequestSimple(DpaTask & dpaTask, std::vector<std::string>& tokens) { int address = -1; std::string command; if (tokens.size() > 1) { address = std::stoi(tokens[0]); command = tokens[1]; dpaTask.setAddress(address); dpaTask.parseCommand(command); } else { THROW_EX(std::logic_error, "Parse error: " << NAME_PAR(tokensNum, tokens.size())); } } void encodeResponseSimple(const DpaTask & dt, std::ostream& ostr) { ostr << dt.getPrfName() << " " << dt.getAddress() << " " << dt.encodeCommand() << " "; } void encodeTokens(const DpaTask& dpaTask, const std::string& errStr, std::ostream& ostr) { if (dpaTask.getTimeout() >= 0) { ostr << " " << "TIMEOUT=" << dpaTask.getTimeout(); } if (!dpaTask.getClid().empty()) { ostr << " " << "CLID=" << dpaTask.getClid(); } ostr << " " << errStr; } ////////////////////////////////////////// //00 00 06 03 ff ff LedR 0 PULSE //00 00 07 03 ff ff LedG 0 PULSE PrfRawSimple::PrfRawSimple(std::istream& istr) :PrfRaw() { uint8_t bbyte; int val; int i = 0; std::vector<std::string> vstrings = parseTokens(*this, istr); //workaround to handle "." if (vstrings.size() == 1) { std::string dotbuf = vstrings[0]; vstrings.clear(); m_dotNotation = true; std::replace(dotbuf.begin(), dotbuf.end(), '.', ' '); std::istringstream is(dotbuf); vstrings = parseTokens(*this, is); } int sz = (int)vstrings.size(); while (i < MAX_DPA_BUFFER && i < sz) { val = std::stoi(vstrings[i], nullptr, 16); m_request.DpaPacket().Buffer[i] = (uint8_t)val; i++; } m_request.SetLength(i); } std::string PrfRawSimple::encodeResponse(const std::string& errStr) { std::ostringstream ostr; int len = getResponse().Length(); TRC_DBG(PAR(len)); std::ostringstream os; os << iqrf::TracerHexString((unsigned char*)getResponse().DpaPacket().Buffer, len, true); std::string buf = os.str(); if (buf[buf.size() - 1] == ' ') { buf.pop_back(); } if (m_dotNotation) { std::replace(buf.begin(), buf.end(), ' ', '.'); } ostr << getPrfName() << " " << buf; encodeTokens(*this, errStr, ostr); return ostr.str(); } ////////////////////////////////////////// PrfThermometerSimple::PrfThermometerSimple(std::istream& istr) { std::vector<std::string> v = parseTokens(*this, istr); parseRequestSimple(*this, v); } std::string PrfThermometerSimple::encodeResponse(const std::string& errStr) { std::ostringstream ostr; encodeResponseSimple(*this, ostr); ostr << " " << getFloatTemperature(); encodeTokens(*this, errStr, ostr); return ostr.str(); } /////////////////////////////////////////// SimpleSerializer::SimpleSerializer() :m_name("Simple") { init(); } SimpleSerializer::SimpleSerializer(const std::string& name) :m_name(name) { init(); } void SimpleSerializer::init() { m_dpaParser.registerClass<PrfThermometerSimple>(PrfThermometer::PRF_NAME); m_dpaParser.registerClass<PrfLedGSimple>(PrfLedG::PRF_NAME); m_dpaParser.registerClass<PrfLedRSimple>(PrfLedR::PRF_NAME); m_dpaParser.registerClass<PrfRawSimple>(PrfRawSimple::PRF_NAME); } std::string SimpleSerializer::parseCategory(const std::string& request) { std::istringstream istr(request); std::string category; istr >> category; if (category == CAT_CONF_STR) { return CAT_CONF_STR; } else return CAT_DPA_STR; } std::unique_ptr<DpaTask> SimpleSerializer::parseRequest(const std::string& request) { std::unique_ptr<DpaTask> obj; try { std::istringstream istr(request); std::string perif; istr >> perif; obj = m_dpaParser.createObject(perif, istr); m_lastError = "OK"; } catch (std::exception &e) { m_lastError = e.what(); } return std::move(obj); } std::string SimpleSerializer::parseConfig(const std::string& request) { std::string cmd = "unknown"; std::istringstream istr(request); std::string category; istr >> category >> cmd; if (category == CAT_CONF_STR) { m_lastError = "OK"; return cmd; } else { std::ostringstream ostr; ostr << "Unexpected: " << PAR(category); m_lastError = ostr.str(); return ""; } } std::string SimpleSerializer::getLastError() const { return m_lastError; } <commit_msg>Fixed error based on iqrfapp gets stuck #38<commit_after>/** * Copyright 2016-2017 MICRORISC s.r.o. * * 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 "LaunchUtils.h" #include "SimpleSerializer.h" #include "IqrfLogging.h" #include <vector> #include <iterator> #include <array> INIT_COMPONENT(ISerializer, SimpleSerializer) std::vector<std::string> parseTokens(DpaTask& dpaTask, std::istream& istr) { std::istream_iterator<std::string> begin(istr); std::istream_iterator<std::string> end; std::vector<std::string> vstrings(begin, end); std::size_t found; auto it = vstrings.begin(); while (it != vstrings.end()) { if (std::string::npos != (found = it->find("TIMEOUT"))) { std::string timeoutStr = *it; it = vstrings.erase(it); found = timeoutStr.find_first_of('='); if (std::string::npos != found && found < timeoutStr.size()-1) { dpaTask.setTimeout(std::stoi(timeoutStr.substr(++found, timeoutStr.size() - 1))); } else { THROW_EX(std::logic_error, "Parse error: " << NAME_PAR(token, timeoutStr)); } } else if (std::string::npos != (found = it->find("CLID"))) { std::string clientIdStr = *it; it = vstrings.erase(it); found = clientIdStr.find_first_of('='); if (std::string::npos != found && found < clientIdStr.size() - 1) { dpaTask.setClid(clientIdStr.substr(++found, clientIdStr.size() - 1)); } else { THROW_EX(std::logic_error, "Parse error: " << NAME_PAR(token, clientIdStr)); } } else it++; } return vstrings; } void parseRequestSimple(DpaTask & dpaTask, std::vector<std::string>& tokens) { int address = -1; std::string command; if (tokens.size() > 1) { address = std::stoi(tokens[0]); command = tokens[1]; dpaTask.setAddress(address); dpaTask.parseCommand(command); } else { THROW_EX(std::logic_error, "Parse error: " << NAME_PAR(tokensNum, tokens.size())); } } void encodeResponseSimple(const DpaTask & dt, std::ostream& ostr) { ostr << dt.getPrfName() << " " << dt.getAddress() << " " << dt.encodeCommand() << " "; } void encodeTokens(const DpaTask& dpaTask, const std::string& errStr, std::ostream& ostr) { if (dpaTask.getTimeout() >= 0) { ostr << " " << "TIMEOUT=" << dpaTask.getTimeout(); } if (!dpaTask.getClid().empty()) { ostr << " " << "CLID=" << dpaTask.getClid(); } ostr << " " << errStr; } ////////////////////////////////////////// //00 00 06 03 ff ff LedR 0 PULSE //00 00 07 03 ff ff LedG 0 PULSE PrfRawSimple::PrfRawSimple(std::istream& istr) :PrfRaw() { uint8_t bbyte; int val; int i = 0; std::vector<std::string> vstrings = parseTokens(*this, istr); //workaround to handle "." if (vstrings.size() == 1) { std::string dotbuf = vstrings[0]; vstrings.clear(); m_dotNotation = true; std::replace(dotbuf.begin(), dotbuf.end(), '.', ' '); std::istringstream is(dotbuf); vstrings = parseTokens(*this, is); } int sz = (int)vstrings.size(); while (i < MAX_DPA_BUFFER && i < sz) { val = std::stoi(vstrings[i], nullptr, 16); m_request.DpaPacket().Buffer[i] = (uint8_t)val; i++; } m_request.SetLength(i); } std::string PrfRawSimple::encodeResponse(const std::string& errStr) { std::ostringstream ostr; int len = getResponse().Length(); TRC_DBG(PAR(len)); std::ostringstream os; os << iqrf::TracerHexString((unsigned char*)getResponse().DpaPacket().Buffer, len, true); std::string buf = os.str(); if (buf.size() > 0 && buf[buf.size() - 1] == ' ') { buf.pop_back(); } if (m_dotNotation) { std::replace(buf.begin(), buf.end(), ' ', '.'); } ostr << getPrfName() << " " << buf; encodeTokens(*this, errStr, ostr); return ostr.str(); } ////////////////////////////////////////// PrfThermometerSimple::PrfThermometerSimple(std::istream& istr) { std::vector<std::string> v = parseTokens(*this, istr); parseRequestSimple(*this, v); } std::string PrfThermometerSimple::encodeResponse(const std::string& errStr) { std::ostringstream ostr; encodeResponseSimple(*this, ostr); ostr << " " << getFloatTemperature(); encodeTokens(*this, errStr, ostr); return ostr.str(); } /////////////////////////////////////////// SimpleSerializer::SimpleSerializer() :m_name("Simple") { init(); } SimpleSerializer::SimpleSerializer(const std::string& name) :m_name(name) { init(); } void SimpleSerializer::init() { m_dpaParser.registerClass<PrfThermometerSimple>(PrfThermometer::PRF_NAME); m_dpaParser.registerClass<PrfLedGSimple>(PrfLedG::PRF_NAME); m_dpaParser.registerClass<PrfLedRSimple>(PrfLedR::PRF_NAME); m_dpaParser.registerClass<PrfRawSimple>(PrfRawSimple::PRF_NAME); } std::string SimpleSerializer::parseCategory(const std::string& request) { std::istringstream istr(request); std::string category; istr >> category; if (category == CAT_CONF_STR) { return CAT_CONF_STR; } else return CAT_DPA_STR; } std::unique_ptr<DpaTask> SimpleSerializer::parseRequest(const std::string& request) { std::unique_ptr<DpaTask> obj; try { std::istringstream istr(request); std::string perif; istr >> perif; obj = m_dpaParser.createObject(perif, istr); m_lastError = "OK"; } catch (std::exception &e) { m_lastError = e.what(); } return std::move(obj); } std::string SimpleSerializer::parseConfig(const std::string& request) { std::string cmd = "unknown"; std::istringstream istr(request); std::string category; istr >> category >> cmd; if (category == CAT_CONF_STR) { m_lastError = "OK"; return cmd; } else { std::ostringstream ostr; ostr << "Unexpected: " << PAR(category); m_lastError = ostr.str(); return ""; } } std::string SimpleSerializer::getLastError() const { return m_lastError; } <|endoftext|>
<commit_before>#include <libdariadb/compression/compression.h> #include <libdariadb/compression/delta.h> #include <libdariadb/compression/flag.h> #include <libdariadb/compression/xor.h> #include <benchmark/benchmark_api.h> class Compression : public benchmark::Fixture { virtual void SetUp(const ::benchmark::State &st) { auto test_buffer_size = 1024 * 1024 * 100; buffer = new uint8_t[test_buffer_size]; std::fill_n(buffer, test_buffer_size, uint8_t()); size = test_buffer_size; } virtual void TearDown(const ::benchmark::State &) { delete[] buffer; size = 0; } public: uint8_t *buffer; size_t size; }; BENCHMARK_DEFINE_F(Compression, Delta)(benchmark::State &state) { dariadb::compression::Range rng{buffer, buffer + size}; auto bw = std::make_shared<dariadb::compression::ByteBuffer>(rng); dariadb::compression::DeltaCompressor dc(bw); std::vector<dariadb::Time> deltas{50, 2553, 1000, 524277, 500}; dariadb::Time t = 0; size_t runs = 0; while (state.KeepRunning()) { for (int i = 0; i < state.range(0); i++) { dc.append(t); t += deltas[i % deltas.size()]; if (t > dariadb::MAX_TIME) { t = 0; } } runs++; } auto w = dc.used_space(); auto sz = sizeof(dariadb::Time) * state.range(0); state.counters["used space"] = ((w * 100.0) / (sz)) / runs; } BENCHMARK_DEFINE_F(Compression, Xor)(benchmark::State &state) { dariadb::compression::Range rng{buffer, buffer + size}; auto bw = std::make_shared<dariadb::compression::ByteBuffer>(rng); dariadb::compression::XorCompressor dc(bw); size_t runs = 0; dariadb::Value t = 3.14; while (state.KeepRunning()) { for (int i = 0; i < state.range(0); i++) { dc.append(t); t *= 1.5; } runs++; } auto w = dc.used_space(); auto sz = sizeof(dariadb::Value) * state.range(0); state.counters["used space"] = ((w * 100.0) / (sz)) / runs; } BENCHMARK_DEFINE_F(Compression, Flag)(benchmark::State &state) { dariadb::compression::Range rng{buffer, buffer + size}; auto bw = std::make_shared<dariadb::compression::ByteBuffer>(rng); dariadb::compression::XorCompressor dc(bw); size_t runs = 0; dariadb::Flag t = 1; while (state.KeepRunning()) { for (int i = 0; i < state.range(0) / 2; i++) { if (!dc.append(t)) { break; } if (!dc.append(t)) { break; } t++; } runs++; } auto w = dc.used_space(); auto sz = sizeof(dariadb::Flag) * state.range(0); state.counters["used space"] = ((w * 100.0) / (sz)) / runs; } BENCHMARK_DEFINE_F(Compression, Meas)(benchmark::State &state) { dariadb::compression::Range rng{buffer, buffer + size}; auto bw = std::make_shared<dariadb::compression::ByteBuffer>(rng); dariadb::compression::CopmressedWriter cwr{bw}; size_t runs = 0; dariadb::Time t = 0; auto m = dariadb::Meas(); while (state.KeepRunning()) { for (int i = 0; i < state.range(0) / 2; i++) { m.time = t++; m.flag = dariadb::Flag(i); m.value = dariadb::Value(i); if (!cwr.append(m)) { break; } } runs++; } auto w = cwr.usedSpace(); auto sz = sizeof(dariadb::Meas) * state.range(0); state.counters["used space"] = ((w * 100.0) / (sz)) / runs; } BENCHMARK_REGISTER_F(Compression, Delta)->Arg(100)->Arg(10000); BENCHMARK_REGISTER_F(Compression, Xor)->Arg(100)->Arg(10000); BENCHMARK_REGISTER_F(Compression, Flag)->Arg(100)->Arg(10000); BENCHMARK_REGISTER_F(Compression, Meas)->Arg(100)->Arg(10000); <commit_msg>microbenchmark: compression refact.<commit_after>#include <libdariadb/compression/compression.h> #include <libdariadb/compression/delta.h> #include <libdariadb/compression/flag.h> #include <libdariadb/compression/xor.h> #include <benchmark/benchmark_api.h> class Compression : public benchmark::Fixture { virtual void SetUp(const ::benchmark::State &) { buffer = new uint8_t[test_buffer_size]; std::fill_n(buffer, test_buffer_size, uint8_t()); size = test_buffer_size; } virtual void TearDown(const ::benchmark::State &) { delete[] buffer; size = 0; } public: size_t test_buffer_size = 1024 * 1024 * 100; uint8_t *buffer; size_t size; }; BENCHMARK_DEFINE_F(Compression, Delta)(benchmark::State &state) { dariadb::compression::Range rng{buffer, buffer + size}; std::vector<dariadb::Time> deltas{50, 2553, 1000, 524277, 500}; dariadb::Time t = 0; while (state.KeepRunning()) { size_t packed = 0; auto bw = std::make_shared<dariadb::compression::ByteBuffer>(rng); dariadb::compression::DeltaCompressor dc(bw); std::fill_n(buffer, test_buffer_size, uint8_t()); for (int i = 0; i < state.range(0); i++) { if (!dc.append(t)) { break; } packed++; t += deltas[i % deltas.size()]; if (t > dariadb::MAX_TIME) { t = 0; } } auto w = dc.used_space(); auto sz = sizeof(dariadb::Time) * packed; state.counters["used space"] = ((w * 100.0) / (sz)); } } BENCHMARK_DEFINE_F(Compression, Xor)(benchmark::State &state) { dariadb::Value t = 3.14; while (state.KeepRunning()) { size_t packed = 0; dariadb::compression::Range rng{buffer, buffer + size}; auto bw = std::make_shared<dariadb::compression::ByteBuffer>(rng); dariadb::compression::XorCompressor dc(bw); for (int i = 0; i < state.range(0); i++) { if (!dc.append(t)) { break; } t *= 1.5; packed++; } auto w = dc.used_space(); auto sz = sizeof(dariadb::Value) * packed; state.counters["used space"] = ((w * 100.0) / (sz)); } } BENCHMARK_DEFINE_F(Compression, Flag)(benchmark::State &state) { dariadb::Flag t = 1; while (state.KeepRunning()) { dariadb::compression::Range rng{buffer, buffer + size}; auto bw = std::make_shared<dariadb::compression::ByteBuffer>(rng); dariadb::compression::XorCompressor dc(bw); size_t packed = 0; for (int i = 0; i < state.range(0) / 2; i++) { if (!dc.append(t)) { break; } packed++; if (!dc.append(t)) { break; } packed++; t++; } auto w = dc.used_space(); auto sz = sizeof(dariadb::Flag) * packed; state.counters["used space"] = ((w * 100.0) / (sz)); } } BENCHMARK_DEFINE_F(Compression, Meas)(benchmark::State &state) { dariadb::Time t = 0; auto m = dariadb::Meas(); while (state.KeepRunning()) { dariadb::compression::Range rng{buffer, buffer + size}; auto bw = std::make_shared<dariadb::compression::ByteBuffer>(rng); dariadb::compression::CopmressedWriter cwr{bw}; size_t packed = 0; for (int i = 0; i < state.range(0) / 2; i++) { m.time = t++; m.flag = dariadb::Flag(i); m.value = dariadb::Value(i); if (!cwr.append(m)) { break; } packed++; } auto w = cwr.usedSpace(); auto sz = sizeof(dariadb::Meas) * packed; state.counters["used space"] = ((w * 100.0) / (sz)); } } BENCHMARK_REGISTER_F(Compression, Delta)->Arg(100)->Arg(10000); BENCHMARK_REGISTER_F(Compression, Xor)->Arg(100)->Arg(10000); BENCHMARK_REGISTER_F(Compression, Flag)->Arg(100)->Arg(10000); BENCHMARK_REGISTER_F(Compression, Meas)->Arg(100)->Arg(10000); <|endoftext|>
<commit_before> // Includes. #include "UI/NodeItem.h" #include "App/Boundary/NodeProxy.h" // Qt. #include <QPen> #include <QPainter> #include <QString> #include <QFontMetrics> #include <QtGlobal> #include <QGraphicsSceneMouseEvent> #include <QDebug> namespace { // Constants. const int OUTER_MARGIN = 10; // Margin between bounding rect and node box. const int INNER_MARGIN = 10; // Margin between node box and text rect. } NodeItem::NodeItem(const NodeProxy *node) : node_(node) , selected_input_index_(-1) , selected_output_index_(-1) { setFlag(QGraphicsItem::ItemIsMovable, true); setFlag(QGraphicsItem::ItemIsFocusable, true); setFlag(QGraphicsItem::ItemIsSelectable, true); } NodeItem::~NodeItem() { delete node_; } QRectF NodeItem::boundingRect() const { int max_connections = qMax(node_->numInputs(), node_->numOutputs()); qreal height = max_connections * OUTER_MARGIN + (max_connections-1) * OUTER_MARGIN + 4 * OUTER_MARGIN; QFontMetrics metrics(font()); qreal width = metrics.width(QString::fromStdString(node_->name())) + 2 * INNER_MARGIN + 4 * OUTER_MARGIN; return QRectF(-width / 2, -height / 2, width, height); } void NodeItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { drawNodeBox(painter); drawText(painter); drawInputs(painter); drawOutputs(painter); } const std::string &NodeItem::nodeID() const { return node_->id(); } void NodeItem::addDelegate(NodeItem::Delegate *delegate) { if (delegate != nullptr) { delegates_.push_back(delegate); } } void NodeItem::removeDelegate(NodeItem::Delegate *delegate) { std::vector<Delegate*>::iterator to_be_erased_delegate = std::find(delegates_.begin(), delegates_.end(), delegate); delegates_.erase(to_be_erased_delegate); } QPointF NodeItem::inputPos(int index) const { QPainterPath path = pathForInput(index); return mapToScene(path.boundingRect().center()); } QPointF NodeItem::outputPos(int index) const { QPainterPath path = pathForOutput(index); return mapToScene(path.boundingRect().center()); } int NodeItem::indexOfInputUnder(const QPointF &pos) { for (int i = 0; i < node_->numInputs(); ++i) { QPainterPath path = pathForInput(i); if (path.contains(pos)) { return i; } } return -1; } int NodeItem::indexOfOutputUnder(const QPointF &pos) { for (int i = 0; i < node_->numOutputs(); ++i) { QPainterPath path = pathForOutput(i); if (path.contains(pos)) { return i; } } return -1; } void NodeItem::setHighlightInput(int index) { if (index >= 0 && index < node_->numInputs()) { selected_input_index_ = index; } else { selected_input_index_ = -1; } update(boundingRect()); } void NodeItem::setHighlightOutput(int index) { if (index >= 0 && index < node_->numOutputs()) { selected_output_index_ = index; } else { selected_output_index_ = -1; } update(boundingRect()); } void NodeItem::drawNodeBox(QPainter *painter) const { painter->fillRect(nodeBoxRect(), Qt::green); painter->drawRect(nodeBoxRect()); } void NodeItem::drawText(QPainter *painter) const { painter->setFont(font()); painter->drawText(textRect(), Qt::AlignCenter, QString::fromStdString(node_->name())); } void NodeItem::drawInputs(QPainter *painter) const { for (int i = 0; i < node_->numInputs(); ++i) { QPainterPath path = pathForInput(i); painter->fillPath(path, QBrush(selected_input_index_ == i ? Qt::yellow : Qt::red)); painter->drawPath(path); } } void NodeItem::drawOutputs(QPainter *painter) const { for (int i = 0; i < node_->numOutputs(); ++i) { QPainterPath path = pathForOutput(i); painter->fillPath(path, QBrush(selected_output_index_ == i ? Qt::cyan : Qt::blue)); painter->drawPath(path); } } QPainterPath NodeItem::pathForInput(int index) const { qreal start_y = -(node_->numInputs() * OUTER_MARGIN + (node_->numInputs()-1) * OUTER_MARGIN) / 2; qreal x = boundingRect().left(); qreal y = start_y + index * 2 * OUTER_MARGIN; QPainterPath path; path.addPolygon(QPolygonF() << QPointF(x, y) << QPointF(x+OUTER_MARGIN, y + OUTER_MARGIN / 2) << QPointF(x, y + OUTER_MARGIN) ); path.closeSubpath(); return path; } QPainterPath NodeItem::pathForOutput(int index) const { qreal start_y = -(node_->numOutputs() * OUTER_MARGIN + (node_->numOutputs()-1) * OUTER_MARGIN) / 2; qreal x = boundingRect().right() - OUTER_MARGIN / 2; qreal radius = OUTER_MARGIN / 2; qreal y = start_y + (index * 2 * OUTER_MARGIN) + (OUTER_MARGIN / 2); QPainterPath path; path.addEllipse(QPointF(x, y), radius, radius); return path; } QFont NodeItem::font() const { return QFont("Arial"); } QRectF NodeItem::nodeBoxRect() const { QRectF bounding_rect = boundingRect(); return QRectF(bounding_rect.left() + OUTER_MARGIN, bounding_rect.top() + OUTER_MARGIN, bounding_rect.width() - 2 * OUTER_MARGIN, bounding_rect.height() - 2 * OUTER_MARGIN); } QRectF NodeItem::textRect() const { QRectF node_box_rect = nodeBoxRect(); return QRectF(node_box_rect.left() + INNER_MARGIN, node_box_rect.top() + INNER_MARGIN, node_box_rect.width() - 2 * INNER_MARGIN, node_box_rect.height() - 2 * INNER_MARGIN); } void NodeItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { if ( (event->modifiers() & Qt::AltModifier) == 0) { QGraphicsItem::mouseMoveEvent(event); for (size_t j = 0; j < delegates_.size(); ++j) { delegates_[j]->nodeMoved(this); } } } <commit_msg>Remove fill of node item to make item prettier.<commit_after> // Includes. #include "UI/NodeItem.h" #include "App/Boundary/NodeProxy.h" // Qt. #include <QPen> #include <QPainter> #include <QString> #include <QFontMetrics> #include <QtGlobal> #include <QGraphicsSceneMouseEvent> #include <QDebug> namespace { // Constants. const int OUTER_MARGIN = 10; // Margin between bounding rect and node box. const int INNER_MARGIN = 10; // Margin between node box and text rect. } NodeItem::NodeItem(const NodeProxy *node) : node_(node) , selected_input_index_(-1) , selected_output_index_(-1) { setFlag(QGraphicsItem::ItemIsMovable, true); setFlag(QGraphicsItem::ItemIsFocusable, true); setFlag(QGraphicsItem::ItemIsSelectable, true); } NodeItem::~NodeItem() { delete node_; } QRectF NodeItem::boundingRect() const { int max_connections = qMax(node_->numInputs(), node_->numOutputs()); qreal height = max_connections * OUTER_MARGIN + (max_connections-1) * OUTER_MARGIN + 4 * OUTER_MARGIN; QFontMetrics metrics(font()); qreal width = metrics.width(QString::fromStdString(node_->name())) + 2 * INNER_MARGIN + 4 * OUTER_MARGIN; return QRectF(-width / 2, -height / 2, width, height); } void NodeItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { painter->setRenderHint(QPainter::Antialiasing, true); drawNodeBox(painter); drawText(painter); drawInputs(painter); drawOutputs(painter); } const std::string &NodeItem::nodeID() const { return node_->id(); } void NodeItem::addDelegate(NodeItem::Delegate *delegate) { if (delegate != nullptr) { delegates_.push_back(delegate); } } void NodeItem::removeDelegate(NodeItem::Delegate *delegate) { std::vector<Delegate*>::iterator to_be_erased_delegate = std::find(delegates_.begin(), delegates_.end(), delegate); delegates_.erase(to_be_erased_delegate); } QPointF NodeItem::inputPos(int index) const { QPainterPath path = pathForInput(index); return mapToScene(path.boundingRect().center()); } QPointF NodeItem::outputPos(int index) const { QPainterPath path = pathForOutput(index); return mapToScene(path.boundingRect().center()); } int NodeItem::indexOfInputUnder(const QPointF &pos) { for (int i = 0; i < node_->numInputs(); ++i) { QPainterPath path = pathForInput(i); if (path.contains(pos)) { return i; } } return -1; } int NodeItem::indexOfOutputUnder(const QPointF &pos) { for (int i = 0; i < node_->numOutputs(); ++i) { QPainterPath path = pathForOutput(i); if (path.contains(pos)) { return i; } } return -1; } void NodeItem::setHighlightInput(int index) { if (index >= 0 && index < node_->numInputs()) { selected_input_index_ = index; } else { selected_input_index_ = -1; } update(boundingRect()); } void NodeItem::setHighlightOutput(int index) { if (index >= 0 && index < node_->numOutputs()) { selected_output_index_ = index; } else { selected_output_index_ = -1; } update(boundingRect()); } void NodeItem::drawNodeBox(QPainter *painter) const { QPainterPath path; path.addRoundedRect(nodeBoxRect(), 5, 5); painter->drawPath(path); } void NodeItem::drawText(QPainter *painter) const { painter->setFont(font()); painter->drawText(textRect(), Qt::AlignCenter, QString::fromStdString(node_->name())); } void NodeItem::drawInputs(QPainter *painter) const { for (int i = 0; i < node_->numInputs(); ++i) { QPainterPath path = pathForInput(i); painter->drawPath(path); } } void NodeItem::drawOutputs(QPainter *painter) const { for (int i = 0; i < node_->numOutputs(); ++i) { QPainterPath path = pathForOutput(i); painter->drawPath(path); } } QPainterPath NodeItem::pathForInput(int index) const { qreal start_y = -(node_->numInputs() * OUTER_MARGIN + (node_->numInputs()-1) * OUTER_MARGIN) / 2; qreal x = boundingRect().left(); qreal y = start_y + index * 2 * OUTER_MARGIN; QPainterPath path; path.addPolygon(QPolygonF() << QPointF(x, y) << QPointF(x+OUTER_MARGIN, y + OUTER_MARGIN / 2) << QPointF(x, y + OUTER_MARGIN) ); path.closeSubpath(); return path; } QPainterPath NodeItem::pathForOutput(int index) const { qreal start_y = -(node_->numOutputs() * OUTER_MARGIN + (node_->numOutputs()-1) * OUTER_MARGIN) / 2; qreal x = boundingRect().right() - OUTER_MARGIN / 2; qreal radius = OUTER_MARGIN / 2; qreal y = start_y + (index * 2 * OUTER_MARGIN) + (OUTER_MARGIN / 2); QPainterPath path; path.addEllipse(QPointF(x, y), radius, radius); return path; } QFont NodeItem::font() const { return QFont("Arial"); } QRectF NodeItem::nodeBoxRect() const { QRectF bounding_rect = boundingRect(); return QRectF(bounding_rect.left() + OUTER_MARGIN, bounding_rect.top() + OUTER_MARGIN, bounding_rect.width() - 2 * OUTER_MARGIN, bounding_rect.height() - 2 * OUTER_MARGIN); } QRectF NodeItem::textRect() const { QRectF node_box_rect = nodeBoxRect(); return QRectF(node_box_rect.left() + INNER_MARGIN, node_box_rect.top() + INNER_MARGIN, node_box_rect.width() - 2 * INNER_MARGIN, node_box_rect.height() - 2 * INNER_MARGIN); } void NodeItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { if ( (event->modifiers() & Qt::AltModifier) == 0) { QGraphicsItem::mouseMoveEvent(event); for (size_t j = 0; j < delegates_.size(); ++j) { delegates_[j]->nodeMoved(this); } } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: processinginstruction.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2004-11-16 12:26:31 $ * * 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: 2004 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "processinginstruction.hxx" namespace DOM { CProcessingInstruction::CProcessingInstruction(const xmlNodePtr aNodePtr) { m_aNodeType = NodeType_PROCESSING_INSTRUCTION_NODE; init_node(aNodePtr); } /** The content of this processing instruction. */ OUString SAL_CALL CProcessingInstruction::getData() throw (RuntimeException) { // XXX return OUString(); } /** The target of this processing instruction. */ OUString SAL_CALL CProcessingInstruction::getTarget() throw (RuntimeException) { // XXX return OUString(); } /** The content of this processing instruction. */ void SAL_CALL CProcessingInstruction::setData(const OUString& data) throw (DOMException) { // XXX } OUString SAL_CALL CProcessingInstruction::getNodeName()throw (RuntimeException) { OUString aName; if (m_aNodePtr != NULL) { const xmlChar* xName = m_aNodePtr->name; aName = OUString((sal_Char*)xName, strlen((char*)xName), RTL_TEXTENCODING_UTF8); } return aName; } OUString SAL_CALL CProcessingInstruction::getNodeValue() throw (RuntimeException) { return getData(); } } <commit_msg>INTEGRATION: CWS ooo19126 (1.4.12); FILE MERGED 2005/09/05 17:20:01 rt 1.4.12.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: processinginstruction.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-09 10:04:54 $ * * 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 "processinginstruction.hxx" namespace DOM { CProcessingInstruction::CProcessingInstruction(const xmlNodePtr aNodePtr) { m_aNodeType = NodeType_PROCESSING_INSTRUCTION_NODE; init_node(aNodePtr); } /** The content of this processing instruction. */ OUString SAL_CALL CProcessingInstruction::getData() throw (RuntimeException) { // XXX return OUString(); } /** The target of this processing instruction. */ OUString SAL_CALL CProcessingInstruction::getTarget() throw (RuntimeException) { // XXX return OUString(); } /** The content of this processing instruction. */ void SAL_CALL CProcessingInstruction::setData(const OUString& data) throw (DOMException) { // XXX } OUString SAL_CALL CProcessingInstruction::getNodeName()throw (RuntimeException) { OUString aName; if (m_aNodePtr != NULL) { const xmlChar* xName = m_aNodePtr->name; aName = OUString((sal_Char*)xName, strlen((char*)xName), RTL_TEXTENCODING_UTF8); } return aName; } OUString SAL_CALL CProcessingInstruction::getNodeValue() throw (RuntimeException) { return getData(); } } <|endoftext|>
<commit_before>// ***************************************************************************** // // Copyright (c) 2015, Southwest Research Institute® (SwRI®) // 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 Southwest Research Institute® (SwRI®) 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 Southwest Research Institute® 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 <swri_profiler_tools/profile.h> #include <algorithm> #include <QStringList> #include <QDebug> namespace swri_profiler_tools { Profile::Profile() : db_handle_(-1), min_time_s_(0), max_time_s_(0) { } Profile::~Profile() { } void Profile::initialize(int db_handle, const QString &name) { if (isValid()) { qWarning("Re-initializing a valid profile (%d,%s) with (%d,%s). " "Something is probably horribly wrong.", db_handle_, qPrintable(name_), db_handle, qPrintable(name)); } db_handle_ = db_handle; name_ = name; } void Profile::addData(const NewProfileDataVector &data) { if (db_handle_ < 0) { qWarning("Attempt to add %zu elements to an invalid profile.", data.size()); return; } if (data.size() == 0) { return; } uint64_t earliest_sec = data.front().wall_stamp_sec; bool blocks_added = false; for (auto const &item : data) { expandTimeline(item.wall_stamp_sec); blocks_added |= touchBlock(item.label); size_t index = indexFromSec(item.wall_stamp_sec); ProfileBlock &block = blocks_[item.label]; block.data[index].valid = true; block.data[index].measured = true; block.data[index].cumulative_call_count = item.cumulative_call_count; block.data[index].cumulative_inclusive_duration_ns = item.cumulative_inclusive_duration_ns; block.data[index].incremental_inclusive_duration_ns = item.incremental_inclusive_duration_ns; block.data[index].incremental_max_duration_ns = item.incremental_max_duration_ns; earliest_sec = std::min(earliest_sec, item.wall_stamp_sec); } if (blocks_added) { rebuildIndices(); Q_EMIT blocksAdded(db_handle_); } updateDerivedData(indexFromSec(earliest_sec)); Q_EMIT dataAdded(db_handle_); } void Profile::expandTimeline(const uint64_t sec) { if (sec >= min_time_s_ && sec < max_time_s_) { // This time is already in our timeline, so ignore it. } else if (min_time_s_ == max_time_s_) { // The timeline is empty min_time_s_ = sec; max_time_s_ = sec+1; addDataToAllBlocks(true, 1); } else if (sec >= max_time_s_) { // New data extends the back of the timeline. size_t new_elements = sec - max_time_s_ + 1; max_time_s_ = sec+1; addDataToAllBlocks(true, new_elements); } else { // New data must be at the front of the timeline. size_t new_elements = min_time_s_ - sec; min_time_s_ = sec; addDataToAllBlocks(false, new_elements); } } void Profile::addDataToAllBlocks(const bool back, const size_t count) { if (back) { for (auto &it : blocks_) { std::deque<ProfileEntry> &data = it.second.data; data.insert(data.end(), count, ProfileEntry()); } } else { for (auto &it : blocks_) { std::deque<ProfileEntry> &data = it.second.data; data.insert(data.begin(), count, ProfileEntry()); } } } bool Profile::touchBlock(const QString &path) { if (blocks_.count(path)) { return false; } QStringList all_parts = path.split('/'); if (all_parts.isEmpty()) { qWarning("Path block does not have a root component? '%s'", qPrintable(path)); return false; } int depth = 0; QString this_path = all_parts.takeFirst(); if (!blocks_.count(this_path)) { addBlock(this_path, this_path, depth); } while (!all_parts.isEmpty()) { QString this_name = all_parts.takeFirst(); depth++; this_path = this_path + "/" + this_name; if (!blocks_.count(this_path)) { addBlock(this_path, this_name, depth); } } return true; } void Profile::addBlock(const QString &path, const QString &name, int depth) { ProfileBlock &block = blocks_[path]; block.name = name; block.path = path; block.depth = depth; block.data.resize(max_time_s_ - min_time_s_); } void Profile::rebuildIndices() { rebuildFlatIndex(); rebuildTreeIndex(); } void Profile::rebuildFlatIndex() { QStringList index; for (auto const &it : blocks_) { index.append(it.first); } index.sort(); flat_index_ = index; } // Compares the first N items of two string lists. static bool compareInitialStringList( const QStringList &list1, const QStringList &list2) { int size = std::min(list1.size(), list2.size()); if (size == 0) { return true; } // Comparing in reverse because, in our use case, the differences // are more likely to be at the end of the lists. for (int i = size; i > 0; i--) { if (list1[i-1] != list2[i-1]) { return false; } } return true; } // static void printTree(ProfileTreeNode *node, const QString &prefix) // { // qWarning(qPrintable(prefix + node->name)); // for (size_t i = 0; i < node->child_nodes.size(); i++) { // printTree(&(node->child_nodes[i]), prefix + " "); // } // } void Profile::rebuildTreeIndex() { tree_root_.path = ""; tree_root_.parent_node = NULL; tree_root_.child_nodes.clear(); ProfileTreeNode *current = &tree_root_; QStringList stack; stack.push_back(""); for (int i = 0; i < flat_index_.size(); i++) { qDebug() << i << ": " << flat_index_[i]; } // Start at 1 because the first key is the root node. for (int i = 1; i < flat_index_.size(); i++) { QStringList parts = flat_index_[i].split('/'); while (stack.size() > 1 && !compareInitialStringList(stack, parts)) { stack.pop_back(); current = current->parent_node; } while (stack.size() < parts.size()) { QString name = parts[stack.size()]; stack.push_back(name); QString path = stack.join("/") + "/" + name; current->child_nodes.emplace_back(); ProfileTreeNode *new_node = &(current->child_nodes.back()); new_node->name = name; new_node->path = path; new_node->parent_node = current; current = new_node; } } } size_t Profile::findLastValidIndex(const ProfileBlock& block, size_t index) { while (index > 0 && !block.data[index].valid) { index--; } return index; } void Profile::updateDerivedData(size_t index) { updateDerivedDataInternal(&tree_root_, index); } void Profile::updateDerivedDataInternal(ProfileTreeNode *node, size_t index) { uint64_t children_cum_call_count = 0; uint64_t children_cum_incl_duration = 0; uint64_t children_inc_incl_duration = 0; uint64_t children_inc_max_duration = 0; for (auto &child : node->child_nodes) { updateDerivedDataInternal(&child, index); ProfileBlock &block = blocks_[child.path]; int valid_index = findLastValidIndex(block, index); ProfileEntry &data = block.data[valid_index]; children_cum_call_count += data.cumulative_call_count; children_cum_incl_duration += data.cumulative_inclusive_duration_ns; children_inc_incl_duration += data.incremental_inclusive_duration_ns; children_inc_max_duration = std::max(children_inc_max_duration, data.incremental_max_duration_ns); } auto& data = blocks_[node->path].data[index]; if (!data.measured) { data.valid = true; data.cumulative_call_count = children_cum_call_count; data.cumulative_inclusive_duration_ns = children_cum_incl_duration; data.incremental_inclusive_duration_ns = children_inc_incl_duration; data.incremental_max_duration_ns = children_inc_max_duration; } data.cumulative_exclusive_duration_ns = data.cumulative_inclusive_duration_ns - children_cum_incl_duration; data.incremental_exclusive_duration_ns = data.incremental_inclusive_duration_ns - children_inc_incl_duration; } } // namespace swri_profiler_tools <commit_msg>Update derived data for all modified times instead of one.<commit_after>// ***************************************************************************** // // Copyright (c) 2015, Southwest Research Institute® (SwRI®) // 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 Southwest Research Institute® (SwRI®) 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 Southwest Research Institute® 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 <swri_profiler_tools/profile.h> #include <algorithm> #include <set> #include <QStringList> #include <QDebug> namespace swri_profiler_tools { Profile::Profile() : db_handle_(-1), min_time_s_(0), max_time_s_(0) { } Profile::~Profile() { } void Profile::initialize(int db_handle, const QString &name) { if (isValid()) { qWarning("Re-initializing a valid profile (%d,%s) with (%d,%s). " "Something is probably horribly wrong.", db_handle_, qPrintable(name_), db_handle, qPrintable(name)); } db_handle_ = db_handle; name_ = name; } void Profile::addData(const NewProfileDataVector &data) { if (db_handle_ < 0) { qWarning("Attempt to add %zu elements to an invalid profile.", data.size()); return; } if (data.size() == 0) { return; } std::set<uint64_t> modified_times; bool blocks_added = false; for (auto const &item : data) { expandTimeline(item.wall_stamp_sec); blocks_added |= touchBlock(item.label); size_t index = indexFromSec(item.wall_stamp_sec); ProfileBlock &block = blocks_[item.label]; block.data[index].valid = true; block.data[index].measured = true; block.data[index].cumulative_call_count = item.cumulative_call_count; block.data[index].cumulative_inclusive_duration_ns = item.cumulative_inclusive_duration_ns; block.data[index].incremental_inclusive_duration_ns = item.incremental_inclusive_duration_ns; block.data[index].incremental_max_duration_ns = item.incremental_max_duration_ns; modified_times.insert(item.wall_stamp_sec); } if (blocks_added) { rebuildIndices(); Q_EMIT blocksAdded(db_handle_); } for (auto const &t : modified_times) { updateDerivedData(indexFromSec(t)); } Q_EMIT dataAdded(db_handle_); } void Profile::expandTimeline(const uint64_t sec) { if (sec >= min_time_s_ && sec < max_time_s_) { // This time is already in our timeline, so ignore it. } else if (min_time_s_ == max_time_s_) { // The timeline is empty min_time_s_ = sec; max_time_s_ = sec+1; addDataToAllBlocks(true, 1); } else if (sec >= max_time_s_) { // New data extends the back of the timeline. size_t new_elements = sec - max_time_s_ + 1; max_time_s_ = sec+1; addDataToAllBlocks(true, new_elements); } else { // New data must be at the front of the timeline. size_t new_elements = min_time_s_ - sec; min_time_s_ = sec; addDataToAllBlocks(false, new_elements); } } void Profile::addDataToAllBlocks(const bool back, const size_t count) { if (back) { for (auto &it : blocks_) { std::deque<ProfileEntry> &data = it.second.data; data.insert(data.end(), count, ProfileEntry()); } } else { for (auto &it : blocks_) { std::deque<ProfileEntry> &data = it.second.data; data.insert(data.begin(), count, ProfileEntry()); } } } bool Profile::touchBlock(const QString &path) { if (blocks_.count(path)) { return false; } QStringList all_parts = path.split('/'); if (all_parts.isEmpty()) { qWarning("Path block does not have a root component? '%s'", qPrintable(path)); return false; } int depth = 0; QString this_path = all_parts.takeFirst(); if (!blocks_.count(this_path)) { addBlock(this_path, this_path, depth); } while (!all_parts.isEmpty()) { QString this_name = all_parts.takeFirst(); depth++; this_path = this_path + "/" + this_name; if (!blocks_.count(this_path)) { addBlock(this_path, this_name, depth); } } return true; } void Profile::addBlock(const QString &path, const QString &name, int depth) { ProfileBlock &block = blocks_[path]; block.name = name; block.path = path; block.depth = depth; block.data.resize(max_time_s_ - min_time_s_); } void Profile::rebuildIndices() { rebuildFlatIndex(); rebuildTreeIndex(); } void Profile::rebuildFlatIndex() { QStringList index; for (auto const &it : blocks_) { index.append(it.first); } index.sort(); flat_index_ = index; } // Compares the first N items of two string lists. static bool compareInitialStringList( const QStringList &list1, const QStringList &list2) { int size = std::min(list1.size(), list2.size()); if (size == 0) { return true; } // Comparing in reverse because, in our use case, the differences // are more likely to be at the end of the lists. for (int i = size; i > 0; i--) { if (list1[i-1] != list2[i-1]) { return false; } } return true; } // static void printTree(ProfileTreeNode *node, const QString &prefix) // { // qWarning(qPrintable(prefix + node->name)); // for (size_t i = 0; i < node->child_nodes.size(); i++) { // printTree(&(node->child_nodes[i]), prefix + " "); // } // } void Profile::rebuildTreeIndex() { tree_root_.path = ""; tree_root_.parent_node = NULL; tree_root_.child_nodes.clear(); ProfileTreeNode *current = &tree_root_; QStringList stack; stack.push_back(""); for (int i = 0; i < flat_index_.size(); i++) { qDebug() << i << ": " << flat_index_[i]; } // Start at 1 because the first key is the root node. for (int i = 1; i < flat_index_.size(); i++) { QStringList parts = flat_index_[i].split('/'); while (stack.size() > 1 && !compareInitialStringList(stack, parts)) { stack.pop_back(); current = current->parent_node; } while (stack.size() < parts.size()) { QString name = parts[stack.size()]; stack.push_back(name); QString path = stack.join("/") + "/" + name; current->child_nodes.emplace_back(); ProfileTreeNode *new_node = &(current->child_nodes.back()); new_node->name = name; new_node->path = path; new_node->parent_node = current; current = new_node; } } } size_t Profile::findLastValidIndex(const ProfileBlock& block, size_t index) { while (index > 0 && !block.data[index].valid) { index--; } return index; } void Profile::updateDerivedData(size_t index) { updateDerivedDataInternal(&tree_root_, index); } void Profile::updateDerivedDataInternal(ProfileTreeNode *node, size_t index) { uint64_t children_cum_call_count = 0; uint64_t children_cum_incl_duration = 0; uint64_t children_inc_incl_duration = 0; uint64_t children_inc_max_duration = 0; for (auto &child : node->child_nodes) { updateDerivedDataInternal(&child, index); ProfileBlock &block = blocks_[child.path]; int valid_index = findLastValidIndex(block, index); ProfileEntry &data = block.data[valid_index]; children_cum_call_count += data.cumulative_call_count; children_cum_incl_duration += data.cumulative_inclusive_duration_ns; children_inc_incl_duration += data.incremental_inclusive_duration_ns; children_inc_max_duration = std::max(children_inc_max_duration, data.incremental_max_duration_ns); } auto& data = blocks_[node->path].data[index]; if (!data.measured) { data.valid = true; data.cumulative_call_count = children_cum_call_count; data.cumulative_inclusive_duration_ns = children_cum_incl_duration; data.incremental_inclusive_duration_ns = children_inc_incl_duration; data.incremental_max_duration_ns = children_inc_max_duration; } data.cumulative_exclusive_duration_ns = data.cumulative_inclusive_duration_ns - children_cum_incl_duration; data.incremental_exclusive_duration_ns = data.incremental_inclusive_duration_ns - children_inc_incl_duration; } } // namespace swri_profiler_tools <|endoftext|>
<commit_before>// RUN: %clang_cc1 -fsyntax-only -verify %s // RUN: %clang_cc1 -fsyntax-only -verify -std=c++98 %s // RUN: %clang_cc1 -fsyntax-only -verify -std=c++11 %s struct A {}; enum B { Dummy }; namespace C {} struct D : A {}; struct E : A {}; struct F : D, E {}; struct G : virtual D {}; class H : A {}; // expected-note 2{{implicitly declared private here}} int A::*pdi1; int (::A::*pdi2); int (A::*pfi)(int); void (*A::*ppfie)() throw(); // expected-error {{exception specifications are not allowed beyond a single level of indirection}} int B::*pbi; #if __cplusplus <= 199711L // C++03 or earlier modes // expected-warning@-2 {{use of enumeration in a nested name specifier is a C++11 extension}} #endif // expected-error@-4 {{'pbi' does not point into a class}} int C::*pci; // expected-error {{'pci' does not point into a class}} void A::*pdv; // expected-error {{'pdv' declared as a member pointer to void}} int& A::*pdr; // expected-error {{'pdr' declared as a member pointer to a reference}} void f() { // This requires tentative parsing. int (A::*pf)(int, int); // Implicit conversion to bool. bool b = pdi1; b = pfi; // Conversion from null pointer constant. pf = 0; pf = __null; // Conversion to member of derived. int D::*pdid = pdi1; pdid = pdi2; // Fail conversion due to ambiguity and virtuality. int F::*pdif = pdi1; // expected-error {{ambiguous conversion from pointer to member of base class 'A' to pointer to member of derived class 'F':}} int G::*pdig = pdi1; // expected-error {{conversion from pointer to member of class 'A' to pointer to member of class 'G' via virtual base 'D' is not allowed}} // Conversion to member of base. pdi1 = pdid; // expected-error {{assigning to 'int A::*' from incompatible type 'int D::*'}} // Comparisons int (A::*pf2)(int, int); int (D::*pf3)(int, int) = 0; bool b1 = (pf == pf2); (void)b1; bool b2 = (pf != pf2); (void)b2; bool b3 = (pf == pf3); (void)b3; bool b4 = (pf != 0); (void)b4; } struct TheBase { void d(); }; struct HasMembers : TheBase { int i; void f(); void g(); void g(int); static void g(double); }; namespace Fake { int i; void f(); } void g() { HasMembers hm; int HasMembers::*pmi = &HasMembers::i; int *pni = &Fake::i; int *pmii = &hm.i; void (HasMembers::*pmf)() = &HasMembers::f; void (*pnf)() = &Fake::f; &hm.f; // expected-error {{cannot create a non-constant pointer to member function}} void (HasMembers::*pmgv)() = &HasMembers::g; void (HasMembers::*pmgi)(int) = &HasMembers::g; void (*pmgd)(double) = &HasMembers::g; void (HasMembers::*pmd)() = &HasMembers::d; } struct Incomplete; void h() { HasMembers hm, *phm = &hm; int HasMembers::*pi = &HasMembers::i; hm.*pi = 0; int i = phm->*pi; (void)&(hm.*pi); (void)&(phm->*pi); (void)&((&hm)->*pi); void (HasMembers::*pf)() = &HasMembers::f; (hm.*pf)(); (phm->*pf)(); (void)(hm->*pi); // expected-error {{left hand operand to ->* must be a pointer to class compatible with the right hand operand, but is 'HasMembers'}} (void)(phm.*pi); // expected-error {{left hand operand to .* must be a class compatible with the right hand operand, but is 'HasMembers *'}} (void)(i.*pi); // expected-error {{left hand operand to .* must be a class compatible with the right hand operand, but is 'int'}} int *ptr; (void)(ptr->*pi); // expected-error {{left hand operand to ->* must be a pointer to class compatible with the right hand operand, but is 'int *'}} int A::*pai = 0; D d, *pd = &d; (void)(d.*pai); (void)(pd->*pai); F f, *ptrf = &f; (void)(f.*pai); // expected-error {{ambiguous conversion from derived class 'F' to base class 'A'}} (void)(ptrf->*pai); // expected-error {{ambiguous conversion from derived class 'F' to base class 'A'}} H h, *ptrh = &h; (void)(h.*pai); // expected-error {{cannot cast 'H' to its private base class 'A'}} (void)(ptrh->*pai); // expected-error {{cannot cast 'H' to its private base class 'A'}} (void)(hm.*i); // expected-error {{pointer-to-member}} (void)(phm->*i); // expected-error {{pointer-to-member}} // Okay Incomplete *inc; int Incomplete::*pii = 0; (void)(inc->*pii); } struct OverloadsPtrMem { int operator ->*(const char *); }; void i() { OverloadsPtrMem m; int foo = m->*"Awesome!"; } namespace pr5985 { struct c { void h(); void f() { void (c::*p)(); p = &h; // expected-error {{must explicitly qualify}} p = &this->h; // expected-error {{cannot create a non-constant pointer to member function}} p = &(*this).h; // expected-error {{cannot create a non-constant pointer to member function}} } }; } namespace pr6783 { struct Base {}; struct X; // expected-note {{forward declaration}} int test1(int Base::* p2m, X* object) { return object->*p2m; // expected-error {{left hand operand to ->*}} } } namespace PR7176 { namespace base { struct Process { }; struct Continuous : Process { bool cond(); }; } typedef bool( base::Process::*Condition )(); void m() { (void)(Condition) &base::Continuous::cond; } } namespace rdar8358512 { // We can't call this with an overload set because we're not allowed // to look into overload sets unless the parameter has some kind of // function type. template <class F> void bind(F f); // expected-note 12 {{candidate template ignored}} template <class F, class T> void bindmem(F (T::*f)()); // expected-note 4 {{candidate template ignored}} template <class F> void bindfn(F (*f)()); // expected-note 4 {{candidate template ignored}} struct A { void nonstat(); void nonstat(int); void mixed(); static void mixed(int); static void stat(); static void stat(int); template <typename T> struct Test0 { void test() { bind(&nonstat); // expected-error {{no matching function for call}} bind(&A::nonstat); // expected-error {{no matching function for call}} bind(&mixed); // expected-error {{no matching function for call}} bind(&A::mixed); // expected-error {{no matching function for call}} bind(&stat); // expected-error {{no matching function for call}} bind(&A::stat); // expected-error {{no matching function for call}} } }; template <typename T> struct Test1 { void test() { bindmem(&nonstat); // expected-error {{no matching function for call}} bindmem(&A::nonstat); bindmem(&mixed); // expected-error {{no matching function for call}} bindmem(&A::mixed); bindmem(&stat); // expected-error {{no matching function for call}} bindmem(&A::stat); // expected-error {{no matching function for call}} } }; template <typename T> struct Test2 { void test() { bindfn(&nonstat); // expected-error {{no matching function for call}} bindfn(&A::nonstat); // expected-error {{no matching function for call}} bindfn(&mixed); // expected-error {{no matching function for call}} bindfn(&A::mixed); // expected-error {{no matching function for call}} bindfn(&stat); bindfn(&A::stat); } }; }; template <class T> class B { void nonstat(); void nonstat(int); void mixed(); static void mixed(int); static void stat(); static void stat(int); // None of these can be diagnosed yet, because the arguments are // still dependent. void test0a() { bind(&nonstat); bind(&B::nonstat); bind(&mixed); bind(&B::mixed); bind(&stat); bind(&B::stat); } void test0b() { bind(&nonstat); // expected-error {{no matching function for call}} bind(&B::nonstat); // expected-error {{no matching function for call}} bind(&mixed); // expected-error {{no matching function for call}} bind(&B::mixed); // expected-error {{no matching function for call}} bind(&stat); // expected-error {{no matching function for call}} bind(&B::stat); // expected-error {{no matching function for call}} } }; template void B<int>::test0b(); // expected-note {{in instantiation}} } namespace PR9973 { template<class R, class T> struct dm { typedef R T::*F; F f_; template<class U> int & call(U u) { return u->*f_; } // expected-error{{reference to non-static member function must be called; did you mean to call it with no arguments?}} expected-error {{non-const lvalue reference to type 'int' cannot bind to a temporary of type 'int'}} template<class U> int operator()(U u) { call(u); } // expected-note{{in instantiation of}} }; template<class R, class T> dm<R, T> mem_fn(R T::*) ; struct test { int nullary_v(); }; void f() { test* t; mem_fn(&test::nullary_v)(t); // expected-note{{in instantiation of}} } } namespace test8 { struct A { int foo; }; int test1() { // Verify that we perform (and check) an lvalue conversion on the operands here. return (*((A**) 0)) // expected-warning {{indirection of non-volatile null pointer will be deleted}} expected-note {{consider}} ->**(int A::**) 0; // expected-warning {{indirection of non-volatile null pointer will be deleted}} expected-note {{consider}} } int test2() { // Verify that we perform (and check) an lvalue conversion on the operands here. // TODO: the .* should itself warn about being a dereference of null. return (*((A*) 0)) .**(int A::**) 0; // expected-warning {{indirection of non-volatile null pointer will be deleted}} expected-note {{consider}} } } namespace PR27558 { template<typename Args> struct A { void f(); }; template<typename Args> struct B : A<Args> { using A<Args>::f; B() { (void)&B<Args>::f; } }; B<int> b; } <commit_msg>Revert accidentally-committed test for PR27558 (which currently fails...)<commit_after>// RUN: %clang_cc1 -fsyntax-only -verify %s // RUN: %clang_cc1 -fsyntax-only -verify -std=c++98 %s // RUN: %clang_cc1 -fsyntax-only -verify -std=c++11 %s struct A {}; enum B { Dummy }; namespace C {} struct D : A {}; struct E : A {}; struct F : D, E {}; struct G : virtual D {}; class H : A {}; // expected-note 2{{implicitly declared private here}} int A::*pdi1; int (::A::*pdi2); int (A::*pfi)(int); void (*A::*ppfie)() throw(); // expected-error {{exception specifications are not allowed beyond a single level of indirection}} int B::*pbi; #if __cplusplus <= 199711L // C++03 or earlier modes // expected-warning@-2 {{use of enumeration in a nested name specifier is a C++11 extension}} #endif // expected-error@-4 {{'pbi' does not point into a class}} int C::*pci; // expected-error {{'pci' does not point into a class}} void A::*pdv; // expected-error {{'pdv' declared as a member pointer to void}} int& A::*pdr; // expected-error {{'pdr' declared as a member pointer to a reference}} void f() { // This requires tentative parsing. int (A::*pf)(int, int); // Implicit conversion to bool. bool b = pdi1; b = pfi; // Conversion from null pointer constant. pf = 0; pf = __null; // Conversion to member of derived. int D::*pdid = pdi1; pdid = pdi2; // Fail conversion due to ambiguity and virtuality. int F::*pdif = pdi1; // expected-error {{ambiguous conversion from pointer to member of base class 'A' to pointer to member of derived class 'F':}} int G::*pdig = pdi1; // expected-error {{conversion from pointer to member of class 'A' to pointer to member of class 'G' via virtual base 'D' is not allowed}} // Conversion to member of base. pdi1 = pdid; // expected-error {{assigning to 'int A::*' from incompatible type 'int D::*'}} // Comparisons int (A::*pf2)(int, int); int (D::*pf3)(int, int) = 0; bool b1 = (pf == pf2); (void)b1; bool b2 = (pf != pf2); (void)b2; bool b3 = (pf == pf3); (void)b3; bool b4 = (pf != 0); (void)b4; } struct TheBase { void d(); }; struct HasMembers : TheBase { int i; void f(); void g(); void g(int); static void g(double); }; namespace Fake { int i; void f(); } void g() { HasMembers hm; int HasMembers::*pmi = &HasMembers::i; int *pni = &Fake::i; int *pmii = &hm.i; void (HasMembers::*pmf)() = &HasMembers::f; void (*pnf)() = &Fake::f; &hm.f; // expected-error {{cannot create a non-constant pointer to member function}} void (HasMembers::*pmgv)() = &HasMembers::g; void (HasMembers::*pmgi)(int) = &HasMembers::g; void (*pmgd)(double) = &HasMembers::g; void (HasMembers::*pmd)() = &HasMembers::d; } struct Incomplete; void h() { HasMembers hm, *phm = &hm; int HasMembers::*pi = &HasMembers::i; hm.*pi = 0; int i = phm->*pi; (void)&(hm.*pi); (void)&(phm->*pi); (void)&((&hm)->*pi); void (HasMembers::*pf)() = &HasMembers::f; (hm.*pf)(); (phm->*pf)(); (void)(hm->*pi); // expected-error {{left hand operand to ->* must be a pointer to class compatible with the right hand operand, but is 'HasMembers'}} (void)(phm.*pi); // expected-error {{left hand operand to .* must be a class compatible with the right hand operand, but is 'HasMembers *'}} (void)(i.*pi); // expected-error {{left hand operand to .* must be a class compatible with the right hand operand, but is 'int'}} int *ptr; (void)(ptr->*pi); // expected-error {{left hand operand to ->* must be a pointer to class compatible with the right hand operand, but is 'int *'}} int A::*pai = 0; D d, *pd = &d; (void)(d.*pai); (void)(pd->*pai); F f, *ptrf = &f; (void)(f.*pai); // expected-error {{ambiguous conversion from derived class 'F' to base class 'A'}} (void)(ptrf->*pai); // expected-error {{ambiguous conversion from derived class 'F' to base class 'A'}} H h, *ptrh = &h; (void)(h.*pai); // expected-error {{cannot cast 'H' to its private base class 'A'}} (void)(ptrh->*pai); // expected-error {{cannot cast 'H' to its private base class 'A'}} (void)(hm.*i); // expected-error {{pointer-to-member}} (void)(phm->*i); // expected-error {{pointer-to-member}} // Okay Incomplete *inc; int Incomplete::*pii = 0; (void)(inc->*pii); } struct OverloadsPtrMem { int operator ->*(const char *); }; void i() { OverloadsPtrMem m; int foo = m->*"Awesome!"; } namespace pr5985 { struct c { void h(); void f() { void (c::*p)(); p = &h; // expected-error {{must explicitly qualify}} p = &this->h; // expected-error {{cannot create a non-constant pointer to member function}} p = &(*this).h; // expected-error {{cannot create a non-constant pointer to member function}} } }; } namespace pr6783 { struct Base {}; struct X; // expected-note {{forward declaration}} int test1(int Base::* p2m, X* object) { return object->*p2m; // expected-error {{left hand operand to ->*}} } } namespace PR7176 { namespace base { struct Process { }; struct Continuous : Process { bool cond(); }; } typedef bool( base::Process::*Condition )(); void m() { (void)(Condition) &base::Continuous::cond; } } namespace rdar8358512 { // We can't call this with an overload set because we're not allowed // to look into overload sets unless the parameter has some kind of // function type. template <class F> void bind(F f); // expected-note 12 {{candidate template ignored}} template <class F, class T> void bindmem(F (T::*f)()); // expected-note 4 {{candidate template ignored}} template <class F> void bindfn(F (*f)()); // expected-note 4 {{candidate template ignored}} struct A { void nonstat(); void nonstat(int); void mixed(); static void mixed(int); static void stat(); static void stat(int); template <typename T> struct Test0 { void test() { bind(&nonstat); // expected-error {{no matching function for call}} bind(&A::nonstat); // expected-error {{no matching function for call}} bind(&mixed); // expected-error {{no matching function for call}} bind(&A::mixed); // expected-error {{no matching function for call}} bind(&stat); // expected-error {{no matching function for call}} bind(&A::stat); // expected-error {{no matching function for call}} } }; template <typename T> struct Test1 { void test() { bindmem(&nonstat); // expected-error {{no matching function for call}} bindmem(&A::nonstat); bindmem(&mixed); // expected-error {{no matching function for call}} bindmem(&A::mixed); bindmem(&stat); // expected-error {{no matching function for call}} bindmem(&A::stat); // expected-error {{no matching function for call}} } }; template <typename T> struct Test2 { void test() { bindfn(&nonstat); // expected-error {{no matching function for call}} bindfn(&A::nonstat); // expected-error {{no matching function for call}} bindfn(&mixed); // expected-error {{no matching function for call}} bindfn(&A::mixed); // expected-error {{no matching function for call}} bindfn(&stat); bindfn(&A::stat); } }; }; template <class T> class B { void nonstat(); void nonstat(int); void mixed(); static void mixed(int); static void stat(); static void stat(int); // None of these can be diagnosed yet, because the arguments are // still dependent. void test0a() { bind(&nonstat); bind(&B::nonstat); bind(&mixed); bind(&B::mixed); bind(&stat); bind(&B::stat); } void test0b() { bind(&nonstat); // expected-error {{no matching function for call}} bind(&B::nonstat); // expected-error {{no matching function for call}} bind(&mixed); // expected-error {{no matching function for call}} bind(&B::mixed); // expected-error {{no matching function for call}} bind(&stat); // expected-error {{no matching function for call}} bind(&B::stat); // expected-error {{no matching function for call}} } }; template void B<int>::test0b(); // expected-note {{in instantiation}} } namespace PR9973 { template<class R, class T> struct dm { typedef R T::*F; F f_; template<class U> int & call(U u) { return u->*f_; } // expected-error{{reference to non-static member function must be called; did you mean to call it with no arguments?}} expected-error {{non-const lvalue reference to type 'int' cannot bind to a temporary of type 'int'}} template<class U> int operator()(U u) { call(u); } // expected-note{{in instantiation of}} }; template<class R, class T> dm<R, T> mem_fn(R T::*) ; struct test { int nullary_v(); }; void f() { test* t; mem_fn(&test::nullary_v)(t); // expected-note{{in instantiation of}} } } namespace test8 { struct A { int foo; }; int test1() { // Verify that we perform (and check) an lvalue conversion on the operands here. return (*((A**) 0)) // expected-warning {{indirection of non-volatile null pointer will be deleted}} expected-note {{consider}} ->**(int A::**) 0; // expected-warning {{indirection of non-volatile null pointer will be deleted}} expected-note {{consider}} } int test2() { // Verify that we perform (and check) an lvalue conversion on the operands here. // TODO: the .* should itself warn about being a dereference of null. return (*((A*) 0)) .**(int A::**) 0; // expected-warning {{indirection of non-volatile null pointer will be deleted}} expected-note {{consider}} } } <|endoftext|>
<commit_before>// Test -fsanitize-memory-use-after-dtor // RUN: %clang_cc1 -fsanitize=memory -fsanitize-memory-use-after-dtor -triple=x86_64-pc-linux -emit-llvm -o - %s | FileCheck %s // RUN: %clang_cc1 -fsanitize=memory -triple=x86_64-pc-linux -emit-llvm -o - %s | FileCheck %s -check-prefix=NO_DTOR_CHECK struct Simple { ~Simple() {} }; Simple s; // Simple internal member is poisoned by compiler-generated dtor // CHECK-LABEL: @_ZN6SimpleD2Ev // CHECK: call void @__sanitizer_dtor_callback // CHECK: ret void // Compiling without the flag does not generate member-poisoning dtor // NO_DTOR_CHECK-LABEL: @_ZN6SimpleD2Ev // NO_DTOR_CHECK-NOT: call void @sanitizer_dtor_callback // NO_DTOR_CHECK: ret void <commit_msg>adding tests for various dtor decl types<commit_after>// Test -fsanitize-memory-use-after-dtor // RUN: %clang_cc1 -fsanitize=memory -fsanitize-memory-use-after-dtor -triple=x86_64-pc-linux -emit-llvm -o - %s | FileCheck %s // RUN: %clang_cc1 -fsanitize=memory -triple=x86_64-pc-linux -emit-llvm -o - %s | FileCheck %s -check-prefix=NO-DTOR-CHECK // RUN: %clang_cc1 -std=c++11 -fsanitize=memory -fsanitize-memory-use-after-dtor -triple=x86_64-pc-linux -emit-llvm -o - %s | FileCheck %s -check-prefix=STD11 // RUN: %clang_cc1 -std=c++11 -fsanitize=memory -triple=x86_64-pc-linux -emit-llvm -o - %s | FileCheck %s -check-prefix=NO-DTOR-STD11-CHECK struct Simple { ~Simple() {} }; Simple s; // Simple internal member is poisoned by compiler-generated dtor // CHECK-LABEL: @_ZN6SimpleD2Ev // CHECK: call void @__sanitizer_dtor_callback // CHECK: ret void // Compiling without the flag does not generate member-poisoning dtor // NO-DTOR-CHECK-LABEL: @_ZN6SimpleD2Ev // NO-DTOR-CHECK-NOT: call void @__sanitizer_dtor_callback // NO-DTOR-CHECK: ret void struct Inlined { inline ~Inlined() {} }; Inlined in; // Dtor that is inlined where invoked poisons object // CHECK-LABEL: @_ZN7InlinedD2Ev // CHECK: call void @__sanitizer_dtor_callback // CHECK: ret void // Compiling without the flag does not generate member-poisoning dtor // NO-DTOR-CHECK-LABEL: @_ZN7InlinedD2Ev // NO-DTOR-CHECK-NOT: call void @__sanitizer_dtor_callback // NO-DTOR-CHECK: ret void struct Defaulted_Trivial { ~Defaulted_Trivial() = default; }; int main() { Defaulted_Trivial def_trivial; } // The compiler is explicitly signalled to handle object cleanup. // No complex member attributes ensures that the compiler destroys // the memory inline. However, it must still poison this memory. // STD11-CHECK-LABEL: alloca %struct.Defaulted_Trivial // STD11: call void @__sanitizer_dtor_callback // STD11: ret void // Compiling without the flag does not generate member-poisoning dtor // NO-DTOR-STD11-CHECK-LABEL: alloca %struct.Defaulted_Trivial // NO-DTOR-STD11-CHECK-NOT: call void @__sanitizer_dtor_callback // NO-DTOR-STD11-CHECK: ret void struct Defaulted_Non_Trivial { Simple s; ~Defaulted_Non_Trivial() = default; }; Defaulted_Non_Trivial def_non_trivial; // Explicitly compiler-generated dtor poisons object. // By including a Simple member in the struct, the compiler is // forced to generate a non-trivial destructor.. // STD11-CHECK-LABEL: @_ZN21Defaulted_Non_TrivialD2Ev // STD11: call void @__sanitizer_dtor_callback // STD11: ret void // Compiling without the flag does not generate member-poisoning dtor // NO-DTOR-STD11-CHECK-LABEL: @_ZN21Defaulted_Non_TrivialD2Ev // NO-DTOR-STD11-CHECK-NOT: call void @__sanitizer_dtor_callback // NO-DTOR-STD11-CHECK: ret void <|endoftext|>
<commit_before><commit_msg>Document TSSRT push output options<commit_after><|endoftext|>
<commit_before>#include <iostream> #include <stdlib.h> #include <ctime> #include <sys/time.h> #include <omp.h> #include <mkl.h> using namespace std; void mm1(double **A, double **B, double **C, int matrix_size) { for (int i = 0 ; i < matrix_size; i++) { for (int j = 0; j < matrix_size; j++) { for (int k = 0; k < matrix_size; k++) { C[i][j] += A[i][k] * B[k][j]; } } } } void mm2(double **A, double **B, double **C, int matrix_size) { for (int i = 0 ; i < matrix_size; i++) { for (int k = 0; k < matrix_size; k++) { for (int j = 0; j < matrix_size; j++) { C[i][j] += A[i][k] * B[k][j]; } } } } void mm3(double *a, double *b, double *c, int matrix_size) { for (int i=0 ; i<matrix_size; i++) { for (int j=0; j<matrix_size; j++) { int idx = i*matrix_size; for (int k=0; k<matrix_size; k++) { c[idx+j] += a[idx+k]*b[k*matrix_size+j]; } } } } void mm4(double *a, double *b, double *c, int matrix_size) { cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, matrix_size, matrix_size, matrix_size, 1.0, a, matrix_size, b, matrix_size, 0.0, c, matrix_size); } void print_check(double **Z, int matrix_size) { cout<<Z[0][0]<<" "<<Z[1][1]<<" "<<Z[2][2]<<endl; } void print_check_1D(double *Z, int matrix_size) { cout<<Z[0]<<" "<<Z[matrix_size+1]<<" "<<Z[2*matrix_size+2]<<endl; } void zero_result(double **C, int matrix_size) { for (int i = 0 ; i < matrix_size; i++) { for (int j = 0; j < matrix_size; j++) { C[i][j] = 0.0; } } } void zero_result_1D(double *C, int matrix_size) { for (int i = 0 ; i < matrix_size*matrix_size; i++) { C[i] = 0.0; } } void print_elapsed_time(timeval t1, timeval t2, string s) { timeval t; timersub(&t2, &t1, &t); cout << t.tv_sec + t.tv_usec/1000000.0 << " Seconds -- "<< s << endl; } int main(int argc, char *argv[]) { int matrix_size; if(argc<2) { cout<<"ERROR: expecting integer matrix size, i.e., N for NxN matrix"<<endl; exit(1); } else { matrix_size=atoi(argv[1]); } double thresh_1, thresh_2, thresh_3; if(argc<5) { thresh_1=0.1; thresh_2=0.3; thresh_3=0.6; cout<<"Using default thresholds: "; } else { thresh_1=atof(argv[2]); thresh_2=atof(argv[3]); thresh_3=atof(argv[4]); cout<<"Using user supplied thresholds: "; } cout<<thresh_1<<" "<<thresh_2<<" "<<thresh_3<<endl; mkl_set_num_threads(1); cout<<"using matrix size:"<<matrix_size<<endl; double **A, **B, **C; double *a, *b, *c; A = new double*[matrix_size]; B = new double*[matrix_size]; C = new double*[matrix_size]; a = new double[matrix_size*matrix_size]; b = new double[matrix_size*matrix_size]; c = new double[matrix_size*matrix_size]; for (int i = 0 ; i < matrix_size; i++) { A[i] = new double[matrix_size]; B[i] = new double[matrix_size]; C[i] = new double[matrix_size]; } int idx; for (int i=0; i<matrix_size; i++) { idx=i*matrix_size; for (int j = 0 ; j < matrix_size; j++) { A[i][j]=((double) rand() / (RAND_MAX)); B[i][j]=((double) rand() / (RAND_MAX)); C[i][j]=0.0; a[idx+j]=A[i][j]; b[idx+j]=B[i][j]; c[idx+j]=0.0; } } print_check(A, matrix_size); timeval t1, t2, t; //--------------------------------------------------------------------- //standard implementation //--------------------------------------------------------------------- /* gettimeofday(&t1, NULL); mm1(A,B,C,matrix_size); print_check(C,matrix_size); zero_result(C,matrix_size); print_check(C,matrix_size); gettimeofday(&t2, NULL); print_elapsed_time(t1,t2,"mm1"); gettimeofday(&t1, NULL); mm2(A,B,C,matrix_size); print_check(C,matrix_size); zero_result(C,matrix_size); gettimeofday(&t2, NULL); print_elapsed_time(t1,t2,"mm2"); gettimeofday(&t1, NULL); mm3(a,b,c,matrix_size); print_check_1D(c,matrix_size); zero_result_1D(c,matrix_size); gettimeofday(&t2, NULL); print_elapsed_time(t1,t2,"mm3"); gettimeofday(&t1, NULL); mm4(a,b,c,matrix_size); print_check_1D(c,matrix_size); zero_result_1D(c,matrix_size); gettimeofday(&t2, NULL); print_elapsed_time(t1,t2,"mm4"); */ int max_iters=50; double random_choice; for (int r=0; r < max_iters; r++) { random_choice = ((double) rand() / (RAND_MAX)); if (random_choice<thresh_1) { zero_result(C,matrix_size); mm1(A,B,C,matrix_size); } else if (random_choice>=thresh_1 && random_choice<thresh_2) { zero_result(C,matrix_size); mm2(A,B,C,matrix_size); } else if (random_choice>=thresh_2 && random_choice<thresh_3) { zero_result_1D(c,matrix_size); mm3(a,b,c,matrix_size); } else { zero_result_1D(c,matrix_size); mm4(a,b,c,matrix_size); } } for (int i = 0 ; i < matrix_size; i++) { delete A[i]; delete B[i]; delete C[i]; } delete A; delete B; delete C; return 0; } <commit_msg>add more details comments in matmul_test.cpp<commit_after>/****************************************************************************************************** July 10, 2017 Ian A. Cosden Princeton University icosden@princeton.edu Sample Matrix-Matrix multiplication code for CoDaS-HEP Summer School Purpose: To use as a example to profile with performance tuning tools such as VTune. The code does not do anything useful and is for illustrative/educational use only. It is not meant to be exhaustive or demostrating optimal matrix-matrix multiplication techniques. Description: Code generates two matrices with random numbers. They are stored in 2D arrays (named A and B) as well as 1D arrays (a and b). There are 4 functions that multiply A and B and store the result in matrix C (or c in the 1D case). It is possible to set the percentage of time each function is called via the command line. Command line arguments: N <threshold 1> <threshold 2> <threshold 3> N: size of NxN matrix **optional**: thresholds: 4 functions are distributed between 0 and 1. mm1 is called between 0 and <threshold 1> mm2 is called between <threshold 1> and <threshold 2> mm3 is called between <threshold 2> and <threshold 3> mm4 is called between <threshold 3> and 1. Example: to call only mm1 use 1.0 0 0 to call only mm2 use 0 1.0 1.0 to call only mm3 use 0 0 1.0 to call only mm4 use 0 0 0 *******************************************************************************************************/ #include "mm.h" int main(int argc, char *argv[]) { int matrix_size; //N*N matrix double thresh_1, thresh_2, thresh_3; //read command line input //set various paramaters if(argc<2) { cout<<"ERROR: expecting integer matrix size, i.e., N for NxN matrix"<<endl; exit(1); } else { matrix_size=atoi(argv[1]); } if(argc<5) { thresh_1=0.1; thresh_2=0.3; thresh_3=0.6; cout<<"Using default thresholds: "; } else { thresh_1=atof(argv[2]); thresh_2=atof(argv[3]); thresh_3=atof(argv[4]); cout<<"Using user supplied thresholds: "; } cout<<thresh_1<<" "<<thresh_2<<" "<<thresh_3<<endl; cout<<"using matrix size:"<<matrix_size<<endl; mkl_set_num_threads(1); //needed to prevent mkl (mm4) from grabbing all available cores double **A, **B, **C; //2D arrays double *a, *b, *c; //equivalent 1D arrays A = new double*[matrix_size]; B = new double*[matrix_size]; C = new double*[matrix_size]; a = new double[matrix_size*matrix_size]; b = new double[matrix_size*matrix_size]; c = new double[matrix_size*matrix_size]; for (int i = 0 ; i < matrix_size; i++) { A[i] = new double[matrix_size]; B[i] = new double[matrix_size]; C[i] = new double[matrix_size]; } int idx; //initialize values crudely between 0 and 1 //(we don't really care what they are) for (int i=0; i<matrix_size; i++) { idx=i*matrix_size; for (int j = 0 ; j < matrix_size; j++) { A[i][j]=((double) rand() / (RAND_MAX)); B[i][j]=((double) rand() / (RAND_MAX)); C[i][j]=0.0; a[idx+j]=A[i][j]; b[idx+j]=B[i][j]; c[idx+j]=0.0; } } int max_iters=50; //number of times to call a matrix-matrix (mm) function double random_choice; //random number from rng //Depending on random number and earlier set thresholds call a matrix-multiplication //function mm1,mm2,mm3,mm4. This is done to purposely obfuscate the "hotspots" for (int r=0; r < max_iters; r++) { random_choice = ((double) rand() / (RAND_MAX)); if (random_choice<thresh_1) { zero_result(C,matrix_size); mm1(A,B,C,matrix_size); } else if (random_choice>=thresh_1 && random_choice<thresh_2) { zero_result(C,matrix_size); mm2(A,B,C,matrix_size); } else if (random_choice>=thresh_2 && random_choice<thresh_3) { zero_result_1D(c,matrix_size); mm3(a,b,c,matrix_size); } else { zero_result_1D(c,matrix_size); mm4(a,b,c,matrix_size); } } for (int i = 0 ; i < matrix_size; i++) { delete A[i]; delete B[i]; delete C[i]; } delete A; delete B; delete C; return 0; } <|endoftext|>
<commit_before>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */ // vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4: /* COPYING CONDITIONS NOTICE: This program is free software; you can redistribute it and/or modify it under the terms of version 2 of the GNU General Public License as published by the Free Software Foundation, and provided that the following conditions are met: * Redistributions of source code must retain this COPYING CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the PATENT MARKING NOTICE (below), and the PATENT RIGHTS GRANT (below). * Redistributions in binary form must reproduce this COPYING CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the PATENT MARKING NOTICE (below), and the PATENT RIGHTS GRANT (below) in the documentation and/or other materials provided with the distribution. 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. COPYRIGHT NOTICE: TokuFT, Tokutek Fractal Tree Indexing Library. Copyright (C) 2007-2014 Tokutek, Inc. DISCLAIMER: 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. UNIVERSITY PATENT NOTICE: The technology is licensed by the Massachusetts Institute of Technology, Rutgers State University of New Jersey, and the Research Foundation of State University of New York at Stony Brook under United States of America Serial No. 11/760379 and to the patents and/or patent applications resulting from it. PATENT MARKING NOTICE: This software is covered by US Patent No. 8,185,551. This software is covered by US Patent No. 8,489,638. PATENT RIGHTS GRANT: "THIS IMPLEMENTATION" means the copyrightable works distributed by Tokutek as part of the Fractal Tree project. "PATENT CLAIMS" means the claims of patents that are owned or licensable by Tokutek, both currently or in the future; and that in the absence of this license would be infringed by THIS IMPLEMENTATION or by using or running THIS IMPLEMENTATION. "PATENT CHALLENGE" shall mean a challenge to the validity, patentability, enforceability and/or non-infringement of any of the PATENT CLAIMS or otherwise opposing any of the PATENT CLAIMS. Tokutek hereby grants to you, for the term and geographical scope of the PATENT CLAIMS, a non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, transfer, and otherwise run, modify, and propagate the contents of THIS IMPLEMENTATION, where such license applies only to the PATENT CLAIMS. This grant does not include claims that would be infringed only as a consequence of further modifications of THIS IMPLEMENTATION. If you or your agent or licensee institute or order or agree to the institution of patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that THIS IMPLEMENTATION constitutes direct or contributory patent infringement, or inducement of patent infringement, then any rights granted to you under this License shall terminate as of the date such litigation is filed. If you or your agent or exclusive licensee institute or order or agree to the institution of a PATENT CHALLENGE, then Tokutek may terminate any rights granted to you under this License. */ #include <algorithm> #include <string.h> #include "portability/toku_assert.h" #include "ft/serialize/block_allocator_strategy.h" static uint64_t _align(uint64_t value, uint64_t ba_alignment) { return ((value + ba_alignment - 1) / ba_alignment) * ba_alignment; } static uint64_t _roundup_to_power_of_two(uint64_t value) { uint64_t r = 4096; while (r < value) { r *= 2; invariant(r > 0); } return r; } // First fit block allocation static struct block_allocator::blockpair * _first_fit(struct block_allocator::blockpair *blocks_array, uint64_t n_blocks, uint64_t size, uint64_t alignment, bool forward, uint64_t max_padding) { if (n_blocks == 1) { // won't enter loop, can't underflow the direction < 0 case return nullptr; } struct block_allocator::blockpair *bp = forward ? &blocks_array[0] : &blocks_array[-1]; for (uint64_t n_spaces_to_check = n_blocks - 1; n_spaces_to_check > 0; n_spaces_to_check--, forward ? bp++ : bp--) { // Consider the space after bp uint64_t padded_alignment = max_padding != 0 ? _align(max_padding, alignment) : alignment; uint64_t possible_offset = _align(bp->offset + bp->size, padded_alignment); if (possible_offset + size <= bp[1].offset) { invariant((forward ? bp - blocks_array : blocks_array - bp) < (int64_t) n_blocks); return bp; } } return nullptr; } struct block_allocator::blockpair * block_allocator_strategy::first_fit(struct block_allocator::blockpair *blocks_array, uint64_t n_blocks, uint64_t size, uint64_t alignment) { return _first_fit(blocks_array, n_blocks, size, alignment, true, 0); } // Best fit block allocation struct block_allocator::blockpair * block_allocator_strategy::best_fit(struct block_allocator::blockpair *blocks_array, uint64_t n_blocks, uint64_t size, uint64_t alignment) { struct block_allocator::blockpair *best_bp = nullptr; uint64_t best_hole_size = 0; for (uint64_t blocknum = 0; blocknum + 1 < n_blocks; blocknum++) { // Consider the space after blocknum struct block_allocator::blockpair *bp = &blocks_array[blocknum]; uint64_t possible_offset = _align(bp->offset + bp->size, alignment); uint64_t possible_end_offset = possible_offset + size; if (possible_end_offset <= bp[1].offset) { // It fits here. Is it the best fit? uint64_t hole_size = bp[1].offset - possible_end_offset; if (best_bp == nullptr || hole_size < best_hole_size) { best_hole_size = hole_size; best_bp = bp; } } } return best_bp; } static uint64_t padded_fit_alignment = 4096; // TODO: These compiler specific directives should be abstracted in a portability header // portability/toku_compiler.h? __attribute__((__constructor__)) static void determine_padded_fit_alignment_from_env(void) { // TODO: Should be in portability as 'toku_os_getenv()?' const char *s = getenv("TOKU_BA_PADDED_FIT_ALIGNMENT"); if (s != nullptr && strlen(s) > 0) { const int64_t alignment = strtoll(s, nullptr, 10); if (alignment <= 0) { fprintf(stderr, "tokuft: error: block allocator padded fit alignment found in environment (%s), " "but it's out of range (should be an integer > 0). defaulting to %" PRIu64 "\n", s, padded_fit_alignment); } else { padded_fit_alignment = _roundup_to_power_of_two(alignment); fprintf(stderr, "tokuft: setting block allocator padded fit alignment to %" PRIu64 "\n", padded_fit_alignment); } } } // First fit into a block that is oversized by up to max_padding. // The hope is that if we purposefully waste a bit of space at allocation // time we'll be more likely to reuse this block later. struct block_allocator::blockpair * block_allocator_strategy::padded_fit(struct block_allocator::blockpair *blocks_array, uint64_t n_blocks, uint64_t size, uint64_t alignment) { return _first_fit(blocks_array, n_blocks, size, alignment, true, padded_fit_alignment); } static double hot_zone_threshold = 0.85; // TODO: These compiler specific directives should be abstracted in a portability header // portability/toku_compiler.h? __attribute__((__constructor__)) static void determine_hot_zone_threshold_from_env(void) { // TODO: Should be in portability as 'toku_os_getenv()?' const char *s = getenv("TOKU_BA_HOT_ZONE_THRESHOLD"); if (s != nullptr && strlen(s) > 0) { const double hot_zone = strtod(s, nullptr); if (hot_zone < 1 || hot_zone > 99) { fprintf(stderr, "tokuft: error: block allocator hot zone threshold found in environment (%s), " "but it's out of range (should be an integer 1 through 99). defaulting to 85\n", s); hot_zone_threshold = 85 / 100; } else { fprintf(stderr, "tokuft: setting block allocator hot zone threshold to %s\n", s); hot_zone_threshold = hot_zone / 100; } } } struct block_allocator::blockpair * block_allocator_strategy::heat_zone(struct block_allocator::blockpair *blocks_array, uint64_t n_blocks, uint64_t size, uint64_t alignment, uint64_t heat) { if (heat > 0) { struct block_allocator::blockpair *bp, *boundary_bp; // Hot allocation. Find the beginning of the hot zone. boundary_bp = &blocks_array[n_blocks - 1]; uint64_t highest_offset = _align(boundary_bp->offset + boundary_bp->size, alignment); uint64_t hot_zone_offset = static_cast<uint64_t>(hot_zone_threshold * highest_offset); boundary_bp = std::lower_bound(blocks_array, blocks_array + n_blocks, hot_zone_offset); uint64_t blocks_in_zone = (blocks_array + n_blocks) - boundary_bp; uint64_t blocks_outside_zone = boundary_bp - blocks_array; invariant(blocks_in_zone + blocks_outside_zone == n_blocks); if (blocks_in_zone > 0) { // Find the first fit in the hot zone, going forward. bp = _first_fit(boundary_bp, blocks_in_zone, size, alignment, true, 0); if (bp != nullptr) { return bp; } } if (blocks_outside_zone > 0) { // Find the first fit in the cold zone, going backwards. bp = _first_fit(boundary_bp, blocks_outside_zone, size, alignment, false, 0); if (bp != nullptr) { return bp; } } } else { // Cold allocations are simply first-fit from the beginning. return _first_fit(blocks_array, n_blocks, size, alignment, true, 0); } return nullptr; } <commit_msg>FT-591 fix valgrind uninitialized value error in block allocator test caused by reading past the end of a the blockpair array<commit_after>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */ // vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4: /* COPYING CONDITIONS NOTICE: This program is free software; you can redistribute it and/or modify it under the terms of version 2 of the GNU General Public License as published by the Free Software Foundation, and provided that the following conditions are met: * Redistributions of source code must retain this COPYING CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the PATENT MARKING NOTICE (below), and the PATENT RIGHTS GRANT (below). * Redistributions in binary form must reproduce this COPYING CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the PATENT MARKING NOTICE (below), and the PATENT RIGHTS GRANT (below) in the documentation and/or other materials provided with the distribution. 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. COPYRIGHT NOTICE: TokuFT, Tokutek Fractal Tree Indexing Library. Copyright (C) 2007-2014 Tokutek, Inc. DISCLAIMER: 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. UNIVERSITY PATENT NOTICE: The technology is licensed by the Massachusetts Institute of Technology, Rutgers State University of New Jersey, and the Research Foundation of State University of New York at Stony Brook under United States of America Serial No. 11/760379 and to the patents and/or patent applications resulting from it. PATENT MARKING NOTICE: This software is covered by US Patent No. 8,185,551. This software is covered by US Patent No. 8,489,638. PATENT RIGHTS GRANT: "THIS IMPLEMENTATION" means the copyrightable works distributed by Tokutek as part of the Fractal Tree project. "PATENT CLAIMS" means the claims of patents that are owned or licensable by Tokutek, both currently or in the future; and that in the absence of this license would be infringed by THIS IMPLEMENTATION or by using or running THIS IMPLEMENTATION. "PATENT CHALLENGE" shall mean a challenge to the validity, patentability, enforceability and/or non-infringement of any of the PATENT CLAIMS or otherwise opposing any of the PATENT CLAIMS. Tokutek hereby grants to you, for the term and geographical scope of the PATENT CLAIMS, a non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, transfer, and otherwise run, modify, and propagate the contents of THIS IMPLEMENTATION, where such license applies only to the PATENT CLAIMS. This grant does not include claims that would be infringed only as a consequence of further modifications of THIS IMPLEMENTATION. If you or your agent or licensee institute or order or agree to the institution of patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that THIS IMPLEMENTATION constitutes direct or contributory patent infringement, or inducement of patent infringement, then any rights granted to you under this License shall terminate as of the date such litigation is filed. If you or your agent or exclusive licensee institute or order or agree to the institution of a PATENT CHALLENGE, then Tokutek may terminate any rights granted to you under this License. */ #include <algorithm> #include <string.h> #include "portability/toku_assert.h" #include "ft/serialize/block_allocator_strategy.h" static uint64_t _align(uint64_t value, uint64_t ba_alignment) { return ((value + ba_alignment - 1) / ba_alignment) * ba_alignment; } static uint64_t _roundup_to_power_of_two(uint64_t value) { uint64_t r = 4096; while (r < value) { r *= 2; invariant(r > 0); } return r; } // First fit block allocation static struct block_allocator::blockpair * _first_fit(struct block_allocator::blockpair *blocks_array, uint64_t n_blocks, uint64_t size, uint64_t alignment, uint64_t max_padding) { if (n_blocks == 1) { // won't enter loop, can't underflow the direction < 0 case return nullptr; } struct block_allocator::blockpair *bp = &blocks_array[0]; for (uint64_t n_spaces_to_check = n_blocks - 1; n_spaces_to_check > 0; n_spaces_to_check--, bp++) { // Consider the space after bp uint64_t padded_alignment = max_padding != 0 ? _align(max_padding, alignment) : alignment; uint64_t possible_offset = _align(bp->offset + bp->size, padded_alignment); if (possible_offset + size <= bp[1].offset) { // bp[1] is always valid since bp < &blocks_array[n_blocks-1] invariant(bp - blocks_array < (int64_t) n_blocks); return bp; } } return nullptr; } static struct block_allocator::blockpair * _first_fit_bw(struct block_allocator::blockpair *blocks_array, uint64_t n_blocks, uint64_t size, uint64_t alignment, uint64_t max_padding, struct block_allocator::blockpair *blocks_array_limit) { if (n_blocks == 1) { // won't enter loop, can't underflow the direction < 0 case return nullptr; } struct block_allocator::blockpair *bp = &blocks_array[-1]; for (uint64_t n_spaces_to_check = n_blocks - 1; n_spaces_to_check > 0; n_spaces_to_check--, bp--) { // Consider the space after bp uint64_t padded_alignment = max_padding != 0 ? _align(max_padding, alignment) : alignment; uint64_t possible_offset = _align(bp->offset + bp->size, padded_alignment); if (&bp[1] < blocks_array_limit && possible_offset + size <= bp[1].offset) { invariant(blocks_array - bp < (int64_t) n_blocks); return bp; } } return nullptr; } struct block_allocator::blockpair * block_allocator_strategy::first_fit(struct block_allocator::blockpair *blocks_array, uint64_t n_blocks, uint64_t size, uint64_t alignment) { return _first_fit(blocks_array, n_blocks, size, alignment, 0); } // Best fit block allocation struct block_allocator::blockpair * block_allocator_strategy::best_fit(struct block_allocator::blockpair *blocks_array, uint64_t n_blocks, uint64_t size, uint64_t alignment) { struct block_allocator::blockpair *best_bp = nullptr; uint64_t best_hole_size = 0; for (uint64_t blocknum = 0; blocknum + 1 < n_blocks; blocknum++) { // Consider the space after blocknum struct block_allocator::blockpair *bp = &blocks_array[blocknum]; uint64_t possible_offset = _align(bp->offset + bp->size, alignment); uint64_t possible_end_offset = possible_offset + size; if (possible_end_offset <= bp[1].offset) { // It fits here. Is it the best fit? uint64_t hole_size = bp[1].offset - possible_end_offset; if (best_bp == nullptr || hole_size < best_hole_size) { best_hole_size = hole_size; best_bp = bp; } } } return best_bp; } static uint64_t padded_fit_alignment = 4096; // TODO: These compiler specific directives should be abstracted in a portability header // portability/toku_compiler.h? __attribute__((__constructor__)) static void determine_padded_fit_alignment_from_env(void) { // TODO: Should be in portability as 'toku_os_getenv()?' const char *s = getenv("TOKU_BA_PADDED_FIT_ALIGNMENT"); if (s != nullptr && strlen(s) > 0) { const int64_t alignment = strtoll(s, nullptr, 10); if (alignment <= 0) { fprintf(stderr, "tokuft: error: block allocator padded fit alignment found in environment (%s), " "but it's out of range (should be an integer > 0). defaulting to %" PRIu64 "\n", s, padded_fit_alignment); } else { padded_fit_alignment = _roundup_to_power_of_two(alignment); fprintf(stderr, "tokuft: setting block allocator padded fit alignment to %" PRIu64 "\n", padded_fit_alignment); } } } // First fit into a block that is oversized by up to max_padding. // The hope is that if we purposefully waste a bit of space at allocation // time we'll be more likely to reuse this block later. struct block_allocator::blockpair * block_allocator_strategy::padded_fit(struct block_allocator::blockpair *blocks_array, uint64_t n_blocks, uint64_t size, uint64_t alignment) { return _first_fit(blocks_array, n_blocks, size, alignment, padded_fit_alignment); } static double hot_zone_threshold = 0.85; // TODO: These compiler specific directives should be abstracted in a portability header // portability/toku_compiler.h? __attribute__((__constructor__)) static void determine_hot_zone_threshold_from_env(void) { // TODO: Should be in portability as 'toku_os_getenv()?' const char *s = getenv("TOKU_BA_HOT_ZONE_THRESHOLD"); if (s != nullptr && strlen(s) > 0) { const double hot_zone = strtod(s, nullptr); if (hot_zone < 1 || hot_zone > 99) { fprintf(stderr, "tokuft: error: block allocator hot zone threshold found in environment (%s), " "but it's out of range (should be an integer 1 through 99). defaulting to 85\n", s); hot_zone_threshold = 85 / 100; } else { fprintf(stderr, "tokuft: setting block allocator hot zone threshold to %s\n", s); hot_zone_threshold = hot_zone / 100; } } } struct block_allocator::blockpair * block_allocator_strategy::heat_zone(struct block_allocator::blockpair *blocks_array, uint64_t n_blocks, uint64_t size, uint64_t alignment, uint64_t heat) { if (heat > 0) { struct block_allocator::blockpair *bp, *boundary_bp; // Hot allocation. Find the beginning of the hot zone. boundary_bp = &blocks_array[n_blocks - 1]; uint64_t highest_offset = _align(boundary_bp->offset + boundary_bp->size, alignment); uint64_t hot_zone_offset = static_cast<uint64_t>(hot_zone_threshold * highest_offset); boundary_bp = std::lower_bound(blocks_array, blocks_array + n_blocks, hot_zone_offset); uint64_t blocks_in_zone = (blocks_array + n_blocks) - boundary_bp; uint64_t blocks_outside_zone = boundary_bp - blocks_array; invariant(blocks_in_zone + blocks_outside_zone == n_blocks); if (blocks_in_zone > 0) { // Find the first fit in the hot zone, going forward. bp = _first_fit(boundary_bp, blocks_in_zone, size, alignment, 0); if (bp != nullptr) { return bp; } } if (blocks_outside_zone > 0) { // Find the first fit in the cold zone, going backwards. bp = _first_fit_bw(boundary_bp, blocks_outside_zone, size, alignment, 0, &blocks_array[n_blocks]); if (bp != nullptr) { return bp; } } } else { // Cold allocations are simply first-fit from the beginning. return _first_fit(blocks_array, n_blocks, size, alignment, 0); } return nullptr; } <|endoftext|>
<commit_before>#line 2 "quanta/core/object/io/writer.ipp" /** @copyright MIT license; see @ref index or the accompanying LICENSE file. */ #include <quanta/core/config.hpp> #include <quanta/core/object/object.hpp> #include <togo/core/error/assert.hpp> #include <togo/core/utility/utility.hpp> #include <togo/core/collection/array.hpp> #include <togo/core/io/types.hpp> #include <togo/core/io/io.hpp> #include <cstdio> namespace quanta { namespace object { namespace { static constexpr char const TABS[]{ "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t" }; #define RETURN_ERROR(x) if (!(x)) { return false; } static bool write_tabs(IWriter& stream, unsigned tabs) { while (tabs > 0) { unsigned const amount = min(tabs, array_extent(TABS)); if (!io::write(stream, TABS, amount)) { return false; } tabs -= amount; } return true; } #if defined(TOGO_COMPILER_CLANG) || \ defined(TOGO_COMPILER_GCC) __attribute__((__format__ (__printf__, 2, 3))) #endif static bool writef(IWriter& stream, char const* const format, ...) { char buffer[256]; va_list va; va_start(va, format); signed const size = std::vsnprintf(buffer, array_extent(buffer), format, va); va_end(va); if (size < 0) { return false; } return io::write(stream, buffer, static_cast<unsigned>(size)); } inline static unsigned quote_level(StringRef const& str) { auto const it_end = end(str); for (auto it = begin(str); it != it_end; ++it) { switch (*it) { case '\\': case '\"': case '\n': return 1; } } return 0; } inline static bool write_quote(IWriter& stream, unsigned level) { switch (level) { case 0: RETURN_ERROR(io::write_value(stream, '\"')); break; case 1: RETURN_ERROR(io::write(stream, "```", 3)); break; } return true; } inline static bool write_identifier(IWriter& stream, StringRef const& str) { RETURN_ERROR(io::write(stream, str.data, str.size)); return true; } inline static bool write_string(IWriter& stream, StringRef const& str) { unsigned const level = quote_level(str); RETURN_ERROR( write_quote(stream, level) && io::write(stream, str.data, str.size) && write_quote(stream, level) ); return true; } inline static bool write_source(IWriter& stream, unsigned source, bool uncertain) { RETURN_ERROR( io::write(stream, "$?", 1 + uncertain) && (source == 0 || writef(stream, "%u", source)) ); return true; } inline static bool write_markers(IWriter& stream, Object const& obj) { if (object::marker_value_uncertain(obj)) { RETURN_ERROR(io::write_value(stream, '?')); } else if (object::marker_value_guess(obj)) { RETURN_ERROR(io::write(stream, "G~", 2)); } auto approximation = object::value_approximation(obj); if (approximation < 0) { RETURN_ERROR(io::write(stream, "~~~", unsigned_cast(-approximation))); } else if (approximation > 0) { RETURN_ERROR(io::write(stream, "^^^", unsigned_cast(approximation))); } return true; } static bool write_object( IWriter& stream, Object const& obj, unsigned tabs, bool named = true ); static bool write_tag( IWriter& stream, Object const& obj, unsigned tabs, bool scope_childless ) { RETURN_ERROR( io::write_value(stream, ':') && write_markers(stream, obj) && write_identifier(stream, object::name(obj)) ); if (object::has_children(obj)) { RETURN_ERROR(io::write_value(stream, '(')); auto& last_child = array::back(object::children(obj)); for (auto& child : object::children(obj)) { RETURN_ERROR( write_object(stream, child, tabs) && (&child == &last_child || io::write(stream, ", ", 2)) ); } RETURN_ERROR(io::write_value(stream, ')')); } else if (scope_childless) { RETURN_ERROR(io::write(stream, "()", 2)); } return true; } inline char const* op_string(ObjectOperator const op) { switch (op) { case ObjectOperator::add: return " + "; case ObjectOperator::sub: return " - "; case ObjectOperator::mul: return " * "; case ObjectOperator::div: return " / "; } } static bool write_expression( IWriter& stream, Object const& obj, unsigned tabs, bool scoped ) { scoped |= array::size(object::children(obj)) <= 1; if (scoped) { RETURN_ERROR(io::write_value(stream, '(')); } if (object::has_children(obj)) { auto& children = object::children(obj); auto it = begin(children); auto end = array::end(children); RETURN_ERROR(write_object(stream, *it, tabs, true)); for (++it; it != end; ++it) { RETURN_ERROR( io::write(stream, op_string(object::op(*it)), 3) && write_object(stream, *it, tabs, false) ); } } if (scoped) { RETURN_ERROR(io::write_value(stream, ')')); } return true; } static bool write_object( IWriter& stream, Object const& obj, unsigned tabs, bool named ) { if (named && object::is_named(obj)) { RETURN_ERROR( write_identifier(stream, object::name(obj)) && io::write(stream, " = ", 3) ); } RETURN_ERROR(write_markers(stream, obj)); switch (object::type(obj)) { case ObjectValueType::null: if ( !(obj.properties & object::M_VALUE_MARKERS) && !object::has_children(obj) && !object::has_tags(obj) ) { RETURN_ERROR(io::write(stream, "null", 4)); } break; case ObjectValueType::boolean: if (obj.value.boolean) { RETURN_ERROR(io::write(stream, "true", 4)); } else { RETURN_ERROR(io::write(stream, "false", 5)); } break; case ObjectValueType::integer: RETURN_ERROR(writef(stream, "%ld", obj.value.numeric.integer)); goto l_write_unit; case ObjectValueType::decimal: RETURN_ERROR(writef(stream, "%.6lg", obj.value.numeric.decimal)); goto l_write_unit; case ObjectValueType::currency: { RETURN_ERROR(io::write(stream, "\xC2\xA4", 2)); // ¤ in UTF-8 s64 value = 0; if (obj.value.numeric.c.value < 0) { RETURN_ERROR(io::write_value(stream, '-')); value = -obj.value.numeric.c.value; } else { value = obj.value.numeric.c.value; } if (obj.value.numeric.c.exponent == 0) { RETURN_ERROR(writef(stream, "%li", value)); } else if (obj.value.numeric.c.exponent < 0) { RETURN_ERROR(writef(stream, "0.%0*li", -obj.value.numeric.c.exponent, value)); } else { u64 scale = object::pow_int(10, obj.value.numeric.c.exponent); s64 minor = value % scale; RETURN_ERROR(writef( stream, "%li.%0*li", (value - minor) / scale, obj.value.numeric.c.exponent, minor )); } } goto l_write_unit; l_write_unit: if (object::has_unit(obj)) { RETURN_ERROR(write_identifier(stream, object::unit(obj))); } else if (object::is_currency(obj)) { RETURN_ERROR(io::write(stream, "unknown", 7)); } break; case ObjectValueType::time: { Time const& t = object::time_value(obj); bool has_clock = object::has_clock(obj); if (object::has_date(obj)) { bool month_contextual = object::is_month_contextual(obj); Date date = time::gregorian::date(t); if (!object::is_year_contextual(obj)) { RETURN_ERROR(writef(stream, "%04d-", date.year)); } if (!month_contextual) { RETURN_ERROR(writef(stream, "%02d-", date.month)); } RETURN_ERROR(writef(stream, (month_contextual || has_clock) ? "%02dT" : "%02d", date.day)); } if (has_clock) { signed h, m, s; time::clock(t, h, m, s); RETURN_ERROR(writef(stream, "%02d:%02d:%02d", h, m, s)); if (!object::is_zoned(obj)) { // no zone to write } else if (t.zone_offset == 0) { RETURN_ERROR(io::write(stream, "Z", 1)); } else { time::clock(Time{t.zone_offset, 0}, h, m, s); RETURN_ERROR(writef(stream, "%c%02d%02d", t.zone_offset < 0 ? '-' : '+', h, m)); } } } break; case ObjectValueType::string: RETURN_ERROR(write_string(stream, object::string(obj))); break; case ObjectValueType::identifier: RETURN_ERROR(write_identifier(stream, object::identifier(obj))); break; case ObjectValueType::expression: break; } if (object::has_source(obj) || object::marker_source_uncertain(obj)) { RETURN_ERROR(write_source(stream, object::source(obj), object::marker_source_uncertain(obj))); if (object::has_sub_source(obj) || object::marker_sub_source_uncertain(obj)) { RETURN_ERROR(write_source(stream, object::sub_source(obj), object::marker_sub_source_uncertain(obj))); } } // TODO: split pre- and post-tags if (object::is_expression(obj)) { if (object::has_tags(obj)) { auto& last_tag = array::back(object::tags(obj)); for (auto& tag : object::tags(obj)) { RETURN_ERROR(write_tag(stream, tag, tabs, &tag == &last_tag)); } } RETURN_ERROR(write_expression( stream, obj, tabs, (obj.properties & object::M_VALUE_MARKERS) || object::has_source(obj) || object::has_tags(obj) || object::has_quantity(obj) )); } else { for (auto& tag : object::tags(obj)) { RETURN_ERROR(write_tag(stream, tag, tabs, false)); } if (object::has_children(obj)) { RETURN_ERROR(io::write(stream, "{\n", 2)); ++tabs; for (auto& child : object::children(obj)) { RETURN_ERROR( write_tabs(stream, tabs) && write_object(stream, child, tabs) && io::write_value(stream, '\n') ); } --tabs; RETURN_ERROR( write_tabs(stream, tabs) && io::write_value(stream, '}') ); } } if (object::has_quantity(obj)) { auto& quantity = *object::quantity(obj); RETURN_ERROR(io::write_value(stream, '[')); if (object::is_null(quantity) && object::has_children(quantity)) { auto& last_child = array::back(object::children(quantity)); for (auto& child : object::children(quantity)) { RETURN_ERROR( write_object(stream, child, tabs) && (&child == &last_child || io::write(stream, ", ", 2)) ); } } else { RETURN_ERROR(write_object(stream, quantity, tabs)); } RETURN_ERROR(io::write_value(stream, ']')); } return true; } #undef RETURN_ERROR } // anonymous namespace } // namespace object } // namespace quanta <commit_msg>lib/core/object/io/writer: write zone offset for time values.<commit_after>#line 2 "quanta/core/object/io/writer.ipp" /** @copyright MIT license; see @ref index or the accompanying LICENSE file. */ #include <quanta/core/config.hpp> #include <quanta/core/object/object.hpp> #include <togo/core/error/assert.hpp> #include <togo/core/utility/utility.hpp> #include <togo/core/collection/array.hpp> #include <togo/core/io/types.hpp> #include <togo/core/io/io.hpp> #include <cstdio> namespace quanta { namespace object { namespace { static constexpr char const TABS[]{ "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t" }; #define RETURN_ERROR(x) if (!(x)) { return false; } static bool write_tabs(IWriter& stream, unsigned tabs) { while (tabs > 0) { unsigned const amount = min(tabs, array_extent(TABS)); if (!io::write(stream, TABS, amount)) { return false; } tabs -= amount; } return true; } #if defined(TOGO_COMPILER_CLANG) || \ defined(TOGO_COMPILER_GCC) __attribute__((__format__ (__printf__, 2, 3))) #endif static bool writef(IWriter& stream, char const* const format, ...) { char buffer[256]; va_list va; va_start(va, format); signed const size = std::vsnprintf(buffer, array_extent(buffer), format, va); va_end(va); if (size < 0) { return false; } return io::write(stream, buffer, static_cast<unsigned>(size)); } inline static unsigned quote_level(StringRef const& str) { auto const it_end = end(str); for (auto it = begin(str); it != it_end; ++it) { switch (*it) { case '\\': case '\"': case '\n': return 1; } } return 0; } inline static bool write_quote(IWriter& stream, unsigned level) { switch (level) { case 0: RETURN_ERROR(io::write_value(stream, '\"')); break; case 1: RETURN_ERROR(io::write(stream, "```", 3)); break; } return true; } inline static bool write_identifier(IWriter& stream, StringRef const& str) { RETURN_ERROR(io::write(stream, str.data, str.size)); return true; } inline static bool write_string(IWriter& stream, StringRef const& str) { unsigned const level = quote_level(str); RETURN_ERROR( write_quote(stream, level) && io::write(stream, str.data, str.size) && write_quote(stream, level) ); return true; } inline static bool write_source(IWriter& stream, unsigned source, bool uncertain) { RETURN_ERROR( io::write(stream, "$?", 1 + uncertain) && (source == 0 || writef(stream, "%u", source)) ); return true; } inline static bool write_markers(IWriter& stream, Object const& obj) { if (object::marker_value_uncertain(obj)) { RETURN_ERROR(io::write_value(stream, '?')); } else if (object::marker_value_guess(obj)) { RETURN_ERROR(io::write(stream, "G~", 2)); } auto approximation = object::value_approximation(obj); if (approximation < 0) { RETURN_ERROR(io::write(stream, "~~~", unsigned_cast(-approximation))); } else if (approximation > 0) { RETURN_ERROR(io::write(stream, "^^^", unsigned_cast(approximation))); } return true; } static bool write_object( IWriter& stream, Object const& obj, unsigned tabs, bool named = true ); static bool write_tag( IWriter& stream, Object const& obj, unsigned tabs, bool scope_childless ) { RETURN_ERROR( io::write_value(stream, ':') && write_markers(stream, obj) && write_identifier(stream, object::name(obj)) ); if (object::has_children(obj)) { RETURN_ERROR(io::write_value(stream, '(')); auto& last_child = array::back(object::children(obj)); for (auto& child : object::children(obj)) { RETURN_ERROR( write_object(stream, child, tabs) && (&child == &last_child || io::write(stream, ", ", 2)) ); } RETURN_ERROR(io::write_value(stream, ')')); } else if (scope_childless) { RETURN_ERROR(io::write(stream, "()", 2)); } return true; } inline char const* op_string(ObjectOperator const op) { switch (op) { case ObjectOperator::add: return " + "; case ObjectOperator::sub: return " - "; case ObjectOperator::mul: return " * "; case ObjectOperator::div: return " / "; } } static bool write_expression( IWriter& stream, Object const& obj, unsigned tabs, bool scoped ) { scoped |= array::size(object::children(obj)) <= 1; if (scoped) { RETURN_ERROR(io::write_value(stream, '(')); } if (object::has_children(obj)) { auto& children = object::children(obj); auto it = begin(children); auto end = array::end(children); RETURN_ERROR(write_object(stream, *it, tabs, true)); for (++it; it != end; ++it) { RETURN_ERROR( io::write(stream, op_string(object::op(*it)), 3) && write_object(stream, *it, tabs, false) ); } } if (scoped) { RETURN_ERROR(io::write_value(stream, ')')); } return true; } static bool write_object( IWriter& stream, Object const& obj, unsigned tabs, bool named ) { if (named && object::is_named(obj)) { RETURN_ERROR( write_identifier(stream, object::name(obj)) && io::write(stream, " = ", 3) ); } RETURN_ERROR(write_markers(stream, obj)); switch (object::type(obj)) { case ObjectValueType::null: if ( !(obj.properties & object::M_VALUE_MARKERS) && !object::has_children(obj) && !object::has_tags(obj) ) { RETURN_ERROR(io::write(stream, "null", 4)); } break; case ObjectValueType::boolean: if (obj.value.boolean) { RETURN_ERROR(io::write(stream, "true", 4)); } else { RETURN_ERROR(io::write(stream, "false", 5)); } break; case ObjectValueType::integer: RETURN_ERROR(writef(stream, "%ld", obj.value.numeric.integer)); goto l_write_unit; case ObjectValueType::decimal: RETURN_ERROR(writef(stream, "%.6lg", obj.value.numeric.decimal)); goto l_write_unit; case ObjectValueType::currency: { RETURN_ERROR(io::write(stream, "\xC2\xA4", 2)); // ¤ in UTF-8 s64 value = 0; if (obj.value.numeric.c.value < 0) { RETURN_ERROR(io::write_value(stream, '-')); value = -obj.value.numeric.c.value; } else { value = obj.value.numeric.c.value; } if (obj.value.numeric.c.exponent == 0) { RETURN_ERROR(writef(stream, "%li", value)); } else if (obj.value.numeric.c.exponent < 0) { RETURN_ERROR(writef(stream, "0.%0*li", -obj.value.numeric.c.exponent, value)); } else { u64 scale = object::pow_int(10, obj.value.numeric.c.exponent); s64 minor = value % scale; RETURN_ERROR(writef( stream, "%li.%0*li", (value - minor) / scale, obj.value.numeric.c.exponent, minor )); } } goto l_write_unit; l_write_unit: if (object::has_unit(obj)) { RETURN_ERROR(write_identifier(stream, object::unit(obj))); } else if (object::is_currency(obj)) { RETURN_ERROR(io::write(stream, "unknown", 7)); } break; case ObjectValueType::time: { signed h, m, s; Time const& t = object::time_value(obj); if (object::has_date(obj)) { Date date = time::gregorian::date(t); if (!object::is_year_contextual(obj)) { RETURN_ERROR(writef(stream, "%04d-", date.year)); } if (!object::is_month_contextual(obj)) { RETURN_ERROR(writef(stream, "%02d-", date.month)); } RETURN_ERROR(writef(stream, "%02d", date.day)); if ( object::has_clock(obj) || ( object::is_zoned(obj) ? t.zone_offset != 0 : object::is_month_contextual(obj) ) ) { RETURN_ERROR(io::write_value(stream, 'T')); } } if (object::has_clock(obj)) { time::clock(t, h, m, s); RETURN_ERROR(writef(stream, "%02d:%02d:%02d", h, m, s)); } if (object::is_zoned(obj)) { if (t.zone_offset == 0) { RETURN_ERROR(io::write(stream, "Z", 1)); } else { bool negative = t.zone_offset < 0; time::clock(Time{negative ? -t.zone_offset : t.zone_offset, 0}, h, m, s); if (m == 0) { RETURN_ERROR(writef(stream, "%c%02d", negative ? '-' : '+', h)); } else { RETURN_ERROR(writef(stream, "%c%02d:%02d", negative ? '-' : '+', h, m)); } } } } break; case ObjectValueType::string: RETURN_ERROR(write_string(stream, object::string(obj))); break; case ObjectValueType::identifier: RETURN_ERROR(write_identifier(stream, object::identifier(obj))); break; case ObjectValueType::expression: break; } if (object::has_source(obj) || object::marker_source_uncertain(obj)) { RETURN_ERROR(write_source(stream, object::source(obj), object::marker_source_uncertain(obj))); if (object::has_sub_source(obj) || object::marker_sub_source_uncertain(obj)) { RETURN_ERROR(write_source(stream, object::sub_source(obj), object::marker_sub_source_uncertain(obj))); } } // TODO: split pre- and post-tags if (object::is_expression(obj)) { if (object::has_tags(obj)) { auto& last_tag = array::back(object::tags(obj)); for (auto& tag : object::tags(obj)) { RETURN_ERROR(write_tag(stream, tag, tabs, &tag == &last_tag)); } } RETURN_ERROR(write_expression( stream, obj, tabs, (obj.properties & object::M_VALUE_MARKERS) || object::has_source(obj) || object::has_tags(obj) || object::has_quantity(obj) )); } else { for (auto& tag : object::tags(obj)) { RETURN_ERROR(write_tag(stream, tag, tabs, false)); } if (object::has_children(obj)) { RETURN_ERROR(io::write(stream, "{\n", 2)); ++tabs; for (auto& child : object::children(obj)) { RETURN_ERROR( write_tabs(stream, tabs) && write_object(stream, child, tabs) && io::write_value(stream, '\n') ); } --tabs; RETURN_ERROR( write_tabs(stream, tabs) && io::write_value(stream, '}') ); } } if (object::has_quantity(obj)) { auto& quantity = *object::quantity(obj); RETURN_ERROR(io::write_value(stream, '[')); if (object::is_null(quantity) && object::has_children(quantity)) { auto& last_child = array::back(object::children(quantity)); for (auto& child : object::children(quantity)) { RETURN_ERROR( write_object(stream, child, tabs) && (&child == &last_child || io::write(stream, ", ", 2)) ); } } else { RETURN_ERROR(write_object(stream, quantity, tabs)); } RETURN_ERROR(io::write_value(stream, ']')); } return true; } #undef RETURN_ERROR } // anonymous namespace } // namespace object } // namespace quanta <|endoftext|>
<commit_before>/******************************************************************************* Program: Wake Forest University - Virginia Tech CTC Software Id: $Id$ Language: C++ *******************************************************************************/ // command line app to subtract tagged stool from images #include <iostream> #include <cstdlib> using namespace std; // ITK includes #include <itkImageSeriesWriter.h> #include <itkNumericSeriesFileNames.h> #include <itksys/SystemTools.hxx> #include <itkGDCMImageIO.h> #include <itkImageRegionIterator.h> #include <itkImageRegionConstIterator.h> #include <itkMetaDataObject.h> #include <itkMetaDataDictionary.h> #include "gdcmUtil.h" // CTC includes #include "ctcConfigure.h" #include "ctcCTCImage.h" #include "ctcCTCImageReader.h" #include "ctcSegmentColonWithContrastFilter.h" #include "vul_arg.h" int main(int argc, char ** argv) { // parse args vul_arg<char const*> infile(0, "Input DICOM directory"); vul_arg<char const*> outfile(0, "Output DICOM directory"); vul_arg<int> replaceval("-r", "Replacement HU value for tagged regions (default -900)", -900); vul_arg_parse(argc, argv); // test if outfile exists, if so bail out if(itksys::SystemTools::FileExists(outfile())) { if(itksys::SystemTools::FileIsDirectory(outfile())) { cerr << "Error: directory " << outfile() << " exists. Halting." << endl; } else { cerr << "Error: file " << outfile() << " exists. Halting." << endl; } return EXIT_FAILURE; } // read in the DICOM series ctc::CTCImageReader::Pointer reader = ctc::CTCImageReader::New(); reader->SetDirectory(string(infile())); try { reader->Update(); } catch (itk::ExceptionObject &ex) { std::cout << ex << std::endl; return EXIT_FAILURE; } // segment air + constrast clog << "Starting Segment"; ctc::SegmentColonWithContrastFilter::Pointer filter = ctc::SegmentColonWithContrastFilter::New(); filter->SetInput( reader->GetOutput() ); filter->Update(); clog << " Done Segmenting." << endl; // loop through the voxels, testing for threshold and lumen test // replace image values with air clog << "Starting Mask"; int replace = replaceval(); typedef itk::ImageRegionIterator<ctc::CTCImageType> InputIteratorType; typedef itk::ImageRegionConstIterator<ctc::BinaryImageType> BinaryIteratorType; InputIteratorType it1(reader->GetOutput(), reader->GetOutput()->GetRequestedRegion()); BinaryIteratorType it2(filter->GetOutput(), filter->GetOutput()->GetRequestedRegion()); for( it1.GoToBegin(), it2.GoToBegin(); !it1.IsAtEnd() || !it2.IsAtEnd(); ++it1, ++it2) { if( (it2.Get() == 255) && (it1.Get() > -800) ) { it1.Set(replace); } } clog << " Done Masking" << endl; // write out modified image typedef itk::Image< short, 2 > Image2DType; typedef itk::ImageSeriesWriter< ctc::CTCImageType, Image2DType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetInput( reader->GetOutput() ); // modify series number, use old StudyInstanceUID, // alter old SeriesInstanceUId, and add Series description ctc::CTCImageReader::DictionaryArrayRawPointer dictarray = reader->GetMetaDataDictionaryArray(); // taken from ITK code, generate a new series instance UID std::string UIDPrefix = "1.2.826.0.1.3680043.2.1125." "1"; std::string NewSeriesInstanceUIDValue = gdcm::Util::CreateUniqueUID( UIDPrefix ); for(int slice = 0; slice < dictarray->size(); slice++) { std::string SeriesNumberTag = "0020|0011"; std::string SeriesNumberValue = "90"; std::string SeriesDescriptionTag = "0008|103e"; std::string SeriesInstanceUIDTag = "0020|000e"; std::string SeriesInstanceUIDValue; ctc::CTCImageReader::DictionaryRawPointer dict = (*(reader->GetMetaDataDictionaryArray()))[slice]; itk::ExposeMetaData<std::string>(*dict, SeriesInstanceUIDTag, SeriesInstanceUIDValue); itk::EncapsulateMetaData<std::string>(*dict, SeriesNumberTag, SeriesNumberValue); std::string SeriesDescriptionValue = "Derived from SeriesInstance UID " + SeriesInstanceUIDValue; itk::EncapsulateMetaData<std::string>(*dict, SeriesDescriptionTag, SeriesDescriptionValue); itk::EncapsulateMetaData<std::string>(*dict, SeriesInstanceUIDTag, NewSeriesInstanceUIDValue); } writer->SetMetaDataDictionaryArray( dictarray ); itk::GDCMImageIO::Pointer dicomIO = itk::GDCMImageIO::New(); dicomIO->SetKeepOriginalUID(true); writer->SetImageIO( dicomIO ); typedef itk::NumericSeriesFileNames NameGeneratorType; NameGeneratorType::Pointer nameGenerator = NameGeneratorType::New(); if( !itksys::SystemTools::MakeDirectory(outfile()) ) { cerr << "Error: could not create output directory" << endl; return EXIT_FAILURE; } std::string format = outfile(); format += "/%03d.dcm"; nameGenerator->SetSeriesFormat( format.c_str() ); ctc::CTCImageType::ConstPointer inputImage = reader->GetOutput(); ctc::CTCImageType::RegionType region = inputImage->GetLargestPossibleRegion(); ctc::CTCImageType::IndexType start = region.GetIndex(); ctc::CTCImageType::SizeType size = region.GetSize(); const unsigned int firstSlice = start[2]; const unsigned int lastSlice = start[2] + size[2] - 1; nameGenerator->SetStartIndex( firstSlice ); nameGenerator->SetEndIndex( lastSlice ); nameGenerator->SetIncrementIndex( 1 ); writer->SetFileNames( nameGenerator->GetFileNames() ); try { writer->Update(); } catch( itk::ExceptionObject & err ) { cerr << "ExceptionObject caught !" << endl; cerr << err << endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>CLW: yet another attempted fix to DICOM UID issue.<commit_after>/******************************************************************************* Program: Wake Forest University - Virginia Tech CTC Software Id: $Id$ Language: C++ *******************************************************************************/ // command line app to subtract tagged stool from images #include <iostream> #include <cstdlib> using namespace std; // ITK includes #include <itkImageSeriesWriter.h> #include <itkNumericSeriesFileNames.h> #include <itksys/SystemTools.hxx> #include <itkGDCMImageIO.h> #include <itkImageRegionIterator.h> #include <itkImageRegionConstIterator.h> #include <itkMetaDataObject.h> #include <itkMetaDataDictionary.h> #include "gdcmUtil.h" // CTC includes #include "ctcConfigure.h" #include "ctcCTCImage.h" #include "ctcCTCImageReader.h" #include "ctcSegmentColonWithContrastFilter.h" #include "vul_arg.h" int main(int argc, char ** argv) { // parse args vul_arg<char const*> infile(0, "Input DICOM directory"); vul_arg<char const*> outfile(0, "Output DICOM directory"); vul_arg<int> replaceval("-r", "Replacement HU value for tagged regions (default -900)", -900); vul_arg_parse(argc, argv); // test if outfile exists, if so bail out if(itksys::SystemTools::FileExists(outfile())) { if(itksys::SystemTools::FileIsDirectory(outfile())) { cerr << "Error: directory " << outfile() << " exists. Halting." << endl; } else { cerr << "Error: file " << outfile() << " exists. Halting." << endl; } return EXIT_FAILURE; } // read in the DICOM series ctc::CTCImageReader::Pointer reader = ctc::CTCImageReader::New(); reader->SetDirectory(string(infile())); try { reader->Update(); } catch (itk::ExceptionObject &ex) { std::cout << ex << std::endl; return EXIT_FAILURE; } // segment air + constrast clog << "Starting Segment"; ctc::SegmentColonWithContrastFilter::Pointer filter = ctc::SegmentColonWithContrastFilter::New(); filter->SetInput( reader->GetOutput() ); filter->Update(); clog << " Done Segmenting." << endl; // loop through the voxels, testing for threshold and lumen test // replace image values with air clog << "Starting Mask"; int replace = replaceval(); typedef itk::ImageRegionIterator<ctc::CTCImageType> InputIteratorType; typedef itk::ImageRegionConstIterator<ctc::BinaryImageType> BinaryIteratorType; InputIteratorType it1(reader->GetOutput(), reader->GetOutput()->GetRequestedRegion()); BinaryIteratorType it2(filter->GetOutput(), filter->GetOutput()->GetRequestedRegion()); for( it1.GoToBegin(), it2.GoToBegin(); !it1.IsAtEnd() || !it2.IsAtEnd(); ++it1, ++it2) { if( (it2.Get() == 255) && (it1.Get() > -800) ) { it1.Set(replace); } } clog << " Done Masking" << endl; // write out modified image typedef itk::Image< short, 2 > Image2DType; typedef itk::ImageSeriesWriter< ctc::CTCImageType, Image2DType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetInput( reader->GetOutput() ); // modify series number, use old StudyInstanceUID, // alter old SeriesInstanceUId, and add Series description ctc::CTCImageReader::DictionaryArrayRawPointer dictarray = reader->GetMetaDataDictionaryArray(); for(int slice = 0; slice < dictarray->size(); slice++) { std::string SeriesNumberTag = "0020|0011"; std::string SeriesNumberValue = "90"; std::string SeriesDescriptionTag = "0008|103e"; std::string SeriesInstanceUIDTag = "0020|000e"; std::string SeriesInstanceUIDValue; std::string NewSeriesInstanceUIDValue; ctc::CTCImageReader::DictionaryRawPointer dict = (*(reader->GetMetaDataDictionaryArray()))[slice]; itk::ExposeMetaData<std::string>(*dict, SeriesInstanceUIDTag, SeriesInstanceUIDValue); itk::EncapsulateMetaData<std::string>(*dict, SeriesNumberTag, SeriesNumberValue); std::string SeriesDescriptionValue = "Derived from SeriesInstance UID " + SeriesInstanceUIDValue; itk::EncapsulateMetaData<std::string>(*dict, SeriesDescriptionTag, SeriesDescriptionValue); //replace number after the last . size_t dotloc = SeriesInstanceUIDValue.rfind(".", SeriesInstanceUIDValue.size()-1); NewSeriesInstanceUIDValue = SeriesInstanceUIDValue.substr(0, dotloc) + ".90"; itk::EncapsulateMetaData<std::string>(*dict, SeriesInstanceUIDTag, NewSeriesInstanceUIDValue); } writer->SetMetaDataDictionaryArray( dictarray ); itk::GDCMImageIO::Pointer dicomIO = itk::GDCMImageIO::New(); dicomIO->SetKeepOriginalUID(true); writer->SetImageIO( dicomIO ); typedef itk::NumericSeriesFileNames NameGeneratorType; NameGeneratorType::Pointer nameGenerator = NameGeneratorType::New(); if( !itksys::SystemTools::MakeDirectory(outfile()) ) { cerr << "Error: could not create output directory" << endl; return EXIT_FAILURE; } std::string format = outfile(); format += "/%03d.dcm"; nameGenerator->SetSeriesFormat( format.c_str() ); ctc::CTCImageType::ConstPointer inputImage = reader->GetOutput(); ctc::CTCImageType::RegionType region = inputImage->GetLargestPossibleRegion(); ctc::CTCImageType::IndexType start = region.GetIndex(); ctc::CTCImageType::SizeType size = region.GetSize(); const unsigned int firstSlice = start[2]; const unsigned int lastSlice = start[2] + size[2] - 1; nameGenerator->SetStartIndex( firstSlice ); nameGenerator->SetEndIndex( lastSlice ); nameGenerator->SetIncrementIndex( 1 ); writer->SetFileNames( nameGenerator->GetFileNames() ); try { writer->Update(); } catch( itk::ExceptionObject & err ) { cerr << "ExceptionObject caught !" << endl; cerr << err << endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include "sniffer.h" #include "protocol_headers.h" #include "util.h" #include <cstdlib> #include <cstring> #include <string> #include <pcap.h> #include <map> #include <iostream> using namespace std; static pcap_t *handle = NULL; static int datalink; char * interface; const int num_channels = 12; int current_channel = 0; void set_monitor_mode(char * iface) { interface = iface; char * const argv[] = {(char*)("iwconfig"),iface,(char*)("mode"),(char*)("monitor"),0}; int ret = run_command(argv); if ( ret ) { debug("Probably on an Ubuntu system. Trying to set monitor using ifconfig technique."); char * const ifconfig_down[] = {(char*)("ifconfig"),iface,(char*)("down"),0}; char * const ifconfig_up[] = {(char*)("ifconfig"),iface,(char*)("up"),0}; ret = run_command(ifconfig_down); if ( ret ) { error("Interface error. Quitting."); abort(); } ret = run_command(argv); if ( ret ) { error("Interface error. Quitting."); abort(); } ret = run_command(ifconfig_up); if ( ret ) { error("Interface error. Quitting."); abort(); } } } const float max_time = 60; const float round_time = 12; float channel_prob[num_channels+1]; float channel_time[num_channels+1]; int channel_packets[num_channels+1]; void initialize(char * interface) { if ( handle ) { error("Trying to reinitialize using interface %s",interface); abort(); } char errbuf[BUFSIZ]; set_monitor_mode(interface); handle = pcap_open_live(interface, BUFSIZ, 1, 1000, errbuf); if (handle == NULL) { error("Couldn't open interface %s. Error: %s",interface,errbuf); abort(); } datalink = pcap_datalink(handle); verbose("Opened interface %s.",interface); debug("Datalink is %d.", datalink); for ( int i = 1 ; i <= num_channels ; i++ ) { channel_prob[i] = 1.0/num_channels; channel_time[i] = 0; channel_packets[i] = 0; } } map<string,int> mac_count[num_channels+1][4]; void handleMAC(const u_char * mac, int pos) { char mac_c_str[13]; mac_c_str[0] = 0; for ( int i = 0 ; i < 6 ; i++ ) { sprintf(mac_c_str,"%s%02X",mac_c_str,mac[i]); } string mac_str(mac_c_str); mac_count[current_channel][pos][mac_str]++; debug("MAC %d : %s",pos,mac_c_str); } void handlePacket(const u_char* packet, int length) { if ( packet == NULL ) { return; } if ( datalink == DLT_PRISM_HEADER ) { prism_header* rth1 = (prism_header*)(packet); packet = packet + rth1->msglen; length -= rth1->msglen; } if ( datalink == DLT_IEEE802_11_RADIO ) { ieee80211_radiotap_header* rth2 = (ieee80211_radiotap_header*)(packet); packet = packet + rth2->it_len; length -= rth2->it_len; } for ( int i = 0 ; i < 4 ; i++ ) { if ( 4+i*6 < length ) { handleMAC(packet+4+(i*6),i); } } channel_packets[current_channel]++; } void change_channel(int channel) { if ( channel < 1 || channel > num_channels ) { error("Impossible to switch to channel %d. Quitting.",channel); abort(); } current_channel = channel; char channel_no[3]; sprintf(channel_no,"%d",channel); char * const argv[] = {(char*)"iwconfig",interface,(char*)"channel",channel_no,0}; run_command(argv); verbose("Changed to channel %d",channel); } static Timer ch_time; void mark_time() { channel_time[current_channel]+=ch_time.get_time(); } void switch_to_next_channel() { mark_time(); change_channel((current_channel % num_channels) + 1); ch_time.reset(); } void recalculate_probs() { const float min_speed_adder = 0.01; float speed[num_channels+1]; float total_speed = 0; for ( int i = 1 ; i <= num_channels ; i++ ) { debug("Packets on channel %02d = %d",i,channel_packets[i]); speed[i] = channel_packets[i]/channel_time[i]; speed[i] += min_speed_adder; total_speed += speed[i]; } for ( int i = 1 ; i <= num_channels ; i++ ) { channel_prob[i] = speed[i] / total_speed; } verbose("Recalculated time allotted per channel (Greater time for busier channels)"); } void capture_packets() { Timer timer; switch_to_next_channel(); bool end_of_capturing = false; bool end_of_round = false; while ( true ) { if ( timer.get_time() >= max_time ) { end_of_capturing = true; } pcap_pkthdr header; handlePacket(pcap_next(handle, &header),header.len); debug("<<<Channel %02d timer: %f; Total timer: %f>>>",current_channel,ch_time.get_time(),timer.get_time()); if ( ch_time.get_time() > channel_prob[current_channel] * round_time ) { if ( current_channel==num_channels ) { mark_time(); recalculate_probs(); if ( end_of_capturing ) { break; } } switch_to_next_channel(); } } } void print_info() { cout << "\n\n"; for ( int i = 1 ; i <= num_channels ; i++ ) { int total_unique_mac_count = 0; int total_mac_count = 0; if ( is_verbose() ) { cout << "Channel #" << i << ":\n"; } map<string,int> channel_mac_counts; for ( int j = 0 ; j < 4 ; j++ ) { for ( map<string,int>::iterator it = mac_count[i][j].begin() ; it != mac_count[i][j].end() ; it++ ) { channel_mac_counts[it->first] += it->second; } } for ( map<string,int>::iterator it = channel_mac_counts.begin() ; it != channel_mac_counts.end() ; it++ ) { if ( is_verbose() ) { cout << it->first << " : " << it->second << endl; } total_mac_count += it->second; total_unique_mac_count += 1; } cout << "In channel " << i << ":\n"; cout << " Number of unique MACs seen = " << total_unique_mac_count << endl; cout << " Total number of MACs seen = " << total_mac_count << endl; cout << " Total packets captured = " << channel_packets[i] << endl; cout << " Packet capture rate = " << (channel_packets[i]/channel_time[i]) << " packets/sec" << endl; cout << "\n"; } } // TODO: Make sure that pcap_next doesn't take too long // TODO: Output timetamps for each MAC in debug mode<commit_msg>Move global variables and constants<commit_after>const int num_channels = 12; const float max_time = 60; const float round_time = 12; #include "sniffer.h" #include "protocol_headers.h" #include "util.h" #include <cstdlib> #include <cstring> #include <string> #include <pcap.h> #include <map> #include <iostream> using namespace std; static pcap_t *handle = NULL; static int datalink; char * interface; int current_channel = 0; float channel_prob[num_channels+1]; float channel_time[num_channels+1]; int channel_packets[num_channels+1]; map<string,int> mac_count[num_channels+1][4]; void set_monitor_mode(char * iface) { interface = iface; char * const argv[] = {(char*)("iwconfig"),iface,(char*)("mode"),(char*)("monitor"),0}; int ret = run_command(argv); if ( ret ) { debug("Probably on an Ubuntu system. Trying to set monitor using ifconfig technique."); char * const ifconfig_down[] = {(char*)("ifconfig"),iface,(char*)("down"),0}; char * const ifconfig_up[] = {(char*)("ifconfig"),iface,(char*)("up"),0}; ret = run_command(ifconfig_down); if ( ret ) { error("Interface error. Quitting."); abort(); } ret = run_command(argv); if ( ret ) { error("Interface error. Quitting."); abort(); } ret = run_command(ifconfig_up); if ( ret ) { error("Interface error. Quitting."); abort(); } } } void initialize(char * interface) { if ( handle ) { error("Trying to reinitialize using interface %s",interface); abort(); } char errbuf[BUFSIZ]; set_monitor_mode(interface); handle = pcap_open_live(interface, BUFSIZ, 1, 1000, errbuf); if (handle == NULL) { error("Couldn't open interface %s. Error: %s",interface,errbuf); abort(); } datalink = pcap_datalink(handle); verbose("Opened interface %s.",interface); debug("Datalink is %d.", datalink); for ( int i = 1 ; i <= num_channels ; i++ ) { channel_prob[i] = 1.0/num_channels; channel_time[i] = 0; channel_packets[i] = 0; } } void handleMAC(const u_char * mac, int pos) { char mac_c_str[13]; mac_c_str[0] = 0; for ( int i = 0 ; i < 6 ; i++ ) { sprintf(mac_c_str,"%s%02X",mac_c_str,mac[i]); } string mac_str(mac_c_str); mac_count[current_channel][pos][mac_str]++; debug("MAC %d : %s",pos,mac_c_str); } void handlePacket(const u_char* packet, int length) { if ( packet == NULL ) { return; } if ( datalink == DLT_PRISM_HEADER ) { prism_header* rth1 = (prism_header*)(packet); packet = packet + rth1->msglen; length -= rth1->msglen; } if ( datalink == DLT_IEEE802_11_RADIO ) { ieee80211_radiotap_header* rth2 = (ieee80211_radiotap_header*)(packet); packet = packet + rth2->it_len; length -= rth2->it_len; } for ( int i = 0 ; i < 4 ; i++ ) { if ( 4+i*6 < length ) { handleMAC(packet+4+(i*6),i); } } channel_packets[current_channel]++; } void change_channel(int channel) { if ( channel < 1 || channel > num_channels ) { error("Impossible to switch to channel %d. Quitting.",channel); abort(); } current_channel = channel; char channel_no[3]; sprintf(channel_no,"%d",channel); char * const argv[] = {(char*)"iwconfig",interface,(char*)"channel",channel_no,0}; run_command(argv); verbose("Changed to channel %d",channel); } static Timer ch_time; void mark_time() { channel_time[current_channel]+=ch_time.get_time(); } void switch_to_next_channel() { mark_time(); change_channel((current_channel % num_channels) + 1); ch_time.reset(); } void recalculate_probs() { const float min_speed_adder = 0.01; float speed[num_channels+1]; float total_speed = 0; for ( int i = 1 ; i <= num_channels ; i++ ) { debug("Packets on channel %02d = %d",i,channel_packets[i]); speed[i] = channel_packets[i]/channel_time[i]; speed[i] += min_speed_adder; total_speed += speed[i]; } for ( int i = 1 ; i <= num_channels ; i++ ) { channel_prob[i] = speed[i] / total_speed; } verbose("Recalculated time allotted per channel (Greater time for busier channels)"); } void capture_packets() { Timer timer; switch_to_next_channel(); bool end_of_capturing = false; bool end_of_round = false; while ( true ) { if ( timer.get_time() >= max_time ) { end_of_capturing = true; } pcap_pkthdr header; handlePacket(pcap_next(handle, &header),header.len); debug("<<<Channel %02d timer: %f; Total timer: %f>>>",current_channel,ch_time.get_time(),timer.get_time()); if ( ch_time.get_time() > channel_prob[current_channel] * round_time ) { if ( current_channel==num_channels ) { mark_time(); recalculate_probs(); if ( end_of_capturing ) { break; } } switch_to_next_channel(); } } } void print_info() { cout << "\n\n"; for ( int i = 1 ; i <= num_channels ; i++ ) { int total_unique_mac_count = 0; int total_mac_count = 0; if ( is_verbose() ) { cout << "Channel #" << i << ":\n"; } map<string,int> channel_mac_counts; for ( int j = 0 ; j < 4 ; j++ ) { for ( map<string,int>::iterator it = mac_count[i][j].begin() ; it != mac_count[i][j].end() ; it++ ) { channel_mac_counts[it->first] += it->second; } } for ( map<string,int>::iterator it = channel_mac_counts.begin() ; it != channel_mac_counts.end() ; it++ ) { if ( is_verbose() ) { cout << it->first << " : " << it->second << endl; } total_mac_count += it->second; total_unique_mac_count += 1; } cout << "In channel " << i << ":\n"; cout << " Number of unique MACs seen = " << total_unique_mac_count << endl; cout << " Total number of MACs seen = " << total_mac_count << endl; cout << " Total packets captured = " << channel_packets[i] << endl; cout << " Packet capture rate = " << (channel_packets[i]/channel_time[i]) << " packets/sec" << endl; cout << "\n"; } } // TODO: Make sure that pcap_next doesn't take too long // TODO: Output timetamps for each MAC in debug mode<|endoftext|>
<commit_before>const int num_channels = 12; const float max_time = 60; const float round_time = max_time/5; #include "sniffer.h" #include "protocol_headers.h" #include "util.h" #include <cstdlib> #include <cstring> #include <string> #include <pcap.h> #include <map> #include <set> #include <iostream> using namespace std; static pcap_t *handle = NULL; static int datalink; char * interface; int current_channel = 0; float channel_prob[num_channels+1]; float channel_time[num_channels+1]; int channel_packets[num_channels+1]; map<string,int> mac_count[num_channels+1][4]; void set_monitor_mode(char * iface) { interface = iface; char * const argv[] = {(char*)("iwconfig"),iface,(char*)("mode"),(char*)("monitor"),0}; int ret = run_command(argv); if ( ret ) { debug("Probably on an Ubuntu system. Trying to set monitor using ifconfig technique."); char * const ifconfig_down[] = {(char*)("ifconfig"),iface,(char*)("down"),0}; char * const ifconfig_up[] = {(char*)("ifconfig"),iface,(char*)("up"),0}; ret = run_command(ifconfig_down); if ( ret ) { error("Interface error. Quitting."); abort(); } ret = run_command(argv); if ( ret ) { error("Interface error. Quitting."); abort(); } ret = run_command(ifconfig_up); if ( ret ) { error("Interface error. Quitting."); abort(); } } } void initialize(char * interface) { if ( handle ) { error("Trying to reinitialize using interface %s",interface); abort(); } char errbuf[BUFSIZ]; set_monitor_mode(interface); handle = pcap_open_live(interface, BUFSIZ, 1, 1000, errbuf); if (handle == NULL) { error("Couldn't open interface %s. Error: %s",interface,errbuf); abort(); } datalink = pcap_datalink(handle); verbose("Opened interface %s.",interface); debug("Datalink is %d.", datalink); for ( int i = 1 ; i <= num_channels ; i++ ) { channel_prob[i] = 1.0/num_channels; channel_time[i] = 0; channel_packets[i] = 0; } } void handleMAC(const u_char * mac, int pos) { char mac_c_str[13]; mac_c_str[0] = 0; for ( int i = 0 ; i < 6 ; i++ ) { sprintf(mac_c_str,"%s%02X",mac_c_str,mac[i]); } string mac_str(mac_c_str); mac_count[current_channel][pos][mac_str]++; debug("MAC %d : %s",pos,mac_c_str); } void handlePacket(const u_char* packet, int length) { if ( packet == NULL ) { return; } if ( datalink == DLT_PRISM_HEADER ) { prism_header* rth1 = (prism_header*)(packet); packet = packet + rth1->msglen; length -= rth1->msglen; } if ( datalink == DLT_IEEE802_11_RADIO ) { ieee80211_radiotap_header* rth2 = (ieee80211_radiotap_header*)(packet); packet = packet + rth2->it_len; length -= rth2->it_len; } for ( int i = 0 ; i < 4 ; i++ ) { if ( 4+i*6 < length ) { handleMAC(packet+4+(i*6),i); } } channel_packets[current_channel]++; } void change_channel(int channel) { if ( channel < 1 || channel > num_channels ) { error("Impossible to switch to channel %d. Quitting.",channel); abort(); } current_channel = channel; char channel_no[3]; sprintf(channel_no,"%d",channel); char * const argv[] = {(char*)"iwconfig",interface,(char*)"channel",channel_no,0}; run_command(argv); verbose("Changed to channel %d",channel); } static Timer ch_time; void mark_time() { channel_time[current_channel]+=ch_time.get_time(); } void switch_to_next_channel() { mark_time(); change_channel((current_channel % num_channels) + 1); ch_time.reset(); } void recalculate_probs() { const float min_speed_adder = 0.01; float speed[num_channels+1]; float total_speed = 0; for ( int i = 1 ; i <= num_channels ; i++ ) { debug("Packets on channel %02d = %d",i,channel_packets[i]); speed[i] = channel_packets[i]/channel_time[i]; speed[i] += min_speed_adder; total_speed += speed[i]; } for ( int i = 1 ; i <= num_channels ; i++ ) { channel_prob[i] = speed[i] / total_speed; } verbose("Recalculated time allotted per channel (Greater time for busier channels)"); } void capture_packets() { Timer timer; switch_to_next_channel(); bool end_of_capturing = false; bool end_of_round = false; while ( true ) { if ( timer.get_time() >= max_time ) { end_of_capturing = true; } pcap_pkthdr header; handlePacket(pcap_next(handle, &header),header.len); debug("<<<Channel %02d timer: %f; Total timer: %f>>>",current_channel,ch_time.get_time(),timer.get_time()); if ( ch_time.get_time() > channel_prob[current_channel] * round_time ) { if ( current_channel==num_channels ) { mark_time(); recalculate_probs(); if ( end_of_capturing ) { break; } } switch_to_next_channel(); } } } void print_info() { cout << "\n\n"; int overall_total_mac_count = 0; int overall_total_packets_captured = 0; float overall_total_time = 0; set<string> overall_macs; for ( int i = 1 ; i <= num_channels ; i++ ) { int total_unique_mac_count = 0; int total_mac_count = 0; if ( is_verbose() ) { cout << "Channel #" << i << ":\n"; } map<string,int> channel_mac_counts; for ( int j = 0 ; j < 4 ; j++ ) { for ( map<string,int>::iterator it = mac_count[i][j].begin() ; it != mac_count[i][j].end() ; it++ ) { channel_mac_counts[it->first] += it->second; overall_macs.insert(it->first); } } for ( map<string,int>::iterator it = channel_mac_counts.begin() ; it != channel_mac_counts.end() ; it++ ) { if ( is_verbose() ) { cout << it->first << " : " << it->second << endl; } total_mac_count += it->second; total_unique_mac_count += 1; } cout << "In channel " << i << ":\n"; cout << " Number of unique MACs seen = " << total_unique_mac_count << endl; cout << " Total number of MACs seen = " << total_mac_count << endl; cout << " Total packets captured = " << channel_packets[i] << endl; cout << " Packet capture rate = " << (channel_packets[i]/channel_time[i]) << " packets/sec" << endl; cout << "\n"; overall_total_mac_count += total_mac_count; overall_total_packets_captured += channel_packets[i]; overall_total_time += channel_time[i]; } cout << "Overall:\n"; cout << " Number of unique MACs seen = " << overall_macs.size() << endl; cout << " Total number of MACs seen = " << overall_total_mac_count << endl; cout << " Total packets captured = " << overall_total_packets_captured << endl; cout << " Packet capture rate = " << overall_total_packets_captured/overall_total_time << " packets/sec" << endl; cout << "\n"; } // TODO: Make sure that pcap_next doesn't take too long // TODO: Output timetamps for each MAC in debug mode<commit_msg>Use non-blocked mode<commit_after>const int num_channels = 12; const float max_time = 60; const float round_time = max_time/5; #include "sniffer.h" #include "protocol_headers.h" #include "util.h" #include <cstdlib> #include <cstring> #include <string> #include <pcap.h> #include <map> #include <set> #include <iostream> using namespace std; static pcap_t *handle = NULL; static int datalink; char * interface; int current_channel = 0; float channel_prob[num_channels+1]; float channel_time[num_channels+1]; int channel_packets[num_channels+1]; map<string,int> mac_count[num_channels+1][4]; void set_monitor_mode(char * iface) { interface = iface; char * const argv[] = {(char*)("iwconfig"),iface,(char*)("mode"),(char*)("monitor"),0}; int ret = run_command(argv); if ( ret ) { debug("Probably on an Ubuntu system. Trying to set monitor using ifconfig technique."); char * const ifconfig_down[] = {(char*)("ifconfig"),iface,(char*)("down"),0}; char * const ifconfig_up[] = {(char*)("ifconfig"),iface,(char*)("up"),0}; ret = run_command(ifconfig_down); if ( ret ) { error("Interface error. Quitting."); abort(); } ret = run_command(argv); if ( ret ) { error("Interface error. Quitting."); abort(); } ret = run_command(ifconfig_up); if ( ret ) { error("Interface error. Quitting."); abort(); } } } void initialize(char * interface) { if ( handle ) { error("Trying to reinitialize using interface %s",interface); abort(); } char errbuf[BUFSIZ]; set_monitor_mode(interface); handle = pcap_open_live(interface, BUFSIZ, 1, 1000, errbuf); if (handle == NULL) { error("Couldn't open interface %s. Error: %s",interface,errbuf); abort(); } if ( pcap_setnonblock(handle,1,errbuf) == -1 ) { error("Couldn't set to non-blocking mode. Error: %s",errbuf); abort(); } datalink = pcap_datalink(handle); verbose("Opened interface %s.",interface); debug("Datalink is %d.", datalink); for ( int i = 1 ; i <= num_channels ; i++ ) { channel_prob[i] = 1.0/num_channels; channel_time[i] = 0; channel_packets[i] = 0; } } void handleMAC(const u_char * mac, int pos) { char mac_c_str[13]; mac_c_str[0] = 0; for ( int i = 0 ; i < 6 ; i++ ) { sprintf(mac_c_str,"%s%02X",mac_c_str,mac[i]); } string mac_str(mac_c_str); mac_count[current_channel][pos][mac_str]++; debug("MAC %d : %s",pos,mac_c_str); } void handlePacket(const u_char* packet, int length) { if ( packet == NULL ) { return; } if ( datalink == DLT_PRISM_HEADER ) { prism_header* rth1 = (prism_header*)(packet); packet = packet + rth1->msglen; length -= rth1->msglen; } if ( datalink == DLT_IEEE802_11_RADIO ) { ieee80211_radiotap_header* rth2 = (ieee80211_radiotap_header*)(packet); packet = packet + rth2->it_len; length -= rth2->it_len; } for ( int i = 0 ; i < 4 ; i++ ) { if ( 4+i*6 < length ) { handleMAC(packet+4+(i*6),i); } } channel_packets[current_channel]++; } void change_channel(int channel) { if ( channel < 1 || channel > num_channels ) { error("Impossible to switch to channel %d. Quitting.",channel); abort(); } current_channel = channel; char channel_no[3]; sprintf(channel_no,"%d",channel); char * const argv[] = {(char*)"iwconfig",interface,(char*)"channel",channel_no,0}; run_command(argv); verbose("Changed to channel %d",channel); } static Timer ch_time; void mark_time() { channel_time[current_channel]+=ch_time.get_time(); } void switch_to_next_channel() { mark_time(); change_channel((current_channel % num_channels) + 1); ch_time.reset(); } void recalculate_probs() { const float min_speed_adder = 0.01; float speed[num_channels+1]; float total_speed = 0; for ( int i = 1 ; i <= num_channels ; i++ ) { debug("Packets on channel %02d = %d",i,channel_packets[i]); speed[i] = channel_packets[i]/channel_time[i]; speed[i] += min_speed_adder; total_speed += speed[i]; } for ( int i = 1 ; i <= num_channels ; i++ ) { channel_prob[i] = speed[i] / total_speed; } verbose("Recalculated time allotted per channel (Greater time for busier channels)"); } void callback(u_char *user,const struct pcap_pkthdr* pkthdr,const u_char* packet) { handlePacket(packet,pkthdr->len); } void capture_packets() { Timer timer; switch_to_next_channel(); bool end_of_capturing = false; bool end_of_round = false; while ( true ) { if ( timer.get_time() >= max_time ) { end_of_capturing = true; } if ( pcap_dispatch(handle,1,callback,NULL) ) { debug("<<<Channel %02d timer: %f; Total timer: %f>>>",current_channel,ch_time.get_time(),timer.get_time()); } if ( ch_time.get_time() > channel_prob[current_channel] * round_time ) { if ( current_channel==num_channels ) { mark_time(); recalculate_probs(); if ( end_of_capturing ) { break; } } switch_to_next_channel(); } } } void print_info() { cout << "\n\n"; int overall_total_mac_count = 0; int overall_total_packets_captured = 0; float overall_total_time = 0; set<string> overall_macs; for ( int i = 1 ; i <= num_channels ; i++ ) { int total_unique_mac_count = 0; int total_mac_count = 0; if ( is_verbose() ) { cout << "Channel #" << i << ":\n"; } map<string,int> channel_mac_counts; for ( int j = 0 ; j < 4 ; j++ ) { for ( map<string,int>::iterator it = mac_count[i][j].begin() ; it != mac_count[i][j].end() ; it++ ) { channel_mac_counts[it->first] += it->second; overall_macs.insert(it->first); } } for ( map<string,int>::iterator it = channel_mac_counts.begin() ; it != channel_mac_counts.end() ; it++ ) { if ( is_verbose() ) { cout << it->first << " : " << it->second << endl; } total_mac_count += it->second; total_unique_mac_count += 1; } cout << "In channel " << i << ":\n"; cout << " Number of unique MACs seen = " << total_unique_mac_count << endl; cout << " Total number of MACs seen = " << total_mac_count << endl; cout << " Total packets captured = " << channel_packets[i] << endl; cout << " Packet capture rate = " << (channel_packets[i]/channel_time[i]) << " packets/sec" << endl; cout << "\n"; overall_total_mac_count += total_mac_count; overall_total_packets_captured += channel_packets[i]; overall_total_time += channel_time[i]; } cout << "Overall:\n"; cout << " Number of unique MACs seen = " << overall_macs.size() << endl; cout << " Total number of MACs seen = " << overall_total_mac_count << endl; cout << " Total packets captured = " << overall_total_packets_captured << endl; cout << " Packet capture rate = " << overall_total_packets_captured/overall_total_time << " packets/sec" << endl; cout << "\n"; } // TODO: Make sure that pcap_next doesn't take too long // TODO: Output timetamps for each MAC in debug mode<|endoftext|>
<commit_before>/*========================================================================= Program: OpenIGTLink Library Module: git@github.com:openigtlink/OpenIGTLink.git Language: C++ Copyright (c) Insight Software Consortium. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include <iostream> #include <iomanip> #include <math.h> #include <cstdlib> #include <cstring> #include "igtlSessionManager.h" #include "igtlMessageHandler.h" #include "igtlClientSocket.h" #include "igtlServerSocket.h" #include "igtl_header.h" namespace igtl { SessionManager::SessionManager() { this->m_MessageHandlerList.clear(); this->m_Mode = MODE_SERVER; this->m_Header = igtl::MessageHeader::New(); this->m_TimeStamp = igtl::TimeStamp::New(); this->m_CurrentReadIndex = 0; this->m_HeaderDeserialized = 0; } SessionManager::~SessionManager() { } int SessionManager::AddMessageHandler(MessageHandler* handler) { // Check if there is any handler for the same message type std::vector< MessageHandler* >::iterator iter; for (iter = this->m_MessageHandlerList.begin(); iter != this->m_MessageHandlerList.end(); iter ++) { if ( (*iter)->GetMessageType() == handler->GetMessageType() ) { return 0; } } // If not, add the handler to the list. this->m_MessageHandlerList.push_back(handler); return 1; } int SessionManager::RemoveMessageHandler(MessageHandler* handler) { // Check if there is any handler for the same message type std::vector< MessageHandler* >::iterator iter; for (iter = this->m_MessageHandlerList.begin(); iter != this->m_MessageHandlerList.end(); iter ++) { if (*iter == handler) { this->m_MessageHandlerList.erase(iter); return 1; } } return 0; } int SessionManager::Connect() { this->m_Socket = NULL; if (this->m_Mode == MODE_CLIENT) { ClientSocket::Pointer clientSocket; clientSocket = ClientSocket::New(); //this->DebugOff(); if (this->m_Hostname.length() == 0) { return 0; } //this->m_Socket->SetConnectTimeout(1000); int r = clientSocket->ConnectToServer(this->m_Hostname.c_str(), this->m_Port); if (r == 0) // if connected to server { //clientSocket->SetReceiveTimeout(0); this->m_Socket = clientSocket; } } else { ServerSocket::Pointer serverSocket; serverSocket = ServerSocket::New(); int r = serverSocket->CreateServer(this->m_Port); if (r < 0) { return 0; } if (serverSocket.IsNotNull()) { //this->ServerSocket->CreateServer(this->m_Port); this->m_Socket = serverSocket->WaitForConnection(10000); } if (this->m_Socket.IsNotNull() && this->m_Socket->GetConnected()) // if client connected { this->m_Socket->DebugOff(); } else { return 0; } } this->m_Socket->SetReceiveBlocking(0); // Psuedo non-blocking this->m_CurrentReadIndex = 0; this->m_HeaderDeserialized = 0; return 1; } int SessionManager::Disconnect() { if (this->m_Socket.IsNotNull()) { this->m_Socket->CloseSocket(); } return 0; } int SessionManager::ProcessMessage() { // The workflow of this function is as follows: // // HEADER: // IF the message is (a) a new message: // start reading the header; // ELSE IF the message is a message in progress: // if the process is reading the header: // continue to read the header; // ELSE: // GOTO BODY; // // IF the header has not been received: // GOTO BODY; // ELSE // RETURN; // // BODY: // IF the process has not started reading the body: // check the body type; // find an appropriate handler; // start reading the body // ELSE: // continue to read the body // //-------------------------------------------------- // Header if (this->m_CurrentReadIndex == 0) { // Initialize receive buffer this->m_Header->InitBuffer(); // Receive generic header from the socket int r = this->m_Socket->Receive(this->m_Header->GetBufferPointer(), this->m_Header->GetBufferSize(), 0); if (r == 0) { this->m_CurrentReadIndex = 0; this->m_HeaderDeserialized = 0; return 0; // Disconnected } if (r != this->m_Header->GetBufferSize()) { // Only a part of header has arrived. if (r < 0) // timeout { this->m_CurrentReadIndex = 0; } else { this->m_CurrentReadIndex = r; } return -1; } // The header has been received. this->m_CurrentReadIndex = IGTL_HEADER_SIZE; } else if (this->m_CurrentReadIndex < IGTL_HEADER_SIZE) { // Message transfer was interrupted in the header int r = this->m_Socket->Receive((void*)((char*)this->m_Header->GetBufferPointer()+this->m_CurrentReadIndex), this->m_Header->GetBufferSize()-this->m_CurrentReadIndex, 0); if (r == 0) { this->m_CurrentReadIndex = 0; this->m_HeaderDeserialized = 0; return 0; // Disconnected } if (r != this->m_Header->GetBufferSize()-this->m_CurrentReadIndex) { // Only a part of header has arrived. if (r > 0) // exclude a case of timeout { this->m_CurrentReadIndex += r; } return -1; } // The header has been received. this->m_CurrentReadIndex = IGTL_HEADER_SIZE; } //-------------------------------------------------- // Body if (this->m_HeaderDeserialized == 0) { // Deserialize the header this->m_Header->Unpack(); // Get time stamp igtlUint32 sec; igtlUint32 nanosec; this->m_Header->GetTimeStamp(this->m_TimeStamp); this->m_TimeStamp->GetTimeStamp(&sec, &nanosec); //std::cerr << "Time stamp: " // << sec << "." << std::setw(9) << std::setfill('0') // << nanosec << std::endl; // Look for a message handler that matches to the message type. int found = 0; std::vector< MessageHandler* >::iterator iter; for (iter = this->m_MessageHandlerList.begin(); iter != this->m_MessageHandlerList.end(); iter ++) { #if OpenIGTLink_HEADER_VERSION >= 2 if ( this->m_Header->GetMessageType() == (*iter)->GetMessageType() ) #else if (strcmp(this->m_Header->GetDeviceType(), (*iter)->GetMessageType()) == 0) #endif { this->m_CurrentMessageHandler = *iter; found = 1; break; } } // If there is no message handler, skip the message if (!found) { #if OpenIGTLink_HEADER_VERSION >= 2 std::cerr << "Receiving: " << this->m_Header->GetMessageType() << std::endl; #else std::cerr << "Receiving: " << this->m_Header->GetDeviceType() << std::endl; #endif this->m_Socket->Skip(this->m_Header->GetBodySizeToRead(), 0); // Reset the index counter to be ready for the next message this->m_CurrentReadIndex = 0; this->m_HeaderDeserialized = 0; return 1; } this->m_HeaderDeserialized = 1; } int r = this->m_CurrentMessageHandler->ReceiveMessage(this->m_Socket, this->m_Header, this->m_CurrentReadIndex-IGTL_HEADER_SIZE); if (r == this->m_Header->GetBodySizeToRead()) { this->m_CurrentReadIndex = 0; this->m_HeaderDeserialized = 0; } else { this->m_CurrentReadIndex += IGTL_HEADER_SIZE + r; } return 1; } int SessionManager::PushMessage(MessageBase* message) { if (message && this->m_Socket.IsNotNull() && this->m_Socket->GetConnected()) // if client connected { return this->m_Socket->Send(message->GetBufferPointer(), message->GetBufferSize()); } else { return 0; } } } <commit_msg>Add a condition of return<commit_after>/*========================================================================= Program: OpenIGTLink Library Module: git@github.com:openigtlink/OpenIGTLink.git Language: C++ Copyright (c) Insight Software Consortium. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include <iostream> #include <iomanip> #include <math.h> #include <cstdlib> #include <cstring> #include "igtlSessionManager.h" #include "igtlMessageHandler.h" #include "igtlClientSocket.h" #include "igtlServerSocket.h" #include "igtl_header.h" namespace igtl { SessionManager::SessionManager() { this->m_MessageHandlerList.clear(); this->m_Mode = MODE_SERVER; this->m_Header = igtl::MessageHeader::New(); this->m_TimeStamp = igtl::TimeStamp::New(); this->m_CurrentReadIndex = 0; this->m_HeaderDeserialized = 0; } SessionManager::~SessionManager() { } int SessionManager::AddMessageHandler(MessageHandler* handler) { // Check if there is any handler for the same message type std::vector< MessageHandler* >::iterator iter; for (iter = this->m_MessageHandlerList.begin(); iter != this->m_MessageHandlerList.end(); iter ++) { if ( (*iter)->GetMessageType() == handler->GetMessageType() ) { return 0; } } // If not, add the handler to the list. this->m_MessageHandlerList.push_back(handler); return 1; } int SessionManager::RemoveMessageHandler(MessageHandler* handler) { // Check if there is any handler for the same message type std::vector< MessageHandler* >::iterator iter; for (iter = this->m_MessageHandlerList.begin(); iter != this->m_MessageHandlerList.end(); iter ++) { if (*iter == handler) { this->m_MessageHandlerList.erase(iter); return 1; } } return 0; } int SessionManager::Connect() { this->m_Socket = NULL; if (this->m_Mode == MODE_CLIENT) { ClientSocket::Pointer clientSocket; clientSocket = ClientSocket::New(); //this->DebugOff(); if (this->m_Hostname.length() == 0) { return 0; } //this->m_Socket->SetConnectTimeout(1000); int r = clientSocket->ConnectToServer(this->m_Hostname.c_str(), this->m_Port); if (r == 0) // if connected to server { //clientSocket->SetReceiveTimeout(0); this->m_Socket = clientSocket; } else { return 0; } } else { ServerSocket::Pointer serverSocket; serverSocket = ServerSocket::New(); int r = serverSocket->CreateServer(this->m_Port); if (r < 0) { return 0; } if (serverSocket.IsNotNull()) { //this->ServerSocket->CreateServer(this->m_Port); this->m_Socket = serverSocket->WaitForConnection(10000); } if (this->m_Socket.IsNotNull() && this->m_Socket->GetConnected()) // if client connected { this->m_Socket->DebugOff(); } else { return 0; } } this->m_Socket->SetReceiveBlocking(0); // Psuedo non-blocking this->m_CurrentReadIndex = 0; this->m_HeaderDeserialized = 0; return 1; } int SessionManager::Disconnect() { if (this->m_Socket.IsNotNull()) { this->m_Socket->CloseSocket(); } return 0; } int SessionManager::ProcessMessage() { // The workflow of this function is as follows: // // HEADER: // IF the message is (a) a new message: // start reading the header; // ELSE IF the message is a message in progress: // if the process is reading the header: // continue to read the header; // ELSE: // GOTO BODY; // // IF the header has not been received: // GOTO BODY; // ELSE // RETURN; // // BODY: // IF the process has not started reading the body: // check the body type; // find an appropriate handler; // start reading the body // ELSE: // continue to read the body // //-------------------------------------------------- // Header if (this->m_CurrentReadIndex == 0) { // Initialize receive buffer this->m_Header->InitBuffer(); // Receive generic header from the socket int r = this->m_Socket->Receive(this->m_Header->GetBufferPointer(), this->m_Header->GetBufferSize(), 0); if (r == 0) { this->m_CurrentReadIndex = 0; this->m_HeaderDeserialized = 0; return 0; // Disconnected } if (r != this->m_Header->GetBufferSize()) { // Only a part of header has arrived. if (r < 0) // timeout { this->m_CurrentReadIndex = 0; } else { this->m_CurrentReadIndex = r; } return -1; } // The header has been received. this->m_CurrentReadIndex = IGTL_HEADER_SIZE; } else if (this->m_CurrentReadIndex < IGTL_HEADER_SIZE) { // Message transfer was interrupted in the header int r = this->m_Socket->Receive((void*)((char*)this->m_Header->GetBufferPointer()+this->m_CurrentReadIndex), this->m_Header->GetBufferSize()-this->m_CurrentReadIndex, 0); if (r == 0) { this->m_CurrentReadIndex = 0; this->m_HeaderDeserialized = 0; return 0; // Disconnected } if (r != this->m_Header->GetBufferSize()-this->m_CurrentReadIndex) { // Only a part of header has arrived. if (r > 0) // exclude a case of timeout { this->m_CurrentReadIndex += r; } return -1; } // The header has been received. this->m_CurrentReadIndex = IGTL_HEADER_SIZE; } //-------------------------------------------------- // Body if (this->m_HeaderDeserialized == 0) { // Deserialize the header this->m_Header->Unpack(); // Get time stamp igtlUint32 sec; igtlUint32 nanosec; this->m_Header->GetTimeStamp(this->m_TimeStamp); this->m_TimeStamp->GetTimeStamp(&sec, &nanosec); //std::cerr << "Time stamp: " // << sec << "." << std::setw(9) << std::setfill('0') // << nanosec << std::endl; // Look for a message handler that matches to the message type. int found = 0; std::vector< MessageHandler* >::iterator iter; for (iter = this->m_MessageHandlerList.begin(); iter != this->m_MessageHandlerList.end(); iter ++) { #if OpenIGTLink_HEADER_VERSION >= 2 if ( this->m_Header->GetMessageType() == (*iter)->GetMessageType() ) #else if (strcmp(this->m_Header->GetDeviceType(), (*iter)->GetMessageType()) == 0) #endif { this->m_CurrentMessageHandler = *iter; found = 1; break; } } // If there is no message handler, skip the message if (!found) { #if OpenIGTLink_HEADER_VERSION >= 2 std::cerr << "Receiving: " << this->m_Header->GetMessageType() << std::endl; #else std::cerr << "Receiving: " << this->m_Header->GetDeviceType() << std::endl; #endif this->m_Socket->Skip(this->m_Header->GetBodySizeToRead(), 0); // Reset the index counter to be ready for the next message this->m_CurrentReadIndex = 0; this->m_HeaderDeserialized = 0; return 1; } this->m_HeaderDeserialized = 1; } int r = this->m_CurrentMessageHandler->ReceiveMessage(this->m_Socket, this->m_Header, this->m_CurrentReadIndex-IGTL_HEADER_SIZE); if (r == this->m_Header->GetBodySizeToRead()) { this->m_CurrentReadIndex = 0; this->m_HeaderDeserialized = 0; } else { this->m_CurrentReadIndex += IGTL_HEADER_SIZE + r; } return 1; } int SessionManager::PushMessage(MessageBase* message) { if (message && this->m_Socket.IsNotNull() && this->m_Socket->GetConnected()) // if client connected { return this->m_Socket->Send(message->GetBufferPointer(), message->GetBufferSize()); } else { return 0; } } } <|endoftext|>
<commit_before>#include <sirius.h> void test_alltoall(int num_gkvec, int num_bands) { Communicator comm(MPI_COMM_WORLD); splindex<block> spl_gkvec(num_gkvec, comm.size(), comm.rank()); splindex<block> spl_bands(num_bands, comm.size(), comm.rank()); matrix<double_complex> a(spl_gkvec.local_size(), num_bands); matrix<double_complex> b(num_gkvec, spl_bands.local_size()); for (int i = 0; i < num_bands; i++) { for (int j = 0; j < (int)spl_gkvec.local_size(); j++) a(j, i) = type_wrapper<double_complex>::random(); } b.zero(); auto h = a.hash(); std::vector<int> sendcounts(comm.size()); std::vector<int> sdispls(comm.size()); std::vector<int> recvcounts(comm.size()); std::vector<int> rdispls(comm.size()); sdispls[0] = 0; rdispls[0] = 0; for (int rank = 0; rank < comm.size(); rank++) { sendcounts[rank] = int(spl_gkvec.local_size() * spl_bands.local_size(rank)); if (rank) sdispls[rank] = sdispls[rank - 1] + sendcounts[rank - 1]; recvcounts[rank] = int(spl_gkvec.local_size(rank) * spl_bands.local_size()); if (rank) rdispls[rank] = rdispls[rank - 1] + recvcounts[rank - 1]; } sirius::Timer t("alltoall", comm); comm.alltoall(&a(0, 0), &sendcounts[0], &sdispls[0], &b(0, 0), &recvcounts[0], &rdispls[0]); double tval = t.stop(); sdispls[0] = 0; rdispls[0] = 0; for (int rank = 0; rank < comm.size(); rank++) { sendcounts[rank] = int(spl_gkvec.local_size(rank) * spl_bands.local_size()); if (rank) sdispls[rank] = sdispls[rank - 1] + sendcounts[rank - 1]; recvcounts[rank] = int(spl_gkvec.local_size() * spl_bands.local_size(rank)); if (rank) rdispls[rank] = rdispls[rank - 1] + recvcounts[rank - 1]; } t.start(); comm.alltoall(&b(0, 0), &sendcounts[0], &sdispls[0], &a(0, 0), &recvcounts[0], &rdispls[0]); tval = t.stop(); if (a.hash() != h) printf("wrong hash\n"); if (Platform::rank() == 0) { printf("alltoall time (sec) : %12.6f\n", tval); } } int main(int argn, char **argv) { cmd_args args; args.register_key("--num_gkvec=", "{int} number of Gk-vectors"); args.register_key("--num_bands=", "{int} number of bands"); args.register_key("--repeat=", "{int} repeat test number of times"); args.parse_args(argn, argv); if (argn == 1) { printf("Usage: %s [options]\n", argv[0]); args.print_help(); exit(0); } int num_gkvec = args.value<int>("num_gkvec"); int num_bands = args.value<int>("num_bands"); int repeat = args.value<int>("repeat", 1); Platform::initialize(true); for (int i = 0; i < repeat; i++) test_alltoall(num_gkvec, num_bands); Platform::finalize(); } <commit_msg>test a2a<commit_after>#include <sirius.h> void test_alltoall(int num_gkvec, int num_bands) { Communicator comm(MPI_COMM_WORLD); splindex<block> spl_gkvec(num_gkvec, comm.size(), comm.rank()); splindex<block> spl_bands(num_bands, comm.size(), comm.rank()); matrix<double_complex> a(spl_gkvec.local_size(), num_bands); matrix<double_complex> b(num_gkvec, spl_bands.local_size()); for (int i = 0; i < num_bands; i++) { for (int j = 0; j < (int)spl_gkvec.local_size(); j++) a(j, i) = type_wrapper<double_complex>::random(); } b.zero(); auto h = a.hash(); std::vector<int> sendcounts(comm.size()); std::vector<int> sdispls(comm.size()); std::vector<int> recvcounts(comm.size()); std::vector<int> rdispls(comm.size()); sdispls[0] = 0; rdispls[0] = 0; for (int rank = 0; rank < comm.size(); rank++) { sendcounts[rank] = int(spl_gkvec.local_size() * spl_bands.local_size(rank)); if (rank) sdispls[rank] = sdispls[rank - 1] + sendcounts[rank - 1]; recvcounts[rank] = int(spl_gkvec.local_size(rank) * spl_bands.local_size()); if (rank) rdispls[rank] = rdispls[rank - 1] + recvcounts[rank - 1]; } sirius::Timer t("alltoall", comm); comm.alltoall(&a(0, 0), &sendcounts[0], &sdispls[0], &b(0, 0), &recvcounts[0], &rdispls[0]); double tval = t.stop(); sdispls[0] = 0; rdispls[0] = 0; for (int rank = 0; rank < comm.size(); rank++) { sendcounts[rank] = int(spl_gkvec.local_size(rank) * spl_bands.local_size()); if (rank) sdispls[rank] = sdispls[rank - 1] + sendcounts[rank - 1]; recvcounts[rank] = int(spl_gkvec.local_size() * spl_bands.local_size(rank)); if (rank) rdispls[rank] = rdispls[rank - 1] + recvcounts[rank - 1]; } t.start(); comm.alltoall(&b(0, 0), &sendcounts[0], &sdispls[0], &a(0, 0), &recvcounts[0], &rdispls[0]); tval = t.stop(); if (a.hash() != h) printf("wrong hash\n"); if (Platform::rank() == 0) { printf("alltoall time (sec) : %12.6f\n", tval); } } void test_alltoall_v2() { Communicator comm(MPI_COMM_WORLD); std::vector<int> counts_in(comm.size(), 16); std::vector<double_complex> sbuf(10); std::vector<int> counts_out(comm.size(), 0); counts_out[0] = 16 * comm.size(); std::vector<double_complex> rbuf(counts_out[comm.rank()]); auto a2a_desc = comm.map_alltoall(counts_in, counts_out); comm.alltoall(&sbuf[0], &a2a_desc.sendcounts[0], &a2a_desc.sdispls[0], &rbuf[0], &a2a_desc.recvcounts[0], &a2a_desc.rdispls[0]); } void test_alltoall_v3() { Communicator comm(MPI_COMM_WORLD); std::vector<int> counts_in(comm.size(), 16); std::vector<double_complex> sbuf(10); std::vector<int> counts_out(comm.size(), 0); if (comm.size() == 1) { counts_out[0] = 16 * comm.size(); } else { counts_out[0] = 8 * comm.size(); counts_out[1] = 8 * comm.size(); } std::vector<double_complex> rbuf(counts_out[comm.rank()]); auto a2a_desc = comm.map_alltoall(counts_in, counts_out); comm.alltoall(&sbuf[0], &a2a_desc.sendcounts[0], &a2a_desc.sdispls[0], &rbuf[0], &a2a_desc.recvcounts[0], &a2a_desc.rdispls[0]); } int main(int argn, char **argv) { cmd_args args; args.register_key("--num_gkvec=", "{int} number of Gk-vectors"); args.register_key("--num_bands=", "{int} number of bands"); args.register_key("--repeat=", "{int} repeat test number of times"); args.parse_args(argn, argv); if (argn == 1) { printf("Usage: %s [options]\n", argv[0]); args.print_help(); exit(0); } int num_gkvec = args.value<int>("num_gkvec"); int num_bands = args.value<int>("num_bands"); int repeat = args.value<int>("repeat", 1); Platform::initialize(true); for (int i = 0; i < repeat; i++) test_alltoall(num_gkvec, num_bands); test_alltoall_v2(); test_alltoall_v3(); Platform::finalize(); } <|endoftext|>
<commit_before>// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions 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 "SurgSim/Graphics/OsgGroup.h" #include "SurgSim/Framework/Assert.h" #include "SurgSim/Graphics/OsgRepresentation.h" using SurgSim::Graphics::OsgRepresentation; using SurgSim::Graphics::OsgGroup; OsgGroup::OsgGroup(const std::string& name) : SurgSim::Graphics::Group(name), m_isActive(true), m_switch(new osg::Switch()) { m_switch->getOrCreateStateSet()->setGlobalDefaults(); m_switch->setName(name + " Switch"); }; void OsgGroup::setActive(bool val) { m_isActive= val; if (m_isActive) { m_switch->setAllChildrenOn(); } else { m_switch->setAllChildrenOff(); } } bool OsgGroup::isActive() const { return m_isActive; } bool OsgGroup::add(std::shared_ptr<SurgSim::Graphics::Representation> representation) { std::shared_ptr<OsgRepresentation> osgRepresentation = std::dynamic_pointer_cast<OsgRepresentation>(representation); if (osgRepresentation && Group::add(osgRepresentation)) { m_switch->addChild(osgRepresentation->getOsgNode()); m_switch->setChildValue(osgRepresentation->getOsgNode(), m_isActive && osgRepresentation->isActive()); return true; } else { return false; } } bool OsgGroup::append(std::shared_ptr<SurgSim::Graphics::Group> group) { std::shared_ptr<OsgGroup> osgGroup = std::dynamic_pointer_cast<OsgGroup>(group); if (osgGroup && Group::append(osgGroup)) { return true; } else { return false; } } bool OsgGroup::remove(std::shared_ptr<SurgSim::Graphics::Representation> representation) { std::shared_ptr<OsgRepresentation> osgRepresentation = std::dynamic_pointer_cast<OsgRepresentation>(representation); if (osgRepresentation && Group::remove(osgRepresentation)) { m_switch->removeChild(osgRepresentation->getOsgNode()); return true; } else { return false; } } void OsgGroup::clear() { while (!getMembers().empty()) { std::shared_ptr<Representation> representation = getMembers().front(); SURGSIM_ASSERT(remove(representation)) << "Removal of representation " << representation->getName() << " failed while attempting to clear group " << getName() << "!"; } } osg::ref_ptr<osg::Group> OsgGroup::getOsgGroup() const { return m_switch; }<commit_msg>Roll back changes in OsgGroup<commit_after>// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions 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 "SurgSim/Graphics/OsgGroup.h" #include "SurgSim/Framework/Assert.h" #include "SurgSim/Graphics/OsgRepresentation.h" using SurgSim::Graphics::OsgRepresentation; using SurgSim::Graphics::OsgGroup; OsgGroup::OsgGroup(const std::string& name) : SurgSim::Graphics::Group(name), m_isActive(true), m_switch(new osg::Switch()) { m_switch->getOrCreateStateSet()->setGlobalDefaults(); m_switch->setName(name + " Switch"); }; void OsgGroup::setActive(bool val) { m_isActive= val; if (m_isActive) { m_switch->setAllChildrenOn(); } else { m_switch->setAllChildrenOff(); } } bool OsgGroup::isActive() const { return m_isActive; } bool OsgGroup::add(std::shared_ptr<SurgSim::Graphics::Representation> representation) { std::shared_ptr<OsgRepresentation> osgRepresentation = std::dynamic_pointer_cast<OsgRepresentation>(representation); if (osgRepresentation && Group::add(osgRepresentation)) { m_switch->addChild(osgRepresentation->getOsgNode()); m_switch->setChildValue(osgRepresentation->getOsgNode(), m_isActive); return true; } else { return false; } } bool OsgGroup::append(std::shared_ptr<SurgSim::Graphics::Group> group) { std::shared_ptr<OsgGroup> osgGroup = std::dynamic_pointer_cast<OsgGroup>(group); if (osgGroup && Group::append(osgGroup)) { return true; } else { return false; } } bool OsgGroup::remove(std::shared_ptr<SurgSim::Graphics::Representation> representation) { std::shared_ptr<OsgRepresentation> osgRepresentation = std::dynamic_pointer_cast<OsgRepresentation>(representation); if (osgRepresentation && Group::remove(osgRepresentation)) { m_switch->removeChild(osgRepresentation->getOsgNode()); return true; } else { return false; } } void OsgGroup::clear() { while (!getMembers().empty()) { std::shared_ptr<Representation> representation = getMembers().front(); SURGSIM_ASSERT(remove(representation)) << "Removal of representation " << representation->getName() << " failed while attempting to clear group " << getName() << "!"; } } osg::ref_ptr<osg::Group> OsgGroup::getOsgGroup() const { return m_switch; }<|endoftext|>
<commit_before>//===- IntrinsicEmitter.cpp - Generate intrinsic information --------------===// // // The LLVM Compiler Infrastructure // // This file was developed by Chris Lattner and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This tablegen backend emits information about intrinsic functions. // //===----------------------------------------------------------------------===// #include "IntrinsicEmitter.h" #include "Record.h" #include "llvm/ADT/StringExtras.h" #include <algorithm> using namespace llvm; //===----------------------------------------------------------------------===// // IntrinsicEmitter Implementation //===----------------------------------------------------------------------===// void IntrinsicEmitter::run(std::ostream &OS) { EmitSourceFileHeader("Intrinsic Function Source Fragment", OS); std::vector<CodeGenIntrinsic> Ints = LoadIntrinsics(Records); // Emit the enum information. EmitEnumInfo(Ints, OS); // Emit the intrinsic ID -> name table. EmitIntrinsicToNameTable(Ints, OS); // Emit the function name recognizer. EmitFnNameRecognizer(Ints, OS); // Emit the intrinsic verifier. EmitVerifier(Ints, OS); // Emit mod/ref info for each function. EmitModRefInfo(Ints, OS); // Emit table of non-memory accessing intrinsics. EmitNoMemoryInfo(Ints, OS); // Emit side effect info for each intrinsic. EmitSideEffectInfo(Ints, OS); // Emit a list of intrinsics with corresponding GCC builtins. EmitGCCBuiltinList(Ints, OS); // Emit code to translate GCC builtins into LLVM intrinsics. EmitIntrinsicToGCCBuiltinMap(Ints, OS); } void IntrinsicEmitter::EmitEnumInfo(const std::vector<CodeGenIntrinsic> &Ints, std::ostream &OS) { OS << "// Enum values for Intrinsics.h\n"; OS << "#ifdef GET_INTRINSIC_ENUM_VALUES\n"; for (unsigned i = 0, e = Ints.size(); i != e; ++i) { OS << " " << Ints[i].EnumName; OS << ((i != e-1) ? ", " : " "); OS << std::string(40-Ints[i].EnumName.size(), ' ') << "// " << Ints[i].Name << "\n"; } OS << "#endif\n\n"; } void IntrinsicEmitter:: EmitFnNameRecognizer(const std::vector<CodeGenIntrinsic> &Ints, std::ostream &OS) { // Build a function name -> intrinsic name mapping. std::map<std::string, std::string> IntMapping; for (unsigned i = 0, e = Ints.size(); i != e; ++i) IntMapping[Ints[i].Name] = Ints[i].EnumName; OS << "// Function name -> enum value recognizer code.\n"; OS << "#ifdef GET_FUNCTION_RECOGNIZER\n"; OS << " switch (Name[5]) {\n"; OS << " default: break;\n"; // Emit the intrinsics in sorted order. char LastChar = 0; for (std::map<std::string, std::string>::iterator I = IntMapping.begin(), E = IntMapping.end(); I != E; ++I) { if (I->first[5] != LastChar) { LastChar = I->first[5]; OS << " case '" << LastChar << "':\n"; } OS << " if (Name == \"" << I->first << "\") return Intrinsic::" << I->second << ";\n"; } OS << " }\n"; OS << " // The 'llvm.' namespace is reserved!\n"; OS << " assert(0 && \"Unknown LLVM intrinsic function!\");\n"; OS << "#endif\n\n"; } void IntrinsicEmitter:: EmitIntrinsicToNameTable(const std::vector<CodeGenIntrinsic> &Ints, std::ostream &OS) { std::vector<std::string> Names; for (unsigned i = 0, e = Ints.size(); i != e; ++i) Names.push_back(Ints[i].Name); std::sort(Names.begin(), Names.end()); OS << "// Intrinsic ID to name table\n"; OS << "#ifdef GET_INTRINSIC_NAME_TABLE\n"; OS << " // Note that entry #0 is the invalid intrinsic!\n"; for (unsigned i = 0, e = Names.size(); i != e; ++i) OS << " \"" << Names[i] << "\",\n"; OS << "#endif\n\n"; } static void EmitTypeVerify(std::ostream &OS, const std::string &Val, Record *ArgType) { OS << " Assert1(" << Val << "->getTypeID() == " << ArgType->getValueAsString("TypeVal") << ",\n" << " \"Illegal intrinsic type!\", IF);\n"; // If this is a packed type, check that the subtype and size are correct. if (ArgType->isSubClassOf("LLVMPackedType")) { Record *SubType = ArgType->getValueAsDef("ElTy"); OS << " Assert1(cast<PackedType>(" << Val << ")->getElementType()->getTypeID() == " << SubType->getValueAsString("TypeVal") << ",\n" << " \"Illegal intrinsic type!\", IF);\n"; OS << " Assert1(cast<PackedType>(" << Val << ")->getNumElements() == " << ArgType->getValueAsInt("NumElts") << ",\n" << " \"Illegal intrinsic type!\", IF);\n"; } } void IntrinsicEmitter::EmitVerifier(const std::vector<CodeGenIntrinsic> &Ints, std::ostream &OS) { OS << "// Verifier::visitIntrinsicFunctionCall code.\n"; OS << "#ifdef GET_INTRINSIC_VERIFIER\n"; OS << " switch (ID) {\n"; OS << " default: assert(0 && \"Invalid intrinsic!\");\n"; for (unsigned i = 0, e = Ints.size(); i != e; ++i) { OS << " case Intrinsic::" << Ints[i].EnumName << ":\t\t// " << Ints[i].Name << "\n"; OS << " Assert1(FTy->getNumParams() == " << Ints[i].ArgTypes.size()-1 << ",\n" << " \"Illegal # arguments for intrinsic function!\", IF);\n"; EmitTypeVerify(OS, "FTy->getReturnType()", Ints[i].ArgTypeDefs[0]); for (unsigned j = 1; j != Ints[i].ArgTypes.size(); ++j) EmitTypeVerify(OS, "FTy->getParamType(" + utostr(j-1) + ")", Ints[i].ArgTypeDefs[j]); OS << " break;\n"; } OS << " }\n"; OS << "#endif\n\n"; } void IntrinsicEmitter::EmitModRefInfo(const std::vector<CodeGenIntrinsic> &Ints, std::ostream &OS) { OS << "// BasicAliasAnalysis code.\n"; OS << "#ifdef GET_MODREF_BEHAVIOR\n"; for (unsigned i = 0, e = Ints.size(); i != e; ++i) { switch (Ints[i].ModRef) { default: break; case CodeGenIntrinsic::NoMem: OS << " NoMemoryTable.push_back(\"" << Ints[i].Name << "\");\n"; break; case CodeGenIntrinsic::ReadArgMem: case CodeGenIntrinsic::ReadMem: OS << " OnlyReadsMemoryTable.push_back(\"" << Ints[i].Name << "\");\n"; break; } } OS << "#endif\n\n"; } void IntrinsicEmitter:: EmitNoMemoryInfo(const std::vector<CodeGenIntrinsic> &Ints, std::ostream &OS) { OS << "// SelectionDAGIsel code.\n"; OS << "#ifdef GET_NO_MEMORY_INTRINSICS\n"; OS << " switch (IntrinsicID) {\n"; OS << " default: break;\n"; for (unsigned i = 0, e = Ints.size(); i != e; ++i) { switch (Ints[i].ModRef) { default: break; case CodeGenIntrinsic::NoMem: OS << " case Intrinsic::" << Ints[i].EnumName << ":\n"; break; } } OS << " return true; // These intrinsics have no side effects.\n"; OS << " }\n"; OS << "#endif\n\n"; } void IntrinsicEmitter:: EmitSideEffectInfo(const std::vector<CodeGenIntrinsic> &Ints, std::ostream &OS){ OS << "// isInstructionTriviallyDead code.\n"; OS << "#ifdef GET_SIDE_EFFECT_INFO\n"; OS << " switch (F->getIntrinsicID()) {\n"; OS << " default: break;\n"; for (unsigned i = 0, e = Ints.size(); i != e; ++i) { switch (Ints[i].ModRef) { default: break; case CodeGenIntrinsic::NoMem: case CodeGenIntrinsic::ReadArgMem: case CodeGenIntrinsic::ReadMem: OS << " case Intrinsic::" << Ints[i].EnumName << ":\n"; break; } } OS << " return true; // These intrinsics have no side effects.\n"; OS << " }\n"; OS << "#endif\n\n"; } void IntrinsicEmitter:: EmitGCCBuiltinList(const std::vector<CodeGenIntrinsic> &Ints, std::ostream &OS){ OS << "// Get the GCC builtin that corresponds to an LLVM intrinsic.\n"; OS << "#ifdef GET_GCC_BUILTIN_NAME\n"; OS << " switch (F->getIntrinsicID()) {\n"; OS << " default: BuiltinName = \"\"; break;\n"; for (unsigned i = 0, e = Ints.size(); i != e; ++i) { if (!Ints[i].GCCBuiltinName.empty()) { OS << " case Intrinsic::" << Ints[i].EnumName << ": BuiltinName = \"" << Ints[i].GCCBuiltinName << "\"; break;\n"; } } OS << " }\n"; OS << "#endif\n\n"; } void IntrinsicEmitter:: EmitIntrinsicToGCCBuiltinMap(const std::vector<CodeGenIntrinsic> &Ints, std::ostream &OS) { typedef std::map<std::pair<std::string, std::string>, std::string> BIMTy; BIMTy BuiltinMap; for (unsigned i = 0, e = Ints.size(); i != e; ++i) { if (!Ints[i].GCCBuiltinName.empty()) { std::pair<std::string, std::string> Key(Ints[i].GCCBuiltinName, Ints[i].TargetPrefix); if (!BuiltinMap.insert(std::make_pair(Key, Ints[i].EnumName)).second) throw "Intrinsic '" + Ints[i].TheDef->getName() + "': duplicate GCC builtin name!"; } } OS << "// Get the LLVM intrinsic that corresponds to a GCC builtin.\n"; OS << "// This is used by the C front-end. The GCC builtin name is passed\n"; OS << "// in as BuiltinName, and a target prefix (e.g. 'ppc') is passed\n"; OS << "// in as TargetPrefix. The result is assigned to 'IntrinsicID'.\n"; OS << "#ifdef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN\n"; OS << " if (0);\n"; // Note: this could emit significantly better code if we cared. for (BIMTy::iterator I = BuiltinMap.begin(), E = BuiltinMap.end();I != E;++I){ OS << " else if ("; if (!I->first.second.empty()) { // Emit this as a strcmp, so it can be constant folded by the FE. OS << "!strcmp(TargetPrefix, \"" << I->first.second << "\") &&\n" << " "; } OS << "!strcmp(BuiltinName, \"" << I->first.first << "\"))\n"; OS << " IntrinsicID = Intrinsic::" << I->second << ";\n"; } OS << " else\n"; OS << " IntrinsicID = Intrinsic::not_intrinsic;\n"; OS << "#endif\n\n"; } <commit_msg>Don't sort the names before outputing the intrinsic name table. It causes a mismatch against the enum table. This is a part of Sabre's master plan to drive me nuts with subtle bugs that happens to only affect x86 be. :-)<commit_after>//===- IntrinsicEmitter.cpp - Generate intrinsic information --------------===// // // The LLVM Compiler Infrastructure // // This file was developed by Chris Lattner and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This tablegen backend emits information about intrinsic functions. // //===----------------------------------------------------------------------===// #include "IntrinsicEmitter.h" #include "Record.h" #include "llvm/ADT/StringExtras.h" #include <algorithm> using namespace llvm; //===----------------------------------------------------------------------===// // IntrinsicEmitter Implementation //===----------------------------------------------------------------------===// void IntrinsicEmitter::run(std::ostream &OS) { EmitSourceFileHeader("Intrinsic Function Source Fragment", OS); std::vector<CodeGenIntrinsic> Ints = LoadIntrinsics(Records); // Emit the enum information. EmitEnumInfo(Ints, OS); // Emit the intrinsic ID -> name table. EmitIntrinsicToNameTable(Ints, OS); // Emit the function name recognizer. EmitFnNameRecognizer(Ints, OS); // Emit the intrinsic verifier. EmitVerifier(Ints, OS); // Emit mod/ref info for each function. EmitModRefInfo(Ints, OS); // Emit table of non-memory accessing intrinsics. EmitNoMemoryInfo(Ints, OS); // Emit side effect info for each intrinsic. EmitSideEffectInfo(Ints, OS); // Emit a list of intrinsics with corresponding GCC builtins. EmitGCCBuiltinList(Ints, OS); // Emit code to translate GCC builtins into LLVM intrinsics. EmitIntrinsicToGCCBuiltinMap(Ints, OS); } void IntrinsicEmitter::EmitEnumInfo(const std::vector<CodeGenIntrinsic> &Ints, std::ostream &OS) { OS << "// Enum values for Intrinsics.h\n"; OS << "#ifdef GET_INTRINSIC_ENUM_VALUES\n"; for (unsigned i = 0, e = Ints.size(); i != e; ++i) { OS << " " << Ints[i].EnumName; OS << ((i != e-1) ? ", " : " "); OS << std::string(40-Ints[i].EnumName.size(), ' ') << "// " << Ints[i].Name << "\n"; } OS << "#endif\n\n"; } void IntrinsicEmitter:: EmitFnNameRecognizer(const std::vector<CodeGenIntrinsic> &Ints, std::ostream &OS) { // Build a function name -> intrinsic name mapping. std::map<std::string, std::string> IntMapping; for (unsigned i = 0, e = Ints.size(); i != e; ++i) IntMapping[Ints[i].Name] = Ints[i].EnumName; OS << "// Function name -> enum value recognizer code.\n"; OS << "#ifdef GET_FUNCTION_RECOGNIZER\n"; OS << " switch (Name[5]) {\n"; OS << " default: break;\n"; // Emit the intrinsics in sorted order. char LastChar = 0; for (std::map<std::string, std::string>::iterator I = IntMapping.begin(), E = IntMapping.end(); I != E; ++I) { if (I->first[5] != LastChar) { LastChar = I->first[5]; OS << " case '" << LastChar << "':\n"; } OS << " if (Name == \"" << I->first << "\") return Intrinsic::" << I->second << ";\n"; } OS << " }\n"; OS << " // The 'llvm.' namespace is reserved!\n"; OS << " assert(0 && \"Unknown LLVM intrinsic function!\");\n"; OS << "#endif\n\n"; } void IntrinsicEmitter:: EmitIntrinsicToNameTable(const std::vector<CodeGenIntrinsic> &Ints, std::ostream &OS) { OS << "// Intrinsic ID to name table\n"; OS << "#ifdef GET_INTRINSIC_NAME_TABLE\n"; OS << " // Note that entry #0 is the invalid intrinsic!\n"; for (unsigned i = 0, e = Ints.size(); i != e; ++i) OS << " \"" << Ints[i].Name << "\",\n"; OS << "#endif\n\n"; } static void EmitTypeVerify(std::ostream &OS, const std::string &Val, Record *ArgType) { OS << " Assert1(" << Val << "->getTypeID() == " << ArgType->getValueAsString("TypeVal") << ",\n" << " \"Illegal intrinsic type!\", IF);\n"; // If this is a packed type, check that the subtype and size are correct. if (ArgType->isSubClassOf("LLVMPackedType")) { Record *SubType = ArgType->getValueAsDef("ElTy"); OS << " Assert1(cast<PackedType>(" << Val << ")->getElementType()->getTypeID() == " << SubType->getValueAsString("TypeVal") << ",\n" << " \"Illegal intrinsic type!\", IF);\n"; OS << " Assert1(cast<PackedType>(" << Val << ")->getNumElements() == " << ArgType->getValueAsInt("NumElts") << ",\n" << " \"Illegal intrinsic type!\", IF);\n"; } } void IntrinsicEmitter::EmitVerifier(const std::vector<CodeGenIntrinsic> &Ints, std::ostream &OS) { OS << "// Verifier::visitIntrinsicFunctionCall code.\n"; OS << "#ifdef GET_INTRINSIC_VERIFIER\n"; OS << " switch (ID) {\n"; OS << " default: assert(0 && \"Invalid intrinsic!\");\n"; for (unsigned i = 0, e = Ints.size(); i != e; ++i) { OS << " case Intrinsic::" << Ints[i].EnumName << ":\t\t// " << Ints[i].Name << "\n"; OS << " Assert1(FTy->getNumParams() == " << Ints[i].ArgTypes.size()-1 << ",\n" << " \"Illegal # arguments for intrinsic function!\", IF);\n"; EmitTypeVerify(OS, "FTy->getReturnType()", Ints[i].ArgTypeDefs[0]); for (unsigned j = 1; j != Ints[i].ArgTypes.size(); ++j) EmitTypeVerify(OS, "FTy->getParamType(" + utostr(j-1) + ")", Ints[i].ArgTypeDefs[j]); OS << " break;\n"; } OS << " }\n"; OS << "#endif\n\n"; } void IntrinsicEmitter::EmitModRefInfo(const std::vector<CodeGenIntrinsic> &Ints, std::ostream &OS) { OS << "// BasicAliasAnalysis code.\n"; OS << "#ifdef GET_MODREF_BEHAVIOR\n"; for (unsigned i = 0, e = Ints.size(); i != e; ++i) { switch (Ints[i].ModRef) { default: break; case CodeGenIntrinsic::NoMem: OS << " NoMemoryTable.push_back(\"" << Ints[i].Name << "\");\n"; break; case CodeGenIntrinsic::ReadArgMem: case CodeGenIntrinsic::ReadMem: OS << " OnlyReadsMemoryTable.push_back(\"" << Ints[i].Name << "\");\n"; break; } } OS << "#endif\n\n"; } void IntrinsicEmitter:: EmitNoMemoryInfo(const std::vector<CodeGenIntrinsic> &Ints, std::ostream &OS) { OS << "// SelectionDAGIsel code.\n"; OS << "#ifdef GET_NO_MEMORY_INTRINSICS\n"; OS << " switch (IntrinsicID) {\n"; OS << " default: break;\n"; for (unsigned i = 0, e = Ints.size(); i != e; ++i) { switch (Ints[i].ModRef) { default: break; case CodeGenIntrinsic::NoMem: OS << " case Intrinsic::" << Ints[i].EnumName << ":\n"; break; } } OS << " return true; // These intrinsics have no side effects.\n"; OS << " }\n"; OS << "#endif\n\n"; } void IntrinsicEmitter:: EmitSideEffectInfo(const std::vector<CodeGenIntrinsic> &Ints, std::ostream &OS){ OS << "// isInstructionTriviallyDead code.\n"; OS << "#ifdef GET_SIDE_EFFECT_INFO\n"; OS << " switch (F->getIntrinsicID()) {\n"; OS << " default: break;\n"; for (unsigned i = 0, e = Ints.size(); i != e; ++i) { switch (Ints[i].ModRef) { default: break; case CodeGenIntrinsic::NoMem: case CodeGenIntrinsic::ReadArgMem: case CodeGenIntrinsic::ReadMem: OS << " case Intrinsic::" << Ints[i].EnumName << ":\n"; break; } } OS << " return true; // These intrinsics have no side effects.\n"; OS << " }\n"; OS << "#endif\n\n"; } void IntrinsicEmitter:: EmitGCCBuiltinList(const std::vector<CodeGenIntrinsic> &Ints, std::ostream &OS){ OS << "// Get the GCC builtin that corresponds to an LLVM intrinsic.\n"; OS << "#ifdef GET_GCC_BUILTIN_NAME\n"; OS << " switch (F->getIntrinsicID()) {\n"; OS << " default: BuiltinName = \"\"; break;\n"; for (unsigned i = 0, e = Ints.size(); i != e; ++i) { if (!Ints[i].GCCBuiltinName.empty()) { OS << " case Intrinsic::" << Ints[i].EnumName << ": BuiltinName = \"" << Ints[i].GCCBuiltinName << "\"; break;\n"; } } OS << " }\n"; OS << "#endif\n\n"; } void IntrinsicEmitter:: EmitIntrinsicToGCCBuiltinMap(const std::vector<CodeGenIntrinsic> &Ints, std::ostream &OS) { typedef std::map<std::pair<std::string, std::string>, std::string> BIMTy; BIMTy BuiltinMap; for (unsigned i = 0, e = Ints.size(); i != e; ++i) { if (!Ints[i].GCCBuiltinName.empty()) { std::pair<std::string, std::string> Key(Ints[i].GCCBuiltinName, Ints[i].TargetPrefix); if (!BuiltinMap.insert(std::make_pair(Key, Ints[i].EnumName)).second) throw "Intrinsic '" + Ints[i].TheDef->getName() + "': duplicate GCC builtin name!"; } } OS << "// Get the LLVM intrinsic that corresponds to a GCC builtin.\n"; OS << "// This is used by the C front-end. The GCC builtin name is passed\n"; OS << "// in as BuiltinName, and a target prefix (e.g. 'ppc') is passed\n"; OS << "// in as TargetPrefix. The result is assigned to 'IntrinsicID'.\n"; OS << "#ifdef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN\n"; OS << " if (0);\n"; // Note: this could emit significantly better code if we cared. for (BIMTy::iterator I = BuiltinMap.begin(), E = BuiltinMap.end();I != E;++I){ OS << " else if ("; if (!I->first.second.empty()) { // Emit this as a strcmp, so it can be constant folded by the FE. OS << "!strcmp(TargetPrefix, \"" << I->first.second << "\") &&\n" << " "; } OS << "!strcmp(BuiltinName, \"" << I->first.first << "\"))\n"; OS << " IntrinsicID = Intrinsic::" << I->second << ";\n"; } OS << " else\n"; OS << " IntrinsicID = Intrinsic::not_intrinsic;\n"; OS << "#endif\n\n"; } <|endoftext|>
<commit_before>// Copyright (c) 2016 Alexander Gallego. All rights reserved. // #include <iostream> #include <boost/filesystem.hpp> #include <glog/logging.h> #include "rpc/smf_gen/cpp_generator.h" #include "rpc/smf_gen/smf_file.h" DEFINE_bool(print_smf_gen_to_stderr, false, "prints to stderr the outputs of the generated header"); DEFINE_string(output_path, "", "prints to stderr the outputs of the generated header"); namespace smf_gen { bool generate(const flatbuffers::Parser &parser, std::string file_name) { smf_file fbfile(parser, file_name); std::string header_code = get_header_prologue(&fbfile) + get_header_includes(&fbfile) + get_header_services(&fbfile) + get_header_epilogue(&fbfile); if (FLAGS_print_smf_gen_to_stderr) { std::cerr << header_code << std::endl; } if (!FLAGS_output_path.empty()) { FLAGS_output_path = boost::filesystem::canonical(FLAGS_output_path.c_str()).string(); if (!flatbuffers::DirExists(FLAGS_output_path.c_str())) { LOG(ERROR) << "--output_path specified, but directory: " << FLAGS_output_path << " does not exist;"; return false; } boost::filesystem::path p(file_name); file_name = p.filename().string(); } const std::string fname = FLAGS_output_path.empty() ? file_name + ".smf.fb.h" : FLAGS_output_path + "/" + file_name + ".smf.fb.h"; LOG(INFO) << fname; return flatbuffers::SaveFile(fname.c_str(), header_code, false); } } // namespace smf_gen <commit_msg>smf_gen: add correct --output_path description<commit_after>// Copyright (c) 2016 Alexander Gallego. All rights reserved. // #include <iostream> #include <boost/filesystem.hpp> #include <glog/logging.h> #include "rpc/smf_gen/cpp_generator.h" #include "rpc/smf_gen/smf_file.h" DEFINE_bool(print_smf_gen_to_stderr, false, "prints to stderr the outputs of the generated header"); DEFINE_string(output_path, "", "output path of the generated files"); namespace smf_gen { bool generate(const flatbuffers::Parser &parser, std::string file_name) { smf_file fbfile(parser, file_name); std::string header_code = get_header_prologue(&fbfile) + get_header_includes(&fbfile) + get_header_services(&fbfile) + get_header_epilogue(&fbfile); if (FLAGS_print_smf_gen_to_stderr) { std::cerr << header_code << std::endl; } if (!FLAGS_output_path.empty()) { FLAGS_output_path = boost::filesystem::canonical(FLAGS_output_path.c_str()).string(); if (!flatbuffers::DirExists(FLAGS_output_path.c_str())) { LOG(ERROR) << "--output_path specified, but directory: " << FLAGS_output_path << " does not exist;"; return false; } boost::filesystem::path p(file_name); file_name = p.filename().string(); } const std::string fname = FLAGS_output_path.empty() ? file_name + ".smf.fb.h" : FLAGS_output_path + "/" + file_name + ".smf.fb.h"; LOG(INFO) << fname; return flatbuffers::SaveFile(fname.c_str(), header_code, false); } } // namespace smf_gen <|endoftext|>
<commit_before>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ #if !defined(XALANLOCATOR_HEADER_GUARD_1357924680) #define XALANLOCATOR_HEADER_GUARD_1357924680 // Base include file. Must be first. #include <xalanc/PlatformSupport/PlatformSupportDefinitions.hpp> #include <xercesc/sax/Locator.hpp> XALAN_CPP_NAMESPACE_BEGIN XALAN_USING_XERCES(Locator) /** * This class defines a base class for Locator derivations in Xalan. It was defined * because Xerces made changes in their Locator class which caused turbulence. */ class XALAN_PLATFORMSUPPORT_EXPORT XalanLocator : public Locator { public: typedef Locator ParentType; XalanLocator() {} virtual ~XalanLocator() {} virtual const XMLCh* getPublicId() const = 0; virtual const XMLCh* getSystemId() const = 0; virtual XalanFileLoc getLineNumber() const = 0; virtual XalanFileLoc getColumnNumber() const = 0; static const XalanDOMChar* getPublicId( const Locator* theLocator, const XalanDOMChar* theAlternateId = &s_dczero) { return theLocator == 0 ? theAlternateId : (theLocator->getPublicId() ? theLocator->getPublicId() : theAlternateId); } static const XalanDOMChar* getSystemId( const Locator* theLocator, const XalanDOMChar* theAlternateId = &s_dczero) { return theLocator == 0 ? theAlternateId : (theLocator->getSystemId() ? theLocator->getPublicId() : theAlternateId); } static XalanFileLoc getLineNumber(const ParentType* theLocator) { return theLocator == 0 ? getUnknownValue() : theLocator->getLineNumber(); } static XalanFileLoc getColumnNumber(const ParentType* theLocator) { return theLocator == 0 ? getUnknownValue() : theLocator->getColumnNumber(); } static XalanFileLoc getUnknownValue() { // The parser reports the maximum value of the XalanFileLoc // type for an unknown value. return ~static_cast<XalanFileLoc>(0); } static XalanFileLoc getUnknownDisplayValue() { // The parser reports the maximum value of the XalanFileLoc // type for an unknown value, but that is really non-sensical // for display purposes, so we use 0 instead. return static_cast<XalanFileLoc>(0); } static bool isUnknownValue(XalanFileLoc theLocation) { return theLocation == getUnknownValue(); } private: // Not defined... XalanLocator(const XalanLocator&); XalanLocator& operator=(const XalanLocator&); const static XalanDOMChar s_dczero = 0; }; XALAN_CPP_NAMESPACE_END #endif // PREFIXRESOLVER_HEADER_GUARD_1357924680 <commit_msg>XALANC-733 Ensure that XalanLocator::getSystemId() and getPublicId() do not return NULL<commit_after>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ #if !defined(XALANLOCATOR_HEADER_GUARD_1357924680) #define XALANLOCATOR_HEADER_GUARD_1357924680 // Base include file. Must be first. #include <xalanc/PlatformSupport/PlatformSupportDefinitions.hpp> #include <xercesc/sax/Locator.hpp> XALAN_CPP_NAMESPACE_BEGIN XALAN_USING_XERCES(Locator) /** * This class defines a base class for Locator derivations in Xalan. It was defined * because Xerces made changes in their Locator class which caused turbulence. */ class XALAN_PLATFORMSUPPORT_EXPORT XalanLocator : public Locator { public: typedef Locator ParentType; XalanLocator() {} virtual ~XalanLocator() {} virtual const XMLCh* getPublicId() const = 0; virtual const XMLCh* getSystemId() const = 0; virtual XalanFileLoc getLineNumber() const = 0; virtual XalanFileLoc getColumnNumber() const = 0; /** * Get the public identifier from a locator object. * @param theLocator A locator object inherited from Xerces. * @param theAlternateId A default name for a public identifier. * @return a null terminated XalanDOMChar string. */ static const XalanDOMChar* getPublicId( const Locator* theLocator, const XalanDOMChar* theAlternateId = getEmptyPtr()) { return theLocator == 0 ? theAlternateId : (theLocator->getPublicId() ? theLocator->getPublicId() : theAlternateId); } /** * Get the system identifier from a locator object. * @param theLocator A locator object inherited from Xerces. * @param theAlternateId A default name for a public identifier. * @return a null terminated XalanDOMChar string. */ static const XalanDOMChar* getSystemId( const Locator* theLocator, const XalanDOMChar* theAlternateId = getEmptyPtr()) { return theLocator == 0 ? theAlternateId : (theLocator->getSystemId() ? theLocator->getPublicId() : theAlternateId); } /** * Get the line number from a locator object. */ static XalanFileLoc getLineNumber(const ParentType* theLocator) { return theLocator == 0 ? getUnknownValue() : theLocator->getLineNumber(); } /** * Get the column number from a locator object. */ static XalanFileLoc getColumnNumber(const ParentType* theLocator) { return theLocator == 0 ? getUnknownValue() : theLocator->getColumnNumber(); } static XalanFileLoc getUnknownValue() { // The parser reports the maximum value of the XalanFileLoc // type for an unknown value. return ~static_cast<XalanFileLoc>(0); } static XalanFileLoc getUnknownDisplayValue() { // The parser reports the maximum value of the XalanFileLoc // type for an unknown value, but that is really non-sensical // for display purposes, so we use 0 instead. return static_cast<XalanFileLoc>(0); } static bool isUnknownValue(XalanFileLoc theLocation) { return theLocation == getUnknownValue(); } private: // Not defined... XalanLocator(const XalanLocator&); XalanLocator& operator=(const XalanLocator&); /** * Return static pointer to null XalanDOMChar. * This is crafted to overcome issues with compilers/linkers that * have problems initializing static integer members within a class. * * Replaces: static const int s_zero = 0; * Reference: &s_zero; */ static const XalanDOMChar * getEmptyPtr() { static const XalanDOMChar theZero = 0; static const XalanDOMChar * theEmpty = &theZero; return theEmpty; } }; XALAN_CPP_NAMESPACE_END #endif // PREFIXRESOLVER_HEADER_GUARD_1357924680 <|endoftext|>
<commit_before><commit_msg>removed printing of reference filename for non-root ranks<commit_after><|endoftext|>
<commit_before>#include "raiden.h" #include "geometry.h" #include "gtest.h" TEST(Vector3f,Add){ Vector3f v1(-1); Vector3f v2(1); auto v3=v1+v2; EXPECT_FLOAT_EQ(0.0, v3.x)<<"test operater+"; //这里隐式调用了Vector3的构造函数 v3+=0.5; EXPECT_FLOAT_EQ(0.5, v3.x)<<"test operater+="; v3+=std::numeric_limits<Float>::infinity(); EXPECT_FLOAT_EQ(std::numeric_limits<Float>::infinity(), v3.x)<<"test infinity"; } TEST(Vector3f,Minus){ Vector3f v1(1); Vector3f v2(1); auto v3=v1-v2; EXPECT_FLOAT_EQ(0.0, v3.x)<<"test operater-"; v3-=0.5; EXPECT_FLOAT_EQ(-0.5, v3.x)<<"test operater-="; v3-=std::numeric_limits<Float>::infinity(); EXPECT_FLOAT_EQ(-std::numeric_limits<Float>::infinity(), v3.x)<<"test infinity"; } TEST(Vector3f,Multi){ Vector3f v1(2); Vector3f v2(5); auto v3=v1*5; EXPECT_FLOAT_EQ(10, v3.x)<<"test operater*"; v3*=5; EXPECT_FLOAT_EQ(50, v3.x)<<"test operater*="; v3*=std::numeric_limits<Float>::infinity(); EXPECT_FLOAT_EQ(std::numeric_limits<Float>::infinity(), v3.x)<<"test infinity"; } TEST(Vector3f,Div){ Vector3f v1(1); auto v2=v1/5; EXPECT_FLOAT_EQ(0.2, v2.x)<<"test operater/"; v2/=0.2; EXPECT_FLOAT_EQ(1.0, v2.x)<<"test operater/="; v2/=std::numeric_limits<Float>::infinity(); EXPECT_FLOAT_EQ(0, v2.x)<<"test infinity"; } TEST(Vector3f,Conversion){ Vector3f v1(1); auto p1=Point3f(v1); EXPECT_FLOAT_EQ(p1.x,v1.x)<<"test Vector3f to Point3f conversion"; EXPECT_FLOAT_EQ(p1.y,v1.y)<<"test Vector3f to Point3f conversion"; EXPECT_FLOAT_EQ(p1.z,v1.z)<<"test Vector3f to Point3f conversion"; auto n1=Normal3f(v1); EXPECT_FLOAT_EQ(n1.x,v1.x)<<"test Normal3f to Point3f conversion"; EXPECT_FLOAT_EQ(n1.y,v1.y)<<"test Normal3f to Point3f conversion"; EXPECT_FLOAT_EQ(n1.z,v1.z)<<"test Normal3f to Point3f conversion"; } TEST(Vector3f,Dot){ Vector3f v1(1,1,1); Vector3f v2(5,6,7); auto v1Dotv2=Dot(v1,v2); EXPECT_FLOAT_EQ(18,v1Dotv2)<<"test Dot"; } TEST(Vector3f,Cross){ Vector3f v1(1,2,3); Vector3f v2(4,5,6); auto v3=Cross(v1,v2); EXPECT_EQ(Vector3f(-3,6,-3),v3)<<"test Cross"; Vector3f v4(1,1,1); Vector3f v5(1,1,1); auto v6=Cross(v4,v5); EXPECT_EQ(Vector3f(0,0,0),v6)<<"test degenerate Cross "; } TEST(Vector3f,Index){ Vector3f v1(1,2,3); EXPECT_FLOAT_EQ(1,v1[0])<<"test Index 0"; EXPECT_FLOAT_EQ(2,v1[1])<<"test Index 1"; EXPECT_FLOAT_EQ(3,v1[2])<<"test Index 2"; v1[0]=0; v1[1]=0; v1[2]=0; EXPECT_FLOAT_EQ(0,v1[0])<<"test Index 0"; EXPECT_FLOAT_EQ(0,v1[1])<<"test Index 1"; EXPECT_FLOAT_EQ(0,v1[2])<<"test Index 2"; } TEST(Vector3f,NSign){ Vector3f v1(1); auto v2=-v1; EXPECT_FLOAT_EQ(-1,v2.x)<<"test negative sign"; } TEST(Vector3f,Length){ Vector3f v1(0.5,0.5,0.5); auto l=v1.Length(); EXPECT_FLOAT_EQ(0.86602539,l)<<"test length op"; auto l2=v1.LengthSquared(); EXPECT_FLOAT_EQ(0.75,l2)<<"test length op"; } TEST(Vector2f,Add){ Vector2f v1(-1); Vector2f v2(1); auto v3=v1+v2; EXPECT_FLOAT_EQ(0.0, v3.x)<<"test operater+"; //这里隐式调用了Vector3的构造函数 v3+=0.5; EXPECT_FLOAT_EQ(0.5, v3.x)<<"test operater+="; v3+=std::numeric_limits<Float>::infinity(); EXPECT_FLOAT_EQ(std::numeric_limits<Float>::infinity(), v3.x)<<"test infinity"; } TEST(Vector2f,Minus){ Vector2f v1(1); Vector2f v2(1); auto v3=v1-v2; EXPECT_FLOAT_EQ(0.0, v3.x)<<"test operater-"; v3-=0.5; EXPECT_FLOAT_EQ(-0.5, v3.x)<<"test operater-="; v3-=std::numeric_limits<Float>::infinity(); EXPECT_FLOAT_EQ(-std::numeric_limits<Float>::infinity(), v3.x)<<"test infinity"; } TEST(Vector2f,Multi){ Vector2f v1(2); Vector2f v2(5); auto v3=v1*5; EXPECT_FLOAT_EQ(10, v3.x)<<"test operater*"; v3*=5; EXPECT_FLOAT_EQ(50, v3.x)<<"test operater*="; v3*=std::numeric_limits<Float>::infinity(); EXPECT_FLOAT_EQ(std::numeric_limits<Float>::infinity(), v3.x)<<"test infinity"; } TEST(Vector2f,Div){ Vector2f v1(1); auto v2=v1/5; EXPECT_FLOAT_EQ(0.2, v2.x)<<"test operater/"; v2/=0.2; EXPECT_FLOAT_EQ(1.0, v2.x)<<"test operater/="; v2/=std::numeric_limits<Float>::infinity(); EXPECT_FLOAT_EQ(0, v2.x)<<"test infinity"; } TEST(Vector2f,Conversion){ Vector2f v1(1); auto p1=Point2f(v1); EXPECT_FLOAT_EQ(p1.x,v1.x)<<"test Vector3f to Point3f conversion"; EXPECT_FLOAT_EQ(p1.y,v1.y)<<"test Vector3f to Point3f conversion"; } TEST(Normal3f,Faceforward){ Vector3f v=Vector3f(0.5,-0.5,0); Normal3f n=Normal3f(0,1,0); auto v2=Faceforward(v,n); EXPECT_EQ(Vector3f(-0.5,0.5,0),v2); } <commit_msg>添加一个Vector3i的除法单元测试<commit_after>#include "raiden.h" #include "geometry.h" #include "gtest.h" TEST(Vector3i,Div){ Vector3i v1(1); int f=2;; auto v3=v1/f; EXPECT_EQ(0, v3.x)<<"test operater+"; } TEST(Vector3f,Add){ Vector3f v1(-1); Vector3f v2(1); auto v3=v1+v2; EXPECT_FLOAT_EQ(0.0, v3.x)<<"test operater+"; //这里隐式调用了Vector3的构造函数 v3+=0.5; EXPECT_FLOAT_EQ(0.5, v3.x)<<"test operater+="; v3+=std::numeric_limits<Float>::infinity(); EXPECT_FLOAT_EQ(std::numeric_limits<Float>::infinity(), v3.x)<<"test infinity"; } TEST(Vector3f,Minus){ Vector3f v1(1); Vector3f v2(1); auto v3=v1-v2; EXPECT_FLOAT_EQ(0.0, v3.x)<<"test operater-"; v3-=0.5; EXPECT_FLOAT_EQ(-0.5, v3.x)<<"test operater-="; v3-=std::numeric_limits<Float>::infinity(); EXPECT_FLOAT_EQ(-std::numeric_limits<Float>::infinity(), v3.x)<<"test infinity"; } TEST(Vector3f,Multi){ Vector3f v1(2); Vector3f v2(5); auto v3=v1*5; EXPECT_FLOAT_EQ(10, v3.x)<<"test operater*"; v3*=5; EXPECT_FLOAT_EQ(50, v3.x)<<"test operater*="; v3*=std::numeric_limits<Float>::infinity(); EXPECT_FLOAT_EQ(std::numeric_limits<Float>::infinity(), v3.x)<<"test infinity"; } TEST(Vector3f,Div){ Vector3f v1(1); auto v2=v1/5; EXPECT_FLOAT_EQ(0.2, v2.x)<<"test operater/"; v2/=0.2; EXPECT_FLOAT_EQ(1.0, v2.x)<<"test operater/="; v2/=std::numeric_limits<Float>::infinity(); EXPECT_FLOAT_EQ(0, v2.x)<<"test infinity"; } TEST(Vector3f,Conversion){ Vector3f v1(1); auto p1=Point3f(v1); EXPECT_FLOAT_EQ(p1.x,v1.x)<<"test Vector3f to Point3f conversion"; EXPECT_FLOAT_EQ(p1.y,v1.y)<<"test Vector3f to Point3f conversion"; EXPECT_FLOAT_EQ(p1.z,v1.z)<<"test Vector3f to Point3f conversion"; auto n1=Normal3f(v1); EXPECT_FLOAT_EQ(n1.x,v1.x)<<"test Normal3f to Point3f conversion"; EXPECT_FLOAT_EQ(n1.y,v1.y)<<"test Normal3f to Point3f conversion"; EXPECT_FLOAT_EQ(n1.z,v1.z)<<"test Normal3f to Point3f conversion"; } TEST(Vector3f,Dot){ Vector3f v1(1,1,1); Vector3f v2(5,6,7); auto v1Dotv2=Dot(v1,v2); EXPECT_FLOAT_EQ(18,v1Dotv2)<<"test Dot"; } TEST(Vector3f,Cross){ Vector3f v1(1,2,3); Vector3f v2(4,5,6); auto v3=Cross(v1,v2); EXPECT_EQ(Vector3f(-3,6,-3),v3)<<"test Cross"; Vector3f v4(1,1,1); Vector3f v5(1,1,1); auto v6=Cross(v4,v5); EXPECT_EQ(Vector3f(0,0,0),v6)<<"test degenerate Cross "; } TEST(Vector3f,Index){ Vector3f v1(1,2,3); EXPECT_FLOAT_EQ(1,v1[0])<<"test Index 0"; EXPECT_FLOAT_EQ(2,v1[1])<<"test Index 1"; EXPECT_FLOAT_EQ(3,v1[2])<<"test Index 2"; v1[0]=0; v1[1]=0; v1[2]=0; EXPECT_FLOAT_EQ(0,v1[0])<<"test Index 0"; EXPECT_FLOAT_EQ(0,v1[1])<<"test Index 1"; EXPECT_FLOAT_EQ(0,v1[2])<<"test Index 2"; } TEST(Vector3f,NSign){ Vector3f v1(1); auto v2=-v1; EXPECT_FLOAT_EQ(-1,v2.x)<<"test negative sign"; } TEST(Vector3f,Length){ Vector3f v1(0.5,0.5,0.5); auto l=v1.Length(); EXPECT_FLOAT_EQ(0.86602539,l)<<"test length op"; auto l2=v1.LengthSquared(); EXPECT_FLOAT_EQ(0.75,l2)<<"test length op"; } TEST(Vector2f,Add){ Vector2f v1(-1); Vector2f v2(1); auto v3=v1+v2; EXPECT_FLOAT_EQ(0.0, v3.x)<<"test operater+"; //这里隐式调用了Vector3的构造函数 v3+=0.5; EXPECT_FLOAT_EQ(0.5, v3.x)<<"test operater+="; v3+=std::numeric_limits<Float>::infinity(); EXPECT_FLOAT_EQ(std::numeric_limits<Float>::infinity(), v3.x)<<"test infinity"; } TEST(Vector2f,Minus){ Vector2f v1(1); Vector2f v2(1); auto v3=v1-v2; EXPECT_FLOAT_EQ(0.0, v3.x)<<"test operater-"; v3-=0.5; EXPECT_FLOAT_EQ(-0.5, v3.x)<<"test operater-="; v3-=std::numeric_limits<Float>::infinity(); EXPECT_FLOAT_EQ(-std::numeric_limits<Float>::infinity(), v3.x)<<"test infinity"; } TEST(Vector2f,Multi){ Vector2f v1(2); Vector2f v2(5); auto v3=v1*5; EXPECT_FLOAT_EQ(10, v3.x)<<"test operater*"; v3*=5; EXPECT_FLOAT_EQ(50, v3.x)<<"test operater*="; v3*=std::numeric_limits<Float>::infinity(); EXPECT_FLOAT_EQ(std::numeric_limits<Float>::infinity(), v3.x)<<"test infinity"; } TEST(Vector2f,Div){ Vector2f v1(1); auto v2=v1/5; EXPECT_FLOAT_EQ(0.2, v2.x)<<"test operater/"; v2/=0.2; EXPECT_FLOAT_EQ(1.0, v2.x)<<"test operater/="; v2/=std::numeric_limits<Float>::infinity(); EXPECT_FLOAT_EQ(0, v2.x)<<"test infinity"; } TEST(Vector2f,Conversion){ Vector2f v1(1); auto p1=Point2f(v1); EXPECT_FLOAT_EQ(p1.x,v1.x)<<"test Vector3f to Point3f conversion"; EXPECT_FLOAT_EQ(p1.y,v1.y)<<"test Vector3f to Point3f conversion"; } TEST(Normal3f,Faceforward){ Vector3f v=Vector3f(0.5,-0.5,0); Normal3f n=Normal3f(0,1,0); auto v2=Faceforward(v,n); EXPECT_EQ(Vector3f(-0.5,0.5,0),v2); } <|endoftext|>
<commit_before>// Copyright (c) 2011 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 "webkit/plugins/ppapi/ppb_image_data_impl.h" #include <algorithm> #include <limits> #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "skia/ext/platform_canvas.h" #include "ppapi/c/pp_instance.h" #include "ppapi/c/pp_resource.h" #include "ppapi/c/ppb_image_data.h" #include "ppapi/c/trusted/ppb_image_data_trusted.h" #include "ppapi/thunk/thunk.h" #include "third_party/skia/include/core/SkColorPriv.h" #include "webkit/plugins/ppapi/common.h" #include "webkit/plugins/ppapi/ppapi_plugin_instance.h" using ::ppapi::thunk::PPB_ImageData_API; namespace webkit { namespace ppapi { PPB_ImageData_Impl::PPB_ImageData_Impl(PluginInstance* instance) : Resource(instance), format_(PP_IMAGEDATAFORMAT_BGRA_PREMUL), width_(0), height_(0) { } PPB_ImageData_Impl::~PPB_ImageData_Impl() { } // static PP_Resource PPB_ImageData_Impl::Create(PluginInstance* instance, PP_ImageDataFormat format, const PP_Size& size, PP_Bool init_to_zero) { scoped_refptr<PPB_ImageData_Impl> data(new PPB_ImageData_Impl(instance)); if (!data->Init(format, size.width, size.height, !!init_to_zero)) return 0; return data->GetReference(); } PPB_ImageData_API* PPB_ImageData_Impl::AsPPB_ImageData_API() { return this; } bool PPB_ImageData_Impl::Init(PP_ImageDataFormat format, int width, int height, bool init_to_zero) { // TODO(brettw) this should be called only on the main thread! // TODO(brettw) use init_to_zero when we implement caching. if (!IsImageDataFormatSupported(format)) return false; // Only support this one format for now. if (width <= 0 || height <= 0) return false; if (static_cast<int64>(width) * static_cast<int64>(height) >= std::numeric_limits<int32>::max()) return false; // Prevent overflow of signed 32-bit ints. platform_image_.reset( instance()->delegate()->CreateImage2D(width, height)); format_ = format; width_ = width; height_ = height; return !!platform_image_.get(); } PP_Bool PPB_ImageData_Impl::Describe(PP_ImageDataDesc* desc) { desc->format = format_; desc->size.width = width_; desc->size.height = height_; desc->stride = width_ * 4; return PP_TRUE; } void* PPB_ImageData_Impl::Map() { if (!mapped_canvas_.get()) { mapped_canvas_.reset(platform_image_->Map()); if (!mapped_canvas_.get()) return NULL; } const SkBitmap& bitmap = skia::GetTopDevice(*mapped_canvas_)->accessBitmap(true); // Our platform bitmaps are set to opaque by default, which we don't want. const_cast<SkBitmap&>(bitmap).setIsOpaque(false); bitmap.lockPixels(); return bitmap.getAddr32(0, 0); } void PPB_ImageData_Impl::Unmap() { // This is currently unimplemented, which is OK. The data will just always // be around once it's mapped. Chrome's TransportDIB isn't currently // unmappable without freeing it, but this may be something we want to support // in the future to save some memory. } int32_t PPB_ImageData_Impl::GetSharedMemory(int* handle, uint32_t* byte_count) { *handle = platform_image_->GetSharedMemoryHandle(byte_count); return PP_OK; } const SkBitmap* PPB_ImageData_Impl::GetMappedBitmap() const { if (!mapped_canvas_.get()) return NULL; return &skia::GetTopDevice(*mapped_canvas_)->accessBitmap(false); } void PPB_ImageData_Impl::Swap(PPB_ImageData_Impl* other) { swap(other->platform_image_, platform_image_); swap(other->mapped_canvas_, mapped_canvas_); std::swap(other->format_, format_); std::swap(other->width_, width_); std::swap(other->height_, height_); } } // namespace ppapi } // namespace webkit <commit_msg>Properly account for all color channels when checking for overflow in image creation.<commit_after>// Copyright (c) 2011 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 "webkit/plugins/ppapi/ppb_image_data_impl.h" #include <algorithm> #include <limits> #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "skia/ext/platform_canvas.h" #include "ppapi/c/pp_instance.h" #include "ppapi/c/pp_resource.h" #include "ppapi/c/ppb_image_data.h" #include "ppapi/c/trusted/ppb_image_data_trusted.h" #include "ppapi/thunk/thunk.h" #include "third_party/skia/include/core/SkColorPriv.h" #include "webkit/plugins/ppapi/common.h" #include "webkit/plugins/ppapi/ppapi_plugin_instance.h" using ::ppapi::thunk::PPB_ImageData_API; namespace webkit { namespace ppapi { PPB_ImageData_Impl::PPB_ImageData_Impl(PluginInstance* instance) : Resource(instance), format_(PP_IMAGEDATAFORMAT_BGRA_PREMUL), width_(0), height_(0) { } PPB_ImageData_Impl::~PPB_ImageData_Impl() { } // static PP_Resource PPB_ImageData_Impl::Create(PluginInstance* instance, PP_ImageDataFormat format, const PP_Size& size, PP_Bool init_to_zero) { scoped_refptr<PPB_ImageData_Impl> data(new PPB_ImageData_Impl(instance)); if (!data->Init(format, size.width, size.height, !!init_to_zero)) return 0; return data->GetReference(); } PPB_ImageData_API* PPB_ImageData_Impl::AsPPB_ImageData_API() { return this; } bool PPB_ImageData_Impl::Init(PP_ImageDataFormat format, int width, int height, bool init_to_zero) { // TODO(brettw) this should be called only on the main thread! // TODO(brettw) use init_to_zero when we implement caching. if (!IsImageDataFormatSupported(format)) return false; // Only support this one format for now. if (width <= 0 || height <= 0) return false; if (static_cast<int64>(width) * static_cast<int64>(height) * 4 >= std::numeric_limits<int32>::max()) return false; // Prevent overflow of signed 32-bit ints. platform_image_.reset( instance()->delegate()->CreateImage2D(width, height)); format_ = format; width_ = width; height_ = height; return !!platform_image_.get(); } PP_Bool PPB_ImageData_Impl::Describe(PP_ImageDataDesc* desc) { desc->format = format_; desc->size.width = width_; desc->size.height = height_; desc->stride = width_ * 4; return PP_TRUE; } void* PPB_ImageData_Impl::Map() { if (!mapped_canvas_.get()) { mapped_canvas_.reset(platform_image_->Map()); if (!mapped_canvas_.get()) return NULL; } const SkBitmap& bitmap = skia::GetTopDevice(*mapped_canvas_)->accessBitmap(true); // Our platform bitmaps are set to opaque by default, which we don't want. const_cast<SkBitmap&>(bitmap).setIsOpaque(false); bitmap.lockPixels(); return bitmap.getAddr32(0, 0); } void PPB_ImageData_Impl::Unmap() { // This is currently unimplemented, which is OK. The data will just always // be around once it's mapped. Chrome's TransportDIB isn't currently // unmappable without freeing it, but this may be something we want to support // in the future to save some memory. } int32_t PPB_ImageData_Impl::GetSharedMemory(int* handle, uint32_t* byte_count) { *handle = platform_image_->GetSharedMemoryHandle(byte_count); return PP_OK; } const SkBitmap* PPB_ImageData_Impl::GetMappedBitmap() const { if (!mapped_canvas_.get()) return NULL; return &skia::GetTopDevice(*mapped_canvas_)->accessBitmap(false); } void PPB_ImageData_Impl::Swap(PPB_ImageData_Impl* other) { swap(other->platform_image_, platform_image_); swap(other->mapped_canvas_, mapped_canvas_); std::swap(other->format_, format_); std::swap(other->width_, width_); std::swap(other->height_, height_); } } // namespace ppapi } // namespace webkit <|endoftext|>
<commit_before>/* * Copyright (C) 2020 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include "size_tiered_compaction_strategy.hh" #include <boost/range/adaptor/transformed.hpp> #include <boost/range/adaptors.hpp> #include <boost/range/algorithm.hpp> namespace sstables { size_tiered_compaction_strategy_options::size_tiered_compaction_strategy_options(const std::map<sstring, sstring>& options) { using namespace cql3::statements; auto tmp_value = compaction_strategy_impl::get_value(options, MIN_SSTABLE_SIZE_KEY); min_sstable_size = property_definitions::to_long(MIN_SSTABLE_SIZE_KEY, tmp_value, DEFAULT_MIN_SSTABLE_SIZE); tmp_value = compaction_strategy_impl::get_value(options, BUCKET_LOW_KEY); bucket_low = property_definitions::to_double(BUCKET_LOW_KEY, tmp_value, DEFAULT_BUCKET_LOW); tmp_value = compaction_strategy_impl::get_value(options, BUCKET_HIGH_KEY); bucket_high = property_definitions::to_double(BUCKET_HIGH_KEY, tmp_value, DEFAULT_BUCKET_HIGH); tmp_value = compaction_strategy_impl::get_value(options, COLD_READS_TO_OMIT_KEY); cold_reads_to_omit = property_definitions::to_double(COLD_READS_TO_OMIT_KEY, tmp_value, DEFAULT_COLD_READS_TO_OMIT); } size_tiered_compaction_strategy_options::size_tiered_compaction_strategy_options() { min_sstable_size = DEFAULT_MIN_SSTABLE_SIZE; bucket_low = DEFAULT_BUCKET_LOW; bucket_high = DEFAULT_BUCKET_HIGH; cold_reads_to_omit = DEFAULT_COLD_READS_TO_OMIT; } std::vector<std::pair<sstables::shared_sstable, uint64_t>> size_tiered_compaction_strategy::create_sstable_and_length_pairs(const std::vector<sstables::shared_sstable>& sstables) { std::vector<std::pair<sstables::shared_sstable, uint64_t>> sstable_length_pairs; sstable_length_pairs.reserve(sstables.size()); for(auto& sstable : sstables) { auto sstable_size = sstable->data_size(); assert(sstable_size != 0); sstable_length_pairs.emplace_back(sstable, sstable_size); } return sstable_length_pairs; } std::vector<std::vector<sstables::shared_sstable>> size_tiered_compaction_strategy::get_buckets(const std::vector<sstables::shared_sstable>& sstables, size_tiered_compaction_strategy_options options) { // sstables sorted by size of its data file. auto sorted_sstables = create_sstable_and_length_pairs(sstables); std::sort(sorted_sstables.begin(), sorted_sstables.end(), [] (auto& i, auto& j) { return i.second < j.second; }); std::map<size_t, std::vector<sstables::shared_sstable>> buckets; bool found; for (auto& pair : sorted_sstables) { found = false; size_t size = pair.second; // look for a bucket containing similar-sized files: // group in the same bucket if it's w/in 50% of the average for this bucket, // or this file and the bucket are all considered "small" (less than `minSSTableSize`) for (auto it = buckets.begin(); it != buckets.end(); it++) { size_t old_average_size = it->first; if ((size > (old_average_size * options.bucket_low) && size < (old_average_size * options.bucket_high)) || (size < options.min_sstable_size && old_average_size < options.min_sstable_size)) { auto bucket = std::move(it->second); size_t total_size = bucket.size() * old_average_size; size_t new_average_size = (total_size + size) / (bucket.size() + 1); bucket.push_back(pair.first); buckets.erase(it); buckets.insert({ new_average_size, std::move(bucket) }); found = true; break; } } // no similar bucket found; put it in a new one if (!found) { std::vector<sstables::shared_sstable> new_bucket; new_bucket.push_back(pair.first); buckets.insert({ size, std::move(new_bucket) }); } } std::vector<std::vector<sstables::shared_sstable>> bucket_list; bucket_list.reserve(buckets.size()); for (auto& entry : buckets) { bucket_list.push_back(std::move(entry.second)); } return bucket_list; } std::vector<std::vector<sstables::shared_sstable>> size_tiered_compaction_strategy::get_buckets(const std::vector<sstables::shared_sstable>& sstables) const { return get_buckets(sstables, _options); } std::vector<sstables::shared_sstable> size_tiered_compaction_strategy::most_interesting_bucket(std::vector<std::vector<sstables::shared_sstable>> buckets, unsigned min_threshold, unsigned max_threshold) { std::vector<std::pair<std::vector<sstables::shared_sstable>, uint64_t>> pruned_buckets_and_hotness; pruned_buckets_and_hotness.reserve(buckets.size()); // FIXME: add support to get hotness for each bucket. for (auto& bucket : buckets) { // FIXME: the coldest sstables will be trimmed to meet the threshold, so we must add support to this feature // by converting SizeTieredCompactionStrategy::trimToThresholdWithHotness. // By the time being, we will only compact buckets that meet the threshold. bucket.resize(std::min(bucket.size(), size_t(max_threshold))); if (is_bucket_interesting(bucket, min_threshold)) { auto avg = avg_size(bucket); pruned_buckets_and_hotness.push_back({ std::move(bucket), avg }); } } if (pruned_buckets_and_hotness.empty()) { return std::vector<sstables::shared_sstable>(); } // NOTE: Compacting smallest sstables first, located at the beginning of the sorted vector. auto& min = *std::min_element(pruned_buckets_and_hotness.begin(), pruned_buckets_and_hotness.end(), [] (auto& i, auto& j) { // FIXME: ignoring hotness by the time being. return i.second < j.second; }); auto hottest = std::move(min.first); return hottest; } compaction_descriptor size_tiered_compaction_strategy::get_sstables_for_compaction(column_family& cfs, std::vector<sstables::shared_sstable> candidates) { // make local copies so they can't be changed out from under us mid-method int min_threshold = cfs.min_compaction_threshold(); int max_threshold = cfs.schema()->max_compaction_threshold(); auto gc_before = gc_clock::now() - cfs.schema()->gc_grace_seconds(); // TODO: Add support to filter cold sstables (for reference: SizeTieredCompactionStrategy::filterColdSSTables). auto buckets = get_buckets(candidates); if (is_any_bucket_interesting(buckets, min_threshold)) { std::vector<sstables::shared_sstable> most_interesting = most_interesting_bucket(std::move(buckets), min_threshold, max_threshold); return sstables::compaction_descriptor(std::move(most_interesting), cfs.get_sstable_set(), service::get_local_compaction_priority()); } // If we are not enforcing min_threshold explicitly, try any pair of SStables in the same tier. if (!cfs.compaction_enforce_min_threshold() && is_any_bucket_interesting(buckets, 2)) { std::vector<sstables::shared_sstable> most_interesting = most_interesting_bucket(std::move(buckets), 2, max_threshold); return sstables::compaction_descriptor(std::move(most_interesting), cfs.get_sstable_set(), service::get_local_compaction_priority()); } // if there is no sstable to compact in standard way, try compacting single sstable whose droppable tombstone // ratio is greater than threshold. // prefer oldest sstables from biggest size tiers because they will be easier to satisfy conditions for // tombstone purge, i.e. less likely to shadow even older data. for (auto&& sstables : buckets | boost::adaptors::reversed) { // filter out sstables which droppable tombstone ratio isn't greater than the defined threshold. auto e = boost::range::remove_if(sstables, [this, &gc_before] (const sstables::shared_sstable& sst) -> bool { return !worth_dropping_tombstones(sst, gc_before); }); sstables.erase(e, sstables.end()); if (sstables.empty()) { continue; } // find oldest sstable from current tier auto it = std::min_element(sstables.begin(), sstables.end(), [] (auto& i, auto& j) { return i->get_stats_metadata().min_timestamp < j->get_stats_metadata().min_timestamp; }); return sstables::compaction_descriptor({ *it }, cfs.get_sstable_set(), service::get_local_compaction_priority()); } return sstables::compaction_descriptor(); } int64_t size_tiered_compaction_strategy::estimated_pending_compactions(const std::vector<sstables::shared_sstable>& sstables, int min_threshold, int max_threshold, size_tiered_compaction_strategy_options options) { int64_t n = 0; for (auto& bucket : get_buckets(sstables, options)) { if (bucket.size() >= size_t(min_threshold)) { n += std::ceil(double(bucket.size()) / max_threshold); } } return n; } int64_t size_tiered_compaction_strategy::estimated_pending_compactions(column_family& cf) const { int min_threshold = cf.min_compaction_threshold(); int max_threshold = cf.schema()->max_compaction_threshold(); std::vector<sstables::shared_sstable> sstables; sstables.reserve(cf.sstables_count()); for (auto all_sstables = cf.get_sstables(); auto& entry : *all_sstables) { sstables.push_back(entry); } return estimated_pending_compactions(sstables, min_threshold, max_threshold, _options); } std::vector<sstables::shared_sstable> size_tiered_compaction_strategy::most_interesting_bucket(const std::vector<sstables::shared_sstable>& candidates, int min_threshold, int max_threshold, size_tiered_compaction_strategy_options options) { size_tiered_compaction_strategy cs(options); auto buckets = cs.get_buckets(candidates); std::vector<sstables::shared_sstable> most_interesting = cs.most_interesting_bucket(std::move(buckets), min_threshold, max_threshold); return most_interesting; } compaction_descriptor size_tiered_compaction_strategy::get_reshaping_job(std::vector<shared_sstable> input, schema_ptr schema, const ::io_priority_class& iop, reshape_mode mode) { size_t offstrategy_threshold = std::max(schema->min_compaction_threshold(), 4); size_t max_sstables = std::max(schema->max_compaction_threshold(), int(offstrategy_threshold)); if (mode == reshape_mode::relaxed) { offstrategy_threshold = max_sstables; } for (auto& bucket : get_buckets(input)) { if (bucket.size() >= offstrategy_threshold) { // reshape job can work on #max_sstables sstables at once, so by reshaping sstables with the smallest tokens first, // token contiguity is preserved iff sstables are disjoint. if (bucket.size() > max_sstables) { std::partial_sort(bucket.begin(), bucket.begin() + max_sstables, bucket.end(), [&schema](const sstables::shared_sstable& a, const sstables::shared_sstable& b) { return a->get_first_decorated_key().tri_compare(*schema, b->get_first_decorated_key()) <= 0; }); bucket.resize(max_sstables); } compaction_descriptor desc(std::move(bucket), std::optional<sstables::sstable_set>(), iop); desc.options = compaction_options::make_reshape(); return desc; } } return compaction_descriptor(); } } <commit_msg>compaction: size_tiered_compaction_strategy: get_buckets: consider only current bucket for each sstable<commit_after>/* * Copyright (C) 2020 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include "size_tiered_compaction_strategy.hh" #include <boost/range/adaptor/transformed.hpp> #include <boost/range/adaptors.hpp> #include <boost/range/algorithm.hpp> namespace sstables { size_tiered_compaction_strategy_options::size_tiered_compaction_strategy_options(const std::map<sstring, sstring>& options) { using namespace cql3::statements; auto tmp_value = compaction_strategy_impl::get_value(options, MIN_SSTABLE_SIZE_KEY); min_sstable_size = property_definitions::to_long(MIN_SSTABLE_SIZE_KEY, tmp_value, DEFAULT_MIN_SSTABLE_SIZE); tmp_value = compaction_strategy_impl::get_value(options, BUCKET_LOW_KEY); bucket_low = property_definitions::to_double(BUCKET_LOW_KEY, tmp_value, DEFAULT_BUCKET_LOW); tmp_value = compaction_strategy_impl::get_value(options, BUCKET_HIGH_KEY); bucket_high = property_definitions::to_double(BUCKET_HIGH_KEY, tmp_value, DEFAULT_BUCKET_HIGH); tmp_value = compaction_strategy_impl::get_value(options, COLD_READS_TO_OMIT_KEY); cold_reads_to_omit = property_definitions::to_double(COLD_READS_TO_OMIT_KEY, tmp_value, DEFAULT_COLD_READS_TO_OMIT); } size_tiered_compaction_strategy_options::size_tiered_compaction_strategy_options() { min_sstable_size = DEFAULT_MIN_SSTABLE_SIZE; bucket_low = DEFAULT_BUCKET_LOW; bucket_high = DEFAULT_BUCKET_HIGH; cold_reads_to_omit = DEFAULT_COLD_READS_TO_OMIT; } std::vector<std::pair<sstables::shared_sstable, uint64_t>> size_tiered_compaction_strategy::create_sstable_and_length_pairs(const std::vector<sstables::shared_sstable>& sstables) { std::vector<std::pair<sstables::shared_sstable, uint64_t>> sstable_length_pairs; sstable_length_pairs.reserve(sstables.size()); for(auto& sstable : sstables) { auto sstable_size = sstable->data_size(); assert(sstable_size != 0); sstable_length_pairs.emplace_back(sstable, sstable_size); } return sstable_length_pairs; } std::vector<std::vector<sstables::shared_sstable>> size_tiered_compaction_strategy::get_buckets(const std::vector<sstables::shared_sstable>& sstables, size_tiered_compaction_strategy_options options) { // sstables sorted by size of its data file. auto sorted_sstables = create_sstable_and_length_pairs(sstables); std::sort(sorted_sstables.begin(), sorted_sstables.end(), [] (auto& i, auto& j) { return i.second < j.second; }); using bucket_type = std::vector<sstables::shared_sstable>; std::vector<bucket_type> bucket_list; std::vector<size_t> bucket_average_size_list; for (auto& pair : sorted_sstables) { size_t size = pair.second; // look for a bucket containing similar-sized files: // group in the same bucket if it's w/in 50% of the average for this bucket, // or this file and the bucket are all considered "small" (less than `minSSTableSize`) if (!bucket_list.empty()) { // FIXME: rename old_average_size since it's being assigned below auto& old_average_size = bucket_average_size_list.back(); if ((size > (old_average_size * options.bucket_low) && size < (old_average_size * options.bucket_high)) || (size < options.min_sstable_size && old_average_size < options.min_sstable_size)) { auto& bucket = bucket_list.back(); size_t total_size = bucket.size() * old_average_size; size_t new_average_size = (total_size + size) / (bucket.size() + 1); bucket.push_back(pair.first); old_average_size = new_average_size; continue; } } // no similar bucket found; put it in a new one bucket_type new_bucket = {pair.first}; bucket_list.push_back(std::move(new_bucket)); bucket_average_size_list.push_back(size); } return bucket_list; } std::vector<std::vector<sstables::shared_sstable>> size_tiered_compaction_strategy::get_buckets(const std::vector<sstables::shared_sstable>& sstables) const { return get_buckets(sstables, _options); } std::vector<sstables::shared_sstable> size_tiered_compaction_strategy::most_interesting_bucket(std::vector<std::vector<sstables::shared_sstable>> buckets, unsigned min_threshold, unsigned max_threshold) { std::vector<std::pair<std::vector<sstables::shared_sstable>, uint64_t>> pruned_buckets_and_hotness; pruned_buckets_and_hotness.reserve(buckets.size()); // FIXME: add support to get hotness for each bucket. for (auto& bucket : buckets) { // FIXME: the coldest sstables will be trimmed to meet the threshold, so we must add support to this feature // by converting SizeTieredCompactionStrategy::trimToThresholdWithHotness. // By the time being, we will only compact buckets that meet the threshold. bucket.resize(std::min(bucket.size(), size_t(max_threshold))); if (is_bucket_interesting(bucket, min_threshold)) { auto avg = avg_size(bucket); pruned_buckets_and_hotness.push_back({ std::move(bucket), avg }); } } if (pruned_buckets_and_hotness.empty()) { return std::vector<sstables::shared_sstable>(); } // NOTE: Compacting smallest sstables first, located at the beginning of the sorted vector. auto& min = *std::min_element(pruned_buckets_and_hotness.begin(), pruned_buckets_and_hotness.end(), [] (auto& i, auto& j) { // FIXME: ignoring hotness by the time being. return i.second < j.second; }); auto hottest = std::move(min.first); return hottest; } compaction_descriptor size_tiered_compaction_strategy::get_sstables_for_compaction(column_family& cfs, std::vector<sstables::shared_sstable> candidates) { // make local copies so they can't be changed out from under us mid-method int min_threshold = cfs.min_compaction_threshold(); int max_threshold = cfs.schema()->max_compaction_threshold(); auto gc_before = gc_clock::now() - cfs.schema()->gc_grace_seconds(); // TODO: Add support to filter cold sstables (for reference: SizeTieredCompactionStrategy::filterColdSSTables). auto buckets = get_buckets(candidates); if (is_any_bucket_interesting(buckets, min_threshold)) { std::vector<sstables::shared_sstable> most_interesting = most_interesting_bucket(std::move(buckets), min_threshold, max_threshold); return sstables::compaction_descriptor(std::move(most_interesting), cfs.get_sstable_set(), service::get_local_compaction_priority()); } // If we are not enforcing min_threshold explicitly, try any pair of SStables in the same tier. if (!cfs.compaction_enforce_min_threshold() && is_any_bucket_interesting(buckets, 2)) { std::vector<sstables::shared_sstable> most_interesting = most_interesting_bucket(std::move(buckets), 2, max_threshold); return sstables::compaction_descriptor(std::move(most_interesting), cfs.get_sstable_set(), service::get_local_compaction_priority()); } // if there is no sstable to compact in standard way, try compacting single sstable whose droppable tombstone // ratio is greater than threshold. // prefer oldest sstables from biggest size tiers because they will be easier to satisfy conditions for // tombstone purge, i.e. less likely to shadow even older data. for (auto&& sstables : buckets | boost::adaptors::reversed) { // filter out sstables which droppable tombstone ratio isn't greater than the defined threshold. auto e = boost::range::remove_if(sstables, [this, &gc_before] (const sstables::shared_sstable& sst) -> bool { return !worth_dropping_tombstones(sst, gc_before); }); sstables.erase(e, sstables.end()); if (sstables.empty()) { continue; } // find oldest sstable from current tier auto it = std::min_element(sstables.begin(), sstables.end(), [] (auto& i, auto& j) { return i->get_stats_metadata().min_timestamp < j->get_stats_metadata().min_timestamp; }); return sstables::compaction_descriptor({ *it }, cfs.get_sstable_set(), service::get_local_compaction_priority()); } return sstables::compaction_descriptor(); } int64_t size_tiered_compaction_strategy::estimated_pending_compactions(const std::vector<sstables::shared_sstable>& sstables, int min_threshold, int max_threshold, size_tiered_compaction_strategy_options options) { int64_t n = 0; for (auto& bucket : get_buckets(sstables, options)) { if (bucket.size() >= size_t(min_threshold)) { n += std::ceil(double(bucket.size()) / max_threshold); } } return n; } int64_t size_tiered_compaction_strategy::estimated_pending_compactions(column_family& cf) const { int min_threshold = cf.min_compaction_threshold(); int max_threshold = cf.schema()->max_compaction_threshold(); std::vector<sstables::shared_sstable> sstables; sstables.reserve(cf.sstables_count()); for (auto all_sstables = cf.get_sstables(); auto& entry : *all_sstables) { sstables.push_back(entry); } return estimated_pending_compactions(sstables, min_threshold, max_threshold, _options); } std::vector<sstables::shared_sstable> size_tiered_compaction_strategy::most_interesting_bucket(const std::vector<sstables::shared_sstable>& candidates, int min_threshold, int max_threshold, size_tiered_compaction_strategy_options options) { size_tiered_compaction_strategy cs(options); auto buckets = cs.get_buckets(candidates); std::vector<sstables::shared_sstable> most_interesting = cs.most_interesting_bucket(std::move(buckets), min_threshold, max_threshold); return most_interesting; } compaction_descriptor size_tiered_compaction_strategy::get_reshaping_job(std::vector<shared_sstable> input, schema_ptr schema, const ::io_priority_class& iop, reshape_mode mode) { size_t offstrategy_threshold = std::max(schema->min_compaction_threshold(), 4); size_t max_sstables = std::max(schema->max_compaction_threshold(), int(offstrategy_threshold)); if (mode == reshape_mode::relaxed) { offstrategy_threshold = max_sstables; } for (auto& bucket : get_buckets(input)) { if (bucket.size() >= offstrategy_threshold) { // reshape job can work on #max_sstables sstables at once, so by reshaping sstables with the smallest tokens first, // token contiguity is preserved iff sstables are disjoint. if (bucket.size() > max_sstables) { std::partial_sort(bucket.begin(), bucket.begin() + max_sstables, bucket.end(), [&schema](const sstables::shared_sstable& a, const sstables::shared_sstable& b) { return a->get_first_decorated_key().tri_compare(*schema, b->get_first_decorated_key()) <= 0; }); bucket.resize(max_sstables); } compaction_descriptor desc(std::move(bucket), std::optional<sstables::sstable_set>(), iop); desc.options = compaction_options::make_reshape(); return desc; } } return compaction_descriptor(); } } <|endoftext|>
<commit_before>/* Sirikata Object Host -- Proxy WebView Object * ProxyWebViewObject.cpp * * Copyright (c) 2009, Adam Jean Simmons * 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 Sirikata 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 <sirikata/proxyobject/ProxyWebViewObject.hpp> using namespace Sirikata; ProxyWebViewObject::ProxyWebViewObject(ProxyManager* man, const SpaceObjectReference& id, VWObjectPtr vwobj, const SpaceObjectReference& owner_sor) : ProxyMeshObject(man, id, vwobj, owner_sor) { } void ProxyWebViewObject::loadURL(const std::string& url) { WebViewProvider::notify(&WebViewListener::loadURL, url); } void ProxyWebViewObject::loadFile(const std::string& filename) { WebViewProvider::notify(&WebViewListener::loadFile, filename); } void ProxyWebViewObject::loadHTML(const std::string& html) { WebViewProvider::notify(&WebViewListener::loadHTML, html); } void ProxyWebViewObject::evaluateJS(const std::string& javascript) { WebViewProvider::notify(&WebViewListener::evaluateJS, javascript); } void ProxyWebViewObject::setPosition(const OverlayPosition& position) { WebViewProvider::notify(&WebViewListener::setPosition, position); } void ProxyWebViewObject::hide() { WebViewProvider::notify(&WebViewListener::hide); } void ProxyWebViewObject::show() { WebViewProvider::notify(&WebViewListener::show); } void ProxyWebViewObject::resize(int width, int height) { WebViewProvider::notify(&WebViewListener::resize, width, height); } <commit_msg>Trying to find the hook for getting the action.<commit_after>/* Sirikata Object Host -- Proxy WebView Object * ProxyWebViewObject.cpp * * Copyright (c) 2009, Adam Jean Simmons * 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 Sirikata 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 <sirikata/proxyobject/ProxyWebViewObject.hpp> using namespace Sirikata; ProxyWebViewObject::ProxyWebViewObject(ProxyManager* man, const SpaceObjectReference& id, VWObjectPtr vwobj, const SpaceObjectReference& owner_sor) : ProxyMeshObject(man, id, vwobj, owner_sor) { } void ProxyWebViewObject::loadURL(const std::string& url) { WebViewProvider::notify(&WebViewListener::loadURL, url); } void ProxyWebViewObject::loadFile(const std::string& filename) { WebViewProvider::notify(&WebViewListener::loadFile, filename); } void ProxyWebViewObject::loadHTML(const std::string& html) { WebViewProvider::notify(&WebViewListener::loadHTML, html); } void ProxyWebViewObject::evaluateJS(const std::string& javascript) { std::cout<<"\n\n\n"; std::cout<<"Got into evaluateJS"; std::cout<<"\n\n\n"; WebViewProvider::notify(&WebViewListener::evaluateJS, javascript); } void ProxyWebViewObject::setPosition(const OverlayPosition& position) { WebViewProvider::notify(&WebViewListener::setPosition, position); } void ProxyWebViewObject::hide() { WebViewProvider::notify(&WebViewListener::hide); } void ProxyWebViewObject::show() { WebViewProvider::notify(&WebViewListener::show); } void ProxyWebViewObject::resize(int width, int height) { WebViewProvider::notify(&WebViewListener::resize, width, height); } <|endoftext|>
<commit_before>#include "kernel.h" #include "ilwisdata.h" #include "basedrawer.h" #include "coordinatesystem.h" #include "rootdrawer.h" using namespace Ilwis; using namespace Geodrawer; BaseDrawer::BaseDrawer(const QString& nme, DrawerInterface *parentDrawer, RootDrawer *rootdrawer, const IOOptions &) : DrawerInterface(0),Identity(nme,i64UNDEF,nme.toLower()), _rootDrawer(rootdrawer), _parentDrawer(parentDrawer) { Identity::prepare(); } void BaseDrawer::valid(bool yesno) { _valid = yesno; } bool BaseDrawer::prepare(DrawerInterface::PreparationType prepType, const IOOptions &) { if ( code() == "RootDrawer") // rootdrawer for the moment has no need of shaders return true; if ( !rootDrawer()) // rootdrawer must be set return false; if ( hasType(prepType, ptSHADERS) && !isPrepared(ptSHADERS)){ _shaders.addShaderFromSourceCode(QOpenGLShader::Vertex, "attribute highp vec4 position;" "attribute mediump vec3 normal;" "uniform mat4 mvp;" "uniform vec3 scalecenter;" "uniform float scalefactor;" "uniform float alpha;" "attribute lowp vec4 vertexColor;" "varying lowp vec4 fragmentColor;" "void main() {" " if ( scalefactor != 1) {" " float x = scalecenter[0] + (position[0] - scalecenter[0]) * scalefactor;" " float y = scalecenter[1] + (position[1] - scalecenter[1]) * scalefactor;" " float z = position[2];" " position[0] = x;" " position[1] = y;" " position[2] = z;" " position[3] = 1;" " }" " vertexColor[3] = alpha;" " gl_Position = mvp * position;" " fragmentColor = vertexColor;" "}"); _shaders.addShaderFromSourceCode(QOpenGLShader::Fragment, "varying lowp vec4 fragmentColor;" "void main() {" " gl_FragColor = fragmentColor;" "}"); if(!_shaders.link()){ return ERROR2(QString("%1 : %2"),TR("Drawing failed"),TR(_shaders.log())); } if (!_shaders.bind()){ return ERROR2(QString("%1 : %2"),TR("Drawing failed"),TR(_shaders.log())); } _prepared |= DrawerInterface::ptSHADERS; _vboPosition = _shaders.attributeLocation("position"); _vboNormal = _shaders.attributeLocation("normal"); _vboColor = _shaders.attributeLocation("vertexColor"); _modelview = _shaders.uniformLocation("mvp"); _scaleCenter = _shaders.uniformLocation("scalecenter"); _scaleFactor = _shaders.uniformLocation("scalefactor"); _vboAlpha = _shaders.uniformLocation("alpha"); } return true; } void BaseDrawer::unprepare(DrawerInterface::PreparationType prepType ) { if ( hasType(_prepared, prepType)) { _prepared &= ~ prepType; } } bool BaseDrawer::isPrepared(quint32 type) const { return hasType(_prepared, type); } bool BaseDrawer::draw(const IOOptions &) const { return false; } RootDrawer *BaseDrawer::rootDrawer() { return _rootDrawer; } const RootDrawer *BaseDrawer::rootDrawer() const { return _rootDrawer; } DrawerInterface *BaseDrawer::parent() { return _parentDrawer; } const DrawerInterface *BaseDrawer::parent() const { return _parentDrawer; } bool BaseDrawer::isActive() const { return _active; } void BaseDrawer::active(bool yesno) { _active = yesno; } bool BaseDrawer::isValid() const { return _valid; } void BaseDrawer::selected(bool yesno) { _selected= yesno; } bool BaseDrawer::isSelected() const { return _selected; } BaseDrawer::Containment BaseDrawer::containment() const { if ( _envelope.isValid()){ if ( rootDrawer()->zoomEnvelope().intersects(_envelope)) return BaseDrawer::cINSIDE; } return BaseDrawer::cUNKNOWN; } void BaseDrawer::cleanUp() { _shaders.removeAllShaders(); unprepare(ptSHADERS); } void BaseDrawer::code(const QString &code) { Identity::code(code); } QString BaseDrawer::code() const { return Identity::code(); } quint64 BaseDrawer::id() const { return Identity::id(); } QString BaseDrawer::name() const { return Identity::name(); } void BaseDrawer::name(const QString &n) { Identity::name(n); } QString BaseDrawer::description() const { return Identity::description(); } void BaseDrawer::setDescription(const QString &desc) { return Identity::setDescription(desc); } std::vector<QVariant> BaseDrawer::attributes(const QString &attrNames) const { std::vector<QVariant> result; return result; } QVariant BaseDrawer::attribute(const QString &attrName) const { if ( attrName == "alphachannel") return _alpha; return QVariant(); } QVariant BaseDrawer::attributeOfDrawer(const QString &, const QString &) const { return QVariant(); } void BaseDrawer::setAttribute(const QString &attrName, const QVariant &value) { if ( attrName == "alphachannel") _alpha = value.toFloat(); } bool BaseDrawer::drawerAttribute(const QString , const QString &, const QVariant &) { return false; } QColor BaseDrawer::color(const IRepresentation &rpr, double , DrawerInterface::ColorValueMeaning ) { return QColor(); } quint32 BaseDrawer::defaultOrder() const { return iUNDEF; } float BaseDrawer::alpha() const { return _alpha; } void BaseDrawer::alpha(float alp) { if ( alp >= 0 && alp <= 1.0) _alpha = alp; } void BaseDrawer::redraw() { rootDrawer()->redraw(); } <commit_msg>improved shader code by taking into account already set alphas<commit_after>#include "kernel.h" #include "ilwisdata.h" #include "basedrawer.h" #include "coordinatesystem.h" #include "rootdrawer.h" using namespace Ilwis; using namespace Geodrawer; BaseDrawer::BaseDrawer(const QString& nme, DrawerInterface *parentDrawer, RootDrawer *rootdrawer, const IOOptions &) : DrawerInterface(0),Identity(nme,i64UNDEF,nme.toLower()), _rootDrawer(rootdrawer), _parentDrawer(parentDrawer) { Identity::prepare(); } void BaseDrawer::valid(bool yesno) { _valid = yesno; } bool BaseDrawer::prepare(DrawerInterface::PreparationType prepType, const IOOptions &) { if ( code() == "RootDrawer") // rootdrawer for the moment has no need of shaders return true; if ( !rootDrawer()) // rootdrawer must be set return false; if ( hasType(prepType, ptSHADERS) && !isPrepared(ptSHADERS)){ _shaders.addShaderFromSourceCode(QOpenGLShader::Vertex, "attribute highp vec4 position;" "attribute mediump vec3 normal;" "uniform mat4 mvp;" "uniform vec3 scalecenter;" "uniform float scalefactor;" "uniform float alpha;" "attribute lowp vec4 vertexColor;" "varying lowp vec4 fragmentColor;" "void main() {" " if ( scalefactor != 1) {" " float x = scalecenter[0] + (position[0] - scalecenter[0]) * scalefactor;" " float y = scalecenter[1] + (position[1] - scalecenter[1]) * scalefactor;" " float z = position[2];" " position[0] = x;" " position[1] = y;" " position[2] = z;" " position[3] = 1;" " }" " vertexColor[3] = alpha * vertexColor[3];" " gl_Position = mvp * position;" " fragmentColor = vertexColor;" "}"); _shaders.addShaderFromSourceCode(QOpenGLShader::Fragment, "varying lowp vec4 fragmentColor;" "void main() {" " gl_FragColor = fragmentColor;" "}"); if(!_shaders.link()){ return ERROR2(QString("%1 : %2"),TR("Drawing failed"),TR(_shaders.log())); } if (!_shaders.bind()){ return ERROR2(QString("%1 : %2"),TR("Drawing failed"),TR(_shaders.log())); } _prepared |= DrawerInterface::ptSHADERS; _vboPosition = _shaders.attributeLocation("position"); _vboNormal = _shaders.attributeLocation("normal"); _vboColor = _shaders.attributeLocation("vertexColor"); _modelview = _shaders.uniformLocation("mvp"); _scaleCenter = _shaders.uniformLocation("scalecenter"); _scaleFactor = _shaders.uniformLocation("scalefactor"); _vboAlpha = _shaders.uniformLocation("alpha"); } return true; } void BaseDrawer::unprepare(DrawerInterface::PreparationType prepType ) { if ( hasType(_prepared, prepType)) { _prepared &= ~ prepType; } } bool BaseDrawer::isPrepared(quint32 type) const { return hasType(_prepared, type); } bool BaseDrawer::draw(const IOOptions &) const { return false; } RootDrawer *BaseDrawer::rootDrawer() { return _rootDrawer; } const RootDrawer *BaseDrawer::rootDrawer() const { return _rootDrawer; } DrawerInterface *BaseDrawer::parent() { return _parentDrawer; } const DrawerInterface *BaseDrawer::parent() const { return _parentDrawer; } bool BaseDrawer::isActive() const { return _active; } void BaseDrawer::active(bool yesno) { _active = yesno; } bool BaseDrawer::isValid() const { return _valid; } void BaseDrawer::selected(bool yesno) { _selected= yesno; } bool BaseDrawer::isSelected() const { return _selected; } BaseDrawer::Containment BaseDrawer::containment() const { if ( _envelope.isValid()){ if ( rootDrawer()->zoomEnvelope().intersects(_envelope)) return BaseDrawer::cINSIDE; } return BaseDrawer::cUNKNOWN; } void BaseDrawer::cleanUp() { _shaders.removeAllShaders(); unprepare(ptSHADERS); } void BaseDrawer::code(const QString &code) { Identity::code(code); } QString BaseDrawer::code() const { return Identity::code(); } quint64 BaseDrawer::id() const { return Identity::id(); } QString BaseDrawer::name() const { return Identity::name(); } void BaseDrawer::name(const QString &n) { Identity::name(n); } QString BaseDrawer::description() const { return Identity::description(); } void BaseDrawer::setDescription(const QString &desc) { return Identity::setDescription(desc); } std::vector<QVariant> BaseDrawer::attributes(const QString &attrNames) const { std::vector<QVariant> result; return result; } QVariant BaseDrawer::attribute(const QString &attrName) const { if ( attrName == "alphachannel") return _alpha; return QVariant(); } QVariant BaseDrawer::attributeOfDrawer(const QString &, const QString &) const { return QVariant(); } void BaseDrawer::setAttribute(const QString &attrName, const QVariant &value) { if ( attrName == "alphachannel") _alpha = value.toFloat(); } bool BaseDrawer::drawerAttribute(const QString , const QString &, const QVariant &) { return false; } QColor BaseDrawer::color(const IRepresentation &rpr, double , DrawerInterface::ColorValueMeaning ) { return QColor(); } quint32 BaseDrawer::defaultOrder() const { return iUNDEF; } float BaseDrawer::alpha() const { return _alpha; } void BaseDrawer::alpha(float alp) { if ( alp >= 0 && alp <= 1.0) _alpha = alp; } void BaseDrawer::redraw() { rootDrawer()->redraw(); } <|endoftext|>
<commit_before>//============================================================================================================= /** * @file main.cpp * @author Lorenz Esch <lorenz.esch@tu-ilmenau.de>; * Matti Hamalainen <msh@nmr.mgh.harvard.edu> * @version 1.0 * @date July, 2016 * * @section LICENSE * * Copyright (C) 2016, Lorenz Esch and Matti Hamalainen. 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 MNE-CPP authors 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. * * * @brief Example of using the MNE-CPP Disp3D library * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include <disp3D/engine/view/view3D.h> #include <disp3D/engine/control/control3dwidget.h> #include <disp3D/engine/model/items/sourceactivity/mneestimatetreeitem.h> #include <disp3D/engine/model/items/sensordata/sensordatatreeitem.h> #include <disp3D/engine/model/data3Dtreemodel.h> #include <fs/surfaceset.h> #include <fs/annotationset.h> #include <mne/mne_sourceestimate.h> #include <mne/mne_bem.h> #include <fiff/fiff_dig_point_set.h> #include <inverse/minimumNorm/minimumnorm.h> #include <disp3D/helpers/geometryinfo/geometryinfo.h> #include <disp3D/helpers/interpolation/interpolation.h> //************************************************************************************************************* //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <QApplication> #include <QMainWindow> #include <QCommandLineParser> //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace DISP3DLIB; using namespace MNELIB; using namespace FSLIB; using namespace FIFFLIB; using namespace INVERSELIB; //************************************************************************************************************* //============================================================================================================= // MAIN //============================================================================================================= //============================================================================================================= /** * The function main marks the entry point of the program. * By default, main has the storage class extern. * * @param [in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started. * @param [in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started. * @return the value that was set to exit() (which is 0 if exit() is called via quit()). */ int main(int argc, char *argv[]) { QApplication a(argc, argv); // Command Line Parser QCommandLineParser parser; parser.setApplicationDescription("Disp3D Example"); parser.addHelpOption(); QCommandLineOption surfOption("surfType", "Surface type <type>.", "type", "inflated"); QCommandLineOption annotOption("annotType", "Annotation type <type>.", "type", "aparc.a2009s"); QCommandLineOption hemiOption("hemi", "Selected hemisphere <hemi>.", "hemi", "2"); QCommandLineOption subjectOption("subject", "Selected subject <subject>.", "subject", "sample"); QCommandLineOption subjectPathOption("subjectPath", "Selected subject path <subjectPath>.", "subjectPath", "./MNE-sample-data/subjects"); QCommandLineOption sourceLocOption("doSourceLoc", "Do real time source localization.", "doSourceLoc", "false"); QCommandLineOption fwdOption("fwd", "Path to forwad solution <file>.", "file", "./MNE-sample-data/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif"); QCommandLineOption invOpOption("inv", "Path to inverse operator <file>.", "file", ""); QCommandLineOption clustOption("doClust", "Path to clustered inverse operator <doClust>.", "doClust", "true"); QCommandLineOption covFileOption("cov", "Path to the covariance <file>.", "file", "./MNE-sample-data/MEG/sample/sample_audvis-cov.fif"); QCommandLineOption evokedFileOption("ave", "Path to the evoked/average <file>.", "file", "./MNE-sample-data/MEG/sample/sample_audvis-ave.fif"); QCommandLineOption methodOption("method", "Inverse estimation <method>, i.e., 'MNE', 'dSPM' or 'sLORETA'.", "method", "dSPM");//"MNE" | "dSPM" | "sLORETA" QCommandLineOption snrOption("snr", "The SNR value used for computation <snr>.", "snr", "3.0");//3.0;//0.1;//3.0; QCommandLineOption evokedIndexOption("aveIdx", "The average <index> to choose from the average file.", "index", "3"); parser.addOption(surfOption); parser.addOption(annotOption); parser.addOption(hemiOption); parser.addOption(subjectOption); parser.addOption(subjectPathOption); parser.addOption(sourceLocOption); parser.addOption(fwdOption); parser.addOption(invOpOption); parser.addOption(clustOption); parser.addOption(covFileOption); parser.addOption(evokedFileOption); parser.addOption(methodOption); parser.addOption(snrOption); parser.addOption(evokedIndexOption); parser.process(a); bool bAddRtSourceLoc = false; if(parser.value(sourceLocOption) == "false" || parser.value(sourceLocOption) == "0") { bAddRtSourceLoc = false; } else if(parser.value(sourceLocOption) == "true" || parser.value(sourceLocOption) == "1") { bAddRtSourceLoc = true; } bool bDoClustering = false; if(parser.value(clustOption) == "false" || parser.value(clustOption) == "0") { bDoClustering = false; } else if(parser.value(clustOption) == "true" || parser.value(clustOption) == "1") { bDoClustering = true; } //Inits SurfaceSet tSurfSet (parser.value(subjectOption), parser.value(hemiOption).toInt(), parser.value(surfOption), parser.value(subjectPathOption)); AnnotationSet tAnnotSet (parser.value(subjectOption), parser.value(hemiOption).toInt(), parser.value(annotOption), parser.value(subjectPathOption)); QFile t_fileFwd(parser.value(fwdOption)); MNEForwardSolution t_Fwd(t_fileFwd); MNEForwardSolution t_clusteredFwd; QString t_sFileClusteredInverse(parser.value(invOpOption)); QFile t_fileCov(parser.value(covFileOption)); QFile t_fileEvoked(parser.value(evokedFileOption)); //######################################################################################## // // Source Estimate START // //######################################################################################## // Load data QPair<QVariant, QVariant> baseline(QVariant(), 0); MNESourceEstimate sourceEstimate; FiffEvoked evoked(t_fileEvoked, parser.value(evokedIndexOption).toInt(), baseline); if(bAddRtSourceLoc) { double snr = parser.value(snrOption).toDouble(); double lambda2 = 1.0 / pow(snr, 2); QString method(parser.value(methodOption)); // Load data t_fileEvoked.close(); if(evoked.isEmpty()) return 1; std::cout << std::endl; std::cout << "Evoked description: " << evoked.comment.toUtf8().constData() << std::endl; if(t_Fwd.isEmpty()) return 1; FiffCov noise_cov(t_fileCov); // regularize noise covariance noise_cov = noise_cov.regularize(evoked.info, 0.05, 0.05, 0.1, true); // // Cluster forward solution; // if(bDoClustering) { t_clusteredFwd = t_Fwd.cluster_forward_solution(tAnnotSet, 40); } else { t_clusteredFwd = t_Fwd; } // // make an inverse operators // FiffInfo info = evoked.info; MNEInverseOperator inverse_operator(info, t_clusteredFwd, noise_cov, 0.2f, 0.8f); if(!t_sFileClusteredInverse.isEmpty()) { QFile t_fileClusteredInverse(t_sFileClusteredInverse); inverse_operator.write(t_fileClusteredInverse); } // // Compute inverse solution // MinimumNorm minimumNorm(inverse_operator, lambda2, method); sourceEstimate = minimumNorm.calculateInverse(evoked); if(sourceEstimate.isEmpty()) return 1; // View activation time-series std::cout << "\nsourceEstimate:\n" << sourceEstimate.data.block(0,0,10,10) << std::endl; std::cout << "time\n" << sourceEstimate.times.block(0,0,1,10) << std::endl; std::cout << "timeMin\n" << sourceEstimate.times[0] << std::endl; std::cout << "timeMax\n" << sourceEstimate.times[sourceEstimate.times.size()-1] << std::endl; std::cout << "time step\n" << sourceEstimate.tstep << std::endl; } //######################################################################################## // //Source Estimate END // //######################################################################################## //Create 3D data model Data3DTreeModel::SPtr p3DDataModel = Data3DTreeModel::SPtr(new Data3DTreeModel()); //Add fressurfer surface set including both hemispheres p3DDataModel->addSurfaceSet(parser.value(subjectOption), "MRI", tSurfSet, tAnnotSet); //Read and show BEM QFile t_fileBem("./MNE-sample-data/subjects/sample/bem/sample-5120-5120-5120-bem.fif");//sample-5120-5120-5120-bem MNEBem t_Bem(t_fileBem); p3DDataModel->addBemData(parser.value(subjectOption), "BEM", t_Bem); //Read and show sensor helmets QFile t_filesensorSurfaceVV("./resources/general/sensorSurfaces/306m_rt.fif"); MNEBem t_sensorSurfaceVV(t_filesensorSurfaceVV); p3DDataModel->addMegSensorInfo("Sensors", "VectorView", evoked.info.chs, t_sensorSurfaceVV); // // Read & show digitizer points // QFile t_fileDig("./MNE-sample-data/MEG/sample/sample_audvis-ave.fif"); // FiffDigPointSet t_Dig(t_fileDig); // p3DDataModel->addDigitizerData(parser.value(subjectOption), evoked.comment, t_Dig); //Co-Register EEG points QFile coordTransfile("./MNE-sample-data/MEG/sample/all-trans.fif"); FiffCoordTrans coordTransA(coordTransfile); for(int i = 0; i < evoked.info.chs.size(); ++i) { if(evoked.info.chs.at(i).kind == FIFFV_EEG_CH) { Vector4f tempvec; tempvec(0) = evoked.info.chs.at(i).chpos.r0(0); tempvec(1) = evoked.info.chs.at(i).chpos.r0(1); tempvec(2) = evoked.info.chs.at(i).chpos.r0(2); tempvec(3) = 1; tempvec = coordTransA.invtrans * tempvec; evoked.info.chs[i].chpos.r0(0) = tempvec(0); evoked.info.chs[i].chpos.r0(1) = tempvec(1); evoked.info.chs[i].chpos.r0(2) = tempvec(2); } } //Create the 3D view View3D::SPtr testWindow = View3D::SPtr(new View3D()); //add sensor item for MEG data // if (SensorDataTreeItem* pMegSensorTreeItem = p3DDataModel->addSensorData(parser.value(subjectOption), // evoked.comment, // evoked.data, // t_sensorSurfaceVV[0], // evoked.info, // "MEG", // 0.10, // "Cubic", // testWindow->format())) { // pMegSensorTreeItem->setLoopState(true); // pMegSensorTreeItem->setTimeInterval(17); // pMegSensorTreeItem->setNumberAverages(1); // pMegSensorTreeItem->setStreamingState(false); // pMegSensorTreeItem->setNormalization(QVector3D(0.0, 3e-12/2, 3e-12)); // pMegSensorTreeItem->setColormapType("Jet"); // pMegSensorTreeItem->setSFreq(evoked.info.sfreq); // } //add sensor item for EEG data if (SensorDataTreeItem* pEegSensorTreeItem = p3DDataModel->addSensorData(parser.value(subjectOption), evoked.comment, evoked.data, t_Bem[0], evoked.info, "EEG", 0.05, "Cubic", testWindow->format())) { pEegSensorTreeItem->setLoopState(true); pEegSensorTreeItem->setTimeInterval(17); pEegSensorTreeItem->setNumberAverages(1); pEegSensorTreeItem->setStreamingState(false); //pEegSensorTreeItem->setThresholds(QVector3D(0.0, 6e-6/2, 6e-6)); pEegSensorTreeItem->setColormapType("Jet"); pEegSensorTreeItem->setSFreq(evoked.info.sfreq); } if(bAddRtSourceLoc) { //Add rt source loc data and init some visualization values if(MneEstimateTreeItem* pRTDataItem = p3DDataModel->addSourceData(parser.value(subjectOption), evoked.comment, sourceEstimate, t_clusteredFwd)) { pRTDataItem->setLoopState(true); pRTDataItem->setTimeInterval(0); pRTDataItem->setNumberAverages(1); pRTDataItem->setStreamingActive(false); pRTDataItem->setThresholds(QVector3D(0.0,0.5,10.0)); pRTDataItem->setVisualizationType("Smoothing based"); pRTDataItem->setColormapType("Jet"); } } //Setup window testWindow->setModel(p3DDataModel); testWindow->show(); Control3DWidget::SPtr control3DWidget = Control3DWidget::SPtr(new Control3DWidget()); control3DWidget->init(p3DDataModel, testWindow); control3DWidget->show(); return a.exec(); } <commit_msg>[LIB-176] Uncomment setThreshold<commit_after>//============================================================================================================= /** * @file main.cpp * @author Lorenz Esch <lorenz.esch@tu-ilmenau.de>; * Matti Hamalainen <msh@nmr.mgh.harvard.edu> * @version 1.0 * @date July, 2016 * * @section LICENSE * * Copyright (C) 2016, Lorenz Esch and Matti Hamalainen. 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 MNE-CPP authors 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. * * * @brief Example of using the MNE-CPP Disp3D library * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include <disp3D/engine/view/view3D.h> #include <disp3D/engine/control/control3dwidget.h> #include <disp3D/engine/model/items/sourceactivity/mneestimatetreeitem.h> #include <disp3D/engine/model/items/sensordata/sensordatatreeitem.h> #include <disp3D/engine/model/data3Dtreemodel.h> #include <fs/surfaceset.h> #include <fs/annotationset.h> #include <mne/mne_sourceestimate.h> #include <mne/mne_bem.h> #include <fiff/fiff_dig_point_set.h> #include <inverse/minimumNorm/minimumnorm.h> #include <disp3D/helpers/geometryinfo/geometryinfo.h> #include <disp3D/helpers/interpolation/interpolation.h> //************************************************************************************************************* //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <QApplication> #include <QMainWindow> #include <QCommandLineParser> //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace DISP3DLIB; using namespace MNELIB; using namespace FSLIB; using namespace FIFFLIB; using namespace INVERSELIB; //************************************************************************************************************* //============================================================================================================= // MAIN //============================================================================================================= //============================================================================================================= /** * The function main marks the entry point of the program. * By default, main has the storage class extern. * * @param [in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started. * @param [in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started. * @return the value that was set to exit() (which is 0 if exit() is called via quit()). */ int main(int argc, char *argv[]) { QApplication a(argc, argv); // Command Line Parser QCommandLineParser parser; parser.setApplicationDescription("Disp3D Example"); parser.addHelpOption(); QCommandLineOption surfOption("surfType", "Surface type <type>.", "type", "inflated"); QCommandLineOption annotOption("annotType", "Annotation type <type>.", "type", "aparc.a2009s"); QCommandLineOption hemiOption("hemi", "Selected hemisphere <hemi>.", "hemi", "2"); QCommandLineOption subjectOption("subject", "Selected subject <subject>.", "subject", "sample"); QCommandLineOption subjectPathOption("subjectPath", "Selected subject path <subjectPath>.", "subjectPath", "./MNE-sample-data/subjects"); QCommandLineOption sourceLocOption("doSourceLoc", "Do real time source localization.", "doSourceLoc", "false"); QCommandLineOption fwdOption("fwd", "Path to forwad solution <file>.", "file", "./MNE-sample-data/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif"); QCommandLineOption invOpOption("inv", "Path to inverse operator <file>.", "file", ""); QCommandLineOption clustOption("doClust", "Path to clustered inverse operator <doClust>.", "doClust", "true"); QCommandLineOption covFileOption("cov", "Path to the covariance <file>.", "file", "./MNE-sample-data/MEG/sample/sample_audvis-cov.fif"); QCommandLineOption evokedFileOption("ave", "Path to the evoked/average <file>.", "file", "./MNE-sample-data/MEG/sample/sample_audvis-ave.fif"); QCommandLineOption methodOption("method", "Inverse estimation <method>, i.e., 'MNE', 'dSPM' or 'sLORETA'.", "method", "dSPM");//"MNE" | "dSPM" | "sLORETA" QCommandLineOption snrOption("snr", "The SNR value used for computation <snr>.", "snr", "3.0");//3.0;//0.1;//3.0; QCommandLineOption evokedIndexOption("aveIdx", "The average <index> to choose from the average file.", "index", "3"); parser.addOption(surfOption); parser.addOption(annotOption); parser.addOption(hemiOption); parser.addOption(subjectOption); parser.addOption(subjectPathOption); parser.addOption(sourceLocOption); parser.addOption(fwdOption); parser.addOption(invOpOption); parser.addOption(clustOption); parser.addOption(covFileOption); parser.addOption(evokedFileOption); parser.addOption(methodOption); parser.addOption(snrOption); parser.addOption(evokedIndexOption); parser.process(a); bool bAddRtSourceLoc = false; if(parser.value(sourceLocOption) == "false" || parser.value(sourceLocOption) == "0") { bAddRtSourceLoc = false; } else if(parser.value(sourceLocOption) == "true" || parser.value(sourceLocOption) == "1") { bAddRtSourceLoc = true; } bool bDoClustering = false; if(parser.value(clustOption) == "false" || parser.value(clustOption) == "0") { bDoClustering = false; } else if(parser.value(clustOption) == "true" || parser.value(clustOption) == "1") { bDoClustering = true; } //Inits SurfaceSet tSurfSet (parser.value(subjectOption), parser.value(hemiOption).toInt(), parser.value(surfOption), parser.value(subjectPathOption)); AnnotationSet tAnnotSet (parser.value(subjectOption), parser.value(hemiOption).toInt(), parser.value(annotOption), parser.value(subjectPathOption)); QFile t_fileFwd(parser.value(fwdOption)); MNEForwardSolution t_Fwd(t_fileFwd); MNEForwardSolution t_clusteredFwd; QString t_sFileClusteredInverse(parser.value(invOpOption)); QFile t_fileCov(parser.value(covFileOption)); QFile t_fileEvoked(parser.value(evokedFileOption)); //######################################################################################## // // Source Estimate START // //######################################################################################## // Load data QPair<QVariant, QVariant> baseline(QVariant(), 0); MNESourceEstimate sourceEstimate; FiffEvoked evoked(t_fileEvoked, parser.value(evokedIndexOption).toInt(), baseline); if(bAddRtSourceLoc) { double snr = parser.value(snrOption).toDouble(); double lambda2 = 1.0 / pow(snr, 2); QString method(parser.value(methodOption)); // Load data t_fileEvoked.close(); if(evoked.isEmpty()) return 1; std::cout << std::endl; std::cout << "Evoked description: " << evoked.comment.toUtf8().constData() << std::endl; if(t_Fwd.isEmpty()) return 1; FiffCov noise_cov(t_fileCov); // regularize noise covariance noise_cov = noise_cov.regularize(evoked.info, 0.05, 0.05, 0.1, true); // // Cluster forward solution; // if(bDoClustering) { t_clusteredFwd = t_Fwd.cluster_forward_solution(tAnnotSet, 40); } else { t_clusteredFwd = t_Fwd; } // // make an inverse operators // FiffInfo info = evoked.info; MNEInverseOperator inverse_operator(info, t_clusteredFwd, noise_cov, 0.2f, 0.8f); if(!t_sFileClusteredInverse.isEmpty()) { QFile t_fileClusteredInverse(t_sFileClusteredInverse); inverse_operator.write(t_fileClusteredInverse); } // // Compute inverse solution // MinimumNorm minimumNorm(inverse_operator, lambda2, method); sourceEstimate = minimumNorm.calculateInverse(evoked); if(sourceEstimate.isEmpty()) return 1; // View activation time-series std::cout << "\nsourceEstimate:\n" << sourceEstimate.data.block(0,0,10,10) << std::endl; std::cout << "time\n" << sourceEstimate.times.block(0,0,1,10) << std::endl; std::cout << "timeMin\n" << sourceEstimate.times[0] << std::endl; std::cout << "timeMax\n" << sourceEstimate.times[sourceEstimate.times.size()-1] << std::endl; std::cout << "time step\n" << sourceEstimate.tstep << std::endl; } //######################################################################################## // //Source Estimate END // //######################################################################################## //Create 3D data model Data3DTreeModel::SPtr p3DDataModel = Data3DTreeModel::SPtr(new Data3DTreeModel()); //Add fressurfer surface set including both hemispheres p3DDataModel->addSurfaceSet(parser.value(subjectOption), "MRI", tSurfSet, tAnnotSet); //Read and show BEM QFile t_fileBem("./MNE-sample-data/subjects/sample/bem/sample-5120-5120-5120-bem.fif");//sample-5120-5120-5120-bem MNEBem t_Bem(t_fileBem); p3DDataModel->addBemData(parser.value(subjectOption), "BEM", t_Bem); //Read and show sensor helmets QFile t_filesensorSurfaceVV("./resources/general/sensorSurfaces/306m_rt.fif"); MNEBem t_sensorSurfaceVV(t_filesensorSurfaceVV); p3DDataModel->addMegSensorInfo("Sensors", "VectorView", evoked.info.chs, t_sensorSurfaceVV); // // Read & show digitizer points // QFile t_fileDig("./MNE-sample-data/MEG/sample/sample_audvis-ave.fif"); // FiffDigPointSet t_Dig(t_fileDig); // p3DDataModel->addDigitizerData(parser.value(subjectOption), evoked.comment, t_Dig); //Co-Register EEG points QFile coordTransfile("./MNE-sample-data/MEG/sample/all-trans.fif"); FiffCoordTrans coordTransA(coordTransfile); for(int i = 0; i < evoked.info.chs.size(); ++i) { if(evoked.info.chs.at(i).kind == FIFFV_EEG_CH) { Vector4f tempvec; tempvec(0) = evoked.info.chs.at(i).chpos.r0(0); tempvec(1) = evoked.info.chs.at(i).chpos.r0(1); tempvec(2) = evoked.info.chs.at(i).chpos.r0(2); tempvec(3) = 1; tempvec = coordTransA.invtrans * tempvec; evoked.info.chs[i].chpos.r0(0) = tempvec(0); evoked.info.chs[i].chpos.r0(1) = tempvec(1); evoked.info.chs[i].chpos.r0(2) = tempvec(2); } } //Create the 3D view View3D::SPtr testWindow = View3D::SPtr(new View3D()); //add sensor item for MEG data // if (SensorDataTreeItem* pMegSensorTreeItem = p3DDataModel->addSensorData(parser.value(subjectOption), // evoked.comment, // evoked.data, // t_sensorSurfaceVV[0], // evoked.info, // "MEG", // 0.10, // "Cubic", // testWindow->format())) { // pMegSensorTreeItem->setLoopState(true); // pMegSensorTreeItem->setTimeInterval(17); // pMegSensorTreeItem->setNumberAverages(1); // pMegSensorTreeItem->setStreamingState(false); // pMegSensorTreeItem->setNormalization(QVector3D(0.0, 3e-12/2, 3e-12)); // pMegSensorTreeItem->setColormapType("Jet"); // pMegSensorTreeItem->setSFreq(evoked.info.sfreq); // } //add sensor item for EEG data if (SensorDataTreeItem* pEegSensorTreeItem = p3DDataModel->addSensorData(parser.value(subjectOption), evoked.comment, evoked.data, t_Bem[0], evoked.info, "EEG", 0.05, "Cubic", testWindow->format())) { pEegSensorTreeItem->setLoopState(true); pEegSensorTreeItem->setTimeInterval(17); pEegSensorTreeItem->setNumberAverages(1); pEegSensorTreeItem->setStreamingState(false); pEegSensorTreeItem->setThresholds(QVector3D(0.0, 6e-6/2, 6e-6)); pEegSensorTreeItem->setColormapType("Jet"); pEegSensorTreeItem->setSFreq(evoked.info.sfreq); } if(bAddRtSourceLoc) { //Add rt source loc data and init some visualization values if(MneEstimateTreeItem* pRTDataItem = p3DDataModel->addSourceData(parser.value(subjectOption), evoked.comment, sourceEstimate, t_clusteredFwd)) { pRTDataItem->setLoopState(true); pRTDataItem->setTimeInterval(0); pRTDataItem->setNumberAverages(1); pRTDataItem->setStreamingActive(false); pRTDataItem->setThresholds(QVector3D(0.0,0.5,10.0)); pRTDataItem->setVisualizationType("Smoothing based"); pRTDataItem->setColormapType("Jet"); } } //Setup window testWindow->setModel(p3DDataModel); testWindow->show(); Control3DWidget::SPtr control3DWidget = Control3DWidget::SPtr(new Control3DWidget()); control3DWidget->init(p3DDataModel, testWindow); control3DWidget->show(); return a.exec(); } <|endoftext|>
<commit_before>/* linbox/algorithms/coppersmith-invariant-factors.h * Copyright (C) 2015 Gavin Harrison * * Written by Gavin Harrison <gavin.har@gmail.com> * * ========LICENCE======== * This file is part of the library LinBox. * * LinBox is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ========LICENCE======== */ #include "linbox/linbox-config.h" #include <iostream> #include <vector> #include "linbox/ring/modular.h" #include "linbox/matrix/sparse-matrix.h" #include "linbox/matrix/dense-matrix.h" #include "linbox/matrix/matrix-domain.h" #include "linbox/algorithms/invariant-factors.h" using namespace LinBox; typedef Givaro::Modular<double> Field; typedef typename Field::Element Element; typedef SparseMatrix<Field, SparseMatrixFormat::TPL> SparseMat; typedef InvariantFactors<Field,SparseMat> FactorDomain; typedef typename FactorDomain::PolyDom PolyDom; typedef typename FactorDomain::PolyRing PolyRing; typedef DenseVector<PolyRing> FactorVector; int main(int argc, char** argv) { int earlyTerm; int p = 3, b = 3; std::string mFname,oFname; static Argument args[] = { { 'p', "-p P", "Set the field GF(p)", TYPE_INT, &p}, { 't', "-t T", "Early term threshold", TYPE_INT, &earlyTerm}, { 'b', "-b B", "Blocking factor", TYPE_INT, &b}, { 'm', "-m M", "Name of file for matrix M", TYPE_STR, &mFname}, { 'o', "-o O", "Name of file for output", TYPE_STR, &oFname}, END_OF_ARGUMENTS }; parseArguments(argc,argv,args); Field F(p); SparseMat M(F); { std::ifstream iF(mFname); M.read(iF); M.finalize(); iF.close(); } std::cout << "Finished reading" << std::endl; PolyDom PD(F,"x"); PolyRing R(PD); FactorVector factorList(R); FactorDomain CIF(F, R); CIF.computeFactors(factorList, M, b, earlyTerm); std::cout << "Finished computing factors" << std::endl; { std::ofstream out(oFname); for (size_t i = 0; i<factorList.size(); i++) { R.write(out,factorList[i]); out << std::endl; } out.close(); } return 0; } <commit_msg>Add iliopolous domain to invariant factors domain<commit_after>/* linbox/algorithms/coppersmith-invariant-factors.h * Copyright (C) 2015 Gavin Harrison * * Written by Gavin Harrison <gavin.har@gmail.com> * * ========LICENCE======== * This file is part of the library LinBox. * * LinBox is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ========LICENCE======== */ #include "linbox/linbox-config.h" #include <iostream> #include <vector> #include "linbox/ring/modular.h" #include "linbox/matrix/sparse-matrix.h" #include "linbox/matrix/dense-matrix.h" #include "linbox/matrix/matrix-domain.h" #include "linbox/algorithms/invariant-factors.h" #include "linbox/algorithms/smith-form-iliopoulos2.h" using namespace LinBox; typedef Givaro::Modular<double> Field; typedef typename Field::Element Element; typedef SparseMatrix<Field, SparseMatrixFormat::TPL> SparseMat; typedef InvariantFactors<Field,SparseMat> FactorDomain; typedef typename FactorDomain::PolyDom PolyDom; typedef typename FactorDomain::PolyRing PolyRing; typedef DenseVector<PolyRing> FactorVector; int main(int argc, char** argv) { int earlyTerm; int p = 3, b = 3; std::string mFname,oFname; static Argument args[] = { { 'p', "-p P", "Set the field GF(p)", TYPE_INT, &p}, { 't', "-t T", "Early term threshold", TYPE_INT, &earlyTerm}, { 'b', "-b B", "Blocking factor", TYPE_INT, &b}, { 'm', "-m M", "Name of file for matrix M", TYPE_STR, &mFname}, { 'o', "-o O", "Name of file for output", TYPE_STR, &oFname}, END_OF_ARGUMENTS }; parseArguments(argc,argv,args); Field F(p); SparseMat M(F); { std::ifstream iF(mFname); M.read(iF); M.finalize(); iF.close(); } std::cout << "Finished reading" << std::endl; PolyDom PD(F,"x"); PolyRing R(PD); FactorVector factorList(R); FactorDomain CIF(F, R); IliopoulosDomain<PolyRing> ID(R); CIF.computeFactors(factorList, M, b, earlyTerm); std::cout << "Finished computing factors" << std::endl; { std::ofstream out(oFname); for (size_t i = 0; i<factorList.size(); i++) { R.write(out,factorList[i]); out << std::endl; } out.close(); } return 0; } <|endoftext|>
<commit_before>#include "App.hpp" #include "Config.hpp" #include "imgui/imgui.h" #include "imgui/imgui_impl_glfw_gl3.h" #define STB_IMAGE_IMPLEMENTATION #include <stb/stb_image.h> #define STB_IMAGE_WRITE_IMPLEMENTATION #include "stb/stb_image_write.h" App* App::_sInst = nullptr; const float TARGET_FPS = 60.0f; void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode); void scroll_callback(GLFWwindow* window, double xoffset, double yoffset); void mouse_button_callback(GLFWwindow* window, int button, int action, int mode); void mouse_pos_callback(GLFWwindow* window, double x, double y); App::~App() { delete _mWindow; _mWindow = nullptr; Camera::Delete(); ImGui_ImplGlfwGL3_Shutdown(); DeleteShaders(); } void App::Run() { const float targetElapsed = 1.0f / TARGET_FPS; Start(); float prevTime = 0.0f; while (!GetWindow()->ShouldClose()) { float currTime = (float)glfwGetTime(); float elapsed = currTime - prevTime; float dt = elapsed / targetElapsed; HandleInput(dt); Update(dt); Render(); prevTime = currTime; } } void App::Start() { // Welcome printf("Temporality Engine v%s\n\n", VERSION); // Window _mWindow = new Window(1024, 768); // Display OpenGL info OpenGLInfo(); // Load Engine Shaders AddShader("axis", new Shader({ "shaders/axis.vert", "shaders/axis.frag" })); // Clear Window glClearColor(0.2f, 0.3f, 0.3f, 1.0f); // Depth glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); // Blend glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Setup Scene _mCurrentScene->Start(); GLFWwindow * glfwWin = GetWindow()->GetGLFWWindow(); // Input glfwSetKeyCallback(glfwWin, &key_callback); glfwSetMouseButtonCallback(glfwWin, &mouse_button_callback); glfwSetScrollCallback(glfwWin, &scroll_callback); glfwSetCursorPosCallback(glfwWin, &mouse_pos_callback); glfwSetInputMode(glfwWin, GLFW_CURSOR, GLFW_CURSOR_NORMAL); // Movement _mInputMap[GLFW_KEY_W] = false; _mInputMap[GLFW_KEY_A] = false; _mInputMap[GLFW_KEY_S] = false; _mInputMap[GLFW_KEY_D] = false; _mInputMap[GLFW_KEY_Q] = false; _mInputMap[GLFW_KEY_E] = false; _mInputMap[GLFW_MOUSE_BUTTON_RIGHT] = false; // Other Input keys _mInputMap[GLFW_KEY_H] = false; // Register the options function into the UI DevUI::RegisterOptionsFunc(&Scene::Options); } void App::Update(float dt) { glfwPollEvents(); _mCurrentScene->Update(dt); } void App::Render() { _mWindow->Clear(); _mCurrentScene->Render(); DevUI::Render(); _mWindow->Present(); } void App::OpenGLInfo() { // OpenGL Basic Info printf("OpenGL Vendor: %s\n", glGetString(GL_VENDOR)); printf("OpenGL Renderer: %s\n", glGetString(GL_RENDERER)); printf("OpenGL Version: %s\n", glGetString(GL_VERSION)); printf("GLSL Version: %s\n\n", glGetString(GL_SHADING_LANGUAGE_VERSION)); // Anti-Aliasing int samples; glGetIntegerv(GL_SAMPLES, &samples); printf("Anti-Aliasing: %dx\n", samples); // Binary Shader Formats GLint formats = 0; glGetIntegerv(GL_NUM_PROGRAM_BINARY_FORMATS, &formats); printf("Binary Shader Formats: %d\n", formats); // Max UBO Size int tmp; glGetIntegerv(GL_MAX_UNIFORM_BLOCK_SIZE, &tmp); printf("Max UBO Size: %d\n", tmp); // Max Vertex UBOs glGetIntegerv(GL_MAX_VERTEX_UNIFORM_BLOCKS, &tmp); printf("Max Vertex UBOs: %d\n", tmp); // Max Fragment UBOs glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_BLOCKS, &tmp); printf("Max Fragment UBOs: %d\n", tmp); // Max Geometry UBOs glGetIntegerv(GL_MAX_GEOMETRY_UNIFORM_BLOCKS, &tmp); printf("Max Geometry UBOs: %d\n", tmp); // Max UBO Bindings int maxBindings; glGetIntegerv(GL_MAX_UNIFORM_BUFFER_BINDINGS, &maxBindings); printf("Max UBO Bindings: %d\n", maxBindings); } void App::Screenshot() { std::vector<unsigned int> pixels(3 * GetWindow()->GetWidth() * GetWindow()->GetHeight()); glReadPixels(0, 0, GetWindow()->GetWidth(), GetWindow()->GetHeight(), GL_RGB, GL_UNSIGNED_BYTE, pixels.data()); stbi_flip_vertically_on_write(true); stbi_write_png("Screenshot.png", GetWindow()->GetWidth(), GetWindow()->GetHeight(), 3, pixels.data(), 3 * GetWindow()->GetWidth()); } void App::AddShader(std::string name, Shader* shader) { _mShaders[name] = shader; } Shader* App::GetShader(std::string name) { if (_mShaders.find(name) == _mShaders.end()) { return nullptr; } return _mShaders[name]; } void App::DeleteShaders() { // Destroy the shaders for (auto& shader : _mShaders) shader.second->Destroy(); // Clear shader vector _mShaders.clear(); } void App::ReloadShaders() { for (auto s : _mShaders) s.second->Reload(); } void App::HandleInput(float dt) { if (_mInputMap[GLFW_KEY_W]) Camera::Inst().HandleMovement(Direction::FORWARD, dt); if (_mInputMap[GLFW_KEY_S]) Camera::Inst().HandleMovement(Direction::BACKWARD, dt); if (_mInputMap[GLFW_KEY_A]) Camera::Inst().HandleMovement(Direction::LEFT, dt); if (_mInputMap[GLFW_KEY_D]) Camera::Inst().HandleMovement(Direction::RIGHT, dt); if (_mInputMap[GLFW_KEY_Q]) Camera::Inst().HandleMovement(Direction::UP, dt); if (_mInputMap[GLFW_KEY_E]) Camera::Inst().HandleMovement(Direction::DOWN, dt); } void App::HandleGLFWKey(GLFWwindow* window, int key, int scancode, int action, int mode) { if (action == GLFW_RELEASE) { if (_mInputMap.find(key) != _mInputMap.end()) { _mInputMap[key] = false; } } if (action == GLFW_PRESS) { if (_mInputMap.find(key) != _mInputMap.end()) { _mInputMap[key] = true; } switch (key) { case GLFW_KEY_F5: // Reloads shaders { std::cout << "\nReloading shaders!\n"; //_mCurrentScene->DeleteShaders(); //_mCurrentScene->SetupShaders(); ReloadShaders(); break; } case GLFW_KEY_PRINT_SCREEN: { Screenshot(); break; } } } DevUI::HandleKeyEvent(key, scancode, action, mode); ImGui_ImplGlfw_KeyCallback(window, key, scancode, action, mode); } void App::HandleGLFWMouseButton(GLFWwindow* window, int button, int action, int mode) { if (action == GLFW_RELEASE) { if (_mInputMap.find(button) != _mInputMap.end()) { _mInputMap[button] = false; } } if (action == GLFW_PRESS) { if (_mInputMap.find(button) != _mInputMap.end()) { _mInputMap[button] = true; } } // Handle mouse button ImGui_ImplGlfw_MouseButtonCallback(window, button, action, mode); } void App::HandleGLFWScroll(GLFWwindow* window, double xoffset, double yoffset) { Camera::Inst().HandleFoV((float)xoffset, (float)yoffset); // scroll ImGui_ImplGlfw_ScrollCallback(window, xoffset, yoffset); } void App::HandleGLFWMousePos(GLFWwindow* window, double x, double y) { if (_mLastMX < 0 && _mLastMY < 0) { _mLastMX = (float)x; _mLastMY = (float)y; } float xoffset = (float)x - _mLastMX; float yoffset = _mLastMY - (float)y; _mLastMX = (float)x; _mLastMY = (float)y; // handle mouse pos if (_mInputMap[GLFW_MOUSE_BUTTON_RIGHT]) { Camera::Inst().HandleRotation(xoffset, yoffset); } } // Not part of the class itself but used for key callback. void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode) { App::Inst()->HandleGLFWKey(window, key, scancode, action, mode); } void mouse_button_callback(GLFWwindow* window, int button, int action, int mode) { App::Inst()->HandleGLFWMouseButton(window, button, action, mode); } void scroll_callback(GLFWwindow* window, double xoffset, double yoffset) { App::Inst()->HandleGLFWScroll(window, xoffset, yoffset); } void mouse_pos_callback(GLFWwindow* window, double x, double y) { App::Inst()->HandleGLFWMousePos(window, x, y); } <commit_msg>Frame Limiting should be working correctly now.<commit_after>#include "App.hpp" #include "Config.hpp" #include "imgui/imgui.h" #include "imgui/imgui_impl_glfw_gl3.h" #define STB_IMAGE_IMPLEMENTATION #include <stb/stb_image.h> #define STB_IMAGE_WRITE_IMPLEMENTATION #include "stb/stb_image_write.h" App* App::_sInst = nullptr; const float TARGET_FPS = 60.0f; void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode); void scroll_callback(GLFWwindow* window, double xoffset, double yoffset); void mouse_button_callback(GLFWwindow* window, int button, int action, int mode); void mouse_pos_callback(GLFWwindow* window, double x, double y); App::~App() { delete _mWindow; _mWindow = nullptr; Camera::Delete(); ImGui_ImplGlfwGL3_Shutdown(); DeleteShaders(); } void App::Run() { const float targetElapsed = 1.0f / TARGET_FPS; Start(); float prevTime = 0.0f; float frameTime = 0.0f; while (!GetWindow()->ShouldClose()) { float currTime = (float)glfwGetTime(); float elapsed = currTime - prevTime; frameTime += elapsed; float dt = elapsed / targetElapsed; HandleInput(dt); Update(dt); if (frameTime >= targetElapsed) { frameTime = 0.0f; Render(); } prevTime = currTime; } } void App::Start() { // Welcome printf("Temporality Engine v%s\n\n", VERSION); // Window _mWindow = new Window(1024, 768); // Display OpenGL info OpenGLInfo(); // Load Engine Shaders AddShader("axis", new Shader({ "shaders/axis.vert", "shaders/axis.frag" })); // Clear Window glClearColor(0.2f, 0.3f, 0.3f, 1.0f); // Depth glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); // Blend glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Setup Scene _mCurrentScene->Start(); GLFWwindow * glfwWin = GetWindow()->GetGLFWWindow(); // Input glfwSetKeyCallback(glfwWin, &key_callback); glfwSetMouseButtonCallback(glfwWin, &mouse_button_callback); glfwSetScrollCallback(glfwWin, &scroll_callback); glfwSetCursorPosCallback(glfwWin, &mouse_pos_callback); glfwSetInputMode(glfwWin, GLFW_CURSOR, GLFW_CURSOR_NORMAL); // Movement _mInputMap[GLFW_KEY_W] = false; _mInputMap[GLFW_KEY_A] = false; _mInputMap[GLFW_KEY_S] = false; _mInputMap[GLFW_KEY_D] = false; _mInputMap[GLFW_KEY_Q] = false; _mInputMap[GLFW_KEY_E] = false; _mInputMap[GLFW_MOUSE_BUTTON_RIGHT] = false; // Other Input keys _mInputMap[GLFW_KEY_H] = false; // Register the options function into the UI DevUI::RegisterOptionsFunc(&Scene::Options); } void App::Update(float dt) { glfwPollEvents(); _mCurrentScene->Update(dt); } void App::Render() { _mWindow->Clear(); _mCurrentScene->Render(); DevUI::Render(); _mWindow->Present(); } void App::OpenGLInfo() { // OpenGL Basic Info printf("OpenGL Vendor: %s\n", glGetString(GL_VENDOR)); printf("OpenGL Renderer: %s\n", glGetString(GL_RENDERER)); printf("OpenGL Version: %s\n", glGetString(GL_VERSION)); printf("GLSL Version: %s\n\n", glGetString(GL_SHADING_LANGUAGE_VERSION)); // Anti-Aliasing int samples; glGetIntegerv(GL_SAMPLES, &samples); printf("Anti-Aliasing: %dx\n", samples); // Binary Shader Formats GLint formats = 0; glGetIntegerv(GL_NUM_PROGRAM_BINARY_FORMATS, &formats); printf("Binary Shader Formats: %d\n", formats); // Max UBO Size int tmp; glGetIntegerv(GL_MAX_UNIFORM_BLOCK_SIZE, &tmp); printf("Max UBO Size: %d\n", tmp); // Max Vertex UBOs glGetIntegerv(GL_MAX_VERTEX_UNIFORM_BLOCKS, &tmp); printf("Max Vertex UBOs: %d\n", tmp); // Max Fragment UBOs glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_BLOCKS, &tmp); printf("Max Fragment UBOs: %d\n", tmp); // Max Geometry UBOs glGetIntegerv(GL_MAX_GEOMETRY_UNIFORM_BLOCKS, &tmp); printf("Max Geometry UBOs: %d\n", tmp); // Max UBO Bindings int maxBindings; glGetIntegerv(GL_MAX_UNIFORM_BUFFER_BINDINGS, &maxBindings); printf("Max UBO Bindings: %d\n", maxBindings); } void App::Screenshot() { std::vector<unsigned int> pixels(3 * GetWindow()->GetWidth() * GetWindow()->GetHeight()); glReadPixels(0, 0, GetWindow()->GetWidth(), GetWindow()->GetHeight(), GL_RGB, GL_UNSIGNED_BYTE, pixels.data()); stbi_flip_vertically_on_write(true); stbi_write_png("Screenshot.png", GetWindow()->GetWidth(), GetWindow()->GetHeight(), 3, pixels.data(), 3 * GetWindow()->GetWidth()); } void App::AddShader(std::string name, Shader* shader) { _mShaders[name] = shader; } Shader* App::GetShader(std::string name) { if (_mShaders.find(name) == _mShaders.end()) { return nullptr; } return _mShaders[name]; } void App::DeleteShaders() { // Destroy the shaders for (auto& shader : _mShaders) shader.second->Destroy(); // Clear shader vector _mShaders.clear(); } void App::ReloadShaders() { for (auto s : _mShaders) s.second->Reload(); } void App::HandleInput(float dt) { if (_mInputMap[GLFW_KEY_W]) Camera::Inst().HandleMovement(Direction::FORWARD, dt); if (_mInputMap[GLFW_KEY_S]) Camera::Inst().HandleMovement(Direction::BACKWARD, dt); if (_mInputMap[GLFW_KEY_A]) Camera::Inst().HandleMovement(Direction::LEFT, dt); if (_mInputMap[GLFW_KEY_D]) Camera::Inst().HandleMovement(Direction::RIGHT, dt); if (_mInputMap[GLFW_KEY_Q]) Camera::Inst().HandleMovement(Direction::UP, dt); if (_mInputMap[GLFW_KEY_E]) Camera::Inst().HandleMovement(Direction::DOWN, dt); } void App::HandleGLFWKey(GLFWwindow* window, int key, int scancode, int action, int mode) { if (action == GLFW_RELEASE) { if (_mInputMap.find(key) != _mInputMap.end()) { _mInputMap[key] = false; } } if (action == GLFW_PRESS) { if (_mInputMap.find(key) != _mInputMap.end()) { _mInputMap[key] = true; } switch (key) { case GLFW_KEY_F5: // Reloads shaders { std::cout << "\nReloading shaders!\n"; //_mCurrentScene->DeleteShaders(); //_mCurrentScene->SetupShaders(); ReloadShaders(); break; } case GLFW_KEY_PRINT_SCREEN: { Screenshot(); break; } } } DevUI::HandleKeyEvent(key, scancode, action, mode); ImGui_ImplGlfw_KeyCallback(window, key, scancode, action, mode); } void App::HandleGLFWMouseButton(GLFWwindow* window, int button, int action, int mode) { if (action == GLFW_RELEASE) { if (_mInputMap.find(button) != _mInputMap.end()) { _mInputMap[button] = false; } } if (action == GLFW_PRESS) { if (_mInputMap.find(button) != _mInputMap.end()) { _mInputMap[button] = true; } } // Handle mouse button ImGui_ImplGlfw_MouseButtonCallback(window, button, action, mode); } void App::HandleGLFWScroll(GLFWwindow* window, double xoffset, double yoffset) { Camera::Inst().HandleFoV((float)xoffset, (float)yoffset); // scroll ImGui_ImplGlfw_ScrollCallback(window, xoffset, yoffset); } void App::HandleGLFWMousePos(GLFWwindow* window, double x, double y) { if (_mLastMX < 0 && _mLastMY < 0) { _mLastMX = (float)x; _mLastMY = (float)y; } float xoffset = (float)x - _mLastMX; float yoffset = _mLastMY - (float)y; _mLastMX = (float)x; _mLastMY = (float)y; // handle mouse pos if (_mInputMap[GLFW_MOUSE_BUTTON_RIGHT]) { Camera::Inst().HandleRotation(xoffset, yoffset); } } // Not part of the class itself but used for key callback. void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode) { App::Inst()->HandleGLFWKey(window, key, scancode, action, mode); } void mouse_button_callback(GLFWwindow* window, int button, int action, int mode) { App::Inst()->HandleGLFWMouseButton(window, button, action, mode); } void scroll_callback(GLFWwindow* window, double xoffset, double yoffset) { App::Inst()->HandleGLFWScroll(window, xoffset, yoffset); } void mouse_pos_callback(GLFWwindow* window, double x, double y) { App::Inst()->HandleGLFWMousePos(window, x, y); } <|endoftext|>
<commit_before>/****************************************************************************** This source file is part of the Avogadro project. Copyright 2014 Kitware, Inc. This source code is released under the New BSD License, (the "License"). 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 "vtkglwidget.h" #include <avogadro/core/cube.h> #include <avogadro/qtgui/molecule.h> #include <avogadro/qtgui/sceneplugin.h> #include <avogadro/qtgui/scenepluginmodel.h> #include <avogadro/qtgui/toolplugin.h> #include "vtkAvogadroActor.h" #include <QVTKInteractor.h> #include <vtkColorTransferFunction.h> #include <vtkGenericOpenGLRenderWindow.h> #include <vtkImageData.h> #include <vtkImageShiftScale.h> #include <vtkInteractorStyleTrackballCamera.h> #include <vtkLookupTable.h> #include <vtkPiecewiseFunction.h> #include <vtkRenderViewBase.h> #include <vtkRenderer.h> #include <vtkRenderer.h> #include <vtkSmartVolumeMapper.h> #include <vtkVolume.h> #include <vtkVolumeProperty.h> #include <vtkPolyDataMapper.h> #include <vtkSphereSource.h> #include <QDebug> namespace Avogadro { namespace VTK { vtkVolume* cubeVolume(Core::Cube* cube) { qDebug() << "Cube dimensions: " << cube->dimensions().x() << cube->dimensions().y() << cube->dimensions().z(); qDebug() << "min/max:" << cube->minValue() << cube->maxValue(); qDebug() << cube->data()->size(); vtkNew<vtkImageData> data; // data->SetNumberOfScalarComponents(1, nullptr); Eigen::Vector3i dim = cube->dimensions(); data->SetExtent(0, dim.x() - 1, 0, dim.y() - 1, 0, dim.z() - 1); data->SetOrigin(cube->min().x(), cube->min().y(), cube->min().z()); data->SetSpacing(cube->spacing().data()); data->AllocateScalars(VTK_DOUBLE, 1); double* dataPtr = static_cast<double*>(data->GetScalarPointer()); std::vector<double>* cubePtr = cube->data(); for (int i = 0; i < dim.x(); ++i) for (int j = 0; j < dim.y(); ++j) for (int k = 0; k < dim.z(); ++k) { dataPtr[(k * dim.y() + j) * dim.x() + i] = (*cubePtr)[(i * dim.y() + j) * dim.z() + k]; } double range[2]; range[0] = data->GetScalarRange()[0]; range[1] = data->GetScalarRange()[1]; // a->GetRange(range); qDebug() << "ImageData range: " << range[0] << range[1]; vtkNew<vtkImageShiftScale> t; t->SetInputData(data.GetPointer()); t->SetShift(-range[0]); double magnitude = range[1] - range[0]; if (magnitude == 0.0) { magnitude = 1.0; } t->SetScale(255.0 / magnitude); t->SetOutputScalarTypeToDouble(); qDebug() << "magnitude: " << magnitude; t->Update(); vtkNew<vtkSmartVolumeMapper> volumeMapper; vtkNew<vtkVolumeProperty> volumeProperty; vtkVolume* volume = vtkVolume::New(); volumeMapper->SetBlendModeToComposite(); // volumeMapper->SetBlendModeToComposite(); // composite first volumeMapper->SetInputConnection(t->GetOutputPort()); volumeProperty->ShadeOff(); volumeProperty->SetInterpolationTypeToLinear(); vtkNew<vtkPiecewiseFunction> compositeOpacity; vtkNew<vtkColorTransferFunction> color; // if (cube->cubeType() == Core::Cube::MO) { compositeOpacity->AddPoint(0.00, 0.6); compositeOpacity->AddPoint(63.75, 0.7); compositeOpacity->AddPoint(127.50, 0.0); compositeOpacity->AddPoint(192.25, 0.7); compositeOpacity->AddPoint(255.00, 0.6); color->AddRGBPoint(0.00, 1.0, 0.0, 0.0); color->AddRGBPoint(63.75, 0.8, 0.0, 0.0); color->AddRGBPoint(127.50, 0.0, 0.1, 0.0); color->AddRGBPoint(192.25, 0.0, 0.0, 0.8); color->AddRGBPoint(255.00, 0.0, 0.0, 1.0); //} // else { // compositeOpacity->AddPoint( 0.00, 0.00); // compositeOpacity->AddPoint( 1.75, 0.30); // compositeOpacity->AddPoint( 2.50, 0.50); // compositeOpacity->AddPoint(192.25, 0.85); // compositeOpacity->AddPoint(255.00, 0.90); // color->AddRGBPoint( 0.00, 0.0, 0.0, 1.0); // color->AddRGBPoint( 63.75, 0.0, 0.0, 0.8); // color->AddRGBPoint(127.50, 0.0, 0.0, 0.5); // color->AddRGBPoint(191.25, 0.0, 0.0, 0.2); // color->AddRGBPoint(255.00, 0.0, 0.0, 0.0); // } volumeProperty->SetScalarOpacity( compositeOpacity.GetPointer()); // composite first. volumeProperty->SetColor(color.GetPointer()); volume->SetMapper(volumeMapper.GetPointer()); volume->SetProperty(volumeProperty.GetPointer()); return volume; } vtkGLWidget::vtkGLWidget(QWidget* p, Qt::WindowFlags f) : QVTKOpenGLWidget(p, f), m_activeTool(nullptr), m_defaultTool(nullptr) { setFocusPolicy(Qt::ClickFocus); connect(&m_scenePlugins, SIGNAL(pluginStateChanged(Avogadro::QtGui::ScenePlugin*)), SLOT(updateScene())); // Set up our renderer, window, scene, etc. GetRenderWindow()->AddRenderer(m_vtkRenderer.Get()); vtkNew<vtkInteractorStyleTrackballCamera> interactor; GetInteractor()->SetInteractorStyle(interactor.Get()); GetInteractor()->Initialize(); m_actor->setScene(&this->renderer().scene()); m_vtkRenderer->AddActor(m_actor.Get()); // GetRenderWindow()->SetSwapBuffers(0); // setAutoBufferSwap(true); } vtkGLWidget::~vtkGLWidget() { } void vtkGLWidget::setMolecule(QtGui::Molecule* mol) { clearScene(); if (m_molecule) disconnect(m_molecule, 0, 0, 0); m_molecule = mol; foreach (QtGui::ToolPlugin* tool, m_tools) tool->setMolecule(m_molecule); connect(m_molecule, SIGNAL(changed(unsigned int)), SLOT(updateScene())); if (mol->cubeCount() > 0) { vtkVolume* vol = cubeVolume(mol->cube(0)); m_vtkRenderer->AddViewProp(vol); } } QtGui::Molecule* vtkGLWidget::molecule() { return m_molecule; } const QtGui::Molecule* vtkGLWidget::molecule() const { return m_molecule; } void vtkGLWidget::updateScene() { // Build up the scene with the scene plugins, creating the appropriate nodes. QtGui::Molecule* mol = m_molecule; if (!mol) mol = new QtGui::Molecule(this); if (mol) { Rendering::GroupNode& node = m_renderer.scene().rootNode(); node.clear(); Rendering::GroupNode* moleculeNode = new Rendering::GroupNode(&node); foreach (QtGui::ScenePlugin* scenePlugin, m_scenePlugins.activeScenePlugins()) { Rendering::GroupNode* engineNode = new Rendering::GroupNode(moleculeNode); scenePlugin->process(*mol, *engineNode); } // Let the tools perform any drawing they need to do. if (m_activeTool) { Rendering::GroupNode* toolNode = new Rendering::GroupNode(moleculeNode); m_activeTool->draw(*toolNode); } if (m_defaultTool) { Rendering::GroupNode* toolNode = new Rendering::GroupNode(moleculeNode); m_defaultTool->draw(*toolNode); } m_renderer.resetGeometry(); update(); } if (mol != m_molecule) delete mol; } void vtkGLWidget::clearScene() { m_renderer.scene().clear(); } void vtkGLWidget::resetCamera() { m_renderer.resetCamera(); update(); } void vtkGLWidget::resetGeometry() { m_renderer.resetGeometry(); } } } <commit_msg>Fix clang-format error in vtkglwidget.cpp<commit_after>/****************************************************************************** This source file is part of the Avogadro project. Copyright 2014 Kitware, Inc. This source code is released under the New BSD License, (the "License"). 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 "vtkglwidget.h" #include <avogadro/core/cube.h> #include <avogadro/qtgui/molecule.h> #include <avogadro/qtgui/sceneplugin.h> #include <avogadro/qtgui/scenepluginmodel.h> #include <avogadro/qtgui/toolplugin.h> #include "vtkAvogadroActor.h" #include <QVTKInteractor.h> #include <vtkColorTransferFunction.h> #include <vtkGenericOpenGLRenderWindow.h> #include <vtkImageData.h> #include <vtkImageShiftScale.h> #include <vtkInteractorStyleTrackballCamera.h> #include <vtkLookupTable.h> #include <vtkPiecewiseFunction.h> #include <vtkRenderViewBase.h> #include <vtkRenderer.h> #include <vtkSmartVolumeMapper.h> #include <vtkVolume.h> #include <vtkVolumeProperty.h> #include <vtkPolyDataMapper.h> #include <vtkSphereSource.h> #include <QDebug> namespace Avogadro { namespace VTK { vtkVolume* cubeVolume(Core::Cube* cube) { qDebug() << "Cube dimensions: " << cube->dimensions().x() << cube->dimensions().y() << cube->dimensions().z(); qDebug() << "min/max:" << cube->minValue() << cube->maxValue(); qDebug() << cube->data()->size(); vtkNew<vtkImageData> data; // data->SetNumberOfScalarComponents(1, nullptr); Eigen::Vector3i dim = cube->dimensions(); data->SetExtent(0, dim.x() - 1, 0, dim.y() - 1, 0, dim.z() - 1); data->SetOrigin(cube->min().x(), cube->min().y(), cube->min().z()); data->SetSpacing(cube->spacing().data()); data->AllocateScalars(VTK_DOUBLE, 1); double* dataPtr = static_cast<double*>(data->GetScalarPointer()); std::vector<double>* cubePtr = cube->data(); for (int i = 0; i < dim.x(); ++i) for (int j = 0; j < dim.y(); ++j) for (int k = 0; k < dim.z(); ++k) { dataPtr[(k * dim.y() + j) * dim.x() + i] = (*cubePtr)[(i * dim.y() + j) * dim.z() + k]; } double range[2]; range[0] = data->GetScalarRange()[0]; range[1] = data->GetScalarRange()[1]; // a->GetRange(range); qDebug() << "ImageData range: " << range[0] << range[1]; vtkNew<vtkImageShiftScale> t; t->SetInputData(data.GetPointer()); t->SetShift(-range[0]); double magnitude = range[1] - range[0]; if (magnitude == 0.0) { magnitude = 1.0; } t->SetScale(255.0 / magnitude); t->SetOutputScalarTypeToDouble(); qDebug() << "magnitude: " << magnitude; t->Update(); vtkNew<vtkSmartVolumeMapper> volumeMapper; vtkNew<vtkVolumeProperty> volumeProperty; vtkVolume* volume = vtkVolume::New(); volumeMapper->SetBlendModeToComposite(); // volumeMapper->SetBlendModeToComposite(); // composite first volumeMapper->SetInputConnection(t->GetOutputPort()); volumeProperty->ShadeOff(); volumeProperty->SetInterpolationTypeToLinear(); vtkNew<vtkPiecewiseFunction> compositeOpacity; vtkNew<vtkColorTransferFunction> color; // if (cube->cubeType() == Core::Cube::MO) { compositeOpacity->AddPoint(0.00, 0.6); compositeOpacity->AddPoint(63.75, 0.7); compositeOpacity->AddPoint(127.50, 0.0); compositeOpacity->AddPoint(192.25, 0.7); compositeOpacity->AddPoint(255.00, 0.6); color->AddRGBPoint(0.00, 1.0, 0.0, 0.0); color->AddRGBPoint(63.75, 0.8, 0.0, 0.0); color->AddRGBPoint(127.50, 0.0, 0.1, 0.0); color->AddRGBPoint(192.25, 0.0, 0.0, 0.8); color->AddRGBPoint(255.00, 0.0, 0.0, 1.0); //} // else { // compositeOpacity->AddPoint( 0.00, 0.00); // compositeOpacity->AddPoint( 1.75, 0.30); // compositeOpacity->AddPoint( 2.50, 0.50); // compositeOpacity->AddPoint(192.25, 0.85); // compositeOpacity->AddPoint(255.00, 0.90); // color->AddRGBPoint( 0.00, 0.0, 0.0, 1.0); // color->AddRGBPoint( 63.75, 0.0, 0.0, 0.8); // color->AddRGBPoint(127.50, 0.0, 0.0, 0.5); // color->AddRGBPoint(191.25, 0.0, 0.0, 0.2); // color->AddRGBPoint(255.00, 0.0, 0.0, 0.0); // } volumeProperty->SetScalarOpacity( compositeOpacity.GetPointer()); // composite first. volumeProperty->SetColor(color.GetPointer()); volume->SetMapper(volumeMapper.GetPointer()); volume->SetProperty(volumeProperty.GetPointer()); return volume; } vtkGLWidget::vtkGLWidget(QWidget* p, Qt::WindowFlags f) : QVTKOpenGLWidget(p, f), m_activeTool(nullptr), m_defaultTool(nullptr) { setFocusPolicy(Qt::ClickFocus); connect(&m_scenePlugins, SIGNAL(pluginStateChanged(Avogadro::QtGui::ScenePlugin*)), SLOT(updateScene())); // Set up our renderer, window, scene, etc. GetRenderWindow()->AddRenderer(m_vtkRenderer.Get()); vtkNew<vtkInteractorStyleTrackballCamera> interactor; GetInteractor()->SetInteractorStyle(interactor.Get()); GetInteractor()->Initialize(); m_actor->setScene(&this->renderer().scene()); m_vtkRenderer->AddActor(m_actor.Get()); // GetRenderWindow()->SetSwapBuffers(0); // setAutoBufferSwap(true); } vtkGLWidget::~vtkGLWidget() { } void vtkGLWidget::setMolecule(QtGui::Molecule* mol) { clearScene(); if (m_molecule) disconnect(m_molecule, 0, 0, 0); m_molecule = mol; foreach (QtGui::ToolPlugin* tool, m_tools) tool->setMolecule(m_molecule); connect(m_molecule, SIGNAL(changed(unsigned int)), SLOT(updateScene())); if (mol->cubeCount() > 0) { vtkVolume* vol = cubeVolume(mol->cube(0)); m_vtkRenderer->AddViewProp(vol); } } QtGui::Molecule* vtkGLWidget::molecule() { return m_molecule; } const QtGui::Molecule* vtkGLWidget::molecule() const { return m_molecule; } void vtkGLWidget::updateScene() { // Build up the scene with the scene plugins, creating the appropriate nodes. QtGui::Molecule* mol = m_molecule; if (!mol) mol = new QtGui::Molecule(this); if (mol) { Rendering::GroupNode& node = m_renderer.scene().rootNode(); node.clear(); Rendering::GroupNode* moleculeNode = new Rendering::GroupNode(&node); foreach (QtGui::ScenePlugin* scenePlugin, m_scenePlugins.activeScenePlugins()) { Rendering::GroupNode* engineNode = new Rendering::GroupNode(moleculeNode); scenePlugin->process(*mol, *engineNode); } // Let the tools perform any drawing they need to do. if (m_activeTool) { Rendering::GroupNode* toolNode = new Rendering::GroupNode(moleculeNode); m_activeTool->draw(*toolNode); } if (m_defaultTool) { Rendering::GroupNode* toolNode = new Rendering::GroupNode(moleculeNode); m_defaultTool->draw(*toolNode); } m_renderer.resetGeometry(); update(); } if (mol != m_molecule) delete mol; } void vtkGLWidget::clearScene() { m_renderer.scene().clear(); } void vtkGLWidget::resetCamera() { m_renderer.resetCamera(); update(); } void vtkGLWidget::resetGeometry() { m_renderer.resetGeometry(); } } } <|endoftext|>
<commit_before>#pragma ident "$Id$" //============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // any later version. // // The GPSTk 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 GPSTk; if not, write to the Free Software Foundation, // Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Copyright 2004, The University of Texas at Austin // //============================================================================ //============================================================================ // //This software developed by Applied Research Laboratories at the University of //Texas at Austin, under contract to an agency or agencies within the U.S. //Department of Defense. The U.S. Government retains all rights to use, //duplicate, distribute, disclose, or release this software. // //Pursuant to DoD Directive 523024 // // DISTRIBUTION STATEMENT A: This software has been approved for public // release, distribution is unlimited. // //============================================================================= #include <iostream> #include "OrdApp.hpp" using namespace std; using namespace gpstk; const string OrdApp::defaultTimeFormat("%4Y %3j %02H:%02M:%04.1f"); //----------------------------------------------------------------------------- // The constructor basically just sets up all the command line options //----------------------------------------------------------------------------- OrdApp::OrdApp( const string& applName, const string& appDesc) throw() : BasicFramework(applName, appDesc), timeFormat(defaultTimeFormat), headerWritten(false), inputOpt('i', "input", "Where to get the data to analyze. The default is stdin."), outputOpt('r', "output", "Where to send the output. The default is stdout."), timeFormatOpt('t', "time-format", "Daytime format specifier used for " "times in the output. The default is \"" + defaultTimeFormat + "\".") {} //----------------------------------------------------------------------------- // Here the command line options parsed and used to configure the program //----------------------------------------------------------------------------- bool OrdApp::initialize(int argc, char *argv[]) throw() { if (!BasicFramework::initialize(argc,argv)) return false; if (debugLevel) cout << "# program:" << argv0 << endl << "# debugLevel: " << debugLevel << endl << "# verboseLevel: " << verboseLevel << endl; if (outputOpt.getCount()) { const string fn=outputOpt.getValue()[0]; output.open(fn.c_str(), ios::out); if (debugLevel) cout << "# Sending output to" << fn << endl; } else { if (debugLevel) cout << "# Sending output to stdout" << endl; output.copyfmt(cout); output.clear(cout.rdstate()); output.basic_ios<char>::rdbuf(cout.rdbuf()); } if (inputOpt.getCount()) { const string fn = inputOpt.getValue()[0]; input.open(fn.c_str(), ios::in); if (debugLevel) cout << "# Reading ords from" << fn << endl; } else { if (debugLevel) cout << "# Reading ords from stdin" << endl; input.copyfmt(cin); input.clear(cin.rdstate()); input.basic_ios<char>::rdbuf(cin.rdbuf()); } if (timeFormatOpt.getCount()) timeFormat = timeFormatOpt.getValue()[0]; return true; } void OrdApp::write(ofstream& s, const ORDEpoch& ordEpoch) throw() { if (!headerWritten) { s << "# Time Type PRN Elev ORD(m) wonky" << endl; headerWritten=true; } s.setf(ios::fixed, ios::floatfield); s << setfill(' ') << right; string time = ordEpoch.time.printf(timeFormat); ORDEpoch::ORDMap::const_iterator pi; for (pi = ordEpoch.ords.begin(); pi != ordEpoch.ords.end(); pi++) { const SatID& svid = pi->first; const ObsRngDev& ord = pi->second; int type = 0; s << time << " " << setw(4) << type << " " << setw(3) << svid.id << " " << setprecision(1) << setw(5) << ord.getElevation() << " " << setprecision(5) << setw(14) << ord.getORD() << " " << hex << setw(5) << ord.wonky << dec << endl; } if (ordEpoch.clockResidual.is_valid()) { int type = 1; s << time << " " << setw(4) << type << " " << setprecision(5) << setw(24) << ordEpoch.clockResidual << endl; } if (ordEpoch.clockOffset.is_valid()) { int type = 50; if (ordEpoch.wonky) type = 70; s << time << " " << setw(4) << type << " " << setprecision(5) << setw(24) << ordEpoch.clockOffset << endl; } } ORDEpoch OrdApp::read(std::ifstream& s) throw() { ORDEpoch ordEpoch; ordEpoch.time = DayTime(DayTime::BEGINNING_OF_TIME); using namespace StringUtils; while (s) { try { if (readBuffer.size() == 0) { getline(s, readBuffer); strip(readBuffer); } if (readBuffer.size() < 24 || readBuffer[0] == '#') { readBuffer.erase(0, string::npos); continue; } DayTime time; time.setToString(readBuffer.substr(0,19), timeFormat); // This means that we have a complete epoch. Note that the most // recently read line is left in readBuffer if (ordEpoch.time != time && ordEpoch.ords.size() > 0) break; ordEpoch.time = time; istringstream iss(readBuffer.substr(20, string::npos)); int type; iss >> type; if (type == 0) { if (readBuffer.size() < 46) { cout << "# Line to short" << endl; continue; } ObsRngDev ord; ord.obstime = time; int prn; double elev, res; unsigned wonky; iss >> prn >> elev >> res >> hex >> wonky >> dec; SatID svid(prn, SatID::systemGPS); ord.svid = svid; ord.elevation = elev; ord.ord = res; ord.wonky = wonky; ordEpoch.ords[svid] = ord; } else if (type == 1) { double c; iss >> c; ordEpoch.clockResidual = c; } else if (type == 50 || type == 70) { double c; iss >> c; ordEpoch.clockOffset = c; if (type == 70) ordEpoch.wonky = true; } readBuffer.erase(0, string::npos); } catch (Exception& e) { cout << "# Error reading ord file " << e << endl; } } return ordEpoch; } <commit_msg>Lines that begin with a '#' are echoed through in the read function, with the exception of the Time/Type/PRN/Elev header line. <commit_after>#pragma ident "$Id$" //============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // any later version. // // The GPSTk 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 GPSTk; if not, write to the Free Software Foundation, // Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Copyright 2004, The University of Texas at Austin // //============================================================================ //============================================================================ // //This software developed by Applied Research Laboratories at the University of //Texas at Austin, under contract to an agency or agencies within the U.S. //Department of Defense. The U.S. Government retains all rights to use, //duplicate, distribute, disclose, or release this software. // //Pursuant to DoD Directive 523024 // // DISTRIBUTION STATEMENT A: This software has been approved for public // release, distribution is unlimited. // //============================================================================= #include <iostream> #include "OrdApp.hpp" using namespace std; using namespace gpstk; const string OrdApp::defaultTimeFormat("%4Y %3j %02H:%02M:%04.1f"); //----------------------------------------------------------------------------- // The constructor basically just sets up all the command line options //----------------------------------------------------------------------------- OrdApp::OrdApp( const string& applName, const string& appDesc) throw() : BasicFramework(applName, appDesc), timeFormat(defaultTimeFormat), headerWritten(false), inputOpt('i', "input", "Where to get the data to analyze. The default is stdin."), outputOpt('r', "output", "Where to send the output. The default is stdout."), timeFormatOpt('t', "time-format", "Daytime format specifier used for " "times in the output. The default is \"" + defaultTimeFormat + "\".") {} //----------------------------------------------------------------------------- // Here the command line options parsed and used to configure the program //----------------------------------------------------------------------------- bool OrdApp::initialize(int argc, char *argv[]) throw() { if (!BasicFramework::initialize(argc,argv)) return false; if (debugLevel) cout << "# program:" << argv0 << endl << "# debugLevel: " << debugLevel << endl << "# verboseLevel: " << verboseLevel << endl; if (outputOpt.getCount()) { const string fn=outputOpt.getValue()[0]; output.open(fn.c_str(), ios::out); if (debugLevel) cout << "# Sending output to" << fn << endl; } else { if (debugLevel) cout << "# Sending output to stdout" << endl; output.copyfmt(cout); output.clear(cout.rdstate()); output.basic_ios<char>::rdbuf(cout.rdbuf()); } if (inputOpt.getCount()) { const string fn = inputOpt.getValue()[0]; input.open(fn.c_str(), ios::in); if (debugLevel) cout << "# Reading ords from" << fn << endl; } else { if (debugLevel) cout << "# Reading ords from stdin" << endl; input.copyfmt(cin); input.clear(cin.rdstate()); input.basic_ios<char>::rdbuf(cin.rdbuf()); } if (timeFormatOpt.getCount()) timeFormat = timeFormatOpt.getValue()[0]; return true; } void OrdApp::write(ofstream& s, const ORDEpoch& ordEpoch) throw() { if (!headerWritten) { s << "# Time Type PRN Elev ORD(m) wonky" << endl; headerWritten=true; } s.setf(ios::fixed, ios::floatfield); s << setfill(' ') << right; string time = ordEpoch.time.printf(timeFormat); ORDEpoch::ORDMap::const_iterator pi; for (pi = ordEpoch.ords.begin(); pi != ordEpoch.ords.end(); pi++) { const SatID& svid = pi->first; const ObsRngDev& ord = pi->second; int type = 0; s << time << " " << setw(4) << type << " " << setw(3) << svid.id << " " << setprecision(1) << setw(5) << ord.getElevation() << " " << setprecision(5) << setw(14) << ord.getORD() << " " << hex << setw(5) << ord.wonky << dec << endl; } if (ordEpoch.clockResidual.is_valid()) { int type = 1; s << time << " " << setw(4) << type << " " << setprecision(5) << setw(24) << ordEpoch.clockResidual << endl; } if (ordEpoch.clockOffset.is_valid()) { int type = 50; if (ordEpoch.wonky) type = 70; s << time << " " << setw(4) << type << " " << setprecision(5) << setw(24) << ordEpoch.clockOffset << endl; } } ORDEpoch OrdApp::read(std::ifstream& s) throw() { ORDEpoch ordEpoch; ordEpoch.time = DayTime(DayTime::BEGINNING_OF_TIME); using namespace StringUtils; while (s) { try { if (readBuffer.size() == 0) { getline(s, readBuffer); strip(readBuffer); } if ((readBuffer.size() < 24) || (readBuffer=="# Time Type PRN Elev ORD(m) wonky")) { readBuffer.erase(0, string::npos); continue; } else if (readBuffer[0] == '#') { output << readBuffer << endl; readBuffer.erase(0, string::npos); continue; } DayTime time; time.setToString(readBuffer.substr(0,19), timeFormat); // This means that we have a complete epoch. Note that the most // recently read line is left in readBuffer if (ordEpoch.time != time && ordEpoch.ords.size() > 0) break; ordEpoch.time = time; istringstream iss(readBuffer.substr(20, string::npos)); int type; iss >> type; if (type == 0) { if (readBuffer.size() < 46) { cout << "# Line too short" << endl; continue; } ObsRngDev ord; ord.obstime = time; int prn; double elev, res; unsigned wonky; iss >> prn >> elev >> res >> hex >> wonky >> dec; SatID svid(prn, SatID::systemGPS); ord.svid = svid; ord.elevation = elev; ord.ord = res; ord.wonky = wonky; ordEpoch.ords[svid] = ord; } else if (type == 1) { double c; iss >> c; ordEpoch.clockResidual = c; } else if (type == 50 || type == 70) { double c; iss >> c; ordEpoch.clockOffset = c; if (type == 70) ordEpoch.wonky = true; } readBuffer.erase(0, string::npos); } catch (Exception& e) { cout << "# Error reading ord file " << e << endl; } } return ordEpoch; } <|endoftext|>
<commit_before>f072ac1e-2e4e-11e5-9284-b827eb9e62be<commit_msg>f077aa52-2e4e-11e5-9284-b827eb9e62be<commit_after>f077aa52-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>d5082144-2e4d-11e5-9284-b827eb9e62be<commit_msg>d50d153c-2e4d-11e5-9284-b827eb9e62be<commit_after>d50d153c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>e7ea6384-2e4e-11e5-9284-b827eb9e62be<commit_msg>e7ef971e-2e4e-11e5-9284-b827eb9e62be<commit_after>e7ef971e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>09ea4104-2e4d-11e5-9284-b827eb9e62be<commit_msg>09ef5a36-2e4d-11e5-9284-b827eb9e62be<commit_after>09ef5a36-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>4a893e44-2e4e-11e5-9284-b827eb9e62be<commit_msg>4a8e3502-2e4e-11e5-9284-b827eb9e62be<commit_after>4a8e3502-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>87da57f6-2e4e-11e5-9284-b827eb9e62be<commit_msg>87df65e8-2e4e-11e5-9284-b827eb9e62be<commit_after>87df65e8-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>6e586afc-2e4e-11e5-9284-b827eb9e62be<commit_msg>6e5d7010-2e4e-11e5-9284-b827eb9e62be<commit_after>6e5d7010-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>3f74cd74-2e4f-11e5-9284-b827eb9e62be<commit_msg>3f79df08-2e4f-11e5-9284-b827eb9e62be<commit_after>3f79df08-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>301fb796-2e4d-11e5-9284-b827eb9e62be<commit_msg>3024a99a-2e4d-11e5-9284-b827eb9e62be<commit_after>3024a99a-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>3197d8c4-2e4d-11e5-9284-b827eb9e62be<commit_msg>319ccdca-2e4d-11e5-9284-b827eb9e62be<commit_after>319ccdca-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>8fae75ee-2e4d-11e5-9284-b827eb9e62be<commit_msg>8fb37652-2e4d-11e5-9284-b827eb9e62be<commit_after>8fb37652-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>60552030-2e4e-11e5-9284-b827eb9e62be<commit_msg>605a3322-2e4e-11e5-9284-b827eb9e62be<commit_after>605a3322-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>9d88bdfe-2e4e-11e5-9284-b827eb9e62be<commit_msg>9dab6386-2e4e-11e5-9284-b827eb9e62be<commit_after>9dab6386-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>cec4293a-2e4e-11e5-9284-b827eb9e62be<commit_msg>cee26558-2e4e-11e5-9284-b827eb9e62be<commit_after>cee26558-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>1eadbc28-2e4e-11e5-9284-b827eb9e62be<commit_msg>1eb2cbf0-2e4e-11e5-9284-b827eb9e62be<commit_after>1eb2cbf0-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>d5915960-2e4c-11e5-9284-b827eb9e62be<commit_msg>d5968ebc-2e4c-11e5-9284-b827eb9e62be<commit_after>d5968ebc-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>9180e6da-2e4e-11e5-9284-b827eb9e62be<commit_msg>919454a4-2e4e-11e5-9284-b827eb9e62be<commit_after>919454a4-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>8b2fe4a8-2e4d-11e5-9284-b827eb9e62be<commit_msg>8b34e1ce-2e4d-11e5-9284-b827eb9e62be<commit_after>8b34e1ce-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>c6b77b6c-2e4d-11e5-9284-b827eb9e62be<commit_msg>c6bd5d3e-2e4d-11e5-9284-b827eb9e62be<commit_after>c6bd5d3e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>b90a9360-2e4c-11e5-9284-b827eb9e62be<commit_msg>b90fbf34-2e4c-11e5-9284-b827eb9e62be<commit_after>b90fbf34-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>6baae7bc-2e4e-11e5-9284-b827eb9e62be<commit_msg>6bafe0aa-2e4e-11e5-9284-b827eb9e62be<commit_after>6bafe0aa-2e4e-11e5-9284-b827eb9e62be<|endoftext|>