text
stringlengths
54
60.6k
<commit_before>#include <despoof/win32/targetwindows.h> #include <algorithm> #include <boost/locale.hpp> #include "context.h" #include "command_line.h" #include "init.h" #include <despoof/import/log.h> #include <despoof/import/collect.h> #include <despoof/win32/error.h> using boost::format; using boost::locale::localization_backend_manager; using boost::locale::generator; using namespace std; using namespace boost::locale::conv; using namespace despoof; template<typename GetFunction> static GetFunction loadsym(const string &file, const char *symbol) { auto module = LoadLibrary(utf_to_utf<wchar_t>(file).c_str()); if(!module) { throw_windows_error("LoadLibrary"); } auto raw_get = GetProcAddress(module, symbol); if(!raw_get) { throw_windows_error("GetProcAddress"); } return static_cast<GetFunction>(static_cast<void*>(raw_get)); } static string modfile(const char *prefix, const string &name) { return (format("%1%-%2%.dll") % prefix % name).str(); } bool despoof::init(int argc, char **argv, unique_ptr<context> &ctx) { localization_backend_manager::global().select("std"); locale::global(generator().generate("")); configuration config; try { command_line_to_configuration(config, argc, argv); } catch(const command_line_error &e) { e.print_errors(); return false; } if(config._nostart) { return false; } ctx.reset(new context(config, unique_ptr<network_api>(loadsym<getapi_function>(modfile("nw", config.nw_module), "getapi")()), loadsym<getlog_function>(modfile("log", config.log_module), "getlog")())); return true; } <commit_msg>removed boost::locale backend selection<commit_after>#include <despoof/win32/targetwindows.h> #include <algorithm> #include <boost/locale.hpp> #include "context.h" #include "command_line.h" #include "init.h" #include <despoof/import/log.h> #include <despoof/import/collect.h> #include <despoof/win32/error.h> using boost::format; using boost::locale::generator; using namespace std; using namespace boost::locale::conv; using namespace despoof; template<typename GetFunction> static GetFunction loadsym(const string &file, const char *symbol) { auto module = LoadLibrary(utf_to_utf<wchar_t>(file).c_str()); if(!module) { throw_windows_error("LoadLibrary"); } auto raw_get = GetProcAddress(module, symbol); if(!raw_get) { throw_windows_error("GetProcAddress"); } return static_cast<GetFunction>(static_cast<void*>(raw_get)); } static string modfile(const char *prefix, const string &name) { return (format("%1%-%2%.dll") % prefix % name).str(); } bool despoof::init(int argc, char **argv, unique_ptr<context> &ctx) { locale::global(generator().generate("")); configuration config; try { command_line_to_configuration(config, argc, argv); } catch(const command_line_error &e) { e.print_errors(); return false; } if(config._nostart) { return false; } ctx.reset(new context(config, unique_ptr<network_api>(loadsym<getapi_function>(modfile("nw", config.nw_module), "getapi")()), loadsym<getlog_function>(modfile("log", config.log_module), "getlog")())); return true; } <|endoftext|>
<commit_before>/* * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #ifndef SHARE_VM_GC_IMPLEMENTATION_G1_G1OOPCLOSURES_HPP #define SHARE_VM_GC_IMPLEMENTATION_G1_G1OOPCLOSURES_HPP class HeapRegion; class G1CollectedHeap; class G1RemSet; class ConcurrentMark; class DirtyCardToOopClosure; class CMBitMap; class CMMarkStack; class G1ParScanThreadState; class CMTask; class ReferenceProcessor; // A class that scans oops in a given heap region (much as OopsInGenClosure // scans oops in a generation.) class OopsInHeapRegionClosure: public ExtendedOopClosure { protected: HeapRegion* _from; public: void set_region(HeapRegion* from) { _from = from; } }; class G1ParClosureSuper : public OopsInHeapRegionClosure { protected: G1CollectedHeap* _g1; G1RemSet* _g1_rem; ConcurrentMark* _cm; G1ParScanThreadState* _par_scan_state; uint _worker_id; bool _during_initial_mark; bool _mark_in_progress; public: G1ParClosureSuper(G1CollectedHeap* g1, G1ParScanThreadState* par_scan_state); bool apply_to_weak_ref_discovered_field() { return true; } }; class G1ParPushHeapRSClosure : public G1ParClosureSuper { public: G1ParPushHeapRSClosure(G1CollectedHeap* g1, G1ParScanThreadState* par_scan_state): G1ParClosureSuper(g1, par_scan_state) { } template <class T> void do_oop_nv(T* p); virtual void do_oop(oop* p) { do_oop_nv(p); } virtual void do_oop(narrowOop* p) { do_oop_nv(p); } }; class G1ParScanClosure : public G1ParClosureSuper { public: G1ParScanClosure(G1CollectedHeap* g1, G1ParScanThreadState* par_scan_state, ReferenceProcessor* rp) : G1ParClosureSuper(g1, par_scan_state) { assert(_ref_processor == NULL, "sanity"); _ref_processor = rp; } template <class T> void do_oop_nv(T* p); virtual void do_oop(oop* p) { do_oop_nv(p); } virtual void do_oop(narrowOop* p) { do_oop_nv(p); } }; #define G1_PARTIAL_ARRAY_MASK 0x2 template <class T> inline bool has_partial_array_mask(T* ref) { return ((uintptr_t)ref & G1_PARTIAL_ARRAY_MASK) == G1_PARTIAL_ARRAY_MASK; } template <class T> inline T* set_partial_array_mask(T obj) { assert(((uintptr_t)(void *)obj & G1_PARTIAL_ARRAY_MASK) == 0, "Information loss!"); return (T*) ((uintptr_t)(void *)obj | G1_PARTIAL_ARRAY_MASK); } template <class T> inline oop clear_partial_array_mask(T* ref) { return cast_to_oop((intptr_t)ref & ~G1_PARTIAL_ARRAY_MASK); } class G1ParScanPartialArrayClosure : public G1ParClosureSuper { G1ParScanClosure _scanner; public: G1ParScanPartialArrayClosure(G1CollectedHeap* g1, G1ParScanThreadState* par_scan_state, ReferenceProcessor* rp) : G1ParClosureSuper(g1, par_scan_state), _scanner(g1, par_scan_state, rp) { assert(_ref_processor == NULL, "sanity"); } G1ParScanClosure* scanner() { return &_scanner; } template <class T> void do_oop_nv(T* p); virtual void do_oop(oop* p) { do_oop_nv(p); } virtual void do_oop(narrowOop* p) { do_oop_nv(p); } }; // Add back base class for metadata class G1ParCopyHelper : public G1ParClosureSuper { Klass* _scanned_klass; public: G1ParCopyHelper(G1CollectedHeap* g1, G1ParScanThreadState* par_scan_state) : _scanned_klass(NULL), G1ParClosureSuper(g1, par_scan_state) {} void set_scanned_klass(Klass* k) { _scanned_klass = k; } template <class T> void do_klass_barrier(T* p, oop new_obj); }; template <G1Barrier barrier, bool do_mark_object> class G1ParCopyClosure : public G1ParCopyHelper { G1ParScanClosure _scanner; template <class T> void do_oop_work(T* p); protected: // Mark the object if it's not already marked. This is used to mark // objects pointed to by roots that are guaranteed not to move // during the GC (i.e., non-CSet objects). It is MT-safe. void mark_object(oop obj); // Mark the object if it's not already marked. This is used to mark // objects pointed to by roots that have been forwarded during a // GC. It is MT-safe. void mark_forwarded_object(oop from_obj, oop to_obj); oop copy_to_survivor_space(oop obj); public: G1ParCopyClosure(G1CollectedHeap* g1, G1ParScanThreadState* par_scan_state, ReferenceProcessor* rp) : _scanner(g1, par_scan_state, rp), G1ParCopyHelper(g1, par_scan_state) { assert(_ref_processor == NULL, "sanity"); } G1ParScanClosure* scanner() { return &_scanner; } template <class T> void do_oop_nv(T* p) { do_oop_work(p); } virtual void do_oop(oop* p) { do_oop_nv(p); } virtual void do_oop(narrowOop* p) { do_oop_nv(p); } }; typedef G1ParCopyClosure<G1BarrierNone, false> G1ParScanExtRootClosure; typedef G1ParCopyClosure<G1BarrierKlass, false> G1ParScanMetadataClosure; typedef G1ParCopyClosure<G1BarrierNone, true> G1ParScanAndMarkExtRootClosure; typedef G1ParCopyClosure<G1BarrierKlass, true> G1ParScanAndMarkMetadataClosure; // The following closure type is defined in g1_specialized_oop_closures.hpp: // // typedef G1ParCopyClosure<G1BarrierEvac, false> G1ParScanHeapEvacClosure; // We use a separate closure to handle references during evacuation // failure processing. // We could have used another instance of G1ParScanHeapEvacClosure // (since that closure no longer assumes that the references it // handles point into the collection set). typedef G1ParCopyClosure<G1BarrierEvac, false> G1ParScanHeapEvacFailureClosure; class FilterIntoCSClosure: public ExtendedOopClosure { G1CollectedHeap* _g1; OopClosure* _oc; DirtyCardToOopClosure* _dcto_cl; public: FilterIntoCSClosure( DirtyCardToOopClosure* dcto_cl, G1CollectedHeap* g1, OopClosure* oc) : _dcto_cl(dcto_cl), _g1(g1), _oc(oc) { } template <class T> void do_oop_nv(T* p); virtual void do_oop(oop* p) { do_oop_nv(p); } virtual void do_oop(narrowOop* p) { do_oop_nv(p); } bool apply_to_weak_ref_discovered_field() { return true; } }; class FilterOutOfRegionClosure: public ExtendedOopClosure { HeapWord* _r_bottom; HeapWord* _r_end; OopClosure* _oc; public: FilterOutOfRegionClosure(HeapRegion* r, OopClosure* oc); template <class T> void do_oop_nv(T* p); virtual void do_oop(oop* p) { do_oop_nv(p); } virtual void do_oop(narrowOop* p) { do_oop_nv(p); } bool apply_to_weak_ref_discovered_field() { return true; } }; // Closure for iterating over object fields during concurrent marking class G1CMOopClosure : public ExtendedOopClosure { private: G1CollectedHeap* _g1h; ConcurrentMark* _cm; CMTask* _task; public: G1CMOopClosure(G1CollectedHeap* g1h, ConcurrentMark* cm, CMTask* task); template <class T> void do_oop_nv(T* p); virtual void do_oop( oop* p) { do_oop_nv(p); } virtual void do_oop(narrowOop* p) { do_oop_nv(p); } }; // Closure to scan the root regions during concurrent marking class G1RootRegionScanClosure : public ExtendedOopClosure { private: G1CollectedHeap* _g1h; ConcurrentMark* _cm; uint _worker_id; public: G1RootRegionScanClosure(G1CollectedHeap* g1h, ConcurrentMark* cm, uint worker_id) : _g1h(g1h), _cm(cm), _worker_id(worker_id) { } template <class T> void do_oop_nv(T* p); virtual void do_oop( oop* p) { do_oop_nv(p); } virtual void do_oop(narrowOop* p) { do_oop_nv(p); } }; // Closure that applies the given two closures in sequence. // Used by the RSet refinement code (when updating RSets // during an evacuation pause) to record cards containing // pointers into the collection set. class G1Mux2Closure : public ExtendedOopClosure { OopClosure* _c1; OopClosure* _c2; public: G1Mux2Closure(OopClosure *c1, OopClosure *c2); template <class T> void do_oop_nv(T* p); virtual void do_oop(oop* p) { do_oop_nv(p); } virtual void do_oop(narrowOop* p) { do_oop_nv(p); } }; // A closure that returns true if it is actually applied // to a reference class G1TriggerClosure : public ExtendedOopClosure { bool _triggered; public: G1TriggerClosure(); bool triggered() const { return _triggered; } template <class T> void do_oop_nv(T* p); virtual void do_oop(oop* p) { do_oop_nv(p); } virtual void do_oop(narrowOop* p) { do_oop_nv(p); } }; // A closure which uses a triggering closure to determine // whether to apply an oop closure. class G1InvokeIfNotTriggeredClosure: public ExtendedOopClosure { G1TriggerClosure* _trigger_cl; OopClosure* _oop_cl; public: G1InvokeIfNotTriggeredClosure(G1TriggerClosure* t, OopClosure* oc); template <class T> void do_oop_nv(T* p); virtual void do_oop(oop* p) { do_oop_nv(p); } virtual void do_oop(narrowOop* p) { do_oop_nv(p); } }; class G1UpdateRSOrPushRefOopClosure: public ExtendedOopClosure { G1CollectedHeap* _g1; G1RemSet* _g1_rem_set; HeapRegion* _from; OopsInHeapRegionClosure* _push_ref_cl; bool _record_refs_into_cset; int _worker_i; public: G1UpdateRSOrPushRefOopClosure(G1CollectedHeap* g1h, G1RemSet* rs, OopsInHeapRegionClosure* push_ref_cl, bool record_refs_into_cset, int worker_i = 0); void set_from(HeapRegion* from) { assert(from != NULL, "from region must be non-NULL"); _from = from; } bool self_forwarded(oop obj) { bool result = (obj->is_forwarded() && (obj->forwardee()== obj)); return result; } bool apply_to_weak_ref_discovered_field() { return true; } template <class T> void do_oop_nv(T* p); virtual void do_oop(narrowOop* p) { do_oop_nv(p); } virtual void do_oop(oop* p) { do_oop_nv(p); } }; #endif // SHARE_VM_GC_IMPLEMENTATION_G1_G1OOPCLOSURES_HPP <commit_msg>6991197: G1: specialize deal_with_reference() for narrowOop* Summary: Clean up and slightly optimize reference handling from the GC reference task queue. Since we never push partial array chunks as narrowOop* we can manually specialize the code so that some code can be optimized away. Reviewed-by: tonyp, brutisso, stefank<commit_after>/* * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #ifndef SHARE_VM_GC_IMPLEMENTATION_G1_G1OOPCLOSURES_HPP #define SHARE_VM_GC_IMPLEMENTATION_G1_G1OOPCLOSURES_HPP class HeapRegion; class G1CollectedHeap; class G1RemSet; class ConcurrentMark; class DirtyCardToOopClosure; class CMBitMap; class CMMarkStack; class G1ParScanThreadState; class CMTask; class ReferenceProcessor; // A class that scans oops in a given heap region (much as OopsInGenClosure // scans oops in a generation.) class OopsInHeapRegionClosure: public ExtendedOopClosure { protected: HeapRegion* _from; public: void set_region(HeapRegion* from) { _from = from; } }; class G1ParClosureSuper : public OopsInHeapRegionClosure { protected: G1CollectedHeap* _g1; G1RemSet* _g1_rem; ConcurrentMark* _cm; G1ParScanThreadState* _par_scan_state; uint _worker_id; bool _during_initial_mark; bool _mark_in_progress; public: G1ParClosureSuper(G1CollectedHeap* g1, G1ParScanThreadState* par_scan_state); bool apply_to_weak_ref_discovered_field() { return true; } }; class G1ParPushHeapRSClosure : public G1ParClosureSuper { public: G1ParPushHeapRSClosure(G1CollectedHeap* g1, G1ParScanThreadState* par_scan_state): G1ParClosureSuper(g1, par_scan_state) { } template <class T> void do_oop_nv(T* p); virtual void do_oop(oop* p) { do_oop_nv(p); } virtual void do_oop(narrowOop* p) { do_oop_nv(p); } }; class G1ParScanClosure : public G1ParClosureSuper { public: G1ParScanClosure(G1CollectedHeap* g1, G1ParScanThreadState* par_scan_state, ReferenceProcessor* rp) : G1ParClosureSuper(g1, par_scan_state) { assert(_ref_processor == NULL, "sanity"); _ref_processor = rp; } template <class T> void do_oop_nv(T* p); virtual void do_oop(oop* p) { do_oop_nv(p); } virtual void do_oop(narrowOop* p) { do_oop_nv(p); } }; #define G1_PARTIAL_ARRAY_MASK 0x2 inline bool has_partial_array_mask(oop* ref) { return ((uintptr_t)ref & G1_PARTIAL_ARRAY_MASK) == G1_PARTIAL_ARRAY_MASK; } // We never encode partial array oops as narrowOop*, so return false immediately. // This allows the compiler to create optimized code when popping references from // the work queue. inline bool has_partial_array_mask(narrowOop* ref) { assert(((uintptr_t)ref & G1_PARTIAL_ARRAY_MASK) != G1_PARTIAL_ARRAY_MASK, "Partial array oop reference encoded as narrowOop*"); return false; } // Only implement set_partial_array_mask() for regular oops, not for narrowOops. // We always encode partial arrays as regular oop, to allow the // specialization for has_partial_array_mask() for narrowOops above. // This means that unintentional use of this method with narrowOops are caught // by the compiler. inline oop* set_partial_array_mask(oop obj) { assert(((uintptr_t)(void *)obj & G1_PARTIAL_ARRAY_MASK) == 0, "Information loss!"); return (oop*) ((uintptr_t)(void *)obj | G1_PARTIAL_ARRAY_MASK); } template <class T> inline oop clear_partial_array_mask(T* ref) { return cast_to_oop((intptr_t)ref & ~G1_PARTIAL_ARRAY_MASK); } class G1ParScanPartialArrayClosure : public G1ParClosureSuper { G1ParScanClosure _scanner; public: G1ParScanPartialArrayClosure(G1CollectedHeap* g1, G1ParScanThreadState* par_scan_state, ReferenceProcessor* rp) : G1ParClosureSuper(g1, par_scan_state), _scanner(g1, par_scan_state, rp) { assert(_ref_processor == NULL, "sanity"); } G1ParScanClosure* scanner() { return &_scanner; } template <class T> void do_oop_nv(T* p); virtual void do_oop(oop* p) { do_oop_nv(p); } virtual void do_oop(narrowOop* p) { do_oop_nv(p); } }; // Add back base class for metadata class G1ParCopyHelper : public G1ParClosureSuper { Klass* _scanned_klass; public: G1ParCopyHelper(G1CollectedHeap* g1, G1ParScanThreadState* par_scan_state) : _scanned_klass(NULL), G1ParClosureSuper(g1, par_scan_state) {} void set_scanned_klass(Klass* k) { _scanned_klass = k; } template <class T> void do_klass_barrier(T* p, oop new_obj); }; template <G1Barrier barrier, bool do_mark_object> class G1ParCopyClosure : public G1ParCopyHelper { G1ParScanClosure _scanner; template <class T> void do_oop_work(T* p); protected: // Mark the object if it's not already marked. This is used to mark // objects pointed to by roots that are guaranteed not to move // during the GC (i.e., non-CSet objects). It is MT-safe. void mark_object(oop obj); // Mark the object if it's not already marked. This is used to mark // objects pointed to by roots that have been forwarded during a // GC. It is MT-safe. void mark_forwarded_object(oop from_obj, oop to_obj); oop copy_to_survivor_space(oop obj); public: G1ParCopyClosure(G1CollectedHeap* g1, G1ParScanThreadState* par_scan_state, ReferenceProcessor* rp) : _scanner(g1, par_scan_state, rp), G1ParCopyHelper(g1, par_scan_state) { assert(_ref_processor == NULL, "sanity"); } G1ParScanClosure* scanner() { return &_scanner; } template <class T> void do_oop_nv(T* p) { do_oop_work(p); } virtual void do_oop(oop* p) { do_oop_nv(p); } virtual void do_oop(narrowOop* p) { do_oop_nv(p); } }; typedef G1ParCopyClosure<G1BarrierNone, false> G1ParScanExtRootClosure; typedef G1ParCopyClosure<G1BarrierKlass, false> G1ParScanMetadataClosure; typedef G1ParCopyClosure<G1BarrierNone, true> G1ParScanAndMarkExtRootClosure; typedef G1ParCopyClosure<G1BarrierKlass, true> G1ParScanAndMarkMetadataClosure; // The following closure type is defined in g1_specialized_oop_closures.hpp: // // typedef G1ParCopyClosure<G1BarrierEvac, false> G1ParScanHeapEvacClosure; // We use a separate closure to handle references during evacuation // failure processing. // We could have used another instance of G1ParScanHeapEvacClosure // (since that closure no longer assumes that the references it // handles point into the collection set). typedef G1ParCopyClosure<G1BarrierEvac, false> G1ParScanHeapEvacFailureClosure; class FilterIntoCSClosure: public ExtendedOopClosure { G1CollectedHeap* _g1; OopClosure* _oc; DirtyCardToOopClosure* _dcto_cl; public: FilterIntoCSClosure( DirtyCardToOopClosure* dcto_cl, G1CollectedHeap* g1, OopClosure* oc) : _dcto_cl(dcto_cl), _g1(g1), _oc(oc) { } template <class T> void do_oop_nv(T* p); virtual void do_oop(oop* p) { do_oop_nv(p); } virtual void do_oop(narrowOop* p) { do_oop_nv(p); } bool apply_to_weak_ref_discovered_field() { return true; } }; class FilterOutOfRegionClosure: public ExtendedOopClosure { HeapWord* _r_bottom; HeapWord* _r_end; OopClosure* _oc; public: FilterOutOfRegionClosure(HeapRegion* r, OopClosure* oc); template <class T> void do_oop_nv(T* p); virtual void do_oop(oop* p) { do_oop_nv(p); } virtual void do_oop(narrowOop* p) { do_oop_nv(p); } bool apply_to_weak_ref_discovered_field() { return true; } }; // Closure for iterating over object fields during concurrent marking class G1CMOopClosure : public ExtendedOopClosure { private: G1CollectedHeap* _g1h; ConcurrentMark* _cm; CMTask* _task; public: G1CMOopClosure(G1CollectedHeap* g1h, ConcurrentMark* cm, CMTask* task); template <class T> void do_oop_nv(T* p); virtual void do_oop( oop* p) { do_oop_nv(p); } virtual void do_oop(narrowOop* p) { do_oop_nv(p); } }; // Closure to scan the root regions during concurrent marking class G1RootRegionScanClosure : public ExtendedOopClosure { private: G1CollectedHeap* _g1h; ConcurrentMark* _cm; uint _worker_id; public: G1RootRegionScanClosure(G1CollectedHeap* g1h, ConcurrentMark* cm, uint worker_id) : _g1h(g1h), _cm(cm), _worker_id(worker_id) { } template <class T> void do_oop_nv(T* p); virtual void do_oop( oop* p) { do_oop_nv(p); } virtual void do_oop(narrowOop* p) { do_oop_nv(p); } }; // Closure that applies the given two closures in sequence. // Used by the RSet refinement code (when updating RSets // during an evacuation pause) to record cards containing // pointers into the collection set. class G1Mux2Closure : public ExtendedOopClosure { OopClosure* _c1; OopClosure* _c2; public: G1Mux2Closure(OopClosure *c1, OopClosure *c2); template <class T> void do_oop_nv(T* p); virtual void do_oop(oop* p) { do_oop_nv(p); } virtual void do_oop(narrowOop* p) { do_oop_nv(p); } }; // A closure that returns true if it is actually applied // to a reference class G1TriggerClosure : public ExtendedOopClosure { bool _triggered; public: G1TriggerClosure(); bool triggered() const { return _triggered; } template <class T> void do_oop_nv(T* p); virtual void do_oop(oop* p) { do_oop_nv(p); } virtual void do_oop(narrowOop* p) { do_oop_nv(p); } }; // A closure which uses a triggering closure to determine // whether to apply an oop closure. class G1InvokeIfNotTriggeredClosure: public ExtendedOopClosure { G1TriggerClosure* _trigger_cl; OopClosure* _oop_cl; public: G1InvokeIfNotTriggeredClosure(G1TriggerClosure* t, OopClosure* oc); template <class T> void do_oop_nv(T* p); virtual void do_oop(oop* p) { do_oop_nv(p); } virtual void do_oop(narrowOop* p) { do_oop_nv(p); } }; class G1UpdateRSOrPushRefOopClosure: public ExtendedOopClosure { G1CollectedHeap* _g1; G1RemSet* _g1_rem_set; HeapRegion* _from; OopsInHeapRegionClosure* _push_ref_cl; bool _record_refs_into_cset; int _worker_i; public: G1UpdateRSOrPushRefOopClosure(G1CollectedHeap* g1h, G1RemSet* rs, OopsInHeapRegionClosure* push_ref_cl, bool record_refs_into_cset, int worker_i = 0); void set_from(HeapRegion* from) { assert(from != NULL, "from region must be non-NULL"); _from = from; } bool self_forwarded(oop obj) { bool result = (obj->is_forwarded() && (obj->forwardee()== obj)); return result; } bool apply_to_weak_ref_discovered_field() { return true; } template <class T> void do_oop_nv(T* p); virtual void do_oop(narrowOop* p) { do_oop_nv(p); } virtual void do_oop(oop* p) { do_oop_nv(p); } }; #endif // SHARE_VM_GC_IMPLEMENTATION_G1_G1OOPCLOSURES_HPP <|endoftext|>
<commit_before>#include "binary.h" #include "options.h" #include "trace.h" #include <llvm/CodeGen/CommandFlags.h> #include <llvm/MC/SubtargetFeature.h> #include <llvm/ADT/Triple.h> #include <llvm/Support/Host.h> #include <llvm/Support/FileSystem.h> #include <llvm/Support/TargetRegistry.h> #include <llvm/Support/ToolOutputFile.h> #include <llvm/Support/FormattedStream.h> #include <llvm/Analysis/TargetLibraryInfo.h> #include <llvm/Target/TargetMachine.h> #include <llvm/Support/TargetSelect.h> #include <llvm/Pass.h> #include <llvm/PassManager.h> #include <iostream> #include <system_error> static llvm::tool_output_file *GetOutputStream(const std::string& filename) { // Open the file. std::error_code error; llvm::sys::fs::OpenFlags OpenFlags = llvm::sys::fs::F_None; llvm::tool_output_file *FDOut = new llvm::tool_output_file(filename, error, OpenFlags); if (error) { std::cerr << error << '\n'; delete FDOut; return 0; } return FDOut; } static void CreateObject(llvm::Module *module, const std::string& objname) { TIME_TRACE(); llvm::InitializeAllTargets(); llvm::InitializeAllTargetMCs(); llvm::InitializeAllAsmPrinters(); llvm::InitializeAllAsmParsers(); llvm::Triple triple(llvm::sys::getDefaultTargetTriple()); module->setTargetTriple(triple.getTriple()); std::string error; const llvm::Target *target = llvm::TargetRegistry::lookupTarget("", triple, error); if (!target) { std::cerr << "Error, could not find target: " << error << std::endl; return; } if (MCPU == "native") { MCPU = sys::getHostCPUName(); } std::string FeaturesStr; if (MAttrs.size()) { SubtargetFeatures Features; for (unsigned i = 0; i != MAttrs.size(); ++i) { Features.AddFeature(MAttrs[i]); } FeaturesStr = Features.getString(); } llvm::TargetOptions options; llvm::TargetMachine* tm = target->createTargetMachine(triple.getTriple(), MCPU, FeaturesStr, options); if (!tm) { std::cerr << "Error: Could not create targetmachine." << std::endl; return; } llvm::PassManager PM; llvm::TargetLibraryInfoWrapperPass *TLI = new llvm::TargetLibraryInfoWrapperPass(triple); PM.add(TLI); std::unique_ptr<llvm::tool_output_file> Out(GetOutputStream(objname)); if (!Out) { std::cerr << "Could not open file ... " << std::endl; return; } llvm::formatted_raw_ostream FOS(Out->os()); llvm::AnalysisID StartAfterID = 0; llvm::AnalysisID StopAfterID = 0; if (tm->addPassesToEmitFile(PM, FOS, llvm::LLVMTargetMachine::CGFT_ObjectFile, false, StartAfterID, StopAfterID)) { std::cerr << objname << ": target does not support generation of this" << " file type!\n"; return; } PM.run(*module); Out->keep(); } std::string replace_ext(const std::string &origName, const std::string& expectedExt, const std::string& newExt) { if (origName.substr(origName.size() - expectedExt.size()) != expectedExt) { std::cerr << "Could not find extension..." << std::endl; exit(1); } return origName.substr(0, origName.size() - expectedExt.size()) + newExt; } void CreateBinary(llvm::Module *module, const std::string& filename, EmitType emit) { TIME_TRACE(); if (emit == Exe) { std::string objname = replace_ext(filename, ".pas", ".o"); std::string exename = replace_ext(filename, ".pas", ""); CreateObject(module, objname); std::string verboseflags; if (verbosity) { verboseflags = "-v "; } std::string cmd = std::string("clang ") + verboseflags + objname + " -L. -lruntime -lm -o " + exename; if (verbosity) { std::cerr << "Executing final link command: " << cmd << std::endl; } system(cmd.c_str()); return; } if (emit == LlvmIr) { std::string irName = replace_ext(filename, ".pas", ".ll"); std::unique_ptr<llvm::tool_output_file> Out(GetOutputStream(irName)); llvm::formatted_raw_ostream FOS(Out->os()); module->print(FOS, 0); Out->keep(); return; } assert(0 && "Unknown emit type"); } <commit_msg>Fix for updated LLVM<commit_after>#include "binary.h" #include "options.h" #include "trace.h" #include <llvm/CodeGen/CommandFlags.h> #include <llvm/MC/SubtargetFeature.h> #include <llvm/ADT/Triple.h> #include <llvm/Support/Host.h> #include <llvm/Support/FileSystem.h> #include <llvm/Support/TargetRegistry.h> #include <llvm/Support/ToolOutputFile.h> #include <llvm/Support/FormattedStream.h> #include <llvm/Analysis/TargetLibraryInfo.h> #include <llvm/Target/TargetMachine.h> #include <llvm/Support/TargetSelect.h> #include <llvm/Pass.h> #include <llvm/PassManager.h> #include <iostream> #include <system_error> static llvm::tool_output_file *GetOutputStream(const std::string& filename) { // Open the file. std::error_code error; llvm::sys::fs::OpenFlags OpenFlags = llvm::sys::fs::F_None; llvm::tool_output_file *FDOut = new llvm::tool_output_file(filename, error, OpenFlags); if (error) { std::cerr << error << '\n'; delete FDOut; return 0; } return FDOut; } static void CreateObject(llvm::Module *module, const std::string& objname) { TIME_TRACE(); llvm::InitializeAllTargets(); llvm::InitializeAllTargetMCs(); llvm::InitializeAllAsmPrinters(); llvm::InitializeAllAsmParsers(); llvm::Triple triple(llvm::sys::getDefaultTargetTriple()); module->setTargetTriple(triple.getTriple()); std::string error; const llvm::Target *target = llvm::TargetRegistry::lookupTarget("", triple, error); if (!target) { std::cerr << "Error, could not find target: " << error << std::endl; return; } if (MCPU == "native") { MCPU = sys::getHostCPUName(); } std::string FeaturesStr; if (MAttrs.size()) { SubtargetFeatures Features; for (unsigned i = 0; i != MAttrs.size(); ++i) { Features.AddFeature(MAttrs[i]); } FeaturesStr = Features.getString(); } llvm::TargetOptions options; llvm::TargetMachine* tm = target->createTargetMachine(triple.getTriple(), MCPU, FeaturesStr, options); if (!tm) { std::cerr << "Error: Could not create targetmachine." << std::endl; return; } llvm::PassManager PM; llvm::TargetLibraryInfoWrapperPass *TLI = new llvm::TargetLibraryInfoWrapperPass(triple); PM.add(TLI); std::unique_ptr<llvm::tool_output_file> Out(GetOutputStream(objname)); if (!Out) { std::cerr << "Could not open file ... " << std::endl; return; } llvm::raw_pwrite_stream *OS = &Out->os(); llvm::AnalysisID StartAfterID = 0; llvm::AnalysisID StopAfterID = 0; if (tm->addPassesToEmitFile(PM, *OS, llvm::LLVMTargetMachine::CGFT_ObjectFile, false, StartAfterID, StopAfterID)) { std::cerr << objname << ": target does not support generation of this" << " file type!\n"; return; } PM.run(*module); Out->keep(); } std::string replace_ext(const std::string &origName, const std::string& expectedExt, const std::string& newExt) { if (origName.substr(origName.size() - expectedExt.size()) != expectedExt) { std::cerr << "Could not find extension..." << std::endl; exit(1); } return origName.substr(0, origName.size() - expectedExt.size()) + newExt; } void CreateBinary(llvm::Module *module, const std::string& filename, EmitType emit) { TIME_TRACE(); if (emit == Exe) { std::string objname = replace_ext(filename, ".pas", ".o"); std::string exename = replace_ext(filename, ".pas", ""); CreateObject(module, objname); std::string verboseflags; if (verbosity) { verboseflags = "-v "; } std::string cmd = std::string("clang ") + verboseflags + objname + " -L. -lruntime -lm -o " + exename; if (verbosity) { std::cerr << "Executing final link command: " << cmd << std::endl; } system(cmd.c_str()); return; } if (emit == LlvmIr) { std::string irName = replace_ext(filename, ".pas", ".ll"); std::unique_ptr<llvm::tool_output_file> Out(GetOutputStream(irName)); llvm::formatted_raw_ostream FOS(Out->os()); module->print(FOS, 0); Out->keep(); return; } assert(0 && "Unknown emit type"); } <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include <cucumber-cpp/autodetect.hpp> #include <mylib/calculator.hpp> using cucumber::ScenarioScope; struct CalcCtx { calculator calc; double first; double second; double result; }; GIVEN("^I have entered (\\d+) into the calculator$") { REGEX_PARAM(double, n); ScenarioScope<CalcCtx> context; context->first = n; context->second = n; } WHEN("^I press add") { ScenarioScope<CalcCtx> context; context->result = context->calc.sum(context->first, context->second); } WHEN("^I press divide") { ScenarioScope<CalcCtx> context; //context->result = context->calc.divide(); } THEN("^the result should be (.*) on the screen$") { REGEX_PARAM(double, expected); ScenarioScope<CalcCtx> context; EXPECT_EQ(expected, context->result); }<commit_msg>Fixed conversion-warning<commit_after>#include <gtest/gtest.h> #include <cucumber-cpp/autodetect.hpp> #include <mylib/calculator.hpp> using cucumber::ScenarioScope; struct CalcCtx { calculator calc; int first; int second; int result; }; GIVEN("^I have entered (\\d+) into the calculator$") { REGEX_PARAM(int, n); ScenarioScope<CalcCtx> context; context->first = n; context->second = n; } WHEN("^I press add") { ScenarioScope<CalcCtx> context; context->result = context->calc.sum(context->first, context->second); } WHEN("^I press divide") { ScenarioScope<CalcCtx> context; //context->result = context->calc.divide(); } THEN("^the result should be (.*) on the screen$") { REGEX_PARAM(int, expected); ScenarioScope<CalcCtx> context; EXPECT_EQ(expected, context->result); }<|endoftext|>
<commit_before>#include "agenda.h" #include "errors.h" #include <unistd.h> #include <thread> #include <sstream> #include <unistd.h> #include <boost/bind.hpp> #include <time.h> #include <iostream> using namespace es3; agenda::agenda(size_t num_unbound, size_t num_cpu_bound, size_t num_io_bound, bool quiet, bool final_quiet, size_t segment_size, size_t max_segments_in_flight) : class_limits_ {{taskUnbound, num_unbound}, {taskCPUBound, num_cpu_bound}, {taskIOBound, num_io_bound}}, quiet_(quiet), final_quiet_(final_quiet), segment_size_(segment_size), max_segments_in_flight_(max_segments_in_flight), num_working_(), num_submitted_(), num_done_(), num_failed_(), segments_in_flight_() { clock_gettime(CLOCK_MONOTONIC, &start_time_) | libc_die2("Can't get time"); } namespace es3 { struct segment_deleter { agenda_ptr parent_; void operator()(segment *seg) { delete seg; u_guard_t guard(parent_->segment_m_); assert(parent_->segments_in_flight_>0); parent_->segments_in_flight_--; parent_->segment_ready_condition_.notify_all(); } }; class task_executor { agenda_ptr agenda_; public: task_executor(agenda_ptr agenda) : agenda_(agenda) {} sync_task_ptr claim_task() { while(true) { u_guard_t lock(agenda_->m_); if (agenda_->tasks_.empty()) { if (agenda_->num_working_==0) return sync_task_ptr(); } for(auto iter=agenda_->tasks_.begin(); iter!=agenda_->tasks_.end();++iter) { sync_task_ptr cur_task = *iter; //Check if there are too many tasks of this type running task_type_e cur_class=cur_task->get_class(); size_t cur_num=agenda_->classes_[cur_class]; //Unbound tasks are allowed to exceed their limits and //borrow threads from other classes if (cur_class!=taskUnbound && agenda_->get_capability(cur_class)<=cur_num) continue; agenda_->tasks_.erase(iter); agenda_->num_working_++; agenda_->classes_[cur_class]++; return cur_task; } agenda_->condition_.wait(lock); } } void cleanup(sync_task_ptr cur_task, bool fail) { u_guard_t lock(agenda_->m_); agenda_->num_working_--; assert(agenda_->classes_[cur_task->get_class()]>0); agenda_->classes_[cur_task->get_class()]--; if (agenda_->tasks_.empty() && agenda_->num_working_==0) agenda_->condition_.notify_all(); //We've finished our tasks! else agenda_->condition_.notify_one(); //Update stats guard_t lockst(agenda_->stats_m_); agenda_->num_done_++; if (fail) agenda_->num_failed_++; } void operator ()() { while(true) { sync_task_ptr cur_task=claim_task(); if (!cur_task) break; bool fail=true; for(int f=0; f<10; ++f) { try { (*cur_task)(agenda_); fail=false; break; } catch (const es3_exception &ex) { const result_code_t &code = ex.err(); if (code.code()==errNone) { VLOG(2) << "INFO: " << ex.what(); sleep(5); continue; } else if (code.code()==errWarn) { VLOG(1) << "WARN: " << ex.what(); sleep(5); continue; } else { VLOG(0) << ex.what(); break; } } catch(const std::exception &ex) { VLOG(0) << "ERROR: " << ex.what(); break; } catch(...) { VLOG(0) << "Unknown exception. Skipping"; break; } } cleanup(cur_task, fail); } } }; } segment_ptr agenda::get_segment() { u_guard_t guard(segment_m_); while(segments_in_flight_>max_segments_in_flight_) segment_ready_condition_.wait(guard); segment_deleter del {shared_from_this()}; segment_ptr res=segment_ptr(new segment(), del); segments_in_flight_++; return res; } void agenda::schedule(sync_task_ptr task) { u_guard_t lock(m_); agenda_ptr ptr = shared_from_this(); tasks_.push_back(task); condition_.notify_one(); guard_t lockst(stats_m_); num_submitted_++; } size_t agenda::run() { std::vector<std::thread> threads; size_t thread_num=0; for(auto iter=class_limits_.begin();iter!=class_limits_.end();++iter) thread_num+=iter->second; for(int f=0;f<thread_num;++f) threads.push_back(std::thread(task_executor(shared_from_this()))); if (!quiet_) { threads.push_back(std::thread(boost::bind(&agenda::draw_progress, this))); for(int f=0;f<threads.size();++f) threads.at(f).join(); //Draw progress the last time draw_progress_widget(); std::cerr<<std::endl; } else { for(int f=0;f<threads.size();++f) threads.at(f).join(); } if (!final_quiet_) draw_stats(); return num_failed_; } void agenda::draw_progress() { while(true) { { guard_t g(m_); if (num_working_==0 && tasks_.empty()) return; } draw_progress_widget(); usleep(500000); } } void agenda::add_stat_counter(const std::string &stat, uint64_t val) { guard_t lockst(stats_m_); cur_stats_[stat]+=val; } std::pair<std::string, std::string> agenda::format_si(uint64_t val, bool per_sec) { std::pair<std::string, std::string> res; uint64_t denom = 1; if (val<10000) { denom = 1; res.second = "B"; } else if (val<2000000) { denom = 1024; res.second = "K"; } else { denom = 1024*1024; res.second = "M"; } res.first = int_to_string(val/denom); if (val%denom) res.first+="."+int_to_string((val%denom)*100/denom); return res; } void agenda::draw_progress_widget() { uint64_t el = get_elapsed_millis(); std::stringstream str; { guard_t lockst(stats_m_); str << "Tasks: [" << num_done_ << "/" << num_submitted_ << "]"; if (num_failed_) str << " Failed tasks: " << num_failed_; uint64_t uploaded = cur_stats_["uploaded"]; uint64_t downloaded = cur_stats_["downloaded"]; if (downloaded) { auto dl=format_si(downloaded, false); auto ds=format_si(el==0? 0 : (downloaded*1000/el), true); str << " Downloaded: " << dl.first << " " << dl.second << ", speed: " << ds.first << " " << ds.second << "/sec"; } if (uploaded) { auto ul=format_si(uploaded, false); auto us=format_si(el==0? 0 : (uploaded*1000/el), true); str << " Uploaded: " << ul.first << " " << ul.second << ", speed: " << us.first << " " << us.second << "/sec"; } str << "\r"; } std::cerr << str.str(); //No std::endl std::cerr.flush(); } uint64_t agenda::get_elapsed_millis() const { struct timespec cur; clock_gettime(CLOCK_MONOTONIC, &cur) | libc_die2("Can't get time"); uint64_t start_tm = uint64_t(start_time_.tv_sec)*1000 + start_time_.tv_nsec/1000000; uint64_t cur_tm = uint64_t(cur.tv_sec)*1000+cur.tv_nsec/1000000; return cur_tm-start_tm; } void agenda::draw_stats() { uint64_t el = get_elapsed_millis(); std::cerr << "time taken [sec]: " << el/1000 << "." << el%1000 << std::endl; for(auto f=cur_stats_.begin();f!=cur_stats_.end();++f) { std::string name=f->first; uint64_t val=f->second; uint64_t avg = val*1000/el; std::cerr << name << " [B]: " << val << ", average [B/sec]: " << avg << std::endl; } } <commit_msg>Tweak<commit_after>#include "agenda.h" #include "errors.h" #include <unistd.h> #include <thread> #include <sstream> #include <unistd.h> #include <boost/bind.hpp> #include <time.h> #include <iostream> using namespace es3; agenda::agenda(size_t num_unbound, size_t num_cpu_bound, size_t num_io_bound, bool quiet, bool final_quiet, size_t segment_size, size_t max_segments_in_flight) : class_limits_ {{taskUnbound, num_unbound}, {taskCPUBound, num_cpu_bound}, {taskIOBound, num_io_bound}}, quiet_(quiet), final_quiet_(final_quiet), segment_size_(segment_size), max_segments_in_flight_(max_segments_in_flight), num_working_(), num_submitted_(), num_done_(), num_failed_(), segments_in_flight_() { clock_gettime(CLOCK_MONOTONIC, &start_time_) | libc_die2("Can't get time"); } namespace es3 { struct segment_deleter { agenda_ptr parent_; void operator()(segment *seg) { delete seg; u_guard_t guard(parent_->segment_m_); assert(parent_->segments_in_flight_>0); parent_->segments_in_flight_--; parent_->segment_ready_condition_.notify_all(); } }; class task_executor { agenda_ptr agenda_; public: task_executor(agenda_ptr agenda) : agenda_(agenda) {} sync_task_ptr claim_task() { while(true) { u_guard_t lock(agenda_->m_); if (agenda_->tasks_.empty()) { if (agenda_->num_working_==0) return sync_task_ptr(); } for(auto iter=agenda_->tasks_.begin(); iter!=agenda_->tasks_.end();++iter) { sync_task_ptr cur_task = *iter; //Check if there are too many tasks of this type running task_type_e cur_class=cur_task->get_class(); size_t cur_num=agenda_->classes_[cur_class]; //Unbound tasks are allowed to exceed their limits and //borrow threads from other classes if (cur_class!=taskUnbound && agenda_->get_capability(cur_class)<=cur_num) continue; agenda_->tasks_.erase(iter); agenda_->num_working_++; agenda_->classes_[cur_class]++; return cur_task; } agenda_->condition_.wait(lock); } } void cleanup(sync_task_ptr cur_task, bool fail) { u_guard_t lock(agenda_->m_); agenda_->num_working_--; assert(agenda_->classes_[cur_task->get_class()]>0); agenda_->classes_[cur_task->get_class()]--; if (agenda_->tasks_.empty() && agenda_->num_working_==0) agenda_->condition_.notify_all(); //We've finished our tasks! else agenda_->condition_.notify_one(); //Update stats guard_t lockst(agenda_->stats_m_); agenda_->num_done_++; if (fail) agenda_->num_failed_++; } void operator ()() { while(true) { sync_task_ptr cur_task=claim_task(); if (!cur_task) break; bool fail=true; for(int f=0; f<10; ++f) { try { (*cur_task)(agenda_); fail=false; break; } catch (const es3_exception &ex) { const result_code_t &code = ex.err(); if (code.code()==errNone) { VLOG(2) << "INFO: " << ex.what(); sleep(5); continue; } else if (code.code()==errWarn) { VLOG(1) << "WARN: " << ex.what(); sleep(5); continue; } else { VLOG(0) << ex.what(); break; } } catch(const std::exception &ex) { VLOG(0) << "ERROR: " << ex.what(); break; } catch(...) { VLOG(0) << "Unknown exception. Skipping"; break; } } cleanup(cur_task, fail); } } }; } segment_ptr agenda::get_segment() { u_guard_t guard(segment_m_); while(segments_in_flight_>max_segments_in_flight_) segment_ready_condition_.wait(guard); segment_deleter del {shared_from_this()}; segment_ptr res=segment_ptr(new segment(), del); segments_in_flight_++; return res; } void agenda::schedule(sync_task_ptr task) { u_guard_t lock(m_); agenda_ptr ptr = shared_from_this(); tasks_.push_back(task); condition_.notify_one(); guard_t lockst(stats_m_); num_submitted_++; } size_t agenda::run() { std::vector<std::thread> threads; size_t thread_num=0; for(auto iter=class_limits_.begin();iter!=class_limits_.end();++iter) thread_num+=iter->second; for(int f=0;f<thread_num;++f) threads.push_back(std::thread(task_executor(shared_from_this()))); if (!quiet_) { threads.push_back(std::thread(boost::bind(&agenda::draw_progress, this))); for(int f=0;f<threads.size();++f) threads.at(f).join(); //Draw progress the last time draw_progress_widget(); std::cerr<<std::endl; } else { for(int f=0;f<threads.size();++f) threads.at(f).join(); } if (!final_quiet_) draw_stats(); return num_failed_; } void agenda::draw_progress() { while(true) { { guard_t g(m_); if (num_working_==0 && tasks_.empty()) return; } draw_progress_widget(); usleep(500000); } } void agenda::add_stat_counter(const std::string &stat, uint64_t val) { guard_t lockst(stats_m_); cur_stats_[stat]+=val; } std::pair<std::string, std::string> agenda::format_si(uint64_t val, bool per_sec) { std::pair<std::string, std::string> res; uint64_t denom = 1; if (val<10000) { denom = 1; res.second = "B"; } else if (val<2000000) { denom = 1024; res.second = "K"; } else { denom = 1024*1024; res.second = "M"; } res.first = int_to_string(val/denom); if (val%denom) res.first+="."+int_to_string((val%denom)*100/denom); return res; } void agenda::draw_progress_widget() { uint64_t el = get_elapsed_millis(); std::stringstream str; { guard_t lockst(stats_m_); str << "Tasks: [" << num_done_ << "/" << num_submitted_ << "]"; if (num_failed_) str << " Failed tasks: " << num_failed_; uint64_t uploaded = cur_stats_["uploaded"]; uint64_t downloaded = cur_stats_["downloaded"]; if (downloaded) { auto dl=format_si(downloaded, false); auto ds=format_si(el==0? 0 : (downloaded*1000/el), true); str << " Downloaded: " << dl.first << " " << dl.second << ", speed: " << ds.first << " " << ds.second << "/sec"; } if (uploaded) { auto ul=format_si(uploaded, false); auto us=format_si(el==0? 0 : (uploaded*1000/el), true); str << " Uploaded: " << ul.first << " " << ul.second << ", speed: " << us.first << " " << us.second << "/sec"; } str << "\r"; } std::cerr << str.str(); //No std::endl std::cerr.flush(); } uint64_t agenda::get_elapsed_millis() const { struct timespec cur; clock_gettime(CLOCK_MONOTONIC, &cur) | libc_die2("Can't get time"); uint64_t start_tm = uint64_t(start_time_.tv_sec)*1000 + start_time_.tv_nsec/1000000; uint64_t cur_tm = uint64_t(cur.tv_sec)*1000+cur.tv_nsec/1000000; return cur_tm-start_tm; } void agenda::draw_stats() { uint64_t el = get_elapsed_millis(); std::cerr << "time taken [sec]: " << el/1000 << "." << el%1000 << std::endl; for(auto f=cur_stats_.begin();f!=cur_stats_.end();++f) { std::string name=f->first; uint64_t val=f->second; if (!val) continue uint64_t avg = val*1000/el; std::cerr << name << " [B]: " << val << ", average [B/sec]: " << avg << std::endl; } } <|endoftext|>
<commit_before>// // Physical page allocator. // Slab allocator, for chunks larger than one page. // #include "types.h" #include "mmu.h" #include "kernel.hh" #include "spinlock.h" #include "kalloc.hh" #include "mtrace.h" #include "cpu.hh" #include "multiboot.hh" #include "wq.hh" static struct Mbmem mem[128]; static u64 nmem; static u64 membytes; struct kmem kmems[NCPU]; struct kmem slabmem[slab_type_max][NCPU]; extern char end[]; // first address after kernel loaded from ELF file char *newend; static int kinited __mpalign__; static struct Mbmem * memsearch(paddr pa) { struct Mbmem *e; struct Mbmem *q; q = mem+nmem; for (e = &mem[0]; e < q; e++) if ((e->base <= pa) && ((e->base+e->length) > pa)) return e; return 0; } static u64 memsize(void *va) { struct Mbmem *e; paddr pa = v2p(va); e = memsearch(pa); if (e == nullptr) return -1; return (e->base+e->length) - pa; } static void * memnext(void *va, u64 inc) { struct Mbmem *e, *q; paddr pa = v2p(va); e = memsearch(pa); if (e == nullptr) return (void *)-1; pa += inc; if (pa < (e->base+e->length)) return p2v(pa); q = mem+nmem; for (e = e + 1; e < q; e++) return p2v(e->base); return (void *)-1; } static void initmem(u64 mbaddr) { struct Mbdata *mb; struct Mbmem *mbmem; u8 *p, *ep; mb = (Mbdata*) p2v(mbaddr); if(!(mb->flags & (1<<6))) panic("multiboot header has no memory map"); p = (u8*) p2v(mb->mmap_addr); ep = p + mb->mmap_length; while (p < ep) { mbmem = (Mbmem *)(p+4); p += 4 + *(u32*)p; if (mbmem->type == 1) { membytes += mbmem->length; mem[nmem] = *mbmem; nmem++; } } } // simple page allocator to get off the ground during boot static char * pgalloc(void) { if (newend == 0) newend = end; void *p = (void*)PGROUNDUP((uptr)newend); memset(p, 0, PGSIZE); newend = newend + PGSIZE; return (char*) p; } // // kmem // run* kmem::alloc(const char* name) { for (;;) { auto headval = freelist.load(); run* r = headval.ptr(); if (!r) return nullptr; run *nxt = r->next; if (freelist.compare_exchange(headval, nxt)) { if (r->next != nxt) panic("kmem:alloc: aba race %p %p %p\n", r, r->next, nxt); nfree--; return r; } } if (name) mtlabel(mtrace_label_block, r, m->size, name, strlen(name)); } void kmem::free(run* r) { if (kinited) mtunlabel(mtrace_label_block, r); for (;;) { auto headval = freelist.load(); r->next = headval.ptr(); if (freelist.compare_exchange(headval, r)) break; } nfree++; } // Free the page of physical memory pointed at by v, // which normally should have been returned by a // call to kalloc(). (The exception is when // initializing the allocator; see kinit above.) static void kfree_pool(struct kmem *m, char *v) { if ((uptr)v % PGSIZE) panic("kfree_pool: misaligned %p", v); if (memsize(v) == -1ull) panic("kfree_pool: unknown region %p", v); // Fill with junk to catch dangling refs. if (ALLOC_MEMSET && kinited && m->size <= 16384) memset(v, 1, m->size); m->free((run*)v); } static void kmemprint_pool(struct kmem *km) { cprintf("pool %s: [ ", &km[0].name[1]); for (u32 i = 0; i < NCPU; i++) if (i == mycpu()->id) cprintf("<%lu> ", km[i].nfree.load()); else cprintf("%lu ", km[i].nfree.load()); cprintf("]\n"); } void kmemprint() { kmemprint_pool(kmems); for (int i = 0; i < slab_type_max; i++) kmemprint_pool(slabmem[i]); } static char* kalloc_pool(struct kmem *km, const char *name) { struct run *r = 0; struct kmem *m; u32 startcpu = mycpu()->id; for (u32 i = 0; r == 0 && i < NCPU; i++) { int cn = (i + startcpu) % NCPU; m = &km[cn]; r = m->alloc(name); } if (r == 0) { cprintf("kalloc: out of memory in pool %s\n", km->name); kmemprint(); return 0; } if (ALLOC_MEMSET && m->size <= 16384) memset(r, 2, m->size); return (char*)r; } // Allocate one 4096-byte page of physical memory. // Returns a pointer that the kernel can use. // Returns 0 if the memory cannot be allocated. char* kalloc(const char *name) { if (!kinited) return pgalloc(); return kalloc_pool(kmems, name); } void * ksalloc(int slab) { return kalloc_pool(slabmem[slab], slabmem[slab]->name); } void slabinit(struct kmem *k, char **p, u64 *off) { for (int i = 0; i < k->ninit; i++) { if (*p == (void *)-1) panic("slabinit: memnext"); // XXX(sbw) handle this condition if (memsize(p) < k->size) panic("slabinit: memsize"); kfree_pool(k, *p); *p = (char*) memnext(*p, k->size); *off = *off+k->size; } } // Initialize free list of physical pages. void initkalloc(u64 mbaddr) { char *p; u64 n; u64 k; initmem(mbaddr); for (int c = 0; c < NCPU; c++) { kmems[c].name[0] = (char) c + '0'; safestrcpy(kmems[c].name+1, "kmem", MAXNAME-1); kmems[c].size = PGSIZE; } if (VERBOSE) cprintf("%lu mbytes\n", membytes / (1<<20)); n = membytes / NCPU; if (n & (PGSIZE-1)) n = PGROUNDDOWN(n); p = (char*)PGROUNDUP((uptr)newend); k = (((uptr)p) - KCODE); p = (char*) KBASE + k; for (int c = 0; c < NCPU; c++) { // Fill slab allocators strncpy(slabmem[slab_stack][c].name, " kstack", MAXNAME); slabmem[slab_stack][c].size = KSTACKSIZE; slabmem[slab_stack][c].ninit = CPUKSTACKS; strncpy(slabmem[slab_perf][c].name, " kperf", MAXNAME); slabmem[slab_perf][c].size = PERFSIZE; slabmem[slab_perf][c].ninit = 1; strncpy(slabmem[slab_kshared][c].name, " kshared", MAXNAME); slabmem[slab_kshared][c].size = KSHAREDSIZE; slabmem[slab_kshared][c].ninit = CPUKSTACKS; strncpy(slabmem[slab_wq][c].name, " wq", MAXNAME); slabmem[slab_wq][c].size = PGROUNDUP(wq_size()); slabmem[slab_wq][c].ninit = NCPU; strncpy(slabmem[slab_userwq][c].name, " uwq", MAXNAME); slabmem[slab_userwq][c].size = USERWQSIZE; slabmem[slab_userwq][c].ninit = CPUKSTACKS; for (int i = 0; i < slab_type_max; i++) { slabmem[i][c].name[0] = (char) c + '0'; slabinit(&slabmem[i][c], &p, &k); } // The rest goes to the page allocator for (; k != n; k += PGSIZE, p = (char*) memnext(p, PGSIZE)) { if (p == (void *)-1) panic("initkalloc: e820next"); kfree_pool(&kmems[c], p); } k = 0; } kminit(); kinited = 1; } void kfree(void *v) { verifyfree((char*) v, mykmem()->size); kfree_pool(mykmem(), (char*) v); } void ksfree(int slab, void *v) { kfree_pool(slabmem[slab], (char*) v); } void verifyfree(char *ptr, u64 nbytes) { #if VERIFYFREE char *p = ptr; char *e = p + nbytes; for (; p < e; p++) { // Search for pointers in the ptr region u64 x = *(uptr *)p; if ((KBASE < x && x < KBASE+(128ull<<30)) || (KCODE < x)) { struct klockstat *kls = (struct klockstat *) x; if (kls->magic == LOCKSTAT_MAGIC) panic("LOCKSTAT_MAGIC %p(%lu):%p->%p", ptr, nbytes, p, kls); } } #endif } <commit_msg>fix define MTRACE 1 build bug<commit_after>// // Physical page allocator. // Slab allocator, for chunks larger than one page. // #include "types.h" #include "mmu.h" #include "kernel.hh" #include "spinlock.h" #include "kalloc.hh" #include "mtrace.h" #include "cpu.hh" #include "multiboot.hh" #include "wq.hh" static struct Mbmem mem[128]; static u64 nmem; static u64 membytes; struct kmem kmems[NCPU]; struct kmem slabmem[slab_type_max][NCPU]; extern char end[]; // first address after kernel loaded from ELF file char *newend; static int kinited __mpalign__; static struct Mbmem * memsearch(paddr pa) { struct Mbmem *e; struct Mbmem *q; q = mem+nmem; for (e = &mem[0]; e < q; e++) if ((e->base <= pa) && ((e->base+e->length) > pa)) return e; return 0; } static u64 memsize(void *va) { struct Mbmem *e; paddr pa = v2p(va); e = memsearch(pa); if (e == nullptr) return -1; return (e->base+e->length) - pa; } static void * memnext(void *va, u64 inc) { struct Mbmem *e, *q; paddr pa = v2p(va); e = memsearch(pa); if (e == nullptr) return (void *)-1; pa += inc; if (pa < (e->base+e->length)) return p2v(pa); q = mem+nmem; for (e = e + 1; e < q; e++) return p2v(e->base); return (void *)-1; } static void initmem(u64 mbaddr) { struct Mbdata *mb; struct Mbmem *mbmem; u8 *p, *ep; mb = (Mbdata*) p2v(mbaddr); if(!(mb->flags & (1<<6))) panic("multiboot header has no memory map"); p = (u8*) p2v(mb->mmap_addr); ep = p + mb->mmap_length; while (p < ep) { mbmem = (Mbmem *)(p+4); p += 4 + *(u32*)p; if (mbmem->type == 1) { membytes += mbmem->length; mem[nmem] = *mbmem; nmem++; } } } // simple page allocator to get off the ground during boot static char * pgalloc(void) { if (newend == 0) newend = end; void *p = (void*)PGROUNDUP((uptr)newend); memset(p, 0, PGSIZE); newend = newend + PGSIZE; return (char*) p; } // // kmem // run* kmem::alloc(const char* name) { run* r; for (;;) { auto headval = freelist.load(); r = headval.ptr(); if (!r) return nullptr; run *nxt = r->next; if (freelist.compare_exchange(headval, nxt)) { if (r->next != nxt) panic("kmem:alloc: aba race %p %p %p\n", r, r->next, nxt); nfree--; return r; } } if (name) mtlabel(mtrace_label_block, r, size, name, strlen(name)); } void kmem::free(run* r) { if (kinited) mtunlabel(mtrace_label_block, r); for (;;) { auto headval = freelist.load(); r->next = headval.ptr(); if (freelist.compare_exchange(headval, r)) break; } nfree++; } // Free the page of physical memory pointed at by v, // which normally should have been returned by a // call to kalloc(). (The exception is when // initializing the allocator; see kinit above.) static void kfree_pool(struct kmem *m, char *v) { if ((uptr)v % PGSIZE) panic("kfree_pool: misaligned %p", v); if (memsize(v) == -1ull) panic("kfree_pool: unknown region %p", v); // Fill with junk to catch dangling refs. if (ALLOC_MEMSET && kinited && m->size <= 16384) memset(v, 1, m->size); m->free((run*)v); } static void kmemprint_pool(struct kmem *km) { cprintf("pool %s: [ ", &km[0].name[1]); for (u32 i = 0; i < NCPU; i++) if (i == mycpu()->id) cprintf("<%lu> ", km[i].nfree.load()); else cprintf("%lu ", km[i].nfree.load()); cprintf("]\n"); } void kmemprint() { kmemprint_pool(kmems); for (int i = 0; i < slab_type_max; i++) kmemprint_pool(slabmem[i]); } static char* kalloc_pool(struct kmem *km, const char *name) { struct run *r = 0; struct kmem *m; u32 startcpu = mycpu()->id; for (u32 i = 0; r == 0 && i < NCPU; i++) { int cn = (i + startcpu) % NCPU; m = &km[cn]; r = m->alloc(name); } if (r == 0) { cprintf("kalloc: out of memory in pool %s\n", km->name); kmemprint(); return 0; } if (ALLOC_MEMSET && m->size <= 16384) memset(r, 2, m->size); return (char*)r; } // Allocate one 4096-byte page of physical memory. // Returns a pointer that the kernel can use. // Returns 0 if the memory cannot be allocated. char* kalloc(const char *name) { if (!kinited) return pgalloc(); return kalloc_pool(kmems, name); } void * ksalloc(int slab) { return kalloc_pool(slabmem[slab], slabmem[slab]->name); } void slabinit(struct kmem *k, char **p, u64 *off) { for (int i = 0; i < k->ninit; i++) { if (*p == (void *)-1) panic("slabinit: memnext"); // XXX(sbw) handle this condition if (memsize(p) < k->size) panic("slabinit: memsize"); kfree_pool(k, *p); *p = (char*) memnext(*p, k->size); *off = *off+k->size; } } // Initialize free list of physical pages. void initkalloc(u64 mbaddr) { char *p; u64 n; u64 k; initmem(mbaddr); for (int c = 0; c < NCPU; c++) { kmems[c].name[0] = (char) c + '0'; safestrcpy(kmems[c].name+1, "kmem", MAXNAME-1); kmems[c].size = PGSIZE; } if (VERBOSE) cprintf("%lu mbytes\n", membytes / (1<<20)); n = membytes / NCPU; if (n & (PGSIZE-1)) n = PGROUNDDOWN(n); p = (char*)PGROUNDUP((uptr)newend); k = (((uptr)p) - KCODE); p = (char*) KBASE + k; for (int c = 0; c < NCPU; c++) { // Fill slab allocators strncpy(slabmem[slab_stack][c].name, " kstack", MAXNAME); slabmem[slab_stack][c].size = KSTACKSIZE; slabmem[slab_stack][c].ninit = CPUKSTACKS; strncpy(slabmem[slab_perf][c].name, " kperf", MAXNAME); slabmem[slab_perf][c].size = PERFSIZE; slabmem[slab_perf][c].ninit = 1; strncpy(slabmem[slab_kshared][c].name, " kshared", MAXNAME); slabmem[slab_kshared][c].size = KSHAREDSIZE; slabmem[slab_kshared][c].ninit = CPUKSTACKS; strncpy(slabmem[slab_wq][c].name, " wq", MAXNAME); slabmem[slab_wq][c].size = PGROUNDUP(wq_size()); slabmem[slab_wq][c].ninit = NCPU; strncpy(slabmem[slab_userwq][c].name, " uwq", MAXNAME); slabmem[slab_userwq][c].size = USERWQSIZE; slabmem[slab_userwq][c].ninit = CPUKSTACKS; for (int i = 0; i < slab_type_max; i++) { slabmem[i][c].name[0] = (char) c + '0'; slabinit(&slabmem[i][c], &p, &k); } // The rest goes to the page allocator for (; k != n; k += PGSIZE, p = (char*) memnext(p, PGSIZE)) { if (p == (void *)-1) panic("initkalloc: e820next"); kfree_pool(&kmems[c], p); } k = 0; } kminit(); kinited = 1; } void kfree(void *v) { verifyfree((char*) v, mykmem()->size); kfree_pool(mykmem(), (char*) v); } void ksfree(int slab, void *v) { kfree_pool(slabmem[slab], (char*) v); } void verifyfree(char *ptr, u64 nbytes) { #if VERIFYFREE char *p = ptr; char *e = p + nbytes; for (; p < e; p++) { // Search for pointers in the ptr region u64 x = *(uptr *)p; if ((KBASE < x && x < KBASE+(128ull<<30)) || (KCODE < x)) { struct klockstat *kls = (struct klockstat *) x; if (kls->magic == LOCKSTAT_MAGIC) panic("LOCKSTAT_MAGIC %p(%lu):%p->%p", ptr, nbytes, p, kls); } } #endif } <|endoftext|>
<commit_before>#include "angel_wings.h" void Dart_WingsSocket_getPort(Dart_NativeArguments arguments) { // TODO: Actually do something. } void Dart_WingsSocket_write(Dart_NativeArguments arguments) { // TODO: Actually do something. } void Dart_WingsSocket_closeDescriptor(Dart_NativeArguments arguments) { // TODO: Actually do something. } void Dart_WingsSocket_close(Dart_NativeArguments arguments) { // TODO: Actually do something. }<commit_msg>Add getPort<commit_after>#include "angel_wings.h" #include "wings_socket.h" using namespace wings; void Dart_WingsSocket_getPort(Dart_NativeArguments arguments) { uint64_t ptr; Dart_Handle pointerHandle = Dart_GetNativeArgument(arguments, 0); HandleError(Dart_IntegerToUint64(pointerHandle, &ptr)); auto* socket = (WingsSocket*) ptr; auto outHandle = Dart_NewIntegerFromUint64(socket->getInfo().port); Dart_SetReturnValue(arguments, outHandle); } void Dart_WingsSocket_write(Dart_NativeArguments arguments) { // TODO: Actually do something. } void Dart_WingsSocket_closeDescriptor(Dart_NativeArguments arguments) { // TODO: Actually do something. } void Dart_WingsSocket_close(Dart_NativeArguments arguments) { // TODO: Actually do something. }<|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #ifndef DBN_DBN_HPP #define DBN_DBN_HPP #include <tuple> #include "rbm.hpp" #include "vector.hpp" template< bool B, class T = void > using enable_if_t = typename std::enable_if<B, T>::type; namespace dbn { template<typename Input, typename Target, typename V> struct gradient_context { size_t max_iterations; size_t epoch; batch<Input> inputs; batch<Target> targets; size_t start_layer; std::vector<std::vector<V>>& probs; gradient_context(batch<Input> i, std::vector<std::vector<V>>& p, size_t e) : max_iterations(3), epoch(e), inputs(i), start_layer(0), probs(p) { //Nothing else to init } }; template<typename... Layers> struct dbn { private: typedef std::tuple<rbm<Layers>...> tuple_type; tuple_type tuples; template <std::size_t N> using rbm_type = typename std::tuple_element<N, tuple_type>::type; static constexpr const std::size_t layers = sizeof...(Layers); public: template<std::size_t N> auto layer() -> typename std::add_lvalue_reference<rbm_type<N>>::type { return std::get<N>(tuples); } template<std::size_t N> constexpr auto layer() const -> typename std::add_lvalue_reference<typename std::add_const<rbm_type<N>>::type>::type { return std::get<N>(tuples); } template<std::size_t N> constexpr std::size_t num_visible() const { return rbm_type<N>::num_visible; } template<std::size_t N> constexpr std::size_t num_hidden() const { return rbm_type<N>::num_hidden; } template<std::size_t I, typename TrainingItems, typename LabelItems> inline enable_if_t<(I == layers - 1), void> train_rbm_layers(TrainingItems& training_data, std::size_t max_epochs, const LabelItems&, std::size_t){ std::cout << "Train layer " << I << std::endl; std::get<I>(tuples).train(training_data, max_epochs); } template<std::size_t I, typename TrainingItems, typename LabelItems> inline enable_if_t<(I < layers - 1), void> train_rbm_layers(TrainingItems& training_data, std::size_t max_epochs, const LabelItems& training_labels = {}, std::size_t labels = 0){ std::cout << "Train layer " << I << std::endl; auto& rbm = layer<I>(); rbm.train(training_data, max_epochs); auto append_labels = I + 1 == layers - 1 && !training_labels.empty(); std::vector<vector<double>> next; next.reserve(training_data.size()); for(auto& training_item : training_data){ vector<double> next_item(num_hidden<I>() + (append_labels ? labels : 0)); rbm.activate_hidden(next_item, training_item); next.emplace_back(std::move(next_item)); } //If the next layers is the last layer if(append_labels){ for(size_t i = 0; i < training_labels.size(); ++i){ auto label = training_labels[i]; for(size_t l = 0; l < labels; ++l){ if(label == l){ next[i][num_hidden<I>() + l] = 1; } else { next[i][num_hidden<I>() + l] = 0; } } } } train_rbm_layers<I + 1>(next, max_epochs, training_labels, labels); } template<typename TrainingItem> void pretrain(std::vector<TrainingItem>& training_data, std::size_t max_epochs){ train_rbm_layers<0, decltype(training_data), std::vector<uint8_t>>(training_data, max_epochs); } template<typename TrainingItem, typename Label> void pretrain_with_labels(std::vector<TrainingItem>& training_data, const std::vector<Label>& training_labels, std::size_t labels, std::size_t max_epochs){ dbn_assert(training_data.size() == training_labels.size(), "There must be the same number of values than labels"); dbn_assert(num_visible<layers - 1>() == num_hidden<layers - 2>() + labels, "There is no room for the labels units"); train_rbm_layers<0>(training_data, max_epochs, training_labels, labels); } template<std::size_t I, typename TrainingItem, typename Output> inline enable_if_t<(I == layers - 1), void> activate_layers(const TrainingItem& input, size_t, Output& output){ auto& rbm = layer<I>(); static vector<double> h1(num_hidden<I>()); static vector<double> hs(num_hidden<I>()); rbm.activate_hidden(h1, input); rbm.activate_visible(rbm_type<I>::bernoulli(h1, hs), output); } template<std::size_t I, typename TrainingItem, typename Output> inline enable_if_t<(I < layers - 1), void> activate_layers(const TrainingItem& input, std::size_t labels, Output& output){ auto& rbm = layer<I>(); static vector<double> next(num_visible<I+1>()); rbm.activate_hidden(next, input); //If the next layers is the last layer if(I + 1 == layers - 1){ for(size_t l = 0; l < labels; ++l){ next[num_hidden<I>() + l] = 0.1; } } activate_layers<I + 1>(next, labels, output); } template<typename TrainingItem> size_t predict(TrainingItem& item, std::size_t labels){ dbn_assert(num_visible<layers - 1>() == num_hidden<layers - 2>() + labels, "There is no room for the labels units"); static vector<double> output(num_visible<layers - 1>()); activate_layers<0>(item, labels, output); size_t label = 0; double max = 0; for(size_t l = 0; l < labels; ++l){ auto value = output[num_visible<layers - 1>() - labels + l]; if(value > max){ max = value; label = l; } } return label; } template<std::size_t I, typename TrainingItem, typename Output> inline enable_if_t<(I == layers - 1), void> deep_activate_layers(const TrainingItem& input, size_t, Output& output, std::size_t sampling){ auto& rbm = layer<I>(); static vector<double> v1(num_visible<I>()); static vector<double> v2(num_visible<I>()); for(size_t i = 0; i < input.size(); ++i){ v1(i) = input[i]; } static vector<double> h1(num_hidden<I>()); static vector<double> h2(num_hidden<I>()); static vector<double> hs(num_hidden<I>()); for(size_t i = 0; i< sampling; ++i){ rbm.activate_hidden(h1, v1); rbm.activate_visible(rbm_type<I>::bernoulli(h1, hs), v1); //TODO Perhaps we should apply a new bernoulli on v1 ? } rbm.activate_hidden(h1, input); rbm.activate_visible(rbm_type<I>::bernoulli(h1, hs), output); } template<std::size_t I, typename TrainingItem, typename Output> inline enable_if_t<(I < layers - 1), void> deep_activate_layers(const TrainingItem& input, std::size_t labels, Output& output, std::size_t sampling){ auto& rbm = layer<I>(); static vector<double> next(num_visible<I+1>()); rbm.activate_hidden(next, input); //If the next layers is the last layer if(I + 1 == layers - 1){ for(size_t l = 0; l < labels; ++l){ next[num_hidden<I>() + l] = 0.1; } } deep_activate_layers<I + 1>(next, labels, output, sampling); } template<typename TrainingItem> size_t deep_predict(TrainingItem& item, std::size_t labels, std::size_t sampling){ dbn_assert(num_visible<layers - 1>() == num_hidden<layers - 2>() + labels, "There is no room for the labels units"); vector<double> output(num_visible<layers - 1>()); deep_activate_layers<0>(item, labels, output, sampling); size_t label = 0; double max = 0; for(size_t l = 0; l < labels; ++l){ auto value = output[num_visible<layers - 1>() - labels + l]; if(value > max){ max = value; label = l; } } return label; } }; } //end of namespace dbn #endif <commit_msg>Fine-tuning preparation again<commit_after>//======================================================================= // Copyright (c) 2014 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #ifndef DBN_DBN_HPP #define DBN_DBN_HPP #include <tuple> #include "rbm.hpp" #include "vector.hpp" template< bool B, class T = void > using enable_if_t = typename std::enable_if<B, T>::type; namespace dbn { template<typename Input, typename Target> struct gradient_context { size_t max_iterations; size_t epoch; batch<Input> inputs; batch<Target> targets; size_t start_layer; gradient_context(batch<Input> i, batch<Target> t, size_t e) : max_iterations(3), epoch(e), inputs(i), targets(t), start_layer(0) { //Nothing else to init } }; template<typename... Layers> struct dbn { private: typedef std::tuple<rbm<Layers>...> tuple_type; tuple_type tuples; template <std::size_t N> using rbm_type = typename std::tuple_element<N, tuple_type>::type; static constexpr const std::size_t layers = sizeof...(Layers); typedef typename rbm_type<0>::weight weight; public: template<std::size_t N> auto layer() -> typename std::add_lvalue_reference<rbm_type<N>>::type { return std::get<N>(tuples); } template<std::size_t N> constexpr auto layer() const -> typename std::add_lvalue_reference<typename std::add_const<rbm_type<N>>::type>::type { return std::get<N>(tuples); } template<std::size_t N> constexpr std::size_t num_visible() const { return rbm_type<N>::num_visible; } template<std::size_t N> constexpr std::size_t num_hidden() const { return rbm_type<N>::num_hidden; } template<std::size_t I, typename TrainingItems, typename LabelItems> inline enable_if_t<(I == layers - 1), void> train_rbm_layers(TrainingItems& training_data, std::size_t max_epochs, const LabelItems&, std::size_t){ std::cout << "Train layer " << I << std::endl; std::get<I>(tuples).train(training_data, max_epochs); } template<std::size_t I, typename TrainingItems, typename LabelItems> inline enable_if_t<(I < layers - 1), void> train_rbm_layers(TrainingItems& training_data, std::size_t max_epochs, const LabelItems& training_labels = {}, std::size_t labels = 0){ std::cout << "Train layer " << I << std::endl; auto& rbm = layer<I>(); rbm.train(training_data, max_epochs); auto append_labels = I + 1 == layers - 1 && !training_labels.empty(); std::vector<vector<double>> next; next.reserve(training_data.size()); for(auto& training_item : training_data){ vector<double> next_item(num_hidden<I>() + (append_labels ? labels : 0)); rbm.activate_hidden(next_item, training_item); next.emplace_back(std::move(next_item)); } //If the next layers is the last layer if(append_labels){ for(size_t i = 0; i < training_labels.size(); ++i){ auto label = training_labels[i]; for(size_t l = 0; l < labels; ++l){ if(label == l){ next[i][num_hidden<I>() + l] = 1; } else { next[i][num_hidden<I>() + l] = 0; } } } } train_rbm_layers<I + 1>(next, max_epochs, training_labels, labels); } template<typename TrainingItem> void pretrain(std::vector<TrainingItem>& training_data, std::size_t max_epochs){ train_rbm_layers<0, decltype(training_data), std::vector<uint8_t>>(training_data, max_epochs); } template<typename TrainingItem, typename Label> void pretrain_with_labels(std::vector<TrainingItem>& training_data, const std::vector<Label>& training_labels, std::size_t labels, std::size_t max_epochs){ dbn_assert(training_data.size() == training_labels.size(), "There must be the same number of values than labels"); dbn_assert(num_visible<layers - 1>() == num_hidden<layers - 2>() + labels, "There is no room for the labels units"); train_rbm_layers<0>(training_data, max_epochs, training_labels, labels); } template<std::size_t I, typename TrainingItem, typename Output> inline enable_if_t<(I == layers - 1), void> activate_layers(const TrainingItem& input, size_t, Output& output){ auto& rbm = layer<I>(); static vector<double> h1(num_hidden<I>()); static vector<double> hs(num_hidden<I>()); rbm.activate_hidden(h1, input); rbm.activate_visible(rbm_type<I>::bernoulli(h1, hs), output); } template<std::size_t I, typename TrainingItem, typename Output> inline enable_if_t<(I < layers - 1), void> activate_layers(const TrainingItem& input, std::size_t labels, Output& output){ auto& rbm = layer<I>(); static vector<double> next(num_visible<I+1>()); rbm.activate_hidden(next, input); //If the next layers is the last layer if(I + 1 == layers - 1){ for(size_t l = 0; l < labels; ++l){ next[num_hidden<I>() + l] = 0.1; } } activate_layers<I + 1>(next, labels, output); } template<typename TrainingItem> size_t predict(TrainingItem& item, std::size_t labels){ dbn_assert(num_visible<layers - 1>() == num_hidden<layers - 2>() + labels, "There is no room for the labels units"); static vector<double> output(num_visible<layers - 1>()); activate_layers<0>(item, labels, output); size_t label = 0; double max = 0; for(size_t l = 0; l < labels; ++l){ auto value = output[num_visible<layers - 1>() - labels + l]; if(value > max){ max = value; label = l; } } return label; } template<std::size_t I, typename TrainingItem, typename Output> inline enable_if_t<(I == layers - 1), void> deep_activate_layers(const TrainingItem& input, size_t, Output& output, std::size_t sampling){ auto& rbm = layer<I>(); static vector<double> v1(num_visible<I>()); static vector<double> v2(num_visible<I>()); for(size_t i = 0; i < input.size(); ++i){ v1(i) = input[i]; } static vector<double> h1(num_hidden<I>()); static vector<double> h2(num_hidden<I>()); static vector<double> hs(num_hidden<I>()); for(size_t i = 0; i< sampling; ++i){ rbm.activate_hidden(h1, v1); rbm.activate_visible(rbm_type<I>::bernoulli(h1, hs), v1); //TODO Perhaps we should apply a new bernoulli on v1 ? } rbm.activate_hidden(h1, input); rbm.activate_visible(rbm_type<I>::bernoulli(h1, hs), output); } template<std::size_t I, typename TrainingItem, typename Output> inline enable_if_t<(I < layers - 1), void> deep_activate_layers(const TrainingItem& input, std::size_t labels, Output& output, std::size_t sampling){ auto& rbm = layer<I>(); static vector<double> next(num_visible<I+1>()); rbm.activate_hidden(next, input); //If the next layers is the last layer if(I + 1 == layers - 1){ for(size_t l = 0; l < labels; ++l){ next[num_hidden<I>() + l] = 0.1; } } deep_activate_layers<I + 1>(next, labels, output, sampling); } template<typename TrainingItem> size_t deep_predict(TrainingItem& item, std::size_t labels, std::size_t sampling){ dbn_assert(num_visible<layers - 1>() == num_hidden<layers - 2>() + labels, "There is no room for the labels units"); vector<double> output(num_visible<layers - 1>()); deep_activate_layers<0>(item, labels, output, sampling); size_t label = 0; double max = 0; for(size_t l = 0; l < labels; ++l){ auto value = output[num_visible<layers - 1>() - labels + l]; if(value > max){ max = value; label = l; } } return label; } /* Gradient */ template<typename Input, typename Target, typename V1, typename V2> size_t gradient(gradient_context<Input, Target>& context, V1& weights, V2& weights_incs, weight& cost){ } template<typename Input, typename Target> size_t minimize(gradient_context<Input, Target>& context){ constexpr const double INT = 0.1; constexpr const double EXT = 3.0; constexpr const double SIG = 0.1; constexpr const double RHO = SIG / 2.0; constexpr const double RATIO = 10.0; auto max_iteration = context.max_iteration; double cost = 0.0; } template<typename TrainingItem, typename Label> void fine_tune(std::vector<TrainingItem>& training_data, std::vector<Label>& labels, size_t epochs, size_t batch_size = rbm_type<0>::BatchSize){ //TODO Put probs in each RBM auto batches = training_data.size() / batch_size; batches = 100; for(size_t epoch = 0; epoch < epochs; ++epoch){ for(size_t i = 0; i < batches; ++i){ auto start = i * batch_size; auto end = (i+1) * batch_size; gradient_context<TrainingItem, Label> context( batch<TrainingItem>(training_data.begin() + start, training_data.begin() + end), batch<Label>(labels.egin() + start, labels.begin() + end), epoch); minimize(context); } } } }; } //end of namespace dbn #endif <|endoftext|>
<commit_before>/** \mainpage # Overview of GAL This library consists of four different array classes: ``` | Owns Memory Non Owning Pointer --------|--------------------------------------- Static | gal::sarray gal::sarray_ptr Dynamic | gal::darray gal::darray_ptr ``` The size of a static array is known at compile time. The size of a dynamic array is known at run time. The arrays that own memory are containers, similar to those in the standard template library [STL](http://www.cplusplus.com/reference/stl/). The non owning arrays just point to an array owned by someone else. They can point to any array, e.g. an array from another library. All four array types in GAL support multiple dimensions. Furthermore, they all assume contiguous memory. There is no support for strided arrays. GAL provides array interfaces that are consistent across these four use cases, while also being consistent with the arrays in the standard library. # Other Array Libraries The standard template library [STL](http://www.cplusplus.com/reference/stl/) has some array containers: ``` | Owns Memory Non Owning Pointer --------|--------------------------------------- Static | std::array - Dynamic | std::vector - | std::valarray ``` STL has no class for multi-dimensional arrays or any class for representing non owning pointers to general arrays. The Guidelines Support Library [GSL](https://github.com/Microsoft/GSL) has a class that represents a non owning pointer to a single-dimensional dynamic array: ``` | Owns Memory Non Owning Pointer --------|--------------------------------------- Static | - - Dynamic | - gsl::span ``` [The Boost Multidimensional Array Library] (http://www.boost.org/doc/libs/1_60_0/libs/multi_array/doc/index.html) has support for multi-dimensional dynamic arrays: ``` | Owns Memory Non Owning Pointer --------|------------------------------------------------- Static | - - Dynamic | boost::multi_array boost::multi_array_ref | boost::const_multi_array_ref ``` GAL attempts to fill in the gaps between these libraries and provide a consistent interface. # Common interface for arrays in GAL The following holds for all of the arrays in GAL: - The elements are stored contiguously in memory. Strided arrays are not supported. - The element with index `i` of array `a` is retrieved as `a[i]`. - The indexing of the elements starts at `0`. - The number of elements is retrieved by calling the member function `size()`. - The size of a static array is known at compile time. - The size of a dynamic array is known at run time. - The elements might be structured over multiple dimensions. The number of dimensions is retrieved by calling the member function `rank()`. The rank is known at compile time for all arrays. - The array has an extent in each dimension. The size of the array is the product of all its extents. - The extents of a static array is known at compile time. - The extent of a dynamic array is known at run time. - The extent of dimension `n` is retrieved by calling the templated member function `extent<n>()`. Alternatively by calling any of the non-templated member functions: `extent0()`, `extent1()`, `extent2()`... - The member function `extents` returns all extents of the array as an `std::array<size_t, rank()>`. # Example ``` // Function that works on any of the four array classes in GAL: template<typename array_2d> void fill_array_2d(array_2d& array) { // Check the rank of the array, i.e. the number of dimensions: assert(array.rank() == 2); // Get the value_type of of an array similar to standard containers: using value_type = typename array_2d::value_type; for (size_t i = 0; i < array.size(); ++i) { // Access array data with linear index, using operator[]: array[i] = static_cast<value_type>(i); } // Use array in range based for loop: for (auto& element : array) { element += 10; } } // Function that works on any of the four array classes in GAL: template<typename array_2d> void print_array_2d(const array_2d& array) { // Check the rank of the array, i.e. the number of dimensions: assert(array.rank() == 2); using namespace std; // Loop over the extent of each dimension: for (size_t y = 0; y < extent1(array); ++y) { for (size_t x = 0; x < extent0(array); ++x) { // Access array data with multi-dimensional index, using operator() cout << array(x, y) << " "; } cout << endl; } cout << endl; } int main() { using namespace gal; using namespace std; // Create array containers that own their data: auto static_array_2d = sarray<float, 3, 3>(); auto dynamic_array_2d = darray<int, 2>(4, 4); // Create arrays that points to data owned by someone else: auto static_array_ptr_2d = sarray_ptr<float, 3, 2>(static_array_2d.data()); auto dynamic_array_ptr_2d = darray_ptr<int, 2>(4, 2, dynamic_array_2d.data()); fill_array_2d(static_array_2d); fill_array_2d(dynamic_array_2d); cout << "Data of owning arrays: " << endl; print_array_2d(static_array_2d); print_array_2d(dynamic_array_2d); cout << "Data pointed to by non-owning arrays: " << endl; print_array_2d(static_array_ptr_2d); print_array_2d(dynamic_array_ptr_2d); } ``` Prints: ``` Data of owning arrays: 10 11 12 13 14 15 16 17 18 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Data pointed to by non-owning arrays: 10 11 12 13 14 15 10 11 12 13 14 15 16 17 ``` Please see the page for each class for more exampels and details: gal::sarray, gal::sarray_ptr, gal::darray, gal::darray_ptr. */ #pragma once #include "sarray.hpp" #include "darray.hpp" #include "sarray_ptr.hpp" #include "darray_ptr.hpp" #include "vector_math.hpp" #include "geometry.hpp" <commit_msg>Don't include vector_math and geometry.<commit_after>/** \mainpage # Overview of GAL This library consists of four different array classes: ``` | Owns Memory Non Owning Pointer --------|--------------------------------------- Static | gal::sarray gal::sarray_ptr Dynamic | gal::darray gal::darray_ptr ``` The size of a static array is known at compile time. The size of a dynamic array is known at run time. The arrays that own memory are containers, similar to those in the standard template library [STL](http://www.cplusplus.com/reference/stl/). The non owning arrays just point to an array owned by someone else. They can point to any array, e.g. an array from another library. All four array types in GAL support multiple dimensions. Furthermore, they all assume contiguous memory. There is no support for strided arrays. GAL provides array interfaces that are consistent across these four use cases, while also being consistent with the arrays in the standard library. # Other Array Libraries The standard template library [STL](http://www.cplusplus.com/reference/stl/) has some array containers: ``` | Owns Memory Non Owning Pointer --------|--------------------------------------- Static | std::array - Dynamic | std::vector - | std::valarray ``` STL has no class for multi-dimensional arrays or any class for representing non owning pointers to general arrays. The Guidelines Support Library [GSL](https://github.com/Microsoft/GSL) has a class that represents a non owning pointer to a single-dimensional dynamic array: ``` | Owns Memory Non Owning Pointer --------|--------------------------------------- Static | - - Dynamic | - gsl::span ``` [The Boost Multidimensional Array Library] (http://www.boost.org/doc/libs/1_60_0/libs/multi_array/doc/index.html) has support for multi-dimensional dynamic arrays: ``` | Owns Memory Non Owning Pointer --------|------------------------------------------------- Static | - - Dynamic | boost::multi_array boost::multi_array_ref | boost::const_multi_array_ref ``` GAL attempts to fill in the gaps between these libraries and provide a consistent interface. # Common interface for arrays in GAL The following holds for all of the arrays in GAL: - The elements are stored contiguously in memory. Strided arrays are not supported. - The element with index `i` of array `a` is retrieved as `a[i]`. - The indexing of the elements starts at `0`. - The number of elements is retrieved by calling the member function `size()`. - The size of a static array is known at compile time. - The size of a dynamic array is known at run time. - The elements might be structured over multiple dimensions. The number of dimensions is retrieved by calling the member function `rank()`. The rank is known at compile time for all arrays. - The array has an extent in each dimension. The size of the array is the product of all its extents. - The extents of a static array is known at compile time. - The extent of a dynamic array is known at run time. - The extent of dimension `n` is retrieved by calling the templated member function `extent<n>()`. Alternatively by calling any of the non-templated member functions: `extent0()`, `extent1()`, `extent2()`... - The member function `extents` returns all extents of the array as an `std::array<size_t, rank()>`. # Example ``` // Function that works on any of the four array classes in GAL: template<typename array_2d> void fill_array_2d(array_2d& array) { // Check the rank of the array, i.e. the number of dimensions: assert(array.rank() == 2); // Get the value_type of of an array similar to standard containers: using value_type = typename array_2d::value_type; for (size_t i = 0; i < array.size(); ++i) { // Access array data with linear index, using operator[]: array[i] = static_cast<value_type>(i); } // Use array in range based for loop: for (auto& element : array) { element += 10; } } // Function that works on any of the four array classes in GAL: template<typename array_2d> void print_array_2d(const array_2d& array) { // Check the rank of the array, i.e. the number of dimensions: assert(array.rank() == 2); using namespace std; // Loop over the extent of each dimension: for (size_t y = 0; y < extent1(array); ++y) { for (size_t x = 0; x < extent0(array); ++x) { // Access array data with multi-dimensional index, using operator() cout << array(x, y) << " "; } cout << endl; } cout << endl; } int main() { using namespace gal; using namespace std; // Create array containers that own their data: auto static_array_2d = sarray<float, 3, 3>(); auto dynamic_array_2d = darray<int, 2>(4, 4); // Create arrays that points to data owned by someone else: auto static_array_ptr_2d = sarray_ptr<float, 3, 2>(static_array_2d.data()); auto dynamic_array_ptr_2d = darray_ptr<int, 2>(4, 2, dynamic_array_2d.data()); fill_array_2d(static_array_2d); fill_array_2d(dynamic_array_2d); cout << "Data of owning arrays: " << endl; print_array_2d(static_array_2d); print_array_2d(dynamic_array_2d); cout << "Data pointed to by non-owning arrays: " << endl; print_array_2d(static_array_ptr_2d); print_array_2d(dynamic_array_ptr_2d); } ``` Prints: ``` Data of owning arrays: 10 11 12 13 14 15 16 17 18 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Data pointed to by non-owning arrays: 10 11 12 13 14 15 10 11 12 13 14 15 16 17 ``` Please see the page for each class for more exampels and details: gal::sarray, gal::sarray_ptr, gal::darray, gal::darray_ptr. */ #pragma once #include "sarray.hpp" #include "darray.hpp" #include "sarray_ptr.hpp" #include "darray_ptr.hpp" <|endoftext|>
<commit_before>/*! \mainpage ecspp Index page * \section intro_sec Introduction * This will be the intro eventually probs * \section install_sec Installation * \subsection step1 Step 1: I'm a masochist and use Eclipse CDT * eff me right? * \subsection step2 Step 2: It's really not that bad * says no one on the internet * \subsection step3 Step 3: Coming out * okay I'm actually enjoying it and am not to thrilled about visual studio D: */ /*! \file ecs.hpp * */ #ifndef ECS_HPP_ #define ECS_HPP_ #include <vector> #include <queue> // available entity ids and idices #include <typeindex> // to store component types #include <bitset> // component bitmasking #include <functional> //make_shared #include <memory> //shared_ptr for CMaps #include <cassert> #include <algorithm>//find_if for entities #include <cassert> #include <unordered_map> //Comonent Mask map #include <initializer_list> /*!\namespace ecs * \brief header only entity component system implementation * * Entities are a combination of a uuid and their component mask which is std::bitset. A component's * "bit" is determined by its index in the component type vector. Bit '0' is the alive flag in the * ComponentMask. * * Custom container objects derived from BaseContainer are used to hold components. * At the moment there is only a vector implementation. * Components are expected to hold most/all of what a system will need to update. * * The 'ComponentContainers' object holds a map of BaseContainer shared_ptrs. At the moment, systems need * to cast the ptr to the correct type and container using the 'ComponentContainerTypeCast' function where * 'ContainerType' is the implemented container such as vector. For now, the only type of container is * ComponentContainer so there is only one cast function (more may be added later): * ComponentVectorCast. * * Systems need to be derived from BaseSystem and define update, init, and destroy functions (messaging * functions may be added later). The 'Systems' object will contain all of the systems in a map where * the key is the system's given name and the value is the object itself. * */ namespace ecs{ //max expected number of entities and components to pass into container.reserve() const int maxEntities = 1000; // amount of entities to reserve for vector<Entity> const int maxComponentTypes = 64; typedef unsigned int Entity; typedef std::bitset<maxComponentTypes> ComponentMask; typedef std::pair<Entity, ComponentMask> EntityData; /*!\class CompareFirst * \brief unary predicate returns true if pair.first equals the passed in value. * * Meant to be used with find_if and a vector of pairs, for more info see: * http://stackoverflow.com/questions/12008059/find-if-and-stdpair-but-just-one-element */ template <typename K, typename T> struct CompareFirst { CompareFirst(K key) : m_key(key) {} bool operator()(const std::pair<K,T>& element) const { return m_key == element.first; } private: K m_key; }; /*!\class CompareSecond * \brief unary predicate returns true if pair.second equals the passed in value. * * Meant to be used with find_if and a vector of pairs, for more info see: * http://stackoverflow.com/questions/12008059/find-if-and-stdpair-but-just-one-element */ template <typename K, typename T> struct CompareSecond { CompareSecond(T t) : m_t(t) {} bool operator()(const std::pair<K,T>& element) const { return m_t == element.second; } private: T m_t; }; /****************************** COMPONENT ******************************************************/ /*!\class BaseContainer * Base class for component container implementations */ class BaseContainer{ public: virtual ~BaseContainer(){}; virtual void add(Entity& entity) = 0; virtual void remove(Entity& entity) = 0; virtual void init(const int& maxComponents) = 0; }; /*!\class ComponentVector * generic component vector container */ template <class Component> class ComponentVector : public BaseContainer { public: ComponentVector(){} ~ComponentVector(){} /*!\fn add * \brief add passed in entity to vector with default component */ void add(Entity& entity){ Component component; components.emplace_back(entity, component); } //! add overload that takes a reference of a component void add(Entity& entity, Component& component){ components.emplace_back(std::make_pair(entity,component)); } /*!\fn remove * removes the entity and its component from the vector */ void remove(Entity& entity){ if(!components.empty()){ auto it = std::find_if(components.begin(), components.end(),CompareFirst<Entity,Component>(entity)); std::swap(components[it - components.begin()], components.back()); components.pop_back(); } } /*!\fn get * returns the component associated with the passed in entity */ Component get(Entity& entity){ auto it = std::find_if(components.begin(), components.end(),CompareFirst<Entity,Component>(entity)); return it->second; } /*!\fn init * sets the capacity of the vector */ void init(const int& maxComponents){ components.reserve(maxComponents); } std::vector<std::pair<Entity, Component>> components; //TODO finish interface so logging can be done with components private };// ComponentVector /*!\fn ComponentVectorCast * \brief casts a BaseContainer shared_ptr to a ComponentVector of the template type */ template<class Component> std::shared_ptr<ComponentVector<Component>> ComponentVectorCast(std::shared_ptr<BaseContainer> basePtr){ return std::static_pointer_cast<ecs::ComponentVector<Component>>(basePtr); } /*!\class ComponentContainers * \brief holds pointers to all component containers by name * * A map of BaseContainer shared_ptrs is utilized so that there can be various implementations of component * containers. Containers are accessed by name and need to casted after calling the get(). See * ComponentVectorCast for an example of pointer cast. */ class ComponentContainers{ public: /*!\fn add * \brief makes a new container for the passed in type. */ template <class Component> void add(const std::string& name, Component& type){ for(auto const& it : types){ assert(it.first != name); } types[name] = bitCounter; ++bitCounter; auto cVecPtr = std::make_shared<ComponentVector<Component>>(); pointers[name] = cVecPtr; } /*!\fn get * returns void ptr to component data structure related to the passed in name */ std::shared_ptr< BaseContainer > get(const std::string& name){ return pointers[name]; } //! returns a ComponentMask representing the passed in names of types ComponentMask getBitMask(std::initializer_list<std::string> names){ ComponentMask CMask; for(auto it : names){ unsigned short int bit = types[it]; CMask.set(bit , true); } return CMask; } private: std::unordered_map<std::string, std::shared_ptr< BaseContainer> > pointers; std::unordered_map<std::string, unsigned short int> types; unsigned short int bitCounter = 1; //bit '0' is alive flag for entities }; /************************* SYSTEM *********************************************************/ /*!\class BaseSystem * \brief class that all systems should inherit from */ class BaseSystem{ public: virtual ~BaseSystem(){}; virtual void update() = 0; virtual void init() = 0; virtual void destroy() = 0; protected: std::unordered_map<std::string, std::shared_ptr< BaseContainer> > components; }; // BaseSystem Interface /**\class Systems * \brief registers systems by name and can call inherited functions from BaseSystem */ class Systems{ public: //! registers a system by name template<class T> void add(std::string const& name, std::shared_ptr<T> systemPtr){ for(auto const& it : pointers){ assert(it.first != name); } pointers[name] = std::static_pointer_cast<BaseSystem>(systemPtr); } //! calls init on all registered systmes void init(){ for(auto const& it : pointers){ it.second->init(); } } //! calls update on all registered systems void update(){ for(auto const& it : pointers){ it.second->update(); } } //! calls destroy on all registered systems void destroy(){ for(auto const& it : pointers){ it.second->destroy(); } pointers.clear(); } private: std::unordered_map<std::string, std::shared_ptr<BaseSystem>> pointers; }; // Systems class /******************************** ENTITY *****************************************************/ /*!\class Entities * \brief Contains all entities and has add, remove, create, and bitMasking functions */ class Entities{ public: Entities(ComponentContainers& compContainers){ compContainers = componentContainers; componentMasks.reserve(maxEntities); } /*!\fn create * */ Entity create(){ Entity entity; if(deletedEntities.empty()){ entity = entityCount; ++entityCount; } else{ entity = deletedEntities.front(); deletedEntities.pop(); } ComponentMask CMask; CMask.set(0, true);//!first bit in CMask is "alive" bit componentMasks[entity] = CMask; return entity; } Entity create(std::initializer_list<std::string>& components){ Entity e = create(); addEntity(e, components); return e; } /*!\fn remove * \brief sets the "alive" flag for the passed in entity to false. */ void remove(Entity& entity){ deletedEntities.push(entity); componentMasks[entity] = 0; } //! overload that takes variable amounts of entities void remove(std::initializer_list<Entity>& entities){ for(Entity e : entities){ deletedEntities.push(e); this->componentMasks[e] = 0; } } private: /*!\fn addEntity * \brief adds entity with a default ComponentMask */ void addEntity(Entity& entity){ if(deletedEntities.empty()){ entity = entityCount; ++entityCount; } else{ entity = deletedEntities.front(); deletedEntities.pop(); } ComponentMask CMask; CMask.set(0, true);//!first bit in CMask is "alive" bit componentMasks[entity] = CMask; } //! addEntity overload to take multiple components to mask entity with while adding void addEntity(Entity& entity, std::initializer_list<std::string>& components){ if(deletedEntities.empty()){ entity = entityCount; ++entityCount; } else{ entity = deletedEntities.front(); deletedEntities.pop(); } ComponentMask CMask; CMask.set(0, true);//!first bit in CMask is "alive" bit CMask | componentContainers.getBitMask(components); componentMasks[entity] = CMask; } /*!\fn maskEntity * \brief 'assigns' components to an entity by ORing its component mask with given components */ void maskEntity(Entity& entity, ComponentMask& CMask){ componentMasks[entity] | CMask; } //! maskEntity overload to take names of components void maskEntity(Entity& entity, std::initializer_list<std::string>& components){ componentMasks[entity] |componentContainers.getBitMask(components); } std::vector<ComponentMask> componentMasks; //! index = entity id. bit '0' = alive flag std::queue<Entity> deletedEntities; //! available indices to use in componentMasks vector Entity entityCount = 0; //! Max number of entity ids used so far ComponentContainers componentContainers; }; }// ecs namespace #endif /* ECS_HPP_ */ <commit_msg>Added start of an 'Engine' class<commit_after>/*! \mainpage ecspp Index page * \section intro_sec Introduction * This will be the intro eventually probs * \section install_sec Installation * \subsection step1 Step 1: I'm a masochist and use Eclipse CDT * eff me right? * \subsection step2 Step 2: It's really not that bad * says no one on the internet * \subsection step3 Step 3: Coming out * okay I'm actually enjoying it and am not to thrilled about visual studio D: */ /*! \file ecs.hpp * */ #ifndef ECS_HPP_ #define ECS_HPP_ #include <vector> #include <queue> // available entity ids and idices #include <typeindex> // to store component types #include <bitset> // component bitmasking #include <functional> //make_shared #include <memory> //shared_ptr for CMaps #include <cassert> #include <algorithm>//find_if for entities #include <cassert> #include <unordered_map> //Comonent Mask map #include <initializer_list> /*!\namespace ecs * \brief header only entity component system implementation * * Entities are a combination of a uuid and their component mask which is std::bitset. A component's * "bit" is determined by its index in the component type vector. Bit '0' is the alive flag in the * ComponentMask. * * Custom container objects derived from BaseContainer are used to hold components. * At the moment there is only a vector implementation. * Components are expected to hold most/all of what a system will need to update. * * The 'ComponentContainers' object holds a map of BaseContainer shared_ptrs. At the moment, systems need * to cast the ptr to the correct type and container using the 'ComponentContainerTypeCast' function where * 'ContainerType' is the implemented container such as vector. For now, the only type of container is * ComponentContainer so there is only one cast function (more may be added later): * ComponentVectorCast. * * Systems need to be derived from BaseSystem and define update, init, and destroy functions (messaging * functions may be added later). The 'Systems' object will contain all of the systems in a map where * the key is the system's given name and the value is the object itself. * */ namespace ecs{ //max expected number of entities and components to pass into container.reserve() const int maxEntities = 1000; // amount of entities to reserve for vector<Entity> const int maxComponentTypes = 64; typedef unsigned int Entity; typedef std::bitset<maxComponentTypes> ComponentMask; typedef std::pair<Entity, ComponentMask> EntityData; /*!\class CompareFirst * \brief unary predicate returns true if pair.first equals the passed in value. * * Meant to be used with find_if and a vector of pairs, for more info see: * http://stackoverflow.com/questions/12008059/find-if-and-stdpair-but-just-one-element */ template <typename K, typename T> struct CompareFirst { CompareFirst(K key) : m_key(key) {} bool operator()(const std::pair<K,T>& element) const { return m_key == element.first; } private: K m_key; }; /*!\class CompareSecond * \brief unary predicate returns true if pair.second equals the passed in value. * * Meant to be used with find_if and a vector of pairs, for more info see: * http://stackoverflow.com/questions/12008059/find-if-and-stdpair-but-just-one-element */ template <typename K, typename T> struct CompareSecond { CompareSecond(T t) : m_t(t) {} bool operator()(const std::pair<K,T>& element) const { return m_t == element.second; } private: T m_t; }; /****************************** COMPONENT ******************************************************/ /*!\class BaseContainer * Base class for component container implementations */ class BaseContainer{ public: virtual ~BaseContainer(){}; virtual void add(Entity& entity) = 0; virtual void remove(Entity& entity) = 0; virtual void init(const int& maxComponents) = 0; }; /*!\class ComponentVector * generic component vector container */ template <class Component> class ComponentVector : public BaseContainer { public: ComponentVector(){} ~ComponentVector(){} /*!\fn add * \brief add passed in entity to vector with default component */ void add(Entity& entity){ Component component; components.emplace_back(entity, component); } //! add overload that takes a reference of a component void add(Entity& entity, Component& component){ components.emplace_back(std::make_pair(entity,component)); } /*!\fn remove * removes the entity and its component from the vector */ void remove(Entity& entity){ if(!components.empty()){ auto it = std::find_if(components.begin(), components.end(),CompareFirst<Entity,Component>(entity)); std::swap(components[it - components.begin()], components.back()); components.pop_back(); } } /*!\fn get * returns the component associated with the passed in entity */ Component get(Entity& entity){ auto it = std::find_if(components.begin(), components.end(),CompareFirst<Entity,Component>(entity)); return it->second; } /*!\fn init * sets the capacity of the vector */ void init(const int& maxComponents){ components.reserve(maxComponents); } std::vector<std::pair<Entity, Component>> components; //TODO finish interface so logging can be done with components private };// ComponentVector /*!\fn ComponentVectorCast * \brief casts a BaseContainer shared_ptr to a ComponentVector of the template type */ template<class Component> std::shared_ptr<ComponentVector<Component>> ComponentVectorCast(std::shared_ptr<BaseContainer> basePtr){ return std::static_pointer_cast<ecs::ComponentVector<Component>>(basePtr); } /*!\class ComponentContainers * \brief holds pointers to all component containers by name * * A map of BaseContainer shared_ptrs is utilized so that there can be various implementations of component * containers. Containers are accessed by name and need to casted after calling the get(). See * ComponentVectorCast for an example of pointer cast. */ class ComponentContainers{ public: /*!\fn add * \brief makes a new container for the passed in type. */ template <class Component> void add(const std::string& name, Component& type){ for(auto const& it : types){ assert(it.first != name); } types[name] = bitCounter; ++bitCounter; auto cVecPtr = std::make_shared<ComponentVector<Component>>(); pointers[name] = cVecPtr; } /*!\fn get * returns void ptr to component data structure related to the passed in name */ std::shared_ptr< BaseContainer > get(const std::string& name){ return pointers[name]; } //! returns a ComponentMask representing the passed in names of types ComponentMask getBitMask(std::initializer_list<std::string> names){ ComponentMask CMask; for(auto it : names){ unsigned short int bit = types[it]; CMask.set(bit , true); } return CMask; } private: std::unordered_map<std::string, std::shared_ptr< BaseContainer> > pointers; std::unordered_map<std::string, unsigned short int> types; unsigned short int bitCounter = 1; //bit '0' is alive flag for entities }; /************************* SYSTEM *********************************************************/ /*!\class BaseSystem * \brief class that all systems should inherit from */ class BaseSystem{ public: virtual ~BaseSystem(){}; virtual void update() = 0; virtual void init() = 0; virtual void destroy() = 0; protected: std::unordered_map<std::string, std::shared_ptr< BaseContainer> > components; }; // BaseSystem Interface /**\class Systems * \brief registers systems by name and can call inherited functions from BaseSystem */ class Systems{ public: //! registers a system by name template<class T> void add(std::string const& name, std::shared_ptr<T> systemPtr){ for(auto const& it : pointers){ assert(it.first != name); } pointers[name] = std::static_pointer_cast<BaseSystem>(systemPtr); } //! calls init on all registered systmes void init(){ for(auto const& it : pointers){ it.second->init(); } } //! calls update on all registered systems void update(){ for(auto const& it : pointers){ it.second->update(); } } //! calls destroy on all registered systems void destroy(){ for(auto const& it : pointers){ it.second->destroy(); } pointers.clear(); } private: std::unordered_map<std::string, std::shared_ptr<BaseSystem>> pointers; }; // Systems class /******************************** ENTITY *****************************************************/ /*!\class Entities * \brief Contains all entities and has add, remove, create, and bitMasking functions */ class Entities{ public: Entities(ComponentContainers& compContainers){ compContainers = componentContainers; componentMasks.reserve(maxEntities); } /*!\fn create * */ Entity create(){ Entity entity; if(deletedEntities.empty()){ entity = entityCount; ++entityCount; } else{ entity = deletedEntities.front(); deletedEntities.pop(); } ComponentMask CMask; CMask.set(0, true);//!first bit in CMask is "alive" bit componentMasks[entity] = CMask; return entity; } Entity create(std::initializer_list<std::string> const& components){ Entity e = create(); addEntity(e, components); return e; } /*!\fn remove * \brief sets the "alive" flag for the passed in entity to false. */ void remove(Entity const& entity){ deletedEntities.push(entity); componentMasks[entity] = 0; } //! overload that takes variable amounts of entities void remove(std::initializer_list<Entity>& entities){ for(Entity e : entities){ deletedEntities.push(e); this->componentMasks[e] = 0; } } private: /*!\fn addEntity * \brief adds entity with a default ComponentMask */ void addEntity(Entity& entity){ if(deletedEntities.empty()){ entity = entityCount; ++entityCount; } else{ entity = deletedEntities.front(); deletedEntities.pop(); } ComponentMask CMask; CMask.set(0, true);//!first bit in CMask is "alive" bit componentMasks[entity] = CMask; } //! addEntity overload to take multiple components to mask entity with while adding void addEntity(Entity& entity, std::initializer_list<std::string> const& components){ if(deletedEntities.empty()){ entity = entityCount; ++entityCount; } else{ entity = deletedEntities.front(); deletedEntities.pop(); } ComponentMask CMask; CMask.set(0, true);//!first bit in CMask is "alive" bit CMask | componentContainers.getBitMask(components); componentMasks[entity] = CMask; } /*!\fn maskEntity * \brief 'assigns' components to an entity by ORing its component mask with given components */ void maskEntity(Entity& entity, ComponentMask& CMask){ componentMasks[entity] | CMask; } //! maskEntity overload to take names of components void maskEntity(Entity& entity, std::initializer_list<std::string>& components){ componentMasks[entity] |componentContainers.getBitMask(components); } std::vector<ComponentMask> componentMasks; //! index = entity id. bit '0' = alive flag std::queue<Entity> deletedEntities; //! available indices to use in componentMasks vector Entity entityCount = 0; //! Max number of entity ids used so far ComponentContainers componentContainers; }; class Engine{ public: Entity createEntity(){ return entities.create(); } Entity createEntity(std::initializer_list<std::string> const& componentNames){ return entities.create(componentNames); } void destroyEntity(Entity const& entity){ entities.remove(entity); } template <class Component> void newComponentType(std::string const& name, Component const& type){ } template <class Component> std::shared_ptr<BaseContainer> getComponents(std::string name){ } private: Entities entities; ComponentContainers components; Systems systems; }; }// ecs namespace #endif /* ECS_HPP_ */ <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <test/sheet/xsheetannotations.hxx> #include <com/sun/star/table/CellAddress.hpp> #include <com/sun/star/container/XIndexAccess.hpp> #include <com/sun/star/sheet/XSheetAnnotation.hpp> #include <com/sun/star/text/XTextRange.hpp> #include "cppunit/extensions/HelperMacros.h" #include <rtl/ustring.hxx> using namespace css; using namespace css::uno; namespace apitest { void XSheetAnnotations::testInsertNew() { uno::Reference< sheet::XSheetAnnotations > aSheetAnnotations (init(), UNO_QUERY_THROW); // count before inserting uno::Reference< container::XIndexAccess > xAnnotationsIndex (aSheetAnnotations, UNO_QUERY_THROW); sal_Int32 nBefore = xAnnotationsIndex->getCount(); // insert the annotation table::CellAddress xTargetCellAddress (0,3,4); aSheetAnnotations->insertNew(xTargetCellAddress, "an inserted annotation"); // count after inserting //uno::Reference< container::XIndexAccess > xAnnotationsIndexAfter (aSheetAnnotations, UNO_QUERY_THROW); sal_Int32 nAfter = xAnnotationsIndex->getCount(); CPPUNIT_ASSERT_MESSAGE("Annotations index not updated", nAfter == nBefore + 1); // is the position ok ? uno::Reference< sheet::XSheetAnnotation > aLastSheetAnnotation (xAnnotationsIndex->getByIndex(nAfter-1), UNO_QUERY_THROW); table::CellAddress xResultCellAddress = aLastSheetAnnotation->getPosition(); CPPUNIT_ASSERT_MESSAGE("Insert Annotation - Wrong SHEET reference position", xResultCellAddress.Sheet == xTargetCellAddress.Sheet); CPPUNIT_ASSERT_MESSAGE("Insert Annotation - Wrong COLUMN reference position", xResultCellAddress.Column == xTargetCellAddress.Column); CPPUNIT_ASSERT_MESSAGE("Insert Annotation - Wrong ROW reference position", xResultCellAddress.Row == xTargetCellAddress.Row); // is the string ok ? uno::Reference< text::XTextRange > aTextSheetAnnotation(aLastSheetAnnotation, UNO_QUERY_THROW); OUString aString = aTextSheetAnnotation->getString(); CPPUNIT_ASSERT_MESSAGE("Insert Annotation - Wrong string", aString == "an inserted annotation"); } void XSheetAnnotations::testRemoveByIndex() { uno::Reference< sheet::XSheetAnnotations > aSheetAnnotations (init(), UNO_QUERY_THROW); // insert some annotations table::CellAddress xTargetCellAddress (0,4,5); aSheetAnnotations->insertNew(xTargetCellAddress, "an inserted annotation 1"); table::CellAddress xToBeRemovedCellAddress (0,5,6); aSheetAnnotations->insertNew(xToBeRemovedCellAddress, "an inserted annotation 2"); table::CellAddress xOtherCellAddress (0,7,8); aSheetAnnotations->insertNew(xOtherCellAddress, "an inserted annotation 3"); // count before removing uno::Reference< container::XIndexAccess > xAnnotationsIndex (aSheetAnnotations, UNO_QUERY_THROW); sal_Int32 nBefore = xAnnotationsIndex->getCount(); // remove the xToBeRemovedCellAddress aSheetAnnotations->removeByIndex(nBefore-2); // count after removing //uno::Reference< container::XIndexAccess > xAnnotationsIndex (aSheetAnnotations, UNO_QUERY_THROW); sal_Int32 nAfter = xAnnotationsIndex->getCount(); // the last position should be xOtherCellAddress uno::Reference< sheet::XSheetAnnotation > aLastSheetAnnotation (xAnnotationsIndex->getByIndex(nAfter-1), UNO_QUERY_THROW); table::CellAddress xResultCellAddress = aLastSheetAnnotation->getPosition(); CPPUNIT_ASSERT_MESSAGE("Remove Annotation - Wrong SHEET reference position", xResultCellAddress.Sheet == xOtherCellAddress.Sheet); CPPUNIT_ASSERT_MESSAGE("Remove Annotation - Wrong COLUMN reference position", xResultCellAddress.Column == xOtherCellAddress.Column); CPPUNIT_ASSERT_MESSAGE("Remove Annotation - Wrong ROW reference position", xResultCellAddress.Row == xOtherCellAddress.Row); // is the string ok ? uno::Reference< text::XTextRange > aLastTextSheetAnnotation(aLastSheetAnnotation, UNO_QUERY_THROW); OUString aLastString = aLastTextSheetAnnotation->getString(); CPPUNIT_ASSERT_MESSAGE("Remove Annotation - Wrong string", aLastString == "an inserted annotation 3"); // the previous should be xTargetCellAddress uno::Reference< sheet::XSheetAnnotation > aPreviousSheetAnnotation (xAnnotationsIndex->getByIndex(nAfter-2), UNO_QUERY_THROW); table::CellAddress xPreviousCellAddress = aPreviousSheetAnnotation->getPosition(); CPPUNIT_ASSERT_MESSAGE("Remove Annotation - Wrong SHEET reference position", xPreviousCellAddress.Sheet == xTargetCellAddress.Sheet); CPPUNIT_ASSERT_MESSAGE("Remove Annotation - Wrong COLUMN reference position", xPreviousCellAddress.Column == xTargetCellAddress.Column); CPPUNIT_ASSERT_MESSAGE("Remove Annotation - Wrong ROW reference position", xPreviousCellAddress.Row == xTargetCellAddress.Row); // is the string ok ? uno::Reference< text::XTextRange > aPreviousTextSheetAnnotation(aPreviousSheetAnnotation, UNO_QUERY_THROW); OUString aPreviousString = aPreviousTextSheetAnnotation->getString(); CPPUNIT_ASSERT_MESSAGE("Remove Annotation - Wrong string", aPreviousString == "an inserted annotation 1"); } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Improve test assertions<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <test/sheet/xsheetannotations.hxx> #include <com/sun/star/table/CellAddress.hpp> #include <com/sun/star/container/XIndexAccess.hpp> #include <com/sun/star/sheet/XSheetAnnotation.hpp> #include <com/sun/star/text/XTextRange.hpp> #include "cppunit/extensions/HelperMacros.h" #include <rtl/ustring.hxx> using namespace css; using namespace css::uno; namespace apitest { void XSheetAnnotations::testInsertNew() { uno::Reference< sheet::XSheetAnnotations > aSheetAnnotations (init(), UNO_QUERY_THROW); // count before inserting uno::Reference< container::XIndexAccess > xAnnotationsIndex (aSheetAnnotations, UNO_QUERY_THROW); sal_Int32 nBefore = xAnnotationsIndex->getCount(); // insert the annotation table::CellAddress xTargetCellAddress (0,3,4); aSheetAnnotations->insertNew(xTargetCellAddress, "an inserted annotation"); // count after inserting //uno::Reference< container::XIndexAccess > xAnnotationsIndexAfter (aSheetAnnotations, UNO_QUERY_THROW); sal_Int32 nAfter = xAnnotationsIndex->getCount(); CPPUNIT_ASSERT_EQUAL_MESSAGE( "Annotations index not updated", nBefore + 1, nAfter); // is the position ok ? uno::Reference< sheet::XSheetAnnotation > aLastSheetAnnotation (xAnnotationsIndex->getByIndex(nAfter-1), UNO_QUERY_THROW); table::CellAddress xResultCellAddress = aLastSheetAnnotation->getPosition(); CPPUNIT_ASSERT_EQUAL_MESSAGE( "Insert Annotation - Wrong SHEET reference position", xTargetCellAddress.Sheet, xResultCellAddress.Sheet); CPPUNIT_ASSERT_EQUAL_MESSAGE( "Insert Annotation - Wrong COLUMN reference position", xTargetCellAddress.Column, xResultCellAddress.Column); CPPUNIT_ASSERT_EQUAL_MESSAGE( "Insert Annotation - Wrong ROW reference position", xTargetCellAddress.Row, xResultCellAddress.Row); // is the string ok ? uno::Reference< text::XTextRange > aTextSheetAnnotation(aLastSheetAnnotation, UNO_QUERY_THROW); OUString aString = aTextSheetAnnotation->getString(); CPPUNIT_ASSERT_EQUAL_MESSAGE( "Insert Annotation - Wrong string", OUString("an inserted annotation"), aString); } void XSheetAnnotations::testRemoveByIndex() { uno::Reference< sheet::XSheetAnnotations > aSheetAnnotations (init(), UNO_QUERY_THROW); // insert some annotations table::CellAddress xTargetCellAddress (0,4,5); aSheetAnnotations->insertNew(xTargetCellAddress, "an inserted annotation 1"); table::CellAddress xToBeRemovedCellAddress (0,5,6); aSheetAnnotations->insertNew(xToBeRemovedCellAddress, "an inserted annotation 2"); table::CellAddress xOtherCellAddress (0,7,8); aSheetAnnotations->insertNew(xOtherCellAddress, "an inserted annotation 3"); // count before removing uno::Reference< container::XIndexAccess > xAnnotationsIndex (aSheetAnnotations, UNO_QUERY_THROW); sal_Int32 nBefore = xAnnotationsIndex->getCount(); // remove the xToBeRemovedCellAddress aSheetAnnotations->removeByIndex(nBefore-2); // count after removing //uno::Reference< container::XIndexAccess > xAnnotationsIndex (aSheetAnnotations, UNO_QUERY_THROW); sal_Int32 nAfter = xAnnotationsIndex->getCount(); // the last position should be xOtherCellAddress uno::Reference< sheet::XSheetAnnotation > aLastSheetAnnotation (xAnnotationsIndex->getByIndex(nAfter-1), UNO_QUERY_THROW); table::CellAddress xResultCellAddress = aLastSheetAnnotation->getPosition(); CPPUNIT_ASSERT_EQUAL_MESSAGE( "Remove Annotation - Wrong SHEET reference position", xOtherCellAddress.Sheet, xResultCellAddress.Sheet); CPPUNIT_ASSERT_EQUAL_MESSAGE( "Remove Annotation - Wrong COLUMN reference position", xOtherCellAddress.Column, xResultCellAddress.Column); CPPUNIT_ASSERT_EQUAL_MESSAGE( "Remove Annotation - Wrong ROW reference position", xOtherCellAddress.Row, xResultCellAddress.Row); // is the string ok ? uno::Reference< text::XTextRange > aLastTextSheetAnnotation(aLastSheetAnnotation, UNO_QUERY_THROW); OUString aLastString = aLastTextSheetAnnotation->getString(); CPPUNIT_ASSERT_EQUAL_MESSAGE( "Remove Annotation - Wrong string", OUString("an inserted annotation 3"), aLastString); // the previous should be xTargetCellAddress uno::Reference< sheet::XSheetAnnotation > aPreviousSheetAnnotation (xAnnotationsIndex->getByIndex(nAfter-2), UNO_QUERY_THROW); table::CellAddress xPreviousCellAddress = aPreviousSheetAnnotation->getPosition(); CPPUNIT_ASSERT_EQUAL_MESSAGE( "Remove Annotation - Wrong SHEET reference position", xTargetCellAddress.Sheet, xPreviousCellAddress.Sheet); CPPUNIT_ASSERT_EQUAL_MESSAGE( "Remove Annotation - Wrong COLUMN reference position", xTargetCellAddress.Column, xPreviousCellAddress.Column); CPPUNIT_ASSERT_EQUAL_MESSAGE( "Remove Annotation - Wrong ROW reference position", xTargetCellAddress.Row, xPreviousCellAddress.Row); // is the string ok ? uno::Reference< text::XTextRange > aPreviousTextSheetAnnotation(aPreviousSheetAnnotation, UNO_QUERY_THROW); OUString aPreviousString = aPreviousTextSheetAnnotation->getString(); CPPUNIT_ASSERT_EQUAL_MESSAGE( "Remove Annotation - Wrong string", OUString("an inserted annotation 1"), aPreviousString); } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2016 // Mehdi Goli Codeplay Software Ltd. // Ralph Potter Codeplay Software Ltd. // Luke Iwanski Codeplay Software Ltd. // Contact: <eigen@codeplay.com> // // 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/. #define EIGEN_TEST_NO_LONGDOUBLE #define EIGEN_TEST_NO_COMPLEX #define EIGEN_TEST_FUNC cxx11_tensor_builtins_sycl #define EIGEN_DEFAULT_DENSE_INDEX_TYPE int #define EIGEN_USE_SYCL #include "main.h" #include <unsupported/Eigen/CXX11/Tensor> using Eigen::array; using Eigen::SyclDevice; using Eigen::Tensor; using Eigen::TensorMap; namespace std { template <typename T> T rsqrt(T x) { return 1 / std::sqrt(x); } template <typename T> T square(T x) { return x * x; } template <typename T> T cube(T x) { return x * x * x; } template <typename T> T inverse(T x) { return 1 / x; } } #define TEST_UNARY_BUILTINS_FOR_SCALAR(FUNC, SCALAR, OPERATOR) \ { \ /* out OPERATOR in.FUNC() */ \ Tensor<SCALAR, 3> in(tensorRange); \ Tensor<SCALAR, 3> out(tensorRange); \ in = in.random() + static_cast<SCALAR>(0.01); \ out = out.random() + static_cast<SCALAR>(0.01); \ Tensor<SCALAR, 3> reference(out); \ SCALAR *gpu_data = static_cast<SCALAR *>( \ sycl_device.allocate(in.size() * sizeof(SCALAR))); \ SCALAR *gpu_data_out = static_cast<SCALAR *>( \ sycl_device.allocate(out.size() * sizeof(SCALAR))); \ TensorMap<Tensor<SCALAR, 3>> gpu(gpu_data, tensorRange); \ TensorMap<Tensor<SCALAR, 3>> gpu_out(gpu_data_out, tensorRange); \ sycl_device.memcpyHostToDevice(gpu_data, in.data(), \ (in.size()) * sizeof(SCALAR)); \ sycl_device.memcpyHostToDevice(gpu_data_out, out.data(), \ (out.size()) * sizeof(SCALAR)); \ gpu_out.device(sycl_device) OPERATOR gpu.FUNC(); \ sycl_device.memcpyDeviceToHost(out.data(), gpu_data_out, \ (out.size()) * sizeof(SCALAR)); \ for (int i = 0; i < out.size(); ++i) { \ SCALAR ver = reference(i); \ ver OPERATOR std::FUNC(in(i)); \ VERIFY_IS_APPROX(out(i), ver); \ } \ sycl_device.deallocate(gpu_data); \ sycl_device.deallocate(gpu_data_out); \ } \ { \ /* out OPERATOR out.FUNC() */ \ Tensor<SCALAR, 3> out(tensorRange); \ out = out.random() + static_cast<SCALAR>(0.01); \ Tensor<SCALAR, 3> reference(out); \ SCALAR *gpu_data_out = static_cast<SCALAR *>( \ sycl_device.allocate(out.size() * sizeof(SCALAR))); \ TensorMap<Tensor<SCALAR, 3>> gpu_out(gpu_data_out, tensorRange); \ sycl_device.memcpyHostToDevice(gpu_data_out, out.data(), \ (out.size()) * sizeof(SCALAR)); \ gpu_out.device(sycl_device) OPERATOR gpu_out.FUNC(); \ sycl_device.memcpyDeviceToHost(out.data(), gpu_data_out, \ (out.size()) * sizeof(SCALAR)); \ for (int i = 0; i < out.size(); ++i) { \ SCALAR ver = reference(i); \ ver OPERATOR std::FUNC(reference(i)); \ VERIFY_IS_APPROX(out(i), ver); \ } \ sycl_device.deallocate(gpu_data_out); \ } #define TEST_UNARY_BUILTINS_OPERATOR(SCALAR, OPERATOR) \ TEST_UNARY_BUILTINS_FOR_SCALAR(abs, SCALAR, OPERATOR) \ TEST_UNARY_BUILTINS_FOR_SCALAR(sqrt, SCALAR, OPERATOR) \ TEST_UNARY_BUILTINS_FOR_SCALAR(rsqrt, SCALAR, OPERATOR) \ TEST_UNARY_BUILTINS_FOR_SCALAR(square, SCALAR, OPERATOR) \ TEST_UNARY_BUILTINS_FOR_SCALAR(cube, SCALAR, OPERATOR) \ TEST_UNARY_BUILTINS_FOR_SCALAR(inverse, SCALAR, OPERATOR) \ TEST_UNARY_BUILTINS_FOR_SCALAR(tanh, SCALAR, OPERATOR) \ TEST_UNARY_BUILTINS_FOR_SCALAR(exp, SCALAR, OPERATOR) \ TEST_UNARY_BUILTINS_FOR_SCALAR(log, SCALAR, OPERATOR) \ TEST_UNARY_BUILTINS_FOR_SCALAR(abs, SCALAR, OPERATOR) \ TEST_UNARY_BUILTINS_FOR_SCALAR(ceil, SCALAR, OPERATOR) \ TEST_UNARY_BUILTINS_FOR_SCALAR(floor, SCALAR, OPERATOR) \ TEST_UNARY_BUILTINS_FOR_SCALAR(round, SCALAR, OPERATOR) \ TEST_UNARY_BUILTINS_FOR_SCALAR(log1p, SCALAR, OPERATOR) #define TEST_IS_THAT_RETURNS_BOOL(SCALAR, FUNC) \ { \ /* out = in.FUNC() */ \ Tensor<SCALAR, 3> in(tensorRange); \ Tensor<bool, 3> out(tensorRange); \ in = in.random() + static_cast<SCALAR>(0.01); \ SCALAR *gpu_data = static_cast<SCALAR *>( \ sycl_device.allocate(in.size() * sizeof(SCALAR))); \ bool *gpu_data_out = \ static_cast<bool *>(sycl_device.allocate(out.size() * sizeof(bool))); \ TensorMap<Tensor<SCALAR, 3>> gpu(gpu_data, tensorRange); \ TensorMap<Tensor<bool, 3>> gpu_out(gpu_data_out, tensorRange); \ sycl_device.memcpyHostToDevice(gpu_data, in.data(), \ (in.size()) * sizeof(SCALAR)); \ gpu_out.device(sycl_device) = gpu.FUNC(); \ sycl_device.memcpyDeviceToHost(out.data(), gpu_data_out, \ (out.size()) * sizeof(bool)); \ for (int i = 0; i < out.size(); ++i) { \ VERIFY_IS_EQUAL(out(i), std::FUNC(in(i))); \ } \ sycl_device.deallocate(gpu_data); \ sycl_device.deallocate(gpu_data_out); \ } #define TEST_UNARY_BUILTINS(SCALAR) \ TEST_UNARY_BUILTINS_OPERATOR(SCALAR, += ) \ TEST_UNARY_BUILTINS_OPERATOR(SCALAR, = ) \ TEST_IS_THAT_RETURNS_BOOL(SCALAR, isnan) \ TEST_IS_THAT_RETURNS_BOOL(SCALAR, isfinite) \ TEST_IS_THAT_RETURNS_BOOL(SCALAR, isinf) static void test_builtin_unary_sycl(const Eigen::SyclDevice &sycl_device) { int sizeDim1 = 10; int sizeDim2 = 10; int sizeDim3 = 10; array<int, 3> tensorRange = {{sizeDim1, sizeDim2, sizeDim3}}; TEST_UNARY_BUILTINS(float) /// your GPU must support double. Otherwise, disable the double test. TEST_UNARY_BUILTINS(double) } void test_cxx11_tensor_builtins_sycl() { cl::sycl::gpu_selector s; QueueInterface queueInterface(s); Eigen::SyclDevice sycl_device(&queueInterface); CALL_SUBTEST(test_builtin_unary_sycl(sycl_device)); } <commit_msg>Added test for cwiseMin, cwiseMax and operator%.<commit_after>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2016 // Mehdi Goli Codeplay Software Ltd. // Ralph Potter Codeplay Software Ltd. // Luke Iwanski Codeplay Software Ltd. // Contact: <eigen@codeplay.com> // // 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/. #define EIGEN_TEST_NO_LONGDOUBLE #define EIGEN_TEST_NO_COMPLEX #define EIGEN_TEST_FUNC cxx11_tensor_builtins_sycl #define EIGEN_DEFAULT_DENSE_INDEX_TYPE int #define EIGEN_USE_SYCL #include "main.h" #include <unsupported/Eigen/CXX11/Tensor> using Eigen::array; using Eigen::SyclDevice; using Eigen::Tensor; using Eigen::TensorMap; namespace std { template <typename T> T rsqrt(T x) { return 1 / std::sqrt(x); } template <typename T> T square(T x) { return x * x; } template <typename T> T cube(T x) { return x * x * x; } template <typename T> T inverse(T x) { return 1 / x; } } #define TEST_UNARY_BUILTINS_FOR_SCALAR(FUNC, SCALAR, OPERATOR) \ { \ /* out OPERATOR in.FUNC() */ \ Tensor<SCALAR, 3> in(tensorRange); \ Tensor<SCALAR, 3> out(tensorRange); \ in = in.random() + static_cast<SCALAR>(0.01); \ out = out.random() + static_cast<SCALAR>(0.01); \ Tensor<SCALAR, 3> reference(out); \ SCALAR *gpu_data = static_cast<SCALAR *>( \ sycl_device.allocate(in.size() * sizeof(SCALAR))); \ SCALAR *gpu_data_out = static_cast<SCALAR *>( \ sycl_device.allocate(out.size() * sizeof(SCALAR))); \ TensorMap<Tensor<SCALAR, 3>> gpu(gpu_data, tensorRange); \ TensorMap<Tensor<SCALAR, 3>> gpu_out(gpu_data_out, tensorRange); \ sycl_device.memcpyHostToDevice(gpu_data, in.data(), \ (in.size()) * sizeof(SCALAR)); \ sycl_device.memcpyHostToDevice(gpu_data_out, out.data(), \ (out.size()) * sizeof(SCALAR)); \ gpu_out.device(sycl_device) OPERATOR gpu.FUNC(); \ sycl_device.memcpyDeviceToHost(out.data(), gpu_data_out, \ (out.size()) * sizeof(SCALAR)); \ for (int i = 0; i < out.size(); ++i) { \ SCALAR ver = reference(i); \ ver OPERATOR std::FUNC(in(i)); \ VERIFY_IS_APPROX(out(i), ver); \ } \ sycl_device.deallocate(gpu_data); \ sycl_device.deallocate(gpu_data_out); \ } \ { \ /* out OPERATOR out.FUNC() */ \ Tensor<SCALAR, 3> out(tensorRange); \ out = out.random() + static_cast<SCALAR>(0.01); \ Tensor<SCALAR, 3> reference(out); \ SCALAR *gpu_data_out = static_cast<SCALAR *>( \ sycl_device.allocate(out.size() * sizeof(SCALAR))); \ TensorMap<Tensor<SCALAR, 3>> gpu_out(gpu_data_out, tensorRange); \ sycl_device.memcpyHostToDevice(gpu_data_out, out.data(), \ (out.size()) * sizeof(SCALAR)); \ gpu_out.device(sycl_device) OPERATOR gpu_out.FUNC(); \ sycl_device.memcpyDeviceToHost(out.data(), gpu_data_out, \ (out.size()) * sizeof(SCALAR)); \ for (int i = 0; i < out.size(); ++i) { \ SCALAR ver = reference(i); \ ver OPERATOR std::FUNC(reference(i)); \ VERIFY_IS_APPROX(out(i), ver); \ } \ sycl_device.deallocate(gpu_data_out); \ } #define TEST_UNARY_BUILTINS_OPERATOR(SCALAR, OPERATOR) \ TEST_UNARY_BUILTINS_FOR_SCALAR(abs, SCALAR, OPERATOR) \ TEST_UNARY_BUILTINS_FOR_SCALAR(sqrt, SCALAR, OPERATOR) \ TEST_UNARY_BUILTINS_FOR_SCALAR(rsqrt, SCALAR, OPERATOR) \ TEST_UNARY_BUILTINS_FOR_SCALAR(square, SCALAR, OPERATOR) \ TEST_UNARY_BUILTINS_FOR_SCALAR(cube, SCALAR, OPERATOR) \ TEST_UNARY_BUILTINS_FOR_SCALAR(inverse, SCALAR, OPERATOR) \ TEST_UNARY_BUILTINS_FOR_SCALAR(tanh, SCALAR, OPERATOR) \ TEST_UNARY_BUILTINS_FOR_SCALAR(exp, SCALAR, OPERATOR) \ TEST_UNARY_BUILTINS_FOR_SCALAR(log, SCALAR, OPERATOR) \ TEST_UNARY_BUILTINS_FOR_SCALAR(abs, SCALAR, OPERATOR) \ TEST_UNARY_BUILTINS_FOR_SCALAR(ceil, SCALAR, OPERATOR) \ TEST_UNARY_BUILTINS_FOR_SCALAR(floor, SCALAR, OPERATOR) \ TEST_UNARY_BUILTINS_FOR_SCALAR(round, SCALAR, OPERATOR) \ TEST_UNARY_BUILTINS_FOR_SCALAR(log1p, SCALAR, OPERATOR) #define TEST_IS_THAT_RETURNS_BOOL(SCALAR, FUNC) \ { \ /* out = in.FUNC() */ \ Tensor<SCALAR, 3> in(tensorRange); \ Tensor<bool, 3> out(tensorRange); \ in = in.random() + static_cast<SCALAR>(0.01); \ SCALAR *gpu_data = static_cast<SCALAR *>( \ sycl_device.allocate(in.size() * sizeof(SCALAR))); \ bool *gpu_data_out = \ static_cast<bool *>(sycl_device.allocate(out.size() * sizeof(bool))); \ TensorMap<Tensor<SCALAR, 3>> gpu(gpu_data, tensorRange); \ TensorMap<Tensor<bool, 3>> gpu_out(gpu_data_out, tensorRange); \ sycl_device.memcpyHostToDevice(gpu_data, in.data(), \ (in.size()) * sizeof(SCALAR)); \ gpu_out.device(sycl_device) = gpu.FUNC(); \ sycl_device.memcpyDeviceToHost(out.data(), gpu_data_out, \ (out.size()) * sizeof(bool)); \ for (int i = 0; i < out.size(); ++i) { \ VERIFY_IS_EQUAL(out(i), std::FUNC(in(i))); \ } \ sycl_device.deallocate(gpu_data); \ sycl_device.deallocate(gpu_data_out); \ } #define TEST_UNARY_BUILTINS(SCALAR) \ TEST_UNARY_BUILTINS_OPERATOR(SCALAR, +=) \ TEST_UNARY_BUILTINS_OPERATOR(SCALAR, =) \ TEST_IS_THAT_RETURNS_BOOL(SCALAR, isnan) \ TEST_IS_THAT_RETURNS_BOOL(SCALAR, isfinite) \ TEST_IS_THAT_RETURNS_BOOL(SCALAR, isinf) static void test_builtin_unary_sycl(const Eigen::SyclDevice &sycl_device) { int sizeDim1 = 10; int sizeDim2 = 10; int sizeDim3 = 10; array<int, 3> tensorRange = {{sizeDim1, sizeDim2, sizeDim3}}; TEST_UNARY_BUILTINS(float) /// your GPU must support double. Otherwise, disable the double test. TEST_UNARY_BUILTINS(double) } namespace std { template <typename T> T cwiseMax(T x, T y) { return std::max(x, y); } template <typename T> T cwiseMin(T x, T y) { return std::min(x, y); } } #define TEST_BINARY_BUILTINS_FUNC(SCALAR, FUNC) \ { \ /* out = in_1.FUNC(in_2) */ \ Tensor<SCALAR, 3> in_1(tensorRange); \ Tensor<SCALAR, 3> in_2(tensorRange); \ Tensor<SCALAR, 3> out(tensorRange); \ in_1 = in_1.random() + static_cast<SCALAR>(0.01); \ in_2 = in_2.random() + static_cast<SCALAR>(0.01); \ out = out.random() + static_cast<SCALAR>(0.01); \ Tensor<SCALAR, 3> reference(out); \ SCALAR *gpu_data_1 = static_cast<SCALAR *>( \ sycl_device.allocate(in_1.size() * sizeof(SCALAR))); \ SCALAR *gpu_data_2 = static_cast<SCALAR *>( \ sycl_device.allocate(in_2.size() * sizeof(SCALAR))); \ SCALAR *gpu_data_out = static_cast<SCALAR *>( \ sycl_device.allocate(out.size() * sizeof(SCALAR))); \ TensorMap<Tensor<SCALAR, 3>> gpu_1(gpu_data_1, tensorRange); \ TensorMap<Tensor<SCALAR, 3>> gpu_2(gpu_data_2, tensorRange); \ TensorMap<Tensor<SCALAR, 3>> gpu_out(gpu_data_out, tensorRange); \ sycl_device.memcpyHostToDevice(gpu_data_1, in_1.data(), \ (in_1.size()) * sizeof(SCALAR)); \ sycl_device.memcpyHostToDevice(gpu_data_2, in_2.data(), \ (in_2.size()) * sizeof(SCALAR)); \ sycl_device.memcpyHostToDevice(gpu_data_out, out.data(), \ (out.size()) * sizeof(SCALAR)); \ gpu_out.device(sycl_device) = gpu_1.FUNC(gpu_2); \ sycl_device.memcpyDeviceToHost(out.data(), gpu_data_out, \ (out.size()) * sizeof(SCALAR)); \ for (int i = 0; i < out.size(); ++i) { \ SCALAR ver = reference(i); \ ver = std::FUNC(in_1(i), in_2(i)); \ VERIFY_IS_APPROX(out(i), ver); \ } \ sycl_device.deallocate(gpu_data_1); \ sycl_device.deallocate(gpu_data_2); \ sycl_device.deallocate(gpu_data_out); \ } #define TEST_BINARY_BUILTINS_OPERATORS(SCALAR, OPERATOR) \ { \ /* out = in_1 OPERATOR in_2 */ \ Tensor<SCALAR, 3> in_1(tensorRange); \ Tensor<SCALAR, 3> in_2(tensorRange); \ Tensor<SCALAR, 3> out(tensorRange); \ in_1 = in_1.random() + static_cast<SCALAR>(0.01); \ in_2 = in_2.random() + static_cast<SCALAR>(0.01); \ out = out.random() + static_cast<SCALAR>(0.01); \ Tensor<SCALAR, 3> reference(out); \ SCALAR *gpu_data_1 = static_cast<SCALAR *>( \ sycl_device.allocate(in_1.size() * sizeof(SCALAR))); \ SCALAR *gpu_data_2 = static_cast<SCALAR *>( \ sycl_device.allocate(in_2.size() * sizeof(SCALAR))); \ SCALAR *gpu_data_out = static_cast<SCALAR *>( \ sycl_device.allocate(out.size() * sizeof(SCALAR))); \ TensorMap<Tensor<SCALAR, 3>> gpu_1(gpu_data_1, tensorRange); \ TensorMap<Tensor<SCALAR, 3>> gpu_2(gpu_data_2, tensorRange); \ TensorMap<Tensor<SCALAR, 3>> gpu_out(gpu_data_out, tensorRange); \ sycl_device.memcpyHostToDevice(gpu_data_1, in_1.data(), \ (in_1.size()) * sizeof(SCALAR)); \ sycl_device.memcpyHostToDevice(gpu_data_2, in_2.data(), \ (in_2.size()) * sizeof(SCALAR)); \ sycl_device.memcpyHostToDevice(gpu_data_out, out.data(), \ (out.size()) * sizeof(SCALAR)); \ gpu_out.device(sycl_device) = gpu_1 OPERATOR gpu_2; \ sycl_device.memcpyDeviceToHost(out.data(), gpu_data_out, \ (out.size()) * sizeof(SCALAR)); \ for (int i = 0; i < out.size(); ++i) { \ VERIFY_IS_APPROX(out(i), in_1(i) OPERATOR in_2(i)); \ } \ sycl_device.deallocate(gpu_data_1); \ sycl_device.deallocate(gpu_data_2); \ sycl_device.deallocate(gpu_data_out); \ } #define TEST_BINARY_BUILTINS_OPERATORS_THAT_TAKES_SCALAR(SCALAR, OPERATOR) \ { \ /* out = in_1 OPERATOR 2 */ \ Tensor<SCALAR, 3> in_1(tensorRange); \ Tensor<SCALAR, 3> out(tensorRange); \ in_1 = in_1.random() + static_cast<SCALAR>(0.01); \ Tensor<SCALAR, 3> reference(out); \ SCALAR *gpu_data_1 = static_cast<SCALAR *>( \ sycl_device.allocate(in_1.size() * sizeof(SCALAR))); \ SCALAR *gpu_data_out = static_cast<SCALAR *>( \ sycl_device.allocate(out.size() * sizeof(SCALAR))); \ TensorMap<Tensor<SCALAR, 3>> gpu_1(gpu_data_1, tensorRange); \ TensorMap<Tensor<SCALAR, 3>> gpu_out(gpu_data_out, tensorRange); \ sycl_device.memcpyHostToDevice(gpu_data_1, in_1.data(), \ (in_1.size()) * sizeof(SCALAR)); \ sycl_device.memcpyHostToDevice(gpu_data_out, out.data(), \ (out.size()) * sizeof(SCALAR)); \ gpu_out.device(sycl_device) = gpu_1 OPERATOR 2; \ sycl_device.memcpyDeviceToHost(out.data(), gpu_data_out, \ (out.size()) * sizeof(SCALAR)); \ for (int i = 0; i < out.size(); ++i) { \ VERIFY_IS_APPROX(out(i), in_1(i) OPERATOR 2); \ } \ sycl_device.deallocate(gpu_data_1); \ sycl_device.deallocate(gpu_data_out); \ } #define TEST_BINARY_BUILTINS(SCALAR) \ TEST_BINARY_BUILTINS_FUNC(SCALAR, cwiseMax) \ TEST_BINARY_BUILTINS_FUNC(SCALAR, cwiseMin) \ TEST_BINARY_BUILTINS_OPERATORS(SCALAR, +) \ TEST_BINARY_BUILTINS_OPERATORS(SCALAR, -) \ TEST_BINARY_BUILTINS_OPERATORS(SCALAR, *) \ TEST_BINARY_BUILTINS_OPERATORS(SCALAR, /) static void test_builtin_binary_sycl(const Eigen::SyclDevice &sycl_device) { int sizeDim1 = 10; int sizeDim2 = 10; int sizeDim3 = 10; array<int, 3> tensorRange = {{sizeDim1, sizeDim2, sizeDim3}}; TEST_BINARY_BUILTINS(float) TEST_BINARY_BUILTINS_OPERATORS_THAT_TAKES_SCALAR(int, %) } void test_cxx11_tensor_builtins_sycl() { cl::sycl::gpu_selector s; QueueInterface queueInterface(s); Eigen::SyclDevice sycl_device(&queueInterface); CALL_SUBTEST(test_builtin_unary_sycl(sycl_device)); CALL_SUBTEST(test_builtin_binary_sycl(sycl_device)); } <|endoftext|>
<commit_before>#include <cstring> #include <boost/lexical_cast.hpp> #include "nsscompiler.hpp" #include "scriptfile.hpp" #include "parser.hpp" #include "buffer.hpp" using namespace NpaPrivate; class Program; extern Program* pRoot; extern int yyparse(); typedef struct yy_buffer_state* YY_BUFFER_STATE; extern int yyparse(); #if ((FLEX_VERSION_MAJOR) > 2 || \ ((FLEX_VERSION_MAJOR == 2 && FLEX_VERSION_MINOR > 5) || \ ((FLEX_VERSION_MAJOR == 2 && FLEX_VERSION_MINOR == 5 && FLEX_VERSION_PATCH > 35)))) extern YY_BUFFER_STATE yy_scan_bytes(const char* bytes, size_t len); #else extern YY_BUFFER_STATE yy_scan_bytes(const char* bytes, int len); #endif extern void yy_delete_buffer(YY_BUFFER_STATE buffer); static uint32_t SymCounter = 1; static uint32_t Counter = 1; static Buffer* Output; static Buffer* MapOutput; const char* ArgumentTypes[] = { "INT", "STRING", "FLOAT" }; Call* MakeCall(string Name, uint16_t Magic) { ExpressionList Args; Args.push_back(new Argument(Name, ARG_STRING)); Argument* Arg = new Argument(Nsb::StringifyMagic(Magic), ARG_FUNCTION); return new Call(*Arg, Args, Magic); } void WriteSymbol(const string& Symbol) { uint32_t Pos = Output->Size(); uint16_t Size = Symbol.size(); MapOutput->Write((char*)&Pos, sizeof(uint32_t)); MapOutput->Write((char*)&Size, sizeof(uint16_t)); MapOutput->Write(Symbol.c_str(), Size); } void Node::Compile(uint16_t Magic, uint16_t NumParams) { Output->Write((char*)&Counter, sizeof(uint32_t)); Output->Write((char*)&Magic, sizeof(uint16_t)); Output->Write((char*)&NumParams, sizeof(uint16_t)); ++Counter; } void Argument::Compile() { // Value if (Type == ARG_VARIABLE) Node::Compile(MAGIC_GET, 1); // Variable else { Node::Compile(MAGIC_LITERAL, 2); string Data = NpaFile::FromUtf8(ArgumentTypes[Type]); uint32_t TypeSize = Data.size(); Output->Write((char*)&TypeSize, sizeof(uint32_t)); Output->Write(Data.c_str(), TypeSize); } CompileRaw(); } void Argument::CompileRaw() { uint32_t Size = Data.size(); Output->Write((char*)&Size, sizeof(uint32_t)); Output->Write(Data.c_str(), Size); } void Expression::CompileRaw() { uint32_t Size = 1; Output->Write((char*)&Size, sizeof(uint32_t)); Output->Write("@", Size); } void Call::Compile() { uint16_t NumParams = Arguments.size(); uint32_t BuiltinMagic = Nsb::MagicifyString(Name.Data.c_str()); // Parameters if (BuiltinMagic != MAGIC_PARSE_TEXT && BuiltinMagic != MAGIC_CALL_SCENE && BuiltinMagic != MAGIC_CALL_CHAPTER) for (auto i = Arguments.begin(); i != Arguments.end(); ++i) (*i)->Compile(); // Builtin function if (BuiltinMagic != 0) Node::Compile(BuiltinMagic, NumParams); // Script function else { NumParams += 1; Node::Compile(Magic, NumParams); Name.CompileRaw(); } // Arguments for (auto i = Arguments.begin(); i != Arguments.end(); ++i) (*i)->CompileRaw(); } void CallStatement::Compile() { Call::Compile(); Node::Compile(MAGIC_CLEAR_PARAMS, 0); } void Block::Compile() { Node::Compile(MAGIC_SCOPE_BEGIN, 0); for (auto i = Statements.begin(); i != Statements.end(); ++i) (*i)->Compile(); Node::Compile(MAGIC_SCOPE_END, 0); } void Subroutine::CompilePrototype(uint16_t BeginMagic, uint32_t NumBeginParams) { WriteSymbol(Name.Data); Node::Compile(BeginMagic, NumBeginParams); Name.CompileRaw(); } void Subroutine::Compile() { SubroutineBlock.Compile(); } void Subroutine::CompileReturn(uint16_t EndMagic) { Node::Compile(EndMagic, NumEndParams); } void Program::Compile() { for (auto i = Subroutines.begin(); i != Subroutines.end(); ++i) (*i)->Compile(); } void Function::Compile() { CompilePrototype(MAGIC_FUNCTION_DECLARATION, Arguments.size() + 1); for (auto i = Arguments.begin(); i != Arguments.end(); ++i) (*i)->CompileRaw(); Subroutine::Compile(); CompileReturn(MAGIC_END_FUNCTION); } void Chapter::Compile() { CompilePrototype(MAGIC_CHAPTER_DECLARATION, 1); Subroutine::Compile(); CompileReturn(MAGIC_END_CHAPTER); } void Scene::Compile() { CompilePrototype(MAGIC_SCENE_DECLARATION, 1); Subroutine::Compile(); CompileReturn(MAGIC_END_SCENE); } void Assignment::Compile() { Rhs.Compile(); Node::Compile(Magic, 1); Name.CompileRaw(); Node::Compile(MAGIC_CLEAR_PARAMS, 0); } void BinaryOperator::Compile() { Lhs.Compile(); Rhs.Compile(); Node::Compile(Magic, 0); } void UnaryOperator::Compile() { Rhs.Compile(); Node::Compile(Magic, 0); } void Condition::_Compile(Argument& EndSym) { Expr.Compile(); Node::Compile(Magic, 1); EndSym.CompileRaw(); ConditionBlock.Compile(); SymCounter++; } void If::Compile() { Argument EndSym("label.if.end." + boost::lexical_cast<string>(SymCounter), ARG_STRING); Condition::_Compile(EndSym); WriteSymbol(EndSym.Data); } void While::Compile() { Argument BeginSym("label.while.begin." + boost::lexical_cast<string>(SymCounter), ARG_STRING); Argument EndSym("label.while.end." + boost::lexical_cast<string>(SymCounter), ARG_STRING); WriteSymbol(BeginSym.Data); Condition::_Compile(EndSym); Node::Compile(MAGIC_JUMP, 1); BeginSym.CompileRaw(); WriteSymbol(EndSym.Data); Node::Compile(MAGIC_WHILE_END, 0); } void Else::Compile() { ElseBlock.Compile(); } void Select::Compile() { SelectBlock.Compile(); } void Case::Compile() { CaseBlock.Compile(); } namespace Nss { void Compile(const char* pBuffer, uint32_t Length, Buffer* NsbBuffer, Buffer* MapBuffer) { Output = NsbBuffer; MapOutput = MapBuffer; YY_BUFFER_STATE buffer = yy_scan_bytes(pBuffer, Length); yyparse(); pRoot->Compile(); yy_delete_buffer(buffer); } } <commit_msg>nsscompiler: WHILE_END should be before JUMP<commit_after>#include <cstring> #include <boost/lexical_cast.hpp> #include "nsscompiler.hpp" #include "scriptfile.hpp" #include "parser.hpp" #include "buffer.hpp" using namespace NpaPrivate; class Program; extern Program* pRoot; extern int yyparse(); typedef struct yy_buffer_state* YY_BUFFER_STATE; extern int yyparse(); #if ((FLEX_VERSION_MAJOR) > 2 || \ ((FLEX_VERSION_MAJOR == 2 && FLEX_VERSION_MINOR > 5) || \ ((FLEX_VERSION_MAJOR == 2 && FLEX_VERSION_MINOR == 5 && FLEX_VERSION_PATCH > 35)))) extern YY_BUFFER_STATE yy_scan_bytes(const char* bytes, size_t len); #else extern YY_BUFFER_STATE yy_scan_bytes(const char* bytes, int len); #endif extern void yy_delete_buffer(YY_BUFFER_STATE buffer); static uint32_t SymCounter = 1; static uint32_t Counter = 1; static Buffer* Output; static Buffer* MapOutput; const char* ArgumentTypes[] = { "INT", "STRING", "FLOAT" }; Call* MakeCall(string Name, uint16_t Magic) { ExpressionList Args; Args.push_back(new Argument(Name, ARG_STRING)); Argument* Arg = new Argument(Nsb::StringifyMagic(Magic), ARG_FUNCTION); return new Call(*Arg, Args, Magic); } void WriteSymbol(const string& Symbol) { uint32_t Pos = Output->Size(); uint16_t Size = Symbol.size(); MapOutput->Write((char*)&Pos, sizeof(uint32_t)); MapOutput->Write((char*)&Size, sizeof(uint16_t)); MapOutput->Write(Symbol.c_str(), Size); } void Node::Compile(uint16_t Magic, uint16_t NumParams) { Output->Write((char*)&Counter, sizeof(uint32_t)); Output->Write((char*)&Magic, sizeof(uint16_t)); Output->Write((char*)&NumParams, sizeof(uint16_t)); ++Counter; } void Argument::Compile() { // Value if (Type == ARG_VARIABLE) Node::Compile(MAGIC_GET, 1); // Variable else { Node::Compile(MAGIC_LITERAL, 2); string Data = NpaFile::FromUtf8(ArgumentTypes[Type]); uint32_t TypeSize = Data.size(); Output->Write((char*)&TypeSize, sizeof(uint32_t)); Output->Write(Data.c_str(), TypeSize); } CompileRaw(); } void Argument::CompileRaw() { uint32_t Size = Data.size(); Output->Write((char*)&Size, sizeof(uint32_t)); Output->Write(Data.c_str(), Size); } void Expression::CompileRaw() { uint32_t Size = 1; Output->Write((char*)&Size, sizeof(uint32_t)); Output->Write("@", Size); } void Call::Compile() { uint16_t NumParams = Arguments.size(); uint32_t BuiltinMagic = Nsb::MagicifyString(Name.Data.c_str()); // Parameters if (BuiltinMagic != MAGIC_PARSE_TEXT && BuiltinMagic != MAGIC_CALL_SCENE && BuiltinMagic != MAGIC_CALL_CHAPTER) for (auto i = Arguments.begin(); i != Arguments.end(); ++i) (*i)->Compile(); // Builtin function if (BuiltinMagic != 0) Node::Compile(BuiltinMagic, NumParams); // Script function else { NumParams += 1; Node::Compile(Magic, NumParams); Name.CompileRaw(); } // Arguments for (auto i = Arguments.begin(); i != Arguments.end(); ++i) (*i)->CompileRaw(); } void CallStatement::Compile() { Call::Compile(); Node::Compile(MAGIC_CLEAR_PARAMS, 0); } void Block::Compile() { Node::Compile(MAGIC_SCOPE_BEGIN, 0); for (auto i = Statements.begin(); i != Statements.end(); ++i) (*i)->Compile(); Node::Compile(MAGIC_SCOPE_END, 0); } void Subroutine::CompilePrototype(uint16_t BeginMagic, uint32_t NumBeginParams) { WriteSymbol(Name.Data); Node::Compile(BeginMagic, NumBeginParams); Name.CompileRaw(); } void Subroutine::Compile() { SubroutineBlock.Compile(); } void Subroutine::CompileReturn(uint16_t EndMagic) { Node::Compile(EndMagic, NumEndParams); } void Program::Compile() { for (auto i = Subroutines.begin(); i != Subroutines.end(); ++i) (*i)->Compile(); } void Function::Compile() { CompilePrototype(MAGIC_FUNCTION_DECLARATION, Arguments.size() + 1); for (auto i = Arguments.begin(); i != Arguments.end(); ++i) (*i)->CompileRaw(); Subroutine::Compile(); CompileReturn(MAGIC_END_FUNCTION); } void Chapter::Compile() { CompilePrototype(MAGIC_CHAPTER_DECLARATION, 1); Subroutine::Compile(); CompileReturn(MAGIC_END_CHAPTER); } void Scene::Compile() { CompilePrototype(MAGIC_SCENE_DECLARATION, 1); Subroutine::Compile(); CompileReturn(MAGIC_END_SCENE); } void Assignment::Compile() { Rhs.Compile(); Node::Compile(Magic, 1); Name.CompileRaw(); Node::Compile(MAGIC_CLEAR_PARAMS, 0); } void BinaryOperator::Compile() { Lhs.Compile(); Rhs.Compile(); Node::Compile(Magic, 0); } void UnaryOperator::Compile() { Rhs.Compile(); Node::Compile(Magic, 0); } void Condition::_Compile(Argument& EndSym) { Expr.Compile(); Node::Compile(Magic, 1); EndSym.CompileRaw(); ConditionBlock.Compile(); SymCounter++; } void If::Compile() { Argument EndSym("label.if.end." + boost::lexical_cast<string>(SymCounter), ARG_STRING); Condition::_Compile(EndSym); WriteSymbol(EndSym.Data); } void While::Compile() { Argument BeginSym("label.while.begin." + boost::lexical_cast<string>(SymCounter), ARG_STRING); Argument EndSym("label.while.end." + boost::lexical_cast<string>(SymCounter), ARG_STRING); WriteSymbol(BeginSym.Data); Condition::_Compile(EndSym); Node::Compile(MAGIC_WHILE_END, 0); Node::Compile(MAGIC_JUMP, 1); BeginSym.CompileRaw(); WriteSymbol(EndSym.Data); } void Else::Compile() { ElseBlock.Compile(); } void Select::Compile() { SelectBlock.Compile(); } void Case::Compile() { CaseBlock.Compile(); } namespace Nss { void Compile(const char* pBuffer, uint32_t Length, Buffer* NsbBuffer, Buffer* MapBuffer) { Output = NsbBuffer; MapOutput = MapBuffer; YY_BUFFER_STATE buffer = yy_scan_bytes(pBuffer, Length); yyparse(); pRoot->Compile(); yy_delete_buffer(buffer); } } <|endoftext|>
<commit_before>AliAnalysisTaskNetLambdaTrad *AddTaskNetLambdaTrad(const char* outputFileName = 0, const char* containerName = "NetLambdaOutput") { // Get the pointer to the existing analysis manager via the static access method. //============================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskNetLambdaTrad", "No analysis manager to connect to."); return NULL; } // Create the task and configure it. //=========================================================================== AliAnalysisTaskNetLambdaTrad* ana = new AliAnalysisTaskNetLambdaTrad(containerName); // common config, ana->SetDebugLevel(0); // gSystem->Sleep(3000); mgr->AddTask(ana); // Create ONLY the output containers for the data produced by the task. // Get and connect other common input/output containers via the manager as below //============================================================================== if (!outputFileName) outputFileName = AliAnalysisManager::GetCommonFileName(); outputFileName = "AnalysisResults.root"; AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("LambdaList", TList::Class(),AliAnalysisManager::kOutputContainer,outputFileName); mgr->ConnectInput (ana, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput (ana, 1, coutput1 ); return ana; } <commit_msg>Update AddTaskNetLambdaMCTrad.C<commit_after>AliAnalysisTaskNetLambdaMCTrad *AddTaskNetLambdaMCTrad(const char* outputFileName = 0, const char* containerName = "NetLambdaOutput") { // Get the pointer to the existing analysis manager via the static access method. //============================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskNetLambdaMCTrad", "No analysis manager to connect to."); return NULL; } // Create the task and configure it. //=========================================================================== AliAnalysisTaskNetLambdaMCTrad* ana = new AliAnalysisTaskNetLambdaMCTrad(containerName); // common config, ana->SetDebugLevel(0); // gSystem->Sleep(3000); mgr->AddTask(ana); // Create ONLY the output containers for the data produced by the task. // Get and connect other common input/output containers via the manager as below //============================================================================== if (!outputFileName) outputFileName = AliAnalysisManager::GetCommonFileName(); outputFileName = "AnalysisResults.root"; AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("LambdaList", TList::Class(),AliAnalysisManager::kOutputContainer,outputFileName); mgr->ConnectInput (ana, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput (ana, 1, coutput1 ); return ana; } <|endoftext|>
<commit_before>/* * pylon_camera_node.cpp * * Created on: Jun 10, 2015 * Author: md */ #include <pylon_camera/pylon_camera_node.h> namespace pylon_camera { PylonCameraNode::PylonCameraNode() : pylon_interface_(NULL), params_(), target_brightness_(-42), set_exposure_service_(), set_brightness_service_(), set_sleeping_service_(), img_raw_msg_(), cam_info_msg_(), img_raw_pub_(), params_update_counter_(0), brightness_service_running_(false), nh_("~"), it_(NULL), is_sleeping_(false) { it_ = new image_transport::ImageTransport(nh_); img_raw_pub_ = it_->advertiseCamera("image_raw", 10); set_exposure_service_ = nh_.advertiseService("set_exposure_srv", &PylonCameraNode::setExposureCallback, this); set_brightness_service_ = nh_.advertiseService("set_brightness_srv", &PylonCameraNode::setBrightnessCallback, this); set_sleeping_service_ = nh_.advertiseService("set_sleeping_srv", &PylonCameraNode::setSleepingCallback, this); } // Set parameter to open the desired camera void PylonCameraNode::getInitialCameraParameter() { // Write Magazino cam id to the camera using write_magazino_id_2_camera nh_.param<std::string>("magazino_cam_id", params_.magazino_cam_id_, "x"); if (params_.magazino_cam_id_ != "x") { ROS_INFO("Using Camera: %s", params_.magazino_cam_id_.c_str()); } else { ROS_INFO("No Magazino Cam ID set -> Will use the camera device found fist"); } // nh_.param<int>("parameter_update_frequency", params_.param_update_frequency_, 100); // params_update_counter_ = params_.param_update_frequency_ - 1; nh_.param<double>("desired_framerate", params_.desired_frame_rate_, 10.0); if (params_.desired_frame_rate_ < 0 && params_.desired_frame_rate_ != -1) { params_.desired_frame_rate_ = -1.0; nh_.setParam("desired_framerate", params_.desired_frame_rate_); ROS_ERROR("Unexpected framerate (%f). Setting to -1 (max possible)", params_.desired_frame_rate_); } nh_.param<std::string>("camera_frame", params_.camera_frame_, "pylon_camera"); nh_.param<int>("mtu_size", params_.mtu_size_, 3000); // nh_.param<int>("parameter_update_frequency", params_.param_update_frequency_, 100); // params_update_counter_ = params_.param_update_frequency_ - 1; // -2: AutoExposureOnce // -1: AutoExposureContinuous // 0: AutoExposureOff // > 0: Exposure in micro-seconds nh_.param<double>("start_exposure", params_.start_exposure_, 35000.0); nh_.param<bool>("use_brightness", params_.use_brightness_, false); // Using exposure or brightness // -2: AutoExposureOnce // -1: AutoExposureContinuous // 0: AutoExposureOff // > 0: Intensity Value (0-255) nh_.param<int>("start_brightness", params_.start_brightness_, 128); } uint32_t PylonCameraNode::getNumSubscribers() { return img_raw_pub_.getNumSubscribers(); } void PylonCameraNode::checkForPylonAutoFunctionRunning() { brightness_service_running_ = pylon_interface_->isAutoBrightnessFunctionRunning(); } // Using OpenCV -> creates PylonOpenCVNode (with sequencer and rectification), else: only image_raw void PylonCameraNode::createPylonInterface() { pylon_interface_ = new PylonInterface(); } bool PylonCameraNode::init() { if (!initAndRegister()) { ros::shutdown(); return false; } if (!startGrabbing()) { ros::shutdown(); return false; } return true; } bool PylonCameraNode::initAndRegister() { if (!pylon_interface_->initialize(params_)) { ROS_ERROR("Error while initializing the Pylon Interface"); return false; } // cout << "BASE CAM NODE INIT FINISHED" << endl; if (!pylon_interface_->registerCameraConfiguration(params_)) { ROS_ERROR("Error while registering the camera configuration"); return false; } // cout << "BASE CAM NODE REGISTER FINISHED" << endl; return true; } bool PylonCameraNode::startGrabbing() { if (!pylon_interface_->startGrabbing(params_)) { ROS_ERROR("Error while start grabbing"); return false; } // Framrate Settings if (pylon_interface_->max_possible_framerate() < params_.desired_frame_rate_) { ROS_INFO("Desired framerate %.2f is higher than max possible. Will limit framerate to: %.2f Hz", params_.desired_frame_rate_, pylon_interface_->max_possible_framerate()); params_.desired_frame_rate_ = pylon_interface_->max_possible_framerate(); nh_.setParam("desired_framerate", pylon_interface_->max_possible_framerate()); } else if (params_.desired_frame_rate_ == -1) { params_.desired_frame_rate_ = pylon_interface_->max_possible_framerate(); ROS_INFO("Max possible framerate is %.2f Hz", pylon_interface_->max_possible_framerate()); } std_msgs::Header header; header.frame_id = params_.camera_frame_; //header.seq = header.stamp = ros::Time::now(); cam_info_msg_.header = header; cam_info_msg_.height = pylon_interface_->img_rows(); cam_info_msg_.width = pylon_interface_->img_cols(); cam_info_msg_.distortion_model = "plumb_bob"; img_raw_msg_.header = header; // Encoding of pixels -- channel meaning, ordering, size // taken from the list of strings in include/sensor_msgs/image_encodings.h img_raw_msg_.encoding = pylon_interface_->img_encoding(); img_raw_msg_.height = pylon_interface_->img_rows(); img_raw_msg_.width = pylon_interface_->img_cols(); // step = full row length in bytes img_raw_msg_.step = img_raw_msg_.width * pylon_interface_->img_pixel_depth(); // img_raw_msg_.data // actual matrix data, size is (step * rows) pylon_interface_->set_image_size(img_raw_msg_.step * img_raw_msg_.height); return true; } bool PylonCameraNode::grabImage() { if (!pylon_interface_->grab(params_, img_raw_msg_.data)) { if (pylon_interface_->is_cam_removed()) { ROS_ERROR("Pylon Camera has been removed!"); ros::shutdown(); } else { ROS_WARN("Pylon Interface returned invalid image! Skipping"); } return false; } img_raw_msg_.header.stamp = ros::Time::now(); cam_info_msg_.header.stamp = img_raw_msg_.header.stamp; return true; } bool PylonCameraNode::setExposureCallback(pylon_camera_msgs::SetExposureSrv::Request &req, pylon_camera_msgs::SetExposureSrv::Response &res) { float current_exposure = getCurrenCurrentExposure(); // ROS_INFO("New exposure request for exposure %.f, current exposure = %.f", req.target_exposure, current_exposure); if (!pylon_interface_->is_ready_) { res.success = false; return true; } if (current_exposure != req.target_exposure) { pylon_interface_->setExposure(req.target_exposure); } // wait for 2 cycles till the cam has updated the exposure ros::Rate r(5.0); ros::Time start = ros::Time::now(); int ctr = 0; while (ros::ok() && ctr < 2) { if (ros::Time::now() - start > ros::Duration(5.0)) { ROS_ERROR("Did not reach the required brightness in time"); res.success = false; return true; } ros::spinOnce(); r.sleep(); ctr++; } current_exposure = getCurrenCurrentExposure(); if (current_exposure == req.target_exposure) { res.success = true; } else { res.success = false; } return true; } bool PylonCameraNode::setBrightnessCallback(pylon_camera_msgs::SetBrightnessSrv::Request &req, pylon_camera_msgs::SetBrightnessSrv::Response &res) { // Brightness Service can only work, if an image has already been grabbed (calc mean on current img) if (!pylon_interface_->is_ready_) { ros::Rate r(2.0); ros::Time start = ros::Time::now(); while (ros::ok() && !pylon_interface_->is_ready_) { if (ros::Time::now() - start > ros::Duration(3.0)) { ROS_ERROR("Pylon Interface has not yet grabbed an image, although waiting for 3 seconds!"); res.success = false; return true; } ros::spinOnce(); r.sleep(); } } // Get actual image ros::spinOnce(); int current_brightness = calcCurrentBrightness(); ROS_INFO("New brightness request for brightness %i, current brightness = %i", req.target_brightness, current_brightness); target_brightness_ = req.target_brightness; brightness_service_running_ = true; if (current_brightness != target_brightness_) { pylon_interface_->setBrightness(target_brightness_); } else { res.success = true; return true; } ros::Duration duration; if (target_brightness_ > 205) { // Need more time for great exposure values duration = ros::Duration(15.0); } else { duration = ros::Duration(5.0); } ros::Rate r(5.0); ros::Time start = ros::Time::now(); while (ros::ok() && brightness_service_running_) { if (ros::Time::now() - start > duration) { ROS_ERROR("Did not reach the required brightness in time"); brightness_service_running_ = false; res.success = false; return true; } ros::spinOnce(); r.sleep(); } if (pylon_interface_->is_opencv_interface_) { if (!brightnessValidation(req.target_brightness)) res.success = false; else res.success = true; return true; } res.success = true; return true; } bool PylonCameraNode::brightnessValidation(int target) { int mean = calcCurrentBrightness(); if (abs(target - mean) > 2) { return false; } return true; } int PylonCameraNode::calcCurrentBrightness() { int sum = std::accumulate(img_raw_msg_.data.begin(), img_raw_msg_.data.end(), 0); assert(img_raw_msg_.data.size() > 0); float mean = sum / img_raw_msg_.data.size(); return (int)mean; } float PylonCameraNode::getCurrenCurrentExposure() { return pylon_interface_->getCurrentExposure(); } /// Warum Service, wenn sofort immer true zurueckgegeben wird? bool PylonCameraNode::setSleepingCallback(pylon_camera_msgs::SetSleepingSrv::Request &req, pylon_camera_msgs::SetSleepingSrv::Response &res) { is_sleeping_ = req.set_sleeping; if (is_sleeping_) { ROS_INFO("Seting Pylon Camera Node to sleep..."); } else { ROS_INFO("Pylon Camera Node continues grabbing"); } res.success = true; return true; } bool PylonCameraNode::is_sleeping() { return is_sleeping_; } bool PylonCameraNode::have_intrinsic_data() { return params_.have_intrinsic_data_; } PylonCameraNode::~PylonCameraNode() { if (!pylon_interface_->is_opencv_interface_) { delete pylon_interface_; pylon_interface_ = NULL; } delete it_; it_ = NULL; } } /* namespace pylon_camera */ <commit_msg>brightness & exp server only available if in non-sequencer mode<commit_after>/* * pylon_camera_node.cpp * * Created on: Jun 10, 2015 * Author: md */ #include <pylon_camera/pylon_camera_node.h> namespace pylon_camera { PylonCameraNode::PylonCameraNode() : pylon_interface_(NULL), params_(), target_brightness_(-42), set_exposure_service_(), set_brightness_service_(), set_sleeping_service_(), img_raw_msg_(), cam_info_msg_(), img_raw_pub_(), params_update_counter_(0), brightness_service_running_(false), nh_("~"), it_(NULL), is_sleeping_(false) { it_ = new image_transport::ImageTransport(nh_); img_raw_pub_ = it_->advertiseCamera("image_raw", 10); set_sleeping_service_ = nh_.advertiseService("set_sleeping_srv", &PylonCameraNode::setSleepingCallback, this); } // Set parameter to open the desired camera void PylonCameraNode::getInitialCameraParameter() { // Write Magazino cam id to the camera using write_magazino_id_2_camera nh_.param<std::string>("magazino_cam_id", params_.magazino_cam_id_, "x"); if (params_.magazino_cam_id_ != "x") { ROS_INFO("Using Camera: %s", params_.magazino_cam_id_.c_str()); } else { ROS_INFO("No Magazino Cam ID set -> Will use the camera device found fist"); } // nh_.param<int>("parameter_update_frequency", params_.param_update_frequency_, 100); // params_update_counter_ = params_.param_update_frequency_ - 1; nh_.param<double>("desired_framerate", params_.desired_frame_rate_, 10.0); if (params_.desired_frame_rate_ < 0 && params_.desired_frame_rate_ != -1) { params_.desired_frame_rate_ = -1.0; nh_.setParam("desired_framerate", params_.desired_frame_rate_); ROS_ERROR("Unexpected framerate (%f). Setting to -1 (max possible)", params_.desired_frame_rate_); } nh_.param<std::string>("camera_frame", params_.camera_frame_, "pylon_camera"); nh_.param<int>("mtu_size", params_.mtu_size_, 3000); // nh_.param<int>("parameter_update_frequency", params_.param_update_frequency_, 100); // params_update_counter_ = params_.param_update_frequency_ - 1; // -2: AutoExposureOnce // -1: AutoExposureContinuous // 0: AutoExposureOff // > 0: Exposure in micro-seconds nh_.param<double>("start_exposure", params_.start_exposure_, 35000.0); nh_.param<bool>("use_brightness", params_.use_brightness_, false); // Using exposure or brightness // -2: AutoExposureOnce // -1: AutoExposureContinuous // 0: AutoExposureOff // > 0: Intensity Value (0-255) nh_.param<int>("start_brightness", params_.start_brightness_, 128); } uint32_t PylonCameraNode::getNumSubscribers() { return img_raw_pub_.getNumSubscribers(); } void PylonCameraNode::checkForPylonAutoFunctionRunning() { brightness_service_running_ = pylon_interface_->isAutoBrightnessFunctionRunning(); } // Using OpenCV -> creates PylonOpenCVNode (with sequencer and rectification), else: only image_raw void PylonCameraNode::createPylonInterface() { pylon_interface_ = new PylonInterface(); } bool PylonCameraNode::init() { if (!params_.use_sequencer_) { set_exposure_service_ = nh_.advertiseService("set_exposure_srv", &PylonCameraNode::setExposureCallback, this); set_brightness_service_ = nh_.advertiseService("set_brightness_srv", &PylonCameraNode::setBrightnessCallback, this); } if (!initAndRegister()) { ros::shutdown(); return false; } if (!startGrabbing()) { ros::shutdown(); return false; } return true; } bool PylonCameraNode::initAndRegister() { if (!pylon_interface_->initialize(params_)) { ROS_ERROR("Error while initializing the Pylon Interface"); return false; } // cout << "BASE CAM NODE INIT FINISHED" << endl; if (!pylon_interface_->registerCameraConfiguration(params_)) { ROS_ERROR("Error while registering the camera configuration"); return false; } // cout << "BASE CAM NODE REGISTER FINISHED" << endl; return true; } bool PylonCameraNode::startGrabbing() { if (!pylon_interface_->startGrabbing(params_)) { ROS_ERROR("Error while start grabbing"); return false; } // Framrate Settings if (pylon_interface_->max_possible_framerate() < params_.desired_frame_rate_) { ROS_INFO("Desired framerate %.2f is higher than max possible. Will limit framerate to: %.2f Hz", params_.desired_frame_rate_, pylon_interface_->max_possible_framerate()); params_.desired_frame_rate_ = pylon_interface_->max_possible_framerate(); nh_.setParam("desired_framerate", pylon_interface_->max_possible_framerate()); } else if (params_.desired_frame_rate_ == -1) { params_.desired_frame_rate_ = pylon_interface_->max_possible_framerate(); ROS_INFO("Max possible framerate is %.2f Hz", pylon_interface_->max_possible_framerate()); } std_msgs::Header header; header.frame_id = params_.camera_frame_; //header.seq = header.stamp = ros::Time::now(); cam_info_msg_.header = header; cam_info_msg_.height = pylon_interface_->img_rows(); cam_info_msg_.width = pylon_interface_->img_cols(); cam_info_msg_.distortion_model = "plumb_bob"; img_raw_msg_.header = header; // Encoding of pixels -- channel meaning, ordering, size // taken from the list of strings in include/sensor_msgs/image_encodings.h img_raw_msg_.encoding = pylon_interface_->img_encoding(); img_raw_msg_.height = pylon_interface_->img_rows(); img_raw_msg_.width = pylon_interface_->img_cols(); // step = full row length in bytes img_raw_msg_.step = img_raw_msg_.width * pylon_interface_->img_pixel_depth(); // img_raw_msg_.data // actual matrix data, size is (step * rows) pylon_interface_->set_image_size(img_raw_msg_.step * img_raw_msg_.height); return true; } bool PylonCameraNode::grabImage() { if (!pylon_interface_->grab(params_, img_raw_msg_.data)) { if (pylon_interface_->is_cam_removed()) { ROS_ERROR("Pylon Camera has been removed!"); ros::shutdown(); } else { ROS_WARN("Pylon Interface returned invalid image! Skipping"); } return false; } img_raw_msg_.header.stamp = ros::Time::now(); cam_info_msg_.header.stamp = img_raw_msg_.header.stamp; return true; } bool PylonCameraNode::setExposureCallback(pylon_camera_msgs::SetExposureSrv::Request &req, pylon_camera_msgs::SetExposureSrv::Response &res) { float current_exposure = getCurrenCurrentExposure(); // ROS_INFO("New exposure request for exposure %.f, current exposure = %.f", req.target_exposure, current_exposure); if (!pylon_interface_->is_ready_) { res.success = false; return true; } if (current_exposure != req.target_exposure) { pylon_interface_->setExposure(req.target_exposure); } // wait for 2 cycles till the cam has updated the exposure ros::Rate r(5.0); ros::Time start = ros::Time::now(); int ctr = 0; while (ros::ok() && ctr < 2) { if (ros::Time::now() - start > ros::Duration(5.0)) { ROS_ERROR("Did not reach the required brightness in time"); res.success = false; return true; } ros::spinOnce(); r.sleep(); ctr++; } current_exposure = getCurrenCurrentExposure(); if (current_exposure == req.target_exposure) { res.success = true; } else { res.success = false; } return true; } bool PylonCameraNode::setBrightnessCallback(pylon_camera_msgs::SetBrightnessSrv::Request &req, pylon_camera_msgs::SetBrightnessSrv::Response &res) { // Brightness Service can only work, if an image has already been grabbed (calc mean on current img) if (!pylon_interface_->is_ready_) { ros::Rate r(2.0); ros::Time start = ros::Time::now(); while (ros::ok() && !pylon_interface_->is_ready_) { if (ros::Time::now() - start > ros::Duration(3.0)) { ROS_ERROR("Pylon Interface has not yet grabbed an image, although waiting for 3 seconds!"); res.success = false; return true; } ros::spinOnce(); r.sleep(); } } // Get actual image ros::spinOnce(); int current_brightness = calcCurrentBrightness(); ROS_INFO("New brightness request for brightness %i, current brightness = %i", req.target_brightness, current_brightness); target_brightness_ = req.target_brightness; brightness_service_running_ = true; if (current_brightness != target_brightness_) { pylon_interface_->setBrightness(target_brightness_); } else { res.success = true; return true; } ros::Duration duration; if (target_brightness_ > 205) { // Need more time for great exposure values duration = ros::Duration(15.0); } else { duration = ros::Duration(5.0); } ros::Rate r(5.0); ros::Time start = ros::Time::now(); while (ros::ok() && brightness_service_running_) { if (ros::Time::now() - start > duration) { ROS_ERROR("Did not reach the required brightness in time"); brightness_service_running_ = false; res.success = false; return true; } ros::spinOnce(); r.sleep(); } if (pylon_interface_->is_opencv_interface_) { if (!brightnessValidation(req.target_brightness)) res.success = false; else res.success = true; return true; } res.success = true; return true; } bool PylonCameraNode::brightnessValidation(int target) { int mean = calcCurrentBrightness(); if (abs(target - mean) > 2) { return false; } return true; } int PylonCameraNode::calcCurrentBrightness() { int sum = std::accumulate(img_raw_msg_.data.begin(), img_raw_msg_.data.end(), 0); assert(img_raw_msg_.data.size() > 0); float mean = sum / img_raw_msg_.data.size(); return (int)mean; } float PylonCameraNode::getCurrenCurrentExposure() { return pylon_interface_->getCurrentExposure(); } /// Warum Service, wenn sofort immer true zurueckgegeben wird? bool PylonCameraNode::setSleepingCallback(pylon_camera_msgs::SetSleepingSrv::Request &req, pylon_camera_msgs::SetSleepingSrv::Response &res) { is_sleeping_ = req.set_sleeping; if (is_sleeping_) { ROS_INFO("Seting Pylon Camera Node to sleep..."); } else { ROS_INFO("Pylon Camera Node continues grabbing"); } res.success = true; return true; } bool PylonCameraNode::is_sleeping() { return is_sleeping_; } bool PylonCameraNode::have_intrinsic_data() { return params_.have_intrinsic_data_; } PylonCameraNode::~PylonCameraNode() { if (!pylon_interface_->is_opencv_interface_) { delete pylon_interface_; pylon_interface_ = NULL; } delete it_; it_ = NULL; } } /* namespace pylon_camera */ <|endoftext|>
<commit_before>#include "bind.hpp" #include "ast.hpp" #include "context.hpp" #include "eval.hpp" #include <map> #include <iostream> #include <sstream> #include "to_string.hpp" namespace Sass { void bind(std::string callee, Parameters* ps, Arguments* as, Context* ctx, Env* env, Eval* eval) { Listize listize(*ctx); std::map<std::string, Parameter*> param_map; for (size_t i = 0, L = as->length(); i < L; ++i) { if (auto str = dynamic_cast<String_Quoted*>((*as)[i]->value())) { // force optional quotes (only if needed) if (str->quote_mark()) { str->quote_mark('*'); str->is_delayed(true); } } } // Set up a map to ensure named arguments refer to actual parameters. Also // eval each default value left-to-right, wrt env, populating env as we go. for (size_t i = 0, L = ps->length(); i < L; ++i) { Parameter* p = (*ps)[i]; param_map[p->name()] = p; // if (p->default_value()) { // env->local_frame()[p->name()] = p->default_value()->perform(eval->with(env)); // } } // plug in all args; if we have leftover params, deal with it later size_t ip = 0, LP = ps->length(); size_t ia = 0, LA = as->length(); while (ia < LA) { Argument* a = (*as)[ia]; if (ip >= LP) { // skip empty rest arguments if (a->is_rest_argument()) { if (List* l = dynamic_cast<List*>(a->value())) { if (l->length() == 0) { ++ ia; continue; } } } std::stringstream msg; msg << callee << " takes " << LP; msg << (LP == 1 ? " argument" : " arguments"); msg << " but " << LA; msg << (LA == 1 ? " was passed" : " were passed."); deprecated_bind(msg.str(), as->pstate()); } Parameter* p = (*ps)[ip]; // If the current parameter is the rest parameter, process and break the loop if (p->is_rest_parameter()) { // The next argument by coincidence provides a rest argument if (a->is_rest_argument()) { // We should always get a list for rest arguments if (List* rest = dynamic_cast<List*>(a->value())) { // arg contains a list List* args = rest; // make sure it's an arglist if (rest->is_arglist()) { // can pass it through as it was env->local_frame()[p->name()] = args; } // create a new list and wrap each item as an argument // otherwise we will not be able to fetch it again else { // create a new list object for wrapped items List* arglist = SASS_MEMORY_NEW(ctx->mem, List, p->pstate(), 0, rest->separator(), true); // wrap each item from list as an argument for (Expression* item : rest->elements()) { (*arglist) << SASS_MEMORY_NEW(ctx->mem, Argument, item->pstate(), item, "", false, false); } // assign new arglist to environment env->local_frame()[p->name()] = arglist; } } // invalid state else { throw std::runtime_error("invalid state"); } } else if (a->is_keyword_argument()) { // expand keyword arguments into their parameters List* arglist = SASS_MEMORY_NEW(ctx->mem, List, p->pstate(), 0, SASS_COMMA, true); env->local_frame()[p->name()] = arglist; Map* argmap = static_cast<Map*>(a->value()); for (auto key : argmap->keys()) { std::string name = unquote(static_cast<String_Constant*>(key)->value()); (*arglist) << SASS_MEMORY_NEW(ctx->mem, Argument, key->pstate(), argmap->at(key), "$" + name, false, false); } } else { // create a new list object for wrapped items List* arglist = SASS_MEMORY_NEW(ctx->mem, List, p->pstate(), 0, SASS_COMMA, true); // consume the next args while (ia < LA) { // get and post inc a = (*as)[ia++]; // maybe we have another list as argument List* ls = dynamic_cast<List*>(a->value()); // skip any list completely if empty if (ls && ls->empty() && a->is_rest_argument()) continue; // flatten all nested arglists if (ls && ls->is_arglist()) { for (size_t i = 0, L = ls->size(); i < L; ++i) { // already have a wrapped argument if (Argument* arg = dynamic_cast<Argument*>((*ls)[i])) { (*arglist) << SASS_MEMORY_NEW(ctx->mem, Argument, *arg); } // wrap all other value types into Argument else { (*arglist) << SASS_MEMORY_NEW(ctx->mem, Argument, (*ls)[i]->pstate(), (*ls)[i], "", false, false); } } } // already have a wrapped argument else if (Argument* arg = dynamic_cast<Argument*>(a->value())) { (*arglist) << SASS_MEMORY_NEW(ctx->mem, Argument, *arg); } // wrap all other value types into Argument else { (*arglist) << SASS_MEMORY_NEW(ctx->mem, Argument, a->pstate(), a->value(), a->name(), false, false); } // check if we have rest argument if (a->is_rest_argument()) { // preserve the list separator from rest args if (List* rest = dynamic_cast<List*>(a->value())) { arglist->separator(rest->separator()); } // no more arguments break; } } // assign new arglist to environment env->local_frame()[p->name()] = arglist; } // consumed parameter ++ip; // no more paramaters break; } // If the current argument is the rest argument, extract a value for processing else if (a->is_rest_argument()) { // normal param and rest arg List* arglist = static_cast<List*>(a->value()); // empty rest arg - treat all args as default values if (!arglist->length()) { break; } else { if (arglist->length() + ia > LP) { int arg_count = (arglist->length() + LA - 1); std::stringstream msg; msg << callee << " takes " << LP; msg << (LP == 1 ? " argument" : " arguments"); msg << " but " << arg_count; msg << (arg_count == 1 ? " was passed" : " were passed."); deprecated_bind(msg.str(), as->pstate()); } } // otherwise move one of the rest args into the param, converting to argument if necessary if (!(a = dynamic_cast<Argument*>((*arglist)[0]))) { Expression* a_to_convert = (*arglist)[0]; a = SASS_MEMORY_NEW(ctx->mem, Argument, a_to_convert->pstate(), a_to_convert, "", false, false); } arglist->elements().erase(arglist->elements().begin()); if (!arglist->length() || (!arglist->is_arglist() && ip + 1 == LP)) { ++ia; } } else if (a->is_keyword_argument()) { Map* argmap = static_cast<Map*>(a->value()); for (auto key : argmap->keys()) { std::string name = "$" + unquote(static_cast<String_Constant*>(key)->value()); if (!param_map.count(name)) { std::stringstream msg; msg << callee << " has no parameter named " << name; error(msg.str(), a->pstate()); } env->local_frame()[name] = argmap->at(key); } ++ia; continue; } else { ++ia; } if (a->name().empty()) { if (env->has_local(p->name())) { std::stringstream msg; msg << "parameter " << p->name() << " provided more than once in call to " << callee; error(msg.str(), a->pstate()); } // ordinal arg -- bind it to the next param env->local_frame()[p->name()] = a->value(); ++ip; } else { // named arg -- bind it to the appropriately named param if (!param_map.count(a->name())) { std::stringstream msg; msg << callee << " has no parameter named " << a->name(); error(msg.str(), a->pstate()); } if (param_map[a->name()]->is_rest_parameter()) { std::stringstream msg; msg << "argument " << a->name() << " of " << callee << "cannot be used as named argument"; error(msg.str(), a->pstate()); } if (env->has_local(a->name())) { std::stringstream msg; msg << "parameter " << p->name() << "provided more than once in call to " << callee; error(msg.str(), a->pstate()); } env->local_frame()[a->name()] = a->value(); } } // EO while ia // If we make it here, we're out of args but may have leftover params. // That's only okay if they have default values, or were already bound by // named arguments, or if it's a single rest-param. for (size_t i = ip; i < LP; ++i) { To_String to_string(ctx); Parameter* leftover = (*ps)[i]; // cerr << "env for default params:" << endl; // env->print(); // cerr << "********" << endl; if (!env->has_local(leftover->name())) { if (leftover->is_rest_parameter()) { env->local_frame()[leftover->name()] = SASS_MEMORY_NEW(ctx->mem, List, leftover->pstate(), 0, SASS_COMMA, true); } else if (leftover->default_value()) { Expression* dv = leftover->default_value()->perform(eval); env->local_frame()[leftover->name()] = dv; } else { // param is unbound and has no default value -- error std::stringstream msg; msg << "required parameter " << leftover->name() << " is missing in call to " << callee; error(msg.str(), as->pstate()); } } } return; } } <commit_msg>Don't throw too many arguments error is there is a rest parameter<commit_after>#include "bind.hpp" #include "ast.hpp" #include "context.hpp" #include "eval.hpp" #include <map> #include <iostream> #include <sstream> #include "to_string.hpp" namespace Sass { void bind(std::string callee, Parameters* ps, Arguments* as, Context* ctx, Env* env, Eval* eval) { Listize listize(*ctx); std::map<std::string, Parameter*> param_map; for (size_t i = 0, L = as->length(); i < L; ++i) { if (auto str = dynamic_cast<String_Quoted*>((*as)[i]->value())) { // force optional quotes (only if needed) if (str->quote_mark()) { str->quote_mark('*'); str->is_delayed(true); } } } // Set up a map to ensure named arguments refer to actual parameters. Also // eval each default value left-to-right, wrt env, populating env as we go. for (size_t i = 0, L = ps->length(); i < L; ++i) { Parameter* p = (*ps)[i]; param_map[p->name()] = p; // if (p->default_value()) { // env->local_frame()[p->name()] = p->default_value()->perform(eval->with(env)); // } } // plug in all args; if we have leftover params, deal with it later size_t ip = 0, LP = ps->length(); size_t ia = 0, LA = as->length(); while (ia < LA) { Argument* a = (*as)[ia]; if (ip >= LP) { // skip empty rest arguments if (a->is_rest_argument()) { if (List* l = dynamic_cast<List*>(a->value())) { if (l->length() == 0) { ++ ia; continue; } } } std::stringstream msg; msg << callee << " takes " << LP; msg << (LP == 1 ? " argument" : " arguments"); msg << " but " << LA; msg << (LA == 1 ? " was passed" : " were passed."); deprecated_bind(msg.str(), as->pstate()); } Parameter* p = (*ps)[ip]; // If the current parameter is the rest parameter, process and break the loop if (p->is_rest_parameter()) { // The next argument by coincidence provides a rest argument if (a->is_rest_argument()) { // We should always get a list for rest arguments if (List* rest = dynamic_cast<List*>(a->value())) { // arg contains a list List* args = rest; // make sure it's an arglist if (rest->is_arglist()) { // can pass it through as it was env->local_frame()[p->name()] = args; } // create a new list and wrap each item as an argument // otherwise we will not be able to fetch it again else { // create a new list object for wrapped items List* arglist = SASS_MEMORY_NEW(ctx->mem, List, p->pstate(), 0, rest->separator(), true); // wrap each item from list as an argument for (Expression* item : rest->elements()) { (*arglist) << SASS_MEMORY_NEW(ctx->mem, Argument, item->pstate(), item, "", false, false); } // assign new arglist to environment env->local_frame()[p->name()] = arglist; } } // invalid state else { throw std::runtime_error("invalid state"); } } else if (a->is_keyword_argument()) { // expand keyword arguments into their parameters List* arglist = SASS_MEMORY_NEW(ctx->mem, List, p->pstate(), 0, SASS_COMMA, true); env->local_frame()[p->name()] = arglist; Map* argmap = static_cast<Map*>(a->value()); for (auto key : argmap->keys()) { std::string name = unquote(static_cast<String_Constant*>(key)->value()); (*arglist) << SASS_MEMORY_NEW(ctx->mem, Argument, key->pstate(), argmap->at(key), "$" + name, false, false); } } else { // create a new list object for wrapped items List* arglist = SASS_MEMORY_NEW(ctx->mem, List, p->pstate(), 0, SASS_COMMA, true); // consume the next args while (ia < LA) { // get and post inc a = (*as)[ia++]; // maybe we have another list as argument List* ls = dynamic_cast<List*>(a->value()); // skip any list completely if empty if (ls && ls->empty() && a->is_rest_argument()) continue; // flatten all nested arglists if (ls && ls->is_arglist()) { for (size_t i = 0, L = ls->size(); i < L; ++i) { // already have a wrapped argument if (Argument* arg = dynamic_cast<Argument*>((*ls)[i])) { (*arglist) << SASS_MEMORY_NEW(ctx->mem, Argument, *arg); } // wrap all other value types into Argument else { (*arglist) << SASS_MEMORY_NEW(ctx->mem, Argument, (*ls)[i]->pstate(), (*ls)[i], "", false, false); } } } // already have a wrapped argument else if (Argument* arg = dynamic_cast<Argument*>(a->value())) { (*arglist) << SASS_MEMORY_NEW(ctx->mem, Argument, *arg); } // wrap all other value types into Argument else { (*arglist) << SASS_MEMORY_NEW(ctx->mem, Argument, a->pstate(), a->value(), a->name(), false, false); } // check if we have rest argument if (a->is_rest_argument()) { // preserve the list separator from rest args if (List* rest = dynamic_cast<List*>(a->value())) { arglist->separator(rest->separator()); } // no more arguments break; } } // assign new arglist to environment env->local_frame()[p->name()] = arglist; } // consumed parameter ++ip; // no more paramaters break; } // If the current argument is the rest argument, extract a value for processing else if (a->is_rest_argument()) { // normal param and rest arg List* arglist = static_cast<List*>(a->value()); // empty rest arg - treat all args as default values if (!arglist->length()) { break; } else { if (arglist->length() + ia > LP && !ps->has_rest_parameter()) { int arg_count = (arglist->length() + LA - 1); std::stringstream msg; msg << callee << " takes " << LP; msg << (LP == 1 ? " argument" : " arguments"); msg << " but " << arg_count; msg << (arg_count == 1 ? " was passed" : " were passed."); deprecated_bind(msg.str(), as->pstate()); } } // otherwise move one of the rest args into the param, converting to argument if necessary if (!(a = dynamic_cast<Argument*>((*arglist)[0]))) { Expression* a_to_convert = (*arglist)[0]; a = SASS_MEMORY_NEW(ctx->mem, Argument, a_to_convert->pstate(), a_to_convert, "", false, false); } arglist->elements().erase(arglist->elements().begin()); if (!arglist->length() || (!arglist->is_arglist() && ip + 1 == LP)) { ++ia; } } else if (a->is_keyword_argument()) { Map* argmap = static_cast<Map*>(a->value()); for (auto key : argmap->keys()) { std::string name = "$" + unquote(static_cast<String_Constant*>(key)->value()); if (!param_map.count(name)) { std::stringstream msg; msg << callee << " has no parameter named " << name; error(msg.str(), a->pstate()); } env->local_frame()[name] = argmap->at(key); } ++ia; continue; } else { ++ia; } if (a->name().empty()) { if (env->has_local(p->name())) { std::stringstream msg; msg << "parameter " << p->name() << " provided more than once in call to " << callee; error(msg.str(), a->pstate()); } // ordinal arg -- bind it to the next param env->local_frame()[p->name()] = a->value(); ++ip; } else { // named arg -- bind it to the appropriately named param if (!param_map.count(a->name())) { std::stringstream msg; msg << callee << " has no parameter named " << a->name(); error(msg.str(), a->pstate()); } if (param_map[a->name()]->is_rest_parameter()) { std::stringstream msg; msg << "argument " << a->name() << " of " << callee << "cannot be used as named argument"; error(msg.str(), a->pstate()); } if (env->has_local(a->name())) { std::stringstream msg; msg << "parameter " << p->name() << "provided more than once in call to " << callee; error(msg.str(), a->pstate()); } env->local_frame()[a->name()] = a->value(); } } // EO while ia // If we make it here, we're out of args but may have leftover params. // That's only okay if they have default values, or were already bound by // named arguments, or if it's a single rest-param. for (size_t i = ip; i < LP; ++i) { To_String to_string(ctx); Parameter* leftover = (*ps)[i]; // cerr << "env for default params:" << endl; // env->print(); // cerr << "********" << endl; if (!env->has_local(leftover->name())) { if (leftover->is_rest_parameter()) { env->local_frame()[leftover->name()] = SASS_MEMORY_NEW(ctx->mem, List, leftover->pstate(), 0, SASS_COMMA, true); } else if (leftover->default_value()) { Expression* dv = leftover->default_value()->perform(eval); env->local_frame()[leftover->name()] = dv; } else { // param is unbound and has no default value -- error std::stringstream msg; msg << "required parameter " << leftover->name() << " is missing in call to " << callee; error(msg.str(), as->pstate()); } } } return; } } <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////// // // File StdMatrixKey.cpp // // For more information, please see: http://www.nektar.info // // The MIT License // // Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA), // Department of Aeronautics, Imperial College London (UK), and Scientific // Computing and Imaging Institute, University of Utah (USA). // // License for the specific language governing rights and limitations under // 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. // // Description: Definition of StdMatrixKey // /////////////////////////////////////////////////////////////////////////////// #include <boost/functional/hash.hpp> #include "StdRegions/StdExpansion.h" #include "StdRegions/StdMatrixKey.h" namespace Nektar { namespace StdRegions { static int s_matrixcnt = 99; StdMatrixKey::StdMatrixKey(const MatrixType matrixType, const ExpansionType expansionType, const StdExpansion &stdExpansion, const ConstFactorMap &factorMap, const VarCoeffMap &varCoeffMap, LibUtilities::PointsType nodalType) : m_expansionType(expansionType), m_base(stdExpansion.GetBase()), m_ncoeffs(stdExpansion.GetNcoeffs()), m_matrixType(matrixType), m_nodalPointsType(nodalType), m_factors(factorMap), m_varcoeffs(varCoeffMap), m_varcoeff_hashes(varCoeffMap.size()) { // Create hash int i = 0; for (VarCoeffMap::const_iterator x = varCoeffMap.begin(); x != varCoeffMap.end(); ++x) { m_varcoeff_hashes[i++] = boost::hash_range(x->second.begin(), x->second.end()); boost::hash_combine(m_varcoeff_hashes[i], x->first); } } StdMatrixKey::StdMatrixKey(const StdMatrixKey& rhs) : m_expansionType(rhs.m_expansionType), m_base(rhs.m_base), m_ncoeffs(rhs.m_ncoeffs), m_matrixType(rhs.m_matrixType), m_nodalPointsType(rhs.m_nodalPointsType), m_factors(rhs.m_factors), m_varcoeffs(rhs.m_varcoeffs), m_varcoeff_hashes(rhs.m_varcoeff_hashes) { } bool StdMatrixKey::opLess::operator()(const StdMatrixKey &lhs, const StdMatrixKey &rhs) const { return (lhs.m_matrixType < rhs.m_matrixType); } bool operator<(const StdMatrixKey &lhs, const StdMatrixKey &rhs) { if(lhs.m_matrixType < rhs.m_matrixType) { return true; } if(lhs.m_matrixType > rhs.m_matrixType) { return false; } if(lhs.m_ncoeffs < rhs.m_ncoeffs) { return true; } if(lhs.m_ncoeffs > rhs.m_ncoeffs) { return false; } for(unsigned int i = 0; i < ExpansionTypeDimMap[lhs.m_expansionType]; ++i) { if(lhs.m_base[i].get() < rhs.m_base[i].get()) { return true; } if(lhs.m_base[i].get() > rhs.m_base[i].get()) { return false; } } if(lhs.m_factors.size() < rhs.m_factors.size()) { return true; } else if(lhs.m_factors.size() > rhs.m_factors.size()) { return false; } else { ConstFactorMap::const_iterator x, y; for(x = lhs.m_factors.begin(), y = rhs.m_factors.begin(); x != lhs.m_factors.end(); ++x, ++y) { if (x->second < y->second) { return true; } if (x->second > y->second) { return false; } } } if(lhs.m_varcoeffs.size() < rhs.m_varcoeffs.size()) { return true; } if(lhs.m_varcoeffs.size() > rhs.m_varcoeffs.size()) { return false; } for (unsigned int i = 0; i < lhs.m_varcoeff_hashes.size(); ++i) { if(lhs.m_varcoeff_hashes[i] < rhs.m_varcoeff_hashes[i]) { return true; } if(lhs.m_varcoeff_hashes[i] > rhs.m_varcoeff_hashes[i]) { return false; } } if(lhs.m_nodalPointsType < rhs.m_nodalPointsType) { return true; } if(lhs.m_nodalPointsType > rhs.m_nodalPointsType) { return false; } return false; } std::ostream& operator<<(std::ostream& os, const StdMatrixKey& rhs) { os << "MatrixType: " << MatrixTypeMap[rhs.GetMatrixType()] << ", ShapeType: " << ExpansionTypeMap[rhs.GetExpansionType()] << ", Ncoeffs: " << rhs.GetNcoeffs() << std::endl; if(rhs.GetConstFactors().size()) { os << "Constants: " << endl; ConstFactorMap::const_iterator x; for(x = rhs.GetConstFactors().begin(); x != rhs.GetConstFactors().end(); ++x) { os << "\t value " << ConstFactorTypeMap[x->first] <<" : " << x->second << endl; } } if(rhs.GetVarCoeffs().size()) { os << "Variable coefficients: " << endl; VarCoeffMap::const_iterator x; unsigned int i = 0; for (x = rhs.GetVarCoeffs().begin(); x != rhs.GetVarCoeffs().end(); ++x) { os << "\t Coeff defined: " << VarCoeffTypeMap[x->first] << endl; os << "\t Hash: " << rhs.GetVarCoeffHashes()[i++] << endl; } } for(unsigned int i = 0; i < ExpansionTypeDimMap[rhs.GetExpansionType()]; ++i) { os << rhs.GetBase()[i]->GetBasisKey(); } return os; } } } /** * $Log: StdMatrixKey.cpp,v $ * Revision 1.17 2009/11/07 21:09:11 sehunchun * Add more functions with various parameters * * Revision 1.16 2009/09/06 22:23:18 sherwin * Somehow deleted opless operator in previous submission * * Revision 1.15 2009/09/06 21:55:26 sherwin * Updates related to Navier Stokes Solver * * Revision 1.14 2008/11/19 16:02:47 pvos * Added functionality for variable Laplacian coeffcients * * Revision 1.13 2008/05/30 00:33:49 delisi * Renamed StdRegions::ShapeType to StdRegions::ExpansionType. * * Revision 1.12 2008/04/06 06:04:15 bnelson * Changed ConstArray to Array<const> * * Revision 1.11 2007/12/17 13:03:51 sherwin * Modified StdMatrixKey to contain a list of constants and GenMatrix to take a StdMatrixKey * * Revision 1.10 2007/08/11 23:42:26 sherwin * A few changes * * Revision 1.9 2007/07/26 02:39:21 bnelson * Fixed Visual C++ compiler errors when compiling in release mode. * * Revision 1.8 2007/07/20 02:16:54 bnelson * Replaced boost::shared_ptr with Nektar::ptr * * Revision 1.7 2007/07/09 15:19:15 sherwin * Introduced an InvMassMatrix and replaced the StdLinSysManager call with a StdMatrixManager call to the inverse matrix * * Revision 1.6 2007/05/15 05:18:23 bnelson * Updated to use the new Array object. * * Revision 1.5 2007/04/10 14:00:45 sherwin * Update to include SharedArray in all 2D element (including Nodal tris). Have also remvoed all new and double from 2D shapes in StdRegions * * Revision 1.4 2007/03/29 19:35:09 bnelson * Replaced boost::shared_array with SharedArray * * Revision 1.3 2007/03/20 16:58:43 sherwin * Update to use Array<OneD, NekDouble> storage and NekDouble usage, compiling and executing up to Demos/StdRegions/Project1D * * Revision 1.2 2007/03/05 08:07:13 sherwin * Modified so that StdMatrixKey has const calling arguments in its constructor. * * Revision 1.1 2007/02/28 19:05:11 sherwin * Moved key definitions to their own files to make things more transparent * * Revision 1.6 2007/02/28 09:53:17 sherwin * Update including adding GetBasis call to StdExpansion * * Revision 1.5 2007/02/24 09:07:25 sherwin * Working version of stdMatrixManager and stdLinSysMatrix * * Revision 1.4 2007/02/23 19:26:04 jfrazier * General bug fix and formatting. * * Revision 1.3 2007/02/22 22:02:27 sherwin * Update with executing StdMatManager * * Revision 1.2 2007/02/22 18:11:31 sherwin * Version with some create functions introduced for StdMatManagers * * Revision 1.1 2007/02/21 22:55:16 sherwin * First integration of StdMatrixManagers * ***/ <commit_msg>Fixed out of range error in var coeff hashing.<commit_after>/////////////////////////////////////////////////////////////////////////////// // // File StdMatrixKey.cpp // // For more information, please see: http://www.nektar.info // // The MIT License // // Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA), // Department of Aeronautics, Imperial College London (UK), and Scientific // Computing and Imaging Institute, University of Utah (USA). // // License for the specific language governing rights and limitations under // 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. // // Description: Definition of StdMatrixKey // /////////////////////////////////////////////////////////////////////////////// #include <boost/functional/hash.hpp> #include "StdRegions/StdExpansion.h" #include "StdRegions/StdMatrixKey.h" namespace Nektar { namespace StdRegions { static int s_matrixcnt = 99; StdMatrixKey::StdMatrixKey(const MatrixType matrixType, const ExpansionType expansionType, const StdExpansion &stdExpansion, const ConstFactorMap &factorMap, const VarCoeffMap &varCoeffMap, LibUtilities::PointsType nodalType) : m_expansionType(expansionType), m_base(stdExpansion.GetBase()), m_ncoeffs(stdExpansion.GetNcoeffs()), m_matrixType(matrixType), m_nodalPointsType(nodalType), m_factors(factorMap), m_varcoeffs(varCoeffMap), m_varcoeff_hashes(varCoeffMap.size()) { // Create hash int i = 0; for (VarCoeffMap::const_iterator x = varCoeffMap.begin(); x != varCoeffMap.end(); ++x) { m_varcoeff_hashes[i] = boost::hash_range(x->second.begin(), x->second.end()); boost::hash_combine(m_varcoeff_hashes[i], x->first); i++; } } StdMatrixKey::StdMatrixKey(const StdMatrixKey& rhs) : m_expansionType(rhs.m_expansionType), m_base(rhs.m_base), m_ncoeffs(rhs.m_ncoeffs), m_matrixType(rhs.m_matrixType), m_nodalPointsType(rhs.m_nodalPointsType), m_factors(rhs.m_factors), m_varcoeffs(rhs.m_varcoeffs), m_varcoeff_hashes(rhs.m_varcoeff_hashes) { } bool StdMatrixKey::opLess::operator()(const StdMatrixKey &lhs, const StdMatrixKey &rhs) const { return (lhs.m_matrixType < rhs.m_matrixType); } bool operator<(const StdMatrixKey &lhs, const StdMatrixKey &rhs) { if(lhs.m_matrixType < rhs.m_matrixType) { return true; } if(lhs.m_matrixType > rhs.m_matrixType) { return false; } if(lhs.m_ncoeffs < rhs.m_ncoeffs) { return true; } if(lhs.m_ncoeffs > rhs.m_ncoeffs) { return false; } for(unsigned int i = 0; i < ExpansionTypeDimMap[lhs.m_expansionType]; ++i) { if(lhs.m_base[i].get() < rhs.m_base[i].get()) { return true; } if(lhs.m_base[i].get() > rhs.m_base[i].get()) { return false; } } if(lhs.m_factors.size() < rhs.m_factors.size()) { return true; } else if(lhs.m_factors.size() > rhs.m_factors.size()) { return false; } else { ConstFactorMap::const_iterator x, y; for(x = lhs.m_factors.begin(), y = rhs.m_factors.begin(); x != lhs.m_factors.end(); ++x, ++y) { if (x->second < y->second) { return true; } if (x->second > y->second) { return false; } } } if(lhs.m_varcoeffs.size() < rhs.m_varcoeffs.size()) { return true; } if(lhs.m_varcoeffs.size() > rhs.m_varcoeffs.size()) { return false; } for (unsigned int i = 0; i < lhs.m_varcoeff_hashes.size(); ++i) { if(lhs.m_varcoeff_hashes[i] < rhs.m_varcoeff_hashes[i]) { return true; } if(lhs.m_varcoeff_hashes[i] > rhs.m_varcoeff_hashes[i]) { return false; } } if(lhs.m_nodalPointsType < rhs.m_nodalPointsType) { return true; } if(lhs.m_nodalPointsType > rhs.m_nodalPointsType) { return false; } return false; } std::ostream& operator<<(std::ostream& os, const StdMatrixKey& rhs) { os << "MatrixType: " << MatrixTypeMap[rhs.GetMatrixType()] << ", ShapeType: " << ExpansionTypeMap[rhs.GetExpansionType()] << ", Ncoeffs: " << rhs.GetNcoeffs() << std::endl; if(rhs.GetConstFactors().size()) { os << "Constants: " << endl; ConstFactorMap::const_iterator x; for(x = rhs.GetConstFactors().begin(); x != rhs.GetConstFactors().end(); ++x) { os << "\t value " << ConstFactorTypeMap[x->first] <<" : " << x->second << endl; } } if(rhs.GetVarCoeffs().size()) { os << "Variable coefficients: " << endl; VarCoeffMap::const_iterator x; unsigned int i = 0; for (x = rhs.GetVarCoeffs().begin(); x != rhs.GetVarCoeffs().end(); ++x) { os << "\t Coeff defined: " << VarCoeffTypeMap[x->first] << endl; os << "\t Hash: " << rhs.GetVarCoeffHashes()[i++] << endl; } } for(unsigned int i = 0; i < ExpansionTypeDimMap[rhs.GetExpansionType()]; ++i) { os << rhs.GetBase()[i]->GetBasisKey(); } return os; } } } /** * $Log: StdMatrixKey.cpp,v $ * Revision 1.17 2009/11/07 21:09:11 sehunchun * Add more functions with various parameters * * Revision 1.16 2009/09/06 22:23:18 sherwin * Somehow deleted opless operator in previous submission * * Revision 1.15 2009/09/06 21:55:26 sherwin * Updates related to Navier Stokes Solver * * Revision 1.14 2008/11/19 16:02:47 pvos * Added functionality for variable Laplacian coeffcients * * Revision 1.13 2008/05/30 00:33:49 delisi * Renamed StdRegions::ShapeType to StdRegions::ExpansionType. * * Revision 1.12 2008/04/06 06:04:15 bnelson * Changed ConstArray to Array<const> * * Revision 1.11 2007/12/17 13:03:51 sherwin * Modified StdMatrixKey to contain a list of constants and GenMatrix to take a StdMatrixKey * * Revision 1.10 2007/08/11 23:42:26 sherwin * A few changes * * Revision 1.9 2007/07/26 02:39:21 bnelson * Fixed Visual C++ compiler errors when compiling in release mode. * * Revision 1.8 2007/07/20 02:16:54 bnelson * Replaced boost::shared_ptr with Nektar::ptr * * Revision 1.7 2007/07/09 15:19:15 sherwin * Introduced an InvMassMatrix and replaced the StdLinSysManager call with a StdMatrixManager call to the inverse matrix * * Revision 1.6 2007/05/15 05:18:23 bnelson * Updated to use the new Array object. * * Revision 1.5 2007/04/10 14:00:45 sherwin * Update to include SharedArray in all 2D element (including Nodal tris). Have also remvoed all new and double from 2D shapes in StdRegions * * Revision 1.4 2007/03/29 19:35:09 bnelson * Replaced boost::shared_array with SharedArray * * Revision 1.3 2007/03/20 16:58:43 sherwin * Update to use Array<OneD, NekDouble> storage and NekDouble usage, compiling and executing up to Demos/StdRegions/Project1D * * Revision 1.2 2007/03/05 08:07:13 sherwin * Modified so that StdMatrixKey has const calling arguments in its constructor. * * Revision 1.1 2007/02/28 19:05:11 sherwin * Moved key definitions to their own files to make things more transparent * * Revision 1.6 2007/02/28 09:53:17 sherwin * Update including adding GetBasis call to StdExpansion * * Revision 1.5 2007/02/24 09:07:25 sherwin * Working version of stdMatrixManager and stdLinSysMatrix * * Revision 1.4 2007/02/23 19:26:04 jfrazier * General bug fix and formatting. * * Revision 1.3 2007/02/22 22:02:27 sherwin * Update with executing StdMatManager * * Revision 1.2 2007/02/22 18:11:31 sherwin * Version with some create functions introduced for StdMatManagers * * Revision 1.1 2007/02/21 22:55:16 sherwin * First integration of StdMatrixManagers * ***/ <|endoftext|>
<commit_before>#if defined(LINUX) #include "user/util.h" #include "types.h" #include <fcntl.h> #include <unistd.h> #include <assert.h> #include <sys/stat.h> #include <sys/wait.h> #include "xsys.h" #else #include "types.h" #include "stat.h" #include "user.h" #include "mtrace.h" #include "amd64.h" #include "fcntl.h" #include "xsys.h" #endif static const bool pinit = true; enum { nfile = 10 }; enum { nlookup = 100 }; void bench(u32 tid, int nloop, const char* path) { char pn[32]; if (pinit) setaffinity(tid); for (u32 x = 0; x < nloop; x++) { for (u32 i = 0; i < nfile; i++) { snprintf(pn, sizeof(pn), "%s/f:%d:%d", path, tid, i); int fd = xcreat(pn); if (fd < 0) die("create failed\n"); close(fd); } for (u32 i = 0; i < nlookup; i++) { snprintf(pn, sizeof(pn), "%s/f:%d:%d", path, tid, (i % nfile)); int fd = open(pn, O_RDWR); if (fd < 0) die("open failed %s", pn); close(fd); } for (u32 i = 0; i < nfile; i++) { snprintf(pn, sizeof(pn), "%s/f:%d:%d", path, tid, i); if (unlink(pn) < 0) die("unlink failed\n"); } } xexit(); } int main(int ac, char** av) { const char* path; int nthread; int nloop; #ifdef HW_qemu nloop = 50; #else nloop = 1000; #endif path = "/dbx"; if (ac < 2) die("usage: %s nthreads [nloop] [path]", av[0]); nthread = atoi(av[1]); if (ac > 2) nloop = atoi(av[2]); if (ac > 3) path = av[3]; xmkdir(path); mtenable("xv6-dirbench"); u64 t0 = rdtsc(); for(u32 i = 0; i < nthread; i++) { int pid = xfork(); if (pid == 0) bench(i, nloop, path); else if (pid < 0) die("fork"); } for (u32 i = 0; i < nthread; i++) xwait(); u64 t1 = rdtsc(); mtdisable("xv6-dirbench"); printf("dirbench: %lu\n", t1-t0); return 0; } <commit_msg>Tweak dirbench to start mtrace after setup<commit_after>#if defined(LINUX) #include "user/util.h" #include "types.h" #include <fcntl.h> #include <unistd.h> #include <assert.h> #include <sys/stat.h> #include <sys/wait.h> #include "xsys.h" #else #include "types.h" #include "stat.h" #include "user.h" #include "mtrace.h" #include "amd64.h" #include "fcntl.h" #include "xsys.h" #endif static const bool pinit = true; enum { nfile = MTRACE ? 2 : 10 }; enum { nlookup = MTRACE ? 2 : 100 }; void bench(u32 tid, int nloop, const char* path) { char pn[32]; if (pinit) setaffinity(tid); for (u32 x = 0; x < nloop; x++) { for (u32 i = 0; i < nfile; i++) { snprintf(pn, sizeof(pn), "%s/f:%d:%d", path, tid, i); int fd = xcreat(pn); if (fd < 0) die("create failed\n"); close(fd); } for (u32 i = 0; i < nlookup; i++) { snprintf(pn, sizeof(pn), "%s/f:%d:%d", path, tid, (i % nfile)); int fd = open(pn, O_RDWR); if (fd < 0) die("open failed %s", pn); close(fd); } for (u32 i = 0; i < nfile; i++) { snprintf(pn, sizeof(pn), "%s/f:%d:%d", path, tid, i); if (unlink(pn) < 0) die("unlink failed\n"); } } xexit(); } int main(int ac, char** av) { const char* path; int nthread; int nloop; #ifdef HW_qemu nloop = 50; #else nloop = 1000; #endif path = "/dbx"; if (ac < 2) die("usage: %s nthreads [nloop] [path]", av[0]); nthread = atoi(av[1]); if (ac > 2) nloop = atoi(av[2]); if (ac > 3) path = av[3]; xmkdir(path); int start[2]; if (pipe(start) < 0) die("pipe"); u64 t0 = rdtsc(); for(u32 i = 0; i < nthread; i++) { int pid = xfork(); if (pid == 0) { close(start[1]); char token; if (read(start[0], &token, 1) < 1) die("read"); bench(i, nloop, path); } else if (pid < 0) die("fork"); } mtenable_type(mtrace_record_ascope, "xv6-dirbench"); const char wakeup[256] = {}; if (write(start[1], wakeup, nthread) < nthread) die("write"); for (u32 i = 0; i < nthread; i++) xwait(); u64 t1 = rdtsc(); mtdisable("xv6-dirbench"); printf("dirbench: %lu\n", t1-t0); return 0; } <|endoftext|>
<commit_before>/* * Copyright (C) 2010 Toni Gundogdu. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "config.h" #include <ctime> #include <boost/foreach.hpp> #include <boost/random.hpp> #include <curl/curl.h> #ifndef foreach #define foreach BOOST_FOREACH #endif #include "cclive/application.h" #include "cclive/get.h" #include "cclive/error.h" #include "cclive/log.h" #include "cclive/background.h" namespace cclive { static boost::mt19937 _rng; static void rand_decor () { boost::uniform_int<> r(2,5); boost::variate_generator<boost::mt19937&, boost::uniform_int<> > v(_rng,r); const int n = v(); for (int i=0; i<n; ++i) cclive::log << "."; } static void handle_fetch (const quvi_word type, void*) { rand_decor(); if (type == QUVISTATUSTYPE_DONE) cclive::log << " "; } static void handle_verify (const quvi_word type) { rand_decor(); if (type == QUVISTATUSTYPE_DONE) cclive::log << "done.\n"; } static int status_callback (long param, void *ptr) { const quvi_word status = quvi_loword(param); const quvi_word type = quvi_hiword(param); switch (status) { case QUVISTATUS_FETCH : handle_fetch (type,ptr); break; case QUVISTATUS_VERIFY: handle_verify(type); break; } cclive::log << std::flush; return QUVI_OK; } template<class Iterator> static Iterator make_unique (Iterator first, Iterator last) { while (first != last) { Iterator next (first); last = std::remove (++next, last, *first); first = next; } return last; } extern char LICENSE[]; // cclive/license.cpp int application::exec (int argc, char **argv) { try { _opts.exec(argc,argv); } catch (const std::exception& x) { std::clog << "error: " << x.what() << std::endl; return invalid_option; } const boost::program_options::variables_map map = _opts.map(); // Dump and terminate options. if (map.count("help")) { std::clog << _opts; return ok; } if (map.count("version")) { std::clog << "cclive version " << VERSION_LONG << std::endl; return ok; } if (map.count("license")) { std::clog << LICENSE << std::endl; return ok; } // Set up quvicpp. quvicpp::query query; // Throws quvicpp::error caught in main.cpp . if (map.count("support")) { std::clog << quvicpp::support_to_s (query.support ()) << std::flush; return ok; } // Parse input. std::vector<std::string> input; if (map.count("url")) input = map["url"].as< std::vector<std::string> >(); else _read_stdin (input); // Remove duplicates. input.erase (make_unique (input.begin(), input.end()), input.end()); // Turn on libcurl verbose output. if (map.count("verbose-libcurl")) curl_easy_setopt (query.curlHandle(), CURLOPT_VERBOSE, 1L); // Set up quvicpp. _tweak_curl_opts(query,map); quvicpp::options qopts; qopts.statusfunc (status_callback); qopts.format (map["format"].as<std::string>()); // Seed random generator. _rng.seed ( static_cast<unsigned int>(std::time(0)) ); // Omit flag. bool omit = map.count ("quiet"); // Go to background. if (map.count ("background")) { // Throws std::runtime_error if fails. cclive::go_background (map["log-file"].as<std::string>(), omit); } // Omit std output. Note that --background flips this above. cclive::log.push (cclive::omit_sink (omit)); // For each input URL. const size_t n = input.size(); size_t i = 0; foreach(std::string url, input) { try { if (n > 1) cclive::log << "(" << ++i << " of " << n << ") "; cclive::log << "Checking "; quvicpp::video v = query.parse (url, qopts); cclive::get (query, v, _opts); } catch (const quvicpp::error& e) { cclive::log << "libquvi: error: " << e.what() << std::endl; } catch (const std::runtime_error& e) { cclive::log << "error: " << e.what() << std::endl; } } return ok; } void application::_read_stdin (std::vector<std::string>& dst) { std::string s; char ch = 0; while (std::cin.get(ch)) s += ch; std::istringstream iss(s); std::copy( std::istream_iterator<std::string >(iss), std::istream_iterator<std::string >(), std::back_inserter<std::vector<std::string> >(dst) ); } void application::_tweak_curl_opts ( const quvicpp::query& query, const boost::program_options::variables_map& map) { CURL *curl = query.curlHandle(); curl_easy_setopt(curl, CURLOPT_USERAGENT, map["agent"].as<std::string>().c_str()); if (map.count("verbose-curl")) curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); if (map.count("proxy")) { curl_easy_setopt(curl, CURLOPT_PROXY, map["proxy"].as<std::string>().c_str()); } if (map.count("no-proxy")) curl_easy_setopt(curl, CURLOPT_PROXY, ""); if (map.count("throttle")) { curl_off_t limit = map["throttle"].as<int>()*1024; curl_easy_setopt(curl, CURLOPT_MAX_RECV_SPEED_LARGE, limit); } curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, map["connect-timeout"].as<int>()); } } // End namespace. <commit_msg>add libquvi to --version output.<commit_after>/* * Copyright (C) 2010 Toni Gundogdu. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "config.h" #include <ctime> #include <boost/foreach.hpp> #include <boost/random.hpp> #include <curl/curl.h> #ifndef foreach #define foreach BOOST_FOREACH #endif #include "cclive/application.h" #include "cclive/get.h" #include "cclive/error.h" #include "cclive/log.h" #include "cclive/background.h" namespace cclive { static boost::mt19937 _rng; static void rand_decor () { boost::uniform_int<> r(2,5); boost::variate_generator<boost::mt19937&, boost::uniform_int<> > v(_rng,r); const int n = v(); for (int i=0; i<n; ++i) cclive::log << "."; } static void handle_fetch (const quvi_word type, void*) { rand_decor(); if (type == QUVISTATUSTYPE_DONE) cclive::log << " "; } static void handle_verify (const quvi_word type) { rand_decor(); if (type == QUVISTATUSTYPE_DONE) cclive::log << "done.\n"; } static int status_callback (long param, void *ptr) { const quvi_word status = quvi_loword(param); const quvi_word type = quvi_hiword(param); switch (status) { case QUVISTATUS_FETCH : handle_fetch (type,ptr); break; case QUVISTATUS_VERIFY: handle_verify(type); break; } cclive::log << std::flush; return QUVI_OK; } template<class Iterator> static Iterator make_unique (Iterator first, Iterator last) { while (first != last) { Iterator next (first); last = std::remove (++next, last, *first); first = next; } return last; } extern char LICENSE[]; // cclive/license.cpp int application::exec (int argc, char **argv) { try { _opts.exec(argc,argv); } catch (const std::exception& x) { std::clog << "error: " << x.what() << std::endl; return invalid_option; } const boost::program_options::variables_map map = _opts.map(); // Dump and terminate options. if (map.count("help")) { std::clog << _opts; return ok; } if (map.count("version")) { std::clog << "cclive version " << VERSION_LONG << "\n" << "libquvi version " << quvi_version (QUVI_VERSION_LONG) << std::endl; return ok; } if (map.count("license")) { std::clog << LICENSE << std::endl; return ok; } // Set up quvicpp. quvicpp::query query; // Throws quvicpp::error caught in main.cpp . if (map.count("support")) { std::clog << quvicpp::support_to_s (query.support ()) << std::flush; return ok; } // Parse input. std::vector<std::string> input; if (map.count("url")) input = map["url"].as< std::vector<std::string> >(); else _read_stdin (input); // Remove duplicates. input.erase (make_unique (input.begin(), input.end()), input.end()); // Turn on libcurl verbose output. if (map.count("verbose-libcurl")) curl_easy_setopt (query.curlHandle(), CURLOPT_VERBOSE, 1L); // Set up quvicpp. _tweak_curl_opts(query,map); quvicpp::options qopts; qopts.statusfunc (status_callback); qopts.format (map["format"].as<std::string>()); // Seed random generator. _rng.seed ( static_cast<unsigned int>(std::time(0)) ); // Omit flag. bool omit = map.count ("quiet"); // Go to background. if (map.count ("background")) { // Throws std::runtime_error if fails. cclive::go_background (map["log-file"].as<std::string>(), omit); } // Omit std output. Note that --background flips this above. cclive::log.push (cclive::omit_sink (omit)); // For each input URL. const size_t n = input.size(); size_t i = 0; foreach(std::string url, input) { try { if (n > 1) cclive::log << "(" << ++i << " of " << n << ") "; cclive::log << "Checking "; quvicpp::video v = query.parse (url, qopts); cclive::get (query, v, _opts); } catch (const quvicpp::error& e) { cclive::log << "libquvi: error: " << e.what() << std::endl; } catch (const std::runtime_error& e) { cclive::log << "error: " << e.what() << std::endl; } } return ok; } void application::_read_stdin (std::vector<std::string>& dst) { std::string s; char ch = 0; while (std::cin.get(ch)) s += ch; std::istringstream iss(s); std::copy( std::istream_iterator<std::string >(iss), std::istream_iterator<std::string >(), std::back_inserter<std::vector<std::string> >(dst) ); } void application::_tweak_curl_opts ( const quvicpp::query& query, const boost::program_options::variables_map& map) { CURL *curl = query.curlHandle(); curl_easy_setopt(curl, CURLOPT_USERAGENT, map["agent"].as<std::string>().c_str()); if (map.count("verbose-curl")) curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); if (map.count("proxy")) { curl_easy_setopt(curl, CURLOPT_PROXY, map["proxy"].as<std::string>().c_str()); } if (map.count("no-proxy")) curl_easy_setopt(curl, CURLOPT_PROXY, ""); if (map.count("throttle")) { curl_off_t limit = map["throttle"].as<int>()*1024; curl_easy_setopt(curl, CURLOPT_MAX_RECV_SPEED_LARGE, limit); } curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, map["connect-timeout"].as<int>()); } } // End namespace. <|endoftext|>
<commit_before>/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/plot/Attic/CPlotSpec2Vector.cpp,v $ $Revision: 1.5 $ $Name: $ $Author: ssahle $ $Date: 2004/10/08 09:21:43 $ End CVS Header */ #include "copasi.h" #include "CPlotSpec2Vector.h" #include "report/CKeyFactory.h" #include "report/CCopasiObjectReference.h" #include "model/CModel.h" #include "plotwindow.h" #include "utilities/CGlobals.h" CPlotSpec2Vector::CPlotSpec2Vector(const std::string & name, const CCopasiContainer * pParent): CCopasiVectorN<CPlotSpecification>(name, pParent), mKey(GlobalKeys.add("CPlotSpecificationVector", this)), inputFlag(NO_INPUT) {} CPlotSpec2Vector::~CPlotSpec2Vector() { cleanup(); } void CPlotSpec2Vector::cleanup() { GlobalKeys.remove(mKey); } const std::string& CPlotSpec2Vector::getKey() { return mKey; } CPlotSpecification* CPlotSpec2Vector::createPlotSpec(const std::string & name, CPlotItem::Type type) { unsigned C_INT32 i; for (i = 0; i < size(); i++) if ((*this)[i]->getObjectName() == name) return NULL; // duplicate name CPlotSpecification* pNewPlotSpec = new CPlotSpecification(name, this, type); pNewPlotSpec->setObjectName(name); add(pNewPlotSpec); return pNewPlotSpec; } bool CPlotSpec2Vector::removePlotSpec(const std::string & key) { CPlotSpecification* pPl = dynamic_cast<CPlotSpecification*>(GlobalKeys.get(key)); unsigned C_INT32 index = this->CCopasiVector<CPlotSpecification>::getIndex(pPl); if (index == C_INVALID_INDEX) return false; this->CCopasiVector<CPlotSpecification>::remove(index); return true; } bool CPlotSpec2Vector::initPlottingFromObjects() { inputFlag = NO_INPUT; if (size() == 0) { std::cout << "plot: not plots defined" << std::endl; return false; } mObjectNames.resize(0); if (!initAllPlots()) //create mObjectNames; { std::cout << "plot: problem while creating indices" << std::endl; return false; } if (mObjectNames.size() <= 0) { std::cout << "plot: number of objects <=0" << std::endl; return false; } data.resize(mObjectNames.size()); inputFlag = FROM_OBJECTS; mTime.init(); return compile(); //create mObjects } bool CPlotSpec2Vector::sendDataToAllPlots() { std::vector<PlotWindow*>::const_iterator it; for (it = windows.begin(); it != windows.end(); ++it) { (*it)->takeData(data); } return true; } bool CPlotSpec2Vector::updateAllPlots() { std::vector<PlotWindow*>::const_iterator it; for (it = windows.begin(); it != windows.end(); ++it) { (*it)->updatePlot(); } return true; } bool CPlotSpec2Vector::initAllPlots() { windows.resize(0); //step through the vector of specifications and create the plot windows std::string key; const_iterator it; for (it = begin(); it != end(); ++it) { if ((*it)->isActive()) { key = (*it)->CCopasiParameter::getKey(); std::cout << key << std::endl; if (windowMap[key] == NULL) { windowMap[key] = new PlotWindow(this, *it); } else { windowMap[key]->initFromSpec(this, *it); } windowMap[key]->show(); windows.push_back(windowMap[key]); } } return true; } bool CPlotSpec2Vector::doPlotting() { bool success = true; if (inputFlag == FROM_OBJECTS) { unsigned C_INT32 i = 0; std::vector<CCopasiObject*>::const_iterator it = mObjects.begin(); for (; it != mObjects.end(); ++it, ++i) { data[i] = *(C_FLOAT64*)(((CCopasiObjectReference<C_FLOAT64>*)(*it))->getReference()); //std::cout << "debug1: " << *(C_FLOAT64*)(((CCopasiObjectReference<C_FLOAT64>*)(*it))->getReference())<< std::endl; //std::cout << "debug2: " << data[i] << std::endl; //(*it)->print(&std::cout); } sendDataToAllPlots(); } else { //std::cout << "doPlotting: no input method" << std::endl; return false; } if (mTime.getTimeDiff() > 200) { updateAllPlots(); mTime.init(); } return success; } bool CPlotSpec2Vector::finishPlotting() { return updateAllPlots(); } C_INT32 CPlotSpec2Vector::getIndexFromCN(const CCopasiObjectName & name) { //first look up the name in the vector std::vector<CCopasiObjectName>::const_iterator it; for (it = mObjectNames.begin(); it != mObjectNames.end(); ++it) if (*it == name) break; if (it != mObjectNames.end()) return (it - mObjectNames.begin()); //the name is not yet in the list mObjectNames.push_back(name); return mObjectNames.size() - 1; } bool CPlotSpec2Vector::compile() { mObjects.clear(); CCopasiObject* pSelected; std::vector<CCopasiObjectName>::const_iterator it; for (it = mObjectNames.begin(); it != mObjectNames.end(); ++it) { //std::cout << "CPlotSpecVector::compile " << *it << std::endl; pSelected = CCopasiContainer::ObjectFromName(*it); if (!pSelected) { //std::cout << "Object not found!" << std::endl; return false; } //TODO check hasValue() //std::cout << " compile: " << pSelected->getObjectName() << std::endl; mObjects.push_back(pSelected); } return true; //success; } <commit_msg>now deals better with unresolvable object CNs<commit_after>/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/plot/Attic/CPlotSpec2Vector.cpp,v $ $Revision: 1.6 $ $Name: $ $Author: ssahle $ $Date: 2004/10/09 14:42:38 $ End CVS Header */ #include "copasi.h" #include "CPlotSpec2Vector.h" #include "report/CKeyFactory.h" #include "report/CCopasiObjectReference.h" #include "model/CModel.h" #include "plotwindow.h" #include "utilities/CGlobals.h" CPlotSpec2Vector::CPlotSpec2Vector(const std::string & name, const CCopasiContainer * pParent): CCopasiVectorN<CPlotSpecification>(name, pParent), mKey(GlobalKeys.add("CPlotSpecificationVector", this)), inputFlag(NO_INPUT) {} CPlotSpec2Vector::~CPlotSpec2Vector() { cleanup(); } void CPlotSpec2Vector::cleanup() { GlobalKeys.remove(mKey); } const std::string& CPlotSpec2Vector::getKey() { return mKey; } CPlotSpecification* CPlotSpec2Vector::createPlotSpec(const std::string & name, CPlotItem::Type type) { unsigned C_INT32 i; for (i = 0; i < size(); i++) if ((*this)[i]->getObjectName() == name) return NULL; // duplicate name CPlotSpecification* pNewPlotSpec = new CPlotSpecification(name, this, type); pNewPlotSpec->setObjectName(name); add(pNewPlotSpec); return pNewPlotSpec; } bool CPlotSpec2Vector::removePlotSpec(const std::string & key) { CPlotSpecification* pPl = dynamic_cast<CPlotSpecification*>(GlobalKeys.get(key)); unsigned C_INT32 index = this->CCopasiVector<CPlotSpecification>::getIndex(pPl); if (index == C_INVALID_INDEX) return false; this->CCopasiVector<CPlotSpecification>::remove(index); return true; } bool CPlotSpec2Vector::initPlottingFromObjects() { inputFlag = NO_INPUT; if (size() == 0) { std::cout << "plot: not plots defined" << std::endl; return false; } mObjectNames.resize(0); if (!initAllPlots()) //create mObjectNames; { std::cout << "plot: problem while creating indices" << std::endl; return false; } if (mObjectNames.size() <= 0) { std::cout << "plot: number of objects <=0" << std::endl; return false; } data.resize(mObjectNames.size()); inputFlag = FROM_OBJECTS; mTime.init(); return compile(); //create mObjects } bool CPlotSpec2Vector::sendDataToAllPlots() { std::vector<PlotWindow*>::const_iterator it; for (it = windows.begin(); it != windows.end(); ++it) { (*it)->takeData(data); } return true; } bool CPlotSpec2Vector::updateAllPlots() { std::vector<PlotWindow*>::const_iterator it; for (it = windows.begin(); it != windows.end(); ++it) { (*it)->updatePlot(); } return true; } bool CPlotSpec2Vector::initAllPlots() { windows.resize(0); //step through the vector of specifications and create the plot windows std::string key; const_iterator it; for (it = begin(); it != end(); ++it) { if ((*it)->isActive()) { key = (*it)->CCopasiParameter::getKey(); std::cout << key << std::endl; if (windowMap[key] == NULL) { windowMap[key] = new PlotWindow(this, *it); } else { windowMap[key]->initFromSpec(this, *it); } windowMap[key]->show(); windows.push_back(windowMap[key]); } } return true; } bool CPlotSpec2Vector::doPlotting() { bool success = true; if (inputFlag == FROM_OBJECTS) { unsigned C_INT32 i = 0; std::vector<CCopasiObject*>::const_iterator it = mObjects.begin(); for (; it != mObjects.end(); ++it, ++i) { if (*it) data[i] = *(C_FLOAT64*)(((CCopasiObjectReference<C_FLOAT64>*)(*it))->getReference()); else data[i] = 0; //std::cout << "debug1: " << *(C_FLOAT64*)(((CCopasiObjectReference<C_FLOAT64>*)(*it))->getReference())<< std::endl; //std::cout << "debug2: " << data[i] << std::endl; //(*it)->print(&std::cout); } sendDataToAllPlots(); } else { //std::cout << "doPlotting: no input method" << std::endl; return false; } if (mTime.getTimeDiff() > 200) { updateAllPlots(); mTime.init(); } return success; } bool CPlotSpec2Vector::finishPlotting() { return updateAllPlots(); } C_INT32 CPlotSpec2Vector::getIndexFromCN(const CCopasiObjectName & name) { //first look up the name in the vector std::vector<CCopasiObjectName>::const_iterator it; for (it = mObjectNames.begin(); it != mObjectNames.end(); ++it) if (*it == name) break; if (it != mObjectNames.end()) return (it - mObjectNames.begin()); //the name is not yet in the list mObjectNames.push_back(name); return mObjectNames.size() - 1; } bool CPlotSpec2Vector::compile() { mObjects.clear(); CCopasiObject* pSelected; std::vector<CCopasiObjectName>::const_iterator it; for (it = mObjectNames.begin(); it != mObjectNames.end(); ++it) { //std::cout << "CPlotSpecVector::compile " << *it << std::endl; pSelected = CCopasiContainer::ObjectFromName(*it); if (!pSelected) { //std::cout << "Object not found!" << std::endl; mObjects.push_back(NULL); //return false; } //TODO check hasValue() //std::cout << " compile: " << pSelected->getObjectName() << std::endl; mObjects.push_back(pSelected); } return true; //success; } <|endoftext|>
<commit_before>// Copyright (C) 2017 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and University of // of Connecticut School of Medicine. // All rights reserved. // Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. // Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. // Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. /** * CTSSATask class. * * This class implements a time scale separation analysis task which is comprised of a * of a problem and a method. Additionally calls to the reporting * methods are done when initialized. * */ #include <string> #include "copasi.h" #include "CTSSATask.h" #include "CTSSAProblem.h" #include "CTSSAMethod.h" #include "math/CMathContainer.h" #include "report/CKeyFactory.h" #include "report/CReport.h" #include "utilities/CProcessReport.h" #include "utilities/CCopasiException.h" #include "CopasiDataModel/CDataModel.h" #define XXXX_Reporting bool tfle(const C_FLOAT64 & d1, const C_FLOAT64 & d2) {return (d1 <= d2);} bool tfl(const C_FLOAT64 & d1, const C_FLOAT64 & d2) {return (d1 < d2);} bool tble(const C_FLOAT64 & d1, const C_FLOAT64 & d2) {return (d1 >= d2);} bool tbl(const C_FLOAT64 & d1, const C_FLOAT64 & d2) {return (d1 > d2);} // static const CTaskEnum::Method CTSSATask::ValidMethods[] = { CTaskEnum::Method::tssILDM, CTaskEnum::Method::tssILDMModified, CTaskEnum::Method::tssCSP, CTaskEnum::Method::UnsetMethod }; CTSSATask::CTSSATask(const CDataContainer * pParent, const CTaskEnum::Task & type): CCopasiTask(pParent, type), mTimeSeriesRequested(true), mTimeSeries(), mpTSSAProblem(NULL), mpTSSAMethod(NULL), mContainerState(), mpContainerStateTime(NULL) { mpProblem = new CTSSAProblem(this); mpMethod = createMethod(CTaskEnum::Method::tssILDM); CCopasiParameter * pParameter = mpMethod->getParameter("Integrate Reduced Model"); if (pParameter != NULL) mUpdateMoieties = pParameter->getValue< bool >(); else mUpdateMoieties = false; } CTSSATask::CTSSATask(const CTSSATask & src, const CDataContainer * pParent): CCopasiTask(src, pParent), mTimeSeriesRequested(src.mTimeSeriesRequested), mTimeSeries(), mpTSSAProblem(NULL), mpTSSAMethod(NULL), mContainerState(), mpContainerStateTime(NULL) { mpProblem = new CTSSAProblem(*static_cast< CTSSAProblem * >(src.mpProblem), this); mpMethod = createMethod(src.mpMethod->getSubType()); * mpMethod = * src.mpMethod; mpMethod->elevateChildren(); this->add(mpMethod, true); CCopasiParameter * pParameter = mpMethod->getParameter("Integrate Reduced Model"); if (pParameter != NULL) mUpdateMoieties = pParameter->getValue< bool >(); else mUpdateMoieties = false; } CTSSATask::~CTSSATask() {} bool CTSSATask::updateMatrices() { assert(mpProblem != NULL && mpMethod != NULL); assert(dynamic_cast<CTSSAProblem *>(mpProblem) != NULL); if (!mpMethod->isValidProblem(mpProblem)) return false; CTSSAMethod * pMethod = dynamic_cast<CTSSAMethod*>(mpMethod); if (!pMethod) return false; pMethod->initializeOutput(); return true; } bool CTSSATask::initialize(const OutputFlag & of, COutputHandler * pOutputHandler, std::ostream * pOstream) { assert(mpProblem && mpMethod); mpTSSAProblem = dynamic_cast<CTSSAProblem *>(mpProblem); assert(mpTSSAProblem); mpTSSAMethod = dynamic_cast<CTSSAMethod *>(mpMethod); assert(mpTSSAMethod); mpTSSAMethod->setProblem(mpTSSAProblem); bool success = mpMethod->isValidProblem(mpProblem); CCopasiParameter * pParameter = mpMethod->getParameter("Integrate Reduced Model"); if (pParameter != NULL) mUpdateMoieties = pParameter->getValue< bool >(); else mUpdateMoieties = false; // Handle the time series as a regular output. mTimeSeriesRequested = mpTSSAProblem->timeSeriesRequested(); if (pOutputHandler != NULL) { if (mTimeSeriesRequested) { mTimeSeries.allocate(mpTSSAProblem->getStepNumber()); pOutputHandler->addInterface(&mTimeSeries); } else { mTimeSeries.clear(); } } mpTSSAMethod->initializeOutput(); success &= CCopasiTask::initialize(of, pOutputHandler, pOstream); mContainerState.initialize(mpContainer->getState(mUpdateMoieties)); mpContainerStateTime = mContainerState.array() + mpContainer->getCountFixedEventTargets(); return success; } bool CTSSATask::process(const bool & useInitialValues) { //***** processStart(useInitialValues); //***** C_FLOAT64 StepSize = mpTSSAProblem->getStepSize(); C_FLOAT64 NextTimeToReport; const C_FLOAT64 EndTime = *mpContainerStateTime + mpTSSAProblem->getDuration(); const C_FLOAT64 StartTime = *mpContainerStateTime; C_FLOAT64 StepNumber = (mpTSSAProblem->getDuration()) / StepSize; bool (*LE)(const C_FLOAT64 &, const C_FLOAT64 &); bool (*L)(const C_FLOAT64 &, const C_FLOAT64 &); if (StepSize < 0.0) { LE = &tble; L = &tbl; } else { LE = &tfle; L = &tfl; } size_t StepCounter = 1; C_FLOAT64 outputStartTime = mpTSSAProblem->getOutputStartTime(); if (StepSize == 0.0 && mpTSSAProblem->getDuration() != 0.0) { CCopasiMessage(CCopasiMessage::ERROR, MCTSSAProblem + 1, StepSize); return false; } output(COutputInterface::BEFORE); bool flagProceed = true; C_FLOAT64 handlerFactor = 100.0 / mpTSSAProblem->getDuration(); C_FLOAT64 Percentage = 0; size_t hProcess; if (mpCallBack) { mpCallBack->setName("performing simulation..."); C_FLOAT64 hundred = 100; hProcess = mpCallBack->addItem("Completion", Percentage, &hundred); } //if ((*LE)(outputStartTime, *mpContainerStateTime)) output(COutputInterface::DURING); try { do { // This is numerically more stable then adding // mpTSSAProblem->getStepSize(). NextTimeToReport = StartTime + (EndTime - StartTime) * StepCounter++ / StepNumber; flagProceed &= processStep(NextTimeToReport); if (mpCallBack) { Percentage = (*mpContainerStateTime - StartTime) * handlerFactor; flagProceed &= mpCallBack->progressItem(hProcess); } if ((*LE)(outputStartTime, *mpContainerStateTime)) { output(COutputInterface::DURING); } } while ((*L)(*mpContainerStateTime, EndTime) && flagProceed); } catch (int) { mpContainer->updateSimulatedValues(mUpdateMoieties); if ((*LE)(outputStartTime, *mpContainerStateTime)) { output(COutputInterface::DURING); } if (mpCallBack) mpCallBack->finishItem(hProcess); output(COutputInterface::AFTER); CCopasiMessage(CCopasiMessage::EXCEPTION, MCTSSAMethod + 4); } catch (CCopasiException & Exception) { mpContainer->updateSimulatedValues(mUpdateMoieties); if ((*LE)(outputStartTime, *mpContainerStateTime)) { output(COutputInterface::DURING); } if (mpCallBack) mpCallBack->finishItem(hProcess); output(COutputInterface::AFTER); throw CCopasiException(Exception.getMessage()); } if (mpCallBack) mpCallBack->finishItem(hProcess); output(COutputInterface::AFTER); return true; } void CTSSATask::processStart(const bool & useInitialValues) { if (useInitialValues) { mpContainer->applyInitialValues(); } mContainerState.initialize(mpContainer->getState(mUpdateMoieties)); mpTSSAMethod->start(); return; } bool CTSSATask::processStep(const C_FLOAT64 & nextTime) { C_FLOAT64 CompareTime = nextTime - 100.0 * fabs(nextTime) * std::numeric_limits< C_FLOAT64 >::epsilon(); if (*mpContainerStateTime <= CompareTime) { do { mpTSSAMethod->step(nextTime - *mpContainerStateTime); if (*mpContainerStateTime > CompareTime) break; /* Here we will do conditional event processing */ /* Currently this is correct since no events are processed. */ CCopasiMessage(CCopasiMessage::EXCEPTION, MCTSSAMethod + 3); } while (true); mpContainer->updateSimulatedValues(mUpdateMoieties); return true; } CompareTime = nextTime + 100.0 * fabs(nextTime) * std::numeric_limits< C_FLOAT64 >::epsilon(); if (*mpContainerStateTime >= CompareTime) { do { mpTSSAMethod->step(nextTime - *mpContainerStateTime); if (*mpContainerStateTime < CompareTime) break; /* Here we will do conditional event processing */ /* Currently this is correct since no events are processed. */ CCopasiMessage(CCopasiMessage::EXCEPTION, MCTSSAMethod + 3); } while (true); mpContainer->updateSimulatedValues(mUpdateMoieties); return true; } // Current time is approximately nextTime; return false; } // virtual const CTaskEnum::Method * CTSSATask::getValidMethods() const { return CTSSATask::ValidMethods; } const CTimeSeries & CTSSATask::getTimeSeries() const {return mTimeSeries;} <commit_msg>fix crash in selecting matrices from TSSA in simple selection tree<commit_after>// Copyright (C) 2017 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and University of // of Connecticut School of Medicine. // All rights reserved. // Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. // Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. // Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. /** * CTSSATask class. * * This class implements a time scale separation analysis task which is comprised of a * of a problem and a method. Additionally calls to the reporting * methods are done when initialized. * */ #include <string> #include "copasi.h" #include "CTSSATask.h" #include "CTSSAProblem.h" #include "CTSSAMethod.h" #include "math/CMathContainer.h" #include "report/CKeyFactory.h" #include "report/CReport.h" #include "utilities/CProcessReport.h" #include "utilities/CCopasiException.h" #include "CopasiDataModel/CDataModel.h" #define XXXX_Reporting bool tfle(const C_FLOAT64 & d1, const C_FLOAT64 & d2) {return (d1 <= d2);} bool tfl(const C_FLOAT64 & d1, const C_FLOAT64 & d2) {return (d1 < d2);} bool tble(const C_FLOAT64 & d1, const C_FLOAT64 & d2) {return (d1 >= d2);} bool tbl(const C_FLOAT64 & d1, const C_FLOAT64 & d2) {return (d1 > d2);} // static const CTaskEnum::Method CTSSATask::ValidMethods[] = { CTaskEnum::Method::tssILDM, CTaskEnum::Method::tssILDMModified, CTaskEnum::Method::tssCSP, CTaskEnum::Method::UnsetMethod }; CTSSATask::CTSSATask(const CDataContainer * pParent, const CTaskEnum::Task & type): CCopasiTask(pParent, type), mTimeSeriesRequested(true), mTimeSeries(), mpTSSAProblem(NULL), mpTSSAMethod(NULL), mContainerState(), mpContainerStateTime(NULL) { mpProblem = new CTSSAProblem(this); mpMethod = createMethod(CTaskEnum::Method::tssILDM); CCopasiParameter * pParameter = mpMethod->getParameter("Integrate Reduced Model"); if (pParameter != NULL) mUpdateMoieties = pParameter->getValue< bool >(); else mUpdateMoieties = false; } CTSSATask::CTSSATask(const CTSSATask & src, const CDataContainer * pParent): CCopasiTask(src, pParent), mTimeSeriesRequested(src.mTimeSeriesRequested), mTimeSeries(), mpTSSAProblem(NULL), mpTSSAMethod(NULL), mContainerState(), mpContainerStateTime(NULL) { mpProblem = new CTSSAProblem(*static_cast< CTSSAProblem * >(src.mpProblem), this); mpMethod = createMethod(src.mpMethod->getSubType()); * mpMethod = * src.mpMethod; mpMethod->elevateChildren(); this->add(mpMethod, true); CCopasiParameter * pParameter = mpMethod->getParameter("Integrate Reduced Model"); if (pParameter != NULL) mUpdateMoieties = pParameter->getValue< bool >(); else mUpdateMoieties = false; } CTSSATask::~CTSSATask() {} bool CTSSATask::updateMatrices() { assert(mpProblem != NULL && mpMethod != NULL); assert(dynamic_cast<CTSSAProblem *>(mpProblem) != NULL); mpMethod->setMathContainer(mpContainer); if (!mpMethod->isValidProblem(mpProblem)) return false; CTSSAMethod * pMethod = dynamic_cast<CTSSAMethod*>(mpMethod); if (!pMethod) return false; pMethod->initializeOutput(); return true; } bool CTSSATask::initialize(const OutputFlag & of, COutputHandler * pOutputHandler, std::ostream * pOstream) { assert(mpProblem && mpMethod); mpTSSAProblem = dynamic_cast<CTSSAProblem *>(mpProblem); assert(mpTSSAProblem); mpTSSAMethod = dynamic_cast<CTSSAMethod *>(mpMethod); assert(mpTSSAMethod); mpTSSAMethod->setProblem(mpTSSAProblem); bool success = mpMethod->isValidProblem(mpProblem); CCopasiParameter * pParameter = mpMethod->getParameter("Integrate Reduced Model"); if (pParameter != NULL) mUpdateMoieties = pParameter->getValue< bool >(); else mUpdateMoieties = false; // Handle the time series as a regular output. mTimeSeriesRequested = mpTSSAProblem->timeSeriesRequested(); if (pOutputHandler != NULL) { if (mTimeSeriesRequested) { mTimeSeries.allocate(mpTSSAProblem->getStepNumber()); pOutputHandler->addInterface(&mTimeSeries); } else { mTimeSeries.clear(); } } mpTSSAMethod->initializeOutput(); success &= CCopasiTask::initialize(of, pOutputHandler, pOstream); mContainerState.initialize(mpContainer->getState(mUpdateMoieties)); mpContainerStateTime = mContainerState.array() + mpContainer->getCountFixedEventTargets(); return success; } bool CTSSATask::process(const bool & useInitialValues) { //***** processStart(useInitialValues); //***** C_FLOAT64 StepSize = mpTSSAProblem->getStepSize(); C_FLOAT64 NextTimeToReport; const C_FLOAT64 EndTime = *mpContainerStateTime + mpTSSAProblem->getDuration(); const C_FLOAT64 StartTime = *mpContainerStateTime; C_FLOAT64 StepNumber = (mpTSSAProblem->getDuration()) / StepSize; bool (*LE)(const C_FLOAT64 &, const C_FLOAT64 &); bool (*L)(const C_FLOAT64 &, const C_FLOAT64 &); if (StepSize < 0.0) { LE = &tble; L = &tbl; } else { LE = &tfle; L = &tfl; } size_t StepCounter = 1; C_FLOAT64 outputStartTime = mpTSSAProblem->getOutputStartTime(); if (StepSize == 0.0 && mpTSSAProblem->getDuration() != 0.0) { CCopasiMessage(CCopasiMessage::ERROR, MCTSSAProblem + 1, StepSize); return false; } output(COutputInterface::BEFORE); bool flagProceed = true; C_FLOAT64 handlerFactor = 100.0 / mpTSSAProblem->getDuration(); C_FLOAT64 Percentage = 0; size_t hProcess; if (mpCallBack) { mpCallBack->setName("performing simulation..."); C_FLOAT64 hundred = 100; hProcess = mpCallBack->addItem("Completion", Percentage, &hundred); } //if ((*LE)(outputStartTime, *mpContainerStateTime)) output(COutputInterface::DURING); try { do { // This is numerically more stable then adding // mpTSSAProblem->getStepSize(). NextTimeToReport = StartTime + (EndTime - StartTime) * StepCounter++ / StepNumber; flagProceed &= processStep(NextTimeToReport); if (mpCallBack) { Percentage = (*mpContainerStateTime - StartTime) * handlerFactor; flagProceed &= mpCallBack->progressItem(hProcess); } if ((*LE)(outputStartTime, *mpContainerStateTime)) { output(COutputInterface::DURING); } } while ((*L)(*mpContainerStateTime, EndTime) && flagProceed); } catch (int) { mpContainer->updateSimulatedValues(mUpdateMoieties); if ((*LE)(outputStartTime, *mpContainerStateTime)) { output(COutputInterface::DURING); } if (mpCallBack) mpCallBack->finishItem(hProcess); output(COutputInterface::AFTER); CCopasiMessage(CCopasiMessage::EXCEPTION, MCTSSAMethod + 4); } catch (CCopasiException & Exception) { mpContainer->updateSimulatedValues(mUpdateMoieties); if ((*LE)(outputStartTime, *mpContainerStateTime)) { output(COutputInterface::DURING); } if (mpCallBack) mpCallBack->finishItem(hProcess); output(COutputInterface::AFTER); throw CCopasiException(Exception.getMessage()); } if (mpCallBack) mpCallBack->finishItem(hProcess); output(COutputInterface::AFTER); return true; } void CTSSATask::processStart(const bool & useInitialValues) { if (useInitialValues) { mpContainer->applyInitialValues(); } mContainerState.initialize(mpContainer->getState(mUpdateMoieties)); mpTSSAMethod->start(); return; } bool CTSSATask::processStep(const C_FLOAT64 & nextTime) { C_FLOAT64 CompareTime = nextTime - 100.0 * fabs(nextTime) * std::numeric_limits< C_FLOAT64 >::epsilon(); if (*mpContainerStateTime <= CompareTime) { do { mpTSSAMethod->step(nextTime - *mpContainerStateTime); if (*mpContainerStateTime > CompareTime) break; /* Here we will do conditional event processing */ /* Currently this is correct since no events are processed. */ CCopasiMessage(CCopasiMessage::EXCEPTION, MCTSSAMethod + 3); } while (true); mpContainer->updateSimulatedValues(mUpdateMoieties); return true; } CompareTime = nextTime + 100.0 * fabs(nextTime) * std::numeric_limits< C_FLOAT64 >::epsilon(); if (*mpContainerStateTime >= CompareTime) { do { mpTSSAMethod->step(nextTime - *mpContainerStateTime); if (*mpContainerStateTime < CompareTime) break; /* Here we will do conditional event processing */ /* Currently this is correct since no events are processed. */ CCopasiMessage(CCopasiMessage::EXCEPTION, MCTSSAMethod + 3); } while (true); mpContainer->updateSimulatedValues(mUpdateMoieties); return true; } // Current time is approximately nextTime; return false; } // virtual const CTaskEnum::Method * CTSSATask::getValidMethods() const { return CTSSATask::ValidMethods; } const CTimeSeries & CTSSATask::getTimeSeries() const {return mTimeSeries;} <|endoftext|>
<commit_before>/* * Unit tests for the TTValue object * Copyright © 2011, Timothy Place * * License: This code is licensed under the terms of the "New BSD License" * http://creativecommons.org/licenses/BSD/ */ #include "TTValueTest.h" #define thisTTClass TTValueTest #define thisTTClassName "value.test" #define thisTTClassTags "test, foundation" TT_OBJECT_CONSTRUCTOR {;} TTValueTest::~TTValueTest() {;} void TTValueTestBasic(int& errorCount, int&testAssertionCount) { TTTestLog("\n"); TTTestLog("Testing basic TTValue operation"); TTValue v1(3.14); TTTestAssertion("init with a double is correctly typed as kTypeFloat64", v1.getType(0) == kTypeFloat64, testAssertionCount, errorCount); TTTestAssertion("init with a double has correct element count", v1.getSize() == 1, testAssertionCount, errorCount); TTTestAssertion("init with a double has correct value when retrieved as a double", TTTestFloatEquivalence(double(v1), 3.14), testAssertionCount, errorCount); TTTestAssertion("init with a double has correct value when retrieved as an TTInt32", TTInt32(v1) == 3, testAssertionCount, errorCount); TTTestLog("Appending a symbol to TTValue"); v1.append(TT("foo")); TTTestAssertion("TTValue correctly updated element count to 2", v1.getSize() == 2, testAssertionCount, errorCount); TTTestAssertion("first item still is correctly typed as kTypeFloat64", v1.getType(0) == kTypeFloat64, testAssertionCount, errorCount); TTTestAssertion("first item still has correct value when retrieved as a double", TTTestFloatEquivalence(double(v1), 3.14), testAssertionCount, errorCount); TTTestAssertion("second item has correct type", v1.getType(1) == kTypeSymbol, testAssertionCount, errorCount); // TODO: want to implement this: // TTSymbolPtr s = v1[1]; TTSymbolPtr s = NULL; v1.get(1, &s); TTTestAssertion("second item has correct value, retreiving with get() method", s == TT("foo"), testAssertionCount, errorCount); TTTestLog("Clearing TTValue"); v1.clear(); TTTestAssertion("element count is zero", v1.getSize() == 0, testAssertionCount, errorCount); TTTestAssertion("type of TTValue which is returned is kTypeNone", v1.getType() == kTypeNone, testAssertionCount, errorCount); } void TTValueTestStringConversion(int& errorCount, int&testAssertionCount) { TTTestLog("\n"); TTTestLog("Testing TTValue string conversion methods"); // TODO: test toString() // TODO: test fromString() // TODO: test transformCSVStringToSymbolArray() TTValue v1(3.14); } void TTValueTestNumericTransformations(int& errorCount, int&testAssertionCount) { TTTestLog("\n"); TTTestLog("Testing TTValue numeric transformations"); // TODO: test clip() // TODO: test cliplow() // TODO: test cliphigh() // TODO: test round() // TODO: test truncate() // TODO: test booleanize() TTValue v1(3.14); } void TTValueTestOperators(int& errorCount, int&testAssertionCount) { TTTestLog("\n"); TTTestLog("Testing TTValue operators"); // TODO: test > // TODO: test == // TODO: test = // TODO: test casting // TODO: should + be concatenating elements to create a new value of a+b element count? TTValue v1(3.14); } // TODO: Benchmarking TTErr TTValueTest::test(TTValue& returnedTestInfo) { int errorCount = 0; int testAssertionCount = 0; TTValueTestBasic(errorCount, testAssertionCount); TTValueTestStringConversion(errorCount, testAssertionCount); TTValueTestNumericTransformations(errorCount, testAssertionCount); TTValueTestOperators(errorCount, testAssertionCount); return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo); } <commit_msg>Adding a bunch of trivial tests<commit_after>/* * Unit tests for the TTValue object * Copyright © 2011, Timothy Place * * License: This code is licensed under the terms of the "New BSD License" * http://creativecommons.org/licenses/BSD/ */ #include "TTValueTest.h" #define thisTTClass TTValueTest #define thisTTClassName "value.test" #define thisTTClassTags "test, foundation" TT_OBJECT_CONSTRUCTOR {;} TTValueTest::~TTValueTest() {;} void TTValueTestBasic(int& errorCount, int&testAssertionCount) { TTTestLog("\n"); TTTestLog("Testing basic TTValue operation"); TTValue v1(3.14); TTTestAssertion("init with a double is correctly typed as kTypeFloat64", v1.getType(0) == kTypeFloat64, testAssertionCount, errorCount); TTTestAssertion("init with a double has correct element count", v1.getSize() == 1, testAssertionCount, errorCount); TTTestAssertion("init with a double has correct value when retrieved as a double", TTTestFloatEquivalence(double(v1), 3.14), testAssertionCount, errorCount); TTTestAssertion("init with a double has correct value when retrieved as an TTInt32", TTInt32(v1) == 3, testAssertionCount, errorCount); TTTestLog("Appending a symbol to TTValue"); v1.append(TT("foo")); TTTestAssertion("TTValue correctly updated element count to 2", v1.getSize() == 2, testAssertionCount, errorCount); TTTestAssertion("first item still is correctly typed as kTypeFloat64", v1.getType(0) == kTypeFloat64, testAssertionCount, errorCount); TTTestAssertion("first item still has correct value when retrieved as a double", TTTestFloatEquivalence(double(v1), 3.14), testAssertionCount, errorCount); TTTestAssertion("second item has correct type", v1.getType(1) == kTypeSymbol, testAssertionCount, errorCount); // TODO: want to implement this: // TTSymbolPtr s = v1[1]; TTSymbolPtr s = NULL; v1.get(1, &s); TTTestAssertion("second item has correct value, retreiving with get() method", s == TT("foo"), testAssertionCount, errorCount); TTTestLog("Clearing TTValue"); v1.clear(); TTTestAssertion("element count is zero", v1.getSize() == 0, testAssertionCount, errorCount); TTTestAssertion("type of TTValue which is returned is kTypeNone", v1.getType() == kTypeNone, testAssertionCount, errorCount); } void TTValueTestStringConversion(int& errorCount, int&testAssertionCount) { TTTestLog("\n"); TTTestLog("Testing TTValue string conversion methods"); // TODO: test toString() // TODO: test fromString() // TODO: test transformCSVStringToSymbolArray() TTValue v1(3.14); } void TTValueTestNumericTransformations(int& errorCount, int&testAssertionCount) { TTTestLog("\n"); TTTestLog("Testing TTValue numeric transformations"); /****************************************************************************************************/ TTTestLog("\n"); TTTestLog("Testing clip()"); /****************************************************************************************************/ // TTFloat64 TTValue v1(3.14); v1.clip(6.0, 12.0); TTTestAssertion("positive double clipped (out of lower bound)", TTTestFloatEquivalence(double(v1), 6.0), testAssertionCount, errorCount); v1 = 3.14; v1.clip(0.0, 4.0); TTTestAssertion("positive double not clipped (within range)", TTTestFloatEquivalence(double(v1), 3.14), testAssertionCount, errorCount); v1 = 3.14; v1.clip(0.0, 2.0); TTTestAssertion("positive double clipped (out of upper bound)", TTTestFloatEquivalence(double(v1), 2.0), testAssertionCount, errorCount); v1 = -3.14; v1.clip(-2.0, 0.0); TTTestAssertion("negative double clipped (out of lower bound)", TTTestFloatEquivalence(double(v1), -2.0), testAssertionCount, errorCount); v1 = -3.14; v1.clip(-4.0, 0.0); TTTestAssertion("negative double not clipped (within range)", TTTestFloatEquivalence(double(v1), -3.14), testAssertionCount, errorCount); v1 = -3.14; v1.clip(-8.0, -4.0); TTTestAssertion("negative double clipped (out of upper bound)", TTTestFloatEquivalence(double(v1), -4.0), testAssertionCount, errorCount); // TTInt8 v1.clip(6, 12); TTTestAssertion("positive TTInt8 clipped (out of lower bound)", TTInt8(v1) == 6, testAssertionCount, errorCount); v1 = TTInt8(3); v1.clip(0, 4); TTTestAssertion("positive TTInt8 not clipped (within range)", TTInt8(v1) == 3, testAssertionCount, errorCount); v1 = TTInt8(3); v1.clip(0, 2); // TTFloat64 myFloat = v1.get; TTTestAssertion("positive TTInt8 clipped (out of upper bound)", TTInt8(v1) == 2, testAssertionCount, errorCount); v1 = TTInt8(-3); v1.clip(-2, 0); // TTFloat64 myFloat = v1.get; TTTestAssertion("negative TTInt8 clipped (out of lower bound)", TTInt8(v1) == -2, testAssertionCount, errorCount); v1 = TTInt8(-3); v1.clip(-4, 0); // TTFloat64 myFloat = v1.get; TTTestAssertion("negative TTInt8 not clipped (within range)", TTInt8(v1) == -3, testAssertionCount, errorCount); v1 = TTInt8(-3); v1.clip(-8, -4); // TTFloat64 myFloat = v1.get; TTTestAssertion("negative TTInt8 clipped (out of upper bound)", TTInt8(v1) == -4, testAssertionCount, errorCount); // TTInt16 v1.clip(6, 12); TTTestAssertion("positive TTInt16 clipped (out of lower bound)", TTInt16(v1) == 6, testAssertionCount, errorCount); v1 = TTInt16(3); v1.clip(0, 4); TTTestAssertion("positive TTInt16 not clipped (within range)", TTInt16(v1) == 3, testAssertionCount, errorCount); v1 = TTInt16(3); v1.clip(0, 2); // TTFloat64 myFloat = v1.get; TTTestAssertion("positive TTInt16 clipped (out of upper bound)", TTInt16(v1) == 2, testAssertionCount, errorCount); v1 = TTInt16(-3); v1.clip(-2, 0); // TTFloat64 myFloat = v1.get; TTTestAssertion("negative TTInt16 clipped (out of lower bound)", TTInt16(v1) == -2, testAssertionCount, errorCount); v1 = TTInt16(-3); v1.clip(-4, 0); // TTFloat64 myFloat = v1.get; TTTestAssertion("negative TTInt16 not clipped (within range)", TTInt16(v1) == -3, testAssertionCount, errorCount); v1 = TTInt16(-3); v1.clip(-8, -4); // TTFloat64 myFloat = v1.get; TTTestAssertion("negative TTInt16 clipped (out of upper bound)", TTInt16(v1) == -4, testAssertionCount, errorCount); // TTInt32 v1.clip(6, 12); TTTestAssertion("positive TTInt32 clipped (out of lower bound)", TTInt32(v1) == 6, testAssertionCount, errorCount); v1 = TTInt32(3); v1.clip(0, 4); TTTestAssertion("positive TTInt32 not clipped (within range)", TTInt32(v1) == 3, testAssertionCount, errorCount); v1 = TTInt32(3); v1.clip(0, 2); // TTFloat64 myFloat = v1.get; TTTestAssertion("positive TTInt32 clipped (out of upper bound)", TTInt32(v1) == 2, testAssertionCount, errorCount); v1 = TTInt32(-3); v1.clip(-2, 0); // TTFloat64 myFloat = v1.get; TTTestAssertion("negative TTInt32 clipped (out of lower bound)", TTInt32(v1) == -2, testAssertionCount, errorCount); v1 = TTInt32(-3); v1.clip(-4, 0); // TTFloat64 myFloat = v1.get; TTTestAssertion("negative TTInt32 not clipped (within range)", TTInt32(v1) == -3, testAssertionCount, errorCount); v1 = TTInt32(-3); v1.clip(-8, -4); // TTFloat64 myFloat = v1.get; TTTestAssertion("negative TTInt32 clipped (out of upper bound)", TTInt32(v1) == -4, testAssertionCount, errorCount); // TTInt64 v1.clip(6, 12); TTTestAssertion("positive TTInt64 clipped (out of lower bound)", TTInt64(v1) == 6, testAssertionCount, errorCount); v1 = TTInt64(3); v1.clip(0, 4); TTTestAssertion("positive TTInt64 not clipped (within range)", TTInt64(v1) == 3, testAssertionCount, errorCount); v1 = TTInt64(3); v1.clip(0, 2); // TTFloat64 myFloat = v1.get; TTTestAssertion("positive TTInt64 clipped (out of upper bound)", TTInt64(v1) == 2, testAssertionCount, errorCount); v1 = TTInt64(-3); v1.clip(-2, 0); // TTFloat64 myFloat = v1.get; TTTestAssertion("negative TTInt64 clipped (out of lower bound)", TTInt64(v1) == -2, testAssertionCount, errorCount); v1 = TTInt64(-3); v1.clip(-4, 0); // TTFloat64 myFloat = v1.get; TTTestAssertion("negative TTInt64 not clipped (within range)", TTInt64(v1) == -3, testAssertionCount, errorCount); v1 = TTInt64(-3); v1.clip(-8, -4); // TTFloat64 myFloat = v1.get; TTTestAssertion("negative TTInt64 clipped (out of upper bound)", TTInt64(v1) == -4, testAssertionCount, errorCount); // TODO: test cliplow() // TODO: test cliphigh() // TODO: test round() // TODO: test truncate() // TODO: test booleanize() //TTValue v1(3.14); } void TTValueTestOperators(int& errorCount, int&testAssertionCount) { TTTestLog("\n"); TTTestLog("Testing TTValue operators"); // TODO: test > // TODO: test == // TODO: test = // TODO: test casting // TODO: should + be concatenating elements to create a new value of a+b element count? TTValue v1(3.14); } // TODO: Benchmarking TTErr TTValueTest::test(TTValue& returnedTestInfo) { int errorCount = 0; int testAssertionCount = 0; TTValueTestBasic(errorCount, testAssertionCount); TTValueTestStringConversion(errorCount, testAssertionCount); TTValueTestNumericTransformations(errorCount, testAssertionCount); TTValueTestOperators(errorCount, testAssertionCount); return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo); } <|endoftext|>
<commit_before>#include <Bull/Core/Utility/Random.hpp> #include <Bull/Core/Time/Time.hpp> namespace Bull { RandomGenerator::RandomGenerator() : RandomGenerator(Time::now().getSecond()) { /// Nothing } RandomGenerator::RandomGenerator(Uint64 seed) : m_generator(seed) { /// Nothing } #ifndef BULL_COMPILER_MSC /// FIXME : provide a fallback implementation for MSC template <> char RandomGenerator::number<char>(char min, char max) { std::uniform_int_distribution<char> distribution(min, max); return distribution(m_generator); } template <> unsigned char RandomGenerator::number<unsigned char>(unsigned char min, unsigned char max) { std::uniform_int_distribution<unsigned char> distribution(min, max); return distribution(m_generator); } #endif template <> short RandomGenerator::number<short>(short min, short max) { std::uniform_int_distribution<short> distribution(min, max); return distribution(m_generator); } template <> unsigned short RandomGenerator::number<unsigned short>(unsigned short min, unsigned short max) { std::uniform_int_distribution<unsigned short> distribution(min, max); return distribution(m_generator); } template <> int RandomGenerator::number<int>(int min, int max) { std::uniform_int_distribution<int> distribution(min, max); return distribution(m_generator); } template <> unsigned int RandomGenerator::number<unsigned int>(unsigned int min, unsigned int max) { std::uniform_int_distribution<unsigned int> distribution(min, max); return distribution(m_generator); } template <> long RandomGenerator::number<long>(long min, long max) { std::uniform_int_distribution<long> distribution(min, max); return distribution(m_generator); } template <> unsigned long RandomGenerator::number<unsigned long>(unsigned long min, unsigned long max) { std::uniform_int_distribution<unsigned long> distribution(min, max); return distribution(m_generator); } template <> float RandomGenerator::number<float>(float min, float max) { std::uniform_real_distribution<float> distribution(min, max); return distribution(m_generator); } template <> double RandomGenerator::number<double>(double min, double max) { std::uniform_real_distribution<double> distribution(min, max); return distribution(m_generator); } } <commit_msg>[Core/Random] Fix MSC preprocessor protection<commit_after>#include <Bull/Core/Utility/Random.hpp> #include <Bull/Core/Time/Time.hpp> namespace Bull { RandomGenerator::RandomGenerator() : RandomGenerator(Time::now().getSecond()) { /// Nothing } RandomGenerator::RandomGenerator(Uint64 seed) : m_generator(seed) { /// Nothing } #if BULL_COMPILER != BULL_COMPILER_MSC /// FIXME : provide a fallback implementation for MSC template <> char RandomGenerator::number<char>(char min, char max) { std::uniform_int_distribution<char> distribution(min, max); return distribution(m_generator); } template <> unsigned char RandomGenerator::number<unsigned char>(unsigned char min, unsigned char max) { std::uniform_int_distribution<unsigned char> distribution(min, max); return distribution(m_generator); } #endif template <> short RandomGenerator::number<short>(short min, short max) { std::uniform_int_distribution<short> distribution(min, max); return distribution(m_generator); } template <> unsigned short RandomGenerator::number<unsigned short>(unsigned short min, unsigned short max) { std::uniform_int_distribution<unsigned short> distribution(min, max); return distribution(m_generator); } template <> int RandomGenerator::number<int>(int min, int max) { std::uniform_int_distribution<int> distribution(min, max); return distribution(m_generator); } template <> unsigned int RandomGenerator::number<unsigned int>(unsigned int min, unsigned int max) { std::uniform_int_distribution<unsigned int> distribution(min, max); return distribution(m_generator); } template <> long RandomGenerator::number<long>(long min, long max) { std::uniform_int_distribution<long> distribution(min, max); return distribution(m_generator); } template <> unsigned long RandomGenerator::number<unsigned long>(unsigned long min, unsigned long max) { std::uniform_int_distribution<unsigned long> distribution(min, max); return distribution(m_generator); } template <> float RandomGenerator::number<float>(float min, float max) { std::uniform_real_distribution<float> distribution(min, max); return distribution(m_generator); } template <> double RandomGenerator::number<double>(double min, double max) { std::uniform_real_distribution<double> distribution(min, max); return distribution(m_generator); } } <|endoftext|>
<commit_before>//===- JITMemoryManagerTest.cpp - Unit tests for the JIT memory manager ---===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "gtest/gtest.h" #include "llvm/ADT/OwningPtr.h" #include "llvm/ExecutionEngine/JITMemoryManager.h" #include "llvm/DerivedTypes.h" #include "llvm/Function.h" #include "llvm/GlobalValue.h" #include "llvm/LLVMContext.h" using namespace llvm; namespace { Function *makeFakeFunction() { std::vector<const Type*> params; const FunctionType *FTy = FunctionType::get(Type::getVoidTy(getGlobalContext()), params, false); return Function::Create(FTy, GlobalValue::ExternalLinkage); } // Allocate three simple functions that fit in the initial slab. This exercises // the code in the case that we don't have to allocate more memory to store the // function bodies. TEST(JITMemoryManagerTest, NoAllocations) { OwningPtr<JITMemoryManager> MemMgr( JITMemoryManager::CreateDefaultMemManager()); uintptr_t size; std::string Error; // Allocate the functions. OwningPtr<Function> F1(makeFakeFunction()); size = 1024; uint8_t *FunctionBody1 = MemMgr->startFunctionBody(F1.get(), size); memset(FunctionBody1, 0xFF, 1024); MemMgr->endFunctionBody(F1.get(), FunctionBody1, FunctionBody1 + 1024); EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error; OwningPtr<Function> F2(makeFakeFunction()); size = 1024; uint8_t *FunctionBody2 = MemMgr->startFunctionBody(F2.get(), size); memset(FunctionBody2, 0xFF, 1024); MemMgr->endFunctionBody(F2.get(), FunctionBody2, FunctionBody2 + 1024); EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error; OwningPtr<Function> F3(makeFakeFunction()); size = 1024; uint8_t *FunctionBody3 = MemMgr->startFunctionBody(F3.get(), size); memset(FunctionBody3, 0xFF, 1024); MemMgr->endFunctionBody(F3.get(), FunctionBody3, FunctionBody3 + 1024); EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error; // Deallocate them out of order, in case that matters. MemMgr->deallocateFunctionBody(FunctionBody2); EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error; MemMgr->deallocateFunctionBody(FunctionBody1); EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error; MemMgr->deallocateFunctionBody(FunctionBody3); EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error; } // Make three large functions that take up most of the space in the slab. Then // try allocating three smaller functions that don't require additional slabs. TEST(JITMemoryManagerTest, TestCodeAllocation) { OwningPtr<JITMemoryManager> MemMgr( JITMemoryManager::CreateDefaultMemManager()); uintptr_t size; std::string Error; // Big functions are a little less than the largest block size. const uintptr_t smallFuncSize = 1024; const uintptr_t bigFuncSize = (MemMgr->GetDefaultCodeSlabSize() - smallFuncSize * 2); // Allocate big functions OwningPtr<Function> F1(makeFakeFunction()); size = bigFuncSize; uint8_t *FunctionBody1 = MemMgr->startFunctionBody(F1.get(), size); ASSERT_LE(bigFuncSize, size); memset(FunctionBody1, 0xFF, bigFuncSize); MemMgr->endFunctionBody(F1.get(), FunctionBody1, FunctionBody1 + bigFuncSize); EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error; OwningPtr<Function> F2(makeFakeFunction()); size = bigFuncSize; uint8_t *FunctionBody2 = MemMgr->startFunctionBody(F2.get(), size); ASSERT_LE(bigFuncSize, size); memset(FunctionBody2, 0xFF, bigFuncSize); MemMgr->endFunctionBody(F2.get(), FunctionBody2, FunctionBody2 + bigFuncSize); EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error; OwningPtr<Function> F3(makeFakeFunction()); size = bigFuncSize; uint8_t *FunctionBody3 = MemMgr->startFunctionBody(F3.get(), size); ASSERT_LE(bigFuncSize, size); memset(FunctionBody3, 0xFF, bigFuncSize); MemMgr->endFunctionBody(F3.get(), FunctionBody3, FunctionBody3 + bigFuncSize); EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error; // Check that each large function took it's own slab. EXPECT_EQ(3U, MemMgr->GetNumCodeSlabs()); // Allocate small functions OwningPtr<Function> F4(makeFakeFunction()); size = smallFuncSize; uint8_t *FunctionBody4 = MemMgr->startFunctionBody(F4.get(), size); ASSERT_LE(smallFuncSize, size); memset(FunctionBody4, 0xFF, smallFuncSize); MemMgr->endFunctionBody(F4.get(), FunctionBody4, FunctionBody4 + smallFuncSize); EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error; OwningPtr<Function> F5(makeFakeFunction()); size = smallFuncSize; uint8_t *FunctionBody5 = MemMgr->startFunctionBody(F5.get(), size); ASSERT_LE(smallFuncSize, size); memset(FunctionBody5, 0xFF, smallFuncSize); MemMgr->endFunctionBody(F5.get(), FunctionBody5, FunctionBody5 + smallFuncSize); EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error; OwningPtr<Function> F6(makeFakeFunction()); size = smallFuncSize; uint8_t *FunctionBody6 = MemMgr->startFunctionBody(F6.get(), size); ASSERT_LE(smallFuncSize, size); memset(FunctionBody6, 0xFF, smallFuncSize); MemMgr->endFunctionBody(F6.get(), FunctionBody6, FunctionBody6 + smallFuncSize); EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error; // Check that the small functions didn't allocate any new slabs. EXPECT_EQ(3U, MemMgr->GetNumCodeSlabs()); // Deallocate them out of order, in case that matters. MemMgr->deallocateFunctionBody(FunctionBody2); EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error; MemMgr->deallocateFunctionBody(FunctionBody1); EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error; MemMgr->deallocateFunctionBody(FunctionBody4); EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error; MemMgr->deallocateFunctionBody(FunctionBody3); EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error; MemMgr->deallocateFunctionBody(FunctionBody5); EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error; MemMgr->deallocateFunctionBody(FunctionBody6); EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error; } // Allocate five global ints of varying widths and alignment, and check their // alignment and overlap. TEST(JITMemoryManagerTest, TestSmallGlobalInts) { OwningPtr<JITMemoryManager> MemMgr( JITMemoryManager::CreateDefaultMemManager()); uint8_t *a = (uint8_t *)MemMgr->allocateGlobal(8, 0); uint16_t *b = (uint16_t*)MemMgr->allocateGlobal(16, 2); uint32_t *c = (uint32_t*)MemMgr->allocateGlobal(32, 4); uint64_t *d = (uint64_t*)MemMgr->allocateGlobal(64, 8); // Check the alignment. EXPECT_EQ(0U, ((uintptr_t)b) & 0x1); EXPECT_EQ(0U, ((uintptr_t)c) & 0x3); EXPECT_EQ(0U, ((uintptr_t)d) & 0x7); // Initialize them each one at a time and make sure they don't overlap. *a = 0xff; *b = 0U; *c = 0U; *d = 0U; EXPECT_EQ(0xffU, *a); EXPECT_EQ(0U, *b); EXPECT_EQ(0U, *c); EXPECT_EQ(0U, *d); *a = 0U; *b = 0xffffU; EXPECT_EQ(0U, *a); EXPECT_EQ(0xffffU, *b); EXPECT_EQ(0U, *c); EXPECT_EQ(0U, *d); *b = 0U; *c = 0xffffffffU; EXPECT_EQ(0U, *a); EXPECT_EQ(0U, *b); EXPECT_EQ(0xffffffffU, *c); EXPECT_EQ(0U, *d); *c = 0U; *d = 0xffffffffffffffffULL; EXPECT_EQ(0U, *a); EXPECT_EQ(0U, *b); EXPECT_EQ(0U, *c); EXPECT_EQ(0xffffffffffffffffULL, *d); // Make sure we didn't allocate any extra slabs for this tiny amount of data. EXPECT_EQ(1U, MemMgr->GetNumDataSlabs()); } // Allocate a small global, a big global, and a third global, and make sure we // only use two slabs for that. TEST(JITMemoryManagerTest, TestLargeGlobalArray) { OwningPtr<JITMemoryManager> MemMgr( JITMemoryManager::CreateDefaultMemManager()); size_t Size = 4 * MemMgr->GetDefaultDataSlabSize(); uint64_t *a = (uint64_t*)MemMgr->allocateGlobal(64, 8); uint8_t *g = MemMgr->allocateGlobal(Size, 8); uint64_t *b = (uint64_t*)MemMgr->allocateGlobal(64, 8); // Check the alignment. EXPECT_EQ(0U, ((uintptr_t)a) & 0x7); EXPECT_EQ(0U, ((uintptr_t)g) & 0x7); EXPECT_EQ(0U, ((uintptr_t)b) & 0x7); // Initialize them to make sure we don't segfault and make sure they don't // overlap. memset(a, 0x1, 8); memset(g, 0x2, Size); memset(b, 0x3, 8); EXPECT_EQ(0x0101010101010101ULL, *a); // Just check the edges. EXPECT_EQ(0x02U, g[0]); EXPECT_EQ(0x02U, g[Size - 1]); EXPECT_EQ(0x0303030303030303ULL, *b); // Check the number of slabs. EXPECT_EQ(2U, MemMgr->GetNumDataSlabs()); } // Allocate lots of medium globals so that we can test moving the bump allocator // to a new slab. TEST(JITMemoryManagerTest, TestManyGlobals) { OwningPtr<JITMemoryManager> MemMgr( JITMemoryManager::CreateDefaultMemManager()); size_t SlabSize = MemMgr->GetDefaultDataSlabSize(); size_t Size = 128; int Iters = (SlabSize / Size) + 1; // We should start with one slab. EXPECT_EQ(1U, MemMgr->GetNumDataSlabs()); // After allocating a bunch of globals, we should have two. for (int I = 0; I < Iters; ++I) MemMgr->allocateGlobal(Size, 8); EXPECT_EQ(2U, MemMgr->GetNumDataSlabs()); // And after much more, we should have three. for (int I = 0; I < Iters; ++I) MemMgr->allocateGlobal(Size, 8); EXPECT_EQ(3U, MemMgr->GetNumDataSlabs()); } // Allocate lots of function stubs so that we can test moving the stub bump // allocator to a new slab. TEST(JITMemoryManagerTest, TestManyStubs) { OwningPtr<JITMemoryManager> MemMgr( JITMemoryManager::CreateDefaultMemManager()); size_t SlabSize = MemMgr->GetDefaultStubSlabSize(); size_t Size = 128; int Iters = (SlabSize / Size) + 1; // We should start with one slab. EXPECT_EQ(1U, MemMgr->GetNumStubSlabs()); // After allocating a bunch of stubs, we should have two. for (int I = 0; I < Iters; ++I) MemMgr->allocateStub(NULL, Size, 8); EXPECT_EQ(2U, MemMgr->GetNumStubSlabs()); // And after much more, we should have three. for (int I = 0; I < Iters; ++I) MemMgr->allocateStub(NULL, Size, 8); EXPECT_EQ(3U, MemMgr->GetNumStubSlabs()); } } <commit_msg>Update unittest for allocator laziness.<commit_after>//===- JITMemoryManagerTest.cpp - Unit tests for the JIT memory manager ---===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "gtest/gtest.h" #include "llvm/ADT/OwningPtr.h" #include "llvm/ExecutionEngine/JITMemoryManager.h" #include "llvm/DerivedTypes.h" #include "llvm/Function.h" #include "llvm/GlobalValue.h" #include "llvm/LLVMContext.h" using namespace llvm; namespace { Function *makeFakeFunction() { std::vector<const Type*> params; const FunctionType *FTy = FunctionType::get(Type::getVoidTy(getGlobalContext()), params, false); return Function::Create(FTy, GlobalValue::ExternalLinkage); } // Allocate three simple functions that fit in the initial slab. This exercises // the code in the case that we don't have to allocate more memory to store the // function bodies. TEST(JITMemoryManagerTest, NoAllocations) { OwningPtr<JITMemoryManager> MemMgr( JITMemoryManager::CreateDefaultMemManager()); uintptr_t size; std::string Error; // Allocate the functions. OwningPtr<Function> F1(makeFakeFunction()); size = 1024; uint8_t *FunctionBody1 = MemMgr->startFunctionBody(F1.get(), size); memset(FunctionBody1, 0xFF, 1024); MemMgr->endFunctionBody(F1.get(), FunctionBody1, FunctionBody1 + 1024); EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error; OwningPtr<Function> F2(makeFakeFunction()); size = 1024; uint8_t *FunctionBody2 = MemMgr->startFunctionBody(F2.get(), size); memset(FunctionBody2, 0xFF, 1024); MemMgr->endFunctionBody(F2.get(), FunctionBody2, FunctionBody2 + 1024); EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error; OwningPtr<Function> F3(makeFakeFunction()); size = 1024; uint8_t *FunctionBody3 = MemMgr->startFunctionBody(F3.get(), size); memset(FunctionBody3, 0xFF, 1024); MemMgr->endFunctionBody(F3.get(), FunctionBody3, FunctionBody3 + 1024); EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error; // Deallocate them out of order, in case that matters. MemMgr->deallocateFunctionBody(FunctionBody2); EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error; MemMgr->deallocateFunctionBody(FunctionBody1); EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error; MemMgr->deallocateFunctionBody(FunctionBody3); EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error; } // Make three large functions that take up most of the space in the slab. Then // try allocating three smaller functions that don't require additional slabs. TEST(JITMemoryManagerTest, TestCodeAllocation) { OwningPtr<JITMemoryManager> MemMgr( JITMemoryManager::CreateDefaultMemManager()); uintptr_t size; std::string Error; // Big functions are a little less than the largest block size. const uintptr_t smallFuncSize = 1024; const uintptr_t bigFuncSize = (MemMgr->GetDefaultCodeSlabSize() - smallFuncSize * 2); // Allocate big functions OwningPtr<Function> F1(makeFakeFunction()); size = bigFuncSize; uint8_t *FunctionBody1 = MemMgr->startFunctionBody(F1.get(), size); ASSERT_LE(bigFuncSize, size); memset(FunctionBody1, 0xFF, bigFuncSize); MemMgr->endFunctionBody(F1.get(), FunctionBody1, FunctionBody1 + bigFuncSize); EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error; OwningPtr<Function> F2(makeFakeFunction()); size = bigFuncSize; uint8_t *FunctionBody2 = MemMgr->startFunctionBody(F2.get(), size); ASSERT_LE(bigFuncSize, size); memset(FunctionBody2, 0xFF, bigFuncSize); MemMgr->endFunctionBody(F2.get(), FunctionBody2, FunctionBody2 + bigFuncSize); EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error; OwningPtr<Function> F3(makeFakeFunction()); size = bigFuncSize; uint8_t *FunctionBody3 = MemMgr->startFunctionBody(F3.get(), size); ASSERT_LE(bigFuncSize, size); memset(FunctionBody3, 0xFF, bigFuncSize); MemMgr->endFunctionBody(F3.get(), FunctionBody3, FunctionBody3 + bigFuncSize); EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error; // Check that each large function took it's own slab. EXPECT_EQ(3U, MemMgr->GetNumCodeSlabs()); // Allocate small functions OwningPtr<Function> F4(makeFakeFunction()); size = smallFuncSize; uint8_t *FunctionBody4 = MemMgr->startFunctionBody(F4.get(), size); ASSERT_LE(smallFuncSize, size); memset(FunctionBody4, 0xFF, smallFuncSize); MemMgr->endFunctionBody(F4.get(), FunctionBody4, FunctionBody4 + smallFuncSize); EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error; OwningPtr<Function> F5(makeFakeFunction()); size = smallFuncSize; uint8_t *FunctionBody5 = MemMgr->startFunctionBody(F5.get(), size); ASSERT_LE(smallFuncSize, size); memset(FunctionBody5, 0xFF, smallFuncSize); MemMgr->endFunctionBody(F5.get(), FunctionBody5, FunctionBody5 + smallFuncSize); EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error; OwningPtr<Function> F6(makeFakeFunction()); size = smallFuncSize; uint8_t *FunctionBody6 = MemMgr->startFunctionBody(F6.get(), size); ASSERT_LE(smallFuncSize, size); memset(FunctionBody6, 0xFF, smallFuncSize); MemMgr->endFunctionBody(F6.get(), FunctionBody6, FunctionBody6 + smallFuncSize); EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error; // Check that the small functions didn't allocate any new slabs. EXPECT_EQ(3U, MemMgr->GetNumCodeSlabs()); // Deallocate them out of order, in case that matters. MemMgr->deallocateFunctionBody(FunctionBody2); EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error; MemMgr->deallocateFunctionBody(FunctionBody1); EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error; MemMgr->deallocateFunctionBody(FunctionBody4); EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error; MemMgr->deallocateFunctionBody(FunctionBody3); EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error; MemMgr->deallocateFunctionBody(FunctionBody5); EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error; MemMgr->deallocateFunctionBody(FunctionBody6); EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error; } // Allocate five global ints of varying widths and alignment, and check their // alignment and overlap. TEST(JITMemoryManagerTest, TestSmallGlobalInts) { OwningPtr<JITMemoryManager> MemMgr( JITMemoryManager::CreateDefaultMemManager()); uint8_t *a = (uint8_t *)MemMgr->allocateGlobal(8, 0); uint16_t *b = (uint16_t*)MemMgr->allocateGlobal(16, 2); uint32_t *c = (uint32_t*)MemMgr->allocateGlobal(32, 4); uint64_t *d = (uint64_t*)MemMgr->allocateGlobal(64, 8); // Check the alignment. EXPECT_EQ(0U, ((uintptr_t)b) & 0x1); EXPECT_EQ(0U, ((uintptr_t)c) & 0x3); EXPECT_EQ(0U, ((uintptr_t)d) & 0x7); // Initialize them each one at a time and make sure they don't overlap. *a = 0xff; *b = 0U; *c = 0U; *d = 0U; EXPECT_EQ(0xffU, *a); EXPECT_EQ(0U, *b); EXPECT_EQ(0U, *c); EXPECT_EQ(0U, *d); *a = 0U; *b = 0xffffU; EXPECT_EQ(0U, *a); EXPECT_EQ(0xffffU, *b); EXPECT_EQ(0U, *c); EXPECT_EQ(0U, *d); *b = 0U; *c = 0xffffffffU; EXPECT_EQ(0U, *a); EXPECT_EQ(0U, *b); EXPECT_EQ(0xffffffffU, *c); EXPECT_EQ(0U, *d); *c = 0U; *d = 0xffffffffffffffffULL; EXPECT_EQ(0U, *a); EXPECT_EQ(0U, *b); EXPECT_EQ(0U, *c); EXPECT_EQ(0xffffffffffffffffULL, *d); // Make sure we didn't allocate any extra slabs for this tiny amount of data. EXPECT_EQ(1U, MemMgr->GetNumDataSlabs()); } // Allocate a small global, a big global, and a third global, and make sure we // only use two slabs for that. TEST(JITMemoryManagerTest, TestLargeGlobalArray) { OwningPtr<JITMemoryManager> MemMgr( JITMemoryManager::CreateDefaultMemManager()); size_t Size = 4 * MemMgr->GetDefaultDataSlabSize(); uint64_t *a = (uint64_t*)MemMgr->allocateGlobal(64, 8); uint8_t *g = MemMgr->allocateGlobal(Size, 8); uint64_t *b = (uint64_t*)MemMgr->allocateGlobal(64, 8); // Check the alignment. EXPECT_EQ(0U, ((uintptr_t)a) & 0x7); EXPECT_EQ(0U, ((uintptr_t)g) & 0x7); EXPECT_EQ(0U, ((uintptr_t)b) & 0x7); // Initialize them to make sure we don't segfault and make sure they don't // overlap. memset(a, 0x1, 8); memset(g, 0x2, Size); memset(b, 0x3, 8); EXPECT_EQ(0x0101010101010101ULL, *a); // Just check the edges. EXPECT_EQ(0x02U, g[0]); EXPECT_EQ(0x02U, g[Size - 1]); EXPECT_EQ(0x0303030303030303ULL, *b); // Check the number of slabs. EXPECT_EQ(2U, MemMgr->GetNumDataSlabs()); } // Allocate lots of medium globals so that we can test moving the bump allocator // to a new slab. TEST(JITMemoryManagerTest, TestManyGlobals) { OwningPtr<JITMemoryManager> MemMgr( JITMemoryManager::CreateDefaultMemManager()); size_t SlabSize = MemMgr->GetDefaultDataSlabSize(); size_t Size = 128; int Iters = (SlabSize / Size) + 1; // We should start with no slabs. EXPECT_EQ(0U, MemMgr->GetNumDataSlabs()); // After allocating a bunch of globals, we should have two. for (int I = 0; I < Iters; ++I) MemMgr->allocateGlobal(Size, 8); EXPECT_EQ(2U, MemMgr->GetNumDataSlabs()); // And after much more, we should have three. for (int I = 0; I < Iters; ++I) MemMgr->allocateGlobal(Size, 8); EXPECT_EQ(3U, MemMgr->GetNumDataSlabs()); } // Allocate lots of function stubs so that we can test moving the stub bump // allocator to a new slab. TEST(JITMemoryManagerTest, TestManyStubs) { OwningPtr<JITMemoryManager> MemMgr( JITMemoryManager::CreateDefaultMemManager()); size_t SlabSize = MemMgr->GetDefaultStubSlabSize(); size_t Size = 128; int Iters = (SlabSize / Size) + 1; // We should start with no slabs. EXPECT_EQ(0U, MemMgr->GetNumDataSlabs()); // After allocating a bunch of stubs, we should have two. for (int I = 0; I < Iters; ++I) MemMgr->allocateStub(NULL, Size, 8); EXPECT_EQ(2U, MemMgr->GetNumStubSlabs()); // And after much more, we should have three. for (int I = 0; I < Iters; ++I) MemMgr->allocateStub(NULL, Size, 8); EXPECT_EQ(3U, MemMgr->GetNumStubSlabs()); } } <|endoftext|>
<commit_before>/* Copyright 2010 Anders Wallin (anders.e.e.wallin "at" gmail.com) * * This file is part of OpenCAMlib. * * OpenCAMlib is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenCAMlib 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 OpenCAMlib. If not, see <http://www.gnu.org/licenses/>. */ #include <boost/python.hpp> #include "point.h" #include "cutter.h" /* * wrap cutters */ using namespace ocl; namespace bp = boost::python; void export_cutters() { bp::class_<MillingCutterWrap, boost::noncopyable>("MillingCutter", bp::no_init) .def("vertexDrop", bp::pure_virtual(&MillingCutter::vertexDrop) ) .def("facetDrop", bp::pure_virtual(&MillingCutter::facetDrop) ) .def("edgeDrop", bp::pure_virtual(&MillingCutter::edgeDrop) ) //.def("offsetCutter", bp::pure_virtual(&MillingCutter::offsetCutter) ) .add_property("radius", &MillingCutter::getRadius ) .add_property("length", &MillingCutter::getLength, &MillingCutter::setLength ) .add_property("diameter", &MillingCutter::getDiameter, &MillingCutter::setDiameter ) ; bp::class_<CylCutter, bp::bases<MillingCutter> >("CylCutter") .def(bp::init<double>()) .def("vertexDrop", &CylCutter::vertexDrop) .def("facetDrop", &CylCutter::facetDrop) .def("edgeDrop", &CylCutter::edgeDrop) .def("dropCutter", &CylCutter::dropCutter) .def("vertexPush", &CylCutter::vertexPush) .def("facetPush", &CylCutter::facetPush) .def("edgePush", &CylCutter::edgePush) .def("dropCutterSTL", &CylCutter::dropCutterSTL) .def("__str__", &CylCutter::str) ; bp::class_<BallCutter, bp::bases<MillingCutter> >("BallCutter") .def(bp::init<double>()) .def("vertexDrop", &BallCutter::vertexDrop) .def("facetDrop", &BallCutter::facetDrop) .def("edgeDrop", &BallCutter::edgeDrop) .def("dropCutter", &BallCutter::dropCutter) .def("dropCutterSTL", &BallCutter::dropCutterSTL) .def("__str__", &BallCutter::str) ; bp::class_<BullCutter, bp::bases<MillingCutter> >("BullCutter") .def(bp::init<double, double>()) .def("vertexDrop", &BullCutter::vertexDrop) .def("facetDrop", &BullCutter::facetDrop) .def("edgeDrop", &BullCutter::edgeDrop) .def("__str__", &BullCutter::str) ; bp::class_<ConeCutter, bp::bases<MillingCutter> >("ConeCutter") .def(bp::init<double, double>()) .def("vertexDrop", &ConeCutter::vertexDrop) .def("facetDrop", &ConeCutter::facetDrop) .def("edgeDrop", &ConeCutter::edgeDrop) .def("__str__", &ConeCutter::str) ; bp::class_<CylConeCutter, bp::bases<MillingCutter> >("CylConeCutter") .def(bp::init<double, double, double>()) .def("vertexDrop", &CylConeCutter::vertexDrop) .def("facetDrop", &CylConeCutter::facetDrop) .def("edgeDrop", &CylConeCutter::edgeDrop) ; bp::class_<BallConeCutter, bp::bases<MillingCutter> >("BallConeCutter") .def(bp::init<double, double, double>()) .def("vertexDrop", &BallConeCutter::vertexDrop) .def("facetDrop", &BallConeCutter::facetDrop) .def("edgeDrop", &BallConeCutter::edgeDrop) ; bp::class_<BullConeCutter, bp::bases<MillingCutter> >("BullConeCutter") .def(bp::init<double, double, double, double>()) .def("vertexDrop", &BullConeCutter::vertexDrop) .def("facetDrop", &BullConeCutter::facetDrop) .def("edgeDrop", &BullConeCutter::edgeDrop) ; bp::class_<ConeConeCutter, bp::bases<MillingCutter> >("ConeConeCutter") .def(bp::init<double, double, double, double>()) .def("vertexDrop", &ConeConeCutter::vertexDrop) .def("facetDrop", &ConeConeCutter::facetDrop) .def("edgeDrop", &ConeConeCutter::edgeDrop) ; } <commit_msg>better (less code) python wrappers for the cutters<commit_after>/* Copyright 2010 Anders Wallin (anders.e.e.wallin "at" gmail.com) * * This file is part of OpenCAMlib. * * OpenCAMlib is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenCAMlib 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 OpenCAMlib. If not, see <http://www.gnu.org/licenses/>. */ #include <boost/python.hpp> #include "point.h" #include "cutter.h" /* * wrap cutters */ using namespace ocl; namespace bp = boost::python; void export_cutters() { // documentation here: // http://www.boost.org/doc/libs/1_43_0/libs/python/doc/tutorial/doc/html/python/exposing.html#python.inheritance // bp::class_<MillingCutterWrap, boost::noncopyable>("MillingCutter", bp::no_init) bp::class_<MillingCutterWrap , boost::noncopyable>("MillingCutter") .def("vertexDrop", &MillingCutter::vertexDrop, &MillingCutterWrap::default_vertexDrop ) .def("facetDrop", &MillingCutter::facetDrop ) .def("edgeDrop", &MillingCutter::edgeDrop ) .def("__str__", &MillingCutter::str, &MillingCutterWrap::default_str ) .add_property("radius", &MillingCutter::getRadius ) .add_property("length", &MillingCutter::getLength, &MillingCutter::setLength ) .add_property("diameter", &MillingCutter::getDiameter, &MillingCutter::setDiameter ) ; /* bp::class_<MillingCutter>("MillingCutter") .def("vertexDrop", &MillingCutter::vertexDrop ) .def("facetDrop", &MillingCutter::facetDrop ) .def("edgeDrop", &MillingCutter::edgeDrop ) .def("__str__", bp::virtual(&MillingCutter::str) ) .add_property("radius", &MillingCutter::getRadius ) .add_property("length", &MillingCutter::getLength, &MillingCutter::setLength ) .add_property("diameter", &MillingCutter::getDiameter, &MillingCutter::setDiameter ) ;*/ bp::class_<CylCutter, bp::bases<MillingCutter> >("CylCutter") .def(bp::init<double>()) .def("vertexDrop", &CylCutter::vertexDrop) .def("facetDrop", &CylCutter::facetDrop) .def("edgeDrop", &CylCutter::edgeDrop) .def("dropCutter", &CylCutter::dropCutter) .def("vertexPush", &CylCutter::vertexPush) .def("facetPush", &CylCutter::facetPush) .def("edgePush", &CylCutter::edgePush) //.def("offsetCutter", &CylCutter::offsetCutter, bp::return_value_policy<bp::manage_new_object>() ) .def("dropCutterSTL", &CylCutter::dropCutterSTL) ; bp::class_<BallCutter, bp::bases<MillingCutter> >("BallCutter") .def(bp::init<double>()) .def("vertexDrop", &BallCutter::vertexDrop) .def("facetDrop", &BallCutter::facetDrop) .def("edgeDrop", &BallCutter::edgeDrop) .def("dropCutter", &BallCutter::dropCutter) .def("dropCutterSTL", &BallCutter::dropCutterSTL) ; bp::class_<BullCutter, bp::bases<MillingCutter> >("BullCutter") .def(bp::init<double, double>()) .def("vertexDrop", &BullCutter::vertexDrop) .def("facetDrop", &BullCutter::facetDrop) .def("edgeDrop", &BullCutter::edgeDrop) ; bp::class_<ConeCutter, bp::bases<MillingCutter> >("ConeCutter") .def(bp::init<double, double>()) .def("vertexDrop", &ConeCutter::vertexDrop) .def("facetDrop", &ConeCutter::facetDrop) .def("edgeDrop", &ConeCutter::edgeDrop) ; bp::class_<CylConeCutter, bp::bases<MillingCutter> >("CylConeCutter") .def(bp::init<double, double, double>()) .def("vertexDrop", &CylConeCutter::vertexDrop) .def("facetDrop", &CylConeCutter::facetDrop) .def("edgeDrop", &CylConeCutter::edgeDrop) ; bp::class_<BallConeCutter, bp::bases<MillingCutter> >("BallConeCutter") .def(bp::init<double, double, double>()) .def("vertexDrop", &BallConeCutter::vertexDrop) .def("facetDrop", &BallConeCutter::facetDrop) .def("edgeDrop", &BallConeCutter::edgeDrop) ; bp::class_<BullConeCutter, bp::bases<MillingCutter> >("BullConeCutter") .def(bp::init<double, double, double, double>()) .def("vertexDrop", &BullConeCutter::vertexDrop) .def("facetDrop", &BullConeCutter::facetDrop) .def("edgeDrop", &BullConeCutter::edgeDrop) ; bp::class_<ConeConeCutter, bp::bases<MillingCutter> >("ConeConeCutter") .def(bp::init<double, double, double, double>()) .def("vertexDrop", &ConeConeCutter::vertexDrop) .def("facetDrop", &ConeConeCutter::facetDrop) .def("edgeDrop", &ConeConeCutter::edgeDrop) ; } <|endoftext|>
<commit_before>/* * Copyright 2009-2011 The VOTCA Development Team (http://www.votca.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 <stdlib.h> #include <votca/kmc/kmccalculatorfactory.h> #include <votca/kmc/kmcapplication.h> #include <string> namespace votca { namespace kmc { KMCApplication::KMCApplication() { KMCCalculatorFactory::RegisterAll(); } KMCApplication::~KMCApplication() {} void KMCApplication::Initialize() { Application::Initialize(); KMCCalculatorFactory::RegisterAll(); AddProgramOptions() ("options,o", boost::program_options::value<string>(), " program and calculator options") ("file,f", boost::program_options::value<string>(), " sqlite state file"); AddProgramOptions("Calculators") ("execute,e", boost::program_options::value<string>(), "list of calculators separated by commas or spaces") ("list,l", "lists all available calculators") ("description,d", boost::program_options::value<string>(), "detailed description of a calculator"); AddProgramOptions() ("nthreads,t", boost::program_options::value<int>()->default_value(1), " number of threads to create"); } void KMCApplication::ShowHelpText(std::ostream &out) { string name = ProgramName(); if(VersionString() != "") name = name + ", version " + VersionString(); votca::kmc::HelpTextHeader(name); HelpText(out); out << "\n\n" << OptionsDesc() << endl; } void KMCApplication::PrintDescription(const char *name, const bool length) { // loading the documentation xml file from VOTCASHARE char *votca_share = getenv("VOTCASHARE"); if(votca_share == NULL) throw std::runtime_error("VOTCASHARE not set, cannot open help files."); string xmlFile = string(getenv("VOTCASHARE")) + string("/kmc/xml/")+name+string(".xml"); try { Property options; load_property_from_xml(options, xmlFile); if ( length ) { // short description of the calculator cout << string(" ") << _fwstring(string(name),14); cout << options.get(name+string(".description")).as<string>(); } else { // long description of the calculator cout << " " << _fwstring(string(name),18); cout << options.get(name+string(".description")).as<string>() << endl; list<Property *> items = options.Select(name+string(".item")); for(list<Property*>::iterator iter = items.begin(); iter!=items.end(); ++iter) { //cout << "Long description" << endl; Property *pname=&( (*iter)->get( string("name") ) ); Property *pdesc=&( (*iter)->get( string("description") ) ); //Property *pdflt=&( (*iter)->get( string("default") ) ); if ( ! (pname->value()).empty() ) { cout << string(" -") << _fwstring(pname->value(), 14); cout << pdesc->value() << endl; } } } cout << endl; } catch(std::exception &error) { cout << string("XML file or description tag missing: ") << xmlFile << endl; } } // check if required options are provided bool KMCApplication::EvaluateOptions() { if(OptionsMap().count("list")) { cout << "Available calculators: \n"; for(KMCCalculatorFactory::assoc_map::const_iterator iter=Calculators().getObjects().begin(); iter != Calculators().getObjects().end(); ++iter) { PrintDescription( (iter->first).c_str(), _short ); } StopExecution(); return true; } if(OptionsMap().count("description")) { CheckRequired("description", "no calculator is given"); Tokenizer tok(OptionsMap()["description"].as<string>(), " ,\n\t"); // loop over the names in the description string for (Tokenizer::iterator n = tok.begin(); n != tok.end(); ++n) { // loop over calculators bool printerror = true; for(KMCCalculatorFactory::assoc_map::const_iterator iter=Calculators().getObjects().begin(); iter != Calculators().getObjects().end(); ++iter) { if ( (*n).compare( (iter->first).c_str() ) == 0 ) { PrintDescription( (iter->first).c_str(), _long ); printerror = false; break; } } if ( printerror ) cout << "Calculator " << *n << " does not exist\n"; } StopExecution(); return true; } Application::EvaluateOptions(); CheckRequired("execute", "no calculator is given"); Tokenizer tok(OptionsMap()["execute"].as<string>(), " ,\n\t"); for (Tokenizer::iterator n = tok.begin(); n != tok.end(); ++n) AddCalculator(Calculators().Create((*n).c_str())); CheckRequired("options", "please provide an xml file with program options"); CheckRequired("file", "no database file specified"); _filename = OptionsMap()["file"].as<string > (); _nThreads = OptionsMap()["nthreads"].as<int>(); //cout << " Database file: " << _filename << endl; return true; } void KMCApplication::AddCalculator(KMCCalculator* calculator) { _calculators.push_back(calculator); } void KMCApplication::Run() { load_property_from_xml(_options, _op_vm["options"].as<string>()); BeginEvaluate(); EvaluateFrame(); EndEvaluate(); } void KMCApplication::BeginEvaluate(){ list<KMCCalculator *>::iterator iter; for (iter = _calculators.begin(); iter != _calculators.end(); ++iter){ (*iter)->setnThreads(_nThreads); (*iter)->Initialize(_filename.c_str(), &_options); } } bool KMCApplication::EvaluateFrame(){ list<KMCCalculator *>::iterator iter; int i=0; for (iter = _calculators.begin(); iter != _calculators.end(); ++iter){ (*iter)->EvaluateFrame(); } } void KMCApplication::EndEvaluate(){ list<KMCCalculator *>::iterator iter; for (iter = _calculators.begin(); iter != _calculators.end(); ++iter){ (*iter)->EndEvaluate(); } } }} <commit_msg>kmc_application is adjusted to new xml help<commit_after>/* * Copyright 2009-2011 The VOTCA Development Team (http://www.votca.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 <stdlib.h> #include <votca/kmc/kmccalculatorfactory.h> #include <votca/kmc/kmcapplication.h> #include <string> namespace votca { namespace kmc { KMCApplication::KMCApplication() { KMCCalculatorFactory::RegisterAll(); } KMCApplication::~KMCApplication() {} void KMCApplication::Initialize() { Application::Initialize(); KMCCalculatorFactory::RegisterAll(); AddProgramOptions() ("options,o", boost::program_options::value<string>(), " program and calculator options") ("file,f", boost::program_options::value<string>(), " sqlite state file"); AddProgramOptions("Calculators") ("execute,e", boost::program_options::value<string>(), "list of calculators separated by commas or spaces") ("list,l", "lists all available calculators") ("description,d", boost::program_options::value<string>(), "detailed description of a calculator"); AddProgramOptions() ("nthreads,t", boost::program_options::value<int>()->default_value(1), " number of threads to create"); } void KMCApplication::ShowHelpText(std::ostream &out) { string name = ProgramName(); if(VersionString() != "") name = name + ", version " + VersionString(); votca::kmc::HelpTextHeader(name); HelpText(out); out << "\n\n" << OptionsDesc() << endl; } void KMCApplication::PrintDescription(const char *name, const bool length) { // loading the documentation xml file from VOTCASHARE char *votca_share = getenv("VOTCASHARE"); if(votca_share == NULL) throw std::runtime_error("VOTCASHARE not set, cannot open help files."); string xmlFile = string(getenv("VOTCASHARE")) + string("/kmc/xml/")+name+string(".xml"); try { Property options; load_property_from_xml(options, xmlFile); if ( length ) { // short description of the calculator cout << string(" ") << _fwstring(string(name),14); cout << options.begin()->getAttribute<string>("help"); } else { // long description of the calculator cout << HLP << options; } cout << endl; } catch(std::exception &error) { cout << string("XML file or description tag missing: ") << xmlFile << endl; } } // check if required options are provided bool KMCApplication::EvaluateOptions() { if(OptionsMap().count("list")) { cout << "Available calculators: \n"; for(KMCCalculatorFactory::assoc_map::const_iterator iter=Calculators().getObjects().begin(); iter != Calculators().getObjects().end(); ++iter) { PrintDescription( (iter->first).c_str(), _short ); } StopExecution(); return true; } if(OptionsMap().count("description")) { CheckRequired("description", "no calculator is given"); Tokenizer tok(OptionsMap()["description"].as<string>(), " ,\n\t"); // loop over the names in the description string for (Tokenizer::iterator n = tok.begin(); n != tok.end(); ++n) { // loop over calculators bool printerror = true; for(KMCCalculatorFactory::assoc_map::const_iterator iter=Calculators().getObjects().begin(); iter != Calculators().getObjects().end(); ++iter) { if ( (*n).compare( (iter->first).c_str() ) == 0 ) { PrintDescription( (iter->first).c_str(), _long ); printerror = false; break; } } if ( printerror ) cout << "Calculator " << *n << " does not exist\n"; } StopExecution(); return true; } Application::EvaluateOptions(); CheckRequired("execute", "no calculator is given"); Tokenizer tok(OptionsMap()["execute"].as<string>(), " ,\n\t"); for (Tokenizer::iterator n = tok.begin(); n != tok.end(); ++n) AddCalculator(Calculators().Create((*n).c_str())); CheckRequired("options", "please provide an xml file with program options"); CheckRequired("file", "no database file specified"); _filename = OptionsMap()["file"].as<string > (); _nThreads = OptionsMap()["nthreads"].as<int>(); //cout << " Database file: " << _filename << endl; return true; } void KMCApplication::AddCalculator(KMCCalculator* calculator) { _calculators.push_back(calculator); } void KMCApplication::Run() { load_property_from_xml(_options, _op_vm["options"].as<string>()); BeginEvaluate(); EvaluateFrame(); EndEvaluate(); } void KMCApplication::BeginEvaluate(){ list<KMCCalculator *>::iterator iter; for (iter = _calculators.begin(); iter != _calculators.end(); ++iter){ (*iter)->setnThreads(_nThreads); (*iter)->Initialize(_filename.c_str(), &_options); } } bool KMCApplication::EvaluateFrame(){ list<KMCCalculator *>::iterator iter; int i=0; for (iter = _calculators.begin(); iter != _calculators.end(); ++iter){ (*iter)->EvaluateFrame(); } } void KMCApplication::EndEvaluate(){ list<KMCCalculator *>::iterator iter; for (iter = _calculators.begin(); iter != _calculators.end(); ++iter){ (*iter)->EndEvaluate(); } } }} <|endoftext|>
<commit_before>#ifndef __STATICHASHTABLE_HPP__ #define __STATICHASHTABLE_HPP__ #include <stdexcept> #include <functional> #include "Array.hpp" template <typename T> class StaticHashMap { public: struct Pair { unsigned int key; T target; Pair (unsigned int k, T&& t) : key(k), target(std::move(t)) {}; Pair (unsigned int k, const T& t) : key(k), target(t) {}; //NOT CopyConstructible :: avoid copies, pairs are always unique in a HashTable Pair (const Pair&) = delete; //MoveConstructible Pair (Pair&& other) : Pair(other.key, std::move(other.target)) {}; //NOT CopyAssignable :: same reason Pair& operator= (const Pair& other) = delete; //MoveAssignable Pair& operator= (Pair&& other) { key = other.key; target = std::move(other.target); return *this; } }; private: Array<Array<Pair>> mTable; public: explicit StaticHashMap (const unsigned int size) : mTable(size) {} StaticHashMap (StaticHashMap&& other) : mTable(std::move(other.mTable)) {} ~StaticHashMap () {} bool exists (const unsigned int key) const { for (const Pair& x : mTable[key % mTable.getLength()]) { if (x.key == key) return true; } return false; } void add (const unsigned int key, const T& target) { //if (exists(key)) throw std::invalid_argument( "Key already exists." ); mTable[key % mTable.getLength()].pushBack(Pair(key, target)); } void add (const unsigned int key, T&& target) { //if (exists(key)) throw std::invalid_argument( "Key already exists." ); mTable[key % mTable.getLength()].pushBack(Pair(key, std::move(target))); } const Array<Pair>& operator[] (const unsigned int key) const { return mTable[key % mTable.getLength()]; } void for_each (const std::function<void (const Pair&)> func) const { for (const Array<Pair>& bucket : mTable) { for (const Pair& x : bucket) { func (x); } } } void for_each_value (const std::function<void (const T&)> func) const { for_each([&] (const Pair& x) { func(x.target); }); } void for_each_key (const std::function<void (const int&)> func) const { for_each([&] (const Pair& x) { func(x.key); }); } typename Array<Array<Pair>>::sizeType getLength() const { return mTable.getLength(); } template <typename M> friend std::ostream& operator<< (std::ostream& os, const StaticHashMap<M>& ht); }; template <typename T> std::ostream& operator<< (std::ostream& os, const StaticHashMap<T>& ht) { os << '{'; bool first = true; ht.for_each([&] (const typename StaticHashMap<T>::Pair& x) { if (!first) os << ", "; else first = false; os << x.key << " : " << x.target; }); os << '}'; return os; } #endif /* end of include guard: __STATICHASHTABLE_HPP__ */ <commit_msg>int -> uint64_t key<commit_after>#ifndef __STATICHASHTABLE_HPP__ #define __STATICHASHTABLE_HPP__ #include <stdexcept> #include <functional> #include "Array.hpp" template <typename T> class StaticHashMap { public: struct Pair { unsigned int key; T target; Pair (unsigned int k, T&& t) : key(k), target(std::move(t)) {}; Pair (unsigned int k, const T& t) : key(k), target(t) {}; //NOT CopyConstructible :: avoid copies, pairs are always unique in a HashTable Pair (const Pair&) = delete; //MoveConstructible Pair (Pair&& other) : Pair(other.key, std::move(other.target)) {}; //NOT CopyAssignable :: same reason Pair& operator= (const Pair& other) = delete; //MoveAssignable Pair& operator= (Pair&& other) { key = other.key; target = std::move(other.target); return *this; } }; private: Array<Array<Pair>> mTable; public: explicit StaticHashMap (const unsigned int size) : mTable(size) {} StaticHashMap (StaticHashMap&& other) : mTable(std::move(other.mTable)) {} ~StaticHashMap () {} bool exists (const uint64_t key) const { for (const Pair& x : mTable[key % (uint64_t)mTable.getLength()]) { if (x.key == key) return true; } return false; } void add (const uint64_t key, const T& target) { //if (exists(key)) throw std::invalid_argument( "Key already exists." ); mTable[key % (uint64_t)mTable.getLength()].pushBack(Pair(key, target)); } void add (const uint64_t key, T&& target) { //if (exists(key)) throw std::invalid_argument( "Key already exists." ); mTable[key % (uint64_t)mTable.getLength()].pushBack(Pair(key, std::move(target))); } const Array<Pair>& operator[] (const uint64_t key) const { return mTable[key % (uint64_t)mTable.getLength()]; } void for_each (const std::function<void (const Pair&)> func) const { for (const Array<Pair>& bucket : mTable) { for (const Pair& x : bucket) { func (x); } } } void for_each_value (const std::function<void (const T&)> func) const { for_each([&] (const Pair& x) { func(x.target); }); } void for_each_key (const std::function<void (const uint64_t&)> func) const { for_each([&] (const Pair& x) { func(x.key); }); } typename Array<Array<Pair>>::sizeType getLength() const { return mTable.getLength(); } template <typename M> friend std::ostream& operator<< (std::ostream& os, const StaticHashMap<M>& ht); }; template <typename T> std::ostream& operator<< (std::ostream& os, const StaticHashMap<T>& ht) { os << '{'; bool first = true; ht.for_each([&] (const typename StaticHashMap<T>::Pair& x) { if (!first) os << ", "; else first = false; os << x.key << " : " << x.target; }); os << '}'; return os; } #endif /* end of include guard: __STATICHASHTABLE_HPP__ */ <|endoftext|>
<commit_before>#include "ROOT/TThreadExecutor.hxx" #include "ROOT/TTaskGroup.hxx" #if !defined(_MSC_VER) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wshadow" #endif #include "tbb/tbb.h" #if !defined(_MSC_VER) #pragma GCC diagnostic pop #endif ////////////////////////////////////////////////////////////////////////// /// /// \class ROOT::TThreadExecutor /// \ingroup Parallelism /// \brief This class provides a simple interface to execute the same task /// multiple times in parallel, possibly with different arguments every /// time. This mimics the behaviour of python's pool.Map method. /// /// ### ROOT::TThreadExecutor::Map /// This class inherits its interfaces from ROOT::TExecutor\n. /// The two possible usages of the Map method are:\n /// * Map(F func, unsigned nTimes): func is executed nTimes with no arguments /// * Map(F func, T& args): func is executed on each element of the collection of arguments args /// /// For either signature, func is executed as many times as needed by a pool of /// nThreads threads; It defaults to the number of cores.\n /// A collection containing the result of each execution is returned.\n /// **Note:** the user is responsible for the deletion of any object that might /// be created upon execution of func, returned objects included: ROOT::TThreadExecutor never /// deletes what it returns, it simply forgets it.\n /// /// \param func /// \parblock /// a lambda expression, an std::function, a loaded macro, a /// functor class or a function that takes zero arguments (for the first signature) /// or one (for the second signature). /// \endparblock /// \param args /// \parblock /// a standard vector, a ROOT::TSeq of integer type or an initializer list for the second signature. /// An integer only for the first. /// \endparblock /// **Note:** in cases where the function to be executed takes more than /// zero/one argument but all are fixed except zero/one, the function can be wrapped /// in a lambda or via std::bind to give it the right signature.\n /// /// #### Return value: /// An std::vector. The elements in the container /// will be the objects returned by func. /// /// /// #### Examples: /// /// ~~~{.cpp} /// root[] ROOT::TThreadExecutor pool; auto hists = pool.Map(CreateHisto, 10); /// root[] ROOT::TThreadExecutor pool(2); auto squares = pool.Map([](int a) { return a*a; }, {1,2,3}); /// ~~~ /// /// ### ROOT::TThreadExecutor::MapReduce /// This set of methods behaves exactly like Map, but takes an additional /// function as a third argument. This function is applied to the set of /// objects returned by the corresponding Map execution to "squash" them /// to a single object. This function should be independent of the size of /// the vector returned by Map due to optimization of the number of chunks. /// /// If this function is a binary operator, the "squashing" will be performed in parallel. /// This is exclusive to ROOT::TThreadExecutor and not any other ROOT::TExecutor-derived classes.\n /// An integer can be passed as the fourth argument indicating the number of chunks we want to divide our work in. /// This may be useful to avoid the overhead introduced when running really short tasks. /// /// #### Examples: /// ~~~{.cpp} /// root[] ROOT::TThreadExecutor pool; auto ten = pool.MapReduce([]() { return 1; }, 10, [](std::vector<int> v) { return std::accumulate(v.begin(), v.end(), 0); }) /// root[] ROOT::TThreadExecutor pool; auto hist = pool.MapReduce(CreateAndFillHists, 10, PoolUtils::ReduceObjects); /// ~~~ /// ////////////////////////////////////////////////////////////////////////// /* VERY IMPORTANT NOTE ABOUT WORK ISOLATION We enclose the parallel_for and parallel_reduce invocations in a task_arena::isolate because we want to prevent a thread to start executing an outer task when the task it's running spawned subtasks, e.g. with a parallel_for, and is waiting on inner tasks to be completed. While this change has a negligible performance impact, it has benefits for several applications, for example big parallelised HEP frameworks and RDataFrame analyses. - For HEP Frameworks, without work isolation, it can happen that a huge framework task is pulled by a yielding ROOT task. This causes to delay the processing of the event which is interrupted by the long task. For example, work isolation avoids that during the wait due to the parallel flushing of baskets, a very long simulation task is pulled in by the idle task. - For RDataFrame analyses we want to guarantee that each entry is processed from the beginning to the end without TBB interrupting it to pull in other work items. As a corollary, the usage of ROOT (or TBB in work isolation mode) in actions and transformations guarantee that each entry is processed from the beginning to the end without being interrupted by the processing of outer tasks. */ namespace ROOT { namespace Internal { /// A helper function to implement the TThreadExecutor::ParallelReduce methods template<typename T> static T ParallelReduceHelper(const std::vector<T> &objs, const std::function<T(T a, T b)> &redfunc) { using BRange_t = tbb::blocked_range<decltype(objs.begin())>; auto pred = [redfunc](BRange_t const & range, T init) { return std::accumulate(range.begin(), range.end(), init, redfunc); }; BRange_t objRange(objs.begin(), objs.end()); return tbb::this_task_arena::isolate([&]{ return tbb::parallel_reduce(objRange, T{}, pred, redfunc); }); } } // End NS Internal } // End NS ROOT namespace ROOT { ////////////////////////////////////////////////////////////////////////// /// Class constructor. /// If the scheduler is active, gets a pointer to it and works with the current pool of threads. /// If not, initializes the pool of threads, spawning nThreads. nThreads' default value, 0, initializes the /// pool with as many logical threads as there should be available in the system (see NLogicalCores in TPoolManager.cxx). TThreadExecutor::TThreadExecutor(UInt_t nThreads) { auto current = ROOT::Internal::TPoolManager::GetPoolSize(); if (nThreads && current && (current != nThreads)) { Warning("TThreadExecutor", "There's already an active pool of threads. Proceeding with the current %d threads", current); } fSched = ROOT::Internal::GetPoolManager(nThreads); } void TThreadExecutor::ParallelFor(unsigned int start, unsigned int end, unsigned step, const std::function<void(unsigned int i)> &f) { tbb::this_task_arena::isolate([&]{ tbb::parallel_for(start, end, step, f); }); } double TThreadExecutor::ParallelReduce(const std::vector<double> &objs, const std::function<double(double a, double b)> &redfunc) { return ROOT::Internal::ParallelReduceHelper<double>(objs, redfunc); } float TThreadExecutor::ParallelReduce(const std::vector<float> &objs, const std::function<float(float a, float b)> &redfunc) { return ROOT::Internal::ParallelReduceHelper<float>(objs, redfunc); } unsigned TThreadExecutor::GetPoolSize(){ return ROOT::Internal::TPoolManager::GetPoolSize(); } } <commit_msg>[MT] Call EnableThreadSafety from TThreadExecutor's ctor<commit_after>#include "ROOT/TThreadExecutor.hxx" #include "ROOT/TTaskGroup.hxx" #if !defined(_MSC_VER) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wshadow" #endif #include "tbb/tbb.h" #if !defined(_MSC_VER) #pragma GCC diagnostic pop #endif ////////////////////////////////////////////////////////////////////////// /// /// \class ROOT::TThreadExecutor /// \ingroup Parallelism /// \brief This class provides a simple interface to execute the same task /// multiple times in parallel, possibly with different arguments every /// time. This mimics the behaviour of python's pool.Map method. /// /// ### ROOT::TThreadExecutor::Map /// This class inherits its interfaces from ROOT::TExecutor\n. /// The two possible usages of the Map method are:\n /// * Map(F func, unsigned nTimes): func is executed nTimes with no arguments /// * Map(F func, T& args): func is executed on each element of the collection of arguments args /// /// For either signature, func is executed as many times as needed by a pool of /// nThreads threads; It defaults to the number of cores.\n /// A collection containing the result of each execution is returned.\n /// **Note:** the user is responsible for the deletion of any object that might /// be created upon execution of func, returned objects included: ROOT::TThreadExecutor never /// deletes what it returns, it simply forgets it.\n /// /// \param func /// \parblock /// a lambda expression, an std::function, a loaded macro, a /// functor class or a function that takes zero arguments (for the first signature) /// or one (for the second signature). /// \endparblock /// \param args /// \parblock /// a standard vector, a ROOT::TSeq of integer type or an initializer list for the second signature. /// An integer only for the first. /// \endparblock /// **Note:** in cases where the function to be executed takes more than /// zero/one argument but all are fixed except zero/one, the function can be wrapped /// in a lambda or via std::bind to give it the right signature.\n /// /// #### Return value: /// An std::vector. The elements in the container /// will be the objects returned by func. /// /// /// #### Examples: /// /// ~~~{.cpp} /// root[] ROOT::TThreadExecutor pool; auto hists = pool.Map(CreateHisto, 10); /// root[] ROOT::TThreadExecutor pool(2); auto squares = pool.Map([](int a) { return a*a; }, {1,2,3}); /// ~~~ /// /// ### ROOT::TThreadExecutor::MapReduce /// This set of methods behaves exactly like Map, but takes an additional /// function as a third argument. This function is applied to the set of /// objects returned by the corresponding Map execution to "squash" them /// to a single object. This function should be independent of the size of /// the vector returned by Map due to optimization of the number of chunks. /// /// If this function is a binary operator, the "squashing" will be performed in parallel. /// This is exclusive to ROOT::TThreadExecutor and not any other ROOT::TExecutor-derived classes.\n /// An integer can be passed as the fourth argument indicating the number of chunks we want to divide our work in. /// This may be useful to avoid the overhead introduced when running really short tasks. /// /// #### Examples: /// ~~~{.cpp} /// root[] ROOT::TThreadExecutor pool; auto ten = pool.MapReduce([]() { return 1; }, 10, [](std::vector<int> v) { return std::accumulate(v.begin(), v.end(), 0); }) /// root[] ROOT::TThreadExecutor pool; auto hist = pool.MapReduce(CreateAndFillHists, 10, PoolUtils::ReduceObjects); /// ~~~ /// ////////////////////////////////////////////////////////////////////////// /* VERY IMPORTANT NOTE ABOUT WORK ISOLATION We enclose the parallel_for and parallel_reduce invocations in a task_arena::isolate because we want to prevent a thread to start executing an outer task when the task it's running spawned subtasks, e.g. with a parallel_for, and is waiting on inner tasks to be completed. While this change has a negligible performance impact, it has benefits for several applications, for example big parallelised HEP frameworks and RDataFrame analyses. - For HEP Frameworks, without work isolation, it can happen that a huge framework task is pulled by a yielding ROOT task. This causes to delay the processing of the event which is interrupted by the long task. For example, work isolation avoids that during the wait due to the parallel flushing of baskets, a very long simulation task is pulled in by the idle task. - For RDataFrame analyses we want to guarantee that each entry is processed from the beginning to the end without TBB interrupting it to pull in other work items. As a corollary, the usage of ROOT (or TBB in work isolation mode) in actions and transformations guarantee that each entry is processed from the beginning to the end without being interrupted by the processing of outer tasks. */ namespace ROOT { namespace Internal { /// A helper function to implement the TThreadExecutor::ParallelReduce methods template<typename T> static T ParallelReduceHelper(const std::vector<T> &objs, const std::function<T(T a, T b)> &redfunc) { using BRange_t = tbb::blocked_range<decltype(objs.begin())>; auto pred = [redfunc](BRange_t const & range, T init) { return std::accumulate(range.begin(), range.end(), init, redfunc); }; BRange_t objRange(objs.begin(), objs.end()); return tbb::this_task_arena::isolate([&]{ return tbb::parallel_reduce(objRange, T{}, pred, redfunc); }); } } // End NS Internal } // End NS ROOT namespace ROOT { ////////////////////////////////////////////////////////////////////////// /// Class constructor. /// If the scheduler is active (e.g. because another TThreadExecutor is in flight, or ROOT::EnableImplicitMT() was /// called), work with the current pool of threads. /// If not, initialize the pool of threads, spawning nThreads. nThreads' default value, 0, initializes the /// pool with as many logical threads as are available in the system (see NLogicalCores in TPoolManager.cxx). /// /// At construction time, TThreadExecutor automatically enables ROOT's thread-safety locks as per calling /// ROOT::EnableThreadSafety(). TThreadExecutor::TThreadExecutor(UInt_t nThreads) { ROOT::EnableThreadSafety(); auto current = ROOT::Internal::TPoolManager::GetPoolSize(); if (nThreads && current && (current != nThreads)) { Warning("TThreadExecutor", "There's already an active pool of threads. Proceeding with the current %d threads", current); } fSched = ROOT::Internal::GetPoolManager(nThreads); } void TThreadExecutor::ParallelFor(unsigned int start, unsigned int end, unsigned step, const std::function<void(unsigned int i)> &f) { tbb::this_task_arena::isolate([&]{ tbb::parallel_for(start, end, step, f); }); } double TThreadExecutor::ParallelReduce(const std::vector<double> &objs, const std::function<double(double a, double b)> &redfunc) { return ROOT::Internal::ParallelReduceHelper<double>(objs, redfunc); } float TThreadExecutor::ParallelReduce(const std::vector<float> &objs, const std::function<float(float a, float b)> &redfunc) { return ROOT::Internal::ParallelReduceHelper<float>(objs, redfunc); } unsigned TThreadExecutor::GetPoolSize(){ return ROOT::Internal::TPoolManager::GetPoolSize(); } } <|endoftext|>
<commit_before>/* Copyright (C) 2013 Slawomir Cygan <slawomir.cygan@gmail.com> * * 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 "gl-auxcontext.h" #include "gl-state.h" #include "display.h" #include "native-surface.h" #include "pointers.h" #include <sstream> namespace dglState { GLAuxContextSession::GLAuxContextSession(GLAuxContext* ctx):m_ctx(ctx) { m_ctx->doRefCurrent(); } GLAuxContextSession::~GLAuxContextSession() { m_ctx->doUnrefCurrent(); } GLAuxContextSurface::GLAuxContextSurface(const DGLDisplayState* display, opaque_id_t pixfmt):m_DisplayId(display->getId()), m_Id(0) { EGLint attributes[] = { EGL_HEIGHT, 1, EGL_WIDTH, 1, EGL_NONE }; m_Id = (opaque_id_t)DIRECT_CALL_CHK(eglCreatePbufferSurface)((EGLDisplay)m_DisplayId, (EGLConfig)pixfmt, attributes); if (!m_Id) { throw std::runtime_error("Cannot allocate axualiary pbuffer surface"); } } GLAuxContextSurface::~GLAuxContextSurface() { if (m_Id) { DIRECT_CALL_CHK(eglDestroySurface)((EGLDisplay)m_DisplayId, (EGLSurface)m_Id); } } opaque_id_t GLAuxContextSurface::getId() const { return m_Id; } GLAuxContext::GLAuxContext(const GLContext* origCtx):queries(this), m_Id(0),m_PixelFormat(0), m_Parrent(origCtx), m_MakeCurrentRef(0) { if (m_Parrent->getDisplay()->getType() != DGLDisplayState::Type::EGL) { throw std::runtime_error("auxaliary contexts implemented only for EGL"); } std::vector<EGLint> eglAttributes(m_Parrent->getContextCreationData().getAttribs().size()); for (size_t i = 0; i < m_Parrent->getContextCreationData().getAttribs().size(); i++) { eglAttributes[i] = (EGLint)m_Parrent->getContextCreationData().getAttribs()[i]; } eglAttributes.push_back(EGL_NONE); m_PixelFormat = choosePixelFormat(m_Parrent->getContextCreationData().getPixelFormat(), m_Parrent->getDisplay()->getId()); switch (origCtx->getContextCreationData().getEntryPoint()) { case eglCreateContext_Call: m_Id = (opaque_id_t)DIRECT_CALL_CHK(eglCreateContext)( (EGLDisplay)m_Parrent->getDisplay()->getId(), (EGLConfig)m_PixelFormat, (EGLContext)m_Parrent->getId(), &eglAttributes[0] ); break; } if (!m_Id) { throw std::runtime_error("Cannot allocate auxaliary context"); } } GLAuxContext::~GLAuxContext() { while (m_MakeCurrentRef) { doUnrefCurrent(); } if (m_Id) { DIRECT_CALL_CHK(eglDestroyContext)((EGLDisplay)m_Parrent->getDisplay()->getId(), (EGLContext)m_Id); } } GLAuxContextSession GLAuxContext::makeCurrent() { return GLAuxContextSession(this); } void GLAuxContext::doRefCurrent() { if (!m_MakeCurrentRef) { if (!m_AuxSurface) { m_AuxSurface = std::make_shared<GLAuxContextSurface>(m_Parrent->getDisplay(), m_PixelFormat); } EGLBoolean status = DIRECT_CALL_CHK(eglMakeCurrent)( (EGLDisplay)m_Parrent->getDisplay()->getId(), (EGLSurface)m_AuxSurface->getId(), (EGLSurface)m_AuxSurface->getId(), (EGLContext)m_Id); if (!status) { throw std::runtime_error("Cannot switch to auxaliary context."); } queries.setupInitialState(); } m_MakeCurrentRef ++; } void GLAuxContext::doUnrefCurrent() { if (m_MakeCurrentRef) { m_MakeCurrentRef--; } if (!m_MakeCurrentRef) { EGLBoolean status = DIRECT_CALL_CHK(eglMakeCurrent)( (EGLDisplay)m_Parrent->getDisplay()->getId(), (EGLSurface)m_Parrent->getNativeDrawSurface()->getId(), (EGLSurface)m_Parrent->getNativeReadSurface()->getId(), (EGLContext)m_Parrent->getId()); if (!status) { throw std::runtime_error("Cannot switch back from auxaliary context."); } } } opaque_id_t GLAuxContext::choosePixelFormat(opaque_id_t preferred, opaque_id_t displayId) { EGLDisplay eglDpy = (EGLDisplay)displayId; EGLConfig preferredConfig = (EGLConfig)preferred; EGLint supportedSurfType = 0; EGLBoolean status = EGL_TRUE; status &= DIRECT_CALL_CHK(eglGetConfigAttrib)(eglDpy, preferredConfig, EGL_SURFACE_TYPE, &supportedSurfType); if (!status) { throw std::runtime_error("Cannot query EGLConfig associated with ctx"); } EGLConfig ret; if (supportedSurfType & EGL_PBUFFER_BIT) { ret = preferredConfig; } else { EGLint renderableType = 0; if (m_Parrent->getVersion().check(GLContextVersion::Type::DT)) { renderableType = EGL_OPENGL_BIT; } else if (m_Parrent->getVersion().check(GLContextVersion::Type::ES, 3)) { renderableType = EGL_OPENGL_ES3_BIT_KHR; } else if (m_Parrent->getVersion().check(GLContextVersion::Type::ES, 2)) { renderableType = EGL_OPENGL_ES2_BIT; } else if (m_Parrent->getVersion().check(GLContextVersion::Type::ES, 1)) { renderableType = EGL_OPENGL_ES_BIT; } EGLint attributes [] = { EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, EGL_RED_SIZE, 1, EGL_GREEN_SIZE, 1, EGL_BLUE_SIZE, 1, EGL_ALPHA_SIZE, 1, EGL_RENDERABLE_TYPE, renderableType, EGL_NONE }; EGLint numConfigs = 0; status &= DIRECT_CALL_CHK(eglChooseConfig)(eglDpy, attributes, &ret, 1, &numConfigs); if ((status != EGL_TRUE) || numConfigs < 1) { throw std::runtime_error("Cannot choose EGLConfig capable of driving auxaliary context"); } } return (opaque_id_t)ret; } GLAuxContext::GLQueries::GLQueries(GLAuxContext* ctx):m_InitialState(false),m_AuxCtx(ctx) {} void GLAuxContext::GLQueries::setupInitialState() { if (m_InitialState) return DIRECT_CALL_CHK(glGenFramebuffers)(1, &fbo); DIRECT_CALL_CHK(glBindFramebuffer)(GL_FRAMEBUFFER, fbo); DIRECT_CALL_CHK(glGenRenderbuffers)(1, &rbo); DIRECT_CALL_CHK(glBindRenderbuffer)(GL_RENDERBUFFER, rbo); DIRECT_CALL_CHK(glFramebufferRenderbuffer)(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, rbo); if (m_AuxCtx->m_Parrent->getVersion().check(GLContextVersion::Type::ES, 3) || m_AuxCtx->m_Parrent->getVersion().check(GLContextVersion::Type::DT, 3)) { DIRECT_CALL_CHK(glGenVertexArrays)(1, &vao); DIRECT_CALL_CHK(glBindVertexArray)(vao); } DIRECT_CALL_CHK(glGenBuffers)(1, &vbo); DIRECT_CALL_CHK(glBindBuffer)(GL_ARRAY_BUFFER, vbo); GLfloat triangleStrip[] = { -1.0f, 1.0f, 0.0f, 1.0f, -1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, -1.0f, 0.0f, 1.0f }; DIRECT_CALL_CHK(glBufferData)(GL_ARRAY_BUFFER, sizeof(triangleStrip), triangleStrip, GL_STATIC_DRAW); DIRECT_CALL_CHK(glVertexAttribPointer)(0, 4, GL_FLOAT, GL_FALSE, 0, NULL); vshobj = DIRECT_CALL_CHK(glCreateShader)(GL_VERTEX_SHADER); const char * vsh = "attribute vec4 inPos;\n" "varying vec2 texPos;\n" "void main() {\n" " gl_Position = inPos;\n" " texPos = inPos.xy * 0.5 + 0.5;\n" "}\n"; DIRECT_CALL_CHK(glShaderSource)(vshobj, 1, &vsh, NULL); DIRECT_CALL_CHK(glCompileShader)(vshobj); GLint status = 0; DIRECT_CALL_CHK(glGetShaderiv)(vshobj, GL_COMPILE_STATUS, &status); if (!status) { char log[1000]; DIRECT_CALL_CHK(glGetShaderInfoLog)(vshobj, 1000, NULL, log); throw std::runtime_error(std::string("Cannot compile vertex shader") + log); } if (DIRECT_CALL_CHK(glGetError)() != GL_NO_ERROR) { throw std::runtime_error("Got GL error on auxiliary context"); } m_InitialState = true; } void GLAuxContext::GLQueries::auxGetTexImage(GLuint name, GLenum target, GLint level, GLenum format, GLenum type, int width, int height, GLvoid* pixels) { if (!m_AuxCtx->m_Parrent->getVersion().check(GLContextVersion::Type::ES, 2)) { throw std::runtime_error("GLAuxContext::GLQueries::auxGetTexImage not implemented for this context version"); } if (!DIRECT_CALL_CHK(glIsTexture)(name)) { throw std::runtime_error("Texture object not found in auxaliary context"); } GLenum bindableTarget = target; if (target >= GL_TEXTURE_CUBE_MAP_POSITIVE_X && target <= GL_TEXTURE_CUBE_MAP_NEGATIVE_Z) { target = GL_TEXTURE_CUBE_MAP; } DIRECT_CALL_CHK(glBindTexture)(bindableTarget, name); DIRECT_CALL_CHK(glRenderbufferStorage)(GL_RENDERBUFFER, GL_RGBA4, width, height); GLuint program = getTextureShaderProgram(target, format); DIRECT_CALL_CHK(glUseProgram)(program); DIRECT_CALL_CHK(glUniform1f)(DIRECT_CALL_CHK(glGetUniformLocation)(program, "level"), static_cast<GLfloat>(level)); DIRECT_CALL_CHK(glDrawArrays)(GL_TRIANGLE_STRIP, 0, 4); DIRECT_CALL_CHK(glReadPixels)(0, 0, width, height, format, type, pixels); if (DIRECT_CALL_CHK(glGetError)() != GL_NO_ERROR) { throw std::runtime_error("Got GL error on auxiliary context"); } } GLuint GLAuxContext::GLQueries::getTextureShaderProgram(GLenum target, GLenum format) { std::string suffix, pos; if (format != GL_RGBA) { throw std::runtime_error("GLAuxContext::GLQueries::getTextureShaderProgram: format unsupported"); } switch (target) { case GL_TEXTURE_1D: suffix = "1D"; pos = "texPos.x"; break; case GL_TEXTURE_2D: suffix = "2D"; pos = "vec2(texPos.xy)"; break; case GL_TEXTURE_RECTANGLE: suffix = "Rect"; pos = "vec2(texPos.xy)"; break; case GL_TEXTURE_1D_ARRAY: suffix = "1DArray"; pos = "vec2(texPos.xy)"; break; //case GL_TEXTURE_CUBE_MAP: // suffix = "Cube"; // pos = // break; default: throw std::runtime_error("cannot generate program for this texture target"); } bool glsl300 = m_AuxCtx->m_Parrent->getVersion().check(GLContextVersion::Type::ES, 3); std::ostringstream fsh; if (glsl300) { fsh << "#version 300 es\n" << "out vec4 oColor\n;" << "varying vec2 texPos;\n"; } fsh << "#ifdef GL_FRAGMENT_PRECISION_HIGH\n" << "precision highp float; \n" << "#else \n" << "precision mediump float; \n" << "#endif \n" "uniform sampler" << suffix << " s;\n" "uniform float level;\n" << "varying vec2 texPos;\n"; fsh << "void main() {\n"; if (glsl300) { fsh << " oColor = textureLod(s, "; } else { fsh << " gl_FragColor = texture" << suffix << "(s, "; } fsh << pos; if (glsl300) { fsh << ", level"; } fsh << ");\n" << "}\n"; auto i = programs.find(fsh.str()); if (i != programs.end()) { return i->second; } else { GLuint program = DIRECT_CALL_CHK(glCreateProgram)(); DIRECT_CALL_CHK(glAttachShader)(program, vshobj); GLuint fShader = DIRECT_CALL_CHK(glCreateShader)(GL_FRAGMENT_SHADER); DIRECT_CALL_CHK(glAttachShader)(program, fShader); DIRECT_CALL_CHK(glDeleteShader)(fShader); std::string fshStr = fsh.str(); const char* csrc[] = { fshStr.c_str() }; DIRECT_CALL_CHK(glShaderSource)(fShader, 1, csrc, NULL); DIRECT_CALL_CHK(glCompileShader)(fShader); GLint status = 0; DIRECT_CALL_CHK(glGetShaderiv)(fShader, GL_COMPILE_STATUS, &status); if (!status) { char log[1000]; DIRECT_CALL_CHK(glGetShaderInfoLog)(fShader, 1000, NULL, log); throw std::runtime_error(std::string("Cannot compile fragment shader:") + log); } DIRECT_CALL_CHK(glLinkProgram)(program); DIRECT_CALL_CHK(glGetProgramiv)(program, GL_LINK_STATUS, &status); if (status != GL_TRUE) { char log[10000]; DIRECT_CALL_CHK(glGetProgramInfoLog)(program, 10000, NULL, log); DIRECT_CALL_CHK(glDeleteProgram)(program); throw std::runtime_error(std::string("cannot link program: ") + log); } else { programs[fshStr] = program; return program; } } } } //namespace dglState<commit_msg>Auxcontext state: added missing VA enable. Now simple texture queries work<commit_after>/* Copyright (C) 2013 Slawomir Cygan <slawomir.cygan@gmail.com> * * 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 "gl-auxcontext.h" #include "gl-state.h" #include "display.h" #include "native-surface.h" #include "pointers.h" #include <sstream> namespace dglState { GLAuxContextSession::GLAuxContextSession(GLAuxContext* ctx):m_ctx(ctx) { m_ctx->doRefCurrent(); } GLAuxContextSession::~GLAuxContextSession() { m_ctx->doUnrefCurrent(); } GLAuxContextSurface::GLAuxContextSurface(const DGLDisplayState* display, opaque_id_t pixfmt):m_DisplayId(display->getId()), m_Id(0) { EGLint attributes[] = { EGL_HEIGHT, 1, EGL_WIDTH, 1, EGL_NONE }; m_Id = (opaque_id_t)DIRECT_CALL_CHK(eglCreatePbufferSurface)((EGLDisplay)m_DisplayId, (EGLConfig)pixfmt, attributes); if (!m_Id) { throw std::runtime_error("Cannot allocate axualiary pbuffer surface"); } } GLAuxContextSurface::~GLAuxContextSurface() { if (m_Id) { DIRECT_CALL_CHK(eglDestroySurface)((EGLDisplay)m_DisplayId, (EGLSurface)m_Id); } } opaque_id_t GLAuxContextSurface::getId() const { return m_Id; } GLAuxContext::GLAuxContext(const GLContext* origCtx):queries(this), m_Id(0),m_PixelFormat(0), m_Parrent(origCtx), m_MakeCurrentRef(0) { if (m_Parrent->getDisplay()->getType() != DGLDisplayState::Type::EGL) { throw std::runtime_error("auxaliary contexts implemented only for EGL"); } std::vector<EGLint> eglAttributes(m_Parrent->getContextCreationData().getAttribs().size()); for (size_t i = 0; i < m_Parrent->getContextCreationData().getAttribs().size(); i++) { eglAttributes[i] = (EGLint)m_Parrent->getContextCreationData().getAttribs()[i]; } eglAttributes.push_back(EGL_NONE); m_PixelFormat = choosePixelFormat(m_Parrent->getContextCreationData().getPixelFormat(), m_Parrent->getDisplay()->getId()); switch (origCtx->getContextCreationData().getEntryPoint()) { case eglCreateContext_Call: m_Id = (opaque_id_t)DIRECT_CALL_CHK(eglCreateContext)( (EGLDisplay)m_Parrent->getDisplay()->getId(), (EGLConfig)m_PixelFormat, (EGLContext)m_Parrent->getId(), &eglAttributes[0] ); break; } if (!m_Id) { throw std::runtime_error("Cannot allocate auxaliary context"); } } GLAuxContext::~GLAuxContext() { while (m_MakeCurrentRef) { doUnrefCurrent(); } if (m_Id) { DIRECT_CALL_CHK(eglDestroyContext)((EGLDisplay)m_Parrent->getDisplay()->getId(), (EGLContext)m_Id); } } GLAuxContextSession GLAuxContext::makeCurrent() { return GLAuxContextSession(this); } void GLAuxContext::doRefCurrent() { if (!m_MakeCurrentRef) { if (!m_AuxSurface) { m_AuxSurface = std::make_shared<GLAuxContextSurface>(m_Parrent->getDisplay(), m_PixelFormat); } EGLBoolean status = DIRECT_CALL_CHK(eglMakeCurrent)( (EGLDisplay)m_Parrent->getDisplay()->getId(), (EGLSurface)m_AuxSurface->getId(), (EGLSurface)m_AuxSurface->getId(), (EGLContext)m_Id); if (!status) { throw std::runtime_error("Cannot switch to auxaliary context."); } queries.setupInitialState(); } m_MakeCurrentRef ++; } void GLAuxContext::doUnrefCurrent() { if (m_MakeCurrentRef) { m_MakeCurrentRef--; } if (!m_MakeCurrentRef) { EGLBoolean status = DIRECT_CALL_CHK(eglMakeCurrent)( (EGLDisplay)m_Parrent->getDisplay()->getId(), (EGLSurface)m_Parrent->getNativeDrawSurface()->getId(), (EGLSurface)m_Parrent->getNativeReadSurface()->getId(), (EGLContext)m_Parrent->getId()); if (!status) { throw std::runtime_error("Cannot switch back from auxaliary context."); } } } opaque_id_t GLAuxContext::choosePixelFormat(opaque_id_t preferred, opaque_id_t displayId) { EGLDisplay eglDpy = (EGLDisplay)displayId; EGLConfig preferredConfig = (EGLConfig)preferred; EGLint supportedSurfType = 0; EGLBoolean status = EGL_TRUE; status &= DIRECT_CALL_CHK(eglGetConfigAttrib)(eglDpy, preferredConfig, EGL_SURFACE_TYPE, &supportedSurfType); if (!status) { throw std::runtime_error("Cannot query EGLConfig associated with ctx"); } EGLConfig ret; if (supportedSurfType & EGL_PBUFFER_BIT) { ret = preferredConfig; } else { EGLint renderableType = 0; if (m_Parrent->getVersion().check(GLContextVersion::Type::DT)) { renderableType = EGL_OPENGL_BIT; } else if (m_Parrent->getVersion().check(GLContextVersion::Type::ES, 3)) { renderableType = EGL_OPENGL_ES3_BIT_KHR; } else if (m_Parrent->getVersion().check(GLContextVersion::Type::ES, 2)) { renderableType = EGL_OPENGL_ES2_BIT; } else if (m_Parrent->getVersion().check(GLContextVersion::Type::ES, 1)) { renderableType = EGL_OPENGL_ES_BIT; } EGLint attributes [] = { EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, EGL_RED_SIZE, 1, EGL_GREEN_SIZE, 1, EGL_BLUE_SIZE, 1, EGL_ALPHA_SIZE, 1, EGL_RENDERABLE_TYPE, renderableType, EGL_NONE }; EGLint numConfigs = 0; status &= DIRECT_CALL_CHK(eglChooseConfig)(eglDpy, attributes, &ret, 1, &numConfigs); if ((status != EGL_TRUE) || numConfigs < 1) { throw std::runtime_error("Cannot choose EGLConfig capable of driving auxaliary context"); } } return (opaque_id_t)ret; } GLAuxContext::GLQueries::GLQueries(GLAuxContext* ctx):m_InitialState(false),m_AuxCtx(ctx) {} void GLAuxContext::GLQueries::setupInitialState() { if (m_InitialState) return DIRECT_CALL_CHK(glGenFramebuffers)(1, &fbo); DIRECT_CALL_CHK(glBindFramebuffer)(GL_FRAMEBUFFER, fbo); DIRECT_CALL_CHK(glGenRenderbuffers)(1, &rbo); DIRECT_CALL_CHK(glBindRenderbuffer)(GL_RENDERBUFFER, rbo); DIRECT_CALL_CHK(glFramebufferRenderbuffer)(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, rbo); if (m_AuxCtx->m_Parrent->getVersion().check(GLContextVersion::Type::ES, 3) || m_AuxCtx->m_Parrent->getVersion().check(GLContextVersion::Type::DT, 3)) { DIRECT_CALL_CHK(glGenVertexArrays)(1, &vao); DIRECT_CALL_CHK(glBindVertexArray)(vao); } DIRECT_CALL_CHK(glGenBuffers)(1, &vbo); DIRECT_CALL_CHK(glBindBuffer)(GL_ARRAY_BUFFER, vbo); GLfloat triangleStrip[] = { -1.0f, 1.0f, 0.0f, 1.0f, -1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, -1.0f, 0.0f, 1.0f }; DIRECT_CALL_CHK(glBufferData)(GL_ARRAY_BUFFER, sizeof(triangleStrip), triangleStrip, GL_STATIC_DRAW); DIRECT_CALL_CHK(glVertexAttribPointer)(0, 4, GL_FLOAT, GL_FALSE, 0, NULL); DIRECT_CALL_CHK(glEnableVertexAttribArray)(0); vshobj = DIRECT_CALL_CHK(glCreateShader)(GL_VERTEX_SHADER); const char * vsh = "attribute vec4 inPos;\n" "varying vec2 texPos;\n" "void main() {\n" " gl_Position = inPos;\n" " texPos = inPos.xy * 0.5 + 0.5;\n" "}\n"; DIRECT_CALL_CHK(glShaderSource)(vshobj, 1, &vsh, NULL); DIRECT_CALL_CHK(glCompileShader)(vshobj); GLint status = 0; DIRECT_CALL_CHK(glGetShaderiv)(vshobj, GL_COMPILE_STATUS, &status); if (!status) { char log[1000]; DIRECT_CALL_CHK(glGetShaderInfoLog)(vshobj, 1000, NULL, log); throw std::runtime_error(std::string("Cannot compile vertex shader") + log); } if (DIRECT_CALL_CHK(glGetError)() != GL_NO_ERROR) { throw std::runtime_error("Got GL error on auxiliary context"); } m_InitialState = true; } void GLAuxContext::GLQueries::auxGetTexImage(GLuint name, GLenum target, GLint level, GLenum format, GLenum type, int width, int height, GLvoid* pixels) { if (!m_AuxCtx->m_Parrent->getVersion().check(GLContextVersion::Type::ES, 2)) { throw std::runtime_error("GLAuxContext::GLQueries::auxGetTexImage not implemented for this context version"); } if (!DIRECT_CALL_CHK(glIsTexture)(name)) { throw std::runtime_error("Texture object not found in auxaliary context"); } GLenum bindableTarget = target; if (target >= GL_TEXTURE_CUBE_MAP_POSITIVE_X && target <= GL_TEXTURE_CUBE_MAP_NEGATIVE_Z) { target = GL_TEXTURE_CUBE_MAP; } DIRECT_CALL_CHK(glBindTexture)(bindableTarget, name); DIRECT_CALL_CHK(glRenderbufferStorage)(GL_RENDERBUFFER, GL_RGBA4, width, height); GLuint program = getTextureShaderProgram(target, format); DIRECT_CALL_CHK(glUseProgram)(program); DIRECT_CALL_CHK(glUniform1f)(DIRECT_CALL_CHK(glGetUniformLocation)(program, "level"), static_cast<GLfloat>(level)); DIRECT_CALL_CHK(glDrawArrays)(GL_TRIANGLE_STRIP, 0, 4); DIRECT_CALL_CHK(glReadPixels)(0, 0, width, height, format, type, pixels); if (DIRECT_CALL_CHK(glGetError)() != GL_NO_ERROR) { throw std::runtime_error("Got GL error on auxiliary context"); } } GLuint GLAuxContext::GLQueries::getTextureShaderProgram(GLenum target, GLenum format) { std::string suffix, pos; if (format != GL_RGBA) { throw std::runtime_error("GLAuxContext::GLQueries::getTextureShaderProgram: format unsupported"); } switch (target) { case GL_TEXTURE_1D: suffix = "1D"; pos = "texPos.x"; break; case GL_TEXTURE_2D: suffix = "2D"; pos = "vec2(texPos.xy)"; break; case GL_TEXTURE_RECTANGLE: suffix = "Rect"; pos = "vec2(texPos.xy)"; break; case GL_TEXTURE_1D_ARRAY: suffix = "1DArray"; pos = "vec2(texPos.xy)"; break; //case GL_TEXTURE_CUBE_MAP: // suffix = "Cube"; // pos = // break; default: throw std::runtime_error("cannot generate program for this texture target"); } bool glsl300 = m_AuxCtx->m_Parrent->getVersion().check(GLContextVersion::Type::ES, 3); std::ostringstream fsh; if (glsl300) { fsh << "#version 300 es\n" << "out vec4 oColor\n;" << "varying vec2 texPos;\n"; } fsh << "#ifdef GL_FRAGMENT_PRECISION_HIGH\n" << "precision highp float; \n" << "#else \n" << "precision mediump float; \n" << "#endif \n" "uniform sampler" << suffix << " s;\n" "uniform float level;\n" << "varying vec2 texPos;\n"; fsh << "void main() {\n"; if (glsl300) { fsh << " oColor = textureLod(s, "; } else { fsh << " gl_FragColor = texture" << suffix << "(s, "; } fsh << pos; if (glsl300) { fsh << ", level"; } fsh << ");\n" << "}\n"; auto i = programs.find(fsh.str()); if (i != programs.end()) { return i->second; } else { GLuint program = DIRECT_CALL_CHK(glCreateProgram)(); DIRECT_CALL_CHK(glAttachShader)(program, vshobj); GLuint fShader = DIRECT_CALL_CHK(glCreateShader)(GL_FRAGMENT_SHADER); DIRECT_CALL_CHK(glAttachShader)(program, fShader); DIRECT_CALL_CHK(glDeleteShader)(fShader); std::string fshStr = fsh.str(); const char* csrc[] = { fshStr.c_str() }; DIRECT_CALL_CHK(glShaderSource)(fShader, 1, csrc, NULL); DIRECT_CALL_CHK(glCompileShader)(fShader); GLint status = 0; DIRECT_CALL_CHK(glGetShaderiv)(fShader, GL_COMPILE_STATUS, &status); if (!status) { char log[1000]; DIRECT_CALL_CHK(glGetShaderInfoLog)(fShader, 1000, NULL, log); throw std::runtime_error(std::string("Cannot compile fragment shader:") + log); } DIRECT_CALL_CHK(glLinkProgram)(program); DIRECT_CALL_CHK(glGetProgramiv)(program, GL_LINK_STATUS, &status); if (status != GL_TRUE) { char log[10000]; DIRECT_CALL_CHK(glGetProgramInfoLog)(program, 10000, NULL, log); DIRECT_CALL_CHK(glDeleteProgram)(program); throw std::runtime_error(std::string("cannot link program: ") + log); } else { programs[fshStr] = program; return program; } } } } //namespace dglState<|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: sdiocmpt.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: pjunck $ $Date: 2004-11-03 08:53:40 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #pragma hdrstop #ifndef _DEBUG_HXX //autogen #include <tools/debug.hxx> #endif #include "sdiocmpt.hxx" //BFS02 ////////////////////////////////////////////////////////////////////////////// old_SdrDownCompat::old_SdrDownCompat(SvStream& rNewStream, UINT16 nNewMode) : rStream(rNewStream), nSubRecSiz(0), nSubRecPos(0), nMode(nNewMode), bOpen(FALSE) { OpenSubRecord(); } old_SdrDownCompat::~old_SdrDownCompat() { if(bOpen) CloseSubRecord(); } void old_SdrDownCompat::Read() { rStream >> nSubRecSiz; } void old_SdrDownCompat::Write() { rStream << nSubRecSiz; } void old_SdrDownCompat::OpenSubRecord() { if(rStream.GetError()) return; nSubRecPos = rStream.Tell(); if(nMode == STREAM_READ) { Read(); } else if(nMode == STREAM_WRITE) { Write(); } bOpen = TRUE; } void old_SdrDownCompat::CloseSubRecord() { if(rStream.GetError()) return; UINT32 nAktPos(rStream.Tell()); if(nMode == STREAM_READ) { UINT32 nReadAnz(nAktPos - nSubRecPos); if(nReadAnz != nSubRecSiz) { rStream.Seek(nSubRecPos + nSubRecSiz); } } else if(nMode == STREAM_WRITE) { nSubRecSiz = nAktPos - nSubRecPos; rStream.Seek(nSubRecPos); Write(); rStream.Seek(nAktPos); } bOpen = FALSE; } /************************************************************************* |* |* Konstruktor, schreibt bzw. liest Versionsnummer |* \************************************************************************/ SdIOCompat::SdIOCompat(SvStream& rNewStream, USHORT nNewMode, UINT16 nVer) : old_SdrDownCompat(rNewStream, nNewMode), nVersion(nVer) { if (nNewMode == STREAM_WRITE) { DBG_ASSERT(nVer != SDIOCOMPAT_VERSIONDONTKNOW, "kann unbekannte Version nicht schreiben"); rNewStream << nVersion; } else if (nNewMode == STREAM_READ) { DBG_ASSERT(nVer == SDIOCOMPAT_VERSIONDONTKNOW, "Lesen mit Angabe der Version ist Quatsch!"); rNewStream >> nVersion; } } SdIOCompat::~SdIOCompat() { } // eof <commit_msg>INTEGRATION: CWS ooo19126 (1.2.310); FILE MERGED 2005/09/05 13:20:20 rt 1.2.310.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: sdiocmpt.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-09 03:13:28 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #pragma hdrstop #ifndef _DEBUG_HXX //autogen #include <tools/debug.hxx> #endif #include "sdiocmpt.hxx" //BFS02 ////////////////////////////////////////////////////////////////////////////// old_SdrDownCompat::old_SdrDownCompat(SvStream& rNewStream, UINT16 nNewMode) : rStream(rNewStream), nSubRecSiz(0), nSubRecPos(0), nMode(nNewMode), bOpen(FALSE) { OpenSubRecord(); } old_SdrDownCompat::~old_SdrDownCompat() { if(bOpen) CloseSubRecord(); } void old_SdrDownCompat::Read() { rStream >> nSubRecSiz; } void old_SdrDownCompat::Write() { rStream << nSubRecSiz; } void old_SdrDownCompat::OpenSubRecord() { if(rStream.GetError()) return; nSubRecPos = rStream.Tell(); if(nMode == STREAM_READ) { Read(); } else if(nMode == STREAM_WRITE) { Write(); } bOpen = TRUE; } void old_SdrDownCompat::CloseSubRecord() { if(rStream.GetError()) return; UINT32 nAktPos(rStream.Tell()); if(nMode == STREAM_READ) { UINT32 nReadAnz(nAktPos - nSubRecPos); if(nReadAnz != nSubRecSiz) { rStream.Seek(nSubRecPos + nSubRecSiz); } } else if(nMode == STREAM_WRITE) { nSubRecSiz = nAktPos - nSubRecPos; rStream.Seek(nSubRecPos); Write(); rStream.Seek(nAktPos); } bOpen = FALSE; } /************************************************************************* |* |* Konstruktor, schreibt bzw. liest Versionsnummer |* \************************************************************************/ SdIOCompat::SdIOCompat(SvStream& rNewStream, USHORT nNewMode, UINT16 nVer) : old_SdrDownCompat(rNewStream, nNewMode), nVersion(nVer) { if (nNewMode == STREAM_WRITE) { DBG_ASSERT(nVer != SDIOCOMPAT_VERSIONDONTKNOW, "kann unbekannte Version nicht schreiben"); rNewStream << nVersion; } else if (nNewMode == STREAM_READ) { DBG_ASSERT(nVer == SDIOCOMPAT_VERSIONDONTKNOW, "Lesen mit Angabe der Version ist Quatsch!"); rNewStream >> nVersion; } } SdIOCompat::~SdIOCompat() { } // eof <|endoftext|>
<commit_before>#include <iostream> #include "Spellable.h" using namespace std; int main(int argc, char** argv) { int i = 195; Spellable<int> si(&i); Spellable<int> sj(i); cout << i << endl << si.spell() << endl << endl; // si is bound to i i = 190; cout << i << endl << si.spell() << endl; cout << sj.GetValue() << endl << sj.spell() << endl; // We can also, obviously, use a constant Spellable<int> sk(190); cout << sk.GetValue() << endl << sk.spell() << endl << endl; // TODO: This is the largest long long and it is off by one // Slightly smaller numbers are off by an order of magnitude Spellable<long long> sm(9223372036854775807); cout << sm.GetValue() << endl << sm.spell() << endl << endl; // Some quirks of floating point Spellable<double> sg(20.12312); cout << sg.GetValue() << endl << sg.spell() << endl; cout.precision(3); cout << sg.GetValue() << endl << sg.spell() << endl; cout.precision(4); cout << sg.GetValue() << endl << sg.spell() << endl; cout.precision(5); cout << sg.GetValue() << endl << sg.spell() << endl; // TODO: Fixing the decimal causes the fraction's precision to be short /* cout.setf(ios::fixed, ios::floatfield); cout << sg.GetValue() << endl << sg.spell() << endl; cout.precision(14); cout << sg.GetValue() << endl << sg.spell() << endl; */ return 0; } <commit_msg>Update main.cpp<commit_after>#include <iostream> #include "Spellable.h" using namespace std; int main(int argc, char** argv) { int i = 195; Spellable<int> si(&i); Spellable<int> sj(i); cout << i << endl << si.spell() << endl << endl; // si is bound to i i = 190; cout << i << endl << si.spell() << endl; cout << sj.GetValue() << endl << sj.spell() << endl; // We can also, obviously, use a constant Spellable<int> sk(190); cout << sk.GetValue() << endl << sk.spell() << endl << endl; Spellable<double> sg(20.12315); cout << sg.GetValue() << endl << sg.spell() << endl; sg = 20.5; cout << sg.GetValue() << endl << sg.spell() << endl; sg = 20.1; cout << sg.GetValue() << endl << sg.spell() << endl; sg = 1.0 / 3.0; cout << sg.GetValue() << endl << sg.spell() << endl; cout.precision(7); cout << sg.GetValue() << endl << sg.spell() << endl; cout.setf(ios::fixed, ios::floatfield); cout << sg.GetValue() << endl << sg.spell() << endl; // The following crashes the program cout.precision(14); cout << sg.GetValue() << endl << sg.spell() << endl; cout.unsetf(ios::floatfield); // We can handle assignment and negative numbers sg = -4234.62; cout << sg.GetValue() << endl << sg.spell() << endl; return 0; // TODO: This is the largest long long and it is off by one // Slightly smaller numbers are off by an order of magnitude //Spellable<long long> sm(9223372036854775807); //cout << sm.GetValue() << endl << sm.spell() << endl << endl; } <|endoftext|>
<commit_before>/* * Copyright (C) 2015 Cloudius Systems, Ltd. */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include "sets.hh" #include "constants.hh" #include "cql3_type.hh" namespace cql3 { shared_ptr<column_specification> sets::value_spec_of(shared_ptr<column_specification> column) { return make_shared<column_specification>(column->ks_name, column->cf_name, ::make_shared<column_identifier>(sprint("value(%s)", *column->name), true), dynamic_pointer_cast<const set_type_impl>(column->type)->get_elements_type()); } shared_ptr<term> sets::literal::prepare(database& db, const sstring& keyspace, shared_ptr<column_specification> receiver) { validate_assignable_to(db, keyspace, receiver); // We've parsed empty maps as a set literal to break the ambiguity so // handle that case now if (_elements.empty() && dynamic_pointer_cast<const map_type_impl>(receiver->type)) { // use empty_type for comparator, set is empty anyway. std::map<bytes, bytes, serialized_compare> m(empty_type->as_less_comparator()); return ::make_shared<maps::value>(std::move(m)); } auto value_spec = value_spec_of(receiver); std::vector<shared_ptr<term>> values; values.reserve(_elements.size()); bool all_terminal = true; for (shared_ptr<term::raw> rt : _elements) { auto t = rt->prepare(db, keyspace, value_spec); if (t->contains_bind_marker()) { throw exceptions::invalid_request_exception(sprint("Invalid set literal for %s: bind variables are not supported inside collection literals", *receiver->name)); } if (dynamic_pointer_cast<non_terminal>(t)) { all_terminal = false; } values.push_back(std::move(t)); } auto compare = dynamic_pointer_cast<const set_type_impl>(receiver->type)->get_elements_type()->as_less_comparator(); auto value = ::make_shared<delayed_value>(compare, std::move(values)); if (all_terminal) { return value->bind(query_options::DEFAULT); } else { return value; } } void sets::literal::validate_assignable_to(database& db, const sstring& keyspace, shared_ptr<column_specification> receiver) { if (!dynamic_pointer_cast<const set_type_impl>(receiver->type)) { // We've parsed empty maps as a set literal to break the ambiguity so // handle that case now if (dynamic_pointer_cast<const map_type_impl>(receiver->type) && _elements.empty()) { return; } throw exceptions::invalid_request_exception(sprint("Invalid set literal for %s of type %s", *receiver->name, *receiver->type->as_cql3_type())); } auto&& value_spec = value_spec_of(receiver); for (shared_ptr<term::raw> rt : _elements) { if (!is_assignable(rt->test_assignment(db, keyspace, value_spec))) { throw exceptions::invalid_request_exception(sprint("Invalid set literal for %s: value %s is not of type %s", *receiver->name, *rt, *value_spec->type->as_cql3_type())); } } } assignment_testable::test_result sets::literal::test_assignment(database& db, const sstring& keyspace, shared_ptr<column_specification> receiver) { if (!dynamic_pointer_cast<const set_type_impl>(receiver->type)) { // We've parsed empty maps as a set literal to break the ambiguity so handle that case now if (dynamic_pointer_cast<const map_type_impl>(receiver->type) && _elements.empty()) { return assignment_testable::test_result::WEAKLY_ASSIGNABLE; } return assignment_testable::test_result::NOT_ASSIGNABLE; } // If there is no elements, we can't say it's an exact match (an empty set if fundamentally polymorphic). if (_elements.empty()) { return assignment_testable::test_result::WEAKLY_ASSIGNABLE; } auto&& value_spec = value_spec_of(receiver); // FIXME: make assignment_testable::test_all() accept ranges std::vector<shared_ptr<assignment_testable>> to_test(_elements.begin(), _elements.end()); return assignment_testable::test_all(db, keyspace, value_spec, to_test); } sstring sets::literal::to_string() const { return "{" + join(", ", _elements) + "}"; } sets::value sets::value::from_serialized(bytes_view v, set_type type, serialization_format sf) { try { // Collections have this small hack that validate cannot be called on a serialized object, // but compose does the validation (so we're fine). // FIXME: deserializeForNativeProtocol?! auto s = value_cast<set_type_impl::native_type>(type->deserialize(v, sf)); std::set<bytes, serialized_compare> elements(type->get_elements_type()->as_less_comparator()); for (auto&& element : s) { elements.insert(elements.end(), type->get_elements_type()->decompose(element)); } return value(std::move(elements)); } catch (marshal_exception& e) { throw exceptions::invalid_request_exception(e.what()); } } bytes_opt sets::value::get(const query_options& options) { return get_with_protocol_version(options.get_serialization_format()); } bytes sets::value::get_with_protocol_version(serialization_format sf) { return collection_type_impl::pack(_elements.begin(), _elements.end(), _elements.size(), sf); } bool sets::value::equals(set_type st, const value& v) { if (_elements.size() != v._elements.size()) { return false; } auto&& elements_type = st->get_elements_type(); return std::equal(_elements.begin(), _elements.end(), v._elements.begin(), [elements_type] (bytes_view v1, bytes_view v2) { return elements_type->equal(v1, v2); }); } sstring sets::value::to_string() const { sstring result = "{"; bool first = true; for (auto&& e : _elements) { if (!first) { result += ", "; } first = true; result += to_hex(e); } result += "}"; return result; } bool sets::delayed_value::contains_bind_marker() const { // False since we don't support them in collection return false; } void sets::delayed_value::collect_marker_specification(shared_ptr<variable_specifications> bound_names) { } shared_ptr<terminal> sets::delayed_value::bind(const query_options& options) { std::set<bytes, serialized_compare> buffers(_comparator); for (auto&& t : _elements) { auto b = t->bind_and_get(options); if (!b) { throw exceptions::invalid_request_exception("null is not supported inside collections"); } // We don't support value > 64K because the serialization format encode the length as an unsigned short. if (b->size() > std::numeric_limits<uint16_t>::max()) { throw exceptions::invalid_request_exception(sprint("Set value is too long. Set values are limited to %d bytes but %d bytes value provided", std::numeric_limits<uint16_t>::max(), b->size())); } buffers.insert(buffers.end(), std::move(to_bytes(*b))); } return ::make_shared<value>(std::move(buffers)); } ::shared_ptr<terminal> sets::marker::bind(const query_options& options) { const auto& value = options.get_value_at(_bind_index); if (!value) { return nullptr; } else { auto as_set_type = static_pointer_cast<const set_type_impl>(_receiver->type); return make_shared(value::from_serialized(*value, as_set_type, options.get_serialization_format())); } } void sets::setter::execute(mutation& m, const exploded_clustering_prefix& row_key, const update_parameters& params) { if (column.type->is_multi_cell()) { // delete + add collection_type_impl::mutation mut; mut.tomb = params.make_tombstone_just_before(); auto ctype = static_pointer_cast<const set_type_impl>(column.type); auto col_mut = ctype->serialize_mutation_form(std::move(mut)); m.set_cell(row_key, column, std::move(col_mut)); } adder::do_add(m, row_key, params, _t, column); } void sets::adder::execute(mutation& m, const exploded_clustering_prefix& row_key, const update_parameters& params) { assert(column.type->is_multi_cell()); // "Attempted to add items to a frozen set"; do_add(m, row_key, params, _t, column); } void sets::adder::do_add(mutation& m, const exploded_clustering_prefix& row_key, const update_parameters& params, shared_ptr<term> t, const column_definition& column) { auto&& value = t->bind(params._options); auto set_value = dynamic_pointer_cast<sets::value>(std::move(value)); auto set_type = dynamic_pointer_cast<const set_type_impl>(column.type); if (column.type->is_multi_cell()) { // FIXME: mutation_view? not compatible with params.make_cell(). collection_type_impl::mutation mut; if (!set_value || set_value->_elements.empty()) { return; } for (auto&& e : set_value->_elements) { mut.cells.emplace_back(e, params.make_cell({})); } auto smut = set_type->serialize_mutation_form(mut); m.set_cell(row_key, column, std::move(smut)); } else { // for frozen sets, we're overwriting the whole cell auto v = set_type->serialize_partially_deserialized_form( {set_value->_elements.begin(), set_value->_elements.end()}, serialization_format::internal()); if (set_value->_elements.empty()) { m.set_cell(row_key, column, params.make_dead_cell()); } else { m.set_cell(row_key, column, params.make_cell(std::move(v))); } } } void sets::discarder::execute(mutation& m, const exploded_clustering_prefix& row_key, const update_parameters& params) { assert(column.type->is_multi_cell()); // "Attempted to remove items from a frozen set"; auto&& value = _t->bind(params._options); if (!value) { return; } collection_type_impl::mutation mut; auto kill = [&] (bytes idx) { mut.cells.push_back({std::move(idx), params.make_dead_cell()}); }; auto svalue = dynamic_pointer_cast<sets::value>(value); assert(svalue); mut.cells.reserve(svalue->_elements.size()); for (auto&& e : svalue->_elements) { kill(e); } auto ctype = static_pointer_cast<const collection_type_impl>(column.type); m.set_cell(row_key, column, atomic_cell_or_collection::from_collection_mutation( ctype->serialize_mutation_form(mut))); } void sets::element_discarder::execute(mutation& m, const exploded_clustering_prefix& row_key, const update_parameters& params) { assert(column.type->is_multi_cell() && "Attempted to remove items from a frozen set"); auto elt = _t->bind(params._options); if (!elt) { throw exceptions::invalid_request_exception("Invalid null set element"); } collection_type_impl::mutation mut; mut.cells.emplace_back(*elt->get(params._options), params.make_dead_cell()); auto ctype = static_pointer_cast<const collection_type_impl>(column.type); m.set_cell(row_key, column, ctype->serialize_mutation_form(mut)); } } <commit_msg>cql3::sets: Make insert/update frozen set handle null/empty correctly<commit_after>/* * Copyright (C) 2015 Cloudius Systems, Ltd. */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include "sets.hh" #include "constants.hh" #include "cql3_type.hh" namespace cql3 { shared_ptr<column_specification> sets::value_spec_of(shared_ptr<column_specification> column) { return make_shared<column_specification>(column->ks_name, column->cf_name, ::make_shared<column_identifier>(sprint("value(%s)", *column->name), true), dynamic_pointer_cast<const set_type_impl>(column->type)->get_elements_type()); } shared_ptr<term> sets::literal::prepare(database& db, const sstring& keyspace, shared_ptr<column_specification> receiver) { validate_assignable_to(db, keyspace, receiver); // We've parsed empty maps as a set literal to break the ambiguity so // handle that case now if (_elements.empty() && dynamic_pointer_cast<const map_type_impl>(receiver->type)) { // use empty_type for comparator, set is empty anyway. std::map<bytes, bytes, serialized_compare> m(empty_type->as_less_comparator()); return ::make_shared<maps::value>(std::move(m)); } auto value_spec = value_spec_of(receiver); std::vector<shared_ptr<term>> values; values.reserve(_elements.size()); bool all_terminal = true; for (shared_ptr<term::raw> rt : _elements) { auto t = rt->prepare(db, keyspace, value_spec); if (t->contains_bind_marker()) { throw exceptions::invalid_request_exception(sprint("Invalid set literal for %s: bind variables are not supported inside collection literals", *receiver->name)); } if (dynamic_pointer_cast<non_terminal>(t)) { all_terminal = false; } values.push_back(std::move(t)); } auto compare = dynamic_pointer_cast<const set_type_impl>(receiver->type)->get_elements_type()->as_less_comparator(); auto value = ::make_shared<delayed_value>(compare, std::move(values)); if (all_terminal) { return value->bind(query_options::DEFAULT); } else { return value; } } void sets::literal::validate_assignable_to(database& db, const sstring& keyspace, shared_ptr<column_specification> receiver) { if (!dynamic_pointer_cast<const set_type_impl>(receiver->type)) { // We've parsed empty maps as a set literal to break the ambiguity so // handle that case now if (dynamic_pointer_cast<const map_type_impl>(receiver->type) && _elements.empty()) { return; } throw exceptions::invalid_request_exception(sprint("Invalid set literal for %s of type %s", *receiver->name, *receiver->type->as_cql3_type())); } auto&& value_spec = value_spec_of(receiver); for (shared_ptr<term::raw> rt : _elements) { if (!is_assignable(rt->test_assignment(db, keyspace, value_spec))) { throw exceptions::invalid_request_exception(sprint("Invalid set literal for %s: value %s is not of type %s", *receiver->name, *rt, *value_spec->type->as_cql3_type())); } } } assignment_testable::test_result sets::literal::test_assignment(database& db, const sstring& keyspace, shared_ptr<column_specification> receiver) { if (!dynamic_pointer_cast<const set_type_impl>(receiver->type)) { // We've parsed empty maps as a set literal to break the ambiguity so handle that case now if (dynamic_pointer_cast<const map_type_impl>(receiver->type) && _elements.empty()) { return assignment_testable::test_result::WEAKLY_ASSIGNABLE; } return assignment_testable::test_result::NOT_ASSIGNABLE; } // If there is no elements, we can't say it's an exact match (an empty set if fundamentally polymorphic). if (_elements.empty()) { return assignment_testable::test_result::WEAKLY_ASSIGNABLE; } auto&& value_spec = value_spec_of(receiver); // FIXME: make assignment_testable::test_all() accept ranges std::vector<shared_ptr<assignment_testable>> to_test(_elements.begin(), _elements.end()); return assignment_testable::test_all(db, keyspace, value_spec, to_test); } sstring sets::literal::to_string() const { return "{" + join(", ", _elements) + "}"; } sets::value sets::value::from_serialized(bytes_view v, set_type type, serialization_format sf) { try { // Collections have this small hack that validate cannot be called on a serialized object, // but compose does the validation (so we're fine). // FIXME: deserializeForNativeProtocol?! auto s = value_cast<set_type_impl::native_type>(type->deserialize(v, sf)); std::set<bytes, serialized_compare> elements(type->get_elements_type()->as_less_comparator()); for (auto&& element : s) { elements.insert(elements.end(), type->get_elements_type()->decompose(element)); } return value(std::move(elements)); } catch (marshal_exception& e) { throw exceptions::invalid_request_exception(e.what()); } } bytes_opt sets::value::get(const query_options& options) { return get_with_protocol_version(options.get_serialization_format()); } bytes sets::value::get_with_protocol_version(serialization_format sf) { return collection_type_impl::pack(_elements.begin(), _elements.end(), _elements.size(), sf); } bool sets::value::equals(set_type st, const value& v) { if (_elements.size() != v._elements.size()) { return false; } auto&& elements_type = st->get_elements_type(); return std::equal(_elements.begin(), _elements.end(), v._elements.begin(), [elements_type] (bytes_view v1, bytes_view v2) { return elements_type->equal(v1, v2); }); } sstring sets::value::to_string() const { sstring result = "{"; bool first = true; for (auto&& e : _elements) { if (!first) { result += ", "; } first = true; result += to_hex(e); } result += "}"; return result; } bool sets::delayed_value::contains_bind_marker() const { // False since we don't support them in collection return false; } void sets::delayed_value::collect_marker_specification(shared_ptr<variable_specifications> bound_names) { } shared_ptr<terminal> sets::delayed_value::bind(const query_options& options) { std::set<bytes, serialized_compare> buffers(_comparator); for (auto&& t : _elements) { auto b = t->bind_and_get(options); if (!b) { throw exceptions::invalid_request_exception("null is not supported inside collections"); } // We don't support value > 64K because the serialization format encode the length as an unsigned short. if (b->size() > std::numeric_limits<uint16_t>::max()) { throw exceptions::invalid_request_exception(sprint("Set value is too long. Set values are limited to %d bytes but %d bytes value provided", std::numeric_limits<uint16_t>::max(), b->size())); } buffers.insert(buffers.end(), std::move(to_bytes(*b))); } return ::make_shared<value>(std::move(buffers)); } ::shared_ptr<terminal> sets::marker::bind(const query_options& options) { const auto& value = options.get_value_at(_bind_index); if (!value) { return nullptr; } else { auto as_set_type = static_pointer_cast<const set_type_impl>(_receiver->type); return make_shared(value::from_serialized(*value, as_set_type, options.get_serialization_format())); } } void sets::setter::execute(mutation& m, const exploded_clustering_prefix& row_key, const update_parameters& params) { if (column.type->is_multi_cell()) { // delete + add collection_type_impl::mutation mut; mut.tomb = params.make_tombstone_just_before(); auto ctype = static_pointer_cast<const set_type_impl>(column.type); auto col_mut = ctype->serialize_mutation_form(std::move(mut)); m.set_cell(row_key, column, std::move(col_mut)); } adder::do_add(m, row_key, params, _t, column); } void sets::adder::execute(mutation& m, const exploded_clustering_prefix& row_key, const update_parameters& params) { assert(column.type->is_multi_cell()); // "Attempted to add items to a frozen set"; do_add(m, row_key, params, _t, column); } void sets::adder::do_add(mutation& m, const exploded_clustering_prefix& row_key, const update_parameters& params, shared_ptr<term> t, const column_definition& column) { auto&& value = t->bind(params._options); auto set_value = dynamic_pointer_cast<sets::value>(std::move(value)); auto set_type = dynamic_pointer_cast<const set_type_impl>(column.type); if (column.type->is_multi_cell()) { // FIXME: mutation_view? not compatible with params.make_cell(). collection_type_impl::mutation mut; if (!set_value || set_value->_elements.empty()) { return; } for (auto&& e : set_value->_elements) { mut.cells.emplace_back(e, params.make_cell({})); } auto smut = set_type->serialize_mutation_form(mut); m.set_cell(row_key, column, std::move(smut)); } else if (set_value != nullptr) { // for frozen sets, we're overwriting the whole cell auto v = set_type->serialize_partially_deserialized_form( {set_value->_elements.begin(), set_value->_elements.end()}, serialization_format::internal()); m.set_cell(row_key, column, params.make_cell(std::move(v))); } else { m.set_cell(row_key, column, params.make_dead_cell()); } } void sets::discarder::execute(mutation& m, const exploded_clustering_prefix& row_key, const update_parameters& params) { assert(column.type->is_multi_cell()); // "Attempted to remove items from a frozen set"; auto&& value = _t->bind(params._options); if (!value) { return; } collection_type_impl::mutation mut; auto kill = [&] (bytes idx) { mut.cells.push_back({std::move(idx), params.make_dead_cell()}); }; auto svalue = dynamic_pointer_cast<sets::value>(value); assert(svalue); mut.cells.reserve(svalue->_elements.size()); for (auto&& e : svalue->_elements) { kill(e); } auto ctype = static_pointer_cast<const collection_type_impl>(column.type); m.set_cell(row_key, column, atomic_cell_or_collection::from_collection_mutation( ctype->serialize_mutation_form(mut))); } void sets::element_discarder::execute(mutation& m, const exploded_clustering_prefix& row_key, const update_parameters& params) { assert(column.type->is_multi_cell() && "Attempted to remove items from a frozen set"); auto elt = _t->bind(params._options); if (!elt) { throw exceptions::invalid_request_exception("Invalid null set element"); } collection_type_impl::mutation mut; mut.cells.emplace_back(*elt->get(params._options), params.make_dead_cell()); auto ctype = static_pointer_cast<const collection_type_impl>(column.type); m.set_cell(row_key, column, ctype->serialize_mutation_form(mut)); } } <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007-2015, Image Engine Design 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 Image Engine Design nor the names of any // other contributors to this software 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 "IECoreMaya/FromMayaCameraConverter.h" #include "IECoreMaya/Convert.h" #include "IECore/CompoundParameter.h" #include "IECore/AngleConversion.h" #include "IECoreScene/Camera.h" #include "IECoreScene/MatrixTransform.h" #include "maya/MFnCamera.h" #include "maya/MFnEnumAttribute.h" #include "maya/MString.h" #include "maya/MRenderUtil.h" #include "maya/MCommonRenderSettingsData.h" #include "maya/MDagPath.h" #include "maya/MPlug.h" #include "OpenEXR/ImathMath.h" using namespace IECoreMaya; using namespace IECore; using namespace IECoreScene; using namespace Imath; namespace { // It's awesome that not only does Maya bake this random mm-to-inch conversion into their // camera, but they use the pre 1959 definition of the inch const float INCH_TO_MM = 25.400051; } IE_CORE_DEFINERUNTIMETYPED( FromMayaCameraConverter ); FromMayaDagNodeConverter::Description<FromMayaCameraConverter> FromMayaCameraConverter::m_description( MFn::kCamera, Camera::staticTypeId(), true ); FromMayaCameraConverter::FromMayaCameraConverter( const MDagPath &dagPath ) : FromMayaDagNodeConverter( "Converts maya camera shape nodes into IECoreScene::Camera objects.", dagPath ) { } IECore::ObjectPtr FromMayaCameraConverter::doConversion( const MDagPath &dagPath, IECore::ConstCompoundObjectPtr operands ) const { MFnCamera fnCamera( dagPath ); // convert things that are required by the IECore::Renderer specification CameraPtr result = new Camera; if( fnCamera.hasAttribute( "ieCamera_overrideResolution" ) ) { MStatus success1, success2; MPlug resPlug( fnCamera.object(), fnCamera.attribute( "ieCamera_overrideResolution" )); if( resPlug.numChildren() == 2 ) { int x = resPlug.child(0).asInt( MDGContext::fsNormal, &success1 ); int y = resPlug.child(1).asInt( MDGContext::fsNormal, &success2 ); if( success1 == MS::kSuccess && success2 == MS::kSuccess ) { result->setResolution( Imath::V2i( x, y ) ); } } } if( fnCamera.hasAttribute( "ieCamera_overridePixelAspectRatio" ) ) { MStatus success; float overridePixelAspectRatio = MPlug( fnCamera.object(), fnCamera.attribute( "ieCamera_overridePixelAspectRatio" ) ).asFloat( MDGContext::fsNormal, &success ); if( success == MS::kSuccess ) { result->setPixelAspectRatio( overridePixelAspectRatio ); } } if( fnCamera.hasAttribute( "ieCamera_overrideFilmFit" ) ) { MStatus success; MPlug overrideFilmFitPlug( fnCamera.object(), fnCamera.attribute( "ieCamera_overrideFilmFit" ) ); MFnEnumAttribute enumAttr( overrideFilmFitPlug.attribute(), &success ); if( success == MS::kSuccess ) { MString overrideFilmFit = enumAttr.fieldName( overrideFilmFitPlug.asInt( MDGContext::fsNormal, &success) ); if( success == MS::kSuccess ) { if( overrideFilmFit == "Horizontal" ) { result->setFilmFit( Camera::FilmFit::Horizontal ); } else if( overrideFilmFit == "Vertical" ) { result->setFilmFit( Camera::FilmFit::Vertical ); } else if( overrideFilmFit == "Fit" ) { result->setFilmFit( Camera::FilmFit::Fit ); } else if( overrideFilmFit == "Fill" ) { result->setFilmFit( Camera::FilmFit::Fill ); } else if( overrideFilmFit == "Distort" ) { result->setFilmFit( Camera::FilmFit::Distort ); } } } } result->setClippingPlanes( Imath::V2f( fnCamera.nearClippingPlane(), fnCamera.farClippingPlane() ) ); if( fnCamera.isOrtho() ) { // orthographic result->setProjection( "orthographic" ); result->setAperture( V2f( fnCamera.orthoWidth() ) ); } else { // perspective result->setProjection( "perspective" ); result->setAperture( INCH_TO_MM * V2f( fnCamera.horizontalFilmAperture(), fnCamera.verticalFilmAperture() ) ); result->setApertureOffset( INCH_TO_MM * V2f( fnCamera.horizontalFilmOffset(), fnCamera.verticalFilmOffset() ) ); result->setFocalLength( fnCamera.focalLength() ); } if( fnCamera.isDepthOfField() ) { result->setFStop( fnCamera.fStop() ); } result->setFocusDistance( fnCamera.focusDistance() ); return result; } <commit_msg>IECoreMaya : Build fixes for Maya 2018<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007-2015, Image Engine Design 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 Image Engine Design nor the names of any // other contributors to this software 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 "IECoreMaya/FromMayaCameraConverter.h" #include "IECoreMaya/Convert.h" #include "IECore/CompoundParameter.h" #include "IECore/AngleConversion.h" #include "IECoreScene/Camera.h" #include "IECoreScene/MatrixTransform.h" #include "maya/MFnCamera.h" #include "maya/MFnEnumAttribute.h" #include "maya/MString.h" #include "maya/MRenderUtil.h" #include "maya/MCommonRenderSettingsData.h" #include "maya/MDagPath.h" #include "maya/MPlug.h" #include "OpenEXR/ImathMath.h" using namespace IECoreMaya; using namespace IECore; using namespace IECoreScene; using namespace Imath; namespace { // It's awesome that not only does Maya bake this random mm-to-inch conversion into their // camera, but they use the pre 1959 definition of the inch const float INCH_TO_MM = 25.400051; } IE_CORE_DEFINERUNTIMETYPED( FromMayaCameraConverter ); FromMayaDagNodeConverter::Description<FromMayaCameraConverter> FromMayaCameraConverter::m_description( MFn::kCamera, Camera::staticTypeId(), true ); FromMayaCameraConverter::FromMayaCameraConverter( const MDagPath &dagPath ) : FromMayaDagNodeConverter( "Converts maya camera shape nodes into IECoreScene::Camera objects.", dagPath ) { } IECore::ObjectPtr FromMayaCameraConverter::doConversion( const MDagPath &dagPath, IECore::ConstCompoundObjectPtr operands ) const { MFnCamera fnCamera( dagPath ); // convert things that are required by the IECore::Renderer specification CameraPtr result = new Camera; if( fnCamera.hasAttribute( "ieCamera_overrideResolution" ) ) { MStatus success1, success2; MPlug resPlug( fnCamera.object(), fnCamera.attribute( "ieCamera_overrideResolution" )); if( resPlug.numChildren() == 2 ) { #if MAYA_API_VERSION >= 20180000 int x = resPlug.child(0).asInt( &success1 ); int y = resPlug.child(1).asInt( &success2 ); #else int x = resPlug.child(0).asInt( MDGContext::fsNormal, &success1 ); int y = resPlug.child(1).asInt( MDGContext::fsNormal, &success2 ); #endif if( success1 == MS::kSuccess && success2 == MS::kSuccess ) { result->setResolution( Imath::V2i( x, y ) ); } } } if( fnCamera.hasAttribute( "ieCamera_overridePixelAspectRatio" ) ) { MStatus success; MPlug overridePixelAspectRatioPlug( fnCamera.object(), fnCamera.attribute( "ieCamera_overridePixelAspectRatio" ) ); #if MAYA_API_VERSION >= 20180000 float overridePixelAspectRatio = overridePixelAspectRatioPlug.asFloat( &success ); #else float overridePixelAspectRatio = overridePixelAspectRatioPlug.asFloat( MDGContext::fsNormal, &success ); #endif if( success == MS::kSuccess ) { result->setPixelAspectRatio( overridePixelAspectRatio ); } } if( fnCamera.hasAttribute( "ieCamera_overrideFilmFit" ) ) { MStatus success; MPlug overrideFilmFitPlug( fnCamera.object(), fnCamera.attribute( "ieCamera_overrideFilmFit" ) ); MFnEnumAttribute enumAttr( overrideFilmFitPlug.attribute(), &success ); if( success == MS::kSuccess ) { #if MAYA_API_VERSION >= 20180000 MString overrideFilmFit = enumAttr.fieldName( overrideFilmFitPlug.asInt( &success) ); #else MString overrideFilmFit = enumAttr.fieldName( overrideFilmFitPlug.asInt( MDGContext::fsNormal, &success) ); #endif if( success == MS::kSuccess ) { if( overrideFilmFit == "Horizontal" ) { result->setFilmFit( Camera::FilmFit::Horizontal ); } else if( overrideFilmFit == "Vertical" ) { result->setFilmFit( Camera::FilmFit::Vertical ); } else if( overrideFilmFit == "Fit" ) { result->setFilmFit( Camera::FilmFit::Fit ); } else if( overrideFilmFit == "Fill" ) { result->setFilmFit( Camera::FilmFit::Fill ); } else if( overrideFilmFit == "Distort" ) { result->setFilmFit( Camera::FilmFit::Distort ); } } } } result->setClippingPlanes( Imath::V2f( fnCamera.nearClippingPlane(), fnCamera.farClippingPlane() ) ); if( fnCamera.isOrtho() ) { // orthographic result->setProjection( "orthographic" ); result->setAperture( V2f( fnCamera.orthoWidth() ) ); } else { // perspective result->setProjection( "perspective" ); result->setAperture( INCH_TO_MM * V2f( fnCamera.horizontalFilmAperture(), fnCamera.verticalFilmAperture() ) ); result->setApertureOffset( INCH_TO_MM * V2f( fnCamera.horizontalFilmOffset(), fnCamera.verticalFilmOffset() ) ); result->setFocalLength( fnCamera.focalLength() ); } if( fnCamera.isDepthOfField() ) { result->setFStop( fnCamera.fStop() ); } result->setFocusDistance( fnCamera.focusDistance() ); return result; } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/widget/desktop_native_widget_helper_aura.h" #include "ui/aura/client/dispatcher_client.h" #include "ui/aura/client/screen_position_client.h" #include "ui/aura/cursor_manager.h" #include "ui/aura/desktop/desktop_activation_client.h" #include "ui/aura/desktop/desktop_dispatcher_client.h" #include "ui/aura/focus_manager.h" #include "ui/aura/root_window.h" #include "ui/aura/shared/compound_event_filter.h" #include "ui/aura/shared/input_method_event_filter.h" #include "ui/aura/shared/root_window_capture_client.h" #include "ui/aura/window_property.h" #include "ui/views/widget/native_widget_aura.h" #if defined(OS_WIN) #include "ui/base/win/hwnd_subclass.h" #include "ui/views/widget/widget_message_filter.h" #elif defined(USE_X11) #include "ui/views/widget/x11_desktop_handler.h" #include "ui/views/widget/x11_window_event_filter.h" #endif DECLARE_WINDOW_PROPERTY_TYPE(aura::Window*); namespace views { DEFINE_WINDOW_PROPERTY_KEY( aura::Window*, kViewsWindowForRootWindow, NULL); namespace { // Client that always offsets the passed in point by the RootHost's origin. class RootWindowScreenPositionClient : public aura::client::ScreenPositionClient { public: explicit RootWindowScreenPositionClient(aura::RootWindow* root_window) : root_window_(root_window) {} virtual ~RootWindowScreenPositionClient() {} // aura::client::ScreenPositionClient: virtual void ConvertToScreenPoint(gfx::Point* screen_point) OVERRIDE { gfx::Point origin = root_window_->GetHostOrigin(); screen_point->Offset(origin.x(), origin.y()); } private: aura::RootWindow* root_window_; }; // Client that always offsets by the toplevel RootWindow of the passed in child // NativeWidgetAura. class EmbeddedWindowScreenPositionClient : public aura::client::ScreenPositionClient { public: explicit EmbeddedWindowScreenPositionClient(NativeWidgetAura* widget) : widget_(widget) {} virtual ~EmbeddedWindowScreenPositionClient() {} // aura::client::ScreenPositionClient: virtual void ConvertToScreenPoint(gfx::Point* screen_point) OVERRIDE { aura::RootWindow* root = widget_->GetNativeWindow()->GetRootWindow()->GetRootWindow(); gfx::Point origin = root->GetHostOrigin(); screen_point->Offset(origin.x(), origin.y()); } private: NativeWidgetAura* widget_; }; } // namespace DesktopNativeWidgetHelperAura::DesktopNativeWidgetHelperAura( NativeWidgetAura* widget) : widget_(widget), root_window_event_filter_(NULL), is_embedded_window_(false) { } DesktopNativeWidgetHelperAura::~DesktopNativeWidgetHelperAura() { if (root_window_event_filter_) { #if defined(USE_X11) root_window_event_filter_->RemoveFilter(x11_window_event_filter_.get()); #endif root_window_event_filter_->RemoveFilter(input_method_filter_.get()); } } // static aura::Window* DesktopNativeWidgetHelperAura::GetViewsWindowForRootWindow( aura::RootWindow* root) { return root ? root->GetProperty(kViewsWindowForRootWindow) : NULL; } void DesktopNativeWidgetHelperAura::PreInitialize( aura::Window* window, const Widget::InitParams& params) { #if !defined(OS_WIN) // We don't want the status bubble or the omnibox to get their own root // window on the desktop; on Linux // // TODO(erg): This doesn't map perfectly to what I want to do. TYPE_POPUP is // used for lots of stuff, like dragged tabs, and I only want this to trigger // for the status bubble and the omnibox. if (params.type == Widget::InitParams::TYPE_POPUP) { is_embedded_window_ = true; position_client_.reset(new EmbeddedWindowScreenPositionClient(widget_)); aura::client::SetScreenPositionClient(window, position_client_.get()); return; } else if (params.type == Widget::InitParams::TYPE_CONTROL) { return; } #endif gfx::Rect bounds = params.bounds; if (bounds.IsEmpty()) { // We must pass some non-zero value when we initialize a RootWindow. This // will probably be SetBounds()ed soon. bounds.set_size(gfx::Size(100, 100)); } // TODO(erg): Implement aura::CursorManager::Delegate to control // cursor's shape and visibility. aura::FocusManager* focus_manager = NULL; aura::DesktopActivationClient* activation_client = NULL; #if defined(USE_X11) focus_manager = X11DesktopHandler::get()->get_focus_manager(); activation_client = X11DesktopHandler::get()->get_activation_client(); #else // TODO(ben): This is almost certainly wrong; I suspect that the windows // build will need a singleton like above. focus_manager = new aura::FocusManager; activation_client = new aura::DesktopActivationClient(focus_manager); #endif root_window_.reset(new aura::RootWindow(bounds)); root_window_->SetProperty(kViewsWindowForRootWindow, window); root_window_->Init(); root_window_->set_focus_manager(focus_manager); // No event filter for aura::Env. Create CompoundEvnetFilter per RootWindow. root_window_event_filter_ = new aura::shared::CompoundEventFilter; // Pass ownership of the filter to the root_window. root_window_->SetEventFilter(root_window_event_filter_); input_method_filter_.reset(new aura::shared::InputMethodEventFilter()); input_method_filter_->SetInputMethodPropertyInRootWindow(root_window_.get()); root_window_event_filter_->AddFilter(input_method_filter_.get()); capture_client_.reset( new aura::shared::RootWindowCaptureClient(root_window_.get())); #if defined(USE_X11) x11_window_event_filter_.reset( new X11WindowEventFilter(root_window_.get(), activation_client, widget_)); x11_window_event_filter_->SetUseHostWindowBorders(false); root_window_event_filter_->AddFilter(x11_window_event_filter_.get()); #endif root_window_->AddRootWindowObserver(this); aura::client::SetActivationClient(root_window_.get(), activation_client); aura::client::SetDispatcherClient(root_window_.get(), new aura::DesktopDispatcherClient); position_client_.reset( new RootWindowScreenPositionClient(root_window_.get())); aura::client::SetScreenPositionClient(window, position_client_.get()); } void DesktopNativeWidgetHelperAura::PostInitialize() { #if defined(OS_WIN) DCHECK(root_window_->GetAcceleratedWidget()); hwnd_message_filter_.reset(new WidgetMessageFilter(root_window_.get(), widget_->GetWidget())); ui::HWNDSubclass::AddFilterToTarget(root_window_->GetAcceleratedWidget(), hwnd_message_filter_.get()); #endif } void DesktopNativeWidgetHelperAura::ShowRootWindow() { if (root_window_.get()) root_window_->ShowRootWindow(); } aura::RootWindow* DesktopNativeWidgetHelperAura::GetRootWindow() { return root_window_.get(); } gfx::Rect DesktopNativeWidgetHelperAura::ModifyAndSetBounds( const gfx::Rect& bounds) { gfx::Rect out_bounds = bounds; if (root_window_.get() && !out_bounds.IsEmpty()) { root_window_->SetHostBounds(out_bounds); out_bounds.set_x(0); out_bounds.set_y(0); } else if (is_embedded_window_) { // The caller expects windows we consider "embedded" to be placed in the // screen coordinate system. So we need to offset the root window's // position (which is in screen coordinates) from these bounds. aura::RootWindow* root = widget_->GetNativeWindow()->GetRootWindow()->GetRootWindow(); gfx::Point point = root->GetHostOrigin(); out_bounds.set_x(out_bounds.x() - point.x()); out_bounds.set_y(out_bounds.y() - point.y()); } return out_bounds; } //////////////////////////////////////////////////////////////////////////////// // DesktopNativeWidgetHelperAura, aura::RootWindowObserver implementation: void DesktopNativeWidgetHelperAura::OnRootWindowResized( const aura::RootWindow* root, const gfx::Size& old_size) { DCHECK_EQ(root, root_window_.get()); widget_->SetBounds(gfx::Rect(root->GetHostOrigin(), root->GetHostSize())); } void DesktopNativeWidgetHelperAura::OnRootWindowHostClosed( const aura::RootWindow* root) { DCHECK_EQ(root, root_window_.get()); widget_->GetWidget()->Close(); } } // namespace views <commit_msg>linux_aura: Bubbles shouldn't have their own RootWindow.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/widget/desktop_native_widget_helper_aura.h" #include "ui/aura/client/dispatcher_client.h" #include "ui/aura/client/screen_position_client.h" #include "ui/aura/cursor_manager.h" #include "ui/aura/desktop/desktop_activation_client.h" #include "ui/aura/desktop/desktop_dispatcher_client.h" #include "ui/aura/focus_manager.h" #include "ui/aura/root_window.h" #include "ui/aura/shared/compound_event_filter.h" #include "ui/aura/shared/input_method_event_filter.h" #include "ui/aura/shared/root_window_capture_client.h" #include "ui/aura/window_property.h" #include "ui/views/widget/native_widget_aura.h" #if defined(OS_WIN) #include "ui/base/win/hwnd_subclass.h" #include "ui/views/widget/widget_message_filter.h" #elif defined(USE_X11) #include "ui/views/widget/x11_desktop_handler.h" #include "ui/views/widget/x11_window_event_filter.h" #endif DECLARE_WINDOW_PROPERTY_TYPE(aura::Window*); namespace views { DEFINE_WINDOW_PROPERTY_KEY( aura::Window*, kViewsWindowForRootWindow, NULL); namespace { // Client that always offsets the passed in point by the RootHost's origin. class RootWindowScreenPositionClient : public aura::client::ScreenPositionClient { public: explicit RootWindowScreenPositionClient(aura::RootWindow* root_window) : root_window_(root_window) {} virtual ~RootWindowScreenPositionClient() {} // aura::client::ScreenPositionClient: virtual void ConvertToScreenPoint(gfx::Point* screen_point) OVERRIDE { gfx::Point origin = root_window_->GetHostOrigin(); screen_point->Offset(origin.x(), origin.y()); } private: aura::RootWindow* root_window_; }; // Client that always offsets by the toplevel RootWindow of the passed in child // NativeWidgetAura. class EmbeddedWindowScreenPositionClient : public aura::client::ScreenPositionClient { public: explicit EmbeddedWindowScreenPositionClient(NativeWidgetAura* widget) : widget_(widget) {} virtual ~EmbeddedWindowScreenPositionClient() {} // aura::client::ScreenPositionClient: virtual void ConvertToScreenPoint(gfx::Point* screen_point) OVERRIDE { aura::RootWindow* root = widget_->GetNativeWindow()->GetRootWindow()->GetRootWindow(); gfx::Point origin = root->GetHostOrigin(); screen_point->Offset(origin.x(), origin.y()); } private: NativeWidgetAura* widget_; }; } // namespace DesktopNativeWidgetHelperAura::DesktopNativeWidgetHelperAura( NativeWidgetAura* widget) : widget_(widget), root_window_event_filter_(NULL), is_embedded_window_(false) { } DesktopNativeWidgetHelperAura::~DesktopNativeWidgetHelperAura() { if (root_window_event_filter_) { #if defined(USE_X11) root_window_event_filter_->RemoveFilter(x11_window_event_filter_.get()); #endif root_window_event_filter_->RemoveFilter(input_method_filter_.get()); } } // static aura::Window* DesktopNativeWidgetHelperAura::GetViewsWindowForRootWindow( aura::RootWindow* root) { return root ? root->GetProperty(kViewsWindowForRootWindow) : NULL; } void DesktopNativeWidgetHelperAura::PreInitialize( aura::Window* window, const Widget::InitParams& params) { #if !defined(OS_WIN) // We don't want the status bubble or the omnibox to get their own root // window on the desktop; on Linux // // TODO(erg): This doesn't map perfectly to what I want to do. TYPE_POPUP is // used for lots of stuff, like dragged tabs, and I only want this to trigger // for the status bubble and the omnibox. if (params.type == Widget::InitParams::TYPE_POPUP || params.type == Widget::InitParams::TYPE_BUBBLE) { is_embedded_window_ = true; position_client_.reset(new EmbeddedWindowScreenPositionClient(widget_)); aura::client::SetScreenPositionClient(window, position_client_.get()); return; } else if (params.type == Widget::InitParams::TYPE_CONTROL) { return; } #endif gfx::Rect bounds = params.bounds; if (bounds.IsEmpty()) { // We must pass some non-zero value when we initialize a RootWindow. This // will probably be SetBounds()ed soon. bounds.set_size(gfx::Size(100, 100)); } // TODO(erg): Implement aura::CursorManager::Delegate to control // cursor's shape and visibility. aura::FocusManager* focus_manager = NULL; aura::DesktopActivationClient* activation_client = NULL; #if defined(USE_X11) focus_manager = X11DesktopHandler::get()->get_focus_manager(); activation_client = X11DesktopHandler::get()->get_activation_client(); #else // TODO(ben): This is almost certainly wrong; I suspect that the windows // build will need a singleton like above. focus_manager = new aura::FocusManager; activation_client = new aura::DesktopActivationClient(focus_manager); #endif root_window_.reset(new aura::RootWindow(bounds)); root_window_->SetProperty(kViewsWindowForRootWindow, window); root_window_->Init(); root_window_->set_focus_manager(focus_manager); // No event filter for aura::Env. Create CompoundEvnetFilter per RootWindow. root_window_event_filter_ = new aura::shared::CompoundEventFilter; // Pass ownership of the filter to the root_window. root_window_->SetEventFilter(root_window_event_filter_); input_method_filter_.reset(new aura::shared::InputMethodEventFilter()); input_method_filter_->SetInputMethodPropertyInRootWindow(root_window_.get()); root_window_event_filter_->AddFilter(input_method_filter_.get()); capture_client_.reset( new aura::shared::RootWindowCaptureClient(root_window_.get())); #if defined(USE_X11) x11_window_event_filter_.reset( new X11WindowEventFilter(root_window_.get(), activation_client, widget_)); x11_window_event_filter_->SetUseHostWindowBorders(false); root_window_event_filter_->AddFilter(x11_window_event_filter_.get()); #endif root_window_->AddRootWindowObserver(this); aura::client::SetActivationClient(root_window_.get(), activation_client); aura::client::SetDispatcherClient(root_window_.get(), new aura::DesktopDispatcherClient); position_client_.reset( new RootWindowScreenPositionClient(root_window_.get())); aura::client::SetScreenPositionClient(window, position_client_.get()); } void DesktopNativeWidgetHelperAura::PostInitialize() { #if defined(OS_WIN) DCHECK(root_window_->GetAcceleratedWidget()); hwnd_message_filter_.reset(new WidgetMessageFilter(root_window_.get(), widget_->GetWidget())); ui::HWNDSubclass::AddFilterToTarget(root_window_->GetAcceleratedWidget(), hwnd_message_filter_.get()); #endif } void DesktopNativeWidgetHelperAura::ShowRootWindow() { if (root_window_.get()) root_window_->ShowRootWindow(); } aura::RootWindow* DesktopNativeWidgetHelperAura::GetRootWindow() { return root_window_.get(); } gfx::Rect DesktopNativeWidgetHelperAura::ModifyAndSetBounds( const gfx::Rect& bounds) { gfx::Rect out_bounds = bounds; if (root_window_.get() && !out_bounds.IsEmpty()) { root_window_->SetHostBounds(out_bounds); out_bounds.set_x(0); out_bounds.set_y(0); } else if (is_embedded_window_) { // The caller expects windows we consider "embedded" to be placed in the // screen coordinate system. So we need to offset the root window's // position (which is in screen coordinates) from these bounds. aura::RootWindow* root = widget_->GetNativeWindow()->GetRootWindow()->GetRootWindow(); gfx::Point point = root->GetHostOrigin(); out_bounds.set_x(out_bounds.x() - point.x()); out_bounds.set_y(out_bounds.y() - point.y()); } return out_bounds; } //////////////////////////////////////////////////////////////////////////////// // DesktopNativeWidgetHelperAura, aura::RootWindowObserver implementation: void DesktopNativeWidgetHelperAura::OnRootWindowResized( const aura::RootWindow* root, const gfx::Size& old_size) { DCHECK_EQ(root, root_window_.get()); widget_->SetBounds(gfx::Rect(root->GetHostOrigin(), root->GetHostSize())); } void DesktopNativeWidgetHelperAura::OnRootWindowHostClosed( const aura::RootWindow* root) { DCHECK_EQ(root, root_window_.get()); widget_->GetWidget()->Close(); } } // namespace views <|endoftext|>
<commit_before>#ifndef SERVER_HTTP_HPP #define SERVER_HTTP_HPP #include <boost/asio.hpp> #include <regex> #include <unordered_map> #include <thread> namespace SimpleWeb { struct Request { std::string method, path, http_version; std::shared_ptr<std::istream> content; std::unordered_map<std::string, std::string> header; std::smatch path_match; }; typedef std::map<std::string, std::unordered_map<std::string, std::function<void(std::ostream&, Request&)> > > resource_type; template <class socket_type> class ServerBase { public: resource_type resource; resource_type default_resource; void start() { //All resources with default_resource at the end of vector //Used in the respond-method for(auto it=resource.begin(); it!=resource.end();it++) { all_resources.push_back(it); } for(auto it=default_resource.begin(); it!=default_resource.end();it++) { all_resources.push_back(it); } accept(); //If num_threads>1, start m_io_service.run() in (num_threads-1) threads for thread-pooling for(size_t c=1;c<num_threads;c++) { threads.emplace_back([this](){ m_io_service.run(); }); } //Main thread m_io_service.run(); //Wait for the rest of the threads, if any, to finish as well for(auto& t: threads) { t.join(); } } protected: boost::asio::io_service m_io_service; boost::asio::ip::tcp::endpoint endpoint; boost::asio::ip::tcp::acceptor acceptor; size_t num_threads; std::vector<std::thread> threads; size_t timeout_request; size_t timeout_content; //All resources with default_resource at the end of vector //Created in start() std::vector<resource_type::iterator> all_resources; ServerBase(unsigned short port, size_t num_threads, size_t timeout_request, size_t timeout_send_or_receive) : endpoint(boost::asio::ip::tcp::v4(), port), acceptor(m_io_service, endpoint), num_threads(num_threads), timeout_request(timeout_request), timeout_content(timeout_send_or_receive) {} virtual void accept()=0; virtual std::shared_ptr<boost::asio::deadline_timer> set_timeout_on_socket(std::shared_ptr<socket_type> socket, size_t seconds)=0; void process_request_and_respond(std::shared_ptr<socket_type> socket) { //Create new read_buffer for async_read_until() //Shared_ptr is used to pass temporary objects to the asynchronous functions std::shared_ptr<boost::asio::streambuf> read_buffer(new boost::asio::streambuf); //Set timeout on the following boost::asio::async-read or write function auto timer=set_timeout_on_socket(socket, timeout_request); boost::asio::async_read_until(*socket, *read_buffer, "\r\n\r\n", [this, socket, read_buffer, timer](const boost::system::error_code& ec, size_t bytes_transferred) { timer->cancel(); if(!ec) { //read_buffer->size() is not necessarily the same as bytes_transferred, from Boost-docs: //"After a successful async_read_until operation, the streambuf may contain additional data beyond the delimiter" //The chosen solution is to extract lines from the stream directly when parsing the header. What is left of the //read_buffer (maybe some bytes of the content) is appended to in the async_read-function below (for retrieving content). size_t total=read_buffer->size(); //Convert to istream to extract string-lines std::istream stream(read_buffer.get()); std::shared_ptr<Request> request(new Request()); *request=parse_request(stream); size_t num_additional_bytes=total-bytes_transferred; //If content, read that as well if(request->header.count("Content-Length")>0) { //Set timeout on the following boost::asio::async-read or write function auto timer=set_timeout_on_socket(socket, timeout_content); boost::asio::async_read(*socket, *read_buffer, boost::asio::transfer_exactly(stoull(request->header["Content-Length"])-num_additional_bytes), [this, socket, read_buffer, request, timer](const boost::system::error_code& ec, size_t bytes_transferred) { timer->cancel(); if(!ec) { //Store pointer to read_buffer as istream object request->content=std::shared_ptr<std::istream>(new std::istream(read_buffer.get())); respond(socket, request); } }); } else { respond(socket, request); } } }); } Request parse_request(std::istream& stream) const { Request request; std::regex e("^([^ ]*) ([^ ]*) HTTP/([^ ]*)$"); std::smatch sm; //First parse request method, path, and HTTP-version from the first line std::string line; getline(stream, line); line.pop_back(); if(std::regex_match(line, sm, e)) { request.method=sm[1]; request.path=sm[2]; request.http_version=sm[3]; bool matched; e="^([^:]*): ?(.*)$"; //Parse the rest of the header do { getline(stream, line); line.pop_back(); matched=std::regex_match(line, sm, e); if(matched) { request.header[sm[1]]=sm[2]; } } while(matched==true); } return request; } void respond(std::shared_ptr<socket_type> socket, std::shared_ptr<Request> request) { //Find path- and method-match, and generate response for(auto res_it: all_resources) { std::regex e(res_it->first); std::smatch sm_res; if(std::regex_match(request->path, sm_res, e)) { if(res_it->second.count(request->method)>0) { request->path_match=move(sm_res); std::shared_ptr<boost::asio::streambuf> write_buffer(new boost::asio::streambuf); std::ostream response(write_buffer.get()); res_it->second[request->method](response, *request); //Set timeout on the following boost::asio::async-read or write function auto timer=set_timeout_on_socket(socket, timeout_content); //Capture write_buffer in lambda so it is not destroyed before async_write is finished boost::asio::async_write(*socket, *write_buffer, [this, socket, request, write_buffer, timer](const boost::system::error_code& ec, size_t bytes_transferred) { timer->cancel(); //HTTP persistent connection (HTTP 1.1): if(!ec && stof(request->http_version)>1.05) process_request_and_respond(socket); }); return; } } } } }; template<class socket_type> class Server : public ServerBase<socket_type> {}; typedef boost::asio::ip::tcp::socket HTTP; template<> class Server<HTTP> : public ServerBase<HTTP> { public: Server(unsigned short port, size_t num_threads=1, size_t timeout_request=5, size_t timeout_content=300) : ServerBase<HTTP>::ServerBase(port, num_threads, timeout_request, timeout_content) {}; private: void accept() { //Create new socket for this connection //Shared_ptr is used to pass temporary objects to the asynchronous functions std::shared_ptr<HTTP> socket(new HTTP(m_io_service)); acceptor.async_accept(*socket, [this, socket](const boost::system::error_code& ec) { //Immediately start accepting a new connection accept(); if(!ec) { process_request_and_respond(socket); } }); } std::shared_ptr<boost::asio::deadline_timer> set_timeout_on_socket(std::shared_ptr<HTTP> socket, size_t seconds) { std::shared_ptr<boost::asio::deadline_timer> timeout(new boost::asio::deadline_timer(m_io_service)); timeout->expires_from_now(boost::posix_time::seconds(seconds)); timeout->async_wait([socket](const boost::system::error_code& ec){ if(!ec) { socket->shutdown(boost::asio::ip::tcp::socket::shutdown_both); socket->close(); } }); return timeout; } }; } #endif /* SERVER_HTTP_HPP */<commit_msg>Minor changes<commit_after>#ifndef SERVER_HTTP_HPP #define SERVER_HTTP_HPP #include <boost/asio.hpp> #include <regex> #include <unordered_map> #include <thread> namespace SimpleWeb { struct Request { std::string method, path, http_version; std::shared_ptr<std::istream> content; std::unordered_map<std::string, std::string> header; std::smatch path_match; }; typedef std::map<std::string, std::unordered_map<std::string, std::function<void(std::ostream&, Request&)> > > resource_type; template <class socket_type> class ServerBase { public: resource_type resource; resource_type default_resource; void start() { //All resources with default_resource at the end of vector //Used in the respond-method for(auto it=resource.begin(); it!=resource.end();it++) { all_resources.push_back(it); } for(auto it=default_resource.begin(); it!=default_resource.end();it++) { all_resources.push_back(it); } accept(); //If num_threads>1, start m_io_service.run() in (num_threads-1) threads for thread-pooling for(size_t c=1;c<num_threads;c++) { threads.emplace_back([this](){ m_io_service.run(); }); } //Main thread m_io_service.run(); //Wait for the rest of the threads, if any, to finish as well for(auto& t: threads) { t.join(); } } protected: boost::asio::io_service m_io_service; boost::asio::ip::tcp::endpoint endpoint; boost::asio::ip::tcp::acceptor acceptor; size_t num_threads; std::vector<std::thread> threads; size_t timeout_request; size_t timeout_content; //All resources with default_resource at the end of vector //Created in start() std::vector<resource_type::iterator> all_resources; ServerBase(unsigned short port, size_t num_threads, size_t timeout_request, size_t timeout_send_or_receive) : endpoint(boost::asio::ip::tcp::v4(), port), acceptor(m_io_service, endpoint), num_threads(num_threads), timeout_request(timeout_request), timeout_content(timeout_send_or_receive) {} virtual void accept()=0; virtual std::shared_ptr<boost::asio::deadline_timer> set_timeout_on_socket(std::shared_ptr<socket_type> socket, size_t seconds)=0; void process_request_and_respond(std::shared_ptr<socket_type> socket) { //Create new read_buffer for async_read_until() //Shared_ptr is used to pass temporary objects to the asynchronous functions std::shared_ptr<boost::asio::streambuf> read_buffer(new boost::asio::streambuf); //Set timeout on the following boost::asio::async-read or write function auto timer=set_timeout_on_socket(socket, timeout_request); boost::asio::async_read_until(*socket, *read_buffer, "\r\n\r\n", [this, socket, read_buffer, timer](const boost::system::error_code& ec, size_t bytes_transferred) { timer->cancel(); if(!ec) { //read_buffer->size() is not necessarily the same as bytes_transferred, from Boost-docs: //"After a successful async_read_until operation, the streambuf may contain additional data beyond the delimiter" //The chosen solution is to extract lines from the stream directly when parsing the header. What is left of the //read_buffer (maybe some bytes of the content) is appended to in the async_read-function below (for retrieving content). size_t total=read_buffer->size(); //Convert to istream to extract string-lines std::istream stream(read_buffer.get()); std::shared_ptr<Request> request(new Request()); *request=parse_request(stream); size_t num_additional_bytes=total-bytes_transferred; //If content, read that as well if(request->header.count("Content-Length")>0) { //Set timeout on the following boost::asio::async-read or write function auto timer=set_timeout_on_socket(socket, timeout_content); boost::asio::async_read(*socket, *read_buffer, boost::asio::transfer_exactly(stoull(request->header["Content-Length"])-num_additional_bytes), [this, socket, read_buffer, request, timer] (const boost::system::error_code& ec, size_t bytes_transferred) { timer->cancel(); if(!ec) { //Store pointer to read_buffer as istream object request->content=std::shared_ptr<std::istream>(new std::istream(read_buffer.get())); respond(socket, request); } }); } else { respond(socket, request); } } }); } Request parse_request(std::istream& stream) const { Request request; std::regex e("^([^ ]*) ([^ ]*) HTTP/([^ ]*)$"); std::smatch sm; //First parse request method, path, and HTTP-version from the first line std::string line; getline(stream, line); line.pop_back(); if(std::regex_match(line, sm, e)) { request.method=sm[1]; request.path=sm[2]; request.http_version=sm[3]; bool matched; e="^([^:]*): ?(.*)$"; //Parse the rest of the header do { getline(stream, line); line.pop_back(); matched=std::regex_match(line, sm, e); if(matched) { request.header[sm[1]]=sm[2]; } } while(matched==true); } return request; } void respond(std::shared_ptr<socket_type> socket, std::shared_ptr<Request> request) { //Find path- and method-match, and generate response for(auto res_it: all_resources) { std::regex e(res_it->first); std::smatch sm_res; if(std::regex_match(request->path, sm_res, e)) { if(res_it->second.count(request->method)>0) { request->path_match=move(sm_res); std::shared_ptr<boost::asio::streambuf> write_buffer(new boost::asio::streambuf); std::ostream response(write_buffer.get()); res_it->second[request->method](response, *request); //Set timeout on the following boost::asio::async-read or write function auto timer=set_timeout_on_socket(socket, timeout_content); //Capture write_buffer in lambda so it is not destroyed before async_write is finished boost::asio::async_write(*socket, *write_buffer, [this, socket, request, write_buffer, timer] (const boost::system::error_code& ec, size_t bytes_transferred) { timer->cancel(); //HTTP persistent connection (HTTP 1.1): if(!ec && stof(request->http_version)>1.05) process_request_and_respond(socket); }); return; } } } } }; template<class socket_type> class Server : public ServerBase<socket_type> {}; typedef boost::asio::ip::tcp::socket HTTP; template<> class Server<HTTP> : public ServerBase<HTTP> { public: Server(unsigned short port, size_t num_threads=1, size_t timeout_request=5, size_t timeout_content=300) : ServerBase<HTTP>::ServerBase(port, num_threads, timeout_request, timeout_content) {}; private: void accept() { //Create new socket for this connection //Shared_ptr is used to pass temporary objects to the asynchronous functions std::shared_ptr<HTTP> socket(new HTTP(m_io_service)); acceptor.async_accept(*socket, [this, socket](const boost::system::error_code& ec) { //Immediately start accepting a new connection accept(); if(!ec) { process_request_and_respond(socket); } }); } std::shared_ptr<boost::asio::deadline_timer> set_timeout_on_socket(std::shared_ptr<HTTP> socket, size_t seconds) { std::shared_ptr<boost::asio::deadline_timer> timeout(new boost::asio::deadline_timer(m_io_service)); timeout->expires_from_now(boost::posix_time::seconds(seconds)); timeout->async_wait([socket](const boost::system::error_code& ec){ if(!ec) { socket->shutdown(boost::asio::ip::tcp::socket::shutdown_both); socket->close(); } }); return timeout; } }; } #endif /* SERVER_HTTP_HPP */<|endoftext|>
<commit_before><commit_msg>Checkpoint added<commit_after><|endoftext|>
<commit_before>/* Copyright (c) 2010, The Barbarian Group 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. 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 "cinder/Area.h" #include "cinder/Rect.h" #include <algorithm> using std::pair; namespace cinder { template<typename T> AreaT<T>::AreaT( const Vec2<T> &UL, const Vec2<T> &LR ) { set( UL.x, UL.y, LR.x, LR.y ); } template<typename T> AreaT<T>::AreaT( const RectT<float> &r ) { set( r.x1, r.y1, r.x2, r.y2 ); } template<> template<> AreaT<int32_t>::AreaT( const AreaT<boost::rational<int32_t> > &aAreaBase ) { x1 = aAreaBase.x1.numerator() / aAreaBase.x1.denominator(); y1 = aAreaBase.y1.numerator() / aAreaBase.y1.denominator(); x2 = aAreaBase.x2.numerator() / aAreaBase.x2.denominator(); y2 = aAreaBase.y2.numerator() / aAreaBase.y2.denominator(); } template<> template<> AreaT<boost::rational<int32_t> >::AreaT( const AreaT<int32_t> &aAreaBase ) { x1 = aAreaBase.x1; y1 = aAreaBase.y1; x2 = aAreaBase.x2; y2 = aAreaBase.y2; } template<typename T> void AreaT<T>::set( T aX1, T aY1, T aX2, T aY2 ) { if ( aX1 <= aX2 ) { x1 = aX1; x2 = aX2; } else { x1 = aX2; x2 = aX1; } if ( aY1 <= aY2 ) { y1 = aY1; y2 = aY2; } else { y1 = aY2; y2 = aY1; } } template<typename T> void AreaT<T>::clipBy( const AreaT<T> &clip ) { if ( x1 < clip.x1 ) x1 = clip.x1; if ( x2 < clip.x1 ) x2 = clip.x1; if ( x1 > clip.x2 ) x1 = clip.x2; if ( x2 > clip.x2 ) x2 = clip.x2; if ( y1 < clip.y1 ) y1 = clip.y1; if ( y2 < clip.y1 ) y2 = clip.y1; if ( y1 > clip.y2 ) y1 = clip.y2; if ( y2 > clip.y2 ) y2 = clip.y2; } template<typename T> AreaT<T> AreaT<T>::getClipBy( const AreaT<T> &clip ) const { AreaT<T> result( *this ); result.clipBy( clip ); return result; } template<typename T> void AreaT<T>::offset( const Vec2<T> &o ) { x1 += o.x; x2 += o.x; y1 += o.y; y2 += o.y; } template<typename T> AreaT<T> AreaT<T>::getOffset( const Vec2<T> &offset ) const { return AreaT<T>( x1 + offset.x, y1 + offset.y, x2 + offset.x, y2 + offset.y ); } template<typename T> void AreaT<T>::moveULTo( const Vec2<T> &newUL ) { set( newUL.x, newUL.y, newUL.x + getWidth(), newUL.y + getHeight() ); } template<typename T> AreaT<T> AreaT<T>::getMoveULTo( const Vec2<T> &newUL ) const { return AreaT<T>( newUL.x, newUL.y, newUL.x + getWidth(), newUL.y + getHeight() ); } template<typename T> bool AreaT<T>::contains( const Vec2<T> &offset ) const { return ( ( offset.x >= x1 ) && ( offset.x < x2 ) && ( offset.y >= y1 ) && ( offset.y < y2 ) ); } template<typename T> bool AreaT<T>::intersects( const AreaT<T> &area ) const { if( ( x1 >= area.x2 ) || ( x2 < area.x1 ) || ( y1 >= area.y2 ) || ( y2 < area.y1 ) ) return false; else return true; } template<typename T> template<typename Y> float AreaT<T>::distance( const Vec2<Y> &pt ) const { float squaredDistance = 0; if( pt.x < x1 ) squaredDistance += ( x1 - pt.x ) * ( x1 - pt.x ); else if( pt.x > x2 ) squaredDistance += ( pt.x - x2 ) * ( pt.x - x2 ); if( pt.y < y1 ) squaredDistance += ( y1 - pt.y ) * ( y1 - pt.y ); else if( pt.y > y2 ) squaredDistance += ( pt.y - y2 ) * ( pt.y - y2 ); if( squaredDistance > 0 ) return math<float>::sqrt( squaredDistance ); else return 0; } template<typename T> template<typename Y> float AreaT<T>::distanceSquared( const Vec2<Y> &pt ) const { float squaredDistance = 0; if( pt.x < x1 ) squaredDistance += ( x1 - pt.x ) * ( x1 - pt.x ); else if( pt.x > x2 ) squaredDistance += ( pt.x - x2 ) * ( pt.x - x2 ); if( pt.y < y1 ) squaredDistance += ( y1 - pt.y ) * ( y1 - pt.y ); else if( pt.y > y2 ) squaredDistance += ( pt.y - y2 ) * ( pt.y - y2 ); return squaredDistance; } template<typename T> template<typename Y> Vec2<Y> AreaT<T>::closestPoint( const Vec2<Y> &pt ) const { Vec2<Y> result = pt; if( pt.x < x1 ) result.x = x1; else if( pt.x > x2 ) result.x = x2; if( pt.y < y1 ) result.y = y1; else if( pt.y > y2 ) result.y = y2; return result; } template<typename T> bool AreaT<T>::operator<( const AreaT<T> &aArea ) const { if ( x1 != aArea.x1 ) return x1 < x1; if ( y1 != aArea.y1 ) return y1 < y1; if ( x2 != aArea.x2 ) return x2 < x2; if ( y2 != aArea.y2 ) return y2 < y2; return false; } template<typename T> AreaT<T> AreaT<T>::proportionalFit( const AreaT<T> &srcArea, const AreaT<T> &dstArea, bool center, bool expand ) { T resultWidth, resultHeight; if( srcArea.getWidth() >= srcArea.getHeight() ) { // wider than tall resultWidth = ( expand ) ? dstArea.getWidth() : std::min( dstArea.getWidth(), srcArea.getWidth() ); resultHeight = resultWidth * srcArea.getHeight() / srcArea.getWidth(); if( resultHeight > dstArea.getHeight() ) { // maximized proportional would be too tall resultHeight = dstArea.getHeight(); resultWidth = resultHeight * srcArea.getWidth() / srcArea.getHeight(); } } else { // taller than wide resultHeight = ( expand ) ? dstArea.getHeight() : std::min( dstArea.getHeight(), srcArea.getHeight() ); resultWidth = resultHeight * srcArea.getWidth() / srcArea.getHeight(); if( resultWidth > dstArea.getWidth() ) { // maximized proportional would be too wide resultWidth = dstArea.getWidth(); resultHeight = resultWidth * srcArea.getHeight() / srcArea.getWidth(); } } AreaT<T> resultArea( 0, 0, resultWidth, resultHeight ); if ( center ) resultArea.offset( Vec2<T>( ( dstArea.getWidth() - resultWidth ) / 2, ( dstArea.getHeight() - resultHeight ) / 2 ) ); resultArea.offset( dstArea.getUL() ); return resultArea; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /*** Returns a pair composed of the source area and the destination absolute offset ***/ pair<Area,Vec2i> clippedSrcDst( const Area &srcSurfaceBounds, const Area &srcArea, const Area &dstSurfaceBounds, const Vec2i &dstLT ) { Area clippedSrc = srcArea.getClipBy( srcSurfaceBounds ); Vec2i newDstLT = dstLT + ( clippedSrc.getUL() - srcArea.getUL() ); Vec2i oldSrcLT = clippedSrc.getUL(); clippedSrc.moveULTo( newDstLT ); Area oldClippedDst = clippedSrc; clippedSrc.clipBy( dstSurfaceBounds ); newDstLT = clippedSrc.getUL(); clippedSrc.moveULTo( oldSrcLT + ( clippedSrc.getUL() - oldClippedDst.getUL() ) ); clippedSrc.clipBy( srcSurfaceBounds ); return std::make_pair( clippedSrc, newDstLT ); } template class AreaT<int32_t>; template class AreaT<boost::rational<int32_t> >; template float AreaT<int32_t>::distance( const Vec2i &pt ) const; template float AreaT<int32_t>::distance( const Vec2f &pt ) const; template float AreaT<int32_t>::distanceSquared( const Vec2i &pt ) const; template float AreaT<int32_t>::distanceSquared( const Vec2f &pt ) const; template Vec2i AreaT<int32_t>::closestPoint( const Vec2i &pt ) const; template Vec2f AreaT<int32_t>::closestPoint( const Vec2f &pt ) const; } // namespace cinder <commit_msg>Fixed broken operator< on Area<commit_after>/* Copyright (c) 2010, The Barbarian Group 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. 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 "cinder/Area.h" #include "cinder/Rect.h" #include <algorithm> using std::pair; namespace cinder { template<typename T> AreaT<T>::AreaT( const Vec2<T> &UL, const Vec2<T> &LR ) { set( UL.x, UL.y, LR.x, LR.y ); } template<typename T> AreaT<T>::AreaT( const RectT<float> &r ) { set( r.x1, r.y1, r.x2, r.y2 ); } template<> template<> AreaT<int32_t>::AreaT( const AreaT<boost::rational<int32_t> > &aAreaBase ) { x1 = aAreaBase.x1.numerator() / aAreaBase.x1.denominator(); y1 = aAreaBase.y1.numerator() / aAreaBase.y1.denominator(); x2 = aAreaBase.x2.numerator() / aAreaBase.x2.denominator(); y2 = aAreaBase.y2.numerator() / aAreaBase.y2.denominator(); } template<> template<> AreaT<boost::rational<int32_t> >::AreaT( const AreaT<int32_t> &aAreaBase ) { x1 = aAreaBase.x1; y1 = aAreaBase.y1; x2 = aAreaBase.x2; y2 = aAreaBase.y2; } template<typename T> void AreaT<T>::set( T aX1, T aY1, T aX2, T aY2 ) { if ( aX1 <= aX2 ) { x1 = aX1; x2 = aX2; } else { x1 = aX2; x2 = aX1; } if ( aY1 <= aY2 ) { y1 = aY1; y2 = aY2; } else { y1 = aY2; y2 = aY1; } } template<typename T> void AreaT<T>::clipBy( const AreaT<T> &clip ) { if ( x1 < clip.x1 ) x1 = clip.x1; if ( x2 < clip.x1 ) x2 = clip.x1; if ( x1 > clip.x2 ) x1 = clip.x2; if ( x2 > clip.x2 ) x2 = clip.x2; if ( y1 < clip.y1 ) y1 = clip.y1; if ( y2 < clip.y1 ) y2 = clip.y1; if ( y1 > clip.y2 ) y1 = clip.y2; if ( y2 > clip.y2 ) y2 = clip.y2; } template<typename T> AreaT<T> AreaT<T>::getClipBy( const AreaT<T> &clip ) const { AreaT<T> result( *this ); result.clipBy( clip ); return result; } template<typename T> void AreaT<T>::offset( const Vec2<T> &o ) { x1 += o.x; x2 += o.x; y1 += o.y; y2 += o.y; } template<typename T> AreaT<T> AreaT<T>::getOffset( const Vec2<T> &offset ) const { return AreaT<T>( x1 + offset.x, y1 + offset.y, x2 + offset.x, y2 + offset.y ); } template<typename T> void AreaT<T>::moveULTo( const Vec2<T> &newUL ) { set( newUL.x, newUL.y, newUL.x + getWidth(), newUL.y + getHeight() ); } template<typename T> AreaT<T> AreaT<T>::getMoveULTo( const Vec2<T> &newUL ) const { return AreaT<T>( newUL.x, newUL.y, newUL.x + getWidth(), newUL.y + getHeight() ); } template<typename T> bool AreaT<T>::contains( const Vec2<T> &offset ) const { return ( ( offset.x >= x1 ) && ( offset.x < x2 ) && ( offset.y >= y1 ) && ( offset.y < y2 ) ); } template<typename T> bool AreaT<T>::intersects( const AreaT<T> &area ) const { if( ( x1 >= area.x2 ) || ( x2 < area.x1 ) || ( y1 >= area.y2 ) || ( y2 < area.y1 ) ) return false; else return true; } template<typename T> template<typename Y> float AreaT<T>::distance( const Vec2<Y> &pt ) const { float squaredDistance = 0; if( pt.x < x1 ) squaredDistance += ( x1 - pt.x ) * ( x1 - pt.x ); else if( pt.x > x2 ) squaredDistance += ( pt.x - x2 ) * ( pt.x - x2 ); if( pt.y < y1 ) squaredDistance += ( y1 - pt.y ) * ( y1 - pt.y ); else if( pt.y > y2 ) squaredDistance += ( pt.y - y2 ) * ( pt.y - y2 ); if( squaredDistance > 0 ) return math<float>::sqrt( squaredDistance ); else return 0; } template<typename T> template<typename Y> float AreaT<T>::distanceSquared( const Vec2<Y> &pt ) const { float squaredDistance = 0; if( pt.x < x1 ) squaredDistance += ( x1 - pt.x ) * ( x1 - pt.x ); else if( pt.x > x2 ) squaredDistance += ( pt.x - x2 ) * ( pt.x - x2 ); if( pt.y < y1 ) squaredDistance += ( y1 - pt.y ) * ( y1 - pt.y ); else if( pt.y > y2 ) squaredDistance += ( pt.y - y2 ) * ( pt.y - y2 ); return squaredDistance; } template<typename T> template<typename Y> Vec2<Y> AreaT<T>::closestPoint( const Vec2<Y> &pt ) const { Vec2<Y> result = pt; if( pt.x < x1 ) result.x = x1; else if( pt.x > x2 ) result.x = x2; if( pt.y < y1 ) result.y = y1; else if( pt.y > y2 ) result.y = y2; return result; } template<typename T> bool AreaT<T>::operator<( const AreaT<T> &aArea ) const { if ( x1 != aArea.x1 ) return x1 < aArea.x1; if ( y1 != aArea.y1 ) return y1 < aArea.y1; if ( x2 != aArea.x2 ) return x2 < aArea.x2; if ( y2 != aArea.y2 ) return y2 < aArea.y2; return false; } template<typename T> AreaT<T> AreaT<T>::proportionalFit( const AreaT<T> &srcArea, const AreaT<T> &dstArea, bool center, bool expand ) { T resultWidth, resultHeight; if( srcArea.getWidth() >= srcArea.getHeight() ) { // wider than tall resultWidth = ( expand ) ? dstArea.getWidth() : std::min( dstArea.getWidth(), srcArea.getWidth() ); resultHeight = resultWidth * srcArea.getHeight() / srcArea.getWidth(); if( resultHeight > dstArea.getHeight() ) { // maximized proportional would be too tall resultHeight = dstArea.getHeight(); resultWidth = resultHeight * srcArea.getWidth() / srcArea.getHeight(); } } else { // taller than wide resultHeight = ( expand ) ? dstArea.getHeight() : std::min( dstArea.getHeight(), srcArea.getHeight() ); resultWidth = resultHeight * srcArea.getWidth() / srcArea.getHeight(); if( resultWidth > dstArea.getWidth() ) { // maximized proportional would be too wide resultWidth = dstArea.getWidth(); resultHeight = resultWidth * srcArea.getHeight() / srcArea.getWidth(); } } AreaT<T> resultArea( 0, 0, resultWidth, resultHeight ); if ( center ) resultArea.offset( Vec2<T>( ( dstArea.getWidth() - resultWidth ) / 2, ( dstArea.getHeight() - resultHeight ) / 2 ) ); resultArea.offset( dstArea.getUL() ); return resultArea; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /*** Returns a pair composed of the source area and the destination absolute offset ***/ pair<Area,Vec2i> clippedSrcDst( const Area &srcSurfaceBounds, const Area &srcArea, const Area &dstSurfaceBounds, const Vec2i &dstLT ) { Area clippedSrc = srcArea.getClipBy( srcSurfaceBounds ); Vec2i newDstLT = dstLT + ( clippedSrc.getUL() - srcArea.getUL() ); Vec2i oldSrcLT = clippedSrc.getUL(); clippedSrc.moveULTo( newDstLT ); Area oldClippedDst = clippedSrc; clippedSrc.clipBy( dstSurfaceBounds ); newDstLT = clippedSrc.getUL(); clippedSrc.moveULTo( oldSrcLT + ( clippedSrc.getUL() - oldClippedDst.getUL() ) ); clippedSrc.clipBy( srcSurfaceBounds ); return std::make_pair( clippedSrc, newDstLT ); } template class AreaT<int32_t>; template class AreaT<boost::rational<int32_t> >; template float AreaT<int32_t>::distance( const Vec2i &pt ) const; template float AreaT<int32_t>::distance( const Vec2f &pt ) const; template float AreaT<int32_t>::distanceSquared( const Vec2i &pt ) const; template float AreaT<int32_t>::distanceSquared( const Vec2f &pt ) const; template Vec2i AreaT<int32_t>::closestPoint( const Vec2i &pt ) const; template Vec2f AreaT<int32_t>::closestPoint( const Vec2f &pt ) const; } // namespace cinder <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: SlsPageObjectFactory.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2006-09-16 19:06:29 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sd.hxx" #include "controller/SlsPageObjectFactory.hxx" #include "view/SlsPageObject.hxx" #include "view/SlsPageObjectViewContact.hxx" #include "view/SlsPageObjectViewObjectContact.hxx" #include "sdpage.hxx" namespace sd { namespace slidesorter { namespace controller { PageObjectFactory::PageObjectFactory (const ::boost::shared_ptr<cache::PageCache>& rpCache) : mpPageCache(rpCache) { } PageObjectFactory::~PageObjectFactory (void) { } view::PageObject* PageObjectFactory::CreatePageObject ( SdPage* pPage, model::PageDescriptor& rDescriptor) const { return new view::PageObject( Rectangle (Point(0,0), pPage->GetSize()), pPage, rDescriptor); } ::sdr::contact::ViewContact* PageObjectFactory::CreateViewContact ( view::PageObject* pPageObject, model::PageDescriptor& rDescriptor) const { return new view::PageObjectViewContact ( *pPageObject, rDescriptor); } ::sdr::contact::ViewObjectContact* PageObjectFactory::CreateViewObjectContact ( ::sdr::contact::ObjectContact& rObjectContact, ::sdr::contact::ViewContact& rViewContact) const { return new view::PageObjectViewObjectContact ( rObjectContact, rViewContact, mpPageCache); } } } } // end of namespace ::sd::slidesorter::controller <commit_msg>INTEGRATION: CWS presenterview (1.5.122); FILE MERGED 2007/04/26 14:25:46 af 1.5.122.1: #i75317# Using shared_ptr for PageDescriptor. Passing Properties to page objects.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: SlsPageObjectFactory.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: kz $ $Date: 2008-04-03 14:26:26 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sd.hxx" #include "controller/SlsPageObjectFactory.hxx" #include "view/SlsPageObject.hxx" #include "view/SlsPageObjectViewContact.hxx" #include "view/SlsPageObjectViewObjectContact.hxx" #include "sdpage.hxx" namespace sd { namespace slidesorter { namespace controller { PageObjectFactory::PageObjectFactory ( const ::boost::shared_ptr<cache::PageCache>& rpCache, const ::boost::shared_ptr<controller::Properties>& rpProperties) : mpPageCache(rpCache), mpProperties(rpProperties) { } PageObjectFactory::~PageObjectFactory (void) { } view::PageObject* PageObjectFactory::CreatePageObject ( SdPage* pPage, const model::SharedPageDescriptor& rpDescriptor) const { return new view::PageObject( Rectangle (Point(0,0), pPage->GetSize()), pPage, rpDescriptor); } ::sdr::contact::ViewContact* PageObjectFactory::CreateViewContact ( view::PageObject* pPageObject, const model::SharedPageDescriptor& rpDescriptor) const { return new view::PageObjectViewContact ( *pPageObject, rpDescriptor); } ::sdr::contact::ViewObjectContact* PageObjectFactory::CreateViewObjectContact ( ::sdr::contact::ObjectContact& rObjectContact, ::sdr::contact::ViewContact& rViewContact) const { return new view::PageObjectViewObjectContact ( rObjectContact, rViewContact, mpPageCache, mpProperties); } } } } // end of namespace ::sd::slidesorter::controller <|endoftext|>
<commit_before>#include <iostream> #include <getopt.h> #include <linux/input.h> #include <ros/ros.h> #include <sensor_msgs/Image.h> #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/image_encodings.h> #include <message_filters/subscriber.h> #include <message_filters/time_synchronizer.h> #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/image_encodings.h> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include "../../../devel/include/orsens/Obstacles.h" #include "../../../devel/include/orsens/Way.h" using namespace cv; using namespace sensor_msgs; Mat disp, left, right; orsens::Obstacles obs; orsens::Way way; Mat colorize_disp(Mat disp_mono) { Mat disp_color(disp_mono.rows, disp_mono.cols, CV_8UC3); Mat hsv(disp_mono.rows, disp_mono.cols, CV_32FC3); disp_color = Scalar::all(0); hsv = Scalar::all(0); for (int y=0; y<disp_mono.rows; y++) for (int x=0; x<disp_mono.cols; x++) { uchar d = disp_mono.at<uchar>(y,x); if (d==0) continue; hsv.at<Vec3f>(y,x) = Vec3f(255-d, 1.0,1.0); } cvtColor(hsv, disp_color, CV_HSV2BGR); return disp_color; } void disp_cb(sensor_msgs::Image disp_img) { cv_bridge::CvImagePtr disp_ptr; try { disp_ptr = cv_bridge::toCvCopy(disp_img, sensor_msgs::image_encodings::TYPE_8UC1); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); return; } disp = disp_ptr->image.clone(); Mat disp_color = colorize_disp(disp); imshow("disp", disp); imshow("disp colored", disp_color); waitKey(5); } void disp_filtered_cb(sensor_msgs::Image disp_filtered_img) { cv_bridge::CvImagePtr disp_ptr; try { disp_ptr = cv_bridge::toCvCopy(disp_filtered_img, sensor_msgs::image_encodings::TYPE_8UC1); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); return; } disp = disp_ptr->image.clone(); Mat disp_color = colorize_disp(disp); imshow("disp_filtered", disp); imshow("disp_filtered colored", disp_color); waitKey(5); } void left_cb(sensor_msgs::Image left_img) { cv_bridge::CvImagePtr left_ptr; try { left_ptr = cv_bridge::toCvCopy(left_img, sensor_msgs::image_encodings::TYPE_8UC3); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); return; } left = left_ptr->image.clone(); imshow("left", left); waitKey(5); } int main(int argc, char *argv[]) { // Initialize ROS ros::init (argc, argv, "orview"); ros::NodeHandle nh; ros::Subscriber sub_disp = nh.subscribe("/orsens/disparity", 1, disp_cb); ros::Subscriber sub_disp_filtered = nh.subscribe("/orsens/disparity_filtered", 1, disp_filtered_cb); ros::Subscriber sub_left = nh.subscribe("/orsens/left", 1, left_cb); namedWindow("disp", 1); namedWindow("left", 1); // Spin ros::spin (); return 0; } <commit_msg>viewer node fix<commit_after>#include <iostream> #include <getopt.h> #include <linux/input.h> #include <ros/ros.h> #include <sensor_msgs/Image.h> #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/image_encodings.h> #include <message_filters/subscriber.h> #include <message_filters/time_synchronizer.h> #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/image_encodings.h> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <../../devel/include/orsens/Obstacles.h> #include <../../devel/include/orsens/Way.h> using namespace cv; using namespace sensor_msgs; Mat disp, left, right; orsens::Obstacles obs; orsens::Way way; Mat colorize_disp(Mat disp_mono) { Mat disp_color(disp_mono.rows, disp_mono.cols, CV_8UC3); Mat hsv(disp_mono.rows, disp_mono.cols, CV_32FC3); disp_color = Scalar::all(0); hsv = Scalar::all(0); for (int y=0; y<disp_mono.rows; y++) for (int x=0; x<disp_mono.cols; x++) { uchar d = disp_mono.at<uchar>(y,x); if (d==0) continue; hsv.at<Vec3f>(y,x) = Vec3f(255-d, 1.0,1.0); } cvtColor(hsv, disp_color, CV_HSV2BGR); return disp_color; } void disp_cb(sensor_msgs::Image disp_img) { cv_bridge::CvImagePtr disp_ptr; try { disp_ptr = cv_bridge::toCvCopy(disp_img, sensor_msgs::image_encodings::TYPE_8UC1); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); return; } disp = disp_ptr->image.clone(); Mat disp_color = colorize_disp(disp); imshow("disp", disp); imshow("disp colored", disp_color); waitKey(5); } void disp_filtered_cb(sensor_msgs::Image disp_filtered_img) { cv_bridge::CvImagePtr disp_ptr; try { disp_ptr = cv_bridge::toCvCopy(disp_filtered_img, sensor_msgs::image_encodings::TYPE_8UC1); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); return; } disp = disp_ptr->image.clone(); Mat disp_color = colorize_disp(disp); imshow("disp_filtered", disp); imshow("disp_filtered colored", disp_color); waitKey(5); } void left_cb(sensor_msgs::Image left_img) { cv_bridge::CvImagePtr left_ptr; try { left_ptr = cv_bridge::toCvCopy(left_img, sensor_msgs::image_encodings::TYPE_8UC3); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); return; } left = left_ptr->image.clone(); imshow("left", left); waitKey(5); } int main(int argc, char *argv[]) { // Initialize ROS ros::init (argc, argv, "orview"); ros::NodeHandle nh; ros::Subscriber sub_disp = nh.subscribe("/orsens/disparity", 1, disp_cb); ros::Subscriber sub_disp_filtered = nh.subscribe("/orsens/disparity_filtered", 1, disp_filtered_cb); ros::Subscriber sub_left = nh.subscribe("/orsens/left", 1, left_cb); namedWindow("disp", 1); namedWindow("left", 1); // Spin ros::spin (); return 0; } <|endoftext|>
<commit_before>#ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include <string> #include <string.h> #include <assert.h> #include <mutex> #include <zmq.h> #include "json11.hpp" #include "common/timing.h" #include "common/util.h" #include "common/version.h" #include "swaglog.h" typedef struct LogState { std::mutex lock; bool inited; json11::Json::object ctx_j; void *zctx; void *sock; int print_level; } LogState; static LogState s = {}; static void cloudlog_bind_locked(const char* k, const char* v) { s.ctx_j[k] = v; } static void cloudlog_init() { if (s.inited) return; s.ctx_j = json11::Json::object {}; s.zctx = zmq_ctx_new(); s.sock = zmq_socket(s.zctx, ZMQ_PUSH); zmq_connect(s.sock, "ipc:///tmp/logmessage"); s.print_level = CLOUDLOG_WARNING; const char* print_level = getenv("LOGPRINT"); if (print_level) { if (strcmp(print_level, "debug") == 0) { s.print_level = CLOUDLOG_DEBUG; } else if (strcmp(print_level, "info") == 0) { s.print_level = CLOUDLOG_INFO; } else if (strcmp(print_level, "warning") == 0) { s.print_level = CLOUDLOG_WARNING; } } // openpilot bindings char* dongle_id = getenv("DONGLE_ID"); if (dongle_id) { cloudlog_bind_locked("dongle_id", dongle_id); } cloudlog_bind_locked("version", COMMA_VERSION); s.ctx_j["dirty"] = !getenv("CLEAN"); // device type if (util::file_exists("/EON")) { cloudlog_bind_locked("device", "eon"); } else if (util::file_exists("/TICI")) { cloudlog_bind_locked("device", "tici"); } else { cloudlog_bind_locked("device", "pc"); } s.inited = true; } void cloudlog_e(int levelnum, const char* filename, int lineno, const char* func, const char* fmt, ...) { std::lock_guard lk(s.lock); cloudlog_init(); char* msg_buf = NULL; va_list args; va_start(args, fmt); vasprintf(&msg_buf, fmt, args); va_end(args); if (!msg_buf) { return; } if (levelnum >= s.print_level) { printf("%s: %s\n", filename, msg_buf); } json11::Json log_j = json11::Json::object { {"msg", msg_buf}, {"ctx", s.ctx_j}, {"levelnum", levelnum}, {"filename", filename}, {"lineno", lineno}, {"funcname", func}, {"created", seconds_since_epoch()} }; std::string log_s = log_j.dump(); free(msg_buf); char levelnum_c = levelnum; zmq_send(s.sock, &levelnum_c, 1, ZMQ_NOBLOCK | ZMQ_SNDMORE); zmq_send(s.sock, log_s.c_str(), log_s.length(), ZMQ_NOBLOCK); } void cloudlog_bind(const char* k, const char* v) { std::lock_guard lk(s.lock); cloudlog_init(); cloudlog_bind_locked(k, v); } <commit_msg>C++ swaglog (#19825)<commit_after>#ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include <string> #include <string.h> #include <assert.h> #include <mutex> #include <zmq.h> #include "json11.hpp" #include "common/util.h" #include "common/version.h" #include "swaglog.h" class LogState { public: LogState() = default; ~LogState(); std::mutex lock; bool inited; json11::Json::object ctx_j; void *zctx; void *sock; int print_level; }; LogState::~LogState() { zmq_close(sock); zmq_ctx_destroy(zctx); } static LogState s = {}; static void cloudlog_bind_locked(const char* k, const char* v) { s.ctx_j[k] = v; } static void cloudlog_init() { if (s.inited) return; s.ctx_j = json11::Json::object {}; s.zctx = zmq_ctx_new(); s.sock = zmq_socket(s.zctx, ZMQ_PUSH); zmq_connect(s.sock, "ipc:///tmp/logmessage"); s.print_level = CLOUDLOG_WARNING; const char* print_level = getenv("LOGPRINT"); if (print_level) { if (strcmp(print_level, "debug") == 0) { s.print_level = CLOUDLOG_DEBUG; } else if (strcmp(print_level, "info") == 0) { s.print_level = CLOUDLOG_INFO; } else if (strcmp(print_level, "warning") == 0) { s.print_level = CLOUDLOG_WARNING; } } // openpilot bindings char* dongle_id = getenv("DONGLE_ID"); if (dongle_id) { cloudlog_bind_locked("dongle_id", dongle_id); } cloudlog_bind_locked("version", COMMA_VERSION); s.ctx_j["dirty"] = !getenv("CLEAN"); // device type if (util::file_exists("/EON")) { cloudlog_bind_locked("device", "eon"); } else if (util::file_exists("/TICI")) { cloudlog_bind_locked("device", "tici"); } else { cloudlog_bind_locked("device", "pc"); } s.inited = true; } void log(int levelnum, const char* filename, int lineno, const char* func, const char* msg, const std::string& log_s) { std::lock_guard lk(s.lock); cloudlog_init(); if (levelnum >= s.print_level) { printf("%s: %s\n", filename, msg); } char levelnum_c = levelnum; zmq_send(s.sock, &levelnum_c, 1, ZMQ_NOBLOCK | ZMQ_SNDMORE); zmq_send(s.sock, log_s.c_str(), log_s.length(), ZMQ_NOBLOCK); } void cloudlog_e(int levelnum, const char* filename, int lineno, const char* func, const char* fmt, ...) { char* msg_buf = nullptr; va_list args; va_start(args, fmt); vasprintf(&msg_buf, fmt, args); va_end(args); if (!msg_buf) return; json11::Json log_j = json11::Json::object { {"msg", msg_buf}, {"ctx", s.ctx_j}, {"levelnum", levelnum}, {"filename", filename}, {"lineno", lineno}, {"funcname", func}, {"created", seconds_since_epoch()} }; std::string log_s = log_j.dump(); log(levelnum, filename, lineno, func, msg_buf, log_s); free(msg_buf); } void cloudlog_bind(const char* k, const char* v) { std::lock_guard lk(s.lock); cloudlog_init(); cloudlog_bind_locked(k, v); } <|endoftext|>
<commit_before>/* * Copyright 2015 Cloudius Systems */ #pragma once #include "http/httpd.hh" #include "json/json_elements.hh" #include "database.hh" #include "service/storage_proxy.hh" #include <boost/lexical_cast.hpp> #include <boost/algorithm/string/split.hpp> #include <boost/algorithm/string/classification.hpp> #include "api/api-doc/utils.json.hh" #include "utils/histogram.hh" namespace api { struct http_context { sstring api_dir; httpd::http_server_control http_server; distributed<database>& db; distributed<service::storage_proxy>& sp; http_context(distributed<database>& _db, distributed<service::storage_proxy>& _sp) : db(_db), sp(_sp) {} }; future<> set_server(http_context& ctx); template<class T> std::vector<sstring> container_to_vec(const T& container) { std::vector<sstring> res; for (auto i : container) { res.push_back(boost::lexical_cast<std::string>(i)); } return res; } template<class T> std::vector<T> map_to_key_value(const std::map<sstring, sstring>& map) { std::vector<T> res; for (auto i : map) { res.push_back(T()); res.back().key = i.first; res.back().value = i.second; } return res; } template<class T, class MAP> std::vector<T>& map_to_key_value(const MAP& map, std::vector<T>& res) { for (auto i : map) { T val; val.key = boost::lexical_cast<std::string>(i.first); val.value = boost::lexical_cast<std::string>(i.second); res.push_back(val); } return res; } template <typename T, typename S = T> T map_sum(T&& dest, const S& src) { for (auto i : src) { dest[i.first] += i.second; } return dest; } template <typename MAP> std::vector<sstring> map_keys(const MAP& map) { std::vector<sstring> res; for (const auto& i : map) { res.push_back(boost::lexical_cast<std::string>(i.first)); } return res; } /** * General sstring splitting function */ inline std::vector<sstring> split(const sstring& text, const char* separator) { if (text == "") { return std::vector<sstring>(); } std::vector<sstring> tokens; return boost::split(tokens, text, boost::is_any_of(separator)); } /** * Split a column family parameter */ inline std::vector<sstring> split_cf(const sstring& cf) { return split(cf, ","); } /** * A helper function to sum values on an a distributed object that * has a get_stats method. * */ template<class T, class F, class V> future<json::json_return_type> sum_stats(distributed<T>& d, V F::*f) { return d.map_reduce0([f](const T& p) {return p.get_stats().*f;}, 0, std::plus<V>()).then([](V val) { return make_ready_future<json::json_return_type>(val); }); } inline double pow2(double a) { return a * a; } inline httpd::utils_json::histogram add_histogram(httpd::utils_json::histogram res, const utils::ihistogram& val) { if (val.count == 0) { return res; } if (!res.count._set) { res = val; return res; } if (res.min() > val.min) { res.min = val.min; } if (res.max() < val.max) { res.max = val.max; } double ncount = res.count() + val.count; res.sum = res.sum() + val.sum; double a = res.count()/ncount; double b = val.count/ncount; double mean = a * res.mean() + b * val.mean; res.variance = (res.variance() + pow2(res.mean() - mean) )* a + (val.variance + pow2(val.mean -mean))* b; res.mean = mean; res.count = res.count() + val.count; for (auto i : val.sample) { res.sample.push(i); } return res; } template<class T, class F> future<json::json_return_type> sum_histogram_stats(distributed<T>& d, utils::ihistogram F::*f) { return d.map_reduce0([f](const T& p) {return p.get_stats().*f;}, httpd::utils_json::histogram(), add_histogram).then([](const httpd::utils_json::histogram& val) { return make_ready_future<json::json_return_type>(val); }); } } <commit_msg>API: Add a wrapper function for min and max<commit_after>/* * Copyright 2015 Cloudius Systems */ #pragma once #include "http/httpd.hh" #include "json/json_elements.hh" #include "database.hh" #include "service/storage_proxy.hh" #include <boost/lexical_cast.hpp> #include <boost/algorithm/string/split.hpp> #include <boost/algorithm/string/classification.hpp> #include "api/api-doc/utils.json.hh" #include "utils/histogram.hh" namespace api { struct http_context { sstring api_dir; httpd::http_server_control http_server; distributed<database>& db; distributed<service::storage_proxy>& sp; http_context(distributed<database>& _db, distributed<service::storage_proxy>& _sp) : db(_db), sp(_sp) {} }; future<> set_server(http_context& ctx); template<class T> std::vector<sstring> container_to_vec(const T& container) { std::vector<sstring> res; for (auto i : container) { res.push_back(boost::lexical_cast<std::string>(i)); } return res; } template<class T> std::vector<T> map_to_key_value(const std::map<sstring, sstring>& map) { std::vector<T> res; for (auto i : map) { res.push_back(T()); res.back().key = i.first; res.back().value = i.second; } return res; } template<class T, class MAP> std::vector<T>& map_to_key_value(const MAP& map, std::vector<T>& res) { for (auto i : map) { T val; val.key = boost::lexical_cast<std::string>(i.first); val.value = boost::lexical_cast<std::string>(i.second); res.push_back(val); } return res; } template <typename T, typename S = T> T map_sum(T&& dest, const S& src) { for (auto i : src) { dest[i.first] += i.second; } return dest; } template <typename MAP> std::vector<sstring> map_keys(const MAP& map) { std::vector<sstring> res; for (const auto& i : map) { res.push_back(boost::lexical_cast<std::string>(i.first)); } return res; } /** * General sstring splitting function */ inline std::vector<sstring> split(const sstring& text, const char* separator) { if (text == "") { return std::vector<sstring>(); } std::vector<sstring> tokens; return boost::split(tokens, text, boost::is_any_of(separator)); } /** * Split a column family parameter */ inline std::vector<sstring> split_cf(const sstring& cf) { return split(cf, ","); } /** * A helper function to sum values on an a distributed object that * has a get_stats method. * */ template<class T, class F, class V> future<json::json_return_type> sum_stats(distributed<T>& d, V F::*f) { return d.map_reduce0([f](const T& p) {return p.get_stats().*f;}, 0, std::plus<V>()).then([](V val) { return make_ready_future<json::json_return_type>(val); }); } inline double pow2(double a) { return a * a; } inline httpd::utils_json::histogram add_histogram(httpd::utils_json::histogram res, const utils::ihistogram& val) { if (val.count == 0) { return res; } if (!res.count._set) { res = val; return res; } if (res.min() > val.min) { res.min = val.min; } if (res.max() < val.max) { res.max = val.max; } double ncount = res.count() + val.count; res.sum = res.sum() + val.sum; double a = res.count()/ncount; double b = val.count/ncount; double mean = a * res.mean() + b * val.mean; res.variance = (res.variance() + pow2(res.mean() - mean) )* a + (val.variance + pow2(val.mean -mean))* b; res.mean = mean; res.count = res.count() + val.count; for (auto i : val.sample) { res.sample.push(i); } return res; } template<class T, class F> future<json::json_return_type> sum_histogram_stats(distributed<T>& d, utils::ihistogram F::*f) { return d.map_reduce0([f](const T& p) {return p.get_stats().*f;}, httpd::utils_json::histogram(), add_histogram).then([](const httpd::utils_json::histogram& val) { return make_ready_future<json::json_return_type>(val); }); } inline int64_t min_int64(int64_t a, int64_t b) { return std::min(a,b); } inline int64_t max_int64(int64_t a, int64_t b) { return std::max(a,b); } } <|endoftext|>
<commit_before>// @(#)root/ged:$Name: $:$Id: TGedEditor.cxx,v 1.16 2005/02/02 17:45:47 brun Exp $ // Author: Marek Biskup, Ilka Antcheva 02/08/2003 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TGedEditor // // // // Editor is a composite frame that contains TGedToolBox and // // TGedAttFrames. It is connected to a Canvas and listens for // // selected objects // // // ////////////////////////////////////////////////////////////////////////// #include "TGedEditor.h" #include "TCanvas.h" #include "TGCanvas.h" #include "TGTab.h" #include "TGedFrame.h" #include "TGLabel.h" #include "TGFrame.h" #include "TBaseClass.h" #include "TSystem.h" ClassImp(TGedEditor) //______________________________________________________________________________ TGedEditor::TGedEditor(TCanvas* canvas) : TGMainFrame(gClient->GetRoot(), 175, 20) { fCan = new TGCanvas(this, 170, 10, kFixedWidth); fTab = new TGTab(fCan->GetViewPort(), 10, 10); fCan->SetContainer(fTab); AddFrame(fCan, new TGLayoutHints(kLHintsExpandY | kLHintsExpandX)); fTab->Associate(fCan); fTabContainer = fTab->AddTab("Style"); fStyle = new TGCompositeFrame(fTabContainer, 110, 30, kVerticalFrame); fStyle->AddFrame(new TGedNameFrame(fStyle, 1),\ new TGLayoutHints(kLHintsTop | kLHintsExpandX,0, 0, 2, 2)); fTabContainer->AddFrame(fStyle, new TGLayoutHints(kLHintsTop | kLHintsExpandX,\ 5, 0, 2, 2)); fWid = GetCounter(); fGlobal = kTRUE; if (canvas) { if (!canvas->GetSelected()) canvas->SetSelected(canvas); if (!canvas->GetSelectedPad()) canvas->SetSelectedPad(canvas); fModel = canvas->GetSelected(); fPad = canvas->GetSelectedPad(); fCanvas = canvas; fClass = fModel->IsA(); GetEditors(); ConnectToCanvas(canvas); SetWindowName(Form("%s_Editor", canvas->GetName())); } else { fModel = 0; fPad = 0; fCanvas = 0; fClass = 0; if (gPad) SetCanvas(gPad->GetCanvas()); SetWindowName("Global Editor"); } MapSubwindows(); Resize(GetDefaultSize()); MapWindow(); if (canvas) Resize(GetWidth(), canvas->GetWh()+4); // 4 canvas borders gROOT->GetListOfCleanups()->Add(this); } //______________________________________________________________________________ void TGedEditor::CloseWindow() { // When closed via WM close button, just unmap (i.e. hide) editor // for later use. UnmapWindow(); Disconnect(fCanvas, "Selected(TVirtualPad*,TObject*,Int_t)", this, "SetModel(TVirtualPad*,TObject*,Int_t)"); gROOT->GetListOfCleanups()->Remove(this); } //______________________________________________________________________________ void TGedEditor::GetEditors() { // Get existing editors of selected object // Look in TClass::GetEditorList() for any object deriving from TGedFrame, Bool_t found = kFALSE; TGedElement *ge; TList *list = fModel->IsA()->GetEditorList(); if (list->First() != 0) { TIter next1(list); while ((ge = (TGedElement *) next1())) { // check if the editor ge->fGedframe is already in the list of fStyle TList *l = fStyle->GetList(); if (l->First() != 0) { TGFrameElement *fr; TIter next(l); while ((fr = (TGFrameElement *) next())) { TGedFrame *f = ge->fGedFrame; found = (fr->fFrame->InheritsFrom(f->ClassName()) && (ge->fCanvas == fCanvas)); if (found) break; else { GetClassEditor(fModel->IsA()); TList *blist = fModel->IsA()->GetListOfBases(); if (blist->First() != 0) GetBaseClassEditor(fModel->IsA()); } } } } } else { //search for a class editor = classname + 'Editor' GetClassEditor(fModel->IsA()); //now scan all base classes list = fModel->IsA()->GetListOfBases(); if (list->First() != 0) GetBaseClassEditor(fModel->IsA()); } fStyle->Layout(); fStyle->MapSubwindows(); } //______________________________________________________________________________ void TGedEditor::GetBaseClassEditor(TClass *cl) { // Scan the base classes of cl and add attribute editors to the list. TList *list = cl->GetListOfBases(); if (list->First() == 0) return; TBaseClass *base; TIter next(list); while ((base = (TBaseClass *)next())) { TClass *c1; if ((c1 = base->GetClassPointer())) GetClassEditor(c1); if (c1->GetListOfBases()->First() == 0) continue; else GetBaseClassEditor(c1); } } //______________________________________________________________________________ void TGedEditor::GetClassEditor(TClass *cl) { // Add attribute editor of class cl to the list of fStyle frame. TClass *class2, *class3; Bool_t found = kFALSE; class2 = gROOT->GetClass(Form("%sEditor",cl->GetName())); if (class2 && class2->InheritsFrom("TGedFrame")) { TList *list = fStyle->GetList(); if (list->First() != 0) { TGFrameElement *fr; TIter next(list); while ((fr = (TGFrameElement *) next())) {; found = fr->fFrame->InheritsFrom(class2); if (found) break; } } if (found == kFALSE) { gROOT->ProcessLine(Form("((TGCompositeFrame *)0x%lx)->AddFrame(new %s((TGWindow *)0x%lx, %d),\ new TGLayoutHints(kLHintsTop | kLHintsExpandX,0, 0, 2, 2))",\ (Long_t)fStyle, class2->GetName(), (Long_t)fStyle, fWid)); fWid++; class3 = (TClass*)gROOT->GetListOfClasses()->FindObject(cl->GetName()); TGedElement *ge; TIter next3(class3->GetEditorList()); while ((ge = (TGedElement *)next3())) { if (!strcmp(ge->fGedFrame->ClassName(), class2->GetName()) && (ge->fCanvas == 0)) { ge->fCanvas = fCanvas; } } } } } //______________________________________________________________________________ void TGedEditor::ConnectToCanvas(TCanvas *c) { // Connect this editor to the selected object in the canvas 'c'. c->Connect("Selected(TVirtualPad*,TObject*,Int_t)", "TGedEditor",\ this, "SetModel(TVirtualPad*,TObject*,Int_t)"); if (!c->GetSelected()) c->SetSelected(c); if (!c->GetSelectedPad()) c->SetSelectedPad(c); c->Selected(c->GetSelectedPad(), c->GetSelected(), kButton1Down); } //______________________________________________________________________________ void TGedEditor::SetCanvas(TCanvas *newcan) { // Change connection to another canvas. if (!newcan || !fCanvas || (fCanvas == newcan)) return; if (fCanvas && (fCanvas != newcan)) DisconnectEditors(fCanvas); fCanvas = newcan; SetWindowName(Form("%s_Editor", fCanvas->GetName())); if (!fCanvas->GetSelected()) fCanvas->SetSelected(newcan); if (!fCanvas->GetSelectedPad()) fCanvas->SetSelectedPad(newcan); fModel = fCanvas->GetSelected(); fPad = fCanvas->GetSelectedPad(); fClass = fModel->IsA(); GetEditors(); ConnectToCanvas(fCanvas); SetModel(fPad, fModel, kButton1Down); } //______________________________________________________________________________ void TGedEditor::SetModel(TVirtualPad* pad, TObject* obj, Int_t event) { if (!fGlobal && (event != kButton1Down)) return; TCanvas *c = (TCanvas *) gTQSender; if (!fGlobal && (c != fCanvas)) return; fModel = obj; fPad = pad; if ((obj != 0) && (obj->IsA() != fClass) && !obj->IsA()->InheritsFrom(fClass)) { fClass = obj->IsA(); GetEditors(); } else if ((obj == 0) && fPad) { TCanvas *canvas = fPad->GetCanvas(); if (canvas) { fPad->SetSelected(fPad); canvas->Selected(fPad, fPad, 0); return; } else { DeleteEditors(); DeleteWindow(); return; } } TGFrameElement *el; TIter next(fStyle->GetList()); while ((el = (TGFrameElement *) next())) { if ((el->fFrame)->InheritsFrom("TGedFrame")) ((TGedFrame *)(el->fFrame))->SetModel(fPad, fModel, event); } } //______________________________________________________________________________ void TGedEditor::Show() { // Show editor. if (gPad && (gPad->GetCanvas() != fCanvas)) SetCanvas(gPad->GetCanvas()); else ConnectToCanvas(fCanvas); if (fCanvas->GetShowEditor()) fCanvas->ToggleEditor(); MapWindow(); if (!gROOT->GetListOfCleanups()->FindObject(this)) gROOT->GetListOfCleanups()->Add(this); } //______________________________________________________________________________ void TGedEditor::Hide() { // Hide editor. if (gPad->GetCanvas() == fCanvas) { UnmapWindow(); Disconnect(fCanvas, "Selected(TVirtualPad*,TObject*,Int_t)", this, "SetModel(TVirtualPad*,TObject*,Int_t)"); gROOT->GetListOfCleanups()->Remove(this); } } //______________________________________________________________________________ void TGedEditor::DisconnectEditors(TCanvas *canvas) { // Disconnect GUI editors connected to canvas. if (!canvas) return; Disconnect(canvas, "Selected(TVirtualPad*,TObject*,Int_t)", this, "SetModel(TVirtualPad*,TObject*,Int_t)"); TClass * cl; TIter next(gROOT->GetListOfClasses()); while((cl = (TClass *)next())) { if (cl->GetEditorList()->First() != 0) { TList *editors = cl->GetEditorList(); TIter next1(editors); TGedElement *ge; while ((ge = (TGedElement *)next1())) { if (ge->fCanvas == canvas) { ge->fCanvas = 0; } } } } } //______________________________________________________________________________ void TGedEditor::DeleteEditors() { // Delete GUI editors connected to the canvas fCanvas. DisconnectEditors(fCanvas); Bool_t del = kTRUE; TClass * cl; TIter next(gROOT->GetListOfClasses()); while((cl = (TClass *)next())) { if (cl->GetEditorList()->First() != 0) { TList *editors = cl->GetEditorList(); TIter next1(editors); TGedElement *ge; while ((ge = (TGedElement *)next1())) { if (ge->fCanvas != 0) { del = kFALSE; } } } } if (del) { TIter next(gROOT->GetListOfClasses()); while((cl = (TClass *)next())) { if (cl->GetEditorList()->First() != 0) { TList *editors = cl->GetEditorList(); TIter next1(editors); TGedElement *ge; while ((ge = (TGedElement *)next1())) { editors->Remove(ge); } } } } } //______________________________________________________________________________ TGedEditor::~TGedEditor() { // Editor destructor. gROOT->GetListOfCleanups()->Remove(this); fStyle->Cleanup(); Cleanup(); } //______________________________________________________________________________ void TGedEditor::RecursiveRemove(TObject* obj) { // Remove references to fModel in case the fModel is being deleted. // Deactivate attribute frames if they point to obj. if ((fModel != obj) || (obj == fCanvas)) return; if (obj == fPad) SetModel(fCanvas, fCanvas, kButton1Down); else SetModel(fPad, fPad, kButton1Down); } <commit_msg>From Ilka: improvement of the global editor position. Its window appears closer to the canvas window on the left or right side according to the available display space.<commit_after>// @(#)root/ged:$Name: $:$Id: TGedEditor.cxx,v 1.17 2005/03/03 22:06:49 brun Exp $ // Author: Marek Biskup, Ilka Antcheva 02/08/2003 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TGedEditor // // // // Editor is a composite frame that contains TGedToolBox and // // TGedAttFrames. It is connected to a Canvas and listens for // // selected objects // // // ////////////////////////////////////////////////////////////////////////// #include "TGedEditor.h" #include "TCanvas.h" #include "TGCanvas.h" #include "TGTab.h" #include "TGedFrame.h" #include "TGLabel.h" #include "TGFrame.h" #include "TBaseClass.h" #include "TSystem.h" ClassImp(TGedEditor) //______________________________________________________________________________ TGedEditor::TGedEditor(TCanvas* canvas) : TGMainFrame(gClient->GetRoot(), 175, 20) { fCan = new TGCanvas(this, 170, 10, kFixedWidth); fTab = new TGTab(fCan->GetViewPort(), 10, 10); fCan->SetContainer(fTab); AddFrame(fCan, new TGLayoutHints(kLHintsExpandY | kLHintsExpandX)); fTab->Associate(fCan); fTabContainer = fTab->AddTab("Style"); fStyle = new TGCompositeFrame(fTabContainer, 110, 30, kVerticalFrame); fStyle->AddFrame(new TGedNameFrame(fStyle, 1),\ new TGLayoutHints(kLHintsTop | kLHintsExpandX,0, 0, 2, 2)); fTabContainer->AddFrame(fStyle, new TGLayoutHints(kLHintsTop | kLHintsExpandX,\ 5, 0, 2, 2)); fWid = GetCounter(); fGlobal = kTRUE; if (canvas) { if (!canvas->GetSelected()) canvas->SetSelected(canvas); if (!canvas->GetSelectedPad()) canvas->SetSelectedPad(canvas); fModel = canvas->GetSelected(); fPad = canvas->GetSelectedPad(); fCanvas = canvas; fClass = fModel->IsA(); GetEditors(); ConnectToCanvas(canvas); SetWindowName(Form("%s_Editor", canvas->GetName())); } else { fModel = 0; fPad = 0; fCanvas = 0; fClass = 0; if (gPad) SetCanvas(gPad->GetCanvas()); SetWindowName("Global Editor"); } MapSubwindows(); Resize(GetDefaultSize()); MapWindow(); if (canvas) Resize(GetWidth(), canvas->GetWindowHeight()); gROOT->GetListOfCleanups()->Add(this); } //______________________________________________________________________________ void TGedEditor::CloseWindow() { // When closed via WM close button, just unmap (i.e. hide) editor // for later use. UnmapWindow(); Disconnect(fCanvas, "Selected(TVirtualPad*,TObject*,Int_t)", this, "SetModel(TVirtualPad*,TObject*,Int_t)"); gROOT->GetListOfCleanups()->Remove(this); } //______________________________________________________________________________ void TGedEditor::GetEditors() { // Get existing editors of selected object // Look in TClass::GetEditorList() for any object deriving from TGedFrame, Bool_t found = kFALSE; TGedElement *ge; TList *list = fModel->IsA()->GetEditorList(); if (list->First() != 0) { TIter next1(list); while ((ge = (TGedElement *) next1())) { // check if the editor ge->fGedframe is already in the list of fStyle TList *l = fStyle->GetList(); if (l->First() != 0) { TGFrameElement *fr; TIter next(l); while ((fr = (TGFrameElement *) next())) { TGedFrame *f = ge->fGedFrame; found = (fr->fFrame->InheritsFrom(f->ClassName()) && (ge->fCanvas == fCanvas)); if (found) break; else { GetClassEditor(fModel->IsA()); TList *blist = fModel->IsA()->GetListOfBases(); if (blist->First() != 0) GetBaseClassEditor(fModel->IsA()); } } } } } else { //search for a class editor = classname + 'Editor' GetClassEditor(fModel->IsA()); //now scan all base classes list = fModel->IsA()->GetListOfBases(); if (list->First() != 0) GetBaseClassEditor(fModel->IsA()); } fStyle->Layout(); fStyle->MapSubwindows(); } //______________________________________________________________________________ void TGedEditor::GetBaseClassEditor(TClass *cl) { // Scan the base classes of cl and add attribute editors to the list. TList *list = cl->GetListOfBases(); if (list->First() == 0) return; TBaseClass *base; TIter next(list); while ((base = (TBaseClass *)next())) { TClass *c1; if ((c1 = base->GetClassPointer())) GetClassEditor(c1); if (c1->GetListOfBases()->First() == 0) continue; else GetBaseClassEditor(c1); } } //______________________________________________________________________________ void TGedEditor::GetClassEditor(TClass *cl) { // Add attribute editor of class cl to the list of fStyle frame. TClass *class2, *class3; Bool_t found = kFALSE; class2 = gROOT->GetClass(Form("%sEditor",cl->GetName())); if (class2 && class2->InheritsFrom("TGedFrame")) { TList *list = fStyle->GetList(); if (list->First() != 0) { TGFrameElement *fr; TIter next(list); while ((fr = (TGFrameElement *) next())) {; found = fr->fFrame->InheritsFrom(class2); if (found) break; } } if (found == kFALSE) { gROOT->ProcessLine(Form("((TGCompositeFrame *)0x%lx)->AddFrame(new %s((TGWindow *)0x%lx, %d),\ new TGLayoutHints(kLHintsTop | kLHintsExpandX,0, 0, 2, 2))",\ (Long_t)fStyle, class2->GetName(), (Long_t)fStyle, fWid)); fWid++; class3 = (TClass*)gROOT->GetListOfClasses()->FindObject(cl->GetName()); TGedElement *ge; TIter next3(class3->GetEditorList()); while ((ge = (TGedElement *)next3())) { if (!strcmp(ge->fGedFrame->ClassName(), class2->GetName()) && (ge->fCanvas == 0)) { ge->fCanvas = fCanvas; } } } } } //______________________________________________________________________________ void TGedEditor::ConnectToCanvas(TCanvas *c) { // Connect this editor to the selected object in the canvas 'c'. c->Connect("Selected(TVirtualPad*,TObject*,Int_t)", "TGedEditor",\ this, "SetModel(TVirtualPad*,TObject*,Int_t)"); if (!c->GetSelected()) c->SetSelected(c); if (!c->GetSelectedPad()) c->SetSelectedPad(c); c->Selected(c->GetSelectedPad(), c->GetSelected(), kButton1Down); } //______________________________________________________________________________ void TGedEditor::SetCanvas(TCanvas *newcan) { // Change connection to another canvas. if (!newcan || !fCanvas || (fCanvas == newcan)) return; if (fCanvas && (fCanvas != newcan)) DisconnectEditors(fCanvas); fCanvas = newcan; SetWindowName(Form("%s_Editor", fCanvas->GetName())); if (!fCanvas->GetSelected()) fCanvas->SetSelected(newcan); if (!fCanvas->GetSelectedPad()) fCanvas->SetSelectedPad(newcan); fModel = fCanvas->GetSelected(); fPad = fCanvas->GetSelectedPad(); fClass = fModel->IsA(); GetEditors(); ConnectToCanvas(fCanvas); SetModel(fPad, fModel, kButton1Down); } //______________________________________________________________________________ void TGedEditor::SetModel(TVirtualPad* pad, TObject* obj, Int_t event) { if (!fGlobal && (event != kButton1Down)) return; TCanvas *c = (TCanvas *) gTQSender; if (!fGlobal && (c != fCanvas)) return; fModel = obj; fPad = pad; if ((obj != 0) && (obj->IsA() != fClass) && !obj->IsA()->InheritsFrom(fClass)) { fClass = obj->IsA(); GetEditors(); } else if ((obj == 0) && fPad) { TCanvas *canvas = fPad->GetCanvas(); if (canvas) { fPad->SetSelected(fPad); canvas->Selected(fPad, fPad, 0); return; } else { DeleteEditors(); DeleteWindow(); return; } } TGFrameElement *el; TIter next(fStyle->GetList()); while ((el = (TGFrameElement *) next())) { if ((el->fFrame)->InheritsFrom("TGedFrame")) ((TGedFrame *)(el->fFrame))->SetModel(fPad, fModel, event); } } //______________________________________________________________________________ void TGedEditor::Show() { // Show editor. if (gPad && (gPad->GetCanvas() != fCanvas)) SetCanvas(gPad->GetCanvas()); else ConnectToCanvas(fCanvas); if (fCanvas->GetShowEditor()) fCanvas->ToggleEditor(); if (fGlobal) { Int_t gedx = 0, gedy = fCanvas->GetWindowTopY() - 20; UInt_t cx = (UInt_t)fCanvas->GetWindowTopX(); if (cx > GetWidth()) gedx = cx - GetWidth() - 20; else gedx = cx + fCanvas->GetWindowWidth() + 10; MoveResize(gedx, gedy, GetWidth(), fCanvas->GetWindowHeight()); SetWMPosition(gedx, gedy); } MapWindow(); if (!gROOT->GetListOfCleanups()->FindObject(this)) gROOT->GetListOfCleanups()->Add(this); } //______________________________________________________________________________ void TGedEditor::Hide() { // Hide editor. if (gPad->GetCanvas() == fCanvas) { UnmapWindow(); Disconnect(fCanvas, "Selected(TVirtualPad*,TObject*,Int_t)", this, "SetModel(TVirtualPad*,TObject*,Int_t)"); gROOT->GetListOfCleanups()->Remove(this); } } //______________________________________________________________________________ void TGedEditor::DisconnectEditors(TCanvas *canvas) { // Disconnect GUI editors connected to canvas. if (!canvas) return; Disconnect(canvas, "Selected(TVirtualPad*,TObject*,Int_t)", this, "SetModel(TVirtualPad*,TObject*,Int_t)"); TClass * cl; TIter next(gROOT->GetListOfClasses()); while((cl = (TClass *)next())) { if (cl->GetEditorList()->First() != 0) { TList *editors = cl->GetEditorList(); TIter next1(editors); TGedElement *ge; while ((ge = (TGedElement *)next1())) { if (ge->fCanvas == canvas) { ge->fCanvas = 0; } } } } } //______________________________________________________________________________ void TGedEditor::DeleteEditors() { // Delete GUI editors connected to the canvas fCanvas. DisconnectEditors(fCanvas); Bool_t del = kTRUE; TClass * cl; TIter next(gROOT->GetListOfClasses()); while((cl = (TClass *)next())) { if (cl->GetEditorList()->First() != 0) { TList *editors = cl->GetEditorList(); TIter next1(editors); TGedElement *ge; while ((ge = (TGedElement *)next1())) { if (ge->fCanvas != 0) { del = kFALSE; } } } } if (del) { TIter next(gROOT->GetListOfClasses()); while((cl = (TClass *)next())) { if (cl->GetEditorList()->First() != 0) { TList *editors = cl->GetEditorList(); TIter next1(editors); TGedElement *ge; while ((ge = (TGedElement *)next1())) { editors->Remove(ge); } } } } } //______________________________________________________________________________ TGedEditor::~TGedEditor() { // Editor destructor. gROOT->GetListOfCleanups()->Remove(this); fStyle->Cleanup(); Cleanup(); } //______________________________________________________________________________ void TGedEditor::RecursiveRemove(TObject* obj) { // Remove references to fModel in case the fModel is being deleted. // Deactivate attribute frames if they point to obj. if ((fModel != obj) || (obj == fCanvas)) return; if (obj == fPad) SetModel(fCanvas, fCanvas, kButton1Down); else SetModel(fPad, fPad, kButton1Down); } <|endoftext|>
<commit_before>#include "VRManager.hpp" #include "Utility/Log.hpp" #include "../Component/VRDevice.hpp" VRManager::VRManager() : scale(1.f) { // Check if VR runtime is installed. if (!vr::VR_IsRuntimeInstalled()) { vrSystem = nullptr; Log() << "VR runtime not installed. Playing without VR.\n"; return; } // Load VR Runtime. vr::EVRInitError eError = vr::VRInitError_None; vrSystem = vr::VR_Init(&eError, vr::VRApplication_Scene); if (eError != vr::VRInitError_None) { vrSystem = nullptr; Log() << "Unable to init VR runtime: " << vr::VR_GetVRInitErrorAsEnglishDescription(eError) << "\n"; return; } // Get focus. vr::VRCompositor()->WaitGetPoses(NULL, 0, NULL, 0); } VRManager::~VRManager() { if (vrSystem == nullptr) return; vr::VR_Shutdown(); vrSystem = nullptr; } bool VRManager::Active() const { return vrSystem != nullptr; } void VRManager::Sync() { if (vrSystem == nullptr) { Log() << "No initialized VR device.\n"; return; } // Get VR device pose(s). vr::VRCompositor()->WaitGetPoses(tracedDevicePoseArray, vr::k_unMaxTrackedDeviceCount, NULL, 0); vr::ETrackedControllerRole role; // Convert to glm format. for (int nDevice = 0; nDevice < vr::k_unMaxTrackedDeviceCount; ++nDevice) if (tracedDevicePoseArray[nDevice].bPoseIsValid) deviceTransforms[nDevice] = ConvertMatrix(tracedDevicePoseArray[nDevice].mDeviceToAbsoluteTracking); } void VRManager::Update() { if (vrSystem == nullptr) return; // Update VR devices. for (Component::VRDevice* vrDevice : vrDevices.GetAll()) { if (vrDevice->IsKilled() || !vrDevice->entity->enabled) continue; Entity* entity = vrDevice->entity; if (vrDevice->type == Component::VRDevice::CONTROLLER) { // Update controller transformation. glm::mat4 transform = GetControllerPoseMatrix(vrDevice->controllerID); glm::vec3 position = glm::vec3(transform[3][0], transform[3][1], transform[3][2]); /// @todo Update rotation. entity->position = position * GetScale(); } else if (vrDevice->type == Component::VRDevice::HEADSET) { /// @todo Update headset transformation. } } } glm::vec2 VRManager::GetRecommendedRenderTargetSize() const { if (vrSystem == nullptr) { Log() << "No initialized VR device.\n"; return glm::vec2(); } std::uint32_t width, height; vrSystem->GetRecommendedRenderTargetSize(&width, &height); return glm::vec2(width, height); } glm::mat4 VRManager::GetHMDPoseMatrix() const { if (vrSystem == nullptr) { Log() << "No initialized VR device.\n"; return glm::mat4(); } return glm::inverse(deviceTransforms[vr::k_unTrackedDeviceIndex_Hmd]); } glm::mat4 VRManager::GetControllerPoseMatrix(int controlID) const { if (vrSystem == nullptr) { Log() << "No initialized VR device.\n"; return glm::mat4(); } for (vr::TrackedDeviceIndex_t untrackedDevice = 0; untrackedDevice < vr::k_unMaxTrackedDeviceCount; untrackedDevice++) { // Skip current VR device if it's not connected if (!vrSystem->IsTrackedDeviceConnected(untrackedDevice)) continue; // Skip current device if it's not a controller else if (vrSystem->GetTrackedDeviceClass(untrackedDevice) != vr::TrackedDeviceClass_Controller) continue; // Skip current controller if it's not in a valid position else if (!tracedDevicePoseArray[untrackedDevice].bPoseIsValid) continue; // Find out if current controller is the left or right one. vr::ETrackedControllerRole role = vrSystem->GetControllerRoleForTrackedDeviceIndex(untrackedDevice); // If we want to differentiate between left and right controller. if (role == vr::ETrackedControllerRole::TrackedControllerRole_Invalid) continue; else if (role == vr::ETrackedControllerRole::TrackedControllerRole_LeftHand && controlID == 1) { return deviceTransforms[untrackedDevice]; } else if (role == vr::ETrackedControllerRole::TrackedControllerRole_RightHand && controlID == 2) { return deviceTransforms[untrackedDevice]; } } return glm::mat4(); } glm::mat4 VRManager::GetHMDEyeToHeadMatrix(vr::Hmd_Eye eye) const { if (vrSystem == nullptr) { Log() << "No initialized VR device.\n"; return glm::mat4(); } return glm::inverse(ConvertMatrix(vrSystem->GetEyeToHeadTransform(eye))); } glm::mat4 VRManager::GetHandleTransformation(int controlID, Entity* entity) { glm::mat4 ctrlTransform = GetControllerPoseMatrix(controlID); glm::vec3 ctrlRight = glm::vec3(ctrlTransform[0][0], ctrlTransform[1][0], ctrlTransform[2][0]); glm::vec3 ctrlUp = glm::vec3(ctrlTransform[0][1], ctrlTransform[1][1], ctrlTransform[2][1]); glm::vec3 ctrlForward = glm::vec3(ctrlTransform[0][2], ctrlTransform[1][2], ctrlTransform[2][2]); glm::vec3 ctrlPosition = glm::vec3(-ctrlTransform[3][0], -ctrlTransform[3][1], -ctrlTransform[3][2]); glm::mat4 ctrlOrientation = glm::mat4( glm::vec4(ctrlRight, 0.0f), glm::vec4(ctrlUp, 0.0f), glm::vec4(ctrlForward, 0.0f), glm::vec4(0.0f, 0.0f, 0.0f, 1.0f) ); glm::vec3 localPosition = ctrlPosition * GetScale(); glm::mat4 localTranslationMatrix = glm::translate(glm::mat4(), localPosition); glm::mat4 globalTranslationMatrix = entity->GetModelMatrix() * (ctrlOrientation * localTranslationMatrix); return globalTranslationMatrix; } glm::mat4 VRManager::GetHMDProjectionMatrix(vr::Hmd_Eye eye, float zNear, float zFar) const { if (vrSystem == nullptr) { Log() << "No initialized VR device.\n"; return glm::mat4(); } return ConvertMatrix(vrSystem->GetProjectionMatrix(eye, zNear, zFar)); } void VRManager::Submit(vr::Hmd_Eye eye, vr::Texture_t* texture) const { if (vrSystem == nullptr) { Log() << "No initialized VR device.\n"; return; } const vr::EVRCompositorError eError = vr::VRCompositor()->Submit(eye, texture); if (eError != vr::VRCompositorError_None) Log() << "Unable to submit texture to hmd: " << eError << "\n"; } glm::mat4 VRManager::ConvertMatrix(const vr::HmdMatrix34_t& mat) { glm::mat4 glmMat( mat.m[0][0], mat.m[1][0], mat.m[2][0], 0.0, mat.m[0][1], mat.m[1][1], mat.m[2][1], 0.0, mat.m[0][2], mat.m[1][2], mat.m[2][2], 0.0, mat.m[0][3], mat.m[1][3], mat.m[2][3], 1.0f ); return glmMat; } glm::mat4 VRManager::ConvertMatrix(const vr::HmdMatrix44_t& mat) { glm::mat4 glmMat( mat.m[0][0], mat.m[1][0], mat.m[2][0], mat.m[3][0], mat.m[0][1], mat.m[1][1], mat.m[2][1], mat.m[3][1], mat.m[0][2], mat.m[1][2], mat.m[2][2], mat.m[3][2], mat.m[0][3], mat.m[1][3], mat.m[2][3], mat.m[3][3] ); return glmMat; } float VRManager::GetScale() const { return scale; } void VRManager::SetScale(float scale) { this->scale = scale; } bool VRManager::GetInput(vr::EVRButtonId buttonID) { for (vr::TrackedDeviceIndex_t unDevice = 0; unDevice < vr::k_unMaxTrackedDeviceCount; unDevice++) { vr::VRControllerState_t controllerState; if (vrSystem->GetControllerState(unDevice, &controllerState, sizeof(controllerState))) { pressedTrackedDevice[unDevice] = controllerState.ulButtonPressed == 0; if (controllerState.ulButtonPressed & vr::ButtonMaskFromId(buttonID)) return true; } } return false; } Component::VRDevice* VRManager::CreateVRDevice() { return vrDevices.Create(); } Component::VRDevice* VRManager::CreateVRDevice(const Json::Value& node) { Component::VRDevice* vrDevice = vrDevices.Create(); // Load values from Json node. std::string type = node.get("type", "controller").asString(); if (type == "controller") vrDevice->type = Component::VRDevice::CONTROLLER; else if (type == "headset") vrDevice->type = Component::VRDevice::HEADSET; vrDevice->controllerID = node.get("controllerID", 1).asInt(); return vrDevice; } const std::vector<Component::VRDevice*>& VRManager::GetVRDevices() const { return vrDevices.GetAll(); } void VRManager::ClearKilledComponents() { vrDevices.ClearKilled(); } <commit_msg>Update rotation of controllers<commit_after>#include "VRManager.hpp" #include "Utility/Log.hpp" #include "../Component/VRDevice.hpp" VRManager::VRManager() : scale(1.f) { // Check if VR runtime is installed. if (!vr::VR_IsRuntimeInstalled()) { vrSystem = nullptr; Log() << "VR runtime not installed. Playing without VR.\n"; return; } // Load VR Runtime. vr::EVRInitError eError = vr::VRInitError_None; vrSystem = vr::VR_Init(&eError, vr::VRApplication_Scene); if (eError != vr::VRInitError_None) { vrSystem = nullptr; Log() << "Unable to init VR runtime: " << vr::VR_GetVRInitErrorAsEnglishDescription(eError) << "\n"; return; } // Get focus. vr::VRCompositor()->WaitGetPoses(NULL, 0, NULL, 0); } VRManager::~VRManager() { if (vrSystem == nullptr) return; vr::VR_Shutdown(); vrSystem = nullptr; } bool VRManager::Active() const { return vrSystem != nullptr; } void VRManager::Sync() { if (vrSystem == nullptr) { Log() << "No initialized VR device.\n"; return; } // Get VR device pose(s). vr::VRCompositor()->WaitGetPoses(tracedDevicePoseArray, vr::k_unMaxTrackedDeviceCount, NULL, 0); vr::ETrackedControllerRole role; // Convert to glm format. for (int nDevice = 0; nDevice < vr::k_unMaxTrackedDeviceCount; ++nDevice) if (tracedDevicePoseArray[nDevice].bPoseIsValid) deviceTransforms[nDevice] = ConvertMatrix(tracedDevicePoseArray[nDevice].mDeviceToAbsoluteTracking); } void VRManager::Update() { if (vrSystem == nullptr) return; // Update VR devices. for (Component::VRDevice* vrDevice : vrDevices.GetAll()) { if (vrDevice->IsKilled() || !vrDevice->entity->enabled) continue; Entity* entity = vrDevice->entity; if (vrDevice->type == Component::VRDevice::CONTROLLER) { glm::mat4 transform = GetControllerPoseMatrix(vrDevice->controllerID); // Update position based on controller position. glm::vec3 position = glm::vec3(transform[3][0], transform[3][1], transform[3][2]); entity->position = position * GetScale(); // Update rotation based on controller rotation. entity->rotation.x = atan2(transform[1][0], transform[0][0]); entity->rotation.y = atan2(-transform[2][0], sqrt(transform[2][1] * transform[2][1] + transform[2][2] * transform[2][2])); entity->rotation.z = atan2(transform[2][1], transform[2][2]); } else if (vrDevice->type == Component::VRDevice::HEADSET) { /// @todo Update headset transformation. } } } glm::vec2 VRManager::GetRecommendedRenderTargetSize() const { if (vrSystem == nullptr) { Log() << "No initialized VR device.\n"; return glm::vec2(); } std::uint32_t width, height; vrSystem->GetRecommendedRenderTargetSize(&width, &height); return glm::vec2(width, height); } glm::mat4 VRManager::GetHMDPoseMatrix() const { if (vrSystem == nullptr) { Log() << "No initialized VR device.\n"; return glm::mat4(); } return glm::inverse(deviceTransforms[vr::k_unTrackedDeviceIndex_Hmd]); } glm::mat4 VRManager::GetControllerPoseMatrix(int controlID) const { if (vrSystem == nullptr) { Log() << "No initialized VR device.\n"; return glm::mat4(); } for (vr::TrackedDeviceIndex_t untrackedDevice = 0; untrackedDevice < vr::k_unMaxTrackedDeviceCount; untrackedDevice++) { // Skip current VR device if it's not connected if (!vrSystem->IsTrackedDeviceConnected(untrackedDevice)) continue; // Skip current device if it's not a controller else if (vrSystem->GetTrackedDeviceClass(untrackedDevice) != vr::TrackedDeviceClass_Controller) continue; // Skip current controller if it's not in a valid position else if (!tracedDevicePoseArray[untrackedDevice].bPoseIsValid) continue; // Find out if current controller is the left or right one. vr::ETrackedControllerRole role = vrSystem->GetControllerRoleForTrackedDeviceIndex(untrackedDevice); // If we want to differentiate between left and right controller. if (role == vr::ETrackedControllerRole::TrackedControllerRole_Invalid) continue; else if (role == vr::ETrackedControllerRole::TrackedControllerRole_LeftHand && controlID == 1) { return deviceTransforms[untrackedDevice]; } else if (role == vr::ETrackedControllerRole::TrackedControllerRole_RightHand && controlID == 2) { return deviceTransforms[untrackedDevice]; } } return glm::mat4(); } glm::mat4 VRManager::GetHMDEyeToHeadMatrix(vr::Hmd_Eye eye) const { if (vrSystem == nullptr) { Log() << "No initialized VR device.\n"; return glm::mat4(); } return glm::inverse(ConvertMatrix(vrSystem->GetEyeToHeadTransform(eye))); } glm::mat4 VRManager::GetHandleTransformation(int controlID, Entity* entity) { glm::mat4 ctrlTransform = GetControllerPoseMatrix(controlID); glm::vec3 ctrlRight = glm::vec3(ctrlTransform[0][0], ctrlTransform[1][0], ctrlTransform[2][0]); glm::vec3 ctrlUp = glm::vec3(ctrlTransform[0][1], ctrlTransform[1][1], ctrlTransform[2][1]); glm::vec3 ctrlForward = glm::vec3(ctrlTransform[0][2], ctrlTransform[1][2], ctrlTransform[2][2]); glm::vec3 ctrlPosition = glm::vec3(-ctrlTransform[3][0], -ctrlTransform[3][1], -ctrlTransform[3][2]); glm::mat4 ctrlOrientation = glm::mat4( glm::vec4(ctrlRight, 0.0f), glm::vec4(ctrlUp, 0.0f), glm::vec4(ctrlForward, 0.0f), glm::vec4(0.0f, 0.0f, 0.0f, 1.0f) ); glm::vec3 localPosition = ctrlPosition * GetScale(); glm::mat4 localTranslationMatrix = glm::translate(glm::mat4(), localPosition); glm::mat4 globalTranslationMatrix = entity->GetModelMatrix() * (ctrlOrientation * localTranslationMatrix); return globalTranslationMatrix; } glm::mat4 VRManager::GetHMDProjectionMatrix(vr::Hmd_Eye eye, float zNear, float zFar) const { if (vrSystem == nullptr) { Log() << "No initialized VR device.\n"; return glm::mat4(); } return ConvertMatrix(vrSystem->GetProjectionMatrix(eye, zNear, zFar)); } void VRManager::Submit(vr::Hmd_Eye eye, vr::Texture_t* texture) const { if (vrSystem == nullptr) { Log() << "No initialized VR device.\n"; return; } const vr::EVRCompositorError eError = vr::VRCompositor()->Submit(eye, texture); if (eError != vr::VRCompositorError_None) Log() << "Unable to submit texture to hmd: " << eError << "\n"; } glm::mat4 VRManager::ConvertMatrix(const vr::HmdMatrix34_t& mat) { glm::mat4 glmMat( mat.m[0][0], mat.m[1][0], mat.m[2][0], 0.0, mat.m[0][1], mat.m[1][1], mat.m[2][1], 0.0, mat.m[0][2], mat.m[1][2], mat.m[2][2], 0.0, mat.m[0][3], mat.m[1][3], mat.m[2][3], 1.0f ); return glmMat; } glm::mat4 VRManager::ConvertMatrix(const vr::HmdMatrix44_t& mat) { glm::mat4 glmMat( mat.m[0][0], mat.m[1][0], mat.m[2][0], mat.m[3][0], mat.m[0][1], mat.m[1][1], mat.m[2][1], mat.m[3][1], mat.m[0][2], mat.m[1][2], mat.m[2][2], mat.m[3][2], mat.m[0][3], mat.m[1][3], mat.m[2][3], mat.m[3][3] ); return glmMat; } float VRManager::GetScale() const { return scale; } void VRManager::SetScale(float scale) { this->scale = scale; } bool VRManager::GetInput(vr::EVRButtonId buttonID) { for (vr::TrackedDeviceIndex_t unDevice = 0; unDevice < vr::k_unMaxTrackedDeviceCount; unDevice++) { vr::VRControllerState_t controllerState; if (vrSystem->GetControllerState(unDevice, &controllerState, sizeof(controllerState))) { pressedTrackedDevice[unDevice] = controllerState.ulButtonPressed == 0; if (controllerState.ulButtonPressed & vr::ButtonMaskFromId(buttonID)) return true; } } return false; } Component::VRDevice* VRManager::CreateVRDevice() { return vrDevices.Create(); } Component::VRDevice* VRManager::CreateVRDevice(const Json::Value& node) { Component::VRDevice* vrDevice = vrDevices.Create(); // Load values from Json node. std::string type = node.get("type", "controller").asString(); if (type == "controller") vrDevice->type = Component::VRDevice::CONTROLLER; else if (type == "headset") vrDevice->type = Component::VRDevice::HEADSET; vrDevice->controllerID = node.get("controllerID", 1).asInt(); return vrDevice; } const std::vector<Component::VRDevice*>& VRManager::GetVRDevices() const { return vrDevices.GetAll(); } void VRManager::ClearKilledComponents() { vrDevices.ClearKilled(); } <|endoftext|>
<commit_before>// Copyright (c) 2009-2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <chainparams.h> #include <core_io.h> #include <rpc/client.h> #include <rpc/util.h> #include <test/fuzz/fuzz.h> #include <util/memory.h> #include <limits> #include <string> void initialize() { static const auto verify_handle = MakeUnique<ECCVerifyHandle>(); SelectParams(CBaseChainParams::REGTEST); } void test_one_input(const std::vector<uint8_t>& buffer) { const std::string random_string(buffer.begin(), buffer.end()); bool valid = true; const UniValue univalue = [&] { try { return ParseNonRFCJSONValue(random_string); } catch (const std::runtime_error&) { valid = false; return NullUniValue; } }(); if (!valid) { return; } try { (void)ParseHashO(univalue, "A"); (void)ParseHashO(univalue, random_string); } catch (const UniValue&) { } catch (const std::runtime_error&) { } try { (void)ParseHashV(univalue, "A"); (void)ParseHashV(univalue, random_string); } catch (const UniValue&) { } catch (const std::runtime_error&) { } try { (void)ParseHexO(univalue, "A"); (void)ParseHexO(univalue, random_string); } catch (const UniValue&) { } catch (const std::runtime_error&) { } try { (void)ParseHexUV(univalue, "A"); (void)ParseHexUV(univalue, random_string); } catch (const UniValue&) { } catch (const std::runtime_error&) { } try { (void)ParseHexV(univalue, "A"); (void)ParseHexV(univalue, random_string); } catch (const UniValue&) { } catch (const std::runtime_error&) { } try { (void)ParseSighashString(univalue); } catch (const std::runtime_error&) { } try { (void)AmountFromValue(univalue); } catch (const UniValue&) { } catch (const std::runtime_error&) { } try { FlatSigningProvider provider; (void)EvalDescriptorStringOrObject(univalue, provider); } catch (const UniValue&) { } catch (const std::runtime_error&) { } try { (void)ParseConfirmTarget(univalue, std::numeric_limits<unsigned int>::max()); } catch (const UniValue&) { } catch (const std::runtime_error&) { } try { (void)ParseDescriptorRange(univalue); } catch (const UniValue&) { } catch (const std::runtime_error&) { } } <commit_msg>tests: Re-arrange test cases in parse_univalue to increase coverage<commit_after>// Copyright (c) 2009-2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <chainparams.h> #include <core_io.h> #include <rpc/client.h> #include <rpc/util.h> #include <test/fuzz/fuzz.h> #include <util/memory.h> #include <limits> #include <string> void initialize() { static const auto verify_handle = MakeUnique<ECCVerifyHandle>(); SelectParams(CBaseChainParams::REGTEST); } void test_one_input(const std::vector<uint8_t>& buffer) { const std::string random_string(buffer.begin(), buffer.end()); bool valid = true; const UniValue univalue = [&] { try { return ParseNonRFCJSONValue(random_string); } catch (const std::runtime_error&) { valid = false; return NullUniValue; } }(); if (!valid) { return; } try { (void)ParseHashO(univalue, "A"); } catch (const UniValue&) { } catch (const std::runtime_error&) { } try { (void)ParseHashO(univalue, random_string); } catch (const UniValue&) { } catch (const std::runtime_error&) { } try { (void)ParseHashV(univalue, "A"); } catch (const UniValue&) { } catch (const std::runtime_error&) { } try { (void)ParseHashV(univalue, random_string); } catch (const UniValue&) { } catch (const std::runtime_error&) { } try { (void)ParseHexO(univalue, "A"); } catch (const UniValue&) { } try { (void)ParseHexO(univalue, random_string); } catch (const UniValue&) { } try { (void)ParseHexUV(univalue, "A"); (void)ParseHexUV(univalue, random_string); } catch (const UniValue&) { } catch (const std::runtime_error&) { } try { (void)ParseHexV(univalue, "A"); } catch (const UniValue&) { } catch (const std::runtime_error&) { } try { (void)ParseHexV(univalue, random_string); } catch (const UniValue&) { } catch (const std::runtime_error&) { } try { (void)ParseSighashString(univalue); } catch (const std::runtime_error&) { } try { (void)AmountFromValue(univalue); } catch (const UniValue&) { } catch (const std::runtime_error&) { } try { FlatSigningProvider provider; (void)EvalDescriptorStringOrObject(univalue, provider); } catch (const UniValue&) { } catch (const std::runtime_error&) { } try { (void)ParseConfirmTarget(univalue, std::numeric_limits<unsigned int>::max()); } catch (const UniValue&) { } catch (const std::runtime_error&) { } try { (void)ParseDescriptorRange(univalue); } catch (const UniValue&) { } catch (const std::runtime_error&) { } } <|endoftext|>
<commit_before>/** * \file * \brief chip::lowLevelInitialization() implementation for STM32F7 * * \author Copyright (C) 2017 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "distortos/chip/lowLevelInitialization.hpp" namespace distortos { namespace chip { /*---------------------------------------------------------------------------------------------------------------------+ | global functions +---------------------------------------------------------------------------------------------------------------------*/ void lowLevelInitialization() { } } // namespace chip } // namespace distortos <commit_msg>Enable clock for selected GPIOs in lowLevelInitialization() for STM32F7<commit_after>/** * \file * \brief chip::lowLevelInitialization() implementation for STM32F7 * * \author Copyright (C) 2017 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "distortos/chip/lowLevelInitialization.hpp" #include "distortos/chip/CMSIS-proxy.h" namespace distortos { namespace chip { /*---------------------------------------------------------------------------------------------------------------------+ | global functions +---------------------------------------------------------------------------------------------------------------------*/ void lowLevelInitialization() { RCC->AHB1ENR |= #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOA_ENABLE RCC_AHB1ENR_GPIOAEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOA_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOB_ENABLE RCC_AHB1ENR_GPIOBEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOB_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOC_ENABLE RCC_AHB1ENR_GPIOCEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOC_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOD_ENABLE RCC_AHB1ENR_GPIODEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOD_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOE_ENABLE RCC_AHB1ENR_GPIOEEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOE_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOF_ENABLE RCC_AHB1ENR_GPIOFEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOF_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOG_ENABLE RCC_AHB1ENR_GPIOGEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOG_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOH_ENABLE RCC_AHB1ENR_GPIOHEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOH_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOI_ENABLE RCC_AHB1ENR_GPIOIEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOI_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOJ_ENABLE RCC_AHB1ENR_GPIOJEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOJ_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOK_ENABLE RCC_AHB1ENR_GPIOKEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOK_ENABLE 0; } } // namespace chip } // namespace distortos <|endoftext|>
<commit_before>// This file is part of the dune-gdt project: // https://github.com/dune-community/dune-gdt // Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved. // License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // or GPL-2.0+ (http://opensource.org/licenses/gpl-license) // with "runtime exception" (http://www.dune-project.org/license.html) // Authors: // Felix Schindler (2018) #ifndef DUNE_GDT_LOCAL_NUMERICAL_FLUXES_VIJAYASUNDARAM_HH #define DUNE_GDT_LOCAL_NUMERICAL_FLUXES_VIJAYASUNDARAM_HH #include <functional> #include <dune/xt/common/matrix.hh> #include <dune/xt/common/math.hh> #include <dune/xt/la/eigen-solver.hh> #include "interface.hh" namespace Dune { namespace GDT { template <size_t d, size_t m = 1, class R = double> class NumericalVijayasundaramFlux : public NumericalFluxInterface<d, m, R> { using ThisType = NumericalVijayasundaramFlux<d, m, R>; using BaseType = NumericalFluxInterface<d, m, R>; public: using typename BaseType::FluxType; using typename BaseType::PhysicalDomainType; using typename BaseType::StateRangeType; using FluxEigenDecompositionLambdaType = std::function<std::tuple<std::vector<XT::Common::real_t<R>>, XT::Common::FieldMatrix<XT::Common::real_t<R>, m, m>, XT::Common::FieldMatrix<XT::Common::real_t<R>, m, m>>( const FieldVector<R, m>&, const FieldVector<double, d>&, const XT::Common::Parameter& param)>; NumericalVijayasundaramFlux(const FluxType& flx) : BaseType(flx) , flux_eigen_decomposition_([&](const auto& w, const auto& n, const auto& param) { // evaluate flux jacobian, compute P matrix [DF2016, p. 404, (8.17)] const auto df = this->flux().jacobian(w, param); const auto P = df * n; auto eigensolver = XT::LA::make_eigen_solver( P, {{"type", XT::LA::eigen_solver_types(P)[0]}, {"assert_real_eigendecomposition", "1e-10"}}); return std::make_tuple( eigensolver.real_eigenvalues(), eigensolver.real_eigenvectors(), eigensolver.real_eigenvectors_inverse()); }) { } NumericalVijayasundaramFlux(const FluxType& flx, FluxEigenDecompositionLambdaType flux_eigen_decomposition) : BaseType(flx) , flux_eigen_decomposition_(flux_eigen_decomposition) { } std::unique_ptr<BaseType> copy() const override final { return std::make_unique<ThisType>(*this); } using BaseType::apply; StateRangeType apply(const StateRangeType& u, const StateRangeType& v, const PhysicalDomainType& n, const XT::Common::Parameter& param = {}) const override final { // compute decomposition const auto eigendecomposition = flux_eigen_decomposition_(0.5 * (u + v), n, param); const auto& evs = std::get<0>(eigendecomposition); const auto& T = std::get<1>(eigendecomposition); const auto& T_inv = std::get<2>(eigendecomposition); // compute numerical flux [DF2016, p. 428, (8.108)] auto lambda_plus = XT::Common::zeros_like(T); auto lambda_minus = XT::Common::zeros_like(T); for (size_t ii = 0; ii < m; ++ii) { const auto& real_ev = evs[ii]; XT::Common::set_matrix_entry(lambda_plus, ii, ii, XT::Common::max(real_ev, 0.)); XT::Common::set_matrix_entry(lambda_minus, ii, ii, XT::Common::min(real_ev, 0.)); } const auto P_plus = T * lambda_plus * T_inv; const auto P_minus = T * lambda_minus * T_inv; return P_plus * u + P_minus * v; } // ... apply(...) private: const FluxEigenDecompositionLambdaType flux_eigen_decomposition_; }; // class NumericalVijayasundaramFlux template <size_t d, size_t m, class R, class... Args> NumericalVijayasundaramFlux<d, m, R> make_numerical_vijayasundaram_flux(const XT::Functions::FunctionInterface<m, d, m, R>& flux, Args&&... args) { return NumericalVijayasundaramFlux<d, m, R>(flux, std::forward<Args>(args)...); } } // namespace GDT } // namespace Dune #endif // DUNE_GDT_LOCAL_NUMERICAL_FLUXES_VIJAYASUNDARAM_HH <commit_msg>[local.numerical-fluxes.vijayasundaram] fix memory error<commit_after>// This file is part of the dune-gdt project: // https://github.com/dune-community/dune-gdt // Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved. // License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // or GPL-2.0+ (http://opensource.org/licenses/gpl-license) // with "runtime exception" (http://www.dune-project.org/license.html) // Authors: // Felix Schindler (2018) #ifndef DUNE_GDT_LOCAL_NUMERICAL_FLUXES_VIJAYASUNDARAM_HH #define DUNE_GDT_LOCAL_NUMERICAL_FLUXES_VIJAYASUNDARAM_HH #include <functional> #include <tuple> #include <dune/xt/common/matrix.hh> #include <dune/xt/common/math.hh> #include <dune/xt/la/eigen-solver.hh> #include "interface.hh" namespace Dune { namespace GDT { template <size_t d, size_t m = 1, class R = double> class NumericalVijayasundaramFlux : public NumericalFluxInterface<d, m, R> { using ThisType = NumericalVijayasundaramFlux<d, m, R>; using BaseType = NumericalFluxInterface<d, m, R>; public: using typename BaseType::FluxType; using typename BaseType::PhysicalDomainType; using typename BaseType::StateRangeType; using FluxEigenDecompositionLambdaType = std::function<std::tuple<std::vector<XT::Common::real_t<R>>, XT::Common::FieldMatrix<XT::Common::real_t<R>, m, m>, XT::Common::FieldMatrix<XT::Common::real_t<R>, m, m>>( const FluxType&, const FieldVector<R, m>&, const FieldVector<double, d>&, const XT::Common::Parameter& param)>; NumericalVijayasundaramFlux(const FluxType& flx) : BaseType(flx) , flux_eigen_decomposition_([](const auto& f, const auto& w, const auto& n, const auto& param) { // evaluate flux jacobian, compute P matrix [DF2016, p. 404, (8.17)] const auto df = f.jacobian(w, param); const auto P = df * n; auto eigensolver = XT::LA::make_eigen_solver( P, {{"type", XT::LA::eigen_solver_types(P)[0]}, {"assert_real_eigendecomposition", "1e-10"}}); return std::make_tuple( eigensolver.real_eigenvalues(), eigensolver.real_eigenvectors(), eigensolver.real_eigenvectors_inverse()); }) { } NumericalVijayasundaramFlux(const FluxType& flx, FluxEigenDecompositionLambdaType flux_eigen_decomposition) : BaseType(flx) , flux_eigen_decomposition_(flux_eigen_decomposition) { } std::unique_ptr<BaseType> copy() const override final { return std::make_unique<ThisType>(*this); } using BaseType::apply; StateRangeType apply(const StateRangeType& u, const StateRangeType& v, const PhysicalDomainType& n, const XT::Common::Parameter& param = {}) const override final { // compute decomposition const auto eigendecomposition = flux_eigen_decomposition_(this->flux(), 0.5 * (u + v), n, param); const auto& evs = std::get<0>(eigendecomposition); const auto& T = std::get<1>(eigendecomposition); const auto& T_inv = std::get<2>(eigendecomposition); // compute numerical flux [DF2016, p. 428, (8.108)] auto lambda_plus = XT::Common::zeros_like(T); auto lambda_minus = XT::Common::zeros_like(T); for (size_t ii = 0; ii < m; ++ii) { const auto& real_ev = evs[ii]; XT::Common::set_matrix_entry(lambda_plus, ii, ii, XT::Common::max(real_ev, 0.)); XT::Common::set_matrix_entry(lambda_minus, ii, ii, XT::Common::min(real_ev, 0.)); } const auto P_plus = T * lambda_plus * T_inv; const auto P_minus = T * lambda_minus * T_inv; return P_plus * u + P_minus * v; } // ... apply(...) private: const FluxEigenDecompositionLambdaType flux_eigen_decomposition_; }; // class NumericalVijayasundaramFlux template <size_t d, size_t m, class R, class... Args> NumericalVijayasundaramFlux<d, m, R> make_numerical_vijayasundaram_flux(const XT::Functions::FunctionInterface<m, d, m, R>& flux, Args&&... args) { return NumericalVijayasundaramFlux<d, m, R>(flux, std::forward<Args>(args)...); } } // namespace GDT } // namespace Dune #endif // DUNE_GDT_LOCAL_NUMERICAL_FLUXES_VIJAYASUNDARAM_HH <|endoftext|>
<commit_before>// This file is part of the dune-gdt project: // https://github.com/dune-community/dune-gdt // Copyright 2010-2017 dune-gdt developers and contributors. All rights reserved. // License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // or GPL-2.0+ (http://opensource.org/licenses/gpl-license) // with "runtime exception" (http://www.dune-project.org/license.html) // Authors: // Felix Schindler (2016 - 2017) // Rene Milk (2016 - 2017) #ifndef DUNE_GDT_TESTS_LINEARELLIPTIC_SWIPDG_ESTIMATORS_HH #define DUNE_GDT_TESTS_LINEARELLIPTIC_SWIPDG_ESTIMATORS_HH #include <dune/xt/functions/spe10/model1.hh> #include <dune/xt/common/test/common.hh> #include "discretizers/ipdg.hh" #include "eocstudy.hh" #include "estimators/swipdg-fluxreconstruction.hh" #include "swipdg-estimator-expectations.hh" namespace Dune { namespace GDT { namespace Test { template <class TestCaseImp, class DiscretizerImp> class LinearEllipticSwipdgEstimatorStudy : public LinearEllipticEocStudy<TestCaseImp, DiscretizerImp> { typedef LinearEllipticSwipdgEstimatorStudy<TestCaseImp, DiscretizerImp> ThisType; typedef LinearEllipticEocStudy<TestCaseImp, DiscretizerImp> BaseType; public: using typename BaseType::TestCaseType; using typename BaseType::Discretizer; using typename BaseType::DiscretizationType; using typename BaseType::FunctionType; using typename BaseType::VectorType; using typename BaseType::SpaceType; using typename BaseType::ProblemType; using typename BaseType::GridViewType; private: typedef typename ProblemType::DiffusionFactorType DiffusionFactorType; typedef typename ProblemType::DiffusionTensorType DiffusionTensorType; static const int polOrder = Discretizer::polOrder; typedef LinearElliptic::SwipdgFluxreconstrutionEstimators:: LocalNonconformityESV2007<SpaceType, VectorType, DiffusionFactorType, DiffusionTensorType, GridViewType> LocalNonconformityESV2007Estimator; typedef LinearElliptic::SwipdgFluxreconstrutionEstimators:: LocalResidualESV2007<SpaceType, VectorType, FunctionType, DiffusionFactorType, DiffusionTensorType, GridViewType> LocalResidualESV2007Estimator; typedef LinearElliptic::SwipdgFluxreconstrutionEstimators:: LocalDiffusiveFluxESV2007<SpaceType, VectorType, DiffusionFactorType, DiffusionTensorType, GridViewType> LocalDiffusiveFluxESV2007Estimator; typedef LinearElliptic::SwipdgFluxreconstrutionEstimators:: ESV2007<SpaceType, VectorType, FunctionType, DiffusionFactorType, DiffusionTensorType, GridViewType> ESV2007Estimator; typedef LinearElliptic::SwipdgFluxreconstrutionEstimators::ESV2007AlternativeSummation<SpaceType, VectorType, FunctionType, DiffusionFactorType, DiffusionTensorType, GridViewType> ESV2007AlternativeSummationEstimator; public: // a perfect forwarding ctor did not do the job here, since it was not able to match the std::initializer_list: {"L2"} LinearEllipticSwipdgEstimatorStudy(TestCaseType& test_case, const std::vector<std::string> only_these_norms = {}, const std::string visualize_prefix = "", const size_t over_integrate = 2) : BaseType(test_case, only_these_norms, visualize_prefix, over_integrate) { } virtual ~LinearEllipticSwipdgEstimatorStudy() = default; virtual std::string identifier() const override final { return "gdt.linearelliptic.estimators.swipdg.polorder_" + Dune::XT::Common::to_string(int(polOrder)); } virtual size_t expected_rate(const std::string type) const override final { // If you get an undefined reference here from the linker, see the explanation in LinearEllipticEocStudy! return LinearEllipticSwipdgEstimatorExpectations<TestCaseType, Discretizer::type, polOrder>::rate(type); } virtual std::vector<double> expected_results(const std::string type) const override final { // If you get an undefined reference here from the linker, see above! return LinearEllipticSwipdgEstimatorExpectations<TestCaseType, Discretizer::type, polOrder>::results( this->test_case_, type); } virtual std::vector<std::string> available_norms() const override final { return {"energy"}; } virtual std::vector<std::string> available_estimators() const override final { return {LocalNonconformityESV2007Estimator::id(), LocalResidualESV2007Estimator::id(), LocalDiffusiveFluxESV2007Estimator::id(), "efficiency_" + ESV2007Estimator::id(), "efficiency_" + ESV2007AlternativeSummationEstimator::id()}; } virtual double estimate(const VectorType& vector, const std::string type) override final { const auto& space = this->current_discretization_->ansatz_space(); const auto& force = this->test_case_.problem().force(); const auto& diffusion_factor = this->test_case_.problem().diffusion_factor(); const auto& diffusion_tensor = this->test_case_.problem().diffusion_tensor(); const auto grid_view = this->test_case_.level_provider(this->current_refinement_) .template layer<TestCaseType::layer_type, XT::Grid::Backends::view>( this->test_case_.level_of(this->current_refinement_)); if (type == LocalNonconformityESV2007Estimator::id()) return LocalNonconformityESV2007Estimator::estimate(grid_view, space, vector, diffusion_factor, diffusion_tensor); else if (type == LocalResidualESV2007Estimator::id()) return LocalResidualESV2007Estimator::estimate( grid_view, space, vector, force, diffusion_factor, diffusion_tensor); else if (type == LocalDiffusiveFluxESV2007Estimator::id()) return LocalDiffusiveFluxESV2007Estimator::estimate(grid_view, space, vector, diffusion_factor, diffusion_tensor); else if (type == ESV2007Estimator::id()) return ESV2007Estimator::estimate(grid_view, space, vector, force, diffusion_factor, diffusion_tensor); else if (type == "efficiency_" + ESV2007Estimator::id()) return estimate(vector, ESV2007Estimator::id()) / this->current_error_norm("energy"); else if (type == ESV2007AlternativeSummationEstimator::id()) return ESV2007AlternativeSummationEstimator::estimate( grid_view, space, vector, force, diffusion_factor, diffusion_tensor); else if (type == "efficiency_" + ESV2007AlternativeSummationEstimator::id()) return estimate(vector, ESV2007AlternativeSummationEstimator::id()) / this->current_error_norm("energy"); else DUNE_THROW(XT::Common::Exceptions::wrong_input_given, "Wrong type `" << type << "` requested (see available_estimators()!"); return 0.; } // ... estimate(...) std::map<std::string, std::vector<double>> run(std::ostream& out, const bool print_timings = false) { return XT::Common::ConvergenceStudy::run(false, out, print_timings); } }; // class LinearEllipticSwipdgEstimatorStudy } // namespace Test } // namespace GDT } // namespace Dune template <class TestCaseType> struct linearelliptic_SWIPDG_estimators : public ::testing::Test { template <Dune::GDT::Backends space_backend, Dune::XT::LA::Backends la_backend, int polOrder> static void eoc_study() { using namespace Dune; using namespace Dune::GDT; TestCaseType test_case; test_case.print_header(DXTC_LOG_INFO_0); DXTC_LOG_INFO_0 << std::endl; typedef LinearElliptic::IpdgDiscretizer<typename TestCaseType::GridType, TestCaseType::layer_type, space_backend, la_backend, polOrder, typename TestCaseType::ProblemType::RangeFieldType, 1, LocalEllipticIpdgIntegrands::Method::swipdg> Discretizer; Dune::GDT::Test::LinearEllipticSwipdgEstimatorStudy<TestCaseType, Discretizer> eoc_study(test_case); try { Dune::XT::Test::check_eoc_study_for_success(eoc_study, eoc_study.run(DXTC_LOG_INFO_0), /*zero_tolerance=*/1e-10); } catch (Dune::XT::Common::Exceptions::spe10_data_file_missing&) { Dune::XT::Common::TimedLogger().get("gdt.test.linearelliptic.swipdg.discretization").warn() << "missing SPE10 data file!" << std::endl; } } // ... eoc_study() }; // linearelliptic_SWIPDG_estimators #endif // DUNE_GDT_TESTS_LINEARELLIPTIC_SWIPDG_ESTIMATORS_HH <commit_msg>[test] increase swipdg-est zero-tol for iterative la solves in mpiruns<commit_after>// This file is part of the dune-gdt project: // https://github.com/dune-community/dune-gdt // Copyright 2010-2017 dune-gdt developers and contributors. All rights reserved. // License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // or GPL-2.0+ (http://opensource.org/licenses/gpl-license) // with "runtime exception" (http://www.dune-project.org/license.html) // Authors: // Felix Schindler (2016 - 2017) // Rene Milk (2016 - 2017) #ifndef DUNE_GDT_TESTS_LINEARELLIPTIC_SWIPDG_ESTIMATORS_HH #define DUNE_GDT_TESTS_LINEARELLIPTIC_SWIPDG_ESTIMATORS_HH #include <dune/xt/functions/spe10/model1.hh> #include <dune/xt/common/test/common.hh> #include "discretizers/ipdg.hh" #include "eocstudy.hh" #include "estimators/swipdg-fluxreconstruction.hh" #include "swipdg-estimator-expectations.hh" namespace Dune { namespace GDT { namespace Test { template <class TestCaseImp, class DiscretizerImp> class LinearEllipticSwipdgEstimatorStudy : public LinearEllipticEocStudy<TestCaseImp, DiscretizerImp> { typedef LinearEllipticSwipdgEstimatorStudy<TestCaseImp, DiscretizerImp> ThisType; typedef LinearEllipticEocStudy<TestCaseImp, DiscretizerImp> BaseType; public: using typename BaseType::TestCaseType; using typename BaseType::Discretizer; using typename BaseType::DiscretizationType; using typename BaseType::FunctionType; using typename BaseType::VectorType; using typename BaseType::SpaceType; using typename BaseType::ProblemType; using typename BaseType::GridViewType; private: typedef typename ProblemType::DiffusionFactorType DiffusionFactorType; typedef typename ProblemType::DiffusionTensorType DiffusionTensorType; static const int polOrder = Discretizer::polOrder; typedef LinearElliptic::SwipdgFluxreconstrutionEstimators:: LocalNonconformityESV2007<SpaceType, VectorType, DiffusionFactorType, DiffusionTensorType, GridViewType> LocalNonconformityESV2007Estimator; typedef LinearElliptic::SwipdgFluxreconstrutionEstimators:: LocalResidualESV2007<SpaceType, VectorType, FunctionType, DiffusionFactorType, DiffusionTensorType, GridViewType> LocalResidualESV2007Estimator; typedef LinearElliptic::SwipdgFluxreconstrutionEstimators:: LocalDiffusiveFluxESV2007<SpaceType, VectorType, DiffusionFactorType, DiffusionTensorType, GridViewType> LocalDiffusiveFluxESV2007Estimator; typedef LinearElliptic::SwipdgFluxreconstrutionEstimators:: ESV2007<SpaceType, VectorType, FunctionType, DiffusionFactorType, DiffusionTensorType, GridViewType> ESV2007Estimator; typedef LinearElliptic::SwipdgFluxreconstrutionEstimators::ESV2007AlternativeSummation<SpaceType, VectorType, FunctionType, DiffusionFactorType, DiffusionTensorType, GridViewType> ESV2007AlternativeSummationEstimator; public: // a perfect forwarding ctor did not do the job here, since it was not able to match the std::initializer_list: {"L2"} LinearEllipticSwipdgEstimatorStudy(TestCaseType& test_case, const std::vector<std::string> only_these_norms = {}, const std::string visualize_prefix = "", const size_t over_integrate = 2) : BaseType(test_case, only_these_norms, visualize_prefix, over_integrate) { } virtual ~LinearEllipticSwipdgEstimatorStudy() = default; virtual std::string identifier() const override final { return "gdt.linearelliptic.estimators.swipdg.polorder_" + Dune::XT::Common::to_string(int(polOrder)); } virtual size_t expected_rate(const std::string type) const override final { // If you get an undefined reference here from the linker, see the explanation in LinearEllipticEocStudy! return LinearEllipticSwipdgEstimatorExpectations<TestCaseType, Discretizer::type, polOrder>::rate(type); } virtual std::vector<double> expected_results(const std::string type) const override final { // If you get an undefined reference here from the linker, see above! return LinearEllipticSwipdgEstimatorExpectations<TestCaseType, Discretizer::type, polOrder>::results( this->test_case_, type); } virtual std::vector<std::string> available_norms() const override final { return {"energy"}; } virtual std::vector<std::string> available_estimators() const override final { return {LocalNonconformityESV2007Estimator::id(), LocalResidualESV2007Estimator::id(), LocalDiffusiveFluxESV2007Estimator::id(), "efficiency_" + ESV2007Estimator::id(), "efficiency_" + ESV2007AlternativeSummationEstimator::id()}; } virtual double estimate(const VectorType& vector, const std::string type) override final { const auto& space = this->current_discretization_->ansatz_space(); const auto& force = this->test_case_.problem().force(); const auto& diffusion_factor = this->test_case_.problem().diffusion_factor(); const auto& diffusion_tensor = this->test_case_.problem().diffusion_tensor(); const auto grid_view = this->test_case_.level_provider(this->current_refinement_) .template layer<TestCaseType::layer_type, XT::Grid::Backends::view>( this->test_case_.level_of(this->current_refinement_)); if (type == LocalNonconformityESV2007Estimator::id()) return LocalNonconformityESV2007Estimator::estimate(grid_view, space, vector, diffusion_factor, diffusion_tensor); else if (type == LocalResidualESV2007Estimator::id()) return LocalResidualESV2007Estimator::estimate( grid_view, space, vector, force, diffusion_factor, diffusion_tensor); else if (type == LocalDiffusiveFluxESV2007Estimator::id()) return LocalDiffusiveFluxESV2007Estimator::estimate(grid_view, space, vector, diffusion_factor, diffusion_tensor); else if (type == ESV2007Estimator::id()) return ESV2007Estimator::estimate(grid_view, space, vector, force, diffusion_factor, diffusion_tensor); else if (type == "efficiency_" + ESV2007Estimator::id()) return estimate(vector, ESV2007Estimator::id()) / this->current_error_norm("energy"); else if (type == ESV2007AlternativeSummationEstimator::id()) return ESV2007AlternativeSummationEstimator::estimate( grid_view, space, vector, force, diffusion_factor, diffusion_tensor); else if (type == "efficiency_" + ESV2007AlternativeSummationEstimator::id()) return estimate(vector, ESV2007AlternativeSummationEstimator::id()) / this->current_error_norm("energy"); else DUNE_THROW(XT::Common::Exceptions::wrong_input_given, "Wrong type `" << type << "` requested (see available_estimators()!"); return 0.; } // ... estimate(...) std::map<std::string, std::vector<double>> run(std::ostream& out, const bool print_timings = false) { return XT::Common::ConvergenceStudy::run(false, out, print_timings); } }; // class LinearEllipticSwipdgEstimatorStudy } // namespace Test } // namespace GDT } // namespace Dune template <class TestCaseType> struct linearelliptic_SWIPDG_estimators : public ::testing::Test { template <Dune::GDT::Backends space_backend, Dune::XT::LA::Backends la_backend, int polOrder> static void eoc_study() { using namespace Dune; using namespace Dune::GDT; TestCaseType test_case; test_case.print_header(DXTC_LOG_INFO_0); DXTC_LOG_INFO_0 << std::endl; typedef LinearElliptic::IpdgDiscretizer<typename TestCaseType::GridType, TestCaseType::layer_type, space_backend, la_backend, polOrder, typename TestCaseType::ProblemType::RangeFieldType, 1, LocalEllipticIpdgIntegrands::Method::swipdg> Discretizer; Dune::GDT::Test::LinearEllipticSwipdgEstimatorStudy<TestCaseType, Discretizer> eoc_study(test_case); try { Dune::XT::Test::check_eoc_study_for_success( eoc_study, eoc_study.run(DXTC_LOG_INFO_0), /*zero_tolerance=*/1.4e-10); } catch (Dune::XT::Common::Exceptions::spe10_data_file_missing&) { Dune::XT::Common::TimedLogger().get("gdt.test.linearelliptic.swipdg.discretization").warn() << "missing SPE10 data file!" << std::endl; } } // ... eoc_study() }; // linearelliptic_SWIPDG_estimators #endif // DUNE_GDT_TESTS_LINEARELLIPTIC_SWIPDG_ESTIMATORS_HH <|endoftext|>
<commit_before>/* * Copyright (C) 2012 by Glenn Hickey (hickey@soe.ucsc.edu) * * Released under the MIT license, see LICENSE.txt */ #include <deque> #include <cassert> #include "halLiftover.h" using namespace std; using namespace hal; Liftover::Liftover() : _outBedStream(NULL), _inBedVersion(-1), _outBedVersion(-1), _srcGenome(NULL), _tgtGenome(NULL) { } Liftover::~Liftover() { } void Liftover::convert(AlignmentConstPtr alignment, const Genome* srcGenome, istream* inBedStream, const Genome* tgtGenome, ostream* outBedStream, int inBedVersion, int outBedVersion, bool addExtraColumns, bool traverseDupes) { _srcGenome = srcGenome; _tgtGenome = tgtGenome; _outBedStream = outBedStream; _addExtraColumns = addExtraColumns; _inBedVersion = inBedVersion; _outBedVersion = outBedVersion; _traverseDupes = traverseDupes; _missedSet.clear(); _tgtSet.clear(); assert(_srcGenome && inBedStream && tgtGenome && outBedStream); _tgtSet.insert(tgtGenome); // we copy into a stringstream because we never want to // run getBedVersion (which does random access) on cin (which is a // possible value for inBedStream) string firstLineBuffer; stringstream* firstLineStream = NULL; if (_inBedVersion <= 0) { skipWhiteSpaces(inBedStream); std::getline(*inBedStream, firstLineBuffer); firstLineStream = new stringstream(firstLineBuffer); _inBedVersion = BedScanner::getBedVersion(firstLineStream); assert(inBedStream->eof() || _inBedVersion >= 3); size_t numCols = BedScanner::getNumColumns(firstLineBuffer); if ((int)numCols > _inBedVersion) { cerr << "Warning: auto-detecting input BED version " << _inBedVersion << " even though " << numCols << " columns present" << endl; } } if (_outBedVersion <= 0) { _outBedVersion = _inBedVersion; } if (_inBedVersion <= 9 && _outBedVersion > _inBedVersion) { stringstream ss; ss << "Unable to convert from BED version " << _inBedVersion << " to " << _outBedVersion << ": input version must be at least as high as output" " version."; throw hal_exception(ss.str()); } if (firstLineStream != NULL) { scan(firstLineStream, _inBedVersion); delete firstLineStream; } scan(inBedStream, _inBedVersion); } void Liftover::visitBegin() { } void Liftover::visitLine() { _outBedLines.clear(); _srcSequence = _srcGenome->getSequence(_bedLine._chrName); if (_srcSequence == NULL) { pair<set<string>::iterator, bool> result = _missedSet.insert( _bedLine._chrName); if (result.second == true) { std::cerr << "Unable to find sequence " << _bedLine._chrName << " in genome " << _srcGenome->getName() << endl; } return; } else if (_bedLine._end > (hal_index_t)_srcSequence->getSequenceLength()) { std::cerr << "Skipping interval with endpoint " << _bedLine._end << "because sequence " << _bedLine._chrName << " has length " << _srcSequence->getSequenceLength() << endl; return; } liftInterval(_outBedLines); if (_inBedVersion > 9 && !_bedLine._blocks.empty()) { _mappedBlocks.clear(); liftBlockIntervals(); if (_mappedBlocks.size() > 0 && _outBedVersion > 9) { // extend the intervals mergeIntervals(); // fill them with mapped blocks assignBlocksToIntervals(); } if (_outBedVersion <= 9) { //only map the blocks and forget about the intervals writeBlocksAsIntervals(); } } cleanResults(); _outBedLines.sort(BedLineSrcLess()); writeLineResults(); } void Liftover::visitEOF() { } void Liftover::writeLineResults() { BedList::iterator i = _outBedLines.begin(); for (; i != _outBedLines.end(); ++i) { if (_addExtraColumns == false) { i->_extra.clear(); } i->write(*_outBedStream, _outBedVersion); } } void Liftover::assignBlocksToIntervals() { // sort the mapped blocks by source coordinate _mappedBlocks.sort(BedLineSrcLess()); // sort intervals in target coordinates set<BedLine*, BedLinePLess> intervalSet; set<BedLine*, BedLinePLess>::iterator setIt; for (BedList::iterator i = _outBedLines.begin(); i != _outBedLines.end(); ++i) { assert((*i)._blocks.empty()); intervalSet.insert(&*i); } BedList::iterator blockPrev = _mappedBlocks.end(); BedList::iterator blockNext; for (BedList::iterator blockIt = _mappedBlocks.begin(); blockIt != _mappedBlocks.end(); blockIt = blockNext) { blockNext = blockIt; ++blockNext; // find first interval with start coordinate less than setIt = intervalSet.lower_bound(&*blockIt); if (setIt != intervalSet.begin() && ( setIt == intervalSet.end() || (*setIt)->_chrName != (*blockIt)._chrName || (*setIt)->_start > (*blockIt)._start)) { --setIt; } assert((*setIt)->_chrName == (*blockIt)._chrName); // check if the found interval contains the block if ((*setIt)->_start <= (*blockIt)._start && (*setIt)->_end >= (*blockIt)._end) { bool compatible = blockPrev == _mappedBlocks.end() || (*setIt)->_blocks.empty(); if (!compatible) { hal_index_t blockStart = (*setIt)->_blocks.back()._start + (*setIt)->_start; hal_index_t blockEnd = blockStart + (*setIt)->_blocks.back()._length; compatible = ((*blockPrev)._start == blockStart && (*blockPrev)._end == blockEnd && (*blockIt)._start >= blockEnd) ; } BedBlock block; block._start = (*blockIt)._start - (*setIt)->_start; block._length = (*blockIt)._end - (*blockIt)._start; // we can add the block to the intervals list without breaking // ordering in the original input if (compatible == true) { (*setIt)->_blocks.push_back(block); } else { /* cout << "setIt.start " << (*setIt)->_start << " setIt.end " << (*setIt)->_end << " blockit.start " << (*blockIt)._start << " blockit.end " << (*blockIt)._end << endl; cout << " blockprev.start " << (*blockPrev)._start << " blockprev.end " << (*blockPrev)._end << endl; cout << " blockback " <<( (*setIt)->_blocks.back()._start + (*setIt)->_start) << " blockbakcend " << ( (*setIt)->_blocks.back()._start + (*setIt)->_start + (*setIt)->_blocks.back()._length) << endl; */ assert((*setIt)->_blocks.size() > 0); // otherwise, we duplicate the containing interval, zap all its // blocks, and add the new block. the old interval can no longer // be modified and it is removed from the set BedLine newInterval = **setIt; intervalSet.erase(setIt); newInterval._blocks.clear(); newInterval._blocks.push_back(block); _outBedLines.push_back(newInterval); intervalSet.insert(&_outBedLines.back()); } } else { /* cout << "setIt.start " << (*setIt)->_start << " setIt.end " << (*setIt)->_end << " blockit.start " << (*blockIt)._start << " blockit.end " << (*blockIt)._end << endl; */ assert(false); } blockPrev = blockIt; } } void Liftover::writeBlocksAsIntervals() { _outBedLines = _mappedBlocks; } void Liftover::liftBlockIntervals() { BedLine originalBedLine = _bedLine; std::sort(_bedLine._blocks.begin(), _bedLine._blocks.end()); vector<BedBlock>::iterator blockIt = _bedLine._blocks.begin(); for (; blockIt != _bedLine._blocks.end(); ++blockIt) { _bedLine._start = blockIt->_start + originalBedLine._start; _bedLine._end = _bedLine._start + blockIt->_length; if (_bedLine._end > _bedLine._start) { liftInterval(_mappedBlocks); } } _bedLine._start = originalBedLine._start; _bedLine._end = originalBedLine._end; } // merge intervals (that will contain blocks) if they are on same strand // and sequence and are colinear (but not necessarily directly adjacent) void Liftover::mergeIntervals() { assert(_outBedLines.empty() == false); if (_outBedLines.size() > 1) { // sort by target coordinate _outBedLines.sort(BedLineLess()); BedList::iterator i; BedList::iterator j; for (i = _outBedLines.begin(); i != _outBedLines.end(); ++i) { j = i; ++j; if (j != _outBedLines.end()) { if ((*i)._chrName == (*j)._chrName && (*i)._strand == (*j)._strand) { assert((*i)._start < (*j)._start); (*i)._end = max((*i)._end, (*j)._end); _outBedLines.erase(j); } } } } } // do a little postprocessing on the lifted intervals to make sure // they are bed compliant void Liftover::cleanResults() { if (_outBedVersion > 6) { BedList::iterator i; for (i = _outBedLines.begin(); i != _outBedLines.end(); ++i) { if (_bedLine._thickStart != 0 || _bedLine._thickEnd != 0) { i->_thickStart = i->_start; i->_thickEnd = i->_end; if (_bedLine._thickStart != _bedLine._start || _bedLine._thickEnd != _bedLine._end) { cerr << "Input BED line " << _lineNumber << " warning: " << "thickStart different from chromStart or thickEnd " << "different from chromEnd not supported. Assuming they" << " are the same." << endl; } } else { assert(i->_thickStart == 0 && i->_thickEnd == 0); } if (_outBedVersion > 9 && i->_blocks.size() > 0) { hal_index_t startDelta = i->_blocks[0]._start; assert(startDelta >= 0); if (startDelta > 0) { vector<BedBlock>::iterator j; vector<BedBlock>::iterator k; for (j = i->_blocks.begin(); j != i->_blocks.end(); ++j) { j->_start -= startDelta; k = j; ++k; assert(k == i->_blocks.end() || k->_start >= (j->_start + j->_length)); } i->_start += startDelta; } assert(i->_blocks[0]._start == 0); hal_index_t endDelta = i->_end - (i->_blocks.back()._start + i->_blocks.back()._length + i->_start); assert(endDelta >= 0); i->_end -= endDelta; assert(i->_blocks.back()._start + i->_blocks.back()._length + i->_start == i->_end); } } } } <commit_msg>filter out lines with zero blocks when writing bed12<commit_after>/* * Copyright (C) 2012 by Glenn Hickey (hickey@soe.ucsc.edu) * * Released under the MIT license, see LICENSE.txt */ #include <deque> #include <cassert> #include "halLiftover.h" using namespace std; using namespace hal; Liftover::Liftover() : _outBedStream(NULL), _inBedVersion(-1), _outBedVersion(-1), _srcGenome(NULL), _tgtGenome(NULL) { } Liftover::~Liftover() { } void Liftover::convert(AlignmentConstPtr alignment, const Genome* srcGenome, istream* inBedStream, const Genome* tgtGenome, ostream* outBedStream, int inBedVersion, int outBedVersion, bool addExtraColumns, bool traverseDupes) { _srcGenome = srcGenome; _tgtGenome = tgtGenome; _outBedStream = outBedStream; _addExtraColumns = addExtraColumns; _inBedVersion = inBedVersion; _outBedVersion = outBedVersion; _traverseDupes = traverseDupes; _missedSet.clear(); _tgtSet.clear(); assert(_srcGenome && inBedStream && tgtGenome && outBedStream); _tgtSet.insert(tgtGenome); // we copy into a stringstream because we never want to // run getBedVersion (which does random access) on cin (which is a // possible value for inBedStream) string firstLineBuffer; stringstream* firstLineStream = NULL; if (_inBedVersion <= 0) { skipWhiteSpaces(inBedStream); std::getline(*inBedStream, firstLineBuffer); firstLineStream = new stringstream(firstLineBuffer); _inBedVersion = BedScanner::getBedVersion(firstLineStream); assert(inBedStream->eof() || _inBedVersion >= 3); size_t numCols = BedScanner::getNumColumns(firstLineBuffer); if ((int)numCols > _inBedVersion) { cerr << "Warning: auto-detecting input BED version " << _inBedVersion << " even though " << numCols << " columns present" << endl; } } if (_outBedVersion <= 0) { _outBedVersion = _inBedVersion; } if (_inBedVersion <= 9 && _outBedVersion > _inBedVersion) { stringstream ss; ss << "Unable to convert from BED version " << _inBedVersion << " to " << _outBedVersion << ": input version must be at least as high as output" " version."; throw hal_exception(ss.str()); } if (firstLineStream != NULL) { scan(firstLineStream, _inBedVersion); delete firstLineStream; } scan(inBedStream, _inBedVersion); } void Liftover::visitBegin() { } void Liftover::visitLine() { _outBedLines.clear(); _srcSequence = _srcGenome->getSequence(_bedLine._chrName); if (_srcSequence == NULL) { pair<set<string>::iterator, bool> result = _missedSet.insert( _bedLine._chrName); if (result.second == true) { std::cerr << "Unable to find sequence " << _bedLine._chrName << " in genome " << _srcGenome->getName() << endl; } return; } else if (_bedLine._end > (hal_index_t)_srcSequence->getSequenceLength()) { std::cerr << "Skipping interval with endpoint " << _bedLine._end << "because sequence " << _bedLine._chrName << " has length " << _srcSequence->getSequenceLength() << endl; return; } liftInterval(_outBedLines); if (_inBedVersion > 9 && !_bedLine._blocks.empty()) { _mappedBlocks.clear(); liftBlockIntervals(); if (_mappedBlocks.size() > 0 && _outBedVersion > 9) { // extend the intervals mergeIntervals(); // fill them with mapped blocks assignBlocksToIntervals(); } if (_outBedVersion <= 9) { //only map the blocks and forget about the intervals writeBlocksAsIntervals(); } } cleanResults(); _outBedLines.sort(BedLineSrcLess()); writeLineResults(); } void Liftover::visitEOF() { } void Liftover::writeLineResults() { BedList::iterator i = _outBedLines.begin(); for (; i != _outBedLines.end(); ++i) { if (_addExtraColumns == false) { i->_extra.clear(); } i->write(*_outBedStream, _outBedVersion); } } void Liftover::assignBlocksToIntervals() { // sort the mapped blocks by source coordinate _mappedBlocks.sort(BedLineSrcLess()); // sort intervals in target coordinates set<BedLine*, BedLinePLess> intervalSet; set<BedLine*, BedLinePLess>::iterator setIt; for (BedList::iterator i = _outBedLines.begin(); i != _outBedLines.end(); ++i) { assert((*i)._blocks.empty()); intervalSet.insert(&*i); } BedList::iterator blockPrev = _mappedBlocks.end(); BedList::iterator blockNext; for (BedList::iterator blockIt = _mappedBlocks.begin(); blockIt != _mappedBlocks.end(); blockIt = blockNext) { blockNext = blockIt; ++blockNext; // find first interval with start coordinate less than setIt = intervalSet.lower_bound(&*blockIt); if (setIt != intervalSet.begin() && ( setIt == intervalSet.end() || (*setIt)->_chrName != (*blockIt)._chrName || (*setIt)->_start > (*blockIt)._start)) { --setIt; } assert((*setIt)->_chrName == (*blockIt)._chrName); // check if the found interval contains the block if ((*setIt)->_start <= (*blockIt)._start && (*setIt)->_end >= (*blockIt)._end) { bool compatible = blockPrev == _mappedBlocks.end() || (*setIt)->_blocks.empty(); if (!compatible) { hal_index_t blockStart = (*setIt)->_blocks.back()._start + (*setIt)->_start; hal_index_t blockEnd = blockStart + (*setIt)->_blocks.back()._length; compatible = ((*blockPrev)._start == blockStart && (*blockPrev)._end == blockEnd && (*blockIt)._start >= blockEnd) ; } BedBlock block; block._start = (*blockIt)._start - (*setIt)->_start; block._length = (*blockIt)._end - (*blockIt)._start; // we can add the block to the intervals list without breaking // ordering in the original input if (compatible == true) { (*setIt)->_blocks.push_back(block); } else { /* cout << "setIt.start " << (*setIt)->_start << " setIt.end " << (*setIt)->_end << " blockit.start " << (*blockIt)._start << " blockit.end " << (*blockIt)._end << endl; cout << " blockprev.start " << (*blockPrev)._start << " blockprev.end " << (*blockPrev)._end << endl; cout << " blockback " <<( (*setIt)->_blocks.back()._start + (*setIt)->_start) << " blockbakcend " << ( (*setIt)->_blocks.back()._start + (*setIt)->_start + (*setIt)->_blocks.back()._length) << endl; */ assert((*setIt)->_blocks.size() > 0); // otherwise, we duplicate the containing interval, zap all its // blocks, and add the new block. the old interval can no longer // be modified and it is removed from the set BedLine newInterval = **setIt; intervalSet.erase(setIt); newInterval._blocks.clear(); newInterval._blocks.push_back(block); _outBedLines.push_back(newInterval); intervalSet.insert(&_outBedLines.back()); } } else { /* cout << "setIt.start " << (*setIt)->_start << " setIt.end " << (*setIt)->_end << " blockit.start " << (*blockIt)._start << " blockit.end " << (*blockIt)._end << endl; */ assert(false); } blockPrev = blockIt; } } void Liftover::writeBlocksAsIntervals() { _outBedLines = _mappedBlocks; } void Liftover::liftBlockIntervals() { BedLine originalBedLine = _bedLine; std::sort(_bedLine._blocks.begin(), _bedLine._blocks.end()); vector<BedBlock>::iterator blockIt = _bedLine._blocks.begin(); for (; blockIt != _bedLine._blocks.end(); ++blockIt) { _bedLine._start = blockIt->_start + originalBedLine._start; _bedLine._end = _bedLine._start + blockIt->_length; if (_bedLine._end > _bedLine._start) { liftInterval(_mappedBlocks); } } _bedLine._start = originalBedLine._start; _bedLine._end = originalBedLine._end; } // merge intervals (that will contain blocks) if they are on same strand // and sequence and are colinear (but not necessarily directly adjacent) void Liftover::mergeIntervals() { assert(_outBedLines.empty() == false); if (_outBedLines.size() > 1) { // sort by target coordinate _outBedLines.sort(BedLineLess()); BedList::iterator i; BedList::iterator j; for (i = _outBedLines.begin(); i != _outBedLines.end(); ++i) { j = i; ++j; if (j != _outBedLines.end()) { if ((*i)._chrName == (*j)._chrName && (*i)._strand == (*j)._strand) { assert((*i)._start < (*j)._start); (*i)._end = max((*i)._end, (*j)._end); _outBedLines.erase(j); } } } } } // do a little postprocessing on the lifted intervals to make sure // they are bed compliant void Liftover::cleanResults() { if (_outBedVersion > 6) { BedList::iterator i; BedList::iterator j; for (i = _outBedLines.begin(); i != _outBedLines.end(); i = j) { j = i; ++j; if (_bedLine._thickStart != 0 || _bedLine._thickEnd != 0) { i->_thickStart = i->_start; i->_thickEnd = i->_end; if (_bedLine._thickStart != _bedLine._start || _bedLine._thickEnd != _bedLine._end) { cerr << "Input BED line " << _lineNumber << " warning: " << "thickStart different from chromStart or thickEnd " << "different from chromEnd not supported. Assuming they" << " are the same." << endl; } } else { assert(i->_thickStart == 0 && i->_thickEnd == 0); } if (_outBedVersion > 9) { if (i->_blocks.size() > 0) { hal_index_t startDelta = i->_blocks[0]._start; assert(startDelta >= 0); if (startDelta > 0) { vector<BedBlock>::iterator j; vector<BedBlock>::iterator k; for (j = i->_blocks.begin(); j != i->_blocks.end(); ++j) { j->_start -= startDelta; k = j; ++k; assert(k == i->_blocks.end() || k->_start >= (j->_start + j->_length)); } i->_start += startDelta; } assert(i->_blocks[0]._start == 0); hal_index_t endDelta = i->_end - (i->_blocks.back()._start + i->_blocks.back()._length + i->_start); assert(endDelta >= 0); i->_end -= endDelta; assert(i->_blocks.back()._start + i->_blocks.back()._length + i->_start == i->_end); } else { // if we're in bed 12, we don't want any empty regions in the // output _outBedLines.erase(i); } } } } } <|endoftext|>
<commit_before>// This file is part of MLDB. Copyright 2015 Datacratic. All rights reserved. /* glz_classifier_generator.cc Jeremy Barnes, 15 March 2006 Copyright (c) 2006 Jeremy Barnes All rights reserved. Generator for glz_classifiers. */ #include "glz_classifier_generator.h" #include "mldb/ml/jml/registry.h" #include <boost/timer.hpp> #include <boost/progress.hpp> #include "training_index.h" #include "weighted_training.h" #include "mldb/jml/utils/smart_ptr_utils.h" #include "mldb/ml/algebra/matrix_ops.h" #include "mldb/ml/algebra/lapack.h" #include "mldb/ml/algebra/least_squares.h" #include "mldb/arch/timers.h" #include "mldb/base/parallel.h" using namespace std; namespace ML { /*****************************************************************************/ /* GLZ_CLASSIFIER_GENERATOR */ /*****************************************************************************/ GLZ_Classifier_Generator:: GLZ_Classifier_Generator() { defaults(); } GLZ_Classifier_Generator::~GLZ_Classifier_Generator() { } void GLZ_Classifier_Generator:: configure(const Configuration & config) { Classifier_Generator::configure(config); config.find(add_bias, "add_bias"); config.find(do_decode, "decode"); config.find(link_function, "link_function"); config.find(normalize, "normalize"); config.find(condition, "condition"); config.find(regularization, "regularization"); config.find(regularization_factor, "regularization_factor"); config.find(max_regularization_iteration, "max_regularization_iteration"); config.find(regularization_epsilon, "regularization_epsilon"); config.find(feature_proportion, "feature_proportion"); } void GLZ_Classifier_Generator:: defaults() { Classifier_Generator::defaults(); link_function = LOGIT; add_bias = true; do_decode = true; normalize = true; condition = false; regularization = Regularization_l2; regularization_factor = 1e-5; max_regularization_iteration = 20; regularization_epsilon = 1e-4; feature_proportion = 1.0; } Config_Options GLZ_Classifier_Generator:: options() const { Config_Options result = Classifier_Generator::options(); result .add("add_bias", add_bias, "add a constant bias term to the classifier?") .add("decode", do_decode, "run the decoder (link function) after classification?") .add("link_function", link_function, "which link function to use for the output function") .add("regularization", regularization, "regularization factor to use. L1 is slower.") .add("regularization_factor", regularization_factor, "-1 to infinite", "regularization factor to use. Auto-determined if negative. Auto-determined is slower.") .add("max_regularization_iteration", max_regularization_iteration, "1 to infinite", "Maximum number of iterations in regularization. Not all regularizations will need to iterate.") .add("regularization_epsilon", regularization_epsilon, "positive number", "Epsilon to use when looking for convergence in regularization. Smaller numbers will mean more iterations.") .add("normalize", normalize, "normalize features to have zero mean and unit variance for greater numeric stability (but slower training)") .add("condition", condition, "condition features to have no correlation for greater numeric stability (but much slower training)") .add("feature_proportion", feature_proportion, "0 to 1", "use only a (random) portion of available features when training classifier"); return result; } void GLZ_Classifier_Generator:: init(std::shared_ptr<const Feature_Space> fs, Feature predicted) { Classifier_Generator::init(fs, predicted); model = GLZ_Classifier(fs, predicted); } std::shared_ptr<Classifier_Impl> GLZ_Classifier_Generator:: generate(Thread_Context & thread_context, const Training_Data & training_data, const boost::multi_array<float, 2> & weights, const std::vector<Feature> & features, float & Z, int) const { boost::timer timer; Feature predicted = model.predicted(); GLZ_Classifier current(model); train_weighted(thread_context, training_data, weights, features, current); if (verbosity > 2) { cerr << endl << "Learned GLZ function: " << endl; cerr << "link: " << current.link << endl; int nl = current.feature_space()->info(predicted).value_count(); cerr << "feature "; if (nl == 2 && false) cerr << " label1"; else for (unsigned l = 0; l < nl; ++l) cerr << format(" label%-4d", l); cerr << endl; for (unsigned i = 0; i < current.features.size() + current.add_bias; ++i) { if (i == current.features.size()) { cerr << format("%-40s", "BIAS"); } else { string feat = current.feature_space() ->print(current.features[i].feature); cerr << format("%-36s", feat.c_str()); switch (current.features[i].type) { case GLZ_Classifier::Feature_Spec::VALUE: cerr << " VAL"; break; case GLZ_Classifier::Feature_Spec::VALUE_IF_PRESENT: cerr << " VIP"; break; case GLZ_Classifier::Feature_Spec::PRESENCE: cerr << " PRS"; break; case GLZ_Classifier::Feature_Spec::VALUE_EQUALS: cerr << " " << current.feature_space() ->print(current.features[i].feature, current.features[i].value); break; default: throw Exception("invalid type"); } } if (nl == 2 && false) cerr << format("%13f", current.weights[1][i]); else for (unsigned l = 0; l < nl; ++l) cerr << format("%13f", current.weights[l][i]); cerr << endl; } cerr << endl; } Z = 0.0; return make_sp(current.make_copy()); } float GLZ_Classifier_Generator:: train_weighted(Thread_Context & thread_context, const Training_Data & data, const boost::multi_array<float, 2> & weights, const std::vector<Feature> & unfiltered, GLZ_Classifier & result) const { /* Algorithm: 1. Convert training data to a dense format; 2. Train on each column */ result = model; result.features.clear(); result.add_bias = add_bias; result.link = (do_decode ? link_function : LINEAR); Feature predicted = model.predicted(); for (unsigned i = 0; i < unfiltered.size(); ++i) { if (unfiltered[i] == model.predicted()) continue; // don't use the label to predict itself // If we don't want to use all features then take a random subset if (feature_proportion < 1.0 && thread_context.random01() > feature_proportion) continue; auto info = data.feature_space()->info(unfiltered[i]); GLZ_Classifier::Feature_Spec spec(unfiltered[i]); if (info.categorical()) { // One for each category. Missing takes care of itself as it // means that we just have none set. for (auto & v: data.index().freqs(unfiltered[i])) { spec.value = v.first; spec.type = GLZ_Classifier::Feature_Spec::VALUE_EQUALS; spec.category = data.feature_space() ->print(unfiltered[i], v.first); result.features.push_back(spec); } } else { // Can't use a feature that has multiple occurrences if (!data.index().only_one(unfiltered[i])) continue; if (data.index().exactly_one(unfiltered[i])) { // Feature that's always there but constant has no information if (data.index().constant(unfiltered[i])) continue; result.features.push_back(spec); } else { if (!data.index().constant(unfiltered[i])) { spec.type = GLZ_Classifier::Feature_Spec::VALUE_IF_PRESENT; result.features.push_back(spec); } spec.type = GLZ_Classifier::Feature_Spec::PRESENCE; result.features.push_back(spec); } } } size_t nl = result.label_count(); // Number of labels bool regression_problem = (nl == 1); size_t nx = data.example_count(); // Number of examples size_t nv = result.features.size(); // Number of variables if (add_bias) ++nv; // This contains a list of non-zero weighted examples std::vector<int> indexes; indexes.reserve(nx); distribution<double> total_weight(nx); for (unsigned x = 0; x < nx; ++x) { for (unsigned l = 0; l < weights.shape()[1]; ++l) total_weight[x] += weights[x][l]; if (total_weight[x] > 0.0) indexes.push_back(x); } size_t nx2 = indexes.size(); //cerr << "nx = " << nx << " nv = " << nv << " nx * nv = " << nx * nv // << endl; Timer t; /* Get the labels by example. */ const vector<Label> & labels = data.index().labels(predicted); // Use double precision, we have enough memory (<= 1GB) // NOTE: always on due to issues with convergence boost::multi_array<double, 2> dense_data(boost::extents[nv][nx2]); // training data, dense distribution<double> model(nx2, 0.0); // to initialise weights, correct vector<distribution<double> > w(nl, model); // weights for each label vector<distribution<double> > correct(nl, model); // correct values cerr << "setup: " << t.elapsed() << endl; t.restart(); auto onIndex = [&] (int index) { int x = indexes[index]; distribution<float> decoded = result.decode(data[x]); if (add_bias) decoded.push_back(1.0); //cerr << "x = " << x << " decoded = " << decoded << endl; /* Record the values of the variables. */ assert(decoded.size() == nv); for (unsigned v = 0; v < decoded.size(); ++v) { if (!isfinite(decoded[v])) decoded[v] = 0.0; dense_data[v][index] = decoded[v]; } /* Record the correct label. */ if (regression_problem) { correct[0][index] = labels[x].value(); w[0][index] = weights[x][0]; } else if (nl == 2 && weights.shape()[1] == 1) { correct[0][index] = (double)(labels[x] == 0); correct[1][index] = (double)(labels[x] == 1); w[0][index] = weights[x][0]; } else { for (unsigned l = 0; l < nl; ++l) { correct[l][index] = (double)(labels[x] == l); w[l][index] = weights[x][l]; } } }; Datacratic::parallelMap(0, indexes.size(), onIndex); cerr << "marshalling: " << t.elapsed() << endl; t.restart(); distribution<double> means(nv), stds(nv, 1.0); /* Scale */ for (unsigned v = 0; v < nv && normalize; ++v) { double total = 0.0; for (unsigned x = 0; x < nx2; ++x) total += dense_data[v][x]; double mean = total / nx2; double std_total = 0.0; for (unsigned x = 0; x < nx2; ++x) std_total += (dense_data[v][x] - mean) * (dense_data[v][x] - mean); double std = sqrt(std_total / nx2); if (std == 0.0 && mean == 1.0) { // bias column std = 1.0; mean = 0.0; } else if (std == 0.0) std = 1.0; double std_recip = 1.0 / std; for (unsigned x = 0; x < nx2; ++x) dense_data[v][x] = (dense_data[v][x] - mean) * std_recip; means[v] = mean; stds[v] = std; } cerr << "normalization: " << t.elapsed() << endl; t.restart(); int nlr = nl; if (nl == 2) nlr = 1; /* Perform a GLZ for each label. */ result.weights.clear(); double extra_bias = 0.0; for (unsigned l = 0; l < nlr; ++l) { //cerr << "l = " << l << " correct[l] = " << correct[l] // << " w = " << w[l] << endl; distribution<double> trained = perform_irls(correct[l], dense_data, w[l], link_function, stds, regularization, regularization_factor, max_regularization_iteration, regularization_epsilon, condition); cerr << "trained before de-normalization: " << endl; for (unsigned v = 0; v < nv && normalize; ++v) { cerr << "v: " << v << " , " << trained[v] << endl; } trained /= stds; cerr << "trained post de-normalization: " << endl; for (unsigned v = 0; v < nv && normalize; ++v) { cerr << "v: " << v << " , " << trained[v] << endl; } extra_bias = - (trained.dotprod(means)); if (extra_bias != 0.0) { if (!add_bias) throw Exception("extra bias but nowhere to put it"); trained.back() += extra_bias; } //cerr << "l = " << l <<" param = " << param << endl; result.weights.push_back(trained.cast<float>()); } cerr << "irls: " << t.elapsed() << endl; t.restart(); if (nl == 2) { // weights for second label are the mirror of those of the first // label result.weights.push_back(-1.0F * result.weights.front()); } //cerr << "glz_classifier: irls time " << t.elapsed() << "s" << endl; return 0.0; } /*****************************************************************************/ /* REGISTRATION */ /*****************************************************************************/ namespace { Register_Factory<Classifier_Generator, GLZ_Classifier_Generator> GLZ_CLASSIFIER_REGISTER("glz"); } // file scope } // namespace ML <commit_msg>Update glz_classifier_generator.cc<commit_after>// This file is part of MLDB. Copyright 2015 Datacratic. All rights reserved. /* glz_classifier_generator.cc Jeremy Barnes, 15 March 2006 Copyright (c) 2006 Jeremy Barnes All rights reserved. Generator for glz_classifiers. */ #include "glz_classifier_generator.h" #include "mldb/ml/jml/registry.h" #include <boost/timer.hpp> #include <boost/progress.hpp> #include "training_index.h" #include "weighted_training.h" #include "mldb/jml/utils/smart_ptr_utils.h" #include "mldb/ml/algebra/matrix_ops.h" #include "mldb/ml/algebra/lapack.h" #include "mldb/ml/algebra/least_squares.h" #include "mldb/arch/timers.h" #include "mldb/base/parallel.h" using namespace std; namespace ML { /*****************************************************************************/ /* GLZ_CLASSIFIER_GENERATOR */ /*****************************************************************************/ GLZ_Classifier_Generator:: GLZ_Classifier_Generator() { defaults(); } GLZ_Classifier_Generator::~GLZ_Classifier_Generator() { } void GLZ_Classifier_Generator:: configure(const Configuration & config) { Classifier_Generator::configure(config); config.find(add_bias, "add_bias"); config.find(do_decode, "decode"); config.find(link_function, "link_function"); config.find(normalize, "normalize"); config.find(condition, "condition"); config.find(regularization, "regularization"); config.find(regularization_factor, "regularization_factor"); config.find(max_regularization_iteration, "max_regularization_iteration"); config.find(regularization_epsilon, "regularization_epsilon"); config.find(feature_proportion, "feature_proportion"); } void GLZ_Classifier_Generator:: defaults() { Classifier_Generator::defaults(); link_function = LOGIT; add_bias = true; do_decode = true; normalize = true; condition = false; regularization = Regularization_l2; regularization_factor = 1e-5; max_regularization_iteration = 20; regularization_epsilon = 1e-4; feature_proportion = 1.0; } Config_Options GLZ_Classifier_Generator:: options() const { Config_Options result = Classifier_Generator::options(); result .add("add_bias", add_bias, "add a constant bias term to the classifier?") .add("decode", do_decode, "run the decoder (link function) after classification?") .add("link_function", link_function, "which link function to use for the output function") .add("regularization", regularization, "regularization factor to use. L1 is slower.") .add("regularization_factor", regularization_factor, "-1 to infinite", "regularization factor to use. Auto-determined if negative. Auto-determined is slower.") .add("max_regularization_iteration", max_regularization_iteration, "1 to infinite", "Maximum number of iterations in regularization. Not all regularizations will need to iterate.") .add("regularization_epsilon", regularization_epsilon, "positive number", "Epsilon to use when looking for convergence in regularization. Smaller numbers will mean more iterations.") .add("normalize", normalize, "normalize features to have zero mean and unit variance for greater numeric stability (but slower training)") .add("condition", condition, "condition features to have no correlation for greater numeric stability (but much slower training)") .add("feature_proportion", feature_proportion, "0 to 1", "use only a (random) portion of available features when training classifier"); return result; } void GLZ_Classifier_Generator:: init(std::shared_ptr<const Feature_Space> fs, Feature predicted) { Classifier_Generator::init(fs, predicted); model = GLZ_Classifier(fs, predicted); } std::shared_ptr<Classifier_Impl> GLZ_Classifier_Generator:: generate(Thread_Context & thread_context, const Training_Data & training_data, const boost::multi_array<float, 2> & weights, const std::vector<Feature> & features, float & Z, int) const { boost::timer timer; Feature predicted = model.predicted(); GLZ_Classifier current(model); train_weighted(thread_context, training_data, weights, features, current); if (verbosity > 2) { cerr << endl << "Learned GLZ function: " << endl; cerr << "link: " << current.link << endl; int nl = current.feature_space()->info(predicted).value_count(); cerr << "feature "; if (nl == 2 && false) cerr << " label1"; else for (unsigned l = 0; l < nl; ++l) cerr << format(" label%-4d", l); cerr << endl; for (unsigned i = 0; i < current.features.size() + current.add_bias; ++i) { if (i == current.features.size()) { cerr << format("%-40s", "BIAS"); } else { string feat = current.feature_space() ->print(current.features[i].feature); cerr << format("%-36s", feat.c_str()); switch (current.features[i].type) { case GLZ_Classifier::Feature_Spec::VALUE: cerr << " VAL"; break; case GLZ_Classifier::Feature_Spec::VALUE_IF_PRESENT: cerr << " VIP"; break; case GLZ_Classifier::Feature_Spec::PRESENCE: cerr << " PRS"; break; case GLZ_Classifier::Feature_Spec::VALUE_EQUALS: cerr << " " << current.feature_space() ->print(current.features[i].feature, current.features[i].value); break; default: throw Exception("invalid type"); } } if (nl == 2 && false) cerr << format("%13f", current.weights[1][i]); else for (unsigned l = 0; l < nl; ++l) cerr << format("%13f", current.weights[l][i]); cerr << endl; } cerr << endl; } Z = 0.0; return make_sp(current.make_copy()); } float GLZ_Classifier_Generator:: train_weighted(Thread_Context & thread_context, const Training_Data & data, const boost::multi_array<float, 2> & weights, const std::vector<Feature> & unfiltered, GLZ_Classifier & result) const { /* Algorithm: 1. Convert training data to a dense format; 2. Train on each column */ result = model; result.features.clear(); result.add_bias = add_bias; result.link = (do_decode ? link_function : LINEAR); Feature predicted = model.predicted(); for (unsigned i = 0; i < unfiltered.size(); ++i) { if (unfiltered[i] == model.predicted()) continue; // don't use the label to predict itself // If we don't want to use all features then take a random subset if (feature_proportion < 1.0 && thread_context.random01() > feature_proportion) continue; auto info = data.feature_space()->info(unfiltered[i]); GLZ_Classifier::Feature_Spec spec(unfiltered[i]); if (info.categorical()) { // One for each category. Missing takes care of itself as it // means that we just have none set. for (auto & v: data.index().freqs(unfiltered[i])) { spec.value = v.first; spec.type = GLZ_Classifier::Feature_Spec::VALUE_EQUALS; spec.category = data.feature_space() ->print(unfiltered[i], v.first); result.features.push_back(spec); } } else { // Can't use a feature that has multiple occurrences if (!data.index().only_one(unfiltered[i])) continue; if (data.index().exactly_one(unfiltered[i])) { // Feature that's always there but constant has no information if (data.index().constant(unfiltered[i])) continue; result.features.push_back(spec); } else { if (!data.index().constant(unfiltered[i])) { spec.type = GLZ_Classifier::Feature_Spec::VALUE_IF_PRESENT; result.features.push_back(spec); } spec.type = GLZ_Classifier::Feature_Spec::PRESENCE; result.features.push_back(spec); } } } size_t nl = result.label_count(); // Number of labels bool regression_problem = (nl == 1); size_t nx = data.example_count(); // Number of examples size_t nv = result.features.size(); // Number of variables if (add_bias) ++nv; // This contains a list of non-zero weighted examples std::vector<int> indexes; indexes.reserve(nx); distribution<double> total_weight(nx); for (unsigned x = 0; x < nx; ++x) { for (unsigned l = 0; l < weights.shape()[1]; ++l) total_weight[x] += weights[x][l]; if (total_weight[x] > 0.0) indexes.push_back(x); } size_t nx2 = indexes.size(); //cerr << "nx = " << nx << " nv = " << nv << " nx * nv = " << nx * nv // << endl; Timer t; /* Get the labels by example. */ const vector<Label> & labels = data.index().labels(predicted); // Use double precision, we have enough memory (<= 1GB) // NOTE: always on due to issues with convergence boost::multi_array<double, 2> dense_data(boost::extents[nv][nx2]); // training data, dense distribution<double> model(nx2, 0.0); // to initialise weights, correct vector<distribution<double> > w(nl, model); // weights for each label vector<distribution<double> > correct(nl, model); // correct values cerr << "setup: " << t.elapsed() << endl; t.restart(); auto onIndex = [&] (int index) { int x = indexes[index]; distribution<float> decoded = result.decode(data[x]); if (add_bias) decoded.push_back(1.0); //cerr << "x = " << x << " decoded = " << decoded << endl; /* Record the values of the variables. */ assert(decoded.size() == nv); for (unsigned v = 0; v < decoded.size(); ++v) { if (!isfinite(decoded[v])) decoded[v] = 0.0; dense_data[v][index] = decoded[v]; } /* Record the correct label. */ if (regression_problem) { correct[0][index] = labels[x].value(); w[0][index] = weights[x][0]; } else if (nl == 2 && weights.shape()[1] == 1) { correct[0][index] = (double)(labels[x] == 0); correct[1][index] = (double)(labels[x] == 1); w[0][index] = weights[x][0]; } else { for (unsigned l = 0; l < nl; ++l) { correct[l][index] = (double)(labels[x] == l); w[l][index] = weights[x][l]; } } }; Datacratic::parallelMap(0, indexes.size(), onIndex); cerr << "marshalling: " << t.elapsed() << endl; t.restart(); distribution<double> means(nv), stds(nv, 1.0); /* Scale */ for (unsigned v = 0; v < nv && normalize; ++v) { double total = 0.0; for (unsigned x = 0; x < nx2; ++x) total += dense_data[v][x]; double mean = total / nx2; double std_total = 0.0; for (unsigned x = 0; x < nx2; ++x) std_total += (dense_data[v][x] - mean) * (dense_data[v][x] - mean); double std = sqrt(std_total / nx2); if (std == 0.0 && mean == 1.0) { // bias column std = 1.0; mean = 0.0; } else if (std == 0.0) std = 1.0; double std_recip = 1.0 / std; for (unsigned x = 0; x < nx2; ++x) dense_data[v][x] = (dense_data[v][x] - mean) * std_recip; means[v] = mean; stds[v] = std; } cerr << "normalization: " << t.elapsed() << endl; t.restart(); int nlr = nl; if (nl == 2) nlr = 1; /* Perform a GLZ for each label. */ result.weights.clear(); double extra_bias = 0.0; for (unsigned l = 0; l < nlr; ++l) { //cerr << "l = " << l << " correct[l] = " << correct[l] // << " w = " << w[l] << endl; distribution<double> trained = perform_irls(correct[l], dense_data, w[l], link_function, stds, regularization, regularization_factor, max_regularization_iteration, regularization_epsilon, condition); trained /= stds; extra_bias = - (trained.dotprod(means)); if (extra_bias != 0.0) { if (!add_bias) throw Exception("extra bias but nowhere to put it"); trained.back() += extra_bias; } //cerr << "l = " << l <<" param = " << param << endl; result.weights.push_back(trained.cast<float>()); } cerr << "irls: " << t.elapsed() << endl; t.restart(); if (nl == 2) { // weights for second label are the mirror of those of the first // label result.weights.push_back(-1.0F * result.weights.front()); } //cerr << "glz_classifier: irls time " << t.elapsed() << "s" << endl; return 0.0; } /*****************************************************************************/ /* REGISTRATION */ /*****************************************************************************/ namespace { Register_Factory<Classifier_Generator, GLZ_Classifier_Generator> GLZ_CLASSIFIER_REGISTER("glz"); } // file scope } // namespace ML <|endoftext|>
<commit_before>/* * This File is part of Davix, The IO library for HTTP based protocols * Copyright (C) 2013 Adrien Devresse <adrien.devresse@cern.ch>, CERN * * 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 <davix_internal.hpp> #include <davix.hpp> #include <tools/davix_tool_params.hpp> #include <tools/davix_tool_util.hpp> #include <tools/davix_taskqueue.hpp> #include <tools/davix_op.hpp> #include <tools/davix_thread_pool.hpp> #include <utils/davix_logger_internal.hpp> #include <cstdio> #include <fstream> // @author : Devresse Adrien // main file for davix low level cmd line tool using namespace Davix; using namespace std; #define READ_BLOCK_SIZE 4096 const std::string scope_main = "Davix::Tools::davix-rm"; const std::string openTag_req = "<Delete>"; const std::string closeTag_req = "</Delete>"; const std::string openTags_entry = "<Object><Key>"; const std::string closeTags_entry = "</Key></Object>"; std::string get_base_rm_options(){ return " Delete Options:\n" "\t-r: Remove contents recursively, also works on S3 objects for storage systems that supports multi-objects deletion\n"; } static std::string help_msg(const std::string & cmd_path){ std::string help_msg = fmt::format("Usage : {} ", cmd_path); help_msg += Tool::get_base_description_options(); help_msg += Tool::get_common_options(); help_msg += get_base_rm_options(); return help_msg; } static int populateTaskQueue(Context& c, const Tool::OptParams & opts, std::string uri, DavixTaskQueue* tq, DavixError** err ){ DAVIX_DIR* fd = NULL; DavPosix pos(&c); DavixError* tmp_err=NULL; struct stat st; struct dirent* d; int counter = 0; int entry_counter = 0; std::string protocol, host; std::string buffer(openTag_req); if( (fd = pos.opendirpp(&opts.params, opts.vec_arg[0], &tmp_err)) == NULL){ DavixError::propagateError(err, tmp_err); return -1; } if(opts.vec_arg[0].compare(2,1,"s") == 0){ protocol = "s3s://"; } else{ protocol = "s3://"; } host = protocol + Uri(uri).getHost(); while( (d = pos.readdirpp(fd, &st, &tmp_err)) != NULL ){ // for every entry //TODO: unless user has turned on rr mode, skip entries that end with a '/'? //that way we can provide a way to just delete files inside the directory and not the other directories // format to xml and push to buffer string, for every n entries, create a DeleteOp(PostRequest) std::string entry(d->d_name); // for each entry, <Object><Key>entry</Key></Object> buffer += openTags_entry + entry + closeTags_entry; counter++; entry_counter++; // although the S3 API supports up to 1000 keys per request, in practice this will most likely results in a 504 gateway timeout if(counter == opts.s3_delete_per_request){ // default is set to 20, just to be safe buffer += closeTag_req; // push op to task queue DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CORE, "Adding item to work queue, target is {}.", host); DeleteOp* op = new DeleteOp(opts, host, c, buffer); tq->pushOp(op); counter = 0; buffer.clear(); buffer = openTag_req; } if(!opts.debug) Tool::batchTransferMonitor(uri, "Multi-objects delete ", entry_counter, 0); } // check if there is still anything in buffer for remainder entries if(!buffer.empty()){ buffer += closeTag_req; // push op to task queue DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CORE, "Adding item to work queue, target is {}.", host); DeleteOp* op = new DeleteOp(opts, host, c, buffer); tq->pushOp(op); } pos.closedirpp(fd, NULL); return 0; } static int preDeleteCheck(Tool::OptParams & opts, DavixError** err ) { Context c; configureContext(c, opts); DavPosix f(&c); struct stat st; DavixError* tmp_err=NULL; // see if the requested url actually points to a directory or not int r = f.stat(&opts.params, opts.vec_arg[0], &st, &tmp_err); if (tmp_err) { DavixError::propagateError(err, tmp_err); return -1; } if (r && !(st.st_mode & S_IFDIR)){ DavixError::setupError(&tmp_err, scope_main, StatusCode::IsNotADirectory, "Failed to delete, target is not a directory."); DavixError::propagateError(err, tmp_err); return -1; } DavixTaskQueue tq; // create threadpool instance DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CORE, "Creating threadpool"); DavixThreadPool tp(&tq); // TODO two modes, one to delete "recursively, one for depth of 1. can probbaly do it in readdirpp // set listing mode to SemiHierarchical, we want to get every object under the same prefix in one go opts.params.setS3ListingMode(S3ListingMode::SemiHierarchical); // unfortunately s3 defaults max-keys to 1000 and doesn't provide a way to disable the cap, set to large number opts.params.setS3MaxKey(999999999); std::string url(opts.vec_arg[0]); if (url[url.size()-1] != '/') url += '/'; populateTaskQueue(c, opts, url, &tq, &tmp_err); // if task queue is empty, then all work is done, stop workers. Otherwise wait. while(!tq.isEmpty()){ sleep(2); } tp.shutdown(); Tool::flushFinalLineShell(STDOUT_FILENO); if(tmp_err){ DavixError::propagateError(err, tmp_err); return -1; } return 0; } int main(int argc, char** argv){ int retcode=-1; Tool::OptParams opts; DavixError* tmp_err=NULL; opts.help_msg = help_msg(argv[0]); if( (retcode= Tool::parse_davix_rm_options(argc, argv, opts, &tmp_err)) ==0){ if( (retcode = Tool::configureAuth(opts)) == 0){ if (opts.vec_arg[0].compare(0,4,"http") ==0){ opts.params.setProtocol(RequestProtocol::Http); }else if( opts.vec_arg[0].compare(0,2,"s3") ==0){ opts.params.setProtocol(RequestProtocol::AwsS3); }else if ( opts.vec_arg[0].compare(0, 3,"dav") ==0){ opts.params.setProtocol(RequestProtocol::Webdav); } // only s3 needs special treatment, WebDAV delete on collection already works if((opts.params.getProtocol() == RequestProtocol::AwsS3) && (opts.params.getRecursiveMode())){ preDeleteCheck(opts, &tmp_err); } else{ Context c; configureContext(c, opts); DavFile f(c,opts.vec_arg[0]); f.deletion(&opts.params, &tmp_err); } } } Tool::errorPrint(&tmp_err); return retcode; } <commit_msg>Add -n switch in davix-rm that allows users to specify number of keys in a S3 multi-objects delete request<commit_after>/* * This File is part of Davix, The IO library for HTTP based protocols * Copyright (C) 2013 Adrien Devresse <adrien.devresse@cern.ch>, CERN * * 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 <davix_internal.hpp> #include <davix.hpp> #include <tools/davix_tool_params.hpp> #include <tools/davix_tool_util.hpp> #include <tools/davix_taskqueue.hpp> #include <tools/davix_op.hpp> #include <tools/davix_thread_pool.hpp> #include <utils/davix_logger_internal.hpp> #include <cstdio> #include <fstream> // @author : Devresse Adrien // main file for davix low level cmd line tool using namespace Davix; using namespace std; #define READ_BLOCK_SIZE 4096 const std::string scope_main = "Davix::Tools::davix-rm"; const std::string openTag_req = "<Delete>"; const std::string closeTag_req = "</Delete>"; const std::string openTags_entry = "<Object><Key>"; const std::string closeTags_entry = "</Key></Object>"; std::string get_base_rm_options(){ return " Delete Options:\n" "\t-r: Remove contents recursively, also works on S3 objects for storage systems that supports multi-objects deletion\n" "\t-n: NUMBER_OF_KEYS Number of object keys to include in each delete request, S3 supports up to 1000, but request will likely timeout. Default: 20\n"; } static std::string help_msg(const std::string & cmd_path){ std::string help_msg = fmt::format("Usage : {} ", cmd_path); help_msg += Tool::get_base_description_options(); help_msg += Tool::get_common_options(); help_msg += get_base_rm_options(); return help_msg; } static int populateTaskQueue(Context& c, const Tool::OptParams & opts, std::string uri, DavixTaskQueue* tq, DavixError** err ){ DAVIX_DIR* fd = NULL; DavPosix pos(&c); DavixError* tmp_err=NULL; struct stat st; struct dirent* d; int counter = 0; int entry_counter = 0; std::string protocol, host; std::string buffer(openTag_req); if( (fd = pos.opendirpp(&opts.params, opts.vec_arg[0], &tmp_err)) == NULL){ DavixError::propagateError(err, tmp_err); return -1; } if(opts.vec_arg[0].compare(2,1,"s") == 0){ protocol = "s3s://"; } else{ protocol = "s3://"; } host = protocol + Uri(uri).getHost(); while( (d = pos.readdirpp(fd, &st, &tmp_err)) != NULL ){ // for every entry //TODO: unless user has turned on rr mode, skip entries that end with a '/'? //that way we can provide a way to just delete files inside the directory and not the other directories // format to xml and push to buffer string, for every n entries, create a DeleteOp(PostRequest) std::string entry(d->d_name); // for each entry, <Object><Key>entry</Key></Object> buffer += openTags_entry + entry + closeTags_entry; counter++; entry_counter++; // although the S3 API supports up to 1000 keys per request, in practice this will most likely results in a 504 gateway timeout if(counter == opts.s3_delete_per_request){ // default is set to 20, just to be safe buffer += closeTag_req; // push op to task queue DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CORE, "Adding item to work queue, target is {}.", host); DeleteOp* op = new DeleteOp(opts, host, c, buffer); tq->pushOp(op); counter = 0; buffer.clear(); buffer = openTag_req; } if(!opts.debug) Tool::batchTransferMonitor(uri, "Multi-objects delete ", entry_counter, 0); } // check if there is still anything in buffer for remainder entries if(!buffer.empty()){ buffer += closeTag_req; // push op to task queue DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CORE, "Adding item to work queue, target is {}.", host); DeleteOp* op = new DeleteOp(opts, host, c, buffer); tq->pushOp(op); } pos.closedirpp(fd, NULL); return 0; } static int preDeleteCheck(Tool::OptParams & opts, DavixError** err ) { Context c; configureContext(c, opts); DavPosix f(&c); struct stat st; DavixError* tmp_err=NULL; // see if the requested url actually points to a directory or not int r = f.stat(&opts.params, opts.vec_arg[0], &st, &tmp_err); if (tmp_err) { DavixError::propagateError(err, tmp_err); return -1; } if (r && !(st.st_mode & S_IFDIR)){ DavixError::setupError(&tmp_err, scope_main, StatusCode::IsNotADirectory, "Failed to delete, target is not a directory."); DavixError::propagateError(err, tmp_err); return -1; } DavixTaskQueue tq; // create threadpool instance DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CORE, "Creating threadpool"); DavixThreadPool tp(&tq); // TODO two modes, one to delete "recursively, one for depth of 1. can probbaly do it in readdirpp // set listing mode to SemiHierarchical, we want to get every object under the same prefix in one go opts.params.setS3ListingMode(S3ListingMode::SemiHierarchical); // unfortunately s3 defaults max-keys to 1000 and doesn't provide a way to disable the cap, set to large number opts.params.setS3MaxKey(999999999); std::string url(opts.vec_arg[0]); if (url[url.size()-1] != '/') url += '/'; populateTaskQueue(c, opts, url, &tq, &tmp_err); // if task queue is empty, then all work is done, stop workers. Otherwise wait. while(!tq.isEmpty()){ sleep(2); } tp.shutdown(); Tool::flushFinalLineShell(STDOUT_FILENO); if(tmp_err){ DavixError::propagateError(err, tmp_err); return -1; } return 0; } int main(int argc, char** argv){ int retcode=-1; Tool::OptParams opts; DavixError* tmp_err=NULL; opts.help_msg = help_msg(argv[0]); if( (retcode= Tool::parse_davix_rm_options(argc, argv, opts, &tmp_err)) ==0){ if( (retcode = Tool::configureAuth(opts)) == 0){ if (opts.vec_arg[0].compare(0,4,"http") ==0){ opts.params.setProtocol(RequestProtocol::Http); }else if( opts.vec_arg[0].compare(0,2,"s3") ==0){ opts.params.setProtocol(RequestProtocol::AwsS3); }else if ( opts.vec_arg[0].compare(0, 3,"dav") ==0){ opts.params.setProtocol(RequestProtocol::Webdav); } // only s3 needs special treatment, WebDAV delete on collection already works if((opts.params.getProtocol() == RequestProtocol::AwsS3) && (opts.params.getRecursiveMode())){ preDeleteCheck(opts, &tmp_err); } else{ Context c; configureContext(c, opts); DavFile f(c,opts.vec_arg[0]); f.deletion(&opts.params, &tmp_err); } } } Tool::errorPrint(&tmp_err); return retcode; } <|endoftext|>
<commit_before>#ifndef PRESETEDITOR_HPP #define PRESETEDITOR_HPP // stdlib #include <string> #include <functional> // Libslic3r #include "libslic3r.h" #include "ConfigBase.hpp" #include "Config.hpp" // GUI #include "misc_ui.hpp" #include "Preset.hpp" // Wx #include <wx/treectrl.h> #include <wx/imaglist.h> #include <wx/panel.h> #include <wx/scrolwin.h> using namespace std::string_literals; namespace Slic3r { namespace GUI { class PresetPage; class PresetEditor : public wxPanel { public: /// Member function to retrieve a list of options /// that this preset governs. Subclasses should /// call their own static method. virtual t_config_option_keys my_options() = 0; static t_config_option_keys options() { return t_config_option_keys {}; } static t_config_option_keys overridable_options() { return t_config_option_keys {}; }; static t_config_option_keys overriding_options() { return t_config_option_keys {}; }; virtual t_config_option_keys my_overridable_options() = 0; virtual t_config_option_keys my_overriding_options() = 0; wxSizer* sizer() { return _sizer; }; PresetEditor(wxWindow* parent, t_config_option_keys options = {}); PresetEditor() : PresetEditor(nullptr, {}) {}; std::shared_ptr<Preset> current_preset; /// Check if there is a dirty config that is different than the loaded config. bool prompt_unsaved_changes(); void select_preset_by_name(const wxString& name, bool force = false); /// suppress the callback when the tree selection is changed. bool disable_tree_sel_changed_event {false}; void save_preset(); std::function<void ()> on_save_preset {}; std::function<void ()> on_value_change {}; config_ptr config; void reload_config(); void reload_preset(); PresetPage* add_options_page(const wxString& _title, const wxString& _icon = ""); virtual wxString title() = 0; virtual std::string name() = 0; virtual preset_t type() = 0; virtual int typeId() = 0; protected: // Main sizer wxSizer* _sizer {nullptr}; wxString presets; wxImageList* _icons {nullptr}; wxTreeCtrl* _treectrl {nullptr}; wxBitmapButton* _btn_save_preset {nullptr}; wxBitmapButton* _btn_delete_preset {nullptr}; wxChoice* _presets_choice {nullptr}; int _iconcount {-1}; /// Vector of PresetPage pointers; trust wxWidgets RTTI to avoid leaks std::vector<PresetPage*> _pages {}; const unsigned int left_col_width {150}; void _update_tree(); void load_presets(); virtual void _build() = 0; virtual void _update() = 0; virtual void _on_preset_loaded() = 0; void set_tooltips() { this->_btn_save_preset->SetToolTip(wxString(_("Save current ")) + this->title()); this->_btn_delete_preset->SetToolTip(_("Delete this preset.")); } void reload_compatible_printers_widget(); wxSizer* compatible_printers_widget(); /// This method is called: /// - upon first initialization; /// - whenever user selects a preset from the dropdown; /// - whenever select_preset() or select_preset_by_name() are called. void _on_select_preset(bool force = false); /// This method is supposed to be called whenever new values are loaded /// or changed by the user (including when presets are loaded). /// Pushes a callback onto the owning Slic3r app to be processed during /// an idle event. void _on_value_change(std::string opt_key); virtual const std::string LogChannel() = 0; //< Which log these messages should go to. }; class PrintEditor : public PresetEditor { public: PrintEditor(wxWindow* parent, t_config_option_keys options = {}); PrintEditor() : PrintEditor(nullptr, {}) {}; wxString title() override { return _("Print Settings"); } std::string name() override { return "print"s; } t_config_option_keys my_overridable_options() override { return PresetEditor::overridable_options(); }; static t_config_option_keys overridable_options() { return PresetEditor::overridable_options(); }; t_config_option_keys my_overriding_options() override { return PresetEditor::overriding_options(); }; static t_config_option_keys overriding_options() { return PresetEditor::overriding_options(); }; /// Static method to retrieve list of options that this preset governs. static t_config_option_keys options() { return t_config_option_keys { "layer_height"s, "first_layer_height"s, "adaptive_slicing"s, "adaptive_slicing_quality"s, "match_horizontal_surfaces"s, "perimeters"s, "spiral_vase"s, "top_solid_layers"s, "bottom_solid_layers"s, "extra_perimeters"s, "avoid_crossing_perimeters"s, "thin_walls"s, "overhangs"s, "seam_position"s, "external_perimeters_first"s, "fill_density"s, "fill_pattern"s, "top_infill_pattern"s, "bottom_infill_pattern"s, "fill_gaps"s, "infill_every_layers"s, "infill_only_where_needed"s, "solid_infill_every_layers"s, "fill_angle"s, "solid_infill_below_area"s, ""s, "only_retract_when_crossing_perimeters"s, "infill_first"s, "max_print_speed"s, "max_volumetric_speed"s, "perimeter_speed"s, "small_perimeter_speed"s, "external_perimeter_speed"s, "infill_speed"s, ""s, "solid_infill_speed"s, "top_solid_infill_speed"s, "support_material_speed"s, "support_material_interface_speed"s, "bridge_speed"s, "gap_fill_speed"s, "travel_speed"s, "first_layer_speed"s, "perimeter_acceleration"s, "infill_acceleration"s, "bridge_acceleration"s, "first_layer_acceleration"s, "default_acceleration"s, "skirts"s, "skirt_distance"s, "skirt_height"s, "min_skirt_length"s, "brim_connections_width"s, "brim_width"s, "interior_brim_width"s, "support_material"s, "support_material_threshold"s, "support_material_max_layers"s, "support_material_enforce_layers"s, "raft_layers"s, "support_material_pattern"s, "support_material_spacing"s, "support_material_angle"s, ""s, "support_material_interface_layers"s, "support_material_interface_spacing"s, "support_material_contact_distance"s, "support_material_buildplate_only"s, "dont_support_bridges"s, "notes"s, "complete_objects"s, "extruder_clearance_radius"s, "extruder_clearance_height"s, "gcode_comments"s, "output_filename_format"s, "post_process"s, "perimeter_extruder"s, "infill_extruder"s, "solid_infill_extruder"s, "support_material_extruder"s, "support_material_interface_extruder"s, "ooze_prevention"s, "standby_temperature_delta"s, "interface_shells"s, "regions_overlap"s, "extrusion_width"s, "first_layer_extrusion_width"s, "perimeter_extrusion_width"s, ""s, "external_perimeter_extrusion_width"s, "infill_extrusion_width"s, "solid_infill_extrusion_width"s, "top_infill_extrusion_width"s, "support_material_extrusion_width"s, "support_material_interface_extrusion_width"s, "infill_overlap"s, "bridge_flow_ratio"s, "xy_size_compensation"s, "resolution"s, "shortcuts"s, "compatible_printers"s, "print_settings_id"s }; } t_config_option_keys my_options() override { return PrintEditor::options(); } protected: void _update() override; void _build() override; }; class PrinterEditor : public PresetEditor { public: PrinterEditor(wxWindow* parent, t_config_option_keys options = {}); PrinterEditor() : PrinterEditor(nullptr, {}) {}; wxString title() override { return _("Printer Settings"); } std::string name() override { return "printer"s; } static t_config_option_keys overridable_options() { return t_config_option_keys { "pressure_advance"s, "retract_length"s, "retract_lift"s, "retract_speed"s, "retract_restart_extra"s, "retract_before_travel"s, "retract_layer_change"s, "wipe"s }; }; static t_config_option_keys overriding_options() { return PresetEditor::overriding_options(); }; t_config_option_keys my_overridable_options() override { return PrinterEditor::overridable_options(); }; t_config_option_keys my_overriding_options() override { return PrinterEditor::overriding_options(); }; static t_config_option_keys options() { return t_config_option_keys { "bed_shape"s, "z_offset"s, "z_steps_per_mm"s, "has_heatbed"s, "gcode_flavor"s, "use_relative_e_distances"s, "serial_port"s, "serial_speed"s, "host_type"s, "print_host"s, "octoprint_apikey"s, "use_firmware_retraction"s, "pressure_advance"s, "vibration_limit"s, "use_volumetric_e"s, "start_gcode"s, "end_gcode"s, "before_layer_gcode"s, "layer_gcode"s, "toolchange_gcode"s, "between_objects_gcode"s, "nozzle_diameter"s, "extruder_offset"s, "min_layer_height"s, "max_layer_height"s, "retract_length"s, "retract_lift"s, "retract_speed"s, "retract_restart_extra"s, "retract_before_travel"s, "retract_layer_change"s, "wipe"s, "retract_length_toolchange"s, "retract_restart_extra_toolchange"s, "retract_lift_above"s, "retract_lift_below"s, "printer_settings_id"s, "printer_notes"s, "use_set_and_wait_bed"s, "use_set_and_wait_extruder"s }; } t_config_option_keys my_options() override { return PrinterEditor::options(); } protected: void _update() override; void _build() override; const std::string LogChannel() override {return "PrinterEditor"s;} //< Which log these messages should go to. }; class MaterialEditor : public PresetEditor { public: wxString title() override { return _("Material Settings"); } std::string name() override { return "material"s; } preset_t type() override { return preset_t::Material; }; int typeId() override { return static_cast<int>(preset_t::Material); }; MaterialEditor(wxWindow* parent, t_config_option_keys options = {}); MaterialEditor() : MaterialEditor(nullptr, {}) {}; t_config_option_keys my_overridable_options() override { return PresetEditor::overridable_options(); }; t_config_option_keys my_overriding_options() override { return PrinterEditor::overridable_options(); }; static t_config_option_keys overriding_options() { return PrinterEditor::overridable_options(); }; static t_config_option_keys overridable_options() { return PresetEditor::overridable_options(); }; static t_config_option_keys options() { return t_config_option_keys { "filament_colour"s, "filament_diameter"s, "filament_notes"s, "filament_max_volumetric_speed"s, "extrusion_multiplier"s, "filament_density"s, "filament_cost"s, "temperature"s, "first_layer_temperature"s, "bed_temperature"s, "first_layer_bed_temperature"s, "fan_always_on"s, "cooling"s, "compatible_printers"s, "min_fan_speed"s, "max_fan_speed"s, "bridge_fan_speed"s, "disable_fan_first_layers"s, "fan_below_layer_time"s, "slowdown_below_layer_time"s, "min_print_speed"s, "start_filament_gcode"s, "end_filament_gcode"s, "filament_settings_id"s }; } t_config_option_keys my_options() override { return MaterialEditor::options(); } protected: void _update() override; void _build() override; const std::string LogChannel() override {return "MaterialEditor"s;} //< Which log these messages should go to. }; class PresetPage : wxScrolledWindow { public: PresetPage(wxWindow* parent, wxString _title, int _iconID) : wxScrolledWindow(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL), title(_title), iconID(_iconID) { this->vsizer = new wxBoxSizer(wxVERTICAL); this->SetSizer(this->vsizer); this->SetScrollRate(ui_settings->scroll_step(), ui_settings->scroll_step()); } protected: wxSizer* vsizer {nullptr}; wxString title {""}; int iconID {0}; }; }} // namespace Slic3r::GUI #endif // PRESETEDITOR_HPP <commit_msg>Fixed signatures for on_save_preset and on_value_change function objects.<commit_after>#ifndef PRESETEDITOR_HPP #define PRESETEDITOR_HPP // stdlib #include <string> #include <functional> // Libslic3r #include "libslic3r.h" #include "ConfigBase.hpp" #include "Config.hpp" // GUI #include "misc_ui.hpp" #include "Preset.hpp" // Wx #include <wx/treectrl.h> #include <wx/imaglist.h> #include <wx/panel.h> #include <wx/scrolwin.h> using namespace std::string_literals; namespace Slic3r { namespace GUI { class PresetPage; class PresetEditor : public wxPanel { public: /// Member function to retrieve a list of options /// that this preset governs. Subclasses should /// call their own static method. virtual t_config_option_keys my_options() = 0; static t_config_option_keys options() { return t_config_option_keys {}; } static t_config_option_keys overridable_options() { return t_config_option_keys {}; }; static t_config_option_keys overriding_options() { return t_config_option_keys {}; }; virtual t_config_option_keys my_overridable_options() = 0; virtual t_config_option_keys my_overriding_options() = 0; wxSizer* sizer() { return _sizer; }; PresetEditor(wxWindow* parent, t_config_option_keys options = {}); PresetEditor() : PresetEditor(nullptr, {}) {}; std::shared_ptr<Preset> current_preset; /// Check if there is a dirty config that is different than the loaded config. bool prompt_unsaved_changes(); void select_preset_by_name(const wxString& name, bool force = false); /// suppress the callback when the tree selection is changed. bool disable_tree_sel_changed_event {false}; void save_preset(); std::function<void (wxString, preset_t)> on_save_preset {nullptr}; std::function<void (std::string)> on_value_change {nullptr}; config_ptr config; void reload_config(); void reload_preset(); PresetPage* add_options_page(const wxString& _title, const wxString& _icon = ""); virtual wxString title() = 0; virtual std::string name() = 0; virtual preset_t type() = 0; virtual int typeId() = 0; protected: // Main sizer wxSizer* _sizer {nullptr}; wxString presets; wxImageList* _icons {nullptr}; wxTreeCtrl* _treectrl {nullptr}; wxBitmapButton* _btn_save_preset {nullptr}; wxBitmapButton* _btn_delete_preset {nullptr}; wxChoice* _presets_choice {nullptr}; int _iconcount {-1}; /// Vector of PresetPage pointers; trust wxWidgets RTTI to avoid leaks std::vector<PresetPage*> _pages {}; const unsigned int left_col_width {150}; void _update_tree(); void load_presets(); virtual void _build() = 0; virtual void _update() = 0; virtual void _on_preset_loaded() = 0; void set_tooltips() { this->_btn_save_preset->SetToolTip(wxString(_("Save current ")) + this->title()); this->_btn_delete_preset->SetToolTip(_("Delete this preset.")); } void reload_compatible_printers_widget(); wxSizer* compatible_printers_widget(); /// This method is called: /// - upon first initialization; /// - whenever user selects a preset from the dropdown; /// - whenever select_preset() or select_preset_by_name() are called. void _on_select_preset(bool force = false); /// This method is supposed to be called whenever new values are loaded /// or changed by the user (including when presets are loaded). /// Pushes a callback onto the owning Slic3r app to be processed during /// an idle event. void _on_value_change(std::string opt_key); virtual const std::string LogChannel() = 0; //< Which log these messages should go to. }; class PrintEditor : public PresetEditor { public: PrintEditor(wxWindow* parent, t_config_option_keys options = {}); PrintEditor() : PrintEditor(nullptr, {}) {}; wxString title() override { return _("Print Settings"); } std::string name() override { return "print"s; } t_config_option_keys my_overridable_options() override { return PresetEditor::overridable_options(); }; static t_config_option_keys overridable_options() { return PresetEditor::overridable_options(); }; t_config_option_keys my_overriding_options() override { return PresetEditor::overriding_options(); }; static t_config_option_keys overriding_options() { return PresetEditor::overriding_options(); }; /// Static method to retrieve list of options that this preset governs. static t_config_option_keys options() { return t_config_option_keys { "layer_height"s, "first_layer_height"s, "adaptive_slicing"s, "adaptive_slicing_quality"s, "match_horizontal_surfaces"s, "perimeters"s, "spiral_vase"s, "top_solid_layers"s, "bottom_solid_layers"s, "extra_perimeters"s, "avoid_crossing_perimeters"s, "thin_walls"s, "overhangs"s, "seam_position"s, "external_perimeters_first"s, "fill_density"s, "fill_pattern"s, "top_infill_pattern"s, "bottom_infill_pattern"s, "fill_gaps"s, "infill_every_layers"s, "infill_only_where_needed"s, "solid_infill_every_layers"s, "fill_angle"s, "solid_infill_below_area"s, ""s, "only_retract_when_crossing_perimeters"s, "infill_first"s, "max_print_speed"s, "max_volumetric_speed"s, "perimeter_speed"s, "small_perimeter_speed"s, "external_perimeter_speed"s, "infill_speed"s, ""s, "solid_infill_speed"s, "top_solid_infill_speed"s, "support_material_speed"s, "support_material_interface_speed"s, "bridge_speed"s, "gap_fill_speed"s, "travel_speed"s, "first_layer_speed"s, "perimeter_acceleration"s, "infill_acceleration"s, "bridge_acceleration"s, "first_layer_acceleration"s, "default_acceleration"s, "skirts"s, "skirt_distance"s, "skirt_height"s, "min_skirt_length"s, "brim_connections_width"s, "brim_width"s, "interior_brim_width"s, "support_material"s, "support_material_threshold"s, "support_material_max_layers"s, "support_material_enforce_layers"s, "raft_layers"s, "support_material_pattern"s, "support_material_spacing"s, "support_material_angle"s, ""s, "support_material_interface_layers"s, "support_material_interface_spacing"s, "support_material_contact_distance"s, "support_material_buildplate_only"s, "dont_support_bridges"s, "notes"s, "complete_objects"s, "extruder_clearance_radius"s, "extruder_clearance_height"s, "gcode_comments"s, "output_filename_format"s, "post_process"s, "perimeter_extruder"s, "infill_extruder"s, "solid_infill_extruder"s, "support_material_extruder"s, "support_material_interface_extruder"s, "ooze_prevention"s, "standby_temperature_delta"s, "interface_shells"s, "regions_overlap"s, "extrusion_width"s, "first_layer_extrusion_width"s, "perimeter_extrusion_width"s, ""s, "external_perimeter_extrusion_width"s, "infill_extrusion_width"s, "solid_infill_extrusion_width"s, "top_infill_extrusion_width"s, "support_material_extrusion_width"s, "support_material_interface_extrusion_width"s, "infill_overlap"s, "bridge_flow_ratio"s, "xy_size_compensation"s, "resolution"s, "shortcuts"s, "compatible_printers"s, "print_settings_id"s }; } t_config_option_keys my_options() override { return PrintEditor::options(); } protected: void _update() override; void _build() override; }; class PrinterEditor : public PresetEditor { public: PrinterEditor(wxWindow* parent, t_config_option_keys options = {}); PrinterEditor() : PrinterEditor(nullptr, {}) {}; wxString title() override { return _("Printer Settings"); } std::string name() override { return "printer"s; } static t_config_option_keys overridable_options() { return t_config_option_keys { "pressure_advance"s, "retract_length"s, "retract_lift"s, "retract_speed"s, "retract_restart_extra"s, "retract_before_travel"s, "retract_layer_change"s, "wipe"s }; }; static t_config_option_keys overriding_options() { return PresetEditor::overriding_options(); }; t_config_option_keys my_overridable_options() override { return PrinterEditor::overridable_options(); }; t_config_option_keys my_overriding_options() override { return PrinterEditor::overriding_options(); }; static t_config_option_keys options() { return t_config_option_keys { "bed_shape"s, "z_offset"s, "z_steps_per_mm"s, "has_heatbed"s, "gcode_flavor"s, "use_relative_e_distances"s, "serial_port"s, "serial_speed"s, "host_type"s, "print_host"s, "octoprint_apikey"s, "use_firmware_retraction"s, "pressure_advance"s, "vibration_limit"s, "use_volumetric_e"s, "start_gcode"s, "end_gcode"s, "before_layer_gcode"s, "layer_gcode"s, "toolchange_gcode"s, "between_objects_gcode"s, "nozzle_diameter"s, "extruder_offset"s, "min_layer_height"s, "max_layer_height"s, "retract_length"s, "retract_lift"s, "retract_speed"s, "retract_restart_extra"s, "retract_before_travel"s, "retract_layer_change"s, "wipe"s, "retract_length_toolchange"s, "retract_restart_extra_toolchange"s, "retract_lift_above"s, "retract_lift_below"s, "printer_settings_id"s, "printer_notes"s, "use_set_and_wait_bed"s, "use_set_and_wait_extruder"s }; } t_config_option_keys my_options() override { return PrinterEditor::options(); } protected: void _update() override; void _build() override; const std::string LogChannel() override {return "PrinterEditor"s;} //< Which log these messages should go to. }; class MaterialEditor : public PresetEditor { public: wxString title() override { return _("Material Settings"); } std::string name() override { return "material"s; } preset_t type() override { return preset_t::Material; }; int typeId() override { return static_cast<int>(preset_t::Material); }; MaterialEditor(wxWindow* parent, t_config_option_keys options = {}); MaterialEditor() : MaterialEditor(nullptr, {}) {}; t_config_option_keys my_overridable_options() override { return PresetEditor::overridable_options(); }; t_config_option_keys my_overriding_options() override { return PrinterEditor::overridable_options(); }; static t_config_option_keys overriding_options() { return PrinterEditor::overridable_options(); }; static t_config_option_keys overridable_options() { return PresetEditor::overridable_options(); }; static t_config_option_keys options() { return t_config_option_keys { "filament_colour"s, "filament_diameter"s, "filament_notes"s, "filament_max_volumetric_speed"s, "extrusion_multiplier"s, "filament_density"s, "filament_cost"s, "temperature"s, "first_layer_temperature"s, "bed_temperature"s, "first_layer_bed_temperature"s, "fan_always_on"s, "cooling"s, "compatible_printers"s, "min_fan_speed"s, "max_fan_speed"s, "bridge_fan_speed"s, "disable_fan_first_layers"s, "fan_below_layer_time"s, "slowdown_below_layer_time"s, "min_print_speed"s, "start_filament_gcode"s, "end_filament_gcode"s, "filament_settings_id"s }; } t_config_option_keys my_options() override { return MaterialEditor::options(); } protected: void _update() override; void _build() override; const std::string LogChannel() override {return "MaterialEditor"s;} //< Which log these messages should go to. }; class PresetPage : wxScrolledWindow { public: PresetPage(wxWindow* parent, wxString _title, int _iconID) : wxScrolledWindow(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL), title(_title), iconID(_iconID) { this->vsizer = new wxBoxSizer(wxVERTICAL); this->SetSizer(this->vsizer); this->SetScrollRate(ui_settings->scroll_step(), ui_settings->scroll_step()); } protected: wxSizer* vsizer {nullptr}; wxString title {""}; int iconID {0}; }; }} // namespace Slic3r::GUI #endif // PRESETEDITOR_HPP <|endoftext|>
<commit_before>/* * * Copyright (c) 2014, Alessandro Sperinde' * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. 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 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 <iostream> #include <stdio.h> #include <stdlib.h> #include <time.h> #define TILE_FLOOR 0 #define TILE_WALL 1 typedef struct { int r1Cutoff; int r2Cutoff; int reps; } generation_params_t; int **grid; int **grid2; int fillprob = 40; int r1_cutoff = 5; int r2_cutoff = 2; int size_x = 64; int size_y = 20; generation_params_t *params; generation_params_t *paramsSet; int generations; int RandPick(void) { if (rand() % 100 < fillprob) { return TILE_WALL; } return TILE_FLOOR; } void InitMap(void) { int xi, yi; grid = (int **) malloc(sizeof(int *) * size_y); grid2 = (int **) malloc(sizeof(int *) * size_y); for(yi = 0; yi < size_y; yi++) { grid [yi] = (int *) malloc(sizeof(int) * size_x); grid2[yi] = (int *) malloc(sizeof(int) * size_x); } for (yi = 1; yi < (size_y - 1); yi++) { for (xi = 1; xi < (size_x - 1); xi++) { grid[yi][xi] = RandPick(); } } for (yi = 0; yi < size_y; yi++) { for (xi = 0; xi < size_x; xi++) { grid2[yi][xi] = TILE_WALL; } } for (yi = 0; yi < size_y; yi++) { grid[yi][0] = grid[yi][size_x - 1] = TILE_WALL; } for (xi = 0; xi < size_x; xi++) { grid[0][xi] = grid[size_y - 1][xi] = TILE_WALL; } } void Generation(void) { int xi, yi, ii, jj; for (yi = 1; yi < (size_y - 1); yi++) { for (xi = 1; xi < (size_x - 1); xi++) { int adjcount_r1 = 0; int adjcount_r2 = 0; for (ii = -1; ii <= 1; ii++) { for (jj = -1; jj <= 1; jj++) { if (grid[yi + ii][xi + jj] != TILE_FLOOR) { adjcount_r1++; } } } for (ii = (yi - 2); ii <= (yi + 2); ii++) { for (jj = (xi - 2); jj <= (xi + 2); jj++) { if (abs(ii - yi) == 2 && abs(jj - xi) == 2) { continue; } if (ii < 0 || jj < 0 || ii >= size_y || jj >= size_x) { continue; } if (grid[ii][jj] != TILE_FLOOR) { adjcount_r2++; } } } if (adjcount_r1 >= params->r1Cutoff || adjcount_r2 <= params->r2Cutoff) { grid2[yi][xi] = TILE_WALL; } else { grid2[yi][xi] = TILE_FLOOR; } } } for (yi = 1; yi < (size_y - 1); yi++) { for (xi = 1; xi < (size_x - 1); xi++) { grid[yi][xi] = grid2[yi][xi]; } } } void PrintFunc(void) { int ii; std::cout<<"W[0](p) = rand[0,100) < "<<fillprob<<"\n"; for (ii = 0; ii < generations; ii++) { std::cout<<"Repeat "<<paramsSet[ii].reps<<": W'(p) = R[1](p) >= "<<paramsSet[ii].r1Cutoff; if (paramsSet[ii].r2Cutoff >= 0) { std::cout<<" || R[2](p) <= "<<paramsSet[ii].r2Cutoff<<"\n"; } else { std::cout<<std::endl; } } } void PrintMap(void) { int xi, yi; for (yi = 0; yi < size_y; yi++) { for (xi = 0; xi < size_x; xi++) { switch (grid[yi][xi]) { case TILE_WALL: std::cout<<"#"; break; case TILE_FLOOR: std::cout<<"."; break; } } std::cout<<std::endl; } } int main(int argc, char **argv) { int ii, jj; if (argc < 7) { std::cerr<<"Usage: "<<argv[0]<<" xsize ysize fill (r1 r2 count)\n"; return 1; } size_x = atoi(argv[1]); size_y = atoi(argv[2]); fillprob = atoi(argv[3]); generations = (argc - 4) / 3; params = paramsSet = (generation_params_t *) malloc( sizeof(generation_params_t) * generations ); for (ii = 4; (ii + 2) < argc; ii += 3) { params->r1Cutoff = atoi(argv[ii]); params->r2Cutoff = atoi(argv[ii + 1]); params->reps = atoi(argv[ii + 2]); params++; } srand(time(NULL)); InitMap(); for (ii = 0; ii < generations; ii++) { params = &paramsSet[ii]; for (jj = 0; jj < params->reps; jj++) { Generation(); } } PrintFunc(); PrintMap(); return 0; } <commit_msg>no message<commit_after>/* * * Copyright (c) 2014, Alessandro Sperinde' * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. 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 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 <iostream> #include <stdio.h> #include <stdlib.h> #include <time.h> #define TILE_FLOOR 0 #define TILE_WALL 1 typedef struct { int r1Cutoff; int r2Cutoff; int reps; } generation_params_t; int **grid; int **grid2; int fillprob = 40; int r1_cutoff = 5; int r2_cutoff = 2; int size_x = 64; int size_y = 20; generation_params_t *params; generation_params_t *paramsSet; int generations; int RandPick(void) { if (rand() % 100 < fillprob) { return TILE_WALL; } return TILE_FLOOR; } void InitMap(void) { int xi, yi; grid = (int **) malloc(sizeof(int *) * size_y); grid2 = (int **) malloc(sizeof(int *) * size_y); for(yi = 0; yi < size_y; yi++) { grid [yi] = (int *) malloc(sizeof(int) * size_x); grid2[yi] = (int *) malloc(sizeof(int) * size_x); } for (yi = 1; yi < (size_y - 1); yi++) { for (xi = 1; xi < (size_x - 1); xi++) { grid[yi][xi] = RandPick(); } } for (yi = 0; yi < size_y; yi++) { for (xi = 0; xi < size_x; xi++) { grid2[yi][xi] = TILE_WALL; } } for (yi = 0; yi < size_y; yi++) { grid[yi][0] = grid[yi][size_x - 1] = TILE_WALL; } for (xi = 0; xi < size_x; xi++) { grid[0][xi] = grid[size_y - 1][xi] = TILE_WALL; } } void Generation(void) { int xi, yi, ii, jj; for (yi = 1; yi < (size_y - 1); yi++) { for (xi = 1; xi < (size_x - 1); xi++) { int adjcount_r1 = 0; int adjcount_r2 = 0; for (ii = -1; ii <= 1; ii++) { for (jj = -1; jj <= 1; jj++) { if (grid[yi + ii][xi + jj] != TILE_FLOOR) { adjcount_r1++; } } } for (ii = (yi - 2); ii <= (yi + 2); ii++) { for (jj = (xi - 2); jj <= (xi + 2); jj++) { if (abs(ii - yi) == 2 && abs(jj - xi) == 2) { continue; } if (ii < 0 || jj < 0 || ii >= size_y || jj >= size_x) { continue; } if (grid[ii][jj] != TILE_FLOOR) { adjcount_r2++; } } } if (adjcount_r1 >= params->r1Cutoff || adjcount_r2 <= params->r2Cutoff) { grid2[yi][xi] = TILE_WALL; } else { grid2[yi][xi] = TILE_FLOOR; } } } for (yi = 1; yi < (size_y - 1); yi++) { for (xi = 1; xi < (size_x - 1); xi++) { grid[yi][xi] = grid2[yi][xi]; } } } void PrintFunc(void) { int ii; std::cout<<"W[0](p) = rand[0,100) < "<<fillprob<<"\n"; for (ii = 0; ii < generations; ii++) { std::cout<<"Repeat "<<paramsSet[ii].reps<<": W'(p) = R[1](p) >= "<<paramsSet[ii].r1Cutoff; if (paramsSet[ii].r2Cutoff >= 0) { std::cout<<" || R[2](p) <= "<<paramsSet[ii].r2Cutoff<<"\n"; } else { std::cout<<std::endl; } } } void PrintMap(void) { int xi, yi; for (yi = 0; yi < size_y; yi++) { for (xi = 0; xi < size_x; xi++) { switch (grid[yi][xi]) { case TILE_WALL: std::cout<<"#"; break; case TILE_FLOOR: std::cout<<"."; break; } } std::cout<<std::endl; } } int main(int argc, char **argv) { int ii, jj; if (argc < 7) { std::cerr<<"Usage: "<<argv[0]<<" xsize ysize fill (r1 r2 count)\n"; return 1; } size_x = atoi(argv[1]); size_y = atoi(argv[2]); fillprob = atoi(argv[3]); generations = (argc - 4) / 3; params = paramsSet = (generation_params_t *) malloc( sizeof(generation_params_t) * generations ); for (ii = 4; (ii + 2) < argc; ii += 3) { params->r1Cutoff = atoi(argv[ii]); params->r2Cutoff = atoi(argv[ii + 1]); params->reps = atoi(argv[ii + 2]); params++; } srand(time(NULL)); InitMap(); for (ii = 0; ii < generations; ii++) { params = &paramsSet[ii]; for (jj = 0; jj < params->reps; jj++) { Generation(); } } PrintFunc(); PrintMap(); return 0; } <|endoftext|>
<commit_before>// // GWEN // Copyright (c) 2013-2014 James Lammlein // Copyright (c) 2010 Facepunch Studios // // This file is part of GWEN. // // MIT License // // 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 "Gwen.h" #include "Gwen/Controls/Label.h" #include "Gwen/Utility.h" namespace Gwen { namespace Controls { GWEN_CONTROL_CONSTRUCTOR(Label, Base) { _font = nullptr; _text = new ControlsInternal::Text(this); _text->SetFont(GetSkin()->GetDefaultFont()); SetAlignment(Position::LEFT | Position::TOP); SetMouseInputEnabled(false); SetSize(200, 20); SetTextPadding(Gwen::Padding(0, 1, 0, 0)); } void Label::SetText(const std::string& text) { _text->SetText(text); Redraw(); } std::string Label::GetText() const { return _text->GetText(); } void Label::SetFont(std::string name, int size, bool is_bold) { if (_font != nullptr) { GetSkin()->ReleaseFont(_font); delete _font; _font = nullptr; SetFont(nullptr); } _font = new Renderer::Font(); _font->_bold = is_bold; _font->_face_name = name; _font->_size = static_cast<float>(size); SetFont(_font); _text->RefreshSize(); } void Label::SetFont(Renderer::Font* font) { _text->SetFont(font); } Renderer::Font* Label::GetFont() { return _text->GetFont(); } void Label::SetTextColor(const Gwen::Color& color) { _text->SetTextColor(color); } Gwen::Color Label::GetTextColor() const { return _text->GetTextColor(); } void Label::SetTextColorOverride(const Gwen::Color& color) { _text->SetTextColorOverride(color); } Gwen::Color Label::GetTextColorOverride() const { return _text->GetTextColorOverride(); } void Label::SetAlignment(int alignment) { if (_alignment == alignment) { return; } _alignment = alignment; Invalidate(); } int Label::GetAlignment() { return _alignment; } void Label::SetWrap(bool do_wrap) { _text->SetWrap(do_wrap); } bool Label::GetWrap() const { return _text->GetWrap(); } void Label::SetTextPadding(const Padding& padding) { _text->SetPadding(padding); Invalidate(); InvalidateParent(); } Padding Label::GetTextPadding() const { return _text->GetPadding(); } int Label::GetTextLength() const { return _text->GetLength(); } Gwen::Rectangle Label::GetCharacterPosition(unsigned character) const { return _text->GetCharacterPosition(character); } int Label::GetClosestCharacter(const Gwen::Point& point) const { return _text->GetClosestCharacter(point); } void Label::SizeToContents() { _text->SetPosition(_padding._left, _padding._top); _text->RefreshSize(); SetSize(_text->Width() + _padding._left + _padding._right, _text->Height() + _padding._top + _padding._bottom); } void Label::PreDelete(Gwen::Skin::Base* skin) { if (_font) { skin->ReleaseFont(_font); delete _font; _font = nullptr; SetFont(nullptr); } } void Label::PostLayout(Skin::Base*) { _text->SetPosition(_alignment); } void Label::_OnBoundsChanged(const Gwen::Rectangle& old_bounds) { // Call the base class. Base::_OnBoundsChanged(old_bounds); if (_text->GetWrap()) { _text->RefreshSize(); Invalidate(); } } }; // namespace Controls }; // namespace Gwen <commit_msg>Reverting the label padding change.<commit_after>// // GWEN // Copyright (c) 2013-2014 James Lammlein // Copyright (c) 2010 Facepunch Studios // // This file is part of GWEN. // // MIT License // // 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 "Gwen.h" #include "Gwen/Controls/Label.h" #include "Gwen/Utility.h" namespace Gwen { namespace Controls { GWEN_CONTROL_CONSTRUCTOR(Label, Base) { _font = nullptr; _text = new ControlsInternal::Text(this); _text->SetFont(GetSkin()->GetDefaultFont()); SetAlignment(Position::LEFT | Position::TOP); SetMouseInputEnabled(false); SetSize(200, 20); } void Label::SetText(const std::string& text) { _text->SetText(text); Redraw(); } std::string Label::GetText() const { return _text->GetText(); } void Label::SetFont(std::string name, int size, bool is_bold) { if (_font != nullptr) { GetSkin()->ReleaseFont(_font); delete _font; _font = nullptr; SetFont(nullptr); } _font = new Renderer::Font(); _font->_bold = is_bold; _font->_face_name = name; _font->_size = static_cast<float>(size); SetFont(_font); _text->RefreshSize(); } void Label::SetFont(Renderer::Font* font) { _text->SetFont(font); } Renderer::Font* Label::GetFont() { return _text->GetFont(); } void Label::SetTextColor(const Gwen::Color& color) { _text->SetTextColor(color); } Gwen::Color Label::GetTextColor() const { return _text->GetTextColor(); } void Label::SetTextColorOverride(const Gwen::Color& color) { _text->SetTextColorOverride(color); } Gwen::Color Label::GetTextColorOverride() const { return _text->GetTextColorOverride(); } void Label::SetAlignment(int alignment) { if (_alignment == alignment) { return; } _alignment = alignment; Invalidate(); } int Label::GetAlignment() { return _alignment; } void Label::SetWrap(bool do_wrap) { _text->SetWrap(do_wrap); } bool Label::GetWrap() const { return _text->GetWrap(); } void Label::SetTextPadding(const Padding& padding) { _text->SetPadding(padding); Invalidate(); InvalidateParent(); } Padding Label::GetTextPadding() const { return _text->GetPadding(); } int Label::GetTextLength() const { return _text->GetLength(); } Gwen::Rectangle Label::GetCharacterPosition(unsigned character) const { return _text->GetCharacterPosition(character); } int Label::GetClosestCharacter(const Gwen::Point& point) const { return _text->GetClosestCharacter(point); } void Label::SizeToContents() { _text->SetPosition(_padding._left, _padding._top); _text->RefreshSize(); SetSize(_text->Width() + _padding._left + _padding._right, _text->Height() + _padding._top + _padding._bottom); } void Label::PreDelete(Gwen::Skin::Base* skin) { if (_font) { skin->ReleaseFont(_font); delete _font; _font = nullptr; SetFont(nullptr); } } void Label::PostLayout(Skin::Base*) { _text->SetPosition(_alignment); } void Label::_OnBoundsChanged(const Gwen::Rectangle& old_bounds) { // Call the base class. Base::_OnBoundsChanged(old_bounds); if (_text->GetWrap()) { _text->RefreshSize(); Invalidate(); } } }; // namespace Controls }; // namespace Gwen <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: tools.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: obo $ $Date: 2006-09-17 12:51:00 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_cppcanvas.hxx" #include <tools.hxx> using namespace ::com::sun::star; namespace cppcanvas { namespace tools { uno::Sequence< double > intSRGBAToDoubleSequence( const uno::Reference< rendering::XGraphicDevice >& rDevice, Color::IntSRGBA aColor ) { uno::Sequence< double > aRes( 4 ); aRes[0] = getRed(aColor) / 255.0; aRes[1] = getGreen(aColor) / 255.0; aRes[2] = getBlue(aColor) / 255.0; aRes[3] = getAlpha(aColor) / 255.0; return aRes; } Color::IntSRGBA doubleSequenceToIntSRGBA( const uno::Reference< rendering::XGraphicDevice >& rDevice, const uno::Sequence< double >& rColor ) { return makeColor( static_cast<sal_uInt8>( 255*rColor[0] + .5 ), static_cast<sal_uInt8>( 255*rColor[1] + .5 ), static_cast<sal_uInt8>( 255*rColor[2] + .5 ), static_cast<sal_uInt8>( 255*rColor[3] + .5 ) ); } } } <commit_msg>INTEGRATION: CWS sb59 (1.5.26); FILE MERGED 2006/08/11 15:36:04 thb 1.5.26.1: #i68336# Removed unused params; added a few using declarations for hidden methods; added a few casts; added some default statements to get cppcanvas warning free<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: tools.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: obo $ $Date: 2006-10-12 15:00:54 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_cppcanvas.hxx" #include <tools.hxx> using namespace ::com::sun::star; namespace cppcanvas { namespace tools { uno::Sequence< double > intSRGBAToDoubleSequence( const uno::Reference< rendering::XGraphicDevice >&, Color::IntSRGBA aColor ) { uno::Sequence< double > aRes( 4 ); aRes[0] = getRed(aColor) / 255.0; aRes[1] = getGreen(aColor) / 255.0; aRes[2] = getBlue(aColor) / 255.0; aRes[3] = getAlpha(aColor) / 255.0; return aRes; } Color::IntSRGBA doubleSequenceToIntSRGBA( const uno::Reference< rendering::XGraphicDevice >&, const uno::Sequence< double >& rColor ) { return makeColor( static_cast<sal_uInt8>( 255*rColor[0] + .5 ), static_cast<sal_uInt8>( 255*rColor[1] + .5 ), static_cast<sal_uInt8>( 255*rColor[2] + .5 ), static_cast<sal_uInt8>( 255*rColor[3] + .5 ) ); } } } <|endoftext|>
<commit_before>// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_ENUM_MAKER_HPP_INCLUDED #define LUABIND_ENUM_MAKER_HPP_INCLUDED #include <vector> #include <string> #include <boost/config.hpp> #if !defined(NDEBUG) && !defined(BOOST_NO_CXX11_SCOPED_ENUMS) # include <climits> # include <type_traits> #endif #include <luabind/config.hpp> #include <luabind/detail/class_rep.hpp> namespace luabind { struct value; struct value_vector : public std::vector<value> { // a bug in intel's compiler forces us to declare these constructors explicitly. value_vector(); virtual ~value_vector(); value_vector(const value_vector& v); value_vector& operator,(const value& rhs); }; struct value { friend class std::vector<value>; template<class T> value(const char* name, T v) : name_(name) , val_(static_cast<int>(v)) { #ifndef NDEBUG typedef typename std::underlying_type<T>::type integral_t; assert(static_cast<integral_t>(v) <= INT_MAX); assert(static_cast<integral_t>(v) >= INT_MIN); #endif // ifndef NDEBUG } const char* name_; int val_; value_vector operator,(const value& rhs) const { value_vector v; v.push_back(*this); v.push_back(rhs); return v; } private: value() {} }; inline value_vector::value_vector() : std::vector<value>() { } inline value_vector::~value_vector() {} inline value_vector::value_vector(const value_vector& rhs) : std::vector<value>(rhs) { } inline value_vector& value_vector::operator,(const value& rhs) { push_back(rhs); return *this; } namespace detail { template<class From> struct enum_maker { explicit enum_maker(From& from): from_(from) {} From& operator[](const value& val) { from_.add_static_constant(val.name_, val.val_); return from_; } From& operator[](const value_vector& values) { for (value_vector::const_iterator i = values.begin(); i != values.end(); ++i) { from_.add_static_constant(i->name_, i->val_); } return from_; } From& from_; private: void operator=(enum_maker const&); // C4512, assignment operator could not be generated template<class T> void operator,(T const&) const; }; } } #endif // LUABIND_ENUM_MAKER_HPP_INCLUDED <commit_msg>Fix condition for C++11 support.<commit_after>// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_ENUM_MAKER_HPP_INCLUDED #define LUABIND_ENUM_MAKER_HPP_INCLUDED #include <vector> #include <string> #include <boost/config.hpp> #if !defined(NDEBUG) && !defined(BOOST_NO_CXX11_SCOPED_ENUMS) # include <climits> # include <type_traits> #endif #include <luabind/config.hpp> #include <luabind/detail/class_rep.hpp> namespace luabind { struct value; struct value_vector : public std::vector<value> { // a bug in intel's compiler forces us to declare these constructors explicitly. value_vector(); virtual ~value_vector(); value_vector(const value_vector& v); value_vector& operator,(const value& rhs); }; struct value { friend class std::vector<value>; template<class T> value(const char* name, T v) : name_(name) , val_(static_cast<int>(v)) { #if !defined(NDEBUG) && !defined(BOOST_NO_CXX11_SCOPED_ENUMS) typedef typename std::underlying_type<T>::type integral_t; assert(static_cast<integral_t>(v) <= INT_MAX); assert(static_cast<integral_t>(v) >= INT_MIN); #endif // if in debug mode and C++11 scoped enums are supported } const char* name_; int val_; value_vector operator,(const value& rhs) const { value_vector v; v.push_back(*this); v.push_back(rhs); return v; } private: value() {} }; inline value_vector::value_vector() : std::vector<value>() { } inline value_vector::~value_vector() {} inline value_vector::value_vector(const value_vector& rhs) : std::vector<value>(rhs) { } inline value_vector& value_vector::operator,(const value& rhs) { push_back(rhs); return *this; } namespace detail { template<class From> struct enum_maker { explicit enum_maker(From& from): from_(from) {} From& operator[](const value& val) { from_.add_static_constant(val.name_, val.val_); return from_; } From& operator[](const value_vector& values) { for (value_vector::const_iterator i = values.begin(); i != values.end(); ++i) { from_.add_static_constant(i->name_, i->val_); } return from_; } From& from_; private: void operator=(enum_maker const&); // C4512, assignment operator could not be generated template<class T> void operator,(T const&) const; }; } } #endif // LUABIND_ENUM_MAKER_HPP_INCLUDED <|endoftext|>
<commit_before>// Copyright (c) 2009 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 "media/audio/mac/audio_manager_mac.h" #include "media/audio/mac/audio_output_mac.h" #include "base/basictypes.h" #include "base/logging.h" #include "media/audio/audio_util.h" // Overview of operation: // 1) An object of PCMQueueOutAudioOutputStream is created by the AudioManager // factory: audio_man->MakeAudioStream(). This just fills some structure. // 2) Next some thread will call Open(), at that point the underliying OS // queue is created and the audio buffers allocated. // 3) Then some thread will call Start(source) At this point the source will be // called to fill the initial buffers in the context of that same thread. // Then the OS queue is started which will create its own thread which // periodically will call the source for more data as buffers are being // consumed. // 4) At some point some thread will call Stop(), which we handle by directly // stoping the OS queue. // 5) One more callback to the source could be delivered in in the context of // the queue's own thread. Data, if any will be discared. // 6) The same thread that called stop will call Close() where we cleanup // and notifiy the audio manager, which likley will destroy this object. #if !defined(MAC_OS_X_VERSION_10_6) || \ MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6 enum { kAudioQueueErr_EnqueueDuringReset = -66632 }; #endif PCMQueueOutAudioOutputStream::PCMQueueOutAudioOutputStream( AudioManagerMac* manager, int channels, int sampling_rate, char bits_per_sample) : format_(), audio_queue_(NULL), buffer_(), source_(NULL), manager_(manager), silence_bytes_(0), volume_(1), pending_bytes_(0) { // We must have a manager. DCHECK(manager_); // A frame is one sample across all channels. In interleaved audio the per // frame fields identify the set of n |channels|. In uncompressed audio, a // packet is always one frame. format_.mSampleRate = sampling_rate; format_.mFormatID = kAudioFormatLinearPCM; format_.mFormatFlags = kLinearPCMFormatFlagIsPacked | kLinearPCMFormatFlagIsSignedInteger; format_.mBitsPerChannel = bits_per_sample; format_.mChannelsPerFrame = channels; format_.mFramesPerPacket = 1; format_.mBytesPerPacket = (format_.mBitsPerChannel * channels) / 8; format_.mBytesPerFrame = format_.mBytesPerPacket; // Silence buffer has a duration of 6ms to simulate the behavior of Windows. // This value is choosen by experiments and macs cannot keep up with // anything less than 6ms. silence_bytes_ = format_.mBytesPerFrame * sampling_rate * 6 / 1000; } PCMQueueOutAudioOutputStream::~PCMQueueOutAudioOutputStream() { } void PCMQueueOutAudioOutputStream::HandleError(OSStatus err) { // source_ can be set to NULL from another thread. We need to cache its // pointer while we operate here. Note that does not mean that the source // has been destroyed. AudioSourceCallback* source = source_; if (source) source->OnError(this, static_cast<int>(err)); NOTREACHED() << "error code " << err; } bool PCMQueueOutAudioOutputStream::Open(size_t packet_size) { if (0 == packet_size) { // TODO(cpu) : Impelement default buffer computation. return false; } // Create the actual queue object and let the OS use its own thread to // run its CFRunLoop. OSStatus err = AudioQueueNewOutput(&format_, RenderCallback, this, NULL, kCFRunLoopCommonModes, 0, &audio_queue_); if (err != noErr) { HandleError(err); return false; } // Allocate the hardware-managed buffers. for (size_t ix = 0; ix != kNumBuffers; ++ix) { err = AudioQueueAllocateBuffer(audio_queue_, packet_size, &buffer_[ix]); if (err != noErr) { HandleError(err); return false; } } // Set initial volume here. err = AudioQueueSetParameter(audio_queue_, kAudioQueueParam_Volume, 1.0); if (err != noErr) { HandleError(err); return false; } return true; } void PCMQueueOutAudioOutputStream::Close() { // It is valid to call Close() before calling Open(), thus audio_queue_ // might be NULL. if (audio_queue_) { OSStatus err = 0; for (size_t ix = 0; ix != kNumBuffers; ++ix) { if (buffer_[ix]) { err = AudioQueueFreeBuffer(audio_queue_, buffer_[ix]); if (err != noErr) { HandleError(err); break; } } } err = AudioQueueDispose(audio_queue_, true); if (err != noErr) HandleError(err); } // Inform the audio manager that we have been closed. This can cause our // destruction. manager_->ReleaseStream(this); } void PCMQueueOutAudioOutputStream::Stop() { // We request a synchronous stop, so the next call can take some time. In // the windows implementation we block here as well. source_ = NULL; // We set the source to null to signal to the data queueing thread it can stop // queueing data, however at most one callback might still be in flight which // could attempt to enqueue right after the next call. Rather that trying to // use a lock we rely on the internal Mac queue lock so the enqueue might // succeed or might fail but it won't crash or leave the queue itself in an // inconsistent state. OSStatus err = AudioQueueStop(audio_queue_, true); if (err != noErr) HandleError(err); } void PCMQueueOutAudioOutputStream::SetVolume(double left_level, double ) { if (!audio_queue_) return; volume_ = static_cast<float>(left_level); OSStatus err = AudioQueueSetParameter(audio_queue_, kAudioQueueParam_Volume, left_level); if (err != noErr) { HandleError(err); } } void PCMQueueOutAudioOutputStream::GetVolume(double* left_level, double* right_level) { if (!audio_queue_) return; *left_level = volume_; *right_level = volume_; } // Reorder PCM from AAC layout to Core Audio layout. // TODO(fbarchard): Switch layout when ffmpeg is updated. // TODO(fbarchard): Add 8 and 32 bit versions of this function. static void PCM16LayoutSwizzle(int16 *b, size_t filled) { int16 aac[6]; for (size_t i = 0; i < filled; i += 12, b += 6) { memcpy(aac, b, sizeof(aac)); b[0] = aac[1]; // L b[1] = aac[2]; // R b[2] = aac[0]; // C b[3] = aac[5]; // LFE b[4] = aac[3]; // Ls b[5] = aac[4]; // Rs } } // Note to future hackers of this function: Do not add locks here because we // call out to third party source that might do crazy things including adquire // external locks or somehow re-enter here because its legal for them to call // some audio functions. void PCMQueueOutAudioOutputStream::RenderCallback(void* p_this, AudioQueueRef queue, AudioQueueBufferRef buffer) { PCMQueueOutAudioOutputStream* audio_stream = static_cast<PCMQueueOutAudioOutputStream*>(p_this); // Call the audio source to fill the free buffer with data. Not having a // source means that the queue has been closed. This is not an error. AudioSourceCallback* source = audio_stream->source_; if (!source) return; // Adjust the number of pending bytes by subtracting the amount played. audio_stream->pending_bytes_ -= buffer->mAudioDataByteSize; size_t capacity = buffer->mAudioDataBytesCapacity; size_t filled = source->OnMoreData(audio_stream, buffer->mAudioData, capacity, audio_stream->pending_bytes_); // In order to keep the callback running, we need to provide a positive amount // of data to the audio queue. To simulate the behavior of Windows, we write // a buffer of silence. if (!filled) { CHECK(audio_stream->silence_bytes_ <= static_cast<int>(capacity)); filled = audio_stream->silence_bytes_; memset(buffer->mAudioData, 0, filled); } else if (filled > capacity) { // User probably overran our buffer. audio_stream->HandleError(0); return; } // Handle channel order for PCM 5.1 audio. if (audio_stream->format_.mChannelsPerFrame == 6 && audio_stream->format_.mBitsPerChannel == 16) { PCM16LayoutSwizzle(reinterpret_cast<int16*>(buffer->mAudioData), filled); } buffer->mAudioDataByteSize = filled; // Incremnet bytes by amount filled into audio buffer. audio_stream->pending_bytes_ += filled; if (NULL == queue) return; // Queue the audio data to the audio driver. OSStatus err = AudioQueueEnqueueBuffer(queue, buffer, 0, NULL); if (err != noErr) { if (err == kAudioQueueErr_EnqueueDuringReset) { // This is the error you get if you try to enqueue a buffer and the // queue has been closed. Not really a problem if indeed the queue // has been closed. if (!audio_stream->source_) return; } audio_stream->HandleError(err); } } void PCMQueueOutAudioOutputStream::Start(AudioSourceCallback* callback) { DCHECK(callback); OSStatus err = noErr; source_ = callback; pending_bytes_ = 0; // Ask the source to pre-fill all our buffers before playing. for (size_t ix = 0; ix != kNumBuffers; ++ix) { buffer_[ix]->mAudioDataByteSize = 0; RenderCallback(this, NULL, buffer_[ix]); } // Queue the buffers to the audio driver, sounds starts now. for (size_t ix = 0; ix != kNumBuffers; ++ix) { err = AudioQueueEnqueueBuffer(audio_queue_, buffer_[ix], 0, NULL); if (err != noErr) { HandleError(err); return; } } err = AudioQueueStart(audio_queue_, NULL); if (err != noErr) { HandleError(err); return; } } <commit_msg>Support 8 and 32 bit formats for Mac Channel Swizzler.<commit_after>// Copyright (c) 2009 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 "media/audio/mac/audio_manager_mac.h" #include "media/audio/mac/audio_output_mac.h" #include "base/basictypes.h" #include "base/logging.h" #include "media/audio/audio_util.h" // Overview of operation: // 1) An object of PCMQueueOutAudioOutputStream is created by the AudioManager // factory: audio_man->MakeAudioStream(). This just fills some structure. // 2) Next some thread will call Open(), at that point the underliying OS // queue is created and the audio buffers allocated. // 3) Then some thread will call Start(source) At this point the source will be // called to fill the initial buffers in the context of that same thread. // Then the OS queue is started which will create its own thread which // periodically will call the source for more data as buffers are being // consumed. // 4) At some point some thread will call Stop(), which we handle by directly // stoping the OS queue. // 5) One more callback to the source could be delivered in in the context of // the queue's own thread. Data, if any will be discared. // 6) The same thread that called stop will call Close() where we cleanup // and notifiy the audio manager, which likley will destroy this object. #if !defined(MAC_OS_X_VERSION_10_6) || \ MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6 enum { kAudioQueueErr_EnqueueDuringReset = -66632 }; #endif PCMQueueOutAudioOutputStream::PCMQueueOutAudioOutputStream( AudioManagerMac* manager, int channels, int sampling_rate, char bits_per_sample) : format_(), audio_queue_(NULL), buffer_(), source_(NULL), manager_(manager), silence_bytes_(0), volume_(1), pending_bytes_(0) { // We must have a manager. DCHECK(manager_); // A frame is one sample across all channels. In interleaved audio the per // frame fields identify the set of n |channels|. In uncompressed audio, a // packet is always one frame. format_.mSampleRate = sampling_rate; format_.mFormatID = kAudioFormatLinearPCM; format_.mFormatFlags = kLinearPCMFormatFlagIsPacked | kLinearPCMFormatFlagIsSignedInteger; format_.mBitsPerChannel = bits_per_sample; format_.mChannelsPerFrame = channels; format_.mFramesPerPacket = 1; format_.mBytesPerPacket = (format_.mBitsPerChannel * channels) / 8; format_.mBytesPerFrame = format_.mBytesPerPacket; // Silence buffer has a duration of 6ms to simulate the behavior of Windows. // This value is choosen by experiments and macs cannot keep up with // anything less than 6ms. silence_bytes_ = format_.mBytesPerFrame * sampling_rate * 6 / 1000; } PCMQueueOutAudioOutputStream::~PCMQueueOutAudioOutputStream() { } void PCMQueueOutAudioOutputStream::HandleError(OSStatus err) { // source_ can be set to NULL from another thread. We need to cache its // pointer while we operate here. Note that does not mean that the source // has been destroyed. AudioSourceCallback* source = source_; if (source) source->OnError(this, static_cast<int>(err)); NOTREACHED() << "error code " << err; } bool PCMQueueOutAudioOutputStream::Open(size_t packet_size) { if (0 == packet_size) { // TODO(cpu) : Impelement default buffer computation. return false; } // Create the actual queue object and let the OS use its own thread to // run its CFRunLoop. OSStatus err = AudioQueueNewOutput(&format_, RenderCallback, this, NULL, kCFRunLoopCommonModes, 0, &audio_queue_); if (err != noErr) { HandleError(err); return false; } // Allocate the hardware-managed buffers. for (size_t ix = 0; ix != kNumBuffers; ++ix) { err = AudioQueueAllocateBuffer(audio_queue_, packet_size, &buffer_[ix]); if (err != noErr) { HandleError(err); return false; } } // Set initial volume here. err = AudioQueueSetParameter(audio_queue_, kAudioQueueParam_Volume, 1.0); if (err != noErr) { HandleError(err); return false; } return true; } void PCMQueueOutAudioOutputStream::Close() { // It is valid to call Close() before calling Open(), thus audio_queue_ // might be NULL. if (audio_queue_) { OSStatus err = 0; for (size_t ix = 0; ix != kNumBuffers; ++ix) { if (buffer_[ix]) { err = AudioQueueFreeBuffer(audio_queue_, buffer_[ix]); if (err != noErr) { HandleError(err); break; } } } err = AudioQueueDispose(audio_queue_, true); if (err != noErr) HandleError(err); } // Inform the audio manager that we have been closed. This can cause our // destruction. manager_->ReleaseStream(this); } void PCMQueueOutAudioOutputStream::Stop() { // We request a synchronous stop, so the next call can take some time. In // the windows implementation we block here as well. source_ = NULL; // We set the source to null to signal to the data queueing thread it can stop // queueing data, however at most one callback might still be in flight which // could attempt to enqueue right after the next call. Rather that trying to // use a lock we rely on the internal Mac queue lock so the enqueue might // succeed or might fail but it won't crash or leave the queue itself in an // inconsistent state. OSStatus err = AudioQueueStop(audio_queue_, true); if (err != noErr) HandleError(err); } void PCMQueueOutAudioOutputStream::SetVolume(double left_level, double ) { if (!audio_queue_) return; volume_ = static_cast<float>(left_level); OSStatus err = AudioQueueSetParameter(audio_queue_, kAudioQueueParam_Volume, left_level); if (err != noErr) { HandleError(err); } } void PCMQueueOutAudioOutputStream::GetVolume(double* left_level, double* right_level) { if (!audio_queue_) return; *left_level = volume_; *right_level = volume_; } // Reorder PCM from AAC layout to Core Audio layout. // TODO(fbarchard): Switch layout when ffmpeg is updated. const int kNumSurroundChannels = 6; template<class Format> static void SwizzleLayout(Format *b, size_t filled) { Format aac[kNumSurroundChannels]; for (size_t i = 0; i < filled; i += sizeof(aac), b += kNumSurroundChannels) { memcpy(aac, b, sizeof(aac)); b[0] = aac[1]; // L b[1] = aac[2]; // R b[2] = aac[0]; // C b[3] = aac[5]; // LFE b[4] = aac[3]; // Ls b[5] = aac[4]; // Rs } } // Note to future hackers of this function: Do not add locks here because we // call out to third party source that might do crazy things including adquire // external locks or somehow re-enter here because its legal for them to call // some audio functions. void PCMQueueOutAudioOutputStream::RenderCallback(void* p_this, AudioQueueRef queue, AudioQueueBufferRef buffer) { PCMQueueOutAudioOutputStream* audio_stream = static_cast<PCMQueueOutAudioOutputStream*>(p_this); // Call the audio source to fill the free buffer with data. Not having a // source means that the queue has been closed. This is not an error. AudioSourceCallback* source = audio_stream->source_; if (!source) return; // Adjust the number of pending bytes by subtracting the amount played. audio_stream->pending_bytes_ -= buffer->mAudioDataByteSize; size_t capacity = buffer->mAudioDataBytesCapacity; size_t filled = source->OnMoreData(audio_stream, buffer->mAudioData, capacity, audio_stream->pending_bytes_); // In order to keep the callback running, we need to provide a positive amount // of data to the audio queue. To simulate the behavior of Windows, we write // a buffer of silence. if (!filled) { CHECK(audio_stream->silence_bytes_ <= static_cast<int>(capacity)); filled = audio_stream->silence_bytes_; memset(buffer->mAudioData, 0, filled); } else if (filled > capacity) { // User probably overran our buffer. audio_stream->HandleError(0); return; } // Handle channel order for PCM 5.1 audio. if (audio_stream->format_.mChannelsPerFrame == 6) { if (audio_stream->format_.mBitsPerChannel == 8) SwizzleLayout(reinterpret_cast<uint8*>(buffer->mAudioData), filled); } else if (audio_stream->format_.mBitsPerChannel == 16) { SwizzleLayout(reinterpret_cast<int16*>(buffer->mAudioData), filled); } else if (audio_stream->format_.mBitsPerChannel == 32) { SwizzleLayout(reinterpret_cast<int32*>(buffer->mAudioData), filled); } } buffer->mAudioDataByteSize = filled; // Incremnet bytes by amount filled into audio buffer. audio_stream->pending_bytes_ += filled; if (NULL == queue) return; // Queue the audio data to the audio driver. OSStatus err = AudioQueueEnqueueBuffer(queue, buffer, 0, NULL); if (err != noErr) { if (err == kAudioQueueErr_EnqueueDuringReset) { // This is the error you get if you try to enqueue a buffer and the // queue has been closed. Not really a problem if indeed the queue // has been closed. if (!audio_stream->source_) return; } audio_stream->HandleError(err); } } void PCMQueueOutAudioOutputStream::Start(AudioSourceCallback* callback) { DCHECK(callback); OSStatus err = noErr; source_ = callback; pending_bytes_ = 0; // Ask the source to pre-fill all our buffers before playing. for (size_t ix = 0; ix != kNumBuffers; ++ix) { buffer_[ix]->mAudioDataByteSize = 0; RenderCallback(this, NULL, buffer_[ix]); } // Queue the buffers to the audio driver, sounds starts now. for (size_t ix = 0; ix != kNumBuffers; ++ix) { err = AudioQueueEnqueueBuffer(audio_queue_, buffer_[ix], 0, NULL); if (err != noErr) { HandleError(err); return; } } err = AudioQueueStart(audio_queue_, NULL); if (err != noErr) { HandleError(err); return; } } <|endoftext|>
<commit_before><commit_msg>fix higher debug level build<commit_after><|endoftext|>
<commit_before> #include <girepository.h> #include <glib.h> #include "boxed.h" #include "debug.h" #include "function.h" #include "gi.h" #include "gobject.h" #include "type.h" #include "util.h" #include "value.h" using v8::Array; using v8::External; using v8::Function; using v8::FunctionTemplate; using v8::Isolate; using v8::Local; using v8::Number; using v8::Object; using v8::String; using v8::Persistent; using Nan::New; using Nan::WeakCallbackType; namespace GNodeJS { size_t Boxed::GetSize (GIBaseInfo *boxed_info) { GIInfoType i_type = g_base_info_get_type(boxed_info); if (i_type == GI_INFO_TYPE_STRUCT) { return g_struct_info_get_size((GIStructInfo*)boxed_info); } else if (i_type == GI_INFO_TYPE_UNION) { return g_union_info_get_size((GIUnionInfo*)boxed_info); } else { g_assert_not_reached(); } } static bool IsNoArgsConstructor(GIFunctionInfo *info) { auto flags = g_function_info_get_flags (info); return ((flags & GI_FUNCTION_IS_CONSTRUCTOR) != 0 && g_callable_info_get_n_args (info) == 0); } static GIFunctionInfo* FindBoxedConstructor(GIBaseInfo* info) { if (GI_IS_STRUCT_INFO (info)) { int n_methods = g_struct_info_get_n_methods (info); for (int i = 0; i < n_methods; i++) { GIFunctionInfo* fn_info = g_struct_info_get_method (info, i); if (IsNoArgsConstructor (fn_info)) return fn_info; g_base_info_unref(fn_info); } } else { int n_methods = g_union_info_get_n_methods (info); for (int i = 0; i < n_methods; i++) { GIFunctionInfo* fn_info = g_union_info_get_method (info, i); if (IsNoArgsConstructor (fn_info)) return fn_info; g_base_info_unref(fn_info); } } return NULL; } static void BoxedDestroyed(const Nan::WeakCallbackInfo<Boxed> &info); static void BoxedConstructor(const Nan::FunctionCallbackInfo<Value> &args) { /* See gobject.cc for how this works */ if (!args.IsConstructCall ()) { Nan::ThrowTypeError("Not a construct call"); return; } void *boxed = NULL; unsigned long size = 0; Local<Object> self = args.This (); GIBaseInfo *gi_info = (GIBaseInfo *) External::Cast (*args.Data ())->Value (); if (args[0]->IsExternal ()) { /* The External case. This is how WrapperFromBoxed is called. */ boxed = External::Cast(*args[0])->Value(); } else { /* User code calling `new Pango.AttrList()` */ size = Boxed::GetSize(gi_info); if (size != 0) { boxed = g_slice_alloc0(size); } /* TODO(find what to do in these cases) else { GIFunctionInfo* fn_info = FindBoxedConstructor(gi_info); if (fn_info != NULL) { GError *error = NULL; GIArgument return_value; g_function_info_invoke (fn_info, NULL, 0, NULL, 0, &return_value, &error); g_base_info_unref(fn_info); if (error != NULL) { Util::ThrowGError("Boxed allocation failed", error); return; } boxed = return_value.v_pointer; } } */ if (!boxed) { Nan::ThrowError("Boxed allocation failed"); return; } } self->SetAlignedPointerInInternalField (0, boxed); Nan::DefineOwnProperty(self, UTF8("__gtype__"), Nan::New<Number>(g_registered_type_info_get_g_type(gi_info)), (v8::PropertyAttribute)(v8::PropertyAttribute::ReadOnly | v8::PropertyAttribute::DontEnum) ); auto* cont = new Boxed(); cont->data = boxed; cont->size = size; cont->g_type = g_registered_type_info_get_g_type(gi_info); cont->persistent = new Nan::Persistent<Object>(self); cont->persistent->SetWeak(cont, BoxedDestroyed, Nan::WeakCallbackType::kParameter); } static void BoxedDestroyed(const Nan::WeakCallbackInfo<Boxed> &info) { Boxed *box = info.GetParameter(); if (G_TYPE_IS_BOXED(box->g_type)) { g_boxed_free(box->g_type, box->data); } else if (box->size != 0) { // Allocated in ./function.cc @ AllocateArgument g_slice_free1(box->size, box->data); } else if (box->data != NULL) { g_boxed_free(box->g_type, box->data); } delete box->persistent; delete box; } Local<FunctionTemplate> GetBoxedTemplate(GIBaseInfo *info, GType gtype) { void *data = NULL; if (gtype != G_TYPE_NONE) { data = g_type_get_qdata(gtype, GNodeJS::template_quark()); } /* * Template already created */ if (data) { Persistent<FunctionTemplate> *persistent = (Persistent<FunctionTemplate> *) data; Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate> (*persistent); return tpl; } /* * Template not created yet */ auto tpl = New<FunctionTemplate>(BoxedConstructor, New<External>(info)); tpl->InstanceTemplate()->SetInternalFieldCount(1); if (gtype != G_TYPE_NONE) { const char *class_name = g_type_name(gtype); tpl->SetClassName (UTF8(class_name)); } else { const char *class_name = g_base_info_get_name (info); tpl->SetClassName (UTF8(class_name)); } if (gtype == G_TYPE_NONE) return tpl; Isolate *isolate = Isolate::GetCurrent(); auto *persistent = new v8::Persistent<FunctionTemplate>(isolate, tpl); persistent->SetWeak( g_base_info_ref(info), GNodeJS::ClassDestroyed, WeakCallbackType::kParameter); g_type_set_qdata(gtype, GNodeJS::template_quark(), persistent); return tpl; } Local<Function> MakeBoxedClass(GIBaseInfo *info) { GType gtype = g_registered_type_info_get_g_type ((GIRegisteredTypeInfo *) info); if (gtype == G_TYPE_NONE) { auto moduleCache = GNodeJS::GetModuleCache(); auto ns = UTF8 (g_base_info_get_namespace (info)); auto name = UTF8 (g_base_info_get_name (info)); if (Nan::HasOwnProperty(moduleCache, ns).FromMaybe(false)) { auto module = Nan::Get(moduleCache, ns).ToLocalChecked()->ToObject(); if (Nan::HasOwnProperty(module, name).FromMaybe(false)) { auto constructor = Nan::Get(module, name).ToLocalChecked()->ToObject(); return Local<Function>::Cast (constructor); } } } Local<FunctionTemplate> tpl = GetBoxedTemplate (info, gtype); return tpl->GetFunction (); } Local<Value> WrapperFromBoxed(GIBaseInfo *info, void *data) { if (data == NULL) return Nan::Null(); Local<Function> constructor = MakeBoxedClass (info); Local<Value> boxed_external = Nan::New<External> (data); Local<Value> args[] = { boxed_external }; Local<Object> obj = Nan::NewInstance(constructor, 1, args).ToLocalChecked(); return obj; } void* BoxedFromWrapper(Local<Value> value) { Local<Object> object = value->ToObject (); g_assert(object->InternalFieldCount() > 0); void *boxed = object->GetAlignedPointerFromInternalField(0); return boxed; } }; <commit_msg>boxed.cc: refactor<commit_after> #include <girepository.h> #include <glib.h> #include "boxed.h" #include "debug.h" #include "function.h" #include "gi.h" #include "gobject.h" #include "type.h" #include "util.h" #include "value.h" using v8::Array; using v8::External; using v8::Function; using v8::FunctionTemplate; using v8::Isolate; using v8::Local; using v8::Number; using v8::Object; using v8::String; using v8::Persistent; using Nan::New; using Nan::WeakCallbackType; namespace GNodeJS { size_t Boxed::GetSize (GIBaseInfo *boxed_info) { GIInfoType i_type = g_base_info_get_type(boxed_info); if (i_type == GI_INFO_TYPE_STRUCT) { return g_struct_info_get_size((GIStructInfo*)boxed_info); } else if (i_type == GI_INFO_TYPE_UNION) { return g_union_info_get_size((GIUnionInfo*)boxed_info); } else { g_assert_not_reached(); } } static bool IsNoArgsConstructor(GIFunctionInfo *info) { auto flags = g_function_info_get_flags (info); return ((flags & GI_FUNCTION_IS_CONSTRUCTOR) != 0 && g_callable_info_get_n_args (info) == 0); } static GIFunctionInfo* FindBoxedConstructor(GIBaseInfo* info) { if (GI_IS_STRUCT_INFO (info)) { int n_methods = g_struct_info_get_n_methods (info); for (int i = 0; i < n_methods; i++) { GIFunctionInfo* fn_info = g_struct_info_get_method (info, i); if (IsNoArgsConstructor (fn_info)) return fn_info; g_base_info_unref(fn_info); } } else { int n_methods = g_union_info_get_n_methods (info); for (int i = 0; i < n_methods; i++) { GIFunctionInfo* fn_info = g_union_info_get_method (info, i); if (IsNoArgsConstructor (fn_info)) return fn_info; g_base_info_unref(fn_info); } } return NULL; } static void BoxedDestroyed(const Nan::WeakCallbackInfo<Boxed> &info); static void BoxedConstructor(const Nan::FunctionCallbackInfo<Value> &args) { /* See gobject.cc for how this works */ if (!args.IsConstructCall ()) { Nan::ThrowTypeError("Not a construct call"); return; } void *boxed = NULL; unsigned long size = 0; Local<Object> self = args.This (); GIBaseInfo *gi_info = (GIBaseInfo *) External::Cast (*args.Data ())->Value (); if (args[0]->IsExternal ()) { /* The External case. This is how WrapperFromBoxed is called. */ boxed = External::Cast(*args[0])->Value(); } else { /* User code calling `new Pango.AttrList()` */ size = Boxed::GetSize(gi_info); if (size != 0) { boxed = g_slice_alloc0(size); } /* TODO(find what to do in these cases) else { GIFunctionInfo* fn_info = FindBoxedConstructor(gi_info); if (fn_info != NULL) { GError *error = NULL; GIArgument return_value; g_function_info_invoke (fn_info, NULL, 0, NULL, 0, &return_value, &error); g_base_info_unref(fn_info); if (error != NULL) { Util::ThrowGError("Boxed allocation failed", error); return; } boxed = return_value.v_pointer; } } */ if (!boxed) { Nan::ThrowError("Boxed allocation failed"); return; } } self->SetAlignedPointerInInternalField (0, boxed); Nan::DefineOwnProperty(self, UTF8("__gtype__"), Nan::New<Number>(g_registered_type_info_get_g_type(gi_info)), (v8::PropertyAttribute)(v8::PropertyAttribute::ReadOnly | v8::PropertyAttribute::DontEnum) ); auto* box = new Boxed(); box->data = boxed; box->size = size; box->g_type = g_registered_type_info_get_g_type(gi_info); box->persistent = new Nan::Persistent<Object>(self); box->persistent->SetWeak(box, BoxedDestroyed, Nan::WeakCallbackType::kParameter); } static void BoxedDestroyed(const Nan::WeakCallbackInfo<Boxed> &info) { Boxed *box = info.GetParameter(); if (G_TYPE_IS_BOXED(box->g_type)) { g_boxed_free(box->g_type, box->data); } else if (box->size != 0) { // Allocated in ./function.cc @ AllocateArgument g_slice_free1(box->size, box->data); } else if (box->data != NULL) { g_boxed_free(box->g_type, box->data); } delete box->persistent; delete box; } Local<FunctionTemplate> GetBoxedTemplate(GIBaseInfo *info, GType gtype) { void *data = NULL; if (gtype != G_TYPE_NONE) { data = g_type_get_qdata(gtype, GNodeJS::template_quark()); } /* * Template already created */ if (data) { Persistent<FunctionTemplate> *persistent = (Persistent<FunctionTemplate> *) data; Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate> (*persistent); return tpl; } /* * Template not created yet */ auto tpl = New<FunctionTemplate>(BoxedConstructor, New<External>(info)); tpl->InstanceTemplate()->SetInternalFieldCount(1); if (gtype != G_TYPE_NONE) { const char *class_name = g_type_name(gtype); tpl->SetClassName (UTF8(class_name)); } else { const char *class_name = g_base_info_get_name (info); tpl->SetClassName (UTF8(class_name)); } if (gtype == G_TYPE_NONE) return tpl; Isolate *isolate = Isolate::GetCurrent(); auto *persistent = new v8::Persistent<FunctionTemplate>(isolate, tpl); persistent->SetWeak( g_base_info_ref(info), GNodeJS::ClassDestroyed, WeakCallbackType::kParameter); g_type_set_qdata(gtype, GNodeJS::template_quark(), persistent); return tpl; } Local<Function> MakeBoxedClass(GIBaseInfo *info) { GType gtype = g_registered_type_info_get_g_type ((GIRegisteredTypeInfo *) info); if (gtype == G_TYPE_NONE) { auto moduleCache = GNodeJS::GetModuleCache(); auto ns = UTF8 (g_base_info_get_namespace (info)); auto name = UTF8 (g_base_info_get_name (info)); if (Nan::HasOwnProperty(moduleCache, ns).FromMaybe(false)) { auto module = Nan::Get(moduleCache, ns).ToLocalChecked()->ToObject(); if (Nan::HasOwnProperty(module, name).FromMaybe(false)) { auto constructor = Nan::Get(module, name).ToLocalChecked()->ToObject(); return Local<Function>::Cast (constructor); } } } Local<FunctionTemplate> tpl = GetBoxedTemplate (info, gtype); return tpl->GetFunction (); } Local<Value> WrapperFromBoxed(GIBaseInfo *info, void *data) { if (data == NULL) return Nan::Null(); Local<Function> constructor = MakeBoxedClass (info); Local<Value> boxed_external = Nan::New<External> (data); Local<Value> args[] = { boxed_external }; Local<Object> obj = Nan::NewInstance(constructor, 1, args).ToLocalChecked(); return obj; } void* BoxedFromWrapper(Local<Value> value) { Local<Object> object = value->ToObject (); g_assert(object->InternalFieldCount() > 0); void *boxed = object->GetAlignedPointerFromInternalField(0); return boxed; } }; <|endoftext|>
<commit_before>/// \file TClingRdictModuleFileExtension.cxx /// /// \brief The file contains facilities to work with C++ module files extensions /// used to store rdict files. /// /// \author Vassil Vassilev <vvasilev@cern.ch> /// /// \date May, 2019 /// /************************************************************************* * Copyright (C) 1995-2018, 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 "TClingRdictModuleFileExtension.h" #include "TClingUtils.h" #include "clang/Frontend/FrontendDiagnostic.h" #include "clang/Lex/HeaderSearchOptions.h" #include "clang/Lex/Preprocessor.h" #include "clang/Sema/Sema.h" #include "clang/Serialization/ASTReader.h" #include "clang/Serialization/Module.h" #include "llvm/ADT/Hashing.h" #include "llvm/Bitcode/BitstreamWriter.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" /// Rdict module extension block name. const std::string ROOT_CLING_RDICT_BLOCK_NAME = "root.cling.rdict"; /// Rdict module extension major version number. constexpr uint16_t ROOT_CLING_RDICT_VERSION_MAJOR = 1; /// Rdict module extension minor version number. /// /// When the format changes IN ANY WAY, this number should be incremented. constexpr uint16_t ROOT_CLING_RDICT_VERSION_MINOR = 1; TClingRdictModuleFileExtension::Writer::~Writer() {} void TClingRdictModuleFileExtension::Writer::writeExtensionContents(clang::Sema &SemaRef, llvm::BitstreamWriter &Stream) { const clang::LangOptions &Opts = SemaRef.getLangOpts(); const clang::Preprocessor &PP = SemaRef.getPreprocessor(); llvm::StringRef CachePath = PP.getHeaderSearchInfo().getHeaderSearchOpts().ModuleCachePath; std::string RdictsStart = "lib" + Opts.CurrentModule + "_"; const std::string RdictsEnd = "_rdict.pcm"; using namespace llvm; using namespace clang; using namespace clang::serialization; // Write an abbreviation for this record. auto Abv = std::make_shared<BitCodeAbbrev>(); Abv->Add(BitCodeAbbrevOp(FIRST_EXTENSION_RECORD_ID)); Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); auto Abbrev = Stream.EmitAbbrev(std::move(Abv)); auto Abv1 = std::make_shared<BitCodeAbbrev>(); Abv1->Add(BitCodeAbbrevOp(FIRST_EXTENSION_RECORD_ID + 1)); Abv1->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); auto Abbrev1 = Stream.EmitAbbrev(std::move(Abv1)); // Write a dict files into the extension block. std::error_code EC; for (llvm::sys::fs::directory_iterator DirIt(CachePath, EC), DirEnd; DirIt != DirEnd && !EC; DirIt.increment(EC)) { StringRef FilePath(DirIt->path()); if (llvm::sys::fs::is_directory(FilePath)) continue; StringRef FileName = llvm::sys::path::filename(FilePath); if (FileName.startswith(RdictsStart) && FileName.endswith(RdictsEnd)) { uint64_t Record[] = {FIRST_EXTENSION_RECORD_ID}; Stream.EmitRecordWithBlob(Abbrev, Record, FileName); uint64_t Record1[] = {FIRST_EXTENSION_RECORD_ID + 1}; auto MBOrErr = MemoryBuffer::getFile(FilePath); MemoryBuffer &MB = *MBOrErr.get(); Stream.EmitRecordWithBlob(Abbrev1, Record1, MB.getBuffer()); llvm::sys::fs::remove(FilePath); } } } extern "C" void TCling__RegisterRdictForLoadPCM(const std::string &pcmFileNameFullPath, llvm::StringRef *pcmContent); TClingRdictModuleFileExtension::Reader::Reader(clang::ModuleFileExtension *Ext, clang::ASTReader &Reader, clang::serialization::ModuleFile &Mod, const llvm::BitstreamCursor &InStream) : ModuleFileExtensionReader(Ext), Stream(InStream) { // Read the extension block. llvm::SmallVector<uint64_t, 4> Record; llvm::StringRef CurrentRdictName; while (true) { llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); switch (Entry.Kind) { case llvm::BitstreamEntry::SubBlock: case llvm::BitstreamEntry::EndBlock: case llvm::BitstreamEntry::Error: return; case llvm::BitstreamEntry::Record: break; } Record.clear(); llvm::StringRef Blob; unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob); using namespace clang::serialization; switch (RecCode) { case FIRST_EXTENSION_RECORD_ID: { CurrentRdictName = Blob; break; } case FIRST_EXTENSION_RECORD_ID + 1: { // FIXME: Remove the string copy in fPendingRdicts. std::string ResolvedFileName = ROOT::TMetaUtils::GetRealPath(Mod.FileName); llvm::StringRef ModDir = llvm::sys::path::parent_path(ResolvedFileName); llvm::SmallString<255> FullRdictName = ModDir; llvm::sys::path::append(FullRdictName, CurrentRdictName); TCling__RegisterRdictForLoadPCM(FullRdictName.str(), &Blob); break; } } } } TClingRdictModuleFileExtension::Reader::~Reader() {} TClingRdictModuleFileExtension::~TClingRdictModuleFileExtension() {} clang::ModuleFileExtensionMetadata TClingRdictModuleFileExtension::getExtensionMetadata() const { const std::string UserInfo = ""; return {ROOT_CLING_RDICT_BLOCK_NAME, ROOT_CLING_RDICT_VERSION_MAJOR, ROOT_CLING_RDICT_VERSION_MINOR, UserInfo}; } llvm::hash_code TClingRdictModuleFileExtension::hashExtension(llvm::hash_code Code) const { Code = llvm::hash_combine(Code, ROOT_CLING_RDICT_BLOCK_NAME); Code = llvm::hash_combine(Code, ROOT_CLING_RDICT_VERSION_MAJOR); Code = llvm::hash_combine(Code, ROOT_CLING_RDICT_VERSION_MINOR); return Code; } std::unique_ptr<clang::ModuleFileExtensionWriter> TClingRdictModuleFileExtension::createExtensionWriter(clang::ASTWriter &) { return std::unique_ptr<clang::ModuleFileExtensionWriter>(new Writer(this)); } std::unique_ptr<clang::ModuleFileExtensionReader> TClingRdictModuleFileExtension::createExtensionReader(const clang::ModuleFileExtensionMetadata &Metadata, clang::ASTReader &Reader, clang::serialization::ModuleFile &Mod, const llvm::BitstreamCursor &Stream) { return std::unique_ptr<clang::ModuleFileExtensionReader>( new TClingRdictModuleFileExtension::Reader(this, Reader, Mod, Stream)); } <commit_msg>Shift to standard C++ filestreams when generating _rdict files<commit_after>/// \file TClingRdictModuleFileExtension.cxx /// /// \brief The file contains facilities to work with C++ module files extensions /// used to store rdict files. /// /// \author Vassil Vassilev <vvasilev@cern.ch> /// /// \date May, 2019 /// /************************************************************************* * Copyright (C) 1995-2018, 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 "TClingRdictModuleFileExtension.h" #include "TClingUtils.h" #include "clang/Frontend/FrontendDiagnostic.h" #include "clang/Lex/HeaderSearchOptions.h" #include "clang/Lex/Preprocessor.h" #include "clang/Sema/Sema.h" #include "clang/Serialization/ASTReader.h" #include "clang/Serialization/Module.h" #include "llvm/ADT/Hashing.h" #include "llvm/Bitcode/BitstreamWriter.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" #include <fstream> #include <sstream> /// Rdict module extension block name. const std::string ROOT_CLING_RDICT_BLOCK_NAME = "root.cling.rdict"; /// Rdict module extension major version number. constexpr uint16_t ROOT_CLING_RDICT_VERSION_MAJOR = 1; /// Rdict module extension minor version number. /// /// When the format changes IN ANY WAY, this number should be incremented. constexpr uint16_t ROOT_CLING_RDICT_VERSION_MINOR = 1; TClingRdictModuleFileExtension::Writer::~Writer() {} void TClingRdictModuleFileExtension::Writer::writeExtensionContents(clang::Sema &SemaRef, llvm::BitstreamWriter &Stream) { const clang::LangOptions &Opts = SemaRef.getLangOpts(); const clang::Preprocessor &PP = SemaRef.getPreprocessor(); llvm::StringRef CachePath = PP.getHeaderSearchInfo().getHeaderSearchOpts().ModuleCachePath; std::string RdictsStart = "lib" + Opts.CurrentModule + "_"; const std::string RdictsEnd = "_rdict.pcm"; using namespace llvm; using namespace clang; using namespace clang::serialization; // Write an abbreviation for this record. auto Abv = std::make_shared<BitCodeAbbrev>(); Abv->Add(BitCodeAbbrevOp(FIRST_EXTENSION_RECORD_ID)); Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); auto Abbrev = Stream.EmitAbbrev(std::move(Abv)); auto Abv1 = std::make_shared<BitCodeAbbrev>(); Abv1->Add(BitCodeAbbrevOp(FIRST_EXTENSION_RECORD_ID + 1)); Abv1->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); auto Abbrev1 = Stream.EmitAbbrev(std::move(Abv1)); // Write a dict files into the extension block. std::error_code EC; for (llvm::sys::fs::directory_iterator DirIt(CachePath, EC), DirEnd; DirIt != DirEnd && !EC; DirIt.increment(EC)) { StringRef FilePath(DirIt->path()); if (llvm::sys::fs::is_directory(FilePath)) continue; StringRef FileName = llvm::sys::path::filename(FilePath); if (FileName.startswith(RdictsStart) && FileName.endswith(RdictsEnd)) { uint64_t Record[] = {FIRST_EXTENSION_RECORD_ID}; Stream.EmitRecordWithBlob(Abbrev, Record, FileName); uint64_t Record1[] = {FIRST_EXTENSION_RECORD_ID + 1}; std::ifstream fp(FilePath, std::ios::binary); std::ostringstream os; os << fp.rdbuf(); Stream.EmitRecordWithBlob(Abbrev1, Record1, StringRef(os.str())); fp.close(); EC = llvm::sys::fs::remove(FilePath); assert(!EC && "Unable to close _rdict file"); } } } extern "C" void TCling__RegisterRdictForLoadPCM(const std::string &pcmFileNameFullPath, llvm::StringRef *pcmContent); TClingRdictModuleFileExtension::Reader::Reader(clang::ModuleFileExtension *Ext, clang::ASTReader &Reader, clang::serialization::ModuleFile &Mod, const llvm::BitstreamCursor &InStream) : ModuleFileExtensionReader(Ext), Stream(InStream) { // Read the extension block. llvm::SmallVector<uint64_t, 4> Record; llvm::StringRef CurrentRdictName; while (true) { llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); switch (Entry.Kind) { case llvm::BitstreamEntry::SubBlock: case llvm::BitstreamEntry::EndBlock: case llvm::BitstreamEntry::Error: return; case llvm::BitstreamEntry::Record: break; } Record.clear(); llvm::StringRef Blob; unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob); using namespace clang::serialization; switch (RecCode) { case FIRST_EXTENSION_RECORD_ID: { CurrentRdictName = Blob; break; } case FIRST_EXTENSION_RECORD_ID + 1: { // FIXME: Remove the string copy in fPendingRdicts. std::string ResolvedFileName = ROOT::TMetaUtils::GetRealPath(Mod.FileName); llvm::StringRef ModDir = llvm::sys::path::parent_path(ResolvedFileName); llvm::SmallString<255> FullRdictName = ModDir; llvm::sys::path::append(FullRdictName, CurrentRdictName); TCling__RegisterRdictForLoadPCM(FullRdictName.str(), &Blob); break; } } } } TClingRdictModuleFileExtension::Reader::~Reader() {} TClingRdictModuleFileExtension::~TClingRdictModuleFileExtension() {} clang::ModuleFileExtensionMetadata TClingRdictModuleFileExtension::getExtensionMetadata() const { const std::string UserInfo = ""; return {ROOT_CLING_RDICT_BLOCK_NAME, ROOT_CLING_RDICT_VERSION_MAJOR, ROOT_CLING_RDICT_VERSION_MINOR, UserInfo}; } llvm::hash_code TClingRdictModuleFileExtension::hashExtension(llvm::hash_code Code) const { Code = llvm::hash_combine(Code, ROOT_CLING_RDICT_BLOCK_NAME); Code = llvm::hash_combine(Code, ROOT_CLING_RDICT_VERSION_MAJOR); Code = llvm::hash_combine(Code, ROOT_CLING_RDICT_VERSION_MINOR); return Code; } std::unique_ptr<clang::ModuleFileExtensionWriter> TClingRdictModuleFileExtension::createExtensionWriter(clang::ASTWriter &) { return std::unique_ptr<clang::ModuleFileExtensionWriter>(new Writer(this)); } std::unique_ptr<clang::ModuleFileExtensionReader> TClingRdictModuleFileExtension::createExtensionReader(const clang::ModuleFileExtensionMetadata &Metadata, clang::ASTReader &Reader, clang::serialization::ModuleFile &Mod, const llvm::BitstreamCursor &Stream) { return std::unique_ptr<clang::ModuleFileExtensionReader>( new TClingRdictModuleFileExtension::Reader(this, Reader, Mod, Stream)); } <|endoftext|>
<commit_before>/************************************************************************* * * Copyright 2016 Realm Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **************************************************************************/ #ifndef REALM_UTIL_BUFFER_HPP #define REALM_UTIL_BUFFER_HPP #include <cstddef> #include <algorithm> #include <exception> #include <limits> #include <utility> #include <realm/util/features.h> #include <realm/util/safe_int_ops.hpp> #include <memory> namespace realm { namespace util { /// A simple buffer concept that owns a region of memory and knows its /// size. template <class T> class Buffer { public: Buffer() noexcept : m_size(0) { } explicit Buffer(size_t initial_size); Buffer(Buffer<T>&&) noexcept = default; ~Buffer() noexcept { } Buffer<T>& operator=(Buffer<T>&&) noexcept = default; T& operator[](size_t i) noexcept { return m_data[i]; } const T& operator[](size_t i) const noexcept { return m_data[i]; } T* data() noexcept { return m_data.get(); } const T* data() const noexcept { return m_data.get(); } size_t size() const noexcept { return m_size; } /// False iff the data() returns null. explicit operator bool() const noexcept { return bool(m_data); } /// Discards the original contents. void set_size(size_t new_size); /// \param new_size Specifies the new buffer size. /// \param copy_begin, copy_end Specifies a range of element /// values to be retained. \a copy_end must be less than, or equal /// to size(). /// /// \param copy_to Specifies where the retained range should be /// copied to. `\a copy_to + \a copy_end - \a copy_begin` must be /// less than, or equal to \a new_size. void resize(size_t new_size, size_t copy_begin, size_t copy_end, size_t copy_to); void reserve(size_t used_size, size_t min_capacity); void reserve_extra(size_t used_size, size_t min_extra_capacity); T* release() noexcept; friend void swap(Buffer& a, Buffer& b) noexcept { using std::swap; swap(a.m_data, b.m_data); swap(a.m_size, b.m_size); } private: std::unique_ptr<T[]> m_data; size_t m_size; }; /// A buffer that can be efficiently resized. It acheives this by /// using an underlying buffer that may be larger than the logical /// size, and is automatically expanded in progressively larger steps. template <class T> class AppendBuffer { public: AppendBuffer() noexcept; ~AppendBuffer() noexcept { } /// Returns the current size of the buffer. size_t size() const noexcept; /// Gives read and write access to the elements. T* data() noexcept; /// Gives read access the elements. const T* data() const noexcept; /// Append the specified elements. This increases the size of this /// buffer by \a append_data_size. If the caller has previously requested /// a minimum capacity that is greater than, or equal to the /// resulting size, this function is guaranteed to not throw. void append(const T* append_data, size_t append_data_size); /// If the specified size is less than the current size, then the /// buffer contents is truncated accordingly. If the specified /// size is greater than the current size, then the extra elements /// will have undefined values. If the caller has previously /// requested a minimum capacity that is greater than, or equal to /// the specified size, this function is guaranteed to not throw. void resize(size_t new_size); /// This operation does not change the size of the buffer as /// returned by size(). If the specified capacity is less than the /// current capacity, this operation has no effect. void reserve(size_t min_capacity); /// Set the size to zero. The capacity remains unchanged. void clear() noexcept; private: util::Buffer<T> m_buffer; size_t m_size; }; // Implementation: class BufferSizeOverflow : public std::exception { public: const char* what() const noexcept override { return "Buffer size overflow"; } }; template <class T> inline Buffer<T>::Buffer(size_t initial_size) : m_data(new T[initial_size]) // Throws , m_size(initial_size) { } template <class T> inline void Buffer<T>::set_size(size_t new_size) { m_data.reset(new T[new_size]); // Throws m_size = new_size; } template <class T> inline void Buffer<T>::resize(size_t new_size, size_t copy_begin, size_t copy_end, size_t copy_to) { std::unique_ptr<T[]> new_data(new T[new_size]); // Throws std::copy_n(m_data.get() + copy_begin, copy_end - copy_begin, new_data.get() + copy_to); m_data.reset(new_data.release()); m_size = new_size; } template <class T> inline void Buffer<T>::reserve(size_t used_size, size_t min_capacity) { size_t current_capacity = m_size; if (REALM_LIKELY(current_capacity >= min_capacity)) return; size_t new_capacity = current_capacity; // Use growth factor 1.5. if (REALM_UNLIKELY(int_multiply_with_overflow_detect(new_capacity, 3))) new_capacity = std::numeric_limits<size_t>::max(); new_capacity /= 2; if (REALM_UNLIKELY(new_capacity < min_capacity)) new_capacity = min_capacity; resize(new_capacity, 0, used_size, 0); // Throws } template <class T> inline void Buffer<T>::reserve_extra(size_t used_size, size_t min_extra_capacity) { size_t min_capacity = used_size; if (REALM_UNLIKELY(int_add_with_overflow_detect(min_capacity, min_extra_capacity))) throw BufferSizeOverflow(); reserve(used_size, min_capacity); // Throws } template <class T> inline T* Buffer<T>::release() noexcept { m_size = 0; return m_data.release(); } template <class T> inline AppendBuffer<T>::AppendBuffer() noexcept : m_size(0) { } template <class T> inline size_t AppendBuffer<T>::size() const noexcept { return m_size; } template <class T> inline T* AppendBuffer<T>::data() noexcept { return m_buffer.data(); } template <class T> inline const T* AppendBuffer<T>::data() const noexcept { return m_buffer.data(); } template <class T> inline void AppendBuffer<T>::append(const T* append_data, size_t append_data_size) { m_buffer.reserve_extra(m_size, append_data_size); // Throws std::copy_n(append_data, append_data_size, m_buffer.data() + m_size); m_size += append_data_size; } template <class T> inline void AppendBuffer<T>::reserve(size_t min_capacity) { m_buffer.reserve(m_size, min_capacity); } template <class T> inline void AppendBuffer<T>::resize(size_t new_size) { reserve(new_size); m_size = new_size; } template <class T> inline void AppendBuffer<T>::clear() noexcept { m_size = 0; } } // namespace util } // namespace realm #endif // REALM_UTIL_BUFFER_HPP <commit_msg>Add AppendBuffer<T>::release()<commit_after>/************************************************************************* * * Copyright 2016 Realm Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **************************************************************************/ #ifndef REALM_UTIL_BUFFER_HPP #define REALM_UTIL_BUFFER_HPP #include <cstddef> #include <algorithm> #include <exception> #include <limits> #include <utility> #include <realm/util/features.h> #include <realm/util/safe_int_ops.hpp> #include <memory> namespace realm { namespace util { /// A simple buffer concept that owns a region of memory and knows its /// size. template <class T> class Buffer { public: Buffer() noexcept : m_size(0) { } explicit Buffer(size_t initial_size); Buffer(Buffer<T>&&) noexcept = default; ~Buffer() noexcept { } Buffer<T>& operator=(Buffer<T>&&) noexcept = default; T& operator[](size_t i) noexcept { return m_data[i]; } const T& operator[](size_t i) const noexcept { return m_data[i]; } T* data() noexcept { return m_data.get(); } const T* data() const noexcept { return m_data.get(); } size_t size() const noexcept { return m_size; } /// False iff the data() returns null. explicit operator bool() const noexcept { return bool(m_data); } /// Discards the original contents. void set_size(size_t new_size); /// \param new_size Specifies the new buffer size. /// \param copy_begin, copy_end Specifies a range of element /// values to be retained. \a copy_end must be less than, or equal /// to size(). /// /// \param copy_to Specifies where the retained range should be /// copied to. `\a copy_to + \a copy_end - \a copy_begin` must be /// less than, or equal to \a new_size. void resize(size_t new_size, size_t copy_begin, size_t copy_end, size_t copy_to); void reserve(size_t used_size, size_t min_capacity); void reserve_extra(size_t used_size, size_t min_extra_capacity); T* release() noexcept; friend void swap(Buffer& a, Buffer& b) noexcept { using std::swap; swap(a.m_data, b.m_data); swap(a.m_size, b.m_size); } private: std::unique_ptr<T[]> m_data; size_t m_size; }; /// A buffer that can be efficiently resized. It acheives this by /// using an underlying buffer that may be larger than the logical /// size, and is automatically expanded in progressively larger steps. template <class T> class AppendBuffer { public: AppendBuffer() noexcept; ~AppendBuffer() noexcept { } /// Returns the current size of the buffer. size_t size() const noexcept; /// Gives read and write access to the elements. T* data() noexcept; /// Gives read access the elements. const T* data() const noexcept; /// Append the specified elements. This increases the size of this /// buffer by \a append_data_size. If the caller has previously requested /// a minimum capacity that is greater than, or equal to the /// resulting size, this function is guaranteed to not throw. void append(const T* append_data, size_t append_data_size); /// If the specified size is less than the current size, then the /// buffer contents is truncated accordingly. If the specified /// size is greater than the current size, then the extra elements /// will have undefined values. If the caller has previously /// requested a minimum capacity that is greater than, or equal to /// the specified size, this function is guaranteed to not throw. void resize(size_t new_size); /// This operation does not change the size of the buffer as /// returned by size(). If the specified capacity is less than the /// current capacity, this operation has no effect. void reserve(size_t min_capacity); /// Set the size to zero. The capacity remains unchanged. void clear() noexcept; /// Release the underlying buffer and reset the size. Note: The returned /// buffer may be larger than the amount of data appended to this buffer. /// Callers should call `size()` prior to releasing the buffer to know the /// usable/logical size. Buffer<T> release() noexcept; private: util::Buffer<T> m_buffer; size_t m_size; }; // Implementation: class BufferSizeOverflow : public std::exception { public: const char* what() const noexcept override { return "Buffer size overflow"; } }; template <class T> inline Buffer<T>::Buffer(size_t initial_size) : m_data(new T[initial_size]) // Throws , m_size(initial_size) { } template <class T> inline void Buffer<T>::set_size(size_t new_size) { m_data.reset(new T[new_size]); // Throws m_size = new_size; } template <class T> inline void Buffer<T>::resize(size_t new_size, size_t copy_begin, size_t copy_end, size_t copy_to) { std::unique_ptr<T[]> new_data(new T[new_size]); // Throws std::copy_n(m_data.get() + copy_begin, copy_end - copy_begin, new_data.get() + copy_to); m_data.reset(new_data.release()); m_size = new_size; } template <class T> inline void Buffer<T>::reserve(size_t used_size, size_t min_capacity) { size_t current_capacity = m_size; if (REALM_LIKELY(current_capacity >= min_capacity)) return; size_t new_capacity = current_capacity; // Use growth factor 1.5. if (REALM_UNLIKELY(int_multiply_with_overflow_detect(new_capacity, 3))) new_capacity = std::numeric_limits<size_t>::max(); new_capacity /= 2; if (REALM_UNLIKELY(new_capacity < min_capacity)) new_capacity = min_capacity; resize(new_capacity, 0, used_size, 0); // Throws } template <class T> inline void Buffer<T>::reserve_extra(size_t used_size, size_t min_extra_capacity) { size_t min_capacity = used_size; if (REALM_UNLIKELY(int_add_with_overflow_detect(min_capacity, min_extra_capacity))) throw BufferSizeOverflow(); reserve(used_size, min_capacity); // Throws } template <class T> inline T* Buffer<T>::release() noexcept { m_size = 0; return m_data.release(); } template <class T> inline AppendBuffer<T>::AppendBuffer() noexcept : m_size(0) { } template <class T> inline size_t AppendBuffer<T>::size() const noexcept { return m_size; } template <class T> inline T* AppendBuffer<T>::data() noexcept { return m_buffer.data(); } template <class T> inline const T* AppendBuffer<T>::data() const noexcept { return m_buffer.data(); } template <class T> inline void AppendBuffer<T>::append(const T* append_data, size_t append_data_size) { m_buffer.reserve_extra(m_size, append_data_size); // Throws std::copy_n(append_data, append_data_size, m_buffer.data() + m_size); m_size += append_data_size; } template <class T> inline void AppendBuffer<T>::reserve(size_t min_capacity) { m_buffer.reserve(m_size, min_capacity); } template <class T> inline void AppendBuffer<T>::resize(size_t new_size) { reserve(new_size); m_size = new_size; } template <class T> inline void AppendBuffer<T>::clear() noexcept { m_size = 0; } template <class T> inline Buffer<T> AppendBuffer<T>::release() noexcept { m_size = 0; return std::move(m_buffer); } } // namespace util } // namespace realm #endif // REALM_UTIL_BUFFER_HPP <|endoftext|>
<commit_before>#include <iostream> #include <vector> #include <map> #include <node.h> #include "PSATResult.h" #include "calculator/EstimateFLA.h" #include "calculator/MotorCurrent.h" #include "calculator/MotorPowerFactor.h" #include "calculator/OptimalPrePumpEff.h" #include "calculator/OptimalSpecificSpeedCorrection.h" #include "calculator/OptimalDeviationFactor.h" using namespace v8; using namespace std; Isolate* iso; Local<Object> inp; Local<Object> r; double Get(const char *nm) { auto rObj = inp->ToObject()->Get(String::NewFromUtf8(iso,nm)); if (rObj->IsUndefined()) { cout << nm << endl;; assert(!"defined"); } return rObj->NumberValue(); } double SetR(const char *nm, double n) { r->Set(String::NewFromUtf8(iso,nm),Number::New(iso,n)); } Motor::LineFrequency line() { return (Motor::LineFrequency)(int)(!Get("line")); } Motor::EfficiencyClass effCls() { return (Motor::EfficiencyClass)(int)Get("efficiency_class"); } Pump::Drive drive() { return (Pump::Drive)(int)Get("drive"); } Pump::Style style() { return (Pump::Style)(int)Get("pump_style"); } void Setup(const FunctionCallbackInfo<Value>& args) { iso = args.GetIsolate(); inp = args[0]->ToObject(); r = Object::New(iso); args.GetReturnValue().Set(r); } void Results(const FunctionCallbackInfo<Value>& args) { Setup(args); Pump pump(style(),Get("pump_specified"),Get("pump_rated_speed"),drive(), Get("viscosity"),Get("specific_gravity"),Get("stages"),(Pump::Speed)(int)(!Get("fixed_speed"))); Motor motor(line(),Get("motor_rated_power"),Get("motor_rated_speed"),effCls(), Get("efficiency"),Get("motor_rated_voltage"),Get("motor_rated_flc"),Get("margin")); Financial fin(Get("fraction"),Get("cost")); FieldData fd(Get("flow"),Get("head"),(FieldData::LoadEstimationMethod)(Get("motor_field_power")>0?0:1), Get("motor_field_power"),Get("motor_field_current"),Get("motor_field_voltage")); PSATResult psat(pump,motor,fin,fd); psat.calculateExisting(); psat.calculateOptimal(); auto ex = psat.getExisting(), opt = psat.getOptimal(); map<const char *,vector<double>> out = { {"Pump Efficiency",{ex.pumpEfficiency_*100,opt.pumpEfficiency_*100}}, {"Motor Rated Power",{ex.motorRatedPower_,opt.motorRatedPower_}}, {"Motor Shaft Power",{ex.motorShaftPower_,opt.motorShaftPower_}}, {"Pump Shaft Power",{ex.pumpShaftPower_,opt.pumpShaftPower_}}, {"Motor Efficiency",{ex.motorEfficiency_,opt.motorEfficiency_}}, {"Motor Power Factor",{ex.motorPowerFactor_,opt.motorPowerFactor_}}, {"Motor Current",{ex.motorCurrent_,opt.motorCurrent_}}, {"Motor Power", {ex.motorPower_,opt.motorPower_}}, {"Annual Energy", {ex.annualEnergy_,opt.annualEnergy_}}, {"Annual Cost", {ex.annualCost_*1000,opt.annualCost_*1000}}, {"Savings Potential", {psat.getAnnualSavingsPotential(),-1}}, {"Optimization Rating", {psat.getOptimizationRating(),-1}} }; for(auto p: out) { auto a = Array::New(iso); a->Set(0,Number::New(iso,p.second[0])); a->Set(1,Number::New(iso,p.second[1])); r->Set(String::NewFromUtf8(iso,p.first),a); } } void EstFLA(const FunctionCallbackInfo<Value>& args) { Setup(args); EstimateFLA fla(Get("motor_rated_power"),Get("motor_rated_speed"),line(),effCls(), Get("efficiency"),Get("motor_rated_voltage")); fla.calculate(); args.GetReturnValue().Set(fla.getEstimatedFLA()); } void MotorPerformance(const FunctionCallbackInfo<Value>& args) { Setup(args); MotorEfficiency mef(line(),Get("motor_rated_speed"),effCls(),Get("efficiency"),Get("motor_rated_power"),Get("load_factor")); auto mefVal = mef.calculate(); SetR("efficiency",mefVal*100); MotorCurrent mc(Get("motor_rated_power"),Get("motor_rated_speed"),line(),effCls(),Get("efficiency"),Get("load_factor"),Get("motor_rated_voltage"),Get("flc")); auto mcVal = mc.calculate(); SetR("current",mcVal/225.8*100); MotorPowerFactor pf(Get("motor_rated_power"),Get("load_factor"),mcVal,mefVal,Get("motor_rated_voltage")); SetR("pf",pf.calculate()*100); } void PumpEfficiency(const FunctionCallbackInfo<Value>& args) { Setup(args); OptimalPrePumpEff pef(style(), Get("pump_specified"), Get("flow")); auto v = pef.calculate(); SetR("average",v); //OptimalDeviationFactor df(Get("flow")); SetR("max",v*OptimalDeviationFactor(Get("flow")).calculate()); } void AchievableEfficiency(const FunctionCallbackInfo<Value>& args) { Setup(args); //OptimalPrePumpEff pef(style(), Get("pump_specified"), Get("flow")); //auto v = pef.calculate(); //cout << OptimalSpecificSpeedCorrection(Pump::Style::END_SUCTION_ANSI_API, Get("specific_speed")).calculate() << endl; args.GetReturnValue().Set( OptimalSpecificSpeedCorrection(Pump::Style::END_SUCTION_ANSI_API, Get("specific_speed")).calculate()*100); //OptimalDeviationFactor df(Get("flow")); //SetR("max",v*OptimalDeviationFactor(Get("flow")).calculate()); } void Nema(const FunctionCallbackInfo<Value>& args) { Setup(args); args.GetReturnValue().Set( MotorEfficiency(line(),Get("motor_rated_speed"),Motor::EfficiencyClass::ENERGY_EFFICIENT,0,200,1).calculate() ); } //TODO round vs js round; loosen up to make next test case void Check(double exp, double act, const char* nm="") { //cout << "e " << exp << "; a " << act << endl; // if (isnan(act) || (abs(exp-act)>.01*exp)) { auto p = 10; if (isnan(act) || ( (round(exp*p)/p)!=round(act*p)/p)) { printf("\"%s\" TEST FAILED: %f %f\n",nm,exp,act); assert(!"equal"); } } void Check100(double exp, double act, const char* nm="") { Check(exp,act*100,nm); } void Test(const FunctionCallbackInfo<Value>& args) { EstimateFLA fla(200,1780,(Motor::LineFrequency)1,(Motor::EfficiencyClass)(1),0,460); fla.calculate(); Check(225.8,fla.getEstimatedFLA()); // motor perf { MotorPowerFactor pf(200,0,.28*225.8,0,460); //cout << pf.calculate(); //Check100(0,pf.calculate()); MotorCurrent mc(200,1780,Motor::LineFrequency::FREQ60,Motor::EfficiencyClass::ENERGY_EFFICIENT,0,.25,460,225.8); auto mcVal = mc.calculate(); Check100(36.11,mcVal/225.8); } { MotorEfficiency mef(Motor::LineFrequency::FREQ60,1780,Motor::EfficiencyClass::ENERGY_EFFICIENT,0,200,.75); auto mefVal = mef.calculate(); Check100(95.69,mefVal); MotorCurrent mc(200,1780,Motor::LineFrequency::FREQ60,Motor::EfficiencyClass::ENERGY_EFFICIENT,0,.75,460,225.8); auto mcVal = mc.calculate(); Check100(76.63,mcVal/225.8); MotorPowerFactor pf(200,.75,mcVal,mefVal,460); Check100(84.82,pf.calculate()); } //nema { MotorEfficiency mef(Motor::LineFrequency::FREQ60,1200, Motor::EfficiencyClass::ENERGY_EFFICIENT,0,200,1); //Check100(95,mef.calculate()); } //pump eff { OptimalPrePumpEff pef(Pump::Style::END_SUCTION_ANSI_API, 0, 2000); OptimalDeviationFactor df(2000); // Check(87.1,pef.calculate()*df.calculate()); } //spec speed { OptimalSpecificSpeedCorrection cor(Pump::Style::END_SUCTION_ANSI_API, 1170); //Check100(2.3,cor.calculate()); } return; #define BASE \ Pump pump(Pump::Style::END_SUCTION_ANSI_API,0,1780,Pump::Drive::DIRECT_DRIVE,\ 1,1,1,Pump::Speed::NOT_FIXED_SPEED);\ Motor motor(Motor::LineFrequency::FREQ60,200,1780,\ Motor::EfficiencyClass::ENERGY_EFFICIENT,0,460,225.8,0);\ Financial fin(1,.05);\ FieldData fd(2000,277,FieldData::LoadEstimationMethod::POWER,\ 150,0,460); #define CALC \ PSATResult psat(pump,motor,fin,fd);\ psat.calculateExisting();\ auto ex = psat.getExisting(); for (int i=1; i<=10000; i=i+2) { BASE CALC Check(ex.motorShaftPower_,ex.motorShaftPower_,"SAME"); } { BASE motor.setMotorRpm(1786); fd.setMotorPower(80); CALC Check(101.9,ex.motorShaftPower_); Check100(95,ex.motorEfficiency_); Check100(79.1,ex.motorPowerFactor_); Check(127,ex.motorCurrent_); } { BASE fd.setMotorPower(80); motor.setMotorRatedPower(100); motor.setFullLoadAmps(113.8); CALC Check(101.8,ex.motorShaftPower_); Check100(94.9,ex.motorEfficiency_); Check100(86.7,ex.motorPowerFactor_); Check(115.8,ex.motorCurrent_); } { BASE fd.setMotorPower(80); fd.setVoltage(260); CALC Check(101.9,ex.motorShaftPower_); Check100(95,ex.motorEfficiency_); Check100(138.8,ex.motorPowerFactor_); Check(128,ex.motorCurrent_); } { BASE motor.setMotorRpm(1200); fd.setMotorPower(80); motor.setFullLoadAmps(235.3); CALC Check(101.4,ex.motorShaftPower_); Check100(94.5,ex.motorEfficiency_); Check100(74.3,ex.motorPowerFactor_); Check(135.1,ex.motorCurrent_); } { BASE fd.setMotorPower(111.855); CALC Check(143.4,ex.motorShaftPower_); Check100(95.6,ex.motorEfficiency_); Check100(84.3,ex.motorPowerFactor_); Check(166.5,ex.motorCurrent_); } { BASE fd.setMotorPower(80); motor.setMotorRatedVoltage(200); motor.setFullLoadAmps(519.3); CALC Check(101.9,ex.motorShaftPower_); Check100(95,ex.motorEfficiency_); Check100(35.2,ex.motorPowerFactor_); Check(284.9,ex.motorCurrent_); } { BASE CALC Check(217.5,ex.motorCurrent_); } { BASE fd.setLoadEstimationMethod(FieldData::LoadEstimationMethod::CURRENT); fd.setMotorAmps(218); fd.setMotorPower(0); CALC Check(150.4,ex.motorPower_); Check100(72.5,ex.pumpEfficiency_); } { BASE fd.setMotorPower(80); CALC Check(700.8,ex.annualEnergy_); } { BASE fin.setOperatingFraction(.25); CALC Check(328.5,ex.annualEnergy_); Check(16.4,ex.annualCost_); } { BASE motor.setFullLoadAmps(300); CALC Check(288.9,ex.motorCurrent_); } { BASE motor.setEfficiencyClass(Motor::EfficiencyClass(0)); CALC Check(213.7,ex.motorCurrent_); } { BASE motor.setEfficiencyClass(Motor::EfficiencyClass(2)); motor.setSpecifiedEfficiency(75); CALC Check(173.7,ex.motorCurrent_); } cout << "done"; } void Wtf(const FunctionCallbackInfo<Value>& args) { } void Init(Local<Object> exports) { NODE_SET_METHOD(exports, "results", Results); NODE_SET_METHOD(exports, "estFLA", EstFLA); NODE_SET_METHOD(exports, "motorPerformance", MotorPerformance); NODE_SET_METHOD(exports, "pumpEfficiency", PumpEfficiency); NODE_SET_METHOD(exports, "achievableEfficiency", AchievableEfficiency); NODE_SET_METHOD(exports, "nema", Nema); NODE_SET_METHOD(exports, "test", Test); NODE_SET_METHOD(exports, "wtf", Wtf); } NODE_MODULE(bridge, Init) <commit_msg>no message<commit_after>#include <iostream> #include <vector> #include <map> #include <node.h> #include "PSATResult.h" #include "calculator/EstimateFLA.h" #include "calculator/MotorCurrent.h" #include "calculator/MotorPowerFactor.h" #include "calculator/OptimalPrePumpEff.h" #include "calculator/OptimalSpecificSpeedCorrection.h" #include "calculator/OptimalDeviationFactor.h" using namespace v8; using namespace std; Isolate* iso; Local<Object> inp; Local<Object> r; double Get(const char *nm) { auto rObj = inp->ToObject()->Get(String::NewFromUtf8(iso,nm)); if (rObj->IsUndefined()) { cout << nm << endl;; assert(!"defined"); } return rObj->NumberValue(); } double SetR(const char *nm, double n) { r->Set(String::NewFromUtf8(iso,nm),Number::New(iso,n)); } Motor::LineFrequency line() { return (Motor::LineFrequency)(int)(!Get("line")); } Motor::EfficiencyClass effCls() { return (Motor::EfficiencyClass)(int)Get("efficiency_class"); } Pump::Drive drive() { return (Pump::Drive)(int)Get("drive"); } Pump::Style style() { return (Pump::Style)(int)Get("pump_style"); } void Setup(const FunctionCallbackInfo<Value>& args) { iso = args.GetIsolate(); inp = args[0]->ToObject(); r = Object::New(iso); args.GetReturnValue().Set(r); } void Results(const FunctionCallbackInfo<Value>& args) { Setup(args); Pump pump(style(),Get("pump_specified"),Get("pump_rated_speed"),drive(), Get("viscosity"),Get("specific_gravity"),Get("stages"),(Pump::Speed)(int)(!Get("fixed_speed"))); Motor motor(line(),Get("motor_rated_power"),Get("motor_rated_speed"),effCls(), Get("efficiency"),Get("motor_rated_voltage"),Get("motor_rated_flc"),Get("margin")); Financial fin(Get("fraction"),Get("cost")); FieldData fd(Get("flow"),Get("head"),(FieldData::LoadEstimationMethod)(Get("motor_field_power")>0?0:1), Get("motor_field_power"),Get("motor_field_current"),Get("motor_field_voltage")); PSATResult psat(pump,motor,fin,fd); psat.calculateExisting(); psat.calculateOptimal(); auto ex = psat.getExisting(), opt = psat.getOptimal(); map<const char *,vector<double>> out = { {"Pump Efficiency",{ex.pumpEfficiency_*100,opt.pumpEfficiency_*100}}, {"Motor Rated Power",{ex.motorRatedPower_,opt.motorRatedPower_}}, {"Motor Shaft Power",{ex.motorShaftPower_,opt.motorShaftPower_}}, {"Pump Shaft Power",{ex.pumpShaftPower_,opt.pumpShaftPower_}}, {"Motor Efficiency",{ex.motorEfficiency_,opt.motorEfficiency_}}, {"Motor Power Factor",{ex.motorPowerFactor_,opt.motorPowerFactor_}}, {"Motor Current",{ex.motorCurrent_,opt.motorCurrent_}}, {"Motor Power", {ex.motorPower_,opt.motorPower_}}, {"Annual Energy", {ex.annualEnergy_,opt.annualEnergy_}}, {"Annual Cost", {ex.annualCost_*1000,opt.annualCost_*1000}}, {"Savings Potential", {psat.getAnnualSavingsPotential(),-1}}, {"Optimization Rating", {psat.getOptimizationRating(),-1}} }; for(auto p: out) { auto a = Array::New(iso); a->Set(0,Number::New(iso,p.second[0])); a->Set(1,Number::New(iso,p.second[1])); r->Set(String::NewFromUtf8(iso,p.first),a); } } void EstFLA(const FunctionCallbackInfo<Value>& args) { Setup(args); EstimateFLA fla(Get("motor_rated_power"),Get("motor_rated_speed"),line(),effCls(), Get("efficiency"),Get("motor_rated_voltage")); fla.calculate(); args.GetReturnValue().Set(fla.getEstimatedFLA()); } void MotorPerformance(const FunctionCallbackInfo<Value>& args) { Setup(args); MotorEfficiency mef(line(),Get("motor_rated_speed"),effCls(),Get("efficiency"),Get("motor_rated_power"),Get("load_factor")); auto mefVal = mef.calculate(); SetR("efficiency",mefVal*100); MotorCurrent mc(Get("motor_rated_power"),Get("motor_rated_speed"),line(),effCls(),Get("efficiency"),Get("load_factor"),Get("motor_rated_voltage"),Get("flc")); auto mcVal = mc.calculate(); SetR("current",mcVal/225.8*100); MotorPowerFactor pf(Get("motor_rated_power"),Get("load_factor"),mcVal,mefVal,Get("motor_rated_voltage")); SetR("pf",pf.calculate()*100); } void PumpEfficiency(const FunctionCallbackInfo<Value>& args) { Setup(args); OptimalPrePumpEff pef(style(), Get("pump_specified"), Get("flow")); auto v = pef.calculate(); SetR("average",v); //OptimalDeviationFactor df(Get("flow")); SetR("max",v*OptimalDeviationFactor(Get("flow")).calculate()); } void AchievableEfficiency(const FunctionCallbackInfo<Value>& args) { Setup(args); //OptimalPrePumpEff pef(style(), Get("pump_specified"), Get("flow")); //auto v = pef.calculate(); //cout << OptimalSpecificSpeedCorrection(Pump::Style::END_SUCTION_ANSI_API, Get("specific_speed")).calculate() << endl; args.GetReturnValue().Set( OptimalSpecificSpeedCorrection(Pump::Style::END_SUCTION_ANSI_API, Get("specific_speed")).calculate()*100); //OptimalDeviationFactor df(Get("flow")); //SetR("max",v*OptimalDeviationFactor(Get("flow")).calculate()); } void Nema(const FunctionCallbackInfo<Value>& args) { Setup(args); args.GetReturnValue().Set( MotorEfficiency(line(),Get("motor_rated_speed"),effCls(),0,200,1).calculate() ); } //TODO round vs js round; loosen up to make next test case void Check(double exp, double act, const char* nm="") { //cout << "e " << exp << "; a " << act << endl; // if (isnan(act) || (abs(exp-act)>.01*exp)) { auto p = 10; if (isnan(act) || ( (round(exp*p)/p)!=round(act*p)/p)) { printf("\"%s\" TEST FAILED: %f %f\n",nm,exp,act); assert(!"equal"); } } void Check100(double exp, double act, const char* nm="") { Check(exp,act*100,nm); } void Test(const FunctionCallbackInfo<Value>& args) { EstimateFLA fla(200,1780,(Motor::LineFrequency)1,(Motor::EfficiencyClass)(1),0,460); fla.calculate(); Check(225.8,fla.getEstimatedFLA()); // motor perf { MotorPowerFactor pf(200,0,.28*225.8,0,460); //cout << pf.calculate(); //Check100(0,pf.calculate()); MotorCurrent mc(200,1780,Motor::LineFrequency::FREQ60,Motor::EfficiencyClass::ENERGY_EFFICIENT,0,.25,460,225.8); auto mcVal = mc.calculate(); Check100(36.11,mcVal/225.8); } { MotorEfficiency mef(Motor::LineFrequency::FREQ60,1780,Motor::EfficiencyClass::ENERGY_EFFICIENT,0,200,.75); auto mefVal = mef.calculate(); Check100(95.69,mefVal); MotorCurrent mc(200,1780,Motor::LineFrequency::FREQ60,Motor::EfficiencyClass::ENERGY_EFFICIENT,0,.75,460,225.8); auto mcVal = mc.calculate(); Check100(76.63,mcVal/225.8); MotorPowerFactor pf(200,.75,mcVal,mefVal,460); Check100(84.82,pf.calculate()); } //nema { MotorEfficiency mef(Motor::LineFrequency::FREQ60,1200, Motor::EfficiencyClass::ENERGY_EFFICIENT,0,200,1); //Check100(95,mef.calculate()); } //pump eff { OptimalPrePumpEff pef(Pump::Style::END_SUCTION_ANSI_API, 0, 2000); OptimalDeviationFactor df(2000); // Check(87.1,pef.calculate()*df.calculate()); } //spec speed { OptimalSpecificSpeedCorrection cor(Pump::Style::END_SUCTION_ANSI_API, 1170); //Check100(2.3,cor.calculate()); } return; #define BASE \ Pump pump(Pump::Style::END_SUCTION_ANSI_API,0,1780,Pump::Drive::DIRECT_DRIVE,\ 1,1,1,Pump::Speed::NOT_FIXED_SPEED);\ Motor motor(Motor::LineFrequency::FREQ60,200,1780,\ Motor::EfficiencyClass::ENERGY_EFFICIENT,0,460,225.8,0);\ Financial fin(1,.05);\ FieldData fd(2000,277,FieldData::LoadEstimationMethod::POWER,\ 150,0,460); #define CALC \ PSATResult psat(pump,motor,fin,fd);\ psat.calculateExisting();\ auto ex = psat.getExisting(); for (int i=1; i<=10000; i=i+2) { BASE CALC Check(ex.motorShaftPower_,ex.motorShaftPower_,"SAME"); } { BASE motor.setMotorRpm(1786); fd.setMotorPower(80); CALC Check(101.9,ex.motorShaftPower_); Check100(95,ex.motorEfficiency_); Check100(79.1,ex.motorPowerFactor_); Check(127,ex.motorCurrent_); } { BASE fd.setMotorPower(80); motor.setMotorRatedPower(100); motor.setFullLoadAmps(113.8); CALC Check(101.8,ex.motorShaftPower_); Check100(94.9,ex.motorEfficiency_); Check100(86.7,ex.motorPowerFactor_); Check(115.8,ex.motorCurrent_); } { BASE fd.setMotorPower(80); fd.setVoltage(260); CALC Check(101.9,ex.motorShaftPower_); Check100(95,ex.motorEfficiency_); Check100(138.8,ex.motorPowerFactor_); Check(128,ex.motorCurrent_); } { BASE motor.setMotorRpm(1200); fd.setMotorPower(80); motor.setFullLoadAmps(235.3); CALC Check(101.4,ex.motorShaftPower_); Check100(94.5,ex.motorEfficiency_); Check100(74.3,ex.motorPowerFactor_); Check(135.1,ex.motorCurrent_); } { BASE fd.setMotorPower(111.855); CALC Check(143.4,ex.motorShaftPower_); Check100(95.6,ex.motorEfficiency_); Check100(84.3,ex.motorPowerFactor_); Check(166.5,ex.motorCurrent_); } { BASE fd.setMotorPower(80); motor.setMotorRatedVoltage(200); motor.setFullLoadAmps(519.3); CALC Check(101.9,ex.motorShaftPower_); Check100(95,ex.motorEfficiency_); Check100(35.2,ex.motorPowerFactor_); Check(284.9,ex.motorCurrent_); } { BASE CALC Check(217.5,ex.motorCurrent_); } { BASE fd.setLoadEstimationMethod(FieldData::LoadEstimationMethod::CURRENT); fd.setMotorAmps(218); fd.setMotorPower(0); CALC Check(150.4,ex.motorPower_); Check100(72.5,ex.pumpEfficiency_); } { BASE fd.setMotorPower(80); CALC Check(700.8,ex.annualEnergy_); } { BASE fin.setOperatingFraction(.25); CALC Check(328.5,ex.annualEnergy_); Check(16.4,ex.annualCost_); } { BASE motor.setFullLoadAmps(300); CALC Check(288.9,ex.motorCurrent_); } { BASE motor.setEfficiencyClass(Motor::EfficiencyClass(0)); CALC Check(213.7,ex.motorCurrent_); } { BASE motor.setEfficiencyClass(Motor::EfficiencyClass(2)); motor.setSpecifiedEfficiency(75); CALC Check(173.7,ex.motorCurrent_); } cout << "done"; } void Wtf(const FunctionCallbackInfo<Value>& args) { } void Init(Local<Object> exports) { NODE_SET_METHOD(exports, "results", Results); NODE_SET_METHOD(exports, "estFLA", EstFLA); NODE_SET_METHOD(exports, "motorPerformance", MotorPerformance); NODE_SET_METHOD(exports, "pumpEfficiency", PumpEfficiency); NODE_SET_METHOD(exports, "achievableEfficiency", AchievableEfficiency); NODE_SET_METHOD(exports, "nema", Nema); NODE_SET_METHOD(exports, "test", Test); NODE_SET_METHOD(exports, "wtf", Wtf); } NODE_MODULE(bridge, Init) <|endoftext|>
<commit_before>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file whisperMessage.cpp * @author Vladislav Gluhovsky <vlad@ethdev.com> * @date June 2015 */ #include <boost/test/unit_test.hpp> #include <libdevcore/SHA3.h> #include <libwhisper/BloomFilter.h> using namespace std; using namespace dev; using namespace dev::shh; void testAddNonExisting(TopicBloomFilter& _f, AbridgedTopic const& _h) { BOOST_REQUIRE(!_f.containsRaw(_h)); _f.addRaw(_h); BOOST_REQUIRE(_f.containsRaw(_h)); } void testRemoveExisting(TopicBloomFilter& _f, AbridgedTopic const& _h) { BOOST_REQUIRE(_f.containsRaw(_h)); _f.removeRaw(_h); BOOST_REQUIRE(!_f.containsRaw(_h)); } void testAddNonExistingBloom(TopicBloomFilter& _f, AbridgedTopic const& _h) { BOOST_REQUIRE(!_f.containsBloom(_h)); _f.addBloom(_h); BOOST_REQUIRE(_f.containsBloom(_h)); } void testRemoveExistingBloom(TopicBloomFilter& _f, AbridgedTopic const& _h) { BOOST_REQUIRE(_f.containsBloom(_h)); _f.removeBloom(_h); BOOST_REQUIRE(!_f.containsBloom(_h)); } int calculateExpected(TopicBloomFilter const& f, int const n) { int const m = f.size * 8; // number of bits in the bloom int const k = f.BitsPerBloom; // number of hash functions (e.g. bits set to 1 in every bloom) double singleBitSet = 1.0 / m; // probability of any bit being set after inserting a single bit double singleBitNotSet = (1.0 - singleBitSet); double singleNot = 1; // single bit not set after inserting N elements in the bloom filter for (int i = 0; i < k * n; ++i) singleNot *= singleBitNotSet; double single = 1.0 - singleNot; // probability of a single bit being set after inserting N elements in the bloom filter double kBitsSet = 1; // probability of K bits being set after inserting N elements in the bloom filter for (int i = 0; i < k; ++i) kBitsSet *= single; return static_cast<int>(kBitsSet * 100 + 0.5); // in percents, rounded up } void testFalsePositiveRate(TopicBloomFilter const& f, int const inserted, Topic& x) { int const c_sampleSize = 1000; int falsePositive = 0; for (int i = 0; i < c_sampleSize; ++i) { x = sha3(x); AbridgedTopic a(x); if (f.containsBloom(a)) ++falsePositive; } falsePositive /= (c_sampleSize / 100); // in percents int expected = calculateExpected(f, inserted); int allowed = expected + (expected / 5); // allow deviations ~20% //cnote << "Inserted: " << inserted << ", False Positive Rate: " << falsePositive << ", Expected: " << expected; BOOST_REQUIRE(falsePositive <= allowed); } BOOST_AUTO_TEST_SUITE(bloomFilter) BOOST_AUTO_TEST_CASE(falsePositiveRate) { VerbosityHolder setTemporaryLevel(10); cnote << "Testing Bloom Filter False Positive Rate..."; TopicBloomFilter f; Topic x(0xABCDEF); // deterministic pseudorandom value for (int i = 1; i < 21; ++i) { x = sha3(x); f.addBloom(AbridgedTopic(x)); testFalsePositiveRate(f, i, x); } } BOOST_AUTO_TEST_CASE(bloomFilterRandom) { VerbosityHolder setTemporaryLevel(10); cnote << "Testing Bloom Filter matching..."; TopicBloomFilter f; vector<AbridgedTopic> vec; Topic x(0xDEADBEEF); int const c_rounds = 4; for (int i = 0; i < c_rounds; ++i, x = sha3(x)) vec.push_back(abridge(x)); for (int i = 0; i < c_rounds; ++i) testAddNonExisting(f, vec[i]); for (int i = 0; i < c_rounds; ++i) testRemoveExisting(f, vec[i]); for (int i = 0; i < c_rounds; ++i) testAddNonExistingBloom(f, vec[i]); for (int i = 0; i < c_rounds; ++i) testRemoveExistingBloom(f, vec[i]); } BOOST_AUTO_TEST_CASE(bloomFilterRaw) { VerbosityHolder setTemporaryLevel(10); cnote << "Testing Raw Bloom matching..."; TopicBloomFilter f; AbridgedTopic b00000001(0x01); AbridgedTopic b00010000(0x10); AbridgedTopic b00011000(0x18); AbridgedTopic b00110000(0x30); AbridgedTopic b00110010(0x32); AbridgedTopic b00111000(0x38); AbridgedTopic b00000110(0x06); AbridgedTopic b00110110(0x36); AbridgedTopic b00110111(0x37); testAddNonExisting(f, b00000001); testAddNonExisting(f, b00010000); testAddNonExisting(f, b00011000); testAddNonExisting(f, b00110000); BOOST_REQUIRE(f.contains(b00111000)); testAddNonExisting(f, b00110010); testAddNonExisting(f, b00000110); BOOST_REQUIRE(f.contains(b00110110)); BOOST_REQUIRE(f.contains(b00110111)); f.removeRaw(b00000001); f.removeRaw(b00000001); f.removeRaw(b00000001); BOOST_REQUIRE(!f.contains(b00000001)); BOOST_REQUIRE(f.contains(b00010000)); BOOST_REQUIRE(f.contains(b00011000)); BOOST_REQUIRE(f.contains(b00110000)); BOOST_REQUIRE(f.contains(b00110010)); BOOST_REQUIRE(f.contains(b00111000)); BOOST_REQUIRE(f.contains(b00000110)); BOOST_REQUIRE(f.contains(b00110110)); BOOST_REQUIRE(!f.contains(b00110111)); f.removeRaw(b00010000); BOOST_REQUIRE(!f.contains(b00000001)); BOOST_REQUIRE(f.contains(b00010000)); BOOST_REQUIRE(f.contains(b00011000)); BOOST_REQUIRE(f.contains(b00110000)); BOOST_REQUIRE(f.contains(b00110010)); BOOST_REQUIRE(f.contains(b00111000)); BOOST_REQUIRE(f.contains(b00000110)); BOOST_REQUIRE(f.contains(b00110110)); BOOST_REQUIRE(!f.contains(b00110111)); f.removeRaw(b00111000); BOOST_REQUIRE(!f.contains(b00000001)); BOOST_REQUIRE(f.contains(b00010000)); BOOST_REQUIRE(!f.contains(b00011000)); BOOST_REQUIRE(f.contains(b00110000)); BOOST_REQUIRE(f.contains(b00110010)); BOOST_REQUIRE(!f.contains(b00111000)); BOOST_REQUIRE(f.contains(b00000110)); BOOST_REQUIRE(f.contains(b00110110)); BOOST_REQUIRE(!f.contains(b00110111)); f.addRaw(b00000001); BOOST_REQUIRE(f.contains(b00000001)); BOOST_REQUIRE(f.contains(b00010000)); BOOST_REQUIRE(!f.contains(b00011000)); BOOST_REQUIRE(f.contains(b00110000)); BOOST_REQUIRE(f.contains(b00110010)); BOOST_REQUIRE(!f.contains(b00111000)); BOOST_REQUIRE(f.contains(b00000110)); BOOST_REQUIRE(f.contains(b00110110)); BOOST_REQUIRE(f.contains(b00110111)); f.removeRaw(b00110111); BOOST_REQUIRE(!f.contains(b00000001)); BOOST_REQUIRE(f.contains(b00010000)); BOOST_REQUIRE(!f.contains(b00011000)); BOOST_REQUIRE(!f.contains(b00110000)); BOOST_REQUIRE(!f.contains(b00110010)); BOOST_REQUIRE(!f.contains(b00111000)); BOOST_REQUIRE(!f.contains(b00000110)); BOOST_REQUIRE(!f.contains(b00110110)); BOOST_REQUIRE(!f.contains(b00110111)); f.removeRaw(b00110111); BOOST_REQUIRE(!f.contains(b00000001)); BOOST_REQUIRE(!f.contains(b00010000)); BOOST_REQUIRE(!f.contains(b00011000)); BOOST_REQUIRE(!f.contains(b00110000)); BOOST_REQUIRE(!f.contains(b00110010)); BOOST_REQUIRE(!f.contains(b00111000)); BOOST_REQUIRE(!f.contains(b00000110)); BOOST_REQUIRE(!f.contains(b00110110)); BOOST_REQUIRE(!f.contains(b00110111)); } BOOST_AUTO_TEST_SUITE_END()<commit_msg>made TopicBloomFilter a template<commit_after>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file whisperMessage.cpp * @author Vladislav Gluhovsky <vlad@ethdev.com> * @date June 2015 */ #include <boost/test/unit_test.hpp> #include <libdevcore/SHA3.h> #include <libwhisper/BloomFilter.h> using namespace std; using namespace dev; using namespace dev::shh; using TopicBloomFilterShort = TopicBloomFilterBase<4>; using TopicBloomFilterLong = TopicBloomFilterBase<8>; using TopicBloomFilterTest = TopicBloomFilterLong; void testAddNonExisting(TopicBloomFilterShort& _f, AbridgedTopic const& _h) { BOOST_REQUIRE(!_f.containsRaw(_h)); _f.addRaw(_h); BOOST_REQUIRE(_f.containsRaw(_h)); } void testRemoveExisting(TopicBloomFilterShort& _f, AbridgedTopic const& _h) { BOOST_REQUIRE(_f.containsRaw(_h)); _f.removeRaw(_h); BOOST_REQUIRE(!_f.containsRaw(_h)); } void testAddNonExistingBloom(TopicBloomFilterShort& _f, AbridgedTopic const& _h) { BOOST_REQUIRE(!_f.containsBloom(_h)); _f.addBloom(_h); BOOST_REQUIRE(_f.containsBloom(_h)); } void testRemoveExistingBloom(TopicBloomFilterShort& _f, AbridgedTopic const& _h) { BOOST_REQUIRE(_f.containsBloom(_h)); _f.removeBloom(_h); BOOST_REQUIRE(!_f.containsBloom(_h)); } int calculateExpected(TopicBloomFilterTest const& f, int const n) { int const m = f.size * 8; // number of bits in the bloom int const k = f.BitsPerBloom; // number of hash functions (e.g. bits set to 1 in every bloom) double singleBitSet = 1.0 / m; // probability of any bit being set after inserting a single bit double singleBitNotSet = (1.0 - singleBitSet); double singleNot = 1; // single bit not set after inserting N elements in the bloom filter for (int i = 0; i < k * n; ++i) singleNot *= singleBitNotSet; double single = 1.0 - singleNot; // probability of a single bit being set after inserting N elements in the bloom filter double kBitsSet = 1; // probability of K bits being set after inserting N elements in the bloom filter for (int i = 0; i < k; ++i) kBitsSet *= single; return static_cast<int>(kBitsSet * 100 + 0.5); // in percents, rounded up } void testFalsePositiveRate(TopicBloomFilterTest const& f, int const inserted, Topic& x) { int const c_sampleSize = 1000; int falsePositive = 0; for (int i = 0; i < c_sampleSize; ++i) { x = sha3(x); AbridgedTopic a(x); if (f.containsBloom(a)) ++falsePositive; } falsePositive /= (c_sampleSize / 100); // in percents int expected = calculateExpected(f, inserted); int allowed = expected + (expected / 5); // allow deviations ~20% //cnote << "Inserted: " << inserted << ", False Positive Rate: " << falsePositive << ", Expected: " << expected; BOOST_REQUIRE(falsePositive <= allowed); } BOOST_AUTO_TEST_SUITE(bloomFilter) BOOST_AUTO_TEST_CASE(falsePositiveRate) { VerbosityHolder setTemporaryLevel(10); cnote << "Testing Bloom Filter False Positive Rate..."; TopicBloomFilterTest f; Topic x(0xC0DEFEED); // deterministic pseudorandom value for (int i = 1; i < 21; ++i) { x = sha3(x); f.addBloom(AbridgedTopic(x)); testFalsePositiveRate(f, i, x); } } BOOST_AUTO_TEST_CASE(bloomFilterRandom) { VerbosityHolder setTemporaryLevel(10); cnote << "Testing Bloom Filter matching..."; TopicBloomFilterShort f; vector<AbridgedTopic> vec; Topic x(0xDEADBEEF); int const c_rounds = 4; for (int i = 0; i < c_rounds; ++i, x = sha3(x)) vec.push_back(abridge(x)); for (int i = 0; i < c_rounds; ++i) testAddNonExisting(f, vec[i]); for (int i = 0; i < c_rounds; ++i) testRemoveExisting(f, vec[i]); for (int i = 0; i < c_rounds; ++i) testAddNonExistingBloom(f, vec[i]); for (int i = 0; i < c_rounds; ++i) testRemoveExistingBloom(f, vec[i]); } BOOST_AUTO_TEST_CASE(bloomFilterRaw) { VerbosityHolder setTemporaryLevel(10); cnote << "Testing Raw Bloom matching..."; TopicBloomFilterShort f; AbridgedTopic b00000001(0x01); AbridgedTopic b00010000(0x10); AbridgedTopic b00011000(0x18); AbridgedTopic b00110000(0x30); AbridgedTopic b00110010(0x32); AbridgedTopic b00111000(0x38); AbridgedTopic b00000110(0x06); AbridgedTopic b00110110(0x36); AbridgedTopic b00110111(0x37); testAddNonExisting(f, b00000001); testAddNonExisting(f, b00010000); testAddNonExisting(f, b00011000); testAddNonExisting(f, b00110000); BOOST_REQUIRE(f.contains(b00111000)); testAddNonExisting(f, b00110010); testAddNonExisting(f, b00000110); BOOST_REQUIRE(f.contains(b00110110)); BOOST_REQUIRE(f.contains(b00110111)); f.removeRaw(b00000001); f.removeRaw(b00000001); f.removeRaw(b00000001); BOOST_REQUIRE(!f.contains(b00000001)); BOOST_REQUIRE(f.contains(b00010000)); BOOST_REQUIRE(f.contains(b00011000)); BOOST_REQUIRE(f.contains(b00110000)); BOOST_REQUIRE(f.contains(b00110010)); BOOST_REQUIRE(f.contains(b00111000)); BOOST_REQUIRE(f.contains(b00000110)); BOOST_REQUIRE(f.contains(b00110110)); BOOST_REQUIRE(!f.contains(b00110111)); f.removeRaw(b00010000); BOOST_REQUIRE(!f.contains(b00000001)); BOOST_REQUIRE(f.contains(b00010000)); BOOST_REQUIRE(f.contains(b00011000)); BOOST_REQUIRE(f.contains(b00110000)); BOOST_REQUIRE(f.contains(b00110010)); BOOST_REQUIRE(f.contains(b00111000)); BOOST_REQUIRE(f.contains(b00000110)); BOOST_REQUIRE(f.contains(b00110110)); BOOST_REQUIRE(!f.contains(b00110111)); f.removeRaw(b00111000); BOOST_REQUIRE(!f.contains(b00000001)); BOOST_REQUIRE(f.contains(b00010000)); BOOST_REQUIRE(!f.contains(b00011000)); BOOST_REQUIRE(f.contains(b00110000)); BOOST_REQUIRE(f.contains(b00110010)); BOOST_REQUIRE(!f.contains(b00111000)); BOOST_REQUIRE(f.contains(b00000110)); BOOST_REQUIRE(f.contains(b00110110)); BOOST_REQUIRE(!f.contains(b00110111)); f.addRaw(b00000001); BOOST_REQUIRE(f.contains(b00000001)); BOOST_REQUIRE(f.contains(b00010000)); BOOST_REQUIRE(!f.contains(b00011000)); BOOST_REQUIRE(f.contains(b00110000)); BOOST_REQUIRE(f.contains(b00110010)); BOOST_REQUIRE(!f.contains(b00111000)); BOOST_REQUIRE(f.contains(b00000110)); BOOST_REQUIRE(f.contains(b00110110)); BOOST_REQUIRE(f.contains(b00110111)); f.removeRaw(b00110111); BOOST_REQUIRE(!f.contains(b00000001)); BOOST_REQUIRE(f.contains(b00010000)); BOOST_REQUIRE(!f.contains(b00011000)); BOOST_REQUIRE(!f.contains(b00110000)); BOOST_REQUIRE(!f.contains(b00110010)); BOOST_REQUIRE(!f.contains(b00111000)); BOOST_REQUIRE(!f.contains(b00000110)); BOOST_REQUIRE(!f.contains(b00110110)); BOOST_REQUIRE(!f.contains(b00110111)); f.removeRaw(b00110111); BOOST_REQUIRE(!f.contains(b00000001)); BOOST_REQUIRE(!f.contains(b00010000)); BOOST_REQUIRE(!f.contains(b00011000)); BOOST_REQUIRE(!f.contains(b00110000)); BOOST_REQUIRE(!f.contains(b00110010)); BOOST_REQUIRE(!f.contains(b00111000)); BOOST_REQUIRE(!f.contains(b00000110)); BOOST_REQUIRE(!f.contains(b00110110)); BOOST_REQUIRE(!f.contains(b00110111)); } BOOST_AUTO_TEST_SUITE_END()<|endoftext|>
<commit_before>#pragma once #include <warpcoil/cpp/generate/generate_name_for_structure.hpp> #include <warpcoil/types.hpp> #include <warpcoil/block.hpp> #include <boost/lexical_cast.hpp> #include <set> namespace warpcoil { namespace cpp { template <class CharSink> void generate_parser_type(CharSink &&code, types::type const &parsed); template <class CharSink> struct shared_code_generator; template <class CharSink1, class CharSink2> type_emptiness generate_type(CharSink1 &&code, shared_code_generator<CharSink2> &shared, types::type const &root); template <class CharSink> struct shared_code_generator { explicit shared_code_generator(CharSink code, indentation_level indentation) : m_code(std::forward<CharSink>(code)) , m_indentation(indentation) { } void require_structure(types::structure const &required) { auto const found = m_generated_structures.find(required); if (found != m_generated_structures.end()) { return; } start_line(m_code, m_indentation, "struct "); warpcoil::cpp::generate_name_for_structure(m_code, required); Si::append(m_code, "\n"); block(m_code, m_indentation, [&](indentation_level const in_struct) { for (types::structure::element const &element : required.elements) { start_line(m_code, in_struct, ""); generate_type(m_code, *this, element.what); Si::append(m_code, " "); Si::append(m_code, element.name); Si::append(m_code, ";\n"); } }, ";\n"); start_line(m_code, m_indentation, "template <> struct warpcoil::cpp::structure_parser<"); warpcoil::cpp::generate_name_for_structure(m_code, required); if (required.elements.empty()) { Si::append(m_code, ">\n"); block(m_code, m_indentation, [&](indentation_level const in_struct) { start_line(m_code, in_struct, "typedef "); warpcoil::cpp::generate_name_for_structure(m_code, required); Si::append(m_code, " result_type;\n"); start_line(m_code, in_struct, "parse_result<result_type> parse_byte(std::uint8_t const) const " "{ return " "warpcoil::cpp::parse_complete<result_type>{result_type{}, " "warpcoil::cpp::input_consumption::does_not_consume}; }\n"); start_line(m_code, in_struct, "Si::optional<result_type> " "check_for_immediate_completion() const { return " "result_type{}; }\n"); }, ";\n"); } else { Si::append(m_code, "> : warpcoil::cpp::basic_tuple_parser<warpcoil::cpp::structure_parser<"); warpcoil::cpp::generate_name_for_structure(m_code, required); Si::append(m_code, ">, "); warpcoil::cpp::generate_name_for_structure(m_code, required); for (types::structure::element const &element : required.elements) { Si::append(m_code, ", "); generate_parser_type(m_code, element.what); } Si::append(m_code, ">\n "); block(m_code, m_indentation, [&](indentation_level const in_struct) { std::size_t index = 0; for (types::structure::element const &element : required.elements) { start_line(m_code, in_struct, ""); generate_type(m_code, *this, element.what); Si::append(m_code, " &get("); warpcoil::cpp::generate_name_for_structure(m_code, required); Si::append(m_code, " &result, std::integral_constant<std::size_t, "); Si::append(m_code, boost::lexical_cast<std::string>(index)); Si::append(m_code, ">) const\n"); block(m_code, in_struct, [&](indentation_level const in_get) { start_line(m_code, in_get, "return result.", element.name, ";\n"); }, "\n"); ++index; } }, ";\n"); } m_generated_structures.insert(required.clone()); } private: struct structure_less { bool operator()(types::structure const &left, types::structure const &right) const { return less(left, right); } }; CharSink m_code; indentation_level m_indentation; std::set<types::structure, structure_less> m_generated_structures; }; } } <commit_msg>specialize structure_parser in the right namespace<commit_after>#pragma once #include <warpcoil/cpp/generate/generate_name_for_structure.hpp> #include <warpcoil/types.hpp> #include <warpcoil/block.hpp> #include <boost/lexical_cast.hpp> #include <set> namespace warpcoil { namespace cpp { template <class CharSink> void generate_parser_type(CharSink &&code, types::type const &parsed); template <class CharSink> struct shared_code_generator; template <class CharSink1, class CharSink2> type_emptiness generate_type(CharSink1 &&code, shared_code_generator<CharSink2> &shared, types::type const &root); template <class CharSink> struct shared_code_generator { explicit shared_code_generator(CharSink code, indentation_level indentation) : m_code(std::forward<CharSink>(code)) , m_indentation(indentation) { } void require_structure(types::structure const &required) { auto const found = m_generated_structures.find(required); if (found != m_generated_structures.end()) { return; } start_line(m_code, m_indentation, "struct "); warpcoil::cpp::generate_name_for_structure(m_code, required); Si::append(m_code, "\n"); block(m_code, m_indentation, [&](indentation_level const in_struct) { for (types::structure::element const &element : required.elements) { start_line(m_code, in_struct, ""); generate_type(m_code, *this, element.what); Si::append(m_code, " "); Si::append(m_code, element.name); Si::append(m_code, ";\n"); } }, ";\n"); start_line(m_code, m_indentation, "namespace warpcoil"); block(m_code, m_indentation, [&](indentation_level const in_warpcoil) { start_line(m_code, m_indentation, "namespace cpp"); block(m_code, in_warpcoil, [&](indentation_level const in_cpp) { start_line(m_code, in_cpp, "template <> struct structure_parser<"); warpcoil::cpp::generate_name_for_structure(m_code, required); if (required.elements.empty()) { Si::append(m_code, ">\n"); block(m_code, in_cpp, [&](indentation_level const in_struct) { start_line(m_code, in_struct, "typedef "); warpcoil::cpp::generate_name_for_structure(m_code, required); Si::append(m_code, " result_type;\n"); start_line( m_code, in_struct, "parse_result<result_type> parse_byte(std::uint8_t const) const " "{ return " "parse_complete<result_type>{result_type{}, " "input_consumption::does_not_consume}; }\n"); start_line(m_code, in_struct, "Si::optional<result_type> " "check_for_immediate_completion() const { return " "result_type{}; }\n"); }, ";\n"); } else { Si::append(m_code, "> : basic_tuple_parser<structure_parser<"); warpcoil::cpp::generate_name_for_structure(m_code, required); Si::append(m_code, ">, "); warpcoil::cpp::generate_name_for_structure(m_code, required); for (types::structure::element const &element : required.elements) { Si::append(m_code, ", "); generate_parser_type(m_code, element.what); } Si::append(m_code, ">\n "); block(m_code, in_cpp, [&](indentation_level const in_struct) { std::size_t index = 0; for (types::structure::element const &element : required.elements) { start_line(m_code, in_struct, ""); generate_type(m_code, *this, element.what); Si::append(m_code, " &get("); warpcoil::cpp::generate_name_for_structure(m_code, required); Si::append(m_code, " &result, std::integral_constant<std::size_t, "); Si::append(m_code, boost::lexical_cast<std::string>(index)); Si::append(m_code, ">) const\n"); block(m_code, in_struct, [&](indentation_level const in_get) { start_line(m_code, in_get, "return result.", element.name, ";\n"); }, "\n"); ++index; } }, ";\n"); } }, "\n"); }, "\n"); m_generated_structures.insert(required.clone()); } private: struct structure_less { bool operator()(types::structure const &left, types::structure const &right) const { return less(left, right); } }; CharSink m_code; indentation_level m_indentation; std::set<types::structure, structure_less> m_generated_structures; }; } } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the demonstration applications of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** 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. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QGuiApplication> #include <QtQuick/QQuickView> #include "squircle.h" //! [1] int main(int argc, char **argv) { QGuiApplication app(argc, argv); qmlRegisterType<Squircle>("OpenGLUnderQML", 1, 0, "Squircle"); QQuickView view; view.setSource(QUrl("qrc:///scenegraph/openglunderqml/main.qml")); view.show(); return app.exec(); } //! [1] <commit_msg>Updated the code to resize the text box on window resize<commit_after>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the demonstration applications of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** 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. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QGuiApplication> #include <QtQuick/QQuickView> #include "squircle.h" //! [1] int main(int argc, char **argv) { QGuiApplication app(argc, argv); qmlRegisterType<Squircle>("OpenGLUnderQML", 1, 0, "Squircle"); QQuickView view; view.setResizeMode(QQuickView::SizeRootObjectToView); view.setSource(QUrl("qrc:///scenegraph/openglunderqml/main.qml")); view.show(); return app.exec(); } //! [1] <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: selectlabeldialog.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: ihi $ $Date: 2008-01-14 15:00:44 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_extensions.hxx" #ifndef _EXTENSIONS_PROPCTRLR_SELECTLABELDIALOG_HXX_ #include "selectlabeldialog.hxx" #endif #ifndef _EXTENSIONS_PROPCTRLR_FORMRESID_HRC_ #include "formresid.hrc" #endif #ifndef _EXTENSIONS_FORMSCTRLR_FORMBROWSERTOOLS_HXX_ #include "formbrowsertools.hxx" #endif #ifndef _EXTENSIONS_FORMSCTRLR_FORMSTRINGS_HXX_ #include "formstrings.hxx" #endif #ifndef _COM_SUN_STAR_FORM_FORMCOMPONENTTYPE_HPP_ #include <com/sun/star/form/FormComponentType.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XCHILD_HPP_ #include <com/sun/star/container/XChild.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_ #include <com/sun/star/container/XIndexAccess.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_ #include <com/sun/star/sdbc/XResultSet.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COMPHELPER_PROPERTY_HXX_ #include <comphelper/property.hxx> #endif #ifndef _COMPHELPER_TYPES_HXX_ #include <comphelper/types.hxx> #endif //............................................................................ namespace pcr { //............................................................................ using namespace ::com::sun::star::uno; using namespace ::com::sun::star::container; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::form; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::lang; //======================================================================== // OSelectLabelDialog //======================================================================== DBG_NAME(OSelectLabelDialog) //------------------------------------------------------------------------ OSelectLabelDialog::OSelectLabelDialog( Window* pParent, Reference< XPropertySet > _xControlModel ) :ModalDialog(pParent, PcrRes(RID_DLG_SELECTLABELCONTROL)) ,m_aMainDesc(this, PcrRes(1)) ,m_aControlTree(this, PcrRes(1)) ,m_aNoAssignment(this, PcrRes(1)) ,m_aSeparator(this, PcrRes(1)) ,m_aOk(this, PcrRes(1)) ,m_aCancel(this, PcrRes(1)) ,m_aModelImages(PcrRes(RID_IL_FORMEXPLORER)) ,m_xControlModel(_xControlModel) ,m_pInitialSelection(NULL) ,m_pLastSelected(NULL) ,m_bHaveAssignableControl(sal_False) { DBG_CTOR(OSelectLabelDialog,NULL); // initialize the TreeListBox m_aControlTree.SetSelectionMode( SINGLE_SELECTION ); m_aControlTree.SetDragDropMode( 0 ); m_aControlTree.EnableInplaceEditing( sal_False ); m_aControlTree.SetWindowBits(WB_BORDER | WB_HASLINES | WB_HASLINESATROOT | WB_HASBUTTONS | WB_HASBUTTONSATROOT | WB_HSCROLL); m_aControlTree.SetNodeBitmaps( m_aModelImages.GetImage( RID_SVXIMG_COLLAPSEDNODE ), m_aModelImages.GetImage( RID_SVXIMG_EXPANDEDNODE ) ); m_aControlTree.SetSelectHdl(LINK(this, OSelectLabelDialog, OnEntrySelected)); m_aControlTree.SetDeselectHdl(LINK(this, OSelectLabelDialog, OnEntrySelected)); // fill the description UniString sDescription = m_aMainDesc.GetText(); sal_Int16 nClassID = FormComponentType::CONTROL; if (::comphelper::hasProperty(PROPERTY_CLASSID, m_xControlModel)) nClassID = ::comphelper::getINT16(m_xControlModel->getPropertyValue(PROPERTY_CLASSID)); sDescription.SearchAndReplace(String::CreateFromAscii("$control_class$"), GetUIHeadlineName(nClassID, makeAny(m_xControlModel))); UniString sName = ::comphelper::getString(m_xControlModel->getPropertyValue(PROPERTY_NAME)).getStr(); sDescription.SearchAndReplace(String::CreateFromAscii("$control_name$"), sName); m_aMainDesc.SetText(sDescription); // search for the root of the form hierarchy Reference< XChild > xCont(m_xControlModel, UNO_QUERY); Reference< XInterface > xSearch( xCont.is() ? xCont->getParent() : Reference< XInterface > ()); Reference< XResultSet > xParentAsResultSet(xSearch, UNO_QUERY); while (xParentAsResultSet.is()) { xCont = Reference< XChild > (xSearch, UNO_QUERY); xSearch = xCont.is() ? xCont->getParent() : Reference< XInterface > (); xParentAsResultSet = Reference< XResultSet > (xSearch, UNO_QUERY); } // and insert all entries below this root into the listbox if (xSearch.is()) { // check wich service the allowed components must suppport sal_Int16 nClassId = 0; try { nClassId = ::comphelper::getINT16(m_xControlModel->getPropertyValue(PROPERTY_CLASSID)); } catch(...) { } m_sRequiredService = (FormComponentType::RADIOBUTTON == nClassId) ? SERVICE_COMPONENT_GROUPBOX : SERVICE_COMPONENT_FIXEDTEXT; m_aRequiredControlImage = m_aModelImages.GetImage((FormComponentType::RADIOBUTTON == nClassId) ? RID_SVXIMG_GROUPBOX : RID_SVXIMG_FIXEDTEXT); // calc the currently set label control (so InsertEntries can calc m_pInitialSelection) Any aCurrentLabelControl( m_xControlModel->getPropertyValue(PROPERTY_CONTROLLABEL) ); DBG_ASSERT((aCurrentLabelControl.getValueTypeClass() == TypeClass_INTERFACE) || !aCurrentLabelControl.hasValue(), "OSelectLabelDialog::OSelectLabelDialog : invalid ControlLabel property !"); if (aCurrentLabelControl.hasValue()) aCurrentLabelControl >>= m_xInitialLabelControl; // insert the root Image aRootImage = m_aModelImages.GetImage(RID_SVXIMG_FORMS); SvLBoxEntry* pRoot = m_aControlTree.InsertEntry(PcrRes(RID_STR_FORMS), aRootImage, aRootImage); // build the tree m_pInitialSelection = NULL; m_bHaveAssignableControl = sal_False; InsertEntries(xSearch, pRoot); m_aControlTree.Expand(pRoot); } if (m_pInitialSelection) { m_aControlTree.MakeVisible(m_pInitialSelection, sal_True); m_aControlTree.Select(m_pInitialSelection, sal_True); } else { m_aControlTree.MakeVisible(m_aControlTree.First(), sal_True); if (m_aControlTree.FirstSelected()) m_aControlTree.Select(m_aControlTree.FirstSelected(), sal_False); m_aNoAssignment.Check(sal_True); } if (!m_bHaveAssignableControl) { // no controls which can be assigned m_aNoAssignment.Check(sal_True); m_aNoAssignment.Enable(sal_False); } m_aNoAssignment.SetClickHdl(LINK(this, OSelectLabelDialog, OnNoAssignmentClicked)); m_aNoAssignment.GetClickHdl().Call(&m_aNoAssignment); FreeResource(); } //------------------------------------------------------------------------ OSelectLabelDialog::~OSelectLabelDialog() { // delete the entry datas of the listbox entries SvLBoxEntry* pLoop = m_aControlTree.First(); while (pLoop) { void* pData = pLoop->GetUserData(); if (pData) delete (Reference< XPropertySet > *)pData; pLoop = m_aControlTree.Next(pLoop); } DBG_DTOR(OSelectLabelDialog,NULL); } //------------------------------------------------------------------------ sal_Int32 OSelectLabelDialog::InsertEntries(const Reference< XInterface > & _xContainer, SvLBoxEntry* pContainerEntry) { Reference< XIndexAccess > xContainer(_xContainer, UNO_QUERY); if (!xContainer.is()) return 0; sal_Int32 nChildren = 0; UniString sName,sDisplayName; Reference< XPropertySet > xAsSet; for (sal_Int32 i=0; i<xContainer->getCount(); ++i) { xContainer->getByIndex(i) >>= xAsSet; if (!xAsSet.is()) { DBG_WARNING("OSelectLabelDialog::InsertEntries : strange : a form component which isn't a property set !"); continue; } if (!::comphelper::hasProperty(PROPERTY_NAME, xAsSet)) // we need at least a name for displaying ... continue; sName = ::comphelper::getString(xAsSet->getPropertyValue(PROPERTY_NAME)).getStr(); // we need to check if the control model supports the required service Reference< XServiceInfo > xInfo(xAsSet, UNO_QUERY); if (!xInfo.is()) continue; if (!xInfo->supportsService(m_sRequiredService)) { // perhaps it is a container Reference< XIndexAccess > xCont(xAsSet, UNO_QUERY); if (xCont.is() && xCont->getCount()) { // yes -> step down Image aFormImage = m_aModelImages.GetImage( RID_SVXIMG_FORM ); SvLBoxEntry* pCont = m_aControlTree.InsertEntry(sName, aFormImage, aFormImage, pContainerEntry); sal_Int32 nContChildren = InsertEntries(xCont, pCont); if (nContChildren) { m_aControlTree.Expand(pCont); ++nChildren; } else { // oops, no valid childs -> remove the entry m_aControlTree.ModelIsRemoving(pCont); m_aControlTree.GetModel()->Remove(pCont); m_aControlTree.ModelHasRemoved(pCont); } } continue; } // get the label if (!::comphelper::hasProperty(PROPERTY_LABEL, xAsSet)) continue; sDisplayName = ::comphelper::getString(xAsSet->getPropertyValue(PROPERTY_LABEL)).getStr(); sDisplayName += String::CreateFromAscii(" ("); sDisplayName += sName; sDisplayName += ')'; // all requirements met -> insert SvLBoxEntry* pCurrent = m_aControlTree.InsertEntry(sDisplayName, m_aRequiredControlImage, m_aRequiredControlImage, pContainerEntry); pCurrent->SetUserData(new Reference< XPropertySet > (xAsSet)); ++nChildren; if (m_xInitialLabelControl == xAsSet) m_pInitialSelection = pCurrent; m_bHaveAssignableControl = sal_True; } return nChildren; } //------------------------------------------------------------------------ IMPL_LINK(OSelectLabelDialog, OnEntrySelected, SvTreeListBox*, pLB) { DBG_ASSERT(pLB == &m_aControlTree, "OSelectLabelDialog::OnEntrySelected : where did this come from ?"); (void)pLB; SvLBoxEntry* pSelected = m_aControlTree.FirstSelected(); void* pData = pSelected ? pSelected->GetUserData() : NULL; if (pData) m_xSelectedControl = Reference< XPropertySet > (*(Reference< XPropertySet > *)pData); m_aNoAssignment.SetClickHdl(Link()); m_aNoAssignment.Check(pData == NULL); m_aNoAssignment.SetClickHdl(LINK(this, OSelectLabelDialog, OnNoAssignmentClicked)); return 0L; } //------------------------------------------------------------------------ IMPL_LINK(OSelectLabelDialog, OnNoAssignmentClicked, Button*, pButton) { DBG_ASSERT(pButton == &m_aNoAssignment, "OSelectLabelDialog::OnNoAssignmentClicked : where did this come from ?"); (void)pButton; if (m_aNoAssignment.IsChecked()) m_pLastSelected = m_aControlTree.FirstSelected(); else { DBG_ASSERT(m_bHaveAssignableControl, "OSelectLabelDialog::OnNoAssignmentClicked"); // search the first assignable entry SvLBoxEntry* pSearch = m_aControlTree.First(); while (pSearch) { if (pSearch->GetUserData()) break; pSearch = m_aControlTree.Next(pSearch); } // and select it if (pSearch) { m_aControlTree.Select(pSearch); m_pLastSelected = pSearch; } } if (m_pLastSelected) { m_aControlTree.SetSelectHdl(Link()); m_aControlTree.SetDeselectHdl(Link()); m_aControlTree.Select(m_pLastSelected, !m_aNoAssignment.IsChecked()); m_aControlTree.SetSelectHdl(LINK(this, OSelectLabelDialog, OnEntrySelected)); m_aControlTree.SetDeselectHdl(LINK(this, OSelectLabelDialog, OnEntrySelected)); } return 0L; } //............................................................................ } // namespace pcr //............................................................................ <commit_msg>INTEGRATION: CWS changefileheader (1.9.48); FILE MERGED 2008/04/01 15:15:20 thb 1.9.48.3: #i85898# Stripping all external header guards 2008/04/01 12:29:54 thb 1.9.48.2: #i85898# Stripping all external header guards 2008/03/31 12:31:54 rt 1.9.48.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: selectlabeldialog.cxx,v $ * $Revision: 1.10 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_extensions.hxx" #include "selectlabeldialog.hxx" #ifndef _EXTENSIONS_PROPCTRLR_FORMRESID_HRC_ #include "formresid.hrc" #endif #include "formbrowsertools.hxx" #include "formstrings.hxx" #include <com/sun/star/form/FormComponentType.hpp> #include <com/sun/star/container/XChild.hpp> #include <com/sun/star/container/XIndexAccess.hpp> #include <com/sun/star/sdbc/XResultSet.hpp> #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/lang/XServiceInfo.hpp> #include <comphelper/property.hxx> #include <comphelper/types.hxx> //............................................................................ namespace pcr { //............................................................................ using namespace ::com::sun::star::uno; using namespace ::com::sun::star::container; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::form; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::lang; //======================================================================== // OSelectLabelDialog //======================================================================== DBG_NAME(OSelectLabelDialog) //------------------------------------------------------------------------ OSelectLabelDialog::OSelectLabelDialog( Window* pParent, Reference< XPropertySet > _xControlModel ) :ModalDialog(pParent, PcrRes(RID_DLG_SELECTLABELCONTROL)) ,m_aMainDesc(this, PcrRes(1)) ,m_aControlTree(this, PcrRes(1)) ,m_aNoAssignment(this, PcrRes(1)) ,m_aSeparator(this, PcrRes(1)) ,m_aOk(this, PcrRes(1)) ,m_aCancel(this, PcrRes(1)) ,m_aModelImages(PcrRes(RID_IL_FORMEXPLORER)) ,m_xControlModel(_xControlModel) ,m_pInitialSelection(NULL) ,m_pLastSelected(NULL) ,m_bHaveAssignableControl(sal_False) { DBG_CTOR(OSelectLabelDialog,NULL); // initialize the TreeListBox m_aControlTree.SetSelectionMode( SINGLE_SELECTION ); m_aControlTree.SetDragDropMode( 0 ); m_aControlTree.EnableInplaceEditing( sal_False ); m_aControlTree.SetWindowBits(WB_BORDER | WB_HASLINES | WB_HASLINESATROOT | WB_HASBUTTONS | WB_HASBUTTONSATROOT | WB_HSCROLL); m_aControlTree.SetNodeBitmaps( m_aModelImages.GetImage( RID_SVXIMG_COLLAPSEDNODE ), m_aModelImages.GetImage( RID_SVXIMG_EXPANDEDNODE ) ); m_aControlTree.SetSelectHdl(LINK(this, OSelectLabelDialog, OnEntrySelected)); m_aControlTree.SetDeselectHdl(LINK(this, OSelectLabelDialog, OnEntrySelected)); // fill the description UniString sDescription = m_aMainDesc.GetText(); sal_Int16 nClassID = FormComponentType::CONTROL; if (::comphelper::hasProperty(PROPERTY_CLASSID, m_xControlModel)) nClassID = ::comphelper::getINT16(m_xControlModel->getPropertyValue(PROPERTY_CLASSID)); sDescription.SearchAndReplace(String::CreateFromAscii("$control_class$"), GetUIHeadlineName(nClassID, makeAny(m_xControlModel))); UniString sName = ::comphelper::getString(m_xControlModel->getPropertyValue(PROPERTY_NAME)).getStr(); sDescription.SearchAndReplace(String::CreateFromAscii("$control_name$"), sName); m_aMainDesc.SetText(sDescription); // search for the root of the form hierarchy Reference< XChild > xCont(m_xControlModel, UNO_QUERY); Reference< XInterface > xSearch( xCont.is() ? xCont->getParent() : Reference< XInterface > ()); Reference< XResultSet > xParentAsResultSet(xSearch, UNO_QUERY); while (xParentAsResultSet.is()) { xCont = Reference< XChild > (xSearch, UNO_QUERY); xSearch = xCont.is() ? xCont->getParent() : Reference< XInterface > (); xParentAsResultSet = Reference< XResultSet > (xSearch, UNO_QUERY); } // and insert all entries below this root into the listbox if (xSearch.is()) { // check wich service the allowed components must suppport sal_Int16 nClassId = 0; try { nClassId = ::comphelper::getINT16(m_xControlModel->getPropertyValue(PROPERTY_CLASSID)); } catch(...) { } m_sRequiredService = (FormComponentType::RADIOBUTTON == nClassId) ? SERVICE_COMPONENT_GROUPBOX : SERVICE_COMPONENT_FIXEDTEXT; m_aRequiredControlImage = m_aModelImages.GetImage((FormComponentType::RADIOBUTTON == nClassId) ? RID_SVXIMG_GROUPBOX : RID_SVXIMG_FIXEDTEXT); // calc the currently set label control (so InsertEntries can calc m_pInitialSelection) Any aCurrentLabelControl( m_xControlModel->getPropertyValue(PROPERTY_CONTROLLABEL) ); DBG_ASSERT((aCurrentLabelControl.getValueTypeClass() == TypeClass_INTERFACE) || !aCurrentLabelControl.hasValue(), "OSelectLabelDialog::OSelectLabelDialog : invalid ControlLabel property !"); if (aCurrentLabelControl.hasValue()) aCurrentLabelControl >>= m_xInitialLabelControl; // insert the root Image aRootImage = m_aModelImages.GetImage(RID_SVXIMG_FORMS); SvLBoxEntry* pRoot = m_aControlTree.InsertEntry(PcrRes(RID_STR_FORMS), aRootImage, aRootImage); // build the tree m_pInitialSelection = NULL; m_bHaveAssignableControl = sal_False; InsertEntries(xSearch, pRoot); m_aControlTree.Expand(pRoot); } if (m_pInitialSelection) { m_aControlTree.MakeVisible(m_pInitialSelection, sal_True); m_aControlTree.Select(m_pInitialSelection, sal_True); } else { m_aControlTree.MakeVisible(m_aControlTree.First(), sal_True); if (m_aControlTree.FirstSelected()) m_aControlTree.Select(m_aControlTree.FirstSelected(), sal_False); m_aNoAssignment.Check(sal_True); } if (!m_bHaveAssignableControl) { // no controls which can be assigned m_aNoAssignment.Check(sal_True); m_aNoAssignment.Enable(sal_False); } m_aNoAssignment.SetClickHdl(LINK(this, OSelectLabelDialog, OnNoAssignmentClicked)); m_aNoAssignment.GetClickHdl().Call(&m_aNoAssignment); FreeResource(); } //------------------------------------------------------------------------ OSelectLabelDialog::~OSelectLabelDialog() { // delete the entry datas of the listbox entries SvLBoxEntry* pLoop = m_aControlTree.First(); while (pLoop) { void* pData = pLoop->GetUserData(); if (pData) delete (Reference< XPropertySet > *)pData; pLoop = m_aControlTree.Next(pLoop); } DBG_DTOR(OSelectLabelDialog,NULL); } //------------------------------------------------------------------------ sal_Int32 OSelectLabelDialog::InsertEntries(const Reference< XInterface > & _xContainer, SvLBoxEntry* pContainerEntry) { Reference< XIndexAccess > xContainer(_xContainer, UNO_QUERY); if (!xContainer.is()) return 0; sal_Int32 nChildren = 0; UniString sName,sDisplayName; Reference< XPropertySet > xAsSet; for (sal_Int32 i=0; i<xContainer->getCount(); ++i) { xContainer->getByIndex(i) >>= xAsSet; if (!xAsSet.is()) { DBG_WARNING("OSelectLabelDialog::InsertEntries : strange : a form component which isn't a property set !"); continue; } if (!::comphelper::hasProperty(PROPERTY_NAME, xAsSet)) // we need at least a name for displaying ... continue; sName = ::comphelper::getString(xAsSet->getPropertyValue(PROPERTY_NAME)).getStr(); // we need to check if the control model supports the required service Reference< XServiceInfo > xInfo(xAsSet, UNO_QUERY); if (!xInfo.is()) continue; if (!xInfo->supportsService(m_sRequiredService)) { // perhaps it is a container Reference< XIndexAccess > xCont(xAsSet, UNO_QUERY); if (xCont.is() && xCont->getCount()) { // yes -> step down Image aFormImage = m_aModelImages.GetImage( RID_SVXIMG_FORM ); SvLBoxEntry* pCont = m_aControlTree.InsertEntry(sName, aFormImage, aFormImage, pContainerEntry); sal_Int32 nContChildren = InsertEntries(xCont, pCont); if (nContChildren) { m_aControlTree.Expand(pCont); ++nChildren; } else { // oops, no valid childs -> remove the entry m_aControlTree.ModelIsRemoving(pCont); m_aControlTree.GetModel()->Remove(pCont); m_aControlTree.ModelHasRemoved(pCont); } } continue; } // get the label if (!::comphelper::hasProperty(PROPERTY_LABEL, xAsSet)) continue; sDisplayName = ::comphelper::getString(xAsSet->getPropertyValue(PROPERTY_LABEL)).getStr(); sDisplayName += String::CreateFromAscii(" ("); sDisplayName += sName; sDisplayName += ')'; // all requirements met -> insert SvLBoxEntry* pCurrent = m_aControlTree.InsertEntry(sDisplayName, m_aRequiredControlImage, m_aRequiredControlImage, pContainerEntry); pCurrent->SetUserData(new Reference< XPropertySet > (xAsSet)); ++nChildren; if (m_xInitialLabelControl == xAsSet) m_pInitialSelection = pCurrent; m_bHaveAssignableControl = sal_True; } return nChildren; } //------------------------------------------------------------------------ IMPL_LINK(OSelectLabelDialog, OnEntrySelected, SvTreeListBox*, pLB) { DBG_ASSERT(pLB == &m_aControlTree, "OSelectLabelDialog::OnEntrySelected : where did this come from ?"); (void)pLB; SvLBoxEntry* pSelected = m_aControlTree.FirstSelected(); void* pData = pSelected ? pSelected->GetUserData() : NULL; if (pData) m_xSelectedControl = Reference< XPropertySet > (*(Reference< XPropertySet > *)pData); m_aNoAssignment.SetClickHdl(Link()); m_aNoAssignment.Check(pData == NULL); m_aNoAssignment.SetClickHdl(LINK(this, OSelectLabelDialog, OnNoAssignmentClicked)); return 0L; } //------------------------------------------------------------------------ IMPL_LINK(OSelectLabelDialog, OnNoAssignmentClicked, Button*, pButton) { DBG_ASSERT(pButton == &m_aNoAssignment, "OSelectLabelDialog::OnNoAssignmentClicked : where did this come from ?"); (void)pButton; if (m_aNoAssignment.IsChecked()) m_pLastSelected = m_aControlTree.FirstSelected(); else { DBG_ASSERT(m_bHaveAssignableControl, "OSelectLabelDialog::OnNoAssignmentClicked"); // search the first assignable entry SvLBoxEntry* pSearch = m_aControlTree.First(); while (pSearch) { if (pSearch->GetUserData()) break; pSearch = m_aControlTree.Next(pSearch); } // and select it if (pSearch) { m_aControlTree.Select(pSearch); m_pLastSelected = pSearch; } } if (m_pLastSelected) { m_aControlTree.SetSelectHdl(Link()); m_aControlTree.SetDeselectHdl(Link()); m_aControlTree.Select(m_pLastSelected, !m_aNoAssignment.IsChecked()); m_aControlTree.SetSelectHdl(LINK(this, OSelectLabelDialog, OnEntrySelected)); m_aControlTree.SetDeselectHdl(LINK(this, OSelectLabelDialog, OnEntrySelected)); } return 0L; } //............................................................................ } // namespace pcr //............................................................................ <|endoftext|>
<commit_before>/* ** Copyright 1998 by the Condor Design Team ** ** Permission to use, copy, modify, and distribute this software and its ** documentation for any purpose and without fee is hereby granted, ** provided that the above copyright notice appear in all copies and that ** both that copyright notice and this permission notice appear in ** supporting documentation, and that the names of the University of ** Wisconsin and the Condor Design Team not be used in advertising or ** publicity pertaining to distribution of the software without specific, ** written prior permission. The University of Wisconsin and the Condor ** Design Team make no representations about the suitability of this ** software for any purpose. It is provided "as is" without express ** or implied warranty. ** ** THE UNIVERSITY OF WISCONSIN AND THE CONDOR DESIGN TEAM DISCLAIM ALL ** WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES ** OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE UNIVERSITY OF ** WISCONSIN OR THE CONDOR DESIGN TEAM BE LIABLE FOR ANY SPECIAL, INDIRECT ** OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS ** OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE ** OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE ** OR PERFORMANCE OF THIS SOFTWARE. ** ** Authors: Mike Litzkow, Jim Pruyne, and Jim Basney ** University of Wisconsin, Computer Sciences Dept. ** */ #include "condor_common.h" #include "condor_classad.h" #include "condor_attributes.h" #include "condor_debug.h" #include "condor_io.h" #include "condor_uid.h" #include "shadow.h" #include "pseudo_ops.h" #include "exit.h" static char *_FileName_ = __FILE__; extern ReliSock *syscall_sock; extern BaseShadow *Shadow; extern RemoteResource *thisRemoteResource; int pseudo_register_machine_info(char *uiddomain, char *fsdomain, char * starterAddr, char *full_hostname ) { // do something with uiddomain or fsdomain? We've already // got them from the jobAd at startup... thisRemoteResource->setStarterAddress( starterAddr ); thisRemoteResource->setMachineName( full_hostname ); return 0; } int pseudo_get_job_info(ClassAd *&ad) { ad = thisRemoteResource->getJobAd(); return 0; } int pseudo_get_executable(char *source) { sprintf(source, "%s/cluster%d.ickpt.subproc0", Shadow->getSpool(), Shadow->getCluster()); return 0; } int pseudo_job_exit(int status, int reason) { dprintf(D_SYSCALLS, "in pseudo_job_exit: status=%d,reason=%d\n", status, reason); thisRemoteResource->setExitStatus(status); thisRemoteResource->setExitReason(reason); return 0; } <commit_msg>+ update copyright notice<commit_after>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE** * CONDOR Copyright Notice * * See LICENSE.TXT for additional notices and disclaimers. * * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department, * University of Wisconsin-Madison, Madison, WI. All Rights Reserved. * No use of the CONDOR Software Program Source Code is authorized * without the express consent of the CONDOR Team. For more information * contact: CONDOR Team, Attention: Professor Miron Livny, * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685, * (608) 262-0856 or miron@cs.wisc.edu. * * U.S. Government Rights Restrictions: Use, duplication, or disclosure * by the U.S. Government is subject to restrictions as set forth in * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and * (2) of Commercial Computer Software-Restricted Rights at 48 CFR * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison, * WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu. ****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/ #include "condor_common.h" #include "condor_classad.h" #include "condor_attributes.h" #include "condor_debug.h" #include "condor_io.h" #include "condor_uid.h" #include "shadow.h" #include "pseudo_ops.h" #include "exit.h" extern ReliSock *syscall_sock; extern BaseShadow *Shadow; extern RemoteResource *thisRemoteResource; int pseudo_register_machine_info(char *uiddomain, char *fsdomain, char * starterAddr, char *full_hostname ) { thisRemoteResource->setUidDomain( uiddomain ); thisRemoteResource->setFilesystemDomain( fsdomain ); thisRemoteResource->setStarterAddress( starterAddr ); thisRemoteResource->setMachineName( full_hostname ); return 0; } int pseudo_get_job_info(ClassAd *&ad) { ClassAd * the_ad; the_ad = thisRemoteResource->getJobAd(); ASSERT( the_ad ); thisRemoteResource->filetrans.Init( the_ad ); ad = the_ad; return 0; } int pseudo_get_executable(char *source) { sprintf(source, "%s/cluster%d.ickpt.subproc0", Shadow->getSpool(), Shadow->getCluster()); return 0; } int pseudo_job_exit(int status, int reason) { dprintf(D_SYSCALLS, "in pseudo_job_exit: status=%d,reason=%d\n", status, reason); thisRemoteResource->setExitStatus(status); thisRemoteResource->setExitReason(reason); return 0; } <|endoftext|>
<commit_before>/* * Example.cpp (Example_PrimitiveRestart) * * This file is part of the "LLGL" project (Copyright (c) 2015-2019 by Lukas Hermanns) * See "LICENSE.txt" for license information. */ #include <ExampleBase.h> #include <vector> class Example_PrimitiveRestart : public ExampleBase { LLGL::ShaderProgram* shaderProgram = nullptr; LLGL::PipelineState* pipeline = nullptr; LLGL::Buffer* vertexBuffer = nullptr; LLGL::Buffer* indexBuffer = nullptr; std::uint64_t indexOffset16 = 0; std::uint32_t indexCount16 = 0; std::uint64_t indexOffset32 = 0; std::uint32_t indexCount32 = 0; public: Example_PrimitiveRestart() : ExampleBase { L"LLGL Example: PrimitiveRestart" } { auto vertexFormats = CreateBuffers(); shaderProgram = LoadStandardShaderProgram(vertexFormats); CreatePipeline(); } private: // Vertex data structure struct Vertex { Gs::Vector2f position; LLGL::ColorRGBAub color; }; void AddSquare( float centerX, float centerY, float size, std::vector<Vertex>& vertices, std::vector<std::uint16_t>& indices, std::uint32_t& indexCount, bool indexType16Bits) { float left = centerX - size / 2.0f; float right = centerX + size / 2.0f; float top = centerY + size / 2.0f; float bottom = centerY - size / 2.0f; const auto startIndex = vertices.size(); vertices.push_back({{ right, top }, { 255, 0, 0, 255 } }); vertices.push_back({{ right, bottom }, { 0, 255, 0, 255 } }); vertices.push_back({{ left, top }, { 0, 0, 255, 255 } }); vertices.push_back({{ left, bottom }, { 255, 255, 255, 255 } }); auto AddIndex = [&indices, &indexCount, indexType16Bits](std::size_t idx) { if (indexType16Bits) { // Add single 16-bit index to buffer indices.push_back(static_cast<std::uint16_t>(idx & 0xFFFF)); } else { // Add split 32-bit index to buffer indices.push_back(static_cast<std::uint16_t>(idx & 0xFFFF)); indices.push_back(static_cast<std::uint16_t>((idx >> 16) & 0xFFFF)); } // Only count a single index, even if we have to add two 16-bit entries for a single 32-bit index. ++indexCount; }; AddIndex(startIndex); AddIndex(startIndex + 1); AddIndex(startIndex + 2); AddIndex(startIndex + 3); AddIndex(0xFFFFFFFF); } std::vector<LLGL::VertexFormat> CreateBuffers() { std::vector<Vertex> vertices; std::vector<std::uint16_t> indices; // Add 16-bit indices indexOffset16 = indices.size() * sizeof(std::uint16_t); AddSquare( .5f, .5f, 0.8f, vertices, indices, indexCount16, /*indexType16Bits:*/ true); AddSquare(-.5f, .5f, 0.8f, vertices, indices, indexCount16, /*indexType16Bits:*/ true); // Add 32-bit indices indexOffset32 = indices.size() * sizeof(std::uint16_t); AddSquare( .5f, -.5f, 0.8f, vertices, indices, indexCount32, /*indexType16Bits:*/ false); AddSquare(-.5f, -.5f, 0.8f, vertices, indices, indexCount32, /*indexType16Bits:*/ false); // Setup vertex format: 2D float vector for position, 4D unsigned byte vector for color LLGL::VertexFormat vertexFormat; vertexFormat.AppendAttribute({ "position", LLGL::Format::RG32Float }); vertexFormat.AppendAttribute({ "color", LLGL::Format::RGBA8UNorm }); vertexFormat.SetStride(sizeof(Vertex)); // Create vertex buffer LLGL::BufferDescriptor vertexBufferDesc; { vertexBufferDesc.size = vertices.size() * sizeof(Vertex); vertexBufferDesc.bindFlags = LLGL::BindFlags::VertexBuffer; vertexBufferDesc.vertexAttribs = vertexFormat.attributes; } vertexBuffer = renderer->CreateBuffer(vertexBufferDesc, vertices.data()); // Create index buffer (contains both 16 and 32 bit indices) LLGL::BufferDescriptor indexBufferDesc; { indexBufferDesc.size = indices.size() * sizeof(std::uint16_t); indexBufferDesc.bindFlags = LLGL::BindFlags::IndexBuffer; } indexBuffer = renderer->CreateBuffer(indexBufferDesc, indices.data()); return { vertexFormat }; } void CreatePipeline() { LLGL::GraphicsPipelineDescriptor pipelineDesc; { pipelineDesc.shaderProgram = shaderProgram; pipelineDesc.primitiveTopology = LLGL::PrimitiveTopology::TriangleStrip; pipelineDesc.renderPass = context->GetRenderPass(); pipelineDesc.rasterizer.multiSampleEnabled = (GetSampleCount() > 1); } pipeline = renderer->CreatePipelineState(pipelineDesc); } private: void OnDrawFrame() override { // Begin recording commands commands->Begin(); { // Set viewport and scissor rectangle commands->SetViewport(context->GetResolution()); // Set graphics pipeline commands->SetPipelineState(*pipeline); // Set vertex buffer commands->SetVertexBuffer(*vertexBuffer); // Set the render context as the initial render target commands->BeginRenderPass(*context); { // Clear color buffer commands->Clear(LLGL::ClearFlags::Color); if (indexCount16 > 0) { commands->SetIndexBuffer(*indexBuffer, LLGL::Format::R16UInt, indexOffset16); commands->DrawIndexed(indexCount16, 0); } if (indexCount32 > 0) { commands->SetIndexBuffer(*indexBuffer, LLGL::Format::R32UInt, indexOffset32); commands->DrawIndexed(indexCount32, 0); } } commands->EndRenderPass(); } commands->End(); commandQueue->Submit(*commands); // Present the result on the screen context->Present(); } }; LLGL_IMPLEMENT_EXAMPLE(Example_PrimitiveRestart); <commit_msg>Minor simplification in PrimitiveRestart example.<commit_after>/* * Example.cpp (Example_PrimitiveRestart) * * This file is part of the "LLGL" project (Copyright (c) 2015-2019 by Lukas Hermanns) * See "LICENSE.txt" for license information. */ #include <ExampleBase.h> #include <vector> class Example_PrimitiveRestart : public ExampleBase { LLGL::ShaderProgram* shaderProgram = nullptr; LLGL::PipelineState* pipeline = nullptr; LLGL::Buffer* vertexBuffer = nullptr; LLGL::Buffer* indexBuffer = nullptr; std::uint64_t indexOffset16 = 0; std::uint32_t indexCount16 = 0; std::uint64_t indexOffset32 = 0; std::uint32_t indexCount32 = 0; public: Example_PrimitiveRestart() : ExampleBase { L"LLGL Example: PrimitiveRestart" } { auto vertexFormats = CreateBuffers(); shaderProgram = LoadStandardShaderProgram(vertexFormats); CreatePipeline(); } private: // Vertex data structure struct Vertex { float position[2]; std::uint8_t color[4]; }; void AddSquare( float centerX, float centerY, float size, std::vector<Vertex>& vertices, std::vector<std::uint16_t>& indices, std::uint32_t& indexCount, bool indexType16Bits) { float left = centerX - size / 2.0f; float right = centerX + size / 2.0f; float top = centerY + size / 2.0f; float bottom = centerY - size / 2.0f; const auto startIndex = vertices.size(); vertices.push_back({{ right, top }, { 255, 0, 0, 255 } }); vertices.push_back({{ right, bottom }, { 0, 255, 0, 255 } }); vertices.push_back({{ left, top }, { 0, 0, 255, 255 } }); vertices.push_back({{ left, bottom }, { 255, 255, 255, 255 } }); auto AddIndex = [&indices, &indexCount, indexType16Bits](std::size_t idx) { if (indexType16Bits) { // Add single 16-bit index to buffer indices.push_back(static_cast<std::uint16_t>(idx & 0xFFFF)); } else { // Add split 32-bit index to buffer indices.push_back(static_cast<std::uint16_t>(idx & 0xFFFF)); indices.push_back(static_cast<std::uint16_t>((idx >> 16) & 0xFFFF)); } // Only count a single index, even if we have to add two 16-bit entries for a single 32-bit index. ++indexCount; }; AddIndex(startIndex); AddIndex(startIndex + 1); AddIndex(startIndex + 2); AddIndex(startIndex + 3); AddIndex(0xFFFFFFFF); } std::vector<LLGL::VertexFormat> CreateBuffers() { std::vector<Vertex> vertices; std::vector<std::uint16_t> indices; // Add 16-bit indices indexOffset16 = indices.size() * sizeof(indices[0]); AddSquare( .5f, .5f, 0.8f, vertices, indices, indexCount16, /*indexType16Bits:*/ true); AddSquare(-.5f, .5f, 0.8f, vertices, indices, indexCount16, /*indexType16Bits:*/ true); // Add 32-bit indices indexOffset32 = indices.size() * sizeof(indices[0]); AddSquare( .5f, -.5f, 0.8f, vertices, indices, indexCount32, /*indexType16Bits:*/ false); AddSquare(-.5f, -.5f, 0.8f, vertices, indices, indexCount32, /*indexType16Bits:*/ false); // Setup vertex format: 2D float vector for position, 4D unsigned byte vector for color LLGL::VertexFormat vertexFormat; vertexFormat.AppendAttribute({ "position", LLGL::Format::RG32Float }); vertexFormat.AppendAttribute({ "color", LLGL::Format::RGBA8UNorm }); vertexFormat.SetStride(sizeof(Vertex)); // Create vertex buffer LLGL::BufferDescriptor vertexBufferDesc; { vertexBufferDesc.size = vertices.size() * sizeof(Vertex); vertexBufferDesc.bindFlags = LLGL::BindFlags::VertexBuffer; vertexBufferDesc.vertexAttribs = vertexFormat.attributes; } vertexBuffer = renderer->CreateBuffer(vertexBufferDesc, vertices.data()); // Create index buffer (contains both 16 and 32 bit indices) LLGL::BufferDescriptor indexBufferDesc; { indexBufferDesc.size = indices.size() * sizeof(std::uint16_t); indexBufferDesc.bindFlags = LLGL::BindFlags::IndexBuffer; } indexBuffer = renderer->CreateBuffer(indexBufferDesc, indices.data()); return { vertexFormat }; } void CreatePipeline() { LLGL::GraphicsPipelineDescriptor pipelineDesc; { pipelineDesc.shaderProgram = shaderProgram; pipelineDesc.primitiveTopology = LLGL::PrimitiveTopology::TriangleStrip; pipelineDesc.renderPass = context->GetRenderPass(); pipelineDesc.rasterizer.multiSampleEnabled = (GetSampleCount() > 1); } pipeline = renderer->CreatePipelineState(pipelineDesc); } private: void OnDrawFrame() override { // Begin recording commands commands->Begin(); { // Set viewport and scissor rectangle commands->SetViewport(context->GetResolution()); // Set graphics pipeline commands->SetPipelineState(*pipeline); // Set vertex buffer commands->SetVertexBuffer(*vertexBuffer); // Set the render context as the initial render target commands->BeginRenderPass(*context); { // Clear color buffer commands->Clear(LLGL::ClearFlags::Color, backgroundColor); if (indexCount16 > 0) { // TODO: This does not work for D3D12 at the moment as the primitive restart index // (aka. strip cut value) needs to be specified at PSO creation time. commands->SetIndexBuffer(*indexBuffer, LLGL::Format::R16UInt, indexOffset16); commands->DrawIndexed(indexCount16, 0); } if (indexCount32 > 0) { commands->SetIndexBuffer(*indexBuffer, LLGL::Format::R32UInt, indexOffset32); commands->DrawIndexed(indexCount32, 0); } } commands->EndRenderPass(); } commands->End(); commandQueue->Submit(*commands); // Present the result on the screen context->Present(); } }; LLGL_IMPLEMENT_EXAMPLE(Example_PrimitiveRestart); <|endoftext|>
<commit_before>/* * Copyright 2014 Google Inc. 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 <iostream> #include <set> #include <map> #include <random> #include <cassert> #include <fstream> #include <sstream> #include <chrono> using namespace std; constexpr int num_types_per_component = 1; constexpr int num_components_with_no_deps = 10; constexpr int num_components_with_deps = 90; constexpr int num_deps = 10; static_assert(num_components_with_no_deps >= num_deps, "Too few components with no deps."); // This is a constant so that we always generate the same file (=> benchmark more repeatable). unsigned seed = 42; std::default_random_engine generator(seed); string getHeaderName(int n) { ostringstream stream; stream << "component" << n << ".h"; return stream.str(); } string getSourceName(int n) { ostringstream stream; stream << "component" << n << ".cpp"; return stream.str(); } string getObjectName(int n) { ostringstream stream; stream << "component" << n << ".o"; return stream.str(); } void printComponentArgs(int id, ostream& str) { str << "<" << endl; for (int i = 0; i < num_types_per_component; ++i) { str << "Interface" << id << "_" << i; if (i == num_types_per_component - 1) { str << endl; } else { str << "," << endl; } } str << ">"; } void add_node(int n, set<int> deps) { std::string headerName = getHeaderName(n); std::string sourceName = getSourceName(n); ofstream headerFile(headerName); headerFile << "#include <fruit/fruit.h>" << endl << endl; headerFile << "#ifndef COMPONENT" << n << "_H" << endl; headerFile << "#define COMPONENT" << n << "_H" << endl; for (int i = 0; i < num_types_per_component; ++i) { headerFile << "struct Interface" << n << "_" << i << " {};" << endl; } headerFile << "fruit::Component" << endl; printComponentArgs(n, headerFile); headerFile << " getComponent" << n << "();" << endl; headerFile << "#endif // COMPONENT" << n << "_H" << endl; ofstream sourceFile(sourceName); sourceFile << "#include \"" << headerName << "\"" << endl << endl; for (auto dep : deps) { sourceFile << "#include \"" << getHeaderName(dep) << "\"" << endl; } for (int i = 0; i < num_types_per_component; ++i) { sourceFile << "struct X" << n << "_" << i << " : public Interface" << n << "_" << i << " { INJECT(X" << n << "_" << i << "("; for (auto dep = deps.begin(), dep_end = deps.end(); dep != dep_end; ++dep) { if (dep != deps.begin()) { sourceFile << ", "; } sourceFile << "Interface" << *dep << "_" << i << "*"; } sourceFile << ")) {} };" << endl; } sourceFile << "fruit::Component" << endl; printComponentArgs(n, sourceFile); sourceFile << " getComponent" << n << "() {" << endl; sourceFile << " return fruit::createComponent()" << endl; for (auto dep : deps) { sourceFile << " .install(getComponent" << dep << "())" << endl; } for (int i = 0; i < num_types_per_component; ++i) { sourceFile << " .bind<Interface" << n << "_" << i << ", " << "X" << n << "_" << i << ">()" << endl; } sourceFile << ";" << endl; sourceFile << "}" << endl; } void cover(int i, vector<bool>& covered, const map<int, set<int>>& deps_map) { if (covered[i]) { return; } covered[i] = true; for (int dep : deps_map.at(i)) { cover(dep, covered, deps_map); } } int main(int argc, char* argv[]) { if (argc != 3) { cout << "Invalid invocation: " << argv[0]; for (int i = 1; i < argc; i++) { cout << " " << argv[i]; } cout << endl; cout << "Usage: " << argv[0] << " /path/to/compiler path/to/fruit/sources/root" << endl; return 1; } int num_used_ids = 0; map<int, set<int>> deps_map; for (int i = 0; i < num_components_with_no_deps; i++) { int id = num_used_ids++; add_node(id, set<int>{}); deps_map[id] = {}; } // Then the rest have num_deps deps, chosen (pseudo-)randomly from the previous components with no deps, plus the previous // component with deps (if any). for (int i = 0; i < num_components_with_deps; i++) { int current_dep_id = num_used_ids++; set<int> deps; if (i != 0) { deps.insert(i - 1); } std::uniform_int_distribution<int> distribution(0, num_components_with_no_deps - 1); while (deps.size() != num_deps) { int dep = distribution(generator); deps.insert(dep); } add_node(current_dep_id, deps); deps_map[current_dep_id] = deps; } set<int> toplevel_types; vector<bool> covered(num_used_ids, false); for (int i = num_used_ids - 1; i >= 0; --i) { if (!covered[i]) { toplevel_types.insert(i); cover(i, covered, deps_map); } } int toplevel_component = num_used_ids++; add_node(toplevel_component, toplevel_types); ofstream mainFile("main.cpp"); mainFile << "#include \"" << getHeaderName(toplevel_component) << "\"" << endl; mainFile << "#include <ctime>" << endl; mainFile << "#include <iostream>" << endl; mainFile << "#include <iomanip>" << endl; mainFile << "#include <chrono>" << endl; mainFile << "using namespace std;" << endl; mainFile << "int main() {" << endl; mainFile << "size_t num_loops;" << endl; mainFile << "cin >> num_loops;" << endl; mainFile << "double componentCreationTime = 0;" << endl; mainFile << "double componentNormalizationTime = 0;" << endl; //mainFile << "double componentCopyTime = 0;" << endl; //mainFile << "double injectorCreationTime = 0;" << endl; //mainFile << "double injectionTime = 0;" << endl; //mainFile << "double destructionTime = 0;" << endl; mainFile << "double perRequestTime = 0;" << endl; mainFile << "std::chrono::high_resolution_clock::time_point start_time;" << endl; mainFile << "for (size_t i = 0; i < 1 + num_loops/50; i++) {" << endl; mainFile << "start_time = std::chrono::high_resolution_clock::now();" << endl; mainFile << "fruit::Component"; printComponentArgs(toplevel_component, mainFile); mainFile << " component(getComponent" << toplevel_component << "());" << endl; mainFile << "componentCreationTime += 1000000*std::chrono::duration_cast<std::chrono::duration<double>>(std::chrono::high_resolution_clock::now() - start_time).count();" << endl; mainFile << "start_time = std::chrono::high_resolution_clock::now();" << endl; mainFile << "fruit::NormalizedComponent"; printComponentArgs(toplevel_component, mainFile); mainFile << " normalizedComponent(std::move(component));" << endl; mainFile << "componentNormalizationTime += 1000000*std::chrono::duration_cast<std::chrono::duration<double>>(std::chrono::high_resolution_clock::now() - start_time).count();" << endl; mainFile << "}" << endl; mainFile << "fruit::Component"; printComponentArgs(toplevel_component, mainFile); mainFile << " component(getComponent" << toplevel_component << "());" << endl; mainFile << "fruit::NormalizedComponent"; printComponentArgs(toplevel_component, mainFile); mainFile << " normalizedComponent(std::move(component));" << endl; mainFile << "start_time = std::chrono::high_resolution_clock::now();" << endl; mainFile << "for (size_t i = 0; i < num_loops; i++) {" << endl; mainFile << "{" << endl; mainFile << "fruit::NormalizedComponent"; printComponentArgs(toplevel_component, mainFile); mainFile << " normalizedComponentCopy = normalizedComponent;" << endl; // mainFile << "componentCopyTime += 1000000*std::chrono::duration_cast<std::chrono::duration<double>>(std::chrono::high_resolution_clock::now() - start_time).count();" << endl; // mainFile << "start_time = std::chrono::high_resolution_clock::now();" << endl; mainFile << "fruit::Injector"; printComponentArgs(toplevel_component, mainFile); mainFile << " injector(std::move(normalizedComponentCopy), fruit::createComponent());" << endl; // mainFile << "injectorCreationTime += 1000000*std::chrono::duration_cast<std::chrono::duration<double>>(std::chrono::high_resolution_clock::now() - start_time).count();" << endl; // mainFile << "start_time = std::chrono::high_resolution_clock::now();" << endl; for (int i = 0; i < num_types_per_component; ++i) { mainFile << "injector.get<Interface" << toplevel_component << "_" << i << "*>();" << endl; } // mainFile << "injectionTime += 1000000*std::chrono::duration_cast<std::chrono::duration<double>>(std::chrono::high_resolution_clock::now() - start_time).count();" << endl; // mainFile << "start_time = std::chrono::high_resolution_clock::now();" << endl; mainFile << "}" << endl; // mainFile << "destructionTime += 1000000*std::chrono::duration_cast<std::chrono::duration<double>>(std::chrono::high_resolution_clock::now() - start_time).count();" << endl; mainFile << "}" << endl; mainFile << "perRequestTime += 1000000*std::chrono::duration_cast<std::chrono::duration<double>>(std::chrono::high_resolution_clock::now() - start_time).count();" << endl; mainFile << "std::cout << std::fixed;" << endl; mainFile << "std::cout << std::setprecision(2);" << endl; mainFile << "std::cout << \"componentCreationTime = \" << componentCreationTime * 50 / num_loops << std::endl;" << endl; mainFile << "std::cout << \"componentNormalizationTime = \" << componentNormalizationTime * 50 / num_loops << std::endl;" << endl; mainFile << "std::cout << \"Total for setup = \" << (componentCreationTime + componentNormalizationTime) * 50 / num_loops << std::endl;" << endl; //mainFile << "std::cout << \"componentCopyTime = \" << componentCopyTime / num_loops << std::endl;" << endl; //mainFile << "std::cout << \"injectorCreationTime = \" << injectorCreationTime / num_loops << std::endl;" << endl; //mainFile << "std::cout << \"injectionTime = \" << injectionTime / num_loops << std::endl;" << endl; //mainFile << "std::cout << \"destructionTime = \" << destructionTime / num_loops << std::endl;" << endl; mainFile << "std::cout << \"Total per request = \" << perRequestTime / num_loops << std::endl;" << endl; mainFile << "return 0;" << endl; mainFile << "}" << endl; const string compiler = string(argv[1]) + " -std=c++11 -O2 -g -W -Wall -Werror -DNDEBUG -ftemplate-depth=1000 -I" + argv[2] + "/include"; vector<string> fruit_srcs = {"component_storage", "demangle_type_name", "injector_storage", "normalized_component_storage", "semistatic_map"}; ofstream buildFile("build.sh"); buildFile << "#!/bin/bash" << endl; for (int i = 0; i < num_used_ids; i++) { buildFile << compiler << " -c " << getSourceName(i) << " -o " << getObjectName(i) << " &" << endl; if (i % 20 == 0) { // Avoids having too many parallel processes. buildFile << "wait || exit 1" << endl; } } buildFile << compiler << " -c main.cpp -o main.o &" << endl; for (string s : fruit_srcs) { buildFile << compiler << " -c " << argv[2] << "/src/" << s << ".cpp -o " << s << ".o &" << endl; } buildFile << "wait" << endl; buildFile << compiler << " main.o "; for (string s : fruit_srcs) { buildFile << s << ".o "; } for (int i = 0; i < num_used_ids; i++) { buildFile << getObjectName(i) << " "; } buildFile << " -o main" << endl; return 0; } <commit_msg>Update the benchmark to avoid copying NormalizedComponents (it's no longer allowed).<commit_after>/* * Copyright 2014 Google Inc. 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 <iostream> #include <set> #include <map> #include <random> #include <cassert> #include <fstream> #include <sstream> #include <chrono> using namespace std; constexpr int num_types_per_component = 1; constexpr int num_components_with_no_deps = 10; constexpr int num_components_with_deps = 90; constexpr int num_deps = 10; static_assert(num_components_with_no_deps >= num_deps, "Too few components with no deps."); // This is a constant so that we always generate the same file (=> benchmark more repeatable). unsigned seed = 42; std::default_random_engine generator(seed); string getHeaderName(int n) { ostringstream stream; stream << "component" << n << ".h"; return stream.str(); } string getSourceName(int n) { ostringstream stream; stream << "component" << n << ".cpp"; return stream.str(); } string getObjectName(int n) { ostringstream stream; stream << "component" << n << ".o"; return stream.str(); } void printComponentArgs(int id, ostream& str) { str << "<" << endl; for (int i = 0; i < num_types_per_component; ++i) { str << "Interface" << id << "_" << i; if (i == num_types_per_component - 1) { str << endl; } else { str << "," << endl; } } str << ">"; } void add_node(int n, set<int> deps) { std::string headerName = getHeaderName(n); std::string sourceName = getSourceName(n); ofstream headerFile(headerName); headerFile << "#include <fruit/fruit.h>" << endl << endl; headerFile << "#ifndef COMPONENT" << n << "_H" << endl; headerFile << "#define COMPONENT" << n << "_H" << endl; for (int i = 0; i < num_types_per_component; ++i) { headerFile << "struct Interface" << n << "_" << i << " {};" << endl; } headerFile << "fruit::Component" << endl; printComponentArgs(n, headerFile); headerFile << " getComponent" << n << "();" << endl; headerFile << "#endif // COMPONENT" << n << "_H" << endl; ofstream sourceFile(sourceName); sourceFile << "#include \"" << headerName << "\"" << endl << endl; for (auto dep : deps) { sourceFile << "#include \"" << getHeaderName(dep) << "\"" << endl; } for (int i = 0; i < num_types_per_component; ++i) { sourceFile << "struct X" << n << "_" << i << " : public Interface" << n << "_" << i << " { INJECT(X" << n << "_" << i << "("; for (auto dep = deps.begin(), dep_end = deps.end(); dep != dep_end; ++dep) { if (dep != deps.begin()) { sourceFile << ", "; } sourceFile << "Interface" << *dep << "_" << i << "*"; } sourceFile << ")) {} };" << endl; } sourceFile << "fruit::Component" << endl; printComponentArgs(n, sourceFile); sourceFile << " getComponent" << n << "() {" << endl; sourceFile << " return fruit::createComponent()" << endl; for (auto dep : deps) { sourceFile << " .install(getComponent" << dep << "())" << endl; } for (int i = 0; i < num_types_per_component; ++i) { sourceFile << " .bind<Interface" << n << "_" << i << ", " << "X" << n << "_" << i << ">()" << endl; } sourceFile << ";" << endl; sourceFile << "}" << endl; } void cover(int i, vector<bool>& covered, const map<int, set<int>>& deps_map) { if (covered[i]) { return; } covered[i] = true; for (int dep : deps_map.at(i)) { cover(dep, covered, deps_map); } } int main(int argc, char* argv[]) { if (argc != 3) { cout << "Invalid invocation: " << argv[0]; for (int i = 1; i < argc; i++) { cout << " " << argv[i]; } cout << endl; cout << "Usage: " << argv[0] << " /path/to/compiler path/to/fruit/sources/root" << endl; return 1; } int num_used_ids = 0; map<int, set<int>> deps_map; for (int i = 0; i < num_components_with_no_deps; i++) { int id = num_used_ids++; add_node(id, set<int>{}); deps_map[id] = {}; } // Then the rest have num_deps deps, chosen (pseudo-)randomly from the previous components with no deps, plus the previous // component with deps (if any). for (int i = 0; i < num_components_with_deps; i++) { int current_dep_id = num_used_ids++; set<int> deps; if (i != 0) { deps.insert(i - 1); } std::uniform_int_distribution<int> distribution(0, num_components_with_no_deps - 1); while (deps.size() != num_deps) { int dep = distribution(generator); deps.insert(dep); } add_node(current_dep_id, deps); deps_map[current_dep_id] = deps; } set<int> toplevel_types; vector<bool> covered(num_used_ids, false); for (int i = num_used_ids - 1; i >= 0; --i) { if (!covered[i]) { toplevel_types.insert(i); cover(i, covered, deps_map); } } int toplevel_component = num_used_ids++; add_node(toplevel_component, toplevel_types); ofstream mainFile("main.cpp"); mainFile << "#include \"" << getHeaderName(toplevel_component) << "\"" << endl; mainFile << "#include <ctime>" << endl; mainFile << "#include <iostream>" << endl; mainFile << "#include <iomanip>" << endl; mainFile << "#include <chrono>" << endl; mainFile << "using namespace std;" << endl; mainFile << "int main() {" << endl; mainFile << "size_t num_loops;" << endl; mainFile << "cin >> num_loops;" << endl; mainFile << "double componentCreationTime = 0;" << endl; mainFile << "double componentNormalizationTime = 0;" << endl; //mainFile << "double componentCopyTime = 0;" << endl; //mainFile << "double injectorCreationTime = 0;" << endl; //mainFile << "double injectionTime = 0;" << endl; //mainFile << "double destructionTime = 0;" << endl; mainFile << "double perRequestTime = 0;" << endl; mainFile << "std::chrono::high_resolution_clock::time_point start_time;" << endl; mainFile << "for (size_t i = 0; i < 1 + num_loops/50; i++) {" << endl; mainFile << "start_time = std::chrono::high_resolution_clock::now();" << endl; mainFile << "fruit::Component"; printComponentArgs(toplevel_component, mainFile); mainFile << " component(getComponent" << toplevel_component << "());" << endl; mainFile << "componentCreationTime += 1000000*std::chrono::duration_cast<std::chrono::duration<double>>(std::chrono::high_resolution_clock::now() - start_time).count();" << endl; mainFile << "start_time = std::chrono::high_resolution_clock::now();" << endl; mainFile << "fruit::NormalizedComponent"; printComponentArgs(toplevel_component, mainFile); mainFile << " normalizedComponent(std::move(component));" << endl; mainFile << "componentNormalizationTime += 1000000*std::chrono::duration_cast<std::chrono::duration<double>>(std::chrono::high_resolution_clock::now() - start_time).count();" << endl; mainFile << "}" << endl; mainFile << "fruit::Component"; printComponentArgs(toplevel_component, mainFile); mainFile << " component(getComponent" << toplevel_component << "());" << endl; mainFile << "fruit::NormalizedComponent"; printComponentArgs(toplevel_component, mainFile); mainFile << " normalizedComponent(std::move(component));" << endl; mainFile << "start_time = std::chrono::high_resolution_clock::now();" << endl; mainFile << "for (size_t i = 0; i < num_loops; i++) {" << endl; mainFile << "{" << endl; // mainFile << "start_time = std::chrono::high_resolution_clock::now();" << endl; mainFile << "fruit::Injector"; printComponentArgs(toplevel_component, mainFile); mainFile << " injector(normalizedComponent, fruit::createComponent());" << endl; // mainFile << "injectorCreationTime += 1000000*std::chrono::duration_cast<std::chrono::duration<double>>(std::chrono::high_resolution_clock::now() - start_time).count();" << endl; // mainFile << "start_time = std::chrono::high_resolution_clock::now();" << endl; for (int i = 0; i < num_types_per_component; ++i) { mainFile << "injector.get<Interface" << toplevel_component << "_" << i << "*>();" << endl; } // mainFile << "injectionTime += 1000000*std::chrono::duration_cast<std::chrono::duration<double>>(std::chrono::high_resolution_clock::now() - start_time).count();" << endl; // mainFile << "start_time = std::chrono::high_resolution_clock::now();" << endl; mainFile << "}" << endl; // mainFile << "destructionTime += 1000000*std::chrono::duration_cast<std::chrono::duration<double>>(std::chrono::high_resolution_clock::now() - start_time).count();" << endl; mainFile << "}" << endl; mainFile << "perRequestTime += 1000000*std::chrono::duration_cast<std::chrono::duration<double>>(std::chrono::high_resolution_clock::now() - start_time).count();" << endl; mainFile << "std::cout << std::fixed;" << endl; mainFile << "std::cout << std::setprecision(2);" << endl; mainFile << "std::cout << \"componentCreationTime = \" << componentCreationTime * 50 / num_loops << std::endl;" << endl; mainFile << "std::cout << \"componentNormalizationTime = \" << componentNormalizationTime * 50 / num_loops << std::endl;" << endl; mainFile << "std::cout << \"Total for setup = \" << (componentCreationTime + componentNormalizationTime) * 50 / num_loops << std::endl;" << endl; //mainFile << "std::cout << \"injectorCreationTime = \" << injectorCreationTime / num_loops << std::endl;" << endl; //mainFile << "std::cout << \"injectionTime = \" << injectionTime / num_loops << std::endl;" << endl; //mainFile << "std::cout << \"destructionTime = \" << destructionTime / num_loops << std::endl;" << endl; mainFile << "std::cout << \"Total per request = \" << perRequestTime / num_loops << std::endl;" << endl; mainFile << "return 0;" << endl; mainFile << "}" << endl; const string compiler = string(argv[1]) + " -std=c++11 -O2 -g -W -Wall -Werror -DNDEBUG -ftemplate-depth=1000 -I" + argv[2] + "/include"; vector<string> fruit_srcs = {"component_storage", "demangle_type_name", "injector_storage", "normalized_component_storage", "semistatic_map"}; ofstream buildFile("build.sh"); buildFile << "#!/bin/bash" << endl; for (int i = 0; i < num_used_ids; i++) { buildFile << compiler << " -c " << getSourceName(i) << " -o " << getObjectName(i) << " &" << endl; if (i % 20 == 0) { // Avoids having too many parallel processes. buildFile << "wait || exit 1" << endl; } } buildFile << compiler << " -c main.cpp -o main.o &" << endl; for (string s : fruit_srcs) { buildFile << compiler << " -c " << argv[2] << "/src/" << s << ".cpp -o " << s << ".o &" << endl; } buildFile << "wait" << endl; buildFile << compiler << " main.o "; for (string s : fruit_srcs) { buildFile << s << ".o "; } for (int i = 0; i < num_used_ids; i++) { buildFile << getObjectName(i) << " "; } buildFile << " -o main" << endl; return 0; } <|endoftext|>
<commit_before>// $Id$ // system and C includes #include <pcap.h> #include <cstdio> #include </usr/local/include/getopt.h> #include <sys/types.h> #include <unistd.h> #include <sys/socket.h> #include <ifaddrs.h> #include <stdio.h> #include <net/if_dl.h> #include <signal.h> #include <time.h> // C++ includes #include <string> #include <iostream> #include <set> #include <map> #include <algorithm> #include <iterator> using namespace std; // container that keeps pairs (MAC, count) representing src // addresses of packets ordered by MAC adress map<string, int> src; // same for dst addresses map<string, int> dst; // container that keeps pairs (MAC, count) // representing src addresses of packets // ordered by count of packets multimap<int, string> src_score; // same for dst addresses multimap<int, string> dst_score; // keeps list of own macs (for -r handling) set<string> ownmacs; bool g_verbose = false; bool g_remote = false; bool g_mark = false; bool g_debug = false; bool g_ascend = false; bool g_percent = false; bool g_only_dst = false; bool g_only_src = false; bool g_cont = false; #define DEFAULT_PKT_CNT (100) #define DEFAULT_MAC_CNT (-1) #define DEFAULT_DELAY (10) int pkt_cnt = DEFAULT_PKT_CNT; int mac_cnt = DEFAULT_MAC_CNT; int time_delay = DEFAULT_DELAY; int src_cnt; int dst_cnt; int pkt_grb = 0; // number of packets actually grabbed int time_start = 0; void h(u_char * useless, const struct pcap_pkthdr * pkthdr, const u_char * pkt) { char buf[50]; int i; map<string, int>::iterator mit; pkt_grb++; for (i = 0; i < 6; i++) sprintf(buf+3*i, "%02x:", pkt[i]); buf[17] = '\0'; string s1(buf); mit=src.find(s1); // find element of src having MAC equal to s1 if (mit == src.end()) // not found, create src.insert(make_pair(s1, 1)); else // found, increase count by 1 ++(mit -> second); for (i = 0; i < 6; i++) sprintf(buf+3*i, "%02x:", pkt[i + 6]); buf[17] = '\0'; string s2(buf); mit=dst.find(s2); // same for dst if (mit == dst.end()) dst.insert(make_pair(s2, 1)); else ++(mit -> second); if (g_verbose) cout << s1 << " ->> " << s2 << endl; } template<class T> class uncount { int* cnt_var; public: uncount(int* cv) : cnt_var(cv) {} void operator() (T x) { if (ownmacs.find(x.second) != ownmacs.end()) { *cnt_var = *cnt_var - x.first; if (g_debug) cout << "DEBUG uncount: " << x.first << " " << *cnt_var << endl; } } }; // utility for printing pairs to output stream template<class T> class print { ostream &os; int _pkt_cnt; int _mac_cnt; bool g_mac_cnt; public: print(ostream &out, int pc, int mc) : os(out), _pkt_cnt(pc), _mac_cnt(mc) { if (mc != DEFAULT_MAC_CNT) g_mac_cnt = true; else g_mac_cnt = false; } void operator() (T x) { if (g_remote) { if (ownmacs.find(x.second) != ownmacs.end()) { if (g_debug) cout << "DEBUG: erased: " << x.second << endl; return; } } if (g_mac_cnt) { _mac_cnt--; if (_mac_cnt < 0) return; // shouldn't be asserted? } os << "\t" << x.first << "\t" << x.second; if (g_percent) { char s[10]; sprintf(s, "%4.1f", (static_cast<double>(x.first)/_pkt_cnt)*100.0); cout << "\t" << s << "%"; } if (g_mark) { if (ownmacs.find(x.second) != ownmacs.end()) cout << " *"; } cout << endl; } }; // utility for reverting pairs template <class T, class S> class revert { // input: pair (A, B) // output: pair (B, A) public: revert() {} pair<S, T> operator() (pair<T, S> x) { return make_pair(x.second, x.first); } }; void report(void) { // container that keeps pairs (MAC, count) // representing src addresses of packets // ordered by count of packets multimap<int, string> src_score; // same for dst addresses multimap<int, string> dst_score; // count the packets-per-second long delta = time(NULL) - time_start; long pps = pkt_grb / (delta ? delta : 1); cout << endl; cout << "Total packets: " << pkt_grb << " (" << pps << " pkts/s)" << endl; if (!g_only_dst) { cout << "SRC stats:" << endl; src_cnt = pkt_grb; // we have first to copy all stats from src, which is ordered by MAC to src_score // which is ordered by count, making possible printing stats ordered by count transform(src.begin(), src.end(), inserter(src_score, src_score.begin()), revert<string, int>()); if (g_remote) for_each(src_score.begin(), src_score.end(), uncount<pair<int, string> >(&src_cnt)); // and now we simply print stats by count :) if (g_ascend) for_each(src_score.begin(), src_score.end(), print<pair<int, string> >(cout, src_cnt, mac_cnt)); else for_each(src_score.rbegin(), src_score.rend(), print<pair<int, string> >(cout, src_cnt, mac_cnt)); } if (!g_only_src) { cout << "DST stats:" << endl; dst_cnt = pkt_grb; // same for dst transform(dst.begin(), dst.end(), inserter(dst_score, dst_score.begin()), revert<string, int>()); if (g_remote) for_each(dst_score.begin(), dst_score.end(), uncount<pair<int, string> >(&dst_cnt)); if (g_ascend) for_each(dst_score.begin(), dst_score.end(), print<pair<int, string> >(cout, dst_cnt, mac_cnt)); else for_each(dst_score.rbegin(), dst_score.rend(), print<pair<int, string> >(cout, dst_cnt, mac_cnt)); } } void alarm_report(int sig) { report(); alarm(time_delay); } void sig_handler(int sig) { cerr << endl << "saker: shutdown" << endl; exit(127); } int main(int argc, char *argv[]) { char *pcap_dev = NULL; bpf_u_int32 net, mask; char errbuff[1024]; int opt; bool usage = false; // show usage time_start = time(NULL); char rev[255] = "$Revision$"; rev[strlen(rev)-2] = '\0'; char *revp = rev + 11; // skip prefix cerr << "saker v" << revp << endl; signal(SIGINT, sig_handler); signal(SIGTERM, sig_handler); while ((opt = getopt (argc, argv, "i:n:m:t:claphvrsdVD")) != -1) { switch (opt) { case 'i': pcap_dev = (char *) strdup (optarg); break; case 'n': pkt_cnt = atoi(optarg); break; case 'm': mac_cnt = atoi(optarg); break; case 't': time_delay = atoi(optarg); if (time_delay < 1) time_delay = 1; break; case 'a': g_ascend = true; break; case 'p': g_percent = true; break; case 'h': usage = true; break; case 'v': g_verbose = true; break; case 'r': g_remote = true; break; case 'l': g_mark = true; break; case 'c': g_cont = true; break; case 'd': g_only_dst = true; if (g_only_src) { cerr << "Error: You cannot have both -d and -s." << endl; usage = true; } break; case 's': g_only_src = true; if (g_only_dst) { cerr << "Error: You cannot have both -d and -s." << endl; usage = true; } break; case 'V': exit(0); break; case 'D': g_debug = true; break; case '?': default: cerr << "Error: Unknown command line option." << endl; usage = true; break; } } if (usage == false && pcap_dev == NULL) { cerr << "Error: Interface not specified." << endl; usage = true; } if (usage) { cerr << endl << "Usage: saker [-aprmvhVD] [-n num] [-m num] [-s|-d] [-c -t num] -i <if>" << endl << "\t-i <if>\t\tnetwork interface" << endl << "\t-h\t\tshow this info" << endl << "\t-n num\t\tnumber of packets to capture (default " << DEFAULT_PKT_CNT << ", -1 for unlimited)" << endl << "\t-a\t\tascending sort (default descending)" << endl << "\t-m num\t\tnumber of MACs to display in summary (all by default)" << endl << "\t-p\t\tshow percentage" << endl << "\t-r\t\tcount only remote ends (exclude my MACs)" << endl << "\t-l\t\tmark local MACs with asterisk (see also -r)" << endl << "\t-s\t\tshow only source stats" << endl << "\t-d\t\tshow only destination stats" << endl << "\t-c\t\tcontinuous mode" << endl << "\t-t\t\ttime delay for continuous mode in seconds (default "<< DEFAULT_DELAY << ")" << endl << "\t-v\t\tbe verbose (e.g. output each packet)" << endl << "\t-V\t\tprint version and exit" << endl << "\t-D\t\tenable debug output (you are not supposed to understand it)" << endl; exit(1); } cerr << "Listening on: " << pcap_dev << endl; // get own mac's struct ifaddrs *ifap, *ifaphead; int rtnerr; const struct sockaddr_dl *sdl; caddr_t ap; int alen; char ownmac[18] = "..:..:..:..:..:.."; // 6*2+5+1 rtnerr = getifaddrs(&ifaphead); if (rtnerr) { perror("getifaddrs"); exit(2); } if (g_verbose) cout << "Own MAC adresses:" << endl; for (ifap = ifaphead; ifap; ifap = ifap->ifa_next) { if (ifap->ifa_addr->sa_family == AF_LINK) { sdl = (const struct sockaddr_dl *) ifap->ifa_addr; ap = ((caddr_t)((sdl)->sdl_data + (sdl)->sdl_nlen)); alen = sdl->sdl_alen; if (ap && alen > 0) { int i; // printf ("%s:", ifap->ifa_name); device name for (i = 0; i < alen; i++, ap++) { if (i > 0) sprintf(ownmac+2+(i-1)*3,"%c%02x", ':' , 0xff&*ap); else sprintf(ownmac+i*3,"%02x", 0xff&*ap); } if (g_verbose) cout << ownmac << endl; string ownmacstr(ownmac); ownmacs.insert(ownmacstr); } } } if (g_debug) copy(ownmacs.begin(), ownmacs.end(), ostream_iterator<string>(cout, "!\n")); freeifaddrs(ifaphead); // initialize pcap int pcap_net = pcap_lookupnet(pcap_dev, &net, &mask, errbuff); pcap_t *pcap_desc = pcap_open_live(pcap_dev, 100, 1, 1000, errbuff); if (pcap_desc == NULL) { perror("pcap_open_live"); exit(3); } if (g_cont) { signal(SIGALRM, alarm_report); alarm(time_delay); } pcap_loop(pcap_desc, pkt_cnt, h, NULL); report(); return 0; } <commit_msg>unnecessary include removed<commit_after>// $Id$ // system and C includes #include <pcap.h> #include <cstdio> #include <sys/types.h> #include <unistd.h> #include <sys/socket.h> #include <ifaddrs.h> #include <stdio.h> #include <net/if_dl.h> #include <signal.h> #include <time.h> // C++ includes #include <string> #include <iostream> #include <set> #include <map> #include <algorithm> #include <iterator> using namespace std; // container that keeps pairs (MAC, count) representing src // addresses of packets ordered by MAC adress map<string, int> src; // same for dst addresses map<string, int> dst; // container that keeps pairs (MAC, count) // representing src addresses of packets // ordered by count of packets multimap<int, string> src_score; // same for dst addresses multimap<int, string> dst_score; // keeps list of own macs (for -r handling) set<string> ownmacs; bool g_verbose = false; bool g_remote = false; bool g_mark = false; bool g_debug = false; bool g_ascend = false; bool g_percent = false; bool g_only_dst = false; bool g_only_src = false; bool g_cont = false; #define DEFAULT_PKT_CNT (100) #define DEFAULT_MAC_CNT (-1) #define DEFAULT_DELAY (10) int pkt_cnt = DEFAULT_PKT_CNT; int mac_cnt = DEFAULT_MAC_CNT; int time_delay = DEFAULT_DELAY; int src_cnt; int dst_cnt; int pkt_grb = 0; // number of packets actually grabbed int time_start = 0; void h(u_char * useless, const struct pcap_pkthdr * pkthdr, const u_char * pkt) { char buf[50]; int i; map<string, int>::iterator mit; pkt_grb++; for (i = 0; i < 6; i++) sprintf(buf+3*i, "%02x:", pkt[i]); buf[17] = '\0'; string s1(buf); mit=src.find(s1); // find element of src having MAC equal to s1 if (mit == src.end()) // not found, create src.insert(make_pair(s1, 1)); else // found, increase count by 1 ++(mit -> second); for (i = 0; i < 6; i++) sprintf(buf+3*i, "%02x:", pkt[i + 6]); buf[17] = '\0'; string s2(buf); mit=dst.find(s2); // same for dst if (mit == dst.end()) dst.insert(make_pair(s2, 1)); else ++(mit -> second); if (g_verbose) cout << s1 << " ->> " << s2 << endl; } template<class T> class uncount { int* cnt_var; public: uncount(int* cv) : cnt_var(cv) {} void operator() (T x) { if (ownmacs.find(x.second) != ownmacs.end()) { *cnt_var = *cnt_var - x.first; if (g_debug) cout << "DEBUG uncount: " << x.first << " " << *cnt_var << endl; } } }; // utility for printing pairs to output stream template<class T> class print { ostream &os; int _pkt_cnt; int _mac_cnt; bool g_mac_cnt; public: print(ostream &out, int pc, int mc) : os(out), _pkt_cnt(pc), _mac_cnt(mc) { if (mc != DEFAULT_MAC_CNT) g_mac_cnt = true; else g_mac_cnt = false; } void operator() (T x) { if (g_remote) { if (ownmacs.find(x.second) != ownmacs.end()) { if (g_debug) cout << "DEBUG: erased: " << x.second << endl; return; } } if (g_mac_cnt) { _mac_cnt--; if (_mac_cnt < 0) return; // shouldn't be asserted? } os << "\t" << x.first << "\t" << x.second; if (g_percent) { char s[10]; sprintf(s, "%4.1f", (static_cast<double>(x.first)/_pkt_cnt)*100.0); cout << "\t" << s << "%"; } if (g_mark) { if (ownmacs.find(x.second) != ownmacs.end()) cout << " *"; } cout << endl; } }; // utility for reverting pairs template <class T, class S> class revert { // input: pair (A, B) // output: pair (B, A) public: revert() {} pair<S, T> operator() (pair<T, S> x) { return make_pair(x.second, x.first); } }; void report(void) { // container that keeps pairs (MAC, count) // representing src addresses of packets // ordered by count of packets multimap<int, string> src_score; // same for dst addresses multimap<int, string> dst_score; // count the packets-per-second long delta = time(NULL) - time_start; long pps = pkt_grb / (delta ? delta : 1); cout << endl; cout << "Total packets: " << pkt_grb << " (" << pps << " pkts/s)" << endl; if (!g_only_dst) { cout << "SRC stats:" << endl; src_cnt = pkt_grb; // we have first to copy all stats from src, which is ordered by MAC to src_score // which is ordered by count, making possible printing stats ordered by count transform(src.begin(), src.end(), inserter(src_score, src_score.begin()), revert<string, int>()); if (g_remote) for_each(src_score.begin(), src_score.end(), uncount<pair<int, string> >(&src_cnt)); // and now we simply print stats by count :) if (g_ascend) for_each(src_score.begin(), src_score.end(), print<pair<int, string> >(cout, src_cnt, mac_cnt)); else for_each(src_score.rbegin(), src_score.rend(), print<pair<int, string> >(cout, src_cnt, mac_cnt)); } if (!g_only_src) { cout << "DST stats:" << endl; dst_cnt = pkt_grb; // same for dst transform(dst.begin(), dst.end(), inserter(dst_score, dst_score.begin()), revert<string, int>()); if (g_remote) for_each(dst_score.begin(), dst_score.end(), uncount<pair<int, string> >(&dst_cnt)); if (g_ascend) for_each(dst_score.begin(), dst_score.end(), print<pair<int, string> >(cout, dst_cnt, mac_cnt)); else for_each(dst_score.rbegin(), dst_score.rend(), print<pair<int, string> >(cout, dst_cnt, mac_cnt)); } } void alarm_report(int sig) { report(); alarm(time_delay); } void sig_handler(int sig) { cerr << endl << "saker: shutdown" << endl; exit(127); } int main(int argc, char *argv[]) { char *pcap_dev = NULL; bpf_u_int32 net, mask; char errbuff[1024]; int opt; bool usage = false; // show usage time_start = time(NULL); char rev[255] = "$Revision$"; rev[strlen(rev)-2] = '\0'; char *revp = rev + 11; // skip prefix cerr << "saker v" << revp << endl; signal(SIGINT, sig_handler); signal(SIGTERM, sig_handler); while ((opt = getopt (argc, argv, "i:n:m:t:claphvrsdVD")) != -1) { switch (opt) { case 'i': pcap_dev = (char *) strdup (optarg); break; case 'n': pkt_cnt = atoi(optarg); break; case 'm': mac_cnt = atoi(optarg); break; case 't': time_delay = atoi(optarg); if (time_delay < 1) time_delay = 1; break; case 'a': g_ascend = true; break; case 'p': g_percent = true; break; case 'h': usage = true; break; case 'v': g_verbose = true; break; case 'r': g_remote = true; break; case 'l': g_mark = true; break; case 'c': g_cont = true; break; case 'd': g_only_dst = true; if (g_only_src) { cerr << "Error: You cannot have both -d and -s." << endl; usage = true; } break; case 's': g_only_src = true; if (g_only_dst) { cerr << "Error: You cannot have both -d and -s." << endl; usage = true; } break; case 'V': exit(0); break; case 'D': g_debug = true; break; case '?': default: cerr << "Error: Unknown command line option." << endl; usage = true; break; } } if (usage == false && pcap_dev == NULL) { cerr << "Error: Interface not specified." << endl; usage = true; } if (usage) { cerr << endl << "Usage: saker [-aprmvhVD] [-n num] [-m num] [-s|-d] [-c -t num] -i <if>" << endl << "\t-i <if>\t\tnetwork interface" << endl << "\t-h\t\tshow this info" << endl << "\t-n num\t\tnumber of packets to capture (default " << DEFAULT_PKT_CNT << ", -1 for unlimited)" << endl << "\t-a\t\tascending sort (default descending)" << endl << "\t-m num\t\tnumber of MACs to display in summary (all by default)" << endl << "\t-p\t\tshow percentage" << endl << "\t-r\t\tcount only remote ends (exclude my MACs)" << endl << "\t-l\t\tmark local MACs with asterisk (see also -r)" << endl << "\t-s\t\tshow only source stats" << endl << "\t-d\t\tshow only destination stats" << endl << "\t-c\t\tcontinuous mode" << endl << "\t-t\t\ttime delay for continuous mode in seconds (default "<< DEFAULT_DELAY << ")" << endl << "\t-v\t\tbe verbose (e.g. output each packet)" << endl << "\t-V\t\tprint version and exit" << endl << "\t-D\t\tenable debug output (you are not supposed to understand it)" << endl; exit(1); } cerr << "Listening on: " << pcap_dev << endl; // get own mac's struct ifaddrs *ifap, *ifaphead; int rtnerr; const struct sockaddr_dl *sdl; caddr_t ap; int alen; char ownmac[18] = "..:..:..:..:..:.."; // 6*2+5+1 rtnerr = getifaddrs(&ifaphead); if (rtnerr) { perror("getifaddrs"); exit(2); } if (g_verbose) cout << "Own MAC adresses:" << endl; for (ifap = ifaphead; ifap; ifap = ifap->ifa_next) { if (ifap->ifa_addr->sa_family == AF_LINK) { sdl = (const struct sockaddr_dl *) ifap->ifa_addr; ap = ((caddr_t)((sdl)->sdl_data + (sdl)->sdl_nlen)); alen = sdl->sdl_alen; if (ap && alen > 0) { int i; // printf ("%s:", ifap->ifa_name); device name for (i = 0; i < alen; i++, ap++) { if (i > 0) sprintf(ownmac+2+(i-1)*3,"%c%02x", ':' , 0xff&*ap); else sprintf(ownmac+i*3,"%02x", 0xff&*ap); } if (g_verbose) cout << ownmac << endl; string ownmacstr(ownmac); ownmacs.insert(ownmacstr); } } } if (g_debug) copy(ownmacs.begin(), ownmacs.end(), ostream_iterator<string>(cout, "!\n")); freeifaddrs(ifaphead); // initialize pcap int pcap_net = pcap_lookupnet(pcap_dev, &net, &mask, errbuff); pcap_t *pcap_desc = pcap_open_live(pcap_dev, 100, 1, 1000, errbuff); if (pcap_desc == NULL) { perror("pcap_open_live"); exit(3); } if (g_cont) { signal(SIGALRM, alarm_report); alarm(time_delay); } pcap_loop(pcap_desc, pkt_cnt, h, NULL); report(); return 0; } <|endoftext|>
<commit_before>#include "perf_precomp.hpp" using namespace std; using namespace cv; using namespace perf; using namespace testing; using std::tr1::make_tuple; using std::tr1::get; enum{HALF_SIZE=0, UPSIDE_DOWN, REFLECTION_X, REFLECTION_BOTH}; CV_ENUM(BorderMode, BORDER_CONSTANT, BORDER_REPLICATE) CV_ENUM(InterType, INTER_NEAREST, INTER_LINEAR) CV_ENUM(RemapMode, HALF_SIZE, UPSIDE_DOWN, REFLECTION_X, REFLECTION_BOTH) typedef TestBaseWithParam< tr1::tuple<Size, InterType, BorderMode> > TestWarpAffine; typedef TestBaseWithParam< tr1::tuple<Size, InterType, BorderMode> > TestWarpPerspective; typedef TestBaseWithParam< tr1::tuple<MatType, Size, InterType, BorderMode, RemapMode> > TestRemap; void update_map(const Mat& src, Mat& map_x, Mat& map_y, const int remapMode ); PERF_TEST_P( TestWarpAffine, WarpAffine, Combine( Values( szVGA, sz720p, sz1080p ), ValuesIn( InterType::all() ), ValuesIn( BorderMode::all() ) ) ) { Size sz; int borderMode, interType; sz = get<0>(GetParam()); borderMode = get<1>(GetParam()); interType = get<2>(GetParam()); Mat src, img = imread(getDataPath("cv/shared/fruits.png")); cvtColor(img, src, COLOR_BGR2RGBA, 4); Mat warpMat = getRotationMatrix2D(Point2f(src.cols/2.f, src.rows/2.f), 30., 2.2); Mat dst(sz, CV_8UC4); declare.in(src).out(dst); TEST_CYCLE() warpAffine( src, dst, warpMat, sz, interType, borderMode, Scalar::all(150) ); SANITY_CHECK(dst); } PERF_TEST_P( TestWarpPerspective, WarpPerspective, Combine( Values( szVGA, sz720p, sz1080p ), ValuesIn( InterType::all() ), ValuesIn( BorderMode::all() ) ) ) { Size sz; int borderMode, interType; sz = get<0>(GetParam()); borderMode = get<1>(GetParam()); interType = get<2>(GetParam()); Mat src, img = imread(getDataPath("cv/shared/fruits.png")); cvtColor(img, src, COLOR_BGR2RGBA, 4); Mat rotMat = getRotationMatrix2D(Point2f(src.cols/2.f, src.rows/2.f), 30., 2.2); Mat warpMat(3, 3, CV_64FC1); for(int r=0; r<2; r++) for(int c=0; c<3; c++) warpMat.at<double>(r, c) = rotMat.at<double>(r, c); warpMat.at<double>(2, 0) = .3/sz.width; warpMat.at<double>(2, 1) = .3/sz.height; warpMat.at<double>(2, 2) = 1; Mat dst(sz, CV_8UC4); declare.in(src).out(dst); TEST_CYCLE() warpPerspective( src, dst, warpMat, sz, interType, borderMode, Scalar::all(150) ); SANITY_CHECK(dst); } PERF_TEST_P( TestWarpPerspective, WarpPerspectiveLarge, Combine( Values( sz3MP, sz5MP ), ValuesIn( InterType::all() ), ValuesIn( BorderMode::all() ) ) ) { Size sz; int borderMode, interType; sz = get<0>(GetParam()); borderMode = get<1>(GetParam()); interType = get<2>(GetParam()); string resolution; if (sz == sz3MP) resolution = "3MP"; else if (sz == sz5MP) resolution = "5MP"; else FAIL(); Mat src, img = imread(getDataPath("cv/shared/" + resolution + ".png")); cvtColor(img, src, COLOR_BGR2BGRA, 4); int shift = 103; Mat srcVertices = (Mat_<Vec2f>(1, 4) << Vec2f(0, 0), Vec2f(sz.width-1, 0), Vec2f(sz.width-1, sz.height-1), Vec2f(0, sz.height-1)); Mat dstVertices = (Mat_<Vec2f>(1, 4) << Vec2f(0, shift), Vec2f(sz.width-shift/2, 0), Vec2f(sz.width-shift, sz.height-shift), Vec2f(shift/2, sz.height-1)); Mat warpMat = getPerspectiveTransform(srcVertices, dstVertices); Mat dst(sz, CV_8UC4); declare.in(src).out(dst); TEST_CYCLE() warpPerspective( src, dst, warpMat, sz, interType, borderMode, Scalar::all(150) ); SANITY_CHECK(dst); //imwrite("/home/kir/temp/dst" + resolution + ".png", dst); } PERF_TEST_P( TestRemap, remap, Combine( Values( TYPICAL_MAT_TYPES ), Values( szVGA, sz720p, sz1080p ), ValuesIn( InterType::all() ), ValuesIn( BorderMode::all() ), ValuesIn( RemapMode::all() ) ) ) { int type = get<0>(GetParam()); Size size = get<1>(GetParam()); int interpolationType = get<2>(GetParam()); int borderMode = get<3>(GetParam()); int remapMode = get<4>(GetParam()); unsigned int height = size.height; unsigned int width = size.width; Mat source(height, width, type); Mat destination; Mat map_x(height, width, CV_32F); Mat map_y(height, width, CV_32F); declare.in(source, WARMUP_RNG); update_map(source, map_x, map_y, remapMode); TEST_CYCLE() { remap(source, destination, map_x, map_y, interpolationType, borderMode); } SANITY_CHECK(destination, 1); } void update_map(const Mat& src, Mat& map_x, Mat& map_y, const int remapMode ) { for( int j = 0; j < src.rows; j++ ) { for( int i = 0; i < src.cols; i++ ) { switch( remapMode ) { case HALF_SIZE: if( i > src.cols*0.25 && i < src.cols*0.75 && j > src.rows*0.25 && j < src.rows*0.75 ) { map_x.at<float>(j,i) = 2*( i - src.cols*0.25f ) + 0.5f ; map_y.at<float>(j,i) = 2*( j - src.rows*0.25f ) + 0.5f ; } else { map_x.at<float>(j,i) = 0 ; map_y.at<float>(j,i) = 0 ; } break; case UPSIDE_DOWN: map_x.at<float>(j,i) = static_cast<float>(i) ; map_y.at<float>(j,i) = static_cast<float>(src.rows - j) ; break; case REFLECTION_X: map_x.at<float>(j,i) = static_cast<float>(src.cols - i) ; map_y.at<float>(j,i) = static_cast<float>(j) ; break; case REFLECTION_BOTH: map_x.at<float>(j,i) = static_cast<float>(src.cols - i) ; map_y.at<float>(j,i) = static_cast<float>(src.rows - j) ; break; } // end of switch } } } PERF_TEST(Transform, getPerspectiveTransform) { unsigned int size = 8; Mat source(1, size/2, CV_32FC2); Mat destination(1, size/2, CV_32FC2); Mat transformCoefficient; declare.in(source, destination, WARMUP_RNG); TEST_CYCLE() { transformCoefficient = getPerspectiveTransform(source, destination); } SANITY_CHECK(transformCoefficient, 1e-5); } <commit_msg>deleted wrong line<commit_after>#include "perf_precomp.hpp" using namespace std; using namespace cv; using namespace perf; using namespace testing; using std::tr1::make_tuple; using std::tr1::get; enum{HALF_SIZE=0, UPSIDE_DOWN, REFLECTION_X, REFLECTION_BOTH}; CV_ENUM(BorderMode, BORDER_CONSTANT, BORDER_REPLICATE) CV_ENUM(InterType, INTER_NEAREST, INTER_LINEAR) CV_ENUM(RemapMode, HALF_SIZE, UPSIDE_DOWN, REFLECTION_X, REFLECTION_BOTH) typedef TestBaseWithParam< tr1::tuple<Size, InterType, BorderMode> > TestWarpAffine; typedef TestBaseWithParam< tr1::tuple<Size, InterType, BorderMode> > TestWarpPerspective; typedef TestBaseWithParam< tr1::tuple<MatType, Size, InterType, BorderMode, RemapMode> > TestRemap; void update_map(const Mat& src, Mat& map_x, Mat& map_y, const int remapMode ); PERF_TEST_P( TestWarpAffine, WarpAffine, Combine( Values( szVGA, sz720p, sz1080p ), ValuesIn( InterType::all() ), ValuesIn( BorderMode::all() ) ) ) { Size sz; int borderMode, interType; sz = get<0>(GetParam()); borderMode = get<1>(GetParam()); interType = get<2>(GetParam()); Mat src, img = imread(getDataPath("cv/shared/fruits.png")); cvtColor(img, src, COLOR_BGR2RGBA, 4); Mat warpMat = getRotationMatrix2D(Point2f(src.cols/2.f, src.rows/2.f), 30., 2.2); Mat dst(sz, CV_8UC4); declare.in(src).out(dst); TEST_CYCLE() warpAffine( src, dst, warpMat, sz, interType, borderMode, Scalar::all(150) ); SANITY_CHECK(dst); } PERF_TEST_P( TestWarpPerspective, WarpPerspective, Combine( Values( szVGA, sz720p, sz1080p ), ValuesIn( InterType::all() ), ValuesIn( BorderMode::all() ) ) ) { Size sz; int borderMode, interType; sz = get<0>(GetParam()); borderMode = get<1>(GetParam()); interType = get<2>(GetParam()); Mat src, img = imread(getDataPath("cv/shared/fruits.png")); cvtColor(img, src, COLOR_BGR2RGBA, 4); Mat rotMat = getRotationMatrix2D(Point2f(src.cols/2.f, src.rows/2.f), 30., 2.2); Mat warpMat(3, 3, CV_64FC1); for(int r=0; r<2; r++) for(int c=0; c<3; c++) warpMat.at<double>(r, c) = rotMat.at<double>(r, c); warpMat.at<double>(2, 0) = .3/sz.width; warpMat.at<double>(2, 1) = .3/sz.height; warpMat.at<double>(2, 2) = 1; Mat dst(sz, CV_8UC4); declare.in(src).out(dst); TEST_CYCLE() warpPerspective( src, dst, warpMat, sz, interType, borderMode, Scalar::all(150) ); SANITY_CHECK(dst); } PERF_TEST_P( TestWarpPerspective, WarpPerspectiveLarge, Combine( Values( sz3MP, sz5MP ), ValuesIn( InterType::all() ), ValuesIn( BorderMode::all() ) ) ) { Size sz; int borderMode, interType; sz = get<0>(GetParam()); borderMode = get<1>(GetParam()); interType = get<2>(GetParam()); string resolution; if (sz == sz3MP) resolution = "3MP"; else if (sz == sz5MP) resolution = "5MP"; else FAIL(); Mat src, img = imread(getDataPath("cv/shared/" + resolution + ".png")); cvtColor(img, src, COLOR_BGR2BGRA, 4); int shift = 103; Mat srcVertices = (Mat_<Vec2f>(1, 4) << Vec2f(0, 0), Vec2f(sz.width-1, 0), Vec2f(sz.width-1, sz.height-1), Vec2f(0, sz.height-1)); Mat dstVertices = (Mat_<Vec2f>(1, 4) << Vec2f(0, shift), Vec2f(sz.width-shift/2, 0), Vec2f(sz.width-shift, sz.height-shift), Vec2f(shift/2, sz.height-1)); Mat warpMat = getPerspectiveTransform(srcVertices, dstVertices); Mat dst(sz, CV_8UC4); declare.in(src).out(dst); TEST_CYCLE() warpPerspective( src, dst, warpMat, sz, interType, borderMode, Scalar::all(150) ); SANITY_CHECK(dst); } PERF_TEST_P( TestRemap, remap, Combine( Values( TYPICAL_MAT_TYPES ), Values( szVGA, sz720p, sz1080p ), ValuesIn( InterType::all() ), ValuesIn( BorderMode::all() ), ValuesIn( RemapMode::all() ) ) ) { int type = get<0>(GetParam()); Size size = get<1>(GetParam()); int interpolationType = get<2>(GetParam()); int borderMode = get<3>(GetParam()); int remapMode = get<4>(GetParam()); unsigned int height = size.height; unsigned int width = size.width; Mat source(height, width, type); Mat destination; Mat map_x(height, width, CV_32F); Mat map_y(height, width, CV_32F); declare.in(source, WARMUP_RNG); update_map(source, map_x, map_y, remapMode); TEST_CYCLE() { remap(source, destination, map_x, map_y, interpolationType, borderMode); } SANITY_CHECK(destination, 1); } void update_map(const Mat& src, Mat& map_x, Mat& map_y, const int remapMode ) { for( int j = 0; j < src.rows; j++ ) { for( int i = 0; i < src.cols; i++ ) { switch( remapMode ) { case HALF_SIZE: if( i > src.cols*0.25 && i < src.cols*0.75 && j > src.rows*0.25 && j < src.rows*0.75 ) { map_x.at<float>(j,i) = 2*( i - src.cols*0.25f ) + 0.5f ; map_y.at<float>(j,i) = 2*( j - src.rows*0.25f ) + 0.5f ; } else { map_x.at<float>(j,i) = 0 ; map_y.at<float>(j,i) = 0 ; } break; case UPSIDE_DOWN: map_x.at<float>(j,i) = static_cast<float>(i) ; map_y.at<float>(j,i) = static_cast<float>(src.rows - j) ; break; case REFLECTION_X: map_x.at<float>(j,i) = static_cast<float>(src.cols - i) ; map_y.at<float>(j,i) = static_cast<float>(j) ; break; case REFLECTION_BOTH: map_x.at<float>(j,i) = static_cast<float>(src.cols - i) ; map_y.at<float>(j,i) = static_cast<float>(src.rows - j) ; break; } // end of switch } } } PERF_TEST(Transform, getPerspectiveTransform) { unsigned int size = 8; Mat source(1, size/2, CV_32FC2); Mat destination(1, size/2, CV_32FC2); Mat transformCoefficient; declare.in(source, destination, WARMUP_RNG); TEST_CYCLE() { transformCoefficient = getPerspectiveTransform(source, destination); } SANITY_CHECK(transformCoefficient, 1e-5); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: frameloaderfactory.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2006-09-17 07:37:28 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_filter.hxx" #include "frameloaderfactory.hxx" #include "macros.hxx" #include "constant.hxx" #include "versions.hxx" //_______________________________________________ // includes #ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_ #include <com/sun/star/lang/XInitialization.hpp> #endif #ifndef _COMPHELPER_ENUMHELPER_HXX_ #include <comphelper/enumhelper.hxx> #endif //_______________________________________________ // namespace namespace filter{ namespace config{ namespace css = ::com::sun::star; //_______________________________________________ // definitions /*----------------------------------------------- 09.07.2003 07:43 -----------------------------------------------*/ FrameLoaderFactory::FrameLoaderFactory(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR) { BaseContainer::init(xSMGR , FrameLoaderFactory::impl_getImplementationName() , FrameLoaderFactory::impl_getSupportedServiceNames(), FilterCache::E_FRAMELOADER ); } /*----------------------------------------------- 09.07.2003 07:43 -----------------------------------------------*/ FrameLoaderFactory::~FrameLoaderFactory() { } /*----------------------------------------------- 16.07.2003 13:37 -----------------------------------------------*/ css::uno::Reference< css::uno::XInterface > SAL_CALL FrameLoaderFactory::createInstance(const ::rtl::OUString& sLoader) throw(css::uno::Exception , css::uno::RuntimeException) { return createInstanceWithArguments(sLoader, css::uno::Sequence< css::uno::Any >()); } /*----------------------------------------------- 17.07.2003 09:00 -----------------------------------------------*/ css::uno::Reference< css::uno::XInterface > SAL_CALL FrameLoaderFactory::createInstanceWithArguments(const ::rtl::OUString& sLoader , const css::uno::Sequence< css::uno::Any >& lArguments) throw(css::uno::Exception , css::uno::RuntimeException) { // SAFE -> ::osl::ResettableMutexGuard aLock(m_aLock); ::rtl::OUString sRealLoader = sLoader; #ifdef _FILTER_CONFIG_MIGRATION_Q_ /* -> TODO - HACK check if the given loader name realy exist ... Because our old implementation worked with an internal type name instead of a loader name. For a small migration time we must simulate this old feature :-( */ if (!m_rCache->hasItem(FilterCache::E_FRAMELOADER, sLoader) && m_rCache->hasItem(FilterCache::E_TYPE, sLoader)) { _FILTER_CONFIG_LOG_("FrameLoaderFactory::createInstanceWithArguments() ... simulate old type search functionality!\n"); css::uno::Sequence< ::rtl::OUString > lTypes(1); lTypes[0] = sLoader; css::uno::Sequence< css::beans::NamedValue > lQuery(1); lQuery[0].Name = PROPNAME_TYPES; lQuery[0].Value <<= lTypes; css::uno::Reference< css::container::XEnumeration > xSet = createSubSetEnumerationByProperties(lQuery); while(xSet->hasMoreElements()) { ::comphelper::SequenceAsHashMap lLoaderProps(xSet->nextElement()); if (!(lLoaderProps[PROPNAME_NAME] >>= sRealLoader)) continue; } // prevent outside code against NoSuchElementException! // But dont implement such defensive strategy for our new create handling :-) if (!m_rCache->hasItem(FilterCache::E_FRAMELOADER, sRealLoader)) return css::uno::Reference< css::uno::XInterface>(); } /* <- HACK */ #endif // _FILTER_CONFIG_MIGRATION_Q_ // search loader on cache CacheItem aLoader = m_rCache->getItem(m_eType, sRealLoader); // create service instance css::uno::Reference< css::uno::XInterface > xLoader = m_xSMGR->createInstance(sRealLoader); // initialize filter css::uno::Reference< css::lang::XInitialization > xInit(xLoader, css::uno::UNO_QUERY); if (xInit.is()) { // format: lInitData[0] = seq<PropertyValue>, which contains all configuration properties of this loader // lInitData[1] = lArguments[0] // ... // lInitData[n] = lArguments[n-1] css::uno::Sequence< css::beans::PropertyValue > lConfig; aLoader >> lConfig; ::comphelper::SequenceAsVector< css::uno::Any > stlArguments(lArguments); stlArguments.insert(stlArguments.begin(), css::uno::makeAny(lConfig)); css::uno::Sequence< css::uno::Any > lInitData; stlArguments >> lInitData; xInit->initialize(lInitData); } return xLoader; // <- SAFE } /*----------------------------------------------- 09.07.2003 07:46 -----------------------------------------------*/ css::uno::Sequence< ::rtl::OUString > SAL_CALL FrameLoaderFactory::getAvailableServiceNames() throw(css::uno::RuntimeException) { // must be the same list as ((XNameAccess*)this)->getElementNames() return! return getElementNames(); } /*----------------------------------------------- 09.07.2003 07:43 -----------------------------------------------*/ ::rtl::OUString FrameLoaderFactory::impl_getImplementationName() { return ::rtl::OUString::createFromAscii("com.sun.star.comp.filter.config.FrameLoaderFactory"); } /*----------------------------------------------- 09.07.2003 07:43 -----------------------------------------------*/ css::uno::Sequence< ::rtl::OUString > FrameLoaderFactory::impl_getSupportedServiceNames() { css::uno::Sequence< ::rtl::OUString > lServiceNames(1); lServiceNames[0] = ::rtl::OUString::createFromAscii("com.sun.star.frame.FrameLoaderFactory"); return lServiceNames; } /*----------------------------------------------- 09.07.2003 07:43 -----------------------------------------------*/ css::uno::Reference< css::uno::XInterface > SAL_CALL FrameLoaderFactory::impl_createInstance(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR) { FrameLoaderFactory* pNew = new FrameLoaderFactory(xSMGR); return css::uno::Reference< css::uno::XInterface >(static_cast< css::lang::XMultiServiceFactory* >(pNew), css::uno::UNO_QUERY); } } // namespace config } // namespace filter <commit_msg>INTEGRATION: CWS changefileheader (1.4.252); FILE MERGED 2008/04/01 15:15:53 thb 1.4.252.3: #i85898# Stripping all external header guards 2008/04/01 10:56:15 thb 1.4.252.2: #i85898# Stripping all external header guards 2008/03/28 15:31:02 rt 1.4.252.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: frameloaderfactory.cxx,v $ * $Revision: 1.5 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_filter.hxx" #include "frameloaderfactory.hxx" #include "macros.hxx" #include "constant.hxx" #include "versions.hxx" //_______________________________________________ // includes #include <com/sun/star/lang/XInitialization.hpp> #include <comphelper/enumhelper.hxx> //_______________________________________________ // namespace namespace filter{ namespace config{ namespace css = ::com::sun::star; //_______________________________________________ // definitions /*----------------------------------------------- 09.07.2003 07:43 -----------------------------------------------*/ FrameLoaderFactory::FrameLoaderFactory(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR) { BaseContainer::init(xSMGR , FrameLoaderFactory::impl_getImplementationName() , FrameLoaderFactory::impl_getSupportedServiceNames(), FilterCache::E_FRAMELOADER ); } /*----------------------------------------------- 09.07.2003 07:43 -----------------------------------------------*/ FrameLoaderFactory::~FrameLoaderFactory() { } /*----------------------------------------------- 16.07.2003 13:37 -----------------------------------------------*/ css::uno::Reference< css::uno::XInterface > SAL_CALL FrameLoaderFactory::createInstance(const ::rtl::OUString& sLoader) throw(css::uno::Exception , css::uno::RuntimeException) { return createInstanceWithArguments(sLoader, css::uno::Sequence< css::uno::Any >()); } /*----------------------------------------------- 17.07.2003 09:00 -----------------------------------------------*/ css::uno::Reference< css::uno::XInterface > SAL_CALL FrameLoaderFactory::createInstanceWithArguments(const ::rtl::OUString& sLoader , const css::uno::Sequence< css::uno::Any >& lArguments) throw(css::uno::Exception , css::uno::RuntimeException) { // SAFE -> ::osl::ResettableMutexGuard aLock(m_aLock); ::rtl::OUString sRealLoader = sLoader; #ifdef _FILTER_CONFIG_MIGRATION_Q_ /* -> TODO - HACK check if the given loader name realy exist ... Because our old implementation worked with an internal type name instead of a loader name. For a small migration time we must simulate this old feature :-( */ if (!m_rCache->hasItem(FilterCache::E_FRAMELOADER, sLoader) && m_rCache->hasItem(FilterCache::E_TYPE, sLoader)) { _FILTER_CONFIG_LOG_("FrameLoaderFactory::createInstanceWithArguments() ... simulate old type search functionality!\n"); css::uno::Sequence< ::rtl::OUString > lTypes(1); lTypes[0] = sLoader; css::uno::Sequence< css::beans::NamedValue > lQuery(1); lQuery[0].Name = PROPNAME_TYPES; lQuery[0].Value <<= lTypes; css::uno::Reference< css::container::XEnumeration > xSet = createSubSetEnumerationByProperties(lQuery); while(xSet->hasMoreElements()) { ::comphelper::SequenceAsHashMap lLoaderProps(xSet->nextElement()); if (!(lLoaderProps[PROPNAME_NAME] >>= sRealLoader)) continue; } // prevent outside code against NoSuchElementException! // But dont implement such defensive strategy for our new create handling :-) if (!m_rCache->hasItem(FilterCache::E_FRAMELOADER, sRealLoader)) return css::uno::Reference< css::uno::XInterface>(); } /* <- HACK */ #endif // _FILTER_CONFIG_MIGRATION_Q_ // search loader on cache CacheItem aLoader = m_rCache->getItem(m_eType, sRealLoader); // create service instance css::uno::Reference< css::uno::XInterface > xLoader = m_xSMGR->createInstance(sRealLoader); // initialize filter css::uno::Reference< css::lang::XInitialization > xInit(xLoader, css::uno::UNO_QUERY); if (xInit.is()) { // format: lInitData[0] = seq<PropertyValue>, which contains all configuration properties of this loader // lInitData[1] = lArguments[0] // ... // lInitData[n] = lArguments[n-1] css::uno::Sequence< css::beans::PropertyValue > lConfig; aLoader >> lConfig; ::comphelper::SequenceAsVector< css::uno::Any > stlArguments(lArguments); stlArguments.insert(stlArguments.begin(), css::uno::makeAny(lConfig)); css::uno::Sequence< css::uno::Any > lInitData; stlArguments >> lInitData; xInit->initialize(lInitData); } return xLoader; // <- SAFE } /*----------------------------------------------- 09.07.2003 07:46 -----------------------------------------------*/ css::uno::Sequence< ::rtl::OUString > SAL_CALL FrameLoaderFactory::getAvailableServiceNames() throw(css::uno::RuntimeException) { // must be the same list as ((XNameAccess*)this)->getElementNames() return! return getElementNames(); } /*----------------------------------------------- 09.07.2003 07:43 -----------------------------------------------*/ ::rtl::OUString FrameLoaderFactory::impl_getImplementationName() { return ::rtl::OUString::createFromAscii("com.sun.star.comp.filter.config.FrameLoaderFactory"); } /*----------------------------------------------- 09.07.2003 07:43 -----------------------------------------------*/ css::uno::Sequence< ::rtl::OUString > FrameLoaderFactory::impl_getSupportedServiceNames() { css::uno::Sequence< ::rtl::OUString > lServiceNames(1); lServiceNames[0] = ::rtl::OUString::createFromAscii("com.sun.star.frame.FrameLoaderFactory"); return lServiceNames; } /*----------------------------------------------- 09.07.2003 07:43 -----------------------------------------------*/ css::uno::Reference< css::uno::XInterface > SAL_CALL FrameLoaderFactory::impl_createInstance(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR) { FrameLoaderFactory* pNew = new FrameLoaderFactory(xSMGR); return css::uno::Reference< css::uno::XInterface >(static_cast< css::lang::XMultiServiceFactory* >(pNew), css::uno::UNO_QUERY); } } // namespace config } // namespace filter <|endoftext|>
<commit_before>#pragma once #include <cstdlib> #include <cstdint> #include <utility> namespace darkfeed { /// @brief Serializes data using Simple-Binary-Encoding with internal framing /// @ingroup serialization class SBESerializer { public: /// @brief Serializes argument using appropriate SBE schema. No framing is needed. /// @param buf The buffer to serialize the object to. /// @param buf_size The size of the buffer in bytes /// @warning buf must be sufficiently large to accomodate the resulting data. It's recommended to round it up an order of magnitude larger than the sum of the fields in bytes. Eg; for a 200 byte message, make this 1kB. /// @param x The object to serialize /// @return The number of bytes written to buf template<typename T> static std::size_t serialize(char *buf, std::size_t buf_size, const T &x); /// @brief Deserializes argument using appropriate flatbuffer schema. No framing is assumed. /// @param buf The buffer containing the SBE serialized data /// @return a pair containing the deserialized object and a status indicator. If the status indicator is true, deserialization was successful. template<typename T> static std::pair<T, bool> deserialize(const char *buf, std::size_t len); /// @brief Returns the type of message. Can be cast to darkfeed::EventType /// @param buf The buffer containing the SBE serialized data /// @param len The size of the buffer in bytes /// @return Message type ID (castable to darkfeed::EventType) std::uint8_t msg_type(const char *buf, std::size_t len); }; } <commit_msg>[cpp] Fix incorrect wording in SBESerializer docs<commit_after>#pragma once #include <cstdlib> #include <cstdint> #include <utility> namespace darkfeed { /// @brief Serializes data using Simple-Binary-Encoding with internal framing /// @ingroup serialization class SBESerializer { public: /// @brief Serializes argument using appropriate SBE schema. Framing is added within the SBE header. /// @param buf The buffer to serialize the object to. /// @param buf_size The size of the buffer in bytes /// @warning buf must be sufficiently large to accomodate the resulting data. It's recommended to round it up an order of magnitude larger than the sum of the fields in bytes. Eg; for a 200 byte message, make this 1kB. /// @param x The object to serialize /// @return The number of bytes written to buf template<typename T> static std::size_t serialize(char *buf, std::size_t buf_size, const T &x); /// @brief Deserializes argument using appropriate flatbuffer schema. No framing is assumed. /// @param buf The buffer containing the SBE serialized data /// @return a pair containing the deserialized object and a status indicator. If the status indicator is true, deserialization was successful. template<typename T> static std::pair<T, bool> deserialize(const char *buf, std::size_t len); /// @brief Returns the type of message. Can be cast to darkfeed::EventType /// @param buf The buffer containing the SBE serialized data /// @param len The size of the buffer in bytes /// @return Message type ID (castable to darkfeed::EventType) std::uint8_t msg_type(const char *buf, std::size_t len); }; } <|endoftext|>
<commit_before>#include "rust_scheduler.h" #include "rust_util.h" rust_scheduler::rust_scheduler(rust_kernel *kernel, rust_srv *srv, size_t num_threads, rust_sched_id id) : kernel(kernel), srv(srv), env(srv->env), live_threads(num_threads), live_tasks(0), num_threads(num_threads), id(id) { create_task_threads(); } rust_scheduler::~rust_scheduler() { destroy_task_threads(); } rust_task_thread * rust_scheduler::create_task_thread(int id) { rust_srv *srv = this->srv->clone(); rust_task_thread *thread = new (kernel, "rust_task_thread") rust_task_thread(this, srv, id); KLOG(kernel, kern, "created task thread: " PTR ", id: %d, index: %d", thread, id, thread->list_index); return thread; } void rust_scheduler::destroy_task_thread(rust_task_thread *thread) { KLOG(kernel, kern, "deleting task thread: " PTR ", name: %s, index: %d", thread, thread->name, thread->list_index); rust_srv *srv = thread->srv; delete thread; delete srv; } void rust_scheduler::create_task_threads() { KLOG(kernel, kern, "Using %d scheduler threads.", num_threads); for(size_t i = 0; i < num_threads; ++i) { threads.push(create_task_thread(i)); } } void rust_scheduler::destroy_task_threads() { for(size_t i = 0; i < num_threads; ++i) { destroy_task_thread(threads[i]); } } void rust_scheduler::start_task_threads() { for(size_t i = 0; i < num_threads; ++i) { rust_task_thread *thread = threads[i]; thread->start(); } } void rust_scheduler::join_task_threads() { for(size_t i = 0; i < num_threads; ++i) { rust_task_thread *thread = threads[i]; thread->join(); } } void rust_scheduler::kill_all_tasks() { for(size_t i = 0; i < num_threads; ++i) { rust_task_thread *thread = threads[i]; thread->kill_all_tasks(); } } rust_task * rust_scheduler::create_task(rust_task *spawner, const char *name) { size_t thread_no; { scoped_lock with(lock); live_tasks++; if (++cur_thread >= num_threads) cur_thread = 0; thread_no = cur_thread; } rust_task_thread *thread = threads[thread_no]; return thread->create_task(spawner, name); } void rust_scheduler::release_task() { bool need_exit = false; { scoped_lock with(lock); live_tasks--; if (live_tasks == 0) { need_exit = true; } } if (need_exit) { // There are no more tasks on this scheduler. Time to leave exit(); } } void rust_scheduler::exit() { // Take a copy of num_threads. After the last thread exits this // scheduler will get destroyed, and our fields will cease to exist. size_t current_num_threads = num_threads; for(size_t i = 0; i < current_num_threads; ++i) { threads[i]->exit(); } } size_t rust_scheduler::number_of_threads() { return num_threads; } void rust_scheduler::release_task_thread() { uintptr_t new_live_threads; { scoped_lock with(lock); new_live_threads = --live_threads; } if (new_live_threads == 0) { kernel->release_scheduler_id(id); } } <commit_msg>initialize cur_thread, first task on thread 0<commit_after>#include "rust_scheduler.h" #include "rust_util.h" rust_scheduler::rust_scheduler(rust_kernel *kernel, rust_srv *srv, size_t num_threads, rust_sched_id id) : kernel(kernel), srv(srv), env(srv->env), live_threads(num_threads), live_tasks(0), num_threads(num_threads), cur_thread(0), id(id) { create_task_threads(); } rust_scheduler::~rust_scheduler() { destroy_task_threads(); } rust_task_thread * rust_scheduler::create_task_thread(int id) { rust_srv *srv = this->srv->clone(); rust_task_thread *thread = new (kernel, "rust_task_thread") rust_task_thread(this, srv, id); KLOG(kernel, kern, "created task thread: " PTR ", id: %d, index: %d", thread, id, thread->list_index); return thread; } void rust_scheduler::destroy_task_thread(rust_task_thread *thread) { KLOG(kernel, kern, "deleting task thread: " PTR ", name: %s, index: %d", thread, thread->name, thread->list_index); rust_srv *srv = thread->srv; delete thread; delete srv; } void rust_scheduler::create_task_threads() { KLOG(kernel, kern, "Using %d scheduler threads.", num_threads); for(size_t i = 0; i < num_threads; ++i) { threads.push(create_task_thread(i)); } } void rust_scheduler::destroy_task_threads() { for(size_t i = 0; i < num_threads; ++i) { destroy_task_thread(threads[i]); } } void rust_scheduler::start_task_threads() { for(size_t i = 0; i < num_threads; ++i) { rust_task_thread *thread = threads[i]; thread->start(); } } void rust_scheduler::join_task_threads() { for(size_t i = 0; i < num_threads; ++i) { rust_task_thread *thread = threads[i]; thread->join(); } } void rust_scheduler::kill_all_tasks() { for(size_t i = 0; i < num_threads; ++i) { rust_task_thread *thread = threads[i]; thread->kill_all_tasks(); } } rust_task * rust_scheduler::create_task(rust_task *spawner, const char *name) { size_t thread_no; { scoped_lock with(lock); live_tasks++; thread_no = cur_thread++; if (cur_thread >= num_threads) cur_thread = 0; } rust_task_thread *thread = threads[thread_no]; return thread->create_task(spawner, name); } void rust_scheduler::release_task() { bool need_exit = false; { scoped_lock with(lock); live_tasks--; if (live_tasks == 0) { need_exit = true; } } if (need_exit) { // There are no more tasks on this scheduler. Time to leave exit(); } } void rust_scheduler::exit() { // Take a copy of num_threads. After the last thread exits this // scheduler will get destroyed, and our fields will cease to exist. size_t current_num_threads = num_threads; for(size_t i = 0; i < current_num_threads; ++i) { threads[i]->exit(); } } size_t rust_scheduler::number_of_threads() { return num_threads; } void rust_scheduler::release_task_thread() { uintptr_t new_live_threads; { scoped_lock with(lock); new_live_threads = --live_threads; } if (new_live_threads == 0) { kernel->release_scheduler_id(id); } } <|endoftext|>
<commit_before><commit_msg>fdo#76324: Make pasting a lot of cell notes faster by disabling broadcasting.<commit_after><|endoftext|>
<commit_before><commit_msg>We can't deal with "date" field mixed with ordinary strings.<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: core_pch.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2001-08-10 10:15:35 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ // ItemID-Defines etc. muessen immer ganz vorne stehen #include "scitems.hxx" #include "eetext.hxx" #define ITEMID_FIELD EE_FEATURE_FIELD #define _ZFORLIST_DECLARE_TABLE #define SC_PROGRESS_CXX // ab hier automatisch per makepch generiert // folgende duerfen nicht aufgenommen werden: // setjmp.h #include <tools/solar.h> #include <string.h> #include <tools/string.hxx> #include <tools/rtti.hxx> #include <limits.h> #include <tools/ref.hxx> #include <tools/list.hxx> #include <tools/contnr.hxx> #include <tools/link.hxx> #include <tools/stream.hxx> #include <tools/errinf.hxx> #include <tools/errcode.hxx> #include <vcl/sv.h> #include <global.hxx> #include <vcl/color.hxx> #include <tools/lang.hxx> #include <tools/debug.hxx> #include <tools/gen.hxx> #include <svtools/svarray.hxx> #include <markarr.hxx> #include <vcl/timer.hxx> #include <rangelst.hxx> #include <document.hxx> #include <vcl/prntypes.hxx> #include <table.hxx> #include <column.hxx> #include <svtools/hint.hxx> #include <svtools/lstner.hxx> #include <svtools/args.hxx> #include <svtools/poolitem.hxx> #include <tools/time.hxx> #include <svtools/solar.hrc> #include <tools/date.hxx> #include <svtools/brdcst.hxx> #include <svx/svxids.hrc> #include <svtools/memberid.hrc> #include <sfx2/sfx.hrc> #include <sfx2/sfxsids.hrc> #include <svtools/cntwids.hrc> #include <tools/resid.hxx> #include <tools/table.hxx> #include <stdarg.h> #include <vcl/rc.hxx> #include <tools/rc.hxx> #include <tools/resmgr.hxx> #include <vcl/resid.hxx> #include <tools/unqidx.hxx> #include <rsc/rscsfx.hxx> #include <svtools/sbxdef.hxx> #include <svtools/itemset.hxx> #include <stddef.h> #include <collect.hxx> #include <scitems.hxx> #include <tools/globname.hxx> #include <tools/fract.hxx> #include <sfx2/shell.hxx> #include <cell.hxx> #include <tools/mempool.hxx> #include <vcl/color.hxx> #include <vcl/region.hxx> #include <vcl/mapmod.hxx> #include <vcl/bitmap.hxx> #include <svtools/eitem.hxx> #include <svtools/intitem.hxx> #include <sot/object.hxx> #include <sot/factory.hxx> #include <sot/sotdata.hxx> #include <vcl/keycod.hxx> #include <vcl/keycodes.hxx> #include <sot/sotref.hxx> #include <rechead.hxx> #include <tools/unqid.hxx> #include <vcl/apptypes.hxx> #include <vcl/fonttype.hxx> #include <globstr.hrc> #include <compiler.hrc> #include <tools/shl.hxx> #include <compiler.hxx> #include <vcl/font.hxx> #include <svtools/smplhint.hxx> #include <vcl/wall.hxx> #include <vcl/settings.hxx> #include <vcl/accel.hxx> #include <vcl/gdiobj.hxx> #include <patattr.hxx> #include <svtools/zforlist.hxx> #include <tools/pstm.hxx> #include <vcl/svapp.hxx> #include <vcl/outdev.hxx> #include <vcl/pointr.hxx> #include <vcl/ptrstyle.hxx> #include <vcl/wintypes.hxx> #include <vcl/event.hxx> #include <tools/ownlist.hxx> #include <svtools/itempool.hxx> #include <tools/datetime.hxx> #include <so3/factory.hxx> #include <so3/so2dll.hxx> #include <so3/iface.hxx> #include <attrib.hxx> #include <so3/so2ref.hxx> #include <so3/persist.hxx> #include <docpool.hxx> #include <sot/storage.hxx> #include <so3/so2defs.hxx> #include <sfx2/objsh.hxx> #include <vcl/window.hxx> #include <sfx2/cfgitem.hxx> #include <svtools/confitem.hxx> #include <vcl/syswin.hxx> #include <sc.hrc> #include <svx/dialogs.hrc> #include <math.h> #include <svtools/style.hxx> #include <svtools/style.hrc> #include <stdlib.h> #include <vcl/prntypes.hxx> #include <vcl/jobset.hxx> #include <vcl/gdimtf.hxx> //#include <setjmp.h> #include <tools/urlobj.hxx> #include <vcl/print.hxx> #include <docoptio.hxx> #include <markdata.hxx> #include <vcl/system.hxx> #include <vcl/wrkwin.hxx> #include <stlpool.hxx> #include <sfx2/app.hxx> #include <svtools/inetmsg.hxx> #include <svtools/compat.hxx> #include <svtools/inetdef.hxx> #include <svtools/inethist.hxx> #include <svtools/cancel.hxx> #include <vcl/accel.hxx> #include <sfx2/sfxdefs.hxx> #include <sfx2/module.hxx> #include <sfx2/imgdef.hxx> #include <segmentc.hxx> #include <tcov.hxx> #include <vcl/ctrl.hxx> #include <vcl/field.hxx> #include <vcl/spinfld.hxx> #include <vcl/edit.hxx> #include <vcl/timer.hxx> #include <vcl/combobox.hxx> #include <vcl/combobox.h> #include <refupdat.hxx> #include <svx/boxitem.hxx> #include <conditio.hxx> #include <brdcst.hxx> #include <svx/svxenum.hxx> #include <dociter.hxx> #include <scdll.hxx> #include <stdio.h> #include <stlsheet.hxx> #include <vcl/gdiobj.hxx> #include <vcl/mapmod.hxx> #include <progress.hxx> #include <sfx2/progress.hxx> #include <vcl/event.hxx> #include <vcl/window.hxx> #include <svx/algitem.hxx> #include <vcl/field.hxx> #include <svx/svdtypes.hxx> #include <vcl/graph.hxx> #include <vcl/bitmapex.hxx> #include <vcl/animate.hxx> #include <vcl/graph.h> #include <drwlayer.hxx> #include <svx/svdmodel.hxx> #include <scresid.hxx> #include <vcl/print.hxx> #include <attarray.hxx> #include <so3/pseudo.hxx> #include <svtools/ownlist.hxx> #include <interpre.hxx> #include <subtotal.hxx> #include <rangenam.hxx> #include <scmatrix.hxx> #include <svx/pageitem.hxx> #include <dbcolect.hxx> #include <userlist.hxx> #include <svx/editdata.hxx> #include <svtools/sbxvar.hxx> #include <svtools/sbxcore.hxx> #include <svx/svdobj.hxx> #include <svx/svdsob.hxx> #include <svx/svdglue.hxx> #include <svx/langitem.hxx> #include <svx/eeitem.hxx> #include <callform.hxx> #include <validat.hxx> #include <so3/linkmgr.hxx> #include <svx/brshitem.hxx> #include <so3/lnkbase.hxx> #include <sot/exchange.hxx> #include <svx/editeng.hxx> #include <vcl/fonttype.hxx> #include <svx/editobj.hxx> #include <svx/wghtitem.hxx> #include <svx/fhgtitem.hxx> #include <svtools/stritem.hxx> #include <pivot.hxx> #include <vcl/gdimtf.hxx> #include <svx/svdpage.hxx> #include <svx/svdlayer.hxx> #include <svx/linkmgr.hxx> #include <ctype.h> #include <vcl/font.hxx> #include <svx/fontitem.hxx> #include <svx/postitem.hxx> #include <so3/protocol.hxx> #include <svx/svditer.hxx> #include <svx/udlnitem.hxx> #include <adiasync.hxx> #include <sfx2/bindings.hxx> #include <ddelink.hxx> #include <chartlis.hxx> #include <sfx2/minarray.hxx> #include <svtools/txtcmp.hxx> #include <olinetab.hxx> #include <svtools/sbxobj.hxx> #include <cfgids.hxx> <commit_msg>INTEGRATION: CWS qdiet01 (1.8.290); FILE MERGED 2003/10/09 10:35:30 mh 1.8.290.1: del: unused file, #i18390#<commit_after>/************************************************************************* * * $RCSfile: core_pch.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: obo $ $Date: 2003-10-20 15:36:09 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ // ItemID-Defines etc. muessen immer ganz vorne stehen #include "scitems.hxx" #include "eetext.hxx" #define ITEMID_FIELD EE_FEATURE_FIELD #define _ZFORLIST_DECLARE_TABLE #define SC_PROGRESS_CXX // ab hier automatisch per makepch generiert // folgende duerfen nicht aufgenommen werden: // setjmp.h #include <tools/solar.h> #include <string.h> #include <tools/string.hxx> #include <tools/rtti.hxx> #include <limits.h> #include <tools/ref.hxx> #include <tools/list.hxx> #include <tools/contnr.hxx> #include <tools/link.hxx> #include <tools/stream.hxx> #include <tools/errinf.hxx> #include <tools/errcode.hxx> #include <vcl/sv.h> #include <global.hxx> #include <vcl/color.hxx> #include <tools/lang.hxx> #include <tools/debug.hxx> #include <tools/gen.hxx> #include <svtools/svarray.hxx> #include <markarr.hxx> #include <vcl/timer.hxx> #include <rangelst.hxx> #include <document.hxx> #include <vcl/prntypes.hxx> #include <table.hxx> #include <column.hxx> #include <svtools/hint.hxx> #include <svtools/lstner.hxx> #include <svtools/args.hxx> #include <svtools/poolitem.hxx> #include <tools/time.hxx> #include <svtools/solar.hrc> #include <tools/date.hxx> #include <svtools/brdcst.hxx> #include <svx/svxids.hrc> #include <svtools/memberid.hrc> #include <sfx2/sfx.hrc> #include <sfx2/sfxsids.hrc> #include <svtools/cntwids.hrc> #include <tools/resid.hxx> #include <tools/table.hxx> #include <stdarg.h> #include <vcl/rc.hxx> #include <tools/rc.hxx> #include <tools/resmgr.hxx> #include <vcl/resid.hxx> #include <tools/unqidx.hxx> #include <rsc/rscsfx.hxx> #include <svtools/sbxdef.hxx> #include <svtools/itemset.hxx> #include <stddef.h> #include <collect.hxx> #include <scitems.hxx> #include <tools/globname.hxx> #include <tools/fract.hxx> #include <sfx2/shell.hxx> #include <cell.hxx> #include <tools/mempool.hxx> #include <vcl/color.hxx> #include <vcl/region.hxx> #include <vcl/mapmod.hxx> #include <vcl/bitmap.hxx> #include <svtools/eitem.hxx> #include <svtools/intitem.hxx> #include <sot/object.hxx> #include <sot/factory.hxx> #include <sot/sotdata.hxx> #include <vcl/keycod.hxx> #include <vcl/keycodes.hxx> #include <sot/sotref.hxx> #include <rechead.hxx> #include <tools/unqid.hxx> #include <vcl/apptypes.hxx> #include <vcl/fonttype.hxx> #include <globstr.hrc> #include <compiler.hrc> #include <tools/shl.hxx> #include <compiler.hxx> #include <vcl/font.hxx> #include <svtools/smplhint.hxx> #include <vcl/wall.hxx> #include <vcl/settings.hxx> #include <vcl/accel.hxx> #include <vcl/gdiobj.hxx> #include <patattr.hxx> #include <svtools/zforlist.hxx> #include <tools/pstm.hxx> #include <vcl/svapp.hxx> #include <vcl/outdev.hxx> #include <vcl/pointr.hxx> #include <vcl/ptrstyle.hxx> #include <vcl/wintypes.hxx> #include <vcl/event.hxx> #include <tools/ownlist.hxx> #include <svtools/itempool.hxx> #include <tools/datetime.hxx> #include <so3/factory.hxx> #include <so3/so2dll.hxx> #include <so3/iface.hxx> #include <attrib.hxx> #include <so3/so2ref.hxx> #include <so3/persist.hxx> #include <docpool.hxx> #include <sot/storage.hxx> #include <so3/so2defs.hxx> #include <sfx2/objsh.hxx> #include <vcl/window.hxx> #include <sfx2/cfgitem.hxx> #include <svtools/confitem.hxx> #include <vcl/syswin.hxx> #include <sc.hrc> #include <svx/dialogs.hrc> #include <math.h> #include <svtools/style.hxx> #include <svtools/style.hrc> #include <stdlib.h> #include <vcl/prntypes.hxx> #include <vcl/jobset.hxx> #include <vcl/gdimtf.hxx> //#include <setjmp.h> #include <tools/urlobj.hxx> #include <vcl/print.hxx> #include <docoptio.hxx> #include <markdata.hxx> #include <vcl/system.hxx> #include <vcl/wrkwin.hxx> #include <stlpool.hxx> #include <sfx2/app.hxx> #include <svtools/inetmsg.hxx> #include <svtools/compat.hxx> #include <svtools/inetdef.hxx> #include <svtools/inethist.hxx> #include <svtools/cancel.hxx> #include <vcl/accel.hxx> #include <sfx2/sfxdefs.hxx> #include <sfx2/module.hxx> #include <sfx2/imgdef.hxx> #include <vcl/ctrl.hxx> #include <vcl/field.hxx> #include <vcl/spinfld.hxx> #include <vcl/edit.hxx> #include <vcl/timer.hxx> #include <vcl/combobox.hxx> #include <vcl/combobox.h> #include <refupdat.hxx> #include <svx/boxitem.hxx> #include <conditio.hxx> #include <brdcst.hxx> #include <svx/svxenum.hxx> #include <dociter.hxx> #include <scdll.hxx> #include <stdio.h> #include <stlsheet.hxx> #include <vcl/gdiobj.hxx> #include <vcl/mapmod.hxx> #include <progress.hxx> #include <sfx2/progress.hxx> #include <vcl/event.hxx> #include <vcl/window.hxx> #include <svx/algitem.hxx> #include <vcl/field.hxx> #include <svx/svdtypes.hxx> #include <vcl/graph.hxx> #include <vcl/bitmapex.hxx> #include <vcl/animate.hxx> #include <vcl/graph.h> #include <drwlayer.hxx> #include <svx/svdmodel.hxx> #include <scresid.hxx> #include <vcl/print.hxx> #include <attarray.hxx> #include <so3/pseudo.hxx> #include <svtools/ownlist.hxx> #include <interpre.hxx> #include <subtotal.hxx> #include <rangenam.hxx> #include <scmatrix.hxx> #include <svx/pageitem.hxx> #include <dbcolect.hxx> #include <userlist.hxx> #include <svx/editdata.hxx> #include <svtools/sbxvar.hxx> #include <svtools/sbxcore.hxx> #include <svx/svdobj.hxx> #include <svx/svdsob.hxx> #include <svx/svdglue.hxx> #include <svx/langitem.hxx> #include <svx/eeitem.hxx> #include <callform.hxx> #include <validat.hxx> #include <so3/linkmgr.hxx> #include <svx/brshitem.hxx> #include <so3/lnkbase.hxx> #include <sot/exchange.hxx> #include <svx/editeng.hxx> #include <vcl/fonttype.hxx> #include <svx/editobj.hxx> #include <svx/wghtitem.hxx> #include <svx/fhgtitem.hxx> #include <svtools/stritem.hxx> #include <pivot.hxx> #include <vcl/gdimtf.hxx> #include <svx/svdpage.hxx> #include <svx/svdlayer.hxx> #include <svx/linkmgr.hxx> #include <ctype.h> #include <vcl/font.hxx> #include <svx/fontitem.hxx> #include <svx/postitem.hxx> #include <so3/protocol.hxx> #include <svx/svditer.hxx> #include <svx/udlnitem.hxx> #include <adiasync.hxx> #include <sfx2/bindings.hxx> #include <ddelink.hxx> #include <chartlis.hxx> #include <sfx2/minarray.hxx> #include <svtools/txtcmp.hxx> #include <olinetab.hxx> #include <svtools/sbxobj.hxx> #include <cfgids.hxx> <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: imp_op.hxx,v $ * * $Revision: 1.40 $ * * last change: $Author: vg $ $Date: 2007-02-27 12:34:36 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _IMP_OP_HXX #define _IMP_OP_HXX #ifndef _GEN_HXX //autogen #include <tools/gen.hxx> #endif #ifndef SC_XIROOT_HXX #include "xiroot.hxx" #endif #ifndef SC_XISTREAM_HXX #include "xistream.hxx" #endif #ifndef SC_XISTYLE_HXX #include "xistyle.hxx" #endif #ifndef _FLTTYPES_HXX #include "flttypes.hxx" #endif #ifndef _NAMEBUFF_HXX #include "namebuff.hxx" #endif #ifndef _ROOT_HXX #include "root.hxx" #endif #ifndef _OTLNBUFF_HXX #include "otlnbuff.hxx" #endif #ifndef _COLROWST_HXX #include "colrowst.hxx" #endif #ifndef _EXCDEFS_HXX #include "excdefs.hxx" #endif class SfxItemSet; class SvStream; class ScFormulaCell; class SdrObject; class ScDocument; class ScToken; class _ScRangeListTabs; class ExcelToSc; class ImportTyp { protected: CharSet eQuellChar; // Quell-Zeichensatz ScDocument* pD; // Dokument public: ImportTyp( ScDocument*, CharSet eSrc ); virtual ~ImportTyp(); virtual FltError Read( void ); }; class SvInPlaceObjectRef; struct ExcelChartData { Rectangle aRect; // Ecken String aTitle, aXTitle, aYTitle, aZTitle; String aLastLabel; // letzter SERIESTEXT-Label SfxItemSet* pAttrs; // Attribute ExcelChartData* pNext; // wer weiss schon... SCCOL nCol1, nCol2; SCROW nRow1, nRow2; SCTAB nTab1, nTab2; // Quellbereich SCTAB nBaseTab; UINT32 nObjNum; ExcelChartData( ScDocument*, const Point&, const Point&, const SCTAB nBaseTab ); ~ExcelChartData(); }; class XclImpOutlineDataBuffer : protected XclImpRoot { public: explicit XclImpOutlineDataBuffer( const XclImpRoot& rRoot, SCTAB nScTab ); virtual ~XclImpOutlineDataBuffer(); inline XclImpColRowSettings* GetColRowBuff() const { return mxColRowBuff.get(); } inline XclImpOutlineBuffer* GetColOutline() const { return mxColOutlineBuff.get(); } inline XclImpOutlineBuffer* GetRowOutline() const { return mxRowOutlineBuff.get(); } void Convert(); private: typedef ScfRef< XclImpOutlineBuffer > XclImpOutlineBfrRef; typedef ScfRef< XclImpColRowSettings > XclImpColRowSettRef; XclImpOutlineBfrRef mxColOutlineBuff; XclImpOutlineBfrRef mxRowOutlineBuff; XclImpColRowSettRef mxColRowBuff; SCTAB mnScTab; }; class ImportExcel : public ImportTyp, protected XclImpRoot { private: ExcelChartData* pChart; // aktuelle Chart-Daten ExcelChartData* pUsedChartFirst; // benutzte Chart-Daten, erster ExcelChartData* pUsedChartLast; // benutzte Chart-Daten, letzter protected: static const double fExcToTwips; // Umrechnung 1/256 Zeichen -> Twips RootData* pExcRoot; XclImpStream maStrm; // input stream XclImpStream& aIn; // input stream NameBuffer* pExtNameBuff; // ... externe Namen (Ind.-Basis=1) ExcelToSc* pFormConv; // Formel-Konverter XclImpOutlineBuffer* pColOutlineBuff; XclImpOutlineBuffer* pRowOutlineBuff; XclImpColRowSettings* pColRowBuff; // Col/Row-Einstellungen 1 Tabelle typedef ScfDelList< XclImpOutlineDataBuffer > XclImpOutlineListBuffer; XclImpOutlineListBuffer* pOutlineListBuffer; UINT16 nIxfeIndex; // merkt sich Angabe im IXFE-Record UINT16 nLastXF; // letzter XF in Formula-Record SCTAB nBdshtTab; // Counter fuer Boundsheet ScFormulaCell* pLastFormCell; // fuer String-Records BOOL bTabTruncated; // wenn Bereichsueberschreitung zum // Abschneiden von Zellen fuehrt // Record-Funktionen sal_uInt16 ReadXFIndex( bool bBiff2 ); void ReadDimensions(); void ReadBlank(); void ReadInteger(); void ReadNumber(); void ReadLabel(); void ReadBoolErr(); void ReadRk(); void Window1(); void Formula25( void ); // 0x06 -> excform.cxx void Row25( void ); // 0x08 void Bof2( void ); // 0x09 void Eof( void ); // 0x0A void DocProtect( void ); // 0x12 void Protect( void ); // 0x12 Sheet Protection BOOL Password( void ); // 0x13 void Externsheet( void ); // 0x17 void Note( void ); // 0x1C void Columndefault( void ); // 0x20 void Array25( void ); // 0x21 void Rec1904( void ); // 0x22 void Externname25( void ); // 0x23 void Colwidth( void ); // 0x24 void Defrowheight2( void ); // 0x25 // void Window1( void ); // 0x3D void Codepage( void ); // 0x42 void Ixfe( void ); // 0x44 void DefColWidth( void ); // 0x55 void Builtinfmtcnt( void ); // 0x56 void Obj( void ); // 0x5D void Colinfo( void ); // 0x7D void Wsbool( void ); // 0x81 void Boundsheet( void ); // 0x85 void Country( void ); // 0x8C void Hideobj( void ); // 0x8D void Bundleheader( void ); // 0x8F void Standardwidth( void ); // 0x99 void Shrfmla( void ); // 0xBC void Mulrk( void ); // 0xBD void Mulblank( void ); // 0xBE void Rstring( void ); // 0xD6 void Cellmerging( void ); // 0xE5 void Olesize( void ); // 0xDE void ReadUsesElfs(); // 0x0160 void Formula3( void ); // 0x0206 -> excform.cxx // 0x0207 -> 0x07 void Row34( void ); // 0x0208 void Bof3( void ); // 0x0209 void Array34( void ); // 0x0221 void Externname34( void ); // 0x0223 void Defrowheight345( void ); // 0x0225 void TableOp( void ); // 0x0236 //void Rk( void ); // 0x027E -> 0x7E void Formula4( void ); // 0x0406 -> excform.cxx void Bof4( void ); // 0x0409 void Bof5( void ); // 0x0809 // --------------------------------------------------------------- void SetLineStyle( SfxItemSet&, short, short, short ); void SetFillStyle( SfxItemSet&, short, short, short ); SdrObject* LineObj( SfxItemSet&, const Point&, const Point& ); SdrObject* RectObj( SfxItemSet&, const Point&, const Point& ); SdrObject* BeginChartObj( SfxItemSet&, const Point&, const Point& ); void EndChartObj( void ); void ChartSelection( void ); void ChartSeriesText( void ); void ChartObjectLink( void ); void ChartAi( void ); // --------------------------------------------------------------- void Formula( const XclAddress& rXclPos, UINT16 nXF, UINT16 nFormLen, double &rCurVal, BOOL bShrFmla ); // -> excform.cxx virtual void EndSheet( void ); void NeueTabelle( void ); const ScTokenArray* ErrorToFormula( BYTE bErrOrVal, BYTE nError, double& rVal ); virtual void EndAllChartObjects( void ); // -> excobj.cxx virtual void AdjustRowHeight(); virtual void PostDocLoad( void ); public: ImportExcel( XclImpRootData& rImpData, SvStream& rStrm ); virtual ~ImportExcel( void ); virtual FltError Read( void ); }; #endif <commit_msg>INTEGRATION: CWS chart2mst3 (1.34.26); FILE MERGED 2007/04/25 02:57:05 bm 1.34.26.8: RESYNC: (1.39-1.40); FILE MERGED 2006/10/16 11:15:13 dr 1.34.26.7: RESYNC: (1.37-1.39); FILE MERGED 2006/07/11 14:13:47 dr 1.34.26.6: #export of chart line and area formats 2006/06/16 13:41:30 bm 1.34.26.5: RESYNC: (1.36-1.37); FILE MERGED 2006/05/05 15:14:06 bm 1.34.26.4: RESYNC: (1.35-1.36); FILE MERGED 2006/02/22 14:19:46 dr 1.34.26.3: joined new dumper from dr46 2006/01/25 14:15:28 bm 1.34.26.2: RESYNC: (1.34-1.35); FILE MERGED 2005/11/16 17:00:54 dr 1.34.26.1: #i3997# remove non-working BIFF5 chart import<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: imp_op.hxx,v $ * * $Revision: 1.41 $ * * last change: $Author: vg $ $Date: 2007-05-22 19:55:08 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _IMP_OP_HXX #define _IMP_OP_HXX #ifndef _GEN_HXX //autogen #include <tools/gen.hxx> #endif #ifndef SC_XIROOT_HXX #include "xiroot.hxx" #endif #ifndef SC_XISTREAM_HXX #include "xistream.hxx" #endif #ifndef SC_XISTYLE_HXX #include "xistyle.hxx" #endif #ifndef _FLTTYPES_HXX #include "flttypes.hxx" #endif #ifndef _NAMEBUFF_HXX #include "namebuff.hxx" #endif #ifndef _ROOT_HXX #include "root.hxx" #endif #ifndef _OTLNBUFF_HXX #include "otlnbuff.hxx" #endif #ifndef _COLROWST_HXX #include "colrowst.hxx" #endif #ifndef _EXCDEFS_HXX #include "excdefs.hxx" #endif class SfxItemSet; class SvStream; class ScFormulaCell; class SdrObject; class ScDocument; class ScToken; class _ScRangeListTabs; class ExcelToSc; class ImportTyp { protected: CharSet eQuellChar; // Quell-Zeichensatz ScDocument* pD; // Dokument public: ImportTyp( ScDocument*, CharSet eSrc ); virtual ~ImportTyp(); virtual FltError Read( void ); }; class XclImpOutlineDataBuffer : protected XclImpRoot { public: explicit XclImpOutlineDataBuffer( const XclImpRoot& rRoot, SCTAB nScTab ); virtual ~XclImpOutlineDataBuffer(); inline XclImpColRowSettings* GetColRowBuff() const { return mxColRowBuff.get(); } inline XclImpOutlineBuffer* GetColOutline() const { return mxColOutlineBuff.get(); } inline XclImpOutlineBuffer* GetRowOutline() const { return mxRowOutlineBuff.get(); } void Convert(); private: typedef ScfRef< XclImpOutlineBuffer > XclImpOutlineBfrRef; typedef ScfRef< XclImpColRowSettings > XclImpColRowSettRef; XclImpOutlineBfrRef mxColOutlineBuff; XclImpOutlineBfrRef mxRowOutlineBuff; XclImpColRowSettRef mxColRowBuff; SCTAB mnScTab; }; class ImportExcel : public ImportTyp, protected XclImpRoot { protected: static const double fExcToTwips; // Umrechnung 1/256 Zeichen -> Twips RootData* pExcRoot; XclImpStream maStrm; // input stream XclImpStream& aIn; // input stream NameBuffer* pExtNameBuff; // ... externe Namen (Ind.-Basis=1) ExcelToSc* pFormConv; // Formel-Konverter XclImpOutlineBuffer* pColOutlineBuff; XclImpOutlineBuffer* pRowOutlineBuff; XclImpColRowSettings* pColRowBuff; // Col/Row-Einstellungen 1 Tabelle typedef ScfDelList< XclImpOutlineDataBuffer > XclImpOutlineListBuffer; XclImpOutlineListBuffer* pOutlineListBuffer; UINT16 nIxfeIndex; // merkt sich Angabe im IXFE-Record UINT16 nLastXF; // letzter XF in Formula-Record SCTAB nBdshtTab; // Counter fuer Boundsheet ScFormulaCell* pLastFormCell; // fuer String-Records BOOL bTabTruncated; // wenn Bereichsueberschreitung zum // Abschneiden von Zellen fuehrt // Record-Funktionen sal_uInt16 ReadXFIndex( bool bBiff2 ); void ReadDimensions(); void ReadBlank(); void ReadInteger(); void ReadNumber(); void ReadLabel(); void ReadBoolErr(); void ReadRk(); void Window1(); void Formula25( void ); // 0x06 -> excform.cxx void Row25( void ); // 0x08 void Bof2( void ); // 0x09 void Eof( void ); // 0x0A void DocProtect( void ); // 0x12 void Protect( void ); // 0x12 Sheet Protection BOOL Password( void ); // 0x13 void Externsheet( void ); // 0x17 void Note( void ); // 0x1C void Columndefault( void ); // 0x20 void Array25( void ); // 0x21 void Rec1904( void ); // 0x22 void Externname25( void ); // 0x23 void Colwidth( void ); // 0x24 void Defrowheight2( void ); // 0x25 // void Window1( void ); // 0x3D void Codepage( void ); // 0x42 void Ixfe( void ); // 0x44 void DefColWidth( void ); // 0x55 void Builtinfmtcnt( void ); // 0x56 void Obj( void ); // 0x5D void Colinfo( void ); // 0x7D void Wsbool( void ); // 0x81 void Boundsheet( void ); // 0x85 void Country( void ); // 0x8C void Hideobj( void ); // 0x8D void Bundleheader( void ); // 0x8F void Standardwidth( void ); // 0x99 void Shrfmla( void ); // 0xBC void Mulrk( void ); // 0xBD void Mulblank( void ); // 0xBE void Rstring( void ); // 0xD6 void Cellmerging( void ); // 0xE5 void Olesize( void ); // 0xDE void ReadUsesElfs(); // 0x0160 void Formula3( void ); // 0x0206 -> excform.cxx // 0x0207 -> 0x07 void Row34( void ); // 0x0208 void Bof3( void ); // 0x0209 void Array34( void ); // 0x0221 void Externname34( void ); // 0x0223 void Defrowheight345( void ); // 0x0225 void TableOp( void ); // 0x0236 //void Rk( void ); // 0x027E -> 0x7E void Formula4( void ); // 0x0406 -> excform.cxx void Bof4( void ); // 0x0409 void Bof5( void ); // 0x0809 // --------------------------------------------------------------- void SetLineStyle( SfxItemSet&, sal_uInt16, sal_uInt16, sal_uInt16 ); void SetFillStyle( SfxItemSet&, sal_uInt16, sal_uInt16, sal_uInt16 ); SdrObject* LineObj( SfxItemSet&, const Point&, const Point& ); SdrObject* RectObj( SfxItemSet&, const Point&, const Point& ); // --------------------------------------------------------------- void Formula( const XclAddress& rXclPos, UINT16 nXF, UINT16 nFormLen, double &rCurVal, BOOL bShrFmla ); // -> excform.cxx virtual void EndSheet( void ); void NeueTabelle( void ); const ScTokenArray* ErrorToFormula( BYTE bErrOrVal, BYTE nError, double& rVal ); virtual void AdjustRowHeight(); virtual void PostDocLoad( void ); public: ImportExcel( XclImpRootData& rImpData, SvStream& rStrm ); virtual ~ImportExcel( void ); virtual FltError Read( void ); }; #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: xiroot.hxx,v $ * * $Revision: 1.12 $ * * last change: $Author: hr $ $Date: 2004-09-08 15:47:41 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SC_XIROOT_HXX #define SC_XIROOT_HXX #ifndef SC_XLROOT_HXX #include "xlroot.hxx" #endif // Global data ================================================================ class XclImpSst; class XclImpPalette; class XclImpFontBuffer; class XclImpNumFmtBuffer; class XclImpXFBuffer; class XclImpXFRangeBuffer; class XclImpPageSettings; class _ScRangeListTabs; class XclImpTabInfo; class XclImpNameBuffer; class XclImpLinkManager; class XclImpObjectManager; class XclImpCondFormatManager; class XclImpAutoFilterBuffer; class XclImpWebQueryBuffer; class XclImpPivotTableManager; /** Stores global buffers and data needed for Excel import filter. */ struct XclImpRootData : public XclRootData { typedef ::std::auto_ptr< XclImpSst > XclImpSstPtr; typedef ::std::auto_ptr< XclImpPalette > XclImpPalettePtr; typedef ::std::auto_ptr< XclImpFontBuffer > XclImpFontBfrPtr; typedef ::std::auto_ptr< XclImpNumFmtBuffer > XclImpNumFmtBfrPtr; typedef ::std::auto_ptr< XclImpXFBuffer > XclImpXFBfrPtr; typedef ::std::auto_ptr< XclImpXFRangeBuffer > XclImpXFRangeBfrPtr; typedef ::std::auto_ptr< XclImpPageSettings > XclImpPageSettPtr; typedef ::std::auto_ptr< XclImpTabInfo > XclImpTabInfoPtr; typedef ::std::auto_ptr< XclImpNameBuffer > XclImpNameBfrPtr; typedef ::std::auto_ptr< XclImpLinkManager > XclImpLinkMgrPtr; typedef ::std::auto_ptr< XclImpObjectManager > XclImpObjectMgrPtr; typedef ::std::auto_ptr< XclImpCondFormatManager > XclImpCondFmtMgrPtr; typedef ::std::auto_ptr< XclImpWebQueryBuffer > XclImpWebQueryBfrPtr; typedef ::std::auto_ptr< XclImpPivotTableManager > XclImpPTableMgrPtr; XclImpSstPtr mxSst; /// The shared string table. XclImpPalettePtr mxPalette; /// The color buffer. XclImpFontBfrPtr mxFontBfr; /// All fonts in the file. XclImpNumFmtBfrPtr mxNumFmtBfr; /// All number formats in the file. XclImpXFBfrPtr mpXFBfr; /// All XF record data in the file. XclImpXFRangeBfrPtr mxXFRangeBfr; /// Buffer of XF index ranges in a sheet. XclImpPageSettPtr mxPageSettings; /// Page settings for current sheet. XclImpTabInfoPtr mxTabInfo; /// Sheet creation order list. XclImpNameBfrPtr mxNameBfr; /// Internal defined names. XclImpLinkMgrPtr mxLinkMgr; /// Manager for internal/external links. XclImpObjectMgrPtr mxObjMgr; /// All drawing objects. XclImpCondFmtMgrPtr mxCondFmtMgr; /// Conditional formattings. XclImpWebQueryBfrPtr mxWebQueryBfr; /// All web queries. XclImpPTableMgrPtr mxPTableMgr; /// All pivot tables and pivot caches. explicit XclImpRootData( XclBiff eBiff, SfxMedium& rMedium, ScDocument& rDocument, CharSet eCharSet ); virtual ~XclImpRootData(); }; // ---------------------------------------------------------------------------- class ExcelToSc; /** Access to global data from other classes. */ class XclImpRoot : public XclRoot { public: /** Returns this root instance - for code readability in derived classes. */ inline const XclImpRoot& GetRoot() const { return *this; } /** Returns the shared string table. */ XclImpSst& GetSst() const; /** Returns the color buffer. */ XclImpPalette& GetPalette() const; /** Returns the font buffer. */ XclImpFontBuffer& GetFontBuffer() const; /** Returns the number format buffer. */ XclImpNumFmtBuffer& GetNumFmtBuffer() const; /** Returns the cell formatting attributes buffer. */ XclImpXFBuffer& GetXFBuffer() const; /** Returns the buffer of XF index ranges for a sheet. */ XclImpXFRangeBuffer& GetXFRangeBuffer() const; /** Returns the page settings of the current sheet. */ XclImpPageSettings& GetPageSettings() const; /** Returns the buffer that contains all print areas in the document. */ _ScRangeListTabs& GetPrintAreaBuffer() const; /** Returns the buffer that contains all print areas in the document. */ _ScRangeListTabs& GetTitleAreaBuffer() const; /** Returns the buffer that contains the sheet creation order. */ XclImpTabInfo& GetTabInfo() const; /** Returns the buffer that contains internal defined names. */ XclImpNameBuffer& GetNameBuffer() const; /** Returns the link manager. */ XclImpLinkManager& GetLinkManager() const; /** Returns the drawing object manager. */ XclImpObjectManager& GetObjectManager() const; /** Returns the conditional formattings manager. */ XclImpCondFormatManager& GetCondFormatManager() const; /** Returns the filter manager. */ XclImpAutoFilterBuffer& GetFilterManager() const; /** Returns the web query buffer. */ XclImpWebQueryBuffer& GetWebQueryBuffer() const; /** Returns the pivot table manager. */ XclImpPivotTableManager& GetPivotTableManager() const; /** Returns the formula converter. */ ExcelToSc& GetFmlaConverter() const; /** Returns the Calc add-in function name for an Excel function name. */ String GetScAddInName( const String& rXclName ) const; /** Checks if the passed cell address is a valid Calc cell position. @descr See XclRoot::CheckCellAddress for details. */ bool CheckCellAddress( const ScAddress& rPos ) const; /** Checks and eventually crops the cell range to valid Calc dimensions. @descr See XclRoot::CheckCellRange for details. */ bool CheckCellRange( ScRange& rRange ) const; /** Checks and eventually crops the cell ranges to valid Calc dimensions. @descr See XclRoot::CheckCellRangeList for details. */ void CheckCellRangeList( ScRangeList& rRanges ) const; protected: explicit XclImpRoot( XclImpRootData& rImpRootData ); private: mutable XclImpRootData& mrImpData; /// Reference to the global import data struct. }; // ============================================================================ #endif <commit_msg>INTEGRATION: CWS dr26 (1.12.8); FILE MERGED 2004/10/13 11:41:30 dr 1.12.8.1: #i35275# mav09 followup: storage/stream handling reworked<commit_after>/************************************************************************* * * $RCSfile: xiroot.hxx,v $ * * $Revision: 1.13 $ * * last change: $Author: obo $ $Date: 2004-10-18 15:19:54 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SC_XIROOT_HXX #define SC_XIROOT_HXX #ifndef SC_XLROOT_HXX #include "xlroot.hxx" #endif // Global data ================================================================ class XclImpSst; class XclImpPalette; class XclImpFontBuffer; class XclImpNumFmtBuffer; class XclImpXFBuffer; class XclImpXFRangeBuffer; class XclImpPageSettings; class _ScRangeListTabs; class XclImpTabInfo; class XclImpNameBuffer; class XclImpLinkManager; class XclImpObjectManager; class XclImpCondFormatManager; class XclImpAutoFilterBuffer; class XclImpWebQueryBuffer; class XclImpPivotTableManager; /** Stores global buffers and data needed for Excel import filter. */ struct XclImpRootData : public XclRootData { typedef ::std::auto_ptr< XclImpSst > XclImpSstPtr; typedef ::std::auto_ptr< XclImpPalette > XclImpPalettePtr; typedef ::std::auto_ptr< XclImpFontBuffer > XclImpFontBfrPtr; typedef ::std::auto_ptr< XclImpNumFmtBuffer > XclImpNumFmtBfrPtr; typedef ::std::auto_ptr< XclImpXFBuffer > XclImpXFBfrPtr; typedef ::std::auto_ptr< XclImpXFRangeBuffer > XclImpXFRangeBfrPtr; typedef ::std::auto_ptr< XclImpPageSettings > XclImpPageSettPtr; typedef ::std::auto_ptr< XclImpTabInfo > XclImpTabInfoPtr; typedef ::std::auto_ptr< XclImpNameBuffer > XclImpNameBfrPtr; typedef ::std::auto_ptr< XclImpLinkManager > XclImpLinkMgrPtr; typedef ::std::auto_ptr< XclImpObjectManager > XclImpObjectMgrPtr; typedef ::std::auto_ptr< XclImpCondFormatManager > XclImpCondFmtMgrPtr; typedef ::std::auto_ptr< XclImpWebQueryBuffer > XclImpWebQueryBfrPtr; typedef ::std::auto_ptr< XclImpPivotTableManager > XclImpPTableMgrPtr; XclImpSstPtr mxSst; /// The shared string table. XclImpPalettePtr mxPalette; /// The color buffer. XclImpFontBfrPtr mxFontBfr; /// All fonts in the file. XclImpNumFmtBfrPtr mxNumFmtBfr; /// All number formats in the file. XclImpXFBfrPtr mpXFBfr; /// All XF record data in the file. XclImpXFRangeBfrPtr mxXFRangeBfr; /// Buffer of XF index ranges in a sheet. XclImpPageSettPtr mxPageSettings; /// Page settings for current sheet. XclImpTabInfoPtr mxTabInfo; /// Sheet creation order list. XclImpNameBfrPtr mxNameBfr; /// Internal defined names. XclImpLinkMgrPtr mxLinkMgr; /// Manager for internal/external links. XclImpObjectMgrPtr mxObjMgr; /// All drawing objects. XclImpCondFmtMgrPtr mxCondFmtMgr; /// Conditional formattings. XclImpWebQueryBfrPtr mxWebQueryBfr; /// All web queries. XclImpPTableMgrPtr mxPTableMgr; /// All pivot tables and pivot caches. explicit XclImpRootData( XclBiff eBiff, SfxMedium& rMedium, SotStorageRef xRootStrg, SvStream& rBookStrm, ScDocument& rDoc, CharSet eCharSet ); virtual ~XclImpRootData(); }; // ---------------------------------------------------------------------------- class ExcelToSc; /** Access to global data from other classes. */ class XclImpRoot : public XclRoot { public: explicit XclImpRoot( XclImpRootData& rImpRootData ); /** Returns this root instance - for code readability in derived classes. */ inline const XclImpRoot& GetRoot() const { return *this; } /** Returns the shared string table. */ XclImpSst& GetSst() const; /** Returns the color buffer. */ XclImpPalette& GetPalette() const; /** Returns the font buffer. */ XclImpFontBuffer& GetFontBuffer() const; /** Returns the number format buffer. */ XclImpNumFmtBuffer& GetNumFmtBuffer() const; /** Returns the cell formatting attributes buffer. */ XclImpXFBuffer& GetXFBuffer() const; /** Returns the buffer of XF index ranges for a sheet. */ XclImpXFRangeBuffer& GetXFRangeBuffer() const; /** Returns the page settings of the current sheet. */ XclImpPageSettings& GetPageSettings() const; /** Returns the buffer that contains all print areas in the document. */ _ScRangeListTabs& GetPrintAreaBuffer() const; /** Returns the buffer that contains all print areas in the document. */ _ScRangeListTabs& GetTitleAreaBuffer() const; /** Returns the buffer that contains the sheet creation order. */ XclImpTabInfo& GetTabInfo() const; /** Returns the buffer that contains internal defined names. */ XclImpNameBuffer& GetNameBuffer() const; /** Returns the link manager. */ XclImpLinkManager& GetLinkManager() const; /** Returns the drawing object manager. */ XclImpObjectManager& GetObjectManager() const; /** Returns the conditional formattings manager. */ XclImpCondFormatManager& GetCondFormatManager() const; /** Returns the filter manager. */ XclImpAutoFilterBuffer& GetFilterManager() const; /** Returns the web query buffer. */ XclImpWebQueryBuffer& GetWebQueryBuffer() const; /** Returns the pivot table manager. */ XclImpPivotTableManager& GetPivotTableManager() const; /** Returns the formula converter. */ ExcelToSc& GetFmlaConverter() const; /** Returns the Calc add-in function name for an Excel function name. */ String GetScAddInName( const String& rXclName ) const; /** Checks if the passed cell address is a valid Calc cell position. @descr See XclRoot::CheckCellAddress for details. */ bool CheckCellAddress( const ScAddress& rPos ) const; /** Checks and eventually crops the cell range to valid Calc dimensions. @descr See XclRoot::CheckCellRange for details. */ bool CheckCellRange( ScRange& rRange ) const; /** Checks and eventually crops the cell ranges to valid Calc dimensions. @descr See XclRoot::CheckCellRangeList for details. */ void CheckCellRangeList( ScRangeList& rRanges ) const; private: mutable XclImpRootData& mrImpData; /// Reference to the global import data struct. }; // ============================================================================ #endif <|endoftext|>
<commit_before>/* * Author: Yiming Yang * * Copyright (c) 2016, University Of Edinburgh * 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 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 "CoM.h" REGISTER_TASKMAP_TYPE("CoM", exotica::CoM); namespace exotica { CoM::CoM() { } CoM::~CoM() { } void CoM::update(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi) { if(phi.rows() != dim_) throw_named("Wrong size of phi!"); phi.setZero(); KDL::Vector com; for(int i=0;i<Kinematics.Phi.rows();i++) { com += Kinematics.Phi(i).p*mass_(i); if (debug_) { com_marker_.points[i].x = Kinematics.Phi(i).p[0]; com_marker_.points[i].y = Kinematics.Phi(i).p[1]; com_marker_.points[i].z = Kinematics.Phi(i).p[2]; } } double M = mass_.sum(); com = com / M; for(int i=0;i<dim_;i++) phi(i) = com[i]; if (debug_) { COM_marker_.pose.position.x = phi(0); COM_marker_.pose.position.y = phi(1); COM_marker_.pose.position.z = phi(2); COM_marker_.header.stamp = com_marker_.header.stamp = ros::Time::now(); com_pub_.publish(com_marker_); COM_pub_.publish(COM_marker_); } } void CoM::update(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi, Eigen::MatrixXdRef J) { if(phi.rows() != dim_) throw_named("Wrong size of phi!"); if(J.rows() != dim_ || J.cols() != Kinematics.J(0).data.cols()) throw_named("Wrong size of J! " << Kinematics.J(0).data.cols()); phi.setZero(); J.setZero(); KDL::Vector com; double M = mass_.sum(); for(int i=0;i<Kinematics.Phi.rows();i++) { com += Kinematics.Phi(i).p*mass_(i); J += mass_(i) / M * Kinematics.J(i).data.topRows(dim_); if (debug_) { com_marker_.points[i].x = Kinematics.Phi(i).p[0]; com_marker_.points[i].y = Kinematics.Phi(i).p[1]; com_marker_.points[i].z = Kinematics.Phi(i).p[2]; } } com =com / mass_.sum(); for(int i=0;i<dim_;i++) phi(i) = com[i]; if (debug_) { COM_marker_.pose.position.x = phi(0); COM_marker_.pose.position.y = phi(1); COM_marker_.pose.position.z = phi(2); COM_marker_.header.stamp = com_marker_.header.stamp = ros::Time::now(); com_pub_.publish(com_marker_); COM_pub_.publish(COM_marker_); } } int CoM::taskSpaceDim() { return dim_; } void CoM::Initialize() { enable_z_ = init_.EnableZ; if (enable_z_) dim_ = 3; else dim_ = 2; if(Frames.size()>0) { mass_.resize(Frames.size()); for(int i=0; i<Frames.size(); i++) { if(Frames[i].FrameBLinkName!="") { throw_named("Requesting CoM frame with base other than root! '" << Frames[i].FrameALinkName << "'"); } Frames[i].FrameAOffset.p = scene_->getSolver().getTreeMap()[Frames[i].FrameALinkName]->Segment.getInertia().getCOG(); mass_(i) = scene_->getSolver().getTreeMap()[Frames[i].FrameALinkName]->Segment.getInertia().getMass(); } } else { int N = scene_->getSolver().getTree().size(); mass_.resize(N); Frames.resize(N); for(int i=0; i<N; i++) { Frames[i].FrameALinkName = scene_->getSolver().getTree()[i]->Segment.getName(); Frames[i].FrameAOffset.p = scene_->getSolver().getTree()[i]->Segment.getInertia().getCOG(); mass_(i) = scene_->getSolver().getTree()[i]->Segment.getInertia().getMass(); } } InitDebug(); } void CoM::assignScene(Scene_ptr scene) { scene_ = scene; Initialize(); } void CoM::Instantiate(CoMInitializer& init) { init_ = init; } void CoM::InitDebug() { com_marker_.points.resize(Frames.size()); com_marker_.type = visualization_msgs::Marker::SPHERE_LIST; com_marker_.color.a = .7; com_marker_.color.r = 0.5; com_marker_.color.g = 0; com_marker_.color.b = 0; com_marker_.scale.x = com_marker_.scale.y = com_marker_.scale.z = .02; com_marker_.action = visualization_msgs::Marker::ADD; COM_marker_.type = visualization_msgs::Marker::CYLINDER; COM_marker_.color.a = 1; COM_marker_.color.r = 1; COM_marker_.color.g = 0; COM_marker_.color.b = 0; COM_marker_.scale.x = COM_marker_.scale.y = .15; COM_marker_.scale.z = .02; COM_marker_.action = visualization_msgs::Marker::ADD; com_marker_.header.frame_id = COM_marker_.header.frame_id = scene_->getRootName(); com_pub_ = Server::Instance()->advertise<visualization_msgs::Marker>(object_name_ + "coms_marker", 1); COM_pub_ = Server::Instance()->advertise<visualization_msgs::Marker>(object_name_ + "COM_marker", 1); } } <commit_msg>Beautified CoM<commit_after>/* * Author: Yiming Yang * * Copyright (c) 2016, University Of Edinburgh * 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 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 "CoM.h" REGISTER_TASKMAP_TYPE("CoM", exotica::CoM); namespace exotica { CoM::CoM() { } CoM::~CoM() { } void CoM::update(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi) { if(phi.rows() != dim_) throw_named("Wrong size of phi!"); phi.setZero(); double M = mass_.sum(); if(M==0.0) return; KDL::Vector com; for(int i=0;i<Kinematics.Phi.rows();i++) { com += Kinematics.Phi(i).p*mass_(i); if (debug_) { com_marker_.points[i].x = Kinematics.Phi(i).p[0]; com_marker_.points[i].y = Kinematics.Phi(i).p[1]; com_marker_.points[i].z = Kinematics.Phi(i).p[2]; } } com = com / M; for(int i=0;i<dim_;i++) phi(i) = com[i]; if (debug_) { COM_marker_.pose.position.x = phi(0); COM_marker_.pose.position.y = phi(1); COM_marker_.pose.position.z = phi(2); COM_marker_.header.stamp = com_marker_.header.stamp = ros::Time::now(); com_pub_.publish(com_marker_); COM_pub_.publish(COM_marker_); } } void CoM::update(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi, Eigen::MatrixXdRef J) { if(phi.rows() != dim_) throw_named("Wrong size of phi!"); if(J.rows() != dim_ || J.cols() != Kinematics.J(0).data.cols()) throw_named("Wrong size of J! " << Kinematics.J(0).data.cols()); phi.setZero(); J.setZero(); KDL::Vector com; double M = mass_.sum(); if(M==0.0) return; for(int i=0;i<Kinematics.Phi.rows();i++) { com += Kinematics.Phi(i).p*mass_(i); J += mass_(i) / M * Kinematics.J(i).data.topRows(dim_); if (debug_) { com_marker_.points[i].x = Kinematics.Phi(i).p[0]; com_marker_.points[i].y = Kinematics.Phi(i).p[1]; com_marker_.points[i].z = Kinematics.Phi(i).p[2]; } } com =com / M; for(int i=0;i<dim_;i++) phi(i) = com[i]; if (debug_) { COM_marker_.pose.position.x = phi(0); COM_marker_.pose.position.y = phi(1); COM_marker_.pose.position.z = phi(2); COM_marker_.header.stamp = com_marker_.header.stamp = ros::Time::now(); com_pub_.publish(com_marker_); COM_pub_.publish(COM_marker_); } } int CoM::taskSpaceDim() { return dim_; } void CoM::Initialize() { enable_z_ = init_.EnableZ; if (enable_z_) dim_ = 3; else dim_ = 2; if(Frames.size()>0) { mass_.resize(Frames.size()); for(int i=0; i<Frames.size(); i++) { if(Frames[i].FrameBLinkName!="") { throw_named("Requesting CoM frame with base other than root! '" << Frames[i].FrameALinkName << "'"); } Frames[i].FrameAOffset.p = scene_->getSolver().getTreeMap()[Frames[i].FrameALinkName]->Segment.getInertia().getCOG(); mass_(i) = scene_->getSolver().getTreeMap()[Frames[i].FrameALinkName]->Segment.getInertia().getMass(); } } else { int N = scene_->getSolver().getTree().size(); mass_.resize(N); Frames.resize(N); for(int i=0; i<N; i++) { Frames[i].FrameALinkName = scene_->getSolver().getTree()[i]->Segment.getName(); Frames[i].FrameAOffset.p = scene_->getSolver().getTree()[i]->Segment.getInertia().getCOG(); mass_(i) = scene_->getSolver().getTree()[i]->Segment.getInertia().getMass(); } } InitDebug(); } void CoM::assignScene(Scene_ptr scene) { scene_ = scene; Initialize(); } void CoM::Instantiate(CoMInitializer& init) { init_ = init; } void CoM::InitDebug() { com_marker_.points.resize(Frames.size()); com_marker_.type = visualization_msgs::Marker::SPHERE_LIST; com_marker_.color.a = .7; com_marker_.color.r = 0.5; com_marker_.color.g = 0; com_marker_.color.b = 0; com_marker_.scale.x = com_marker_.scale.y = com_marker_.scale.z = .02; com_marker_.action = visualization_msgs::Marker::ADD; COM_marker_.type = visualization_msgs::Marker::CYLINDER; COM_marker_.color.a = 1; COM_marker_.color.r = 1; COM_marker_.color.g = 0; COM_marker_.color.b = 0; COM_marker_.scale.x = COM_marker_.scale.y = .15; COM_marker_.scale.z = .02; COM_marker_.action = visualization_msgs::Marker::ADD; com_marker_.header.frame_id = COM_marker_.header.frame_id = scene_->getRootName(); com_pub_ = Server::Instance()->advertise<visualization_msgs::Marker>(object_name_ + "coms_marker", 1); COM_pub_ = Server::Instance()->advertise<visualization_msgs::Marker>(object_name_ + "COM_marker", 1); } } <|endoftext|>
<commit_before>// Copyright (c) 2021 The Orbit 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 "TestUtils.h" #include <absl/strings/str_cat.h> #include <capstone/capstone.h> #include <string> #include "ObjectUtils/Address.h" #include "ObjectUtils/ElfFile.h" #include "ObjectUtils/LinuxMap.h" #include "OrbitBase/ExecutablePath.h" #include "OrbitBase/Logging.h" #include "OrbitBase/UniqueResource.h" namespace orbit_user_space_instrumentation { AddressRange GetFunctionAbsoluteAddressRangeOrDie(std::string_view function_name) { auto modules = orbit_object_utils::ReadModules(getpid()); CHECK(!modules.has_error()); std::string module_file_path; AddressRange address_range_code(0, 0); for (const auto& module : modules.value()) { if (module.file_path() == orbit_base::GetExecutablePath()) { module_file_path = module.file_path(); address_range_code.start = module.address_start(); address_range_code.end = module.address_end(); break; } } CHECK(!module_file_path.empty()); auto elf_file = orbit_object_utils::CreateElfFile(module_file_path); CHECK(!elf_file.has_error()); auto syms = elf_file.value()->LoadDebugSymbols(); CHECK(!syms.has_error()); for (const auto& sym : syms.value().symbol_infos()) { if (sym.name() == function_name) { const uint64_t address = orbit_object_utils::SymbolVirtualAddressToAbsoluteAddress( sym.address(), address_range_code.start, syms.value().load_bias(), elf_file.value()->GetExecutableSegmentOffset()); const uint64_t size = sym.size(); return {address, address + size}; } } UNREACHABLE(); } AddressRange GetFunctionRelativeAddressRangeOrDie(std::string_view function_name) { auto elf_file = orbit_object_utils::CreateElfFile(orbit_base::GetExecutablePath()); CHECK(!elf_file.has_error()); auto syms = elf_file.value()->LoadDebugSymbols(); CHECK(!syms.has_error()); for (const auto& sym : syms.value().symbol_infos()) { if (sym.name() == function_name) { return AddressRange(sym.address(), sym.address() + sym.size()); } } UNREACHABLE(); } void DumpDisassembly(const std::vector<uint8_t>& code, uint64_t start_address) { // Init Capstone disassembler. csh capstone_handle = 0; cs_err error_code = cs_open(CS_ARCH_X86, CS_MODE_64, &capstone_handle); CHECK(error_code == CS_ERR_OK); error_code = cs_option(capstone_handle, CS_OPT_DETAIL, CS_OPT_ON); CHECK(error_code == CS_ERR_OK); orbit_base::unique_resource close_on_exit{ &capstone_handle, [](csh* capstone_handle) { cs_close(capstone_handle); }}; cs_insn* instruction = nullptr; const size_t count = cs_disasm(capstone_handle, static_cast<const uint8_t*>(code.data()), code.size(), start_address, 0, &instruction); size_t i; for (i = 0; i < count; i++) { std::string machine_code; for (int j = 0; j < instruction[i].size; j++) { machine_code = absl::StrCat(machine_code, j == 0 ? absl::StrFormat("%#0.2x", instruction[i].bytes[j]) : absl::StrFormat(" %0.2x", instruction[i].bytes[j])); } LOG("%#x:\t%-12s %s , %s", instruction[i].address, instruction[i].mnemonic, instruction[i].op_str, machine_code); } // Print out the next offset, after the last instruction. LOG("%#x:", instruction[i - 1].address + instruction[i - 1].size); cs_free(instruction, count); } } // namespace orbit_user_space_instrumentation<commit_msg>Add error message to GetFunction*AddressRangeOrDie (#2834)<commit_after>// Copyright (c) 2021 The Orbit 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 "TestUtils.h" #include <absl/strings/str_cat.h> #include <capstone/capstone.h> #include <string> #include "ObjectUtils/Address.h" #include "ObjectUtils/ElfFile.h" #include "ObjectUtils/LinuxMap.h" #include "OrbitBase/ExecutablePath.h" #include "OrbitBase/Logging.h" #include "OrbitBase/UniqueResource.h" namespace orbit_user_space_instrumentation { AddressRange GetFunctionAbsoluteAddressRangeOrDie(std::string_view function_name) { auto modules = orbit_object_utils::ReadModules(getpid()); CHECK(!modules.has_error()); std::string module_file_path; AddressRange address_range_code(0, 0); for (const auto& module : modules.value()) { if (module.file_path() == orbit_base::GetExecutablePath()) { module_file_path = module.file_path(); address_range_code.start = module.address_start(); address_range_code.end = module.address_end(); break; } } CHECK(!module_file_path.empty()); auto elf_file = orbit_object_utils::CreateElfFile(module_file_path); CHECK(!elf_file.has_error()); auto syms = elf_file.value()->LoadDebugSymbols(); CHECK(!syms.has_error()); for (const auto& sym : syms.value().symbol_infos()) { if (sym.name() == function_name) { const uint64_t address = orbit_object_utils::SymbolVirtualAddressToAbsoluteAddress( sym.address(), address_range_code.start, syms.value().load_bias(), elf_file.value()->GetExecutableSegmentOffset()); const uint64_t size = sym.size(); return {address, address + size}; } } FATAL("GetFunctionAbsoluteAddressRangeOrDie hasn't found a function '%s'", function_name); } AddressRange GetFunctionRelativeAddressRangeOrDie(std::string_view function_name) { auto elf_file = orbit_object_utils::CreateElfFile(orbit_base::GetExecutablePath()); CHECK(!elf_file.has_error()); auto syms = elf_file.value()->LoadDebugSymbols(); CHECK(!syms.has_error()); for (const auto& sym : syms.value().symbol_infos()) { if (sym.name() == function_name) { return AddressRange(sym.address(), sym.address() + sym.size()); } } FATAL("GetFunctionRelativeAddressRangeOrDie hasn't found a function '%s'", function_name); } void DumpDisassembly(const std::vector<uint8_t>& code, uint64_t start_address) { // Init Capstone disassembler. csh capstone_handle = 0; cs_err error_code = cs_open(CS_ARCH_X86, CS_MODE_64, &capstone_handle); CHECK(error_code == CS_ERR_OK); error_code = cs_option(capstone_handle, CS_OPT_DETAIL, CS_OPT_ON); CHECK(error_code == CS_ERR_OK); orbit_base::unique_resource close_on_exit{ &capstone_handle, [](csh* capstone_handle) { cs_close(capstone_handle); }}; cs_insn* instruction = nullptr; const size_t count = cs_disasm(capstone_handle, static_cast<const uint8_t*>(code.data()), code.size(), start_address, 0, &instruction); size_t i; for (i = 0; i < count; i++) { std::string machine_code; for (int j = 0; j < instruction[i].size; j++) { machine_code = absl::StrCat(machine_code, j == 0 ? absl::StrFormat("%#0.2x", instruction[i].bytes[j]) : absl::StrFormat(" %0.2x", instruction[i].bytes[j])); } LOG("%#x:\t%-12s %s , %s", instruction[i].address, instruction[i].mnemonic, instruction[i].op_str, machine_code); } // Print out the next offset, after the last instruction. LOG("%#x:", instruction[i - 1].address + instruction[i - 1].size); cs_free(instruction, count); } } // namespace orbit_user_space_instrumentation<|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xmlHierarchyCollection.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2006-06-20 02:51:25 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef DBA_XMLHIERARCHYCOLLECTION_HXX #include "xmlHierarchyCollection.hxx" #endif #ifndef DBA_XMLCOMPONENT_HXX #include "xmlComponent.hxx" #endif #ifndef DBA_XMLQUERY_HXX #include "xmlQuery.hxx" #endif #ifndef DBA_XMLCOLUMN_HXX #include "xmlColumn.hxx" #endif #ifndef DBA_XMLFILTER_HXX #include "xmlfilter.hxx" #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include <xmloff/xmltoken.hxx> #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include <xmloff/xmlnmspe.hxx> #endif #ifndef _XMLOFF_NMSPMAP_HXX #include <xmloff/nmspmap.hxx> #endif #ifndef DBA_XMLENUMS_HXX #include "xmlEnums.hxx" #endif #ifndef DBACCESS_SHARED_XMLSTRINGS_HRC #include "xmlstrings.hrc" #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_ #include <com/sun/star/container/XNameContainer.hpp> #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif namespace dbaxml { using namespace ::rtl; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::container; using namespace ::com::sun::star::xml::sax; DBG_NAME(OXMLHierarchyCollection) OXMLHierarchyCollection::OXMLHierarchyCollection( ODBFilter& rImport ,sal_uInt16 nPrfx ,const OUString& _sLocalName ,const Reference< XAttributeList > & _xAttrList ,const Reference< XNameAccess >& _xParentContainer ,const ::rtl::OUString& _sCollectionServiceName ,const ::rtl::OUString& _sComponentServiceName) : SvXMLImportContext( rImport, nPrfx, _sLocalName ) ,m_xParentContainer(_xParentContainer) ,m_sCollectionServiceName(_sCollectionServiceName) ,m_sComponentServiceName(_sComponentServiceName) { DBG_CTOR(OXMLHierarchyCollection,NULL); const SvXMLNamespaceMap& rMap = rImport.GetNamespaceMap(); const SvXMLTokenMap& rTokenMap = rImport.GetComponentElemTokenMap(); sal_Int16 nLength = (_xAttrList.is()) ? _xAttrList->getLength() : 0; for(sal_Int16 i = 0; i < nLength; ++i) { OUString sLocalName; rtl::OUString sAttrName = _xAttrList->getNameByIndex( i ); sal_uInt16 nPrefix = rMap.GetKeyByAttrName( sAttrName,&sLocalName ); rtl::OUString sValue = _xAttrList->getValueByIndex( i ); switch( rTokenMap.Get( nPrefix, sLocalName ) ) { case XML_TOK_COMPONENT_NAME: m_sName = sValue; break; } } if ( m_sName.getLength() && _xParentContainer.is() ) { try { Sequence< Any > aArguments(2); PropertyValue aValue; // set as folder aValue.Name = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Name")); aValue.Value <<= m_sName; aArguments[0] <<= aValue; //parent aValue.Name = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Parent")); aValue.Value <<= _xParentContainer; aArguments[1] <<= aValue; Reference<XMultiServiceFactory> xORB(_xParentContainer,UNO_QUERY); if ( xORB.is() ) { m_xContainer.set(xORB->createInstanceWithArguments(_sCollectionServiceName,aArguments),UNO_QUERY); Reference<XNameContainer> xNameContainer(_xParentContainer,UNO_QUERY); if ( xNameContainer.is() ) xNameContainer->insertByName(m_sName,makeAny(m_xContainer)); } } catch(Exception&) { OSL_ENSURE(0,"OXMLHierarchyCollection::OXMLHierarchyCollection -> exception catched"); } } } // ----------------------------------------------------------------------------- OXMLHierarchyCollection::OXMLHierarchyCollection( ODBFilter& rImport ,sal_uInt16 nPrfx ,const OUString& _sLocalName ,const Reference< XNameAccess >& _xContainer ) : SvXMLImportContext( rImport, nPrfx, _sLocalName ) ,m_xContainer(_xContainer) { DBG_CTOR(OXMLHierarchyCollection,NULL); } // ----------------------------------------------------------------------------- OXMLHierarchyCollection::~OXMLHierarchyCollection() { DBG_DTOR(OXMLHierarchyCollection,NULL); } // ----------------------------------------------------------------------------- SvXMLImportContext* OXMLHierarchyCollection::CreateChildContext( sal_uInt16 nPrefix, const OUString& rLocalName, const Reference< XAttributeList > & xAttrList ) { SvXMLImportContext *pContext = 0; const SvXMLTokenMap& rTokenMap = GetOwnImport().GetDocumentsElemTokenMap(); switch( rTokenMap.Get( nPrefix, rLocalName ) ) { // case XML_TOK_QUERY: // pContext = new OXMLQuery( GetOwnImport(), nPrefix, rLocalName,xAttrList,m_xContainer ); // break; case XML_TOK_COMPONENT: GetOwnImport().GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP ); pContext = new OXMLComponent( GetOwnImport(), nPrefix, rLocalName,xAttrList,m_xContainer,m_sComponentServiceName ); break; case XML_TOK_COLUMN: GetOwnImport().GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP ); pContext = new OXMLColumn( GetOwnImport(), nPrefix, rLocalName,xAttrList,m_xContainer); break; // case XML_TOK_QUERY_COLLECTION: case XML_TOK_COMPONENT_COLLECTION: GetOwnImport().GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP ); pContext = new OXMLHierarchyCollection( GetOwnImport(), nPrefix, rLocalName,xAttrList,m_xContainer,m_sCollectionServiceName,m_sComponentServiceName); break; } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName ); return pContext; } // ----------------------------------------------------------------------------- ODBFilter& OXMLHierarchyCollection::GetOwnImport() { return static_cast<ODBFilter&>(GetImport()); } // ----------------------------------------------------------------------------- //---------------------------------------------------------------------------- } // namespace dbaxml // ----------------------------------------------------------------------------- <commit_msg>INTEGRATION: CWS dba204a (1.5.8); FILE MERGED 2006/07/06 06:21:08 oj 1.5.8.1: #i66620# use of correct property types for tables<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xmlHierarchyCollection.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: obo $ $Date: 2006-07-13 15:22:48 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef DBA_XMLHIERARCHYCOLLECTION_HXX #include "xmlHierarchyCollection.hxx" #endif #ifndef DBA_XMLCOMPONENT_HXX #include "xmlComponent.hxx" #endif #ifndef DBA_XMLQUERY_HXX #include "xmlQuery.hxx" #endif #ifndef DBA_XMLCOLUMN_HXX #include "xmlColumn.hxx" #endif #ifndef DBA_XMLFILTER_HXX #include "xmlfilter.hxx" #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include <xmloff/xmltoken.hxx> #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include <xmloff/xmlnmspe.hxx> #endif #ifndef _XMLOFF_NMSPMAP_HXX #include <xmloff/nmspmap.hxx> #endif #ifndef DBA_XMLENUMS_HXX #include "xmlEnums.hxx" #endif #ifndef DBACCESS_SHARED_XMLSTRINGS_HRC #include "xmlstrings.hrc" #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_ #include <com/sun/star/container/XNameContainer.hpp> #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif namespace dbaxml { using namespace ::rtl; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::container; using namespace ::com::sun::star::xml::sax; DBG_NAME(OXMLHierarchyCollection) OXMLHierarchyCollection::OXMLHierarchyCollection( ODBFilter& rImport ,sal_uInt16 nPrfx ,const OUString& _sLocalName ,const Reference< XAttributeList > & _xAttrList ,const Reference< XNameAccess >& _xParentContainer ,const ::rtl::OUString& _sCollectionServiceName ,const ::rtl::OUString& _sComponentServiceName) : SvXMLImportContext( rImport, nPrfx, _sLocalName ) ,m_xParentContainer(_xParentContainer) ,m_sCollectionServiceName(_sCollectionServiceName) ,m_sComponentServiceName(_sComponentServiceName) { DBG_CTOR(OXMLHierarchyCollection,NULL); const SvXMLNamespaceMap& rMap = rImport.GetNamespaceMap(); const SvXMLTokenMap& rTokenMap = rImport.GetComponentElemTokenMap(); sal_Int16 nLength = (_xAttrList.is()) ? _xAttrList->getLength() : 0; for(sal_Int16 i = 0; i < nLength; ++i) { OUString sLocalName; rtl::OUString sAttrName = _xAttrList->getNameByIndex( i ); sal_uInt16 nPrefix = rMap.GetKeyByAttrName( sAttrName,&sLocalName ); rtl::OUString sValue = _xAttrList->getValueByIndex( i ); switch( rTokenMap.Get( nPrefix, sLocalName ) ) { case XML_TOK_COMPONENT_NAME: m_sName = sValue; break; } } if ( m_sName.getLength() && _xParentContainer.is() ) { try { Sequence< Any > aArguments(2); PropertyValue aValue; // set as folder aValue.Name = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Name")); aValue.Value <<= m_sName; aArguments[0] <<= aValue; //parent aValue.Name = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Parent")); aValue.Value <<= _xParentContainer; aArguments[1] <<= aValue; Reference<XMultiServiceFactory> xORB(_xParentContainer,UNO_QUERY); if ( xORB.is() ) { m_xContainer.set(xORB->createInstanceWithArguments(_sCollectionServiceName,aArguments),UNO_QUERY); Reference<XNameContainer> xNameContainer(_xParentContainer,UNO_QUERY); if ( xNameContainer.is() && !xNameContainer->hasByName(m_sName) ) xNameContainer->insertByName(m_sName,makeAny(m_xContainer)); } } catch(Exception&) { OSL_ENSURE(0,"OXMLHierarchyCollection::OXMLHierarchyCollection -> exception catched"); } } } // ----------------------------------------------------------------------------- OXMLHierarchyCollection::OXMLHierarchyCollection( ODBFilter& rImport ,sal_uInt16 nPrfx ,const OUString& _sLocalName ,const Reference< XNameAccess >& _xContainer ) : SvXMLImportContext( rImport, nPrfx, _sLocalName ) ,m_xContainer(_xContainer) { DBG_CTOR(OXMLHierarchyCollection,NULL); } // ----------------------------------------------------------------------------- OXMLHierarchyCollection::~OXMLHierarchyCollection() { DBG_DTOR(OXMLHierarchyCollection,NULL); } // ----------------------------------------------------------------------------- SvXMLImportContext* OXMLHierarchyCollection::CreateChildContext( sal_uInt16 nPrefix, const OUString& rLocalName, const Reference< XAttributeList > & xAttrList ) { SvXMLImportContext *pContext = 0; const SvXMLTokenMap& rTokenMap = GetOwnImport().GetDocumentsElemTokenMap(); switch( rTokenMap.Get( nPrefix, rLocalName ) ) { // case XML_TOK_QUERY: // pContext = new OXMLQuery( GetOwnImport(), nPrefix, rLocalName,xAttrList,m_xContainer ); // break; case XML_TOK_COMPONENT: GetOwnImport().GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP ); pContext = new OXMLComponent( GetOwnImport(), nPrefix, rLocalName,xAttrList,m_xContainer,m_sComponentServiceName ); break; case XML_TOK_COLUMN: GetOwnImport().GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP ); pContext = new OXMLColumn( GetOwnImport(), nPrefix, rLocalName,xAttrList,m_xContainer); break; // case XML_TOK_QUERY_COLLECTION: case XML_TOK_COMPONENT_COLLECTION: GetOwnImport().GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP ); pContext = new OXMLHierarchyCollection( GetOwnImport(), nPrefix, rLocalName,xAttrList,m_xContainer,m_sCollectionServiceName,m_sComponentServiceName); break; } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName ); return pContext; } // ----------------------------------------------------------------------------- ODBFilter& OXMLHierarchyCollection::GetOwnImport() { return static_cast<ODBFilter&>(GetImport()); } // ----------------------------------------------------------------------------- //---------------------------------------------------------------------------- } // namespace dbaxml // ----------------------------------------------------------------------------- <|endoftext|>
<commit_before>#include <algorithm> #include <string> #include <sstream> #include <iostream> #include "descriptors.h" #include "parser.h" #include "ctab.h" using namespace std; void read1stOrder(istream& inp, vector<LevelOne> &dest) { string s; Parser parser(inp); while (!parser.eof()) { string sym = parser.quotedString(); string valency = parser.quotedString(); stringstream dcStr(parser.line()); //rest of the line int dc; //cout << valency << endl; dcStr >> dc; Code code(sym); stringstream str(valency); for (;;) { int val; char delim; str >> val; LevelOne toInsert(code, val, dc); auto it = lower_bound(begin(dest), end(dest), toInsert); dest.insert(it, toInsert); str >> delim; if (!str.good() || delim != ',') break; } } //for (auto a : dest) // cout << "*** " << a.center.symbol() << " " << a.valence << " " << "DC: " << a.dc << endl; } void read2ndOrder(istream& inp, vector<LevelTwo> &dest) { vector<SDF> sdf = readSdf(inp); for (auto& rec : sdf) { auto & b = rec.mol.bounds; int center = 1; //atom with index 1 as center for 2 atom patterns if (rec.mol.atoms.size() > 2) { int f = b[0].a1; auto cnt = count_if(begin(b), end(b), [f](BoundEntry e){ return e.a1 == f || e.a2 == f; }); if (cnt == b.size()) //present in all bonds { center = f; } else { center = b[0].a2; } } Code c = rec.mol.atoms[center - 1].code; int valency = 0; vector<Linked> links; for_each(begin(b), end(b), [&valency, &rec, &links, center](BoundEntry e){ valency += e.type; if (e.a1 == center) links.emplace_back(rec.mol.atoms[e.a2 - 1].code, e.type); else links.emplace_back(rec.mol.atoms[e.a1 - 1].code, e.type); }); //TODO: check AA key for_each(rec.props["DC"].begin(), rec.props["DC"].end(), [&dest, c, valency, &links](string s){ stringstream str(s); int dc; str >> dc; LevelTwo t(c, valency, links, dc); auto lb = lower_bound(begin(dest), end(dest), t); dest.insert(lb, t); }); } /* for (auto &e : dest) { cout << "^^^ " << e.center.symbol() << " " << e.valence << "{ "; for (auto lnk : e.bonds) cout << lnk.atom.symbol() << " "; cout << "} DC: " << e.dc << endl; } */ } <commit_msg>[WIP] Bootstrap page for FCSP codec<commit_after>#include <algorithm> #include <string> #include <sstream> #include <iostream> #include "descriptors.h" #include "parser.h" #include "ctab.h" using namespace std; void read1stOrder(istream& inp, vector<LevelOne> &dest) { string s; Parser parser(inp); while (!parser.eof()) { string sym = parser.quotedString(); string valency = parser.quotedString(); stringstream dcStr(parser.line()); //rest of the line int dc; //cout << valency << endl; dcStr >> dc; Code code(sym); stringstream str(valency); for (;;) { int val; char delim; str >> val; LevelOne toInsert(code, val, dc); auto it = lower_bound(begin(dest), end(dest), toInsert); dest.insert(it, toInsert); str >> delim; if (!str.good() || delim != ',') break; } } //for (auto a : dest) // cout << "*** " << a.center.symbol() << " " << a.valence << " " << "DC: " << a.dc << endl; } void read2ndOrder(istream& inp, vector<LevelTwo> &dest) { vector<SDF> sdf = readSdf(inp); for (auto& rec : sdf) { auto & b = rec.mol.bounds; int center = 1; //atom with index 1 as center for 2 atom patterns if (rec.mol.atoms.size() > 2) { int f = b[0].a1; auto cnt = count_if(begin(b), end(b), [f](BoundEntry e){ return e.a1 == f || e.a2 == f; }); if (cnt == b.size()) //present in all bonds { center = f; } else { center = b[0].a2; } } Code c = rec.mol.atoms[center - 1].code; int valency = 0; vector<Linked> links; for_each(begin(b), end(b), [&valency, &rec, &links, center](BoundEntry e){ valency += e.type; if (e.a1 == center) links.emplace_back(rec.mol.atoms[e.a2 - 1].code, e.type); else links.emplace_back(rec.mol.atoms[e.a1 - 1].code, e.type); }); //TODO: check AA key for_each(rec.props["DC"].begin(), rec.props["DC"].end(), [&dest, c, valency, &links](string s){ stringstream str(s); int dc; str >> dc; LevelTwo t(c, valency, links, dc); auto lb = lower_bound(begin(dest), end(dest), t); dest.insert(lb, t); }); } for (auto &e : dest) { cerr << "^^^ " << e.center.symbol() << " " << e.valence << "{ "; for (auto lnk : e.bonds) cerr << lnk.atom.symbol() << " "; cerr << "} DC: " << e.dc << endl; } } <|endoftext|>
<commit_before>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2011-2013 Preferred Networks 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 #ifndef JUBATUS_SERVER_SERVER_NEAREST_NEIGHBOR_SERV_HPP_ #define JUBATUS_SERVER_SERVER_NEAREST_NEIGHBOR_SERV_HPP_ #include <string> #include <utility> #include <vector> #include "jubatus/core/driver/nearest_neighbor.hpp" #include "jubatus/core/table/column/column_table.hpp" #include "../common/lock_service.hpp" #include "../framework/server_base.hpp" #include "../fv_converter/so_factory.hpp" #include "nearest_neighbor_types.hpp" namespace jubatus { namespace server { using jubatus::core::nearest_neighbor::nearest_neighbor_base; typedef std::vector<std::pair<std::string, float> > neighbor_result; class nearest_neighbor_serv : public framework::server_base { public: nearest_neighbor_serv( const framework::server_argv& a, const jubatus::util::lang::shared_ptr<common::lock_service>& zk); virtual ~nearest_neighbor_serv(); framework::mixer::mixer* get_mixer() const { return mixer_.get(); } core::driver::driver_base* get_driver() const { return nearest_neighbor_.get(); } void get_status(status_t& status) const; uint64_t user_data_version() const; void set_config(const std::string& config); std::string get_config() const; bool clear(); bool set_row(const std::string& id, const core::fv_converter::datum& dat); neighbor_result neighbor_row_from_id(const std::string& id, size_t size); neighbor_result neighbor_row_from_datum(const core::fv_converter::datum& dat, size_t size); neighbor_result similar_row_from_id(const std::string& id, size_t ret_num); neighbor_result similar_row_from_datum(const core::fv_converter::datum&, size_t); std::vector<std::string> get_all_rows() const; private: void check_set_config()const; jubatus::util::lang::scoped_ptr<framework::mixer::mixer> mixer_; std::string config_; uint64_t clear_row_cnt_; uint64_t update_row_cnt_; uint64_t build_cnt_; uint64_t mix_cnt_; jubatus::util::lang::shared_ptr<core::driver::nearest_neighbor> nearest_neighbor_; fv_converter::so_factory so_loader_; }; } // namespace server } // namespace jubatus #endif // JUBATUS_SERVER_SERVER_NEAREST_NEIGHBOR_SERV_HPP_ <commit_msg>use storage::column instead of table::column<commit_after>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2011-2013 Preferred Networks 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 #ifndef JUBATUS_SERVER_SERVER_NEAREST_NEIGHBOR_SERV_HPP_ #define JUBATUS_SERVER_SERVER_NEAREST_NEIGHBOR_SERV_HPP_ #include <string> #include <utility> #include <vector> #include "jubatus/core/driver/nearest_neighbor.hpp" #include "jubatus/core/storage/column_table.hpp" #include "../common/lock_service.hpp" #include "../framework/server_base.hpp" #include "../fv_converter/so_factory.hpp" #include "nearest_neighbor_types.hpp" namespace jubatus { namespace server { using jubatus::core::nearest_neighbor::nearest_neighbor_base; typedef std::vector<std::pair<std::string, float> > neighbor_result; class nearest_neighbor_serv : public framework::server_base { public: nearest_neighbor_serv( const framework::server_argv& a, const jubatus::util::lang::shared_ptr<common::lock_service>& zk); virtual ~nearest_neighbor_serv(); framework::mixer::mixer* get_mixer() const { return mixer_.get(); } core::driver::driver_base* get_driver() const { return nearest_neighbor_.get(); } void get_status(status_t& status) const; uint64_t user_data_version() const; void set_config(const std::string& config); std::string get_config() const; bool clear(); bool set_row(const std::string& id, const core::fv_converter::datum& dat); neighbor_result neighbor_row_from_id(const std::string& id, size_t size); neighbor_result neighbor_row_from_datum(const core::fv_converter::datum& dat, size_t size); neighbor_result similar_row_from_id(const std::string& id, size_t ret_num); neighbor_result similar_row_from_datum(const core::fv_converter::datum&, size_t); std::vector<std::string> get_all_rows() const; private: void check_set_config()const; jubatus::util::lang::scoped_ptr<framework::mixer::mixer> mixer_; std::string config_; uint64_t clear_row_cnt_; uint64_t update_row_cnt_; uint64_t build_cnt_; uint64_t mix_cnt_; jubatus::util::lang::shared_ptr<core::driver::nearest_neighbor> nearest_neighbor_; fv_converter::so_factory so_loader_; }; } // namespace server } // namespace jubatus #endif // JUBATUS_SERVER_SERVER_NEAREST_NEIGHBOR_SERV_HPP_ <|endoftext|>
<commit_before>/** * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com> * All Rights Reserved. * * This file is CONFIDENTIAL -- Distribution or duplication of this material or * the information contained herein is strictly forbidden unless prior written * permission is obtained. */ #include "logjoin/LogJoinUpload.h" #include "fnord-base/uri.h" #include "fnord-base/util/binarymessagereader.h" #include "fnord-base/util/binarymessagewriter.h" #include "fnord-http/httprequest.h" #include "fnord-json/json.h" using namespace fnord; namespace cm { LogJoinUpload::LogJoinUpload( RefPtr<mdb::MDB> db, const String& tsdb_addr, const String& broker_addr, http::HTTPConnectionPool* http) : db_(db), tsdb_addr_(tsdb_addr), broker_addr_(InetAddr::resolve(broker_addr)), http_(http), batch_size_(kDefaultBatchSize), broker_client_(http) {} void LogJoinUpload::upload() { while (scanQueue("__uploadq-sessions") > 0); } size_t LogJoinUpload::scanQueue(const String& queue_name) { auto txn = db_->startTransaction(); auto cursor = txn->getCursor(); Buffer key; Buffer value; Vector<Buffer> batch; for (int i = 0; i < batch_size_; ++i) { if (i == 0) { key.append(queue_name); if (!cursor->getFirstOrGreater(&key, &value)) { break; } } else { if (!cursor->getNext(&key, &value)) { break; } } if (!StringUtil::beginsWith(key.toString(), queue_name)) { break; } try { util::BinaryMessageReader reader(value.data(), value.size()); reader.readUInt64(); reader.readUInt64(); auto ssize = reader.readVarUInt(); auto sdata = reader.read(ssize); JoinedSession session; msg::decode<JoinedSession>(sdata, ssize, &session); uploadPreferenceSetFeed(session); } catch (...) { txn->abort(); throw; } batch.emplace_back(value); cursor->del(); } cursor->close(); try { if (batch.size() > 0) { uploadTSDBBatch(batch); } } catch (...) { txn->abort(); throw; } txn->commit(); return batch.size(); } void LogJoinUpload::uploadTSDBBatch(const Vector<Buffer>& batch) { URI uri(tsdb_addr_ + "/tsdb/insert_batch?stream=joined_sessions.dawanda"); http::HTTPRequest req(http::HTTPMessage::M_POST, uri.pathAndQuery()); req.addHeader("Host", uri.hostAndPort()); req.addHeader("Content-Type", "application/fnord-msg"); util::BinaryMessageWriter body; for (const auto& b : batch) { body.append(b.data(), b.size()); } req.addBody(body.data(), body.size()); auto res = http_->executeRequest(req); res.wait(); const auto& r = res.get(); if (r.statusCode() != 201) { RAISEF(kRuntimeError, "received non-201 response: $0", r.body().toString()); } } void LogJoinUpload::uploadPreferenceSetFeed(const JoinedSession& session) { Set<String> visited_products; for (const auto& item_visit : session.item_visits()) { visited_products.emplace(item_visit.item_id()); } Set<String> bought_products; for (const auto& cart_item : session.cart_items()) { if (cart_item.checkout_step() != 1) { continue; } bought_products.emplace(cart_item.item_id()); } Buffer buf; json::JSONOutputStream json(BufferOutputStream::fromBuffer(&buf)); json.beginObject(); json.addObjectEntry("time"); json.addInteger(WallClock::unixMicros() / kMicrosPerSecond); json.addComma(); json.addObjectEntry("visited_products"); json::toJSON(visited_products, &json); json.addComma(); json.addObjectEntry("bought_products"); json::toJSON(bought_products, &json); json.endObject(); auto topic = StringUtil::format( "logjoin.ecommerce_preference_sets.$0", session.customer()); broker_client_.insert(broker_addr_, topic, buf); } void LogJoinUpload::uploadQueryFeed(const JoinedSession& session) { } } // namespace cm <commit_msg>logjoin.ecommerce_search_queries feed<commit_after>/** * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com> * All Rights Reserved. * * This file is CONFIDENTIAL -- Distribution or duplication of this material or * the information contained herein is strictly forbidden unless prior written * permission is obtained. */ #include "logjoin/LogJoinUpload.h" #include "fnord-base/uri.h" #include "fnord-base/util/binarymessagereader.h" #include "fnord-base/util/binarymessagewriter.h" #include "fnord-base/wallclock.h" #include "fnord-http/httprequest.h" #include "fnord-json/json.h" using namespace fnord; namespace cm { LogJoinUpload::LogJoinUpload( RefPtr<mdb::MDB> db, const String& tsdb_addr, const String& broker_addr, http::HTTPConnectionPool* http) : db_(db), tsdb_addr_(tsdb_addr), broker_addr_(InetAddr::resolve(broker_addr)), http_(http), batch_size_(kDefaultBatchSize), broker_client_(http) {} void LogJoinUpload::upload() { while (scanQueue("__uploadq-sessions") > 0); } size_t LogJoinUpload::scanQueue(const String& queue_name) { auto txn = db_->startTransaction(); auto cursor = txn->getCursor(); Buffer key; Buffer value; Vector<Buffer> batch; for (int i = 0; i < batch_size_; ++i) { if (i == 0) { key.append(queue_name); if (!cursor->getFirstOrGreater(&key, &value)) { break; } } else { if (!cursor->getNext(&key, &value)) { break; } } if (!StringUtil::beginsWith(key.toString(), queue_name)) { break; } try { util::BinaryMessageReader reader(value.data(), value.size()); reader.readUInt64(); reader.readUInt64(); auto ssize = reader.readVarUInt(); auto sdata = reader.read(ssize); JoinedSession session; msg::decode<JoinedSession>(sdata, ssize, &session); uploadPreferenceSetFeed(session); uploadQueryFeed(session); } catch (...) { txn->abort(); throw; } batch.emplace_back(value); cursor->del(); } cursor->close(); try { if (batch.size() > 0) { uploadTSDBBatch(batch); } } catch (...) { txn->abort(); throw; } txn->commit(); return batch.size(); } void LogJoinUpload::uploadTSDBBatch(const Vector<Buffer>& batch) { URI uri(tsdb_addr_ + "/tsdb/insert_batch?stream=joined_sessions.dawanda"); http::HTTPRequest req(http::HTTPMessage::M_POST, uri.pathAndQuery()); req.addHeader("Host", uri.hostAndPort()); req.addHeader("Content-Type", "application/fnord-msg"); util::BinaryMessageWriter body; for (const auto& b : batch) { body.append(b.data(), b.size()); } req.addBody(body.data(), body.size()); auto res = http_->executeRequest(req); res.wait(); const auto& r = res.get(); if (r.statusCode() != 201) { RAISEF(kRuntimeError, "received non-201 response: $0", r.body().toString()); } } void LogJoinUpload::uploadPreferenceSetFeed(const JoinedSession& session) { Set<String> visited_products; for (const auto& item_visit : session.item_visits()) { visited_products.emplace(item_visit.item_id()); } Set<String> bought_products; for (const auto& cart_item : session.cart_items()) { if (cart_item.checkout_step() != 1) { continue; } bought_products.emplace(cart_item.item_id()); } Buffer buf; json::JSONOutputStream json(BufferOutputStream::fromBuffer(&buf)); json.beginObject(); json.addObjectEntry("time"); json.addInteger(WallClock::unixMicros() / kMicrosPerSecond); json.addComma(); json.addObjectEntry("visited_products"); json::toJSON(visited_products, &json); json.addComma(); json.addObjectEntry("bought_products"); json::toJSON(bought_products, &json); json.endObject(); auto topic = StringUtil::format( "logjoin.ecommerce_preference_sets.$0", session.customer()); broker_client_.insert(broker_addr_, topic, buf); } void LogJoinUpload::uploadQueryFeed(const JoinedSession& session) { for (const auto& q : session.search_queries()) { Set<String> product_list; Set<String> clicked_products; for (const auto& item : q.result_items()) { product_list.emplace(item.item_id()); if (item.clicked()) { clicked_products.emplace(item.item_id()); } } Buffer buf; json::JSONOutputStream json(BufferOutputStream::fromBuffer(&buf)); json.beginObject(); json.addObjectEntry("time"); json.addInteger(WallClock::unixMicros() / kMicrosPerSecond); json.addComma(); json.addObjectEntry("product_list"); json::toJSON(product_list, &json); json.addComma(); json.addObjectEntry("clicked_products"); json::toJSON(clicked_products, &json); json.endObject(); auto topic = StringUtil::format( "logjoin.ecommerce_search_queries.$0", session.customer()); broker_client_.insert(broker_addr_, topic, buf); } } } // namespace cm <|endoftext|>
<commit_before>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2013-2015 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY 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 <modules/opencl/buffer/buffercl.h> namespace inviwo { BufferCL::BufferCL(size_t size, const DataFormatBase* format, BufferType type, BufferUsage usage, const void* data, cl_mem_flags readWriteFlag) : BufferCLBase() , BufferRepresentation(format, type, usage) , readWriteFlag_(readWriteFlag) , size_(size) { // Generate a new buffer if (data != nullptr) { // CL_MEM_COPY_HOST_PTR can be used with CL_MEM_ALLOC_HOST_PTR to initialize the contents of // the cl_mem object allocated using host-accessible (e.g. PCIe) memory. clBuffer_ = std::make_unique<cl::Buffer>(cl::Buffer(OpenCL::getPtr()->getContext(), readWriteFlag_ | CL_MEM_COPY_HOST_PTR | CL_MEM_ALLOC_HOST_PTR, getSize() * getSizeOfElement(), const_cast<void*>(data))); } else { clBuffer_ = std::make_unique<cl::Buffer>(cl::Buffer(OpenCL::getPtr()->getContext(), readWriteFlag_, getSize() * getSizeOfElement())); } } BufferCL::BufferCL(const BufferCL& rhs) : BufferRepresentation(rhs) , readWriteFlag_(rhs.readWriteFlag_) , size_(rhs.size_) { clBuffer_ = std::make_unique<cl::Buffer>(cl::Buffer(OpenCL::getPtr()->getContext(), readWriteFlag_, getSize() * getSizeOfElement())); OpenCL::getPtr()->getQueue().enqueueCopyBuffer(rhs.get(), *clBuffer_, 0, 0, getSize() * getSizeOfElement()); } BufferCL* BufferCL::clone() const { return new BufferCL(*this); } BufferCL::~BufferCL() { } void BufferCL::setSize(size_t size) { size_ = size; clBuffer_ = std::make_unique<cl::Buffer>(cl::Buffer(OpenCL::getPtr()->getContext(), readWriteFlag_, getSize() * getSizeOfElement())); } size_t BufferCL::getSize() const { return size_; } void BufferCL::upload(const void* data, size_t size) { // Resize buffer if necessary if (size > size_ * getSizeOfElement()) { clBuffer_ = std::make_unique<cl::Buffer>(cl::Buffer(OpenCL::getPtr()->getContext(), readWriteFlag_ | CL_MEM_COPY_HOST_PTR | CL_MEM_ALLOC_HOST_PTR, getSize() * getSizeOfElement(), const_cast<void*>(data))); } else { OpenCL::getPtr()->getQueue().enqueueWriteBuffer(*clBuffer_, true, 0, size, const_cast<void*>(data)); } } void BufferCL::download(void* data) const { try { OpenCL::getPtr()->getQueue().enqueueReadBuffer(*clBuffer_, true, 0, getSize() * getSizeOfElement(), data); } catch (cl::Error& err) { LogError(getCLErrorString(err)); } } } // namespace inviwo namespace cl { template <> cl_int Kernel::setArg(cl_uint index, const inviwo::BufferCL& value) { return setArg(index, value.get()); } template <> cl_int Kernel::setArg(cl_uint index, const inviwo::Buffer& value) { return setArg(index, value.getRepresentation<inviwo::BufferCL>()->get()); } } // namespace cl<commit_msg>OpenCL: Jenkins fix<commit_after>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2013-2015 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY 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 <modules/opencl/buffer/buffercl.h> #include <inviwo/core/util/stdextensions.h> // make_unique is c++14 but works on some compilers namespace inviwo { BufferCL::BufferCL(size_t size, const DataFormatBase* format, BufferType type, BufferUsage usage, const void* data, cl_mem_flags readWriteFlag) : BufferCLBase() , BufferRepresentation(format, type, usage) , readWriteFlag_(readWriteFlag) , size_(size) { // Generate a new buffer if (data != nullptr) { // CL_MEM_COPY_HOST_PTR can be used with CL_MEM_ALLOC_HOST_PTR to initialize the contents of // the cl_mem object allocated using host-accessible (e.g. PCIe) memory. clBuffer_ = util::make_unique<cl::Buffer>(cl::Buffer(OpenCL::getPtr()->getContext(), readWriteFlag_ | CL_MEM_COPY_HOST_PTR | CL_MEM_ALLOC_HOST_PTR, getSize() * getSizeOfElement(), const_cast<void*>(data))); } else { clBuffer_ = util::make_unique<cl::Buffer>(cl::Buffer(OpenCL::getPtr()->getContext(), readWriteFlag_, getSize() * getSizeOfElement())); } } BufferCL::BufferCL(const BufferCL& rhs) : BufferRepresentation(rhs) , readWriteFlag_(rhs.readWriteFlag_) , size_(rhs.size_) { clBuffer_ = util::make_unique<cl::Buffer>(cl::Buffer(OpenCL::getPtr()->getContext(), readWriteFlag_, getSize() * getSizeOfElement())); OpenCL::getPtr()->getQueue().enqueueCopyBuffer(rhs.get(), *clBuffer_, 0, 0, getSize() * getSizeOfElement()); } BufferCL* BufferCL::clone() const { return new BufferCL(*this); } BufferCL::~BufferCL() { } void BufferCL::setSize(size_t size) { size_ = size; clBuffer_ = util::make_unique<cl::Buffer>(cl::Buffer(OpenCL::getPtr()->getContext(), readWriteFlag_, getSize() * getSizeOfElement())); } size_t BufferCL::getSize() const { return size_; } void BufferCL::upload(const void* data, size_t size) { // Resize buffer if necessary if (size > size_ * getSizeOfElement()) { clBuffer_ = util::make_unique<cl::Buffer>(cl::Buffer(OpenCL::getPtr()->getContext(), readWriteFlag_ | CL_MEM_COPY_HOST_PTR | CL_MEM_ALLOC_HOST_PTR, getSize() * getSizeOfElement(), const_cast<void*>(data))); } else { OpenCL::getPtr()->getQueue().enqueueWriteBuffer(*clBuffer_, true, 0, size, const_cast<void*>(data)); } } void BufferCL::download(void* data) const { try { OpenCL::getPtr()->getQueue().enqueueReadBuffer(*clBuffer_, true, 0, getSize() * getSizeOfElement(), data); } catch (cl::Error& err) { LogError(getCLErrorString(err)); } } } // namespace inviwo namespace cl { template <> cl_int Kernel::setArg(cl_uint index, const inviwo::BufferCL& value) { return setArg(index, value.get()); } template <> cl_int Kernel::setArg(cl_uint index, const inviwo::Buffer& value) { return setArg(index, value.getRepresentation<inviwo::BufferCL>()->get()); } } // namespace cl<|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: manager.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: ihi $ $Date: 2008-01-14 14:50:27 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_extensions.hxx" #if STLPORT_VERSION>=321 #include <cstdarg> #endif #include <plugin/impl.hxx> #ifndef _OSL_MUTEX_HXX #include <osl/mutex.hxx> #endif #ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX #include <svtools/pathoptions.hxx> #endif #ifndef _COM_SUN_STAR_CONTAINER_XENUMERATIONACCESS_HPP_ #include <com/sun/star/container/XEnumerationAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XENUMERATION_HPP_ #include <com/sun/star/container/XEnumeration.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XELEMENTACCESS_HPP_ #include <com/sun/star/container/XElementAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_ #include <com/sun/star/container/XIndexAccess.hpp> #endif #ifndef _COM_SUN_STAR_LOADER_XIMPLEMENTATIONLOADER_HPP_ #include <com/sun/star/loader/XImplementationLoader.hpp> #endif #ifndef _COM_SUN_STAR_LOADER_CANNOTACTIVATEFACTORYEXCEPTION_HPP_ #include <com/sun/star/loader/CannotActivateFactoryException.hpp> #endif PluginManager* PluginManager::pManager = NULL; PluginManager& PluginManager::get() { if( ! pManager ) pManager = new PluginManager(); return *pManager; } void PluginManager::setServiceFactory( const Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory ) { PluginManager& rManager = get(); if( ! rManager.m_xSMgr.is() ) rManager.m_xSMgr = xFactory; } PluginManager::PluginManager() { } PluginManager::~PluginManager() { } const Sequence< ::rtl::OUString >& PluginManager::getAdditionalSearchPaths() { static Sequence< ::rtl::OUString > aPaths; if( ! aPaths.getLength() ) { SvtPathOptions aOptions; String aPluginPath( aOptions.GetPluginPath() ); if( aPluginPath.Len() ) { USHORT nPaths = aPluginPath.GetTokenCount( ';' ); aPaths.realloc( nPaths ); for( USHORT i = 0; i < nPaths; i++ ) aPaths.getArray()[i] = aPluginPath.GetToken( i, ';' ); } } return aPaths; } //================================================================================================== Reference< XInterface > SAL_CALL PluginManager_CreateInstance( const Reference< ::com::sun::star::lang::XMultiServiceFactory > & rSMgr ) throw( Exception ) { Reference< XInterface > xService = *new XPluginManager_Impl( rSMgr ); return xService; } // ::com::sun::star::lang::XServiceInfo ::rtl::OUString XPluginManager_Impl::getImplementationName() throw( ) { return getImplementationName_Static(); } // ::com::sun::star::lang::XServiceInfo sal_Bool XPluginManager_Impl::supportsService(const ::rtl::OUString& ServiceName) throw( ) { Sequence< ::rtl::OUString > aSNL = getSupportedServiceNames(); const ::rtl::OUString * pArray = aSNL.getConstArray(); for( sal_Int32 i = 0; i < aSNL.getLength(); i++ ) if( pArray[i] == ServiceName ) return sal_True; return sal_False; } // ::com::sun::star::lang::XServiceInfo Sequence< ::rtl::OUString > XPluginManager_Impl::getSupportedServiceNames(void) throw( ) { return getSupportedServiceNames_Static(); } // XPluginManager_Impl Sequence< ::rtl::OUString > XPluginManager_Impl::getSupportedServiceNames_Static(void) throw( ) { Sequence< ::rtl::OUString > aSNS( 1 ); aSNS.getArray()[0] = ::rtl::OUString::createFromAscii( "com.sun.star.plugin.PluginManager" ); return aSNS; } XPluginManager_Impl::XPluginManager_Impl( const Reference< ::com::sun::star::lang::XMultiServiceFactory > & rSMgr ) : m_xSMgr( rSMgr ) { PluginManager::setServiceFactory( rSMgr ); } XPluginManager_Impl::~XPluginManager_Impl() { } XPlugin_Impl* XPluginManager_Impl::getXPluginFromNPP( NPP instance ) { ::std::list<XPlugin_Impl*>::iterator iter; for( iter = PluginManager::get().getPlugins().begin(); iter != PluginManager::get().getPlugins().end(); ++iter ) { if( (*iter)->getNPPInstance() == instance ) return *iter; } return NULL; } XPlugin_Impl* XPluginManager_Impl::getPluginImplementation( const Reference< ::com::sun::star::plugin::XPlugin >& plugin ) { ::std::list<XPlugin_Impl*>::iterator iter; for( iter = PluginManager::get().getPlugins().begin(); iter != PluginManager::get().getPlugins().end(); ++iter ) { if( plugin == Reference< ::com::sun::star::plugin::XPlugin >((*iter)) ) return *iter; } return NULL; } XPlugin_Impl* XPluginManager_Impl::getFirstXPlugin() { if( PluginManager::get().getPlugins().begin() == PluginManager::get().getPlugins().end() ) return NULL; return *PluginManager::get().getPlugins().begin(); } Reference< ::com::sun::star::plugin::XPlugin > XPluginManager_Impl::createPlugin( const Reference< ::com::sun::star::plugin::XPluginContext >& acontext, INT16 mode, const Sequence< ::rtl::OUString >& argn, const Sequence< ::rtl::OUString >& argv, const ::com::sun::star::plugin::PluginDescription& plugintype) throw( RuntimeException,::com::sun::star::plugin::PluginException ) { XPlugin_Impl* pImpl = new XPlugin_Impl( m_xSMgr ); pImpl->setPluginContext( acontext ); PluginManager::get().getPlugins().push_back( pImpl ); pImpl->initInstance( plugintype, argn, argv, mode ); return pImpl; } Reference< ::com::sun::star::plugin::XPlugin > XPluginManager_Impl::createPluginFromURL( const Reference< ::com::sun::star::plugin::XPluginContext > & acontext, sal_Int16 mode, const Sequence< ::rtl::OUString >& argn, const Sequence< ::rtl::OUString >& argv, const Reference< ::com::sun::star::awt::XToolkit > & toolkit, const Reference< ::com::sun::star::awt::XWindowPeer > & parent, const ::rtl::OUString& url ) throw() { XPlugin_Impl* pImpl = new XPlugin_Impl( m_xSMgr ); Reference< ::com::sun::star::plugin::XPlugin > xRef = pImpl; pImpl->setPluginContext( acontext ); PluginManager::get().getPlugins().push_back( pImpl ); pImpl->initInstance( url, argn, argv, mode ); pImpl->createPeer( toolkit, parent ); pImpl->provideNewStream( pImpl->getDescription().Mimetype, Reference< com::sun::star::io::XActiveDataSource >(), url, 0, 0, (sal_Bool)(url.compareToAscii( "file:", 5 ) == 0) ); if( ! pImpl->getPluginComm() ) { pImpl->dispose(); xRef = NULL; } return xRef; } <commit_msg>INTEGRATION: CWS changefileheader (1.9.48); FILE MERGED 2008/04/01 15:15:09 thb 1.9.48.3: #i85898# Stripping all external header guards 2008/04/01 12:29:46 thb 1.9.48.2: #i85898# Stripping all external header guards 2008/03/31 12:31:35 rt 1.9.48.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: manager.cxx,v $ * $Revision: 1.10 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_extensions.hxx" #if STLPORT_VERSION>=321 #include <cstdarg> #endif #include <plugin/impl.hxx> #ifndef _OSL_MUTEX_HXX #include <osl/mutex.hxx> #endif #include <svtools/pathoptions.hxx> #include <com/sun/star/container/XEnumerationAccess.hpp> #include <com/sun/star/container/XNameAccess.hpp> #include <com/sun/star/container/XEnumeration.hpp> #include <com/sun/star/container/XElementAccess.hpp> #include <com/sun/star/container/XIndexAccess.hpp> #include <com/sun/star/loader/XImplementationLoader.hpp> #include <com/sun/star/loader/CannotActivateFactoryException.hpp> PluginManager* PluginManager::pManager = NULL; PluginManager& PluginManager::get() { if( ! pManager ) pManager = new PluginManager(); return *pManager; } void PluginManager::setServiceFactory( const Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory ) { PluginManager& rManager = get(); if( ! rManager.m_xSMgr.is() ) rManager.m_xSMgr = xFactory; } PluginManager::PluginManager() { } PluginManager::~PluginManager() { } const Sequence< ::rtl::OUString >& PluginManager::getAdditionalSearchPaths() { static Sequence< ::rtl::OUString > aPaths; if( ! aPaths.getLength() ) { SvtPathOptions aOptions; String aPluginPath( aOptions.GetPluginPath() ); if( aPluginPath.Len() ) { USHORT nPaths = aPluginPath.GetTokenCount( ';' ); aPaths.realloc( nPaths ); for( USHORT i = 0; i < nPaths; i++ ) aPaths.getArray()[i] = aPluginPath.GetToken( i, ';' ); } } return aPaths; } //================================================================================================== Reference< XInterface > SAL_CALL PluginManager_CreateInstance( const Reference< ::com::sun::star::lang::XMultiServiceFactory > & rSMgr ) throw( Exception ) { Reference< XInterface > xService = *new XPluginManager_Impl( rSMgr ); return xService; } // ::com::sun::star::lang::XServiceInfo ::rtl::OUString XPluginManager_Impl::getImplementationName() throw( ) { return getImplementationName_Static(); } // ::com::sun::star::lang::XServiceInfo sal_Bool XPluginManager_Impl::supportsService(const ::rtl::OUString& ServiceName) throw( ) { Sequence< ::rtl::OUString > aSNL = getSupportedServiceNames(); const ::rtl::OUString * pArray = aSNL.getConstArray(); for( sal_Int32 i = 0; i < aSNL.getLength(); i++ ) if( pArray[i] == ServiceName ) return sal_True; return sal_False; } // ::com::sun::star::lang::XServiceInfo Sequence< ::rtl::OUString > XPluginManager_Impl::getSupportedServiceNames(void) throw( ) { return getSupportedServiceNames_Static(); } // XPluginManager_Impl Sequence< ::rtl::OUString > XPluginManager_Impl::getSupportedServiceNames_Static(void) throw( ) { Sequence< ::rtl::OUString > aSNS( 1 ); aSNS.getArray()[0] = ::rtl::OUString::createFromAscii( "com.sun.star.plugin.PluginManager" ); return aSNS; } XPluginManager_Impl::XPluginManager_Impl( const Reference< ::com::sun::star::lang::XMultiServiceFactory > & rSMgr ) : m_xSMgr( rSMgr ) { PluginManager::setServiceFactory( rSMgr ); } XPluginManager_Impl::~XPluginManager_Impl() { } XPlugin_Impl* XPluginManager_Impl::getXPluginFromNPP( NPP instance ) { ::std::list<XPlugin_Impl*>::iterator iter; for( iter = PluginManager::get().getPlugins().begin(); iter != PluginManager::get().getPlugins().end(); ++iter ) { if( (*iter)->getNPPInstance() == instance ) return *iter; } return NULL; } XPlugin_Impl* XPluginManager_Impl::getPluginImplementation( const Reference< ::com::sun::star::plugin::XPlugin >& plugin ) { ::std::list<XPlugin_Impl*>::iterator iter; for( iter = PluginManager::get().getPlugins().begin(); iter != PluginManager::get().getPlugins().end(); ++iter ) { if( plugin == Reference< ::com::sun::star::plugin::XPlugin >((*iter)) ) return *iter; } return NULL; } XPlugin_Impl* XPluginManager_Impl::getFirstXPlugin() { if( PluginManager::get().getPlugins().begin() == PluginManager::get().getPlugins().end() ) return NULL; return *PluginManager::get().getPlugins().begin(); } Reference< ::com::sun::star::plugin::XPlugin > XPluginManager_Impl::createPlugin( const Reference< ::com::sun::star::plugin::XPluginContext >& acontext, INT16 mode, const Sequence< ::rtl::OUString >& argn, const Sequence< ::rtl::OUString >& argv, const ::com::sun::star::plugin::PluginDescription& plugintype) throw( RuntimeException,::com::sun::star::plugin::PluginException ) { XPlugin_Impl* pImpl = new XPlugin_Impl( m_xSMgr ); pImpl->setPluginContext( acontext ); PluginManager::get().getPlugins().push_back( pImpl ); pImpl->initInstance( plugintype, argn, argv, mode ); return pImpl; } Reference< ::com::sun::star::plugin::XPlugin > XPluginManager_Impl::createPluginFromURL( const Reference< ::com::sun::star::plugin::XPluginContext > & acontext, sal_Int16 mode, const Sequence< ::rtl::OUString >& argn, const Sequence< ::rtl::OUString >& argv, const Reference< ::com::sun::star::awt::XToolkit > & toolkit, const Reference< ::com::sun::star::awt::XWindowPeer > & parent, const ::rtl::OUString& url ) throw() { XPlugin_Impl* pImpl = new XPlugin_Impl( m_xSMgr ); Reference< ::com::sun::star::plugin::XPlugin > xRef = pImpl; pImpl->setPluginContext( acontext ); PluginManager::get().getPlugins().push_back( pImpl ); pImpl->initInstance( url, argn, argv, mode ); pImpl->createPeer( toolkit, parent ); pImpl->provideNewStream( pImpl->getDescription().Mimetype, Reference< com::sun::star::io::XActiveDataSource >(), url, 0, 0, (sal_Bool)(url.compareToAscii( "file:", 5 ) == 0) ); if( ! pImpl->getPluginComm() ) { pImpl->dispose(); xRef = NULL; } return xRef; } <|endoftext|>
<commit_before> namespace allpix { /** * Get a value from the field assigned to a specific pixel. This means, we cannot wrap around at the pixel edges and * start using the field of the adjacent pixel, but need to calculate the total distance from the lookup point in local * coordinates to the field origin in the given pixel. */ template <typename T, size_t N> T DetectorField<T, N>::getRelativeTo(const ROOT::Math::XYZPoint& pos, const ROOT::Math::XYPoint& ref) const { if(type_ == FieldType::NONE) { return {}; } // Calculate the coordinates relative to the reference point: auto x = pos.x() - ref.x(); auto y = pos.y() - ref.y(); auto z = pos.z(); T ret_val; if(type_ == FieldType::GRID) { ret_val = get_field_from_grid(ROOT::Math::XYZPoint(x, y, z)); } else { // Check if inside the thickness domain if(z < thickness_domain_.first || thickness_domain_.second < z) { return {}; } // Calculate the field from the configured function: ret_val = function_(ROOT::Math::XYZPoint(x, y, z)); } return ret_val; } // Maps the field indices onto the range of -d/2 < x < d/2, where d is the scale of the field in coordinate x. // This means, {x,y,z} = (0,0,0) is in the center of the field. template <typename T, size_t N> T DetectorField<T, N>::get_field_from_grid(const ROOT::Math::XYZPoint& dist) const { // Compute indices // If the dimension in a certain direction is 1, the field is assumed to be 2-dimensional and the respective index // is forced to zero. This circumvents that the field size in the respective dimension would otherwise be zero // clang-format off auto x_ind = (dimensions_[0] == 1 ? 0 : static_cast<int>(std::floor(static_cast<double>(dimensions_[0]) * (dist.x() + scales_[0] / 2.0) / scales_[0]))); auto y_ind = (dimensions_[1] == 1 ? 0 : static_cast<int>(std::floor(static_cast<double>(dimensions_[1]) * (dist.y() + scales_[1] / 2.0) / scales_[1]))); auto z_ind = (dimensions_[2] == 1 ? 0 : static_cast<int>(std::floor(static_cast<double>(dimensions_[2]) * (dist.z() - thickness_domain_.first) / (thickness_domain_.second - thickness_domain_.first)))); // clang-format on // Check for indices within the field map if(x_ind < 0 || x_ind >= static_cast<int>(dimensions_[0]) || y_ind < 0 || y_ind >= static_cast<int>(dimensions_[1]) || z_ind < 0 || z_ind >= static_cast<int>(dimensions_[2])) { return {}; } // Compute total index size_t tot_ind = static_cast<size_t>(x_ind) * dimensions_[1] * dimensions_[2] * N + static_cast<size_t>(y_ind) * dimensions_[2] * N + static_cast<size_t>(z_ind) * N; return get_impl(tot_ind, std::make_index_sequence<N>{}); } /** * The field is replicated for all pixels and uses flipping at each boundary (edge effects are currently not modeled. * Outside of the sensor the field is strictly zero by definition. */ template <typename T, size_t N> T DetectorField<T, N>::get(const ROOT::Math::XYZPoint& pos) const { // FIXME: We need to revisit this to be faster and not too specific if(type_ == FieldType::NONE) { return {}; } // Shift the coordinates by the offset configured for the field: auto x = pos.x() - offset_[0]; auto y = pos.y() - offset_[1]; auto z = pos.z(); // Compute corresponding field replica coordinates: // WARNING This relies on the origin of the local coordinate system auto replica_x = static_cast<int>(std::floor((x + 0.5 * pixel_size_.x()) / scales_[0])); auto replica_y = static_cast<int>(std::floor((y + 0.5 * pixel_size_.y()) / scales_[1])); // Convert to the replica frame: x -= (replica_x + 0.5) * scales_[0] - 0.5 * pixel_size_.x(); y -= (replica_y + 0.5) * scales_[1] - 0.5 * pixel_size_.y(); // Do flipping if necessary if((replica_x % 2) == 1) { x *= -1; } if((replica_y % 2) == 1) { y *= -1; } // Compute using the grid or a function depending on the setting T ret_val; if(type_ == FieldType::GRID) { ret_val = get_field_from_grid(ROOT::Math::XYZPoint(x, y, z)); } else { // Check if inside the thickness domain if(z < thickness_domain_.first || thickness_domain_.second < z) { return {}; } // Calculate the field from the configured function: ret_val = function_(ROOT::Math::XYZPoint(x, y, z)); } // Flip vector if necessary flip_vector_components(ret_val, replica_x % 2, replica_y % 2); return ret_val; } /** * Woohoo, template magic! Using an index_sequence to construct the templated return type with a variable number of * elements from the flat field vector, e.g. 3 for a vector field and 1 for a scalar field. Using a braced-init-list * allows to call the appropriate constructor of the return type, e.g. ROOT::Math::XYZVector or simply a double. */ template <typename T, size_t N> template <std::size_t... I> auto DetectorField<T, N>::get_impl(size_t offset, std::index_sequence<I...>) const { return T{(*field_)[offset + I]...}; } /** * The type of the field is set depending on the function used to apply it. */ template <typename T, size_t N> FieldType DetectorField<T, N>::getType() const { return type_; } /** * @throws std::invalid_argument If the field dimensions are incorrect or the thickness domain is outside the sensor */ template <typename T, size_t N> void DetectorField<T, N>::setGrid(std::shared_ptr<std::vector<double>> field, std::array<size_t, 3> dimensions, std::array<double, 2> scales, std::array<double, 2> offset, std::pair<double, double> thickness_domain) { if(!model_initialized_) { throw std::invalid_argument("field not initialized with detector model parameters"); } if(dimensions[0] * dimensions[1] * dimensions[2] * N != field->size()) { throw std::invalid_argument("field does not match the given dimensions"); } if(thickness_domain.first + 1e-9 < sensor_center_.z() - sensor_size_.z() / 2.0 || sensor_center_.z() + sensor_size_.z() / 2.0 < thickness_domain.second - 1e-9) { throw std::invalid_argument("thickness domain is outside sensor dimensions"); } if(thickness_domain.first >= thickness_domain.second) { throw std::invalid_argument("end of thickness domain is before begin"); } field_ = std::move(field); dimensions_ = dimensions; scales_ = scales; offset_ = offset; thickness_domain_ = std::move(thickness_domain); type_ = FieldType::GRID; } template <typename T, size_t N> void DetectorField<T, N>::setFunction(FieldFunction<T> function, std::pair<double, double> thickness_domain, FieldType type) { thickness_domain_ = std::move(thickness_domain); function_ = std::move(function); type_ = type; } } // namespace allpix <commit_msg>Fix issue introduced in f2afca0f437c211d87b05e8e59d632fa3bd2c5fc: with single bin in Z, field was always returned instead of obeying the thickness domain<commit_after> namespace allpix { /** * Get a value from the field assigned to a specific pixel. This means, we cannot wrap around at the pixel edges and * start using the field of the adjacent pixel, but need to calculate the total distance from the lookup point in local * coordinates to the field origin in the given pixel. */ template <typename T, size_t N> T DetectorField<T, N>::getRelativeTo(const ROOT::Math::XYZPoint& pos, const ROOT::Math::XYPoint& ref) const { if(type_ == FieldType::NONE) { return {}; } // Calculate the coordinates relative to the reference point: auto x = pos.x() - ref.x(); auto y = pos.y() - ref.y(); auto z = pos.z(); T ret_val; if(type_ == FieldType::GRID) { ret_val = get_field_from_grid(ROOT::Math::XYZPoint(x, y, z)); } else { // Check if inside the thickness domain if(z < thickness_domain_.first || thickness_domain_.second < z) { return {}; } // Calculate the field from the configured function: ret_val = function_(ROOT::Math::XYZPoint(x, y, z)); } return ret_val; } // Maps the field indices onto the range of -d/2 < x < d/2, where d is the scale of the field in coordinate x. // This means, {x,y,z} = (0,0,0) is in the center of the field. template <typename T, size_t N> T DetectorField<T, N>::get_field_from_grid(const ROOT::Math::XYZPoint& dist) const { // Compute indices // If the dimension in a certain direction is 1, the field is assumed to be 2-dimensional and the respective index // is forced to zero. This circumvents that the field size in the respective dimension would otherwise be zero // clang-format off auto x_ind = (dimensions_[0] == 1 ? 0 : static_cast<int>(std::floor(static_cast<double>(dimensions_[0]) * (dist.x() + scales_[0] / 2.0) / scales_[0]))); auto y_ind = (dimensions_[1] == 1 ? 0 : static_cast<int>(std::floor(static_cast<double>(dimensions_[1]) * (dist.y() + scales_[1] / 2.0) / scales_[1]))); auto z_ind = static_cast<int>(std::floor(static_cast<double>(dimensions_[2]) * (dist.z() - thickness_domain_.first) / (thickness_domain_.second - thickness_domain_.first))); // clang-format on // Check for indices within the field map if(x_ind < 0 || x_ind >= static_cast<int>(dimensions_[0]) || y_ind < 0 || y_ind >= static_cast<int>(dimensions_[1]) || z_ind < 0 || z_ind >= static_cast<int>(dimensions_[2])) { return {}; } // Compute total index size_t tot_ind = static_cast<size_t>(x_ind) * dimensions_[1] * dimensions_[2] * N + static_cast<size_t>(y_ind) * dimensions_[2] * N + static_cast<size_t>(z_ind) * N; return get_impl(tot_ind, std::make_index_sequence<N>{}); } /** * The field is replicated for all pixels and uses flipping at each boundary (edge effects are currently not modeled. * Outside of the sensor the field is strictly zero by definition. */ template <typename T, size_t N> T DetectorField<T, N>::get(const ROOT::Math::XYZPoint& pos) const { // FIXME: We need to revisit this to be faster and not too specific if(type_ == FieldType::NONE) { return {}; } // Shift the coordinates by the offset configured for the field: auto x = pos.x() - offset_[0]; auto y = pos.y() - offset_[1]; auto z = pos.z(); // Compute corresponding field replica coordinates: // WARNING This relies on the origin of the local coordinate system auto replica_x = static_cast<int>(std::floor((x + 0.5 * pixel_size_.x()) / scales_[0])); auto replica_y = static_cast<int>(std::floor((y + 0.5 * pixel_size_.y()) / scales_[1])); // Convert to the replica frame: x -= (replica_x + 0.5) * scales_[0] - 0.5 * pixel_size_.x(); y -= (replica_y + 0.5) * scales_[1] - 0.5 * pixel_size_.y(); // Do flipping if necessary if((replica_x % 2) == 1) { x *= -1; } if((replica_y % 2) == 1) { y *= -1; } // Compute using the grid or a function depending on the setting T ret_val; if(type_ == FieldType::GRID) { ret_val = get_field_from_grid(ROOT::Math::XYZPoint(x, y, z)); } else { // Check if inside the thickness domain if(z < thickness_domain_.first || thickness_domain_.second < z) { return {}; } // Calculate the field from the configured function: ret_val = function_(ROOT::Math::XYZPoint(x, y, z)); } // Flip vector if necessary flip_vector_components(ret_val, replica_x % 2, replica_y % 2); return ret_val; } /** * Woohoo, template magic! Using an index_sequence to construct the templated return type with a variable number of * elements from the flat field vector, e.g. 3 for a vector field and 1 for a scalar field. Using a braced-init-list * allows to call the appropriate constructor of the return type, e.g. ROOT::Math::XYZVector or simply a double. */ template <typename T, size_t N> template <std::size_t... I> auto DetectorField<T, N>::get_impl(size_t offset, std::index_sequence<I...>) const { return T{(*field_)[offset + I]...}; } /** * The type of the field is set depending on the function used to apply it. */ template <typename T, size_t N> FieldType DetectorField<T, N>::getType() const { return type_; } /** * @throws std::invalid_argument If the field dimensions are incorrect or the thickness domain is outside the sensor */ template <typename T, size_t N> void DetectorField<T, N>::setGrid(std::shared_ptr<std::vector<double>> field, std::array<size_t, 3> dimensions, std::array<double, 2> scales, std::array<double, 2> offset, std::pair<double, double> thickness_domain) { if(!model_initialized_) { throw std::invalid_argument("field not initialized with detector model parameters"); } if(dimensions[0] * dimensions[1] * dimensions[2] * N != field->size()) { throw std::invalid_argument("field does not match the given dimensions"); } if(thickness_domain.first + 1e-9 < sensor_center_.z() - sensor_size_.z() / 2.0 || sensor_center_.z() + sensor_size_.z() / 2.0 < thickness_domain.second - 1e-9) { throw std::invalid_argument("thickness domain is outside sensor dimensions"); } if(thickness_domain.first >= thickness_domain.second) { throw std::invalid_argument("end of thickness domain is before begin"); } field_ = std::move(field); dimensions_ = dimensions; scales_ = scales; offset_ = offset; thickness_domain_ = std::move(thickness_domain); type_ = FieldType::GRID; } template <typename T, size_t N> void DetectorField<T, N>::setFunction(FieldFunction<T> function, std::pair<double, double> thickness_domain, FieldType type) { thickness_domain_ = std::move(thickness_domain); function_ = std::move(function); type_ = type; } } // namespace allpix <|endoftext|>
<commit_before>/* Copyright (c) 2009 Volker Krause <vkrause@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; 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 "move.h" #include <akonadiconnection.h> #include <entities.h> #include <imapstreamparser.h> #include <handlerhelper.h> #include <storage/datastore.h> #include <storage/itemretriever.h> #include <storage/itemqueryhelper.h> #include <storage/selectquerybuilder.h> #include <storage/transaction.h> #include <storage/collectionqueryhelper.h> namespace Akonadi { Move::Move( Scope::SelectionScope scope ) : mScope( scope ) { } bool Move::parseStream() { mScope.parseScope( m_streamParser ); Scope destScope( mScope.scope() ); destScope.parseScope( m_streamParser ); const Collection destination = CollectionQueryHelper::singleCollectionFromScope( destScope, connection() ); const Resource destResource = destination.resource(); // make sure all the items we want to move are in the cache ItemRetriever retriever( connection() ); retriever.setScope( mScope ); retriever.setRetrieveFullPayload( true ); retriever.exec(); DataStore *store = connection()->storageBackend(); Transaction transaction( store ); SelectQueryBuilder<PimItem> qb; ItemQueryHelper::scopeToQuery( mScope, connection(), qb ); qb.addValueCondition( PimItem::collectionIdFullColumnName(), Query::NotEquals, destination.id() ); const QDateTime mtime = QDateTime::currentDateTime(); if ( qb.exec() ) { const QList<PimItem> items = qb.result(); if ( items.isEmpty() ) throw HandlerException( "No items found" ); foreach ( PimItem item, items ) { if ( !item.isValid() ) throw HandlerException( "Invalid item in result set!?" ); Q_ASSERT( item.collectionId() != destination.id() ); const Collection source = item.collection(); if ( !source.isValid() ) throw HandlerException( "Item without collection found!?" ); // reset remote id on inter-resource moves if ( item.collection().resource().id() != destination.resource().id() ) item.setRemoteId( QString() ); item.setCollectionId( destination.id() ); item.setAtime( mtime ); item.setDatetime( mtime ); // if the resource moved itself, we assume it did so because the change happend in the backend if ( connection()->resourceContext().id() != destResource.id() ) item.setDirty( true ); if ( !item.update() ) throw HandlerException( "Unable to update item" ); store->notificationCollector()->itemMoved( item, source, destination ); } } else { throw HandlerException( "Unable to execute query" ); } if ( !transaction.commit() ) return failureResponse( "Unable to commit transaction." ); return successResponse( "MOVE complete" ); } } #include "move.moc" <commit_msg>Reset the RID after generating the change notification message. This way the source resource still has a valid RID to work with.<commit_after>/* Copyright (c) 2009 Volker Krause <vkrause@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; 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 "move.h" #include <akonadiconnection.h> #include <entities.h> #include <imapstreamparser.h> #include <handlerhelper.h> #include <storage/datastore.h> #include <storage/itemretriever.h> #include <storage/itemqueryhelper.h> #include <storage/selectquerybuilder.h> #include <storage/transaction.h> #include <storage/collectionqueryhelper.h> namespace Akonadi { Move::Move( Scope::SelectionScope scope ) : mScope( scope ) { } bool Move::parseStream() { mScope.parseScope( m_streamParser ); Scope destScope( mScope.scope() ); destScope.parseScope( m_streamParser ); const Collection destination = CollectionQueryHelper::singleCollectionFromScope( destScope, connection() ); const Resource destResource = destination.resource(); // make sure all the items we want to move are in the cache ItemRetriever retriever( connection() ); retriever.setScope( mScope ); retriever.setRetrieveFullPayload( true ); retriever.exec(); DataStore *store = connection()->storageBackend(); Transaction transaction( store ); SelectQueryBuilder<PimItem> qb; ItemQueryHelper::scopeToQuery( mScope, connection(), qb ); qb.addValueCondition( PimItem::collectionIdFullColumnName(), Query::NotEquals, destination.id() ); const QDateTime mtime = QDateTime::currentDateTime(); if ( qb.exec() ) { const QList<PimItem> items = qb.result(); if ( items.isEmpty() ) throw HandlerException( "No items found" ); foreach ( PimItem item, items ) { if ( !item.isValid() ) throw HandlerException( "Invalid item in result set!?" ); Q_ASSERT( item.collectionId() != destination.id() ); const Collection source = item.collection(); if ( !source.isValid() ) throw HandlerException( "Item without collection found!?" ); const bool isInterResourceMove = item.collection().resource().id() != destResource.id(); item.setCollectionId( destination.id() ); item.setAtime( mtime ); item.setDatetime( mtime ); // if the resource moved itself, we assume it did so because the change happend in the backend if ( connection()->resourceContext().id() != destResource.id() ) item.setDirty( true ); store->notificationCollector()->itemMoved( item, source, destination ); // reset RID on inter-resource moves, but only after generating the change notification // so that this still contains the old one for the source resource if ( isInterResourceMove ) item.setRemoteId( QString() ); if ( !item.update() ) throw HandlerException( "Unable to update item" ); } } else { throw HandlerException( "Unable to execute query" ); } if ( !transaction.commit() ) return failureResponse( "Unable to commit transaction." ); return successResponse( "MOVE complete" ); } } #include "move.moc" <|endoftext|>
<commit_before>#include <array> #include <stdexcept> #include <string> #include <utility> #include <vector> #include <ros/ros.h> #include <controller_manager/controller_manager.h> #include <geometry_msgs/Twist.h> #include <hardware_interface/joint_command_interface.h> #include <hardware_interface/joint_state_interface.h> #include <hardware_interface/robot_hw.h> #include <nav_msgs/Odometry.h> #include <ics3/ics> struct JointData { std::string name_; double cmd_; double pos_; double vel_; double eff_; }; template<class JntCmdIF> struct JointControlBuildData { std::string joint_name_; hardware_interface::JointStateInterface& jnt_stat_; JntCmdIF& jnt_cmd_; }; class JointControlInterface { public: virtual void fetch() = 0; virtual void move() = 0; virtual ~JointControlInterface() noexcept {} }; class ICSControl : public JointControlInterface { public: using JntCmdType = hardware_interface::PositionJointInterface; using BuildDataType = JointControlBuildData<JntCmdType>; ICSControl(BuildDataType&, ics::ICS3&, const ics::ID&); void fetch() override; void move() override; private: JointData data_; ics::ICS3& driver_; ics::ID id_; double last_pos_; }; class DCMotorControl : public JointControlInterface { public: using JntCmdType = hardware_interface::VelocityJointInterface; using BuildDataType = JointControlBuildData<JntCmdType>; DCMotorControl(BuildDataType&); void fetch() override; void move() override; void odomCb(const nav_msgs::OdometryConstPtr&); private: JointData data_; double last_pos_; double last_vel_; ros::NodeHandle nh_; ros::Publisher pub_; ros::Subscriber sub_; }; template<class JntCmdIF> class DammyControl : public JointControlInterface { public: using JntCmdType = JntCmdIF; using BuildDataType = JointControlBuildData<JntCmdType>; DammyControl(BuildDataType&); void fetch() override; void move() override; private: JointData data_; }; using DammyPositionControl = DammyControl<hardware_interface::PositionJointInterface>; using DammyVelocityControl = DammyControl<hardware_interface::VelocityJointInterface>; class Arcsys2HW : public hardware_interface::RobotHW { public: static constexpr std::size_t JOINT_COUNT {6}; using JointControlContainer = std::array<JointControlInterface*, JOINT_COUNT>; Arcsys2HW(hardware_interface::JointStateInterface*); void registerControl(JointControlInterface*); void read(); void write(); ros::Time getTime(); ros::Duration getPeriod(); private: JointControlContainer controls; }; template<class JntCmdIF> void registerJoint( JointData&, hardware_interface::JointStateInterface&, JntCmdIF&); template<class JntCmdIF> void registerJoint( JointData&, JointControlBuildData<JntCmdIF>&); int main(int argc, char *argv[]) { ros::init(argc, argv, "arcsys2_control_node"); ros::NodeHandle pnh {"~"}; std::string ics_device_path {"/dev/ttyUSB0"}; pnh.param<std::string>("ics_device_path", ics_device_path, ics_device_path); ics::ICS3 ics_driver {std::move(ics_device_path)}; std::vector<int> ics_id_vec {}; pnh.getParam("ics_id_vec", ics_id_vec); if (ics_id_vec.empty()) throw std::invalid_argument {"ics_id_vec parameter is not found"}; std::vector<ics::ID> ics_ids(ics_id_vec.cbegin(), ics_id_vec.cend()); hardware_interface::JointStateInterface joint_state_interface {}; hardware_interface::PositionJointInterface position_joint_interface {}; hardware_interface::VelocityJointInterface velocity_joint_interface {}; DammyVelocityControl::BuildDataType shaft_builder {"rail_to_shaft_joint", joint_state_interface, velocity_joint_interface}; DammyVelocityControl shaft_control {shaft_builder}; DammyVelocityControl::BuildDataType arm0_builder {"shaft_to_arm0_joint", joint_state_interface, velocity_joint_interface}; DammyVelocityControl arm0_control {arm0_builder}; auto ics_id_it = ics_ids.cbegin(); ICSControl::BuildDataType arm1_builder {"arm0_to_arm1_joint", joint_state_interface, position_joint_interface}; ICSControl arm1_control {arm1_builder, ics_driver, *ics_id_it++}; ICSControl::BuildDataType arm2_builder {"arm1_to_arm2_joint", joint_state_interface, position_joint_interface}; ICSControl arm2_control {arm2_builder, ics_driver, *ics_id_it++}; ICSControl::BuildDataType effector_base_builder {"arm2_to_effector_base_joint", joint_state_interface, position_joint_interface}; ICSControl effector_base_control {effector_base_builder, ics_driver, *ics_id_it++}; DammyPositionControl::BuildDataType effector_end_builder {"effector_base_to_effector_end_joint", joint_state_interface, position_joint_interface}; DammyPositionControl effector_end_control {effector_end_builder}; Arcsys2HW robot {&joint_state_interface}; robot.registerInterface(&position_joint_interface); robot.registerInterface(&velocity_joint_interface); robot.registerControl(&shaft_control); robot.registerControl(&arm0_control); robot.registerControl(&arm1_control); robot.registerControl(&arm2_control); robot.registerControl(&effector_base_control); robot.registerControl(&effector_end_control); controller_manager::ControllerManager cm {&robot}; ros::Rate rate(1.0 / robot.getPeriod().toSec()); ros::AsyncSpinner spinner {1}; spinner.start(); while(ros::ok()) { robot.read(); cm.update(robot.getTime(), robot.getPeriod()); robot.write(); rate.sleep(); } spinner.stop(); return 0; } inline ICSControl::ICSControl(BuildDataType& build_data, ics::ICS3& driver, const ics::ID& id) : data_ {build_data.joint_name_}, driver_(driver), // for ubuntu 14.04 id_ {id}, last_pos_ {0} { registerJoint(data_, build_data); } inline void ICSControl::fetch() { data_.pos_ = last_pos_; } inline void ICSControl::move() { last_pos_ = driver_.move(id_, ics::Angle::newRadian(data_.cmd_)) / 2 + last_pos_ / 2; } inline DCMotorControl::DCMotorControl(BuildDataType& build_data) : data_ {build_data.joint_name_}, last_pos_ {}, last_vel_ {}, nh_ {build_data.joint_name_}, pub_ {nh_.advertise<geometry_msgs::Twist>("cmd_vel", 1)}, sub_ {nh_.subscribe("odom", 1, &DCMotorControl::odomCb, this)} { } inline void DCMotorControl::fetch() { data_.pos_ = last_pos_; data_.vel_ = last_vel_; } inline void DCMotorControl::move() { geometry_msgs::Twist msg {}; msg.linear.x = data_.cmd_; pub_.publish(std::move(msg)); } inline void DCMotorControl::odomCb(const nav_msgs::OdometryConstPtr& odom) { last_pos_ = odom->pose.pose.position.x; last_vel_ = odom->twist.twist.linear.x; } template<class JntCmdIF> inline DammyControl<JntCmdIF>::DammyControl(BuildDataType& build_data) : data_ {build_data.joint_name_} { registerJoint(data_, build_data); } template<> inline void DammyPositionControl::fetch() { data_.pos_ = data_.cmd_; } template<> inline void DammyVelocityControl::fetch() { data_.pos_ += data_.cmd_ * 0.01; // FIXME: test code data_.vel_ = data_.cmd_; } template<class JntCmdIF> inline void DammyControl<JntCmdIF>::move() { } inline Arcsys2HW::Arcsys2HW(hardware_interface::JointStateInterface* jnt_stat) : controls {} { registerInterface(jnt_stat); } inline void Arcsys2HW::registerControl(JointControlInterface* jnt_cntr) { static auto inserter = controls.begin(); if (inserter == controls.cend()) throw std::out_of_range {"Too many JointControl"}; *inserter = jnt_cntr; ++inserter; } inline void Arcsys2HW::read() { for (auto control : controls) control->fetch(); } inline void Arcsys2HW::write() { for (auto control : controls) control->move(); } inline ros::Time Arcsys2HW::getTime() { return ros::Time::now(); } inline ros::Duration Arcsys2HW::getPeriod() { return ros::Duration {0.01}; } template<class JntCmdIF> inline void registerJoint( JointData& joint, hardware_interface::JointStateInterface& jnt_stat, JntCmdIF& jnt_cmd) { jnt_stat.registerHandle(hardware_interface::JointStateHandle {joint.name_, &joint.pos_, &joint.vel_, &joint.eff_}); jnt_cmd.registerHandle(hardware_interface::JointHandle {jnt_stat.getHandle(joint.name_), &joint.cmd_}); } template<class JntCmdIF> inline void registerJoint( JointData& joint, JointControlBuildData<JntCmdIF>& build_data) { registerJoint(joint, build_data.jnt_stat_, build_data.jnt_cmd_); } <commit_msg>Rename DCMotorControl to SimpleVelocityControl<commit_after>#include <array> #include <stdexcept> #include <string> #include <utility> #include <vector> #include <ros/ros.h> #include <controller_manager/controller_manager.h> #include <geometry_msgs/Twist.h> #include <hardware_interface/joint_command_interface.h> #include <hardware_interface/joint_state_interface.h> #include <hardware_interface/robot_hw.h> #include <nav_msgs/Odometry.h> #include <ics3/ics> struct JointData { std::string name_; double cmd_; double pos_; double vel_; double eff_; }; template<class JntCmdIF> struct JointControlBuildData { std::string joint_name_; hardware_interface::JointStateInterface& jnt_stat_; JntCmdIF& jnt_cmd_; }; class JointControlInterface { public: virtual void fetch() = 0; virtual void move() = 0; virtual ~JointControlInterface() noexcept {} }; class ICSControl : public JointControlInterface { public: using JntCmdType = hardware_interface::PositionJointInterface; using BuildDataType = JointControlBuildData<JntCmdType>; ICSControl(BuildDataType&, ics::ICS3&, const ics::ID&); void fetch() override; void move() override; private: JointData data_; ics::ICS3& driver_; ics::ID id_; double last_pos_; }; class SimpleVelocityControl : public JointControlInterface { public: using JntCmdType = hardware_interface::VelocityJointInterface; using BuildDataType = JointControlBuildData<JntCmdType>; SimpleVelocityControl(BuildDataType&); void fetch() override; void move() override; void odomCb(const nav_msgs::OdometryConstPtr&); private: JointData data_; double last_pos_; double last_vel_; ros::NodeHandle nh_; ros::Publisher pub_; ros::Subscriber sub_; }; template<class JntCmdIF> class DammyControl : public JointControlInterface { public: using JntCmdType = JntCmdIF; using BuildDataType = JointControlBuildData<JntCmdType>; DammyControl(BuildDataType&); void fetch() override; void move() override; private: JointData data_; }; using DammyPositionControl = DammyControl<hardware_interface::PositionJointInterface>; using DammyVelocityControl = DammyControl<hardware_interface::VelocityJointInterface>; class Arcsys2HW : public hardware_interface::RobotHW { public: static constexpr std::size_t JOINT_COUNT {6}; using JointControlContainer = std::array<JointControlInterface*, JOINT_COUNT>; Arcsys2HW(hardware_interface::JointStateInterface*); void registerControl(JointControlInterface*); void read(); void write(); ros::Time getTime(); ros::Duration getPeriod(); private: JointControlContainer controls; }; template<class JntCmdIF> void registerJoint( JointData&, hardware_interface::JointStateInterface&, JntCmdIF&); template<class JntCmdIF> void registerJoint( JointData&, JointControlBuildData<JntCmdIF>&); int main(int argc, char *argv[]) { ros::init(argc, argv, "arcsys2_control_node"); ros::NodeHandle pnh {"~"}; std::string ics_device_path {"/dev/ttyUSB0"}; pnh.param<std::string>("ics_device_path", ics_device_path, ics_device_path); ics::ICS3 ics_driver {std::move(ics_device_path)}; std::vector<int> ics_id_vec {}; pnh.getParam("ics_id_vec", ics_id_vec); if (ics_id_vec.empty()) throw std::invalid_argument {"ics_id_vec parameter is not found"}; std::vector<ics::ID> ics_ids(ics_id_vec.cbegin(), ics_id_vec.cend()); hardware_interface::JointStateInterface joint_state_interface {}; hardware_interface::PositionJointInterface position_joint_interface {}; hardware_interface::VelocityJointInterface velocity_joint_interface {}; DammyVelocityControl::BuildDataType shaft_builder {"rail_to_shaft_joint", joint_state_interface, velocity_joint_interface}; DammyVelocityControl shaft_control {shaft_builder}; DammyVelocityControl::BuildDataType arm0_builder {"shaft_to_arm0_joint", joint_state_interface, velocity_joint_interface}; DammyVelocityControl arm0_control {arm0_builder}; auto ics_id_it = ics_ids.cbegin(); ICSControl::BuildDataType arm1_builder {"arm0_to_arm1_joint", joint_state_interface, position_joint_interface}; ICSControl arm1_control {arm1_builder, ics_driver, *ics_id_it++}; ICSControl::BuildDataType arm2_builder {"arm1_to_arm2_joint", joint_state_interface, position_joint_interface}; ICSControl arm2_control {arm2_builder, ics_driver, *ics_id_it++}; ICSControl::BuildDataType effector_base_builder {"arm2_to_effector_base_joint", joint_state_interface, position_joint_interface}; ICSControl effector_base_control {effector_base_builder, ics_driver, *ics_id_it++}; DammyPositionControl::BuildDataType effector_end_builder {"effector_base_to_effector_end_joint", joint_state_interface, position_joint_interface}; DammyPositionControl effector_end_control {effector_end_builder}; Arcsys2HW robot {&joint_state_interface}; robot.registerInterface(&position_joint_interface); robot.registerInterface(&velocity_joint_interface); robot.registerControl(&shaft_control); robot.registerControl(&arm0_control); robot.registerControl(&arm1_control); robot.registerControl(&arm2_control); robot.registerControl(&effector_base_control); robot.registerControl(&effector_end_control); controller_manager::ControllerManager cm {&robot}; ros::Rate rate(1.0 / robot.getPeriod().toSec()); ros::AsyncSpinner spinner {1}; spinner.start(); while(ros::ok()) { robot.read(); cm.update(robot.getTime(), robot.getPeriod()); robot.write(); rate.sleep(); } spinner.stop(); return 0; } inline ICSControl::ICSControl(BuildDataType& build_data, ics::ICS3& driver, const ics::ID& id) : data_ {build_data.joint_name_}, driver_(driver), // for ubuntu 14.04 id_ {id}, last_pos_ {0} { registerJoint(data_, build_data); } inline void ICSControl::fetch() { data_.pos_ = last_pos_; } inline void ICSControl::move() { last_pos_ = driver_.move(id_, ics::Angle::newRadian(data_.cmd_)) / 2 + last_pos_ / 2; } inline SimpleVelocityControl::SimpleVelocityControl(BuildDataType& build_data) : data_ {build_data.joint_name_}, last_pos_ {}, last_vel_ {}, nh_ {build_data.joint_name_}, pub_ {nh_.advertise<geometry_msgs::Twist>("cmd_vel", 1)}, sub_ {nh_.subscribe("odom", 1, &SimpleVelocityControl::odomCb, this)} { } inline void SimpleVelocityControl::fetch() { data_.pos_ = last_pos_; data_.vel_ = last_vel_; } inline void SimpleVelocityControl::move() { geometry_msgs::Twist msg {}; msg.linear.x = data_.cmd_; pub_.publish(std::move(msg)); } inline void SimpleVelocityControl::odomCb(const nav_msgs::OdometryConstPtr& odom) { last_pos_ = odom->pose.pose.position.x; last_vel_ = odom->twist.twist.linear.x; } template<class JntCmdIF> inline DammyControl<JntCmdIF>::DammyControl(BuildDataType& build_data) : data_ {build_data.joint_name_} { registerJoint(data_, build_data); } template<> inline void DammyPositionControl::fetch() { data_.pos_ = data_.cmd_; } template<> inline void DammyVelocityControl::fetch() { data_.pos_ += data_.cmd_ * 0.01; // FIXME: test code data_.vel_ = data_.cmd_; } template<class JntCmdIF> inline void DammyControl<JntCmdIF>::move() { } inline Arcsys2HW::Arcsys2HW(hardware_interface::JointStateInterface* jnt_stat) : controls {} { registerInterface(jnt_stat); } inline void Arcsys2HW::registerControl(JointControlInterface* jnt_cntr) { static auto inserter = controls.begin(); if (inserter == controls.cend()) throw std::out_of_range {"Too many JointControl"}; *inserter = jnt_cntr; ++inserter; } inline void Arcsys2HW::read() { for (auto control : controls) control->fetch(); } inline void Arcsys2HW::write() { for (auto control : controls) control->move(); } inline ros::Time Arcsys2HW::getTime() { return ros::Time::now(); } inline ros::Duration Arcsys2HW::getPeriod() { return ros::Duration {0.01}; } template<class JntCmdIF> inline void registerJoint( JointData& joint, hardware_interface::JointStateInterface& jnt_stat, JntCmdIF& jnt_cmd) { jnt_stat.registerHandle(hardware_interface::JointStateHandle {joint.name_, &joint.pos_, &joint.vel_, &joint.eff_}); jnt_cmd.registerHandle(hardware_interface::JointHandle {jnt_stat.getHandle(joint.name_), &joint.cmd_}); } template<class JntCmdIF> inline void registerJoint( JointData& joint, JointControlBuildData<JntCmdIF>& build_data) { registerJoint(joint, build_data.jnt_stat_, build_data.jnt_cmd_); } <|endoftext|>
<commit_before>// Copyright (c) 2014 Yandex LLC. All rights reserved. // Author: Vasily Chekalkin <bacek@yandex-team.ru> #include <phantom/io_benchmark/method_stream/source.H> #include <phantom/module.H> #include <pd/base/config.H> #include <pd/base/config_list.H> #include <pd/base/string.H> #include "spdy_transport.H" #include "spdy_framer.H" #include <ctype.h> namespace phantom { namespace io_benchmark { namespace method_stream { // Class to filter source data into SPDY request frames // Basically it can parse some HTTP requests and generate SPDY requests from // them. class spdy_source_filter_t : public source_t { public: // source_t implementation // Generate request. Returns false if source is exhausted virtual bool get_request(in_segment_t &request, in_segment_t &tag) const; virtual void do_init(); virtual void do_run() const; virtual void do_stat_print() const; virtual void do_fini(); public: typedef method_stream::source_t source_t; struct config_t { config_binding_type_ref(source_t); config::objptr_t<source_t> source; config::list_t<string_t> headers; // Amount of concurrent requests to send // Default 1. ssize_t burst; void check(in_t::ptr_t const &) const; }; spdy_source_filter_t(string_t const &name, config_t const &config); inline ~spdy_source_filter_t() {} private: source_t& source; ssize_t burst; // Storage for predefined headers. // All headers stored in continuous memory block, \0 terminated. string_t nv_data_seg; sarray1_t<const char*> nv; }; namespace { // Aggregate all headers into single chunk of \0 separated values string_t aggregator(const config::list_t<string_t> &headers) { string_t::ctor_t cons(1024); // Construct single buffer with all predefined headers. for (auto ptr = headers._ptr(); ptr; ++ptr) { cons(ptr.val()); cons('\0'); } return cons; } // Parse and aggregate headers into single storage // Parsed headers are handled in next way: // 1. Change to lower-case. // 2. Replace "Host" with ":host" // 3. Skip "Connection" // 4. Remember "Content-Length" to pass POST body (if any) string_t parse_headers(in_t::ptr_t& ptr, size_t& num_headers) { size_t limit = 4096; string_t::ctor_t storage_ctor(limit); num_headers = 0; while (true) { if (*ptr == '\r') ++ptr; in_t::ptr_t start = ++ptr; // skip '\r\n' on previous line // If it's empty line we have reached our destination if ((*ptr == '\n') || ((*ptr == '\r') && *(ptr + (size_t)1) == '\n')) break; if(!ptr.scan(":", 1, limit)) throw exception_log_t(log::error, "Can't parse header name"); in_segment_t header(start, ptr - start); MKCSTR(_header, header); log_debug("Found header '%s'", _header); in_t::ptr_t m = header; if (m.match<lower_t>(CSTR("host"))) { storage_ctor(CSTR(":host")); } else { for (char *p = _header; *p; ++p) { storage_ctor(tolower(*p)); } } storage_ctor('\0'); // Skip : ++ptr; // and spaces while (ptr.match<ident_t>(' ')) ; start = ptr; if(!ptr.scan("\r\n", 2, limit)) throw exception_log_t(log::error, "Can't parse header value"); MKCSTR(value, in_segment_t(start, ptr - start)); log_debug("Found value '%s'", value); storage_ctor(in_segment_t(start, ptr - start)); storage_ctor('\0'); num_headers++; } return storage_ctor; } } spdy_source_filter_t::spdy_source_filter_t(string_t const& name, config_t const& config) : source_t(name), source(*config.source), burst(config.burst ? config.burst : 1), nv_data_seg(aggregator(config.headers)), nv(config.headers, [&](const string_t& h) { static const char* d = nv_data_seg.ptr(); const char* ret = d; d += h.size() + 1; return ret; }) { } bool spdy_source_filter_t::get_request(in_segment_t& request, in_segment_t& tag) const { auto* framer = spdy_transport_t::current_framer(); // Wait for framer. if (!framer) { tag = STRING("*skip*"); return true; } // If it's fresh framer - start it. if (!framer->is_started()) { framer->start(); } // Submit N requests while (framer->in_flight_requests() < burst) { in_segment_t original_request; if (!source.get_request(original_request, tag)) { // Wait for already in flight requests to finish log_debug("SPDY: original source is exhausted (%ld)", framer->in_flight_requests()); if (framer->in_flight_requests()) return framer->send_data(request); else return false; } in_t::ptr_t ptr = original_request; // Meh. operator bool actually initialize ptr... if (!ptr) { log_error("Meh!"); return false; } // Parse generated request and produce SPDY request from it. // First line should be <method> <url> <version> in_t::ptr_t start = ptr; size_t limit = 4096; // Up to 4k URLs. // We should switch to be able to send DATA frames. But this will work // for now if(!ptr.scan(" ", 1, limit)) throw exception_log_t(log::error, "Can't parse METHOD"); MKCSTR(method, in_segment_t(start, ptr - start)); start = ++ptr; if(!ptr.scan(" ", 1, limit)) throw exception_log_t(log::error, "Can't parse URL"); MKCSTR(path, in_segment_t(start, ptr - start)); start = ++ptr; if(!ptr.scan("\r\n", 2, limit)) throw exception_log_t(log::error, "Can't parse VERSION"); MKCSTR(version, in_segment_t(start, ptr - start)); size_t num_headers; string_t headers_storage = parse_headers(ptr, num_headers); // Skip last \r\n if (*ptr == '\r') ++ptr; ++ptr; in_segment_t post_body(ptr, ptr.pending()); // 8 for "standard" headers // +1 for nullptr const char *nv_send[8 + num_headers * 2 + nv.size + 1]; nv_send[0] = ":method"; nv_send[1] = method; nv_send[2] = ":version"; nv_send[3] = version; nv_send[4] = ":path"; nv_send[5] = path; nv_send[6] = ":scheme"; nv_send[7] = "https"; // Copy configured headers const char ** nv_ptr = nv_send + 8; memcpy(nv_ptr, nv.items, nv.size * sizeof(nv.items[0])); nv_ptr += nv.size; // Propagate pointers into NV const char *data = headers_storage.ptr(); start = headers_storage; in_t::ptr_t tmp = start; while (tmp.scan("\0", 1, limit)) { *nv_ptr++ = data; data += tmp - start + 1; start = ++tmp; } *nv_ptr = nullptr; int rv = framer->submit_request(0, nv_send, post_body); if (rv != 0) return false; } return framer->send_data(request); } void spdy_source_filter_t::config_t::check(in_t::ptr_t const &ptr) const { if (!source) config::error(ptr, "Original 'source' is required for spdy_source_filter"); } void spdy_source_filter_t::do_init() { source.init(name); } void spdy_source_filter_t::do_run() const { source.run(name); } void spdy_source_filter_t::do_stat_print() const { source.stat_print(name); } void spdy_source_filter_t::do_fini() { source.fini(name); } }}} // namespace phantom::io_benchmark::method_stream namespace pd { namespace config { using phantom::io_benchmark::method_stream::spdy_source_filter_t; using phantom::io_benchmark::method_stream::source_t; config_binding_sname(spdy_source_filter_t); config_binding_value(spdy_source_filter_t, source); config_binding_value(spdy_source_filter_t, headers); config_binding_value(spdy_source_filter_t, burst); config_binding_cast(spdy_source_filter_t, source_t); config_binding_ctor(source_t, spdy_source_filter_t); }} <commit_msg>Enable uncoditional request generation.<commit_after>// Copyright (c) 2014 Yandex LLC. All rights reserved. // Author: Vasily Chekalkin <bacek@yandex-team.ru> #include <phantom/io_benchmark/method_stream/source.H> #include <phantom/module.H> #include <pd/base/config.H> #include <pd/base/config_list.H> #include <pd/base/string.H> #include "spdy_transport.H" #include "spdy_framer.H" #include <ctype.h> #include "spdy_misc.H" namespace phantom { namespace io_benchmark { namespace method_stream { // Class to filter source data into SPDY request frames // Basically it can parse some HTTP requests and generate SPDY requests from // them. class spdy_source_filter_t : public source_t { public: // source_t implementation // Generate request. Returns false if source is exhausted virtual bool get_request(in_segment_t &request, in_segment_t &tag) const; virtual void do_init(); virtual void do_run() const; virtual void do_stat_print() const; virtual void do_fini(); public: typedef method_stream::source_t source_t; struct config_t { config_binding_type_ref(source_t); config::objptr_t<source_t> source; config::list_t<string_t> headers; // Amount of concurrent requests to send // Default 1. ssize_t burst; void check(in_t::ptr_t const &) const; }; spdy_source_filter_t(string_t const &name, config_t const &config); inline ~spdy_source_filter_t() {} private: bool generate_request(in_segment_t &request, in_segment_t &tag) const; source_t& source; ssize_t burst; // Storage for predefined headers. // All headers stored in continuous memory block, \0 terminated. string_t nv_data_seg; sarray1_t<const char*> nv; }; namespace { // Aggregate all headers into single chunk of \0 separated values string_t aggregator(const config::list_t<string_t> &headers) { string_t::ctor_t cons(1024); // Construct single buffer with all predefined headers. for (auto ptr = headers._ptr(); ptr; ++ptr) { cons(ptr.val()); cons('\0'); } return cons; } // Parse and aggregate headers into single storage // Parsed headers are handled in next way: // 1. Change to lower-case. // 2. Replace "Host" with ":host" // 3. Skip "Connection" // 4. Remember "Content-Length" to pass POST body (if any) string_t parse_headers(in_t::ptr_t& ptr, size_t& num_headers) { size_t limit = 4096; string_t::ctor_t storage_ctor(limit); num_headers = 0; while (true) { if (*ptr == '\r') ++ptr; in_t::ptr_t start = ++ptr; // skip '\r\n' on previous line // If it's empty line we have reached our destination if ((*ptr == '\n') || ((*ptr == '\r') && *(ptr + (size_t)1) == '\n')) break; if(!ptr.scan(":", 1, limit)) throw exception_log_t(log::error, "Can't parse header name"); in_segment_t header(start, ptr - start); MKCSTR(_header, header); log_debug("Found header '%s'", _header); in_t::ptr_t m = header; if (m.match<lower_t>(CSTR("host"))) { storage_ctor(CSTR(":host")); } else { for (char *p = _header; *p; ++p) { storage_ctor(tolower(*p)); } } storage_ctor('\0'); // Skip : ++ptr; // and spaces while (ptr.match<ident_t>(' ')) ; start = ptr; if(!ptr.scan("\r\n", 2, limit)) throw exception_log_t(log::error, "Can't parse header value"); MKCSTR(value, in_segment_t(start, ptr - start)); log_debug("Found value '%s'", value); storage_ctor(in_segment_t(start, ptr - start)); storage_ctor('\0'); num_headers++; } return storage_ctor; } } spdy_source_filter_t::spdy_source_filter_t(string_t const& name, config_t const& config) : source_t(name), source(*config.source), burst(config.burst ? config.burst : 1), nv_data_seg(aggregator(config.headers)), nv(config.headers, [&](const string_t& h) { static const char* d = nv_data_seg.ptr(); const char* ret = d; d += h.size() + 1; return ret; }) { } bool spdy_source_filter_t::get_request(in_segment_t& request, in_segment_t& tag) const { auto* framer = spdy_transport_t::current_framer(); // Wait for framer. if (!framer) { //tag = STRING("*skip*"); return true; } // If it's fresh framer - start it. if (!framer->is_started()) { framer->start(); } // Submit N requests if (burst) { while (framer->in_flight_requests() < burst) { if (!generate_request(request, tag)) return false; } } else { if (!generate_request(request, tag)) return false; } return framer->send_data(request); } bool spdy_source_filter_t::generate_request(in_segment_t &request, in_segment_t &tag) const { auto* framer = spdy_transport_t::current_framer(); assert(framer); in_segment_t original_request; if (!source.get_request(original_request, tag)) { // Wait for already in flight requests to finish log_debug("SPDY: original source is exhausted (%ld)", framer->in_flight_requests()); if (framer->in_flight_requests()) return framer->send_data(request); else return false; } in_t::ptr_t ptr = original_request; // Meh. operator bool actually initialize ptr... if (!ptr) { log_error("Meh!"); return false; } // Parse generated request and produce SPDY request from it. // First line should be <method> <url> <version> in_t::ptr_t start = ptr; size_t limit = 4096; // Up to 4k URLs. // We should switch to be able to send DATA frames. But this will work // for now if(!ptr.scan(" ", 1, limit)) throw exception_log_t(log::error, "Can't parse METHOD"); MKCSTR(method, in_segment_t(start, ptr - start)); start = ++ptr; if(!ptr.scan(" ", 1, limit)) throw exception_log_t(log::error, "Can't parse URL"); MKCSTR(path, in_segment_t(start, ptr - start)); start = ++ptr; if(!ptr.scan("\r\n", 2, limit)) throw exception_log_t(log::error, "Can't parse VERSION"); MKCSTR(version, in_segment_t(start, ptr - start)); size_t num_headers; string_t headers_storage = parse_headers(ptr, num_headers); // Skip last \r\n if (*ptr == '\r') ++ptr; ++ptr; in_segment_t post_body(ptr, ptr.pending()); // 8 for "standard" headers // +1 for nullptr const char *nv_send[8 + num_headers * 2 + nv.size + 1]; nv_send[0] = ":method"; nv_send[1] = method; nv_send[2] = ":version"; nv_send[3] = version; nv_send[4] = ":path"; nv_send[5] = path; nv_send[6] = ":scheme"; nv_send[7] = "https"; // Copy configured headers const char ** nv_ptr = nv_send + 8; memcpy(nv_ptr, nv.items, nv.size * sizeof(nv.items[0])); nv_ptr += nv.size; // Propagate pointers into NV const char *data = headers_storage.ptr(); start = headers_storage; in_t::ptr_t tmp = start; while (tmp.scan("\0", 1, limit)) { *nv_ptr++ = data; data += tmp - start + 1; start = ++tmp; } *nv_ptr = nullptr; int rv = framer->submit_request(0, nv_send, post_body); if (rv != 0) return false; return true; } void spdy_source_filter_t::config_t::check(in_t::ptr_t const &ptr) const { if (!source) config::error(ptr, "Original 'source' is required for spdy_source_filter"); } void spdy_source_filter_t::do_init() { source.init(name); } void spdy_source_filter_t::do_run() const { source.run(name); } void spdy_source_filter_t::do_stat_print() const { source.stat_print(name); } void spdy_source_filter_t::do_fini() { source.fini(name); } }}} // namespace phantom::io_benchmark::method_stream namespace pd { namespace config { using phantom::io_benchmark::method_stream::spdy_source_filter_t; using phantom::io_benchmark::method_stream::source_t; config_binding_sname(spdy_source_filter_t); config_binding_value(spdy_source_filter_t, source); config_binding_value(spdy_source_filter_t, headers); config_binding_value(spdy_source_filter_t, burst); config_binding_cast(spdy_source_filter_t, source_t); config_binding_ctor(source_t, spdy_source_filter_t); }} <|endoftext|>
<commit_before>#include <algorithm> #include <istream> #include <sstream> #include "parsers/parse_error.hh" #include "parsers/tina.hh" #include "pn/arc.hh" namespace pnmc { namespace parsers { /*------------------------------------------------------------------------------------------------*/ /*------------------------------------------------------------------------------------------------*/ std::pair<std::string, unsigned int> place_valuation(const std::string& s) { const auto star_cit = std::find(s.cbegin(), s.cend(), '*'); if (star_cit == s.cend()) { return std::make_pair(s, 1); } try { const auto valuation = std::stoi(std::string(star_cit + 1, s.cend())); return std::make_pair(std::string(s.cbegin(), star_cit), valuation); } catch (const std::invalid_argument&) { throw parse_error("Valuation '" + std::string(star_cit + 1, s.cend()) + "' is not a value"); } } /*------------------------------------------------------------------------------------------------*/ unsigned int marking(const std::string& s) { if (*s.cbegin() == '(' and *std::prev(s.cend()) == ')') { try { return std::stoi(std::string(std::next(s.cbegin()), std::prev(s.cend()))); } catch (const std::invalid_argument&) { throw parse_error( "Marking '" + std::string(std::next(s.cbegin()), std::prev(s.cend())) + "' is not a value"); } } else { throw parse_error("Invalid marking format: " + s); } } /*------------------------------------------------------------------------------------------------*/ std::shared_ptr<pn::net> tina(std::istream& in) { std::shared_ptr<pn::net> net_ptr = std::make_shared<pn::net>(); auto& net = *net_ptr; try { std::string line, s0, s1, s2; line.reserve(1024); while (std::getline(in, line)) { std::istringstream ss(line); // Empty line or comment. if (((ss >> std::ws).peek() == '#') or not (ss >> s0)) { continue; } // Net if (s0 == "net") { continue; } // Transitions else if (s0 == "tr") { std::string place_id; unsigned int valuation; if (ss >> s0) { net.add_transition(s0, ""); } else { throw parse_error("Invalid transition: " + line); } // Skip time interval, if any. const auto c = (ss >> std::ws).peek(); if (c == '[' or c == ']') { ss >> s1; } bool found_arrow = false; while (ss >> s1) { if (s1 == "->") { found_arrow = true; break; } std::tie(place_id, valuation) = place_valuation(s1); net.add_pre_place(s0, place_id, pn::arc(valuation)); } if (not found_arrow) { throw parse_error("Invalid transition (missing '->'): " + line); } while (ss >> s1) { std::tie(place_id, valuation) = place_valuation(s1); net.add_post_place(s0, place_id, pn::arc(valuation)); } } // Places else if (s0 == "pl") { if (ss >> s1 >> s2) { net.add_place(s1, "", marking(s2)); } else { throw parse_error("Invalid place: " + line); } } // Error. else { throw parse_error("Invalid line: " + line); } } } catch (const parse_error& p) { std::cerr << p.what() << std::endl; return nullptr; } return net_ptr; } /*------------------------------------------------------------------------------------------------*/ }} // namespace pnmc::parsers <commit_msg>Result of peek() is not a char, but an int_type.<commit_after>#include <algorithm> #include <istream> #include <sstream> #include "parsers/parse_error.hh" #include "parsers/tina.hh" #include "pn/arc.hh" namespace pnmc { namespace parsers { /*------------------------------------------------------------------------------------------------*/ /*------------------------------------------------------------------------------------------------*/ std::pair<std::string, unsigned int> place_valuation(const std::string& s) { const auto star_cit = std::find(s.cbegin(), s.cend(), '*'); if (star_cit == s.cend()) { return std::make_pair(s, 1); } try { const auto valuation = std::stoi(std::string(star_cit + 1, s.cend())); return std::make_pair(std::string(s.cbegin(), star_cit), valuation); } catch (const std::invalid_argument&) { throw parse_error("Valuation '" + std::string(star_cit + 1, s.cend()) + "' is not a value"); } } /*------------------------------------------------------------------------------------------------*/ unsigned int marking(const std::string& s) { if (*s.cbegin() == '(' and *std::prev(s.cend()) == ')') { try { return std::stoi(std::string(std::next(s.cbegin()), std::prev(s.cend()))); } catch (const std::invalid_argument&) { throw parse_error( "Marking '" + std::string(std::next(s.cbegin()), std::prev(s.cend())) + "' is not a value"); } } else { throw parse_error("Invalid marking format: " + s); } } /*------------------------------------------------------------------------------------------------*/ std::shared_ptr<pn::net> tina(std::istream& in) { std::shared_ptr<pn::net> net_ptr = std::make_shared<pn::net>(); auto& net = *net_ptr; try { std::string line, s0, s1, s2; line.reserve(1024); while (std::getline(in, line)) { std::istringstream ss(line); // Empty line or comment. if (((ss >> std::ws).peek() == std::char_traits<char>::to_int_type('#')) or not (ss >> s0)) { continue; } // Net if (s0 == "net") { continue; } // Transitions else if (s0 == "tr") { std::string place_id; unsigned int valuation; if (ss >> s0) { net.add_transition(s0, ""); } else { throw parse_error("Invalid transition: " + line); } // Skip time interval, if any. const auto c = (ss >> std::ws).peek(); if (c == '[' or c == ']') { ss >> s1; } bool found_arrow = false; while (ss >> s1) { if (s1 == "->") { found_arrow = true; break; } std::tie(place_id, valuation) = place_valuation(s1); net.add_pre_place(s0, place_id, pn::arc(valuation)); } if (not found_arrow) { throw parse_error("Invalid transition (missing '->'): " + line); } while (ss >> s1) { std::tie(place_id, valuation) = place_valuation(s1); net.add_post_place(s0, place_id, pn::arc(valuation)); } } // Places else if (s0 == "pl") { if (ss >> s1 >> s2) { net.add_place(s1, "", marking(s2)); } else { throw parse_error("Invalid place: " + line); } } // Error. else { throw parse_error("Invalid line: " + line); } } } catch (const parse_error& p) { std::cerr << p.what() << std::endl; return nullptr; } return net_ptr; } /*------------------------------------------------------------------------------------------------*/ }} // namespace pnmc::parsers <|endoftext|>
<commit_before>#include "EventWatcher.hpp" #include "RemapUtil.hpp" #include "IOLockWrapper.hpp" namespace org_pqrs_KeyRemap4MacBook { EventWatcher::Item EventWatcher::item_[MAXNUM]; IOLock* EventWatcher::lock_; int EventWatcher::count_; void EventWatcher::initialize(void) { lock_ = IOLockWrapper::alloc(); reset(); } void EventWatcher::terminate(void) { IOLockWrapper::free(lock_); } void EventWatcher::reset(void) { IOLockWrapper::ScopedLock lk(lock_); for (int i = 0; i < MAXNUM; ++i) { item_[i].flag = NULL; } } void EventWatcher::on(void) { IOLockWrapper::ScopedLock lk(lock_); for (int i = 0; i < MAXNUM; ++i) { if (item_[i].flag && item_[i].count != count_) { *(item_[i].flag) = true; item_[i].flag = NULL; } } } void EventWatcher::set(bool& b) { IOLockWrapper::ScopedLock lk(lock_); b = false; for (int i = 0; i < MAXNUM; ++i) { if (item_[i].flag == NULL) { item_[i].flag = &b; item_[i].count = count_; } } } void EventWatcher::unset(bool& b) { IOLockWrapper::ScopedLock lk(lock_); for (int i = 0; i < MAXNUM; ++i) { if (item_[i].flag == &b) { item_[i].flag = NULL; } } } void EventWatcher::countup(void) { IOLockWrapper::ScopedLock lk(lock_); ++count_; } } <commit_msg>fix EventWatcher @ kext<commit_after>#include "EventWatcher.hpp" #include "RemapUtil.hpp" #include "IOLockWrapper.hpp" namespace org_pqrs_KeyRemap4MacBook { EventWatcher::Item EventWatcher::item_[MAXNUM]; IOLock* EventWatcher::lock_; int EventWatcher::count_; void EventWatcher::initialize(void) { lock_ = IOLockWrapper::alloc(); reset(); } void EventWatcher::terminate(void) { IOLockWrapper::free(lock_); } void EventWatcher::reset(void) { IOLockWrapper::ScopedLock lk(lock_); for (int i = 0; i < MAXNUM; ++i) { item_[i].flag = NULL; } } void EventWatcher::on(void) { IOLockWrapper::ScopedLock lk(lock_); for (int i = 0; i < MAXNUM; ++i) { if (item_[i].flag && item_[i].count != count_) { *(item_[i].flag) = true; item_[i].flag = NULL; } } } void EventWatcher::set(bool& b) { IOLockWrapper::ScopedLock lk(lock_); b = false; for (int i = 0; i < MAXNUM; ++i) { if (item_[i].flag == NULL) { item_[i].flag = &b; item_[i].count = count_; return; } } } void EventWatcher::unset(bool& b) { IOLockWrapper::ScopedLock lk(lock_); for (int i = 0; i < MAXNUM; ++i) { if (item_[i].flag == &b) { item_[i].flag = NULL; } } } void EventWatcher::countup(void) { IOLockWrapper::ScopedLock lk(lock_); ++count_; } } <|endoftext|>
<commit_before>#include <array> #include <stdexcept> #include <string> #include <utility> #include <vector> #include <ros/ros.h> #include <controller_manager/controller_manager.h> #include <geometry_msgs/Twist.h> #include <hardware_interface/joint_command_interface.h> #include <hardware_interface/joint_state_interface.h> #include <hardware_interface/robot_hw.h> #include <nav_msgs/Odometry.h> #include <ics3/ics> struct JointData { std::string name_; double cmd_; double pos_; double vel_; double eff_; }; template<class JntCmdIF> struct JointControlBuildData { std::string joint_name_; hardware_interface::JointStateInterface& jnt_stat_; JntCmdIF& jnt_cmd_; }; class JointControlInterface { public: virtual void fetch() = 0; virtual void move() = 0; virtual ~JointControlInterface() noexcept {} }; class ICSControl : public JointControlInterface { public: using JntCmdType = hardware_interface::PositionJointInterface; using BuildDataType = JointControlBuildData<JntCmdType>; ICSControl(BuildDataType&, ics::ICS3&, const ics::ID&); void fetch() override; void move() override; private: JointData data_; ics::ICS3& driver_; ics::ID id_; }; class DCMotorControl : public JointControlInterface { public: using JntCmdType = hardware_interface::VelocityJointInterface; using BuildDataType = JointControlBuildData<JntCmdType>; DCMotorControl(BuildDataType&); void fetch() override; void move() override; void odomCb(const nav_msgs::OdometryConstPtr&); private: JointData data_; double last_pos_; double last_vel_; ros::NodeHandle nh_; ros::Publisher pub_; ros::Subscriber sub_; }; template<class JntCmdIF> class DammyControl : public JointControlInterface { public: using JntCmdType = JntCmdIF; using BuildDataType = JointControlBuildData<JntCmdType>; DammyControl(BuildDataType&); void fetch() override; void move() override; private: JointData data_; }; using DammyPositionControl = DammyControl<hardware_interface::PositionJointInterface>; using DammyVelocityControl = DammyControl<hardware_interface::VelocityJointInterface>; class Arcsys2HW : public hardware_interface::RobotHW { public: static constexpr std::size_t JOINT_COUNT {6}; using JointControlContainer = std::array<JointControlInterface*, JOINT_COUNT>; Arcsys2HW(hardware_interface::JointStateInterface*); void registerControl(JointControlInterface*); void read(); void write(); ros::Time getTime(); ros::Duration getPeriod(); private: JointControlContainer controls; }; template<class JntCmdIF> void registerJoint( JointData&, hardware_interface::JointStateInterface&, JntCmdIF&); template<class JntCmdIF> void registerJoint( JointData&, JointControlBuildData<JntCmdIF>&); int main(int argc, char *argv[]) { ros::init(argc, argv, "arcsys2_control_node"); ros::NodeHandle pnh {"~"}; std::string ics_device_path {"/dev/ttyUSB0"}; pnh.param<std::string>("ics_device_path", ics_device_path, ics_device_path); ics::ICS3 ics_driver {std::move(ics_device_path)}; std::vector<int> ics_id_vec {}; pnh.getParam("ics_id_vec", ics_id_vec); if (ics_id_vec.empty()) throw std::invalid_argument {"ics_id_vec parameter is not found"}; std::vector<ics::ID> ics_ids(ics_id_vec.cbegin(), ics_id_vec.cend()); hardware_interface::JointStateInterface joint_state_interface {}; hardware_interface::PositionJointInterface position_joint_interface {}; hardware_interface::VelocityJointInterface velocity_joint_interface {}; DCMotorControl::BuildDataType shaft_builder {"rail_to_shaft_joint", joint_state_interface, velocity_joint_interface}; DCMotorControl shaft_control {shaft_builder}; DCMotorControl::BuildDataType arm0_builder {"shaft_to_arm0_joint", joint_state_interface, velocity_joint_interface}; DCMotorControl arm0_control {arm0_builder}; auto ics_id_it = ics_ids.cbegin(); ICSControl::BuildDataType arm1_builder {"arm0_to_arm1_joint", joint_state_interface, position_joint_interface}; ICSControl arm1_control {arm1_builder, ics_driver, *ics_id_it++}; ICSControl::BuildDataType arm2_builder {"arm1_to_arm2_joint", joint_state_interface, position_joint_interface}; ICSControl arm2_control {arm2_builder, ics_driver, *ics_id_it++}; ICSControl::BuildDataType effector_base_builder {"arm2_to_effector_base_joint", joint_state_interface, position_joint_interface}; ICSControl effector_base_control {effector_base_builder, ics_driver, *ics_id_it++}; DammyPositionControl::BuildDataType effector_end_builder {"effector_base_to_effector_end_joint", joint_state_interface, position_joint_interface}; DammyPositionControl effector_end_control {effector_end_builder}; Arcsys2HW robot {&joint_state_interface}; robot.registerInterface(&position_joint_interface); robot.registerInterface(&velocity_joint_interface); robot.registerControl(&shaft_control); robot.registerControl(&arm0_control); robot.registerControl(&arm1_control); robot.registerControl(&arm2_control); robot.registerControl(&effector_base_control); robot.registerControl(&effector_end_control); controller_manager::ControllerManager cm {&robot}; ros::Rate rate(1.0 / robot.getPeriod().toSec()); ros::AsyncSpinner spinner {1}; spinner.start(); while(ros::ok()) { robot.read(); cm.update(robot.getTime(), robot.getPeriod()); robot.write(); rate.sleep(); } spinner.stop(); return 0; } inline ICSControl::ICSControl(BuildDataType& build_data, ics::ICS3& driver, const ics::ID& id) : data_ {build_data.joint_name_}, driver_ {driver}, id_ {id} { registerJoint(data_, build_data); } inline void ICSControl::fetch() { } inline void ICSControl::move() { data_.pos_ = driver_.move(id_, ics::Angle::newRadian(data_.cmd_)); } inline DCMotorControl::DCMotorControl(BuildDataType& build_data) : data_ {build_data.joint_name_}, last_pos_ {}, last_vel_ {}, nh_ {build_data.joint_name_}, pub_ {nh_.advertise<geometry_msgs::Twist>("cmd_vel", 1)}, sub_ {nh_.subscribe("odom", 1, &DCMotorControl::odomCb, this)} { } inline void DCMotorControl::fetch() { data_.pos_ = last_pos_; data_.vel_ = last_vel_; } inline void DCMotorControl::move() { geometry_msgs::Twist msg {}; msg.linear.x = data_.cmd_; pub_.publish(std::move(msg)); } inline void DCMotorControl::odomCb(const nav_msgs::OdometryConstPtr& odom) { last_pos_ = odom->pose.pose.position.x; last_vel_ = odom->twist.twist.linear.x; } template<class JntCmdIF> inline DammyControl<JntCmdIF>::DammyControl(BuildDataType& build_data) : data_ {build_data.joint_name_} { registerJoint(data_, build_data); } template<> inline void DammyPositionControl::fetch() { data_.pos_ = data_.cmd_; } template<> inline void DammyVelocityControl::fetch() { data_.pos_ += data_.cmd_ * 0.01; // FIXME: test code data_.vel_ = data_.cmd_; } template<class JntCmdIF> inline void DammyControl<JntCmdIF>::move() { } inline Arcsys2HW::Arcsys2HW(hardware_interface::JointStateInterface* jnt_stat) : controls {} { registerInterface(jnt_stat); } inline void Arcsys2HW::registerControl(JointControlInterface* jnt_cntr) { static auto inserter = controls.begin(); if (inserter == controls.cend()) throw std::out_of_range {"Too many JointControl"}; *inserter = jnt_cntr; ++inserter; } inline void Arcsys2HW::read() { for (auto control : controls) control->fetch(); } inline void Arcsys2HW::write() { for (auto control : controls) control->move(); } inline ros::Time Arcsys2HW::getTime() { return ros::Time::now(); } inline ros::Duration Arcsys2HW::getPeriod() { return ros::Duration {0.01}; } template<class JntCmdIF> inline void registerJoint( JointData& joint, hardware_interface::JointStateInterface& jnt_stat, JntCmdIF& jnt_cmd) { jnt_stat.registerHandle(hardware_interface::JointStateHandle {joint.name_, &joint.pos_, &joint.vel_, &joint.eff_}); jnt_cmd.registerHandle(hardware_interface::JointHandle {jnt_stat.getHandle(joint.name_), &joint.cmd_}); } template<class JntCmdIF> inline void registerJoint( JointData& joint, JointControlBuildData<JntCmdIF>& build_data) { registerJoint(joint, build_data.jnt_stat_, build_data.jnt_cmd_); } <commit_msg>Update ICSControl for fetch timing<commit_after>#include <array> #include <stdexcept> #include <string> #include <utility> #include <vector> #include <ros/ros.h> #include <controller_manager/controller_manager.h> #include <geometry_msgs/Twist.h> #include <hardware_interface/joint_command_interface.h> #include <hardware_interface/joint_state_interface.h> #include <hardware_interface/robot_hw.h> #include <nav_msgs/Odometry.h> #include <ics3/ics> struct JointData { std::string name_; double cmd_; double pos_; double vel_; double eff_; }; template<class JntCmdIF> struct JointControlBuildData { std::string joint_name_; hardware_interface::JointStateInterface& jnt_stat_; JntCmdIF& jnt_cmd_; }; class JointControlInterface { public: virtual void fetch() = 0; virtual void move() = 0; virtual ~JointControlInterface() noexcept {} }; class ICSControl : public JointControlInterface { public: using JntCmdType = hardware_interface::PositionJointInterface; using BuildDataType = JointControlBuildData<JntCmdType>; ICSControl(BuildDataType&, ics::ICS3&, const ics::ID&); void fetch() override; void move() override; private: JointData data_; ics::ICS3& driver_; ics::ID id_; }; class DCMotorControl : public JointControlInterface { public: using JntCmdType = hardware_interface::VelocityJointInterface; using BuildDataType = JointControlBuildData<JntCmdType>; DCMotorControl(BuildDataType&); void fetch() override; void move() override; void odomCb(const nav_msgs::OdometryConstPtr&); private: JointData data_; double last_pos_; double last_vel_; ros::NodeHandle nh_; ros::Publisher pub_; ros::Subscriber sub_; }; template<class JntCmdIF> class DammyControl : public JointControlInterface { public: using JntCmdType = JntCmdIF; using BuildDataType = JointControlBuildData<JntCmdType>; DammyControl(BuildDataType&); void fetch() override; void move() override; private: JointData data_; }; using DammyPositionControl = DammyControl<hardware_interface::PositionJointInterface>; using DammyVelocityControl = DammyControl<hardware_interface::VelocityJointInterface>; class Arcsys2HW : public hardware_interface::RobotHW { public: static constexpr std::size_t JOINT_COUNT {6}; using JointControlContainer = std::array<JointControlInterface*, JOINT_COUNT>; Arcsys2HW(hardware_interface::JointStateInterface*); void registerControl(JointControlInterface*); void read(); void write(); ros::Time getTime(); ros::Duration getPeriod(); private: JointControlContainer controls; }; template<class JntCmdIF> void registerJoint( JointData&, hardware_interface::JointStateInterface&, JntCmdIF&); template<class JntCmdIF> void registerJoint( JointData&, JointControlBuildData<JntCmdIF>&); int main(int argc, char *argv[]) { ros::init(argc, argv, "arcsys2_control_node"); ros::NodeHandle pnh {"~"}; std::string ics_device_path {"/dev/ttyUSB0"}; pnh.param<std::string>("ics_device_path", ics_device_path, ics_device_path); ics::ICS3 ics_driver {std::move(ics_device_path)}; std::vector<int> ics_id_vec {}; pnh.getParam("ics_id_vec", ics_id_vec); if (ics_id_vec.empty()) throw std::invalid_argument {"ics_id_vec parameter is not found"}; std::vector<ics::ID> ics_ids(ics_id_vec.cbegin(), ics_id_vec.cend()); hardware_interface::JointStateInterface joint_state_interface {}; hardware_interface::PositionJointInterface position_joint_interface {}; hardware_interface::VelocityJointInterface velocity_joint_interface {}; DCMotorControl::BuildDataType shaft_builder {"rail_to_shaft_joint", joint_state_interface, velocity_joint_interface}; DCMotorControl shaft_control {shaft_builder}; DCMotorControl::BuildDataType arm0_builder {"shaft_to_arm0_joint", joint_state_interface, velocity_joint_interface}; DCMotorControl arm0_control {arm0_builder}; auto ics_id_it = ics_ids.cbegin(); ICSControl::BuildDataType arm1_builder {"arm0_to_arm1_joint", joint_state_interface, position_joint_interface}; ICSControl arm1_control {arm1_builder, ics_driver, *ics_id_it++}; ICSControl::BuildDataType arm2_builder {"arm1_to_arm2_joint", joint_state_interface, position_joint_interface}; ICSControl arm2_control {arm2_builder, ics_driver, *ics_id_it++}; ICSControl::BuildDataType effector_base_builder {"arm2_to_effector_base_joint", joint_state_interface, position_joint_interface}; ICSControl effector_base_control {effector_base_builder, ics_driver, *ics_id_it++}; DammyPositionControl::BuildDataType effector_end_builder {"effector_base_to_effector_end_joint", joint_state_interface, position_joint_interface}; DammyPositionControl effector_end_control {effector_end_builder}; Arcsys2HW robot {&joint_state_interface}; robot.registerInterface(&position_joint_interface); robot.registerInterface(&velocity_joint_interface); robot.registerControl(&shaft_control); robot.registerControl(&arm0_control); robot.registerControl(&arm1_control); robot.registerControl(&arm2_control); robot.registerControl(&effector_base_control); robot.registerControl(&effector_end_control); controller_manager::ControllerManager cm {&robot}; ros::Rate rate(1.0 / robot.getPeriod().toSec()); ros::AsyncSpinner spinner {1}; spinner.start(); while(ros::ok()) { robot.read(); cm.update(robot.getTime(), robot.getPeriod()); robot.write(); rate.sleep(); } spinner.stop(); return 0; } inline ICSControl::ICSControl(BuildDataType& build_data, ics::ICS3& driver, const ics::ID& id) : data_ {build_data.joint_name_}, driver_ {driver}, id_ {id} { registerJoint(data_, build_data); } inline void ICSControl::fetch() { data_.pos_ = driver_.move(id_, ics::Angle::newRadian(data_.cmd_)); } inline void ICSControl::move() { driver_.move(id_, ics::Angle::newRadian(data_.cmd_)); } inline DCMotorControl::DCMotorControl(BuildDataType& build_data) : data_ {build_data.joint_name_}, last_pos_ {}, last_vel_ {}, nh_ {build_data.joint_name_}, pub_ {nh_.advertise<geometry_msgs::Twist>("cmd_vel", 1)}, sub_ {nh_.subscribe("odom", 1, &DCMotorControl::odomCb, this)} { } inline void DCMotorControl::fetch() { data_.pos_ = last_pos_; data_.vel_ = last_vel_; } inline void DCMotorControl::move() { geometry_msgs::Twist msg {}; msg.linear.x = data_.cmd_; pub_.publish(std::move(msg)); } inline void DCMotorControl::odomCb(const nav_msgs::OdometryConstPtr& odom) { last_pos_ = odom->pose.pose.position.x; last_vel_ = odom->twist.twist.linear.x; } template<class JntCmdIF> inline DammyControl<JntCmdIF>::DammyControl(BuildDataType& build_data) : data_ {build_data.joint_name_} { registerJoint(data_, build_data); } template<> inline void DammyPositionControl::fetch() { data_.pos_ = data_.cmd_; } template<> inline void DammyVelocityControl::fetch() { data_.pos_ += data_.cmd_ * 0.01; // FIXME: test code data_.vel_ = data_.cmd_; } template<class JntCmdIF> inline void DammyControl<JntCmdIF>::move() { } inline Arcsys2HW::Arcsys2HW(hardware_interface::JointStateInterface* jnt_stat) : controls {} { registerInterface(jnt_stat); } inline void Arcsys2HW::registerControl(JointControlInterface* jnt_cntr) { static auto inserter = controls.begin(); if (inserter == controls.cend()) throw std::out_of_range {"Too many JointControl"}; *inserter = jnt_cntr; ++inserter; } inline void Arcsys2HW::read() { for (auto control : controls) control->fetch(); } inline void Arcsys2HW::write() { for (auto control : controls) control->move(); } inline ros::Time Arcsys2HW::getTime() { return ros::Time::now(); } inline ros::Duration Arcsys2HW::getPeriod() { return ros::Duration {0.01}; } template<class JntCmdIF> inline void registerJoint( JointData& joint, hardware_interface::JointStateInterface& jnt_stat, JntCmdIF& jnt_cmd) { jnt_stat.registerHandle(hardware_interface::JointStateHandle {joint.name_, &joint.pos_, &joint.vel_, &joint.eff_}); jnt_cmd.registerHandle(hardware_interface::JointHandle {jnt_stat.getHandle(joint.name_), &joint.cmd_}); } template<class JntCmdIF> inline void registerJoint( JointData& joint, JointControlBuildData<JntCmdIF>& build_data) { registerJoint(joint, build_data.jnt_stat_, build_data.jnt_cmd_); } <|endoftext|>
<commit_before>/************************************************* * PBE Retrieval Source File * * (C) 1999-2007 Jack Lloyd * *************************************************/ #include <botan/get_pbe.h> #include <botan/oids.h> #include <botan/parsing.h> #if defined(BOTAN_HAS_PBE_PKCS_V15) #include <botan/pbes1.h> #endif #if defined(BOTAN_HAS_PBE_PKCS_V20) #include <botan/pbes2.h> #endif namespace Botan { /************************************************* * Get an encryption PBE, set new parameters * *************************************************/ PBE* get_pbe(const std::string& pbe_name) { std::vector<std::string> algo_name; algo_name = parse_algorithm_name(pbe_name); if(algo_name.size() != 3) throw Invalid_Algorithm_Name(pbe_name); const std::string pbe = algo_name[0]; const std::string digest = algo_name[1]; const std::string cipher = algo_name[2]; #if defined(BOTAN_HAS_PBE_PKCS_V15) if(pbe == "PBE-PKCS5v15") return new PBE_PKCS5v15(digest, cipher, ENCRYPTION); #endif #if defined(BOTAN_HAS_PBE_PKCS_V20) if(pbe == "PBE-PKCS5v20") return new PBE_PKCS5v20(digest, cipher); #endif throw Algorithm_Not_Found(pbe_name); } /************************************************* * Get a decryption PBE, decode parameters * *************************************************/ PBE* get_pbe(const OID& pbe_oid, DataSource& params) { std::vector<std::string> algo_name; algo_name = parse_algorithm_name(OIDS::lookup(pbe_oid)); if(algo_name.size() < 1) throw Invalid_Algorithm_Name(pbe_oid.as_string()); const std::string pbe_algo = algo_name[0]; #if defined(BOTAN_HAS_PBE_PKCS_V15) if(pbe_algo == "PBE-PKCS5v15") { if(algo_name.size() != 3) throw Invalid_Algorithm_Name(pbe_oid.as_string()); const std::string digest = algo_name[1]; const std::string cipher = algo_name[2]; PBE* pbe = new PBE_PKCS5v15(digest, cipher, DECRYPTION); pbe->decode_params(params); return pbe; } #endif #if defined(BOTAN_HAS_PBE_PKCS_V20) if(pbe_algo == "PBE-PKCS5v20") return new PBE_PKCS5v20(params); #endif throw Algorithm_Not_Found(pbe_oid.as_string()); } } <commit_msg>Modify get_pbe to use SCAN_Name<commit_after>/************************************************* * PBE Retrieval Source File * * (C) 1999-2007 Jack Lloyd * *************************************************/ #include <botan/get_pbe.h> #include <botan/oids.h> #include <botan/scan_name.h> #if defined(BOTAN_HAS_PBE_PKCS_V15) #include <botan/pbes1.h> #endif #if defined(BOTAN_HAS_PBE_PKCS_V20) #include <botan/pbes2.h> #endif namespace Botan { /************************************************* * Get an encryption PBE, set new parameters * *************************************************/ PBE* get_pbe(const std::string& pbe_name) { SCAN_Name request(pbe_name); if(request.arg_count() != 2) throw Invalid_Algorithm_Name(pbe_name); const std::string pbe = request.algo_name(); const std::string digest = request.argument(0); const std::string cipher = request.argument(1); #if defined(BOTAN_HAS_PBE_PKCS_V15) if(pbe == "PBE-PKCS5v15") return new PBE_PKCS5v15(digest, cipher, ENCRYPTION); #endif #if defined(BOTAN_HAS_PBE_PKCS_V20) if(pbe == "PBE-PKCS5v20") return new PBE_PKCS5v20(digest, cipher); #endif throw Algorithm_Not_Found(pbe_name); } /************************************************* * Get a decryption PBE, decode parameters * *************************************************/ PBE* get_pbe(const OID& pbe_oid, DataSource& params) { SCAN_Name request(OIDS::lookup(pbe_oid)); #if defined(BOTAN_HAS_PBE_PKCS_V15) if(request.algo_name() == "PBE-PKCS5v15") { if(request.arg_count() != 2) throw Invalid_Algorithm_Name(pbe_oid.as_string()); const std::string digest = request.argument(0); const std::string cipher = request.argument(1); PBE* pbe = new PBE_PKCS5v15(digest, cipher, DECRYPTION); pbe->decode_params(params); return pbe; } #endif #if defined(BOTAN_HAS_PBE_PKCS_V20) if(request.algo_name() == "PBE-PKCS5v20") return new PBE_PKCS5v20(params); #endif throw Algorithm_Not_Found(pbe_oid.as_string()); } } <|endoftext|>
<commit_before>/* * User.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/system/User.hpp> #include <pwd.h> #include <boost/algorithm/string.hpp> #include <shared_core/Error.hpp> #include <shared_core/FilePath.hpp> #include <shared_core/SafeConvert.hpp> namespace rstudio { namespace core { namespace system { namespace { inline std::string getEnvVariable(const std::string& in_name) { char* value = ::getenv(in_name.c_str()); if (value) return std::string(value); return std::string(); } } // anonymous namespace struct User::Impl { template<class T> using GetPasswdFunc = std::function<int(T, struct passwd*, char*, size_t, struct passwd**)>; Impl() : UserId(-1), GroupId(-1) { }; template<typename T> Error populateUser(const GetPasswdFunc<T>& in_getPasswdFunc, T in_value) { struct passwd pwd; struct passwd* tempPtrPwd; // Get the maximum size of a passwd for this system. long buffSize = ::sysconf(_SC_GETPW_R_SIZE_MAX); if (buffSize == 1) buffSize = 4096; // some systems return -1, be conservative! std::vector<char> buffer(buffSize); int result = in_getPasswdFunc(in_value, &pwd, &(buffer[0]), buffSize, &tempPtrPwd); if (tempPtrPwd == nullptr) { if (result == 0) // will happen if user is simply not found. Return EACCES (not found error). result = EACCES; Error error = systemError(result, "Failed to get user details.", ERROR_LOCATION); error.addProperty("user-value", safe_convert::numberToString(in_value)); return error; } else { UserId = pwd.pw_uid; GroupId = pwd.pw_gid; Name = pwd.pw_name; HomeDirectory = FilePath(pwd.pw_dir); Shell = pwd.pw_shell; } return Success(); } UidType UserId; GidType GroupId; std::string Name; FilePath HomeDirectory; std::string Shell; }; PRIVATE_IMPL_DELETER_IMPL(User) User::User(bool in_isEmpty) : m_impl(new Impl()) { m_impl->Name = in_isEmtpy ? "" : "*"; } User::User(const User& in_other) : m_impl(new Impl(*in_other.m_impl)) { } Error User::getCurrentUser(User& out_currentUser) { return getUserFromIdentifier(::geteuid(), out_currentUser); } Error User::getUserFromIdentifier(const std::string& in_username, User& out_user) { User user; Error error = user.m_impl->populateUser<const char*>(::getpwnam_r, in_username.c_str()); if (!error) out_user = user; return error; } Error User::getUserFromIdentifier(UidType in_userId, User& out_user) { User user; Error error = user.m_impl->populateUser<UidType>(::getpwuid_r, in_userId); if (!error) out_user = user; return error; } FilePath User::getUserHomePath(const std::string& in_envOverride) { // use environment override if specified if (!in_envOverride.empty()) { using namespace boost::algorithm; for (split_iterator<std::string::const_iterator> it = make_split_iterator(in_envOverride, first_finder("|", is_iequal())); it != split_iterator<std::string::const_iterator>(); ++it) { std::string envHomePath = getEnvVariable(boost::copy_range<std::string>(*it)); if (!envHomePath.empty()) { FilePath userHomePath(envHomePath); if (userHomePath.exists()) return userHomePath; } } } // otherwise use standard unix HOME return FilePath(getEnvVariable("HOME")); } bool User::exists() const { return !isEmpty() && !isAllUsers(); } bool User::isAllUsers() const { return m_impl->Name == "*"; } bool User::isEmpty() const { return m_impl->Name.empty(); } const FilePath& User::getHomePath() const { return m_impl->HomeDirectory; } GidType User::getGroupId() const { return m_impl->GroupId; } UidType User::getUserId() const { return m_impl->UserId; } const std::string& User::getUsername() const { return m_impl->Name; } const std::string& User::getShell() const { return m_impl->Shell; } User& User::operator=(const User& in_other) { m_impl->Name = in_other.m_impl->Name; m_impl->UserId = in_other.m_impl->UserId; m_impl->GroupId = in_other.m_impl->GroupId; m_impl->HomeDirectory = in_other.m_impl->HomeDirectory; m_impl->Shell = in_other.m_impl->Shell; return *this; } } // namespace system } // namespace core } // namespace rstudio <commit_msg>fixes a typo in User.cpp<commit_after>/* * User.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/system/User.hpp> #include <pwd.h> #include <boost/algorithm/string.hpp> #include <shared_core/Error.hpp> #include <shared_core/FilePath.hpp> #include <shared_core/SafeConvert.hpp> namespace rstudio { namespace core { namespace system { namespace { inline std::string getEnvVariable(const std::string& in_name) { char* value = ::getenv(in_name.c_str()); if (value) return std::string(value); return std::string(); } } // anonymous namespace struct User::Impl { template<class T> using GetPasswdFunc = std::function<int(T, struct passwd*, char*, size_t, struct passwd**)>; Impl() : UserId(-1), GroupId(-1) { }; template<typename T> Error populateUser(const GetPasswdFunc<T>& in_getPasswdFunc, T in_value) { struct passwd pwd; struct passwd* tempPtrPwd; // Get the maximum size of a passwd for this system. long buffSize = ::sysconf(_SC_GETPW_R_SIZE_MAX); if (buffSize == 1) buffSize = 4096; // some systems return -1, be conservative! std::vector<char> buffer(buffSize); int result = in_getPasswdFunc(in_value, &pwd, &(buffer[0]), buffSize, &tempPtrPwd); if (tempPtrPwd == nullptr) { if (result == 0) // will happen if user is simply not found. Return EACCES (not found error). result = EACCES; Error error = systemError(result, "Failed to get user details.", ERROR_LOCATION); error.addProperty("user-value", safe_convert::numberToString(in_value)); return error; } else { UserId = pwd.pw_uid; GroupId = pwd.pw_gid; Name = pwd.pw_name; HomeDirectory = FilePath(pwd.pw_dir); Shell = pwd.pw_shell; } return Success(); } UidType UserId; GidType GroupId; std::string Name; FilePath HomeDirectory; std::string Shell; }; PRIVATE_IMPL_DELETER_IMPL(User) User::User(bool in_isEmpty) : m_impl(new Impl()) { m_impl->Name = in_isEmpty ? "" : "*"; } User::User(const User& in_other) : m_impl(new Impl(*in_other.m_impl)) { } Error User::getCurrentUser(User& out_currentUser) { return getUserFromIdentifier(::geteuid(), out_currentUser); } Error User::getUserFromIdentifier(const std::string& in_username, User& out_user) { User user; Error error = user.m_impl->populateUser<const char*>(::getpwnam_r, in_username.c_str()); if (!error) out_user = user; return error; } Error User::getUserFromIdentifier(UidType in_userId, User& out_user) { User user; Error error = user.m_impl->populateUser<UidType>(::getpwuid_r, in_userId); if (!error) out_user = user; return error; } FilePath User::getUserHomePath(const std::string& in_envOverride) { // use environment override if specified if (!in_envOverride.empty()) { using namespace boost::algorithm; for (split_iterator<std::string::const_iterator> it = make_split_iterator(in_envOverride, first_finder("|", is_iequal())); it != split_iterator<std::string::const_iterator>(); ++it) { std::string envHomePath = getEnvVariable(boost::copy_range<std::string>(*it)); if (!envHomePath.empty()) { FilePath userHomePath(envHomePath); if (userHomePath.exists()) return userHomePath; } } } // otherwise use standard unix HOME return FilePath(getEnvVariable("HOME")); } bool User::exists() const { return !isEmpty() && !isAllUsers(); } bool User::isAllUsers() const { return m_impl->Name == "*"; } bool User::isEmpty() const { return m_impl->Name.empty(); } const FilePath& User::getHomePath() const { return m_impl->HomeDirectory; } GidType User::getGroupId() const { return m_impl->GroupId; } UidType User::getUserId() const { return m_impl->UserId; } const std::string& User::getUsername() const { return m_impl->Name; } const std::string& User::getShell() const { return m_impl->Shell; } User& User::operator=(const User& in_other) { m_impl->Name = in_other.m_impl->Name; m_impl->UserId = in_other.m_impl->UserId; m_impl->GroupId = in_other.m_impl->GroupId; m_impl->HomeDirectory = in_other.m_impl->HomeDirectory; m_impl->Shell = in_other.m_impl->Shell; return *this; } } // namespace system } // namespace core } // namespace rstudio <|endoftext|>
<commit_before>#ifndef Interfaces_hxx #define Interfaces_hxx #include "InterfaceTraits.h" namespace selx { template<class InterfaceT> int InterfaceAcceptor<InterfaceT>::Connect(ComponentBase* providerComponent){ InterfaceT* providerInterface = dynamic_cast<InterfaceT*> (providerComponent); if (!providerInterface) { //TODO log message? //std::cout << "providerComponent does not have required " << InterfaceName < InterfaceT >::Get() << std::endl; return 0; } // connect value interfaces this->Set(providerInterface); // due to the input argument being uniquely defined in the multiple inheritance tree, all versions of Set() are accessible at component level return 1; } ////////////////////////////////////////////////////////////////////////// template<typename AcceptingInterfaces, typename ProvidingInterfaces> ComponentBase::interfaceStatus Implements<AcceptingInterfaces, ProvidingInterfaces>::AcceptConnectionFrom(const char * interfacename, ComponentBase* other) { return AcceptingInterfaces::ConnectFromImpl(interfacename, other); } template<typename AcceptingInterfaces, typename ProvidingInterfaces> int Implements<AcceptingInterfaces, ProvidingInterfaces>::AcceptConnectionFrom(ComponentBase* other) { return AcceptingInterfaces::ConnectFromImpl(other); } template<typename AcceptingInterfaces, typename ProvidingInterfaces> bool Implements<AcceptingInterfaces, ProvidingInterfaces>::HasAcceptingInterface(const char * interfacename) { return AcceptingInterfaces::HasInterface(interfacename); } template<typename AcceptingInterfaces, typename ProvidingInterfaces> bool Implements<AcceptingInterfaces, ProvidingInterfaces>::HasProvidingInterface(const char * interfacename) { return ProvidingInterfaces::HasInterface(interfacename); } ////////////////////////////////////////////////////////////////////////// template<typename FirstInterface, typename ... RestInterfaces> ComponentBase::interfaceStatus Accepting<FirstInterface, RestInterfaces... >::ConnectFromImpl(const char * interfacename, ComponentBase* other) { // does our component have an accepting interface called interfacename? if (InterfaceName<InterfaceAcceptor<FirstInterface>>::Get() == interfacename) { // cast always succeeds since we know via the template arguments of the component which InterfaceAcceptors its base classes are. InterfaceAcceptor<FirstInterface>* acceptIF = this; // See if the other component has the right interface and try to connect them if (1 == acceptIF->Connect(other)) { //success. By terminating this function, we assume only one interface listens to interfacename and that one connection with the other component can be made by this name return ComponentBase::interfaceStatus::success; } else { // interfacename was found, but other component doesn't match return ComponentBase::interfaceStatus::noprovider; } } return Accepting< RestInterfaces ... >::ConnectFromImpl(interfacename, other); } template<typename FirstInterface, typename ... RestInterfaces> int Accepting<FirstInterface, RestInterfaces... >::ConnectFromImpl(ComponentBase* other) { // cast always succeeds since we know via the template arguments of the component which InterfaceAcceptors its base classes are. InterfaceAcceptor<FirstInterface>* acceptIF = (this); // See if the other component has the right interface and try to connect them // count the number of successes return acceptIF->Connect(other) + Accepting< RestInterfaces ... >::ConnectFromImpl(other); } template<typename FirstInterface, typename ... RestInterfaces> bool Accepting<FirstInterface, RestInterfaces... >::HasInterface(const char* interfacename) { if (InterfaceName<InterfaceAcceptor<FirstInterface>>::Get() == interfacename) { return true; } return Accepting< RestInterfaces ... >::HasInterface(interfacename); } template<typename FirstInterface, typename ... RestInterfaces> bool Providing<FirstInterface, RestInterfaces... >::HasInterface(const char* interfacename) { if (InterfaceName<FirstInterface>::Get() == interfacename) { return true; } return Providing< RestInterfaces ... >::HasInterface(interfacename); } } // end namespace selx #endif // #define Interfaces_hxx<commit_msg>BUG: added std::sting, since equality check doesn't work for 2 char*<commit_after>#ifndef Interfaces_hxx #define Interfaces_hxx #include "InterfaceTraits.h" namespace selx { template<class InterfaceT> int InterfaceAcceptor<InterfaceT>::Connect(ComponentBase* providerComponent){ InterfaceT* providerInterface = dynamic_cast<InterfaceT*> (providerComponent); if (!providerInterface) { //TODO log message? //std::cout << "providerComponent does not have required " << InterfaceName < InterfaceT >::Get() << std::endl; return 0; } // connect value interfaces this->Set(providerInterface); // due to the input argument being uniquely defined in the multiple inheritance tree, all versions of Set() are accessible at component level return 1; } ////////////////////////////////////////////////////////////////////////// template<typename AcceptingInterfaces, typename ProvidingInterfaces> ComponentBase::interfaceStatus Implements<AcceptingInterfaces, ProvidingInterfaces>::AcceptConnectionFrom(const char * interfacename, ComponentBase* other) { return AcceptingInterfaces::ConnectFromImpl(interfacename, other); } template<typename AcceptingInterfaces, typename ProvidingInterfaces> int Implements<AcceptingInterfaces, ProvidingInterfaces>::AcceptConnectionFrom(ComponentBase* other) { return AcceptingInterfaces::ConnectFromImpl(other); } template<typename AcceptingInterfaces, typename ProvidingInterfaces> bool Implements<AcceptingInterfaces, ProvidingInterfaces>::HasAcceptingInterface(const char * interfacename) { return AcceptingInterfaces::HasInterface(interfacename); } template<typename AcceptingInterfaces, typename ProvidingInterfaces> bool Implements<AcceptingInterfaces, ProvidingInterfaces>::HasProvidingInterface(const char * interfacename) { return ProvidingInterfaces::HasInterface(interfacename); } ////////////////////////////////////////////////////////////////////////// template<typename FirstInterface, typename ... RestInterfaces> ComponentBase::interfaceStatus Accepting<FirstInterface, RestInterfaces... >::ConnectFromImpl(const char * interfacename, ComponentBase* other) { // does our component have an accepting interface called interfacename? if (InterfaceName<InterfaceAcceptor<FirstInterface>>::Get() == std::string(interfacename)) { // cast always succeeds since we know via the template arguments of the component which InterfaceAcceptors its base classes are. InterfaceAcceptor<FirstInterface>* acceptIF = this; // See if the other component has the right interface and try to connect them if (1 == acceptIF->Connect(other)) { //success. By terminating this function, we assume only one interface listens to interfacename and that one connection with the other component can be made by this name return ComponentBase::interfaceStatus::success; } else { // interfacename was found, but other component doesn't match return ComponentBase::interfaceStatus::noprovider; } } return Accepting< RestInterfaces ... >::ConnectFromImpl(interfacename, other); } template<typename FirstInterface, typename ... RestInterfaces> int Accepting<FirstInterface, RestInterfaces... >::ConnectFromImpl(ComponentBase* other) { // cast always succeeds since we know via the template arguments of the component which InterfaceAcceptors its base classes are. InterfaceAcceptor<FirstInterface>* acceptIF = (this); // See if the other component has the right interface and try to connect them // count the number of successes return acceptIF->Connect(other) + Accepting< RestInterfaces ... >::ConnectFromImpl(other); } template<typename FirstInterface, typename ... RestInterfaces> bool Accepting<FirstInterface, RestInterfaces... >::HasInterface(const char* interfacename) { if (InterfaceName<InterfaceAcceptor<FirstInterface>>::Get() == std::string(interfacename)) { return true; } return Accepting< RestInterfaces ... >::HasInterface(interfacename); } template<typename FirstInterface, typename ... RestInterfaces> bool Providing<FirstInterface, RestInterfaces... >::HasInterface(const char* interfacename) { if (InterfaceName<FirstInterface>::Get() == std::string( interfacename)) { return true; } return Providing< RestInterfaces ... >::HasInterface(interfacename); } } // end namespace selx #endif // #define Interfaces_hxx<|endoftext|>
<commit_before><commit_msg>GSvar: small Somatic DNA report formatting change<commit_after><|endoftext|>
<commit_before>// Filename: pca.cpp // Author: Christopher Goes // Course: CS 404 Machine Learning and Data Mining // Semester: Spring 2016 // Description: Assignment 5 main program logic // Github: https://github.com/GhostofGoes/cgoes-cs404 #include <iostream> #include "mat.h" #define DEBUG 1 #define DEBUG_EIGEN 1 #define DEBUGINPUT 1 #define DEBUG_RESULTS 1 using namespace std; const int NUM_VECTORS = 10; int main() { //int numRows = 0; //int numCols = 0; Matrix data("data"); // Read in the input dataset data.read(); if(DEBUGINPUT) { cout << "**data matrix**" << endl; data.print(); } //numRows = data.maxRows(); //numCols = data.maxCols(); //if(DEBUGINPUT) { cout << "numRows: " << numRows << endl; cout << "numCols: " << numCols << endl; } Matrix centered = data.subRowVector(data.meanVec()); cout << "centered" << endl; centered.print(); // Correlation Matrix Matrix corr = data.cov(); if(DEBUG) { cout << "\nCorrelation Matrix" << endl; corr.print(); } // Create eigen vectors and values Matrix eVecs(corr); Matrix eVals = eVecs.eigenSystem(); if(DEBUG_EIGEN) { cout << "\nEigen Values" << endl; eVals.print(); } if(DEBUG_EIGEN) { cout << "\nEigen Vectors" << endl; eVecs.print(); } // Normalize Eigenvectors //eVecs.normalize(); //if(DEBUG_EIGEN) { cout << "\nNormalized Eigen Vectors" << endl; eVecs.print(); } // Sort eigenvectors by eigenvalue eVals = eVals.transpose(); // leaky boat eVecs.transposeSelf(); // less leaky but very square boat int index = 0; for( int i = 0; i < eVecs.maxRows() - 1; i++ ) { index = i; for(int j = i + 1; j < eVecs.maxRows(); j++) { if(eVals.get(j, 0) > eVals.get(index, 0)) index = j; } eVecs.swapRows(index, i); eVals.swapRows(index, i); } eVals = eVals.transpose(); eVecs.transposeSelf(); if(DEBUG_RESULTS) { cout << "\nSorted Eigen Values" << endl; eVals.print(); } if(DEBUG_RESULTS) { cout << "\nSorted Eigen Vectors" << endl; eVecs.print(); } Matrix compressed = centered.dotT(eVecs); compressed.write(); Matrix recovered = compressed.dot(eVecs); /* SOME BS vector<pair <double, double*> > sorting; double * eigenvals = eVals.getRow(0); for(int i = 0; i < eVecs.maxRows(); i++) { sorting.push_back(make_pair(eigenvals[i], eVecs.getRow(i))); // This probably leaks memory } sort(sorting.begin(), sorting.end()); cout << "\nSorted eigenvectors" << endl; for(int i = 0; i < numRows; i++) // Wormulon runs gcc 4.4 since UI CS dept is trapped in the late 90's. No C++ 11 { cout << "Eigen Value: " << sorting[i].first << endl; cout << "\tEigen Vector: "; for( int c = 0; c < eVecs.maxCols(); c++ ) { cout << " " << sorting[i].second[c]; } cout << endl; }*/ return(0); } <commit_msg>its working! ITS WORKING!<commit_after>// Filename: pca.cpp // Author: Christopher Goes // Course: CS 404 Machine Learning and Data Mining // Semester: Spring 2016 // Description: Assignment 5 main program logic // Github: https://github.com/GhostofGoes/cgoes-cs404 #include <iostream> #include "mat.h" #define DEBUG 0 #define DEBUG_EIGEN 0 #define DEBUG_INPUT 0 using namespace std; const int NUM_VECTORS = 10; int main() { Matrix data("data"); data.read(); if(DEBUG_INPUT) { cout << "**data matrix**" << endl; data.print(); } // Center the data (cov will center for me, I do this for when I need to translate the data later) Matrix centered = data.subRowVector(data.meanVec()); // Correlation Matrix Matrix corr = data.cov(); if(DEBUG) { cout << "\nCorrelation Matrix" << endl; corr.print(); } // Create eigen vectors and values Matrix eVecs(corr); Matrix eVals = eVecs.eigenSystem(); if(DEBUG_EIGEN) { cout << "\nEigen Values" << endl; eVals.print(); } if(DEBUG_EIGEN) { cout << "\nEigen Vectors" << endl; eVecs.print(); } // Normalize Eigenvectors (apparantly not needed) // eVecs.normalize(); // Sort eigenvectors by eigenvalue eVals = eVals.transpose(); // leaky boat eVecs.transposeSelf(); // less leaky but very square boat int index = 0; for( int i = 0; i < eVecs.maxRows() - 1; i++ ) { index = i; for(int j = i + 1; j < eVecs.maxRows(); j++) { if(eVals.get(j, 0) > eVals.get(index, 0)) index = j; } eVecs.swapRows(index, i); eVals.swapRows(index, i); } eVals = eVals.transpose(); eVecs.transposeSelf(); if(DEBUG_EIGEN) { cout << "\nSorted Eigen Values" << endl; eVals.print(); } if(DEBUG_EIGEN) { cout << "\nSorted Eigen Vectors" << endl; eVecs.print(); } // Trim columns down for his test script eVecs = eVecs.transpose(); if( NUM_VECTORS < eVecs.maxCols() ) { eVecs.narrow(NUM_VECTORS); eVals.narrow(NUM_VECTORS); } eVecs = eVecs.transpose(); // Compress! eVecs = eVecs.transpose(); Matrix compressed = centered.dot(eVecs); compressed.write(); // Recover the compressed data! Matrix recovered = compressed.dot(eVecs); return(0); } <|endoftext|>
<commit_before>/****************************************************************************** Copyright 2013 Allied Telesis Labs Ltd. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY 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 <buildsys.h> bool Extraction::add(ExtractionUnit * eu) { ExtractionUnit **t = this->EUs; this->EU_count++; this->EUs = (ExtractionUnit **) realloc(t, sizeof(ExtractionUnit *) * this->EU_count); if(this->EUs == NULL) { this->EUs = t; this->EU_count--; return false; } this->EUs[this->EU_count - 1] = eu; return true; } void Extraction::prepareNewExtractInfo(Package * P, BuildDir * bd) { if(this->extracted) { log(P, "Already extracted"); return; } if(bd) { // Create the new extraction info file std::string fname = string_format("%s/.extraction.info.new", bd->getPath()); std::ofstream exInfo(fname.c_str()); this->print(exInfo); exInfo.close(); } } bool Extraction::extractionRequired(Package * P, BuildDir * bd) { if(this->extracted) { return false; } std::string cmd = string_format("cmp -s %s/.extraction.info.new %s/.extraction.info", bd->getPath(), bd->getPath()); int res = std::system(cmd.c_str()); // if there are changes, if(res != 0 || P->isCodeUpdated()) { // Extract our source code return true; } return false; } bool Extraction::extract(Package * P, BuildDir * bd) { log(P, "Extracting sources and patching"); for(size_t i = 0; i < this->EU_count; i++) { if(!EUs[i]->extract(P, bd)) return false; } // mv the file into the regular place std::string oldfname = string_format("%s/.extraction.info.new", bd->getPath()); std::string newfname = string_format("%s/.extraction.info", bd->getPath()); rename(oldfname.c_str(), newfname.c_str()); return true; }; ExtractionInfoFileUnit *Extraction::extractionInfo(Package * P, BuildDir * bd) { std::string fname = string_format("%s/.extraction.info", bd->getShortPath()); ExtractionInfoFileUnit *ret = new ExtractionInfoFileUnit(fname); return ret; } CompressedFileExtractionUnit::CompressedFileExtractionUnit(FetchUnit * f) { this->fetch = f; this->uri = f->relative_path(); } CompressedFileExtractionUnit::CompressedFileExtractionUnit(const std::string & fname) { this->fetch = NULL; this->uri = fname; } std::string CompressedFileExtractionUnit::HASH() { if(this->hash.empty()) { if(this->fetch) { this->hash = std::string(this->fetch->HASH()); } else { this->hash = hash_file(this->uri); } } return this->hash; }; bool TarExtractionUnit::extract(Package * P, BuildDir * bd) { std::unique_ptr < PackageCmd > pc(new PackageCmd(bd->getPath(), "tar")); filesystem::create_directories("dl"); pc->addArg("xf"); pc->addArg(P->getWorld()->getWorkingDir() + "/" + this->uri); if(!pc->Run(P)) throw CustomException("Failed to extract file"); return true; } bool ZipExtractionUnit::extract(Package * P, BuildDir * bd) { std::unique_ptr < PackageCmd > pc(new PackageCmd(bd->getPath(), "unzip")); filesystem::create_directories("dl"); pc->addArg("-o"); pc->addArg(P->getWorld()->getWorkingDir() + "/" + this->uri); if(!pc->Run(P)) throw CustomException("Failed to extract file"); return true; } PatchExtractionUnit::PatchExtractionUnit(int level, const std::string & patch_path, const std::string & patch_fname, const std::string & fname_short) { this->uri = patch_fname; this->fname_short = fname_short; this->hash = hash_file(this->uri); this->level = level; this->patch_path = patch_path; } bool PatchExtractionUnit::extract(Package * P, BuildDir * bd) { std::unique_ptr < PackageCmd > pc_dry(new PackageCmd(this->patch_path.c_str(), "patch")); std::unique_ptr < PackageCmd > pc(new PackageCmd(this->patch_path.c_str(), "patch")); pc_dry->addArg("-p" + std::to_string(this->level)); pc->addArg("-p" + std::to_string(this->level)); pc_dry->addArg("-stN"); pc->addArg("-stN"); pc_dry->addArg("-i"); pc->addArg("-i"); auto pwd = P->getWorld()->getWorkingDir(); pc_dry->addArg(pwd + "/" + this->uri); pc->addArg(pwd + "/" + this->uri); pc_dry->addArg("--dry-run"); if(!pc_dry->Run(P)) { log(P->getName().c_str(), "Patch file: %s", this->uri.c_str()); throw CustomException("Will fail to patch"); } if(!pc->Run(P)) throw CustomException("Truely failed to patch"); return true; } FileCopyExtractionUnit::FileCopyExtractionUnit(const std::string & fname, const std::string & fname_short) { this->uri = fname; this->fname_short = fname_short; this->hash = hash_file(this->uri); } bool FileCopyExtractionUnit::extract(Package * P, BuildDir * bd) { std::string path = this->uri; std::unique_ptr < PackageCmd > pc(new PackageCmd(bd->getPath(), "cp")); pc->addArg("-pRLuf"); if(path.at(0) == '/') { pc->addArg(path); } else { std::string arg = P->getWorld()->getWorkingDir() + "/" + path; pc->addArg(arg); } pc->addArg("."); if(!pc->Run(P)) { throw CustomException("Failed to copy file"); } return true; } FetchedFileCopyExtractionUnit::FetchedFileCopyExtractionUnit(FetchUnit * fetched, const char *fname_short) { this->fetched = fetched; this->uri = fetched->relative_path(); this->fname_short = std::string(fname_short); this->hash = std::string(""); } std::string FetchedFileCopyExtractionUnit::HASH() { if(this->hash.empty()) { this->hash = std::string(this->fetched->HASH()); } return this->hash; } bool FetchedFileCopyExtractionUnit::extract(Package * P, BuildDir * bd) { const char *path = this->uri.c_str(); std::unique_ptr < PackageCmd > pc(new PackageCmd(bd->getPath(), "cp")); pc->addArg("-pRLuf"); if(path[0] == '/') { pc->addArg(path); } else { pc->addArg(P->getWorld()->getWorkingDir() + "/" + path); } pc->addArg("."); if(!pc->Run(P)) { throw CustomException("Failed to copy file"); } return true; } <commit_msg>extraction: Declare PackageCmd objects on the stack<commit_after>/****************************************************************************** Copyright 2013 Allied Telesis Labs Ltd. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY 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 <buildsys.h> bool Extraction::add(ExtractionUnit * eu) { ExtractionUnit **t = this->EUs; this->EU_count++; this->EUs = (ExtractionUnit **) realloc(t, sizeof(ExtractionUnit *) * this->EU_count); if(this->EUs == NULL) { this->EUs = t; this->EU_count--; return false; } this->EUs[this->EU_count - 1] = eu; return true; } void Extraction::prepareNewExtractInfo(Package * P, BuildDir * bd) { if(this->extracted) { log(P, "Already extracted"); return; } if(bd) { // Create the new extraction info file std::string fname = string_format("%s/.extraction.info.new", bd->getPath()); std::ofstream exInfo(fname.c_str()); this->print(exInfo); exInfo.close(); } } bool Extraction::extractionRequired(Package * P, BuildDir * bd) { if(this->extracted) { return false; } std::string cmd = string_format("cmp -s %s/.extraction.info.new %s/.extraction.info", bd->getPath(), bd->getPath()); int res = std::system(cmd.c_str()); // if there are changes, if(res != 0 || P->isCodeUpdated()) { // Extract our source code return true; } return false; } bool Extraction::extract(Package * P, BuildDir * bd) { log(P, "Extracting sources and patching"); for(size_t i = 0; i < this->EU_count; i++) { if(!EUs[i]->extract(P, bd)) return false; } // mv the file into the regular place std::string oldfname = string_format("%s/.extraction.info.new", bd->getPath()); std::string newfname = string_format("%s/.extraction.info", bd->getPath()); rename(oldfname.c_str(), newfname.c_str()); return true; }; ExtractionInfoFileUnit *Extraction::extractionInfo(Package * P, BuildDir * bd) { std::string fname = string_format("%s/.extraction.info", bd->getShortPath()); ExtractionInfoFileUnit *ret = new ExtractionInfoFileUnit(fname); return ret; } CompressedFileExtractionUnit::CompressedFileExtractionUnit(FetchUnit * f) { this->fetch = f; this->uri = f->relative_path(); } CompressedFileExtractionUnit::CompressedFileExtractionUnit(const std::string & fname) { this->fetch = NULL; this->uri = fname; } std::string CompressedFileExtractionUnit::HASH() { if(this->hash.empty()) { if(this->fetch) { this->hash = std::string(this->fetch->HASH()); } else { this->hash = hash_file(this->uri); } } return this->hash; }; bool TarExtractionUnit::extract(Package * P, BuildDir * bd) { PackageCmd pc(bd->getPath(), "tar"); filesystem::create_directories("dl"); pc.addArg("xf"); pc.addArg(P->getWorld()->getWorkingDir() + "/" + this->uri); if(!pc.Run(P)) throw CustomException("Failed to extract file"); return true; } bool ZipExtractionUnit::extract(Package * P, BuildDir * bd) { PackageCmd pc(bd->getPath(), "unzip"); filesystem::create_directories("dl"); pc.addArg("-o"); pc.addArg(P->getWorld()->getWorkingDir() + "/" + this->uri); if(!pc.Run(P)) throw CustomException("Failed to extract file"); return true; } PatchExtractionUnit::PatchExtractionUnit(int level, const std::string & patch_path, const std::string & patch_fname, const std::string & fname_short) { this->uri = patch_fname; this->fname_short = fname_short; this->hash = hash_file(this->uri); this->level = level; this->patch_path = patch_path; } bool PatchExtractionUnit::extract(Package * P, BuildDir * bd) { PackageCmd pc_dry(this->patch_path.c_str(), "patch"); PackageCmd pc(this->patch_path.c_str(), "patch"); pc_dry.addArg("-p" + std::to_string(this->level)); pc.addArg("-p" + std::to_string(this->level)); pc_dry.addArg("-stN"); pc.addArg("-stN"); pc_dry.addArg("-i"); pc.addArg("-i"); auto pwd = P->getWorld()->getWorkingDir(); pc_dry.addArg(pwd + "/" + this->uri); pc.addArg(pwd + "/" + this->uri); pc_dry.addArg("--dry-run"); if(!pc_dry.Run(P)) { log(P->getName().c_str(), "Patch file: %s", this->uri.c_str()); throw CustomException("Will fail to patch"); } if(!pc.Run(P)) throw CustomException("Truely failed to patch"); return true; } FileCopyExtractionUnit::FileCopyExtractionUnit(const std::string & fname, const std::string & fname_short) { this->uri = fname; this->fname_short = fname_short; this->hash = hash_file(this->uri); } bool FileCopyExtractionUnit::extract(Package * P, BuildDir * bd) { std::string path = this->uri; PackageCmd pc(bd->getPath(), "cp"); pc.addArg("-pRLuf"); if(path.at(0) == '/') { pc.addArg(path); } else { std::string arg = P->getWorld()->getWorkingDir() + "/" + path; pc.addArg(arg); } pc.addArg("."); if(!pc.Run(P)) { throw CustomException("Failed to copy file"); } return true; } FetchedFileCopyExtractionUnit::FetchedFileCopyExtractionUnit(FetchUnit * fetched, const char *fname_short) { this->fetched = fetched; this->uri = fetched->relative_path(); this->fname_short = std::string(fname_short); this->hash = std::string(""); } std::string FetchedFileCopyExtractionUnit::HASH() { if(this->hash.empty()) { this->hash = std::string(this->fetched->HASH()); } return this->hash; } bool FetchedFileCopyExtractionUnit::extract(Package * P, BuildDir * bd) { const char *path = this->uri.c_str(); PackageCmd pc(bd->getPath(), "cp"); pc.addArg("-pRLuf"); if(path[0] == '/') { pc.addArg(path); } else { pc.addArg(P->getWorld()->getWorkingDir() + "/" + path); } pc.addArg("."); if(!pc.Run(P)) { throw CustomException("Failed to copy file"); } return true; } <|endoftext|>
<commit_before>/* * fMBT, free Model Based Testing tool * Copyright (c) 2011, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope 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 program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include <stack> #include "conf.hh" #include "log.hh" #include "helper.hh" #include <iostream> #include <unistd.h> #include <cstdlib> #ifndef DROI #include <error.h> #else void error(int exitval, int dontcare, const char* format, ...) { va_list ap; fprintf(stderr, "fMBT error: "); vfprintf(stderr, format, ap); exit(exitval); } #endif #include <cstdio> #include <getopt.h> void print_usage() { std::printf( "Usage: fmbt [options] configfile\n" "Options:\n" " -D enable debug output (written to the log)\n" " -E print precompiled configuration in human readable form\n" " -e print precompiled configuration in machine readable form\n" " -h help\n" " -i start in interactive mode\n" " -L<f> append log to file f (default: standard output)\n" " -l<f> overwrite log to file f (default: standard output)\n" ); } int main(int argc,char * const argv[]) { FILE* logfile=stdout; bool interactive=false; bool debug_enabled=false; bool E=false; int c; static struct option long_opts[] = { {"help", no_argument, 0, 'h'}, {0, 0, 0, 0} }; while ((c = getopt_long (argc, argv, "DEL:heil:", long_opts, NULL)) != -1) switch (c) { case 'D': debug_enabled=true; break; case 'E': human_readable=true; E=true; break; case 'L': case 'l': if (logfile!=stdout) { std::printf("Only one logfile\n"); return 3; } logfile=fopen(optarg,c=='L'?"a":"w"); if (!logfile) { std::printf("Can't open logfile \"%s\"\n",optarg); return 1; } break; case 'e': human_readable=false; E=true; break; case 'i': interactive=true; break; case 'h': print_usage(); return 0; default: return 2; } if (optind == argc) { print_usage(); error(3, 0, "test configuration file missing.\n"); } { Log log(logfile); Conf c(log,debug_enabled); std::string conffilename(argv[optind]); c.load(conffilename); if (!c.status) error(4, 0, "%s", c.stringify().c_str()); if (E) { std::printf("%s\n",c.stringify().c_str()); } else { c.execute(interactive); if (!c.status) { std::printf("%s\n",c.stringify().c_str()); return 5; } } } return 0; } <commit_msg>fix fmbt_droid error messages<commit_after>/* * fMBT, free Model Based Testing tool * Copyright (c) 2011, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope 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 program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include <stack> #include "conf.hh" #include "log.hh" #include "helper.hh" #include <iostream> #include <unistd.h> #include <cstdlib> #ifndef DROI #include <error.h> #else void error(int exitval, int dontcare, const char* format, ...) { va_list ap; fprintf(stderr, "fMBT error: "); va_start (ap, format); vfprintf(stderr, format, ap); va_end(ap); exit(exitval); } #endif #include <cstdio> #include <getopt.h> void print_usage() { std::printf( "Usage: fmbt [options] configfile\n" "Options:\n" " -D enable debug output (written to the log)\n" " -E print precompiled configuration in human readable form\n" " -e print precompiled configuration in machine readable form\n" " -h help\n" " -i start in interactive mode\n" " -L<f> append log to file f (default: standard output)\n" " -l<f> overwrite log to file f (default: standard output)\n" ); } int main(int argc,char * const argv[]) { FILE* logfile=stdout; bool interactive=false; bool debug_enabled=false; bool E=false; int c; static struct option long_opts[] = { {"help", no_argument, 0, 'h'}, {0, 0, 0, 0} }; while ((c = getopt_long (argc, argv, "DEL:heil:", long_opts, NULL)) != -1) switch (c) { case 'D': debug_enabled=true; break; case 'E': human_readable=true; E=true; break; case 'L': case 'l': if (logfile!=stdout) { std::printf("Only one logfile\n"); return 3; } logfile=fopen(optarg,c=='L'?"a":"w"); if (!logfile) { std::printf("Can't open logfile \"%s\"\n",optarg); return 1; } break; case 'e': human_readable=false; E=true; break; case 'i': interactive=true; break; case 'h': print_usage(); return 0; default: return 2; } if (optind == argc) { print_usage(); error(3, 0, "test configuration file missing.\n"); } { Log log(logfile); Conf c(log,debug_enabled); std::string conffilename(argv[optind]); c.load(conffilename); if (!c.status) error(4, 0, "%s\n", c.stringify().c_str()); if (E) { std::printf("%s\n",c.stringify().c_str()); } else { c.execute(interactive); if (!c.status) { std::printf("%s\n",c.stringify().c_str()); return 5; } } } return 0; } <|endoftext|>