commit
stringlengths
40
40
old_file
stringlengths
2
205
new_file
stringlengths
2
205
old_contents
stringlengths
0
32.9k
new_contents
stringlengths
1
38.9k
subject
stringlengths
3
9.4k
message
stringlengths
6
9.84k
lang
stringlengths
3
13
license
stringclasses
13 values
repos
stringlengths
6
115k
4a775c326b1a6a7fa46b4c29326754b5ef4f9bad
backend/src/llvm/llvm_unroll.cpp
backend/src/llvm/llvm_unroll.cpp
/* * Copyright © 2012 Intel Corporation * * 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 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, see <http://www.gnu.org/licenses/>. */ #include "llvm/Config/llvm-config.h" #if LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR >= 5 #include <set> #if LLVM_VERSION_MINOR <= 2 #include "llvm/Function.h" #include "llvm/InstrTypes.h" #include "llvm/Instructions.h" #include "llvm/IntrinsicInst.h" #include "llvm/Module.h" #else #include "llvm/IR/Function.h" #include "llvm/IR/InstrTypes.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/Module.h" #endif /* LLVM_VERSION_MINOR <= 2 */ #include "llvm/Pass.h" #if LLVM_VERSION_MINOR <= 1 #include "llvm/Support/IRBuilder.h" #elif LLVM_VERSION_MINOR == 2 #include "llvm/IRBuilder.h" #else #include "llvm/IR/IRBuilder.h" #endif /* LLVM_VERSION_MINOR <= 1 */ #include "llvm/Support/raw_ostream.h" #include "llvm/PassManager.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Analysis/ScalarEvolution.h" #include "llvm/Analysis/LoopPass.h" #include "llvm/Analysis/TargetTransformInfo.h" #include "llvm/IR/Dominators.h" #include "llvm/llvm_gen_backend.hpp" #include "sys/map.hpp" using namespace llvm; namespace gbe { class CustomLoopUnroll : public LoopPass { public: static char ID; CustomLoopUnroll() : LoopPass(ID) {} void getAnalysisUsage(AnalysisUsage &AU) const { AU.addRequired<LoopInfo>(); AU.addPreserved<LoopInfo>(); AU.addRequiredID(LoopSimplifyID); AU.addPreservedID(LoopSimplifyID); AU.addRequiredID(LCSSAID); AU.addPreservedID(LCSSAID); AU.addRequired<ScalarEvolution>(); AU.addPreserved<ScalarEvolution>(); // FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info. // If loop unroll does not preserve dom info then LCSSA pass on next // loop will receive invalid dom info. // For now, recreate dom info, if loop is unrolled. AU.addPreserved<DominatorTreeWrapperPass>(); } // Returns the value associated with the given metadata node name (for // example, "llvm.loop.unroll.count"). If no such named metadata node // exists, then nullptr is returned. static const ConstantInt *GetUnrollMetadataValue(const Loop *L, StringRef Name) { MDNode *LoopID = L->getLoopID(); if (!LoopID) return nullptr; // First operand should refer to the loop id itself. assert(LoopID->getNumOperands() > 0 && "requires at least one operand"); assert(LoopID->getOperand(0) == LoopID && "invalid loop id"); for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) { const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i)); if (!MD) continue; const MDString *S = dyn_cast<MDString>(MD->getOperand(0)); if (!S) continue; if (Name.equals(S->getString())) { assert(MD->getNumOperands() == 2 && "Unroll hint metadata should have two operands."); return cast<ConstantInt>(MD->getOperand(1)); } } return nullptr; } void setUnrollID(Loop *L, bool enable) { if (!enable && disabledLoops.find(L) != disabledLoops.end()) return; LLVMContext &Context = L->getHeader()->getContext(); SmallVector<Value *, 2> forceUnroll; forceUnroll.push_back(MDString::get(Context, "llvm.loop.unroll.enable")); forceUnroll.push_back(ConstantInt::get(Type::getInt1Ty(Context), enable)); MDNode *forceUnrollNode = MDNode::get(Context, forceUnroll); SmallVector<Value *, 4> Vals; Vals.push_back(NULL); Vals.push_back(forceUnrollNode); MDNode *NewLoopID = MDNode::get(Context, Vals); // Set operand 0 to refer to the loop id itself. NewLoopID->replaceOperandWith(0, NewLoopID); L->setLoopID(NewLoopID); if (!enable) disabledLoops.insert(L); } static bool hasPrivateLoadStore(Loop *L) { const std::vector<Loop*> subLoops = L->getSubLoops(); std::set<BasicBlock*> subBlocks, blocks; for(auto l : subLoops) for(auto bb : l->getBlocks()) subBlocks.insert(bb); for(auto bb : L->getBlocks()) if (subBlocks.find(bb) == subBlocks.end()) blocks.insert(bb); for(auto bb : blocks) { for (BasicBlock::iterator inst = bb->begin(), instE = bb->end(); inst != instE; ++inst) { unsigned addrSpace = 0; if (isa<LoadInst>(*inst)) { LoadInst *ld = cast<LoadInst>(&*inst); addrSpace = ld->getPointerAddressSpace(); } else if (isa<StoreInst>(*inst)) { StoreInst *st = cast<StoreInst>(&*inst); addrSpace = st->getPointerAddressSpace(); } if (addrSpace == 0) return true; } } return false; } // If one loop has very large self trip count // we don't want to unroll it. // self trip count means trip count divide by the parent's trip count. for example // for (int i = 0; i < 16; i++) { // for (int j = 0; j < 4; j++) { // for (int k = 0; k < 2; k++) { // ... // } // ... // } // The inner loops j and k could be unrolled, but the loop i will not be unrolled. // The return value true means the L could be unrolled, otherwise, it could not // be unrolled. bool handleParentLoops(Loop *L, LPPassManager &LPM) { Loop *currL = L; ScalarEvolution *SE = &getAnalysis<ScalarEvolution>(); BasicBlock *latchBlock = currL->getLoopLatch(); unsigned currTripCount = 0; bool shouldUnroll = true; if (latchBlock) currTripCount = SE->getSmallConstantTripCount(L, latchBlock); while(currL) { Loop *parentL = currL->getParentLoop(); unsigned parentTripCount = 0; if (parentL) { BasicBlock *parentLatchBlock = parentL->getLoopLatch(); if (parentLatchBlock) parentTripCount = SE->getSmallConstantTripCount(parentL, parentLatchBlock); } if ((parentTripCount != 0 && currTripCount / parentTripCount > 16) || (currTripCount > 32)) { if (currL == L) shouldUnroll = false; setUnrollID(currL, false); if (currL != L) LPM.deleteLoopFromQueue(currL); } currL = parentL; currTripCount = parentTripCount; } return shouldUnroll; } // Analyze the outermost BBs of this loop, if there are // some private load or store, we change it's loop meta data // to indicate more aggresive unrolling on it. virtual bool runOnLoop(Loop *L, LPPassManager &LPM) { const ConstantInt *Enable = GetUnrollMetadataValue(L, "llvm.loop.unroll.enable"); if (Enable) return false; const ConstantInt *Count = GetUnrollMetadataValue(L, "llvm.loop.unroll.count"); if (Count) return false; if (!handleParentLoops(L, LPM)) return false; if (!hasPrivateLoadStore(L)) return false; setUnrollID(L, true); return true; } virtual const char *getPassName() const { return "SPIR backend: custom loop unrolling pass"; } private: std::set<Loop *> disabledLoops; }; char CustomLoopUnroll::ID = 0; LoopPass *createCustomLoopUnrollPass() { return new CustomLoopUnroll(); } } // end namespace #endif
/* * Copyright © 2012 Intel Corporation * * 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 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, see <http://www.gnu.org/licenses/>. */ #include "llvm/Config/llvm-config.h" #if LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR >= 5 #include <set> #if LLVM_VERSION_MINOR <= 2 #include "llvm/Function.h" #include "llvm/InstrTypes.h" #include "llvm/Instructions.h" #include "llvm/IntrinsicInst.h" #include "llvm/Module.h" #else #include "llvm/IR/Function.h" #include "llvm/IR/InstrTypes.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/Module.h" #endif /* LLVM_VERSION_MINOR <= 2 */ #include "llvm/Pass.h" #if LLVM_VERSION_MINOR <= 1 #include "llvm/Support/IRBuilder.h" #elif LLVM_VERSION_MINOR == 2 #include "llvm/IRBuilder.h" #else #include "llvm/IR/IRBuilder.h" #endif /* LLVM_VERSION_MINOR <= 1 */ #include "llvm/Support/raw_ostream.h" #include "llvm/PassManager.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Analysis/ScalarEvolution.h" #include "llvm/Analysis/LoopPass.h" #include "llvm/Analysis/TargetTransformInfo.h" #include "llvm/IR/Dominators.h" #include "llvm/llvm_gen_backend.hpp" #include "sys/map.hpp" using namespace llvm; namespace gbe { class CustomLoopUnroll : public LoopPass { public: static char ID; CustomLoopUnroll() : LoopPass(ID) {} void getAnalysisUsage(AnalysisUsage &AU) const { AU.addRequired<LoopInfo>(); AU.addPreserved<LoopInfo>(); AU.addRequiredID(LoopSimplifyID); AU.addPreservedID(LoopSimplifyID); AU.addRequiredID(LCSSAID); AU.addPreservedID(LCSSAID); AU.addRequired<ScalarEvolution>(); AU.addPreserved<ScalarEvolution>(); // FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info. // If loop unroll does not preserve dom info then LCSSA pass on next // loop will receive invalid dom info. // For now, recreate dom info, if loop is unrolled. AU.addPreserved<DominatorTreeWrapperPass>(); } // Returns the value associated with the given metadata node name (for // example, "llvm.loop.unroll.count"). If no such named metadata node // exists, then nullptr is returned. static const ConstantInt *GetUnrollMetadataValue(const Loop *L, StringRef Name) { MDNode *LoopID = L->getLoopID(); if (!LoopID) return nullptr; // First operand should refer to the loop id itself. assert(LoopID->getNumOperands() > 0 && "requires at least one operand"); assert(LoopID->getOperand(0) == LoopID && "invalid loop id"); for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) { const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i)); if (!MD) continue; const MDString *S = dyn_cast<MDString>(MD->getOperand(0)); if (!S) continue; if (Name.equals(S->getString())) { assert(MD->getNumOperands() == 2 && "Unroll hint metadata should have two operands."); return cast<ConstantInt>(MD->getOperand(1)); } } return nullptr; } void setUnrollID(Loop *L, bool enable) { if (!enable && disabledLoops.find(L) != disabledLoops.end()) return; LLVMContext &Context = L->getHeader()->getContext(); SmallVector<Value *, 2> forceUnroll; forceUnroll.push_back(MDString::get(Context, "llvm.loop.unroll.enable")); forceUnroll.push_back(ConstantInt::get(Type::getInt1Ty(Context), enable)); MDNode *forceUnrollNode = MDNode::get(Context, forceUnroll); SmallVector<Value *, 4> Vals; Vals.push_back(NULL); Vals.push_back(forceUnrollNode); MDNode *NewLoopID = MDNode::get(Context, Vals); // Set operand 0 to refer to the loop id itself. NewLoopID->replaceOperandWith(0, NewLoopID); L->setLoopID(NewLoopID); if (!enable) disabledLoops.insert(L); } static bool hasPrivateLoadStore(Loop *L) { const std::vector<Loop*> subLoops = L->getSubLoops(); std::set<BasicBlock*> subBlocks, blocks; for(auto l : subLoops) for(auto bb : l->getBlocks()) subBlocks.insert(bb); for(auto bb : L->getBlocks()) if (subBlocks.find(bb) == subBlocks.end()) blocks.insert(bb); for(auto bb : blocks) { for (BasicBlock::iterator inst = bb->begin(), instE = bb->end(); inst != instE; ++inst) { unsigned addrSpace = -1; if (isa<LoadInst>(*inst)) { LoadInst *ld = cast<LoadInst>(&*inst); addrSpace = ld->getPointerAddressSpace(); } else if (isa<StoreInst>(*inst)) { StoreInst *st = cast<StoreInst>(&*inst); addrSpace = st->getPointerAddressSpace(); } if (addrSpace == 0) return true; } } return false; } // If one loop has very large self trip count // we don't want to unroll it. // self trip count means trip count divide by the parent's trip count. for example // for (int i = 0; i < 16; i++) { // for (int j = 0; j < 4; j++) { // for (int k = 0; k < 2; k++) { // ... // } // ... // } // The inner loops j and k could be unrolled, but the loop i will not be unrolled. // The return value true means the L could be unrolled, otherwise, it could not // be unrolled. bool handleParentLoops(Loop *L, LPPassManager &LPM) { Loop *currL = L; ScalarEvolution *SE = &getAnalysis<ScalarEvolution>(); BasicBlock *latchBlock = currL->getLoopLatch(); unsigned currTripCount = 0; bool shouldUnroll = true; if (latchBlock) currTripCount = SE->getSmallConstantTripCount(L, latchBlock); while(currL) { Loop *parentL = currL->getParentLoop(); unsigned parentTripCount = 0; if (parentL) { BasicBlock *parentLatchBlock = parentL->getLoopLatch(); if (parentLatchBlock) parentTripCount = SE->getSmallConstantTripCount(parentL, parentLatchBlock); } if ((parentTripCount != 0 && currTripCount / parentTripCount > 16) || (currTripCount > 32)) { if (currL == L) shouldUnroll = false; setUnrollID(currL, false); if (currL != L) LPM.deleteLoopFromQueue(currL); } currL = parentL; currTripCount = parentTripCount; } return shouldUnroll; } // Analyze the outermost BBs of this loop, if there are // some private load or store, we change it's loop meta data // to indicate more aggresive unrolling on it. virtual bool runOnLoop(Loop *L, LPPassManager &LPM) { const ConstantInt *Enable = GetUnrollMetadataValue(L, "llvm.loop.unroll.enable"); if (Enable) return false; const ConstantInt *Count = GetUnrollMetadataValue(L, "llvm.loop.unroll.count"); if (Count) return false; if (!handleParentLoops(L, LPM)) return false; if (!hasPrivateLoadStore(L)) return false; setUnrollID(L, true); return true; } virtual const char *getPassName() const { return "SPIR backend: custom loop unrolling pass"; } private: std::set<Loop *> disabledLoops; }; char CustomLoopUnroll::ID = 0; LoopPass *createCustomLoopUnrollPass() { return new CustomLoopUnroll(); } } // end namespace #endif
set default address space to -1 to avoid incorrect unroll hint.
GBE: set default address space to -1 to avoid incorrect unroll hint. Signed-off-by: Zhigang Gong <[email protected]> Tested-by: Meng Mengmeng <[email protected]>
C++
lgpl-2.1
freedesktop-unofficial-mirror/beignet,wdv4758h/beignet,freedesktop-unofficial-mirror/beignet,zhenyw/beignet,wdv4758h/beignet,zhenyw/beignet,zhenyw/beignet,wdv4758h/beignet,freedesktop-unofficial-mirror/beignet,wdv4758h/beignet,zhenyw/beignet,zhenyw/beignet,wdv4758h/beignet,freedesktop-unofficial-mirror/beignet
a010180e0bbf7cf53e525f51b34c3b2cac2deb81
ui/views/examples/content_client/examples_browser_main_parts.cc
ui/views/examples/content_client/examples_browser_main_parts.cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/examples/content_client/examples_browser_main_parts.h" #include "base/bind.h" #include "base/command_line.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "base/threading/thread.h" #include "base/threading/thread_restrictions.h" #include "content/public/common/content_switches.h" #include "content/shell/browser/shell_browser_context.h" #include "ui/views/examples/examples_window_with_content.h" #include "ui/views/focus/accelerator_handler.h" #include "ui/views/test/desktop_test_views_delegate.h" #include "url/gurl.h" #if defined(USE_AURA) #include "ui/aura/env.h" #include "ui/gfx/screen.h" #include "ui/views/widget/desktop_aura/desktop_screen.h" #include "ui/views/widget/native_widget_aura.h" #endif #if defined(OS_CHROMEOS) #include "ui/aura/root_window.h" #include "ui/aura/test/test_screen.h" #include "ui/shell/minimal_shell.h" #endif namespace views { namespace examples { ExamplesBrowserMainParts::ExamplesBrowserMainParts( const content::MainFunctionParams& parameters) { } ExamplesBrowserMainParts::~ExamplesBrowserMainParts() { } void ExamplesBrowserMainParts::PreMainMessageLoopRun() { browser_context_.reset(new content::ShellBrowserContext(false, NULL)); gfx::NativeView window_context = NULL; #if defined(OS_CHROMEOS) gfx::Screen::SetScreenInstance( gfx::SCREEN_TYPE_NATIVE, aura::TestScreen::Create()); // Set up basic pieces of views::corewm. minimal_shell_.reset(new shell::MinimalShell(gfx::Size(800, 600))); // Ensure the X window gets mapped. minimal_shell_->root_window()->ShowRootWindow(); // Ensure Aura knows where to open new windows. window_context = minimal_shell_->root_window(); #elif defined(USE_AURA) gfx::Screen::SetScreenInstance( gfx::SCREEN_TYPE_NATIVE, CreateDesktopScreen()); #endif views_delegate_.reset(new DesktopTestViewsDelegate); ShowExamplesWindowWithContent( QUIT_ON_CLOSE, browser_context_.get(), window_context); } void ExamplesBrowserMainParts::PostMainMessageLoopRun() { browser_context_.reset(); #if defined(OS_CHROMEOS) minimal_shell_.reset(); #endif views_delegate_.reset(); #if defined(USE_AURA) aura::Env::DeleteInstance(); #endif } bool ExamplesBrowserMainParts::MainMessageLoopRun(int* result_code) { // xxx: Hax here because this kills event handling. #if !defined(USE_AURA) AcceleratorHandler accelerator_handler; base::RunLoop run_loop(&accelerator_handler); #else base::RunLoop run_loop; #endif run_loop.Run(); return true; } } // namespace examples } // namespace views
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/examples/content_client/examples_browser_main_parts.h" #include "base/bind.h" #include "base/command_line.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "base/threading/thread.h" #include "base/threading/thread_restrictions.h" #include "content/public/common/content_switches.h" #include "content/shell/browser/shell_browser_context.h" #include "ui/views/examples/examples_window_with_content.h" #include "ui/views/focus/accelerator_handler.h" #include "ui/views/test/desktop_test_views_delegate.h" #include "url/gurl.h" #if defined(USE_AURA) #include "ui/aura/env.h" #include "ui/gfx/screen.h" #include "ui/views/widget/desktop_aura/desktop_screen.h" #include "ui/views/widget/native_widget_aura.h" #endif #if defined(OS_CHROMEOS) #include "ui/aura/root_window.h" #include "ui/aura/test/test_screen.h" #include "ui/shell/minimal_shell.h" #endif namespace views { namespace examples { ExamplesBrowserMainParts::ExamplesBrowserMainParts( const content::MainFunctionParams& parameters) { } ExamplesBrowserMainParts::~ExamplesBrowserMainParts() { } void ExamplesBrowserMainParts::PreMainMessageLoopRun() { browser_context_.reset(new content::ShellBrowserContext(false, NULL)); gfx::NativeView window_context = NULL; #if defined(OS_CHROMEOS) gfx::Screen::SetScreenInstance( gfx::SCREEN_TYPE_NATIVE, aura::TestScreen::Create()); // Set up basic pieces of views::corewm. minimal_shell_.reset(new shell::MinimalShell(gfx::Size(800, 600))); // Ensure the X window gets mapped. minimal_shell_->root_window()->ShowRootWindow(); // Ensure Aura knows where to open new windows. window_context = minimal_shell_->root_window(); #elif defined(USE_AURA) aura::Env::CreateInstance(); gfx::Screen::SetScreenInstance( gfx::SCREEN_TYPE_NATIVE, CreateDesktopScreen()); #endif views_delegate_.reset(new DesktopTestViewsDelegate); ShowExamplesWindowWithContent( QUIT_ON_CLOSE, browser_context_.get(), window_context); } void ExamplesBrowserMainParts::PostMainMessageLoopRun() { browser_context_.reset(); #if defined(OS_CHROMEOS) minimal_shell_.reset(); #endif views_delegate_.reset(); #if defined(USE_AURA) aura::Env::DeleteInstance(); #endif } bool ExamplesBrowserMainParts::MainMessageLoopRun(int* result_code) { // xxx: Hax here because this kills event handling. #if !defined(USE_AURA) AcceleratorHandler accelerator_handler; base::RunLoop run_loop(&accelerator_handler); #else base::RunLoop run_loop; #endif run_loop.Run(); return true; } } // namespace examples } // namespace views
Call aura::Env::CreateInstance in ExamplesBrowserMainParts::PreMainMessageLoopRun.
Call aura::Env::CreateInstance in ExamplesBrowserMainParts::PreMainMessageLoopRun. BUG=313848 TEST=views_examples_with_content_exe runs in Win Aura. [email protected] Review URL: https://codereview.chromium.org/49533005 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@232962 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
anirudhSK/chromium,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,littlstar/chromium.src,krieger-od/nwjs_chromium.src,anirudhSK/chromium,dushu1203/chromium.src,Chilledheart/chromium,M4sse/chromium.src,krieger-od/nwjs_chromium.src,bright-sparks/chromium-spacewalk,M4sse/chromium.src,dednal/chromium.src,jaruba/chromium.src,anirudhSK/chromium,patrickm/chromium.src,ltilve/chromium,jaruba/chromium.src,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,Just-D/chromium-1,fujunwei/chromium-crosswalk,markYoungH/chromium.src,patrickm/chromium.src,dednal/chromium.src,Pluto-tv/chromium-crosswalk,Chilledheart/chromium,ondra-novak/chromium.src,ChromiumWebApps/chromium,Just-D/chromium-1,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,M4sse/chromium.src,anirudhSK/chromium,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,jaruba/chromium.src,fujunwei/chromium-crosswalk,ondra-novak/chromium.src,dushu1203/chromium.src,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,jaruba/chromium.src,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,jaruba/chromium.src,PeterWangIntel/chromium-crosswalk,krieger-od/nwjs_chromium.src,Just-D/chromium-1,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,bright-sparks/chromium-spacewalk,Just-D/chromium-1,chuan9/chromium-crosswalk,Chilledheart/chromium,littlstar/chromium.src,dednal/chromium.src,ltilve/chromium,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,bright-sparks/chromium-spacewalk,crosswalk-project/chromium-crosswalk-efl,M4sse/chromium.src,dushu1203/chromium.src,fujunwei/chromium-crosswalk,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk-efl,dednal/chromium.src,ondra-novak/chromium.src,ondra-novak/chromium.src,Pluto-tv/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,markYoungH/chromium.src,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,crosswalk-project/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,ltilve/chromium,krieger-od/nwjs_chromium.src,littlstar/chromium.src,crosswalk-project/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,ltilve/chromium,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,markYoungH/chromium.src,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,TheTypoMaster/chromium-crosswalk,ChromiumWebApps/chromium,TheTypoMaster/chromium-crosswalk,ChromiumWebApps/chromium,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,ChromiumWebApps/chromium,dednal/chromium.src,ltilve/chromium,Jonekee/chromium.src,dednal/chromium.src,dednal/chromium.src,ondra-novak/chromium.src,chuan9/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,fujunwei/chromium-crosswalk,jaruba/chromium.src,ChromiumWebApps/chromium,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,crosswalk-project/chromium-crosswalk-efl,dushu1203/chromium.src,crosswalk-project/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,anirudhSK/chromium,chuan9/chromium-crosswalk,anirudhSK/chromium,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,M4sse/chromium.src,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,anirudhSK/chromium,TheTypoMaster/chromium-crosswalk,bright-sparks/chromium-spacewalk,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,jaruba/chromium.src,hgl888/chromium-crosswalk,ltilve/chromium,axinging/chromium-crosswalk,M4sse/chromium.src,ondra-novak/chromium.src,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,bright-sparks/chromium-spacewalk,fujunwei/chromium-crosswalk,chuan9/chromium-crosswalk,Chilledheart/chromium,dushu1203/chromium.src,jaruba/chromium.src,littlstar/chromium.src,ltilve/chromium,hgl888/chromium-crosswalk-efl,dushu1203/chromium.src,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,littlstar/chromium.src,Chilledheart/chromium,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,dednal/chromium.src,Just-D/chromium-1,patrickm/chromium.src,markYoungH/chromium.src,littlstar/chromium.src,markYoungH/chromium.src,jaruba/chromium.src,ondra-novak/chromium.src,patrickm/chromium.src,chuan9/chromium-crosswalk,ondra-novak/chromium.src,Jonekee/chromium.src,mohamed--abdel-maksoud/chromium.src,littlstar/chromium.src,Just-D/chromium-1,bright-sparks/chromium-spacewalk,Chilledheart/chromium,Jonekee/chromium.src,patrickm/chromium.src,ChromiumWebApps/chromium,M4sse/chromium.src,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,anirudhSK/chromium,patrickm/chromium.src,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,markYoungH/chromium.src,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,M4sse/chromium.src,Pluto-tv/chromium-crosswalk,ltilve/chromium,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,fujunwei/chromium-crosswalk,Fireblend/chromium-crosswalk,littlstar/chromium.src,crosswalk-project/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,dushu1203/chromium.src,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,Just-D/chromium-1,anirudhSK/chromium,bright-sparks/chromium-spacewalk,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,ltilve/chromium,markYoungH/chromium.src,patrickm/chromium.src,hgl888/chromium-crosswalk,Jonekee/chromium.src,jaruba/chromium.src,Jonekee/chromium.src,markYoungH/chromium.src,dednal/chromium.src,Fireblend/chromium-crosswalk,Jonekee/chromium.src,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,hgl888/chromium-crosswalk-efl,ChromiumWebApps/chromium,Jonekee/chromium.src,Jonekee/chromium.src,dednal/chromium.src,dushu1203/chromium.src,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,M4sse/chromium.src,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk,patrickm/chromium.src,Chilledheart/chromium,hgl888/chromium-crosswalk-efl,dushu1203/chromium.src,M4sse/chromium.src,jaruba/chromium.src,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,ondra-novak/chromium.src,M4sse/chromium.src,dushu1203/chromium.src,dushu1203/chromium.src,fujunwei/chromium-crosswalk,markYoungH/chromium.src,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk
649e69dd22bc9fdb9b85e504985aa4ff16aaf8a2
test/libcxx/utilities/utility/pairs/pairs.pair/default.pass.cpp
test/libcxx/utilities/utility/pairs/pairs.pair/default.pass.cpp
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++98, c++03 // <utility> // template <class T1, class T2> struct pair // constexpr pair(); #include <utility> #include <type_traits> #include "archetypes.hpp" int main() { using NonThrowingDefault = NonThrowingTypes::DefaultOnly; using ThrowingDefault = NonTrivialTypes::DefaultOnly; static_assert(!std::is_nothrow_default_constructible<std::pair<ThrowingDefault, ThrowingDefault>>::value, ""); static_assert(!std::is_nothrow_default_constructible<std::pair<NonThrowingDefault, ThrowingDefault>>::value, ""); static_assert(!std::is_nothrow_default_constructible<std::pair<ThrowingDefault, NonThrowingDefault>>::value, ""); static_assert( std::is_nothrow_default_constructible<std::pair<NonThrowingDefault, NonThrowingDefault>>::value, ""); }
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++98, c++03 // <utility> // template <class T1, class T2> struct pair // constexpr pair(); #include <utility> #include <type_traits> struct ThrowingDefault { ThrowingDefault() { } }; struct NonThrowingDefault { NonThrowingDefault() noexcept { } }; int main() { static_assert(!std::is_nothrow_default_constructible<std::pair<ThrowingDefault, ThrowingDefault>>::value, ""); static_assert(!std::is_nothrow_default_constructible<std::pair<NonThrowingDefault, ThrowingDefault>>::value, ""); static_assert(!std::is_nothrow_default_constructible<std::pair<ThrowingDefault, NonThrowingDefault>>::value, ""); static_assert( std::is_nothrow_default_constructible<std::pair<NonThrowingDefault, NonThrowingDefault>>::value, ""); }
Fix test failure on GCC 4.9
[libcxx] Fix test failure on GCC 4.9 GCC 4.9 seems to think that a constexpr default constructor implies the constructor to be noexcept. git-svn-id: 756ef344af921d95d562d9e9f9389127a89a6314@348850 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/libcxx,llvm-mirror/libcxx,llvm-mirror/libcxx,llvm-mirror/libcxx,llvm-mirror/libcxx
ca17bba411240f89128c3b44eab7168f63d22e66
Modules/Wrappers/ApplicationEngine/src/otbWrapperApplicationRegistry.cxx
Modules/Wrappers/ApplicationEngine/src/otbWrapperApplicationRegistry.cxx
/* * Copyright (C) 2005-2019 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. */ #include "otbWrapperApplicationRegistry.h" #include "otbWrapperApplicationFactoryBase.h" #include "otbMacro.h" #include "itksys/SystemTools.hxx" #include "itkDynamicLoader.h" #include "itkDirectory.h" #include "itkMutexLock.h" #include "itkMutexLockHolder.h" #include <iterator> namespace otb { namespace Wrapper { // Constant : environment variable for application path static const char OTB_APPLICATION_VAR[] = "OTB_APPLICATION_PATH"; class ApplicationPrivateRegistry { public: typedef std::pair<Application*, void* > AppHandlePairType; typedef std::list<AppHandlePairType> AppHandleContainerType; /** Add a pair (application, library handle) in the private registry */ bool AddPair(Application *app, void *handle) { AppHandlePairType pair; if (app && handle) { // mutex lock to ensure thread safety itk::MutexLockHolder<itk::SimpleMutexLock> mutexHolder(m_Mutex); pair.first = app; pair.second = handle; m_Container.push_back(pair); return true; } return false; } /** When an application is deleted, unregister its pointer from private registry */ void UnregisterApp(const Application *app) { if (app) { // mutex lock to ensure thread safety itk::MutexLockHolder<itk::SimpleMutexLock> mutexHolder(m_Mutex); AppHandleContainerType::iterator it = m_Container.begin(); while (it != m_Container.end()) { if ((*it).first == app) { (*it).first = nullptr; } ++it; } } } /** Release the library handles from applications already deleted */ void ReleaseUnusedHandle() { itk::MutexLockHolder<itk::SimpleMutexLock> mutexHolder(m_Mutex); AppHandleContainerType::iterator it; for (it = m_Container.begin() ; it != m_Container.end() ; ++it) { if ((*it).first == nullptr) { itk::DynamicLoader::CloseLibrary( static_cast<itk::LibHandle>((*it).second)); (*it).second = nullptr; } } m_Container.remove(AppHandlePairType((Application*) nullptr, (void*) nullptr)); } /** close all handles at program exit */ ~ApplicationPrivateRegistry() { // unregister all ITK factories, because some of them could have been // registered by the shared libs we are about to close. itk::ObjectFactoryBase::UnRegisterAllFactories(); // Close all opened shared libs AppHandleContainerType::iterator it; for (it = m_Container.begin() ; it != m_Container.end() ; ++it) { itk::DynamicLoader::CloseLibrary( static_cast<itk::LibHandle>((*it).second)); } m_Container.clear(); } private: AppHandleContainerType m_Container; itk::SimpleMutexLock m_Mutex; }; // static finalizer to close opened libraries static ApplicationPrivateRegistry m_ApplicationPrivateRegistryGlobal; // Define callbacks to unregister applications in ApplicationPrivateRegistry void DeleteAppCallback(itk::Object *obj,const itk::EventObject &, void *) { Application *appPtr = dynamic_cast<Application*>(obj); m_ApplicationPrivateRegistryGlobal.UnregisterApp(appPtr); } void DeleteAppConstCallback(const itk::Object *obj,const itk::EventObject &, void *) { const Application *appPtr = dynamic_cast<const Application*>(obj); m_ApplicationPrivateRegistryGlobal.UnregisterApp(appPtr); } ApplicationRegistry::ApplicationRegistry() { } ApplicationRegistry::~ApplicationRegistry() { } void ApplicationRegistry::SetApplicationPath(std::string newpath) { std::ostringstream putEnvPath; putEnvPath << OTB_APPLICATION_VAR << "=" << newpath; // do NOT use putenv() directly, since the string memory must be managed carefully itksys::SystemTools::PutEnv(putEnvPath.str()); } void ApplicationRegistry::AddApplicationPath(std::string newpath) { std::ostringstream putEnvPath; putEnvPath << OTB_APPLICATION_VAR <<"="; // Can be NULL if the env var is not set const char* currentEnv = itksys::SystemTools::GetEnv(OTB_APPLICATION_VAR); #if defined(WIN32) const char pathSeparator = ';'; #else const char pathSeparator = ':'; #endif putEnvPath << newpath << pathSeparator; if (currentEnv) { putEnvPath << currentEnv; } // do NOT use putenv() directly, since the string memory must be managed carefully itksys::SystemTools::PutEnv(putEnvPath.str()); } std::string ApplicationRegistry::GetApplicationPath() { std::string ret; // Can be NULL if the env var is not set const char* currentEnv = itksys::SystemTools::GetEnv(OTB_APPLICATION_VAR); if (currentEnv) { ret = std::string(currentEnv); } return ret; } Application::Pointer ApplicationRegistry::CreateApplication(const std::string& name, bool useFactory) { ApplicationPointer appli; // Fast search : uses OTB_APPLICATION_PATH appli = ApplicationRegistry::CreateApplicationFaster(name); if (appli.IsNotNull()) { return appli; } // Classic search : uses factories registered by ITK ( see ITK_AUTOLOAD_PATH ) if (useFactory) { LightObject::Pointer possibleApp = itk::ObjectFactoryBase::CreateInstance(name.c_str()); if (possibleApp.IsNotNull()) { // Downcast Application* app = dynamic_cast<Application*> (possibleApp.GetPointer()); if (app) { appli = app; appli->Init(); } } } return appli; } typedef itk::ObjectFactoryBase * ( *ITK_LOAD_FUNCTION )(); Application::Pointer ApplicationRegistry::CreateApplicationFaster(const std::string& name) { ApplicationPointer appli = nullptr; std::string appExtension = itksys::DynamicLoader::LibExtension(); #ifdef __APPLE__ appExtension = ".dylib"; #endif std::ostringstream appLibName; appLibName << "otbapp_" << name << appExtension; #if defined(WIN32) const char pathSeparator = ';'; #else const char pathSeparator = ':'; #endif #ifdef _WIN32 const char sep = '\\'; #else const char sep = '/'; #endif std::string otbAppPath = GetApplicationPath(); std::vector<itksys::String> pathList; if (!otbAppPath.empty()) { pathList = itksys::SystemTools::SplitString(otbAppPath,pathSeparator,false); } for (unsigned int i=0 ; i<pathList.size() ; ++i) { std::string possiblePath = pathList[i]; if ( !possiblePath.empty() && possiblePath[possiblePath.size() - 1] != sep ) { possiblePath += sep; } possiblePath += appLibName.str(); appli = LoadApplicationFromPath(possiblePath,name); if (appli.IsNotNull()) { break; } } return appli; } std::vector<std::string> ApplicationRegistry::GetAvailableApplications(bool useFactory) { ApplicationPointer appli; std::set<std::string> appSet; std::string appPrefix("otbapp_"); std::string appExtension = itksys::DynamicLoader::LibExtension(); #ifdef __APPLE__ appExtension = ".dylib"; #endif #if defined(WIN32) const char pathSeparator = ';'; #else const char pathSeparator = ':'; #endif #ifdef _WIN32 const char sep = '\\'; #else const char sep = '/'; #endif std::string otbAppPath = GetApplicationPath(); std::vector<itksys::String> pathList; if (!otbAppPath.empty()) { pathList = itksys::SystemTools::SplitString(otbAppPath,pathSeparator,false); } for (unsigned int k=0 ; k<pathList.size() ; ++k) { itk::Directory::Pointer dir = itk::Directory::New(); if (!dir->Load(pathList[k].c_str())) { continue; } for (unsigned int i = 0; i < dir->GetNumberOfFiles(); i++) { const char *filename = dir->GetFile(i); std::string sfilename(filename); std::string::size_type extPos = sfilename.rfind(appExtension); std::string::size_type prefixPos = sfilename.find(appPrefix); // Check if current file is a shared lib with the right pattern if (extPos + appExtension.size() == sfilename.size() && prefixPos == 0) { std::string name = sfilename.substr(appPrefix.size(),extPos-appPrefix.size()); std::string fullpath = pathList[k]; if (!fullpath.empty() && fullpath[fullpath.size() - 1] != sep) { fullpath.push_back(sep); } fullpath.append(sfilename); appli = LoadApplicationFromPath(fullpath,name); if (appli.IsNotNull()) { appSet.insert(name); } appli = nullptr; } } } if (useFactory) { std::list<LightObject::Pointer> allobjects = itk::ObjectFactoryBase::CreateAllInstance("otbWrapperApplication"); // Downcast and Sanity check for (std::list<LightObject::Pointer>::iterator i = allobjects.begin(); i != allobjects.end(); ++i) { Application* app = dynamic_cast<Application*> (i->GetPointer()); if (app) { app->Init(); std::string curName(app->GetName()); appSet.insert(curName); } } } std::vector<std::string> appVec; std::copy(appSet.begin(), appSet.end(), std::back_inserter(appVec)); return appVec; } void ApplicationRegistry::CleanRegistry() { m_ApplicationPrivateRegistryGlobal.ReleaseUnusedHandle(); } Application::Pointer ApplicationRegistry::LoadApplicationFromPath(std::string path,std::string name) { Application::Pointer appli; if (itksys::SystemTools::FileExists(path,true)) { #if defined(_WIN32) && !defined(__CYGWIN__) int cp = CP_UTF8; int acp = GetACP(); if (acp != CP_UTF8) { bool hasNonAscii=false; for (auto c: path) { if (0 > (int) c) { hasNonAscii = true; break; } } if (hasNonAscii) cp = acp; } int length = MultiByteToWideChar(cp, 0, path.c_str(), -1, NULL, 0); wchar_t* wpath = new wchar_t[length+1]; wpath[0] = '\0'; MultiByteToWideChar(cp, 0, path.c_str(), -1, wpath, length); itk::LibHandle lib = LoadLibraryW(wpath); delete [] wpath; #else itk::LibHandle lib = itksys::DynamicLoader::OpenLibrary(path); #endif if (lib) { /** * Look for the symbol itkLoad in the library */ ITK_LOAD_FUNCTION loadfunction = ( ITK_LOAD_FUNCTION ) itk::DynamicLoader::GetSymbolAddress(lib, "itkLoad"); /** * if the symbol is found call it to create the factory * from the library */ if ( loadfunction ) { itk::ObjectFactoryBase *newfactory = ( *loadfunction )( ); // Downcast ApplicationFactoryBase* appFactory = dynamic_cast<ApplicationFactoryBase*>(newfactory); if (appFactory) { appli = appFactory->CreateApplication(name.c_str()); if (appli.IsNotNull()) { appli->Init(); // register library handle m_ApplicationPrivateRegistryGlobal.AddPair(appli.GetPointer(), (void*) lib); // set a callback on DeleteEvent itk::CStyleCommand::Pointer command = itk::CStyleCommand::New(); command->SetCallback(&DeleteAppCallback); command->SetConstCallback(&DeleteAppConstCallback); appli->AddObserver(itk::DeleteEvent(),command); return appli; } } } itk::DynamicLoader::CloseLibrary(lib); } else { otbLogMacro(Warning,<< "Failed to load libraries from " << path << " while trying to create application "<<name ); } } return appli; } } // end namespace Wrapper } //end namespace otb
/* * Copyright (C) 2005-2019 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. */ #include "otbWrapperApplicationRegistry.h" #include "otbWrapperApplicationFactoryBase.h" #include "otbMacro.h" #include "itksys/SystemTools.hxx" #include "itkDynamicLoader.h" #include "itkDirectory.h" #include "itkMutexLock.h" #include "itkMutexLockHolder.h" #include <iterator> namespace otb { namespace Wrapper { // Constant : environment variable for application path static const char OTB_APPLICATION_VAR[] = "OTB_APPLICATION_PATH"; class ApplicationPrivateRegistry { public: typedef std::pair<Application*, void* > AppHandlePairType; typedef std::list<AppHandlePairType> AppHandleContainerType; /** Add a pair (application, library handle) in the private registry */ bool AddPair(Application *app, void *handle) { AppHandlePairType pair; if (app && handle) { // mutex lock to ensure thread safety itk::MutexLockHolder<itk::SimpleMutexLock> mutexHolder(m_Mutex); pair.first = app; pair.second = handle; m_Container.push_back(pair); return true; } return false; } /** When an application is deleted, unregister its pointer from private registry */ void UnregisterApp(const Application *app) { if (app) { // mutex lock to ensure thread safety itk::MutexLockHolder<itk::SimpleMutexLock> mutexHolder(m_Mutex); AppHandleContainerType::iterator it = m_Container.begin(); while (it != m_Container.end()) { if ((*it).first == app) { (*it).first = nullptr; } ++it; } } } /** Release the library handles from applications already deleted */ void ReleaseUnusedHandle() { itk::MutexLockHolder<itk::SimpleMutexLock> mutexHolder(m_Mutex); AppHandleContainerType::iterator it; for (it = m_Container.begin() ; it != m_Container.end() ; ++it) { if ((*it).first == nullptr) { itk::DynamicLoader::CloseLibrary( static_cast<itk::LibHandle>((*it).second)); (*it).second = nullptr; } } m_Container.remove(AppHandlePairType((Application*) nullptr, (void*) nullptr)); } /** close all handles at program exit */ ~ApplicationPrivateRegistry() { // unregister all ITK factories, because some of them could have been // registered by the shared libs we are about to close. itk::ObjectFactoryBase::UnRegisterAllFactories(); // Close all opened shared libs AppHandleContainerType::iterator it; for (it = m_Container.begin() ; it != m_Container.end() ; ++it) { itk::DynamicLoader::CloseLibrary( static_cast<itk::LibHandle>((*it).second)); } m_Container.clear(); } private: AppHandleContainerType m_Container; itk::SimpleMutexLock m_Mutex; }; // static finalizer to close opened libraries static ApplicationPrivateRegistry m_ApplicationPrivateRegistryGlobal; // Define callbacks to unregister applications in ApplicationPrivateRegistry void DeleteAppCallback(itk::Object *obj,const itk::EventObject &, void *) { Application *appPtr = dynamic_cast<Application*>(obj); m_ApplicationPrivateRegistryGlobal.UnregisterApp(appPtr); } void DeleteAppConstCallback(const itk::Object *obj,const itk::EventObject &, void *) { const Application *appPtr = dynamic_cast<const Application*>(obj); m_ApplicationPrivateRegistryGlobal.UnregisterApp(appPtr); } ApplicationRegistry::ApplicationRegistry() { } ApplicationRegistry::~ApplicationRegistry() { } void ApplicationRegistry::SetApplicationPath(std::string newpath) { std::ostringstream putEnvPath; putEnvPath << OTB_APPLICATION_VAR << "=" << newpath; // do NOT use putenv() directly, since the string memory must be managed carefully itksys::SystemTools::PutEnv(putEnvPath.str()); } void ApplicationRegistry::AddApplicationPath(std::string newpath) { std::ostringstream putEnvPath; putEnvPath << OTB_APPLICATION_VAR <<"="; // Can be NULL if the env var is not set const char* currentEnv = itksys::SystemTools::GetEnv(OTB_APPLICATION_VAR); #if defined(WIN32) const char pathSeparator = ';'; #else const char pathSeparator = ':'; #endif putEnvPath << newpath << pathSeparator; if (currentEnv) { putEnvPath << currentEnv; } // do NOT use putenv() directly, since the string memory must be managed carefully itksys::SystemTools::PutEnv(putEnvPath.str()); } std::string ApplicationRegistry::GetApplicationPath() { std::string ret; // Can be NULL if the env var is not set const char* currentEnv = itksys::SystemTools::GetEnv(OTB_APPLICATION_VAR); if (currentEnv) { ret = std::string(currentEnv); } return ret; } Application::Pointer ApplicationRegistry::CreateApplication(const std::string& name, bool useFactory) { ApplicationPointer appli; // Fast search : uses OTB_APPLICATION_PATH appli = ApplicationRegistry::CreateApplicationFaster(name); if (appli.IsNotNull()) { return appli; } // Classic search : uses factories registered by ITK ( see ITK_AUTOLOAD_PATH ) if (useFactory) { LightObject::Pointer possibleApp = itk::ObjectFactoryBase::CreateInstance(name.c_str()); if (possibleApp.IsNotNull()) { // Downcast Application* app = dynamic_cast<Application*> (possibleApp.GetPointer()); if (app) { appli = app; appli->Init(); } } } return appli; } typedef itk::ObjectFactoryBase * ( *ITK_LOAD_FUNCTION )(); Application::Pointer ApplicationRegistry::CreateApplicationFaster(const std::string& name) { ApplicationPointer appli = nullptr; std::string appExtension = itksys::DynamicLoader::LibExtension(); #ifdef __APPLE__ appExtension = ".dylib"; #endif std::ostringstream appLibName; appLibName << "otbapp_" << name << appExtension; #if defined(WIN32) const char pathSeparator = ';'; #else const char pathSeparator = ':'; #endif #ifdef _WIN32 const char sep = '\\'; #else const char sep = '/'; #endif std::string otbAppPath = GetApplicationPath(); std::vector<itksys::String> pathList; if (!otbAppPath.empty()) { pathList = itksys::SystemTools::SplitString(otbAppPath,pathSeparator,false); } for (unsigned int i=0 ; i<pathList.size() ; ++i) { std::string possiblePath = pathList[i]; if ( !possiblePath.empty() && possiblePath[possiblePath.size() - 1] != sep ) { possiblePath += sep; } possiblePath += appLibName.str(); appli = LoadApplicationFromPath(possiblePath,name); if (appli.IsNotNull()) { break; } } return appli; } std::vector<std::string> ApplicationRegistry::GetAvailableApplications(bool useFactory) { ApplicationPointer appli; std::set<std::string> appSet; std::string appPrefix("otbapp_"); std::string appExtension = itksys::DynamicLoader::LibExtension(); #ifdef __APPLE__ appExtension = ".dylib"; #endif #if defined(WIN32) const char pathSeparator = ';'; #else const char pathSeparator = ':'; #endif #ifdef _WIN32 const char sep = '\\'; #else const char sep = '/'; #endif std::string otbAppPath = GetApplicationPath(); std::vector<itksys::String> pathList; if (!otbAppPath.empty()) { pathList = itksys::SystemTools::SplitString(otbAppPath,pathSeparator,false); } for (unsigned int k=0 ; k<pathList.size() ; ++k) { itk::Directory::Pointer dir = itk::Directory::New(); if (!dir->Load(pathList[k].c_str())) { continue; } for (unsigned int i = 0; i < dir->GetNumberOfFiles(); i++) { const char *filename = dir->GetFile(i); std::string sfilename(filename); std::string::size_type extPos = sfilename.rfind(appExtension); std::string::size_type prefixPos = sfilename.find(appPrefix); // Check if current file is a shared lib with the right pattern if (extPos + appExtension.size() == sfilename.size() && prefixPos == 0) { std::string name = sfilename.substr(appPrefix.size(),extPos-appPrefix.size()); std::string fullpath = pathList[k]; if (!fullpath.empty() && fullpath[fullpath.size() - 1] != sep) { fullpath.push_back(sep); } fullpath.append(sfilename); appli = LoadApplicationFromPath(fullpath,name); if (appli.IsNotNull()) { appSet.insert(name); } appli = nullptr; } } } if (useFactory) { std::list<LightObject::Pointer> allobjects = itk::ObjectFactoryBase::CreateAllInstance("otbWrapperApplication"); // Downcast and Sanity check for (std::list<LightObject::Pointer>::iterator i = allobjects.begin(); i != allobjects.end(); ++i) { Application* app = dynamic_cast<Application*> (i->GetPointer()); if (app) { app->Init(); std::string curName(app->GetName()); appSet.insert(curName); } } } std::vector<std::string> appVec; std::copy(appSet.begin(), appSet.end(), std::back_inserter(appVec)); return appVec; } void ApplicationRegistry::CleanRegistry() { m_ApplicationPrivateRegistryGlobal.ReleaseUnusedHandle(); } Application::Pointer ApplicationRegistry::LoadApplicationFromPath(std::string path,std::string name) { Application::Pointer appli; if (itksys::SystemTools::FileExists(path,true)) { #if defined(_WIN32) && !defined(__CYGWIN__) int cp = CP_UTF8; int acp = GetACP(); if (acp != CP_UTF8) { bool hasNonAscii=false; for (auto c: path) { if (0 > (int) c) { hasNonAscii = true; break; } } if (hasNonAscii) cp = acp; } int length = MultiByteToWideChar(cp, 0, path.c_str(), -1, NULL, 0); wchar_t* wpath = new wchar_t[length+1]; wpath[0] = '\0'; MultiByteToWideChar(cp, 0, path.c_str(), -1, wpath, length); itk::LibHandle lib = LoadLibraryW(wpath); delete [] wpath; #else itk::LibHandle lib = itksys::DynamicLoader::OpenLibrary(path); #endif if (lib) { /** * Look for the symbol itkLoad in the library */ ITK_LOAD_FUNCTION loadfunction = ( ITK_LOAD_FUNCTION ) itk::DynamicLoader::GetSymbolAddress(lib, "itkLoad"); /** * if the symbol is found call it to create the factory * from the library */ if ( loadfunction ) { itk::ObjectFactoryBase *newfactory = ( *loadfunction )( ); // Downcast ApplicationFactoryBase* appFactory = dynamic_cast<ApplicationFactoryBase*>(newfactory); if (appFactory) { appli = appFactory->CreateApplication(name.c_str()); if (appli.IsNotNull()) { appli->Init(); // register library handle m_ApplicationPrivateRegistryGlobal.AddPair(appli.GetPointer(), (void*) lib); // set a callback on DeleteEvent itk::CStyleCommand::Pointer command = itk::CStyleCommand::New(); command->SetCallback(&DeleteAppCallback); command->SetConstCallback(&DeleteAppConstCallback); appli->AddObserver(itk::DeleteEvent(),command); return appli; } } } itk::DynamicLoader::CloseLibrary(lib); } else { otbLogMacro(Warning,<< "Failed to load libraries from " << path << " while trying to create application "<<name << "\nbecause: -> " << itksys::DynamicLoader::LastError() ); } } return appli; } } // end namespace Wrapper } //end namespace otb
Improve errors messages when loading app fail
ENH: Improve errors messages when loading app fail When we try to load an OTB application and when this fails, the error message assumes that we have given an incorrect application name. Sometimes this is simply not the case: the dynamic library may be missing symbols, it may need other dynamic library not in the `$LD_LIBRARY_PATH`... Of course, we could set `LD_DEBUG=libs` on many * nix boxes -- if we are aware of its existence, when we have given up on other leads, when we are on a * nix box... Fortunatly ITK provides the information in a portable manner, so let's cut the chase and simply give it to the end-user
C++
apache-2.0
orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB
6dea362304a597084836c9fb8daa080ce094bb0f
core/scattered_message.hh
core/scattered_message.hh
/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. 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. */ /* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef SCATTERED_MESSAGE_HH #define SCATTERED_MESSAGE_HH #include "core/reactor.hh" #include "core/deleter.hh" #include "core/temporary_buffer.hh" #include "net/packet.hh" #include "sstring.hh" #include <memory> #include <vector> template <typename CharType> class scattered_message { private: using fragment = net::fragment; using packet = net::packet; using char_type = CharType; packet _p; public: scattered_message() {} scattered_message(scattered_message&&) = default; scattered_message(const scattered_message&) = delete; void append_static(const char_type* buf, size_t size) { if (size) { _p = packet(std::move(_p), fragment{(char_type*)buf, size}, deleter()); } } template <size_t N> void append_static(const char_type(&s)[N]) { append_static(s, N - 1); } void append_static(const char_type* s) { append_static(s, strlen(s)); } template <typename size_type, size_type max_size> void append_static(const basic_sstring<char_type, size_type, max_size>& s) { append_static(s.begin(), s.size()); } template <typename size_type, size_type max_size> void append(basic_sstring<char_type, size_type, max_size> s) { if (s.size()) { _p = packet(std::move(_p), std::move(s).release()); } } template <typename size_type, size_type max_size, typename Callback> void append(const basic_sstring<char_type, size_type, max_size>& s, Callback callback) { if (s.size()) { _p = packet(std::move(_p), fragment{s.begin(), s.size()}, make_deleter(std::move(callback))); } } void reserve(int n_frags) { _p.reserve(n_frags); } packet release() && { return std::move(_p); } template <typename Callback> void on_delete(Callback callback) { _p = packet(std::move(_p), std::move(callback)); } operator bool() const { return _p.len(); } size_t size() { return _p.len(); } }; #endif
/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. 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. */ /* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef SCATTERED_MESSAGE_HH #define SCATTERED_MESSAGE_HH #include "core/reactor.hh" #include "core/deleter.hh" #include "core/temporary_buffer.hh" #include "net/packet.hh" #include "sstring.hh" #include <memory> #include <vector> #include <experimental/string_view> template <typename CharType> class scattered_message { private: using fragment = net::fragment; using packet = net::packet; using char_type = CharType; packet _p; public: scattered_message() {} scattered_message(scattered_message&&) = default; scattered_message(const scattered_message&) = delete; void append_static(const char_type* buf, size_t size) { if (size) { _p = packet(std::move(_p), fragment{(char_type*)buf, size}, deleter()); } } template <size_t N> void append_static(const char_type(&s)[N]) { append_static(s, N - 1); } void append_static(const char_type* s) { append_static(s, strlen(s)); } template <typename size_type, size_type max_size> void append_static(const basic_sstring<char_type, size_type, max_size>& s) { append_static(s.begin(), s.size()); } void append_static(const std::experimental::string_view& s) { append_static(s.data(), s.size()); } template <typename size_type, size_type max_size> void append(basic_sstring<char_type, size_type, max_size> s) { if (s.size()) { _p = packet(std::move(_p), std::move(s).release()); } } template <typename size_type, size_type max_size, typename Callback> void append(const basic_sstring<char_type, size_type, max_size>& s, Callback callback) { if (s.size()) { _p = packet(std::move(_p), fragment{s.begin(), s.size()}, make_deleter(std::move(callback))); } } void reserve(int n_frags) { _p.reserve(n_frags); } packet release() && { return std::move(_p); } template <typename Callback> void on_delete(Callback callback) { _p = packet(std::move(_p), std::move(callback)); } operator bool() const { return _p.len(); } size_t size() { return _p.len(); } }; #endif
Add experimental::string_view option to scattered_message::append_static
Add experimental::string_view option to scattered_message::append_static Signed-off-by: Raphael S. Carvalho <[email protected]>
C++
agpl-3.0
aruanruan/scylla,linearregression/seastar,slivne/seastar,gwicke/scylla,koolhazz/seastar,hongliangzhao/seastar,capturePointer/scylla,norcimo5/seastar,bowlofstew/seastar,victorbriz/scylla,sjperkins/seastar,glommer/scylla,stamhe/scylla,tempbottle/scylla,duarten/scylla,ducthangho/imdb,kjniemi/scylla,avikivity/seastar,glommer/scylla,flashbuckets/seastar,rentongzhang/scylla,raphaelsc/scylla,scylladb/seastar,xtao/seastar,joerg84/seastar,wildinto/scylla,acbellini/seastar,shyamalschandra/seastar,printedheart/seastar,anzihenry/seastar,stamhe/scylla,norcimo5/seastar,guiquanz/scylla,acbellini/scylla,glommer/scylla,dwdm/scylla,shyamalschandra/seastar,aruanruan/scylla,flashbuckets/seastar,linearregression/seastar,avikivity/scylla,avikivity/seastar,scylladb/scylla-seastar,shaunstanislaus/scylla,dreamsxin/seastar,mixja/seastar,acbellini/seastar,justintung/scylla,senseb/scylla,asias/scylla,raphaelsc/scylla,gwicke/scylla,joerg84/seastar,avikivity/scylla,raphaelsc/scylla,wildinto/scylla,kangkot/scylla,victorbriz/scylla,justintung/scylla,stamhe/scylla,justintung/scylla,kjniemi/scylla,rluta/scylla,eklitzke/scylla,syuu1228/seastar,stamhe/seastar,raphaelsc/seastar,bzero/seastar,printedheart/seastar,sjperkins/seastar,jonathanleang/seastar,acbellini/seastar,shaunstanislaus/scylla,scylladb/scylla-seastar,respu/scylla,wildinto/seastar,phonkee/scylla,capturePointer/scylla,sjperkins/seastar,kjniemi/scylla,dwdm/seastar,kangkot/scylla,ducthangho/imdb,senseb/scylla,stamhe/seastar,rluta/scylla,joerg84/seastar,bowlofstew/scylla,scylladb/seastar,avikivity/scylla,dwdm/scylla,linearregression/scylla,acbellini/scylla,tempbottle/seastar,syuu1228/seastar,kjniemi/seastar,slivne/seastar,dwdm/scylla,rluta/scylla,leejir/seastar,respu/scylla,koolhazz/seastar,cloudius-systems/seastar,asias/scylla,bzero/seastar,acbellini/scylla,bzero/seastar,phonkee/scylla,jonathanleang/seastar,shyamalschandra/seastar,eklitzke/scylla,linearregression/scylla,syuu1228/seastar,bowlofstew/scylla,wildinto/scylla,dreamsxin/seastar,linearregression/seastar,raphaelsc/seastar,tempbottle/scylla,gwicke/scylla,rentongzhang/scylla,chunshengster/seastar,senseb/scylla,dreamsxin/seastar,duarten/scylla,scylladb/scylla,bowlofstew/scylla,phonkee/scylla,shaunstanislaus/scylla,bowlofstew/seastar,tempbottle/scylla,asias/scylla,scylladb/scylla,guiquanz/scylla,anzihenry/seastar,scylladb/scylla,wildinto/seastar,tempbottle/seastar,flashbuckets/seastar,norcimo5/seastar,capturePointer/scylla,kjniemi/seastar,hongliangzhao/seastar,eklitzke/scylla,raphaelsc/seastar,stamhe/seastar,aruanruan/scylla,dwdm/seastar,linearregression/scylla,avikivity/seastar,xtao/seastar,dwdm/seastar,koolhazz/seastar,tempbottle/seastar,cloudius-systems/seastar,mixja/seastar,guiquanz/scylla,leejir/seastar,duarten/scylla,victorbriz/scylla,slivne/seastar,scylladb/scylla-seastar,mixja/seastar,jonathanleang/seastar,xtao/seastar,bowlofstew/seastar,chunshengster/seastar,cloudius-systems/seastar,scylladb/scylla,chunshengster/seastar,ducthangho/imdb,kjniemi/seastar,respu/scylla,leejir/seastar,printedheart/seastar,wildinto/seastar,hongliangzhao/seastar,kangkot/scylla,rentongzhang/scylla,anzihenry/seastar,scylladb/seastar
fbb9ebd771bfae2186cd221948e52ec6ab679c0b
core/src/util/usUtils.cpp
core/src/util/usUtils.cpp
/*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics 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 "usUtils_p.h" #include "usLog_p.h" #include "usModuleInfo.h" #include "usModuleSettings.h" #include <cstdio> #include <cctype> #include <algorithm> #include <typeinfo> #ifdef US_PLATFORM_POSIX #include <errno.h> #include <string.h> #include <dlfcn.h> #include <dirent.h> #else #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include <windows.h> #include <crtdbg.h> #include "dirent_win32.h" #endif //------------------------------------------------------------------- // Module auto-loading //------------------------------------------------------------------- namespace { #if !defined(US_PLATFORM_LINUX) std::string library_suffix() { #ifdef US_PLATFORM_WINDOWS return ".dll"; #elif defined(US_PLATFORM_APPLE) return ".dylib"; #else return ".so"; #endif } #endif #ifdef US_PLATFORM_POSIX const char DIR_SEP = '/'; bool load_impl(const std::string& modulePath) { void* handle = dlopen(modulePath.c_str(), RTLD_NOW | RTLD_LOCAL); if (handle == NULL) { US_WARN << dlerror(); } return (handle != NULL); } #elif defined(US_PLATFORM_WINDOWS) const char DIR_SEP = '\\'; bool load_impl(const std::string& modulePath) { void* handle = LoadLibrary(modulePath.c_str()); if (handle == NULL) { US_WARN << us::GetLastErrorStr(); } return (handle != NULL); } #else #ifdef US_ENABLE_AUTOLOADING_SUPPORT #error "Missing load_impl implementation for this platform." #else bool load_impl(const std::string&) { return false; } #endif #endif } US_BEGIN_NAMESPACE std::vector<std::string> AutoLoadModulesFromPath(const std::string& absoluteBasePath, const std::string& subDir) { std::vector<std::string> loadedModules; std::string loadPath = absoluteBasePath + DIR_SEP + subDir; DIR* dir = opendir(loadPath.c_str()); #ifdef CMAKE_INTDIR // Try intermediate output directories if (dir == NULL) { std::size_t indexOfLastSeparator = absoluteBasePath.find_last_of(DIR_SEP); if (indexOfLastSeparator != std::string::npos) { std::string intermediateDir = absoluteBasePath.substr(indexOfLastSeparator+1); bool equalSubDir = intermediateDir.size() == std::strlen(CMAKE_INTDIR); for (std::size_t i = 0; equalSubDir && i < intermediateDir.size(); ++i) { if (std::tolower(intermediateDir[i]) != std::tolower(CMAKE_INTDIR[i])) { equalSubDir = false; } } if (equalSubDir) { loadPath = absoluteBasePath.substr(0, indexOfLastSeparator+1) + subDir + DIR_SEP + CMAKE_INTDIR; dir = opendir(loadPath.c_str()); } } } #endif if (dir != NULL) { struct dirent *ent = NULL; while ((ent = readdir(dir)) != NULL) { bool loadFile = true; #ifdef _DIRENT_HAVE_D_TYPE if (ent->d_type != DT_UNKNOWN && ent->d_type != DT_REG) { loadFile = false; } #endif std::string entryFileName(ent->d_name); // On Linux, library file names can have version numbers appended. On other platforms, we // check the file ending. This could be refined for Linux in the future. #if !defined(US_PLATFORM_LINUX) if (entryFileName.rfind(library_suffix()) != (entryFileName.size() - library_suffix().size())) { loadFile = false; } #endif if (!loadFile) continue; std::string libPath = loadPath; if (!libPath.empty() && libPath.find_last_of(DIR_SEP) != libPath.size() -1) { libPath += DIR_SEP; } libPath += entryFileName; US_DEBUG << "Auto-loading module " << libPath; if (!load_impl(libPath)) { US_WARN << "Auto-loading of module " << libPath << " failed."; } else { loadedModules.push_back(libPath); } } closedir(dir); } return loadedModules; } std::vector<std::string> AutoLoadModules(const ModuleInfo& moduleInfo) { std::vector<std::string> loadedModules; if (moduleInfo.autoLoadDir.empty()) { return loadedModules; } ModuleSettings::PathList autoLoadPaths = ModuleSettings::GetAutoLoadPaths(); std::size_t indexOfLastSeparator = moduleInfo.location.find_last_of(DIR_SEP); std::string moduleBasePath = moduleInfo.location.substr(0, indexOfLastSeparator); for (ModuleSettings::PathList::iterator i = autoLoadPaths.begin(); i != autoLoadPaths.end(); ++i) { if (*i == ModuleSettings::CURRENT_MODULE_PATH()) { // Load all modules from a directory located relative to this modules location // and named after this modules library name. *i = moduleBasePath; } } // We could have introduced a duplicate above, so remove it. std::sort(autoLoadPaths.begin(), autoLoadPaths.end()); autoLoadPaths.erase(std::unique(autoLoadPaths.begin(), autoLoadPaths.end()), autoLoadPaths.end()); for (ModuleSettings::PathList::iterator i = autoLoadPaths.begin(); i != autoLoadPaths.end(); ++i) { if (i->empty()) continue; std::vector<std::string> paths = AutoLoadModulesFromPath(*i, moduleInfo.autoLoadDir); loadedModules.insert(loadedModules.end(), paths.begin(), paths.end()); } return loadedModules; } US_END_NAMESPACE //------------------------------------------------------------------- // Error handling //------------------------------------------------------------------- US_BEGIN_NAMESPACE std::string GetLastErrorStr() { #ifdef US_PLATFORM_POSIX return std::string(strerror(errno)); #else // Retrieve the system error message for the last-error code LPVOID lpMsgBuf; DWORD dw = GetLastError(); FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0, NULL ); std::string errMsg((LPCTSTR)lpMsgBuf); LocalFree(lpMsgBuf); return errMsg; #endif } static MsgHandler handler = 0; MsgHandler installMsgHandler(MsgHandler h) { MsgHandler old = handler; handler = h; return old; } void message_output(MsgType msgType, const char *buf) { if (handler) { (*handler)(msgType, buf); } else { fprintf(stderr, "%s\n", buf); fflush(stderr); } if (msgType == ErrorMsg) { #if defined(_MSC_VER) && !defined(NDEBUG) && defined(_DEBUG) && defined(_CRT_ERROR) // get the current report mode int reportMode = _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_WNDW); _CrtSetReportMode(_CRT_ERROR, reportMode); int ret = _CrtDbgReport(_CRT_ERROR, __FILE__, __LINE__, CppMicroServices_VERSION_STR, buf); if (ret == 0 && reportMode & _CRTDBG_MODE_WNDW) return; // ignore else if (ret == 1) _CrtDbgBreak(); #endif #ifdef US_PLATFORM_POSIX abort(); // trap; generates core dump #else exit(1); // goodbye cruel world #endif } } #ifdef US_HAVE_CXXABI_H #include <cxxabi.h> #endif US_Core_EXPORT std::string GetDemangledName(const std::type_info& typeInfo) { std::string result; #ifdef US_HAVE_CXXABI_H int status = 0; char* demangled = abi::__cxa_demangle(typeInfo.name(), 0, 0, &status); if (demangled && status == 0) { result = demangled; free(demangled); } #elif defined(US_PLATFORM_WINDOWS) const char* demangled = typeInfo.name(); if (demangled != NULL) { result = demangled; // remove "struct" qualifiers std::size_t pos = 0; while (pos != std::string::npos) { if ((pos = result.find("struct ", pos)) != std::string::npos) { result = result.substr(0, pos) + result.substr(pos + 7); pos += 8; } } // remove "class" qualifiers pos = 0; while (pos != std::string::npos) { if ((pos = result.find("class ", pos)) != std::string::npos) { result = result.substr(0, pos) + result.substr(pos + 6); pos += 7; } } } #else (void)typeInfo; #endif return result; } US_END_NAMESPACE
/*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics 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 "usUtils_p.h" #include "usLog_p.h" #include "usModuleInfo.h" #include "usModuleSettings.h" #include <string> #include <cstdio> #include <cctype> #include <algorithm> #include <typeinfo> #ifdef US_PLATFORM_POSIX #include <errno.h> #include <string.h> #include <dlfcn.h> #include <dirent.h> #else #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include <windows.h> #include <crtdbg.h> #include "dirent_win32.h" #endif //------------------------------------------------------------------- // Module auto-loading //------------------------------------------------------------------- namespace { #if !defined(US_PLATFORM_LINUX) std::string library_suffix() { #ifdef US_PLATFORM_WINDOWS return ".dll"; #elif defined(US_PLATFORM_APPLE) return ".dylib"; #else return ".so"; #endif } #endif #ifdef US_PLATFORM_POSIX const char DIR_SEP = '/'; bool load_impl(const std::string& modulePath) { void* handle = dlopen(modulePath.c_str(), RTLD_NOW | RTLD_LOCAL); if (handle == NULL) { US_WARN << dlerror(); } return (handle != NULL); } #elif defined(US_PLATFORM_WINDOWS) const char DIR_SEP = '\\'; bool load_impl(const std::string& modulePath) { void* handle = LoadLibrary(modulePath.c_str()); if (handle == NULL) { US_WARN << us::GetLastErrorStr(); } return (handle != NULL); } #else #ifdef US_ENABLE_AUTOLOADING_SUPPORT #error "Missing load_impl implementation for this platform." #else bool load_impl(const std::string&) { return false; } #endif #endif } US_BEGIN_NAMESPACE std::vector<std::string> AutoLoadModulesFromPath(const std::string& absoluteBasePath, const std::string& subDir) { std::vector<std::string> loadedModules; std::string loadPath = absoluteBasePath + DIR_SEP + subDir; DIR* dir = opendir(loadPath.c_str()); #ifdef CMAKE_INTDIR // Try intermediate output directories if (dir == NULL) { std::size_t indexOfLastSeparator = absoluteBasePath.find_last_of(DIR_SEP); if (indexOfLastSeparator != std::string::npos) { std::string intermediateDir = absoluteBasePath.substr(indexOfLastSeparator+1); bool equalSubDir = intermediateDir.size() == std::strlen(CMAKE_INTDIR); for (std::size_t i = 0; equalSubDir && i < intermediateDir.size(); ++i) { if (std::tolower(intermediateDir[i]) != std::tolower(CMAKE_INTDIR[i])) { equalSubDir = false; } } if (equalSubDir) { loadPath = absoluteBasePath.substr(0, indexOfLastSeparator+1) + subDir + DIR_SEP + CMAKE_INTDIR; dir = opendir(loadPath.c_str()); } } } #endif if (dir != NULL) { struct dirent *ent = NULL; while ((ent = readdir(dir)) != NULL) { bool loadFile = true; #ifdef _DIRENT_HAVE_D_TYPE if (ent->d_type != DT_UNKNOWN && ent->d_type != DT_REG) { loadFile = false; } #endif std::string entryFileName(ent->d_name); // On Linux, library file names can have version numbers appended. On other platforms, we // check the file ending. This could be refined for Linux in the future. #if !defined(US_PLATFORM_LINUX) if (entryFileName.rfind(library_suffix()) != (entryFileName.size() - library_suffix().size())) { loadFile = false; } #endif if (!loadFile) continue; std::string libPath = loadPath; if (!libPath.empty() && libPath.find_last_of(DIR_SEP) != libPath.size() -1) { libPath += DIR_SEP; } libPath += entryFileName; US_DEBUG << "Auto-loading module " << libPath; if (!load_impl(libPath)) { US_WARN << "Auto-loading of module " << libPath << " failed."; } else { loadedModules.push_back(libPath); } } closedir(dir); } return loadedModules; } std::vector<std::string> AutoLoadModules(const ModuleInfo& moduleInfo) { std::vector<std::string> loadedModules; if (moduleInfo.autoLoadDir.empty()) { return loadedModules; } ModuleSettings::PathList autoLoadPaths = ModuleSettings::GetAutoLoadPaths(); std::size_t indexOfLastSeparator = moduleInfo.location.find_last_of(DIR_SEP); std::string moduleBasePath = moduleInfo.location.substr(0, indexOfLastSeparator); for (ModuleSettings::PathList::iterator i = autoLoadPaths.begin(); i != autoLoadPaths.end(); ++i) { if (*i == ModuleSettings::CURRENT_MODULE_PATH()) { // Load all modules from a directory located relative to this modules location // and named after this modules library name. *i = moduleBasePath; } } // We could have introduced a duplicate above, so remove it. std::sort(autoLoadPaths.begin(), autoLoadPaths.end()); autoLoadPaths.erase(std::unique(autoLoadPaths.begin(), autoLoadPaths.end()), autoLoadPaths.end()); for (ModuleSettings::PathList::iterator i = autoLoadPaths.begin(); i != autoLoadPaths.end(); ++i) { if (i->empty()) continue; std::vector<std::string> paths = AutoLoadModulesFromPath(*i, moduleInfo.autoLoadDir); loadedModules.insert(loadedModules.end(), paths.begin(), paths.end()); } return loadedModules; } US_END_NAMESPACE //------------------------------------------------------------------- // Error handling //------------------------------------------------------------------- US_BEGIN_NAMESPACE std::string GetLastErrorStr() { #ifdef US_PLATFORM_POSIX return std::string(strerror(errno)); #else // Retrieve the system error message for the last-error code LPVOID lpMsgBuf; DWORD dw = GetLastError(); FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0, NULL ); std::string errMsg((LPCTSTR)lpMsgBuf); LocalFree(lpMsgBuf); return errMsg; #endif } static MsgHandler handler = 0; MsgHandler installMsgHandler(MsgHandler h) { MsgHandler old = handler; handler = h; return old; } void message_output(MsgType msgType, const char *buf) { if (handler) { (*handler)(msgType, buf); } else { fprintf(stderr, "%s\n", buf); fflush(stderr); } if (msgType == ErrorMsg) { #if defined(_MSC_VER) && !defined(NDEBUG) && defined(_DEBUG) && defined(_CRT_ERROR) // get the current report mode int reportMode = _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_WNDW); _CrtSetReportMode(_CRT_ERROR, reportMode); int ret = _CrtDbgReport(_CRT_ERROR, __FILE__, __LINE__, CppMicroServices_VERSION_STR, buf); if (ret == 0 && reportMode & _CRTDBG_MODE_WNDW) return; // ignore else if (ret == 1) _CrtDbgBreak(); #endif #ifdef US_PLATFORM_POSIX abort(); // trap; generates core dump #else exit(1); // goodbye cruel world #endif } } #ifdef US_HAVE_CXXABI_H #include <cxxabi.h> #endif US_Core_EXPORT ::std::string GetDemangledName(const std::type_info& typeInfo) { ::std::string result; #ifdef US_HAVE_CXXABI_H int status = 0; char* demangled = abi::__cxa_demangle(typeInfo.name(), 0, 0, &status); if (demangled && status == 0) { result = demangled; free(demangled); } #elif defined(US_PLATFORM_WINDOWS) const char* demangled = typeInfo.name(); if (demangled != NULL) { result = demangled; // remove "struct" qualifiers std::size_t pos = 0; while (pos != std::string::npos) { if ((pos = result.find("struct ", pos)) != std::string::npos) { result = result.substr(0, pos) + result.substr(pos + 7); pos += 8; } } // remove "class" qualifiers pos = 0; while (pos != std::string::npos) { if ((pos = result.find("class ", pos)) != std::string::npos) { result = result.substr(0, pos) + result.substr(pos + 6); pos += 7; } } } #else (void)typeInfo; #endif return result; } US_END_NAMESPACE
Fix gcc MacOS namespace issue.
Fix gcc MacOS namespace issue.
C++
apache-2.0
saschazelzer/CppMicroServices,ksubramz/CppMicroServices,ksubramz/CppMicroServices,CppMicroServices/CppMicroServices,CppMicroServices/CppMicroServices,ksubramz/CppMicroServices,CppMicroServices/CppMicroServices,ksubramz/CppMicroServices,ksubramz/CppMicroServices,CppMicroServices/CppMicroServices,CppMicroServices/CppMicroServices,saschazelzer/CppMicroServices
a23a9bfd2075c2bf0d28423e3f25d1d4be0b962b
Applications/Projections/otbSuperimpose.cxx
Applications/Projections/otbSuperimpose.cxx
/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. 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 "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" #include "otbGenericRSResampleImageFilter.h" #include "itkLinearInterpolateImageFunction.h" #include "otbBCOInterpolateImageFunction.h" #include "itkNearestNeighborInterpolateImageFunction.h" // Elevation handler #include "otbWrapperElevationParametersHandler.h" namespace otb { enum { Interpolator_BCO, Interpolator_NNeighbor, Interpolator_Linear }; namespace Wrapper { class Superimpose : public Application { public: /** Standard class typedefs. */ typedef Superimpose Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; /** Standard macro */ itkNewMacro(Self); itkTypeMacro(Superimpose, Application); typedef unsigned short int PixelType; typedef itk::LinearInterpolateImageFunction <FloatVectorImageType, double> LinInterpolatorType; typedef itk::NearestNeighborInterpolateImageFunction <FloatVectorImageType, double> NNInterpolatorType; typedef otb::BCOInterpolateImageFunction <FloatVectorImageType> BCOInterpolatorType; typedef otb::GenericRSResampleImageFilter<FloatVectorImageType, FloatVectorImageType> ResamplerType; private: void DoInit() { SetName("Superimpose"); SetDescription("Using available image metadata, project one image onto another one"); // Documentation SetDocName("Superimpose sensor"); SetDocLongDescription("This application performs the projection of an image into the geometry of another one."); SetDocLimitations("None"); SetDocAuthors("OTB-Team"); SetDocSeeAlso(" "); AddDocTag(Tags::Geometry); AddDocTag("Superimposition"); AddParameter(ParameterType_InputImage, "inr", "Reference input"); SetParameterDescription("inr","The input reference image."); AddParameter(ParameterType_InputImage, "inm", "The image to reproject"); SetParameterDescription("inm","The image to reproject into the geometry of the reference input."); // Elevation ElevationParametersHandler::AddElevationParameters(this, "elev"); AddParameter(ParameterType_Float, "lms", "Spacing of the deformation field"); SetParameterDescription("lms","Generate a coarser deformation field with the given spacing"); SetDefaultParameterFloat("lms", 4.); MandatoryOff("lms"); AddParameter(ParameterType_OutputImage, "out", "Output image"); SetParameterDescription("out","Output reprojected image."); // Interpolators AddParameter(ParameterType_Choice, "interpolator", "Interpolation"); SetParameterDescription("interpolator","This group of parameters allows to define how the input image will be interpolated during resampling."); AddChoice("interpolator.bco", "Bicubic interpolation"); SetParameterDescription("interpolator.bco", "Bicubic interpolation leads to very good image quality but is slow."); AddParameter(ParameterType_Radius, "interpolator.bco.radius", "Radius for bicubic interpolation"); SetParameterDescription("interpolator.bco.radius","This parameter allows to control the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artefacts."); SetDefaultParameterInt("interpolator.bco.radius", 2); AddChoice("interpolator.nn", "Nearest Neighbor interpolation"); SetParameterDescription("interpolator.nn","Nearest neighbor interpolation leads to poor image quality, but it is very fast."); AddChoice("interpolator.linear", "Linear interpolation"); SetParameterDescription("interpolator.linear","Linear interpolation leads to average image quality but is quite fast"); AddRAMParameter(); // Doc example parameter settings SetDocExampleParameterValue("inr", "QB_Toulouse_Ortho_PAN.tif"); SetDocExampleParameterValue("inm", "QB_Toulouse_Ortho_XS.tif"); SetDocExampleParameterValue("out", "SuperimposedXS_to_PAN.tif"); } void DoUpdateParameters() { // Nothing to do here : all parameters are independent } void DoExecute() { // Get the inputs FloatVectorImageType* refImage = GetParameterImage("inr"); FloatVectorImageType* movingImage = GetParameterImage("inm"); // Resample filter m_Resampler = ResamplerType::New(); // Get Interpolator switch ( GetParameterInt("interpolator") ) { case Interpolator_Linear: { LinInterpolatorType::Pointer interpolator = LinInterpolatorType::New(); m_Resampler->SetInterpolator(interpolator); } break; case Interpolator_NNeighbor: { NNInterpolatorType::Pointer interpolator = NNInterpolatorType::New(); m_Resampler->SetInterpolator(interpolator); } break; case Interpolator_BCO: { BCOInterpolatorType::Pointer interpolator = BCOInterpolatorType::New(); interpolator->SetRadius(GetParameterInt("interpolator.bco.radius")); m_Resampler->SetInterpolator(interpolator); } break; } // Setup the DEM Handler otb::Wrapper::ElevationParametersHandler::SetupDEMHandlerFromElevationParameters(this,"elev"); // Set up output image informations FloatVectorImageType::SpacingType spacing = refImage->GetSpacing(); FloatVectorImageType::IndexType start = refImage->GetLargestPossibleRegion().GetIndex(); FloatVectorImageType::SizeType size = refImage->GetLargestPossibleRegion().GetSize(); FloatVectorImageType::PointType origin = refImage->GetOrigin(); if(IsParameterEnabled("lms")) { float defScalarSpacing = vcl_abs(GetParameterFloat("lms")); std::cout<<"Generating coarse deformation field (spacing="<<defScalarSpacing<<")"<<std::endl; FloatVectorImageType::SpacingType defSpacing; defSpacing[0] = defScalarSpacing; defSpacing[1] = defScalarSpacing; if (spacing[0]<0.0) defSpacing[0] *= -1.0; if (spacing[1]<0.0) defSpacing[1] *= -1.0; m_Resampler->SetDeformationFieldSpacing(defSpacing); } FloatVectorImageType::PixelType defaultValue; itk::PixelBuilder<FloatVectorImageType::PixelType>::Zero(defaultValue, movingImage->GetNumberOfComponentsPerPixel()); m_Resampler->SetInput(movingImage); m_Resampler->SetInputKeywordList(movingImage->GetImageKeywordlist()); m_Resampler->SetInputProjectionRef(movingImage->GetProjectionRef()); m_Resampler->SetOutputOrigin(origin); m_Resampler->SetOutputSpacing(spacing); m_Resampler->SetOutputSize(size); m_Resampler->SetOutputStartIndex(start); m_Resampler->SetOutputKeywordList(refImage->GetImageKeywordlist()); m_Resampler->SetOutputProjectionRef(refImage->GetProjectionRef()); m_Resampler->SetEdgePaddingValue(defaultValue); // Set the output image SetParameterOutputImage("out", m_Resampler->GetOutput()); } ResamplerType::Pointer m_Resampler; }; } // end namespace Wrapper } // end namespace otb OTB_APPLICATION_EXPORT(otb::Wrapper::Superimpose)
/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. 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 "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" #include "otbGenericRSResampleImageFilter.h" #include "itkLinearInterpolateImageFunction.h" #include "otbBCOInterpolateImageFunction.h" #include "itkNearestNeighborInterpolateImageFunction.h" // Elevation handler #include "otbWrapperElevationParametersHandler.h" namespace otb { enum { Interpolator_BCO, Interpolator_NNeighbor, Interpolator_Linear }; namespace Wrapper { class Superimpose : public Application { public: /** Standard class typedefs. */ typedef Superimpose Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; /** Standard macro */ itkNewMacro(Self); itkTypeMacro(Superimpose, Application); typedef unsigned short int PixelType; typedef itk::LinearInterpolateImageFunction <FloatVectorImageType, double> LinInterpolatorType; typedef itk::NearestNeighborInterpolateImageFunction <FloatVectorImageType, double> NNInterpolatorType; typedef otb::BCOInterpolateImageFunction <FloatVectorImageType> BCOInterpolatorType; typedef otb::GenericRSResampleImageFilter<FloatVectorImageType, FloatVectorImageType> ResamplerType; private: void DoInit() { SetName("Superimpose"); SetDescription("Using available image metadata, project one image onto another one"); // Documentation SetDocName("Superimpose sensor"); SetDocLongDescription("This application performs the projection of an image into the geometry of another one."); SetDocLimitations("None"); SetDocAuthors("OTB-Team"); SetDocSeeAlso(" "); AddDocTag(Tags::Geometry); AddDocTag("Superimposition"); AddParameter(ParameterType_InputImage, "inr", "Reference input"); SetParameterDescription("inr","The input reference image."); AddParameter(ParameterType_InputImage, "inm", "The image to reproject"); SetParameterDescription("inm","The image to reproject into the geometry of the reference input."); // Elevation ElevationParametersHandler::AddElevationParameters(this, "elev"); AddParameter(ParameterType_Float, "lms", "Spacing of the deformation field"); SetParameterDescription("lms","Generate a coarser deformation field with the given spacing"); SetDefaultParameterFloat("lms", 4.); MandatoryOff("lms"); AddParameter(ParameterType_OutputImage, "out", "Output image"); SetParameterDescription("out","Output reprojected image."); // Interpolators AddParameter(ParameterType_Choice, "interpolator", "Interpolation"); SetParameterDescription("interpolator","This group of parameters allows to define how the input image will be interpolated during resampling."); AddChoice("interpolator.bco", "Bicubic interpolation"); SetParameterDescription("interpolator.bco", "Bicubic interpolation leads to very good image quality but is slow."); AddParameter(ParameterType_Radius, "interpolator.bco.radius", "Radius for bicubic interpolation"); SetParameterDescription("interpolator.bco.radius","This parameter allows to control the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artefacts."); SetDefaultParameterInt("interpolator.bco.radius", 2); AddChoice("interpolator.nn", "Nearest Neighbor interpolation"); SetParameterDescription("interpolator.nn","Nearest neighbor interpolation leads to poor image quality, but it is very fast."); AddChoice("interpolator.linear", "Linear interpolation"); SetParameterDescription("interpolator.linear","Linear interpolation leads to average image quality but is quite fast"); AddRAMParameter(); // Doc example parameter settings SetDocExampleParameterValue("inr", "QB_Toulouse_Ortho_PAN.tif"); SetDocExampleParameterValue("inm", "QB_Toulouse_Ortho_XS.tif"); SetDocExampleParameterValue("out", "SuperimposedXS_to_PAN.tif"); } void DoUpdateParameters() { // Nothing to do here : all parameters are independent } void DoExecute() { // Get the inputs FloatVectorImageType* refImage = GetParameterImage("inr"); FloatVectorImageType* movingImage = GetParameterImage("inm"); // Resample filter m_Resampler = ResamplerType::New(); // Get Interpolator switch ( GetParameterInt("interpolator") ) { case Interpolator_Linear: { LinInterpolatorType::Pointer interpolator = LinInterpolatorType::New(); m_Resampler->SetInterpolator(interpolator); } break; case Interpolator_NNeighbor: { NNInterpolatorType::Pointer interpolator = NNInterpolatorType::New(); m_Resampler->SetInterpolator(interpolator); } break; case Interpolator_BCO: { BCOInterpolatorType::Pointer interpolator = BCOInterpolatorType::New(); interpolator->SetRadius(GetParameterInt("interpolator.bco.radius")); m_Resampler->SetInterpolator(interpolator); } break; } // Setup the DEM Handler otb::Wrapper::ElevationParametersHandler::SetupDEMHandlerFromElevationParameters(this,"elev"); // Set up output image informations FloatVectorImageType::SpacingType spacing = refImage->GetSpacing(); FloatVectorImageType::IndexType start = refImage->GetLargestPossibleRegion().GetIndex(); FloatVectorImageType::SizeType size = refImage->GetLargestPossibleRegion().GetSize(); FloatVectorImageType::PointType origin = refImage->GetOrigin(); if(IsParameterEnabled("lms")) { float defScalarSpacing = vcl_abs(GetParameterFloat("lms")); otbAppLogDEBUG("Generating coarse deformation field (spacing="<<defScalarSpacing<<")"); FloatVectorImageType::SpacingType defSpacing; defSpacing[0] = defScalarSpacing; defSpacing[1] = defScalarSpacing; if (spacing[0]<0.0) defSpacing[0] *= -1.0; if (spacing[1]<0.0) defSpacing[1] *= -1.0; m_Resampler->SetDeformationFieldSpacing(defSpacing); } FloatVectorImageType::PixelType defaultValue; itk::PixelBuilder<FloatVectorImageType::PixelType>::Zero(defaultValue, movingImage->GetNumberOfComponentsPerPixel()); m_Resampler->SetInput(movingImage); m_Resampler->SetInputKeywordList(movingImage->GetImageKeywordlist()); m_Resampler->SetInputProjectionRef(movingImage->GetProjectionRef()); m_Resampler->SetOutputOrigin(origin); m_Resampler->SetOutputSpacing(spacing); m_Resampler->SetOutputSize(size); m_Resampler->SetOutputStartIndex(start); m_Resampler->SetOutputKeywordList(refImage->GetImageKeywordlist()); m_Resampler->SetOutputProjectionRef(refImage->GetProjectionRef()); m_Resampler->SetEdgePaddingValue(defaultValue); // Set the output image SetParameterOutputImage("out", m_Resampler->GetOutput()); } ResamplerType::Pointer m_Resampler; }; } // end namespace Wrapper } // end namespace otb OTB_APPLICATION_EXPORT(otb::Wrapper::Superimpose)
replace std::cout by application logger in Superimpose
ENH: replace std::cout by application logger in Superimpose
C++
apache-2.0
orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB
8032f774767dcdab874c719f2787d547fabe4d6a
cores/esp8266/Updater.cpp
cores/esp8266/Updater.cpp
#include "Updater.h" #include "Arduino.h" #include "eboot_command.h" #include "interrupts.h" //#define DEBUG_UPDATER Serial extern "C" { #include "c_types.h" #include "spi_flash.h" #include "user_interface.h" } extern "C" uint32_t _SPIFFS_start; UpdaterClass::UpdaterClass() : _error(0) , _buffer(0) , _bufferLen(0) , _size(0) , _startAddress(0) , _currentAddress(0) , _command(U_FLASH) { } void UpdaterClass::_reset() { if (_buffer) delete[] _buffer; _buffer = 0; _bufferLen = 0; _startAddress = 0; _currentAddress = 0; _size = 0; _command = U_FLASH; } bool UpdaterClass::begin(size_t size, int command) { if(_size > 0){ #ifdef DEBUG_UPDATER DEBUG_UPDATER.println("[begin] already running"); #endif return false; } #ifdef DEBUG_UPDATER if (command == U_SPIFFS) { DEBUG_UPDATER.println("[begin] Update SPIFFS."); } #endif if(size == 0) { _error = UPDATE_ERROR_SIZE; #ifdef DEBUG_UPDATER printError(DEBUG_UPDATER); #endif return false; } if(ESP.checkFlashConfig(false)) { _error = UPDATE_ERROR_FLASH_CONFIG; #ifdef DEBUG_UPDATER printError(DEBUG_UPDATER); #endif return false; } _reset(); _error = 0; wifi_set_sleep_type(NONE_SLEEP_T); uint32_t updateStartAddress = 0; if (command == U_FLASH) { //size of current sketch rounded to a sector uint32_t currentSketchSize = (ESP.getSketchSize() + FLASH_SECTOR_SIZE - 1) & (~(FLASH_SECTOR_SIZE - 1)); //address of the end of the space available for sketch and update uint32_t updateEndAddress = (uint32_t)&_SPIFFS_start - 0x40200000; //size of the update rounded to a sector uint32_t roundedSize = (size + FLASH_SECTOR_SIZE - 1) & (~(FLASH_SECTOR_SIZE - 1)); //address where we will start writing the update updateStartAddress = updateEndAddress - roundedSize; #ifdef DEBUG_UPDATER DEBUG_UPDATER.printf("[begin] roundedSize: 0x%08X (%d)\n", roundedSize, roundedSize); DEBUG_UPDATER.printf("[begin] updateEndAddress: 0x%08X (%d)\n", updateEndAddress, updateEndAddress); DEBUG_UPDATER.printf("[begin] currentSketchSize: 0x%08X (%d)\n", currentSketchSize, currentSketchSize); #endif //make sure that the size of both sketches is less than the total space (updateEndAddress) if(updateStartAddress < currentSketchSize) { _error = UPDATE_ERROR_SPACE; #ifdef DEBUG_UPDATER printError(DEBUG_UPDATER); #endif return false; } } else if (command == U_SPIFFS) { updateStartAddress = (uint32_t)&_SPIFFS_start - 0x40200000; } else { // unknown command #ifdef DEBUG_UPDATER DEBUG_UPDATER.println("[begin] Unknown update command."); #endif return false; } //initialize _startAddress = updateStartAddress; _currentAddress = _startAddress; _size = size; _buffer = new uint8_t[FLASH_SECTOR_SIZE]; _command = command; #ifdef DEBUG_UPDATER DEBUG_UPDATER.printf("[begin] _startAddress: 0x%08X (%d)\n", _startAddress, _startAddress); DEBUG_UPDATER.printf("[begin] _currentAddress: 0x%08X (%d)\n", _currentAddress, _currentAddress); DEBUG_UPDATER.printf("[begin] _size: 0x%08X (%d)\n", _size, _size); #endif _md5.begin(); return true; } bool UpdaterClass::setMD5(const char * expected_md5){ if(strlen(expected_md5) != 32) { return false; } _target_md5 = expected_md5; return true; } bool UpdaterClass::end(bool evenIfRemaining){ if(_size == 0){ #ifdef DEBUG_UPDATER DEBUG_UPDATER.println("no update"); #endif return false; } if(hasError() || (!isFinished() && !evenIfRemaining)){ #ifdef DEBUG_UPDATER DEBUG_UPDATER.printf("premature end: res:%u, pos:%u/%u\n", getError(), progress(), _size); #endif _reset(); return false; } if(evenIfRemaining) { if(_bufferLen > 0) { _writeBuffer(); } _size = progress(); } _md5.calculate(); if(_target_md5.length()) { if(_target_md5 != _md5.toString()){ _error = UPDATE_ERROR_MD5; #ifdef DEBUG_UPDATER DEBUG_UPDATER.printf("MD5 Failed: expected:%s, calculated:%s\n", _target_md5.c_str(), _md5.toString().c_str()); #endif _reset(); return false; } #ifdef DEBUG_UPDATER else DEBUG_UPDATER.printf("MD5 Success: %s\n", _target_md5.c_str()); #endif } if (_command == U_FLASH) { eboot_command ebcmd; ebcmd.action = ACTION_COPY_RAW; ebcmd.args[0] = _startAddress; ebcmd.args[1] = 0x00000; ebcmd.args[2] = _size; eboot_command_write(&ebcmd); #ifdef DEBUG_UPDATER DEBUG_UPDATER.printf("Staged: address:0x%08X, size:0x%08X\n", _startAddress, _size); } else if (_command == U_SPIFFS) { DEBUG_UPDATER.printf("SPIFFS: address:0x%08X, size:0x%08X\n", _startAddress, _size); #endif } _reset(); return true; } bool UpdaterClass::_writeBuffer(){ yield(); bool result = ESP.flashEraseSector(_currentAddress/FLASH_SECTOR_SIZE); yield(); if (result) { result = ESP.flashWrite(_currentAddress, (uint32_t*) _buffer, _bufferLen); } yield(); if (!result) { _error = UPDATE_ERROR_WRITE; _currentAddress = (_startAddress + _size); #ifdef DEBUG_UPDATER printError(DEBUG_UPDATER); #endif return false; } _md5.add(_buffer, _bufferLen); _currentAddress += _bufferLen; _bufferLen = 0; return true; } size_t UpdaterClass::write(uint8_t *data, size_t len) { size_t left = len; if(hasError() || !isRunning()) return 0; if(len > remaining()) len = remaining(); while((_bufferLen + left) > FLASH_SECTOR_SIZE) { size_t toBuff = FLASH_SECTOR_SIZE - _bufferLen; memcpy(_buffer + _bufferLen, data + (len - left), toBuff); _bufferLen += toBuff; if(!_writeBuffer()){ return len - left; } left -= toBuff; yield(); } //lets see whats left memcpy(_buffer + _bufferLen, data + (len - left), left); _bufferLen += left; if(_bufferLen == remaining()){ //we are at the end of the update, so should write what's left to flash if(!_writeBuffer()){ return len - left; } } return len; } size_t UpdaterClass::writeStream(Stream &data) { size_t written = 0; size_t toRead = 0; if(hasError() || !isRunning()) return 0; while(remaining()) { toRead = data.readBytes(_buffer + _bufferLen, (FLASH_SECTOR_SIZE - _bufferLen)); if(toRead == 0) { //Timeout delay(100); toRead = data.readBytes(_buffer + _bufferLen, (FLASH_SECTOR_SIZE - _bufferLen)); if(toRead == 0) { //Timeout _error = UPDATE_ERROR_STREAM; _currentAddress = (_startAddress + _size); #ifdef DEBUG_UPDATER printError(DEBUG_UPDATER); #endif } return written; } _bufferLen += toRead; if((_bufferLen == remaining() || _bufferLen == FLASH_SECTOR_SIZE) && !_writeBuffer()) return written; written += toRead; yield(); } return written; } void UpdaterClass::printError(Stream &out){ out.printf("ERROR[%u]: ", _error); if(_error == UPDATE_ERROR_OK){ out.println("No Error"); } else if(_error == UPDATE_ERROR_WRITE){ out.println("Flash Write Failed"); } else if(_error == UPDATE_ERROR_ERASE){ out.println("Flash Erase Failed"); } else if(_error == UPDATE_ERROR_SPACE){ out.println("Not Enough Space"); } else if(_error == UPDATE_ERROR_SIZE){ out.println("Bad Size Given"); } else if(_error == UPDATE_ERROR_STREAM){ out.println("Stream Read Timeout"); } else if(_error == UPDATE_ERROR_MD5){ out.println("MD5 Check Failed"); } else if(_error == UPDATE_ERROR_FLASH_CONFIG){ out.printf("Flash config wrong real: %d IDE: %d\n", ESP.getFlashChipRealSize(), ESP.getFlashChipSize()); } else { out.println("UNKNOWN"); } } UpdaterClass Update;
#include "Updater.h" #include "Arduino.h" #include "eboot_command.h" #include "interrupts.h" //#define DEBUG_UPDATER Serial extern "C" { #include "c_types.h" #include "spi_flash.h" #include "user_interface.h" } extern "C" uint32_t _SPIFFS_start; UpdaterClass::UpdaterClass() : _error(0) , _buffer(0) , _bufferLen(0) , _size(0) , _startAddress(0) , _currentAddress(0) , _command(U_FLASH) { } void UpdaterClass::_reset() { if (_buffer) delete[] _buffer; _buffer = 0; _bufferLen = 0; _startAddress = 0; _currentAddress = 0; _size = 0; _command = U_FLASH; } bool UpdaterClass::begin(size_t size, int command) { if(_size > 0){ #ifdef DEBUG_UPDATER DEBUG_UPDATER.println("[begin] already running"); #endif return false; } #ifdef DEBUG_UPDATER if (command == U_SPIFFS) { DEBUG_UPDATER.println("[begin] Update SPIFFS."); } #endif if(size == 0) { _error = UPDATE_ERROR_SIZE; #ifdef DEBUG_UPDATER printError(DEBUG_UPDATER); #endif return false; } if(!ESP.checkFlashConfig(false)) { _error = UPDATE_ERROR_FLASH_CONFIG; #ifdef DEBUG_UPDATER printError(DEBUG_UPDATER); #endif return false; } _reset(); _error = 0; wifi_set_sleep_type(NONE_SLEEP_T); uint32_t updateStartAddress = 0; if (command == U_FLASH) { //size of current sketch rounded to a sector uint32_t currentSketchSize = (ESP.getSketchSize() + FLASH_SECTOR_SIZE - 1) & (~(FLASH_SECTOR_SIZE - 1)); //address of the end of the space available for sketch and update uint32_t updateEndAddress = (uint32_t)&_SPIFFS_start - 0x40200000; //size of the update rounded to a sector uint32_t roundedSize = (size + FLASH_SECTOR_SIZE - 1) & (~(FLASH_SECTOR_SIZE - 1)); //address where we will start writing the update updateStartAddress = updateEndAddress - roundedSize; #ifdef DEBUG_UPDATER DEBUG_UPDATER.printf("[begin] roundedSize: 0x%08X (%d)\n", roundedSize, roundedSize); DEBUG_UPDATER.printf("[begin] updateEndAddress: 0x%08X (%d)\n", updateEndAddress, updateEndAddress); DEBUG_UPDATER.printf("[begin] currentSketchSize: 0x%08X (%d)\n", currentSketchSize, currentSketchSize); #endif //make sure that the size of both sketches is less than the total space (updateEndAddress) if(updateStartAddress < currentSketchSize) { _error = UPDATE_ERROR_SPACE; #ifdef DEBUG_UPDATER printError(DEBUG_UPDATER); #endif return false; } } else if (command == U_SPIFFS) { updateStartAddress = (uint32_t)&_SPIFFS_start - 0x40200000; } else { // unknown command #ifdef DEBUG_UPDATER DEBUG_UPDATER.println("[begin] Unknown update command."); #endif return false; } //initialize _startAddress = updateStartAddress; _currentAddress = _startAddress; _size = size; _buffer = new uint8_t[FLASH_SECTOR_SIZE]; _command = command; #ifdef DEBUG_UPDATER DEBUG_UPDATER.printf("[begin] _startAddress: 0x%08X (%d)\n", _startAddress, _startAddress); DEBUG_UPDATER.printf("[begin] _currentAddress: 0x%08X (%d)\n", _currentAddress, _currentAddress); DEBUG_UPDATER.printf("[begin] _size: 0x%08X (%d)\n", _size, _size); #endif _md5.begin(); return true; } bool UpdaterClass::setMD5(const char * expected_md5){ if(strlen(expected_md5) != 32) { return false; } _target_md5 = expected_md5; return true; } bool UpdaterClass::end(bool evenIfRemaining){ if(_size == 0){ #ifdef DEBUG_UPDATER DEBUG_UPDATER.println("no update"); #endif return false; } if(hasError() || (!isFinished() && !evenIfRemaining)){ #ifdef DEBUG_UPDATER DEBUG_UPDATER.printf("premature end: res:%u, pos:%u/%u\n", getError(), progress(), _size); #endif _reset(); return false; } if(evenIfRemaining) { if(_bufferLen > 0) { _writeBuffer(); } _size = progress(); } _md5.calculate(); if(_target_md5.length()) { if(_target_md5 != _md5.toString()){ _error = UPDATE_ERROR_MD5; #ifdef DEBUG_UPDATER DEBUG_UPDATER.printf("MD5 Failed: expected:%s, calculated:%s\n", _target_md5.c_str(), _md5.toString().c_str()); #endif _reset(); return false; } #ifdef DEBUG_UPDATER else DEBUG_UPDATER.printf("MD5 Success: %s\n", _target_md5.c_str()); #endif } if (_command == U_FLASH) { eboot_command ebcmd; ebcmd.action = ACTION_COPY_RAW; ebcmd.args[0] = _startAddress; ebcmd.args[1] = 0x00000; ebcmd.args[2] = _size; eboot_command_write(&ebcmd); #ifdef DEBUG_UPDATER DEBUG_UPDATER.printf("Staged: address:0x%08X, size:0x%08X\n", _startAddress, _size); } else if (_command == U_SPIFFS) { DEBUG_UPDATER.printf("SPIFFS: address:0x%08X, size:0x%08X\n", _startAddress, _size); #endif } _reset(); return true; } bool UpdaterClass::_writeBuffer(){ yield(); bool result = ESP.flashEraseSector(_currentAddress/FLASH_SECTOR_SIZE); yield(); if (result) { result = ESP.flashWrite(_currentAddress, (uint32_t*) _buffer, _bufferLen); } yield(); if (!result) { _error = UPDATE_ERROR_WRITE; _currentAddress = (_startAddress + _size); #ifdef DEBUG_UPDATER printError(DEBUG_UPDATER); #endif return false; } _md5.add(_buffer, _bufferLen); _currentAddress += _bufferLen; _bufferLen = 0; return true; } size_t UpdaterClass::write(uint8_t *data, size_t len) { size_t left = len; if(hasError() || !isRunning()) return 0; if(len > remaining()) len = remaining(); while((_bufferLen + left) > FLASH_SECTOR_SIZE) { size_t toBuff = FLASH_SECTOR_SIZE - _bufferLen; memcpy(_buffer + _bufferLen, data + (len - left), toBuff); _bufferLen += toBuff; if(!_writeBuffer()){ return len - left; } left -= toBuff; yield(); } //lets see whats left memcpy(_buffer + _bufferLen, data + (len - left), left); _bufferLen += left; if(_bufferLen == remaining()){ //we are at the end of the update, so should write what's left to flash if(!_writeBuffer()){ return len - left; } } return len; } size_t UpdaterClass::writeStream(Stream &data) { size_t written = 0; size_t toRead = 0; if(hasError() || !isRunning()) return 0; while(remaining()) { toRead = data.readBytes(_buffer + _bufferLen, (FLASH_SECTOR_SIZE - _bufferLen)); if(toRead == 0) { //Timeout delay(100); toRead = data.readBytes(_buffer + _bufferLen, (FLASH_SECTOR_SIZE - _bufferLen)); if(toRead == 0) { //Timeout _error = UPDATE_ERROR_STREAM; _currentAddress = (_startAddress + _size); #ifdef DEBUG_UPDATER printError(DEBUG_UPDATER); #endif } return written; } _bufferLen += toRead; if((_bufferLen == remaining() || _bufferLen == FLASH_SECTOR_SIZE) && !_writeBuffer()) return written; written += toRead; yield(); } return written; } void UpdaterClass::printError(Stream &out){ out.printf("ERROR[%u]: ", _error); if(_error == UPDATE_ERROR_OK){ out.println("No Error"); } else if(_error == UPDATE_ERROR_WRITE){ out.println("Flash Write Failed"); } else if(_error == UPDATE_ERROR_ERASE){ out.println("Flash Erase Failed"); } else if(_error == UPDATE_ERROR_SPACE){ out.println("Not Enough Space"); } else if(_error == UPDATE_ERROR_SIZE){ out.println("Bad Size Given"); } else if(_error == UPDATE_ERROR_STREAM){ out.println("Stream Read Timeout"); } else if(_error == UPDATE_ERROR_MD5){ out.println("MD5 Check Failed"); } else if(_error == UPDATE_ERROR_FLASH_CONFIG){ out.printf("Flash config wrong real: %d IDE: %d\n", ESP.getFlashChipRealSize(), ESP.getFlashChipSize()); } else { out.println("UNKNOWN"); } } UpdaterClass Update;
add missing ! for the checkFlashConfig call
add missing ! for the checkFlashConfig call
C++
lgpl-2.1
NextDevBoard/Arduino,jes/Arduino,me-no-dev/Arduino,martinayotte/ESP8266-Arduino,NullMedia/Arduino,me-no-dev/Arduino,Lan-Hekary/Arduino,jes/Arduino,Juppit/Arduino,gguuss/Arduino,NullMedia/Arduino,Lan-Hekary/Arduino,hallard/Arduino,gguuss/Arduino,martinayotte/ESP8266-Arduino,hallard/Arduino,wemos/Arduino,KaloNK/Arduino,lrmoreno007/Arduino,NullMedia/Arduino,quertenmont/Arduino,Links2004/Arduino,jes/Arduino,NullMedia/Arduino,me-no-dev/Arduino,wemos/Arduino,sticilface/Arduino,Links2004/Arduino,wemos/Arduino,quertenmont/Arduino,sticilface/Arduino,gguuss/Arduino,esp8266/Arduino,hallard/Arduino,me-no-dev/Arduino,toastedcode/esp8266-Arduino,lrmoreno007/Arduino,jes/Arduino,Lan-Hekary/Arduino,Juppit/Arduino,hallard/Arduino,Lan-Hekary/Arduino,toastedcode/esp8266-Arduino,martinayotte/ESP8266-Arduino,quertenmont/Arduino,lrmoreno007/Arduino,martinayotte/ESP8266-Arduino,lrmoreno007/Arduino,Links2004/Arduino,Juppit/Arduino,Lan-Hekary/Arduino,NextDevBoard/Arduino,quertenmont/Arduino,wemos/Arduino,jes/Arduino,esp8266/Arduino,Juppit/Arduino,Links2004/Arduino,Adam5Wu/Arduino,toastedcode/esp8266-Arduino,gguuss/Arduino,Adam5Wu/Arduino,martinayotte/ESP8266-Arduino,hallard/Arduino,esp8266/Arduino,KaloNK/Arduino,NextDevBoard/Arduino,gguuss/Arduino,KaloNK/Arduino,wemos/Arduino,NullMedia/Arduino,sticilface/Arduino,Juppit/Arduino,esp8266/Arduino,Links2004/Arduino,toastedcode/esp8266-Arduino,sticilface/Arduino,me-no-dev/Arduino,toastedcode/esp8266-Arduino,KaloNK/Arduino,NextDevBoard/Arduino,quertenmont/Arduino,sticilface/Arduino,KaloNK/Arduino,esp8266/Arduino,Adam5Wu/Arduino,NextDevBoard/Arduino,Adam5Wu/Arduino,Adam5Wu/Arduino,lrmoreno007/Arduino
8b0603fa65c87d8fe51ed2f2ed546bf04da0987f
copasi/trajectory/CTrajectory.cpp
copasi/trajectory/CTrajectory.cpp
/** * File name: CTrajactory.cpp * * Research Programmer: Yongqun He * Contact email: [email protected] * Purpose: This is the .cpp file for the class CTrajectory. * It is to solve the trajectory time course problem of copasi */ #include "copasi.h" #include "CTrajectory.h" //default constructor CTrajectory::CTrajectory() { mPoints = 0; mEndTime = 0.0; mN = 0; mMethod = 0; mY = NULL; mModel = NULL; mODESolver = NULL; } //Constructor CTrajectory::CTrajectory(CModel * aModel, C_INT32 aPoints, C_FLOAT64 aEndTime, C_INT32 aMethod) { mPoints = aPoints; mEndTime = aEndTime; mMethod = aMethod; mN = 0; mY = NULL; mModel = NULL; mODESolver = NULL; initialize(aModel); } // Object assignment overloading, CTrajectory & CTrajectory::operator = (const CTrajectory& source) { cleanup(); if(this != &source) { mMethod = source.mMethod; mPoints = source.mPoints; mEndTime = source.mEndTime; } initialize(source.mModel); return *this; } //destructor CTrajectory::~CTrajectory() { cout << "~CTrajectory " << endl; } void CTrajectory::initialize(CModel * aModel) { cleanup(); // we really need a copy of the model here mModel = aModel; mN = mModel->getIndMetab(); mY = mModel->getInitialNumbers(); switch (mMethod) { case 1: mODESolver = new CODESolver(); mODESolver->initialize(* mModel, mY, mN, mMethod); break; default: fatalError(); } return; } void CTrajectory::cleanup() { if (mY) delete [] mY; mY = NULL; //if (mModel) delete mModel; mModel = NULL; if (mODESolver) { mODESolver->cleanup(); delete mODESolver; } mODESolver = NULL; return; } C_INT32 CTrajectory::load(CReadConfig & configbuffer) { C_INT32 Fail = 0; if((Fail = configbuffer.getVariable("EndTime", "C_FLOAT64", (void *) &mEndTime, CReadConfig::LOOP))) return Fail; if((Fail = configbuffer.getVariable("Points", "C_INT32", (void *) &mPoints))) return Fail; return Fail; } C_INT32 CTrajectory::save(CWriteConfig & configbuffer) { C_INT32 Fail = 0; if((Fail = configbuffer.setVariable("EndTime", "C_FLOAT64", (void *) &mEndTime))) return Fail; if((Fail = configbuffer.setVariable("Points", "C_FLOAT64", (void *) &mPoints))) return Fail; return Fail; } void CTrajectory::setModel(CModel * aModel) { mModel = aModel; } CModel * CTrajectory::getModel() const { return mModel; } void CTrajectory::setODESolver(CODESolver * aSolver) { mODESolver = aSolver; } CODESolver * CTrajectory::getODESolver() const { return mODESolver; } void CTrajectory::setPoints(const C_INT32 anInt) { mPoints = anInt; } C_INT32 CTrajectory::getPoints() const { return mPoints; } void CTrajectory::setArrSize(const C_INT32 anInt) { mN = anInt; } C_INT32 CTrajectory::getArrSize() const { return mN; } void CTrajectory::setEndTime(const C_FLOAT64 aDouble) { mEndTime = aDouble; } const C_FLOAT64 & CTrajectory::getEndTime() const { return mEndTime; } const C_FLOAT64 & CTrajectory::getTime() const { return mTime; } void CTrajectory::setMethod(const C_INT32 anInt) { mMethod = anInt; } C_INT32 CTrajectory::getMethod() const { return mMethod; } void CTrajectory::process() { // mODESolver->initialize(* mModel, mY, mN, mMethod); // COutputEvent *OutInit = NULL, *OutPoint = NULL, *OutEnd = NULL; // mOutInit = COutputEvent(TIME_INIT, this); // mOutPoint = COutputEvent(TIME_POINT, this); // mOutEnd = COutputEvent(TIME_END, this); //calculates number of iterations and time intervals C_FLOAT64 length = mEndTime/mPoints; mTime = 0.0; // print for the initial time point // if (mOutInit) mOutInit->Print(); // if (mOutPoint) mOutPoint->Print(); for(C_INT32 i = 0; i < mPoints; i++) { //update the CODESolver from current time to end time cout << mTime << " "; mODESolver->step(mTime, mTime+length); //update CModel mModel->setConcentrations(mY); //print for current time point in the outputEvent // if (OutPoint) OutPoint.Print(); mTime += length; } // if (OutEnd) OutEnd.Print(); // delete OutInit; -> to cleanup // delete OutPoint; // delete OutEnd; // mODESolver->cleanup(); }
/** * File name: CTrajactory.cpp * * Research Programmer: Yongqun He * Contact email: [email protected] * Purpose: This is the .cpp file for the class CTrajectory. * It is to solve the trajectory time course problem of copasi */ #include "copasi.h" #include "CTrajectory.h" //default constructor CTrajectory::CTrajectory() { mPoints = 0; mEndTime = 0.0; mN = 0; mMethod = 0; mY = NULL; mModel = NULL; mODESolver = NULL; } //Constructor CTrajectory::CTrajectory(CModel * aModel, C_INT32 aPoints, C_FLOAT64 aEndTime, C_INT32 aMethod) { mPoints = aPoints; mEndTime = aEndTime; mMethod = aMethod; mN = 0; mY = NULL; mModel = NULL; mODESolver = NULL; initialize(aModel); } // Object assignment overloading, CTrajectory & CTrajectory::operator = (const CTrajectory& source) { cleanup(); if(this != &source) { mMethod = source.mMethod; mPoints = source.mPoints; mEndTime = source.mEndTime; } initialize(source.mModel); return *this; } //destructor CTrajectory::~CTrajectory() { cout << "~CTrajectory " << endl; } void CTrajectory::initialize(CModel * aModel) { cleanup(); // we really need a copy of the model here mModel = aModel; mN = mModel->getIndMetab(); mY = mModel->getInitialNumbers(); switch (mMethod) { case 1: mODESolver = new CODESolver(); mODESolver->initialize(* mModel, mY, mN, mMethod); break; default: fatalError(); } return; } void CTrajectory::cleanup() { if (mY) delete [] mY; mY = NULL; //if (mModel) delete mModel; mModel = NULL; if (mODESolver) { mODESolver->cleanup(); delete mODESolver; } mODESolver = NULL; return; } C_INT32 CTrajectory::load(CReadConfig & configbuffer) { C_INT32 Fail = 0; if((Fail = configbuffer.getVariable("EndTime", "C_FLOAT64", (void *) &mEndTime, CReadConfig::LOOP))) return Fail; if((Fail = configbuffer.getVariable("Points", "C_INT32", (void *) &mPoints))) return Fail; return Fail; } C_INT32 CTrajectory::save(CWriteConfig & configbuffer) { C_INT32 Fail = 0; if((Fail = configbuffer.setVariable("EndTime", "C_FLOAT64", (void *) &mEndTime))) return Fail; if((Fail = configbuffer.setVariable("Points", "C_FLOAT64", (void *) &mPoints))) return Fail; return Fail; } void CTrajectory::setModel(CModel * aModel) { mModel = aModel; } CModel * CTrajectory::getModel() const { return mModel; } void CTrajectory::setODESolver(CODESolver * aSolver) { mODESolver = aSolver; } CODESolver * CTrajectory::getODESolver() const { return mODESolver; } void CTrajectory::setPoints(const C_INT32 anInt) { mPoints = anInt; } C_INT32 CTrajectory::getPoints() const { return mPoints; } void CTrajectory::setArrSize(const C_INT32 anInt) { mN = anInt; } C_INT32 CTrajectory::getArrSize() const { return mN; } //calculate the time lenghth C_FLOAT64 CTrajectory::calcTimeLength() { return mEndTime/mPoints; } void CTrajectory::setEndTime(const C_FLOAT64 aDouble) { mEndTime = aDouble; } const C_FLOAT64 & CTrajectory::getEndTime() const { return mEndTime; } const C_FLOAT64 & CTrajectory::getTime() const { return mTime; } void CTrajectory::setMethod(const C_INT32 anInt) { mMethod = anInt; } C_INT32 CTrajectory::getMethod() const { return mMethod; } void CTrajectory::process() { // mODESolver->initialize(* mModel, mY, mN, mMethod); // COutputEvent *OutInit = NULL, *OutPoint = NULL, *OutEnd = NULL; // mOutInit = COutputEvent(TIME_INIT, this); // mOutPoint = COutputEvent(TIME_POINT, this); // mOutEnd = COutputEvent(TIME_END, this); //calculates number of iterations and time intervals C_FLOAT64 length = mEndTime/mPoints; mTime = 0.0; // print for the initial time point // if (mOutInit) mOutInit->Print(); // if (mOutPoint) mOutPoint->Print(); for(C_INT32 i = 0; i < mPoints; i++) { //update the CODESolver from current time to end time cout << mTime << " "; mODESolver->step(mTime, mTime+length); //update CModel mModel->setConcentrations(mY); //print for current time point in the outputEvent // if (OutPoint) OutPoint.Print(); mTime += length; } // if (OutEnd) OutEnd.Print(); // delete OutInit; -> to cleanup // delete OutPoint; // delete OutEnd; // mODESolver->cleanup(); }
add calcTimeLength() for CSS_Solution
add calcTimeLength() for CSS_Solution
C++
artistic-2.0
copasi/COPASI,copasi/COPASI,copasi/COPASI,jonasfoe/COPASI,jonasfoe/COPASI,jonasfoe/COPASI,copasi/COPASI,copasi/COPASI,jonasfoe/COPASI,jonasfoe/COPASI,copasi/COPASI,copasi/COPASI,jonasfoe/COPASI,jonasfoe/COPASI,jonasfoe/COPASI,copasi/COPASI,copasi/COPASI,jonasfoe/COPASI
3b2557ad4b7ac2a72c1c814dab6029ca938560d7
Modules/Applications/AppClassification/app/otbZonalStatistics.cxx
Modules/Applications/AppClassification/app/otbZonalStatistics.cxx
/* * Copyright (C) 2017 National Research Institute of Science and * Technology for Environment and Agriculture (IRSTEA) * * 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. */ #include "itkFixedArray.h" #include "itkObjectFactory.h" // Elevation handler #include "otbWrapperElevationParametersHandler.h" #include "otbWrapperApplicationFactory.h" // Application engine #include "otbStandardFilterWatcher.h" // Process objects #include "otbVectorDataToLabelImageFilter.h" #include "otbVectorDataIntoImageProjectionFilter.h" #include "otbStreamingStatisticsMapFromLabelImageFilter.h" #include "otbStatisticsXMLFileWriter.h" namespace otb { namespace Wrapper { class ZonalStatistics : public Application { public: /** Standard class typedefs. */ typedef ZonalStatistics Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; /* Typedefs */ typedef Int32ImageType LabelImageType; typedef LabelImageType::ValueType LabelValueType; typedef otb::VectorData<double, 2> VectorDataType; typedef otb::VectorDataIntoImageProjectionFilter<VectorDataType, FloatVectorImageType> VectorDataReprojFilterType; typedef otb::VectorDataToLabelImageFilter<VectorDataType, LabelImageType> RasterizeFilterType; typedef VectorDataType::DataTreeType DataTreeType; typedef itk::PreOrderTreeIterator<DataTreeType> TreeIteratorType; typedef VectorDataType::DataNodeType DataNodeType; typedef DataNodeType::PolygonListPointerType PolygonListPointerType; typedef otb::StreamingStatisticsMapFromLabelImageFilter<FloatVectorImageType, LabelImageType> StatsFilterType; typedef otb::StatisticsXMLFileWriter<FloatVectorImageType::PixelType> StatsWriterType; /** Standard macro */ itkNewMacro(Self); itkTypeMacro(ZonalStatistics, Application); void DoInit() { SetName("ZonalStatistics"); SetDescription("This application computes zonal statistics"); // Documentation SetDocName("ZonalStatistics"); SetDocLongDescription("This application computes zonal statistics from label image, or vector data. " "The application inputs one input multiband image, and a label input. " "If the label input is a raster, the output statistics are exported in a XML file. If the label " "input is a vector data, the output statistics are exported in a new vector data with statistics " "in the attribute table. The computed statistics are mean, min, max, and standard deviation."); SetDocLimitations("The shapefile must fit in memory"); SetDocAuthors("Remi Cresson"); AddDocTag(Tags::Manip); AddDocTag(Tags::Analysis); // Input image AddParameter(ParameterType_InputImage, "in", "Input Image"); // Processing mode AddParameter(ParameterType_Choice, "mode", "Processing mode"); AddChoice("mode.vector", "Input objects from vector data"); AddChoice("mode.labelimage", "Input objects from label image"); // Input for vector mode AddParameter(ParameterType_InputVectorData, "mode.vector.in", "Input vector data"); AddParameter(ParameterType_Bool, "mode.vector.reproject", "Reproject the input vector"); AddParameter(ParameterType_OutputVectorData, "mode.vector.out", "Output vector data"); // Input for label image mode AddParameter(ParameterType_InputImage, "mode.labelimage.in", "Input label image"); AddParameter(ParameterType_Int, "mode.labelimage.nodata", "No-data value for the input label image"); SetDefaultParameterInt ("mode.labelimage.nodata", 0); MandatoryOff ("mode.labelimage.nodata"); AddParameter(ParameterType_InputImage, "mode.labelimage.outxml", "Output XML file"); AddRAMParameter(); // Doc example parameter settings SetDocExampleParameterValue("in", "input.tif"); SetDocExampleParameterValue("mode.vector.in", "myvector.shp"); SetDocExampleParameterValue("mode.vector.out", "myvector_with_stats.shp"); } void DoUpdateParameters() { // Nothing to do here : all parameters are independent } // Returns a string of the kind "prefix_i" const std::string CreateFieldName(const std::string & prefix, const unsigned int i) { std::stringstream ss; ss << prefix << "_" << i; return ss.str(); } // Returns a null pixel which has the same number of components per pixels as img FloatVectorImageType::PixelType NullPixel(FloatVectorImageType::Pointer & img) { const unsigned int nBands = img->GetNumberOfComponentsPerPixel(); FloatVectorImageType::PixelType pix; pix.SetSize(nBands); pix.Fill(0); return pix; } void DoExecute() { // Get input image FloatVectorImageType::Pointer img = GetParameterImage("in"); // Statistics filter m_StatsFilter = StatsFilterType::New(); m_StatsFilter->SetInput(img); m_StatsFilter->GetStreamer()->SetAutomaticAdaptativeStreaming(GetParameterInt("ram")); AddProcess(m_StatsFilter->GetStreamer(), "Computing statistics"); // Select mode if (GetParameterAsString("mode") == "vector") { otbAppLogINFO("Processing mode: vector"); otbAppLogINFO("Loading vector data..."); VectorDataType* shp = GetParameterVectorData("mode.vector.in"); // Reproject vector data if (GetParameterInt("mode.vector.reproject") != 0) { otbAppLogINFO("Vector data reprojection enabled"); m_VectorDataReprojectionFilter = VectorDataReprojFilterType::New(); m_VectorDataReprojectionFilter->SetInputVectorData(shp); m_VectorDataReprojectionFilter->SetInputImage(img); AddProcess(m_VectorDataReprojectionFilter, "Reproject vector data"); m_VectorDataReprojectionFilter->Update(); m_VectorDataSrc = m_VectorDataReprojectionFilter->GetOutput(); } else { m_VectorDataSrc = shp; } // Internal no-data value const LabelValueType intNoData = itk::NumericTraits<LabelValueType>::max(); // Rasterize vector data m_RasterizeFilter = RasterizeFilterType::New(); m_RasterizeFilter->AddVectorData(m_VectorDataSrc); m_RasterizeFilter->SetOutputOrigin(img->GetOrigin()); m_RasterizeFilter->SetOutputSpacing(img->GetSignedSpacing()); m_RasterizeFilter->SetOutputSize(img->GetLargestPossibleRegion().GetSize()); m_RasterizeFilter->SetOutputProjectionRef(img->GetProjectionRef()); m_RasterizeFilter->SetBurnAttribute("________"); m_RasterizeFilter->SetDefaultBurnValue(intNoData); m_RasterizeFilter->SetGlobalWarningDisplay(false); m_RasterizeFilter->SetBackgroundValue(intNoData); // Computing stats m_StatsFilter->SetInputLabelImage(m_RasterizeFilter->GetOutput()); m_StatsFilter->Update(); // Remove the no-data entry StatsFilterType::LabelPopulationMapType countMap = m_StatsFilter->GetLabelPopulationMap(); StatsFilterType::PixelValueMapType meanMap = m_StatsFilter->GetMeanValueMap(); StatsFilterType::PixelValueMapType stdMap = m_StatsFilter->GetStandardDeviationValueMap(); StatsFilterType::PixelValueMapType minMap = m_StatsFilter->GetMinValueMap(); StatsFilterType::PixelValueMapType maxMap = m_StatsFilter->GetMaxValueMap(); countMap.erase(intNoData); meanMap.erase(intNoData); stdMap.erase(intNoData); minMap.erase(intNoData); maxMap.erase(intNoData); // Add a statistics fields otbAppLogINFO("Writing output vector data"); LabelValueType internalFID = 0; m_NewVectorData = VectorDataType::New(); DataNodeType::Pointer root = m_NewVectorData->GetDataTree()->GetRoot()->Get(); DataNodeType::Pointer document = DataNodeType::New(); document->SetNodeType(otb::DOCUMENT); m_NewVectorData->GetDataTree()->Add(document, root); DataNodeType::Pointer folder = DataNodeType::New(); folder->SetNodeType(otb::FOLDER); m_NewVectorData->GetDataTree()->Add(folder, document); m_NewVectorData->SetProjectionRef(m_VectorDataSrc->GetProjectionRef()); TreeIteratorType itVector(m_VectorDataSrc->GetDataTree()); itVector.GoToBegin(); while (!itVector.IsAtEnd()) { if (!itVector.Get()->IsRoot() && !itVector.Get()->IsDocument() && !itVector.Get()->IsFolder()) { DataNodeType::Pointer currentGeometry = itVector.Get(); // Add the geometry with the new fields if (countMap.count(internalFID) > 0) { currentGeometry->SetFieldAsDouble("count", countMap[internalFID] ); for (unsigned int band = 0 ; band < img->GetNumberOfComponentsPerPixel() ; band++) { currentGeometry->SetFieldAsDouble(CreateFieldName("mean", band), meanMap[internalFID][band] ); currentGeometry->SetFieldAsDouble(CreateFieldName("stdev", band), stdMap [internalFID][band] ); currentGeometry->SetFieldAsDouble(CreateFieldName("min", band), minMap [internalFID][band] ); currentGeometry->SetFieldAsDouble(CreateFieldName("max", band), maxMap [internalFID][band] ); } m_NewVectorData->GetDataTree()->Add(currentGeometry, folder); } internalFID++; } ++itVector; } // next feature SetParameterOutputVectorData("mode.vector.out", m_NewVectorData); } else if (GetParameterAsString("mode") == "labelimage") { otbAppLogINFO("Processing mode: label image"); // Computing stats m_StatsFilter->SetInputLabelImage(GetParameterInt32Image("mode.labelimage.in")); m_StatsFilter->Update(); // Remove the no-data entry StatsFilterType::LabelPopulationMapType countMap = m_StatsFilter->GetLabelPopulationMap(); StatsFilterType::PixelValueMapType meanMap = m_StatsFilter->GetMeanValueMap(); StatsFilterType::PixelValueMapType stdMap = m_StatsFilter->GetStandardDeviationValueMap(); StatsFilterType::PixelValueMapType minMap = m_StatsFilter->GetMinValueMap(); StatsFilterType::PixelValueMapType maxMap = m_StatsFilter->GetMaxValueMap(); if (HasUserValue("mode.labelimage.nodata")) { // Internal no-data value const LabelValueType intNoData = GetParameterInt("mode.labelimage.nodata"); otbAppLogINFO("Using no-data value: " << intNoData); countMap.erase(intNoData); meanMap.erase(intNoData); stdMap.erase(intNoData); minMap.erase(intNoData); maxMap.erase(intNoData); } // Write stats const std::string outXMLFile = this->GetParameterString("mode.labelimage.outxml"); otbAppLogINFO("Writing " + outXMLFile) StatsWriterType::Pointer statWriter = StatsWriterType::New(); statWriter->SetFileName(outXMLFile); statWriter->AddInputMap<StatsFilterType::LabelPopulationMapType>("count",countMap); statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("mean",meanMap); statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("std",stdMap); statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("min",minMap); statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("max",maxMap); statWriter->Update(); } else { otbAppLogFATAL("Unknow processing mode"); } } VectorDataType::Pointer m_VectorDataSrc; VectorDataType::Pointer m_NewVectorData; VectorDataReprojFilterType::Pointer m_VectorDataReprojectionFilter; RasterizeFilterType::Pointer m_RasterizeFilter; StatsFilterType::Pointer m_StatsFilter; }; } } OTB_APPLICATION_EXPORT( otb::Wrapper::ZonalStatistics )
/* * Copyright (C) 2017 National Research Institute of Science and * Technology for Environment and Agriculture (IRSTEA) * * 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. */ #include "itkFixedArray.h" #include "itkObjectFactory.h" // Elevation handler #include "otbWrapperElevationParametersHandler.h" #include "otbWrapperApplicationFactory.h" // Application engine #include "otbStandardFilterWatcher.h" // Process objects #include "otbVectorDataToLabelImageFilter.h" #include "otbVectorDataIntoImageProjectionFilter.h" #include "otbStreamingStatisticsMapFromLabelImageFilter.h" #include "otbStatisticsXMLFileWriter.h" namespace otb { namespace Wrapper { class ZonalStatistics : public Application { public: /** Standard class typedefs. */ typedef ZonalStatistics Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; /* Typedefs */ typedef Int32ImageType LabelImageType; typedef LabelImageType::ValueType LabelValueType; typedef otb::VectorData<double, 2> VectorDataType; typedef otb::VectorDataIntoImageProjectionFilter<VectorDataType, FloatVectorImageType> VectorDataReprojFilterType; typedef otb::VectorDataToLabelImageFilter<VectorDataType, LabelImageType> RasterizeFilterType; typedef VectorDataType::DataTreeType DataTreeType; typedef itk::PreOrderTreeIterator<DataTreeType> TreeIteratorType; typedef VectorDataType::DataNodeType DataNodeType; typedef DataNodeType::PolygonListPointerType PolygonListPointerType; typedef otb::StreamingStatisticsMapFromLabelImageFilter<FloatVectorImageType, LabelImageType> StatsFilterType; typedef otb::StatisticsXMLFileWriter<FloatVectorImageType::PixelType> StatsWriterType; /** Standard macro */ itkNewMacro(Self); itkTypeMacro(ZonalStatistics, Application); void DoInit() { SetName("ZonalStatistics"); SetDescription("This application computes zonal statistics"); // Documentation SetDocName("ZonalStatistics"); SetDocLongDescription("This application computes zonal statistics from label image, or vector data. " "The application inputs one input multiband image, and a label input. " "If the label input is a raster, the output statistics are exported in a XML file. If the label " "input is a vector data, the output statistics are exported in a new vector data with statistics " "in the attribute table. The computed statistics are mean, min, max, and standard deviation."); SetDocLimitations("The shapefile must fit in memory"); SetDocAuthors("Remi Cresson"); AddDocTag(Tags::Manip); AddDocTag(Tags::Analysis); // Input image AddParameter(ParameterType_InputImage, "in", "Input Image"); // Processing mode AddParameter(ParameterType_Choice, "mode", "Processing mode"); AddChoice("mode.vector", "Input objects from vector data"); AddChoice("mode.labelimage", "Input objects from label image"); // Input for vector mode AddParameter(ParameterType_InputVectorData, "mode.vector.in", "Input vector data"); AddParameter(ParameterType_Bool, "mode.vector.reproject", "Reproject the input vector"); AddParameter(ParameterType_OutputVectorData, "mode.vector.out", "Output vector data"); // Input for label image mode AddParameter(ParameterType_InputImage, "mode.labelimage.in", "Input label image"); AddParameter(ParameterType_Int, "mode.labelimage.nodata", "No-data value for the input label image"); SetDefaultParameterInt ("mode.labelimage.nodata", 0); MandatoryOff ("mode.labelimage.nodata"); AddParameter(ParameterType_InputImage, "mode.labelimage.outxml", "Output XML file"); AddRAMParameter(); // Doc example parameter settings SetDocExampleParameterValue("in", "input.tif"); SetDocExampleParameterValue("mode.vector.in", "myvector.shp"); SetDocExampleParameterValue("mode.vector.out", "myvector_with_stats.shp"); } void DoUpdateParameters() { // Nothing to do here : all parameters are independent } // Returns a string of the kind "prefix_i" const std::string CreateFieldName(const std::string & prefix, const unsigned int i) { std::stringstream ss; ss << prefix << "_" << i; return ss.str(); } // Returns a null pixel which has the same number of components per pixels as img FloatVectorImageType::PixelType NullPixel(FloatVectorImageType::Pointer & img) { const unsigned int nBands = img->GetNumberOfComponentsPerPixel(); FloatVectorImageType::PixelType pix; pix.SetSize(nBands); pix.Fill(0); return pix; } void DoExecute() { // Get input image FloatVectorImageType::Pointer img = GetParameterImage("in"); // Statistics filter m_StatsFilter = StatsFilterType::New(); m_StatsFilter->SetInput(img); m_StatsFilter->GetStreamer()->SetAutomaticAdaptativeStreaming(GetParameterInt("ram")); AddProcess(m_StatsFilter->GetStreamer(), "Computing statistics"); // Select mode if (GetParameterAsString("mode") == "vector") { otbAppLogINFO("Processing mode: vector"); otbAppLogINFO("Loading vector data..."); VectorDataType* shp = GetParameterVectorData("mode.vector.in"); // Reproject vector data if (GetParameterInt("mode.vector.reproject") != 0) { otbAppLogINFO("Vector data reprojection enabled"); m_VectorDataReprojectionFilter = VectorDataReprojFilterType::New(); m_VectorDataReprojectionFilter->SetInputVectorData(shp); m_VectorDataReprojectionFilter->SetInputImage(img); AddProcess(m_VectorDataReprojectionFilter, "Reproject vector data"); m_VectorDataReprojectionFilter->Update(); m_VectorDataSrc = m_VectorDataReprojectionFilter->GetOutput(); } else { m_VectorDataSrc = shp; } // Internal no-data value const LabelValueType intNoData = itk::NumericTraits<LabelValueType>::max(); // Rasterize vector data m_RasterizeFilter = RasterizeFilterType::New(); m_RasterizeFilter->AddVectorData(m_VectorDataSrc); m_RasterizeFilter->SetOutputOrigin(img->GetOrigin()); m_RasterizeFilter->SetOutputSpacing(img->GetSignedSpacing()); m_RasterizeFilter->SetOutputSize(img->GetLargestPossibleRegion().GetSize()); m_RasterizeFilter->SetOutputProjectionRef(img->GetProjectionRef()); m_RasterizeFilter->SetBurnAttribute("________"); m_RasterizeFilter->SetDefaultBurnValue(0); m_RasterizeFilter->SetGlobalWarningDisplay(false); m_RasterizeFilter->SetBackgroundValue(intNoData); // Computing stats m_StatsFilter->SetInputLabelImage(m_RasterizeFilter->GetOutput()); m_StatsFilter->Update(); // Remove the no-data entry StatsFilterType::LabelPopulationMapType countMap = m_StatsFilter->GetLabelPopulationMap(); StatsFilterType::PixelValueMapType meanMap = m_StatsFilter->GetMeanValueMap(); StatsFilterType::PixelValueMapType stdMap = m_StatsFilter->GetStandardDeviationValueMap(); StatsFilterType::PixelValueMapType minMap = m_StatsFilter->GetMinValueMap(); StatsFilterType::PixelValueMapType maxMap = m_StatsFilter->GetMaxValueMap(); countMap.erase(intNoData); meanMap.erase(intNoData); stdMap.erase(intNoData); minMap.erase(intNoData); maxMap.erase(intNoData); // Add a statistics fields otbAppLogINFO("Writing output vector data"); LabelValueType internalFID = 0; m_NewVectorData = VectorDataType::New(); DataNodeType::Pointer root = m_NewVectorData->GetDataTree()->GetRoot()->Get(); DataNodeType::Pointer document = DataNodeType::New(); document->SetNodeType(otb::DOCUMENT); m_NewVectorData->GetDataTree()->Add(document, root); DataNodeType::Pointer folder = DataNodeType::New(); folder->SetNodeType(otb::FOLDER); m_NewVectorData->GetDataTree()->Add(folder, document); m_NewVectorData->SetProjectionRef(m_VectorDataSrc->GetProjectionRef()); TreeIteratorType itVector(m_VectorDataSrc->GetDataTree()); itVector.GoToBegin(); while (!itVector.IsAtEnd()) { if (!itVector.Get()->IsRoot() && !itVector.Get()->IsDocument() && !itVector.Get()->IsFolder()) { DataNodeType::Pointer currentGeometry = itVector.Get(); // Add the geometry with the new fields if (countMap.count(internalFID) > 0) { currentGeometry->SetFieldAsDouble("count", countMap[internalFID] ); for (unsigned int band = 0 ; band < img->GetNumberOfComponentsPerPixel() ; band++) { currentGeometry->SetFieldAsDouble(CreateFieldName("mean", band), meanMap[internalFID][band] ); currentGeometry->SetFieldAsDouble(CreateFieldName("stdev", band), stdMap [internalFID][band] ); currentGeometry->SetFieldAsDouble(CreateFieldName("min", band), minMap [internalFID][band] ); currentGeometry->SetFieldAsDouble(CreateFieldName("max", band), maxMap [internalFID][band] ); } m_NewVectorData->GetDataTree()->Add(currentGeometry, folder); } internalFID++; } ++itVector; } // next feature SetParameterOutputVectorData("mode.vector.out", m_NewVectorData); } else if (GetParameterAsString("mode") == "labelimage") { otbAppLogINFO("Processing mode: label image"); // Computing stats m_StatsFilter->SetInputLabelImage(GetParameterInt32Image("mode.labelimage.in")); m_StatsFilter->Update(); // Remove the no-data entry StatsFilterType::LabelPopulationMapType countMap = m_StatsFilter->GetLabelPopulationMap(); StatsFilterType::PixelValueMapType meanMap = m_StatsFilter->GetMeanValueMap(); StatsFilterType::PixelValueMapType stdMap = m_StatsFilter->GetStandardDeviationValueMap(); StatsFilterType::PixelValueMapType minMap = m_StatsFilter->GetMinValueMap(); StatsFilterType::PixelValueMapType maxMap = m_StatsFilter->GetMaxValueMap(); if (HasUserValue("mode.labelimage.nodata")) { // Internal no-data value const LabelValueType intNoData = GetParameterInt("mode.labelimage.nodata"); otbAppLogINFO("Using no-data value: " << intNoData); countMap.erase(intNoData); meanMap.erase(intNoData); stdMap.erase(intNoData); minMap.erase(intNoData); maxMap.erase(intNoData); } // Write stats const std::string outXMLFile = this->GetParameterString("mode.labelimage.outxml"); otbAppLogINFO("Writing " + outXMLFile) StatsWriterType::Pointer statWriter = StatsWriterType::New(); statWriter->SetFileName(outXMLFile); statWriter->AddInputMap<StatsFilterType::LabelPopulationMapType>("count",countMap); statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("mean",meanMap); statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("std",stdMap); statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("min",minMap); statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("max",maxMap); statWriter->Update(); } else { otbAppLogFATAL("Unknow processing mode"); } } VectorDataType::Pointer m_VectorDataSrc; VectorDataType::Pointer m_NewVectorData; VectorDataReprojFilterType::Pointer m_VectorDataReprojectionFilter; RasterizeFilterType::Pointer m_RasterizeFilter; StatsFilterType::Pointer m_StatsFilter; }; } } OTB_APPLICATION_EXPORT( otb::Wrapper::ZonalStatistics )
change first value of label to 0
ADD: change first value of label to 0
C++
apache-2.0
orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB
46f209f2ae8e24001ea4dbc5771a2fcb620d12af
websocket_server.cpp
websocket_server.cpp
/* * Copyright (c) 2017-2018 dresden elektronik ingenieurtechnik gmbh. * All rights reserved. * * The software in this package is published under the terms of the BSD * style license a copy of which has been included with this distribution in * the LICENSE.txt file. * */ #ifdef USE_WEBSOCKETS #include "deconz/dbg_trace.h" #include "deconz/util.h" #include "websocket_server.h" /*! Constructor. */ WebSocketServer::WebSocketServer(QObject *parent, quint16 port) : QObject(parent) { srv = new QWebSocketServer("deconz", QWebSocketServer::NonSecureMode, this); quint16 p = 0; quint16 ports[] = { 443, 443, 8080, 8088, 20877, 0 }; // start with proxy frinedly ports first, use random port as fallback if (port > 0) { ports[0] = port; } QHostAddress address; if (deCONZ::appArgumentString("--http-listen", QString()).isEmpty()) // Tie websocket server to specified IP, if any { address = QHostAddress::AnyIPv4; } else { address = deCONZ::appArgumentString("--http-listen", QString()); } while (!srv->listen(address, ports[p])) { if (ports[p] == 0) { DBG_Printf(DBG_ERROR, "Giveup starting websocket server on %s, port: %u. error: %s\n", qPrintable(address.toString()), ports[p], qPrintable(srv->errorString())); break; } DBG_Printf(DBG_ERROR, "Failed to start websocket server on %s, port: %u. error: %s\n", qPrintable(address.toString()), ports[p], qPrintable(srv->errorString())); p++; } if (srv->isListening()) { DBG_Printf(DBG_INFO, "Started websocket server on %s, port: %u\n", qPrintable(address.toString()), srv->serverPort()); connect(srv, SIGNAL(newConnection()), this, SLOT(onNewConnection())); } } /*! Returns the websocket server port. \return the active server port, or 0 if not active */ quint16 WebSocketServer::port() const { return srv->isListening() ? srv->serverPort() : 0; } /*! Handler for new client connections. */ void WebSocketServer::onNewConnection() { while (srv->hasPendingConnections()) { QWebSocket *sock = srv->nextPendingConnection(); DBG_Printf(DBG_INFO, "New websocket %s:%u (state: %d) \n", qPrintable(sock->peerAddress().toString()), sock->peerPort(), sock->state()); connect(sock, SIGNAL(disconnected()), this, SLOT(onSocketDisconnected())); connect(sock, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(onSocketError(QAbstractSocket::SocketError))); clients.push_back(sock); } } /*! Handle websocket disconnected signal. */ void WebSocketServer::onSocketDisconnected() { for (size_t i = 0; i < clients.size(); i++) { QWebSocket *sock = qobject_cast<QWebSocket*>(sender()); DBG_Assert(sock); if (sock && clients[i] == sock) { DBG_Printf(DBG_INFO, "Websocket disconnected %s:%u, state: %d, close-code: %d, reason: %s\n", qPrintable(sock->peerAddress().toString()), sock->peerPort(), sock->state(), sock->closeCode(), qPrintable(sock->closeReason())); sock->deleteLater(); clients[i] = clients.back(); clients.pop_back(); } } } /*! Handle websocket error signal. \param err - the error which occured */ void WebSocketServer::onSocketError(QAbstractSocket::SocketError err) { Q_UNUSED(err); for (size_t i = 0; i < clients.size(); i++) { QWebSocket *sock = qobject_cast<QWebSocket*>(sender()); DBG_Assert(sock); if (sock && clients[i] == sock) { DBG_Printf(DBG_INFO, "Remove websocket %s:%u after error %s, close-code: %d, reason: %s\n", qPrintable(sock->peerAddress().toString()), sock->peerPort(), qPrintable(sock->errorString()), sock->closeCode(), qPrintable(sock->closeReason())); sock->deleteLater(); clients[i] = clients.back(); clients.pop_back(); } } } /*! Broadcasts a message to all connected clients. \param msg the message as JSON string */ void WebSocketServer::broadcastTextMessage(const QString &msg) { for (size_t i = 0; i < clients.size(); i++) { QWebSocket *sock = clients[i]; if (sock->state() != QAbstractSocket::ConnectedState) { DBG_Printf(DBG_INFO, "Websocket %s:%u unexpected state: %d\n", qPrintable(sock->peerAddress().toString()), sock->peerPort(), sock->state()); } qint64 ret = sock->sendTextMessage(msg); DBG_Printf(DBG_INFO_L2, "Websocket %s:%u send message: %s (ret = %d)\n", qPrintable(sock->peerAddress().toString()), sock->peerPort(), qPrintable(msg), ret); sock->flush(); } } /*! Flush the sockets of all connected clients. */ void WebSocketServer::flush() { for (size_t i = 0; i < clients.size(); i++) { QWebSocket *sock = clients[i]; if (sock->state() == QAbstractSocket::ConnectedState) { sock->flush(); } } } #else // no websockets WebSocketServer::WebSocketServer(QObject *parent) : QObject(parent) { } void WebSocketServer::onNewConnection() { } void WebSocketServer::broadcastTextMessage(const QString &) { } quint16 WebSocketServer::port() const { return 0; } #endif
/* * Copyright (c) 2017-2018 dresden elektronik ingenieurtechnik gmbh. * All rights reserved. * * The software in this package is published under the terms of the BSD * style license a copy of which has been included with this distribution in * the LICENSE.txt file. * */ #ifdef USE_WEBSOCKETS #include "deconz/dbg_trace.h" #include "deconz/util.h" #include "websocket_server.h" /*! Constructor. */ WebSocketServer::WebSocketServer(QObject *parent, quint16 port) : QObject(parent) { srv = new QWebSocketServer("deconz", QWebSocketServer::NonSecureMode, this); quint16 p = 0; quint16 ports[] = { 443, 443, 8080, 8088, 20877, 0 }; // start with proxy frinedly ports first, use random port as fallback if (port > 0) { ports[0] = port; } QHostAddress address; QString addrArg = deCONZ::appArgumentString("--http-listen", QString()); if (addrArg.isEmpty()) // Tie websocket server to specified IP, if any { address = QHostAddress::AnyIPv4; } else { address = QHostAddress(addrArg); } while (!srv->listen(address, ports[p])) { if (ports[p] == 0) { DBG_Printf(DBG_ERROR, "Giveup starting websocket server on %s, port: %u. error: %s\n", qPrintable(address.toString()), ports[p], qPrintable(srv->errorString())); break; } DBG_Printf(DBG_ERROR, "Failed to start websocket server on %s, port: %u. error: %s\n", qPrintable(address.toString()), ports[p], qPrintable(srv->errorString())); p++; } if (srv->isListening()) { DBG_Printf(DBG_INFO, "Started websocket server on %s, port: %u\n", qPrintable(address.toString()), srv->serverPort()); connect(srv, SIGNAL(newConnection()), this, SLOT(onNewConnection())); } } /*! Returns the websocket server port. \return the active server port, or 0 if not active */ quint16 WebSocketServer::port() const { return srv->isListening() ? srv->serverPort() : 0; } /*! Handler for new client connections. */ void WebSocketServer::onNewConnection() { while (srv->hasPendingConnections()) { QWebSocket *sock = srv->nextPendingConnection(); DBG_Printf(DBG_INFO, "New websocket %s:%u (state: %d) \n", qPrintable(sock->peerAddress().toString()), sock->peerPort(), sock->state()); connect(sock, SIGNAL(disconnected()), this, SLOT(onSocketDisconnected())); connect(sock, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(onSocketError(QAbstractSocket::SocketError))); clients.push_back(sock); } } /*! Handle websocket disconnected signal. */ void WebSocketServer::onSocketDisconnected() { for (size_t i = 0; i < clients.size(); i++) { QWebSocket *sock = qobject_cast<QWebSocket*>(sender()); DBG_Assert(sock); if (sock && clients[i] == sock) { DBG_Printf(DBG_INFO, "Websocket disconnected %s:%u, state: %d, close-code: %d, reason: %s\n", qPrintable(sock->peerAddress().toString()), sock->peerPort(), sock->state(), sock->closeCode(), qPrintable(sock->closeReason())); sock->deleteLater(); clients[i] = clients.back(); clients.pop_back(); } } } /*! Handle websocket error signal. \param err - the error which occured */ void WebSocketServer::onSocketError(QAbstractSocket::SocketError err) { Q_UNUSED(err); for (size_t i = 0; i < clients.size(); i++) { QWebSocket *sock = qobject_cast<QWebSocket*>(sender()); DBG_Assert(sock); if (sock && clients[i] == sock) { DBG_Printf(DBG_INFO, "Remove websocket %s:%u after error %s, close-code: %d, reason: %s\n", qPrintable(sock->peerAddress().toString()), sock->peerPort(), qPrintable(sock->errorString()), sock->closeCode(), qPrintable(sock->closeReason())); sock->deleteLater(); clients[i] = clients.back(); clients.pop_back(); } } } /*! Broadcasts a message to all connected clients. \param msg the message as JSON string */ void WebSocketServer::broadcastTextMessage(const QString &msg) { for (size_t i = 0; i < clients.size(); i++) { QWebSocket *sock = clients[i]; if (sock->state() != QAbstractSocket::ConnectedState) { DBG_Printf(DBG_INFO, "Websocket %s:%u unexpected state: %d\n", qPrintable(sock->peerAddress().toString()), sock->peerPort(), sock->state()); } qint64 ret = sock->sendTextMessage(msg); DBG_Printf(DBG_INFO_L2, "Websocket %s:%u send message: %s (ret = %d)\n", qPrintable(sock->peerAddress().toString()), sock->peerPort(), qPrintable(msg), ret); sock->flush(); } } /*! Flush the sockets of all connected clients. */ void WebSocketServer::flush() { for (size_t i = 0; i < clients.size(); i++) { QWebSocket *sock = clients[i]; if (sock->state() == QAbstractSocket::ConnectedState) { sock->flush(); } } } #else // no websockets WebSocketServer::WebSocketServer(QObject *parent) : QObject(parent) { } void WebSocketServer::onNewConnection() { } void WebSocketServer::broadcastTextMessage(const QString &) { } quint16 WebSocketServer::port() const { return 0; } #endif
Fix QHostAddress deprecated warning; guard against empty argument
Fix QHostAddress deprecated warning; guard against empty argument
C++
bsd-3-clause
dresden-elektronik/deconz-rest-plugin,dresden-elektronik/deconz-rest-plugin,dresden-elektronik/deconz-rest-plugin,dresden-elektronik/deconz-rest-plugin,dresden-elektronik/deconz-rest-plugin
6e861467938e5dace01d1958b0c03dd2d665b8a0
PWGJE/EMCALJetTasks/Tracks/AliAnalysisTaskEmcalJetEnergyScale.cxx
PWGJE/EMCALJetTasks/Tracks/AliAnalysisTaskEmcalJetEnergyScale.cxx
/************************************************************************************ * Copyright (C) 2017, Copyright Holders of the ALICE Collaboration * * 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 <organization> 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 ALICE COLLABORATION 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 <algorithm> #include <array> #include <string> #include <sstream> #include <vector> #include <THistManager.h> #include <TCustomBinning.h> #include <TLinearBinning.h> #include "AliAODInputHandler.h" #include "AliAnalysisManager.h" #include "AliAnalysisTaskEmcalJetEnergyScale.h" #include "AliEmcalTriggerDecisionContainer.h" #include "AliEmcalAnalysisFactory.h" #include "AliLog.h" #include "AliVEventHandler.h" ClassImp(EmcalTriggerJets::AliAnalysisTaskEmcalJetEnergyScale) using namespace EmcalTriggerJets; AliAnalysisTaskEmcalJetEnergyScale::AliAnalysisTaskEmcalJetEnergyScale(): AliAnalysisTaskEmcalJet(), fHistos(nullptr), fNameDetectorJets(), fNameParticleJets(), fTriggerSelectionString(), fNameTriggerDecisionContainer("EmcalTriggerDecision") { } AliAnalysisTaskEmcalJetEnergyScale::AliAnalysisTaskEmcalJetEnergyScale(const char *name): AliAnalysisTaskEmcalJet(name, true), fHistos(nullptr), fNameDetectorJets(), fNameParticleJets(), fTriggerSelectionString(), fNameTriggerDecisionContainer("EmcalTriggerDecision") { SetUseAliAnaUtils(true); DefineOutput(1, TList::Class()); } AliAnalysisTaskEmcalJetEnergyScale::~AliAnalysisTaskEmcalJetEnergyScale() { if(fHistos) delete fHistos; } void AliAnalysisTaskEmcalJetEnergyScale::UserCreateOutputObjects(){ AliAnalysisTaskEmcal::UserCreateOutputObjects(); TLinearBinning jetPtBinning(200, 0., 200.), nefbinning(100, 0., 1.), ptdiffbinning(200, -1., 1.), jetEtaBinning(100, -0.9, 0.9), jetPhiBinning(100, 0., TMath::TwoPi()); const TBinning *diffbinning[3] = {&jetPtBinning, &nefbinning, &ptdiffbinning}, *corrbinning[3] = {&jetPtBinning, &jetPtBinning, &nefbinning}, *effbinning[3] = {&jetPtBinning, &jetEtaBinning, &jetPhiBinning}; fHistos = new THistManager("energyScaleHistos"); fHistos->CreateTH1("hEventCounter", "Event counter", 1, 0.5, 1.5); fHistos->CreateTHnSparse("hPtDiff", "pt diff det/part", 3., diffbinning, "s"); fHistos->CreateTHnSparse("hPtCorr", "Correlation det pt / part pt", 3., corrbinning, "s"); fHistos->CreateTHnSparse("hPartJetsAccepted", "Accepted particle level jets", 3, effbinning, "s"); fHistos->CreateTHnSparse("hPartJetsReconstructed", "Accepted and reconstructed particle level jets", 3, effbinning, "s"); for(auto h : *(fHistos->GetListOfHistograms())) fOutput->Add(h); PostData(1, fOutput); } Bool_t AliAnalysisTaskEmcalJetEnergyScale::Run(){ AliDebugStream(1) << "Next event" << std::endl; if(!(fInputHandler->IsEventSelected() & AliVEvent::kINT7)) return false; if(IsSelectEmcalTriggers(fTriggerSelectionString.Data())){ auto mctrigger = static_cast<PWG::EMCAL::AliEmcalTriggerDecisionContainer *>(fInputEvent->FindListObject(fNameTriggerDecisionContainer)); AliDebugStream(1) << "Found trigger decision object: " << (mctrigger ? "yes" : "no") << std::endl; if(!mctrigger){ AliErrorStream() << "Trigger decision container with name " << fNameTriggerDecisionContainer << " not found in event - not possible to select EMCAL triggers" << std::endl; return false; } if(!mctrigger->IsEventSelected(fTriggerSelectionString)) return false; } AliDebugStream(1) << "event selected" << std::endl; fHistos->FillTH1("hEventCounter", 1); auto detjets = GetJetContainer(fNameDetectorJets), partjets = GetJetContainer(fNameParticleJets); if(!detjets || !partjets) { AliErrorStream() << "At least one jet container missing, exiting ..." << std::endl; return false; } AliDebugStream(1) << "Have both jet containers: part(" << partjets->GetNAcceptedJets() << "|" << partjets->GetNJets() << "), det(" << detjets->GetNAcceptedJets() << "|" << detjets->GetNJets() << ")" << std::endl; std::vector<AliEmcalJet *> taggedjets; for(auto detjet : detjets->accepted()){ AliDebugStream(2) << "Next jet" << std::endl; auto partjet = detjet->ClosestJet(); if(!partjet) { AliDebugStream(2) << "No tagged jet" << std::endl; continue; } taggedjets.emplace_back(partjet); double pointCorr[3] = {partjet->Pt(), detjet->Pt(), detjet->NEF()}, pointDiff[3] = {partjet->Pt(), detjet->NEF(), (detjet->Pt()-partjet->Pt())/partjet->Pt()}; fHistos->FillTHnSparse("hPtDiff", pointDiff); fHistos->FillTHnSparse("hPtCorr", pointCorr); } // efficiency x acceptance: Add histos for all accepted and reconstucted accepted jets for(auto partjet : partjets->accepted()){ double pvect[3] = {partjet->Pt(), partjet->Eta(), partjet->Phi()}; if(pvect[2] < 0) pvect[2] += TMath::TwoPi(); fHistos->FillTHnSparse("hPartJetsAccepted", pvect); if(std::find(taggedjets.begin(), taggedjets.end(), partjet) != taggedjets.end()) fHistos->FillTHnSparse("hPartJetsReconstructed", pvect); } return true; } bool AliAnalysisTaskEmcalJetEnergyScale::IsSelectEmcalTriggers(const TString &triggerstring) const { const std::array<TString, 8> kEMCALTriggers = { "EJ1", "EJ2", "DJ1", "DJ2", "EG1", "EG2", "DG1", "DG2" }; bool isEMCAL = false; for(auto emcaltrg : kEMCALTriggers) { if(triggerstring.Contains(emcaltrg)) { isEMCAL = true; break; } } return isEMCAL; } AliAnalysisTaskEmcalJetEnergyScale *AliAnalysisTaskEmcalJetEnergyScale::AddTaskJetEnergyScale(AliJetContainer::EJetType_t jettype, Double_t jetradius, Bool_t useDCAL, const char *trigger) { AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if(!mgr){ ::Error("EmcalTriggerJets::AliAnalysisTaskEmcalJetEnergyScale::AddTaskJetEnergyScale", "No analysis manager available"); return nullptr; } auto inputhandler = mgr->GetInputEventHandler(); auto isAOD = inputhandler->IsA() == AliAODInputHandler::Class(); std::string jettypename; AliJetContainer::JetAcceptanceType acceptance(AliJetContainer::kTPCfid); bool addClusterContainer(false), addTrackContainer(false); switch(jettype){ case AliJetContainer::kFullJet: jettypename = "FullJet"; acceptance = useDCAL ? AliJetContainer::kDCALfid : AliJetContainer::kEMCALfid; addClusterContainer = addTrackContainer = true; break; case AliJetContainer::kChargedJet: jettypename = "ChargedJet"; acceptance = AliJetContainer::kTPCfid; addTrackContainer = true; break; case AliJetContainer::kNeutralJet: jettypename = "NeutralJet"; acceptance = useDCAL ? AliJetContainer::kDCALfid : AliJetContainer::kEMCALfid; addClusterContainer = true; break; }; std::stringstream taskname, tag; tag << jettypename << "_R" << std::setw(2) << std::setfill('0') << int(jetradius * 10.) << "_" << trigger; taskname << "EnergyScaleTask_" << tag.str(); AliAnalysisTaskEmcalJetEnergyScale *energyscaletask = new AliAnalysisTaskEmcalJetEnergyScale(taskname.str().data()); mgr->AddTask(energyscaletask); energyscaletask->SetTriggerName(trigger); auto partcont = energyscaletask->AddMCParticleContainer("mcparticles"); partcont->SetMinPt(0.); AliClusterContainer *clusters(nullptr); if(addClusterContainer) { clusters = energyscaletask->AddClusterContainer(EMCalTriggerPtAnalysis::AliEmcalAnalysisFactory::ClusterContainerNameFactory(isAOD)); switch(jettype){ case AliJetContainer::kChargedJet: break; // Silence compiler case AliJetContainer::kFullJet: clusters->SetDefaultClusterEnergy(AliVCluster::kHadCorr); clusters->SetClusHadCorrEnergyCut(0.3); break; case AliJetContainer::kNeutralJet: clusters->SetDefaultClusterEnergy(AliVCluster::kNonLinCorr); clusters->SetClusNonLinCorrEnergyCut(0.3); break; }; } AliTrackContainer *tracks(nullptr); if(addTrackContainer) { tracks = energyscaletask->AddTrackContainer(EMCalTriggerPtAnalysis::AliEmcalAnalysisFactory::TrackContainerNameFactory(isAOD)); } auto contpartjet = energyscaletask->AddJetContainer(jettype, AliJetContainer::antikt_algorithm, AliJetContainer::E_scheme, jetradius, AliJetContainer::kTPCfid, partcont, nullptr); contpartjet->SetName("particleLevelJets"); energyscaletask->SetNamePartJetContainer("particleLevelJets"); std::cout << "Adding particle-level jet container with underling array: " << contpartjet->GetArrayName() << std::endl; auto contdetjet = energyscaletask->AddJetContainer(jettype, AliJetContainer::antikt_algorithm, AliJetContainer::E_scheme, jetradius, acceptance, tracks, clusters); contdetjet->SetName("detectorLevelJets"); energyscaletask->SetNameDetJetContainer("detectorLevelJets"); std::cout << "Adding detector-level jet container with underling array: " << contdetjet->GetArrayName() << std::endl; std::stringstream outnamebuilder, listnamebuilder; listnamebuilder << "EnergyScaleHists_" << tag.str(); outnamebuilder << mgr->GetCommonFileName() << ":EnergyScaleResults_" << tag.str(); mgr->ConnectInput(energyscaletask, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(energyscaletask, 1, mgr->CreateContainer(listnamebuilder.str().data(), TList::Class(), AliAnalysisManager::kOutputContainer, outnamebuilder.str().data())); return energyscaletask; }
/************************************************************************************ * Copyright (C) 2017, Copyright Holders of the ALICE Collaboration * * 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 <organization> 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 ALICE COLLABORATION 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 <algorithm> #include <array> #include <string> #include <sstream> #include <vector> #include <THistManager.h> #include <TCustomBinning.h> #include <TLinearBinning.h> #include "AliAODInputHandler.h" #include "AliAnalysisManager.h" #include "AliAnalysisTaskEmcalJetEnergyScale.h" #include "AliEmcalTriggerDecisionContainer.h" #include "AliEmcalAnalysisFactory.h" #include "AliLog.h" #include "AliVEventHandler.h" ClassImp(EmcalTriggerJets::AliAnalysisTaskEmcalJetEnergyScale) using namespace EmcalTriggerJets; AliAnalysisTaskEmcalJetEnergyScale::AliAnalysisTaskEmcalJetEnergyScale(): AliAnalysisTaskEmcalJet(), fHistos(nullptr), fNameDetectorJets(), fNameParticleJets(), fTriggerSelectionString(), fNameTriggerDecisionContainer("EmcalTriggerDecision") { } AliAnalysisTaskEmcalJetEnergyScale::AliAnalysisTaskEmcalJetEnergyScale(const char *name): AliAnalysisTaskEmcalJet(name, true), fHistos(nullptr), fNameDetectorJets(), fNameParticleJets(), fTriggerSelectionString(), fNameTriggerDecisionContainer("EmcalTriggerDecision") { SetUseAliAnaUtils(true); DefineOutput(1, TList::Class()); } AliAnalysisTaskEmcalJetEnergyScale::~AliAnalysisTaskEmcalJetEnergyScale() { if(fHistos) delete fHistos; } void AliAnalysisTaskEmcalJetEnergyScale::UserCreateOutputObjects(){ AliAnalysisTaskEmcal::UserCreateOutputObjects(); TLinearBinning jetPtBinning(300, 0., 300.), nefbinning(100, 0., 1.), ptdiffbinning(200, -1., 1.), jetEtaBinning(100, -0.9, 0.9), jetPhiBinning(100, 0., TMath::TwoPi()); const TBinning *diffbinning[3] = {&jetPtBinning, &nefbinning, &ptdiffbinning}, *corrbinning[3] = {&jetPtBinning, &jetPtBinning, &nefbinning}, *effbinning[3] = {&jetPtBinning, &jetEtaBinning, &jetPhiBinning}; fHistos = new THistManager("energyScaleHistos"); fHistos->CreateTH1("hEventCounter", "Event counter", 1, 0.5, 1.5); fHistos->CreateTHnSparse("hPtDiff", "pt diff det/part", 3., diffbinning, "s"); fHistos->CreateTHnSparse("hPtCorr", "Correlation det pt / part pt", 3., corrbinning, "s"); fHistos->CreateTHnSparse("hPartJetsAccepted", "Accepted particle level jets", 3, effbinning, "s"); fHistos->CreateTHnSparse("hPartJetsReconstructed", "Accepted and reconstructed particle level jets", 3, effbinning, "s"); for(auto h : *(fHistos->GetListOfHistograms())) fOutput->Add(h); PostData(1, fOutput); } Bool_t AliAnalysisTaskEmcalJetEnergyScale::Run(){ AliDebugStream(1) << "Next event" << std::endl; if(!(fInputHandler->IsEventSelected() & AliVEvent::kINT7)) return false; if(IsSelectEmcalTriggers(fTriggerSelectionString.Data())){ auto mctrigger = static_cast<PWG::EMCAL::AliEmcalTriggerDecisionContainer *>(fInputEvent->FindListObject(fNameTriggerDecisionContainer)); AliDebugStream(1) << "Found trigger decision object: " << (mctrigger ? "yes" : "no") << std::endl; if(!mctrigger){ AliErrorStream() << "Trigger decision container with name " << fNameTriggerDecisionContainer << " not found in event - not possible to select EMCAL triggers" << std::endl; return false; } if(!mctrigger->IsEventSelected(fTriggerSelectionString)) return false; } AliDebugStream(1) << "event selected" << std::endl; fHistos->FillTH1("hEventCounter", 1); auto detjets = GetJetContainer(fNameDetectorJets), partjets = GetJetContainer(fNameParticleJets); if(!detjets || !partjets) { AliErrorStream() << "At least one jet container missing, exiting ..." << std::endl; return false; } AliDebugStream(1) << "Have both jet containers: part(" << partjets->GetNAcceptedJets() << "|" << partjets->GetNJets() << "), det(" << detjets->GetNAcceptedJets() << "|" << detjets->GetNJets() << ")" << std::endl; std::vector<AliEmcalJet *> taggedjets; for(auto detjet : detjets->accepted()){ AliDebugStream(2) << "Next jet" << std::endl; auto partjet = detjet->ClosestJet(); if(!partjet) { AliDebugStream(2) << "No tagged jet" << std::endl; continue; } taggedjets.emplace_back(partjet); double pointCorr[3] = {partjet->Pt(), detjet->Pt(), detjet->NEF()}, pointDiff[3] = {partjet->Pt(), detjet->NEF(), (detjet->Pt()-partjet->Pt())/partjet->Pt()}; fHistos->FillTHnSparse("hPtDiff", pointDiff); fHistos->FillTHnSparse("hPtCorr", pointCorr); } // efficiency x acceptance: Add histos for all accepted and reconstucted accepted jets for(auto partjet : partjets->accepted()){ double pvect[3] = {partjet->Pt(), partjet->Eta(), partjet->Phi()}; if(pvect[2] < 0) pvect[2] += TMath::TwoPi(); fHistos->FillTHnSparse("hPartJetsAccepted", pvect); if(std::find(taggedjets.begin(), taggedjets.end(), partjet) != taggedjets.end()) fHistos->FillTHnSparse("hPartJetsReconstructed", pvect); } return true; } bool AliAnalysisTaskEmcalJetEnergyScale::IsSelectEmcalTriggers(const TString &triggerstring) const { const std::array<TString, 8> kEMCALTriggers = { "EJ1", "EJ2", "DJ1", "DJ2", "EG1", "EG2", "DG1", "DG2" }; bool isEMCAL = false; for(auto emcaltrg : kEMCALTriggers) { if(triggerstring.Contains(emcaltrg)) { isEMCAL = true; break; } } return isEMCAL; } AliAnalysisTaskEmcalJetEnergyScale *AliAnalysisTaskEmcalJetEnergyScale::AddTaskJetEnergyScale(AliJetContainer::EJetType_t jettype, Double_t jetradius, Bool_t useDCAL, const char *trigger) { AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if(!mgr){ ::Error("EmcalTriggerJets::AliAnalysisTaskEmcalJetEnergyScale::AddTaskJetEnergyScale", "No analysis manager available"); return nullptr; } auto inputhandler = mgr->GetInputEventHandler(); auto isAOD = inputhandler->IsA() == AliAODInputHandler::Class(); std::string jettypename; AliJetContainer::JetAcceptanceType acceptance(AliJetContainer::kTPCfid); bool addClusterContainer(false), addTrackContainer(false); switch(jettype){ case AliJetContainer::kFullJet: jettypename = "FullJet"; acceptance = useDCAL ? AliJetContainer::kDCALfid : AliJetContainer::kEMCALfid; addClusterContainer = addTrackContainer = true; break; case AliJetContainer::kChargedJet: jettypename = "ChargedJet"; acceptance = AliJetContainer::kTPCfid; addTrackContainer = true; break; case AliJetContainer::kNeutralJet: jettypename = "NeutralJet"; acceptance = useDCAL ? AliJetContainer::kDCALfid : AliJetContainer::kEMCALfid; addClusterContainer = true; break; }; std::stringstream taskname, tag; tag << jettypename << "_R" << std::setw(2) << std::setfill('0') << int(jetradius * 10.) << "_" << trigger; taskname << "EnergyScaleTask_" << tag.str(); AliAnalysisTaskEmcalJetEnergyScale *energyscaletask = new AliAnalysisTaskEmcalJetEnergyScale(taskname.str().data()); mgr->AddTask(energyscaletask); energyscaletask->SetTriggerName(trigger); auto partcont = energyscaletask->AddMCParticleContainer("mcparticles"); partcont->SetMinPt(0.); AliClusterContainer *clusters(nullptr); if(addClusterContainer) { clusters = energyscaletask->AddClusterContainer(EMCalTriggerPtAnalysis::AliEmcalAnalysisFactory::ClusterContainerNameFactory(isAOD)); switch(jettype){ case AliJetContainer::kChargedJet: break; // Silence compiler case AliJetContainer::kFullJet: clusters->SetDefaultClusterEnergy(AliVCluster::kHadCorr); clusters->SetClusHadCorrEnergyCut(0.3); break; case AliJetContainer::kNeutralJet: clusters->SetDefaultClusterEnergy(AliVCluster::kNonLinCorr); clusters->SetClusNonLinCorrEnergyCut(0.3); break; }; } AliTrackContainer *tracks(nullptr); if(addTrackContainer) { tracks = energyscaletask->AddTrackContainer(EMCalTriggerPtAnalysis::AliEmcalAnalysisFactory::TrackContainerNameFactory(isAOD)); } auto contpartjet = energyscaletask->AddJetContainer(jettype, AliJetContainer::antikt_algorithm, AliJetContainer::E_scheme, jetradius, AliJetContainer::kTPCfid, partcont, nullptr); contpartjet->SetName("particleLevelJets"); energyscaletask->SetNamePartJetContainer("particleLevelJets"); std::cout << "Adding particle-level jet container with underling array: " << contpartjet->GetArrayName() << std::endl; auto contdetjet = energyscaletask->AddJetContainer(jettype, AliJetContainer::antikt_algorithm, AliJetContainer::E_scheme, jetradius, acceptance, tracks, clusters); contdetjet->SetName("detectorLevelJets"); energyscaletask->SetNameDetJetContainer("detectorLevelJets"); std::cout << "Adding detector-level jet container with underling array: " << contdetjet->GetArrayName() << std::endl; std::stringstream outnamebuilder, listnamebuilder; listnamebuilder << "EnergyScaleHists_" << tag.str(); outnamebuilder << mgr->GetCommonFileName() << ":EnergyScaleResults_" << tag.str(); mgr->ConnectInput(energyscaletask, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(energyscaletask, 1, mgr->CreateContainer(listnamebuilder.str().data(), TList::Class(), AliAnalysisManager::kOutputContainer, outnamebuilder.str().data())); return energyscaletask; }
Increase jet pt range to 300 GeV/c
Increase jet pt range to 300 GeV/c Allowing for feed down to lower det-level jet pt in the range covered by the jet trigger.
C++
bsd-3-clause
carstooon/AliPhysics,adriansev/AliPhysics,victor-gonzalez/AliPhysics,hcab14/AliPhysics,amaringarcia/AliPhysics,pbuehler/AliPhysics,amatyja/AliPhysics,rihanphys/AliPhysics,pchrista/AliPhysics,mpuccio/AliPhysics,nschmidtALICE/AliPhysics,carstooon/AliPhysics,nschmidtALICE/AliPhysics,preghenella/AliPhysics,sebaleh/AliPhysics,AMechler/AliPhysics,mpuccio/AliPhysics,hcab14/AliPhysics,rihanphys/AliPhysics,amaringarcia/AliPhysics,hzanoli/AliPhysics,AMechler/AliPhysics,mvala/AliPhysics,pbuehler/AliPhysics,preghenella/AliPhysics,akubera/AliPhysics,amatyja/AliPhysics,preghenella/AliPhysics,pbuehler/AliPhysics,AMechler/AliPhysics,lcunquei/AliPhysics,sebaleh/AliPhysics,adriansev/AliPhysics,amatyja/AliPhysics,SHornung1/AliPhysics,victor-gonzalez/AliPhysics,lcunquei/AliPhysics,dmuhlhei/AliPhysics,nschmidtALICE/AliPhysics,alisw/AliPhysics,carstooon/AliPhysics,preghenella/AliPhysics,amaringarcia/AliPhysics,amaringarcia/AliPhysics,fbellini/AliPhysics,SHornung1/AliPhysics,fcolamar/AliPhysics,mvala/AliPhysics,amaringarcia/AliPhysics,dmuhlhei/AliPhysics,lcunquei/AliPhysics,hcab14/AliPhysics,akubera/AliPhysics,adriansev/AliPhysics,amatyja/AliPhysics,fbellini/AliPhysics,alisw/AliPhysics,pbuehler/AliPhysics,sebaleh/AliPhysics,SHornung1/AliPhysics,dmuhlhei/AliPhysics,lcunquei/AliPhysics,rbailhac/AliPhysics,alisw/AliPhysics,AMechler/AliPhysics,kreisl/AliPhysics,btrzecia/AliPhysics,lcunquei/AliPhysics,pchrista/AliPhysics,mvala/AliPhysics,sebaleh/AliPhysics,amatyja/AliPhysics,rbailhac/AliPhysics,carstooon/AliPhysics,hcab14/AliPhysics,akubera/AliPhysics,pchrista/AliPhysics,preghenella/AliPhysics,mvala/AliPhysics,rbailhac/AliPhysics,btrzecia/AliPhysics,rbailhac/AliPhysics,pbuehler/AliPhysics,victor-gonzalez/AliPhysics,kreisl/AliPhysics,carstooon/AliPhysics,preghenella/AliPhysics,pchrista/AliPhysics,AMechler/AliPhysics,adriansev/AliPhysics,mpuccio/AliPhysics,hcab14/AliPhysics,akubera/AliPhysics,fcolamar/AliPhysics,lcunquei/AliPhysics,nschmidtALICE/AliPhysics,pchrista/AliPhysics,sebaleh/AliPhysics,adriansev/AliPhysics,btrzecia/AliPhysics,hcab14/AliPhysics,rbailhac/AliPhysics,kreisl/AliPhysics,rihanphys/AliPhysics,fcolamar/AliPhysics,victor-gonzalez/AliPhysics,akubera/AliPhysics,hzanoli/AliPhysics,kreisl/AliPhysics,dmuhlhei/AliPhysics,nschmidtALICE/AliPhysics,victor-gonzalez/AliPhysics,kreisl/AliPhysics,hzanoli/AliPhysics,rbailhac/AliPhysics,amatyja/AliPhysics,SHornung1/AliPhysics,preghenella/AliPhysics,alisw/AliPhysics,btrzecia/AliPhysics,sebaleh/AliPhysics,alisw/AliPhysics,hzanoli/AliPhysics,mpuccio/AliPhysics,btrzecia/AliPhysics,rihanphys/AliPhysics,AMechler/AliPhysics,kreisl/AliPhysics,adriansev/AliPhysics,fcolamar/AliPhysics,akubera/AliPhysics,fbellini/AliPhysics,fbellini/AliPhysics,SHornung1/AliPhysics,alisw/AliPhysics,victor-gonzalez/AliPhysics,nschmidtALICE/AliPhysics,dmuhlhei/AliPhysics,fbellini/AliPhysics,amaringarcia/AliPhysics,rihanphys/AliPhysics,SHornung1/AliPhysics,carstooon/AliPhysics,fbellini/AliPhysics,rihanphys/AliPhysics,adriansev/AliPhysics,mvala/AliPhysics,pbuehler/AliPhysics,amatyja/AliPhysics,hzanoli/AliPhysics,SHornung1/AliPhysics,fcolamar/AliPhysics,kreisl/AliPhysics,btrzecia/AliPhysics,hcab14/AliPhysics,rihanphys/AliPhysics,sebaleh/AliPhysics,nschmidtALICE/AliPhysics,rbailhac/AliPhysics,pchrista/AliPhysics,mpuccio/AliPhysics,btrzecia/AliPhysics,amaringarcia/AliPhysics,AMechler/AliPhysics,hzanoli/AliPhysics,victor-gonzalez/AliPhysics,lcunquei/AliPhysics,akubera/AliPhysics,dmuhlhei/AliPhysics,fcolamar/AliPhysics,mvala/AliPhysics,alisw/AliPhysics,mpuccio/AliPhysics,carstooon/AliPhysics,fcolamar/AliPhysics,mvala/AliPhysics,pbuehler/AliPhysics,hzanoli/AliPhysics,pchrista/AliPhysics,mpuccio/AliPhysics,dmuhlhei/AliPhysics,fbellini/AliPhysics
5c42d7288a175f6d976ec0d90ced688aacd0d8b3
src/client/linux/microdump_writer/microdump_writer_unittest.cc
src/client/linux/microdump_writer/microdump_writer_unittest.cc
// Copyright (c) 2014 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. #include <ctype.h> #include <sys/syscall.h> #include <sys/types.h> #include <unistd.h> #include <ucontext.h> #include <sstream> #include <string> #include "breakpad_googletest_includes.h" #include "client/linux/handler/exception_handler.h" #include "client/linux/handler/microdump_extra_info.h" #include "client/linux/microdump_writer/microdump_writer.h" #include "common/linux/eintr_wrapper.h" #include "common/linux/ignore_ret.h" #include "common/scoped_ptr.h" #include "common/tests/auto_tempdir.h" #include "common/using_std_string.h" using namespace google_breakpad; extern "C" { extern char __executable_start; extern char __etext; } namespace { typedef testing::Test MicrodumpWriterTest; MicrodumpExtraInfo MakeMicrodumpExtraInfo( const char* build_fingerprint, const char* product_info, const char* gpu_fingerprint, bool suppress_microdump_based_on_interest_range = false, uintptr_t interest_range_start = 0, uintptr_t interest_range_end = 0) { MicrodumpExtraInfo info; info.build_fingerprint = build_fingerprint; info.product_info = product_info; info.gpu_fingerprint = gpu_fingerprint; info.suppress_microdump_based_on_interest_range = suppress_microdump_based_on_interest_range; info.interest_range_start = interest_range_start; info.interest_range_end = interest_range_end; return info; } void AssertContainsMicrodump(const std::string& buf) { ASSERT_NE(std::string::npos, buf.find("-----BEGIN BREAKPAD MICRODUMP-----")); ASSERT_NE(std::string::npos, buf.find("-----END BREAKPAD MICRODUMP-----")); } void CrashAndGetMicrodump(const MappingList& mappings, const MicrodumpExtraInfo& microdump_extra_info, std::string* microdump) { int fds[2]; ASSERT_NE(-1, pipe(fds)); AutoTempDir temp_dir; string stderr_file = temp_dir.path() + "/stderr.log"; int err_fd = open(stderr_file.c_str(), O_CREAT | O_RDWR, S_IRUSR | S_IWUSR); ASSERT_NE(-1, err_fd); const pid_t child = fork(); if (child == 0) { close(fds[1]); char b; IGNORE_RET(HANDLE_EINTR(read(fds[0], &b, sizeof(b)))); close(fds[0]); syscall(__NR_exit); } close(fds[0]); ExceptionHandler::CrashContext context; memset(&context, 0, sizeof(context)); // Pretend the current context is the child context (which is // approximately right) so that we have a valid stack pointer, and // can fetch child stack data via ptrace. getcontext(&context.context); // Set a non-zero tid to avoid tripping asserts. context.tid = child; // Redirect temporarily stderr to the stderr.log file. int save_err = dup(STDERR_FILENO); ASSERT_NE(-1, save_err); ASSERT_NE(-1, dup2(err_fd, STDERR_FILENO)); ASSERT_TRUE(WriteMicrodump(child, &context, sizeof(context), mappings, microdump_extra_info)); // Revert stderr back to the console. dup2(save_err, STDERR_FILENO); close(save_err); // Read back the stderr file and check for the microdump marker. fsync(err_fd); lseek(err_fd, 0, SEEK_SET); microdump->clear(); char buf[1024]; while (true) { int bytes_read = IGNORE_EINTR(read(err_fd, buf, 1024)); if (bytes_read <= 0) break; microdump->append(buf, buf + bytes_read); } close(err_fd); close(fds[1]); } void CheckMicrodumpContents(const string& microdump_content, const MicrodumpExtraInfo& expected_info) { std::istringstream iss(microdump_content); bool did_find_os_info = false; bool did_find_product_info = false; bool did_find_gpu_info = false; for (string line; std::getline(iss, line);) { if (line.find("O ") == 0) { std::istringstream os_info_tokens(line); string token; os_info_tokens.ignore(2); // Ignore the "O " preamble. // Check the OS descriptor char (L=Linux, A=Android). os_info_tokens >> token; ASSERT_TRUE(token == "L" || token == "A"); os_info_tokens >> token; // HW architecture. os_info_tokens >> token; // Number of cpus. for (size_t i = 0; i < token.size(); ++i) ASSERT_TRUE(isxdigit(token[i])); os_info_tokens >> token; // SW architecture. // Check that the build fingerprint is in the right place. os_info_tokens >> token; if (expected_info.build_fingerprint) ASSERT_EQ(expected_info.build_fingerprint, token); did_find_os_info = true; } else if (line.find("V ") == 0) { if (expected_info.product_info) ASSERT_EQ(string("V ") + expected_info.product_info, line); did_find_product_info = true; } else if (line.find("G ") == 0) { if (expected_info.gpu_fingerprint) ASSERT_EQ(string("G ") + expected_info.gpu_fingerprint, line); did_find_gpu_info = true; } } ASSERT_TRUE(did_find_os_info); ASSERT_TRUE(did_find_product_info); ASSERT_TRUE(did_find_gpu_info); } void CheckMicrodumpContents(const string& microdump_content, const string& expected_fingerprint, const string& expected_product_info, const string& expected_gpu_fingerprint) { CheckMicrodumpContents( microdump_content, MakeMicrodumpExtraInfo(expected_fingerprint.c_str(), expected_product_info.c_str(), expected_gpu_fingerprint.c_str())); } TEST(MicrodumpWriterTest, BasicWithMappings) { // Push some extra mapping to check the MappingList logic. const uint32_t memory_size = sysconf(_SC_PAGESIZE); const char* kMemoryName = "libfoo.so"; const uint8_t kModuleGUID[sizeof(MDGUID)] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF }; MappingInfo info; info.start_addr = memory_size; info.size = memory_size; info.offset = 42; strcpy(info.name, kMemoryName); MappingList mappings; MappingEntry mapping; mapping.first = info; memcpy(mapping.second, kModuleGUID, sizeof(MDGUID)); mappings.push_back(mapping); std::string buf; CrashAndGetMicrodump(mappings, MicrodumpExtraInfo(), &buf); AssertContainsMicrodump(buf); #ifdef __LP64__ ASSERT_NE(std::string::npos, buf.find("M 0000000000001000 000000000000002A 0000000000001000 " "33221100554477668899AABBCCDDEEFF0 libfoo.so")); #else ASSERT_NE(std::string::npos, buf.find("M 00001000 0000002A 00001000 " "33221100554477668899AABBCCDDEEFF0 libfoo.so")); #endif // In absence of a product info in the minidump, the writer should just write // an unknown marker. ASSERT_NE(std::string::npos, buf.find("V UNKNOWN:0.0.0.0")); } // Ensure that no output occurs if the interest region is set, but // doesn't overlap anything on the stack. TEST(MicrodumpWriterTest, NoOutputIfUninteresting) { const char kProductInfo[] = "MockProduct:42.0.2311.99"; const char kBuildFingerprint[] = "aosp/occam/mako:5.1.1/LMY47W/12345678:userdegbug/dev-keys"; const char kGPUFingerprint[] = "Qualcomm;Adreno (TM) 330;OpenGL ES 3.0 [email protected] AU@ (GIT@Id3510ff6dc)"; const MicrodumpExtraInfo kMicrodumpExtraInfo( MakeMicrodumpExtraInfo(kBuildFingerprint, kProductInfo, kGPUFingerprint, true, 0xdeadbeef, 0xdeadbeef - 1)); std::string buf; MappingList no_mappings; CrashAndGetMicrodump(no_mappings, kMicrodumpExtraInfo, &buf); ASSERT_EQ(0, buf.size()); } // Ensure that output occurs if the interest region is set, and // does overlap something on the stack. TEST(MicrodumpWriterTest, OutputIfInteresting) { const char kProductInfo[] = "MockProduct:42.0.2311.99"; const char kBuildFingerprint[] = "aosp/occam/mako:5.1.1/LMY47W/12345678:userdegbug/dev-keys"; const char kGPUFingerprint[] = "Qualcomm;Adreno (TM) 330;OpenGL ES 3.0 [email protected] AU@ (GIT@Id3510ff6dc)"; const MicrodumpExtraInfo kMicrodumpExtraInfo( MakeMicrodumpExtraInfo(kBuildFingerprint, kProductInfo, kGPUFingerprint, true, reinterpret_cast<uintptr_t>(&__executable_start), reinterpret_cast<uintptr_t>(&__etext))); std::string buf; MappingList no_mappings; CrashAndGetMicrodump(no_mappings, kMicrodumpExtraInfo, &buf); ASSERT_LT(0, buf.size()); } // Ensure that the product info and build fingerprint metadata show up in the // final microdump if present. TEST(MicrodumpWriterTest, BuildFingerprintAndProductInfo) { const char kProductInfo[] = "MockProduct:42.0.2311.99"; const char kBuildFingerprint[] = "aosp/occam/mako:5.1.1/LMY47W/12345678:userdegbug/dev-keys"; const char kGPUFingerprint[] = "Qualcomm;Adreno (TM) 330;OpenGL ES 3.0 [email protected] AU@ (GIT@Id3510ff6dc)"; const MicrodumpExtraInfo kMicrodumpExtraInfo( MakeMicrodumpExtraInfo(kBuildFingerprint, kProductInfo, kGPUFingerprint)); std::string buf; MappingList no_mappings; CrashAndGetMicrodump(no_mappings, kMicrodumpExtraInfo, &buf); AssertContainsMicrodump(buf); CheckMicrodumpContents(buf, kMicrodumpExtraInfo); } TEST(MicrodumpWriterTest, NoProductInfo) { const char kBuildFingerprint[] = "foobar"; const char kGPUFingerprint[] = "bazqux"; std::string buf; MappingList no_mappings; const MicrodumpExtraInfo kMicrodumpExtraInfoNoProductInfo( MakeMicrodumpExtraInfo(kBuildFingerprint, NULL, kGPUFingerprint)); CrashAndGetMicrodump(no_mappings, kMicrodumpExtraInfoNoProductInfo, &buf); AssertContainsMicrodump(buf); CheckMicrodumpContents(buf, kBuildFingerprint, "UNKNOWN:0.0.0.0", kGPUFingerprint); } TEST(MicrodumpWriterTest, NoGPUInfo) { const char kProductInfo[] = "bazqux"; const char kBuildFingerprint[] = "foobar"; std::string buf; MappingList no_mappings; const MicrodumpExtraInfo kMicrodumpExtraInfoNoGPUInfo( MakeMicrodumpExtraInfo(kBuildFingerprint, kProductInfo, NULL)); CrashAndGetMicrodump(no_mappings, kMicrodumpExtraInfoNoGPUInfo, &buf); AssertContainsMicrodump(buf); CheckMicrodumpContents(buf, kBuildFingerprint, kProductInfo, "UNKNOWN"); } } // namespace
// Copyright (c) 2014 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. #include <ctype.h> #include <sys/syscall.h> #include <sys/types.h> #include <unistd.h> #include <ucontext.h> #include <sstream> #include <string> #include "breakpad_googletest_includes.h" #include "client/linux/handler/exception_handler.h" #include "client/linux/handler/microdump_extra_info.h" #include "client/linux/microdump_writer/microdump_writer.h" #include "common/linux/eintr_wrapper.h" #include "common/linux/ignore_ret.h" #include "common/scoped_ptr.h" #include "common/tests/auto_tempdir.h" #include "common/using_std_string.h" using namespace google_breakpad; extern "C" { extern char __executable_start; extern char __etext; } namespace { typedef testing::Test MicrodumpWriterTest; MicrodumpExtraInfo MakeMicrodumpExtraInfo( const char* build_fingerprint, const char* product_info, const char* gpu_fingerprint, bool suppress_microdump_based_on_interest_range = false, uintptr_t interest_range_start = 0, uintptr_t interest_range_end = 0) { MicrodumpExtraInfo info; info.build_fingerprint = build_fingerprint; info.product_info = product_info; info.gpu_fingerprint = gpu_fingerprint; info.suppress_microdump_based_on_interest_range = suppress_microdump_based_on_interest_range; info.interest_range_start = interest_range_start; info.interest_range_end = interest_range_end; return info; } void AssertContainsMicrodump(const std::string& buf) { ASSERT_NE(std::string::npos, buf.find("-----BEGIN BREAKPAD MICRODUMP-----")); ASSERT_NE(std::string::npos, buf.find("-----END BREAKPAD MICRODUMP-----")); } void CrashAndGetMicrodump(const MappingList& mappings, const MicrodumpExtraInfo& microdump_extra_info, std::string* microdump) { int fds[2]; ASSERT_NE(-1, pipe(fds)); AutoTempDir temp_dir; string stderr_file = temp_dir.path() + "/stderr.log"; int err_fd = open(stderr_file.c_str(), O_CREAT | O_RDWR, S_IRUSR | S_IWUSR); ASSERT_NE(-1, err_fd); const pid_t child = fork(); if (child == 0) { close(fds[1]); char b; IGNORE_RET(HANDLE_EINTR(read(fds[0], &b, sizeof(b)))); close(fds[0]); syscall(__NR_exit); } close(fds[0]); ExceptionHandler::CrashContext context; memset(&context, 0, sizeof(context)); // Pretend the current context is the child context (which is // approximately right) so that we have a valid stack pointer, and // can fetch child stack data via ptrace. getcontext(&context.context); // Set a non-zero tid to avoid tripping asserts. context.tid = child; // Redirect temporarily stderr to the stderr.log file. int save_err = dup(STDERR_FILENO); ASSERT_NE(-1, save_err); ASSERT_NE(-1, dup2(err_fd, STDERR_FILENO)); ASSERT_TRUE(WriteMicrodump(child, &context, sizeof(context), mappings, microdump_extra_info)); // Revert stderr back to the console. dup2(save_err, STDERR_FILENO); close(save_err); // Read back the stderr file and check for the microdump marker. fsync(err_fd); lseek(err_fd, 0, SEEK_SET); microdump->clear(); char buf[1024]; while (true) { int bytes_read = IGNORE_EINTR(read(err_fd, buf, 1024)); if (bytes_read <= 0) break; microdump->append(buf, buf + bytes_read); } close(err_fd); close(fds[1]); } void CheckMicrodumpContents(const string& microdump_content, const MicrodumpExtraInfo& expected_info) { std::istringstream iss(microdump_content); bool did_find_os_info = false; bool did_find_product_info = false; bool did_find_gpu_info = false; for (string line; std::getline(iss, line);) { if (line.find("O ") == 0) { std::istringstream os_info_tokens(line); string token; os_info_tokens.ignore(2); // Ignore the "O " preamble. // Check the OS descriptor char (L=Linux, A=Android). os_info_tokens >> token; ASSERT_TRUE(token == "L" || token == "A"); os_info_tokens >> token; // HW architecture. os_info_tokens >> token; // Number of cpus. for (size_t i = 0; i < token.size(); ++i) ASSERT_TRUE(isxdigit(token[i])); os_info_tokens >> token; // SW architecture. // Check that the build fingerprint is in the right place. os_info_tokens >> token; if (expected_info.build_fingerprint) ASSERT_EQ(expected_info.build_fingerprint, token); did_find_os_info = true; } else if (line.find("V ") == 0) { if (expected_info.product_info) ASSERT_EQ(string("V ") + expected_info.product_info, line); did_find_product_info = true; } else if (line.find("G ") == 0) { if (expected_info.gpu_fingerprint) ASSERT_EQ(string("G ") + expected_info.gpu_fingerprint, line); did_find_gpu_info = true; } } ASSERT_TRUE(did_find_os_info); ASSERT_TRUE(did_find_product_info); ASSERT_TRUE(did_find_gpu_info); } void CheckMicrodumpContents(const string& microdump_content, const string& expected_fingerprint, const string& expected_product_info, const string& expected_gpu_fingerprint) { CheckMicrodumpContents( microdump_content, MakeMicrodumpExtraInfo(expected_fingerprint.c_str(), expected_product_info.c_str(), expected_gpu_fingerprint.c_str())); } TEST(MicrodumpWriterTest, BasicWithMappings) { // Push some extra mapping to check the MappingList logic. const uint32_t memory_size = sysconf(_SC_PAGESIZE); const char* kMemoryName = "libfoo.so"; const uint8_t kModuleGUID[sizeof(MDGUID)] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF }; MappingInfo info; info.start_addr = memory_size; info.size = memory_size; info.offset = 42; strcpy(info.name, kMemoryName); MappingList mappings; MappingEntry mapping; mapping.first = info; memcpy(mapping.second, kModuleGUID, sizeof(MDGUID)); mappings.push_back(mapping); std::string buf; CrashAndGetMicrodump(mappings, MicrodumpExtraInfo(), &buf); AssertContainsMicrodump(buf); #ifdef __LP64__ ASSERT_NE(std::string::npos, buf.find("M 0000000000001000 000000000000002A 0000000000001000 " "33221100554477668899AABBCCDDEEFF0 libfoo.so")); #else ASSERT_NE(std::string::npos, buf.find("M 00001000 0000002A 00001000 " "33221100554477668899AABBCCDDEEFF0 libfoo.so")); #endif // In absence of a product info in the minidump, the writer should just write // an unknown marker. ASSERT_NE(std::string::npos, buf.find("V UNKNOWN:0.0.0.0")); } // Ensure that no output occurs if the interest region is set, but // doesn't overlap anything on the stack. TEST(MicrodumpWriterTest, NoOutputIfUninteresting) { const char kProductInfo[] = "MockProduct:42.0.2311.99"; const char kBuildFingerprint[] = "aosp/occam/mako:5.1.1/LMY47W/12345678:userdegbug/dev-keys"; const char kGPUFingerprint[] = "Qualcomm;Adreno (TM) 330;OpenGL ES 3.0 [email protected] AU@ (GIT@Id3510ff6dc)"; const MicrodumpExtraInfo kMicrodumpExtraInfo( MakeMicrodumpExtraInfo(kBuildFingerprint, kProductInfo, kGPUFingerprint, true, 0xdeadbeef, 0xdeadbeef - 1)); std::string buf; MappingList no_mappings; CrashAndGetMicrodump(no_mappings, kMicrodumpExtraInfo, &buf); ASSERT_EQ(0U, buf.size()); } // Ensure that output occurs if the interest region is set, and // does overlap something on the stack. TEST(MicrodumpWriterTest, OutputIfInteresting) { const char kProductInfo[] = "MockProduct:42.0.2311.99"; const char kBuildFingerprint[] = "aosp/occam/mako:5.1.1/LMY47W/12345678:userdegbug/dev-keys"; const char kGPUFingerprint[] = "Qualcomm;Adreno (TM) 330;OpenGL ES 3.0 [email protected] AU@ (GIT@Id3510ff6dc)"; const MicrodumpExtraInfo kMicrodumpExtraInfo( MakeMicrodumpExtraInfo(kBuildFingerprint, kProductInfo, kGPUFingerprint, true, reinterpret_cast<uintptr_t>(&__executable_start), reinterpret_cast<uintptr_t>(&__etext))); std::string buf; MappingList no_mappings; CrashAndGetMicrodump(no_mappings, kMicrodumpExtraInfo, &buf); ASSERT_LT(0U, buf.size()); } // Ensure that the product info and build fingerprint metadata show up in the // final microdump if present. TEST(MicrodumpWriterTest, BuildFingerprintAndProductInfo) { const char kProductInfo[] = "MockProduct:42.0.2311.99"; const char kBuildFingerprint[] = "aosp/occam/mako:5.1.1/LMY47W/12345678:userdegbug/dev-keys"; const char kGPUFingerprint[] = "Qualcomm;Adreno (TM) 330;OpenGL ES 3.0 [email protected] AU@ (GIT@Id3510ff6dc)"; const MicrodumpExtraInfo kMicrodumpExtraInfo( MakeMicrodumpExtraInfo(kBuildFingerprint, kProductInfo, kGPUFingerprint)); std::string buf; MappingList no_mappings; CrashAndGetMicrodump(no_mappings, kMicrodumpExtraInfo, &buf); AssertContainsMicrodump(buf); CheckMicrodumpContents(buf, kMicrodumpExtraInfo); } TEST(MicrodumpWriterTest, NoProductInfo) { const char kBuildFingerprint[] = "foobar"; const char kGPUFingerprint[] = "bazqux"; std::string buf; MappingList no_mappings; const MicrodumpExtraInfo kMicrodumpExtraInfoNoProductInfo( MakeMicrodumpExtraInfo(kBuildFingerprint, NULL, kGPUFingerprint)); CrashAndGetMicrodump(no_mappings, kMicrodumpExtraInfoNoProductInfo, &buf); AssertContainsMicrodump(buf); CheckMicrodumpContents(buf, kBuildFingerprint, "UNKNOWN:0.0.0.0", kGPUFingerprint); } TEST(MicrodumpWriterTest, NoGPUInfo) { const char kProductInfo[] = "bazqux"; const char kBuildFingerprint[] = "foobar"; std::string buf; MappingList no_mappings; const MicrodumpExtraInfo kMicrodumpExtraInfoNoGPUInfo( MakeMicrodumpExtraInfo(kBuildFingerprint, kProductInfo, NULL)); CrashAndGetMicrodump(no_mappings, kMicrodumpExtraInfoNoGPUInfo, &buf); AssertContainsMicrodump(buf); CheckMicrodumpContents(buf, kBuildFingerprint, kProductInfo, "UNKNOWN"); } } // namespace
Fix sign-compare compiler warning in MicrodumpWriterTest
Fix sign-compare compiler warning in MicrodumpWriterTest Commit 7a8980997d0e0dcf3f3a5d8ccf3c1d8c2840ea27 introduced additional tests into MicrodumpWriterTest, two of which throw warnings which break "make check" under default settings on Linux, because the Makefiles are configured with -Werror=sign-compare. This patch just makes the signedness of the assertion arguments match. Change-Id: Ib522f44205c84f91bc9b93276fad60ebbf005f60 Reviewed-on: https://chromium-review.googlesource.com/418938 Reviewed-by: Tobias Sargeant <[email protected]> Reviewed-by: Mike Frysinger <[email protected]>
C++
bsd-3-clause
bittorrent/breakpad,bittorrent/breakpad,bittorrent/breakpad,bittorrent/breakpad,bittorrent/breakpad,bittorrent/breakpad,bittorrent/breakpad
b8f9e611ff3a8a1938dae9d6a95c9d3e00b64ea2
src/components/hmi_message_handler/test/hmi_message_handler_impl_test.cc
src/components/hmi_message_handler/test/hmi_message_handler_impl_test.cc
/* * Copyright (c) 2015, Ford Motor Company * 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 Ford Motor Company nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "gtest/gtest.h" #include "application_manager/message.h" #include "hmi_message_handler/hmi_message_handler_impl.h" #include "hmi_message_handler/messagebroker_adapter.h" #include "hmi_message_handler/mock_hmi_message_observer.h" #include "hmi_message_handler/mock_hmi_message_handler_settings.h" #include "hmi_message_handler/mock_hmi_message_adapter_impl.h" namespace test { namespace components { namespace hmi_message_handler_test { using ::testing::ReturnRef; using ::testing::_; class HMIMessageHandlerImplTest : public ::testing::Test { public: HMIMessageHandlerImplTest() : mb_adapter_(NULL) , hmi_handler_(NULL) , mock_hmi_message_observer_(NULL) {} protected: hmi_message_handler::MessageBrokerAdapter* mb_adapter_; hmi_message_handler::HMIMessageHandlerImpl* hmi_handler_; MockHMIMessageObserver* mock_hmi_message_observer_; testing::NiceMock<MockHMIMessageHandlerSettings> mock_hmi_message_handler_settings; const uint64_t stack_size = 1000u; virtual void SetUp() OVERRIDE { ON_CALL(mock_hmi_message_handler_settings, thread_min_stack_size()) .WillByDefault(ReturnRef(stack_size)); hmi_handler_ = new hmi_message_handler::HMIMessageHandlerImpl( mock_hmi_message_handler_settings); ASSERT_TRUE(NULL != hmi_handler_); mb_adapter_ = new hmi_message_handler::MessageBrokerAdapter( hmi_handler_, "localhost", 22); ASSERT_TRUE(NULL != mb_adapter_); mock_hmi_message_observer_ = new MockHMIMessageObserver(); ASSERT_TRUE(NULL != mock_hmi_message_observer_); hmi_handler_->set_message_observer(mock_hmi_message_observer_); EXPECT_TRUE(NULL != hmi_handler_->observer()); } void TearDown() OVERRIDE { hmi_handler_->set_message_observer(NULL); delete mock_hmi_message_observer_; delete hmi_handler_; delete mb_adapter_; } hmi_message_handler::MessageSharedPointer CreateMessage() { // The ServiceType doesn't really matter return new application_manager::Message( protocol_handler::MessagePriority::FromServiceType( protocol_handler::ServiceType::kInvalidServiceType)); } }; TEST_F(HMIMessageHandlerImplTest, OnErrorSending_EmptyMessage_OnErrorSendingProceeded) { // Arrange hmi_message_handler::MessageSharedPointer empty_message; EXPECT_CALL(*mock_hmi_message_observer_, OnErrorSending(empty_message)); // Act hmi_handler_->OnErrorSending(empty_message); } TEST_F(HMIMessageHandlerImplTest, OnErrorSending_NotEmptyMessage_ExpectOnErrorSendingProceeded) { // Arrange utils::SharedPtr<application_manager::Message> message = CreateMessage(); EXPECT_CALL(*mock_hmi_message_observer_, OnErrorSending(message)); // Act hmi_handler_->OnErrorSending(message); } TEST_F(HMIMessageHandlerImplTest, OnErrorSending_InvalidObserver_Cancelled) { // Arrange utils::SharedPtr<application_manager::Message> message = CreateMessage(); hmi_handler_->set_message_observer(NULL); EXPECT_CALL(*mock_hmi_message_observer_, OnErrorSending(_)).Times(0); // Act hmi_handler_->OnErrorSending(message); } TEST_F(HMIMessageHandlerImplTest, AddHMIMessageAdapter_AddExistedAdapter_ExpectAdded) { // Check before action EXPECT_TRUE(hmi_handler_->message_adapters().empty()); // Act hmi_handler_->AddHMIMessageAdapter(mb_adapter_); // Check after action EXPECT_EQ(1u, hmi_handler_->message_adapters().size()); } TEST_F(HMIMessageHandlerImplTest, AddHMIMessageAdapter_AddUnexistedAdapter_ExpectNotAdded) { // Check before action EXPECT_TRUE(hmi_handler_->message_adapters().empty()); // Act mb_adapter_ = NULL; hmi_handler_->AddHMIMessageAdapter(mb_adapter_); // Check adapter not added EXPECT_TRUE(hmi_handler_->message_adapters().empty()); } TEST_F(HMIMessageHandlerImplTest, RemoveHMIMessageAdapter_ExpectRemoved) { // Arrange hmi_handler_->AddHMIMessageAdapter(mb_adapter_); // Act hmi_handler_->RemoveHMIMessageAdapter(mb_adapter_); // Check after action EXPECT_TRUE(hmi_handler_->message_adapters().empty()); } // TODO(atimchenko) SDLOPEN-44 Wrong message to observer TEST_F(HMIMessageHandlerImplTest, DISABLED_OnMessageReceived_ValidObserver_Success) { hmi_message_handler::MessageSharedPointer message = CreateMessage(); EXPECT_CALL(*mock_hmi_message_observer_, OnMessageReceived(message)); hmi_handler_->OnMessageReceived(message); // Wait for the message to be processed hmi_handler_->messages_from_hmi()->WaitDumpQueue(); } TEST_F(HMIMessageHandlerImplTest, OnMessageReceived_InvalidObserver_Cancelled) { hmi_message_handler::MessageSharedPointer message = CreateMessage(); EXPECT_CALL(*mock_hmi_message_observer_, OnMessageReceived(_)).Times(0); // Make the observer invalid hmi_handler_->set_message_observer(NULL); hmi_handler_->OnMessageReceived(message); hmi_handler_->messages_from_hmi()->WaitDumpQueue(); } TEST_F(HMIMessageHandlerImplTest, SendMessageToHMI_Success) { hmi_message_handler::MessageSharedPointer message = CreateMessage(); MockHMIMessageAdapterImpl message_adapter(hmi_handler_); EXPECT_CALL(message_adapter, SendMessageToHMI(message)); hmi_handler_->AddHMIMessageAdapter(&message_adapter); hmi_handler_->SendMessageToHMI(message); // Wait for the message to be processed hmi_handler_->messages_to_hmi()->WaitDumpQueue(); testing::Mock::AsyncVerifyAndClearExpectations(100); } } // namespace hmi_message_handler_test } // namespace components } // namespace test
/* * Copyright (c) 2015, Ford Motor Company * 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 Ford Motor Company nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "gtest/gtest.h" #include "application_manager/message.h" #include "hmi_message_handler/hmi_message_handler_impl.h" #include "hmi_message_handler/messagebroker_adapter.h" #include "hmi_message_handler/mock_hmi_message_observer.h" #include "hmi_message_handler/mock_hmi_message_handler_settings.h" #include "hmi_message_handler/mock_hmi_message_adapter_impl.h" #include "utils/test_async_waiter.h" namespace test { namespace components { namespace hmi_message_handler_test { using ::testing::ReturnRef; using ::testing::_; class HMIMessageHandlerImplTest : public ::testing::Test { public: HMIMessageHandlerImplTest() : mb_adapter_(NULL) , hmi_handler_(NULL) , mock_hmi_message_observer_(NULL) {} protected: hmi_message_handler::MessageBrokerAdapter* mb_adapter_; hmi_message_handler::HMIMessageHandlerImpl* hmi_handler_; MockHMIMessageObserver* mock_hmi_message_observer_; testing::NiceMock<MockHMIMessageHandlerSettings> mock_hmi_message_handler_settings; const uint64_t stack_size = 1000u; virtual void SetUp() OVERRIDE { ON_CALL(mock_hmi_message_handler_settings, thread_min_stack_size()) .WillByDefault(ReturnRef(stack_size)); hmi_handler_ = new hmi_message_handler::HMIMessageHandlerImpl( mock_hmi_message_handler_settings); ASSERT_TRUE(NULL != hmi_handler_); mb_adapter_ = new hmi_message_handler::MessageBrokerAdapter( hmi_handler_, "localhost", 22); ASSERT_TRUE(NULL != mb_adapter_); mock_hmi_message_observer_ = new MockHMIMessageObserver(); ASSERT_TRUE(NULL != mock_hmi_message_observer_); hmi_handler_->set_message_observer(mock_hmi_message_observer_); EXPECT_TRUE(NULL != hmi_handler_->observer()); } void TearDown() OVERRIDE { hmi_handler_->set_message_observer(NULL); delete mock_hmi_message_observer_; delete hmi_handler_; delete mb_adapter_; } hmi_message_handler::MessageSharedPointer CreateMessage() { // The ServiceType doesn't really matter return new application_manager::Message( protocol_handler::MessagePriority::FromServiceType( protocol_handler::ServiceType::kInvalidServiceType)); } }; TEST_F(HMIMessageHandlerImplTest, OnErrorSending_EmptyMessage_OnErrorSendingProceeded) { // Arrange hmi_message_handler::MessageSharedPointer empty_message; EXPECT_CALL(*mock_hmi_message_observer_, OnErrorSending(empty_message)); // Act hmi_handler_->OnErrorSending(empty_message); } TEST_F(HMIMessageHandlerImplTest, OnErrorSending_NotEmptyMessage_ExpectOnErrorSendingProceeded) { // Arrange utils::SharedPtr<application_manager::Message> message = CreateMessage(); EXPECT_CALL(*mock_hmi_message_observer_, OnErrorSending(message)); // Act hmi_handler_->OnErrorSending(message); } TEST_F(HMIMessageHandlerImplTest, OnErrorSending_InvalidObserver_Cancelled) { // Arrange utils::SharedPtr<application_manager::Message> message = CreateMessage(); hmi_handler_->set_message_observer(NULL); EXPECT_CALL(*mock_hmi_message_observer_, OnErrorSending(_)).Times(0); // Act hmi_handler_->OnErrorSending(message); } TEST_F(HMIMessageHandlerImplTest, AddHMIMessageAdapter_AddExistedAdapter_ExpectAdded) { // Check before action EXPECT_TRUE(hmi_handler_->message_adapters().empty()); // Act hmi_handler_->AddHMIMessageAdapter(mb_adapter_); // Check after action EXPECT_EQ(1u, hmi_handler_->message_adapters().size()); } TEST_F(HMIMessageHandlerImplTest, AddHMIMessageAdapter_AddUnexistedAdapter_ExpectNotAdded) { // Check before action EXPECT_TRUE(hmi_handler_->message_adapters().empty()); // Act mb_adapter_ = NULL; hmi_handler_->AddHMIMessageAdapter(mb_adapter_); // Check adapter not added EXPECT_TRUE(hmi_handler_->message_adapters().empty()); } TEST_F(HMIMessageHandlerImplTest, RemoveHMIMessageAdapter_ExpectRemoved) { // Arrange hmi_handler_->AddHMIMessageAdapter(mb_adapter_); // Act hmi_handler_->RemoveHMIMessageAdapter(mb_adapter_); // Check after action EXPECT_TRUE(hmi_handler_->message_adapters().empty()); } // TODO(atimchenko) SDLOPEN-44 Wrong message to observer TEST_F(HMIMessageHandlerImplTest, DISABLED_OnMessageReceived_ValidObserver_Success) { hmi_message_handler::MessageSharedPointer message = CreateMessage(); EXPECT_CALL(*mock_hmi_message_observer_, OnMessageReceived(message)); hmi_handler_->OnMessageReceived(message); // Wait for the message to be processed hmi_handler_->messages_from_hmi()->WaitDumpQueue(); } TEST_F(HMIMessageHandlerImplTest, OnMessageReceived_InvalidObserver_Cancelled) { hmi_message_handler::MessageSharedPointer message = CreateMessage(); EXPECT_CALL(*mock_hmi_message_observer_, OnMessageReceived(_)).Times(0); // Make the observer invalid hmi_handler_->set_message_observer(NULL); hmi_handler_->OnMessageReceived(message); hmi_handler_->messages_from_hmi()->WaitDumpQueue(); } TEST_F(HMIMessageHandlerImplTest, SendMessageToHMI_Success) { hmi_message_handler::MessageSharedPointer message = CreateMessage(); TestAsyncWaiter waiter; MockHMIMessageAdapterImpl message_adapter(hmi_handler_); EXPECT_CALL(message_adapter, SendMessageToHMI(message)) .WillOnce(NotifyTestAsyncWaiter(&waiter)); hmi_handler_->AddHMIMessageAdapter(&message_adapter); hmi_handler_->SendMessageToHMI(message); // Wait for the message to be processed hmi_handler_->messages_to_hmi()->WaitDumpQueue(); EXPECT_TRUE(waiter.WaitFor(1, 1000)); } } // namespace hmi_message_handler_test } // namespace components } // namespace test
Refactor HMIMessageHandler test to use TestAsyncWaiter
Refactor HMIMessageHandler test to use TestAsyncWaiter Related tasks APPLINK-30588 APPLINK-30977
C++
bsd-3-clause
smartdevicelink/sdl_core,smartdevicelink/sdl_core,APCVSRepo/sdl_core,smartdevicelink/sdl_core,APCVSRepo/sdl_core,APCVSRepo/sdl_core,LuxoftAKutsan/sdl_core,LuxoftAKutsan/sdl_core,LuxoftAKutsan/sdl_core,LuxoftAKutsan/sdl_core,LuxoftAKutsan/sdl_core,smartdevicelink/sdl_core,LuxoftAKutsan/sdl_core,APCVSRepo/sdl_core,APCVSRepo/sdl_core
c557e675af34ff31ff91bd8fcd16940ac9bf4b2e
xchainer/backprop.cc
xchainer/backprop.cc
#include "xchainer/backprop.h" #include <memory> #include <queue> #include <set> #include <unordered_map> #include <gsl/gsl> #include <nonstd/optional.hpp> #include "xchainer/array.h" #include "xchainer/array_node.h" #include "xchainer/op_node.h" namespace xchainer { namespace { using PreviousNodeMap = std::unordered_map<const OpNode*, std::shared_ptr<ArrayNode>>; } // namespace void Backward(Array& output) { std::shared_ptr<ArrayNode> node = output.mutable_node(); auto cmp = [](std::shared_ptr<const OpNode> lhs, std::shared_ptr<const OpNode> rhs) { return lhs->rank() < rhs->rank(); }; std::priority_queue<std::shared_ptr<const OpNode>, std::vector<std::shared_ptr<const OpNode>>, decltype(cmp)> candidate_nodes(cmp); std::set<const OpNode*> seen_set; PreviousNodeMap previous_node_map; // Initialize the output gradient if needed. if (!node->grad()) { node->set_grad(Array::OnesLike(output)); } // Push the OpNode next to the output's ArrayNode to the priority queue. std::shared_ptr<const OpNode> op_node = node->next_node(); if (op_node) { const OpNode* op_node_ptr = op_node.get(); candidate_nodes.push(op_node); seen_set.insert(op_node_ptr); previous_node_map.emplace(op_node_ptr, node); } // Iteratively backprop. while (!candidate_nodes.empty()) { std::shared_ptr<const OpNode> op_node = candidate_nodes.top(); candidate_nodes.pop(); // TODO(takagi): Properly handle the case that the same array is passed multiple times as inputs in the same function (e.g. an // expression like f(x, x)) // Get the OpNode's previous node. auto it = previous_node_map.find(op_node.get()); assert(it != previous_node_map.end()); std::shared_ptr<ArrayNode> previous_node = it->second; // Get the previous node's gradient. const nonstd::optional<Array>& gy = previous_node->grad(); assert(gy); // Compute the OpNode's next gradients. std::vector<nonstd::optional<Array>> gxs; for (auto& backward_function : op_node->backward_functions()) { if (backward_function) { Array gx = backward_function(*gy); gxs.emplace_back(std::move(gx)); } else { gxs.emplace_back(nonstd::nullopt); } } // Release the intermediate node's gradient. previous_node->ClearGrad(); gsl::span<const std::shared_ptr<ArrayNode>> next_nodes = op_node->next_nodes(); auto next_size = next_nodes.size(); for (decltype(next_size) i = 0; i < next_size; ++i) { nonstd::optional<Array> gx = std::move(gxs[i]); std::shared_ptr<ArrayNode> next_node = next_nodes[i]; if (gx) { // Accumulate the Opnode's next gradient. const nonstd::optional<Array>& grad = next_node->grad(); if (grad) { next_node->set_grad(*grad + *gx); } else { next_node->set_grad(std::move(*gx)); } // Push the next OpNode to the priority queue. std::shared_ptr<const OpNode> next_op_node = next_node->next_node(); if (next_op_node) { const OpNode* next_op_node_ptr = next_op_node.get(); if (seen_set.find(next_op_node_ptr) == seen_set.end()) { candidate_nodes.push(next_op_node); seen_set.insert(next_op_node_ptr); previous_node_map.emplace(next_op_node_ptr, next_node); } } } } } } } // namespace xchainer
#include "xchainer/backprop.h" #include <memory> #include <queue> #include <set> #include <unordered_map> #include <gsl/gsl> #include <nonstd/optional.hpp> #include "xchainer/array.h" #include "xchainer/array_node.h" #include "xchainer/op_node.h" namespace xchainer { namespace { auto cmp = [](std::shared_ptr<const OpNode> lhs, std::shared_ptr<const OpNode> rhs) { return lhs->rank() < rhs->rank(); }; class BackwardImpl { using CandidateOpNodes = std::priority_queue<std::shared_ptr<const OpNode>, std::vector<std::shared_ptr<const OpNode>>, decltype(cmp)>; using PreviousArrayNodeMap = std::unordered_map<std::shared_ptr<const OpNode>, std::shared_ptr<ArrayNode>>; public: BackwardImpl() : candidate_op_nodes_(cmp) {}; void run(Array& output) { std::shared_ptr<ArrayNode> array_node = output.mutable_node(); if (!array_node->grad()) { array_node->set_grad(Array::OnesLike(output)); } BuildCandidateOpNodes(array_node); ProcessOpNodes(); }; private: void BuildCandidateOpNodes(std::shared_ptr<ArrayNode> array_node) { std::shared_ptr<const OpNode> op_node = array_node->next_node(); if (op_node) { PushOpNode(op_node); InsertPreviousArrayNode(op_node, array_node); auto next_array_nodes = op_node->next_nodes(); auto backward_functions = op_node->backward_functions(); auto next_size = next_array_nodes.size(); for (decltype(next_size) i = 0; i < next_size; ++i) { if (backward_functions[i]) { BuildCandidateOpNodes(next_array_nodes[i]); } } } } std::vector<nonstd::optional<Array>> ComputeNextGradients() { std::shared_ptr<const OpNode> op_node = TopOpNode(); std::shared_ptr<ArrayNode> previous_array_node = PreviousArrayNode(op_node); nonstd::optional<Array> gy = previous_array_node->grad(); assert(gy); previous_array_node->ClearGrad(); std::vector<nonstd::optional<Array>> gxs; for (auto& backward_function : op_node->backward_functions()) { if (backward_function) { Array gx = backward_function(*gy); gxs.emplace_back(std::move(gx)); } else { gxs.emplace_back(nonstd::nullopt); } } return gxs; } void AccumulateNextGradients(std::vector<nonstd::optional<Array>> gxs) { std::shared_ptr<const OpNode> op_node = TopOpNode(); gsl::span<const std::shared_ptr<ArrayNode>> next_nodes = op_node->next_nodes(); auto next_size = next_nodes.size(); for (decltype(next_size) i = 0; i < next_size; ++i) { nonstd::optional<Array> gx = std::move(gxs[i]); std::shared_ptr<ArrayNode> next_node = next_nodes[i]; if (gx) { const nonstd::optional<Array>& grad = next_node->grad(); if (grad) { next_node->set_grad(*grad + *gx); } else { next_node->set_grad(std::move(*gx)); } } } } void ProcessOpNodes() { while (!EmptyOpNodes()) { std::vector<nonstd::optional<Array>> gxs = ComputeNextGradients(); AccumulateNextGradients(gxs); PopOpNode(); } } const std::shared_ptr<const OpNode>& TopOpNode() const { return candidate_op_nodes_.top(); } bool EmptyOpNodes() const noexcept { return candidate_op_nodes_.empty(); } void PushOpNode(std::shared_ptr<const OpNode> op_node) { candidate_op_nodes_.push(std::move(op_node)); } void PopOpNode() { candidate_op_nodes_.pop(); } std::shared_ptr<ArrayNode> PreviousArrayNode(std::shared_ptr<const OpNode> op_node) const { auto it = previous_array_node_map_.find(op_node); assert(it != previous_array_node_map_.end()); return it->second; } void InsertPreviousArrayNode(std::shared_ptr<const OpNode> op_node, std::shared_ptr<ArrayNode> array_node) { previous_array_node_map_.emplace(std::move(op_node), std::move(array_node)); } CandidateOpNodes candidate_op_nodes_; PreviousArrayNodeMap previous_array_node_map_; }; } // namespace void Backward(Array& output) { BackwardImpl impl; impl.run(output); } } // namespace xchainer
Reimplement with class
Reimplement with class
C++
mit
jnishi/chainer,keisuke-umezawa/chainer,niboshi/chainer,hvy/chainer,niboshi/chainer,jnishi/chainer,wkentaro/chainer,okuta/chainer,wkentaro/chainer,ktnyt/chainer,ktnyt/chainer,pfnet/chainer,wkentaro/chainer,chainer/chainer,chainer/chainer,niboshi/chainer,okuta/chainer,chainer/chainer,keisuke-umezawa/chainer,jnishi/chainer,hvy/chainer,chainer/chainer,wkentaro/chainer,niboshi/chainer,keisuke-umezawa/chainer,hvy/chainer,keisuke-umezawa/chainer,okuta/chainer,ktnyt/chainer,ktnyt/chainer,okuta/chainer,hvy/chainer,jnishi/chainer,tkerola/chainer
a4bd3427cd571ef5b6e7f6476b61e0aa5195cfc1
xchainer/backprop.cc
xchainer/backprop.cc
#include "xchainer/backprop.h" #include <memory> #include <queue> #include <unordered_map> #include <gsl/gsl> #include <nonstd/optional.hpp> #include "xchainer/array.h" #include "xchainer/array_node.h" #include "xchainer/op_node.h" namespace xchainer { namespace { auto cmp = [](std::shared_ptr<const OpNode> lhs, std::shared_ptr<const OpNode> rhs) { return lhs->rank() < rhs->rank(); }; class BackwardImpl { using CandidateOpNodes = std::priority_queue<std::shared_ptr<const OpNode>, std::vector<std::shared_ptr<const OpNode>>, decltype(cmp)>; using PreviousArrayNodeMap = std::unordered_map<std::shared_ptr<const OpNode>, std::shared_ptr<ArrayNode>>; public: BackwardImpl() : candidate_op_nodes_(cmp) {}; void run(Array& output) { std::shared_ptr<ArrayNode> array_node = output.mutable_node(); if (!array_node->grad()) { array_node->set_grad(Array::OnesLike(output)); } BuildCandidateOpNodes(array_node); ProcessOpNodes(); }; private: void BuildCandidateOpNodes(std::shared_ptr<ArrayNode> array_node) { std::shared_ptr<const OpNode> op_node = array_node->next_node(); if (op_node) { PushOpNode(op_node); InsertPreviousArrayNode(op_node, array_node); auto next_array_nodes = op_node->next_nodes(); auto backward_functions = op_node->backward_functions(); auto next_size = next_array_nodes.size(); for (decltype(next_size) i = 0; i < next_size; ++i) { if (backward_functions[i]) { BuildCandidateOpNodes(next_array_nodes[i]); } } } } std::vector<nonstd::optional<Array>> ComputeNextGradients() { std::shared_ptr<const OpNode> op_node = TopOpNode(); std::shared_ptr<ArrayNode> previous_array_node = PreviousArrayNode(op_node); nonstd::optional<Array> gy = previous_array_node->grad(); assert(gy); previous_array_node->ClearGrad(); std::vector<nonstd::optional<Array>> gxs; for (auto& backward_function : op_node->backward_functions()) { if (backward_function) { gxs.emplace_back(backward_function(*gy)); } else { gxs.emplace_back(nonstd::nullopt); } } return gxs; } void AccumulateNextGradients(std::vector<nonstd::optional<Array>> gxs) { std::shared_ptr<const OpNode> op_node = TopOpNode(); gsl::span<const std::shared_ptr<ArrayNode>> next_array_nodes = op_node->next_nodes(); auto next_size = next_array_nodes.size(); for (decltype(next_size) i = 0; i < next_size; ++i) { nonstd::optional<Array> gx = std::move(gxs[i]); std::shared_ptr<ArrayNode> next_array_node = next_array_nodes[i]; if (gx) { const nonstd::optional<Array>& grad = next_array_node->grad(); if (grad) { next_array_node->set_grad(*grad + *gx); } else { next_array_node->set_grad(std::move(*gx)); } } } } void ProcessOpNodes() { while (!EmptyOpNodes()) { std::vector<nonstd::optional<Array>> gxs = ComputeNextGradients(); AccumulateNextGradients(gxs); PopOpNode(); } } const std::shared_ptr<const OpNode>& TopOpNode() const { return candidate_op_nodes_.top(); } bool EmptyOpNodes() const noexcept { return candidate_op_nodes_.empty(); } void PushOpNode(std::shared_ptr<const OpNode> op_node) { candidate_op_nodes_.push(std::move(op_node)); } void PopOpNode() { candidate_op_nodes_.pop(); } std::shared_ptr<ArrayNode> PreviousArrayNode(std::shared_ptr<const OpNode> op_node) const { auto it = previous_array_node_map_.find(op_node); assert(it != previous_array_node_map_.end()); return it->second; } void InsertPreviousArrayNode(std::shared_ptr<const OpNode> op_node, std::shared_ptr<ArrayNode> array_node) { previous_array_node_map_.emplace(std::move(op_node), std::move(array_node)); } CandidateOpNodes candidate_op_nodes_; PreviousArrayNodeMap previous_array_node_map_; }; } // namespace void Backward(Array& output) { BackwardImpl impl; impl.run(output); } } // namespace xchainer
#include "xchainer/backprop.h" #include <memory> #include <queue> #include <unordered_map> #include <gsl/gsl> #include <nonstd/optional.hpp> #include "xchainer/array.h" #include "xchainer/array_node.h" #include "xchainer/op_node.h" namespace xchainer { namespace { auto cmp = [](std::shared_ptr<const OpNode> lhs, std::shared_ptr<const OpNode> rhs) { return lhs->rank() < rhs->rank(); }; class BackwardImpl { using CandidateOpNodes = std::priority_queue<std::shared_ptr<const OpNode>, std::vector<std::shared_ptr<const OpNode>>, decltype(cmp)>; using PreviousArrayNodeMap = std::unordered_map<std::shared_ptr<const OpNode>, std::shared_ptr<ArrayNode>>; public: BackwardImpl() : candidate_op_nodes_(cmp) {}; void run(Array& output) { std::shared_ptr<ArrayNode> array_node = output.mutable_node(); if (!array_node->grad()) { array_node->set_grad(Array::OnesLike(output)); } BuildCandidateOpNodes(array_node); ProcessOpNodes(); }; private: void BuildCandidateOpNodes(std::shared_ptr<ArrayNode> array_node) { std::shared_ptr<const OpNode> op_node = array_node->next_node(); if (op_node) { PushOpNode(op_node); InsertPreviousArrayNode(op_node, array_node); auto next_array_nodes = op_node->next_nodes(); auto backward_functions = op_node->backward_functions(); auto next_size = next_array_nodes.size(); for (decltype(next_size) i = 0; i < next_size; ++i) { if (backward_functions[i]) { BuildCandidateOpNodes(next_array_nodes[i]); } } } } std::vector<nonstd::optional<Array>> ComputeNextGradients() { std::shared_ptr<const OpNode> op_node = TopOpNode(); std::shared_ptr<ArrayNode> previous_array_node = PreviousArrayNode(op_node); nonstd::optional<Array> gy = previous_array_node->grad(); assert(gy); previous_array_node->ClearGrad(); std::vector<nonstd::optional<Array>> gxs; for (auto& backward_function : op_node->backward_functions()) { if (backward_function) { gxs.emplace_back(backward_function(*gy)); } else { gxs.emplace_back(nonstd::nullopt); } } return gxs; } void AccumulateNextGradients(std::vector<nonstd::optional<Array>> gxs) { std::shared_ptr<const OpNode> op_node = TopOpNode(); gsl::span<const std::shared_ptr<ArrayNode>> next_array_nodes = op_node->next_nodes(); auto next_size = next_array_nodes.size(); for (decltype(next_size) i = 0; i < next_size; ++i) { const nonstd::optional<Array>& gx = gxs[i]; std::shared_ptr<ArrayNode> next_array_node = next_array_nodes[i]; if (gx) { const nonstd::optional<Array>& grad = next_array_node->grad(); if (grad) { next_array_node->set_grad(*grad + *gx); } else { next_array_node->set_grad(std::move(*gx)); } } } } void ProcessOpNodes() { while (!EmptyOpNodes()) { std::vector<nonstd::optional<Array>> gxs = ComputeNextGradients(); AccumulateNextGradients(gxs); PopOpNode(); } } const std::shared_ptr<const OpNode>& TopOpNode() const { return candidate_op_nodes_.top(); } bool EmptyOpNodes() const noexcept { return candidate_op_nodes_.empty(); } void PushOpNode(std::shared_ptr<const OpNode> op_node) { candidate_op_nodes_.push(std::move(op_node)); } void PopOpNode() { candidate_op_nodes_.pop(); } std::shared_ptr<ArrayNode> PreviousArrayNode(std::shared_ptr<const OpNode> op_node) const { auto it = previous_array_node_map_.find(op_node); assert(it != previous_array_node_map_.end()); return it->second; } void InsertPreviousArrayNode(std::shared_ptr<const OpNode> op_node, std::shared_ptr<ArrayNode> array_node) { previous_array_node_map_.emplace(std::move(op_node), std::move(array_node)); } CandidateOpNodes candidate_op_nodes_; PreviousArrayNodeMap previous_array_node_map_; }; } // namespace void Backward(Array& output) { BackwardImpl impl; impl.run(output); } } // namespace xchainer
Use const&
Use const&
C++
mit
niboshi/chainer,hvy/chainer,okuta/chainer,okuta/chainer,wkentaro/chainer,ktnyt/chainer,wkentaro/chainer,niboshi/chainer,chainer/chainer,chainer/chainer,jnishi/chainer,jnishi/chainer,tkerola/chainer,niboshi/chainer,hvy/chainer,niboshi/chainer,wkentaro/chainer,chainer/chainer,keisuke-umezawa/chainer,jnishi/chainer,keisuke-umezawa/chainer,ktnyt/chainer,wkentaro/chainer,pfnet/chainer,okuta/chainer,hvy/chainer,keisuke-umezawa/chainer,keisuke-umezawa/chainer,chainer/chainer,jnishi/chainer,hvy/chainer,ktnyt/chainer,ktnyt/chainer,okuta/chainer
551cf11ab2778d67a0604d967d2d3624259aaad4
xine/audiooutput.cpp
xine/audiooutput.cpp
/* This file is part of the KDE project Copyright (C) 2006 Tim Beaulen <[email protected]> Copyright (C) 2006-2007 Matthias Kretz <[email protected]> This program 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; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "audiooutput.h" #include <QVector> #include <QtCore/QCoreApplication> #include <sys/ioctl.h> #include <iostream> #include <QSet> #include "mediaobject.h" #include "backend.h" #include "events.h" #include "wirecall.h" #include "xineengine.h" #include "xinethread.h" #include "keepreference.h" #include <xine/audio_out.h> #undef assert typedef QPair<QByteArray, QString> PhononDeviceAccess; typedef QList<PhononDeviceAccess> PhononDeviceAccessList; Q_DECLARE_METATYPE(PhononDeviceAccessList) namespace Phonon { namespace Xine { AudioOutput::AudioOutput(QObject *parent) : AbstractAudioOutput(new AudioOutputXT, parent) { } AudioOutput::~AudioOutput() { //debug() << Q_FUNC_INFO ; } AudioOutputXT::~AudioOutputXT() { if (m_audioPort) { xine_close_audio_driver(m_xine, m_audioPort); m_audioPort = 0; debug() << Q_FUNC_INFO << "----------------------------------------------- audio_port destroyed"; } } qreal AudioOutput::volume() const { return m_volume; } int AudioOutput::outputDevice() const { return m_device.index(); } void AudioOutput::setVolume(qreal newVolume) { m_volume = newVolume; int xinevolume = static_cast<int>(m_volume * 100); if (xinevolume > 200) { xinevolume = 200; } else if (xinevolume < 0) { xinevolume = 0; } upstreamEvent(new UpdateVolumeEvent(xinevolume)); emit volumeChanged(m_volume); } xine_audio_port_t *AudioOutputXT::audioPort() const { return m_audioPort; } static QByteArray audioDriverFor(const QByteArray &driver) { if (driver == "alsa" || driver == "oss" || driver == "pulseaudio" || driver == "esd" || driver == "arts" || driver == "jack") { return driver; } return QByteArray(); } static bool lookupConfigEntry(xine_t *xine, const char *key, xine_cfg_entry_t *entry, const char *driver) { if(!xine_config_lookup_entry(xine, key, entry)) { // the config key is not registered yet - it is registered when the output // plugin is opened. So we open the plugin and close it again, then we can set the // setting. :( xine_audio_port_t *port = xine_open_audio_driver(xine, driver, 0); if (port) { xine_close_audio_driver(xine, port); // port == 0 does not have to be fatal, since it might be only the default device // that cannot be opened } // now the config key should be registered if(!xine_config_lookup_entry(xine, key, entry)) { qWarning() << "cannot configure the device on Xine's" << driver << "output plugin"; return false; } } return true; } xine_audio_port_t *AudioOutput::createPort(const AudioOutputDevice &deviceDesc) { K_XT(AudioOutput); xine_audio_port_t *port = 0; const QVariant &deviceAccessListVariant = deviceDesc.property("deviceAccessList"); if (deviceAccessListVariant.isValid()) { const PhononDeviceAccessList &deviceAccessList = qvariant_cast<PhononDeviceAccessList>(deviceAccessListVariant); foreach (const PhononDeviceAccess &access, deviceAccessList) { const QByteArray &outputPlugin = audioDriverFor(access.first); if (outputPlugin.isEmpty()) { continue; } const QString &handle = access.second; if (outputPlugin == "alsa") { xine_cfg_entry_t deviceConfig; if (!lookupConfigEntry(xt->m_xine, "audio.device.alsa_default_device", &deviceConfig, "alsa")) { continue; } Q_ASSERT(deviceConfig.type == XINE_CONFIG_TYPE_STRING); QByteArray deviceStr = handle.toUtf8(); deviceConfig.str_value = deviceStr.data(); xine_config_update_entry(xt->m_xine, &deviceConfig); const int err = xine_config_lookup_entry(xt->m_xine, "audio.device.alsa_front_device", &deviceConfig); Q_ASSERT(err); Q_UNUSED(err); Q_ASSERT(deviceConfig.type == XINE_CONFIG_TYPE_STRING); deviceConfig.str_value = deviceStr.data(); xine_config_update_entry(xt->m_xine, &deviceConfig); port = xine_open_audio_driver(xt->m_xine, "alsa", 0); if (port) { debug() << Q_FUNC_INFO << "use ALSA device: " << handle; debug() << Q_FUNC_INFO << "----------------------------------------------- audio_port created"; return port; } } else if (outputPlugin == "pulseaudio") { xine_cfg_entry_t deviceConfig; if (!lookupConfigEntry(xt->m_xine, "audio.pulseaudio_device", &deviceConfig, "pulseaudio")) { continue; } Q_ASSERT(deviceConfig.type == XINE_CONFIG_TYPE_STRING); QByteArray deviceStr = handle.toUtf8(); deviceConfig.str_value = deviceStr.data(); xine_config_update_entry(xt->m_xine, &deviceConfig); port = xine_open_audio_driver(xt->m_xine, "pulseaudio", 0); if (port) { debug() << Q_FUNC_INFO << "use PulseAudio: " << handle; debug() << Q_FUNC_INFO << "----------------------------------------------- audio_port created"; return port; } } else if (outputPlugin == "oss") { xine_cfg_entry_t deviceConfig; if (!lookupConfigEntry(xt->m_xine, "audio.device.oss_device_name", &deviceConfig, "oss")) { continue; } Q_ASSERT(deviceConfig.type == XINE_CONFIG_TYPE_ENUM); deviceConfig.num_value = 0; xine_config_update_entry(xt->m_xine, &deviceConfig); if(!xine_config_lookup_entry(xt->m_xine, "audio.device.oss_device_number", &deviceConfig)) { qWarning() << "cannot set the OSS device on Xine's OSS output plugin"; return 0; } Q_ASSERT(deviceConfig.type == XINE_CONFIG_TYPE_NUM); const QByteArray &deviceStr = handle.toUtf8(); char lastChar = deviceStr[deviceStr.length() - 1]; int deviceNumber = -1; if (lastChar >= '0' || lastChar <= '9') { deviceNumber = lastChar - '0'; char lastChar = deviceStr[deviceStr.length() - 2]; if (lastChar >= '0' || lastChar <= '9') { deviceNumber += 10 * (lastChar - '0'); } } deviceConfig.num_value = deviceNumber; xine_config_update_entry(xt->m_xine, &deviceConfig); port = xine_open_audio_driver(xt->m_xine, "oss", 0); if (port) { debug() << Q_FUNC_INFO << "use OSS device: " << handle; debug() << Q_FUNC_INFO << "----------------------------------------------- audio_port created"; return port; } } } } QVariant v = deviceDesc.property("driver"); if (!v.isValid()) { const QByteArray &outputPlugin = Backend::audioDriverFor(deviceDesc.index()); debug() << Q_FUNC_INFO << "use output plugin:" << outputPlugin; port = xine_open_audio_driver(xt->m_xine, outputPlugin.constData(), 0); } else { const QByteArray &outputPlugin = v.toByteArray(); v = deviceDesc.property("deviceIds"); const QStringList &deviceIds = v.toStringList(); if (deviceIds.isEmpty()) { return 0; } //debug() << Q_FUNC_INFO << outputPlugin << alsaDevices; if (outputPlugin == "alsa") { foreach (const QString &device, deviceIds) { xine_cfg_entry_t deviceConfig; if (!lookupConfigEntry(xt->m_xine, "audio.device.alsa_default_device", &deviceConfig, "alsa")) { return 0; } Q_ASSERT(deviceConfig.type == XINE_CONFIG_TYPE_STRING); QByteArray deviceStr = device.toUtf8(); deviceConfig.str_value = deviceStr.data(); xine_config_update_entry(xt->m_xine, &deviceConfig); int err = xine_config_lookup_entry(xt->m_xine, "audio.device.alsa_front_device", &deviceConfig); Q_ASSERT(err); Q_ASSERT(deviceConfig.type == XINE_CONFIG_TYPE_STRING); deviceConfig.str_value = deviceStr.data(); xine_config_update_entry(xt->m_xine, &deviceConfig); port = xine_open_audio_driver(xt->m_xine, "alsa", 0); if (port) { debug() << Q_FUNC_INFO << "use ALSA device: " << device; break; } } } else if (outputPlugin == "oss") { debug() << Q_FUNC_INFO << "use OSS output"; port = xine_open_audio_driver(xt->m_xine, "oss", 0); } } debug() << Q_FUNC_INFO << "----------------------------------------------- audio_port created"; return port; } bool AudioOutput::setOutputDevice(int newDevice) { return setOutputDevice(AudioOutputDevice::fromIndex(newDevice)); } bool AudioOutput::setOutputDevice(const AudioOutputDevice &newDevice) { K_XT(AudioOutput); if (!xt->m_xine) { // remeber the choice until we have a xine_t m_device = newDevice; return true; } xine_audio_port_t *port = createPort(newDevice); if (!port) { debug() << Q_FUNC_INFO << "new audio port is invalid"; return false; } KeepReference<> *keep = new KeepReference<>; keep->addObject(xt); keep->ready(); AudioOutputXT *newXt = new AudioOutputXT; newXt->m_audioPort = port; newXt->m_xine = xt->m_xine; m_threadSafeObject = newXt; m_device = newDevice; SourceNode *src = source(); if (src) { QList<WireCall> wireCall; QList<WireCall> unwireCall; wireCall << WireCall(src, this); unwireCall << WireCall(src, QExplicitlySharedDataPointer<SinkNodeXT>(xt)); QCoreApplication::postEvent(XineThread::instance(), new RewireEvent(wireCall, unwireCall)); graphChanged(); } return true; } void AudioOutput::xineEngineChanged() { K_XT(AudioOutput); if (xt->m_xine) { xine_audio_port_t *port = createPort(m_device); if (!port) { debug() << Q_FUNC_INFO << "stored audio port is invalid"; QMetaObject::invokeMethod(this, "audioDeviceFailed", Qt::QueuedConnection); return; } // our XT object is in a wirecall, better not delete it Q_ASSERT(xt->m_audioPort == 0); xt->m_audioPort = port; } } void AudioOutput::aboutToChangeXineEngine() { K_XT(AudioOutput); if (xt->m_audioPort) { AudioOutputXT *xt2 = new AudioOutputXT; xt2->m_xine = xt->m_xine; xt2->m_audioPort = xt->m_audioPort; xt->m_audioPort = 0; KeepReference<> *keep = new KeepReference<>; keep->addObject(xt2); keep->ready(); } } void AudioOutput::downstreamEvent(Event *e) { Q_ASSERT(e); QCoreApplication::sendEvent(this, e); SinkNode::downstreamEvent(e); } void AudioOutputXT::rewireTo(SourceNodeXT *source) { if (!source->audioOutputPort()) { return; } source->assert(); xine_post_wire_audio_port(source->audioOutputPort(), m_audioPort); source->assert(); SinkNodeXT::assert(); } bool AudioOutput::event(QEvent *ev) { switch (ev->type()) { case Event::AudioDeviceFailed: { ev->accept(); // we don't know for sure which AudioPort failed. We also can't know from the // information libxine makes available. So we have to just try the old device again if (setOutputDevice(m_device)) { return true; } // we really need a different output device QMetaObject::invokeMethod(this, "audioDeviceFailed", Qt::QueuedConnection); } return true; default: return AbstractAudioOutput::event(ev); } } void AudioOutput::graphChanged() { debug() << Q_FUNC_INFO; // we got connected to a new XineStream, it needs to know our m_volume int xinevolume = static_cast<int>(m_volume * 100); if (xinevolume > 200) { xinevolume = 200; } else if (xinevolume < 0) { xinevolume = 0; } upstreamEvent(new UpdateVolumeEvent(xinevolume)); } }} //namespace Phonon::Xine #include "audiooutput.moc" // vim: sw=4 ts=4
/* This file is part of the KDE project Copyright (C) 2006 Tim Beaulen <[email protected]> Copyright (C) 2006-2007 Matthias Kretz <[email protected]> This program 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; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "audiooutput.h" #include <QVector> #include <QtCore/QCoreApplication> #include <sys/ioctl.h> #include <iostream> #include <QSet> #include "mediaobject.h" #include "backend.h" #include "events.h" #include "wirecall.h" #include "xineengine.h" #include "xinethread.h" #include "keepreference.h" #include <xine/audio_out.h> #undef assert namespace Phonon { namespace Xine { AudioOutput::AudioOutput(QObject *parent) : AbstractAudioOutput(new AudioOutputXT, parent) { } AudioOutput::~AudioOutput() { //debug() << Q_FUNC_INFO ; } AudioOutputXT::~AudioOutputXT() { if (m_audioPort) { xine_close_audio_driver(m_xine, m_audioPort); m_audioPort = 0; debug() << Q_FUNC_INFO << "----------------------------------------------- audio_port destroyed"; } } qreal AudioOutput::volume() const { return m_volume; } int AudioOutput::outputDevice() const { return m_device.index(); } void AudioOutput::setVolume(qreal newVolume) { m_volume = newVolume; int xinevolume = static_cast<int>(m_volume * 100); if (xinevolume > 200) { xinevolume = 200; } else if (xinevolume < 0) { xinevolume = 0; } upstreamEvent(new UpdateVolumeEvent(xinevolume)); emit volumeChanged(m_volume); } xine_audio_port_t *AudioOutputXT::audioPort() const { return m_audioPort; } static QByteArray audioDriverFor(const QByteArray &driver) { if (driver == "alsa" || driver == "oss" || driver == "pulseaudio" || driver == "esd" || driver == "arts" || driver == "jack") { return driver; } return QByteArray(); } static bool lookupConfigEntry(xine_t *xine, const char *key, xine_cfg_entry_t *entry, const char *driver) { if(!xine_config_lookup_entry(xine, key, entry)) { // the config key is not registered yet - it is registered when the output // plugin is opened. So we open the plugin and close it again, then we can set the // setting. :( xine_audio_port_t *port = xine_open_audio_driver(xine, driver, 0); if (port) { xine_close_audio_driver(xine, port); // port == 0 does not have to be fatal, since it might be only the default device // that cannot be opened } // now the config key should be registered if(!xine_config_lookup_entry(xine, key, entry)) { qWarning() << "cannot configure the device on Xine's" << driver << "output plugin"; return false; } } return true; } xine_audio_port_t *AudioOutput::createPort(const AudioOutputDevice &deviceDesc) { K_XT(AudioOutput); xine_audio_port_t *port = 0; const QList<QPair<QByteArray, QString> > &deviceAccessList = deviceAccessListFor(deviceDesc); typedef QPair<QByteArray, QString> PhononDeviceAccess; foreach (const PhononDeviceAccess &access, deviceAccessList) { const QByteArray &outputPlugin = audioDriverFor(access.first); if (outputPlugin.isEmpty()) { continue; } const QString &handle = access.second; if (outputPlugin == "alsa") { xine_cfg_entry_t deviceConfig; if (!lookupConfigEntry(xt->m_xine, "audio.device.alsa_default_device", &deviceConfig, "alsa")) { continue; } Q_ASSERT(deviceConfig.type == XINE_CONFIG_TYPE_STRING); QByteArray deviceStr = handle.toUtf8(); deviceConfig.str_value = deviceStr.data(); xine_config_update_entry(xt->m_xine, &deviceConfig); const int err = xine_config_lookup_entry(xt->m_xine, "audio.device.alsa_front_device", &deviceConfig); Q_ASSERT(err); Q_UNUSED(err); Q_ASSERT(deviceConfig.type == XINE_CONFIG_TYPE_STRING); deviceConfig.str_value = deviceStr.data(); xine_config_update_entry(xt->m_xine, &deviceConfig); port = xine_open_audio_driver(xt->m_xine, "alsa", 0); if (port) { debug() << Q_FUNC_INFO << "use ALSA device: " << handle; debug() << Q_FUNC_INFO << "----------------------------------------------- audio_port created"; return port; } } else if (outputPlugin == "pulseaudio") { xine_cfg_entry_t deviceConfig; if (!lookupConfigEntry(xt->m_xine, "audio.pulseaudio_device", &deviceConfig, "pulseaudio")) { continue; } Q_ASSERT(deviceConfig.type == XINE_CONFIG_TYPE_STRING); QByteArray deviceStr = handle.toUtf8(); deviceConfig.str_value = deviceStr.data(); xine_config_update_entry(xt->m_xine, &deviceConfig); port = xine_open_audio_driver(xt->m_xine, "pulseaudio", 0); if (port) { debug() << Q_FUNC_INFO << "use PulseAudio: " << handle; debug() << Q_FUNC_INFO << "----------------------------------------------- audio_port created"; return port; } } else if (outputPlugin == "oss") { xine_cfg_entry_t deviceConfig; if (!lookupConfigEntry(xt->m_xine, "audio.device.oss_device_name", &deviceConfig, "oss")) { continue; } Q_ASSERT(deviceConfig.type == XINE_CONFIG_TYPE_ENUM); deviceConfig.num_value = 0; xine_config_update_entry(xt->m_xine, &deviceConfig); if(!xine_config_lookup_entry(xt->m_xine, "audio.device.oss_device_number", &deviceConfig)) { qWarning() << "cannot set the OSS device on Xine's OSS output plugin"; return 0; } Q_ASSERT(deviceConfig.type == XINE_CONFIG_TYPE_NUM); const QByteArray &deviceStr = handle.toUtf8(); char lastChar = deviceStr[deviceStr.length() - 1]; int deviceNumber = -1; if (lastChar >= '0' || lastChar <= '9') { deviceNumber = lastChar - '0'; char lastChar = deviceStr[deviceStr.length() - 2]; if (lastChar >= '0' || lastChar <= '9') { deviceNumber += 10 * (lastChar - '0'); } } deviceConfig.num_value = deviceNumber; xine_config_update_entry(xt->m_xine, &deviceConfig); port = xine_open_audio_driver(xt->m_xine, "oss", 0); if (port) { debug() << Q_FUNC_INFO << "use OSS device: " << handle; debug() << Q_FUNC_INFO << "----------------------------------------------- audio_port created"; return port; } } } const QByteArray &outputPlugin = Backend::audioDriverFor(deviceDesc.index()); debug() << Q_FUNC_INFO << "use output plugin:" << outputPlugin; port = xine_open_audio_driver(xt->m_xine, outputPlugin.constData(), 0); debug() << Q_FUNC_INFO << "----------------------------------------------- audio_port created"; return port; } bool AudioOutput::setOutputDevice(int newDevice) { return setOutputDevice(AudioOutputDevice::fromIndex(newDevice)); } bool AudioOutput::setOutputDevice(const AudioOutputDevice &newDevice) { K_XT(AudioOutput); if (!xt->m_xine) { // remeber the choice until we have a xine_t m_device = newDevice; return true; } xine_audio_port_t *port = createPort(newDevice); if (!port) { debug() << Q_FUNC_INFO << "new audio port is invalid"; return false; } KeepReference<> *keep = new KeepReference<>; keep->addObject(xt); keep->ready(); AudioOutputXT *newXt = new AudioOutputXT; newXt->m_audioPort = port; newXt->m_xine = xt->m_xine; m_threadSafeObject = newXt; m_device = newDevice; SourceNode *src = source(); if (src) { QList<WireCall> wireCall; QList<WireCall> unwireCall; wireCall << WireCall(src, this); unwireCall << WireCall(src, QExplicitlySharedDataPointer<SinkNodeXT>(xt)); QCoreApplication::postEvent(XineThread::instance(), new RewireEvent(wireCall, unwireCall)); graphChanged(); } return true; } void AudioOutput::xineEngineChanged() { K_XT(AudioOutput); if (xt->m_xine) { xine_audio_port_t *port = createPort(m_device); if (!port) { debug() << Q_FUNC_INFO << "stored audio port is invalid"; QMetaObject::invokeMethod(this, "audioDeviceFailed", Qt::QueuedConnection); return; } // our XT object is in a wirecall, better not delete it Q_ASSERT(xt->m_audioPort == 0); xt->m_audioPort = port; } } void AudioOutput::aboutToChangeXineEngine() { K_XT(AudioOutput); if (xt->m_audioPort) { AudioOutputXT *xt2 = new AudioOutputXT; xt2->m_xine = xt->m_xine; xt2->m_audioPort = xt->m_audioPort; xt->m_audioPort = 0; KeepReference<> *keep = new KeepReference<>; keep->addObject(xt2); keep->ready(); } } void AudioOutput::downstreamEvent(Event *e) { Q_ASSERT(e); QCoreApplication::sendEvent(this, e); SinkNode::downstreamEvent(e); } void AudioOutputXT::rewireTo(SourceNodeXT *source) { if (!source->audioOutputPort()) { return; } source->assert(); xine_post_wire_audio_port(source->audioOutputPort(), m_audioPort); source->assert(); SinkNodeXT::assert(); } bool AudioOutput::event(QEvent *ev) { switch (ev->type()) { case Event::AudioDeviceFailed: { ev->accept(); // we don't know for sure which AudioPort failed. We also can't know from the // information libxine makes available. So we have to just try the old device again if (setOutputDevice(m_device)) { return true; } // we really need a different output device QMetaObject::invokeMethod(this, "audioDeviceFailed", Qt::QueuedConnection); } return true; default: return AbstractAudioOutput::event(ev); } } void AudioOutput::graphChanged() { debug() << Q_FUNC_INFO; // we got connected to a new XineStream, it needs to know our m_volume int xinevolume = static_cast<int>(m_volume * 100); if (xinevolume > 200) { xinevolume = 200; } else if (xinevolume < 0) { xinevolume = 0; } upstreamEvent(new UpdateVolumeEvent(xinevolume)); } }} //namespace Phonon::Xine #include "audiooutput.moc" // vim: sw=4 ts=4
make use of the new helper function in AudioOutputInterface
make use of the new helper function in AudioOutputInterface
C++
lgpl-2.1
KDE/phonon-xine,KDE/phonon-quicktime,KDE/phonon-directshow,KDE/phonon-gstreamer,shadeslayer/phonon-gstreamer,shadeslayer/phonon-gstreamer,shadeslayer/phonon-gstreamer,KDE/phonon-waveout,KDE/phonon-xine,KDE/phonon-mmf,KDE/phonon-directshow,KDE/phonon-gstreamer,KDE/phonon-xine
ea9ecbac299f41f14801d13806a0a0b700c38aa3
01/PrintAll.cpp
01/PrintAll.cpp
#include <iostream> #include "PrintAll.h" using namespace std; void samples::PrintEverything() { int integer = 10; float decimal = 1.5f; char letter = 'A'; char string[] = "Hello, world!"; cout << integer << endl; cout << decimal << endl; cout << letter << endl; cout << string << endl; }
#include <iostream> #include "PrintAll.h" using namespace std; void samples::PrintEverything() { int integer = 10; float decimal = 1.5f; char letter = 'A'; char string[] = "Hello, world!"; cout << integer << endl; cout << decimal << endl; cout << letter << endl; cout << string << endl; }
Update PrintAll.cpp
Update PrintAll.cpp
C++
mit
popekim/CppSamples
60758dde2e7b118438b5b1aa91342f083a489eb7
Modules/Radiometry/Simulation/test/otbImageSimulationMethodSVMClassif.cxx
Modules/Radiometry/Simulation/test/otbImageSimulationMethodSVMClassif.cxx
/* * 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. */ //Warning !! the SVM model estimator do not converge in this test !! #include "otbVectorImage.h" #include "otbImageFileWriter.h" #include "otbVectorDataFileReader.h" #include "otbVectorDataToLabelMapWithAttributesFilter.h" #include "otbSpatialisationFilter.h" #include "otbImageSimulationMethod.h" #include "otbAttributesMapLabelObject.h" #include "otbLibSVMMachineLearningModel.h" #include "otbImageClassificationFilter.h" #include "otbImageFileReader.h" int otbImageSimulationMethodSVMClassif(int itkNotUsed(argc), char * argv[]) { const char * satRSRFilename = argv[1]; unsigned int nbBands = static_cast<unsigned int>(atoi(argv[2])); const char * rootPath = argv[3]; unsigned int radius = atoi(argv[4]); const char * outfilename = argv[5]; const char * outLabelfilename = argv[6]; typedef unsigned short LabelType; const unsigned int Dimension = 2; typedef otb::Image<LabelType, Dimension> LabelImageType; typedef otb::VectorImage<double, Dimension> OutputImageType; typedef otb::ImageFileWriter<OutputImageType> ImageWriterType; typedef otb::ImageFileWriter<LabelImageType> LabelImageWriterType; typedef otb::VectorData<double, Dimension> VectorDataType; typedef otb::AttributesMapLabelObject<LabelType, Dimension, std::string> LabelObjectType; typedef itk::LabelMap<LabelObjectType> LabelMapType; typedef otb::SpatialisationFilter<LabelMapType> SpatialisationFilterType; // typedef otb::VectorDataToLabelMapWithAttributesFilter<VectorDataType, LabelMapType> SpatialisationFilterType; typedef otb::ProspectModel SimulationStep1Type; typedef otb::SailModel SimulationStep2Type; typedef otb::ProlateInterpolateImageFunction<LabelImageType> FTMType; typedef otb::ImageSimulationMethod<VectorDataType, SpatialisationFilterType, SimulationStep1Type, SimulationStep2Type, FTMType , OutputImageType> ImageSimulationMethodType; typedef otb::LibSVMMachineLearningModel<double, unsigned short> SVMType; typedef otb::ImageClassificationFilter<OutputImageType,LabelImageType> ClassificationFilterType; /** Instantiation of pointer objects*/ ImageWriterType::Pointer writer = ImageWriterType::New(); LabelImageWriterType::Pointer labelWriter = LabelImageWriterType::New(); ImageSimulationMethodType::Pointer imageSimulation = ImageSimulationMethodType::New(); SpatialisationFilterType::Pointer spatialisationFilter = SpatialisationFilterType::New(); SVMType::Pointer model = SVMType::New(); ClassificationFilterType::Pointer classifier = ClassificationFilterType::New(); SpatialisationFilterType::SizeType objectSize; objectSize[0]=300; objectSize[1]=300; SpatialisationFilterType::SizeType nbOjects; nbOjects[0]=2; nbOjects[1]=1; std::vector<std::string> pathVector(2); pathVector[0]="JHU/becknic/rocks/sedimentary/powder/0_75/txt/greywa1f.txt"; pathVector[1]=""; // pathVector[2]="JHU/becknic/manmade/txt/0092uuu.txt"; // pathVector[3]="JHU/becknic/vegetation/txt/conifers.txt"; // pathVector[4]="JHU/becknic/manmade/txt/0834uuu.txt"; // pathVector[5]="JHU/becknic/vegetation/txt/grass.txt"; // pathVector[6]="JHU/becknic/water/txt/coarse.txt"; // pathVector[7]="JHU/becknic/rocks/igneous/solid/txt/andesi1s.txt"; // pathVector[8]="JHU/becknic/soils/txt/0015c.txt"; std::vector<std::string> areaVector(2); areaVector[0]="sedimentaryRock"; areaVector[1]="prosail"; // areaVector[2]="manmade"; // areaVector[3]="conifers"; // areaVector[4]="manmade"; // areaVector[5]="grass"; // areaVector[6]="water"; // areaVector[7]="igneousRocks"; // areaVector[8]="soils"; std::vector<LabelType> labels(2); labels[0]=1; labels[1]=2; // labels[2]=1; // labels[3]=2; // labels[4]=3; // labels[5]=2; // labels[6]=4; // labels[7]=5; // labels[8]=3; spatialisationFilter->SetObjectSize(objectSize); spatialisationFilter->SetNumberOfObjects(nbOjects); spatialisationFilter->SetPathVector(pathVector); spatialisationFilter->SetAreaVector(areaVector); spatialisationFilter->SetLabels(labels); imageSimulation->SetSpatialisation(spatialisationFilter); imageSimulation->SetNumberOfComponentsPerPixel(nbBands); imageSimulation->SetSatRSRFilename(satRSRFilename); imageSimulation->SetPathRoot(rootPath); imageSimulation->SetRadius(radius); // imageSimulation->SetMean(); // imageSimulation->SetVariance(); imageSimulation->UpdateData(); //~ svmEstimator->SetInputImage(imageSimulation->GetOutputReflectanceImage()); //~ svmEstimator->SetTrainingImage(imageSimulation->GetOutputLabelImage()); //~ svmEstimator->SetParametersOptimization(false); //~ svmEstimator->DoProbabilityEstimates(true); //~ svmEstimator->Update(); OutputImageType::Pointer outReflectance = imageSimulation->GetOutputReflectanceImage(); LabelImageType::Pointer outLabels = imageSimulation->GetOutputLabelImage(); typedef SVMType::InputListSampleType InputListSampleType; typedef SVMType::TargetListSampleType TargetListSampleType; InputListSampleType::Pointer inputSamples = InputListSampleType::New(); TargetListSampleType::Pointer trainSamples = TargetListSampleType::New(); inputSamples->SetMeasurementVectorSize(nbBands); trainSamples->SetMeasurementVectorSize(1); itk::ImageRegionConstIterator<OutputImageType> itIn(outReflectance,outReflectance->GetLargestPossibleRegion() ); itk::ImageRegionConstIterator<LabelImageType> itLabel(outLabels, outLabels->GetLargestPossibleRegion()); itIn.GoToBegin(); itLabel.GoToBegin(); while (!itIn.IsAtEnd()) { SVMType::InputSampleType sample; SVMType::TargetSampleType target; sample.SetSize(nbBands); for (unsigned int i=0 ; i<nbBands ; i++) { sample[i] = itIn.Get()[i]; } target[0] = itLabel.Value(); inputSamples->PushBack(sample); trainSamples->PushBack(target); ++itIn; ++itLabel; } model->SetInputListSample(inputSamples); model->SetTargetListSample(trainSamples); model->DoProbabilityEstimates(true); model->Train(); classifier->SetModel(model); classifier->SetInput(imageSimulation->GetOutput()); //Write the result to an image file writer->SetFileName(outfilename); writer->SetInput(imageSimulation->GetOutputReflectanceImage()); writer->Update(); labelWriter->SetFileName(outLabelfilename); // labelWriter->SetInput(imageSimulation->GetOutputLabelImage()); labelWriter->SetInput(classifier->GetOutput()); labelWriter->Update(); return EXIT_SUCCESS; }
/* * 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. */ //Warning !! the SVM model estimator do not converge in this test !! #include "otbVectorImage.h" #include "otbImageFileWriter.h" #include "otbVectorDataFileReader.h" #include "otbVectorDataToLabelMapWithAttributesFilter.h" #include "otbSpatialisationFilter.h" #include "otbImageSimulationMethod.h" #include "otbAttributesMapLabelObject.h" #include "otbLibSVMMachineLearningModel.h" #include "otbImageClassificationFilter.h" #include "otbImageFileReader.h" #include "itkImageToListSampleAdaptor.h" int otbImageSimulationMethodSVMClassif(int itkNotUsed(argc), char * argv[]) { const char * satRSRFilename = argv[1]; unsigned int nbBands = static_cast<unsigned int>(atoi(argv[2])); const char * rootPath = argv[3]; unsigned int radius = atoi(argv[4]); const char * outfilename = argv[5]; const char * outLabelfilename = argv[6]; typedef unsigned short LabelType; const unsigned int Dimension = 2; typedef otb::Image<LabelType, Dimension> LabelImageType; typedef otb::VectorImage<double, Dimension> OutputImageType; typedef otb::ImageFileWriter<OutputImageType> ImageWriterType; typedef otb::ImageFileWriter<LabelImageType> LabelImageWriterType; typedef otb::VectorData<double, Dimension> VectorDataType; typedef otb::AttributesMapLabelObject<LabelType, Dimension, std::string> LabelObjectType; typedef itk::LabelMap<LabelObjectType> LabelMapType; typedef otb::SpatialisationFilter<LabelMapType> SpatialisationFilterType; // typedef otb::VectorDataToLabelMapWithAttributesFilter<VectorDataType, LabelMapType> SpatialisationFilterType; typedef otb::ProspectModel SimulationStep1Type; typedef otb::SailModel SimulationStep2Type; typedef otb::ProlateInterpolateImageFunction<LabelImageType> FTMType; typedef otb::ImageSimulationMethod<VectorDataType, SpatialisationFilterType, SimulationStep1Type, SimulationStep2Type, FTMType , OutputImageType> ImageSimulationMethodType; typedef otb::LibSVMMachineLearningModel<double, unsigned short> SVMType; typedef otb::ImageClassificationFilter<OutputImageType,LabelImageType> ClassificationFilterType; /** Instantiation of pointer objects*/ ImageWriterType::Pointer writer = ImageWriterType::New(); LabelImageWriterType::Pointer labelWriter = LabelImageWriterType::New(); ImageSimulationMethodType::Pointer imageSimulation = ImageSimulationMethodType::New(); SpatialisationFilterType::Pointer spatialisationFilter = SpatialisationFilterType::New(); SVMType::Pointer model = SVMType::New(); ClassificationFilterType::Pointer classifier = ClassificationFilterType::New(); SpatialisationFilterType::SizeType objectSize; objectSize[0]=300; objectSize[1]=300; SpatialisationFilterType::SizeType nbOjects; nbOjects[0]=2; nbOjects[1]=1; std::vector<std::string> pathVector(2); pathVector[0]="JHU/becknic/rocks/sedimentary/powder/0_75/txt/greywa1f.txt"; pathVector[1]=""; // pathVector[2]="JHU/becknic/manmade/txt/0092uuu.txt"; // pathVector[3]="JHU/becknic/vegetation/txt/conifers.txt"; // pathVector[4]="JHU/becknic/manmade/txt/0834uuu.txt"; // pathVector[5]="JHU/becknic/vegetation/txt/grass.txt"; // pathVector[6]="JHU/becknic/water/txt/coarse.txt"; // pathVector[7]="JHU/becknic/rocks/igneous/solid/txt/andesi1s.txt"; // pathVector[8]="JHU/becknic/soils/txt/0015c.txt"; std::vector<std::string> areaVector(2); areaVector[0]="sedimentaryRock"; areaVector[1]="prosail"; // areaVector[2]="manmade"; // areaVector[3]="conifers"; // areaVector[4]="manmade"; // areaVector[5]="grass"; // areaVector[6]="water"; // areaVector[7]="igneousRocks"; // areaVector[8]="soils"; std::vector<LabelType> labels(2); labels[0]=1; labels[1]=2; // labels[2]=1; // labels[3]=2; // labels[4]=3; // labels[5]=2; // labels[6]=4; // labels[7]=5; // labels[8]=3; spatialisationFilter->SetObjectSize(objectSize); spatialisationFilter->SetNumberOfObjects(nbOjects); spatialisationFilter->SetPathVector(pathVector); spatialisationFilter->SetAreaVector(areaVector); spatialisationFilter->SetLabels(labels); imageSimulation->SetSpatialisation(spatialisationFilter); imageSimulation->SetNumberOfComponentsPerPixel(nbBands); imageSimulation->SetSatRSRFilename(satRSRFilename); imageSimulation->SetPathRoot(rootPath); imageSimulation->SetRadius(radius); // imageSimulation->SetMean(); // imageSimulation->SetVariance(); imageSimulation->UpdateData(); //~ svmEstimator->SetInputImage(imageSimulation->GetOutputReflectanceImage()); //~ svmEstimator->SetTrainingImage(imageSimulation->GetOutputLabelImage()); //~ svmEstimator->SetParametersOptimization(false); //~ svmEstimator->DoProbabilityEstimates(true); //~ svmEstimator->Update(); typedef itk::Statistics::ImageToListSampleAdaptor<OutputImageType> ListSampleAdaptorType; typedef itk::Statistics::ImageToListSampleAdaptor<LabelImageType> TargetListSampleAdaptorType; ListSampleAdaptorType::Pointer listSample = ListSampleAdaptorType::New(); listSample->SetImage(imageSimulation->GetOutputReflectanceImage()); TargetListSampleAdaptorType::Pointer targetListSample = TargetListSampleAdaptorType::New(); targetListSample->SetImage(imageSimulation->GetOutputLabelImage()); model->SetInputListSample(listSample); model->SetTargetListSample(targetListSample); model->SetDoProbabilityEstimates(true); model->Train(); classifier->SetModel(model); classifier->SetInput(imageSimulation->GetOutput()); //Write the result to an image file writer->SetFileName(outfilename); writer->SetInput(imageSimulation->GetOutputReflectanceImage()); writer->Update(); labelWriter->SetFileName(outLabelfilename); // labelWriter->SetInput(imageSimulation->GetOutputLabelImage()); labelWriter->SetInput(classifier->GetOutput()); labelWriter->Update(); return EXIT_SUCCESS; }
use an ImageToListSampleAdaptor
REFAC: use an ImageToListSampleAdaptor
C++
apache-2.0
orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB
cf576c860a780a3f34ea17cb2d931e4532606217
lib/tsan/lit_tests/tsan-vs-gvn.cc
lib/tsan/lit_tests/tsan-vs-gvn.cc
// RUN: %clangxx_tsan -O1 %s -o %t && %t 2>&1 | FileCheck %s // RUN: %clangxx_tsan -O2 %s -o %t && %t 2>&1 | FileCheck %s // RUN: %clangxx_tsan -O3 %s -o %t && %t 2>&1 | FileCheck %s // // Check that load widening is not tsan-hostile. #include <pthread.h> #include <stdio.h> #include <string.h> struct { int i; char c1, c2, c3, c4; } S; int G; void *Thread1(void *x) { G = S.c1 + S.c3; return NULL; } void *Thread2(void *x) { // FIXME: enable this line back once gvn vs tsan is fixed. // S.c2 = 1; return NULL; } int main() { pthread_t t[2]; memset(&S, 123, sizeof(S)); pthread_create(&t[0], NULL, Thread1, NULL); pthread_create(&t[1], NULL, Thread2, NULL); pthread_join(t[0], NULL); pthread_join(t[1], NULL); printf("PASS\n"); } // CHECK-NOT: WARNING: ThreadSanitizer: data race // CHECK: PASS
// RUN: %clangxx_tsan -O1 %s -o %t && %t 2>&1 | FileCheck %s // RUN: %clangxx_tsan -O2 %s -o %t && %t 2>&1 | FileCheck %s // RUN: %clangxx_tsan -O3 %s -o %t && %t 2>&1 | FileCheck %s // // Check that load widening is not tsan-hostile. #include <pthread.h> #include <stdio.h> #include <string.h> struct { int i; char c1, c2, c3, c4; } S; int G; void *Thread1(void *x) { G = S.c1 + S.c3; return NULL; } void *Thread2(void *x) { S.c2 = 1; return NULL; } int main() { pthread_t t[2]; memset(&S, 123, sizeof(S)); pthread_create(&t[0], NULL, Thread1, NULL); pthread_create(&t[1], NULL, Thread2, NULL); pthread_join(t[0], NULL); pthread_join(t[1], NULL); printf("PASS\n"); } // CHECK-NOT: WARNING: ThreadSanitizer: data race // CHECK: PASS
enable tsan-vs-gvn test since it is now fixed
[tsan] enable tsan-vs-gvn test since it is now fixed git-svn-id: c199f293c43da69278bea8e88f92242bf3aa95f7@176079 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt
77d5812178a70989bf637357235b1b7d42141685
contracts/eosio.system/native.hpp
contracts/eosio.system/native.hpp
/** * @file * @copyright defined in eos/LICENSE.txt */ #pragma once #include <eosiolib/types.hpp> namespace eosiosystem { typedef std::vector<char> bytes; typedef std::string type_name; typedef std::string field_name; struct permission_level_weight { permission_level permission; weight_type weight; EOSLIB_SERIALIZE( permission_level_weight, (permission)(weight) ) }; struct key_weight { public_key key; weight_type weight; EOSLIB_SERIALIZE( key_weight, (key)(weight) ) }; struct authority { uint32_t threshold; std::vector<key_weight> keys; std::vector<permission_level_weight> accounts; EOSLIB_SERIALIZE( authority, (threshold)(keys)(accounts) ) }; template <account_name SystemAccount> class native { public: ACTION( SystemAccount, newaccount ) { account_name creator; account_name name; authority owner; authority active; authority recovery; EOSLIB_SERIALIZE( newaccount, (creator)(name)(owner)(active)(recovery) ) }; static void on( const newaccount& ) { } ACTION( SystemAccount, updateauth ) { account_name account; permission_name permission; permission_name parent; authority data; EOSLIB_SERIALIZE( updateauth, (account)(permission)(parent)(data) ) }; static void on( const updateauth& ) { } ACTION( SystemAccount, deleteauth ) { account_name account; permission_name permission; EOSLIB_SERIALIZE( deleteauth, (account)(permission) ) }; static void on( const deleteauth& ) { } ACTION( SystemAccount, linkauth ) { account_name account; account_name code; action_name type; permission_name requirement; EOSLIB_SERIALIZE( linkauth, (account)(code)(type)(requirement) ) }; static void on( const linkauth& ) { } ACTION( SystemAccount, unlinkauth ) { account_name account; account_name code; action_name type; EOSLIB_SERIALIZE( unlinkauth, (account)(code)(type) ) }; static void on( const unlinkauth& ) { } ACTION( SystemAccount, postrecovery ) { account_name account; authority data; std::string memo; EOSLIB_SERIALIZE( postrecovery, (account)(data)(memo) ) }; static void on( const postrecovery& ) { } ACTION( SystemAccount, passrecovery ) { account_name account; EOSLIB_SERIALIZE( passrecovery, (account) ) }; static void on( const passrecovery& ) { } ACTION( SystemAccount, vetorecovery ) { account_name account; EOSLIB_SERIALIZE( vetorecovery, (account) ) }; static void on( const vetorecovery& ) { } struct onerror: eosio::action_meta<SystemAccount, N(onerror)>, bytes { EOSLIB_SERIALIZE_DERIVED( onerror, bytes, BOOST_PP_SEQ_NIL ) }; static void on( const onerror& ) { } ACTION( SystemAccount, canceldelay ) { permission_level canceling_auth; transaction_id_type trx_id; EOSLIB_SERIALIZE( canceldelay, (canceling_auth)(trx_id) ) }; static void on( const canceldelay& ) { } }; }
/** * @file * @copyright defined in eos/LICENSE.txt */ #pragma once #include <eosiolib/types.hpp> namespace eosiosystem { typedef std::vector<char> bytes; typedef std::string type_name; typedef std::string field_name; struct permission_level_weight { permission_level permission; weight_type weight; EOSLIB_SERIALIZE( permission_level_weight, (permission)(weight) ) }; struct key_weight { public_key key; weight_type weight; EOSLIB_SERIALIZE( key_weight, (key)(weight) ) }; struct authority { uint32_t threshold; uint32_t delay_sec; std::vector<key_weight> keys; std::vector<permission_level_weight> accounts; EOSLIB_SERIALIZE( authority, (threshold)(delay_sec)(keys)(accounts) ) }; template <account_name SystemAccount> class native { public: ACTION( SystemAccount, newaccount ) { account_name creator; account_name name; authority owner; authority active; authority recovery; EOSLIB_SERIALIZE( newaccount, (creator)(name)(owner)(active)(recovery) ) }; static void on( const newaccount& ) { } ACTION( SystemAccount, updateauth ) { account_name account; permission_name permission; permission_name parent; authority auth; EOSLIB_SERIALIZE( updateauth, (account)(permission)(parent)(auth) ) }; static void on( const updateauth& ) { } ACTION( SystemAccount, deleteauth ) { account_name account; permission_name permission; EOSLIB_SERIALIZE( deleteauth, (account)(permission) ) }; static void on( const deleteauth& ) { } ACTION( SystemAccount, linkauth ) { account_name account; account_name code; action_name type; permission_name requirement; EOSLIB_SERIALIZE( linkauth, (account)(code)(type)(requirement) ) }; static void on( const linkauth& ) { } ACTION( SystemAccount, unlinkauth ) { account_name account; account_name code; action_name type; EOSLIB_SERIALIZE( unlinkauth, (account)(code)(type) ) }; static void on( const unlinkauth& ) { } ACTION( SystemAccount, postrecovery ) { account_name account; authority auth; std::string memo; EOSLIB_SERIALIZE( postrecovery, (account)(auth)(memo) ) }; static void on( const postrecovery& ) { } ACTION( SystemAccount, passrecovery ) { account_name account; EOSLIB_SERIALIZE( passrecovery, (account) ) }; static void on( const passrecovery& ) { } ACTION( SystemAccount, vetorecovery ) { account_name account; EOSLIB_SERIALIZE( vetorecovery, (account) ) }; static void on( const vetorecovery& ) { } struct onerror: eosio::action_meta<SystemAccount, N(onerror)>, bytes { EOSLIB_SERIALIZE_DERIVED( onerror, bytes, BOOST_PP_SEQ_NIL ) }; static void on( const onerror& ) { } ACTION( SystemAccount, canceldelay ) { permission_level canceling_auth; transaction_id_type trx_id; EOSLIB_SERIALIZE( canceldelay, (canceling_auth)(trx_id) ) }; static void on( const canceldelay& ) { } }; }
Add delay_sec to authority, rename data to auth
Add delay_sec to authority, rename data to auth
C++
mit
EOSIO/eos,EOSIO/eos,EOSIO/eos,EOSIO/eos,EOSIO/eos
d89cd8e845ee5a28488162f560d22631a928b723
core/meta/src/TClingCallbacks.cxx
core/meta/src/TClingCallbacks.cxx
// @(#)root/core/meta:$Id$ // Author: Vassil Vassilev 7/10/2012 /************************************************************************* * Copyright (C) 1995-2012, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "TClingCallbacks.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/InterpreterCallbacks.h" #include "cling/Interpreter/Transaction.h" #include "cling/Utils/AST.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclBase.h" #include "clang/Lex/Preprocessor.h" #include "clang/Parse/Parser.h" #include "clang/Sema/Lookup.h" #include "clang/Sema/Scope.h" using namespace clang; using namespace cling; class TObject; // Functions used to forward calls from code compiled with no-rtti to code // compiled with rtti. extern "C" { void TCintWithCling__UpdateListsOnCommitted(const cling::Transaction&); void TCintWithCling__UpdateListsOnUnloaded(const cling::Transaction&); TObject* TCintWithCling__GetObjectAddress(const char *Name, void *&LookupCtx); Decl* TCintWithCling__GetObjectDecl(TObject *obj); int TCintWithCling__AutoLoadCallback(const char* className); } TClingCallbacks::TClingCallbacks(cling::Interpreter* interp) : InterpreterCallbacks(interp), fLastLookupCtx(0), fROOTSpecialNamespace(0), fFirstRun(true), fIsAutoloading(false), fIsAutoloadingRecursively(false) { const Decl* D = 0; m_Interpreter->declare("namespace __ROOT_SpecialObjects{}", &D); fROOTSpecialNamespace = dyn_cast<NamespaceDecl>(const_cast<Decl*>(D)); } //pin the vtable here TClingCallbacks::~TClingCallbacks() {} // On a failed lookup we have to try to more things before issuing an error. // The symbol might need to be loaded by ROOT's autoloading mechanism or // it might be a ROOT special object. // // Try those first and if still failing issue the diagnostics. // // returns true when a declaration is found and no error should be emitted. // bool TClingCallbacks::LookupObject(LookupResult &R, Scope *S) { if (tryAutoloadInternal(R, S)) return true; // happiness. // If the autoload wasn't successful try ROOT specials. return tryFindROOTSpecialInternal(R, S); } // The symbol might be defined in the ROOT class autoloading map so we have to // try to autoload it first and do secondary lookup to try to find it. // // returns true when a declaration is found and no error should be emitted. // bool TClingCallbacks::tryAutoloadInternal(LookupResult &R, Scope *S) { Sema &SemaR = m_Interpreter->getSema(); ASTContext& C = SemaR.getASTContext(); Preprocessor &PP = SemaR.getPreprocessor(); DeclarationName Name = R.getLookupName(); // Try to autoload first if autoloading is enabled if (IsAutoloadingEnabled()) { // Avoid tail chasing. if (fIsAutoloadingRecursively) return false; fIsAutoloadingRecursively = true; // Save state of the PP Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP); Parser& P = const_cast<Parser&>(m_Interpreter->getParser()); Parser::ParserCurTokRestoreRAII savedCurToken(P); // After we have saved the token reset the current one to something which // is safe (semi colon usually means empty decl) Token& Tok = const_cast<Token&>(P.getCurToken()); Tok.setKind(tok::semi); bool oldSuppressDiags = SemaR.getDiagnostics().getSuppressAllDiagnostics(); SemaR.getDiagnostics().setSuppressAllDiagnostics(); // We can't PushDeclContext, because we go up and the routine that pops // the DeclContext assumes that we drill down always. // We have to be on the global context. At that point we are in a // wrapper function so the parent context must be the global. Sema::ContextAndScopeRAII pushedDCAndS(SemaR, C.getTranslationUnitDecl(), SemaR.TUScope); bool lookupSuccess = false; if (TCintWithCling__AutoLoadCallback(Name.getAsString().c_str())) { pushedDCAndS.pop(); cleanupRAII.pop(); lookupSuccess = SemaR.LookupName(R, S); } SemaR.getDiagnostics().setSuppressAllDiagnostics(oldSuppressDiags); fIsAutoloadingRecursively = false; if (lookupSuccess) return true; } return false; } // If cling cannot find a name it should ask ROOT before it issues an error. // If ROOT knows the name then it has to create a new variable with that name // and type in dedicated for that namespace (eg. __ROOT_SpecialObjects). // For example if the interpreter is looking for h in h-Draw(), this routine // will create // namespace __ROOT_SpecialObjects { // THist* h = (THist*) the_address; // } // // Later if h is called again it again won't be found by the standart lookup // because it is in our hidden namespace (nobody should do using namespace // __ROOT_SpecialObjects). It caches the variable declarations and their // last address. If the newly found decl with the same name (h) has different // address than the cached one it goes directly at the address and updates it. // // returns true when declaration is found and no error should be emitted. // bool TClingCallbacks::tryFindROOTSpecialInternal(LookupResult &R, Scope *S) { Sema &SemaR = m_Interpreter->getSema(); ASTContext& C = SemaR.getASTContext(); Preprocessor &PP = SemaR.getPreprocessor(); DeclContext *CurDC = SemaR.CurContext; DeclarationName Name = R.getLookupName(); // Make sure that the failed lookup comes from the prompt. if(!CurDC || !CurDC->isFunctionOrMethod()) return false; if (NamedDecl* ND = dyn_cast<NamedDecl>(CurDC)) if (!m_Interpreter->isUniqueWrapper(ND->getNameAsString())) return false; TObject *obj = TCintWithCling__GetObjectAddress(Name.getAsString().c_str(), fLastLookupCtx); if (obj) { VarDecl *VD = cast_or_null<VarDecl>(utils::Lookup::Named(&SemaR, Name, fROOTSpecialNamespace)); if (VD) { //TODO: Check for same types. TObject **address = (TObject**)m_Interpreter->getAddressOfGlobal(VD); // Since code was generated already we cannot rely on the initializer // of the decl in the AST, however we will update that init so that it // will be easier while debugging. CStyleCastExpr *CStyleCast = cast<CStyleCastExpr>(VD->getInit()); Expr* newInit = utils::Synthesize::IntegerLiteralExpr(C, (uint64_t)obj); CStyleCast->setSubExpr(newInit); // The actual update happens here, directly in memory. *address = obj; } else { // Save state of the PP Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP); const Decl *TD = TCintWithCling__GetObjectDecl(obj); // We will declare the variable as pointer. QualType QT = C.getPointerType(C.getTypeDeclType(cast<TypeDecl>(TD))); VD = VarDecl::Create(C, fROOTSpecialNamespace, SourceLocation(), SourceLocation(), Name.getAsIdentifierInfo(), QT, /*TypeSourceInfo*/0, SC_None, SC_None ); // Build an initializer Expr* Init = utils::Synthesize::CStyleCastPtrExpr(&SemaR, QT, (uint64_t)obj); // Register the decl in our hidden special namespace VD->setInit(Init); fROOTSpecialNamespace->addDecl(VD); cling::CompilationOptions CO; CO.DeclarationExtraction = 0; CO.ValuePrinting = CompilationOptions::VPDisabled; CO.ResultEvaluation = 0; CO.DynamicScoping = 0; CO.Debug = 0; CO.CodeGeneration = 1; cling::Transaction T(CO, /*llvm::Module=*/0); T.append(VD); T.setCompleted(); m_Interpreter->codegen(&T); assert(T.getState() == Transaction::kCommitted && "Compilation should never fail!"); } assert(VD && "Cannot be null!"); R.addDecl(VD); return true; } return false; } // The callback is used to update the list of globals in ROOT. // void TClingCallbacks::TransactionCommitted(const Transaction &T) { if (!T.size()) return; if (fFirstRun) { // Before setting up the callbacks register what cling have seen during init. const cling::Transaction* T = m_Interpreter->getFirstTransaction(); while (T) { if (T->getState() == cling::Transaction::kCommitted) TCintWithCling__UpdateListsOnCommitted(*T); T = T->getNext(); } fFirstRun = false; } TCintWithCling__UpdateListsOnCommitted(T); } // The callback is used to update the list of globals in ROOT. // void TClingCallbacks::TransactionUnloaded(const Transaction &T) { if (!T.size()) return; TCintWithCling__UpdateListsOnUnloaded(T); }
// @(#)root/core/meta:$Id$ // Author: Vassil Vassilev 7/10/2012 /************************************************************************* * Copyright (C) 1995-2012, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "TClingCallbacks.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/InterpreterCallbacks.h" #include "cling/Interpreter/Transaction.h" #include "cling/Utils/AST.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclBase.h" #include "clang/Lex/Preprocessor.h" #include "clang/Parse/Parser.h" #include "clang/Sema/Lookup.h" #include "clang/Sema/Scope.h" using namespace clang; using namespace cling; class TObject; // Functions used to forward calls from code compiled with no-rtti to code // compiled with rtti. extern "C" { void TCintWithCling__UpdateListsOnCommitted(const cling::Transaction&); void TCintWithCling__UpdateListsOnUnloaded(const cling::Transaction&); TObject* TCintWithCling__GetObjectAddress(const char *Name, void *&LookupCtx); Decl* TCintWithCling__GetObjectDecl(TObject *obj); int TCintWithCling__AutoLoadCallback(const char* className); } TClingCallbacks::TClingCallbacks(cling::Interpreter* interp) : InterpreterCallbacks(interp), fLastLookupCtx(0), fROOTSpecialNamespace(0), fFirstRun(true), fIsAutoloading(false), fIsAutoloadingRecursively(false) { const Decl* D = 0; m_Interpreter->declare("namespace __ROOT_SpecialObjects{}", &D); fROOTSpecialNamespace = dyn_cast<NamespaceDecl>(const_cast<Decl*>(D)); } //pin the vtable here TClingCallbacks::~TClingCallbacks() {} // On a failed lookup we have to try to more things before issuing an error. // The symbol might need to be loaded by ROOT's autoloading mechanism or // it might be a ROOT special object. // // Try those first and if still failing issue the diagnostics. // // returns true when a declaration is found and no error should be emitted. // bool TClingCallbacks::LookupObject(LookupResult &R, Scope *S) { if (tryAutoloadInternal(R, S)) return true; // happiness. // If the autoload wasn't successful try ROOT specials. return tryFindROOTSpecialInternal(R, S); } // The symbol might be defined in the ROOT class autoloading map so we have to // try to autoload it first and do secondary lookup to try to find it. // // returns true when a declaration is found and no error should be emitted. // bool TClingCallbacks::tryAutoloadInternal(LookupResult &R, Scope *S) { Sema &SemaR = m_Interpreter->getSema(); ASTContext& C = SemaR.getASTContext(); Preprocessor &PP = SemaR.getPreprocessor(); DeclarationName Name = R.getLookupName(); // Try to autoload first if autoloading is enabled if (IsAutoloadingEnabled()) { // Avoid tail chasing. if (fIsAutoloadingRecursively) return false; fIsAutoloadingRecursively = true; // Save state of the PP Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP); Parser& P = const_cast<Parser&>(m_Interpreter->getParser()); Parser::ParserCurTokRestoreRAII savedCurToken(P); // After we have saved the token reset the current one to something which // is safe (semi colon usually means empty decl) Token& Tok = const_cast<Token&>(P.getCurToken()); Tok.setKind(tok::semi); bool oldSuppressDiags = SemaR.getDiagnostics().getSuppressAllDiagnostics(); SemaR.getDiagnostics().setSuppressAllDiagnostics(); // We can't PushDeclContext, because we go up and the routine that pops // the DeclContext assumes that we drill down always. // We have to be on the global context. At that point we are in a // wrapper function so the parent context must be the global. Sema::ContextAndScopeRAII pushedDCAndS(SemaR, C.getTranslationUnitDecl(), SemaR.TUScope); bool lookupSuccess = false; if (TCintWithCling__AutoLoadCallback(Name.getAsString().c_str())) { pushedDCAndS.pop(); cleanupRAII.pop(); lookupSuccess = SemaR.LookupName(R, S); } SemaR.getDiagnostics().setSuppressAllDiagnostics(oldSuppressDiags); fIsAutoloadingRecursively = false; if (lookupSuccess) return true; } return false; } // If cling cannot find a name it should ask ROOT before it issues an error. // If ROOT knows the name then it has to create a new variable with that name // and type in dedicated for that namespace (eg. __ROOT_SpecialObjects). // For example if the interpreter is looking for h in h-Draw(), this routine // will create // namespace __ROOT_SpecialObjects { // THist* h = (THist*) the_address; // } // // Later if h is called again it again won't be found by the standart lookup // because it is in our hidden namespace (nobody should do using namespace // __ROOT_SpecialObjects). It caches the variable declarations and their // last address. If the newly found decl with the same name (h) has different // address than the cached one it goes directly at the address and updates it. // // returns true when declaration is found and no error should be emitted. // bool TClingCallbacks::tryFindROOTSpecialInternal(LookupResult &R, Scope *S) { Sema &SemaR = m_Interpreter->getSema(); ASTContext& C = SemaR.getASTContext(); Preprocessor &PP = SemaR.getPreprocessor(); DeclContext *CurDC = SemaR.CurContext; DeclarationName Name = R.getLookupName(); // Make sure that the failed lookup comes from the prompt. if(!CurDC || !CurDC->isFunctionOrMethod()) return false; if (NamedDecl* ND = dyn_cast<NamedDecl>(CurDC)) if (!m_Interpreter->isUniqueWrapper(ND->getNameAsString())) return false; TObject *obj = TCintWithCling__GetObjectAddress(Name.getAsString().c_str(), fLastLookupCtx); if (obj) { #if defined(R__MUST_REVISIT) #if R__MUST_REVISIT(6,2) // Register the address in TCling::fgSetOfSpecials // to speed-up the execution of TCling::RecursiveRemove when // the object is not a special. // See http://root.cern.ch/viewvc/trunk/core/meta/src/TCint.cxx?view=log#rev18109 if (!fgSetOfSpecials) { fgSetOfSpecials = new std::set<TObject*>; } ((std::set<TObject*>*)fgSetOfSpecials)->insert((TObject*)*obj); #endif #endif VarDecl *VD = cast_or_null<VarDecl>(utils::Lookup::Named(&SemaR, Name, fROOTSpecialNamespace)); if (VD) { //TODO: Check for same types. TObject **address = (TObject**)m_Interpreter->getAddressOfGlobal(VD); // Since code was generated already we cannot rely on the initializer // of the decl in the AST, however we will update that init so that it // will be easier while debugging. CStyleCastExpr *CStyleCast = cast<CStyleCastExpr>(VD->getInit()); Expr* newInit = utils::Synthesize::IntegerLiteralExpr(C, (uint64_t)obj); CStyleCast->setSubExpr(newInit); // The actual update happens here, directly in memory. *address = obj; } else { // Save state of the PP Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP); const Decl *TD = TCintWithCling__GetObjectDecl(obj); // We will declare the variable as pointer. QualType QT = C.getPointerType(C.getTypeDeclType(cast<TypeDecl>(TD))); VD = VarDecl::Create(C, fROOTSpecialNamespace, SourceLocation(), SourceLocation(), Name.getAsIdentifierInfo(), QT, /*TypeSourceInfo*/0, SC_None, SC_None ); // Build an initializer Expr* Init = utils::Synthesize::CStyleCastPtrExpr(&SemaR, QT, (uint64_t)obj); // Register the decl in our hidden special namespace VD->setInit(Init); fROOTSpecialNamespace->addDecl(VD); cling::CompilationOptions CO; CO.DeclarationExtraction = 0; CO.ValuePrinting = CompilationOptions::VPDisabled; CO.ResultEvaluation = 0; CO.DynamicScoping = 0; CO.Debug = 0; CO.CodeGeneration = 1; cling::Transaction T(CO, /*llvm::Module=*/0); T.append(VD); T.setCompleted(); m_Interpreter->codegen(&T); assert(T.getState() == Transaction::kCommitted && "Compilation should never fail!"); } assert(VD && "Cannot be null!"); R.addDecl(VD); return true; } return false; } // The callback is used to update the list of globals in ROOT. // void TClingCallbacks::TransactionCommitted(const Transaction &T) { if (!T.size()) return; if (fFirstRun) { // Before setting up the callbacks register what cling have seen during init. const cling::Transaction* T = m_Interpreter->getFirstTransaction(); while (T) { if (T->getState() == cling::Transaction::kCommitted) TCintWithCling__UpdateListsOnCommitted(*T); T = T->getNext(); } fFirstRun = false; } TCintWithCling__UpdateListsOnCommitted(T); } // The callback is used to update the list of globals in ROOT. // void TClingCallbacks::TransactionUnloaded(const Transaction &T) { if (!T.size()) return; TCintWithCling__UpdateListsOnUnloaded(T); }
Insert the caching code (formely in TCintWithCling::FindSpecialObject) to be re-add in 6.02
Insert the caching code (formely in TCintWithCling::FindSpecialObject) to be re-add in 6.02 git-svn-id: ecbadac9c76e8cf640a0bca86f6bd796c98521e3@47794 27541ba8-7e3a-0410-8455-c3a389f83636
C++
lgpl-2.1
bbannier/ROOT,bbannier/ROOT,bbannier/ROOT,bbannier/ROOT,bbannier/ROOT,bbannier/ROOT,bbannier/ROOT
4db362a83d0ead168bcdc0376f5f24a1f7466a85
core/src/oned/ODDataBarReader.cpp
core/src/oned/ODDataBarReader.cpp
/* * Copyright 2016 Nu-book Inc. * Copyright 2016 ZXing authors * Copyright 2020 Axel Waggershauser */ // SPDX-License-Identifier: Apache-2.0 #include "ODDataBarReader.h" #include "BarcodeFormat.h" #include "DecoderResult.h" #include "GTIN.h" #include "ODDataBarCommon.h" #include "Result.h" #include "TextDecoder.h" #include <iomanip> #include <sstream> #include <unordered_set> namespace ZXing::OneD { using namespace DataBar; DataBarReader::DataBarReader(const DecodeHints&) {} DataBarReader::~DataBarReader() = default; static bool IsCharacterPair(PatternView v, int modsLeft, int modsRight) { float modSizeRef = ModSizeFinder(v); return IsCharacter(LeftChar(v), modsLeft, modSizeRef) && IsCharacter(RightChar(v), modsRight, modSizeRef); } static bool IsLeftPair(const PatternView& v) { return IsFinder(v[8], v[9], v[10], v[11], v[12]) && IsGuard(v[-1], v[11]) && IsCharacterPair(v, 16, 15); } static bool IsRightPair(const PatternView& v) { return IsFinder(v[12], v[11], v[10], v[9], v[8]) && IsGuard(v[9], v[21]) && IsCharacterPair(v, 15, 16); } static Character ReadDataCharacter(const PatternView& view, bool outsideChar, bool rightPair) { constexpr int OUTSIDE_EVEN_TOTAL_SUBSET[] = {1, 10, 34, 70, 126}; constexpr int INSIDE_ODD_TOTAL_SUBSET[] = {4, 20, 48, 81}; constexpr int OUTSIDE_GSUM[] = {0, 161, 961, 2015, 2715}; constexpr int INSIDE_GSUM[] = {0, 336, 1036, 1516}; constexpr int OUTSIDE_ODD_WIDEST[] = {8, 6, 4, 3, 1}; constexpr int INSIDE_ODD_WIDEST[] = {2, 4, 6, 8}; Array4I oddPattern = {}, evnPattern = {}; if (!ReadDataCharacterRaw(view, outsideChar ? 16 : 15, outsideChar == rightPair, oddPattern, evnPattern)) return {}; auto calcChecksumPortion = [](const Array4I& counts) { int res = 0; for (auto it = counts.rbegin(); it != counts.rend(); ++it) res = 9 * res + *it; return res; }; int checksumPortion = calcChecksumPortion(oddPattern) + 3 * calcChecksumPortion(evnPattern); if (outsideChar) { int oddSum = Reduce(oddPattern); assert((oddSum & 1) == 0 && oddSum <= 12 && oddSum >= 4); // checked in ReadDataCharacterRaw int group = (12 - oddSum) / 2; int oddWidest = OUTSIDE_ODD_WIDEST[group]; int evnWidest = 9 - oddWidest; int vOdd = GetValue(oddPattern, oddWidest, false); int vEvn = GetValue(evnPattern, evnWidest, true); int tEvn = OUTSIDE_EVEN_TOTAL_SUBSET[group]; int gSum = OUTSIDE_GSUM[group]; return {vOdd * tEvn + vEvn + gSum, checksumPortion}; } else { int evnSum = Reduce(evnPattern); assert((evnSum & 1) == 0 && evnSum <= 12 && evnSum >= 4); // checked in ReadDataCharacterRaw int group = (10 - evnSum) / 2; int oddWidest = INSIDE_ODD_WIDEST[group]; int evnWidest = 9 - oddWidest; int vOdd = GetValue(oddPattern, oddWidest, true); int vEvn = GetValue(evnPattern, evnWidest, false); int tOdd = INSIDE_ODD_TOTAL_SUBSET[group]; int gSum = INSIDE_GSUM[group]; return {vEvn * tOdd + vOdd + gSum, checksumPortion}; } } int ParseFinderPattern(const PatternView& view, bool reversed) { static constexpr std::array<FixedPattern<5, 15>, 10> FINDER_PATTERNS = {{ {3, 8, 2, 1, 1}, {3, 5, 5, 1, 1}, {3, 3, 7, 1, 1}, {3, 1, 9, 1, 1}, {2, 7, 4, 1, 1}, {2, 5, 6, 1, 1}, {2, 3, 8, 1, 1}, {1, 5, 7, 1, 1}, {1, 3, 9, 1, 1}, }}; // TODO: c++20 constexpr inversion from FIND_PATTERN? static constexpr std::array<FixedPattern<5, 15>, 10> REVERSED_FINDER_PATTERNS = {{ {1, 1, 2, 8, 3}, {1, 1, 5, 5, 3}, {1, 1, 7, 3, 3}, {1, 1, 9, 1, 3}, {1, 1, 4, 7, 2}, {1, 1, 6, 5, 2}, {1, 1, 8, 3, 2}, {1, 1, 7, 5, 1}, {1, 1, 9, 3, 1}, }}; return ParseFinderPattern(view, reversed, FINDER_PATTERNS, REVERSED_FINDER_PATTERNS); } static Pair ReadPair(const PatternView& view, bool rightPair) { if (int pattern = ParseFinderPattern(Finder(view), rightPair)) if (auto outside = ReadDataCharacter(rightPair ? RightChar(view) : LeftChar(view), true, rightPair)) if (auto inside = ReadDataCharacter(rightPair ? LeftChar(view) : RightChar(view), false, rightPair)) { // include left and right guards int xStart = view.pixelsInFront() - view[-1]; int xStop = view.pixelsTillEnd() + 2 * view[FULL_PAIR_SIZE]; return {outside, inside, pattern, xStart, xStop}; } return {}; } static bool ChecksumIsValid(Pair leftPair, Pair rightPair) { auto checksum = [](Pair p) { return p.left.checksum + 4 * p.right.checksum; }; int a = (checksum(leftPair) + 16 * checksum(rightPair)) % 79; int b = 9 * (std::abs(leftPair.finder) - 1) + (std::abs(rightPair.finder) - 1); if (b > 72) b--; if (b > 8) b--; return a == b; } static std::string ConstructText(Pair leftPair, Pair rightPair) { auto value = [](Pair p) { return 1597 * p.left.value + p.right.value; }; auto res = 4537077LL * value(leftPair) + value(rightPair); std::ostringstream txt; txt << std::setw(13) << std::setfill('0') << res; txt << GTIN::ComputeCheckDigit(txt.str()); return txt.str(); } struct State : public RowReader::DecodingState { std::unordered_set<Pair, PairHash> leftPairs; std::unordered_set<Pair, PairHash> rightPairs; }; Result DataBarReader::decodePattern(int rowNumber, PatternView& next, std::unique_ptr<RowReader::DecodingState>& state) const { #if 0 // non-stacked version next = next.subView(-1, FULL_PAIR_SIZE); // yes: the first view we test is at index 1 (black bar at 0 would be the guard pattern) while (next.shift(2)) { if (IsLeftPair(next)) { if (auto leftPair = ReadPair(next, false); leftPair && next.shift(FULL_PAIR_SIZE) && IsRightPair(next)) { if (auto rightPair = ReadPair(next, true); rightPair && ChecksumIsValid(leftPair, rightPair)) { return {ConstructText(leftPair, rightPair), rowNumber, leftPair.xStart, rightPair.xStop, BarcodeFormat::DataBar}; } } } } #else if (!state) state.reset(new State); auto* prevState = static_cast<State*>(state.get()); next = next.subView(0, FULL_PAIR_SIZE); // yes: the first view we test is at index 1 (black bar at 0 would be the guard pattern) while (next.shift(1)) { if (IsLeftPair(next)) { if (auto leftPair = ReadPair(next, false)) { leftPair.y = rowNumber; prevState->leftPairs.insert(leftPair); next.shift(FULL_PAIR_SIZE - 1); } } if (next.shift(1) && IsRightPair(next)) { if (auto rightPair = ReadPair(next, true)) { rightPair.y = rowNumber; prevState->rightPairs.insert(rightPair); next.shift(FULL_PAIR_SIZE + 2); } } } for (const auto& leftPair : prevState->leftPairs) for (const auto& rightPair : prevState->rightPairs) if (ChecksumIsValid(leftPair, rightPair)) { // Symbology identifier ISO/IEC 24724:2011 Section 9 and GS1 General Specifications 5.1.3 Figure 5.1.3-2 Result res{DecoderResult({}, TextDecoder::FromLatin1(ConstructText(leftPair, rightPair))) .setSymbologyIdentifier("]e0") .setLineCount(EstimateLineCount(leftPair, rightPair)), EstimatePosition(leftPair, rightPair), BarcodeFormat::DataBar}; prevState->leftPairs.erase(leftPair); prevState->rightPairs.erase(rightPair); return res; } #endif // guaratee progress (see loop in ODReader.cpp) next = {}; return Result(DecodeStatus::NotFound); } } // namespace ZXing::OneD
/* * Copyright 2016 Nu-book Inc. * Copyright 2016 ZXing authors * Copyright 2020 Axel Waggershauser */ // SPDX-License-Identifier: Apache-2.0 #include "ODDataBarReader.h" #include "BarcodeFormat.h" #include "DecoderResult.h" #include "GTIN.h" #include "ODDataBarCommon.h" #include "Result.h" #include "TextDecoder.h" #include <iomanip> #include <sstream> #include <unordered_set> namespace ZXing::OneD { using namespace DataBar; DataBarReader::DataBarReader(const DecodeHints&) {} DataBarReader::~DataBarReader() = default; static bool IsCharacterPair(PatternView v, int modsLeft, int modsRight) { float modSizeRef = ModSizeFinder(v); return IsCharacter(LeftChar(v), modsLeft, modSizeRef) && IsCharacter(RightChar(v), modsRight, modSizeRef); } static bool IsLeftPair(const PatternView& v) { return IsFinder(v[8], v[9], v[10], v[11], v[12]) && IsGuard(v[-1], v[11]) && IsCharacterPair(v, 16, 15); } static bool IsRightPair(const PatternView& v) { return IsFinder(v[12], v[11], v[10], v[9], v[8]) && IsGuard(v[9], v[21]) && IsCharacterPair(v, 15, 16); } static Character ReadDataCharacter(const PatternView& view, bool outsideChar, bool rightPair) { constexpr int OUTSIDE_EVEN_TOTAL_SUBSET[] = {1, 10, 34, 70, 126}; constexpr int INSIDE_ODD_TOTAL_SUBSET[] = {4, 20, 48, 81}; constexpr int OUTSIDE_GSUM[] = {0, 161, 961, 2015, 2715}; constexpr int INSIDE_GSUM[] = {0, 336, 1036, 1516}; constexpr int OUTSIDE_ODD_WIDEST[] = {8, 6, 4, 3, 1}; constexpr int INSIDE_ODD_WIDEST[] = {2, 4, 6, 8}; Array4I oddPattern = {}, evnPattern = {}; if (!ReadDataCharacterRaw(view, outsideChar ? 16 : 15, outsideChar == rightPair, oddPattern, evnPattern)) return {}; auto calcChecksumPortion = [](const Array4I& counts) { int res = 0; for (auto it = counts.rbegin(); it != counts.rend(); ++it) res = 9 * res + *it; return res; }; int checksumPortion = calcChecksumPortion(oddPattern) + 3 * calcChecksumPortion(evnPattern); if (outsideChar) { int oddSum = Reduce(oddPattern); assert((oddSum & 1) == 0 && oddSum <= 12 && oddSum >= 4); // checked in ReadDataCharacterRaw int group = (12 - oddSum) / 2; int oddWidest = OUTSIDE_ODD_WIDEST[group]; int evnWidest = 9 - oddWidest; int vOdd = GetValue(oddPattern, oddWidest, false); int vEvn = GetValue(evnPattern, evnWidest, true); int tEvn = OUTSIDE_EVEN_TOTAL_SUBSET[group]; int gSum = OUTSIDE_GSUM[group]; return {vOdd * tEvn + vEvn + gSum, checksumPortion}; } else { int evnSum = Reduce(evnPattern); assert((evnSum & 1) == 0 && evnSum <= 12 && evnSum >= 4); // checked in ReadDataCharacterRaw int group = (10 - evnSum) / 2; int oddWidest = INSIDE_ODD_WIDEST[group]; int evnWidest = 9 - oddWidest; int vOdd = GetValue(oddPattern, oddWidest, true); int vEvn = GetValue(evnPattern, evnWidest, false); int tOdd = INSIDE_ODD_TOTAL_SUBSET[group]; int gSum = INSIDE_GSUM[group]; return {vEvn * tOdd + vOdd + gSum, checksumPortion}; } } int ParseFinderPattern(const PatternView& view, bool reversed) { static constexpr std::array<FixedPattern<5, 15>, 10> FINDER_PATTERNS = {{ {3, 8, 2, 1, 1}, {3, 5, 5, 1, 1}, {3, 3, 7, 1, 1}, {3, 1, 9, 1, 1}, {2, 7, 4, 1, 1}, {2, 5, 6, 1, 1}, {2, 3, 8, 1, 1}, {1, 5, 7, 1, 1}, {1, 3, 9, 1, 1}, }}; // TODO: c++20 constexpr inversion from FIND_PATTERN? static constexpr std::array<FixedPattern<5, 15>, 10> REVERSED_FINDER_PATTERNS = {{ {1, 1, 2, 8, 3}, {1, 1, 5, 5, 3}, {1, 1, 7, 3, 3}, {1, 1, 9, 1, 3}, {1, 1, 4, 7, 2}, {1, 1, 6, 5, 2}, {1, 1, 8, 3, 2}, {1, 1, 7, 5, 1}, {1, 1, 9, 3, 1}, }}; return ParseFinderPattern(view, reversed, FINDER_PATTERNS, REVERSED_FINDER_PATTERNS); } static Pair ReadPair(const PatternView& view, bool rightPair) { if (int pattern = ParseFinderPattern(Finder(view), rightPair)) if (auto outside = ReadDataCharacter(rightPair ? RightChar(view) : LeftChar(view), true, rightPair)) if (auto inside = ReadDataCharacter(rightPair ? LeftChar(view) : RightChar(view), false, rightPair)) { // include left and right guards int xStart = view.pixelsInFront() - view[-1]; int xStop = view.pixelsTillEnd() + 2 * view[FULL_PAIR_SIZE]; return {outside, inside, pattern, xStart, xStop}; } return {}; } static bool ChecksumIsValid(Pair leftPair, Pair rightPair) { auto checksum = [](Pair p) { return p.left.checksum + 4 * p.right.checksum; }; int a = (checksum(leftPair) + 16 * checksum(rightPair)) % 79; int b = 9 * (std::abs(leftPair.finder) - 1) + (std::abs(rightPair.finder) - 1); if (b > 72) b--; if (b > 8) b--; return a == b; } static std::string ConstructText(Pair leftPair, Pair rightPair) { auto value = [](Pair p) { return 1597 * p.left.value + p.right.value; }; auto res = 4537077LL * value(leftPair) + value(rightPair); std::ostringstream txt; txt << std::setw(13) << std::setfill('0') << res; txt << GTIN::ComputeCheckDigit(txt.str()); return txt.str(); } struct State : public RowReader::DecodingState { std::unordered_set<Pair, PairHash> leftPairs; std::unordered_set<Pair, PairHash> rightPairs; }; Result DataBarReader::decodePattern(int rowNumber, PatternView& next, std::unique_ptr<RowReader::DecodingState>& state) const { #if 0 // non-stacked version next = next.subView(-1, FULL_PAIR_SIZE + 1); // +1 reflects the guard pattern on the right, see IsRightPair()); // yes: the first view we test is at index 1 (black bar at 0 would be the guard pattern) while (next.shift(2)) { if (IsLeftPair(next)) { if (auto leftPair = ReadPair(next, false); leftPair && next.shift(FULL_PAIR_SIZE) && IsRightPair(next)) { if (auto rightPair = ReadPair(next, true); rightPair && ChecksumIsValid(leftPair, rightPair)) { return {ConstructText(leftPair, rightPair), rowNumber, leftPair.xStart, rightPair.xStop, BarcodeFormat::DataBar}; } } } } #else if (!state) state.reset(new State); auto* prevState = static_cast<State*>(state.get()); next = next.subView(0, FULL_PAIR_SIZE + 1); // +1 reflects the guard pattern on the right, see IsRightPair() // yes: the first view we test is at index 1 (black bar at 0 would be the guard pattern) while (next.shift(1)) { if (IsLeftPair(next)) { if (auto leftPair = ReadPair(next, false)) { leftPair.y = rowNumber; prevState->leftPairs.insert(leftPair); next.shift(FULL_PAIR_SIZE - 1); } } if (next.shift(1) && IsRightPair(next)) { if (auto rightPair = ReadPair(next, true)) { rightPair.y = rowNumber; prevState->rightPairs.insert(rightPair); next.shift(FULL_PAIR_SIZE + 2); } } } for (const auto& leftPair : prevState->leftPairs) for (const auto& rightPair : prevState->rightPairs) if (ChecksumIsValid(leftPair, rightPair)) { // Symbology identifier ISO/IEC 24724:2011 Section 9 and GS1 General Specifications 5.1.3 Figure 5.1.3-2 Result res{DecoderResult({}, TextDecoder::FromLatin1(ConstructText(leftPair, rightPair))) .setSymbologyIdentifier("]e0") .setLineCount(EstimateLineCount(leftPair, rightPair)), EstimatePosition(leftPair, rightPair), BarcodeFormat::DataBar}; prevState->leftPairs.erase(leftPair); prevState->rightPairs.erase(rightPair); return res; } #endif // guaratee progress (see loop in ODReader.cpp) next = {}; return Result(DecodeStatus::NotFound); } } // namespace ZXing::OneD
fix heap overflow regression
ODDataBarReader: fix heap overflow regression
C++
apache-2.0
nu-book/zxing-cpp,nu-book/zxing-cpp,nu-book/zxing-cpp,nu-book/zxing-cpp,huycn/zxing-cpp,huycn/zxing-cpp,huycn/zxing-cpp,huycn/zxing-cpp,nu-book/zxing-cpp,huycn/zxing-cpp,nu-book/zxing-cpp,huycn/zxing-cpp,huycn/zxing-cpp,huycn/zxing-cpp,nu-book/zxing-cpp,nu-book/zxing-cpp
9953d7fc06ef5db2701d37b62d227fcebd9f70f2
applications/mne_scan/plugins/ftbuffer/FormFiles/ftbuffersetupwidget.cpp
applications/mne_scan/plugins/ftbuffer/FormFiles/ftbuffersetupwidget.cpp
//============================================================================================================= /** * @file ftbuffersetupwidget.cpp * @author Gabriel B Motta <[email protected]> * @since 0.1.0 * @date January, 2020 * * @section LICENSE * * Copyright (C) 2020, Gabriel B Motta. 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 Definition of the FtBufferSetupWidget class. * */ //============================================================================================================= // INCLUDES //============================================================================================================= #include "ftbuffersetupwidget.h" #include "ui_ftbuffersetup.h" //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <QDebug> //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace FTBUFFERPLUGIN; //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= FtBufferSetupWidget::FtBufferSetupWidget(FtBuffer* toolbox, const QString& sSettingsPath, QWidget *parent) : QWidget(parent) , m_pFtBuffer(toolbox) , m_sSettingsPath(sSettingsPath) , m_pUi(new Ui::FtBufferSetupUi) { m_pUi->setupUi(this); this->m_pUi->m_lineEditIP->setText(toolbox->m_pFtBuffProducer->m_pFtConnector->getAddr()); loadSettings(); //Always connect GUI elemts after m_pUi->setpUi has been called connect(m_pUi->m_qPushButton_Connect, &QPushButton::released, this, &FtBufferSetupWidget::pressedConnect); // Connect/Disconnect button connect(this, &FtBufferSetupWidget::connectAtAddr, m_pFtBuffer->m_pFtBuffProducer.data(), &FtBuffProducer::connectToBuffer); connect(m_pFtBuffer->m_pFtBuffProducer.data(), &FtBuffProducer::connecStatus, this, &FtBufferSetupWidget::isConnected); connect(m_pUi->m_lineEditIP, &QLineEdit::textChanged, toolbox, &FtBuffer::setBufferAddress); connect(m_pUi->m_spinBoxPort, qOverload<int>(&QSpinBox::valueChanged), toolbox, &FtBuffer::setBufferPort); toolbox->setBufferAddress(m_pUi->m_lineEditIP->text()); toolbox->setBufferPort(m_pUi->m_spinBoxPort->value()); } //============================================================================================================= FtBufferSetupWidget::~FtBufferSetupWidget() { saveSettings(); } //============================================================================================================= void FtBufferSetupWidget::saveSettings() { if(m_sSettingsPath.isEmpty()) { return; } // Save Settings QSettings settings("MNECPP"); settings.setValue(m_sSettingsPath + QString("/IP"), m_pUi->m_lineEditIP->text()); } //============================================================================================================= void FtBufferSetupWidget::loadSettings() { if(m_sSettingsPath.isEmpty()) { return; } // Load Settings QSettings settings("MNECPP"); m_pUi->m_lineEditIP->setText(settings.value(m_sSettingsPath + QString("/IP"), "127.0.0.1").toString()); } //============================================================================================================= void FtBufferSetupWidget::pressedConnect() { emit connectAtAddr(m_pUi->m_lineEditIP->text(), m_pUi->m_spinBoxPort->value()); } //============================================================================================================= void FtBufferSetupWidget::isConnected(bool stat) { if (stat) { m_pUi->m_qPushButton_Connect->setText("Set"); } else { qWarning() << "[FtBufferSetupWidget::isConnected] Unable to find relevant fiff info."; QMessageBox msgBox; msgBox.setText("Unable to find relevant fiff info. Is there header data in the buffer?"); msgBox.exec(); } }
//============================================================================================================= /** * @file ftbuffersetupwidget.cpp * @author Gabriel B Motta <[email protected]> * @since 0.1.0 * @date January, 2020 * * @section LICENSE * * Copyright (C) 2020, Gabriel B Motta. 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 Definition of the FtBufferSetupWidget class. * */ //============================================================================================================= // INCLUDES //============================================================================================================= #include "ftbuffersetupwidget.h" #include "ui_ftbuffersetup.h" //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <QDebug> //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace FTBUFFERPLUGIN; //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= FtBufferSetupWidget::FtBufferSetupWidget(FtBuffer* toolbox, const QString& sSettingsPath, QWidget *parent) : QWidget(parent) , m_pFtBuffer(toolbox) , m_sSettingsPath(sSettingsPath) , m_pUi(new Ui::FtBufferSetupUi) { m_pUi->setupUi(this); this->m_pUi->m_lineEditIP->setText(toolbox->m_pFtBuffProducer->m_pFtConnector->getAddr()); loadSettings(); //Always connect GUI elemts after m_pUi->setpUi has been called connect(m_pUi->m_qPushButton_Connect, &QPushButton::released, this, &FtBufferSetupWidget::pressedConnect); // Connect/Disconnect button connect(this, &FtBufferSetupWidget::connectAtAddr, m_pFtBuffer->m_pFtBuffProducer.data(), &FtBuffProducer::connectToBuffer); connect(m_pFtBuffer->m_pFtBuffProducer.data(), &FtBuffProducer::connecStatus, this, &FtBufferSetupWidget::isConnected); connect(m_pUi->m_lineEditIP, &QLineEdit::textChanged, toolbox, &FtBuffer::setBufferAddress); connect(m_pUi->m_spinBoxPort, QOverload<int>::of(&QSpinBox::valueChanged), toolbox, &FtBuffer::setBufferPort); toolbox->setBufferAddress(m_pUi->m_lineEditIP->text()); toolbox->setBufferPort(m_pUi->m_spinBoxPort->value()); } //============================================================================================================= FtBufferSetupWidget::~FtBufferSetupWidget() { saveSettings(); } //============================================================================================================= void FtBufferSetupWidget::saveSettings() { if(m_sSettingsPath.isEmpty()) { return; } // Save Settings QSettings settings("MNECPP"); settings.setValue(m_sSettingsPath + QString("/IP"), m_pUi->m_lineEditIP->text()); } //============================================================================================================= void FtBufferSetupWidget::loadSettings() { if(m_sSettingsPath.isEmpty()) { return; } // Load Settings QSettings settings("MNECPP"); m_pUi->m_lineEditIP->setText(settings.value(m_sSettingsPath + QString("/IP"), "127.0.0.1").toString()); } //============================================================================================================= void FtBufferSetupWidget::pressedConnect() { emit connectAtAddr(m_pUi->m_lineEditIP->text(), m_pUi->m_spinBoxPort->value()); } //============================================================================================================= void FtBufferSetupWidget::isConnected(bool stat) { if (stat) { m_pUi->m_qPushButton_Connect->setText("Set"); } else { qWarning() << "[FtBufferSetupWidget::isConnected] Unable to find relevant fiff info."; QMessageBox msgBox; msgBox.setText("Unable to find relevant fiff info. Is there header data in the buffer?"); msgBox.exec(); } }
use correct qoverload
DEBUG: use correct qoverload
C++
bsd-3-clause
mne-tools/mne-cpp,chdinh/mne-cpp,mne-tools/mne-cpp,mne-tools/mne-cpp,mne-tools/mne-cpp,chdinh/mne-cpp,chdinh/mne-cpp,chdinh/mne-cpp,chdinh/mne-cpp,chdinh/mne-cpp,mne-tools/mne-cpp,mne-tools/mne-cpp
ca6f1f1871512a3ef742959f7d99a0d1dde716bb
tutorials/EdmundOptics.C
tutorials/EdmundOptics.C
// Author: Akira Okumura 2012/11/26 // Examples for simple optical systems which use products by Edmund Optics. // define useful units static const Double_t cm = AOpticsManager::cm(); static const Double_t mm = AOpticsManager::mm(); static const Double_t um = AOpticsManager::um(); static const Double_t nm = AOpticsManager::nm(); static const Double_t m = AOpticsManager::m(); void EdmundOptics() { // Aspherized achromatic lens. // http://www.edmundoptics.com/optics/optical-lenses/aspheric-lenses/aspherized-achromatic-lenses/2953 // ZEMAX data is available at // http://www.edmundoptics.jp/techsupport/resource_center/product_docs/zmax_49665.zmx AOpticsManager* manager = new AOpticsManager("NT49665", "NT49665"); // Make the world TGeoBBox* box = new TGeoBBox("box", 10 * cm, 10 * cm, 10 * cm); AOpticalComponent* top = new AOpticalComponent("top", box); manager->SetTopVolume(top); Double_t rmax = 12.5 * mm; Double_t rmin = 0. * mm; Double_t d1 = 9.0 * mm; Double_t d2 = 2.5 * mm; Double_t d3 = 8e-2 * mm; Double_t d4 = 4.40605264801e1 * mm; Double_t z1 = 0 * mm; Double_t z2 = z1 + d1; Double_t z3 = z2 + d2; Double_t z4 = z3 + d3; Double_t z5 = z4 + d4; Double_t curv1 = 1. / (28.5 * mm); Double_t curv2 = 1. / (-31.0 * mm); Double_t curv3 = 1. / (-66.0 * mm); Double_t curv4 = 1. / (-63.0 * mm); AGeoAsphericDisk* disk1 = new AGeoAsphericDisk("disk1", z1, curv1, z2, curv2, rmax, rmin); AGeoAsphericDisk* disk2 = new AGeoAsphericDisk("disk2", z2, curv2, z3, curv3, rmax, rmin); AGeoAsphericDisk* disk3 = new AGeoAsphericDisk("disk3", z3, curv3, z4, curv4, rmax, rmin); Double_t coefficients[3] = {0, 4.66252900195e-6 / (mm * mm * mm), -8.02842124899e-9 / (mm * mm * mm * mm * mm)}; disk3->SetPolynomials(0, 0, 3, coefficients); // Ohara S-FSL5 // http://www.ohara-inc.co.jp/jp/product/optical/dl/data/jsfsl05.pdf ASellmeierFormula* FSL5 = new ASellmeierFormula(1.17447043e0, 1.40056154e-2, 1.19272435e0, 8.41855181e-3, -5.81790767e-2, 1.29599726e2); // should be 1.48749 std::cout << FSL5->GetRefractiveIndex(0.58756 * um) << std::endl; // S-TIH13 // http://www.ohara-inc.co.jp/jp/product/optical/dl/data/jstih13.pdf ASellmeierFormula* TIH13 = new ASellmeierFormula(1.62224674e0, 2.93844589e-1, 1.99225164e0, 1.18368386e-2, 5.90208025e-2, 1.71959976e2); // should be 1.74077 std::cout << TIH13->GetRefractiveIndex(0.58756 * um) << std::endl; ALens* lens1 = new ALens("lens1", disk1); lens1->SetRefractiveIndex(FSL5); ALens* lens2 = new ALens("lens2", disk2); lens2->SetRefractiveIndex(TIH13); ALens* lens3 = new ALens("lens3", disk3); lens3->SetConstantRefractiveIndex(1.517); top->AddNode(lens1, 1); top->AddNode(lens2, 1); top->AddNode(lens3, 1); Double_t origin[3] = {0, 0, z5 + 1 * um}; TGeoBBox* box2 = new TGeoBBox("box2", 1 * mm, 1 * mm, 1 * um, origin); AFocalSurface* screen = new AFocalSurface("screen", box2); top->AddNode(screen, 1); manager->CloseGeometry(); top->Draw("ogl"); TGeoRotation* rot = new TGeoRotation; rot->SetAngles(180., 0., 0.); TGeoTranslation* tr = new TGeoTranslation("tr", 0, 0, -15 * mm); const Int_t nColor = 3; Double_t wavelength[nColor] = {486.1 * nm, 587.6 * nm, 656.3 * nm}; // n_F, n_d, n_C TH2D* spot[nColor]; for (Int_t j = 0; j < nColor; j++) { ARayArray* array = ARayShooter::Circle(wavelength[j], rmax * 1.1, 50, 4, rot, tr); manager->TraceNonSequential(*array); spot[j] = new TH2D(Form("spot%d", j), Form("Spot Diagram for #it{#lambda} = %5.1f (nm);X " "(#it{#mu}m);Y (#it{#mu}m)", wavelength[j] / nm), 500, -25, 25, 500, -25, 25); TObjArray* focused = array->GetFocused(); for (Int_t i = 0; i <= focused->GetLast(); i++) { ARay* ray = (ARay*)(*focused)[i]; if (j == 1 && i % 10 == 0) { ray->MakePolyLine3D()->Draw(); } // if Double_t p[4]; ray->GetLastPoint(p); spot[j]->Fill(p[0] / um, p[1] / um); } // i delete array; } // j TCanvas* can = new TCanvas("can", "can", 1200, 400); can->Divide(3, 1, 1e-10, 1e-10); for (int i = 0; i < nColor; i++) { can->cd(i + 1); spot[i]->Draw("colz"); } // i }
// Author: Akira Okumura 2012/11/26 // Examples for simple optical systems which use products by Edmund Optics. // define useful units static const Double_t cm = AOpticsManager::cm(); static const Double_t mm = AOpticsManager::mm(); static const Double_t um = AOpticsManager::um(); static const Double_t nm = AOpticsManager::nm(); static const Double_t m = AOpticsManager::m(); void EdmundOptics() { // Aspherized achromatic lens. // http://www.edmundoptics.com/optics/optical-lenses/aspheric-lenses/aspherized-achromatic-lenses/2953 // ZEMAX data is available at // http://www.edmundoptics.jp/techsupport/resource_center/product_docs/zmax_49665.zmx AOpticsManager* manager = new AOpticsManager("NT49665", "NT49665"); // Make the world TGeoBBox* box = new TGeoBBox("box", 10 * cm, 10 * cm, 10 * cm); AOpticalComponent* top = new AOpticalComponent("top", box); manager->SetTopVolume(top); Double_t rmax = 12.5 * mm; Double_t rmin = 0. * mm; Double_t d1 = 9.0 * mm; Double_t d2 = 2.5 * mm; Double_t d3 = 8e-2 * mm; Double_t d4 = 4.40605264801e1 * mm; Double_t z1 = 0 * mm; Double_t z2 = z1 + d1; Double_t z3 = z2 + d2; Double_t z4 = z3 + d3; Double_t z5 = z4 + d4; Double_t curv1 = 1. / (28.5 * mm); Double_t curv2 = 1. / (-31.0 * mm); Double_t curv3 = 1. / (-66.0 * mm); Double_t curv4 = 1. / (-63.0 * mm); AGeoAsphericDisk* disk1 = new AGeoAsphericDisk("disk1", z1, curv1, z2, curv2, rmax, rmin); AGeoAsphericDisk* disk2 = new AGeoAsphericDisk("disk2", z2, curv2, z3, curv3, rmax, rmin); AGeoAsphericDisk* disk3 = new AGeoAsphericDisk("disk3", z3, curv3, z4, curv4, rmax, rmin); Double_t coefficients[3] = {0, 4.66252900195e-6 / (mm * mm * mm), -8.02842124899e-9 / (mm * mm * mm * mm * mm)}; disk3->SetPolynomials(0, 0, 3, coefficients); // Ohara S-FSL5 // http://www.ohara-inc.co.jp/jp/product/optical/dl/data/jsfsl05.pdf auto FSL5 = std::make_shared<ASellmeierFormula>(1.17447043e0, 1.40056154e-2, 1.19272435e0, 8.41855181e-3, -5.81790767e-2, 1.29599726e2); // should be 1.48749 std::cout << FSL5->GetRefractiveIndex(0.58756 * um) << std::endl; // S-TIH13 // http://www.ohara-inc.co.jp/jp/product/optical/dl/data/jstih13.pdf auto TIH13 = std::make_shared<ASellmeierFormula>(1.62224674e0, 2.93844589e-1, 1.99225164e0, 1.18368386e-2, 5.90208025e-2, 1.71959976e2); // should be 1.74077 std::cout << TIH13->GetRefractiveIndex(0.58756 * um) << std::endl; ALens* lens1 = new ALens("lens1", disk1); lens1->SetRefractiveIndex(FSL5); ALens* lens2 = new ALens("lens2", disk2); lens2->SetRefractiveIndex(TIH13); ALens* lens3 = new ALens("lens3", disk3); lens3->SetRefractiveIndex(std::make_shared<ARefractiveIndex>(1.517)); top->AddNode(lens1, 1); top->AddNode(lens2, 1); top->AddNode(lens3, 1); Double_t origin[3] = {0, 0, z5 + 1 * um}; TGeoBBox* box2 = new TGeoBBox("box2", 1 * mm, 1 * mm, 1 * um, origin); AFocalSurface* screen = new AFocalSurface("screen", box2); top->AddNode(screen, 1); manager->CloseGeometry(); top->Draw("ogl"); TGeoRotation* rot = new TGeoRotation; rot->SetAngles(180., 0., 0.); TGeoTranslation* tr = new TGeoTranslation("tr", 0, 0, -15 * mm); const Int_t nColor = 3; Double_t wavelength[nColor] = {486.1 * nm, 587.6 * nm, 656.3 * nm}; // n_F, n_d, n_C TH2D* spot[nColor]; for (Int_t j = 0; j < nColor; j++) { ARayArray* array = ARayShooter::Circle(wavelength[j], rmax * 1.1, 50, 4, rot, tr); manager->TraceNonSequential(*array); spot[j] = new TH2D(Form("spot%d", j), Form("Spot Diagram for #it{#lambda} = %5.1f (nm);X " "(#it{#mu}m);Y (#it{#mu}m)", wavelength[j] / nm), 500, -25, 25, 500, -25, 25); TObjArray* focused = array->GetFocused(); for (Int_t i = 0; i <= focused->GetLast(); i++) { ARay* ray = (ARay*)(*focused)[i]; if (j == 1 && i % 10 == 0) { ray->MakePolyLine3D()->Draw(); } // if Double_t p[4]; ray->GetLastPoint(p); spot[j]->Fill(p[0] / um, p[1] / um); } // i delete array; } // j TCanvas* can = new TCanvas("can", "can", 1200, 400); can->Divide(3, 1, 1e-10, 1e-10); for (int i = 0; i < nColor; i++) { can->cd(i + 1); spot[i]->Draw("colz"); } // i }
Make it compatible with ROBAST 3
Make it compatible with ROBAST 3
C++
lgpl-2.1
ROBAST/ROBAST,ROBAST/ROBAST,ROBAST/ROBAST,ROBAST/ROBAST,ROBAST/ROBAST
6136f78e6f09cec72b35efaaa544ac9e04dd0a0c
cpp/include/geometry/Geometry.hpp
cpp/include/geometry/Geometry.hpp
#pragma once #include "../template/const_value.hpp" #include "../template/float_torelance.hpp" #include "../template/includes.hpp" template <typename real_t> using Vector = std::complex<real_t>; template <typename real_t> class Point { public: std::complex<real_t> p; Point() : p(0.0, 0.0) { ; } explicit Point(std::complex<real_t> p_) : p(p_) { ; } Point(real_t x, real_t y) : p(x, y) { ; } Vector<real_t> operator-(const Point &r) const { return p - r.p; } Point operator+(const Vector<real_t> &r) const { return Point(p + r); } Point operator-(const Vector<real_t> &r) const { return Point(p - r); } real_t x() const { return p.real(); } real_t y() const { return p.imag(); } }; template <typename real_t> std::istream &operator>>(std::istream &is, Point<real_t> &p) { real_t x, y; is >> x >> y; p = Point<real_t>(x, y); return is; } template <typename real_t> std::ostream &operator<<(std::ostream &os, const Point<real_t> &p) { os << p.p.real() << " " << p.p.imag(); return os; } // template <typename point_t> class Polygon { // std::vector<point_t> g; // Polygon() : g(0) { ; } // Polygon(const int n) : g(n, point_t()) { ; } // Polygon(const std::vector<point_t> &g_) : g(g_) { ; } // void push_back(const point_t &p) { g.push_back(p); } // point_t &front() { return g.front(); } // point_t &back() { return g.back(); } // int size() const { return g.size(); } // point_t &operator[](int i) { // i %= size(); // return g[i < 0 ? i + size() : i]; // } // }; template <typename real_t> real_t dot(Vector<real_t> a, Vector<real_t> b) { return std::real(std::conj(a) * b); } template <typename real_t> real_t cross(Vector<real_t> a, Vector<real_t> b) { return std::imag(std::conj(a) * b); } // counter clockwise template <typename real_t> int ccw(const Point<real_t> &a, const Point<real_t> &b, const Point<real_t> &c) { Vector<real_t> base = b - a, target = c - a; if (cross(base, target) > 0) return 1; // counter clockwise if (cross(base, target) < 0) return -1; // clockwise if (dot(base, target) < 0) return 2; // c--a--b on line if (norm(base) < norm(target)) return -2; // a--b--c on line return 0; // a--c--b on line } // std::vector<Point> unique(std::vector<Point> ps) { // std::sort(std::begin(ps), std::end(ps), comp); // std::vector<Point> res; // for (Point p : ps) // if (res.empty() || std::abs(res.back() - p) != 0) res.push_back(p); // return res; // }
#pragma once #include "../template/const_value.hpp" #include "../template/float_torelance.hpp" #include "../template/includes.hpp" template <typename real_t> using Vector = std::complex<real_t>; template <typename real_t> class Point { public: std::complex<real_t> p; Point() : p(0.0, 0.0) { ; } explicit Point(std::complex<real_t> p_) : p(p_) { ; } Point(real_t x, real_t y) : p(x, y) { ; } Vector<real_t> operator-(const Point &r) const { return p - r.p; } Point operator+(const Vector<real_t> &r) const { return Point(p + r); } Point operator-(const Vector<real_t> &r) const { return Point(p - r); } real_t x() const { return p.real(); } real_t y() const { return p.imag(); } bool operator==(const Point &r) { return abs(p == r.p) <= 0; } bool operator<(const Point &r) const { return x() < r.x() || (x() <= r.x() && y() < r.y()); } bool operator<=(const Point &r) const { return x() < r.x() || (x() <= r.x() && y() <= r.y()); } bool operator>(const Point &r) const { return x() > r.x() || (x() >= r.x() && y() > r.y()); } bool operator>=(const Point &r) const { return x() > r.x() || (x() >= r.x() && y() >= r.y()); } }; template <typename real_t> std::istream &operator>>(std::istream &is, Point<real_t> &p) { real_t x, y; is >> x >> y; p = Point<real_t>(x, y); return is; } template <typename real_t> std::ostream &operator<<(std::ostream &os, const Point<real_t> &p) { os << p.p.real() << " " << p.p.imag(); return os; } // template <typename point_t> class Polygon { // std::vector<point_t> g; // Polygon() : g(0) { ; } // Polygon(const int n) : g(n, point_t()) { ; } // Polygon(const std::vector<point_t> &g_) : g(g_) { ; } // void push_back(const point_t &p) { g.push_back(p); } // point_t &front() { return g.front(); } // point_t &back() { return g.back(); } // int size() const { return g.size(); } // point_t &operator[](int i) { // i %= size(); // return g[i < 0 ? i + size() : i]; // } // }; template <typename real_t> real_t dot(Vector<real_t> a, Vector<real_t> b) { return std::real(std::conj(a) * b); } template <typename real_t> real_t cross(Vector<real_t> a, Vector<real_t> b) { return std::imag(std::conj(a) * b); } // counter clockwise template <typename real_t> int ccw(const Point<real_t> &a, const Point<real_t> &b, const Point<real_t> &c) { Vector<real_t> base = b - a, target = c - a; if (cross(base, target) > 0) return 1; // counter clockwise if (cross(base, target) < 0) return -1; // clockwise if (dot(base, target) < 0) return 2; // c--a--b on line if (norm(base) < norm(target)) return -2; // a--b--c on line return 0; // a--c--b on line } // std::vector<Point> unique(std::vector<Point> ps) { // std::sort(std::begin(ps), std::end(ps), comp); // std::vector<Point> res; // for (Point p : ps) // if (res.empty() || std::abs(res.back() - p) != 0) res.push_back(p); // return res; // }
Add comparison of point
Add comparison of point
C++
mit
asi1024/competitive-library,asi1024/ContestLibrary,asi1024/competitive-library,asi1024/competitive-library
91d3f614766044a13b863d0b03e4f20f43f11669
cpp/libjoynr/proxy/Arbitrator.cpp
cpp/libjoynr/proxy/Arbitrator.cpp
/* * #%L * %% * Copyright (C) 2011 - 2017 BMW Car IT GmbH * %% * 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. * #L% */ #include "joynr/Arbitrator.h" #include <cassert> #include <chrono> #include <vector> #include <boost/algorithm/string/join.hpp> #include "joynr/Future.h" #include "joynr/Logger.h" #include "joynr/Semaphore.h" #include "joynr/exceptions/JoynrException.h" #include "joynr/exceptions/NoCompatibleProviderFoundException.h" #include "joynr/system/IDiscovery.h" #include "joynr/types/DiscoveryScope.h" namespace joynr { INIT_LOGGER(Arbitrator); Arbitrator::Arbitrator( const std::string& domain, const std::string& interfaceName, const joynr::types::Version& interfaceVersion, std::weak_ptr<joynr::system::IDiscoveryAsync> discoveryProxy, const DiscoveryQos& discoveryQos, std::unique_ptr<const ArbitrationStrategyFunction> arbitrationStrategyFunction) : discoveryProxy(discoveryProxy), discoveryQos(discoveryQos), systemDiscoveryQos(discoveryQos.getCacheMaxAgeMs(), discoveryQos.getDiscoveryTimeoutMs(), discoveryQos.getDiscoveryScope(), discoveryQos.getProviderMustSupportOnChange()), domains({domain}), interfaceName(interfaceName), interfaceVersion(interfaceVersion), discoveredIncompatibleVersions(), arbitrationError("Arbitration could not be finished in time."), arbitrationStrategyFunction(std::move(arbitrationStrategyFunction)), arbitrationFinished(false), arbitrationRunning(false), keepArbitrationRunning(false), arbitrationThread() { } Arbitrator::~Arbitrator() { keepArbitrationRunning = false; if (arbitrationThread.joinable()) { arbitrationThread.join(); } } void Arbitrator::startArbitration( std::function<void(const types::DiscoveryEntryWithMetaInfo& discoveryEntry)> onSuccess, std::function<void(const exceptions::DiscoveryException& exception)> onError) { if (arbitrationRunning) { return; } arbitrationRunning = true; keepArbitrationRunning = true; onSuccessCallback = onSuccess; onErrorCallback = onError; arbitrationThread = std::thread([this]() { Semaphore semaphore; arbitrationFinished = false; std::string serializedDomainsList = boost::algorithm::join(domains, ", "); JOYNR_LOG_DEBUG(logger, "DISCOVERY lookup for domain: [{}], interface: {}", serializedDomainsList, interfaceName); // Arbitrate until successful or timed out auto start = std::chrono::system_clock::now(); while (keepArbitrationRunning) { attemptArbitration(); if (arbitrationFinished) { return; } // If there are no suitable providers, retry the arbitration after the retry interval // elapsed auto now = std::chrono::system_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(now - start); if (discoveryQos.getDiscoveryTimeoutMs() <= duration.count()) { // discovery timeout reached break; } else if (discoveryQos.getDiscoveryTimeoutMs() - duration.count() <= discoveryQos.getRetryIntervalMs()) { /* * no retry possible -> wait until discoveryTimeout is reached and inform caller * about * cancelled arbitration */ semaphore.waitFor(std::chrono::milliseconds(discoveryQos.getDiscoveryTimeoutMs() - duration.count())); break; } else { // wait for retry interval and attempt a new arbitration semaphore.waitFor(std::chrono::milliseconds(discoveryQos.getRetryIntervalMs())); } } // If this point is reached the arbitration timed out if (!discoveredIncompatibleVersions.empty()) { onErrorCallback( exceptions::NoCompatibleProviderFoundException(discoveredIncompatibleVersions)); } else { onErrorCallback(arbitrationError); } arbitrationRunning = false; }); } void Arbitrator::attemptArbitration() { std::vector<joynr::types::DiscoveryEntryWithMetaInfo> result; try { if (auto discoveryProxySharedPtr = discoveryProxy.lock()) { if (discoveryQos.getArbitrationStrategy() == DiscoveryQos::ArbitrationStrategy::FIXED_PARTICIPANT) { types::DiscoveryEntryWithMetaInfo fixedParticipantResult; std::string fixedParticipantId = discoveryQos.getCustomParameter("fixedParticipantId").getValue(); auto future = discoveryProxySharedPtr->lookupAsync(fixedParticipantId); future->get(fixedParticipantResult); result.push_back(fixedParticipantResult); } else { auto future = discoveryProxySharedPtr->lookupAsync( domains, interfaceName, systemDiscoveryQos); future->get(result); } } else { throw exceptions::JoynrRuntimeException("discoveryProxy not available"); } receiveCapabilitiesLookupResults(result); } catch (const exceptions::JoynrException& e) { std::string errorMsg = "Unable to lookup provider (domain: " + (domains.size() > 0 ? domains.at(0) : std::string("EMPTY")) + ", interface: " + interfaceName + ") from discovery. Error: " + e.getMessage(); JOYNR_LOG_ERROR(logger, errorMsg); arbitrationError.setMessage(errorMsg); } } void Arbitrator::receiveCapabilitiesLookupResults( const std::vector<joynr::types::DiscoveryEntryWithMetaInfo>& discoveryEntries) { discoveredIncompatibleVersions.clear(); // Check for empty results if (discoveryEntries.size() == 0) { arbitrationError.setMessage("No entries found for domain: " + (domains.size() > 0 ? domains.at(0) : std::string("EMPTY")) + ", interface: " + interfaceName); return; } std::vector<joynr::types::DiscoveryEntryWithMetaInfo> preFilteredDiscoveryEntries; joynr::types::Version providerVersion; std::size_t providersWithoutSupportOnChange = 0; std::size_t providersWithIncompatibleVersion = 0; for (const joynr::types::DiscoveryEntryWithMetaInfo discoveryEntry : discoveryEntries) { types::ProviderQos providerQos = discoveryEntry.getQos(); JOYNR_LOG_TRACE(logger, "Looping over capabilitiesEntry: {}", discoveryEntry.toString()); providerVersion = discoveryEntry.getProviderVersion(); if (discoveryQos.getProviderMustSupportOnChange() && !providerQos.getSupportsOnChangeSubscriptions()) { ++providersWithoutSupportOnChange; continue; } if (providerVersion.getMajorVersion() != interfaceVersion.getMajorVersion() || providerVersion.getMinorVersion() < interfaceVersion.getMinorVersion()) { JOYNR_LOG_TRACE(logger, "Skipping capabilitiesEntry with incompatible version, expected: " + std::to_string(interfaceVersion.getMajorVersion()) + "." + std::to_string(interfaceVersion.getMinorVersion())); discoveredIncompatibleVersions.insert(providerVersion); ++providersWithIncompatibleVersion; continue; } preFilteredDiscoveryEntries.push_back(discoveryEntry); } if (preFilteredDiscoveryEntries.empty()) { std::string errorMsg; if (providersWithoutSupportOnChange == discoveryEntries.size()) { errorMsg = "There was more than one entries in capabilitiesEntries, but none supported " "on change subscriptions."; JOYNR_LOG_WARN(logger, errorMsg); arbitrationError.setMessage(errorMsg); } else if ((providersWithoutSupportOnChange + providersWithIncompatibleVersion) == discoveryEntries.size()) { errorMsg = "There was more than one entries in capabilitiesEntries, but none " "was compatible."; JOYNR_LOG_WARN(logger, errorMsg); arbitrationError.setMessage(errorMsg); } return; } else { types::DiscoveryEntryWithMetaInfo res; try { res = arbitrationStrategyFunction->select( discoveryQos.getCustomParameters(), preFilteredDiscoveryEntries); } catch (const exceptions::DiscoveryException& e) { arbitrationError = e; } if (!res.getParticipantId().empty()) { onSuccessCallback(res); arbitrationFinished = true; } } } } // namespace joynr
/* * #%L * %% * Copyright (C) 2011 - 2017 BMW Car IT GmbH * %% * 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. * #L% */ #include "joynr/Arbitrator.h" #include <cassert> #include <chrono> #include <vector> #include <boost/algorithm/string/join.hpp> #include "joynr/Future.h" #include "joynr/Logger.h" #include "joynr/Semaphore.h" #include "joynr/exceptions/JoynrException.h" #include "joynr/exceptions/NoCompatibleProviderFoundException.h" #include "joynr/system/IDiscovery.h" #include "joynr/types/DiscoveryScope.h" namespace joynr { INIT_LOGGER(Arbitrator); Arbitrator::Arbitrator( const std::string& domain, const std::string& interfaceName, const joynr::types::Version& interfaceVersion, std::weak_ptr<joynr::system::IDiscoveryAsync> discoveryProxy, const DiscoveryQos& discoveryQos, std::unique_ptr<const ArbitrationStrategyFunction> arbitrationStrategyFunction) : discoveryProxy(discoveryProxy), discoveryQos(discoveryQos), systemDiscoveryQos(discoveryQos.getCacheMaxAgeMs(), discoveryQos.getDiscoveryTimeoutMs(), discoveryQos.getDiscoveryScope(), discoveryQos.getProviderMustSupportOnChange()), domains({domain}), interfaceName(interfaceName), interfaceVersion(interfaceVersion), discoveredIncompatibleVersions(), arbitrationError("Arbitration could not be finished in time."), arbitrationStrategyFunction(std::move(arbitrationStrategyFunction)), arbitrationFinished(false), arbitrationRunning(false), keepArbitrationRunning(false), arbitrationThread() { } Arbitrator::~Arbitrator() { keepArbitrationRunning = false; if (arbitrationThread.joinable()) { arbitrationThread.join(); } } void Arbitrator::startArbitration( std::function<void(const types::DiscoveryEntryWithMetaInfo& discoveryEntry)> onSuccess, std::function<void(const exceptions::DiscoveryException& exception)> onError) { if (arbitrationRunning) { return; } arbitrationRunning = true; keepArbitrationRunning = true; onSuccessCallback = onSuccess; onErrorCallback = onError; arbitrationThread = std::thread([this]() { Semaphore semaphore; arbitrationFinished = false; std::string serializedDomainsList = boost::algorithm::join(domains, ", "); JOYNR_LOG_DEBUG(logger, "DISCOVERY lookup for domain: [{}], interface: {}", serializedDomainsList, interfaceName); // Arbitrate until successful or timed out auto start = std::chrono::system_clock::now(); while (keepArbitrationRunning) { attemptArbitration(); if (arbitrationFinished) { return; } // If there are no suitable providers, retry the arbitration after the retry interval // elapsed auto now = std::chrono::system_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(now - start); if (discoveryQos.getDiscoveryTimeoutMs() <= duration.count()) { // discovery timeout reached break; } else if (discoveryQos.getDiscoveryTimeoutMs() - duration.count() <= discoveryQos.getRetryIntervalMs()) { /* * no retry possible -> wait until discoveryTimeout is reached and inform caller * about * cancelled arbitration */ semaphore.waitFor(std::chrono::milliseconds(discoveryQos.getDiscoveryTimeoutMs() - duration.count())); break; } else { // wait for retry interval and attempt a new arbitration semaphore.waitFor(std::chrono::milliseconds(discoveryQos.getRetryIntervalMs())); } } // If this point is reached the arbitration timed out if (!discoveredIncompatibleVersions.empty()) { onErrorCallback( exceptions::NoCompatibleProviderFoundException(discoveredIncompatibleVersions)); } else { onErrorCallback(arbitrationError); } arbitrationRunning = false; }); } void Arbitrator::attemptArbitration() { std::vector<joynr::types::DiscoveryEntryWithMetaInfo> result; try { if (auto discoveryProxySharedPtr = discoveryProxy.lock()) { if (discoveryQos.getArbitrationStrategy() == DiscoveryQos::ArbitrationStrategy::FIXED_PARTICIPANT) { types::DiscoveryEntryWithMetaInfo fixedParticipantResult; std::string fixedParticipantId = discoveryQos.getCustomParameter("fixedParticipantId").getValue(); auto future = discoveryProxySharedPtr->lookupAsync(fixedParticipantId); future->get(fixedParticipantResult); result.push_back(fixedParticipantResult); } else { auto future = discoveryProxySharedPtr->lookupAsync( domains, interfaceName, systemDiscoveryQos); future->get(result); } } else { throw exceptions::JoynrRuntimeException("discoveryProxy not available"); } receiveCapabilitiesLookupResults(result); } catch (const exceptions::JoynrException& e) { std::string errorMsg = "Unable to lookup provider (domain: " + (domains.empty() ? std::string("EMPTY") : domains.at(0)) + ", interface: " + interfaceName + ") from discovery. Error: " + e.getMessage(); JOYNR_LOG_ERROR(logger, errorMsg); arbitrationError.setMessage(errorMsg); } } void Arbitrator::receiveCapabilitiesLookupResults( const std::vector<joynr::types::DiscoveryEntryWithMetaInfo>& discoveryEntries) { discoveredIncompatibleVersions.clear(); // Check for empty results if (discoveryEntries.empty()) { arbitrationError.setMessage("No entries found for domain: " + (domains.empty() ? std::string("EMPTY") : domains.at(0)) + ", interface: " + interfaceName); return; } std::vector<joynr::types::DiscoveryEntryWithMetaInfo> preFilteredDiscoveryEntries; joynr::types::Version providerVersion; std::size_t providersWithoutSupportOnChange = 0; std::size_t providersWithIncompatibleVersion = 0; for (const joynr::types::DiscoveryEntryWithMetaInfo discoveryEntry : discoveryEntries) { types::ProviderQos providerQos = discoveryEntry.getQos(); JOYNR_LOG_TRACE(logger, "Looping over capabilitiesEntry: {}", discoveryEntry.toString()); providerVersion = discoveryEntry.getProviderVersion(); if (discoveryQos.getProviderMustSupportOnChange() && !providerQos.getSupportsOnChangeSubscriptions()) { ++providersWithoutSupportOnChange; continue; } if (providerVersion.getMajorVersion() != interfaceVersion.getMajorVersion() || providerVersion.getMinorVersion() < interfaceVersion.getMinorVersion()) { JOYNR_LOG_TRACE(logger, "Skipping capabilitiesEntry with incompatible version, expected: " + std::to_string(interfaceVersion.getMajorVersion()) + "." + std::to_string(interfaceVersion.getMinorVersion())); discoveredIncompatibleVersions.insert(providerVersion); ++providersWithIncompatibleVersion; continue; } preFilteredDiscoveryEntries.push_back(discoveryEntry); } if (preFilteredDiscoveryEntries.empty()) { std::string errorMsg; if (providersWithoutSupportOnChange == discoveryEntries.size()) { errorMsg = "There was more than one entries in capabilitiesEntries, but none supported " "on change subscriptions."; JOYNR_LOG_WARN(logger, errorMsg); arbitrationError.setMessage(errorMsg); } else if ((providersWithoutSupportOnChange + providersWithIncompatibleVersion) == discoveryEntries.size()) { errorMsg = "There was more than one entries in capabilitiesEntries, but none " "was compatible."; JOYNR_LOG_WARN(logger, errorMsg); arbitrationError.setMessage(errorMsg); } return; } else { types::DiscoveryEntryWithMetaInfo res; try { res = arbitrationStrategyFunction->select( discoveryQos.getCustomParameters(), preFilteredDiscoveryEntries); } catch (const exceptions::DiscoveryException& e) { arbitrationError = e; } if (!res.getParticipantId().empty()) { onSuccessCallback(res); arbitrationFinished = true; } } } } // namespace joynr
use ‘empty()’ instead of ‘size()’
[C++] use ‘empty()’ instead of ‘size()’ Change-Id: I977c05037baf6443df3f9bc0cdc29c9466dd850a
C++
apache-2.0
clive-jevons/joynr,bmwcarit/joynr,clive-jevons/joynr,bmwcarit/joynr,clive-jevons/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,clive-jevons/joynr,bmwcarit/joynr,clive-jevons/joynr,bmwcarit/joynr,clive-jevons/joynr
7a24a02273315bcf7d7ec015f282cd6625d79891
curiosity_animation/src/ofApp.cpp
curiosity_animation/src/ofApp.cpp
#include "ofApp.h" #include "ofxXmlSettings.h" const int kForward = 1; const int kBack = -1; void ofApp::animateVideo(const int direction) { if (direction != kForward && direction != kBack) { ofLogError() << "Invalid direction " << direction; return; } if (videoPlayer.getSpeed() != direction) { videoPlayer.setPaused(true); videoPlayer.setSpeed(direction); } if (!isPlaying()) { frameAtLastAnimationStart = videoPlayer.getCurrentFrame(); videoPlayer.play(); } videoPlayer.update(); } bool ofApp::isPlaying() { return videoPlayer.isPlaying() && !videoPlayer.isPaused(); } bool ofApp::loadVideo() { videoPlayer = ofVideoPlayer(); if (!videoPlayer.loadMovie(ofToDataPath(configuration.VideoFileName))) { return false; } videoPlayer.setLoopState(OF_LOOP_NONE); return true; } void ofApp::setup(){ // start logging ofLogToFile("app.log"); // start recoding events if (!eventLog.open(ofToDataPath("events.txt"), ofFile::WriteOnly)) { ofLogError() << "Error opening events.txt - !!!DATA WILL BE LOST!!!"; } if (!configuration.Read()) { ofLogError() << "Error reading configuration"; } if (!gameStats.Read()) { ofLogError() << "Error reading game stats."; } ofSetFrameRate(configuration.FrameRate); ofSetFullscreen(configuration.Fullscreen); #ifdef TARGET_OSX ofSetDataPathRoot("../Resources/data/"); #endif // Distance reading serialPort.listDevices(); vector<ofSerialDeviceInfo> deviceList = serialPort.getDeviceList(); if (configuration.ActiveSerialPort < deviceList.size()) { if (!serialPort.setup(configuration.ActiveSerialPort, 9600)) { ofLogError() << "Failed to connect to serial device! " << deviceList[configuration.ActiveSerialPort].getDeviceName(); } } currentDistance = configuration.MaxDistance; previousDistanceChangeAt = ofGetElapsedTimeMillis(); // HUD if (!f.loadFont("verdana.ttf", 16, true, true)) { ofLogError() << "Error loading font"; } f.setLineHeight(18.0f); f.setLetterSpacing(1.037); // Audio if (!heartbeatSound.loadSound("2.mp3")) { ofLogError() << "Error loading heartbeat sound"; } heartbeatSound.setLoop(true); // Video if (!loadVideo()) { ofLogError() << "Error loading video"; } } bool Configuration::Read() { // Read configuration or create default ofxXmlSettings xml; if (!xml.loadFile("configuration.xml")) { xml.setValue("configuration:Fullscreen", Fullscreen); xml.setValue("configuration:MinDistance", MinDistance); xml.setValue("configuration:MaxDistance", MaxDistance); xml.setValue("configuration:DeathZone", DeathZone); xml.setValue("configuration:RestartIntervalSeconds", RestartIntervalSeconds); xml.setValue("configuration:ActiveSerialPort", ActiveSerialPort); xml.setValue("configuration:StartingFramesPerSecond", StartingFramesPerSecond); xml.setValue("configuration:FinishingFramesPerSecond", FinishingFramesPerSecond); xml.setValue("configuration:StartingVolume", StartingVolume); xml.setValue("configuration:FinishingVolume", FinishingVolume); xml.setValue("configuration:StartingHeartBeatSpeed", StartingHeartBeatSpeed); xml.setValue("configuration:FinishingHeartBeatSpeed", FinishingHeartBeatSpeed); xml.setValue("configuration:FrameRate", FrameRate); xml.setValue("configuration:VideoFileName", VideoFileName); xml.setValue("configuration:CheckAfterNFrames", CheckAfterNFrames); if (!xml.saveFile("configuration.xml")) { ofLogError() << "Error saving configuration file"; return false; } } else { Fullscreen = xml.getValue("configuration:Fullscreen", Fullscreen); MinDistance = xml.getValue("configuration:MinDistance", MinDistance); MaxDistance = xml.getValue("configuration:MaxDistance", MaxDistance); DeathZone = xml.getValue("configuration:DeathZone", DeathZone); RestartIntervalSeconds = xml.getValue("configuration:RestartIntervalSeconds", RestartIntervalSeconds); ActiveSerialPort = xml.getValue("configuration:ActiveSerialPort", ActiveSerialPort); StartingFramesPerSecond = xml.getValue("configuration:StartingFramesPerSecond", StartingFramesPerSecond); FinishingFramesPerSecond = xml.getValue("configuration:FinishingFramesPerSecond", FinishingFramesPerSecond); StartingVolume = xml.getValue("configuration:StartingVolume", StartingVolume); FinishingVolume = xml.getValue("configuration:FinishingVolume", FinishingVolume); StartingHeartBeatSpeed = xml.getValue("configuration:StartingHeartBeatSpeed", StartingHeartBeatSpeed); FinishingHeartBeatSpeed = xml.getValue("configuration:FinishingHeartBeatSpeed", FinishingHeartBeatSpeed); FrameRate = xml.getValue("configuration:FrameRate", FrameRate); VideoFileName = xml.getValue("configuration:VideoFileName", VideoFileName); CheckAfterNFrames = xml.getValue("configuration:CheckAfterNFrames", CheckAfterNFrames); } return true; } bool GameStats::Read() { // Read game stats or create default ofxXmlSettings xml; if (!xml.loadFile("gamestats.xml")) { if (!Write()) { return false; } } else { Saves = xml.getValue("gamestats:Saves", Saves); Kills = xml.getValue("gamestats:Kills", Kills); } return true; } bool GameStats::Write() const { ofFile f(ofToDataPath("gamestats.xml")); f.moveTo("gamestats_backup.xml", false, true); ofxXmlSettings xml; xml.setValue("gamestats:Saves", Saves); xml.setValue("gamestats:Kills", Kills); return xml.saveFile("gamestats.xml"); } void ofApp::update(){ long now = ofGetElapsedTimeMillis(); if (isPlaying()) { if (videoPlayer.getSpeed() == kForward) { if (videoPlayer.getCurrentFrame() >= frameForDistance()) { videoPlayer.setPaused(true); } } else if (videoPlayer.getSpeed() == kBack) { if (videoPlayer.getCurrentFrame() <= frameForDistance()) { videoPlayer.setPaused(true); } } } // Determine if user is now in the death zone if (!state.finishedAt && (currentDistance < configuration.MinDistance + configuration.DeathZone)) { ofLogNotice() << "Game finished with kill at " << now << " with current distance of " << currentDistance; eventLog << "killed=" << now << std::endl; state.finishedAt = now; state.saved = false; setDistance("killed", configuration.MinDistance); gameStats.Kills++; if (!gameStats.Write()) { ofLogError() << "Error writing game stats"; } } // If save zone is active and user finds itself in it, // then declare the game saved and finish it. int saveZoneStartsAt = std::abs(configuration.MaxDistance - configuration.DeathZone); if (!state.finishedAt && state.saveZoneActive && currentDistance > saveZoneStartsAt) { ofLogNotice() << "Game finished with save at " << now << " with current distance of " << currentDistance; eventLog << "saved=" << now << std::endl; state.finishedAt = now; state.saved = true; setDistance("saved", configuration.MaxDistance); gameStats.Saves++; if (!gameStats.Write()) { ofLogError() << "Error writing game stats"; } } // If user has moved out of save zone, and game is not finished // yet, activate save zone int moved = std::abs(configuration.MaxDistance - currentDistance); if (!state.finishedAt && moved > configuration.DeathZone) { state.saveZoneActive = true; } // Restart if needed if (state.finishedAt && (state.finishedAt < now - (configuration.RestartIntervalSeconds*1000))) { ofLogNotice() << "Game restarted"; state = GameState(); setDistance("restart", configuration.MaxDistance); if (!loadVideo()) { ofLogError() << "Error loading video after kill"; } ofLogNotice() << "frame after resettting video player: " << videoPlayer.getCurrentFrame(); eventLog << "started=" << now << std::endl; } // Read serial if (serialPort.isInitialized() && serialPort.available()) { char c = serialPort.readByte(); if ('\n' == c) { std::string input = serialbuf.str(); serialbuf.str(""); if (isAccepingInput()) { float f = ofToFloat(input); int prev = currentDistance; setDistance("Serial input", f); if (prev > currentDistance) { animateVideo(kForward); ofLogNotice() << "Serial input: " << input << " f: " << f << " moving: forward prev: " << prev << " current distance: " << currentDistance; } else if (prev < currentDistance) { animateVideo(kBack); ofLogNotice() << "Serial input: " << input << " f: " << f << " moving: back prev: " << prev << " current distance: " << currentDistance; } } } else { serialbuf << c; } } // Update visual int millis = ofMap(currentDistance, configuration.MaxDistance, configuration.MinDistance, 1000 / configuration.StartingFramesPerSecond, 1000 / configuration.FinishingFramesPerSecond); fps = 1000 / millis; // Update video videoPlayer.update(); // Update audio if (!state.finishedAt) { if (!heartbeatSound.getIsPlaying()) { heartbeatSound.play(); } heartbeatSound.setSpeed(ofMap(currentDistance, configuration.MaxDistance, configuration.MinDistance, configuration.StartingHeartBeatSpeed, configuration.FinishingHeartBeatSpeed)); } else { if (heartbeatSound.getIsPlaying()) { heartbeatSound.stop(); } } ofSoundUpdate(); } bool ofApp::isAccepingInput() { if (state.finishedAt) { return false; } if (!isPlaying()) { return true; } int framesPlayed = std::abs(frameAtLastAnimationStart - videoPlayer.getCurrentFrame()); return framesPlayed >= configuration.CheckAfterNFrames; } // Frame for current distance // Note that this is not the actual frame that will be animated. // Instead will start to animate towards this frame. int ofApp::frameForDistance() { return ofMap(currentDistance, configuration.MinDistance, configuration.MaxDistance, videoPlayer.getTotalNumFrames(), 0); } void ofApp::draw(){ int restartCountdownSeconds = 0; if (state.finishedAt) { long now = ofGetElapsedTimeMillis(); int beenDeadSeconds = (now - state.finishedAt) / 1000; restartCountdownSeconds = configuration.RestartIntervalSeconds - beenDeadSeconds; } // Update HUD int y = 40; f.drawString("dist=" + ofToString(currentDistance), 10, y); f.drawString("f=" + ofToString(videoPlayer.getCurrentFrame()) + "/" + ofToString(videoPlayer.getTotalNumFrames()), 160, y); f.drawString("dest.f=" + ofToString(frameForDistance()), 300, y); f.drawString("fps=" + ofToString(fps), 460, y); f.drawString("sv=" + ofToString(gameStats.Saves), 560, y); f.drawString("kl=" + ofToString(gameStats.Kills), 660, y); f.drawString("rs=" + ofToString(restartCountdownSeconds), 760, y); f.drawString("vid=" + ofToString(isPlaying()), 860, y); const int margin = 50; // Draw video if (state.finishedAt && !isPlaying()) { if (state.saved) { ofSetHexColor(0xFFFFFF); } else { ofSetHexColor(0x000000); } ofRect(0, margin, ofGetWindowWidth(), ofGetWindowHeight() - margin); ofFill(); if (!state.saved) { ofSetHexColor(0xFFFFFF); } else { ofSetHexColor(0x000000); } std::string text(""); if (state.saved) { text = "LIFES SAVED: " + ofToString(gameStats.Saves); } else { text = "TOTAL KILLS: " + ofToString(gameStats.Kills); } f.drawString(text, ofGetWindowWidth() / 2 - 100, ofGetWindowHeight() / 2); return; } ofSetHexColor(0xFFFFFF); ofFill(); videoPlayer.draw(0, margin, ofGetWindowWidth(), ofGetWindowHeight() - margin); } void ofApp::keyPressed(int key){ ofLogNotice() << "keyPressed key=" << key; if (!isAccepingInput()) { return; } const int kMinStep = 100; if (OF_KEY_UP == key) { // distance decreases as viewer approaches int n = currentDistance - kMinStep - int(ofRandom(100)); setDistance("keyboard up", n); animateVideo(kForward); } else if (OF_KEY_DOWN == key) { // distance incrases as viewer steps back int n = currentDistance + kMinStep + int(ofRandom(100)); setDistance("keyboard down", n); animateVideo(kBack); } } void ofApp::setDistance(const std::string reason, const int value) { currentDistance = ofClamp(value, configuration.MinDistance, configuration.MaxDistance); }
#include "ofApp.h" #include "ofxXmlSettings.h" const int kForward = 1; const int kBack = -1; void ofApp::animateVideo(const int direction) { if (direction != kForward && direction != kBack) { ofLogError() << "Invalid direction " << direction; return; } if (videoPlayer.getSpeed() != direction) { videoPlayer.setPaused(true); videoPlayer.setSpeed(direction); } if (!isPlaying()) { frameAtLastAnimationStart = videoPlayer.getCurrentFrame(); videoPlayer.play(); } videoPlayer.update(); } bool ofApp::isPlaying() { return videoPlayer.isPlaying() && !videoPlayer.isPaused(); } bool ofApp::loadVideo() { videoPlayer = ofVideoPlayer(); if (!videoPlayer.loadMovie(ofToDataPath(configuration.VideoFileName))) { return false; } videoPlayer.setLoopState(OF_LOOP_NONE); return true; } void ofApp::setup(){ // start logging ofLogToFile("app.log"); // start recoding events if (!eventLog.open(ofToDataPath("events.txt"), ofFile::WriteOnly)) { ofLogError() << "Error opening events.txt - !!!DATA WILL BE LOST!!!"; } if (!configuration.Read()) { ofLogError() << "Error reading configuration"; } if (!gameStats.Read()) { ofLogError() << "Error reading game stats."; } ofSetFrameRate(configuration.FrameRate); ofSetFullscreen(configuration.Fullscreen); #ifdef TARGET_OSX ofSetDataPathRoot("../Resources/data/"); #endif // Distance reading serialPort.listDevices(); vector<ofSerialDeviceInfo> deviceList = serialPort.getDeviceList(); if (configuration.ActiveSerialPort < deviceList.size()) { if (!serialPort.setup(configuration.ActiveSerialPort, 9600)) { ofLogError() << "Failed to connect to serial device! " << deviceList[configuration.ActiveSerialPort].getDeviceName(); } } currentDistance = configuration.MaxDistance; previousDistanceChangeAt = ofGetElapsedTimeMillis(); // HUD if (!f.loadFont("verdana.ttf", 16, true, true)) { ofLogError() << "Error loading font"; } f.setLineHeight(18.0f); f.setLetterSpacing(1.037); // Audio if (!heartbeatSound.loadSound("2.mp3")) { ofLogError() << "Error loading heartbeat sound"; } heartbeatSound.setLoop(true); // Video if (!loadVideo()) { ofLogError() << "Error loading video"; } } bool Configuration::Read() { // Read configuration or create default ofxXmlSettings xml; if (!xml.loadFile("configuration.xml")) { xml.setValue("configuration:Fullscreen", Fullscreen); xml.setValue("configuration:MinDistance", MinDistance); xml.setValue("configuration:MaxDistance", MaxDistance); xml.setValue("configuration:DeathZone", DeathZone); xml.setValue("configuration:RestartIntervalSeconds", RestartIntervalSeconds); xml.setValue("configuration:ActiveSerialPort", ActiveSerialPort); xml.setValue("configuration:StartingFramesPerSecond", StartingFramesPerSecond); xml.setValue("configuration:FinishingFramesPerSecond", FinishingFramesPerSecond); xml.setValue("configuration:StartingVolume", StartingVolume); xml.setValue("configuration:FinishingVolume", FinishingVolume); xml.setValue("configuration:StartingHeartBeatSpeed", StartingHeartBeatSpeed); xml.setValue("configuration:FinishingHeartBeatSpeed", FinishingHeartBeatSpeed); xml.setValue("configuration:FrameRate", FrameRate); xml.setValue("configuration:VideoFileName", VideoFileName); xml.setValue("configuration:CheckAfterNFrames", CheckAfterNFrames); if (!xml.saveFile("configuration.xml")) { ofLogError() << "Error saving configuration file"; return false; } } else { Fullscreen = xml.getValue("configuration:Fullscreen", Fullscreen); MinDistance = xml.getValue("configuration:MinDistance", MinDistance); MaxDistance = xml.getValue("configuration:MaxDistance", MaxDistance); DeathZone = xml.getValue("configuration:DeathZone", DeathZone); RestartIntervalSeconds = xml.getValue("configuration:RestartIntervalSeconds", RestartIntervalSeconds); ActiveSerialPort = xml.getValue("configuration:ActiveSerialPort", ActiveSerialPort); StartingFramesPerSecond = xml.getValue("configuration:StartingFramesPerSecond", StartingFramesPerSecond); FinishingFramesPerSecond = xml.getValue("configuration:FinishingFramesPerSecond", FinishingFramesPerSecond); StartingVolume = xml.getValue("configuration:StartingVolume", StartingVolume); FinishingVolume = xml.getValue("configuration:FinishingVolume", FinishingVolume); StartingHeartBeatSpeed = xml.getValue("configuration:StartingHeartBeatSpeed", StartingHeartBeatSpeed); FinishingHeartBeatSpeed = xml.getValue("configuration:FinishingHeartBeatSpeed", FinishingHeartBeatSpeed); FrameRate = xml.getValue("configuration:FrameRate", FrameRate); VideoFileName = xml.getValue("configuration:VideoFileName", VideoFileName); CheckAfterNFrames = xml.getValue("configuration:CheckAfterNFrames", CheckAfterNFrames); } return true; } bool GameStats::Read() { // Read game stats or create default ofxXmlSettings xml; if (!xml.loadFile("gamestats.xml")) { if (!Write()) { return false; } } else { Saves = xml.getValue("gamestats:Saves", Saves); Kills = xml.getValue("gamestats:Kills", Kills); } return true; } bool GameStats::Write() const { ofFile f(ofToDataPath("gamestats.xml")); f.moveTo("gamestats_backup.xml", false, true); ofxXmlSettings xml; xml.setValue("gamestats:Saves", Saves); xml.setValue("gamestats:Kills", Kills); return xml.saveFile("gamestats.xml"); } void ofApp::update(){ long now = ofGetElapsedTimeMillis(); if (isPlaying()) { if (videoPlayer.getSpeed() == kForward) { if (videoPlayer.getCurrentFrame() >= frameForDistance()) { videoPlayer.setPaused(true); } } else if (videoPlayer.getSpeed() == kBack) { if (videoPlayer.getCurrentFrame() <= frameForDistance()) { videoPlayer.setPaused(true); } } } // Determine if user is now in the death zone if (!state.finishedAt && (currentDistance < configuration.MinDistance + configuration.DeathZone)) { ofLogNotice() << "Game finished with kill at " << now << " with current distance of " << currentDistance; eventLog << "killed=" << now << std::endl; state.finishedAt = now; state.saved = false; setDistance("killed", configuration.MinDistance); gameStats.Kills++; if (!gameStats.Write()) { ofLogError() << "Error writing game stats"; } } // If save zone is active and user finds itself in it, // then declare the game saved and finish it. int saveZoneStartsAt = std::abs(configuration.MaxDistance - configuration.DeathZone); if (!state.finishedAt && state.saveZoneActive && currentDistance > saveZoneStartsAt) { ofLogNotice() << "Game finished with save at " << now << " with current distance of " << currentDistance; eventLog << "saved=" << now << std::endl; state.finishedAt = now; state.saved = true; setDistance("saved", configuration.MaxDistance); gameStats.Saves++; if (!gameStats.Write()) { ofLogError() << "Error writing game stats"; } } // If user has moved out of save zone, and game is not finished // yet, activate save zone int moved = std::abs(configuration.MaxDistance - currentDistance); if (!state.finishedAt && moved > configuration.DeathZone * 2) { state.saveZoneActive = true; } // Restart if needed if (state.finishedAt && (state.finishedAt < now - (configuration.RestartIntervalSeconds*1000))) { ofLogNotice() << "Game restarted"; state = GameState(); setDistance("restart", configuration.MaxDistance); if (!loadVideo()) { ofLogError() << "Error loading video after kill"; } ofLogNotice() << "frame after resettting video player: " << videoPlayer.getCurrentFrame(); eventLog << "started=" << now << std::endl; } // Read serial if (serialPort.isInitialized() && serialPort.available()) { char c = serialPort.readByte(); if ('\n' == c) { std::string input = serialbuf.str(); serialbuf.str(""); if (isAccepingInput()) { float f = ofToFloat(input); int prev = currentDistance; setDistance("Serial input", f); if (prev > currentDistance) { animateVideo(kForward); ofLogNotice() << "Serial input: " << input << " f: " << f << " moving: forward prev: " << prev << " current distance: " << currentDistance; } else if (prev < currentDistance) { animateVideo(kBack); ofLogNotice() << "Serial input: " << input << " f: " << f << " moving: back prev: " << prev << " current distance: " << currentDistance; } } } else { serialbuf << c; } } // Update visual int millis = ofMap(currentDistance, configuration.MaxDistance, configuration.MinDistance, 1000 / configuration.StartingFramesPerSecond, 1000 / configuration.FinishingFramesPerSecond); fps = 1000 / millis; // Update video videoPlayer.update(); // Update audio if (!state.finishedAt) { if (!heartbeatSound.getIsPlaying()) { heartbeatSound.play(); } heartbeatSound.setSpeed(ofMap(currentDistance, configuration.MaxDistance, configuration.MinDistance, configuration.StartingHeartBeatSpeed, configuration.FinishingHeartBeatSpeed)); } else { if (heartbeatSound.getIsPlaying()) { heartbeatSound.stop(); } } ofSoundUpdate(); } bool ofApp::isAccepingInput() { if (state.finishedAt) { return false; } if (!isPlaying()) { return true; } int framesPlayed = std::abs(frameAtLastAnimationStart - videoPlayer.getCurrentFrame()); return framesPlayed >= configuration.CheckAfterNFrames; } // Frame for current distance // Note that this is not the actual frame that will be animated. // Instead will start to animate towards this frame. int ofApp::frameForDistance() { return ofMap(currentDistance, configuration.MinDistance, configuration.MaxDistance, videoPlayer.getTotalNumFrames(), 0); } void ofApp::draw(){ int restartCountdownSeconds = 0; if (state.finishedAt) { long now = ofGetElapsedTimeMillis(); int beenDeadSeconds = (now - state.finishedAt) / 1000; restartCountdownSeconds = configuration.RestartIntervalSeconds - beenDeadSeconds; } // Update HUD int y = 40; f.drawString("dist=" + ofToString(currentDistance), 10, y); f.drawString("f=" + ofToString(videoPlayer.getCurrentFrame()) + "/" + ofToString(videoPlayer.getTotalNumFrames()), 160, y); f.drawString("dest.f=" + ofToString(frameForDistance()), 300, y); f.drawString("fps=" + ofToString(fps), 460, y); f.drawString("sv=" + ofToString(gameStats.Saves), 560, y); f.drawString("kl=" + ofToString(gameStats.Kills), 660, y); f.drawString("rs=" + ofToString(restartCountdownSeconds), 760, y); f.drawString("vid=" + ofToString(isPlaying()), 860, y); const int margin = 50; // Draw video if (state.finishedAt && !isPlaying()) { if (state.saved) { ofSetHexColor(0xFFFFFF); } else { ofSetHexColor(0x000000); } ofRect(0, margin, ofGetWindowWidth(), ofGetWindowHeight() - margin); ofFill(); if (!state.saved) { ofSetHexColor(0xFFFFFF); } else { ofSetHexColor(0x000000); } std::string text(""); if (state.saved) { text = "LIFES SAVED: " + ofToString(gameStats.Saves); } else { text = "TOTAL KILLS: " + ofToString(gameStats.Kills); } f.drawString(text, ofGetWindowWidth() / 2 - 100, ofGetWindowHeight() / 2); return; } ofSetHexColor(0xFFFFFF); ofFill(); videoPlayer.draw(0, margin, ofGetWindowWidth(), ofGetWindowHeight() - margin); } void ofApp::keyPressed(int key){ ofLogNotice() << "keyPressed key=" << key; if (!isAccepingInput()) { return; } const int kMinStep = 100; if (OF_KEY_UP == key) { // distance decreases as viewer approaches int n = currentDistance - kMinStep - int(ofRandom(100)); setDistance("keyboard up", n); animateVideo(kForward); } else if (OF_KEY_DOWN == key) { // distance incrases as viewer steps back int n = currentDistance + kMinStep + int(ofRandom(100)); setDistance("keyboard down", n); animateVideo(kBack); } } void ofApp::setDistance(const std::string reason, const int value) { currentDistance = ofClamp(value, configuration.MinDistance, configuration.MaxDistance); }
save zone actives later
save zone actives later
C++
mit
tanel/processing_ultrasonic_animation,tanel/processing_ultrasonic_animation,tanel/processing_ultrasonic_animation,tanel/processing_ultrasonic_animation,tanel/processing_ultrasonic_animation,tanel/processing_ultrasonic_animation,tanel/processing_ultrasonic_animation
73bd1120afeed6c4f906dc476280ea494e350caa
src/cpp/shared_core/FileLogDestination.cpp
src/cpp/shared_core/FileLogDestination.cpp
/* * FileLogDestination.cpp * * Copyright (C) 2019 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant to the terms of a commercial license agreement * with RStudio, then this program is licensed to you under the following terms: * * 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 <shared_core/FileLogDestination.hpp> #include <boost/thread.hpp> #include <vector> #include <shared_core/Logger.hpp> namespace rstudio { namespace core { namespace log { // FileLogOptions ====================================================================================================== FileLogOptions::FileLogOptions(FilePath in_directory) : m_directory(std::move(in_directory)), m_fileMode(s_defaultFileMode), m_maxSizeMb(s_defaultMaxSizeMb), m_doRotation(s_defaultDoRotation), m_includePid(s_defaultIncludePid) { } FileLogOptions::FileLogOptions( FilePath in_directory, std::string in_fileMode, double in_maxSizeMb, bool in_doRotation, bool in_includePid) : m_directory(std::move(in_directory)), m_fileMode(std::move(in_fileMode)), m_maxSizeMb(in_maxSizeMb), m_doRotation(in_doRotation), m_includePid(in_includePid) { } const FilePath& FileLogOptions::getDirectory() const { return m_directory; } const std::string& FileLogOptions::getFileMode() const { return m_fileMode; } double FileLogOptions::getMaxSizeMb() const { return m_maxSizeMb; } bool FileLogOptions::doRotation() const { return m_doRotation; } bool FileLogOptions::includePid() const { return m_includePid; } // FileLogDestination ================================================================================================== struct FileLogDestination::Impl { Impl(unsigned int in_id, const std::string& in_name, FileLogOptions in_options) : LogOptions(std::move(in_options)), LogName(in_name + ".log"), RotatedLogName(in_name + ".old.log"), Id(in_id) { LogOptions.getDirectory().ensureDirectory(); }; ~Impl() { closeLogFile(); } void closeLogFile() { if (LogOutputStream) { LogOutputStream->flush(); LogOutputStream.reset(); } } // Returns true if the log file was opened, false otherwise. bool openLogFile() { // We can't safely log in this function. Error error = LogOptions.getDirectory().completeChildPath(LogName, LogFile); if (error) return false; error = LogFile.ensureFile(); if (error) return false; error = LogFile.openForWrite(LogOutputStream, false); if (error) return false; return true; } // Returns true if it is safe to log; false otherwise. bool rotateLogFile() { // Calculate the maximum size in bytes. const uintmax_t maxSize = 1048576.0 * LogOptions.getMaxSizeMb(); // Only rotate if we're configured to rotate. if (LogOptions.doRotation()) { // Convert MB to B for comparison. if (LogFile.getSize() >= maxSize) { FilePath rotatedLogFile = FilePath(LogOptions.getDirectory()).completeChildPath(RotatedLogName); // We can't safely log errors in this function because we'll end up in an infinitely recursive // rotateLogFile() call. Error error = rotatedLogFile.remove(); if (error) return false; // Close the existing log file and then move it. closeLogFile(); error = LogFile.move(rotatedLogFile); if (error) return false; // Now re-open the log file. openLogFile(); } } return LogFile.getSize() < maxSize; } FileLogOptions LogOptions; FilePath LogFile; std::string LogName; std::string RotatedLogName; boost::mutex Mutex; unsigned int Id; std::shared_ptr<std::ostream> LogOutputStream; }; FileLogDestination::FileLogDestination( unsigned int in_id, LogLevel in_logLevel, const std::string& in_programId, FileLogOptions in_logOptions) : ILogDestination(in_logLevel), m_impl(new Impl(in_id, in_programId, std::move(in_logOptions))) { } FileLogDestination::~FileLogDestination() { if (m_impl->LogOutputStream.get()) m_impl->LogOutputStream->flush(); } unsigned int FileLogDestination::getId() const { return m_impl->Id; } void FileLogDestination::writeLog(LogLevel in_logLevel, const std::string& in_message) { // Don't write logs that are more detailed than the configured maximum. if (in_logLevel > m_logLevel) return; // Lock the mutex before attempting to write. boost::unique_lock<boost::mutex> lock(m_impl->Mutex); // Open the log file if it's not open. If it fails to open, log nothing. if (!m_impl->LogOutputStream && !m_impl->openLogFile()) return; // Rotate the log file if necessary. m_impl->rotateLogFile(); (*m_impl->LogOutputStream) << in_message; m_impl->LogOutputStream->flush(); } } // namespace log } // namespace core } // namespace rstudio
/* * FileLogDestination.cpp * * Copyright (C) 2019 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant to the terms of a commercial license agreement * with RStudio, then this program is licensed to you under the following terms: * * 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 <shared_core/FileLogDestination.hpp> #include <boost/thread.hpp> #include <vector> #include <shared_core/Error.hpp> #include <shared_core/Logger.hpp> namespace rstudio { namespace core { namespace log { // FileLogOptions ====================================================================================================== FileLogOptions::FileLogOptions(FilePath in_directory) : m_directory(std::move(in_directory)), m_fileMode(s_defaultFileMode), m_maxSizeMb(s_defaultMaxSizeMb), m_doRotation(s_defaultDoRotation), m_includePid(s_defaultIncludePid) { } FileLogOptions::FileLogOptions( FilePath in_directory, std::string in_fileMode, double in_maxSizeMb, bool in_doRotation, bool in_includePid) : m_directory(std::move(in_directory)), m_fileMode(std::move(in_fileMode)), m_maxSizeMb(in_maxSizeMb), m_doRotation(in_doRotation), m_includePid(in_includePid) { } const FilePath& FileLogOptions::getDirectory() const { return m_directory; } const std::string& FileLogOptions::getFileMode() const { return m_fileMode; } double FileLogOptions::getMaxSizeMb() const { return m_maxSizeMb; } bool FileLogOptions::doRotation() const { return m_doRotation; } bool FileLogOptions::includePid() const { return m_includePid; } // FileLogDestination ================================================================================================== struct FileLogDestination::Impl { Impl(unsigned int in_id, const std::string& in_name, FileLogOptions in_options) : LogOptions(std::move(in_options)), LogName(in_name + ".log"), RotatedLogName(in_name + ".old.log"), Id(in_id) { LogOptions.getDirectory().ensureDirectory(); }; ~Impl() { closeLogFile(); } void closeLogFile() { if (LogOutputStream) { LogOutputStream->flush(); LogOutputStream.reset(); } } // Returns true if the log file was opened, false otherwise. bool openLogFile() { // We can't safely log in this function. Error error = LogOptions.getDirectory().completeChildPath(LogName, LogFile); if (error) return false; error = LogFile.ensureFile(); if (error) return false; error = LogFile.openForWrite(LogOutputStream, false); if (error) return false; return true; } // Returns true if it is safe to log; false otherwise. bool rotateLogFile() { // Calculate the maximum size in bytes. const uintmax_t maxSize = 1048576.0 * LogOptions.getMaxSizeMb(); // Only rotate if we're configured to rotate. if (LogOptions.doRotation()) { // Convert MB to B for comparison. if (LogFile.getSize() >= maxSize) { FilePath rotatedLogFile = FilePath(LogOptions.getDirectory()).completeChildPath(RotatedLogName); // We can't safely log errors in this function because we'll end up in an infinitely recursive // rotateLogFile() call. Error error = rotatedLogFile.remove(); if (error) return false; // Close the existing log file and then move it. closeLogFile(); error = LogFile.move(rotatedLogFile); if (error) return false; // Now re-open the log file. openLogFile(); } } return LogFile.getSize() < maxSize; } FileLogOptions LogOptions; FilePath LogFile; std::string LogName; std::string RotatedLogName; boost::mutex Mutex; unsigned int Id; std::shared_ptr<std::ostream> LogOutputStream; }; FileLogDestination::FileLogDestination( unsigned int in_id, LogLevel in_logLevel, const std::string& in_programId, FileLogOptions in_logOptions) : ILogDestination(in_logLevel), m_impl(new Impl(in_id, in_programId, std::move(in_logOptions))) { } FileLogDestination::~FileLogDestination() { if (m_impl->LogOutputStream.get()) m_impl->LogOutputStream->flush(); } unsigned int FileLogDestination::getId() const { return m_impl->Id; } void FileLogDestination::writeLog(LogLevel in_logLevel, const std::string& in_message) { // Don't write logs that are more detailed than the configured maximum. if (in_logLevel > m_logLevel) return; // Lock the mutex before attempting to write. boost::unique_lock<boost::mutex> lock(m_impl->Mutex); // Open the log file if it's not open. If it fails to open, log nothing. if (!m_impl->LogOutputStream && !m_impl->openLogFile()) return; // Rotate the log file if necessary. m_impl->rotateLogFile(); (*m_impl->LogOutputStream) << in_message; m_impl->LogOutputStream->flush(); } } // namespace log } // namespace core } // namespace rstudio
add missing include and clean up whitespace
add missing include and clean up whitespace
C++
agpl-3.0
JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio
76b5b2b6889fa9db699dcddb2feb60b0774171f9
src/cxx_supportlib/BackgroundEventLoop.cpp
src/cxx_supportlib/BackgroundEventLoop.cpp
/* * Phusion Passenger - https://www.phusionpassenger.com/ * Copyright (c) 2011-2015 Phusion Holding B.V. * * "Passenger", "Phusion Passenger" and "Union Station" are registered * trademarks of Phusion Holding B.V. * * 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 <cstdlib> #include <cerrno> #include <cassert> #include <boost/bind.hpp> #include <boost/make_shared.hpp> #include <boost/scoped_ptr.hpp> #include <oxt/thread.hpp> #include <oxt/backtrace.hpp> #include <oxt/system_calls.hpp> #include <oxt/detail/context.hpp> #include <ev.h> #include <uv.h> #include <BackgroundEventLoop.h> #include <Logging.h> #include <Exceptions.h> #include <SafeLibev.h> #ifndef HAVE_KQUEUE #if defined(__APPLE__) || \ defined(__DragonFly__) || \ defined(__FreeBSD__) || \ defined(__OpenBSD__) || \ defined(__NetBSD__) #define HAVE_KQUEUE 1 #endif #endif #ifndef HAVE_EPOLL #ifdef __linux__ #define HAVE_EPOLL 1 #endif #endif #ifndef HAVE_POLLSET #ifdef __AIX #define HAVE_POLLSET 1 #endif #endif #ifndef HAVE_EVENT_PORTS #if defined(sun) || defined(__sun) #define HAVE_EVENT_PORTS #endif #endif #if defined(HAVE_KQUEUE) #include <sys/types.h> #include <sys/event.h> #include <sys/time.h> #elif defined(HAVE_EPOLL) #include <sys/epoll.h> #elif defined(HAVE_POLLSET) #include <sys/poll.h> #include <sys/pollset.h> #include <sys/fcntl.h> #elif defined(HAVE_EVENT_PORTS) #include <port.h> #endif namespace Passenger { using namespace std; using namespace boost; using namespace oxt; struct BackgroundEventLoopPrivate { struct ev_async exitSignaller; struct ev_async libuvActivitySignaller; uv_loop_t libuv_loop; /** * Coordinates communication between the libuv poller thread and the * libuv activity callback (the latter which runs on the libevent thread. */ uv_sem_t libuv_sem; /** * This timer doesn't do anything. It only exists to prevent * uv_backend_timeout() from returning 0, which would make the * libuv poller thread use 100% CPU. */ uv_timer_t libuv_timer; oxt::thread *thr; oxt::thread *libuvPollerThr; uv_barrier_t startBarrier; bool usesLibuv; bool started; }; static void signalLibevExit(struct ev_loop *loop, ev_async *async, int revents) { BackgroundEventLoop *bg = (BackgroundEventLoop *) async->data; if (bg->priv->usesLibuv) { ev_async_stop(bg->libev_loop, &bg->priv->libuvActivitySignaller); } ev_async_stop(bg->libev_loop, &bg->priv->exitSignaller); ev_break(bg->libev_loop, EVBREAK_ALL); if (bg->priv->usesLibuv) { uv_timer_stop(&bg->priv->libuv_timer); uv_run(bg->libuv_loop, UV_RUN_NOWAIT); } } static void onLibuvActivity(struct ev_loop *loop, ev_async *async, int revents) { BackgroundEventLoop *bg = (BackgroundEventLoop *) async->data; uv_run(bg->libuv_loop, UV_RUN_NOWAIT); uv_sem_post(&bg->priv->libuv_sem); } static void doNothing(uv_timer_t *timer) { // Do nothing } static void runBackgroundLoop(BackgroundEventLoop *bg) { bg->safe->setCurrentThread(); if (bg->priv->usesLibuv) { uv_timer_start(&bg->priv->libuv_timer, doNothing, 99999000, 99999000); uv_run(bg->libuv_loop, UV_RUN_NOWAIT); } uv_barrier_wait(&bg->priv->startBarrier); ev_run(bg->libev_loop, 0); } static void pollLibuv(BackgroundEventLoop *bg) { uv_barrier_wait(&bg->priv->startBarrier); int ret; int fd; int timeout; int lastErrno; bool intrRequested = false; oxt::thread_local_context *ctx = oxt::get_thread_local_context(); assert(ctx != NULL); fd = uv_backend_fd(&bg->priv->libuv_loop); while (!this_thread::interruption_requested()) { timeout = uv_backend_timeout(&bg->priv->libuv_loop); ctx->syscall_interruption_lock.unlock(); do { #if defined(HAVE_KQUEUE) struct timespec ts; struct kevent event; ts.tv_sec = timeout / 1000; ts.tv_nsec = (timeout % 1000) * 1000000; ret = kevent(fd, NULL, 0, &event, 1, (timeout == -1) ? NULL : &ts); #elif defined(HAVE_EPOLL) struct epoll_event ev; ret = epoll_wait(fd, &ev, 1, timeout); #elif defined(HAVE_POLLSET) struct pollfd event; ret = pollset_poll(fd, &event, 1, timeout); #elif defined(HAVE_EVENT_PORTS) struct timespec ts; struct port_event event; ts.tv_sec = timeout / 1000; ts.tv_nsec = (timeout % 1000) * 1000000; ret = port_get(fd, &event, (timeout == -1) ? NULL : &ts); #else #error "This platform is not supported. Please add corresponding I/O polling code." #endif lastErrno = errno; } while (ret == -1 && lastErrno == EINTR && (!boost::this_thread::syscalls_interruptable() || !(intrRequested = this_thread::interruption_requested()))); ctx->syscall_interruption_lock.lock(); if (ret == -1 && lastErrno == EINTR && this_thread::syscalls_interruptable() && intrRequested) { throw boost::thread_interrupted(); } ev_async_send(bg->libev_loop, &bg->priv->libuvActivitySignaller); uv_sem_wait(&bg->priv->libuv_sem); } } BackgroundEventLoop::BackgroundEventLoop(bool scalable, bool usesLibuv) : libev_loop(NULL), libuv_loop(NULL), priv(NULL) { struct Guard { BackgroundEventLoop *self; Guard(BackgroundEventLoop *_self) : self(_self) { } ~Guard() { if (self != NULL) { if (self->libev_loop != NULL) { ev_loop_destroy(self->libev_loop); } if (self->libuv_loop != NULL) { uv_loop_close(self->libuv_loop); } delete self->priv; } } void clear() { self = NULL; } }; TRACE_POINT(); Guard guard(this); priv = new BackgroundEventLoopPrivate(); if (scalable) { libev_loop = ev_loop_new(EVBACKEND_KQUEUE); if (libev_loop == NULL) { libev_loop = ev_loop_new(EVBACKEND_EPOLL); } if (libev_loop == NULL) { libev_loop = ev_loop_new(EVFLAG_AUTO); } } else { libev_loop = ev_loop_new(EVBACKEND_POLL); } if (libev_loop == NULL) { throw RuntimeException("Cannot create a libev event loop"); } P_LOG_FILE_DESCRIPTOR_OPEN2(ev_backend_fd(libev_loop), "libev event loop: backend FD"); ev_async_init(&priv->exitSignaller, signalLibevExit); ev_async_start(libev_loop, &priv->exitSignaller); P_LOG_FILE_DESCRIPTOR_OPEN2(ev_loop_get_pipe(libev_loop, 0), "libev event loop: async pipe 0"); P_LOG_FILE_DESCRIPTOR_OPEN2(ev_loop_get_pipe(libev_loop, 1), "libev event loop: async pipe 1"); priv->exitSignaller.data = this; safe = boost::make_shared<SafeLibev>(libev_loop); uv_barrier_init(&priv->startBarrier, usesLibuv ? 3 : 2); if (usesLibuv) { ev_async_init(&priv->libuvActivitySignaller, onLibuvActivity); ev_async_start(libev_loop, &priv->libuvActivitySignaller); priv->libuvActivitySignaller.data = this; libuv_loop = &priv->libuv_loop; uv_loop_init(&priv->libuv_loop); uv_timer_init(&priv->libuv_loop, &priv->libuv_timer); uv_sem_init(&priv->libuv_sem, 0); P_LOG_FILE_DESCRIPTOR_OPEN2(uv_backend_fd(libuv_loop), "libuv event loop: backend"); P_LOG_FILE_DESCRIPTOR_OPEN2(libuv_loop->signal_pipefd[0], "libuv event loop: signal pipe 0"); P_LOG_FILE_DESCRIPTOR_OPEN2(libuv_loop->signal_pipefd[1], "libuv event loop: signal pipe 1"); } priv->thr = NULL; priv->libuvPollerThr = NULL; priv->usesLibuv = usesLibuv; priv->started = false; guard.clear(); } BackgroundEventLoop::~BackgroundEventLoop() { stop(); if (priv->usesLibuv) { while (uv_loop_alive(libuv_loop)) { uv_run(libuv_loop, UV_RUN_NOWAIT); syscalls::usleep(10000); } uv_sem_destroy(&priv->libuv_sem); P_LOG_FILE_DESCRIPTOR_CLOSE(uv_backend_fd(libuv_loop)); P_LOG_FILE_DESCRIPTOR_CLOSE(libuv_loop->signal_pipefd[0]); P_LOG_FILE_DESCRIPTOR_CLOSE(libuv_loop->signal_pipefd[1]); uv_loop_close(libuv_loop); } uv_barrier_destroy(&priv->startBarrier); delete priv; } void BackgroundEventLoop::start(const string &threadName, unsigned int stackSize) { assert(priv->thr == NULL); priv->thr = new oxt::thread( boost::bind(runBackgroundLoop, this), threadName, stackSize ); if (priv->usesLibuv) { priv->libuvPollerThr = new oxt::thread( boost::bind(pollLibuv, this), threadName + ": libuv poller", 1024 * 512 ); } uv_barrier_wait(&priv->startBarrier); } void BackgroundEventLoop::stop() { if (priv->thr != NULL) { if (priv->usesLibuv) { priv->libuvPollerThr->interrupt_and_join(); delete priv->libuvPollerThr; priv->libuvPollerThr = NULL; } ev_async_send(libev_loop, &priv->exitSignaller); priv->thr->join(); delete priv->thr; priv->thr = NULL; } } bool BackgroundEventLoop::isStarted() const { return priv->thr != NULL; } pthread_t BackgroundEventLoop::getNativeHandle() const { return priv->thr->native_handle(); } } // namespace Passenger
/* * Phusion Passenger - https://www.phusionpassenger.com/ * Copyright (c) 2011-2015 Phusion Holding B.V. * * "Passenger", "Phusion Passenger" and "Union Station" are registered * trademarks of Phusion Holding B.V. * * 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 <cstdlib> #include <cerrno> #include <cassert> #include <boost/bind.hpp> #include <boost/make_shared.hpp> #include <boost/scoped_ptr.hpp> #include <oxt/thread.hpp> #include <oxt/backtrace.hpp> #include <oxt/system_calls.hpp> #include <oxt/detail/context.hpp> #include <ev.h> #include <uv.h> #include <BackgroundEventLoop.h> #include <Logging.h> #include <Exceptions.h> #include <SafeLibev.h> #ifndef HAVE_KQUEUE #if defined(__APPLE__) || \ defined(__DragonFly__) || \ defined(__FreeBSD__) || \ defined(__OpenBSD__) || \ defined(__NetBSD__) #define HAVE_KQUEUE 1 #endif #endif #ifndef HAVE_EPOLL #ifdef __linux__ #define HAVE_EPOLL 1 #endif #endif #ifndef HAVE_POLLSET #ifdef __AIX #define HAVE_POLLSET 1 #endif #endif #ifndef HAVE_EVENT_PORTS #if defined(sun) || defined(__sun) #define HAVE_EVENT_PORTS #endif #endif #if defined(HAVE_KQUEUE) #include <sys/types.h> #include <sys/event.h> #include <sys/time.h> #elif defined(HAVE_EPOLL) #include <sys/epoll.h> #elif defined(HAVE_POLLSET) #include <sys/poll.h> #include <sys/pollset.h> #include <sys/fcntl.h> #elif defined(HAVE_EVENT_PORTS) #include <port.h> #endif namespace Passenger { using namespace std; using namespace boost; using namespace oxt; struct BackgroundEventLoopPrivate { struct ev_async exitSignaller; struct ev_async libuvActivitySignaller; uv_loop_t libuv_loop; /** * Coordinates communication between the libuv poller thread and the * libuv activity callback (the latter which runs on the libevent thread. */ uv_sem_t libuv_sem; /** * This timer doesn't do anything. It only exists to prevent * uv_backend_timeout() from returning 0, which would make the * libuv poller thread use 100% CPU. */ uv_timer_t libuv_timer; oxt::thread *thr; oxt::thread *libuvPollerThr; uv_barrier_t startBarrier; bool usesLibuv; bool started; }; static void signalLibevExit(struct ev_loop *loop, ev_async *async, int revents) { BackgroundEventLoop *bg = (BackgroundEventLoop *) async->data; if (bg->priv->usesLibuv) { ev_async_stop(bg->libev_loop, &bg->priv->libuvActivitySignaller); } ev_async_stop(bg->libev_loop, &bg->priv->exitSignaller); ev_break(bg->libev_loop, EVBREAK_ALL); if (bg->priv->usesLibuv) { uv_timer_stop(&bg->priv->libuv_timer); uv_run(bg->libuv_loop, UV_RUN_NOWAIT); } } static void onLibuvActivity(struct ev_loop *loop, ev_async *async, int revents) { BackgroundEventLoop *bg = (BackgroundEventLoop *) async->data; uv_run(bg->libuv_loop, UV_RUN_NOWAIT); uv_sem_post(&bg->priv->libuv_sem); } static void doNothing(uv_timer_t *timer) { // Do nothing } static void runBackgroundLoop(BackgroundEventLoop *bg) { bg->safe->setCurrentThread(); if (bg->priv->usesLibuv) { uv_timer_start(&bg->priv->libuv_timer, doNothing, 99999000, 99999000); uv_run(bg->libuv_loop, UV_RUN_NOWAIT); } uv_barrier_wait(&bg->priv->startBarrier); ev_run(bg->libev_loop, 0); } static void pollLibuv(BackgroundEventLoop *bg) { uv_barrier_wait(&bg->priv->startBarrier); int ret; int fd; int timeout; int lastErrno; bool intrRequested = false; oxt::thread_local_context *ctx = oxt::get_thread_local_context(); assert(ctx != NULL); fd = uv_backend_fd(&bg->priv->libuv_loop); while (!this_thread::interruption_requested()) { timeout = uv_backend_timeout(&bg->priv->libuv_loop); ctx->syscall_interruption_lock.unlock(); do { #if defined(HAVE_KQUEUE) struct timespec ts; struct kevent event; ts.tv_sec = timeout / 1000; ts.tv_nsec = (timeout % 1000) * 1000000; ret = kevent(fd, NULL, 0, &event, 1, (timeout == -1) ? NULL : &ts); #elif defined(HAVE_EPOLL) struct epoll_event ev; ret = epoll_wait(fd, &ev, 1, timeout); #elif defined(HAVE_POLLSET) struct pollfd event; ret = pollset_poll(fd, &event, 1, timeout); #elif defined(HAVE_EVENT_PORTS) struct timespec ts; struct port_event event; ts.tv_sec = timeout / 1000; ts.tv_nsec = (timeout % 1000) * 1000000; ret = port_get(fd, &event, (timeout == -1) ? NULL : &ts); #else #error "This platform is not supported. Please add corresponding I/O polling code." #endif lastErrno = errno; } while (ret == -1 && lastErrno == EINTR && (!boost::this_thread::syscalls_interruptable() || !(intrRequested = this_thread::interruption_requested()))); ctx->syscall_interruption_lock.lock(); if (ret == -1 && lastErrno == EINTR && this_thread::syscalls_interruptable() && intrRequested) { throw boost::thread_interrupted(); } ev_async_send(bg->libev_loop, &bg->priv->libuvActivitySignaller); uv_sem_wait(&bg->priv->libuv_sem); } } BackgroundEventLoop::BackgroundEventLoop(bool scalable, bool usesLibuv) : libev_loop(NULL), libuv_loop(NULL), priv(NULL) { struct Guard { BackgroundEventLoop *self; Guard(BackgroundEventLoop *_self) : self(_self) { } ~Guard() { if (self != NULL) { if (self->libev_loop != NULL) { ev_loop_destroy(self->libev_loop); } if (self->libuv_loop != NULL) { uv_loop_close(self->libuv_loop); } delete self->priv; } } void clear() { self = NULL; } }; TRACE_POINT(); Guard guard(this); priv = new BackgroundEventLoopPrivate(); if (scalable) { libev_loop = ev_loop_new(EVBACKEND_KQUEUE); if (libev_loop == NULL) { libev_loop = ev_loop_new(EVBACKEND_EPOLL); } if (libev_loop == NULL) { libev_loop = ev_loop_new(EVFLAG_AUTO); } } else { libev_loop = ev_loop_new(EVBACKEND_POLL); } if (libev_loop == NULL) { throw RuntimeException("Cannot create a libev event loop"); } P_LOG_FILE_DESCRIPTOR_OPEN2(ev_backend_fd(libev_loop), "libev event loop: backend FD"); ev_async_init(&priv->exitSignaller, signalLibevExit); P_LOG_FILE_DESCRIPTOR_OPEN2(ev_loop_get_pipe(libev_loop, 0), "libev event loop: async pipe 0"); P_LOG_FILE_DESCRIPTOR_OPEN2(ev_loop_get_pipe(libev_loop, 1), "libev event loop: async pipe 1"); priv->exitSignaller.data = this; safe = boost::make_shared<SafeLibev>(libev_loop); uv_barrier_init(&priv->startBarrier, usesLibuv ? 3 : 2); if (usesLibuv) { ev_async_init(&priv->libuvActivitySignaller, onLibuvActivity); priv->libuvActivitySignaller.data = this; libuv_loop = &priv->libuv_loop; uv_loop_init(&priv->libuv_loop); uv_timer_init(&priv->libuv_loop, &priv->libuv_timer); uv_sem_init(&priv->libuv_sem, 0); P_LOG_FILE_DESCRIPTOR_OPEN2(uv_backend_fd(libuv_loop), "libuv event loop: backend"); P_LOG_FILE_DESCRIPTOR_OPEN2(libuv_loop->signal_pipefd[0], "libuv event loop: signal pipe 0"); P_LOG_FILE_DESCRIPTOR_OPEN2(libuv_loop->signal_pipefd[1], "libuv event loop: signal pipe 1"); } priv->thr = NULL; priv->libuvPollerThr = NULL; priv->usesLibuv = usesLibuv; priv->started = false; guard.clear(); } BackgroundEventLoop::~BackgroundEventLoop() { stop(); if (priv->usesLibuv) { while (uv_loop_alive(libuv_loop)) { uv_run(libuv_loop, UV_RUN_NOWAIT); syscalls::usleep(10000); } uv_sem_destroy(&priv->libuv_sem); P_LOG_FILE_DESCRIPTOR_CLOSE(uv_backend_fd(libuv_loop)); P_LOG_FILE_DESCRIPTOR_CLOSE(libuv_loop->signal_pipefd[0]); P_LOG_FILE_DESCRIPTOR_CLOSE(libuv_loop->signal_pipefd[1]); uv_loop_close(libuv_loop); if (ev_is_active(&priv->libuvActivitySignaller)) { ev_async_stop(libev_loop, &priv->libuvActivitySignaller); } } if (ev_is_active(&priv->exitSignaller)) { ev_async_stop(libev_loop, &priv->exitSignaller); } uv_barrier_destroy(&priv->startBarrier); delete priv; } void BackgroundEventLoop::start(const string &threadName, unsigned int stackSize) { assert(priv->thr == NULL); ev_async_start(libev_loop, &priv->exitSignaller); if (priv->usesLibuv) { ev_async_start(libev_loop, &priv->libuvActivitySignaller); } priv->thr = new oxt::thread( boost::bind(runBackgroundLoop, this), threadName, stackSize ); if (priv->usesLibuv) { priv->libuvPollerThr = new oxt::thread( boost::bind(pollLibuv, this), threadName + ": libuv poller", 1024 * 512 ); } uv_barrier_wait(&priv->startBarrier); } void BackgroundEventLoop::stop() { if (priv->thr != NULL) { if (priv->usesLibuv) { priv->libuvPollerThr->interrupt_and_join(); delete priv->libuvPollerThr; priv->libuvPollerThr = NULL; } ev_async_send(libev_loop, &priv->exitSignaller); priv->thr->join(); delete priv->thr; priv->thr = NULL; } } bool BackgroundEventLoop::isStarted() const { return priv->thr != NULL; } pthread_t BackgroundEventLoop::getNativeHandle() const { return priv->thr->native_handle(); } } // namespace Passenger
Fix memory corruption errors when destroying a BackgroundEventLoop that isn't started
Fix memory corruption errors when destroying a BackgroundEventLoop that isn't started
C++
mit
phusion/passenger,clemensg/passenger,phusion/passenger,clemensg/passenger,phusion/passenger,phusion/passenger,clemensg/passenger,clemensg/passenger,clemensg/passenger,phusion/passenger,phusion/passenger,clemensg/passenger,clemensg/passenger,phusion/passenger,clemensg/passenger,phusion/passenger
04e6f9242b57ab4656046c1c58020680954172b6
src/mediaplayer.cpp
src/mediaplayer.cpp
/* Copyright (C) 2011-2012 Harald Sitter <[email protected]> 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, see <http://www.gnu.org/licenses/>. */ #include "mediaplayer.h" #include <QtCore/QDebug> #include <QtCore/QDir> #include <QtCore/QMetaType> #include <QtCore/QString> #include <QtCore/QTemporaryFile> #include <QtGui/QImage> #include <vlc/libvlc_version.h> #include "utils/libvlc.h" #include "media.h" // Callbacks come from a VLC thread. In some cases Qt fails to detect this and // tries to invoke directly (i.e. from same thread). This can lead to thread // pollution throughout Phonon, which is very much not desired. #define P_EMIT_HAS_VIDEO(hasVideo) \ QMetaObject::invokeMethod(\ that, "hasVideoChanged", \ Qt::QueuedConnection, \ Q_ARG(bool, hasVideo)) #define P_EMIT_STATE(__state) \ QMetaObject::invokeMethod(\ that, "stateChanged", \ Qt::QueuedConnection, \ Q_ARG(MediaPlayer::State, __state)) namespace Phonon { namespace VLC { MediaPlayer::MediaPlayer(QObject *parent) : QObject(parent), m_player(libvlc_media_player_new(libvlc)), m_bufferCache(-1) { Q_ASSERT(m_player); qRegisterMetaType<MediaPlayer::State>("MediaPlayer::State"); libvlc_event_manager_t *manager = libvlc_media_player_event_manager(m_player); libvlc_event_type_t events[] = { libvlc_MediaPlayerMediaChanged, libvlc_MediaPlayerNothingSpecial, libvlc_MediaPlayerOpening, libvlc_MediaPlayerBuffering, libvlc_MediaPlayerPlaying, libvlc_MediaPlayerPaused, libvlc_MediaPlayerStopped, libvlc_MediaPlayerForward, libvlc_MediaPlayerBackward, libvlc_MediaPlayerEndReached, libvlc_MediaPlayerEncounteredError, libvlc_MediaPlayerTimeChanged, libvlc_MediaPlayerPositionChanged, libvlc_MediaPlayerSeekableChanged, libvlc_MediaPlayerPausableChanged, libvlc_MediaPlayerTitleChanged, libvlc_MediaPlayerSnapshotTaken, libvlc_MediaPlayerLengthChanged, libvlc_MediaPlayerVout }; const int eventCount = sizeof(events) / sizeof(*events); for (int i = 0; i < eventCount; ++i) { libvlc_event_attach(manager, events[i], event_cb, this); } } MediaPlayer::~MediaPlayer() { libvlc_media_player_release(m_player); } void MediaPlayer::setMedia(Media *media) { m_media = media; libvlc_media_player_set_media(m_player, *m_media); } bool MediaPlayer::play() { return libvlc_media_player_play(m_player) == 0; } void MediaPlayer::pause() { libvlc_media_player_set_pause(m_player, 1); } void MediaPlayer::resume() { libvlc_media_player_set_pause(m_player, 0); } void MediaPlayer::togglePause() { libvlc_media_player_pause(m_player); } void MediaPlayer::stop() { libvlc_media_player_stop(m_player); } qint64 MediaPlayer::length() const { return libvlc_media_player_get_length(m_player); } qint64 MediaPlayer::time() const { return libvlc_media_player_get_time(m_player); } void MediaPlayer::setTime(qint64 newTime) { libvlc_media_player_set_time(m_player, newTime); } bool MediaPlayer::isSeekable() const { return libvlc_media_player_is_seekable(m_player); } bool MediaPlayer::hasVideoOutput() const { return libvlc_media_player_has_vout(m_player) > 0; } bool MediaPlayer::setSubtitle(int subtitle) { return libvlc_video_set_spu(m_player, subtitle) == 0; } bool MediaPlayer::setSubtitle(const QString &file) { return libvlc_video_set_subtitle_file(m_player, file.toAscii().data()) == 0; } void MediaPlayer::setTitle(int title) { libvlc_media_player_set_title(m_player, title); } void MediaPlayer::setChapter(int chapter) { libvlc_media_player_set_chapter(m_player, chapter); } QImage MediaPlayer::snapshot() const { QTemporaryFile tempFile(QDir::tempPath() % QDir::separator() % QLatin1Literal("phonon-vlc-snapshot")); tempFile.open(); // This function is sync. if (libvlc_video_take_snapshot(m_player, 0, tempFile.fileName().toLocal8Bit().data(), 0, 0) != 0) return QImage(); return QImage(tempFile.fileName()); } bool MediaPlayer::setAudioTrack(int track) { return libvlc_audio_set_track(m_player, track) == 0; } void MediaPlayer::event_cb(const libvlc_event_t *event, void *opaque) { MediaPlayer *that = reinterpret_cast<MediaPlayer *>(opaque); Q_ASSERT(that); // Do not forget to register for the events you want to handle here! switch (event->type) { case libvlc_MediaPlayerTimeChanged: QMetaObject::invokeMethod( that, "timeChanged", Qt::QueuedConnection, Q_ARG(qint64, event->u.media_player_time_changed.new_time)); break; case libvlc_MediaPlayerSeekableChanged: QMetaObject::invokeMethod( that, "seekableChanged", Qt::QueuedConnection, Q_ARG(bool, event->u.media_player_seekable_changed.new_seekable)); break; case libvlc_MediaPlayerLengthChanged: QMetaObject::invokeMethod( that, "lengthChanged", Qt::QueuedConnection, Q_ARG(qint64, event->u.media_player_length_changed.new_length)); break; case libvlc_MediaPlayerNothingSpecial: P_EMIT_STATE(NoState); break; case libvlc_MediaPlayerOpening: P_EMIT_STATE(OpeningState); break; case libvlc_MediaPlayerBuffering: // We need to only process the buffering event in >= 2.0 as the fact // that no explicit switch to Playing is sent would lock us into // buffering with no chance of ever getting back to playing (well, unless // there is a playing event obviously). #if (LIBVLC_VERSION_INT >= LIBVLC_VERSION(2, 0, 0, 0)) // LibVLC <= 2.0 (possibly greater) does not explicitly switch to playing // once 100 % cache was reached. So we need to work around this by fake // emitting a playingstate event whereas really it was buffering :S // http://trac.videolan.org/vlc/ticket/5277 that->m_bufferCache = event->u.media_player_buffering.new_cache; #warning for some reason VLC is constantly buffering with dragon3's recent items, which keeps the mainloop busy and results in discarding just about every frame // if (that->m_bufferCache < 100) // P_EMIT_STATE(BufferingState); // else P_EMIT_STATE(PlayingState); #endif // VLC >= 2.0 break; case libvlc_MediaPlayerPlaying: P_EMIT_STATE(PlayingState); break; case libvlc_MediaPlayerPaused: P_EMIT_STATE(PausedState); break; case libvlc_MediaPlayerStopped: P_EMIT_STATE(StoppedState); break; case libvlc_MediaPlayerEndReached: P_EMIT_STATE(EndedState); break; case libvlc_MediaPlayerEncounteredError: P_EMIT_STATE(ErrorState); break; case libvlc_MediaPlayerVout: if (event->u.media_player_vout.new_count > 0) P_EMIT_HAS_VIDEO(true); else P_EMIT_HAS_VIDEO(false); break; case libvlc_MediaPlayerMediaChanged: break; case libvlc_MediaPlayerForward: case libvlc_MediaPlayerBackward: case libvlc_MediaPlayerPositionChanged: case libvlc_MediaPlayerPausableChanged: case libvlc_MediaPlayerTitleChanged: case libvlc_MediaPlayerSnapshotTaken: // Snapshot call is sync, so this is useless. default: break; QString msg = QString("Unknown event: ") + QString(libvlc_event_type_name(event->type)); Q_ASSERT_X(false, "event_cb", qPrintable(msg)); break; } } QDebug operator<<(QDebug dbg, const MediaPlayer::State &s) { QString name; switch (s) { case MediaPlayer::NoState: name = QLatin1String("MediaPlayer::NoState"); break; case MediaPlayer::OpeningState: name = QLatin1String("MediaPlayer::OpeningState"); break; case MediaPlayer::BufferingState: name = QLatin1String("MediaPlayer::BufferingState"); break; case MediaPlayer::PlayingState: name = QLatin1String("MediaPlayer::PlayingState"); break; case MediaPlayer::PausedState: name = QLatin1String("MediaPlayer::PausedState"); break; case MediaPlayer::StoppedState: name = QLatin1String("MediaPlayer::StoppedState"); break; case MediaPlayer::EndedState: name = QLatin1String("MediaPlayer::EndedState"); break; case MediaPlayer::ErrorState: name = QLatin1String("MediaPlayer::ErrorState"); break; } dbg.nospace() << "State(" << qPrintable(name) << ")"; return dbg.space(); } } // namespace VLC } // namespace Phonon
/* Copyright (C) 2011-2012 Harald Sitter <[email protected]> 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, see <http://www.gnu.org/licenses/>. */ #include "mediaplayer.h" #include <QtCore/QDebug> #include <QtCore/QDir> #include <QtCore/QMetaType> #include <QtCore/QString> #include <QtCore/QTemporaryFile> #include <QtGui/QImage> #include <vlc/libvlc_version.h> #include "utils/libvlc.h" #include "media.h" // Callbacks come from a VLC thread. In some cases Qt fails to detect this and // tries to invoke directly (i.e. from same thread). This can lead to thread // pollution throughout Phonon, which is very much not desired. #define P_EMIT_HAS_VIDEO(hasVideo) \ QMetaObject::invokeMethod(\ that, "hasVideoChanged", \ Qt::QueuedConnection, \ Q_ARG(bool, hasVideo)) #define P_EMIT_STATE(__state) \ QMetaObject::invokeMethod(\ that, "stateChanged", \ Qt::QueuedConnection, \ Q_ARG(MediaPlayer::State, __state)) namespace Phonon { namespace VLC { MediaPlayer::MediaPlayer(QObject *parent) : QObject(parent), m_player(libvlc_media_player_new(libvlc)), m_bufferCache(-1) { Q_ASSERT(m_player); qRegisterMetaType<MediaPlayer::State>("MediaPlayer::State"); libvlc_event_manager_t *manager = libvlc_media_player_event_manager(m_player); libvlc_event_type_t events[] = { libvlc_MediaPlayerMediaChanged, libvlc_MediaPlayerNothingSpecial, libvlc_MediaPlayerOpening, libvlc_MediaPlayerBuffering, libvlc_MediaPlayerPlaying, libvlc_MediaPlayerPaused, libvlc_MediaPlayerStopped, libvlc_MediaPlayerForward, libvlc_MediaPlayerBackward, libvlc_MediaPlayerEndReached, libvlc_MediaPlayerEncounteredError, libvlc_MediaPlayerTimeChanged, libvlc_MediaPlayerPositionChanged, libvlc_MediaPlayerSeekableChanged, libvlc_MediaPlayerPausableChanged, libvlc_MediaPlayerTitleChanged, libvlc_MediaPlayerSnapshotTaken, libvlc_MediaPlayerLengthChanged, libvlc_MediaPlayerVout }; const int eventCount = sizeof(events) / sizeof(*events); for (int i = 0; i < eventCount; ++i) { libvlc_event_attach(manager, events[i], event_cb, this); } } MediaPlayer::~MediaPlayer() { libvlc_media_player_release(m_player); } void MediaPlayer::setMedia(Media *media) { m_media = media; libvlc_media_player_set_media(m_player, *m_media); } bool MediaPlayer::play() { return libvlc_media_player_play(m_player) == 0; } void MediaPlayer::pause() { libvlc_media_player_set_pause(m_player, 1); } void MediaPlayer::resume() { libvlc_media_player_set_pause(m_player, 0); } void MediaPlayer::togglePause() { libvlc_media_player_pause(m_player); } void MediaPlayer::stop() { libvlc_media_player_stop(m_player); } qint64 MediaPlayer::length() const { return libvlc_media_player_get_length(m_player); } qint64 MediaPlayer::time() const { return libvlc_media_player_get_time(m_player); } void MediaPlayer::setTime(qint64 newTime) { libvlc_media_player_set_time(m_player, newTime); } bool MediaPlayer::isSeekable() const { return libvlc_media_player_is_seekable(m_player); } bool MediaPlayer::hasVideoOutput() const { return libvlc_media_player_has_vout(m_player) > 0; } bool MediaPlayer::setSubtitle(int subtitle) { return libvlc_video_set_spu(m_player, subtitle) == 0; } bool MediaPlayer::setSubtitle(const QString &file) { return libvlc_video_set_subtitle_file(m_player, file.toAscii().data()) == 0; } void MediaPlayer::setTitle(int title) { libvlc_media_player_set_title(m_player, title); } void MediaPlayer::setChapter(int chapter) { libvlc_media_player_set_chapter(m_player, chapter); } QImage MediaPlayer::snapshot() const { QTemporaryFile tempFile(QDir::tempPath() % QDir::separator() % QLatin1Literal("phonon-vlc-snapshot")); tempFile.open(); // This function is sync. if (libvlc_video_take_snapshot(m_player, 0, tempFile.fileName().toLocal8Bit().data(), 0, 0) != 0) return QImage(); return QImage(tempFile.fileName()); } bool MediaPlayer::setAudioTrack(int track) { return libvlc_audio_set_track(m_player, track) == 0; } void MediaPlayer::event_cb(const libvlc_event_t *event, void *opaque) { MediaPlayer *that = reinterpret_cast<MediaPlayer *>(opaque); Q_ASSERT(that); // Do not forget to register for the events you want to handle here! switch (event->type) { case libvlc_MediaPlayerTimeChanged: QMetaObject::invokeMethod( that, "timeChanged", Qt::QueuedConnection, Q_ARG(qint64, event->u.media_player_time_changed.new_time)); break; case libvlc_MediaPlayerSeekableChanged: QMetaObject::invokeMethod( that, "seekableChanged", Qt::QueuedConnection, Q_ARG(bool, event->u.media_player_seekable_changed.new_seekable)); break; case libvlc_MediaPlayerLengthChanged: QMetaObject::invokeMethod( that, "lengthChanged", Qt::QueuedConnection, Q_ARG(qint64, event->u.media_player_length_changed.new_length)); break; case libvlc_MediaPlayerNothingSpecial: P_EMIT_STATE(NoState); break; case libvlc_MediaPlayerOpening: P_EMIT_STATE(OpeningState); break; case libvlc_MediaPlayerBuffering: // We need to only process the buffering event in >= 2.0 as the fact // that no explicit switch to Playing is sent would lock us into // buffering with no chance of ever getting back to playing (well, unless // there is a playing event obviously). #if (LIBVLC_VERSION_INT >= LIBVLC_VERSION(2, 0, 0, 0)) // LibVLC <= 2.0 (possibly greater) does not explicitly switch to playing // once 100 % cache was reached. So we need to work around this by fake // emitting a playingstate event whereas really it was buffering :S // http://trac.videolan.org/vlc/ticket/5277 that->m_bufferCache = event->u.media_player_buffering.new_cache; #warning for some reason VLC is constantly buffering with dragon3 recent items, which keeps the mainloop busy and results in discarding just about every frame // if (that->m_bufferCache < 100) // P_EMIT_STATE(BufferingState); // else P_EMIT_STATE(PlayingState); #endif // VLC >= 2.0 break; case libvlc_MediaPlayerPlaying: P_EMIT_STATE(PlayingState); break; case libvlc_MediaPlayerPaused: P_EMIT_STATE(PausedState); break; case libvlc_MediaPlayerStopped: P_EMIT_STATE(StoppedState); break; case libvlc_MediaPlayerEndReached: P_EMIT_STATE(EndedState); break; case libvlc_MediaPlayerEncounteredError: P_EMIT_STATE(ErrorState); break; case libvlc_MediaPlayerVout: if (event->u.media_player_vout.new_count > 0) P_EMIT_HAS_VIDEO(true); else P_EMIT_HAS_VIDEO(false); break; case libvlc_MediaPlayerMediaChanged: break; case libvlc_MediaPlayerForward: case libvlc_MediaPlayerBackward: case libvlc_MediaPlayerPositionChanged: case libvlc_MediaPlayerPausableChanged: case libvlc_MediaPlayerTitleChanged: case libvlc_MediaPlayerSnapshotTaken: // Snapshot call is sync, so this is useless. default: break; QString msg = QString("Unknown event: ") + QString(libvlc_event_type_name(event->type)); Q_ASSERT_X(false, "event_cb", qPrintable(msg)); break; } } QDebug operator<<(QDebug dbg, const MediaPlayer::State &s) { QString name; switch (s) { case MediaPlayer::NoState: name = QLatin1String("MediaPlayer::NoState"); break; case MediaPlayer::OpeningState: name = QLatin1String("MediaPlayer::OpeningState"); break; case MediaPlayer::BufferingState: name = QLatin1String("MediaPlayer::BufferingState"); break; case MediaPlayer::PlayingState: name = QLatin1String("MediaPlayer::PlayingState"); break; case MediaPlayer::PausedState: name = QLatin1String("MediaPlayer::PausedState"); break; case MediaPlayer::StoppedState: name = QLatin1String("MediaPlayer::StoppedState"); break; case MediaPlayer::EndedState: name = QLatin1String("MediaPlayer::EndedState"); break; case MediaPlayer::ErrorState: name = QLatin1String("MediaPlayer::ErrorState"); break; } dbg.nospace() << "State(" << qPrintable(name) << ")"; return dbg.space(); } } // namespace VLC } // namespace Phonon
Remove ' in #warning confuses gettext
Remove ' in #warning confuses gettext And pollutes scripty logs
C++
lgpl-2.1
KDE/phonon-vlc,BinChengfei/phonon-vlc,KDE/phonon-vlc,BinChengfei/phonon-vlc,KDE/phonon-vlc,BinChengfei/phonon-vlc
dc0a26c6a141662b33331d5fb58a010cd7fe0936
src/misc/result.hpp
src/misc/result.hpp
/* * Copyright (C) 2018 Nagisa Sekiguchi * * 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 YDSH_RESULT_HPP #define YDSH_RESULT_HPP #include <type_traits> #include "noncopyable.h" namespace ydsh { template <typename T> struct TypeHolder { using type = T; }; namespace __detail { constexpr bool andAll(bool b) { return b; } template <typename ...T> constexpr bool andAll(bool b, T && ...t) { return b && andAll(std::forward<T>(t)...); } template <typename T> constexpr int toTypeIndex(int) { return -1; } template <typename T, typename F, typename ...R> constexpr int toTypeIndex(int index) { return std::is_same<T, F>::value ? index : toTypeIndex<T, R...>(index + 1); } template <std::size_t I, std::size_t N, typename F, typename ...R> struct TypeByIndex : TypeByIndex<I + 1, N, R...> {}; template <std::size_t N, typename F, typename ...R> struct TypeByIndex<N, N, F, R...> { using type = F; }; template <typename ...T> struct OverloadResolver; template <typename F, typename ...T> struct OverloadResolver<F, T...> : OverloadResolver<T...> { using OverloadResolver<T...>::operator(); TypeHolder<F> operator()(F) const; }; template <> struct OverloadResolver<> { void operator()() const; }; template <typename T> using result_of_t = typename std::result_of<T>::type; template <typename F, typename ...T> using resolvedType = typename result_of_t<OverloadResolver<T...>(F)>::type; } // namespace __detail template <typename U, typename ...T> struct TypeTag { static constexpr int value = __detail::toTypeIndex<U, T...>(0); }; template <std::size_t N, typename T0, typename ...T> struct TypeByIndex { static_assert(N < sizeof...(T) + 1, "out of range"); using type = typename __detail::TypeByIndex<0, N, T0, T...>::type; }; // ##################### // ## Storage ## // ##################### template <typename ...T> struct Storage { static_assert(sizeof...(T) > 0, "at least 1 type"); std::aligned_union_t<1, T...> data; template <typename U, typename F = __detail::resolvedType<U, T...>> void obtain(U &&value) { static_assert(TypeTag<F, T...>::value > -1, "invalid type"); using Decayed = typename std::decay<F>::type; new (&this->data) Decayed(std::forward<U>(value)); } }; template <typename T, typename ...R> inline T &get(Storage<R...> &storage) { static_assert(TypeTag<T, R...>::value > -1, "invalid type"); return *reinterpret_cast<T *>(&storage.data); } template <typename T, typename ...R> inline const T &get(const Storage<R...> &storage) { static_assert(TypeTag<T, R...>::value > -1, "invalid type"); return *reinterpret_cast<const T *>(&storage.data); } template <typename T, typename ...R> inline void destroy(Storage<R...> &storage) { get<T>(storage).~T(); } /** * * @tparam T * @tparam R * @param src * @param dest * must be uninitialized */ template <typename T, typename ...R> inline void move(Storage<R...> &src, Storage<R...> &dest) { dest.obtain(std::move(get<T>(src))); destroy<T>(src); } template <typename T, typename ...R> inline void copy(const Storage<R...> &src, Storage<R...> &dest) { dest.obtain(get<T>(src)); } namespace __detail_union { template <int N, typename ...R> struct Destroyer { void operator()(Storage<R...> &storage, int tag) const { if(tag == N) { using T = typename TypeByIndex<N, R...>::type; destroy<T>(storage); } else { Destroyer<N - 1, R...>()(storage, tag); } } }; template <typename ...R> struct Destroyer<-1, R...> { void operator()(Storage<R...> &, int) const {} }; template <int N, typename ...R> struct Mover { void operator()(Storage<R...> &src, int srcTag, Storage<R...> &dest) const { if(srcTag == N) { using T = typename TypeByIndex<N, R...>::type; move<T>(src, dest); } else { Mover<N - 1, R...>()(src, srcTag, dest); } } }; template <typename ...R> struct Mover<-1, R...> { void operator()(Storage<R...> &, int, Storage<R...> &) const {} }; template <int N, typename ...R> struct Copier { void operator()(const Storage<R...> &src, int srcTag, Storage<R...> &dest) const { if(srcTag == N) { using T = typename TypeByIndex<N, R...>::type; copy<T>(src, dest); } else { Copier<N - 1, R...>()(src, srcTag, dest); } } }; template <typename ...R> struct Copier<-1, R...> { void operator()(const Storage<R...> &, int, Storage<R...> &) const {} }; } // namespace __detail_union template <typename ...R> inline void polyDestroy(Storage<R...> &storage, int tag) { __detail_union::Destroyer<sizeof...(R) - 1, R...>()(storage, tag); } /** * * @tparam N * @tparam R * @param src * @param srcTag * @param dest * must be uninitialized */ template <typename ...R> inline void polyMove(Storage<R...> &src, int srcTag, Storage<R...> &dest) { __detail_union::Mover<sizeof...(R) - 1, R...>()(src, srcTag, dest); } template <typename ...R> inline void polyCopy(const Storage<R...> &src, int srcTag, Storage<R...> &dest) { __detail_union::Copier<sizeof...(R) - 1, R...>()(src, srcTag, dest); } // ################### // ## Union ## // ################### template <typename ...T> class Union { private: static_assert(__detail::andAll(std::is_move_constructible<T>::value...), "must be move-constructible"); using StorageType = Storage<T...>; StorageType value_; int tag_; public: template <typename R> static constexpr auto TAG = TypeTag<R, T...>::value; Union() noexcept : tag_(-1) {} template <typename U, typename F = __detail::resolvedType<U, T...>> Union(U &&value) noexcept : tag_(TAG<F>) { //NOLINT this->value_.obtain(std::forward<U>(value)); } Union(Union &&value) noexcept : tag_(value.tag()) { polyMove(value.value(), this->tag(), this->value()); value.tag_ = -1; } Union(const Union &value) : tag_(value.tag()) { polyCopy(value.value(), this->tag(), this->value()); } ~Union() { polyDestroy(this->value(), this->tag()); } Union &operator=(Union && value) noexcept { this->moveAssign(value); return *this; } Union &operator=(const Union &value) { this->copyAssign(value); return *this; } StorageType &value() { return this->value_; } const StorageType &value() const { return this->value_; } int tag() const { return this->tag_; } bool hasValue() const { return this->tag() > -1; } private: void moveAssign(Union &value) noexcept { polyDestroy(this->value(), this->tag()); polyMove(value.value(), value.tag(), this->value()); this->tag_ = value.tag(); value.tag_ = -1; } void copyAssign(const Union &value) { polyDestroy(this->value(), this->tag()); polyCopy(value.value(), value.tag(), this->value()); this->tag_ = value.tag(); } }; template <typename T, typename ...R> inline bool is(const Union<R...> &value) { return value.tag() == TypeTag<T, R...>::value; } template <typename T, typename ...R> inline T &get(Union<R...> &value) { return get<T>(value.value()); } template <typename T, typename ...R> inline const T &get(const Union<R...> &value) { return get<T>(value.value()); } // ###################### // ## Optional ## // ###################### template <typename T> class OptionalBase : public Union<T> { public: OptionalBase() noexcept : Union<T>() {} OptionalBase(T &&value) noexcept : Union<T>(std::forward<T>(value)) {} //NOLINT T &unwrap() noexcept { return get<T>(*this); } const T &unwrap() const noexcept { return get<T>(*this); } }; template <typename ...T> class OptionalBase<Union<T...>> : public Union<T...> { public: OptionalBase() noexcept : Union<T...>() {} template <typename U> OptionalBase(U &&value) noexcept : Union<T...>(std::forward<U>(value)) {} //NOLINT }; template <typename T> struct OptFlattener { using type = T; }; template <typename T> struct OptFlattener<OptionalBase<T>> : OptFlattener<T> {}; template <typename T> using Optional = OptionalBase<typename OptFlattener<T>::type>; // #################### // ## Result ## // #################### template <typename T> struct OkHolder { T value; explicit OkHolder(T &&value) : value(std::move(value)) {} explicit OkHolder(const T &value) : value(value) {} }; template <typename E> struct ErrHolder { E value; explicit ErrHolder(E &&value) : value(std::move(value)) {} explicit ErrHolder(const E &value) : value(value) {} }; template <typename T, typename Decayed = typename std::decay<T>::type> OkHolder<Decayed> Ok(T &&value) { return OkHolder<Decayed>(std::forward<T>(value)); } template <typename E, typename Decayed = typename std::decay<E>::type> ErrHolder<Decayed> Err(E &&value) { return ErrHolder<Decayed>(std::forward<E>(value)); } template <typename T, typename E> class Result : public Union<T, E> { public: NON_COPYABLE(Result); Result() = delete; template <typename T0> Result(OkHolder<T0> &&okHolder) noexcept : Union<T, E>(std::move(okHolder.value)) {} //NOLINT Result(ErrHolder<E> &&errHolder) noexcept : Union<T, E>(std::move(errHolder.value)) {} //NOLINT Result(Result &&result) noexcept = default; ~Result() = default; Result &operator=(Result &&result) noexcept = default; explicit operator bool() const { return is<T>(*this); } T &asOk() { return get<T>(*this); } E &asErr() { return get<E>(*this); } T &&take() { return std::move(this->asOk()); } E &&takeError() { return std::move(this->asErr()); } }; } // namespace ydsh #endif //YDSH_RESULT_HPP
/* * Copyright (C) 2018 Nagisa Sekiguchi * * 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 YDSH_RESULT_HPP #define YDSH_RESULT_HPP #include <type_traits> #include <cassert> #include "noncopyable.h" namespace ydsh { template <typename T> struct TypeHolder { using type = T; }; namespace __detail { constexpr bool andAll(bool b) { return b; } template <typename ...T> constexpr bool andAll(bool b, T && ...t) { return b && andAll(std::forward<T>(t)...); } template <typename T> constexpr int toTypeIndex(int) { return -1; } template <typename T, typename F, typename ...R> constexpr int toTypeIndex(int index) { return std::is_same<T, F>::value ? index : toTypeIndex<T, R...>(index + 1); } template <std::size_t I, std::size_t N, typename F, typename ...R> struct TypeByIndex : TypeByIndex<I + 1, N, R...> {}; template <std::size_t N, typename F, typename ...R> struct TypeByIndex<N, N, F, R...> { using type = F; }; template <typename ...T> struct OverloadResolver; template <typename F, typename ...T> struct OverloadResolver<F, T...> : OverloadResolver<T...> { using OverloadResolver<T...>::operator(); TypeHolder<F> operator()(F) const; }; template <> struct OverloadResolver<> { void operator()() const; }; template <typename T> using result_of_t = typename std::result_of<T>::type; template <typename F, typename ...T> using resolvedType = typename result_of_t<OverloadResolver<T...>(F)>::type; } // namespace __detail template <typename U, typename ...T> struct TypeTag { static constexpr int value = __detail::toTypeIndex<U, T...>(0); }; template <std::size_t N, typename T0, typename ...T> struct TypeByIndex { static_assert(N < sizeof...(T) + 1, "out of range"); using type = typename __detail::TypeByIndex<0, N, T0, T...>::type; }; // ##################### // ## Storage ## // ##################### template <typename ...T> struct Storage { static_assert(sizeof...(T) > 0, "at least 1 type"); std::aligned_union_t<1, T...> data; template <typename U, typename F = __detail::resolvedType<U, T...>> void obtain(U &&value) { static_assert(TypeTag<F, T...>::value > -1, "invalid type"); using Decayed = typename std::decay<F>::type; new (&this->data) Decayed(std::forward<U>(value)); } }; template <typename T, typename ...R> inline T &get(Storage<R...> &storage) { static_assert(TypeTag<T, R...>::value > -1, "invalid type"); return *reinterpret_cast<T *>(&storage.data); } template <typename T, typename ...R> inline const T &get(const Storage<R...> &storage) { static_assert(TypeTag<T, R...>::value > -1, "invalid type"); return *reinterpret_cast<const T *>(&storage.data); } template <typename T, typename ...R> inline void destroy(Storage<R...> &storage) { get<T>(storage).~T(); } /** * * @tparam T * @tparam R * @param src * @param dest * must be uninitialized */ template <typename T, typename ...R> inline void move(Storage<R...> &src, Storage<R...> &dest) { dest.obtain(std::move(get<T>(src))); destroy<T>(src); } template <typename T, typename ...R> inline void copy(const Storage<R...> &src, Storage<R...> &dest) { dest.obtain(get<T>(src)); } namespace __detail_union { template <int N, typename ...R> struct Destroyer { void operator()(Storage<R...> &storage, int tag) const { if(tag == N) { using T = typename TypeByIndex<N, R...>::type; destroy<T>(storage); } else { Destroyer<N - 1, R...>()(storage, tag); } } }; template <typename ...R> struct Destroyer<-1, R...> { void operator()(Storage<R...> &, int) const {} }; template <int N, typename ...R> struct Mover { void operator()(Storage<R...> &src, int srcTag, Storage<R...> &dest) const { if(srcTag == N) { using T = typename TypeByIndex<N, R...>::type; move<T>(src, dest); } else { Mover<N - 1, R...>()(src, srcTag, dest); } } }; template <typename ...R> struct Mover<-1, R...> { void operator()(Storage<R...> &, int, Storage<R...> &) const {} }; template <int N, typename ...R> struct Copier { void operator()(const Storage<R...> &src, int srcTag, Storage<R...> &dest) const { if(srcTag == N) { using T = typename TypeByIndex<N, R...>::type; copy<T>(src, dest); } else { Copier<N - 1, R...>()(src, srcTag, dest); } } }; template <typename ...R> struct Copier<-1, R...> { void operator()(const Storage<R...> &, int, Storage<R...> &) const {} }; } // namespace __detail_union template <typename ...R> inline void polyDestroy(Storage<R...> &storage, int tag) { __detail_union::Destroyer<sizeof...(R) - 1, R...>()(storage, tag); } /** * * @tparam N * @tparam R * @param src * @param srcTag * @param dest * must be uninitialized */ template <typename ...R> inline void polyMove(Storage<R...> &src, int srcTag, Storage<R...> &dest) { __detail_union::Mover<sizeof...(R) - 1, R...>()(src, srcTag, dest); } template <typename ...R> inline void polyCopy(const Storage<R...> &src, int srcTag, Storage<R...> &dest) { __detail_union::Copier<sizeof...(R) - 1, R...>()(src, srcTag, dest); } // ################### // ## Union ## // ################### template <typename ...T> class Union { private: static_assert(__detail::andAll(std::is_move_constructible<T>::value...), "must be move-constructible"); using StorageType = Storage<T...>; StorageType value_; int tag_; public: template <typename R> static constexpr auto TAG = TypeTag<R, T...>::value; Union() noexcept : tag_(-1) {} template <typename U, typename F = __detail::resolvedType<U, T...>> Union(U &&value) noexcept : tag_(TAG<F>) { //NOLINT this->value_.obtain(std::forward<U>(value)); } Union(Union &&value) noexcept : tag_(value.tag()) { polyMove(value.value(), this->tag(), this->value()); value.tag_ = -1; } Union(const Union &value) : tag_(value.tag()) { polyCopy(value.value(), this->tag(), this->value()); } ~Union() { polyDestroy(this->value(), this->tag()); } Union &operator=(Union && value) noexcept { this->moveAssign(value); return *this; } Union &operator=(const Union &value) { this->copyAssign(value); return *this; } StorageType &value() { return this->value_; } const StorageType &value() const { return this->value_; } int tag() const { return this->tag_; } bool hasValue() const { return this->tag() > -1; } private: void moveAssign(Union &value) noexcept { polyDestroy(this->value(), this->tag()); polyMove(value.value(), value.tag(), this->value()); this->tag_ = value.tag(); value.tag_ = -1; } void copyAssign(const Union &value) { polyDestroy(this->value(), this->tag()); polyCopy(value.value(), value.tag(), this->value()); this->tag_ = value.tag(); } }; template <typename T, typename ...R> inline bool is(const Union<R...> &value) { return value.tag() == TypeTag<T, R...>::value; } template <typename T, typename ...R> inline T &get(Union<R...> &value) { assert(is<T>(value)); return get<T>(value.value()); } template <typename T, typename ...R> inline const T &get(const Union<R...> &value) { assert(is<T>(value)); return get<T>(value.value()); } // ###################### // ## Optional ## // ###################### template <typename T> class OptionalBase : public Union<T> { public: OptionalBase() noexcept : Union<T>() {} OptionalBase(T &&value) noexcept : Union<T>(std::forward<T>(value)) {} //NOLINT T &unwrap() noexcept { return get<T>(*this); } const T &unwrap() const noexcept { return get<T>(*this); } }; template <typename ...T> class OptionalBase<Union<T...>> : public Union<T...> { public: OptionalBase() noexcept : Union<T...>() {} template <typename U> OptionalBase(U &&value) noexcept : Union<T...>(std::forward<U>(value)) {} //NOLINT }; template <typename T> struct OptFlattener { using type = T; }; template <typename T> struct OptFlattener<OptionalBase<T>> : OptFlattener<T> {}; template <typename T> using Optional = OptionalBase<typename OptFlattener<T>::type>; // #################### // ## Result ## // #################### template <typename T> struct OkHolder { T value; explicit OkHolder(T &&value) : value(std::move(value)) {} explicit OkHolder(const T &value) : value(value) {} }; template <typename E> struct ErrHolder { E value; explicit ErrHolder(E &&value) : value(std::move(value)) {} explicit ErrHolder(const E &value) : value(value) {} }; template <typename T, typename Decayed = typename std::decay<T>::type> OkHolder<Decayed> Ok(T &&value) { return OkHolder<Decayed>(std::forward<T>(value)); } template <typename E, typename Decayed = typename std::decay<E>::type> ErrHolder<Decayed> Err(E &&value) { return ErrHolder<Decayed>(std::forward<E>(value)); } template <typename T, typename E> class Result : public Union<T, E> { public: NON_COPYABLE(Result); Result() = delete; template <typename T0> Result(OkHolder<T0> &&okHolder) noexcept : Union<T, E>(std::move(okHolder.value)) {} //NOLINT Result(ErrHolder<E> &&errHolder) noexcept : Union<T, E>(std::move(errHolder.value)) {} //NOLINT Result(Result &&result) noexcept = default; ~Result() = default; Result &operator=(Result &&result) noexcept = default; explicit operator bool() const { return is<T>(*this); } T &asOk() { return get<T>(*this); } E &asErr() { return get<E>(*this); } T &&take() { return std::move(this->asOk()); } E &&takeError() { return std::move(this->asErr()); } }; } // namespace ydsh #endif //YDSH_RESULT_HPP
add extra assertion to Union
add extra assertion to Union
C++
apache-2.0
sekiguchi-nagisa/ydsh,sekiguchi-nagisa/ydsh,sekiguchi-nagisa/ydsh
7bca36c41770f32652e9ec32926e674f78e603ac
src/eventql/sql/expressions/table/limit.cc
src/eventql/sql/expressions/table/limit.cc
/** * This file is part of the "libfnord" project * Copyright (c) 2015 Paul Asmuth * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. You should have received a * copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ #include <eventql/sql/expressions/table/limit.h> namespace csql { Limit::Limit( size_t limit, size_t offset, ScopedPtr<TableExpression> input) : limit_(limit), offset_(offset), input_(std::move(input)), counter_(0) {} ScopedPtr<ResultCursor> Limit::execute() { input_cursor_ = input_->execute(); buf_.resize(input_cursor_->getNumColumns()); return mkScoped( new DefaultResultCursor( input_cursor_->getNumColumns(), std::bind( &Limit::next, this, std::placeholders::_1, std::placeholders::_2))); } bool Limit::next(SValue* row, size_t row_len) { if (limit == 0 || counter_ >= offset_ + limit_) { return false; } while (input_cursor_->next(buf_.data(), buf_.size())) { if (counter_++ < offset_) { continue; } else { for (size_t i = 0; i < row_len && i < buf_.size(); ++i) { row[i] = buf_[i]; } return true; } } } }
/** * This file is part of the "libfnord" project * Copyright (c) 2015 Paul Asmuth * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. You should have received a * copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ #include <eventql/sql/expressions/table/limit.h> namespace csql { Limit::Limit( size_t limit, size_t offset, ScopedPtr<TableExpression> input) : limit_(limit), offset_(offset), input_(std::move(input)), counter_(0) {} ScopedPtr<ResultCursor> Limit::execute() { input_cursor_ = input_->execute(); buf_.resize(input_cursor_->getNumColumns()); return mkScoped( new DefaultResultCursor( input_cursor_->getNumColumns(), std::bind( &Limit::next, this, std::placeholders::_1, std::placeholders::_2))); } bool Limit::next(SValue* row, size_t row_len) { if (limit == 0 || counter_ >= offset_ + limit_) { return false; } while (input_cursor_->next(buf_.data(), buf_.size())) { if (counter_++ < offset_) { continue; } else { for (size_t i = 0; i < row_len && i < buf_.size(); ++i) { row[i] = buf_[i]; } return true; } } return false; } }
Update limit.cc
Update limit.cc
C++
agpl-3.0
eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql
6bb4547531bbb46e41e8bf1db1a7bbc14e0d1c21
src/motor_serial.cc
src/motor_serial.cc
/** Copyright (c) 2016, Ubiquity Robotics 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 ubiquity_motor nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ #include <ros/ros.h> #include <serial/serial.h> #include <ubiquity_motor/motor_serial.h> MotorSerial::MotorSerial(const std::string& port, uint32_t baud_rate) : motors(port, baud_rate, serial::Timeout::simpleTimeout(100)), serial_errors(0), error_threshold(12) { serial_thread = boost::thread(&MotorSerial::SerialThread, this); } MotorSerial::~MotorSerial() { serial_thread.interrupt(); serial_thread.join(); motors.close(); } int MotorSerial::transmitCommand(MotorMessage command) { RawMotorMessage out = command.serialize(); ROS_DEBUG("out %02x %02x %02x %02x %02x %02x %02x %02x", out[0], out[1], out[2], out[3], out[4], out[5], out[6], out[7]); motors.write(out.c_array(), out.size()); return 0; } int MotorSerial::transmitCommands(const std::vector<MotorMessage>& commands) { for (auto& command : commands) { RawMotorMessage out = command.serialize(); ROS_DEBUG("out %02x %02x %02x %02x %02x %02x %02x %02x", out[0], out[1], out[2], out[3], out[4], out[5], out[6], out[7]); motors.write(out.c_array(), out.size()); boost::this_thread::sleep(boost::posix_time::milliseconds(2)); } return 0; } MotorMessage MotorSerial::receiveCommand() { MotorMessage mc; if (!this->output.empty()) { mc = output.front_pop(); } return mc; } int MotorSerial::commandAvailable() { return !output.fast_empty(); } void MotorSerial::appendOutput(MotorMessage command) { output.push(command); } void MotorSerial::SerialThread() { try { while (motors.isOpen()) { boost::this_thread::interruption_point(); if (motors.waitReadable()) { RawMotorMessage innew = {0, 0, 0, 0, 0, 0, 0, 0}; motors.read(innew.c_array(), 1); if (innew[0] != MotorMessage::delimeter) { // The first byte was not the delimiter, so re-loop if (++serial_errors > error_threshold) { ROS_WARN("REJECT %02x", innew[0]); } continue; } // This will wait for the transmission time of 8 bytes motors.waitByteTimes(innew.size()); // Read in next 7 bytes motors.read(&innew.c_array()[1], 7); ROS_DEBUG("Got message %x %x %x %x %x %x %x %x", innew[0], innew[1], innew[2], innew[3], innew[4], innew[5], innew[6], innew[7]); MotorMessage mc; int error_code = mc.deserialize(innew); if (error_code == 0) { appendOutput(mc); if (mc.getType() == MotorMessage::TYPE_ERROR) { ROS_ERROR("GOT error from Firm 0x%02x", mc.getRegister()); } } else { if (++serial_errors > error_threshold) { ROS_ERROR("DESERIALIZATION ERROR! - %d", error_code); } } } } } catch (const boost::thread_interrupted& e) { motors.close(); } catch (const serial::IOException& e) { ROS_ERROR("%s", e.what()); } catch (const serial::PortNotOpenedException& e) { ROS_ERROR("%s", e.what()); } catch (...) { ROS_ERROR("Unknown Error"); throw; } }
/** Copyright (c) 2016, Ubiquity Robotics 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 ubiquity_motor nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ #include <ros/ros.h> #include <serial/serial.h> #include <ubiquity_motor/motor_serial.h> MotorSerial::MotorSerial(const std::string& port, uint32_t baud_rate) : motors(port, baud_rate, serial::Timeout::simpleTimeout(100)), serial_errors(0), error_threshold(20) { serial_thread = boost::thread(&MotorSerial::SerialThread, this); } MotorSerial::~MotorSerial() { serial_thread.interrupt(); serial_thread.join(); motors.close(); } int MotorSerial::transmitCommand(MotorMessage command) { RawMotorMessage out = command.serialize(); ROS_DEBUG("out %02x %02x %02x %02x %02x %02x %02x %02x", out[0], out[1], out[2], out[3], out[4], out[5], out[6], out[7]); motors.write(out.c_array(), out.size()); return 0; } int MotorSerial::transmitCommands(const std::vector<MotorMessage>& commands) { for (auto& command : commands) { RawMotorMessage out = command.serialize(); ROS_DEBUG("out %02x %02x %02x %02x %02x %02x %02x %02x", out[0], out[1], out[2], out[3], out[4], out[5], out[6], out[7]); motors.write(out.c_array(), out.size()); boost::this_thread::sleep(boost::posix_time::milliseconds(2)); } return 0; } MotorMessage MotorSerial::receiveCommand() { MotorMessage mc; if (!this->output.empty()) { mc = output.front_pop(); } return mc; } int MotorSerial::commandAvailable() { return !output.fast_empty(); } void MotorSerial::appendOutput(MotorMessage command) { output.push(command); } void MotorSerial::SerialThread() { try { while (motors.isOpen()) { boost::this_thread::interruption_point(); if (motors.waitReadable()) { RawMotorMessage innew = {0, 0, 0, 0, 0, 0, 0, 0}; motors.read(innew.c_array(), 1); if (innew[0] != MotorMessage::delimeter) { // The first byte was not the delimiter, so re-loop if (++serial_errors > error_threshold) { ROS_WARN("REJECT %02x", innew[0]); } continue; } // This will wait for the transmission time of 8 bytes motors.waitByteTimes(innew.size()); // Read in next 7 bytes motors.read(&innew.c_array()[1], 7); ROS_DEBUG("Got message %x %x %x %x %x %x %x %x", innew[0], innew[1], innew[2], innew[3], innew[4], innew[5], innew[6], innew[7]); MotorMessage mc; int error_code = mc.deserialize(innew); if (error_code == 0) { appendOutput(mc); if (mc.getType() == MotorMessage::TYPE_ERROR) { ROS_ERROR("GOT error from Firm 0x%02x", mc.getRegister()); } } else { if (++serial_errors > error_threshold) { ROS_ERROR("DESERIALIZATION ERROR! - %d", error_code); } } } } } catch (const boost::thread_interrupted& e) { motors.close(); } catch (const serial::IOException& e) { ROS_ERROR("%s", e.what()); } catch (const serial::PortNotOpenedException& e) { ROS_ERROR("%s", e.what()); } catch (...) { ROS_ERROR("Unknown Error"); throw; } }
Increase error_threshold
Increase error_threshold
C++
bsd-3-clause
UbiquityRobotics/ubiquity_motor,UbiquityRobotics/ubiquity_motor,UbiquityRobotics/ubiquity_motor
e479679b805baa44282b4e34fa9e34f60c4ebe6a
src/initiation/transport/tcpconnection.cpp
src/initiation/transport/tcpconnection.cpp
#include "tcpconnection.h" #include "common.h" #include "logger.h" #include <QDataStream> #include <QtConcurrent/QtConcurrent> #include <stdint.h> const uint32_t MAX_READ_BYTES = 10000; const uint8_t NUMBER_OF_RETRIES = 3; const uint16_t CONNECTION_TIMEOUT_MS = 200; const uint16_t DISCONNECT_TIMEOUT_MS = 1000; TCPConnection::TCPConnection() : socket_(nullptr), shouldConnect_(false), destination_(), port_(0), socketDescriptor_(0), buffer_(), sendMutex_(), active_(false) {} TCPConnection::~TCPConnection() { uninit(); } void TCPConnection::init() { QObject::connect(this, &TCPConnection::error, this, &TCPConnection::printError); active_ = true; if (socket_ == nullptr) { socket_ = new QTcpSocket(); QObject::connect(socket_, &QAbstractSocket::disconnected, this, &TCPConnection::disconnected); QObject::connect(socket_, &QAbstractSocket::bytesWritten, this, &TCPConnection::printBytesWritten); QObject::connect(socket_, &QAbstractSocket::readyRead, this, &TCPConnection::receivedMessage); } } void TCPConnection::uninit() { active_ = false; if(socket_ != nullptr) { QObject::disconnect(socket_, &QAbstractSocket::disconnected, this, &TCPConnection::disconnected); QObject::disconnect(socket_, &QAbstractSocket::bytesWritten, this, &TCPConnection::printBytesWritten); QObject::disconnect(socket_, &QAbstractSocket::readyRead, this, &TCPConnection::receivedMessage); delete socket_; socket_ = nullptr; } } bool TCPConnection::isConnected() const { return socket_ != nullptr && socket_->state() == QAbstractSocket::ConnectedState; } QString TCPConnection::localAddress() const { if (isConnected()) { return socket_->localAddress().toString(); } return ""; } QString TCPConnection::remoteAddress() const { if (isConnected()) { return socket_->peerAddress().toString(); } return ""; } uint16_t TCPConnection::localPort() const { if (isConnected()) { return socket_->localPort(); } return 0; } uint16_t TCPConnection::remotePort() const { if (isConnected()) { return socket_->peerPort(); } return 0; } QAbstractSocket::NetworkLayerProtocol TCPConnection::localProtocol() const { if (isConnected()) { return socket_->localAddress().protocol(); } return QAbstractSocket::NetworkLayerProtocol::AnyIPProtocol; } QAbstractSocket::NetworkLayerProtocol TCPConnection::remoteProtocol() const { if (isConnected()) { return socket_->peerAddress().protocol(); } return QAbstractSocket::NetworkLayerProtocol::AnyIPProtocol; } void TCPConnection::stopConnection() { active_ = false; eventDispatcher()->interrupt(); } void TCPConnection::establishConnection(const QString &destination, uint16_t port) { Logger::getLogger()->printDebug(DEBUG_NORMAL, this, "Establishing connection", {"Destination", "port"}, {destination, QString::number(port)}); destination_ = destination; port_ = port; shouldConnect_ = true; start(); } void TCPConnection::setExistingConnection(qintptr socketDescriptor) { Logger::getLogger()->printNormal(this, "Setting existing/incoming connection.", {"Sock desc"}, {QString::number(socketDescriptor)}); socketDescriptor_ = socketDescriptor; shouldConnect_ = true; start(); } void TCPConnection::sendPacket(const QString &data) { //Logger::getLogger()->printNormal(this, "Adding to send buffer"); if(active_) { sendMutex_.lock(); buffer_.push(data); sendMutex_.unlock(); eventDispatcher()->wakeUp(); } else { Logger::getLogger()->printWarning(this, "Not sending message, " "because sender has been shut down."); } } void TCPConnection::receivedMessage() { //Logger::getLogger()->printNormal(this, "Socket ready to read."); if (active_ ) { eventDispatcher()->wakeUp(); } else { Logger::getLogger()->printWarning(this, "Socket not active when receiving message"); } } bool TCPConnection::connectLoop() { Logger::getLogger()->printNormal(this, "Starting to connect TCP"); if (socket_ == nullptr) { Logger::getLogger()->printProgramWarning(this, "Socket not initialized before connection"); init(); } if (socketDescriptor_ != 0) { Logger::getLogger()->printNormal(this, "Setting existing socket descriptor", {"Sock desc"}, {QString::number(socketDescriptor_)}); if (!socket_->setSocketDescriptor(socketDescriptor_)) { Logger::getLogger()->printProgramError(this, "Could not set socket descriptor " "for existing connection."); return false; } } else { Logger::getLogger()->printNormal(this, "Checking status", {"Address"}, {destination_ + ":" + QString::number(port_)}); for (unsigned int i = 0; i < NUMBER_OF_RETRIES && socket_->state() != QAbstractSocket::ConnectedState; ++i) { Logger::getLogger()->printDebug(DEBUG_NORMAL, this, "Attempting to connect", {"Attempt"}, {QString::number(i + 1)}); socket_->connectToHost(destination_, port_); // attempt connection with increasing wait time socket_->waitForConnected(CONNECTION_TIMEOUT_MS * (i + 1)); } } if (socket_->state() != QAbstractSocket::ConnectedState) { emit error(socket_->error(), socket_->errorString()); emit unableToConnect(destination_); return false; } Logger::getLogger()->printNormal( this, "Connected succesfully", {"Connection"}, {socket_->localAddress().toString() + ":" + QString::number(socket_->localPort()) + " <-> " + socket_->peerAddress().toString() + ":" + QString::number(socket_->peerPort())}); emit socketConnected(socket_->localAddress().toString(), socket_->peerAddress().toString()); return true; } void TCPConnection::run() { Logger::getLogger()->printImportant(this, "Starting TCP loop"); init(); if(eventDispatcher() == nullptr) { Logger::getLogger()->printDebug(DEBUG_WARNING, this, "No event dispatcher for this connection."); return; } while(active_) { // TODO: Stop trying if connection can't be established. if(!isConnected() && shouldConnect_) { if (!connectLoop()) { Logger::getLogger()->printWarning(this, "Failed to connect TCP connection"); shouldConnect_ = false; } } if(socket_->bytesToWrite() > 0) { Logger::getLogger()->printDebug(DEBUG_NORMAL, this, "Detected need to send.", {"Bytes", "State"}, {QString::number(socket_->bytesToWrite()), QString::number(socket_->state())}); } if(socket_->state() == QAbstractSocket::ConnectedState) { if(socket_->isValid() && socket_->canReadLine() && socket_->bytesAvailable() < MAX_READ_BYTES) { Logger::getLogger()->printNormal(this, "Can read one line", {"Bytes available"}, {QString::number(socket_->bytesAvailable())}); // TODO: This should probably be some other stream, because we get also non text stuff in content? QTextStream in(socket_); QString message; message = in.read(MAX_READ_BYTES); emit messageAvailable(message); } else if(socket_->bytesAvailable() > MAX_READ_BYTES) { Logger::getLogger()->printDebug(DEBUG_WARNING, this, "Flushing the socket because of too much data!"); socket_->flush(); } sendMutex_.lock(); while(buffer_.size() > 0 && socket_->state() == QAbstractSocket::ConnectedState) { bufferToSocket(); } sendMutex_.unlock(); } eventDispatcher()->processEvents(QEventLoop::WaitForMoreEvents); } // send all remaining messages in buffer while(buffer_.size() > 0 && socket_->state() == QAbstractSocket::ConnectedState) { bufferToSocket(); } eventDispatcher()->processEvents(QEventLoop::ExcludeUserInputEvents); Logger::getLogger()->printNormal(this, "Disconnecting TCP connection"); disconnect(); uninit(); Logger::getLogger()->printImportant(this, "Ended TCP loop"); } void TCPConnection::bufferToSocket() { Logger::getLogger()->printNormal(this, "Writing buffer to TCP socket", {"Buffer size"}, {QString::number(buffer_.size())}); if(buffer_.size() > MAX_READ_BYTES) { Logger::getLogger()->printDebug(DEBUG_WARNING, this, "We are sending too much stuff to the other end", {"Buffer size"}, {QString::number(buffer_.size())}); } QString message = buffer_.front(); buffer_.pop(); // For some reason write stream has to be created every write, otherwise // a mysterious crash appears. QTextStream stream (socket_); stream << message; } void TCPConnection::disconnect() { active_ = false; shouldConnect_ = false; if (socket_) { socket_->disconnectFromHost(); if(socket_->state() == QAbstractSocket::UnconnectedState || socket_->waitForDisconnected(DISCONNECT_TIMEOUT_MS)) { Logger::getLogger()->printNormal(this, "TCP disconnected"); } else { emit error(socket_->error(), socket_->errorString()); return; } } } void TCPConnection::disconnected() { Logger::getLogger()->printWarning(this, "TCP socket disconnected"); } void TCPConnection::printError(int socketError, const QString &message) { Logger::getLogger()->printDebug(DEBUG_ERROR, this, "Socket Error", {"Code", "Message"}, {QString::number(socketError), message}); } void TCPConnection::printBytesWritten(qint64 bytes) { Logger::getLogger()->printNormal(this, "Written to socket", {"Bytes"}, {QString::number(bytes)}); }
#include "tcpconnection.h" #include "common.h" #include "logger.h" #include <QDataStream> #include <QtConcurrent/QtConcurrent> #include <stdint.h> const uint32_t MAX_READ_BYTES = 10000; const uint8_t NUMBER_OF_RETRIES = 3; const uint16_t CONNECTION_TIMEOUT_MS = 200; const uint16_t DISCONNECT_TIMEOUT_MS = 1000; TCPConnection::TCPConnection() : socket_(nullptr), shouldConnect_(false), destination_(), port_(0), socketDescriptor_(0), buffer_(), sendMutex_(), active_(false) {} TCPConnection::~TCPConnection() { uninit(); } void TCPConnection::init() { QObject::connect(this, &TCPConnection::error, this, &TCPConnection::printError); active_ = true; if (socket_ == nullptr) { socket_ = new QTcpSocket(); QObject::connect(socket_, &QAbstractSocket::disconnected, this, &TCPConnection::disconnected); QObject::connect(socket_, &QAbstractSocket::bytesWritten, this, &TCPConnection::printBytesWritten); QObject::connect(socket_, &QAbstractSocket::readyRead, this, &TCPConnection::receivedMessage); } } void TCPConnection::uninit() { active_ = false; if(socket_ != nullptr) { QObject::disconnect(socket_, &QAbstractSocket::disconnected, this, &TCPConnection::disconnected); QObject::disconnect(socket_, &QAbstractSocket::bytesWritten, this, &TCPConnection::printBytesWritten); QObject::disconnect(socket_, &QAbstractSocket::readyRead, this, &TCPConnection::receivedMessage); delete socket_; socket_ = nullptr; } } bool TCPConnection::isConnected() const { return socket_ != nullptr && socket_->state() == QAbstractSocket::ConnectedState; } QString TCPConnection::localAddress() const { if (isConnected()) { return socket_->localAddress().toString(); } return ""; } QString TCPConnection::remoteAddress() const { if (isConnected()) { return socket_->peerAddress().toString(); } return ""; } uint16_t TCPConnection::localPort() const { if (isConnected()) { return socket_->localPort(); } return 0; } uint16_t TCPConnection::remotePort() const { if (isConnected()) { return socket_->peerPort(); } return 0; } QAbstractSocket::NetworkLayerProtocol TCPConnection::localProtocol() const { if (isConnected()) { return socket_->localAddress().protocol(); } return QAbstractSocket::NetworkLayerProtocol::AnyIPProtocol; } QAbstractSocket::NetworkLayerProtocol TCPConnection::remoteProtocol() const { if (isConnected()) { return socket_->peerAddress().protocol(); } return QAbstractSocket::NetworkLayerProtocol::AnyIPProtocol; } void TCPConnection::stopConnection() { active_ = false; eventDispatcher()->interrupt(); } void TCPConnection::establishConnection(const QString &destination, uint16_t port) { Logger::getLogger()->printDebug(DEBUG_NORMAL, this, "Establishing connection", {"Destination", "port"}, {destination, QString::number(port)}); destination_ = destination; port_ = port; shouldConnect_ = true; start(); } void TCPConnection::setExistingConnection(qintptr socketDescriptor) { Logger::getLogger()->printNormal(this, "Setting existing/incoming connection.", {"Sock desc"}, {QString::number(socketDescriptor)}); socketDescriptor_ = socketDescriptor; shouldConnect_ = true; start(); } void TCPConnection::sendPacket(const QString &data) { //Logger::getLogger()->printNormal(this, "Adding to send buffer"); if(active_) { sendMutex_.lock(); buffer_.push(data); sendMutex_.unlock(); eventDispatcher()->wakeUp(); } else { Logger::getLogger()->printWarning(this, "Not sending message, " "because sender has been shut down."); } } void TCPConnection::receivedMessage() { //Logger::getLogger()->printNormal(this, "Socket ready to read."); if (active_ ) { eventDispatcher()->wakeUp(); } else { Logger::getLogger()->printWarning(this, "Socket not active when receiving message"); } } bool TCPConnection::connectLoop() { Logger::getLogger()->printNormal(this, "Starting to connect TCP"); if (socket_ == nullptr) { Logger::getLogger()->printProgramWarning(this, "Socket not initialized before connection"); init(); } if (socketDescriptor_ != 0) { Logger::getLogger()->printNormal(this, "Setting existing socket descriptor", {"Sock desc"}, {QString::number(socketDescriptor_)}); if (!socket_->setSocketDescriptor(socketDescriptor_)) { Logger::getLogger()->printProgramError(this, "Could not set socket descriptor " "for existing connection."); return false; } } else { Logger::getLogger()->printNormal(this, "Checking status", {"Address"}, {destination_ + ":" + QString::number(port_)}); for (unsigned int i = 0; i < NUMBER_OF_RETRIES && socket_->state() != QAbstractSocket::ConnectedState; ++i) { Logger::getLogger()->printDebug(DEBUG_NORMAL, this, "Attempting to connect", {"Attempt"}, {QString::number(i + 1)}); socket_->connectToHost(destination_, port_); // attempt connection with increasing wait time socket_->waitForConnected(CONNECTION_TIMEOUT_MS * (i + 1)); } } if (socket_->state() != QAbstractSocket::ConnectedState) { emit error(socket_->error(), socket_->errorString()); emit unableToConnect(destination_); return false; } Logger::getLogger()->printNormal( this, "Connected succesfully", {"Connection"}, {socket_->localAddress().toString() + ":" + QString::number(socket_->localPort()) + " <-> " + socket_->peerAddress().toString() + ":" + QString::number(socket_->peerPort())}); emit socketConnected(socket_->localAddress().toString(), socket_->peerAddress().toString()); return true; } void TCPConnection::run() { Logger::getLogger()->printImportant(this, "Starting TCP loop"); init(); if(eventDispatcher() == nullptr) { Logger::getLogger()->printDebug(DEBUG_WARNING, this, "No event dispatcher for this connection."); return; } while(active_) { if(!isConnected() && shouldConnect_) { if (!connectLoop()) { Logger::getLogger()->printWarning(this, "Failed to connect TCP connection"); shouldConnect_ = false; active_ = false; } } if(socket_->bytesToWrite() > 0) { Logger::getLogger()->printDebug(DEBUG_NORMAL, this, "Detected need to send.", {"Bytes", "State"}, {QString::number(socket_->bytesToWrite()), QString::number(socket_->state())}); } if(socket_->state() == QAbstractSocket::ConnectedState) { if(socket_->isValid() && socket_->canReadLine() && socket_->bytesAvailable() < MAX_READ_BYTES) { Logger::getLogger()->printNormal(this, "Can read one line", {"Bytes available"}, {QString::number(socket_->bytesAvailable())}); // TODO: This should probably be some other stream, because we get also non text stuff in content? QTextStream in(socket_); QString message; message = in.read(MAX_READ_BYTES); emit messageAvailable(message); } else if(socket_->bytesAvailable() > MAX_READ_BYTES) { Logger::getLogger()->printDebug(DEBUG_WARNING, this, "Flushing the socket because of too much data!"); socket_->flush(); } sendMutex_.lock(); while(buffer_.size() > 0 && socket_->state() == QAbstractSocket::ConnectedState) { bufferToSocket(); } sendMutex_.unlock(); } eventDispatcher()->processEvents(QEventLoop::WaitForMoreEvents); } // send all remaining messages in buffer while(buffer_.size() > 0 && socket_->state() == QAbstractSocket::ConnectedState) { bufferToSocket(); } eventDispatcher()->processEvents(QEventLoop::ExcludeUserInputEvents); Logger::getLogger()->printNormal(this, "Disconnecting TCP connection"); disconnect(); uninit(); Logger::getLogger()->printImportant(this, "Ended TCP loop"); } void TCPConnection::bufferToSocket() { Logger::getLogger()->printNormal(this, "Writing buffer to TCP socket", {"Buffer size"}, {QString::number(buffer_.size())}); if(buffer_.size() > MAX_READ_BYTES) { Logger::getLogger()->printDebug(DEBUG_WARNING, this, "We are sending too much stuff to the other end", {"Buffer size"}, {QString::number(buffer_.size())}); } QString message = buffer_.front(); buffer_.pop(); // For some reason write stream has to be created every write, otherwise // a mysterious crash appears. QTextStream stream (socket_); stream << message; } void TCPConnection::disconnect() { active_ = false; shouldConnect_ = false; if (socket_) { if(socket_->state() != QAbstractSocket::UnconnectedState) { socket_->disconnectFromHost(); } if(socket_->state() == QAbstractSocket::UnconnectedState || socket_->waitForDisconnected(DISCONNECT_TIMEOUT_MS)) { Logger::getLogger()->printNormal(this, "TCP disconnected"); } else { emit error(socket_->error(), socket_->errorString()); return; } } } void TCPConnection::disconnected() { Logger::getLogger()->printWarning(this, "TCP socket disconnected"); } void TCPConnection::printError(int socketError, const QString &message) { Logger::getLogger()->printDebug(DEBUG_ERROR, this, "Socket Error", {"Code", "Message"}, {QString::number(socketError), message}); } void TCPConnection::printBytesWritten(qint64 bytes) { Logger::getLogger()->printNormal(this, "Written to socket", {"Bytes"}, {QString::number(bytes)}); }
Exit connection loop if connection cannot be formed
fix(Transport): Exit connection loop if connection cannot be formed
C++
isc
ultravideo/kvazzup,ultravideo/kvazzup
eb532ad79f923ed0b3f34862530b32de01e828a5
src/renderstate.cpp
src/renderstate.cpp
#include "renderstate.hpp" #include "buffer.hpp" #include "framebuffer.hpp" #include "framebufferattachment.hpp" #include "graphicsdevice.hpp" #include "graphicssynchronizer.hpp" #include "program.hpp" #include "renderbuffer.hpp" #include "texture.hpp" #include "vertexarray.hpp" gst::RenderState::RenderState( std::shared_ptr<GraphicsDevice> device, std::shared_ptr<GraphicsSynchronizer> synchronizer) : device(device), synchronizer(synchronizer), clear_color(0.0f, 0.0f, 0.0f, 0.0f), blend_mode(BlendMode::NONE), cull_face(CullFace::NONE), depth_mask(true), depth_test(false) { device->set_clear_color(clear_color); device->set_blend_mode(blend_mode); device->set_cull_face(cull_face); device->set_depth_mask(depth_mask); device->set_depth_test(depth_test); device->bind_framebuffer(0); device->set_viewport(viewport); } void gst::RenderState::set_clear_color(Color const & clear_color) { if (this->clear_color != clear_color) { this->clear_color = clear_color; device->set_clear_color(clear_color); } } void gst::RenderState::set_blend_mode(BlendMode blend_mode) { if (this->blend_mode != blend_mode) { this->blend_mode = blend_mode; device->set_blend_mode(blend_mode); } } void gst::RenderState::set_cull_face(CullFace cull_face) { if (this->cull_face != cull_face) { this->cull_face = cull_face; device->set_cull_face(cull_face); } } void gst::RenderState::set_depth_mask(bool depth_mask) { if (this->depth_mask != depth_mask) { this->depth_mask = depth_mask; device->set_depth_mask(depth_mask); } } void gst::RenderState::set_depth_test(bool depth_test) { if (this->depth_test != depth_test) { this->depth_test = depth_test; device->set_depth_test(depth_test); } } void gst::RenderState::set_framebuffer(std::shared_ptr<Framebuffer> framebuffer) { if (this->framebuffer != framebuffer) { this->framebuffer = framebuffer; if (framebuffer) { synchronizer->bind(*framebuffer); } else { device->bind_framebuffer(0); } } if (framebuffer) { // keep attachments up-to-date set_framebuffer_attachment(framebuffer->get_color_attachment()); set_framebuffer_attachment(framebuffer->get_depth_attachment()); synchronizer->update(*framebuffer); } } void gst::RenderState::set_renderbuffer(std::shared_ptr<Renderbuffer> renderbuffer) { if (this->renderbuffer != renderbuffer) { this->renderbuffer = renderbuffer; synchronizer->bind(*renderbuffer); } synchronizer->update(*renderbuffer); } void gst::RenderState::set_program(std::shared_ptr<Program> program) { if (this->program != program) { this->program = program; synchronizer->bind(*program); } synchronizer->update(*program); } void gst::RenderState::set_texture(std::shared_ptr<Texture> texture, int unit) { auto current = textures.count(unit) > 0 ? textures.at(unit) : nullptr; if (current != texture) { textures[unit] = texture; synchronizer->bind(*texture, unit); } synchronizer->update(*texture); } void gst::RenderState::set_vertex_array(std::shared_ptr<VertexArray> vertex_array) { if (this->vertex_array != vertex_array) { this->vertex_array = vertex_array; synchronizer->bind(*vertex_array); } synchronizer->update(*vertex_array); } void gst::RenderState::set_viewport(Viewport const & viewport) { if (this->viewport != viewport) { this->viewport = viewport; device->set_viewport(viewport); } } void gst::RenderState::set_framebuffer_attachment(FramebufferAttachment const & attachment) { auto resource = attachment.get_resource(); if (!resource) { return; } if (attachment.get_type() == AttachmentType::RENDERBUFFER) { set_renderbuffer(std::static_pointer_cast<Renderbuffer>(resource)); } else { set_texture(std::static_pointer_cast<Texture>(resource)); } }
#include "renderstate.hpp" #include "buffer.hpp" #include "framebuffer.hpp" #include "framebufferattachment.hpp" #include "graphicsdevice.hpp" #include "graphicssynchronizer.hpp" #include "program.hpp" #include "renderbuffer.hpp" #include "texture.hpp" #include "vertexarray.hpp" gst::RenderState::RenderState( std::shared_ptr<GraphicsDevice> device, std::shared_ptr<GraphicsSynchronizer> synchronizer) : device(device), synchronizer(synchronizer), clear_color(0.0f, 0.0f, 0.0f, 0.0f), blend_mode(BlendMode::NONE), cull_face(CullFace::NONE), depth_mask(true), depth_test(false) { device->set_clear_color(clear_color); device->set_blend_mode(blend_mode); device->set_cull_face(cull_face); device->set_depth_mask(depth_mask); device->set_depth_test(depth_test); device->bind_framebuffer(0); } void gst::RenderState::set_clear_color(Color const & clear_color) { if (this->clear_color != clear_color) { this->clear_color = clear_color; device->set_clear_color(clear_color); } } void gst::RenderState::set_blend_mode(BlendMode blend_mode) { if (this->blend_mode != blend_mode) { this->blend_mode = blend_mode; device->set_blend_mode(blend_mode); } } void gst::RenderState::set_cull_face(CullFace cull_face) { if (this->cull_face != cull_face) { this->cull_face = cull_face; device->set_cull_face(cull_face); } } void gst::RenderState::set_depth_mask(bool depth_mask) { if (this->depth_mask != depth_mask) { this->depth_mask = depth_mask; device->set_depth_mask(depth_mask); } } void gst::RenderState::set_depth_test(bool depth_test) { if (this->depth_test != depth_test) { this->depth_test = depth_test; device->set_depth_test(depth_test); } } void gst::RenderState::set_framebuffer(std::shared_ptr<Framebuffer> framebuffer) { if (this->framebuffer != framebuffer) { this->framebuffer = framebuffer; if (framebuffer) { synchronizer->bind(*framebuffer); } else { device->bind_framebuffer(0); } } if (framebuffer) { // keep attachments up-to-date set_framebuffer_attachment(framebuffer->get_color_attachment()); set_framebuffer_attachment(framebuffer->get_depth_attachment()); synchronizer->update(*framebuffer); } } void gst::RenderState::set_renderbuffer(std::shared_ptr<Renderbuffer> renderbuffer) { if (this->renderbuffer != renderbuffer) { this->renderbuffer = renderbuffer; synchronizer->bind(*renderbuffer); } synchronizer->update(*renderbuffer); } void gst::RenderState::set_program(std::shared_ptr<Program> program) { if (this->program != program) { this->program = program; synchronizer->bind(*program); } synchronizer->update(*program); } void gst::RenderState::set_texture(std::shared_ptr<Texture> texture, int unit) { auto current = textures.count(unit) > 0 ? textures.at(unit) : nullptr; if (current != texture) { textures[unit] = texture; synchronizer->bind(*texture, unit); } synchronizer->update(*texture); } void gst::RenderState::set_vertex_array(std::shared_ptr<VertexArray> vertex_array) { if (this->vertex_array != vertex_array) { this->vertex_array = vertex_array; synchronizer->bind(*vertex_array); } synchronizer->update(*vertex_array); } void gst::RenderState::set_viewport(Viewport const & viewport) { if (this->viewport != viewport) { this->viewport = viewport; device->set_viewport(viewport); } } void gst::RenderState::set_framebuffer_attachment(FramebufferAttachment const & attachment) { auto resource = attachment.get_resource(); if (!resource) { return; } if (attachment.get_type() == AttachmentType::RENDERBUFFER) { set_renderbuffer(std::static_pointer_cast<Renderbuffer>(resource)); } else { set_texture(std::static_pointer_cast<Texture>(resource)); } }
remove unneeded viewport update
remove unneeded viewport update
C++
mit
mharrys/gust,mharrys/gust,mharrys/gust
455e10b617402701fc13453778a86f37e7bf899c
bindings/python/mapnik_image.cpp
bindings/python/mapnik_image.cpp
/* This file is part of python_mapnik (c++/python mapping toolkit) * Copyright (C) 2005 Artem Pavlenko, Jean-Francois Doyon * * Mapnik 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 any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ //$Id$ #include <boost/python.hpp> #include <mapnik.hpp> using mapnik::Image32; char const* rawdata(const Image32& image) { return (char const* )image.raw_data(); } void export_image() { using namespace boost::python; class_<Image32>("Image","This class represents a 32 bit image.",init<int,int>()) ; def("rawdata",&rawdata); }
/* This file is part of python_mapnik (c++/python mapping toolkit) * Copyright (C) 2005 Artem Pavlenko, Jean-Francois Doyon * * Mapnik 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 any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ //$Id$ # include <boost/python.hpp> # include <boost/python/module.hpp> # include <boost/python/def.hpp> # include <mapnik.hpp> using mapnik::Image32; using namespace boost::python; PyObject* rawdata( Image32 const& im) { int size = im.width() * im.height() * 4; return ::PyString_FromStringAndSize((const char*)im.raw_data(),size); } void export_image() { using namespace boost::python; class_<Image32>("Image","This class represents a 32 bit image.",init<int,int>()) .def("width",&Image32::width) .def("height",&Image32::height) ; def("rawdata",&rawdata); }
fix rawdata() method to return PyString_FromStringAndSize
fix rawdata() method to return PyString_FromStringAndSize git-svn-id: 06a2cde72a096d93ff72b88e3e6711b8f00772a4@218 d397654b-2ff0-0310-9e29-ba003691a0f9
C++
lgpl-2.1
semprebon/mapnik,semprebon/mapnik,semprebon/mapnik,semprebon/mapnik,semprebon/mapnik
de569b365b8ab0451888a69df9c90a3ed798dcd9
jubatus/core/stat/stat_test.cpp
jubatus/core/stat/stat_test.cpp
// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2012 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 <gtest/gtest.h> #include <pficommon/math/random.h> #include "stat.hpp" namespace jubatus { template<typename T> class stat_test : public testing::Test { }; TYPED_TEST_CASE_P(stat_test); TYPED_TEST_P(stat_test, trivial) { TypeParam p(3); p.push("test", 1.0); p.push("test", 5.0); p.push("test", 3.0); EXPECT_TRUE(p.sum("test") == 9.0); EXPECT_TRUE(p.max("test") == 5.0); EXPECT_TRUE(p.min("test") == 1.0); EXPECT_NEAR(p.moment("test", 0 , 0.0) , 1.0, 0.1); EXPECT_NEAR(p.moment("test", 1 , 0.0) , 3.0, 0.1); EXPECT_NEAR(p.moment("test", 2 , 0.0) , 11.67, 0.1); EXPECT_NEAR(p.moment("test", 2 , 3.0) , 2.67, 0.1); EXPECT_NEAR(p.moment("test", 3 , 0.0) , 51.0, 0.1); EXPECT_NEAR(p.stddev("test"), 1.63, 0.01); p.push("test", 2.0); p.push("test", 4.0); EXPECT_TRUE(p.sum("test") == 9.0); EXPECT_TRUE(p.max("test") == 4.0); EXPECT_TRUE(p.min("test") == 2.0); EXPECT_NEAR(p.moment("test", 0 , 0.0) , 1.0, 0.1); EXPECT_NEAR(p.moment("test", 1 , 0.0) , 3.0, 0.1); EXPECT_NEAR(p.moment("test", 2 , 0.0) , 9.67, 0.1); EXPECT_NEAR(p.moment("test", 2 , 3.0) , 0.67, 0.1); EXPECT_NEAR(p.moment("test", 3 , 0.0) , 33.0, 0.1); EXPECT_NEAR(p.stddev("test"), 0.82, 0.1); p.clear(); p.push("test", 1.0); EXPECT_TRUE(p.sum("test") == 1.0); EXPECT_TRUE(p.max("test") == 1.0); EXPECT_TRUE(p.min("test") == 1.0); EXPECT_NEAR(p.moment("test", 0 , 0.0) , 1.0, 0.1); EXPECT_NEAR(p.moment("test", 1 , 0.0) , 1.0, 0.1); EXPECT_NEAR(p.moment("test", 2 , 0.0) , 1.0, 0.1); EXPECT_NEAR(p.moment("test", 2 , 3.0) , 4.0, 0.1); EXPECT_NEAR(p.moment("test", 3 , 0.0) , 1.0, 0.1); EXPECT_NEAR(p.stddev("test"), 0.0, 0.1); } REGISTER_TYPED_TEST_CASE_P( stat_test, trivial); typedef testing::Types<core::stat::stat> stat_types; INSTANTIATE_TYPED_TEST_CASE_P(stt, stat_test, stat_types); } // namespace jubatus
// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2012 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 <gtest/gtest.h> #include <pficommon/math/random.h> #include "stat.hpp" #include "mixable_stat.hpp" namespace jubatus { template<typename T> class stat_test : public testing::Test { }; TYPED_TEST_CASE_P(stat_test); TYPED_TEST_P(stat_test, trivial) { TypeParam p(3); p.push("test", 1.0); p.push("test", 5.0); p.push("test", 3.0); EXPECT_TRUE(p.sum("test") == 9.0); EXPECT_TRUE(p.max("test") == 5.0); EXPECT_TRUE(p.min("test") == 1.0); EXPECT_NEAR(p.moment("test", 0 , 0.0) , 1.0, 0.1); EXPECT_NEAR(p.moment("test", 1 , 0.0) , 3.0, 0.1); EXPECT_NEAR(p.moment("test", 2 , 0.0) , 11.67, 0.1); EXPECT_NEAR(p.moment("test", 2 , 3.0) , 2.67, 0.1); EXPECT_NEAR(p.moment("test", 3 , 0.0) , 51.0, 0.1); EXPECT_NEAR(p.stddev("test"), 1.63, 0.01); p.push("test", 2.0); p.push("test", 4.0); EXPECT_TRUE(p.sum("test") == 9.0); EXPECT_TRUE(p.max("test") == 4.0); EXPECT_TRUE(p.min("test") == 2.0); EXPECT_NEAR(p.moment("test", 0 , 0.0) , 1.0, 0.1); EXPECT_NEAR(p.moment("test", 1 , 0.0) , 3.0, 0.1); EXPECT_NEAR(p.moment("test", 2 , 0.0) , 9.67, 0.1); EXPECT_NEAR(p.moment("test", 2 , 3.0) , 0.67, 0.1); EXPECT_NEAR(p.moment("test", 3 , 0.0) , 33.0, 0.1); EXPECT_NEAR(p.stddev("test"), 0.82, 0.1); p.clear(); p.push("test", 1.0); EXPECT_TRUE(p.sum("test") == 1.0); EXPECT_TRUE(p.max("test") == 1.0); EXPECT_TRUE(p.min("test") == 1.0); EXPECT_NEAR(p.moment("test", 0 , 0.0) , 1.0, 0.1); EXPECT_NEAR(p.moment("test", 1 , 0.0) , 1.0, 0.1); EXPECT_NEAR(p.moment("test", 2 , 0.0) , 1.0, 0.1); EXPECT_NEAR(p.moment("test", 2 , 3.0) , 4.0, 0.1); EXPECT_NEAR(p.moment("test", 3 , 0.0) , 1.0, 0.1); EXPECT_NEAR(p.stddev("test"), 0.0, 0.1); } REGISTER_TYPED_TEST_CASE_P( stat_test, trivial); typedef testing::Types<core::stat::stat, core::stat::mixable_stat> stat_types; INSTANTIATE_TYPED_TEST_CASE_P(stt, stat_test, stat_types); } // namespace jubatus
Add mixable_stat test
Add mixable_stat test
C++
lgpl-2.1
rimms/jubatus,kumagi/jubatus_core,kmaehashi/jubatus_core,Asuka52/jubatus,rimms/jubatus_core,elkingtonmcb/jubatus,rimms/jubatus,gintenlabo/jubatus,gintenlabo/jubatus_core,gintenlabo/jubatus_core,kmaehashi/jubatus_core,Asuka52/jubatus,elkingtonmcb/jubatus,kmaehashi/jubatus_core,jubatus/jubatus,jubatus/jubatus,gintenlabo/jubatus_core,gintenlabo/jubatus,rimms/jubatus_core,mathn/jubatus,kmaehashi/jubatus,jubatus/jubatus,kumagi/jubatus_core,rimms/jubatus_core,mathn/jubatus,roselleebarle04/jubatus,kumagi/jubatus_core,roselleebarle04/jubatus,kmaehashi/jubatus_core,kumagi/jubatus_core,gintenlabo/jubatus_core,kmaehashi/jubatus,rimms/jubatus_core
08a48fec3953e27472b78fd4ac421f772e217a84
unittests/Support/FileCollectorTest.cpp
unittests/Support/FileCollectorTest.cpp
//===-- FileCollectorTest.cpp -----------------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "gmock/gmock.h" #include "gtest/gtest.h" #include "llvm/Support/FileCollector.h" #include "llvm/Support/FileSystem.h" using namespace llvm; namespace llvm { namespace vfs { inline bool operator==(const llvm::vfs::YAMLVFSEntry &LHS, const llvm::vfs::YAMLVFSEntry &RHS) { return LHS.VPath == RHS.VPath && LHS.RPath == RHS.RPath; } } // namespace vfs } // namespace llvm namespace { class TestingFileCollector : public FileCollector { public: using FileCollector::FileCollector; using FileCollector::Root; using FileCollector::Seen; using FileCollector::SymlinkMap; using FileCollector::VFSWriter; bool hasSeen(StringRef fs) { return Seen.find(fs) != Seen.end(); } }; struct ScopedDir { SmallString<128> Path; ScopedDir(const Twine &Name, bool Unique = false) { std::error_code EC; if (Unique) { EC = llvm::sys::fs::createUniqueDirectory(Name, Path); } else { Path = Name.str(); EC = llvm::sys::fs::create_directory(Twine(Path)); } if (EC) Path = ""; EXPECT_FALSE(EC); // Ensure the path is the real path so tests can use it to compare against // realpath output. SmallString<128> RealPath; if (!llvm::sys::fs::real_path(Path, RealPath)) Path.swap(RealPath); } ~ScopedDir() { if (Path != "") { EXPECT_FALSE(llvm::sys::fs::remove_directories(Path.str())); } } operator StringRef() { return Path.str(); } }; struct ScopedLink { SmallString<128> Path; ScopedLink(const Twine &To, const Twine &From) { Path = From.str(); std::error_code EC = sys::fs::create_link(To, From); if (EC) Path = ""; EXPECT_FALSE(EC); } ~ScopedLink() { if (Path != "") { EXPECT_FALSE(llvm::sys::fs::remove(Path.str())); } } operator StringRef() { return Path.str(); } }; struct ScopedFile { SmallString<128> Path; ScopedFile(const Twine &Name) { std::error_code EC; EC = llvm::sys::fs::createUniqueFile(Name, Path); if (EC) Path = ""; EXPECT_FALSE(EC); } ~ScopedFile() { if (Path != "") { EXPECT_FALSE(llvm::sys::fs::remove(Path.str())); } } operator StringRef() { return Path.str(); } }; } // end anonymous namespace TEST(FileCollectorTest, addFile) { ScopedDir root("add_file_root", true); std::string root_fs = root.Path.str(); TestingFileCollector FileCollector(root_fs, root_fs); FileCollector.addFile("/path/to/a"); FileCollector.addFile("/path/to/b"); FileCollector.addFile("/path/to/c"); // Make sure the root is correct. EXPECT_EQ(FileCollector.Root, root_fs); // Make sure we've seen all the added files. EXPECT_TRUE(FileCollector.hasSeen("/path/to/a")); EXPECT_TRUE(FileCollector.hasSeen("/path/to/b")); EXPECT_TRUE(FileCollector.hasSeen("/path/to/c")); // Make sure we've only seen the added files. EXPECT_FALSE(FileCollector.hasSeen("/path/to/d")); } TEST(FileCollectorTest, copyFiles) { ScopedDir file_root("file_root", true); ScopedFile a(file_root + "/aaa"); ScopedFile b(file_root + "/bbb"); ScopedFile c(file_root + "/ccc"); // Create file collector and add files. ScopedDir root("copy_files_root", true); std::string root_fs = root.Path.str(); TestingFileCollector FileCollector(root_fs, root_fs); FileCollector.addFile(a.Path); FileCollector.addFile(b.Path); FileCollector.addFile(c.Path); // Make sure we can copy the files. std::error_code ec = FileCollector.copyFiles(true); EXPECT_FALSE(ec); // Now add a bogus file and make sure we error out. FileCollector.addFile("/some/bogus/file"); ec = FileCollector.copyFiles(true); EXPECT_TRUE(ec); // However, if stop_on_error is true the copy should still succeed. ec = FileCollector.copyFiles(false); EXPECT_FALSE(ec); } TEST(FileCollectorTest, recordAndConstructDirectory) { ScopedDir file_root("dir_root", true); ScopedDir subdir(file_root + "/subdir"); ScopedDir subdir2(file_root + "/subdir2"); ScopedFile a(subdir2 + "/a"); // Create file collector and add files. ScopedDir root("copy_files_root", true); std::string root_fs = root.Path.str(); TestingFileCollector FileCollector(root_fs, root_fs); FileCollector.addFile(a.Path); // The empty directory isn't seen until we add it. EXPECT_TRUE(FileCollector.hasSeen(a.Path)); EXPECT_FALSE(FileCollector.hasSeen(subdir.Path)); FileCollector.addFile(subdir.Path); EXPECT_TRUE(FileCollector.hasSeen(subdir.Path)); // Make sure we can construct the directory. std::error_code ec = FileCollector.copyFiles(true); EXPECT_FALSE(ec); bool IsDirectory = false; llvm::SmallString<128> SubdirInRoot = root.Path; llvm::sys::path::append(SubdirInRoot, llvm::sys::path::relative_path(subdir.Path)); ec = sys::fs::is_directory(SubdirInRoot, IsDirectory); EXPECT_FALSE(ec); ASSERT_TRUE(IsDirectory); } TEST(FileCollectorTest, recordVFSAccesses) { ScopedDir file_root("dir_root", true); ScopedDir subdir(file_root + "/subdir"); ScopedDir subdir2(file_root + "/subdir2"); ScopedFile a(subdir2 + "/a"); ScopedFile b(file_root + "/b"); ScopedDir subdir3(file_root + "/subdir3"); ScopedFile subdir3a(subdir3 + "/aa"); ScopedDir subdir3b(subdir3 + "/subdirb"); { ScopedFile subdir3fileremoved(subdir3 + "/removed"); } // Create file collector and add files. ScopedDir root("copy_files_root", true); std::string root_fs = root.Path.str(); auto Collector = std::make_shared<TestingFileCollector>(root_fs, root_fs); auto VFS = FileCollector::createCollectorVFS(vfs::getRealFileSystem(), Collector); VFS->status(a.Path); EXPECT_TRUE(Collector->hasSeen(a.Path)); VFS->openFileForRead(b.Path); EXPECT_TRUE(Collector->hasSeen(b.Path)); VFS->status(subdir.Path); EXPECT_TRUE(Collector->hasSeen(subdir.Path)); std::error_code EC; auto It = VFS->dir_begin(subdir3.Path, EC); EXPECT_FALSE(EC); EXPECT_TRUE(Collector->hasSeen(subdir3.Path)); EXPECT_TRUE(Collector->hasSeen(subdir3a.Path)); EXPECT_TRUE(Collector->hasSeen(subdir3b.Path)); std::string RemovedFileName = (Twine(subdir3.Path) + "/removed").str(); EXPECT_FALSE(Collector->hasSeen(RemovedFileName)); } #ifndef _WIN32 TEST(FileCollectorTest, Symlinks) { // Root where the original files live. ScopedDir file_root("file_root", true); // Create some files in the file root. ScopedFile a(file_root + "/aaa"); ScopedFile b(file_root + "/bbb"); ScopedFile c(file_root + "/ccc"); // Create a directory foo with file ddd. ScopedDir foo(file_root + "/foo"); ScopedFile d(foo + "/ddd"); // Create a file eee in the foo's parent directory. ScopedFile e(foo + "/../eee"); // Create a symlink bar pointing to foo. ScopedLink symlink(file_root + "/foo", file_root + "/bar"); // Root where files are copied to. ScopedDir reproducer_root("reproducer_root", true); std::string root_fs = reproducer_root.Path.str(); TestingFileCollector FileCollector(root_fs, root_fs); // Add all the files to the collector. FileCollector.addFile(a.Path); FileCollector.addFile(b.Path); FileCollector.addFile(c.Path); FileCollector.addFile(d.Path); FileCollector.addFile(e.Path); FileCollector.addFile(file_root + "/bar/ddd"); auto mapping = FileCollector.VFSWriter.getMappings(); { // Make sure the common case works. std::string vpath = (file_root + "/aaa").str(); std::string rpath = (reproducer_root.Path + file_root.Path + "/aaa").str(); printf("%s -> %s\n", vpath.c_str(), rpath.c_str()); EXPECT_THAT(mapping, testing::Contains(vfs::YAMLVFSEntry(vpath, rpath))); } { // Make sure the virtual path points to the real source path. std::string vpath = (file_root + "/bar/ddd").str(); std::string rpath = (reproducer_root.Path + file_root.Path + "/foo/ddd").str(); printf("%s -> %s\n", vpath.c_str(), rpath.c_str()); EXPECT_THAT(mapping, testing::Contains(vfs::YAMLVFSEntry(vpath, rpath))); } { // Make sure that .. is removed from the source path. std::string vpath = (file_root + "/eee").str(); std::string rpath = (reproducer_root.Path + file_root.Path + "/eee").str(); printf("%s -> %s\n", vpath.c_str(), rpath.c_str()); EXPECT_THAT(mapping, testing::Contains(vfs::YAMLVFSEntry(vpath, rpath))); } } TEST(FileCollectorTest, recordVFSSymlinkAccesses) { ScopedDir file_root("dir_root", true); ScopedFile a(file_root + "/a"); ScopedLink symlink(file_root + "/a", file_root + "/b"); // Create file collector and add files. ScopedDir root("copy_files_root", true); std::string root_fs = root.Path.str(); auto Collector = std::make_shared<TestingFileCollector>(root_fs, root_fs); auto VFS = FileCollector::createCollectorVFS(vfs::getRealFileSystem(), Collector); SmallString<256> Output; VFS->getRealPath(symlink.Path, Output); EXPECT_TRUE(Collector->hasSeen(a.Path)); EXPECT_TRUE(Collector->hasSeen(symlink.Path)); } #endif
//===-- FileCollectorTest.cpp -----------------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "gmock/gmock.h" #include "gtest/gtest.h" #include "llvm/Support/FileCollector.h" #include "llvm/Support/FileSystem.h" using namespace llvm; namespace llvm { namespace vfs { inline bool operator==(const llvm::vfs::YAMLVFSEntry &LHS, const llvm::vfs::YAMLVFSEntry &RHS) { return LHS.VPath == RHS.VPath && LHS.RPath == RHS.RPath; } } // namespace vfs } // namespace llvm namespace { class TestingFileCollector : public FileCollector { public: using FileCollector::FileCollector; using FileCollector::Root; using FileCollector::Seen; using FileCollector::SymlinkMap; using FileCollector::VFSWriter; bool hasSeen(StringRef fs) { return Seen.find(fs) != Seen.end(); } }; struct ScopedDir { SmallString<128> Path; ScopedDir(const Twine &Name, bool Unique = false) { std::error_code EC; if (Unique) { EC = llvm::sys::fs::createUniqueDirectory(Name, Path); } else { Path = Name.str(); EC = llvm::sys::fs::create_directory(Twine(Path)); } if (EC) Path = ""; EXPECT_FALSE(EC); // Ensure the path is the real path so tests can use it to compare against // realpath output. SmallString<128> RealPath; if (!llvm::sys::fs::real_path(Path, RealPath)) Path.swap(RealPath); } ~ScopedDir() { if (Path != "") { EXPECT_FALSE(llvm::sys::fs::remove_directories(Path.str())); } } operator StringRef() { return Path.str(); } }; struct ScopedLink { SmallString<128> Path; ScopedLink(const Twine &To, const Twine &From) { Path = From.str(); std::error_code EC = sys::fs::create_link(To, From); if (EC) Path = ""; EXPECT_FALSE(EC); } ~ScopedLink() { if (Path != "") { EXPECT_FALSE(llvm::sys::fs::remove(Path.str())); } } operator StringRef() { return Path.str(); } }; struct ScopedFile { SmallString<128> Path; ScopedFile(const Twine &Name) { std::error_code EC; EC = llvm::sys::fs::createUniqueFile(Name, Path); if (EC) Path = ""; EXPECT_FALSE(EC); } ~ScopedFile() { if (Path != "") { EXPECT_FALSE(llvm::sys::fs::remove(Path.str())); } } operator StringRef() { return Path.str(); } }; } // end anonymous namespace TEST(FileCollectorTest, addFile) { ScopedDir root("add_file_root", true); std::string root_fs = root.Path.str(); TestingFileCollector FileCollector(root_fs, root_fs); FileCollector.addFile("/path/to/a"); FileCollector.addFile("/path/to/b"); FileCollector.addFile("/path/to/c"); // Make sure the root is correct. EXPECT_EQ(FileCollector.Root, root_fs); // Make sure we've seen all the added files. EXPECT_TRUE(FileCollector.hasSeen("/path/to/a")); EXPECT_TRUE(FileCollector.hasSeen("/path/to/b")); EXPECT_TRUE(FileCollector.hasSeen("/path/to/c")); // Make sure we've only seen the added files. EXPECT_FALSE(FileCollector.hasSeen("/path/to/d")); } TEST(FileCollectorTest, copyFiles) { ScopedDir file_root("file_root", true); ScopedFile a(file_root + "/aaa"); ScopedFile b(file_root + "/bbb"); ScopedFile c(file_root + "/ccc"); // Create file collector and add files. ScopedDir root("copy_files_root", true); std::string root_fs = root.Path.str(); TestingFileCollector FileCollector(root_fs, root_fs); FileCollector.addFile(a.Path); FileCollector.addFile(b.Path); FileCollector.addFile(c.Path); // Make sure we can copy the files. std::error_code ec = FileCollector.copyFiles(true); EXPECT_FALSE(ec); // Now add a bogus file and make sure we error out. FileCollector.addFile("/some/bogus/file"); ec = FileCollector.copyFiles(true); EXPECT_TRUE(ec); // However, if stop_on_error is true the copy should still succeed. ec = FileCollector.copyFiles(false); EXPECT_FALSE(ec); } TEST(FileCollectorTest, recordAndConstructDirectory) { ScopedDir file_root("dir_root", true); ScopedDir subdir(file_root + "/subdir"); ScopedDir subdir2(file_root + "/subdir2"); ScopedFile a(subdir2 + "/a"); // Create file collector and add files. ScopedDir root("copy_files_root", true); std::string root_fs = root.Path.str(); TestingFileCollector FileCollector(root_fs, root_fs); FileCollector.addFile(a.Path); // The empty directory isn't seen until we add it. EXPECT_TRUE(FileCollector.hasSeen(a.Path)); EXPECT_FALSE(FileCollector.hasSeen(subdir.Path)); FileCollector.addFile(subdir.Path); EXPECT_TRUE(FileCollector.hasSeen(subdir.Path)); // Make sure we can construct the directory. std::error_code ec = FileCollector.copyFiles(true); EXPECT_FALSE(ec); bool IsDirectory = false; llvm::SmallString<128> SubdirInRoot = root.Path; llvm::sys::path::append(SubdirInRoot, llvm::sys::path::relative_path(subdir.Path)); ec = sys::fs::is_directory(SubdirInRoot, IsDirectory); EXPECT_FALSE(ec); ASSERT_TRUE(IsDirectory); } TEST(FileCollectorTest, recordVFSAccesses) { ScopedDir file_root("dir_root", true); ScopedDir subdir(file_root + "/subdir"); ScopedDir subdir2(file_root + "/subdir2"); ScopedFile a(subdir2 + "/a"); ScopedFile b(file_root + "/b"); ScopedDir subdir3(file_root + "/subdir3"); ScopedFile subdir3a(subdir3 + "/aa"); ScopedDir subdir3b(subdir3 + "/subdirb"); { ScopedFile subdir3fileremoved(subdir3 + "/removed"); } // Create file collector and add files. ScopedDir root("copy_files_root", true); std::string root_fs = root.Path.str(); auto Collector = std::make_shared<TestingFileCollector>(root_fs, root_fs); auto VFS = FileCollector::createCollectorVFS(vfs::getRealFileSystem(), Collector); VFS->status(a.Path); EXPECT_TRUE(Collector->hasSeen(a.Path)); VFS->openFileForRead(b.Path); EXPECT_TRUE(Collector->hasSeen(b.Path)); VFS->status(subdir.Path); EXPECT_TRUE(Collector->hasSeen(subdir.Path)); #ifndef _WIN32 std::error_code EC; auto It = VFS->dir_begin(subdir3.Path, EC); EXPECT_FALSE(EC); EXPECT_TRUE(Collector->hasSeen(subdir3.Path)); EXPECT_TRUE(Collector->hasSeen(subdir3a.Path)); EXPECT_TRUE(Collector->hasSeen(subdir3b.Path)); std::string RemovedFileName = (Twine(subdir3.Path) + "/removed").str(); EXPECT_FALSE(Collector->hasSeen(RemovedFileName)); #endif } #ifndef _WIN32 TEST(FileCollectorTest, Symlinks) { // Root where the original files live. ScopedDir file_root("file_root", true); // Create some files in the file root. ScopedFile a(file_root + "/aaa"); ScopedFile b(file_root + "/bbb"); ScopedFile c(file_root + "/ccc"); // Create a directory foo with file ddd. ScopedDir foo(file_root + "/foo"); ScopedFile d(foo + "/ddd"); // Create a file eee in the foo's parent directory. ScopedFile e(foo + "/../eee"); // Create a symlink bar pointing to foo. ScopedLink symlink(file_root + "/foo", file_root + "/bar"); // Root where files are copied to. ScopedDir reproducer_root("reproducer_root", true); std::string root_fs = reproducer_root.Path.str(); TestingFileCollector FileCollector(root_fs, root_fs); // Add all the files to the collector. FileCollector.addFile(a.Path); FileCollector.addFile(b.Path); FileCollector.addFile(c.Path); FileCollector.addFile(d.Path); FileCollector.addFile(e.Path); FileCollector.addFile(file_root + "/bar/ddd"); auto mapping = FileCollector.VFSWriter.getMappings(); { // Make sure the common case works. std::string vpath = (file_root + "/aaa").str(); std::string rpath = (reproducer_root.Path + file_root.Path + "/aaa").str(); printf("%s -> %s\n", vpath.c_str(), rpath.c_str()); EXPECT_THAT(mapping, testing::Contains(vfs::YAMLVFSEntry(vpath, rpath))); } { // Make sure the virtual path points to the real source path. std::string vpath = (file_root + "/bar/ddd").str(); std::string rpath = (reproducer_root.Path + file_root.Path + "/foo/ddd").str(); printf("%s -> %s\n", vpath.c_str(), rpath.c_str()); EXPECT_THAT(mapping, testing::Contains(vfs::YAMLVFSEntry(vpath, rpath))); } { // Make sure that .. is removed from the source path. std::string vpath = (file_root + "/eee").str(); std::string rpath = (reproducer_root.Path + file_root.Path + "/eee").str(); printf("%s -> %s\n", vpath.c_str(), rpath.c_str()); EXPECT_THAT(mapping, testing::Contains(vfs::YAMLVFSEntry(vpath, rpath))); } } TEST(FileCollectorTest, recordVFSSymlinkAccesses) { ScopedDir file_root("dir_root", true); ScopedFile a(file_root + "/a"); ScopedLink symlink(file_root + "/a", file_root + "/b"); // Create file collector and add files. ScopedDir root("copy_files_root", true); std::string root_fs = root.Path.str(); auto Collector = std::make_shared<TestingFileCollector>(root_fs, root_fs); auto VFS = FileCollector::createCollectorVFS(vfs::getRealFileSystem(), Collector); SmallString<256> Output; VFS->getRealPath(symlink.Path, Output); EXPECT_TRUE(Collector->hasSeen(a.Path)); EXPECT_TRUE(Collector->hasSeen(symlink.Path)); } #endif
disable the directory entry collection checks on windows
[FileCollector] test: disable the directory entry collection checks on windows Looks like one of the entries isn't found on windows. I'm investigating why. In the meantime, I'll disable this part of the test on windows. git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@367280 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm
16337168448c1f1bdf8fec9f2f7df6ff3adec9d5
kfile-plugins/ics/kfile_ics.cpp
kfile-plugins/ics/kfile_ics.cpp
/* This file is part of the KDE project * Copyright (C) 2004 Bram Schoenmakers <[email protected]> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation version 2. * * This program is distributed in the hope that t it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * */ #include <qdatetime.h> #include <qfile.h> #include <libkcal/calendarlocal.h> #include <libkcal/todo.h> #include "kfile_ics.h" #include <kgenericfactory.h> using namespace KCal; typedef KGenericFactory<ICSPlugin> ICSFactory; K_EXPORT_COMPONENT_FACTORY(kfile_ics, ICSFactory( "kfile_ics" )) ICSPlugin::ICSPlugin( QObject *parent, const char *name, const QStringList& args ) : KFilePlugin( parent, name, args ) { KFileMimeTypeInfo* info = addMimeTypeInfo( "text/calendar" ); //TODO: vcs !! KFileMimeTypeInfo::GroupInfo* group = 0L; group = addGroupInfo(info, "ICSInfo", i18n("Calendar Statistics")); addItemInfo( group, "ProductID", i18n("Product ID"), QVariant::String ); addItemInfo( group, "Events", i18n("Events"), QVariant::Int ); addItemInfo( group, "Todos", i18n("To-Dos"), QVariant::Int ); addItemInfo( group, "TodoCompleted", i18n("Completed To-Dos"), QVariant::Int ); addItemInfo( group, "TodoOverdue", i18n("Overdue To-Dos"), QVariant::Int ); addItemInfo( group, "Journals", i18n("Journals"), QVariant::Int ); // addItemInfo( group, "Reminders", i18n("Reminders"), QVariant::Int ); } /* I chose to use libkcal instead of reading the calendar manually. It's easier to maintain this way. */ bool ICSPlugin::readInfo( KFileMetaInfo& info, uint /*what*/ ) { KFileMetaInfoGroup group = appendGroup( info, "ICSInfo"); CalendarLocal cal; if( !cal.load( info.path() ) ) { kdDebug() << "Could not load calendar" << endl; return false; } appendItem( group, "ProductID", QVariant( cal.loadedProductId() ) ); appendItem( group, "Events", QVariant( int( cal.events().count() ) ) ); appendItem( group, "Journals", QVariant( int( cal.journals().count() ) ) ); Todo::List todos = cal.todos(); // count completed and overdue Todo::List::ConstIterator it = todos.begin(); Todo::List::ConstIterator end = todos.end(); int completed = 0; int overdue = 0; for ( ; it != end ; ++it ) { Todo *todo = *it; if ( todo->isCompleted() ) ++completed; else if ( todo->hasDueDate() && todo->dtDue().date() < QDate::currentDate() ) ++overdue; } appendItem( group, "Todos", QVariant( int(todos.count() ) ) ); appendItem( group, "TodoCompleted", QVariant( completed ) ); appendItem( group, "TodoOverdue", QVariant( overdue ) ); cal.close(); return true; } #include "kfile_ics.moc"
/* This file is part of the KDE project * Copyright (C) 2004 Bram Schoenmakers <[email protected]> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation version 2. * * This program is distributed in the hope that t it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * */ #include <qdatetime.h> #include <qfile.h> #include <libkcal/calendarlocal.h> #include <libkcal/todo.h> #include "kfile_ics.h" #include <kgenericfactory.h> using namespace KCal; typedef KGenericFactory<ICSPlugin> ICSFactory; K_EXPORT_COMPONENT_FACTORY(kfile_ics, ICSFactory( "kfile_ics" )) ICSPlugin::ICSPlugin( QObject *parent, const char *name, const QStringList& args ) : KFilePlugin( parent, name, args ) { KFileMimeTypeInfo* info = addMimeTypeInfo( "text/calendar" ); //TODO: vcs !! KFileMimeTypeInfo::GroupInfo* group = 0L; group = addGroupInfo(info, "ICSInfo", i18n("Calendar Statistics")); addItemInfo( group, "ProductID", i18n("Product ID"), QVariant::String ); addItemInfo( group, "Events", i18n("Events"), QVariant::Int ); addItemInfo( group, "Todos", i18n("To-dos"), QVariant::Int ); addItemInfo( group, "TodoCompleted", i18n("Completed To-dos"), QVariant::Int ); addItemInfo( group, "TodoOverdue", i18n("Overdue To-dos"), QVariant::Int ); addItemInfo( group, "Journals", i18n("Journals"), QVariant::Int ); // addItemInfo( group, "Reminders", i18n("Reminders"), QVariant::Int ); } /* I chose to use libkcal instead of reading the calendar manually. It's easier to maintain this way. */ bool ICSPlugin::readInfo( KFileMetaInfo& info, uint /*what*/ ) { KFileMetaInfoGroup group = appendGroup( info, "ICSInfo"); CalendarLocal cal; if( !cal.load( info.path() ) ) { kdDebug() << "Could not load calendar" << endl; return false; } appendItem( group, "ProductID", QVariant( cal.loadedProductId() ) ); appendItem( group, "Events", QVariant( int( cal.events().count() ) ) ); appendItem( group, "Journals", QVariant( int( cal.journals().count() ) ) ); Todo::List todos = cal.todos(); // count completed and overdue Todo::List::ConstIterator it = todos.begin(); Todo::List::ConstIterator end = todos.end(); int completed = 0; int overdue = 0; for ( ; it != end ; ++it ) { Todo *todo = *it; if ( todo->isCompleted() ) ++completed; else if ( todo->hasDueDate() && todo->dtDue().date() < QDate::currentDate() ) ++overdue; } appendItem( group, "Todos", QVariant( int(todos.count() ) ) ); appendItem( group, "TodoCompleted", QVariant( completed ) ); appendItem( group, "TodoOverdue", QVariant( overdue ) ); cal.close(); return true; } #include "kfile_ics.moc"
Correct capitalization for To-do
Correct capitalization for To-do svn path=/trunk/kdepim/; revision=344995
C++
lgpl-2.1
lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi
5ead340ec2917f22b7a6d2dbd5b8b149852e94dd
test/std/experimental/language.support/support.coroutines/end.to.end/fullexpr-dtor.pass.cpp
test/std/experimental/language.support/support.coroutines/end.to.end/fullexpr-dtor.pass.cpp
// -*- C++ -*- //===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++98, c++03, c++11 #include <experimental/coroutine> #include <cassert> #include "test_macros.h" using namespace std::experimental; int alive = 0; int ctor_called = 0; int dtor_called = 0; void reset() { assert(alive == 0); alive = 0; ctor_called = 0; dtor_called = 0; } struct Noisy { Noisy() { ++alive; ++ctor_called; } ~Noisy() { --alive; ++dtor_called; } #if TEST_STD_VER > 14 Noisy(Noisy const&) = delete; #else // FIXME: This test depends on copy elision taking place in C++14 // (pre-c++17 guaranteed copy elision) Noisy(Noisy const&); #endif }; struct Bug { bool await_ready() { return true; } void await_suspend(std::experimental::coroutine_handle<>) {} Noisy await_resume() { return {}; } }; struct coro2 { struct promise_type { suspend_never initial_suspend() { return{}; } suspend_never final_suspend() { return{}; } coro2 get_return_object() { return{}; } void return_void() {} Bug yield_value(int) { return {}; } void unhandled_exception() {} }; }; // Checks that destructors are correctly invoked for the object returned by // coawait. coro2 a() { reset(); { auto x = co_await Bug{}; assert(alive == 1); assert(ctor_called == 1); assert(dtor_called == 0); ((void)x); } assert(alive == 0); assert(dtor_called == 1); } coro2 b() { reset(); { auto x = co_await Bug{}; ((void)x); assert(ctor_called == 1); assert(dtor_called == 1); assert(alive == 0); } assert(ctor_called == 1); assert(dtor_called == 1); assert(alive == 0); } coro2 c() { reset(); { auto x = co_yield 42; assert(alive == 1); assert(ctor_called == 1); assert(dtor_called == 0); } assert(alive == 0); assert(ctor_called == 1); assert(dtor_called == 1); } coro2 d() { reset(); { auto x = co_yield 42; ((void)x); assert(ctor_called == 1); assert(dtor_called == 1); assert(alive == 0); } assert(alive == 0); assert(ctor_called == 1); assert(dtor_called == 1); } int main() { a(); b(); c(); d(); }
// -*- C++ -*- //===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++98, c++03, c++11 #include <experimental/coroutine> #include <cassert> #include "test_macros.h" using namespace std::experimental; int alive = 0; int ctor_called = 0; int dtor_called = 0; void reset() { assert(alive == 0); alive = 0; ctor_called = 0; dtor_called = 0; } struct Noisy { Noisy() { ++alive; ++ctor_called; } ~Noisy() { --alive; ++dtor_called; } #if TEST_STD_VER > 14 Noisy(Noisy const&) = delete; #else // FIXME: This test depends on copy elision taking place in C++14 // (pre-c++17 guaranteed copy elision) Noisy(Noisy const&); #endif }; struct Bug { bool await_ready() { return true; } void await_suspend(std::experimental::coroutine_handle<>) {} Noisy await_resume() { return {}; } }; struct coro2 { struct promise_type { suspend_never initial_suspend() { return{}; } suspend_never final_suspend() { return{}; } coro2 get_return_object() { return{}; } void return_void() {} Bug yield_value(int) { return {}; } void unhandled_exception() {} }; }; // Checks that destructors are correctly invoked for the object returned by // coawait. coro2 a() { reset(); { auto x = co_await Bug{}; assert(alive == 1); assert(ctor_called == 1); assert(dtor_called == 0); ((void)x); } assert(alive == 0); assert(dtor_called == 1); } coro2 b() { reset(); { (void)(co_await Bug{}); assert(ctor_called == 1); assert(dtor_called == 1); assert(alive == 0); } assert(ctor_called == 1); assert(dtor_called == 1); assert(alive == 0); } coro2 c() { reset(); { auto x = co_yield 42; assert(alive == 1); assert(ctor_called == 1); assert(dtor_called == 0); } assert(alive == 0); assert(ctor_called == 1); assert(dtor_called == 1); } coro2 d() { reset(); { (void)(co_yield 42); assert(ctor_called == 1); assert(dtor_called == 1); assert(alive == 0); } assert(alive == 0); assert(ctor_called == 1); assert(dtor_called == 1); } int main() { a(); b(); c(); d(); }
Fix silly mistakes in recent changes made to coroutine test
Fix silly mistakes in recent changes made to coroutine test git-svn-id: 756ef344af921d95d562d9e9f9389127a89a6314@304364 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/libcxx,llvm-mirror/libcxx,llvm-mirror/libcxx,llvm-mirror/libcxx,llvm-mirror/libcxx
2cb4433c15c5caa029450255caeb35e6b893c4da
include/metaverse/bitcoin/chain/attachment/asset/asset_transfer.hpp
include/metaverse/bitcoin/chain/attachment/asset/asset_transfer.hpp
/** * Copyright (c) 2011-2015 metaverse developers (see AUTHORS) * * This file is part of mvs-node. * * metaverse is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef MVS_CHAIN_ATTACHMENT_ASSET_TRANSFER_HPP #define MVS_CHAIN_ATTACHMENT_ASSET_TRANSFER_HPP #include <cstdint> #include <istream> #include <vector> #include <metaverse/bitcoin/chain/point.hpp> #include <metaverse/bitcoin/chain/script/script.hpp> #include <metaverse/bitcoin/define.hpp> #include <metaverse/bitcoin/utility/reader.hpp> #include <metaverse/bitcoin/utility/writer.hpp> #include <metaverse/bitcoin/chain/history.hpp> namespace libbitcoin { namespace chain { BC_CONSTEXPR size_t ASSET_TRANSFER_SYMBOL_FIX_SIZE = 64; BC_CONSTEXPR size_t ASSET_TRANSFER_QUANTITY_FIX_SIZE = 8; BC_CONSTEXPR size_t ASSET_TRANSFER_FIX_SIZE = ASSET_TRANSFER_SYMBOL_FIX_SIZE + ASSET_TRANSFER_QUANTITY_FIX_SIZE; struct asset_balances { typedef std::vector<asset_balances> list; std::string symbol; std::string address; uint64_t unspent_asset; uint64_t locked_asset; // for sort bool operator< (const asset_balances& other) const { auto ret = symbol.compare(other.symbol); if (ret < 0) { return true; } else if (ret == 0) { ret = address.compare(other.address); if (ret < 0) { return true; } else if (ret == 0) { ret = unspent_asset - other.unspent_asset; if (ret < 0) { return true; } else if (ret == 0) { return locked_asset <= other.locked_asset; } } } return false; } }; class BC_API asset_transfer { public: asset_transfer(); asset_transfer(const std::string& symbol, uint64_t quantity); static asset_transfer factory_from_data(const data_chunk& data); static asset_transfer factory_from_data(std::istream& stream); static asset_transfer factory_from_data(reader& source); static uint64_t satoshi_fixed_size(); bool from_data(const data_chunk& data); bool from_data(std::istream& stream); bool from_data(reader& source); data_chunk to_data() const; void to_data(std::ostream& stream) const; void to_data(writer& sink) const; std::string to_string() const; bool is_valid() const; void reset(); uint64_t serialized_size() const; const std::string& get_symbol() const; void set_symbol(const std::string& symbol); uint64_t get_quantity() const; void set_quantity(uint64_t quantity); private: std::string symbol; // symbol -- in block uint64_t quantity; // -- in block }; } // namespace chain } // namespace libbitcoin #endif
/** * Copyright (c) 2011-2015 metaverse developers (see AUTHORS) * * This file is part of mvs-node. * * metaverse is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef MVS_CHAIN_ATTACHMENT_ASSET_TRANSFER_HPP #define MVS_CHAIN_ATTACHMENT_ASSET_TRANSFER_HPP #include <cstdint> #include <istream> #include <vector> #include <metaverse/bitcoin/chain/point.hpp> #include <metaverse/bitcoin/chain/script/script.hpp> #include <metaverse/bitcoin/define.hpp> #include <metaverse/bitcoin/utility/reader.hpp> #include <metaverse/bitcoin/utility/writer.hpp> #include <metaverse/bitcoin/chain/history.hpp> namespace libbitcoin { namespace chain { BC_CONSTEXPR size_t ASSET_TRANSFER_SYMBOL_FIX_SIZE = 64; BC_CONSTEXPR size_t ASSET_TRANSFER_QUANTITY_FIX_SIZE = 8; BC_CONSTEXPR size_t ASSET_TRANSFER_FIX_SIZE = ASSET_TRANSFER_SYMBOL_FIX_SIZE + ASSET_TRANSFER_QUANTITY_FIX_SIZE; struct asset_balances { typedef std::vector<asset_balances> list; std::string symbol; std::string address; uint64_t unspent_asset; uint64_t locked_asset; // for sort bool operator< (const asset_balances& other) const { auto ret = symbol.compare(other.symbol); if (ret < 0) { return true; } else if (ret == 0) { ret = address.compare(other.address); if (ret < 0) { return true; } else if (ret == 0) { ret = unspent_asset - other.unspent_asset; if (ret < 0) { return true; } else if (ret == 0) { return locked_asset < other.locked_asset; } } } return false; } }; class BC_API asset_transfer { public: asset_transfer(); asset_transfer(const std::string& symbol, uint64_t quantity); static asset_transfer factory_from_data(const data_chunk& data); static asset_transfer factory_from_data(std::istream& stream); static asset_transfer factory_from_data(reader& source); static uint64_t satoshi_fixed_size(); bool from_data(const data_chunk& data); bool from_data(std::istream& stream); bool from_data(reader& source); data_chunk to_data() const; void to_data(std::ostream& stream) const; void to_data(writer& sink) const; std::string to_string() const; bool is_valid() const; void reset(); uint64_t serialized_size() const; const std::string& get_symbol() const; void set_symbol(const std::string& symbol); uint64_t get_quantity() const; void set_quantity(uint64_t quantity); private: std::string symbol; // symbol -- in block uint64_t quantity; // -- in block }; } // namespace chain } // namespace libbitcoin #endif
fix sort bug
fix sort bug
C++
agpl-3.0
mvs-live/metaverse,the-metaverse/metaverse,mvs-org/metaverse,the-metaverse/metaverse,mvs-live/metaverse,mvs-org/metaverse,mvs-org/metaverse,mvs-org/metaverse,the-metaverse/metaverse,mvs-org/metaverse,mvs-org/metaverse
3aa6598b9bbcc19e6c05067149e904a121d1c384
dune/gdt/localoperator/codim0.hh
dune/gdt/localoperator/codim0.hh
// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_LOCALOPERATOR_INTEGRAL_HH #define DUNE_GDT_LOCALOPERATOR_INTEGRAL_HH #include <vector> #include <utility> #include <type_traits> #include <limits> #include <dune/stuff/common/disable_warnings.hh> # include <dune/common/densematrix.hh> #include <dune/stuff/common/reenable_warnings.hh> #include <dune/stuff/common/disable_warnings.hh> # include <dune/geometry/quadraturerules.hh> #include <dune/stuff/common/reenable_warnings.hh> #include <dune/stuff/functions/interfaces.hh> #include "../localevaluation/interface.hh" #include "interface.hh" namespace Dune { namespace GDT { namespace LocalOperator { // forward, to be used in the traits template< class BinaryEvaluationImp > class Codim0Integral; template< class BinaryEvaluationImp > class Codim0IntegralTraits { static_assert(std::is_base_of< LocalEvaluation::Codim0Interface< typename BinaryEvaluationImp::Traits, 2 >, BinaryEvaluationImp >::value, "BinaryEvaluationImp has to be derived from LocalEvaluation::Codim0Interface< ..., 2 >!"); public: typedef Codim0Integral< BinaryEvaluationImp > derived_type; typedef LocalEvaluation::Codim0Interface< typename BinaryEvaluationImp::Traits, 2 > BinaryEvaluationType; }; template< class BinaryEvaluationImp > class Codim0Integral : public LocalOperator::Codim0Interface< Codim0IntegralTraits< BinaryEvaluationImp > > { public: typedef Codim0IntegralTraits< BinaryEvaluationImp > Traits; typedef typename Traits::BinaryEvaluationType BinaryEvaluationType; private: static const size_t numTmpObjectsRequired_ = 1; public: Codim0Integral(const BinaryEvaluationImp eval, const size_t over_integrate = 0) : evaluation_(eval) , over_integrate_(over_integrate) {} Codim0Integral(const size_t over_integrate, const BinaryEvaluationImp eval) : evaluation_(eval) , over_integrate_(over_integrate) {} template< class... Args > explicit Codim0Integral(Args&& ...args) : evaluation_(std::forward< Args >(args)...) , over_integrate_(0) {} template< class... Args > Codim0Integral(const int over_integrate, Args&& ...args) : evaluation_(std::forward< Args >(args)...) , over_integrate_(over_integrate) {} template< class... Args > Codim0Integral(const size_t over_integrate, Args&& ...args) : evaluation_(std::forward< Args >(args)...) , over_integrate_(over_integrate) {} const BinaryEvaluationType& inducingEvaluation() const { return evaluation_; } size_t numTmpObjectsRequired() const { return numTmpObjectsRequired_; } template< class E, class D, int d, class R, int rT, int rCT, int rA, int rCA > void apply(const Stuff::LocalfunctionSetInterface< E, D, d, R, rT, rCT >& testBase, const Stuff::LocalfunctionSetInterface< E, D, d, R, rA, rCA >& ansatzBase, Dune::DynamicMatrix< R >& ret, std::vector< Dune::DynamicMatrix< R > >& tmpLocalMatrices) const { const auto& entity = ansatzBase.entity(); const auto localFunctions = evaluation_.localFunctions(entity); // quadrature typedef Dune::QuadratureRules< D, d > VolumeQuadratureRules; typedef Dune::QuadratureRule< D, d > VolumeQuadratureType; const size_t integrand_order = evaluation().order(localFunctions, ansatzBase, testBase) + over_integrate_; assert(integrand_order < std::numeric_limits< int >::max()); const VolumeQuadratureType& volumeQuadrature = VolumeQuadratureRules::rule(entity.type(), int(integrand_order)); // check matrix and tmp storage const size_t rows = testBase.size(); const size_t cols = ansatzBase.size(); ret *= 0.0; assert(ret.rows() >= rows); assert(ret.cols() >= cols); assert(tmpLocalMatrices.size() >= numTmpObjectsRequired_); auto& evaluationResult = tmpLocalMatrices[0]; // loop over all quadrature points const auto quadPointEndIt = volumeQuadrature.end(); for (auto quadPointIt = volumeQuadrature.begin(); quadPointIt != quadPointEndIt; ++quadPointIt) { const Dune::FieldVector< D, d > x = quadPointIt->position(); // integration factors const double integrationFactor = entity.geometry().integrationElement(x); const double quadratureWeight = quadPointIt->weight(); // evaluate the local operation evaluation().evaluate(localFunctions, ansatzBase, testBase, x, evaluationResult); // compute integral for (size_t ii = 0; ii < rows; ++ii) { auto& retRow = ret[ii]; const auto& evaluationResultRow = evaluationResult[ii]; for (size_t jj = 0; jj < cols; ++jj) retRow[jj] += evaluationResultRow[jj] * integrationFactor * quadratureWeight; } // compute integral } // loop over all quadrature points } // ... apply(...) private: const BinaryEvaluationType& evaluation() const { return evaluation_; } const BinaryEvaluationImp evaluation_; const size_t over_integrate_; }; // class Codim0Integral } // namespace LocalOperator } // namespace GDT } // namespace Dune #endif // DUNE_GDT_LOCALOPERATOR_INTEGRAL_HH
// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_LOCALOPERATOR_INTEGRAL_HH #define DUNE_GDT_LOCALOPERATOR_INTEGRAL_HH #include <vector> #include <utility> #include <type_traits> #include <limits> #include <boost/numeric/conversion/cast.hpp> #include <dune/stuff/common/disable_warnings.hh> # include <dune/common/densematrix.hh> #include <dune/stuff/common/reenable_warnings.hh> #include <dune/stuff/common/disable_warnings.hh> # include <dune/geometry/quadraturerules.hh> #include <dune/stuff/common/reenable_warnings.hh> #include <dune/stuff/functions/interfaces.hh> #include "../localevaluation/interface.hh" #include "interface.hh" namespace Dune { namespace GDT { namespace LocalOperator { // forward, to be used in the traits template< class BinaryEvaluationImp > class Codim0Integral; template< class BinaryEvaluationImp > class Codim0IntegralTraits { static_assert(std::is_base_of< LocalEvaluation::Codim0Interface< typename BinaryEvaluationImp::Traits, 2 >, BinaryEvaluationImp >::value, "BinaryEvaluationImp has to be derived from LocalEvaluation::Codim0Interface< ..., 2 >!"); public: typedef Codim0Integral< BinaryEvaluationImp > derived_type; typedef LocalEvaluation::Codim0Interface< typename BinaryEvaluationImp::Traits, 2 > BinaryEvaluationType; }; template< class BinaryEvaluationImp > class Codim0Integral : public LocalOperator::Codim0Interface< Codim0IntegralTraits< BinaryEvaluationImp > > { public: typedef Codim0IntegralTraits< BinaryEvaluationImp > Traits; typedef typename Traits::BinaryEvaluationType BinaryEvaluationType; private: static const size_t numTmpObjectsRequired_ = 1; public: template< class... Args > Codim0Integral(Args&& ...args) : evaluation_(std::forward< Args >(args)...) , over_integrate_(0) {} template< class... Args > Codim0Integral(const int over_integrate, Args&& ...args) : evaluation_(std::forward< Args >(args)...) , over_integrate_(boost::numeric_cast< size_t >(over_integrate)) {} template< class... Args > Codim0Integral(const size_t over_integrate, Args&& ...args) : evaluation_(std::forward< Args >(args)...) , over_integrate_(over_integrate) {} const BinaryEvaluationType& inducingEvaluation() const { return evaluation_; } size_t numTmpObjectsRequired() const { return numTmpObjectsRequired_; } template< class E, class D, int d, class R, int rT, int rCT, int rA, int rCA > void apply(const Stuff::LocalfunctionSetInterface< E, D, d, R, rT, rCT >& testBase, const Stuff::LocalfunctionSetInterface< E, D, d, R, rA, rCA >& ansatzBase, Dune::DynamicMatrix< R >& ret, std::vector< Dune::DynamicMatrix< R > >& tmpLocalMatrices) const { const auto& entity = ansatzBase.entity(); const auto localFunctions = evaluation_.localFunctions(entity); // quadrature typedef Dune::QuadratureRules< D, d > VolumeQuadratureRules; typedef Dune::QuadratureRule< D, d > VolumeQuadratureType; const size_t integrand_order = evaluation().order(localFunctions, ansatzBase, testBase) + over_integrate_; assert(integrand_order < std::numeric_limits< int >::max()); const VolumeQuadratureType& volumeQuadrature = VolumeQuadratureRules::rule(entity.type(), int(integrand_order)); // check matrix and tmp storage const size_t rows = testBase.size(); const size_t cols = ansatzBase.size(); ret *= 0.0; assert(ret.rows() >= rows); assert(ret.cols() >= cols); assert(tmpLocalMatrices.size() >= numTmpObjectsRequired_); auto& evaluationResult = tmpLocalMatrices[0]; // loop over all quadrature points const auto quadPointEndIt = volumeQuadrature.end(); for (auto quadPointIt = volumeQuadrature.begin(); quadPointIt != quadPointEndIt; ++quadPointIt) { const Dune::FieldVector< D, d > x = quadPointIt->position(); // integration factors const double integrationFactor = entity.geometry().integrationElement(x); const double quadratureWeight = quadPointIt->weight(); // evaluate the local operation evaluation().evaluate(localFunctions, ansatzBase, testBase, x, evaluationResult); // compute integral for (size_t ii = 0; ii < rows; ++ii) { auto& retRow = ret[ii]; const auto& evaluationResultRow = evaluationResult[ii]; for (size_t jj = 0; jj < cols; ++jj) retRow[jj] += evaluationResultRow[jj] * integrationFactor * quadratureWeight; } // compute integral } // loop over all quadrature points } // ... apply(...) private: const BinaryEvaluationType& evaluation() const { return evaluation_; } const BinaryEvaluationImp evaluation_; const size_t over_integrate_; }; // class Codim0Integral } // namespace LocalOperator } // namespace GDT } // namespace Dune #endif // DUNE_GDT_LOCALOPERATOR_INTEGRAL_HH
remove obsolete ctors, add safe integer conversion
[localoperator.codim0] remove obsolete ctors, add safe integer conversion
C++
bsd-2-clause
ftalbrecht/dune-gdt,BarbaraV/dune-gdt
ec7852b4dafc04586fd04b0a18a80d27dc837a7e
GAME/OBJLIGHT.C
GAME/OBJLIGHT.C
#include "OBJLIGHT.H" #include "SPECIFIC.H" struct FOOTPRINT FootPrint[32]; int FootPrintNum; void TriggerAlertLight(long x, long y, long z, long r, long g, long b, long angle, int room_no, int falloff)//5D018, 5D494 { } void ControlBlinker(short item_number)//5D660, 5DADC { UNIMPLEMENTED(); } void ControlElectricalLight(short item_number)//5D3F8, 5D874 { UNIMPLEMENTED(); } void ControlColouredLight(short item_number)//5D368, 5D7E4 { UNIMPLEMENTED(); } void ControlPulseLight(short item_number)//5D254, 5D6D0 { UNIMPLEMENTED(); } void ControlStrobeLight(short item_number)//5D118, 5D594 { UNIMPLEMENTED(); }
#include "OBJLIGHT.H" #include "CONTROL.H" #include "SPECIFIC.H" #if PSX_VERSION || PSXPC_VERSION #include "SPHERES.H" #endif struct FOOTPRINT FootPrint[32]; int FootPrintNum; void TriggerAlertLight(long x, long y, long z, long r, long g, long b, long angle, int room_no, int falloff)//5D018, 5D494 { } void ControlBlinker(short item_number)//5D660(<), 5DADC (F) { struct ITEM_INFO* item; struct PHD_VECTOR pos; long r; long g; long b; item = &items[item_number]; if (TriggerActive(item) == 0) return; if (--item->item_flags[0] < 3) { pos.z = 0; pos.y = 0; pos.z = 0; GetJointAbsPosition(item, &pos, 0); r = (item->trigger_flags & 0x1F) << 3; g = (item->trigger_flags >> 4) & 0xF8; b = (item->trigger_flags >> 1) & 0xF8; TriggerDynamic(pos.x, pos.y, pos.z, 16, r, g, b); item->mesh_bits = 2; if (item->item_flags[0] < 0) { item->item_flags[0] = 30; }//5D73C } else { //5D734 item->mesh_bits = 1; } } void ControlElectricalLight(short item_number)//5D3F8, 5D874 { UNIMPLEMENTED(); } void ControlColouredLight(short item_number)//5D368, 5D7E4 { UNIMPLEMENTED(); } void ControlPulseLight(short item_number)//5D254, 5D6D0 { UNIMPLEMENTED(); } void ControlStrobeLight(short item_number)//5D118, 5D594 { UNIMPLEMENTED(); }
Add ControlBlinker
Add ControlBlinker
C++
mit
TOMB5/TOMB5,TOMB5/TOMB5,TOMB5/TOMB5,TOMB5/TOMB5
273d17cbe2450d610006ce28c00c0c57025b66fb
engine/desert_platform_linux.cpp
engine/desert_platform_linux.cpp
/******************************************************************************** * Copyright (C) 2017 by Bogdan Kozyrev <[email protected]> * * All rights reserved. * * * * Part of the Desert Engine Project: * * https://github.com/t800danya/desert-engine/ * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions * * are met: * * - Redistributions may not be sold, nor may they be used in a * * commercial product or activity. * * - Redistributions of source code and/or in binary form must reproduce * * the above copyright notice, this list of conditions and the * * following disclaimer in the documentation and/or other materials * * provided with the distribution. * * * * THIS SOFTWARE IS "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. * *******************************************************************************/
/******************************************************************************** * Copyright (C) 2017 by Bogdan Kozyrev <[email protected]> * * All rights reserved. * * * * Part of the Desert Engine Project: * * https://github.com/t800danya/desert-engine/ * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions * * are met: * * - Redistributions may not be sold, nor may they be used in a * * commercial product or activity. * * - Redistributions of source code and/or in binary form must reproduce * * the above copyright notice, this list of conditions and the * * following disclaimer in the documentation and/or other materials * * provided with the distribution. * * * * THIS SOFTWARE IS "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 "arctic_platform_def.h" #ifdef DESERT_PLATFORM_LINUX #endif //DESERT_PLATFORM_LINUX
Update desert_platform_linux.cpp
Update desert_platform_linux.cpp
C++
mit
t800danya/desert-engine,t800danya/desert-engine,t800danya/desert-engine,t800danya/desert-engine
35b8e61fbbb284c59f82ece9d91684ecef01f3cd
engine/tests/test_rule_hooks.cpp
engine/tests/test_rule_hooks.cpp
/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS 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. ****************************************************************************/ /** * @file * @brief IronBee --- Rule Engine Hook Tests * * @author Christopher Alfeld <[email protected]> */ #include "gtest/gtest.h" #include "base_fixture.h" #include <ironbee/rule_engine.h> class RuleHooksTest : public BaseTransactionFixture { }; struct result_t { result_t() : at(0) {} void called(const ib_rule_exec_t* rule_exec_) { rule_exec = rule_exec_; at = next_at; ++next_at; } static int next_at; const ib_rule_exec_t* rule_exec; int at; }; int result_t::next_at = 0; struct pre_operator_result_t : result_t { pre_operator_result_t() : opinst(NULL), invert(false), value(NULL) {} void called( const ib_rule_exec_t* rule_exec_, const ib_operator_inst_t* opinst_, bool invert_, const ib_field_t* value_ ) { result_t::called(rule_exec_); opinst = opinst_; invert = invert_; value = value_; } const ib_operator_inst_t* opinst; bool invert; const ib_field_t* value; }; struct post_operator_result_t : pre_operator_result_t { post_operator_result_t() : op_rc(IB_ENOTIMPL), result(2), capture(NULL) {} void called( const ib_rule_exec_t* rule_exec_, const ib_operator_inst_t* opinst_, bool invert_, const ib_field_t* value_, ib_status_t op_rc_, ib_num_t result_, ib_field_t* capture_ ) { pre_operator_result_t::called( rule_exec_, opinst_, invert_, value_ ); op_rc = op_rc_; result = result_; capture = capture_; } ib_status_t op_rc; ib_num_t result; ib_field_t* capture; }; struct pre_action_result_t : result_t { pre_action_result_t() : action(NULL), result(2) {} void called( const ib_rule_exec_t* rule_exec_, const ib_action_inst_t* action_, ib_num_t result_ ) { result_t::called(rule_exec_); action = action_; result = result_; } const ib_action_inst_t* action; ib_num_t result; }; struct post_action_result_t : pre_action_result_t { post_action_result_t() : act_rc(IB_ENOTIMPL) {} void called( const ib_rule_exec_t* rule_exec_, const ib_action_inst_t* action_, ib_num_t result_, ib_status_t act_rc_ ) { pre_action_result_t::called(rule_exec_, action_, result_); act_rc = act_rc_; } ib_status_t act_rc; }; extern "C" { static void pre_post_rule( const ib_rule_exec_t* rule_exec, void* cbdata ) { result_t* hook_result = reinterpret_cast<result_t*>(cbdata); hook_result->called(rule_exec); } static void pre_operator( const ib_rule_exec_t* rule_exec, const ib_operator_inst_t* opinst, bool invert, const ib_field_t* value, void* cbdata ) { pre_operator_result_t* hook_result = reinterpret_cast<pre_operator_result_t*>(cbdata); hook_result->called(rule_exec, opinst, invert, value); } static void post_operator( const ib_rule_exec_t* rule_exec, const ib_operator_inst_t* opinst, bool invert, const ib_field_t* value, ib_status_t op_rc, ib_num_t result, ib_field_t* capture, void* cbdata ) { post_operator_result_t* hook_result = reinterpret_cast<post_operator_result_t*>(cbdata); hook_result->called( rule_exec, opinst, invert, value, op_rc, result, capture ); } static void pre_action( const ib_rule_exec_t* rule_exec, const ib_action_inst_t* action, ib_num_t result, void* cbdata ) { pre_action_result_t* hook_result = reinterpret_cast<pre_action_result_t*>(cbdata); hook_result->called(rule_exec, action, result); } static void post_action( const ib_rule_exec_t* rule_exec, const ib_action_inst_t* action, ib_num_t result, ib_status_t act_rc, void* cbdata ) { post_action_result_t* hook_result = reinterpret_cast<post_action_result_t*>(cbdata); hook_result->called(rule_exec, action, result, act_rc); } } // extern "C" TEST_F(RuleHooksTest, test_basic) { result_t pre_rule_result; result_t post_rule_result; pre_operator_result_t pre_operator_result; post_operator_result_t post_operator_result; pre_action_result_t pre_action_result; post_action_result_t post_action_result; result_t::next_at = 1; ASSERT_EQ(IB_OK, ib_rule_register_pre_rule_fn( ib_engine, pre_post_rule, &pre_rule_result )); ASSERT_EQ(IB_OK, ib_rule_register_post_rule_fn( ib_engine, pre_post_rule, &post_rule_result )); ASSERT_EQ(IB_OK, ib_rule_register_pre_operator_fn( ib_engine, pre_operator, &pre_operator_result )); ASSERT_EQ(IB_OK, ib_rule_register_post_operator_fn( ib_engine, post_operator, &post_operator_result )); ASSERT_EQ(IB_OK, ib_rule_register_pre_action_fn( ib_engine, pre_action, &pre_action_result )); ASSERT_EQ(IB_OK, ib_rule_register_post_action_fn( ib_engine, post_action, &post_action_result )); configureIronBee(); performTx(); EXPECT_EQ(1, pre_rule_result.at); EXPECT_TRUE(pre_rule_result.rule_exec); EXPECT_EQ(2, pre_operator_result.at); EXPECT_TRUE(pre_operator_result.rule_exec); EXPECT_TRUE(pre_operator_result.opinst); EXPECT_FALSE(pre_operator_result.invert); EXPECT_TRUE(pre_operator_result.value); EXPECT_EQ(3, post_operator_result.at); EXPECT_TRUE(post_operator_result.rule_exec); EXPECT_TRUE(post_operator_result.opinst); EXPECT_FALSE(post_operator_result.invert); EXPECT_TRUE(post_operator_result.value); EXPECT_EQ(IB_OK, post_operator_result.op_rc); EXPECT_EQ(1, post_operator_result.result); EXPECT_FALSE(post_operator_result.capture); EXPECT_EQ(4, pre_action_result.at); EXPECT_TRUE(pre_action_result.rule_exec); EXPECT_TRUE(pre_action_result.action); EXPECT_EQ(1, pre_action_result.result); EXPECT_EQ(5, post_action_result.at); EXPECT_TRUE(post_action_result.rule_exec); EXPECT_TRUE(post_action_result.action); EXPECT_EQ(1, post_action_result.result); EXPECT_EQ(IB_OK, post_action_result.act_rc); EXPECT_EQ(6, post_rule_result.at); EXPECT_TRUE(post_rule_result.rule_exec); }
/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS 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. ****************************************************************************/ /** * @file * @brief IronBee --- Rule Engine Hook Tests * * @author Christopher Alfeld <[email protected]> */ #include "gtest/gtest.h" #include "base_fixture.h" #include <ironbee/rule_engine.h> class RuleHooksTest : public BaseTransactionFixture { }; struct result_t { result_t() : next_at(0), rule_exec(NULL), at(0) {} void called(const ib_rule_exec_t* rule_exec_) { rule_exec = rule_exec_; at = next_at; ++next_at; } static int next_at; const ib_rule_exec_t* rule_exec; int at; }; int result_t::next_at = 0; struct pre_operator_result_t : result_t { pre_operator_result_t() : opinst(NULL), invert(false), value(NULL) {} void called( const ib_rule_exec_t* rule_exec_, const ib_operator_inst_t* opinst_, bool invert_, const ib_field_t* value_ ) { result_t::called(rule_exec_); opinst = opinst_; invert = invert_; value = value_; } const ib_operator_inst_t* opinst; bool invert; const ib_field_t* value; }; struct post_operator_result_t : pre_operator_result_t { post_operator_result_t() : op_rc(IB_ENOTIMPL), result(2), capture(NULL) {} void called( const ib_rule_exec_t* rule_exec_, const ib_operator_inst_t* opinst_, bool invert_, const ib_field_t* value_, ib_status_t op_rc_, ib_num_t result_, ib_field_t* capture_ ) { pre_operator_result_t::called( rule_exec_, opinst_, invert_, value_ ); op_rc = op_rc_; result = result_; capture = capture_; } ib_status_t op_rc; ib_num_t result; ib_field_t* capture; }; struct pre_action_result_t : result_t { pre_action_result_t() : action(NULL), result(2) {} void called( const ib_rule_exec_t* rule_exec_, const ib_action_inst_t* action_, ib_num_t result_ ) { result_t::called(rule_exec_); action = action_; result = result_; } const ib_action_inst_t* action; ib_num_t result; }; struct post_action_result_t : pre_action_result_t { post_action_result_t() : act_rc(IB_ENOTIMPL) {} void called( const ib_rule_exec_t* rule_exec_, const ib_action_inst_t* action_, ib_num_t result_, ib_status_t act_rc_ ) { pre_action_result_t::called(rule_exec_, action_, result_); act_rc = act_rc_; } ib_status_t act_rc; }; extern "C" { static void pre_post_rule( const ib_rule_exec_t* rule_exec, void* cbdata ) { result_t* hook_result = reinterpret_cast<result_t*>(cbdata); hook_result->called(rule_exec); } static void pre_operator( const ib_rule_exec_t* rule_exec, const ib_operator_inst_t* opinst, bool invert, const ib_field_t* value, void* cbdata ) { pre_operator_result_t* hook_result = reinterpret_cast<pre_operator_result_t*>(cbdata); hook_result->called(rule_exec, opinst, invert, value); } static void post_operator( const ib_rule_exec_t* rule_exec, const ib_operator_inst_t* opinst, bool invert, const ib_field_t* value, ib_status_t op_rc, ib_num_t result, ib_field_t* capture, void* cbdata ) { post_operator_result_t* hook_result = reinterpret_cast<post_operator_result_t*>(cbdata); hook_result->called( rule_exec, opinst, invert, value, op_rc, result, capture ); } static void pre_action( const ib_rule_exec_t* rule_exec, const ib_action_inst_t* action, ib_num_t result, void* cbdata ) { pre_action_result_t* hook_result = reinterpret_cast<pre_action_result_t*>(cbdata); hook_result->called(rule_exec, action, result); } static void post_action( const ib_rule_exec_t* rule_exec, const ib_action_inst_t* action, ib_num_t result, ib_status_t act_rc, void* cbdata ) { post_action_result_t* hook_result = reinterpret_cast<post_action_result_t*>(cbdata); hook_result->called(rule_exec, action, result, act_rc); } } // extern "C" TEST_F(RuleHooksTest, test_basic) { result_t pre_rule_result; result_t post_rule_result; pre_operator_result_t pre_operator_result; post_operator_result_t post_operator_result; pre_action_result_t pre_action_result; post_action_result_t post_action_result; result_t::next_at = 1; ASSERT_EQ(IB_OK, ib_rule_register_pre_rule_fn( ib_engine, pre_post_rule, &pre_rule_result )); ASSERT_EQ(IB_OK, ib_rule_register_post_rule_fn( ib_engine, pre_post_rule, &post_rule_result )); ASSERT_EQ(IB_OK, ib_rule_register_pre_operator_fn( ib_engine, pre_operator, &pre_operator_result )); ASSERT_EQ(IB_OK, ib_rule_register_post_operator_fn( ib_engine, post_operator, &post_operator_result )); ASSERT_EQ(IB_OK, ib_rule_register_pre_action_fn( ib_engine, pre_action, &pre_action_result )); ASSERT_EQ(IB_OK, ib_rule_register_post_action_fn( ib_engine, post_action, &post_action_result )); configureIronBee(); performTx(); EXPECT_EQ(1, pre_rule_result.at); EXPECT_TRUE(pre_rule_result.rule_exec); EXPECT_EQ(2, pre_operator_result.at); EXPECT_TRUE(pre_operator_result.rule_exec); EXPECT_TRUE(pre_operator_result.opinst); EXPECT_FALSE(pre_operator_result.invert); EXPECT_TRUE(pre_operator_result.value); EXPECT_EQ(3, post_operator_result.at); EXPECT_TRUE(post_operator_result.rule_exec); EXPECT_TRUE(post_operator_result.opinst); EXPECT_FALSE(post_operator_result.invert); EXPECT_TRUE(post_operator_result.value); EXPECT_EQ(IB_OK, post_operator_result.op_rc); EXPECT_EQ(1, post_operator_result.result); EXPECT_FALSE(post_operator_result.capture); EXPECT_EQ(4, pre_action_result.at); EXPECT_TRUE(pre_action_result.rule_exec); EXPECT_TRUE(pre_action_result.action); EXPECT_EQ(1, pre_action_result.result); EXPECT_EQ(5, post_action_result.at); EXPECT_TRUE(post_action_result.rule_exec); EXPECT_TRUE(post_action_result.action); EXPECT_EQ(1, post_action_result.result); EXPECT_EQ(IB_OK, post_action_result.act_rc); EXPECT_EQ(6, post_rule_result.at); EXPECT_TRUE(post_rule_result.rule_exec); }
Initialize all class memebers. CID 11007.
test_rule_hooks.cpp: Initialize all class memebers. CID 11007.
C++
apache-2.0
ironbee/ironbee,b1v1r/ironbee,b1v1r/ironbee,b1v1r/ironbee,ironbee/ironbee,ironbee/ironbee,ironbee/ironbee,b1v1r/ironbee,ironbee/ironbee,b1v1r/ironbee,ironbee/ironbee,b1v1r/ironbee,ironbee/ironbee,ironbee/ironbee,b1v1r/ironbee,b1v1r/ironbee,ironbee/ironbee,b1v1r/ironbee,b1v1r/ironbee,b1v1r/ironbee,ironbee/ironbee,b1v1r/ironbee,ironbee/ironbee,ironbee/ironbee
67a3d455e91b5a87c4962ed55b998c0cc169e3cc
ext/flow/mex_broxOpticalFlow.cpp
ext/flow/mex_broxOpticalFlow.cpp
#include <vector> #include "opencv2/core.hpp" #include <opencv2/core/utility.hpp> #include "opencv2/cudaoptflow.hpp" #include "opencv2/cudaarithm.hpp" #include "mex.h" /* This is a mex wrapper for Matlab's CUDA implementation of Brox et al.'s * optical flow implementation[0], which is apparently insanely fast. * * Usage: * * flow_field = brox_optical_flow_mex(first_frame, second_frame); * * [0] http://docs.opencv.org/3.0-beta/modules/cudaoptflow/doc/optflow.html */ bool verifyMatrix(const mxArray *mat) { // uint8s are returned by imread() (which we want to support out of the box) return mxGetClassID(mat) == mxSINGLE_CLASS && mxGetNumberOfDimensions(mat) == 2; } bool dimensionsMatch(const mxArray *mat1, const mxArray *mat2) { mwSize ndim = mxGetNumberOfDimensions(mat1); if (ndim != mxGetNumberOfDimensions(mat2)) { return false; } const mwSize *dim1 = mxGetDimensions(mat1); const mwSize *dim2 = mxGetDimensions(mat2); for (mwSize i = 0; i < ndim; i++) { if (dim1[i] != dim2[i]) { return false; } } return true; } cv::cuda::GpuMat toGPUMat(const mxArray *m) { // XXX: mxGetData will return something in column-major order (so the first // m cells represent the rows of the first column), but I think openCV // expects row-major order. Looks like I'm going to have to copy in the data // manually, or perhaps do a transpose in Matlab (at best) :( float *columnMajor = (float*)mxGetData(m); size_t rows = mxGetM(m); size_t cols = mxGetN(m); cv::Mat cvMatrix = cv::Mat((int)rows, (int)cols, CV_32F); for (size_t row = 0; row < rows; row++) { for (size_t col = 0; col < cols; col++) { cvMatrix.at<float>(row, col) = columnMajor[col * rows + row]; } } return cv::cuda::GpuMat(cvMatrix); } void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { if (nlhs > 1) { mexErrMsgIdAndTxt( "JointRegressor:brox_optical_flow_mex:nlhs", "Only one output is produced" ); return; } if (nrhs != 2) { mexErrMsgIdAndTxt( "JointRegressor:brox_optical_flow_mex:nrhs", "Two inputs required" ); return; } if (!verifyMatrix(prhs[0]) || !verifyMatrix(prhs[1])) { mexErrMsgIdAndTxt( "JointRegressor:brox_optical_flow_mex:prhs", "Inputs should be 2D single arrays" ); return; } if (!dimensionsMatch(prhs[0], prhs[1])) { mexErrMsgIdAndTxt( "JointRegressor:brox_optical_flow_mex:prhs", "Input dimensions don't match" ); return; } /* Now we can read the images and convert them to CV_32FC1 (grayscale image, * single-precision float). * This is straight from the optical_flow.cpp example in the repository. */ cv::Ptr<cv::cuda::BroxOpticalFlow> brox = cv::cuda::BroxOpticalFlow::create(); cv::cuda::GpuMat im0 = toGPUMat(prhs[0]); cv::cuda::GpuMat im1 = toGPUMat(prhs[1]); cv::cuda::GpuMat outFlow(im0.size(), CV_32FC2); brox->calc(im0, im1, outFlow); cv::Mat result; outFlow.download(result); std::vector<cv::Mat> channels(2); cv::split(result, channels); /* Finally, output the m*n*2 flow field */ cv::Size outSize = result.size(); mwSize outDim[3] = {outSize.height, outSize.width, 2}; mwSize rows = outDim[0], cols = outDim[1]; plhs[0] = mxCreateNumericArray(3, outDim, mxSINGLE_CLASS, mxREAL); float *outMatrix = (float*)mxGetData(plhs[0]); for (int chan = 0; chan < outDim[2]; chan++) { for (int col = 0; col < outDim[1]; col++) { for (int row = 0; row < outDim[0]; row++) { int index = chan * cols * rows + col * rows + row; outMatrix[index] = channels[chan].at<float>(row, col); } } } }
#include <vector> #include "opencv2/core.hpp" #include <opencv2/core/utility.hpp> #include "opencv2/cudaoptflow.hpp" #include "opencv2/cudaarithm.hpp" #include "mex.h" /* This is a mex wrapper for OpenCV's CUDA implementation of Brox et al.'s * optical flow method[0], since that implementation is insanely fast. * * Usage: * * flow_field = brox_optical_flow_mex(first_frame, second_frame); * * [0] http://docs.opencv.org/3.0-beta/modules/cudaoptflow/doc/optflow.html */ bool verifyMatrix(const mxArray *mat) { // uint8s are returned by imread() (which we want to support out of the box) return mxGetClassID(mat) == mxSINGLE_CLASS && mxGetNumberOfDimensions(mat) == 2; } bool dimensionsMatch(const mxArray *mat1, const mxArray *mat2) { mwSize ndim = mxGetNumberOfDimensions(mat1); if (ndim != mxGetNumberOfDimensions(mat2)) { return false; } const mwSize *dim1 = mxGetDimensions(mat1); const mwSize *dim2 = mxGetDimensions(mat2); for (mwSize i = 0; i < ndim; i++) { if (dim1[i] != dim2[i]) { return false; } } return true; } cv::cuda::GpuMat toGPUMat(const mxArray *m) { // XXX: mxGetData will return something in column-major order (so the first // m cells represent the rows of the first column), but I think openCV // expects row-major order. Looks like I'm going to have to copy in the data // manually, or perhaps do a transpose in Matlab (at best) :( float *columnMajor = (float*)mxGetData(m); size_t rows = mxGetM(m); size_t cols = mxGetN(m); cv::Mat cvMatrix = cv::Mat((int)rows, (int)cols, CV_32F); for (size_t row = 0; row < rows; row++) { for (size_t col = 0; col < cols; col++) { cvMatrix.at<float>(row, col) = columnMajor[col * rows + row]; } } return cv::cuda::GpuMat(cvMatrix); } void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { if (nlhs > 1) { mexErrMsgIdAndTxt( "JointRegressor:brox_optical_flow_mex:nlhs", "Only one output is produced" ); return; } if (nrhs != 2) { mexErrMsgIdAndTxt( "JointRegressor:brox_optical_flow_mex:nrhs", "Two inputs required" ); return; } if (!verifyMatrix(prhs[0]) || !verifyMatrix(prhs[1])) { mexErrMsgIdAndTxt( "JointRegressor:brox_optical_flow_mex:prhs", "Inputs should be 2D single arrays" ); return; } if (!dimensionsMatch(prhs[0], prhs[1])) { mexErrMsgIdAndTxt( "JointRegressor:brox_optical_flow_mex:prhs", "Input dimensions don't match" ); return; } /* Now we can read the images and convert them to CV_32FC1 (grayscale image, * single-precision float). * This is straight from the optical_flow.cpp example in the repository. */ cv::Ptr<cv::cuda::BroxOpticalFlow> brox = cv::cuda::BroxOpticalFlow::create(); cv::cuda::GpuMat im0 = toGPUMat(prhs[0]); cv::cuda::GpuMat im1 = toGPUMat(prhs[1]); cv::cuda::GpuMat outFlow(im0.size(), CV_32FC2); brox->calc(im0, im1, outFlow); cv::Mat result; outFlow.download(result); std::vector<cv::Mat> channels(2); cv::split(result, channels); /* Finally, output the m*n*2 flow field */ cv::Size outSize = result.size(); mwSize outDim[3] = {outSize.height, outSize.width, 2}; mwSize rows = outDim[0], cols = outDim[1]; plhs[0] = mxCreateNumericArray(3, outDim, mxSINGLE_CLASS, mxREAL); float *outMatrix = (float*)mxGetData(plhs[0]); for (int chan = 0; chan < outDim[2]; chan++) { for (int col = 0; col < outDim[1]; col++) { for (int row = 0; row < outDim[0]; row++) { int index = chan * cols * rows + col * rows + row; outMatrix[index] = channels[chan].at<float>(row, col); } } } }
Correct typo in optical flow explanation
Correct typo in optical flow explanation
C++
apache-2.0
qxcv/joint-regressor,qxcv/joint-regressor,qxcv/joint-regressor,qxcv/joint-regressor
b2b9bfb3560b0b6d4b2c7b7b5bab5dd4572f80c7
allocore/src/protocol/al_OSC.cpp
allocore/src/protocol/al_OSC.cpp
#include <ctype.h> // isgraph #include <stdio.h> // printf #include <string.h> #include "allocore/system/al_Printing.hpp" #include "allocore/protocol/al_OSC.hpp" #include "oscpack/osc/OscOutboundPacketStream.h" #include "oscpack/osc/OscPacketListener.h" #include "oscpack/osc/OscReceivedElements.h" #include "oscpack/osc/OscTypes.h" #include "oscpack/osc/OscException.h" /* Summary of OSC 1.0 spec from http://opensoundcontrol.org The unit of transmission of OSC is an OSC Packet. An OSC Packet consists of its contents a contiguous block of binary data its size, the number of 8-bit bytes that comprise the contents The contents of an OSC packet must be either an OSC Message or an OSC Bundle. The first byte of the packet's contents unambiguously distinguishes between these two alternatives. The size of an OSC packet is always a multiple of 4. An OSC message consists of 1) an OSC Address Pattern 2) an OSC Type Tag String 3) zero or more OSC Arguments An OSC Address Pattern is an OSC-string beginning with the character '/' An OSC Type Tag String is an OSC-string beginning with the character ',' (comma) followed by a sequence of characters corresponding exactly to the sequence of OSC Arguments in the given message. i int32 f float32 s OSC-string b OSC-blob Anatomy of a bundle: OSC-string "#bundle" 8 bytes How to know that this data is a bundle OSC-timetag 8 bytes (int64) Time tag that applies to the entire bundle Size of first bundle element 4 bytes (int32) First bundle element 1st bundle element's contents size of 1st bundle Size of second bundle element 4 bytes (int32) Second bundle element 2nd bundle element's contents size of 2nd bundle etc. Addtional bundle elements */ #define OSCTRY(msg, expr) \ try { \ expr \ } catch (::osc::Exception& e) { \ AL_WARN("OSC error: %s", e.what()); \ } //#define VERBOSE #ifdef VERBOSE #define DPRINTF(...) printf(__VA_ARGS__) #else #define DPRINTF(...) #endif namespace al{ namespace osc{ class Packet::Impl : public ::osc::OutboundPacketStream{ public: Impl(char * buf, int size) : ::osc::OutboundPacketStream(buf, size) {} }; Packet::Packet(int size) : mData(size), mImpl(0) { OSCTRY("Packet::Packet", mImpl = new Impl(&mData[0], size);) } Packet::Packet(const char * contents, int size) : mData(size), mImpl(0) { OSCTRY("Packet::Packet1", memcpy(&mData[0], contents, size); mImpl = new Impl(&mData[0], size); ) } Packet::~Packet(){ delete mImpl; } Packet& Packet::operator<< (int v){ OSCTRY("Packet::<<int", (*mImpl) << (::osc::int32)v;) return *this; } Packet& Packet::operator<< (unsigned v){ OSCTRY("Packet::<<unsigned", (*mImpl) << (::osc::int32)v;) return *this; } Packet& Packet::operator<< (float v){ OSCTRY("Packet::<<float", (*mImpl) << v;) return *this; } Packet& Packet::operator<< (double v){ OSCTRY("Packet::<<double", (*mImpl) << v;) return *this; } Packet& Packet::operator<< (char v){ OSCTRY("Packet<<char", (*mImpl) << v;) return *this; } Packet& Packet::operator<< (const char * v){ OSCTRY("Packet::<<const char *", (*mImpl) << v;) return *this; } Packet& Packet::operator<< (const std::string& v){ OSCTRY("Packet::<< string", (*mImpl) << v.c_str();) return *this; } Packet& Packet::operator<< (const Blob& v){ OSCTRY("Packet::<<Blob", (*mImpl) << ::osc::Blob(v.data, v.size);) return *this; } Packet& Packet::beginMessage(const std::string& addr){ OSCTRY("Packet::beginMessage", (*mImpl) << ::osc::BeginMessage(addr.c_str());) return *this; } Packet& Packet::endMessage(){ OSCTRY("Packet::endMessage", (*mImpl) << ::osc::EndMessage;) return *this; } Packet& Packet::beginBundle(TimeTag timeTag){ OSCTRY("Packet::beginBundle", (*mImpl) << ::osc::BeginBundle(timeTag);) return *this; } Packet& Packet::endBundle(){ OSCTRY("Packet::endBundle", (*mImpl) << ::osc::EndBundle;) return *this; } Packet& Packet::clear(){ OSCTRY("Packet::clear", mImpl->Clear();) return *this; } const char * Packet::data() const { return mImpl->Data(); } bool Packet::isBundle() const { return ::osc::ReceivedPacket(data(), size()).IsBundle(); } bool Packet::isMessage() const { return ::osc::ReceivedPacket(data(), size()).IsMessage(); } void Packet::printRaw() const { for(int i=0; i<size(); ++i){ unsigned char c = data()[i]; printf("%2x ", c); isgraph(c) ? printf(" %c ", c) : printf(" "); if((i+1)%4 == 0) printf("\n"); } } int Packet::size() const { return mImpl->Size(); } class Message::Impl : public ::osc::ReceivedMessage { public: Impl(const char * message, int size) : ::osc::ReceivedMessage(::osc::ReceivedPacket(message,size)), args(ArgumentStream()) { // printf("made an ::osc::ReceivedMessage out of message %p and size %d\n", message, size); } template <class T> void operator>> (T& v){ OSCTRY("Message>>", args>>v;) } ::osc::ReceivedMessageArgumentStream args; }; Message::Message(const char * message, int size, const TimeTag& timeTag, const char *senderAddr) : mImpl(new Impl(message, size)), mTimeTag(timeTag) { OSCTRY("Message()", mAddressPattern = mImpl->AddressPattern(); mTypeTags = mImpl->ArgumentCount() ? mImpl->TypeTags() : ""; resetStream(); ) if (senderAddr != nullptr) { strncpy(mSenderAddr, senderAddr, 32); } else { mSenderAddr[0] = '\0'; } } Message::~Message() { OSCTRY("~Message()", delete mImpl;) } void Message::print() const { OSCTRY("Message::print", printf("%s, %s %" AL_PRINTF_LL "d from %s\n", addressPattern().c_str(), typeTags().c_str(), timeTag(), mSenderAddr); ::osc::ReceivedMessageArgumentIterator it = mImpl->ArgumentsBegin(); printf("\targs = ("); for(unsigned i=0; i<typeTags().size(); ++i){ char tag = typeTags()[i]; switch(tag){ case 'f': {float v = it->AsFloat(); printf("%g", v);} break; case 'i': {long v = it->AsInt32(); printf("%ld", v);} break; case 'h': {long long v = it->AsInt64(); printf("%" AL_PRINTF_LL "d", v);} break; case 'c': {char v = it->AsChar(); printf("'%c' (=%3d)", isprint(v) ? v : ' ', v);} break; case 'd': {double v = it->AsDouble(); printf("%g", v);} break; case 's': {const char * v = it->AsString(); printf("%s", v);} break; case 'b': printf("blob"); break; default: printf("?"); } if(i < (typeTags().size() - 1)) printf(", "); ++it; } printf(")\n"); ) } Message& Message::resetStream(){ mImpl->args = mImpl->ArgumentStream(); return *this; } Message& Message::operator>> (int& v){ ::osc::int32 r=0; OSCTRY("Message >> int", (*mImpl)>>r;) v=r; return *this; } Message& Message::operator>> (float& v){ OSCTRY("Message >> float", (*mImpl)>>v;) return *this; } Message& Message::operator>> (double& v){ OSCTRY("Message >> double", (*mImpl)>>v;) return *this; } Message& Message::operator>> (char& v){ OSCTRY("Message >> char", (*mImpl)>>v;) return *this; } Message& Message::operator>> (const char*& v){ OSCTRY("Message >> const char *", (*mImpl)>>v;) return *this; } Message& Message::operator>> (std::string& v){ const char * r = ""; OSCTRY("Message >> string", (*mImpl)>>r;) v=r; return *this; } Message& Message::operator>> (Blob& v){ ::osc::Blob b; OSCTRY("Message >> Blob", (*mImpl)>>b;) v.data=b.data; v.size=b.size; return *this; } #ifdef VERBOSE #include <netinet/in.h> // for ntohl #endif void PacketHandler::parse(const char *packet, int size, TimeTag timeTag, const char *senderAddr){ #ifdef VERBOSE int i = 1; #endif OSCTRY("PacketHandler::parse", DPRINTF("PacketHandler::parse(size %d, packet %p)\n", size, packet); DPRINTF("Data to parse: "); for(int i=0; i<size; ++i){ DPRINTF("%c", packet[i]); } DPRINTF("\n"); // this is the only generic entry point for parsing packets ::osc::ReceivedPacket p(packet, size); DPRINTF("Just made an ::osc::ReceivedPacket that has contents %p and size %d\n", p.Contents(), (int)p.Size()); // iterate through all the bundle elements (bundles or messages) if(p.IsBundle()){ DPRINTF("It's a bundle\n"); //char *afterTimeTag = (char *)packet+16; // "#bundle\0" plus 8-byte time tag DPRINTF("First bundle element has size %d\n", ntohl(*((int *)(packet+16))/*firstBundleElementSize*/)); ::osc::ReceivedBundle r(p); //DPRINTF("Just made an ::osc::ReceivedBundle that has time tag at %p and %d elements\n", r.timeTag_, r.ElementCount() ); for(auto it = r.ElementsBegin(); it != r.ElementsEnd(); ++it){ const ::osc::ReceivedBundleElement& e = *it; DPRINTF("Just made an ::osc::ReceivedBundleElement with contents %p and size %d\n", e.Contents(), (int)e.Size()); DPRINTF("Parsing bundle element %d\n", i++); DPRINTF("Made an ::osc::ReceivedBundleElement out of the iterator.\n"); DPRINTF("\tcontents: %p\n", e.Contents()); DPRINTF("\tsize: %d\n", (int)e.Size()); DPRINTF("\ttimeTag %lu\n", (unsigned long)r.TimeTag()); DPRINTF("\tLet's try to parse it...\n"); parse(e.Contents(), e.Size(), r.TimeTag(), senderAddr); } } else if(p.IsMessage()){ DPRINTF("Parsing a message\n"); Message m(packet, size, timeTag, senderAddr); onMessage(m); } ) // OSCTRY } Send::Send(uint16_t port, const char * address, al_sec timeout, int size) : SocketClient(port, address, timeout, Socket::UDP), Packet(size) {} int Send::send(){ //int r = Socket::send(Packet::data(), Packet::size()); int r = send(*this); OSCTRY("Packet::endMessage", Packet::clear();) return r; } int Send::send(const Packet& p){ int r = 0; OSCTRY("Packet::endMessage", r = Socket::send(p.data(), p.size());) return r; } static void * recvThreadFunc(void * user){ Recv * r = static_cast<Recv *>(user); while(r->background()){ r->recv(); } // printf("thread done\n"); return NULL; } Recv::Recv() : mHandler(0), mBuffer(1024), mBackground(false) { //printf("Entering Recv::Recv()\n"); } Recv::Recv(uint16_t port, const char * address, al_sec timeout) : SocketServer(port, address, timeout, Socket::UDP), mHandler(0), mBuffer(1024), mBackground(false) { //printf("Entering Recv::Recv(port=%d, addr=%s)\n", port, address); } int Recv::recv(){ int r = 0; DPRINTF("Entering Recv::recv() - mBuffer = %p and mBuffer.size() = %d\n", &mBuffer[0], mBuffer.size()); /* printf("Here's what's in my buffer before recv...\n"); for (int i = 0; i < mBuffer.size(); ++i) { if (mBuffer[i] != 0) printf("Byte %d: %d (%c)\n", i, mBuffer[i], mBuffer[i]); } */ OSCTRY("Packet::endMessage", char sender[16] = ""; r = Socket::recv(&mBuffer[0], mBuffer.size(), sender); if(r && mHandler){ DPRINTF("Recv:recv() Received %d bytes from %s; parsing...\n", r, sender); mHandler->parse(&mBuffer[0], r, 1, sender); } ) DPRINTF("Exiting Recv::recv() - mBuffer = %p and mBuffer.size() = %d\n", &mBuffer[0], mBuffer.size()); return r; } bool Recv::start(){ // printf("Entering Recv::start()\n"); mBackground = true; if (timeout() <= 0) { printf("warning (osc::Recv): timeout <= 0 and background polling may eat up your CPU! Set timeout(seconds) to avoid this.\n"); } return mThread.start(recvThreadFunc, this); } void Recv::stop(){ if(mBackground){ mBackground = false; mThread.join(); } } } // osc:: } // al::
#include <ctype.h> // isgraph #include <stdio.h> // printf #include <string.h> #include "allocore/system/al_Printing.hpp" #include "allocore/protocol/al_OSC.hpp" #include "oscpack/osc/OscOutboundPacketStream.h" #include "oscpack/osc/OscReceivedElements.h" #include "oscpack/osc/OscTypes.h" #include "oscpack/osc/OscException.h" /* Summary of OSC 1.0 spec from http://opensoundcontrol.org The unit of transmission of OSC is an OSC Packet. An OSC Packet consists of its contents a contiguous block of binary data its size, the number of 8-bit bytes that comprise the contents The contents of an OSC packet must be either an OSC Message or an OSC Bundle. The first byte of the packet's contents unambiguously distinguishes between these two alternatives. The size of an OSC packet is always a multiple of 4. An OSC message consists of 1) an OSC Address Pattern 2) an OSC Type Tag String 3) zero or more OSC Arguments An OSC Address Pattern is an OSC-string beginning with the character '/' An OSC Type Tag String is an OSC-string beginning with the character ',' (comma) followed by a sequence of characters corresponding exactly to the sequence of OSC Arguments in the given message. i int32 f float32 s OSC-string b OSC-blob Anatomy of a bundle: OSC-string "#bundle" 8 bytes How to know that this data is a bundle OSC-timetag 8 bytes (int64) Time tag that applies to the entire bundle Size of first bundle element 4 bytes (int32) First bundle element 1st bundle element's contents size of 1st bundle Size of second bundle element 4 bytes (int32) Second bundle element 2nd bundle element's contents size of 2nd bundle etc. Addtional bundle elements */ #define OSCTRY(msg, expr) \ try { \ expr \ } catch (::osc::Exception& e) { \ AL_WARN("OSC error: %s", e.what()); \ } //#define VERBOSE #ifdef VERBOSE #define DPRINTF(...) printf(__VA_ARGS__) #else #define DPRINTF(...) #endif namespace al{ namespace osc{ class Packet::Impl : public ::osc::OutboundPacketStream{ public: Impl(char * buf, int size) : ::osc::OutboundPacketStream(buf, size) {} }; Packet::Packet(int size) : mData(size), mImpl(0) { OSCTRY("Packet::Packet", mImpl = new Impl(&mData[0], size);) } Packet::Packet(const char * contents, int size) : mData(size), mImpl(0) { OSCTRY("Packet::Packet1", memcpy(&mData[0], contents, size); mImpl = new Impl(&mData[0], size); ) } Packet::~Packet(){ delete mImpl; } Packet& Packet::operator<< (int v){ OSCTRY("Packet::<<int", (*mImpl) << (::osc::int32)v;) return *this; } Packet& Packet::operator<< (unsigned v){ OSCTRY("Packet::<<unsigned", (*mImpl) << (::osc::int32)v;) return *this; } Packet& Packet::operator<< (float v){ OSCTRY("Packet::<<float", (*mImpl) << v;) return *this; } Packet& Packet::operator<< (double v){ OSCTRY("Packet::<<double", (*mImpl) << v;) return *this; } Packet& Packet::operator<< (char v){ OSCTRY("Packet<<char", (*mImpl) << v;) return *this; } Packet& Packet::operator<< (const char * v){ OSCTRY("Packet::<<const char *", (*mImpl) << v;) return *this; } Packet& Packet::operator<< (const std::string& v){ OSCTRY("Packet::<< string", (*mImpl) << v.c_str();) return *this; } Packet& Packet::operator<< (const Blob& v){ OSCTRY("Packet::<<Blob", (*mImpl) << ::osc::Blob(v.data, v.size);) return *this; } Packet& Packet::beginMessage(const std::string& addr){ OSCTRY("Packet::beginMessage", (*mImpl) << ::osc::BeginMessage(addr.c_str());) return *this; } Packet& Packet::endMessage(){ OSCTRY("Packet::endMessage", (*mImpl) << ::osc::EndMessage;) return *this; } Packet& Packet::beginBundle(TimeTag timeTag){ OSCTRY("Packet::beginBundle", (*mImpl) << ::osc::BeginBundle(timeTag);) return *this; } Packet& Packet::endBundle(){ OSCTRY("Packet::endBundle", (*mImpl) << ::osc::EndBundle;) return *this; } Packet& Packet::clear(){ OSCTRY("Packet::clear", mImpl->Clear();) return *this; } const char * Packet::data() const { return mImpl->Data(); } bool Packet::isBundle() const { return ::osc::ReceivedPacket(data(), size()).IsBundle(); } bool Packet::isMessage() const { return ::osc::ReceivedPacket(data(), size()).IsMessage(); } void Packet::printRaw() const { for(int i=0; i<size(); ++i){ unsigned char c = data()[i]; printf("%2x ", c); isgraph(c) ? printf(" %c ", c) : printf(" "); if((i+1)%4 == 0) printf("\n"); } } int Packet::size() const { return mImpl->Size(); } class Message::Impl : public ::osc::ReceivedMessage { public: Impl(const char * message, int size) : ::osc::ReceivedMessage(::osc::ReceivedPacket(message,size)), args(ArgumentStream()) { // printf("made an ::osc::ReceivedMessage out of message %p and size %d\n", message, size); } template <class T> void operator>> (T& v){ OSCTRY("Message>>", args>>v;) } ::osc::ReceivedMessageArgumentStream args; }; Message::Message(const char * message, int size, const TimeTag& timeTag, const char *senderAddr) : mImpl(new Impl(message, size)), mTimeTag(timeTag) { OSCTRY("Message()", mAddressPattern = mImpl->AddressPattern(); mTypeTags = mImpl->ArgumentCount() ? mImpl->TypeTags() : ""; resetStream(); ) if (senderAddr != nullptr) { strncpy(mSenderAddr, senderAddr, 32); } else { mSenderAddr[0] = '\0'; } } Message::~Message() { OSCTRY("~Message()", delete mImpl;) } void Message::print() const { OSCTRY("Message::print", printf("%s, %s %" AL_PRINTF_LL "d from %s\n", addressPattern().c_str(), typeTags().c_str(), timeTag(), mSenderAddr); ::osc::ReceivedMessageArgumentIterator it = mImpl->ArgumentsBegin(); printf("\targs = ("); for(unsigned i=0; i<typeTags().size(); ++i){ char tag = typeTags()[i]; switch(tag){ case 'f': {float v = it->AsFloat(); printf("%g", v);} break; case 'i': {long v = it->AsInt32(); printf("%ld", v);} break; case 'h': {long long v = it->AsInt64(); printf("%" AL_PRINTF_LL "d", v);} break; case 'c': {char v = it->AsChar(); printf("'%c' (=%3d)", isprint(v) ? v : ' ', v);} break; case 'd': {double v = it->AsDouble(); printf("%g", v);} break; case 's': {const char * v = it->AsString(); printf("%s", v);} break; case 'b': printf("blob"); break; default: printf("?"); } if(i < (typeTags().size() - 1)) printf(", "); ++it; } printf(")\n"); ) } Message& Message::resetStream(){ mImpl->args = mImpl->ArgumentStream(); return *this; } Message& Message::operator>> (int& v){ ::osc::int32 r=0; OSCTRY("Message >> int", (*mImpl)>>r;) v=r; return *this; } Message& Message::operator>> (float& v){ OSCTRY("Message >> float", (*mImpl)>>v;) return *this; } Message& Message::operator>> (double& v){ OSCTRY("Message >> double", (*mImpl)>>v;) return *this; } Message& Message::operator>> (char& v){ OSCTRY("Message >> char", (*mImpl)>>v;) return *this; } Message& Message::operator>> (const char*& v){ OSCTRY("Message >> const char *", (*mImpl)>>v;) return *this; } Message& Message::operator>> (std::string& v){ const char * r = ""; OSCTRY("Message >> string", (*mImpl)>>r;) v=r; return *this; } Message& Message::operator>> (Blob& v){ ::osc::Blob b; OSCTRY("Message >> Blob", (*mImpl)>>b;) v.data=b.data; v.size=b.size; return *this; } #ifdef VERBOSE #include <netinet/in.h> // for ntohl #endif void PacketHandler::parse(const char *packet, int size, TimeTag timeTag, const char *senderAddr){ #ifdef VERBOSE int i = 1; #endif OSCTRY("PacketHandler::parse", DPRINTF("PacketHandler::parse(size %d, packet %p)\n", size, packet); DPRINTF("Data to parse: "); for(int i=0; i<size; ++i){ DPRINTF("%c", packet[i]); } DPRINTF("\n"); // this is the only generic entry point for parsing packets ::osc::ReceivedPacket p(packet, size); DPRINTF("Just made an ::osc::ReceivedPacket that has contents %p and size %d\n", p.Contents(), (int)p.Size()); // iterate through all the bundle elements (bundles or messages) if(p.IsBundle()){ DPRINTF("It's a bundle\n"); //char *afterTimeTag = (char *)packet+16; // "#bundle\0" plus 8-byte time tag DPRINTF("First bundle element has size %d\n", ntohl(*((int *)(packet+16))/*firstBundleElementSize*/)); ::osc::ReceivedBundle r(p); //DPRINTF("Just made an ::osc::ReceivedBundle that has time tag at %p and %d elements\n", r.timeTag_, r.ElementCount() ); for(auto it = r.ElementsBegin(); it != r.ElementsEnd(); ++it){ const ::osc::ReceivedBundleElement& e = *it; DPRINTF("Just made an ::osc::ReceivedBundleElement with contents %p and size %d\n", e.Contents(), (int)e.Size()); DPRINTF("Parsing bundle element %d\n", i++); DPRINTF("Made an ::osc::ReceivedBundleElement out of the iterator.\n"); DPRINTF("\tcontents: %p\n", e.Contents()); DPRINTF("\tsize: %d\n", (int)e.Size()); DPRINTF("\ttimeTag %lu\n", (unsigned long)r.TimeTag()); DPRINTF("\tLet's try to parse it...\n"); parse(e.Contents(), e.Size(), r.TimeTag(), senderAddr); } } else if(p.IsMessage()){ DPRINTF("Parsing a message\n"); Message m(packet, size, timeTag, senderAddr); onMessage(m); } ) // OSCTRY } Send::Send(uint16_t port, const char * address, al_sec timeout, int size) : SocketClient(port, address, timeout, Socket::UDP), Packet(size) {} int Send::send(){ //int r = Socket::send(Packet::data(), Packet::size()); int r = send(*this); OSCTRY("Packet::endMessage", Packet::clear();) return r; } int Send::send(const Packet& p){ int r = 0; OSCTRY("Packet::endMessage", r = Socket::send(p.data(), p.size());) return r; } static void * recvThreadFunc(void * user){ Recv * r = static_cast<Recv *>(user); while(r->background()){ r->recv(); } // printf("thread done\n"); return NULL; } Recv::Recv() : mHandler(0), mBuffer(1024), mBackground(false) { //printf("Entering Recv::Recv()\n"); } Recv::Recv(uint16_t port, const char * address, al_sec timeout) : SocketServer(port, address, timeout, Socket::UDP), mHandler(0), mBuffer(1024), mBackground(false) { //printf("Entering Recv::Recv(port=%d, addr=%s)\n", port, address); } int Recv::recv(){ int r = 0; DPRINTF("Entering Recv::recv() - mBuffer = %p and mBuffer.size() = %d\n", &mBuffer[0], mBuffer.size()); /* printf("Here's what's in my buffer before recv...\n"); for (int i = 0; i < mBuffer.size(); ++i) { if (mBuffer[i] != 0) printf("Byte %d: %d (%c)\n", i, mBuffer[i], mBuffer[i]); } */ OSCTRY("Packet::endMessage", char sender[16] = ""; r = Socket::recv(&mBuffer[0], mBuffer.size(), sender); if(r && mHandler){ DPRINTF("Recv:recv() Received %d bytes from %s; parsing...\n", r, sender); mHandler->parse(&mBuffer[0], r, 1, sender); } ) DPRINTF("Exiting Recv::recv() - mBuffer = %p and mBuffer.size() = %d\n", &mBuffer[0], mBuffer.size()); return r; } bool Recv::start(){ // printf("Entering Recv::start()\n"); mBackground = true; if (timeout() <= 0) { printf("warning (osc::Recv): timeout <= 0 and background polling may eat up your CPU! Set timeout(seconds) to avoid this.\n"); } return mThread.start(recvThreadFunc, this); } void Recv::stop(){ if(mBackground){ mBackground = false; mThread.join(); } } } // osc:: } // al::
Remove unused oscpack header
Remove unused oscpack header
C++
bsd-3-clause
AlloSphere-Research-Group/AlloSystem,AlloSphere-Research-Group/AlloSystem,AlloSphere-Research-Group/AlloSystem,AlloSphere-Research-Group/AlloSystem,AlloSphere-Research-Group/AlloSystem
d694261e0ab928649c4458bfd9cb01e242c7c1f4
extensions/ringqt/codeeditor.cpp
extensions/ringqt/codeeditor.cpp
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** BSD License Usage ** Alternatively, you may use this file under the terms of the BSD license ** as follows: ** ** "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 Qt Company Ltd 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." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ /* File is modified to be merged with RingQt Updated by : Mahmoud Fayed <[email protected]> Date : 2017.01.29 */ #include <QtWidgets> #include "codeeditor.h" #include "ring.h" CodeEditor::CodeEditor(QWidget *parent, VM *pVM) : GPlainTextEdit(parent,pVM) { lineNumberArea = new LineNumberArea(this); connect(this, SIGNAL(blockCountChanged(int)), this, SLOT(updateLineNumberAreaWidth(int))); connect(this, SIGNAL(updateRequest(QRect,int)), this, SLOT(updateLineNumberArea(QRect,int))); updateLineNumberAreaWidth(0); } int CodeEditor::lineNumberAreaWidth() { int digits = 1; int max = qMax(1, blockCount()); while (max >= 10) { max /= 10; ++digits; } int space = 3 + fontMetrics().width(QLatin1Char('9')) * digits; return space*2; } void CodeEditor::updateLineNumberAreaWidth(int /* newBlockCount */) { setViewportMargins(lineNumberAreaWidth(), 0, 0, 0); } void CodeEditor::updateLineNumberArea(const QRect &rect, int dy) { if (dy) lineNumberArea->scroll(0, dy); else lineNumberArea->update(0, rect.y(), lineNumberArea->width(), rect.height()); if (rect.contains(viewport()->rect())) updateLineNumberAreaWidth(0); } void CodeEditor::resizeEvent(QResizeEvent *e) { QPlainTextEdit::resizeEvent(e); QRect cr = contentsRect(); lineNumberArea->setGeometry(QRect(cr.left(), cr.top(), lineNumberAreaWidth(), cr.height())); } void CodeEditor::lineNumberAreaPaintEvent(QPaintEvent *event) { QPainter painter(lineNumberArea); QFont font = painter.font() ; font.setPointSize(fontMetrics().height()); painter.setFont(font); painter.fillRect(event->rect(), Qt::cyan); QTextBlock block = firstVisibleBlock(); int blockNumber = block.blockNumber(); int top = (int) blockBoundingGeometry(block).translated(contentOffset()).top(); int bottom = top + (int) blockBoundingRect(block).height(); while (block.isValid() && top <= event->rect().bottom()) { if (block.isVisible() && bottom >= event->rect().top()) { QString number = QString::number(blockNumber + 1); painter.setPen(Qt::black); painter.drawText(0, top, lineNumberArea->width(), bottom-top, Qt::AlignCenter, number); } block = block.next(); top = bottom; bottom = top + (int) blockBoundingRect(block).height(); ++blockNumber; } } void CodeEditor::setCompleter(QCompleter *completer) { if (c) QObject::disconnect(c, 0, this, 0); c = completer; if (!c) return; c->setWidget(this); c->setCompletionMode(QCompleter::PopupCompletion); c->setCaseSensitivity(Qt::CaseInsensitive); QObject::connect(c, SIGNAL(activated(QString)), this, SLOT(insertCompletion(QString))); } QCompleter *CodeEditor::completer() const { return c; } void CodeEditor::insertCompletion(const QString& completion) { if (c->widget() != this) return; QTextCursor tc = textCursor(); int extra = completion.length() - c->completionPrefix().length(); tc.movePosition(QTextCursor::Left); tc.movePosition(QTextCursor::EndOfWord); tc.insertText(completion.right(extra)); setTextCursor(tc); } QString CodeEditor::textUnderCursor() const { QTextCursor tc = textCursor(); tc.select(QTextCursor::WordUnderCursor); return tc.selectedText(); } void CodeEditor::focusInEvent(QFocusEvent *e) { if (c) c->setWidget(this); CodeEditor::focusInEvent(e); } void CodeEditor::keyPressEvent(QKeyEvent *e) { if (c && c->popup()->isVisible()) { // The following keys are forwarded by the completer to the widget switch (e->key()) { case Qt::Key_Enter: case Qt::Key_Return: case Qt::Key_Escape: case Qt::Key_Tab: case Qt::Key_Backtab: e->ignore(); return; // let the completer do default behavior default: break; } } bool isShortcut = ((e->modifiers() & Qt::ControlModifier) && e->key() == Qt::Key_E); // CTRL+E if (!c || !isShortcut) // do not process the shortcut when we have a completer CodeEditor::keyPressEvent(e); const bool ctrlOrShift = e->modifiers() & (Qt::ControlModifier | Qt::ShiftModifier); if (!c || (ctrlOrShift && e->text().isEmpty())) return; static QString eow("~!@#$%^&*()_+{}|:\"<>?,./;'[]\\-="); // end of word bool hasModifier = (e->modifiers() != Qt::NoModifier) && !ctrlOrShift; QString completionPrefix = textUnderCursor(); if (!isShortcut && (hasModifier || e->text().isEmpty()|| completionPrefix.length() < 3 || eow.contains(e->text().right(1)))) { c->popup()->hide(); return; } if (completionPrefix != c->completionPrefix()) { c->setCompletionPrefix(completionPrefix); c->popup()->setCurrentIndex(c->completionModel()->index(0, 0)); } QRect cr = cursorRect(); cr.setWidth(c->popup()->sizeHintForColumn(0) + c->popup()->verticalScrollBar()->sizeHint().width()); c->complete(cr); // popup it up! }
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** BSD License Usage ** Alternatively, you may use this file under the terms of the BSD license ** as follows: ** ** "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 Qt Company Ltd 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." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ /* File is modified to be merged with RingQt Updated by : Mahmoud Fayed <[email protected]> Date : 2017.01.29 */ #include <QtWidgets> #include "codeeditor.h" #include "ring.h" CodeEditor::CodeEditor(QWidget *parent, VM *pVM) : GPlainTextEdit(parent,pVM) , c(0) { lineNumberArea = new LineNumberArea(this); connect(this, SIGNAL(blockCountChanged(int)), this, SLOT(updateLineNumberAreaWidth(int))); connect(this, SIGNAL(updateRequest(QRect,int)), this, SLOT(updateLineNumberArea(QRect,int))); updateLineNumberAreaWidth(0); } int CodeEditor::lineNumberAreaWidth() { int digits = 1; int max = qMax(1, blockCount()); while (max >= 10) { max /= 10; ++digits; } int space = 3 + fontMetrics().width(QLatin1Char('9')) * digits; return space*2; } void CodeEditor::updateLineNumberAreaWidth(int /* newBlockCount */) { setViewportMargins(lineNumberAreaWidth(), 0, 0, 0); } void CodeEditor::updateLineNumberArea(const QRect &rect, int dy) { if (dy) lineNumberArea->scroll(0, dy); else lineNumberArea->update(0, rect.y(), lineNumberArea->width(), rect.height()); if (rect.contains(viewport()->rect())) updateLineNumberAreaWidth(0); } void CodeEditor::resizeEvent(QResizeEvent *e) { QPlainTextEdit::resizeEvent(e); QRect cr = contentsRect(); lineNumberArea->setGeometry(QRect(cr.left(), cr.top(), lineNumberAreaWidth(), cr.height())); } void CodeEditor::lineNumberAreaPaintEvent(QPaintEvent *event) { QPainter painter(lineNumberArea); QFont font = painter.font() ; font.setPointSize(fontMetrics().height()); painter.setFont(font); painter.fillRect(event->rect(), Qt::cyan); QTextBlock block = firstVisibleBlock(); int blockNumber = block.blockNumber(); int top = (int) blockBoundingGeometry(block).translated(contentOffset()).top(); int bottom = top + (int) blockBoundingRect(block).height(); while (block.isValid() && top <= event->rect().bottom()) { if (block.isVisible() && bottom >= event->rect().top()) { QString number = QString::number(blockNumber + 1); painter.setPen(Qt::black); painter.drawText(0, top, lineNumberArea->width(), bottom-top, Qt::AlignCenter, number); } block = block.next(); top = bottom; bottom = top + (int) blockBoundingRect(block).height(); ++blockNumber; } } void CodeEditor::setCompleter(QCompleter *completer) { if (c) QObject::disconnect(c, 0, this, 0); c = completer; if (!c) return; c->setWidget(this); c->setCompletionMode(QCompleter::PopupCompletion); c->setCaseSensitivity(Qt::CaseInsensitive); QObject::connect(c, SIGNAL(activated(QString)), this, SLOT(insertCompletion(QString))); } QCompleter *CodeEditor::completer() const { return c; } void CodeEditor::insertCompletion(const QString& completion) { if (c->widget() != this) return; QTextCursor tc = textCursor(); int extra = completion.length() - c->completionPrefix().length(); tc.movePosition(QTextCursor::Left); tc.movePosition(QTextCursor::EndOfWord); tc.insertText(completion.right(extra)); setTextCursor(tc); } QString CodeEditor::textUnderCursor() const { QTextCursor tc = textCursor(); tc.select(QTextCursor::WordUnderCursor); return tc.selectedText(); } void CodeEditor::focusInEvent(QFocusEvent *e) { if (c) c->setWidget(this); GPlainTextEdit::focusInEvent(e); } void CodeEditor::keyPressEvent(QKeyEvent *e) { if (c && c->popup()->isVisible()) { // The following keys are forwarded by the completer to the widget switch (e->key()) { case Qt::Key_Enter: case Qt::Key_Return: case Qt::Key_Escape: case Qt::Key_Tab: case Qt::Key_Backtab: e->ignore(); return; // let the completer do default behavior default: break; } } bool isShortcut = ((e->modifiers() & Qt::ControlModifier) && e->key() == Qt::Key_E); // CTRL+E if (!c || !isShortcut) // do not process the shortcut when we have a completer GPlainTextEdit::keyPressEvent(e); const bool ctrlOrShift = e->modifiers() & (Qt::ControlModifier | Qt::ShiftModifier); if (!c || (ctrlOrShift && e->text().isEmpty())) return; static QString eow("~!@#$%^&*()_+{}|:\"<>?,./;'[]\\-="); // end of word bool hasModifier = (e->modifiers() != Qt::NoModifier) && !ctrlOrShift; QString completionPrefix = textUnderCursor(); if (!isShortcut && (hasModifier || e->text().isEmpty()|| completionPrefix.length() < 3 || eow.contains(e->text().right(1)))) { c->popup()->hide(); return; } if (completionPrefix != c->completionPrefix()) { c->setCompletionPrefix(completionPrefix); c->popup()->setCurrentIndex(c->completionModel()->index(0, 0)); } QRect cr = cursorRect(); cr.setWidth(c->popup()->sizeHintForColumn(0) + c->popup()->verticalScrollBar()->sizeHint().width()); c->complete(cr); // popup it up! }
Update RingQt - codeeditor.cpp
Update RingQt - codeeditor.cpp
C++
mit
ring-lang/ring,ring-lang/ring,ring-lang/ring,ring-lang/ring,ring-lang/ring,ring-lang/ring,ring-lang/ring,ring-lang/ring
f0b9f2b6f0b63738d40877b98fc400a66211fdd1
extensions/ringqt/codeeditor.cpp
extensions/ringqt/codeeditor.cpp
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** BSD License Usage ** Alternatively, you may use this file under the terms of the BSD license ** as follows: ** ** "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 Qt Company Ltd 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." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ /* File is modified to be merged with RingQt Updated by : Mahmoud Fayed <[email protected]> Date : 2017.01.29 */ #include <QtWidgets> #include "codeeditor.h" #include "ring.h" #include <algorithm> CodeEditor::CodeEditor(QWidget *parent, VM *pVM) : GPlainTextEdit(parent,pVM) , c(0) { lineNumberArea = new LineNumberArea(this); this->areaColor = Qt::black; this->areaBackColor = Qt::cyan; connect(this, SIGNAL(blockCountChanged(int)), this, SLOT(updateLineNumberAreaWidth(int))); connect(this, SIGNAL(updateRequest(QRect,int)), this, SLOT(updateLineNumberArea(QRect,int))); updateLineNumberAreaWidth(0); } void CodeEditor::setLineNumbersAreaColor(QColor oColor) { this->areaColor = oColor; } void CodeEditor::setLineNumbersAreaBackColor(QColor oColor) { this->areaBackColor = oColor; } int CodeEditor::lineNumberAreaWidth() { int digits = 1; int max = qMax(1, blockCount()); while (max >= 10) { max /= 10; ++digits; } int space = 3 + fontMetrics().width(QLatin1Char('9')) * digits; return space*2; } void CodeEditor::updateLineNumberAreaWidth(int /* newBlockCount */) { setViewportMargins(lineNumberAreaWidth(), 0, 0, 0); } void CodeEditor::updateLineNumberArea(const QRect &rect, int dy) { if (dy) lineNumberArea->scroll(0, dy); else lineNumberArea->update(0, rect.y(), lineNumberArea->width(), rect.height()); if (rect.contains(viewport()->rect())) updateLineNumberAreaWidth(0); } void CodeEditor::resizeEvent(QResizeEvent *e) { QPlainTextEdit::resizeEvent(e); QRect cr = contentsRect(); lineNumberArea->setGeometry(QRect(cr.left(), cr.top(), lineNumberAreaWidth(), cr.height())); } void CodeEditor::lineNumberAreaPaintEvent(QPaintEvent *event) { QPainter painter(lineNumberArea); QFont font = painter.font() ; font.setPointSize(fontMetrics().height()); painter.setFont(font); painter.fillRect(event->rect(), this->areaBackColor); QTextBlock block = firstVisibleBlock(); int blockNumber = block.blockNumber(); int top = (int) blockBoundingGeometry(block).translated(contentOffset()).top(); int bottom = top + (int) blockBoundingRect(block).height(); while (block.isValid() && top <= event->rect().bottom()) { if (block.isVisible() && bottom >= event->rect().top()) { QString number = QString::number(blockNumber + 1); painter.setPen(this->areaColor); painter.drawText(0, top, lineNumberArea->width(), bottom-top, Qt::AlignCenter, number); } block = block.next(); top = bottom; bottom = top + (int) blockBoundingRect(block).height(); ++blockNumber; } } void CodeEditor::setCompleter(QCompleter *completer) { if (c) { QObject::disconnect(c, 0, this, 0); delete c; } c = completer; if (!c) return; c->setWidget(this); c->setCompletionMode(QCompleter::PopupCompletion); c->setCaseSensitivity(Qt::CaseInsensitive); QObject::connect(c, SIGNAL(activated(QString)), this, SLOT(insertCompletion(QString))); } QCompleter *CodeEditor::completer() const { return c; } void CodeEditor::insertCompletion(const QString& completion) { if (c->widget() != this) return; QTextCursor tc = textCursor(); int extra = completion.length() - c->completionPrefix().length(); tc.movePosition(QTextCursor::Left); tc.movePosition(QTextCursor::EndOfWord); tc.insertText(completion.right(extra)); setTextCursor(tc); } QString CodeEditor::textUnderCursor() const { QTextCursor tc = textCursor(); tc.select(QTextCursor::WordUnderCursor); return tc.selectedText(); } void CodeEditor::focusInEvent(QFocusEvent *e) { if (c) c->setWidget(this); GPlainTextEdit::focusInEvent(e); } void CodeEditor::keyPressEvent(QKeyEvent *e) { QTextCursor cur ; int a ; int p ; int m ; QString str ; QStringList list ; if ( e->key() == Qt::Key_Tab) { cur = textCursor(); a = cur.anchor(); p = cur.position(); cur.setPosition(a); cur.movePosition(QTextCursor::StartOfBlock,QTextCursor::MoveAnchor); a = cur.position(); cur.setPosition(a); cur.setPosition(p, QTextCursor::KeepAnchor); str = cur.selection().toPlainText(); list = str.split("\n"); for (int i = 0; i < list.count(); i++) list[i].insert(0,"\t"); str=list.join("\n"); cur.removeSelectedText(); cur.insertText(str); cur.setPosition(std::min(a,p)); cur.setPosition(std::max(a,p)+list.count(), QTextCursor::KeepAnchor); setTextCursor(cur); e->accept(); return ; } else if ( e->key() == Qt::Key_Backtab) { cur = textCursor(); a = cur.anchor(); p = cur.position(); cur.setPosition(a); cur.movePosition(QTextCursor::StartOfBlock,QTextCursor::MoveAnchor); a = cur.position(); cur.setPosition(a); cur.setPosition(p, QTextCursor::KeepAnchor); str = cur.selection().toPlainText(); list = str.split("\n"); m = 0; for (int i = 0; i < list.count(); i++) { if (list[i][0] == '\t') { list[i] = list[i].right(list[i].count()-1); m++; } } str=list.join("\n"); cur.removeSelectedText(); cur.insertText(str); cur.setPosition(std::min(a,p)); cur.setPosition(std::max(a,p)-m, QTextCursor::KeepAnchor); setTextCursor(cur); e->accept(); return ; } if (c && c->popup()->isVisible()) { // The following keys are forwarded by the completer to the widget switch (e->key()) { case Qt::Key_Enter: case Qt::Key_Return: e->ignore(); return; // let the completer do default behavior case Qt::Key_Escape: case Qt::Key_Backtab: c->popup()->hide(); return; // let the completer do default behavior default: break; } } bool isShortcut = ((e->modifiers() & Qt::ControlModifier) && e->key() == Qt::Key_E); // CTRL+E if (!c || !isShortcut) // do not process the shortcut when we have a completer GPlainTextEdit::keyPressEvent(e); const bool ctrlOrShift = e->modifiers() & (Qt::ControlModifier | Qt::ShiftModifier); if (!c || (ctrlOrShift && e->text().isEmpty())) return; static QString eow("~!#%^&*()+{}|:<>?,/;[]\\-="); // end of word bool hasModifier = (e->modifiers() != Qt::NoModifier) && !ctrlOrShift; QString completionPrefix = textUnderCursor(); if (!isShortcut && (hasModifier || e->text().isEmpty()|| completionPrefix.length() < 3 || eow.contains(e->text().right(1)))) { c->popup()->hide(); return; } if (completionPrefix != c->completionPrefix()) { c->setCompletionPrefix(completionPrefix); c->popup()->setCurrentIndex(c->completionModel()->index(0, 0)); } QRect cr = cursorRect(); cr.setWidth(c->popup()->sizeHintForColumn(0) + c->popup()->verticalScrollBar()->sizeHint().width()); c->complete(cr); // popup it up! }
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** BSD License Usage ** Alternatively, you may use this file under the terms of the BSD license ** as follows: ** ** "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 Qt Company Ltd 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." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ /* File is modified to be merged with RingQt Updated by : Mahmoud Fayed <[email protected]> Date : 2017.01.29 */ #include <QtWidgets> #include "codeeditor.h" #include "ring.h" #include <algorithm> CodeEditor::CodeEditor(QWidget *parent, VM *pVM) : GPlainTextEdit(parent,pVM) , c(0) { lineNumberArea = new LineNumberArea(this); this->areaColor = Qt::black; this->areaBackColor = Qt::cyan; connect(this, SIGNAL(blockCountChanged(int)), this, SLOT(updateLineNumberAreaWidth(int))); connect(this, SIGNAL(updateRequest(QRect,int)), this, SLOT(updateLineNumberArea(QRect,int))); updateLineNumberAreaWidth(0); } void CodeEditor::setLineNumbersAreaColor(QColor oColor) { this->areaColor = oColor; } void CodeEditor::setLineNumbersAreaBackColor(QColor oColor) { this->areaBackColor = oColor; } int CodeEditor::lineNumberAreaWidth() { int digits = 1; int max = qMax(1, blockCount()); while (max >= 10) { max /= 10; ++digits; } int space = 3 + fontMetrics().width(QLatin1Char('9')) * digits; return space*2; } void CodeEditor::updateLineNumberAreaWidth(int /* newBlockCount */) { setViewportMargins(lineNumberAreaWidth(), 0, 0, 0); } void CodeEditor::updateLineNumberArea(const QRect &rect, int dy) { if (dy) lineNumberArea->scroll(0, dy); else lineNumberArea->update(0, rect.y(), lineNumberArea->width(), rect.height()); if (rect.contains(viewport()->rect())) updateLineNumberAreaWidth(0); } void CodeEditor::resizeEvent(QResizeEvent *e) { QPlainTextEdit::resizeEvent(e); QRect cr = contentsRect(); lineNumberArea->setGeometry(QRect(cr.left(), cr.top(), lineNumberAreaWidth(), cr.height())); } void CodeEditor::lineNumberAreaPaintEvent(QPaintEvent *event) { QPainter painter(lineNumberArea); QFont font = painter.font() ; font.setPointSize(fontMetrics().height()); painter.setFont(font); painter.fillRect(event->rect(), this->areaBackColor); QTextBlock block = firstVisibleBlock(); int blockNumber = block.blockNumber(); int top = (int) blockBoundingGeometry(block).translated(contentOffset()).top(); int bottom = top + (int) blockBoundingRect(block).height(); while (block.isValid() && top <= event->rect().bottom()) { if (block.isVisible() && bottom >= event->rect().top()) { QString number = QString::number(blockNumber + 1); painter.setPen(this->areaColor); painter.drawText(0, top, lineNumberArea->width(), bottom-top, Qt::AlignCenter, number); } block = block.next(); top = bottom; bottom = top + (int) blockBoundingRect(block).height(); ++blockNumber; } } void CodeEditor::setCompleter(QCompleter *completer) { if (c) { QObject::disconnect(c, 0, this, 0); delete c; } c = completer; if (!c) return; c->setWidget(this); c->setCompletionMode(QCompleter::PopupCompletion); c->setCaseSensitivity(Qt::CaseInsensitive); QObject::connect(c, SIGNAL(activated(QString)), this, SLOT(insertCompletion(QString))); } QCompleter *CodeEditor::completer() const { return c; } void CodeEditor::insertCompletion(const QString& completion) { if (c->widget() != this) return; QTextCursor tc = textCursor(); int extra = completion.length() - c->completionPrefix().length(); tc.movePosition(QTextCursor::Left); tc.movePosition(QTextCursor::EndOfWord); tc.insertText(completion.right(extra)); setTextCursor(tc); } QString CodeEditor::textUnderCursor() const { QTextCursor tc = textCursor(); tc.select(QTextCursor::WordUnderCursor); return tc.selectedText(); } void CodeEditor::focusInEvent(QFocusEvent *e) { if (c) c->setWidget(this); GPlainTextEdit::focusInEvent(e); } void CodeEditor::keyPressEvent(QKeyEvent *e) { QTextCursor cur ; int a ; int p ; int m ; QString str ; QStringList list ; if ( e->key() == Qt::Key_Tab) { blockSignals(true); cur = textCursor(); a = cur.anchor(); p = cur.position(); cur.setPosition(a); cur.movePosition(QTextCursor::StartOfBlock,QTextCursor::MoveAnchor); a = cur.position(); cur.setPosition(a); cur.setPosition(p, QTextCursor::KeepAnchor); str = cur.selection().toPlainText(); list = str.split("\n"); for (int i = 0; i < list.count(); i++) list[i].insert(0,"\t"); str=list.join("\n"); cur.removeSelectedText(); cur.insertText(str); cur.setPosition(std::min(a,p)); cur.setPosition(std::max(a,p)+list.count(), QTextCursor::KeepAnchor); setTextCursor(cur); e->accept(); blockSignals(false); return ; } else if ( e->key() == Qt::Key_Backtab) { blockSignals(true); cur = textCursor(); a = cur.anchor(); p = cur.position(); cur.setPosition(a); cur.movePosition(QTextCursor::StartOfBlock,QTextCursor::MoveAnchor); a = cur.position(); cur.setPosition(a); cur.setPosition(p, QTextCursor::KeepAnchor); str = cur.selection().toPlainText(); list = str.split("\n"); m = 0; for (int i = 0; i < list.count(); i++) { if (list[i][0] == '\t') { list[i] = list[i].right(list[i].count()-1); m++; } } str=list.join("\n"); cur.removeSelectedText(); cur.insertText(str); cur.setPosition(std::min(a,p)); cur.setPosition(std::max(a,p)-m, QTextCursor::KeepAnchor); setTextCursor(cur); e->accept(); blockSignals(false); return ; } if (c && c->popup()->isVisible()) { // The following keys are forwarded by the completer to the widget switch (e->key()) { case Qt::Key_Enter: case Qt::Key_Return: e->ignore(); return; // let the completer do default behavior case Qt::Key_Escape: case Qt::Key_Backtab: c->popup()->hide(); return; // let the completer do default behavior default: break; } } bool isShortcut = ((e->modifiers() & Qt::ControlModifier) && e->key() == Qt::Key_E); // CTRL+E if (!c || !isShortcut) // do not process the shortcut when we have a completer GPlainTextEdit::keyPressEvent(e); const bool ctrlOrShift = e->modifiers() & (Qt::ControlModifier | Qt::ShiftModifier); if (!c || (ctrlOrShift && e->text().isEmpty())) return; static QString eow("~!#%^&*()+{}|:<>?,/;[]\\-="); // end of word bool hasModifier = (e->modifiers() != Qt::NoModifier) && !ctrlOrShift; QString completionPrefix = textUnderCursor(); if (!isShortcut && (hasModifier || e->text().isEmpty()|| completionPrefix.length() < 3 || eow.contains(e->text().right(1)))) { c->popup()->hide(); return; } if (completionPrefix != c->completionPrefix()) { c->setCompletionPrefix(completionPrefix); c->popup()->setCurrentIndex(c->completionModel()->index(0, 0)); } QRect cr = cursorRect(); cr.setWidth(c->popup()->sizeHintForColumn(0) + c->popup()->verticalScrollBar()->sizeHint().width()); c->complete(cr); // popup it up! }
Update RingQt - codeeditor.cpp - use blockSignals()
Update RingQt - codeeditor.cpp - use blockSignals()
C++
mit
ring-lang/ring,ring-lang/ring,ring-lang/ring,ring-lang/ring,ring-lang/ring,ring-lang/ring,ring-lang/ring,ring-lang/ring
de3ae50aef191e8f7cb21700a334ad48dff22487
indexer.cc
indexer.cc
#include "indexer.h" #include <gflags/gflags.h> #include <list> #include <stdarg.h> DEFINE_bool(debug_index, false, "Debug the index query generator."); static void __index_debug(const char *format, ...) __attribute__((format (printf, 1, 2))); #define debug(fmt, ...) do { \ if (FLAGS_debug_index) \ __index_debug(fmt, ## __VA_ARGS__); \ } while(0) static void __index_debug(const char *format, ...) { if (!FLAGS_debug_index) return; va_list ap; va_start(ap, format); vprintf(format, ap); va_end(ap); } using namespace re2; using namespace std; const unsigned kMinWeight = 16; const int kMaxWidth = 32; double IndexKey::selectivity() { if (this == 0) return 1.0; if (empty()) return 1.0; double s = 0.0; for (IndexKey::iterator it = begin(); it != end(); ++it) s += double(it->first.second - it->first.first + 1)/128 * it->second->selectivity(); return s; } unsigned IndexKey::weight() { if (1/selectivity() > double(numeric_limits<unsigned>::max())) return numeric_limits<unsigned>::max() / 2; return 1/selectivity(); } void IndexKey::collect_tails(list<IndexKey::iterator>& tails) { if (this == 0) return; for (IndexKey::iterator it = begin(); it != end(); ++it) { if (!it->second) tails.push_back(it); else it->second->collect_tails(tails); } } void IndexKey::concat(shared_ptr<IndexKey> rhs) { assert(anchor & kAnchorRight); assert(rhs->anchor & kAnchorLeft); assert(!empty()); list<IndexKey::iterator> tails; collect_tails(tails); for (auto it = tails.begin(); it != tails.end(); ++it) { if (!(*it)->second) (*it)->second = rhs; } if (anchor & kAnchorRepeat) anchor &= ~kAnchorLeft; if ((rhs->anchor & (kAnchorRepeat|kAnchorRight)) != kAnchorRight) anchor &= ~kAnchorRight; } static string strprintf(const char *fmt, ...) __attribute__((format (printf, 1, 2))); static string strprintf(const char *fmt, ...) { char buf[4096]; va_list ap; va_start(ap, fmt); vsnprintf(buf, sizeof buf, fmt, ap); va_end(ap); return string(buf); } static string ToString(IndexKey *k, int indent = 0) { string out; if (k == 0) return strprintf("%*.s[]\n", indent, ""); for (IndexKey::iterator it = k->begin(); it != k->end(); ++it) { out += strprintf("%*.s[%c-%c] -> \n", indent, "", it->first.first, it->first.second); out += ToString(it->second.get(), indent + 1); } return out; } string IndexKey::ToString() { string out = ::ToString(this, 0); if (this == 0) return out; out += "|"; if (anchor & kAnchorLeft) out += "<"; if (anchor & kAnchorRepeat) out += "*"; if (anchor & kAnchorRight) out += ">"; return out; } class IndexWalker : public Regexp::Walker<shared_ptr<IndexKey> > { public: IndexWalker() { } virtual shared_ptr<IndexKey> PostVisit(Regexp* re, shared_ptr<IndexKey> parent_arg, shared_ptr<IndexKey> pre_arg, shared_ptr<IndexKey> *child_args, int nchild_args); virtual shared_ptr<IndexKey> ShortVisit(Regexp* re, shared_ptr<IndexKey> parent_arg); private: IndexWalker(const IndexWalker&); void operator=(const IndexWalker&); }; namespace { string RuneToString(Rune r) { char buf[UTFmax]; int n = runetochar(buf, &r); return string(buf, n); } shared_ptr<IndexKey> Any() { return shared_ptr<IndexKey>(0); } shared_ptr<IndexKey> Empty() { return shared_ptr<IndexKey>(new IndexKey(kAnchorBoth)); } shared_ptr<IndexKey> Literal(string s) { shared_ptr<IndexKey> k = 0; for (string::reverse_iterator it = s.rbegin(); it != s.rend(); ++it) { k = shared_ptr<IndexKey>(new IndexKey(pair<uchar, uchar>(*it, *it), k)); } k->anchor = kAnchorBoth; return k; } shared_ptr<IndexKey> Literal(Rune r) { return Literal(RuneToString(r)); } shared_ptr<IndexKey> Literal(Rune *runes, int nrunes) { string lit; for (int i = 0; i < nrunes; i++) { lit.append(RuneToString(runes[i])); } return Literal(lit); } shared_ptr<IndexKey> CClass(CharClass *cc) { if (cc->size() > kMaxWidth) return Any(); shared_ptr<IndexKey> k(new IndexKey(kAnchorBoth)); for (CharClass::iterator i = cc->begin(); i != cc->end(); ++i) { /* TODO: Handle arbitrary unicode ranges. Probably have to convert to UTF-8 ranges ourselves.*/ assert (i->lo < Runeself); assert (i->hi < Runeself); k->insert(IndexKey::value_type (pair<uchar, uchar>(i->lo, i->hi), 0)); } return k; } shared_ptr<IndexKey> Concat(shared_ptr<IndexKey> lhs, shared_ptr<IndexKey> rhs) { shared_ptr<IndexKey> out = lhs; debug("Concat([%s](%d), [%s](%d)) = ", lhs->ToString().c_str(), lhs->weight(), rhs->ToString().c_str(), rhs->weight()); if (lhs && rhs && (lhs->anchor & kAnchorRight) && (rhs->anchor & kAnchorLeft) && !lhs->empty() && !rhs->empty()) { lhs->concat(rhs); out = lhs; } else if (lhs) { lhs->anchor &= ~kAnchorRight; } if (rhs && rhs->weight() > out->weight()) { out = rhs; out->anchor &= ~kAnchorLeft; } debug("[%s]\n", out->ToString().c_str()); return out; } bool intersects(const pair<uchar, uchar>& left, const pair<uchar, uchar>& right) { if (left.first <= right.first) return left.second >= right.first; else return right.second >= left.first; } enum { kTakeLeft = 0x01, kTakeRight = 0x02, kTakeBoth = 0x03 }; shared_ptr<IndexKey> Alternate(shared_ptr<IndexKey> lhs, shared_ptr<IndexKey> rhs); int Merge(shared_ptr<IndexKey> out, pair<uchar, uchar>& left, shared_ptr<IndexKey> lnext, pair<uchar, uchar>& right, shared_ptr<IndexKey> rnext) { if (intersects(left, right)) { debug("Processing intersection: <%hhx,%hhx> vs. <%hhx,%hhx>\n", left.first, left.second, right.first, right.second); if (left.first < right.first) { out->insert (make_pair(make_pair(left.first, right.first - 1), lnext)); left.first = right.first; } else if (right.first < left.first) { out->insert (make_pair(make_pair(right.first, left.first - 1), rnext)); right.first = left.first; } /* left and right now start at the same location */ assert(left.first == right.first); uchar end = min(left.second, right.second); out->insert (make_pair(make_pair(left.first, end), Alternate(lnext, rnext))); if (left.second > end) { left.first = end+1; return kTakeRight; } else if (right.second > end) { right.first = end+1; return kTakeLeft; } return kTakeBoth; } /* Non-intersecting */ if (left.first < right.first) { out->insert(make_pair(left, lnext)); return kTakeLeft; } assert(right.first < left.first); out->insert(make_pair(right, rnext)); return kTakeRight; } shared_ptr<IndexKey> Alternate(shared_ptr<IndexKey> lhs, shared_ptr<IndexKey> rhs) { if (lhs == rhs) return lhs; if (lhs == 0 || rhs == 0 || lhs->size() + rhs->size() >= kMaxWidth) return Any(); shared_ptr<IndexKey> out(new IndexKey ((lhs->anchor & rhs->anchor) | ((lhs->anchor | lhs->anchor) & kAnchorRepeat))); IndexKey::const_iterator lit, rit; lit = lhs->begin(); rit = rhs->begin(); pair<uchar, uchar> left; if (lit != lhs->end()) left = lit->first; pair<uchar, uchar> right = rit->first; if (rit != rhs->end()) right = rit->first; while (lit != lhs->end() && rit != rhs->end()) { int action = Merge(out, left, lit->second, right, rit->second); if (action & kTakeLeft) if (++lit != lhs->end()) left = lit->first; if (action & kTakeRight) if (++rit != rhs->end()) right = rit->first; } if (lit != lhs->end()) { out->insert(make_pair(left, lit->second)); ++lit; } if (rit != rhs->end()) { out->insert(make_pair(right, rit->second)); ++rit; } for (; lit != lhs->end(); ++lit) out->insert(*lit); for (; rit != rhs->end(); ++rit) out->insert(*rit); return out; } }; shared_ptr<IndexKey> indexRE(const re2::RE2 &re) { IndexWalker walk; shared_ptr<IndexKey> key = walk.Walk(re.Regexp(), 0); if (key && key->weight() < kMinWeight) key = 0; return key; } shared_ptr<IndexKey> IndexWalker::PostVisit(Regexp* re, shared_ptr<IndexKey> parent_arg, shared_ptr<IndexKey> pre_arg, shared_ptr<IndexKey> *child_args, int nchild_args) { shared_ptr<IndexKey> key; switch (re->op()) { case kRegexpNoMatch: case kRegexpEmptyMatch: // anywhere case kRegexpBeginLine: // at beginning of line case kRegexpEndLine: // at end of line case kRegexpBeginText: // at beginning of text case kRegexpEndText: // at end of text case kRegexpWordBoundary: // at word boundary case kRegexpNoWordBoundary: // not at word boundary key = Empty(); break; case kRegexpAnyChar: case kRegexpAnyByte: key = Any(); break; case kRegexpLiteral: key = Literal(re->rune()); break; case kRegexpCharClass: key = CClass(re->cc()); break; case kRegexpLiteralString: key = Literal(re->runes(), re->nrunes()); break; case kRegexpConcat: key = Empty(); for (int i = 0; i < nchild_args; i++) key = Concat(key, child_args[i]); break; case kRegexpAlternate: key = child_args[0]; for (int i = 1; i < nchild_args; i++) key = Alternate(key, child_args[i]); break; case kRegexpStar: case kRegexpQuest: key = Any(); break; case kRegexpCapture: key = child_args[0]; break; case kRegexpRepeat: if (re->min() == 0) return Any(); case kRegexpPlus: key = child_args[0]; if ((key->anchor & kAnchorBoth) == kAnchorBoth) key->anchor |= kAnchorRepeat; break; default: assert(false); } debug("* INDEX %s ==> [%s](%d)\n", re->ToString().c_str(), key->ToString().c_str(), key->weight()); if (FLAGS_debug_index && key) key->check_rep(); return key; } shared_ptr<IndexKey> IndexWalker::ShortVisit(Regexp* re, shared_ptr<IndexKey> parent_arg) { return Any(); } void IndexKey::check_rep() { pair<uchar, uchar> last = make_pair('\0', '\0'); for (iterator it = begin(); it != end(); ++it) { assert(!intersects(last, it->first)); last = it->first; } }
#include "indexer.h" #include <gflags/gflags.h> #include <list> #include <stdarg.h> DEFINE_bool(debug_index, false, "Debug the index query generator."); static void __index_debug(const char *format, ...) __attribute__((format (printf, 1, 2))); #define debug(fmt, ...) do { \ if (FLAGS_debug_index) \ __index_debug(fmt, ## __VA_ARGS__); \ } while(0) static void __index_debug(const char *format, ...) { if (!FLAGS_debug_index) return; va_list ap; va_start(ap, format); vprintf(format, ap); va_end(ap); } using namespace re2; using namespace std; const unsigned kMinWeight = 16; const int kMaxWidth = 32; double IndexKey::selectivity() { if (this == 0) return 1.0; if (empty()) return 1.0; double s = 0.0; for (IndexKey::iterator it = begin(); it != end(); ++it) s += double(it->first.second - it->first.first + 1)/128 * it->second->selectivity(); return s; } unsigned IndexKey::weight() { if (1/selectivity() > double(numeric_limits<unsigned>::max())) return numeric_limits<unsigned>::max() / 2; return 1/selectivity(); } void IndexKey::collect_tails(list<IndexKey::iterator>& tails) { if (this == 0) return; for (IndexKey::iterator it = begin(); it != end(); ++it) { if (!it->second) tails.push_back(it); else it->second->collect_tails(tails); } } void IndexKey::concat(shared_ptr<IndexKey> rhs) { assert(anchor & kAnchorRight); assert(rhs->anchor & kAnchorLeft); assert(!empty()); list<IndexKey::iterator> tails; collect_tails(tails); for (auto it = tails.begin(); it != tails.end(); ++it) { if (!(*it)->second) (*it)->second = rhs; } if (anchor & kAnchorRepeat) anchor &= ~kAnchorLeft; if ((rhs->anchor & (kAnchorRepeat|kAnchorRight)) != kAnchorRight) anchor &= ~kAnchorRight; } static string strprintf(const char *fmt, ...) __attribute__((format (printf, 1, 2))); static string strprintf(const char *fmt, ...) { char buf[4096]; va_list ap; va_start(ap, fmt); vsnprintf(buf, sizeof buf, fmt, ap); va_end(ap); return string(buf); } static string ToString(IndexKey *k, int indent = 0) { string out; if (k == 0) return strprintf("%*.s[]\n", indent, ""); for (IndexKey::iterator it = k->begin(); it != k->end(); ++it) { out += strprintf("%*.s[%c-%c] -> \n", indent, "", it->first.first, it->first.second); out += ToString(it->second.get(), indent + 1); } return out; } string IndexKey::ToString() { string out = ::ToString(this, 0); if (this == 0) return out; out += "|"; if (anchor & kAnchorLeft) out += "<"; if (anchor & kAnchorRepeat) out += "*"; if (anchor & kAnchorRight) out += ">"; return out; } class IndexWalker : public Regexp::Walker<shared_ptr<IndexKey> > { public: IndexWalker() { } virtual shared_ptr<IndexKey> PostVisit(Regexp* re, shared_ptr<IndexKey> parent_arg, shared_ptr<IndexKey> pre_arg, shared_ptr<IndexKey> *child_args, int nchild_args); virtual shared_ptr<IndexKey> ShortVisit(Regexp* re, shared_ptr<IndexKey> parent_arg); private: IndexWalker(const IndexWalker&); void operator=(const IndexWalker&); }; namespace { string RuneToString(Rune r) { char buf[UTFmax]; int n = runetochar(buf, &r); return string(buf, n); } shared_ptr<IndexKey> Any() { return shared_ptr<IndexKey>(0); } shared_ptr<IndexKey> Empty() { return shared_ptr<IndexKey>(new IndexKey(kAnchorBoth)); } shared_ptr<IndexKey> Literal(string s) { shared_ptr<IndexKey> k = 0; for (string::reverse_iterator it = s.rbegin(); it != s.rend(); ++it) { k = shared_ptr<IndexKey>(new IndexKey(pair<uchar, uchar>(*it, *it), k)); } k->anchor = kAnchorBoth; return k; } shared_ptr<IndexKey> Literal(Rune r) { return Literal(RuneToString(r)); } shared_ptr<IndexKey> Literal(Rune *runes, int nrunes) { string lit; for (int i = 0; i < nrunes; i++) { lit.append(RuneToString(runes[i])); } return Literal(lit); } shared_ptr<IndexKey> CClass(CharClass *cc) { if (cc->size() > kMaxWidth) return Any(); shared_ptr<IndexKey> k(new IndexKey(kAnchorBoth)); for (CharClass::iterator i = cc->begin(); i != cc->end(); ++i) { /* TODO: Handle arbitrary unicode ranges. Probably have to convert to UTF-8 ranges ourselves.*/ assert (i->lo < Runeself); assert (i->hi < Runeself); k->insert(IndexKey::value_type (pair<uchar, uchar>(i->lo, i->hi), 0)); } return k; } shared_ptr<IndexKey> Concat(shared_ptr<IndexKey> lhs, shared_ptr<IndexKey> rhs) { assert(lhs); shared_ptr<IndexKey> out = lhs; debug("Concat([%s](%d), [%s](%d)) = ", lhs->ToString().c_str(), lhs->weight(), rhs->ToString().c_str(), rhs->weight()); if (lhs && rhs && (lhs->anchor & kAnchorRight) && (rhs->anchor & kAnchorLeft) && !lhs->empty() && !rhs->empty()) { out->concat(rhs); } else { out->anchor &= ~kAnchorRight; } if (rhs && rhs->weight() > out->weight()) { out = rhs; out->anchor &= ~kAnchorLeft; } debug("[%s]\n", out->ToString().c_str()); return out; } bool intersects(const pair<uchar, uchar>& left, const pair<uchar, uchar>& right) { if (left.first <= right.first) return left.second >= right.first; else return right.second >= left.first; } enum { kTakeLeft = 0x01, kTakeRight = 0x02, kTakeBoth = 0x03 }; shared_ptr<IndexKey> Alternate(shared_ptr<IndexKey> lhs, shared_ptr<IndexKey> rhs); int Merge(shared_ptr<IndexKey> out, pair<uchar, uchar>& left, shared_ptr<IndexKey> lnext, pair<uchar, uchar>& right, shared_ptr<IndexKey> rnext) { if (intersects(left, right)) { debug("Processing intersection: <%hhx,%hhx> vs. <%hhx,%hhx>\n", left.first, left.second, right.first, right.second); if (left.first < right.first) { out->insert (make_pair(make_pair(left.first, right.first - 1), lnext)); left.first = right.first; } else if (right.first < left.first) { out->insert (make_pair(make_pair(right.first, left.first - 1), rnext)); right.first = left.first; } /* left and right now start at the same location */ assert(left.first == right.first); uchar end = min(left.second, right.second); out->insert (make_pair(make_pair(left.first, end), Alternate(lnext, rnext))); if (left.second > end) { left.first = end+1; return kTakeRight; } else if (right.second > end) { right.first = end+1; return kTakeLeft; } return kTakeBoth; } /* Non-intersecting */ if (left.first < right.first) { out->insert(make_pair(left, lnext)); return kTakeLeft; } assert(right.first < left.first); out->insert(make_pair(right, rnext)); return kTakeRight; } shared_ptr<IndexKey> Alternate(shared_ptr<IndexKey> lhs, shared_ptr<IndexKey> rhs) { if (lhs == rhs) return lhs; if (lhs == 0 || rhs == 0 || lhs->size() + rhs->size() >= kMaxWidth) return Any(); shared_ptr<IndexKey> out(new IndexKey ((lhs->anchor & rhs->anchor) | ((lhs->anchor | lhs->anchor) & kAnchorRepeat))); IndexKey::const_iterator lit, rit; lit = lhs->begin(); rit = rhs->begin(); pair<uchar, uchar> left; if (lit != lhs->end()) left = lit->first; pair<uchar, uchar> right = rit->first; if (rit != rhs->end()) right = rit->first; while (lit != lhs->end() && rit != rhs->end()) { int action = Merge(out, left, lit->second, right, rit->second); if (action & kTakeLeft) if (++lit != lhs->end()) left = lit->first; if (action & kTakeRight) if (++rit != rhs->end()) right = rit->first; } if (lit != lhs->end()) { out->insert(make_pair(left, lit->second)); ++lit; } if (rit != rhs->end()) { out->insert(make_pair(right, rit->second)); ++rit; } for (; lit != lhs->end(); ++lit) out->insert(*lit); for (; rit != rhs->end(); ++rit) out->insert(*rit); return out; } }; shared_ptr<IndexKey> indexRE(const re2::RE2 &re) { IndexWalker walk; shared_ptr<IndexKey> key = walk.Walk(re.Regexp(), 0); if (key && key->weight() < kMinWeight) key = 0; return key; } shared_ptr<IndexKey> IndexWalker::PostVisit(Regexp* re, shared_ptr<IndexKey> parent_arg, shared_ptr<IndexKey> pre_arg, shared_ptr<IndexKey> *child_args, int nchild_args) { shared_ptr<IndexKey> key; switch (re->op()) { case kRegexpNoMatch: case kRegexpEmptyMatch: // anywhere case kRegexpBeginLine: // at beginning of line case kRegexpEndLine: // at end of line case kRegexpBeginText: // at beginning of text case kRegexpEndText: // at end of text case kRegexpWordBoundary: // at word boundary case kRegexpNoWordBoundary: // not at word boundary key = Empty(); break; case kRegexpAnyChar: case kRegexpAnyByte: key = Any(); break; case kRegexpLiteral: key = Literal(re->rune()); break; case kRegexpCharClass: key = CClass(re->cc()); break; case kRegexpLiteralString: key = Literal(re->runes(), re->nrunes()); break; case kRegexpConcat: key = Empty(); for (int i = 0; i < nchild_args; i++) key = Concat(key, child_args[i]); break; case kRegexpAlternate: key = child_args[0]; for (int i = 1; i < nchild_args; i++) key = Alternate(key, child_args[i]); break; case kRegexpStar: case kRegexpQuest: key = Any(); break; case kRegexpCapture: key = child_args[0]; break; case kRegexpRepeat: if (re->min() == 0) return Any(); case kRegexpPlus: key = child_args[0]; if ((key->anchor & kAnchorBoth) == kAnchorBoth) key->anchor |= kAnchorRepeat; break; default: assert(false); } debug("* INDEX %s ==> [%s](%d)\n", re->ToString().c_str(), key->ToString().c_str(), key->weight()); if (FLAGS_debug_index && key) key->check_rep(); return key; } shared_ptr<IndexKey> IndexWalker::ShortVisit(Regexp* re, shared_ptr<IndexKey> parent_arg) { return Any(); } void IndexKey::check_rep() { pair<uchar, uchar> last = make_pair('\0', '\0'); for (iterator it = begin(); it != end(); ++it) { assert(!intersects(last, it->first)); last = it->first; } }
Make explicit the assumption that Concat is always called with a non-null LHS.
Make explicit the assumption that Concat is always called with a non-null LHS.
C++
bsd-2-clause
paulproteus/livegrep,wfxiang08/livegrep,paulproteus/livegrep,lekkas/livegrep,paulproteus/livegrep,lekkas/livegrep,wfxiang08/livegrep,wfxiang08/livegrep,lekkas/livegrep,wfxiang08/livegrep,lekkas/livegrep,paulproteus/livegrep,paulproteus/livegrep,wfxiang08/livegrep,wfxiang08/livegrep,lekkas/livegrep,paulproteus/livegrep,lekkas/livegrep
a6881edc1b823c4ecccf7e4ab18c6ee0463c9ab7
korganizer/archivedialog.cpp
korganizer/archivedialog.cpp
/* This file is part of KOrganizer. Copyright (c) 2000,2001 Cornelius Schumacher <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ // ArchiveDialog -- archive/delete past appointments. #include <qlabel.h> #include <qlayout.h> #include <qdatetime.h> #include <qcheckbox.h> #include <qwhatsthis.h> #include <kdebug.h> #include <klocale.h> #include <kurlrequester.h> #include <kmessagebox.h> #include <kglobal.h> #include <kfiledialog.h> #include <kurl.h> #include <ktempfile.h> #include <kio/netaccess.h> #include <klineedit.h> #include <kactivelabel.h> #include <libkcal/event.h> #include <libkcal/calendar.h> #include <libkcal/calendarlocal.h> #include <libkcal/filestorage.h> #include <libkdepim/kdateedit.h> #include "koprefs.h" #include "archivedialog.h" #include "archivedialog.moc" ArchiveDialog::ArchiveDialog(Calendar *cal,QWidget *parent, const char *name) : KDialogBase (Plain,i18n("Archive/Delete Past Appointments"), User1|Cancel,User1,parent,name,false,true, i18n("&Archive")) { mCalendar = cal; QFrame *topFrame = plainPage(); QVBoxLayout *topLayout = new QVBoxLayout(topFrame); topLayout->setSpacing(spacingHint()); KActiveLabel *descLabel = new KActiveLabel( i18n("Archiving saves old appointments into the given file and " "then deletes them in the current calendar. If the archive file " "already exists they will be added. " "(<a href=\"whatsthis:In order to add an archive " "to your calendar, use the &quot;Merge Calendar&quot; function. " "You can view an archive by opening it in KOrganizer like any " "other calendar. It is not saved in a special format, but as " "vCalendar.\">How to restore</a>)"), topFrame); topLayout->addWidget(descLabel); QHBoxLayout *dateLayout = new QHBoxLayout(0); QLabel *dateLabel = new QLabel(i18n("A&ppointments older than:"),topFrame); dateLayout->addWidget(dateLabel); mDateEdit = new KDateEdit(topFrame); QWhatsThis::add(mDateEdit, i18n("The age of the appointments to archive. All older appointments " "will be saved and deleted, the newer will be kept.")); dateLabel->setBuddy(mDateEdit); dateLayout->addWidget(mDateEdit); topLayout->addLayout(dateLayout); QHBoxLayout *fileLayout = new QHBoxLayout(0); fileLayout->setSpacing(spacingHint()); QLabel *l = new QLabel(i18n("Archive &file:"),topFrame); fileLayout->addWidget(l); mArchiveFile = new KURLRequester(KOPrefs::instance()->mArchiveFile,topFrame); mArchiveFile->setMode(KFile::File); mArchiveFile->setFilter(i18n("*.vcs|vCalendar Files")); QWhatsThis::add(mArchiveFile, i18n("The path of the archive. The appointments will be added to the " "archive file, so any appointments that are already in the file " "will not be modified or deleted. You can later load or merge the " "file like any other calendar. It is not saved in a special " "format, it uses the vCalendar format. ")); l->setBuddy(mArchiveFile->lineEdit()); fileLayout->addWidget(mArchiveFile); topLayout->addLayout(fileLayout); mDeleteCb = new QCheckBox(i18n("&Delete only, do not save"), topFrame); QWhatsThis::add(mDeleteCb, i18n("Select this option to delete old appointments without saving them." "It is not possible to recover the appointments later.")); topLayout->addWidget(mDeleteCb); connect(mDeleteCb, SIGNAL(toggled(bool)), mArchiveFile, SLOT(setDisabled(bool))); connect(mDeleteCb, SIGNAL(toggled(bool)), this, SLOT(slotEnableUser1())); connect(mArchiveFile->lineEdit(),SIGNAL(textChanged ( const QString & )), this,SLOT(slotEnableUser1())); enableButton(KDialogBase::User1,!mArchiveFile->lineEdit()->text().isEmpty()); } ArchiveDialog::~ArchiveDialog() { } void ArchiveDialog::slotEnableUser1() { bool state = ( mDeleteCb->isChecked() || !mArchiveFile->lineEdit()->text().isEmpty() ); enableButton(KDialogBase::User1,state); } // Archive old events void ArchiveDialog::slotUser1() { if (mDeleteCb->isChecked()) { deleteOldEvents(); return; } // Get destination URL KURL destUrl = mArchiveFile->url(); if ( !destUrl.isValid() ) { KMessageBox::sorry(this,i18n("The archive file name is not valid.\n")); return; } // Force filename to be ending with vCalendar extension QString filename = destUrl.fileName(); if (filename.right(4) != ".vcs") { filename.append(".vcs"); destUrl.setFileName(filename); } // Get events to be archived Event::List events = mCalendar->events( QDate( 1800, 1, 1 ), mDateEdit->date().addDays( -1 ), true ); if ( events.count() == 0 ) { KMessageBox::sorry(this,i18n("There are no events before %1") .arg(KGlobal::locale()->formatDate(mDateEdit->date()))); return; } FileStorage storage( mCalendar ); // Save current calendar to disk KTempFile tmpFile; tmpFile.setAutoDelete(true); storage.setFileName( tmpFile.name() ); if ( !storage.save() ) { kdDebug(5850) << "ArchiveDialog::slotUser1(): Can't save calendar to temp file" << endl; return; } // Duplicate current calendar by loading in new calendar object CalendarLocal archiveCalendar( KOPrefs::instance()->mTimeZoneId ); FileStorage archiveStore( &archiveCalendar ); archiveStore.setFileName( tmpFile.name() ); if (!archiveStore.load()) { kdDebug(5850) << "ArchiveDialog::slotUser1(): Can't load calendar from temp file" << endl; return; } // Strip active events from calendar so that only events to be archived // remain. Event::List activeEvents = archiveCalendar.events( mDateEdit->date(), QDate( 3000, 1, 1 ), false ); Event::List::ConstIterator it; for( it = activeEvents.begin(); it != activeEvents.end(); ++it ) { archiveCalendar.deleteEvent( *it ); } // Get or create the archive file QString archiveFile; if ( KIO::NetAccess::exists( destUrl, true, this ) ) { if( !KIO::NetAccess::download( destUrl, archiveFile, this ) ) { kdDebug(5850) << "ArchiveDialog::slotUser1(): Can't download archive file" << endl; return; } // Merge with events to be archived. archiveStore.setFileName( archiveFile ); if ( !archiveStore.load() ) { kdDebug(5850) << "ArchiveDialog::slotUser1(): Can't merge with archive file" << endl; return; } /* QPtrList<Event> es = archiveCalendar.events(QDate(1800,1,1), QDate(3000,1,1), false); kdDebug(5850) << "--Following events in archive calendar:" << endl; Event *e; for(e=es.first();e;e=es.next()) { kdDebug(5850) << "-----Event: " << e->getSummary() << endl; } */ } else { archiveFile = tmpFile.name(); } // Save archive calendar if ( !archiveStore.save() ) { KMessageBox::error(this,i18n("Cannot write archive file.")); return; } // Upload if necessary KURL srcUrl; srcUrl.setPath(archiveFile); if (srcUrl != destUrl) { if ( !KIO::NetAccess::upload( archiveFile, destUrl, this ) ) { KMessageBox::error(this,i18n("Cannot write archive to final destination.")); return; } } KOPrefs::instance()->mArchiveFile = destUrl.url(); KIO::NetAccess::removeTempFile(archiveFile); // Delete archived events from calendar for( it = events.begin(); it != events.end(); ++it ) { mCalendar->deleteEvent( *it ); } emit eventsDeleted(); accept(); } // Delete old events void ArchiveDialog::deleteOldEvents() { Event::List events = mCalendar->events( QDate( 1769, 12, 1 ), mDateEdit->date().addDays( -1 ), true ); if ( events.count() == 0 ) { KMessageBox::sorry(this,i18n("There are no events before %1") .arg(KGlobal::locale()->formatDate(mDateEdit->date()))); return; } QStringList eventStrs; Event::List::ConstIterator it; for( it = events.begin(); it != events.end(); ++it ) { eventStrs.append( (*it)->summary() ); } int result = KMessageBox::warningContinueCancelList(this, i18n("Delete all events before %1 without saving?\n" "The following events will be deleted:") .arg(KGlobal::locale()->formatDate(mDateEdit->date())),eventStrs, i18n("Delete old events"),i18n("&Delete")); if (result == KMessageBox::Continue) { for( it = events.begin(); it != events.end(); ++it ) { mCalendar->deleteEvent( *it ); } emit eventsDeleted(); accept(); } }
/* This file is part of KOrganizer. Copyright (c) 2000,2001 Cornelius Schumacher <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ // ArchiveDialog -- archive/delete past appointments. #include <qlabel.h> #include <qlayout.h> #include <qdatetime.h> #include <qcheckbox.h> #include <qwhatsthis.h> #include <kdebug.h> #include <klocale.h> #include <kurlrequester.h> #include <kmessagebox.h> #include <kglobal.h> #include <kfiledialog.h> #include <kurl.h> #include <ktempfile.h> #include <kio/netaccess.h> #include <klineedit.h> #include <kactivelabel.h> #include <libkcal/event.h> #include <libkcal/calendar.h> #include <libkcal/calendarlocal.h> #include <libkcal/filestorage.h> #include <libkdepim/kdateedit.h> #include "koprefs.h" #include "archivedialog.h" #include "archivedialog.moc" ArchiveDialog::ArchiveDialog(Calendar *cal,QWidget *parent, const char *name) : KDialogBase (Plain,i18n("Archive/Delete Past Appointments"), User1|Cancel,User1,parent,name,false,true, i18n("&Archive")) { mCalendar = cal; QFrame *topFrame = plainPage(); QVBoxLayout *topLayout = new QVBoxLayout(topFrame); topLayout->setSpacing(spacingHint()); KActiveLabel *descLabel = new KActiveLabel( i18n("Archiving saves old appointments into the given file and " "then deletes them in the current calendar. If the archive file " "already exists they will be added. " "(<a href=\"whatsthis:In order to add an archive " "to your calendar, use the &quot;Merge Calendar&quot; function. " "You can view an archive by opening it in KOrganizer like any " "other calendar. It is not saved in a special format, but as " "vCalendar.\">How to restore</a>)"), topFrame); topLayout->addWidget(descLabel); QHBoxLayout *dateLayout = new QHBoxLayout(0); QLabel *dateLabel = new QLabel(i18n("A&ppointments older than:"),topFrame); dateLayout->addWidget(dateLabel); mDateEdit = new KDateEdit(topFrame); QWhatsThis::add(mDateEdit, i18n("The age of the appointments to archive. All older appointments " "will be saved and deleted, the newer will be kept.")); dateLabel->setBuddy(mDateEdit); dateLayout->addWidget(mDateEdit); topLayout->addLayout(dateLayout); QHBoxLayout *fileLayout = new QHBoxLayout(0); fileLayout->setSpacing(spacingHint()); QLabel *l = new QLabel(i18n("Archive &file:"),topFrame); fileLayout->addWidget(l); mArchiveFile = new KURLRequester(KOPrefs::instance()->mArchiveFile,topFrame); mArchiveFile->setMode(KFile::File); mArchiveFile->setFilter(i18n("*.vcs|vCalendar Files")); QWhatsThis::add(mArchiveFile, i18n("The path of the archive. The appointments will be added to the " "archive file, so any appointments that are already in the file " "will not be modified or deleted. You can later load or merge the " "file like any other calendar. It is not saved in a special " "format, it uses the vCalendar format. ")); l->setBuddy(mArchiveFile->lineEdit()); fileLayout->addWidget(mArchiveFile); topLayout->addLayout(fileLayout); mDeleteCb = new QCheckBox(i18n("&Delete only, do not save"), topFrame); QWhatsThis::add(mDeleteCb, i18n("Select this option to delete old appointments without saving them." "It is not possible to recover the appointments later.")); topLayout->addWidget(mDeleteCb); connect(mDeleteCb, SIGNAL(toggled(bool)), mArchiveFile, SLOT(setDisabled(bool))); connect(mDeleteCb, SIGNAL(toggled(bool)), this, SLOT(slotEnableUser1())); connect(mArchiveFile->lineEdit(),SIGNAL(textChanged ( const QString & )), this,SLOT(slotEnableUser1())); enableButton(KDialogBase::User1,!mArchiveFile->lineEdit()->text().isEmpty()); } ArchiveDialog::~ArchiveDialog() { } void ArchiveDialog::slotEnableUser1() { bool state = ( mDeleteCb->isChecked() || !mArchiveFile->lineEdit()->text().isEmpty() ); enableButton(KDialogBase::User1,state); } // Archive old events void ArchiveDialog::slotUser1() { if (mDeleteCb->isChecked()) { deleteOldEvents(); return; } // Get destination URL KURL destUrl = mArchiveFile->url(); if ( !destUrl.isValid() ) { KMessageBox::sorry(this,i18n("The archive file name is not valid.\n")); return; } // Force filename to be ending with vCalendar extension QString filename = destUrl.fileName(); if (filename.right(4) != ".vcs" && filename.right(4) != ".ics") { filename.append(".ics"); destUrl.setFileName(filename); } // Get events to be archived Event::List events = mCalendar->events( QDate( 1800, 1, 1 ), mDateEdit->date().addDays( -1 ), true ); if ( events.count() == 0 ) { KMessageBox::sorry(this,i18n("There are no events before %1") .arg(KGlobal::locale()->formatDate(mDateEdit->date()))); return; } FileStorage storage( mCalendar ); // Save current calendar to disk KTempFile tmpFile; tmpFile.setAutoDelete(true); storage.setFileName( tmpFile.name() ); if ( !storage.save() ) { kdDebug(5850) << "ArchiveDialog::slotUser1(): Can't save calendar to temp file" << endl; return; } // Duplicate current calendar by loading in new calendar object CalendarLocal archiveCalendar( KOPrefs::instance()->mTimeZoneId ); FileStorage archiveStore( &archiveCalendar ); archiveStore.setFileName( tmpFile.name() ); if (!archiveStore.load()) { kdDebug(5850) << "ArchiveDialog::slotUser1(): Can't load calendar from temp file" << endl; return; } // Strip active events from calendar so that only events to be archived // remain. Event::List activeEvents = archiveCalendar.events( mDateEdit->date(), QDate( 3000, 1, 1 ), false ); Event::List::ConstIterator it; for( it = activeEvents.begin(); it != activeEvents.end(); ++it ) { archiveCalendar.deleteEvent( *it ); } // Get or create the archive file QString archiveFile; if ( KIO::NetAccess::exists( destUrl, true, this ) ) { if( !KIO::NetAccess::download( destUrl, archiveFile, this ) ) { kdDebug(5850) << "ArchiveDialog::slotUser1(): Can't download archive file" << endl; return; } // Merge with events to be archived. archiveStore.setFileName( archiveFile ); if ( !archiveStore.load() ) { kdDebug(5850) << "ArchiveDialog::slotUser1(): Can't merge with archive file" << endl; return; } /* QPtrList<Event> es = archiveCalendar.events(QDate(1800,1,1), QDate(3000,1,1), false); kdDebug(5850) << "--Following events in archive calendar:" << endl; Event *e; for(e=es.first();e;e=es.next()) { kdDebug(5850) << "-----Event: " << e->getSummary() << endl; } */ } else { archiveFile = tmpFile.name(); } // Save archive calendar if ( !archiveStore.save() ) { KMessageBox::error(this,i18n("Cannot write archive file.")); return; } // Upload if necessary KURL srcUrl; srcUrl.setPath(archiveFile); if (srcUrl != destUrl) { if ( !KIO::NetAccess::upload( archiveFile, destUrl, this ) ) { KMessageBox::error(this,i18n("Cannot write archive to final destination.")); return; } } KOPrefs::instance()->mArchiveFile = destUrl.url(); KIO::NetAccess::removeTempFile(archiveFile); // Delete archived events from calendar for( it = events.begin(); it != events.end(); ++it ) { mCalendar->deleteEvent( *it ); } emit eventsDeleted(); accept(); } // Delete old events void ArchiveDialog::deleteOldEvents() { Event::List events = mCalendar->events( QDate( 1769, 12, 1 ), mDateEdit->date().addDays( -1 ), true ); if ( events.count() == 0 ) { KMessageBox::sorry(this,i18n("There are no events before %1") .arg(KGlobal::locale()->formatDate(mDateEdit->date()))); return; } QStringList eventStrs; Event::List::ConstIterator it; for( it = events.begin(); it != events.end(); ++it ) { eventStrs.append( (*it)->summary() ); } int result = KMessageBox::warningContinueCancelList(this, i18n("Delete all events before %1 without saving?\n" "The following events will be deleted:") .arg(KGlobal::locale()->formatDate(mDateEdit->date())),eventStrs, i18n("Delete old events"),i18n("&Delete")); if (result == KMessageBox::Continue) { for( it = events.begin(); it != events.end(); ++it ) { mCalendar->deleteEvent( *it ); } emit eventsDeleted(); accept(); } }
Allow .ics extension for the archive calendar file.
Allow .ics extension for the archive calendar file. svn path=/trunk/kdepim/; revision=248666
C++
lgpl-2.1
lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi
a03fc40779965846dab199a8ed926f5387d8779d
korganizer/koeventeditor.cpp
korganizer/koeventeditor.cpp
/* This file is part of KOrganizer. Copyright (c) 2001, 2002, 2003 Cornelius Schumacher <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include <qtooltip.h> #include <qframe.h> #include <qpixmap.h> #include <qlayout.h> #include <qwidgetstack.h> #include <kabc/addressee.h> #include <kiconloader.h> #include <kdebug.h> #include <klocale.h> #include <kmessagebox.h> #include <libkcal/calendarresources.h> #include <libkcal/resourcecalendar.h> #include <libkdepim/categoryselectdialog.h> #include <libkcal/calendarlocal.h> #include "koprefs.h" #include "koeditorgeneralevent.h" #include "koeditorrecurrence.h" #include "koeditordetails.h" #include "koeditorattachments.h" #include "koeditorfreebusy.h" #include "kogroupware.h" #include "kodialogmanager.h" #include "koeventeditor.h" KOEventEditor::KOEventEditor( Calendar *calendar, QWidget *parent ) : KOIncidenceEditor( i18n("Edit Event"), calendar, parent ), mEvent( 0 ) { } KOEventEditor::~KOEventEditor() { emit dialogClose( mEvent ); } void KOEventEditor::init() { setupGeneral(); setupAttendeesTab(); setupRecurrence(); setupAttachmentsTab(); setupFreeBusy(); mDetails->setFreeBusyWidget( mFreeBusy ); // Propagate date time settings to recurrence tab connect( mGeneral, SIGNAL( dateTimesChanged( QDateTime, QDateTime ) ), mRecurrence, SLOT( setDateTimes( QDateTime, QDateTime ) ) ); connect( mGeneral, SIGNAL( dateTimeStrChanged( const QString & ) ), mRecurrence, SLOT( setDateTimeStr( const QString & ) ) ); connect( mFreeBusy, SIGNAL( dateTimesChanged( QDateTime, QDateTime ) ), mRecurrence, SLOT( setDateTimes( QDateTime, QDateTime ) ) ); // Propagate date time settings to gantt tab and back connect( mGeneral, SIGNAL( dateTimesChanged( QDateTime, QDateTime ) ), mFreeBusy, SLOT( slotUpdateGanttView( QDateTime, QDateTime ) ) ); connect( mFreeBusy, SIGNAL( dateTimesChanged( QDateTime, QDateTime ) ), mGeneral, SLOT( setDateTimes( QDateTime, QDateTime ) ) ); // Category dialog connect( mGeneral, SIGNAL( openCategoryDialog() ), mCategoryDialog, SLOT( show() ) ); connect( mCategoryDialog, SIGNAL( categoriesSelected( const QString & ) ), mGeneral, SLOT( setCategories( const QString & ) ) ); connect( mGeneral, SIGNAL( focusReceivedSignal() ), SIGNAL( focusReceivedSignal() ) ); } void KOEventEditor::reload() { kdDebug() << "KOEventEditor::reload()" << endl; if ( mEvent ) readEvent( mEvent ); } void KOEventEditor::setupGeneral() { mGeneral = new KOEditorGeneralEvent( this ); if( KOPrefs::instance()->mCompactDialogs ) { QFrame *topFrame = addPage(i18n("General")); QBoxLayout *topLayout = new QVBoxLayout(topFrame); topLayout->setSpacing(spacingHint()); mGeneral->initHeader(topFrame,topLayout); mGeneral->initTime(topFrame,topLayout); // QBoxLayout *alarmLineLayout = new QHBoxLayout(topLayout); mGeneral->initAlarm(topFrame,topLayout); mGeneral->enableAlarm( false ); mGeneral->initCategories( topFrame, topLayout ); topLayout->addStretch( 1 ); QFrame *topFrame2 = addPage(i18n("Details")); QBoxLayout *topLayout2 = new QVBoxLayout(topFrame2); topLayout2->setSpacing(spacingHint()); mGeneral->initClass(topFrame2,topLayout2); mGeneral->initSecrecy( topFrame2, topLayout2 ); mGeneral->initDescription(topFrame2,topLayout2); } else { QFrame *topFrame = addPage(i18n("&General")); QBoxLayout *topLayout = new QVBoxLayout(topFrame); topLayout->setSpacing(spacingHint()); mGeneral->initHeader(topFrame,topLayout); mGeneral->initTime(topFrame,topLayout); QBoxLayout *alarmLineLayout = new QHBoxLayout(topLayout); mGeneral->initAlarm(topFrame,alarmLineLayout); mGeneral->initClass(topFrame,alarmLineLayout); mGeneral->initDescription(topFrame,topLayout); QBoxLayout *detailsLayout = new QHBoxLayout(topLayout); mGeneral->initCategories( topFrame, detailsLayout ); mGeneral->initSecrecy( topFrame, detailsLayout ); } mGeneral->finishSetup(); } void KOEventEditor::modified (int /*modification*/) { // Play dump, just reload the event. This dialog has become so complicated // that there is no point in trying to be smart here... reload(); } void KOEventEditor::setupRecurrence() { QFrame *topFrame = addPage( i18n("Rec&urrence") ); QBoxLayout *topLayout = new QVBoxLayout( topFrame ); mRecurrence = new KOEditorRecurrence( topFrame ); topLayout->addWidget( mRecurrence ); } void KOEventEditor::setupFreeBusy() { QFrame *freeBusyPage = addPage( i18n("&Free/Busy") ); QBoxLayout *topLayout = new QVBoxLayout( freeBusyPage ); mFreeBusy = new KOEditorFreeBusy( spacingHint(), freeBusyPage ); topLayout->addWidget( mFreeBusy ); } void KOEventEditor::editIncidence(Incidence *incidence) { Event*event = dynamic_cast<Event*>(incidence); if (event) { init(); mEvent = event; readEvent(mEvent); } } void KOEventEditor::newEvent( QDateTime from, QDateTime to, bool allDay ) { init(); mEvent = 0; setDefaults(from,to,allDay); } void KOEventEditor::newEvent( const QString &text ) { init(); mEvent = 0; loadDefaults(); mGeneral->setDescription( text ); int pos = text.find( "\n" ); if ( pos > 0 ) { mGeneral->setSummary( text.left( pos ) ); mGeneral->setDescription( text ); } else { mGeneral->setSummary( text ); } } void KOEventEditor::newEvent( const QString &summary, const QString &description, const QString &attachment ) { init(); mEvent = 0; loadDefaults(); mGeneral->setSummary( summary ); mGeneral->setDescription( description ); if ( !attachment.isEmpty() ) { mAttachments->addAttachment( attachment ); } } void KOEventEditor::newEvent( const QString &summary, const QString &description, const QString &attachment, const QStringList &attendees ) { newEvent( summary, description, attachment ); QStringList::ConstIterator it; for ( it = attendees.begin(); it != attendees.end(); ++it ) { QString name, email; KABC::Addressee::parseEmailAddress( *it, name, email ); mDetails->insertAttendee( new Attendee( name, email ) ); } } void KOEventEditor::loadDefaults() { QTime defaultDuration( KOPrefs::instance()->mDefaultDuration.time() ); QDateTime from(QDate::currentDate(), KOPrefs::instance()->mStartTime.time() ); QDateTime to( from.addSecs(defaultDuration.hour()*3600 + defaultDuration.minute()*60 + defaultDuration.second()) ); setDefaults(from,to,false); } bool KOEventEditor::myAttendeeStatusChanged( Event *oldEvent, Event *newEvent ) { Attendee *oldMe = oldEvent->attendeeByMails( KOPrefs::instance()->allEmails() ); Attendee *newMe = newEvent->attendeeByMails( KOPrefs::instance()->allEmails() ); if ( oldMe && newMe && ( oldMe->status() != newMe->status() ) ) return true; return false; } // TODO_RK: make sure calendar()->endChange is called somewhere! bool KOEventEditor::processInput() { kdDebug(5850) << "KOEventEditor::processInput()" << endl; if ( !validateInput() ) return false; if ( mEvent ) { bool rc = true; Event *event = mEvent->clone(); Event *oldEvent = mEvent->clone(); kdDebug(5850) << "KOEventEditor::processInput() write event." << endl; writeEvent( event ); kdDebug(5850) << "KOEventEditor::processInput() event written." << endl; if( *mEvent == *event ) // Don't do anything kdDebug(5850) << "Event not changed\n"; else { kdDebug(5850) << "Event changed\n"; int revision = event->revision(); event->setRevision( revision + 1 ); bool statusChanged = myAttendeeStatusChanged( mEvent, event ); if( !KOPrefs::instance()->mUseGroupwareCommunication || KOGroupware::instance()->sendICalMessage( this, KCal::Scheduler::Request, event, false, statusChanged ) ) { // Accept the event changes writeEvent( mEvent ); mEvent->setRevision( revision + 1 ); emit incidenceChanged( oldEvent, mEvent ); } else { // Revert the changes event->setRevision( revision ); rc = false; } } delete event; delete oldEvent; return rc; } else { mEvent = new Event; mEvent->setOrganizer( Person( KOPrefs::instance()->fullName(), KOPrefs::instance()->email() ) ); writeEvent( mEvent ); if ( KOPrefs::instance()->mUseGroupwareCommunication ) { if ( !KOGroupware::instance()->sendICalMessage( this, KCal::Scheduler::Request, mEvent ) ) { kdError() << "sendIcalMessage failed." << endl; } } if ( mCalendar->addEvent( mEvent ) ) { emit incidenceAdded( mEvent ); } else { KODialogManager::errorSaveEvent( this ); delete mEvent; mEvent = 0; return false; } } if ( mFreeBusy ) mFreeBusy->cancelReload(); return true; } void KOEventEditor::processCancel() { kdDebug() << "KOEventEditor::processCancel()" << endl; if ( mEvent ) { emit editCanceled( mEvent ); } if ( mFreeBusy ) mFreeBusy->cancelReload(); } void KOEventEditor::deleteEvent() { kdDebug(5850) << "Delete event" << endl; if (mEvent) { bool groupwareCheck = KOPrefs::instance()->mConfirm && (!KOPrefs::instance()->mUseGroupwareCommunication || KOPrefs::instance()->thatIsMe( mEvent->organizer().email() ) ); if (!groupwareCheck || (msgItemDelete()==KMessageBox::Continue)) { // Either no groupware check needed, or OK pressed emit incidenceToBeDeleted(mEvent); emit dialogClose(mEvent); mCalendar->deleteEvent(mEvent); emit incidenceDeleted(mEvent); reject(); } } else { reject(); } } void KOEventEditor::setDefaults( QDateTime from, QDateTime to, bool allDay ) { mGeneral->setDefaults( from, to, allDay ); mDetails->setDefaults(); mAttachments->setDefaults(); mRecurrence->setDefaults( from, to, allDay ); if( mFreeBusy ) { if ( allDay ) mFreeBusy->setDateTimes( from, to.addDays( 1 ) ); else mFreeBusy->setDateTimes( from, to ); } } void KOEventEditor::readEvent( Event *event, bool tmpl ) { mGeneral->readEvent( event, tmpl ); mDetails->readEvent( event ); mRecurrence->readIncidence( event ); mAttachments->readIncidence( event ); if( mFreeBusy ) { mFreeBusy->readEvent( event ); mFreeBusy->triggerReload(); } // categories mCategoryDialog->setSelected( event->categories() ); } void KOEventEditor::writeEvent( Event *event ) { mGeneral->writeEvent( event ); mDetails->writeEvent( event ); mAttachments->writeIncidence( event ); cancelRemovedAttendees( event ); mRecurrence->writeIncidence( event ); } bool KOEventEditor::validateInput() { if ( !mGeneral->validateInput() ) return false; if ( !mDetails->validateInput() ) return false; if ( !mRecurrence->validateInput() ) return false; return true; } int KOEventEditor::msgItemDelete() { return KMessageBox::warningContinueCancel(this, i18n("This item will be permanently deleted."), i18n("KOrganizer Confirmation"),KGuiItem(i18n("Delete"),"editdelete")); } void KOEventEditor::slotLoadTemplate() { CalendarLocal cal( KOPrefs::instance()->mTimeZoneId ); Event *event = new Event; QString templateName = loadTemplate( &cal, event->type(), KOPrefs::instance()->mEventTemplates ); delete event; if ( templateName.isEmpty() ) { return; } Event::List events = cal.events(); if ( events.count() == 0 ) { KMessageBox::error( this, i18n("Template does not contain a valid event.") .arg( templateName ) ); } else { kdDebug(5850) << "KOEventEditor::slotLoadTemplate(): readTemplate" << endl; readEvent( events.first(), true ); } } void KOEventEditor::saveTemplate( const QString &templateName ) { Event *event = new Event; writeEvent( event ); saveAsTemplate( event, templateName ); } QObject *KOEventEditor::typeAheadReceiver() const { return mGeneral->typeAheadReceiver(); } #include "koeventeditor.moc"
/* This file is part of KOrganizer. Copyright (c) 2001, 2002, 2003 Cornelius Schumacher <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include <qtooltip.h> #include <qframe.h> #include <qpixmap.h> #include <qlayout.h> #include <qwidgetstack.h> #include <qfile.h> #include <kabc/addressee.h> #include <kiconloader.h> #include <kdebug.h> #include <klocale.h> #include <kmessagebox.h> #include <libkcal/calendarresources.h> #include <libkcal/resourcecalendar.h> #include <libkdepim/categoryselectdialog.h> #include <libkcal/calendarlocal.h> #include "koprefs.h" #include "koeditorgeneralevent.h" #include "koeditorrecurrence.h" #include "koeditordetails.h" #include "koeditorattachments.h" #include "koeditorfreebusy.h" #include "kogroupware.h" #include "kodialogmanager.h" #include "koeventeditor.h" KOEventEditor::KOEventEditor( Calendar *calendar, QWidget *parent ) : KOIncidenceEditor( i18n("Edit Event"), calendar, parent ), mEvent( 0 ) { } KOEventEditor::~KOEventEditor() { emit dialogClose( mEvent ); } void KOEventEditor::init() { setupGeneral(); setupAttendeesTab(); setupRecurrence(); setupAttachmentsTab(); setupFreeBusy(); mDetails->setFreeBusyWidget( mFreeBusy ); // Propagate date time settings to recurrence tab connect( mGeneral, SIGNAL( dateTimesChanged( QDateTime, QDateTime ) ), mRecurrence, SLOT( setDateTimes( QDateTime, QDateTime ) ) ); connect( mGeneral, SIGNAL( dateTimeStrChanged( const QString & ) ), mRecurrence, SLOT( setDateTimeStr( const QString & ) ) ); connect( mFreeBusy, SIGNAL( dateTimesChanged( QDateTime, QDateTime ) ), mRecurrence, SLOT( setDateTimes( QDateTime, QDateTime ) ) ); // Propagate date time settings to gantt tab and back connect( mGeneral, SIGNAL( dateTimesChanged( QDateTime, QDateTime ) ), mFreeBusy, SLOT( slotUpdateGanttView( QDateTime, QDateTime ) ) ); connect( mFreeBusy, SIGNAL( dateTimesChanged( QDateTime, QDateTime ) ), mGeneral, SLOT( setDateTimes( QDateTime, QDateTime ) ) ); // Category dialog connect( mGeneral, SIGNAL( openCategoryDialog() ), mCategoryDialog, SLOT( show() ) ); connect( mCategoryDialog, SIGNAL( categoriesSelected( const QString & ) ), mGeneral, SLOT( setCategories( const QString & ) ) ); connect( mGeneral, SIGNAL( focusReceivedSignal() ), SIGNAL( focusReceivedSignal() ) ); } void KOEventEditor::reload() { kdDebug() << "KOEventEditor::reload()" << endl; if ( mEvent ) readEvent( mEvent ); } void KOEventEditor::setupGeneral() { mGeneral = new KOEditorGeneralEvent( this ); if( KOPrefs::instance()->mCompactDialogs ) { QFrame *topFrame = addPage(i18n("General")); QBoxLayout *topLayout = new QVBoxLayout(topFrame); topLayout->setSpacing(spacingHint()); mGeneral->initHeader(topFrame,topLayout); mGeneral->initTime(topFrame,topLayout); // QBoxLayout *alarmLineLayout = new QHBoxLayout(topLayout); mGeneral->initAlarm(topFrame,topLayout); mGeneral->enableAlarm( false ); mGeneral->initCategories( topFrame, topLayout ); topLayout->addStretch( 1 ); QFrame *topFrame2 = addPage(i18n("Details")); QBoxLayout *topLayout2 = new QVBoxLayout(topFrame2); topLayout2->setSpacing(spacingHint()); mGeneral->initClass(topFrame2,topLayout2); mGeneral->initSecrecy( topFrame2, topLayout2 ); mGeneral->initDescription(topFrame2,topLayout2); } else { QFrame *topFrame = addPage(i18n("&General")); QBoxLayout *topLayout = new QVBoxLayout(topFrame); topLayout->setSpacing(spacingHint()); mGeneral->initHeader(topFrame,topLayout); mGeneral->initTime(topFrame,topLayout); QBoxLayout *alarmLineLayout = new QHBoxLayout(topLayout); mGeneral->initAlarm(topFrame,alarmLineLayout); mGeneral->initClass(topFrame,alarmLineLayout); mGeneral->initDescription(topFrame,topLayout); QBoxLayout *detailsLayout = new QHBoxLayout(topLayout); mGeneral->initCategories( topFrame, detailsLayout ); mGeneral->initSecrecy( topFrame, detailsLayout ); } mGeneral->finishSetup(); } void KOEventEditor::modified (int /*modification*/) { // Play dump, just reload the event. This dialog has become so complicated // that there is no point in trying to be smart here... reload(); } void KOEventEditor::setupRecurrence() { QFrame *topFrame = addPage( i18n("Rec&urrence") ); QBoxLayout *topLayout = new QVBoxLayout( topFrame ); mRecurrence = new KOEditorRecurrence( topFrame ); topLayout->addWidget( mRecurrence ); } void KOEventEditor::setupFreeBusy() { QFrame *freeBusyPage = addPage( i18n("&Free/Busy") ); QBoxLayout *topLayout = new QVBoxLayout( freeBusyPage ); mFreeBusy = new KOEditorFreeBusy( spacingHint(), freeBusyPage ); topLayout->addWidget( mFreeBusy ); } void KOEventEditor::editIncidence(Incidence *incidence) { Event*event = dynamic_cast<Event*>(incidence); if (event) { init(); mEvent = event; readEvent(mEvent); } } void KOEventEditor::newEvent( QDateTime from, QDateTime to, bool allDay ) { init(); mEvent = 0; setDefaults(from,to,allDay); } void KOEventEditor::newEvent( const QString &text ) { init(); mEvent = 0; loadDefaults(); mGeneral->setDescription( text ); int pos = text.find( "\n" ); if ( pos > 0 ) { mGeneral->setSummary( text.left( pos ) ); mGeneral->setDescription( text ); } else { mGeneral->setSummary( text ); } } void KOEventEditor::newEvent( const QString &summary, const QString &description, const QString &attachment ) { init(); mEvent = 0; loadDefaults(); mGeneral->setSummary( summary ); mGeneral->setDescription( description ); if ( !attachment.isEmpty() ) { mAttachments->addAttachment( attachment ); } } void KOEventEditor::newEvent( const QString &summary, const QString &description, const QString &attachment, const QStringList &attendees ) { newEvent( summary, description, attachment ); QStringList::ConstIterator it; for ( it = attendees.begin(); it != attendees.end(); ++it ) { QString name, email; KABC::Addressee::parseEmailAddress( *it, name, email ); mDetails->insertAttendee( new Attendee( name, email ) ); } } void KOEventEditor::loadDefaults() { QTime defaultDuration( KOPrefs::instance()->mDefaultDuration.time() ); QDateTime from(QDate::currentDate(), KOPrefs::instance()->mStartTime.time() ); QDateTime to( from.addSecs(defaultDuration.hour()*3600 + defaultDuration.minute()*60 + defaultDuration.second()) ); setDefaults(from,to,false); } bool KOEventEditor::myAttendeeStatusChanged( Event *oldEvent, Event *newEvent ) { Attendee *oldMe = oldEvent->attendeeByMails( KOPrefs::instance()->allEmails() ); Attendee *newMe = newEvent->attendeeByMails( KOPrefs::instance()->allEmails() ); if ( oldMe && newMe && ( oldMe->status() != newMe->status() ) ) return true; return false; } // TODO_RK: make sure calendar()->endChange is called somewhere! bool KOEventEditor::processInput() { kdDebug(5850) << "KOEventEditor::processInput()" << endl; if ( !validateInput() ) return false; if ( mEvent ) { bool rc = true; Event *event = mEvent->clone(); Event *oldEvent = mEvent->clone(); kdDebug(5850) << "KOEventEditor::processInput() write event." << endl; writeEvent( event ); kdDebug(5850) << "KOEventEditor::processInput() event written." << endl; #ifdef OPERATOREQUALDEBUG ICalFormat ical; QString firstEvent = ical.toICalString( mEvent ); QString secondEvent = ical.toICalString( event ); QFile f( "/tmp/firstEvent" ); f.open( IO_WriteOnly ); f.writeBlock( firstEvent.local8Bit() ); f.close(); QFile f2( "/tmp/secondEvent" ); f2.open( IO_WriteOnly ); f2.writeBlock( secondEvent.local8Bit() ); f2.close(); #endif if( *mEvent == *event ) // Don't do anything kdDebug(5850) << "Event not changed\n"; else { kdDebug(5850) << "Event changed\n"; int revision = event->revision(); event->setRevision( revision + 1 ); bool statusChanged = myAttendeeStatusChanged( mEvent, event ); if( !KOPrefs::instance()->mUseGroupwareCommunication || KOGroupware::instance()->sendICalMessage( this, KCal::Scheduler::Request, event, false, statusChanged ) ) { // Accept the event changes writeEvent( mEvent ); mEvent->setRevision( revision + 1 ); emit incidenceChanged( oldEvent, mEvent ); } else { // Revert the changes event->setRevision( revision ); rc = false; } } delete event; delete oldEvent; return rc; } else { mEvent = new Event; mEvent->setOrganizer( Person( KOPrefs::instance()->fullName(), KOPrefs::instance()->email() ) ); writeEvent( mEvent ); if ( KOPrefs::instance()->mUseGroupwareCommunication ) { if ( !KOGroupware::instance()->sendICalMessage( this, KCal::Scheduler::Request, mEvent ) ) { kdError() << "sendIcalMessage failed." << endl; } } if ( mCalendar->addEvent( mEvent ) ) { emit incidenceAdded( mEvent ); } else { KODialogManager::errorSaveEvent( this ); delete mEvent; mEvent = 0; return false; } } if ( mFreeBusy ) mFreeBusy->cancelReload(); return true; } void KOEventEditor::processCancel() { kdDebug() << "KOEventEditor::processCancel()" << endl; if ( mEvent ) { emit editCanceled( mEvent ); } if ( mFreeBusy ) mFreeBusy->cancelReload(); } void KOEventEditor::deleteEvent() { kdDebug(5850) << "Delete event" << endl; if (mEvent) { bool groupwareCheck = KOPrefs::instance()->mConfirm && (!KOPrefs::instance()->mUseGroupwareCommunication || KOPrefs::instance()->thatIsMe( mEvent->organizer().email() ) ); if (!groupwareCheck || (msgItemDelete()==KMessageBox::Continue)) { // Either no groupware check needed, or OK pressed emit incidenceToBeDeleted(mEvent); emit dialogClose(mEvent); mCalendar->deleteEvent(mEvent); emit incidenceDeleted(mEvent); reject(); } } else { reject(); } } void KOEventEditor::setDefaults( QDateTime from, QDateTime to, bool allDay ) { mGeneral->setDefaults( from, to, allDay ); mDetails->setDefaults(); mAttachments->setDefaults(); mRecurrence->setDefaults( from, to, allDay ); if( mFreeBusy ) { if ( allDay ) mFreeBusy->setDateTimes( from, to.addDays( 1 ) ); else mFreeBusy->setDateTimes( from, to ); } } void KOEventEditor::readEvent( Event *event, bool tmpl ) { mGeneral->readEvent( event, tmpl ); mDetails->readEvent( event ); mRecurrence->readIncidence( event ); mAttachments->readIncidence( event ); if( mFreeBusy ) { mFreeBusy->readEvent( event ); mFreeBusy->triggerReload(); } // categories mCategoryDialog->setSelected( event->categories() ); } void KOEventEditor::writeEvent( Event *event ) { mGeneral->writeEvent( event ); mDetails->writeEvent( event ); mAttachments->writeIncidence( event ); cancelRemovedAttendees( event ); mRecurrence->writeIncidence( event ); } bool KOEventEditor::validateInput() { if ( !mGeneral->validateInput() ) return false; if ( !mDetails->validateInput() ) return false; if ( !mRecurrence->validateInput() ) return false; return true; } int KOEventEditor::msgItemDelete() { return KMessageBox::warningContinueCancel(this, i18n("This item will be permanently deleted."), i18n("KOrganizer Confirmation"),KGuiItem(i18n("Delete"),"editdelete")); } void KOEventEditor::slotLoadTemplate() { CalendarLocal cal( KOPrefs::instance()->mTimeZoneId ); Event *event = new Event; QString templateName = loadTemplate( &cal, event->type(), KOPrefs::instance()->mEventTemplates ); delete event; if ( templateName.isEmpty() ) { return; } Event::List events = cal.events(); if ( events.count() == 0 ) { KMessageBox::error( this, i18n("Template does not contain a valid event.") .arg( templateName ) ); } else { kdDebug(5850) << "KOEventEditor::slotLoadTemplate(): readTemplate" << endl; readEvent( events.first(), true ); } } void KOEventEditor::saveTemplate( const QString &templateName ) { Event *event = new Event; writeEvent( event ); saveAsTemplate( event, templateName ); } QObject *KOEventEditor::typeAheadReceiver() const { return mGeneral->typeAheadReceiver(); } #include "koeventeditor.moc"
Add operator== debuggin helper.
Add operator== debuggin helper. svn path=/branches/proko2/kdepim/; revision=360330
C++
lgpl-2.1
lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi
777c9a5d4ac43d584db76ba91b5fa4f9a6d565d1
Synopsis/Parsers/Cxx/occ/PTree/Encoding.hh
Synopsis/Parsers/Cxx/occ/PTree/Encoding.hh
// // Copyright (C) 1997 Shigeru Chiba // Copyright (C) 2004 Stefan Seefeld // All rights reserved. // Licensed to the public under the terms of the GNU LGPL (>= 2), // see the file COPYING for details. // #ifndef _PTree_Encoding_hh #define _PTree_Encoding_hh #include <string> #include <iostream> namespace PTree { class Node; //. 'b' boolean //. 'c' char //. 'w' wchar_t //. 'i' int (signed, unsigned) //. 's' short (short int) //. 'l' long (long int) //. 'j' long long //. 'f' float //. 'd' double //. 'r' long double //. 'v' void //. //. 'T' template class (e.g. Foo<int,char> ==> T[3]Foo[2]ic. [2] means //. the length of "ic". It doesn't mean the number of template //. arguments. //. 'e' ... //. '?' no return type. the return type of constructors //. '*' non-type template parameter //. //. 'S' signed //. 'U' unsigned //. 'C' const //. 'V' volatile //. //. 'P' pointer //. 'R' reference //. 'A' array (e.g. char[16] ==> A16_c) //. 'F' function (e.g. char foo(int) ==> Fi_c) //. 'M' pointer to member (e.g. Type::* ==> M[4]Type) //. //. 'Q' qualified class (e.g. X::YY ==> Q[2][1]X[2]YY, ::YY ==> Q[2][0][2]YY) //. //. [x] means (0x80 + x) //. '0' means :: (global scope) //. //. Special function names: //. //. operator + ==> + //. operator new[] ==> new[] //. operator <type> ==> @<encoded type> cast operator //. class Encoding { public: struct char_traits { typedef unsigned char char_type; typedef unsigned long int_type; typedef std::streampos pos_type; typedef std::streamoff off_type; typedef std::mbstate_t state_type; static void assign(char_type &c1, const char_type &c2) { c1 = c2;} static bool eq(const char_type &c1, const char_type &c2) { return c1 == c2;} static bool lt(const char_type &c1, const char_type &c2) { return c1 < c2;} static int compare(const char_type *s1, const char_type *s2, std::size_t n) { return memcmp(s1, s2, n);} static std::size_t length(const char_type *s) { return strlen((const char *)s);} static const char_type *find(const char_type *s, std::size_t n, const char_type &a) { return static_cast<const char_type *>(memchr(s, a, n));} static char_type *move(char_type *s1, const char_type *s2, std::size_t n) { return static_cast<char_type *>(memmove(s1, s2, n));} static char_type *copy(char_type *s1, const char_type *s2, std::size_t n) { return static_cast<char_type *>(memcpy(s1, s2, n));} static char_type *assign(char_type *s, std::size_t n, char_type a) { return static_cast<char_type *>(memset(s, a, n));} static char_type to_char_type(const int_type &c) { return static_cast<char_type>(c);} static int_type to_int_type(const char_type &c) { return static_cast<int_type>(c);} static bool eq_int_type(const int_type &c1, const int_type &c2) { return c1 == c2;} static int_type eof() { return static_cast<int_type>(EOF);} static int_type not_eof(const int_type &c) { return !eq_int_type(c, eof()) ? c : to_int_type(char_type());} }; typedef std::basic_string<unsigned char, char_traits> Code; typedef Code::const_iterator iterator; static void do_init_static(); Encoding() {} Encoding(const Code &b) : my_buffer(b) {} Encoding(const char *b) : my_buffer(b, b + strlen(b)) {} Encoding(const char *b, size_t s) : my_buffer(b, b + s) {} Encoding(iterator b, iterator e) : my_buffer(b, e) {} void clear() { my_buffer.clear();} bool empty() const { return my_buffer.empty();} size_t size() const { return my_buffer.size();} iterator begin() const { return my_buffer.begin();} iterator end() const { return my_buffer.end();} unsigned char front() const { return *begin();} unsigned char at(size_t i) const { return my_buffer.at(i);} //. return a copy of the underlaying buffer //. FIXME: this is a temporary workaround while there are //. still places that use raw strings const char *copy() const; bool operator == (const Encoding &e) const { return my_buffer == e.my_buffer;} bool operator == (const std::string &s) const { return my_buffer == (const unsigned char *)s.c_str();} bool operator == (const char *s) const { return my_buffer == (const unsigned char *)s;} void prepend(unsigned char c) { my_buffer.insert(my_buffer.begin(), c);} void prepend(const char *p, size_t s) { my_buffer.insert(0, (const unsigned char *)p, s);} void prepend(const Encoding &e) { my_buffer.insert(0, e.my_buffer);} void append(unsigned char c) { my_buffer.append(1, c);} void append(const char *p, size_t s) { my_buffer.append((const unsigned char *)p, s);} void append(const Encoding &e) { my_buffer.append(e.my_buffer);} void append_with_length(const char *s, size_t n) { append(0x80 + n); append((const char *)s, n);} void append_with_length(const Encoding &e) { append(0x80 + e.size()); append(e);} unsigned char pop(); void pop(size_t n) { my_buffer.erase(my_buffer.begin(), my_buffer.begin() + n);} void cv_qualify(const Node *, const Node * = 0); void simple_const() { append("Ci", 2);} void global_scope(); void simple_name(const Node *); void anonymous(); void template_(const Node *, const Encoding &); void qualified(int); void destructor(const Node *); void ptr_operator(int); void ptr_to_member(const Encoding &, int); void cast_operator(const Encoding &); void array() { prepend("A_", 2);} void array(unsigned long s); void function(const Encoding &e) { prepend(e);} void recursion(const Encoding &e) { prepend(e);} void start_func_args() { append('F');} void end_func_args() { append('_');} void void_() { append('v');} void ellipsis_arg() { append('e');} void no_return_type() { append('?');} void value_temp_param() { append('*');} Encoding get_template_arguments(); PTree::Node *make_name(); PTree::Node *make_qname(); PTree::Node *make_ptree(PTree::Node *); bool is_simple_name() const { return front() >= 0x80;} PTree::Node *name_to_ptree(); friend bool operator < (const Encoding &, const Encoding &); friend std::ostream &operator << (std::ostream &, const Encoding &); private: Code my_buffer; public: static PTree::Node *bool_t, *char_t, *wchar_t_t, *int_t, *short_t, *long_t, *float_t, *double_t, *void_t; static PTree::Node *signed_t, *unsigned_t, *const_t, *volatile_t; static PTree::Node *operator_name, *new_operator, *anew_operator, *delete_operator, *adelete_operator; static PTree::Node *star, *ampersand, *comma, *dots, *scope, *tilder, *left_paren, *right_paren, *left_bracket, *right_bracket, *left_angle, *right_angle; }; inline bool operator < (const Encoding &e1, const Encoding &e2) { return e1.my_buffer < e2.my_buffer; } inline std::ostream &operator << (std::ostream &os, const Encoding &e) { for (Encoding::iterator i = e.begin(); i != e.end(); ++i) if(*i < 0x80) os.put(static_cast<char>(*i)); else os << '[' << static_cast<int>(*i - 0x80) << ']'; return os; } inline unsigned char Encoding::pop() { unsigned char code = my_buffer[0]; my_buffer.erase(0, 1); return code; } } #endif
// // Copyright (C) 1997 Shigeru Chiba // Copyright (C) 2004 Stefan Seefeld // All rights reserved. // Licensed to the public under the terms of the GNU LGPL (>= 2), // see the file COPYING for details. // #ifndef _PTree_Encoding_hh #define _PTree_Encoding_hh #include <string> #include <iostream> namespace PTree { class Node; //. 'b' boolean //. 'c' char //. 'w' wchar_t //. 'i' int (signed, unsigned) //. 's' short (short int) //. 'l' long (long int) //. 'j' long long //. 'f' float //. 'd' double //. 'r' long double //. 'v' void //. //. 'T' template class (e.g. Foo<int,char> ==> T[3]Foo[2]ic. [2] means //. the length of "ic". It doesn't mean the number of template //. arguments. //. 'e' ... //. '?' no return type. the return type of constructors //. '*' non-type template parameter //. //. 'S' signed //. 'U' unsigned //. 'C' const //. 'V' volatile //. //. 'P' pointer //. 'R' reference //. 'A' array (e.g. char[16] ==> A16_c) //. 'F' function (e.g. char foo(int) ==> Fi_c) //. 'M' pointer to member (e.g. Type::* ==> M[4]Type) //. //. 'Q' qualified class (e.g. X::YY ==> Q[2][1]X[2]YY, ::YY ==> Q[2][0][2]YY) //. //. [x] means (0x80 + x) //. '0' means :: (global scope) //. //. Special function names: //. //. operator + ==> + //. operator new[] ==> new[] //. operator <type> ==> @<encoded type> cast operator //. class Encoding { public: struct char_traits { typedef unsigned char char_type; typedef unsigned long int_type; typedef std::streampos pos_type; typedef std::streamoff off_type; typedef std::mbstate_t state_type; static void assign(char_type &c1, const char_type &c2) { c1 = c2;} static bool eq(const char_type &c1, const char_type &c2) { return c1 == c2;} static bool lt(const char_type &c1, const char_type &c2) { return c1 < c2;} static int compare(const char_type *s1, const char_type *s2, std::size_t n) { return memcmp(s1, s2, n);} static std::size_t length(const char_type *s) { return strlen((const char *)s);} static const char_type *find(const char_type *s, std::size_t n, const char_type &a) { return static_cast<const char_type *>(memchr(s, a, n));} static char_type *move(char_type *s1, const char_type *s2, std::size_t n) { return static_cast<char_type *>(memmove(s1, s2, n));} static char_type *copy(char_type *s1, const char_type *s2, std::size_t n) { return static_cast<char_type *>(memcpy(s1, s2, n));} static char_type *assign(char_type *s, std::size_t n, char_type a) { return static_cast<char_type *>(memset(s, a, n));} static char_type to_char_type(const int_type &c) { return static_cast<char_type>(c);} static int_type to_int_type(const char_type &c) { return static_cast<int_type>(c);} static bool eq_int_type(const int_type &c1, const int_type &c2) { return c1 == c2;} static int_type eof() { return static_cast<int_type>(EOF);} static int_type not_eof(const int_type &c) { return !eq_int_type(c, eof()) ? c : to_int_type(char_type());} }; typedef std::basic_string<unsigned char, char_traits> Code; typedef Code::const_iterator iterator; static void do_init_static(); Encoding() {} Encoding(const Code &b) : my_buffer(b) {} Encoding(const char *b) : my_buffer(b, b + strlen(b)) {} Encoding(const char *b, size_t s) : my_buffer(b, b + s) {} Encoding(iterator b, iterator e) : my_buffer(b, e) {} void clear() { my_buffer.clear();} bool empty() const { return my_buffer.empty();} size_t size() const { return my_buffer.size();} iterator begin() const { return my_buffer.begin();} iterator end() const { return my_buffer.end();} unsigned char front() const { return *begin();} unsigned char at(size_t i) const { return my_buffer.at(i);} //. return a copy of the underlaying buffer //. FIXME: this is a temporary workaround while there are //. still places that use raw strings const char *copy() const; bool operator == (const Encoding &e) const { return my_buffer == e.my_buffer;} bool operator == (const std::string &s) const { return my_buffer == (const unsigned char *)s.c_str();} bool operator == (const char *s) const { return my_buffer == (const unsigned char *)s;} void prepend(unsigned char c) { my_buffer.insert(my_buffer.begin(), c);} void prepend(const char *p, size_t s) { my_buffer.insert(0, (const unsigned char *)p, s);} void prepend(const Encoding &e) { my_buffer.insert(0, e.my_buffer);} void append(unsigned char c) { my_buffer.append(1, c);} void append(const char *p, size_t s) { my_buffer.append((const unsigned char *)p, s);} void append(const Encoding &e) { my_buffer.append(e.my_buffer);} void append_with_length(const char *s, size_t n) { append(0x80 + n); append((const char *)s, n);} void append_with_length(const Encoding &e) { append(0x80 + e.size()); append(e);} unsigned char pop(); void pop(size_t n) { my_buffer.erase(my_buffer.begin(), my_buffer.begin() + n);} void cv_qualify(const Node *, const Node * = 0); void simple_const() { append("Ci", 2);} void global_scope(); void simple_name(const Node *); void anonymous(); void template_(const Node *, const Encoding &); void qualified(int); void destructor(const Node *); void ptr_operator(int); void ptr_to_member(const Encoding &, int); void cast_operator(const Encoding &); void array() { prepend("A_", 2);} void array(unsigned long s); void function(const Encoding &e) { prepend(e);} void recursion(const Encoding &e) { prepend(e);} void start_func_args() { append('F');} void end_func_args() { append('_');} void void_() { append('v');} void ellipsis_arg() { append('e');} void no_return_type() { append('?');} void value_temp_param() { append('*');} Encoding get_template_arguments(); PTree::Node *make_name(); PTree::Node *make_qname(); PTree::Node *make_ptree(PTree::Node *); bool is_simple_name() const { return front() >= 0x80;} bool is_qualified() const { return front() == 'Q';} PTree::Node *name_to_ptree(); friend bool operator < (const Encoding &, const Encoding &); friend std::ostream &operator << (std::ostream &, const Encoding &); private: Code my_buffer; public: static PTree::Node *bool_t, *char_t, *wchar_t_t, *int_t, *short_t, *long_t, *float_t, *double_t, *void_t; static PTree::Node *signed_t, *unsigned_t, *const_t, *volatile_t; static PTree::Node *operator_name, *new_operator, *anew_operator, *delete_operator, *adelete_operator; static PTree::Node *star, *ampersand, *comma, *dots, *scope, *tilder, *left_paren, *right_paren, *left_bracket, *right_bracket, *left_angle, *right_angle; }; inline bool operator < (const Encoding &e1, const Encoding &e2) { return e1.my_buffer < e2.my_buffer; } inline std::ostream &operator << (std::ostream &os, const Encoding &e) { for (Encoding::iterator i = e.begin(); i != e.end(); ++i) if(*i < 0x80) os.put(static_cast<char>(*i)); else os << '[' << static_cast<int>(*i - 0x80) << ']'; return os; } inline unsigned char Encoding::pop() { unsigned char code = my_buffer[0]; my_buffer.erase(0, 1); return code; } } #endif
add 'is_qualified' to Encoding interface
add 'is_qualified' to Encoding interface
C++
lgpl-2.1
stefanseefeld/synopsis,stefanseefeld/synopsis,stefanseefeld/synopsis,stefanseefeld/synopsis,stefanseefeld/synopsis,stefanseefeld/synopsis
9f3515f90c7b05d5f387dc15e2d6c10892e208bb
desktop/source/app/configinit.cxx
desktop/source/app/configinit.cxx
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * 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 . */ #include "configinit.hxx" #include "desktop.hrc" #include "app.hxx" #include <comphelper/processfactory.hxx> #include <uno/current_context.hxx> #include <cppuhelper/implbase1.hxx> #include <rtl/ustrbuf.hxx> #include <osl/diagnose.h> #include <stdio.h> #include <com/sun/star/task/InteractionHandler.hpp> namespace uno = ::com::sun::star::uno; namespace lang = ::com::sun::star::lang; using uno::UNO_QUERY; // must be aligned with configmgr/source/misc/configinteractionhandler static char const CONFIG_ERROR_HANDLER[] = "configuration.interaction-handler"; // ConfigurationErrorHandler namespace { typedef uno::Reference< uno::XCurrentContext > CurrentContext; class SimpleCurrentContext : public cppu::WeakImplHelper1< uno::XCurrentContext > { CurrentContext m_xChainedContext; public: explicit SimpleCurrentContext(const CurrentContext & xChainedContext) : m_xChainedContext(xChainedContext) {} void install() { uno::setCurrentContext(this); } void deinstall() { uno::setCurrentContext(m_xChainedContext); } uno::Any getChainedValueByName( OUString const & aName) const { return m_xChainedContext.is() ? m_xChainedContext->getValueByName(aName) : uno::Any(); } // XCurrentContext virtual uno::Any SAL_CALL getValueByName( OUString const & aName) throw (uno::RuntimeException, std::exception) SAL_OVERRIDE; }; uno::Any SAL_CALL SimpleCurrentContext::getValueByName( OUString const & aName) throw (uno::RuntimeException, std::exception) { return getChainedValueByName(aName); } } class ConfigurationErrorHandler::Context : public SimpleCurrentContext { public: Context() : SimpleCurrentContext( uno::getCurrentContext() ) { } virtual ~Context() { } // XCurrentContext virtual uno::Any SAL_CALL getValueByName( OUString const & aName) throw (uno::RuntimeException, std::exception) SAL_OVERRIDE; private: InteractionHandler m_xHandler; }; uno::Any SAL_CALL ConfigurationErrorHandler::Context::getValueByName( OUString const & aName) throw (uno::RuntimeException, std::exception) { if ( aName == CONFIG_ERROR_HANDLER ) { if ( !m_xHandler.is() ) m_xHandler = ConfigurationErrorHandler::getDefaultInteractionHandler(); return uno::Any( m_xHandler ); } return SimpleCurrentContext::getValueByName( aName ); } ConfigurationErrorHandler::~ConfigurationErrorHandler() { deactivate(); } /// installs the handler into the current context void ConfigurationErrorHandler::activate() { if (!m_pContext) { m_pContext = new Context; m_pContext->acquire(); } m_pContext->install(); } /// deinstalls the handler from the current context, restoring the previous context void ConfigurationErrorHandler::deactivate() { if (m_pContext) { m_pContext->deinstall(); m_pContext->release(); m_pContext = 0; } } ConfigurationErrorHandler::InteractionHandler ConfigurationErrorHandler::getDefaultInteractionHandler() { uno::Reference< uno::XComponentContext > xContext = ::comphelper::getProcessComponentContext(); InteractionHandler xHandler( com::sun::star::task::InteractionHandler::createWithParent(xContext, 0), UNO_QUERY ); return xHandler; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * 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 . */ #include "configinit.hxx" #include "desktop.hrc" #include "app.hxx" #include <comphelper/processfactory.hxx> #include <uno/current_context.hxx> #include <cppuhelper/implbase1.hxx> #include <rtl/ustrbuf.hxx> #include <osl/diagnose.h> #include <stdio.h> #include <com/sun/star/task/InteractionHandler.hpp> namespace uno = ::com::sun::star::uno; namespace lang = ::com::sun::star::lang; using uno::UNO_QUERY; static char const CONFIG_ERROR_HANDLER[] = "configuration.interaction-handler"; // ConfigurationErrorHandler namespace { typedef uno::Reference< uno::XCurrentContext > CurrentContext; class SimpleCurrentContext : public cppu::WeakImplHelper1< uno::XCurrentContext > { CurrentContext m_xChainedContext; public: explicit SimpleCurrentContext(const CurrentContext & xChainedContext) : m_xChainedContext(xChainedContext) {} void install() { uno::setCurrentContext(this); } void deinstall() { uno::setCurrentContext(m_xChainedContext); } uno::Any getChainedValueByName( OUString const & aName) const { return m_xChainedContext.is() ? m_xChainedContext->getValueByName(aName) : uno::Any(); } // XCurrentContext virtual uno::Any SAL_CALL getValueByName( OUString const & aName) throw (uno::RuntimeException, std::exception) SAL_OVERRIDE; }; uno::Any SAL_CALL SimpleCurrentContext::getValueByName( OUString const & aName) throw (uno::RuntimeException, std::exception) { return getChainedValueByName(aName); } } class ConfigurationErrorHandler::Context : public SimpleCurrentContext { public: Context() : SimpleCurrentContext( uno::getCurrentContext() ) { } virtual ~Context() { } // XCurrentContext virtual uno::Any SAL_CALL getValueByName( OUString const & aName) throw (uno::RuntimeException, std::exception) SAL_OVERRIDE; private: InteractionHandler m_xHandler; }; uno::Any SAL_CALL ConfigurationErrorHandler::Context::getValueByName( OUString const & aName) throw (uno::RuntimeException, std::exception) { if ( aName == CONFIG_ERROR_HANDLER ) { if ( !m_xHandler.is() ) m_xHandler = ConfigurationErrorHandler::getDefaultInteractionHandler(); return uno::Any( m_xHandler ); } return SimpleCurrentContext::getValueByName( aName ); } ConfigurationErrorHandler::~ConfigurationErrorHandler() { deactivate(); } /// installs the handler into the current context void ConfigurationErrorHandler::activate() { if (!m_pContext) { m_pContext = new Context; m_pContext->acquire(); } m_pContext->install(); } /// deinstalls the handler from the current context, restoring the previous context void ConfigurationErrorHandler::deactivate() { if (m_pContext) { m_pContext->deinstall(); m_pContext->release(); m_pContext = 0; } } ConfigurationErrorHandler::InteractionHandler ConfigurationErrorHandler::getDefaultInteractionHandler() { uno::Reference< uno::XComponentContext > xContext = ::comphelper::getProcessComponentContext(); InteractionHandler xHandler( com::sun::star::task::InteractionHandler::createWithParent(xContext, 0), UNO_QUERY ); return xHandler; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
Remove comment filename
Remove comment filename This file was rm/mv on commit 47692bfc1275bfa24a7fb2627cc263142549d29d Change-Id: I141794aee5c57e345334af42fcea4eaa71709f1b Reviewed-on: https://gerrit.libreoffice.org/16259 Reviewed-by: Andras Timar <[email protected]> Tested-by: Andras Timar <[email protected]>
C++
mpl-2.0
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
928fe027693637bda0f1a43acf08a7dbe7e75f18
src/piggy_back_loggers/SD_Mag_Prototype/Firmware/magnetometer.cpp
src/piggy_back_loggers/SD_Mag_Prototype/Firmware/magnetometer.cpp
#include "magnetometer.h" #include <Arduino.h> #include <DebugMacros.h> #include <LSM303CTypes.h> #include <SparkFunIMU.h> #include <SparkFunLSM303C.h> #include "powerSleep.h" #include "state.h" /*********************************************************************\ * * Library for interfacing with the SparkFun LSM303C magnetometer. * * Functions: * Initialize Magnetomter * Read Data * \*********************************************************************/ void magnetometerInit(LSM303C *mag) { twiPowerUp(); if (mag->begin( MODE_I2C, MAG_DO_20_Hz, MAG_FS_8_Ga, MAG_BDU_DISABLE, MAG_OMXY_LOW_POWER, MAG_OMZ_MEDIUM_PERFORMANCE, MAG_MD_CONTINUOUS, ACC_FS_2g, ACC_BDU_DISABLE, ACC_DISABLE_ALL, ACC_ODR_POWER_DOWN ) != IMU_SUCCESS) { Serial.println("Magnetometer setup failed. Check connection and reset."); while(1); } twiPowerDown(); return; } void readData(LSM303C* mag, volatile SignalState_t* SignalState) { twiPowerUp(); SignalState->x[0] = SignalState->x[1]; SignalState->x[1] = mag->readMagZ(); twiPowerDown(); return; } void initializeData(LSM303C* mag, volatile SignalState_t* SignalState) { twiPowerUp(); SignalState->x[0] = mag->readMagZ(); SignalState->x[1] = SignalState->x[0]; SignalState->x_max = SignalState->x[1]; SignalState->x_min = SignalState->x[1]; SignalState->currentMax = SignalState->x[1]; SignalState->currentMin = SignalState->x[1]; twiPowerDown(); return; }
#include "magnetometer.h" #include <Arduino.h> #include <DebugMacros.h> #include <LSM303CTypes.h> #include <SparkFunIMU.h> #include <SparkFunLSM303C.h> #include "powerSleep.h" #include "state.h" /*********************************************************************\ * * Library for interfacing with the SparkFun LSM303C magnetometer. * * Functions: * Initialize Magnetomter * Read Data * Initialize Data * \*********************************************************************/ void magnetometerInit(LSM303C *mag) { twiPowerUp(); if (mag->begin( MODE_I2C, MAG_DO_20_Hz, MAG_FS_8_Ga, MAG_BDU_DISABLE, MAG_OMXY_LOW_POWER, MAG_OMZ_MEDIUM_PERFORMANCE, MAG_MD_CONTINUOUS, ACC_FS_2g, ACC_BDU_DISABLE, ACC_DISABLE_ALL, ACC_ODR_POWER_DOWN ) != IMU_SUCCESS) { Serial.println("Magnetometer setup failed. Check connection and reset."); while(1); } twiPowerDown(); return; } void readData(LSM303C* mag, volatile SignalState_t* SignalState) { twiPowerUp(); SignalState->x[0] = SignalState->x[1]; SignalState->x[1] = mag->readMagZ(); twiPowerDown(); return; } void initializeData(LSM303C* mag, volatile SignalState_t* SignalState) { twiPowerUp(); SignalState->x[0] = mag->readMagZ(); SignalState->x[1] = SignalState->x[0]; SignalState->x_max = SignalState->x[1]; SignalState->x_min = SignalState->x[1]; SignalState->currentMax = SignalState->x[1]; SignalState->currentMin = SignalState->x[1]; twiPowerDown(); return; }
Update magnetometer.cpp
Update magnetometer.cpp Updated comments
C++
bsd-3-clause
UCHIC/WaterMonitor
674e7c9b0c390fbfa274556b04ecedc337b0f0c2
src/plugins/qmlprojectmanager/fileformat/qmlprojectfileformat.cpp
src/plugins/qmlprojectmanager/fileformat/qmlprojectfileformat.cpp
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** 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, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "qmlprojectfileformat.h" #include "qmlprojectitem.h" #include "filefilteritems.h" #include <qmljs/qmljssimplereader.h> #include <QVariant> #include <QDebug> enum { debug = false }; namespace { void setupFileFilterItem(QmlProjectManager::FileFilterBaseItem *fileFilterItem, const QmlJS::SimpleReaderNode::Ptr &node) { const QVariant directoryProperty = node->property(QLatin1String("directory")); if (directoryProperty.isValid()) fileFilterItem->setDirectory(directoryProperty.toString()); const QVariant recursiveProperty = node->property(QLatin1String("recursive")); if (recursiveProperty.isValid()) fileFilterItem->setRecursive(recursiveProperty.toBool()); const QVariant pathsProperty = node->property(QLatin1String("paths")); if (pathsProperty.isValid()) fileFilterItem->setPathsProperty(pathsProperty.toStringList()); if (debug) qDebug() << "directory:" << directoryProperty << "recursive" << recursiveProperty << "paths" << pathsProperty; } } //namespace namespace QmlProjectManager { QmlProjectItem *QmlProjectFileFormat::parseProjectFile(const QString &fileName, QString *errorMessage) { QmlJS::SimpleReader simpleQmlJSReader; const QmlJS::SimpleReaderNode::Ptr rootNode = simpleQmlJSReader.readFile(fileName); if (!simpleQmlJSReader.errors().isEmpty() || !rootNode->isValid()) { qWarning() << "unable to parse:" << fileName; qWarning() << simpleQmlJSReader.errors(); if (errorMessage) *errorMessage = simpleQmlJSReader.errors().join(QLatin1String(", ")); return 0; } if (rootNode->name() == QLatin1String("Project")) { QmlProjectItem *projectItem = new QmlProjectItem(); const QVariant mainFileProperty = rootNode->property(QLatin1String("mainFile")); if (mainFileProperty.isValid()) projectItem->setMainFile(mainFileProperty.toString()); const QVariant importPathsProperty = rootNode->property(QLatin1String("importPaths")); if (importPathsProperty.isValid()) projectItem->setImportPaths(importPathsProperty.toStringList()); if (debug) qDebug() << "importPath:" << importPathsProperty << "mainFile:" << mainFileProperty; foreach (const QmlJS::SimpleReaderNode::Ptr &childNode, rootNode->children()) { if (childNode->name() == QLatin1String("QmlFiles")) { if (debug) qDebug() << "QmlFiles"; QmlFileFilterItem *qmlFileFilterItem = new QmlFileFilterItem(projectItem); setupFileFilterItem(qmlFileFilterItem, childNode); projectItem->appendContent(qmlFileFilterItem); } else if (childNode->name() == QLatin1String("JavaScriptFiles")) { if (debug) qDebug() << "JavaScriptFiles"; JsFileFilterItem *jsFileFilterItem = new JsFileFilterItem(projectItem); setupFileFilterItem(jsFileFilterItem, childNode); projectItem->appendContent(jsFileFilterItem); } else if (childNode->name() == QLatin1String("ImageFiles")) { if (debug) qDebug() << "ImageFiles"; ImageFileFilterItem *imageFileFilterItem = new ImageFileFilterItem(projectItem); setupFileFilterItem(imageFileFilterItem, childNode); projectItem->appendContent(imageFileFilterItem); } else if (childNode->name() == QLatin1String("CssFiles")) { if (debug) qDebug() << "CssFiles"; CssFileFilterItem *cssFileFilterItem = new CssFileFilterItem(projectItem); setupFileFilterItem(cssFileFilterItem, childNode); projectItem->appendContent(cssFileFilterItem); } else { qWarning() << "Unkwown type:" << childNode->name(); } } return projectItem; } if (errorMessage) *errorMessage = tr("Invalid root element: %1").arg(rootNode->name()); return 0; } } // namespace QmlProjectManager
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** 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, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "qmlprojectfileformat.h" #include "qmlprojectitem.h" #include "filefilteritems.h" #include <qmljs/qmljssimplereader.h> #include <QVariant> #include <QDebug> enum { debug = false }; namespace { void setupFileFilterItem(QmlProjectManager::FileFilterBaseItem *fileFilterItem, const QmlJS::SimpleReaderNode::Ptr &node) { const QVariant directoryProperty = node->property(QLatin1String("directory")); if (directoryProperty.isValid()) fileFilterItem->setDirectory(directoryProperty.toString()); const QVariant recursiveProperty = node->property(QLatin1String("recursive")); if (recursiveProperty.isValid()) fileFilterItem->setRecursive(recursiveProperty.toBool()); const QVariant pathsProperty = node->property(QLatin1String("paths")); if (pathsProperty.isValid()) fileFilterItem->setPathsProperty(pathsProperty.toStringList()); if (debug) qDebug() << "directory:" << directoryProperty << "recursive" << recursiveProperty << "paths" << pathsProperty; } } //namespace namespace QmlProjectManager { QmlProjectItem *QmlProjectFileFormat::parseProjectFile(const QString &fileName, QString *errorMessage) { QmlJS::SimpleReader simpleQmlJSReader; const QmlJS::SimpleReaderNode::Ptr rootNode = simpleQmlJSReader.readFile(fileName); if (!simpleQmlJSReader.errors().isEmpty() || !rootNode->isValid()) { qWarning() << "unable to parse:" << fileName; qWarning() << simpleQmlJSReader.errors(); if (errorMessage) *errorMessage = simpleQmlJSReader.errors().join(QLatin1String(", ")); return 0; } if (rootNode->name() == QLatin1String("Project")) { QmlProjectItem *projectItem = new QmlProjectItem(); const QVariant mainFileProperty = rootNode->property(QLatin1String("mainFile")); if (mainFileProperty.isValid()) projectItem->setMainFile(mainFileProperty.toString()); const QVariant importPathsProperty = rootNode->property(QLatin1String("importPaths")); if (importPathsProperty.isValid()) projectItem->setImportPaths(importPathsProperty.toStringList()); if (debug) qDebug() << "importPath:" << importPathsProperty << "mainFile:" << mainFileProperty; foreach (const QmlJS::SimpleReaderNode::Ptr &childNode, rootNode->children()) { if (childNode->name() == QLatin1String("QmlFiles")) { if (debug) qDebug() << "QmlFiles"; QmlFileFilterItem *qmlFileFilterItem = new QmlFileFilterItem(projectItem); setupFileFilterItem(qmlFileFilterItem, childNode); projectItem->appendContent(qmlFileFilterItem); } else if (childNode->name() == QLatin1String("JavaScriptFiles")) { if (debug) qDebug() << "JavaScriptFiles"; JsFileFilterItem *jsFileFilterItem = new JsFileFilterItem(projectItem); setupFileFilterItem(jsFileFilterItem, childNode); projectItem->appendContent(jsFileFilterItem); } else if (childNode->name() == QLatin1String("ImageFiles")) { if (debug) qDebug() << "ImageFiles"; ImageFileFilterItem *imageFileFilterItem = new ImageFileFilterItem(projectItem); setupFileFilterItem(imageFileFilterItem, childNode); projectItem->appendContent(imageFileFilterItem); } else if (childNode->name() == QLatin1String("CssFiles")) { if (debug) qDebug() << "CssFiles"; CssFileFilterItem *cssFileFilterItem = new CssFileFilterItem(projectItem); setupFileFilterItem(cssFileFilterItem, childNode); projectItem->appendContent(cssFileFilterItem); } else { qWarning() << "Unknown type:" << childNode->name(); } } return projectItem; } if (errorMessage) *errorMessage = tr("Invalid root element: %1").arg(rootNode->name()); return 0; } } // namespace QmlProjectManager
Fix spelling
QmlProjectManager: Fix spelling Change-Id: Ia03bb14c7e19090fa71ebf35597539a254bcb308 Reviewed-by: Christian Stenger <[email protected]>
C++
lgpl-2.1
Distrotech/qtcreator,xianian/qt-creator,darksylinc/qt-creator,maui-packages/qt-creator,AltarBeastiful/qt-creator,farseerri/git_code,amyvmiwei/qt-creator,danimo/qt-creator,darksylinc/qt-creator,martyone/sailfish-qtcreator,maui-packages/qt-creator,martyone/sailfish-qtcreator,amyvmiwei/qt-creator,colede/qtcreator,kuba1/qtcreator,darksylinc/qt-creator,omniacreator/qtcreator,xianian/qt-creator,colede/qtcreator,darksylinc/qt-creator,colede/qtcreator,AltarBeastiful/qt-creator,kuba1/qtcreator,darksylinc/qt-creator,kuba1/qtcreator,colede/qtcreator,danimo/qt-creator,AltarBeastiful/qt-creator,martyone/sailfish-qtcreator,omniacreator/qtcreator,amyvmiwei/qt-creator,darksylinc/qt-creator,kuba1/qtcreator,omniacreator/qtcreator,martyone/sailfish-qtcreator,martyone/sailfish-qtcreator,kuba1/qtcreator,martyone/sailfish-qtcreator,omniacreator/qtcreator,farseerri/git_code,xianian/qt-creator,amyvmiwei/qt-creator,colede/qtcreator,kuba1/qtcreator,colede/qtcreator,farseerri/git_code,danimo/qt-creator,amyvmiwei/qt-creator,Distrotech/qtcreator,farseerri/git_code,kuba1/qtcreator,danimo/qt-creator,Distrotech/qtcreator,xianian/qt-creator,AltarBeastiful/qt-creator,kuba1/qtcreator,xianian/qt-creator,AltarBeastiful/qt-creator,farseerri/git_code,amyvmiwei/qt-creator,maui-packages/qt-creator,omniacreator/qtcreator,AltarBeastiful/qt-creator,darksylinc/qt-creator,AltarBeastiful/qt-creator,Distrotech/qtcreator,farseerri/git_code,omniacreator/qtcreator,danimo/qt-creator,Distrotech/qtcreator,martyone/sailfish-qtcreator,danimo/qt-creator,omniacreator/qtcreator,darksylinc/qt-creator,xianian/qt-creator,danimo/qt-creator,amyvmiwei/qt-creator,martyone/sailfish-qtcreator,maui-packages/qt-creator,xianian/qt-creator,maui-packages/qt-creator,maui-packages/qt-creator,Distrotech/qtcreator,danimo/qt-creator,kuba1/qtcreator,colede/qtcreator,AltarBeastiful/qt-creator,danimo/qt-creator,maui-packages/qt-creator,martyone/sailfish-qtcreator,farseerri/git_code,amyvmiwei/qt-creator,farseerri/git_code,xianian/qt-creator,xianian/qt-creator,Distrotech/qtcreator
5a467eb5a11198a8e072c60ebc6399938c76aae8
mimosa/stream/direct-fd-stream.cc
mimosa/stream/direct-fd-stream.cc
#include <sys/sendfile.h> #include <cerrno> #include <algorithm> #include "direct-fd-stream.hh" #include "copy.hh" namespace mimosa { namespace stream { DirectFdStream::DirectFdStream(int fd, bool own_fd) : fd_(fd), own_fd_(own_fd), mode_(0) { } DirectFdStream::~DirectFdStream() { if (own_fd_ && fd_ >= 0) { ::close(fd_); fd_ = -1; } } int64_t DirectFdStream::write(const char * data, uint64_t nbytes, runtime::Time /*timeout*/) { return ::write(fd_, data, nbytes); } int64_t DirectFdStream::writev(const struct iovec *iov, int iovcnt, runtime::Time /*timeout*/) { return ::writev(fd_, iov, iovcnt < IOV_MAX ? iovcnt : IOV_MAX); } int64_t DirectFdStream::read(char * data, uint64_t nbytes, runtime::Time /*timeout*/) { return ::read(fd_, data, nbytes); } int64_t DirectFdStream::readv(const struct iovec *iov, int iovcnt, runtime::Time /*timeout*/) { return ::readv(fd_, iov, iovcnt < IOV_MAX ? iovcnt : IOV_MAX); } void DirectFdStream::close() { assert(own_fd_); if (own_fd_ && fd_ >= 0) { int fd = fd_; fd_ = -1; ::close(fd); } } bool DirectFdStream::stat() const { struct ::stat st; if (::fstat(fd_, &st)) return false; mode_ = st.st_mode; return true; } int64_t copySendfile(DirectFdStream & input, DirectFdStream & output, int64_t max_bytes, runtime::Time /*timeout*/) { int64_t total = 0; while (total < max_bytes || max_bytes == 0) { int64_t limit; if (max_bytes == 0) limit = 128 * 1024; else limit = std::min((int64_t)128 * 1024, (int64_t)max_bytes - total); ssize_t bytes = ::sendfile(input.fd(), output.fd(), nullptr, limit); if (bytes < 0) return total; total += bytes; } return total; } int64_t copySplice(DirectFdStream & input, DirectFdStream & output, int64_t max_bytes, runtime::Time /*timeout*/) { int64_t total = 0; while (total < max_bytes || max_bytes == 0) { int64_t limit; if (max_bytes == 0) limit = 128 * 1024; else limit = std::min((uint64_t)128 * 1024, (uint64_t)max_bytes - total); ssize_t bytes = ::splice(input.fd(), nullptr, output.fd(), nullptr, limit, 0); if (bytes < 0) return total; total += bytes; } return total; } int64_t copy(DirectFdStream & input, DirectFdStream & output, int64_t max_bytes, runtime::Time timeout) { if (S_ISREG(input.fdMode())) return copySendfile(input, output, max_bytes, timeout); else if (S_ISFIFO(input.fdMode()) || S_ISSOCK(input.fdMode())) return copySplice(input, output, max_bytes, timeout); return copy(static_cast<Stream &> (input), static_cast<Stream &> (output), max_bytes, timeout); } } }
#include <sys/sendfile.h> #include <cerrno> #include <algorithm> #include "direct-fd-stream.hh" #include "copy.hh" namespace mimosa { namespace stream { DirectFdStream::DirectFdStream(int fd, bool own_fd) : fd_(fd), own_fd_(own_fd), mode_(0) { } DirectFdStream::~DirectFdStream() { if (own_fd_ && fd_ >= 0) { ::close(fd_); fd_ = -1; } } int64_t DirectFdStream::write(const char * data, uint64_t nbytes, runtime::Time /*timeout*/) { return ::write(fd_, data, nbytes); } int64_t DirectFdStream::writev(const struct iovec *iov, int iovcnt, runtime::Time /*timeout*/) { return ::writev(fd_, iov, iovcnt < IOV_MAX ? iovcnt : IOV_MAX); } int64_t DirectFdStream::read(char * data, uint64_t nbytes, runtime::Time /*timeout*/) { return ::read(fd_, data, nbytes); } int64_t DirectFdStream::readv(const struct iovec *iov, int iovcnt, runtime::Time /*timeout*/) { return ::readv(fd_, iov, iovcnt < IOV_MAX ? iovcnt : IOV_MAX); } void DirectFdStream::close() { assert(own_fd_); if (own_fd_ && fd_ >= 0) { int fd = fd_; fd_ = -1; ::close(fd); } } bool DirectFdStream::stat() const { struct ::stat st; if (::fstat(fd_, &st)) return false; mode_ = st.st_mode; return true; } int64_t copySendfile(DirectFdStream & input, DirectFdStream & output, int64_t max_bytes, runtime::Time /*timeout*/) { int64_t total = 0; while (total < max_bytes || max_bytes == 0) { int64_t limit; if (max_bytes == 0) limit = 128 * 1024; else limit = std::min((int64_t)128 * 1024, (int64_t)max_bytes - total); ssize_t bytes = ::sendfile(output.fd(), input.fd(), nullptr, limit); if (bytes < 0) return total; total += bytes; } return total; } int64_t copySplice(DirectFdStream & input, DirectFdStream & output, int64_t max_bytes, runtime::Time /*timeout*/) { int64_t total = 0; while (total < max_bytes || max_bytes == 0) { int64_t limit; if (max_bytes == 0) limit = 128 * 1024; else limit = std::min((uint64_t)128 * 1024, (uint64_t)max_bytes - total); ssize_t bytes = ::splice(input.fd(), nullptr, output.fd(), nullptr, limit, 0); if (bytes < 0) return total; total += bytes; } return total; } int64_t copy(DirectFdStream & input, DirectFdStream & output, int64_t max_bytes, runtime::Time timeout) { if (S_ISREG(input.fdMode())) return copySendfile(input, output, max_bytes, timeout); else if (S_ISFIFO(input.fdMode()) || S_ISSOCK(input.fdMode())) return copySplice(input, output, max_bytes, timeout); return copy(static_cast<Stream &> (input), static_cast<Stream &> (output), max_bytes, timeout); } } }
fix the sendfile call
DirectFdStream: fix the sendfile call
C++
mit
abique/mimosa,abique/mimosa
a5bdd6cce36d10cc374ad87b6a1c8f3fb7fb6d93
webkit/tools/test_shell/plugin_tests.cc
webkit/tools/test_shell/plugin_tests.cc
// Copyright (c) 2006-2008 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 <string> #include "base/file_path.h" #include "base/file_util.h" #include "base/path_service.h" #include "base/string_util.h" #include "net/base/escape.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/WebKit/WebKit/chromium/public/WebData.h" #include "third_party/WebKit/WebKit/chromium/public/WebFrame.h" #include "third_party/WebKit/WebKit/chromium/public/WebInputEvent.h" #include "third_party/WebKit/WebKit/chromium/public/WebScriptSource.h" #include "third_party/WebKit/WebKit/chromium/public/WebView.h" #include "webkit/tools/test_shell/test_shell.h" #include "webkit/tools/test_shell/test_shell_test.h" using WebKit::WebFrame; using WebKit::WebScriptSource; using WebKit::WebString; #if defined(OS_WIN) #define TEST_PLUGIN_NAME "npapi_test_plugin.dll" #elif defined(OS_MACOSX) #define TEST_PLUGIN_NAME "npapi_test_plugin.plugin" #elif defined(OS_POSIX) #define TEST_PLUGIN_NAME "libnpapi_test_plugin.so" #endif #if defined(OS_MACOSX) #define TEST_PLUGIN_DIRECTORY "PlugIns" #else #define TEST_PLUGIN_DIRECTORY "plugins" #endif // Ignore these until 64-bit plugin build is fixed. http://crbug.com/18337 #if !defined(ARCH_CPU_64_BITS) // Provides functionality for creating plugin tests. class PluginTest : public TestShellTest { public: PluginTest() { FilePath executable_directory; PathService::Get(base::DIR_EXE, &executable_directory); plugin_src_ = executable_directory.AppendASCII(TEST_PLUGIN_NAME); CHECK(file_util::PathExists(plugin_src_)); plugin_file_path_ = executable_directory.AppendASCII(TEST_PLUGIN_DIRECTORY); file_util::CreateDirectory(plugin_file_path_); plugin_file_path_ = plugin_file_path_.AppendASCII(TEST_PLUGIN_NAME); } void CopyTestPlugin() { // On Linux, we need to delete before copying because if the plugin is a // hard link, the copy will fail. DeleteTestPlugin(); ASSERT_TRUE(file_util::CopyDirectory(plugin_src_, plugin_file_path_, true)); } void DeleteTestPlugin() { file_util::Delete(plugin_file_path_, true); } virtual void SetUp() { CopyTestPlugin(); TestShellTest::SetUp(); } virtual void TearDown() { DeleteTestPlugin(); TestShellTest::TearDown(); } FilePath plugin_src_; FilePath plugin_file_path_; }; #if !defined(OS_LINUX) // TODO(tony): http://code.google.com/p/chromium/issues/detail?id=51402 // Tests navigator.plugins.refresh() works. TEST_F(PluginTest, Refresh) { std::string html = "\ <div id='result'>Test running....</div>\ <script>\ function check() {\ var l = navigator.plugins.length;\ var result = document.getElementById('result');\ for(var i = 0; i < l; i++) {\ if (navigator.plugins[i].filename == '" TEST_PLUGIN_NAME "') {\ result.innerHTML = 'DONE';\ break;\ }\ }\ \ if (result.innerHTML != 'DONE')\ result.innerHTML = 'FAIL';\ }\ </script>\ "; WebScriptSource call_check( WebString::fromUTF8("check();")); WebScriptSource refresh( WebString::fromUTF8("navigator.plugins.refresh(false)")); // Remove any leftover from previous tests if they exist. We must also // refresh WebKit's plugin cache since it might have had an entry for the // test plugin from a previous test. DeleteTestPlugin(); ASSERT_FALSE(file_util::PathExists(plugin_file_path_)); test_shell_->webView()->mainFrame()->executeScript(refresh); test_shell_->webView()->mainFrame()->loadHTMLString( html, GURL("about:blank")); test_shell_->WaitTestFinished(); std::string text; test_shell_->webView()->mainFrame()->executeScript(call_check); text = test_shell_->webView()->mainFrame()->contentAsText(10000).utf8(); ASSERT_EQ(text, "FAIL"); CopyTestPlugin(); test_shell_->webView()->mainFrame()->executeScript(refresh); test_shell_->webView()->mainFrame()->executeScript(call_check); text = test_shell_->webView()->mainFrame()->contentAsText(10000).utf8(); ASSERT_EQ(text, "DONE"); } #endif // Tests that if a frame is deleted as a result of calling NPP_HandleEvent, we // don't crash. TEST_F(PluginTest, DeleteFrameDuringEvent) { FilePath test_html = data_dir_; test_html = test_html.AppendASCII("plugins"); test_html = test_html.AppendASCII("delete_frame.html"); test_shell_->LoadFile(test_html); test_shell_->WaitTestFinished(); WebKit::WebMouseEvent input; input.button = WebKit::WebMouseEvent::ButtonLeft; input.x = 50; input.y = 50; input.type = WebKit::WebInputEvent::MouseUp; test_shell_->webView()->handleInputEvent(input); // No crash means we passed. } #if defined(OS_WIN) BOOL CALLBACK EnumChildProc(HWND hwnd, LPARAM lparam) { HWND* plugin_hwnd = reinterpret_cast<HWND*>(lparam); if (*plugin_hwnd) { // More than one child window found, unexpected. plugin_hwnd = NULL; return FALSE; } *plugin_hwnd = hwnd; return TRUE; } // Tests that hiding/showing the parent frame hides/shows the plugin. TEST_F(PluginTest, PluginVisibilty) { FilePath test_html = data_dir_; test_html = test_html.AppendASCII("plugins"); test_html = test_html.AppendASCII("plugin_visibility.html"); test_shell_->LoadFile(test_html); test_shell_->WaitTestFinished(); WebFrame* main_frame = test_shell_->webView()->mainFrame(); HWND frame_hwnd = test_shell_->webViewWnd(); HWND plugin_hwnd = NULL; EnumChildWindows(frame_hwnd, EnumChildProc, reinterpret_cast<LPARAM>(&plugin_hwnd)); ASSERT_TRUE(plugin_hwnd != NULL); ASSERT_FALSE(IsWindowVisible(plugin_hwnd)); main_frame->executeScript(WebString::fromUTF8("showPlugin(true)")); ASSERT_TRUE(IsWindowVisible(plugin_hwnd)); main_frame->executeScript(WebString::fromUTF8("showFrame(false)")); ASSERT_FALSE(IsWindowVisible(plugin_hwnd)); main_frame->executeScript(WebString::fromUTF8("showFrame(true)")); ASSERT_TRUE(IsWindowVisible(plugin_hwnd)); } #endif #endif //!ARCH_CPU_64_BITS
// Copyright (c) 2006-2008 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 <string> #include "base/file_path.h" #include "base/file_util.h" #include "base/path_service.h" #include "base/string_util.h" #include "net/base/escape.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/WebKit/WebKit/chromium/public/WebData.h" #include "third_party/WebKit/WebKit/chromium/public/WebFrame.h" #include "third_party/WebKit/WebKit/chromium/public/WebInputEvent.h" #include "third_party/WebKit/WebKit/chromium/public/WebScriptSource.h" #include "third_party/WebKit/WebKit/chromium/public/WebView.h" #include "webkit/tools/test_shell/test_shell.h" #include "webkit/tools/test_shell/test_shell_test.h" using WebKit::WebFrame; using WebKit::WebScriptSource; using WebKit::WebString; #if defined(OS_WIN) #define TEST_PLUGIN_NAME "npapi_test_plugin.dll" #elif defined(OS_MACOSX) #define TEST_PLUGIN_NAME "npapi_test_plugin.plugin" #elif defined(OS_POSIX) #define TEST_PLUGIN_NAME "libnpapi_test_plugin.so" #endif #if defined(OS_MACOSX) #define TEST_PLUGIN_DIRECTORY "PlugIns" #else #define TEST_PLUGIN_DIRECTORY "plugins" #endif // Ignore these until 64-bit plugin build is fixed. http://crbug.com/18337 #if !defined(ARCH_CPU_64_BITS) // Provides functionality for creating plugin tests. class PluginTest : public TestShellTest { public: PluginTest() { FilePath executable_directory; PathService::Get(base::DIR_EXE, &executable_directory); plugin_src_ = executable_directory.AppendASCII(TEST_PLUGIN_NAME); CHECK(file_util::PathExists(plugin_src_)); plugin_file_path_ = executable_directory.AppendASCII(TEST_PLUGIN_DIRECTORY); file_util::CreateDirectory(plugin_file_path_); plugin_file_path_ = plugin_file_path_.AppendASCII(TEST_PLUGIN_NAME); } void CopyTestPlugin() { // On Linux, we need to delete before copying because if the plugin is a // hard link, the copy will fail. DeleteTestPlugin(); ASSERT_TRUE(file_util::CopyDirectory(plugin_src_, plugin_file_path_, true)); } void DeleteTestPlugin() { file_util::Delete(plugin_file_path_, true); } virtual void SetUp() { CopyTestPlugin(); TestShellTest::SetUp(); } virtual void TearDown() { DeleteTestPlugin(); TestShellTest::TearDown(); } FilePath plugin_src_; FilePath plugin_file_path_; }; // Tests navigator.plugins.refresh() works. TEST_F(PluginTest, Refresh) { std::string html = "\ <div id='result'>Test running....</div>\ <script>\ function check() {\ var l = navigator.plugins.length;\ var result = document.getElementById('result');\ for(var i = 0; i < l; i++) {\ if (navigator.plugins[i].filename == '" TEST_PLUGIN_NAME "') {\ result.innerHTML = 'DONE';\ break;\ }\ }\ \ if (result.innerHTML != 'DONE')\ result.innerHTML = 'FAIL';\ }\ </script>\ "; WebScriptSource call_check( WebString::fromUTF8("check();")); WebScriptSource refresh( WebString::fromUTF8("navigator.plugins.refresh(false)")); // Remove any leftover from previous tests if they exist. We must also // refresh WebKit's plugin cache since it might have had an entry for the // test plugin from a previous test. DeleteTestPlugin(); ASSERT_FALSE(file_util::PathExists(plugin_file_path_)); test_shell_->webView()->mainFrame()->executeScript(refresh); test_shell_->webView()->mainFrame()->loadHTMLString( html, GURL("about:blank")); test_shell_->WaitTestFinished(); std::string text; test_shell_->webView()->mainFrame()->executeScript(call_check); text = test_shell_->webView()->mainFrame()->contentAsText(10000).utf8(); ASSERT_EQ(text, "FAIL"); CopyTestPlugin(); test_shell_->webView()->mainFrame()->executeScript(refresh); test_shell_->webView()->mainFrame()->executeScript(call_check); text = test_shell_->webView()->mainFrame()->contentAsText(10000).utf8(); ASSERT_EQ(text, "DONE"); } // Tests that if a frame is deleted as a result of calling NPP_HandleEvent, we // don't crash. TEST_F(PluginTest, DeleteFrameDuringEvent) { FilePath test_html = data_dir_; test_html = test_html.AppendASCII("plugins"); test_html = test_html.AppendASCII("delete_frame.html"); test_shell_->LoadFile(test_html); test_shell_->WaitTestFinished(); WebKit::WebMouseEvent input; input.button = WebKit::WebMouseEvent::ButtonLeft; input.x = 50; input.y = 50; input.type = WebKit::WebInputEvent::MouseUp; test_shell_->webView()->handleInputEvent(input); // No crash means we passed. } #if defined(OS_WIN) BOOL CALLBACK EnumChildProc(HWND hwnd, LPARAM lparam) { HWND* plugin_hwnd = reinterpret_cast<HWND*>(lparam); if (*plugin_hwnd) { // More than one child window found, unexpected. plugin_hwnd = NULL; return FALSE; } *plugin_hwnd = hwnd; return TRUE; } // Tests that hiding/showing the parent frame hides/shows the plugin. TEST_F(PluginTest, PluginVisibilty) { FilePath test_html = data_dir_; test_html = test_html.AppendASCII("plugins"); test_html = test_html.AppendASCII("plugin_visibility.html"); test_shell_->LoadFile(test_html); test_shell_->WaitTestFinished(); WebFrame* main_frame = test_shell_->webView()->mainFrame(); HWND frame_hwnd = test_shell_->webViewWnd(); HWND plugin_hwnd = NULL; EnumChildWindows(frame_hwnd, EnumChildProc, reinterpret_cast<LPARAM>(&plugin_hwnd)); ASSERT_TRUE(plugin_hwnd != NULL); ASSERT_FALSE(IsWindowVisible(plugin_hwnd)); main_frame->executeScript(WebString::fromUTF8("showPlugin(true)")); ASSERT_TRUE(IsWindowVisible(plugin_hwnd)); main_frame->executeScript(WebString::fromUTF8("showFrame(false)")); ASSERT_FALSE(IsWindowVisible(plugin_hwnd)); main_frame->executeScript(WebString::fromUTF8("showFrame(true)")); ASSERT_TRUE(IsWindowVisible(plugin_hwnd)); } #endif #endif //!ARCH_CPU_64_BITS
Revert "Disable failing test on Linux."
Revert "Disable failing test on Linux." This reverts commit r55243. The builder just needed to be clobbered. TBR=phajdan.jr Review URL: http://codereview.chromium.org/3074039 git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@55260 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
C++
bsd-3-clause
wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser
6d169f24747b64dda70820e5f11368385826d9c8
src/video_engine/main/test/AutoTest/helpers/vie_window_creator.cc
src/video_engine/main/test/AutoTest/helpers/vie_window_creator.cc
/* * Copyright (c) 2011 The WebRTC 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 in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "vie_window_creator.h" #include "vie_autotest_main.h" #include "vie_codec.h" #include "voe_codec.h" #if defined(WIN32) #include "vie_autotest_windows.h" #include <tchar.h> #include <ShellAPI.h> //ShellExecute #elif defined(WEBRTC_MAC_INTEL) #if defined(COCOA_RENDERING) #include "vie_autotest_mac_cocoa.h" #elif defined(CARBON_RENDERING) #include "vie_autotest_mac_carbon.h" #endif #elif defined(WEBRTC_LINUX) #include "vie_autotest_linux.h" #endif ViEWindowCreator::ViEWindowCreator() { // Create platform dependent render windows. window_manager_ = new ViEAutoTestWindowManager(); } ViEWindowCreator::~ViEWindowCreator() { delete window_manager_; } ViEAutoTestWindowManagerInterface* ViEWindowCreator::CreateTwoWindows() { #if (defined(_WIN32)) TCHAR window1Title[1024] = _T("ViE Autotest Window 1"); TCHAR window2Title[1024] = _T("ViE Autotest Window 2"); #else char window1Title[1024] = "ViE Autotest Window 1"; char window2Title[1024] = "ViE Autotest Window 2"; #endif AutoTestRect window1Size(352, 288, 600, 100); AutoTestRect window2Size(352, 288, 1000, 100); window_manager_->CreateWindows(window1Size, window2Size, window1Title, window2Title); window_manager_->SetTopmostWindow(); return window_manager_; } void ViEWindowCreator::TerminateWindows() { window_manager_->TerminateWindows(); }
/* * Copyright (c) 2011 The WebRTC 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 in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "vie_window_creator.h" #include "engine_configurations.h" #include "vie_autotest_main.h" #include "vie_codec.h" #include "voe_codec.h" #if defined(WIN32) #include "vie_autotest_windows.h" #include <tchar.h> #include <ShellAPI.h> //ShellExecute #elif defined(WEBRTC_MAC_INTEL) #if defined(COCOA_RENDERING) #include "vie_autotest_mac_cocoa.h" #elif defined(CARBON_RENDERING) #include "vie_autotest_mac_carbon.h" #endif #elif defined(WEBRTC_LINUX) #include "vie_autotest_linux.h" #endif ViEWindowCreator::ViEWindowCreator() { // Create platform dependent render windows. window_manager_ = new ViEAutoTestWindowManager(); } ViEWindowCreator::~ViEWindowCreator() { delete window_manager_; } ViEAutoTestWindowManagerInterface* ViEWindowCreator::CreateTwoWindows() { #if (defined(_WIN32)) TCHAR window1Title[1024] = _T("ViE Autotest Window 1"); TCHAR window2Title[1024] = _T("ViE Autotest Window 2"); #else char window1Title[1024] = "ViE Autotest Window 1"; char window2Title[1024] = "ViE Autotest Window 2"; #endif AutoTestRect window1Size(352, 288, 600, 100); AutoTestRect window2Size(352, 288, 1000, 100); window_manager_->CreateWindows(window1Size, window2Size, window1Title, window2Title); window_manager_->SetTopmostWindow(); return window_manager_; } void ViEWindowCreator::TerminateWindows() { window_manager_->TerminateWindows(); }
Fix Mac build error in vie_auto_test introduced in r666.
Fix Mac build error in vie_auto_test introduced in r666. COCOA_RENDERING was undefined. Committing without review. Review URL: http://webrtc-codereview.appspot.com/191002 git-svn-id: 917f5d3ca488f358c4d40eaec14422cf392ccec9@672 4adac7df-926f-26a2-2b94-8c16560cd09d
C++
bsd-3-clause
mwgoldsmith/ilbc,mwgoldsmith/libilbc,mwgoldsmith/ilbc,TimothyGu/libilbc,mwgoldsmith/libilbc,mwgoldsmith/libilbc,TimothyGu/libilbc,mwgoldsmith/ilbc,TimothyGu/libilbc,mwgoldsmith/ilbc,ShiftMediaProject/libilbc,mwgoldsmith/libilbc,TimothyGu/libilbc,ShiftMediaProject/libilbc,TimothyGu/libilbc,ShiftMediaProject/libilbc,ShiftMediaProject/libilbc,ShiftMediaProject/libilbc
75f54517a8a84224ef6f9fec8f4fff037d239956
Library/Sources/Stroika/Frameworks/UPnP/SSDP/Client/Listener.cpp
Library/Sources/Stroika/Frameworks/UPnP/SSDP/Client/Listener.cpp
/* * Copyright(c) Sophist Solutions, Inc. 1990-2019. All rights reserved */ #include "../../../StroikaPreComp.h" #include <vector> #include "../../../../Foundation/Characters/String_Constant.h" #include "../../../../Foundation/Characters/ToString.h" #include "../../../../Foundation/Containers/Bijection.h" #include "../../../../Foundation/Containers/Collection.h" #include "../../../../Foundation/Debug/Trace.h" #include "../../../../Foundation/Execution/Exceptions.h" #include "../../../../Foundation/Execution/Sleep.h" #include "../../../../Foundation/Execution/Thread.h" #include "../../../../Foundation/Execution/WaitForIOReady.h" #include "../../../../Foundation/IO/Network/ConnectionlessSocket.h" #include "../../../../Foundation/IO/Network/WaitForSocketIOReady.h" #include "../../../../Foundation/Streams/ExternallyOwnedMemoryInputStream.h" #include "../../../../Foundation/Streams/TextReader.h" #include "../Advertisement.h" #include "../Common.h" #include "Listener.h" using std::byte; using namespace Stroika::Foundation; using namespace Stroika::Foundation::Characters; using namespace Stroika::Foundation::Containers; using namespace Stroika::Foundation::IO; using namespace Stroika::Foundation::IO::Network; using namespace Stroika::Frameworks; using namespace Stroika::Frameworks::UPnP; using namespace Stroika::Frameworks::UPnP::SSDP; using namespace Stroika::Frameworks::UPnP::SSDP::Client; // Comment this in to turn on tracing in this module //#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1 /* ******************************************************************************** ****************************** Listener::Rep_ ********************************** ******************************************************************************** */ class Listener::Rep_ { public: Rep_ (IO::Network::InternetProtocol::IP::IPVersionSupport ipVersion) { static constexpr Execution::Activity kConstructingSSDPListener_{L"constucting SSDP Listener"sv}; Execution::DeclareActivity activity{&kConstructingSSDPListener_}; Socket::BindFlags bindFlags = Socket::BindFlags (); bindFlags.fReUseAddr = true; if (InternetProtocol::IP::SupportIPV4 (ipVersion)) { ConnectionlessSocket::Ptr s = ConnectionlessSocket::New (SocketAddress::INET, Socket::DGRAM); s.Bind (SocketAddress (Network::V4::kAddrAny, UPnP::SSDP::V4::kSocketAddress.GetPort ()), bindFlags); s.JoinMulticastGroup (UPnP::SSDP::V4::kSocketAddress.GetInternetAddress ()); fSockets_.Add (s); } if (InternetProtocol::IP::SupportIPV6 (ipVersion)) { ConnectionlessSocket::Ptr s = ConnectionlessSocket::New (SocketAddress::INET6, Socket::DGRAM); s.Bind (SocketAddress (Network::V6::kAddrAny, UPnP::SSDP::V6::kSocketAddress.GetPort ()), bindFlags); s.JoinMulticastGroup (UPnP::SSDP::V6::kSocketAddress.GetInternetAddress ()); fSockets_.Add (s); } } ~Rep_ () = default; void AddOnFoundCallback (const function<void (const SSDP::Advertisement& d)>& callOnFinds) { [[maybe_unused]] auto&& critSec = lock_guard{fCritSection_}; fFoundCallbacks_.push_back (callOnFinds); } void Start () { static const String kThreadName_ = L"SSDP Listener"sv; fThread_ = Execution::Thread::New ( [this] () { DoRun_ (); }, Execution::Thread::eAutoStart, kThreadName_); } void Stop () { if (fThread_ != nullptr) { fThread_.AbortAndWaitForDone (); fThread_ = nullptr; } } void DoRun_ () { // only stopped by thread abort WaitForSocketIOReady<ConnectionlessSocket::Ptr> readyChecker{fSockets_}; while (true) { for (ConnectionlessSocket::Ptr s : readyChecker.Wait ()) { try { byte buf[3 * 1024]; // not sure of max packet size SocketAddress from; size_t nBytesRead = s.ReceiveFrom (std::begin (buf), std::end (buf), 0, &from); Assert (nBytesRead <= NEltsOf (buf)); using namespace Streams; ParsePacketAndNotifyCallbacks_ (TextReader::New (ExternallyOwnedMemoryInputStream<byte>::New (std::begin (buf), std::begin (buf) + nBytesRead))); } catch (const Execution::Thread::AbortException&) { Execution::ReThrow (); } catch (...) { // ignore errors - and keep on trucking // but avoid wasting too much time if we get into an error storm #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"Caught/ignored exception for SSDP advertisement packet: %s", Characters::ToString (current_exception ()).c_str ()); #endif Execution::Sleep (1.0); } } } } void ParsePacketAndNotifyCallbacks_ (Streams::InputStream<Character>::Ptr in) { String firstLine = in.ReadLine ().Trim (); #if USE_NOISY_TRACE_IN_THIS_MODULE_ Debug::TraceContextBumper ctx ("Read SSDP Packet"); DbgTrace (L"firstLine: %s", firstLine.c_str ()); #endif const String kNOTIFY_LEAD = String_Constant (L"NOTIFY "); if (firstLine.length () > kNOTIFY_LEAD.length () and firstLine.SubString (0, kNOTIFY_LEAD.length ()) == kNOTIFY_LEAD) { SSDP::Advertisement d; while (true) { String line = in.ReadLine ().Trim (); if (line.empty ()) { break; } // Need to simplify this code (stroika string util) String label; String value; if (optional<size_t> n = line.Find (':')) { label = line.SubString (0, *n); value = line.SubString (*n + 1).Trim (); } if (not label.empty ()) { d.fRawHeaders.Add (label, value); } if (label.Compare (L"Location", Characters::CompareOptions::eCaseInsensitive) == 0) { d.fLocation = IO::Network::URI{value}; } else if (label.Compare (L"NT", Characters::CompareOptions::eCaseInsensitive) == 0) { d.fTarget = value; } else if (label.Compare (L"USN", Characters::CompareOptions::eCaseInsensitive) == 0) { d.fUSN = value; } else if (label.Compare (L"Server", Characters::CompareOptions::eCaseInsensitive) == 0) { d.fServer = value; } else if (label.Compare (L"NTS", Characters::CompareOptions::eCaseInsensitive) == 0) { if (value.Compare (L"ssdp:alive", Characters::CompareOptions::eCaseInsensitive) == 0) { d.fAlive = true; } else if (value.Compare (L"ssdp:byebye", Characters::CompareOptions::eCaseInsensitive) == 0) { d.fAlive = false; } } } { [[maybe_unused]] auto&& critSec = lock_guard{fCritSection_}; for (auto i : fFoundCallbacks_) { i (d); } } } } private: recursive_mutex fCritSection_; vector<function<void (const SSDP::Advertisement& d)>> fFoundCallbacks_; Collection<ConnectionlessSocket::Ptr> fSockets_; Execution::Thread::CleanupPtr fThread_{Execution::Thread::CleanupPtr::eAbortBeforeWaiting}; }; /* ******************************************************************************** ************************************* Listener ********************************* ******************************************************************************** */ Listener::Listener (IO::Network::InternetProtocol::IP::IPVersionSupport ipVersion) : fRep_ (make_shared<Rep_> (ipVersion)) { } Listener::Listener (const function<void (const SSDP::Advertisement& d)>& callOnFinds, IO::Network::InternetProtocol::IP::IPVersionSupport ipVersion) : Listener (ipVersion) { AddOnFoundCallback (callOnFinds); } Listener::Listener (const function<void (const SSDP::Advertisement& d)>& callOnFinds, IO::Network::InternetProtocol::IP::IPVersionSupport ipVersion, AutoStart) : Listener (callOnFinds, ipVersion) { Start (); } Listener::Listener (const function<void (const SSDP::Advertisement& d)>& callOnFinds, AutoStart) : Listener (callOnFinds) { Start (); } Listener::~Listener () { IgnoreExceptionsForCall (fRep_->Stop ()); } void Listener::AddOnFoundCallback (const function<void (const SSDP::Advertisement& d)>& callOnFinds) { fRep_->AddOnFoundCallback (callOnFinds); } void Listener::Start () { fRep_->Start (); } void Listener::Stop () { fRep_->Stop (); }
/* * Copyright(c) Sophist Solutions, Inc. 1990-2019. All rights reserved */ #include "../../../StroikaPreComp.h" #include <vector> #include "../../../../Foundation/Characters/String_Constant.h" #include "../../../../Foundation/Characters/ToString.h" #include "../../../../Foundation/Containers/Bijection.h" #include "../../../../Foundation/Containers/Collection.h" #include "../../../../Foundation/Debug/Trace.h" #include "../../../../Foundation/Execution/Exceptions.h" #include "../../../../Foundation/Execution/Sleep.h" #include "../../../../Foundation/Execution/Thread.h" #include "../../../../Foundation/Execution/WaitForIOReady.h" #include "../../../../Foundation/IO/Network/ConnectionlessSocket.h" #include "../../../../Foundation/IO/Network/WaitForSocketIOReady.h" #include "../../../../Foundation/Streams/ExternallyOwnedMemoryInputStream.h" #include "../../../../Foundation/Streams/TextReader.h" #include "../Advertisement.h" #include "../Common.h" #include "Listener.h" using std::byte; using namespace Stroika::Foundation; using namespace Stroika::Foundation::Characters; using namespace Stroika::Foundation::Containers; using namespace Stroika::Foundation::IO; using namespace Stroika::Foundation::IO::Network; using namespace Stroika::Frameworks; using namespace Stroika::Frameworks::UPnP; using namespace Stroika::Frameworks::UPnP::SSDP; using namespace Stroika::Frameworks::UPnP::SSDP::Client; // Comment this in to turn on tracing in this module //#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1 /* ******************************************************************************** ****************************** Listener::Rep_ ********************************** ******************************************************************************** */ class Listener::Rep_ { public: Rep_ (IO::Network::InternetProtocol::IP::IPVersionSupport ipVersion) { static constexpr Execution::Activity kConstructingSSDPListener_{L"constucting SSDP Listener"sv}; Execution::DeclareActivity activity{&kConstructingSSDPListener_}; Socket::BindFlags bindFlags = Socket::BindFlags (); bindFlags.fReUseAddr = true; if (InternetProtocol::IP::SupportIPV4 (ipVersion)) { ConnectionlessSocket::Ptr s = ConnectionlessSocket::New (SocketAddress::INET, Socket::DGRAM); s.Bind (SocketAddress (Network::V4::kAddrAny, UPnP::SSDP::V4::kSocketAddress.GetPort ()), bindFlags); s.JoinMulticastGroup (UPnP::SSDP::V4::kSocketAddress.GetInternetAddress ()); fSockets_.Add (s); } if (InternetProtocol::IP::SupportIPV6 (ipVersion)) { ConnectionlessSocket::Ptr s = ConnectionlessSocket::New (SocketAddress::INET6, Socket::DGRAM); s.Bind (SocketAddress (Network::V6::kAddrAny, UPnP::SSDP::V6::kSocketAddress.GetPort ()), bindFlags); s.JoinMulticastGroup (UPnP::SSDP::V6::kSocketAddress.GetInternetAddress ()); fSockets_.Add (s); } } ~Rep_ () = default; void AddOnFoundCallback (const function<void (const SSDP::Advertisement& d)>& callOnFinds) { [[maybe_unused]] auto&& critSec = lock_guard{fCritSection_}; fFoundCallbacks_.push_back (callOnFinds); } void Start () { static const String kThreadName_ = L"SSDP Listener"sv; fThread_ = Execution::Thread::New ( [this] () { DoRun_ (); }, Execution::Thread::eAutoStart, kThreadName_); } void Stop () { if (fThread_ != nullptr) { fThread_.AbortAndWaitForDone (); fThread_ = nullptr; } } void DoRun_ () { // only stopped by thread abort WaitForSocketIOReady<ConnectionlessSocket::Ptr> readyChecker{fSockets_}; while (true) { for (ConnectionlessSocket::Ptr s : readyChecker.Wait ()) { try { byte buf[3 * 1024]; // not sure of max packet size SocketAddress from; size_t nBytesRead = s.ReceiveFrom (std::begin (buf), std::end (buf), 0, &from); Assert (nBytesRead <= NEltsOf (buf)); using namespace Streams; ParsePacketAndNotifyCallbacks_ (TextReader::New (ExternallyOwnedMemoryInputStream<byte>::New (std::begin (buf), std::begin (buf) + nBytesRead))); } catch (const Execution::Thread::AbortException&) { Execution::ReThrow (); } catch (...) { // ignore errors - and keep on trucking // but avoid wasting too much time if we get into an error storm #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"Caught/ignored exception for SSDP advertisement packet: %s", Characters::ToString (current_exception ()).c_str ()); #endif Execution::Sleep (1.0); } } } } void ParsePacketAndNotifyCallbacks_ (Streams::InputStream<Character>::Ptr in) { String firstLine = in.ReadLine ().Trim (); #if USE_NOISY_TRACE_IN_THIS_MODULE_ Debug::TraceContextBumper ctx ("Read SSDP Packet"); DbgTrace (L"firstLine: %s", firstLine.c_str ()); #endif const String kNOTIFY_LEAD = String_Constant (L"NOTIFY "); if (firstLine.length () > kNOTIFY_LEAD.length () and firstLine.SubString (0, kNOTIFY_LEAD.length ()) == kNOTIFY_LEAD) { SSDP::Advertisement d; while (true) { String line = in.ReadLine ().Trim (); if (line.empty ()) { break; } // Need to simplify this code (stroika string util) String label; String value; if (optional<size_t> n = line.Find (':')) { label = line.SubString (0, *n); value = line.SubString (*n + 1).Trim (); } if (not label.empty ()) { d.fRawHeaders.Add (label, value); } auto labelComparer = Common::ThreeWayComparer<String>{Characters::CompareOptions::eCaseInsensitive}; if (labelComparer (label, L"Location") == 0) { d.fLocation = IO::Network::URI{value}; } else if (labelComparer (label, L"NT") == 0) { d.fTarget = value; } else if (labelComparer (label, L"USN") == 0) { d.fUSN = value; } else if (labelComparer (label, L"Server") == 0) { d.fServer = value; } else if (labelComparer (label, L"NTS") == 0) { auto valueComparer = Common::ThreeWayComparer<String>{Characters::CompareOptions::eCaseInsensitive}; if (valueComparer (value, L"ssdp:alive") == 0) { d.fAlive = true; } else if (valueComparer (value, L"ssdp:byebye") == 0) { d.fAlive = false; } } } { [[maybe_unused]] auto&& critSec = lock_guard{fCritSection_}; for (auto i : fFoundCallbacks_) { i (d); } } } } private: recursive_mutex fCritSection_; vector<function<void (const SSDP::Advertisement& d)>> fFoundCallbacks_; Collection<ConnectionlessSocket::Ptr> fSockets_; Execution::Thread::CleanupPtr fThread_{Execution::Thread::CleanupPtr::eAbortBeforeWaiting}; }; /* ******************************************************************************** ************************************* Listener ********************************* ******************************************************************************** */ Listener::Listener (IO::Network::InternetProtocol::IP::IPVersionSupport ipVersion) : fRep_ (make_shared<Rep_> (ipVersion)) { } Listener::Listener (const function<void (const SSDP::Advertisement& d)>& callOnFinds, IO::Network::InternetProtocol::IP::IPVersionSupport ipVersion) : Listener (ipVersion) { AddOnFoundCallback (callOnFinds); } Listener::Listener (const function<void (const SSDP::Advertisement& d)>& callOnFinds, IO::Network::InternetProtocol::IP::IPVersionSupport ipVersion, AutoStart) : Listener (callOnFinds, ipVersion) { Start (); } Listener::Listener (const function<void (const SSDP::Advertisement& d)>& callOnFinds, AutoStart) : Listener (callOnFinds) { Start (); } Listener::~Listener () { IgnoreExceptionsForCall (fRep_->Stop ()); } void Listener::AddOnFoundCallback (const function<void (const SSDP::Advertisement& d)>& callOnFinds) { fRep_->AddOnFoundCallback (callOnFinds); } void Listener::Start () { fRep_->Start (); } void Listener::Stop () { fRep_->Stop (); }
use Common::ThreeWayComparer<String> in place of deprecated String::Compare
use Common::ThreeWayComparer<String> in place of deprecated String::Compare
C++
mit
SophistSolutions/Stroika,SophistSolutions/Stroika,SophistSolutions/Stroika,SophistSolutions/Stroika,SophistSolutions/Stroika
828ae96714d5b4aca1cdc8d3d4e9b483df07aae7
src/util/Sysout.cpp
src/util/Sysout.cpp
#include "Sysout.h" #include <iostream> #include <sstream> #include <string> #include <unistd.h> #include "../language/Dictionary.h" #include "../language/Grammar.h" #include "../util/Point3i.h" #include "../Fuzzy.h" // How wide the screen is unsigned short Sysout::displayWidth; void Sysout::setDisplayWidth(unsigned short width) { displayWidth = width; } // Adds newlines to a string to accommodate to screen width std::string Sysout::wordWrappify(std::string paragraph) { // The position used to determine where the string would normally be cut off unsigned int maxPos = displayWidth; // While we have not gone overboard while(maxPos < paragraph.length()) { // Find the last space before the maxPosition unsigned int spaceIndex = paragraph.rfind(' ', maxPos); // Replace the space with newline paragraph[spaceIndex] = '\n'; // Move the maxPosition to be one width after the space maxPos = spaceIndex + displayWidth; } // Return the new string return paragraph; } // Print out all the dictionary entries #ifdef DEBUG void Sysout::printDictionaryEntries() { println("=== Dictionary Entries ==="); std::string nounz = "["; nounz += toString(Dictionary::registeredNouns.size()); nounz += " nouns registered]"; println(wordWrappify(nounz)); std::string modifierz = "["; modifierz += toString(Dictionary::registeredModifiers.size()); modifierz += " modifiers registered]"; println(wordWrappify(modifierz)); println("=== End of Entries ==="); } #endif // Word type std::string Sysout::toFriendlyString(gmr::WordType wordType) { if(wordType == gmr::noun) { return "noun"; } if(wordType == gmr::adjunct) { return "adjunct"; } if(wordType == gmr::modifier) { return "modifier"; } if(wordType == gmr::article) { return "article"; } if(wordType == gmr::gibberish) { return "gibberish"; } return "hyper-gibberish"; } // Plurality std::string Sysout::toFriendlyString(gmr::Plurality plurality) { return plurality == gmr::singular ? "singular" : plurality == gmr::plural ? "plural" : plurality == gmr::ambiguous ? "ambiguous" : "lolwut???"; } // Article Type std::string Sysout::toFriendlyString(gmr::Definity definity) { return definity == gmr::definite ? "definite" : definity == gmr::indefinite ? "indefinite" : definity == gmr::undefinite ? "undefined" : "lolwut???"; } // Noun State std::string Sysout::toFriendlyString(gmr::NounState* nounState) { std::string returnVal = "["; returnVal += Dictionary::getNoun(nounState->id)->getSingularForm(); returnVal += "-"; returnVal += toFriendlyString(nounState->plurality); returnVal += "_"; returnVal += toFriendlyString(nounState->definity); returnVal += ":"; returnVal += toString(nounState->modifiers->size()); for(unsigned int modifierIndex = 0; modifierIndex < nounState->modifiers->size(); ++ modifierIndex) { returnVal += ":" + Dictionary::getModifier(nounState->modifiers->at(modifierIndex))->getForm(); } return returnVal + "]"; } // Word List std::string Sysout::toFriendlyString(std::vector<std::string>* wordList) { std::string returnVal = "["; if(wordList->size() == 0) { return returnVal + "]"; } std::vector<std::string>::iterator it = wordList->begin(); returnVal += *it; ++ it; while(it != wordList->end()) { returnVal += ", " + *it; ++ it; } return returnVal + "]"; } // Sentence State std::string Sysout::toFriendlyString(gmr::SentenceState* stncState) { std::string returnVal = "{"; for(unsigned int nounIndex = 0; nounIndex < stncState->nounStates->size(); ++ nounIndex) { returnVal += toFriendlyString(stncState->nounStates->at(nounIndex)); } return returnVal + "}"; } // Point3i std::string Sysout::toFriendlyString(Point3i p) { std::string returnVal = "{"; returnVal += toString(p.x) + ", "; returnVal += toString(p.y) + ", "; returnVal += toString(p.z) + "}"; return returnVal; } // Integer to String // Probably really inefficient std::string Sysout::toString(int i) { // Make a string stream std::stringstream ss; // Add number ss << i; // Return string return ss.str(); } // Prints stuff out slow // Make this better! void Sysout::printSlow(std::string str) { for(unsigned int index = 0; index < str.length(); ++ index) { // Print out one char std::cout << str.substr(index, 1); // Wait for some amount of time usleep(12500); //100000 = super slow // 50000 = slow // 25000 = medium // 12500 = fast } } // Integer void Sysout::print(int i) { std::cout << i; } void Sysout::println(int i) { std::cout << i << std::endl; } // Line // String void Sysout::print(std::string str) { std::cout << str; } void Sysout::println(std::string str) { std::cout << str << std::endl; } // Line // Line void Sysout::println() { std::cout << std::endl; }
#include "Sysout.h" #include <iostream> #include <sstream> #include <string> #include <unistd.h> #include "../language/Dictionary.h" #include "../language/Grammar.h" #include "../util/Point3i.h" #include "../Libirid.h" // How wide the screen is unsigned short Sysout::displayWidth; void Sysout::setDisplayWidth(unsigned short width) { displayWidth = width; } // Adds newlines to a string to accommodate to screen width std::string Sysout::wordWrappify(std::string paragraph) { // The position used to determine where the string would normally be cut off unsigned int maxPos = displayWidth; // While we have not gone overboard while(maxPos < paragraph.length()) { // Find the last space before the maxPosition unsigned int spaceIndex = paragraph.rfind(' ', maxPos); // Replace the space with newline paragraph[spaceIndex] = '\n'; // Move the maxPosition to be one width after the space maxPos = spaceIndex + displayWidth; } // Return the new string return paragraph; } // Print out all the dictionary entries #ifdef DEBUG void Sysout::printDictionaryEntries() { println("=== Dictionary Entries ==="); std::string nounz = "["; nounz += toString(Dictionary::registeredNouns.size()); nounz += " nouns registered]"; println(wordWrappify(nounz)); std::string modifierz = "["; modifierz += toString(Dictionary::registeredModifiers.size()); modifierz += " modifiers registered]"; println(wordWrappify(modifierz)); println("=== End of Entries ==="); } #endif // Word type std::string Sysout::toFriendlyString(gmr::WordType wordType) { if(wordType == gmr::noun) { return "noun"; } if(wordType == gmr::adjunct) { return "adjunct"; } if(wordType == gmr::modifier) { return "modifier"; } if(wordType == gmr::article) { return "article"; } if(wordType == gmr::gibberish) { return "gibberish"; } return "hyper-gibberish"; } // Plurality std::string Sysout::toFriendlyString(gmr::Plurality plurality) { return plurality == gmr::singular ? "singular" : plurality == gmr::plural ? "plural" : plurality == gmr::ambiguous ? "ambiguous" : "lolwut???"; } // Article Type std::string Sysout::toFriendlyString(gmr::Definity definity) { return definity == gmr::definite ? "definite" : definity == gmr::indefinite ? "indefinite" : definity == gmr::undefinite ? "undefined" : "lolwut???"; } // Noun State std::string Sysout::toFriendlyString(gmr::NounState* nounState) { std::string returnVal = "["; returnVal += Dictionary::getNoun(nounState->id)->getSingularForm(); returnVal += "-"; returnVal += toFriendlyString(nounState->plurality); returnVal += "_"; returnVal += toFriendlyString(nounState->definity); returnVal += ":"; returnVal += toString(nounState->modifiers->size()); for(unsigned int modifierIndex = 0; modifierIndex < nounState->modifiers->size(); ++ modifierIndex) { returnVal += ":" + Dictionary::getModifier(nounState->modifiers->at(modifierIndex))->getForm(); } return returnVal + "]"; } // Word List std::string Sysout::toFriendlyString(std::vector<std::string>* wordList) { std::string returnVal = "["; if(wordList->size() == 0) { return returnVal + "]"; } std::vector<std::string>::iterator it = wordList->begin(); returnVal += *it; ++ it; while(it != wordList->end()) { returnVal += ", " + *it; ++ it; } return returnVal + "]"; } // Sentence State std::string Sysout::toFriendlyString(gmr::SentenceState* stncState) { std::string returnVal = "{"; for(unsigned int nounIndex = 0; nounIndex < stncState->nounStates->size(); ++ nounIndex) { returnVal += toFriendlyString(stncState->nounStates->at(nounIndex)); } return returnVal + "}"; } // Point3i std::string Sysout::toFriendlyString(Point3i p) { std::string returnVal = "{"; returnVal += toString(p.x) + ", "; returnVal += toString(p.y) + ", "; returnVal += toString(p.z) + "}"; return returnVal; } // Integer to String // Probably really inefficient std::string Sysout::toString(int i) { // Make a string stream std::stringstream ss; // Add number ss << i; // Return string return ss.str(); } // Prints stuff out slow // Make this better! void Sysout::printSlow(std::string str) { for(unsigned int index = 0; index < str.length(); ++ index) { // Print out one char std::cout << str.substr(index, 1); // Wait for some amount of time usleep(12500); //100000 = super slow // 50000 = slow // 25000 = medium // 12500 = fast } } // Integer void Sysout::print(int i) { std::cout << i; } void Sysout::println(int i) { std::cout << i << std::endl; } // Line // String void Sysout::print(std::string str) { std::cout << str; } void Sysout::println(std::string str) { std::cout << str << std::endl; } // Line // Line void Sysout::println() { std::cout << std::endl; }
Update Sysout.cpp
Update Sysout.cpp
C++
mit
Naftoreiclag/Libirid
437124e2f1c67b6103a20071d9a0bcb7d107f003
o3d/statsreport/metrics_unittest.cc
o3d/statsreport/metrics_unittest.cc
/* * Copyright 2009, 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. */ // Metrics report unit testing #include <new> #include <algorithm> #include "gtest/gtest.h" #include "metrics.h" DECLARE_METRIC_count(count); DEFINE_METRIC_count(count); DECLARE_METRIC_timing(timing); DEFINE_METRIC_timing(timing); DECLARE_METRIC_integer(integer); DEFINE_METRIC_integer(integer); DECLARE_METRIC_bool(bool); DEFINE_METRIC_bool(bool); using ::stats_report::BoolMetric; using ::stats_report::CountMetric; using ::stats_report::IntegerMetric; using ::stats_report::MetricBase; using ::stats_report::MetricCollection; using ::stats_report::MetricCollectionBase; using ::stats_report::MetricIterator; using ::stats_report::TimingMetric; using ::stats_report::TimingSample; using ::stats_report::kBoolType; using ::stats_report::kCountType; using ::stats_report::kIntegerType; using ::stats_report::kTimingType; namespace { class MetricsTest: public testing::Test { protected: MetricCollection coll_; }; class MetricsEnumTest: public MetricsTest { public: virtual void SetUp() { coll_.Initialize(); } virtual void TearDown() { coll_.Uninitialize(); } protected: MetricsEnumTest(): count_("count", &coll_), timing_("timing", &coll_), integer_("integer", &coll_), bool_("bool", &coll_) { } CountMetric count_; TimingMetric timing_; IntegerMetric integer_; BoolMetric bool_; }; } // namespace // Validates that the above-declared metrics are available // in the expected namespace TEST_F(MetricsTest, Globals) { EXPECT_EQ(0, ::metric_count.Reset()); TimingMetric::TimingData data = ::metric_timing.Reset(); EXPECT_EQ(0, data.count); EXPECT_EQ(0, data.maximum); EXPECT_EQ(0, data.minimum); EXPECT_EQ(0, data.sum); EXPECT_EQ(0, ::metric_integer.value()); EXPECT_EQ(BoolMetric::kBoolUnset, ::metric_bool.Reset()); // Check for correct initialization EXPECT_STREQ("count", metric_count.name()); EXPECT_STREQ("timing", metric_timing.name()); EXPECT_STREQ("integer", metric_integer.name()); EXPECT_STREQ("bool", metric_bool.name()); } // make GUnit happy inline std::ostream &operator << (std::ostream &str, const MetricIterator &it) { str << std::hex << reinterpret_cast<void*>(*it); return str; } TEST_F(MetricsTest, CollectionInitialization) { // The global MetricCollection is aliased to zero memory so as to ensure // no initialization order snafus. If an initialized MetricCollection // sets any of its storage to non-zero, there's a good chance that e.g. a // vtbl has snuck in there, which must not happen char buf1[sizeof(MetricCollection)] = { 0 }; char buf2[sizeof(MetricCollection)] = { 0 }; // Placement new a MetricCollection to one of the buffers new (buf1) MetricCollection(); // and check they're still equivalent EXPECT_EQ(0, memcmp(buf1, buf2, sizeof(MetricCollection))); // MetricCollection must not extend MetricCollectionBase in size EXPECT_EQ(sizeof(MetricCollection), sizeof(MetricCollectionBase)); } TEST_F(MetricsTest, Count) { CountMetric foo("foo", &coll_); EXPECT_EQ(0, foo.Reset()); EXPECT_EQ(kCountType, foo.type()); ASSERT_TRUE(NULL != foo.AsCount()); ASSERT_TRUE(NULL == foo.AsTiming()); ASSERT_TRUE(NULL == foo.AsInteger()); ASSERT_TRUE(NULL == foo.AsBool()); ++foo; EXPECT_EQ(1, foo.value()); foo++; EXPECT_EQ(2, foo.value()); foo += 100; EXPECT_EQ(102, foo.value()); } TEST_F(MetricsTest, Timing) { TimingMetric foo("foo", &coll_); EXPECT_EQ(kTimingType, foo.type()); ASSERT_TRUE(NULL == foo.AsCount()); ASSERT_TRUE(NULL != foo.AsTiming()); ASSERT_TRUE(NULL == foo.AsInteger()); ASSERT_TRUE(NULL == foo.AsBool()); foo.AddSample(100); foo.AddSample(50); EXPECT_EQ(2, foo.count()); EXPECT_EQ(150, foo.sum()); EXPECT_EQ(100, foo.maximum()); EXPECT_EQ(50, foo.minimum()); EXPECT_EQ(75, foo.average()); TimingMetric::TimingData data = foo.Reset(); EXPECT_EQ(2, data.count); EXPECT_EQ(150, data.sum); EXPECT_EQ(100, data.maximum); EXPECT_EQ(50, data.minimum); EXPECT_EQ(0, foo.count()); EXPECT_EQ(0, foo.sum()); EXPECT_EQ(0, foo.maximum()); EXPECT_EQ(0, foo.minimum()); EXPECT_EQ(0, foo.average()); // Test counted samples foo.AddSamples(10, 1000); foo.AddSamples(10, 500); EXPECT_EQ(20, foo.count()); EXPECT_EQ(1500, foo.sum()); EXPECT_EQ(100, foo.maximum()); EXPECT_EQ(50, foo.minimum()); EXPECT_EQ(75, foo.average()); } TEST_F(MetricsTest, TimingSample) { TimingMetric foo("foo", &coll_); // add a sample to foo { TimingSample sample(&foo); ::Sleep(30); } TimingMetric::TimingData data = foo.Reset(); // Should be precisely one sample in there EXPECT_EQ(1, data.count); // Disable flaky tests on build server, unfortunately this reduces coverage // too, but it seems preferrable to breaking the build on a regular basis. #ifndef BUILD_SERVER_BUILD // Let's hope the scheduler doesn't leave us hanging more than 10 ms. EXPECT_GT(40, data.sum); // The sleep above seems to often terminate early on the build server, // I've observed captured times down to 18 ms, which is strange. // TODO: figure out whether the timer is broken or whether // sleep is breaking its promise, or whether e.g. we're getting different // walltimes on different CPUs due to BIOS bugs on the build server EXPECT_LT(15, data.sum); #endif // again, this time with a non-unity count { TimingSample sample(&foo, 2); EXPECT_EQ(2, sample.count()); ::Sleep(30); } data = foo.Reset(); // Should be precisely two samples in there EXPECT_EQ(2, data.count); // Disable flaky tests on build server, unfortunately this reduces coverage // too, but it seems preferrable to breaking the build on a regular basis. #ifndef BUILD_SERVER_BUILD // Let's hope the scheduler doesn't leave us hanging more than 10 ms. EXPECT_GT(40, data.sum); EXPECT_LT(15, data.sum); #endif // now with zero count { TimingSample sample(&foo, 0); } data = foo.Reset(); // Should be no samples in there EXPECT_EQ(0, data.count); } TEST_F(MetricsTest, Integer) { IntegerMetric foo("foo", &coll_); EXPECT_EQ(kIntegerType, foo.type()); ASSERT_TRUE(NULL == foo.AsCount()); ASSERT_TRUE(NULL == foo.AsTiming()); ASSERT_TRUE(NULL != foo.AsInteger()); ASSERT_TRUE(NULL == foo.AsBool()); EXPECT_EQ(0, foo.value()); foo.Set(1005); EXPECT_EQ(1005, foo.value()); foo = 1009UL; EXPECT_EQ(1009, foo.value()); foo.Set(0); ++foo; EXPECT_EQ(1, foo.value()); foo++; EXPECT_EQ(2, foo.value()); foo += 100; EXPECT_EQ(102, foo.value()); foo -= 100; EXPECT_EQ(2, foo.value()); foo--; EXPECT_EQ(1, foo.value()); --foo; EXPECT_EQ(0, foo.value()); } TEST_F(MetricsTest, Bool) { BoolMetric foo("foo", &coll_); EXPECT_EQ(kBoolType, foo.type()); ASSERT_TRUE(NULL == foo.AsCount()); ASSERT_TRUE(NULL == foo.AsTiming()); ASSERT_TRUE(NULL == foo.AsInteger()); ASSERT_TRUE(NULL != foo.AsBool()); EXPECT_EQ(BoolMetric::kBoolUnset, foo.Reset()); foo.Set(true); EXPECT_EQ(BoolMetric::kBoolTrue, foo.Reset()); foo.Set(false); EXPECT_EQ(BoolMetric::kBoolFalse, foo.Reset()); EXPECT_EQ(BoolMetric::kBoolUnset, foo.Reset()); } TEST_F(MetricsEnumTest, Enumeration) { MetricBase *metrics[] = { &count_, &timing_, &integer_, &bool_, }; for (int i = 0; i < sizeof(metrics) / sizeof(metrics[0]); ++i) { MetricBase *stat = metrics[i]; MetricBase *curr = coll_.first(); for (; NULL != curr; curr = curr->next()) { if (stat == curr) break; } // if NULL, we didn't find our counter EXPECT_TRUE(NULL != curr); } } TEST_F(MetricsEnumTest, Iterator) { typedef MetricBase *MetricBasePtr; MetricBasePtr metrics[] = { &count_, &timing_, &integer_, &bool_, }; int num_stats = arraysize(metrics); MetricIterator it(coll_), end; EXPECT_NE(it, end); // copy construction EXPECT_EQ(it, MetricIterator(it)); EXPECT_EQ(end, MetricIterator(end)); // # of iterations int i = 0; while (it++ != end) ++i; ASSERT_EQ(num_stats, i); ASSERT_EQ(end, it); // increment past end is idempotent ++it; ASSERT_EQ(end, it); // Check that we return no garbage or nonsense for (it = MetricIterator(coll_); it != end; ++it) { MetricBasePtr *stats_end = &metrics[num_stats]; EXPECT_NE(stats_end, std::find(metrics, stats_end, *it)); } // and that all metrics can be found for (int i = 0; i < sizeof(metrics) / sizeof(metrics[0]); ++i) { MetricBase *stat = metrics[i]; EXPECT_EQ(stat, *std::find(MetricIterator(coll_), end, stat)); } } TEST_F(MetricsTest, SimpleConstruction) { const CountMetric c("c", 100); EXPECT_EQ(100, c.value()); EXPECT_EQ(kCountType, c.type()); EXPECT_STREQ("c", c.name()); EXPECT_TRUE(NULL == c.next()); TimingMetric::TimingData data = { 10, 0, 1000, 10, 500 }; const TimingMetric t("t", data); EXPECT_EQ(10, t.count()); EXPECT_EQ(1000, t.sum()); EXPECT_EQ(10, t.minimum()); EXPECT_EQ(500, t.maximum()); EXPECT_EQ(kTimingType, t.type()); EXPECT_STREQ("t", t.name()); EXPECT_TRUE(NULL == t.next()); const IntegerMetric i("i", 200); EXPECT_EQ(200, i.value()); EXPECT_EQ(kIntegerType, i.type()); EXPECT_STREQ("i", i.name()); EXPECT_TRUE(NULL == i.next()); const BoolMetric bool_true("bool_true", BoolMetric::kBoolTrue); EXPECT_EQ(BoolMetric::kBoolTrue, bool_true.value()); EXPECT_EQ(kBoolType, bool_true.type()); EXPECT_STREQ("bool_true", bool_true.name()); EXPECT_TRUE(NULL == bool_true.next()); const BoolMetric bool_false("bool_false", BoolMetric::kBoolFalse); EXPECT_EQ(BoolMetric::kBoolFalse, bool_false.value()); EXPECT_EQ(kBoolType, bool_false.type()); EXPECT_STREQ("bool_false", bool_false.name()); EXPECT_TRUE(NULL == bool_false.next()); }
/* * Copyright 2009, 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. */ // Metrics report unit testing #include <new> #include <algorithm> #include "gtest/gtest.h" #include "metrics.h" DECLARE_METRIC_count(count); DEFINE_METRIC_count(count); DECLARE_METRIC_timing(timing); DEFINE_METRIC_timing(timing); DECLARE_METRIC_integer(integer); DEFINE_METRIC_integer(integer); DECLARE_METRIC_bool(bool); DEFINE_METRIC_bool(bool); using ::stats_report::BoolMetric; using ::stats_report::CountMetric; using ::stats_report::IntegerMetric; using ::stats_report::MetricBase; using ::stats_report::MetricCollection; using ::stats_report::MetricCollectionBase; using ::stats_report::MetricIterator; using ::stats_report::TimingMetric; using ::stats_report::TimingSample; using ::stats_report::kBoolType; using ::stats_report::kCountType; using ::stats_report::kIntegerType; using ::stats_report::kTimingType; namespace { class MetricsTest: public testing::Test { protected: MetricCollection coll_; }; class MetricsEnumTest: public MetricsTest { public: virtual void SetUp() { coll_.Initialize(); } virtual void TearDown() { coll_.Uninitialize(); } protected: MetricsEnumTest(): count_("count", &coll_), timing_("timing", &coll_), integer_("integer", &coll_), bool_("bool", &coll_) { } CountMetric count_; TimingMetric timing_; IntegerMetric integer_; BoolMetric bool_; }; } // namespace // Validates that the above-declared metrics are available // in the expected namespace TEST_F(MetricsTest, Globals) { EXPECT_EQ(0, ::metric_count.Reset()); TimingMetric::TimingData data = ::metric_timing.Reset(); EXPECT_EQ(0, data.count); EXPECT_EQ(0, data.maximum); EXPECT_EQ(0, data.minimum); EXPECT_EQ(0, data.sum); EXPECT_EQ(0, ::metric_integer.value()); EXPECT_EQ(BoolMetric::kBoolUnset, ::metric_bool.Reset()); // Check for correct initialization EXPECT_STREQ("count", metric_count.name()); EXPECT_STREQ("timing", metric_timing.name()); EXPECT_STREQ("integer", metric_integer.name()); EXPECT_STREQ("bool", metric_bool.name()); } // make GUnit happy inline std::ostream &operator << (std::ostream &str, const MetricIterator &it) { str << std::hex << reinterpret_cast<void*>(*it); return str; } TEST_F(MetricsTest, CollectionInitialization) { // The global MetricCollection is aliased to zero memory so as to ensure // no initialization order snafus. If an initialized MetricCollection // sets any of its storage to non-zero, there's a good chance that e.g. a // vtbl has snuck in there, which must not happen char buf1[sizeof(MetricCollection)] = { 0 }; char buf2[sizeof(MetricCollection)] = { 0 }; // Placement new a MetricCollection to one of the buffers new (buf1) MetricCollection(); // and check they're still equivalent EXPECT_EQ(0, memcmp(buf1, buf2, sizeof(MetricCollection))); // MetricCollection must not extend MetricCollectionBase in size EXPECT_EQ(sizeof(MetricCollection), sizeof(MetricCollectionBase)); } TEST_F(MetricsTest, Count) { CountMetric foo("foo", &coll_); EXPECT_EQ(0, foo.Reset()); EXPECT_EQ(kCountType, foo.type()); ASSERT_TRUE(NULL != foo.AsCount()); ASSERT_TRUE(NULL == foo.AsTiming()); ASSERT_TRUE(NULL == foo.AsInteger()); ASSERT_TRUE(NULL == foo.AsBool()); ++foo; EXPECT_EQ(1, foo.value()); foo++; EXPECT_EQ(2, foo.value()); foo += 100; EXPECT_EQ(102, foo.value()); } TEST_F(MetricsTest, Timing) { TimingMetric foo("foo", &coll_); EXPECT_EQ(kTimingType, foo.type()); ASSERT_TRUE(NULL == foo.AsCount()); ASSERT_TRUE(NULL != foo.AsTiming()); ASSERT_TRUE(NULL == foo.AsInteger()); ASSERT_TRUE(NULL == foo.AsBool()); foo.AddSample(100); foo.AddSample(50); EXPECT_EQ(2, foo.count()); EXPECT_EQ(150, foo.sum()); EXPECT_EQ(100, foo.maximum()); EXPECT_EQ(50, foo.minimum()); EXPECT_EQ(75, foo.average()); TimingMetric::TimingData data = foo.Reset(); EXPECT_EQ(2, data.count); EXPECT_EQ(150, data.sum); EXPECT_EQ(100, data.maximum); EXPECT_EQ(50, data.minimum); EXPECT_EQ(0, foo.count()); EXPECT_EQ(0, foo.sum()); EXPECT_EQ(0, foo.maximum()); EXPECT_EQ(0, foo.minimum()); EXPECT_EQ(0, foo.average()); // Test counted samples foo.AddSamples(10, 1000); foo.AddSamples(10, 500); EXPECT_EQ(20, foo.count()); EXPECT_EQ(1500, foo.sum()); EXPECT_EQ(100, foo.maximum()); EXPECT_EQ(50, foo.minimum()); EXPECT_EQ(75, foo.average()); } TEST_F(MetricsTest, TimingSample) { TimingMetric foo("foo", &coll_); // add a sample to foo { TimingSample sample(&foo); ::Sleep(30); } TimingMetric::TimingData data = foo.Reset(); // Should be precisely one sample in there EXPECT_EQ(1, data.count); // again, this time with a non-unity count { TimingSample sample(&foo, 2); EXPECT_EQ(2, sample.count()); ::Sleep(30); } data = foo.Reset(); // Should be precisely two samples in there EXPECT_EQ(2, data.count); // now with zero count { TimingSample sample(&foo, 0); } data = foo.Reset(); // Should be no samples in there EXPECT_EQ(0, data.count); } TEST_F(MetricsTest, Integer) { IntegerMetric foo("foo", &coll_); EXPECT_EQ(kIntegerType, foo.type()); ASSERT_TRUE(NULL == foo.AsCount()); ASSERT_TRUE(NULL == foo.AsTiming()); ASSERT_TRUE(NULL != foo.AsInteger()); ASSERT_TRUE(NULL == foo.AsBool()); EXPECT_EQ(0, foo.value()); foo.Set(1005); EXPECT_EQ(1005, foo.value()); foo = 1009UL; EXPECT_EQ(1009, foo.value()); foo.Set(0); ++foo; EXPECT_EQ(1, foo.value()); foo++; EXPECT_EQ(2, foo.value()); foo += 100; EXPECT_EQ(102, foo.value()); foo -= 100; EXPECT_EQ(2, foo.value()); foo--; EXPECT_EQ(1, foo.value()); --foo; EXPECT_EQ(0, foo.value()); } TEST_F(MetricsTest, Bool) { BoolMetric foo("foo", &coll_); EXPECT_EQ(kBoolType, foo.type()); ASSERT_TRUE(NULL == foo.AsCount()); ASSERT_TRUE(NULL == foo.AsTiming()); ASSERT_TRUE(NULL == foo.AsInteger()); ASSERT_TRUE(NULL != foo.AsBool()); EXPECT_EQ(BoolMetric::kBoolUnset, foo.Reset()); foo.Set(true); EXPECT_EQ(BoolMetric::kBoolTrue, foo.Reset()); foo.Set(false); EXPECT_EQ(BoolMetric::kBoolFalse, foo.Reset()); EXPECT_EQ(BoolMetric::kBoolUnset, foo.Reset()); } TEST_F(MetricsEnumTest, Enumeration) { MetricBase *metrics[] = { &count_, &timing_, &integer_, &bool_, }; for (int i = 0; i < sizeof(metrics) / sizeof(metrics[0]); ++i) { MetricBase *stat = metrics[i]; MetricBase *curr = coll_.first(); for (; NULL != curr; curr = curr->next()) { if (stat == curr) break; } // if NULL, we didn't find our counter EXPECT_TRUE(NULL != curr); } } TEST_F(MetricsEnumTest, Iterator) { typedef MetricBase *MetricBasePtr; MetricBasePtr metrics[] = { &count_, &timing_, &integer_, &bool_, }; int num_stats = arraysize(metrics); MetricIterator it(coll_), end; EXPECT_NE(it, end); // copy construction EXPECT_EQ(it, MetricIterator(it)); EXPECT_EQ(end, MetricIterator(end)); // # of iterations int i = 0; while (it++ != end) ++i; ASSERT_EQ(num_stats, i); ASSERT_EQ(end, it); // increment past end is idempotent ++it; ASSERT_EQ(end, it); // Check that we return no garbage or nonsense for (it = MetricIterator(coll_); it != end; ++it) { MetricBasePtr *stats_end = &metrics[num_stats]; EXPECT_NE(stats_end, std::find(metrics, stats_end, *it)); } // and that all metrics can be found for (int i = 0; i < sizeof(metrics) / sizeof(metrics[0]); ++i) { MetricBase *stat = metrics[i]; EXPECT_EQ(stat, *std::find(MetricIterator(coll_), end, stat)); } } TEST_F(MetricsTest, SimpleConstruction) { const CountMetric c("c", 100); EXPECT_EQ(100, c.value()); EXPECT_EQ(kCountType, c.type()); EXPECT_STREQ("c", c.name()); EXPECT_TRUE(NULL == c.next()); TimingMetric::TimingData data = { 10, 0, 1000, 10, 500 }; const TimingMetric t("t", data); EXPECT_EQ(10, t.count()); EXPECT_EQ(1000, t.sum()); EXPECT_EQ(10, t.minimum()); EXPECT_EQ(500, t.maximum()); EXPECT_EQ(kTimingType, t.type()); EXPECT_STREQ("t", t.name()); EXPECT_TRUE(NULL == t.next()); const IntegerMetric i("i", 200); EXPECT_EQ(200, i.value()); EXPECT_EQ(kIntegerType, i.type()); EXPECT_STREQ("i", i.name()); EXPECT_TRUE(NULL == i.next()); const BoolMetric bool_true("bool_true", BoolMetric::kBoolTrue); EXPECT_EQ(BoolMetric::kBoolTrue, bool_true.value()); EXPECT_EQ(kBoolType, bool_true.type()); EXPECT_STREQ("bool_true", bool_true.name()); EXPECT_TRUE(NULL == bool_true.next()); const BoolMetric bool_false("bool_false", BoolMetric::kBoolFalse); EXPECT_EQ(BoolMetric::kBoolFalse, bool_false.value()); EXPECT_EQ(kBoolType, bool_false.type()); EXPECT_STREQ("bool_false", bool_false.name()); EXPECT_TRUE(NULL == bool_false.next()); }
Delete bad sleep based tests
Delete bad sleep based tests If you need the tests, refractor them to follow the guidelines instead of having them fail intermittently http://big.corp.google.com/~joejoejoe/testing/2008/05/episode-90-sleeping-synchronization_27.html Review URL: http://codereview.chromium.org/159117 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@21209 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
ropik/chromium,adobe/chromium,yitian134/chromium,adobe/chromium,gavinp/chromium,ropik/chromium,adobe/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,adobe/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,gavinp/chromium,gavinp/chromium,yitian134/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,ropik/chromium,adobe/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,gavinp/chromium,ropik/chromium,gavinp/chromium,adobe/chromium,ropik/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,yitian134/chromium,gavinp/chromium,yitian134/chromium,gavinp/chromium,gavinp/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,yitian134/chromium,yitian134/chromium,ropik/chromium,Crystalnix/house-of-life-chromium
4bade526a9c7f25bf0a42cc86520fc9b6d0048c9
NaoTHSoccer/Source/Cognition/Modules/Behavior/PathPlanner/PathPlanner.cpp
NaoTHSoccer/Source/Cognition/Modules/Behavior/PathPlanner/PathPlanner.cpp
/** * @file PathPlanner.cpp * * @author <a href="mailto:[email protected]">Yigit Can Akcay</a> * Implementation of class PathPlanner */ #include "PathPlanner.h" PathPlanner::PathPlanner() : step_buffer({}), foot_to_use(Foot::RIGHT), last_stepRequestID(getMotionStatus().stepControl.stepRequestID + 1), // WalkRequest stepRequestID starts at 0, we have to start at 1 kick_planned(false) { DEBUG_REQUEST_REGISTER("PathPlanner:walk_to_ball", "Walks to the ball from far.", false); getDebugParameterList().add(&params); } PathPlanner::~PathPlanner() { getDebugParameterList().remove(&params); } void PathPlanner::execute() { // --- DEBUG REQUESTS --- DEBUG_REQUEST("PathPlanner:walk_to_ball", if (getBallModel().positionPreview.x > 250) { walk_to_ball(Foot::NONE); } ); // --- DEBUG REQUESTS --- getPathModel().kick_executed = false; STOPWATCH_START("PathPlanner"); // Always executed first manage_step_buffer(); // The kick has been executed // Tells XABSL to jump into next state if (kick_planned && step_buffer.empty()) { getPathModel().kick_executed = true; } // HACK: xabsl set a firced motion request => clear everything if(getPathModel().path_routine == PathModel::PathRoutine::NONE && getMotionRequest().forced) { step_buffer.clear(); return; } switch (getPathModel().path_routine) { case PathModel::PathRoutine::NONE: // There is no kick planned, since the kick has been executed // and XABSL is in a different state now if (kick_planned) { kick_planned = false; } if (step_buffer.empty()) { return; } break; case PathModel::PathRoutine::GO_TO_BALL_FAST: walk_to_ball(Foot::NONE , true); break; case PathModel::PathRoutine::GO_TO_BALL_SLOW: walk_to_ball(Foot::NONE); break; case PathModel::PathRoutine::MOVE_AROUND_BALL: move_around_ball(getPathModel().direction, getPathModel().radius); break; case PathModel::PathRoutine::APPROACH_BALL_LEFT: approach_ball(Foot::LEFT); break; case PathModel::PathRoutine::APPROACH_BALL_RIGHT: approach_ball(Foot::RIGHT); break; case PathModel::PathRoutine::SHORT_KICK_LEFT: short_kick(Foot::LEFT); break; case PathModel::PathRoutine::SHORT_KICK_RIGHT: short_kick(Foot::RIGHT); break; case PathModel::PathRoutine::LONG_KICK_LEFT: long_kick(Foot::LEFT); break; case PathModel::PathRoutine::LONG_KICK_RIGHT: long_kick(Foot::RIGHT); break; case PathModel::PathRoutine::SIDEKICK_LEFT: sidekick(Foot::LEFT); break; case PathModel::PathRoutine::SIDEKICK_RIGHT: sidekick(Foot::RIGHT); break; } // Always executed last execute_step_buffer(); STOPWATCH_STOP("PathPlanner"); } void PathPlanner::walk_to_ball(const Foot foot, const bool go_fast) { Vector2d ballPos = Vector2d(); double ballRadius = getFieldInfo().ballRadius; WalkRequest::Coordinate coordinate = WalkRequest::Hip; switch (foot) { case Foot::LEFT: ballPos = getBallModel().positionPreviewInLFoot; coordinate = WalkRequest::LFoot; break; case Foot::RIGHT: ballPos = getBallModel().positionPreviewInRFoot; coordinate = WalkRequest::RFoot; break; case Foot::NONE: ballPos = getBallModel().positionPreview; coordinate = WalkRequest::Hip; break; } double ballRotation = ballPos.angle(); Pose2D pose = { ballRotation, 0.7*(ballPos.x - getPathModel().distance - ballRadius), ballPos.y }; if (step_buffer.empty()) { StepType type = StepType::WALKSTEP; double scale = 1.0; double speed_direction = 0.0; if (go_fast) { double character = 1.0; add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::HARD, false); } else { double character = 0.3; add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::HARD, false); } } else { update_step(pose); } } void PathPlanner::move_around_ball(const double direction, const double radius) { Vector2d ballPos = getBallModel().positionPreview; double ballRotation = ballPos.angle(); double ballDistance = ballPos.abs(); WalkRequest::Coordinate coordinate = WalkRequest::Hip; double min1; double min2; double max1; double max2; if (direction <= 0) { min1 = 0.0; min2 = 0.0; max1 = 45.0; max2 = 100.0; } else { min1 = -45; min2 = -100; max1 = 0; max2 = 0; } double stepX = (ballDistance - radius) * std::cos(ballRotation); double stepY = Math::clamp(radius * std::tan(Math::clamp(Math::toDegrees(-direction), min1, max1)), min2, max2) * std::cos(ballRotation); Pose2D pose = { ballRotation, stepX, stepY }; if (step_buffer.empty()) { StepType type = StepType::WALKSTEP; double character = 0.7; Foot foot = Foot::NONE; double scale = 1.0; double speed_direction = 0.0; add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::HARD, false); } else { update_step(pose); } } void PathPlanner::approach_ball(const Foot foot) { Vector2d ballPos = Vector2d(); WalkRequest::Coordinate coordinate = WalkRequest::Hip; double stepX = 0.0; double stepY = 0.0; double ballRadius = getFieldInfo().ballRadius; double stepRotation = ballPos.abs() > 250 ? ballPos.angle() : 0; switch (foot) { case Foot::LEFT: ballPos = getBallModel().positionPreviewInLFoot; coordinate = WalkRequest::LFoot; stepX = ballPos.x - std::abs(ballPos.y - getPathModel().yOffset) - getPathModel().distance - ballRadius; stepY = ballPos.y - getPathModel().yOffset; break; case Foot::RIGHT: ballPos = getBallModel().positionPreviewInRFoot; coordinate = WalkRequest::RFoot; stepX = ballPos.x - std::abs(ballPos.y + getPathModel().yOffset) - getPathModel().distance - ballRadius; stepY = ballPos.y + getPathModel().yOffset; break; case Foot::NONE: ASSERT(false); } //if (ballPos.x < getPathModel().distance + 30 && ballPos.x > getPathModel().distance - 30) if (stepX < 0 && ballPos.x > getPathModel().distance + 30) { stepX = 0; } const double slow_down_factor = 0.7; Pose2D pose; if ( params.approach_ball_adapt_control && Vector2d(stepX, stepY).abs() < params.approach_ball_adapt_threshold) { pose = { stepRotation, stepX, stepY }; } else { pose = { stepRotation, slow_down_factor * stepX, slow_down_factor * stepY }; } if (step_buffer.empty()) { StepType type = StepType::WALKSTEP; double character = 0.7; double scale = 1.0; double speed_direction = 0.0; add_step(pose, type, coordinate, character, Foot::NONE, scale, speed_direction, WalkRequest::StepControlRequest::HARD, false); } else { update_step(pose); } } void PathPlanner::short_kick(const Foot foot) { if (!kick_planned) { WalkRequest::Coordinate coordinate = WalkRequest::Hip; switch (foot) { case Foot::LEFT: coordinate = WalkRequest::RFoot; break; case Foot::RIGHT: coordinate = WalkRequest::LFoot; break; case Foot::NONE: ASSERT(false); } if (step_buffer.empty()) { Pose2D pose = { 0.0, 500 , 0.0 }; StepType type = StepType::KICKSTEP; double character = 1.0; double scale = 0.7; double speed_direction = 0.0; add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::SOFT, true); type = StepType::ZEROSTEP; add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::SOFT, true); pose = { 0.0, 0.0, 0.0 }; type = StepType::WALKSTEP; add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::HARD, true); kick_planned = true; } } } void PathPlanner::long_kick(const Foot foot) { if (!kick_planned) { WalkRequest::Coordinate coordinate = WalkRequest::Hip; switch (foot) { case Foot::LEFT: coordinate = WalkRequest::RFoot; break; case Foot::RIGHT: coordinate = WalkRequest::LFoot; break; case Foot::NONE: ASSERT(false); } if (step_buffer.empty()) { Pose2D pose = { 0.0, 500, 0.0 }; StepType type = StepType::KICKSTEP; double character = 1.0; double scale = 0.7; double speed_direction = 0.0; add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::SOFT, true); type = StepType::ZEROSTEP; add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::SOFT, true); pose = { 0.0, 0.0, 0.0 }; type = StepType::WALKSTEP; add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::HARD, true); kick_planned = true; } } } void PathPlanner::sidekick(const Foot foot) { if (!kick_planned) { double speed_direction = 0.0; double stepY = 0.0; WalkRequest::Coordinate coordinate = WalkRequest::Hip; switch (foot) { case Foot::LEFT: coordinate = WalkRequest::LFoot; speed_direction = 90; stepY = 100; break; case Foot::RIGHT: coordinate = WalkRequest::RFoot; speed_direction = -90; stepY = -100; break; case Foot::NONE: ASSERT(false); } if (step_buffer.empty()) { Pose2D pose = { 0.0, 500, stepY }; StepType type = StepType::KICKSTEP; double character = 1.0; Foot step_foot = foot == Foot::RIGHT ? Foot::LEFT : Foot::RIGHT; double scale = params.sidekick_scale; add_step(pose, type, coordinate, character, step_foot, scale, speed_direction, WalkRequest::StepControlRequest::SOFT, true); type = StepType::ZEROSTEP; add_step(pose, type, coordinate, character, step_foot, scale, speed_direction, WalkRequest::StepControlRequest::SOFT, true); pose = { 0.0, 0.0, 0.0 }; type = StepType::WALKSTEP; add_step(pose, type, coordinate, character, step_foot, scale, speed_direction, WalkRequest::StepControlRequest::HARD, true); kick_planned = true; } } } // Stepcontrol void PathPlanner::add_step(Pose2D &pose, const StepType &type, const WalkRequest::Coordinate &coordinate, const double character, const Foot foot, const double scale, const double speedDirection, const WalkRequest::StepControlRequest::RestrictionMode restriction, bool isProtected) { step_buffer.push_back(Step_Buffer_Element({ pose, speedDirection, type, type == StepType::KICKSTEP ? params.kick_time : 250, character, scale, foot, coordinate, restriction, isProtected})); } void PathPlanner::update_step(Pose2D &pose) { ASSERT(step_buffer.size() > 0); step_buffer.front().pose = pose; } void PathPlanner::manage_step_buffer() { if (step_buffer.empty()) { return; } // requested step has been accepted if (last_stepRequestID == getMotionStatus().stepControl.stepRequestID) { step_buffer.erase(step_buffer.begin()); last_stepRequestID = getMotionStatus().stepControl.stepRequestID + 1; } } void PathPlanner::execute_step_buffer() { STOPWATCH_START("PathPlanner:execute_steplist"); if (step_buffer.empty()) { return; } getMotionRequest().id = motion::walk; getMotionRequest().walkRequest.coordinate = step_buffer.front().coordinate; getMotionRequest().walkRequest.character = step_buffer.front().character; getMotionRequest().walkRequest.stepControl.scale = step_buffer.front().scale; getMotionRequest().walkRequest.stepControl.stepID = getMotionStatus().stepControl.stepID; getMotionRequest().walkRequest.stepControl.type = step_buffer.front().type; getMotionRequest().walkRequest.stepControl.time = step_buffer.front().time; getMotionRequest().walkRequest.stepControl.speedDirection = step_buffer.front().speedDirection; getMotionRequest().walkRequest.stepControl.target = step_buffer.front().pose; getMotionRequest().walkRequest.stepControl.restriction = step_buffer.front().restriction; getMotionRequest().walkRequest.stepControl.isProtected = step_buffer.front().isProtected; getMotionRequest().walkRequest.stepControl.stepRequestID = last_stepRequestID; // normal walking WALKSTEPs use Foot::NONE, for KICKSTEPs the foot to use has to be specified if (step_buffer.front().foot == Foot::NONE) { switch (getMotionStatus().stepControl.moveableFoot) { case MotionStatus::StepControlStatus::LEFT: foot_to_use = Foot::LEFT; break; case MotionStatus::StepControlStatus::RIGHT: foot_to_use = Foot::RIGHT; break; case MotionStatus::StepControlStatus::BOTH: if (step_buffer.front().pose.translation.y > 0.0f || step_buffer.front().pose.rotation > 0.0f) { foot_to_use = Foot::LEFT; } else { foot_to_use = Foot::RIGHT; } break; case MotionStatus::StepControlStatus::NONE: foot_to_use = Foot::RIGHT; break; } } else { foot_to_use = step_buffer.front().foot; } // false means right foot getMotionRequest().walkRequest.stepControl.moveLeftFoot = (foot_to_use != Foot::RIGHT); STOPWATCH_STOP("PathPlanner:execute_steplist"); }
/** * @file PathPlanner.cpp * * @author <a href="mailto:[email protected]">Yigit Can Akcay</a> * Implementation of class PathPlanner */ #include "PathPlanner.h" PathPlanner::PathPlanner() : step_buffer({}), foot_to_use(Foot::RIGHT), last_stepRequestID(getMotionStatus().stepControl.stepRequestID + 1), // WalkRequest stepRequestID starts at 0, we have to start at 1 kick_planned(false) { DEBUG_REQUEST_REGISTER("PathPlanner:walk_to_ball", "Walks to the ball from far.", false); getDebugParameterList().add(&params); } PathPlanner::~PathPlanner() { getDebugParameterList().remove(&params); } void PathPlanner::execute() { // --- DEBUG REQUESTS --- DEBUG_REQUEST("PathPlanner:walk_to_ball", if (getBallModel().positionPreview.x > 250) { walk_to_ball(Foot::NONE); } ); // --- DEBUG REQUESTS --- getPathModel().kick_executed = false; STOPWATCH_START("PathPlanner"); // Always executed first manage_step_buffer(); // The kick has been executed // Tells XABSL to jump into next state if (kick_planned && step_buffer.empty()) { getPathModel().kick_executed = true; } // HACK: xabsl set a firced motion request => clear everything if(getPathModel().path_routine == PathModel::PathRoutine::NONE && getMotionRequest().forced) { step_buffer.clear(); return; } switch (getPathModel().path_routine) { case PathModel::PathRoutine::NONE: // There is no kick planned, since the kick has been executed // and XABSL is in a different state now if (kick_planned) { kick_planned = false; } if (step_buffer.empty()) { return; } break; case PathModel::PathRoutine::GO_TO_BALL_FAST: walk_to_ball(Foot::NONE , true); break; case PathModel::PathRoutine::GO_TO_BALL_SLOW: walk_to_ball(Foot::NONE); break; case PathModel::PathRoutine::MOVE_AROUND_BALL: move_around_ball(getPathModel().direction, getPathModel().radius); break; case PathModel::PathRoutine::APPROACH_BALL_LEFT: approach_ball(Foot::LEFT); break; case PathModel::PathRoutine::APPROACH_BALL_RIGHT: approach_ball(Foot::RIGHT); break; case PathModel::PathRoutine::SHORT_KICK_LEFT: short_kick(Foot::LEFT); break; case PathModel::PathRoutine::SHORT_KICK_RIGHT: short_kick(Foot::RIGHT); break; case PathModel::PathRoutine::LONG_KICK_LEFT: long_kick(Foot::LEFT); break; case PathModel::PathRoutine::LONG_KICK_RIGHT: long_kick(Foot::RIGHT); break; case PathModel::PathRoutine::SIDEKICK_LEFT: sidekick(Foot::LEFT); break; case PathModel::PathRoutine::SIDEKICK_RIGHT: sidekick(Foot::RIGHT); break; } // Always executed last execute_step_buffer(); STOPWATCH_STOP("PathPlanner"); } void PathPlanner::walk_to_ball(const Foot foot, const bool go_fast) { Vector2d ballPos = Vector2d(); double ballRadius = getFieldInfo().ballRadius; WalkRequest::Coordinate coordinate = WalkRequest::Hip; switch (foot) { case Foot::LEFT: ballPos = getBallModel().positionPreviewInLFoot; coordinate = WalkRequest::LFoot; break; case Foot::RIGHT: ballPos = getBallModel().positionPreviewInRFoot; coordinate = WalkRequest::RFoot; break; case Foot::NONE: ballPos = getBallModel().positionPreview; coordinate = WalkRequest::Hip; break; } double ballRotation = ballPos.angle(); Pose2D pose = { ballRotation, 0.7*(ballPos.x - getPathModel().distance - ballRadius), ballPos.y }; if (step_buffer.empty()) { StepType type = StepType::WALKSTEP; double scale = 1.0; double speed_direction = 0.0; if (go_fast) { double character = 1.0; add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::HARD, false); } else { double character = 0.3; add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::HARD, false); } } else { update_step(pose); } } void PathPlanner::move_around_ball(const double direction, const double radius) { Vector2d ballPos = getBallModel().positionPreview; double ballRotation = ballPos.angle(); double ballDistance = ballPos.abs(); WalkRequest::Coordinate coordinate = WalkRequest::Hip; double min1; double min2; double max1; double max2; if (direction <= 0) { min1 = 0.0; min2 = 0.0; max1 = 45.0; max2 = 100.0; } else { min1 = -45; min2 = -100; max1 = 0; max2 = 0; } double stepX = (ballDistance - radius) * std::cos(ballRotation); double stepY = Math::clamp(radius * std::tan(Math::clamp(Math::toDegrees(-direction), min1, max1)), min2, max2) * std::cos(ballRotation); Pose2D pose = { ballRotation, stepX, stepY }; if (step_buffer.empty()) { StepType type = StepType::WALKSTEP; double character = 0.7; Foot foot = Foot::NONE; double scale = 1.0; double speed_direction = 0.0; add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::HARD, false); } else { update_step(pose); } } void PathPlanner::approach_ball(const Foot foot) { Vector2d ballPos = Vector2d(); WalkRequest::Coordinate coordinate = WalkRequest::Hip; double stepX = 0.0; double stepY = 0.0; double ballRadius = getFieldInfo().ballRadius; double stepRotation = ballPos.abs() > 250 ? ballPos.angle() : 0; switch (foot) { case Foot::LEFT: ballPos = getBallModel().positionPreviewInLFoot; coordinate = WalkRequest::LFoot; stepX = ballPos.x - std::abs(ballPos.y - getPathModel().yOffset) - getPathModel().distance - ballRadius; stepY = ballPos.y - getPathModel().yOffset; break; case Foot::RIGHT: ballPos = getBallModel().positionPreviewInRFoot; coordinate = WalkRequest::RFoot; stepX = ballPos.x - std::abs(ballPos.y + getPathModel().yOffset) - getPathModel().distance - ballRadius; stepY = ballPos.y + getPathModel().yOffset; break; case Foot::NONE: ASSERT(false); } //if (ballPos.x < getPathModel().distance + 30 && ballPos.x > getPathModel().distance - 30) if (stepX < 0 && ballPos.x > getPathModel().distance + 30) { stepX = 0; } const double slow_down_factor = 0.7; Pose2D pose; if ( params.approach_ball_adapt_control && Vector2d(stepX, stepY).abs() < params.approach_ball_adapt_threshold) { pose = { stepRotation, stepX, stepY }; } else { pose = { stepRotation, slow_down_factor * stepX, slow_down_factor * stepY }; } if (step_buffer.empty()) { StepType type = StepType::WALKSTEP; double character = 0.7; double scale = 1.0; double speed_direction = 0.0; add_step(pose, type, coordinate, character, Foot::NONE, scale, speed_direction, WalkRequest::StepControlRequest::HARD, false); } else { update_step(pose); } } void PathPlanner::short_kick(const Foot foot) { if (!kick_planned) { WalkRequest::Coordinate coordinate = WalkRequest::Hip; switch (foot) { case Foot::LEFT: coordinate = WalkRequest::RFoot; break; case Foot::RIGHT: coordinate = WalkRequest::LFoot; break; case Foot::NONE: ASSERT(false); } if (step_buffer.empty()) { Pose2D pose = { 0.0, 500 , 0.0 }; StepType type = StepType::KICKSTEP; double character = 1.0; double scale = 0.7; double speed_direction = 0.0; add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::SOFT, true); type = StepType::ZEROSTEP; add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::SOFT, true); pose = { 0.0, 0.0, 0.0 }; type = StepType::WALKSTEP; add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::HARD, true); kick_planned = true; } } } void PathPlanner::long_kick(const Foot foot) { if (!kick_planned) { WalkRequest::Coordinate coordinate = WalkRequest::Hip; switch (foot) { case Foot::LEFT: coordinate = WalkRequest::RFoot; break; case Foot::RIGHT: coordinate = WalkRequest::LFoot; break; case Foot::NONE: ASSERT(false); } if (step_buffer.empty()) { Pose2D pose = { 0.0, 500, 0.0 }; StepType type = StepType::KICKSTEP; double character = 1.0; double scale = 0.7; double speed_direction = 0.0; add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::SOFT, true); type = StepType::ZEROSTEP; add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::SOFT, true); pose = { 0.0, 0.0, 0.0 }; type = StepType::WALKSTEP; add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::HARD, true); kick_planned = true; } } } void PathPlanner::sidekick(const Foot foot) { if (!kick_planned) { double speed_direction = 0.0; double stepY = 0.0; WalkRequest::Coordinate coordinate = WalkRequest::Hip; switch (foot) { case Foot::LEFT: coordinate = WalkRequest::LFoot; speed_direction = 90; stepY = 100; break; case Foot::RIGHT: coordinate = WalkRequest::RFoot; speed_direction = -90; stepY = -100; break; case Foot::NONE: ASSERT(false); } if (step_buffer.empty()) { Pose2D pose = { 0.0, 500, stepY }; StepType type = StepType::KICKSTEP; double character = 1.0; Foot step_foot = foot == Foot::RIGHT ? Foot::LEFT : Foot::RIGHT; double scale = params.sidekick_scale; add_step(pose, type, coordinate, character, step_foot, scale, speed_direction, WalkRequest::StepControlRequest::SOFT, true); type = StepType::ZEROSTEP; add_step(pose, type, coordinate, character, step_foot, scale, speed_direction, WalkRequest::StepControlRequest::SOFT, true); pose = { 0.0, 0.0, 0.0 }; type = StepType::WALKSTEP; add_step(pose, type, coordinate, character, step_foot, scale, speed_direction, WalkRequest::StepControlRequest::HARD, true); kick_planned = true; } } } // Stepcontrol void PathPlanner::add_step(Pose2D &pose, const StepType &type, const WalkRequest::Coordinate &coordinate, const double character, const Foot foot, const double scale, const double speedDirection, const WalkRequest::StepControlRequest::RestrictionMode restriction, bool isProtected) { step_buffer.push_back(Step_Buffer_Element({ pose, speedDirection, type, type == StepType::KICKSTEP ? params.kick_time : 250, character, scale, foot, coordinate, restriction, isProtected})); } void PathPlanner::update_step(Pose2D &pose) { ASSERT(step_buffer.size() > 0); step_buffer.front().pose = pose; } void PathPlanner::manage_step_buffer() { if (step_buffer.empty()) { return; } // requested step has been accepted if (last_stepRequestID == getMotionStatus().stepControl.stepRequestID) { step_buffer.erase(step_buffer.begin()); last_stepRequestID = getMotionStatus().stepControl.stepRequestID + 1; } } void PathPlanner::execute_step_buffer() { STOPWATCH_START("PathPlanner:execute_steplist"); if (step_buffer.empty()) { return; } getMotionRequest().id = motion::walk; getMotionRequest().walkRequest.coordinate = step_buffer.front().coordinate; getMotionRequest().walkRequest.character = step_buffer.front().character; getMotionRequest().walkRequest.stepControl.scale = step_buffer.front().scale; getMotionRequest().walkRequest.stepControl.stepID = getMotionStatus().stepControl.stepID; getMotionRequest().walkRequest.stepControl.type = step_buffer.front().type; getMotionRequest().walkRequest.stepControl.time = step_buffer.front().time; getMotionRequest().walkRequest.stepControl.speedDirection = Math::fromDegrees(step_buffer.front().speedDirection); getMotionRequest().walkRequest.stepControl.target = step_buffer.front().pose; getMotionRequest().walkRequest.stepControl.restriction = step_buffer.front().restriction; getMotionRequest().walkRequest.stepControl.isProtected = step_buffer.front().isProtected; getMotionRequest().walkRequest.stepControl.stepRequestID = last_stepRequestID; // normal walking WALKSTEPs use Foot::NONE, for KICKSTEPs the foot to use has to be specified if (step_buffer.front().foot == Foot::NONE) { switch (getMotionStatus().stepControl.moveableFoot) { case MotionStatus::StepControlStatus::LEFT: foot_to_use = Foot::LEFT; break; case MotionStatus::StepControlStatus::RIGHT: foot_to_use = Foot::RIGHT; break; case MotionStatus::StepControlStatus::BOTH: if (step_buffer.front().pose.translation.y > 0.0f || step_buffer.front().pose.rotation > 0.0f) { foot_to_use = Foot::LEFT; } else { foot_to_use = Foot::RIGHT; } break; case MotionStatus::StepControlStatus::NONE: foot_to_use = Foot::RIGHT; break; } } else { foot_to_use = step_buffer.front().foot; } // false means right foot getMotionRequest().walkRequest.stepControl.moveLeftFoot = (foot_to_use != Foot::RIGHT); STOPWATCH_STOP("PathPlanner:execute_steplist"); }
convert speedDirection from degrees to radians in PathPlanner
convert speedDirection from degrees to radians in PathPlanner
C++
apache-2.0
BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH
33ae1aa08cb9b0f8ae328fb18cd2cd710858eb0c
Modules/ToFHardware/Testing/mitkToFNrrdImageWriterTest.cpp
Modules/ToFHardware/Testing/mitkToFNrrdImageWriterTest.cpp
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include <mitkTestingMacros.h> #include <mitkToFNrrdImageWriter.h> #include <mitkImageGenerator.h> #include <mitkImageSliceSelector.h> #include "mitkItkImageFileReader.h" /**Documentation * test for the class "ToFImageWriter". */ int mitkToFNrrdImageWriterTest(int /* argc */, char* /*argv*/[]) { MITK_TEST_BEGIN("ToFNrrdImageWriter"); mitk::ToFNrrdImageWriter::Pointer tofNrrdWriter = mitk::ToFNrrdImageWriter::New(); // testing correct initialization MITK_TEST_CONDITION_REQUIRED(tofNrrdWriter.GetPointer(), "Testing initialization of test object!"); MITK_TEST_CONDITION_REQUIRED(tofNrrdWriter->GetExtension() == ".nrrd", "testing initialization of extension member variable!"); //GENERATE TEST DATA ////run the test with some unusual parameters unsigned int dimX = 255; unsigned int dimY = 178; unsigned int pixelNumber = dimX*dimY; unsigned int numOfFrames = 23; //or numberOfSlices ////create 3 images filled with random values mitk::Image::Pointer distanceImage = mitk::ImageGenerator::GenerateRandomImage<float>(dimX, dimY, numOfFrames,0, 1.0f, 1.0f); mitk::Image::Pointer amplitudeImage = mitk::ImageGenerator::GenerateRandomImage<float>(dimX, dimY, numOfFrames,0, 0.0f, 2000.0f); mitk::Image::Pointer intensityImage = mitk::ImageGenerator::GenerateRandomImage<float>(dimX, dimY, numOfFrames,0, 0.0f, 100000.0f); //SET NEEDED PARAMETER //file names on the disc std::string distanceImageFileName("distImg.nrrd"); std::string amplitudeImageFileName("amplImg.nrrd"); std::string intensityImageFileName("intImg.nrrd"); // set file name methods tofNrrdWriter->SetDistanceImageFileName(distanceImageFileName); tofNrrdWriter->SetAmplitudeImageFileName(amplitudeImageFileName); tofNrrdWriter->SetIntensityImageFileName(intensityImageFileName); tofNrrdWriter->SetCaptureWidth(dimX); tofNrrdWriter->SetCaptureHeight(dimY); tofNrrdWriter->SetToFImageType(mitk::ToFNrrdImageWriter::ToFImageType3D); tofNrrdWriter->SetRGBImageSelected(false); //buffer for each slice float* distanceArray; float* amplitudeArray; float* intensityArray; float* distanceArrayRead; float* amplitudeArrayRead; float* intensityArrayRead; tofNrrdWriter->Open(); //open file/stream for(unsigned int i = 0; i < numOfFrames ; i++) { distanceArray = (float*)distanceImage->GetSliceData(i, 0, 0)->GetData(); amplitudeArray = (float*)amplitudeImage->GetSliceData(i, 0, 0)->GetData(); intensityArray = (float*)intensityImage->GetSliceData(i, 0, 0)->GetData(); //write (or add) the three slices to the file tofNrrdWriter->Add(distanceArray, amplitudeArray, intensityArray); } tofNrrdWriter->Close(); //close file //read in the three images from disc mitk::ItkImageFileReader::Pointer fileReader = mitk::ItkImageFileReader::New(); fileReader->SetFileName(distanceImageFileName); fileReader->Update(); mitk::Image::Pointer distanceImageRead = fileReader->GetOutput(); fileReader = mitk::ItkImageFileReader::New(); fileReader->SetFileName(amplitudeImageFileName); fileReader->Update(); mitk::Image::Pointer amplitudeImageRead = fileReader->GetOutput(); fileReader = mitk::ItkImageFileReader::New(); fileReader->SetFileName(intensityImageFileName); fileReader->Update(); mitk::Image::Pointer intensityImageRead = fileReader->GetOutput(); bool readingCorrect = true; // for all frames... for(unsigned int j=0; j < numOfFrames; j++) { //get one slice of each image and compare it //original data distanceArray = (float*)distanceImage->GetSliceData(j, 0, 0)->GetData(); amplitudeArray = (float*)amplitudeImage->GetSliceData(j, 0, 0)->GetData(); intensityArray = (float*)intensityImage->GetSliceData(j, 0, 0)->GetData(); //data read from disc distanceArrayRead = (float*)distanceImageRead->GetSliceData(j, 0, 0)->GetData(); amplitudeArrayRead = (float*)amplitudeImageRead->GetSliceData(j, 0, 0)->GetData(); intensityArrayRead = (float*)intensityImageRead->GetSliceData(j, 0, 0)->GetData(); //for all pixels for(unsigned int i=0; i<pixelNumber; i++) { //compare if input == output if(!mitk::Equal(distanceArrayRead[i], distanceArray[i]) || !mitk::Equal(amplitudeArrayRead[i], amplitudeArray[i]) || !mitk::Equal(intensityArrayRead[i], intensityArray[i])) { readingCorrect = false; } } } remove( distanceImageFileName.c_str() ); remove( amplitudeImageFileName.c_str() ); remove( intensityImageFileName.c_str() ); MITK_TEST_CONDITION_REQUIRED(readingCorrect, "Testing if the output values are correct."); //delete created image files MITK_TEST_END(); }
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include <mitkTestingMacros.h> #include <mitkToFNrrdImageWriter.h> #include <mitkImageGenerator.h> #include <mitkImageSliceSelector.h> #include "mitkItkImageFileReader.h" /**Documentation * test for the class "ToFImageWriter". */ int mitkToFNrrdImageWriterTest(int /* argc */, char* /*argv*/[]) { MITK_TEST_BEGIN("ToFNrrdImageWriter"); mitk::ToFNrrdImageWriter::Pointer tofNrrdWriter = mitk::ToFNrrdImageWriter::New(); // testing correct initialization MITK_TEST_CONDITION_REQUIRED(tofNrrdWriter.GetPointer(), "Testing initialization of test object!"); MITK_TEST_CONDITION_REQUIRED(tofNrrdWriter->GetExtension() == ".nrrd", "testing initialization of extension member variable!"); //GENERATE TEST DATA ////run the test with some unusual parameters unsigned int dimX = 255; unsigned int dimY = 178; unsigned int pixelNumber = dimX*dimY; unsigned int numOfFrames = 23; //or numberOfSlices ////create 3 images filled with random values mitk::Image::Pointer distanceImage = mitk::ImageGenerator::GenerateRandomImage<float>(dimX, dimY, numOfFrames,0, 1.0f, 1.0f); mitk::Image::Pointer amplitudeImage = mitk::ImageGenerator::GenerateRandomImage<float>(dimX, dimY, numOfFrames,0, 0.0f, 2000.0f); mitk::Image::Pointer intensityImage = mitk::ImageGenerator::GenerateRandomImage<float>(dimX, dimY, numOfFrames,0, 0.0f, 100000.0f); //SET NEEDED PARAMETER //file names on the disc std::string distanceImageFileName("distImg.nrrd"); std::string amplitudeImageFileName("amplImg.nrrd"); std::string intensityImageFileName("intImg.nrrd"); // set file name methods tofNrrdWriter->SetDistanceImageFileName(distanceImageFileName); tofNrrdWriter->SetAmplitudeImageFileName(amplitudeImageFileName); tofNrrdWriter->SetIntensityImageFileName(intensityImageFileName); tofNrrdWriter->SetToFCaptureWidth(dimX); tofNrrdWriter->SetToFCaptureHeight(dimY); tofNrrdWriter->SetToFImageType(mitk::ToFNrrdImageWriter::ToFImageType3D); tofNrrdWriter->SetRGBImageSelected(false); //buffer for each slice float* distanceArray; float* amplitudeArray; float* intensityArray; float* distanceArrayRead; float* amplitudeArrayRead; float* intensityArrayRead; tofNrrdWriter->Open(); //open file/stream for(unsigned int i = 0; i < numOfFrames ; i++) { distanceArray = (float*)distanceImage->GetSliceData(i, 0, 0)->GetData(); amplitudeArray = (float*)amplitudeImage->GetSliceData(i, 0, 0)->GetData(); intensityArray = (float*)intensityImage->GetSliceData(i, 0, 0)->GetData(); //write (or add) the three slices to the file tofNrrdWriter->Add(distanceArray, amplitudeArray, intensityArray); } tofNrrdWriter->Close(); //close file //read in the three images from disc mitk::ItkImageFileReader::Pointer fileReader = mitk::ItkImageFileReader::New(); fileReader->SetFileName(distanceImageFileName); fileReader->Update(); mitk::Image::Pointer distanceImageRead = fileReader->GetOutput(); fileReader = mitk::ItkImageFileReader::New(); fileReader->SetFileName(amplitudeImageFileName); fileReader->Update(); mitk::Image::Pointer amplitudeImageRead = fileReader->GetOutput(); fileReader = mitk::ItkImageFileReader::New(); fileReader->SetFileName(intensityImageFileName); fileReader->Update(); mitk::Image::Pointer intensityImageRead = fileReader->GetOutput(); bool readingCorrect = true; // for all frames... for(unsigned int j=0; j < numOfFrames; j++) { //get one slice of each image and compare it //original data distanceArray = (float*)distanceImage->GetSliceData(j, 0, 0)->GetData(); amplitudeArray = (float*)amplitudeImage->GetSliceData(j, 0, 0)->GetData(); intensityArray = (float*)intensityImage->GetSliceData(j, 0, 0)->GetData(); //data read from disc distanceArrayRead = (float*)distanceImageRead->GetSliceData(j, 0, 0)->GetData(); amplitudeArrayRead = (float*)amplitudeImageRead->GetSliceData(j, 0, 0)->GetData(); intensityArrayRead = (float*)intensityImageRead->GetSliceData(j, 0, 0)->GetData(); //for all pixels for(unsigned int i=0; i<pixelNumber; i++) { //compare if input == output if(!mitk::Equal(distanceArrayRead[i], distanceArray[i]) || !mitk::Equal(amplitudeArrayRead[i], amplitudeArray[i]) || !mitk::Equal(intensityArrayRead[i], intensityArray[i])) { readingCorrect = false; } } } remove( distanceImageFileName.c_str() ); remove( amplitudeImageFileName.c_str() ); remove( intensityImageFileName.c_str() ); MITK_TEST_CONDITION_REQUIRED(readingCorrect, "Testing if the output values are correct."); //delete created image files MITK_TEST_END(); }
Use correct method for accessing CaptureHeigth / Width
Use correct method for accessing CaptureHeigth / Width
C++
bsd-3-clause
NifTK/MITK,nocnokneo/MITK,nocnokneo/MITK,fmilano/mitk,fmilano/mitk,NifTK/MITK,iwegner/MITK,RabadanLab/MITKats,iwegner/MITK,danielknorr/MITK,fmilano/mitk,rfloca/MITK,MITK/MITK,MITK/MITK,lsanzdiaz/MITK-BiiG,nocnokneo/MITK,lsanzdiaz/MITK-BiiG,lsanzdiaz/MITK-BiiG,lsanzdiaz/MITK-BiiG,danielknorr/MITK,lsanzdiaz/MITK-BiiG,NifTK/MITK,rfloca/MITK,fmilano/mitk,rfloca/MITK,nocnokneo/MITK,danielknorr/MITK,RabadanLab/MITKats,MITK/MITK,NifTK/MITK,lsanzdiaz/MITK-BiiG,fmilano/mitk,iwegner/MITK,rfloca/MITK,rfloca/MITK,fmilano/mitk,MITK/MITK,danielknorr/MITK,NifTK/MITK,NifTK/MITK,iwegner/MITK,nocnokneo/MITK,lsanzdiaz/MITK-BiiG,nocnokneo/MITK,danielknorr/MITK,danielknorr/MITK,nocnokneo/MITK,MITK/MITK,lsanzdiaz/MITK-BiiG,rfloca/MITK,iwegner/MITK,RabadanLab/MITKats,RabadanLab/MITKats,RabadanLab/MITKats,MITK/MITK,danielknorr/MITK,rfloca/MITK,RabadanLab/MITKats,iwegner/MITK,fmilano/mitk
58dac26533d37f490dc1fdea6757e11e16795052
lib/src/models/api/html-api.cpp
lib/src/models/api/html-api.cpp
#include "models/api/html-api.h" #include <QRegularExpression> #include "vendor/json.h" HtmlApi::HtmlApi(const QMap<QString, QString> &data) : Api("Html", data) {} ParsedPage HtmlApi::parsePage(Page *parentPage, const QString &source, int first) const { ParsedPage ret; // Getting tags if (contains("Regex/Tags")) { QRegularExpression rxtags(value("Regex/Tags"), QRegularExpression::DotMatchesEverythingOption); QStringList tags = QStringList(); auto matches = rxtags.globalMatch(source); while (matches.hasNext()) { auto match = matches.next(); if (!tags.contains(match.captured(2))) { ret.tags.append(Tag(match.captured(2), match.captured(1), match.captured(3).toInt())); tags.append(match.captured(2)); } } } // Getting images QRegularExpression rx(value("Regex/Image"), QRegularExpression::DotMatchesEverythingOption); auto matches = rx.globalMatch(source); int id = 0; while (matches.hasNext()) { auto match = matches.next(); QMap<QString, QString> d; for (QString group : rx.namedCaptureGroups()) { if (group.isEmpty()) continue; QString val = match.captured(group); if (!val.isEmpty()) { int underscorePos = group.lastIndexOf('_'); bool ok; group.midRef(underscorePos + 1).toInt(&ok); if (underscorePos != -1 && ok) { group = group.left(underscorePos); } d[group] = val; } } // JSON elements if (d.contains("json") && !d["json"].isEmpty()) { QVariant src = Json::parse(d["json"]); if (!src.isNull()) { QMap<QString, QVariant> map = src.toMap(); for (auto it = map.begin(); it != map.end(); ++it) { d[it.key()] = it.value().toString(); } } } QSharedPointer<Image> img = parseImage(parentPage, d, id + first); if (!img.isNull()) { ret.images.append(img); } id++; } // Navigation if (contains("Regex/NextPage")) { QRegularExpression rx(value("Regex/NextPage")); auto match = rx.match(source); if (match.hasMatch()) { ret.urlNextPage = QUrl(match.captured(1)); } } if (contains("Regex/PrevPage")) { QRegularExpression rx(value("Regex/PrevPage")); auto match = rx.match(source); if (match.hasMatch()) { ret.urlPrevPage = QUrl(match.captured(1)); } } // Count images if (contains("Regex/Count")) { QRegularExpression rxlast(value("Regex/Count")); auto match = rxlast.match(source); int cnt = match.hasMatch() ? match.captured(1).remove(",").toInt() : 0; if (cnt > 0) { ret.imageCount = cnt; } } return ret; }
#include "models/api/html-api.h" #include <QRegularExpression> #include "vendor/json.h" HtmlApi::HtmlApi(const QMap<QString, QString> &data) : Api("Html", data) {} ParsedPage HtmlApi::parsePage(Page *parentPage, const QString &source, int first) const { ParsedPage ret; // Getting tags if (contains("Regex/Tags")) { QList<Tag> tgs = Tag::FromRegexp(value("Regex/Tags"), source); if (!tgs.isEmpty()) { ret.tags = tgs; } } // Getting images QRegularExpression rx(value("Regex/Image"), QRegularExpression::DotMatchesEverythingOption); auto matches = rx.globalMatch(source); int id = 0; while (matches.hasNext()) { auto match = matches.next(); QMap<QString, QString> d; for (QString group : rx.namedCaptureGroups()) { if (group.isEmpty()) continue; QString val = match.captured(group); if (!val.isEmpty()) { int underscorePos = group.lastIndexOf('_'); bool ok; group.midRef(underscorePos + 1).toInt(&ok); if (underscorePos != -1 && ok) { group = group.left(underscorePos); } d[group] = val; } } // JSON elements if (d.contains("json") && !d["json"].isEmpty()) { QVariant src = Json::parse(d["json"]); if (!src.isNull()) { QMap<QString, QVariant> map = src.toMap(); for (auto it = map.begin(); it != map.end(); ++it) { d[it.key()] = it.value().toString(); } } } QSharedPointer<Image> img = parseImage(parentPage, d, id + first); if (!img.isNull()) { ret.images.append(img); } id++; } // Navigation if (contains("Regex/NextPage")) { QRegularExpression rx(value("Regex/NextPage")); auto match = rx.match(source); if (match.hasMatch()) { ret.urlNextPage = QUrl(match.captured(1)); } } if (contains("Regex/PrevPage")) { QRegularExpression rx(value("Regex/PrevPage")); auto match = rx.match(source); if (match.hasMatch()) { ret.urlPrevPage = QUrl(match.captured(1)); } } // Count images if (contains("Regex/Count")) { QRegularExpression rxlast(value("Regex/Count")); auto match = rxlast.match(source); int cnt = match.hasMatch() ? match.captured(1).remove(",").toInt() : 0; if (cnt > 0) { ret.imageCount = cnt; } } return ret; }
Simplify tag regex parsing in HtmlApi class
Simplify tag regex parsing in HtmlApi class
C++
apache-2.0
Bionus/imgbrd-grabber,Bionus/imgbrd-grabber,Bionus/imgbrd-grabber,Bionus/imgbrd-grabber,Bionus/imgbrd-grabber,Bionus/imgbrd-grabber
b505a12c5a055c5de481736d7b9b6b17593aaede
Source/RuntimeMeshComponentEditor/Private/RuntimeMeshComponentDetails.cpp
Source/RuntimeMeshComponentEditor/Private/RuntimeMeshComponentDetails.cpp
// Copyright 2016 Chris Conway (Koderz). All Rights Reserved. #include "RuntimeMeshComponentEditorPrivatePCH.h" #include "RuntimeMeshComponentDetails.h" #include "DlgPickAssetPath.h" #include "AssetToolsModule.h" #include "AssetRegistryModule.h" #define LOCTEXT_NAMESPACE "RuntimeMeshComponentDetails" TSharedRef<IDetailCustomization> FRuntimeMeshComponentDetails::MakeInstance() { return MakeShareable(new FRuntimeMeshComponentDetails); } void FRuntimeMeshComponentDetails::CustomizeDetails( IDetailLayoutBuilder& DetailBuilder ) { IDetailCategoryBuilder& RuntimeMeshCategory = DetailBuilder.EditCategory("RuntimeMesh"); const FText ConvertToStaticMeshText = LOCTEXT("ConvertToStaticMesh", "Create StaticMesh"); // Cache set of selected things SelectedObjectsList = DetailBuilder.GetDetailsView().GetSelectedObjects(); RuntimeMeshCategory.AddCustomRow(ConvertToStaticMeshText, false) .NameContent() [ SNullWidget::NullWidget ] .ValueContent() .VAlign(VAlign_Center) .MaxDesiredWidth(250) [ SNew(SButton) .VAlign(VAlign_Center) .ToolTipText(LOCTEXT("ConvertToStaticMeshTooltip", "Create a new StaticMesh asset using current geometry from this RuntimeMeshComponent. Does not modify instance.")) .OnClicked(this, &FRuntimeMeshComponentDetails::ClickedOnConvertToStaticMesh) .IsEnabled(this, &FRuntimeMeshComponentDetails::ConvertToStaticMeshEnabled) .Content() [ SNew(STextBlock) .Text(ConvertToStaticMeshText) ] ]; } URuntimeMeshComponent* FRuntimeMeshComponentDetails::GetFirstSelectedRuntimeMeshComp() const { // Find first selected valid RuntimeMeshComp URuntimeMeshComponent* RuntimeMeshComp = nullptr; for (const TWeakObjectPtr<UObject>& Object : SelectedObjectsList) { URuntimeMeshComponent* TestRuntimeComp = Cast<URuntimeMeshComponent>(Object.Get()); // See if this one is good if (TestRuntimeComp != nullptr && !TestRuntimeComp->IsTemplate()) { RuntimeMeshComp = TestRuntimeComp; break; } } return RuntimeMeshComp; } bool FRuntimeMeshComponentDetails::ConvertToStaticMeshEnabled() const { return GetFirstSelectedRuntimeMeshComp() != nullptr; } FReply FRuntimeMeshComponentDetails::ClickedOnConvertToStaticMesh() { // Find first selected RuntimeMeshComp URuntimeMeshComponent* RuntimeMeshComp = GetFirstSelectedRuntimeMeshComp(); if (RuntimeMeshComp != nullptr) { FString NewNameSuggestion = FString(TEXT("RuntimeMeshComp")); FString PackageName = FString(TEXT("/Game/Meshes/")) + NewNameSuggestion; FString Name; FAssetToolsModule& AssetToolsModule = FModuleManager::LoadModuleChecked<FAssetToolsModule>("AssetTools"); AssetToolsModule.Get().CreateUniqueAssetName(PackageName, TEXT(""), PackageName, Name); TSharedPtr<SDlgPickAssetPath> PickAssetPathWidget = SNew(SDlgPickAssetPath) .Title(LOCTEXT("ConvertToStaticMeshPickName", "Choose New StaticMesh Location")) .DefaultAssetPath(FText::FromString(PackageName)); if (PickAssetPathWidget->ShowModal() == EAppReturnType::Ok) { // Get the full name of where we want to create the physics asset. FString UserPackageName = PickAssetPathWidget->GetFullAssetPath().ToString(); FName MeshName(*FPackageName::GetLongPackageAssetName(UserPackageName)); // Check if the user inputed a valid asset name, if they did not, give it the generated default name if (MeshName == NAME_None) { // Use the defaults that were already generated. UserPackageName = PackageName; MeshName = *Name; } // Raw mesh data we are filling in FRawMesh RawMesh; // Materials to apply to new mesh TArray<UMaterialInterface*> MeshMaterials; bool bUseHighPrecisionTangents = false; bool bUseFullPrecisionUVs = false; const int32 NumSections = RuntimeMeshComp->GetNumSections(); int32 VertexBase = 0; for (int32 SectionIdx = 0; SectionIdx < NumSections; SectionIdx++) { const IRuntimeMeshVerticesBuilder* Vertices; const FRuntimeMeshIndicesBuilder* Indices; RuntimeMeshComp->GetSectionMesh(SectionIdx, Vertices, Indices); if (Vertices->HasHighPrecisionNormals()) { bUseHighPrecisionTangents = true; } if (Vertices->HasHighPrecisionUVs()) { bUseFullPrecisionUVs = true; } // Copy verts Vertices->Seek(-1); while (Vertices->MoveNext() < Vertices->Length()) { RawMesh.VertexPositions.Add(Vertices->GetPosition()); } // Copy 'wedge' info Indices->Seek(0); while (Indices->HasRemaining()) { int32 Index = Indices->ReadOne(); RawMesh.WedgeIndices.Add(Index + VertexBase); Vertices->Seek(Index); FVector TangentX = Vertices->GetTangent(); FVector TangentZ = Vertices->GetNormal(); FVector TangentY = (TangentX ^ TangentZ).GetSafeNormal() * Vertices->GetNormal().W; RawMesh.WedgeTangentX.Add(TangentX); RawMesh.WedgeTangentY.Add(TangentY); RawMesh.WedgeTangentZ.Add(TangentZ); for (int UVIndex = 0; UVIndex < 8; UVIndex++) { if (!Vertices->HasUVComponent(UVIndex)) { break; } RawMesh.WedgeTexCoords[UVIndex].Add(Vertices->GetUV(UVIndex)); } RawMesh.WedgeColors.Add(Vertices->GetColor()); } // copy face info int32 NumTris = Indices->Length() / 3; for (int32 TriIdx=0; TriIdx < NumTris; TriIdx++) { RawMesh.FaceMaterialIndices.Add(SectionIdx); RawMesh.FaceSmoothingMasks.Add(0); // Assume this is ignored as bRecomputeNormals is false } // Remember material MeshMaterials.Add(RuntimeMeshComp->GetMaterial(SectionIdx)); // Update offset for creating one big index/vertex buffer VertexBase += Vertices->Length(); } // If we got some valid data. if (RawMesh.VertexPositions.Num() > 3 && RawMesh.WedgeIndices.Num() > 3) { // Then find/create it. UPackage* Package = CreatePackage(NULL, *UserPackageName); check(Package); // Create StaticMesh object UStaticMesh* StaticMesh = NewObject<UStaticMesh>(Package, MeshName, RF_Public | RF_Standalone); StaticMesh->InitResources(); StaticMesh->LightingGuid = FGuid::NewGuid(); // Add source to new StaticMesh FStaticMeshSourceModel* SrcModel = new (StaticMesh->SourceModels) FStaticMeshSourceModel(); SrcModel->BuildSettings.bRecomputeNormals = false; SrcModel->BuildSettings.bRecomputeTangents = false; SrcModel->BuildSettings.bRemoveDegenerates = false; SrcModel->BuildSettings.bUseHighPrecisionTangentBasis = bUseHighPrecisionTangents; SrcModel->BuildSettings.bUseFullPrecisionUVs = bUseFullPrecisionUVs; SrcModel->BuildSettings.bGenerateLightmapUVs = true; SrcModel->BuildSettings.SrcLightmapIndex = 0; SrcModel->BuildSettings.DstLightmapIndex = 1; SrcModel->RawMeshBulkData->SaveRawMesh(RawMesh); // Copy materials to new mesh for (UMaterialInterface* Material : MeshMaterials) { #if ENGINE_MAJOR_VERSION == 4 && ENGINE_MINOR_VERSION >= 14 StaticMesh->StaticMaterials.Add(FStaticMaterial(Material)); #else StaticMesh->Materials.Add(Material); #endif } // Build mesh from source StaticMesh->Build(false); StaticMesh->PostEditChange(); // Notify asset registry of new asset FAssetRegistryModule::AssetCreated(StaticMesh); } } } return FReply::Handled(); } #undef LOCTEXT_NAMESPACE
// Copyright 2016 Chris Conway (Koderz). All Rights Reserved. #include "RuntimeMeshComponentEditorPrivatePCH.h" #include "RuntimeMeshComponentDetails.h" #include "DlgPickAssetPath.h" #include "AssetToolsModule.h" #include "AssetRegistryModule.h" #define LOCTEXT_NAMESPACE "RuntimeMeshComponentDetails" TSharedRef<IDetailCustomization> FRuntimeMeshComponentDetails::MakeInstance() { return MakeShareable(new FRuntimeMeshComponentDetails); } void FRuntimeMeshComponentDetails::CustomizeDetails( IDetailLayoutBuilder& DetailBuilder ) { IDetailCategoryBuilder& RuntimeMeshCategory = DetailBuilder.EditCategory("RuntimeMesh"); const FText ConvertToStaticMeshText = LOCTEXT("ConvertToStaticMesh", "Create StaticMesh"); // Cache set of selected things SelectedObjectsList = DetailBuilder.GetDetailsView().GetSelectedObjects(); RuntimeMeshCategory.AddCustomRow(ConvertToStaticMeshText, false) .NameContent() [ SNullWidget::NullWidget ] .ValueContent() .VAlign(VAlign_Center) .MaxDesiredWidth(250) [ SNew(SButton) .VAlign(VAlign_Center) .ToolTipText(LOCTEXT("ConvertToStaticMeshTooltip", "Create a new StaticMesh asset using current geometry from this RuntimeMeshComponent. Does not modify instance.")) .OnClicked(this, &FRuntimeMeshComponentDetails::ClickedOnConvertToStaticMesh) .IsEnabled(this, &FRuntimeMeshComponentDetails::ConvertToStaticMeshEnabled) .Content() [ SNew(STextBlock) .Text(ConvertToStaticMeshText) ] ]; } URuntimeMeshComponent* FRuntimeMeshComponentDetails::GetFirstSelectedRuntimeMeshComp() const { // Find first selected valid RuntimeMeshComp URuntimeMeshComponent* RuntimeMeshComp = nullptr; for (const TWeakObjectPtr<UObject>& Object : SelectedObjectsList) { URuntimeMeshComponent* TestRuntimeComp = Cast<URuntimeMeshComponent>(Object.Get()); // See if this one is good if (TestRuntimeComp != nullptr && !TestRuntimeComp->IsTemplate()) { RuntimeMeshComp = TestRuntimeComp; break; } } return RuntimeMeshComp; } bool FRuntimeMeshComponentDetails::ConvertToStaticMeshEnabled() const { return GetFirstSelectedRuntimeMeshComp() != nullptr; } FReply FRuntimeMeshComponentDetails::ClickedOnConvertToStaticMesh() { // Find first selected RuntimeMeshComp URuntimeMeshComponent* RuntimeMeshComp = GetFirstSelectedRuntimeMeshComp(); if (RuntimeMeshComp != nullptr) { FString NewNameSuggestion = FString(TEXT("RuntimeMeshComp")); FString PackageName = FString(TEXT("/Game/Meshes/")) + NewNameSuggestion; FString Name; FAssetToolsModule& AssetToolsModule = FModuleManager::LoadModuleChecked<FAssetToolsModule>("AssetTools"); AssetToolsModule.Get().CreateUniqueAssetName(PackageName, TEXT(""), PackageName, Name); TSharedPtr<SDlgPickAssetPath> PickAssetPathWidget = SNew(SDlgPickAssetPath) .Title(LOCTEXT("ConvertToStaticMeshPickName", "Choose New StaticMesh Location")) .DefaultAssetPath(FText::FromString(PackageName)); if (PickAssetPathWidget->ShowModal() == EAppReturnType::Ok) { // Get the full name of where we want to create the physics asset. FString UserPackageName = PickAssetPathWidget->GetFullAssetPath().ToString(); FName MeshName(*FPackageName::GetLongPackageAssetName(UserPackageName)); // Check if the user inputed a valid asset name, if they did not, give it the generated default name if (MeshName == NAME_None) { // Use the defaults that were already generated. UserPackageName = PackageName; MeshName = *Name; } // Raw mesh data we are filling in FRawMesh RawMesh; // Materials to apply to new mesh TArray<UMaterialInterface*> MeshMaterials; bool bUseHighPrecisionTangents = false; bool bUseFullPrecisionUVs = false; const int32 NumSections = RuntimeMeshComp->GetNumSections(); int32 VertexBase = 0; for (int32 SectionIdx = 0; SectionIdx < NumSections; SectionIdx++) { const IRuntimeMeshVerticesBuilder* Vertices; const FRuntimeMeshIndicesBuilder* Indices; RuntimeMeshComp->GetSectionMesh(SectionIdx, Vertices, Indices); if (Vertices->HasHighPrecisionNormals()) { bUseHighPrecisionTangents = true; } if (Vertices->HasHighPrecisionUVs()) { bUseFullPrecisionUVs = true; } // Copy verts Vertices->Seek(-1); while (Vertices->MoveNext() < Vertices->Length()) { RawMesh.VertexPositions.Add(Vertices->GetPosition()); } // Copy 'wedge' info Indices->Seek(0); while (Indices->HasRemaining()) { int32 Index = Indices->ReadOne(); RawMesh.WedgeIndices.Add(Index + VertexBase); Vertices->Seek(Index); FVector TangentX = Vertices->GetTangent(); FVector TangentZ = Vertices->GetNormal(); FVector TangentY = (TangentX ^ TangentZ).GetSafeNormal() * Vertices->GetNormal().W; RawMesh.WedgeTangentX.Add(TangentX); RawMesh.WedgeTangentY.Add(TangentY); RawMesh.WedgeTangentZ.Add(TangentZ); for (int UVIndex = 0; UVIndex < 8; UVIndex++) { if (!Vertices->HasUVComponent(UVIndex)) { break; } RawMesh.WedgeTexCoords[UVIndex].Add(Vertices->GetUV(UVIndex)); } RawMesh.WedgeColors.Add(Vertices->GetColor()); } // copy face info int32 NumTris = Indices->Length() / 3; for (int32 TriIdx=0; TriIdx < NumTris; TriIdx++) { RawMesh.FaceMaterialIndices.Add(SectionIdx); RawMesh.FaceSmoothingMasks.Add(0); // Assume this is ignored as bRecomputeNormals is false } // Remember material MeshMaterials.Add(RuntimeMeshComp->GetMaterial(SectionIdx)); // Update offset for creating one big index/vertex buffer VertexBase += Vertices->Length(); } // If we got some valid data. if (RawMesh.VertexPositions.Num() > 3 && RawMesh.WedgeIndices.Num() > 3) { // Then find/create it. UPackage* Package = CreatePackage(NULL, *UserPackageName); check(Package); // Create StaticMesh object UStaticMesh* StaticMesh = NewObject<UStaticMesh>(Package, MeshName, RF_Public | RF_Standalone); StaticMesh->InitResources(); StaticMesh->LightingGuid = FGuid::NewGuid(); // Add source to new StaticMesh FStaticMeshSourceModel* SrcModel = new (StaticMesh->SourceModels) FStaticMeshSourceModel(); SrcModel->BuildSettings.bRecomputeNormals = false; SrcModel->BuildSettings.bRecomputeTangents = false; SrcModel->BuildSettings.bRemoveDegenerates = false; SrcModel->BuildSettings.bUseHighPrecisionTangentBasis = bUseHighPrecisionTangents; SrcModel->BuildSettings.bUseFullPrecisionUVs = bUseFullPrecisionUVs; SrcModel->BuildSettings.bGenerateLightmapUVs = true; SrcModel->BuildSettings.SrcLightmapIndex = 0; SrcModel->BuildSettings.DstLightmapIndex = 1; SrcModel->RawMeshBulkData->SaveRawMesh(RawMesh); // Copy materials to new mesh for (UMaterialInterface* Material : MeshMaterials) { #if ENGINE_MAJOR_VERSION == 4 && ENGINE_MINOR_VERSION >= 14 StaticMesh->StaticMaterials.Add(FStaticMaterial(Material)); #else StaticMesh->Materials.Add(Material); #endif } // @alleysark: Set up the SectionInfoMap to enable collision (code from StaticMeshEdit.cpp:CreateStaticMesh) for (int32 SectionIdx = 0, NumSections = StaticMesh->StaticMaterials.Num(); SectionIdx < NumSections; ++SectionIdx) { FMeshSectionInfo Info = StaticMesh->SectionInfoMap.Get(0, SectionIdx); Info.MaterialIndex = SectionIdx; Info.bEnableCollision = true; StaticMesh->SectionInfoMap.Set(0, SectionIdx, Info); } // Build mesh from source StaticMesh->Build(false); StaticMesh->PostEditChange(); // Notify asset registry of new asset FAssetRegistryModule::AssetCreated(StaticMesh); } } } return FReply::Handled(); } #undef LOCTEXT_NAMESPACE
enable collision of SM created from RMC
enable collision of SM created from RMC to enable collision, SM must have a valid SectionInfoMap for each SM sections. Now you can enable the 'Use Complex Collision As Simple' option!!
C++
mit
Koderz/UE4RuntimeMeshComponent,Koderz/RuntimeMeshComponent,Koderz/UE4RuntimeMeshComponent,Koderz/UE4RuntimeMeshComponent,Koderz/RuntimeMeshComponent
a09cbe4a27bf1861ce6825f8ea456cfb83498a9c
Ext/SamplingAnalysis/E_SamplingAnalysis.cpp
Ext/SamplingAnalysis/E_SamplingAnalysis.cpp
/* This file is part of the E_MinSG library extension SamplingAnalysis. Copyright (C) 2011-2012 Claudius Jähn <[email protected]> This library is subject to the terms of the Mozilla Public License, v. 2.0. You should have received a copy of the MPL along with this library; see the file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/. */ #ifdef MINSG_EXT_SAMPLING_ANALYSIS #include "E_SamplingAnalysis.h" #include "../../ELibMinSG.h" #include <EScript/Utils/DeprecatedMacros.h> #include <E_Geometry/E_Vec3.h> #include <E_Util/Graphics/E_Bitmap.h> #include <MinSG/Ext/SamplingAnalysis/SamplingAnalysis.h> namespace E_MinSG { namespace E_SamplingAnalysis{ using namespace EScript; using namespace MinSG; using namespace E_Geometry; using namespace SamplingAnalysis; static Object * createEHistogram(SamplingAnalysis::Histogram1D * hist){ Array * buckets(Array::create()); for(std::vector<uint32_t>::iterator it=hist->buckets.begin();it!=hist->buckets.end();++it) buckets->pushBack(Number::create(*it)); ObjRef eHist( ExtObject::create() ); eHist->setAttribute("buckets",buckets); eHist->setAttribute("sum",Number::create(hist->sum)); eHist->setAttribute("maxValue",Number::create(hist->maxValue)); eHist->setAttribute("overflow",Number::create(hist->overflow)); return eHist.detachAndDecrease(); } //! (static) void init(EScript::Namespace & lib) { Namespace * ns = new Namespace(); declareConstant(&lib,"SamplingAnalysis",ns); //! result createDistanceHistogram(Array Vec3, numberOfBuckets) ES_FUNCTION2( ns, "createDistanceHistogram",2,2,{ std::vector<Geometry::Vec3> positions; for(auto & entry : *parameter[0].to<EScript::Array*>(rt)) positions.emplace_back( entry.to<const Geometry::Vec3&>(rt) ); return createEHistogram(createDistanceHistogram(positions,parameter[1].toInt())); }) //! result create2dDistanceHistogram(Array Vec3, numberOfBuckets) ES_FUNCTION2( ns, "create2dDistanceHistogram",2,2,{ std::vector<Geometry::Vec3> positions; for(auto & entry : *parameter[0].to<EScript::Array*>(rt)) positions.emplace_back( entry.to<const Geometry::Vec3&>(rt) ); return new E_Util::E_Bitmap(create2dDistanceHistogram(positions,parameter[1].toInt())); }) //! result createAngleHistogram(Array Vec3, numberOfBuckets) ES_FUNCTION2( ns, "createAngleHistogram",2,2,{ std::vector<Geometry::Vec3> positions; for(auto & entry : *parameter[0].to<EScript::Array*>(rt)) positions.emplace_back( entry.to<const Geometry::Vec3&>(rt) ); return createEHistogram(createAngleHistogram(positions,parameter[1].toInt())); }) //! result createClosestPointDistanceHistogram(Array Vec3, numberOfBuckets) ES_FUNCTION2( ns, "createClosestPointDistanceHistogram",2,2,{ std::vector<Geometry::Vec3> positions; for(auto & entry : *parameter[0].to<EScript::Array*>(rt)) positions.emplace_back( entry.to<const Geometry::Vec3&>(rt) ); return createEHistogram(createClosestPointDistanceHistogram(positions,parameter[1].toInt())); }) } } } #endif // MINSG_EXT_SAMPLING_ANALYSIS
/* This file is part of the E_MinSG library extension SamplingAnalysis. Copyright (C) 2011-2012 Claudius Jähn <[email protected]> This library is subject to the terms of the Mozilla Public License, v. 2.0. You should have received a copy of the MPL along with this library; see the file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/. */ #ifdef MINSG_EXT_SAMPLING_ANALYSIS #include "E_SamplingAnalysis.h" #include "../../ELibMinSG.h" #include <EScript/Utils/DeprecatedMacros.h> #include <E_Geometry/E_Vec3.h> #include <E_Util/Graphics/E_Bitmap.h> #include <MinSG/Ext/SamplingAnalysis/SamplingAnalysis.h> namespace E_MinSG { namespace E_SamplingAnalysis{ using namespace EScript; using namespace MinSG; using namespace E_Geometry; using namespace SamplingAnalysis; static Object * createEHistogram(SamplingAnalysis::Histogram1D * hist){ Array * buckets(Array::create()); for(std::vector<uint32_t>::iterator it=hist->buckets.begin();it!=hist->buckets.end();++it) buckets->pushBack(Number::create(*it)); ObjRef eHist( ExtObject::create() ); eHist->setAttribute("buckets",buckets); eHist->setAttribute("sum",Number::create(hist->sum)); eHist->setAttribute("maxValue",Number::create(hist->maxValue)); eHist->setAttribute("overflow",Number::create(hist->overflow)); return eHist.detachAndDecrease(); } //! (static) void init(EScript::Namespace & lib) { Namespace * ns = new Namespace(); declareConstant(&lib,"SamplingAnalysis",ns); //! result createDistanceHistogram(Array Vec3, numberOfBuckets) ES_FUNCTION2( ns, "createDistanceHistogram",2,2,{ std::vector<Geometry::Vec3> positions; for(auto & entry : *parameter[0].to<EScript::Array*>(rt)) positions.emplace_back( entry.to<const Geometry::Vec3&>(rt) ); return createEHistogram(createDistanceHistogram(positions,parameter[1].toInt())); }) //! result create2dDistanceHistogram(Array Vec3, numberOfBuckets) ES_FUNCTION2( ns, "create2dDistanceHistogram",2,2,{ std::vector<Geometry::Vec3> positions; for(auto & entry : *parameter[0].to<EScript::Array*>(rt)) positions.emplace_back( entry.to<const Geometry::Vec3&>(rt) ); return EScript::create(create2dDistanceHistogram(positions,parameter[1].toInt())); }) //! result createAngleHistogram(Array Vec3, numberOfBuckets) ES_FUNCTION2( ns, "createAngleHistogram",2,2,{ std::vector<Geometry::Vec3> positions; for(auto & entry : *parameter[0].to<EScript::Array*>(rt)) positions.emplace_back( entry.to<const Geometry::Vec3&>(rt) ); return createEHistogram(createAngleHistogram(positions,parameter[1].toInt())); }) //! result createClosestPointDistanceHistogram(Array Vec3, numberOfBuckets) ES_FUNCTION2( ns, "createClosestPointDistanceHistogram",2,2,{ std::vector<Geometry::Vec3> positions; for(auto & entry : *parameter[0].to<EScript::Array*>(rt)) positions.emplace_back( entry.to<const Geometry::Vec3&>(rt) ); return createEHistogram(createClosestPointDistanceHistogram(positions,parameter[1].toInt())); }) } } } #endif // MINSG_EXT_SAMPLING_ANALYSIS
Use EScript::create
Use EScript::create
C++
mpl-2.0
PADrend/E_MinSG
0eb7c11a7c2d5cfe741278f1263b4cb810e4d852
libcaf_core/caf/local_actor.hpp
libcaf_core/caf/local_actor.hpp
/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2018 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #pragma once #include <atomic> #include <cstdint> #include <exception> #include <functional> #include <type_traits> #include <utility> #include "caf/abstract_actor.hpp" #include "caf/abstract_group.hpp" #include "caf/actor.hpp" #include "caf/actor_cast.hpp" #include "caf/actor_config.hpp" #include "caf/actor_system.hpp" #include "caf/behavior.hpp" #include "caf/check_typed_input.hpp" #include "caf/delegated.hpp" #include "caf/duration.hpp" #include "caf/error.hpp" #include "caf/fwd.hpp" #include "caf/message.hpp" #include "caf/message_handler.hpp" #include "caf/message_id.hpp" #include "caf/message_priority.hpp" #include "caf/monitorable_actor.hpp" #include "caf/response_promise.hpp" #include "caf/response_type.hpp" #include "caf/resumable.hpp" #include "caf/spawn_options.hpp" #include "caf/typed_actor.hpp" #include "caf/typed_response_promise.hpp" #include "caf/detail/typed_actor_util.hpp" namespace caf { /// Base class for actors running on this node, either /// living in an own thread or cooperatively scheduled. class local_actor : public monitorable_actor { public: // -- member types ----------------------------------------------------------- /// Defines a monotonic clock suitable for measuring intervals. using clock_type = std::chrono::steady_clock; // -- constructors, destructors, and assignment operators -------------------- local_actor(actor_config& cfg); ~local_actor() override; void on_destroy() override; // -- pure virtual modifiers ------------------------------------------------- virtual void launch(execution_unit* eu, bool lazy, bool hide) = 0; // -- time ------------------------------------------------------------------- /// Returns the current time. clock_type::time_point now() const noexcept; /// Returns the difference between `t0` and `t1`, allowing the clock to /// return any arbitrary value depending on the measurement that took place. clock_type::duration difference(atom_value measurement, clock_type::time_point t0, clock_type::time_point t1); // -- timeout management ----------------------------------------------------- /// Requests a new timeout for `mid`. /// @pre `mid.valid()` void request_response_timeout(const duration& d, message_id mid); // -- spawn functions -------------------------------------------------------- template <class T, spawn_options Os = no_spawn_options, class... Ts> infer_handle_from_class_t<T> spawn(Ts&&... xs) { actor_config cfg{context()}; return eval_opts(Os, system().spawn_class<T, make_unbound(Os)>( cfg, std::forward<Ts>(xs)...)); } template <class T, spawn_options Os = no_spawn_options> infer_handle_from_state_t<T> spawn() { using impl = composable_behavior_based_actor<T>; actor_config cfg{context()}; return eval_opts(Os, system().spawn_class<impl, make_unbound(Os)>(cfg)); } template <spawn_options Os = no_spawn_options, class F, class... Ts> infer_handle_from_fun_t<F> spawn(F fun, Ts&&... xs) { actor_config cfg{context()}; return eval_opts(Os, system().spawn_functor<make_unbound(Os)>( cfg, fun, std::forward<Ts>(xs)...)); } template <class T, spawn_options Os = no_spawn_options, class Groups, class... Ts> actor spawn_in_groups(const Groups& gs, Ts&&... xs) { actor_config cfg{context()}; return eval_opts(Os, system().spawn_class_in_groups<T, make_unbound(Os)>( cfg, gs.begin(), gs.end(), std::forward<Ts>(xs)...)); } template <class T, spawn_options Os = no_spawn_options, class... Ts> actor spawn_in_groups(std::initializer_list<group> gs, Ts&&... xs) { actor_config cfg{context()}; return eval_opts(Os, system().spawn_class_in_groups<T, make_unbound(Os)>( cfg, gs.begin(), gs.end(), std::forward<Ts>(xs)...)); } template <class T, spawn_options Os = no_spawn_options, class... Ts> actor spawn_in_group(const group& grp, Ts&&... xs) { actor_config cfg{context()}; auto first = &grp; return eval_opts(Os, system().spawn_class_in_groups<T, make_unbound(Os)>( cfg, first, first + 1, std::forward<Ts>(xs)...)); } template <spawn_options Os = no_spawn_options, class Groups, class F, class... Ts> actor spawn_in_groups(const Groups& gs, F fun, Ts&&... xs) { actor_config cfg{context()}; return eval_opts( Os, system().spawn_fun_in_groups<make_unbound(Os)>( cfg, gs.begin(), gs.end(), fun, std::forward<Ts>(xs)...)); } template <spawn_options Os = no_spawn_options, class F, class... Ts> actor spawn_in_groups(std::initializer_list<group> gs, F fun, Ts&&... xs) { actor_config cfg{context()}; return eval_opts( Os, system().spawn_fun_in_groups<make_unbound(Os)>( cfg, gs.begin(), gs.end(), fun, std::forward<Ts>(xs)...)); } template <spawn_options Os = no_spawn_options, class F, class... Ts> actor spawn_in_group(const group& grp, F fun, Ts&&... xs) { actor_config cfg{context()}; auto first = &grp; return eval_opts(Os, system().spawn_fun_in_groups<make_unbound(Os)>( cfg, first, first + 1, fun, std::forward<Ts>(xs)...)); } // -- sending asynchronous messages ------------------------------------------ /// Sends an exit message to `dest`. void send_exit(const actor_addr& whom, error reason); void send_exit(const strong_actor_ptr& dest, error reason); /// Sends an exit message to `dest`. template <class ActorHandle> void send_exit(const ActorHandle& dest, error reason) { if (dest) dest->eq_impl(make_message_id(), ctrl(), context(), exit_msg{address(), std::move(reason)}); } // -- miscellaneous actor operations ----------------------------------------- /// Returns the execution unit currently used by this actor. inline execution_unit* context() const { return context_; } /// Sets the execution unit for this actor. inline void context(execution_unit* x) { context_ = x; } /// Returns the hosting actor system. inline actor_system& system() const { CAF_ASSERT(context_); return context_->system(); } /// Returns the config of the hosting actor system. inline const actor_system_config& config() const { return system().config(); } /// Returns the clock of the actor system. inline actor_clock& clock() const { return home_system().clock(); } /// @cond PRIVATE void monitor(abstract_actor* ptr); /// @endcond /// Returns a pointer to the sender of the current message. /// @pre `current_mailbox_element() != nullptr` inline strong_actor_ptr& current_sender() { CAF_ASSERT(current_element_); return current_element_->sender; } /// Returns the ID of the current message. inline message_id current_message_id() { CAF_ASSERT(current_element_); return current_element_->mid; } /// Returns the ID of the current message and marks the ID stored in the /// current mailbox element as answered. inline message_id take_current_message_id() { CAF_ASSERT(current_element_); auto result = current_element_->mid; current_element_->mid.mark_as_answered(); return result; } /// Marks the current message ID as answered. inline void drop_current_message_id() { CAF_ASSERT(current_element_); current_element_->mid.mark_as_answered(); } /// Returns a pointer to the next stage from the forwarding path of the /// current message or `nullptr` if the path is empty. inline strong_actor_ptr current_next_stage() { CAF_ASSERT(current_element_); auto& stages = current_element_->stages; if (!stages.empty()) stages.back(); return nullptr; } /// Returns a pointer to the next stage from the forwarding path of the /// current message and removes it from the path. Returns `nullptr` if the /// path is empty. inline strong_actor_ptr take_current_next_stage() { CAF_ASSERT(current_element_); auto& stages = current_element_->stages; if (!stages.empty()) { auto result = stages.back(); stages.pop_back(); return result; } return nullptr; } /// Returns the forwarding stack from the current mailbox element. const mailbox_element::forwarding_stack& current_forwarding_stack() { CAF_ASSERT(current_element_); return current_element_->stages; } /// Moves the forwarding stack from the current mailbox element. mailbox_element::forwarding_stack take_current_forwarding_stack() { CAF_ASSERT(current_element_); return std::move(current_element_->stages); } /// Returns a pointer to the currently processed mailbox element. inline mailbox_element* current_mailbox_element() { return current_element_; } /// Returns a pointer to the currently processed mailbox element. /// @private inline void current_mailbox_element(mailbox_element* ptr) { current_element_ = ptr; } /// Adds a unidirectional `monitor` to `whom`. /// @note Each call to `monitor` creates a new, independent monitor. template <class Handle> void monitor(const Handle& whom) { monitor(actor_cast<abstract_actor*>(whom)); } /// Removes a monitor from `whom`. void demonitor(const actor_addr& whom); /// Removes a monitor from `whom`. inline void demonitor(const actor& whom) { demonitor(whom.address()); } /// Can be overridden to perform cleanup code after an actor /// finished execution. virtual void on_exit(); /// Creates a `typed_response_promise` to respond to a request later on. /// `make_response_promise<typed_response_promise<int, int>>()` /// is equivalent to `make_response_promise<int, int>()`. template <class... Ts> typename detail::make_response_promise_helper<Ts...>::type make_response_promise() { if (current_element_ == nullptr || current_element_->mid.is_answered()) return {}; return {this->ctrl(), *current_element_}; } /// Creates a `response_promise` to respond to a request later on. inline response_promise make_response_promise() { return make_response_promise<response_promise>(); } /// Creates a `typed_response_promise` and responds immediately. /// Return type is deduced from arguments. /// Return value is implicitly convertible to untyped response promise. template <class... Ts, class R = typename detail::make_response_promise_helper< typename std::decay<Ts>::type... >::type> R response(Ts&&... xs) { auto promise = make_response_promise<R>(); promise.deliver(std::forward<Ts>(xs)...); return promise; } const char* name() const override; /// Serializes the state of this actor to `sink`. This function is /// only called if this actor has set the `is_serializable` flag. /// The default implementation throws a `std::logic_error`. virtual error save_state(serializer& sink, unsigned int version); /// Deserializes the state of this actor from `source`. This function is /// only called if this actor has set the `is_serializable` flag. /// The default implementation throws a `std::logic_error`. virtual error load_state(deserializer& source, unsigned int version); /// Returns the currently defined fail state. If this reason is not /// `none` then the actor will terminate with this error after executing /// the current message handler. inline const error& fail_state() const { return fail_state_; } // -- here be dragons: end of public interface ------------------------------- /// @cond PRIVATE template <class ActorHandle> inline ActorHandle eval_opts(spawn_options opts, ActorHandle res) { if (has_monitor_flag(opts)) monitor(res->address()); if (has_link_flag(opts)) link_to(res->address()); return res; } // returns 0 if last_dequeued() is an asynchronous or sync request message, // a response id generated from the request id otherwise inline message_id get_response_id() const { auto mid = current_element_->mid; return (mid.is_request()) ? mid.response_id() : message_id(); } template <message_priority P = message_priority::normal, class Handle = actor, class... Ts> typename response_type< typename Handle::signatures, detail::implicit_conversions_t<typename std::decay<Ts>::type>... >::delegated_type delegate(const Handle& dest, Ts&&... xs) { static_assert(sizeof...(Ts) > 0, "nothing to delegate"); using token = detail::type_list< typename detail::implicit_conversions< typename std::decay<Ts>::type >::type...>; static_assert(response_type_unbox<signatures_of_t<Handle>, token>::valid, "receiver does not accept given message"); auto mid = current_element_->mid; current_element_->mid = P == message_priority::high ? mid.with_high_priority() : mid.with_normal_priority(); dest->enqueue(make_mailbox_element(std::move(current_element_->sender), mid, std::move(current_element_->stages), std::forward<Ts>(xs)...), context()); return {}; } virtual void initialize(); bool cleanup(error&& fail_state, execution_unit* host) override; message_id new_request_id(message_priority mp); protected: // -- member variables ------------------------------------------------------- // identifies the execution unit this actor is currently executed by execution_unit* context_; // pointer to the sender of the currently processed message mailbox_element* current_element_; // last used request ID message_id last_request_id_; /// Factory function for returning initial behavior in function-based actors. std::function<behavior (local_actor*)> initial_behavior_fac_; }; } // namespace caf
/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2018 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #pragma once #include <atomic> #include <cstdint> #include <exception> #include <functional> #include <type_traits> #include <utility> #include "caf/abstract_actor.hpp" #include "caf/abstract_group.hpp" #include "caf/actor.hpp" #include "caf/actor_cast.hpp" #include "caf/actor_config.hpp" #include "caf/actor_system.hpp" #include "caf/behavior.hpp" #include "caf/check_typed_input.hpp" #include "caf/delegated.hpp" #include "caf/duration.hpp" #include "caf/error.hpp" #include "caf/fwd.hpp" #include "caf/message.hpp" #include "caf/message_handler.hpp" #include "caf/message_id.hpp" #include "caf/message_priority.hpp" #include "caf/monitorable_actor.hpp" #include "caf/response_promise.hpp" #include "caf/response_type.hpp" #include "caf/resumable.hpp" #include "caf/spawn_options.hpp" #include "caf/typed_actor.hpp" #include "caf/typed_response_promise.hpp" #include "caf/detail/typed_actor_util.hpp" namespace caf { /// Base class for actors running on this node, either /// living in an own thread or cooperatively scheduled. class local_actor : public monitorable_actor { public: // -- member types ----------------------------------------------------------- /// Defines a monotonic clock suitable for measuring intervals. using clock_type = std::chrono::steady_clock; // -- constructors, destructors, and assignment operators -------------------- local_actor(actor_config& cfg); ~local_actor() override; void on_destroy() override; // -- pure virtual modifiers ------------------------------------------------- virtual void launch(execution_unit* eu, bool lazy, bool hide) = 0; // -- time ------------------------------------------------------------------- /// Returns the current time. clock_type::time_point now() const noexcept; /// Returns the difference between `t0` and `t1`, allowing the clock to /// return any arbitrary value depending on the measurement that took place. clock_type::duration difference(atom_value measurement, clock_type::time_point t0, clock_type::time_point t1); // -- timeout management ----------------------------------------------------- /// Requests a new timeout for `mid`. /// @pre `mid.valid()` void request_response_timeout(const duration& d, message_id mid); // -- spawn functions -------------------------------------------------------- template <class T, spawn_options Os = no_spawn_options, class... Ts> infer_handle_from_class_t<T> spawn(Ts&&... xs) { actor_config cfg{context()}; return eval_opts(Os, system().spawn_class<T, make_unbound(Os)>( cfg, std::forward<Ts>(xs)...)); } template <class T, spawn_options Os = no_spawn_options> infer_handle_from_state_t<T> spawn() { using impl = composable_behavior_based_actor<T>; actor_config cfg{context()}; return eval_opts(Os, system().spawn_class<impl, make_unbound(Os)>(cfg)); } template <spawn_options Os = no_spawn_options, class F, class... Ts> infer_handle_from_fun_t<F> spawn(F fun, Ts&&... xs) { actor_config cfg{context()}; return eval_opts(Os, system().spawn_functor<make_unbound(Os)>( cfg, fun, std::forward<Ts>(xs)...)); } template <class T, spawn_options Os = no_spawn_options, class Groups, class... Ts> actor spawn_in_groups(const Groups& gs, Ts&&... xs) { actor_config cfg{context()}; return eval_opts(Os, system().spawn_class_in_groups<T, make_unbound(Os)>( cfg, gs.begin(), gs.end(), std::forward<Ts>(xs)...)); } template <class T, spawn_options Os = no_spawn_options, class... Ts> actor spawn_in_groups(std::initializer_list<group> gs, Ts&&... xs) { actor_config cfg{context()}; return eval_opts(Os, system().spawn_class_in_groups<T, make_unbound(Os)>( cfg, gs.begin(), gs.end(), std::forward<Ts>(xs)...)); } template <class T, spawn_options Os = no_spawn_options, class... Ts> actor spawn_in_group(const group& grp, Ts&&... xs) { actor_config cfg{context()}; auto first = &grp; return eval_opts(Os, system().spawn_class_in_groups<T, make_unbound(Os)>( cfg, first, first + 1, std::forward<Ts>(xs)...)); } template <spawn_options Os = no_spawn_options, class Groups, class F, class... Ts> actor spawn_in_groups(const Groups& gs, F fun, Ts&&... xs) { actor_config cfg{context()}; return eval_opts( Os, system().spawn_fun_in_groups<make_unbound(Os)>( cfg, gs.begin(), gs.end(), fun, std::forward<Ts>(xs)...)); } template <spawn_options Os = no_spawn_options, class F, class... Ts> actor spawn_in_groups(std::initializer_list<group> gs, F fun, Ts&&... xs) { actor_config cfg{context()}; return eval_opts( Os, system().spawn_fun_in_groups<make_unbound(Os)>( cfg, gs.begin(), gs.end(), fun, std::forward<Ts>(xs)...)); } template <spawn_options Os = no_spawn_options, class F, class... Ts> actor spawn_in_group(const group& grp, F fun, Ts&&... xs) { actor_config cfg{context()}; auto first = &grp; return eval_opts(Os, system().spawn_fun_in_groups<make_unbound(Os)>( cfg, first, first + 1, fun, std::forward<Ts>(xs)...)); } // -- sending asynchronous messages ------------------------------------------ /// Sends an exit message to `dest`. void send_exit(const actor_addr& whom, error reason); void send_exit(const strong_actor_ptr& dest, error reason); /// Sends an exit message to `dest`. template <class ActorHandle> void send_exit(const ActorHandle& dest, error reason) { if (dest) dest->eq_impl(make_message_id(), ctrl(), context(), exit_msg{address(), std::move(reason)}); } // -- miscellaneous actor operations ----------------------------------------- /// Returns the execution unit currently used by this actor. inline execution_unit* context() const { return context_; } /// Sets the execution unit for this actor. inline void context(execution_unit* x) { context_ = x; } /// Returns the hosting actor system. inline actor_system& system() const { CAF_ASSERT(context_); return context_->system(); } /// Returns the config of the hosting actor system. inline const actor_system_config& config() const { return system().config(); } /// Returns the clock of the actor system. inline actor_clock& clock() const { return home_system().clock(); } /// @cond PRIVATE void monitor(abstract_actor* ptr); /// @endcond /// Returns a pointer to the sender of the current message. /// @pre `current_mailbox_element() != nullptr` inline strong_actor_ptr& current_sender() { CAF_ASSERT(current_element_); return current_element_->sender; } /// Returns the ID of the current message. inline message_id current_message_id() { CAF_ASSERT(current_element_); return current_element_->mid; } /// Returns the ID of the current message and marks the ID stored in the /// current mailbox element as answered. inline message_id take_current_message_id() { CAF_ASSERT(current_element_); auto result = current_element_->mid; current_element_->mid.mark_as_answered(); return result; } /// Marks the current message ID as answered. inline void drop_current_message_id() { CAF_ASSERT(current_element_); current_element_->mid.mark_as_answered(); } /// Returns a pointer to the next stage from the forwarding path of the /// current message or `nullptr` if the path is empty. inline strong_actor_ptr current_next_stage() { CAF_ASSERT(current_element_); auto& stages = current_element_->stages; if (!stages.empty()) return stages.back(); return nullptr; } /// Returns a pointer to the next stage from the forwarding path of the /// current message and removes it from the path. Returns `nullptr` if the /// path is empty. inline strong_actor_ptr take_current_next_stage() { CAF_ASSERT(current_element_); auto& stages = current_element_->stages; if (!stages.empty()) { auto result = stages.back(); stages.pop_back(); return result; } return nullptr; } /// Returns the forwarding stack from the current mailbox element. const mailbox_element::forwarding_stack& current_forwarding_stack() { CAF_ASSERT(current_element_); return current_element_->stages; } /// Moves the forwarding stack from the current mailbox element. mailbox_element::forwarding_stack take_current_forwarding_stack() { CAF_ASSERT(current_element_); return std::move(current_element_->stages); } /// Returns a pointer to the currently processed mailbox element. inline mailbox_element* current_mailbox_element() { return current_element_; } /// Returns a pointer to the currently processed mailbox element. /// @private inline void current_mailbox_element(mailbox_element* ptr) { current_element_ = ptr; } /// Adds a unidirectional `monitor` to `whom`. /// @note Each call to `monitor` creates a new, independent monitor. template <class Handle> void monitor(const Handle& whom) { monitor(actor_cast<abstract_actor*>(whom)); } /// Removes a monitor from `whom`. void demonitor(const actor_addr& whom); /// Removes a monitor from `whom`. inline void demonitor(const actor& whom) { demonitor(whom.address()); } /// Can be overridden to perform cleanup code after an actor /// finished execution. virtual void on_exit(); /// Creates a `typed_response_promise` to respond to a request later on. /// `make_response_promise<typed_response_promise<int, int>>()` /// is equivalent to `make_response_promise<int, int>()`. template <class... Ts> typename detail::make_response_promise_helper<Ts...>::type make_response_promise() { if (current_element_ == nullptr || current_element_->mid.is_answered()) return {}; return {this->ctrl(), *current_element_}; } /// Creates a `response_promise` to respond to a request later on. inline response_promise make_response_promise() { return make_response_promise<response_promise>(); } /// Creates a `typed_response_promise` and responds immediately. /// Return type is deduced from arguments. /// Return value is implicitly convertible to untyped response promise. template <class... Ts, class R = typename detail::make_response_promise_helper< typename std::decay<Ts>::type... >::type> R response(Ts&&... xs) { auto promise = make_response_promise<R>(); promise.deliver(std::forward<Ts>(xs)...); return promise; } const char* name() const override; /// Serializes the state of this actor to `sink`. This function is /// only called if this actor has set the `is_serializable` flag. /// The default implementation throws a `std::logic_error`. virtual error save_state(serializer& sink, unsigned int version); /// Deserializes the state of this actor from `source`. This function is /// only called if this actor has set the `is_serializable` flag. /// The default implementation throws a `std::logic_error`. virtual error load_state(deserializer& source, unsigned int version); /// Returns the currently defined fail state. If this reason is not /// `none` then the actor will terminate with this error after executing /// the current message handler. inline const error& fail_state() const { return fail_state_; } // -- here be dragons: end of public interface ------------------------------- /// @cond PRIVATE template <class ActorHandle> inline ActorHandle eval_opts(spawn_options opts, ActorHandle res) { if (has_monitor_flag(opts)) monitor(res->address()); if (has_link_flag(opts)) link_to(res->address()); return res; } // returns 0 if last_dequeued() is an asynchronous or sync request message, // a response id generated from the request id otherwise inline message_id get_response_id() const { auto mid = current_element_->mid; return (mid.is_request()) ? mid.response_id() : message_id(); } template <message_priority P = message_priority::normal, class Handle = actor, class... Ts> typename response_type< typename Handle::signatures, detail::implicit_conversions_t<typename std::decay<Ts>::type>... >::delegated_type delegate(const Handle& dest, Ts&&... xs) { static_assert(sizeof...(Ts) > 0, "nothing to delegate"); using token = detail::type_list< typename detail::implicit_conversions< typename std::decay<Ts>::type >::type...>; static_assert(response_type_unbox<signatures_of_t<Handle>, token>::valid, "receiver does not accept given message"); auto mid = current_element_->mid; current_element_->mid = P == message_priority::high ? mid.with_high_priority() : mid.with_normal_priority(); dest->enqueue(make_mailbox_element(std::move(current_element_->sender), mid, std::move(current_element_->stages), std::forward<Ts>(xs)...), context()); return {}; } virtual void initialize(); bool cleanup(error&& fail_state, execution_unit* host) override; message_id new_request_id(message_priority mp); protected: // -- member variables ------------------------------------------------------- // identifies the execution unit this actor is currently executed by execution_unit* context_; // pointer to the sender of the currently processed message mailbox_element* current_element_; // last used request ID message_id last_request_id_; /// Factory function for returning initial behavior in function-based actors. std::function<behavior (local_actor*)> initial_behavior_fac_; }; } // namespace caf
Fix missing return
Fix missing return
C++
bsd-3-clause
DavadDi/actor-framework,DavadDi/actor-framework,DavadDi/actor-framework,actor-framework/actor-framework,actor-framework/actor-framework,DavadDi/actor-framework,actor-framework/actor-framework,actor-framework/actor-framework
dca3a9a3a96be64db4294501f5b222f751322381
sources/instruments/selectioninstrument.cpp
sources/instruments/selectioninstrument.cpp
/* * This source file is part of EasyPaint. * * Copyright (c) 2012 EasyPaint <https://github.com/Gr1N/EasyPaint> * * 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 "selectioninstrument.h" #include "../imagearea.h" #include "../undocommand.h" #include "math.h" #include <QtGui/QPainter> #include <QtGui/QApplication> #include <QtGui/QClipboard> SelectionInstrument::SelectionInstrument(QObject *parent) : AbstractSelection(parent) { } void SelectionInstrument::copyImage(ImageArea &imageArea) { if (mIsSelectionExists) { imageArea.setImage(mImageCopy); QClipboard *globalClipboard = QApplication::clipboard(); QImage copyImage; if(mIsImageSelected) { copyImage = mSelectedImage; } else { copyImage = imageArea.getImage()->copy(mTopLeftPoint.x(), mTopLeftPoint.y(), mWidth, mHeight); } globalClipboard->setImage(copyImage, QClipboard::Clipboard); } } void SelectionInstrument::cutImage(ImageArea &imageArea) { if (mIsSelectionExists) { copyImage(imageArea); makeUndoCommand(imageArea); if (/*mSelectedImage != mPasteImage || !*/mIsImageSelected) { imageArea.setImage(mImageCopy); } else { clearSelectionBackground(imageArea); } mTopLeftPoint = QPoint(0, 0); mBottomRightPoint = QPoint(0, 0); mImageCopy = *imageArea.getImage(); imageArea.update(); if (mIsImageSelected) { makeUndoCommand(imageArea); } mIsSelectionExists = false; imageArea.restoreCursor(); emit sendEnableCopyCutActions(false); } } void SelectionInstrument::pasteImage(ImageArea &imageArea) { QClipboard *globalClipboard = QApplication::clipboard(); if(mIsSelectionExists) { imageArea.setImage(mImageCopy); paint(imageArea); mImageCopy = *imageArea.getImage(); } makeUndoCommand(imageArea); mPasteImage = globalClipboard->image(); if (!mPasteImage.isNull()) { mSelectedImage = mPasteImage; mImageCopy = *imageArea.getImage(); mTopLeftPoint = QPoint(0, 0); mBottomRightPoint = QPoint(mPasteImage.width(), mPasteImage.height()); mHeight = mBottomRightPoint.y(); mWidth = mBottomRightPoint.x(); mIsImageSelected = mIsSelectionExists = true; paint(imageArea); drawBorder(imageArea); imageArea.restoreCursor(); emit sendEnableCopyCutActions(true); } } void SelectionInstrument::startSelection(ImageArea &imageArea) { } void SelectionInstrument::startResizing(ImageArea &imageArea) { if (!mIsImageSelected) { clearSelectionBackground(imageArea); } } void SelectionInstrument::startMoving(ImageArea &imageArea) { clearSelectionBackground(imageArea); } void SelectionInstrument::select(ImageArea &imageArea) { } void SelectionInstrument::resize(ImageArea &imageArea) { } void SelectionInstrument::move(ImageArea &imageArea) { } void SelectionInstrument::completeSelection(ImageArea &imageArea) { mSelectedImage = imageArea.getImage()->copy(mTopLeftPoint.x(), mTopLeftPoint.y(), mWidth, mHeight); emit sendEnableCopyCutActions(true); } void SelectionInstrument::completeResizing(ImageArea &imageArea) { mSelectedImage = imageArea.getImage()->copy(mTopLeftPoint.x(), mTopLeftPoint.y(), mWidth, mHeight); } void SelectionInstrument::completeMoving(ImageArea &imageArea) { } void SelectionInstrument::clearSelectionBackground(ImageArea &imageArea) { QPainter blankPainter(imageArea.getImage()); blankPainter.setPen(Qt::white); blankPainter.setBrush(QBrush(Qt::white)); blankPainter.setBackgroundMode(Qt::OpaqueMode); blankPainter.drawRect(QRect(mTopLeftPoint, mBottomRightPoint - QPoint(1, 1))); blankPainter.end(); mImageCopy = *imageArea.getImage(); } void SelectionInstrument::clear(ImageArea &imageArea) { mSelectedImage = QImage(); emit sendEnableCopyCutActions(false); } void SelectionInstrument::paint(ImageArea &imageArea, bool isSecondaryColor, bool additionalFlag) { if (mIsSelectionExists) { if(mTopLeftPoint != mBottomRightPoint) { QPainter painter(imageArea.getImage()); QRect source(0, 0, mSelectedImage.width(), mSelectedImage.height()); QRect target(mTopLeftPoint, mBottomRightPoint); painter.drawImage(target, mSelectedImage, source); painter.end(); } imageArea.setEdited(true); imageArea.update(); } }
/* * This source file is part of EasyPaint. * * Copyright (c) 2012 EasyPaint <https://github.com/Gr1N/EasyPaint> * * 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 "selectioninstrument.h" #include "../imagearea.h" #include "../undocommand.h" #include "math.h" #include <QtGui/QPainter> #include <QtGui/QApplication> #include <QtGui/QClipboard> SelectionInstrument::SelectionInstrument(QObject *parent) : AbstractSelection(parent) { } void SelectionInstrument::copyImage(ImageArea &imageArea) { if (mIsSelectionExists) { imageArea.setImage(mImageCopy); QClipboard *globalClipboard = QApplication::clipboard(); QImage copyImage; if(mIsImageSelected) { copyImage = mSelectedImage; } else { copyImage = imageArea.getImage()->copy(mTopLeftPoint.x(), mTopLeftPoint.y(), mWidth, mHeight); } globalClipboard->setImage(copyImage, QClipboard::Clipboard); } } void SelectionInstrument::cutImage(ImageArea &imageArea) { if (mIsSelectionExists) { copyImage(imageArea); if(mIsSelectionExists) { imageArea.setImage(mImageCopy); paint(imageArea); } makeUndoCommand(imageArea); if (/*mSelectedImage != mPasteImage || !*/mIsImageSelected) { imageArea.setImage(mImageCopy); } else { clearSelectionBackground(imageArea); } mTopLeftPoint = QPoint(0, 0); mBottomRightPoint = QPoint(0, 0); mImageCopy = *imageArea.getImage(); imageArea.update(); mIsSelectionExists = false; imageArea.restoreCursor(); emit sendEnableCopyCutActions(false); } } void SelectionInstrument::pasteImage(ImageArea &imageArea) { QClipboard *globalClipboard = QApplication::clipboard(); if(mIsSelectionExists) { imageArea.setImage(mImageCopy); paint(imageArea); mImageCopy = *imageArea.getImage(); } makeUndoCommand(imageArea); mPasteImage = globalClipboard->image(); if (!mPasteImage.isNull()) { mSelectedImage = mPasteImage; mImageCopy = *imageArea.getImage(); mTopLeftPoint = QPoint(0, 0); mBottomRightPoint = QPoint(mPasteImage.width(), mPasteImage.height()); mHeight = mBottomRightPoint.y(); mWidth = mBottomRightPoint.x(); mIsImageSelected = mIsSelectionExists = true; paint(imageArea); drawBorder(imageArea); imageArea.restoreCursor(); emit sendEnableCopyCutActions(true); } } void SelectionInstrument::startSelection(ImageArea &imageArea) { } void SelectionInstrument::startResizing(ImageArea &imageArea) { if (!mIsImageSelected) { clearSelectionBackground(imageArea); } } void SelectionInstrument::startMoving(ImageArea &imageArea) { clearSelectionBackground(imageArea); } void SelectionInstrument::select(ImageArea &imageArea) { } void SelectionInstrument::resize(ImageArea &imageArea) { } void SelectionInstrument::move(ImageArea &imageArea) { } void SelectionInstrument::completeSelection(ImageArea &imageArea) { mSelectedImage = imageArea.getImage()->copy(mTopLeftPoint.x(), mTopLeftPoint.y(), mWidth, mHeight); emit sendEnableCopyCutActions(true); } void SelectionInstrument::completeResizing(ImageArea &imageArea) { mSelectedImage = imageArea.getImage()->copy(mTopLeftPoint.x(), mTopLeftPoint.y(), mWidth, mHeight); } void SelectionInstrument::completeMoving(ImageArea &imageArea) { } void SelectionInstrument::clearSelectionBackground(ImageArea &imageArea) { QPainter blankPainter(imageArea.getImage()); blankPainter.setPen(Qt::white); blankPainter.setBrush(QBrush(Qt::white)); blankPainter.setBackgroundMode(Qt::OpaqueMode); blankPainter.drawRect(QRect(mTopLeftPoint, mBottomRightPoint - QPoint(1, 1))); blankPainter.end(); mImageCopy = *imageArea.getImage(); } void SelectionInstrument::clear(ImageArea &imageArea) { mSelectedImage = QImage(); emit sendEnableCopyCutActions(false); } void SelectionInstrument::paint(ImageArea &imageArea, bool isSecondaryColor, bool additionalFlag) { if (mIsSelectionExists) { if(mTopLeftPoint != mBottomRightPoint) { QPainter painter(imageArea.getImage()); QRect source(0, 0, mSelectedImage.width(), mSelectedImage.height()); QRect target(mTopLeftPoint, mBottomRightPoint); painter.drawImage(target, mSelectedImage, source); painter.end(); } imageArea.setEdited(true); imageArea.update(); } }
Fix cut selection undo history
Fix cut selection undo history
C++
mit
Gr1N/EasyPaint,Gr1N/EasyPaint,Gr1N/EasyPaint
9eb3d5def407f9898859889841133e5a48286c95
webrtc/modules/remote_bitrate_estimator/remote_estimator_proxy.cc
webrtc/modules/remote_bitrate_estimator/remote_estimator_proxy.cc
/* * Copyright (c) 2015 The WebRTC 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 in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/remote_bitrate_estimator/remote_estimator_proxy.h" #include "webrtc/base/checks.h" #include "webrtc/base/logging.h" #include "webrtc/system_wrappers/include/clock.h" #include "webrtc/modules/pacing/packet_router.h" #include "webrtc/modules/rtp_rtcp/source/rtcp_packet/transport_feedback.h" #include "webrtc/modules/rtp_rtcp/include/rtp_rtcp.h" namespace webrtc { // TODO(sprang): Tune these! const int RemoteEstimatorProxy::kDefaultProcessIntervalMs = 50; const int RemoteEstimatorProxy::kBackWindowMs = 500; RemoteEstimatorProxy::RemoteEstimatorProxy(Clock* clock, PacketRouter* packet_router) : clock_(clock), packet_router_(packet_router), last_process_time_ms_(-1), media_ssrc_(0), feedback_sequence_(0), window_start_seq_(-1) {} RemoteEstimatorProxy::~RemoteEstimatorProxy() {} void RemoteEstimatorProxy::IncomingPacketFeedbackVector( const std::vector<PacketInfo>& packet_feedback_vector) { rtc::CritScope cs(&lock_); for (PacketInfo info : packet_feedback_vector) OnPacketArrival(info.sequence_number, info.arrival_time_ms); } void RemoteEstimatorProxy::IncomingPacket(int64_t arrival_time_ms, size_t payload_size, const RTPHeader& header) { if (!header.extension.hasTransportSequenceNumber) { LOG(LS_WARNING) << "RemoteEstimatorProxy: Incoming packet " "is missing the transport sequence number extension!"; return; } rtc::CritScope cs(&lock_); media_ssrc_ = header.ssrc; OnPacketArrival(header.extension.transportSequenceNumber, arrival_time_ms); } bool RemoteEstimatorProxy::LatestEstimate(std::vector<unsigned int>* ssrcs, unsigned int* bitrate_bps) const { return false; } int64_t RemoteEstimatorProxy::TimeUntilNextProcess() { int64_t now = clock_->TimeInMilliseconds(); int64_t time_until_next = 0; if (last_process_time_ms_ != -1 && now - last_process_time_ms_ < kDefaultProcessIntervalMs) { time_until_next = (last_process_time_ms_ + kDefaultProcessIntervalMs - now); } return time_until_next; } void RemoteEstimatorProxy::Process() { if (TimeUntilNextProcess() > 0) return; last_process_time_ms_ = clock_->TimeInMilliseconds(); bool more_to_build = true; while (more_to_build) { rtcp::TransportFeedback feedback_packet; if (BuildFeedbackPacket(&feedback_packet)) { RTC_DCHECK(packet_router_ != nullptr); packet_router_->SendFeedback(&feedback_packet); } else { more_to_build = false; } } } void RemoteEstimatorProxy::OnPacketArrival(uint16_t sequence_number, int64_t arrival_time) { // TODO(holmer): We should handle a backwards wrap here if the first // sequence number was small and the new sequence number is large. The // SequenceNumberUnwrapper doesn't do this, so we should replace this with // calls to IsNewerSequenceNumber instead. int64_t seq = unwrapper_.Unwrap(sequence_number); if (seq > window_start_seq_ + 0xFFFF / 2) { LOG(LS_WARNING) << "Skipping this sequence number (" << sequence_number << ") since it likely is reordered, but the unwrapper" "failed to handle it. Feedback window starts at " << window_start_seq_ << "."; return; } if (packet_arrival_times_.lower_bound(window_start_seq_) == packet_arrival_times_.end()) { // Start new feedback packet, cull old packets. for (auto it = packet_arrival_times_.begin(); it != packet_arrival_times_.end() && it->first < seq && arrival_time - it->second >= kBackWindowMs;) { auto delete_it = it; ++it; packet_arrival_times_.erase(delete_it); } } if (window_start_seq_ == -1) { window_start_seq_ = sequence_number; } else if (seq < window_start_seq_) { window_start_seq_ = seq; } // We are only interested in the first time a packet is received. if (packet_arrival_times_.find(seq) != packet_arrival_times_.end()) return; packet_arrival_times_[seq] = arrival_time; } bool RemoteEstimatorProxy::BuildFeedbackPacket( rtcp::TransportFeedback* feedback_packet) { // window_start_seq_ is the first sequence number to include in the current // feedback packet. Some older may still be in the map, in case a reordering // happens and we need to retransmit them. rtc::CritScope cs(&lock_); auto it = packet_arrival_times_.lower_bound(window_start_seq_); if (it == packet_arrival_times_.end()) { // Feedback for all packets already sent. return false; } // TODO(sprang): Measure receive times in microseconds and remove the // conversions below. const int64_t first_sequence = it->first; feedback_packet->WithMediaSourceSsrc(media_ssrc_); // Base sequence is the expected next (window_start_seq_). This is known, but // we might not have actually received it, so the base time shall be the time // of the first received packet in the feedback. feedback_packet->WithBase(static_cast<uint16_t>(window_start_seq_ & 0xFFFF), it->second * 1000); feedback_packet->WithFeedbackSequenceNumber(feedback_sequence_++); for (; it != packet_arrival_times_.end(); ++it) { if (!feedback_packet->WithReceivedPacket( static_cast<uint16_t>(it->first & 0xFFFF), it->second * 1000)) { // If we can't even add the first seq to the feedback packet, we won't be // able to build it at all. RTC_CHECK_NE(first_sequence, it->first); // Could not add timestamp, feedback packet might be full. Return and // try again with a fresh packet. break; } // Note: Don't erase items from packet_arrival_times_ after sending, in case // they need to be re-sent after a reordering. Removal will be handled // by OnPacketArrival once packets are too old. window_start_seq_ = it->first + 1; } return true; } } // namespace webrtc
/* * Copyright (c) 2015 The WebRTC 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 in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/remote_bitrate_estimator/remote_estimator_proxy.h" #include <limits> #include "webrtc/base/checks.h" #include "webrtc/base/logging.h" #include "webrtc/system_wrappers/include/clock.h" #include "webrtc/modules/pacing/packet_router.h" #include "webrtc/modules/rtp_rtcp/source/rtcp_packet/transport_feedback.h" #include "webrtc/modules/rtp_rtcp/include/rtp_rtcp.h" namespace webrtc { // TODO(sprang): Tune these! const int RemoteEstimatorProxy::kDefaultProcessIntervalMs = 50; const int RemoteEstimatorProxy::kBackWindowMs = 500; // The maximum allowed value for a timestamp in milliseconds. This is lower // than the numerical limit since we often convert to microseconds. static constexpr int64_t kMaxTimeMs = std::numeric_limits<int64_t>::max() / 1000; RemoteEstimatorProxy::RemoteEstimatorProxy(Clock* clock, PacketRouter* packet_router) : clock_(clock), packet_router_(packet_router), last_process_time_ms_(-1), media_ssrc_(0), feedback_sequence_(0), window_start_seq_(-1) {} RemoteEstimatorProxy::~RemoteEstimatorProxy() {} void RemoteEstimatorProxy::IncomingPacketFeedbackVector( const std::vector<PacketInfo>& packet_feedback_vector) { rtc::CritScope cs(&lock_); for (PacketInfo info : packet_feedback_vector) OnPacketArrival(info.sequence_number, info.arrival_time_ms); } void RemoteEstimatorProxy::IncomingPacket(int64_t arrival_time_ms, size_t payload_size, const RTPHeader& header) { if (!header.extension.hasTransportSequenceNumber) { LOG(LS_WARNING) << "RemoteEstimatorProxy: Incoming packet " "is missing the transport sequence number extension!"; return; } rtc::CritScope cs(&lock_); media_ssrc_ = header.ssrc; OnPacketArrival(header.extension.transportSequenceNumber, arrival_time_ms); } bool RemoteEstimatorProxy::LatestEstimate(std::vector<unsigned int>* ssrcs, unsigned int* bitrate_bps) const { return false; } int64_t RemoteEstimatorProxy::TimeUntilNextProcess() { int64_t now = clock_->TimeInMilliseconds(); int64_t time_until_next = 0; if (last_process_time_ms_ != -1 && now - last_process_time_ms_ < kDefaultProcessIntervalMs) { time_until_next = (last_process_time_ms_ + kDefaultProcessIntervalMs - now); } return time_until_next; } void RemoteEstimatorProxy::Process() { if (TimeUntilNextProcess() > 0) return; last_process_time_ms_ = clock_->TimeInMilliseconds(); bool more_to_build = true; while (more_to_build) { rtcp::TransportFeedback feedback_packet; if (BuildFeedbackPacket(&feedback_packet)) { RTC_DCHECK(packet_router_ != nullptr); packet_router_->SendFeedback(&feedback_packet); } else { more_to_build = false; } } } void RemoteEstimatorProxy::OnPacketArrival(uint16_t sequence_number, int64_t arrival_time) { if (arrival_time < 0 || arrival_time > kMaxTimeMs) { LOG(LS_WARNING) << "Arrival time out of bounds: " << arrival_time; return; } // TODO(holmer): We should handle a backwards wrap here if the first // sequence number was small and the new sequence number is large. The // SequenceNumberUnwrapper doesn't do this, so we should replace this with // calls to IsNewerSequenceNumber instead. int64_t seq = unwrapper_.Unwrap(sequence_number); if (seq > window_start_seq_ + 0xFFFF / 2) { LOG(LS_WARNING) << "Skipping this sequence number (" << sequence_number << ") since it likely is reordered, but the unwrapper" "failed to handle it. Feedback window starts at " << window_start_seq_ << "."; return; } if (packet_arrival_times_.lower_bound(window_start_seq_) == packet_arrival_times_.end()) { // Start new feedback packet, cull old packets. for (auto it = packet_arrival_times_.begin(); it != packet_arrival_times_.end() && it->first < seq && arrival_time - it->second >= kBackWindowMs;) { auto delete_it = it; ++it; packet_arrival_times_.erase(delete_it); } } if (window_start_seq_ == -1) { window_start_seq_ = sequence_number; } else if (seq < window_start_seq_) { window_start_seq_ = seq; } // We are only interested in the first time a packet is received. if (packet_arrival_times_.find(seq) != packet_arrival_times_.end()) return; packet_arrival_times_[seq] = arrival_time; } bool RemoteEstimatorProxy::BuildFeedbackPacket( rtcp::TransportFeedback* feedback_packet) { // window_start_seq_ is the first sequence number to include in the current // feedback packet. Some older may still be in the map, in case a reordering // happens and we need to retransmit them. rtc::CritScope cs(&lock_); auto it = packet_arrival_times_.lower_bound(window_start_seq_); if (it == packet_arrival_times_.end()) { // Feedback for all packets already sent. return false; } // TODO(sprang): Measure receive times in microseconds and remove the // conversions below. const int64_t first_sequence = it->first; feedback_packet->WithMediaSourceSsrc(media_ssrc_); // Base sequence is the expected next (window_start_seq_). This is known, but // we might not have actually received it, so the base time shall be the time // of the first received packet in the feedback. feedback_packet->WithBase(static_cast<uint16_t>(window_start_seq_ & 0xFFFF), it->second * 1000); feedback_packet->WithFeedbackSequenceNumber(feedback_sequence_++); for (; it != packet_arrival_times_.end(); ++it) { if (!feedback_packet->WithReceivedPacket( static_cast<uint16_t>(it->first & 0xFFFF), it->second * 1000)) { // If we can't even add the first seq to the feedback packet, we won't be // able to build it at all. RTC_CHECK_NE(first_sequence, it->first); // Could not add timestamp, feedback packet might be full. Return and // try again with a fresh packet. break; } // Note: Don't erase items from packet_arrival_times_ after sending, in case // they need to be re-sent after a reordering. Removal will be handled // by OnPacketArrival once packets are too old. window_start_seq_ = it->first + 1; } return true; } } // namespace webrtc
Add sanity check for arrival timestamps.
Add sanity check for arrival timestamps. BUG=chromium:632614 Review-Url: https://codereview.webrtc.org/2195663002 Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#13600}
C++
bsd-3-clause
ShiftMediaProject/libilbc,TimothyGu/libilbc,ShiftMediaProject/libilbc,TimothyGu/libilbc,TimothyGu/libilbc,TimothyGu/libilbc,ShiftMediaProject/libilbc,TimothyGu/libilbc,ShiftMediaProject/libilbc,ShiftMediaProject/libilbc
96e344bf27d956291ccef96b574ff98d7a3ac8fb
You-Controller/internal/query_executor_builder_visitor.cpp
You-Controller/internal/query_executor_builder_visitor.cpp
//@author A0097630B #include "stdafx.h" #include "query_executor.h" #include "../exceptions/context_index_out_of_range_exception.h" #include "../result.h" #include "query_executor_builder_visitor.h" namespace You { namespace Controller { namespace Internal { using You::NLP::TaskField; using You::NLP::TaskPriority; using You::NLP::QUERY; using You::NLP::ADD_QUERY; using You::NLP::SHOW_QUERY; using You::NLP::EDIT_QUERY; using You::NLP::DELETE_QUERY; using You::NLP::UNDO_QUERY; QueryExecutorBuilderVisitor::QueryExecutorBuilderVisitor( const Controller::Context& context) : context(context) { } std::unique_ptr<QueryExecutor> QueryExecutorBuilderVisitor::build(const ADD_QUERY& query) { class AddTaskQueryExecutor : public QueryExecutor { public: explicit AddTaskQueryExecutor( std::unique_ptr<QueryEngine::Query>&& query) : QueryExecutor(std::move(query)) { } virtual ~AddTaskQueryExecutor() = default; protected: Result processResponse( const You::QueryEngine::Response& response) override { return ADD_RESULT { boost::get<Task>(response) }; } }; return std::unique_ptr<QueryExecutor>( new AddTaskQueryExecutor( QueryEngine::AddTask( query.description, query.deadline ? query.deadline.get() : Task::DEFAULT_DEADLINE, query.priority == TaskPriority::HIGH ? Task::Priority::HIGH : Task::Priority::NORMAL, Task::Dependencies(), Task::Subtasks() ) ) ); } std::unique_ptr<QueryExecutor> QueryExecutorBuilderVisitor::build(const SHOW_QUERY& query) { class ShowTaskQueryExecutor : public QueryExecutor { public: explicit ShowTaskQueryExecutor( std::unique_ptr<QueryEngine::Query>&& query) : QueryExecutor(std::move(query)) { } virtual ~ShowTaskQueryExecutor() = default; protected: Result processResponse( const You::QueryEngine::Response& response) override { return SHOW_RESULT { boost::get<TaskList>(response) }; } }; using You::QueryEngine::Filter; using You::QueryEngine::Comparator; Filter filter = Filter::anyTask(); Comparator comparator(Comparator::notSorted()); std::for_each(begin(query.predicates), end(query.predicates), [&filter](const SHOW_QUERY::FIELD_FILTER& field) { std::function<bool(const Task&)> currentFilter; switch (field.field) { case TaskField::DESCRIPTION: assert(boost::get<std::wstring>(&field.value)); currentFilter = buildComparator(&Task::getDescription, field.predicate, boost::get<std::wstring>(field.value)); break; case TaskField::DEADLINE: assert(boost::get<boost::posix_time::ptime>(&field.value)); currentFilter = buildComparator(&Task::getDeadline, field.predicate, boost::get<boost::posix_time::ptime>(field.value)); break; case TaskField::COMPLETE: assert(boost::get<bool>(&field.value)); currentFilter = buildComparator(&Task::isCompleted, field.predicate, boost::get<bool>(field.value)); break; case TaskField::PRIORITY: assert(boost::get<TaskPriority>(&field.value)); currentFilter = buildComparator(&Task::getPriority, field.predicate, Controller::nlpToQueryEnginePriority( boost::get<TaskPriority>(field.value))); break; default: assert(false); abort(); } filter = filter && Filter(currentFilter); }); std::for_each(begin(query.order), end(query.order), [&comparator](const SHOW_QUERY::FIELD_ORDER& field) { Comparator comp(Comparator::notSorted()); switch (field.field) { case TaskField::DESCRIPTION: comp = Comparator::byDescription(); break; case TaskField::DEADLINE: comp = Comparator::byDeadline(); break; case TaskField::PRIORITY: comp = Comparator::byPriority(); break; case TaskField::COMPLETE: default: assert(false); abort(); } if (field.order == SHOW_QUERY::Order::ASCENDING) { comp = comp.ascending(); } else { comp = comp.descending(); } comparator = comparator && comp; }); return std::unique_ptr<QueryExecutor>( new ShowTaskQueryExecutor( QueryEngine::GetTask(filter, comparator) ) ); } template<typename TValue> std::function<bool(const Task&)> QueryExecutorBuilderVisitor::buildComparator( TValue(QueryEngine::Task::*selector)() const, SHOW_QUERY::Predicate predicate, const TValue& value) { switch (predicate) { case SHOW_QUERY::Predicate::EQ: return std::bind(std::equal_to<TValue>(), std::bind(selector, std::placeholders::_1), value); case SHOW_QUERY::Predicate::NOT_EQ: return std::bind(std::not_equal_to<TValue>(), std::bind(selector, std::placeholders::_1), value); case SHOW_QUERY::Predicate::LESS_THAN: return std::bind(std::less<TValue>(), std::bind(selector, std::placeholders::_1), value); case SHOW_QUERY::Predicate::LESS_THAN_EQ: return std::bind(std::less_equal<TValue>(), std::bind(selector, std::placeholders::_1), value); case SHOW_QUERY::Predicate::GREATER_THAN: return std::bind(std::greater<TValue>(), std::bind(selector, std::placeholders::_1), value); case SHOW_QUERY::Predicate::GREATER_THAN_EQ: return std::bind(std::greater_equal<TValue>(), std::bind(selector, std::placeholders::_1), value); default: assert(false); abort(); } } std::unique_ptr<QueryExecutor> QueryExecutorBuilderVisitor::build(const EDIT_QUERY& query) const { class EditTaskQueryExecutor : public QueryExecutor { public: explicit EditTaskQueryExecutor( std::unique_ptr<QueryEngine::Query>&& query) : QueryExecutor(std::move(query)) { } virtual ~EditTaskQueryExecutor() = default; protected: Result processResponse( const You::QueryEngine::Response& response) override { return EDIT_RESULT { boost::get<Task>(response) }; } }; try { Task::ID task = context.at(query.taskID).getID(); You::Utils::Option<Task::Priority> priority; if (query.priority) { priority = Controller::nlpToQueryEnginePriority( query.priority.get()); } if (query.childTask) { assert(!query.description && !query.deadline && !priority && !query.complete && !query.dependingTask && query.attachments.empty() && "Cannot change subtasks with other properties"); int childTask = query.childTask; if (childTask < 0) { return std::unique_ptr<QueryExecutor>( new EditTaskQueryExecutor( QueryEngine::RemoveSubtask(task, context.at(-childTask).getID()))); } else { return std::unique_ptr<QueryExecutor>( new EditTaskQueryExecutor( QueryEngine::AddSubtask(task, context.at(childTask).getID()))); } } You::Utils::Option<Task::Dependencies> dependencies; if (query.dependingTask) { assert(!query.description && !query.deadline && !priority && !query.complete && !query.childTask && query.attachments.empty() && "Cannot change dependencies with other properties"); Task::ID dependentTask = task; int dependingTask = query.dependingTask; if (dependingTask < 0) { return std::unique_ptr<QueryExecutor>( new EditTaskQueryExecutor( QueryEngine::RemoveDependency( context.at(-dependingTask).getID(), dependentTask))); } else { return std::unique_ptr<QueryExecutor>( new EditTaskQueryExecutor( QueryEngine::AddDependency( context.at(dependingTask).getID(), dependentTask))); } } You::Utils::Option<Task::Attachment> attachment; if (!query.attachments.empty()) { assert(!query.description && !query.deadline && !priority && !query.complete && !query.childTask && !query.dependingTask && "Cannot modify attachments with other properties"); assert(query.attachments.size() == 1 && "Controller currently only supports modifying one attachment " "at a time"); if (query.attachments[0].add) { attachment = query.attachments[0].path; } } return std::unique_ptr<QueryExecutor>( new EditTaskQueryExecutor( QueryEngine::UpdateTask( task, query.description, query.deadline, priority, boost::none, query.complete, boost::none, boost::none))); } catch (std::out_of_range& e) { throw ContextIndexOutOfRangeException(e); } } std::unique_ptr<QueryExecutor> QueryExecutorBuilderVisitor::build(const DELETE_QUERY& query) const { class DeleteTaskQueryExecutor : public QueryExecutor { public: explicit DeleteTaskQueryExecutor( std::unique_ptr<QueryEngine::Query>&& query) : QueryExecutor(std::move(query)) { } virtual ~DeleteTaskQueryExecutor() = default; protected: Result processResponse( const You::QueryEngine::Response& response) override { return DELETE_RESULT { boost::get<Task::ID>(response) }; } }; try { const Task& task = context.at(query.taskID); return std::unique_ptr<QueryExecutor>( new DeleteTaskQueryExecutor( QueryEngine::DeleteTask( task.getID()))); } catch (std::out_of_range& e) { throw ContextIndexOutOfRangeException(e); } } std::unique_ptr<QueryExecutor> QueryExecutorBuilderVisitor::build(const UNDO_QUERY& /*query*/) const { class UndoTaskQueryExecutor : public QueryExecutor { public: explicit UndoTaskQueryExecutor( std::unique_ptr<QueryEngine::Query>&& query) : QueryExecutor(std::move(query)) { } virtual ~UndoTaskQueryExecutor() = default; protected: Result processResponse( const You::QueryEngine::Response& response) override { return UNDO_RESULT { boost::get<TaskList>(response) }; } }; return std::unique_ptr<QueryExecutor>( new UndoTaskQueryExecutor( QueryEngine::Undo())); } } // namespace Internal } // namespace Controller } // namespace You
//@author A0097630B #include "stdafx.h" #include "query_executor.h" #include "../exceptions/context_index_out_of_range_exception.h" #include "../result.h" #include "query_executor_builder_visitor.h" namespace You { namespace Controller { namespace Internal { using You::NLP::TaskField; using You::NLP::TaskPriority; using You::NLP::QUERY; using You::NLP::ADD_QUERY; using You::NLP::SHOW_QUERY; using You::NLP::EDIT_QUERY; using You::NLP::DELETE_QUERY; using You::NLP::UNDO_QUERY; QueryExecutorBuilderVisitor::QueryExecutorBuilderVisitor( const Controller::Context& context) : context(context) { } std::unique_ptr<QueryExecutor> QueryExecutorBuilderVisitor::build(const ADD_QUERY& query) { class AddTaskQueryExecutor : public QueryExecutor { public: explicit AddTaskQueryExecutor( std::unique_ptr<QueryEngine::Query>&& query) : QueryExecutor(std::move(query)) { } virtual ~AddTaskQueryExecutor() = default; protected: Result processResponse( const You::QueryEngine::Response& response) override { return ADD_RESULT { boost::get<Task>(response) }; } }; return std::unique_ptr<QueryExecutor>( new AddTaskQueryExecutor( QueryEngine::AddTask( query.description, query.deadline ? query.deadline.get() : Task::DEFAULT_DEADLINE, query.priority == TaskPriority::HIGH ? Task::Priority::HIGH : Task::Priority::NORMAL, Task::Dependencies(), Task::Subtasks() ) ) ); } std::unique_ptr<QueryExecutor> QueryExecutorBuilderVisitor::build(const SHOW_QUERY& query) { class ShowTaskQueryExecutor : public QueryExecutor { public: explicit ShowTaskQueryExecutor( std::unique_ptr<QueryEngine::Query>&& query) : QueryExecutor(std::move(query)) { } virtual ~ShowTaskQueryExecutor() = default; protected: Result processResponse( const You::QueryEngine::Response& response) override { return SHOW_RESULT { boost::get<TaskList>(response) }; } }; using You::QueryEngine::Filter; using You::QueryEngine::Comparator; Filter filter = Filter::anyTask(); Comparator comparator(Comparator::notSorted()); std::for_each(begin(query.predicates), end(query.predicates), [&filter](const SHOW_QUERY::FIELD_FILTER& field) { std::function<bool(const Task&)> currentFilter; switch (field.field) { case TaskField::DESCRIPTION: assert(boost::get<std::wstring>(&field.value)); currentFilter = buildComparator(&Task::getDescription, field.predicate, boost::get<std::wstring>(field.value)); break; case TaskField::DEADLINE: assert(boost::get<boost::posix_time::ptime>(&field.value)); currentFilter = buildComparator(&Task::getDeadline, field.predicate, boost::get<boost::posix_time::ptime>(field.value)); break; case TaskField::COMPLETE: assert(boost::get<bool>(&field.value)); currentFilter = buildComparator(&Task::isCompleted, field.predicate, boost::get<bool>(field.value)); break; case TaskField::PRIORITY: assert(boost::get<TaskPriority>(&field.value)); currentFilter = buildComparator(&Task::getPriority, field.predicate, Controller::nlpToQueryEnginePriority( boost::get<TaskPriority>(field.value))); break; default: assert(false); abort(); } filter = filter && Filter(currentFilter); }); std::for_each(begin(query.order), end(query.order), [&comparator](const SHOW_QUERY::FIELD_ORDER& field) { Comparator comp(Comparator::notSorted()); switch (field.field) { case TaskField::DESCRIPTION: comp = Comparator::byDescription(); break; case TaskField::DEADLINE: comp = Comparator::byDeadline(); break; case TaskField::PRIORITY: comp = Comparator::byPriority(); break; case TaskField::COMPLETE: default: assert(false); abort(); } if (field.order == SHOW_QUERY::Order::ASCENDING) { comp = comp.ascending(); } else { comp = comp.descending(); } comparator = comparator && comp; }); return std::unique_ptr<QueryExecutor>( new ShowTaskQueryExecutor( QueryEngine::GetTask(filter, comparator) ) ); } template<typename TValue> std::function<bool(const Task&)> QueryExecutorBuilderVisitor::buildComparator( TValue(QueryEngine::Task::*selector)() const, SHOW_QUERY::Predicate predicate, const TValue& value) { switch (predicate) { case SHOW_QUERY::Predicate::EQ: return std::bind(std::equal_to<TValue>(), std::bind(selector, std::placeholders::_1), value); case SHOW_QUERY::Predicate::NOT_EQ: return std::bind(std::not_equal_to<TValue>(), std::bind(selector, std::placeholders::_1), value); case SHOW_QUERY::Predicate::LESS_THAN: return std::bind(std::less<TValue>(), std::bind(selector, std::placeholders::_1), value); case SHOW_QUERY::Predicate::LESS_THAN_EQ: return std::bind(std::less_equal<TValue>(), std::bind(selector, std::placeholders::_1), value); case SHOW_QUERY::Predicate::GREATER_THAN: return std::bind(std::greater<TValue>(), std::bind(selector, std::placeholders::_1), value); case SHOW_QUERY::Predicate::GREATER_THAN_EQ: return std::bind(std::greater_equal<TValue>(), std::bind(selector, std::placeholders::_1), value); default: assert(false); abort(); } } std::unique_ptr<QueryExecutor> QueryExecutorBuilderVisitor::build(const EDIT_QUERY& query) const { class EditTaskQueryExecutor : public QueryExecutor { public: explicit EditTaskQueryExecutor( std::unique_ptr<QueryEngine::Query>&& query) : QueryExecutor(std::move(query)) { } virtual ~EditTaskQueryExecutor() = default; protected: Result processResponse( const You::QueryEngine::Response& response) override { return EDIT_RESULT { boost::get<Task>(response) }; } }; try { Task::ID task = context.at(query.taskID).getID(); You::Utils::Option<Task::Priority> priority; if (query.priority) { priority = Controller::nlpToQueryEnginePriority( query.priority.get()); } if (query.childTask) { assert(!query.description && !query.deadline && !priority && !query.complete && !query.dependingTask && query.attachments.empty() && "Cannot change subtasks with other properties"); int childTask = query.childTask.get(); if (childTask < 0) { return std::unique_ptr<QueryExecutor>( new EditTaskQueryExecutor( QueryEngine::RemoveSubtask(task, context.at(-childTask).getID()))); } else { return std::unique_ptr<QueryExecutor>( new EditTaskQueryExecutor( QueryEngine::AddSubtask(task, context.at(childTask).getID()))); } } You::Utils::Option<Task::Dependencies> dependencies; if (query.dependingTask) { assert(!query.description && !query.deadline && !priority && !query.complete && !query.childTask && query.attachments.empty() && "Cannot change dependencies with other properties"); Task::ID dependentTask = task; int dependingTask = query.dependingTask.get(); if (dependingTask < 0) { return std::unique_ptr<QueryExecutor>( new EditTaskQueryExecutor( QueryEngine::RemoveDependency( context.at(-dependingTask).getID(), dependentTask))); } else { return std::unique_ptr<QueryExecutor>( new EditTaskQueryExecutor( QueryEngine::AddDependency( context.at(dependingTask).getID(), dependentTask))); } } You::Utils::Option<Task::Attachment> attachment; if (!query.attachments.empty()) { assert(!query.description && !query.deadline && !priority && !query.complete && !query.childTask && !query.dependingTask && "Cannot modify attachments with other properties"); assert(query.attachments.size() == 1 && "Controller currently only supports modifying one attachment " "at a time"); if (query.attachments[0].add) { attachment = query.attachments[0].path; } } return std::unique_ptr<QueryExecutor>( new EditTaskQueryExecutor( QueryEngine::UpdateTask( task, query.description, query.deadline, priority, boost::none, query.complete, boost::none, boost::none))); } catch (std::out_of_range& e) { throw ContextIndexOutOfRangeException(e); } } std::unique_ptr<QueryExecutor> QueryExecutorBuilderVisitor::build(const DELETE_QUERY& query) const { class DeleteTaskQueryExecutor : public QueryExecutor { public: explicit DeleteTaskQueryExecutor( std::unique_ptr<QueryEngine::Query>&& query) : QueryExecutor(std::move(query)) { } virtual ~DeleteTaskQueryExecutor() = default; protected: Result processResponse( const You::QueryEngine::Response& response) override { return DELETE_RESULT { boost::get<Task::ID>(response) }; } }; try { const Task& task = context.at(query.taskID); return std::unique_ptr<QueryExecutor>( new DeleteTaskQueryExecutor( QueryEngine::DeleteTask( task.getID()))); } catch (std::out_of_range& e) { throw ContextIndexOutOfRangeException(e); } } std::unique_ptr<QueryExecutor> QueryExecutorBuilderVisitor::build(const UNDO_QUERY& /*query*/) const { class UndoTaskQueryExecutor : public QueryExecutor { public: explicit UndoTaskQueryExecutor( std::unique_ptr<QueryEngine::Query>&& query) : QueryExecutor(std::move(query)) { } virtual ~UndoTaskQueryExecutor() = default; protected: Result processResponse( const You::QueryEngine::Response& response) override { return UNDO_RESULT { boost::get<TaskList>(response) }; } }; return std::unique_ptr<QueryExecutor>( new UndoTaskQueryExecutor( QueryEngine::Undo())); } } // namespace Internal } // namespace Controller } // namespace You
Fix #325.
Fix #325.
C++
mit
cs2103aug2014-w10-1c/main,cs2103aug2014-w10-1c/main
ea3eb7f3e1d9bbf60c8c7e1a68807427652a5406
video_engine/vie_remb.cc
video_engine/vie_remb.cc
/* * Copyright (c) 2012 The WebRTC 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 in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "video_engine/vie_remb.h" #include <algorithm> #include <cassert> #include "modules/rtp_rtcp/interface/rtp_rtcp.h" #include "modules/utility/interface/process_thread.h" #include "system_wrappers/interface/critical_section_wrapper.h" #include "system_wrappers/interface/tick_util.h" #include "system_wrappers/interface/trace.h" namespace webrtc { const int kRembTimeOutThresholdMs = 2000; const int kRembSendIntervallMs = 1000; const unsigned int kRembMinimumBitrateKbps = 50; // % threshold for if we should send a new REMB asap. const unsigned int kSendThresholdPercent = 97; VieRemb::VieRemb(ProcessThread* process_thread) : process_thread_(process_thread), list_crit_(CriticalSectionWrapper::CreateCriticalSection()), last_remb_time_(TickTime::MillisecondTimestamp()), last_send_bitrate_(0), bitrate_(0), bitrate_update_time_ms_(-1) { process_thread->RegisterModule(this); } VieRemb::~VieRemb() { process_thread_->DeRegisterModule(this); } void VieRemb::AddReceiveChannel(RtpRtcp* rtp_rtcp) { assert(rtp_rtcp); WEBRTC_TRACE(kTraceStateInfo, kTraceVideo, -1, "VieRemb::AddReceiveChannel(%p)", rtp_rtcp); CriticalSectionScoped cs(list_crit_.get()); if (std::find(receive_modules_.begin(), receive_modules_.end(), rtp_rtcp) != receive_modules_.end()) return; WEBRTC_TRACE(kTraceInfo, kTraceVideo, -1, "AddRembChannel"); // The module probably doesn't have a remote SSRC yet, so don't add it to the // map. receive_modules_.push_back(rtp_rtcp); } void VieRemb::RemoveReceiveChannel(RtpRtcp* rtp_rtcp) { assert(rtp_rtcp); WEBRTC_TRACE(kTraceStateInfo, kTraceVideo, -1, "VieRemb::RemoveReceiveChannel(%p)", rtp_rtcp); CriticalSectionScoped cs(list_crit_.get()); for (RtpModules::iterator it = receive_modules_.begin(); it != receive_modules_.end(); ++it) { if ((*it) == rtp_rtcp) { receive_modules_.erase(it); break; } } } void VieRemb::AddRembSender(RtpRtcp* rtp_rtcp) { assert(rtp_rtcp); WEBRTC_TRACE(kTraceStateInfo, kTraceVideo, -1, "VieRemb::AddRembSender(%p)", rtp_rtcp); CriticalSectionScoped cs(list_crit_.get()); // Verify this module hasn't been added earlier. if (std::find(rtcp_sender_.begin(), rtcp_sender_.end(), rtp_rtcp) != rtcp_sender_.end()) return; rtcp_sender_.push_back(rtp_rtcp); } void VieRemb::RemoveRembSender(RtpRtcp* rtp_rtcp) { assert(rtp_rtcp); WEBRTC_TRACE(kTraceStateInfo, kTraceVideo, -1, "VieRemb::RemoveRembSender(%p)", rtp_rtcp); CriticalSectionScoped cs(list_crit_.get()); for (RtpModules::iterator it = rtcp_sender_.begin(); it != rtcp_sender_.end(); ++it) { if ((*it) == rtp_rtcp) { rtcp_sender_.erase(it); return; } } } bool VieRemb::InUse() const { CriticalSectionScoped cs(list_crit_.get()); if (receive_modules_.empty() && rtcp_sender_.empty()) return false; else return true; } void VieRemb::OnReceiveBitrateChanged(std::vector<unsigned int>* ssrcs, unsigned int bitrate) { WEBRTC_TRACE(kTraceStream, kTraceVideo, -1, "VieRemb::UpdateBitrateEstimate(bitrate: %u)", bitrate); assert(ssrcs); CriticalSectionScoped cs(list_crit_.get()); // If we already have an estimate, check if the new total estimate is below // kSendThresholdPercent of the previous estimate. if (last_send_bitrate_ > 0) { unsigned int new_remb_bitrate = last_send_bitrate_ - bitrate_ + bitrate; if (new_remb_bitrate < kSendThresholdPercent * last_send_bitrate_ / 100) { // The new bitrate estimate is less than kSendThresholdPercent % of the // last report. Send a REMB asap. last_remb_time_ = TickTime::MillisecondTimestamp() - kRembSendIntervallMs; } } bitrate_ = bitrate; ssrcs_.resize(ssrcs->size()); std::copy(ssrcs->begin(), ssrcs->end(), ssrcs_.begin()); bitrate_update_time_ms_ = TickTime::MillisecondTimestamp(); } WebRtc_Word32 VieRemb::ChangeUniqueId(const WebRtc_Word32 id) { return 0; } WebRtc_Word32 VieRemb::TimeUntilNextProcess() { return kRembSendIntervallMs - (TickTime::MillisecondTimestamp() - last_remb_time_); } WebRtc_Word32 VieRemb::Process() { int64_t now = TickTime::MillisecondTimestamp(); if (now - last_remb_time_ < kRembSendIntervallMs) return 0; last_remb_time_ = now; // Calculate total receive bitrate estimate. list_crit_->Enter(); // Reset the estimate if it has timed out. if (TickTime::MillisecondTimestamp() - bitrate_update_time_ms_ > kRembTimeOutThresholdMs) { bitrate_ = 0; bitrate_update_time_ms_ = -1; } if (bitrate_update_time_ms_ == -1 || ssrcs_.empty()) { list_crit_->Leave(); return 0; } // Send a REMB packet. RtpRtcp* sender = NULL; if (!rtcp_sender_.empty()) { sender = rtcp_sender_.front(); } else { sender = receive_modules_.front(); } last_send_bitrate_ = bitrate_; // Never send a REMB lower than last_send_bitrate_. if (last_send_bitrate_ < kRembMinimumBitrateKbps) { last_send_bitrate_ = kRembMinimumBitrateKbps; } list_crit_->Leave(); if (sender) { // TODO(holmer): Change RTP module API to take a vector pointer. sender->SetREMBData(bitrate_, ssrcs_.size(), &ssrcs_[0]); } return 0; } } // namespace webrtc
/* * Copyright (c) 2012 The WebRTC 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 in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "video_engine/vie_remb.h" #include <algorithm> #include <cassert> #include "modules/rtp_rtcp/interface/rtp_rtcp.h" #include "modules/utility/interface/process_thread.h" #include "system_wrappers/interface/critical_section_wrapper.h" #include "system_wrappers/interface/tick_util.h" #include "system_wrappers/interface/trace.h" namespace webrtc { const int kRembTimeOutThresholdMs = 2000; const int kRembSendIntervallMs = 1000; const unsigned int kRembMinimumBitrateKbps = 50; // % threshold for if we should send a new REMB asap. const unsigned int kSendThresholdPercent = 97; VieRemb::VieRemb(ProcessThread* process_thread) : process_thread_(process_thread), list_crit_(CriticalSectionWrapper::CreateCriticalSection()), last_remb_time_(TickTime::MillisecondTimestamp()), last_send_bitrate_(0), bitrate_(0), bitrate_update_time_ms_(-1) { process_thread->RegisterModule(this); } VieRemb::~VieRemb() { process_thread_->DeRegisterModule(this); } void VieRemb::AddReceiveChannel(RtpRtcp* rtp_rtcp) { assert(rtp_rtcp); WEBRTC_TRACE(kTraceStateInfo, kTraceVideo, -1, "VieRemb::AddReceiveChannel(%p)", rtp_rtcp); CriticalSectionScoped cs(list_crit_.get()); if (std::find(receive_modules_.begin(), receive_modules_.end(), rtp_rtcp) != receive_modules_.end()) return; WEBRTC_TRACE(kTraceInfo, kTraceVideo, -1, "AddRembChannel"); // The module probably doesn't have a remote SSRC yet, so don't add it to the // map. receive_modules_.push_back(rtp_rtcp); } void VieRemb::RemoveReceiveChannel(RtpRtcp* rtp_rtcp) { assert(rtp_rtcp); WEBRTC_TRACE(kTraceStateInfo, kTraceVideo, -1, "VieRemb::RemoveReceiveChannel(%p)", rtp_rtcp); CriticalSectionScoped cs(list_crit_.get()); for (RtpModules::iterator it = receive_modules_.begin(); it != receive_modules_.end(); ++it) { if ((*it) == rtp_rtcp) { receive_modules_.erase(it); break; } } } void VieRemb::AddRembSender(RtpRtcp* rtp_rtcp) { assert(rtp_rtcp); WEBRTC_TRACE(kTraceStateInfo, kTraceVideo, -1, "VieRemb::AddRembSender(%p)", rtp_rtcp); CriticalSectionScoped cs(list_crit_.get()); // Verify this module hasn't been added earlier. if (std::find(rtcp_sender_.begin(), rtcp_sender_.end(), rtp_rtcp) != rtcp_sender_.end()) return; rtcp_sender_.push_back(rtp_rtcp); } void VieRemb::RemoveRembSender(RtpRtcp* rtp_rtcp) { assert(rtp_rtcp); WEBRTC_TRACE(kTraceStateInfo, kTraceVideo, -1, "VieRemb::RemoveRembSender(%p)", rtp_rtcp); CriticalSectionScoped cs(list_crit_.get()); for (RtpModules::iterator it = rtcp_sender_.begin(); it != rtcp_sender_.end(); ++it) { if ((*it) == rtp_rtcp) { rtcp_sender_.erase(it); return; } } } bool VieRemb::InUse() const { CriticalSectionScoped cs(list_crit_.get()); if (receive_modules_.empty() && rtcp_sender_.empty()) return false; else return true; } void VieRemb::OnReceiveBitrateChanged(std::vector<unsigned int>* ssrcs, unsigned int bitrate) { WEBRTC_TRACE(kTraceStream, kTraceVideo, -1, "VieRemb::UpdateBitrateEstimate(bitrate: %u)", bitrate); assert(ssrcs); CriticalSectionScoped cs(list_crit_.get()); // If we already have an estimate, check if the new total estimate is below // kSendThresholdPercent of the previous estimate. if (last_send_bitrate_ > 0) { unsigned int new_remb_bitrate = last_send_bitrate_ - bitrate_ + bitrate; if (new_remb_bitrate < kSendThresholdPercent * last_send_bitrate_ / 100) { // The new bitrate estimate is less than kSendThresholdPercent % of the // last report. Send a REMB asap. last_remb_time_ = TickTime::MillisecondTimestamp() - kRembSendIntervallMs; } } bitrate_ = bitrate; ssrcs_.resize(ssrcs->size()); std::copy(ssrcs->begin(), ssrcs->end(), ssrcs_.begin()); bitrate_update_time_ms_ = TickTime::MillisecondTimestamp(); } WebRtc_Word32 VieRemb::ChangeUniqueId(const WebRtc_Word32 id) { return 0; } WebRtc_Word32 VieRemb::TimeUntilNextProcess() { return kRembSendIntervallMs - (TickTime::MillisecondTimestamp() - last_remb_time_); } WebRtc_Word32 VieRemb::Process() { int64_t now = TickTime::MillisecondTimestamp(); if (now - last_remb_time_ < kRembSendIntervallMs) return 0; last_remb_time_ = now; // Calculate total receive bitrate estimate. list_crit_->Enter(); // Reset the estimate if it has timed out. if (TickTime::MillisecondTimestamp() - bitrate_update_time_ms_ > kRembTimeOutThresholdMs) { bitrate_ = 0; bitrate_update_time_ms_ = -1; } if (bitrate_update_time_ms_ == -1 || ssrcs_.empty() || receive_modules_.empty()) { list_crit_->Leave(); return 0; } // Send a REMB packet. RtpRtcp* sender = NULL; if (!rtcp_sender_.empty()) { sender = rtcp_sender_.front(); } else { sender = receive_modules_.front(); } last_send_bitrate_ = bitrate_; // Never send a REMB lower than last_send_bitrate_. if (last_send_bitrate_ < kRembMinimumBitrateKbps) { last_send_bitrate_ = kRembMinimumBitrateKbps; } // Copy SSRCs to avoid race conditions. int ssrcs_length = ssrcs_.size(); unsigned int* ssrcs = new unsigned int[ssrcs_length]; for (int i = 0; i < ssrcs_length; ++i) { ssrcs[i] = ssrcs_[i]; } list_crit_->Leave(); if (sender) { // TODO(holmer): Change RTP module API to take a vector pointer. sender->SetREMBData(bitrate_, ssrcs_length, ssrcs); } delete [] ssrcs; return 0; } } // namespace webrtc
Fix possible race condition and access into an empty list.
Fix possible race condition and access into an empty list. [email protected] BUG= Review URL: https://webrtc-codereview.appspot.com/939021 Cr-Mirrored-From: https://chromium.googlesource.com/external/webrtc Cr-Mirrored-Commit: 467dfe0e7c28c52f65af414474677f4b43f9dc10
C++
bsd-3-clause
sippet/webrtc,sippet/webrtc,sippet/webrtc,sippet/webrtc,sippet/webrtc,sippet/webrtc
a62125b7f77cec5afad98a9963f8966ae8739455
src/mlpack/core/tree/cover_tree/traits.hpp
src/mlpack/core/tree/cover_tree/traits.hpp
/** * @file traits.hpp * @author Ryan Curtin * * This file contains the specialization of the TreeTraits class for the * CoverTree type of tree. */ #ifndef __MLPACK_CORE_TREE_COVER_TREE_TRAITS_HPP #define __MLPACK_CORE_TREE_COVER_TREE_TRAITS_HPP #include <mlpack/core/tree/tree_traits.hpp> namespace mlpack { namespace tree { /** * The specialization of the TreeTraits class for the CoverTree tree type. It * defines characteristics of the cover tree, and is used to help write * tree-independent (but still optimized) tree-based algorithms. See * mlpack/core/tree/tree_traits.hpp for more information. */ template<typename MetricType, typename RootPointPolicy, typename StatisticType> class TreeTraits<CoverTree<MetricType, RootPointPolicy, StatisticType> > { public: /** * The cover tree (or, this implementation of it) does not require that * children represent non-overlapping subsets of the parent node. */ static const bool HasOverlappingChildren = true; /** * Each cover tree node contains only one point, and that point is its * centroid. */ static const bool FirstPointIsCentroid = true; /** * Cover trees do have self-children. */ static const bool HasSelfChildren = true; /** * Points are not rearranged when the tree is built. */ static const bool RearrangesDataset = false; }; }; // namespace tree }; // namespace mlpack #endif
/** * @file traits.hpp * @author Ryan Curtin * * This file contains the specialization of the TreeTraits class for the * CoverTree type of tree. */ #ifndef __MLPACK_CORE_TREE_COVER_TREE_TRAITS_HPP #define __MLPACK_CORE_TREE_COVER_TREE_TRAITS_HPP #include <mlpack/core/tree/tree_traits.hpp> namespace mlpack { namespace tree { /** * The specialization of the TreeTraits class for the CoverTree tree type. It * defines characteristics of the cover tree, and is used to help write * tree-independent (but still optimized) tree-based algorithms. See * mlpack/core/tree/tree_traits.hpp for more information. */ template<typename MetricType, typename RootPointPolicy, typename StatisticType, typename MatType> class TreeTraits<CoverTree<MetricType, RootPointPolicy, StatisticType, MatType>> { public: /** * The cover tree (or, this implementation of it) does not require that * children represent non-overlapping subsets of the parent node. */ static const bool HasOverlappingChildren = true; /** * Each cover tree node contains only one point, and that point is its * centroid. */ static const bool FirstPointIsCentroid = true; /** * Cover trees do have self-children. */ static const bool HasSelfChildren = true; /** * Points are not rearranged when the tree is built. */ static const bool RearrangesDataset = false; }; }; // namespace tree }; // namespace mlpack #endif
Make sure traits are active for all cover trees.
Make sure traits are active for all cover trees.
C++
bsd-3-clause
darcyliu/mlpack,BookChan/mlpack,Azizou/mlpack,BookChan/mlpack,minhpqn/mlpack,bmswgnp/mlpack,BookChan/mlpack,bmswgnp/mlpack,stereomatchingkiss/mlpack,chenmoshushi/mlpack,chenmoshushi/mlpack,ajjl/mlpack,lezorich/mlpack,erubboli/mlpack,minhpqn/mlpack,datachand/mlpack,datachand/mlpack,trungda/mlpack,lezorich/mlpack,Azizou/mlpack,minhpqn/mlpack,bmswgnp/mlpack,darcyliu/mlpack,stereomatchingkiss/mlpack,ersanliqiao/mlpack,theranger/mlpack,palashahuja/mlpack,lezorich/mlpack,erubboli/mlpack,ranjan1990/mlpack,thirdwing/mlpack,chenmoshushi/mlpack,trungda/mlpack,ajjl/mlpack,thirdwing/mlpack,ranjan1990/mlpack,ranjan1990/mlpack,palashahuja/mlpack,thirdwing/mlpack,Azizou/mlpack,palashahuja/mlpack,theranger/mlpack,ersanliqiao/mlpack,trungda/mlpack,darcyliu/mlpack,theranger/mlpack,ajjl/mlpack,ersanliqiao/mlpack,erubboli/mlpack,stereomatchingkiss/mlpack,datachand/mlpack
39c681eea8539d1cd0481202a3bb232e97fc370e
leetcode/longestpalindsub.cc
leetcode/longestpalindsub.cc
#include <iostream> #include <algorithm> using namespace std; string longestpalindsub(string &str) { const int n = str.size(); bool f[n][n]; fill_n(&f[0][0], n * n, false); int start = 0; int max_len = 1; for (int i = 0; i < n; ++i) { f[i][i] = true; for (int j = 0; j < i; ++j) { if (str[j] == str[i] && (f[j+1][i-1] || i == j+1)) { f[j][i] = true; if (max_len < i - j + 1) { start = j; max_len = i - j + 1; } } } } return str.substr(start, max_len); } int main() { string s = "zhangliuluhenggnehuluiltao"; cout << longestpalindsub(s) << endl; return 0; }
#include <iostream> #include <algorithm> using namespace std; string longestpalindsub(string &str) { const int n = str.size(); bool f[n][n]; fill_n(&f[0][0], n * n, false); int start = 0; int max_len = 1; for (int i = 0; i < n; ++i) { f[i][i] = true; for (int j = 0; j < i; ++j) { if (str[j] == str[i] && (f[j+1][i-1] || i == j+1)) { f[j][i] = true; if (max_len < i - j + 1) { start = j; max_len = i - j + 1; } } } } return str.substr(start, max_len); } int main() { string s = "liuliuluhenggnehuluilyuan"; cout << longestpalindsub(s) << endl; return 0; }
Update longestpalindsub.cc
Update longestpalindsub.cc
C++
mit
liuluheng/CTCI,liuluheng/CTCI,liuluheng/CTCI
6ae8bc657d8209ef456828425d5599aa028f77ed
src/Index/src/SimpleIndex.cpp
src/Index/src/SimpleIndex.cpp
// The MIT License (MIT) // Copyright (c) 2016, Microsoft // 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 <iostream> #include "BitFunnel/Configuration/Factories.h" #include "BitFunnel/Index/Factories.h" #include "BitFunnel/Index/Helpers.h" #include "BitFunnel/Index/IRecycler.h" #include "BitFunnel/Index/ISliceBufferAllocator.h" #include "BitFunnel/Index/Row.h" #include "LoggerInterfaces/Check.h" #include "SimpleIndex.h" namespace BitFunnel { //************************************************************************* // // Factory methods. // //************************************************************************* std::unique_ptr<ISimpleIndex> Factories::CreateSimpleIndex(IFileSystem& fileSystem) { return std::unique_ptr<ISimpleIndex>(new SimpleIndex(fileSystem)); } //************************************************************************* // // SimpleIndex // //************************************************************************* SimpleIndex::SimpleIndex(IFileSystem& fileSystem) : m_fileSystem(fileSystem), m_isStarted(false) { } SimpleIndex::~SimpleIndex() { StopIndex(); } // // Setter methods. // void SimpleIndex::SetConfiguration( std::unique_ptr<IConfiguration> config) { EnsureStarted(false); CHECK_EQ(m_configuration.get(), nullptr) << "Attempting to overwrite existing Configuration."; m_configuration = std::move(config); } void SimpleIndex::SetFactSet( std::unique_ptr<IFactSet> facts) { EnsureStarted(false); CHECK_EQ(m_facts.get(), nullptr) << "Attempting to overwrite existing FactSet."; m_facts = std::move(facts); } void SimpleIndex::SetFileManager( std::unique_ptr<IFileManager> fileManager) { EnsureStarted(false); CHECK_EQ(m_fileManager.get(), nullptr) << "Attempting to overwrite existing FileManager."; m_fileManager = std::move(fileManager); } //void SimpleIndex::SetFileSystem( // std::unique_ptr<IFileSystem> fileSystem) //{ // EnsureStarted(false); // CHECK_EQ(m_fileSystem.get(), nullptr) // << "Attempting to overwrite existing FileSystem."; // m_fileSystem = std::move(fileSystem); //} void SimpleIndex::SetIdfTable( std::unique_ptr<IIndexedIdfTable> idfTable) { EnsureStarted(false); CHECK_EQ(m_idfTable.get(), nullptr) << "Attempting to overwrite existing IndexIdfTable."; m_idfTable = std::move(idfTable); } void SimpleIndex::SetSchema( std::unique_ptr<IDocumentDataSchema> schema) { EnsureStarted(false); CHECK_EQ(m_schema.get(), nullptr) << "Attempting to overwrite existing DocumentDataSchema."; m_schema = std::move(schema); } void SimpleIndex::SetShardDefinition( std::unique_ptr<IShardDefinition> definition) { EnsureStarted(false); CHECK_EQ(m_shardDefinition.get(), nullptr) << "Attempting to overwrite existing ShardDefinition."; m_shardDefinition = std::move(definition); } void SimpleIndex::SetSliceBufferAllocator( std::unique_ptr<ISliceBufferAllocator> sliceAllocator) { EnsureStarted(false); CHECK_EQ(m_sliceAllocator.get(), nullptr) << "Attempting to overwrite existing ShardDefinition."; m_sliceAllocator = std::move(sliceAllocator); } void SimpleIndex::SetTermTableCollection( std::unique_ptr<ITermTableCollection> termTables) { EnsureStarted(false); CHECK_EQ(m_termTables.get(), nullptr) << "Attempting to overwrite existing TermTableCollection."; m_termTables = std::move(termTables); } // // Configuration methods. // void SimpleIndex::ConfigureForStatistics(char const * directory, size_t gramSize, bool generateTermToText) { EnsureStarted(false); //if (m_fileSystem.get() == nullptr) //{ // m_fileSystem = Factories::CreateFileSystem(); //} if (m_fileManager.get() == nullptr) { m_fileManager = Factories::CreateFileManager(directory, directory, directory, m_fileSystem); } // TODO: Load schema from file. if (m_schema.get() == nullptr) { m_schema = Factories::CreateDocumentDataSchema(); } // TODO: consider making this work if no ShardDefinition exists. if (m_shardDefinition.get() == nullptr) { auto input = m_fileManager->ShardDefinition().OpenForRead(); m_shardDefinition = Factories::CreateShardDefinition(*input); } if (m_termTables.get() == nullptr) { // When gathering corpus statistics, we don't yet have any // TermTables. For now just create a collection of default // initialized TermTables. m_termTables = Factories::CreateTermTableCollection( m_shardDefinition->GetShardCount()); } if (m_idfTable == nullptr) { // When we're building statistics we don't yet have an // IndexedIdfTable. Just use an empty one for now. This means // that terms that are created will all be marked with the // default IDF value. This is not a problem since the term // IDF values are not examined by the StatisticsBuild. They // exist primarily for the query pipeline where the TermTable // needs terms anotated with IDF values to handle the case // where the terms have an implicit, or adhoc mapping to // RowIds. m_idfTable = Factories::CreateIndexedIdfTable(); } if (m_facts.get() == nullptr) { m_facts = Factories::CreateFactSet(); } if (m_configuration.get() == nullptr) { m_configuration = Factories::CreateConfiguration(gramSize, generateTermToText, *m_idfTable, *m_facts); } } void SimpleIndex::ConfigureForServing(char const * directory, size_t gramSize, bool generateTermToText) { EnsureStarted(false); //if (m_fileSystem.get() == nullptr) //{ // m_fileSystem = Factories::CreateFileSystem(); //} if (m_fileManager.get() == nullptr) { m_fileManager = Factories::CreateFileManager(directory, directory, directory, m_fileSystem); } // TODO: Load schema from file. if (m_schema.get() == nullptr) { m_schema = Factories::CreateDocumentDataSchema(); } // TODO: Load shard definition from file. if (m_shardDefinition.get() == nullptr) { m_shardDefinition = Factories::CreateShardDefinition(); // The following shard-aware code causes problems when the // input file is missing. See issue 308. // https://github.com/BitFunnel/BitFunnel/issues/308 //auto input = m_fileManager->ShardDefinition().OpenForRead(); //m_shardDefinition = // Factories::CreateShardDefinition(*input); } if (m_termTables.get() == nullptr) { m_termTables = Factories::CreateTermTableCollection( *m_fileManager, m_shardDefinition->GetShardCount()); } if (m_idfTable == nullptr) { auto input = m_fileManager->IndexedIdfTable(0).OpenForRead(); Term::IdfX10 defaultIdf = 60; // TODO: use proper value here. m_idfTable = Factories::CreateIndexedIdfTable(*input, defaultIdf); } if (m_facts.get() == nullptr) { m_facts = Factories::CreateFactSet(); } if (m_configuration.get() == nullptr) { m_configuration = Factories::CreateConfiguration(gramSize, generateTermToText, *m_idfTable, *m_facts); } } void SimpleIndex::ConfigureAsMock(size_t gramSize, bool generateTermToText) { EnsureStarted(false); // TODO: Load schema from file. if (m_schema.get() == nullptr) { m_schema = Factories::CreateDocumentDataSchema(); } // TODO: Load shard definition from file. if (m_shardDefinition.get() == nullptr) { m_shardDefinition = Factories::CreateShardDefinition(); } if (m_termTables.get() == nullptr) { m_termTables = Factories::CreateTermTableCollection( m_shardDefinition->GetShardCount()); } if (m_idfTable == nullptr) { m_idfTable = Factories::CreateIndexedIdfTable(); } if (m_facts.get() == nullptr) { m_facts = Factories::CreateFactSet(); } if (m_configuration.get() == nullptr) { m_configuration = Factories::CreateConfiguration(gramSize, generateTermToText, *m_idfTable, *m_facts); } } void SimpleIndex::StartIndex() { EnsureStarted(false); if (m_sliceAllocator.get() == nullptr) { // TODO: Need a blockSize that works for all term tables. const ShardId tempId = 0; const size_t blockSize = 32 * GetReasonableBlockSize(*m_schema, m_termTables->GetTermTable(tempId)); // std::cout << "Blocksize: " << blockSize << std::endl; const size_t initialBlockCount = 512; m_sliceAllocator = Factories::CreateSliceBufferAllocator(blockSize, initialBlockCount); } if (m_recycler.get() == nullptr) { m_recycler = Factories::CreateRecycler(); m_recyclerThread = std::thread(RecyclerThreadEntryPoint, this); } m_ingestor = Factories::CreateIngestor(*m_schema, *m_recycler, *m_termTables, *m_shardDefinition, *m_sliceAllocator); m_isStarted = true; } void SimpleIndex::StopIndex() { // StopIndex() can be called even if the index hasn't been started. // If SimpleIndex::SimpleIndex() throws, ~SimpleIndex() will be // invoked which will call StopIndex(). // See issue 308. // https://github.com/BitFunnel/BitFunnel/issues/308 //EnsureStarted(true); if (m_recycler != nullptr) { m_recycler->Shutdown(); m_recyclerThread.join(); } } IConfiguration const & SimpleIndex::GetConfiguration() const { EnsureStarted(true); return *m_configuration; } IFileManager & SimpleIndex::GetFileManager() const { EnsureStarted(true); return *m_fileManager; } IFileSystem & SimpleIndex::GetFileSystem() const { EnsureStarted(true); return m_fileSystem; } IIngestor & SimpleIndex::GetIngestor() const { EnsureStarted(true); return *m_ingestor; } IRecycler & SimpleIndex::GetRecycler() const { EnsureStarted(true); return *m_recycler; } ITermTable const & SimpleIndex::GetTermTable0() const { return GetTermTable(0); } ITermTable const & SimpleIndex::GetTermTable(ShardId shardId) const { EnsureStarted(true); return m_termTables->GetTermTable(shardId); } void SimpleIndex::EnsureStarted(bool started) const { CHECK_EQ(started, m_isStarted) << (started ? "not allowed before starting index." : "not allowed after starting index."); } void SimpleIndex::RecyclerThreadEntryPoint(void * data) { SimpleIndex* index = reinterpret_cast<SimpleIndex*>(data); index->m_recycler->Run(); } }
// The MIT License (MIT) // Copyright (c) 2016, Microsoft // 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 <iostream> #include "BitFunnel/Configuration/Factories.h" #include "BitFunnel/Index/Factories.h" #include "BitFunnel/Index/Helpers.h" #include "BitFunnel/Index/IRecycler.h" #include "BitFunnel/Index/ISliceBufferAllocator.h" #include "BitFunnel/Index/Row.h" #include "LoggerInterfaces/Check.h" #include "SimpleIndex.h" namespace BitFunnel { //************************************************************************* // // Factory methods. // //************************************************************************* std::unique_ptr<ISimpleIndex> Factories::CreateSimpleIndex(IFileSystem& fileSystem) { return std::unique_ptr<ISimpleIndex>(new SimpleIndex(fileSystem)); } //************************************************************************* // // SimpleIndex // //************************************************************************* SimpleIndex::SimpleIndex(IFileSystem& fileSystem) : m_fileSystem(fileSystem), m_isStarted(false) { } SimpleIndex::~SimpleIndex() { StopIndex(); } // // Setter methods. // void SimpleIndex::SetConfiguration( std::unique_ptr<IConfiguration> config) { EnsureStarted(false); CHECK_EQ(m_configuration.get(), nullptr) << "Attempting to overwrite existing Configuration."; m_configuration = std::move(config); } void SimpleIndex::SetFactSet( std::unique_ptr<IFactSet> facts) { EnsureStarted(false); CHECK_EQ(m_facts.get(), nullptr) << "Attempting to overwrite existing FactSet."; m_facts = std::move(facts); } void SimpleIndex::SetFileManager( std::unique_ptr<IFileManager> fileManager) { EnsureStarted(false); CHECK_EQ(m_fileManager.get(), nullptr) << "Attempting to overwrite existing FileManager."; m_fileManager = std::move(fileManager); } //void SimpleIndex::SetFileSystem( // std::unique_ptr<IFileSystem> fileSystem) //{ // EnsureStarted(false); // CHECK_EQ(m_fileSystem.get(), nullptr) // << "Attempting to overwrite existing FileSystem."; // m_fileSystem = std::move(fileSystem); //} void SimpleIndex::SetIdfTable( std::unique_ptr<IIndexedIdfTable> idfTable) { EnsureStarted(false); CHECK_EQ(m_idfTable.get(), nullptr) << "Attempting to overwrite existing IndexIdfTable."; m_idfTable = std::move(idfTable); } void SimpleIndex::SetSchema( std::unique_ptr<IDocumentDataSchema> schema) { EnsureStarted(false); CHECK_EQ(m_schema.get(), nullptr) << "Attempting to overwrite existing DocumentDataSchema."; m_schema = std::move(schema); } void SimpleIndex::SetShardDefinition( std::unique_ptr<IShardDefinition> definition) { EnsureStarted(false); CHECK_EQ(m_shardDefinition.get(), nullptr) << "Attempting to overwrite existing ShardDefinition."; m_shardDefinition = std::move(definition); } void SimpleIndex::SetSliceBufferAllocator( std::unique_ptr<ISliceBufferAllocator> sliceAllocator) { EnsureStarted(false); CHECK_EQ(m_sliceAllocator.get(), nullptr) << "Attempting to overwrite existing ShardDefinition."; m_sliceAllocator = std::move(sliceAllocator); } void SimpleIndex::SetTermTableCollection( std::unique_ptr<ITermTableCollection> termTables) { EnsureStarted(false); CHECK_EQ(m_termTables.get(), nullptr) << "Attempting to overwrite existing TermTableCollection."; m_termTables = std::move(termTables); } // // Configuration methods. // void SimpleIndex::ConfigureForStatistics(char const * directory, size_t gramSize, bool generateTermToText) { EnsureStarted(false); //if (m_fileSystem.get() == nullptr) //{ // m_fileSystem = Factories::CreateFileSystem(); //} if (m_fileManager.get() == nullptr) { m_fileManager = Factories::CreateFileManager(directory, directory, directory, m_fileSystem); } // TODO: Load schema from file. if (m_schema.get() == nullptr) { m_schema = Factories::CreateDocumentDataSchema(); } // TODO: consider making this work if no ShardDefinition exists. if (m_shardDefinition.get() == nullptr) { auto input = m_fileManager->ShardDefinition().OpenForRead(); m_shardDefinition = Factories::CreateShardDefinition(*input); } if (m_termTables.get() == nullptr) { // When gathering corpus statistics, we don't yet have any // TermTables. For now just create a collection of default // initialized TermTables. m_termTables = Factories::CreateTermTableCollection( m_shardDefinition->GetShardCount()); } if (m_idfTable == nullptr) { // When we're building statistics we don't yet have an // IndexedIdfTable. Just use an empty one for now. This means // that terms that are created will all be marked with the // default IDF value. This is not a problem since the term // IDF values are not examined by the StatisticsBuild. They // exist primarily for the query pipeline where the TermTable // needs terms anotated with IDF values to handle the case // where the terms have an implicit, or adhoc mapping to // RowIds. m_idfTable = Factories::CreateIndexedIdfTable(); } if (m_facts.get() == nullptr) { m_facts = Factories::CreateFactSet(); } if (m_configuration.get() == nullptr) { m_configuration = Factories::CreateConfiguration(gramSize, generateTermToText, *m_idfTable, *m_facts); } } void SimpleIndex::ConfigureForServing(char const * directory, size_t gramSize, bool generateTermToText) { EnsureStarted(false); //if (m_fileSystem.get() == nullptr) //{ // m_fileSystem = Factories::CreateFileSystem(); //} if (m_fileManager.get() == nullptr) { m_fileManager = Factories::CreateFileManager(directory, directory, directory, m_fileSystem); } // TODO: Load schema from file. if (m_schema.get() == nullptr) { m_schema = Factories::CreateDocumentDataSchema(); } // TODO: Load shard definition from file. if (m_shardDefinition.get() == nullptr) { m_shardDefinition = Factories::CreateShardDefinition(); // The following shard-aware code causes problems when the // input file is missing. See issue 308. // https://github.com/BitFunnel/BitFunnel/issues/308 auto input = m_fileManager->ShardDefinition().OpenForRead(); m_shardDefinition = Factories::CreateShardDefinition(*input); } if (m_termTables.get() == nullptr) { m_termTables = Factories::CreateTermTableCollection( *m_fileManager, m_shardDefinition->GetShardCount()); } if (m_idfTable == nullptr) { auto input = m_fileManager->IndexedIdfTable(0).OpenForRead(); Term::IdfX10 defaultIdf = 60; // TODO: use proper value here. m_idfTable = Factories::CreateIndexedIdfTable(*input, defaultIdf); } if (m_facts.get() == nullptr) { m_facts = Factories::CreateFactSet(); } if (m_configuration.get() == nullptr) { m_configuration = Factories::CreateConfiguration(gramSize, generateTermToText, *m_idfTable, *m_facts); } } void SimpleIndex::ConfigureAsMock(size_t gramSize, bool generateTermToText) { EnsureStarted(false); // TODO: Load schema from file. if (m_schema.get() == nullptr) { m_schema = Factories::CreateDocumentDataSchema(); } // TODO: Load shard definition from file. if (m_shardDefinition.get() == nullptr) { m_shardDefinition = Factories::CreateShardDefinition(); } if (m_termTables.get() == nullptr) { m_termTables = Factories::CreateTermTableCollection( m_shardDefinition->GetShardCount()); } if (m_idfTable == nullptr) { m_idfTable = Factories::CreateIndexedIdfTable(); } if (m_facts.get() == nullptr) { m_facts = Factories::CreateFactSet(); } if (m_configuration.get() == nullptr) { m_configuration = Factories::CreateConfiguration(gramSize, generateTermToText, *m_idfTable, *m_facts); } } void SimpleIndex::StartIndex() { EnsureStarted(false); if (m_sliceAllocator.get() == nullptr) { // TODO: Need a blockSize that works for all term tables. const ShardId tempId = 0; const size_t blockSize = 32 * GetReasonableBlockSize(*m_schema, m_termTables->GetTermTable(tempId)); // std::cout << "Blocksize: " << blockSize << std::endl; const size_t initialBlockCount = 512; m_sliceAllocator = Factories::CreateSliceBufferAllocator(blockSize, initialBlockCount); } if (m_recycler.get() == nullptr) { m_recycler = Factories::CreateRecycler(); m_recyclerThread = std::thread(RecyclerThreadEntryPoint, this); } m_ingestor = Factories::CreateIngestor(*m_schema, *m_recycler, *m_termTables, *m_shardDefinition, *m_sliceAllocator); m_isStarted = true; } void SimpleIndex::StopIndex() { // StopIndex() can be called even if the index hasn't been started. // If SimpleIndex::SimpleIndex() throws, ~SimpleIndex() will be // invoked which will call StopIndex(). // See issue 308. // https://github.com/BitFunnel/BitFunnel/issues/308 //EnsureStarted(true); if (m_recycler != nullptr) { m_recycler->Shutdown(); m_recyclerThread.join(); } } IConfiguration const & SimpleIndex::GetConfiguration() const { EnsureStarted(true); return *m_configuration; } IFileManager & SimpleIndex::GetFileManager() const { EnsureStarted(true); return *m_fileManager; } IFileSystem & SimpleIndex::GetFileSystem() const { EnsureStarted(true); return m_fileSystem; } IIngestor & SimpleIndex::GetIngestor() const { EnsureStarted(true); return *m_ingestor; } IRecycler & SimpleIndex::GetRecycler() const { EnsureStarted(true); return *m_recycler; } ITermTable const & SimpleIndex::GetTermTable0() const { return GetTermTable(0); } ITermTable const & SimpleIndex::GetTermTable(ShardId shardId) const { EnsureStarted(true); return m_termTables->GetTermTable(shardId); } void SimpleIndex::EnsureStarted(bool started) const { CHECK_EQ(started, m_isStarted) << (started ? "not allowed before starting index." : "not allowed after starting index."); } void SimpleIndex::RecyclerThreadEntryPoint(void * data) { SimpleIndex* index = reinterpret_cast<SimpleIndex*>(data); index->m_recycler->Run(); } }
Use shardDefinition file in Ingestor.
Use shardDefinition file in Ingestor.
C++
mit
danluu/BitFunnel,BitFunnel/BitFunnel,danluu/BitFunnel,BitFunnel/BitFunnel,danluu/BitFunnel,BitFunnel/BitFunnel,danluu/BitFunnel,danluu/BitFunnel,danluu/BitFunnel,BitFunnel/BitFunnel,BitFunnel/BitFunnel,BitFunnel/BitFunnel
8f2c48cf4c46b3b3d1b58fb8fec13a9c95d2327c
paddle/gserver/layers/Layer.cpp
paddle/gserver/layers/Layer.cpp
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. 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 "paddle/utils/Util.h" #include "CostLayer.h" #include "ValidationLayer.h" #include "paddle/math/SparseMatrix.h" #include "paddle/utils/Error.h" #include "paddle/utils/Logging.h" DEFINE_bool(log_error_clipping, false, "enable log error clipping or not"); namespace paddle { Layer::Layer(const LayerConfig& config, bool useGpu) : config_(config), useGpu_(useGpu), deviceId_(CPU_DEVICE), needSequenceInfo_(true) {} bool Layer::init(const LayerMap& layerMap, const ParameterMap& parameterMap) { if (useGpu_ && FLAGS_parallel_nn) { /* gpu environment is specified by device property */ deviceId_ = config_.device(); if (deviceId_ < 0) { useGpu_ = false; } } output_.deviceId = deviceId_; for (auto& inputConfig : config_.inputs()) { std::string inputName = inputConfig.input_layer_name(); LayerPtr inputLayer; CHECK(mapGet(inputName, layerMap, &inputLayer)) << "Cannot find input layer " << inputName << " for layer " << getName(); this->addPrev(inputLayer); inputLayer->addOutputArgument(deviceId_); if (inputConfig.has_input_parameter_name()) { ParameterPtr parameter; CHECK( mapGet(inputConfig.input_parameter_name(), parameterMap, &parameter)) << "Cannot find input parameter " << inputConfig.input_parameter_name() << " for layer " << getName(); parameter->incShared(); CHECK_EQ(parameter->getDeviceId(), getDeviceId()); parameters_.push_back(parameter); } else { parameters_.push_back(nullptr); } if (inputConfig.has_input_layer_argument()) { inputArgument_.push_back(inputConfig.input_layer_argument()); } else { inputArgument_.push_back(""); } } if (config_.has_bias_parameter_name()) { CHECK(mapGet(config_.bias_parameter_name(), parameterMap, &biasParameter_)) << "Cannot find bias parameter " << config_.bias_parameter_name() << " for layer " << getName(); biasParameter_->incShared(); CHECK_EQ(biasParameter_->getDeviceId(), getDeviceId()); } /* specify the activation function according to the configuration */ std::string action_type = config_.active_type(); activation_.reset(ActivationFunction::create(action_type)); CHECK(activation_); initNeedFlags(); markInBackward_.assign(inputLayers_.size(), false); return true; } ClassRegistrar<Layer, LayerConfig> Layer::registrar_; LayerPtr Layer::create(const LayerConfig& config) { std::string type = config.type(); // NOTE: As following types have illegal character '-', // they can not use REGISTER_LAYER to registrar. // Besides, to fit with old training models, // they can not use '_' instead. if (type == "multi-class-cross-entropy") return LayerPtr(new MultiClassCrossEntropy(config)); else if (type == "rank-cost") return LayerPtr(new RankingCost(config)); #ifndef PADDLE_MOBILE_INFERENCE else if (type == "auc-validation") return LayerPtr(new AucValidation(config)); else if (type == "pnpair-validation") return LayerPtr(new PnpairValidation(config)); #endif return LayerPtr(registrar_.createByType(config.type(), config)); } void Layer::resetSpecifyOutput(Argument& output, size_t height, size_t width, bool isValueClean, bool isGradClean) { SetDevice device(output.deviceId); Matrix::resizeOrCreate( output.value, height, width, /* trans */ false, useGpu(output.deviceId)); if (isValueClean) { output.value->zeroMem(); } if (passType_ != PASS_TEST && needGradient()) { Matrix::resizeOrCreate( output.grad, height, width, /* trans */ false, useGpu(output.deviceId)); if (isGradClean) { output.grad->zeroMem(); } } } void Layer::resizeOutput(size_t height, size_t width) { resetSpecifyOutput(output_, height, width, false, false); for (size_t i = 0; i != outputOtherDevice_.size(); i++) { resetSpecifyOutput(outputOtherDevice_[i], height, width, false, false); } } void Layer::reserveOutput(size_t height, size_t width) { resetSpecifyOutput(output_, height, width, false, true); for (size_t i = 0; i != outputOtherDevice_.size(); i++) { resetSpecifyOutput(outputOtherDevice_[i], height, width, false, true); } } void Layer::resetOutput(size_t height, size_t width) { resetSpecifyOutput(output_, height, width, true, true); for (size_t i = 0; i != outputOtherDevice_.size(); i++) { resetSpecifyOutput(outputOtherDevice_[i], height, width, true, true); } } void Layer::addOutputArgument(int deviceId) { if (deviceId == deviceId_) { output_.countIncrement(); return; } else { for (size_t i = 0; i < outputOtherDevice_.size(); i++) { if (outputOtherDevice_[i].deviceId == deviceId) { outputOtherDevice_[i].countIncrement(); return; } } } Argument argu; argu.deviceId = deviceId; outputOtherDevice_.push_back(argu); outputOtherDevice_.back().countIncrement(); } void Layer::copyOutputToOtherDevice() { for (size_t i = 0; i != outputOtherDevice_.size(); i++) { SetDevice device(outputOtherDevice_[i].deviceId); // If outputOtherDevice_[i].value is a CpuMatrix, // the copyFrom is a synchronous interface. // If outputOtherDevice_[i].value is a GpuMatrix, since subsequent // calculations are all on HPPL_STREAM_DEFAULT, // copyFrom can be an asynchronous interface. outputOtherDevice_[i].value->copyFrom(*getOutputValue(), HPPL_STREAM_DEFAULT); outputOtherDevice_[i].sequenceStartPositions = output_.sequenceStartPositions; outputOtherDevice_[i].subSequenceStartPositions = output_.subSequenceStartPositions; outputOtherDevice_[i].cpuSequenceDims = output_.cpuSequenceDims; outputOtherDevice_[i].notifyValueReady(); } } void Layer::waitInputValue() { for (size_t i = 0; i != inputLayers_.size(); i++) { if (inputLayers_[i]->getDeviceId() != deviceId_) { getInput(i).waitValueReady(); } } } void Layer::waitAndMergeOutputGrad() { if (!output_.grad || !outputOtherDevice_.size()) { return; } for (size_t i = 0; i != outputOtherDevice_.size(); i++) { outputOtherDevice_[i].waitGradReady(); } /* merge output grad */ size_t i = 0; if (!output_.getAllCount()) { output_.grad->copyFrom(*outputOtherDevice_[0].grad, HPPL_STREAM_1); hl_stream_synchronize(HPPL_STREAM_1); i++; if (outputOtherDevice_.size() == 1) return; } Matrix::resizeOrCreate(tmpGrad_, output_.grad->getHeight(), output_.grad->getWidth(), /* trans */ false, useGpu(output_.deviceId)); for (; i != outputOtherDevice_.size(); i++) { tmpGrad_->copyFrom(*outputOtherDevice_[i].grad, HPPL_STREAM_1); hl_stream_synchronize(HPPL_STREAM_1); output_.grad->add(*tmpGrad_); } } void Layer::markAllInputGrad() { for (size_t i = 0; i != inputLayers_.size(); ++i) { if (!markInBackward_[i]) { inputLayers_[i]->getOutput(deviceId_).notifyGradReady(); } markInBackward_[i] = false; } } void Layer::markInputGrad(int inputIndex) { inputLayers_[inputIndex]->getOutput(deviceId_).notifyGradReady(); markInBackward_[inputIndex] = true; } void Layer::zeroGrad() { CHECK(output_.grad.get() != NULL); output_.grad->zeroMem(); } void Layer::initNeedFlags() { auto initFlag = [this]( bool& flag, bool (Layer::*flagQueryFunc)() const, ParameterType type) { flag = false; if (biasParameter_ && biasParameter_->hasType(type)) { flag = true; } if (!flag) { for (auto& para : parameters_) { if (para && para->hasType(type)) { flag = true; break; } } } if (!flag) { for (auto& layer : inputLayers_) { if ((layer.get()->*flagQueryFunc)()) { flag = true; } } } }; initFlag(needGradient_, &Layer::needGradient, PARAMETER_GRADIENT); } void Layer::showOutputStats() { MatrixPtr out = getOutputValue(); if (!out) return; if (!out->getElementCnt()) { LOG(INFO) << "The number of output of " << config_.name() << " is 0, skip to show the statistics"; return; } MatrixPtr outSquare; if (dynamic_cast<GpuSparseMatrix*>(out.get())) { GpuSparseMatrix* tmp = dynamic_cast<GpuSparseMatrix*>(out.get()); outSquare = std::make_shared<CpuSparseMatrix>(tmp->getHeight(), tmp->getWidth(), tmp->getElementCnt(), tmp->getValueType(), tmp->getFormat()); } else { outSquare = out->clone(); } outSquare->copyFrom(*out, HPPL_STREAM_DEFAULT); hl_stream_synchronize(HPPL_STREAM_DEFAULT); real mean = outSquare->getSum() / out->getElementCnt(); real min; real max; if (dynamic_cast<CpuSparseMatrix*>(outSquare.get())) { auto tmpMat = dynamic_cast<CpuSparseMatrix*>(outSquare.get()); min = tmpMat->getMin(); max = tmpMat->getMax(); tmpMat->square2(); LOG(INFO) << "show statistics of [none zero values] in sparse matrix"; } else { min = outSquare->getMin(); max = outSquare->getMax(); outSquare->square2(); } real std = (outSquare->getSum() / outSquare->getElementCnt()) - mean * mean; std = std > 0 ? std : 0; LOG(INFO) << "The output state of " << config_.name() << ": mean=" << mean << ", " << "std=" << std << ", " << "min=" << min << ", " << "max=" << max; } void Layer::forwardActivation() { /* activation */ auto status = activation_->forward(output_); status.check(); /* dropout */ if (config_.drop_rate() > 0) { forwardDropOut(); CHECK_NE(activation_->getName(), "softmax") << "Softmax activation cannot be used with Dropout"; } if (FLAGS_show_layer_stat) { showOutputStats(); } } void Layer::backwardActivation() { /* Do error clipping */ if (config_.error_clipping_threshold() > 0.0f) { if (FLAGS_log_error_clipping) { VectorPtr outGradVec = Vector::create( output_.grad->getData(), output_.grad->getElementCnt(), useGpu_); real maxAbsGrad = outGradVec->getAbsMax(); if (maxAbsGrad > config_.error_clipping_threshold()) { real avgAbsGrad = outGradVec->getAbsSum() / outGradVec->getSize(); LOG(INFO) << " layer=" << config_.name() << " need clipping," << " max error=" << maxAbsGrad << " avg error=" << avgAbsGrad; } } output_.grad->clip(-config_.error_clipping_threshold(), config_.error_clipping_threshold()); } /* Do dropout for delta*/ if (config_.drop_rate() > 0 && passType_ != PASS_TEST) { MatrixPtr oGrad = getOutputGrad(); oGrad->dotMul(*oGrad, *dropOutMask_); } auto status = activation_->backward(output_); status.check(); } void Layer::forwardDropOut() { auto& outV = getOutputValue(); if (passType_ == PASS_TRAIN) { // new dropOutMask_ if dropOutMask_ is null ptr Matrix::resizeOrCreate(dropOutMask_, outV->getHeight(), outV->getWidth(), false, useGpu(deviceId_)); dropOutMask_->randomizeUniform(); // generate a uniform random matrix dropOutMask_->biggerThanScalar(config_.drop_rate()); // random mask outV->dotMul(*outV, *dropOutMask_); // dropout } else if (passType_ == PASS_GC) { // only initialize once if (!dropOutMask_) { dropOutMask_ = Matrix::create( outV->getHeight(), outV->getWidth(), false, useGpu(deviceId_)); // We use cpu matrix to generate mask so that the mask // will be same for both gpu version and cpu version. // This will help unittest to make sure they have same result. MatrixPtr tmpMask = Matrix::create(outV->getHeight(), outV->getWidth()); tmpMask->randomizeUniform(); // generate a uniform random matrix tmpMask->biggerThanScalar(config_.drop_rate()); // random mask dropOutMask_->copyFrom(*tmpMask); } outV->dotMul(*outV, *dropOutMask_); } else { // passType == PASS_TEST outV->mulScalar(1.0 - config_.drop_rate()); } } } // namespace paddle
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. 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 "paddle/utils/Util.h" #include "CostLayer.h" #include "paddle/math/SparseMatrix.h" #include "paddle/utils/Error.h" #include "paddle/utils/Logging.h" #ifndef PADDLE_MOBILE_INFERENCE #include "ValidationLayer.h" #endif DEFINE_bool(log_error_clipping, false, "enable log error clipping or not"); namespace paddle { Layer::Layer(const LayerConfig& config, bool useGpu) : config_(config), useGpu_(useGpu), deviceId_(CPU_DEVICE), needSequenceInfo_(true) {} bool Layer::init(const LayerMap& layerMap, const ParameterMap& parameterMap) { if (useGpu_ && FLAGS_parallel_nn) { /* gpu environment is specified by device property */ deviceId_ = config_.device(); if (deviceId_ < 0) { useGpu_ = false; } } output_.deviceId = deviceId_; for (auto& inputConfig : config_.inputs()) { std::string inputName = inputConfig.input_layer_name(); LayerPtr inputLayer; CHECK(mapGet(inputName, layerMap, &inputLayer)) << "Cannot find input layer " << inputName << " for layer " << getName(); this->addPrev(inputLayer); inputLayer->addOutputArgument(deviceId_); if (inputConfig.has_input_parameter_name()) { ParameterPtr parameter; CHECK( mapGet(inputConfig.input_parameter_name(), parameterMap, &parameter)) << "Cannot find input parameter " << inputConfig.input_parameter_name() << " for layer " << getName(); parameter->incShared(); CHECK_EQ(parameter->getDeviceId(), getDeviceId()); parameters_.push_back(parameter); } else { parameters_.push_back(nullptr); } if (inputConfig.has_input_layer_argument()) { inputArgument_.push_back(inputConfig.input_layer_argument()); } else { inputArgument_.push_back(""); } } if (config_.has_bias_parameter_name()) { CHECK(mapGet(config_.bias_parameter_name(), parameterMap, &biasParameter_)) << "Cannot find bias parameter " << config_.bias_parameter_name() << " for layer " << getName(); biasParameter_->incShared(); CHECK_EQ(biasParameter_->getDeviceId(), getDeviceId()); } /* specify the activation function according to the configuration */ std::string action_type = config_.active_type(); activation_.reset(ActivationFunction::create(action_type)); CHECK(activation_); initNeedFlags(); markInBackward_.assign(inputLayers_.size(), false); return true; } ClassRegistrar<Layer, LayerConfig> Layer::registrar_; LayerPtr Layer::create(const LayerConfig& config) { std::string type = config.type(); // NOTE: As following types have illegal character '-', // they can not use REGISTER_LAYER to registrar. // Besides, to fit with old training models, // they can not use '_' instead. if (type == "multi-class-cross-entropy") return LayerPtr(new MultiClassCrossEntropy(config)); else if (type == "rank-cost") return LayerPtr(new RankingCost(config)); #ifndef PADDLE_MOBILE_INFERENCE else if (type == "auc-validation") return LayerPtr(new AucValidation(config)); else if (type == "pnpair-validation") return LayerPtr(new PnpairValidation(config)); #endif return LayerPtr(registrar_.createByType(config.type(), config)); } void Layer::resetSpecifyOutput(Argument& output, size_t height, size_t width, bool isValueClean, bool isGradClean) { SetDevice device(output.deviceId); Matrix::resizeOrCreate( output.value, height, width, /* trans */ false, useGpu(output.deviceId)); if (isValueClean) { output.value->zeroMem(); } if (passType_ != PASS_TEST && needGradient()) { Matrix::resizeOrCreate( output.grad, height, width, /* trans */ false, useGpu(output.deviceId)); if (isGradClean) { output.grad->zeroMem(); } } } void Layer::resizeOutput(size_t height, size_t width) { resetSpecifyOutput(output_, height, width, false, false); for (size_t i = 0; i != outputOtherDevice_.size(); i++) { resetSpecifyOutput(outputOtherDevice_[i], height, width, false, false); } } void Layer::reserveOutput(size_t height, size_t width) { resetSpecifyOutput(output_, height, width, false, true); for (size_t i = 0; i != outputOtherDevice_.size(); i++) { resetSpecifyOutput(outputOtherDevice_[i], height, width, false, true); } } void Layer::resetOutput(size_t height, size_t width) { resetSpecifyOutput(output_, height, width, true, true); for (size_t i = 0; i != outputOtherDevice_.size(); i++) { resetSpecifyOutput(outputOtherDevice_[i], height, width, true, true); } } void Layer::addOutputArgument(int deviceId) { if (deviceId == deviceId_) { output_.countIncrement(); return; } else { for (size_t i = 0; i < outputOtherDevice_.size(); i++) { if (outputOtherDevice_[i].deviceId == deviceId) { outputOtherDevice_[i].countIncrement(); return; } } } Argument argu; argu.deviceId = deviceId; outputOtherDevice_.push_back(argu); outputOtherDevice_.back().countIncrement(); } void Layer::copyOutputToOtherDevice() { for (size_t i = 0; i != outputOtherDevice_.size(); i++) { SetDevice device(outputOtherDevice_[i].deviceId); // If outputOtherDevice_[i].value is a CpuMatrix, // the copyFrom is a synchronous interface. // If outputOtherDevice_[i].value is a GpuMatrix, since subsequent // calculations are all on HPPL_STREAM_DEFAULT, // copyFrom can be an asynchronous interface. outputOtherDevice_[i].value->copyFrom(*getOutputValue(), HPPL_STREAM_DEFAULT); outputOtherDevice_[i].sequenceStartPositions = output_.sequenceStartPositions; outputOtherDevice_[i].subSequenceStartPositions = output_.subSequenceStartPositions; outputOtherDevice_[i].cpuSequenceDims = output_.cpuSequenceDims; outputOtherDevice_[i].notifyValueReady(); } } void Layer::waitInputValue() { for (size_t i = 0; i != inputLayers_.size(); i++) { if (inputLayers_[i]->getDeviceId() != deviceId_) { getInput(i).waitValueReady(); } } } void Layer::waitAndMergeOutputGrad() { if (!output_.grad || !outputOtherDevice_.size()) { return; } for (size_t i = 0; i != outputOtherDevice_.size(); i++) { outputOtherDevice_[i].waitGradReady(); } /* merge output grad */ size_t i = 0; if (!output_.getAllCount()) { output_.grad->copyFrom(*outputOtherDevice_[0].grad, HPPL_STREAM_1); hl_stream_synchronize(HPPL_STREAM_1); i++; if (outputOtherDevice_.size() == 1) return; } Matrix::resizeOrCreate(tmpGrad_, output_.grad->getHeight(), output_.grad->getWidth(), /* trans */ false, useGpu(output_.deviceId)); for (; i != outputOtherDevice_.size(); i++) { tmpGrad_->copyFrom(*outputOtherDevice_[i].grad, HPPL_STREAM_1); hl_stream_synchronize(HPPL_STREAM_1); output_.grad->add(*tmpGrad_); } } void Layer::markAllInputGrad() { for (size_t i = 0; i != inputLayers_.size(); ++i) { if (!markInBackward_[i]) { inputLayers_[i]->getOutput(deviceId_).notifyGradReady(); } markInBackward_[i] = false; } } void Layer::markInputGrad(int inputIndex) { inputLayers_[inputIndex]->getOutput(deviceId_).notifyGradReady(); markInBackward_[inputIndex] = true; } void Layer::zeroGrad() { CHECK(output_.grad.get() != NULL); output_.grad->zeroMem(); } void Layer::initNeedFlags() { auto initFlag = [this]( bool& flag, bool (Layer::*flagQueryFunc)() const, ParameterType type) { flag = false; if (biasParameter_ && biasParameter_->hasType(type)) { flag = true; } if (!flag) { for (auto& para : parameters_) { if (para && para->hasType(type)) { flag = true; break; } } } if (!flag) { for (auto& layer : inputLayers_) { if ((layer.get()->*flagQueryFunc)()) { flag = true; } } } }; initFlag(needGradient_, &Layer::needGradient, PARAMETER_GRADIENT); } void Layer::showOutputStats() { MatrixPtr out = getOutputValue(); if (!out) return; if (!out->getElementCnt()) { LOG(INFO) << "The number of output of " << config_.name() << " is 0, skip to show the statistics"; return; } MatrixPtr outSquare; if (dynamic_cast<GpuSparseMatrix*>(out.get())) { GpuSparseMatrix* tmp = dynamic_cast<GpuSparseMatrix*>(out.get()); outSquare = std::make_shared<CpuSparseMatrix>(tmp->getHeight(), tmp->getWidth(), tmp->getElementCnt(), tmp->getValueType(), tmp->getFormat()); } else { outSquare = out->clone(); } outSquare->copyFrom(*out, HPPL_STREAM_DEFAULT); hl_stream_synchronize(HPPL_STREAM_DEFAULT); real mean = outSquare->getSum() / out->getElementCnt(); real min; real max; if (dynamic_cast<CpuSparseMatrix*>(outSquare.get())) { auto tmpMat = dynamic_cast<CpuSparseMatrix*>(outSquare.get()); min = tmpMat->getMin(); max = tmpMat->getMax(); tmpMat->square2(); LOG(INFO) << "show statistics of [none zero values] in sparse matrix"; } else { min = outSquare->getMin(); max = outSquare->getMax(); outSquare->square2(); } real std = (outSquare->getSum() / outSquare->getElementCnt()) - mean * mean; std = std > 0 ? std : 0; LOG(INFO) << "The output state of " << config_.name() << ": mean=" << mean << ", " << "std=" << std << ", " << "min=" << min << ", " << "max=" << max; } void Layer::forwardActivation() { /* activation */ auto status = activation_->forward(output_); status.check(); /* dropout */ if (config_.drop_rate() > 0) { forwardDropOut(); CHECK_NE(activation_->getName(), "softmax") << "Softmax activation cannot be used with Dropout"; } if (FLAGS_show_layer_stat) { showOutputStats(); } } void Layer::backwardActivation() { /* Do error clipping */ if (config_.error_clipping_threshold() > 0.0f) { if (FLAGS_log_error_clipping) { VectorPtr outGradVec = Vector::create( output_.grad->getData(), output_.grad->getElementCnt(), useGpu_); real maxAbsGrad = outGradVec->getAbsMax(); if (maxAbsGrad > config_.error_clipping_threshold()) { real avgAbsGrad = outGradVec->getAbsSum() / outGradVec->getSize(); LOG(INFO) << " layer=" << config_.name() << " need clipping," << " max error=" << maxAbsGrad << " avg error=" << avgAbsGrad; } } output_.grad->clip(-config_.error_clipping_threshold(), config_.error_clipping_threshold()); } /* Do dropout for delta*/ if (config_.drop_rate() > 0 && passType_ != PASS_TEST) { MatrixPtr oGrad = getOutputGrad(); oGrad->dotMul(*oGrad, *dropOutMask_); } auto status = activation_->backward(output_); status.check(); } void Layer::forwardDropOut() { auto& outV = getOutputValue(); if (passType_ == PASS_TRAIN) { // new dropOutMask_ if dropOutMask_ is null ptr Matrix::resizeOrCreate(dropOutMask_, outV->getHeight(), outV->getWidth(), false, useGpu(deviceId_)); dropOutMask_->randomizeUniform(); // generate a uniform random matrix dropOutMask_->biggerThanScalar(config_.drop_rate()); // random mask outV->dotMul(*outV, *dropOutMask_); // dropout } else if (passType_ == PASS_GC) { // only initialize once if (!dropOutMask_) { dropOutMask_ = Matrix::create( outV->getHeight(), outV->getWidth(), false, useGpu(deviceId_)); // We use cpu matrix to generate mask so that the mask // will be same for both gpu version and cpu version. // This will help unittest to make sure they have same result. MatrixPtr tmpMask = Matrix::create(outV->getHeight(), outV->getWidth()); tmpMask->randomizeUniform(); // generate a uniform random matrix tmpMask->biggerThanScalar(config_.drop_rate()); // random mask dropOutMask_->copyFrom(*tmpMask); } outV->dotMul(*outV, *dropOutMask_); } else { // passType == PASS_TEST outV->mulScalar(1.0 - config_.drop_rate()); } } } // namespace paddle
Fix Layer.cpp
Fix Layer.cpp
C++
apache-2.0
putcn/Paddle,Canpio/Paddle,luotao1/Paddle,chengduoZH/Paddle,luotao1/Paddle,putcn/Paddle,jacquesqiao/Paddle,lcy-seso/Paddle,QiJune/Paddle,tensor-tang/Paddle,PaddlePaddle/Paddle,pengli09/Paddle,Canpio/Paddle,reyoung/Paddle,reyoung/Paddle,lcy-seso/Paddle,PaddlePaddle/Paddle,luotao1/Paddle,pkuyym/Paddle,baidu/Paddle,pengli09/Paddle,reyoung/Paddle,pkuyym/Paddle,putcn/Paddle,tensor-tang/Paddle,reyoung/Paddle,baidu/Paddle,putcn/Paddle,pengli09/Paddle,tensor-tang/Paddle,QiJune/Paddle,tensor-tang/Paddle,reyoung/Paddle,PaddlePaddle/Paddle,QiJune/Paddle,jacquesqiao/Paddle,pengli09/Paddle,luotao1/Paddle,luotao1/Paddle,jacquesqiao/Paddle,pengli09/Paddle,Canpio/Paddle,chengduoZH/Paddle,QiJune/Paddle,luotao1/Paddle,pkuyym/Paddle,Canpio/Paddle,QiJune/Paddle,chengduoZH/Paddle,Canpio/Paddle,putcn/Paddle,jacquesqiao/Paddle,QiJune/Paddle,PaddlePaddle/Paddle,PaddlePaddle/Paddle,lcy-seso/Paddle,tensor-tang/Paddle,PaddlePaddle/Paddle,putcn/Paddle,baidu/Paddle,chengduoZH/Paddle,Canpio/Paddle,pengli09/Paddle,Canpio/Paddle,luotao1/Paddle,pengli09/Paddle,baidu/Paddle,jacquesqiao/Paddle,jacquesqiao/Paddle,baidu/Paddle,lcy-seso/Paddle,reyoung/Paddle,lcy-seso/Paddle,lcy-seso/Paddle,pkuyym/Paddle,pengli09/Paddle,pkuyym/Paddle,pkuyym/Paddle,chengduoZH/Paddle,Canpio/Paddle,PaddlePaddle/Paddle
9467836a86891571073661b073655e5976a50e08
modules/gui/qt4/input_manager.hpp
modules/gui/qt4/input_manager.hpp
/***************************************************************************** * input_manager.hpp : Manage an input and interact with its GUI elements **************************************************************************** * Copyright (C) 2006-2008 the VideoLAN team * $Id$ * * Authors: Clément Stenac <[email protected]> * Jean-Baptiste <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #ifndef _INPUT_MANAGER_H_ #define _INPUT_MANAGER_H_ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <vlc_input.h> #include <vlc_vout.h> #include <vlc_aout.h> #include "qt4.hpp" #include <QObject> #include <QEvent> enum { PositionUpdate_Type = QEvent::User + IMEventType + 1, ItemChanged_Type, ItemStateChanged_Type, ItemTitleChanged_Type, ItemRateChanged_Type, VolumeChanged_Type, ItemEsChanged_Type, ItemTeletextChanged_Type, InterfaceVoutUpdate_Type, StatisticsUpdate_Type, /*10*/ InterfaceAoutUpdate_Type, MetaChanged_Type, NameChanged_Type, InfoChanged_Type, SynchroChanged_Type, CachingEvent_Type, BookmarksChanged_Type, /* RecordingEvent_Type, ProgramChanged_Type, SignalChanged_Type, */ FullscreenControlToggle_Type = QEvent::User + IMEventType + 20, FullscreenControlShow_Type, FullscreenControlHide_Type, FullscreenControlPlanHide_Type, }; class IMEvent : public QEvent { friend class InputManager; public: IMEvent( int type, int id ) : QEvent( (QEvent::Type)(type) ) { i_id = id ; } ; virtual ~IMEvent() {}; private: int i_id; }; class InputManager : public QObject { Q_OBJECT; friend class MainInputManager; public: InputManager( QObject *, intf_thread_t * ); virtual ~InputManager(); void delInput(); bool hasInput() { return p_input /* We have an input */ && !p_input->b_dead /* not dead yet, */ && !p_input->b_eof /* not EOF either, */ && vlc_object_alive (p_input); /* and the VLC object is alive */ } bool hasAudio(); bool hasVideo() { return hasInput() && b_video; } void requestArtUpdate(); QString getName() { return oldName; } private: intf_thread_t *p_intf; input_thread_t *p_input; int i_input_id; int i_old_playing_status; QString oldName; QString artUrl; int i_rate; float f_cache; bool b_video; mtime_t timeA, timeB; void customEvent( QEvent * ); void addCallbacks(); void delCallbacks(); void UpdateRate(); void UpdateName(); void UpdateStatus(); void UpdateNavigation(); void UpdatePosition(); void UpdateTeletext(); void UpdateArt(); void UpdateInfo(); void UpdateMeta(); void UpdateVout(); void UpdateAout(); void UpdateStats(); void UpdateCaching(); void AtoBLoop( int ); public slots: void setInput( input_thread_t * ); ///< Our controlled input changed void sliderUpdate( float ); ///< User dragged the slider. We get new pos /* SpeedRate Rate Management */ void reverse(); void slower(); void faster(); void normalRate(); void setRate( int ); /* Menus */ void sectionNext(); void sectionPrev(); void sectionMenu(); /* Teletext */ void telexSetPage( int ); ///< Goto teletext page void telexSetTransparency( bool ); ///< Transparency on teletext background void telexActivation( bool ); ///< Enable disable teletext buttons void activateTeletext( bool ); ///< Toggle buttons after click /* A to B Loop */ void setAtoB(); private slots: void togglePlayPause(); signals: /// Send new position, new time and new length void positionUpdated( float , int, int ); void rateChanged( int ); void nameChanged( QString ); /// Used to signal whether we should show navigation buttons void titleChanged( bool ); void chapterChanged( bool ); /// Statistics are updated void statisticsUpdated( input_item_t* ); void infoChanged( input_item_t* ); void metaChanged( input_item_t* ); void artChanged( QString ); /// Play/pause status void statusChanged( int ); /// Teletext void teletextPossible( bool ); void teletextActivated( bool ); void teletextTransparencyActivated( bool ); void newTelexPageSet( int ); /// Advanced buttons void AtoBchanged( bool, bool ); /// Vout void voutChanged( bool ); void synchroChanged(); void bookmarksChanged(); void cachingChanged( float ); void voutListChanged( vout_thread_t **pp_vout, int i_vout ); }; class MainInputManager : public QObject { Q_OBJECT; public: static MainInputManager *getInstance( intf_thread_t *_p_intf ) { if( !instance ) instance = new MainInputManager( _p_intf ); return instance; } static void killInstance() { if( instance ) delete instance; } virtual ~MainInputManager(); input_thread_t *getInput() { return p_input; }; InputManager *getIM() { return im; }; vout_thread_t * getVout() { vout_thread_t **pp_vout; int i_vout; if( p_input && !input_Control( p_input, INPUT_GET_VOUTS, &pp_vout, &i_vout ) ) { for( int i = 1; i < i_vout; i++ ) vlc_object_release( pp_vout[i]); vout_thread_t *p_tmp = pp_vout[0]; free( pp_vout ); return p_tmp; } return NULL; } aout_instance_t *getAout() { aout_instance_t *p_aout; if( p_input && !input_Control( p_input, INPUT_GET_AOUT, &p_aout ) ) { return p_aout; } } private: MainInputManager( intf_thread_t * ); static MainInputManager *instance; void customEvent( QEvent * ); InputManager *im; input_thread_t *p_input; intf_thread_t *p_intf; public slots: void togglePlayPause(); void stop(); void next(); void prev(); signals: void inputChanged( input_thread_t * ); void volumeChanged(); }; #endif
/***************************************************************************** * input_manager.hpp : Manage an input and interact with its GUI elements **************************************************************************** * Copyright (C) 2006-2008 the VideoLAN team * $Id$ * * Authors: Clément Stenac <[email protected]> * Jean-Baptiste <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #ifndef _INPUT_MANAGER_H_ #define _INPUT_MANAGER_H_ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <vlc_input.h> #include <vlc_vout.h> #include <vlc_aout.h> #include "qt4.hpp" #include <QObject> #include <QEvent> enum { PositionUpdate_Type = QEvent::User + IMEventType + 1, ItemChanged_Type, ItemStateChanged_Type, ItemTitleChanged_Type, ItemRateChanged_Type, VolumeChanged_Type, ItemEsChanged_Type, ItemTeletextChanged_Type, InterfaceVoutUpdate_Type, StatisticsUpdate_Type, /*10*/ InterfaceAoutUpdate_Type, MetaChanged_Type, NameChanged_Type, InfoChanged_Type, SynchroChanged_Type, CachingEvent_Type, BookmarksChanged_Type, /* RecordingEvent_Type, ProgramChanged_Type, SignalChanged_Type, */ FullscreenControlToggle_Type = QEvent::User + IMEventType + 20, FullscreenControlShow_Type, FullscreenControlHide_Type, FullscreenControlPlanHide_Type, }; class IMEvent : public QEvent { friend class InputManager; public: IMEvent( int type, int id ) : QEvent( (QEvent::Type)(type) ) { i_id = id ; } ; virtual ~IMEvent() {}; private: int i_id; }; class InputManager : public QObject { Q_OBJECT; friend class MainInputManager; public: InputManager( QObject *, intf_thread_t * ); virtual ~InputManager(); void delInput(); bool hasInput() { return p_input /* We have an input */ && !p_input->b_dead /* not dead yet, */ && !p_input->b_eof /* not EOF either, */ && vlc_object_alive (p_input); /* and the VLC object is alive */ } bool hasAudio(); bool hasVideo() { return hasInput() && b_video; } void requestArtUpdate(); QString getName() { return oldName; } private: intf_thread_t *p_intf; input_thread_t *p_input; int i_input_id; int i_old_playing_status; QString oldName; QString artUrl; int i_rate; float f_cache; bool b_video; mtime_t timeA, timeB; void customEvent( QEvent * ); void addCallbacks(); void delCallbacks(); void UpdateRate(); void UpdateName(); void UpdateStatus(); void UpdateNavigation(); void UpdatePosition(); void UpdateTeletext(); void UpdateArt(); void UpdateInfo(); void UpdateMeta(); void UpdateVout(); void UpdateAout(); void UpdateStats(); void UpdateCaching(); void AtoBLoop( int ); public slots: void setInput( input_thread_t * ); ///< Our controlled input changed void sliderUpdate( float ); ///< User dragged the slider. We get new pos /* SpeedRate Rate Management */ void reverse(); void slower(); void faster(); void normalRate(); void setRate( int ); /* Menus */ void sectionNext(); void sectionPrev(); void sectionMenu(); /* Teletext */ void telexSetPage( int ); ///< Goto teletext page void telexSetTransparency( bool ); ///< Transparency on teletext background void telexActivation( bool ); ///< Enable disable teletext buttons void activateTeletext( bool ); ///< Toggle buttons after click /* A to B Loop */ void setAtoB(); private slots: void togglePlayPause(); signals: /// Send new position, new time and new length void positionUpdated( float , int, int ); void rateChanged( int ); void nameChanged( QString ); /// Used to signal whether we should show navigation buttons void titleChanged( bool ); void chapterChanged( bool ); /// Statistics are updated void statisticsUpdated( input_item_t* ); void infoChanged( input_item_t* ); void metaChanged( input_item_t* ); void artChanged( QString ); /// Play/pause status void statusChanged( int ); /// Teletext void teletextPossible( bool ); void teletextActivated( bool ); void teletextTransparencyActivated( bool ); void newTelexPageSet( int ); /// Advanced buttons void AtoBchanged( bool, bool ); /// Vout void voutChanged( bool ); void synchroChanged(); void bookmarksChanged(); void cachingChanged( float ); void voutListChanged( vout_thread_t **pp_vout, int i_vout ); }; class MainInputManager : public QObject { Q_OBJECT; public: static MainInputManager *getInstance( intf_thread_t *_p_intf ) { if( !instance ) instance = new MainInputManager( _p_intf ); return instance; } static void killInstance() { if( instance ) delete instance; } virtual ~MainInputManager(); input_thread_t *getInput() { return p_input; }; InputManager *getIM() { return im; }; vout_thread_t * getVout() { vout_thread_t **pp_vout; int i_vout; if( p_input && !input_Control( p_input, INPUT_GET_VOUTS, &pp_vout, &i_vout ) ) { for( int i = 1; i < i_vout; i++ ) vlc_object_release( pp_vout[i]); vout_thread_t *p_tmp = pp_vout[0]; free( pp_vout ); return p_tmp; } return NULL; } aout_instance_t *getAout() { aout_instance_t *p_aout; if( p_input && !input_Control( p_input, INPUT_GET_AOUT, &p_aout ) ) { return p_aout; } return NULL; } private: MainInputManager( intf_thread_t * ); static MainInputManager *instance; void customEvent( QEvent * ); InputManager *im; input_thread_t *p_input; intf_thread_t *p_intf; public slots: void togglePlayPause(); void stop(); void next(); void prev(); signals: void inputChanged( input_thread_t * ); void volumeChanged(); }; #endif
return NULL on getAout if no input
Qt4: return NULL on getAout if no input
C++
lgpl-2.1
vlc-mirror/vlc-2.1,shyamalschandra/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.2,krichter722/vlc,shyamalschandra/vlc,xkfz007/vlc,krichter722/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.2,vlc-mirror/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.2,krichter722/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,krichter722/vlc,xkfz007/vlc,xkfz007/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.2,vlc-mirror/vlc,jomanmuk/vlc-2.1,xkfz007/vlc,xkfz007/vlc,krichter722/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,krichter722/vlc,xkfz007/vlc,shyamalschandra/vlc,vlc-mirror/vlc,vlc-mirror/vlc-2.1,xkfz007/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,shyamalschandra/vlc,vlc-mirror/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.1,shyamalschandra/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,vlc-mirror/vlc,krichter722/vlc,vlc-mirror/vlc-2.1,shyamalschandra/vlc
2aa536314cedf143bb40cd7a030fd9d2d501d404
source/lib/hardware/pcb/Base.cc
source/lib/hardware/pcb/Base.cc
#include <iostream> #include <sstream> #include "util/String.h" #include "hardware/pcb/Base.h" namespace blitzortung { namespace hardware { namespace pcb { Base::Base(SerialPort& serial, const gps::Type& gpsType, const data::sample::Base::Creator& sampleCreator) : communication_(serial), logger_("hardware.pcb.Base"), gps_(communication_, gpsType), sampleCreator_(sampleCreator) { if (logger_.isDebugEnabled()) logger_.debugStream() << "initialized"; } Base::~Base() { if (logger_.isDebugEnabled()) logger_.debugStream() << "destroyed"; } int Base::parseHex(const std::string& hexString) { int hexValue; std::istringstream iss(hexString); iss >> std::hex >> hexValue; return hexValue; } bool Base::isOpen() const { return communication_.isOpen(); } data::sample::Base::AP Base::read() { std::string line = communication_.receive(); if (logger_.isInfoEnabled()) logger_.infoStream() << "read() serial input: " << line; int linelength = line.size(); if (linelength > 3 && line[0] == '$' && line[linelength - 4] == '*') { // valid line for checksum calculation std::string content = line.substr(1, linelength - 5); int transmittedChecksum; std::istringstream iss(line.substr(linelength - 3, linelength - 2)); iss >> std::hex >> transmittedChecksum; // calculate checksum of content unsigned char checksum = 0; if (content.length() > 1) { checksum = (unsigned char)content[0]; for (std::string::iterator character = content.begin() + 1; character != content.end(); character++) { checksum ^= (unsigned char)*character; } if (checksum == transmittedChecksum) { // checksum values are identical fields_.clear(); util::String::split(content, fields_, ","); if (fields_[0] == "BLSEC") { parseGps(fields_); fields_.clear(); } else if (fields_[0] == "BLSEQ") { return parse(fields_); } else { std::cout << "unknown data " << fields_[0] << std::endl; } } } } return std::auto_ptr<data::sample::Base>(); } void Base::parseGps(const std::vector<std::string>& fields) { gps_.parse(fields); } } } }
#include <iostream> #include <sstream> #include "util/String.h" #include "hardware/pcb/Base.h" namespace blitzortung { namespace hardware { namespace pcb { Base::Base(SerialPort& serial, const gps::Type& gpsType, const data::sample::Base::Creator& sampleCreator) : communication_(serial), logger_("hardware.pcb.Base"), gps_(communication_, gpsType), sampleCreator_(sampleCreator) { if (logger_.isDebugEnabled()) logger_.debugStream() << "initialized"; } Base::~Base() { if (logger_.isDebugEnabled()) logger_.debugStream() << "destroyed"; } int Base::parseHex(const std::string& hexString) { int hexValue; std::istringstream iss(hexString); iss >> std::hex >> hexValue; return hexValue; } bool Base::isOpen() const { return communication_.isOpen(); } data::sample::Base::AP Base::read() { std::string line = communication_.receive(); if (logger_.isInfoEnabled()) logger_.infoStream() << "read() serial input: " << line; int linelength = line.size(); if (linelength > 3 && line[0] == '$' && line[linelength - 4] == '*') { // valid line for checksum calculation std::string content = line.substr(1, linelength - 5); int transmittedChecksum; std::istringstream iss(line.substr(linelength - 3, linelength - 2)); iss >> std::hex >> transmittedChecksum; // calculate checksum of content unsigned char checksum = 0; if (content.length() > 1) { checksum = (unsigned char)content[0]; for (std::string::iterator character = content.begin() + 1; character != content.end(); character++) { checksum ^= (unsigned char)*character; } if (checksum == transmittedChecksum) { // checksum values are identical fields_.clear(); util::String::split(content, fields_, ","); if (fields_[0] == "BLSEC") { parseGps(fields_); fields_.clear(); } else if (fields_[0] == "BLSEQ" || fields_[0] == "BLSIG") { return parse(fields_); } else { std::cout << "unknown data " << fields_[0] << std::endl; } } } } return std::auto_ptr<data::sample::Base>(); } void Base::parseGps(const std::vector<std::string>& fields) { gps_.parse(fields); } } } }
fix for pcb v4 data
fix for pcb v4 data
C++
mit
wuan/bo-tracker,wuan/bo-tracker,wuan/bo-tracker
57aac5427dcea6eaee8ca71ccc3ae26a42bfaa21
source/type/tests/data_test.cpp
source/type/tests/data_test.cpp
/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved. This file is part of Navitia, the software to build cool stuff with public transport. Hope you'll enjoy and contribute to this project, powered by Canal TP (www.canaltp.fr). Help us simplify mobility and open public transport: a non ending quest to the responsive locomotion way of traveling! LICENCE: This program 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. 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Stay tuned using twitter @navitia IRC #navitia on freenode https://groups.google.com/d/forum/navitia www.navitia.io */ #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE data_test // Boost #include <boost/test/unit_test.hpp> #include <boost/filesystem.hpp> // Std #include <string> #include <fstream> // Data to test #include "type/data.h" using namespace navitia; using namespace boost::filesystem; static const std::string fake_data_file = "fake_data.nav.lz4"; static const std::string fake_disruption_path = "fake_disruption_path"; // We create a empty data with lz4 format in current directory #define CREATE_FAKE_DATA(fake_file_name) \ navitia::type::Data data(0); \ data.save(fake_data_file); \ BOOST_AUTO_TEST_CASE(load_data) { CREATE_FAKE_DATA(fake_data_file) // Load fake data bool check_load = data.load(boost::filesystem::canonical(current_path()).string() \ + "/" + fake_data_file); BOOST_CHECK_EQUAL(check_load, true); } BOOST_AUTO_TEST_CASE(load_data_fail) { navitia::type::Data data(0); bool check_load = data.load("wrong_path"); BOOST_CHECK_EQUAL(check_load, false); } BOOST_AUTO_TEST_CASE(load_disruptions_fail) { CREATE_FAKE_DATA(fake_data_file) // Load fake data bool check_load = data.load(boost::filesystem::canonical(current_path()).string() \ + "/" + fake_data_file, fake_disruption_path); BOOST_CHECK_EQUAL(data.disruption_error, true); BOOST_CHECK_EQUAL(check_load, true); } BOOST_AUTO_TEST_CASE(load_without_disruptions) { CREATE_FAKE_DATA(fake_data_file) // Load fake data bool check_load = data.load_without_disruptions(boost::filesystem::canonical(current_path()).string() \ + "/" + fake_data_file); BOOST_CHECK_EQUAL(data.disruption_error, false); BOOST_CHECK_EQUAL(check_load, true); }
/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved. This file is part of Navitia, the software to build cool stuff with public transport. Hope you'll enjoy and contribute to this project, powered by Canal TP (www.canaltp.fr). Help us simplify mobility and open public transport: a non ending quest to the responsive locomotion way of traveling! LICENCE: This program 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. 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Stay tuned using twitter @navitia IRC #navitia on freenode https://groups.google.com/d/forum/navitia www.navitia.io */ #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE data_test // Boost #include <boost/test/unit_test.hpp> #include <boost/filesystem.hpp> // Std #include <string> #include <fstream> // Data to test #include "type/data.h" using namespace navitia; using namespace boost::filesystem; static const std::string fake_data_file = "fake_data.nav.lz4"; static const std::string fake_disruption_path = "fake_disruption_path"; // We create a empty data with lz4 format in current directory #define CREATE_FAKE_DATA(fake_file_name) \ navitia::type::Data data(0); \ data.save(fake_data_file); \ BOOST_AUTO_TEST_CASE(load_data) { CREATE_FAKE_DATA(fake_data_file) // Load fake data bool check_load = data.load(boost::filesystem::absolute(current_path()).string() \ + "/" + fake_data_file); BOOST_CHECK_EQUAL(check_load, true); } BOOST_AUTO_TEST_CASE(load_data_fail) { navitia::type::Data data(0); bool check_load = data.load("wrong_path"); BOOST_CHECK_EQUAL(check_load, false); } BOOST_AUTO_TEST_CASE(load_disruptions_fail) { CREATE_FAKE_DATA(fake_data_file) // Load fake data bool check_load = data.load(boost::filesystem::absolute(current_path()).string() \ + "/" + fake_data_file, fake_disruption_path); BOOST_CHECK_EQUAL(data.disruption_error, true); BOOST_CHECK_EQUAL(check_load, true); } BOOST_AUTO_TEST_CASE(load_without_disruptions) { CREATE_FAKE_DATA(fake_data_file) // Load fake data bool check_load = data.load_without_disruptions(boost::filesystem::absolute(current_path()).string() \ + "/" + fake_data_file); BOOST_CHECK_EQUAL(data.disruption_error, false); BOOST_CHECK_EQUAL(check_load, true); }
Fix data_test
Fix data_test using absolute path (Boost)
C++
agpl-3.0
CanalTP/navitia,pbougue/navitia,patochectp/navitia,xlqian/navitia,kadhikari/navitia,pbougue/navitia,kinnou02/navitia,CanalTP/navitia,CanalTP/navitia,kadhikari/navitia,Tisseo/navitia,pbougue/navitia,CanalTP/navitia,Tisseo/navitia,Tisseo/navitia,CanalTP/navitia,patochectp/navitia,kinnou02/navitia,patochectp/navitia,pbougue/navitia,Tisseo/navitia,patochectp/navitia,kadhikari/navitia,xlqian/navitia,xlqian/navitia,Tisseo/navitia,kinnou02/navitia,kinnou02/navitia,xlqian/navitia,xlqian/navitia,kadhikari/navitia
aa6da1cc2a019a1ada7f6d11ad2f9f56240027a5
eval/src/tests/instruction/mixed_map_function/mixed_map_function_test.cpp
eval/src/tests/instruction/mixed_map_function/mixed_map_function_test.cpp
// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/eval/eval/tensor_function.h> #include <vespa/eval/instruction/mixed_map_function.h> #include <vespa/eval/eval/test/eval_fixture.h> #include <vespa/eval/eval/test/tensor_model.hpp> #include <vespa/vespalib/gtest/gtest.h> using namespace vespalib; using namespace vespalib::eval; using namespace vespalib::eval::test; using namespace vespalib::eval::tensor_function; const ValueBuilderFactory &prod_factory = FastValueBuilderFactory::get(); EvalFixture::ParamRepo make_params() { return EvalFixture::ParamRepo() .add("a", spec(1.5)) .add("b", spec(2.5)) .add("sparse", spec({x({"a"})}, N())) .add("mixed", spec({x({"a"}),y(5)}, N())) .add_mutable("@sparse", spec({x({"a"})}, N())) .add_mutable("@mixed", spec({x({"a"}),y(5)}, N())) .add_matrix("x", 5, "y", 3); } EvalFixture::ParamRepo param_repo = make_params(); void verify_optimized(const vespalib::string &expr, bool inplace) { EvalFixture slow_fixture(prod_factory, expr, param_repo, false); EvalFixture fixture(prod_factory, expr, param_repo, true, true); EXPECT_EQ(fixture.result(), EvalFixture::ref(expr, param_repo)); EXPECT_EQ(fixture.result(), slow_fixture.result()); auto info = fixture.find_all<MixedMapFunction>(); ASSERT_EQ(info.size(), 1u); EXPECT_TRUE(info[0]->result_is_mutable()); EXPECT_EQ(info[0]->inplace(), inplace); ASSERT_EQ(fixture.num_params(), 1); if (inplace) { EXPECT_EQ(fixture.get_param(0), fixture.result()); } else { EXPECT_TRUE(!(fixture.get_param(0) == fixture.result())); } } void verify_not_optimized(const vespalib::string &expr) { EvalFixture slow_fixture(prod_factory, expr, param_repo, false); EvalFixture fixture(prod_factory, expr, param_repo, true); EXPECT_EQ(fixture.result(), EvalFixture::ref(expr, param_repo)); EXPECT_EQ(fixture.result(), slow_fixture.result()); auto info = fixture.find_all<MixedMapFunction>(); EXPECT_TRUE(info.empty()); } TEST(MapTest, dense_map_is_optimized) { verify_optimized("map(x5y3,f(x)(x+10))", false); verify_optimized("map(x5y3f,f(x)(x+10))", false); } TEST(MapTest, simple_dense_map_can_be_inplace) { verify_optimized("map(@x5y3,f(x)(x+10))", true); verify_optimized("map(@x5y3f,f(x)(x+10))", true); } TEST(MapTest, scalar_map_is_not_optimized) { verify_not_optimized("map(a,f(x)(x+10))"); } TEST(MapTest, sparse_map_is_optimized) { verify_optimized("map(sparse,f(x)(x+10))", false); } TEST(MapTest, sparse_map_can_be_inplace) { verify_optimized("map(@sparse,f(x)(x+10))", true); } TEST(MapTest, mixed_map_is_optimized) { verify_optimized("map(mixed,f(x)(x+10))", false); } TEST(MapTest, mixed_map_can_be_inplace) { verify_optimized("map(@mixed,f(x)(x+10))", true); } GTEST_MAIN_RUN_ALL_TESTS()
// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/eval/eval/tensor_function.h> #include <vespa/eval/instruction/mixed_map_function.h> #include <vespa/eval/eval/test/eval_fixture.h> #include <vespa/eval/eval/test/gen_spec.h> #include <vespa/vespalib/gtest/gtest.h> using namespace vespalib; using namespace vespalib::eval; using namespace vespalib::eval::test; using namespace vespalib::eval::tensor_function; const ValueBuilderFactory &prod_factory = FastValueBuilderFactory::get(); TensorSpec spec(double v) { return TensorSpec("double").add({}, v); } TensorSpec sparse_spec = GenSpec().map("x", {"a"}).gen(); TensorSpec mixed_spec = GenSpec().map("x", {"a"}).idx("y", 5).gen(); EvalFixture::ParamRepo make_params() { return EvalFixture::ParamRepo() .add("a", spec(1.5)) .add("b", spec(2.5)) .add("sparse", sparse_spec) .add("mixed", mixed_spec) .add_mutable("@sparse", sparse_spec) .add_mutable("@mixed", mixed_spec) .add_matrix("x", 5, "y", 3); } EvalFixture::ParamRepo param_repo = make_params(); void verify_optimized(const vespalib::string &expr, bool inplace) { EvalFixture slow_fixture(prod_factory, expr, param_repo, false); EvalFixture fixture(prod_factory, expr, param_repo, true, true); EXPECT_EQ(fixture.result(), EvalFixture::ref(expr, param_repo)); EXPECT_EQ(fixture.result(), slow_fixture.result()); auto info = fixture.find_all<MixedMapFunction>(); ASSERT_EQ(info.size(), 1u); EXPECT_TRUE(info[0]->result_is_mutable()); EXPECT_EQ(info[0]->inplace(), inplace); ASSERT_EQ(fixture.num_params(), 1); if (inplace) { EXPECT_EQ(fixture.get_param(0), fixture.result()); } else { EXPECT_TRUE(!(fixture.get_param(0) == fixture.result())); } } void verify_not_optimized(const vespalib::string &expr) { EvalFixture slow_fixture(prod_factory, expr, param_repo, false); EvalFixture fixture(prod_factory, expr, param_repo, true); EXPECT_EQ(fixture.result(), EvalFixture::ref(expr, param_repo)); EXPECT_EQ(fixture.result(), slow_fixture.result()); auto info = fixture.find_all<MixedMapFunction>(); EXPECT_TRUE(info.empty()); } TEST(MapTest, dense_map_is_optimized) { verify_optimized("map(x5y3,f(x)(x+10))", false); verify_optimized("map(x5y3f,f(x)(x+10))", false); } TEST(MapTest, simple_dense_map_can_be_inplace) { verify_optimized("map(@x5y3,f(x)(x+10))", true); verify_optimized("map(@x5y3f,f(x)(x+10))", true); } TEST(MapTest, scalar_map_is_not_optimized) { verify_not_optimized("map(a,f(x)(x+10))"); } TEST(MapTest, sparse_map_is_optimized) { verify_optimized("map(sparse,f(x)(x+10))", false); } TEST(MapTest, sparse_map_can_be_inplace) { verify_optimized("map(@sparse,f(x)(x+10))", true); } TEST(MapTest, mixed_map_is_optimized) { verify_optimized("map(mixed,f(x)(x+10))", false); } TEST(MapTest, mixed_map_can_be_inplace) { verify_optimized("map(@mixed,f(x)(x+10))", true); } GTEST_MAIN_RUN_ALL_TESTS()
use GenSpec in mixed_map_function_test
use GenSpec in mixed_map_function_test
C++
apache-2.0
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
5a2c0d78f552fb962011eac152cb2a7a0e2dc78a
src/object/fwd.hh
src/object/fwd.hh
/** ** \file object/fwd.hh ** \brief Forward declarations of all node-classes of OBJECT ** (needed by the visitors) */ #ifndef OBJECT_FWD_HH # define OBJECT_FWD_HH # include <deque> # include <libport/fwd.hh> # include <libport/shared-ptr.hh> namespace runner { class Runner; } namespace object { // state.hh struct State; // rObject & objects_type. class Object; // We don't know yet that Object inherits RefCounted, so we have to force // the second template argument. typedef libport::shared_ptr<Object, true> rObject; typedef std::deque<rObject> objects_type; /// \a Macro should be a binary macro whose first arg, \p What, is /// the lower case C++ name, and the second argument, \p Name, the /// capitalized URBI name. This is used in many different contexts, /// such as defining enums, so we do not use terminators here (; /// etc.): Macro must do it. # define APPLY_ON_ALL_PRIMITIVES_BUT_OBJECT(Macro) \ Macro(alien, Alien) \ Macro(code, Code) \ Macro(delegate, Delegate) \ Macro(dictionary, Dictionary) \ Macro(float, Float) \ Macro(integer, Integer) \ Macro(list, List) \ Macro(lobby, Lobby) \ Macro(primitive, Primitive) \ Macro(string, String) # define APPLY_ON_ALL_PRIMITIVES(Macro) \ APPLY_ON_ALL_PRIMITIVES_BUT_OBJECT(Macro) \ Macro(object, Object) # define APPLY_ON_ALL_ROOT_CLASSES_BUT_OBJECT(Macro) \ APPLY_ON_ALL_PRIMITIVES_BUT_OBJECT(Macro) \ Macro(global, Global) \ Macro(tag, Tag) \ Macro(task, Task) # define APPLY_ON_ALL_ROOT_CLASSES(Macro) \ APPLY_ON_ALL_ROOT_CLASSES_BUT_OBJECT(Macro) \ Macro(object, Object) /* Help the generation of precompiled symbols. SYMBOL(Alien) SYMBOL(Call) SYMBOL(Code) SYMBOL(Delegate) SYMBOL(Float) SYMBOL(Integer) SYMBOL(List) SYMBOL(Lobby) SYMBOL(Object) SYMBOL(Primitive) SYMBOL(String) SYMBOL(Task) */ // All the atoms. template <typename Traits> class Atom; /// Define a primitive as an Atom parametrized with a traits. # define DEFINE(What, Name) \ struct What ## _traits; \ typedef Atom< What ## _traits > Name; \ typedef libport::shared_ptr < Name, true > r ## Name; /* You have to understand that the primitives are defined here. For * example, a Code is manipulated through a rCode (r = ref counted) and in * fact Code is just a typedef for Atom<code_traits>. If you get compilation * errors about non existent members, it's most likely because you did * obj.get_value () instead of obj->get_value (). This is a side effect * of the operator-> used for the ref-counting. Keep that in mind. */ APPLY_ON_ALL_PRIMITIVES_BUT_OBJECT(DEFINE) # undef DEFINE // urbi-exception.hh class IDelegate; class UrbiException; class LookupError; class RedefinitionError; class PrimitiveError; class WrongArgumentType; class WrongArgumentCount; extern rObject nil_class; extern rObject task_class; extern rObject void_class; } // namespace object #endif // !OBJECT_FWD_HH
/** ** \file object/fwd.hh ** \brief Forward declarations of all node-classes of OBJECT ** (needed by the visitors) */ #ifndef OBJECT_FWD_HH # define OBJECT_FWD_HH # include <deque> # include <libport/fwd.hh> # include <libport/shared-ptr.hh> namespace runner { class Runner; } namespace object { // state.hh struct State; // rObject & objects_type. class Object; typedef libport::shared_ptr<Object> rObject; // FIXME: we probably want libport::refcouned smart pointers here typedef libport::shared_ptr<rObject, false> rrObject; typedef std::deque<rObject> objects_type; /// \a Macro should be a binary macro whose first arg, \p What, is /// the lower case C++ name, and the second argument, \p Name, the /// capitalized URBI name. This is used in many different contexts, /// such as defining enums, so we do not use terminators here (; /// etc.): Macro must do it. # define APPLY_ON_ALL_PRIMITIVES_BUT_OBJECT(Macro) \ Macro(alien, Alien) \ Macro(code, Code) \ Macro(delegate, Delegate) \ Macro(dictionary, Dictionary) \ Macro(float, Float) \ Macro(integer, Integer) \ Macro(list, List) \ Macro(lobby, Lobby) \ Macro(primitive, Primitive) \ Macro(string, String) # define APPLY_ON_ALL_PRIMITIVES(Macro) \ APPLY_ON_ALL_PRIMITIVES_BUT_OBJECT(Macro) \ Macro(object, Object) # define APPLY_ON_ALL_ROOT_CLASSES_BUT_OBJECT(Macro) \ APPLY_ON_ALL_PRIMITIVES_BUT_OBJECT(Macro) \ Macro(global, Global) \ Macro(tag, Tag) \ Macro(task, Task) # define APPLY_ON_ALL_ROOT_CLASSES(Macro) \ APPLY_ON_ALL_ROOT_CLASSES_BUT_OBJECT(Macro) \ Macro(object, Object) /* Help the generation of precompiled symbols. SYMBOL(Alien) SYMBOL(Call) SYMBOL(Code) SYMBOL(Delegate) SYMBOL(Float) SYMBOL(Integer) SYMBOL(List) SYMBOL(Lobby) SYMBOL(Object) SYMBOL(Primitive) SYMBOL(String) SYMBOL(Task) */ // All the atoms. template <typename Traits> class Atom; /// Define a primitive as an Atom parametrized with a traits. # define DEFINE(What, Name) \ struct What ## _traits; \ typedef Atom< What ## _traits > Name; \ typedef libport::shared_ptr < Name, true > r ## Name; /* You have to understand that the primitives are defined here. For * example, a Code is manipulated through a rCode (r = ref counted) and in * fact Code is just a typedef for Atom<code_traits>. If you get compilation * errors about non existent members, it's most likely because you did * obj.get_value () instead of obj->get_value (). This is a side effect * of the operator-> used for the ref-counting. Keep that in mind. */ APPLY_ON_ALL_PRIMITIVES_BUT_OBJECT(DEFINE) # undef DEFINE // urbi-exception.hh class IDelegate; class UrbiException; class LookupError; class RedefinitionError; class PrimitiveError; class WrongArgumentType; class WrongArgumentCount; extern rObject nil_class; extern rObject task_class; extern rObject void_class; } // namespace object #endif // !OBJECT_FWD_HH
Define rrObject: smart pointers to Object smart pointers.
Define rrObject: smart pointers to Object smart pointers. * src/object/fwd.hh (rrObject): New. Here. (rObject): The libport::shared_ptr second template argument is now true by default anyway.
C++
bsd-3-clause
urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,aldebaran/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,aldebaran/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi
984161edde1b4df2f7adcde4e0ae7790fb336213
tests/rpc_test.cc
tests/rpc_test.cc
/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. 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. */ /* * Copyright (C) 2016 ScyllaDB */ #include "loopback_socket.hh" #include "rpc/rpc.hh" #include "test-utils.hh" #include "core/thread.hh" struct serializer { }; template <typename T, typename Output> inline void write_arithmetic_type(Output& out, T v) { static_assert(std::is_arithmetic<T>::value, "must be arithmetic type"); return out.write(reinterpret_cast<const char*>(&v), sizeof(T)); } template <typename T, typename Input> inline T read_arithmetic_type(Input& in) { static_assert(std::is_arithmetic<T>::value, "must be arithmetic type"); T v; in.read(reinterpret_cast<char*>(&v), sizeof(T)); return v; } template <typename Output> inline void write(serializer, Output& output, int32_t v) { return write_arithmetic_type(output, v); } template <typename Output> inline void write(serializer, Output& output, uint32_t v) { return write_arithmetic_type(output, v); } template <typename Output> inline void write(serializer, Output& output, int64_t v) { return write_arithmetic_type(output, v); } template <typename Output> inline void write(serializer, Output& output, uint64_t v) { return write_arithmetic_type(output, v); } template <typename Output> inline void write(serializer, Output& output, double v) { return write_arithmetic_type(output, v); } template <typename Input> inline int32_t read(serializer, Input& input, rpc::type<int32_t>) { return read_arithmetic_type<int32_t>(input); } template <typename Input> inline uint32_t read(serializer, Input& input, rpc::type<uint32_t>) { return read_arithmetic_type<uint32_t>(input); } template <typename Input> inline uint64_t read(serializer, Input& input, rpc::type<uint64_t>) { return read_arithmetic_type<uint64_t>(input); } template <typename Input> inline uint64_t read(serializer, Input& input, rpc::type<int64_t>) { return read_arithmetic_type<int64_t>(input); } template <typename Input> inline double read(serializer, Input& input, rpc::type<double>) { return read_arithmetic_type<double>(input); } template <typename Output> inline void write(serializer, Output& out, const sstring& v) { write_arithmetic_type(out, uint32_t(v.size())); out.write(v.c_str(), v.size()); } template <typename Input> inline sstring read(serializer, Input& in, rpc::type<sstring>) { auto size = read_arithmetic_type<uint32_t>(in); sstring ret(sstring::initialized_later(), size); in.read(ret.begin(), size); return ret; } using test_rpc_proto = rpc::protocol<serializer>; using connect_fn = std::function<test_rpc_proto::client (ipv4_addr addr)>; class rpc_socket_impl : public net::socket_impl { loopback_connection_factory& _factory; public: rpc_socket_impl(loopback_connection_factory& factory) : _factory(factory) { } virtual future<connected_socket> connect(socket_address sa, socket_address local) override { return _factory.make_new_connection(); } virtual void shutdown() override { } }; future<> with_rpc_env(rpc::resource_limits resource_limits, std::function<future<> (test_rpc_proto& proto, test_rpc_proto::server& server, connect_fn connect)> test_fn) { struct state { test_rpc_proto proto{serializer()}; loopback_connection_factory lcf; std::unique_ptr<test_rpc_proto::server> server; }; return do_with(state(), [=] (state& s) { s.server = std::make_unique<test_rpc_proto::server>(s.proto, s.lcf.get_server_socket(), resource_limits); auto make_client = [&s] (ipv4_addr addr) { auto socket = seastar::socket(std::make_unique<rpc_socket_impl>(s.lcf)); return test_rpc_proto::client(s.proto, std::move(socket), addr); }; return test_fn(s.proto, *s.server, make_client).finally([&] { return s.server->stop(); }); }); } SEASTAR_TEST_CASE(test_rpc_connect) { return with_rpc_env({}, [] (test_rpc_proto& proto, test_rpc_proto::server& s, connect_fn connect) { return seastar::async([&proto, &s, connect] { auto c1 = connect(ipv4_addr()); auto sum = proto.register_handler(1, [](int a, int b) { return make_ready_future<int>(a+b); }); auto result = sum(c1, 2, 3).get0(); BOOST_REQUIRE_EQUAL(result, 2 + 3); c1.stop().get(); }); }); }
/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. 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. */ /* * Copyright (C) 2016 ScyllaDB */ #include "loopback_socket.hh" #include "rpc/rpc.hh" #include "test-utils.hh" #include "core/thread.hh" struct serializer { }; template <typename T, typename Output> inline void write_arithmetic_type(Output& out, T v) { static_assert(std::is_arithmetic<T>::value, "must be arithmetic type"); return out.write(reinterpret_cast<const char*>(&v), sizeof(T)); } template <typename T, typename Input> inline T read_arithmetic_type(Input& in) { static_assert(std::is_arithmetic<T>::value, "must be arithmetic type"); T v; in.read(reinterpret_cast<char*>(&v), sizeof(T)); return v; } template <typename Output> inline void write(serializer, Output& output, int32_t v) { return write_arithmetic_type(output, v); } template <typename Output> inline void write(serializer, Output& output, uint32_t v) { return write_arithmetic_type(output, v); } template <typename Output> inline void write(serializer, Output& output, int64_t v) { return write_arithmetic_type(output, v); } template <typename Output> inline void write(serializer, Output& output, uint64_t v) { return write_arithmetic_type(output, v); } template <typename Output> inline void write(serializer, Output& output, double v) { return write_arithmetic_type(output, v); } template <typename Input> inline int32_t read(serializer, Input& input, rpc::type<int32_t>) { return read_arithmetic_type<int32_t>(input); } template <typename Input> inline uint32_t read(serializer, Input& input, rpc::type<uint32_t>) { return read_arithmetic_type<uint32_t>(input); } template <typename Input> inline uint64_t read(serializer, Input& input, rpc::type<uint64_t>) { return read_arithmetic_type<uint64_t>(input); } template <typename Input> inline uint64_t read(serializer, Input& input, rpc::type<int64_t>) { return read_arithmetic_type<int64_t>(input); } template <typename Input> inline double read(serializer, Input& input, rpc::type<double>) { return read_arithmetic_type<double>(input); } template <typename Output> inline void write(serializer, Output& out, const sstring& v) { write_arithmetic_type(out, uint32_t(v.size())); out.write(v.c_str(), v.size()); } template <typename Input> inline sstring read(serializer, Input& in, rpc::type<sstring>) { auto size = read_arithmetic_type<uint32_t>(in); sstring ret(sstring::initialized_later(), size); in.read(ret.begin(), size); return ret; } using test_rpc_proto = rpc::protocol<serializer>; using connect_fn = std::function<test_rpc_proto::client (ipv4_addr addr)>; class rpc_socket_impl : public net::socket_impl { loopback_connection_factory& _factory; promise<connected_socket> _p; bool _connect; public: rpc_socket_impl(loopback_connection_factory& factory, bool connect) : _factory(factory), _connect(connect) { } virtual future<connected_socket> connect(socket_address sa, socket_address local) override { return _connect ? _factory.make_new_connection() : _p.get_future(); } virtual void shutdown() override { if (!_connect) { _p.set_exception(std::make_exception_ptr(std::system_error(ECONNABORTED, std::system_category()))); } } }; future<> with_rpc_env(rpc::resource_limits resource_limits, bool connect, std::function<future<> (test_rpc_proto& proto, test_rpc_proto::server& server, connect_fn connect)> test_fn) { struct state { test_rpc_proto proto{serializer()}; loopback_connection_factory lcf; std::unique_ptr<test_rpc_proto::server> server; }; return do_with(state(), [=] (state& s) { s.server = std::make_unique<test_rpc_proto::server>(s.proto, s.lcf.get_server_socket(), resource_limits); auto make_client = [&s, connect] (ipv4_addr addr) { auto socket = seastar::socket(std::make_unique<rpc_socket_impl>(s.lcf, connect)); return test_rpc_proto::client(s.proto, std::move(socket), addr); }; return test_fn(s.proto, *s.server, make_client).finally([&] { return s.server->stop(); }); }); } SEASTAR_TEST_CASE(test_rpc_connect) { return with_rpc_env({}, true, [] (test_rpc_proto& proto, test_rpc_proto::server& s, connect_fn connect) { return seastar::async([&proto, &s, connect] { auto c1 = connect(ipv4_addr()); auto sum = proto.register_handler(1, [](int a, int b) { return make_ready_future<int>(a+b); }); auto result = sum(c1, 2, 3).get0(); BOOST_REQUIRE_EQUAL(result, 2 + 3); c1.stop().get(); }); }); } SEASTAR_TEST_CASE(test_rpc_connect_abort) { return with_rpc_env({}, false, [] (test_rpc_proto& proto, test_rpc_proto::server& s, connect_fn connect) { return seastar::async([&proto, &s, connect] { auto c1 = connect(ipv4_addr()); auto f = proto.register_handler(1, []() { return make_ready_future<>(); }); c1.stop().get0(); try { f(c1).get0(); BOOST_REQUIRE(false); } catch (...) {} }); }); }
Add unit test for cancel connection attempt
rpc: Add unit test for cancel connection attempt Signed-off-by: Duarte Nunes <[email protected]>
C++
apache-2.0
cloudius-systems/seastar,syuu1228/seastar,kjniemi/seastar,dreamsxin/seastar,dreamsxin/seastar,syuu1228/seastar,avikivity/seastar,avikivity/seastar,kjniemi/seastar,avikivity/seastar,scylladb/seastar,scylladb/seastar,scylladb/seastar,cloudius-systems/seastar,syuu1228/seastar,dreamsxin/seastar,cloudius-systems/seastar,kjniemi/seastar
eef41d7f998e0e6776589ae4d9bcfd228d56dd73
xchainer/python/array.cc
xchainer/python/array.cc
#include "xchainer/python/array.h" #include <algorithm> #include <cstdint> #include <pybind11/numpy.h> #include <pybind11/operators.h> #include "xchainer/array.h" #include "xchainer/constant.h" #include "xchainer/dtype.h" #include "xchainer/error.h" #include "xchainer/python/common.h" namespace xchainer { namespace py = pybind11; namespace { // TODO(beam2d): The current binding has an overhead on wrapping ArrayBodyPtr by Array, which copies shared_ptr. One // simple way to avoid this overhead is to use reinterpret_cast<Array&>(ptr). This cast is valid if ArrayBodyPtr (i.e., // shared_ptr) satisfies "standard layout" conditions. We can test if ArrayBodyPtr satisfies these conditions by // std::is_standard_layout (see http://en.cppreference.com/w/cpp/types/is_standard_layout#Notes). using ArrayBodyPtr = std::shared_ptr<internal::ArrayBody>; using ConstArrayBodyPtr = std::shared_ptr<const internal::ArrayBody>; Dtype NumpyDtypeToDtype(const py::dtype& npdtype) { switch (npdtype.kind()) { case 'b': return Dtype::kBool; case 'i': switch (npdtype.itemsize()) { case 1: return Dtype::kInt8; case 2: return Dtype::kInt16; case 4: return Dtype::kInt32; case 8: return Dtype::kInt64; default: break; } break; case 'u': switch (npdtype.itemsize()) { case 1: return Dtype::kUInt8; default: break; } break; case 'f': switch (npdtype.itemsize()) { case 4: return Dtype::kFloat32; case 8: return Dtype::kFloat64; default: break; } break; default: break; } throw DtypeError("unsupported NumPy dtype"); } ArrayBodyPtr MakeArray(const Shape& shape, Dtype dtype, py::list list) { auto total_size = shape.GetTotalSize(); auto bytes = GetElementSize(dtype) * total_size; if (static_cast<size_t>(total_size) != list.size()) { throw DimensionError("Invalid data length"); } // Allocate a buffer and copy data std::shared_ptr<void> ptr = std::make_unique<uint8_t[]>(bytes); VisitDtype(dtype, [&](auto pt) { using T = typename decltype(pt)::type; std::transform(list.begin(), list.end(), static_cast<T*>(ptr.get()), [](auto& item) { return py::cast<T>(item); }); }); return Array::FromBuffer(shape, dtype, ptr).move_body(); } ArrayBodyPtr MakeArray(py::array array) { if ((array.flags() & py::array::c_style) == 0) { throw DimensionError("cannot convert non-contiguous NumPy array to Array"); } Dtype dtype = NumpyDtypeToDtype(array.dtype()); py::buffer_info info = array.request(); Shape shape(info.shape); // data holds the copy of py::array which in turn references the NumPy array and the buffer is therefore not released std::shared_ptr<void> data(std::make_shared<py::array>(std::move(array)), array.mutable_data()); return Array::FromBuffer(shape, dtype, data).move_body(); } py::buffer_info MakeNumpyArrayFromArray(internal::ArrayBody& self) { // Used as a temporary accessor Array array{std::move(ArrayBodyPtr(&self, [](internal::ArrayBody* ptr) { (void)ptr; // unused }))}; if (!array.is_contiguous()) { throw DimensionError("cannot convert non-contiguous Array to NumPy array"); } int64_t itemsize{GetElementSize(array.dtype())}; const Shape& shape = array.shape(); // compute C-contiguous strides size_t ndim = array.ndim(); std::vector<size_t> strides(ndim); if (ndim > 0) { std::partial_sum(shape.crbegin(), shape.crend() - 1, strides.rbegin() + 1, std::multiplies<size_t>()); strides.back() = 1; std::transform(strides.crbegin(), strides.crend(), strides.rbegin(), [&itemsize](size_t item) { return item * itemsize; }); } return py::buffer_info(array.data().get(), itemsize, std::string(1, GetCharCode(array.dtype())), ndim, shape, strides); } } // namespace void InitXchainerArray(pybind11::module& m) { py::class_<internal::ArrayBody, ArrayBodyPtr>{m, "Array", py::buffer_protocol()} .def(py::init(py::overload_cast<const Shape&, Dtype, py::list>(&MakeArray))) .def(py::init(py::overload_cast<py::array>(&MakeArray))) .def_buffer(&MakeNumpyArrayFromArray) .def("view", [](const ArrayBodyPtr& self) { // Duplicate the array body return std::make_shared<internal::ArrayBody>(*self); }) .def("__iadd__", [](const ArrayBodyPtr& self, const ArrayBodyPtr& rhs) { return (Array{self} += Array{rhs}).move_body(); }) .def("__imul__", [](const ArrayBodyPtr& self, const ArrayBodyPtr& rhs) { return (Array{self} *= Array{rhs}).move_body(); }) .def("__add__", [](const ArrayBodyPtr& self, const ArrayBodyPtr& rhs) { return (Array{self} + Array{rhs}).move_body(); }) .def("__mul__", [](const ArrayBodyPtr& self, const ArrayBodyPtr& rhs) { return (Array{self} * Array{rhs}).move_body(); }) .def("__repr__", [](const ArrayBodyPtr& self) { return Array{self}.ToString(); }) .def("copy", [](const ArrayBodyPtr& self) { return Array{self}.Copy().move_body(); }) .def("as_constant", [](const ArrayBodyPtr& self, bool copy) { return Array{self}.AsConstant(copy ? CopyKind::kCopy : CopyKind::kView).move_body(); }, py::arg("copy") = false) .def("as_constant", [](const ArrayBodyPtr& self, const std::vector<GraphId>& graph_ids, bool copy) { return Array{self}.AsConstant(graph_ids, copy ? CopyKind::kCopy : CopyKind::kView).move_body(); }, py::arg().noconvert(), py::arg("copy") = false) .def("require_grad", [](const ArrayBodyPtr& self, const GraphId& graph_id) { return Array{self}.RequireGrad(graph_id).move_body(); }, py::arg("graph_id") = kDefaultGraphId) .def("is_grad_required", [](const ArrayBodyPtr& self, const GraphId& graph_id) { return Array{self}.IsGradRequired(graph_id); }, py::arg("graph_id") = kDefaultGraphId) .def("get_grad", [](const ArrayBodyPtr& self, const GraphId& graph_id) -> ConstArrayBodyPtr { const nonstd::optional<Array>& grad = Array{self}.GetGrad(graph_id); if (grad.has_value()) { return grad->body(); } else { return nullptr; } }, py::arg("graph_id") = kDefaultGraphId) .def("set_grad", [](const ArrayBodyPtr& self, const ArrayBodyPtr& grad, const GraphId& graph_id) { auto array = Array{self}; if (grad) { array.SetGrad(Array{grad}, graph_id); } else { array.ClearGrad(graph_id); } }, py::arg("grad"), py::arg("graph_id") = kDefaultGraphId) .def_property_readonly("dtype", [](const ArrayBodyPtr& self) { return Array{self}.dtype(); }) .def_property_readonly("element_bytes", [](const ArrayBodyPtr& self) { return Array{self}.element_bytes(); }) .def_property_readonly("is_contiguous", [](const ArrayBodyPtr& self) { return Array{self}.is_contiguous(); }) .def_property_readonly("ndim", [](const ArrayBodyPtr& self) { return Array{self}.ndim(); }) .def_property_readonly("offset", [](const ArrayBodyPtr& self) { return Array{self}.offset(); }) .def_property_readonly("shape", [](const ArrayBodyPtr& self) { return Array{self}.shape(); }) .def_property_readonly("total_bytes", [](const ArrayBodyPtr& self) { return Array{self}.GetTotalBytes(); }) .def_property_readonly("total_size", [](const ArrayBodyPtr& self) { return Array{self}.GetTotalSize(); }) .def_property_readonly("_debug_data_memory_address", // These methods starting with `_debug_` are stubs for testing [](const ArrayBodyPtr& self) { return reinterpret_cast<std::uintptr_t>(Array{self}.data().get()); }) .def_property_readonly("_debug_flat_data", [](const ArrayBodyPtr& self) { py::list list; Array array{self}; // Copy data into the list VisitDtype(array.dtype(), [&array, &list](auto pt) { using T = typename decltype(pt)::type; auto size = array.GetTotalSize(); const T& data = *std::static_pointer_cast<const T>(array.data()); for (int64_t i = 0; i < size; ++i) { list.append((&data)[i]); } }); return list; }); } } // namespace xchainer
#include "xchainer/python/array.h" #include <algorithm> #include <cstdint> #include <pybind11/numpy.h> #include <pybind11/operators.h> #include "xchainer/array.h" #include "xchainer/constant.h" #include "xchainer/device.h" #include "xchainer/dtype.h" #include "xchainer/error.h" #include "xchainer/python/common.h" namespace xchainer { namespace py = pybind11; namespace { // TODO(beam2d): The current binding has an overhead on wrapping ArrayBodyPtr by Array, which copies shared_ptr. One // simple way to avoid this overhead is to use reinterpret_cast<Array&>(ptr). This cast is valid if ArrayBodyPtr (i.e., // shared_ptr) satisfies "standard layout" conditions. We can test if ArrayBodyPtr satisfies these conditions by // std::is_standard_layout (see http://en.cppreference.com/w/cpp/types/is_standard_layout#Notes). using ArrayBodyPtr = std::shared_ptr<internal::ArrayBody>; using ConstArrayBodyPtr = std::shared_ptr<const internal::ArrayBody>; Dtype NumpyDtypeToDtype(const py::dtype& npdtype) { switch (npdtype.kind()) { case 'b': return Dtype::kBool; case 'i': switch (npdtype.itemsize()) { case 1: return Dtype::kInt8; case 2: return Dtype::kInt16; case 4: return Dtype::kInt32; case 8: return Dtype::kInt64; default: break; } break; case 'u': switch (npdtype.itemsize()) { case 1: return Dtype::kUInt8; default: break; } break; case 'f': switch (npdtype.itemsize()) { case 4: return Dtype::kFloat32; case 8: return Dtype::kFloat64; default: break; } break; default: break; } throw DtypeError("unsupported NumPy dtype"); } ArrayBodyPtr MakeArray(const Shape& shape, Dtype dtype, py::list list) { auto total_size = shape.GetTotalSize(); auto bytes = GetElementSize(dtype) * total_size; if (static_cast<size_t>(total_size) != list.size()) { throw DimensionError("Invalid data length"); } // Allocate a buffer and copy data std::shared_ptr<void> ptr = std::make_unique<uint8_t[]>(bytes); VisitDtype(dtype, [&](auto pt) { using T = typename decltype(pt)::type; std::transform(list.begin(), list.end(), static_cast<T*>(ptr.get()), [](auto& item) { return py::cast<T>(item); }); }); return Array::FromBuffer(shape, dtype, ptr).move_body(); } ArrayBodyPtr MakeArray(py::array array) { if ((array.flags() & py::array::c_style) == 0) { throw DimensionError("cannot convert non-contiguous NumPy array to Array"); } Dtype dtype = NumpyDtypeToDtype(array.dtype()); py::buffer_info info = array.request(); Shape shape(info.shape); // data holds the copy of py::array which in turn references the NumPy array and the buffer is therefore not released std::shared_ptr<void> data(std::make_shared<py::array>(std::move(array)), array.mutable_data()); return Array::FromBuffer(shape, dtype, data).move_body(); } py::buffer_info MakeNumpyArrayFromArray(internal::ArrayBody& self) { // Used as a temporary accessor Array array{std::move(ArrayBodyPtr(&self, [](internal::ArrayBody* ptr) { (void)ptr; // unused }))}; if (!array.is_contiguous()) { throw DimensionError("cannot convert non-contiguous Array to NumPy array"); } int64_t itemsize{GetElementSize(array.dtype())}; const Shape& shape = array.shape(); // compute C-contiguous strides size_t ndim = array.ndim(); std::vector<size_t> strides(ndim); if (ndim > 0) { std::partial_sum(shape.crbegin(), shape.crend() - 1, strides.rbegin() + 1, std::multiplies<size_t>()); strides.back() = 1; std::transform(strides.crbegin(), strides.crend(), strides.rbegin(), [&itemsize](size_t item) { return item * itemsize; }); } return py::buffer_info(array.data().get(), itemsize, std::string(1, GetCharCode(array.dtype())), ndim, shape, strides); } } // namespace void InitXchainerArray(pybind11::module& m) { py::class_<internal::ArrayBody, ArrayBodyPtr>{m, "Array", py::buffer_protocol()} .def(py::init(py::overload_cast<const Shape&, Dtype, py::list>(&MakeArray))) .def(py::init(py::overload_cast<py::array>(&MakeArray))) .def_buffer(&MakeNumpyArrayFromArray) .def("view", [](const ArrayBodyPtr& self) { // Duplicate the array body return std::make_shared<internal::ArrayBody>(*self); }) .def("__iadd__", [](const ArrayBodyPtr& self, const ArrayBodyPtr& rhs) { return (Array{self} += Array{rhs}).move_body(); }) .def("__imul__", [](const ArrayBodyPtr& self, const ArrayBodyPtr& rhs) { return (Array{self} *= Array{rhs}).move_body(); }) .def("__add__", [](const ArrayBodyPtr& self, const ArrayBodyPtr& rhs) { return (Array{self} + Array{rhs}).move_body(); }) .def("__mul__", [](const ArrayBodyPtr& self, const ArrayBodyPtr& rhs) { return (Array{self} * Array{rhs}).move_body(); }) .def("__repr__", [](const ArrayBodyPtr& self) { return Array{self}.ToString(); }) .def("copy", [](const ArrayBodyPtr& self) { return Array{self}.Copy().move_body(); }) .def("as_constant", [](const ArrayBodyPtr& self, bool copy) { return Array{self}.AsConstant(copy ? CopyKind::kCopy : CopyKind::kView).move_body(); }, py::arg("copy") = false) .def("as_constant", [](const ArrayBodyPtr& self, const std::vector<GraphId>& graph_ids, bool copy) { return Array{self}.AsConstant(graph_ids, copy ? CopyKind::kCopy : CopyKind::kView).move_body(); }, py::arg().noconvert(), py::arg("copy") = false) .def("require_grad", [](const ArrayBodyPtr& self, const GraphId& graph_id) { return Array{self}.RequireGrad(graph_id).move_body(); }, py::arg("graph_id") = kDefaultGraphId) .def("is_grad_required", [](const ArrayBodyPtr& self, const GraphId& graph_id) { return Array{self}.IsGradRequired(graph_id); }, py::arg("graph_id") = kDefaultGraphId) .def("get_grad", [](const ArrayBodyPtr& self, const GraphId& graph_id) -> ConstArrayBodyPtr { const nonstd::optional<Array>& grad = Array{self}.GetGrad(graph_id); if (grad.has_value()) { return grad->body(); } else { return nullptr; } }, py::arg("graph_id") = kDefaultGraphId) .def("set_grad", [](const ArrayBodyPtr& self, const ArrayBodyPtr& grad, const GraphId& graph_id) { auto array = Array{self}; if (grad) { array.SetGrad(Array{grad}, graph_id); } else { array.ClearGrad(graph_id); } }, py::arg("grad"), py::arg("graph_id") = kDefaultGraphId) .def_property_readonly("device", [](const ArrayBodyPtr& self) -> Device& { return Array{self}.device(); }, py::return_value_policy::reference) .def_property_readonly("dtype", [](const ArrayBodyPtr& self) { return Array{self}.dtype(); }) .def_property_readonly("element_bytes", [](const ArrayBodyPtr& self) { return Array{self}.element_bytes(); }) .def_property_readonly("is_contiguous", [](const ArrayBodyPtr& self) { return Array{self}.is_contiguous(); }) .def_property_readonly("ndim", [](const ArrayBodyPtr& self) { return Array{self}.ndim(); }) .def_property_readonly("offset", [](const ArrayBodyPtr& self) { return Array{self}.offset(); }) .def_property_readonly("shape", [](const ArrayBodyPtr& self) { return Array{self}.shape(); }) .def_property_readonly("total_bytes", [](const ArrayBodyPtr& self) { return Array{self}.GetTotalBytes(); }) .def_property_readonly("total_size", [](const ArrayBodyPtr& self) { return Array{self}.GetTotalSize(); }) .def_property_readonly("_debug_data_memory_address", // These methods starting with `_debug_` are stubs for testing [](const ArrayBodyPtr& self) { return reinterpret_cast<std::uintptr_t>(Array{self}.data().get()); }) .def_property_readonly("_debug_flat_data", [](const ArrayBodyPtr& self) { py::list list; Array array{self}; // Copy data into the list VisitDtype(array.dtype(), [&array, &list](auto pt) { using T = typename decltype(pt)::type; auto size = array.GetTotalSize(); const T& data = *std::static_pointer_cast<const T>(array.data()); for (int64_t i = 0; i < size; ++i) { list.append((&data)[i]); } }); return list; }); } } // namespace xchainer
Add Array device attr Python binding
Add Array device attr Python binding
C++
mit
niboshi/chainer,chainer/chainer,jnishi/chainer,okuta/chainer,chainer/chainer,ktnyt/chainer,hvy/chainer,niboshi/chainer,ktnyt/chainer,niboshi/chainer,keisuke-umezawa/chainer,ktnyt/chainer,jnishi/chainer,niboshi/chainer,wkentaro/chainer,wkentaro/chainer,hvy/chainer,tkerola/chainer,jnishi/chainer,ktnyt/chainer,keisuke-umezawa/chainer,chainer/chainer,keisuke-umezawa/chainer,keisuke-umezawa/chainer,pfnet/chainer,okuta/chainer,wkentaro/chainer,chainer/chainer,okuta/chainer,hvy/chainer,jnishi/chainer,wkentaro/chainer,okuta/chainer,hvy/chainer
93518c95458ac52e2c1ee05fdb4991e6059aa333
xs/src/libslic3r/Log.cpp
xs/src/libslic3r/Log.cpp
#include <sstream> #include <iostream> #include <string> #include <iomanip> #include "Log.hpp" /// Local class to suppress output class NullStream : public std::streambuf { public: int overflow(int c) { return c; } }; namespace Slic3r { static NullStream log_null; static std::ostream null_log(&log_null); std::unique_ptr<_Log> slic3r_log {_Log::make_log()}; _Log::_Log() : _out(std::clog) { } _Log::_Log(std::ostream& out) : _out(out) { } bool _Log::_has_log_level(log_t lvl) { if (!this->_inclusive_levels && this->_log_level.find(lvl) != this->_log_level.end()) { return true; } else if (this->_inclusive_levels && *(std::max_element(this->_log_level.cbegin(), this->_log_level.cend())) >= lvl) { return true; } return false; } bool _Log::_has_topic(const std::string& topic) { return this->_topics.find(topic) != this->_topics.end() || this->_topics.size() == 0; } void _Log::fatal_error(const std::string& topic, const std::wstring& message) { this->fatal_error(topic, this->converter.to_bytes(message)); } void _Log::error(const std::string& topic, const std::wstring& message) { this->error(topic, this->converter.to_bytes(message)); } void _Log::warn(const std::string& topic, const std::wstring& message) { this->warn(topic, this->converter.to_bytes(message)); } void _Log::info(const std::string& topic, const std::wstring& message) { this->info(topic, this->converter.to_bytes(message)); } void _Log::debug(const std::string& topic, const std::wstring& message) { this->debug(topic, this->converter.to_bytes(message)); } void _Log::fatal_error(const std::string& topic, const std::string& message) { this->fatal_error(topic) << message << std::endl; } std::ostream& _Log::fatal_error(const std::string& topic) { if (this->_has_log_level(log_t::FERR) && this->_has_topic(topic)) { _out << topic << std::setfill(' ') << std::setw(6) << "FERR" << ": "; return _out; } return null_log; } void _Log::error(const std::string& topic, const std::string& message) { this->error(topic) << message << std::endl; } std::ostream& _Log::error(const std::string& topic) { if (this->_has_log_level(log_t::ERR) && this->_has_topic(topic)) { _out << topic << std::setfill(' ') << std::setw(6) << "ERR" << ": "; return _out; } return null_log; } void _Log::info(const std::string& topic, const std::string& message) { this->info(topic) << message << std::endl; } std::ostream& _Log::info(const std::string& topic) { if (this->_has_log_level(log_t::INFO) && this->_has_topic(topic)) { _out << topic << std::setfill(' ') << std::setw(6) << "INFO" << ": "; return _out; } return null_log; } void _Log::warn(const std::string& topic, const std::string& message) { this->warn(topic) << message << std::endl; } std::ostream& _Log::warn(const std::string& topic) { if (this->_has_log_level(log_t::WARN) && this->_has_topic(topic)) { _out << topic << std::setfill(' ') << std::setw(6) << "WARN" << ": "; return _out; } return null_log; } void _Log::debug(const std::string& topic, const std::string& message) { this->debug(topic) << message << std::endl; } std::ostream& _Log::debug(const std::string& topic) { if (this->_has_log_level(log_t::DEBUG) && this->_has_topic(topic)) { _out << topic << std::setfill(' ') << std::setw(6) << "DEBUG" << ": "; return _out; } return null_log; } void _Log::raw(const std::string& message) { this->raw() << message << std::endl; } void _Log::raw(const std::wstring& message) { this->raw(this->converter.to_bytes(message)); } std::ostream& _Log::raw() { return _out; } void _Log::set_level(log_t level) { if (this->_inclusive_levels) { this->_log_level.clear(); this->_log_level.insert(level); } else if (level == log_t::ALL) { this->_log_level.insert(log_t::FERR); this->_log_level.insert(log_t::ERR); this->_log_level.insert(log_t::WARN); this->_log_level.insert(log_t::INFO); this->_log_level.insert(log_t::DEBUG); } else { this->_log_level.insert(level); } } void _Log::clear_level(log_t level) { if (level == log_t::ALL) { this->_log_level.clear(); } else { if (this->_log_level.find(level) != this->_log_level.end()) this->_log_level.erase(level); } } void _Log::clear_topic(const std::string& topic) { if (topic == "") { this->_topics.clear(); } else { if (this->_topics.find(topic) != this->_topics.end()) this->_topics.erase(topic); } } } // Slic3r
#include <sstream> #include <iostream> #include <string> #include <iomanip> #include <algorithm> #include "Log.hpp" /// Local class to suppress output class NullStream : public std::streambuf { public: int overflow(int c) { return c; } }; namespace Slic3r { static NullStream log_null; static std::ostream null_log(&log_null); std::unique_ptr<_Log> slic3r_log {_Log::make_log()}; _Log::_Log() : _out(std::clog) { } _Log::_Log(std::ostream& out) : _out(out) { } bool _Log::_has_log_level(log_t lvl) { if (!this->_inclusive_levels && this->_log_level.find(lvl) != this->_log_level.end()) { return true; } else if (this->_inclusive_levels && *(std::max_element(this->_log_level.cbegin(), this->_log_level.cend())) >= lvl) { return true; } return false; } bool _Log::_has_topic(const std::string& topic) { return this->_topics.find(topic) != this->_topics.end() || this->_topics.size() == 0; } void _Log::fatal_error(const std::string& topic, const std::wstring& message) { this->fatal_error(topic, this->converter.to_bytes(message)); } void _Log::error(const std::string& topic, const std::wstring& message) { this->error(topic, this->converter.to_bytes(message)); } void _Log::warn(const std::string& topic, const std::wstring& message) { this->warn(topic, this->converter.to_bytes(message)); } void _Log::info(const std::string& topic, const std::wstring& message) { this->info(topic, this->converter.to_bytes(message)); } void _Log::debug(const std::string& topic, const std::wstring& message) { this->debug(topic, this->converter.to_bytes(message)); } void _Log::fatal_error(const std::string& topic, const std::string& message) { this->fatal_error(topic) << message << std::endl; } std::ostream& _Log::fatal_error(const std::string& topic) { if (this->_has_log_level(log_t::FERR) && this->_has_topic(topic)) { _out << topic << std::setfill(' ') << std::setw(6) << "FERR" << ": "; return _out; } return null_log; } void _Log::error(const std::string& topic, const std::string& message) { this->error(topic) << message << std::endl; } std::ostream& _Log::error(const std::string& topic) { if (this->_has_log_level(log_t::ERR) && this->_has_topic(topic)) { _out << topic << std::setfill(' ') << std::setw(6) << "ERR" << ": "; return _out; } return null_log; } void _Log::info(const std::string& topic, const std::string& message) { this->info(topic) << message << std::endl; } std::ostream& _Log::info(const std::string& topic) { if (this->_has_log_level(log_t::INFO) && this->_has_topic(topic)) { _out << topic << std::setfill(' ') << std::setw(6) << "INFO" << ": "; return _out; } return null_log; } void _Log::warn(const std::string& topic, const std::string& message) { this->warn(topic) << message << std::endl; } std::ostream& _Log::warn(const std::string& topic) { if (this->_has_log_level(log_t::WARN) && this->_has_topic(topic)) { _out << topic << std::setfill(' ') << std::setw(6) << "WARN" << ": "; return _out; } return null_log; } void _Log::debug(const std::string& topic, const std::string& message) { this->debug(topic) << message << std::endl; } std::ostream& _Log::debug(const std::string& topic) { if (this->_has_log_level(log_t::DEBUG) && this->_has_topic(topic)) { _out << topic << std::setfill(' ') << std::setw(6) << "DEBUG" << ": "; return _out; } return null_log; } void _Log::raw(const std::string& message) { this->raw() << message << std::endl; } void _Log::raw(const std::wstring& message) { this->raw(this->converter.to_bytes(message)); } std::ostream& _Log::raw() { return _out; } void _Log::set_level(log_t level) { if (this->_inclusive_levels) { this->_log_level.clear(); this->_log_level.insert(level); } else if (level == log_t::ALL) { this->_log_level.insert(log_t::FERR); this->_log_level.insert(log_t::ERR); this->_log_level.insert(log_t::WARN); this->_log_level.insert(log_t::INFO); this->_log_level.insert(log_t::DEBUG); } else { this->_log_level.insert(level); } } void _Log::clear_level(log_t level) { if (level == log_t::ALL) { this->_log_level.clear(); } else { if (this->_log_level.find(level) != this->_log_level.end()) this->_log_level.erase(level); } } void _Log::clear_topic(const std::string& topic) { if (topic == "") { this->_topics.clear(); } else { if (this->_topics.find(topic) != this->_topics.end()) this->_topics.erase(topic); } } } // Slic3r
Include STL algorithm
Include STL algorithm
C++
agpl-3.0
curieos/Slic3r,curieos/Slic3r,curieos/Slic3r,curieos/Slic3r,alexrj/Slic3r,pieis2pi/Slic3r,alexrj/Slic3r,pieis2pi/Slic3r,pieis2pi/Slic3r,alexrj/Slic3r,alexrj/Slic3r,alexrj/Slic3r,curieos/Slic3r,curieos/Slic3r,pieis2pi/Slic3r,pieis2pi/Slic3r,alexrj/Slic3r,pieis2pi/Slic3r
b538f33459090fb515a78e6d962301b6f761df4e
xs/src/libslic3r/Log.hpp
xs/src/libslic3r/Log.hpp
#ifndef slic3r_LOG_HPP #define slic3r_LOG_HPP #include <string> #include <vector> #include <sstream> #include <iostream> #include <memory> #include <locale> #include <set> #include <codecvt> // good until c++17 namespace Slic3r { /// All available logging levels. enum class log_t : uint8_t { FERR = 0, ERR = 4, WARN = 8, INFO = 16, DEBUG = 32, ALL = 255 }; inline bool operator>(const log_t lhs, const log_t rhs) { return static_cast<uint8_t>(lhs) > static_cast<uint8_t>(rhs); } inline bool operator<(const log_t lhs, const log_t rhs) { return static_cast<uint8_t>(lhs) < static_cast<uint8_t>(rhs); } inline bool operator>=(const log_t lhs, const log_t rhs) { return static_cast<uint8_t>(lhs) > static_cast<uint8_t>(rhs) || lhs == rhs; } inline bool operator<=(const log_t lhs, const log_t rhs) { return static_cast<uint8_t>(lhs) < static_cast<uint8_t>(rhs) || lhs == rhs; } /// Singleton instance implementing logging functionality in Slic3r /// Basic functionality is stubbed in currently, may pass through to Boost::Log /// eventually. class _Log { public: static std::unique_ptr<_Log> make_log() { std::unique_ptr<_Log> tmp {new _Log()}; return tmp; } static std::unique_ptr<_Log> make_log(std::ostream& out) { std::unique_ptr<_Log> tmp {new _Log(out)}; return tmp; } void fatal_error(const std::string& topic, const std::string& message); void fatal_error(const std::string& topic, const std::wstring& message); std::ostream& fatal_error(const std::string& topic); void error(const std::string& topic, const std::string& message); void error(const std::string& topic, const std::wstring& message); std::ostream& error(const std::string& topic); void info(const std::string& topic, const std::string& message); void info(const std::string& topic, const std::wstring& message); std::ostream& info(const std::string& topic); void debug(const std::string& topic, const std::string& message); void debug(const std::string& topic, const std::wstring& message); std::ostream& debug(const std::string& topic); void warn(const std::string& topic, const std::string& message); void warn(const std::string& topic, const std::wstring& message); std::ostream& warn(const std::string& topic); void raw(const std::string& message); void raw(const std::wstring& message); std::ostream& raw(); template <class T> void debug_svg(const std::string& topic, const T& path, bool append = true); template <class T> void debug_svg(const std::string& topic, const T* path, bool append = true); void set_level(log_t level); void clear_level(log_t level); void set_inclusive(bool v) { this->_inclusive_levels = v; } // _Log(_Log const&) = delete; // void operator=(_Log const&) = delete; private: std::ostream& _out; _Log(); _Log(std::ostream& out); bool _inclusive_levels { true }; std::set<log_t> _log_level { }; std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter; bool _has_log_level(log_t lvl); }; /// Global log reference; initialized in Log.cpp extern std::unique_ptr<_Log> slic3r_log; /// Static class for referencing the various logging functions. Refers to /// class Log { public: static void fatal_error(std::string topic, std::wstring message) { slic3r_log->fatal_error(topic, message); } static void error(std::string topic, std::wstring message) { std::cerr << topic << " ERR" << ": "; std::wcerr << message << std::endl; } static void error(std::string topic, std::string message) { std::cerr << topic << " ERR" << ": "; std::cerr << message << std::endl; } static void info(std::string topic, std::wstring message) { std::clog << topic << " INFO" << ": "; std::wclog << message << std::endl; } static void info(std::string topic, std::string message) { std::clog << topic << " INFO" << ": "; std::clog << message << std::endl; } static void warn(std::string topic, std::wstring message) { std::cerr << topic << " WARN" << ": "; std::wcerr << message << std::endl; } static void warn(std::string topic, std::string message) { std::cerr << topic << " WARN" << ": "; std::cerr << message << std::endl; } static void debug(std::string topic, std::wstring message) { std::cerr << topic << " DEBUG" << ": "; std::wcerr << message << std::endl; } static void debug(std::string topic, std::string message) { std::cerr << topic << " DEBUG" << ": "; std::cerr << message << std::endl; } static std::ostream& error(std::string topic) { std::cerr << topic << " ERR" << ": "; return std::cerr; } static std::ostream& debug(std::string topic) { std::cerr << topic << " DEBUG" << ": "; return std::cerr; } static std::ostream& warn(std::string topic) { std::cerr << topic << " WARN" << ": "; return std::cerr; } static std::ostream& info(std::string topic) { std::cerr << topic << " INFO" << ": "; return std::cerr; } /// Unadorned ostream output for multiline constructions. static std::ostream& raw() { return std::cerr; } }; /// Utility debug function to transform a std::vector of anything that /// supports ostream& operator<<() into a std::string. template <typename T> std::string log_string(const std::vector<T>& in) { std::stringstream ss; bool first {true}; ss << "[ "; for (auto& c : in) { if (!first) { ss << ", "; } ss << c; first = false; } ss << " ]"; return ss.str(); } } #endif // slic3r_LOG_HPP
#ifndef slic3r_LOG_HPP #define slic3r_LOG_HPP #include <string> #include <vector> #include <sstream> #include <iostream> #include <memory> #include <locale> #include <set> #include <codecvt> // good until c++17 namespace Slic3r { /// All available logging levels. enum class log_t : uint8_t { FERR = 0, ERR = 4, WARN = 8, INFO = 16, DEBUG = 32, ALL = 255 }; inline bool operator>(const log_t lhs, const log_t rhs) { return static_cast<uint8_t>(lhs) > static_cast<uint8_t>(rhs); } inline bool operator<(const log_t lhs, const log_t rhs) { return static_cast<uint8_t>(lhs) < static_cast<uint8_t>(rhs); } inline bool operator>=(const log_t lhs, const log_t rhs) { return static_cast<uint8_t>(lhs) > static_cast<uint8_t>(rhs) || lhs == rhs; } inline bool operator<=(const log_t lhs, const log_t rhs) { return static_cast<uint8_t>(lhs) < static_cast<uint8_t>(rhs) || lhs == rhs; } /// Singleton instance implementing logging functionality in Slic3r /// Basic functionality is stubbed in currently, may pass through to Boost::Log /// eventually. class _Log { public: static std::unique_ptr<_Log> make_log() { std::unique_ptr<_Log> tmp {new _Log()}; return tmp; } static std::unique_ptr<_Log> make_log(std::ostream& out) { std::unique_ptr<_Log> tmp {new _Log(out)}; return tmp; } void fatal_error(const std::string& topic, const std::string& message); void fatal_error(const std::string& topic, const std::wstring& message); std::ostream& fatal_error(const std::string& topic); void error(const std::string& topic, const std::string& message); void error(const std::string& topic, const std::wstring& message); std::ostream& error(const std::string& topic); void info(const std::string& topic, const std::string& message); void info(const std::string& topic, const std::wstring& message); std::ostream& info(const std::string& topic); void debug(const std::string& topic, const std::string& message); void debug(const std::string& topic, const std::wstring& message); std::ostream& debug(const std::string& topic); void warn(const std::string& topic, const std::string& message); void warn(const std::string& topic, const std::wstring& message); std::ostream& warn(const std::string& topic); void raw(const std::string& message); void raw(const std::wstring& message); std::ostream& raw(); template <class T> void debug_svg(const std::string& topic, const T& path, bool append = true); template <class T> void debug_svg(const std::string& topic, const T* path, bool append = true); void set_level(log_t level); void clear_level(log_t level); void set_inclusive(bool v) { this->_inclusive_levels = v; } // _Log(_Log const&) = delete; // void operator=(_Log const&) = delete; private: std::ostream& _out; _Log(); _Log(std::ostream& out); bool _inclusive_levels { true }; std::set<log_t> _log_level { }; std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter; bool _has_log_level(log_t lvl); }; /// Global log reference; initialized in Log.cpp extern std::unique_ptr<_Log> slic3r_log; /// Static class for referencing the various logging functions. Refers to /// class Log { public: static void fatal_error(std::string topic, std::wstring message) { slic3r_log->fatal_error(topic, message); } static void error(std::string topic, std::wstring message) { slic3r_log->error(topic, message); } static void error(std::string topic, std::string message) { slic3r_log->error(topic, message); } static void info(std::string topic, std::wstring message) { slic3r_log->info(topic, message); } static void info(std::string topic, std::string message) { slic3r_log->info(topic, message); } static void warn(std::string topic, std::wstring message) { slic3r_log->warn(topic, message); } static void warn(std::string topic, std::string message) { slic3r_log->warn(topic, message); } static void debug(std::string topic, std::wstring message) { slic3r_log->debug(topic, message); } static void debug(std::string topic, std::string message) { slic3r_log->debug(topic, message); } static std::ostream& error(std::string topic) { return slic3r_log->error(topic); } static std::ostream& debug(std::string topic) { return slic3r_log->debug(topic); } static std::ostream& warn(std::string topic) { return slic3r_log->warn(topic); } static std::ostream& info(std::string topic) { return slic3r_log->info(topic); } /// Unadorned ostream output for multiline constructions. static std::ostream& raw() { return slic3r_log->raw(); } }; /// Utility debug function to transform a std::vector of anything that /// supports ostream& operator<<() into a std::string. template <typename T> std::string log_string(const std::vector<T>& in) { std::stringstream ss; bool first {true}; ss << "[ "; for (auto& c : in) { if (!first) { ss << ", "; } ss << c; first = false; } ss << " ]"; return ss.str(); } } #endif // slic3r_LOG_HPP
Call through to underlying method for static Log methods
Call through to underlying method for static Log methods
C++
agpl-3.0
pieis2pi/Slic3r,pieis2pi/Slic3r,curieos/Slic3r,pieis2pi/Slic3r,curieos/Slic3r,alexrj/Slic3r,alexrj/Slic3r,alexrj/Slic3r,curieos/Slic3r,curieos/Slic3r,curieos/Slic3r,alexrj/Slic3r,pieis2pi/Slic3r,pieis2pi/Slic3r,alexrj/Slic3r,alexrj/Slic3r,curieos/Slic3r,pieis2pi/Slic3r
c9688b5aefc1106f72a2e09afc1dd3a46a69c323
okui/src/applications/Android.cpp
okui/src/applications/Android.cpp
#include "onair/okui/applications/Android.h" #if ONAIR_ANDROID namespace onair { namespace okui { namespace applications { namespace { std::weak_ptr<jni::JNIContext> gJNIContext; } Android::~Android() { if (_javaHelper) { _javaHelper.reset(); } if (_activity) { _jniEnv->DeleteGlobalRef(_activity); } } void Android::setActivity(JNIEnv* env, jobject activity) { _jniEnv = env; _activity = env->NewGlobalRef(activity); } void Android::initialize() { if (!resourceManager() && _activity) { ONAIR_LOGF_DEBUG("using resources from asset manager"); _jniEnv->PushLocalFrame(10); auto c = _jniEnv->GetObjectClass(_activity); auto m = _jniEnv->GetMethodID(c, "getAssets", "()Landroid/content/res/AssetManager;"); _resourceManager = std::unique_ptr<AssetResourceManager>(_jniEnv, _jniEnv->CallObjectMethod(_activity, m)); setResourceManager(_resourceManager.get()); _jniEnv->PopLocalFrame(nullptr); JavaVM* jvm = nullptr; _jniEnv->GetJavaVM(&jvm); auto existingContext = gJNIContext.lock(); assert(!existingContext || existingContext->jvm == jvm); if (existingContext) { _jniContext = existingContext; } else { _jniContext = std::make_shared<jni::JNIContext>(jvm, _jniEnv->GetVersion()); JavaHelper::Traits::Register(_jniContext.get(), "tv/watchonair/okui/Helper"); JavaHelper::JavaOpenDialogCallback::Traits::Register(_jniContext.get(), "tv/watchonair/okui/Helper$OpenDialogCallback"); gJNIContext = _jniContext; } _javaHelper = std::make_unique<JavaHelper>(android::app::Activity{_jniEnv, _activity}); } Application::initialize(); } void Android::openDialog(Window* window, const char* title, const char* message, const std::vector<std::string>& buttons, std::function<void(int)> action) { _javaHelper->openDialog(title, message, buttons, new JavaHelper::OpenDialogCallback([=] (int button) { taskScheduler()->async([=] { action(button); }); })); } double Android::renderScale() const { return _javaHelper->renderScale(); } std::string Android::distinctId() const { return _javaHelper->distinctId(); } std::string Android::operatingSystem() const { return _javaHelper->operatingSystem(); } std::string Android::deviceModel() const { return _javaHelper->deviceModel(); } bool Android::wifiConnection() const { return _javaHelper->wifiConnection(); } std::shared_ptr<std::string> Android::AssetResourceManager::load(const char* name) { auto ret = std::make_shared<std::string>(); auto a = AAssetManager_open(_assetManager, name, AASSET_MODE_BUFFER); if (!a) { return ret; } auto size = AAsset_getLength64(a); ret->resize(size); AAsset_read(a, &ret->front(), size); AAsset_close(a); return ret; } } // namespace applications } // namespace okui } // namespace onair #endif
#include "onair/okui/applications/Android.h" #if ONAIR_ANDROID namespace onair { namespace okui { namespace applications { namespace { std::weak_ptr<jni::JNIContext> gJNIContext; } Android::~Android() { if (_javaHelper) { _javaHelper.reset(); } if (_activity) { _jniEnv->DeleteGlobalRef(_activity); } } void Android::setActivity(JNIEnv* env, jobject activity) { _jniEnv = env; _activity = env->NewGlobalRef(activity); } void Android::initialize() { if (!resourceManager() && _activity) { ONAIR_LOGF_DEBUG("using resources from asset manager"); _jniEnv->PushLocalFrame(10); auto c = _jniEnv->GetObjectClass(_activity); auto m = _jniEnv->GetMethodID(c, "getAssets", "()Landroid/content/res/AssetManager;"); _resourceManager = std::make_unique<AssetResourceManager>(_jniEnv, _jniEnv->CallObjectMethod(_activity, m)); setResourceManager(_resourceManager.get()); _jniEnv->PopLocalFrame(nullptr); JavaVM* jvm = nullptr; _jniEnv->GetJavaVM(&jvm); auto existingContext = gJNIContext.lock(); assert(!existingContext || existingContext->jvm == jvm); if (existingContext) { _jniContext = existingContext; } else { _jniContext = std::make_shared<jni::JNIContext>(jvm, _jniEnv->GetVersion()); JavaHelper::Traits::Register(_jniContext.get(), "tv/watchonair/okui/Helper"); JavaHelper::JavaOpenDialogCallback::Traits::Register(_jniContext.get(), "tv/watchonair/okui/Helper$OpenDialogCallback"); gJNIContext = _jniContext; } _javaHelper = std::make_unique<JavaHelper>(android::app::Activity{_jniEnv, _activity}); } Application::initialize(); } void Android::openDialog(Window* window, const char* title, const char* message, const std::vector<std::string>& buttons, std::function<void(int)> action) { _javaHelper->openDialog(title, message, buttons, new JavaHelper::OpenDialogCallback([=] (int button) { taskScheduler()->async([=] { action(button); }); })); } double Android::renderScale() const { return _javaHelper->renderScale(); } std::string Android::distinctId() const { return _javaHelper->distinctId(); } std::string Android::operatingSystem() const { return _javaHelper->operatingSystem(); } std::string Android::deviceModel() const { return _javaHelper->deviceModel(); } bool Android::wifiConnection() const { return _javaHelper->wifiConnection(); } std::shared_ptr<std::string> Android::AssetResourceManager::load(const char* name) { auto ret = std::make_shared<std::string>(); auto a = AAssetManager_open(_assetManager, name, AASSET_MODE_BUFFER); if (!a) { return ret; } auto size = AAsset_getLength64(a); ret->resize(size); AAsset_read(a, &ret->front(), size); AAsset_close(a); return ret; } } // namespace applications } // namespace okui } // namespace onair #endif
fix build
fix build
C++
apache-2.0
bittorrent/okui,bittorrent/okui,bittorrent/okui,bittorrent/okui,bittorrent/okui
d49b13237608d18c6a6409b0ba9989ef38062de2
native/devs_cefclients/win64/source/DeveloperStudio/DevSCefClient_app.cpp
native/devs_cefclients/win64/source/DeveloperStudio/DevSCefClient_app.cpp
/* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) 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 "DeveloperStudio/DevSCefClient_app.h" #include <string> #include <windows.h> #include <stdio.h> #include <process.h> #include <direct.h> #include <stdlib.h> #include "SystemUtils.h" #include "Messages.h" #include "DeveloperStudio/DevSCefBrowserEventHandler.h" #include "include/cef_browser.h" #include "include/cef_command_line.h" #include "include/wrapper/cef_helpers.h" int serverPID; BOOL createProcess(const char* command, STARTUPINFO si, PROCESS_INFORMATION pi) { wchar_t wcharCommand[64]; mbstowcs(wcharCommand, command, strlen(command)+1);//Plus null BOOL result = CreateProcess( NULL, // No module name (use command line) wcharCommand, // Command line NULL, // Process handle not inheritable NULL, // Thread handle not inheritable FALSE, // Set handle inheritance to FALSE 0, // No creation flags NULL, // Use parent's environment block NULL, // Use parent's starting directory &si, // Pointer to STARTUPINFO structure &pi ); // Pointer to PROCESS_INFORMATION structure return result; } void createServerProcess() { STARTUPINFO serverStartupInfo; PROCESS_INFORMATION serverProcessInfo; ZeroMemory( &serverStartupInfo, sizeof(serverStartupInfo) ); serverStartupInfo.cb = sizeof(serverStartupInfo); ZeroMemory( &serverProcessInfo, sizeof(serverProcessInfo) ); //to hide the cmd window serverStartupInfo.wShowWindow = SW_HIDE; serverStartupInfo.dwFlags = STARTF_USESHOWWINDOW; BOOL result = createProcess("server.bat run", serverStartupInfo , serverProcessInfo); } void createWorkspaceProcess() { STARTUPINFO workspaceStartupInfo; PROCESS_INFORMATION workspaceProcessInfo; //TODO comment what this does ZeroMemory(&workspaceStartupInfo, sizeof(workspaceStartupInfo)); workspaceStartupInfo.cb = sizeof(workspaceStartupInfo); ZeroMemory(&workspaceProcessInfo, sizeof(workspaceProcessInfo)); //to hide the cmd window workspaceStartupInfo.wShowWindow = SW_HIDE; workspaceStartupInfo.dwFlags = STARTF_USESHOWWINDOW; BOOL result = createProcess("workspace.bat run", workspaceStartupInfo , workspaceProcessInfo); } DevSCefClient::DevSCefClient() { } void DevSCefClient::OnContextInitialized() { CEF_REQUIRE_UI_THREAD(); // Information used when creating the native window. CefWindowInfo window_info; #if defined(OS_WIN) // On Windows we need to specify certain flags that will be passed to // CreateWindowEx(). window_info.SetAsPopup(NULL, "WSO2 Developer Studio"); #endif char* base_path; // Get the current working directory: if( (base_path = _getcwd( NULL, 0 )) == NULL ) { perror( "_getcwd error" ); } std::string path(base_path); const size_t last_slash_idx = path.rfind('\\'); path = path.substr(0, last_slash_idx); SystemUtils::APPLICATION_BASE_PATH = path; free(base_path); createServerProcess(); createWorkspaceProcess(); const char* pidFilePath = SystemUtils::BIN_PID.c_str(); while (true) { std::FILE *pidFile = std::fopen(pidFilePath, "rb"); if (pidFile) { std::fclose(pidFile); break; } else { Sleep(2); } } std::string sever_pid = SystemUtils::GetFileContents(pidFilePath); serverPID = atoi(sever_pid.c_str()); int pid_file_remove_status = std::remove(pidFilePath); if (pid_file_remove_status != 0) { //std::cerr << Messages::ERROR_IN_FILE_DELETE << pid_file_remove_status << std::endl; } if (serverPID < 0) { //TODO find a way to exit the cef return; } //wait for url file const char * url_cpath = SystemUtils::BIN_URL_TXT.c_str(); while (true) { std::FILE *url_file = std::fopen(url_cpath, "rb"); if (url_file) { std::fclose(url_file); break; } else { Sleep(2); } } //read url file std::string url = SystemUtils::GetFileContents(url_cpath); //close url file int url_file_remove_status = std::remove(url_cpath); if (url_file_remove_status != 0) { //cout << Messages::ERROR_IN_FILE_DELETE << url_file_remove_status << std::endl; } // SimpleHandler implements browser-level callbacks. CefRefPtr<DevSCefBrowserEventHandler> handler(new DevSCefBrowserEventHandler()); // Specify CEF browser settings here. CefBrowserSettings browser_settings; // Create the first browser window. CefBrowserHost::CreateBrowser(window_info, handler.get(), url, browser_settings, NULL); }
/* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) 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 "DeveloperStudio/DevSCefClient_app.h" #include <string> #include <windows.h> #include <stdio.h> #include <process.h> #include <direct.h> #include <stdlib.h> #include "SystemUtils.h" #include "Messages.h" #include "DeveloperStudio/DevSCefBrowserEventHandler.h" #include "include/cef_browser.h" #include "include/cef_command_line.h" #include "include/wrapper/cef_helpers.h" int serverPID; BOOL createProcess(const char* command, STARTUPINFO si, PROCESS_INFORMATION pi) { wchar_t wcharCommand[64]; mbstowcs(wcharCommand, command, strlen(command)+1);//Plus null BOOL result = CreateProcess( NULL, // No module name (use command line) wcharCommand, // Command line NULL, // Process handle not inheritable NULL, // Thread handle not inheritable FALSE, // Set handle inheritance to FALSE 0, // No creation flags NULL, // Use parent's environment block NULL, // Use parent's starting directory &si, // Pointer to STARTUPINFO structure &pi ); // Pointer to PROCESS_INFORMATION structure return result; } void createServerProcess() { STARTUPINFO serverStartupInfo; PROCESS_INFORMATION serverProcessInfo; ZeroMemory( &serverStartupInfo, sizeof(serverStartupInfo) ); serverStartupInfo.cb = sizeof(serverStartupInfo); ZeroMemory( &serverProcessInfo, sizeof(serverProcessInfo) ); //to hide the cmd window serverStartupInfo.wShowWindow = SW_HIDE; serverStartupInfo.dwFlags = STARTF_USESHOWWINDOW; BOOL result = createProcess("server.bat run", serverStartupInfo , serverProcessInfo); } void createWorkspaceProcess() { STARTUPINFO workspaceStartupInfo; PROCESS_INFORMATION workspaceProcessInfo; //TODO comment what this does ZeroMemory(&workspaceStartupInfo, sizeof(workspaceStartupInfo)); workspaceStartupInfo.cb = sizeof(workspaceStartupInfo); ZeroMemory(&workspaceProcessInfo, sizeof(workspaceProcessInfo)); //to hide the cmd window workspaceStartupInfo.wShowWindow = SW_HIDE; workspaceStartupInfo.dwFlags = STARTF_USESHOWWINDOW; BOOL result = createProcess("workspace.bat run", workspaceStartupInfo , workspaceProcessInfo); } DevSCefClient::DevSCefClient() { } void DevSCefClient::OnContextInitialized() { CEF_REQUIRE_UI_THREAD(); // Information used when creating the native window. CefWindowInfo window_info; #if defined(OS_WIN) // On Windows we need to specify certain flags that will be passed to // CreateWindowEx(). window_info.SetAsPopup(NULL, "WSO2 Developer Studio"); #endif char* base_path; // Get the current working directory: if( (base_path = _getcwd( NULL, 0 )) == NULL ) { perror( "_getcwd error" ); } std::string path(base_path); const size_t last_slash_idx = path.rfind('\\'); path = path.substr(0, last_slash_idx); SystemUtils::APPLICATION_BASE_PATH = path; free(base_path); createServerProcess(); createWorkspaceProcess(); const char* pidFilePath = SystemUtils::BIN_PID.c_str(); while (true) { std::FILE *pidFile = std::fopen(pidFilePath, "rb"); if (pidFile) { std::fclose(pidFile); break; } else { Sleep(2); } } std::string sever_pid = SystemUtils::GetFileContents(pidFilePath); serverPID = atoi(sever_pid.c_str()); int pid_file_remove_status = std::remove(pidFilePath); if (pid_file_remove_status != 0) { //std::cerr << Messages::ERROR_IN_FILE_DELETE << pid_file_remove_status << std::endl; } if (serverPID > 0) { //wait for url file const char * url_cpath = SystemUtils::BIN_URL_TXT.c_str(); while (true) { std::FILE *url_file = std::fopen(url_cpath, "rb"); if (url_file) { std::fclose(url_file); break; } else { Sleep(2); } } //read url file std::string url = SystemUtils::GetFileContents(url_cpath); //close url file int url_file_remove_status = std::remove(url_cpath); if (url_file_remove_status != 0) { //cout << Messages::ERROR_IN_FILE_DELETE << url_file_remove_status << std::endl; } // SimpleHandler implements browser-level callbacks. CefRefPtr<DevSCefBrowserEventHandler> handler(new DevSCefBrowserEventHandler()); // Specify CEF browser settings here. CefBrowserSettings browser_settings; // Create the first browser window. CefBrowserHost::CreateBrowser(window_info, handler.get(), url, browser_settings, NULL); } else { HANDLE currentProcessHandle = GetCurrentProcess(); TerminateProcess(currentProcessHandle, 0); } }
exit on workspace cancell implemented
exit on workspace cancell implemented
C++
apache-2.0
liurl3/cloud-dev-studio,liurl3/cloud-dev-studio,rajeevanWSO2/cloud-dev-studio,rajeevanWSO2/cloud-dev-studio,liurl3/cloud-dev-studio,rajeevanWSO2/cloud-dev-studio,rajeevanWSO2/cloud-dev-studio,wso2/cloud-dev-studio,wso2/cloud-dev-studio,wso2/cloud-dev-studio,wso2/cloud-dev-studio,rajeevanWSO2/cloud-dev-studio,rajeevanWSO2/cloud-dev-studio,liurl3/cloud-dev-studio,rajeevanWSO2/cloud-dev-studio
a84da4c68f5ebc0fed401f349f9467ca3e0ddbac
lxqt-config-appearance/main.cpp
lxqt-config-appearance/main.cpp
/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * LXQt - a lightweight, Qt based, desktop toolset * http://razor-qt.org * * Copyright: 2010-2011 Razor team * Authors: * Petr Vanek <[email protected]> * * This program or 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 * * END_COMMON_COPYRIGHT_HEADER */ #include <LXQt/SingleApplication> #include <LXQt/Settings> #include <LXQt/ConfigDialog> #include <QCommandLineParser> #include "iconthemeconfig.h" #include "lxqtthemeconfig.h" #include "styleconfig.h" #include "fontsconfig.h" #include "../liblxqt-config-cursor/selectwnd.h" int main (int argc, char **argv) { LXQt::SingleApplication app(argc, argv); QCommandLineParser parser; parser.setApplicationDescription(QStringLiteral("LXQt Config Appearance")); const QString VERINFO = QStringLiteral(LXQT_CONFIG_VERSION "\nliblxqt " LXQT_VERSION "\nQt " QT_VERSION_STR); app.setApplicationVersion(VERINFO); parser.addVersionOption(); parser.addHelpOption(); parser.process(app); LXQt::Settings* settings = new LXQt::Settings("lxqt"); LXQt::Settings* sessionSettings = new LXQt::Settings("session"); LXQt::ConfigDialog* dialog = new LXQt::ConfigDialog(QObject::tr("LXQt Appearance Configuration"), settings); app.setActivationWindow(dialog); QSettings& qtSettings = *settings; // use lxqt config file for Qt settings in Qt5. StyleConfig* stylePage = new StyleConfig(settings, &qtSettings, dialog); dialog->addPage(stylePage, QObject::tr("Widget Style"), QStringList() << "preferences-desktop-theme" << "preferences-desktop"); QObject::connect(dialog, SIGNAL(reset()), stylePage, SLOT(initControls())); IconThemeConfig* iconPage = new IconThemeConfig(settings, dialog); dialog->addPage(iconPage, QObject::tr("Icons Theme"), QStringList() << "preferences-desktop-icons" << "preferences-desktop"); QObject::connect(dialog, SIGNAL(reset()), iconPage, SLOT(initControls())); LXQtThemeConfig* themePage = new LXQtThemeConfig(settings, dialog); dialog->addPage(themePage, QObject::tr("LXQt Theme"), QStringList() << "preferences-desktop-color" << "preferences-desktop"); QObject::connect(dialog, SIGNAL(reset()), themePage, SLOT(initControls())); FontsConfig* fontsPage = new FontsConfig(settings, &qtSettings, dialog); dialog->addPage(fontsPage, QObject::tr("Font"), QStringList() << "preferences-desktop-font" << "preferences-desktop"); QObject::connect(dialog, SIGNAL(reset()), fontsPage, SLOT(initControls())); SelectWnd* cursorPage = new SelectWnd(sessionSettings, dialog); cursorPage->setCurrent(); dialog->addPage(cursorPage, QObject::tr("Cursor"), QStringList() << "input-mouse" << "preferences-desktop"); dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->setWindowIcon(QIcon::fromTheme("preferences-desktop-theme")); dialog->show(); return app.exec(); }
/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * LXQt - a lightweight, Qt based, desktop toolset * http://razor-qt.org * * Copyright: 2010-2011 Razor team * Authors: * Petr Vanek <[email protected]> * * This program or 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 * * END_COMMON_COPYRIGHT_HEADER */ #include <LXQt/SingleApplication> #include <LXQt/Settings> #include <LXQt/ConfigDialog> #include <QCommandLineParser> #include "iconthemeconfig.h" #include "lxqtthemeconfig.h" #include "styleconfig.h" #include "fontsconfig.h" #include "../liblxqt-config-cursor/selectwnd.h" int main (int argc, char **argv) { LXQt::SingleApplication app(argc, argv); app.setAttribute(Qt::AA_UseHighDpiPixmaps, true); QCommandLineParser parser; parser.setApplicationDescription(QStringLiteral("LXQt Config Appearance")); const QString VERINFO = QStringLiteral(LXQT_CONFIG_VERSION "\nliblxqt " LXQT_VERSION "\nQt " QT_VERSION_STR); app.setApplicationVersion(VERINFO); parser.addVersionOption(); parser.addHelpOption(); parser.process(app); LXQt::Settings* settings = new LXQt::Settings("lxqt"); LXQt::Settings* sessionSettings = new LXQt::Settings("session"); LXQt::ConfigDialog* dialog = new LXQt::ConfigDialog(QObject::tr("LXQt Appearance Configuration"), settings); app.setActivationWindow(dialog); QSettings& qtSettings = *settings; // use lxqt config file for Qt settings in Qt5. StyleConfig* stylePage = new StyleConfig(settings, &qtSettings, dialog); dialog->addPage(stylePage, QObject::tr("Widget Style"), QStringList() << "preferences-desktop-theme" << "preferences-desktop"); QObject::connect(dialog, SIGNAL(reset()), stylePage, SLOT(initControls())); IconThemeConfig* iconPage = new IconThemeConfig(settings, dialog); dialog->addPage(iconPage, QObject::tr("Icons Theme"), QStringList() << "preferences-desktop-icons" << "preferences-desktop"); QObject::connect(dialog, SIGNAL(reset()), iconPage, SLOT(initControls())); LXQtThemeConfig* themePage = new LXQtThemeConfig(settings, dialog); dialog->addPage(themePage, QObject::tr("LXQt Theme"), QStringList() << "preferences-desktop-color" << "preferences-desktop"); QObject::connect(dialog, SIGNAL(reset()), themePage, SLOT(initControls())); FontsConfig* fontsPage = new FontsConfig(settings, &qtSettings, dialog); dialog->addPage(fontsPage, QObject::tr("Font"), QStringList() << "preferences-desktop-font" << "preferences-desktop"); QObject::connect(dialog, SIGNAL(reset()), fontsPage, SLOT(initControls())); SelectWnd* cursorPage = new SelectWnd(sessionSettings, dialog); cursorPage->setCurrent(); dialog->addPage(cursorPage, QObject::tr("Cursor"), QStringList() << "input-mouse" << "preferences-desktop"); dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->setWindowIcon(QIcon::fromTheme("preferences-desktop-theme")); dialog->show(); return app.exec(); }
set Qt::AA_UseHighDpiPixmaps to true
lxqt-config-appearance: set Qt::AA_UseHighDpiPixmaps to true
C++
lgpl-2.1
lxde/lxqt-config,stefonarch/lxqt-config,stefonarch/lxqt-config,stefonarch/lxqt-config,lxde/lxqt-config,lxde/lxqt-config,lxde/lxqt-config
7ac37d22fb400ef35f6ad833895fd2abd914624a
lxqt-config-brightness/main.cpp
lxqt-config-brightness/main.cpp
/* Copyright (C) 2016 P.L. Lucas <[email protected]> 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 "xrandrbrightness.h" #include <QDebug> #include <LXQt/SingleApplication> #include <QCommandLineParser> #include "brightnesssettings.h" int main(int argn, char* argv[]) { LXQt::SingleApplication app(argn, argv); app.setAttribute(Qt::AA_UseHighDpiPixmaps, true); // Command line options QCommandLineParser parser; parser.setApplicationDescription(QStringLiteral("LXQt Config Brightness")); const QString VERINFO = QStringLiteral(LXQT_CONFIG_VERSION "\nliblxqt " LXQT_VERSION "\nQt " QT_VERSION_STR); app.setApplicationVersion(VERINFO); QCommandLineOption increaseOption(QStringList() << "i" << "icrease", app.tr("Increase brightness.")); QCommandLineOption decreaseOption(QStringList() << "d" << "decrease", app.tr("Decrease brightness.")); QCommandLineOption setOption(QStringList() << "s" << "set", app.tr("Set brightness from 1 to 100."), "brightness"); QCommandLineOption helpOption = parser.addHelpOption(); parser.addOption(increaseOption); parser.addOption(decreaseOption); parser.addOption(setOption); parser.addOption(helpOption); parser.addVersionOption(); parser.process(app); if( parser.isSet(increaseOption) || parser.isSet(decreaseOption) || parser.isSet(setOption) ) { XRandrBrightness *brightness = new XRandrBrightness(); const QList<MonitorInfo> monitors = brightness->getMonitorsInfo(); QList<MonitorInfo> monitorsChanged; float sign = parser.isSet(decreaseOption)?-1.0:1.0; double brightness_value = parser.value(setOption).toFloat(); brightness_value = qMin( qMax(brightness_value, 0.0), 100.0 ) / 100.0; if(!parser.value(setOption).isEmpty()) sign = 0.0; for(MonitorInfo monitor : monitors) { if(monitor.isBacklightSupported() ) { long backlight = ( monitor.backlight() + sign*(monitor.backlightMax()/50 + 1) )*qAbs(sign) + brightness_value*monitor.backlightMax(); if(backlight<monitor.backlightMax() && backlight>0) { monitor.setBacklight(backlight); monitorsChanged.append(monitor); } } else { float brightness = (monitor.brightness() + 0.1*sign)*qAbs(sign) + brightness_value*2.0; if(brightness<2.0 && brightness>0.0) { monitor.setBrightness(brightness); monitorsChanged.append(monitor); } } } brightness->setMonitorsSettings(monitorsChanged); return 0; } BrightnessSettings *brightnessSettings = new BrightnessSettings(); brightnessSettings->setWindowIcon(QIcon(ICON_DIR "/brightnesssettings.svg")); brightnessSettings->show(); return app.exec(); }
/* Copyright (C) 2016 P.L. Lucas <[email protected]> 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 "xrandrbrightness.h" #include <QDebug> #include <LXQt/SingleApplication> #include <QCommandLineParser> #include "brightnesssettings.h" int main(int argn, char* argv[]) { LXQt::SingleApplication app(argn, argv); app.setAttribute(Qt::AA_UseHighDpiPixmaps, true); // Command line options QCommandLineParser parser; parser.setApplicationDescription(QStringLiteral("LXQt Config Brightness")); const QString VERINFO = QStringLiteral(LXQT_CONFIG_VERSION "\nliblxqt " LXQT_VERSION "\nQt " QT_VERSION_STR); app.setApplicationVersion(VERINFO); QCommandLineOption increaseOption(QStringList() << "i" << "icrease", app.tr("Increase brightness.")); QCommandLineOption decreaseOption(QStringList() << "d" << "decrease", app.tr("Decrease brightness.")); QCommandLineOption setOption(QStringList() << "s" << "set", app.tr("Set brightness from 1 to 100."), "brightness"); QCommandLineOption resetGammaOption(QStringList() << "r" << "reset", app.tr("Reset gamma to default value.")); QCommandLineOption helpOption = parser.addHelpOption(); parser.addOption(increaseOption); parser.addOption(decreaseOption); parser.addOption(setOption); parser.addOption(resetGammaOption); parser.addOption(helpOption); parser.addVersionOption(); parser.process(app); if( parser.isSet(increaseOption) || parser.isSet(decreaseOption) || parser.isSet(setOption) || parser.isSet(resetGammaOption) ) { XRandrBrightness *brightness = new XRandrBrightness(); const QList<MonitorInfo> monitors = brightness->getMonitorsInfo(); QList<MonitorInfo> monitorsChanged; float sign = parser.isSet(decreaseOption)?-1.0:1.0; double brightness_value = parser.value(setOption).toFloat(); brightness_value = qMin( qMax(brightness_value, 0.0), 100.0 ) / 100.0; if(!parser.value(setOption).isEmpty()) sign = 0.0; for(MonitorInfo monitor : monitors) { if(parser.isSet(resetGammaOption)) { monitor.setBrightness(1.0); monitorsChanged.append(monitor); continue; } if(monitor.isBacklightSupported() ) { long backlight = ( monitor.backlight() + sign*(monitor.backlightMax()/50 + 1) )*qAbs(sign) + brightness_value*monitor.backlightMax(); if(backlight<monitor.backlightMax() && backlight>0) { monitor.setBacklight(backlight); monitorsChanged.append(monitor); } } else { float brightness = (monitor.brightness() + 0.1*sign)*qAbs(sign) + brightness_value*2.0; if(brightness<2.0 && brightness>0.0) { monitor.setBrightness(brightness); monitorsChanged.append(monitor); } } } brightness->setMonitorsSettings(monitorsChanged); return 0; } BrightnessSettings *brightnessSettings = new BrightnessSettings(); brightnessSettings->setWindowIcon(QIcon(ICON_DIR "/brightnesssettings.svg")); brightnessSettings->show(); return app.exec(); }
Add gamma(brightness) reset as a cli option
Add gamma(brightness) reset as a cli option
C++
lgpl-2.1
stefonarch/lxqt-config,stefonarch/lxqt-config,lxde/lxqt-config,stefonarch/lxqt-config,lxde/lxqt-config,lxde/lxqt-config,lxde/lxqt-config
acb546e42470ad16d4d84ac90fc23d78d74fff1f
machine-learning/StateSpace.cpp
machine-learning/StateSpace.cpp
#include "StateSpace.h" StateSpace::StateSpace(const unsigned int _angle_max, const unsigned int _velocity_max): angle_max(_angle_max), velocity_max(_velocity_max), space(_angle_max, std::vector< PriorityQueue<Action*,double> > (_velocity_max, PriorityQueue<Action*,double> (HeapType::MAX))) {} StateSpace::~StateSpace() { //ridiculously extensive clean-up for(unsigned int i=0 ; i<angle_max ; ++i) { for(unsigned int j=0 ; j<velocity_max ; ++j) { PriorityQueue<Action*,double>& queue1=space1[i][j]; PriorityQueue<Action*,double>& queue2=space2[i][j]; for(auto iter=queue1.begin(),queue1=list.end() ; iter!=end ; ++iter) { delete *iter; } for(auto iter=queue2.begin(),queue2=list.end() ; iter!=end ; ++iter) { delete *iter; } } } } StateSpace::SubscriptProxy StateSpace::operator[](const unsigned int robot_state) { if(robot_state>1)throw std::domain_error("action index exceeded"); //return proxy object to accept second [] operator return SubscriptProxy( robot_state ? space1 : space2 ); } //searches state space by state object PriorityQueue<Action *, double> StateSpace::StateSearch(State * state) { return (*this)[state->RobotState][state->theta][state->theta_dot]; }
#include "StateSpace.h" StateSpace::StateSpace(const unsigned int _angle_max, const unsigned int _velocity_max): angle_max(_angle_max), velocity_max(_velocity_max), space(_angle_max, std::vector< PriorityQueue<Action*,double> > (_velocity_max, PriorityQueue<Action*,double> (HeapType::MAX))) {} StateSpace::~StateSpace() { //ridiculously extensive clean-up for(unsigned int i=0 ; i<angle_max ; ++i) { for(unsigned int j=0 ; j<velocity_max ; ++j) { PriorityQueue<Action*,double>& queue1=space1[i][j]; PriorityQueue<Action*,double>& queue2=space2[i][j]; for(auto iter=queue1.begin(),queue1=list.end() ; iter!=end ; ++iter) { delete *iter; } for(auto iter=queue2.begin(),queue2=list.end() ; iter!=end ; ++iter) { delete *iter; } } } } StateSpace::SubscriptProxy1 StateSpace::operator[](const unsigned int robot_state) { if(robot_state>1)throw std::domain_error("action index exceeded"); //return proxy object to accept second [] operator return SubscriptProxy( robot_state ? space1 : space2 ); } //searches state space by state object PriorityQueue<Action *, double> StateSpace::StateSearch(State * state) { return (*this)[state->RobotState][state->theta][state->theta_dot]; }
Update StateSpace.cpp
Update StateSpace.cpp
C++
mit
philj56/robot-swing,philj56/robot-swing,philj56/robot-swing
8826a4efd7e519d1c9434963b1712380136a4aee
include/stack.cpp
include/stack.cpp
#ifndef stack_cpp #define stack_cpp #pragma once #include <iostream> template <typename T> class stack { public: stack(); //noexcept stack(stack const &); //strong ~stack(); //noexcept size_t count() const; //noexcept auto push(T const &) -> void; //strong void pop(); //basic const T& top(); //strong auto operator=(stack const & right)->stack &; //strong auto empty() const -> bool; //noexcept private: T *array_; size_t array_size_; size_t count_; }; template<typename T> auto newcopy(const T * item, size_t size, size_t count) -> T* //strong { T * buff = new T[size]; try { std::copy(item, item + count, buff); } catch (...) { delete[] buff; throw; } return buff; } template <typename T> size_t stack<T>::count() const { return count_; } template <typename T> stack<T>::stack() { array_size_ = 0; array_ = new T[array_size_]; count_ = 0; } template<typename T> stack<T>::stack(stack const & other) :array_size_(other.array_size_), count_(other.count_), array_(newcopy(other.array_, other.array_size_, other.count_)) { } template <typename T> stack<T>::~stack() { delete[] array_; } template<typename T> void stack<T>::push(T const &item) { if (count_ == array_size_) { size_t size = array_size_ * 2 + (array_size_ == 0); delete[] array_; array_ = newcopy(array_, size, array_size_); array_size_ = size; } array_[count_] = item; ++count_; } template<typename T> void stack<T>::pop() { if (count_ == 0) { throw std::logic_error("Stack is empty!"); } else { count_--; } } template<typename T> const T& stack<T>::top() { if (count_ == 0) { throw ("Stack is empty!"); } return array_[count_ - 1]; } template<typename T> auto stack<T>::operator=(stack const & right) -> stack & { if (this != &right) { delete[] array_; newcopy(right.array_, right.array_size_, right.count_); } return *this; } template<typename T> auto stack<T>::empty() const -> bool { if (count_ == 0) { return true; } else { return false; } } #endif
#ifndef stack_cpp #define stack_cpp #pragma once #include <iostream> template <typename T> class allocator { protected: allocator(size_t size = 0); ~allocator(); auto swap(allocator & other) -> void; allocator(allocator const &) = delete; auto operator =(allocator const &) -> allocator & = delete; T * ptr_; size_t size_; size_t count_; }; template <typename T> class stack { public: stack(); //noexcept stack(stack const &); //strong ~stack(); //noexcept size_t count() const; //noexcept auto push(T const &) -> void; //strong void pop(); //basic const T& top(); //strong auto operator=(stack const & right)->stack &; //strong auto empty() const -> bool; //noexcept private: T *array_; size_t array_size_; size_t count_; }; template<typename T> auto newcopy(const T * item, size_t size, size_t count) -> T* //strong { T * buff = new T[size]; try { std::copy(item, item + count, buff); } catch (...) { delete[] buff; throw; } return buff; } template <typename T> size_t stack<T>::count() const { return count_; } template <typename T> stack<T>::stack() { array_size_ = 0; array_ = new T[array_size_]; count_ = 0; } template<typename T> stack<T>::stack(stack const & other) :array_size_(other.array_size_), count_(other.count_), array_(newcopy(other.array_, other.array_size_, other.count_)) { } template <typename T> stack<T>::~stack() { delete[] array_; } template<typename T> void stack<T>::push(T const &item) { if (count_ == array_size_) { size_t size = array_size_ * 2 + (array_size_ == 0); delete[] array_; array_ = newcopy(array_, size, array_size_); array_size_ = size; } array_[count_] = item; ++count_; } template<typename T> void stack<T>::pop() { if (count_ == 0) { throw std::logic_error("Stack is empty!"); } else { count_--; } } template<typename T> const T& stack<T>::top() { if (count_ == 0) { throw ("Stack is empty!"); } return array_[count_ - 1]; } template<typename T> auto stack<T>::operator=(stack const & right) -> stack & { if (this != &right) { delete[] array_; newcopy(right.array_, right.array_size_, right.count_); } return *this; } template<typename T> auto stack<T>::empty() const -> bool { if (count_ == 0) { return true; } else { return false; } } #endif
Update stack.cpp
Update stack.cpp
C++
mit
tpabahatp/Stack
4ebdc55d9f057af685acf70f87edcc54e7f6dcbd
include/stack.hpp
include/stack.hpp
#include <iostream> #include <algorithm> #include <stdexcept> template <typename T> class stack { public: stack(); ~stack()noexcept; stack(stack<T> const&)basic; stack& operator=(stack<T> const&)noexcept; size_t count()const noexcept; size_t array_size()const noexcept; void push(T const&)basic; void pop()basic; T top()const noexcept; void print(std::ostream&stream)const noexcept; void swap(stack<T>&)noexcept; bool empty()const noexcept; private: T * array_; size_t array_size_; size_t count_; }; template <typename T> stack<T>::stack() : array_{ nullptr }, array_size_{ 0 }, count_{ 0 } {} template <typename T> stack<T>::~stack()noexcept { delete[] array_; } template <typename T> stack<T>::stack(stack<T> const& other)basic { array_size_ = other.array_size_; count_ = other.count_; std::copy(other.array_, other.array_ + count_, array_); } template <typename T> stack<T>& stack<T>::operator=(stack<T> const & other)noexcept { if (&other != this) stack(other).swap(*this); return *this; } template <typename T> size_t stack<T>::array_size()const noexcept { return array_size_; } template <typename T> size_t stack<T>::count()const noexcept { return count_; } template <typename T> void stack<T>::push(T const & value)basic { if (empty()) { array_size_ = 1; array_ = new T[array_size_](); } else if (array_size_ == count_) { array_size_ *= 2; T * new_array = new T[array_size_](); std::copy(array_, array_ + count_, new_array); delete[] array_; array_ = new_array; } array_[count_++] = value; } template <typename T> void stack<T>::pop()basic { if (empty()) throw std::logic_error("Stack is empty"); else { T * new_array = new T[array_size_](); --count_; std::copy(array_, array_ + count_, new_array); delete[] array_; array_ = new_array; } } template <typename T> T stack<T>::top()const noexcept { if (empty()) throw std::logic_error("Stack is empty"); else return array_[count_ - 1]; } template <typename T> void stack<T>::print(std::ostream&stream)const noexcept { for (unsigned int i = 0; i < count_; ++i) stream << array_[i] << " "; stream << std::endl; } template <typename T> void stack<T>::swap(stack<T>& other)noexcept { std::swap(array_, other.array_); std::swap(array_size_, other.array_size_); std::swap(count_, other.count_); } template <typename T> bool stack<T>::empty()const noexcept { return (count_ == 0); }
#include <iostream> #include <algorithm> #include <stdexcept> template <typename T> class stack { public: stack(); ~stack()noexcept; stack(stack<T> const&); stack& operator=(stack<T> const&)noexcept; size_t count()const noexcept; size_t array_size()const noexcept; void push(T const&); void pop(); T top()const noexcept; void print(std::ostream&stream)const noexcept; void swap(stack<T>&)noexcept; bool empty()const noexcept; private: T * array_; size_t array_size_; size_t count_; }; template <typename T> stack<T>::stack() : array_{ nullptr }, array_size_{ 0 }, count_{ 0 } {} template <typename T> stack<T>::~stack()noexcept { delete[] array_; } template <typename T> stack<T>::stack(stack<T> const& other) { array_size_ = other.array_size_; count_ = other.count_; std::copy(other.array_, other.array_ + count_, array_); } template <typename T> stack<T>& stack<T>::operator=(stack<T> const & other)noexcept { if (&other != this) stack(other).swap(*this); return *this; } template <typename T> size_t stack<T>::array_size()const noexcept { return array_size_; } template <typename T> size_t stack<T>::count()const noexcept { return count_; } template <typename T> void stack<T>::push(T const & value) { if (empty()) { array_size_ = 1; array_ = new T[array_size_](); } else if (array_size_ == count_) { array_size_ *= 2; T * new_array = new T[array_size_](); std::copy(array_, array_ + count_, new_array); delete[] array_; array_ = new_array; } array_[count_++] = value; } template <typename T> void stack<T>::pop() { if (empty()) throw std::logic_error("Stack is empty"); else { T * new_array = new T[array_size_](); --count_; std::copy(array_, array_ + count_, new_array); delete[] array_; array_ = new_array; } } template <typename T> T stack<T>::top()const noexcept { if (empty()) throw std::logic_error("Stack is empty"); else return array_[count_ - 1]; } template <typename T> void stack<T>::print(std::ostream&stream)const noexcept { for (unsigned int i = 0; i < count_; ++i) stream << array_[i] << " "; stream << std::endl; } template <typename T> void stack<T>::swap(stack<T>& other)noexcept { std::swap(array_, other.array_); std::swap(array_size_, other.array_size_); std::swap(count_, other.count_); } template <typename T> bool stack<T>::empty()const noexcept { return (count_ == 0); }
Update stack.hpp
Update stack.hpp
C++
mit
kate-lozovaya/stack-0.0.3
9295469715fff6899529aed56c041de9c6ef6142
src/mlpack/methods/logistic_regression/logistic_regression_main.cpp
src/mlpack/methods/logistic_regression/logistic_regression_main.cpp
/** * @file logistic_regression_main.cpp * @author Ryan Curtin * * Main executable for logistic regression. */ #include <mlpack/core.hpp> #include "logistic_regression.hpp" #include <mlpack/core/optimizers/sgd/sgd.hpp> using namespace std; using namespace mlpack; using namespace mlpack::regression; using namespace mlpack::optimization; PROGRAM_INFO("L2-regularized Logistic Regression and Prediction", "An implementation of L2-regularized logistic regression using either the " "L-BFGS optimizer or SGD (stochastic gradient descent). This solves the " "regression problem" "\n\n" " y = (1 / 1 + e^-(X * b))" "\n\n" "where y takes values 0 or 1." "\n\n" "This program allows loading a logistic regression model from a file (-i) " "or training a logistic regression model given training data (-t), or both " "those things at once. In addition, this program allows classification on " "a test dataset (-T) and will save the classification results to the given " "output file (-o). The logistic regression model itself may be saved with " "a file specified using the -m option." "\n\n" "The training data given with the -t option should have class labels as its" " last dimension (so, if the training data is in CSV format, labels should " "be the last column). Alternately, the -l (--labels_file) option may be " "used to specify a separate file of labels." "\n\n" "When a model is being trained, there are many options. L2 regularization " "(to prevent overfitting) can be specified with the -l option, and the " "optimizer used to train the model can be specified with the --optimizer " "option. Available options are 'sgd' (stochastic gradient descent) and " "'lbfgs' (the L-BFGS optimizer). There are also various parameters for the" " optimizer; the --max_iterations parameter specifies the maximum number of" " allowed iterations, and the --tolerance parameter specifies the tolerance" " for convergence. For the SGD optimizer, the --step_size parameter " "controls the step size taken at each iteration by the optimizer. If the " "objective function for your data is oscillating between Inf and 0, the " "step size is probably too large. There are more parameters for the SGD " "and L-BFGS optimizers, but the C++ interface must be used to access these." "\n\n" "Optionally, the model can be used to predict the responses for another " "matrix of data points, if --test_file is specified. The --test_file " "option can be specified without --input_file, so long as an existing " "logistic regression model is given with --model_file. The output " "predictions from the logistic regression model are stored in the file " "given with --output_predictions." "\n\n" "This implementation of logistic regression does not support the general " "multi-class case but instead only the two-class case. Any responses must " "be either 0 or 1."); // Training parameters. PARAM_STRING("training_file", "A file containing the training set (the matrix " "of predictors, X).", "t", ""); PARAM_STRING("labels_file", "A file containing labels (0 or 1) for the points " "in the training set (y).", "l", ""); // Optimizer parameters. PARAM_DOUBLE("lambda", "L2-regularization parameter for training.", "L", 0.0); PARAM_STRING("optimizer", "Optimizer to use for training ('lbfgs' or 'sgd').", "O", "lbfgs"); PARAM_DOUBLE("tolerance", "Convergence tolerance for optimizer.", "T", 1e-10); PARAM_INT("max_iterations", "Maximum iterations for optimizer (0 indicates no " "limit).", "M", 10000); PARAM_DOUBLE("step_size", "Step size for SGD optimizer.", "s", 0.01); // Model loading/saving. PARAM_STRING("input_model", "File containing existing model (parameters).", "i", ""); PARAM_STRING("output_model", "File to save trained logistic regression model " "to.", "m", ""); // Testing. PARAM_STRING("test_file", "File containing test dataset.", "T", ""); PARAM_STRING("output_file", "If --test_file is specified, this file is " "where the predicted responses will be saved.", "o", "output.csv"); PARAM_DOUBLE("decision_boundary", "Decision boundary for prediction; if the " "logistic function for a point is less than the boundary, the class is " "taken to be 0; otherwise, the class is 1.", "d", 0.5); int main(int argc, char** argv) { CLI::ParseCommandLine(argc, argv); // Collect command-line options. const string trainingFile = CLI::GetParam<string>("training_file"); const string labelsFile = CLI::GetParam<string>("labels_file"); const double lambda = CLI::GetParam<double>("lambda"); const string optimizerType = CLI::GetParam<string>("optimizer"); const double tolerance = CLI::GetParam<double>("tolerance"); const double stepSize = CLI::GetParam<double>("step_size"); const size_t maxIterations = (size_t) CLI::GetParam<int>("max_iterations"); const string inputModelFile = CLI::GetParam<string>("input_model"); const string outputModelFile = CLI::GetParam<string>("output_model"); const string testFile = CLI::GetParam<string>("test_file"); const string outputFile = CLI::GetParam<string>("output_file"); const double decisionBoundary = CLI::GetParam<double>("decision_boundary"); // One of inputFile and modelFile must be specified. if (trainingFile.empty() && inputModelFile.empty()) Log::Fatal << "One of --input_model or --training_file must be specified." << endl; // If no output file is given, the user should know that the model will not be // saved, but only if a model is being trained. if (outputFile.empty() && !trainingFile.empty()) Log::Warn << "--output_model not given; trained model will not be saved." << endl; // Tolerance needs to be positive. if (tolerance < 0.0) Log::Fatal << "Tolerance must be positive (received " << tolerance << ")." << endl; // Optimizer has to be L-BFGS or SGD. if (optimizerType != "lbfgs" && optimizerType != "sgd") Log::Fatal << "--optimizer must be 'lbfgs' or 'sgd'." << endl; // Lambda must be positive. if (lambda < 0.0) Log::Fatal << "L2-regularization parameter (--lambda) must be positive (" << "received " << lambda << ")." << endl; // Decision boundary must be between 0 and 1. if (decisionBoundary < 0.0 || decisionBoundary > 1.0) Log::Fatal << "Decision boundary (--decision_boundary) must be between 0.0 " << "and 1.0 (received " << decisionBoundary << ")." << endl; if ((stepSize < 0.0) && (optimizerType == "sgd")) Log::Fatal << "Step size (--step_size) must be positive (received " << stepSize << ")." << endl; if (CLI::HasParam("step_size") && optimizerType == "lbfgs") Log::Warn << "Step size (--step_size) ignored because 'sgd' optimizer is " << "not being used." << endl; // These are the matrices we might use. arma::mat regressors; arma::Mat<size_t> responses; arma::mat testSet; arma::Row<size_t> predictions; // Load data matrix. if (!trainingFile.empty()) data::Load(trainingFile, regressors, true); // Load the model, if necessary. LogisticRegression<> model(0, 0); // Empty model. if (!inputModelFile.empty()) { data::Load(inputModelFile, "logistic_regression_model", model); } else { // Set the size of the parameters vector, if necessary. if (labelsFile.empty()) model.Parameters() = arma::zeros<arma::vec>(regressors.n_rows - 1); else model.Parameters() = arma::zeros<arma::vec>(regressors.n_rows); } // Check if the responses are in a separate file. if (!labelsFile.empty()) { data::Load(labelsFile, responses, true); if (responses.n_rows == 1) responses = responses.t(); if (responses.n_rows != regressors.n_cols) Log::Fatal << "The labels (--labels_file) must have the same number of " << "points as the training dataset (--training_file)." << endl; } else { // The initial predictors for y, Nx1. responses = arma::conv_to<arma::Row<size_t>>::from( regressors.row(regressors.n_rows - 1)); regressors.shed_row(regressors.n_rows - 1); } // Verify the labels. if (max(max(responses)) > 1) Log::Fatal << "The labels must be either 0 or 1, not " << max(responses) << "!" << endl; // Now, do the training. if (!trainingFile.empty()) { LogisticRegressionFunction<> lrf(regressors, responses, model.Parameters()); if (optimizerType == "sgd") { SGD<LogisticRegressionFunction<>> sgdOpt(lrf); sgdOpt.MaxIterations() = maxIterations; sgdOpt.Tolerance() = tolerance; sgdOpt.StepSize() = stepSize; Log::Info << "Training model with SGD optimizer." << endl; // This will train the model. model.Train(sgdOpt); } else if (optimizerType == "lbfgs") { L_BFGS<LogisticRegressionFunction<>> lbfgsOpt(lrf); lbfgsOpt.MaxIterations() = maxIterations; lbfgsOpt.MinGradientNorm() = tolerance; Log::Info << "Training model with L-BFGS optimizer." << endl; // This will train the model. model.Train(lbfgsOpt); } } if (!testFile.empty()) { data::Load(testFile, testSet, true); // We must perform predictions on the test set. Training (and the // optimizer) are irrelevant here; we'll pass in the model we have. Log::Info << "Predicting classes of points in '" << testFile << "'." << endl; model.Predict(testSet, predictions, decisionBoundary); // Save the results, if necessary. if (!outputFile.empty()) data::Save(outputFile, predictions, false); } if (!outputModelFile.empty()) { Log::Info << "Saving model to '" << outputFile << "'." << endl; data::Save(outputFile, "logistic_regression_model", model, false); } }
/** * @file logistic_regression_main.cpp * @author Ryan Curtin * * Main executable for logistic regression. */ #include <mlpack/core.hpp> #include "logistic_regression.hpp" #include <mlpack/core/optimizers/sgd/sgd.hpp> using namespace std; using namespace mlpack; using namespace mlpack::regression; using namespace mlpack::optimization; PROGRAM_INFO("L2-regularized Logistic Regression and Prediction", "An implementation of L2-regularized logistic regression using either the " "L-BFGS optimizer or SGD (stochastic gradient descent). This solves the " "regression problem" "\n\n" " y = (1 / 1 + e^-(X * b))" "\n\n" "where y takes values 0 or 1." "\n\n" "This program allows loading a logistic regression model from a file (-i) " "or training a logistic regression model given training data (-t), or both " "those things at once. In addition, this program allows classification on " "a test dataset (-T) and will save the classification results to the given " "output file (-o). The logistic regression model itself may be saved with " "a file specified using the -m option." "\n\n" "The training data given with the -t option should have class labels as its" " last dimension (so, if the training data is in CSV format, labels should " "be the last column). Alternately, the -l (--labels_file) option may be " "used to specify a separate file of labels." "\n\n" "When a model is being trained, there are many options. L2 regularization " "(to prevent overfitting) can be specified with the -l option, and the " "optimizer used to train the model can be specified with the --optimizer " "option. Available options are 'sgd' (stochastic gradient descent) and " "'lbfgs' (the L-BFGS optimizer). There are also various parameters for the" " optimizer; the --max_iterations parameter specifies the maximum number of" " allowed iterations, and the --tolerance (-e) parameter specifies the " "tolerance for convergence. For the SGD optimizer, the --step_size " "parameter controls the step size taken at each iteration by the optimizer." " If the objective function for your data is oscillating between Inf and " "0, the step size is probably too large. There are more parameters for the" " SGD and L-BFGS optimizers, but the C++ interface must be used to access " "these." "\n\n" "Optionally, the model can be used to predict the responses for another " "matrix of data points, if --test_file is specified. The --test_file " "option can be specified without --input_file, so long as an existing " "logistic regression model is given with --model_file. The output " "predictions from the logistic regression model are stored in the file " "given with --output_predictions." "\n\n" "This implementation of logistic regression does not support the general " "multi-class case but instead only the two-class case. Any responses must " "be either 0 or 1."); // Training parameters. PARAM_STRING("training_file", "A file containing the training set (the matrix " "of predictors, X).", "t", ""); PARAM_STRING("labels_file", "A file containing labels (0 or 1) for the points " "in the training set (y).", "l", ""); // Optimizer parameters. PARAM_DOUBLE("lambda", "L2-regularization parameter for training.", "L", 0.0); PARAM_STRING("optimizer", "Optimizer to use for training ('lbfgs' or 'sgd').", "O", "lbfgs"); PARAM_DOUBLE("tolerance", "Convergence tolerance for optimizer.", "e", 1e-10); PARAM_INT("max_iterations", "Maximum iterations for optimizer (0 indicates no " "limit).", "M", 10000); PARAM_DOUBLE("step_size", "Step size for SGD optimizer.", "s", 0.01); // Model loading/saving. PARAM_STRING("input_model", "File containing existing model (parameters).", "i", ""); PARAM_STRING("output_model", "File to save trained logistic regression model " "to.", "m", ""); // Testing. PARAM_STRING("test_file", "File containing test dataset.", "T", ""); PARAM_STRING("output_file", "If --test_file is specified, this file is " "where the predicted responses will be saved.", "o", ""); PARAM_DOUBLE("decision_boundary", "Decision boundary for prediction; if the " "logistic function for a point is less than the boundary, the class is " "taken to be 0; otherwise, the class is 1.", "d", 0.5); int main(int argc, char** argv) { CLI::ParseCommandLine(argc, argv); // Collect command-line options. const string trainingFile = CLI::GetParam<string>("training_file"); const string labelsFile = CLI::GetParam<string>("labels_file"); const double lambda = CLI::GetParam<double>("lambda"); const string optimizerType = CLI::GetParam<string>("optimizer"); const double tolerance = CLI::GetParam<double>("tolerance"); const double stepSize = CLI::GetParam<double>("step_size"); const size_t maxIterations = (size_t) CLI::GetParam<int>("max_iterations"); const string inputModelFile = CLI::GetParam<string>("input_model"); const string outputModelFile = CLI::GetParam<string>("output_model"); const string testFile = CLI::GetParam<string>("test_file"); const string outputFile = CLI::GetParam<string>("output_file"); const double decisionBoundary = CLI::GetParam<double>("decision_boundary"); // One of inputFile and modelFile must be specified. if (trainingFile.empty() && inputModelFile.empty()) Log::Fatal << "One of --input_model or --training_file must be specified." << endl; // If no output file is given, the user should know that the model will not be // saved, but only if a model is being trained. if (outputFile.empty() && !trainingFile.empty()) Log::Warn << "--output_model not given; trained model will not be saved." << endl; // Tolerance needs to be positive. if (tolerance < 0.0) Log::Fatal << "Tolerance must be positive (received " << tolerance << ")." << endl; // Optimizer has to be L-BFGS or SGD. if (optimizerType != "lbfgs" && optimizerType != "sgd") Log::Fatal << "--optimizer must be 'lbfgs' or 'sgd'." << endl; // Lambda must be positive. if (lambda < 0.0) Log::Fatal << "L2-regularization parameter (--lambda) must be positive (" << "received " << lambda << ")." << endl; // Decision boundary must be between 0 and 1. if (decisionBoundary < 0.0 || decisionBoundary > 1.0) Log::Fatal << "Decision boundary (--decision_boundary) must be between 0.0 " << "and 1.0 (received " << decisionBoundary << ")." << endl; if ((stepSize < 0.0) && (optimizerType == "sgd")) Log::Fatal << "Step size (--step_size) must be positive (received " << stepSize << ")." << endl; if (CLI::HasParam("step_size") && optimizerType == "lbfgs") Log::Warn << "Step size (--step_size) ignored because 'sgd' optimizer is " << "not being used." << endl; // These are the matrices we might use. arma::mat regressors; arma::Mat<size_t> responsesMat; arma::Row<size_t> responses; arma::mat testSet; arma::Row<size_t> predictions; // Load data matrix. if (!trainingFile.empty()) data::Load(trainingFile, regressors, true); // Load the model, if necessary. LogisticRegression<> model(0, 0); // Empty model. if (!inputModelFile.empty()) { data::Load(inputModelFile, "logistic_regression_model", model); } else { // Set the size of the parameters vector, if necessary. if (labelsFile.empty()) model.Parameters() = arma::zeros<arma::vec>(regressors.n_rows - 1); else model.Parameters() = arma::zeros<arma::vec>(regressors.n_rows); } // Check if the responses are in a separate file. if (!trainingFile.empty() && !labelsFile.empty()) { data::Load(labelsFile, responsesMat, true); if (responsesMat.n_cols == 1) responses = responsesMat.col(0).t(); else responses = responsesMat.row(0); if (responses.n_cols != regressors.n_cols) Log::Fatal << "The labels (--labels_file) must have the same number of " << "points as the training dataset (--training_file)." << endl; } else if (!trainingFile.empty()) { // The initial predictors for y, Nx1. responses = arma::conv_to<arma::Row<size_t>>::from( regressors.row(regressors.n_rows - 1)); regressors.shed_row(regressors.n_rows - 1); } // Verify the labels. if (!trainingFile.empty() && max(responses) > 1) Log::Fatal << "The labels must be either 0 or 1, not " << max(responses) << "!" << endl; // Now, do the training. if (!trainingFile.empty()) { LogisticRegressionFunction<> lrf(regressors, responses, model.Parameters()); if (optimizerType == "sgd") { SGD<LogisticRegressionFunction<>> sgdOpt(lrf); sgdOpt.MaxIterations() = maxIterations; sgdOpt.Tolerance() = tolerance; sgdOpt.StepSize() = stepSize; Log::Info << "Training model with SGD optimizer." << endl; // This will train the model. model.Train(sgdOpt); } else if (optimizerType == "lbfgs") { L_BFGS<LogisticRegressionFunction<>> lbfgsOpt(lrf); lbfgsOpt.MaxIterations() = maxIterations; lbfgsOpt.MinGradientNorm() = tolerance; Log::Info << "Training model with L-BFGS optimizer." << endl; // This will train the model. model.Train(lbfgsOpt); } } if (!testFile.empty()) { data::Load(testFile, testSet, true); // We must perform predictions on the test set. Training (and the // optimizer) are irrelevant here; we'll pass in the model we have. Log::Info << "Predicting classes of points in '" << testFile << "'." << endl; model.Predict(testSet, predictions, decisionBoundary); // Save the results, if necessary. if (!outputFile.empty()) data::Save(outputFile, predictions, false); } if (!outputModelFile.empty()) { Log::Info << "Saving model to '" << outputModelFile << "'." << endl; data::Save(outputModelFile, "logistic_regression_model", model, false); } }
Fix bugs in logistic_regression.
Fix bugs in logistic_regression.
C++
bsd-3-clause
palashahuja/mlpack,ajjl/mlpack,stereomatchingkiss/mlpack,ranjan1990/mlpack,ajjl/mlpack,stereomatchingkiss/mlpack,lezorich/mlpack,theranger/mlpack,theranger/mlpack,theranger/mlpack,stereomatchingkiss/mlpack,palashahuja/mlpack,darcyliu/mlpack,ranjan1990/mlpack,palashahuja/mlpack,ajjl/mlpack,lezorich/mlpack,darcyliu/mlpack,ranjan1990/mlpack,lezorich/mlpack,darcyliu/mlpack
ff619d4c5eef007f9e6bf6d9eb3d90fd4bb60fac
applications/mne_analyze/plugins/dataloader/dataloader.cpp
applications/mne_analyze/plugins/dataloader/dataloader.cpp
//============================================================================================================= /** * @file dataloader.cpp * @author Lorenz Esch <[email protected]> * @since 0.1.0 * @date November, 2019 * * @section LICENSE * * Copyright (C) 2019, Lorenz Esch. 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 Definition of the DataLoader class. * */ //============================================================================================================= // INCLUDES //============================================================================================================= #include "dataloader.h" #include <anShared/Management/communicator.h> #include <anShared/Management/analyzedata.h> #include <anShared/Model/fiffrawviewmodel.h> #include <anShared/Model/bemdatamodel.h> #include <disp/viewers/progressview.h> //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace DATALOADERPLUGIN; using namespace ANSHAREDLIB; //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= DataLoader::DataLoader() : m_pProgressView(new DISPLIB::ProgressView(false)) , m_pProgressViewWidget(new QWidget()) { m_pProgressViewWidget->setWindowFlags(Qt::Window); QVBoxLayout* layout = new QVBoxLayout(m_pProgressViewWidget.data()); layout->addWidget(m_pProgressView); m_pProgressViewWidget->setLayout(layout); } //============================================================================================================= DataLoader::~DataLoader() { } //============================================================================================================= QSharedPointer<IPlugin> DataLoader::clone() const { QSharedPointer<DataLoader> pDataLoaderClone(new DataLoader); return pDataLoaderClone; } //============================================================================================================= void DataLoader::init() { m_pCommu = new Communicator(this); } //============================================================================================================= void DataLoader::unload() { } //============================================================================================================= QString DataLoader::getName() const { return "Data Loader"; } //============================================================================================================= QMenu *DataLoader::getMenu() { QMenu* pMenuFile = new QMenu(tr("File")); QAction* pActionLoad = new QAction(tr("Open")); pActionLoad->setStatusTip(tr("Load a data file")); connect(pActionLoad, &QAction::triggered, this, &DataLoader::onLoadFilePressed); QAction* pActionSave = new QAction(tr("Save")); pActionLoad->setStatusTip(tr("Save the selected data file")); connect(pActionSave, &QAction::triggered, this, &DataLoader::onSaveFilePressed); pMenuFile->addAction(pActionLoad); pMenuFile->addAction(pActionSave); return pMenuFile; } //============================================================================================================= QDockWidget *DataLoader::getControl() { return Q_NULLPTR; } //============================================================================================================= QWidget *DataLoader::getView() { return Q_NULLPTR; } //============================================================================================================= void DataLoader::handleEvent(QSharedPointer<Event> e) { switch (e->getType()) { case EVENT_TYPE::SELECTED_MODEL_CHANGED: if(e->getData().value<QSharedPointer<ANSHAREDLIB::AbstractModel> >()) { m_pSelectedModel = e->getData().value<QSharedPointer<ANSHAREDLIB::AbstractModel> >(); } break; default: qWarning() << "[DataLoader::handleEvent] Received an Event that is not handled by switch cases."; } } //============================================================================================================= QVector<EVENT_TYPE> DataLoader::getEventSubscriptions(void) const { QVector<EVENT_TYPE> temp = {SELECTED_MODEL_CHANGED}; return temp; } //============================================================================================================= void DataLoader::cmdLineStartup(const QStringList& sArguments) { if(sArguments.size() == 2 && (sArguments.first() == "file" || sArguments.first() == "f")) { loadFilePath(sArguments.at(1)); } } //============================================================================================================= void DataLoader::loadFilePath(const QString& sFilePath) { QFileInfo fileInfo(sFilePath); m_pProgressView->setMessage("Loading " + fileInfo.fileName()); m_pProgressView->setLoadingBarVisible(false); m_pProgressViewWidget->show(); m_pProgressViewWidget->move(qApp->topLevelWindows().first()->screen()->geometry().center() - m_pProgressViewWidget->rect().center()); for (QWindow* window : qApp->topLevelWindows()){ window->setOpacity(0.8); for (QWidget* widget : window->findChildren<QWidget*>()){ widget->setEnabled(false); } } QApplication::processEvents(); if(fileInfo.exists() && (fileInfo.completeSuffix() == "raw.fif")) { m_pAnalyzeData->loadModel<ANSHAREDLIB::FiffRawViewModel>(sFilePath); } else if(fileInfo.exists() && (fileInfo.completeSuffix() == "bem.fif")) { m_pAnalyzeData->loadModel<ANSHAREDLIB::BemDataModel>(sFilePath); } else { qWarning() << "[DataLoader::loadFilePath] Make sure that your files agree with the MNE naming conventions, eg.: *bem.fif; *raw.fif."; } m_pProgressViewWidget->hide(); for (QWindow* window : qApp->topLevelWindows()){ window->setOpacity(1.0); for (QWidget* widget : window->findChildren<QWidget*>()){ widget->setEnabled(true); } } } //============================================================================================================= void DataLoader::onLoadFilePressed() { #ifdef WASMBUILD auto fileContentReady = [&](const QString &sFilePath, const QByteArray &fileContent) { if(!sFilePath.isNull()) { // We need to prepend "wasm/" because QFileDialog::getOpenFileContent does not provide a full // path, which we need for organzing the different models in AnalyzeData m_pAnalyzeData->loadModel<FiffRawViewModel>("wasm/"+sFilePath, fileContent); } }; QFileDialog::getOpenFileContent("Fiff File (*.fif *.fiff)", fileContentReady); #else //Get the path QString sFilePath = QFileDialog::getOpenFileName(Q_NULLPTR, tr("Open File"), QDir::currentPath()+"/MNE-sample-data", tr("Fiff file(*.fif *.fiff)")); loadFilePath(sFilePath); #endif } //============================================================================================================= void DataLoader::onSaveFilePressed() { if(!m_pSelectedModel) { qWarning() << "[DataLoader::onSaveFilePressed] No model selected."; return; } #ifdef WASMBUILD m_pSelectedModel->saveToFile(""); #else //Get the path QString sFilePath = QFileDialog::getSaveFileName(Q_NULLPTR, tr("Save File"), QDir::currentPath()+"/MNE-sample-data", tr("Fiff file(*.fif *.fiff)")); QFileInfo fileInfo(sFilePath); m_pProgressView->setMessage("Saving " + fileInfo.fileName()); m_pProgressView->setLoadingBarVisible(false); m_pProgressViewWidget->show(); m_pProgressViewWidget->move(qApp->topLevelWindows().first()->screen()->geometry().center() - m_pProgressViewWidget->rect().center()); for (QWindow* window : qApp->topLevelWindows()){ window->setOpacity(0.8); for (QWidget* widget : window->findChildren<QWidget*>()){ widget->setEnabled(false); } } m_pProgressViewWidget->setWindowOpacity(1.0); QApplication::processEvents(); m_pSelectedModel->saveToFile(sFilePath); m_pProgressViewWidget->hide(); for (QWindow* window : qApp->topLevelWindows()){ window->setOpacity(1.0); for (QWidget* widget : window->findChildren<QWidget*>()){ widget->setEnabled(true); } } #endif }
//============================================================================================================= /** * @file dataloader.cpp * @author Lorenz Esch <[email protected]> * @since 0.1.0 * @date November, 2019 * * @section LICENSE * * Copyright (C) 2019, Lorenz Esch. 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 Definition of the DataLoader class. * */ //============================================================================================================= // INCLUDES //============================================================================================================= #include "dataloader.h" #include <anShared/Management/communicator.h> #include <anShared/Management/analyzedata.h> #include <anShared/Model/fiffrawviewmodel.h> #include <anShared/Model/bemdatamodel.h> #include <disp/viewers/progressview.h> //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace DATALOADERPLUGIN; using namespace ANSHAREDLIB; //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= DataLoader::DataLoader() : m_pProgressView(new DISPLIB::ProgressView(false)) , m_pProgressViewWidget(new QWidget()) { m_pProgressViewWidget->setWindowFlags(Qt::Window); QVBoxLayout* layout = new QVBoxLayout(m_pProgressViewWidget.data()); layout->addWidget(m_pProgressView); m_pProgressViewWidget->setLayout(layout); } //============================================================================================================= DataLoader::~DataLoader() { } //============================================================================================================= QSharedPointer<IPlugin> DataLoader::clone() const { QSharedPointer<DataLoader> pDataLoaderClone(new DataLoader); return pDataLoaderClone; } //============================================================================================================= void DataLoader::init() { m_pCommu = new Communicator(this); } //============================================================================================================= void DataLoader::unload() { } //============================================================================================================= QString DataLoader::getName() const { return "Data Loader"; } //============================================================================================================= QMenu *DataLoader::getMenu() { QMenu* pMenuFile = new QMenu(tr("File")); QAction* pActionLoad = new QAction(tr("Open")); pActionLoad->setStatusTip(tr("Load a data file")); connect(pActionLoad, &QAction::triggered, this, &DataLoader::onLoadFilePressed); QAction* pActionSave = new QAction(tr("Save")); pActionLoad->setStatusTip(tr("Save the selected data file")); connect(pActionSave, &QAction::triggered, this, &DataLoader::onSaveFilePressed); pMenuFile->addAction(pActionLoad); pMenuFile->addAction(pActionSave); return pMenuFile; } //============================================================================================================= QDockWidget *DataLoader::getControl() { return Q_NULLPTR; } //============================================================================================================= QWidget *DataLoader::getView() { return Q_NULLPTR; } //============================================================================================================= void DataLoader::handleEvent(QSharedPointer<Event> e) { switch (e->getType()) { case EVENT_TYPE::SELECTED_MODEL_CHANGED: if(e->getData().value<QSharedPointer<ANSHAREDLIB::AbstractModel> >()) { m_pSelectedModel = e->getData().value<QSharedPointer<ANSHAREDLIB::AbstractModel> >(); } break; default: qWarning() << "[DataLoader::handleEvent] Received an Event that is not handled by switch cases."; } } //============================================================================================================= QVector<EVENT_TYPE> DataLoader::getEventSubscriptions(void) const { QVector<EVENT_TYPE> temp = {SELECTED_MODEL_CHANGED}; return temp; } //============================================================================================================= void DataLoader::cmdLineStartup(const QStringList& sArguments) { if(sArguments.size() == 2 && (sArguments.first() == "file" || sArguments.first() == "f")) { loadFilePath(sArguments.at(1)); } } //============================================================================================================= void DataLoader::loadFilePath(const QString& sFilePath) { QFileInfo fileInfo(sFilePath); m_pProgressView->setMessage("Loading " + fileInfo.fileName()); m_pProgressView->setLoadingBarVisible(false); m_pProgressViewWidget->show(); m_pProgressViewWidget->move(qApp->topLevelWindows().first()->screen()->geometry().center() - m_pProgressViewWidget->rect().center()); for (QWindow* window : qApp->topLevelWindows()){ window->setOpacity(0.8); for (QWidget* widget : window->findChildren<QWidget*>()){ widget->setEnabled(false); } } QApplication::processEvents(); if(!fileInfo.exists() || (fileInfo.completeSuffix() != "fif")) { qWarning() << "[DataLoader::loadFilePath] The file does not exists or is not a .fif file."; return; } if(fileInfo.completeBaseName().endsWith("raw")) { m_pAnalyzeData->loadModel<ANSHAREDLIB::FiffRawViewModel>(sFilePath); } else if(fileInfo.completeBaseName().endsWith("bem")) { m_pAnalyzeData->loadModel<ANSHAREDLIB::BemDataModel>(sFilePath); } else { qWarning() << "[DataLoader::loadFilePath] Make sure that your files agree with the MNE naming conventions, eg.: *bem.fif; *raw.fif."; } m_pProgressViewWidget->hide(); for (QWindow* window : qApp->topLevelWindows()){ window->setOpacity(1.0); for (QWidget* widget : window->findChildren<QWidget*>()){ widget->setEnabled(true); } } } //============================================================================================================= void DataLoader::onLoadFilePressed() { #ifdef WASMBUILD auto fileContentReady = [&](const QString &sFilePath, const QByteArray &fileContent) { if(!sFilePath.isNull()) { // We need to prepend "wasm/" because QFileDialog::getOpenFileContent does not provide a full // path, which we need for organzing the different models in AnalyzeData m_pAnalyzeData->loadModel<FiffRawViewModel>("wasm/"+sFilePath, fileContent); } }; QFileDialog::getOpenFileContent("Fiff File (*.fif *.fiff)", fileContentReady); #else //Get the path QString sFilePath = QFileDialog::getOpenFileName(Q_NULLPTR, tr("Open File"), QDir::currentPath()+"/MNE-sample-data", tr("Fiff file(*.fif *.fiff)")); loadFilePath(sFilePath); #endif } //============================================================================================================= void DataLoader::onSaveFilePressed() { if(!m_pSelectedModel) { qWarning() << "[DataLoader::onSaveFilePressed] No model selected."; return; } #ifdef WASMBUILD m_pSelectedModel->saveToFile(""); #else //Get the path QString sFilePath = QFileDialog::getSaveFileName(Q_NULLPTR, tr("Save File"), QDir::currentPath()+"/MNE-sample-data", tr("Fiff file(*.fif *.fiff)")); QFileInfo fileInfo(sFilePath); m_pProgressView->setMessage("Saving " + fileInfo.fileName()); m_pProgressView->setLoadingBarVisible(false); m_pProgressViewWidget->show(); m_pProgressViewWidget->move(qApp->topLevelWindows().first()->screen()->geometry().center() - m_pProgressViewWidget->rect().center()); for (QWindow* window : qApp->topLevelWindows()){ window->setOpacity(0.8); for (QWidget* widget : window->findChildren<QWidget*>()){ widget->setEnabled(false); } } m_pProgressViewWidget->setWindowOpacity(1.0); QApplication::processEvents(); m_pSelectedModel->saveToFile(sFilePath); m_pProgressViewWidget->hide(); for (QWindow* window : qApp->topLevelWindows()){ window->setOpacity(1.0); for (QWidget* widget : window->findChildren<QWidget*>()){ widget->setEnabled(true); } } #endif }
add data type differentiation while loading
Enh: add data type differentiation while loading
C++
bsd-3-clause
mne-tools/mne-cpp,LorenzE/mne-cpp,chdinh/mne-cpp,mne-tools/mne-cpp,chdinh/mne-cpp,chdinh/mne-cpp,chdinh/mne-cpp,chdinh/mne-cpp,mne-tools/mne-cpp,chdinh/mne-cpp,LorenzE/mne-cpp,LorenzE/mne-cpp,LorenzE/mne-cpp,mne-tools/mne-cpp,mne-tools/mne-cpp,mne-tools/mne-cpp
cbe02f8911d975d6f6205d5e6bc85c187c320c12
examples/example.hpp
examples/example.hpp
// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2015 Intel Corporation. All Rights Reserved. #pragma once #define GLFW_INCLUDE_GLU #include <GLFW/glfw3.h> #include <string> #include <sstream> #include <iostream> #include <algorithm> ////////////////////////////// // Basic Data Types // ////////////////////////////// struct float3 { float x, y, z; }; struct float2 { float x, y; }; struct rect { float x, y; float w, h; // Create new rect within original boundaries with give aspect ration rect adjust_ratio(float2 size) const { auto H = static_cast<float>(h), W = static_cast<float>(h) * size.x / size.y; if (W > w) { auto scale = w / W; W *= scale; H *= scale; } return{ x + (w - W) / 2, y + (h - H) / 2, W, H }; } }; ////////////////////////////// // Simple font loading code // ////////////////////////////// #include "../third-party/stb_easy_font.h" inline void draw_text(int x, int y, const char * text) { char buffer[60000]; // ~300 chars glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(2, GL_FLOAT, 16, buffer); glDrawArrays(GL_QUADS, 0, 4 * stb_easy_font_print((float)x, (float)(y - 7), (char *)text, nullptr, buffer, sizeof(buffer))); glDisableClientState(GL_VERTEX_ARRAY); } //////////////////////// // Image display code // //////////////////////// class texture { public: void render(const rs2::frameset& frames, int window_width, int window_height) { std::vector<rs2::video_frame> supported_frames; for (auto f : frames) { if (can_render(f)) supported_frames.push_back(f); } if (supported_frames.empty()) return; std::sort(supported_frames.begin(), supported_frames.end(), [](rs2::frame first, rs2::frame second) { return first.get_profile().stream_type() < second.get_profile().stream_type(); }); auto image_grid = calc_grid(float2{ (float)window_width, (float)window_height }, supported_frames); int image_index = 0; for (auto f : supported_frames) { upload(f); show(image_grid.at(image_index)); image_index++; } } void render(const rs2::video_frame& frame, const rect& r) { upload(frame); show(r.adjust_ratio({ float(width), float(height) })); } void upload(const rs2::video_frame& frame) { if (!frame) return; if (!gl_handle) glGenTextures(1, &gl_handle); GLenum err = glGetError(); auto format = frame.get_profile().format(); width = frame.get_width(); height = frame.get_height(); stream = frame.get_profile().stream_type(); glBindTexture(GL_TEXTURE_2D, gl_handle); switch (format) { case RS2_FORMAT_RGB8: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, frame.get_data()); break; case RS2_FORMAT_RGBA8: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, frame.get_data()); break; case RS2_FORMAT_Y8: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, frame.get_data()); break; default: throw std::runtime_error("The requested format is not supported by this demo!"); } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); glBindTexture(GL_TEXTURE_2D, 0); } GLuint get_gl_handle() { return gl_handle; } void show(const rect& r) const { if (!gl_handle) return; glBindTexture(GL_TEXTURE_2D, gl_handle); glEnable(GL_TEXTURE_2D); glBegin(GL_QUAD_STRIP); glTexCoord2f(0.f, 1.f); glVertex2f(r.x, r.y + r.h); glTexCoord2f(0.f, 0.f); glVertex2f(r.x, r.y); glTexCoord2f(1.f, 1.f); glVertex2f(r.x + r.w, r.y + r.h); glTexCoord2f(1.f, 0.f); glVertex2f(r.x + r.w, r.y); glEnd(); glDisable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, 0); draw_text((int)r.x + 15, (int)r.y + 20, rs2_stream_to_string(stream)); } private: GLuint gl_handle = 0; int width = 0; int height = 0; rs2_stream stream = RS2_STREAM_ANY; bool can_render(const rs2::frame& f) const { auto format = f.get_profile().format(); switch (format) { case RS2_FORMAT_RGB8: case RS2_FORMAT_RGBA8: case RS2_FORMAT_Y8: return true; default: return false; } } rect calc_grid(float2 window, int streams) { if (window.x <= 0 || window.y <= 0 || streams <= 0) throw std::runtime_error("invalid window configuration request, failed to calculate window grid"); float ratio = window.x / window.y; auto x = sqrt(ratio * (float)streams); auto y = (float)streams / x; auto w = round(x); auto h = round(y); if (w == 0 || h == 0) throw std::runtime_error("invalid window configuration request, failed to calculate window grid"); while (w*h > streams) h > w ? h-- : w--; while (w*h < streams) h > w ? w++ : h++; auto new_w = round(window.x / w); auto new_h = round(window.y / h); return rect{ w, h, new_w, new_h}; //column count, line count, cell width cell height } std::vector<rect> calc_grid(float2 window, std::vector<rs2::video_frame>& frames) { auto grid = calc_grid(window, frames.size()); int index = 0; std::vector<rect> rv; int curr_line = -1; for (auto f : frames) { auto mod = index % (int)grid.x; auto fw = (float)frames[index].get_width(); auto fh = (float)frames[index].get_height(); float cell_x_postion = (float)(mod * grid.w); if (mod == 0) curr_line++; float cell_y_position = curr_line * grid.h; auto r = rect{ cell_x_postion, cell_y_position, grid.w, grid.h }; rv.push_back(r.adjust_ratio(float2{ fw, fh })); index++; } return rv; } }; class window { public: std::function<void(bool)> on_left_mouse = [](bool) {}; std::function<void(double, double)> on_mouse_scroll = [](double, double) {}; std::function<void(double, double)> on_mouse_move = [](double, double) {}; std::function<void(int)> on_key_release = [](int) {}; window(int width, int height, const char* title) : _width(width), _height(height) { glfwInit(); win = glfwCreateWindow(width, height, title, nullptr, nullptr); if (!win) throw std::runtime_error("Could not open OpenGL window, please check your graphic drivers or use the textual SDK tools"); glfwMakeContextCurrent(win); glfwSetWindowUserPointer(win, this); glfwSetMouseButtonCallback(win, [](GLFWwindow * win, int button, int action, int mods) { auto s = (window*)glfwGetWindowUserPointer(win); if (button == 0) s->on_left_mouse(action == GLFW_PRESS); }); glfwSetScrollCallback(win, [](GLFWwindow * win, double xoffset, double yoffset) { auto s = (window*)glfwGetWindowUserPointer(win); s->on_mouse_scroll(xoffset, yoffset); }); glfwSetCursorPosCallback(win, [](GLFWwindow * win, double x, double y) { auto s = (window*)glfwGetWindowUserPointer(win); s->on_mouse_move(x, y); }); glfwSetKeyCallback(win, [](GLFWwindow * win, int key, int scancode, int action, int mods) { auto s = (window*)glfwGetWindowUserPointer(win); if (0 == action) // on key release { s->on_key_release(key); } }); } float width() const { return float(_width); } float height() const { return float(_height); } operator bool() { glPopMatrix(); glfwSwapBuffers(win); auto res = !glfwWindowShouldClose(win); glfwPollEvents(); glfwGetFramebufferSize(win, &_width, &_height); // Clear the framebuffer glClear(GL_COLOR_BUFFER_BIT); glViewport(0, 0, _width, _height); // Draw the images glPushMatrix(); glfwGetWindowSize(win, &_width, &_height); glOrtho(0, _width, _height, 0, -1, +1); return res; } ~window() { glfwDestroyWindow(win); glfwTerminate(); } operator GLFWwindow*() { return win; } private: GLFWwindow * win; int _width, _height; }; // Struct for managing rotation of pointcloud view struct glfw_state { glfw_state() : yaw(15.0), pitch(15.0), last_x(0.0), last_y(0.0), ml(false), offset_x(2.f), offset_y(2.f), tex() {} double yaw; double pitch; double last_x; double last_y; bool ml; float offset_x; float offset_y; texture tex; }; // Handles all the OpenGL calls needed to display the point cloud void draw_pointcloud(float width, float height, glfw_state& app_state, rs2::points& points) { if (!points) return; // OpenGL commands that prep screen for the pointcloud glPopMatrix(); glPushAttrib(GL_ALL_ATTRIB_BITS); glClearColor(153.f / 255, 153.f / 255, 153.f / 255, 1); glClear(GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glPushMatrix(); gluPerspective(60, width / height, 0.01f, 10.0f); glMatrixMode(GL_MODELVIEW); glPushMatrix(); gluLookAt(0, 0, 0, 0, 0, 1, 0, -1, 0); glTranslatef(0, 0, +0.5f + app_state.offset_y*0.05f); glRotated(app_state.pitch, 1, 0, 0); glRotated(app_state.yaw, 0, 1, 0); glTranslatef(0, 0, -0.5f); glPointSize(width / 640); glEnable(GL_DEPTH_TEST); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, app_state.tex.get_gl_handle()); float tex_border_color[] = { 0.8f, 0.8f, 0.8f, 0.8f }; glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, tex_border_color); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, 0x812F); // GL_CLAMP_TO_EDGE glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, 0x812F); // GL_CLAMP_TO_EDGE glBegin(GL_POINTS); /* this segment actually prints the pointcloud */ auto vertices = points.get_vertices(); // get vertices auto tex_coords = points.get_texture_coordinates(); // and texture coordinates for (int i = 0; i < points.size(); i++) { if (vertices[i].z) { // upload the point and texture coordinates only for points we have depth data for glVertex3fv(vertices[i]); glTexCoord2fv(tex_coords[i]); } } // OpenGL cleanup glEnd(); glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); glPopAttrib(); glPushMatrix(); } // Registers the state variable and callbacks to allow mouse control of the pointcloud void register_glfw_callbacks(window& app, glfw_state& app_state) { app.on_left_mouse = [&](bool pressed) { app_state.ml = pressed; }; app.on_mouse_scroll = [&](double xoffset, double yoffset) { app_state.offset_x -= static_cast<float>(xoffset); app_state.offset_y -= static_cast<float>(yoffset); }; app.on_mouse_move = [&](double x, double y) { if (app_state.ml) { app_state.yaw -= (x - app_state.last_x); app_state.yaw = std::max(app_state.yaw, -120.0); app_state.yaw = std::min(app_state.yaw, +120.0); app_state.pitch += (y - app_state.last_y); app_state.pitch = std::max(app_state.pitch, -80.0); app_state.pitch = std::min(app_state.pitch, +80.0); } app_state.last_x = x; app_state.last_y = y; }; app.on_key_release = [&](int key) { if (key == 32) // Escape { app_state.yaw = app_state.pitch = 0; app_state.offset_x = app_state.offset_y = 0.0; } }; }
// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2015 Intel Corporation. All Rights Reserved. #pragma once #define GLFW_INCLUDE_GLU #include <GLFW/glfw3.h> #include <string> #include <sstream> #include <iostream> #include <algorithm> ////////////////////////////// // Basic Data Types // ////////////////////////////// struct float3 { float x, y, z; }; struct float2 { float x, y; }; struct rect { float x, y; float w, h; // Create new rect within original boundaries with give aspect ration rect adjust_ratio(float2 size) const { auto H = static_cast<float>(h), W = static_cast<float>(h) * size.x / size.y; if (W > w) { auto scale = w / W; W *= scale; H *= scale; } return{ x + (w - W) / 2, y + (h - H) / 2, W, H }; } }; ////////////////////////////// // Simple font loading code // ////////////////////////////// #include "../third-party/stb_easy_font.h" inline void draw_text(int x, int y, const char * text) { char buffer[60000]; // ~300 chars glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(2, GL_FLOAT, 16, buffer); glDrawArrays(GL_QUADS, 0, 4 * stb_easy_font_print((float)x, (float)(y - 7), (char *)text, nullptr, buffer, sizeof(buffer))); glDisableClientState(GL_VERTEX_ARRAY); } //////////////////////// // Image display code // //////////////////////// class texture { public: void render(const rs2::frameset& frames, int window_width, int window_height) { std::vector<rs2::video_frame> supported_frames; for (auto f : frames) { if (can_render(f)) supported_frames.push_back(f); } if (supported_frames.empty()) return; std::sort(supported_frames.begin(), supported_frames.end(), [](rs2::frame first, rs2::frame second) { return first.get_profile().stream_type() < second.get_profile().stream_type(); }); auto image_grid = calc_grid(float2{ (float)window_width, (float)window_height }, supported_frames); int image_index = 0; for (auto f : supported_frames) { upload(f); show(image_grid.at(image_index)); image_index++; } } void render(const rs2::video_frame& frame, const rect& r) { upload(frame); show(r.adjust_ratio({ float(width), float(height) })); } void upload(const rs2::video_frame& frame) { if (!frame) return; if (!gl_handle) glGenTextures(1, &gl_handle); GLenum err = glGetError(); auto format = frame.get_profile().format(); width = frame.get_width(); height = frame.get_height(); stream = frame.get_profile().stream_type(); glBindTexture(GL_TEXTURE_2D, gl_handle); switch (format) { case RS2_FORMAT_RGB8: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, frame.get_data()); break; case RS2_FORMAT_RGBA8: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, frame.get_data()); break; case RS2_FORMAT_Y8: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, frame.get_data()); break; default: throw std::runtime_error("The requested format is not supported by this demo!"); } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); glBindTexture(GL_TEXTURE_2D, 0); } GLuint get_gl_handle() { return gl_handle; } void show(const rect& r) const { if (!gl_handle) return; glBindTexture(GL_TEXTURE_2D, gl_handle); glEnable(GL_TEXTURE_2D); glBegin(GL_QUAD_STRIP); glTexCoord2f(0.f, 1.f); glVertex2f(r.x, r.y + r.h); glTexCoord2f(0.f, 0.f); glVertex2f(r.x, r.y); glTexCoord2f(1.f, 1.f); glVertex2f(r.x + r.w, r.y + r.h); glTexCoord2f(1.f, 0.f); glVertex2f(r.x + r.w, r.y); glEnd(); glDisable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, 0); draw_text((int)r.x + 15, (int)r.y + 20, rs2_stream_to_string(stream)); } private: GLuint gl_handle = 0; int width = 0; int height = 0; rs2_stream stream = RS2_STREAM_ANY; bool can_render(const rs2::frame& f) const { auto format = f.get_profile().format(); switch (format) { case RS2_FORMAT_RGB8: case RS2_FORMAT_RGBA8: case RS2_FORMAT_Y8: return true; default: return false; } } rect calc_grid(float2 window, int streams) { if (window.x <= 0 || window.y <= 0 || streams <= 0) throw std::runtime_error("invalid window configuration request, failed to calculate window grid"); float ratio = window.x / window.y; auto x = sqrt(ratio * (float)streams); auto y = (float)streams / x; auto w = round(x); auto h = round(y); if (w == 0 || h == 0) throw std::runtime_error("invalid window configuration request, failed to calculate window grid"); while (w*h > streams) h > w ? h-- : w--; while (w*h < streams) h > w ? w++ : h++; auto new_w = round(window.x / w); auto new_h = round(window.y / h); // column count, line count, cell width cell height return rect{ static_cast<float>(w), static_cast<float>(h), static_cast<float>(new_w), static_cast<float>(new_h) }; } std::vector<rect> calc_grid(float2 window, std::vector<rs2::video_frame>& frames) { auto grid = calc_grid(window, frames.size()); int index = 0; std::vector<rect> rv; int curr_line = -1; for (auto f : frames) { auto mod = index % (int)grid.x; auto fw = (float)frames[index].get_width(); auto fh = (float)frames[index].get_height(); float cell_x_postion = (float)(mod * grid.w); if (mod == 0) curr_line++; float cell_y_position = curr_line * grid.h; auto r = rect{ cell_x_postion, cell_y_position, grid.w, grid.h }; rv.push_back(r.adjust_ratio(float2{ fw, fh })); index++; } return rv; } }; class window { public: std::function<void(bool)> on_left_mouse = [](bool) {}; std::function<void(double, double)> on_mouse_scroll = [](double, double) {}; std::function<void(double, double)> on_mouse_move = [](double, double) {}; std::function<void(int)> on_key_release = [](int) {}; window(int width, int height, const char* title) : _width(width), _height(height) { glfwInit(); win = glfwCreateWindow(width, height, title, nullptr, nullptr); if (!win) throw std::runtime_error("Could not open OpenGL window, please check your graphic drivers or use the textual SDK tools"); glfwMakeContextCurrent(win); glfwSetWindowUserPointer(win, this); glfwSetMouseButtonCallback(win, [](GLFWwindow * win, int button, int action, int mods) { auto s = (window*)glfwGetWindowUserPointer(win); if (button == 0) s->on_left_mouse(action == GLFW_PRESS); }); glfwSetScrollCallback(win, [](GLFWwindow * win, double xoffset, double yoffset) { auto s = (window*)glfwGetWindowUserPointer(win); s->on_mouse_scroll(xoffset, yoffset); }); glfwSetCursorPosCallback(win, [](GLFWwindow * win, double x, double y) { auto s = (window*)glfwGetWindowUserPointer(win); s->on_mouse_move(x, y); }); glfwSetKeyCallback(win, [](GLFWwindow * win, int key, int scancode, int action, int mods) { auto s = (window*)glfwGetWindowUserPointer(win); if (0 == action) // on key release { s->on_key_release(key); } }); } float width() const { return float(_width); } float height() const { return float(_height); } operator bool() { glPopMatrix(); glfwSwapBuffers(win); auto res = !glfwWindowShouldClose(win); glfwPollEvents(); glfwGetFramebufferSize(win, &_width, &_height); // Clear the framebuffer glClear(GL_COLOR_BUFFER_BIT); glViewport(0, 0, _width, _height); // Draw the images glPushMatrix(); glfwGetWindowSize(win, &_width, &_height); glOrtho(0, _width, _height, 0, -1, +1); return res; } ~window() { glfwDestroyWindow(win); glfwTerminate(); } operator GLFWwindow*() { return win; } private: GLFWwindow * win; int _width, _height; }; // Struct for managing rotation of pointcloud view struct glfw_state { glfw_state() : yaw(15.0), pitch(15.0), last_x(0.0), last_y(0.0), ml(false), offset_x(2.f), offset_y(2.f), tex() {} double yaw; double pitch; double last_x; double last_y; bool ml; float offset_x; float offset_y; texture tex; }; // Handles all the OpenGL calls needed to display the point cloud void draw_pointcloud(float width, float height, glfw_state& app_state, rs2::points& points) { if (!points) return; // OpenGL commands that prep screen for the pointcloud glPopMatrix(); glPushAttrib(GL_ALL_ATTRIB_BITS); glClearColor(153.f / 255, 153.f / 255, 153.f / 255, 1); glClear(GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glPushMatrix(); gluPerspective(60, width / height, 0.01f, 10.0f); glMatrixMode(GL_MODELVIEW); glPushMatrix(); gluLookAt(0, 0, 0, 0, 0, 1, 0, -1, 0); glTranslatef(0, 0, +0.5f + app_state.offset_y*0.05f); glRotated(app_state.pitch, 1, 0, 0); glRotated(app_state.yaw, 0, 1, 0); glTranslatef(0, 0, -0.5f); glPointSize(width / 640); glEnable(GL_DEPTH_TEST); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, app_state.tex.get_gl_handle()); float tex_border_color[] = { 0.8f, 0.8f, 0.8f, 0.8f }; glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, tex_border_color); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, 0x812F); // GL_CLAMP_TO_EDGE glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, 0x812F); // GL_CLAMP_TO_EDGE glBegin(GL_POINTS); /* this segment actually prints the pointcloud */ auto vertices = points.get_vertices(); // get vertices auto tex_coords = points.get_texture_coordinates(); // and texture coordinates for (int i = 0; i < points.size(); i++) { if (vertices[i].z) { // upload the point and texture coordinates only for points we have depth data for glVertex3fv(vertices[i]); glTexCoord2fv(tex_coords[i]); } } // OpenGL cleanup glEnd(); glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); glPopAttrib(); glPushMatrix(); } // Registers the state variable and callbacks to allow mouse control of the pointcloud void register_glfw_callbacks(window& app, glfw_state& app_state) { app.on_left_mouse = [&](bool pressed) { app_state.ml = pressed; }; app.on_mouse_scroll = [&](double xoffset, double yoffset) { app_state.offset_x -= static_cast<float>(xoffset); app_state.offset_y -= static_cast<float>(yoffset); }; app.on_mouse_move = [&](double x, double y) { if (app_state.ml) { app_state.yaw -= (x - app_state.last_x); app_state.yaw = std::max(app_state.yaw, -120.0); app_state.yaw = std::min(app_state.yaw, +120.0); app_state.pitch += (y - app_state.last_y); app_state.pitch = std::max(app_state.pitch, -80.0); app_state.pitch = std::min(app_state.pitch, +80.0); } app_state.last_x = x; app_state.last_y = y; }; app.on_key_release = [&](int key) { if (key == 32) // Escape { app_state.yaw = app_state.pitch = 0; app_state.offset_x = app_state.offset_y = 0.0; } }; }
Fix narrowing conversion error for osx clang
Fix narrowing conversion error for osx clang
C++
apache-2.0
IntelRealSense/librealsense,IntelRealSense/librealsense,IntelRealSense/librealsense,IntelRealSense/librealsense,IntelRealSense/librealsense,IntelRealSense/librealsense,IntelRealSense/librealsense,IntelRealSense/librealsense,IntelRealSense/librealsense
d5367c738b60d1c2924653057bae7174c9bd9540
chrome/browser/chromeos/drive/resource_entry_conversion.cc
chrome/browser/chromeos/drive/resource_entry_conversion.cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/drive/resource_entry_conversion.h" #include <algorithm> #include <string> #include "base/logging.h" #include "base/platform_file.h" #include "base/time/time.h" #include "chrome/browser/chromeos/drive/drive.pb.h" #include "chrome/browser/chromeos/drive/file_system_util.h" #include "chrome/browser/drive/drive_api_util.h" #include "chrome/browser/google_apis/gdata_wapi_parser.h" namespace drive { namespace { const char kSharedWithMeLabel[] = "shared-with-me"; // Checks if |entry| has a label "shared-with-me", which is added to entries // shared with the user. bool HasSharedWithMeLabel(const google_apis::ResourceEntry& entry) { std::vector<std::string>::const_iterator it = std::find(entry.labels().begin(), entry.labels().end(), kSharedWithMeLabel); return it != entry.labels().end(); } } // namespace bool ConvertToResourceEntry(const google_apis::ResourceEntry& input, ResourceEntry* output) { DCHECK(output); // For regular files, the 'filename' and 'title' attribute in the metadata // may be different (e.g. due to rename). To be consistent with the web // interface and other client to use the 'title' attribute, instead of // 'filename', as the file name in the local snapshot. output->set_title(input.title()); output->set_base_name(util::NormalizeFileName(output->title())); output->set_resource_id(input.resource_id()); // Sets parent Resource ID. On drive.google.com, a file can have multiple // parents or no parent, but we are forcing a tree-shaped structure (i.e. no // multi-parent or zero-parent entries). Therefore the first found "parent" is // used for the entry and if the entry has no parent, we assign a special ID // which represents no-parent entries. Tracked in http://crbug.com/158904. const google_apis::Link* parent_link = input.GetLinkByType(google_apis::Link::LINK_PARENT); if (parent_link) { output->set_parent_resource_id(util::ExtractResourceIdFromUrl( parent_link->href())); } // Apply mapping from an empty parent to the special dummy directory. if (output->parent_resource_id().empty()) output->set_parent_resource_id(util::kDriveOtherDirSpecialResourceId); output->set_deleted(input.deleted()); output->set_shared_with_me(HasSharedWithMeLabel(input)); PlatformFileInfoProto* file_info = output->mutable_file_info(); file_info->set_last_modified(input.updated_time().ToInternalValue()); // If the file has never been viewed (last_viewed_time().is_null() == true), // then we will set the last_accessed field in the protocol buffer to 0. file_info->set_last_accessed(input.last_viewed_time().ToInternalValue()); file_info->set_creation_time(input.published_time().ToInternalValue()); if (input.is_file() || input.is_hosted_document()) { FileSpecificInfo* file_specific_info = output->mutable_file_specific_info(); if (input.is_file()) { file_info->set_size(input.file_size()); file_specific_info->set_md5(input.file_md5()); // The resumable-edit-media link should only be present for regular // files as hosted documents are not uploadable. } else if (input.is_hosted_document()) { // Attach .g<something> extension to hosted documents so we can special // case their handling in UI. // TODO(satorux): Figure out better way how to pass input info like kind // to UI through the File API stack. const std::string document_extension = input.GetHostedDocumentExtension(); file_specific_info->set_document_extension(document_extension); output->set_base_name( util::NormalizeFileName(output->title() + document_extension)); // We don't know the size of hosted docs and it does not matter since // is has no effect on the quota. file_info->set_size(0); } file_info->set_is_directory(false); file_specific_info->set_content_mime_type(input.content_mime_type()); file_specific_info->set_is_hosted_document(input.is_hosted_document()); const google_apis::Link* thumbnail_link = input.GetLinkByType(google_apis::Link::LINK_THUMBNAIL); if (thumbnail_link) file_specific_info->set_thumbnail_url(thumbnail_link->href().spec()); const google_apis::Link* alternate_link = input.GetLinkByType(google_apis::Link::LINK_ALTERNATE); if (alternate_link) file_specific_info->set_alternate_url(alternate_link->href().spec()); } else if (input.is_folder()) { file_info->set_is_directory(true); } else { // There are two cases to reach here. // * The entry is something that doesn't map into files (i.e. sites). // We don't handle these kind of entries hence return false. // * The entry is un-shared to you by other owner. In that case, we // get an entry with only deleted() and resource_id() fields are // filled. Since we want to delete such entries locally as well, // in that case we need to return true to proceed. return input.deleted(); } return true; } void ConvertResourceEntryToPlatformFileInfo(const ResourceEntry& entry, base::PlatformFileInfo* file_info) { file_info->size = entry.file_info().size(); file_info->is_directory = entry.file_info().is_directory(); file_info->is_symbolic_link = entry.file_info().is_symbolic_link(); file_info->last_modified = base::Time::FromInternalValue( entry.file_info().last_modified()); file_info->last_accessed = base::Time::FromInternalValue( entry.file_info().last_accessed()); file_info->creation_time = base::Time::FromInternalValue( entry.file_info().creation_time()); } void SetPlatformFileInfoToResourceEntry(const base::PlatformFileInfo& file_info, ResourceEntry* entry) { PlatformFileInfoProto* entry_file_info = entry->mutable_file_info(); entry_file_info->set_size(file_info.size); entry_file_info->set_is_directory(file_info.is_directory); entry_file_info->set_is_symbolic_link(file_info.is_symbolic_link); entry_file_info->set_last_modified(file_info.last_modified.ToInternalValue()); entry_file_info->set_last_accessed(file_info.last_accessed.ToInternalValue()); entry_file_info->set_creation_time(file_info.creation_time.ToInternalValue()); } } // namespace drive
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/drive/resource_entry_conversion.h" #include <algorithm> #include <string> #include "base/logging.h" #include "base/platform_file.h" #include "base/time/time.h" #include "chrome/browser/chromeos/drive/drive.pb.h" #include "chrome/browser/chromeos/drive/file_system_util.h" #include "chrome/browser/drive/drive_api_util.h" #include "chrome/browser/google_apis/gdata_wapi_parser.h" namespace drive { namespace { const char kSharedWithMeLabel[] = "shared-with-me"; // Checks if |entry| has a label "shared-with-me", which is added to entries // shared with the user. bool HasSharedWithMeLabel(const google_apis::ResourceEntry& entry) { std::vector<std::string>::const_iterator it = std::find(entry.labels().begin(), entry.labels().end(), kSharedWithMeLabel); return it != entry.labels().end(); } } // namespace bool ConvertToResourceEntry(const google_apis::ResourceEntry& input, ResourceEntry* output) { DCHECK(output); // For regular files, the 'filename' and 'title' attribute in the metadata // may be different (e.g. due to rename). To be consistent with the web // interface and other client to use the 'title' attribute, instead of // 'filename', as the file name in the local snapshot. output->set_title(input.title()); output->set_base_name(util::NormalizeFileName(output->title())); output->set_resource_id(input.resource_id()); // Sets parent Resource ID. On drive.google.com, a file can have multiple // parents or no parent, but we are forcing a tree-shaped structure (i.e. no // multi-parent or zero-parent entries). Therefore the first found "parent" is // used for the entry and if the entry has no parent, we assign a special ID // which represents no-parent entries. Tracked in http://crbug.com/158904. const google_apis::Link* parent_link = input.GetLinkByType(google_apis::Link::LINK_PARENT); if (parent_link) { output->set_parent_resource_id(util::ExtractResourceIdFromUrl( parent_link->href())); } // Apply mapping from an empty parent to the special dummy directory. if (output->parent_resource_id().empty()) output->set_parent_resource_id(util::kDriveOtherDirSpecialResourceId); output->set_deleted(input.deleted()); output->set_shared_with_me(HasSharedWithMeLabel(input)); PlatformFileInfoProto* file_info = output->mutable_file_info(); file_info->set_last_modified(input.updated_time().ToInternalValue()); // If the file has never been viewed (last_viewed_time().is_null() == true), // then we will set the last_accessed field in the protocol buffer to 0. file_info->set_last_accessed(input.last_viewed_time().ToInternalValue()); file_info->set_creation_time(input.published_time().ToInternalValue()); if (input.is_file() || input.is_hosted_document()) { FileSpecificInfo* file_specific_info = output->mutable_file_specific_info(); if (input.is_file()) { file_info->set_size(input.file_size()); file_specific_info->set_md5(input.file_md5()); // The resumable-edit-media link should only be present for regular // files as hosted documents are not uploadable. } else if (input.is_hosted_document()) { // Attach .g<something> extension to hosted documents so we can special // case their handling in UI. // TODO(satorux): Figure out better way how to pass input info like kind // to UI through the File API stack. const std::string document_extension = input.GetHostedDocumentExtension(); file_specific_info->set_document_extension(document_extension); output->set_base_name( util::NormalizeFileName(output->title() + document_extension)); // We don't know the size of hosted docs and it does not matter since // is has no effect on the quota. file_info->set_size(0); } file_info->set_is_directory(false); file_specific_info->set_content_mime_type(input.content_mime_type()); file_specific_info->set_is_hosted_document(input.is_hosted_document()); const google_apis::Link* thumbnail_link = input.GetLinkByType(google_apis::Link::LINK_THUMBNAIL); if (thumbnail_link) file_specific_info->set_thumbnail_url(thumbnail_link->href().spec()); const google_apis::Link* alternate_link = input.GetLinkByType(google_apis::Link::LINK_ALTERNATE); if (alternate_link) file_specific_info->set_alternate_url(alternate_link->href().spec()); } else if (input.is_folder()) { file_info->set_is_directory(true); } else { // Some resource entries don't map into files (i.e. sites). return false; } return true; } void ConvertResourceEntryToPlatformFileInfo(const ResourceEntry& entry, base::PlatformFileInfo* file_info) { file_info->size = entry.file_info().size(); file_info->is_directory = entry.file_info().is_directory(); file_info->is_symbolic_link = entry.file_info().is_symbolic_link(); file_info->last_modified = base::Time::FromInternalValue( entry.file_info().last_modified()); file_info->last_accessed = base::Time::FromInternalValue( entry.file_info().last_accessed()); file_info->creation_time = base::Time::FromInternalValue( entry.file_info().creation_time()); } void SetPlatformFileInfoToResourceEntry(const base::PlatformFileInfo& file_info, ResourceEntry* entry) { PlatformFileInfoProto* entry_file_info = entry->mutable_file_info(); entry_file_info->set_size(file_info.size); entry_file_info->set_is_directory(file_info.is_directory); entry_file_info->set_is_symbolic_link(file_info.is_symbolic_link); entry_file_info->set_last_modified(file_info.last_modified.ToInternalValue()); entry_file_info->set_last_accessed(file_info.last_accessed.ToInternalValue()); entry_file_info->set_creation_time(file_info.creation_time.ToInternalValue()); } } // namespace drive
Revert 214293 "Drive: Do not treat type-unknown deleted entries ..."
Revert 214293 "Drive: Do not treat type-unknown deleted entries ..." Specurative revert for bug 270308; let's try to see if the crash disappears. The change only fixes an error for a feature behind the flag in M30, so it should be fine to punt to M31. BUG=270308 > Drive: Do not treat type-unknown deleted entries as an error. > > When entries shared to the current user by other user is unshared, > such a change is reported as a 'deleted' entry with all other > metadata (including is_file() or is_folder()) unknown. To reflect > such deletion locally, we must not filter them out as an error. > > Note that this fixes the BUG only for --enable-drive-v2-api case. > > BUG=260020 > [email protected] > > Review URL: https://codereview.chromium.org/20559003 [email protected] Review URL: https://codereview.chromium.org/23000002 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@217161 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
crosswalk-project/chromium-crosswalk-efl,Chilledheart/chromium,fujunwei/chromium-crosswalk,markYoungH/chromium.src,Chilledheart/chromium,markYoungH/chromium.src,M4sse/chromium.src,ondra-novak/chromium.src,M4sse/chromium.src,ChromiumWebApps/chromium,Pluto-tv/chromium-crosswalk,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,dednal/chromium.src,anirudhSK/chromium,fujunwei/chromium-crosswalk,bright-sparks/chromium-spacewalk,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,ltilve/chromium,dushu1203/chromium.src,dushu1203/chromium.src,bright-sparks/chromium-spacewalk,fujunwei/chromium-crosswalk,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,Just-D/chromium-1,dushu1203/chromium.src,mohamed--abdel-maksoud/chromium.src,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,dushu1203/chromium.src,anirudhSK/chromium,anirudhSK/chromium,ltilve/chromium,dushu1203/chromium.src,Jonekee/chromium.src,M4sse/chromium.src,dushu1203/chromium.src,axinging/chromium-crosswalk,patrickm/chromium.src,Just-D/chromium-1,axinging/chromium-crosswalk,Jonekee/chromium.src,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,anirudhSK/chromium,markYoungH/chromium.src,fujunwei/chromium-crosswalk,patrickm/chromium.src,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,dednal/chromium.src,hgl888/chromium-crosswalk,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,ltilve/chromium,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,fujunwei/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,ChromiumWebApps/chromium,markYoungH/chromium.src,Just-D/chromium-1,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,Fireblend/chromium-crosswalk,chuan9/chromium-crosswalk,jaruba/chromium.src,crosswalk-project/chromium-crosswalk-efl,littlstar/chromium.src,axinging/chromium-crosswalk,ChromiumWebApps/chromium,axinging/chromium-crosswalk,ChromiumWebApps/chromium,Just-D/chromium-1,littlstar/chromium.src,ltilve/chromium,TheTypoMaster/chromium-crosswalk,mogoweb/chromium-crosswalk,krieger-od/nwjs_chromium.src,Chilledheart/chromium,Just-D/chromium-1,ondra-novak/chromium.src,dednal/chromium.src,Jonekee/chromium.src,bright-sparks/chromium-spacewalk,chuan9/chromium-crosswalk,jaruba/chromium.src,mogoweb/chromium-crosswalk,fujunwei/chromium-crosswalk,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,patrickm/chromium.src,Just-D/chromium-1,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,markYoungH/chromium.src,littlstar/chromium.src,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ChromiumWebApps/chromium,ondra-novak/chromium.src,anirudhSK/chromium,hgl888/chromium-crosswalk,M4sse/chromium.src,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,markYoungH/chromium.src,M4sse/chromium.src,anirudhSK/chromium,hgl888/chromium-crosswalk-efl,markYoungH/chromium.src,Chilledheart/chromium,Just-D/chromium-1,Chilledheart/chromium,hgl888/chromium-crosswalk-efl,anirudhSK/chromium,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,patrickm/chromium.src,M4sse/chromium.src,patrickm/chromium.src,bright-sparks/chromium-spacewalk,axinging/chromium-crosswalk,mogoweb/chromium-crosswalk,M4sse/chromium.src,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,littlstar/chromium.src,crosswalk-project/chromium-crosswalk-efl,dednal/chromium.src,ondra-novak/chromium.src,ondra-novak/chromium.src,mogoweb/chromium-crosswalk,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Jonekee/chromium.src,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,ChromiumWebApps/chromium,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,littlstar/chromium.src,ondra-novak/chromium.src,littlstar/chromium.src,krieger-od/nwjs_chromium.src,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk,ondra-novak/chromium.src,littlstar/chromium.src,Jonekee/chromium.src,mogoweb/chromium-crosswalk,axinging/chromium-crosswalk,ChromiumWebApps/chromium,Chilledheart/chromium,ltilve/chromium,patrickm/chromium.src,ChromiumWebApps/chromium,mogoweb/chromium-crosswalk,jaruba/chromium.src,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,ltilve/chromium,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,bright-sparks/chromium-spacewalk,ltilve/chromium,Chilledheart/chromium,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,markYoungH/chromium.src,ondra-novak/chromium.src,krieger-od/nwjs_chromium.src,dednal/chromium.src,hgl888/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,M4sse/chromium.src,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,jaruba/chromium.src,mogoweb/chromium-crosswalk,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,dednal/chromium.src,krieger-od/nwjs_chromium.src,mogoweb/chromium-crosswalk,ltilve/chromium,patrickm/chromium.src,jaruba/chromium.src,Fireblend/chromium-crosswalk,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,littlstar/chromium.src,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,anirudhSK/chromium,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,Pluto-tv/chromium-crosswalk,dushu1203/chromium.src,axinging/chromium-crosswalk,bright-sparks/chromium-spacewalk,M4sse/chromium.src,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,dednal/chromium.src,ChromiumWebApps/chromium,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,ondra-novak/chromium.src,dushu1203/chromium.src,ChromiumWebApps/chromium,patrickm/chromium.src,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,chuan9/chromium-crosswalk,jaruba/chromium.src,chuan9/chromium-crosswalk,anirudhSK/chromium,chuan9/chromium-crosswalk,krieger-od/nwjs_chromium.src,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,bright-sparks/chromium-spacewalk,PeterWangIntel/chromium-crosswalk,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,ltilve/chromium,dushu1203/chromium.src,chuan9/chromium-crosswalk,anirudhSK/chromium,chuan9/chromium-crosswalk,dednal/chromium.src
f8c7db538f0dce78ef6e5e8e6f6641b1c7e2eeb7
chrome/browser/extensions/extension_startup_browsertest.cc
chrome/browser/extensions/extension_startup_browsertest.cc
// Copyright (c) 2008 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 <vector> #include "base/command_line.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/path_service.h" #include "chrome/browser/browser.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/extensions/user_script_master.h" #include "chrome/browser/profile.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/notification_details.h" #include "chrome/common/notification_observer.h" #include "chrome/common/notification_registrar.h" #include "chrome/common/notification_service.h" #include "chrome/common/notification_type.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "net/base/net_util.h" // This file contains high-level startup tests for the extensions system. We've // had many silly bugs where command line flags did not get propagated correctly // into the services, so we didn't start correctly. class ExtensionStartupTestBase : public InProcessBrowserTest { public: ExtensionStartupTestBase() : enable_extensions_(false) { } protected: // InProcessBrowserTest virtual void SetUpCommandLine(CommandLine* command_line) { EnableDOMAutomation(); FilePath profile_dir; PathService::Get(chrome::DIR_USER_DATA, &profile_dir); profile_dir = profile_dir.AppendASCII("Default"); file_util::CreateDirectory(profile_dir); preferences_file_ = profile_dir.AppendASCII("Preferences"); user_scripts_dir_ = profile_dir.AppendASCII("User Scripts"); extensions_dir_ = profile_dir.AppendASCII("Extensions"); if (enable_extensions_) { FilePath src_dir; PathService::Get(chrome::DIR_TEST_DATA, &src_dir); src_dir = src_dir.AppendASCII("extensions").AppendASCII("good"); file_util::CopyFile(src_dir.AppendASCII("Preferences"), preferences_file_); file_util::CopyDirectory(src_dir.AppendASCII("Extensions"), profile_dir, true); // recursive } else { command_line->AppendSwitch(switches::kDisableExtensions); } if (!load_extension_.value().empty()) { command_line->AppendSwitchWithValue(switches::kLoadExtension, load_extension_.ToWStringHack()); } } virtual void TearDown() { EXPECT_TRUE(file_util::Delete(preferences_file_, false)); // TODO(phajdan.jr): Check return values of the functions below, carefully. file_util::Delete(user_scripts_dir_, true); file_util::Delete(extensions_dir_, true); } void WaitForServicesToStart(int num_expected_extensions, bool expect_extensions_enabled) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); if (!service->is_ready()) ui_test_utils::WaitForNotification(NotificationType::EXTENSIONS_READY); ASSERT_TRUE(service->is_ready()); ASSERT_EQ(static_cast<uint32>(num_expected_extensions), service->extensions()->size()); ASSERT_EQ(expect_extensions_enabled, service->extensions_enabled()); UserScriptMaster* master = browser()->profile()->GetUserScriptMaster(); if (!master->ScriptsReady()) { ui_test_utils::WaitForNotification( NotificationType::USER_SCRIPTS_UPDATED); } ASSERT_TRUE(master->ScriptsReady()); } void TestInjection(bool expect_css, bool expect_script) { // Load a page affected by the content script and test to see the effect. FilePath test_file; PathService::Get(chrome::DIR_TEST_DATA, &test_file); test_file = test_file.AppendASCII("extensions") .AppendASCII("test_file.html"); ui_test_utils::NavigateToURL(browser(), net::FilePathToFileURL(test_file)); bool result = false; ui_test_utils::ExecuteJavaScriptAndExtractBool( browser()->GetSelectedTabContents()->render_view_host(), L"", L"window.domAutomationController.send(" L"document.defaultView.getComputedStyle(document.body, null)." L"getPropertyValue('background-color') == 'rgb(245, 245, 220)')", &result); EXPECT_EQ(expect_css, result); result = false; ui_test_utils::ExecuteJavaScriptAndExtractBool( browser()->GetSelectedTabContents()->render_view_host(), L"", L"window.domAutomationController.send(document.title == 'Modified')", &result); EXPECT_EQ(expect_script, result); } FilePath preferences_file_; FilePath extensions_dir_; FilePath user_scripts_dir_; bool enable_extensions_; FilePath load_extension_; }; // ExtensionsStartupTest // Ensures that we can startup the browser with --enable-extensions and some // extensions installed and see them run and do basic things. class ExtensionsStartupTest : public ExtensionStartupTestBase { public: ExtensionsStartupTest() { enable_extensions_ = true; } }; IN_PROC_BROWSER_TEST_F(ExtensionsStartupTest, MAYBE_Test) { WaitForServicesToStart(4, true); // 1 component extension and 3 others. TestInjection(true, true); } // ExtensionsLoadTest // Ensures that we can startup the browser with --load-extension and see them // run. class ExtensionsLoadTest : public ExtensionStartupTestBase { public: ExtensionsLoadTest() { PathService::Get(chrome::DIR_TEST_DATA, &load_extension_); load_extension_ = load_extension_ .AppendASCII("extensions") .AppendASCII("good") .AppendASCII("Extensions") .AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj") .AppendASCII("1.0.0.0"); } }; // Flaky (times out) on Mac/Windows. http://crbug.com/46301. #if defined(OS_MAC) || defined(OS_WIN) #define MAYBE_Test FLAKY_Test #else #define MAYBE_Test Test #endif IN_PROC_BROWSER_TEST_F(ExtensionsLoadTest, MAYBE_Test) { WaitForServicesToStart(1, false); TestInjection(true, true); }
// Copyright (c) 2008 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 <vector> #include "base/command_line.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/path_service.h" #include "chrome/browser/browser.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/extensions/user_script_master.h" #include "chrome/browser/profile.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/notification_details.h" #include "chrome/common/notification_observer.h" #include "chrome/common/notification_registrar.h" #include "chrome/common/notification_service.h" #include "chrome/common/notification_type.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "net/base/net_util.h" // This file contains high-level startup tests for the extensions system. We've // had many silly bugs where command line flags did not get propagated correctly // into the services, so we didn't start correctly. class ExtensionStartupTestBase : public InProcessBrowserTest { public: ExtensionStartupTestBase() : enable_extensions_(false) { } protected: // InProcessBrowserTest virtual void SetUpCommandLine(CommandLine* command_line) { EnableDOMAutomation(); FilePath profile_dir; PathService::Get(chrome::DIR_USER_DATA, &profile_dir); profile_dir = profile_dir.AppendASCII("Default"); file_util::CreateDirectory(profile_dir); preferences_file_ = profile_dir.AppendASCII("Preferences"); user_scripts_dir_ = profile_dir.AppendASCII("User Scripts"); extensions_dir_ = profile_dir.AppendASCII("Extensions"); if (enable_extensions_) { FilePath src_dir; PathService::Get(chrome::DIR_TEST_DATA, &src_dir); src_dir = src_dir.AppendASCII("extensions").AppendASCII("good"); file_util::CopyFile(src_dir.AppendASCII("Preferences"), preferences_file_); file_util::CopyDirectory(src_dir.AppendASCII("Extensions"), profile_dir, true); // recursive } else { command_line->AppendSwitch(switches::kDisableExtensions); } if (!load_extension_.value().empty()) { command_line->AppendSwitchWithValue(switches::kLoadExtension, load_extension_.ToWStringHack()); } } virtual void TearDown() { EXPECT_TRUE(file_util::Delete(preferences_file_, false)); // TODO(phajdan.jr): Check return values of the functions below, carefully. file_util::Delete(user_scripts_dir_, true); file_util::Delete(extensions_dir_, true); } void WaitForServicesToStart(int num_expected_extensions, bool expect_extensions_enabled) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); if (!service->is_ready()) ui_test_utils::WaitForNotification(NotificationType::EXTENSIONS_READY); ASSERT_TRUE(service->is_ready()); ASSERT_EQ(static_cast<uint32>(num_expected_extensions), service->extensions()->size()); ASSERT_EQ(expect_extensions_enabled, service->extensions_enabled()); UserScriptMaster* master = browser()->profile()->GetUserScriptMaster(); if (!master->ScriptsReady()) { ui_test_utils::WaitForNotification( NotificationType::USER_SCRIPTS_UPDATED); } ASSERT_TRUE(master->ScriptsReady()); } void TestInjection(bool expect_css, bool expect_script) { // Load a page affected by the content script and test to see the effect. FilePath test_file; PathService::Get(chrome::DIR_TEST_DATA, &test_file); test_file = test_file.AppendASCII("extensions") .AppendASCII("test_file.html"); ui_test_utils::NavigateToURL(browser(), net::FilePathToFileURL(test_file)); bool result = false; ui_test_utils::ExecuteJavaScriptAndExtractBool( browser()->GetSelectedTabContents()->render_view_host(), L"", L"window.domAutomationController.send(" L"document.defaultView.getComputedStyle(document.body, null)." L"getPropertyValue('background-color') == 'rgb(245, 245, 220)')", &result); EXPECT_EQ(expect_css, result); result = false; ui_test_utils::ExecuteJavaScriptAndExtractBool( browser()->GetSelectedTabContents()->render_view_host(), L"", L"window.domAutomationController.send(document.title == 'Modified')", &result); EXPECT_EQ(expect_script, result); } FilePath preferences_file_; FilePath extensions_dir_; FilePath user_scripts_dir_; bool enable_extensions_; FilePath load_extension_; }; // ExtensionsStartupTest // Ensures that we can startup the browser with --enable-extensions and some // extensions installed and see them run and do basic things. class ExtensionsStartupTest : public ExtensionStartupTestBase { public: ExtensionsStartupTest() { enable_extensions_ = true; } }; IN_PROC_BROWSER_TEST_F(ExtensionsStartupTest, Test) { WaitForServicesToStart(4, true); // 1 component extension and 3 others. TestInjection(true, true); } // ExtensionsLoadTest // Ensures that we can startup the browser with --load-extension and see them // run. class ExtensionsLoadTest : public ExtensionStartupTestBase { public: ExtensionsLoadTest() { PathService::Get(chrome::DIR_TEST_DATA, &load_extension_); load_extension_ = load_extension_ .AppendASCII("extensions") .AppendASCII("good") .AppendASCII("Extensions") .AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj") .AppendASCII("1.0.0.0"); } }; // Flaky (times out) on Mac/Windows. http://crbug.com/46301. #if defined(OS_MAC) || defined(OS_WIN) #define MAYBE_Test FLAKY_Test #else #define MAYBE_Test Test #endif IN_PROC_BROWSER_TEST_F(ExtensionsLoadTest, MAYBE_Test) { WaitForServicesToStart(1, false); TestInjection(true, true); }
Remove MAYBE_ prefix from ExtensionStartupTesst.Test (fixing my mistake)
Remove MAYBE_ prefix from ExtensionStartupTesst.Test (fixing my mistake) TEST=NONE BUG=NONE Review URL: http://codereview.chromium.org/2725011 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@49473 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,adobe/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,adobe/chromium,yitian134/chromium,adobe/chromium,adobe/chromium,adobe/chromium,ropik/chromium,yitian134/chromium,ropik/chromium,gavinp/chromium,yitian134/chromium,gavinp/chromium,yitian134/chromium,adobe/chromium,ropik/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,ropik/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,gavinp/chromium,gavinp/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,gavinp/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,yitian134/chromium,gavinp/chromium,gavinp/chromium,adobe/chromium
81b34feda7af721eac52e80948a78e47544ab3cc
chrome/browser/in_process_webkit/indexed_db_browsertest.cc
chrome/browser/in_process_webkit/indexed_db_browsertest.cc
// 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 "base/command_line.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/ref_counted.h" #include "base/scoped_temp_dir.h" #include "base/utf_string_conversions.h" #include "chrome/browser/in_process_webkit/indexed_db_context.h" #include "chrome/browser/in_process_webkit/webkit_context.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/ui/browser.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/testing_profile.h" #include "chrome/test/thread_test_helper.h" #include "chrome/test/ui_test_utils.h" // This browser test is aimed towards exercising the IndexedDB bindings and // the actual implementation that lives in the browser side (in_process_webkit). class IndexedDBBrowserTest : public InProcessBrowserTest { public: IndexedDBBrowserTest() { EnableDOMAutomation(); } GURL testUrl(const FilePath& file_path) { const FilePath kTestDir(FILE_PATH_LITERAL("indexeddb")); return ui_test_utils::GetTestUrl(kTestDir, file_path); } void SimpleTest(const GURL& test_url) { // The test page will perform tests on IndexedDB, then navigate to either // a #pass or #fail ref. LOG(INFO) << "Navigating to URL and blocking."; ui_test_utils::NavigateToURLBlockUntilNavigationsComplete( browser(), test_url, 2); LOG(INFO) << "Navigation done."; std::string result = browser()->GetSelectedTabContents()->GetURL().ref(); if (result != "pass") { std::string js_result; ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString( browser()->GetSelectedTabContents()->render_view_host(), L"", L"window.domAutomationController.send(getLog())", &js_result)); FAIL() << "Failed: " << js_result; } } }; IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, CursorTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("cursor_test.html")))); } // http://code.google.com/p/chromium/issues/detail?id=70773 IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_IndexTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("index_test.html")))); } // http://code.google.com/p/chromium/issues/detail?id=70773 IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_KeyPathTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("key_path_test.html")))); } IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, TransactionGetTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_get_test.html")))); } // http://code.google.com/p/chromium/issues/detail?id=70773 IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_ObjectStoreTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("object_store_test.html")))); } IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DatabaseTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("database_test.html")))); } // http://code.google.com/p/chromium/issues/detail?id=70773 IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_TransactionTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_test.html")))); } // http://code.google.com/p/chromium/issues/detail?id=70773 IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_DoesntHangTest) { SimpleTest(testUrl(FilePath( FILE_PATH_LITERAL("transaction_run_forever.html")))); ui_test_utils::CrashTab(browser()->GetSelectedTabContents()); SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_test.html")))); } // In proc browser test is needed here because ClearLocalState indirectly calls // WebKit's isMainThread through WebSecurityOrigin->SecurityOrigin. IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, ClearLocalState) { // Create test files. ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); FilePath indexeddb_dir = temp_dir.path().Append( IndexedDBContext::kIndexedDBDirectory); ASSERT_TRUE(file_util::CreateDirectory(indexeddb_dir)); FilePath::StringType file_name_1(FILE_PATH_LITERAL("http_foo_0")); file_name_1.append(IndexedDBContext::kIndexedDBExtension); FilePath::StringType file_name_2(FILE_PATH_LITERAL("chrome-extension_foo_0")); file_name_2.append(IndexedDBContext::kIndexedDBExtension); FilePath temp_file_path_1 = indexeddb_dir.Append(file_name_1); FilePath temp_file_path_2 = indexeddb_dir.Append(file_name_2); ASSERT_EQ(1, file_util::WriteFile(temp_file_path_1, ".", 1)); ASSERT_EQ(1, file_util::WriteFile(temp_file_path_2, "o", 1)); // Create the scope which will ensure we run the destructor of the webkit // context which should trigger the clean up. { TestingProfile profile; WebKitContext *webkit_context = profile.GetWebKitContext(); webkit_context->indexed_db_context()->set_data_path(indexeddb_dir); webkit_context->set_clear_local_state_on_exit(true); } // Make sure we wait until the destructor has run. scoped_refptr<ThreadTestHelper> helper( new ThreadTestHelper(BrowserThread::WEBKIT)); ASSERT_TRUE(helper->Run()); // Because we specified https for scheme to be skipped the second file // should survive and the first go into vanity. ASSERT_FALSE(file_util::PathExists(temp_file_path_1)); ASSERT_TRUE(file_util::PathExists(temp_file_path_2)); }
// 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 "base/command_line.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/ref_counted.h" #include "base/scoped_temp_dir.h" #include "base/utf_string_conversions.h" #include "chrome/browser/in_process_webkit/indexed_db_context.h" #include "chrome/browser/in_process_webkit/webkit_context.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/ui/browser.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/testing_profile.h" #include "chrome/test/thread_test_helper.h" #include "chrome/test/ui_test_utils.h" // This browser test is aimed towards exercising the IndexedDB bindings and // the actual implementation that lives in the browser side (in_process_webkit). class IndexedDBBrowserTest : public InProcessBrowserTest { public: IndexedDBBrowserTest() { EnableDOMAutomation(); } GURL testUrl(const FilePath& file_path) { const FilePath kTestDir(FILE_PATH_LITERAL("indexeddb")); return ui_test_utils::GetTestUrl(kTestDir, file_path); } void SimpleTest(const GURL& test_url) { // The test page will perform tests on IndexedDB, then navigate to either // a #pass or #fail ref. LOG(INFO) << "Navigating to URL and blocking."; ui_test_utils::NavigateToURLBlockUntilNavigationsComplete( browser(), test_url, 2); LOG(INFO) << "Navigation done."; std::string result = browser()->GetSelectedTabContents()->GetURL().ref(); if (result != "pass") { std::string js_result; ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString( browser()->GetSelectedTabContents()->render_view_host(), L"", L"window.domAutomationController.send(getLog())", &js_result)); FAIL() << "Failed: " << js_result; } } }; IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_CursorTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("cursor_test.html")))); } // http://code.google.com/p/chromium/issues/detail?id=70773 IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_IndexTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("index_test.html")))); } // http://code.google.com/p/chromium/issues/detail?id=70773 IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_KeyPathTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("key_path_test.html")))); } IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_TransactionGetTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_get_test.html")))); } // http://code.google.com/p/chromium/issues/detail?id=70773 IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_ObjectStoreTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("object_store_test.html")))); } IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_DatabaseTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("database_test.html")))); } // http://code.google.com/p/chromium/issues/detail?id=70773 IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_TransactionTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_test.html")))); } // http://code.google.com/p/chromium/issues/detail?id=70773 IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_DoesntHangTest) { SimpleTest(testUrl(FilePath( FILE_PATH_LITERAL("transaction_run_forever.html")))); ui_test_utils::CrashTab(browser()->GetSelectedTabContents()); SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_test.html")))); } // In proc browser test is needed here because ClearLocalState indirectly calls // WebKit's isMainThread through WebSecurityOrigin->SecurityOrigin. IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_ClearLocalState) { // Create test files. ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); FilePath indexeddb_dir = temp_dir.path().Append( IndexedDBContext::kIndexedDBDirectory); ASSERT_TRUE(file_util::CreateDirectory(indexeddb_dir)); FilePath::StringType file_name_1(FILE_PATH_LITERAL("http_foo_0")); file_name_1.append(IndexedDBContext::kIndexedDBExtension); FilePath::StringType file_name_2(FILE_PATH_LITERAL("chrome-extension_foo_0")); file_name_2.append(IndexedDBContext::kIndexedDBExtension); FilePath temp_file_path_1 = indexeddb_dir.Append(file_name_1); FilePath temp_file_path_2 = indexeddb_dir.Append(file_name_2); ASSERT_EQ(1, file_util::WriteFile(temp_file_path_1, ".", 1)); ASSERT_EQ(1, file_util::WriteFile(temp_file_path_2, "o", 1)); // Create the scope which will ensure we run the destructor of the webkit // context which should trigger the clean up. { TestingProfile profile; WebKitContext *webkit_context = profile.GetWebKitContext(); webkit_context->indexed_db_context()->set_data_path(indexeddb_dir); webkit_context->set_clear_local_state_on_exit(true); } // Make sure we wait until the destructor has run. scoped_refptr<ThreadTestHelper> helper( new ThreadTestHelper(BrowserThread::WEBKIT)); ASSERT_TRUE(helper->Run()); // Because we specified https for scheme to be skipped the second file // should survive and the first go into vanity. ASSERT_FALSE(file_util::PathExists(temp_file_path_1)); ASSERT_TRUE(file_util::PathExists(temp_file_path_2)); }
Disable some tests that need to be updated due to a WebKit patch that hasn't been rolled in yet.
Disable some tests that need to be updated due to a WebKit patch that hasn't been rolled in yet. TEST=none BUG=none Review URL: http://codereview.chromium.org/6523013 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@74906 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
M4sse/chromium.src,fujunwei/chromium-crosswalk,ltilve/chromium,junmin-zhu/chromium-rivertrail,keishi/chromium,krieger-od/nwjs_chromium.src,Chilledheart/chromium,ChromiumWebApps/chromium,PeterWangIntel/chromium-crosswalk,M4sse/chromium.src,junmin-zhu/chromium-rivertrail,rogerwang/chromium,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,hujiajie/pa-chromium,Just-D/chromium-1,hujiajie/pa-chromium,hgl888/chromium-crosswalk-efl,anirudhSK/chromium,Pluto-tv/chromium-crosswalk,patrickm/chromium.src,ltilve/chromium,jaruba/chromium.src,zcbenz/cefode-chromium,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,Just-D/chromium-1,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,M4sse/chromium.src,krieger-od/nwjs_chromium.src,junmin-zhu/chromium-rivertrail,krieger-od/nwjs_chromium.src,rogerwang/chromium,jaruba/chromium.src,hgl888/chromium-crosswalk,Jonekee/chromium.src,dednal/chromium.src,jaruba/chromium.src,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,keishi/chromium,axinging/chromium-crosswalk,M4sse/chromium.src,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk,robclark/chromium,dednal/chromium.src,Jonekee/chromium.src,hujiajie/pa-chromium,keishi/chromium,Jonekee/chromium.src,mogoweb/chromium-crosswalk,krieger-od/nwjs_chromium.src,junmin-zhu/chromium-rivertrail,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,ChromiumWebApps/chromium,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,nacl-webkit/chrome_deps,littlstar/chromium.src,timopulkkinen/BubbleFish,anirudhSK/chromium,pozdnyakov/chromium-crosswalk,mogoweb/chromium-crosswalk,Just-D/chromium-1,pozdnyakov/chromium-crosswalk,dushu1203/chromium.src,hgl888/chromium-crosswalk,anirudhSK/chromium,axinging/chromium-crosswalk,nacl-webkit/chrome_deps,bright-sparks/chromium-spacewalk,anirudhSK/chromium,zcbenz/cefode-chromium,rogerwang/chromium,robclark/chromium,ltilve/chromium,axinging/chromium-crosswalk,keishi/chromium,ondra-novak/chromium.src,ondra-novak/chromium.src,Fireblend/chromium-crosswalk,junmin-zhu/chromium-rivertrail,zcbenz/cefode-chromium,markYoungH/chromium.src,jaruba/chromium.src,hgl888/chromium-crosswalk,Jonekee/chromium.src,Jonekee/chromium.src,zcbenz/cefode-chromium,ChromiumWebApps/chromium,keishi/chromium,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,patrickm/chromium.src,pozdnyakov/chromium-crosswalk,krieger-od/nwjs_chromium.src,pozdnyakov/chromium-crosswalk,markYoungH/chromium.src,robclark/chromium,hgl888/chromium-crosswalk-efl,dednal/chromium.src,Just-D/chromium-1,robclark/chromium,junmin-zhu/chromium-rivertrail,dednal/chromium.src,timopulkkinen/BubbleFish,pozdnyakov/chromium-crosswalk,markYoungH/chromium.src,anirudhSK/chromium,zcbenz/cefode-chromium,littlstar/chromium.src,littlstar/chromium.src,Jonekee/chromium.src,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,keishi/chromium,M4sse/chromium.src,dednal/chromium.src,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,ondra-novak/chromium.src,TheTypoMaster/chromium-crosswalk,jaruba/chromium.src,patrickm/chromium.src,nacl-webkit/chrome_deps,Pluto-tv/chromium-crosswalk,pozdnyakov/chromium-crosswalk,jaruba/chromium.src,markYoungH/chromium.src,Chilledheart/chromium,chuan9/chromium-crosswalk,ChromiumWebApps/chromium,TheTypoMaster/chromium-crosswalk,nacl-webkit/chrome_deps,TheTypoMaster/chromium-crosswalk,dednal/chromium.src,M4sse/chromium.src,hgl888/chromium-crosswalk,Jonekee/chromium.src,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,mogoweb/chromium-crosswalk,Fireblend/chromium-crosswalk,mogoweb/chromium-crosswalk,fujunwei/chromium-crosswalk,dushu1203/chromium.src,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,junmin-zhu/chromium-rivertrail,dednal/chromium.src,mogoweb/chromium-crosswalk,M4sse/chromium.src,mogoweb/chromium-crosswalk,chuan9/chromium-crosswalk,Just-D/chromium-1,chuan9/chromium-crosswalk,rogerwang/chromium,markYoungH/chromium.src,dushu1203/chromium.src,pozdnyakov/chromium-crosswalk,fujunwei/chromium-crosswalk,fujunwei/chromium-crosswalk,timopulkkinen/BubbleFish,pozdnyakov/chromium-crosswalk,patrickm/chromium.src,anirudhSK/chromium,Chilledheart/chromium,anirudhSK/chromium,patrickm/chromium.src,hujiajie/pa-chromium,rogerwang/chromium,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,markYoungH/chromium.src,dushu1203/chromium.src,nacl-webkit/chrome_deps,rogerwang/chromium,Chilledheart/chromium,hujiajie/pa-chromium,TheTypoMaster/chromium-crosswalk,littlstar/chromium.src,zcbenz/cefode-chromium,chuan9/chromium-crosswalk,pozdnyakov/chromium-crosswalk,hujiajie/pa-chromium,ChromiumWebApps/chromium,dednal/chromium.src,M4sse/chromium.src,ondra-novak/chromium.src,bright-sparks/chromium-spacewalk,Jonekee/chromium.src,hgl888/chromium-crosswalk,Chilledheart/chromium,junmin-zhu/chromium-rivertrail,ChromiumWebApps/chromium,ChromiumWebApps/chromium,nacl-webkit/chrome_deps,Fireblend/chromium-crosswalk,junmin-zhu/chromium-rivertrail,mogoweb/chromium-crosswalk,ondra-novak/chromium.src,dednal/chromium.src,keishi/chromium,littlstar/chromium.src,nacl-webkit/chrome_deps,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,junmin-zhu/chromium-rivertrail,jaruba/chromium.src,fujunwei/chromium-crosswalk,mogoweb/chromium-crosswalk,chuan9/chromium-crosswalk,jaruba/chromium.src,ondra-novak/chromium.src,bright-sparks/chromium-spacewalk,hujiajie/pa-chromium,rogerwang/chromium,Just-D/chromium-1,robclark/chromium,hujiajie/pa-chromium,anirudhSK/chromium,hgl888/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,timopulkkinen/BubbleFish,Fireblend/chromium-crosswalk,timopulkkinen/BubbleFish,jaruba/chromium.src,ChromiumWebApps/chromium,robclark/chromium,dushu1203/chromium.src,hgl888/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,dushu1203/chromium.src,zcbenz/cefode-chromium,markYoungH/chromium.src,crosswalk-project/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,anirudhSK/chromium,zcbenz/cefode-chromium,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,keishi/chromium,bright-sparks/chromium-spacewalk,patrickm/chromium.src,ltilve/chromium,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,patrickm/chromium.src,markYoungH/chromium.src,bright-sparks/chromium-spacewalk,Just-D/chromium-1,pozdnyakov/chromium-crosswalk,Just-D/chromium-1,ondra-novak/chromium.src,ondra-novak/chromium.src,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,timopulkkinen/BubbleFish,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,ltilve/chromium,littlstar/chromium.src,PeterWangIntel/chromium-crosswalk,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,Chilledheart/chromium,ChromiumWebApps/chromium,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,krieger-od/nwjs_chromium.src,dednal/chromium.src,fujunwei/chromium-crosswalk,Pluto-tv/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,ChromiumWebApps/chromium,mogoweb/chromium-crosswalk,ltilve/chromium,ChromiumWebApps/chromium,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,bright-sparks/chromium-spacewalk,nacl-webkit/chrome_deps,rogerwang/chromium,axinging/chromium-crosswalk,zcbenz/cefode-chromium,hgl888/chromium-crosswalk-efl,anirudhSK/chromium,hujiajie/pa-chromium,Pluto-tv/chromium-crosswalk,zcbenz/cefode-chromium,zcbenz/cefode-chromium,Pluto-tv/chromium-crosswalk,markYoungH/chromium.src,nacl-webkit/chrome_deps,keishi/chromium,timopulkkinen/BubbleFish,timopulkkinen/BubbleFish,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,mohamed--abdel-maksoud/chromium.src,PeterWangIntel/chromium-crosswalk,nacl-webkit/chrome_deps,dushu1203/chromium.src,jaruba/chromium.src,hujiajie/pa-chromium,crosswalk-project/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,hujiajie/pa-chromium,rogerwang/chromium,nacl-webkit/chrome_deps,M4sse/chromium.src,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,rogerwang/chromium,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,M4sse/chromium.src,ltilve/chromium,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,timopulkkinen/BubbleFish,keishi/chromium,robclark/chromium,dushu1203/chromium.src,robclark/chromium,robclark/chromium,ltilve/chromium,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,keishi/chromium,junmin-zhu/chromium-rivertrail,anirudhSK/chromium,littlstar/chromium.src,krieger-od/nwjs_chromium.src,ltilve/chromium,ChromiumWebApps/chromium,littlstar/chromium.src,chuan9/chromium-crosswalk,Just-D/chromium-1,timopulkkinen/BubbleFish,Jonekee/chromium.src,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,patrickm/chromium.src,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,robclark/chromium,Jonekee/chromium.src
10bdeedd9211feee259eed14fc1430d45423a837
Sources/Tasks/BasicTasks/PlayMinionTask.cpp
Sources/Tasks/BasicTasks/PlayMinionTask.cpp
/************************************************************************* > File Name: PlayMinion.cpp > Project Name: Hearthstonepp > Author: Young-Joong Kim > Purpose: Implement PlayMinion, Summon Minion and Process PowerTasks > Created Time: 2018/07/21 > Copyright (c) 2018, Young-Joong Kim *************************************************************************/ #include <Tasks/BasicTasks/ModifyManaTask.h> #include <Tasks/BasicTasks/PlayMinionTask.h> #include <algorithm> namespace Hearthstonepp::BasicTasks { PlayMinionTask::PlayMinionTask(TaskAgent& agent, Entity* entity) : m_entity(entity), m_requirement(TaskID::SELECT_POSITION, agent) { // Do Nothing } TaskID PlayMinionTask::GetTaskID() const { return TaskID::PLAY_MINION; } MetaData PlayMinionTask::Impl(Player& player1, Player& player2) { TaskMeta meta; // Get Position Response from GameInterface m_requirement.Interact(player1.id, meta); using RequireTaskMeta = FlatData::ResponsePlayMinion; const auto& buffer = meta.GetConstBuffer(); auto req = flatbuffers::GetRoot<RequireTaskMeta>(buffer.get()); if (req == nullptr) { return MetaData::PLAY_MINION_FLATBUFFER_NULLPTR; } BYTE position = req->position(); // Field Position Verification if (position > player1.field.size()) { return MetaData::PLAY_MINION_POSITION_OUT_OF_RANGE; } // Character Casting Verification auto character = dynamic_cast<Character*>(m_entity); if (character == nullptr) { return MetaData::PLAY_MINION_CANNOT_CONVERT_ENTITY; } // Summon player1.field.insert(player1.field.begin() + position, character); // Apply card mechanics tags for (auto tags : m_entity->card->mechanics) { m_entity->gameTags[tags] = 1; } // Summoned minion can't attack right turn if (m_entity->gameTags[+GameTag::CHARGE] == 1) { ((Character*) m_entity)->attackableCount = 1; } BYTE cost = static_cast<BYTE>(m_entity->card->cost); MetaData modified = ModifyManaTask(NumMode::SUB, ManaMode::EXIST, cost) .Run(player1, player2); // Process PowerTasks if (m_entity->card->power != nullptr) { for (auto& power : m_entity->card->power->powerTask) { power->Run(player1, player2); } } if (modified == MetaData::MODIFY_MANA_SUCCESS) { return MetaData::PLAY_MINION_SUCCESS; } return MetaData::PLAY_MINION_MODIFY_MANA_FAIL; } } // namespace Hearthstonepp::BasicTasks
/************************************************************************* > File Name: PlayMinion.cpp > Project Name: Hearthstonepp > Author: Young-Joong Kim > Purpose: Implement PlayMinion, Summon Minion and Process PowerTasks > Created Time: 2018/07/21 > Copyright (c) 2018, Young-Joong Kim *************************************************************************/ #include <Tasks/BasicTasks/ModifyManaTask.h> #include <Tasks/BasicTasks/PlayMinionTask.h> #include <algorithm> namespace Hearthstonepp::BasicTasks { PlayMinionTask::PlayMinionTask(TaskAgent& agent, Entity* entity) : m_entity(entity), m_requirement(TaskID::SELECT_POSITION, agent) { // Do Nothing } TaskID PlayMinionTask::GetTaskID() const { return TaskID::PLAY_MINION; } MetaData PlayMinionTask::Impl(Player& player1, Player& player2) { TaskMeta meta; // Get Position Response from GameInterface m_requirement.Interact(player1.id, meta); using RequireTaskMeta = FlatData::ResponsePlayMinion; const auto& buffer = meta.GetConstBuffer(); auto req = flatbuffers::GetRoot<RequireTaskMeta>(buffer.get()); if (req == nullptr) { return MetaData::PLAY_MINION_FLATBUFFER_NULLPTR; } BYTE position = req->position(); // Field Position Verification if (position > player1.field.size()) { return MetaData::PLAY_MINION_POSITION_OUT_OF_RANGE; } // Character Casting Verification auto character = dynamic_cast<Character*>(m_entity); if (character == nullptr) { return MetaData::PLAY_MINION_CANNOT_CONVERT_ENTITY; } // Summon player1.field.insert(player1.field.begin() + position, character); // Apply card mechanics tags for (auto tags : m_entity->card->mechanics) { m_entity->gameTags[tags] = 1; } // Summoned minion can't attack right turn if (m_entity->gameTags[+GameTag::CHARGE] == 1) { static_cast<Character*>(m_entity)->attackableCount = 1; } BYTE cost = static_cast<BYTE>(m_entity->card->cost); MetaData modified = ModifyManaTask(NumMode::SUB, ManaMode::EXIST, cost) .Run(player1, player2); // Process PowerTasks if (m_entity->card->power != nullptr) { for (auto& power : m_entity->card->power->powerTask) { power->Run(player1, player2); } } if (modified == MetaData::MODIFY_MANA_SUCCESS) { return MetaData::PLAY_MINION_SUCCESS; } return MetaData::PLAY_MINION_MODIFY_MANA_FAIL; } } // namespace Hearthstonepp::BasicTasks
Fix PlayMinionTask C Style Casting
Fix PlayMinionTask C Style Casting
C++
mit
Hearthstonepp/Hearthstonepp,Hearthstonepp/Hearthstonepp