text
stringlengths
54
60.6k
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Log$ Revision 1.2 2000/10/06 16:49:46 cblume Made Getters const Revision 1.1.2.2 2000/10/04 16:34:58 cblume Replace include files by forward declarations Revision 1.1.2.1 2000/09/22 14:47:52 cblume Add the tracking code */ #include <TObject.h> #include "AliRun.h" #include "AliTRD.h" #include "AliTRDgeometry.h" #include "AliTRDcluster.h" #include "AliTRDtimeBin.h" #include "AliTRDtrackingSector.h" ClassImp(AliTRDtrackingSector) //_______________________________________________________ AliTRDtrackingSector::~AliTRDtrackingSector() { // // Destructor // delete[] fTimeBin; } //_______________________________________________________ AliTRDtimeBin &AliTRDtrackingSector::operator[](Int_t i) { // // Index operator // return *(fTimeBin+i); } //_______________________________________________________ void AliTRDtrackingSector::SetUp() { AliTRD *TRD = (AliTRD*) gAlice->GetDetector("TRD"); fGeom = TRD->GetGeometry(); fTimeBinSize = fGeom->GetTimeBinSize(); fN = AliTRDgeometry::Nplan() * (Int_t(AliTRDgeometry::DrThick() /fTimeBinSize) + 1); fTimeBin = new AliTRDtimeBin[fN]; } //______________________________________________________ Double_t AliTRDtrackingSector::GetX(Int_t l) const { if( (l<0) || (l>fN-1)) { fprintf(stderr,"AliTRDtrackingSector::GetX: TimeBin index is out of range !\n"); return -99999.; } else { Int_t tb_per_plane = fN/AliTRDgeometry::Nplan(); Int_t plane = l/tb_per_plane; Int_t time_slice = l%(Int_t(AliTRDgeometry::DrThick() /fTimeBinSize) + 1); Float_t t0 = fGeom->GetTime0(plane); Double_t x = t0 + time_slice * fTimeBinSize; // cerr<<"plane, tb, x = "<<plane<<","<<time_slice<<","<<x<<endl; return x; } } //______________________________________________________ Double_t AliTRDtrackingSector::GetMaxY(Int_t l) const { if((l<(fN-1)) && (l>-1)) { Int_t tb_per_plane = fN/AliTRDgeometry::Nplan(); Int_t plane = l/tb_per_plane; return fGeom->GetChamberWidth(plane); } else { fprintf(stderr, "AliTRDtrackingSector::GetMaxY: TimeBin index is out of range !\n"); if(l<0) return fGeom->GetChamberWidth(0); else return fGeom->GetChamberWidth(AliTRDgeometry::Nplan()-1); } } //______________________________________________________ Int_t AliTRDtrackingSector::GetTimeBinNumber(Double_t x) const { Float_t r_out = fGeom->GetTime0(AliTRDgeometry::Nplan()-1) + AliTRDgeometry::DrThick(); Float_t r_in = fGeom->GetTime0(0); // cerr<<"GetTimeBinNumber: r_in,r_out = "<<r_in<<","<<r_out<<endl; if(x >= r_out) return fN-1; if(x <= r_in) return 0; Float_t gap = fGeom->GetTime0(1) - fGeom->GetTime0(0); // cerr<<"GetTimeBinNumber: gap = "<<gap<<endl; Int_t plane = Int_t((x - r_in + fTimeBinSize/2)/gap); // cerr<<"GetTimeBinNumber: plane="<<plane<<endl; Int_t local_tb = Int_t((x-fGeom->GetTime0(plane))/fTimeBinSize + 0.5); // cerr<<"GetTimeBinNumber: local_tb="<<local_tb<<endl; Int_t time_bin = plane * (Int_t(AliTRDgeometry::DrThick() /fTimeBinSize) + 1) + local_tb; // cerr<<"GetTimeBinNumber: time_bin = "<<time_bin<<endl; return time_bin; } //______________________________________________________ Int_t AliTRDtrackingSector::GetTimeBin(Int_t det, Int_t local_tb) const { Int_t plane = fGeom->GetPlane(det); Int_t time_bin = plane * (Int_t(AliTRDgeometry::DrThick() /fTimeBinSize) + 1) + local_tb; return time_bin; } <commit_msg>Changed timebin 0 to be the one closest to the readout<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Log$ Revision 1.3 2000/10/15 23:40:01 cblume Remove AliTRDconst Revision 1.2 2000/10/06 16:49:46 cblume Made Getters const Revision 1.1.2.2 2000/10/04 16:34:58 cblume Replace include files by forward declarations Revision 1.1.2.1 2000/09/22 14:47:52 cblume Add the tracking code */ #include <TObject.h> #include "AliRun.h" #include "AliTRD.h" #include "AliTRDgeometry.h" #include "AliTRDcluster.h" #include "AliTRDtimeBin.h" #include "AliTRDtrackingSector.h" ClassImp(AliTRDtrackingSector) //_______________________________________________________ AliTRDtrackingSector::~AliTRDtrackingSector() { // // Destructor // delete[] fTimeBin; } //_______________________________________________________ AliTRDtimeBin &AliTRDtrackingSector::operator[](Int_t i) { // // Index operator // return *(fTimeBin+i); } //_______________________________________________________ void AliTRDtrackingSector::SetUp() { AliTRD *TRD = (AliTRD*) gAlice->GetDetector("TRD"); fGeom = TRD->GetGeometry(); fTimeBinSize = fGeom->GetTimeBinSize(); fN = AliTRDgeometry::Nplan() * (Int_t(AliTRDgeometry::DrThick() /fTimeBinSize) + 1); fTimeBin = new AliTRDtimeBin[fN]; } //______________________________________________________ Double_t AliTRDtrackingSector::GetX(Int_t l) const { if( (l<0) || (l>fN-1)) { fprintf(stderr,"AliTRDtrackingSector::GetX: TimeBin index is out of range !\n"); return -99999.; } else { Int_t tb_per_plane = fN/AliTRDgeometry::Nplan(); Int_t plane = l/tb_per_plane; Int_t time_slice = l%(Int_t(AliTRDgeometry::DrThick() /fTimeBinSize) + 1); Float_t t0 = fGeom->GetTime0(plane); Double_t x = t0 + time_slice * fTimeBinSize; // cerr<<"plane, tb, x = "<<plane<<","<<time_slice<<","<<x<<endl; return x; } } //______________________________________________________ Double_t AliTRDtrackingSector::GetMaxY(Int_t l) const { if((l<(fN-1)) && (l>-1)) { Int_t tb_per_plane = fN/AliTRDgeometry::Nplan(); Int_t plane = l/tb_per_plane; return fGeom->GetChamberWidth(plane); } else { fprintf(stderr, "AliTRDtrackingSector::GetMaxY: TimeBin index is out of range !\n"); if(l<0) return fGeom->GetChamberWidth(0); else return fGeom->GetChamberWidth(AliTRDgeometry::Nplan()-1); } } //______________________________________________________ Int_t AliTRDtrackingSector::GetTimeBinNumber(Double_t x) const { //Float_t r_out = fGeom->GetTime0(AliTRDgeometry::Nplan()-1) // + AliTRDgeometry::DrThick(); // Changed to new time0 (CBL) Float_t r_out = fGeom->GetTime0(AliTRDgeometry::Nplan()-1); Float_t r_in = fGeom->GetTime0(0); // cerr<<"GetTimeBinNumber: r_in,r_out = "<<r_in<<","<<r_out<<endl; if(x >= r_out) return fN-1; if(x <= r_in) return 0; Float_t gap = fGeom->GetTime0(1) - fGeom->GetTime0(0); // cerr<<"GetTimeBinNumber: gap = "<<gap<<endl; Int_t plane = Int_t((x - r_in + fTimeBinSize/2)/gap); // cerr<<"GetTimeBinNumber: plane="<<plane<<endl; Int_t local_tb = Int_t((x-fGeom->GetTime0(plane))/fTimeBinSize + 0.5); // cerr<<"GetTimeBinNumber: local_tb="<<local_tb<<endl; Int_t time_bin = plane * (Int_t(AliTRDgeometry::DrThick() /fTimeBinSize) + 1) + local_tb; // cerr<<"GetTimeBinNumber: time_bin = "<<time_bin<<endl; return time_bin; } //______________________________________________________ Int_t AliTRDtrackingSector::GetTimeBin(Int_t det, Int_t local_tb) const { Int_t plane = fGeom->GetPlane(det); Int_t time_bin = plane * (Int_t(AliTRDgeometry::DrThick() /fTimeBinSize) + 1) + local_tb; return time_bin; } <|endoftext|>
<commit_before>/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #include "vast/system/indexer.hpp" #include <new> #include <caf/all.hpp> #include "vast/concept/printable/stream.hpp" #include "vast/concept/printable/vast/expression.hpp" #include "vast/const_table_slice_handle.hpp" #include "vast/detail/assert.hpp" #include "vast/expression.hpp" #include "vast/filesystem.hpp" #include "vast/logger.hpp" #include "vast/system/atoms.hpp" #include "vast/system/indexer.hpp" using namespace caf; namespace vast::system { indexer_state::indexer_state() : initialized(false) { // nop } indexer_state::~indexer_state() { if (initialized) tbl.~table_index(); } void indexer_state::init(table_index&& from) { VAST_ASSERT(!initialized); new (&tbl) table_index(std::move(from)); initialized = true; } behavior indexer(stateful_actor<indexer_state>* self, path dir, record_type layout) { auto maybe_tbl = make_table_index(std::move(dir), layout); if (!maybe_tbl) { VAST_ERROR(self, "unable to generate table layout for", layout); return {}; } self->state.init(std::move(*maybe_tbl)); VAST_DEBUG(self, "operates for layout", layout); return { [=](const predicate& pred) { VAST_DEBUG(self, "got predicate:", pred); return self->state.tbl.lookup(pred); }, [=](const expression& expr) { VAST_DEBUG(self, "got expression:", expr); return self->state.tbl.lookup(expr); }, [=](persist_atom) -> result<void> { if (auto err = self->state.tbl.flush_to_disk(); err != caf::none) return err; return caf::unit; }, [=](stream<const_table_slice_handle> in) { self->make_sink( in, [](unit_t&) { // nop }, [=](unit_t&, const std::vector<const_table_slice_handle>& xs) { for (auto& x : xs) self->state.tbl.add(x); }, [=](unit_t&, const error& err) { if (err) { VAST_ERROR(self, "got a stream error:", self->system().render(err)); } } ); }, [=](shutdown_atom) { self->quit(exit_reason::user_shutdown); }, }; } } // namespace vast::system <commit_msg>Suppress error log entry for ordinary shutdown<commit_after>/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #include "vast/system/indexer.hpp" #include <new> #include <caf/all.hpp> #include "vast/concept/printable/stream.hpp" #include "vast/concept/printable/vast/expression.hpp" #include "vast/const_table_slice_handle.hpp" #include "vast/detail/assert.hpp" #include "vast/expression.hpp" #include "vast/filesystem.hpp" #include "vast/logger.hpp" #include "vast/system/atoms.hpp" #include "vast/system/indexer.hpp" using namespace caf; namespace vast::system { indexer_state::indexer_state() : initialized(false) { // nop } indexer_state::~indexer_state() { if (initialized) tbl.~table_index(); } void indexer_state::init(table_index&& from) { VAST_ASSERT(!initialized); new (&tbl) table_index(std::move(from)); initialized = true; } behavior indexer(stateful_actor<indexer_state>* self, path dir, record_type layout) { auto maybe_tbl = make_table_index(std::move(dir), layout); if (!maybe_tbl) { VAST_ERROR(self, "unable to generate table layout for", layout); return {}; } self->state.init(std::move(*maybe_tbl)); VAST_DEBUG(self, "operates for layout", layout); return { [=](const predicate& pred) { VAST_DEBUG(self, "got predicate:", pred); return self->state.tbl.lookup(pred); }, [=](const expression& expr) { VAST_DEBUG(self, "got expression:", expr); return self->state.tbl.lookup(expr); }, [=](persist_atom) -> result<void> { if (auto err = self->state.tbl.flush_to_disk(); err != caf::none) return err; return caf::unit; }, [=](stream<const_table_slice_handle> in) { self->make_sink( in, [](unit_t&) { // nop }, [=](unit_t&, const std::vector<const_table_slice_handle>& xs) { for (auto& x : xs) self->state.tbl.add(x); }, [=](unit_t&, const error& err) { if (err && err != caf::exit_reason::user_shutdown) { VAST_ERROR(self, "got a stream error:", self->system().render(err)); } } ); }, [=](shutdown_atom) { self->quit(exit_reason::user_shutdown); }, }; } } // namespace vast::system <|endoftext|>
<commit_before>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #pragma once #include <string> #include <db.h> #include "cursor.hpp" #include "db_env.hpp" #include "db_txn.hpp" #include "exceptions.hpp" #include "slice.hpp" #include "stats.hpp" namespace ftcxx { template<class Comparator, class Handler> class CallbackCursor; template<class Comparator, class Predicate> class BufferedCursor; template<class Comparator> class SimpleCursor; class DB { public: DB() : _db(nullptr) {} explicit DB(::DB *d) : _db(d) {} ~DB() { if (_db) { close(); } } DB(const DB &) = delete; DB& operator=(const DB &) = delete; DB(DB &&o) : _db(nullptr) { std::swap(_db, o._db); } DB& operator=(DB &&o) { std::swap(_db, o._db); return *this; } ::DB *db() const { return _db; } Slice descriptor() const { return Slice(_db->cmp_descriptor->dbt); } template<typename Callback> int getf_set(const DBTxn &txn, const Slice &key, int flags, Callback cb) const { class WrappedCallback { Callback &_cb; public: WrappedCallback(Callback &cb_) : _cb(cb_) {} static int call(const DBT *key_, const DBT *val_, void *extra) { WrappedCallback *wc = static_cast<WrappedCallback *>(extra); return wc->call(key_, val_); } int call(const DBT *key_, const DBT *val_) { return _cb(Slice(*key_), Slice(*val_)); } } wc(cb); DBT kdbt = key.dbt(); return _db->getf_set(_db, txn.txn(), flags, &kdbt, &WrappedCallback::call, &wc); } int put(const DBTxn &txn, DBT *key, DBT *val, int flags=0) const { return _db->put(_db, txn.txn(), key, val, flags); } int put(const DBTxn &txn, const Slice &key, const Slice &val, int flags=0) const { DBT kdbt = key.dbt(); DBT vdbt = val.dbt(); return put(txn, &kdbt, &vdbt, flags); } int del(const DBTxn &txn, DBT *key, int flags=0) const { return _db->del(_db, txn.txn(), key, flags); } int del(const DBTxn &txn, const Slice &key, int flags=0) const { DBT kdbt = key.dbt(); return _db->del(_db, txn.txn(), &kdbt, flags); } Stats get_stats() const { Stats stats; DB_BTREE_STAT64 s = {0, 0, 0}; int r = _db->stat64(_db, NULL, &s); handle_ft_retval(r); stats.dataSize = s.bt_dsize; stats.fileSize = s.bt_fsize; stats.numberOfKeys = s.bt_nkeys; return stats; } struct NullFilter { bool operator()(const Slice &, const Slice &) { return true; } }; /** * Constructs a Cursor over this DB, over the range from left to * right (or right to left if !forward). */ template<class Comparator, class Handler> CallbackCursor<Comparator, Handler> cursor(const DBTxn &txn, DBT *left, DBT *right, Comparator &&cmp, Handler &&handler, int flags=0, bool forward=true, bool end_exclusive=false, bool prelock=true) const; template<class Comparator, class Handler> CallbackCursor<Comparator, Handler> cursor(const DBTxn &txn, const Slice &left, const Slice &right, Comparator &&cmp, Handler &&handler, int flags=0, bool forward=true, bool end_exclusive=false, bool prelock=true) const; template<class Comparator, class Handler> CallbackCursor<Comparator, Handler> cursor(const DBTxn &txn, Comparator &&cmp, Handler &&handler, int flags=0, bool forward=true, bool prelock=true) const; template<class Comparator, class Predicate> BufferedCursor<Comparator, Predicate> buffered_cursor(const DBTxn &txn, DBT *left, DBT *right, Comparator &&cmp, Predicate &&filter, int flags=0, bool forward=true, bool end_exclusive=false, bool prelock=true) const; template<class Comparator, class Predicate> BufferedCursor<Comparator, Predicate> buffered_cursor(const DBTxn &txn, const Slice &left, const Slice &right, Comparator &&cmp, Predicate &&filter, int flags=0, bool forward=true, bool end_exclusive=false, bool prelock=true) const; template<class Comparator, class Predicate> BufferedCursor<Comparator, Predicate> buffered_cursor(const DBTxn &txn, Comparator &&cmp, Predicate &&filter, int flags=0, bool forward=true, bool prelock=true) const; template<class Comparator> SimpleCursor<Comparator> simple_cursor(const DBTxn &txn, DBT *left, DBT *right, Comparator &&cmp, Slice &key, Slice &val, int flags=0, bool forward=true, bool end_exclusive=false, bool prelock=true) const; template<class Comparator> SimpleCursor<Comparator> simple_cursor(const DBTxn &txn, const Slice &left, const Slice &right, Comparator &&cmp, Slice &key, Slice &val, int flags=0, bool forward=true, bool end_exclusive=false, bool prelock=true) const; template<class Comparator> SimpleCursor<Comparator> simple_cursor(const DBTxn &txn, Comparator &&cmp, Slice &key, Slice &val, int flags=0, bool forward=true, bool prelock=true) const; void close() { int r = _db->close(_db, 0); handle_ft_retval(r); _db = nullptr; } private: ::DB *_db; }; class DBBuilder { uint32_t _readpagesize; TOKU_COMPRESSION_METHOD _compression_method; uint32_t _fanout; uint8_t _memcmp_magic; uint32_t _pagesize; Slice _descriptor; public: DBBuilder() : _readpagesize(0), _compression_method(TOKU_COMPRESSION_METHOD(0)), _fanout(0), _memcmp_magic(0), _pagesize(0), _descriptor() {} DB open(const DBEnv &env, const DBTxn &txn, const char *fname, const char *dbname, DBTYPE dbtype, uint32_t flags, int mode) const { ::DB *db; int r = db_create(&db, env.env(), 0); handle_ft_retval(r); if (_readpagesize) { r = db->set_readpagesize(db, _readpagesize); handle_ft_retval(r); } if (_compression_method) { r = db->set_compression_method(db, _compression_method); handle_ft_retval(r); } if (_fanout) { r = db->set_fanout(db, _fanout); handle_ft_retval(r); } if (_memcmp_magic) { r = db->set_memcmp_magic(db, _memcmp_magic); handle_ft_retval(r); } if (_pagesize) { r = db->set_pagesize(db, _pagesize); handle_ft_retval(r); } r = db->open(db, txn.txn(), fname, dbname, dbtype, flags, mode); handle_ft_retval(r); if (!_descriptor.empty()) { DBT desc = _descriptor.dbt(); r = db->change_descriptor(db, txn.txn(), &desc, DB_UPDATE_CMP_DESCRIPTOR); handle_ft_retval(r); } return DB(db); } DBBuilder& set_readpagesize(uint32_t readpagesize) { _readpagesize = readpagesize; return *this; } DBBuilder& set_compression_method(TOKU_COMPRESSION_METHOD _compressionmethod) { _compression_method = _compressionmethod; return *this; } DBBuilder& set_fanout(uint32_t fanout) { _fanout = fanout; return *this; } DBBuilder& set_memcmp_magic(uint8_t _memcmpmagic) { _memcmp_magic = _memcmpmagic; return *this; } DBBuilder& set_pagesize(uint32_t pagesize) { _pagesize = pagesize; return *this; } DBBuilder& set_descriptor(const Slice &desc) { _descriptor = desc; return *this; } }; } // namespace ftcxx <commit_msg>allow temporary construction of ftcxx::DB<commit_after>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #pragma once #include <string> #include <db.h> #include "cursor.hpp" #include "db_env.hpp" #include "db_txn.hpp" #include "exceptions.hpp" #include "slice.hpp" #include "stats.hpp" namespace ftcxx { template<class Comparator, class Handler> class CallbackCursor; template<class Comparator, class Predicate> class BufferedCursor; template<class Comparator> class SimpleCursor; class DB { public: DB() : _db(nullptr), _close_on_destroy(false) {} explicit DB(::DB *d, bool close_on_destroy=false) : _db(d), _close_on_destroy(close_on_destroy) {} ~DB() { if (_db && _close_on_destroy) { close(); } } DB(const DB &) = delete; DB& operator=(const DB &) = delete; DB(DB &&o) : _db(nullptr), _close_on_destroy(false) { std::swap(_db, o._db); std::swap(_close_on_destroy, o._close_on_destroy); } DB& operator=(DB &&o) { std::swap(_db, o._db); std::swap(_close_on_destroy, o._close_on_destroy); return *this; } ::DB *db() const { return _db; } Slice descriptor() const { return Slice(_db->cmp_descriptor->dbt); } template<typename Callback> int getf_set(const DBTxn &txn, const Slice &key, int flags, Callback cb) const { class WrappedCallback { Callback &_cb; public: WrappedCallback(Callback &cb_) : _cb(cb_) {} static int call(const DBT *key_, const DBT *val_, void *extra) { WrappedCallback *wc = static_cast<WrappedCallback *>(extra); return wc->call(key_, val_); } int call(const DBT *key_, const DBT *val_) { return _cb(Slice(*key_), Slice(*val_)); } } wc(cb); DBT kdbt = key.dbt(); return _db->getf_set(_db, txn.txn(), flags, &kdbt, &WrappedCallback::call, &wc); } int put(const DBTxn &txn, DBT *key, DBT *val, int flags=0) const { return _db->put(_db, txn.txn(), key, val, flags); } int put(const DBTxn &txn, const Slice &key, const Slice &val, int flags=0) const { DBT kdbt = key.dbt(); DBT vdbt = val.dbt(); return put(txn, &kdbt, &vdbt, flags); } int del(const DBTxn &txn, DBT *key, int flags=0) const { return _db->del(_db, txn.txn(), key, flags); } int del(const DBTxn &txn, const Slice &key, int flags=0) const { DBT kdbt = key.dbt(); return _db->del(_db, txn.txn(), &kdbt, flags); } Stats get_stats() const { Stats stats; DB_BTREE_STAT64 s = {0, 0, 0}; int r = _db->stat64(_db, NULL, &s); handle_ft_retval(r); stats.dataSize = s.bt_dsize; stats.fileSize = s.bt_fsize; stats.numberOfKeys = s.bt_nkeys; return stats; } struct NullFilter { bool operator()(const Slice &, const Slice &) { return true; } }; /** * Constructs a Cursor over this DB, over the range from left to * right (or right to left if !forward). */ template<class Comparator, class Handler> CallbackCursor<Comparator, Handler> cursor(const DBTxn &txn, DBT *left, DBT *right, Comparator &&cmp, Handler &&handler, int flags=0, bool forward=true, bool end_exclusive=false, bool prelock=true) const; template<class Comparator, class Handler> CallbackCursor<Comparator, Handler> cursor(const DBTxn &txn, const Slice &left, const Slice &right, Comparator &&cmp, Handler &&handler, int flags=0, bool forward=true, bool end_exclusive=false, bool prelock=true) const; template<class Comparator, class Handler> CallbackCursor<Comparator, Handler> cursor(const DBTxn &txn, Comparator &&cmp, Handler &&handler, int flags=0, bool forward=true, bool prelock=true) const; template<class Comparator, class Predicate> BufferedCursor<Comparator, Predicate> buffered_cursor(const DBTxn &txn, DBT *left, DBT *right, Comparator &&cmp, Predicate &&filter, int flags=0, bool forward=true, bool end_exclusive=false, bool prelock=true) const; template<class Comparator, class Predicate> BufferedCursor<Comparator, Predicate> buffered_cursor(const DBTxn &txn, const Slice &left, const Slice &right, Comparator &&cmp, Predicate &&filter, int flags=0, bool forward=true, bool end_exclusive=false, bool prelock=true) const; template<class Comparator, class Predicate> BufferedCursor<Comparator, Predicate> buffered_cursor(const DBTxn &txn, Comparator &&cmp, Predicate &&filter, int flags=0, bool forward=true, bool prelock=true) const; template<class Comparator> SimpleCursor<Comparator> simple_cursor(const DBTxn &txn, DBT *left, DBT *right, Comparator &&cmp, Slice &key, Slice &val, int flags=0, bool forward=true, bool end_exclusive=false, bool prelock=true) const; template<class Comparator> SimpleCursor<Comparator> simple_cursor(const DBTxn &txn, const Slice &left, const Slice &right, Comparator &&cmp, Slice &key, Slice &val, int flags=0, bool forward=true, bool end_exclusive=false, bool prelock=true) const; template<class Comparator> SimpleCursor<Comparator> simple_cursor(const DBTxn &txn, Comparator &&cmp, Slice &key, Slice &val, int flags=0, bool forward=true, bool prelock=true) const; void close() { int r = _db->close(_db, 0); handle_ft_retval(r); _db = nullptr; } private: ::DB *_db; bool _close_on_destroy; }; class DBBuilder { uint32_t _readpagesize; TOKU_COMPRESSION_METHOD _compression_method; uint32_t _fanout; uint8_t _memcmp_magic; uint32_t _pagesize; Slice _descriptor; public: DBBuilder() : _readpagesize(0), _compression_method(TOKU_COMPRESSION_METHOD(0)), _fanout(0), _memcmp_magic(0), _pagesize(0), _descriptor() {} DB open(const DBEnv &env, const DBTxn &txn, const char *fname, const char *dbname, DBTYPE dbtype, uint32_t flags, int mode) const { ::DB *db; int r = db_create(&db, env.env(), 0); handle_ft_retval(r); if (_readpagesize) { r = db->set_readpagesize(db, _readpagesize); handle_ft_retval(r); } if (_compression_method) { r = db->set_compression_method(db, _compression_method); handle_ft_retval(r); } if (_fanout) { r = db->set_fanout(db, _fanout); handle_ft_retval(r); } if (_memcmp_magic) { r = db->set_memcmp_magic(db, _memcmp_magic); handle_ft_retval(r); } if (_pagesize) { r = db->set_pagesize(db, _pagesize); handle_ft_retval(r); } r = db->open(db, txn.txn(), fname, dbname, dbtype, flags, mode); handle_ft_retval(r); if (!_descriptor.empty()) { DBT desc = _descriptor.dbt(); r = db->change_descriptor(db, txn.txn(), &desc, DB_UPDATE_CMP_DESCRIPTOR); handle_ft_retval(r); } return DB(db, true); } DBBuilder& set_readpagesize(uint32_t readpagesize) { _readpagesize = readpagesize; return *this; } DBBuilder& set_compression_method(TOKU_COMPRESSION_METHOD _compressionmethod) { _compression_method = _compressionmethod; return *this; } DBBuilder& set_fanout(uint32_t fanout) { _fanout = fanout; return *this; } DBBuilder& set_memcmp_magic(uint8_t _memcmpmagic) { _memcmp_magic = _memcmpmagic; return *this; } DBBuilder& set_pagesize(uint32_t pagesize) { _pagesize = pagesize; return *this; } DBBuilder& set_descriptor(const Slice &desc) { _descriptor = desc; return *this; } }; } // namespace ftcxx <|endoftext|>
<commit_before>// #include <stdexcept> // #include <string> #include "function.hxx" function::operator double () const { return _fptr(_args); } void function::replace(const unsigned idx, const fnbase_ptr arg) { // if (idx >= _args.size()) // throw std::out_of_range("Index out of range, " + std::to_string(idx) // + " >= " + std::to_string(_args.size()) + "\n"); _args.at(idx) = arg; } auto function::components() -> fnbase_vec & { return _args; } <commit_msg>Handle range checking myself<commit_after>#include <stdexcept> #include <string> #include "function.hxx" function::operator double () const { return _fptr(_args); } void function::replace(const unsigned idx, const fnbase_ptr arg) { if (idx >= _args.size()) throw std::out_of_range("Index out of range: " + std::to_string(_args.size()) + "(size) <= " + std::to_string(idx) + "(index)"); _args.at(idx) = arg; } auto function::components() -> fnbase_vec & { return _args; } <|endoftext|>
<commit_before>// // PROJECT: Aspia Remote Desktop // FILE: host/file_transfer_session_client.cc // LICENSE: Mozilla Public License Version 2.0 // PROGRAMMERS: Dmitry Chapyshev (dmitry@aspia.ru) // #include "host/file_transfer_session_client.h" #include "base/files/file_helpers.h" #include "base/strings/unicode.h" #include "protocol/message_serialization.h" #include "protocol/filesystem.h" #include "proto/auth_session.pb.h" namespace aspia { namespace fs = std::experimental::filesystem; void FileTransferSessionClient::Run(const std::wstring& input_channel_name, const std::wstring& output_channel_name) { status_dialog_ = std::make_unique<UiFileStatusDialog>(); ipc_channel_ = PipeChannel::CreateClient(input_channel_name, output_channel_name); if (ipc_channel_) { if (ipc_channel_->Connect(GetCurrentProcessId(), this)) { status_dialog_->WaitForClose(); } ipc_channel_.reset(); } status_dialog_.reset(); } void FileTransferSessionClient::OnPipeChannelConnect(uint32_t user_data) { // The server sends the session type in user_data. proto::SessionType session_type = static_cast<proto::SessionType>(user_data); if (session_type != proto::SessionType::SESSION_TYPE_FILE_TRANSFER) { LOG(FATAL) << "Invalid session type passed: " << session_type; return; } status_dialog_->SetSessionStartedStatus(); } void FileTransferSessionClient::OnPipeChannelDisconnect() { status_dialog_->SetSessionTerminatedStatus(); } void FileTransferSessionClient::OnPipeChannelMessage(const IOBuffer& buffer) { proto::file_transfer::ClientToHost message; if (!ParseMessage(buffer, message)) { ipc_channel_->Close(); return; } switch (message.type()) { case proto::RequestType::REQUEST_TYPE_DRIVE_LIST: ReadDriveListRequest(); break; case proto::RequestType::REQUEST_TYPE_FILE_LIST: ReadFileListRequest(message.file_list_request()); break; case proto::RequestType::REQUEST_TYPE_DIRECTORY_SIZE: ReadDirectorySizeRequest(message.directory_size_request()); break; case proto::RequestType::REQUEST_TYPE_CREATE_DIRECTORY: ReadCreateDirectoryRequest(message.create_directory_request()); break; case proto::RequestType::REQUEST_TYPE_RENAME: ReadRenameRequest(message.rename_request()); break; case proto::RequestType::REQUEST_TYPE_REMOVE: ReadRemoveRequest(message.remove_request()); break; case proto::RequestType::REQUEST_TYPE_FILE_UPLOAD: ReadFileUploadRequest(message.file_upload_request()); break; case proto::RequestType::REQUEST_TYPE_FILE_UPLOAD_DATA: { if (!ReadFileUploadDataRequest(message.file_packet())) ipc_channel_->Close(); } break; case proto::RequestType::REQUEST_TYPE_FILE_DOWNLOAD: ReadFileDownloadRequest(message.file_download_request()); break; case proto::RequestType::REQUEST_TYPE_FILE_DOWNLOAD_DATA: { if (!ReadFileDownloadDataRequest()) ipc_channel_->Close(); } break; default: LOG(ERROR) << "Unknown message from client: " << message.type(); ipc_channel_->Close(); break; } } void FileTransferSessionClient::SendReply( const proto::file_transfer::HostToClient& reply) { IOBuffer buffer(SerializeMessage<IOBuffer>(reply)); std::lock_guard<std::mutex> lock(outgoing_lock_); ipc_channel_->Send(buffer); } void FileTransferSessionClient::ReadDriveListRequest() { proto::file_transfer::HostToClient reply; reply.set_type(proto::RequestType::REQUEST_TYPE_DRIVE_LIST); reply.set_status(ExecuteDriveListRequest(reply.mutable_drive_list())); status_dialog_->SetDriveListRequestStatus(reply.status()); SendReply(reply); } void FileTransferSessionClient::ReadFileListRequest( const proto::FileListRequest& request) { proto::file_transfer::HostToClient reply; FilePath path = fs::u8path(request.path()); reply.set_type(proto::RequestType::REQUEST_TYPE_FILE_LIST); reply.set_status(ExecuteFileListRequest(path, reply.mutable_file_list())); status_dialog_->SetFileListRequestStatus(path, reply.status()); SendReply(reply); } void FileTransferSessionClient::ReadCreateDirectoryRequest( const proto::CreateDirectoryRequest& request) { proto::file_transfer::HostToClient reply; FilePath path = fs::u8path(request.path()); reply.set_type(proto::RequestType::REQUEST_TYPE_CREATE_DIRECTORY); reply.set_status(ExecuteCreateDirectoryRequest(path)); status_dialog_->SetCreateDirectoryRequestStatus(path, reply.status()); SendReply(reply); } void FileTransferSessionClient::ReadDirectorySizeRequest( const proto::DirectorySizeRequest& request) { proto::file_transfer::HostToClient reply; FilePath path = fs::u8path(request.path()); reply.set_type(proto::RequestType::REQUEST_TYPE_DIRECTORY_SIZE); uint64_t directory_size = 0; reply.set_status(ExecuteDirectorySizeRequest(path, directory_size)); reply.mutable_directory_size()->set_size(directory_size); SendReply(reply); } void FileTransferSessionClient::ReadRenameRequest( const proto::RenameRequest& request) { proto::file_transfer::HostToClient reply; FilePath old_name = fs::u8path(request.old_name()); FilePath new_name = fs::u8path(request.new_name()); reply.set_type(proto::RequestType::REQUEST_TYPE_RENAME); reply.set_status(ExecuteRenameRequest(old_name, new_name)); status_dialog_->SetRenameRequestStatus(old_name, new_name, reply.status()); SendReply(reply); } void FileTransferSessionClient::ReadRemoveRequest( const proto::RemoveRequest& request) { proto::file_transfer::HostToClient reply; FilePath path = fs::u8path(request.path()); reply.set_type(proto::RequestType::REQUEST_TYPE_REMOVE); reply.set_status(ExecuteRemoveRequest(path)); status_dialog_->SetRemoveRequestStatus(path, reply.status()); SendReply(reply); } void FileTransferSessionClient::ReadFileUploadRequest( const proto::FileUploadRequest& request) { proto::file_transfer::HostToClient reply; reply.set_type(proto::RequestType::REQUEST_TYPE_FILE_UPLOAD); FilePath file_path = fs::u8path(request.file_path()); if (!IsValidPathName(file_path)) { reply.set_status(proto::RequestStatus::REQUEST_STATUS_INVALID_PATH_NAME); } else { file_depacketizer_ = FileDepacketizer::Create(file_path); if (!file_depacketizer_) { reply.set_status(proto::RequestStatus::REQUEST_STATUS_FILE_CREATE_ERROR); } } status_dialog_->SetFileUploadRequestStatus(file_path, reply.status()); SendReply(reply); } bool FileTransferSessionClient::ReadFileUploadDataRequest( const proto::FilePacket& file_packet) { if (!file_depacketizer_) { LOG(ERROR) << "Unexpected upload data request"; return false; } proto::file_transfer::HostToClient reply; reply.set_type(proto::RequestType::REQUEST_TYPE_FILE_UPLOAD_DATA); if (!file_depacketizer_->ReadNextPacket(file_packet)) { reply.set_status(proto::RequestStatus::REQUEST_STATUS_FILE_WRITE_ERROR); } if (file_packet.flags() & proto::FilePacket::LAST_PACKET) { file_depacketizer_.reset(); } SendReply(reply); return true; } void FileTransferSessionClient::ReadFileDownloadRequest( const proto::FileDownloadRequest& request) { proto::file_transfer::HostToClient reply; reply.set_type(proto::RequestType::REQUEST_TYPE_FILE_DOWNLOAD); FilePath file_path = fs::u8path(request.file_path()); if (!IsValidPathName(file_path)) { reply.set_status(proto::RequestStatus::REQUEST_STATUS_INVALID_PATH_NAME); } else { file_packetizer_ = FilePacketizer::Create(file_path); if (!file_packetizer_) { reply.set_status(proto::RequestStatus::REQUEST_STATUS_FILE_OPEN_ERROR); } } SendReply(reply); } bool FileTransferSessionClient::ReadFileDownloadDataRequest() { if (!file_packetizer_) { LOG(ERROR) << "Unexpected download data request"; return false; } proto::file_transfer::HostToClient reply; reply.set_type(proto::RequestType::REQUEST_TYPE_FILE_DOWNLOAD_DATA); std::unique_ptr<proto::FilePacket> packet = file_packetizer_->CreateNextPacket(); if (!packet) { reply.set_status(proto::RequestStatus::REQUEST_STATUS_FILE_READ_ERROR); } else { if (packet->flags() & proto::FilePacket::LAST_PACKET) { file_packetizer_.reset(); } reply.set_allocated_file_packet(packet.release()); } SendReply(reply); return true; } } // namespace aspia <commit_msg>Added file existence check<commit_after>// // PROJECT: Aspia Remote Desktop // FILE: host/file_transfer_session_client.cc // LICENSE: Mozilla Public License Version 2.0 // PROGRAMMERS: Dmitry Chapyshev (dmitry@aspia.ru) // #include "host/file_transfer_session_client.h" #include "base/files/file_helpers.h" #include "base/strings/unicode.h" #include "protocol/message_serialization.h" #include "protocol/filesystem.h" #include "proto/auth_session.pb.h" namespace aspia { namespace fs = std::experimental::filesystem; void FileTransferSessionClient::Run(const std::wstring& input_channel_name, const std::wstring& output_channel_name) { status_dialog_ = std::make_unique<UiFileStatusDialog>(); ipc_channel_ = PipeChannel::CreateClient(input_channel_name, output_channel_name); if (ipc_channel_) { if (ipc_channel_->Connect(GetCurrentProcessId(), this)) { status_dialog_->WaitForClose(); } ipc_channel_.reset(); } status_dialog_.reset(); } void FileTransferSessionClient::OnPipeChannelConnect(uint32_t user_data) { // The server sends the session type in user_data. proto::SessionType session_type = static_cast<proto::SessionType>(user_data); if (session_type != proto::SESSION_TYPE_FILE_TRANSFER) { LOG(FATAL) << "Invalid session type passed: " << session_type; return; } status_dialog_->SetSessionStartedStatus(); } void FileTransferSessionClient::OnPipeChannelDisconnect() { status_dialog_->SetSessionTerminatedStatus(); } void FileTransferSessionClient::OnPipeChannelMessage(const IOBuffer& buffer) { proto::file_transfer::ClientToHost message; if (!ParseMessage(buffer, message)) { ipc_channel_->Close(); return; } switch (message.type()) { case proto::REQUEST_TYPE_DRIVE_LIST: ReadDriveListRequest(); break; case proto::REQUEST_TYPE_FILE_LIST: ReadFileListRequest(message.file_list_request()); break; case proto::REQUEST_TYPE_DIRECTORY_SIZE: ReadDirectorySizeRequest(message.directory_size_request()); break; case proto::REQUEST_TYPE_CREATE_DIRECTORY: ReadCreateDirectoryRequest(message.create_directory_request()); break; case proto::REQUEST_TYPE_RENAME: ReadRenameRequest(message.rename_request()); break; case proto::REQUEST_TYPE_REMOVE: ReadRemoveRequest(message.remove_request()); break; case proto::REQUEST_TYPE_FILE_UPLOAD: ReadFileUploadRequest(message.file_upload_request()); break; case proto::REQUEST_TYPE_FILE_UPLOAD_DATA: { if (!ReadFileUploadDataRequest(message.file_packet())) ipc_channel_->Close(); } break; case proto::REQUEST_TYPE_FILE_DOWNLOAD: ReadFileDownloadRequest(message.file_download_request()); break; case proto::REQUEST_TYPE_FILE_DOWNLOAD_DATA: { if (!ReadFileDownloadDataRequest()) ipc_channel_->Close(); } break; default: LOG(ERROR) << "Unknown message from client: " << message.type(); ipc_channel_->Close(); break; } } void FileTransferSessionClient::SendReply( const proto::file_transfer::HostToClient& reply) { IOBuffer buffer(SerializeMessage<IOBuffer>(reply)); std::lock_guard<std::mutex> lock(outgoing_lock_); ipc_channel_->Send(buffer); } void FileTransferSessionClient::ReadDriveListRequest() { proto::file_transfer::HostToClient reply; reply.set_type(proto::REQUEST_TYPE_DRIVE_LIST); reply.set_status(ExecuteDriveListRequest(reply.mutable_drive_list())); status_dialog_->SetDriveListRequestStatus(reply.status()); SendReply(reply); } void FileTransferSessionClient::ReadFileListRequest( const proto::FileListRequest& request) { proto::file_transfer::HostToClient reply; FilePath path = fs::u8path(request.path()); reply.set_type(proto::REQUEST_TYPE_FILE_LIST); reply.set_status(ExecuteFileListRequest(path, reply.mutable_file_list())); status_dialog_->SetFileListRequestStatus(path, reply.status()); SendReply(reply); } void FileTransferSessionClient::ReadCreateDirectoryRequest( const proto::CreateDirectoryRequest& request) { proto::file_transfer::HostToClient reply; FilePath path = fs::u8path(request.path()); reply.set_type(proto::REQUEST_TYPE_CREATE_DIRECTORY); reply.set_status(ExecuteCreateDirectoryRequest(path)); status_dialog_->SetCreateDirectoryRequestStatus(path, reply.status()); SendReply(reply); } void FileTransferSessionClient::ReadDirectorySizeRequest( const proto::DirectorySizeRequest& request) { proto::file_transfer::HostToClient reply; FilePath path = fs::u8path(request.path()); reply.set_type(proto::REQUEST_TYPE_DIRECTORY_SIZE); uint64_t directory_size = 0; reply.set_status(ExecuteDirectorySizeRequest(path, directory_size)); reply.mutable_directory_size()->set_size(directory_size); SendReply(reply); } void FileTransferSessionClient::ReadRenameRequest( const proto::RenameRequest& request) { proto::file_transfer::HostToClient reply; FilePath old_name = fs::u8path(request.old_name()); FilePath new_name = fs::u8path(request.new_name()); reply.set_type(proto::REQUEST_TYPE_RENAME); reply.set_status(ExecuteRenameRequest(old_name, new_name)); status_dialog_->SetRenameRequestStatus(old_name, new_name, reply.status()); SendReply(reply); } void FileTransferSessionClient::ReadRemoveRequest( const proto::RemoveRequest& request) { proto::file_transfer::HostToClient reply; FilePath path = fs::u8path(request.path()); reply.set_type(proto::REQUEST_TYPE_REMOVE); reply.set_status(ExecuteRemoveRequest(path)); status_dialog_->SetRemoveRequestStatus(path, reply.status()); SendReply(reply); } void FileTransferSessionClient::ReadFileUploadRequest( const proto::FileUploadRequest& request) { proto::file_transfer::HostToClient reply; reply.set_type(proto::REQUEST_TYPE_FILE_UPLOAD); FilePath file_path = fs::u8path(request.file_path()); if (!IsValidPathName(file_path)) { reply.set_status(proto::REQUEST_STATUS_INVALID_PATH_NAME); } else { std::error_code code; if (fs::exists(file_path, code)) { reply.set_status(proto::REQUEST_STATUS_PATH_ALREADY_EXISTS); } else { file_depacketizer_ = FileDepacketizer::Create(file_path); if (!file_depacketizer_) { reply.set_status(proto::REQUEST_STATUS_FILE_CREATE_ERROR); } } } status_dialog_->SetFileUploadRequestStatus(file_path, reply.status()); SendReply(reply); } bool FileTransferSessionClient::ReadFileUploadDataRequest( const proto::FilePacket& file_packet) { if (!file_depacketizer_) { LOG(ERROR) << "Unexpected upload data request"; return false; } proto::file_transfer::HostToClient reply; reply.set_type(proto::REQUEST_TYPE_FILE_UPLOAD_DATA); if (!file_depacketizer_->ReadNextPacket(file_packet)) { reply.set_status(proto::REQUEST_STATUS_FILE_WRITE_ERROR); } if (file_packet.flags() & proto::FilePacket::LAST_PACKET) { file_depacketizer_.reset(); } SendReply(reply); return true; } void FileTransferSessionClient::ReadFileDownloadRequest( const proto::FileDownloadRequest& request) { proto::file_transfer::HostToClient reply; reply.set_type(proto::REQUEST_TYPE_FILE_DOWNLOAD); FilePath file_path = fs::u8path(request.file_path()); if (!IsValidPathName(file_path)) { reply.set_status(proto::REQUEST_STATUS_INVALID_PATH_NAME); } else { file_packetizer_ = FilePacketizer::Create(file_path); if (!file_packetizer_) { reply.set_status(proto::REQUEST_STATUS_FILE_OPEN_ERROR); } } SendReply(reply); } bool FileTransferSessionClient::ReadFileDownloadDataRequest() { if (!file_packetizer_) { LOG(ERROR) << "Unexpected download data request"; return false; } proto::file_transfer::HostToClient reply; reply.set_type(proto::REQUEST_TYPE_FILE_DOWNLOAD_DATA); std::unique_ptr<proto::FilePacket> packet = file_packetizer_->CreateNextPacket(); if (!packet) { reply.set_status(proto::REQUEST_STATUS_FILE_READ_ERROR); } else { if (packet->flags() & proto::FilePacket::LAST_PACKET) { file_packetizer_.reset(); } reply.set_allocated_file_packet(packet.release()); } SendReply(reply); return true; } } // namespace aspia <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "QmitkViewInitialization.h" #include "QmitkViewInitializationControls.h" #include "icon.xpm" #include <qaction.h> #include <qbuttongroup.h> #include <qcheckbox.h> #include <QmitkStdMultiWidget.h> #include <QmitkSelectableGLWidget.h> #include <QmitkRenderWindowSelector.h> #include <mitkSliceNavigationController.h> QmitkViewInitialization::QmitkViewInitialization(QObject *parent, const char *name, QmitkStdMultiWidget *mitkStdMultiWidget, mitk::DataTreeIteratorBase* it) : QmitkFunctionality(parent, name, it), m_MultiWidget(mitkStdMultiWidget), m_Controls(NULL) { SetAvailability(true); } QmitkViewInitialization::~QmitkViewInitialization() { } QWidget * QmitkViewInitialization::CreateMainWidget(QWidget * /*parent*/) { return NULL; } QWidget * QmitkViewInitialization::CreateControlWidget(QWidget *parent) { if (m_Controls == NULL) { m_Controls = new QmitkViewInitializationControls(parent); } return m_Controls; } void QmitkViewInitialization::CreateConnections() { if ( m_Controls ) { connect( (QObject*)(m_Controls->pbApply), SIGNAL(clicked()),(QObject*) this, SLOT(Apply()) ); connect( (QObject*)(m_Controls->pbReset), SIGNAL(clicked()),(QObject*) this, SLOT(ResetAll()) ); } } QAction * QmitkViewInitialization::CreateAction(QActionGroup *parent) { QAction* action; action = new QAction( tr( "change view initialization" ), QPixmap((const char**)icon_xpm), tr( "&View Initialization" ), 0, parent, "ViewInitialization" ); return action; } void QmitkViewInitialization::Activated() { QmitkFunctionality::Activated(); } void QmitkViewInitialization::Apply() { mitk::SliceNavigationController::ViewDirection viewDirection; switch ( m_Controls->bgOrientation->selectedId() ) { default: case 0: viewDirection = mitk::SliceNavigationController::Transversal; break; case 1: viewDirection = mitk::SliceNavigationController::Frontal; break; case 2: viewDirection = mitk::SliceNavigationController::Sagittal; break; } mitk::RenderWindow* renderwindow = m_Controls->m_RenderWindowSelector->GetSelectedRenderWindow(); if(renderwindow != NULL) { renderwindow->GetSliceNavigationController()->Update(viewDirection, m_Controls->cbTop->isChecked(), m_Controls->cbFrontSide->isChecked(), m_Controls->cbRotated->isChecked() ); renderwindow->GetRenderer()->GetDisplayGeometry()->Fit(); } } void QmitkViewInitialization::ResetAll() { m_MultiWidget->ReInitializeStandardViews(); } <commit_msg>COMP: adapt to Qt-Vtk render mechanism<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "QmitkViewInitialization.h" #include "QmitkViewInitializationControls.h" #include "icon.xpm" #include <qaction.h> #include <qbuttongroup.h> #include <qcheckbox.h> #include <QmitkStdMultiWidget.h> #include <QmitkSelectableGLWidget.h> #include <QmitkRenderWindowSelector.h> #include <mitkSliceNavigationController.h> QmitkViewInitialization::QmitkViewInitialization(QObject *parent, const char *name, QmitkStdMultiWidget *mitkStdMultiWidget, mitk::DataTreeIteratorBase* it) : QmitkFunctionality(parent, name, it), m_MultiWidget(mitkStdMultiWidget), m_Controls(NULL) { SetAvailability(true); } QmitkViewInitialization::~QmitkViewInitialization() { } QWidget * QmitkViewInitialization::CreateMainWidget(QWidget * /*parent*/) { return NULL; } QWidget * QmitkViewInitialization::CreateControlWidget(QWidget *parent) { if (m_Controls == NULL) { m_Controls = new QmitkViewInitializationControls(parent); } return m_Controls; } void QmitkViewInitialization::CreateConnections() { if ( m_Controls ) { connect( (QObject*)(m_Controls->pbApply), SIGNAL(clicked()),(QObject*) this, SLOT(Apply()) ); connect( (QObject*)(m_Controls->pbReset), SIGNAL(clicked()),(QObject*) this, SLOT(ResetAll()) ); } } QAction * QmitkViewInitialization::CreateAction(QActionGroup *parent) { QAction* action; action = new QAction( tr( "change view initialization" ), QPixmap((const char**)icon_xpm), tr( "&View Initialization" ), 0, parent, "ViewInitialization" ); return action; } void QmitkViewInitialization::Activated() { QmitkFunctionality::Activated(); } void QmitkViewInitialization::Apply() { mitk::SliceNavigationController::ViewDirection viewDirection; switch ( m_Controls->bgOrientation->selectedId() ) { default: case 0: viewDirection = mitk::SliceNavigationController::Transversal; break; case 1: viewDirection = mitk::SliceNavigationController::Frontal; break; case 2: viewDirection = mitk::SliceNavigationController::Sagittal; break; } vtkRenderWindow* renderwindow = m_Controls->m_RenderWindowSelector->GetSelectedRenderWindow(); if(renderwindow != NULL) { mitk::BaseRenderer::GetInstance(renderwindow)->GetSliceNavigationController()->Update(viewDirection, m_Controls->cbTop->isChecked(), m_Controls->cbFrontSide->isChecked(), m_Controls->cbRotated->isChecked() ); mitk::BaseRenderer::GetInstance(renderwindow)->GetDisplayGeometry()->Fit(); } } void QmitkViewInitialization::ResetAll() { m_MultiWidget->ReInitializeStandardViews(); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: elements.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: kz $ $Date: 2004-12-16 11:47:13 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #if !defined INCLUDED_JVMFWK_ELEMENTS_HXX #define INCLUDED_JVMFWK_ELEMENTS_HXX #include <vector> #include "jvmfwk/framework.h" #include "rtl/ustring.hxx" #include "rtl/byteseq.hxx" #include "libxml/parser.h" #define NS_JAVA_FRAMEWORK "http://openoffice.org/2004/java/framework/1.0" #define NS_SCHEMA_INSTANCE "http://www.w3.org/2001/XMLSchema-instance" namespace jfw { xmlNode* findChildNode(const xmlNode * pParent, const xmlChar* pName); /** gets the value of the updated element from the javavendors.xml. */ rtl::OString getElementUpdated(); /** creates the javasettings.xml in the users home directory. If javasettings.xml does not exist then it creates the file and inserts the root element with its namespaces. The content should look like this: <?xml version="1.0" encoding="UTF-8"?> <!--This is a generated file. Do not alter this file!--> <java xmlns:="http://openoffice.org/2004/java/framework/1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> </java> */ void createUserSettingsDocument(); /** create the child elements within the root structure for each platform. @param bNeedsSave [out]If true then the respective structure of elements was added and the document needs to be saved. */ void createSettingsStructure( xmlDoc * document, bool * bNeedsSave); /** copies shared settings to user settings. This must only occur the first time when the javasettings.xml is prepared for the user. The shared settings shall be provided as bootstrap parameters. @param userParent The node under which the values are to be copied. */ void copyShareSettings(xmlDoc * userDoc, xmlNode* userParent); /** creates the structure of the documend. When this function is called the first time for a user then it creates the javasettings.xml in th ~/<office>/user/config/ unless it already exists (see createUserSettingsDocument). Then it creates a section for the current platform unless it already exist and creates all children elements. If the respective platform section did not exist then after creating the children, the values from the share/config/javasettings.xml are copied. @return JFW_E_CONFIG_READWRITE */ void prepareSettingsDocument(); class CXmlCharPtr; class CNodeJavaInfo { public: CNodeJavaInfo(); ~CNodeJavaInfo(); /** sUpdated is the value from the <updated> element from the javavendors.xml. */ CNodeJavaInfo(const JavaInfo * pInfo); /** if true, then javaInfo is empty. When writeToNode is called then all child elements are deleted. */ bool m_bEmptyNode; /** Contains the value of the <updated> element of the javavendors.xml after loadFromNode was called. It is not used, when the javaInfo node is written. see writeToNode */ rtl::OString sAttrVendorUpdate; /** contains the nil value of the /java/javaInfo@xsi:nil attribute. Default is true; */ bool bNil; /** contains the value of the /java/javaInfo@autoSelect attribute. Default is true. If it is false then the user has modified the JRE selection by actively choosing a JRE from the options dialog. That is, the function jfw_setSelectedJRE was called. Contrary, the function jfw_findAndSelectJRE sets the attribute to true. */ bool bAutoSelect; rtl::OUString sVendor; rtl::OUString sLocation; rtl::OUString sVersion; sal_uInt64 nFeatures; sal_uInt64 nRequirements; rtl::ByteSequence arVendorData; /** reads the node /java/javaInfo. If javaInfo@xsi:nil = true then member bNil is set to true an no further elements are read. */ void loadFromNode(xmlDoc * pDoc,xmlNode * pJavaInfo); /** Only writes user settings. The attribut nil always gets the value false. The function gets the value javaSettings/updated from the javavendors.xml and writes it to javaInfo@vendorUpdate in javasettings.xml */ void writeToNode(xmlDoc * pDoc, xmlNode * pJavaInfo) const; /** returns NULL if javaInfo is nil in both, user and share, settings. */ JavaInfo * makeJavaInfo() const; }; /** this class represents the javasettings.xml file */ class CNodeJava { /** Share settings are a special case. Per default there are only user settings. Currently there need not be a share settings file. In that case the function returns without throwing an exception. */ void loadShareSettings(); /** This function is called after loadShareSettings. Elements which have been modified by the user, that is, the attribute xsi:nil = false, overwrite the values which have been retrieved with loadShareSettings. */ void loadUserSettings(); /** User configurable option. /java/enabled The value is valid after loadFromSettings has been called successfully. The value is that of the user setting. If it is nil (/java/enabled[@xsi:nil = true]) then it represents the share setting. If there are no share settings or the node is also nil then the default is true. */ sal_Bool m_bEnabled; /** Determines if m_bEnabled has been modified */ bool m_bEnabledModified; /** User configurable option. /java/userClassPath The value is valid after loadFromSettings has been called successfully. The value is that of the user setting. If it is nil (/java/userClassPath[@xsi:nil = true]) then it represents the share setting. If there are no share settings or the node is also nil then the default is an empty string. */ rtl::OUString m_sUserClassPath; /** Determines if m_sUserClassPath has been modified */ bool m_bUserClassPathModified; /** User configurable option. /java/javaInfo The value is valid after loadFromSettings has been called successfully. The value is that of the user setting. If it is nil (/java/javaInfo[@xsi:nil = true]) then it represents the share setting. If there are no share settings then the structure is regarded as empty. */ CNodeJavaInfo m_aInfo; /** Determines if m_aInfo has been modified */ bool m_bJavaInfoModified; /** User configurable option. /java/vmParameters The value is valid after loadFromSettings has been called successfully. The value is that of the user setting. If it is nil (/java/vmParameters[@xsi:nil = true]) then it represents the share setting. If there are no share settings then array is empty. */ std::vector<rtl::OString> m_arVmParameters; bool m_bVmParametersModified; /** User configurable option. /java/jreLocations The value is valid after loadFromSettings has been called successfully. The value is that of the user setting. If it is nil (/java/jreLocations[@xsi:nil = true]) then it represents the share setting. If there are no share settings then array is empty. */ std::vector<rtl::OString> m_arJRELocations; bool m_bJRELocationsModified; public: CNodeJava(); /** sets m_bEnabled. It also sets a flag, that the value has been modified. This will cause that /java/enabled[@xsi:nil] will be set to false. The nil value and the value of enabled are only written when write Settings is called. */ void setEnabled(sal_Bool bEnabled); /** returns the value of the element /java/enabled */ sal_Bool getEnabled() const; /** sets m_sUserClassPath. Analog to setEnabled. */ void setUserClassPath(const rtl::OUString & sClassPath); /** returns the value of the element /java/userClassPath. */ rtl::OUString const & getUserClassPath() const; /** sets m_aInfo. Analog to setEnabled. @param bAutoSelect true- called by jfw_setSelectedJRE false called by jfw_findAndSelectJRE */ void setJavaInfo(const JavaInfo * pInfo, bool bAutoSelect); /** returns a JavaInfo structure representing the node /java/javaInfo. Every time a new JavaInfo structure is created which needs to be freed by the caller. If both, user and share settings are nil, then NULL is returned. */ JavaInfo * createJavaInfo() const; /** returns the value of the attribute /java/javaInfo[@vendorUpdate]. */ rtl::OString const & getJavaInfoAttrVendorUpdate() const; /** returns the javaInfo@autoSelect attribute. Before calling this function loadFromSettings must be called. It uses the javaInfo@autoSelect attribute to determine the return value; */ bool getJavaInfoAttrAutoSelect() const; /** sets the /java/vmParameters/param elements. The values are kept in a vector m_arVmParameters. When this method is called then the vector is cleared and the new values are inserted. The xsi:nil attribute of vmParameters will be set to true; */ void setVmParameters(rtl_uString * * arParameters, sal_Int32 size); /** returns the parameters from the element /java/vmParameters/param. */ const std::vector<rtl::OString> & getVmParameters() const; /** returns an array. Caller must free the strings and the array. */ void getVmParametersArray(rtl_uString *** parParameters, sal_Int32 * size) const; /** sets the /java/jreLocations/location elements. The values are kept in a vector m_arJRELocations. When this method is called then the vector is cleared and the new values are inserted. The xsi:nil attribute of vmParameters will be set to true; */ void setJRELocations(rtl_uString * * arParameters, sal_Int32 size); void addJRELocation(rtl_uString * sLocation); /** returns the parameters from the element /java/jreLocations/location. */ const std::vector<rtl::OString> & getJRELocations() const; /** returns an array. Caller must free the strings and the array. */ void getJRELocations(rtl_uString *** parLocations, sal_Int32 * size) const; /** reads user and share settings. user data supersede share data. These elements can be changed by the user: <enabled>, <userClasspath>, <javaInfo>, <vmParameters> If the user has not changed them then the nil attribute is set to true; */ void loadFromSettings(); /** writes the data to user settings. */ void writeSettings() const; }; class VersionInfo { std::vector<rtl::OUString> vecExcludeVersions; rtl_uString ** arVersions; public: VersionInfo(); ~VersionInfo(); void addExcludeVersion(const rtl::OUString& sVersion); rtl::OUString sMinVersion; rtl::OUString sMaxVersion; /** The caller DOES NOT get ownership of the strings. That is he does not need to release the strings. The array exists as long as this object exists. */ rtl_uString** getExcludeVersions(); sal_Int32 getExcludeVersionSize(); }; struct PluginLibrary { PluginLibrary() { } PluginLibrary(rtl::OUString vendor, rtl::OUString path) : sVendor(vendor), sPath(path) { } /** contains the vendor string which is later userd in the xml API */ rtl::OUString sVendor; /** File URL the plug-in library */ rtl::OUString sPath; }; } //end namespace #endif <commit_msg>INTEGRATION: CWS ooo19126 (1.8.34); FILE MERGED 2005/09/05 17:12:27 rt 1.8.34.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: elements.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: rt $ $Date: 2005-09-07 19:34: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 * ************************************************************************/ #if !defined INCLUDED_JVMFWK_ELEMENTS_HXX #define INCLUDED_JVMFWK_ELEMENTS_HXX #include <vector> #include "jvmfwk/framework.h" #include "rtl/ustring.hxx" #include "rtl/byteseq.hxx" #include "libxml/parser.h" #define NS_JAVA_FRAMEWORK "http://openoffice.org/2004/java/framework/1.0" #define NS_SCHEMA_INSTANCE "http://www.w3.org/2001/XMLSchema-instance" namespace jfw { xmlNode* findChildNode(const xmlNode * pParent, const xmlChar* pName); /** gets the value of the updated element from the javavendors.xml. */ rtl::OString getElementUpdated(); /** creates the javasettings.xml in the users home directory. If javasettings.xml does not exist then it creates the file and inserts the root element with its namespaces. The content should look like this: <?xml version="1.0" encoding="UTF-8"?> <!--This is a generated file. Do not alter this file!--> <java xmlns:="http://openoffice.org/2004/java/framework/1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> </java> */ void createUserSettingsDocument(); /** create the child elements within the root structure for each platform. @param bNeedsSave [out]If true then the respective structure of elements was added and the document needs to be saved. */ void createSettingsStructure( xmlDoc * document, bool * bNeedsSave); /** copies shared settings to user settings. This must only occur the first time when the javasettings.xml is prepared for the user. The shared settings shall be provided as bootstrap parameters. @param userParent The node under which the values are to be copied. */ void copyShareSettings(xmlDoc * userDoc, xmlNode* userParent); /** creates the structure of the documend. When this function is called the first time for a user then it creates the javasettings.xml in th ~/<office>/user/config/ unless it already exists (see createUserSettingsDocument). Then it creates a section for the current platform unless it already exist and creates all children elements. If the respective platform section did not exist then after creating the children, the values from the share/config/javasettings.xml are copied. @return JFW_E_CONFIG_READWRITE */ void prepareSettingsDocument(); class CXmlCharPtr; class CNodeJavaInfo { public: CNodeJavaInfo(); ~CNodeJavaInfo(); /** sUpdated is the value from the <updated> element from the javavendors.xml. */ CNodeJavaInfo(const JavaInfo * pInfo); /** if true, then javaInfo is empty. When writeToNode is called then all child elements are deleted. */ bool m_bEmptyNode; /** Contains the value of the <updated> element of the javavendors.xml after loadFromNode was called. It is not used, when the javaInfo node is written. see writeToNode */ rtl::OString sAttrVendorUpdate; /** contains the nil value of the /java/javaInfo@xsi:nil attribute. Default is true; */ bool bNil; /** contains the value of the /java/javaInfo@autoSelect attribute. Default is true. If it is false then the user has modified the JRE selection by actively choosing a JRE from the options dialog. That is, the function jfw_setSelectedJRE was called. Contrary, the function jfw_findAndSelectJRE sets the attribute to true. */ bool bAutoSelect; rtl::OUString sVendor; rtl::OUString sLocation; rtl::OUString sVersion; sal_uInt64 nFeatures; sal_uInt64 nRequirements; rtl::ByteSequence arVendorData; /** reads the node /java/javaInfo. If javaInfo@xsi:nil = true then member bNil is set to true an no further elements are read. */ void loadFromNode(xmlDoc * pDoc,xmlNode * pJavaInfo); /** Only writes user settings. The attribut nil always gets the value false. The function gets the value javaSettings/updated from the javavendors.xml and writes it to javaInfo@vendorUpdate in javasettings.xml */ void writeToNode(xmlDoc * pDoc, xmlNode * pJavaInfo) const; /** returns NULL if javaInfo is nil in both, user and share, settings. */ JavaInfo * makeJavaInfo() const; }; /** this class represents the javasettings.xml file */ class CNodeJava { /** Share settings are a special case. Per default there are only user settings. Currently there need not be a share settings file. In that case the function returns without throwing an exception. */ void loadShareSettings(); /** This function is called after loadShareSettings. Elements which have been modified by the user, that is, the attribute xsi:nil = false, overwrite the values which have been retrieved with loadShareSettings. */ void loadUserSettings(); /** User configurable option. /java/enabled The value is valid after loadFromSettings has been called successfully. The value is that of the user setting. If it is nil (/java/enabled[@xsi:nil = true]) then it represents the share setting. If there are no share settings or the node is also nil then the default is true. */ sal_Bool m_bEnabled; /** Determines if m_bEnabled has been modified */ bool m_bEnabledModified; /** User configurable option. /java/userClassPath The value is valid after loadFromSettings has been called successfully. The value is that of the user setting. If it is nil (/java/userClassPath[@xsi:nil = true]) then it represents the share setting. If there are no share settings or the node is also nil then the default is an empty string. */ rtl::OUString m_sUserClassPath; /** Determines if m_sUserClassPath has been modified */ bool m_bUserClassPathModified; /** User configurable option. /java/javaInfo The value is valid after loadFromSettings has been called successfully. The value is that of the user setting. If it is nil (/java/javaInfo[@xsi:nil = true]) then it represents the share setting. If there are no share settings then the structure is regarded as empty. */ CNodeJavaInfo m_aInfo; /** Determines if m_aInfo has been modified */ bool m_bJavaInfoModified; /** User configurable option. /java/vmParameters The value is valid after loadFromSettings has been called successfully. The value is that of the user setting. If it is nil (/java/vmParameters[@xsi:nil = true]) then it represents the share setting. If there are no share settings then array is empty. */ std::vector<rtl::OString> m_arVmParameters; bool m_bVmParametersModified; /** User configurable option. /java/jreLocations The value is valid after loadFromSettings has been called successfully. The value is that of the user setting. If it is nil (/java/jreLocations[@xsi:nil = true]) then it represents the share setting. If there are no share settings then array is empty. */ std::vector<rtl::OString> m_arJRELocations; bool m_bJRELocationsModified; public: CNodeJava(); /** sets m_bEnabled. It also sets a flag, that the value has been modified. This will cause that /java/enabled[@xsi:nil] will be set to false. The nil value and the value of enabled are only written when write Settings is called. */ void setEnabled(sal_Bool bEnabled); /** returns the value of the element /java/enabled */ sal_Bool getEnabled() const; /** sets m_sUserClassPath. Analog to setEnabled. */ void setUserClassPath(const rtl::OUString & sClassPath); /** returns the value of the element /java/userClassPath. */ rtl::OUString const & getUserClassPath() const; /** sets m_aInfo. Analog to setEnabled. @param bAutoSelect true- called by jfw_setSelectedJRE false called by jfw_findAndSelectJRE */ void setJavaInfo(const JavaInfo * pInfo, bool bAutoSelect); /** returns a JavaInfo structure representing the node /java/javaInfo. Every time a new JavaInfo structure is created which needs to be freed by the caller. If both, user and share settings are nil, then NULL is returned. */ JavaInfo * createJavaInfo() const; /** returns the value of the attribute /java/javaInfo[@vendorUpdate]. */ rtl::OString const & getJavaInfoAttrVendorUpdate() const; /** returns the javaInfo@autoSelect attribute. Before calling this function loadFromSettings must be called. It uses the javaInfo@autoSelect attribute to determine the return value; */ bool getJavaInfoAttrAutoSelect() const; /** sets the /java/vmParameters/param elements. The values are kept in a vector m_arVmParameters. When this method is called then the vector is cleared and the new values are inserted. The xsi:nil attribute of vmParameters will be set to true; */ void setVmParameters(rtl_uString * * arParameters, sal_Int32 size); /** returns the parameters from the element /java/vmParameters/param. */ const std::vector<rtl::OString> & getVmParameters() const; /** returns an array. Caller must free the strings and the array. */ void getVmParametersArray(rtl_uString *** parParameters, sal_Int32 * size) const; /** sets the /java/jreLocations/location elements. The values are kept in a vector m_arJRELocations. When this method is called then the vector is cleared and the new values are inserted. The xsi:nil attribute of vmParameters will be set to true; */ void setJRELocations(rtl_uString * * arParameters, sal_Int32 size); void addJRELocation(rtl_uString * sLocation); /** returns the parameters from the element /java/jreLocations/location. */ const std::vector<rtl::OString> & getJRELocations() const; /** returns an array. Caller must free the strings and the array. */ void getJRELocations(rtl_uString *** parLocations, sal_Int32 * size) const; /** reads user and share settings. user data supersede share data. These elements can be changed by the user: <enabled>, <userClasspath>, <javaInfo>, <vmParameters> If the user has not changed them then the nil attribute is set to true; */ void loadFromSettings(); /** writes the data to user settings. */ void writeSettings() const; }; class VersionInfo { std::vector<rtl::OUString> vecExcludeVersions; rtl_uString ** arVersions; public: VersionInfo(); ~VersionInfo(); void addExcludeVersion(const rtl::OUString& sVersion); rtl::OUString sMinVersion; rtl::OUString sMaxVersion; /** The caller DOES NOT get ownership of the strings. That is he does not need to release the strings. The array exists as long as this object exists. */ rtl_uString** getExcludeVersions(); sal_Int32 getExcludeVersionSize(); }; struct PluginLibrary { PluginLibrary() { } PluginLibrary(rtl::OUString vendor, rtl::OUString path) : sVendor(vendor), sPath(path) { } /** contains the vendor string which is later userd in the xml API */ rtl::OUString sVendor; /** File URL the plug-in library */ rtl::OUString sPath; }; } //end namespace #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2013 Nicholas Corgan (n.corgan@gmail.com) * * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt * or copy at http://opensource.org/licenses/MIT) */ #include "team_analysis_common.hpp" #include <boost/assign.hpp> #include <boost/format.hpp> #include <boost/program_options.hpp> #include <fstream> #include <iostream> #include <map> #include <pkmnsim/base_pkmn.hpp> #include <pkmnsim/pkmn_types.hpp> #include <stdexcept> #include <string> #include <vector> //TODO: take move types into account //TODO: take counter-effectiveness into account namespace po = boost::program_options; using namespace pkmnsim; using namespace std; void print_help(po::variables_map vm, po::options_description desc) { cout << endl << "Team Analysis - " << desc << endl; cout << "Point the --team_file option at a file with" << endl << "one Pokémon name on each line. Using Lance's" << endl << "first team from Fire Red/Leaf Green as an" << endl << "example:" << endl << endl << "Gyarados" << endl << "Dragonair" << endl << "Dragonair" << endl << "Aerodactyl" << endl << "Dragonite" << endl << endl; } string get_pkmn_effectiveness_string(string pkmn_name, map<string, double> &effectiveness_map) { string output_string = str(boost::format(" * %s") % pkmn_name); string good_types_str = " * Use:"; string bad_types_str = " * Don't use:"; //Iterate over map and add to good/bad_types_str as appropriate for(sd_iter i = effectiveness_map.begin(); i != effectiveness_map.end(); ++i) { if(i->second > 1.0) good_types_str = str(boost::format("%s %s,") % good_types_str % i->first); else if(i->second < 1.0) bad_types_str = str(boost::format("%s %s,") % bad_types_str % i->first); } //Cut off final comma from good/bad_types_str good_types_str = good_types_str.substr(0, good_types_str.size()-1); bad_types_str = bad_types_str.substr(0, bad_types_str.size()-1); //Only add good/bad_types_str onto output string if applicable if(good_types_str != " * Use") output_string = str(boost::format("%s\n%s") % output_string % good_types_str); if(bad_types_str != " * Don't use") output_string = str(boost::format("%s\n%s") % output_string % bad_types_str); return output_string; } string get_trends_string(map<string, int> &super_effective_map, map<string, int> &not_very_effective_map) { string output_string = " * Use:"; for(si_iter i = super_effective_map.begin(); i != super_effective_map.end(); ++i) { if(i->second > 1) output_string = str(boost::format("%s %s,") % output_string % i->first); } output_string = output_string.substr(0, output_string.size()-1); output_string = str(boost::format("%s\n * Don't use:") % output_string); for(si_iter i = not_very_effective_map.begin(); i != not_very_effective_map.end(); ++i) { if(i->second > 1) output_string = str(boost::format("%s %s,") % output_string % i->first); } output_string = output_string.substr(0, output_string.size()-1); return output_string; } int main(int argc, char *argv[]) { //Taking in and processing user options string team_file; int gen; po::options_description desc("Allowed Options"); desc.add_options() ("help", "Display this help message.") ("team_file", po::value<string>(&team_file), "Specify a file with a Pokémon team.") ("gen", po::value<int>(&gen)->default_value(5), "Specify a generation (1-5).") ("verbose", "Enable verbosity.") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); //Process help or user mistake if(vm.count("help") > 0) { print_help(vm, desc); return EXIT_FAILURE; } if(vm.count("team_file") == 0) throw runtime_error("Specify a team file. Run \"team_analysis --help\" for information."); if(gen < 1 or gen > 5) throw runtime_error("Gen must be 1-5."); bool verbose = (vm.count("verbose") > 0); ifstream team_file_input(team_file.c_str(), ifstream::in); if(team_file_input.fail()) throw runtime_error("Specified file doesn't exist."); string pkmn_name; //Get Pokémon team and output vector<base_pkmn::sptr> pkmn_team; int count = 0; cout << "Analyzing team..." << endl << endl; while(getline(team_file_input,pkmn_name)) { if(count > 6) break; pkmn_team.push_back(base_pkmn::make(pkmn_name, gen, true)); if(verbose) cout << "Successfully added Pokémon: " << pkmn_name << endl; count++; } if(verbose) cout << endl; team_file_input.close(); cout << "Team:" << endl; for(int i = 0; i < pkmn_team.size(); i++) { string pkmn_name = pkmn_team[i]->get_display_name(); string type1 = pkmn_team[i]->get_types()[0]; string type2 = pkmn_team[i]->get_types()[1]; if(type2 == "None") cout << boost::format(" * %s (%s)\n") % pkmn_name % type1; else cout << boost::format(" * %s (%s/%s)\n") % pkmn_name % type1 % type2; } cout << endl; //Get type overlaps and output vector<string> type_list = get_type_names(gen); map<string, int> type_overlaps = get_type_overlaps(pkmn_team, type_list); cout << "Type overlaps:" << endl; for(si_iter i = type_overlaps.begin(); i != type_overlaps.end(); ++i) { cout << boost::format(" * %s (%d)\n") % i->first % i->second; } //Get type mods for each Pokémon and output map<string, map<string, double> > team_mod_map; for(int i = 0; i < pkmn_team.size(); i++) //Iterate over Pokémon team { string pkmn_name = pkmn_team[i]->get_display_name(); map<string, double> mod_map; for(int j = 0; j < type_list.size(); j++) //Iterate over type list { string type_name = type_list[j]; string pkmn_type1 = pkmn_team[i]->get_types()[0]; string pkmn_type2 = pkmn_team[i]->get_types()[1]; bool is_gen1 = (gen == 1); mod_map[type_name] = get_type_damage_mod(type_name, pkmn_type1, is_gen1); if(pkmn_type2 != "None") { mod_map[type_name] *= get_type_damage_mod(type_name, pkmn_type2, is_gen1); } } team_mod_map[pkmn_name] = mod_map; } cout << endl << "Individual weaknesses/resistances:" << endl; for(int i = 0; i < pkmn_team.size(); i++) { string pkmn_name = pkmn_team[i]->get_display_name(); string output_string = get_pkmn_effectiveness_string(pkmn_name, team_mod_map[pkmn_name]); cout << output_string << endl; } //Get number of super effective types and not very effective types map<string, int> super_effective_map; map<string, int> not_very_effective_map; for(int i = 0; i < pkmn_team.size(); i++) { string pkmn_name = pkmn_team[i]->get_display_name(); for(int j = 0; j < type_list.size(); j++) { string type_name = type_list[j]; if(type_name != "Shadow" and type_name != "None" and type_name != "???") //Don't use nonstandard types { if(team_mod_map[pkmn_name][type_name] < 1.0) not_very_effective_map[type_name]++; //Not very effective else if(team_mod_map[pkmn_name][type_name] > 1.0) super_effective_map[type_name]++; } } } trim_effectiveness_maps(super_effective_map, not_very_effective_map); string trends_string = get_trends_string(super_effective_map, not_very_effective_map); cout << endl << "Trends:" << endl << trends_string << endl << endl; return EXIT_SUCCESS; } <commit_msg>team_analysis: only allow a team of six members<commit_after>/* * Copyright (c) 2013 Nicholas Corgan (n.corgan@gmail.com) * * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt * or copy at http://opensource.org/licenses/MIT) */ #include "team_analysis_common.hpp" #include <boost/assign.hpp> #include <boost/format.hpp> #include <boost/program_options.hpp> #include <fstream> #include <iostream> #include <map> #include <pkmnsim/base_pkmn.hpp> #include <pkmnsim/pkmn_types.hpp> #include <stdexcept> #include <string> #include <vector> //TODO: take move types into account //TODO: take counter-effectiveness into account namespace po = boost::program_options; using namespace pkmnsim; using namespace std; void print_help(po::variables_map vm, po::options_description desc) { cout << endl << "Team Analysis - " << desc << endl; cout << "Point the --team_file option at a file with" << endl << "one Pokémon name on each line. Using Lance's" << endl << "first team from Fire Red/Leaf Green as an" << endl << "example:" << endl << endl << "Gyarados" << endl << "Dragonair" << endl << "Dragonair" << endl << "Aerodactyl" << endl << "Dragonite" << endl << endl; } string get_pkmn_effectiveness_string(string pkmn_name, map<string, double> &effectiveness_map) { string output_string = str(boost::format(" * %s") % pkmn_name); string good_types_str = " * Use:"; string bad_types_str = " * Don't use:"; //Iterate over map and add to good/bad_types_str as appropriate for(sd_iter i = effectiveness_map.begin(); i != effectiveness_map.end(); ++i) { if(i->second > 1.0) good_types_str = str(boost::format("%s %s,") % good_types_str % i->first); else if(i->second < 1.0) bad_types_str = str(boost::format("%s %s,") % bad_types_str % i->first); } //Cut off final comma from good/bad_types_str good_types_str = good_types_str.substr(0, good_types_str.size()-1); bad_types_str = bad_types_str.substr(0, bad_types_str.size()-1); //Only add good/bad_types_str onto output string if applicable if(good_types_str != " * Use") output_string = str(boost::format("%s\n%s") % output_string % good_types_str); if(bad_types_str != " * Don't use") output_string = str(boost::format("%s\n%s") % output_string % bad_types_str); return output_string; } string get_trends_string(map<string, int> &super_effective_map, map<string, int> &not_very_effective_map) { string output_string = " * Use:"; for(si_iter i = super_effective_map.begin(); i != super_effective_map.end(); ++i) { if(i->second > 1) output_string = str(boost::format("%s %s,") % output_string % i->first); } output_string = output_string.substr(0, output_string.size()-1); output_string = str(boost::format("%s\n * Don't use:") % output_string); for(si_iter i = not_very_effective_map.begin(); i != not_very_effective_map.end(); ++i) { if(i->second > 1) output_string = str(boost::format("%s %s,") % output_string % i->first); } output_string = output_string.substr(0, output_string.size()-1); return output_string; } int main(int argc, char *argv[]) { //Taking in and processing user options string team_file; int gen; po::options_description desc("Allowed Options"); desc.add_options() ("help", "Display this help message.") ("team_file", po::value<string>(&team_file), "Specify a file with a Pokémon team.") ("gen", po::value<int>(&gen)->default_value(5), "Specify a generation (1-5).") ("verbose", "Enable verbosity.") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); //Process help or user mistake if(vm.count("help") > 0) { print_help(vm, desc); return EXIT_FAILURE; } if(vm.count("team_file") == 0) throw runtime_error("Specify a team file. Run \"team_analysis --help\" for information."); if(gen < 1 or gen > 5) throw runtime_error("Gen must be 1-5."); bool verbose = (vm.count("verbose") > 0); ifstream team_file_input(team_file.c_str(), ifstream::in); if(team_file_input.fail()) throw runtime_error("Specified file doesn't exist."); string pkmn_name; //Get Pokémon team and output vector<base_pkmn::sptr> pkmn_team; int count = 0; cout << "Analyzing team..." << endl << endl; while(getline(team_file_input,pkmn_name)) { //A team can only have six members if(count > 6) break; pkmn_team.push_back(base_pkmn::make(pkmn_name, gen, true)); if(verbose) cout << "Successfully added Pokémon: " << pkmn_name << endl; count++; } if(verbose) cout << endl; team_file_input.close(); cout << "Team:" << endl; for(int i = 0; i < pkmn_team.size(); i++) { if(i > 5) break; string pkmn_name = pkmn_team[i]->get_display_name(); string type1 = pkmn_team[i]->get_types()[0]; string type2 = pkmn_team[i]->get_types()[1]; if(type2 == "None") cout << boost::format(" * %s (%s)\n") % pkmn_name % type1; else cout << boost::format(" * %s (%s/%s)\n") % pkmn_name % type1 % type2; } cout << endl; //Get type overlaps and output vector<string> type_list = get_type_names(gen); map<string, int> type_overlaps = get_type_overlaps(pkmn_team, type_list); cout << "Type overlaps:" << endl; for(si_iter i = type_overlaps.begin(); i != type_overlaps.end(); ++i) { cout << boost::format(" * %s (%d)\n") % i->first % i->second; } //Get type mods for each Pokémon and output map<string, map<string, double> > team_mod_map; for(int i = 0; i < pkmn_team.size(); i++) //Iterate over Pokémon team { string pkmn_name = pkmn_team[i]->get_display_name(); map<string, double> mod_map; for(int j = 0; j < type_list.size(); j++) //Iterate over type list { string type_name = type_list[j]; string pkmn_type1 = pkmn_team[i]->get_types()[0]; string pkmn_type2 = pkmn_team[i]->get_types()[1]; bool is_gen1 = (gen == 1); mod_map[type_name] = get_type_damage_mod(type_name, pkmn_type1, is_gen1); if(pkmn_type2 != "None") { mod_map[type_name] *= get_type_damage_mod(type_name, pkmn_type2, is_gen1); } } team_mod_map[pkmn_name] = mod_map; } cout << endl << "Individual weaknesses/resistances:" << endl; for(int i = 0; i < pkmn_team.size(); i++) { string pkmn_name = pkmn_team[i]->get_display_name(); string output_string = get_pkmn_effectiveness_string(pkmn_name, team_mod_map[pkmn_name]); cout << output_string << endl; } //Get number of super effective types and not very effective types map<string, int> super_effective_map; map<string, int> not_very_effective_map; for(int i = 0; i < pkmn_team.size(); i++) { string pkmn_name = pkmn_team[i]->get_display_name(); for(int j = 0; j < type_list.size(); j++) { string type_name = type_list[j]; if(type_name != "Shadow" and type_name != "None" and type_name != "???") //Don't use nonstandard types { if(team_mod_map[pkmn_name][type_name] < 1.0) not_very_effective_map[type_name]++; //Not very effective else if(team_mod_map[pkmn_name][type_name] > 1.0) super_effective_map[type_name]++; } } } trim_effectiveness_maps(super_effective_map, not_very_effective_map); string trends_string = get_trends_string(super_effective_map, not_very_effective_map); cout << endl << "Trends:" << endl << trends_string << endl << endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include <dual_quaternion.hpp> #include <knn_point_cloud.hpp> #include <kfusion/types.hpp> #include <nanoflann.hpp> #include "kfusion/warp_field.hpp" #include "internal.hpp" #include "precomp.hpp" #include <opencv2/core/affine.hpp> #define VOXEL_SIZE 100 using namespace kfusion; std::vector<utils::DualQuaternion<float>> neighbours; //THIS SHOULD BE SOMEWHERE ELSE BUT TOO SLOW TO REINITIALISE utils::PointCloud cloud; WarpField::WarpField() { index = new kd_tree_t(3, cloud, nanoflann::KDTreeSingleIndexAdaptorParams(10)); ret_index = std::vector<size_t>(KNN_NEIGHBOURS); out_dist_sqr = std::vector<float>(KNN_NEIGHBOURS); resultSet = new nanoflann::KNNResultSet<float>(KNN_NEIGHBOURS); resultSet->init(&ret_index[0], &out_dist_sqr[0]); neighbours = std::vector<utils::DualQuaternion<float>>(KNN_NEIGHBOURS); } WarpField::~WarpField() {} /** * * @param frame * \note The pose is assumed to be the identity, as this is the first frame */ // maybe remove this later and do everything as part of energy since all this code is written twice. Leave it for now. void WarpField::init(const cv::Mat& first_frame, const cv::Mat& normals) { assert(first_frame.rows == normals.rows); assert(first_frame.cols == normals.cols); nodes.resize(first_frame.cols * first_frame.rows); for(int i = 0; i < first_frame.rows; i++) for(int j = 0; j < first_frame.cols; j++) { auto point = first_frame.at<Point>(i,j); auto norm = normals.at<Normal>(i,j); if(!std::isnan(point.x)) { nodes[i*first_frame.cols+j].transform = utils::DualQuaternion<float>(utils::Quaternion<float>(0,point.x, point.y, point.z), utils::Quaternion<float>(Vec3f(norm.x,norm.y,norm.z))); nodes[i*first_frame.cols+j].vertex = Vec3f(point.x,point.y,point.z); nodes[i*first_frame.cols+j].weight = VOXEL_SIZE; } else { nodes[i*first_frame.cols+j].valid = false; } } buildKDTree(); } /** * \brief * \param frame * \param normals * \param pose * \param tsdfVolume * \param edges */ void WarpField::energy(const cuda::Cloud &frame, const cuda::Normals &normals, const Affine3f &pose, const cuda::TsdfVolume &tsdfVolume, const std::vector<std::pair<utils::DualQuaternion<float>, utils::DualQuaternion<float>>> &edges ) { assert(normals.cols()==frame.cols()); assert(normals.rows()==frame.rows()); int cols = frame.cols(); std::vector<Point, std::allocator<Point>> cloud_host(size_t(frame.rows()*frame.cols())); frame.download(cloud_host, cols); std::vector<Normal, std::allocator<Normal>> normals_host(size_t(normals.rows()*normals.cols())); normals.download(normals_host, cols); for(size_t i = 0; i < cloud_host.size() && i < nodes.size(); i++) { break; auto point = cloud_host[i]; auto norm = normals_host[i]; if(!std::isnan(point.x)) { } else { // std::cout<<"NANS"<<std::endl; // break; } } // if (m_pWarpField->getNumNodesInLevel(0) == 0) // { // printf("no warp nodes, return\n"); // return FLT_MAX; // } // // m_vmap_warp = &vmap_warp; // m_nmap_warp = &nmap_warp; // m_vmap_live = &vmap_live; // m_nmap_live = &nmap_live; // // // perform Gauss-Newton iteration // //for (int k = 0; k < 100; k++) // float totalEnergy = 0.f, data_energy=0.f, reg_energy=0.f; // m_pWarpField->extract_nodes_info_no_allocation(m_nodesKnn, m_twist, m_nodesVw); // for (int iter = 0; iter < m_param->fusion_GaussNewton_maxIter; iter++) // { // // m_Hd = 0.f; // cudaSafeCall(cudaMemset(m_g.ptr(), 0, sizeof(float)*m_g.size()), // "GpuGaussNewtonSolver::solve, setg=0"); // // checkNan(m_twist, m_numNodes, ("twist_" + std::to_string(iter)).c_str()); // // // 1. calculate data term: Hd += Jd'Jd; g += Jd'fd // // 2. calculate reg term: Jr = [Jr0 Jr1; 0 Jr3]; fr; // // 3. calculate Hessian: Hd += Jr0'Jr0; B = Jr0'Jr1; Hr = Jr1'Jr1 + Jr3'Jr3; g=-(g+Jr'*fr) // // 4. solve H*h = g // if (m_param->graph_single_level) // singleLevelSolve(); // else // blockSolve() // // if not fix step, we perform line search // if (m_param->fusion_GaussNewton_fixedStep <= 0.f) // { // float old_energy = calcTotalEnergy(data_energy, reg_energy); // float new_energy = 0.f; // float alpha = 1.f; // const static float alpha_stop = 1e-2; // cudaSafeCall(cudaMemcpy(m_tmpvec.ptr(), m_twist.ptr(), m_Jr->cols()*sizeof(float), // cudaMemcpyDeviceToDevice), "copy tmp vec to twist"); // for (; alpha > alpha_stop; alpha *= 0.5) // { // // x += alpha * h // updateTwist_inch(m_h.ptr(), alpha); // new_energy = calcTotalEnergy(data_energy, reg_energy); // if (new_energy < old_energy) // break; // // reset x // cudaSafeCall(cudaMemcpy(m_twist.ptr(), m_tmpvec.ptr(), // m_Jr->cols()*sizeof(float), cudaMemcpyDeviceToDevice), "copy twist to tmp vec"); // } // totalEnergy = new_energy; // if (alpha <= alpha_stop) // break; // float norm_h = 0.f, norm_g = 0.f; // cublasStatus_t st = cublasSnrm2(m_cublasHandle, m_Jr->cols(), // m_h.ptr(), 1, &norm_h); // st = cublasSnrm2(m_cublasHandle, m_Jr->cols(), // m_g.ptr(), 1, &norm_g); // if (norm_h < (norm_g + 1e-6f) * 1e-6f) // break; // } // // else, we perform fixed step update. // else // { // // 5. accumulate: x += step * h; // updateTwist_inch(m_h.ptr(), m_param->fusion_GaussNewton_fixedStep); // } // }// end for iter // // if (m_param->fusion_GaussNewton_fixedStep > 0.f) // totalEnergy = calcTotalEnergy(data_energy, reg_energy); // // if (data_energy_) // *data_energy_ = data_energy; // if (reg_energy_) // *reg_energy_ = reg_energy; // // return totalEnergy; //} } /** * \brief * \param frame * \param pose * \param tsdfVolume */ void WarpField::energy_data(Vec3f v, Vec3f n ) { if (std::isnan(n[0]) || std::isnan(v[0])) return; } /** * \brief * \param frame * \param pose * \param tsdfVolume */ void WarpField::energy_data(const cuda::Depth &frame, const Affine3f &pose, const cuda::TsdfVolume &tsdfVolume ) { // const int x = threadIdx.x + blockIdx.x * blockDim.x; // const int y = threadIdx.y + blockIdx.y * blockDim.y; // if (x >= imgWidth || y >= imgHeight) // return; // // const KnnIdx knn = vmapKnn(y, x); // Tbx::Point3 v(convert(read_float3_4(vmap_cano(y, x)))); // Tbx::Vec3 n(convert(read_float3_4(nmap_cano(y, x)))); // // if (isnan(n.x) || isnan(v.x)) // return; // // // 1. get all nodes params // // 2. compute function // float wk[KnnK]; // auto dq = calc_pixel_dq(knn, v, wk); // float norm_dq = dq.norm(); // if (norm_dq < Tbx::Dual_quat_cu::epsilon()) // return; // auto dq_not_normalized = dq; // dq = dq * (1.f / norm_dq); // normalize // // // compute vl // // // the grad energy // const float f = nwarp.dot(vwarp - vl); //normal * (v-vl) // const float psi_f = data_term_penalty(f); // // // 3. compute jacobi // for (int knnK = 0; knnK < KnnK; knnK++) // { // if (knn_k(knn, knnK) >= nNodes) // break; // float df[6]; // // // 3.0 p_rotation[0:2] // for (int i = 0; i < 3; i++) // { // float inc; // Tbx::Dual_quat_cu dq1 = dq_not_normalized; // exchange_ri_k(knn, wk, knnK, i, dq1, inc); // dq1 *= (1.f / dq1.norm()); // nwarp = Tlw*dq1.rotate(n); // vwarp = Tlw*dq1.transform(v); // // float f1 = nwarp.dot(vwarp - vl); // df[i] = (f1 - f) / inc; // }// i=0:3 // // // 3.1 p_translation[0:2] // for (int i = 0; i < 3; i++) // { // float inc; // Tbx::Dual_quat_cu dq1 = dq_not_normalized; // exchange_ti_k(knn, wk, knnK, i, dq1, inc); // dq1 *= (1.f / dq1.norm()); // nwarp = Tlw*dq1.rotate(n); // vwarp = Tlw*dq1.transform(v); // // float f1 = nwarp.dot(vwarp - vl); // df[i+3] = (f1 - f) / inc; // }// i=0:3 // // //// reduce-------------------------------------------------- // int shift = knn_k(knn, knnK) * VarPerNode2; // int shift_g = knn_k(knn, knnK) * VarPerNode; // for (int i = 0; i < VarPerNode; ++i) // { // for (int j = 0; j <= i; ++j) // atomicAdd(&Hd_[shift + j], df[i] * df[j]); // atomicAdd(&g_[shift_g + i], df[i] * psi_f); // shift += VarPerNode; // } // } } /** * \brief * \param edges */ void WarpField::energy_reg(const std::vector<std::pair<kfusion::utils::DualQuaternion<float>, kfusion::utils::DualQuaternion<float>>> &edges) { } /** * Tukey loss function as described in http://web.as.uky.edu/statistics/users/pbreheny/764-F11/notes/12-1.pdf * \param x * \param c * \return * * \note * The value c = 4.685 is usually used for this loss function, and * it provides an asymptotic efficiency 95% that of linear * regression for the normal distribution */ float WarpField::tukeyPenalty(float x, float c) const { return std::abs(x) <= c ? x * std::pow((1 - (x * x) / (c * c)), 2) : 0.0; } /** * Huber penalty function, implemented as described in https://en.wikipedia.org/wiki/Huber_loss * \param a * \param delta * \return */ float WarpField::huberPenalty(float a, float delta) const { return std::abs(a) <= delta ? a * a / 2 : delta * std::abs(a) - delta * delta / 2; } /** * Modifies the * @param points */ void WarpField::warp(std::vector<Vec3f>& points) const { int i = 0; int nans = 0; for (auto& point : points) { i++; if(std::isnan(point[0]) || std::isnan(point[1]) || std::isnan(point[2])) { nans++; continue; } KNN(point); utils::DualQuaternion<float> dqb = DQB(point); point = warp_to_live * point; // Apply T_lw first. Is this not inverse of the pose? // dqb.transform(point); } } /** * Modifies the * @param points */ void WarpField::warp(cuda::Cloud& points) const { int i = 0; int nans = 0; // for (auto& point : points) // { // i++; // if(std::isnan(point[0]) || std::isnan(point[1]) || std::isnan(point[2])) // { // nans++; // continue; // } // KNN(point); // utils::DualQuaternion<float> dqb = DQB(point); // point = warp_to_live * point; // Apply T_lw first. Is this not inverse of the pose? // dqb.transform(point); // } } /** * \brief * \param vertex * \param weight * \return */ utils::DualQuaternion<float> WarpField::DQB(const Vec3f& vertex) const { utils::DualQuaternion<float> quaternion_sum; for (size_t i = 0; i < KNN_NEIGHBOURS; i++) //FIXME: accessing nodes[ret_index[i]].transform VERY SLOW. Assignment also very slow quaternion_sum = quaternion_sum + weighting(out_dist_sqr[ret_index[i]], nodes[ret_index[i]].weight) * nodes[ret_index[i]].transform; auto norm = quaternion_sum.magnitude(); return utils::DualQuaternion<float>(quaternion_sum.getRotation() / norm.first, quaternion_sum.getTranslation() / norm.second); } /** * \brief * \param squared_dist * \param weight * \return */ float WarpField::weighting(float squared_dist, float weight) const { return (float) exp(-squared_dist / (2 * weight * weight)); } /** * \brief * \return */ void WarpField::KNN(Vec3f point) const { index->findNeighbors(*resultSet, point.val, nanoflann::SearchParams(10)); } /** * \brief * \return */ const std::vector<deformation_node>* WarpField::getNodes() const { return &nodes; } /** * \brief * \return */ void WarpField::buildKDTree() { // Build kd-tree with current warp nodes. cloud.pts.resize(nodes.size()); for(size_t i = 0; i < nodes.size(); i++) nodes[i].transform.getTranslation(cloud.pts[i]); index->buildIndex(); } //TODO: This can be optimised const cv::Mat WarpField::getNodesAsMat() const { cv::Mat matrix(1, nodes.size(), CV_32FC3); for(int i = 0; i < nodes.size(); i++) matrix.at<cv::Vec3f>(i) = nodes[i].vertex; return matrix; } /** * \brief */ void WarpField::clear() { } void WarpField::setWarpToLive(const Affine3f &pose) { warp_to_live = pose; }<commit_msg>Removed commented code<commit_after>#include <dual_quaternion.hpp> #include <knn_point_cloud.hpp> #include <kfusion/types.hpp> #include <nanoflann.hpp> #include "kfusion/warp_field.hpp" #include "internal.hpp" #include "precomp.hpp" #include <opencv2/core/affine.hpp> #define VOXEL_SIZE 100 using namespace kfusion; std::vector<utils::DualQuaternion<float>> neighbours; //THIS SHOULD BE SOMEWHERE ELSE BUT TOO SLOW TO REINITIALISE utils::PointCloud cloud; WarpField::WarpField() { index = new kd_tree_t(3, cloud, nanoflann::KDTreeSingleIndexAdaptorParams(10)); ret_index = std::vector<size_t>(KNN_NEIGHBOURS); out_dist_sqr = std::vector<float>(KNN_NEIGHBOURS); resultSet = new nanoflann::KNNResultSet<float>(KNN_NEIGHBOURS); resultSet->init(&ret_index[0], &out_dist_sqr[0]); neighbours = std::vector<utils::DualQuaternion<float>>(KNN_NEIGHBOURS); } WarpField::~WarpField() {} /** * * @param frame * \note The pose is assumed to be the identity, as this is the first frame */ // maybe remove this later and do everything as part of energy since all this code is written twice. Leave it for now. void WarpField::init(const cv::Mat& first_frame, const cv::Mat& normals) { assert(first_frame.rows == normals.rows); assert(first_frame.cols == normals.cols); nodes.resize(first_frame.cols * first_frame.rows); for(int i = 0; i < first_frame.rows; i++) for(int j = 0; j < first_frame.cols; j++) { auto point = first_frame.at<Point>(i,j); auto norm = normals.at<Normal>(i,j); if(!std::isnan(point.x)) { nodes[i*first_frame.cols+j].transform = utils::DualQuaternion<float>(utils::Quaternion<float>(0,point.x, point.y, point.z), utils::Quaternion<float>(Vec3f(norm.x,norm.y,norm.z))); nodes[i*first_frame.cols+j].vertex = Vec3f(point.x,point.y,point.z); nodes[i*first_frame.cols+j].weight = VOXEL_SIZE; } else { nodes[i*first_frame.cols+j].valid = false; } } buildKDTree(); } /** * \brief * \param frame * \param normals * \param pose * \param tsdfVolume * \param edges */ void WarpField::energy(const cuda::Cloud &frame, const cuda::Normals &normals, const Affine3f &pose, const cuda::TsdfVolume &tsdfVolume, const std::vector<std::pair<utils::DualQuaternion<float>, utils::DualQuaternion<float>>> &edges ) { assert(normals.cols()==frame.cols()); assert(normals.rows()==frame.rows()); int cols = frame.cols(); std::vector<Point, std::allocator<Point>> cloud_host(size_t(frame.rows()*frame.cols())); frame.download(cloud_host, cols); std::vector<Normal, std::allocator<Normal>> normals_host(size_t(normals.rows()*normals.cols())); normals.download(normals_host, cols); for(size_t i = 0; i < cloud_host.size() && i < nodes.size(); i++) { break; auto point = cloud_host[i]; auto norm = normals_host[i]; if(!std::isnan(point.x)) { } else { // std::cout<<"NANS"<<std::endl; // break; } } // if (m_pWarpField->getNumNodesInLevel(0) == 0) // { // printf("no warp nodes, return\n"); // return FLT_MAX; // } // // m_vmap_warp = &vmap_warp; // m_nmap_warp = &nmap_warp; // m_vmap_live = &vmap_live; // m_nmap_live = &nmap_live; // // // perform Gauss-Newton iteration // //for (int k = 0; k < 100; k++) // float totalEnergy = 0.f, data_energy=0.f, reg_energy=0.f; // m_pWarpField->extract_nodes_info_no_allocation(m_nodesKnn, m_twist, m_nodesVw); // for (int iter = 0; iter < m_param->fusion_GaussNewton_maxIter; iter++) // { // // m_Hd = 0.f; // cudaSafeCall(cudaMemset(m_g.ptr(), 0, sizeof(float)*m_g.size()), // "GpuGaussNewtonSolver::solve, setg=0"); // // checkNan(m_twist, m_numNodes, ("twist_" + std::to_string(iter)).c_str()); // // // 1. calculate data term: Hd += Jd'Jd; g += Jd'fd // // 2. calculate reg term: Jr = [Jr0 Jr1; 0 Jr3]; fr; // // 3. calculate Hessian: Hd += Jr0'Jr0; B = Jr0'Jr1; Hr = Jr1'Jr1 + Jr3'Jr3; g=-(g+Jr'*fr) // // 4. solve H*h = g // if (m_param->graph_single_level) // singleLevelSolve(); // else // blockSolve() // // if not fix step, we perform line search // if (m_param->fusion_GaussNewton_fixedStep <= 0.f) // { // float old_energy = calcTotalEnergy(data_energy, reg_energy); // float new_energy = 0.f; // float alpha = 1.f; // const static float alpha_stop = 1e-2; // cudaSafeCall(cudaMemcpy(m_tmpvec.ptr(), m_twist.ptr(), m_Jr->cols()*sizeof(float), // cudaMemcpyDeviceToDevice), "copy tmp vec to twist"); // for (; alpha > alpha_stop; alpha *= 0.5) // { // // x += alpha * h // updateTwist_inch(m_h.ptr(), alpha); // new_energy = calcTotalEnergy(data_energy, reg_energy); // if (new_energy < old_energy) // break; // // reset x // cudaSafeCall(cudaMemcpy(m_twist.ptr(), m_tmpvec.ptr(), // m_Jr->cols()*sizeof(float), cudaMemcpyDeviceToDevice), "copy twist to tmp vec"); // } // totalEnergy = new_energy; // if (alpha <= alpha_stop) // break; // float norm_h = 0.f, norm_g = 0.f; // cublasStatus_t st = cublasSnrm2(m_cublasHandle, m_Jr->cols(), // m_h.ptr(), 1, &norm_h); // st = cublasSnrm2(m_cublasHandle, m_Jr->cols(), // m_g.ptr(), 1, &norm_g); // if (norm_h < (norm_g + 1e-6f) * 1e-6f) // break; // } // // else, we perform fixed step update. // else // { // // 5. accumulate: x += step * h; // updateTwist_inch(m_h.ptr(), m_param->fusion_GaussNewton_fixedStep); // } // }// end for iter // // if (m_param->fusion_GaussNewton_fixedStep > 0.f) // totalEnergy = calcTotalEnergy(data_energy, reg_energy); // // if (data_energy_) // *data_energy_ = data_energy; // if (reg_energy_) // *reg_energy_ = reg_energy; // // return totalEnergy; //} } /** * \brief * \param frame * \param pose * \param tsdfVolume */ void WarpField::energy_data(Vec3f v, Vec3f n ) { if (std::isnan(n[0]) || std::isnan(v[0])) return; } /** * \brief * \param frame * \param pose * \param tsdfVolume */ void WarpField::energy_data(const cuda::Depth &frame, const Affine3f &pose, const cuda::TsdfVolume &tsdfVolume ) { } /** * \brief * \param edges */ void WarpField::energy_reg(const std::vector<std::pair<kfusion::utils::DualQuaternion<float>, kfusion::utils::DualQuaternion<float>>> &edges) { } /** * Tukey loss function as described in http://web.as.uky.edu/statistics/users/pbreheny/764-F11/notes/12-1.pdf * \param x * \param c * \return * * \note * The value c = 4.685 is usually used for this loss function, and * it provides an asymptotic efficiency 95% that of linear * regression for the normal distribution */ float WarpField::tukeyPenalty(float x, float c) const { return std::abs(x) <= c ? x * std::pow((1 - (x * x) / (c * c)), 2) : 0.0; } /** * Huber penalty function, implemented as described in https://en.wikipedia.org/wiki/Huber_loss * \param a * \param delta * \return */ float WarpField::huberPenalty(float a, float delta) const { return std::abs(a) <= delta ? a * a / 2 : delta * std::abs(a) - delta * delta / 2; } /** * Modifies the * @param points */ void WarpField::warp(std::vector<Vec3f>& points) const { int i = 0; int nans = 0; for (auto& point : points) { i++; if(std::isnan(point[0]) || std::isnan(point[1]) || std::isnan(point[2])) { nans++; continue; } KNN(point); utils::DualQuaternion<float> dqb = DQB(point); point = warp_to_live * point; // Apply T_lw first. Is this not inverse of the pose? // dqb.transform(point); } } /** * Modifies the * @param points */ void WarpField::warp(cuda::Cloud& points) const { int i = 0; int nans = 0; // for (auto& point : points) // { // i++; // if(std::isnan(point[0]) || std::isnan(point[1]) || std::isnan(point[2])) // { // nans++; // continue; // } // KNN(point); // utils::DualQuaternion<float> dqb = DQB(point); // point = warp_to_live * point; // Apply T_lw first. Is this not inverse of the pose? // dqb.transform(point); // } } /** * \brief * \param vertex * \param weight * \return */ utils::DualQuaternion<float> WarpField::DQB(const Vec3f& vertex) const { utils::DualQuaternion<float> quaternion_sum; for (size_t i = 0; i < KNN_NEIGHBOURS; i++) //FIXME: accessing nodes[ret_index[i]].transform VERY SLOW. Assignment also very slow quaternion_sum = quaternion_sum + weighting(out_dist_sqr[ret_index[i]], nodes[ret_index[i]].weight) * nodes[ret_index[i]].transform; auto norm = quaternion_sum.magnitude(); return utils::DualQuaternion<float>(quaternion_sum.getRotation() / norm.first, quaternion_sum.getTranslation() / norm.second); } /** * \brief * \param squared_dist * \param weight * \return */ float WarpField::weighting(float squared_dist, float weight) const { return (float) exp(-squared_dist / (2 * weight * weight)); } /** * \brief * \return */ void WarpField::KNN(Vec3f point) const { index->findNeighbors(*resultSet, point.val, nanoflann::SearchParams(10)); } /** * \brief * \return */ const std::vector<deformation_node>* WarpField::getNodes() const { return &nodes; } /** * \brief * \return */ void WarpField::buildKDTree() { // Build kd-tree with current warp nodes. cloud.pts.resize(nodes.size()); for(size_t i = 0; i < nodes.size(); i++) nodes[i].transform.getTranslation(cloud.pts[i]); index->buildIndex(); } //TODO: This can be optimised const cv::Mat WarpField::getNodesAsMat() const { cv::Mat matrix(1, nodes.size(), CV_32FC3); for(int i = 0; i < nodes.size(); i++) matrix.at<cv::Vec3f>(i) = nodes[i].vertex; return matrix; } /** * \brief */ void WarpField::clear() { } void WarpField::setWarpToLive(const Affine3f &pose) { warp_to_live = pose; }<|endoftext|>
<commit_before>#include "musicspectrumlayoutwidget.h" #include "musicuiobject.h" #include <QScrollArea> #include <QSignalMapper> MusicSpectrumLayoutItem::MusicSpectrumLayoutItem(QWidget *parent) : MusicClickedLabel(parent) { setFixedSize(250, 40); QHBoxLayout *layout = new QHBoxLayout(this); layout->setContentsMargins(0, 0, 0, 0); m_box = new QCheckBox(this); m_box->setStyleSheet(MusicUIObject::MCheckBoxStyle01); m_box->setAttribute(Qt::WA_TransparentForMouseEvents); #ifdef Q_OS_UNIX m_box->setFocusPolicy(Qt::NoFocus); #endif m_label = new QLabel(this); m_label->setFixedSize(219, 40); layout->addWidget(m_box); layout->addWidget(m_label); layout->addStretch(1); setLayout(layout); } MusicSpectrumLayoutItem::~MusicSpectrumLayoutItem() { delete m_label; delete m_box; } void MusicSpectrumLayoutItem::addItem(const QString &item, const QString &tip) { m_label->setPixmap(item); setToolTip(tip); } void MusicSpectrumLayoutItem::setCheck(bool check) { m_box->setChecked(check); } bool MusicSpectrumLayoutItem::isChecked() const { return m_box->isChecked(); } MusicSpectrumLayoutWidget::MusicSpectrumLayoutWidget(QWidget *parent) : MusicToolMenuWidget(parent) { initWidget(); } MusicSpectrumLayoutWidget::~MusicSpectrumLayoutWidget() { qDeleteAll(m_items); } void MusicSpectrumLayoutWidget::popupMenu() { m_menu->exec( mapToGlobal(QPoint(-m_containWidget->width() + width(), 0))); } void MusicSpectrumLayoutWidget::labelClicked(int index) { if(m_exclusive) { foreach(MusicSpectrumLayoutItem *item, m_items) { item->setCheck(false); } } const QStringList &types = spectrumTypeList(); bool state = m_items[index]->isChecked(); state = !state; m_items[index]->setCheck(state); Q_EMIT stateChanged(state, types[index]); if(!state) { m_items[index]->setCheck(false); } m_menu->close(); } void MusicSpectrumLayoutWidget::initWidget() { m_exclusive = false; const QString &style = MusicUIObject::MBorderStyle04 + MusicUIObject::MBackgroundStyle17; setObjectName("mianWidget"); setStyleSheet(QString("#mianWidget{%1}").arg(style)); m_containWidget->setFixedSize(270, 220); m_containWidget->setObjectName("containWidget"); m_containWidget->setStyleSheet(QString("#containWidget{%1}").arg(style)); QVBoxLayout *layout = new QVBoxLayout(m_containWidget); layout->setContentsMargins(0, 0, 0, 0); layout->setSpacing(0); QScrollArea *scrollArea = new QScrollArea(m_containWidget); QWidget *containWidget = new QWidget(scrollArea); containWidget->setStyleSheet(MusicUIObject::MBackgroundStyle17); m_containLayout = new QVBoxLayout(containWidget); m_containLayout->setContentsMargins(5, 0, 0, 0); m_containLayout->setSpacing(20); containWidget->setLayout(m_containLayout); scrollArea->setStyleSheet(MusicUIObject::MScrollBarStyle01); scrollArea->setWidgetResizable(true); scrollArea->setFrameShape(QFrame::NoFrame); scrollArea->setAlignment(Qt::AlignLeft); scrollArea->setWidget(containWidget); scrollArea->viewport()->setStyleSheet(MusicUIObject::MBackgroundStyle17); layout->addWidget(scrollArea); m_containWidget->setLayout(layout); } void MusicSpectrumLayoutWidget::addItems(const ItemInfos &items) { QSignalMapper *mapper = new QSignalMapper(this); connect(mapper, SIGNAL(mapped(int)), SLOT(labelClicked(int))); for(int i=0; i<items.count(); ++i) { const ItemInfo &info = items[i]; MusicSpectrumLayoutItem *item = new MusicSpectrumLayoutItem(this); item->addItem(info.first, info.second); connect(item, SIGNAL(clicked()), mapper, SLOT(map())); mapper->setMapping(item, i); m_containLayout->addWidget(item); m_items << item; } } MusicSpectrumNormalLayoutWidget::MusicSpectrumNormalLayoutWidget(QWidget *parent) : MusicSpectrumLayoutWidget(parent) { ItemInfos items; items << ItemInfo(":/spectrum/normal_1", tr("Analyzer")); items << ItemInfo(":/spectrum/normal_2", tr("EWave")); items << ItemInfo(":/spectrum/normal_3", tr("FlowWave")); items << ItemInfo(":/spectrum/normal_4", tr("Histogram")); items << ItemInfo(":/spectrum/normal_5", tr("Line")); items << ItemInfo(":/spectrum/normal_6", tr("SpaceWave")); addItems(items); } MusicSpectrumNormalLayoutWidget::~MusicSpectrumNormalLayoutWidget() { } QStringList MusicSpectrumNormalLayoutWidget::spectrumTypeList() const { return QStringList() << "normalanalyzer" << "normalewave" << "normalflowwave" << "normalhistogram" << "normalline" << "normalspacewave"; } MusicSpectrumPlusLayoutWidget::MusicSpectrumPlusLayoutWidget(QWidget *parent) : MusicSpectrumLayoutWidget(parent) { ItemInfos items; items << ItemInfo(":/spectrum/plus_1", tr("FoldWave")); items << ItemInfo(":/spectrum/plus_2", tr("Monowave")); items << ItemInfo(":/spectrum/plus_3", tr("Multiwave")); items << ItemInfo(":/spectrum/plus_4", tr("XRays")); items << ItemInfo(":/spectrum/plus_5", tr("PointXRays")); items << ItemInfo(":/spectrum/plus_6", tr("VolumeWave")); items << ItemInfo(":/spectrum/plus_7", tr("LightEnvelope")); addItems(items); } MusicSpectrumPlusLayoutWidget::~MusicSpectrumPlusLayoutWidget() { } QStringList MusicSpectrumPlusLayoutWidget::spectrumTypeList() const { return QStringList() << "plusfoldwave" << "plusmonowave" << "plusmultiwave" << "plusxrays" << "pluspointxrays" << "plusvolumewave" << "lightenvelope"; } MusicSpectrumFloridLayoutWidget::MusicSpectrumFloridLayoutWidget(QWidget *parent) : MusicSpectrumLayoutWidget(parent) { m_exclusive = true; ItemInfos items; items << ItemInfo(":/spectrum/florid_1", tr("Goom")); items << ItemInfo(":/spectrum/florid_2", tr("Ethereality")); items << ItemInfo(":/spectrum/florid_3", tr("Reverb")); items << ItemInfo(":/spectrum/florid_4", tr("Autism")); items << ItemInfo(":/spectrum/florid_5", tr("Bass")); items << ItemInfo(":/spectrum/florid_6", tr("Surround")); items << ItemInfo(":/spectrum/florid_7", tr("Ancient")); items << ItemInfo(":/spectrum/florid_8", tr("Electric")); addItems(items); } MusicSpectrumFloridLayoutWidget::~MusicSpectrumFloridLayoutWidget() { } QStringList MusicSpectrumFloridLayoutWidget::spectrumTypeList() const { return QStringList() << "floridgoom" << "floridethereality" << "floridreverb" << "floridautism" << "floridbass" << "floridsurround" << "floridancient" << "floridelectric"; } <commit_msg>Add projectM module[648259]<commit_after>#include "musicspectrumlayoutwidget.h" #include "musicuiobject.h" #include <QScrollArea> #include <QSignalMapper> MusicSpectrumLayoutItem::MusicSpectrumLayoutItem(QWidget *parent) : MusicClickedLabel(parent) { setFixedSize(250, 40); QHBoxLayout *layout = new QHBoxLayout(this); layout->setContentsMargins(0, 0, 0, 0); m_box = new QCheckBox(this); m_box->setStyleSheet(MusicUIObject::MCheckBoxStyle01); m_box->setAttribute(Qt::WA_TransparentForMouseEvents); #ifdef Q_OS_UNIX m_box->setFocusPolicy(Qt::NoFocus); #endif m_label = new QLabel(this); m_label->setFixedSize(219, 40); layout->addWidget(m_box); layout->addWidget(m_label); layout->addStretch(1); setLayout(layout); } MusicSpectrumLayoutItem::~MusicSpectrumLayoutItem() { delete m_label; delete m_box; } void MusicSpectrumLayoutItem::addItem(const QString &item, const QString &tip) { m_label->setPixmap(item); setToolTip(tip); } void MusicSpectrumLayoutItem::setCheck(bool check) { m_box->setChecked(check); } bool MusicSpectrumLayoutItem::isChecked() const { return m_box->isChecked(); } MusicSpectrumLayoutWidget::MusicSpectrumLayoutWidget(QWidget *parent) : MusicToolMenuWidget(parent) { initWidget(); } MusicSpectrumLayoutWidget::~MusicSpectrumLayoutWidget() { qDeleteAll(m_items); } void MusicSpectrumLayoutWidget::popupMenu() { m_menu->exec( mapToGlobal(QPoint(-m_containWidget->width() + width(), 0))); } void MusicSpectrumLayoutWidget::labelClicked(int index) { if(m_exclusive) { foreach(MusicSpectrumLayoutItem *item, m_items) { item->setCheck(false); } } const QStringList &types = spectrumTypeList(); bool state = m_items[index]->isChecked(); state = !state; m_items[index]->setCheck(state); Q_EMIT stateChanged(state, types[index]); if(!state) { m_items[index]->setCheck(false); } m_menu->close(); } void MusicSpectrumLayoutWidget::initWidget() { m_exclusive = false; const QString &style = MusicUIObject::MBorderStyle04 + MusicUIObject::MBackgroundStyle17; setObjectName("mianWidget"); setStyleSheet(QString("#mianWidget{%1}").arg(style)); m_containWidget->setFixedSize(270, 220); m_containWidget->setObjectName("containWidget"); m_containWidget->setStyleSheet(QString("#containWidget{%1}").arg(style)); QVBoxLayout *layout = new QVBoxLayout(m_containWidget); layout->setContentsMargins(0, 0, 0, 0); layout->setSpacing(0); QScrollArea *scrollArea = new QScrollArea(m_containWidget); QWidget *containWidget = new QWidget(scrollArea); containWidget->setStyleSheet(MusicUIObject::MBackgroundStyle17); m_containLayout = new QVBoxLayout(containWidget); m_containLayout->setContentsMargins(5, 0, 0, 0); m_containLayout->setSpacing(20); containWidget->setLayout(m_containLayout); scrollArea->setStyleSheet(MusicUIObject::MScrollBarStyle01); scrollArea->setWidgetResizable(true); scrollArea->setFrameShape(QFrame::NoFrame); scrollArea->setAlignment(Qt::AlignLeft); scrollArea->setWidget(containWidget); scrollArea->viewport()->setStyleSheet(MusicUIObject::MBackgroundStyle17); layout->addWidget(scrollArea); m_containWidget->setLayout(layout); } void MusicSpectrumLayoutWidget::addItems(const ItemInfos &items) { QSignalMapper *mapper = new QSignalMapper(this); connect(mapper, SIGNAL(mapped(int)), SLOT(labelClicked(int))); for(int i=0; i<items.count(); ++i) { const ItemInfo &info = items[i]; MusicSpectrumLayoutItem *item = new MusicSpectrumLayoutItem(this); item->addItem(info.first, info.second); connect(item, SIGNAL(clicked()), mapper, SLOT(map())); mapper->setMapping(item, i); m_containLayout->addWidget(item); m_items << item; } } MusicSpectrumNormalLayoutWidget::MusicSpectrumNormalLayoutWidget(QWidget *parent) : MusicSpectrumLayoutWidget(parent) { ItemInfos items; items << ItemInfo(":/spectrum/normal_1", tr("Analyzer")); items << ItemInfo(":/spectrum/normal_2", tr("EWave")); items << ItemInfo(":/spectrum/normal_3", tr("FlowWave")); items << ItemInfo(":/spectrum/normal_4", tr("Histogram")); items << ItemInfo(":/spectrum/normal_5", tr("Line")); items << ItemInfo(":/spectrum/normal_6", tr("SpaceWave")); addItems(items); } MusicSpectrumNormalLayoutWidget::~MusicSpectrumNormalLayoutWidget() { } QStringList MusicSpectrumNormalLayoutWidget::spectrumTypeList() const { return QStringList() << "normalanalyzer" << "normalewave" << "normalflowwave" << "normalhistogram" << "normalline" << "normalspacewave"; } MusicSpectrumPlusLayoutWidget::MusicSpectrumPlusLayoutWidget(QWidget *parent) : MusicSpectrumLayoutWidget(parent) { ItemInfos items; items << ItemInfo(":/spectrum/plus_1", tr("FoldWave")); items << ItemInfo(":/spectrum/plus_2", tr("Monowave")); items << ItemInfo(":/spectrum/plus_3", tr("Multiwave")); items << ItemInfo(":/spectrum/plus_4", tr("XRays")); items << ItemInfo(":/spectrum/plus_5", tr("PointXRays")); items << ItemInfo(":/spectrum/plus_6", tr("VolumeWave")); items << ItemInfo(":/spectrum/plus_7", tr("LightEnvelope")); addItems(items); } MusicSpectrumPlusLayoutWidget::~MusicSpectrumPlusLayoutWidget() { } QStringList MusicSpectrumPlusLayoutWidget::spectrumTypeList() const { return QStringList() << "plusfoldwave" << "plusmonowave" << "plusmultiwave" << "plusxrays" << "pluspointxrays" << "plusvolumewave" << "lightenvelope"; } MusicSpectrumFloridLayoutWidget::MusicSpectrumFloridLayoutWidget(QWidget *parent) : MusicSpectrumLayoutWidget(parent) { m_exclusive = true; ItemInfos items; items << ItemInfo(":/spectrum/florid_1", tr("Goom")); items << ItemInfo(":/spectrum/florid_1", tr("ProjectM")); items << ItemInfo(":/spectrum/florid_2", tr("Ethereality")); items << ItemInfo(":/spectrum/florid_3", tr("Reverb")); items << ItemInfo(":/spectrum/florid_4", tr("Autism")); items << ItemInfo(":/spectrum/florid_5", tr("Bass")); items << ItemInfo(":/spectrum/florid_6", tr("Surround")); items << ItemInfo(":/spectrum/florid_7", tr("Ancient")); items << ItemInfo(":/spectrum/florid_8", tr("Electric")); addItems(items); } MusicSpectrumFloridLayoutWidget::~MusicSpectrumFloridLayoutWidget() { } QStringList MusicSpectrumFloridLayoutWidget::spectrumTypeList() const { return QStringList() << "floridgoom" << "floridprojectm" << "floridethereality" << "floridreverb" << "floridautism" << "floridbass" << "floridsurround" << "floridancient" << "floridelectric"; } <|endoftext|>
<commit_before>/********************************** SIGNATURE *********************************\ | ,, | | db `7MM | | ;MM: MM | | ,V^MM. ,pP"Ybd MMpMMMb. .gP"Ya `7Mb,od8 | | ,M `MM 8I `" MM MM ,M' Yb MM' "' | | AbmmmqMA `YMMMa. MM MM 8M"""""" MM | | A' VML L. I8 MM MM YM. , MM | | .AMA. .AMMA.M9mmmP'.JMML JMML.`Mbmmd'.JMML. | | | | | | ,, ,, | | .g8"""bgd `7MM db `7MM | | .dP' `M MM MM | | dM' ` MM `7MM ,p6"bo MM ,MP' | | MM MM MM 6M' OO MM ;Y | | MM. `7MMF' MM MM 8M MM;Mm | | `Mb. MM MM MM YM. , MM `Mb. | | `"bmmmdPY .JMML..JMML.YMbmd'.JMML. YA. | | | \******************************************************************************/ /*********************************** LICENSE **********************************\ | Copyright (c) 2013, Asher Glick | | 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 <openssl/sha.h> #include <unistd.h> #include <math.h> #include <pwd.h> #include <fstream> #include <iostream> #include <iomanip> #include <string> #include <vector> using namespace std; #define HASHSIZE 32 ////////////////////////////////////////////////////////////////////////////// //////////////////////// BASE MODIFICATION FUNCTIONS ///////////////////////// ////////////////////////////////////////////////////////////////////////////// int calculateNewBaseLength(int oldBase, int oldBaseLength, int newBase) { double logOldBase = log(oldBase); double logNewBase = log(newBase); double newBaseLength = oldBaseLength * (logOldBase/logNewBase); int intNewBaseLength = newBaseLength; if (newBaseLength > intNewBaseLength) intNewBaseLength += 1; // round up return intNewBaseLength; } // Trims all of the preceding zeros off a function vector<int> trimNumber(vector<int> v) { vector<int>::iterator i = v.begin(); while (i != v.end()-1) { if (*i != 0) { break; } i++; } return vector<int>(i, v.end()); } // creats a new base number of the old base value of 10 vector<int> tenInOldBase(int oldBase, int newBase) { // int ten[] = {1,0}; int newBaseLength = calculateNewBaseLength(oldBase, 2, newBase); int maxLength = newBaseLength>2?newBaseLength:2; vector <int> newNumber(maxLength, 0); int currentNumber = oldBase; for (int i = maxLength-1; i >=0; i--) { newNumber[i] = currentNumber % newBase; currentNumber = currentNumber / newBase; } newNumber = trimNumber(newNumber); // return calculateNewBase(oldBase, 2, newBase, ten); return newNumber; } // Multiplies two base n numbers together vector <int> multiply(int base, vector<int> firstNumber, vector<int> secondNumber) { int resultLength = firstNumber.size() + secondNumber.size(); vector<int> resultNumber(resultLength, 0); for (int i = firstNumber.size() - 1 ; i >= 0; i--) { for (int j = secondNumber.size() - 1; j >= 0; j--) { resultNumber[i+j + 1] += firstNumber[i] * secondNumber[j]; } } for (int i = resultNumber.size() -1; i > 0; i--) { if (resultNumber[i] >= base) { resultNumber[i-1] += resultNumber[i]/base; resultNumber[i] = resultNumber[i] % base; } } return trimNumber(resultNumber); } vector<int> calculateNewBase(int oldBase, int newBase, vector<int> oldNumber) { int newNumberLength = calculateNewBaseLength(oldBase, oldNumber.size(), newBase); vector<int> newNumber(newNumberLength, 0); vector<int> conversionFactor(1, 1); // a single digit of 1 for (int i = oldNumber.size()-1; i >= 0; i--) { vector<int> difference(conversionFactor); // size the vector for (unsigned int j = 0; j < difference.size(); j++) { difference[j] *= oldNumber[i]; } // add the vector for (unsigned int j = 0; j < difference.size(); j++) { int newNumberIndex = j + newNumberLength - difference.size(); newNumber[newNumberIndex] += difference[j]; } // increment the conversion factor by oldbase 10 conversionFactor = multiply(newBase, conversionFactor, tenInOldBase(oldBase,newBase)); } // Flatten number to base for (int i = newNumber.size()-1; i >=0; i--) { if (newNumber[i] >= newBase) { newNumber[i-1] += newNumber[i]/newBase; newNumber[i] = newNumber[i]%newBase; } } return trimNumber(newNumber); } ////////////////////////////////////////////////////////////////////////////// /////////////////////////////// READ SETTINGS //////////////////////////////// ////////////////////////////////////////////////////////////////////////////// struct settingWrapper { string domain; string allowedCharacters; uint maxCharacters; string regex; }; settingWrapper getSettings(string domain) { string hexCharacters = "0123456789abcdef"; settingWrapper settings; // open ~/.passcodes/config ifstream configFile; struct passwd *pw = getpwuid(getuid()); const char *homedir = pw->pw_dir; string path = string(homedir) + "/.passcodes/subscriptions"; configFile.open(path.c_str()); string subscription = ""; if (configFile.is_open()) while (getline(configFile, subscription)) { unsigned char hash[20]; SHA1((unsigned char*)subscription.c_str(), subscription.size(), hash); string cashedSubscriptionName = ""; for (int i = 0; i < 4; i++) { cashedSubscriptionName += hexCharacters[hash[i]&0x0F]; cashedSubscriptionName += hexCharacters[(hash[i]>>4)&0x0F]; } cout << cashedSubscriptionName << endl; } // look for 'subscriptions' section // open each file in the subscriptions list in order // ~/.passcodes/<subscription>/<domain> // add any non-blank entry to the settings, latter entries overriding former return settings; } ////////////////////////////////////////////////////////////////////////////// //////////////////////// GENERATE PASSWORD FUNCTIONS ///////////////////////// ////////////////////////////////////////////////////////////////////////////// #define ITERATIONCOUNT 100000 /****************************** GENERATE PASSWORD *****************************\ | The generate password function takes in the domain and the master password | | then returns the 16 character long base64 password based off of the sha256 | | hash | \******************************************************************************/ string generatePassword(string masterpass, string domain) { settingWrapper settings = getSettings(domain); string prehash = masterpass+domain; unsigned char hash[HASHSIZE]; string output = ""; for (int i = 0; i < ITERATIONCOUNT; i++) { SHA256((unsigned char*)prehash.c_str(), prehash.size(), hash); prehash = ""; for (int j = 0; j < HASHSIZE; j++) { prehash += hash[j]; } } vector<int> hashedValues(32); for (int j = 0; j < HASHSIZE; j++) { hashedValues[j] = static_cast<int>(hash[j]); } vector<int> newValues = calculateNewBase(256, 64, hashedValues); for (int val : newValues) { cout << val << ", "; } return "Failed"; } /************************************ HELP ************************************\ | The help fucntion displays the help text to the user, it is called if the | | help flag is present or if the user has used the program incorrectly | \******************************************************************************/ void help() { cout << "Welcome to the command line application for passcod.es\n" "written by Asher Glick (aglick@aglick.com)\n" "\n" "Usage\n" " passcodes [-s] [-h] [-d] <domain text> [-p] <password text>\n" "\n" "Commands\n" " -d Any text that comes after this flag is set as the domain\n" " If no domain is given it is prompted for\n" " -p Any text that comes after this flag is set as the password\n" " If this flag is set a warning will be displayed\n" " If this flag is not set the user is prompted for a password\n" " -h Display the help menu\n" " No other functions will be run if this flag is present\n" " -s Suppress warnings\n" " No warning messages will appear from using the -p flag\n" << endl; } /************************************ MAIN ************************************\ | The main function handles all of the arguments, parsing them into the | | correct locations. Then prompts the user to enter the domain and password | | if they have not been specified in the arguments. Finaly it outputs the | | generated password to the user | \******************************************************************************/ int main(int argc, char* argv[]) { bool silent = false; string domain = ""; string password = ""; string *pointer = NULL; // Parse the arguments for (int i = 1; i < argc; i++) { if (string(argv[i]) == "-p") { // password flag pointer = &password; } else if (string(argv[i]) == "-d") { // domain flag pointer = &domain; } else if (string(argv[i]) == "-s") { // silent flag silent = true; } else if (string(argv[i]) == "-h") { // help flag help(); return 0; } else { if (pointer == NULL) { help(); return 0; } else { *pointer += argv[i]; } } } // If there is no domain given, prompt the user for a domain if (domain == "") { cout << "Enter Domain: "; getline(cin, domain); } // If there is a password given and the silent flag is not present // give the user a warning telling them that the password flag is insecure if (password != "" && !silent) { cout <<"WARNING: you should not use the -p flag as it may be insecure" << endl; } // If there is not a password given, prompt the user for a password securly else if (password == "") { password = string(getpass("Enter Password: ")); } // Output the generated Password to the user cout << generatePassword(domain, password) << endl; } <commit_msg>core creates config file if missing<commit_after>/********************************** SIGNATURE *********************************\ | ,, | | db `7MM | | ;MM: MM | | ,V^MM. ,pP"Ybd MMpMMMb. .gP"Ya `7Mb,od8 | | ,M `MM 8I `" MM MM ,M' Yb MM' "' | | AbmmmqMA `YMMMa. MM MM 8M"""""" MM | | A' VML L. I8 MM MM YM. , MM | | .AMA. .AMMA.M9mmmP'.JMML JMML.`Mbmmd'.JMML. | | | | | | ,, ,, | | .g8"""bgd `7MM db `7MM | | .dP' `M MM MM | | dM' ` MM `7MM ,p6"bo MM ,MP' | | MM MM MM 6M' OO MM ;Y | | MM. `7MMF' MM MM 8M MM;Mm | | `Mb. MM MM MM YM. , MM `Mb. | | `"bmmmdPY .JMML..JMML.YMbmd'.JMML. YA. | | | \******************************************************************************/ /*********************************** LICENSE **********************************\ | Copyright (c) 2013, Asher Glick | | 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 <openssl/sha.h> #include <unistd.h> #include <math.h> #include <pwd.h> #include <stdio.h> #include <sys/stat.h> #include <fstream> #include <iostream> #include <iomanip> #include <string> #include <vector> using namespace std; #define HASHSIZE 32 ////////////////////////////////////////////////////////////////////////////// //////////////////////// BASE MODIFICATION FUNCTIONS ///////////////////////// ////////////////////////////////////////////////////////////////////////////// int calculateNewBaseLength(int oldBase, int oldBaseLength, int newBase) { double logOldBase = log(oldBase); double logNewBase = log(newBase); double newBaseLength = oldBaseLength * (logOldBase/logNewBase); int intNewBaseLength = newBaseLength; if (newBaseLength > intNewBaseLength) intNewBaseLength += 1; // round up return intNewBaseLength; } // Trims all of the preceding zeros off a function vector<int> trimNumber(vector<int> v) { vector<int>::iterator i = v.begin(); while (i != v.end()-1) { if (*i != 0) { break; } i++; } return vector<int>(i, v.end()); } // creats a new base number of the old base value of 10 vector<int> tenInOldBase(int oldBase, int newBase) { // int ten[] = {1,0}; int newBaseLength = calculateNewBaseLength(oldBase, 2, newBase); int maxLength = newBaseLength>2?newBaseLength:2; vector <int> newNumber(maxLength, 0); int currentNumber = oldBase; for (int i = maxLength-1; i >=0; i--) { newNumber[i] = currentNumber % newBase; currentNumber = currentNumber / newBase; } newNumber = trimNumber(newNumber); // return calculateNewBase(oldBase, 2, newBase, ten); return newNumber; } // Multiplies two base n numbers together vector <int> multiply(int base, vector<int> firstNumber, vector<int> secondNumber) { int resultLength = firstNumber.size() + secondNumber.size(); vector<int> resultNumber(resultLength, 0); for (int i = firstNumber.size() - 1 ; i >= 0; i--) { for (int j = secondNumber.size() - 1; j >= 0; j--) { resultNumber[i+j + 1] += firstNumber[i] * secondNumber[j]; } } for (int i = resultNumber.size() -1; i > 0; i--) { if (resultNumber[i] >= base) { resultNumber[i-1] += resultNumber[i]/base; resultNumber[i] = resultNumber[i] % base; } } return trimNumber(resultNumber); } vector<int> calculateNewBase(int oldBase, int newBase, vector<int> oldNumber) { int newNumberLength = calculateNewBaseLength(oldBase, oldNumber.size(), newBase); vector<int> newNumber(newNumberLength, 0); vector<int> conversionFactor(1, 1); // a single digit of 1 for (int i = oldNumber.size()-1; i >= 0; i--) { vector<int> difference(conversionFactor); // size the vector for (unsigned int j = 0; j < difference.size(); j++) { difference[j] *= oldNumber[i]; } // add the vector for (unsigned int j = 0; j < difference.size(); j++) { int newNumberIndex = j + newNumberLength - difference.size(); newNumber[newNumberIndex] += difference[j]; } // increment the conversion factor by oldbase 10 conversionFactor = multiply(newBase, conversionFactor, tenInOldBase(oldBase,newBase)); } // Flatten number to base for (int i = newNumber.size()-1; i >=0; i--) { if (newNumber[i] >= newBase) { newNumber[i-1] += newNumber[i]/newBase; newNumber[i] = newNumber[i]%newBase; } } return trimNumber(newNumber); } ////////////////////////////////////////////////////////////////////////////// /////////////////////////////// READ SETTINGS //////////////////////////////// ////////////////////////////////////////////////////////////////////////////// struct settingWrapper { string domain; string allowedCharacters; uint maxCharacters; string regex; }; settingWrapper getSettings(string domain) { string hexCharacters = "0123456789abcdef"; settingWrapper settings; // open ~/.passcodes/config ifstream configFile; struct passwd *pw = getpwuid(getuid()); const char *homedir = pw->pw_dir; string configPath = string(homedir) + "/.passcodes/"; string subscriptionPath = string(homedir) + "/.passcodes/subscriptions"; configFile.open(subscriptionPath.c_str()); if (!configFile.is_open()) { #if defined(_WIN32) _mkdir(strPath.c_str()); #else mkdir(configPath.c_str(), 0777); // notice that 777 is different than 0777 #endif ofstream testFile; testFile.open(subscriptionPath.c_str()); testFile.close(); configFile.open(subscriptionPath.c_str()); } configFile.open(subscriptionPath.c_str()); string subscription = ""; if (configFile.is_open()) while (getline(configFile, subscription)) { unsigned char hash[20]; SHA1((unsigned char*)subscription.c_str(), subscription.size(), hash); string cashedSubscriptionName = ""; for (int i = 0; i < 4; i++) { cashedSubscriptionName += hexCharacters[hash[i]&0x0F]; cashedSubscriptionName += hexCharacters[(hash[i]>>4)&0x0F]; } cout << cashedSubscriptionName << endl; } // look for 'subscriptions' section // open each file in the subscriptions list in order // ~/.passcodes/<subscription>/<domain> // add any non-blank entry to the settings, latter entries overriding former return settings; } ////////////////////////////////////////////////////////////////////////////// //////////////////////// GENERATE PASSWORD FUNCTIONS ///////////////////////// ////////////////////////////////////////////////////////////////////////////// #define ITERATIONCOUNT 100000 /****************************** GENERATE PASSWORD *****************************\ | The generate password function takes in the domain and the master password | | then returns the 16 character long base64 password based off of the sha256 | | hash | \******************************************************************************/ string generatePassword(string masterpass, string domain) { settingWrapper settings = getSettings(domain); string prehash = masterpass+domain; unsigned char hash[HASHSIZE]; string output = ""; for (int i = 0; i < ITERATIONCOUNT; i++) { SHA256((unsigned char*)prehash.c_str(), prehash.size(), hash); prehash = ""; for (int j = 0; j < HASHSIZE; j++) { prehash += hash[j]; } } vector<int> hashedValues(32); for (int j = 0; j < HASHSIZE; j++) { hashedValues[j] = static_cast<int>(hash[j]); } vector<int> newValues = calculateNewBase(256, 64, hashedValues); for (int val : newValues) { cout << val << ", "; } return "Failed"; } /************************************ HELP ************************************\ | The help fucntion displays the help text to the user, it is called if the | | help flag is present or if the user has used the program incorrectly | \******************************************************************************/ void help() { cout << "Welcome to the command line application for passcod.es\n" "written by Asher Glick (aglick@aglick.com)\n" "\n" "Usage\n" " passcodes [-s] [-h] [-d] <domain text> [-p] <password text>\n" "\n" "Commands\n" " -d Any text that comes after this flag is set as the domain\n" " If no domain is given it is prompted for\n" " -p Any text that comes after this flag is set as the password\n" " If this flag is set a warning will be displayed\n" " If this flag is not set the user is prompted for a password\n" " -h Display the help menu\n" " No other functions will be run if this flag is present\n" " -s Suppress warnings\n" " No warning messages will appear from using the -p flag\n" << endl; } /************************************ MAIN ************************************\ | The main function handles all of the arguments, parsing them into the | | correct locations. Then prompts the user to enter the domain and password | | if they have not been specified in the arguments. Finaly it outputs the | | generated password to the user | \******************************************************************************/ int main(int argc, char* argv[]) { bool silent = false; string domain = ""; string password = ""; string *pointer = NULL; // Parse the arguments for (int i = 1; i < argc; i++) { if (string(argv[i]) == "-p") { // password flag pointer = &password; } else if (string(argv[i]) == "-d") { // domain flag pointer = &domain; } else if (string(argv[i]) == "-s") { // silent flag silent = true; } else if (string(argv[i]) == "-h") { // help flag help(); return 0; } else { if (pointer == NULL) { help(); return 0; } else { *pointer += argv[i]; } } } // If there is no domain given, prompt the user for a domain if (domain == "") { cout << "Enter Domain: "; getline(cin, domain); } // If there is a password given and the silent flag is not present // give the user a warning telling them that the password flag is insecure if (password != "" && !silent) { cout <<"WARNING: you should not use the -p flag as it may be insecure" << endl; } // If there is not a password given, prompt the user for a password securly else if (password == "") { password = string(getpass("Enter Password: ")); } // Output the generated Password to the user cout << generatePassword(domain, password) << endl; } <|endoftext|>
<commit_before>#include <cstdlib> #include <cstdio> #include <cstring> #include <string> #include <algorithm> #include <unistd.h> #include <sys/time.h> #include <time.h> #include "readjpeg.h" typedef struct { float r; float g; float b; } pixel_t; void cuda_function(int data_size_X, int data_size_Y, float* kernel, pixel_t* in, pixel_t* out, double* t0, double* t1); void cuda_function2(int data_size_X, int data_size_Y, float* kernel, float* in, float* out, double* t0, double* t1); void normalize( float * kernel ) { int sum = 0; for (int i = 0; i < 25; i++ ) { sum += kernel[i]; } for (int i = 0; i < 25 && sum != 0; i++ ) { kernel[i] /= sum; } } void print_matrix(float *array, int num, int x_size){ int a = 0; printf("%5.2f, ", array[a]); for (a = 1; a < num; a++){ if (a%x_size == x_size-1){ printf("%5.2f,\n", array[a]); } else{ printf("%5.2f, ", array[a]); } } printf("\n"); } void convert_to_pixel(pixel_t *out, frame_ptr in) { for(int y = 0; y < in->image_height; y++) { for(int x = 0; x < in->image_width; x++) { int r = (int)in->row_pointers[y][in->num_components*x + 0 ]; int g = (int)in->row_pointers[y][in->num_components*x + 1 ]; int b = (int)in->row_pointers[y][in->num_components*x + 2 ]; out[y*in->image_width+x].r = (float)r; out[y*in->image_width+x].g = (float)g; out[y*in->image_width+x].b = (float)b; } } } void convert_to_frame(frame_ptr out, pixel_t *in) { for(int y = 0; y < out->image_height; y++) { for(int x = 0; x < out->image_width; x++) { int r = (int)in[y*out->image_width + x].r; int g = (int)in[y*out->image_width + x].g; int b = (int)in[y*out->image_width + x].b; out->row_pointers[y][out->num_components*x + 0 ] = r; out->row_pointers[y][out->num_components*x + 1 ] = g; out->row_pointers[y][out->num_components*x + 2 ] = b; } } } #define KERNX 5 //this is the x-size of the kernel. It will always be odd. #define KERNY 5 //this is the y-size of the kernel. It will always be odd. int main(int argc, char *argv[]){ double program_start = timestamp(); float kernel_0[] = { 0, 0, 0, 0, 0, // "sharpen" 0, 0,-1, 0, 0, 0,-1, 5,-1, 0, 0, 0,-1, 0, 0, 0, 0, 0, 0, 0, }; normalize(kernel_0); float kernel_1[]={ 1, 1, 1, 1, 1, // blur 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, }; normalize(kernel_1); float kernel_2[] = { 1, 1, 1, 1, 1, // weighted median filter 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, }; float kernel_3[]={1,1,1,1,1, // weighted mean filter 1,2,2,2,1, 1,2,3,2,1, 1,2,2,2,1, 1,1,1,1,1, }; normalize(kernel_3); float kernel_4[] = { 1, 4, 7, 4, 1, // gaussian 4,16,26,16, 4, 7,26,41,26, 7, 4,16,26,16, 4, 1, 4, 7, 4, 1, }; float kernel_5[] = { 0, 0, 0, 0, 0, // "emboss" 0,-2,-1, 0, 0, 0,-1, 1, 1, 0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 0, }; float kernel_6[] = {-1,-1,-1,-1,-1, // "edge detect" -1,-1,-1,-1,-1, -1,-1,24,-1,-1, -1,-1,-1,-1,-1, -1,-1,-1,-1,-1, }; float* kernels[7] = {kernel_0, kernel_1, kernel_2, kernel_3, kernel_4, kernel_5, kernel_6}; int c; int color = 0; char *inName = NULL; char *outName = NULL; int width = -1, height = -1; int kernel_num = 1; frame_ptr frame; pixel_t *inPix = NULL; pixel_t *outPix = NULL; //grab command line arguments while((c = getopt(argc, argv, "i:k:o:c"))!=-1) { switch(c) { case 'i': inName = optarg; break; case 'o': outName = optarg; break; case 'k': kernel_num = atoi(optarg); break; case 'c': color = 1; } } //input file name and output names inName = inName==0 ? (char*)"cpt-kurt.jpg" : inName; outName = outName==0 ? (char*)"output.jpg" : outName; //read file frame = read_JPEG_file(inName); if(!frame){ printf("unable to read %s\n", inName); exit(-1); } width = frame->image_width; height = frame->image_height; inPix = new pixel_t[width*height]; outPix = new pixel_t[width*height]; convert_to_pixel(inPix, frame); float* inFloats = new float[width*height]; float* outFloats2 = new float[width*height]; for (int i=0; i<width*height; i++){ outPix[i].r = 0; outPix[i].g = 0; outPix[i].b = 0; outFloats2[i] = 0; inFloats[i] = (inPix[i].r + inPix[i].g + inPix[i].b)/3; } float* kernel = kernels[kernel_num]; double t0, t1; double thing1, thing2; if(color == 1){ thing1 = timestamp(); cuda_function(width, height, kernel, inPix, outPix, &t0, &t1); thing2 = timestamp(); } else { thing1 = timestamp(); cuda_function2(width, height, kernel, inFloats, outFloats2, &t0, &t1); thing2 = timestamp(); } printf("%g sec whole function\n", thing2 - thing1); printf("%g sec kernel\n", t1-t0); if(color == 0) { for (int i=0; i<width*height; i++){ outPix[i].r = outFloats2[i]; outPix[i].g = outFloats2[i]; outPix[i].b = outFloats2[i]; } } convert_to_frame(frame, outPix); write_JPEG_file(outName,frame,75); destroy_frame(frame); delete [] inPix; delete [] outPix; double program_end = timestamp(); printf("%g sec main function\n", program_end - program_start); return 0; } <commit_msg>Timestamp<commit_after>#include <cstdlib> #include <cstdio> #include <cstring> #include <string> #include <algorithm> #include <unistd.h> #include <sys/time.h> #include <time.h> #include "readjpeg.h" double timestamp() { struct timeval tv; gettimeofday (&tv, 0); return tv.tv_sec + 1e-6*tv.tv_usec; } typedef struct { float r; float g; float b; } pixel_t; void cuda_function(int data_size_X, int data_size_Y, float* kernel, pixel_t* in, pixel_t* out, double* t0, double* t1); void cuda_function2(int data_size_X, int data_size_Y, float* kernel, float* in, float* out, double* t0, double* t1); void normalize( float * kernel ) { int sum = 0; for (int i = 0; i < 25; i++ ) { sum += kernel[i]; } for (int i = 0; i < 25 && sum != 0; i++ ) { kernel[i] /= sum; } } void print_matrix(float *array, int num, int x_size){ int a = 0; printf("%5.2f, ", array[a]); for (a = 1; a < num; a++){ if (a%x_size == x_size-1){ printf("%5.2f,\n", array[a]); } else{ printf("%5.2f, ", array[a]); } } printf("\n"); } void convert_to_pixel(pixel_t *out, frame_ptr in) { for(int y = 0; y < in->image_height; y++) { for(int x = 0; x < in->image_width; x++) { int r = (int)in->row_pointers[y][in->num_components*x + 0 ]; int g = (int)in->row_pointers[y][in->num_components*x + 1 ]; int b = (int)in->row_pointers[y][in->num_components*x + 2 ]; out[y*in->image_width+x].r = (float)r; out[y*in->image_width+x].g = (float)g; out[y*in->image_width+x].b = (float)b; } } } void convert_to_frame(frame_ptr out, pixel_t *in) { for(int y = 0; y < out->image_height; y++) { for(int x = 0; x < out->image_width; x++) { int r = (int)in[y*out->image_width + x].r; int g = (int)in[y*out->image_width + x].g; int b = (int)in[y*out->image_width + x].b; out->row_pointers[y][out->num_components*x + 0 ] = r; out->row_pointers[y][out->num_components*x + 1 ] = g; out->row_pointers[y][out->num_components*x + 2 ] = b; } } } #define KERNX 5 //this is the x-size of the kernel. It will always be odd. #define KERNY 5 //this is the y-size of the kernel. It will always be odd. int main(int argc, char *argv[]){ double program_start = timestamp(); float kernel_0[] = { 0, 0, 0, 0, 0, // "sharpen" 0, 0,-1, 0, 0, 0,-1, 5,-1, 0, 0, 0,-1, 0, 0, 0, 0, 0, 0, 0, }; normalize(kernel_0); float kernel_1[]={ 1, 1, 1, 1, 1, // blur 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, }; normalize(kernel_1); float kernel_2[] = { 1, 1, 1, 1, 1, // weighted median filter 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, }; float kernel_3[]={1,1,1,1,1, // weighted mean filter 1,2,2,2,1, 1,2,3,2,1, 1,2,2,2,1, 1,1,1,1,1, }; normalize(kernel_3); float kernel_4[] = { 1, 4, 7, 4, 1, // gaussian 4,16,26,16, 4, 7,26,41,26, 7, 4,16,26,16, 4, 1, 4, 7, 4, 1, }; float kernel_5[] = { 0, 0, 0, 0, 0, // "emboss" 0,-2,-1, 0, 0, 0,-1, 1, 1, 0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 0, }; float kernel_6[] = {-1,-1,-1,-1,-1, // "edge detect" -1,-1,-1,-1,-1, -1,-1,24,-1,-1, -1,-1,-1,-1,-1, -1,-1,-1,-1,-1, }; float* kernels[7] = {kernel_0, kernel_1, kernel_2, kernel_3, kernel_4, kernel_5, kernel_6}; int c; int color = 0; char *inName = NULL; char *outName = NULL; int width = -1, height = -1; int kernel_num = 1; frame_ptr frame; pixel_t *inPix = NULL; pixel_t *outPix = NULL; //grab command line arguments while((c = getopt(argc, argv, "i:k:o:c"))!=-1) { switch(c) { case 'i': inName = optarg; break; case 'o': outName = optarg; break; case 'k': kernel_num = atoi(optarg); break; case 'c': color = 1; } } //input file name and output names inName = inName==0 ? (char*)"cpt-kurt.jpg" : inName; outName = outName==0 ? (char*)"output.jpg" : outName; //read file frame = read_JPEG_file(inName); if(!frame){ printf("unable to read %s\n", inName); exit(-1); } width = frame->image_width; height = frame->image_height; inPix = new pixel_t[width*height]; outPix = new pixel_t[width*height]; convert_to_pixel(inPix, frame); float* inFloats = new float[width*height]; float* outFloats2 = new float[width*height]; for (int i=0; i<width*height; i++){ outPix[i].r = 0; outPix[i].g = 0; outPix[i].b = 0; outFloats2[i] = 0; inFloats[i] = (inPix[i].r + inPix[i].g + inPix[i].b)/3; } float* kernel = kernels[kernel_num]; double t0, t1; double thing1, thing2; if(color == 1){ thing1 = timestamp(); cuda_function(width, height, kernel, inPix, outPix, &t0, &t1); thing2 = timestamp(); } else { thing1 = timestamp(); cuda_function2(width, height, kernel, inFloats, outFloats2, &t0, &t1); thing2 = timestamp(); } printf("%g sec whole function\n", thing2 - thing1); printf("%g sec kernel\n", t1-t0); if(color == 0) { for (int i=0; i<width*height; i++){ outPix[i].r = outFloats2[i]; outPix[i].g = outFloats2[i]; outPix[i].b = outFloats2[i]; } } convert_to_frame(frame, outPix); write_JPEG_file(outName,frame,75); destroy_frame(frame); delete [] inPix; delete [] outPix; double program_end = timestamp(); printf("%g sec main function\n", program_end - program_start); return 0; } <|endoftext|>
<commit_before>/*========================================================================= Program: GDCM (Grassroots DICOM). A DICOM library Module: $URL$ Copyright (c) 2006-2010 Mathieu Malaterre All rights reserved. See Copyright.txt or http://gdcm.sourceforge.net/Copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "gdcmTag.h" #include "gdcmTrace.h" #include <stdio.h> // sscanf namespace gdcm { bool Tag::ReadFromCommaSeparatedString(const char *str) { unsigned int group = 0, element = 0; if( !str || sscanf(str, "%04x,%04x", &group , &element) != 2 ) { gdcmDebugMacro( "Problem reading Tag: " << str ); return false; } SetGroup( (uint16_t)group ); SetElement( (uint16_t)element ); return true; } bool Tag::ReadFromPipeSeparatedString(const char *str) { unsigned int group = 0, element = 0; if( !str || sscanf(str, "%04x|%04x", &group , &element) != 2 ) { gdcmDebugMacro( "Problem reading Tag: " << str ); return false; } SetGroup( (uint16_t)group ); SetElement( (uint16_t)element ); return true; } std::string Tag::PrintAsPipeSeparatedString() const { std::ostringstream _os; const Tag &_val = *this; _os.setf( std::ios::right); _os << std::hex << '(' << std::setw( 4 ) << std::setfill( '0' ) << _val[0] << '|' << std::setw( 4 ) << std::setfill( '0' ) << _val[1] << ')' << std::setfill( ' ' ) << std::dec; return _os.str(); } } // end namespace gdcm <commit_msg>BUG: This commit fixes bug #0011732<commit_after>/*========================================================================= Program: GDCM (Grassroots DICOM). A DICOM library Module: $URL$ Copyright (c) 2006-2010 Mathieu Malaterre All rights reserved. See Copyright.txt or http://gdcm.sourceforge.net/Copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "gdcmTag.h" #include "gdcmTrace.h" #include <stdio.h> // sscanf namespace gdcm { bool Tag::ReadFromCommaSeparatedString(const char *str) { unsigned int group = 0, element = 0; if( !str || sscanf(str, "%04x,%04x", &group , &element) != 2 ) { gdcmDebugMacro( "Problem reading Tag: " << str ); return false; } SetGroup( (uint16_t)group ); SetElement( (uint16_t)element ); return true; } bool Tag::ReadFromPipeSeparatedString(const char *str) { unsigned int group = 0, element = 0; if( !str || sscanf(str, "%04x|%04x", &group , &element) != 2 ) { gdcmDebugMacro( "Problem reading Tag: " << str ); return false; } SetGroup( (uint16_t)group ); SetElement( (uint16_t)element ); return true; } std::string Tag::PrintAsPipeSeparatedString() const { std::ostringstream _os; const Tag &_val = *this; _os.setf( std::ios::right); _os << std::hex << std::setw( 4 ) << std::setfill( '0' ) << _val[0] << '|' << std::setw( 4 ) << std::setfill( '0' ) << _val[1] << std::setfill( ' ' ) << std::dec; return _os.str(); } } // end namespace gdcm <|endoftext|>
<commit_before>/* This file is part of KDE Kontact. Copyright (c) 2003 Cornelius Schumacher <schumacher@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "kcmkontact.h" #include "prefs.h" #include <kaboutdata.h> #include <kdebug.h> #include <klistview.h> #include <klocale.h> #include <ktrader.h> #include <qbuttongroup.h> #include <qcheckbox.h> #include <qcombobox.h> #include <qlabel.h> #include <qlayout.h> #include <kdepimmacros.h> extern "C" { KDE_EXPORT KCModule *create_kontactconfig( QWidget *parent, const char * ) { return new KcmKontact( parent, "kcmkontact" ); } } class PluginItem : public QListViewItem { public: PluginItem( QListView *parent, const KService::Ptr &ptr ) : QListViewItem( parent, ptr->name(), ptr->comment(), ptr->library() ), mPtr( ptr ) { } KService::Ptr servicePtr() const { return mPtr; } private: KService::Ptr mPtr; }; KcmKontact::KcmKontact( QWidget *parent, const char *name ) : KPrefsModule( Kontact::Prefs::self(), parent, name ) { QBoxLayout *topLayout = new QVBoxLayout( this ); QBoxLayout *pluginStartupLayout = new QHBoxLayout( topLayout ); topLayout->addStretch(); KPrefsWidBool *forceStartupPlugin = addWidBool( Kontact::Prefs::self()->forceStartupPluginItem(), this ); pluginStartupLayout->addWidget( forceStartupPlugin->checkBox() ); PluginSelection *selection = new PluginSelection( Kontact::Prefs::self()->forcedStartupPluginItem(), this ); addWid( selection ); pluginStartupLayout->addWidget( selection->comboBox() ); selection->comboBox()->setEnabled( false ); connect( forceStartupPlugin->checkBox(), SIGNAL( toggled( bool ) ), selection->comboBox(), SLOT( setEnabled( bool ) ) ); load(); } const KAboutData* KcmKontact::aboutData() const { KAboutData *about = new KAboutData( I18N_NOOP( "kontactconfig" ), I18N_NOOP( "KDE Kontact" ), 0, 0, KAboutData::License_GPL, I18N_NOOP( "(c), 2003 Cornelius Schumacher" ) ); about->addAuthor( "Cornelius Schumacher", 0, "schumacher@kde.org" ); about->addAuthor( "Tobias Koenig", 0, "tokoe@kde.org" ); return about; } PluginSelection::PluginSelection( KConfigSkeleton::ItemString *item, QWidget *parent ) { mItem = item; mPluginCombo = new QComboBox( parent ); } PluginSelection::~PluginSelection() { } void PluginSelection::readConfig() { const KTrader::OfferList offers = KTrader::self()->query( QString::fromLatin1( "Kontact/Plugin" ), QString( "[X-KDE-KontactPluginVersion] == %1" ).arg( KONTACT_PLUGIN_VERSION ) ); int activeComponent = 0; for ( KService::List::ConstIterator it = offers.begin(); it != offers.end(); ++it ) { KService::Ptr service = *it; mPluginCombo->insertItem( service->name() ); mPluginList.append( service ); if ( service->property("X-KDE-PluginInfo-Name").toString() == mItem->value() ) activeComponent = mPluginList.count() - 1; } mPluginCombo->setCurrentItem( activeComponent ); } void PluginSelection::writeConfig() { KService::Ptr ptr = *( mPluginList.at( mPluginCombo->currentItem() ) ); mItem->setValue( ptr->library() ); } void PluginSelection::itemClicked( QListViewItem *item ) { if ( item ) emit changed(); } QValueList<QWidget *> PluginSelection::widgets() const { QValueList<QWidget *> widgets; widgets.append( mPluginCombo ); return widgets; } #include "kcmkontact.moc" <commit_msg>load the desired component at startup, if it was configured so (there was a mismatch between the read/write methods semantics)<commit_after>/* This file is part of KDE Kontact. Copyright (c) 2003 Cornelius Schumacher <schumacher@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "kcmkontact.h" #include "prefs.h" #include <kaboutdata.h> #include <kdebug.h> #include <klistview.h> #include <klocale.h> #include <ktrader.h> #include <qbuttongroup.h> #include <qcheckbox.h> #include <qcombobox.h> #include <qlabel.h> #include <qlayout.h> #include <kdepimmacros.h> extern "C" { KDE_EXPORT KCModule *create_kontactconfig( QWidget *parent, const char * ) { return new KcmKontact( parent, "kcmkontact" ); } } class PluginItem : public QListViewItem { public: PluginItem( QListView *parent, const KService::Ptr &ptr ) : QListViewItem( parent, ptr->name(), ptr->comment(), ptr->library() ), mPtr( ptr ) { } KService::Ptr servicePtr() const { return mPtr; } private: KService::Ptr mPtr; }; KcmKontact::KcmKontact( QWidget *parent, const char *name ) : KPrefsModule( Kontact::Prefs::self(), parent, name ) { QBoxLayout *topLayout = new QVBoxLayout( this ); QBoxLayout *pluginStartupLayout = new QHBoxLayout( topLayout ); topLayout->addStretch(); KPrefsWidBool *forceStartupPlugin = addWidBool( Kontact::Prefs::self()->forceStartupPluginItem(), this ); pluginStartupLayout->addWidget( forceStartupPlugin->checkBox() ); PluginSelection *selection = new PluginSelection( Kontact::Prefs::self()->forcedStartupPluginItem(), this ); addWid( selection ); pluginStartupLayout->addWidget( selection->comboBox() ); selection->comboBox()->setEnabled( false ); connect( forceStartupPlugin->checkBox(), SIGNAL( toggled( bool ) ), selection->comboBox(), SLOT( setEnabled( bool ) ) ); load(); } const KAboutData* KcmKontact::aboutData() const { KAboutData *about = new KAboutData( I18N_NOOP( "kontactconfig" ), I18N_NOOP( "KDE Kontact" ), 0, 0, KAboutData::License_GPL, I18N_NOOP( "(c), 2003 Cornelius Schumacher" ) ); about->addAuthor( "Cornelius Schumacher", 0, "schumacher@kde.org" ); about->addAuthor( "Tobias Koenig", 0, "tokoe@kde.org" ); return about; } PluginSelection::PluginSelection( KConfigSkeleton::ItemString *item, QWidget *parent ) { mItem = item; mPluginCombo = new QComboBox( parent ); } PluginSelection::~PluginSelection() { } void PluginSelection::readConfig() { const KTrader::OfferList offers = KTrader::self()->query( QString::fromLatin1( "Kontact/Plugin" ), QString( "[X-KDE-KontactPluginVersion] == %1" ).arg( KONTACT_PLUGIN_VERSION ) ); int activeComponent = 0; for ( KService::List::ConstIterator it = offers.begin(); it != offers.end(); ++it ) { KService::Ptr service = *it; mPluginCombo->insertItem( service->name() ); mPluginList.append( service ); if ( service->property("X-KDE-PluginInfo-Name").toString() == mItem->value() ) activeComponent = mPluginList.count() - 1; } mPluginCombo->setCurrentItem( activeComponent ); } void PluginSelection::writeConfig() { KService::Ptr ptr = *( mPluginList.at( mPluginCombo->currentItem() ) ); mItem->setValue( ptr->property("X-KDE-PluginInfo-Name").toString() ); } void PluginSelection::itemClicked( QListViewItem *item ) { if ( item ) emit changed(); } QValueList<QWidget *> PluginSelection::widgets() const { QValueList<QWidget *> widgets; widgets.append( mPluginCombo ); return widgets; } #include "kcmkontact.moc" <|endoftext|>
<commit_before>/* This file is part of the Groupware/KOrganizer integration. Requires the Qt and KDE widget libraries, available at no cost at http://www.trolltech.com and http://www.kde.org respectively Copyright (c) 2002-2004 Klarälvdalens Datakonsult AB <info@klaralvdalens-datakonsult.se> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "kogroupware.h" #include "freebusymanager.h" #include "calendarview.h" #include "mailscheduler.h" #include "koprefs.h" #include <libemailfunctions/email.h> #include <libkcal/attendee.h> #include <libkcal/journal.h> #include <libkcal/incidenceformatter.h> #include <kdebug.h> #include <kmessagebox.h> #include <kstandarddirs.h> #include <kdirwatch.h> #include <QFile> #include <QRegExp> #include <QDir> //Added by qt3to4: #include <QTextStream> FreeBusyManager *KOGroupware::mFreeBusyManager = 0; KOGroupware *KOGroupware::mInstance = 0; KOGroupware *KOGroupware::create( CalendarView *view, KCal::CalendarResources *calendar ) { if( !mInstance ) mInstance = new KOGroupware( view, calendar ); return mInstance; } KOGroupware *KOGroupware::instance() { // Doesn't create, that is the task of create() Q_ASSERT( mInstance ); return mInstance; } KOGroupware::KOGroupware( CalendarView* view, KCal::CalendarResources* cal ) : QObject( 0 ), mView( view ), mCalendar( cal ) { setObjectName( "kmgroupware_instance" ); // Set up the dir watch of the three incoming dirs KDirWatch* watcher = KDirWatch::self(); watcher->addDir( locateLocal( "data", "korganizer/income.accepted/" ) ); watcher->addDir( locateLocal( "data", "korganizer/income.tentative/" ) ); watcher->addDir( locateLocal( "data", "korganizer/income.cancel/" ) ); watcher->addDir( locateLocal( "data", "korganizer/income.reply/" ) ); connect( watcher, SIGNAL( dirty( const QString& ) ), this, SLOT( incomingDirChanged( const QString& ) ) ); // Now set the ball rolling incomingDirChanged( locateLocal( "data", "korganizer/income.accepted/" ) ); incomingDirChanged( locateLocal( "data", "korganizer/income.tentative/" ) ); incomingDirChanged( locateLocal( "data", "korganizer/income.cancel/" ) ); incomingDirChanged( locateLocal( "data", "korganizer/income.reply/" ) ); } FreeBusyManager *KOGroupware::freeBusyManager() { if ( !mFreeBusyManager ) { mFreeBusyManager = new FreeBusyManager( this ); mFreeBusyManager->setObjectName( "freebusymanager" ); mFreeBusyManager->setCalendar( mCalendar ); connect( mCalendar, SIGNAL( calendarChanged() ), mFreeBusyManager, SLOT( slotPerhapsUploadFB() ) ); } return mFreeBusyManager; } void KOGroupware::incomingDirChanged( const QString& path ) { const QString incomingDirName = locateLocal( "data","korganizer/" ) + "income."; if ( !path.startsWith( incomingDirName ) ) { kDebug(5850) << "incomingDirChanged: Wrong dir " << path << endl; return; } QString action = path.mid( incomingDirName.length() ); while ( action.length() > 0 && action[ action.length()-1 ] == '/' ) // Strip slashes at the end action.truncate( action.length()-1 ); // Handle accepted invitations QDir dir( path ); const QStringList files = dir.entryList( QDir::Files ); if ( files.isEmpty() ) // No more files here return; // Read the file and remove it QFile f( path + '/' + files[0] ); if (!f.open(QIODevice::ReadOnly)) { kError(5850) << "Can't open file '" << files[0] << "'" << endl; return; } QTextStream t(&f); t.setCodec( "UTF-8" ); QString receiver = EmailAddressTools::firstEmailAddress( t.readLine() ); QString iCal = t.readAll(); f.remove(); ScheduleMessage *message = mFormat.parseScheduleMessage( mCalendar, iCal ); if ( !message ) { QString errorMessage; if (mFormat.exception()) errorMessage = i18n( "Error message: %1", mFormat.exception()->message() ); kDebug(5850) << "MailScheduler::retrieveTransactions() Error parsing " << errorMessage << endl; KMessageBox::detailedError( mView, i18n("Error while processing an invitation or update."), errorMessage ); return; } KCal::Scheduler::Method method = static_cast<KCal::Scheduler::Method>( message->method() ); KCal::ScheduleMessage::Status status = message->status(); KCal::Incidence* incidence = dynamic_cast<KCal::Incidence*>( message->event() ); KCal::MailScheduler scheduler( mCalendar ); if ( action.startsWith( "accepted" ) || action.startsWith( "tentative" ) ) { // Find myself and set my status. This can't be done in the scheduler, // since this does not know the choice I made in the KMail bpf KCal::Attendee::List attendees = incidence->attendees(); KCal::Attendee::List::ConstIterator it; for ( it = attendees.begin(); it != attendees.end(); ++it ) { if( (*it)->email() == receiver ) { if ( action.startsWith( "accepted" ) ) (*it)->setStatus( KCal::Attendee::Accepted ); else (*it)->setStatus( KCal::Attendee::Tentative ); break; } } scheduler.acceptTransaction( incidence, method, status ); } else if ( action.startsWith( "cancel" ) ) // Delete the old incidence, if one is present scheduler.acceptTransaction( incidence, KCal::Scheduler::Cancel, status ); else if ( action.startsWith( "reply" ) ) scheduler.acceptTransaction( incidence, method, status ); else kError(5850) << "Unknown incoming action " << action << endl; mView->updateView(); delete message; } class KOInvitationFormatterHelper : public InvitationFormatterHelper { public: virtual QString generateLinkURL( const QString &id ) { return "kmail:groupware_request_" + id; } }; /* This function sends mails if necessary, and makes sure the user really * want to change his calendar. * * Return true means accept the changes * Return false means revert the changes */ bool KOGroupware::sendICalMessage( QWidget* parent, KCal::Scheduler::Method method, Incidence* incidence, bool isDeleting, bool statusChanged ) { // If there are no attendees, don't bother if( incidence->attendees().isEmpty() ) return true; bool isOrganizer = KOPrefs::instance()->thatIsMe( incidence->organizer().email() ); int rc = 0; /* * There are two scenarios: * o "we" are the organizer, where "we" means any of the identities or mail * addresses known to Kontact/PIM. If there are attendees, we need to mail * them all, even if one or more of them are also "us". Otherwise there * would be no way to invite a resource or our boss, other identities we * also manage. * o "we: are not the organizer, which means we changed the completion status * of a todo, or we changed our attendee status from, say, tentative to * accepted. In both cases we only mail the organizer. All other changes * bring us out of sync with the organizer, so we won't mail, if the user * insists on applying them. */ if ( isOrganizer ) { /* We are the organizer. If there is more than one attendee, or if there is * only one, and it's not the same as the organizer, ask the user to send * mail. */ if ( incidence->attendees().count() > 1 || incidence->attendees().first()->email() != incidence->organizer().email() ) { QString type; if( incidence->type() == QLatin1String("Event")) type = i18n("event"); else if( incidence->type() == QLatin1String("Todo") ) type = i18n("task"); else if( incidence->type() == QLatin1String("Journal") ) type = i18n("journal entry"); else type = incidence->type(); QString txt = i18n( "This %1 includes other people. " "Should email be sent out to the attendees?" , type ); rc = KMessageBox::questionYesNoCancel( parent, txt, i18n("Group Scheduling Email"), i18n("Send Email"), i18n("Do Not Send") ); } else { return true; } } else if( incidence->type() == QLatin1String("Todo") ) { if( method == Scheduler::Request ) // This is an update to be sent to the organizer method = Scheduler::Reply; // Ask if the user wants to tell the organizer about the current status QString txt = i18n( "Do you want to send a status update to the " "organizer of this task?"); rc = KMessageBox::questionYesNo( parent, txt, QString(), i18n("Send Update"), i18n("Do Not Send") ); } else if( incidence->type() == QLatin1String("Event") ) { QString txt; if ( statusChanged && method == Scheduler::Request ) { txt = i18n( "Your status as an attendee of this event " "changed. Do you want to send a status update to the " "organizer of this event?" ); method = Scheduler::Reply; rc = KMessageBox::questionYesNo( parent, txt, QString(), i18n("Send Update"), i18n("Do Not Send") ); } else { if( isDeleting ) txt = i18n( "You are not the organizer of this event. " "Deleting it will bring your calendar out of sync " "with the organizers calendar. Do you really want " "to delete it?" ); else txt = i18n( "You are not the organizer of this event. " "Editing it will bring your calendar out of sync " "with the organizers calendar. Do you really want " "to edit it?" ); rc = KMessageBox::warningYesNo( parent, txt ); return ( rc == KMessageBox::Continue ); } } else { kWarning(5850) << "Groupware messages for Journals are not implemented yet!" << endl; return true; } if( rc == KMessageBox::Yes ) { // We will be sending out a message here. Now make sure there is // some summary if( incidence->summary().isEmpty() ) incidence->setSummary( i18n("<No summary given>") ); // Send the mail KCal::MailScheduler scheduler( mCalendar ); scheduler.performTransaction( incidence, method ); return true; } else if( rc == KMessageBox::No ) return true; else return false; } #include "kogroupware.moc" <commit_msg>forward port SVN commit 548388 by bram:<commit_after>/* This file is part of the Groupware/KOrganizer integration. Requires the Qt and KDE widget libraries, available at no cost at http://www.trolltech.com and http://www.kde.org respectively Copyright (c) 2002-2004 Klarälvdalens Datakonsult AB <info@klaralvdalens-datakonsult.se> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "kogroupware.h" #include "freebusymanager.h" #include "calendarview.h" #include "mailscheduler.h" #include "koprefs.h" #include <libemailfunctions/email.h> #include <libkcal/attendee.h> #include <libkcal/journal.h> #include <libkcal/incidenceformatter.h> #include <kdebug.h> #include <kmessagebox.h> #include <kstandarddirs.h> #include <kdirwatch.h> #include <QFile> #include <QRegExp> #include <QDir> //Added by qt3to4: #include <QTextStream> FreeBusyManager *KOGroupware::mFreeBusyManager = 0; KOGroupware *KOGroupware::mInstance = 0; KOGroupware *KOGroupware::create( CalendarView *view, KCal::CalendarResources *calendar ) { if( !mInstance ) mInstance = new KOGroupware( view, calendar ); return mInstance; } KOGroupware *KOGroupware::instance() { // Doesn't create, that is the task of create() Q_ASSERT( mInstance ); return mInstance; } KOGroupware::KOGroupware( CalendarView* view, KCal::CalendarResources* cal ) : QObject( 0 ), mView( view ), mCalendar( cal ) { setObjectName( "kmgroupware_instance" ); // Set up the dir watch of the three incoming dirs KDirWatch* watcher = KDirWatch::self(); watcher->addDir( locateLocal( "data", "korganizer/income.accepted/" ) ); watcher->addDir( locateLocal( "data", "korganizer/income.tentative/" ) ); watcher->addDir( locateLocal( "data", "korganizer/income.cancel/" ) ); watcher->addDir( locateLocal( "data", "korganizer/income.reply/" ) ); connect( watcher, SIGNAL( dirty( const QString& ) ), this, SLOT( incomingDirChanged( const QString& ) ) ); // Now set the ball rolling incomingDirChanged( locateLocal( "data", "korganizer/income.accepted/" ) ); incomingDirChanged( locateLocal( "data", "korganizer/income.tentative/" ) ); incomingDirChanged( locateLocal( "data", "korganizer/income.cancel/" ) ); incomingDirChanged( locateLocal( "data", "korganizer/income.reply/" ) ); } FreeBusyManager *KOGroupware::freeBusyManager() { if ( !mFreeBusyManager ) { mFreeBusyManager = new FreeBusyManager( this ); mFreeBusyManager->setObjectName( "freebusymanager" ); mFreeBusyManager->setCalendar( mCalendar ); connect( mCalendar, SIGNAL( calendarChanged() ), mFreeBusyManager, SLOT( slotPerhapsUploadFB() ) ); } return mFreeBusyManager; } void KOGroupware::incomingDirChanged( const QString& path ) { const QString incomingDirName = locateLocal( "data","korganizer/" ) + "income."; if ( !path.startsWith( incomingDirName ) ) { kDebug(5850) << "incomingDirChanged: Wrong dir " << path << endl; return; } QString action = path.mid( incomingDirName.length() ); while ( action.length() > 0 && action[ action.length()-1 ] == '/' ) // Strip slashes at the end action.truncate( action.length()-1 ); // Handle accepted invitations QDir dir( path ); const QStringList files = dir.entryList( QDir::Files ); if ( files.isEmpty() ) // No more files here return; // Read the file and remove it QFile f( path + '/' + files[0] ); if (!f.open(QIODevice::ReadOnly)) { kError(5850) << "Can't open file '" << files[0] << "'" << endl; return; } QTextStream t(&f); t.setCodec( "UTF-8" ); QString receiver = EmailAddressTools::firstEmailAddress( t.readLine() ); QString iCal = t.readAll(); f.remove(); ScheduleMessage *message = mFormat.parseScheduleMessage( mCalendar, iCal ); if ( !message ) { QString errorMessage; if (mFormat.exception()) errorMessage = i18n( "Error message: %1", mFormat.exception()->message() ); kDebug(5850) << "MailScheduler::retrieveTransactions() Error parsing " << errorMessage << endl; KMessageBox::detailedError( mView, i18n("Error while processing an invitation or update."), errorMessage ); return; } KCal::Scheduler::Method method = static_cast<KCal::Scheduler::Method>( message->method() ); KCal::ScheduleMessage::Status status = message->status(); KCal::Incidence* incidence = dynamic_cast<KCal::Incidence*>( message->event() ); KCal::MailScheduler scheduler( mCalendar ); if ( action.startsWith( "accepted" ) || action.startsWith( "tentative" ) ) { // Find myself and set my status. This can't be done in the scheduler, // since this does not know the choice I made in the KMail bpf KCal::Attendee::List attendees = incidence->attendees(); KCal::Attendee::List::ConstIterator it; for ( it = attendees.begin(); it != attendees.end(); ++it ) { if( (*it)->email() == receiver ) { if ( action.startsWith( "accepted" ) ) (*it)->setStatus( KCal::Attendee::Accepted ); else (*it)->setStatus( KCal::Attendee::Tentative ); break; } } scheduler.acceptTransaction( incidence, method, status ); } else if ( action.startsWith( "cancel" ) ) // Delete the old incidence, if one is present scheduler.acceptTransaction( incidence, KCal::Scheduler::Cancel, status ); else if ( action.startsWith( "reply" ) ) scheduler.acceptTransaction( incidence, method, status ); else kError(5850) << "Unknown incoming action " << action << endl; mView->updateView(); delete message; } class KOInvitationFormatterHelper : public InvitationFormatterHelper { public: virtual QString generateLinkURL( const QString &id ) { return "kmail:groupware_request_" + id; } }; /* This function sends mails if necessary, and makes sure the user really * want to change his calendar. * * Return true means accept the changes * Return false means revert the changes */ bool KOGroupware::sendICalMessage( QWidget* parent, KCal::Scheduler::Method method, Incidence* incidence, bool isDeleting, bool statusChanged ) { // If there are no attendees, don't bother if( incidence->attendees().isEmpty() ) return true; bool isOrganizer = KOPrefs::instance()->thatIsMe( incidence->organizer().email() ); int rc = 0; /* * There are two scenarios: * o "we" are the organizer, where "we" means any of the identities or mail * addresses known to Kontact/PIM. If there are attendees, we need to mail * them all, even if one or more of them are also "us". Otherwise there * would be no way to invite a resource or our boss, other identities we * also manage. * o "we: are not the organizer, which means we changed the completion status * of a todo, or we changed our attendee status from, say, tentative to * accepted. In both cases we only mail the organizer. All other changes * bring us out of sync with the organizer, so we won't mail, if the user * insists on applying them. */ if ( isOrganizer ) { /* We are the organizer. If there is more than one attendee, or if there is * only one, and it's not the same as the organizer, ask the user to send * mail. */ if ( incidence->attendees().count() > 1 || incidence->attendees().first()->email() != incidence->organizer().email() ) { QString type; if( incidence->type() == QLatin1String("Event")) type = i18n("event"); else if( incidence->type() == QLatin1String("Todo") ) type = i18n("task"); else if( incidence->type() == QLatin1String("Journal") ) type = i18n("journal entry"); else type = incidence->type(); QString txt = i18n( "This %1 includes other people. " "Should email be sent out to the attendees?" , type ); rc = KMessageBox::questionYesNoCancel( parent, txt, i18n("Group Scheduling Email"), i18n("Send Email"), i18n("Do Not Send") ); } else { return true; } } else if( incidence->type() == QLatin1String("Todo") ) { if( method == Scheduler::Request ) // This is an update to be sent to the organizer method = Scheduler::Reply; // Ask if the user wants to tell the organizer about the current status QString txt = i18n( "Do you want to send a status update to the " "organizer of this task?"); rc = KMessageBox::questionYesNo( parent, txt, QString(), i18n("Send Update"), i18n("Do Not Send") ); } else if( incidence->type() == QLatin1String("Event") ) { QString txt; if ( statusChanged && method == Scheduler::Request ) { txt = i18n( "Your status as an attendee of this event " "changed. Do you want to send a status update to the " "organizer of this event?" ); method = Scheduler::Reply; rc = KMessageBox::questionYesNo( parent, txt, QString(), i18n("Send Update"), i18n("Do Not Send") ); } else { if( isDeleting ) txt = i18n( "You are not the organizer of this event. " "Deleting it will bring your calendar out of sync " "with the organizers calendar. Do you really want " "to delete it?" ); else txt = i18n( "You are not the organizer of this event. " "Editing it will bring your calendar out of sync " "with the organizers calendar. Do you really want " "to edit it?" ); rc = KMessageBox::warningYesNo( parent, txt ); return ( rc == KMessageBox::Yes ); } } else { kWarning(5850) << "Groupware messages for Journals are not implemented yet!" << endl; return true; } if( rc == KMessageBox::Yes ) { // We will be sending out a message here. Now make sure there is // some summary if( incidence->summary().isEmpty() ) incidence->setSummary( i18n("<No summary given>") ); // Send the mail KCal::MailScheduler scheduler( mCalendar ); scheduler.performTransaction( incidence, method ); return true; } else if( rc == KMessageBox::No ) return true; else return false; } #include "kogroupware.moc" <|endoftext|>
<commit_before>#define BOOST_TEST_MODULE "parse_table_key_test" #ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST #include <boost/test/unit_test.hpp> #else #define BOOST_TEST_NO_LIB #include <boost/test/included/unit_test.hpp> #endif #include <toml/parser.hpp> #include "test_parse_aux.hpp" using namespace toml; using namespace detail; BOOST_AUTO_TEST_CASE(test_table_bare_key) { TOML11_TEST_PARSE_EQUAL(parse_table_key, "[barekey]", std::vector<key>(1, "barekey")); TOML11_TEST_PARSE_EQUAL(parse_table_key, "[bare-key]", std::vector<key>(1, "bare-key")); TOML11_TEST_PARSE_EQUAL(parse_table_key, "[bare_key]", std::vector<key>(1, "bare_key")); TOML11_TEST_PARSE_EQUAL(parse_table_key, "[1234]", std::vector<key>(1, "1234")); } BOOST_AUTO_TEST_CASE(test_table_quoted_key) { TOML11_TEST_PARSE_EQUAL(parse_table_key, "[\"127.0.0.1\"]", std::vector<key>(1, "127.0.0.1" )); TOML11_TEST_PARSE_EQUAL(parse_table_key, "[\"character encoding\"]", std::vector<key>(1, "character encoding")); TOML11_TEST_PARSE_EQUAL(parse_table_key, "[\"ʎǝʞ\"]", std::vector<key>(1, "ʎǝʞ" )); TOML11_TEST_PARSE_EQUAL(parse_table_key, "['key2']", std::vector<key>(1, "key2" )); TOML11_TEST_PARSE_EQUAL(parse_table_key, "['quoted \"value\"']", std::vector<key>(1, "quoted \"value\"" )); } BOOST_AUTO_TEST_CASE(test_table_dotted_key) { { std::vector<key> keys(2); keys[0] = "physical"; keys[1] = "color"; TOML11_TEST_PARSE_EQUAL(parse_table_key, "[physical.color]", keys); } { std::vector<key> keys(2); keys[0] = "physical"; keys[1] = "shape"; TOML11_TEST_PARSE_EQUAL(parse_table_key, "[physical.shape]", keys); } { std::vector<key> keys(4); keys[0] = "x"; keys[1] = "y"; keys[2] = "z"; keys[3] = "w"; TOML11_TEST_PARSE_EQUAL(parse_table_key, "[x.y.z.w]", keys); TOML11_TEST_PARSE_EQUAL(parse_table_key, "[x . y . z . w]", keys); TOML11_TEST_PARSE_EQUAL(parse_table_key, "[x. y .z. w]", keys); TOML11_TEST_PARSE_EQUAL(parse_table_key, "[x .y. z .w]", keys); TOML11_TEST_PARSE_EQUAL(parse_table_key, "[ x. y .z . w ]", keys); TOML11_TEST_PARSE_EQUAL(parse_table_key, "[ x . y . z . w ]", keys); } { std::vector<key> keys(2); keys[0] = "site"; keys[1] = "google.com"; TOML11_TEST_PARSE_EQUAL(parse_table_key, "[site.\"google.com\"]", keys); } } BOOST_AUTO_TEST_CASE(test_array_of_table_bare_key) { TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[[barekey]]", std::vector<key>(1, "barekey")); TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[[bare-key]]", std::vector<key>(1, "bare-key")); TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[[bare_key]]", std::vector<key>(1, "bare_key")); TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[[1234]]", std::vector<key>(1, "1234")); } BOOST_AUTO_TEST_CASE(test_array_of_table_quoted_key) { TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[[\"127.0.0.1\"]]", std::vector<key>(1, "127.0.0.1" )); TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[[\"character encoding\"]]", std::vector<key>(1, "character encoding")); TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[[\"ʎǝʞ\"]]", std::vector<key>(1, "ʎǝʞ" )); TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[['key2']]", std::vector<key>(1, "key2" )); TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[['quoted \"value\"']]", std::vector<key>(1, "quoted \"value\"" )); } BOOST_AUTO_TEST_CASE(test_array_of_table_dotted_key) { { std::vector<key> keys(2); keys[0] = "physical"; keys[1] = "color"; TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[[physical.color]]", keys); } { std::vector<key> keys(2); keys[0] = "physical"; keys[1] = "shape"; TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[[physical.shape]]", keys); } { std::vector<key> keys(4); keys[0] = "x"; keys[1] = "y"; keys[2] = "z"; keys[3] = "w"; TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[[x.y.z.w]]", keys); } { std::vector<key> keys(2); keys[0] = "site"; keys[1] = "google.com"; TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[[site.\"google.com\"]]", keys); } } <commit_msg>add test case for array-of-tables<commit_after>#define BOOST_TEST_MODULE "parse_table_key_test" #ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST #include <boost/test/unit_test.hpp> #else #define BOOST_TEST_NO_LIB #include <boost/test/included/unit_test.hpp> #endif #include <toml/parser.hpp> #include "test_parse_aux.hpp" using namespace toml; using namespace detail; BOOST_AUTO_TEST_CASE(test_table_bare_key) { TOML11_TEST_PARSE_EQUAL(parse_table_key, "[barekey]", std::vector<key>(1, "barekey")); TOML11_TEST_PARSE_EQUAL(parse_table_key, "[bare-key]", std::vector<key>(1, "bare-key")); TOML11_TEST_PARSE_EQUAL(parse_table_key, "[bare_key]", std::vector<key>(1, "bare_key")); TOML11_TEST_PARSE_EQUAL(parse_table_key, "[1234]", std::vector<key>(1, "1234")); } BOOST_AUTO_TEST_CASE(test_table_quoted_key) { TOML11_TEST_PARSE_EQUAL(parse_table_key, "[\"127.0.0.1\"]", std::vector<key>(1, "127.0.0.1" )); TOML11_TEST_PARSE_EQUAL(parse_table_key, "[\"character encoding\"]", std::vector<key>(1, "character encoding")); TOML11_TEST_PARSE_EQUAL(parse_table_key, "[\"ʎǝʞ\"]", std::vector<key>(1, "ʎǝʞ" )); TOML11_TEST_PARSE_EQUAL(parse_table_key, "['key2']", std::vector<key>(1, "key2" )); TOML11_TEST_PARSE_EQUAL(parse_table_key, "['quoted \"value\"']", std::vector<key>(1, "quoted \"value\"" )); } BOOST_AUTO_TEST_CASE(test_table_dotted_key) { { std::vector<key> keys(2); keys[0] = "physical"; keys[1] = "color"; TOML11_TEST_PARSE_EQUAL(parse_table_key, "[physical.color]", keys); } { std::vector<key> keys(2); keys[0] = "physical"; keys[1] = "shape"; TOML11_TEST_PARSE_EQUAL(parse_table_key, "[physical.shape]", keys); } { std::vector<key> keys(4); keys[0] = "x"; keys[1] = "y"; keys[2] = "z"; keys[3] = "w"; TOML11_TEST_PARSE_EQUAL(parse_table_key, "[x.y.z.w]", keys); TOML11_TEST_PARSE_EQUAL(parse_table_key, "[x . y . z . w]", keys); TOML11_TEST_PARSE_EQUAL(parse_table_key, "[x. y .z. w]", keys); TOML11_TEST_PARSE_EQUAL(parse_table_key, "[x .y. z .w]", keys); TOML11_TEST_PARSE_EQUAL(parse_table_key, "[ x. y .z . w ]", keys); TOML11_TEST_PARSE_EQUAL(parse_table_key, "[ x . y . z . w ]", keys); } { std::vector<key> keys(2); keys[0] = "site"; keys[1] = "google.com"; TOML11_TEST_PARSE_EQUAL(parse_table_key, "[site.\"google.com\"]", keys); } } BOOST_AUTO_TEST_CASE(test_array_of_table_bare_key) { TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[[barekey]]", std::vector<key>(1, "barekey")); TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[[bare-key]]", std::vector<key>(1, "bare-key")); TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[[bare_key]]", std::vector<key>(1, "bare_key")); TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[[1234]]", std::vector<key>(1, "1234")); } BOOST_AUTO_TEST_CASE(test_array_of_table_quoted_key) { TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[[\"127.0.0.1\"]]", std::vector<key>(1, "127.0.0.1" )); TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[[\"character encoding\"]]", std::vector<key>(1, "character encoding")); TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[[\"ʎǝʞ\"]]", std::vector<key>(1, "ʎǝʞ" )); TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[['key2']]", std::vector<key>(1, "key2" )); TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[['quoted \"value\"']]", std::vector<key>(1, "quoted \"value\"" )); } BOOST_AUTO_TEST_CASE(test_array_of_table_dotted_key) { { std::vector<key> keys(2); keys[0] = "physical"; keys[1] = "color"; TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[[physical.color]]", keys); } { std::vector<key> keys(2); keys[0] = "physical"; keys[1] = "shape"; TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[[physical.shape]]", keys); } { std::vector<key> keys(4); keys[0] = "x"; keys[1] = "y"; keys[2] = "z"; keys[3] = "w"; TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[[x.y.z.w]]", keys); TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[[x . y . z . w]]", keys); TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[[x. y .z. w]]", keys); TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[[x .y. z .w]]", keys); TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[[ x. y .z . w ]]", keys); TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[[ x . y . z . w ]]", keys); } { std::vector<key> keys(2); keys[0] = "site"; keys[1] = "google.com"; TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[[site.\"google.com\"]]", keys); } } <|endoftext|>
<commit_before>#include "bitcoinunits.h" #include <QStringList> BitcoinUnits::BitcoinUnits(QObject *parent): QAbstractListModel(parent), unitlist(availableUnits()) { } QList<BitcoinUnits::Unit> BitcoinUnits::availableUnits() { QList<BitcoinUnits::Unit> unitlist; unitlist.append(BTC); unitlist.append(mBTC); unitlist.append(uBTC); return unitlist; } bool BitcoinUnits::valid(int unit) { switch(unit) { case BTC: case mBTC: case uBTC: return true; default: return false; } } QString BitcoinUnits::name(int unit) { switch(unit) { case BTC: return QString("EAC"); case mBTC: return QString("EAC"); case uBTC: return QString::fromUtf8("μEAC"); default: return QString("???"); } } QString BitcoinUnits::description(int unit) { switch(unit) { case BTC: return QString("EarthCoins"); case mBTC: return QString("Milli-EarthCoins (1 / 1,000)"); case uBTC: return QString("Micro-EarthCoins (1 / 1,000,000)"); default: return QString("???"); } } qint64 BitcoinUnits::factor(int unit) { switch(unit) { case BTC: return 100000000; case mBTC: return 100000; case uBTC: return 100; default: return 100000000; } } int BitcoinUnits::amountDigits(int unit) { switch(unit) { case BTC: return 8; // 21,000,000 (# digits, without commas) case mBTC: return 11; // 21,000,000,000 case uBTC: return 14; // 21,000,000,000,000 default: return 0; } } int BitcoinUnits::decimals(int unit) { switch(unit) { case BTC: return 8; case mBTC: return 5; case uBTC: return 2; default: return 0; } } QString BitcoinUnits::format(int unit, qint64 n, bool fPlus) { // Note: not using straight sprintf here because we do NOT want // localized number formatting. if(!valid(unit)) return QString(); // Refuse to format invalid unit qint64 coin = factor(unit); int num_decimals = decimals(unit); qint64 n_abs = (n > 0 ? n : -n); qint64 quotient = n_abs / coin; qint64 remainder = n_abs % coin; QString quotient_str = QString::number(quotient); QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0'); // Right-trim excess 0's after the decimal point int nTrim = 0; for (int i = remainder_str.size()-1; i>=2 && (remainder_str.at(i) == '0'); --i) ++nTrim; remainder_str.chop(nTrim); if (n < 0) quotient_str.insert(0, '-'); else if (fPlus && n > 0) quotient_str.insert(0, '+'); return quotient_str + QString(".") + remainder_str; } QString BitcoinUnits::formatWithUnit(int unit, qint64 amount, bool plussign) { return format(unit, amount, plussign) + QString(" ") + name(unit); } bool BitcoinUnits::parse(int unit, const QString &value, qint64 *val_out) { if(!valid(unit) || value.isEmpty()) return false; // Refuse to parse invalid unit or empty string int num_decimals = decimals(unit); QStringList parts = value.split("."); if(parts.size() > 2) { return false; // More than one dot } QString whole = parts[0]; QString decimals; if(parts.size() > 1) { decimals = parts[1]; } if(decimals.size() > num_decimals) { return false; // Exceeds max precision } bool ok = false; QString str = whole + decimals.leftJustified(num_decimals, '0'); if(str.size() > 18) { return false; // Longer numbers will exceed 63 bits } qint64 retvalue = str.toLongLong(&ok); if(val_out) { *val_out = retvalue; } return ok; } int BitcoinUnits::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return unitlist.size(); } QVariant BitcoinUnits::data(const QModelIndex &index, int role) const { int row = index.row(); if(row >= 0 && row < unitlist.size()) { Unit unit = unitlist.at(row); switch(role) { case Qt::EditRole: case Qt::DisplayRole: return QVariant(name(unit)); case Qt::ToolTipRole: return QVariant(description(unit)); case UnitRole: return QVariant(static_cast<int>(unit)); } } return QVariant(); } <commit_msg>display the correct abbreviation for milli-earthcoins<commit_after>#include "bitcoinunits.h" #include <QStringList> BitcoinUnits::BitcoinUnits(QObject *parent): QAbstractListModel(parent), unitlist(availableUnits()) { } QList<BitcoinUnits::Unit> BitcoinUnits::availableUnits() { QList<BitcoinUnits::Unit> unitlist; unitlist.append(BTC); unitlist.append(mBTC); unitlist.append(uBTC); return unitlist; } bool BitcoinUnits::valid(int unit) { switch(unit) { case BTC: case mBTC: case uBTC: return true; default: return false; } } QString BitcoinUnits::name(int unit) { switch(unit) { case BTC: return QString("EAC"); case mBTC: return QString("mEAC"); case uBTC: return QString::fromUtf8("μEAC"); default: return QString("???"); } } QString BitcoinUnits::description(int unit) { switch(unit) { case BTC: return QString("EarthCoins"); case mBTC: return QString("Milli-EarthCoins (1 / 1,000)"); case uBTC: return QString("Micro-EarthCoins (1 / 1,000,000)"); default: return QString("???"); } } qint64 BitcoinUnits::factor(int unit) { switch(unit) { case BTC: return 100000000; case mBTC: return 100000; case uBTC: return 100; default: return 100000000; } } int BitcoinUnits::amountDigits(int unit) { switch(unit) { case BTC: return 8; // 21,000,000 (# digits, without commas) case mBTC: return 11; // 21,000,000,000 case uBTC: return 14; // 21,000,000,000,000 default: return 0; } } int BitcoinUnits::decimals(int unit) { switch(unit) { case BTC: return 8; case mBTC: return 5; case uBTC: return 2; default: return 0; } } QString BitcoinUnits::format(int unit, qint64 n, bool fPlus) { // Note: not using straight sprintf here because we do NOT want // localized number formatting. if(!valid(unit)) return QString(); // Refuse to format invalid unit qint64 coin = factor(unit); int num_decimals = decimals(unit); qint64 n_abs = (n > 0 ? n : -n); qint64 quotient = n_abs / coin; qint64 remainder = n_abs % coin; QString quotient_str = QString::number(quotient); QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0'); // Right-trim excess 0's after the decimal point int nTrim = 0; for (int i = remainder_str.size()-1; i>=2 && (remainder_str.at(i) == '0'); --i) ++nTrim; remainder_str.chop(nTrim); if (n < 0) quotient_str.insert(0, '-'); else if (fPlus && n > 0) quotient_str.insert(0, '+'); return quotient_str + QString(".") + remainder_str; } QString BitcoinUnits::formatWithUnit(int unit, qint64 amount, bool plussign) { return format(unit, amount, plussign) + QString(" ") + name(unit); } bool BitcoinUnits::parse(int unit, const QString &value, qint64 *val_out) { if(!valid(unit) || value.isEmpty()) return false; // Refuse to parse invalid unit or empty string int num_decimals = decimals(unit); QStringList parts = value.split("."); if(parts.size() > 2) { return false; // More than one dot } QString whole = parts[0]; QString decimals; if(parts.size() > 1) { decimals = parts[1]; } if(decimals.size() > num_decimals) { return false; // Exceeds max precision } bool ok = false; QString str = whole + decimals.leftJustified(num_decimals, '0'); if(str.size() > 18) { return false; // Longer numbers will exceed 63 bits } qint64 retvalue = str.toLongLong(&ok); if(val_out) { *val_out = retvalue; } return ok; } int BitcoinUnits::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return unitlist.size(); } QVariant BitcoinUnits::data(const QModelIndex &index, int role) const { int row = index.row(); if(row >= 0 && row < unitlist.size()) { Unit unit = unitlist.at(row); switch(role) { case Qt::EditRole: case Qt::DisplayRole: return QVariant(name(unit)); case Qt::ToolTipRole: return QVariant(description(unit)); case UnitRole: return QVariant(static_cast<int>(unit)); } } return QVariant(); } <|endoftext|>
<commit_before>// Source : https://oj.leetcode.com/problems/maximum-depth-of-binary-tree/ // Author : Hao Chen // Date : 2014-06-21 /********************************************************************************** * * Given a binary tree, find its maximum depth. * * The maximum depth is the number of nodes along the longest path from the root node * down to the farthest leaf node. * **********************************************************************************/ /** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int maxDepth(TreeNode *root) { if (root==NULL){ return 0; } if (!root->left && !root->right){ return 1; } int left=1, right=1; if (root->left){ left += maxDepth(root->left); } if (root->right){ right += maxDepth(root->right); } return left>right?left:right; } }; <commit_msg> modified: algorithms/cpp/maximumDepthOfBinaryTree/maximumDepthOfBinaryTree.cpp 使用 max 函数以及递归 精简实现<commit_after>// Source : https://oj.leetcode.com/problems/maximum-depth-of-binary-tree/ // Author : Hao Chen // Date : 2014-06-21 /********************************************************************************** * * Given a binary tree, find its maximum depth. * * The maximum depth is the number of nodes along the longest path from the root node * down to the farthest leaf node. * **********************************************************************************/ /** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int maxDepth(TreeNode *root) { if (root==NULL){ return 0; } if (!root->left && !root->right){ return 1; } int left=1, right=1; if (root->left){ left += maxDepth(root->left); } if (root->right){ right += maxDepth(root->right); } return left>right?left:right; } }; class Solution2 { public: int maxDepth(TreeNode *root) { if (root==NULL) return 0; return max(maxDepth(root->left), maxDepth(root->right)) + 1; } }; <|endoftext|>
<commit_before>// Copyright (c) 2011-2015 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 "overviewpage.h" #include "ui_overviewpage.h" #include "skinize.h" #include "navcoinunits.h" #include "clientmodel.h" #include "guiconstants.h" #include "guiutil.h" #include "optionsmodel.h" #include "platformstyle.h" #include "transactionfilterproxy.h" #include "transactiontablemodel.h" #include "walletmodel.h" #include "walletframe.h" #include "askpassphrasedialog.h" #include "util.h" #include <QAbstractItemDelegate> #include <QPainter> #define DECORATION_SIZE 17 #define NUM_ITEMS 5 class TxViewDelegate : public QAbstractItemDelegate { Q_OBJECT public: TxViewDelegate(const PlatformStyle *platformStyle): QAbstractItemDelegate(), unit(NavCoinUnits::NAV), platformStyle(platformStyle) { } inline void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const { painter->save(); QIcon icon = qvariant_cast<QIcon>(index.data(TransactionTableModel::RawDecorationRole)); QRect mainRect = option.rect; QRect decorationRect(mainRect.left(), mainRect.top()+DECORATION_SIZE, DECORATION_SIZE, DECORATION_SIZE); int xspace = DECORATION_SIZE + 6; int ypad = 1; int halfheight = (mainRect.height() - 3*ypad - 4)/3 ; QRect amountRect(mainRect.left() + xspace, mainRect.top()+ypad+halfheight, 150, DECORATION_SIZE); QRect addressRect(mainRect.left() + xspace, mainRect.top()+ypad, 300, DECORATION_SIZE); QRect dateRect(mainRect.left() + xspace, mainRect.top()+ypad+halfheight*2, 150, DECORATION_SIZE); icon = platformStyle->SingleColorIcon(icon); icon.paint(painter, decorationRect); QDateTime date = index.data(TransactionTableModel::DateRole).toDateTime(); QString address = index.data(Qt::DisplayRole).toString(); qint64 amount = index.data(TransactionTableModel::AmountRole).toLongLong(); bool confirmed = index.data(TransactionTableModel::ConfirmedRole).toBool(); QVariant value = index.data(Qt::ForegroundRole); QColor foreground = option.palette.color(QPalette::Text); painter->setPen(QColor(60,60,60)); QRect boundingRect; painter->drawText(addressRect, Qt::AlignLeft|Qt::AlignVCenter, address, &boundingRect); if (index.data(TransactionTableModel::WatchonlyRole).toBool()) { QIcon iconWatchonly = qvariant_cast<QIcon>(index.data(TransactionTableModel::WatchonlyDecorationRole)); QRect watchonlyRect(boundingRect.right() + 5, mainRect.top()+ypad+halfheight, 16, halfheight); iconWatchonly.paint(painter, watchonlyRect); } if(amount < 0) { foreground = COLOR_NEGATIVE; } else if(!confirmed) { foreground = COLOR_UNCONFIRMED; } else { foreground = COLOR_POSITIVE; } painter->setPen(foreground); QString amountText = NavCoinUnits::formatWithUnit(unit, amount, true, NavCoinUnits::separatorAlways); if(!confirmed) { amountText = QString("[") + amountText + QString("]"); } painter->drawText(amountRect, Qt::AlignLeft|Qt::AlignVCenter, amountText); painter->setPen(COLOR_BAREADDRESS); painter->drawText(dateRect, Qt::AlignLeft|Qt::AlignVCenter, GUIUtil::dateTimeStr(date)); painter->restore(); } inline QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { return QSize(DECORATION_SIZE, DECORATION_SIZE*2.9 + 4); } int unit; const PlatformStyle *platformStyle; }; #include "overviewpage.moc" OverviewPage::OverviewPage(const PlatformStyle *platformStyle, QWidget *parent) : QWidget(parent), ui(new Ui::OverviewPage), clientModel(0), walletModel(0), currentBalance(-1), currentUnconfirmedBalance(-1), currentStakingBalance(-1), currentImmatureBalance(-1), currentWatchOnlyBalance(-1), currentWatchUnconfBalance(-1), currentWatchImmatureBalance(-1), txdelegate(new TxViewDelegate(platformStyle)), filter(0) { ui->setupUi(this); // use a SingleColorIcon for the "out of sync warning" icon QIcon icon = platformStyle->SingleColorIcon(":/icons/warning"); icon.addPixmap(icon.pixmap(QSize(64,64), QIcon::Normal), QIcon::Disabled); // also set the disabled icon because we are using a disabled QPushButton to work around missing HiDPI support of QLabel (https://bugreports.qt.io/browse/QTBUG-42503) ui->labelWalletStatus->setIcon(icon); // Recent transactions ui->listTransactions->setItemDelegate(txdelegate); ui->listTransactions->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE)); ui->listTransactions->setMinimumHeight(NUM_ITEMS * 3 * (DECORATION_SIZE + 2)); ui->listTransactions->setAttribute(Qt::WA_MacShowFocusRect, false); connect(ui->listTransactions, SIGNAL(clicked(QModelIndex)), this, SLOT(handleTransactionClicked(QModelIndex))); connect(ui->unlockStakingButton, SIGNAL(clicked()), this, SLOT(unlockWalletStaking())); // start with displaying the "out of sync" warnings showOutOfSyncWarning(true); updateStakeReportNow(); } void OverviewPage::handleTransactionClicked(const QModelIndex &index) { if(filter) Q_EMIT transactionClicked(filter->mapToSource(index)); } void OverviewPage::showLockStaking(bool status) { ui->unlockStakingButton->setVisible(status); } OverviewPage::~OverviewPage() { delete ui; } void OverviewPage::setStakingStats(QString day, QString week, QString month) { ui->label24hStakingStats->setText(day); ui->label7dStakingStats->setText(week); ui->label30dStakingStats->setText(month); } void OverviewPage::setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& stakingBalance, const CAmount& immatureBalance, const CAmount& watchOnlyBalance, const CAmount& watchUnconfBalance, const CAmount& watchImmatureBalance) { int unit = walletModel->getOptionsModel()->getDisplayUnit(); currentBalance = balance; currentUnconfirmedBalance = unconfirmedBalance; currentStakingBalance = stakingBalance; currentImmatureBalance = immatureBalance; currentWatchOnlyBalance = watchOnlyBalance; currentWatchUnconfBalance = watchUnconfBalance; currentWatchImmatureBalance = watchImmatureBalance; ui->labelBalance->setText(NavCoinUnits::formatWithUnit(unit, balance, false, NavCoinUnits::separatorAlways)); ui->labelUnconfirmed->setText(NavCoinUnits::formatWithUnit(unit, unconfirmedBalance, false, NavCoinUnits::separatorAlways)); ui->labelStaking->setText(NavCoinUnits::formatWithUnit(unit, stakingBalance, false, NavCoinUnits::separatorAlways)); ui->labelImmature->setText(NavCoinUnits::formatWithUnit(unit, immatureBalance, false, NavCoinUnits::separatorAlways)); ui->labelTotal->setText(NavCoinUnits::formatWithUnit(unit, balance + unconfirmedBalance + stakingBalance + immatureBalance, false, NavCoinUnits::separatorAlways)); bool showStaking = immatureBalance != 0; ui->labelStaking->setVisible(showStaking); ui->labelStakingText->setVisible(showStaking); // only show immature (newly mined) balance if it's non-zero, so as not to complicate things // for the non-mining users bool showImmature = immatureBalance != 0; bool showWatchOnlyImmature = watchImmatureBalance != 0; // for symmetry reasons also show immature label when the watch-only one is shown ui->labelImmature->setVisible(showImmature || showWatchOnlyImmature); ui->labelImmatureText->setVisible(showImmature || showWatchOnlyImmature); } // show/hide watch-only labels void OverviewPage::updateWatchOnlyLabels(bool showWatchOnly) { } void OverviewPage::setStakingStatus(QString text) { ui->stakingStatusLabel->setText(text); }; void OverviewPage::setStatusTitleBlocks(QString text) { ui->statusTitleBlocks->setText(text); } void OverviewPage::setStatusTitleConnections(QString text) { ui->statusTitleConnections->setText(text); } void OverviewPage::setStatusTitle(QString text) { ui->statusTitle->setText(text); } void OverviewPage::showStatusTitleConnections(){ ui->statusTitleConnections->show(); }; void OverviewPage::hideStatusTitleConnections(){ ui->statusTitleConnections->hide(); }; void OverviewPage::showStatusTitleBlocks(){ ui->statusTitleBlocks->show(); }; void OverviewPage::hideStatusTitleBlocks(){ ui->statusTitleBlocks->hide(); }; void OverviewPage::setClientModel(ClientModel *model) { this->clientModel = model; if(model) { // Show warning if this is a prerelease version connect(model, SIGNAL(alertsChanged(QString)), this, SLOT(updateAlerts(QString))); updateAlerts(model->getStatusBarWarnings()); } } void OverviewPage::setWalletModel(WalletModel *model) { this->walletModel = model; if(model && model->getOptionsModel()) { // Set up transaction list filter = new TransactionFilterProxy(); filter->setSourceModel(model->getTransactionTableModel()); filter->setLimit(NUM_ITEMS); filter->setDynamicSortFilter(true); filter->setSortRole(Qt::EditRole); filter->setShowInactive(false); filter->sort(TransactionTableModel::Date, Qt::DescendingOrder); ui->listTransactions->setModel(filter); ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress); // Keep up to date with wallet setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getStake(), model->getImmatureBalance(), model->getWatchBalance(), model->getWatchUnconfirmedBalance(), model->getWatchImmatureBalance()); connect(model, SIGNAL(balanceChanged(CAmount,CAmount,CAmount,CAmount,CAmount,CAmount,CAmount)), this, SLOT(setBalance(CAmount,CAmount,CAmount,CAmount,CAmount,CAmount,CAmount))); connect(model, SIGNAL(balanceChanged(CAmount, CAmount, CAmount, CAmount,CAmount,CAmount,CAmount)), this, SLOT(updateStakeReportbalanceChanged(CAmount, CAmount, CAmount,CAmount, CAmount,CAmount,CAmount))); connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); updateWatchOnlyLabels(model->haveWatchOnly()); connect(model, SIGNAL(notifyWatchonlyChanged(bool)), this, SLOT(updateWatchOnlyLabels(bool))); } // update the display unit, to not use the default ("NAV") updateDisplayUnit(); } void OverviewPage::updateDisplayUnit() { if(walletModel && walletModel->getOptionsModel()) { if(currentBalance != -1) setBalance(currentBalance, currentUnconfirmedBalance, currentStakingBalance, currentImmatureBalance, currentWatchOnlyBalance, currentWatchUnconfBalance, currentWatchImmatureBalance); // Update txdelegate->unit with the current unit txdelegate->unit = walletModel->getOptionsModel()->getDisplayUnit(); ui->listTransactions->update(); } } void OverviewPage::unlockWalletStaking() { if(!walletModel) return; // Unlock wallet when requested by wallet model if (walletModel->getEncryptionStatus() == WalletModel::Locked) { AskPassphraseDialog dlg(AskPassphraseDialog::UnlockStaking, this); dlg.setModel(walletModel); dlg.exec(); } } void OverviewPage::updateAlerts(const QString &warnings) { this->ui->labelAlerts->setVisible(!warnings.isEmpty()); this->ui->labelAlerts->setText(warnings); } void OverviewPage::showOutOfSyncWarning(bool fShow) { ui->labelWalletStatus->setVisible(fShow); } using namespace boost; using namespace std; struct StakePeriodRange_T { int64_t Start; int64_t End; int64_t Total; int Count; string Name; }; typedef vector<StakePeriodRange_T> vStakePeriodRange_T; extern vStakePeriodRange_T PrepareRangeForStakeReport(); extern int GetsStakeSubTotal(vStakePeriodRange_T& aRange); void OverviewPage::updateStakeReport(bool fImmediate=false) { static vStakePeriodRange_T aRange; int nItemCounted=0; if (fImmediate) nLastReportUpdate = 0; if (this->isHidden()) return; int64_t nTook = GetTimeMillis(); // Skip report recalc if not immediate or before 5 minutes from last if (GetTime() - nLastReportUpdate > 300) { aRange = PrepareRangeForStakeReport(); // get subtotal calc nItemCounted = GetsStakeSubTotal(aRange); nLastReportUpdate = GetTime(); nTook = GetTimeMillis() - nTook; } int64_t nTook2 = GetTimeMillis(); int i=30; int unit = walletModel->getOptionsModel()->getDisplayUnit(); ui->label24hStakingStats->setText(NavCoinUnits::formatWithUnit(unit, aRange[i++].Total, false, NavCoinUnits::separatorAlways)); ui->label7dStakingStats->setText(NavCoinUnits::formatWithUnit(unit, aRange[i++].Total, false, NavCoinUnits::separatorAlways)); ui->label30dStakingStats->setText(NavCoinUnits::formatWithUnit(unit, aRange[i++].Total, false, NavCoinUnits::separatorAlways)); } void OverviewPage::updateStakeReportbalanceChanged(qint64, qint64, qint64, qint64, qint64, qint64, qint64) { OverviewPage::updateStakeReportNow(); } void OverviewPage::updateStakeReportNow() { updateStakeReport(true); } <commit_msg>gui: fixed balance amount<commit_after>// Copyright (c) 2011-2015 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 "overviewpage.h" #include "ui_overviewpage.h" #include "skinize.h" #include "navcoinunits.h" #include "clientmodel.h" #include "guiconstants.h" #include "guiutil.h" #include "optionsmodel.h" #include "platformstyle.h" #include "transactionfilterproxy.h" #include "transactiontablemodel.h" #include "walletmodel.h" #include "walletframe.h" #include "askpassphrasedialog.h" #include "util.h" #include <QAbstractItemDelegate> #include <QPainter> #define DECORATION_SIZE 17 #define NUM_ITEMS 5 class TxViewDelegate : public QAbstractItemDelegate { Q_OBJECT public: TxViewDelegate(const PlatformStyle *platformStyle): QAbstractItemDelegate(), unit(NavCoinUnits::NAV), platformStyle(platformStyle) { } inline void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const { painter->save(); QIcon icon = qvariant_cast<QIcon>(index.data(TransactionTableModel::RawDecorationRole)); QRect mainRect = option.rect; QRect decorationRect(mainRect.left(), mainRect.top()+DECORATION_SIZE, DECORATION_SIZE, DECORATION_SIZE); int xspace = DECORATION_SIZE + 6; int ypad = 1; int halfheight = (mainRect.height() - 3*ypad - 4)/3 ; QRect amountRect(mainRect.left() + xspace, mainRect.top()+ypad+halfheight, 150, DECORATION_SIZE); QRect addressRect(mainRect.left() + xspace, mainRect.top()+ypad, 300, DECORATION_SIZE); QRect dateRect(mainRect.left() + xspace, mainRect.top()+ypad+halfheight*2, 150, DECORATION_SIZE); icon = platformStyle->SingleColorIcon(icon); icon.paint(painter, decorationRect); QDateTime date = index.data(TransactionTableModel::DateRole).toDateTime(); QString address = index.data(Qt::DisplayRole).toString(); qint64 amount = index.data(TransactionTableModel::AmountRole).toLongLong(); bool confirmed = index.data(TransactionTableModel::ConfirmedRole).toBool(); QVariant value = index.data(Qt::ForegroundRole); QColor foreground = option.palette.color(QPalette::Text); painter->setPen(QColor(60,60,60)); QRect boundingRect; painter->drawText(addressRect, Qt::AlignLeft|Qt::AlignVCenter, address, &boundingRect); if (index.data(TransactionTableModel::WatchonlyRole).toBool()) { QIcon iconWatchonly = qvariant_cast<QIcon>(index.data(TransactionTableModel::WatchonlyDecorationRole)); QRect watchonlyRect(boundingRect.right() + 5, mainRect.top()+ypad+halfheight, 16, halfheight); iconWatchonly.paint(painter, watchonlyRect); } if(amount < 0) { foreground = COLOR_NEGATIVE; } else if(!confirmed) { foreground = COLOR_UNCONFIRMED; } else { foreground = COLOR_POSITIVE; } painter->setPen(foreground); QString amountText = NavCoinUnits::formatWithUnit(unit, amount, true, NavCoinUnits::separatorAlways); if(!confirmed) { amountText = QString("[") + amountText + QString("]"); } painter->drawText(amountRect, Qt::AlignLeft|Qt::AlignVCenter, amountText); painter->setPen(COLOR_BAREADDRESS); painter->drawText(dateRect, Qt::AlignLeft|Qt::AlignVCenter, GUIUtil::dateTimeStr(date)); painter->restore(); } inline QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { return QSize(DECORATION_SIZE, DECORATION_SIZE*2.9 + 4); } int unit; const PlatformStyle *platformStyle; }; #include "overviewpage.moc" OverviewPage::OverviewPage(const PlatformStyle *platformStyle, QWidget *parent) : QWidget(parent), ui(new Ui::OverviewPage), clientModel(0), walletModel(0), currentBalance(-1), currentUnconfirmedBalance(-1), currentStakingBalance(-1), currentImmatureBalance(-1), currentWatchOnlyBalance(-1), currentWatchUnconfBalance(-1), currentWatchImmatureBalance(-1), txdelegate(new TxViewDelegate(platformStyle)), filter(0) { ui->setupUi(this); // use a SingleColorIcon for the "out of sync warning" icon QIcon icon = platformStyle->SingleColorIcon(":/icons/warning"); icon.addPixmap(icon.pixmap(QSize(64,64), QIcon::Normal), QIcon::Disabled); // also set the disabled icon because we are using a disabled QPushButton to work around missing HiDPI support of QLabel (https://bugreports.qt.io/browse/QTBUG-42503) ui->labelWalletStatus->setIcon(icon); // Recent transactions ui->listTransactions->setItemDelegate(txdelegate); ui->listTransactions->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE)); ui->listTransactions->setMinimumHeight(NUM_ITEMS * 3 * (DECORATION_SIZE + 2)); ui->listTransactions->setAttribute(Qt::WA_MacShowFocusRect, false); connect(ui->listTransactions, SIGNAL(clicked(QModelIndex)), this, SLOT(handleTransactionClicked(QModelIndex))); connect(ui->unlockStakingButton, SIGNAL(clicked()), this, SLOT(unlockWalletStaking())); // start with displaying the "out of sync" warnings showOutOfSyncWarning(true); updateStakeReportNow(); } void OverviewPage::handleTransactionClicked(const QModelIndex &index) { if(filter) Q_EMIT transactionClicked(filter->mapToSource(index)); } void OverviewPage::showLockStaking(bool status) { ui->unlockStakingButton->setVisible(status); } OverviewPage::~OverviewPage() { delete ui; } void OverviewPage::setStakingStats(QString day, QString week, QString month) { ui->label24hStakingStats->setText(day); ui->label7dStakingStats->setText(week); ui->label30dStakingStats->setText(month); } void OverviewPage::setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& stakingBalance, const CAmount& immatureBalance, const CAmount& watchOnlyBalance, const CAmount& watchUnconfBalance, const CAmount& watchImmatureBalance) { int unit = walletModel->getOptionsModel()->getDisplayUnit(); currentBalance = balance; currentUnconfirmedBalance = unconfirmedBalance; currentStakingBalance = stakingBalance; currentImmatureBalance = immatureBalance; currentWatchOnlyBalance = watchOnlyBalance; currentWatchUnconfBalance = watchUnconfBalance; currentWatchImmatureBalance = watchImmatureBalance; ui->labelBalance->setText(NavCoinUnits::formatWithUnit(unit, balance, false, NavCoinUnits::separatorAlways)); ui->labelUnconfirmed->setText(NavCoinUnits::formatWithUnit(unit, unconfirmedBalance, false, NavCoinUnits::separatorAlways)); ui->labelStaking->setText(NavCoinUnits::formatWithUnit(unit, stakingBalance, false, NavCoinUnits::separatorAlways)); ui->labelImmature->setText(NavCoinUnits::formatWithUnit(unit, immatureBalance, false, NavCoinUnits::separatorAlways)); ui->labelTotal->setText(NavCoinUnits::formatWithUnit(unit, balance + unconfirmedBalance + stakingBalance, false, NavCoinUnits::separatorAlways)); bool showStaking = stakingBalance != 0; ui->labelStaking->setVisible(showStaking); ui->labelStakingText->setVisible(showStaking); // only show immature (newly mined) balance if it's non-zero, so as not to complicate things // for the non-mining users bool showImmature = false; bool showWatchOnlyImmature = watchImmatureBalance != 0; // for symmetry reasons also show immature label when the watch-only one is shown ui->labelImmature->setVisible(false); ui->labelImmatureText->setVisible(false); } // show/hide watch-only labels void OverviewPage::updateWatchOnlyLabels(bool showWatchOnly) { } void OverviewPage::setStakingStatus(QString text) { ui->stakingStatusLabel->setText(text); }; void OverviewPage::setStatusTitleBlocks(QString text) { ui->statusTitleBlocks->setText(text); } void OverviewPage::setStatusTitleConnections(QString text) { ui->statusTitleConnections->setText(text); } void OverviewPage::setStatusTitle(QString text) { ui->statusTitle->setText(text); } void OverviewPage::showStatusTitleConnections(){ ui->statusTitleConnections->show(); }; void OverviewPage::hideStatusTitleConnections(){ ui->statusTitleConnections->hide(); }; void OverviewPage::showStatusTitleBlocks(){ ui->statusTitleBlocks->show(); }; void OverviewPage::hideStatusTitleBlocks(){ ui->statusTitleBlocks->hide(); }; void OverviewPage::setClientModel(ClientModel *model) { this->clientModel = model; if(model) { // Show warning if this is a prerelease version connect(model, SIGNAL(alertsChanged(QString)), this, SLOT(updateAlerts(QString))); updateAlerts(model->getStatusBarWarnings()); } } void OverviewPage::setWalletModel(WalletModel *model) { this->walletModel = model; if(model && model->getOptionsModel()) { // Set up transaction list filter = new TransactionFilterProxy(); filter->setSourceModel(model->getTransactionTableModel()); filter->setLimit(NUM_ITEMS); filter->setDynamicSortFilter(true); filter->setSortRole(Qt::EditRole); filter->setShowInactive(false); filter->sort(TransactionTableModel::Date, Qt::DescendingOrder); ui->listTransactions->setModel(filter); ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress); // Keep up to date with wallet setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getStake(), model->getImmatureBalance(), model->getWatchBalance(), model->getWatchUnconfirmedBalance(), model->getWatchImmatureBalance()); connect(model, SIGNAL(balanceChanged(CAmount,CAmount,CAmount,CAmount,CAmount,CAmount,CAmount)), this, SLOT(setBalance(CAmount,CAmount,CAmount,CAmount,CAmount,CAmount,CAmount))); connect(model, SIGNAL(balanceChanged(CAmount, CAmount, CAmount, CAmount,CAmount,CAmount,CAmount)), this, SLOT(updateStakeReportbalanceChanged(CAmount, CAmount, CAmount,CAmount, CAmount,CAmount,CAmount))); connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); updateWatchOnlyLabels(model->haveWatchOnly()); connect(model, SIGNAL(notifyWatchonlyChanged(bool)), this, SLOT(updateWatchOnlyLabels(bool))); } // update the display unit, to not use the default ("NAV") updateDisplayUnit(); } void OverviewPage::updateDisplayUnit() { if(walletModel && walletModel->getOptionsModel()) { if(currentBalance != -1) setBalance(currentBalance, currentUnconfirmedBalance, currentStakingBalance, currentImmatureBalance, currentWatchOnlyBalance, currentWatchUnconfBalance, currentWatchImmatureBalance); // Update txdelegate->unit with the current unit txdelegate->unit = walletModel->getOptionsModel()->getDisplayUnit(); ui->listTransactions->update(); } } void OverviewPage::unlockWalletStaking() { if(!walletModel) return; // Unlock wallet when requested by wallet model if (walletModel->getEncryptionStatus() == WalletModel::Locked) { AskPassphraseDialog dlg(AskPassphraseDialog::UnlockStaking, this); dlg.setModel(walletModel); dlg.exec(); } } void OverviewPage::updateAlerts(const QString &warnings) { this->ui->labelAlerts->setVisible(!warnings.isEmpty()); this->ui->labelAlerts->setText(warnings); } void OverviewPage::showOutOfSyncWarning(bool fShow) { ui->labelWalletStatus->setVisible(fShow); } using namespace boost; using namespace std; struct StakePeriodRange_T { int64_t Start; int64_t End; int64_t Total; int Count; string Name; }; typedef vector<StakePeriodRange_T> vStakePeriodRange_T; extern vStakePeriodRange_T PrepareRangeForStakeReport(); extern int GetsStakeSubTotal(vStakePeriodRange_T& aRange); void OverviewPage::updateStakeReport(bool fImmediate=false) { static vStakePeriodRange_T aRange; int nItemCounted=0; if (fImmediate) nLastReportUpdate = 0; if (this->isHidden()) return; int64_t nTook = GetTimeMillis(); // Skip report recalc if not immediate or before 5 minutes from last if (GetTime() - nLastReportUpdate > 300) { aRange = PrepareRangeForStakeReport(); // get subtotal calc nItemCounted = GetsStakeSubTotal(aRange); nLastReportUpdate = GetTime(); nTook = GetTimeMillis() - nTook; } int64_t nTook2 = GetTimeMillis(); int i=30; int unit = walletModel->getOptionsModel()->getDisplayUnit(); ui->label24hStakingStats->setText(NavCoinUnits::formatWithUnit(unit, aRange[i++].Total, false, NavCoinUnits::separatorAlways)); ui->label7dStakingStats->setText(NavCoinUnits::formatWithUnit(unit, aRange[i++].Total, false, NavCoinUnits::separatorAlways)); ui->label30dStakingStats->setText(NavCoinUnits::formatWithUnit(unit, aRange[i++].Total, false, NavCoinUnits::separatorAlways)); } void OverviewPage::updateStakeReportbalanceChanged(qint64, qint64, qint64, qint64, qint64, qint64, qint64) { OverviewPage::updateStakeReportNow(); } void OverviewPage::updateStakeReportNow() { updateStakeReport(true); } <|endoftext|>
<commit_before>#include "splashscreen.h" #include "clientversion.h" #include "util.h" #include <QPainter> #undef loop /* ugh, remove this when the #define loop is gone from util.h */ #include <QApplication> SplashScreen::SplashScreen(const QPixmap &pixmap, Qt::WindowFlags f) : QSplashScreen(pixmap, f) { // set reference point, paddings int paddingLeftCol2 = 130; int paddingTopCol2 = 376; int line1 = 0; int line2 = 13; int line3 = 26; float fontFactor = 1.0; // define text to place QString titleText = QString(QApplication::applicationName()).replace(QString("-testnet"), QString(""), Qt::CaseSensitive); // cut of testnet, place it as single object further down QString versionText = QString("Version %1 ").arg(QString::fromStdString(FormatFullVersion())); QString copyrightText1 = QChar(0xA9)+QString(" 2009-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Bitcoin developers")); QString copyrightText2 = QChar(0xA9)+QString(" %1 ").arg(COPYRIGHT_YEAR) + QString(tr("The FlappyCoin developers")); QString font = "Arial"; // load the bitmap for writing some text over it QPixmap newPixmap; if(GetBoolArg("-testnet")) { newPixmap = QPixmap(":/images/splash_testnet"); } else { newPixmap = QPixmap(":/images/splash"); } QPainter pixPaint(&newPixmap); pixPaint.setPen(QColor(70,70,70)); pixPaint.setFont(QFont(font, 9*fontFactor)); pixPaint.drawText(paddingLeftCol2,paddingTopCol2+line3,versionText); // draw copyright stuff pixPaint.setFont(QFont(font, 9*fontFactor)); pixPaint.drawText(paddingLeftCol2,paddingTopCol2+line1,copyrightText1); pixPaint.drawText(paddingLeftCol2,paddingTopCol2+line2,copyrightText2); pixPaint.end(); this->setPixmap(newPixmap); } <commit_msg>Update splashscreen.cpp<commit_after>#include "splashscreen.h" #include "clientversion.h" #include "util.h" #include <QPainter> #undef loop /* ugh, remove this when the #define loop is gone from util.h */ #include <QApplication> SplashScreen::SplashScreen(const QPixmap &pixmap, Qt::WindowFlags f) : QSplashScreen(pixmap, f) { // set reference point, paddings int paddingLeftCol2 = 130; int paddingTopCol2 = 376; int line1 = 0; int line2 = 13; int line3 = 26; float fontFactor = 1.0; // define text to place QString titleText = QString(QApplication::applicationName()).replace(QString("-testnet"), QString(""), Qt::CaseSensitive); // cut of testnet, place it as single object further down QString versionText = QString("Version %1 ").arg(QString::fromStdString(FormatFullVersion())); QString copyrightText1 = QChar(0xA9)+QString(" 2009-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("Bitcoin Developers")); QString copyrightText2 = QChar(0xA9)+QString(" %1 ").arg(COPYRIGHT_YEAR) + QString(tr("FlappyCoin Developers")); QString font = "Arial"; // load the bitmap for writing some text over it QPixmap newPixmap; if(GetBoolArg("-testnet")) { newPixmap = QPixmap(":/images/splash_testnet"); } else { newPixmap = QPixmap(":/images/splash"); } QPainter pixPaint(&newPixmap); pixPaint.setPen(QColor(70,70,70)); pixPaint.setFont(QFont(font, 9*fontFactor)); pixPaint.drawText(paddingLeftCol2,paddingTopCol2+line3,versionText); // draw copyright stuff pixPaint.setFont(QFont(font, 9*fontFactor)); pixPaint.drawText(paddingLeftCol2,paddingTopCol2+line1,copyrightText1); pixPaint.drawText(paddingLeftCol2,paddingTopCol2+line2,copyrightText2); pixPaint.end(); this->setPixmap(newPixmap); } <|endoftext|>
<commit_before>/********************************************************************* * * Software License Agreement (BSD License) * * Copyright (c) 2013, Robert Bosch LLC. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Robert Bosch 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. * *********************************************************************/ //\Author Kai Franke #include "raspi_interface/raspi_interface.hpp" /**********************************************************************/ // Constructor /**********************************************************************/ RaspiInterface::RaspiInterface(): is_initialized_( false ) { } /**********************************************************************/ // Destructor /**********************************************************************/ RaspiInterface::~RaspiInterface() { // close all serial connections for (std::map<std::string,int>::iterator it=serial_devices_.begin(); it!=serial_devices_.end(); ++it) { serialClose(it->second); } } /**********************************************************************/ // Initialize: /**********************************************************************/ bool RaspiInterface::initialize() { // Prevent Double-initialization! if( is_initialized_ == true ) { ROS_INFO( "RaspiInterface::initialize(): WiringPi already initialized." ); return true; } // Setup WiringPi int init_reply = wiringPiSetup (); // Set all SPI channels not to use by default for( ssize_t i = 0; i < MAX_SPI_CHANNELS; ++i ) { use_spi[i] = false; } if( init_reply != 0 ) { ROS_ERROR( "WiringPi not initialized properly. Returned %i", init_reply); return false; } is_initialized_ = true; ROS_INFO( "RaspiInterface::initialize(): WiringPi initialized." ); return true; } /**********************************************************************/ // Read /**********************************************************************/ ssize_t RaspiInterface::read( int device_address, interface_protocol protocol, int frequency, int* flags, uint8_t reg_address, uint8_t* data, size_t num_bytes ) { int error_code = 0; // Check initialization: if( is_initialized_ == false ) { return -1; } switch( protocol ) { case GPIO: { error_code = raspiGpioRead( (uint8_t)flags[0], reg_address, data ); break; } case SPI: { error_code = raspiSpi( frequency, (uint8_t)flags[0], reg_address, data, num_bytes ); break; } case I2C: { error_code = raspiI2cRead( device_address, frequency, reg_address, data, num_bytes ); } break; case RS232: { error_code = raspiRs232Read( frequency, flags[0], data, num_bytes ); } break; default: { ROS_ERROR("Raspberry Pi does not support reading through this protocol."); return -1; } } return error_code; } /**********************************************************************/ // Write /**********************************************************************/ ssize_t RaspiInterface::write( int device_address, interface_protocol protocol, int frequency, int* flags, uint8_t reg_address, uint8_t* data, size_t num_bytes ) { int error_code = 0; // Check initialization: if( is_initialized_ == false ) { return -1; } switch( protocol ) { case GPIO: { error_code = raspiGpioWrite( reg_address, (bool)data[0] ); break; } case SPI: { error_code = raspiSpi( frequency, (uint8_t)flags[0], reg_address, data, num_bytes ); break; } case RS232: { error_code = raspiRs232Write( frequency, data, num_bytes ); } break; case I2C: { error_code = raspiI2cWrite( device_address, frequency, reg_address, data, num_bytes ); } break; default: { ROS_ERROR( "Raspberry Pi does not support writing through this protocol." ); error_code = -1; } } return error_code; // bytes written, or error. } /**********************************************************************/ // supportedProtocol /**********************************************************************/ bool RaspiInterface::supportedProtocol( interface_protocol protocol ) { switch( protocol ) { case GPIO: case SPI: case RS232: case I2C: return true; default: return false; } } /**********************************************************************/ std::string RaspiInterface::getID() /**********************************************************************/ { return "Raspberry Pi"; } /**********************************************************************/ /**********************************************************************/ ssize_t RaspiInterface::raspiGpioWrite( uint8_t pin, bool value ) { // check if selected pin is valid for Raspberry Pi if( pin > 16 ) { ROS_ERROR("The selected Pin number is not available for GPIO"); ROS_ERROR("Select Pins 0 through 16 instead"); return -1; } pinMode (pin, OUTPUT); digitalWrite (pin, value); return 1; } /**********************************************************************/ /**********************************************************************/ ssize_t RaspiInterface::raspiGpioRead( uint8_t flags, uint8_t pin, uint8_t* value ) { // check if selected pin is valid for Raspberry Pi if( pin > 16 ) { ROS_ERROR("The selected Pin number is not available for GPIO"); ROS_ERROR("Select Pins 0 through 16 instead"); return -1; } pinMode( pin, INPUT ); switch ((gpio_input_mode) flags ) { case FLOATING: { pullUpDnControl( pin, PUD_OFF ); } break; case PULLUP: { pullUpDnControl( pin, PUD_UP ); } break; case PULLDOWN: { pullUpDnControl( pin, PUD_DOWN ); } break; default: { ROS_ERROR("ArduinoInterface::arduinoGpioRead The selected input mode is not known"); return -1; } } value[0] = digitalRead( pin ); return 1; } /**********************************************************************/ /**********************************************************************/ ssize_t RaspiInterface::raspiSpi( int frequency, uint8_t flags, uint8_t reg_address, uint8_t* data, size_t num_bytes ) { // Decrypt flags: uint8_t spi_slave_select = (flags >> 4); uint8_t bit_order = (flags>>2) & 0x01; uint8_t mode = flags & 0x03; // Sanity check for decrypted flags if( mode != bosch_drivers_common::SPI_MODE_0 ) { ROS_ERROR( "Only mode 0 is implemented in wiringPi at this point" ); return -1; } if( bit_order != 0 ) { ROS_ERROR( "Only MSB first is implemented in wiringPi at this point" ); return -1; } if( spi_slave_select == bosch_drivers_common::NULL_DEVICE ) { ROS_ERROR( "NULL_DEVICE functionality not implemented yet" ); return -1; } if( spi_slave_select >= MAX_SPI_CHANNELS ) { ROS_ERROR( "Maximum SPI channel is %i, you asked for channel %i", MAX_SPI_CHANNELS-1, spi_slave_select ); return -1; } if( frequency < MIN_SPI_FREQUENCY || frequency > MAX_SPI_FREQUENCY ) { ROS_WARN( "The requested frequency of %i is out of bounds. Setting frequency to 1MHz", frequency ); frequency = 1e6; } // setup SPI channel if it has not been setup yet if( use_spi[spi_slave_select] == false ) { if( wiringPiSPISetup (spi_slave_select, frequency) == -1 ) { ROS_ERROR( "RaspiInterface::initializeSPI(): SPI channel 0 not initialized properly."); return -1; } use_spi[spi_slave_select] = true; ROS_INFO( "SPI channel %u initialized.", spi_slave_select ); } // transfer the address register: wiringPiSPIDataRW( spi_slave_select, &reg_address, 1 ); // read/write from/to SPI bus wiringPiSPIDataRW( spi_slave_select, data, num_bytes ); return num_bytes; } ssize_t RaspiInterface::raspiRs232Write( int frequency, uint8_t* data, size_t num_bytes ) { // convert uint8_t* to string std::string complete( data, data + num_bytes ); // split string at first colon size_t delimiter = complete.find_first_of( ':' ); if( delimiter == std::string::npos ) { ROS_ERROR( "No colon found in data string! Example: /dev/ttyUSB0:helloWorld" ); return -1; } std::string device = complete.substr( 0, delimiter ); std::string command = complete.substr( delimiter + 1 ); char* cdevice = reinterpret_cast<char*>(&device[0]); char* ccommand= reinterpret_cast<char*>(&command[0]); // open new serial device if not opened yet if( serial_devices_.count(device) != 1 ) { // open serial interface using wiringPi ROS_INFO("Opening serial interface %s...", cdevice ); int file_descriptor = serialOpen( cdevice, frequency ); // check if serial device was opened successfully if( file_descriptor == -1 ) { ROS_ERROR("Opening serial device %s failed :(", cdevice ); return -1; } else { ROS_INFO( "Successfully opened serial port %s", cdevice ); } // create new hash entry serial_devices_[device] = file_descriptor; } // write command to RS232 connection serialPuts( serial_devices_[device], ccommand ); return command.size(); } ssize_t RaspiInterface::raspiRs232Read( int frequency, int device_name_length, uint8_t* data, size_t num_bytes ) { std::string device( data, data + device_name_length ); char* cdevice = reinterpret_cast<char*>(&device[0]); // open new serial device if not opened yet if( serial_devices_.count(cdevice) != 1 ) { // open serial interface using wiringPi ROS_INFO("Opening serial interface %s...", cdevice ); int file_descriptor = serialOpen( cdevice, frequency ); // check if serial device was opened successfully if( file_descriptor == -1 ) { ROS_ERROR("Opening serial device %s failed :(", cdevice ); return -1; } else { ROS_INFO( "Successfully opened serial port %s", cdevice ); } // create new hash entry serial_devices_[device] = file_descriptor; } // read from RS232 unsigned int index = 0; int temp = 0; while( temp != -1 && num_bytes-- > 0 ) { temp = serialGetchar( serial_devices_[device] ); data[index++] = static_cast<uint8_t>(temp); } if( index != num_bytes ) { ROS_WARN( "You asked for %zd bytes but I only read %i due to error or timeout", num_bytes, index ); } return index; } /**********************************************************************/ /**********************************************************************/ ssize_t RaspiInterface::raspiI2cWrite( uint8_t device_address, uint32_t frequency, uint8_t reg_address, uint8_t* data, size_t num_bytes ) { ROS_INFO("raspiI2cWrite %u %u %u %u %i", device_address, frequency, reg_address, data[0], num_bytes); switch( frequency ) { case 100000: break; default: { ROS_WARN_ONCE("Default frequency 100k. Use 'gpio load i2c XXXX' to set the frequency"); } } // open new i2c device if not opened yet if( i2c_devices_.count(device_address) != 1 ) { // open i2c interface using wiringPi int file_descriptor = wiringPiI2CSetup( device_address ); // check if i2c device was opened successfully if( file_descriptor == -1 ) { ROS_ERROR("Opening i2c device %i failed :(", device_address ); return -1; } // create new hash entry i2c_devices_[device_address] = file_descriptor; ROS_INFO( "Successfully opened i2c device %i", device_address); } int error_code = -1; switch( num_bytes ) { case 1: { error_code = wiringPiI2CWriteReg8 (i2c_devices_[device_address], (int)reg_address, (int)(data[0])); } break; case 2: { // compose 16 Bit value to transmit assuming data[1] is the MSB int temp = ((int)data[1])*256 + data[0]; error_code = wiringPiI2CWriteReg16 (i2c_devices_[device_address], reg_address, temp); } break; default: { ROS_ERROR("Raspberry Pi can only transmit either one or two bytes"); } } if( error_code == -1 ) { ROS_ERROR( "I2C Write failed on device %u, register %i and data %i",device_address, (int)reg_address, (int)(data[0]) ); return error_code; } return num_bytes; } /**********************************************************************/ /**********************************************************************/ ssize_t RaspiInterface::raspiI2cRead( uint8_t device_address, uint32_t frequency, uint8_t reg_address, uint8_t* data, size_t num_bytes ) { ROS_INFO("raspiI2cRead %u %u %u %i", device_address, frequency, reg_address, num_bytes); switch( frequency ) { case 100000: break; default: { ROS_WARN_ONCE("Default frequency 100k. Use 'gpio load i2c XXXX' to set the frequency"); } } // open new i2c device if not opened yet if( i2c_devices_.count(device_address) != 1 ) { // open i2c interface using wiringPi int file_descriptor = wiringPiI2CSetup( device_address ); // check if i2c device was opened successfully if( file_descriptor == -1 ) { ROS_ERROR("Opening i2c device %i failed :(", device_address ); return -1; } // create new hash entry i2c_devices_[device_address] = file_descriptor; ROS_INFO( "Successfully opened i2c device %i", device_address); } for( int i = reg_address; i < reg_address + num_bytes; i++) { data[i-reg_address] = wiringPiI2CReadReg8( i2c_devices_[device_address], i); } return num_bytes; } <commit_msg>remove debug<commit_after>/********************************************************************* * * Software License Agreement (BSD License) * * Copyright (c) 2013, Robert Bosch LLC. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Robert Bosch 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. * *********************************************************************/ //\Author Kai Franke #include "raspi_interface/raspi_interface.hpp" /**********************************************************************/ // Constructor /**********************************************************************/ RaspiInterface::RaspiInterface(): is_initialized_( false ) { } /**********************************************************************/ // Destructor /**********************************************************************/ RaspiInterface::~RaspiInterface() { // close all serial connections for (std::map<std::string,int>::iterator it=serial_devices_.begin(); it!=serial_devices_.end(); ++it) { serialClose(it->second); } } /**********************************************************************/ // Initialize: /**********************************************************************/ bool RaspiInterface::initialize() { // Prevent Double-initialization! if( is_initialized_ == true ) { ROS_INFO( "RaspiInterface::initialize(): WiringPi already initialized." ); return true; } // Setup WiringPi int init_reply = wiringPiSetup (); // Set all SPI channels not to use by default for( ssize_t i = 0; i < MAX_SPI_CHANNELS; ++i ) { use_spi[i] = false; } if( init_reply != 0 ) { ROS_ERROR( "WiringPi not initialized properly. Returned %i", init_reply); return false; } is_initialized_ = true; ROS_INFO( "RaspiInterface::initialize(): WiringPi initialized." ); return true; } /**********************************************************************/ // Read /**********************************************************************/ ssize_t RaspiInterface::read( int device_address, interface_protocol protocol, int frequency, int* flags, uint8_t reg_address, uint8_t* data, size_t num_bytes ) { int error_code = 0; // Check initialization: if( is_initialized_ == false ) { return -1; } switch( protocol ) { case GPIO: { error_code = raspiGpioRead( (uint8_t)flags[0], reg_address, data ); break; } case SPI: { error_code = raspiSpi( frequency, (uint8_t)flags[0], reg_address, data, num_bytes ); break; } case I2C: { error_code = raspiI2cRead( device_address, frequency, reg_address, data, num_bytes ); } break; case RS232: { error_code = raspiRs232Read( frequency, flags[0], data, num_bytes ); } break; default: { ROS_ERROR("Raspberry Pi does not support reading through this protocol."); return -1; } } return error_code; } /**********************************************************************/ // Write /**********************************************************************/ ssize_t RaspiInterface::write( int device_address, interface_protocol protocol, int frequency, int* flags, uint8_t reg_address, uint8_t* data, size_t num_bytes ) { int error_code = 0; // Check initialization: if( is_initialized_ == false ) { return -1; } switch( protocol ) { case GPIO: { error_code = raspiGpioWrite( reg_address, (bool)data[0] ); break; } case SPI: { error_code = raspiSpi( frequency, (uint8_t)flags[0], reg_address, data, num_bytes ); break; } case RS232: { error_code = raspiRs232Write( frequency, data, num_bytes ); } break; case I2C: { error_code = raspiI2cWrite( device_address, frequency, reg_address, data, num_bytes ); } break; default: { ROS_ERROR( "Raspberry Pi does not support writing through this protocol." ); error_code = -1; } } return error_code; // bytes written, or error. } /**********************************************************************/ // supportedProtocol /**********************************************************************/ bool RaspiInterface::supportedProtocol( interface_protocol protocol ) { switch( protocol ) { case GPIO: case SPI: case RS232: case I2C: return true; default: return false; } } /**********************************************************************/ std::string RaspiInterface::getID() /**********************************************************************/ { return "Raspberry Pi"; } /**********************************************************************/ /**********************************************************************/ ssize_t RaspiInterface::raspiGpioWrite( uint8_t pin, bool value ) { // check if selected pin is valid for Raspberry Pi if( pin > 16 ) { ROS_ERROR("The selected Pin number is not available for GPIO"); ROS_ERROR("Select Pins 0 through 16 instead"); return -1; } pinMode (pin, OUTPUT); digitalWrite (pin, value); return 1; } /**********************************************************************/ /**********************************************************************/ ssize_t RaspiInterface::raspiGpioRead( uint8_t flags, uint8_t pin, uint8_t* value ) { // check if selected pin is valid for Raspberry Pi if( pin > 16 ) { ROS_ERROR("The selected Pin number is not available for GPIO"); ROS_ERROR("Select Pins 0 through 16 instead"); return -1; } pinMode( pin, INPUT ); switch ((gpio_input_mode) flags ) { case FLOATING: { pullUpDnControl( pin, PUD_OFF ); } break; case PULLUP: { pullUpDnControl( pin, PUD_UP ); } break; case PULLDOWN: { pullUpDnControl( pin, PUD_DOWN ); } break; default: { ROS_ERROR("ArduinoInterface::arduinoGpioRead The selected input mode is not known"); return -1; } } value[0] = digitalRead( pin ); return 1; } /**********************************************************************/ /**********************************************************************/ ssize_t RaspiInterface::raspiSpi( int frequency, uint8_t flags, uint8_t reg_address, uint8_t* data, size_t num_bytes ) { // Decrypt flags: uint8_t spi_slave_select = (flags >> 4); uint8_t bit_order = (flags>>2) & 0x01; uint8_t mode = flags & 0x03; // Sanity check for decrypted flags if( mode != bosch_drivers_common::SPI_MODE_0 ) { ROS_ERROR( "Only mode 0 is implemented in wiringPi at this point" ); return -1; } if( bit_order != 0 ) { ROS_ERROR( "Only MSB first is implemented in wiringPi at this point" ); return -1; } if( spi_slave_select == bosch_drivers_common::NULL_DEVICE ) { ROS_ERROR( "NULL_DEVICE functionality not implemented yet" ); return -1; } if( spi_slave_select >= MAX_SPI_CHANNELS ) { ROS_ERROR( "Maximum SPI channel is %i, you asked for channel %i", MAX_SPI_CHANNELS-1, spi_slave_select ); return -1; } if( frequency < MIN_SPI_FREQUENCY || frequency > MAX_SPI_FREQUENCY ) { ROS_WARN( "The requested frequency of %i is out of bounds. Setting frequency to 1MHz", frequency ); frequency = 1e6; } // setup SPI channel if it has not been setup yet if( use_spi[spi_slave_select] == false ) { if( wiringPiSPISetup (spi_slave_select, frequency) == -1 ) { ROS_ERROR( "RaspiInterface::initializeSPI(): SPI channel 0 not initialized properly."); return -1; } use_spi[spi_slave_select] = true; ROS_INFO( "SPI channel %u initialized.", spi_slave_select ); } // transfer the address register: wiringPiSPIDataRW( spi_slave_select, &reg_address, 1 ); // read/write from/to SPI bus wiringPiSPIDataRW( spi_slave_select, data, num_bytes ); return num_bytes; } ssize_t RaspiInterface::raspiRs232Write( int frequency, uint8_t* data, size_t num_bytes ) { // convert uint8_t* to string std::string complete( data, data + num_bytes ); // split string at first colon size_t delimiter = complete.find_first_of( ':' ); if( delimiter == std::string::npos ) { ROS_ERROR( "No colon found in data string! Example: /dev/ttyUSB0:helloWorld" ); return -1; } std::string device = complete.substr( 0, delimiter ); std::string command = complete.substr( delimiter + 1 ); char* cdevice = reinterpret_cast<char*>(&device[0]); char* ccommand= reinterpret_cast<char*>(&command[0]); // open new serial device if not opened yet if( serial_devices_.count(device) != 1 ) { // open serial interface using wiringPi ROS_INFO("Opening serial interface %s...", cdevice ); int file_descriptor = serialOpen( cdevice, frequency ); // check if serial device was opened successfully if( file_descriptor == -1 ) { ROS_ERROR("Opening serial device %s failed :(", cdevice ); return -1; } else { ROS_INFO( "Successfully opened serial port %s", cdevice ); } // create new hash entry serial_devices_[device] = file_descriptor; } // write command to RS232 connection serialPuts( serial_devices_[device], ccommand ); return command.size(); } ssize_t RaspiInterface::raspiRs232Read( int frequency, int device_name_length, uint8_t* data, size_t num_bytes ) { std::string device( data, data + device_name_length ); char* cdevice = reinterpret_cast<char*>(&device[0]); // open new serial device if not opened yet if( serial_devices_.count(cdevice) != 1 ) { // open serial interface using wiringPi ROS_INFO("Opening serial interface %s...", cdevice ); int file_descriptor = serialOpen( cdevice, frequency ); // check if serial device was opened successfully if( file_descriptor == -1 ) { ROS_ERROR("Opening serial device %s failed :(", cdevice ); return -1; } else { ROS_INFO( "Successfully opened serial port %s", cdevice ); } // create new hash entry serial_devices_[device] = file_descriptor; } // read from RS232 unsigned int index = 0; int temp = 0; while( temp != -1 && num_bytes-- > 0 ) { temp = serialGetchar( serial_devices_[device] ); data[index++] = static_cast<uint8_t>(temp); } if( index != num_bytes ) { ROS_WARN( "You asked for %zd bytes but I only read %i due to error or timeout", num_bytes, index ); } return index; } /**********************************************************************/ /**********************************************************************/ ssize_t RaspiInterface::raspiI2cWrite( uint8_t device_address, uint32_t frequency, uint8_t reg_address, uint8_t* data, size_t num_bytes ) { switch( frequency ) { case 100000: break; default: { ROS_WARN_ONCE("Default frequency 100k. Use 'gpio load i2c XXXX' to set the frequency"); } } // open new i2c device if not opened yet if( i2c_devices_.count(device_address) != 1 ) { // open i2c interface using wiringPi int file_descriptor = wiringPiI2CSetup( device_address ); // check if i2c device was opened successfully if( file_descriptor == -1 ) { ROS_ERROR("Opening i2c device %i failed :(", device_address ); return -1; } // create new hash entry i2c_devices_[device_address] = file_descriptor; ROS_INFO( "Successfully opened i2c device %i", device_address); } int error_code = -1; switch( num_bytes ) { case 1: { error_code = wiringPiI2CWriteReg8 (i2c_devices_[device_address], (int)reg_address, (int)(data[0])); } break; case 2: { // compose 16 Bit value to transmit assuming data[1] is the MSB int temp = ((int)data[1])*256 + data[0]; error_code = wiringPiI2CWriteReg16 (i2c_devices_[device_address], reg_address, temp); } break; default: { ROS_ERROR("Raspberry Pi can only transmit either one or two bytes"); } } if( error_code == -1 ) { ROS_ERROR( "I2C Write failed on device %u, register %i and data %i",device_address, (int)reg_address, (int)(data[0]) ); return error_code; } return num_bytes; } /**********************************************************************/ /**********************************************************************/ ssize_t RaspiInterface::raspiI2cRead( uint8_t device_address, uint32_t frequency, uint8_t reg_address, uint8_t* data, size_t num_bytes ) { switch( frequency ) { case 100000: break; default: { ROS_WARN_ONCE("Default frequency 100k. Use 'gpio load i2c XXXX' to set the frequency"); } } // open new i2c device if not opened yet if( i2c_devices_.count(device_address) != 1 ) { // open i2c interface using wiringPi int file_descriptor = wiringPiI2CSetup( device_address ); // check if i2c device was opened successfully if( file_descriptor == -1 ) { ROS_ERROR("Opening i2c device %i failed :(", device_address ); return -1; } // create new hash entry i2c_devices_[device_address] = file_descriptor; ROS_INFO( "Successfully opened i2c device %i", device_address); } for( int i = reg_address; i < reg_address + num_bytes; i++) { data[i-reg_address] = wiringPiI2CReadReg8( i2c_devices_[device_address], i); } return num_bytes; } <|endoftext|>
<commit_before>// Copyright 2017 The Ray Authors. // // 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 "ray/util/logging.h" #ifndef _WIN32 #include <execinfo.h> #endif #include <signal.h> #include <stdlib.h> #include <algorithm> #include <cstdlib> #include <iostream> #ifdef RAY_USE_GLOG #include <sys/stat.h> #include "glog/logging.h" #endif #include "ray/util/filesystem.h" namespace ray { #ifdef RAY_USE_GLOG struct StdoutLogger : public google::base::Logger { virtual void Write(bool /* should flush */, time_t /* timestamp */, const char *message, int length) { // note: always flush otherwise it never shows up in raylet.out std::cout << std::string(message, length) << std::flush; } virtual void Flush() { std::cout.flush(); } virtual google::uint32 LogSize() { return 0; } }; static StdoutLogger stdout_logger_singleton; #endif // This is the default implementation of ray log, // which is independent of any libs. class CerrLog { public: CerrLog(RayLogLevel severity) : severity_(severity), has_logged_(false) {} virtual ~CerrLog() { if (has_logged_) { std::cerr << std::endl; } if (severity_ == RayLogLevel::FATAL) { PrintBackTrace(); std::abort(); } } std::ostream &Stream() { has_logged_ = true; return std::cerr; } template <class T> CerrLog &operator<<(const T &t) { if (severity_ != RayLogLevel::DEBUG) { has_logged_ = true; std::cerr << t; } return *this; } protected: const RayLogLevel severity_; bool has_logged_; void PrintBackTrace() { #if defined(_EXECINFO_H) || !defined(_WIN32) void *buffer[255]; const int calls = backtrace(buffer, sizeof(buffer) / sizeof(void *)); backtrace_symbols_fd(buffer, calls, 1); #endif } }; #ifdef RAY_USE_GLOG typedef google::LogMessage LoggingProvider; #else typedef ray::CerrLog LoggingProvider; #endif RayLogLevel RayLog::severity_threshold_ = RayLogLevel::INFO; std::string RayLog::app_name_ = ""; std::string RayLog::log_dir_ = ""; bool RayLog::is_failure_signal_handler_installed_ = false; #ifdef RAY_USE_GLOG using namespace google; // Glog's severity map. static int GetMappedSeverity(RayLogLevel severity) { switch (severity) { case RayLogLevel::DEBUG: return GLOG_INFO; case RayLogLevel::INFO: return GLOG_INFO; case RayLogLevel::WARNING: return GLOG_WARNING; case RayLogLevel::ERROR: return GLOG_ERROR; case RayLogLevel::FATAL: return GLOG_FATAL; default: RAY_LOG(FATAL) << "Unsupported logging level: " << static_cast<int>(severity); // This return won't be hit but compiler needs it. return GLOG_FATAL; } } #endif void RayLog::StartRayLog(const std::string &app_name, RayLogLevel severity_threshold, const std::string &log_dir) { const char *var_value = getenv("RAY_BACKEND_LOG_LEVEL"); if (var_value != nullptr) { std::string data = var_value; std::transform(data.begin(), data.end(), data.begin(), ::tolower); if (data == "debug") { severity_threshold = RayLogLevel::DEBUG; } else if (data == "info") { severity_threshold = RayLogLevel::INFO; } else if (data == "warning") { severity_threshold = RayLogLevel::WARNING; } else if (data == "error") { severity_threshold = RayLogLevel::ERROR; } else if (data == "fatal") { severity_threshold = RayLogLevel::FATAL; } else { RAY_LOG(WARNING) << "Unrecognized setting of RAY_BACKEND_LOG_LEVEL=" << var_value; } RAY_LOG(INFO) << "Set ray log level from environment variable RAY_BACKEND_LOG_LEVEL" << " to " << static_cast<int>(severity_threshold); } severity_threshold_ = severity_threshold; app_name_ = app_name; log_dir_ = log_dir; #ifdef RAY_USE_GLOG google::InitGoogleLogging(app_name_.c_str()); // Enable log file if log_dir_ is not empty. std::string dir_ends_with_slash = log_dir_; if (!ray::IsDirSep(log_dir_[log_dir_.length() - 1])) { dir_ends_with_slash += ray::GetDirSep(); } if (!log_dir_.empty()) { std::string app_name_without_path = app_name; if (app_name.empty()) { app_name_without_path = "DefaultApp"; } else { // Find the app name without the path. std::string app_file_name = ray::GetFileName(app_name); if (!app_file_name.empty()) { app_name_without_path = app_file_name; } } google::SetLogFilenameExtension(app_name_without_path.c_str()); } for (int lvl = 0; lvl < NUM_SEVERITIES; ++lvl) { if (log_dir_.empty()) { google::SetStderrLogging(lvl); google::base::SetLogger(lvl, &stdout_logger_singleton); } else { google::SetLogDestination(lvl, dir_ends_with_slash.c_str()); } } #endif } void RayLog::UninstallSignalAction() { #ifdef RAY_USE_GLOG if (!is_failure_signal_handler_installed_) { return; } RAY_LOG(DEBUG) << "Uninstall signal handlers."; // This signal list comes from glog's signalhandler.cc. // https://github.com/google/glog/blob/master/src/signalhandler.cc#L58-L70 std::vector<int> installed_signals({SIGSEGV, SIGILL, SIGFPE, SIGABRT, SIGTERM}); #ifdef _WIN32 // Do NOT use WIN32 (without the underscore); we want _WIN32 here for (int signal_num : installed_signals) { RAY_CHECK(signal(signal_num, SIG_DFL) != SIG_ERR); } #else struct sigaction sig_action; memset(&sig_action, 0, sizeof(sig_action)); sigemptyset(&sig_action.sa_mask); sig_action.sa_handler = SIG_DFL; for (int signal_num : installed_signals) { RAY_CHECK(sigaction(signal_num, &sig_action, NULL) == 0); } #endif is_failure_signal_handler_installed_ = false; #endif } void RayLog::ShutDownRayLog() { #ifdef RAY_USE_GLOG UninstallSignalAction(); google::ShutdownGoogleLogging(); #endif } void RayLog::InstallFailureSignalHandler() { #ifdef _WIN32 // If process fails to initialize, don't display an error window. SetErrorMode(GetErrorMode() | SEM_FAILCRITICALERRORS); // If process crashes, don't display an error window. SetErrorMode(GetErrorMode() | SEM_NOGPFAULTERRORBOX); #endif #ifdef RAY_USE_GLOG if (is_failure_signal_handler_installed_) { return; } google::InstallFailureSignalHandler(); is_failure_signal_handler_installed_ = true; #endif } bool RayLog::IsLevelEnabled(RayLogLevel log_level) { return log_level >= severity_threshold_; } RayLog::RayLog(const char *file_name, int line_number, RayLogLevel severity) // glog does not have DEBUG level, we can handle it using is_enabled_. : logging_provider_(nullptr), is_enabled_(severity >= severity_threshold_) { #ifdef RAY_USE_GLOG if (is_enabled_) { logging_provider_ = new google::LogMessage(file_name, line_number, GetMappedSeverity(severity)); } #else auto logging_provider = new CerrLog(severity); *logging_provider << file_name << ":" << line_number << ": "; logging_provider_ = logging_provider; #endif } std::ostream &RayLog::Stream() { auto logging_provider = reinterpret_cast<LoggingProvider *>(logging_provider_); #ifdef RAY_USE_GLOG // Before calling this function, user should check IsEnabled. // When IsEnabled == false, logging_provider_ will be empty. return logging_provider->stream(); #else return logging_provider->Stream(); #endif } bool RayLog::IsEnabled() const { return is_enabled_; } RayLog::~RayLog() { if (logging_provider_ != nullptr) { delete reinterpret_cast<LoggingProvider *>(logging_provider_); logging_provider_ = nullptr; } } } // namespace ray <commit_msg>Fix Google log directory again (#9063)<commit_after>// Copyright 2017 The Ray Authors. // // 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 "ray/util/logging.h" #ifndef _WIN32 #include <execinfo.h> #endif #include <signal.h> #include <stdlib.h> #include <algorithm> #include <cstdlib> #include <iostream> #ifdef RAY_USE_GLOG #include <sys/stat.h> #include "glog/logging.h" #endif #include "ray/util/filesystem.h" namespace ray { #ifdef RAY_USE_GLOG struct StdoutLogger : public google::base::Logger { virtual void Write(bool /* should flush */, time_t /* timestamp */, const char *message, int length) { // note: always flush otherwise it never shows up in raylet.out std::cout << std::string(message, length) << std::flush; } virtual void Flush() { std::cout.flush(); } virtual google::uint32 LogSize() { return 0; } }; static StdoutLogger stdout_logger_singleton; #endif // This is the default implementation of ray log, // which is independent of any libs. class CerrLog { public: CerrLog(RayLogLevel severity) : severity_(severity), has_logged_(false) {} virtual ~CerrLog() { if (has_logged_) { std::cerr << std::endl; } if (severity_ == RayLogLevel::FATAL) { PrintBackTrace(); std::abort(); } } std::ostream &Stream() { has_logged_ = true; return std::cerr; } template <class T> CerrLog &operator<<(const T &t) { if (severity_ != RayLogLevel::DEBUG) { has_logged_ = true; std::cerr << t; } return *this; } protected: const RayLogLevel severity_; bool has_logged_; void PrintBackTrace() { #if defined(_EXECINFO_H) || !defined(_WIN32) void *buffer[255]; const int calls = backtrace(buffer, sizeof(buffer) / sizeof(void *)); backtrace_symbols_fd(buffer, calls, 1); #endif } }; #ifdef RAY_USE_GLOG typedef google::LogMessage LoggingProvider; #else typedef ray::CerrLog LoggingProvider; #endif RayLogLevel RayLog::severity_threshold_ = RayLogLevel::INFO; std::string RayLog::app_name_ = ""; std::string RayLog::log_dir_ = ""; bool RayLog::is_failure_signal_handler_installed_ = false; #ifdef RAY_USE_GLOG using namespace google; // Glog's severity map. static int GetMappedSeverity(RayLogLevel severity) { switch (severity) { case RayLogLevel::DEBUG: return GLOG_INFO; case RayLogLevel::INFO: return GLOG_INFO; case RayLogLevel::WARNING: return GLOG_WARNING; case RayLogLevel::ERROR: return GLOG_ERROR; case RayLogLevel::FATAL: return GLOG_FATAL; default: RAY_LOG(FATAL) << "Unsupported logging level: " << static_cast<int>(severity); // This return won't be hit but compiler needs it. return GLOG_FATAL; } } #endif void RayLog::StartRayLog(const std::string &app_name, RayLogLevel severity_threshold, const std::string &log_dir) { const char *var_value = getenv("RAY_BACKEND_LOG_LEVEL"); if (var_value != nullptr) { std::string data = var_value; std::transform(data.begin(), data.end(), data.begin(), ::tolower); if (data == "debug") { severity_threshold = RayLogLevel::DEBUG; } else if (data == "info") { severity_threshold = RayLogLevel::INFO; } else if (data == "warning") { severity_threshold = RayLogLevel::WARNING; } else if (data == "error") { severity_threshold = RayLogLevel::ERROR; } else if (data == "fatal") { severity_threshold = RayLogLevel::FATAL; } else { RAY_LOG(WARNING) << "Unrecognized setting of RAY_BACKEND_LOG_LEVEL=" << var_value; } RAY_LOG(INFO) << "Set ray log level from environment variable RAY_BACKEND_LOG_LEVEL" << " to " << static_cast<int>(severity_threshold); } severity_threshold_ = severity_threshold; app_name_ = app_name; log_dir_ = log_dir; #ifdef RAY_USE_GLOG google::InitGoogleLogging(app_name_.c_str()); // Enable log file if log_dir_ is not empty. std::string dir_ends_with_slash = log_dir_; if (!ray::IsDirSep(log_dir_[log_dir_.length() - 1])) { dir_ends_with_slash += ray::GetDirSep(); } if (!log_dir_.empty()) { std::string app_name_without_path = app_name; if (app_name.empty()) { app_name_without_path = "DefaultApp"; } else { // Find the app name without the path. std::string app_file_name = ray::GetFileName(app_name); if (!app_file_name.empty()) { app_name_without_path = app_file_name; } } google::SetLogFilenameExtension((app_name_without_path + ".log.").c_str()); } for (int lvl = 0; lvl < NUM_SEVERITIES; ++lvl) { if (log_dir_.empty()) { google::SetStderrLogging(lvl); google::base::SetLogger(lvl, &stdout_logger_singleton); } else { std::string prefix = dir_ends_with_slash + LogSeverityNames[lvl] + '.'; google::SetLogDestination(lvl, prefix.c_str()); } } #endif } void RayLog::UninstallSignalAction() { #ifdef RAY_USE_GLOG if (!is_failure_signal_handler_installed_) { return; } RAY_LOG(DEBUG) << "Uninstall signal handlers."; // This signal list comes from glog's signalhandler.cc. // https://github.com/google/glog/blob/master/src/signalhandler.cc#L58-L70 std::vector<int> installed_signals({SIGSEGV, SIGILL, SIGFPE, SIGABRT, SIGTERM}); #ifdef _WIN32 // Do NOT use WIN32 (without the underscore); we want _WIN32 here for (int signal_num : installed_signals) { RAY_CHECK(signal(signal_num, SIG_DFL) != SIG_ERR); } #else struct sigaction sig_action; memset(&sig_action, 0, sizeof(sig_action)); sigemptyset(&sig_action.sa_mask); sig_action.sa_handler = SIG_DFL; for (int signal_num : installed_signals) { RAY_CHECK(sigaction(signal_num, &sig_action, NULL) == 0); } #endif is_failure_signal_handler_installed_ = false; #endif } void RayLog::ShutDownRayLog() { #ifdef RAY_USE_GLOG UninstallSignalAction(); google::ShutdownGoogleLogging(); #endif } void RayLog::InstallFailureSignalHandler() { #ifdef _WIN32 // If process fails to initialize, don't display an error window. SetErrorMode(GetErrorMode() | SEM_FAILCRITICALERRORS); // If process crashes, don't display an error window. SetErrorMode(GetErrorMode() | SEM_NOGPFAULTERRORBOX); #endif #ifdef RAY_USE_GLOG if (is_failure_signal_handler_installed_) { return; } google::InstallFailureSignalHandler(); is_failure_signal_handler_installed_ = true; #endif } bool RayLog::IsLevelEnabled(RayLogLevel log_level) { return log_level >= severity_threshold_; } RayLog::RayLog(const char *file_name, int line_number, RayLogLevel severity) // glog does not have DEBUG level, we can handle it using is_enabled_. : logging_provider_(nullptr), is_enabled_(severity >= severity_threshold_) { #ifdef RAY_USE_GLOG if (is_enabled_) { logging_provider_ = new google::LogMessage(file_name, line_number, GetMappedSeverity(severity)); } #else auto logging_provider = new CerrLog(severity); *logging_provider << file_name << ":" << line_number << ": "; logging_provider_ = logging_provider; #endif } std::ostream &RayLog::Stream() { auto logging_provider = reinterpret_cast<LoggingProvider *>(logging_provider_); #ifdef RAY_USE_GLOG // Before calling this function, user should check IsEnabled. // When IsEnabled == false, logging_provider_ will be empty. return logging_provider->stream(); #else return logging_provider->Stream(); #endif } bool RayLog::IsEnabled() const { return is_enabled_; } RayLog::~RayLog() { if (logging_provider_ != nullptr) { delete reinterpret_cast<LoggingProvider *>(logging_provider_); logging_provider_ = nullptr; } } } // namespace ray <|endoftext|>
<commit_before>#include <thread> #include "reactor.h" const std::string reactor::KEY_TIMER = "timer"; reactor::reactor(std::shared_ptr<zmq::context_t> context) : context_(context), async_handler_socket_(*context, zmq::socket_type::router), unique_id("reactor_" + std::to_string((uintptr_t) this)) { async_handler_socket_.bind("inproc://" + unique_id); } void reactor::add_socket(const std::string &name, std::shared_ptr<socket_wrapper_base> socket) { sockets_.emplace(name, socket); } void reactor::add_handler(const std::vector<std::string> &origins, std::shared_ptr<handler_interface> handler) { auto wrapper = std::make_shared<handler_wrapper>(*this, handler); for (auto &origin : origins) { handlers_.emplace(origin, wrapper); } } void reactor::add_async_handler(const std::vector<std::string> &origins, std::shared_ptr<handler_interface> handler) { auto wrapper = std::make_shared<asynchronous_handler_wrapper>(*context_, async_handler_socket_, *this, handler); for (auto &origin : origins) { handlers_.emplace(origin, wrapper); } } void reactor::send_message(const message_container &message) { auto it = sockets_.find(message.key); // If there is a matching socket, send the message there. If not, let the reactor handle it if (it != std::end(sockets_)) { it->second->send_message(message); } else { process_message(message); } } void reactor::process_message(const message_container &message) { auto range = handlers_.equal_range(message.key); for (auto it = range.first; it != range.second; ++it) { (*it->second)(message); } } void reactor::start_loop() { std::vector<zmq::pollitem_t> pollitems; std::vector<std::string> pollitem_names; // Poll all registered sockets for (auto it : sockets_) { it.second->initialize(); pollitems.push_back(it.second->get_pollitem()); pollitem_names.push_back(it.first); } // Also poll the internal socket for asynchronous communication pollitems.push_back( zmq_pollitem_t{.socket = (void *) async_handler_socket_, .fd = 0, .events = ZMQ_POLLIN, .revents = 0}); termination_flag_.store(false); // Enter the poll loop while (!termination_flag_.load()) { auto time_before_poll = std::chrono::system_clock::now(); zmq::poll(pollitems, std::chrono::milliseconds(100)); auto time_after_poll = std::chrono::system_clock::now(); auto elapsed_time = std::chrono::duration_cast<std::chrono::milliseconds>(time_after_poll - time_before_poll); size_t i = 0; for (auto item : pollitems) { if (item.revents & ZMQ_POLLIN) { message_container received_msg; if (i < pollitem_names.size()) { // message came from a registered socket, fill in its key received_msg.key = pollitem_names.at(i); sockets_.at(received_msg.key)->receive_message(received_msg); } else { // message from the asynchronous handler socket zmq::message_t zmessage; async_handler_socket_.recv(&zmessage); received_msg.key = std::string(static_cast<char *>(zmessage.data()), zmessage.size()); async_handler_socket_.recv(&zmessage); received_msg.identity = std::string(static_cast<char *>(zmessage.data()), zmessage.size()); while (zmessage.more()) { received_msg.data.emplace_back(static_cast<char *>(zmessage.data()), zmessage.size()); } } process_message(received_msg); } ++i; } message_container timer_msg; timer_msg.key = KEY_TIMER; timer_msg.data.push_back(std::to_string(elapsed_time.count())); process_message(timer_msg); } handlers_.clear(); } void reactor::terminate () { termination_flag_.store(true); } handler_wrapper::handler_wrapper(reactor &reactor_ref, std::shared_ptr<handler_interface> handler) : handler_(handler), reactor_(reactor_ref) { } handler_wrapper::~handler_wrapper() { } void handler_wrapper::operator()(const message_container &message) { handler_->on_request(message, [this](const message_container &response) { reactor_.send_message(response); }); } const std::string asynchronous_handler_wrapper::TERMINATE_MSG = "TERMINATE"; asynchronous_handler_wrapper::asynchronous_handler_wrapper(zmq::context_t &context, zmq::socket_t &async_handler_socket, reactor &reactor_ref, std::shared_ptr<handler_interface> handler) : handler_wrapper(reactor_ref, handler), reactor_socket_(async_handler_socket), unique_id_(std::to_string((uintptr_t) this)), handler_thread_socket_(context, zmq::socket_type::dealer) { worker_ = std::thread([this]() { handler_thread(); }); } asynchronous_handler_wrapper::~asynchronous_handler_wrapper() { // Send a message to terminate the worker thread reactor_socket_.send(unique_id_.data(), unique_id_.size(), ZMQ_SNDMORE); reactor_socket_.send(TERMINATE_MSG.data(), TERMINATE_MSG.size()); // Join it worker_.join(); } void asynchronous_handler_wrapper::operator()(const message_container &message) { reactor_socket_.send(message.key.data(), message.key.size(), ZMQ_SNDMORE); reactor_socket_.send(message.identity.data(), message.identity.size(), ZMQ_SNDMORE); for (auto it = std::begin(message.data); it != std::end(message.data); ++it) { reactor_socket_.send(it->c_str(), it->size(), std::next(it) != std::end(message.data) ? ZMQ_SNDMORE : 0); } } void asynchronous_handler_wrapper::handler_thread() { handler_thread_socket_.setsockopt(ZMQ_IDENTITY, unique_id_.data(), unique_id_.size()); handler_thread_socket_.connect("inproc://" + reactor_.unique_id); while (true) { message_container request; zmq::message_t message; handler_thread_socket_.recv(&message, 0); request.key = std::string(static_cast<char *>(message.data()), message.size()); if (request.key == TERMINATE_MSG) { return; } if (!message.more()) { continue; } handler_thread_socket_.recv(&message, 0); request.identity = std::string(static_cast<char *>(message.data()), message.size()); while (message.more()) { handler_thread_socket_.recv(&message, 0); request.data.emplace_back(static_cast<char *>(message.data()), message.size()); } handler_->on_request(request, [this](const message_container &response) { send_response(response); }); } } void asynchronous_handler_wrapper::send_response(const message_container &message) { handler_thread_socket_.send(unique_id_.data(), unique_id_.size(), ZMQ_SNDMORE); handler_thread_socket_.send(message.key.data(), message.key.size(), ZMQ_SNDMORE); handler_thread_socket_.send(message.identity.data(), message.identity.size(), ZMQ_SNDMORE); for (auto it = std::begin(message.data); it != std::end(message.data); ++it) { handler_thread_socket_.send(it->c_str(), it->size(), std::next(it) != std::end(message.data) ? ZMQ_SNDMORE : 0); } } <commit_msg>coding standard<commit_after>#include <thread> #include "reactor.h" const std::string reactor::KEY_TIMER = "timer"; reactor::reactor(std::shared_ptr<zmq::context_t> context) : context_(context), async_handler_socket_(*context, zmq::socket_type::router), unique_id("reactor_" + std::to_string((uintptr_t) this)) { async_handler_socket_.bind("inproc://" + unique_id); } void reactor::add_socket(const std::string &name, std::shared_ptr<socket_wrapper_base> socket) { sockets_.emplace(name, socket); } void reactor::add_handler(const std::vector<std::string> &origins, std::shared_ptr<handler_interface> handler) { auto wrapper = std::make_shared<handler_wrapper>(*this, handler); for (auto &origin : origins) { handlers_.emplace(origin, wrapper); } } void reactor::add_async_handler(const std::vector<std::string> &origins, std::shared_ptr<handler_interface> handler) { auto wrapper = std::make_shared<asynchronous_handler_wrapper>(*context_, async_handler_socket_, *this, handler); for (auto &origin : origins) { handlers_.emplace(origin, wrapper); } } void reactor::send_message(const message_container &message) { auto it = sockets_.find(message.key); // If there is a matching socket, send the message there. If not, let the reactor handle it if (it != std::end(sockets_)) { it->second->send_message(message); } else { process_message(message); } } void reactor::process_message(const message_container &message) { auto range = handlers_.equal_range(message.key); for (auto it = range.first; it != range.second; ++it) { (*it->second)(message); } } void reactor::start_loop() { std::vector<zmq::pollitem_t> pollitems; std::vector<std::string> pollitem_names; // Poll all registered sockets for (auto it : sockets_) { it.second->initialize(); pollitems.push_back(it.second->get_pollitem()); pollitem_names.push_back(it.first); } // Also poll the internal socket for asynchronous communication pollitems.push_back( zmq_pollitem_t{.socket = (void *) async_handler_socket_, .fd = 0, .events = ZMQ_POLLIN, .revents = 0}); termination_flag_.store(false); // Enter the poll loop while (!termination_flag_.load()) { auto time_before_poll = std::chrono::system_clock::now(); zmq::poll(pollitems, std::chrono::milliseconds(100)); auto time_after_poll = std::chrono::system_clock::now(); auto elapsed_time = std::chrono::duration_cast<std::chrono::milliseconds>(time_after_poll - time_before_poll); size_t i = 0; for (auto item : pollitems) { if (item.revents & ZMQ_POLLIN) { message_container received_msg; if (i < pollitem_names.size()) { // message came from a registered socket, fill in its key received_msg.key = pollitem_names.at(i); sockets_.at(received_msg.key)->receive_message(received_msg); } else { // message from the asynchronous handler socket zmq::message_t zmessage; async_handler_socket_.recv(&zmessage); received_msg.key = std::string(static_cast<char *>(zmessage.data()), zmessage.size()); async_handler_socket_.recv(&zmessage); received_msg.identity = std::string(static_cast<char *>(zmessage.data()), zmessage.size()); while (zmessage.more()) { received_msg.data.emplace_back(static_cast<char *>(zmessage.data()), zmessage.size()); } } process_message(received_msg); } ++i; } message_container timer_msg; timer_msg.key = KEY_TIMER; timer_msg.data.push_back(std::to_string(elapsed_time.count())); process_message(timer_msg); } handlers_.clear(); } void reactor::terminate() { termination_flag_.store(true); } handler_wrapper::handler_wrapper(reactor &reactor_ref, std::shared_ptr<handler_interface> handler) : handler_(handler), reactor_(reactor_ref) { } handler_wrapper::~handler_wrapper() { } void handler_wrapper::operator()(const message_container &message) { handler_->on_request(message, [this](const message_container &response) { reactor_.send_message(response); }); } const std::string asynchronous_handler_wrapper::TERMINATE_MSG = "TERMINATE"; asynchronous_handler_wrapper::asynchronous_handler_wrapper(zmq::context_t &context, zmq::socket_t &async_handler_socket, reactor &reactor_ref, std::shared_ptr<handler_interface> handler) : handler_wrapper(reactor_ref, handler), reactor_socket_(async_handler_socket), unique_id_(std::to_string((uintptr_t) this)), handler_thread_socket_(context, zmq::socket_type::dealer) { worker_ = std::thread([this]() { handler_thread(); }); } asynchronous_handler_wrapper::~asynchronous_handler_wrapper() { // Send a message to terminate the worker thread reactor_socket_.send(unique_id_.data(), unique_id_.size(), ZMQ_SNDMORE); reactor_socket_.send(TERMINATE_MSG.data(), TERMINATE_MSG.size()); // Join it worker_.join(); } void asynchronous_handler_wrapper::operator()(const message_container &message) { reactor_socket_.send(message.key.data(), message.key.size(), ZMQ_SNDMORE); reactor_socket_.send(message.identity.data(), message.identity.size(), ZMQ_SNDMORE); for (auto it = std::begin(message.data); it != std::end(message.data); ++it) { reactor_socket_.send(it->c_str(), it->size(), std::next(it) != std::end(message.data) ? ZMQ_SNDMORE : 0); } } void asynchronous_handler_wrapper::handler_thread() { handler_thread_socket_.setsockopt(ZMQ_IDENTITY, unique_id_.data(), unique_id_.size()); handler_thread_socket_.connect("inproc://" + reactor_.unique_id); while (true) { message_container request; zmq::message_t message; handler_thread_socket_.recv(&message, 0); request.key = std::string(static_cast<char *>(message.data()), message.size()); if (request.key == TERMINATE_MSG) { return; } if (!message.more()) { continue; } handler_thread_socket_.recv(&message, 0); request.identity = std::string(static_cast<char *>(message.data()), message.size()); while (message.more()) { handler_thread_socket_.recv(&message, 0); request.data.emplace_back(static_cast<char *>(message.data()), message.size()); } handler_->on_request(request, [this](const message_container &response) { send_response(response); }); } } void asynchronous_handler_wrapper::send_response(const message_container &message) { handler_thread_socket_.send(unique_id_.data(), unique_id_.size(), ZMQ_SNDMORE); handler_thread_socket_.send(message.key.data(), message.key.size(), ZMQ_SNDMORE); handler_thread_socket_.send(message.identity.data(), message.identity.size(), ZMQ_SNDMORE); for (auto it = std::begin(message.data); it != std::end(message.data); ++it) { handler_thread_socket_.send(it->c_str(), it->size(), std::next(it) != std::end(message.data) ? ZMQ_SNDMORE : 0); } } <|endoftext|>
<commit_before>/************************************************************************* * * REALM CONFIDENTIAL * __________________ * * [2011] - [2015] Realm Inc * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Realm Incorporated and its suppliers, * if any. The intellectual and technical concepts contained * herein are proprietary to Realm Incorporated * and its suppliers and may be covered by U.S. and Foreign Patents, * patents in process, and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from Realm Incorporated. * **************************************************************************/ #ifndef REALM_TIMESTAMP_HPP #define REALM_TIMESTAMP_HPP #include <stdint.h> #include <ostream> #include <realm/util/assert.hpp> namespace realm { struct Timestamp { Timestamp(int64_t seconds, uint32_t nanoseconds) : m_seconds(seconds), m_nanoseconds(nanoseconds), m_is_null(false) { REALM_ASSERT_3(nanoseconds, <, nanoseconds_per_second); } Timestamp() : m_is_null(true) { } bool is_null() const { return m_is_null; } int64_t get_seconds() const noexcept { return m_seconds; } uint32_t get_nanoseconds() const noexcept { return m_nanoseconds; } // Note that these operators do not work if one of the Timestamps are null! Please use realm::Greater, realm::Equal // etc instead. This is in order to collect all treatment of null behaviour in a single place for all // types (query_conditions.hpp) to ensure that all types sort and compare null vs. non-null in the same manner, // especially for int/float where we cannot override operators. This design is open for discussion, though, because // it has usability drawbacks bool operator==(const Timestamp& rhs) const { REALM_ASSERT(!is_null()); REALM_ASSERT(!rhs.is_null()); return m_seconds == rhs.m_seconds && m_nanoseconds == rhs.m_nanoseconds; } bool operator!=(const Timestamp& rhs) const { REALM_ASSERT(!is_null()); REALM_ASSERT(!rhs.is_null()); return m_seconds != rhs.m_seconds || m_nanoseconds != rhs.m_nanoseconds; } bool operator>(const Timestamp& rhs) const { REALM_ASSERT(!is_null()); REALM_ASSERT(!rhs.is_null()); return (m_seconds > rhs.m_seconds) || (m_seconds == rhs.m_seconds && m_nanoseconds > rhs.m_nanoseconds); } bool operator<(const Timestamp& rhs) const { REALM_ASSERT(!is_null()); REALM_ASSERT(!rhs.is_null()); return (m_seconds < rhs.m_seconds) || (m_seconds == rhs.m_seconds && m_nanoseconds < rhs.m_nanoseconds); } bool operator<=(const Timestamp& rhs) const { REALM_ASSERT(!is_null()); REALM_ASSERT(!rhs.is_null()); return *this < rhs || *this == rhs; } bool operator>=(const Timestamp& rhs) const { REALM_ASSERT(!is_null()); REALM_ASSERT(!rhs.is_null()); return *this > rhs || *this == rhs; } Timestamp& operator=(const Timestamp& rhs) = default; template<class Ch, class Tr> friend std::basic_ostream<Ch, Tr>& operator<<(std::basic_ostream<Ch, Tr>& out, const Timestamp&); static constexpr uint32_t nanoseconds_per_second = 1000000000; private: int64_t m_seconds; uint32_t m_nanoseconds; bool m_is_null; }; template<class C, class T> inline std::basic_ostream<C, T>& operator<<(std::basic_ostream<C, T>& out, const Timestamp& d) { out << "Timestamp(" << d.m_seconds << ", " << d.m_nanoseconds << ")"; return out; } } // namespace realm #endif // REALM_TIMESTAMP_HPP <commit_msg>Added asserts for only getting seconds and nanoseconds from non-null Timestamps<commit_after>/************************************************************************* * * REALM CONFIDENTIAL * __________________ * * [2011] - [2015] Realm Inc * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Realm Incorporated and its suppliers, * if any. The intellectual and technical concepts contained * herein are proprietary to Realm Incorporated * and its suppliers and may be covered by U.S. and Foreign Patents, * patents in process, and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from Realm Incorporated. * **************************************************************************/ #ifndef REALM_TIMESTAMP_HPP #define REALM_TIMESTAMP_HPP #include <stdint.h> #include <ostream> #include <realm/util/assert.hpp> namespace realm { struct Timestamp { Timestamp(int64_t seconds, uint32_t nanoseconds) : m_seconds(seconds), m_nanoseconds(nanoseconds), m_is_null(false) { REALM_ASSERT_3(nanoseconds, <, nanoseconds_per_second); } Timestamp() : m_is_null(true) { } bool is_null() const { return m_is_null; } int64_t get_seconds() const noexcept { REALM_ASSERT(!m_is_null); return m_seconds; } uint32_t get_nanoseconds() const noexcept { REALM_ASSERT(!m_is_null); return m_nanoseconds; } // Note that these operators do not work if one of the Timestamps are null! Please use realm::Greater, realm::Equal // etc instead. This is in order to collect all treatment of null behaviour in a single place for all // types (query_conditions.hpp) to ensure that all types sort and compare null vs. non-null in the same manner, // especially for int/float where we cannot override operators. This design is open for discussion, though, because // it has usability drawbacks bool operator==(const Timestamp& rhs) const { REALM_ASSERT(!is_null()); REALM_ASSERT(!rhs.is_null()); return m_seconds == rhs.m_seconds && m_nanoseconds == rhs.m_nanoseconds; } bool operator!=(const Timestamp& rhs) const { REALM_ASSERT(!is_null()); REALM_ASSERT(!rhs.is_null()); return m_seconds != rhs.m_seconds || m_nanoseconds != rhs.m_nanoseconds; } bool operator>(const Timestamp& rhs) const { REALM_ASSERT(!is_null()); REALM_ASSERT(!rhs.is_null()); return (m_seconds > rhs.m_seconds) || (m_seconds == rhs.m_seconds && m_nanoseconds > rhs.m_nanoseconds); } bool operator<(const Timestamp& rhs) const { REALM_ASSERT(!is_null()); REALM_ASSERT(!rhs.is_null()); return (m_seconds < rhs.m_seconds) || (m_seconds == rhs.m_seconds && m_nanoseconds < rhs.m_nanoseconds); } bool operator<=(const Timestamp& rhs) const { REALM_ASSERT(!is_null()); REALM_ASSERT(!rhs.is_null()); return *this < rhs || *this == rhs; } bool operator>=(const Timestamp& rhs) const { REALM_ASSERT(!is_null()); REALM_ASSERT(!rhs.is_null()); return *this > rhs || *this == rhs; } Timestamp& operator=(const Timestamp& rhs) = default; template<class Ch, class Tr> friend std::basic_ostream<Ch, Tr>& operator<<(std::basic_ostream<Ch, Tr>& out, const Timestamp&); static constexpr uint32_t nanoseconds_per_second = 1000000000; private: int64_t m_seconds; uint32_t m_nanoseconds; bool m_is_null; }; template<class C, class T> inline std::basic_ostream<C, T>& operator<<(std::basic_ostream<C, T>& out, const Timestamp& d) { out << "Timestamp(" << d.m_seconds << ", " << d.m_nanoseconds << ")"; return out; } } // namespace realm #endif // REALM_TIMESTAMP_HPP <|endoftext|>
<commit_before>// http://lgecodejam.com // lge code jam August, 2014 // problem.3 // hyungyu.jang@lge.com #if defined _EXTERNAL_DEBUGGER && defined _DEBUG #include <trace/trace.h> #else #define trace printf #endif #include <cstdio> #include <cstring> #include <map> using namespace std; typedef map<int, int> MII; int page, link, start, limit; MII in[1002]; // index, count int way[10001][1002]; const int DEVIDER [] = { 1, 1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }; void count(int from) { memset(way, 0, sizeof(int) * 10001 * 1002); int i; for (i = 1; i <= page; i++) { if (in[from][i]) way[1][i] = in[from][i]; } for (i = 2; i <= limit; i++) { for (int index = 1; index <= page; index++) { int c = way[i-1][index]; if (c == 0) continue; if (c % DEVIDER[from] == 0) continue; MII::iterator j = in[index].begin(); for (; j != in[index].end(); j++) { int to = j->first; int cc = j->second; way[i][to] += (c * cc) % DEVIDER[from]; } way[i][index] %= DEVIDER[from]; } } int solution(0); for (i = 1; i <= limit; i++) { solution += way[i][1]; } printf("%d ", solution % DEVIDER[from]); } void solve() { int i, from, to, solution(0); scanf("%d %d %d %d", &page, &link, &start, &limit); for (i = 0; i < link; i++) { scanf("%d %d", &from, &to); in[from][to]++; } start += 1; for (i = 2; i <= start; i++) { count(i); } printf("\n"); } void clear() { for (int i = 1; i <= page; i++) { in[i].clear(); } } int main(int, char*[]) { int num; scanf("%d", &num); for (int i = 0; i < num; i++) {solve(); clear();} return 0; } <commit_msg>lge code jam 2014 august problem 3 completed<commit_after>// http://lgecodejam.com // lge code jam August, 2014 // problem.3 // hyungyu.jang@lge.com #if defined _EXTERNAL_DEBUGGER && defined _DEBUG #include <trace/trace.h> #else #define trace printf #endif #include <cstdio> #include <cstring> #include <map> using namespace std; typedef map<int, int> MII; typedef long long int64; const int64 DEVIDER [] = { 1, 1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, }; const int64 ALL = 2ll * 3ll * 5ll * 7ll * 11ll * 13ll * 17ll * 19ll * 23ll * 29ll; int page, link, start, limit; MII in[1002]; // index, count int64 way[10001][1002]; int64 _length[12]; void count(int from) { memset(way, 0, sizeof(int64) * 10001 * 1002); int i; for (i = 1; i <= page; i++) { if (in[from][i]) way[1][i] = in[from][i]; } for (i = 2; i <= limit; i++) { for (int index = 1; index <= page; index++) { int64 c = way[i-1][index]; if (c == 0) continue; MII::iterator j = in[index].begin(); for (; j != in[index].end(); j++) { int to = j->first; int64 cc = j->second; way[i][to] += (c *cc) % ALL; } //way[i][index] %= ALL; } } for (i = 1; i <= limit; i++) { for (int j = 2; j <= start; j++) { _length[j] += way[i][j] % DEVIDER[j]; } } for (i = 2; i <= start; i++) { printf("%d ", _length[i] % DEVIDER[i]); } printf("\n"); } void solve() { memset(_length, 0, sizeof(int64) * 12); int i, from, to, solution(0); scanf("%d %d %d %d", &page, &link, &start, &limit); for (i = 0; i < link; i++) { scanf("%d %d", &from, &to); in[to][from]++; // reverse } start++; count(1); } void clear() { for (int i = 1; i <= page; i++) { in[i].clear(); } } int main(int, char*[]) { int num; scanf("%d", &num); for (int i = 0; i < num; i++) { solve(); clear(); } return 0; } <|endoftext|>
<commit_before>// Adobe Leaked Email Chcker // Date: December 2013 // Author: Jervis Muindi // Standard Lib Header #include <iostream> // Custom Common Code #include "common/base/flags.h" #include "common/base/init.h" // Program Flags DEFINE_string(db_path, "adobe.db", "Path to LevelDB file containing leaked Adobe passwords." "Defaults to using 'adobe.db'"); using namespace std; int main(int argc, char**argv) { InitProgram(&argc, &argv); cout << "DB PathFlag is " << FLAGS_db_path; return 0; } <commit_msg>Add more program flags<commit_after>// Adobe Leaked Email Chcker // Date: December 2013 // Author: Jervis Muindi // Standard Lib Header #include <iostream> // Custom Common Code #include "common/base/flags.h" #include "common/base/init.h" #include "common/log/log.h" // Program Flags DEFINE_string(file_path, "adobe.db", "Path to LevelDB file containing leaked Adobe passwords." "Defaults to using 'adobe.db'"); DEFINE_string(dump_file, "adobe_dump.txt", "File path to the uncompressed raw dump of the adobe credentials."); DEFINE_bool(process_raw_dump, false, "Assumes that the file path " "in '--dump_file' points to a raw text dump of the credentials and process them" "to generate an on disk LEVELDB hashtable with the name specified in '--output_file'." "The LEVELDB hastable will be queryable in O(1) / constant time. "); using namespace std; static void OutputFlags() { LOG(INFO) << "(LevelDB) file_path: " << FLAGS_file_path; LOG(INFO) << "dump_file: " << FLAGS_dump_file; LOG(INFO) << "process_raw_dump?" << FLAGS_process_raw_dump; } int main(int argc, char **argv) { InitProgram(&argc, &argv); OutputFlags(); return 0; } <|endoftext|>
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "isearchcontext.h" #include "match_master.h" #include "match_context.h" #include "match_tools.h" #include "match_params.h" #include "matcher.h" #include "sessionmanager.h" #include <vespa/searchcore/grouping/groupingcontext.h> #include <vespa/searchlib/engine/errorcodes.h> #include <vespa/searchlib/engine/docsumrequest.h> #include <vespa/searchlib/engine/searchrequest.h> #include <vespa/searchlib/engine/searchreply.h> #include <vespa/searchlib/features/setup.h> #include <vespa/searchlib/fef/test/plugin/setup.h> #include <vespa/log/log.h> LOG_SETUP(".proton.matching.matcher"); using search::fef::Properties; using namespace search::fef::indexproperties::matching; using namespace search::engine; using namespace search::grouping; using search::DocumentMetaData; using search::LidUsageStats; using search::FeatureSet; using search::attribute::IAttributeContext; using search::fef::MatchDataLayout; using search::fef::MatchData; using search::fef::indexproperties::hitcollector::HeapSize; using search::queryeval::Blueprint; using search::queryeval::SearchIterator; using vespalib::Doom; namespace proton::matching { namespace { // used to give out empty whitelist blueprints struct StupidMetaStore : search::IDocumentMetaStore { bool getGid(DocId, GlobalId &) const override { return false; } bool getGidEvenIfMoved(DocId, GlobalId &) const override { return false; } bool getLid(const GlobalId &, DocId &) const override { return false; } DocumentMetaData getMetaData(const GlobalId &) const override { return DocumentMetaData(); } void getMetaData(const BucketId &, DocumentMetaData::Vector &) const override { } DocId getCommittedDocIdLimit() const override { return 1; } DocId getNumUsedLids() const override { return 0; } DocId getNumActiveLids() const override { return 0; } uint64_t getCurrentGeneration() const override { return 0; } LidUsageStats getLidUsageStats() const override { return LidUsageStats(); } Blueprint::UP createWhiteListBlueprint() const override { return Blueprint::UP(); } void foreach(const search::IGidToLidMapperVisitor &) const override { } }; FeatureSet::SP findFeatureSet(const DocsumRequest &req, MatchToolsFactory &mtf, bool summaryFeatures) { std::vector<uint32_t> docs; docs.reserve(req.hits.size()); for (const auto & hit : req.hits) { if (hit.docid != search::endDocId) { docs.push_back(hit.docid); } } std::sort(docs.begin(), docs.end()); return MatchMaster::getFeatureSet(mtf, docs, summaryFeatures); } size_t numThreads(size_t hits, size_t minHits) { return static_cast<size_t>(std::ceil(double(hits) / double(minHits))); } class LimitedThreadBundleWrapper final : public vespalib::ThreadBundle { public: LimitedThreadBundleWrapper(vespalib::ThreadBundle &threadBundle, uint32_t maxThreads) : _threadBundle(threadBundle), _maxThreads(std::min(maxThreads, static_cast<uint32_t>(threadBundle.size()))) { } private: size_t size() const override { return _maxThreads; } void run(const std::vector<vespalib::Runnable*> &targets) override { _threadBundle.run(targets); } vespalib::ThreadBundle &_threadBundle; const uint32_t _maxThreads; }; bool willNotNeedRanking(const SearchRequest & request, const GroupingContext & groupingContext) { return (!groupingContext.needRanking() && (request.maxhits == 0)) || (!request.sortSpec.empty() && (request.sortSpec.find("[rank]") == vespalib::string::npos)); } } // namespace proton::matching::<unnamed> FeatureSet::SP Matcher::getFeatureSet(const DocsumRequest & req, ISearchContext & searchCtx, IAttributeContext & attrCtx, SessionManager & sessionMgr, bool summaryFeatures) { SessionId sessionId(&req.sessionId[0], req.sessionId.size()); if (!sessionId.empty()) { const Properties &cache_props = req.propertiesMap.cacheProperties(); bool searchSessionCached = cache_props.lookup("query").found(); if (searchSessionCached) { SearchSession::SP session(sessionMgr.pickSearch(sessionId)); if (session) { MatchToolsFactory &mtf = session->getMatchToolsFactory(); FeatureSet::SP result = findFeatureSet(req, mtf, summaryFeatures); session->releaseEnumGuards(); return result; } } } StupidMetaStore metaStore; MatchToolsFactory::UP mtf = create_match_tools_factory(req, searchCtx, attrCtx, metaStore, req.propertiesMap.featureOverrides()); if (!mtf->valid()) { LOG(warning, "getFeatureSet(%s): query execution failed (invalid query). Returning empty feature set", (summaryFeatures ? "summary features" : "rank features")); return std::make_shared<FeatureSet>(); } return findFeatureSet(req, *mtf, summaryFeatures); } Matcher::Matcher(const search::index::Schema &schema, const Properties &props, const vespalib::Clock &clock, QueryLimiter &queryLimiter, const IConstantValueRepo &constantValueRepo, uint32_t distributionKey) : _indexEnv(schema, props, constantValueRepo), _blueprintFactory(), _rankSetup(), _viewResolver(ViewResolver::createFromSchema(schema)), _statsLock(), _stats(), _clock(clock), _queryLimiter(queryLimiter), _distributionKey(distributionKey) { search::features::setup_search_features(_blueprintFactory); search::fef::test::setup_fef_test_plugin(_blueprintFactory); _rankSetup = std::make_shared<search::fef::RankSetup>(_blueprintFactory, _indexEnv); _rankSetup->configure(); // reads config values from the property map if (!_rankSetup->compile()) { throw vespalib::IllegalArgumentException("failed to compile rank setup", VESPA_STRLOC); } } MatchingStats Matcher::getStats() { std::lock_guard<std::mutex> guard(_statsLock); MatchingStats stats = std::move(_stats); _stats = std::move(MatchingStats()); _stats.softDoomFactor(stats.softDoomFactor()); return stats; } using search::fef::indexproperties::softtimeout::Enabled; using search::fef::indexproperties::softtimeout::Factor; std::unique_ptr<MatchToolsFactory> Matcher::create_match_tools_factory(const search::engine::Request &request, ISearchContext &searchContext, IAttributeContext &attrContext, const search::IDocumentMetaStore &metaStore, const Properties &feature_overrides) const { const Properties & rankProperties = request.propertiesMap.rankProperties(); bool softTimeoutEnabled = Enabled::lookup(rankProperties, _rankSetup->getSoftTimeoutEnabled()); double factor = softTimeoutEnabled ? Factor::lookup(rankProperties, _stats.softDoomFactor()) : 0.95; int64_t safeLeft = request.getTimeLeft() * factor; fastos::TimeStamp safeDoom(fastos::ClockSystem::now() + safeLeft); if (softTimeoutEnabled) { LOG(debug, "Soft-timeout computed factor=%1.3f, used factor=%1.3f, softTimeout=%lu softDoom=%ld hardDoom=%ld", _stats.softDoomFactor(), factor, safeLeft, safeDoom.ns(), request.getTimeOfDoom().ns()); } return std::make_unique<MatchToolsFactory>(_queryLimiter, vespalib::Doom(_clock, safeDoom), vespalib::Doom(_clock, request.getTimeOfDoom()), searchContext, attrContext, request.getStackRef(), request.location, _viewResolver, metaStore, _indexEnv, *_rankSetup, rankProperties, feature_overrides); } SearchReply::UP Matcher::handleGroupingSession(SessionManager &sessionMgr, GroupingContext & groupingContext, GroupingSession::UP groupingSession) { SearchReply::UP reply = std::make_unique<SearchReply>(); groupingSession->continueExecution(groupingContext); groupingContext.getResult().swap(reply->groupResult); if (!groupingSession->finished()) { sessionMgr.insert(std::move(groupingSession)); } return reply; } size_t Matcher::computeNumThreadsPerSearch(Blueprint::HitEstimate hits, const Properties & rankProperties) const { size_t threads = NumThreadsPerSearch::lookup(rankProperties, _rankSetup->getNumThreadsPerSearch()); uint32_t minHitsPerThread = MinHitsPerThread::lookup(rankProperties, _rankSetup->getMinHitsPerThread()); if ((threads > 1) && (minHitsPerThread > 0)) { threads = (hits.empty) ? 1 : std::min(threads, numThreads(hits.estHits, minHitsPerThread)); } return threads; } SearchReply::UP Matcher::match(const SearchRequest &request, vespalib::ThreadBundle &threadBundle, ISearchContext &searchContext, IAttributeContext &attrContext, SessionManager &sessionMgr, const search::IDocumentMetaStore &metaStore, SearchSession::OwnershipBundle &&owned_objects) { fastos::StopWatch total_matching_time; total_matching_time.start(); MatchingStats my_stats; SearchReply::UP reply = std::make_unique<SearchReply>(); { // we want to measure full set-up and tear-down time as part of // collateral time GroupingContext groupingContext(_clock, request.getTimeOfDoom(), &request.groupSpec[0], request.groupSpec.size()); SessionId sessionId(&request.sessionId[0], request.sessionId.size()); bool shouldCacheSearchSession = false; bool shouldCacheGroupingSession = false; if (!sessionId.empty()) { const Properties &cache_props = request.propertiesMap.cacheProperties(); shouldCacheGroupingSession = cache_props.lookup("grouping").found(); shouldCacheSearchSession = cache_props.lookup("query").found(); if (shouldCacheGroupingSession) { GroupingSession::UP session(sessionMgr.pickGrouping(sessionId)); if (session) { return handleGroupingSession(sessionMgr, groupingContext, std::move(session)); } } } const Properties *feature_overrides = &request.propertiesMap.featureOverrides(); if (shouldCacheSearchSession) { owned_objects.feature_overrides = std::make_unique<Properties>(*feature_overrides); feature_overrides = owned_objects.feature_overrides.get(); } MatchToolsFactory::UP mtf = create_match_tools_factory(request, searchContext, attrContext, metaStore, *feature_overrides); if (!mtf->valid()) { reply->errorCode = ECODE_QUERY_PARSE_ERROR; reply->errorMessage = "query execution failed (invalid query)"; return reply; } const Properties & rankProperties = request.propertiesMap.rankProperties(); uint32_t heapSize = HeapSize::lookup(rankProperties, _rankSetup->getHeapSize()); MatchParams params(searchContext.getDocIdLimit(), heapSize, _rankSetup->getArraySize(), _rankSetup->getRankScoreDropLimit(), request.offset, request.maxhits, !_rankSetup->getSecondPhaseRank().empty(), !willNotNeedRanking(request, groupingContext)); ResultProcessor rp(attrContext, metaStore, sessionMgr, groupingContext, sessionId, request.sortSpec, params.offset, params.hits, request.should_drop_sort_data()); size_t numThreadsPerSearch = computeNumThreadsPerSearch(mtf->estimate(), rankProperties); LimitedThreadBundleWrapper limitedThreadBundle(threadBundle, numThreadsPerSearch); MatchMaster master; uint32_t numSearchPartitions = NumSearchPartitions::lookup(rankProperties, _rankSetup->getNumSearchPartitions()); ResultProcessor::Result::UP result = master.match(params, limitedThreadBundle, *mtf, rp, _distributionKey, numSearchPartitions); my_stats = MatchMaster::getStats(std::move(master)); bool wasLimited = mtf->match_limiter().was_limited(); size_t spaceEstimate = (my_stats.softDoomed()) ? my_stats.docidSpaceCovered() : mtf->match_limiter().getDocIdSpaceEstimate(); uint32_t estHits = mtf->estimate().estHits; if (shouldCacheSearchSession && ((result->_numFs4Hits != 0) || shouldCacheGroupingSession)) { SearchSession::SP session = std::make_shared<SearchSession>(sessionId, request.getTimeOfDoom(), std::move(mtf), std::move(owned_objects)); session->releaseEnumGuards(); sessionMgr.insert(std::move(session)); } reply = std::move(result->_reply); uint32_t numActiveLids = metaStore.getNumActiveLids(); // note: this is actually totalSpace+1, since 0 is reserved uint32_t totalSpace = metaStore.getCommittedDocIdLimit(); LOG(debug, "docid limit = %d", totalSpace); LOG(debug, "num active lids = %d", numActiveLids); LOG(debug, "space Estimate = %zd", spaceEstimate); if (spaceEstimate >= totalSpace) { // estimate is too high, clamp it spaceEstimate = totalSpace; } else { // account for docid 0 reserved spaceEstimate += 1; } size_t covered = (spaceEstimate * numActiveLids) / totalSpace; LOG(debug, "covered = %zd", covered); SearchReply::Coverage & coverage = reply->coverage; coverage.setActive(numActiveLids); //TODO this should be calculated with ClusterState calculator. coverage.setSoonActive(numActiveLids); coverage.setCovered(covered); if (wasLimited) { coverage.degradeMatchPhase(); LOG(debug, "was limited, degraded from match phase"); } if (my_stats.softDoomed()) { coverage.degradeTimeout(); LOG(debug, "soft doomed, degraded from timeout covered = %lu", coverage.getCovered()); } LOG(debug, "numThreadsPerSearch = %zu. Configured = %d, estimated hits=%d, totalHits=%ld , rankprofile=%s", numThreadsPerSearch, _rankSetup->getNumThreadsPerSearch(), estHits, reply->totalHitCount, request.ranking.c_str()); } total_matching_time.stop(); my_stats.queryCollateralTime(total_matching_time.elapsed().sec() - my_stats.queryLatencyAvg()); { fastos::TimeStamp duration = request.getTimeUsed(); std::lock_guard<std::mutex> guard(_statsLock); _stats.add(my_stats); if (my_stats.softDoomed()) { double old = _stats.softDoomFactor(); fastos::TimeStamp softLimit = uint64_t((1.0 - _rankSetup->getSoftTimeoutTailCost()) * request.getTimeout()); _stats.updatesoftDoomFactor(request.getTimeout(), softLimit, duration - my_stats.doomOvertime()); LOG(info, "Triggered softtimeout factor adjustment. request=%1.3f, doomOvertime=%1.3f, limit=%1.3f and duration=%1.3f, rankprofile=%s" ", factor adjusted from %1.3f to %1.3f", request.getTimeout().sec(), my_stats.doomOvertime().sec(), softLimit.sec(), duration.sec(), request.ranking.c_str(), old, _stats.softDoomFactor()); } } return reply; } FeatureSet::SP Matcher::getSummaryFeatures(const DocsumRequest & req, ISearchContext & searchCtx, IAttributeContext & attrCtx, SessionManager &sessionMgr) { return getFeatureSet(req, searchCtx, attrCtx, sessionMgr, true); } FeatureSet::SP Matcher::getRankFeatures(const DocsumRequest & req, ISearchContext & searchCtx, IAttributeContext & attrCtx, SessionManager &sessionMgr) { return getFeatureSet(req, searchCtx, attrCtx, sessionMgr, false); } } <commit_msg>Avoid underflow<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "isearchcontext.h" #include "match_master.h" #include "match_context.h" #include "match_tools.h" #include "match_params.h" #include "matcher.h" #include "sessionmanager.h" #include <vespa/searchcore/grouping/groupingcontext.h> #include <vespa/searchlib/engine/errorcodes.h> #include <vespa/searchlib/engine/docsumrequest.h> #include <vespa/searchlib/engine/searchrequest.h> #include <vespa/searchlib/engine/searchreply.h> #include <vespa/searchlib/features/setup.h> #include <vespa/searchlib/fef/test/plugin/setup.h> #include <vespa/log/log.h> LOG_SETUP(".proton.matching.matcher"); using search::fef::Properties; using namespace search::fef::indexproperties::matching; using namespace search::engine; using namespace search::grouping; using search::DocumentMetaData; using search::LidUsageStats; using search::FeatureSet; using search::attribute::IAttributeContext; using search::fef::MatchDataLayout; using search::fef::MatchData; using search::fef::indexproperties::hitcollector::HeapSize; using search::queryeval::Blueprint; using search::queryeval::SearchIterator; using vespalib::Doom; namespace proton::matching { namespace { // used to give out empty whitelist blueprints struct StupidMetaStore : search::IDocumentMetaStore { bool getGid(DocId, GlobalId &) const override { return false; } bool getGidEvenIfMoved(DocId, GlobalId &) const override { return false; } bool getLid(const GlobalId &, DocId &) const override { return false; } DocumentMetaData getMetaData(const GlobalId &) const override { return DocumentMetaData(); } void getMetaData(const BucketId &, DocumentMetaData::Vector &) const override { } DocId getCommittedDocIdLimit() const override { return 1; } DocId getNumUsedLids() const override { return 0; } DocId getNumActiveLids() const override { return 0; } uint64_t getCurrentGeneration() const override { return 0; } LidUsageStats getLidUsageStats() const override { return LidUsageStats(); } Blueprint::UP createWhiteListBlueprint() const override { return Blueprint::UP(); } void foreach(const search::IGidToLidMapperVisitor &) const override { } }; FeatureSet::SP findFeatureSet(const DocsumRequest &req, MatchToolsFactory &mtf, bool summaryFeatures) { std::vector<uint32_t> docs; docs.reserve(req.hits.size()); for (const auto & hit : req.hits) { if (hit.docid != search::endDocId) { docs.push_back(hit.docid); } } std::sort(docs.begin(), docs.end()); return MatchMaster::getFeatureSet(mtf, docs, summaryFeatures); } size_t numThreads(size_t hits, size_t minHits) { return static_cast<size_t>(std::ceil(double(hits) / double(minHits))); } class LimitedThreadBundleWrapper final : public vespalib::ThreadBundle { public: LimitedThreadBundleWrapper(vespalib::ThreadBundle &threadBundle, uint32_t maxThreads) : _threadBundle(threadBundle), _maxThreads(std::min(maxThreads, static_cast<uint32_t>(threadBundle.size()))) { } private: size_t size() const override { return _maxThreads; } void run(const std::vector<vespalib::Runnable*> &targets) override { _threadBundle.run(targets); } vespalib::ThreadBundle &_threadBundle; const uint32_t _maxThreads; }; bool willNotNeedRanking(const SearchRequest & request, const GroupingContext & groupingContext) { return (!groupingContext.needRanking() && (request.maxhits == 0)) || (!request.sortSpec.empty() && (request.sortSpec.find("[rank]") == vespalib::string::npos)); } } // namespace proton::matching::<unnamed> FeatureSet::SP Matcher::getFeatureSet(const DocsumRequest & req, ISearchContext & searchCtx, IAttributeContext & attrCtx, SessionManager & sessionMgr, bool summaryFeatures) { SessionId sessionId(&req.sessionId[0], req.sessionId.size()); if (!sessionId.empty()) { const Properties &cache_props = req.propertiesMap.cacheProperties(); bool searchSessionCached = cache_props.lookup("query").found(); if (searchSessionCached) { SearchSession::SP session(sessionMgr.pickSearch(sessionId)); if (session) { MatchToolsFactory &mtf = session->getMatchToolsFactory(); FeatureSet::SP result = findFeatureSet(req, mtf, summaryFeatures); session->releaseEnumGuards(); return result; } } } StupidMetaStore metaStore; MatchToolsFactory::UP mtf = create_match_tools_factory(req, searchCtx, attrCtx, metaStore, req.propertiesMap.featureOverrides()); if (!mtf->valid()) { LOG(warning, "getFeatureSet(%s): query execution failed (invalid query). Returning empty feature set", (summaryFeatures ? "summary features" : "rank features")); return std::make_shared<FeatureSet>(); } return findFeatureSet(req, *mtf, summaryFeatures); } Matcher::Matcher(const search::index::Schema &schema, const Properties &props, const vespalib::Clock &clock, QueryLimiter &queryLimiter, const IConstantValueRepo &constantValueRepo, uint32_t distributionKey) : _indexEnv(schema, props, constantValueRepo), _blueprintFactory(), _rankSetup(), _viewResolver(ViewResolver::createFromSchema(schema)), _statsLock(), _stats(), _clock(clock), _queryLimiter(queryLimiter), _distributionKey(distributionKey) { search::features::setup_search_features(_blueprintFactory); search::fef::test::setup_fef_test_plugin(_blueprintFactory); _rankSetup = std::make_shared<search::fef::RankSetup>(_blueprintFactory, _indexEnv); _rankSetup->configure(); // reads config values from the property map if (!_rankSetup->compile()) { throw vespalib::IllegalArgumentException("failed to compile rank setup", VESPA_STRLOC); } } MatchingStats Matcher::getStats() { std::lock_guard<std::mutex> guard(_statsLock); MatchingStats stats = std::move(_stats); _stats = std::move(MatchingStats()); _stats.softDoomFactor(stats.softDoomFactor()); return stats; } using search::fef::indexproperties::softtimeout::Enabled; using search::fef::indexproperties::softtimeout::Factor; std::unique_ptr<MatchToolsFactory> Matcher::create_match_tools_factory(const search::engine::Request &request, ISearchContext &searchContext, IAttributeContext &attrContext, const search::IDocumentMetaStore &metaStore, const Properties &feature_overrides) const { const Properties & rankProperties = request.propertiesMap.rankProperties(); bool softTimeoutEnabled = Enabled::lookup(rankProperties, _rankSetup->getSoftTimeoutEnabled()); double factor = softTimeoutEnabled ? Factor::lookup(rankProperties, _stats.softDoomFactor()) : 0.95; int64_t safeLeft = request.getTimeLeft() * factor; fastos::TimeStamp safeDoom(fastos::ClockSystem::now() + safeLeft); if (softTimeoutEnabled) { LOG(debug, "Soft-timeout computed factor=%1.3f, used factor=%1.3f, softTimeout=%lu softDoom=%ld hardDoom=%ld", _stats.softDoomFactor(), factor, safeLeft, safeDoom.ns(), request.getTimeOfDoom().ns()); } return std::make_unique<MatchToolsFactory>(_queryLimiter, vespalib::Doom(_clock, safeDoom), vespalib::Doom(_clock, request.getTimeOfDoom()), searchContext, attrContext, request.getStackRef(), request.location, _viewResolver, metaStore, _indexEnv, *_rankSetup, rankProperties, feature_overrides); } SearchReply::UP Matcher::handleGroupingSession(SessionManager &sessionMgr, GroupingContext & groupingContext, GroupingSession::UP groupingSession) { SearchReply::UP reply = std::make_unique<SearchReply>(); groupingSession->continueExecution(groupingContext); groupingContext.getResult().swap(reply->groupResult); if (!groupingSession->finished()) { sessionMgr.insert(std::move(groupingSession)); } return reply; } size_t Matcher::computeNumThreadsPerSearch(Blueprint::HitEstimate hits, const Properties & rankProperties) const { size_t threads = NumThreadsPerSearch::lookup(rankProperties, _rankSetup->getNumThreadsPerSearch()); uint32_t minHitsPerThread = MinHitsPerThread::lookup(rankProperties, _rankSetup->getMinHitsPerThread()); if ((threads > 1) && (minHitsPerThread > 0)) { threads = (hits.empty) ? 1 : std::min(threads, numThreads(hits.estHits, minHitsPerThread)); } return threads; } SearchReply::UP Matcher::match(const SearchRequest &request, vespalib::ThreadBundle &threadBundle, ISearchContext &searchContext, IAttributeContext &attrContext, SessionManager &sessionMgr, const search::IDocumentMetaStore &metaStore, SearchSession::OwnershipBundle &&owned_objects) { fastos::StopWatch total_matching_time; total_matching_time.start(); MatchingStats my_stats; SearchReply::UP reply = std::make_unique<SearchReply>(); { // we want to measure full set-up and tear-down time as part of // collateral time GroupingContext groupingContext(_clock, request.getTimeOfDoom(), &request.groupSpec[0], request.groupSpec.size()); SessionId sessionId(&request.sessionId[0], request.sessionId.size()); bool shouldCacheSearchSession = false; bool shouldCacheGroupingSession = false; if (!sessionId.empty()) { const Properties &cache_props = request.propertiesMap.cacheProperties(); shouldCacheGroupingSession = cache_props.lookup("grouping").found(); shouldCacheSearchSession = cache_props.lookup("query").found(); if (shouldCacheGroupingSession) { GroupingSession::UP session(sessionMgr.pickGrouping(sessionId)); if (session) { return handleGroupingSession(sessionMgr, groupingContext, std::move(session)); } } } const Properties *feature_overrides = &request.propertiesMap.featureOverrides(); if (shouldCacheSearchSession) { owned_objects.feature_overrides = std::make_unique<Properties>(*feature_overrides); feature_overrides = owned_objects.feature_overrides.get(); } MatchToolsFactory::UP mtf = create_match_tools_factory(request, searchContext, attrContext, metaStore, *feature_overrides); if (!mtf->valid()) { reply->errorCode = ECODE_QUERY_PARSE_ERROR; reply->errorMessage = "query execution failed (invalid query)"; return reply; } const Properties & rankProperties = request.propertiesMap.rankProperties(); uint32_t heapSize = HeapSize::lookup(rankProperties, _rankSetup->getHeapSize()); MatchParams params(searchContext.getDocIdLimit(), heapSize, _rankSetup->getArraySize(), _rankSetup->getRankScoreDropLimit(), request.offset, request.maxhits, !_rankSetup->getSecondPhaseRank().empty(), !willNotNeedRanking(request, groupingContext)); ResultProcessor rp(attrContext, metaStore, sessionMgr, groupingContext, sessionId, request.sortSpec, params.offset, params.hits, request.should_drop_sort_data()); size_t numThreadsPerSearch = computeNumThreadsPerSearch(mtf->estimate(), rankProperties); LimitedThreadBundleWrapper limitedThreadBundle(threadBundle, numThreadsPerSearch); MatchMaster master; uint32_t numSearchPartitions = NumSearchPartitions::lookup(rankProperties, _rankSetup->getNumSearchPartitions()); ResultProcessor::Result::UP result = master.match(params, limitedThreadBundle, *mtf, rp, _distributionKey, numSearchPartitions); my_stats = MatchMaster::getStats(std::move(master)); bool wasLimited = mtf->match_limiter().was_limited(); size_t spaceEstimate = (my_stats.softDoomed()) ? my_stats.docidSpaceCovered() : mtf->match_limiter().getDocIdSpaceEstimate(); uint32_t estHits = mtf->estimate().estHits; if (shouldCacheSearchSession && ((result->_numFs4Hits != 0) || shouldCacheGroupingSession)) { SearchSession::SP session = std::make_shared<SearchSession>(sessionId, request.getTimeOfDoom(), std::move(mtf), std::move(owned_objects)); session->releaseEnumGuards(); sessionMgr.insert(std::move(session)); } reply = std::move(result->_reply); uint32_t numActiveLids = metaStore.getNumActiveLids(); // note: this is actually totalSpace+1, since 0 is reserved uint32_t totalSpace = metaStore.getCommittedDocIdLimit(); LOG(debug, "docid limit = %d", totalSpace); LOG(debug, "num active lids = %d", numActiveLids); LOG(debug, "space Estimate = %zd", spaceEstimate); if (spaceEstimate >= totalSpace) { // estimate is too high, clamp it spaceEstimate = totalSpace; } else { // account for docid 0 reserved spaceEstimate += 1; } size_t covered = (spaceEstimate * numActiveLids) / totalSpace; LOG(debug, "covered = %zd", covered); SearchReply::Coverage & coverage = reply->coverage; coverage.setActive(numActiveLids); //TODO this should be calculated with ClusterState calculator. coverage.setSoonActive(numActiveLids); coverage.setCovered(covered); if (wasLimited) { coverage.degradeMatchPhase(); LOG(debug, "was limited, degraded from match phase"); } if (my_stats.softDoomed()) { coverage.degradeTimeout(); LOG(debug, "soft doomed, degraded from timeout covered = %lu", coverage.getCovered()); } LOG(debug, "numThreadsPerSearch = %zu. Configured = %d, estimated hits=%d, totalHits=%ld , rankprofile=%s", numThreadsPerSearch, _rankSetup->getNumThreadsPerSearch(), estHits, reply->totalHitCount, request.ranking.c_str()); } total_matching_time.stop(); my_stats.queryCollateralTime(total_matching_time.elapsed().sec() - my_stats.queryLatencyAvg()); { fastos::TimeStamp duration = request.getTimeUsed(); std::lock_guard<std::mutex> guard(_statsLock); _stats.add(my_stats); if (my_stats.softDoomed()) { double old = _stats.softDoomFactor(); fastos::TimeStamp softLimit = uint64_t((1.0 - _rankSetup->getSoftTimeoutTailCost()) * request.getTimeout()); fastos::TimeStamp adjustedDuration = duration - my_stats.doomOvertime(); if (adjustedDuration < 0) { adjustedDuration = 0; } _stats.updatesoftDoomFactor(request.getTimeout(), softLimit, adjustedDuration); LOG(info, "Triggered softtimeout factor adjustment. request=%1.3f, doomOvertime=%1.3f, limit=%1.3f and duration=%1.3f, rankprofile=%s" ", factor adjusted from %1.3f to %1.3f", request.getTimeout().sec(), my_stats.doomOvertime().sec(), softLimit.sec(), duration.sec(), request.ranking.c_str(), old, _stats.softDoomFactor()); } } return reply; } FeatureSet::SP Matcher::getSummaryFeatures(const DocsumRequest & req, ISearchContext & searchCtx, IAttributeContext & attrCtx, SessionManager &sessionMgr) { return getFeatureSet(req, searchCtx, attrCtx, sessionMgr, true); } FeatureSet::SP Matcher::getRankFeatures(const DocsumRequest & req, ISearchContext & searchCtx, IAttributeContext & attrCtx, SessionManager &sessionMgr) { return getFeatureSet(req, searchCtx, attrCtx, sessionMgr, false); } } <|endoftext|>
<commit_before>#include "FAST/Tests/catch.hpp" #include "FAST/DeviceManager.hpp" #include "NonLocalMeans.hpp" namespace fast{ TEST_CASE("No input given to NonLocalMeans throws exception", "[fast][NonLocalMeans]") { NonLocalMeans::pointer filter = NonLocalMeans::New(); CHECK_THROWS(filter->update()); } TEST_CASE("Negative or zero sigma input throws exception in NonLocalMeans", "[fast][NonLocalMeans]") { NonLocalMeans::pointer filter = NonLocalMeans::New(); CHECK_THROWS(filter->setWindowSize(-4)); CHECK_THROWS(filter->setWindowSize(0)); CHECK_THROWS(filter->setGroupSize(-4)); CHECK_THROWS(filter->setGroupSize(0)); CHECK_THROWS(filter->setK(-4)); CHECK_THROWS(filter->setK(0)); CHECK_THROWS(filter->setEuclid(-4)); CHECK_THROWS(filter->setEuclid(0)); CHECK_THROWS(filter->setSigma(-4)); CHECK_THROWS(filter->setSigma(0)); CHECK_THROWS(filter->setDenoiseStrength(-4)); CHECK_THROWS(filter->setDenoiseStrength(0)); } TEST_CASE("Even input as window size or group size throws exception in NonLocalMeans", "[fast][NonLocalMeans]") { NonLocalMeans::pointer filter = NonLocalMeans::New(); CHECK_THROWS(filter->setWindowSize(2)); CHECK_THROWS(filter->setGroupSize(2)); } }<commit_msg>fixed a failing NLM test<commit_after>#include "FAST/Tests/catch.hpp" #include "FAST/DeviceManager.hpp" #include "NonLocalMeans.hpp" namespace fast{ TEST_CASE("No input given to NonLocalMeans throws exception", "[fast][NonLocalMeans]") { NonLocalMeans::pointer filter = NonLocalMeans::New(); CHECK_THROWS(filter->update()); } TEST_CASE("Negative or zero sigma input throws exception in NonLocalMeans", "[fast][NonLocalMeans]") { NonLocalMeans::pointer filter = NonLocalMeans::New(); CHECK_THROWS(filter->setWindowSize(-4)); CHECK_THROWS(filter->setWindowSize(0)); CHECK_THROWS(filter->setGroupSize(-4)); CHECK_THROWS(filter->setGroupSize(0)); CHECK_THROWS(filter->setK(-4)); CHECK_THROWS(filter->setEuclid(-4)); CHECK_THROWS(filter->setSigma(-4)); CHECK_THROWS(filter->setSigma(0)); CHECK_THROWS(filter->setDenoiseStrength(-4)); CHECK_THROWS(filter->setDenoiseStrength(0)); } TEST_CASE("Even input as window size or group size throws exception in NonLocalMeans", "[fast][NonLocalMeans]") { NonLocalMeans::pointer filter = NonLocalMeans::New(); CHECK_THROWS(filter->setWindowSize(2)); CHECK_THROWS(filter->setGroupSize(2)); } } <|endoftext|>
<commit_before>/* * StackAcquisition.cpp * * Created on: May 10, 2010 * Author: Nathan Clack <clackn@janelia.hhmi.org> */ /* * Copyright 2010 Howard Hughes Medical Institute. * All rights reserved. * Use is subject to Janelia Farm Research Campus Software Copyright 1.1 * license terms (http://license.janelia.org/license/jfrc_copyright_1_1.html). */ #include "common.h" #include "StackAcquisition.h" #include "Video.h" #include "frame.h" #include "devices\digitizer.h" #include "devices\Microscope.h" #if 0 #define DBG(...) debug(__VA_ARGS__); #else #define DBG(...) #endif #define DIGWRN( expr ) (niscope_chk( vi, expr, #expr, __FILE__, __LINE__, warning )) #define DIGERR( expr ) (niscope_chk( vi, expr, #expr, __FILE__, __LINE__, error )) #define DIGJMP( expr ) goto_if_fail(VI_SUCCESS == niscope_chk( vi, expr, #expr, __FILE__, __LINE__, warning ), Error) #define DAQWRN( expr ) (Guarded_DAQmx( (expr), #expr, __FILE__, __LINE__, warning)) #define DAQERR( expr ) (Guarded_DAQmx( (expr), #expr, __FILE__, __LINE__, error )) #define DAQJMP( expr ) goto_if_fail( 0==DAQWRN(expr), Error) #define CHKERR( expr ) if(expr) {error("%s(%d)"ENDL"\tExpression indicated failure:"ENDL"\t%s"ENDL,__FILE__,__LINE__,#expr);} //( (expr), #expr, error )) #define CHKJMP( expr ) goto_if((expr),Error) #if 0 #define SCANNER_DEBUG_FAIL_WHEN_FULL #else #define SCANNER_DEBUG_WAIT_WHEN_FULL #endif #ifdef SCANNER_DEBUG_FAIL_WHEN_FULL #define SCANNER_PUSH(...) Chan_Next_Try(__VA_ARGS__) #elif defined(SCANNER_DEBUG_WAIT_WHEN_FULL) #define SCANNER_PUSH(...) Chan_Next(__VA_ARGS__) #else #error("An overflow behavior for the scanner should be specified"); #endif namespace fetch { namespace task { // // StackAcquisition - microscope task // namespace microscope { //Upcasting unsigned int StackAcquisition::config(IDevice *d) {return config(dynamic_cast<device::Microscope*>(d));} unsigned int StackAcquisition::run (IDevice *d) {return run (dynamic_cast<device::Microscope*>(d));} unsigned int StackAcquisition::config(device::Microscope *d) { static task::scanner::ScanStack<i16> grabstack; std::string filename; Guarded_Assert(d); //Assemble pipeline here IDevice *cur; cur = d->configPipeline(); CHKJMP( !d->file_series.ensurePathExists() ); d->file_series.inc(); filename = d->stack_filename(); IDevice::connect(&d->disk,0,cur,0); Guarded_Assert( d->disk.close()==0 ); //Guarded_Assert( d->disk.open(filename,"w")==0); d->__scan_agent.arm(&grabstack,&d->scanner); // why was this arm_nowait? return 1; //success Error: return 0; //failure } static int _handle_wait_for_result(DWORD result, const char *msg) { return_val_if( result == WAIT_OBJECT_0 , 0 ); return_val_if( result == WAIT_OBJECT_0+1, 1 ); Guarded_Assert_WinErr( result != WAIT_FAILED ); if(result == WAIT_ABANDONED_0) warning("StackAcquisition: Wait 0 abandoned"ENDL"\t%s"ENDL, msg); if(result == WAIT_ABANDONED_0+1) warning("StackAcquisition: Wait 1 abandoned"ENDL"\t%s"ENDL, msg); if(result == WAIT_TIMEOUT) warning("StackAcquisition: Wait timeout"ENDL"\t%s"ENDL, msg); Guarded_Assert_WinErr( result != WAIT_FAILED ); return -1; } unsigned int StackAcquisition::run(device::Microscope *dc) { std::string filename; unsigned int eflag = 0; // success Guarded_Assert(dc->__scan_agent.is_runnable()); //Guarded_Assert(dc->__io_agent.is_running()); filename = dc->stack_filename(); dc->file_series.ensurePathExists(); eflag |= dc->disk.open(filename,"w"); if(eflag) return eflag; eflag |= dc->runPipeline(); eflag |= dc->__scan_agent.run() != 1; //Chan_Wait_For_Writer_Count(dc->__scan_agent._owner->_out->contents[0],1); { HANDLE hs[] = {dc->__scan_agent._thread, dc->__self_agent._notify_stop}; DWORD res; int t; // wait for scan to complete (or cancel) res = WaitForMultipleObjects(2,hs,FALSE,INFINITE); t = _handle_wait_for_result(res,"StackAcquisition::run - Wait for scanner to finish."); switch(t) { case 0: // in this case, the scanner thread stopped. Nothing left to do. eflag |= 0; // success //break; case 1: // in this case, the stop event triggered and must be propagated. eflag |= dc->__scan_agent.stop(SCANNER2D_DEFAULT_TIMEOUT) != 1; break; default: // in this case, there was a timeout or abandoned wait eflag |= 1; //failure } // Output metadata and Increment file eflag |= dc->disk.close(); dc->write_stack_metadata(); dc->file_series.inc(); //dc->connect(&dc->disk,0,dc->pipelineEnd(),0); } eflag |= dc->stopPipeline(); // wait till the pipeline stops return eflag; } } // namespace microscope // // ScanStack - scanner task // namespace scanner { template class ScanStack<i8 >; template class ScanStack<i16>; // upcasts template<class TPixel> unsigned int ScanStack<TPixel>::config (IDevice *d) {return config(dynamic_cast<device::Scanner3D*>(d));} template<class TPixel> unsigned int ScanStack<TPixel>::update (IDevice *d) {return update(dynamic_cast<device::Scanner3D*>(d));} template<class TPixel> unsigned int ScanStack<TPixel>::run (IDevice *d) { device::Scanner3D *s = dynamic_cast<device::Scanner3D*>(d); device::Digitizer::Config digcfg = s->_scanner2d._digitizer.get_config(); switch(digcfg.kind()) { case cfg::device::Digitizer_DigitizerType_NIScope: return run_niscope(s); break; case cfg::device::Digitizer_DigitizerType_Alazar: return run_alazar(s); break; case cfg::device::Digitizer_DigitizerType_Simulated: return run_simulated(s); break; default: warning("ScanStack<>::run() - Got invalid kind() for Digitizer.get_config"ENDL); } return 0; //failure } template<class TPixel> unsigned int ScanStack<TPixel>:: config(device::Scanner3D *d) { d->onConfigTask(); debug("Scanner3D configured for StackAcquisition<%s>"ENDL, TypeStr<TPixel> ()); return 1; //success } template<class TPixel> unsigned int ScanStack<TPixel>:: update(device::Scanner3D *scanner) { scanner->generateAO(); return 1; } template<class TPixel> unsigned int ScanStack<TPixel>::run_niscope(device::Scanner3D *d) { Chan *qdata = Chan_Open(d->_out->contents[0],CHAN_WRITE), *qwfm = Chan_Open(d->_out->contents[1],CHAN_WRITE); Frame *frm = NULL; Frame_With_Interleaved_Lines ref; struct niScope_wfmInfo *wfm = NULL; ViInt32 nwfm; ViInt32 width; int i = 0, status = 1; // status == 0 implies success, error otherwise size_t nbytes, nbytes_info; f64 z_um,ummax,ummin,umstep; TicTocTimer outer_clock = tic(), inner_clock = tic(); double dt_in = 0.0, dt_out = 0.0; device::NIScopeDigitizer *dig = d->_scanner2d._digitizer._niscope; device::NIScopeDigitizer::Config digcfg = dig->get_config(); ViSession vi = dig->_vi; ViChar *chan = const_cast<ViChar*>(digcfg.chan_names().c_str()); ref = _describe_actual_frame_niscope<TPixel>( dig, // NISCope Digitizer d->_scanner2d.get_config().nscans(), // number of scans &width, // width in pixels (queried from board) &nwfm); // this should be the number of scans (queried from board) nbytes = ref.size_bytes(); nbytes_info = nwfm * sizeof(struct niScope_wfmInfo); // Chan_Resize(qdata, nbytes); Chan_Resize(qwfm, nbytes_info); frm = (Frame*) Chan_Token_Buffer_Alloc(qdata); wfm = (struct niScope_wfmInfo*) Chan_Token_Buffer_Alloc(qwfm); nbytes = Chan_Buffer_Size_Bytes(qdata); nbytes_info = Chan_Buffer_Size_Bytes(qwfm); // ref.format(frm); d->_zpiezo.getScanRange(&ummin,&ummax,&umstep); d->_zpiezo.moveTo(ummin); // reset to starting position d->generateAORampZ((float)ummin); d->writeAO(); d->_scanner2d._shutter.Open(); CHKJMP(d->_scanner2d._daq.startAO()); for(z_um=ummin+umstep;z_um<=ummax && !d->_agent->is_stopping();z_um+=umstep) { CHKJMP(d->_scanner2d._daq.startCLK()); DIGJMP(niScope_InitiateAcquisition(vi)); dt_out = toc(&outer_clock); toc(&inner_clock); #if 1 DIGJMP(Fetch<TPixel> (vi, chan, SCANNER_STACKACQ_TASK_FETCH_TIMEOUT,//10.0, //(-1=infinite) (0.0=immediate) // seconds width, (TPixel*) frm->data, wfm)); #endif // Push the acquired data down the output pipes DBG("Task: StackAcquisition<%s>: pushing wfm"ENDL, TypeStr<TPixel> ()); Chan_Next_Try(qwfm,(void**)&wfm,nbytes_info); DBG("Task: StackAcquisition<%s>: pushing frame"ENDL, TypeStr<TPixel> ()); if(CHAN_FAILURE( SCANNER_PUSH(qdata,(void**)&frm,nbytes) )) { warning("(%s:%d) Scanner output frame queue overflowed."ENDL"\tAborting stack acquisition task."ENDL,__FILE__,__LINE__); goto Error; } ref.format(frm); dt_in = toc(&inner_clock); toc(&outer_clock); CHKJMP(d->_scanner2d._daq.waitForDone(SCANNER2D_DEFAULT_TIMEOUT)); d->_scanner2d._daq.stopCLK(); debug("Generating AO for z = %f."ENDL,z_um); d->generateAORampZ((float)z_um); d->writeAO(); ++i; } status = 0; DBG("Scanner - Stack Acquisition task completed normally."ENDL); Finalize: d->_scanner2d._shutter.Shut(); d->_zpiezo.moveTo(ummin); // reset to starting position free(frm); free(wfm); Chan_Close(qdata); Chan_Close(qwfm); niscope_debug_print_status(vi); CHKERR(d->_scanner2d._daq.stopAO()); CHKERR(d->_scanner2d._daq.stopCLK()); DIGERR(niScope_Abort(vi)); return status; Error: warning("Error occurred during ScanStack<%s> task."ENDL,TypeStr<TPixel>()); d->_scanner2d._daq.stopAO(); d->_scanner2d._daq.stopCLK(); goto Finalize; } template<class TPixel> unsigned int fetch::task::scanner::ScanStack<TPixel>::run_simulated( device::Scanner3D *d ) { Chan *qdata = Chan_Open(d->_out->contents[0],CHAN_WRITE); Frame *frm = NULL; device::SimulatedDigitizer *dig = d->_scanner2d._digitizer._simulated; Frame_With_Interleaved_Planes ref( dig->get_config().width(), d->_scanner2d.get_config().nscans()*2, 3,TypeID<TPixel>()); size_t nbytes; int status = 1; // status == 0 implies success, error otherwise f64 z_um,ummax,ummin,umstep; nbytes = ref.size_bytes(); Chan_Resize(qdata, nbytes); frm = (Frame*)Chan_Token_Buffer_Alloc(qdata); ref.format(frm); debug("Simulated Stack!"ENDL); HERE; d->_zpiezo.getScanRange(&ummin,&ummax,&umstep); for(z_um=ummin+umstep;z_um<ummax && !d->_agent->is_stopping();z_um+=umstep) //for(int d=0;d<100;++d) { size_t pitch[4]; size_t n[3]; frm->compute_pitches(pitch); frm->get_shape(n); //Fill frame w random colors. { TPixel *c,*e; const f32 low = TypeMin<TPixel>(), high = TypeMax<TPixel>(), ptp = high - low, rmx = RAND_MAX; c=e=(TPixel*)frm->data; e+=pitch[0]/pitch[3]; for(;c<e;++c) *c = (TPixel) ((ptp*rand()/(float)RAND_MAX) + low); } if(CHAN_FAILURE( SCANNER_PUSH(qdata,(void**)&frm,nbytes) )) { warning("Scanner output frame queue overflowed."ENDL"\tAborting acquisition task."ENDL); goto Error; } ref.format(frm); DBG("Task: ScanStack<%s>: pushing frame"ENDL,TypeStr<TPixel>()); } HERE; Finalize: Chan_Close(qdata); free( frm ); return status; // status == 0 implies success, error otherwise Error: warning("Error occurred during ScanStack<%s> task."ENDL,TypeStr<TPixel>()); goto Finalize; } template<class TPixel> unsigned int fetch::task::scanner::ScanStack<TPixel>::run_alazar( device::Scanner3D *d ) { Chan *qdata = Chan_Open(d->_out->contents[0],CHAN_WRITE); Chan_Close(qdata); warning("Implement me!"ENDL); return 1; } } } } <commit_msg>Fix deadlock: added transaction locks in StackAcquistion task<commit_after>/* * StackAcquisition.cpp * * Created on: May 10, 2010 * Author: Nathan Clack <clackn@janelia.hhmi.org> */ /* * Copyright 2010 Howard Hughes Medical Institute. * All rights reserved. * Use is subject to Janelia Farm Research Campus Software Copyright 1.1 * license terms (http://license.janelia.org/license/jfrc_copyright_1_1.html). */ #include "common.h" #include "StackAcquisition.h" #include "Video.h" #include "frame.h" #include "devices\digitizer.h" #include "devices\Microscope.h" #if 0 #define DBG(...) debug(__VA_ARGS__); #else #define DBG(...) #endif #define DIGWRN( expr ) (niscope_chk( vi, expr, #expr, __FILE__, __LINE__, warning )) #define DIGERR( expr ) (niscope_chk( vi, expr, #expr, __FILE__, __LINE__, error )) #define DIGJMP( expr ) goto_if_fail(VI_SUCCESS == niscope_chk( vi, expr, #expr, __FILE__, __LINE__, warning ), Error) #define DAQWRN( expr ) (Guarded_DAQmx( (expr), #expr, __FILE__, __LINE__, warning)) #define DAQERR( expr ) (Guarded_DAQmx( (expr), #expr, __FILE__, __LINE__, error )) #define DAQJMP( expr ) goto_if_fail( 0==DAQWRN(expr), Error) #define CHKERR( expr ) if(expr) {error("%s(%d)"ENDL"\tExpression indicated failure:"ENDL"\t%s"ENDL,__FILE__,__LINE__,#expr);} //( (expr), #expr, error )) #define CHKJMP( expr ) goto_if((expr),Error) #if 0 #define SCANNER_DEBUG_FAIL_WHEN_FULL #else #define SCANNER_DEBUG_WAIT_WHEN_FULL #endif #ifdef SCANNER_DEBUG_FAIL_WHEN_FULL #define SCANNER_PUSH(...) Chan_Next_Try(__VA_ARGS__) #elif defined(SCANNER_DEBUG_WAIT_WHEN_FULL) #define SCANNER_PUSH(...) Chan_Next(__VA_ARGS__) #else #error("An overflow behavior for the scanner should be specified"); #endif namespace fetch { namespace task { // // StackAcquisition - microscope task // namespace microscope { //Upcasting unsigned int StackAcquisition::config(IDevice *d) {return config(dynamic_cast<device::Microscope*>(d));} unsigned int StackAcquisition::run (IDevice *d) {return run (dynamic_cast<device::Microscope*>(d));} unsigned int StackAcquisition::config(device::Microscope *d) { static task::scanner::ScanStack<i16> grabstack; std::string filename; Guarded_Assert(d); //Assemble pipeline here IDevice *cur; cur = d->configPipeline(); CHKJMP( !d->file_series.ensurePathExists() ); d->file_series.inc(); filename = d->stack_filename(); IDevice::connect(&d->disk,0,cur,0); Guarded_Assert( d->disk.close()==0 ); //Guarded_Assert( d->disk.open(filename,"w")==0); d->__scan_agent.arm(&grabstack,&d->scanner); // why was this arm_nowait? return 1; //success Error: return 0; //failure } static int _handle_wait_for_result(DWORD result, const char *msg) { return_val_if( result == WAIT_OBJECT_0 , 0 ); return_val_if( result == WAIT_OBJECT_0+1, 1 ); Guarded_Assert_WinErr( result != WAIT_FAILED ); if(result == WAIT_ABANDONED_0) warning("StackAcquisition: Wait 0 abandoned"ENDL"\t%s"ENDL, msg); if(result == WAIT_ABANDONED_0+1) warning("StackAcquisition: Wait 1 abandoned"ENDL"\t%s"ENDL, msg); if(result == WAIT_TIMEOUT) warning("StackAcquisition: Wait timeout"ENDL"\t%s"ENDL, msg); Guarded_Assert_WinErr( result != WAIT_FAILED ); return -1; } unsigned int StackAcquisition::run(device::Microscope *dc) { std::string filename; unsigned int eflag = 0; // success Guarded_Assert(dc->__scan_agent.is_runnable()); //Guarded_Assert(dc->__io_agent.is_running()); dc->transaction_lock(); filename = dc->stack_filename(); dc->file_series.ensurePathExists(); eflag |= dc->disk.open(filename,"w"); if(eflag) return eflag; eflag |= dc->runPipeline(); eflag |= dc->__scan_agent.run() != 1; //Chan_Wait_For_Writer_Count(dc->__scan_agent._owner->_out->contents[0],1); { HANDLE hs[] = {dc->__scan_agent._thread, dc->__self_agent._notify_stop}; DWORD res; int t; // wait for scan to complete (or cancel) dc->transaction_unlock(); res = WaitForMultipleObjects(2,hs,FALSE,INFINITE); dc->transaction_lock(); t = _handle_wait_for_result(res,"StackAcquisition::run - Wait for scanner to finish."); switch(t) { case 0: // in this case, the scanner thread stopped. Nothing left to do. eflag |= 0; // success //break; case 1: // in this case, the stop event triggered and must be propagated. eflag |= dc->__scan_agent.stop(SCANNER2D_DEFAULT_TIMEOUT) != 1; break; default: // in this case, there was a timeout or abandoned wait eflag |= 1; //failure } } // Output metadata and Increment file eflag |= dc->disk.close(); dc->write_stack_metadata(); dc->file_series.inc(); //dc->connect(&dc->disk,0,dc->pipelineEnd(),0); eflag |= dc->stopPipeline(); // wait till the pipeline stops dc->transaction_unlock(); return eflag; } } // namespace microscope // // ScanStack - scanner task // namespace scanner { template class ScanStack<i8 >; template class ScanStack<i16>; // upcasts template<class TPixel> unsigned int ScanStack<TPixel>::config (IDevice *d) {return config(dynamic_cast<device::Scanner3D*>(d));} template<class TPixel> unsigned int ScanStack<TPixel>::update (IDevice *d) {return update(dynamic_cast<device::Scanner3D*>(d));} template<class TPixel> unsigned int ScanStack<TPixel>::run (IDevice *d) { device::Scanner3D *s = dynamic_cast<device::Scanner3D*>(d); device::Digitizer::Config digcfg = s->_scanner2d._digitizer.get_config(); switch(digcfg.kind()) { case cfg::device::Digitizer_DigitizerType_NIScope: return run_niscope(s); break; case cfg::device::Digitizer_DigitizerType_Alazar: return run_alazar(s); break; case cfg::device::Digitizer_DigitizerType_Simulated: return run_simulated(s); break; default: warning("ScanStack<>::run() - Got invalid kind() for Digitizer.get_config"ENDL); } return 0; //failure } template<class TPixel> unsigned int ScanStack<TPixel>:: config(device::Scanner3D *d) { d->onConfigTask(); debug("Scanner3D configured for StackAcquisition<%s>"ENDL, TypeStr<TPixel> ()); return 1; //success } template<class TPixel> unsigned int ScanStack<TPixel>:: update(device::Scanner3D *scanner) { scanner->generateAO(); return 1; } template<class TPixel> unsigned int ScanStack<TPixel>::run_niscope(device::Scanner3D *d) { Chan *qdata = Chan_Open(d->_out->contents[0],CHAN_WRITE), *qwfm = Chan_Open(d->_out->contents[1],CHAN_WRITE); Frame *frm = NULL; Frame_With_Interleaved_Lines ref; struct niScope_wfmInfo *wfm = NULL; ViInt32 nwfm; ViInt32 width; int i = 0, status = 1; // status == 0 implies success, error otherwise size_t nbytes, nbytes_info; f64 z_um,ummax,ummin,umstep; TicTocTimer outer_clock = tic(), inner_clock = tic(); double dt_in = 0.0, dt_out = 0.0; device::NIScopeDigitizer *dig = d->_scanner2d._digitizer._niscope; device::NIScopeDigitizer::Config digcfg = dig->get_config(); ViSession vi = dig->_vi; ViChar *chan = const_cast<ViChar*>(digcfg.chan_names().c_str()); ref = _describe_actual_frame_niscope<TPixel>( dig, // NISCope Digitizer d->_scanner2d.get_config().nscans(), // number of scans &width, // width in pixels (queried from board) &nwfm); // this should be the number of scans (queried from board) nbytes = ref.size_bytes(); nbytes_info = nwfm * sizeof(struct niScope_wfmInfo); // Chan_Resize(qdata, nbytes); Chan_Resize(qwfm, nbytes_info); frm = (Frame*) Chan_Token_Buffer_Alloc(qdata); wfm = (struct niScope_wfmInfo*) Chan_Token_Buffer_Alloc(qwfm); nbytes = Chan_Buffer_Size_Bytes(qdata); nbytes_info = Chan_Buffer_Size_Bytes(qwfm); // ref.format(frm); d->_zpiezo.getScanRange(&ummin,&ummax,&umstep); d->_zpiezo.moveTo(ummin); // reset to starting position d->generateAORampZ((float)ummin); d->writeAO(); d->_scanner2d._shutter.Open(); CHKJMP(d->_scanner2d._daq.startAO()); for(z_um=ummin+umstep;z_um<=ummax && !d->_agent->is_stopping();z_um+=umstep) { CHKJMP(d->_scanner2d._daq.startCLK()); DIGJMP(niScope_InitiateAcquisition(vi)); dt_out = toc(&outer_clock); toc(&inner_clock); #if 1 DIGJMP(Fetch<TPixel> (vi, chan, SCANNER_STACKACQ_TASK_FETCH_TIMEOUT,//10.0, //(-1=infinite) (0.0=immediate) // seconds width, (TPixel*) frm->data, wfm)); #endif // Push the acquired data down the output pipes DBG("Task: StackAcquisition<%s>: pushing wfm"ENDL, TypeStr<TPixel> ()); Chan_Next_Try(qwfm,(void**)&wfm,nbytes_info); DBG("Task: StackAcquisition<%s>: pushing frame"ENDL, TypeStr<TPixel> ()); if(CHAN_FAILURE( SCANNER_PUSH(qdata,(void**)&frm,nbytes) )) { warning("(%s:%d) Scanner output frame queue overflowed."ENDL"\tAborting stack acquisition task."ENDL,__FILE__,__LINE__); goto Error; } ref.format(frm); dt_in = toc(&inner_clock); toc(&outer_clock); CHKJMP(d->_scanner2d._daq.waitForDone(SCANNER2D_DEFAULT_TIMEOUT)); d->_scanner2d._daq.stopCLK(); debug("Generating AO for z = %f."ENDL,z_um); d->generateAORampZ((float)z_um); d->writeAO(); ++i; } status = 0; DBG("Scanner - Stack Acquisition task completed normally."ENDL); Finalize: d->_scanner2d._shutter.Shut(); d->_zpiezo.moveTo(ummin); // reset to starting position free(frm); free(wfm); Chan_Close(qdata); Chan_Close(qwfm); niscope_debug_print_status(vi); CHKERR(d->_scanner2d._daq.stopAO()); CHKERR(d->_scanner2d._daq.stopCLK()); DIGERR(niScope_Abort(vi)); return status; Error: warning("Error occurred during ScanStack<%s> task."ENDL,TypeStr<TPixel>()); d->_scanner2d._daq.stopAO(); d->_scanner2d._daq.stopCLK(); goto Finalize; } template<class TPixel> unsigned int fetch::task::scanner::ScanStack<TPixel>::run_simulated( device::Scanner3D *d ) { Chan *qdata = Chan_Open(d->_out->contents[0],CHAN_WRITE); Frame *frm = NULL; device::SimulatedDigitizer *dig = d->_scanner2d._digitizer._simulated; Frame_With_Interleaved_Planes ref( dig->get_config().width(), d->_scanner2d.get_config().nscans()*2, 3,TypeID<TPixel>()); size_t nbytes; int status = 1; // status == 0 implies success, error otherwise f64 z_um,ummax,ummin,umstep; nbytes = ref.size_bytes(); Chan_Resize(qdata, nbytes); frm = (Frame*)Chan_Token_Buffer_Alloc(qdata); ref.format(frm); debug("Simulated Stack!"ENDL); HERE; d->_zpiezo.getScanRange(&ummin,&ummax,&umstep); for(z_um=ummin+umstep;z_um<ummax && !d->_agent->is_stopping();z_um+=umstep) //for(int d=0;d<100;++d) { size_t pitch[4]; size_t n[3]; frm->compute_pitches(pitch); frm->get_shape(n); //Fill frame w random colors. { TPixel *c,*e; const f32 low = TypeMin<TPixel>(), high = TypeMax<TPixel>(), ptp = high - low, rmx = RAND_MAX; c=e=(TPixel*)frm->data; e+=pitch[0]/pitch[3]; for(;c<e;++c) *c = (TPixel) ((ptp*rand()/(float)RAND_MAX) + low); } if(CHAN_FAILURE( SCANNER_PUSH(qdata,(void**)&frm,nbytes) )) { warning("Scanner output frame queue overflowed."ENDL"\tAborting acquisition task."ENDL); goto Error; } ref.format(frm); DBG("Task: ScanStack<%s>: pushing frame"ENDL,TypeStr<TPixel>()); } HERE; Finalize: Chan_Close(qdata); free( frm ); return status; // status == 0 implies success, error otherwise Error: warning("Error occurred during ScanStack<%s> task."ENDL,TypeStr<TPixel>()); goto Finalize; } template<class TPixel> unsigned int fetch::task::scanner::ScanStack<TPixel>::run_alazar( device::Scanner3D *d ) { Chan *qdata = Chan_Open(d->_out->contents[0],CHAN_WRITE); Chan_Close(qdata); warning("Implement me!"ENDL); return 1; } } } } <|endoftext|>
<commit_before>#ifndef LTL_TASK_QUEUE_HPP #define LTL_TASK_QUEUE_HPP #include <functional> #include <memory> #include <type_traits> #include "ltl/future.hpp" #include "ltl/promise.hpp" #include "ltl/detail/task_queue_impl.hpp" #include "ltl/detail/current_task_context.hpp" #include "ltl/detail/wrapped_function.hpp" namespace ltl { class task_queue { public: explicit task_queue(char const* name = nullptr) : impl_(std::make_shared<detail::task_queue_impl>(name)) { } task_queue(task_queue const&) =delete; task_queue& operator=(task_queue const&) =delete; void join() { impl_->join(); } void enqueue(std::function<void()> task) { impl_->enqueue_resumable(std::move(task)); } template <typename Function> future<typename std::result_of<Function()>::type> execute(Function&& task); private: std::shared_ptr<detail::task_queue_impl> const impl_; }; template <typename Function> inline future<typename std::result_of<Function()>::type> task_queue::execute(Function&& task) { typedef typename std::result_of<Function()>::type result_type; detail::wrapped_function<result_type> wf(current_task_context::get()->get_task_queue()->shared_from_this(), std::forward<Function>(task)); impl_->enqueue_resumable(wf); return wf.promise_->get_future(); } template <typename Function, typename... Args> future<typename std::result_of<Function(Args const&...)>::type> async(task_queue& tq, Function&& f, Args const&... args) { return tq.execute([=](){ return f(args...); }); } template <typename Function> future<typename std::result_of<Function()>::type> operator <<= (task_queue& tq, Function&& f) { return async(tq, std::forward<Function>(f)); } } // namespace ltl #endif // LTL_TASK_QUEUE_HPP <commit_msg>task_queue is not moveable<commit_after>#ifndef LTL_TASK_QUEUE_HPP #define LTL_TASK_QUEUE_HPP #include <functional> #include <memory> #include <type_traits> #include "ltl/future.hpp" #include "ltl/promise.hpp" #include "ltl/detail/task_queue_impl.hpp" #include "ltl/detail/current_task_context.hpp" #include "ltl/detail/wrapped_function.hpp" namespace ltl { class task_queue { public: explicit task_queue(char const* name = nullptr) : impl_(std::make_shared<detail::task_queue_impl>(name)) { } task_queue(task_queue const&) =delete; task_queue& operator=(task_queue const&) =delete; task_queue(task_queue&& other) : impl_(std::move(other.impl_)) { } task_queue& operator=(task_queue&& other) { impl_ = std::move(other.impl_); return *this; } void join() { impl_->join(); } void enqueue(std::function<void()> task) { impl_->enqueue_resumable(std::move(task)); } template <typename Function> future<typename std::result_of<Function()>::type> execute(Function&& task); private: std::shared_ptr<detail::task_queue_impl> impl_; }; template <typename Function> inline future<typename std::result_of<Function()>::type> task_queue::execute(Function&& task) { typedef typename std::result_of<Function()>::type result_type; detail::wrapped_function<result_type> wf(current_task_context::get()->get_task_queue()->shared_from_this(), std::forward<Function>(task)); impl_->enqueue_resumable(wf); return wf.promise_->get_future(); } template <typename Function, typename... Args> future<typename std::result_of<Function(Args const&...)>::type> async(task_queue& tq, Function&& f, Args const&... args) { return tq.execute([=](){ return f(args...); }); } template <typename Function> future<typename std::result_of<Function()>::type> operator <<= (task_queue& tq, Function&& f) { return async(tq, std::forward<Function>(f)); } } // namespace ltl #endif // LTL_TASK_QUEUE_HPP <|endoftext|>
<commit_before>// __BEGIN_LICENSE__ // Copyright (c) 2009-2013, United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. All // rights reserved. // // The NGT platform is 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. // __END_LICENSE__ /// \file orbitviz.cc /// // This is as scaled-down version of orbitviz that only operates on pinhole files /************************************************************************ * File: orbitviz.cc ************************************************************************/ #include <vw/Core.h> #include <vw/Math.h> #include <vw/FileIO/KML.h> #include <vw/FileIO/FileUtils.h> #include <vw/Camera.h> #include <vw/Cartography.h> #include <iomanip> #include <boost/algorithm/string.hpp> #include <boost/program_options.hpp> #include <boost/filesystem/path.hpp> #include <boost/filesystem/operations.hpp> #include <boost/filesystem/convenience.hpp> #include <boost/filesystem/fstream.hpp> #include <asp/Core/Common.h> using namespace vw; using namespace vw::camera; using namespace vw::cartography; namespace po = boost::program_options; namespace fs = boost::filesystem; struct Options : public vw::cartography::GdalWriteOptions { Options() {} // Input std::vector<std::string> input_files; std::string path_to_outside_model; // Settings bool write_csv, hide_labels; double model_scale; ///< Size scaling applied to 3D models // Output std::string out_file; }; /// Strip the directory out of a file path std::string strip_directory( std::string const& input){ boost::filesystem::path p(input); return p.filename().string(); } /// Strip the directory and extension out of a file path std::string strip_directory_and_extension( std::string const& input){ boost::filesystem::path p(input); return p.stem().string(); } // Would be nice to have this in a function /// Populate a list of all files in a directory. /// - Returns the number of files found. /// - If an extension is passed in, files must match the extension. size_t get_files_in_folder(std::string const& folder, std::vector<std::string> & output, std::string const& ext="") { output.clear(); // Handle invalid inputs if(!boost::filesystem::exists(folder) || !boost::filesystem::is_directory(folder)) return 0; boost::filesystem::directory_iterator it(folder); boost::filesystem::directory_iterator endit; if (ext != ""){ // Check the extension while(it != endit) { if(boost::filesystem::is_regular_file(*it) && it->path().extension() == ext) output.push_back(it->path().filename().string()); ++it; } } else{ // No extension check while(it != endit) { if(boost::filesystem::is_regular_file(*it)) output.push_back(it->path().filename().string()); ++it; } } return output.size(); } void handle_arguments( int argc, char *argv[], Options& opt ) { po::options_description general_options(""); general_options.add_options() ("output,o", po::value(&opt.out_file)->default_value("orbit.kml"), "The output kml file that will be written") ("use-path-to-dae-model,u", po::value(&opt.path_to_outside_model), "Instead of using an icon to mark a camera, use a 3D model with extension .dae") ("hide-labels", po::bool_switch(&opt.hide_labels)->default_value(false)->implicit_value(true), "Hide image names unless the camera is highlighted.") // The KML class applies a model scale of 3000 * this value. ("model-scale", po::value(&opt.model_scale)->default_value(1.0/30.0), "Scale factor applied to 3D model size.") ("write-csv", po::bool_switch(&opt.write_csv)->default_value(false), "Write a csv file with the orbital data."); general_options.add( vw::cartography::GdalWriteOptionsDescription(opt) ); po::options_description positional(""); positional.add_options() ("input-files", po::value(&opt.input_files) ); po::positional_options_description positional_desc; positional_desc.add("input-files", -1); std::string usage("[options] <input cameras>\n"); bool allow_unregistered = false; std::vector<std::string> unregistered; po::variables_map vm = asp::check_command_line( argc, argv, opt, general_options, general_options, positional, positional_desc, usage, allow_unregistered, unregistered ); if (opt.input_files.empty()) vw_throw( ArgumentErr() << "No input files provided!\n" ); } int main(int argc, char* argv[]) { Options opt; //try { handle_arguments( argc, argv, opt ); size_t num_cameras = opt.input_files.size(); // Prepare output directory vw::create_out_dir(opt.out_file); // Create the KML file. KMLFile kml( opt.out_file, "orbitviz" ); // Style listing if ( opt.path_to_outside_model.empty() ) { // Placemark Style kml.append_style( "plane", "", 1.2, "http://maps.google.com/mapfiles/kml/shapes/airports.png", opt.hide_labels); kml.append_style( "plane_highlight", "", 1.4, "http://maps.google.com/mapfiles/kml/shapes/airports.png"); kml.append_stylemap( "camera_placemark", "plane", "plane_highlight" ); } // Load up the datum cartography::Datum datum("WGS84"); std::string csv_file = fs::path(opt.out_file).replace_extension("csv").string(); std::ofstream csv_handle; if ( opt.write_csv ) { csv_handle.open(csv_file.c_str()); if ( !csv_handle.is_open() ) vw_throw( IOErr() << "Unable to open output file.\n" ); } Vector2 camera_pixel(0, 0); // Building Camera Models and then writing to KML std::vector<Vector3> camera_positions(num_cameras); for (size_t i=0; i < num_cameras; i++) { // Load this input file PinholeModel current_camera(opt.input_files[i]); if ( opt.write_csv ) { csv_handle << opt.input_files[i] << ", "; Vector3 xyz = current_camera.camera_center(camera_pixel); csv_handle << std::setprecision(12); csv_handle << xyz[0] << ", " << xyz[1] << ", " << xyz[2] << "\n"; } // End csv write condition // Compute and record the GDC coordinates Vector3 lon_lat_alt = datum.cartesian_to_geodetic( current_camera.camera_center(camera_pixel)); camera_positions[i] = lon_lat_alt; // Adding Placemarks std::string display_name = strip_directory(opt.input_files[i]); if (!opt.path_to_outside_model.empty()) { kml.append_model( opt.path_to_outside_model, lon_lat_alt.x(), lon_lat_alt.y(), inverse(current_camera.camera_pose(camera_pixel)), display_name, "", lon_lat_alt[2], opt.model_scale ); } else { kml.append_placemark( lon_lat_alt.x(), lon_lat_alt.y(), display_name, "", "camera_placemark", lon_lat_alt[2], true ); } } // End loop through cameras // Put the Writing: messages here, so that they show up after all other info. vw_out() << "Writing: " << opt.out_file << std::endl; kml.close_kml(); if (opt.write_csv){ vw_out() << "Writing: " << csv_file << std::endl; csv_handle.close(); } //} ASP_STANDARD_CATCHES; return 0; } <commit_msg>Added input file option to orbitviz_pinhole<commit_after>// __BEGIN_LICENSE__ // Copyright (c) 2009-2013, United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. All // rights reserved. // // The NGT platform is 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. // __END_LICENSE__ /// \file orbitviz.cc /// // This is as scaled-down version of orbitviz that only operates on pinhole files /************************************************************************ * File: orbitviz.cc ************************************************************************/ #include <vw/Core.h> #include <vw/Math.h> #include <vw/FileIO/KML.h> #include <vw/FileIO/FileUtils.h> #include <vw/Camera.h> #include <vw/Cartography.h> #include <iomanip> #include <boost/algorithm/string.hpp> #include <boost/program_options.hpp> #include <boost/filesystem/path.hpp> #include <boost/filesystem/operations.hpp> #include <boost/filesystem/convenience.hpp> #include <boost/filesystem/fstream.hpp> #include <asp/Core/Common.h> using namespace vw; using namespace vw::camera; using namespace vw::cartography; namespace po = boost::program_options; namespace fs = boost::filesystem; struct Options : public vw::cartography::GdalWriteOptions { Options() {} // Input std::vector<std::string> input_files; std::string path_to_outside_model, input_list; // Settings bool write_csv, hide_labels; double model_scale; ///< Size scaling applied to 3D models // Output std::string out_file; }; /// Strip the directory out of a file path std::string strip_directory( std::string const& input){ boost::filesystem::path p(input); return p.filename().string(); } /// Strip the directory and extension out of a file path std::string strip_directory_and_extension( std::string const& input){ boost::filesystem::path p(input); return p.stem().string(); } // Would be nice to have this in a function /// Populate a list of all files in a directory. /// - Returns the number of files found. /// - If an extension is passed in, files must match the extension. size_t get_files_in_folder(std::string const& folder, std::vector<std::string> & output, std::string const& ext="") { output.clear(); // Handle invalid inputs if(!boost::filesystem::exists(folder) || !boost::filesystem::is_directory(folder)) return 0; boost::filesystem::directory_iterator it(folder); boost::filesystem::directory_iterator endit; if (ext != ""){ // Check the extension while(it != endit) { if(boost::filesystem::is_regular_file(*it) && it->path().extension() == ext) output.push_back(it->path().filename().string()); ++it; } } else{ // No extension check while(it != endit) { if(boost::filesystem::is_regular_file(*it)) output.push_back(it->path().filename().string()); ++it; } } return output.size(); } void handle_arguments( int argc, char *argv[], Options& opt ) { po::options_description general_options(""); general_options.add_options() ("output,o", po::value(&opt.out_file)->default_value("orbit.kml"), "The output kml file that will be written") ("input-list", po::value(&opt.input_list)->default_value(""), "File containing list of input files") ("use-path-to-dae-model,u", po::value(&opt.path_to_outside_model), "Instead of using an icon to mark a camera, use a 3D model with extension .dae") ("hide-labels", po::bool_switch(&opt.hide_labels)->default_value(false)->implicit_value(true), "Hide image names unless the camera is highlighted.") // The KML class applies a model scale of 3000 * this value. ("model-scale", po::value(&opt.model_scale)->default_value(1.0/30.0), "Scale factor applied to 3D model size.") ("write-csv", po::bool_switch(&opt.write_csv)->default_value(false), "Write a csv file with the orbital data."); general_options.add( vw::cartography::GdalWriteOptionsDescription(opt) ); po::options_description positional(""); positional.add_options() ("input-files", po::value(&opt.input_files) ); po::positional_options_description positional_desc; positional_desc.add("input-files", -1); std::string usage("[options] <input cameras>\n"); bool allow_unregistered = false; std::vector<std::string> unregistered; po::variables_map vm = asp::check_command_line( argc, argv, opt, general_options, general_options, positional, positional_desc, usage, allow_unregistered, unregistered ); if (opt.input_list != "") { std::ifstream handle(opt.input_list.c_str()); std::string line; size_t count = 0; while (getline(handle, line)){ opt.input_files.push_back(line); ++count; } handle.close(); vw_out() << "Read in " << count << " camera files from " << opt.input_list << std::endl; } if (opt.input_files.empty()) vw_throw( ArgumentErr() << "No input files provided!\n" ); } int main(int argc, char* argv[]) { Options opt; //try { handle_arguments( argc, argv, opt ); size_t num_cameras = opt.input_files.size(); // Prepare output directory vw::create_out_dir(opt.out_file); // Create the KML file. KMLFile kml( opt.out_file, "orbitviz" ); // Style listing if ( opt.path_to_outside_model.empty() ) { // Placemark Style kml.append_style( "plane", "", 1.2, "http://maps.google.com/mapfiles/kml/shapes/airports.png", opt.hide_labels); kml.append_style( "plane_highlight", "", 1.4, "http://maps.google.com/mapfiles/kml/shapes/airports.png"); kml.append_stylemap( "camera_placemark", "plane", "plane_highlight" ); } // Load up the datum cartography::Datum datum("WGS84"); std::string csv_file = fs::path(opt.out_file).replace_extension("csv").string(); std::ofstream csv_handle; if ( opt.write_csv ) { csv_handle.open(csv_file.c_str()); if ( !csv_handle.is_open() ) vw_throw( IOErr() << "Unable to open output file.\n" ); } Vector2 camera_pixel(0, 0); // Building Camera Models and then writing to KML std::vector<Vector3> camera_positions(num_cameras); for (size_t i=0; i < num_cameras; i++) { // Load this input file PinholeModel current_camera(opt.input_files[i]); if ( opt.write_csv ) { csv_handle << opt.input_files[i] << ", "; Vector3 xyz = current_camera.camera_center(camera_pixel); csv_handle << std::setprecision(12); csv_handle << xyz[0] << ", " << xyz[1] << ", " << xyz[2] << "\n"; } // End csv write condition // Compute and record the GDC coordinates Vector3 lon_lat_alt = datum.cartesian_to_geodetic( current_camera.camera_center(camera_pixel)); camera_positions[i] = lon_lat_alt; // Adding Placemarks std::string display_name = strip_directory(opt.input_files[i]); if (!opt.path_to_outside_model.empty()) { kml.append_model( opt.path_to_outside_model, lon_lat_alt.x(), lon_lat_alt.y(), inverse(current_camera.camera_pose(camera_pixel)), display_name, "", lon_lat_alt[2], opt.model_scale ); } else { kml.append_placemark( lon_lat_alt.x(), lon_lat_alt.y(), display_name, "", "camera_placemark", lon_lat_alt[2], true ); } } // End loop through cameras // Put the Writing: messages here, so that they show up after all other info. vw_out() << "Writing: " << opt.out_file << std::endl; kml.close_kml(); if (opt.write_csv){ vw_out() << "Writing: " << csv_file << std::endl; csv_handle.close(); } //} ASP_STANDARD_CATCHES; return 0; } <|endoftext|>
<commit_before>#include <StdAfx.h> #include <UI/ViewPane/SplitterPane.h> namespace viewpane { SplitterPane* SplitterPane::CreateVerticalPane(const int paneID, const UINT uidLabel) { const auto pane = CreateHorizontalPane(paneID, uidLabel); pane->m_bVertical = true; return pane; } SplitterPane* SplitterPane::CreateHorizontalPane(const int paneID, const UINT uidLabel) { const auto pane = new (std::nothrow) SplitterPane(); pane->SetLabel(uidLabel); if (uidLabel) { pane->m_bCollapsible = true; } pane->m_paneID = paneID; return pane; } int SplitterPane::GetMinWidth(_In_ HDC hdc) { (void) ViewPane::GetMinWidth(hdc); if (m_bVertical) { return max(m_PaneOne->GetMinWidth(hdc), m_PaneTwo->GetMinWidth(hdc)); } else { return m_PaneOne->GetMinWidth(hdc) + m_PaneTwo->GetMinWidth(hdc) + m_lpSplitter ? m_lpSplitter->GetSplitWidth() : 0; } } int SplitterPane::GetFixedHeight() { auto iHeight = 0; // TODO: Better way to find the top pane if (0 != m_paneID) iHeight += m_iSmallHeightMargin; // Top margin if (m_bCollapsible) { // Our expand/collapse button iHeight += m_iButtonHeight; } // A small margin between our button and the splitter control, if we're collapsible and not collapsed if (!m_bCollapsed && m_bCollapsible) { iHeight += m_iSmallHeightMargin; } if (!m_bCollapsed) { if (m_bVertical) { iHeight += m_PaneOne->GetFixedHeight() + m_PaneTwo->GetFixedHeight() + (m_lpSplitter ? m_lpSplitter->GetSplitWidth() : 0); } else { iHeight += max(m_PaneOne->GetFixedHeight(), m_PaneTwo->GetFixedHeight()); } } iHeight += m_iSmallHeightMargin; // Bottom margin return iHeight; } int SplitterPane::GetLines() { if (!m_bCollapsed) { if (m_bVertical) { return m_PaneOne->GetLines() + m_PaneTwo->GetLines(); } else { return max(m_PaneOne->GetLines(), m_PaneTwo->GetLines()); } } return 0; } ULONG SplitterPane::HandleChange(const UINT nID) { // See if the panes can handle the change first auto paneID = m_PaneOne->HandleChange(nID); if (paneID != static_cast<ULONG>(-1)) return paneID; paneID = m_PaneTwo->HandleChange(nID); if (paneID != static_cast<ULONG>(-1)) return paneID; return ViewPane::HandleChange(nID); } void SplitterPane::SetMargins( const int iMargin, const int iSideMargin, const int iLabelHeight, // Height of the label const int iSmallHeightMargin, const int iLargeHeightMargin, const int iButtonHeight, // Height of buttons below the control const int iEditHeight) // height of an edit control { ViewPane::SetMargins( iMargin, iSideMargin, iLabelHeight, iSmallHeightMargin, iLargeHeightMargin, iButtonHeight, iEditHeight); if (m_PaneOne) { m_PaneOne->SetMargins( iMargin, iSideMargin, iLabelHeight, iSmallHeightMargin, iLargeHeightMargin, iButtonHeight, iEditHeight); } if (m_PaneTwo) { m_PaneTwo->SetMargins( iMargin, iSideMargin, iLabelHeight, iSmallHeightMargin, iLargeHeightMargin, iButtonHeight, iEditHeight); } } void SplitterPane::Initialize(_In_ CWnd* pParent, _In_ HDC hdc) { ViewPane::Initialize(pParent, nullptr); m_lpSplitter = new controls::CFakeSplitter(); if (m_lpSplitter) { m_lpSplitter->Init(pParent->GetSafeHwnd()); m_lpSplitter->SetSplitType(m_bVertical ? controls::SplitVertical : controls::SplitHorizontal); m_PaneOne->Initialize(m_lpSplitter, hdc); m_PaneTwo->Initialize(m_lpSplitter, hdc); m_lpSplitter->SetPaneOne(m_PaneOne); m_lpSplitter->SetPaneTwo(m_PaneTwo); } m_bInitialized = true; } void SplitterPane::DeferWindowPos( _In_ HDWP hWinPosInfo, _In_ const int x, _In_ int y, _In_ const int width, _In_ int height) { output::DebugPrint( DBGDraw, L"SplitterPane::DeferWindowPos x:%d y:%d width:%d height: %d\n", x, y, width, height); if (0 != m_paneID) { y += m_iSmallHeightMargin; height -= m_iSmallHeightMargin; } ViewPane::DeferWindowPos(hWinPosInfo, x, y, width, height); if (m_bCollapsed) { EC_B_S(m_lpSplitter->ShowWindow(SW_HIDE)); } else { if (m_bCollapsible) { y += m_iLabelHeight + m_iSmallHeightMargin; height -= m_iLabelHeight + m_iSmallHeightMargin; } EC_B_S(m_lpSplitter->ShowWindow(SW_SHOW)); ::DeferWindowPos(hWinPosInfo, m_lpSplitter->GetSafeHwnd(), nullptr, x, y, width, height, SWP_NOZORDER); m_lpSplitter->OnSize(NULL, width, height); } } } // namespace viewpane<commit_msg>Fix bottom margins on non collapsed splitter<commit_after>#include <StdAfx.h> #include <UI/ViewPane/SplitterPane.h> namespace viewpane { SplitterPane* SplitterPane::CreateVerticalPane(const int paneID, const UINT uidLabel) { const auto pane = CreateHorizontalPane(paneID, uidLabel); pane->m_bVertical = true; return pane; } SplitterPane* SplitterPane::CreateHorizontalPane(const int paneID, const UINT uidLabel) { const auto pane = new (std::nothrow) SplitterPane(); pane->SetLabel(uidLabel); if (uidLabel) { pane->m_bCollapsible = true; } pane->m_paneID = paneID; return pane; } int SplitterPane::GetMinWidth(_In_ HDC hdc) { (void) ViewPane::GetMinWidth(hdc); if (m_bVertical) { return max(m_PaneOne->GetMinWidth(hdc), m_PaneTwo->GetMinWidth(hdc)); } else { return m_PaneOne->GetMinWidth(hdc) + m_PaneTwo->GetMinWidth(hdc) + m_lpSplitter ? m_lpSplitter->GetSplitWidth() : 0; } } int SplitterPane::GetFixedHeight() { auto iHeight = 0; // TODO: Better way to find the top pane if (0 != m_paneID) iHeight += m_iSmallHeightMargin; // Top margin if (m_bCollapsible) { // Our expand/collapse button iHeight += m_iButtonHeight; } // A small margin between our button and the splitter control, if we're collapsible and not collapsed if (!m_bCollapsed && m_bCollapsible) { iHeight += m_iSmallHeightMargin; } if (!m_bCollapsed) { if (m_bVertical) { iHeight += m_PaneOne->GetFixedHeight() + m_PaneTwo->GetFixedHeight() + (m_lpSplitter ? m_lpSplitter->GetSplitWidth() : 0); } else { iHeight += max(m_PaneOne->GetFixedHeight(), m_PaneTwo->GetFixedHeight()); } } if (m_bCollapsed) { iHeight += m_iSmallHeightMargin; // Bottom margin } return iHeight; } int SplitterPane::GetLines() { if (!m_bCollapsed) { if (m_bVertical) { return m_PaneOne->GetLines() + m_PaneTwo->GetLines(); } else { return max(m_PaneOne->GetLines(), m_PaneTwo->GetLines()); } } return 0; } ULONG SplitterPane::HandleChange(const UINT nID) { // See if the panes can handle the change first auto paneID = m_PaneOne->HandleChange(nID); if (paneID != static_cast<ULONG>(-1)) return paneID; paneID = m_PaneTwo->HandleChange(nID); if (paneID != static_cast<ULONG>(-1)) return paneID; return ViewPane::HandleChange(nID); } void SplitterPane::SetMargins( const int iMargin, const int iSideMargin, const int iLabelHeight, // Height of the label const int iSmallHeightMargin, const int iLargeHeightMargin, const int iButtonHeight, // Height of buttons below the control const int iEditHeight) // height of an edit control { ViewPane::SetMargins( iMargin, iSideMargin, iLabelHeight, iSmallHeightMargin, iLargeHeightMargin, iButtonHeight, iEditHeight); if (m_PaneOne) { m_PaneOne->SetMargins( iMargin, iSideMargin, iLabelHeight, iSmallHeightMargin, iLargeHeightMargin, iButtonHeight, iEditHeight); } if (m_PaneTwo) { m_PaneTwo->SetMargins( iMargin, iSideMargin, iLabelHeight, iSmallHeightMargin, iLargeHeightMargin, iButtonHeight, iEditHeight); } } void SplitterPane::Initialize(_In_ CWnd* pParent, _In_ HDC hdc) { ViewPane::Initialize(pParent, nullptr); m_lpSplitter = new controls::CFakeSplitter(); if (m_lpSplitter) { m_lpSplitter->Init(pParent->GetSafeHwnd()); m_lpSplitter->SetSplitType(m_bVertical ? controls::SplitVertical : controls::SplitHorizontal); m_PaneOne->Initialize(m_lpSplitter, hdc); m_PaneTwo->Initialize(m_lpSplitter, hdc); m_lpSplitter->SetPaneOne(m_PaneOne); m_lpSplitter->SetPaneTwo(m_PaneTwo); } m_bInitialized = true; } void SplitterPane::DeferWindowPos( _In_ HDWP hWinPosInfo, _In_ const int x, _In_ int y, _In_ const int width, _In_ int height) { output::DebugPrint( DBGDraw, L"SplitterPane::DeferWindowPos x:%d y:%d width:%d height: %d\n", x, y, width, height); if (0 != m_paneID) { y += m_iSmallHeightMargin; height -= m_iSmallHeightMargin; } ViewPane::DeferWindowPos(hWinPosInfo, x, y, width, height); if (m_bCollapsed) { EC_B_S(m_lpSplitter->ShowWindow(SW_HIDE)); } else { if (m_bCollapsible) { y += m_iLabelHeight + m_iSmallHeightMargin; height -= m_iLabelHeight + m_iSmallHeightMargin; } EC_B_S(m_lpSplitter->ShowWindow(SW_SHOW)); ::DeferWindowPos(hWinPosInfo, m_lpSplitter->GetSafeHwnd(), nullptr, x, y, width, height, SWP_NOZORDER); m_lpSplitter->OnSize(NULL, width, height); } } } // namespace viewpane<|endoftext|>
<commit_before>// Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "sling/file/file.h" #include <pthread.h> #include <string> #include <unordered_map> #include "sling/base/init.h" #include "sling/base/logging.h" #include "sling/base/registry.h" #include "sling/base/status.h" #include "sling/base/types.h" // Registry for file systems. REGISTER_SINGLETON_REGISTRY("file system", sling::FileSystem); namespace sling { namespace { // The file systems need to be initialized at most once. pthread_once_t file_systems_initialized = PTHREAD_ONCE_INIT; // Registered file systems. std::unordered_map<string, FileSystem *> file_systems; FileSystem *default_file_system = nullptr; // Initialize all registered file systems. void InitializeFileSystems() { auto *registry = FileSystem::registry(); for (auto *fs = registry->components; fs != nullptr; fs = fs->next()) { VLOG(2) << "Initializing " << fs->type() << " file system"; fs->object()->Init(); if (fs->object()->IsDefaultFileSystem()) { default_file_system = fs->object(); } else { file_systems[fs->type()] = fs->object(); } } } // Find file system for file name. If no matching file system is found, the // default file system is returned. FileSystem *FindFileSystem(const string &filename, string *rest) { // Match the first component in the path. if (!filename.empty() && filename[0] == '/') { int slash = filename.find('/', 1); if (slash != -1) { auto f = file_systems.find(filename.substr(1, slash - 1)); if (f != file_systems.end()) { *rest = filename.substr(slash + 1); return f->second; } } } // Fall back on the default file system. *rest = filename; return default_file_system; } Status NoFileSystem(const string &filename) { return Status(1, "No file system", filename); } } // namespace void File::Init() { // Allow this method to be called multiple times. pthread_once(&file_systems_initialized, InitializeFileSystems); } Status File::Open(const string &name, const char *mode, File **f) { // Find file system. string rest; FileSystem *fs = FindFileSystem(name, &rest); if (fs == nullptr) return NoFileSystem(name); // Open new file. return fs->Open(rest, mode, f); } File *File::Open(const string &name, const char *mode) { File *f; if (!Open(name, mode, &f).ok()) return nullptr; return f; } File *File::OpenOrDie(const string &name, const char *mode) { File *f; CHECK(Open(name, mode, &f)); return f; } File *File::TempFile() { CHECK(default_file_system != nullptr) << "No filesystems"; File *f; CHECK(default_file_system->CreateTempFile(&f)); return f; } Status File::Delete(const string &name) { // Find file system. string rest; FileSystem *fs = FindFileSystem(name, &rest); if (fs == nullptr) return NoFileSystem(name); // Delete file. return fs->DeleteFile(rest); } bool File::Exists(const string &name) { // Find file system. string rest; FileSystem *fs = FindFileSystem(name, &rest); if (fs == nullptr) return false; // Check if file exists. return fs->FileExists(rest); } Status File::GetSize(const string &name, uint64 *size) { // Find file system. string rest; FileSystem *fs = FindFileSystem(name, &rest); if (fs == nullptr) return NoFileSystem(name); // Get file size. return fs->GetFileSize(rest, size); } Status File::Stat(const string &name, FileStat *stat) { // Find file system. string rest; FileSystem *fs = FindFileSystem(name, &rest); if (fs == nullptr) return NoFileSystem(name); // Get file size. return fs->Stat(rest, stat); } Status File::Rename(const string &source, const string &target) { // Find file system. string src; string tgt; FileSystem *srcfs = FindFileSystem(source, &src); FileSystem *tgtfs = FindFileSystem(target, &tgt); if (srcfs == nullptr) return NoFileSystem(source); if (tgtfs == nullptr) return NoFileSystem(target); if (srcfs != tgtfs) return Status(1, "Cross file system rename", source); // Rename file. return srcfs->RenameFile(src, tgt); } Status File::Mkdir(const string &dir) { // Find file system. string rest; FileSystem *fs = FindFileSystem(dir, &rest); if (fs == nullptr) return NoFileSystem(dir); // Create directory. return fs->CreateDir(rest); } Status File::Rmdir(const string &dir) { // Find file system. string rest; FileSystem *fs = FindFileSystem(dir, &rest); if (fs == nullptr) return NoFileSystem(dir); // Create directory. return fs->DeleteDir(rest); } Status File::CreateLocalTempDir(string *dir) { char tmpldir[] = "/tmp/local.XXXXXX"; char *tmpname = mkdtemp(tmpldir); if (tmpname == nullptr) { return Status(errno, "mkdtemp", strerror(errno)); } *dir = tmpname; return Status::OK; } Status File::CreateGlobalTempDir(string *dir) { char tmpldir[] = "/var/data/tmp/global.XXXXXX"; char *tmpname = mkdtemp(tmpldir); if (tmpname == nullptr) { return Status(errno, "mkdtemp", strerror(errno)); } *dir = tmpname; return Status::OK; } Status File::Match(const string &pattern, std::vector<string> *filenames) { // Find file system. string rest; FileSystem *fs = FindFileSystem(pattern, &rest); if (fs == nullptr) return NoFileSystem(pattern); // Convert sharded file pattern. int at = rest.find('@'); if (at != string::npos) { string shards = rest.substr(at + 1); rest.resize(at); rest.append("-\?\?\?\?\?-of-"); rest.append(5 - shards.size(), '0'); rest.append(shards); } // Find files. return fs->Match(rest, filenames); } Status File::ReadContents(const string &filename, string *data) { // Open file for reading. File *f; Status st = Open(filename, "r", &f); if (!st.ok()) return st; // Read contents. st = f->ReadToString(data); if (!st.ok()) { f->Close(); return st; } // Close file. return f->Close(); } Status File::WriteContents(const string &filename, const void *data, size_t size) { // Open file for writing. File *f; Status st = Open(filename, "w", &f); if (!st.ok()) return st; // Write contents. st = f->Write(data, size); if (!st.ok()) { f->Close(); return st; } // Close file. return f->Close(); } size_t File::ReadOrDie(void *buffer, size_t size) { uint64 read; CHECK(Read(buffer, size, &read)); return read; } void File::WriteOrDie(const void *buffer, size_t size) { CHECK(Write(buffer, size)); } Status File::ReadToString(string *contents) { // Get current position and size. uint64 pos, size; Status st = GetPosition(&pos); if (!st.ok()) return st; st = GetSize(&size); if (!st.ok()) return st; size -= pos; // Read file data into string buffer. contents->resize(size); char *data = &(*contents)[0]; uint64 read; st = Read(data, size, &read); if (st.ok() && read < contents->size()) contents->resize(read); return st; } Status File::WriteString(const string &str) { return Write(str.data(), str.size()); } Status File::WriteLine(const string &line) { Status st = WriteString(line); if (st.ok()) st = Write("\n", 1); return st; } uint64 File::Tell() { uint64 pos; if (!GetPosition(&pos).ok()) return -1; return pos; } uint64 File::Size() { uint64 size; if (!GetSize(&size).ok()) return -1; return size; } REGISTER_INITIALIZER(filesystem, { File::Init(); }); } // namespace sling <commit_msg>Ensure that file systems are initialized (#119)<commit_after>// Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "sling/file/file.h" #include <pthread.h> #include <string> #include <unordered_map> #include "sling/base/init.h" #include "sling/base/logging.h" #include "sling/base/registry.h" #include "sling/base/status.h" #include "sling/base/types.h" // Registry for file systems. REGISTER_SINGLETON_REGISTRY("file system", sling::FileSystem); namespace sling { namespace { // The file systems need to be initialized at most once. pthread_once_t file_systems_initialized = PTHREAD_ONCE_INIT; // Registered file systems. std::unordered_map<string, FileSystem *> file_systems; FileSystem *default_file_system = nullptr; // Initialize all registered file systems. void InitializeFileSystems() { auto *registry = FileSystem::registry(); for (auto *fs = registry->components; fs != nullptr; fs = fs->next()) { VLOG(2) << "Initializing " << fs->type() << " file system"; fs->object()->Init(); if (fs->object()->IsDefaultFileSystem()) { default_file_system = fs->object(); } else { file_systems[fs->type()] = fs->object(); } } } // Find file system for file name. If no matching file system is found, the // default file system is returned. FileSystem *FindFileSystem(const string &filename, string *rest) { // Initialize file systems if not already done. if (default_file_system == nullptr) File::Init(); // Match the first component in the path. if (!filename.empty() && filename[0] == '/') { int slash = filename.find('/', 1); if (slash != -1) { auto f = file_systems.find(filename.substr(1, slash - 1)); if (f != file_systems.end()) { *rest = filename.substr(slash + 1); return f->second; } } } // Fall back on the default file system. *rest = filename; return default_file_system; } Status NoFileSystem(const string &filename) { return Status(1, "No file system", filename); } } // namespace void File::Init() { // Allow this method to be called multiple times. pthread_once(&file_systems_initialized, InitializeFileSystems); } Status File::Open(const string &name, const char *mode, File **f) { // Find file system. string rest; FileSystem *fs = FindFileSystem(name, &rest); if (fs == nullptr) return NoFileSystem(name); // Open new file. return fs->Open(rest, mode, f); } File *File::Open(const string &name, const char *mode) { File *f; if (!Open(name, mode, &f).ok()) return nullptr; return f; } File *File::OpenOrDie(const string &name, const char *mode) { File *f; CHECK(Open(name, mode, &f)); return f; } File *File::TempFile() { CHECK(default_file_system != nullptr) << "No filesystems"; File *f; CHECK(default_file_system->CreateTempFile(&f)); return f; } Status File::Delete(const string &name) { // Find file system. string rest; FileSystem *fs = FindFileSystem(name, &rest); if (fs == nullptr) return NoFileSystem(name); // Delete file. return fs->DeleteFile(rest); } bool File::Exists(const string &name) { // Find file system. string rest; FileSystem *fs = FindFileSystem(name, &rest); if (fs == nullptr) return false; // Check if file exists. return fs->FileExists(rest); } Status File::GetSize(const string &name, uint64 *size) { // Find file system. string rest; FileSystem *fs = FindFileSystem(name, &rest); if (fs == nullptr) return NoFileSystem(name); // Get file size. return fs->GetFileSize(rest, size); } Status File::Stat(const string &name, FileStat *stat) { // Find file system. string rest; FileSystem *fs = FindFileSystem(name, &rest); if (fs == nullptr) return NoFileSystem(name); // Get file size. return fs->Stat(rest, stat); } Status File::Rename(const string &source, const string &target) { // Find file system. string src; string tgt; FileSystem *srcfs = FindFileSystem(source, &src); FileSystem *tgtfs = FindFileSystem(target, &tgt); if (srcfs == nullptr) return NoFileSystem(source); if (tgtfs == nullptr) return NoFileSystem(target); if (srcfs != tgtfs) return Status(1, "Cross file system rename", source); // Rename file. return srcfs->RenameFile(src, tgt); } Status File::Mkdir(const string &dir) { // Find file system. string rest; FileSystem *fs = FindFileSystem(dir, &rest); if (fs == nullptr) return NoFileSystem(dir); // Create directory. return fs->CreateDir(rest); } Status File::Rmdir(const string &dir) { // Find file system. string rest; FileSystem *fs = FindFileSystem(dir, &rest); if (fs == nullptr) return NoFileSystem(dir); // Create directory. return fs->DeleteDir(rest); } Status File::CreateLocalTempDir(string *dir) { char tmpldir[] = "/tmp/local.XXXXXX"; char *tmpname = mkdtemp(tmpldir); if (tmpname == nullptr) { return Status(errno, "mkdtemp", strerror(errno)); } *dir = tmpname; return Status::OK; } Status File::CreateGlobalTempDir(string *dir) { char tmpldir[] = "/var/data/tmp/global.XXXXXX"; char *tmpname = mkdtemp(tmpldir); if (tmpname == nullptr) { return Status(errno, "mkdtemp", strerror(errno)); } *dir = tmpname; return Status::OK; } Status File::Match(const string &pattern, std::vector<string> *filenames) { // Find file system. string rest; FileSystem *fs = FindFileSystem(pattern, &rest); if (fs == nullptr) return NoFileSystem(pattern); // Convert sharded file pattern. int at = rest.find('@'); if (at != string::npos) { string shards = rest.substr(at + 1); rest.resize(at); rest.append("-\?\?\?\?\?-of-"); rest.append(5 - shards.size(), '0'); rest.append(shards); } // Find files. return fs->Match(rest, filenames); } Status File::ReadContents(const string &filename, string *data) { // Open file for reading. File *f; Status st = Open(filename, "r", &f); if (!st.ok()) return st; // Read contents. st = f->ReadToString(data); if (!st.ok()) { f->Close(); return st; } // Close file. return f->Close(); } Status File::WriteContents(const string &filename, const void *data, size_t size) { // Open file for writing. File *f; Status st = Open(filename, "w", &f); if (!st.ok()) return st; // Write contents. st = f->Write(data, size); if (!st.ok()) { f->Close(); return st; } // Close file. return f->Close(); } size_t File::ReadOrDie(void *buffer, size_t size) { uint64 read; CHECK(Read(buffer, size, &read)); return read; } void File::WriteOrDie(const void *buffer, size_t size) { CHECK(Write(buffer, size)); } Status File::ReadToString(string *contents) { // Get current position and size. uint64 pos, size; Status st = GetPosition(&pos); if (!st.ok()) return st; st = GetSize(&size); if (!st.ok()) return st; size -= pos; // Read file data into string buffer. contents->resize(size); char *data = &(*contents)[0]; uint64 read; st = Read(data, size, &read); if (st.ok() && read < contents->size()) contents->resize(read); return st; } Status File::WriteString(const string &str) { return Write(str.data(), str.size()); } Status File::WriteLine(const string &line) { Status st = WriteString(line); if (st.ok()) st = Write("\n", 1); return st; } uint64 File::Tell() { uint64 pos; if (!GetPosition(&pos).ok()) return -1; return pos; } uint64 File::Size() { uint64 size; if (!GetSize(&size).ok()) return -1; return size; } REGISTER_INITIALIZER(filesystem, { File::Init(); }); } // namespace sling <|endoftext|>
<commit_before>/* Highly Optimized Object-Oriented Molecular Dynamics (HOOMD) Open Source Software License Copyright (c) 2008 Ames Laboratory Iowa State University All rights reserved. Redistribution and use of HOOMD, in source and binary forms, with or without modification, are permitted, provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names HOOMD's contributors may be used to endorse or promote products derived from this software without specific prior written permission. Disclaimer THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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. */ // $Id$ // $URL$ /*! \file force_compute_bmark.cc \brief Executable for benchmarking all of the various ForceCompute classes \details This is intended as a quick test to check the performance of ForceComputes on various machines and after performance tweaks have been made. It allows for a number of command line options to change settings, but will most likely just be run with the default settings most of the time. \ingroup benchmarks */ #ifdef WIN32 #include <windows.h> #endif #include <stdlib.h> #include <iostream> #include <iomanip> #include <string> #include "BondForceCompute.h" #include "LJForceCompute.h" #include "BinnedNeighborList.h" #include "Initializers.h" #include "SFCPackUpdater.h" #ifdef USE_CUDA #include "LJForceComputeGPU.h" #include "BondForceComputeGPU.h" #endif #include "HOOMDVersion.h" #include <boost/program_options.hpp> #include <boost/shared_ptr.hpp> using namespace boost::program_options; using namespace boost; using namespace std; // options from command line //! quite mode: only display time per compute and nothing else bool quiet = false; //! number of threads (for applicable computes) unsigned int nthreads = 1; //! cutoff radius for pair forces (for applicable computes) Scalar r_cut = 3.0; //! buffer radius for pair forces (for applicable computes) Scalar r_buff = 0.8; //! block size for calculation (for applicable computes) unsigned int block_size = 128; //! number of particles to benchmark unsigned int N = 100000; //! Should the particles be sorted with SFCPACK? bool sort_particles = true; //! number of seconds to average over unsigned int nsec = 10; //! Activate profiling? bool profile_compute = true; //! Use half neighborlist? bool half_nlist = true; //! Specify packing fraction of particles for the benchmark (if applicable) Scalar phi_p = 0.2; //! Helper function to initialize bonds void init_bond_tables(shared_ptr<BondForceCompute> bf_compute) { const unsigned int nbonds = 2; for (unsigned int j = 0; j < N-nbonds/2; j++) { for (unsigned int k = 1; k <= nbonds/2; k++) bf_compute->addBond(j,j+k); } } //! Initialize the force compute from a string selecting it shared_ptr<ForceCompute> init_force_compute(const string& fc_name, shared_ptr<ParticleData> pdata, shared_ptr<NeighborList> nlist) { shared_ptr<ForceCompute> result; // handle creation of the various lennard=jones computes if (fc_name == "LJ") result = shared_ptr<ForceCompute>(new LJForceCompute(pdata, nlist, r_cut)); #ifdef USE_CUDA if (fc_name == "LJ.GPU") { shared_ptr<LJForceComputeGPU> tmp = shared_ptr<LJForceComputeGPU>(new LJForceComputeGPU(pdata, nlist, r_cut)); tmp->setBlockSize(block_size); result = tmp; } #endif // handle the various bond force computes if (fc_name == "Bond") { shared_ptr<BondForceCompute> tmp = shared_ptr<BondForceCompute>(new BondForceCompute(pdata, 150, 1.0)); init_bond_tables(tmp); result = tmp; } #ifdef USE_CUDA if (fc_name == "Bond.GPU") { shared_ptr<BondForceComputeGPU> tmp = shared_ptr<BondForceComputeGPU>(new BondForceComputeGPU(pdata, 150, 1.0)); init_bond_tables(tmp); tmp->setBlockSize(block_size); result = tmp; } #endif return result; } //! Initializes the particle data to a random set of particles shared_ptr<ParticleData> init_pdata() { RandomInitializer rand_init(N, phi_p, 0.0, "A"); shared_ptr<ParticleData> pdata(new ParticleData(rand_init)); if (sort_particles) { SFCPackUpdater sorter(pdata, Scalar(1.0)); sorter.update(0); } return pdata; } //! Actually performs the benchmark on the preconstructed force compute void benchmark(shared_ptr<ForceCompute> fc) { // initialize profiling if requested shared_ptr<Profiler> prof(new Profiler()); if (profile_compute && !quiet) fc->setProfiler(prof); // timer to count how long we spend at each point ClockSource clk; int count = 2; // do a warmup run so memory allocations don't change the benchmark numbers fc->compute(count++); int64_t tstart = clk.getTime(); int64_t tend; // do at least one test, then repeat until we get at least 5s of data at this point int nrepeat = 0; do { fc->compute(count++); nrepeat++; tend = clk.getTime(); } while((tend - tstart) < int64_t(nsec) * int64_t(1000000000) || nrepeat < 5); // make sure all kernels have been executed when using CUDA #ifdef USE_CUDA cudaThreadSynchronize(); #endif tend = clk.getTime(); if (!quiet) cout << *prof << endl; double avgTime = double(tend - tstart)/1e9/double(nrepeat);; cout << setprecision(7) << avgTime << " s/step" << endl; } //! Parses the command line and runs the benchmark int main(int argc, char **argv) { // the name of the ForceCompute to benchmark (gotten from user) string fc_name; options_description desc("Allowed options"); desc.add_options() ("help,h", "Produce help message") ("nparticles,N", value<unsigned int>(&N)->default_value(64000), "Number of particles") ("phi_p", value<Scalar>(&phi_p)->default_value(0.2), "Volume fraction of particles in test system") ("r_cut", value<Scalar>(&r_cut)->default_value(3.0), "Cutoff radius for pair force sum") ("r_buff", value<Scalar>(&r_buff)->default_value(0.8), "Buffer radius for pair force sum") ("nthreads,t", value<unsigned int>(&nthreads)->default_value(1), "Number of threads to execute (for multithreaded computes)") ("block_size", value<unsigned int>(&block_size)->default_value(128), "Block size for GPU computes") ("quiet,q", value<bool>(&quiet)->default_value(false)->zero_tokens(), "Only output time per computation") ("sort", value<bool>(&sort_particles)->default_value(true), "Sort particles with SFCPACK") ("profile", value<bool>(&profile_compute)->default_value(true), "Profile GFLOPS and GB/s sustained") ("half_nlist", value<bool>(&half_nlist)->default_value(true), "Only store 1/2 of the neighbors (optimization for some pair force computes") ("nsec", value<unsigned int>(&nsec)->default_value(10), "Number of seconds to profile for") #ifdef USE_CUDA ("fc_name,f", value<string>(&fc_name)->default_value("LJ.GPU"), "ForceCompute to benchmark") #else ("fc_name,f", value<string>(&fc_name)->default_value("LJ"), "ForceCompute to benchmark") #endif ; // parse the command line variables_map vm; try { store(parse_command_line(argc, argv, desc), vm); notify(vm); } catch (std::logic_error e) { // print help on error cerr << "Error parsing command line: " << e.what() << endl; cout << desc; cout << "Available ForceComputes are: "; cout << "LJ, LJ.Threads, Bond "; #ifdef USE_CUDA cout << "LJ.GPU, and Bond.GPU" << endl; #else cout << endl; #endif exit(1); } if (!quiet) output_version_info(false); // if help is specified, print it if (vm.count("help")) { cout << desc; exit(1); } // initialize the particle data if (!quiet) cout << "Building particle data..." << endl; shared_ptr<ParticleData> pdata = init_pdata(); // initialize the neighbor list if (!quiet) cout << "Building neighbor list data..." << endl; shared_ptr<NeighborList> nlist(new BinnedNeighborList(pdata, r_cut, r_buff)); if (half_nlist) nlist->setStorageMode(NeighborList::half); else nlist->setStorageMode(NeighborList::full); nlist->setEvery(1000000000); nlist->forceUpdate(); nlist->compute(1); // count the average number of neighbors int64_t neigh_count = 0; vector< vector< unsigned int> > list = nlist->getList(); for (unsigned int i = 0; i < N; i++) neigh_count += list[i].size(); double avgNneigh = double(neigh_count) / double(N); // initialize the force compute shared_ptr<ForceCompute> fc = init_force_compute(fc_name, pdata, nlist); if (fc == NULL) { cerr << "Unrecognized force compute: " << fc_name << endl; exit(1); } if (!quiet) { cout << "Starting benchmarking of: " << fc_name << endl; cout << "nsec = " << nsec << " / N = " << N << " / phi_p = "<< phi_p << endl; cout << "sort_particles = " << sort_particles << " / half_nlist = " << half_nlist << endl; cout << "r_cut = " << r_cut << " / r_buff = " << r_buff << " / avg_n_neigh = " << avgNneigh << endl; cout << "nthreads = " << nthreads << " / block_size = " << block_size << endl; } benchmark(fc); return 0; } <commit_msg>Added dot printing to force compute benchmark to tell if it is running or not.<commit_after>/* Highly Optimized Object-Oriented Molecular Dynamics (HOOMD) Open Source Software License Copyright (c) 2008 Ames Laboratory Iowa State University All rights reserved. Redistribution and use of HOOMD, in source and binary forms, with or without modification, are permitted, provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names HOOMD's contributors may be used to endorse or promote products derived from this software without specific prior written permission. Disclaimer THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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. */ // $Id$ // $URL$ /*! \file force_compute_bmark.cc \brief Executable for benchmarking all of the various ForceCompute classes \details This is intended as a quick test to check the performance of ForceComputes on various machines and after performance tweaks have been made. It allows for a number of command line options to change settings, but will most likely just be run with the default settings most of the time. \ingroup benchmarks */ #ifdef WIN32 #include <windows.h> #endif #include <stdlib.h> #include <iostream> #include <iomanip> #include <string> #include "BondForceCompute.h" #include "LJForceCompute.h" #include "BinnedNeighborList.h" #include "Initializers.h" #include "SFCPackUpdater.h" #ifdef USE_CUDA #include "LJForceComputeGPU.h" #include "BondForceComputeGPU.h" #endif #include "HOOMDVersion.h" #include <boost/program_options.hpp> #include <boost/shared_ptr.hpp> using namespace boost::program_options; using namespace boost; using namespace std; // options from command line //! quite mode: only display time per compute and nothing else bool quiet = false; //! number of threads (for applicable computes) unsigned int nthreads = 1; //! cutoff radius for pair forces (for applicable computes) Scalar r_cut = 3.0; //! buffer radius for pair forces (for applicable computes) Scalar r_buff = 0.8; //! block size for calculation (for applicable computes) unsigned int block_size = 128; //! number of particles to benchmark unsigned int N = 100000; //! Should the particles be sorted with SFCPACK? bool sort_particles = true; //! number of seconds to average over unsigned int nsec = 10; //! Activate profiling? bool profile_compute = true; //! Use half neighborlist? bool half_nlist = true; //! Specify packing fraction of particles for the benchmark (if applicable) Scalar phi_p = 0.2; //! Helper function to initialize bonds void init_bond_tables(shared_ptr<BondForceCompute> bf_compute) { const unsigned int nbonds = 2; for (unsigned int j = 0; j < N-nbonds/2; j++) { for (unsigned int k = 1; k <= nbonds/2; k++) bf_compute->addBond(j,j+k); } } //! Initialize the force compute from a string selecting it shared_ptr<ForceCompute> init_force_compute(const string& fc_name, shared_ptr<ParticleData> pdata, shared_ptr<NeighborList> nlist) { shared_ptr<ForceCompute> result; // handle creation of the various lennard=jones computes if (fc_name == "LJ") result = shared_ptr<ForceCompute>(new LJForceCompute(pdata, nlist, r_cut)); #ifdef USE_CUDA if (fc_name == "LJ.GPU") { shared_ptr<LJForceComputeGPU> tmp = shared_ptr<LJForceComputeGPU>(new LJForceComputeGPU(pdata, nlist, r_cut)); tmp->setBlockSize(block_size); result = tmp; } #endif // handle the various bond force computes if (fc_name == "Bond") { shared_ptr<BondForceCompute> tmp = shared_ptr<BondForceCompute>(new BondForceCompute(pdata, 150, 1.0)); init_bond_tables(tmp); result = tmp; } #ifdef USE_CUDA if (fc_name == "Bond.GPU") { shared_ptr<BondForceComputeGPU> tmp = shared_ptr<BondForceComputeGPU>(new BondForceComputeGPU(pdata, 150, 1.0)); init_bond_tables(tmp); tmp->setBlockSize(block_size); result = tmp; } #endif return result; } //! Initializes the particle data to a random set of particles shared_ptr<ParticleData> init_pdata() { RandomInitializer rand_init(N, phi_p, 0.0, "A"); shared_ptr<ParticleData> pdata(new ParticleData(rand_init)); if (sort_particles) { SFCPackUpdater sorter(pdata, Scalar(1.0)); sorter.update(0); } return pdata; } //! Actually performs the benchmark on the preconstructed force compute void benchmark(shared_ptr<ForceCompute> fc) { // initialize profiling if requested shared_ptr<Profiler> prof(new Profiler()); if (profile_compute && !quiet) fc->setProfiler(prof); // timer to count how long we spend at each point ClockSource clk; int count = 2; // do a warmup run so memory allocations don't change the benchmark numbers fc->compute(count++); int64_t tstart = clk.getTime(); int64_t tend; // do at least one test, then repeat until we get at least 5s of data at this point int nrepeat = 0; do { fc->compute(count++); nrepeat++; tend = clk.getTime(); if (nrepeat % 500 == 0) { cout << "."; cout.flush(); } } while((tend - tstart) < int64_t(nsec) * int64_t(1000000000) || nrepeat < 5); // make sure all kernels have been executed when using CUDA #ifdef USE_CUDA cudaThreadSynchronize(); #endif tend = clk.getTime(); if (!quiet) cout << *prof << endl; double avgTime = double(tend - tstart)/1e9/double(nrepeat);; cout << setprecision(7) << avgTime << " s/step" << endl; } //! Parses the command line and runs the benchmark int main(int argc, char **argv) { // the name of the ForceCompute to benchmark (gotten from user) string fc_name; options_description desc("Allowed options"); desc.add_options() ("help,h", "Produce help message") ("nparticles,N", value<unsigned int>(&N)->default_value(64000), "Number of particles") ("phi_p", value<Scalar>(&phi_p)->default_value(0.2), "Volume fraction of particles in test system") ("r_cut", value<Scalar>(&r_cut)->default_value(3.0), "Cutoff radius for pair force sum") ("r_buff", value<Scalar>(&r_buff)->default_value(0.8), "Buffer radius for pair force sum") ("nthreads,t", value<unsigned int>(&nthreads)->default_value(1), "Number of threads to execute (for multithreaded computes)") ("block_size", value<unsigned int>(&block_size)->default_value(128), "Block size for GPU computes") ("quiet,q", value<bool>(&quiet)->default_value(false)->zero_tokens(), "Only output time per computation") ("sort", value<bool>(&sort_particles)->default_value(true), "Sort particles with SFCPACK") ("profile", value<bool>(&profile_compute)->default_value(true), "Profile GFLOPS and GB/s sustained") ("half_nlist", value<bool>(&half_nlist)->default_value(true), "Only store 1/2 of the neighbors (optimization for some pair force computes") ("nsec", value<unsigned int>(&nsec)->default_value(10), "Number of seconds to profile for") #ifdef USE_CUDA ("fc_name,f", value<string>(&fc_name)->default_value("LJ.GPU"), "ForceCompute to benchmark") #else ("fc_name,f", value<string>(&fc_name)->default_value("LJ"), "ForceCompute to benchmark") #endif ; // parse the command line variables_map vm; try { store(parse_command_line(argc, argv, desc), vm); notify(vm); } catch (std::logic_error e) { // print help on error cerr << "Error parsing command line: " << e.what() << endl; cout << desc; cout << "Available ForceComputes are: "; cout << "LJ, LJ.Threads, Bond "; #ifdef USE_CUDA cout << "LJ.GPU, and Bond.GPU" << endl; #else cout << endl; #endif exit(1); } if (!quiet) output_version_info(false); // if help is specified, print it if (vm.count("help")) { cout << desc; exit(1); } // initialize the particle data if (!quiet) cout << "Building particle data..." << endl; shared_ptr<ParticleData> pdata = init_pdata(); // initialize the neighbor list if (!quiet) cout << "Building neighbor list data..." << endl; shared_ptr<NeighborList> nlist(new BinnedNeighborList(pdata, r_cut, r_buff)); if (half_nlist) nlist->setStorageMode(NeighborList::half); else nlist->setStorageMode(NeighborList::full); nlist->setEvery(1000000000); nlist->forceUpdate(); nlist->compute(1); // count the average number of neighbors int64_t neigh_count = 0; vector< vector< unsigned int> > list = nlist->getList(); for (unsigned int i = 0; i < N; i++) neigh_count += list[i].size(); double avgNneigh = double(neigh_count) / double(N); // initialize the force compute shared_ptr<ForceCompute> fc = init_force_compute(fc_name, pdata, nlist); if (fc == NULL) { cerr << "Unrecognized force compute: " << fc_name << endl; exit(1); } if (!quiet) { cout << "Starting benchmarking of: " << fc_name << endl; cout << "nsec = " << nsec << " / N = " << N << " / phi_p = "<< phi_p << endl; cout << "sort_particles = " << sort_particles << " / half_nlist = " << half_nlist << endl; cout << "r_cut = " << r_cut << " / r_buff = " << r_buff << " / avg_n_neigh = " << avgNneigh << endl; cout << "nthreads = " << nthreads << " / block_size = " << block_size << endl; } benchmark(fc); return 0; } <|endoftext|>
<commit_before> // // Cint macro to test I/O of mathcore Lorentz Vectors in a Tree and compare with a // TLorentzVector. A ROOT tree is written and read in both using either a XYZTVector or /// a TLorentzVector. // // To execute the macro type in: // // root[0]: .x mathcoreVectorIO.C #include "TRandom3.h" #include "TStopwatch.h" #include "TSystem.h" #include "TFile.h" #include "TTree.h" #include "TH1D.h" #include "TCanvas.h" #include <iostream> #include "TLorentzVector.h" #include "Math/Vector4D.h" #include "Math/Vector3D.h" #include "Math/Point3D.h" #define DEBUG //#define READONLY //#define USE_REFLEX #ifdef USE_REFLEX #include "Cintex/Cintex.h" #include "Reflex/Reflex.h" #endif #define DEFVECTOR4D(TYPE) \ typedef TYPE Vector4D; \ const std::string vector4d_type = #TYPE ; #define DEFVECTOR3D(TYPE) \ typedef TYPE Vector3D; \ const std::string vector3d_type = #TYPE ; #define DEFPOINT3D(TYPE) \ typedef TYPE Point3D; \ const std::string point3d_type = #TYPE ; //const double tol = 1.0E-16; const double tol = 1.0E-6; // or doublr 32 or float DEFVECTOR4D(ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<Double32_t> >); DEFVECTOR3D(ROOT::Math::DisplacementVector3D<ROOT::Math::Cartesian3D<Double32_t> >); DEFPOINT3D(ROOT::Math::PositionVector3D<ROOT::Math::Cartesian3D<Double32_t> >); // DEFVECTOR4D(ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<Double32_t> >) //using namespace ROOT::Math; template<class Vector> inline double getMag2(const Vector & v) { return v.mag2(); } inline double getMag2(const TVector3 & v) { return v.Mag2(); } inline double getMag2(const TLorentzVector & v) { return v.Mag2(); } template<class U> inline void setValues(ROOT::Math::DisplacementVector3D<U> & v, const double x[] ) { v.SetXYZ(x[0],x[1],x[2]); } template<class U> inline void setValues(ROOT::Math::PositionVector3D<U> & v, const double x[]) { v.SetXYZ(x[0],x[1],x[2]); } template<class U> inline void setValues(ROOT::Math::LorentzVector<U> & v, const double x[]) { v.SetXYZT(x[0],x[1],x[2],x[3]); } // specialization for T -classes inline void setValues(TVector3 & v, const double x[]) { v.SetXYZ(x[0],x[1],x[2]); } inline void setValues(TLorentzVector & v, const double x[]) { v.SetXYZT(x[0],x[1],x[2],x[3]); } template <class Vector> double testDummy(int n) { TRandom3 R(111); TStopwatch timer; Vector v1; double s = 0; double p[4]; timer.Start(); for (int i = 0; i < n; ++i) { p[0] = R.Gaus(0,10); p[1] = R.Gaus(0,10); p[2] = R.Gaus(0,10); p[3] = R.Gaus(100,10); setValues(v1,p); s += getMag2(v1); } timer.Stop(); double sav = std::sqrt(s/double(n)); std::cout << " Time for Random gen " << timer.RealTime() << " " << timer.CpuTime() << std::endl; int pr = std::cout.precision(18); std::cout << "Average : " << sav << std::endl; std::cout.precision(pr); return sav; } //---------------------------------------------------------------- /// writing //---------------------------------------------------------------- template<class Vector> double write(int n, const std::string & file_name, const std::string & vector_type, int compress = 0) { TStopwatch timer; TRandom3 R(111); std::cout << "writing a tree with " << vector_type << std::endl; std::string fname = file_name + ".root"; TFile f1(fname.c_str(),"RECREATE","",compress); // create tree std::string tree_name="Tree with" + vector_type; TTree t1("t1",tree_name.c_str()); Vector *v1 = new Vector(); std::cout << "typeID written : " << typeid(*v1).name() << std::endl; t1.Branch("Vector branch",vector_type.c_str(),&v1); timer.Start(); double p[4]; double s = 0; for (int i = 0; i < n; ++i) { p[0] = R.Gaus(0,10); p[1] = R.Gaus(0,10); p[2] = R.Gaus(0,10); p[3] = R.Gaus(100,10); //CylindricalEta4D<double> & c = v1->Coordinates(); //c.SetValues(Px,pY,pZ,E); setValues(*v1,p); t1.Fill(); s += getMag2(*v1); } f1.Write(); timer.Stop(); double sav = std::sqrt(s/double(n)); #ifdef DEBUG t1.Print(); std::cout << " Time for Writing " << file_name << "\t: " << timer.RealTime() << " " << timer.CpuTime() << std::endl; int pr = std::cout.precision(18); std::cout << "Average : " << sav << std::endl; std::cout.precision(pr); #endif return sav; } //---------------------------------------------------------------- /// reading //---------------------------------------------------------------- template<class Vector> double read(const std::string & file_name) { TStopwatch timer; std::string fname = file_name + ".root"; TFile f1(fname.c_str()); if (f1.IsZombie() ) { std::cout << " Error opening file " << file_name << std::endl; return -1; } //TFile f1("mathcoreVectorIO_D32.root"); // create tree TTree *t1 = (TTree*)f1.Get("t1"); Vector *v1 = 0; std::cout << "reading typeID : " << typeid(*v1).name() << std::endl; t1->SetBranchAddress("Vector branch",&v1); timer.Start(); int n = (int) t1->GetEntries(); std::cout << " Tree Entries " << n << std::endl; double s=0; for (int i = 0; i < n; ++i) { t1->GetEntry(i); s += getMag2(*v1); } timer.Stop(); double sav = std::sqrt(s/double(n)); #ifdef DEBUG std::cout << " Time for Reading " << file_name << "\t: " << timer.RealTime() << " " << timer.CpuTime() << std::endl; int pr = std::cout.precision(18); std::cout << "Average : " << sav << std::endl; std::cout.precision(pr); #endif return sav; } int testResult(double w1, double r1, const std::string & type) { int iret = 0; if ( fabs(w1-r1) > tol) { std::cout << "\nERROR: Differeces found when reading " << std::endl; int pr = std::cout.precision(18); std::cout << w1 << " != " << r1 << std::endl; std::cout.precision(pr); iret = -1; } std::cout << "\n*********************************************************************************************\n"; std::cout << "Test :\t " << type << "\t\t"; if (iret ==0) std::cout << "OK" << std::endl; else std::cout << "FAILED" << std::endl; std::cout << "********************************************************************************************\n\n"; return iret; } int testVectorIO() { int iret = 0; #ifdef __CINT__ gSystem->Load("libMathCore"); gSystem->Load("libPhysics"); using namespace ROOT::Math; #endif #ifdef USE_REFLEX #ifdef __CINT__ gSystem->Load("libReflex"); gSystem->Load("libCintex"); #endif ROOT::Cintex::Cintex::SetDebug(1); ROOT::Cintex::Cintex::Enable(); std::cout << "Use Reflex dictionary " << std::endl; //iret |= gSystem->Load("libSmatrixRflx"); //iret |= gSystem->Load("libMathAddRflx"); iret |= gSystem->Load("libMathRflx"); if (iret |= 0) { std::cerr <<"Failing to Load Reflex dictionaries " << std::endl; return iret; } #endif int nEvents = 100000; double w1, r1 = 0; testDummy<Vector4D>(nEvents); #ifdef READONLY w1 = 98.995527276968474; #else w1 = write<Vector4D>(nEvents,"lorentzvector",vector4d_type); #endif r1 = read<Vector4D>("lorentzvector"); iret |= testResult(w1,r1,vector4d_type); #ifdef READONLY w1 = 17.3281570633214095; #else w1 = write<Vector3D>(nEvents,"displacementvector",vector3d_type); #endif r1 = read<Vector3D>("displacementvector"); iret |= testResult(w1,r1,vector3d_type); #ifndef READONLY w1 = write<Point3D>(nEvents,"positionvector",point3d_type); #endif r1 = read<Point3D>("positionvector"); iret |= testResult(w1,r1,point3d_type); return iret; } int main() { int iret = testVectorIO(); if (iret != 0) std::cerr << "testVectorIO:\t FAILED ! " << std::endl; else std::cerr << "testVectorIO:\t OK ! " << std::endl; return iret; } <commit_msg>add test for reading file written with prev version<commit_after> // // Cint macro to test I/O of mathcore Lorentz Vectors in a Tree and compare with a // TLorentzVector. A ROOT tree is written and read in both using either a XYZTVector or /// a TLorentzVector. // // To execute the macro type in: // // root[0]: .x mathcoreVectorIO.C #include "TRandom3.h" #include "TStopwatch.h" #include "TSystem.h" #include "TFile.h" #include "TTree.h" #include "TH1D.h" #include "TCanvas.h" #include <iostream> #include "TLorentzVector.h" #include "Math/Vector4D.h" #include "Math/Vector3D.h" #include "Math/Point3D.h" #define DEBUG //#define READONLY //#define USE_REFLEX #ifdef USE_REFLEX #include "Cintex/Cintex.h" #include "Reflex/Reflex.h" #endif #define DEFVECTOR4D(TYPE) \ typedef TYPE Vector4D; \ const std::string vector4d_type = #TYPE ; #define DEFVECTOR3D(TYPE) \ typedef TYPE Vector3D; \ const std::string vector3d_type = #TYPE ; #define DEFPOINT3D(TYPE) \ typedef TYPE Point3D; \ const std::string point3d_type = #TYPE ; //const double tol = 1.0E-16; const double tol = 1.0E-6; // or doublr 32 or float DEFVECTOR4D(ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<Double32_t> >); DEFVECTOR3D(ROOT::Math::DisplacementVector3D<ROOT::Math::Cartesian3D<Double32_t> >); DEFPOINT3D(ROOT::Math::PositionVector3D<ROOT::Math::Cartesian3D<Double32_t> >); // DEFVECTOR4D(ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<Double32_t> >) //using namespace ROOT::Math; template<class Vector> inline double getMag2(const Vector & v) { return v.mag2(); } inline double getMag2(const TVector3 & v) { return v.Mag2(); } inline double getMag2(const TLorentzVector & v) { return v.Mag2(); } template<class U> inline void setValues(ROOT::Math::DisplacementVector3D<U> & v, const double x[] ) { v.SetXYZ(x[0],x[1],x[2]); } template<class U> inline void setValues(ROOT::Math::PositionVector3D<U> & v, const double x[]) { v.SetXYZ(x[0],x[1],x[2]); } template<class U> inline void setValues(ROOT::Math::LorentzVector<U> & v, const double x[]) { v.SetXYZT(x[0],x[1],x[2],x[3]); } // specialization for T -classes inline void setValues(TVector3 & v, const double x[]) { v.SetXYZ(x[0],x[1],x[2]); } inline void setValues(TLorentzVector & v, const double x[]) { v.SetXYZT(x[0],x[1],x[2],x[3]); } template <class Vector> double testDummy(int n) { TRandom3 R(111); TStopwatch timer; Vector v1; double s = 0; double p[4]; timer.Start(); for (int i = 0; i < n; ++i) { p[0] = R.Gaus(0,10); p[1] = R.Gaus(0,10); p[2] = R.Gaus(0,10); p[3] = R.Gaus(100,10); setValues(v1,p); s += getMag2(v1); } timer.Stop(); double sav = std::sqrt(s/double(n)); std::cout << " Time for Random gen " << timer.RealTime() << " " << timer.CpuTime() << std::endl; int pr = std::cout.precision(18); std::cout << "Average : " << sav << std::endl; std::cout.precision(pr); return sav; } //---------------------------------------------------------------- /// writing //---------------------------------------------------------------- template<class Vector> double write(int n, const std::string & file_name, const std::string & vector_type, int compress = 0) { TStopwatch timer; TRandom3 R(111); std::cout << "writing a tree with " << vector_type << std::endl; std::string fname = file_name + ".root"; TFile f1(fname.c_str(),"RECREATE","",compress); // create tree std::string tree_name="Tree with" + vector_type; TTree t1("t1",tree_name.c_str()); Vector *v1 = new Vector(); std::cout << "typeID written : " << typeid(*v1).name() << std::endl; t1.Branch("Vector branch",vector_type.c_str(),&v1); timer.Start(); double p[4]; double s = 0; for (int i = 0; i < n; ++i) { p[0] = R.Gaus(0,10); p[1] = R.Gaus(0,10); p[2] = R.Gaus(0,10); p[3] = R.Gaus(100,10); //CylindricalEta4D<double> & c = v1->Coordinates(); //c.SetValues(Px,pY,pZ,E); setValues(*v1,p); t1.Fill(); s += getMag2(*v1); } f1.Write(); timer.Stop(); double sav = std::sqrt(s/double(n)); #ifdef DEBUG t1.Print(); std::cout << " Time for Writing " << file_name << "\t: " << timer.RealTime() << " " << timer.CpuTime() << std::endl; int pr = std::cout.precision(18); std::cout << "Average : " << sav << std::endl; std::cout.precision(pr); #endif return sav; } //---------------------------------------------------------------- /// reading //---------------------------------------------------------------- template<class Vector> double read(const std::string & file_name) { TStopwatch timer; std::string fname = file_name + ".root"; TFile f1(fname.c_str()); if (f1.IsZombie() ) { std::cout << " Error opening file " << file_name << std::endl; return -1; } //TFile f1("mathcoreVectorIO_D32.root"); // create tree TTree *t1 = (TTree*)f1.Get("t1"); Vector *v1 = 0; std::cout << "reading typeID : " << typeid(*v1).name() << std::endl; t1->SetBranchAddress("Vector branch",&v1); timer.Start(); int n = (int) t1->GetEntries(); std::cout << " Tree Entries " << n << std::endl; double s=0; for (int i = 0; i < n; ++i) { t1->GetEntry(i); s += getMag2(*v1); } timer.Stop(); double sav = std::sqrt(s/double(n)); #ifdef DEBUG std::cout << " Time for Reading " << file_name << "\t: " << timer.RealTime() << " " << timer.CpuTime() << std::endl; int pr = std::cout.precision(18); std::cout << "Average : " << sav << std::endl; std::cout.precision(pr); #endif return sav; } int testResult(double w1, double r1, const std::string & type) { int iret = 0; if ( fabs(w1-r1) > tol) { std::cout << "\nERROR: Differeces found when reading " << std::endl; int pr = std::cout.precision(18); std::cout << w1 << " != " << r1 << std::endl; std::cout.precision(pr); iret = -1; } std::cout << "\n*********************************************************************************************\n"; std::cout << "Test :\t " << type << "\t\t"; if (iret ==0) std::cout << "OK" << std::endl; else std::cout << "FAILED" << std::endl; std::cout << "********************************************************************************************\n\n"; return iret; } int testVectorIO(bool readOnly = false) { int iret = 0; #ifdef __CINT__ gSystem->Load("libMathCore"); gSystem->Load("libPhysics"); using namespace ROOT::Math; #endif #ifdef USE_REFLEX #ifdef __CINT__ gSystem->Load("libReflex"); gSystem->Load("libCintex"); #endif ROOT::Cintex::Cintex::SetDebug(1); ROOT::Cintex::Cintex::Enable(); std::cout << "Use Reflex dictionary " << std::endl; //iret |= gSystem->Load("libSmatrixRflx"); //iret |= gSystem->Load("libMathAddRflx"); iret |= gSystem->Load("libMathRflx"); if (iret |= 0) { std::cerr <<"Failing to Load Reflex dictionaries " << std::endl; return iret; } #endif // endif on using reflex int nEvents = 100000; double w1, r1 = 0; std::string fname; testDummy<Vector4D>(nEvents); fname = "lorentzvector"; if (readOnly) { w1 = 98.995527276968474; fname += "_prev"; } else w1 = write<Vector4D>(nEvents,fname,vector4d_type); r1 = read<Vector4D>(fname); iret |= testResult(w1,r1,vector4d_type); fname = "displacementvector"; if (readOnly) { w1 = 17.3281570633214095; fname += "_prev"; } else w1 = write<Vector3D>(nEvents,fname,vector3d_type); r1 = read<Vector3D>(fname); iret |= testResult(w1,r1,vector3d_type); fname = "positionvector"; if (readOnly) fname += "_prev"; else w1 = write<Point3D>(nEvents,fname,point3d_type); r1 = read<Point3D>(fname); iret |= testResult(w1,r1,point3d_type); return iret; } int main(int argc, const char * ) { bool readOnly = false; if (argc > 1) readOnly = true; int iret = testVectorIO(readOnly); if (iret != 0) std::cerr << "testVectorIO:\t FAILED ! " << std::endl; else std::cerr << "testVectorIO:\t OK ! " << std::endl; return iret; } <|endoftext|>
<commit_before>#include <io/Socket.hpp> #include <io/ServerSocket.hpp> #include <io/StringWriter.hpp> #include <test.h> #include <unistd.h> #include <sys/wait.h> #include <cstdlib> using namespace io; using namespace std; int server(uint16_t port) { StreamServerSocket* server_sock = StreamServerSocket::createAndBindListen(port); TEST_BOOL("createBindAndListen", server_sock != NULL); LOG("%s","Server socket opened\n"); StreamSocket* sock = server_sock->accept(); StringWriter writer; writer.stealBaseIO( (BaseIO*&)sock ); writer.printf("Test%d", 0); return 0; } int client(uint16_t port) { StreamSocket* sock = new StreamSocket(); int rc = sock->connect("localhost", port); TEST_EQ_INT( "connect", rc, 0 ); char test[4096]; int size = sock->read( (byte*)test, 4096 - 1); TEST_BOOL( "read", size > 0 ); test[size]=0; TEST_EQ( "strncmp", strncmp(test, "Test0", size), 0 ) ; delete sock; return 0; } int main( int argc, char** argv ) { (void) argc; (void) argv; int rc; uint16_t port = rand() % 50000 + 5000 ; if( fork() == 0) { server(port); } else { sleep(1); TEST_FN( client(port) ); } wait( & rc ); TEST_EQ( "ServerExit", rc, 0 ); return rc; } <commit_msg>forgot srand<commit_after>#include <io/Socket.hpp> #include <io/ServerSocket.hpp> #include <io/StringWriter.hpp> #include <test.h> #include <unistd.h> #include <sys/wait.h> #include <cstdlib> using namespace io; using namespace std; int server(uint16_t port) { StreamServerSocket* server_sock = StreamServerSocket::createAndBindListen(port); TEST_BOOL("createBindAndListen", server_sock != NULL); LOG("%s","Server socket opened\n"); StreamSocket* sock = server_sock->accept(); StringWriter writer; writer.stealBaseIO( (BaseIO*&)sock ); writer.printf("Test%d", 0); return 0; } int client(uint16_t port) { StreamSocket* sock = new StreamSocket(); int rc = sock->connect("localhost", port); TEST_EQ_INT( "connect", rc, 0 ); char test[4096]; int size = sock->read( (byte*)test, 4096 - 1); TEST_BOOL( "read", size > 0 ); test[size]=0; TEST_EQ( "strncmp", strncmp(test, "Test0", size), 0 ) ; delete sock; return 0; } int main( int argc, char** argv ) { (void) argc; (void) argv; int rc; srand(time(NULL)); uint16_t port = rand() % 50000 + 5000 ; if( fork() == 0) { server(port); } else { sleep(1); TEST_FN( client(port) ); } wait( & rc ); TEST_EQ( "ServerExit", rc, 0 ); return rc; } <|endoftext|>
<commit_before>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/pacing/include/paced_sender.h" #include <assert.h> #include "webrtc/modules/interface/module_common_types.h" #include "webrtc/system_wrappers/interface/critical_section_wrapper.h" #include "webrtc/system_wrappers/interface/trace_event.h" namespace { // Time limit in milliseconds between packet bursts. const int kMinPacketLimitMs = 5; // Upper cap on process interval, in case process has not been called in a long // time. const int kMaxIntervalTimeMs = 30; // Max time that the first packet in the queue can sit in the queue if no // packets are sent, regardless of buffer state. In practice only in effect at // low bitrates (less than 320 kbits/s). const int kMaxQueueTimeWithoutSendingMs = 30; } // namespace namespace webrtc { namespace paced_sender { struct Packet { Packet(uint32_t ssrc, uint16_t seq_number, int64_t capture_time_ms, int length_in_bytes, bool retransmission) : ssrc_(ssrc), sequence_number_(seq_number), capture_time_ms_(capture_time_ms), bytes_(length_in_bytes), retransmission_(retransmission) { } uint32_t ssrc_; uint16_t sequence_number_; int64_t capture_time_ms_; int bytes_; bool retransmission_; }; // STL list style class which prevents duplicates in the list. class PacketList { public: PacketList() {}; bool empty() const { return packet_list_.empty(); } Packet front() const { return packet_list_.front(); } void pop_front() { Packet& packet = packet_list_.front(); uint16_t sequence_number = packet.sequence_number_; packet_list_.pop_front(); sequence_number_set_.erase(sequence_number); } void push_back(const Packet& packet) { if (sequence_number_set_.find(packet.sequence_number_) == sequence_number_set_.end()) { // Don't insert duplicates. packet_list_.push_back(packet); sequence_number_set_.insert(packet.sequence_number_); } } private: std::list<Packet> packet_list_; std::set<uint16_t> sequence_number_set_; }; class IntervalBudget { public: explicit IntervalBudget(int initial_target_rate_kbps) : target_rate_kbps_(initial_target_rate_kbps), bytes_remaining_(0) {} void set_target_rate_kbps(int target_rate_kbps) { target_rate_kbps_ = target_rate_kbps; } void IncreaseBudget(int delta_time_ms) { int bytes = target_rate_kbps_ * delta_time_ms / 8; if (bytes_remaining_ < 0) { // We overused last interval, compensate this interval. bytes_remaining_ = bytes_remaining_ + bytes; } else { // If we underused last interval we can't use it this interval. bytes_remaining_ = bytes; } } void UseBudget(int bytes) { bytes_remaining_ = std::max(bytes_remaining_ - bytes, -100 * target_rate_kbps_ / 8); } int bytes_remaining() const { return bytes_remaining_; } private: int target_rate_kbps_; int bytes_remaining_; }; } // namespace paced_sender PacedSender::PacedSender(Callback* callback, int target_bitrate_kbps, float pace_multiplier) : callback_(callback), pace_multiplier_(pace_multiplier), enabled_(false), paused_(false), critsect_(CriticalSectionWrapper::CreateCriticalSection()), media_budget_(new paced_sender::IntervalBudget( pace_multiplier_ * target_bitrate_kbps)), padding_budget_(new paced_sender::IntervalBudget(0)), // No padding until UpdateBitrate is called. pad_up_to_bitrate_budget_(new paced_sender::IntervalBudget(0)), time_last_update_(TickTime::Now()), capture_time_ms_last_queued_(0), capture_time_ms_last_sent_(0), high_priority_packets_(new paced_sender::PacketList), normal_priority_packets_(new paced_sender::PacketList), low_priority_packets_(new paced_sender::PacketList) { UpdateBytesPerInterval(kMinPacketLimitMs); } PacedSender::~PacedSender() { } void PacedSender::Pause() { CriticalSectionScoped cs(critsect_.get()); paused_ = true; } void PacedSender::Resume() { CriticalSectionScoped cs(critsect_.get()); paused_ = false; } void PacedSender::SetStatus(bool enable) { CriticalSectionScoped cs(critsect_.get()); enabled_ = enable; } bool PacedSender::Enabled() const { CriticalSectionScoped cs(critsect_.get()); return enabled_; } void PacedSender::UpdateBitrate(int target_bitrate_kbps, int max_padding_bitrate_kbps, int pad_up_to_bitrate_kbps) { CriticalSectionScoped cs(critsect_.get()); media_budget_->set_target_rate_kbps(pace_multiplier_ * target_bitrate_kbps); padding_budget_->set_target_rate_kbps(max_padding_bitrate_kbps); pad_up_to_bitrate_budget_->set_target_rate_kbps(pad_up_to_bitrate_kbps); } bool PacedSender::SendPacket(Priority priority, uint32_t ssrc, uint16_t sequence_number, int64_t capture_time_ms, int bytes, bool retransmission) { CriticalSectionScoped cs(critsect_.get()); if (!enabled_) { return true; // We can send now. } if (capture_time_ms < 0) { capture_time_ms = TickTime::MillisecondTimestamp(); } if (priority != kHighPriority && capture_time_ms > capture_time_ms_last_queued_) { capture_time_ms_last_queued_ = capture_time_ms; TRACE_EVENT_ASYNC_BEGIN1("webrtc_rtp", "PacedSend", capture_time_ms, "capture_time_ms", capture_time_ms); } paced_sender::PacketList* packet_list = NULL; switch (priority) { case kHighPriority: packet_list = high_priority_packets_.get(); break; case kNormalPriority: packet_list = normal_priority_packets_.get(); break; case kLowPriority: packet_list = low_priority_packets_.get(); break; } packet_list->push_back(paced_sender::Packet(ssrc, sequence_number, capture_time_ms, bytes, retransmission)); return false; } int PacedSender::QueueInMs() const { CriticalSectionScoped cs(critsect_.get()); int64_t now_ms = TickTime::MillisecondTimestamp(); int64_t oldest_packet_capture_time = now_ms; if (!high_priority_packets_->empty()) { oldest_packet_capture_time = std::min( oldest_packet_capture_time, high_priority_packets_->front().capture_time_ms_); } if (!normal_priority_packets_->empty()) { oldest_packet_capture_time = std::min( oldest_packet_capture_time, normal_priority_packets_->front().capture_time_ms_); } if (!low_priority_packets_->empty()) { oldest_packet_capture_time = std::min( oldest_packet_capture_time, low_priority_packets_->front().capture_time_ms_); } return now_ms - oldest_packet_capture_time; } int32_t PacedSender::TimeUntilNextProcess() { CriticalSectionScoped cs(critsect_.get()); int64_t elapsed_time_ms = (TickTime::Now() - time_last_update_).Milliseconds(); if (elapsed_time_ms <= 0) { return kMinPacketLimitMs; } if (elapsed_time_ms >= kMinPacketLimitMs) { return 0; } return kMinPacketLimitMs - elapsed_time_ms; } int32_t PacedSender::Process() { TickTime now = TickTime::Now(); CriticalSectionScoped cs(critsect_.get()); int elapsed_time_ms = (now - time_last_update_).Milliseconds(); time_last_update_ = now; if (!enabled_) { return 0; } if (!paused_) { if (elapsed_time_ms > 0) { uint32_t delta_time_ms = std::min(kMaxIntervalTimeMs, elapsed_time_ms); UpdateBytesPerInterval(delta_time_ms); } uint32_t ssrc; uint16_t sequence_number; int64_t capture_time_ms; bool retransmission; paced_sender::PacketList* packet_list; while (ShouldSendNextPacket(&packet_list)) { GetNextPacketFromList(packet_list, &ssrc, &sequence_number, &capture_time_ms, &retransmission); critsect_->Leave(); const bool success = callback_->TimeToSendPacket(ssrc, sequence_number, capture_time_ms, retransmission); critsect_->Enter(); // If packet cannot be sent then keep it in packet list and exit early. // There's no need to send more packets. if (!success) { return 0; } packet_list->pop_front(); const bool last_packet = packet_list->empty() || packet_list->front().capture_time_ms_ > capture_time_ms; if (packet_list != high_priority_packets_.get()) { if (capture_time_ms > capture_time_ms_last_sent_) { capture_time_ms_last_sent_ = capture_time_ms; } else if (capture_time_ms == capture_time_ms_last_sent_ && last_packet) { TRACE_EVENT_ASYNC_END0("webrtc_rtp", "PacedSend", capture_time_ms); } } } if (high_priority_packets_->empty() && normal_priority_packets_->empty() && low_priority_packets_->empty() && padding_budget_->bytes_remaining() > 0 && pad_up_to_bitrate_budget_->bytes_remaining() > 0) { int padding_needed = std::min( padding_budget_->bytes_remaining(), pad_up_to_bitrate_budget_->bytes_remaining()); critsect_->Leave(); int bytes_sent = callback_->TimeToSendPadding(padding_needed); critsect_->Enter(); media_budget_->UseBudget(bytes_sent); padding_budget_->UseBudget(bytes_sent); pad_up_to_bitrate_budget_->UseBudget(bytes_sent); } } return 0; } // MUST have critsect_ when calling. void PacedSender::UpdateBytesPerInterval(uint32_t delta_time_ms) { media_budget_->IncreaseBudget(delta_time_ms); padding_budget_->IncreaseBudget(delta_time_ms); pad_up_to_bitrate_budget_->IncreaseBudget(delta_time_ms); } // MUST have critsect_ when calling. bool PacedSender::ShouldSendNextPacket(paced_sender::PacketList** packet_list) { if (media_budget_->bytes_remaining() <= 0) { // All bytes consumed for this interval. // Check if we have not sent in a too long time. if ((TickTime::Now() - time_last_send_).Milliseconds() > kMaxQueueTimeWithoutSendingMs) { if (!high_priority_packets_->empty()) { *packet_list = high_priority_packets_.get(); return true; } if (!normal_priority_packets_->empty()) { *packet_list = normal_priority_packets_.get(); return true; } } return false; } if (!high_priority_packets_->empty()) { *packet_list = high_priority_packets_.get(); return true; } if (!normal_priority_packets_->empty()) { *packet_list = normal_priority_packets_.get(); return true; } if (!low_priority_packets_->empty()) { *packet_list = low_priority_packets_.get(); return true; } return false; } void PacedSender::GetNextPacketFromList(paced_sender::PacketList* packets, uint32_t* ssrc, uint16_t* sequence_number, int64_t* capture_time_ms, bool* retransmission) { paced_sender::Packet packet = packets->front(); UpdateMediaBytesSent(packet.bytes_); *sequence_number = packet.sequence_number_; *ssrc = packet.ssrc_; *capture_time_ms = packet.capture_time_ms_; *retransmission = packet.retransmission_; } // MUST have critsect_ when calling. void PacedSender::UpdateMediaBytesSent(int num_bytes) { time_last_send_ = TickTime::Now(); media_budget_->UseBudget(num_bytes); pad_up_to_bitrate_budget_->UseBudget(num_bytes); } } // namespace webrtc <commit_msg>Increase size of pacer window to 500 ms as that better matches the encoder.<commit_after>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/pacing/include/paced_sender.h" #include <assert.h> #include "webrtc/modules/interface/module_common_types.h" #include "webrtc/system_wrappers/interface/critical_section_wrapper.h" #include "webrtc/system_wrappers/interface/trace_event.h" namespace { // Time limit in milliseconds between packet bursts. const int kMinPacketLimitMs = 5; // Upper cap on process interval, in case process has not been called in a long // time. const int kMaxIntervalTimeMs = 30; // Max time that the first packet in the queue can sit in the queue if no // packets are sent, regardless of buffer state. In practice only in effect at // low bitrates (less than 320 kbits/s). const int kMaxQueueTimeWithoutSendingMs = 30; } // namespace namespace webrtc { namespace paced_sender { struct Packet { Packet(uint32_t ssrc, uint16_t seq_number, int64_t capture_time_ms, int length_in_bytes, bool retransmission) : ssrc_(ssrc), sequence_number_(seq_number), capture_time_ms_(capture_time_ms), bytes_(length_in_bytes), retransmission_(retransmission) { } uint32_t ssrc_; uint16_t sequence_number_; int64_t capture_time_ms_; int bytes_; bool retransmission_; }; // STL list style class which prevents duplicates in the list. class PacketList { public: PacketList() {}; bool empty() const { return packet_list_.empty(); } Packet front() const { return packet_list_.front(); } void pop_front() { Packet& packet = packet_list_.front(); uint16_t sequence_number = packet.sequence_number_; packet_list_.pop_front(); sequence_number_set_.erase(sequence_number); } void push_back(const Packet& packet) { if (sequence_number_set_.find(packet.sequence_number_) == sequence_number_set_.end()) { // Don't insert duplicates. packet_list_.push_back(packet); sequence_number_set_.insert(packet.sequence_number_); } } private: std::list<Packet> packet_list_; std::set<uint16_t> sequence_number_set_; }; class IntervalBudget { public: explicit IntervalBudget(int initial_target_rate_kbps) : target_rate_kbps_(initial_target_rate_kbps), bytes_remaining_(0) {} void set_target_rate_kbps(int target_rate_kbps) { target_rate_kbps_ = target_rate_kbps; } void IncreaseBudget(int delta_time_ms) { int bytes = target_rate_kbps_ * delta_time_ms / 8; if (bytes_remaining_ < 0) { // We overused last interval, compensate this interval. bytes_remaining_ = bytes_remaining_ + bytes; } else { // If we underused last interval we can't use it this interval. bytes_remaining_ = bytes; } } void UseBudget(int bytes) { bytes_remaining_ = std::max(bytes_remaining_ - bytes, -500 * target_rate_kbps_ / 8); } int bytes_remaining() const { return bytes_remaining_; } private: int target_rate_kbps_; int bytes_remaining_; }; } // namespace paced_sender PacedSender::PacedSender(Callback* callback, int target_bitrate_kbps, float pace_multiplier) : callback_(callback), pace_multiplier_(pace_multiplier), enabled_(false), paused_(false), critsect_(CriticalSectionWrapper::CreateCriticalSection()), media_budget_(new paced_sender::IntervalBudget( pace_multiplier_ * target_bitrate_kbps)), padding_budget_(new paced_sender::IntervalBudget(0)), // No padding until UpdateBitrate is called. pad_up_to_bitrate_budget_(new paced_sender::IntervalBudget(0)), time_last_update_(TickTime::Now()), capture_time_ms_last_queued_(0), capture_time_ms_last_sent_(0), high_priority_packets_(new paced_sender::PacketList), normal_priority_packets_(new paced_sender::PacketList), low_priority_packets_(new paced_sender::PacketList) { UpdateBytesPerInterval(kMinPacketLimitMs); } PacedSender::~PacedSender() { } void PacedSender::Pause() { CriticalSectionScoped cs(critsect_.get()); paused_ = true; } void PacedSender::Resume() { CriticalSectionScoped cs(critsect_.get()); paused_ = false; } void PacedSender::SetStatus(bool enable) { CriticalSectionScoped cs(critsect_.get()); enabled_ = enable; } bool PacedSender::Enabled() const { CriticalSectionScoped cs(critsect_.get()); return enabled_; } void PacedSender::UpdateBitrate(int target_bitrate_kbps, int max_padding_bitrate_kbps, int pad_up_to_bitrate_kbps) { CriticalSectionScoped cs(critsect_.get()); media_budget_->set_target_rate_kbps(pace_multiplier_ * target_bitrate_kbps); padding_budget_->set_target_rate_kbps(max_padding_bitrate_kbps); pad_up_to_bitrate_budget_->set_target_rate_kbps(pad_up_to_bitrate_kbps); } bool PacedSender::SendPacket(Priority priority, uint32_t ssrc, uint16_t sequence_number, int64_t capture_time_ms, int bytes, bool retransmission) { CriticalSectionScoped cs(critsect_.get()); if (!enabled_) { return true; // We can send now. } if (capture_time_ms < 0) { capture_time_ms = TickTime::MillisecondTimestamp(); } if (priority != kHighPriority && capture_time_ms > capture_time_ms_last_queued_) { capture_time_ms_last_queued_ = capture_time_ms; TRACE_EVENT_ASYNC_BEGIN1("webrtc_rtp", "PacedSend", capture_time_ms, "capture_time_ms", capture_time_ms); } paced_sender::PacketList* packet_list = NULL; switch (priority) { case kHighPriority: packet_list = high_priority_packets_.get(); break; case kNormalPriority: packet_list = normal_priority_packets_.get(); break; case kLowPriority: packet_list = low_priority_packets_.get(); break; } packet_list->push_back(paced_sender::Packet(ssrc, sequence_number, capture_time_ms, bytes, retransmission)); return false; } int PacedSender::QueueInMs() const { CriticalSectionScoped cs(critsect_.get()); int64_t now_ms = TickTime::MillisecondTimestamp(); int64_t oldest_packet_capture_time = now_ms; if (!high_priority_packets_->empty()) { oldest_packet_capture_time = std::min( oldest_packet_capture_time, high_priority_packets_->front().capture_time_ms_); } if (!normal_priority_packets_->empty()) { oldest_packet_capture_time = std::min( oldest_packet_capture_time, normal_priority_packets_->front().capture_time_ms_); } if (!low_priority_packets_->empty()) { oldest_packet_capture_time = std::min( oldest_packet_capture_time, low_priority_packets_->front().capture_time_ms_); } return now_ms - oldest_packet_capture_time; } int32_t PacedSender::TimeUntilNextProcess() { CriticalSectionScoped cs(critsect_.get()); int64_t elapsed_time_ms = (TickTime::Now() - time_last_update_).Milliseconds(); if (elapsed_time_ms <= 0) { return kMinPacketLimitMs; } if (elapsed_time_ms >= kMinPacketLimitMs) { return 0; } return kMinPacketLimitMs - elapsed_time_ms; } int32_t PacedSender::Process() { TickTime now = TickTime::Now(); CriticalSectionScoped cs(critsect_.get()); int elapsed_time_ms = (now - time_last_update_).Milliseconds(); time_last_update_ = now; if (!enabled_) { return 0; } if (!paused_) { if (elapsed_time_ms > 0) { uint32_t delta_time_ms = std::min(kMaxIntervalTimeMs, elapsed_time_ms); UpdateBytesPerInterval(delta_time_ms); } uint32_t ssrc; uint16_t sequence_number; int64_t capture_time_ms; bool retransmission; paced_sender::PacketList* packet_list; while (ShouldSendNextPacket(&packet_list)) { GetNextPacketFromList(packet_list, &ssrc, &sequence_number, &capture_time_ms, &retransmission); critsect_->Leave(); const bool success = callback_->TimeToSendPacket(ssrc, sequence_number, capture_time_ms, retransmission); critsect_->Enter(); // If packet cannot be sent then keep it in packet list and exit early. // There's no need to send more packets. if (!success) { return 0; } packet_list->pop_front(); const bool last_packet = packet_list->empty() || packet_list->front().capture_time_ms_ > capture_time_ms; if (packet_list != high_priority_packets_.get()) { if (capture_time_ms > capture_time_ms_last_sent_) { capture_time_ms_last_sent_ = capture_time_ms; } else if (capture_time_ms == capture_time_ms_last_sent_ && last_packet) { TRACE_EVENT_ASYNC_END0("webrtc_rtp", "PacedSend", capture_time_ms); } } } if (high_priority_packets_->empty() && normal_priority_packets_->empty() && low_priority_packets_->empty() && padding_budget_->bytes_remaining() > 0 && pad_up_to_bitrate_budget_->bytes_remaining() > 0) { int padding_needed = std::min( padding_budget_->bytes_remaining(), pad_up_to_bitrate_budget_->bytes_remaining()); critsect_->Leave(); int bytes_sent = callback_->TimeToSendPadding(padding_needed); critsect_->Enter(); media_budget_->UseBudget(bytes_sent); padding_budget_->UseBudget(bytes_sent); pad_up_to_bitrate_budget_->UseBudget(bytes_sent); } } return 0; } // MUST have critsect_ when calling. void PacedSender::UpdateBytesPerInterval(uint32_t delta_time_ms) { media_budget_->IncreaseBudget(delta_time_ms); padding_budget_->IncreaseBudget(delta_time_ms); pad_up_to_bitrate_budget_->IncreaseBudget(delta_time_ms); } // MUST have critsect_ when calling. bool PacedSender::ShouldSendNextPacket(paced_sender::PacketList** packet_list) { if (media_budget_->bytes_remaining() <= 0) { // All bytes consumed for this interval. // Check if we have not sent in a too long time. if ((TickTime::Now() - time_last_send_).Milliseconds() > kMaxQueueTimeWithoutSendingMs) { if (!high_priority_packets_->empty()) { *packet_list = high_priority_packets_.get(); return true; } if (!normal_priority_packets_->empty()) { *packet_list = normal_priority_packets_.get(); return true; } } return false; } if (!high_priority_packets_->empty()) { *packet_list = high_priority_packets_.get(); return true; } if (!normal_priority_packets_->empty()) { *packet_list = normal_priority_packets_.get(); return true; } if (!low_priority_packets_->empty()) { *packet_list = low_priority_packets_.get(); return true; } return false; } void PacedSender::GetNextPacketFromList(paced_sender::PacketList* packets, uint32_t* ssrc, uint16_t* sequence_number, int64_t* capture_time_ms, bool* retransmission) { paced_sender::Packet packet = packets->front(); UpdateMediaBytesSent(packet.bytes_); *sequence_number = packet.sequence_number_; *ssrc = packet.ssrc_; *capture_time_ms = packet.capture_time_ms_; *retransmission = packet.retransmission_; } // MUST have critsect_ when calling. void PacedSender::UpdateMediaBytesSent(int num_bytes) { time_last_send_ = TickTime::Now(); media_budget_->UseBudget(num_bytes); pad_up_to_bitrate_budget_->UseBudget(num_bytes); } } // namespace webrtc <|endoftext|>
<commit_before>/** * This file is part of the "libfnord" project * Copyright (c) 2015 Paul Asmuth * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. You should have received a * copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ #include <thread> #include <stx/util/Base64.h> #include <stx/fnv.h> #include <stx/protobuf/msg.h> #include <stx/io/fileutil.h> #include <sstable/sstablereader.h> #include <zbase/core/PartitionMap.h> #include <zbase/core/PartitionState.pb.h> #include <zbase/core/PartitionReplication.h> using namespace stx; namespace zbase { static mdb::MDBOptions tsdb_mdb_opts() { mdb::MDBOptions opts; opts.data_filename = "index.db"; opts.lock_filename = "index.db.lck"; return opts; }; PartitionMap::PartitionMap( const String& db_path, RefPtr<ReplicationScheme> repl_scheme) : db_path_(db_path), db_(mdb::MDB::open(db_path, tsdb_mdb_opts())), repl_scheme_(repl_scheme) {} Option<RefPtr<Table>> PartitionMap::findTable( const String& stream_ns, const String& table_name) const { std::unique_lock<std::mutex> lk(mutex_); return findTableWithLock(stream_ns, table_name); } Option<RefPtr<Table>> PartitionMap::findTableWithLock( const String& stream_ns, const String& table_name) const { auto stream_ns_key = stream_ns + "~" + table_name; const auto& iter = tables_.find(stream_ns_key); if (iter == tables_.end()) { return None<RefPtr<Table>>(); } else { return Some(iter->second); } } void PartitionMap::configureTable(const TableDefinition& table) { std::unique_lock<std::mutex> lk(mutex_); auto tbl_key = table.customer() + "~" + table.table_name(); auto iter = tables_.find(tbl_key); if (iter == tables_.end()) { tables_.emplace(tbl_key, new Table(table)); } else { iter->second->updateConfig(table); } } void PartitionMap::open() { auto txn = db_->startTransaction(false); auto cursor = txn->getCursor(); Vector<PartitionKey> partitions; for (int i = 0; ; ++i) { Buffer key; Buffer value; if (i == 0) { if (!cursor->getFirst(&key, &value)) { break; } } else { if (!cursor->getNext(&key, &value)) { break; } } auto db_key = key.toString(); if (db_key.size() == 0) { continue; } if (db_key[0] == 0x1b) { continue; } auto tsdb_namespace_off = StringUtil::find(db_key, '~'); if (tsdb_namespace_off == String::npos) { RAISEF(kRuntimeError, "invalid partition key: $0", db_key); } auto tsdb_namespace = db_key.substr(0, tsdb_namespace_off); SHA1Hash partition_key( db_key.data() + tsdb_namespace_off + 1, db_key.size() - tsdb_namespace_off - 1); auto table_key = value.toString(); auto table = findTableWithLock(tsdb_namespace, table_key); partitions_.emplace(db_key, mkScoped(new LazyPartition())); if (table.isEmpty()) { logWarning( "tsdb", "Orphaned partition: $0/$1", table_key, partition_key.toString()); continue; } partitions.emplace_back( std::make_tuple(tsdb_namespace, table_key, partition_key)); } cursor->close(); txn->abort(); auto background_load_thread = std::thread( std::bind(&PartitionMap::loadPartitions, this, partitions)); background_load_thread.detach(); } void PartitionMap::loadPartitions(const Vector<PartitionKey>& partitions) { for (const auto& p : partitions) { try { findPartition(std::get<0>(p), std::get<1>(p), std::get<2>(p)); } catch (const StandardException& e) { logError( "tsdb", e, "error while loading partition $0/$1/$2", std::get<0>(p), std::get<1>(p), std::get<2>(p).toString()); } } } RefPtr<Partition> PartitionMap::findOrCreatePartition( const String& tsdb_namespace, const String& table_name, const SHA1Hash& partition_key) { auto db_key = tsdb_namespace + "~"; db_key.append((char*) partition_key.data(), partition_key.size()); std::unique_lock<std::mutex> lk(mutex_); auto iter = partitions_.find(db_key); if (iter != partitions_.end()) { if (iter->second->isLoaded()) { return iter->second->getPartition(); } } auto table = findTableWithLock(tsdb_namespace, table_name); if (table.isEmpty()) { RAISEF(kNotFoundError, "table not found: $0", table_name); } if (iter != partitions_.end()) { auto partition = iter->second.get(); lk.unlock(); return partition->getPartition( tsdb_namespace, table.get(), partition_key, db_path_, this); } auto partition = Partition::create( tsdb_namespace, table.get(), partition_key, db_path_); partitions_.emplace(db_key, mkScoped(new LazyPartition(partition))); auto txn = db_->startTransaction(false); txn->update( db_key.data(), db_key.size(), table_name.data(), table_name.size()); txn->commit(); lk.unlock(); auto change = mkRef(new PartitionChangeNotification()); change->partition = partition; publishPartitionChange(change); return partition; } Option<RefPtr<Partition>> PartitionMap::findPartition( const String& tsdb_namespace, const String& table_name, const SHA1Hash& partition_key) { auto db_key = tsdb_namespace + "~"; db_key.append((char*) partition_key.data(), partition_key.size()); std::unique_lock<std::mutex> lk(mutex_); auto iter = partitions_.find(db_key); if (iter == partitions_.end()) { return None<RefPtr<Partition>>(); } else { if (iter->second->isLoaded()) { return Some(iter->second->getPartition()); } auto table = findTableWithLock(tsdb_namespace, table_name); if (table.isEmpty()) { RAISEF(kNotFoundError, "table not found: $0", table_name); } auto partition = iter->second.get(); lk.unlock(); return Some( partition->getPartition( tsdb_namespace, table.get(), partition_key, db_path_, this)); } } void PartitionMap::listTables( const String& tsdb_namespace, Function<void (const TSDBTableInfo& table)> fn) const { for (const auto& tbl : tables_) { if (tbl.second->tsdbNamespace() != tsdb_namespace) { continue; } TSDBTableInfo ti; ti.table_name = tbl.second->name(); ti.config = tbl.second->config(); ti.schema = tbl.second->schema(); fn(ti); } } bool PartitionMap::dropLocalPartition( const String& tsdb_namespace, const String& table_name, const SHA1Hash& partition_key) { auto partition_opt = findPartition(tsdb_namespace, table_name, partition_key); if (partition_opt.isEmpty()) { RAISE(kNotFoundError, "partition not found"); } auto partition = partition_opt.get(); auto partition_writer = partition->getWriter(); /* lock partition */ partition_writer->lock(); /* check preconditions */ size_t full_copies = 0; try { full_copies = partition ->getReplicationStrategy(repl_scheme_, nullptr) ->numFullRemoteCopies(); if (repl_scheme_->hasLocalReplica(partition_key) || full_copies < repl_scheme_->minNumCopies()) { RAISE(kIllegalStateError, "can't delete partition"); } } catch (const StandardException& e) { /* unlock partition and bail */ partition_writer->unlock(); return false; } /* start deletion */ logInfo( "z1.core", "Partition $0/$1/$2 is not owned by this node and has $3 other " \ "full copies, trying to unload and drop", tsdb_namespace, table_name, partition_key.toString(), full_copies); /* freeze partition and unlock waiting writers (they will fail) */ partition_writer->freeze(); partition_writer->unlock(); auto db_key = tsdb_namespace + "~"; db_key.append((char*) partition_key.data(), partition_key.size()); /* grab the main lock */ std::unique_lock<std::mutex> lk(mutex_); /* delete from in memory partition map */ auto iter = partitions_.find(db_key); if (iter == partitions_.end()) { /* somebody else already deleted this partition */ return true; } else { partitions_.erase(iter); } /* delete from on disk partition map */ auto txn = db_->startTransaction(false); txn->del(db_key); txn->commit(); /* delete partition data from disk (move to trash) */ { auto src_path = FileUtil::joinPaths( db_path_, StringUtil::format( "$0/$1/$2", tsdb_namespace, SHA1::compute(table_name).toString(), partition_key.toString())); auto dst_path = FileUtil::joinPaths( db_path_, StringUtil::format( "../trash/$0~$1~$2~$3", tsdb_namespace, SHA1::compute(table_name).toString(), partition_key.toString(), Random::singleton()->hex64())); FileUtil::mv(src_path, dst_path); } return true; } Option<TSDBTableInfo> PartitionMap::tableInfo( const String& tsdb_namespace, const String& table_key) const { auto table = findTable(tsdb_namespace, table_key); if (table.isEmpty()) { return None<TSDBTableInfo>(); } TSDBTableInfo ti; ti.table_name = table.get()->name(); ti.config = table.get()->config(); ti.schema = table.get()->schema(); return Some(ti); } void PartitionMap::subscribeToPartitionChanges(PartitionChangeCallbackFn fn) { callbacks_.emplace_back(fn); } void PartitionMap::publishPartitionChange( RefPtr<PartitionChangeNotification> change) { for (const auto& cb : callbacks_) { cb(change); } } } // namespace tdsb <commit_msg>dry run...<commit_after>/** * This file is part of the "libfnord" project * Copyright (c) 2015 Paul Asmuth * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. You should have received a * copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ #include <thread> #include <stx/util/Base64.h> #include <stx/fnv.h> #include <stx/protobuf/msg.h> #include <stx/io/fileutil.h> #include <sstable/sstablereader.h> #include <zbase/core/PartitionMap.h> #include <zbase/core/PartitionState.pb.h> #include <zbase/core/PartitionReplication.h> using namespace stx; namespace zbase { static mdb::MDBOptions tsdb_mdb_opts() { mdb::MDBOptions opts; opts.data_filename = "index.db"; opts.lock_filename = "index.db.lck"; return opts; }; PartitionMap::PartitionMap( const String& db_path, RefPtr<ReplicationScheme> repl_scheme) : db_path_(db_path), db_(mdb::MDB::open(db_path, tsdb_mdb_opts())), repl_scheme_(repl_scheme) {} Option<RefPtr<Table>> PartitionMap::findTable( const String& stream_ns, const String& table_name) const { std::unique_lock<std::mutex> lk(mutex_); return findTableWithLock(stream_ns, table_name); } Option<RefPtr<Table>> PartitionMap::findTableWithLock( const String& stream_ns, const String& table_name) const { auto stream_ns_key = stream_ns + "~" + table_name; const auto& iter = tables_.find(stream_ns_key); if (iter == tables_.end()) { return None<RefPtr<Table>>(); } else { return Some(iter->second); } } void PartitionMap::configureTable(const TableDefinition& table) { std::unique_lock<std::mutex> lk(mutex_); auto tbl_key = table.customer() + "~" + table.table_name(); auto iter = tables_.find(tbl_key); if (iter == tables_.end()) { tables_.emplace(tbl_key, new Table(table)); } else { iter->second->updateConfig(table); } } void PartitionMap::open() { auto txn = db_->startTransaction(false); auto cursor = txn->getCursor(); Vector<PartitionKey> partitions; for (int i = 0; ; ++i) { Buffer key; Buffer value; if (i == 0) { if (!cursor->getFirst(&key, &value)) { break; } } else { if (!cursor->getNext(&key, &value)) { break; } } auto db_key = key.toString(); if (db_key.size() == 0) { continue; } if (db_key[0] == 0x1b) { continue; } auto tsdb_namespace_off = StringUtil::find(db_key, '~'); if (tsdb_namespace_off == String::npos) { RAISEF(kRuntimeError, "invalid partition key: $0", db_key); } auto tsdb_namespace = db_key.substr(0, tsdb_namespace_off); SHA1Hash partition_key( db_key.data() + tsdb_namespace_off + 1, db_key.size() - tsdb_namespace_off - 1); auto table_key = value.toString(); auto table = findTableWithLock(tsdb_namespace, table_key); partitions_.emplace(db_key, mkScoped(new LazyPartition())); if (table.isEmpty()) { logWarning( "tsdb", "Orphaned partition: $0/$1", table_key, partition_key.toString()); continue; } partitions.emplace_back( std::make_tuple(tsdb_namespace, table_key, partition_key)); } cursor->close(); txn->abort(); auto background_load_thread = std::thread( std::bind(&PartitionMap::loadPartitions, this, partitions)); background_load_thread.detach(); } void PartitionMap::loadPartitions(const Vector<PartitionKey>& partitions) { for (const auto& p : partitions) { try { findPartition(std::get<0>(p), std::get<1>(p), std::get<2>(p)); } catch (const StandardException& e) { logError( "tsdb", e, "error while loading partition $0/$1/$2", std::get<0>(p), std::get<1>(p), std::get<2>(p).toString()); } } } RefPtr<Partition> PartitionMap::findOrCreatePartition( const String& tsdb_namespace, const String& table_name, const SHA1Hash& partition_key) { auto db_key = tsdb_namespace + "~"; db_key.append((char*) partition_key.data(), partition_key.size()); std::unique_lock<std::mutex> lk(mutex_); auto iter = partitions_.find(db_key); if (iter != partitions_.end()) { if (iter->second->isLoaded()) { return iter->second->getPartition(); } } auto table = findTableWithLock(tsdb_namespace, table_name); if (table.isEmpty()) { RAISEF(kNotFoundError, "table not found: $0", table_name); } if (iter != partitions_.end()) { auto partition = iter->second.get(); lk.unlock(); return partition->getPartition( tsdb_namespace, table.get(), partition_key, db_path_, this); } auto partition = Partition::create( tsdb_namespace, table.get(), partition_key, db_path_); partitions_.emplace(db_key, mkScoped(new LazyPartition(partition))); auto txn = db_->startTransaction(false); txn->update( db_key.data(), db_key.size(), table_name.data(), table_name.size()); txn->commit(); lk.unlock(); auto change = mkRef(new PartitionChangeNotification()); change->partition = partition; publishPartitionChange(change); return partition; } Option<RefPtr<Partition>> PartitionMap::findPartition( const String& tsdb_namespace, const String& table_name, const SHA1Hash& partition_key) { auto db_key = tsdb_namespace + "~"; db_key.append((char*) partition_key.data(), partition_key.size()); std::unique_lock<std::mutex> lk(mutex_); auto iter = partitions_.find(db_key); if (iter == partitions_.end()) { return None<RefPtr<Partition>>(); } else { if (iter->second->isLoaded()) { return Some(iter->second->getPartition()); } auto table = findTableWithLock(tsdb_namespace, table_name); if (table.isEmpty()) { RAISEF(kNotFoundError, "table not found: $0", table_name); } auto partition = iter->second.get(); lk.unlock(); return Some( partition->getPartition( tsdb_namespace, table.get(), partition_key, db_path_, this)); } } void PartitionMap::listTables( const String& tsdb_namespace, Function<void (const TSDBTableInfo& table)> fn) const { for (const auto& tbl : tables_) { if (tbl.second->tsdbNamespace() != tsdb_namespace) { continue; } TSDBTableInfo ti; ti.table_name = tbl.second->name(); ti.config = tbl.second->config(); ti.schema = tbl.second->schema(); fn(ti); } } bool PartitionMap::dropLocalPartition( const String& tsdb_namespace, const String& table_name, const SHA1Hash& partition_key) { auto partition_opt = findPartition(tsdb_namespace, table_name, partition_key); if (partition_opt.isEmpty()) { RAISE(kNotFoundError, "partition not found"); } auto partition = partition_opt.get(); auto partition_writer = partition->getWriter(); /* lock partition */ partition_writer->lock(); /* check preconditions */ size_t full_copies = 0; try { full_copies = partition ->getReplicationStrategy(repl_scheme_, nullptr) ->numFullRemoteCopies(); if (repl_scheme_->hasLocalReplica(partition_key) || full_copies < repl_scheme_->minNumCopies()) { RAISE(kIllegalStateError, "can't delete partition"); } } catch (const StandardException& e) { /* unlock partition and bail */ partition_writer->unlock(); return false; } /* start deletion */ logInfo( "z1.core", "Partition $0/$1/$2 is not owned by this node and has $3 other " \ "full copies, trying to unload and drop", tsdb_namespace, table_name, partition_key.toString(), full_copies); /* freeze partition and unlock waiting writers (they will fail) */ partition_writer->freeze(); partition_writer->unlock(); /// BAIL FOR DRY RUN return true; /// EOF DRY RUN auto db_key = tsdb_namespace + "~"; db_key.append((char*) partition_key.data(), partition_key.size()); /* grab the main lock */ std::unique_lock<std::mutex> lk(mutex_); /* delete from in memory partition map */ auto iter = partitions_.find(db_key); if (iter == partitions_.end()) { /* somebody else already deleted this partition */ return true; } else { partitions_.erase(iter); } /* delete from on disk partition map */ auto txn = db_->startTransaction(false); txn->del(db_key); txn->commit(); /* delete partition data from disk (move to trash) */ { auto src_path = FileUtil::joinPaths( db_path_, StringUtil::format( "$0/$1/$2", tsdb_namespace, SHA1::compute(table_name).toString(), partition_key.toString())); auto dst_path = FileUtil::joinPaths( db_path_, StringUtil::format( "../trash/$0~$1~$2~$3", tsdb_namespace, SHA1::compute(table_name).toString(), partition_key.toString(), Random::singleton()->hex64())); FileUtil::mv(src_path, dst_path); } return true; } Option<TSDBTableInfo> PartitionMap::tableInfo( const String& tsdb_namespace, const String& table_key) const { auto table = findTable(tsdb_namespace, table_key); if (table.isEmpty()) { return None<TSDBTableInfo>(); } TSDBTableInfo ti; ti.table_name = table.get()->name(); ti.config = table.get()->config(); ti.schema = table.get()->schema(); return Some(ti); } void PartitionMap::subscribeToPartitionChanges(PartitionChangeCallbackFn fn) { callbacks_.emplace_back(fn); } void PartitionMap::publishPartitionChange( RefPtr<PartitionChangeNotification> change) { for (const auto& cb : callbacks_) { cb(change); } } } // namespace tdsb <|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 EthashAux.cpp * @author Gav Wood <i@gavwood.com> * @date 2014 */ #include "EthashAux.h" #include <boost/detail/endian.hpp> #include <boost/filesystem.hpp> #include <chrono> #include <array> #include <random> #include <thread> #include <libdevcore/Common.h> #include <libdevcore/Guards.h> #include <libdevcore/Log.h> #include <libdevcrypto/CryptoPP.h> #include <libdevcrypto/SHA3.h> #include <libdevcrypto/FileSystem.h> #include <libethash/internal.h> #include "BlockInfo.h" #include "Exceptions.h" using namespace std; using namespace chrono; using namespace dev; using namespace eth; EthashAux* dev::eth::EthashAux::s_this = nullptr; EthashAux::~EthashAux() { } uint64_t EthashAux::cacheSize(BlockInfo const& _header) { return ethash_get_cachesize((uint64_t)_header.number); } h256 EthashAux::seedHash(unsigned _number) { unsigned epoch = _number / ETHASH_EPOCH_LENGTH; Guard l(get()->x_epochs); if (epoch >= get()->m_seedHashes.size()) { h256 ret; unsigned n = 0; if (!get()->m_seedHashes.empty()) { ret = get()->m_seedHashes.back(); n = get()->m_seedHashes.size() - 1; } get()->m_seedHashes.resize(epoch + 1); // cdebug << "Searching for seedHash of epoch " << epoch; for (; n <= epoch; ++n, ret = sha3(ret)) { get()->m_seedHashes[n] = ret; // cdebug << "Epoch" << n << "is" << ret; } } return get()->m_seedHashes[epoch]; } void EthashAux::killCache(h256 const& _s) { RecursiveGuard l(x_this); m_lights.erase(_s); } EthashAux::LightType EthashAux::light(BlockInfo const& _header) { return light((uint64_t)_header.number); } EthashAux::LightType EthashAux::light(uint64_t _blockNumber) { RecursiveGuard l(get()->x_this); h256 seedHash = EthashAux::seedHash(_blockNumber); LightType ret = get()->m_lights[seedHash]; return ret ? ret : (get()->m_lights[seedHash] = make_shared<LightAllocation>(_blockNumber)); } EthashAux::LightAllocation::LightAllocation(uint64_t _blockNumber) { light = ethash_light_new(_blockNumber); size = ethash_get_cachesize(_blockNumber); } EthashAux::LightAllocation::~LightAllocation() { ethash_light_delete(light); } bytesConstRef EthashAux::LightAllocation::data() const { return bytesConstRef((byte const*)light->cache, size); } EthashAux::FullAllocation::FullAllocation(ethash_light_t _light, ethash_callback_t _cb) { full = ethash_full_new(_light, _cb); } EthashAux::FullAllocation::~FullAllocation() { ethash_full_delete(full); } bytesConstRef EthashAux::FullAllocation::data() const { return bytesConstRef((byte const*)ethash_full_dag(full), size()); } EthashAux::FullType EthashAux::full(BlockInfo const& _header) { return full((uint64_t) _header.number); } EthashAux::FullType EthashAux::full(uint64_t _blockNumber) { RecursiveGuard l(get()->x_this); h256 seedHash = EthashAux::seedHash(_blockNumber); FullType ret = get()->m_fulls[seedHash].lock(); if (ret) { get()->m_lastUsedFull = ret; return ret; } ret = get()->m_lastUsedFull = make_shared<FullAllocation>(light(_blockNumber)->light, nullptr); get()->m_fulls[seedHash] = ret; return ret; } Ethash::Result EthashAux::FullAllocation::compute(h256 const& _headerHash, Nonce const& _nonce) const { ethash_return_value_t r = ethash_full_compute(full, *(ethash_h256_t*)_headerHash.data(), (uint64_t)(u64)_nonce); if (!r.success) BOOST_THROW_EXCEPTION(DAGCreationFailure()); return Ethash::Result{h256((uint8_t*)&r.result, h256::ConstructFromPointer), h256((uint8_t*)&r.mix_hash, h256::ConstructFromPointer)}; } Ethash::Result EthashAux::LightAllocation::compute(h256 const& _headerHash, Nonce const& _nonce) const { ethash_return_value r = ethash_light_compute(light, *(ethash_h256_t*)_headerHash.data(), (uint64_t)(u64)_nonce); if (!r.success) BOOST_THROW_EXCEPTION(DAGCreationFailure()); return Ethash::Result{h256((uint8_t*)&r.result, h256::ConstructFromPointer), h256((uint8_t*)&r.mix_hash, h256::ConstructFromPointer)}; } Ethash::Result EthashAux::eval(BlockInfo const& _header, Nonce const& _nonce) { return eval((uint64_t)_header.number, _header.headerHash(WithoutNonce), _nonce); } Ethash::Result EthashAux::eval(uint64_t _blockNumber, h256 const& _headerHash, Nonce const& _nonce) { if (auto dag = EthashAux::get()->full(_blockNumber)) return dag->compute(_headerHash, _nonce); return EthashAux::get()->light(_blockNumber)->compute(_headerHash, _nonce); } <commit_msg>Fix EthashAux eval(). Dagger tests now pass<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 EthashAux.cpp * @author Gav Wood <i@gavwood.com> * @date 2014 */ #include "EthashAux.h" #include <boost/detail/endian.hpp> #include <boost/filesystem.hpp> #include <chrono> #include <array> #include <random> #include <thread> #include <libdevcore/Common.h> #include <libdevcore/Guards.h> #include <libdevcore/Log.h> #include <libdevcrypto/CryptoPP.h> #include <libdevcrypto/SHA3.h> #include <libdevcrypto/FileSystem.h> #include <libethash/internal.h> #include "BlockInfo.h" #include "Exceptions.h" using namespace std; using namespace chrono; using namespace dev; using namespace eth; EthashAux* dev::eth::EthashAux::s_this = nullptr; EthashAux::~EthashAux() { } uint64_t EthashAux::cacheSize(BlockInfo const& _header) { return ethash_get_cachesize((uint64_t)_header.number); } h256 EthashAux::seedHash(unsigned _number) { unsigned epoch = _number / ETHASH_EPOCH_LENGTH; Guard l(get()->x_epochs); if (epoch >= get()->m_seedHashes.size()) { h256 ret; unsigned n = 0; if (!get()->m_seedHashes.empty()) { ret = get()->m_seedHashes.back(); n = get()->m_seedHashes.size() - 1; } get()->m_seedHashes.resize(epoch + 1); // cdebug << "Searching for seedHash of epoch " << epoch; for (; n <= epoch; ++n, ret = sha3(ret)) { get()->m_seedHashes[n] = ret; // cdebug << "Epoch" << n << "is" << ret; } } return get()->m_seedHashes[epoch]; } void EthashAux::killCache(h256 const& _s) { RecursiveGuard l(x_this); m_lights.erase(_s); } EthashAux::LightType EthashAux::light(BlockInfo const& _header) { return light((uint64_t)_header.number); } EthashAux::LightType EthashAux::light(uint64_t _blockNumber) { RecursiveGuard l(get()->x_this); h256 seedHash = EthashAux::seedHash(_blockNumber); LightType ret = get()->m_lights[seedHash]; return ret ? ret : (get()->m_lights[seedHash] = make_shared<LightAllocation>(_blockNumber)); } EthashAux::LightAllocation::LightAllocation(uint64_t _blockNumber) { light = ethash_light_new(_blockNumber); size = ethash_get_cachesize(_blockNumber); } EthashAux::LightAllocation::~LightAllocation() { ethash_light_delete(light); } bytesConstRef EthashAux::LightAllocation::data() const { return bytesConstRef((byte const*)light->cache, size); } EthashAux::FullAllocation::FullAllocation(ethash_light_t _light, ethash_callback_t _cb) { full = ethash_full_new(_light, _cb); } EthashAux::FullAllocation::~FullAllocation() { ethash_full_delete(full); } bytesConstRef EthashAux::FullAllocation::data() const { return bytesConstRef((byte const*)ethash_full_dag(full), size()); } EthashAux::FullType EthashAux::full(BlockInfo const& _header) { return full((uint64_t) _header.number); } EthashAux::FullType EthashAux::full(uint64_t _blockNumber) { RecursiveGuard l(get()->x_this); h256 seedHash = EthashAux::seedHash(_blockNumber); FullType ret; if ((ret = get()->m_fulls[seedHash].lock())) { get()->m_lastUsedFull = ret; return ret; } ret = get()->m_lastUsedFull = make_shared<FullAllocation>(light(_blockNumber)->light, nullptr); get()->m_fulls[seedHash] = ret; return ret; } Ethash::Result EthashAux::FullAllocation::compute(h256 const& _headerHash, Nonce const& _nonce) const { ethash_return_value_t r = ethash_full_compute(full, *(ethash_h256_t*)_headerHash.data(), (uint64_t)(u64)_nonce); if (!r.success) BOOST_THROW_EXCEPTION(DAGCreationFailure()); return Ethash::Result{h256((uint8_t*)&r.result, h256::ConstructFromPointer), h256((uint8_t*)&r.mix_hash, h256::ConstructFromPointer)}; } Ethash::Result EthashAux::LightAllocation::compute(h256 const& _headerHash, Nonce const& _nonce) const { ethash_return_value r = ethash_light_compute(light, *(ethash_h256_t*)_headerHash.data(), (uint64_t)(u64)_nonce); if (!r.success) BOOST_THROW_EXCEPTION(DAGCreationFailure()); return Ethash::Result{h256((uint8_t*)&r.result, h256::ConstructFromPointer), h256((uint8_t*)&r.mix_hash, h256::ConstructFromPointer)}; } Ethash::Result EthashAux::eval(BlockInfo const& _header, Nonce const& _nonce) { return eval((uint64_t)_header.number, _header.headerHash(WithoutNonce), _nonce); } Ethash::Result EthashAux::eval(uint64_t _blockNumber, h256 const& _headerHash, Nonce const& _nonce) { h256 seedHash = EthashAux::seedHash(_blockNumber); if (FullType dag = get()->m_fulls[seedHash].lock()) return dag->compute(_headerHash, _nonce); return EthashAux::get()->light(_blockNumber)->compute(_headerHash, _nonce); } <|endoftext|>
<commit_before>// Copyright 2014 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 "components/password_manager/core/browser/password_store_default.h" #include <set> #include "base/logging.h" #include "base/prefs/pref_service.h" #include "base/stl_util.h" #include "components/password_manager/core/browser/password_store_change.h" using autofill::PasswordForm; namespace password_manager { PasswordStoreDefault::PasswordStoreDefault( scoped_refptr<base::SingleThreadTaskRunner> main_thread_runner, scoped_refptr<base::SingleThreadTaskRunner> db_thread_runner, scoped_ptr<LoginDatabase> login_db) : PasswordStore(main_thread_runner, db_thread_runner), login_db_(login_db.Pass()) { } PasswordStoreDefault::~PasswordStoreDefault() { } bool PasswordStoreDefault::Init( const syncer::SyncableService::StartSyncFlare& flare) { ScheduleTask(base::Bind(&PasswordStoreDefault::InitOnDBThread, this)); return PasswordStore::Init(flare); } void PasswordStoreDefault::InitOnDBThread() { DCHECK(GetBackgroundTaskRunner()->BelongsToCurrentThread()); DCHECK(login_db_); if (!login_db_->Init()) { login_db_.reset(); LOG(ERROR) << "Could not create/open login database."; } } void PasswordStoreDefault::ReportMetricsImpl( const std::string& sync_username, bool custom_passphrase_sync_enabled) { if (!login_db_) return; DCHECK(GetBackgroundTaskRunner()->BelongsToCurrentThread()); login_db_->ReportMetrics(sync_username, custom_passphrase_sync_enabled); } PasswordStoreChangeList PasswordStoreDefault::AddLoginImpl( const PasswordForm& form) { DCHECK(GetBackgroundTaskRunner()->BelongsToCurrentThread()); if (!login_db_) return PasswordStoreChangeList(); return login_db_->AddLogin(form); } PasswordStoreChangeList PasswordStoreDefault::UpdateLoginImpl( const PasswordForm& form) { DCHECK(GetBackgroundTaskRunner()->BelongsToCurrentThread()); if (!login_db_) return PasswordStoreChangeList(); return login_db_->UpdateLogin(form); } PasswordStoreChangeList PasswordStoreDefault::RemoveLoginImpl( const PasswordForm& form) { DCHECK(GetBackgroundTaskRunner()->BelongsToCurrentThread()); PasswordStoreChangeList changes; if (login_db_ && login_db_->RemoveLogin(form)) changes.push_back(PasswordStoreChange(PasswordStoreChange::REMOVE, form)); return changes; } PasswordStoreChangeList PasswordStoreDefault::RemoveLoginsCreatedBetweenImpl( base::Time delete_begin, base::Time delete_end) { ScopedVector<autofill::PasswordForm> forms; PasswordStoreChangeList changes; if (login_db_ && login_db_->GetLoginsCreatedBetween(delete_begin, delete_end, &forms)) { if (login_db_->RemoveLoginsCreatedBetween(delete_begin, delete_end)) { for (const auto* form : forms) { changes.push_back( PasswordStoreChange(PasswordStoreChange::REMOVE, *form)); } LogStatsForBulkDeletion(changes.size()); } } return changes; } PasswordStoreChangeList PasswordStoreDefault::RemoveLoginsSyncedBetweenImpl( base::Time delete_begin, base::Time delete_end) { ScopedVector<autofill::PasswordForm> forms; PasswordStoreChangeList changes; if (login_db_ && login_db_->GetLoginsSyncedBetween(delete_begin, delete_end, &forms)) { if (login_db_->RemoveLoginsSyncedBetween(delete_begin, delete_end)) { for (const auto* form : forms) { changes.push_back( PasswordStoreChange(PasswordStoreChange::REMOVE, *form)); } LogStatsForBulkDeletionDuringRollback(changes.size()); } } return changes; } ScopedVector<autofill::PasswordForm> PasswordStoreDefault::FillMatchingLogins( const autofill::PasswordForm& form, AuthorizationPromptPolicy prompt_policy) { ScopedVector<autofill::PasswordForm> matched_forms; if (login_db_ && !login_db_->GetLogins(form, &matched_forms)) return ScopedVector<autofill::PasswordForm>(); return matched_forms.Pass(); } void PasswordStoreDefault::GetAutofillableLoginsImpl( scoped_ptr<GetLoginsRequest> request) { ScopedVector<PasswordForm> logins; if (!FillAutofillableLogins(&logins)) logins.clear(); request->NotifyConsumerWithResults(logins.Pass()); } void PasswordStoreDefault::GetBlacklistLoginsImpl( scoped_ptr<GetLoginsRequest> request) { ScopedVector<PasswordForm> logins; if (!FillBlacklistLogins(&logins)) logins.clear(); request->NotifyConsumerWithResults(logins.Pass()); } bool PasswordStoreDefault::FillAutofillableLogins( ScopedVector<PasswordForm>* forms) { DCHECK(GetBackgroundTaskRunner()->BelongsToCurrentThread()); return login_db_ && login_db_->GetAutofillableLogins(forms); } bool PasswordStoreDefault::FillBlacklistLogins( ScopedVector<PasswordForm>* forms) { DCHECK(GetBackgroundTaskRunner()->BelongsToCurrentThread()); return login_db_ && login_db_->GetBlacklistLogins(forms); } void PasswordStoreDefault::AddSiteStatsImpl(const InteractionsStats& stats) { DCHECK(GetBackgroundTaskRunner()->BelongsToCurrentThread()); if (login_db_) login_db_->stats_table().AddRow(stats); } void PasswordStoreDefault::RemoveSiteStatsImpl(const GURL& origin_domain) { DCHECK(GetBackgroundTaskRunner()->BelongsToCurrentThread()); if (login_db_) login_db_->stats_table().RemoveRow(origin_domain); } scoped_ptr<InteractionsStats> PasswordStoreDefault::GetSiteStatsImpl( const GURL& origin_domain) { DCHECK(GetBackgroundTaskRunner()->BelongsToCurrentThread()); return login_db_ ? login_db_->stats_table().GetRow(origin_domain) : scoped_ptr<InteractionsStats>(); } } // namespace password_manager <commit_msg>Stop deleting LoginDatabase on the UI thread during shutdown<commit_after>// Copyright 2014 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 "components/password_manager/core/browser/password_store_default.h" #include <set> #include "base/logging.h" #include "base/prefs/pref_service.h" #include "base/stl_util.h" #include "components/password_manager/core/browser/password_store_change.h" using autofill::PasswordForm; namespace password_manager { PasswordStoreDefault::PasswordStoreDefault( scoped_refptr<base::SingleThreadTaskRunner> main_thread_runner, scoped_refptr<base::SingleThreadTaskRunner> db_thread_runner, scoped_ptr<LoginDatabase> login_db) : PasswordStore(main_thread_runner, db_thread_runner), login_db_(login_db.Pass()) { } PasswordStoreDefault::~PasswordStoreDefault() { if (!GetBackgroundTaskRunner()->BelongsToCurrentThread()) GetBackgroundTaskRunner()->DeleteSoon(FROM_HERE, login_db_.release()); } bool PasswordStoreDefault::Init( const syncer::SyncableService::StartSyncFlare& flare) { ScheduleTask(base::Bind(&PasswordStoreDefault::InitOnDBThread, this)); return PasswordStore::Init(flare); } void PasswordStoreDefault::InitOnDBThread() { DCHECK(GetBackgroundTaskRunner()->BelongsToCurrentThread()); DCHECK(login_db_); if (!login_db_->Init()) { login_db_.reset(); LOG(ERROR) << "Could not create/open login database."; } } void PasswordStoreDefault::ReportMetricsImpl( const std::string& sync_username, bool custom_passphrase_sync_enabled) { if (!login_db_) return; DCHECK(GetBackgroundTaskRunner()->BelongsToCurrentThread()); login_db_->ReportMetrics(sync_username, custom_passphrase_sync_enabled); } PasswordStoreChangeList PasswordStoreDefault::AddLoginImpl( const PasswordForm& form) { DCHECK(GetBackgroundTaskRunner()->BelongsToCurrentThread()); if (!login_db_) return PasswordStoreChangeList(); return login_db_->AddLogin(form); } PasswordStoreChangeList PasswordStoreDefault::UpdateLoginImpl( const PasswordForm& form) { DCHECK(GetBackgroundTaskRunner()->BelongsToCurrentThread()); if (!login_db_) return PasswordStoreChangeList(); return login_db_->UpdateLogin(form); } PasswordStoreChangeList PasswordStoreDefault::RemoveLoginImpl( const PasswordForm& form) { DCHECK(GetBackgroundTaskRunner()->BelongsToCurrentThread()); PasswordStoreChangeList changes; if (login_db_ && login_db_->RemoveLogin(form)) changes.push_back(PasswordStoreChange(PasswordStoreChange::REMOVE, form)); return changes; } PasswordStoreChangeList PasswordStoreDefault::RemoveLoginsCreatedBetweenImpl( base::Time delete_begin, base::Time delete_end) { ScopedVector<autofill::PasswordForm> forms; PasswordStoreChangeList changes; if (login_db_ && login_db_->GetLoginsCreatedBetween(delete_begin, delete_end, &forms)) { if (login_db_->RemoveLoginsCreatedBetween(delete_begin, delete_end)) { for (const auto* form : forms) { changes.push_back( PasswordStoreChange(PasswordStoreChange::REMOVE, *form)); } LogStatsForBulkDeletion(changes.size()); } } return changes; } PasswordStoreChangeList PasswordStoreDefault::RemoveLoginsSyncedBetweenImpl( base::Time delete_begin, base::Time delete_end) { ScopedVector<autofill::PasswordForm> forms; PasswordStoreChangeList changes; if (login_db_ && login_db_->GetLoginsSyncedBetween(delete_begin, delete_end, &forms)) { if (login_db_->RemoveLoginsSyncedBetween(delete_begin, delete_end)) { for (const auto* form : forms) { changes.push_back( PasswordStoreChange(PasswordStoreChange::REMOVE, *form)); } LogStatsForBulkDeletionDuringRollback(changes.size()); } } return changes; } ScopedVector<autofill::PasswordForm> PasswordStoreDefault::FillMatchingLogins( const autofill::PasswordForm& form, AuthorizationPromptPolicy prompt_policy) { ScopedVector<autofill::PasswordForm> matched_forms; if (login_db_ && !login_db_->GetLogins(form, &matched_forms)) return ScopedVector<autofill::PasswordForm>(); return matched_forms.Pass(); } void PasswordStoreDefault::GetAutofillableLoginsImpl( scoped_ptr<GetLoginsRequest> request) { ScopedVector<PasswordForm> logins; if (!FillAutofillableLogins(&logins)) logins.clear(); request->NotifyConsumerWithResults(logins.Pass()); } void PasswordStoreDefault::GetBlacklistLoginsImpl( scoped_ptr<GetLoginsRequest> request) { ScopedVector<PasswordForm> logins; if (!FillBlacklistLogins(&logins)) logins.clear(); request->NotifyConsumerWithResults(logins.Pass()); } bool PasswordStoreDefault::FillAutofillableLogins( ScopedVector<PasswordForm>* forms) { DCHECK(GetBackgroundTaskRunner()->BelongsToCurrentThread()); return login_db_ && login_db_->GetAutofillableLogins(forms); } bool PasswordStoreDefault::FillBlacklistLogins( ScopedVector<PasswordForm>* forms) { DCHECK(GetBackgroundTaskRunner()->BelongsToCurrentThread()); return login_db_ && login_db_->GetBlacklistLogins(forms); } void PasswordStoreDefault::AddSiteStatsImpl(const InteractionsStats& stats) { DCHECK(GetBackgroundTaskRunner()->BelongsToCurrentThread()); if (login_db_) login_db_->stats_table().AddRow(stats); } void PasswordStoreDefault::RemoveSiteStatsImpl(const GURL& origin_domain) { DCHECK(GetBackgroundTaskRunner()->BelongsToCurrentThread()); if (login_db_) login_db_->stats_table().RemoveRow(origin_domain); } scoped_ptr<InteractionsStats> PasswordStoreDefault::GetSiteStatsImpl( const GURL& origin_domain) { DCHECK(GetBackgroundTaskRunner()->BelongsToCurrentThread()); return login_db_ ? login_db_->stats_table().GetRow(origin_domain) : scoped_ptr<InteractionsStats>(); } } // namespace password_manager <|endoftext|>
<commit_before>#include <cstdio> #include <iostream> #include <pqxx/connection> #include <pqxx/transaction> #include <pqxx/result> using namespace PGSTD; using namespace pqxx; // Test program for libpqxx. Query a table and report its metadata. // // Usage: test011 [connect-string] [table] // // Where table is the table to be queried; if none is given, pg_tables is // queried by default. // // The connect-string is a set of connection options in Postgresql's // PQconnectdb() format, eg. "dbname=template1" to select from a database // called template1, or "host=foo.bar.net user=smith" to connect to a // backend running on host foo.bar.net, logging in as user smith. int main(int argc, char *argv[]) { try { const string Table = ((argc >= 3) ? argv[2] : "pg_tables"); connection C(argv[1]); work T(C, "test11"); result R( T.exec("SELECT * FROM " + Table) ); // Print column names for (result::tuple::size_type c = 0; c < R.columns(); ++c) { string N= R.column_name(c); cout << c << ":\t" << N << endl; if (R.column_number(N) != c) throw logic_error("Expected column '" + N + "' to be no. " + to_string(c) + ", " "but it was no. " + to_string(R.column_number(N))); } // If there are rows in R, compare their metadata to R's. if (!R.empty()) { if (R[0].rownumber() != 0) throw logic_error("Row 0 said it was row " + R[0].rownumber()); if (R.size() < 2) cout << "(Only one row in table.)" << endl; else if (R[1].rownumber() != 1) throw logic_error("Row 1 said it was row " + R[1].rownumber()); for (result::tuple::size_type c = 0; c < R[0].size(); ++c) { string N = R.column_name(c); if (string(R[0].at(c).c_str()) != R[0].at(N).c_str()) throw logic_error("Field " + to_string(c) + " contains " "'" + R[0].at(c).c_str() + "'; " "field '" + N + "' " "contains '" + R[0].at(N).c_str() + "'"); if (string(R[0][c].c_str()) != R[0][N].c_str()) throw logic_error("Field " + to_string(c) + " ('" + N + "'): " "at() inconsistent with operator[]!"); if (R[0][c].name() != N) throw logic_error("Field " + to_string(c) + " " "called '" + N + "' by result, " "but '" + R[0][c].name() + "' by Field object"); if (size_t(R[0][c].size()) != strlen(R[0][c].c_str())) throw logic_error("Field '" + N + "' " "says its length is " + to_string(R[0][c].size()) + ", " "but its value is '" + R[0][c].c_str() + "' " "(" + to_string(strlen(R[0][c].c_str())) + " " "chars)"); } } else { cout << "(Table is empty.)" << endl; } } catch (const sql_error &e) { // If we're interested in the text of a failed query, we can write separate // exception handling code for this type of exception cerr << "SQL error: " << e.what() << endl << "Query was: '" << e.query() << "'" << endl; return 1; } catch (const exception &e) { // All exceptions thrown by libpqxx are derived from std::exception cerr << "Exception: " << e.what() << endl; return 2; } catch (...) { // This is really unexpected (see above) cerr << "Unhandled exception" << endl; return 100; } return 0; } <commit_msg>Test result::tuple::swap() and equality<commit_after>#include <cstdio> #include <iostream> #include <pqxx/connection> #include <pqxx/transaction> #include <pqxx/result> using namespace PGSTD; using namespace pqxx; // Test program for libpqxx. Query a table and report its metadata. // // Usage: test011 [connect-string] [table] // // Where table is the table to be queried; if none is given, pg_tables is // queried by default. // // The connect-string is a set of connection options in Postgresql's // PQconnectdb() format, eg. "dbname=template1" to select from a database // called template1, or "host=foo.bar.net user=smith" to connect to a // backend running on host foo.bar.net, logging in as user smith. int main(int argc, char *argv[]) { try { const string Table = ((argc >= 3) ? argv[2] : "pg_tables"); connection C(argv[1]); work T(C, "test11"); result R( T.exec("SELECT * FROM " + Table) ); // Print column names for (result::tuple::size_type c = 0; c < R.columns(); ++c) { string N= R.column_name(c); cout << c << ":\t" << N << endl; if (R.column_number(N) != c) throw logic_error("Expected column '" + N + "' to be no. " + to_string(c) + ", " "but it was no. " + to_string(R.column_number(N))); } // If there are rows in R, compare their metadata to R's. if (!R.empty()) { if (R[0].rownumber() != 0) throw logic_error("Row 0 said it was row " + R[0].rownumber()); if (R.size() < 2) cout << "(Only one row in table.)" << endl; else if (R[1].rownumber() != 1) throw logic_error("Row 1 said it was row " + R[1].rownumber()); // Test tuple::swap() const result::tuple T1(R[0]), T2(R[1]); if (T2 == T1) throw runtime_error("Values are identical, can't test swap()!"); result::tuple T1s(T1), T2s(T2); if (T1s != T1 || !(T2s == T2)) throw logic_error("Tuple copy-construction incorrect"); T1s.swap(T2s); if (T1s == T1 || !(T2s != T2)) throw logic_error("Tuple swap doesn't work"); if (T2s != T1 || !(T1s == T2)) throw logic_error("Tuple swap is asymmetric"); for (result::tuple::size_type c = 0; c < R[0].size(); ++c) { string N = R.column_name(c); if (string(R[0].at(c).c_str()) != R[0].at(N).c_str()) throw logic_error("Field " + to_string(c) + " contains " "'" + R[0].at(c).c_str() + "'; " "field '" + N + "' " "contains '" + R[0].at(N).c_str() + "'"); if (string(R[0][c].c_str()) != R[0][N].c_str()) throw logic_error("Field " + to_string(c) + " ('" + N + "'): " "at() inconsistent with operator[]!"); if (R[0][c].name() != N) throw logic_error("Field " + to_string(c) + " " "called '" + N + "' by result, " "but '" + R[0][c].name() + "' by Field object"); if (size_t(R[0][c].size()) != strlen(R[0][c].c_str())) throw logic_error("Field '" + N + "' " "says its length is " + to_string(R[0][c].size()) + ", " "but its value is '" + R[0][c].c_str() + "' " "(" + to_string(strlen(R[0][c].c_str())) + " " "chars)"); } } else { cout << "(Table is empty.)" << endl; } } catch (const sql_error &e) { // If we're interested in the text of a failed query, we can write separate // exception handling code for this type of exception cerr << "SQL error: " << e.what() << endl << "Query was: '" << e.query() << "'" << endl; return 1; } catch (const exception &e) { // All exceptions thrown by libpqxx are derived from std::exception cerr << "Exception: " << e.what() << endl; return 2; } catch (...) { // This is really unexpected (see above) cerr << "Unhandled exception" << endl; return 100; } return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "JsonWrapper.h" #include <algorithm> #include <json/value.h> JsonWrapper::JsonWrapper() : JsonWrapper(Json::nullValue) {} JsonWrapper::JsonWrapper(const Json::Value& config) : m_config(new Json::Value(config)) {} JsonWrapper::~JsonWrapper() {} JsonWrapper::JsonWrapper(JsonWrapper&& other) noexcept : m_config(std::move(other.m_config)) {} JsonWrapper& JsonWrapper::operator=(JsonWrapper&& rhs) noexcept { m_config = std::move(rhs.m_config); return *this; } void JsonWrapper::get(const char* name, int64_t dflt, int64_t& param) const { param = m_config->get(name, (Json::Int64)dflt).asInt(); } void JsonWrapper::get(const char* name, size_t dflt, size_t& param) const { param = m_config->get(name, (Json::UInt)dflt).asUInt(); } void JsonWrapper::get(const char* name, const std::string& dflt, std::string& param) const { param = m_config->get(name, dflt).asString(); } std::string JsonWrapper::get(const char* name, const std::string& dflt) const { return m_config->get(name, dflt).asString(); } void JsonWrapper::get(const char* name, bool dflt, bool& param) const { auto val = m_config->get(name, dflt); // Do some simple type conversions that folly used to do if (val.isBool()) { param = val.asBool(); return; } else if (val.isInt()) { auto valInt = val.asInt(); if (valInt == 0 || valInt == 1) { param = (val.asInt() != 0); return; } } else if (val.isString()) { auto str = val.asString(); std::transform(str.begin(), str.end(), str.begin(), [](auto c) { return ::tolower(c); }); if (str == "0" || str == "false" || str == "off" || str == "no") { param = false; return; } else if (str == "1" || str == "true" || str == "on" || str == "yes") { param = true; return; } } throw std::runtime_error("Cannot convert JSON value to bool: " + val.asString()); } bool JsonWrapper::get(const char* name, bool dflt) const { bool res; get(name, dflt, res); return res; } void JsonWrapper::get(const char* name, const std::vector<std::string>& dflt, std::vector<std::string>& param) const { auto it = (*m_config)[name]; // NOLINTNEXTLINE(readability-container-size-empty) if (it == Json::nullValue) { param = dflt; } else { param.clear(); for (auto const& str : it) { param.emplace_back(str.asString()); } } } void JsonWrapper::get(const char* name, const std::vector<std::string>& dflt, std::unordered_set<std::string>& param) const { auto it = (*m_config)[name]; param.clear(); // NOLINTNEXTLINE(readability-container-size-empty) if (it == Json::nullValue) { param.insert(dflt.begin(), dflt.end()); } else { for (auto const& str : it) { param.emplace(str.asString()); } } } void JsonWrapper::get( const char* name, const std::unordered_map<std::string, std::vector<std::string>>& dflt, std::unordered_map<std::string, std::vector<std::string>>& param) const { auto cfg = (*m_config)[name]; param.clear(); // NOLINTNEXTLINE(readability-container-size-empty) if (cfg == Json::nullValue) { param = dflt; } else { if (!cfg.isObject()) { throw std::runtime_error("Cannot convert JSON value to object: " + cfg.asString()); } for (auto it = cfg.begin(); it != cfg.end(); ++it) { auto key = it.key(); if (!key.isString()) { throw std::runtime_error("Cannot convert JSON value to string: " + key.asString()); } auto& val = *it; if (!val.isArray()) { throw std::runtime_error("Cannot convert JSON value to array: " + val.asString()); } for (auto& str : val) { if (!str.isString()) { throw std::runtime_error("Cannot convert JSON value to string: " + str.asString()); } param[key.asString()].push_back(str.asString()); } } } } void JsonWrapper::get(const char* name, const Json::Value& dflt, Json::Value& param) const { param = m_config->get(name, dflt); } Json::Value JsonWrapper::get(const char* name, const Json::Value& dflt) const { return m_config->get(name, dflt); } const Json::Value& JsonWrapper::operator[](const char* name) const { return (*m_config)[name]; } bool JsonWrapper::contains(const char* name) const { return m_config->isMember(name); } <commit_msg>Fix CI error (#550)<commit_after>/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "JsonWrapper.h" #include <algorithm> #include <json/value.h> #include <stdexcept> JsonWrapper::JsonWrapper() : JsonWrapper(Json::nullValue) {} JsonWrapper::JsonWrapper(const Json::Value& config) : m_config(new Json::Value(config)) {} JsonWrapper::~JsonWrapper() {} JsonWrapper::JsonWrapper(JsonWrapper&& other) noexcept : m_config(std::move(other.m_config)) {} JsonWrapper& JsonWrapper::operator=(JsonWrapper&& rhs) noexcept { m_config = std::move(rhs.m_config); return *this; } void JsonWrapper::get(const char* name, int64_t dflt, int64_t& param) const { param = m_config->get(name, (Json::Int64)dflt).asInt(); } void JsonWrapper::get(const char* name, size_t dflt, size_t& param) const { param = m_config->get(name, (Json::UInt)dflt).asUInt(); } void JsonWrapper::get(const char* name, const std::string& dflt, std::string& param) const { param = m_config->get(name, dflt).asString(); } std::string JsonWrapper::get(const char* name, const std::string& dflt) const { return m_config->get(name, dflt).asString(); } void JsonWrapper::get(const char* name, bool dflt, bool& param) const { auto val = m_config->get(name, dflt); // Do some simple type conversions that folly used to do if (val.isBool()) { param = val.asBool(); return; } else if (val.isInt()) { auto valInt = val.asInt(); if (valInt == 0 || valInt == 1) { param = (val.asInt() != 0); return; } } else if (val.isString()) { auto str = val.asString(); std::transform(str.begin(), str.end(), str.begin(), [](auto c) { return ::tolower(c); }); if (str == "0" || str == "false" || str == "off" || str == "no") { param = false; return; } else if (str == "1" || str == "true" || str == "on" || str == "yes") { param = true; return; } } throw std::runtime_error("Cannot convert JSON value to bool: " + val.asString()); } bool JsonWrapper::get(const char* name, bool dflt) const { bool res; get(name, dflt, res); return res; } void JsonWrapper::get(const char* name, const std::vector<std::string>& dflt, std::vector<std::string>& param) const { auto it = (*m_config)[name]; // NOLINTNEXTLINE(readability-container-size-empty) if (it == Json::nullValue) { param = dflt; } else { param.clear(); for (auto const& str : it) { param.emplace_back(str.asString()); } } } void JsonWrapper::get(const char* name, const std::vector<std::string>& dflt, std::unordered_set<std::string>& param) const { auto it = (*m_config)[name]; param.clear(); // NOLINTNEXTLINE(readability-container-size-empty) if (it == Json::nullValue) { param.insert(dflt.begin(), dflt.end()); } else { for (auto const& str : it) { param.emplace(str.asString()); } } } void JsonWrapper::get( const char* name, const std::unordered_map<std::string, std::vector<std::string>>& dflt, std::unordered_map<std::string, std::vector<std::string>>& param) const { auto cfg = (*m_config)[name]; param.clear(); // NOLINTNEXTLINE(readability-container-size-empty) if (cfg == Json::nullValue) { param = dflt; } else { if (!cfg.isObject()) { throw std::runtime_error("Cannot convert JSON value to object: " + cfg.asString()); } for (auto it = cfg.begin(); it != cfg.end(); ++it) { auto key = it.key(); if (!key.isString()) { throw std::runtime_error("Cannot convert JSON value to string: " + key.asString()); } auto& val = *it; if (!val.isArray()) { throw std::runtime_error("Cannot convert JSON value to array: " + val.asString()); } for (auto& str : val) { if (!str.isString()) { throw std::runtime_error("Cannot convert JSON value to string: " + str.asString()); } param[key.asString()].push_back(str.asString()); } } } } void JsonWrapper::get(const char* name, const Json::Value& dflt, Json::Value& param) const { param = m_config->get(name, dflt); } Json::Value JsonWrapper::get(const char* name, const Json::Value& dflt) const { return m_config->get(name, dflt); } const Json::Value& JsonWrapper::operator[](const char* name) const { return (*m_config)[name]; } bool JsonWrapper::contains(const char* name) const { return m_config->isMember(name); } <|endoftext|>
<commit_before>// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/browser/atom_browser_client.h" #if defined(OS_WIN) #include <shlobj.h> #endif #include "atom/browser/atom_access_token_store.h" #include "atom/browser/atom_browser_context.h" #include "atom/browser/atom_browser_main_parts.h" #include "atom/browser/atom_quota_permission_context.h" #include "atom/browser/atom_speech_recognition_manager_delegate.h" #include "atom/browser/browser.h" #include "atom/browser/native_window.h" #include "atom/browser/web_view_manager.h" #include "atom/browser/window_list.h" #include "atom/common/options_switches.h" #include "base/command_line.h" #include "base/files/file_util.h" #include "base/strings/string_util.h" #include "base/strings/string_number_conversions.h" #include "chrome/browser/printing/printing_message_filter.h" #include "chrome/browser/renderer_host/pepper/chrome_browser_pepper_host_factory.h" #include "chrome/browser/speech/tts_message_filter.h" #include "content/public/browser/browser_ppapi_host.h" #include "content/public/browser/client_certificate_delegate.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/site_instance.h" #include "content/public/browser/web_contents.h" #include "content/public/common/web_preferences.h" #include "net/cert/x509_certificate.h" #include "net/ssl/ssl_cert_request_info.h" #include "ppapi/host/ppapi_host.h" #include "ui/base/l10n/l10n_util.h" namespace atom { namespace { // The default routing id of WebContents. // In Electron each RenderProcessHost only has one WebContents, so this ID is // same for every WebContents. int kDefaultRoutingID = 2; // Next navigation should not restart renderer process. bool g_suppress_renderer_process_restart = false; // Custom schemes to be registered to standard. std::string g_custom_schemes = ""; // Find out the owner of the child process according to |process_id|. enum ProcessOwner { OWNER_NATIVE_WINDOW, OWNER_GUEST_WEB_CONTENTS, OWNER_NONE, // it might be devtools though. }; ProcessOwner GetProcessOwner(int process_id, NativeWindow** window, WebViewManager::WebViewInfo* info) { auto web_contents = content::WebContents::FromRenderViewHost( content::RenderViewHost::FromID(process_id, kDefaultRoutingID)); if (!web_contents) return OWNER_NONE; // First search for NativeWindow. for (auto native_window : *WindowList::GetInstance()) if (web_contents == native_window->web_contents()) { *window = native_window; return OWNER_NATIVE_WINDOW; } // Then search for guest WebContents. if (WebViewManager::GetInfoForWebContents(web_contents, info)) return OWNER_GUEST_WEB_CONTENTS; return OWNER_NONE; } scoped_refptr<net::X509Certificate> ImportCertFromFile( const base::FilePath& path) { if (path.empty()) return nullptr; std::string cert_data; if (!base::ReadFileToString(path, &cert_data)) return nullptr; net::CertificateList certs = net::X509Certificate::CreateCertificateListFromBytes( cert_data.data(), cert_data.size(), net::X509Certificate::FORMAT_AUTO); if (certs.empty()) return nullptr; return certs[0]; } } // namespace // static void AtomBrowserClient::SuppressRendererProcessRestartForOnce() { g_suppress_renderer_process_restart = true; } void AtomBrowserClient::SetCustomSchemes( const std::vector<std::string>& schemes) { g_custom_schemes = JoinString(schemes, ','); } AtomBrowserClient::AtomBrowserClient() { } AtomBrowserClient::~AtomBrowserClient() { } void AtomBrowserClient::RenderProcessWillLaunch( content::RenderProcessHost* host) { int process_id = host->GetID(); host->AddFilter(new printing::PrintingMessageFilter(process_id)); host->AddFilter(new TtsMessageFilter(process_id, host->GetBrowserContext())); } content::SpeechRecognitionManagerDelegate* AtomBrowserClient::CreateSpeechRecognitionManagerDelegate() { return new AtomSpeechRecognitionManagerDelegate; } content::AccessTokenStore* AtomBrowserClient::CreateAccessTokenStore() { return new AtomAccessTokenStore; } void AtomBrowserClient::OverrideWebkitPrefs( content::RenderViewHost* host, content::WebPreferences* prefs) { prefs->javascript_enabled = true; prefs->web_security_enabled = true; prefs->javascript_can_open_windows_automatically = true; prefs->plugins_enabled = true; prefs->dom_paste_enabled = true; prefs->java_enabled = false; prefs->allow_scripts_to_close_windows = true; prefs->javascript_can_access_clipboard = true; prefs->local_storage_enabled = true; prefs->databases_enabled = true; prefs->application_cache_enabled = true; prefs->allow_universal_access_from_file_urls = true; prefs->allow_file_access_from_file_urls = true; prefs->experimental_webgl_enabled = true; prefs->allow_displaying_insecure_content = false; prefs->allow_running_insecure_content = false; // Custom preferences of guest page. auto web_contents = content::WebContents::FromRenderViewHost(host); WebViewManager::WebViewInfo info; if (WebViewManager::GetInfoForWebContents(web_contents, &info)) { prefs->web_security_enabled = !info.disable_web_security; return; } NativeWindow* window = NativeWindow::FromWebContents(web_contents); if (window) window->OverrideWebkitPrefs(prefs); } std::string AtomBrowserClient::GetApplicationLocale() { return l10n_util::GetApplicationLocale(""); } void AtomBrowserClient::OverrideSiteInstanceForNavigation( content::BrowserContext* browser_context, content::SiteInstance* current_instance, const GURL& url, content::SiteInstance** new_instance) { if (g_suppress_renderer_process_restart) { g_suppress_renderer_process_restart = false; return; } // Restart renderer process for all navigations except "javacript:" scheme. if (url.SchemeIs(url::kJavaScriptScheme)) return; *new_instance = content::SiteInstance::CreateForURL(browser_context, url); } void AtomBrowserClient::AppendExtraCommandLineSwitches( base::CommandLine* command_line, int process_id) { std::string process_type = command_line->GetSwitchValueASCII("type"); if (process_type != "renderer") return; // The registered standard schemes. if (!g_custom_schemes.empty()) command_line->AppendSwitchASCII(switches::kRegisterStandardSchemes, g_custom_schemes); #if defined(OS_WIN) // Append --app-user-model-id. PWSTR current_app_id; if (SUCCEEDED(GetCurrentProcessExplicitAppUserModelID(&current_app_id))) { command_line->AppendSwitchNative(switches::kAppUserModelId, current_app_id); CoTaskMemFree(current_app_id); } #endif NativeWindow* window; WebViewManager::WebViewInfo info; ProcessOwner owner = GetProcessOwner(process_id, &window, &info); if (owner == OWNER_NATIVE_WINDOW) { window->AppendExtraCommandLineSwitches(command_line); } else if (owner == OWNER_GUEST_WEB_CONTENTS) { command_line->AppendSwitchASCII( switches::kGuestInstanceID, base::IntToString(info.guest_instance_id)); command_line->AppendSwitchASCII( switches::kNodeIntegration, info.node_integration ? "true" : "false"); if (info.plugins) command_line->AppendSwitch(switches::kEnablePlugins); if (!info.preload_script.empty()) command_line->AppendSwitchPath( switches::kPreloadScript, info.preload_script); } } void AtomBrowserClient::DidCreatePpapiPlugin( content::BrowserPpapiHost* host) { host->GetPpapiHost()->AddHostFactoryFilter( make_scoped_ptr(new chrome::ChromeBrowserPepperHostFactory(host))); } content::QuotaPermissionContext* AtomBrowserClient::CreateQuotaPermissionContext() { return new AtomQuotaPermissionContext; } void AtomBrowserClient::SelectClientCertificate( content::WebContents* web_contents, net::SSLCertRequestInfo* cert_request_info, scoped_ptr<content::ClientCertificateDelegate> delegate) { // --client-certificate=`path` auto cmd = base::CommandLine::ForCurrentProcess(); if (cmd->HasSwitch(switches::kClientCertificate)) { auto cert_path = cmd->GetSwitchValuePath(switches::kClientCertificate); auto certificate = ImportCertFromFile(cert_path); if (certificate.get()) delegate->ContinueWithCertificate(certificate.get()); return; } if (!cert_request_info->client_certs.empty()) Browser::Get()->ClientCertificateSelector(web_contents, cert_request_info, delegate.Pass()); } brightray::BrowserMainParts* AtomBrowserClient::OverrideCreateBrowserMainParts( const content::MainFunctionParams&) { v8::V8::Initialize(); // Init V8 before creating main parts. return new AtomBrowserMainParts; } } // namespace atom <commit_msg>Fix a crash issue in GetProcessOwner if no renderer view host is found.<commit_after>// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/browser/atom_browser_client.h" #if defined(OS_WIN) #include <shlobj.h> #endif #include "atom/browser/atom_access_token_store.h" #include "atom/browser/atom_browser_context.h" #include "atom/browser/atom_browser_main_parts.h" #include "atom/browser/atom_quota_permission_context.h" #include "atom/browser/atom_speech_recognition_manager_delegate.h" #include "atom/browser/browser.h" #include "atom/browser/native_window.h" #include "atom/browser/web_view_manager.h" #include "atom/browser/window_list.h" #include "atom/common/options_switches.h" #include "base/command_line.h" #include "base/files/file_util.h" #include "base/strings/string_util.h" #include "base/strings/string_number_conversions.h" #include "chrome/browser/printing/printing_message_filter.h" #include "chrome/browser/renderer_host/pepper/chrome_browser_pepper_host_factory.h" #include "chrome/browser/speech/tts_message_filter.h" #include "content/public/browser/browser_ppapi_host.h" #include "content/public/browser/client_certificate_delegate.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/site_instance.h" #include "content/public/browser/web_contents.h" #include "content/public/common/web_preferences.h" #include "net/cert/x509_certificate.h" #include "net/ssl/ssl_cert_request_info.h" #include "ppapi/host/ppapi_host.h" #include "ui/base/l10n/l10n_util.h" namespace atom { namespace { // The default routing id of WebContents. // In Electron each RenderProcessHost only has one WebContents, so this ID is // same for every WebContents. int kDefaultRoutingID = 2; // Next navigation should not restart renderer process. bool g_suppress_renderer_process_restart = false; // Custom schemes to be registered to standard. std::string g_custom_schemes = ""; // Find out the owner of the child process according to |process_id|. enum ProcessOwner { OWNER_NATIVE_WINDOW, OWNER_GUEST_WEB_CONTENTS, OWNER_NONE, // it might be devtools though. }; ProcessOwner GetProcessOwner(int process_id, NativeWindow** window, WebViewManager::WebViewInfo* info) { content::RenderViewHost* rvh = content::RenderViewHost::FromID( process_id, kDefaultRoutingID); if (!rvh) return OWNER_NONE; auto web_contents = content::WebContents::FromRenderViewHost(rvh); if (!web_contents) return OWNER_NONE; // First search for NativeWindow. for (auto native_window : *WindowList::GetInstance()) if (web_contents == native_window->web_contents()) { *window = native_window; return OWNER_NATIVE_WINDOW; } // Then search for guest WebContents. if (WebViewManager::GetInfoForWebContents(web_contents, info)) return OWNER_GUEST_WEB_CONTENTS; return OWNER_NONE; } scoped_refptr<net::X509Certificate> ImportCertFromFile( const base::FilePath& path) { if (path.empty()) return nullptr; std::string cert_data; if (!base::ReadFileToString(path, &cert_data)) return nullptr; net::CertificateList certs = net::X509Certificate::CreateCertificateListFromBytes( cert_data.data(), cert_data.size(), net::X509Certificate::FORMAT_AUTO); if (certs.empty()) return nullptr; return certs[0]; } } // namespace // static void AtomBrowserClient::SuppressRendererProcessRestartForOnce() { g_suppress_renderer_process_restart = true; } void AtomBrowserClient::SetCustomSchemes( const std::vector<std::string>& schemes) { g_custom_schemes = JoinString(schemes, ','); } AtomBrowserClient::AtomBrowserClient() { } AtomBrowserClient::~AtomBrowserClient() { } void AtomBrowserClient::RenderProcessWillLaunch( content::RenderProcessHost* host) { int process_id = host->GetID(); host->AddFilter(new printing::PrintingMessageFilter(process_id)); host->AddFilter(new TtsMessageFilter(process_id, host->GetBrowserContext())); } content::SpeechRecognitionManagerDelegate* AtomBrowserClient::CreateSpeechRecognitionManagerDelegate() { return new AtomSpeechRecognitionManagerDelegate; } content::AccessTokenStore* AtomBrowserClient::CreateAccessTokenStore() { return new AtomAccessTokenStore; } void AtomBrowserClient::OverrideWebkitPrefs( content::RenderViewHost* host, content::WebPreferences* prefs) { prefs->javascript_enabled = true; prefs->web_security_enabled = true; prefs->javascript_can_open_windows_automatically = true; prefs->plugins_enabled = true; prefs->dom_paste_enabled = true; prefs->java_enabled = false; prefs->allow_scripts_to_close_windows = true; prefs->javascript_can_access_clipboard = true; prefs->local_storage_enabled = true; prefs->databases_enabled = true; prefs->application_cache_enabled = true; prefs->allow_universal_access_from_file_urls = true; prefs->allow_file_access_from_file_urls = true; prefs->experimental_webgl_enabled = true; prefs->allow_displaying_insecure_content = false; prefs->allow_running_insecure_content = false; // Custom preferences of guest page. auto web_contents = content::WebContents::FromRenderViewHost(host); WebViewManager::WebViewInfo info; if (WebViewManager::GetInfoForWebContents(web_contents, &info)) { prefs->web_security_enabled = !info.disable_web_security; return; } NativeWindow* window = NativeWindow::FromWebContents(web_contents); if (window) window->OverrideWebkitPrefs(prefs); } std::string AtomBrowserClient::GetApplicationLocale() { return l10n_util::GetApplicationLocale(""); } void AtomBrowserClient::OverrideSiteInstanceForNavigation( content::BrowserContext* browser_context, content::SiteInstance* current_instance, const GURL& url, content::SiteInstance** new_instance) { if (g_suppress_renderer_process_restart) { g_suppress_renderer_process_restart = false; return; } // Restart renderer process for all navigations except "javacript:" scheme. if (url.SchemeIs(url::kJavaScriptScheme)) return; *new_instance = content::SiteInstance::CreateForURL(browser_context, url); } void AtomBrowserClient::AppendExtraCommandLineSwitches( base::CommandLine* command_line, int process_id) { std::string process_type = command_line->GetSwitchValueASCII("type"); if (process_type != "renderer") return; // The registered standard schemes. if (!g_custom_schemes.empty()) command_line->AppendSwitchASCII(switches::kRegisterStandardSchemes, g_custom_schemes); #if defined(OS_WIN) // Append --app-user-model-id. PWSTR current_app_id; if (SUCCEEDED(GetCurrentProcessExplicitAppUserModelID(&current_app_id))) { command_line->AppendSwitchNative(switches::kAppUserModelId, current_app_id); CoTaskMemFree(current_app_id); } #endif NativeWindow* window; WebViewManager::WebViewInfo info; ProcessOwner owner = GetProcessOwner(process_id, &window, &info); if (owner == OWNER_NATIVE_WINDOW) { window->AppendExtraCommandLineSwitches(command_line); } else if (owner == OWNER_GUEST_WEB_CONTENTS) { command_line->AppendSwitchASCII( switches::kGuestInstanceID, base::IntToString(info.guest_instance_id)); command_line->AppendSwitchASCII( switches::kNodeIntegration, info.node_integration ? "true" : "false"); if (info.plugins) command_line->AppendSwitch(switches::kEnablePlugins); if (!info.preload_script.empty()) command_line->AppendSwitchPath( switches::kPreloadScript, info.preload_script); } } void AtomBrowserClient::DidCreatePpapiPlugin( content::BrowserPpapiHost* host) { host->GetPpapiHost()->AddHostFactoryFilter( make_scoped_ptr(new chrome::ChromeBrowserPepperHostFactory(host))); } content::QuotaPermissionContext* AtomBrowserClient::CreateQuotaPermissionContext() { return new AtomQuotaPermissionContext; } void AtomBrowserClient::SelectClientCertificate( content::WebContents* web_contents, net::SSLCertRequestInfo* cert_request_info, scoped_ptr<content::ClientCertificateDelegate> delegate) { // --client-certificate=`path` auto cmd = base::CommandLine::ForCurrentProcess(); if (cmd->HasSwitch(switches::kClientCertificate)) { auto cert_path = cmd->GetSwitchValuePath(switches::kClientCertificate); auto certificate = ImportCertFromFile(cert_path); if (certificate.get()) delegate->ContinueWithCertificate(certificate.get()); return; } if (!cert_request_info->client_certs.empty()) Browser::Get()->ClientCertificateSelector(web_contents, cert_request_info, delegate.Pass()); } brightray::BrowserMainParts* AtomBrowserClient::OverrideCreateBrowserMainParts( const content::MainFunctionParams&) { v8::V8::Initialize(); // Init V8 before creating main parts. return new AtomBrowserMainParts; } } // namespace atom <|endoftext|>
<commit_before>/* Crystal Space utility library: string class Copyright (C) 1999,2000 by Andrew Zabolotny <bit@eltech.ru> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ extern "C" { #include <ctype.h> #include <stdarg.h> } #include "cssysdef.h" #include "csutil/csstring.h" #include "csutil/snprintf.h" csString::~csString () { Free (); } void csString::SetCapacity (size_t NewSize) { NewSize++; if (NewSize == MaxSize) return; MaxSize = NewSize; Data = (char *)realloc (Data, MaxSize); if (Size >= MaxSize) { Size = MaxSize - 1; Data [Size] = 0; } } csString &csString::Truncate (size_t iPos) { if (iPos < Size) { Size = iPos; Data [Size] = 0; } return *this; } csString &csString::DeleteAt (size_t iPos, size_t iCount) { #ifdef CS_DEBUG if (iPos > Size || iPos + iCount > Size) STR_FATAL (("Tried to delete characters beyond the end of the string!\n")) #endif memmove(Data + iPos, Data + iPos + iCount, Size - (iPos + iCount)); Size = Size - iCount; Data[Size] = 0; return *this; } csString &csString::Insert (size_t iPos, const csString &iStr) { #ifdef CS_DEBUG if (iPos > Size) STR_FATAL (("Inserting `%s' into `%s' at position %lu\n", iStr.GetData (), Data, (unsigned long)iPos)) #endif if (Data == NULL) { Append (iStr); return *this; } size_t sl = iStr.Length (); size_t NewSize = sl + Length (); if (NewSize >= MaxSize) SetCapacity (NewSize); memmove (Data + iPos + sl, Data + iPos, Size - iPos); memcpy (Data + iPos, iStr.GetData (), sl); Data [Size = NewSize] = 0; return *this; } csString &csString::Insert (size_t iPos, const char iChar) { #ifdef CS_DEBUG if (iPos > Size) STR_FATAL (("Inserting `%c' into `%s' at position %lu\n", iChar, Data, (unsigned long)iPos)) #endif if (Data == NULL) { Append (iChar); return *this; } size_t NewSize = 1 + Length (); if (NewSize >= MaxSize) SetCapacity (NewSize); memmove (Data + iPos + 1, Data + iPos, Size - iPos); Data[iPos] = iChar; Data [Size = NewSize] = 0; return *this; } csString &csString::Overwrite (size_t iPos, const csString &iStr) { #ifdef CS_DEBUG if (iPos > Size) STR_FATAL (("Overwriting `%s' into `%s' at position %lu\n", iStr.GetData (), Data, (unsigned long)iPos)) #endif if (Data == NULL) { Append (iStr); return *this; } size_t sl = iStr.Length (); size_t NewSize = iPos + sl; if (NewSize >= MaxSize) SetCapacity (NewSize); memcpy (Data + iPos, iStr.GetData (), sl); Data [Size = NewSize] = 0; return *this; } csString &csString::Append (const csString &iStr, size_t iCount) { if (iCount == (size_t)-1) iCount = iStr.Length (); if (!iCount) return *this; size_t NewSize = Size + iCount; if (NewSize >= MaxSize) SetCapacity (NewSize); memcpy (Data + Size, iStr.GetData (), iCount); Data [Size = NewSize] = 0; return *this; } csString &csString::Append (const char *iStr, size_t iCount) { if (!iStr) return *this; if (iCount == (size_t)-1) iCount = strlen (iStr); if (!iCount) return *this; size_t NewSize = Size + iCount; if (NewSize >= MaxSize) SetCapacity (NewSize); memcpy (Data + Size, iStr, iCount); Data [Size = NewSize] = 0; return *this; } csString &csString::LTrim() { size_t i; for (i = 0; i < Size; i++) { if (!isspace (Data[i])) return DeleteAt (0, i); } return *this; } csString &csString::RTrim() { if (Size == 0) return *this; int i; for(i = Size - 1; i >= 0; i--) { if (!isspace (Data[i])) { i++; return DeleteAt (i, Size - i); } } return *this; } csString &csString::Trim() { return LTrim().RTrim(); } csString &csString::Collapse() { if (Size == 0) return *this; size_t start = (size_t) -1; Trim(); size_t i; for (i = 1; i < Size - 1; i++) { if (isspace (Data[i])) { if (start==(size_t) -1) { start = i + 1; Data[i] = ' '; // Force 'space' as opposed to anything isspace()able. } } else { // Delete any extra whitespace if (start != (size_t)-1 && start != i) { DeleteAt (start, i - start); i -= i - start; } start = (size_t) -1; } } return *this; } csString &csString::Format(const char *format, ...) { va_list args; int NewSize = -1; va_start(args, format); // Keep trying until the buffer is big enough to hold the entire string while(NewSize < 0) { NewSize = cs_vsnprintf(Data, MaxSize, format, args); // Increasing by the size of the format streams seems logical enough if(NewSize < 0) SetCapacity(MaxSize + strlen(format)); // In this case we know what size it wants if((size_t) NewSize>=MaxSize) { SetCapacity(NewSize + 1); NewSize = -1; // Don't break the while loop just yet! } } // Add in the terminating NULL Size = NewSize + 1; va_end(args); return *this; } #define STR_FORMAT(TYPE,FMT,SZ) \ csString csString::Format (TYPE v) \ { char s[SZ]; cs_snprintf (s, SZ, #FMT, v); return csString ().Append (s); } STR_FORMAT(short, %hd, 32) STR_FORMAT(unsigned short, %hu, 32) STR_FORMAT(int, %d, 32) STR_FORMAT(unsigned int, %u, 32) STR_FORMAT(long, %ld, 32) STR_FORMAT(unsigned long, %lu, 32) STR_FORMAT(float, %g, 64) STR_FORMAT(double, %g, 64) #undef STR_FORMAT #define STR_FORMAT_INT(TYPE,FMT) \ csString csString::Format (TYPE v, int width, int prec/*=0*/) \ { char s[32], s1[32]; \ cs_snprintf (s1, 32, "%%%d.%d"#FMT, width, prec); cs_snprintf (s, 32, s1, v); \ return csString ().Append (s); } STR_FORMAT_INT(short, hd) STR_FORMAT_INT(unsigned short, hu) STR_FORMAT_INT(int, d) STR_FORMAT_INT(unsigned int, u) STR_FORMAT_INT(long, ld) STR_FORMAT_INT(unsigned long, lu) #undef STR_FORMAT_INT #define STR_FORMAT_FLOAT(TYPE) \ csString csString::Format (TYPE v, int width, int prec/*=6*/) \ { char s[64], s1[32]; \ cs_snprintf (s1, 32, "%%%d.%dg", width, prec); cs_snprintf (s, 64, s1, v); \ return csString ().Append (s); } STR_FORMAT_FLOAT(float) STR_FORMAT_FLOAT(double) #undef STR_FORMAT_FLOAT csString &csString::PadLeft (size_t iNewSize, char iChar) { if (Size < iNewSize) { SetCapacity (iNewSize); if (Size == 0) return *this; const size_t toInsert = iNewSize - Size; memmove (Data + toInsert, Data, Size); size_t x; for (x = 0; x < toInsert; x++) { Data [x] = iChar; } Data [iNewSize] = '\0'; Size = iNewSize; } return *this; } csString csString::AsPadLeft (size_t iNewSize, char iChar) { csString newStr = Clone (); newStr.PadLeft (iChar, iNewSize); return newStr; } #define STR_PADLEFT(TYPE) \ csString csString::PadLeft (TYPE v, size_t iNewSize, char iChar) \ { csString newStr; return newStr.Append (v).PadLeft (iNewSize, iChar); } STR_PADLEFT(const csString&) STR_PADLEFT(const char*) STR_PADLEFT(char) STR_PADLEFT(unsigned char) STR_PADLEFT(short) STR_PADLEFT(unsigned short) STR_PADLEFT(int) STR_PADLEFT(unsigned int) STR_PADLEFT(long) STR_PADLEFT(unsigned long) STR_PADLEFT(float) STR_PADLEFT(double) #if !defined(CS_USE_FAKE_BOOL_TYPE) STR_PADLEFT(bool) #endif #undef STR_PADLEFT csString& csString::PadRight (size_t iNewSize, char iChar) { if (Size < iNewSize) { SetCapacity (iNewSize); size_t x; for (x = Size; x < iNewSize; x++) Data [x] = iChar; Data [iNewSize] = '\0'; Size = iNewSize; } return *this; } csString csString::AsPadRight (size_t iNewSize, char iChar) { csString newStr = Clone (); newStr.PadRight (iChar, iNewSize); return newStr; } #define STR_PADRIGHT(TYPE) \ csString csString::PadRight (TYPE v, size_t iNewSize, char iChar) \ { csString newStr; return newStr.Append (v).PadRight (iNewSize, iChar); } STR_PADRIGHT(const csString&) STR_PADRIGHT(const char*) STR_PADRIGHT(char) STR_PADRIGHT(unsigned char) STR_PADRIGHT(short) STR_PADRIGHT(unsigned short) STR_PADRIGHT(int) STR_PADRIGHT(unsigned int) STR_PADRIGHT(long) STR_PADRIGHT(unsigned long) STR_PADRIGHT(float) STR_PADRIGHT(double) #if !defined(CS_USE_FAKE_BOOL_TYPE) STR_PADRIGHT(bool) #endif #undef STR_PADRIGHT csString& csString::PadCenter (size_t iNewSize, char iChar) { if (Size < iNewSize) { SetCapacity (iNewSize); if (Size == 0) return *this; const size_t toInsert = iNewSize - Size; memmove (Data + toInsert / 2 + toInsert % 2, Data, Size); size_t x; for (x = 0; x < toInsert / 2 + toInsert % 2; x++) { Data [x] = iChar; } for (x = iNewSize - toInsert / 2; x < iNewSize; x++) { Data [x] = iChar; } Data [iNewSize] = '\0'; Size = iNewSize; } return *this; } csString csString::AsPadCenter (size_t iNewSize, char iChar) { csString newStr = Clone (); newStr.PadCenter (iChar, iNewSize); return newStr; } #define STR_PADCENTER(TYPE) \ csString csString::PadCenter (TYPE v, size_t iNewSize, char iChar) \ { csString newStr; return newStr.Append (v).PadCenter (iNewSize, iChar); } STR_PADCENTER(const csString&) STR_PADCENTER(const char*) STR_PADCENTER(char) STR_PADCENTER(unsigned char) STR_PADCENTER(short) STR_PADCENTER(unsigned short) STR_PADCENTER(int) STR_PADCENTER(unsigned int) STR_PADCENTER(long) STR_PADCENTER(unsigned long) STR_PADCENTER(float) STR_PADCENTER(double) #if !defined(CS_USE_FAKE_BOOL_TYPE) STR_PADCENTER(bool) #endif #undef STR_PADCENTER <commit_msg>Reverted nonworking sprintf()-to-cs_snprintf() changes to Format() methods.<commit_after>/* Crystal Space utility library: string class Copyright (C) 1999,2000 by Andrew Zabolotny <bit@eltech.ru> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ extern "C" { #include <ctype.h> #include <stdarg.h> } #include "cssysdef.h" #include "csutil/csstring.h" #include "csutil/snprintf.h" csString::~csString () { Free (); } void csString::SetCapacity (size_t NewSize) { NewSize++; if (NewSize == MaxSize) return; MaxSize = NewSize; Data = (char *)realloc (Data, MaxSize); if (Size >= MaxSize) { Size = MaxSize - 1; Data [Size] = 0; } } csString &csString::Truncate (size_t iPos) { if (iPos < Size) { Size = iPos; Data [Size] = 0; } return *this; } csString &csString::DeleteAt (size_t iPos, size_t iCount) { #ifdef CS_DEBUG if (iPos > Size || iPos + iCount > Size) STR_FATAL (("Tried to delete characters beyond the end of the string!\n")) #endif memmove(Data + iPos, Data + iPos + iCount, Size - (iPos + iCount)); Size = Size - iCount; Data[Size] = 0; return *this; } csString &csString::Insert (size_t iPos, const csString &iStr) { #ifdef CS_DEBUG if (iPos > Size) STR_FATAL (("Inserting `%s' into `%s' at position %lu\n", iStr.GetData (), Data, (unsigned long)iPos)) #endif if (Data == NULL) { Append (iStr); return *this; } size_t sl = iStr.Length (); size_t NewSize = sl + Length (); if (NewSize >= MaxSize) SetCapacity (NewSize); memmove (Data + iPos + sl, Data + iPos, Size - iPos); memcpy (Data + iPos, iStr.GetData (), sl); Data [Size = NewSize] = 0; return *this; } csString &csString::Insert (size_t iPos, const char iChar) { #ifdef CS_DEBUG if (iPos > Size) STR_FATAL (("Inserting `%c' into `%s' at position %lu\n", iChar, Data, (unsigned long)iPos)) #endif if (Data == NULL) { Append (iChar); return *this; } size_t NewSize = 1 + Length (); if (NewSize >= MaxSize) SetCapacity (NewSize); memmove (Data + iPos + 1, Data + iPos, Size - iPos); Data[iPos] = iChar; Data [Size = NewSize] = 0; return *this; } csString &csString::Overwrite (size_t iPos, const csString &iStr) { #ifdef CS_DEBUG if (iPos > Size) STR_FATAL (("Overwriting `%s' into `%s' at position %lu\n", iStr.GetData (), Data, (unsigned long)iPos)) #endif if (Data == NULL) { Append (iStr); return *this; } size_t sl = iStr.Length (); size_t NewSize = iPos + sl; if (NewSize >= MaxSize) SetCapacity (NewSize); memcpy (Data + iPos, iStr.GetData (), sl); Data [Size = NewSize] = 0; return *this; } csString &csString::Append (const csString &iStr, size_t iCount) { if (iCount == (size_t)-1) iCount = iStr.Length (); if (!iCount) return *this; size_t NewSize = Size + iCount; if (NewSize >= MaxSize) SetCapacity (NewSize); memcpy (Data + Size, iStr.GetData (), iCount); Data [Size = NewSize] = 0; return *this; } csString &csString::Append (const char *iStr, size_t iCount) { if (!iStr) return *this; if (iCount == (size_t)-1) iCount = strlen (iStr); if (!iCount) return *this; size_t NewSize = Size + iCount; if (NewSize >= MaxSize) SetCapacity (NewSize); memcpy (Data + Size, iStr, iCount); Data [Size = NewSize] = 0; return *this; } csString &csString::LTrim() { size_t i; for (i = 0; i < Size; i++) { if (!isspace (Data[i])) return DeleteAt (0, i); } return *this; } csString &csString::RTrim() { if (Size == 0) return *this; int i; for(i = Size - 1; i >= 0; i--) { if (!isspace (Data[i])) { i++; return DeleteAt (i, Size - i); } } return *this; } csString &csString::Trim() { return LTrim().RTrim(); } csString &csString::Collapse() { if (Size == 0) return *this; size_t start = (size_t) -1; Trim(); size_t i; for (i = 1; i < Size - 1; i++) { if (isspace (Data[i])) { if (start==(size_t) -1) { start = i + 1; Data[i] = ' '; // Force 'space' as opposed to anything isspace()able. } } else { // Delete any extra whitespace if (start != (size_t)-1 && start != i) { DeleteAt (start, i - start); i -= i - start; } start = (size_t) -1; } } return *this; } csString &csString::Format(const char *format, ...) { va_list args; int NewSize = -1; va_start(args, format); // Keep trying until the buffer is big enough to hold the entire string while(NewSize < 0) { NewSize = cs_vsnprintf(Data, MaxSize, format, args); // Increasing by the size of the format streams seems logical enough if(NewSize < 0) SetCapacity(MaxSize + strlen(format)); // In this case we know what size it wants if((size_t) NewSize>=MaxSize) { SetCapacity(NewSize + 1); NewSize = -1; // Don't break the while loop just yet! } } // Add in the terminating NULL Size = NewSize + 1; va_end(args); return *this; } #define STR_FORMAT(TYPE,FMT,SZ) \ csString csString::Format (TYPE v) \ { char s[SZ]; sprintf (s, #FMT, v); return csString ().Append (s); } STR_FORMAT(short, %hd, 32) STR_FORMAT(unsigned short, %hu, 32) STR_FORMAT(int, %d, 32) STR_FORMAT(unsigned int, %u, 32) STR_FORMAT(long, %ld, 32) STR_FORMAT(unsigned long, %lu, 32) STR_FORMAT(float, %g, 64) STR_FORMAT(double, %g, 64) #undef STR_FORMAT #define STR_FORMAT_INT(TYPE,FMT) \ csString csString::Format (TYPE v, int width, int prec/*=0*/) \ { char s[32], s1[32]; \ sprintf (s1, "%%%d.%d"#FMT, width, prec); sprintf (s, s1, v); \ return csString ().Append (s); } STR_FORMAT_INT(short, hd) STR_FORMAT_INT(unsigned short, hu) STR_FORMAT_INT(int, d) STR_FORMAT_INT(unsigned int, u) STR_FORMAT_INT(long, ld) STR_FORMAT_INT(unsigned long, lu) #undef STR_FORMAT_INT #define STR_FORMAT_FLOAT(TYPE) \ csString csString::Format (TYPE v, int width, int prec/*=6*/) \ { char s[64], s1[32]; \ sprintf (s1, "%%%d.%dg", width, prec); sprintf (s, s1, v); \ return csString ().Append (s); } STR_FORMAT_FLOAT(float) STR_FORMAT_FLOAT(double) #undef STR_FORMAT_FLOAT csString &csString::PadLeft (size_t iNewSize, char iChar) { if (Size < iNewSize) { SetCapacity (iNewSize); if (Size == 0) return *this; const size_t toInsert = iNewSize - Size; memmove (Data + toInsert, Data, Size); size_t x; for (x = 0; x < toInsert; x++) { Data [x] = iChar; } Data [iNewSize] = '\0'; Size = iNewSize; } return *this; } csString csString::AsPadLeft (size_t iNewSize, char iChar) { csString newStr = Clone (); newStr.PadLeft (iChar, iNewSize); return newStr; } #define STR_PADLEFT(TYPE) \ csString csString::PadLeft (TYPE v, size_t iNewSize, char iChar) \ { csString newStr; return newStr.Append (v).PadLeft (iNewSize, iChar); } STR_PADLEFT(const csString&) STR_PADLEFT(const char*) STR_PADLEFT(char) STR_PADLEFT(unsigned char) STR_PADLEFT(short) STR_PADLEFT(unsigned short) STR_PADLEFT(int) STR_PADLEFT(unsigned int) STR_PADLEFT(long) STR_PADLEFT(unsigned long) STR_PADLEFT(float) STR_PADLEFT(double) #if !defined(CS_USE_FAKE_BOOL_TYPE) STR_PADLEFT(bool) #endif #undef STR_PADLEFT csString& csString::PadRight (size_t iNewSize, char iChar) { if (Size < iNewSize) { SetCapacity (iNewSize); size_t x; for (x = Size; x < iNewSize; x++) Data [x] = iChar; Data [iNewSize] = '\0'; Size = iNewSize; } return *this; } csString csString::AsPadRight (size_t iNewSize, char iChar) { csString newStr = Clone (); newStr.PadRight (iChar, iNewSize); return newStr; } #define STR_PADRIGHT(TYPE) \ csString csString::PadRight (TYPE v, size_t iNewSize, char iChar) \ { csString newStr; return newStr.Append (v).PadRight (iNewSize, iChar); } STR_PADRIGHT(const csString&) STR_PADRIGHT(const char*) STR_PADRIGHT(char) STR_PADRIGHT(unsigned char) STR_PADRIGHT(short) STR_PADRIGHT(unsigned short) STR_PADRIGHT(int) STR_PADRIGHT(unsigned int) STR_PADRIGHT(long) STR_PADRIGHT(unsigned long) STR_PADRIGHT(float) STR_PADRIGHT(double) #if !defined(CS_USE_FAKE_BOOL_TYPE) STR_PADRIGHT(bool) #endif #undef STR_PADRIGHT csString& csString::PadCenter (size_t iNewSize, char iChar) { if (Size < iNewSize) { SetCapacity (iNewSize); if (Size == 0) return *this; const size_t toInsert = iNewSize - Size; memmove (Data + toInsert / 2 + toInsert % 2, Data, Size); size_t x; for (x = 0; x < toInsert / 2 + toInsert % 2; x++) { Data [x] = iChar; } for (x = iNewSize - toInsert / 2; x < iNewSize; x++) { Data [x] = iChar; } Data [iNewSize] = '\0'; Size = iNewSize; } return *this; } csString csString::AsPadCenter (size_t iNewSize, char iChar) { csString newStr = Clone (); newStr.PadCenter (iChar, iNewSize); return newStr; } #define STR_PADCENTER(TYPE) \ csString csString::PadCenter (TYPE v, size_t iNewSize, char iChar) \ { csString newStr; return newStr.Append (v).PadCenter (iNewSize, iChar); } STR_PADCENTER(const csString&) STR_PADCENTER(const char*) STR_PADCENTER(char) STR_PADCENTER(unsigned char) STR_PADCENTER(short) STR_PADCENTER(unsigned short) STR_PADCENTER(int) STR_PADCENTER(unsigned int) STR_PADCENTER(long) STR_PADCENTER(unsigned long) STR_PADCENTER(float) STR_PADCENTER(double) #if !defined(CS_USE_FAKE_BOOL_TYPE) STR_PADCENTER(bool) #endif #undef STR_PADCENTER <|endoftext|>
<commit_before><commit_msg>glTF: Removing one model breaks an other model<commit_after><|endoftext|>
<commit_before><commit_msg>GSOC work, small code fixes<commit_after><|endoftext|>
<commit_before><commit_msg>Isilon: don't warn for multiple remote parquet blocks<commit_after><|endoftext|>
<commit_before>98526ebc-2e4d-11e5-9284-b827eb9e62be<commit_msg>98576732-2e4d-11e5-9284-b827eb9e62be<commit_after>98576732-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>c6f9a4ca-2e4c-11e5-9284-b827eb9e62be<commit_msg>c6fe962e-2e4c-11e5-9284-b827eb9e62be<commit_after>c6fe962e-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>39d42d3a-2e4d-11e5-9284-b827eb9e62be<commit_msg>39d9378a-2e4d-11e5-9284-b827eb9e62be<commit_after>39d9378a-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>40b584a4-2e4e-11e5-9284-b827eb9e62be<commit_msg>40bab88e-2e4e-11e5-9284-b827eb9e62be<commit_after>40bab88e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>36a97654-2e4f-11e5-9284-b827eb9e62be<commit_msg>36ae698e-2e4f-11e5-9284-b827eb9e62be<commit_after>36ae698e-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>be5a46e2-2e4e-11e5-9284-b827eb9e62be<commit_msg>be5f60aa-2e4e-11e5-9284-b827eb9e62be<commit_after>be5f60aa-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>0252ef48-2e4f-11e5-9284-b827eb9e62be<commit_msg>0257e99e-2e4f-11e5-9284-b827eb9e62be<commit_after>0257e99e-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>e4cf7a22-2e4e-11e5-9284-b827eb9e62be<commit_msg>e4d48ae4-2e4e-11e5-9284-b827eb9e62be<commit_after>e4d48ae4-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>01db4f38-2e4f-11e5-9284-b827eb9e62be<commit_msg>01e04222-2e4f-11e5-9284-b827eb9e62be<commit_after>01e04222-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>3ddb4020-2e4e-11e5-9284-b827eb9e62be<commit_msg>3de0513c-2e4e-11e5-9284-b827eb9e62be<commit_after>3de0513c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>8ea796e4-2e4d-11e5-9284-b827eb9e62be<commit_msg>8eacec0c-2e4d-11e5-9284-b827eb9e62be<commit_after>8eacec0c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>da75e2f0-2e4e-11e5-9284-b827eb9e62be<commit_msg>da7af010-2e4e-11e5-9284-b827eb9e62be<commit_after>da7af010-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>2df49da4-2e4f-11e5-9284-b827eb9e62be<commit_msg>2df9934a-2e4f-11e5-9284-b827eb9e62be<commit_after>2df9934a-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>f25c3e82-2e4e-11e5-9284-b827eb9e62be<commit_msg>f26135a4-2e4e-11e5-9284-b827eb9e62be<commit_after>f26135a4-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>8e705dfa-2e4d-11e5-9284-b827eb9e62be<commit_msg>8e756110-2e4d-11e5-9284-b827eb9e62be<commit_after>8e756110-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>ce228b18-2e4c-11e5-9284-b827eb9e62be<commit_msg>ce278064-2e4c-11e5-9284-b827eb9e62be<commit_after>ce278064-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>a173f768-2e4d-11e5-9284-b827eb9e62be<commit_msg>a178eb88-2e4d-11e5-9284-b827eb9e62be<commit_after>a178eb88-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>c7f8d3d2-2e4c-11e5-9284-b827eb9e62be<commit_msg>c7fdcfb8-2e4c-11e5-9284-b827eb9e62be<commit_after>c7fdcfb8-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>c3d426e4-2e4c-11e5-9284-b827eb9e62be<commit_msg>c3d91712-2e4c-11e5-9284-b827eb9e62be<commit_after>c3d91712-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>c6102b0e-2e4e-11e5-9284-b827eb9e62be<commit_msg>c61520fa-2e4e-11e5-9284-b827eb9e62be<commit_after>c61520fa-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>17ac8a04-2e4d-11e5-9284-b827eb9e62be<commit_msg>17b19792-2e4d-11e5-9284-b827eb9e62be<commit_after>17b19792-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>aac5277a-2e4c-11e5-9284-b827eb9e62be<commit_msg>aaca1802-2e4c-11e5-9284-b827eb9e62be<commit_after>aaca1802-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>bef39118-2e4d-11e5-9284-b827eb9e62be<commit_msg>bef88632-2e4d-11e5-9284-b827eb9e62be<commit_after>bef88632-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>84f476f8-2e4d-11e5-9284-b827eb9e62be<commit_msg>84f974dc-2e4d-11e5-9284-b827eb9e62be<commit_after>84f974dc-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>9cdb5c32-2e4d-11e5-9284-b827eb9e62be<commit_msg>9ce052f0-2e4d-11e5-9284-b827eb9e62be<commit_after>9ce052f0-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>b4f98aec-2e4c-11e5-9284-b827eb9e62be<commit_msg>b4fe942e-2e4c-11e5-9284-b827eb9e62be<commit_after>b4fe942e-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>f8d5142a-2e4c-11e5-9284-b827eb9e62be<commit_msg>f8da1a38-2e4c-11e5-9284-b827eb9e62be<commit_after>f8da1a38-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>33b715b0-2e4e-11e5-9284-b827eb9e62be<commit_msg>33bc1150-2e4e-11e5-9284-b827eb9e62be<commit_after>33bc1150-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>18dfd9b0-2e4f-11e5-9284-b827eb9e62be<commit_msg>18e4e798-2e4f-11e5-9284-b827eb9e62be<commit_after>18e4e798-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>88b71656-2e4d-11e5-9284-b827eb9e62be<commit_msg>88bc0d3c-2e4d-11e5-9284-b827eb9e62be<commit_after>88bc0d3c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>0837d8f6-2e4f-11e5-9284-b827eb9e62be<commit_msg>083cdf22-2e4f-11e5-9284-b827eb9e62be<commit_after>083cdf22-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>7ab45d66-2e4d-11e5-9284-b827eb9e62be<commit_msg>7ab94772-2e4d-11e5-9284-b827eb9e62be<commit_after>7ab94772-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>c90349b8-2e4e-11e5-9284-b827eb9e62be<commit_msg>c908485a-2e4e-11e5-9284-b827eb9e62be<commit_after>c908485a-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>c3bbb5bc-2e4e-11e5-9284-b827eb9e62be<commit_msg>c3c0ac8e-2e4e-11e5-9284-b827eb9e62be<commit_after>c3c0ac8e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>ba5c7f06-2e4e-11e5-9284-b827eb9e62be<commit_msg>ba618fc8-2e4e-11e5-9284-b827eb9e62be<commit_after>ba618fc8-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>312f327e-2e4d-11e5-9284-b827eb9e62be<commit_msg>313431a2-2e4d-11e5-9284-b827eb9e62be<commit_after>313431a2-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>fdac55c4-2e4e-11e5-9284-b827eb9e62be<commit_msg>fdb2128e-2e4e-11e5-9284-b827eb9e62be<commit_after>fdb2128e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>d9ef4570-2e4d-11e5-9284-b827eb9e62be<commit_msg>d9f44548-2e4d-11e5-9284-b827eb9e62be<commit_after>d9f44548-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>9439950c-2e4e-11e5-9284-b827eb9e62be<commit_msg>943e905c-2e4e-11e5-9284-b827eb9e62be<commit_after>943e905c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>#include <JointPythonCore.h> #include <memory> #include <string> #include <binding/Binding.hpp> #include <pyjoint/Array.hpp> #include <pyjoint/Globals.hpp> #include <pyjoint/InterfaceDescriptor.hpp> #include <pyjoint/Module.hpp> #include <pyjoint/ProxyBase.hpp> #include <pyjoint/TypeDescriptor.hpp> #include <utils/PyObjectHolder.hpp> JOINT_DEVKIT_LOGGER("Joint.Python.Core") extern "C" { Joint_Error JointPythonCore_MakeBinding(Joint_BindingHandle* outBinding) { using namespace joint_python::binding; GetLogger().Info() << "MakeBinding"; Joint_BindingDesc binding_desc = { }; binding_desc.name = "python"; binding_desc.deinitBinding = &Binding::Deinit; binding_desc.loadModule = &Binding::LoadModule; binding_desc.unloadModule = &Binding::UnloadModule; binding_desc.getRootObject = &Binding::GetRootObject; binding_desc.invokeMethod = &Binding::InvokeMethod; binding_desc.releaseObject = &Binding::ReleaseObject; binding_desc.castObject = &Binding::CastObject; std::unique_ptr<Binding> binding(new Binding); Joint_Error ret = Joint_MakeBinding(binding_desc, binding.get(), outBinding); if (ret != JOINT_ERROR_NONE) GetLogger().Error() << "Joint_MakeBinding failed: " << ret; else binding.release(); return ret; } } static PyMethodDef g_methods[] = { {"Cast", (PyCFunction)joint_python::pyjoint::Cast, METH_VARARGS, "Cast" }, {NULL, NULL, 0, NULL} }; #if PY_VERSION_HEX >= 0x03000000 static struct PyModuleDef g_module = { # if PY_VERSION_HEX >= 0x03020000 PyModuleDef_HEAD_INIT, # else { PyObject_HEAD_INIT(NULL) NULL, /* m_init */ 0, /* m_index */ NULL, /* m_copy */ }, # endif "pyjoint", NULL, -1, g_methods }; #endif #define ADD_TYPE_TO_PYTHON_MODULE(Type_) \ if (!Type_##_type.tp_new) \ Type_##_type.tp_new = PyType_GenericNew; \ if (PyType_Ready(&Type_##_type) < 0) \ { \ PyErr_SetString(PyExc_RuntimeError, "Import error: Could not initialize pyjoint." #Type_ " type!"); \ RETURN_ERROR; \ } \ Py_INCREF(&Type_##_type); \ if (PyModule_AddObject(m, #Type_, reinterpret_cast<PyObject*>(&Type_##_type)) != 0) \ { \ Py_DECREF(&Type_##_type); \ PyErr_SetString(PyExc_RuntimeError, "Import error: Could not add pyjoint." #Type_ " type to the module!"); \ RETURN_ERROR; \ } #if PY_VERSION_HEX >= 0x03000000 # define STR_LITERAL_TYPE const char* # define RETURN_ERROR return NULL PyMODINIT_FUNC JointPythonCore_InitModule_py3(void) #else # define STR_LITERAL_TYPE char* # define RETURN_ERROR return PyMODINIT_FUNC JointPythonCore_InitModule_py2(void) #endif { using namespace joint_python; using namespace joint_python::pyjoint; #if PY_VERSION_HEX >= 0x03000000 PyObjectHolder m(PyModule_Create(&g_module)); #else PyObjectHolder m(Py_InitModule((STR_LITERAL_TYPE) "pyjoint", g_methods)); #endif if (!m) { PyErr_SetString(PyExc_RuntimeError, "Import error: Could not initialize module object!"); RETURN_ERROR; } ADD_TYPE_TO_PYTHON_MODULE(Array); ADD_TYPE_TO_PYTHON_MODULE(InterfaceDescriptor); ADD_TYPE_TO_PYTHON_MODULE(JointException); ADD_TYPE_TO_PYTHON_MODULE(Module); ADD_TYPE_TO_PYTHON_MODULE(ProxyBase); ADD_TYPE_TO_PYTHON_MODULE(TypeDescriptor); InvalidInterfaceChecksumException = PyErr_NewException("pyjoint.InvalidInterfaceChecksumException", NULL, NULL); Py_INCREF(InvalidInterfaceChecksumException); PyModule_AddObject(m, "InvalidInterfaceChecksumException", InvalidInterfaceChecksumException); #if PY_VERSION_HEX >= 0x03000000 return m.Release(); #else m.Release(); #endif } <commit_msg>Fixed a warning<commit_after>#include <JointPythonCore.h> #include <memory> #include <string> #include <binding/Binding.hpp> #include <pyjoint/Array.hpp> #include <pyjoint/Globals.hpp> #include <pyjoint/InterfaceDescriptor.hpp> #include <pyjoint/Module.hpp> #include <pyjoint/ProxyBase.hpp> #include <pyjoint/TypeDescriptor.hpp> #include <utils/PyObjectHolder.hpp> JOINT_DEVKIT_LOGGER("Joint.Python.Core") extern "C" { Joint_Error JointPythonCore_MakeBinding(Joint_BindingHandle* outBinding) { using namespace joint_python::binding; GetLogger().Info() << "MakeBinding"; Joint_BindingDesc binding_desc = { }; binding_desc.name = "python"; binding_desc.deinitBinding = &Binding::Deinit; binding_desc.loadModule = &Binding::LoadModule; binding_desc.unloadModule = &Binding::UnloadModule; binding_desc.getRootObject = &Binding::GetRootObject; binding_desc.invokeMethod = &Binding::InvokeMethod; binding_desc.releaseObject = &Binding::ReleaseObject; binding_desc.castObject = &Binding::CastObject; std::unique_ptr<Binding> binding(new Binding); Joint_Error ret = Joint_MakeBinding(binding_desc, binding.get(), outBinding); if (ret != JOINT_ERROR_NONE) GetLogger().Error() << "Joint_MakeBinding failed: " << ret; else binding.release(); return ret; } } static PyMethodDef g_methods[] = { {"Cast", (PyCFunction)joint_python::pyjoint::Cast, METH_VARARGS, "Cast" }, {NULL, NULL, 0, NULL} }; #if PY_VERSION_HEX >= 0x03000000 static struct PyModuleDef g_module = { # if PY_VERSION_HEX >= 0x03020000 PyModuleDef_HEAD_INIT, # else { PyObject_HEAD_INIT(NULL) NULL, /* m_init */ 0, /* m_index */ NULL, /* m_copy */ }, # endif "pyjoint", NULL, -1, g_methods }; #endif #define ADD_TYPE_TO_PYTHON_MODULE(Type_) \ if (!Type_##_type.tp_new) \ Type_##_type.tp_new = PyType_GenericNew; \ if (PyType_Ready(&Type_##_type) < 0) \ { \ PyErr_SetString(PyExc_RuntimeError, "Import error: Could not initialize pyjoint." #Type_ " type!"); \ RETURN_ERROR; \ } \ Py_INCREF(&Type_##_type); \ if (PyModule_AddObject(m, #Type_, reinterpret_cast<PyObject*>(&Type_##_type)) != 0) \ { \ Py_DECREF(&Type_##_type); \ PyErr_SetString(PyExc_RuntimeError, "Import error: Could not add pyjoint." #Type_ " type to the module!"); \ RETURN_ERROR; \ } #if PY_VERSION_HEX >= 0x03000000 # define STR_LITERAL_TYPE const char* # define RETURN_ERROR return NULL PyMODINIT_FUNC JointPythonCore_InitModule_py3(void) #else # define STR_LITERAL_TYPE char* # define RETURN_ERROR return PyMODINIT_FUNC JointPythonCore_InitModule_py2(void) #endif { using namespace joint_python; using namespace joint_python::pyjoint; #if PY_VERSION_HEX >= 0x03000000 PyObjectHolder m(PyModule_Create(&g_module)); #else PyObjectHolder m(Py_InitModule((STR_LITERAL_TYPE) "pyjoint", g_methods)); #endif if (!m) { PyErr_SetString(PyExc_RuntimeError, "Import error: Could not initialize module object!"); RETURN_ERROR; } ADD_TYPE_TO_PYTHON_MODULE(Array); ADD_TYPE_TO_PYTHON_MODULE(InterfaceDescriptor); ADD_TYPE_TO_PYTHON_MODULE(JointException); ADD_TYPE_TO_PYTHON_MODULE(Module); ADD_TYPE_TO_PYTHON_MODULE(ProxyBase); ADD_TYPE_TO_PYTHON_MODULE(TypeDescriptor); InvalidInterfaceChecksumException = PyErr_NewException((STR_LITERAL_TYPE)"pyjoint.InvalidInterfaceChecksumException", NULL, NULL); Py_INCREF(InvalidInterfaceChecksumException); PyModule_AddObject(m, "InvalidInterfaceChecksumException", InvalidInterfaceChecksumException); #if PY_VERSION_HEX >= 0x03000000 return m.Release(); #else m.Release(); #endif } <|endoftext|>
<commit_before>cf5f4ad8-2e4d-11e5-9284-b827eb9e62be<commit_msg>cf6c7e38-2e4d-11e5-9284-b827eb9e62be<commit_after>cf6c7e38-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ // boost #include <boost/python.hpp> #include <boost/python/def.hpp> // mapnik #include <mapnik/geometry.hpp> void export_geometry() { using namespace boost::python; using mapnik::geometry_type; class_<geometry_type, boost::noncopyable>("GeometryType",no_init) .def("envelope",&geometry_type::envelope) // .def("__str__",&geometry_type::to_string) .def("type",&geometry_type::type) // TODO add other geometry_type methods ; } <commit_msg>+ use Geometry2d to be compatible<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ // boost #include <boost/python.hpp> #include <boost/python/def.hpp> // mapnik #include <mapnik/geometry.hpp> void export_geometry() { using namespace boost::python; using mapnik::geometry_type; class_<geometry_type, boost::noncopyable>("Geometry2d",no_init) .def("envelope",&geometry_type::envelope) // .def("__str__",&geometry_type::to_string) .def("type",&geometry_type::type) // TODO add other geometry_type methods ; } <|endoftext|>
<commit_before>f3ee05aa-2e4e-11e5-9284-b827eb9e62be<commit_msg>f3f311ee-2e4e-11e5-9284-b827eb9e62be<commit_after>f3f311ee-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>1c6b7d46-2e4f-11e5-9284-b827eb9e62be<commit_msg>1c708b24-2e4f-11e5-9284-b827eb9e62be<commit_after>1c708b24-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>/* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include "bistro/bistro/remote/RemoteWorker.h" DEFINE_int32( heartbeat_grace_period, 60, "Each remote worker tells us their heartbeat period. If the time since " "the last heartbeat exceeds that period, plus the grace period in seconds, " "the worker is marked unhealthy. Values below 1 get bumped to 1." ); DEFINE_int32( healthcheck_period, 60, "Every how many seconds should the scheduler send a healthcheck to each " "remote worker? Values below 1 get bumped to 1." ); DEFINE_int32( healthcheck_grace_period, 60, "If the time since we **sent** the last successful healthcheck exceeds " "healthcheck_period + healtcheck_grace_period, we mark the remote worker " "unhealthy. Values below 1 get bumped to 1." ); DEFINE_int32( lose_unhealthy_worker_after, 180, "If a remote worker is unhealthy for this many seconds, consider it lost. " "This means we decide that its tasks failed, and start to send it suicide " "commands. On startup, a scheduler waits for healthcheck_period + " "healthcheck_grace_period + worker_check_interval + " "lose_unhealthy_worker_after to ensure all live workers have connected " "before running tasks. This value should low enough to be tolerable but " "high enough that heavy worker load does not typically cause it to be lost. " "In particular, aim for over 2*healthcheck_period + worker_check_interval " "to avoid losing workers due to one missed healthcheck. Values below 1 " "get bumped to 1." ); DEFINE_int32(worker_check_interval, 5, "How often to check if a worker is due for a healthcheck, became unhealthy " "or lost, etc. Keep this low to keep worker state up-to-date. Checks have " "a cost for each worker, so large deployments will need to increase this. " "Values below 1 get bumped to 1." ); <commit_msg>Bump the default value of --lose_unhealthy_worker_after<commit_after>/* * Copyright (c) 2016, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include "bistro/bistro/remote/RemoteWorker.h" DEFINE_int32( heartbeat_grace_period, 60, "Each remote worker tells us their heartbeat period. If the time since " "the last heartbeat exceeds that period, plus the grace period in seconds, " "the worker is marked unhealthy. Values below 1 get bumped to 1." ); DEFINE_int32( healthcheck_period, 60, "Every how many seconds should the scheduler send a healthcheck to each " "remote worker? Values below 1 get bumped to 1." ); DEFINE_int32( healthcheck_grace_period, 60, "If the time since we **sent** the last successful healthcheck exceeds " "healthcheck_period + healtcheck_grace_period, we mark the remote worker " "unhealthy. Values below 1 get bumped to 1." ); DEFINE_int32( lose_unhealthy_worker_after, 500, "If a remote worker is unhealthy for this many seconds, consider it lost. " "This means we decide that its tasks failed, and start to send it suicide " "commands. On startup, a scheduler waits for lose_unhealthy_worker_after + " "healthcheck_period + healthcheck_grace_period + worker_check_interval + " "lose_unhealthy_worker_after + worker_suicide_* to ensure all live workers " "have connected before running tasks. This flag should low enough to keep " "this wait tolerable but high enough that heavy IO on workers does not " "cause them to be lost. In principle, a value over 2*healthcheck_period + " "4*heartbeat_period + 2*worker_check_interval should suffice, but in " "practice a higher safety factor reduces the frequency of restarts of a " "crash-looping worker, which in turn makes it less disruptive to reaching " "a worker-set consensus among the other workers -- see the note on worker " "turnover in README.worker_set_consensus. Values below 1 get bumped to 1." ); DEFINE_int32(worker_check_interval, 5, "How often to check if a worker is due for a healthcheck, became unhealthy " "or lost, etc. Keep this low to keep worker state up-to-date. Checks have " "a cost for each worker, so large deployments will need to increase this. " "Values below 1 get bumped to 1." ); <|endoftext|>
<commit_before>1fb043ee-2e4d-11e5-9284-b827eb9e62be<commit_msg>1fb54736-2e4d-11e5-9284-b827eb9e62be<commit_after>1fb54736-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>335d148e-2e4e-11e5-9284-b827eb9e62be<commit_msg>33620994-2e4e-11e5-9284-b827eb9e62be<commit_after>33620994-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>fe5ee132-2e4c-11e5-9284-b827eb9e62be<commit_msg>fe63d70a-2e4c-11e5-9284-b827eb9e62be<commit_after>fe63d70a-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>b280c2ba-2e4e-11e5-9284-b827eb9e62be<commit_msg>b285b8a6-2e4e-11e5-9284-b827eb9e62be<commit_after>b285b8a6-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>5f5b7850-2e4e-11e5-9284-b827eb9e62be<commit_msg>5f607a9e-2e4e-11e5-9284-b827eb9e62be<commit_after>5f607a9e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>3ada85c6-2e4d-11e5-9284-b827eb9e62be<commit_msg>3adf8602-2e4d-11e5-9284-b827eb9e62be<commit_after>3adf8602-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>06edfebc-2e4f-11e5-9284-b827eb9e62be<commit_msg>06f2f7d2-2e4f-11e5-9284-b827eb9e62be<commit_after>06f2f7d2-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>ef0b31e8-2e4e-11e5-9284-b827eb9e62be<commit_msg>ef103940-2e4e-11e5-9284-b827eb9e62be<commit_after>ef103940-2e4e-11e5-9284-b827eb9e62be<|endoftext|>