text
stringlengths
54
60.6k
<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 "mcrouter/lib/WeightedChHashFuncBase.h" #include <glog/logging.h> #include <folly/dynamic.h> #include "mcrouter/lib/fbi/cpp/util.h" namespace facebook { namespace memcache { std::vector<double> WeightedChHashFuncBase::parseWeights( const folly::dynamic& json, size_t n) { std::vector<double> weights; checkLogic( json.isObject() && json.count("weights"), "WeightedChHashFunc: not an object or no weights"); checkLogic( json["weights"].isArray(), "WeightedChHashFunc: weights is not array"); const auto& jWeights = json["weights"]; LOG_IF(ERROR, jWeights.size() < n) << "WeightedChHashFunc: CONFIG IS BROKEN!!! number of weights (" << jWeights.size() << ") is smaller than number of servers (" << n << "). Missing weights are set to 0.5"; for (size_t i = 0; i < std::min(n, jWeights.size()); ++i) { const auto& weight = jWeights[i]; checkLogic(weight.isNumber(), "WeightedChHashFunc: weight is not number"); const auto weightNum = weight.asDouble(); checkLogic( 0 <= weightNum && weightNum <= 1.0, "WeightedChHashFunc: weight must be in range [0, 1.0]"); weights.push_back(weightNum); } weights.resize(n, 0.5); return weights; } } // namespace memcache } // namespace facebook <commit_msg>Avoid vector reallocation calls in WeightedChHashFuncBase::parseWeights - WDB cycles saving: 0.002%<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 "mcrouter/lib/WeightedChHashFuncBase.h" #include <glog/logging.h> #include <folly/dynamic.h> #include "mcrouter/lib/fbi/cpp/util.h" namespace facebook { namespace memcache { std::vector<double> WeightedChHashFuncBase::parseWeights( const folly::dynamic& json, size_t n) { std::vector<double> weights; weights.reserve(n); checkLogic( json.isObject() && json.count("weights"), "WeightedChHashFunc: not an object or no weights"); checkLogic( json["weights"].isArray(), "WeightedChHashFunc: weights is not array"); const auto& jWeights = json["weights"]; LOG_IF(ERROR, jWeights.size() < n) << "WeightedChHashFunc: CONFIG IS BROKEN!!! number of weights (" << jWeights.size() << ") is smaller than number of servers (" << n << "). Missing weights are set to 0.5"; for (size_t i = 0; i < std::min(n, jWeights.size()); ++i) { const auto& weight = jWeights[i]; checkLogic(weight.isNumber(), "WeightedChHashFunc: weight is not number"); const auto weightNum = weight.asDouble(); checkLogic( 0 <= weightNum && weightNum <= 1.0, "WeightedChHashFunc: weight must be in range [0, 1.0]"); weights.push_back(weightNum); } weights.resize(n, 0.5); return weights; } } // namespace memcache } // namespace facebook <|endoftext|>
<commit_before>#ifndef K3_RUNTIME_NETWORK_HPP #define K3_RUNTIME_NETWORK_HPP #include <ios> #include <queue> #include <system_error> #include <boost/asio.hpp> #include <boost/iostreams/categories.hpp> #include <boost/iostreams/stream.hpp> #include <boost/system/error_code.hpp> #include <boost/thread/thread.hpp> #include <external/nanomsg/nn.h> #include <external/nanomsg/pipeline.h> #include <external/nanomsg/tcp.h> #include <Common.hpp> class EndpointBuffer; using namespace boost::iostreams; using boost::thread_group; using std::bind; using std::endl; using std::cin; using std::cout; using std::cerr; namespace K3 { //------------------------------------------------- // Abstract base classes for low-level networking. template<typename NContext, typename Acceptor> class NEndpoint : public virtual LogMT { public: NEndpoint(const string& logId, shared_ptr<NContext> ctxt) : LogMT(logId) {} NEndpoint(const char* logId, shared_ptr<NContext> ctxt) : LogMT(logId) {} virtual Acceptor acceptor() = 0; virtual void close() = 0; }; template<typename NContext, typename Socket> class NConnection : public virtual LogMT { public: NConnection(const string& logId, shared_ptr<NContext> ctxt, Socket s) : LogMT(logId) {} NConnection(const char* logId, shared_ptr<NContext> ctxt, Socket s) : LogMT(logId) {} virtual Socket socket() = 0; virtual void close() = 0; virtual void write(shared_ptr<Value> ) = 0; // TODO //virtual bool has_write() = 0; }; //------------------------------------------------- // Boost ASIO low-level networking implementation. namespace Asio { using namespace boost::asio; // Boost implementation of a network context. class NContext { public: NContext() { service = shared_ptr<io_service>(new io_service()); service_threads = shared_ptr<thread_group>(new thread_group()); } NContext(size_t concurrency) { service = shared_ptr<io_service>(new io_service(concurrency)); service_threads = shared_ptr<thread_group>(new thread_group()); } NContext(shared_ptr<io_service> ios) : service(ios) {} void operator()() { if ( service ) { service->run();} } shared_ptr<io_service> service; shared_ptr<thread_group> service_threads; }; // Low-level endpoint class. This is a wrapper around a Boost tcp acceptor. class NEndpoint : public ::K3::NEndpoint<NContext, shared_ptr<ip::tcp::acceptor> > { public: typedef shared_ptr<ip::tcp::acceptor> Acceptor; NEndpoint(shared_ptr<NContext> ctxt, Address addr) : ::K3::NEndpoint<NContext, Acceptor>("NEndpoint", ctxt), LogMT("NEndpoint") { if ( ctxt ) { ip::tcp::endpoint ep(get<0>(addr), get<1>(addr)); acceptor_ = shared_ptr<ip::tcp::acceptor>(new ip::tcp::acceptor(*(ctxt->service), ep)); } else { logAt(boost::log::trivial::warning, "Invalid network context in constructing an NEndpoint"); } } Acceptor acceptor() { return acceptor_; } void close() { if ( acceptor_ ) { acceptor_->close(); } } protected: Acceptor acceptor_; }; // Low-level connection class. This is a wrapper around a Boost tcp socket. class NConnection : public ::K3::NConnection<NContext, shared_ptr<ip::tcp::socket> > { public: typedef shared_ptr<ip::tcp::socket> Socket; // null ptr for EndpointBuffer NConnection(shared_ptr<NContext> ctxt) : NConnection(ctxt, Socket(new ip::tcp::socket(*(ctxt->service)))) {} // null ptr for EndpointBuffer NConnection(shared_ptr<NContext> ctxt, Address addr) : NConnection(ctxt, Socket(new ip::tcp::socket(*(ctxt->service)))) { if ( ctxt ) { if ( socket_ ) { ip::tcp::endpoint ep(::std::get<0>(addr), ::std::get<1>(addr)); boost::system::error_code error; socket_->connect(ep, error); if (!error) { connected_ = true; //logAt(boost::log::trivial::warning, "connected"); //BOOST_LOG(*this) << "Connected! "; } else { BOOST_LOG(*this) << "Connect error: " << error.message(); throw std::runtime_error("Connect error"); } } else { logAt(boost::log::trivial::warning, "Uninitialized socket in constructing an NConnection"); } } else { logAt(boost::log::trivial::warning, "Invalid network context in constructing an NConnection"); } } Socket socket() { return socket_; } bool connected() { return connected_; } void close() { if ( socket_ ) { socket_->close(); } } void write(shared_ptr<Value> val) { // TODO switch to scoped locks // If the loop is already running, just add the message to the queue mut.lock(); if (busy) { while(buffer_->size() > 1000) { logAt(boost::log::trivial::trace, "Too many messages on outgoing queue: waiting..."); mut.unlock(); boost::this_thread::sleep_for( boost::chrono::seconds(1) ); mut.lock(); } buffer_->push(val); } // Otherwise, start the loop else { busy = true; async_write_loop(val); } mut.unlock(); } void async_write_loop(shared_ptr<Value> val) { size_t desired = val->length(); // Write the value out to the socket async_write(*socket_, boost::asio::buffer(*val, desired), [=](boost::system::error_code ec, size_t s) { // Capture the buffer in closure to keep its pointer count > 0 // until this callback has been executed shared_ptr<Value> keep_alive = val; // Check for errors: if (ec || (s != desired)) { BOOST_LOG(*(static_cast<LogMT*>(this))) << "Error on write: " << ec.message() << " wrote " << s << " out of " << desired << " bytes" << endl; } // Determine loop status: mut.lock(); // If the buffer is empty, terminate the loop for now. if (buffer_->empty()) { busy = false; } // Otherwise, pop the next value and recurse else { shared_ptr<Value> newval = buffer_->front(); buffer_->pop(); async_write_loop(newval); } mut.unlock(); }); } protected: NConnection(shared_ptr<NContext> ctxt, Socket s) : ::K3::NConnection<NContext, Socket>("NConnection", ctxt, s), LogMT("NConnection"), socket_(s), connected_(false), busy(false), buffer_(new std::queue<shared_ptr<Value>>()) {} // use mutex to operate on queues and busy atomically boost::mutex mut; bool busy; shared_ptr<std::queue<shared_ptr<Value>>> buffer_; Socket socket_; bool connected_; }; } //---------------------------------------------- // Nanomsg low-level networking implementation. // // Currently, this is a blocking implementation. namespace Nanomsg { class NContext { public: NContext() { listenerThreads = shared_ptr<thread_group>(new thread_group()); } // K3 Nanomsg endpoints use the TCP transport. string urlOfAddress(Address addr) { return string("tcp://") + addressAsString(addr); } shared_ptr<thread_group> listenerThreads; }; class NEndpoint : public ::K3::NEndpoint<NContext, int> { public: typedef int Acceptor; NEndpoint(shared_ptr<NContext> ctxt, Address addr) : ::K3::NEndpoint<NContext, Acceptor>("NEndpoint", ctxt), LogMT("NEndpoint"), socket_(nn_socket(AF_SP, NN_PULL)) { if ( ctxt && socket_ >= 0 ) { string bindAddr = ctxt->urlOfAddress(addr); int bDone = nn_bind(socket_, bindAddr.c_str()); if ( bDone < 0 ) { socket_ = -1; logAt(boost::log::trivial::error, string("Failed to bind endpoint to address ") + addressAsString(addr) + " : " + nn_strerror(nn_errno())); } } } Acceptor acceptor() { return socket_; } void close() { if ( socket_ >= 0 ) { int cDone = nn_close(socket_); if ( cDone < 0 ) { logAt(boost::log::trivial::error, string("Failed to close endpoint: ") + nn_strerror(nn_errno())); } } } protected: int socket_; }; class NConnection : public ::K3::NConnection<NContext, int> { public: typedef int Socket; NConnection(shared_ptr<NContext> ctxt) : NConnection(ctxt, nn_socket(AF_SP, NN_PUSH)) {} NConnection(shared_ptr<NContext> ctxt, Address addr) : NConnection(ctxt) { if ( ctxt && socket_ >= 0 ) { string connectAddr = ctxt->urlOfAddress(addr); int cDone = nn_connect(socket_, connectAddr.c_str()); if ( cDone < 0 ) { this->close(); logAt(boost::log::trivial::error, string("Failed to connect to address " + addressAsString(addr) + " : " + nn_strerror(nn_errno()))); } else { endpointId_ = cDone; } } } Socket socket() { return socket_; } void close() { if ( socket_ >= 0 ) { int cDone = nn_close(socket_); if ( cDone < 0 ) { logAt(boost::log::trivial::error, string("Failed to close connection: ") + nn_strerror(nn_errno())); } } } void write(const string& val) { size_t n = val.length(); int wDone = nn_send(socket_, &val, n, 0); if ( wDone < 0 ) { int err = nn_errno(); string errStr(nn_strerror(err)); logAt(boost::log::trivial::error, string("Failed to write to socket: " + errStr)); } return; } protected: NConnection(shared_ptr<NContext> ctxt, Socket s) : ::K3::NConnection<NContext, Socket>("NConnection", ctxt, s), LogMT("NConnection"), socket_(s) { if ( socket_ < 0 ) { logAt(boost::log::trivial::error, string("Failed in connection socket construction: ") + nn_strerror(nn_errno())); } } Socket socket_; int endpointId_; }; } //----------------------------------------- // Low-level networking library selection. namespace Net = K3::Asio; } #endif <commit_msg>Handle errors when binding to socket in Network.hpp<commit_after>#ifndef K3_RUNTIME_NETWORK_HPP #define K3_RUNTIME_NETWORK_HPP #include <ios> #include <queue> #include <thread> #include <chrono> #include <system_error> #include <boost/asio.hpp> #include <boost/iostreams/categories.hpp> #include <boost/iostreams/stream.hpp> #include <boost/system/error_code.hpp> #include <boost/thread/thread.hpp> #include <external/nanomsg/nn.h> #include <external/nanomsg/pipeline.h> #include <external/nanomsg/tcp.h> #include <Common.hpp> class EndpointBuffer; using namespace boost::iostreams; using boost::thread_group; using std::bind; using std::endl; using std::cin; using std::cout; using std::cerr; namespace K3 { //------------------------------------------------- // Abstract base classes for low-level networking. template<typename NContext, typename Acceptor> class NEndpoint : public virtual LogMT { public: NEndpoint(const string& logId, shared_ptr<NContext> ctxt) : LogMT(logId) {} NEndpoint(const char* logId, shared_ptr<NContext> ctxt) : LogMT(logId) {} virtual Acceptor acceptor() = 0; virtual void close() = 0; }; template<typename NContext, typename Socket> class NConnection : public virtual LogMT { public: NConnection(const string& logId, shared_ptr<NContext> ctxt, Socket s) : LogMT(logId) {} NConnection(const char* logId, shared_ptr<NContext> ctxt, Socket s) : LogMT(logId) {} virtual Socket socket() = 0; virtual void close() = 0; virtual void write(shared_ptr<Value> ) = 0; // TODO //virtual bool has_write() = 0; }; //------------------------------------------------- // Boost ASIO low-level networking implementation. namespace Asio { using namespace boost::asio; // Boost implementation of a network context. class NContext { public: NContext() { service = shared_ptr<io_service>(new io_service()); service_threads = shared_ptr<thread_group>(new thread_group()); } NContext(size_t concurrency) { service = shared_ptr<io_service>(new io_service(concurrency)); service_threads = shared_ptr<thread_group>(new thread_group()); } NContext(shared_ptr<io_service> ios) : service(ios) {} void operator()() { if ( service ) { service->run();} } shared_ptr<io_service> service; shared_ptr<thread_group> service_threads; }; // Low-level endpoint class. This is a wrapper around a Boost tcp acceptor. class NEndpoint : public ::K3::NEndpoint<NContext, shared_ptr<ip::tcp::acceptor> > { public: typedef shared_ptr<ip::tcp::acceptor> Acceptor; NEndpoint(shared_ptr<NContext> ctxt, Address addr) : ::K3::NEndpoint<NContext, Acceptor>("NEndpoint", ctxt), LogMT("NEndpoint") { if ( ctxt ) { ip::tcp::endpoint ep(get<0>(addr), get<1>(addr)); acceptor_ = shared_ptr<ip::tcp::acceptor>(new ip::tcp::acceptor(*(ctxt->service))); for(int retries=4; retries > 0; retries--) { try { acceptor_->open(ep.protocol()); boost::asio::socket_base::reuse_address option(true); acceptor_->set_option(option); acceptor_->bind(ep); acceptor_->listen(); break; } catch (std::exception e) { logAt(boost::log::trivial::warning, e.what()); if (retries > 1) { logAt(boost::log::trivial::warning, "Trying again in 30 seconds"); std::this_thread::sleep_for (std::chrono::seconds(30)); } else { logAt(boost::log::trivial::warning, "Aborting"); throw e; } } } } else { logAt(boost::log::trivial::warning, "Invalid network context in constructing an NEndpoint"); } } Acceptor acceptor() { return acceptor_; } void close() { if ( acceptor_ ) { acceptor_->close(); } } protected: Acceptor acceptor_; }; // Low-level connection class. This is a wrapper around a Boost tcp socket. class NConnection : public ::K3::NConnection<NContext, shared_ptr<ip::tcp::socket> > { public: typedef shared_ptr<ip::tcp::socket> Socket; // null ptr for EndpointBuffer NConnection(shared_ptr<NContext> ctxt) : NConnection(ctxt, Socket(new ip::tcp::socket(*(ctxt->service)))) {} // null ptr for EndpointBuffer NConnection(shared_ptr<NContext> ctxt, Address addr) : NConnection(ctxt, Socket(new ip::tcp::socket(*(ctxt->service)))) { if ( ctxt ) { if ( socket_ ) { ip::tcp::endpoint ep(::std::get<0>(addr), ::std::get<1>(addr)); boost::system::error_code error; socket_->connect(ep, error); if (!error) { connected_ = true; //logAt(boost::log::trivial::warning, "connected"); //BOOST_LOG(*this) << "Connected! "; } else { BOOST_LOG(*this) << "Connect error: " << error.message(); throw std::runtime_error("Connect error"); } } else { logAt(boost::log::trivial::warning, "Uninitialized socket in constructing an NConnection"); } } else { logAt(boost::log::trivial::warning, "Invalid network context in constructing an NConnection"); } } Socket socket() { return socket_; } bool connected() { return connected_; } void close() { if ( socket_ ) { socket_->close(); } } void write(shared_ptr<Value> val) { // TODO switch to scoped locks // If the loop is already running, just add the message to the queue mut.lock(); if (busy) { while(buffer_->size() > 1000) { logAt(boost::log::trivial::trace, "Too many messages on outgoing queue: waiting..."); mut.unlock(); boost::this_thread::sleep_for( boost::chrono::seconds(1) ); mut.lock(); } buffer_->push(val); } // Otherwise, start the loop else { busy = true; async_write_loop(val); } mut.unlock(); } void async_write_loop(shared_ptr<Value> val) { size_t desired = val->length(); // Write the value out to the socket async_write(*socket_, boost::asio::buffer(*val, desired), [=](boost::system::error_code ec, size_t s) { // Capture the buffer in closure to keep its pointer count > 0 // until this callback has been executed shared_ptr<Value> keep_alive = val; // Check for errors: if (ec || (s != desired)) { BOOST_LOG(*(static_cast<LogMT*>(this))) << "Error on write: " << ec.message() << " wrote " << s << " out of " << desired << " bytes" << endl; } // Determine loop status: mut.lock(); // If the buffer is empty, terminate the loop for now. if (buffer_->empty()) { busy = false; } // Otherwise, pop the next value and recurse else { shared_ptr<Value> newval = buffer_->front(); buffer_->pop(); async_write_loop(newval); } mut.unlock(); }); } protected: NConnection(shared_ptr<NContext> ctxt, Socket s) : ::K3::NConnection<NContext, Socket>("NConnection", ctxt, s), LogMT("NConnection"), socket_(s), connected_(false), busy(false), buffer_(new std::queue<shared_ptr<Value>>()) {} // use mutex to operate on queues and busy atomically boost::mutex mut; bool busy; shared_ptr<std::queue<shared_ptr<Value>>> buffer_; Socket socket_; bool connected_; }; } //---------------------------------------------- // Nanomsg low-level networking implementation. // // Currently, this is a blocking implementation. namespace Nanomsg { class NContext { public: NContext() { listenerThreads = shared_ptr<thread_group>(new thread_group()); } // K3 Nanomsg endpoints use the TCP transport. string urlOfAddress(Address addr) { return string("tcp://") + addressAsString(addr); } shared_ptr<thread_group> listenerThreads; }; class NEndpoint : public ::K3::NEndpoint<NContext, int> { public: typedef int Acceptor; NEndpoint(shared_ptr<NContext> ctxt, Address addr) : ::K3::NEndpoint<NContext, Acceptor>("NEndpoint", ctxt), LogMT("NEndpoint"), socket_(nn_socket(AF_SP, NN_PULL)) { if ( ctxt && socket_ >= 0 ) { string bindAddr = ctxt->urlOfAddress(addr); int bDone = nn_bind(socket_, bindAddr.c_str()); if ( bDone < 0 ) { socket_ = -1; logAt(boost::log::trivial::error, string("Failed to bind endpoint to address ") + addressAsString(addr) + " : " + nn_strerror(nn_errno())); } } } Acceptor acceptor() { return socket_; } void close() { if ( socket_ >= 0 ) { int cDone = nn_close(socket_); if ( cDone < 0 ) { logAt(boost::log::trivial::error, string("Failed to close endpoint: ") + nn_strerror(nn_errno())); } } } protected: int socket_; }; class NConnection : public ::K3::NConnection<NContext, int> { public: typedef int Socket; NConnection(shared_ptr<NContext> ctxt) : NConnection(ctxt, nn_socket(AF_SP, NN_PUSH)) {} NConnection(shared_ptr<NContext> ctxt, Address addr) : NConnection(ctxt) { if ( ctxt && socket_ >= 0 ) { string connectAddr = ctxt->urlOfAddress(addr); int cDone = nn_connect(socket_, connectAddr.c_str()); if ( cDone < 0 ) { this->close(); logAt(boost::log::trivial::error, string("Failed to connect to address " + addressAsString(addr) + " : " + nn_strerror(nn_errno()))); } else { endpointId_ = cDone; } } } Socket socket() { return socket_; } void close() { if ( socket_ >= 0 ) { int cDone = nn_close(socket_); if ( cDone < 0 ) { logAt(boost::log::trivial::error, string("Failed to close connection: ") + nn_strerror(nn_errno())); } } } void write(const string& val) { size_t n = val.length(); int wDone = nn_send(socket_, &val, n, 0); if ( wDone < 0 ) { int err = nn_errno(); string errStr(nn_strerror(err)); logAt(boost::log::trivial::error, string("Failed to write to socket: " + errStr)); } return; } protected: NConnection(shared_ptr<NContext> ctxt, Socket s) : ::K3::NConnection<NContext, Socket>("NConnection", ctxt, s), LogMT("NConnection"), socket_(s) { if ( socket_ < 0 ) { logAt(boost::log::trivial::error, string("Failed in connection socket construction: ") + nn_strerror(nn_errno())); } } Socket socket_; int endpointId_; }; } //----------------------------------------- // Low-level networking library selection. namespace Net = K3::Asio; } #endif <|endoftext|>
<commit_before>/****************************************************************************** * * * @file pcsc-client.cc * * @author Clément Désiles <clement.desiles@telecomsante.com> * * @date 2013/02/14 * * @licence MIT * * * *****************************************************************************/ #include "pcsc-client.h" #include <iostream> // Under Windows it is not defined #ifndef MAX_ATR_SIZE #define MAX_ATR_SIZE 33 #endif namespace PCSC { /** * Get the PCSC context * it's kind of initialization process */ int init_context( SCARDCONTEXT &hContext ) { LONG rv; // Establish context rv = SCardEstablishContext(SCARD_SCOPE_SYSTEM, NULL, NULL, &hContext); if (rv != SCARD_S_SUCCESS) { return ERROR_ESTABLISH_CXT; } // The Mac OS API is from PCSClite 1.4.x // PnP API was introduced in 1.6.x // So I will try not to use the API // Unfortunatly the API pre 1.6.x is nonblocking. // Which is different from the original windows API // // Check if Plug 'n play is supported #ifndef __APPLE__ SCARD_READERSTATE readerState[1]; readerState[0].szReader = "\\\\?PnP?\\Notification"; readerState[0].dwCurrentState = SCARD_STATE_UNAWARE; rv = SCardGetStatusChange(hContext, 0, readerState, 1); if (readerState[0].dwEventState & SCARD_STATE_UNKNOWN) { return ERROR_PNP; } #endif return CONTEXT_SET; } /** * Update the readers list and the associated readersState list * which loops over new readers states. */ int update_readers( SCARDCONTEXT &hContext, SCARD_READERSTATE *&readersState, v8::Persistent<v8::Object> &readers ){ LONG rv; DWORD dwReaders; #ifdef SCARD_AUTOALLOCATE dwReaders = SCARD_AUTOALLOCATE; #endif LPSTR mszReaders; LPTSTR ptr = NULL; int nbReaders = 0; int i = 0; // Check context rv = SCardIsValidContext(hContext); if (rv != SCARD_S_SUCCESS) { return ERROR_INVALID_CXT; } #ifndef SCARD_AUTOALLOCATE // Allocate buffer when autoallocate is not present rv = SCardListReaders(hContext, NULL, NULL, &dwReaders); mszReaders = static_cast<LPSTR>(new char[dwReaders]); #endif // Call with the real allocated buffer rv = SCardListReaders(hContext, NULL, mszReaders, &dwReaders); if(rv != SCARD_S_SUCCESS || mszReaders[0] == '\0') { readers = v8::Persistent<v8::Array>::New(v8::Array::New(0)); #ifdef SCARD_AUTOALLOCATE SCardFreeMemory(hContext, mszReaders); #else delete mszReaders; #endif return NO_READER_FOUND; } // Get number of readers from null separated string ptr = mszReaders; while(*ptr != '\0') { ptr += strlen(ptr)+1; nbReaders++; } // Allocate the ReaderStates table if(readersState) { free(readersState); } readersState = new SCARD_READERSTATE[nbReaders+1]; // +1 For the PnP Record // Create a new readers Array //readers = v8::Persistent<v8::Array>::New(v8::Array::New(nbReaders)); readers = v8::Persistent<v8::Object>::New(v8::Object::New()); // Read the readers structure ptr = mszReaders; for(i=0; i<nbReaders; i++) { // For js binding //readers->Set(v8::Number::New(i), v8::String::New(ptr)); readers->Set(v8::String::NewSymbol(ptr), v8::Undefined()); // Update readers state readersState[i].szReader = ptr; readersState[i].dwCurrentState = SCARD_STATE_UNAWARE; // Read up to next mszReader ptr += strlen(ptr)+1; } // To allow PnP #ifndef __APPLE__ readersState[nbReaders].szReader = "\\\\?PnP?\\Notification"; readersState[nbReaders].dwCurrentState = SCARD_STATE_UNAWARE; #endif #ifdef SCARD_AUTOALLOCATE // This is a Memory Leak, but mszReaders is needed until the end //SCardFreeMemory(hContext, mszReaders); #endif return READERS_UPDATED; } /** * On status change, call the appropriate * registered functions (if there are). */ int check_card_status( SCARDCONTEXT &hContext, SCARD_READERSTATE *&readersState, v8::Persistent<v8::Object> &readers, v8::Local<v8::Function> &callback ){ unsigned int i, k, nbReaders; DWORD evt; LONG rv; v8::Local<v8::String> status; char atr[MAX_ATR_SIZE*3+1]; char uid[30]; // Check context rv = SCardIsValidContext(hContext); if (rv != SCARD_S_SUCCESS) { // Debug purpose ONLY std::cout << "ERROR_INVALID_CXT" << std::endl; return ERROR_INVALID_CXT; } // Count readers nbReaders = readers->GetPropertyNames()->Length(); // Readers state has to be filled up by update_readers if ( !readersState || !nbReaders ) { std::cout << "NO_READER_FOUND" << std::endl; return NO_READER_FOUND; } // Check status rv = SCardGetStatusChange(hContext, INFINITE, readersState, nbReaders); if ((rv == SCARD_S_SUCCESS) || (static_cast<unsigned int>(rv) == SCARD_E_TIMEOUT)) { // Get the event issuer (card reader) for (i=0; i<nbReaders; i++) { evt = readersState[i].dwEventState; if (evt & SCARD_STATE_CHANGED) { // New state is now the current state readersState[i].dwCurrentState = evt; } else { // Nothing changed, then skip to the next reader continue; } // Reader id: i, reader name: readersState[i].szReader if(evt & SCARD_STATE_IGNORE) { status = v8::String::New("SCARD_STATE_IGNORE"); } else if(evt & SCARD_STATE_UNKNOWN) { status = v8::String::New("SCARD_STATE_UNKNOWN"); } else if(evt & SCARD_STATE_UNAVAILABLE) { status = v8::String::New("SCARD_STATE_UNAVAILABLE"); } else if(evt & SCARD_STATE_EMPTY) { status = v8::String::New("SCARD_STATE_EMPTY"); } else if(evt & SCARD_STATE_PRESENT) { status = v8::String::New("SCARD_STATE_PRESENT"); } else if(evt & SCARD_STATE_ATRMATCH) { status = v8::String::New("SCARD_STATE_ATRMATCH"); } else if(evt & SCARD_STATE_EXCLUSIVE) { status = v8::String::New("SCARD_STATE_EXCLUSIVE"); } else if(evt & SCARD_STATE_INUSE) { status = v8::String::New("SCARD_STATE_INUSE"); } else if(evt & SCARD_STATE_MUTE) { status = v8::String::New("SCARD_STATE_MUTE"); } // Prepare readerObject event // --------------------------- v8::Local<v8::Object> readerObj = v8::Object::New(); readerObj->Set(v8::String::NewSymbol("name"), readers->GetOwnPropertyNames()->Get(i)); readerObj->Set(v8::String::NewSymbol("status"), v8::Local<v8::Value>::New(status)); // Card object, will be eventually filled lateron v8::Local<v8::Object> cardObj = v8::Object::New(); // If a card is present prepare card event // ---------------------------------------- if(evt & SCARD_STATE_PRESENT) { // Dump the ATR if available if (readersState[i].cbAtr > 0) { if (readersState[i].cbAtr) { unsigned int j; for (j=0; j<readersState[i].cbAtr; j++) { sprintf(&atr[j*3], "%02X ", readersState[i].rgbAtr[j]); } atr[j*3-1] = '\0'; } else { atr[0] = '\0'; } cardObj->Set(v8::String::NewSymbol("ATR"), v8::String::New(atr)); } // Establishes a connection to a smart card contained by a specific reader. SCARDHANDLE hCard; DWORD activeProtocol; v8::String::Utf8Value readerName(readers->GetOwnPropertyNames()->Get(i)); rv = SCardConnect( hContext, // Resource manager handle (LPCSTR)*readerName, // Reader name SCARD_SHARE_SHARED, // Share Mode SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1, // Preferred protocols (T=0 or T=1) &hCard, // Returns the card handle &activeProtocol // Active protocol ); // Connect to the card reader // ---------------------------------------- if (rv == SCARD_S_SUCCESS) { // APDU exchange LPCSCARD_IO_REQUEST ioRequest; switch (activeProtocol) { case SCARD_PROTOCOL_T0: cardObj->Set(v8::String::NewSymbol("Protocol"), v8::String::New("T=0")); ioRequest = SCARD_PCI_T0; break; case SCARD_PROTOCOL_T1: cardObj->Set(v8::String::NewSymbol("Protocol"), v8::String::New("T=1")); ioRequest = SCARD_PCI_T1; break; default: ioRequest = SCARD_PCI_RAW; break; } // Pseudo ADPU to Retrieve card Serial Number (UID) BYTE pbRecvBuffer[10];//[10*1024]; // Max Card Size currently (2013) was: [256]; BYTE pbSendBuffer[] = { 0xFF, 0xCA, 0x00, 0x00, 0x00 }; SCARD_IO_REQUEST pioRecvPci; DWORD dwSendLength = sizeof(pbSendBuffer); DWORD dwRecvLength = sizeof(pbRecvBuffer); rv = SCardTransmit( hCard, // Card handle ioRequest, // Pointer to the sent protocol header pbSendBuffer, // Send buffer dwSendLength, // Send buffer length &pioRecvPci, // Pointer to the rec. protocol header pbRecvBuffer, // Receive buffer &dwRecvLength // Receive buffer length ); if (rv == SCARD_S_SUCCESS) { // Save UID if (dwRecvLength) { for (k = 0; k < dwRecvLength; k++) { sprintf(&uid[k*3], "%02X ", pbRecvBuffer[k]); } uid[k*3-1] = '\0'; cardObj->Set(v8::String::NewSymbol("UID_length"), v8::Number::New(dwRecvLength)); } else { uid[0] = '\0'; } cardObj->Set(v8::String::NewSymbol("UID"), v8::String::New(uid)); // Disconnect it right now SCardDisconnect( hCard, // Card handle. SCARD_UNPOWER_CARD ); } else { switch(rv) { case SCARD_E_INSUFFICIENT_BUFFER: cardObj->Set(v8::String::NewSymbol("err"), v8::String::New("SCARD_E_INSUFFICIENT_BUFFER")); break; case SCARD_E_INVALID_PARAMETER: cardObj->Set(v8::String::NewSymbol("err"), v8::String::New("SCARD_E_INVALID_PARAMETER")); break; case SCARD_E_INVALID_HANDLE: cardObj->Set(v8::String::NewSymbol("err"), v8::String::New("SCARD_E_INVALID_HANDLE")); break; case SCARD_E_INVALID_VALUE: cardObj->Set(v8::String::NewSymbol("err"), v8::String::New("SCARD_E_INVALID_VALUE")); break; case SCARD_E_NO_SERVICE: cardObj->Set(v8::String::NewSymbol("err"), v8::String::New("SCARD_E_NO_SERVICE")); break; case SCARD_E_NOT_TRANSACTED: cardObj->Set(v8::String::NewSymbol("err"), v8::String::New("SCARD_E_NOT_TRANSACTED")); break; case SCARD_E_PROTO_MISMATCH: cardObj->Set(v8::String::NewSymbol("err"), v8::String::New("SCARD_E_PROTO_MISMATCH")); break; case SCARD_E_READER_UNAVAILABLE: cardObj->Set(v8::String::NewSymbol("err"), v8::String::New("SCARD_E_READER_UNAVAILABLE")); break; case SCARD_F_COMM_ERROR: cardObj->Set(v8::String::NewSymbol("err"), v8::String::New("SCARD_F_COMM_ERROR")); break; case SCARD_W_RESET_CARD: cardObj->Set(v8::String::NewSymbol("err"), v8::String::New("SCARD_W_RESET_CARD")); break; case SCARD_W_REMOVED_CARD: cardObj->Set(v8::String::NewSymbol("err"), v8::String::New("SCARD_W_REMOVED_CARD")); break; } } } } // // Emit an event message // ---------------------- v8::Local<v8::Object> evtMsg = v8::Object::New(); evtMsg->Set(v8::String::NewSymbol("reader"), readerObj); evtMsg->Set(v8::String::NewSymbol("card"), cardObj); const unsigned argc = 1; v8::Local<v8::Value> argv[argc] = { evtMsg }; callback->Call(v8::Context::GetCurrent()->Global(), argc, argv); return STATUS_CHECKED; } } // Simple callback to request another check later on const int argc = 0; v8::Local<v8::Value> *argv = NULL; callback->Call(v8::Context::GetCurrent()->Global(), argc, argv); return STATUS_CHECKED; } /** * Release the PCSC context */ int release_context(SCARDCONTEXT &hContext) { return SCardReleaseContext(hContext); } } // <- end of namespace <commit_msg>It seems that the Linux environment does not like AUTOALLOCATE.<commit_after>/****************************************************************************** * * * @file pcsc-client.cc * * @author Clément Désiles <clement.desiles@telecomsante.com> * * @date 2013/02/14 * * @licence MIT * * * *****************************************************************************/ #include "pcsc-client.h" #include <iostream> // Under Windows it is not defined #ifndef MAX_ATR_SIZE #define MAX_ATR_SIZE 33 #endif namespace PCSC { /** * Get the PCSC context * it's kind of initialization process */ int init_context( SCARDCONTEXT &hContext ) { LONG rv; // Establish context rv = SCardEstablishContext(SCARD_SCOPE_SYSTEM, NULL, NULL, &hContext); if (rv != SCARD_S_SUCCESS) { return ERROR_ESTABLISH_CXT; } // The Mac OS API is from PCSClite 1.4.x // PnP API was introduced in 1.6.x // So I will try not to use the API // Unfortunatly the API pre 1.6.x is nonblocking. // Which is different from the original windows API // // Check if Plug 'n play is supported #ifndef __APPLE__ SCARD_READERSTATE readerState[1]; readerState[0].szReader = "\\\\?PnP?\\Notification"; readerState[0].dwCurrentState = SCARD_STATE_UNAWARE; rv = SCardGetStatusChange(hContext, 0, readerState, 1); if (readerState[0].dwEventState & SCARD_STATE_UNKNOWN) { return ERROR_PNP; } #endif return CONTEXT_SET; } /** * Update the readers list and the associated readersState list * which loops over new readers states. */ int update_readers( SCARDCONTEXT &hContext, SCARD_READERSTATE *&readersState, v8::Persistent<v8::Object> &readers ){ LONG rv; DWORD dwReaders; #ifdef DO_NOT_USE_SCARD_AUTOALLOCATE dwReaders = SCARD_AUTOALLOCATE; #endif LPSTR mszReaders; LPTSTR ptr = NULL; int nbReaders = 0; int i = 0; // Check context rv = SCardIsValidContext(hContext); if (rv != SCARD_S_SUCCESS) { return ERROR_INVALID_CXT; } #ifndef DO_NOT_USE_SCARD_AUTOALLOCATE // Allocate buffer when autoallocate is not present rv = SCardListReaders(hContext, NULL, NULL, &dwReaders); mszReaders = static_cast<LPSTR>(new char[dwReaders]); #endif // Call with the real allocated buffer rv = SCardListReaders(hContext, NULL, mszReaders, &dwReaders); if(rv != SCARD_S_SUCCESS || mszReaders[0] == '\0') { readers = v8::Persistent<v8::Array>::New(v8::Array::New(0)); #ifdef DO_NOT_USE_SCARD_AUTOALLOCATE SCardFreeMemory(hContext, mszReaders); #else delete [] mszReaders; #endif return NO_READER_FOUND; } // Get number of readers from null separated string ptr = mszReaders; while(*ptr != '\0') { ptr += strlen(ptr)+1; nbReaders++; } // Allocate the ReaderStates table if(readersState) { delete [] readersState; } readersState = new SCARD_READERSTATE[nbReaders+1]; // +1 For the PnP Record // Create a new readers Array //readers = v8::Persistent<v8::Array>::New(v8::Array::New(nbReaders)); readers = v8::Persistent<v8::Object>::New(v8::Object::New()); // Read the readers structure ptr = mszReaders; for(i=0; i<nbReaders; i++) { // For js binding //readers->Set(v8::Number::New(i), v8::String::New(ptr)); readers->Set(v8::String::NewSymbol(ptr), v8::Undefined()); // Update readers state readersState[i].szReader = ptr; readersState[i].dwCurrentState = SCARD_STATE_UNAWARE; // Read up to next mszReader ptr += strlen(ptr)+1; } // To allow PnP #ifndef __APPLE__ readersState[nbReaders].szReader = "\\\\?PnP?\\Notification"; readersState[nbReaders].dwCurrentState = SCARD_STATE_UNAWARE; #endif #ifdef DO_NOT_USE_SCARD_AUTOALLOCATE // This is a Memory Leak, but mszReaders is needed until the end //SCardFreeMemory(hContext, mszReaders); #endif return READERS_UPDATED; } /** * On status change, call the appropriate * registered functions (if there are). */ int check_card_status( SCARDCONTEXT &hContext, SCARD_READERSTATE *&readersState, v8::Persistent<v8::Object> &readers, v8::Local<v8::Function> &callback ){ unsigned int i, k, nbReaders; DWORD evt; LONG rv; v8::Local<v8::String> status; char atr[MAX_ATR_SIZE*3+1]; char uid[30]; // Check context rv = SCardIsValidContext(hContext); if (rv != SCARD_S_SUCCESS) { // Debug purpose ONLY std::cout << "ERROR_INVALID_CXT" << std::endl; return ERROR_INVALID_CXT; } // Count readers nbReaders = readers->GetPropertyNames()->Length(); // Readers state has to be filled up by update_readers if ( !readersState || !nbReaders ) { std::cout << "NO_READER_FOUND" << std::endl; return NO_READER_FOUND; } // Check status rv = SCardGetStatusChange(hContext, INFINITE, readersState, nbReaders); if ((rv == SCARD_S_SUCCESS) || (static_cast<unsigned int>(rv) == SCARD_E_TIMEOUT)) { // Get the event issuer (card reader) for (i=0; i<nbReaders; i++) { evt = readersState[i].dwEventState; if (evt & SCARD_STATE_CHANGED) { // New state is now the current state readersState[i].dwCurrentState = evt; } else { // Nothing changed, then skip to the next reader continue; } // Reader id: i, reader name: readersState[i].szReader if(evt & SCARD_STATE_IGNORE) { status = v8::String::New("SCARD_STATE_IGNORE"); } else if(evt & SCARD_STATE_UNKNOWN) { status = v8::String::New("SCARD_STATE_UNKNOWN"); } else if(evt & SCARD_STATE_UNAVAILABLE) { status = v8::String::New("SCARD_STATE_UNAVAILABLE"); } else if(evt & SCARD_STATE_EMPTY) { status = v8::String::New("SCARD_STATE_EMPTY"); } else if(evt & SCARD_STATE_PRESENT) { status = v8::String::New("SCARD_STATE_PRESENT"); } else if(evt & SCARD_STATE_ATRMATCH) { status = v8::String::New("SCARD_STATE_ATRMATCH"); } else if(evt & SCARD_STATE_EXCLUSIVE) { status = v8::String::New("SCARD_STATE_EXCLUSIVE"); } else if(evt & SCARD_STATE_INUSE) { status = v8::String::New("SCARD_STATE_INUSE"); } else if(evt & SCARD_STATE_MUTE) { status = v8::String::New("SCARD_STATE_MUTE"); } // Prepare readerObject event // --------------------------- v8::Local<v8::Object> readerObj = v8::Object::New(); readerObj->Set(v8::String::NewSymbol("name"), readers->GetOwnPropertyNames()->Get(i)); readerObj->Set(v8::String::NewSymbol("status"), v8::Local<v8::Value>::New(status)); // Card object, will be eventually filled lateron v8::Local<v8::Object> cardObj = v8::Object::New(); // If a card is present prepare card event // ---------------------------------------- if(evt & SCARD_STATE_PRESENT) { // Dump the ATR if available if (readersState[i].cbAtr > 0) { if (readersState[i].cbAtr) { unsigned int j; for (j=0; j<readersState[i].cbAtr; j++) { sprintf(&atr[j*3], "%02X ", readersState[i].rgbAtr[j]); } atr[j*3-1] = '\0'; } else { atr[0] = '\0'; } cardObj->Set(v8::String::NewSymbol("ATR"), v8::String::New(atr)); } // Establishes a connection to a smart card contained by a specific reader. SCARDHANDLE hCard; DWORD activeProtocol; v8::String::Utf8Value readerName(readers->GetOwnPropertyNames()->Get(i)); rv = SCardConnect( hContext, // Resource manager handle (LPCSTR)*readerName, // Reader name SCARD_SHARE_SHARED, // Share Mode SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1, // Preferred protocols (T=0 or T=1) &hCard, // Returns the card handle &activeProtocol // Active protocol ); // Connect to the card reader // ---------------------------------------- if (rv == SCARD_S_SUCCESS) { // APDU exchange LPCSCARD_IO_REQUEST ioRequest; switch (activeProtocol) { case SCARD_PROTOCOL_T0: cardObj->Set(v8::String::NewSymbol("Protocol"), v8::String::New("T=0")); ioRequest = SCARD_PCI_T0; break; case SCARD_PROTOCOL_T1: cardObj->Set(v8::String::NewSymbol("Protocol"), v8::String::New("T=1")); ioRequest = SCARD_PCI_T1; break; default: ioRequest = SCARD_PCI_RAW; break; } // Pseudo ADPU to Retrieve card Serial Number (UID) BYTE pbRecvBuffer[10];//[10*1024]; // Max Card Size currently (2013) was: [256]; BYTE pbSendBuffer[] = { 0xFF, 0xCA, 0x00, 0x00, 0x00 }; SCARD_IO_REQUEST pioRecvPci; DWORD dwSendLength = sizeof(pbSendBuffer); DWORD dwRecvLength = sizeof(pbRecvBuffer); rv = SCardTransmit( hCard, // Card handle ioRequest, // Pointer to the sent protocol header pbSendBuffer, // Send buffer dwSendLength, // Send buffer length &pioRecvPci, // Pointer to the rec. protocol header pbRecvBuffer, // Receive buffer &dwRecvLength // Receive buffer length ); if (rv == SCARD_S_SUCCESS) { // Save UID if (dwRecvLength) { for (k = 0; k < dwRecvLength; k++) { sprintf(&uid[k*3], "%02X ", pbRecvBuffer[k]); } uid[k*3-1] = '\0'; cardObj->Set(v8::String::NewSymbol("UID_length"), v8::Number::New(dwRecvLength)); } else { uid[0] = '\0'; } cardObj->Set(v8::String::NewSymbol("UID"), v8::String::New(uid)); // Disconnect it right now SCardDisconnect( hCard, // Card handle. SCARD_UNPOWER_CARD ); } else { switch(rv) { case SCARD_E_INSUFFICIENT_BUFFER: cardObj->Set(v8::String::NewSymbol("err"), v8::String::New("SCARD_E_INSUFFICIENT_BUFFER")); break; case SCARD_E_INVALID_PARAMETER: cardObj->Set(v8::String::NewSymbol("err"), v8::String::New("SCARD_E_INVALID_PARAMETER")); break; case SCARD_E_INVALID_HANDLE: cardObj->Set(v8::String::NewSymbol("err"), v8::String::New("SCARD_E_INVALID_HANDLE")); break; case SCARD_E_INVALID_VALUE: cardObj->Set(v8::String::NewSymbol("err"), v8::String::New("SCARD_E_INVALID_VALUE")); break; case SCARD_E_NO_SERVICE: cardObj->Set(v8::String::NewSymbol("err"), v8::String::New("SCARD_E_NO_SERVICE")); break; case SCARD_E_NOT_TRANSACTED: cardObj->Set(v8::String::NewSymbol("err"), v8::String::New("SCARD_E_NOT_TRANSACTED")); break; case SCARD_E_PROTO_MISMATCH: cardObj->Set(v8::String::NewSymbol("err"), v8::String::New("SCARD_E_PROTO_MISMATCH")); break; case SCARD_E_READER_UNAVAILABLE: cardObj->Set(v8::String::NewSymbol("err"), v8::String::New("SCARD_E_READER_UNAVAILABLE")); break; case SCARD_F_COMM_ERROR: cardObj->Set(v8::String::NewSymbol("err"), v8::String::New("SCARD_F_COMM_ERROR")); break; case SCARD_W_RESET_CARD: cardObj->Set(v8::String::NewSymbol("err"), v8::String::New("SCARD_W_RESET_CARD")); break; case SCARD_W_REMOVED_CARD: cardObj->Set(v8::String::NewSymbol("err"), v8::String::New("SCARD_W_REMOVED_CARD")); break; } } } } // // Emit an event message // ---------------------- v8::Local<v8::Object> evtMsg = v8::Object::New(); evtMsg->Set(v8::String::NewSymbol("reader"), readerObj); evtMsg->Set(v8::String::NewSymbol("card"), cardObj); const unsigned argc = 1; v8::Local<v8::Value> argv[argc] = { evtMsg }; callback->Call(v8::Context::GetCurrent()->Global(), argc, argv); return STATUS_CHECKED; } } // Simple callback to request another check later on const int argc = 0; v8::Local<v8::Value> *argv = NULL; callback->Call(v8::Context::GetCurrent()->Global(), argc, argv); return STATUS_CHECKED; } /** * Release the PCSC context */ int release_context(SCARDCONTEXT &hContext) { return SCardReleaseContext(hContext); } } // <- end of namespace <|endoftext|>
<commit_before>/* For secp384r1 define this macro if using secp384r1 */ // #define MCLBN_FP_UNIT_SIZE 6 /* For secp521r1 1. rebuild libmcl.a make clean && make lib/libmcl.a MCL_MAX_BIT_SIZE=576 2. define this macro if using secp521r1 */ // #define MCLBN_FP_UNIT_SIZE 9 #include <mcl/she.hpp> #include <cybozu/option.hpp> #include <cybozu/benchmark.hpp> #include <sstream> #include <vector> #include <omp.h> using namespace mcl::she; const int maxMsg = 10000; typedef std::vector<CipherTextG1> CipherTextG1Vec; template<class T> void loadSaveTest(const char *msg, const T& x, bool compress) { std::string s; // save { std::ostringstream oss; // you can use std::fstream if (compress) { // cybozu::save(oss, x); x.save(oss); } else { oss.write((const char*)&x, sizeof(x)); } s = oss.str(); printf("size=%zd\n", s.size()); } // load { std::istringstream iss(s); T y; if (compress) { // cybozu::load(y, iss); y.load(iss); } else { iss.read((char*)&y, sizeof(y)); } printf("save and load %s %s\n", msg, (x == y) ? "ok" : "err"); } } void loadSave(const SecretKey& sec, const PublicKey& pub, bool compress) { printf("loadSave compress=%d\n", compress); int m = 123; CipherTextG1 c; pub.enc(c, m); loadSaveTest("sec", sec, compress); loadSaveTest("pub", pub, compress); loadSaveTest("ciphertext", c, compress); } void benchEnc(const PrecomputedPublicKey& ppub, int vecN) { cybozu::CpuClock clk; CipherTextG1Vec cv; cv.resize(vecN); const int C = 10; for (int k = 0; k < C; k++) { clk.begin(); #pragma omp parallel for for (int i = 0; i < vecN; i++) { ppub.enc(cv[i], i); } clk.end(); } clk.put("enc"); } // encrypt and normalize each ciphertext to Affine void benchEncAffine(const PrecomputedPublicKey& ppub, int vecN) { cybozu::CpuClock clk; CipherTextG1Vec cv; cv.resize(vecN); const int C = 10; for (int k = 0; k < C; k++) { clk.begin(); #pragma omp parallel for for (int i = 0; i < vecN; i++) { ppub.enc(cv[i], i); cv[i].normalize(); } clk.end(); } clk.put("enc"); } // encrypt and normalize all ciphertext to Affine void benchEncAffineVec(const PrecomputedPublicKey& ppub, int vecN) { cybozu::CpuClock clk; CipherTextG1Vec cv; cv.resize(vecN); const int C = 10; for (int k = 0; k < C; k++) { clk.begin(); #pragma omp parallel for for (int i = 0; i < vecN; i++) { ppub.enc(cv[i], i); } normalizeVec(&cv[0], vecN); clk.end(); } clk.put("enc"); } void benchAdd(const PrecomputedPublicKey& ppub, int addN, int vecN) { cybozu::CpuClock clk; CipherTextG1Vec sumv, cv; sumv.resize(vecN); cv.resize(addN); for (int i = 0; i < addN; i++) { ppub.enc(cv[i], i); } const int C = 10; for (int k = 0; k < C; k++) { clk.begin(); #pragma omp parallel for for (int j = 0; j < vecN; j++) { sumv[j] = cv[0]; for (int i = 1; i < addN; i++) { sumv[j].add(cv[i]); } } clk.end(); } clk.put("add"); } void benchAddAffine(const PrecomputedPublicKey& ppub, int addN, int vecN) { cybozu::CpuClock clk; CipherTextG1Vec sumv, cv; sumv.resize(vecN); cv.resize(addN); for (int i = 0; i < addN; i++) { ppub.enc(cv[i], i); } normalizeVec(&cv[0], addN); const int C = 10; for (int k = 0; k < C; k++) { clk.begin(); #pragma omp parallel for for (int j = 0; j < vecN; j++) { sumv[j] = cv[0]; for (int i = 1; i < addN; i++) { sumv[j].add(cv[i]); } } clk.end(); } clk.put("add-affine"); } void benchDec(const PrecomputedPublicKey& ppub, const SecretKey& sec, int vecN) { cybozu::CpuClock clk; CipherTextG1Vec cv; cv.resize(vecN); for (int i = 0; i < vecN; i++) { ppub.enc(cv[i], i % maxMsg); } const int C = 10; for (int k = 0; k < C; k++) { clk.begin(); #pragma omp parallel for for (int i = 0; i < vecN; i++) { sec.dec(cv[i]); } clk.end(); } clk.put("dec"); } void exec(const std::string& mode, int addN, int vecN) { SecretKey sec; sec.setByCSPRNG(); PublicKey pub; sec.getPublicKey(pub); PrecomputedPublicKey ppub; ppub.init(pub); if (mode == "enc") { benchEnc(ppub, vecN); return; } if (mode == "enc-affine") { benchEncAffine(ppub, vecN); return; } if (mode == "enc-affine-vec") { benchEncAffineVec(ppub, vecN); return; } if (mode == "add") { benchAdd(ppub, addN, vecN); return; } if (mode == "add-affine") { benchAddAffine(ppub, addN, vecN); return; } if (mode == "dec") { benchDec(ppub, sec, vecN); return; } if (mode == "loadsave") { loadSave(sec, pub, false); loadSave(sec, pub, true); return; } printf("not supported mode=%s\n", mode.c_str()); } int main(int argc, char *argv[]) try { cybozu::Option opt; int cpuN; int addN; int vecN; std::string mode; opt.appendOpt(&cpuN, 1, "cpu", "# of cpus"); opt.appendOpt(&addN, 128, "add", "# of add"); opt.appendOpt(&vecN, 1024, "n", "# of elements"); opt.appendParam(&mode, "mode", "enc|enc-affine|enc-affine-vec|add|add-affine|dec|loadsave"); opt.appendHelp("h"); if (opt.parse(argc, argv)) { opt.put(); } else { opt.usage(); return 1; } omp_set_num_threads(cpuN); // initialize system const size_t hashSize = maxMsg; printf("MCL_MAX_BIT_SIZE=%d\n", MCL_MAX_BIT_SIZE); #if 1 #if MCLBN_FP_UNIT_SIZE == 4 const mcl::EcParam& param = mcl::ecparam::secp256k1; puts("secp256k1"); #elif MCLBN_FP_UNIT_SIZE == 6 const mcl::EcParam& param = mcl::ecparam::secp384r1; puts("secp384r1"); #elif MCLBN_FP_UNIT_SIZE == 9 const mcl::EcParam& param = mcl::ecparam::secp521r1; puts("secp521r1"); #else #error "bad MCLBN_FP_UNIT_SIZE" #endif initG1only(param, hashSize); #else init(); setRangeForDLP(hashSize); #endif exec(mode, addN, vecN); } catch (std::exception& e) { printf("ERR %s\n", e.what()); return 1; } <commit_msg>[she] add affineSerializeTest<commit_after>/* For secp384r1 define this macro if using secp384r1 */ // #define MCLBN_FP_UNIT_SIZE 6 #include <mcl/she.hpp> #include <cybozu/option.hpp> #include <cybozu/benchmark.hpp> #include <sstream> #include <vector> #include <omp.h> using namespace mcl::she; const int maxMsg = 10000; typedef std::vector<CipherTextG1> CipherTextG1Vec; template<class T> void loadSaveTest(const char *msg, const T& x, bool compress) { std::string s; // save { std::ostringstream oss; // you can use std::fstream if (compress) { x.save(oss); } else { oss.write((const char*)&x, sizeof(x)); } s = oss.str(); printf("size=%zd\n", s.size()); } // load { std::istringstream iss(s); T y; if (compress) { y.load(iss); } else { iss.read((char*)&y, sizeof(y)); } printf("save and load %s %s\n", msg, (x == y) ? "ok" : "err"); } } void loadSave(const SecretKey& sec, const PublicKey& pub, bool compress) { printf("loadSave compress=%d\n", compress); int m = 123; CipherTextG1 c; pub.enc(c, m); loadSaveTest("sec", sec, compress); loadSaveTest("pub", pub, compress); loadSaveTest("ciphertext", c, compress); } void benchEnc(const PrecomputedPublicKey& ppub, int vecN) { cybozu::CpuClock clk; CipherTextG1Vec cv; cv.resize(vecN); const int C = 10; for (int k = 0; k < C; k++) { clk.begin(); #pragma omp parallel for for (int i = 0; i < vecN; i++) { ppub.enc(cv[i], i); } clk.end(); } clk.put("enc"); } // encrypt and normalize each ciphertext to Affine void benchEncAffine(const PrecomputedPublicKey& ppub, int vecN) { cybozu::CpuClock clk; CipherTextG1Vec cv; cv.resize(vecN); const int C = 10; for (int k = 0; k < C; k++) { clk.begin(); #pragma omp parallel for for (int i = 0; i < vecN; i++) { ppub.enc(cv[i], i); cv[i].normalize(); } clk.end(); } clk.put("enc"); } // encrypt and normalize all ciphertext to Affine void benchEncAffineVec(const PrecomputedPublicKey& ppub, int vecN) { cybozu::CpuClock clk; CipherTextG1Vec cv; cv.resize(vecN); const int C = 10; for (int k = 0; k < C; k++) { clk.begin(); #pragma omp parallel for for (int i = 0; i < vecN; i++) { ppub.enc(cv[i], i); } normalizeVec(&cv[0], vecN); clk.end(); } clk.put("enc"); } void benchAdd(const PrecomputedPublicKey& ppub, int addN, int vecN) { cybozu::CpuClock clk; CipherTextG1Vec sumv, cv; sumv.resize(vecN); cv.resize(addN); for (int i = 0; i < addN; i++) { ppub.enc(cv[i], i); } const int C = 10; for (int k = 0; k < C; k++) { clk.begin(); #pragma omp parallel for for (int j = 0; j < vecN; j++) { sumv[j] = cv[0]; for (int i = 1; i < addN; i++) { sumv[j].add(cv[i]); } } clk.end(); } clk.put("add"); } void benchAddAffine(const PrecomputedPublicKey& ppub, int addN, int vecN) { cybozu::CpuClock clk; CipherTextG1Vec sumv, cv; sumv.resize(vecN); cv.resize(addN); for (int i = 0; i < addN; i++) { ppub.enc(cv[i], i); } normalizeVec(&cv[0], addN); const int C = 10; for (int k = 0; k < C; k++) { clk.begin(); #pragma omp parallel for for (int j = 0; j < vecN; j++) { sumv[j] = cv[0]; for (int i = 1; i < addN; i++) { sumv[j].add(cv[i]); } } clk.end(); } clk.put("add-affine"); } void benchDec(const PrecomputedPublicKey& ppub, const SecretKey& sec, int vecN) { cybozu::CpuClock clk; CipherTextG1Vec cv; cv.resize(vecN); for (int i = 0; i < vecN; i++) { ppub.enc(cv[i], i % maxMsg); } const int C = 10; for (int k = 0; k < C; k++) { clk.begin(); #pragma omp parallel for for (int i = 0; i < vecN; i++) { sec.dec(cv[i]); } clk.end(); } clk.put("dec"); } void affineSerializeTest(const SecretKey& sec, const PrecomputedPublicKey& ppub) { const int N = 4096; size_t FpSize = 256 / 8; // * 2 : affine coordinate x, y // * 2 : group elements of ElGamal ciphertext std::vector<uint8_t> buf(FpSize * 2 * 2 * N); { CipherTextG1Vec cv; cv.resize(N); for (int i = 0; i < N; i++) { ppub.enc(cv[i], i % maxMsg); } // serialize and write {cv[i]} to buf cybozu::MemoryOutputStream os(buf.data(), buf.size()); serializeVecToAffine(os, cv.data(), N); } { CipherTextG1Vec cv; cv.resize(N); // deserialize buf to {cv[i]} cybozu::MemoryInputStream is(buf.data(), buf.size()); deserializeVecFromAffine(cv.data(), N, is); // check values for (int i = 0; i < N; i++) { int x = sec.dec(cv[i]); int y = i % maxMsg; if (x != y) { printf("err i=%d x=%d y=%d\n", i, x, y); exit(1); } } puts("serialize deserialize ok"); } } void exec(const std::string& mode, int addN, int vecN) { SecretKey sec; sec.setByCSPRNG(); PublicKey pub; sec.getPublicKey(pub); PrecomputedPublicKey ppub; ppub.init(pub); if (mode == "enc") { benchEnc(ppub, vecN); return; } if (mode == "enc-affine") { benchEncAffine(ppub, vecN); return; } if (mode == "enc-affine-vec") { benchEncAffineVec(ppub, vecN); return; } if (mode == "add") { benchAdd(ppub, addN, vecN); return; } if (mode == "add-affine") { benchAddAffine(ppub, addN, vecN); return; } if (mode == "dec") { benchDec(ppub, sec, vecN); return; } if (mode == "loadsave") { loadSave(sec, pub, false); loadSave(sec, pub, true); affineSerializeTest(sec, ppub); return; } printf("not supported mode=%s\n", mode.c_str()); } int main(int argc, char *argv[]) try { cybozu::Option opt; int cpuN; int addN; int vecN; std::string mode; opt.appendOpt(&cpuN, 1, "cpu", "# of cpus"); opt.appendOpt(&addN, 128, "add", "# of add"); opt.appendOpt(&vecN, 1024, "n", "# of elements"); opt.appendParam(&mode, "mode", "enc|enc-affine|enc-affine-vec|add|add-affine|dec|loadsave"); opt.appendHelp("h"); if (opt.parse(argc, argv)) { opt.put(); } else { opt.usage(); return 1; } omp_set_num_threads(cpuN); // initialize system const size_t hashSize = maxMsg; printf("MCL_MAX_BIT_SIZE=%d\n", MCL_MAX_BIT_SIZE); #if 1 #if MCLBN_FP_UNIT_SIZE == 4 const mcl::EcParam& param = mcl::ecparam::secp256k1; puts("secp256k1"); #elif MCLBN_FP_UNIT_SIZE == 6 const mcl::EcParam& param = mcl::ecparam::secp384r1; puts("secp384r1"); #elif MCLBN_FP_UNIT_SIZE == 9 const mcl::EcParam& param = mcl::ecparam::secp521r1; puts("secp521r1"); #else #error "bad MCLBN_FP_UNIT_SIZE" #endif initG1only(param, hashSize); #else init(); setRangeForDLP(hashSize); #endif exec(mode, addN, vecN); } catch (std::exception& e) { printf("ERR %s\n", e.what()); return 1; } <|endoftext|>
<commit_before>/* * Copyright (c) 2017-present, 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 <boost/algorithm/string/join.hpp> #include <boost/filesystem/operations.hpp> #include <boost/filesystem/path.hpp> #include <osquery/core.h> #include <osquery/filesystem.h> #include <osquery/logger.h> #include <osquery/tables.h> #include "osquery/core/conversions.h" #include "osquery/sql/sqlite_util.h" namespace fs = boost::filesystem; namespace pt = boost::property_tree; namespace osquery { namespace tables { const std::string kGkeStatusPath = "/var/db/SystemPolicy-prefs.plist"; const std::string kGkeBundlePath = "/var/db/gke.bundle/Contents/version.plist"; const std::string kGkeOpaquePath = "/var/db/gkopaque.bundle/Contents/version.plist"; const std::string kPolicyDb = "/var/db/SystemPolicy"; bool isGateKeeperDevIdEnabled() { sqlite3* db = nullptr; auto rc = sqlite3_open_v2( kPolicyDb.c_str(), &db, (SQLITE_OPEN_READONLY | SQLITE_OPEN_PRIVATECACHE | SQLITE_OPEN_NOMUTEX), nullptr); if (rc != SQLITE_OK || db == nullptr) { VLOG(1) << "Cannot open Gatekeeper DB: " << rc << " " << getStringForSQLiteReturnCode(rc); if (db != nullptr) { free(db); } return false; } std::string query = "SELECT disabled FROM authority WHERE label = 'Developer ID'"; sqlite3_stmt* stmt = nullptr; rc = sqlite3_prepare_v2(db, query.c_str(), -1, &stmt, nullptr); while ((sqlite3_step(stmt)) == SQLITE_ROW) { int value = sqlite3_column_int(stmt, 0); if (value == 1) { // Clean up. sqlite3_finalize(stmt); free(db); // return false if any rows say "disabled" return false; } } sqlite3_finalize(stmt); free(db); return true; } QueryData genGateKeeper(QueryContext& context) { Row r; auto gke_status = SQL::selectAllFrom("plist", "path", EQUALS, kGkeStatusPath); if (gke_status.empty()) { r["assessments_enabled"] = INTEGER(0); } for (const auto& row : gke_status) { if (row.find("key") == row.end() || row.find("value") == row.end()) { continue; } if (row.at("key") == "enabled" && row.at("value") == "yes") { r["assessments_enabled"] = INTEGER(1); r["dev_id_enabled"] = isGateKeeperDevIdEnabled() ? INTEGER(1) : INTEGER(0); } else { r["assessments_enabled"] = INTEGER(0); r["dev_id_enabled"] = INTEGER(0); } } auto gke_bundle = SQL::selectAllFrom("plist", "path", EQUALS, kGkeBundlePath); if (gke_bundle.empty()) { r["version"] = std::string(); } for (const auto& row : gke_bundle) { if (row.find("key") == row.end() || row.find("value") == row.end()) { continue; } if (row.at("key") == "CFBundleShortVersionString") { r["version"] = row.at("value"); } } auto gke_opaque = SQL::selectAllFrom("plist", "path", EQUALS, kGkeOpaquePath); if (gke_opaque.empty()) { r["opaque_version"] = std::string(); } for (const auto& row : gke_opaque) { if (row.find("key") == row.end() || row.find("value") == row.end()) { continue; } if (row.at("key") == "CFBundleShortVersionString") { r["opaque_version"] = row.at("value"); } } return {r}; } void genGateKeeperApprovedAppRow(sqlite3_stmt* const stmt, Row& r) { for (int i = 0; i < sqlite3_column_count(stmt); i++) { auto column_name = std::string(sqlite3_column_name(stmt, i)); auto column_type = sqlite3_column_type(stmt, i); if (column_type == SQLITE_TEXT) { auto value = sqlite3_column_text(stmt, i); if (value != nullptr) { r[column_name] = std::string(reinterpret_cast<const char*>(value)); } } else if (column_type == SQLITE_FLOAT) { auto value = sqlite3_column_double(stmt, i); r[column_name] = DOUBLE(value); } } } QueryData genGateKeeperApprovedApps(QueryContext& context) { QueryData results; sqlite3* db = nullptr; auto rc = sqlite3_open_v2( kPolicyDb.c_str(), &db, (SQLITE_OPEN_READONLY | SQLITE_OPEN_PRIVATECACHE | SQLITE_OPEN_NOMUTEX), nullptr); if (rc != SQLITE_OK || db == nullptr) { VLOG(1) << "Cannot open Gatekeeper DB: " << rc << " " << getStringForSQLiteReturnCode(rc); if (db != nullptr) { free(db); } return results; } const std::string query = "SELECT remarks as path, requirement, ctime, mtime from authority WHERE " "disabled = 0 AND JULIANDAY('now') < expires AND (flags & 1) = 0 AND " "label is NULL"; sqlite3_stmt* stmt = nullptr; rc = sqlite3_prepare_v2(db, query.c_str(), -1, &stmt, nullptr); while ((sqlite3_step(stmt)) == SQLITE_ROW) { Row r; genGateKeeperApprovedAppRow(stmt, r); results.push_back(r); } // Clean up. sqlite3_finalize(stmt); free(db); return results; } } // namespace tables } // namespace osquery <commit_msg>Fix memory leaks in Gatekeeper table (#3531)<commit_after>/* * Copyright (c) 2017-present, 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 <boost/algorithm/string/join.hpp> #include <boost/filesystem/operations.hpp> #include <boost/filesystem/path.hpp> #include <osquery/core.h> #include <osquery/filesystem.h> #include <osquery/logger.h> #include <osquery/tables.h> #include "osquery/core/conversions.h" #include "osquery/sql/sqlite_util.h" namespace fs = boost::filesystem; namespace pt = boost::property_tree; namespace osquery { namespace tables { const std::string kGkeStatusPath = "/var/db/SystemPolicy-prefs.plist"; const std::string kGkeBundlePath = "/var/db/gke.bundle/Contents/version.plist"; const std::string kGkeOpaquePath = "/var/db/gkopaque.bundle/Contents/version.plist"; const std::string kPolicyDb = "/var/db/SystemPolicy"; bool isGateKeeperDevIdEnabled() { sqlite3* db = nullptr; auto rc = sqlite3_open_v2( kPolicyDb.c_str(), &db, (SQLITE_OPEN_READONLY | SQLITE_OPEN_PRIVATECACHE | SQLITE_OPEN_NOMUTEX), nullptr); if (rc != SQLITE_OK || db == nullptr) { VLOG(1) << "Cannot open Gatekeeper DB: " << rc << " " << getStringForSQLiteReturnCode(rc); if (db != nullptr) { sqlite3_close(db); } return false; } std::string query = "SELECT disabled FROM authority WHERE label = 'Developer ID'"; sqlite3_stmt* stmt = nullptr; rc = sqlite3_prepare_v2(db, query.c_str(), -1, &stmt, nullptr); while ((sqlite3_step(stmt)) == SQLITE_ROW) { int value = sqlite3_column_int(stmt, 0); if (value == 1) { // Clean up. sqlite3_finalize(stmt); sqlite3_close(db); // return false if any rows say "disabled" return false; } } sqlite3_finalize(stmt); sqlite3_close(db); return true; } QueryData genGateKeeper(QueryContext& context) { Row r; auto gke_status = SQL::selectAllFrom("plist", "path", EQUALS, kGkeStatusPath); if (gke_status.empty()) { r["assessments_enabled"] = INTEGER(0); } for (const auto& row : gke_status) { if (row.find("key") == row.end() || row.find("value") == row.end()) { continue; } if (row.at("key") == "enabled" && row.at("value") == "yes") { r["assessments_enabled"] = INTEGER(1); r["dev_id_enabled"] = isGateKeeperDevIdEnabled() ? INTEGER(1) : INTEGER(0); } else { r["assessments_enabled"] = INTEGER(0); r["dev_id_enabled"] = INTEGER(0); } } auto gke_bundle = SQL::selectAllFrom("plist", "path", EQUALS, kGkeBundlePath); if (gke_bundle.empty()) { r["version"] = std::string(); } for (const auto& row : gke_bundle) { if (row.find("key") == row.end() || row.find("value") == row.end()) { continue; } if (row.at("key") == "CFBundleShortVersionString") { r["version"] = row.at("value"); } } auto gke_opaque = SQL::selectAllFrom("plist", "path", EQUALS, kGkeOpaquePath); if (gke_opaque.empty()) { r["opaque_version"] = std::string(); } for (const auto& row : gke_opaque) { if (row.find("key") == row.end() || row.find("value") == row.end()) { continue; } if (row.at("key") == "CFBundleShortVersionString") { r["opaque_version"] = row.at("value"); } } return {r}; } void genGateKeeperApprovedAppRow(sqlite3_stmt* const stmt, Row& r) { for (int i = 0; i < sqlite3_column_count(stmt); i++) { auto column_name = std::string(sqlite3_column_name(stmt, i)); auto column_type = sqlite3_column_type(stmt, i); if (column_type == SQLITE_TEXT) { auto value = sqlite3_column_text(stmt, i); if (value != nullptr) { r[column_name] = std::string(reinterpret_cast<const char*>(value)); } } else if (column_type == SQLITE_FLOAT) { auto value = sqlite3_column_double(stmt, i); r[column_name] = DOUBLE(value); } } } QueryData genGateKeeperApprovedApps(QueryContext& context) { QueryData results; sqlite3* db = nullptr; auto rc = sqlite3_open_v2( kPolicyDb.c_str(), &db, (SQLITE_OPEN_READONLY | SQLITE_OPEN_PRIVATECACHE | SQLITE_OPEN_NOMUTEX), nullptr); if (rc != SQLITE_OK || db == nullptr) { VLOG(1) << "Cannot open Gatekeeper DB: " << rc << " " << getStringForSQLiteReturnCode(rc); if (db != nullptr) { sqlite3_close(db); } return results; } const std::string query = "SELECT remarks as path, requirement, ctime, mtime from authority WHERE " "disabled = 0 AND JULIANDAY('now') < expires AND (flags & 1) = 0 AND " "label is NULL"; sqlite3_stmt* stmt = nullptr; rc = sqlite3_prepare_v2(db, query.c_str(), -1, &stmt, nullptr); while ((sqlite3_step(stmt)) == SQLITE_ROW) { Row r; genGateKeeperApprovedAppRow(stmt, r); results.push_back(r); } // Clean up. sqlite3_finalize(stmt); sqlite3_close(db); return results; } } // namespace tables } // namespace osquery <|endoftext|>
<commit_before>#include <iostream> #include <cstlib> #include <vector> <commit_msg>Use fscanf to read in file.<commit_after>#include <iostream> #include <cstdlib> #include <vector> #include <bitset> #include <cstring> #include <string> #include <fstream> #include <cstdio> #include "rand.h" using namespace std; class individual { public: int key[26]; float fit; }; // user functions go here int main() { // get cipher from cin string cipher, tmp; while( getline( cin, tmp ) ) { cipher.append( tmp ); } // read in freq.txt FILE *freq = fopen( "freq.txt", "r" ); char eng1[488], eng2[488]; float engnum[488]; // check if file is open if( freq != NULL ) { for( int i = 0; i < 488; i++ ) { fscanf( freq, "%c%c %f ", &eng1[i], &eng2[i], &engnum[i] ); // eng1[i] = fgetc( freq ); //eng2[i] = fgetc( freq ); cout << eng1[i] << eng2[i] << " " << engnum[i] <<endl; } } // create cipher count tables char cipher1[488], cipher2[488]; float ciphernum[488]; for( int i = 0; i < cipher.size(); i++ ){ } } // end main <|endoftext|>
<commit_before><commit_msg>Create p10201 - Adventures in Moving - Part IV.cpp<commit_after><|endoftext|>
<commit_before>#include "stdafx.h" #include "AutoPacketFactory.h" #include "AutoPacket.h" AutoPacketFactory::AutoPacketFactory(void): m_wasStopped(false), m_packets( ~0, ~0, [this] { return new AutoPacket(*this); }, [] (AutoPacket& packet) { packet.Reset(); } ) {} AutoPacketFactory::~AutoPacketFactory() {} std::shared_ptr<AutoPacket> AutoPacketFactory::NewPacket(void) { if (!IsRunning()) throw autowiring_error("Cannot create a packet until the AutoPacketFactory is started"); // Obtain a packet, return it std::shared_ptr<AutoPacket> retVal; m_packets(retVal); // Done, return return retVal; } bool AutoPacketFactory::Start(std::shared_ptr<Object> outstanding) { boost::lock_guard<boost::mutex> lk(m_lock); if(m_wasStopped) // Cannot start if already stopped return false; m_outstanding = outstanding; m_stateCondition.notify_all(); return true; } void AutoPacketFactory::Stop(bool graceful) { // Return optimization if(m_wasStopped) return; // Kill the object pool m_packets.SetOutstandingLimit(0); m_packets.ClearCachedEntities(); // Swap outstanding count into a local var, so we can reset outside of a lock std::shared_ptr<Object> outstanding; // Same story with the AutoFilters t_autoFilterSet autoFilters; boost::lock_guard<boost::mutex> lk(m_lock); // Can't safely do a swap outside of a lock outstanding.swap(m_outstanding); autoFilters.swap(m_autoFilters); // Now we can lock, update state, and notify any listeners m_wasStopped = true; m_stateCondition.notify_all(); } void AutoPacketFactory::Clear(void) { // Trigger a stop first, before trying to release anything Stop(false); // Release any external references before obtaining the lock m_autoFilters.clear(); } void AutoPacketFactory::Wait(void) { { boost::unique_lock<boost::mutex> lk(m_lock); m_stateCondition.wait(lk, [this]{return ShouldStop(); }); } // Now we need to block until all packets come back to the object pool: m_packets.Rundown(); } void AutoPacketFactory::AddSubscriber(const AutoFilterDescriptor& rhs) { (boost::lock_guard<boost::mutex>)m_lock, m_autoFilters.insert(rhs); // Trigger object pool reset after releasing the lock. While it's possible that some // packets may be issued between lock reset and object pool reset, these packets will // not be specifically invalid; they will simply result in late delivery to certain // recipients. Eventually, all packets will be reset and released. m_packets.ClearCachedEntities(); } void AutoPacketFactory::RemoveSubscriber(const AutoFilterDescriptor& autoFilter) { // Trivial removal from the autofilter set: { boost::lock_guard<boost::mutex> lk(m_lock); m_autoFilters.erase(autoFilter); } // Regeneration of the packet pool for the same reason as described in AddSubscriber m_packets.ClearCachedEntities(); } <commit_msg>Adding comments<commit_after>#include "stdafx.h" #include "AutoPacketFactory.h" #include "AutoPacket.h" AutoPacketFactory::AutoPacketFactory(void): m_wasStopped(false), m_packets( ~0, ~0, [this] { return new AutoPacket(*this); }, [] (AutoPacket& packet) { packet.Reset(); } ) {} AutoPacketFactory::~AutoPacketFactory() {} std::shared_ptr<AutoPacket> AutoPacketFactory::NewPacket(void) { if (!IsRunning()) throw autowiring_error("Cannot create a packet until the AutoPacketFactory is started"); // Obtain a packet, return it std::shared_ptr<AutoPacket> retVal; m_packets(retVal); // Done, return return retVal; } bool AutoPacketFactory::Start(std::shared_ptr<Object> outstanding) { boost::lock_guard<boost::mutex> lk(m_lock); if(m_wasStopped) // Cannot start if already stopped return false; m_outstanding = outstanding; m_stateCondition.notify_all(); return true; } void AutoPacketFactory::Stop(bool graceful) { // Return optimization if(m_wasStopped) return; // Kill the object pool m_packets.SetOutstandingLimit(0); m_packets.ClearCachedEntities(); // Queue of local variables to be destroyed when leaving scope std::shared_ptr<Object> outstanding; t_autoFilterSet autoFilters; // Lock destruction precedes local variables boost::lock_guard<boost::mutex> lk(m_lock); // Swap outstanding count into a local var, so we can reset outside of a lock outstanding.swap(m_outstanding); // Same story with the AutoFilters autoFilters.swap(m_autoFilters); // Now we can lock, update state, and notify any listeners m_wasStopped = true; m_stateCondition.notify_all(); } void AutoPacketFactory::Clear(void) { // Trigger a stop first, before trying to release anything Stop(false); // Release any external references before obtaining the lock m_autoFilters.clear(); } void AutoPacketFactory::Wait(void) { { boost::unique_lock<boost::mutex> lk(m_lock); m_stateCondition.wait(lk, [this]{return ShouldStop(); }); } // Now we need to block until all packets come back to the object pool: m_packets.Rundown(); } void AutoPacketFactory::AddSubscriber(const AutoFilterDescriptor& rhs) { (boost::lock_guard<boost::mutex>)m_lock, m_autoFilters.insert(rhs); // Trigger object pool reset after releasing the lock. While it's possible that some // packets may be issued between lock reset and object pool reset, these packets will // not be specifically invalid; they will simply result in late delivery to certain // recipients. Eventually, all packets will be reset and released. m_packets.ClearCachedEntities(); } void AutoPacketFactory::RemoveSubscriber(const AutoFilterDescriptor& autoFilter) { // Trivial removal from the autofilter set: { boost::lock_guard<boost::mutex> lk(m_lock); m_autoFilters.erase(autoFilter); } // Regeneration of the packet pool for the same reason as described in AddSubscriber m_packets.ClearCachedEntities(); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: MemoryByteGrabber.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: ihi $ $Date: 2008-02-04 13:59:45 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _MEMORY_BYTE_GRABBER_HXX_ #define _MEMORY_BYTE_GRABBER_HXX_ #ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_ #include <com/sun/star/io/XInputStream.hpp> #endif #ifndef _COM_SUN_STAR_IO_XSEEKABLE_HPP_ #include <com/sun/star/io/XSeekable.hpp> #endif #include <string.h> class MemoryByteGrabber { protected: const com::sun::star::uno::Sequence < sal_Int8 > maBuffer; const sal_Int8 *mpBuffer; sal_Int32 mnCurrent, mnEnd; public: MemoryByteGrabber ( const com::sun::star::uno::Sequence < sal_Int8 > & rBuffer ) : maBuffer ( rBuffer ) , mpBuffer ( rBuffer.getConstArray() ) , mnCurrent ( 0 ) , mnEnd ( rBuffer.getLength() ) { } MemoryByteGrabber() { } const sal_Int8 * getCurrentPos () { return mpBuffer + mnCurrent; } // XInputStream chained sal_Int32 SAL_CALL readBytes( com::sun::star::uno::Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead ) throw(com::sun::star::io::NotConnectedException, com::sun::star::io::BufferSizeExceededException, com::sun::star::io::IOException, com::sun::star::uno::RuntimeException) { if ( nBytesToRead < 0) throw com::sun::star::io::BufferSizeExceededException(); if (nBytesToRead + mnCurrent > mnEnd) nBytesToRead = mnEnd - mnCurrent; aData.realloc ( nBytesToRead ); memcpy ( aData.getArray(), mpBuffer + mnCurrent, nBytesToRead ); mnCurrent += nBytesToRead; return nBytesToRead; } sal_Int32 SAL_CALL readSomeBytes( com::sun::star::uno::Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead ) throw(com::sun::star::io::NotConnectedException, com::sun::star::io::BufferSizeExceededException, com::sun::star::io::IOException, com::sun::star::uno::RuntimeException) { return readBytes( aData, nMaxBytesToRead ); } void SAL_CALL skipBytes( sal_Int32 nBytesToSkip ) throw(com::sun::star::io::NotConnectedException, com::sun::star::io::BufferSizeExceededException, com::sun::star::io::IOException, com::sun::star::uno::RuntimeException) { mnCurrent += nBytesToSkip; } sal_Int32 SAL_CALL available( ) throw(com::sun::star::io::NotConnectedException, com::sun::star::io::IOException, com::sun::star::uno::RuntimeException) { return mnEnd - mnCurrent; } void SAL_CALL closeInput( ) throw(com::sun::star::io::NotConnectedException, com::sun::star::io::IOException, com::sun::star::uno::RuntimeException) { } // XSeekable chained... sal_Int64 SAL_CALL seek( sal_Int64 location ) throw(com::sun::star::lang::IllegalArgumentException, com::sun::star::io::IOException, com::sun::star::uno::RuntimeException) { if ( location < 0 || location > mnEnd ) throw com::sun::star::lang::IllegalArgumentException (); mnCurrent = static_cast < sal_Int32 > ( location ); return mnCurrent; } sal_Int64 SAL_CALL getPosition( ) throw(com::sun::star::io::IOException, com::sun::star::uno::RuntimeException) { return mnCurrent; } sal_Int64 SAL_CALL getLength( ) throw(com::sun::star::io::IOException, com::sun::star::uno::RuntimeException) { return mnEnd; } MemoryByteGrabber& operator >> (sal_Int8& rInt8) { if (mnCurrent + 1 > mnEnd ) rInt8 = 0; else rInt8 = mpBuffer [mnCurrent++] & 0xFF; return *this; } MemoryByteGrabber& operator >> (sal_Int16& rInt16) { if (mnCurrent + 2 > mnEnd ) rInt16 = 0; else { rInt16 = mpBuffer[mnCurrent++] & 0xFF; rInt16 |= ( mpBuffer[mnCurrent++] & 0xFF ) << 8; } return *this; } MemoryByteGrabber& operator >> (sal_Int32& rInt32) { if (mnCurrent + 4 > mnEnd ) rInt32 = 0; else { rInt32 = mpBuffer[mnCurrent++] & 0xFF; rInt32 |= ( mpBuffer[mnCurrent++] & 0xFF ) << 8; rInt32 |= ( mpBuffer[mnCurrent++] & 0xFF ) << 16; rInt32 |= ( mpBuffer[mnCurrent++] & 0xFF ) << 24; } return *this; } MemoryByteGrabber& operator >> (sal_uInt8& rInt8) { if (mnCurrent + 1 > mnEnd ) rInt8 = 0; else rInt8 = mpBuffer [mnCurrent++] & 0xFF; return *this; } MemoryByteGrabber& operator >> (sal_uInt16& rInt16) { if (mnCurrent + 2 > mnEnd ) rInt16 = 0; else { rInt16 = mpBuffer [mnCurrent++] & 0xFF; rInt16 |= ( mpBuffer [mnCurrent++] & 0xFF ) << 8; } return *this; } MemoryByteGrabber& operator >> (sal_uInt32& rInt32) { if (mnCurrent + 4 > mnEnd ) rInt32 = 0; else { rInt32 = mpBuffer [mnCurrent++] & 0xFF; rInt32 |= ( mpBuffer [mnCurrent++] & 0xFF ) << 8; rInt32 |= ( mpBuffer [mnCurrent++] & 0xFF ) << 16; rInt32 |= ( mpBuffer [mnCurrent++] & 0xFF ) << 24; } return *this; } }; #endif <commit_msg>INTEGRATION: CWS changefileheader (1.6.2); FILE MERGED 2008/04/01 12:32:13 thb 1.6.2.2: #i85898# Stripping all external header guards 2008/03/31 16:19:09 rt 1.6.2.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: MemoryByteGrabber.hxx,v $ * $Revision: 1.7 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _MEMORY_BYTE_GRABBER_HXX_ #define _MEMORY_BYTE_GRABBER_HXX_ #include <com/sun/star/io/XInputStream.hpp> #include <com/sun/star/io/XSeekable.hpp> #include <string.h> class MemoryByteGrabber { protected: const com::sun::star::uno::Sequence < sal_Int8 > maBuffer; const sal_Int8 *mpBuffer; sal_Int32 mnCurrent, mnEnd; public: MemoryByteGrabber ( const com::sun::star::uno::Sequence < sal_Int8 > & rBuffer ) : maBuffer ( rBuffer ) , mpBuffer ( rBuffer.getConstArray() ) , mnCurrent ( 0 ) , mnEnd ( rBuffer.getLength() ) { } MemoryByteGrabber() { } const sal_Int8 * getCurrentPos () { return mpBuffer + mnCurrent; } // XInputStream chained sal_Int32 SAL_CALL readBytes( com::sun::star::uno::Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead ) throw(com::sun::star::io::NotConnectedException, com::sun::star::io::BufferSizeExceededException, com::sun::star::io::IOException, com::sun::star::uno::RuntimeException) { if ( nBytesToRead < 0) throw com::sun::star::io::BufferSizeExceededException(); if (nBytesToRead + mnCurrent > mnEnd) nBytesToRead = mnEnd - mnCurrent; aData.realloc ( nBytesToRead ); memcpy ( aData.getArray(), mpBuffer + mnCurrent, nBytesToRead ); mnCurrent += nBytesToRead; return nBytesToRead; } sal_Int32 SAL_CALL readSomeBytes( com::sun::star::uno::Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead ) throw(com::sun::star::io::NotConnectedException, com::sun::star::io::BufferSizeExceededException, com::sun::star::io::IOException, com::sun::star::uno::RuntimeException) { return readBytes( aData, nMaxBytesToRead ); } void SAL_CALL skipBytes( sal_Int32 nBytesToSkip ) throw(com::sun::star::io::NotConnectedException, com::sun::star::io::BufferSizeExceededException, com::sun::star::io::IOException, com::sun::star::uno::RuntimeException) { mnCurrent += nBytesToSkip; } sal_Int32 SAL_CALL available( ) throw(com::sun::star::io::NotConnectedException, com::sun::star::io::IOException, com::sun::star::uno::RuntimeException) { return mnEnd - mnCurrent; } void SAL_CALL closeInput( ) throw(com::sun::star::io::NotConnectedException, com::sun::star::io::IOException, com::sun::star::uno::RuntimeException) { } // XSeekable chained... sal_Int64 SAL_CALL seek( sal_Int64 location ) throw(com::sun::star::lang::IllegalArgumentException, com::sun::star::io::IOException, com::sun::star::uno::RuntimeException) { if ( location < 0 || location > mnEnd ) throw com::sun::star::lang::IllegalArgumentException (); mnCurrent = static_cast < sal_Int32 > ( location ); return mnCurrent; } sal_Int64 SAL_CALL getPosition( ) throw(com::sun::star::io::IOException, com::sun::star::uno::RuntimeException) { return mnCurrent; } sal_Int64 SAL_CALL getLength( ) throw(com::sun::star::io::IOException, com::sun::star::uno::RuntimeException) { return mnEnd; } MemoryByteGrabber& operator >> (sal_Int8& rInt8) { if (mnCurrent + 1 > mnEnd ) rInt8 = 0; else rInt8 = mpBuffer [mnCurrent++] & 0xFF; return *this; } MemoryByteGrabber& operator >> (sal_Int16& rInt16) { if (mnCurrent + 2 > mnEnd ) rInt16 = 0; else { rInt16 = mpBuffer[mnCurrent++] & 0xFF; rInt16 |= ( mpBuffer[mnCurrent++] & 0xFF ) << 8; } return *this; } MemoryByteGrabber& operator >> (sal_Int32& rInt32) { if (mnCurrent + 4 > mnEnd ) rInt32 = 0; else { rInt32 = mpBuffer[mnCurrent++] & 0xFF; rInt32 |= ( mpBuffer[mnCurrent++] & 0xFF ) << 8; rInt32 |= ( mpBuffer[mnCurrent++] & 0xFF ) << 16; rInt32 |= ( mpBuffer[mnCurrent++] & 0xFF ) << 24; } return *this; } MemoryByteGrabber& operator >> (sal_uInt8& rInt8) { if (mnCurrent + 1 > mnEnd ) rInt8 = 0; else rInt8 = mpBuffer [mnCurrent++] & 0xFF; return *this; } MemoryByteGrabber& operator >> (sal_uInt16& rInt16) { if (mnCurrent + 2 > mnEnd ) rInt16 = 0; else { rInt16 = mpBuffer [mnCurrent++] & 0xFF; rInt16 |= ( mpBuffer [mnCurrent++] & 0xFF ) << 8; } return *this; } MemoryByteGrabber& operator >> (sal_uInt32& rInt32) { if (mnCurrent + 4 > mnEnd ) rInt32 = 0; else { rInt32 = mpBuffer [mnCurrent++] & 0xFF; rInt32 |= ( mpBuffer [mnCurrent++] & 0xFF ) << 8; rInt32 |= ( mpBuffer [mnCurrent++] & 0xFF ) << 16; rInt32 |= ( mpBuffer [mnCurrent++] & 0xFF ) << 24; } return *this; } }; #endif <|endoftext|>
<commit_before>// RUN: %clang_cc1 %s -emit-llvm -o - // https://bugs.llvm.org/show_bug.cgi?id=38356 // We only check that we do not crash. template <typename a, a b(unsigned), int c, unsigned...> struct d : d<a, b, c - 1> {}; template <typename a, a b(unsigned), unsigned... e> struct d<a, b, 0, e...> { a f[0]; }; struct g { static g h(unsigned); }; struct i { void j() const; // Current maximum depth of recursive template instantiation is 1024, // thus, this \/ threshold value is used here. BasePathSize in CastExpr might // not fit it, so we are testing that we do fit it. // If -ftemplate-depth= is provided, larger values (4096 and up) cause crashes // elsewhere. d<g, g::h, (1U << 10U) - 2U> f; }; void i::j() const { const void *k{f.f}; (void)k; } <commit_msg>[CodeGenCXX] XFAIL test for ASAN on Darwin.<commit_after>// RUN: %clang_cc1 %s -emit-llvm -o - // https://bugs.llvm.org/show_bug.cgi?id=38356 // We only check that we do not crash. // ASAN increases stack usage, so we are hitting stack overflow before reaching // recursive template instantiation limit. // XFAIL: darwin && asan template <typename a, a b(unsigned), int c, unsigned...> struct d : d<a, b, c - 1> {}; template <typename a, a b(unsigned), unsigned... e> struct d<a, b, 0, e...> { a f[0]; }; struct g { static g h(unsigned); }; struct i { void j() const; // Current maximum depth of recursive template instantiation is 1024, // thus, this \/ threshold value is used here. BasePathSize in CastExpr might // not fit it, so we are testing that we do fit it. // If -ftemplate-depth= is provided, larger values (4096 and up) cause crashes // elsewhere. d<g, g::h, (1U << 10U) - 2U> f; }; void i::j() const { const void *k{f.f}; (void)k; } <|endoftext|>
<commit_before>#include <QCoreApplication> #include <iostream> #include "connectdatabase.h" #include "insertrow.h" #include "htmlparser.h" #include "QtSql/qsqlquery.h" //COnstructor : InsertRow::InsertRow(QObject *parent) { /* QObject::connect(SIGNAL(parsingFinished(htmlPage*)), SLOT(convertHtmlPageIntoSqlQuery(htmlPage* query)));*/ sqlQuery = ""; } void InsertRow::insertNewRow(QString sqlQuery) { //on affiche la requete dans la console : std::cout <<sqlQuery.toStdString()<<std::endl; //Création d'un objet de requête : QSqlQuery newQuery; //On teste si la requête a aboutie: if(newQuery.exec(sqlQuery)){ std::cout << "insertion reussie" <<std::endl; } else { std::cout << "votre insertion a rate" <<std::endl; } } void InsertRow::convertHtmlPageIntoSqlQuery(htmlPage *query) { //On crée ,dans un QString , une requête sql à partir des arguments recus en paramètre : sqlQuery = "INSERT INTO `websites`(`website`,`url`) VALUES(" + query->getTitle() + ","+ query->getUrl().toString() +");"; insertNewRow(sqlQuery); } <commit_msg>update of insert.cpp<commit_after>#include <QCoreApplication> #include <iostream> #include "connectdatabase.h" #include "insertrow.h" #include "htmlparser.h" #include "QtSql/qsqlquery.h" //COnstructor : InsertRow::InsertRow(QObject *parent) { /* QObject::connect(SIGNAL(parsingFinished(htmlPage*)), SLOT(convertHtmlPageIntoSqlQuery(htmlPage* query)));*/ sqlQuery = ""; } void InsertRow::insertNewRow(QString sqlQuery) { //on affiche la requete dans la console : std::cout <<sqlQuery.toStdString()<<std::endl; //Création d'un objet de requête : QSqlQuery newQuery; //On teste si la requête a aboutie: if(newQuery.exec(sqlQuery)){ std::cout << "insertion reussie" <<std::endl; } else { std::cout << "votre insertion a rate" <<std::endl; } } void InsertRow::convertHtmlPageIntoSqlQuery(htmlPage *query) { int id = 0; QSqlQuery tempQuery; QStringList keywordList = query->getKeywords(); //On crée ,dans un QString , une requête sql à partir des arguments recus en paramètre : sqlQuery = "INSERT INTO `websites`(`website`,`url`) VALUES('" + query->getTitle() + "','"+ query->getUrl().toString() +"');"; //On appelle la methode sqlQuery : insertNewRow(sqlQuery); //On crée une nlle requête pour récupérer le website_id : sqlQuery = "SELECT `website_id` FROM `websites` WHERE website="+query->getTitle()+";"; //On récupère le website_id de la table website dans un int: if (tempQuery.exec(sqlQuery)) { int id = tempQuery.value(0).toInt(); } else { std::cout << "impossible d'obtenir le website id "<<std::endl; } //On crée une nouvelle requête pour inserer le mot cle correspondant au website id : for(int i = 0; i < query->getKeywords().size();i++) { sqlQuery = "INSERT INTO `keywords` (`keyword`,`keyword_website`) VALUES('"+ keywordList[i] + "','"+ id +"');"; } //sqlQuery = "INSERT INTO `keywords` (`keyword`,`keyword_website`) VALUES('"+query->getKeywords()+ "','"+ id +"');"; insertNewRow(sqlQuery); } <|endoftext|>
<commit_before>#include "antlr4-runtime.h" #include "IDLLexer.h" #include "Visitor.hpp" #include <Windows.h> #undef INTERFACE int main(int argc, char** argv) { antlr4::ANTLRFileStream input("C:/Projects/cpf/Cpf/Support/idl2/TestData/iRegistry.idl"); IDLLexer lexer(&input); antlr4::CommonTokenStream tokenStream(&lexer); IDLParser parser(&tokenStream); antlr4::tree::ParseTree* tree = parser.main(); // Run the visitor. { IDL::Visitor visitor; visitor.visit(tree); printf("-------------------------------------\n"); for (auto it : visitor.GetSymbolTable()) { auto scope = visitor.GetSymbolTable().GetScopeString(it); printf("%s = %s\n", scope.c_str(), it->ToString().c_str()); } } /* std::wstring s = antlrcpp::s2ws(tree->toStringTree(&parser)) + L"\n"; OutputDebugString(s.data()); */ return 0; } <commit_msg>Fixed a path issue in test data after move.<commit_after>#include "antlr4-runtime.h" #include "IDLLexer.h" #include "Visitor.hpp" #include <Windows.h> #undef INTERFACE int main(int argc, char** argv) { antlr4::ANTLRFileStream input("C:/Projects/cpf/Cpf/Support/idl/TestData/iRegistry.idl"); IDLLexer lexer(&input); antlr4::CommonTokenStream tokenStream(&lexer); IDLParser parser(&tokenStream); antlr4::tree::ParseTree* tree = parser.main(); // Run the visitor. { IDL::Visitor visitor; visitor.visit(tree); printf("-------------------------------------\n"); for (auto it : visitor.GetSymbolTable()) { auto scope = visitor.GetSymbolTable().GetScopeString(it); printf("%s = %s\n", scope.c_str(), it->ToString().c_str()); } } /* std::wstring s = antlrcpp::s2ws(tree->toStringTree(&parser)) + L"\n"; OutputDebugString(s.data()); */ return 0; } <|endoftext|>
<commit_before>#include "torrent-descriptor.hh" #include "../stream/base16-encoder.hh" #include "../format/print.hh" namespace mimosa { namespace bittorrent { TorrentDescriptor::TorrentDescriptor() : length_(0), piece_length_(0), is_private_(false) { } TorrentDescriptor::~TorrentDescriptor() { delete[] pieces_; } void TorrentDescriptor::dump(std::ostream &stream) { stream << "Name: " << name_ << std::endl << "Creation Date: " << creation_date_ << std::endl << "Length: " << length_ << std::endl << "Piece Length: " << piece_length_ << std::endl << "Is Private: " << is_private_ << std::endl << "Files:" << std::endl; for (auto &file : files_) stream << " - " << file.path_ << " " << file.length_ << std::endl; stream << "Trackers: " << std::endl; for (auto &tracker : trackers_) stream << tracker.url_ << ", is backup: " << tracker.is_backup_ << std::endl; stream << "Nodes: " << std::endl; for (auto &node : nodes_) stream << node.host_ << " " << node.port_ << std::endl; stream << "Info Hash: " << std::endl; } } } <commit_msg>Fix build error<commit_after>#include "torrent-descriptor.hh" #include "../stream/base16-encoder.hh" #include "../format/print.hh" namespace mimosa { namespace bittorrent { TorrentDescriptor::TorrentDescriptor() : length_(0), piece_length_(0), is_private_(false) { } void TorrentDescriptor::dump(std::ostream &stream) { stream << "Name: " << name_ << std::endl << "Creation Date: " << creation_date_ << std::endl << "Length: " << length_ << std::endl << "Piece Length: " << piece_length_ << std::endl << "Is Private: " << is_private_ << std::endl << "Files:" << std::endl; for (auto &file : files_) stream << " - " << file.path_ << " " << file.length_ << std::endl; stream << "Trackers: " << std::endl; for (auto &tracker : trackers_) stream << tracker.url_ << ", is backup: " << tracker.is_backup_ << std::endl; stream << "Nodes: " << std::endl; for (auto &node : nodes_) stream << node.host_ << " " << node.port_ << std::endl; stream << "Info Hash: " << std::endl; } } } <|endoftext|>
<commit_before>// Do not remove the include below #include "DecnetDisplay.h" #include <EtherCard.h> #include <enc28j60.h> #include <UTFT.h> /** Prototype board header pins =========================== * * Display module * 01-07 -> DB15-DB8 -> 29-22 08 (NC) 09 -> 10 -> 11 -> 12 -> 13 -> * * Ethernet module * 14 -> CS -> 53 15 -> SI -> 51 16 -> SO -> 50 17 -> SCK -> 52 * * Touch interface * * * Power * 22 -> LED backlight -> 5v or 3v 24 -> 3.3V -> 3.3V 26 -> GND -> GND **/ UTFT lcd(ILI9325C, 41, 40, 39, 38); // Remember to change the model parameter to suit your display module! extern uint8_t BigFont[]; extern uint8_t SmallFont[]; static const byte dnMac[] = { 0xaa, 0x00, 0x04, 0x00, 0xe7, 0x1f }; static const byte mCastHelloEN[] = { 0xAB, 0x00, 0x00, 0x03, 0x00, 0x00 }; static const byte mCastHelloRT[] = { 0xAB, 0x00, 0x00, 0x04, 0x00, 0x00 }; static struct node_s nodes[] = { { 7 * 1024 + 6, "MBSERV", 0, OFFLINE, 1, 1 }, { 7 * 1024 + 60, "BITXOV", 0, OFFLINE, 1, 2 }, { 7 * 1024 + 61, "BITXOO", 0, OFFLINE, 1, 3 }, { 7 * 1024 + 64, "BITXO1", 0, OFFLINE, 1, 4 }, { 7 * 1024 + 65, "BITXO2", 0, OFFLINE, 1, 5 }, { 7 * 1024 + 67, "BITXO4", 0, OFFLINE, 1, 6 }, { 7 * 1024 + 68, "BITXO5", 0, OFFLINE, 2, 1 }, { 7 * 1024 + 70, "BITXOT", 0, OFFLINE, 2, 2 }, { 7 * 1024 + 71, "BITXOR", 0, OFFLINE, 2, 3 }, { 7 * 1024 + 72, "BITXOM", 0, OFFLINE, 2, 4 }, { 7 * 1024 + 74, "BITXOW", 0, OFFLINE, 2, 5 }, { 7 * 1024 + 76, "BITXOX", 0, OFFLINE, 2, 6 }, { 7 * 1024 + 77, "BITXOY", 0, OFFLINE, 3, 1 }, { 7 * 1024 + 79, "BITXT0", 0, OFFLINE, 3, 2 }, { 7 * 1024 + 80, "BITXT1", 0, OFFLINE, 3, 3 }, { 7 * 1024 + 81, "BITXOZ", 0, OFFLINE, 3, 4 }, { 7 * 1024 + 82, "BITXOU", 0, OFFLINE, 3, 5 } }; static int numNodes = 17; int numPk = 0; ENC28J60 card; byte ENC28J60::buffer[512]; unsigned long milliseconds = 0; unsigned long lastMilliseconds = 0; unsigned long secondControl = 0; int ledStatus = 0; long cycle = 0L; void setup() { int i; pinMode(LED_BUILTIN, OUTPUT); digitalWrite(LED_BUILTIN, LOW); Serial.begin(57600); Serial.println("Decnet HELLO listener"); Serial.println("Initializing LCD display..."); lcd.InitLCD(); lcd.setFont(BigFont); lcd.clrScr(); lcd.setColor(VGA_GREEN); lcd.setBackColor(VGA_BLACK); lcd.drawRect(0, 0, 319, 199); Serial.println("Initializing ethernet device..."); card.initSPI(); if (card.initialize(sizeof Ethernet::buffer, dnMac, 53) == 0) { Serial.println("Ethernet device not accessible!"); while (true) ; } else { card.enableBroadcast(); card.enableMulticast(); } Serial.println("Ready to go!"); for (i = 0; i < numNodes; i++) { displayNode(lcd, nodes[i]); } lastMilliseconds = millis(); } void loop() { int i; uint16_t len; long interval; char msgbuff[80]; len = card.packetReceive(); if (len > 0) analyzePacket(0, len); milliseconds = millis(); ledStatus = (secondControl - milliseconds) * 512 / 1000; if (ledStatus > 256) ledStatus = 512 - ledStatus; analogWrite(LED_BUILTIN, ledStatus); if (milliseconds - secondControl >= SECOND_MILLIS) { secondControl = milliseconds; displayClock(secondControl); } interval = (int) (milliseconds - lastMilliseconds); if (interval >= CHECK_MILLIS) { lastMilliseconds = milliseconds; for (i = 0; i < numNodes; i++) { if (nodes[i].status != OFFLINE) { nodes[i].countdown -= interval; #ifdef DEBUG sprintf(msgbuff,"Node: %d (%s), cd=%ld, intv=%ld", i, nodes[i].name, nodes[i].countdown, interval); Serial.println(msgbuff); #endif if (nodes[i].countdown <= 0) { if (nodes[i].status == LOST) { nodes[i].status = OFFLINE; nodes[i].countdown = 0; } else { nodes[i].status = LOST; nodes[i].countdown = CYCLE_MILLIS; } displayNode(lcd, nodes[i]); } } } } } void analyzePacket(uint16_t offset, uint16_t len) { char nodename[8]; memset(nodename, 0, 8); int dnAddr; WORD *etherType; struct hello_t *hello; struct node_s *node; struct frame_s *frame; frame = (struct frame_s *) (&ENC28J60::buffer); if (memcmp(mCastHelloEN, frame->dst, 6) != 0 && memcmp(mCastHelloRT, frame->dst, 6) != 0) return; etherType = (WORD *) ((BYTE *) &(ENC28J60::buffer) + OFS_ETHERTYPE); if (*etherType == ET_VLANTAG) etherType++; if (*etherType != ET_DNETROUTING) return; hello = (struct hello_t *) ((BYTE *) etherType + OFS_FRAMESIZE + OFS_FRAME); if ((*((BYTE *) hello) & 0x80) == 0x80) { hello = (struct hello_t *) ((BYTE *) hello + 1); } dnAddr = hello->dnAddr; if (AREA(dnAddr) != MYAREA) return; if (hello->routingFlags.type != 6 && hello->routingFlags.type != 5) return; node = dicotomica(dnAddr, 0, numNodes - 1); if (node == NULL) return; node->countdown = CYCLE_MILLIS; switch (node->status) { case OFFLINE: case LOST: node->status = HELLO; break; case HELLO: case ENDNODE: case ROUTER: switch (hello->nodeInfo.nodeType) { case 3: node->status = ENDNODE; break; case 2: node->status = ROUTER; break; case 1: node->status = ROUTER2; break; } } displayNode(lcd, *node); } void printHexByte(int b) { int high = b / 16; int low = b % 16; Serial.print(high, HEX); Serial.print(low, HEX); } #ifdef DEBUG void dumpPacket(int offset, int len) { int i, j, k; int c; char ascii[33]; memset(ascii, 0, 33); Serial.print("Paquet rebut ("); Serial.print(numPk++); Serial.print("), longitud="); Serial.print(len); Serial.println(" bytes."); j = 0; for (i = 0; i < len; i++) { if (j < 32) { c = ENC28J60::buffer[offset + i]; Serial.print(" "); printHexByte(c); if (isprint(c)) { ascii[j] = c; } else { ascii[j] = '.'; } j += 1; } else { j = 0; Serial.print(" "); Serial.println(ascii); memset(ascii, 0, 33); } } for (; j < 32; j++) { Serial.print(" "); } Serial.print(" "); Serial.println(ascii); } #endif int getDecnetAddress(byte *macPtr) { return *(macPtr + 5) * 256 + *(macPtr + 4); } void getDecnetName(unsigned int addr, char *buffer) { int area = AREA(addr); int node = NODE(addr); sprintf(buffer, "%d.%d", area, node); } void displayString(UTFT &lcd, int col, int fila, char *string, int background, int color) { int x = 1 + (6 * FONTWIDTH + 2) * (col - 1); int y = 1 + (FONTHEIGHT + 1) * (fila - 1); lcd.setBackColor(background); lcd.setColor(color); lcd.print(string, x, y); } void displayNode(UTFT &lcd, struct node_s &node) { int back, color; switch (node.status) { case OFFLINE: back = BKG_OFFLINE; color = FG_OFFLINE; break; case HELLO: back = BKG_NEW; color = FG_NEW; break; case ENDNODE: back = BKG_STD; color = FG_STD; break; case ROUTER: back = BKG_ROUTER; color = FG_ROUTER; break; case ROUTER2: back = BKG_ROUTER2; color = FG_ROUTER2; break; case LOST: back = BKG_LOST; color = FG_LOST; break; default: back = VGA_RED; color = VGA_BLACK; } displayString(lcd, node.dpyX, node.dpyY, node.name, back, color); } struct node_s *dicotomica(unsigned int addr, int inici, int fi) { int tamany = fi - inici - 1; int pivot = inici + tamany / 2; struct node_s *nodePtr; if ((inici < 0) || (inici > numNodes) || (fi < 0) || (fi >= numNodes) || (inici > fi)) return NULL; #ifdef DEBUG Serial.print(inici); Serial.print(" "); Serial.print(fi); Serial.print(" "); Serial.print(addr); Serial.print(" | "); #endif nodePtr = &nodes[pivot]; #ifdef DEBUG Serial.print(pivot); Serial.print("->"); Serial.print(nodePtr->dnaddr); Serial.print(":"); Serial.println(nodePtr->name); #endif if (nodePtr->dnaddr == addr) { return nodePtr; } else if (fi == inici) { return NULL; } else if (nodePtr->dnaddr > addr) { return dicotomica(addr, inici, pivot - 1); } else { return dicotomica(addr, pivot + 1, fi); } } void displayClock(unsigned long millis) { char line[80]; int sec, min, hrs; unsigned long clock = millis / 1000; sec = clock % 60; clock /= 60; min = clock % 60; clock /= 60; hrs = clock; sprintf(line, "Up: %4d:%02d:%02d", hrs, min, sec); lcd.setFont(SmallFont); lcd.setBackColor(VGA_GRAY); lcd.setColor(VGA_YELLOW); lcd.print(line, 208, 202); lcd.setFont(BigFont); } <commit_msg>- Document protoboard display pins<commit_after>// Do not remove the include below #include "DecnetDisplay.h" #include <EtherCard.h> #include <enc28j60.h> #include <UTFT.h> /** Prototype board header pins =========================== * * Display module * 01-08 -> DB15-DB8 -> 29-22 09 (NC) 10 -> WR -> 40 11 -> RS -> 41 12 -> RST-> 38 13 -> CS -> 39 * * Ethernet module * 14 -> CS -> 53 15 -> SI -> 51 16 -> SO -> 50 17 -> SCK -> 52 * * Touch interface * * * Power * 22 -> LED backlight -> 5v or 3v 24 -> 3.3V -> 3.3V 26 -> GND -> GND **/ UTFT lcd(ILI9325C, 41, 40, 39, 38); // Remember to change the model parameter to suit your display module! extern uint8_t BigFont[]; extern uint8_t SmallFont[]; static const byte dnMac[] = { 0xaa, 0x00, 0x04, 0x00, 0xe7, 0x1f }; static const byte mCastHelloEN[] = { 0xAB, 0x00, 0x00, 0x03, 0x00, 0x00 }; static const byte mCastHelloRT[] = { 0xAB, 0x00, 0x00, 0x04, 0x00, 0x00 }; static struct node_s nodes[] = { { 7 * 1024 + 6, "MBSERV", 0, OFFLINE, 1, 1 }, { 7 * 1024 + 60, "BITXOV", 0, OFFLINE, 1, 2 }, { 7 * 1024 + 61, "BITXOO", 0, OFFLINE, 1, 3 }, { 7 * 1024 + 64, "BITXO1", 0, OFFLINE, 1, 4 }, { 7 * 1024 + 65, "BITXO2", 0, OFFLINE, 1, 5 }, { 7 * 1024 + 67, "BITXO4", 0, OFFLINE, 1, 6 }, { 7 * 1024 + 68, "BITXO5", 0, OFFLINE, 2, 1 }, { 7 * 1024 + 70, "BITXOT", 0, OFFLINE, 2, 2 }, { 7 * 1024 + 71, "BITXOR", 0, OFFLINE, 2, 3 }, { 7 * 1024 + 72, "BITXOM", 0, OFFLINE, 2, 4 }, { 7 * 1024 + 74, "BITXOW", 0, OFFLINE, 2, 5 }, { 7 * 1024 + 76, "BITXOX", 0, OFFLINE, 2, 6 }, { 7 * 1024 + 77, "BITXOY", 0, OFFLINE, 3, 1 }, { 7 * 1024 + 79, "BITXT0", 0, OFFLINE, 3, 2 }, { 7 * 1024 + 80, "BITXT1", 0, OFFLINE, 3, 3 }, { 7 * 1024 + 81, "BITXOZ", 0, OFFLINE, 3, 4 }, { 7 * 1024 + 82, "BITXOU", 0, OFFLINE, 3, 5 } }; static int numNodes = 17; int numPk = 0; ENC28J60 card; byte ENC28J60::buffer[512]; unsigned long milliseconds = 0; unsigned long lastMilliseconds = 0; unsigned long secondControl = 0; int ledStatus = 0; long cycle = 0L; void setup() { int i; pinMode(LED_BUILTIN, OUTPUT); digitalWrite(LED_BUILTIN, LOW); Serial.begin(57600); Serial.println("Decnet HELLO listener"); Serial.println("Initializing LCD display..."); lcd.InitLCD(); lcd.setFont(BigFont); lcd.clrScr(); lcd.setColor(VGA_GREEN); lcd.setBackColor(VGA_BLACK); lcd.drawRect(0, 0, 319, 199); Serial.println("Initializing ethernet device..."); card.initSPI(); if (card.initialize(sizeof Ethernet::buffer, dnMac, 53) == 0) { Serial.println("Ethernet device not accessible!"); while (true) ; } else { card.enableBroadcast(); card.enableMulticast(); } Serial.println("Ready to go!"); for (i = 0; i < numNodes; i++) { displayNode(lcd, nodes[i]); } lastMilliseconds = millis(); } void loop() { int i; uint16_t len; long interval; char msgbuff[80]; len = card.packetReceive(); if (len > 0) analyzePacket(0, len); milliseconds = millis(); ledStatus = (secondControl - milliseconds) * 512 / 1000; if (ledStatus > 256) ledStatus = 512 - ledStatus; analogWrite(LED_BUILTIN, ledStatus); if (milliseconds - secondControl >= SECOND_MILLIS) { secondControl = milliseconds; displayClock(secondControl); } interval = (int) (milliseconds - lastMilliseconds); if (interval >= CHECK_MILLIS) { lastMilliseconds = milliseconds; for (i = 0; i < numNodes; i++) { if (nodes[i].status != OFFLINE) { nodes[i].countdown -= interval; #ifdef DEBUG sprintf(msgbuff,"Node: %d (%s), cd=%ld, intv=%ld", i, nodes[i].name, nodes[i].countdown, interval); Serial.println(msgbuff); #endif if (nodes[i].countdown <= 0) { if (nodes[i].status == LOST) { nodes[i].status = OFFLINE; nodes[i].countdown = 0; } else { nodes[i].status = LOST; nodes[i].countdown = CYCLE_MILLIS; } displayNode(lcd, nodes[i]); } } } } } void analyzePacket(uint16_t offset, uint16_t len) { char nodename[8]; memset(nodename, 0, 8); int dnAddr; WORD *etherType; struct hello_t *hello; struct node_s *node; struct frame_s *frame; frame = (struct frame_s *) (&ENC28J60::buffer); if (memcmp(mCastHelloEN, frame->dst, 6) != 0 && memcmp(mCastHelloRT, frame->dst, 6) != 0) return; etherType = (WORD *) ((BYTE *) &(ENC28J60::buffer) + OFS_ETHERTYPE); if (*etherType == ET_VLANTAG) etherType++; if (*etherType != ET_DNETROUTING) return; hello = (struct hello_t *) ((BYTE *) etherType + OFS_FRAMESIZE + OFS_FRAME); if ((*((BYTE *) hello) & 0x80) == 0x80) { hello = (struct hello_t *) ((BYTE *) hello + 1); } dnAddr = hello->dnAddr; if (AREA(dnAddr) != MYAREA) return; if (hello->routingFlags.type != 6 && hello->routingFlags.type != 5) return; node = dicotomica(dnAddr, 0, numNodes - 1); if (node == NULL) return; node->countdown = CYCLE_MILLIS; switch (node->status) { case OFFLINE: case LOST: node->status = HELLO; break; case HELLO: case ENDNODE: case ROUTER: switch (hello->nodeInfo.nodeType) { case 3: node->status = ENDNODE; break; case 2: node->status = ROUTER; break; case 1: node->status = ROUTER2; break; } } displayNode(lcd, *node); } void printHexByte(int b) { int high = b / 16; int low = b % 16; Serial.print(high, HEX); Serial.print(low, HEX); } #ifdef DEBUG void dumpPacket(int offset, int len) { int i, j, k; int c; char ascii[33]; memset(ascii, 0, 33); Serial.print("Paquet rebut ("); Serial.print(numPk++); Serial.print("), longitud="); Serial.print(len); Serial.println(" bytes."); j = 0; for (i = 0; i < len; i++) { if (j < 32) { c = ENC28J60::buffer[offset + i]; Serial.print(" "); printHexByte(c); if (isprint(c)) { ascii[j] = c; } else { ascii[j] = '.'; } j += 1; } else { j = 0; Serial.print(" "); Serial.println(ascii); memset(ascii, 0, 33); } } for (; j < 32; j++) { Serial.print(" "); } Serial.print(" "); Serial.println(ascii); } #endif int getDecnetAddress(byte *macPtr) { return *(macPtr + 5) * 256 + *(macPtr + 4); } void getDecnetName(unsigned int addr, char *buffer) { int area = AREA(addr); int node = NODE(addr); sprintf(buffer, "%d.%d", area, node); } void displayString(UTFT &lcd, int col, int fila, char *string, int background, int color) { int x = 1 + (6 * FONTWIDTH + 2) * (col - 1); int y = 1 + (FONTHEIGHT + 1) * (fila - 1); lcd.setBackColor(background); lcd.setColor(color); lcd.print(string, x, y); } void displayNode(UTFT &lcd, struct node_s &node) { int back, color; switch (node.status) { case OFFLINE: back = BKG_OFFLINE; color = FG_OFFLINE; break; case HELLO: back = BKG_NEW; color = FG_NEW; break; case ENDNODE: back = BKG_STD; color = FG_STD; break; case ROUTER: back = BKG_ROUTER; color = FG_ROUTER; break; case ROUTER2: back = BKG_ROUTER2; color = FG_ROUTER2; break; case LOST: back = BKG_LOST; color = FG_LOST; break; default: back = VGA_RED; color = VGA_BLACK; } displayString(lcd, node.dpyX, node.dpyY, node.name, back, color); } struct node_s *dicotomica(unsigned int addr, int inici, int fi) { int tamany = fi - inici - 1; int pivot = inici + tamany / 2; struct node_s *nodePtr; if ((inici < 0) || (inici > numNodes) || (fi < 0) || (fi >= numNodes) || (inici > fi)) return NULL; #ifdef DEBUG Serial.print(inici); Serial.print(" "); Serial.print(fi); Serial.print(" "); Serial.print(addr); Serial.print(" | "); #endif nodePtr = &nodes[pivot]; #ifdef DEBUG Serial.print(pivot); Serial.print("->"); Serial.print(nodePtr->dnaddr); Serial.print(":"); Serial.println(nodePtr->name); #endif if (nodePtr->dnaddr == addr) { return nodePtr; } else if (fi == inici) { return NULL; } else if (nodePtr->dnaddr > addr) { return dicotomica(addr, inici, pivot - 1); } else { return dicotomica(addr, pivot + 1, fi); } } void displayClock(unsigned long millis) { char line[80]; int sec, min, hrs; unsigned long clock = millis / 1000; sec = clock % 60; clock /= 60; min = clock % 60; clock /= 60; hrs = clock; sprintf(line, "Up: %4d:%02d:%02d", hrs, min, sec); lcd.setFont(SmallFont); lcd.setBackColor(VGA_GRAY); lcd.setColor(VGA_YELLOW); lcd.print(line, 208, 202); lcd.setFont(BigFont); } <|endoftext|>
<commit_before> #include "fuelgauge.h" FuelGauge::FuelGauge() { } boolean FuelGauge::begin() { // this should be unecessary since, begin is already called from pmic setup return 1; } // Read and return the cell voltage float FuelGauge::getVCell() { byte MSB = 0; byte LSB = 0; readRegister(VCELL_REGISTER, MSB, LSB); int value = (MSB << 4) | (LSB >> 4); return map(value, 0x000, 0xFFF, 0, 50000) / 10000.0; //return value * 0.00125; } // Read and return the state of charge of the cell float FuelGauge::getSoC() { byte MSB = 0; byte LSB = 0; readRegister(SOC_REGISTER, MSB, LSB); float decimal = LSB / 256.0; return MSB + decimal; } // Return the version number of the chip int FuelGauge::getVersion() { byte MSB = 0; byte LSB = 0; readRegister(VERSION_REGISTER, MSB, LSB); return (MSB << 8) | LSB; } byte FuelGauge::getCompensateValue() { byte MSB = 0; byte LSB = 0; readConfigRegister(MSB, LSB); return MSB; } byte FuelGauge::getAlertThreshold() { byte MSB = 0; byte LSB = 0; readConfigRegister(MSB, LSB); return 32 - (LSB & 0x1F); } void FuelGauge::setAlertThreshold(byte threshold) { byte MSB = 0; byte LSB = 0; readConfigRegister(MSB, LSB); if(threshold > 32) threshold = 32; threshold = 32 - threshold; writeRegister(CONFIG_REGISTER, MSB, (LSB & 0xE0) | threshold); } // Check if alert interrupt was generated boolean FuelGauge::getAlert() { byte MSB = 0; byte LSB = 0; readConfigRegister(MSB, LSB); return LSB & 0x20; } void FuelGauge::clearAlert() { byte MSB = 0; byte LSB = 0; readConfigRegister(MSB, LSB); } void FuelGauge::reset() { writeRegister(COMMAND_REGISTER, 0x00, 0x54); } void FuelGauge::quickStart() { writeRegister(MODE_REGISTER, 0x40, 0x00); } void FuelGauge::readConfigRegister(byte &MSB, byte &LSB) { readRegister(CONFIG_REGISTER, MSB, LSB); } void FuelGauge::readRegister(byte startAddress, byte &MSB, byte &LSB) { Wire3.beginTransmission(MAX17043_ADDRESS); Wire3.write(startAddress); Wire3.endTransmission(true); Wire3.requestFrom(MAX17043_ADDRESS, 2, true); MSB = Wire3.read(); LSB = Wire3.read(); } void FuelGauge::writeRegister(byte address, byte MSB, byte LSB) { Wire3.beginTransmission(MAX17043_ADDRESS); Wire3.write(address); Wire3.write(MSB); Wire3.write(LSB); Wire3.endTransmission(true); }<commit_msg>Delete uber-library-example.cpp<commit_after><|endoftext|>
<commit_before>/* * Copyright (C) 2013 The Android Open Source Project * * 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 "malloc_space.h" #include "gc/accounting/card_table-inl.h" #include "gc/accounting/space_bitmap-inl.h" #include "gc/heap.h" #include "gc/space/space-inl.h" #include "gc/space/zygote_space.h" #include "mirror/class-inl.h" #include "mirror/object-inl.h" #include "runtime.h" #include "handle_scope-inl.h" #include "thread.h" #include "thread_list.h" #include "utils.h" namespace art { namespace gc { namespace space { size_t MallocSpace::bitmap_index_ = 0; MallocSpace::MallocSpace(const std::string& name, MemMap* mem_map, byte* begin, byte* end, byte* limit, size_t growth_limit, bool create_bitmaps, bool can_move_objects, size_t starting_size, size_t initial_size) : ContinuousMemMapAllocSpace(name, mem_map, begin, end, limit, kGcRetentionPolicyAlwaysCollect), recent_free_pos_(0), lock_("allocation space lock", kAllocSpaceLock), growth_limit_(growth_limit), can_move_objects_(can_move_objects), starting_size_(starting_size), initial_size_(initial_size) { if (create_bitmaps) { size_t bitmap_index = bitmap_index_++; static const uintptr_t kGcCardSize = static_cast<uintptr_t>(accounting::CardTable::kCardSize); CHECK(IsAligned<kGcCardSize>(reinterpret_cast<uintptr_t>(mem_map->Begin()))); CHECK(IsAligned<kGcCardSize>(reinterpret_cast<uintptr_t>(mem_map->End()))); live_bitmap_.reset(accounting::ContinuousSpaceBitmap::Create( StringPrintf("allocspace %s live-bitmap %d", name.c_str(), static_cast<int>(bitmap_index)), Begin(), Capacity())); DCHECK(live_bitmap_.get() != nullptr) << "could not create allocspace live bitmap #" << bitmap_index; mark_bitmap_.reset(accounting::ContinuousSpaceBitmap::Create( StringPrintf("allocspace %s mark-bitmap %d", name.c_str(), static_cast<int>(bitmap_index)), Begin(), Capacity())); DCHECK(live_bitmap_.get() != nullptr) << "could not create allocspace mark bitmap #" << bitmap_index; } for (auto& freed : recent_freed_objects_) { freed.first = nullptr; freed.second = nullptr; } } MemMap* MallocSpace::CreateMemMap(const std::string& name, size_t starting_size, size_t* initial_size, size_t* growth_limit, size_t* capacity, byte* requested_begin) { // Sanity check arguments if (starting_size > *initial_size) { *initial_size = starting_size; } if (*initial_size > *growth_limit) { LOG(ERROR) << "Failed to create alloc space (" << name << ") where the initial size (" << PrettySize(*initial_size) << ") is larger than its capacity (" << PrettySize(*growth_limit) << ")"; return NULL; } if (*growth_limit > *capacity) { LOG(ERROR) << "Failed to create alloc space (" << name << ") where the growth limit capacity (" << PrettySize(*growth_limit) << ") is larger than the capacity (" << PrettySize(*capacity) << ")"; return NULL; } // Page align growth limit and capacity which will be used to manage mmapped storage *growth_limit = RoundUp(*growth_limit, kPageSize); *capacity = RoundUp(*capacity, kPageSize); std::string error_msg; MemMap* mem_map = MemMap::MapAnonymous(name.c_str(), requested_begin, *capacity, PROT_READ | PROT_WRITE, true, &error_msg); if (mem_map == nullptr) { LOG(ERROR) << "Failed to allocate pages for alloc space (" << name << ") of size " << PrettySize(*capacity) << ": " << error_msg; } return mem_map; } mirror::Class* MallocSpace::FindRecentFreedObject(const mirror::Object* obj) { size_t pos = recent_free_pos_; // Start at the most recently freed object and work our way back since there may be duplicates // caused by dlmalloc reusing memory. if (kRecentFreeCount > 0) { for (size_t i = 0; i + 1 < kRecentFreeCount + 1; ++i) { pos = pos != 0 ? pos - 1 : kRecentFreeMask; if (recent_freed_objects_[pos].first == obj) { return recent_freed_objects_[pos].second; } } } return nullptr; } void MallocSpace::RegisterRecentFree(mirror::Object* ptr) { // No verification since the object is dead. recent_freed_objects_[recent_free_pos_] = std::make_pair(ptr, ptr->GetClass<kVerifyNone>()); recent_free_pos_ = (recent_free_pos_ + 1) & kRecentFreeMask; } void MallocSpace::SetGrowthLimit(size_t growth_limit) { growth_limit = RoundUp(growth_limit, kPageSize); growth_limit_ = growth_limit; if (Size() > growth_limit_) { end_ = begin_ + growth_limit; } } void* MallocSpace::MoreCore(intptr_t increment) { CheckMoreCoreForPrecondition(); byte* original_end = end_; if (increment != 0) { VLOG(heap) << "MallocSpace::MoreCore " << PrettySize(increment); byte* new_end = original_end + increment; if (increment > 0) { // Should never be asked to increase the allocation beyond the capacity of the space. Enforced // by mspace_set_footprint_limit. CHECK_LE(new_end, Begin() + Capacity()); CHECK_MEMORY_CALL(mprotect, (original_end, increment, PROT_READ | PROT_WRITE), GetName()); } else { // Should never be asked for negative footprint (ie before begin). Zero footprint is ok. CHECK_GE(original_end + increment, Begin()); // Advise we don't need the pages and protect them // TODO: by removing permissions to the pages we may be causing TLB shoot-down which can be // expensive (note the same isn't true for giving permissions to a page as the protected // page shouldn't be in a TLB). We should investigate performance impact of just // removing ignoring the memory protection change here and in Space::CreateAllocSpace. It's // likely just a useful debug feature. size_t size = -increment; CHECK_MEMORY_CALL(madvise, (new_end, size, MADV_DONTNEED), GetName()); CHECK_MEMORY_CALL(mprotect, (new_end, size, PROT_NONE), GetName()); } // Update end_ end_ = new_end; } return original_end; } ZygoteSpace* MallocSpace::CreateZygoteSpace(const char* alloc_space_name, bool low_memory_mode, MallocSpace** out_malloc_space) { // For RosAlloc, revoke thread local runs before creating a new // alloc space so that we won't mix thread local runs from different // alloc spaces. RevokeAllThreadLocalBuffers(); end_ = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(end_), kPageSize)); DCHECK(IsAligned<accounting::CardTable::kCardSize>(begin_)); DCHECK(IsAligned<accounting::CardTable::kCardSize>(end_)); DCHECK(IsAligned<kPageSize>(begin_)); DCHECK(IsAligned<kPageSize>(end_)); size_t size = RoundUp(Size(), kPageSize); // Trimming the heap should be done by the caller since we may have invalidated the accounting // stored in between objects. // Remaining size is for the new alloc space. const size_t growth_limit = growth_limit_ - size; const size_t capacity = Capacity() - size; VLOG(heap) << "Begin " << reinterpret_cast<const void*>(begin_) << "\n" << "End " << reinterpret_cast<const void*>(end_) << "\n" << "Size " << size << "\n" << "GrowthLimit " << growth_limit_ << "\n" << "Capacity " << Capacity(); SetGrowthLimit(RoundUp(size, kPageSize)); // FIXME: Do we need reference counted pointers here? // Make the two spaces share the same mark bitmaps since the bitmaps span both of the spaces. VLOG(heap) << "Creating new AllocSpace: "; VLOG(heap) << "Size " << GetMemMap()->Size(); VLOG(heap) << "GrowthLimit " << PrettySize(growth_limit); VLOG(heap) << "Capacity " << PrettySize(capacity); // Remap the tail. std::string error_msg; std::unique_ptr<MemMap> mem_map(GetMemMap()->RemapAtEnd(end_, alloc_space_name, PROT_READ | PROT_WRITE, &error_msg)); CHECK(mem_map.get() != nullptr) << error_msg; void* allocator = CreateAllocator(end_, starting_size_, initial_size_, capacity, low_memory_mode); // Protect memory beyond the initial size. byte* end = mem_map->Begin() + starting_size_; if (capacity > initial_size_) { CHECK_MEMORY_CALL(mprotect, (end, capacity - initial_size_, PROT_NONE), alloc_space_name); } *out_malloc_space = CreateInstance(alloc_space_name, mem_map.release(), allocator, end_, end, limit_, growth_limit, CanMoveObjects()); SetLimit(End()); live_bitmap_->SetHeapLimit(reinterpret_cast<uintptr_t>(End())); CHECK_EQ(live_bitmap_->HeapLimit(), reinterpret_cast<uintptr_t>(End())); mark_bitmap_->SetHeapLimit(reinterpret_cast<uintptr_t>(End())); CHECK_EQ(mark_bitmap_->HeapLimit(), reinterpret_cast<uintptr_t>(End())); // Create the actual zygote space. ZygoteSpace* zygote_space = ZygoteSpace::Create("Zygote space", ReleaseMemMap(), live_bitmap_.release(), mark_bitmap_.release()); if (UNLIKELY(zygote_space == nullptr)) { VLOG(heap) << "Failed creating zygote space from space " << GetName(); } else { VLOG(heap) << "zygote space creation done"; } return zygote_space; } void MallocSpace::Dump(std::ostream& os) const { os << GetType() << " begin=" << reinterpret_cast<void*>(Begin()) << ",end=" << reinterpret_cast<void*>(End()) << ",size=" << PrettySize(Size()) << ",capacity=" << PrettySize(Capacity()) << ",name=\"" << GetName() << "\"]"; } void MallocSpace::SweepCallback(size_t num_ptrs, mirror::Object** ptrs, void* arg) { SweepCallbackContext* context = static_cast<SweepCallbackContext*>(arg); space::MallocSpace* space = context->space->AsMallocSpace(); Thread* self = context->self; Locks::heap_bitmap_lock_->AssertExclusiveHeld(self); // If the bitmaps aren't swapped we need to clear the bits since the GC isn't going to re-swap // the bitmaps as an optimization. if (!context->swap_bitmaps) { accounting::ContinuousSpaceBitmap* bitmap = space->GetLiveBitmap(); for (size_t i = 0; i < num_ptrs; ++i) { bitmap->Clear(ptrs[i]); } } // Use a bulk free, that merges consecutive objects before freeing or free per object? // Documentation suggests better free performance with merging, but this may be at the expensive // of allocation. context->freed_objects += num_ptrs; context->freed_bytes += space->FreeList(self, num_ptrs, ptrs); } } // namespace space } // namespace gc } // namespace art <commit_msg>am 0130ba04: Merge "Allocate large enough space bitmaps for malloc spaces."<commit_after>/* * Copyright (C) 2013 The Android Open Source Project * * 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 "malloc_space.h" #include "gc/accounting/card_table-inl.h" #include "gc/accounting/space_bitmap-inl.h" #include "gc/heap.h" #include "gc/space/space-inl.h" #include "gc/space/zygote_space.h" #include "mirror/class-inl.h" #include "mirror/object-inl.h" #include "runtime.h" #include "handle_scope-inl.h" #include "thread.h" #include "thread_list.h" #include "utils.h" namespace art { namespace gc { namespace space { size_t MallocSpace::bitmap_index_ = 0; MallocSpace::MallocSpace(const std::string& name, MemMap* mem_map, byte* begin, byte* end, byte* limit, size_t growth_limit, bool create_bitmaps, bool can_move_objects, size_t starting_size, size_t initial_size) : ContinuousMemMapAllocSpace(name, mem_map, begin, end, limit, kGcRetentionPolicyAlwaysCollect), recent_free_pos_(0), lock_("allocation space lock", kAllocSpaceLock), growth_limit_(growth_limit), can_move_objects_(can_move_objects), starting_size_(starting_size), initial_size_(initial_size) { if (create_bitmaps) { size_t bitmap_index = bitmap_index_++; static const uintptr_t kGcCardSize = static_cast<uintptr_t>(accounting::CardTable::kCardSize); CHECK(IsAligned<kGcCardSize>(reinterpret_cast<uintptr_t>(mem_map->Begin()))); CHECK(IsAligned<kGcCardSize>(reinterpret_cast<uintptr_t>(mem_map->End()))); live_bitmap_.reset(accounting::ContinuousSpaceBitmap::Create( StringPrintf("allocspace %s live-bitmap %d", name.c_str(), static_cast<int>(bitmap_index)), Begin(), NonGrowthLimitCapacity())); DCHECK(live_bitmap_.get() != nullptr) << "could not create allocspace live bitmap #" << bitmap_index; mark_bitmap_.reset(accounting::ContinuousSpaceBitmap::Create( StringPrintf("allocspace %s mark-bitmap %d", name.c_str(), static_cast<int>(bitmap_index)), Begin(), NonGrowthLimitCapacity())); DCHECK(live_bitmap_.get() != nullptr) << "could not create allocspace mark bitmap #" << bitmap_index; } for (auto& freed : recent_freed_objects_) { freed.first = nullptr; freed.second = nullptr; } } MemMap* MallocSpace::CreateMemMap(const std::string& name, size_t starting_size, size_t* initial_size, size_t* growth_limit, size_t* capacity, byte* requested_begin) { // Sanity check arguments if (starting_size > *initial_size) { *initial_size = starting_size; } if (*initial_size > *growth_limit) { LOG(ERROR) << "Failed to create alloc space (" << name << ") where the initial size (" << PrettySize(*initial_size) << ") is larger than its capacity (" << PrettySize(*growth_limit) << ")"; return NULL; } if (*growth_limit > *capacity) { LOG(ERROR) << "Failed to create alloc space (" << name << ") where the growth limit capacity (" << PrettySize(*growth_limit) << ") is larger than the capacity (" << PrettySize(*capacity) << ")"; return NULL; } // Page align growth limit and capacity which will be used to manage mmapped storage *growth_limit = RoundUp(*growth_limit, kPageSize); *capacity = RoundUp(*capacity, kPageSize); std::string error_msg; MemMap* mem_map = MemMap::MapAnonymous(name.c_str(), requested_begin, *capacity, PROT_READ | PROT_WRITE, true, &error_msg); if (mem_map == nullptr) { LOG(ERROR) << "Failed to allocate pages for alloc space (" << name << ") of size " << PrettySize(*capacity) << ": " << error_msg; } return mem_map; } mirror::Class* MallocSpace::FindRecentFreedObject(const mirror::Object* obj) { size_t pos = recent_free_pos_; // Start at the most recently freed object and work our way back since there may be duplicates // caused by dlmalloc reusing memory. if (kRecentFreeCount > 0) { for (size_t i = 0; i + 1 < kRecentFreeCount + 1; ++i) { pos = pos != 0 ? pos - 1 : kRecentFreeMask; if (recent_freed_objects_[pos].first == obj) { return recent_freed_objects_[pos].second; } } } return nullptr; } void MallocSpace::RegisterRecentFree(mirror::Object* ptr) { // No verification since the object is dead. recent_freed_objects_[recent_free_pos_] = std::make_pair(ptr, ptr->GetClass<kVerifyNone>()); recent_free_pos_ = (recent_free_pos_ + 1) & kRecentFreeMask; } void MallocSpace::SetGrowthLimit(size_t growth_limit) { growth_limit = RoundUp(growth_limit, kPageSize); growth_limit_ = growth_limit; if (Size() > growth_limit_) { end_ = begin_ + growth_limit; } } void* MallocSpace::MoreCore(intptr_t increment) { CheckMoreCoreForPrecondition(); byte* original_end = end_; if (increment != 0) { VLOG(heap) << "MallocSpace::MoreCore " << PrettySize(increment); byte* new_end = original_end + increment; if (increment > 0) { // Should never be asked to increase the allocation beyond the capacity of the space. Enforced // by mspace_set_footprint_limit. CHECK_LE(new_end, Begin() + Capacity()); CHECK_MEMORY_CALL(mprotect, (original_end, increment, PROT_READ | PROT_WRITE), GetName()); } else { // Should never be asked for negative footprint (ie before begin). Zero footprint is ok. CHECK_GE(original_end + increment, Begin()); // Advise we don't need the pages and protect them // TODO: by removing permissions to the pages we may be causing TLB shoot-down which can be // expensive (note the same isn't true for giving permissions to a page as the protected // page shouldn't be in a TLB). We should investigate performance impact of just // removing ignoring the memory protection change here and in Space::CreateAllocSpace. It's // likely just a useful debug feature. size_t size = -increment; CHECK_MEMORY_CALL(madvise, (new_end, size, MADV_DONTNEED), GetName()); CHECK_MEMORY_CALL(mprotect, (new_end, size, PROT_NONE), GetName()); } // Update end_ end_ = new_end; } return original_end; } ZygoteSpace* MallocSpace::CreateZygoteSpace(const char* alloc_space_name, bool low_memory_mode, MallocSpace** out_malloc_space) { // For RosAlloc, revoke thread local runs before creating a new // alloc space so that we won't mix thread local runs from different // alloc spaces. RevokeAllThreadLocalBuffers(); end_ = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(end_), kPageSize)); DCHECK(IsAligned<accounting::CardTable::kCardSize>(begin_)); DCHECK(IsAligned<accounting::CardTable::kCardSize>(end_)); DCHECK(IsAligned<kPageSize>(begin_)); DCHECK(IsAligned<kPageSize>(end_)); size_t size = RoundUp(Size(), kPageSize); // Trimming the heap should be done by the caller since we may have invalidated the accounting // stored in between objects. // Remaining size is for the new alloc space. const size_t growth_limit = growth_limit_ - size; const size_t capacity = Capacity() - size; VLOG(heap) << "Begin " << reinterpret_cast<const void*>(begin_) << "\n" << "End " << reinterpret_cast<const void*>(end_) << "\n" << "Size " << size << "\n" << "GrowthLimit " << growth_limit_ << "\n" << "Capacity " << Capacity(); SetGrowthLimit(RoundUp(size, kPageSize)); // FIXME: Do we need reference counted pointers here? // Make the two spaces share the same mark bitmaps since the bitmaps span both of the spaces. VLOG(heap) << "Creating new AllocSpace: "; VLOG(heap) << "Size " << GetMemMap()->Size(); VLOG(heap) << "GrowthLimit " << PrettySize(growth_limit); VLOG(heap) << "Capacity " << PrettySize(capacity); // Remap the tail. std::string error_msg; std::unique_ptr<MemMap> mem_map(GetMemMap()->RemapAtEnd(end_, alloc_space_name, PROT_READ | PROT_WRITE, &error_msg)); CHECK(mem_map.get() != nullptr) << error_msg; void* allocator = CreateAllocator(end_, starting_size_, initial_size_, capacity, low_memory_mode); // Protect memory beyond the initial size. byte* end = mem_map->Begin() + starting_size_; if (capacity > initial_size_) { CHECK_MEMORY_CALL(mprotect, (end, capacity - initial_size_, PROT_NONE), alloc_space_name); } *out_malloc_space = CreateInstance(alloc_space_name, mem_map.release(), allocator, end_, end, limit_, growth_limit, CanMoveObjects()); SetLimit(End()); live_bitmap_->SetHeapLimit(reinterpret_cast<uintptr_t>(End())); CHECK_EQ(live_bitmap_->HeapLimit(), reinterpret_cast<uintptr_t>(End())); mark_bitmap_->SetHeapLimit(reinterpret_cast<uintptr_t>(End())); CHECK_EQ(mark_bitmap_->HeapLimit(), reinterpret_cast<uintptr_t>(End())); // Create the actual zygote space. ZygoteSpace* zygote_space = ZygoteSpace::Create("Zygote space", ReleaseMemMap(), live_bitmap_.release(), mark_bitmap_.release()); if (UNLIKELY(zygote_space == nullptr)) { VLOG(heap) << "Failed creating zygote space from space " << GetName(); } else { VLOG(heap) << "zygote space creation done"; } return zygote_space; } void MallocSpace::Dump(std::ostream& os) const { os << GetType() << " begin=" << reinterpret_cast<void*>(Begin()) << ",end=" << reinterpret_cast<void*>(End()) << ",limit=" << reinterpret_cast<void*>(Limit()) << ",size=" << PrettySize(Size()) << ",capacity=" << PrettySize(Capacity()) << ",non_growth_limit_capacity=" << PrettySize(NonGrowthLimitCapacity()) << ",name=\"" << GetName() << "\"]"; } void MallocSpace::SweepCallback(size_t num_ptrs, mirror::Object** ptrs, void* arg) { SweepCallbackContext* context = static_cast<SweepCallbackContext*>(arg); space::MallocSpace* space = context->space->AsMallocSpace(); Thread* self = context->self; Locks::heap_bitmap_lock_->AssertExclusiveHeld(self); // If the bitmaps aren't swapped we need to clear the bits since the GC isn't going to re-swap // the bitmaps as an optimization. if (!context->swap_bitmaps) { accounting::ContinuousSpaceBitmap* bitmap = space->GetLiveBitmap(); for (size_t i = 0; i < num_ptrs; ++i) { bitmap->Clear(ptrs[i]); } } // Use a bulk free, that merges consecutive objects before freeing or free per object? // Documentation suggests better free performance with merging, but this may be at the expensive // of allocation. context->freed_objects += num_ptrs; context->freed_bytes += space->FreeList(self, num_ptrs, ptrs); } } // namespace space } // namespace gc } // namespace art <|endoftext|>
<commit_before>/* * File: curves.cpp * Author: Isaac Yochelson * * Created on August 22, 2013, 10:30 AM */ #include <moveit/move_group_interface/move_group.h> #include <moveit_msgs/RobotTrajectory.h> #include <trajectory_msgs/JointTrajectory.h> #include <trajectory_msgs/MultiDOFJointTrajectory.h> #include <geometry_msgs/Pose.h> #include <baxter_core_msgs/EndpointState.h> #include <cstdlib> //standard library for C/C++ #include <iostream> #include <fstream> #include <boost/tokenizer.hpp> using namespace std; string filename = "trj_curve_left_15.txt"; string output = "trj_curve_left_15.trj"; ofstream planOutput; double addTime = 0; geometry_msgs::Pose target; moveit::planning_interface::MoveGroup::Plan planToPose(string joint, move_group_interface::MoveGroup& group, geometry_msgs::Pose* pose); void openPlan(string filename, moveit::planning_interface::MoveGroup::Plan plan); void savePlan(moveit::planning_interface::MoveGroup::Plan plan); void closePlan(); void fillMap(map<string, vector<double> > &goal, string filename); void generateAndSavePlan(move_group_interface::MoveGroup* group, string joint); int main(int argc, char** argv) { ros::init(argc, argv, "Test_Node"); // start a ROS spinning thread ros::AsyncSpinner spinner(1); spinner.start(); // Create MoveGroup instances for each arm, set them to PRM*, and create a pointer to be assigned // to the correct arm to be used for each target. move_group_interface::MoveGroup leftGroup("left_arm"); move_group_interface::MoveGroup rightGroup("right_arm"); leftGroup.setPlannerId("PRMstarkConfigDefault"); leftGroup.setStartStateToCurrentState(); rightGroup.setPlannerId("PRMstarkConfigDefault"); rightGroup.setStartStateToCurrentState(); move_group_interface::MoveGroup* group; target.orientation.x = 0; target.orientation.y = 1; target.orientation.z = 0; target.orientation.w = 0; group = &rightGroup; string joint = "right_wrist"; addTime = 0; stringstream filestream; filestream << "short_" << 3 << ".csv"; filename = filestream.str(); stringstream outstream; outstream << "short_" << 3 << ".trj"; output = outstream.str(); system ("rosrun baxter_examples joint_position_file_playback.py -f clear.trj"); generateAndSavePlan(group, joint); /* for (int i = 3; i < 9; ++i) { addTime = 0; stringstream filestream; filestream << "trj_curve_right_" << i << ".txt"; filename = filestream.str(); stringstream outstream; outstream << "trj_curve_right_" << i << ".trj"; output = outstream.str(); system ("rosrun baxter_examples joint_position_file_playback.py -f clear.trj"); generateAndSavePlan(group, joint); } for (int i = 3; i < 9; ++i) { addTime = 0; stringstream filestream; filestream << "trj_straight_right_" << i << ".txt"; filename = filestream.str(); stringstream outstream; outstream << "trj_straight_right_" << i << ".trj"; output = outstream.str(); system ("rosrun baxter_examples joint_position_file_playback.py -f clear.trj"); generateAndSavePlan(group, joint); } for (int i = 3; i < 9; ++i) { addTime = 0; stringstream filestream; filestream << "short_" << i << ".csv"; filename = filestream.str(); stringstream outstream; outstream << "short_right_" << i << ".trj"; output = outstream.str(); system ("rosrun baxter_examples joint_position_file_playback.py -f clear.trj"); generateAndSavePlan(group, joint); } group = &leftGroup; joint = "left_wrist"; for (int i = 13; i > 7; --i) { addTime = 0; stringstream filestream; filestream << "trj_curve_left_" << i << ".txt"; filename = filestream.str(); stringstream outstream; outstream << "trj_curve_left_" << i << ".trj"; output = outstream.str(); system ("rosrun baxter_examples joint_position_file_playback.py -f clear.trj"); generateAndSavePlan(group, joint); } for (int i = 13; i > 7; --i) { addTime = 0; stringstream filestream; filestream << "trj_straight_left_" << i << ".txt"; filename = filestream.str(); stringstream outstream; outstream << "trj_straight_left_" << i << ".trj"; output = outstream.str(); system ("rosrun baxter_examples joint_position_file_playback.py -f clear.trj"); generateAndSavePlan(group, joint); } for (int i = 13; i > 7; --i) { addTime = 0; stringstream filestream; filestream << "short_" << i << ".csv"; filename = filestream.str(); stringstream outstream; outstream << "short_" << i << ".trj"; output = outstream.str(); system ("rosrun baxter_examples joint_position_file_playback.py -f clear.trj"); generateAndSavePlan(group, joint); }*/ return 0; } void generateAndSavePlan(move_group_interface::MoveGroup* group, string joint) { moveit::planning_interface::MoveGroup::Plan plan; map<string, vector<double> > targetMap; fillMap(targetMap, filename); vector<double>::iterator xiter = targetMap["x"].begin(); vector<double>::iterator yiter = targetMap["y"].begin(); vector<double>::iterator ziter = targetMap["z"].begin(); vector<double>::iterator qxiter = targetMap["qx"].begin(); vector<double>::iterator qyiter = targetMap["qy"].begin(); vector<double>::iterator qziter = targetMap["qz"].begin(); vector<double>::iterator qwiter = targetMap["qw"].begin(); cout << "iterators set" << endl; for (xiter= targetMap["x"].begin(); xiter != targetMap["x"].end(); ++xiter) { target.position.x = *xiter; target.position.y = *yiter; target.position.z = *ziter; cout << "position set" << endl; target.orientation.x = *qxiter; target.orientation.y = *qyiter; target.orientation.z = *qziter; target.orientation.w = *qwiter; cout << "orientation set" << endl; ++yiter; ++ziter; ++qxiter; ++qyiter; ++qziter; ++qwiter; cout << "planning to: " << target << endl; plan = planToPose(joint, *group, &target); if (xiter == targetMap["x"].begin()) { openPlan(output, plan); } savePlan(plan); } cout << "closing plan" << endl; closePlan(); } moveit::planning_interface::MoveGroup::Plan planToPose(string joint, move_group_interface::MoveGroup& group, geometry_msgs::Pose* pose) { bool gotPlan; moveit::planning_interface::MoveGroup::Plan plan; group.setPoseTarget(*pose, joint); ROS_INFO("requesting plan."); gotPlan = group.plan(plan); if (gotPlan) { ROS_INFO("plan received."); // cout << plan.trajectory_ << endl; group.execute(plan); ROS_INFO("plan execution completed."); } return plan; } void fillMap(map<string, vector<double> > &goals, string filename) { cout << "filling map: " << filename << endl; ifstream goalInput; goalInput.open(filename.c_str()); double value; string keyLine = "x,y,z,qx,qy,qz,qw"; string valueLine; cout << keyLine << endl; typedef boost::tokenizer<boost::char_separator<char> > tokenizer; boost::char_separator<char> commaDelimited(", "); tokenizer keys(keyLine, commaDelimited); int count = 0; while (getline(goalInput, valueLine)) { ++count; tokenizer values(valueLine, commaDelimited); tokenizer::iterator value_iter = values.begin(); for (tokenizer::iterator key_iter = keys.begin(); key_iter != keys.end() && value_iter != values.end(); ++key_iter) { value = atof((*value_iter).c_str()); goals[*key_iter].push_back(value); ++value_iter; } } goalInput.close(); cout << "fillMap finished: " << count << " lines" << endl; } void openPlan(string filename, moveit::planning_interface::MoveGroup::Plan plan) { planOutput.open(filename.c_str()); planOutput << "time"; for(vector<string>::iterator it = plan.trajectory_.joint_trajectory.joint_names.begin(); it != plan.trajectory_.joint_trajectory.joint_names.end(); it++) { planOutput << "," << *it; } planOutput << "\n"; } void closePlan() { planOutput.close(); } void savePlan(moveit::planning_interface::MoveGroup::Plan plan) { double secs = 0; for(vector<trajectory_msgs::JointTrajectoryPoint>::iterator pt = plan.trajectory_.joint_trajectory.points.begin(); pt != plan.trajectory_.joint_trajectory.points.end(); pt++) { secs = (*pt).time_from_start.toSec() / 2; stringstream pointStream; pointStream << secs + addTime; for(vector<double>::iterator dt = (*pt).positions.begin(); dt != (*pt).positions.end(); dt++) { pointStream << "," << *dt; } planOutput << pointStream.str() << "\n"; } addTime += secs; } <commit_msg>changes to curves including replacing the system call with a method which calls for moveit to return the robot to the clear position.<commit_after>/* * File: curves.cpp * Author: Isaac Yochelson * * Created on August 22, 2013, 10:30 AM */ #include <moveit/move_group_interface/move_group.h> #include <moveit_msgs/RobotTrajectory.h> #include <trajectory_msgs/JointTrajectory.h> #include <trajectory_msgs/MultiDOFJointTrajectory.h> #include <geometry_msgs/Pose.h> #include <baxter_core_msgs/EndpointState.h> #include <cstdlib> //standard library for C/C++ #include <iostream> #include <fstream> #include <boost/tokenizer.hpp> using namespace std; string filename = "trj_curve_left_15.txt"; string output = "trj_curve_left_15.trj"; ofstream planOutput; double addTime = 0; geometry_msgs::Pose target; map<string, double> clearState; move_group_interface::MoveGroup* bothArmsGroup; moveit::planning_interface::MoveGroup::Plan planToPose(string joint, move_group_interface::MoveGroup& group, geometry_msgs::Pose* pose); void openPlan(string filename, moveit::planning_interface::MoveGroup::Plan plan); void savePlan(moveit::planning_interface::MoveGroup::Plan plan); void closePlan(); void fillMap(map<string, vector<double> > &goal, string filename); void generateAndSavePlan(move_group_interface::MoveGroup* group, string joint); void fillClearState(); void clear(); int main(int argc, char** argv) { ros::init(argc, argv, "Test_Node"); // start a ROS spinning thread ros::AsyncSpinner spinner(1); spinner.start(); // Create MoveGroup instances for each arm, set them to PRM*, and create a pointer to be assigned // to the correct arm to be used for each target. move_group_interface::MoveGroup leftGroup("left_arm"); move_group_interface::MoveGroup rightGroup("right_arm"); move_group_interface::MoveGroup bothGroup("both_arms"); leftGroup.setPlannerId("PRMstarkConfigDefault"); leftGroup.setStartStateToCurrentState(); rightGroup.setPlannerId("PRMstarkConfigDefault"); rightGroup.setStartStateToCurrentState(); bothGroup.setPlannerId("PRMstarkConfigDefault"); bothGroup.setStartStateToCurrentState(); bothArmsGroup = &bothGroup; fillClearState(); move_group_interface::MoveGroup* group; target.orientation.x = 0; target.orientation.y = 1; target.orientation.z = 0; target.orientation.w = 0; group = &rightGroup; string joint = "right_wrist"; addTime = 0; stringstream filestream; filestream << "short_" << 3 << ".csv"; filename = filestream.str(); stringstream outstream; outstream << "short_" << 3 << ".trj"; output = outstream.str(); clear(); generateAndSavePlan(group, joint); /* for (int i = 3; i < 9; ++i) { addTime = 0; stringstream filestream; filestream << "trj_curve_right_" << i << ".txt"; filename = filestream.str(); stringstream outstream; outstream << "trj_curve_right_" << i << ".trj"; output = outstream.str(); clear; generateAndSavePlan(group, joint); } for (int i = 3; i < 9; ++i) { addTime = 0; stringstream filestream; filestream << "trj_straight_right_" << i << ".txt"; filename = filestream.str(); stringstream outstream; outstream << "trj_straight_right_" << i << ".trj"; output = outstream.str(); clear; generateAndSavePlan(group, joint); } for (int i = 3; i < 9; ++i) { addTime = 0; stringstream filestream; filestream << "short_" << i << ".csv"; filename = filestream.str(); stringstream outstream; outstream << "short_right_" << i << ".trj"; output = outstream.str(); clear; generateAndSavePlan(group, joint); } group = &leftGroup; joint = "left_wrist"; for (int i = 13; i > 7; --i) { addTime = 0; stringstream filestream; filestream << "trj_curve_left_" << i << ".txt"; filename = filestream.str(); stringstream outstream; outstream << "trj_curve_left_" << i << ".trj"; output = outstream.str(); clear; generateAndSavePlan(group, joint); } for (int i = 13; i > 7; --i) { addTime = 0; stringstream filestream; filestream << "trj_straight_left_" << i << ".txt"; filename = filestream.str(); stringstream outstream; outstream << "trj_straight_left_" << i << ".trj"; output = outstream.str(); clear; generateAndSavePlan(group, joint); } for (int i = 13; i > 7; --i) { addTime = 0; stringstream filestream; filestream << "short_" << i << ".csv"; filename = filestream.str(); stringstream outstream; outstream << "short_" << i << ".trj"; output = outstream.str(); clear; generateAndSavePlan(group, joint); }*/ return 0; } void generateAndSavePlan(move_group_interface::MoveGroup* group, string joint) { moveit::planning_interface::MoveGroup::Plan plan; map<string, vector<double> > targetMap; fillMap(targetMap, filename); vector<double>::iterator xiter = targetMap["x"].begin(); vector<double>::iterator yiter = targetMap["y"].begin(); vector<double>::iterator ziter = targetMap["z"].begin(); vector<double>::iterator qxiter = targetMap["qx"].begin(); vector<double>::iterator qyiter = targetMap["qy"].begin(); vector<double>::iterator qziter = targetMap["qz"].begin(); vector<double>::iterator qwiter = targetMap["qw"].begin(); cout << "iterators set" << endl; for (xiter= targetMap["x"].begin(); xiter != targetMap["x"].end(); ++xiter) { target.position.x = *xiter; target.position.y = *yiter; target.position.z = *ziter; cout << "position set" << endl; target.orientation.x = *qxiter; target.orientation.y = *qyiter; target.orientation.z = *qziter; target.orientation.w = *qwiter; cout << "orientation set" << endl; ++yiter; ++ziter; ++qxiter; ++qyiter; ++qziter; ++qwiter; cout << "planning to: " << target << endl; plan = planToPose(joint, *group, &target); if (xiter == targetMap["x"].begin()) { openPlan(output, plan); } savePlan(plan); } cout << "closing plan" << endl; closePlan(); } moveit::planning_interface::MoveGroup::Plan planToPose(string joint, move_group_interface::MoveGroup& group, geometry_msgs::Pose* pose) { bool gotPlan; moveit::planning_interface::MoveGroup::Plan plan; group.setPoseTarget(*pose, joint); ROS_INFO("requesting plan."); gotPlan = group.plan(plan); if (gotPlan) { ROS_INFO("plan received."); // cout << plan.trajectory_ << endl; group.execute(plan); ROS_INFO("plan execution completed."); } return plan; } void fillMap(map<string, vector<double> > &goals, string filename) { cout << "filling map: " << filename << endl; ifstream goalInput; goalInput.open(filename.c_str()); double value; string keyLine = "x,y,z,qx,qy,qz,qw"; string valueLine; cout << keyLine << endl; typedef boost::tokenizer<boost::char_separator<char> > tokenizer; boost::char_separator<char> commaDelimited(", "); tokenizer keys(keyLine, commaDelimited); int count = 0; while (getline(goalInput, valueLine)) { ++count; tokenizer values(valueLine, commaDelimited); tokenizer::iterator value_iter = values.begin(); for (tokenizer::iterator key_iter = keys.begin(); key_iter != keys.end() && value_iter != values.end(); ++key_iter) { value = atof((*value_iter).c_str()); goals[*key_iter].push_back(value); ++value_iter; } } goalInput.close(); cout << "fillMap finished: " << count << " lines" << endl; } void openPlan(string filename, moveit::planning_interface::MoveGroup::Plan plan) { planOutput.open(filename.c_str()); planOutput << "time"; for(vector<string>::iterator it = plan.trajectory_.joint_trajectory.joint_names.begin(); it != plan.trajectory_.joint_trajectory.joint_names.end(); it++) { planOutput << "," << *it; } planOutput << "\n"; } void closePlan() { planOutput.close(); } void savePlan(moveit::planning_interface::MoveGroup::Plan plan) { double secs = 0; for(vector<trajectory_msgs::JointTrajectoryPoint>::iterator pt = plan.trajectory_.joint_trajectory.points.begin(); pt != plan.trajectory_.joint_trajectory.points.end(); pt++) { secs = (*pt).time_from_start.toSec() / 2; stringstream pointStream; pointStream << secs + addTime; for(vector<double>::iterator dt = (*pt).positions.begin(); dt != (*pt).positions.end(); dt++) { pointStream << "," << *dt; } planOutput << pointStream.str() << "\n"; } addTime += secs; } void fillClearState() { clearState["left_s0"]=0.8574952594; clearState["left_s1"]=-1.106383642; clearState["left_e0"]=-0.0720970969482; clearState["left_e1"]=1.260548711; clearState["left_w0"]=-0.0720970969482; clearState["left_w1"]=1.1830826813; clearState["left_w2"]=-0.00498543755493; clearState["right_s0"]=-0.708699123193; clearState["right_s1"]=-0.980980712732; clearState["right_e0"]=-0.282635959845; clearState["right_e1"]=1.13859723851; clearState["right_w0"]=0.141509727521; clearState["right_w1"]=1.31922347607; clearState["right_w2"]=-0.00498543755493; } void clear() { bothArmsGroup->setJointValueTarget(clearState); bothArmsGroup->move(); } <|endoftext|>
<commit_before>#include "priorityfs.h" #include <exception> #include <boost/filesystem.hpp> #include <fstream> #include <string> namespace fs = boost::filesystem; class PriorityFS::Impl { public: Impl(const std::string& buffer_directory, const std::string& buffer_parent); std::string GetFilePath(const std::string& file); bool GetInput(const std::string& file, std::ifstream& stream); bool GetOutput(const std::string& file, std::ofstream& stream); bool Delete(const std::string& file); private: fs::path buffer_path_; }; PriorityFS::Impl::Impl(const std::string& buffer_directory, const std::string& buffer_parent) { auto parent_path = buffer_parent.empty() ? fs::temp_directory_path() : fs::path{buffer_parent}; if (buffer_directory.empty()) { throw PriorityFSException{"Cannot initialize PriorityFS with an empty buffer path"}; } buffer_path_ = parent_path / fs::path{buffer_directory}; if (fs::equivalent(buffer_path_, parent_path) || fs::equivalent(buffer_path_, parent_path / fs::path{".."})) { throw PriorityFSException{"PriorityFS must be initialized within a valid parent directory"}; } fs::create_directory(buffer_path_); } std::string PriorityFS::Impl::GetFilePath(const std::string& file) { return (buffer_path_ / fs::path{file}).string(); } bool PriorityFS::Impl::GetInput(const std::string& file, std::ifstream& stream) { auto file_path = buffer_path_ / fs::path{file}; if (!fs::is_directory(file_path) && std::string{".."} != file_path.filename().string() && fs::exists(file_path)) { stream.open(file_path.native()); return true; } return false; } bool PriorityFS::Impl::GetOutput(const std::string& file, std::ofstream& stream) { auto file_path = buffer_path_ / fs::path{file}; if (!fs::is_directory(file_path) && std::string{".."} != file_path.filename().string() && !fs::exists(file_path)) { stream.open(file_path.native()); return true; } return false; } bool PriorityFS::Impl::Delete(const std::string& file) { auto file_path = buffer_path_ / fs::path{file}; if (!fs::is_directory(file_path) && std::string{".."} != file_path.filename().string() && fs::exists(file_path)) { return fs::remove(buffer_path_ / fs::path{file}); } return false; } // Bridge PriorityFS::PriorityFS(const std::string& buffer_directory, const std::string& buffer_parent) : pimpl_{ new Impl{buffer_directory, buffer_parent} } {} PriorityFS::~PriorityFS() {} std::string PriorityFS::GetFilePath(const std::string& file) { return pimpl_->GetFilePath(file); } bool PriorityFS::GetInput(const std::string& file, std::ifstream& stream) { return pimpl_->GetInput(file, stream); } bool PriorityFS::GetOutput(const std::string& file, std::ofstream& stream) { return pimpl_->GetOutput(file, stream); } bool PriorityFS::Delete(const std::string& file) { return pimpl_->Delete(file); } <commit_msg>Fixing binary mode (important for windows/non-unix)<commit_after>#include "priorityfs.h" #include <exception> #include <boost/filesystem.hpp> #include <fstream> #include <string> namespace fs = boost::filesystem; class PriorityFS::Impl { public: Impl(const std::string& buffer_directory, const std::string& buffer_parent); std::string GetFilePath(const std::string& file); bool GetInput(const std::string& file, std::ifstream& stream); bool GetOutput(const std::string& file, std::ofstream& stream); bool Delete(const std::string& file); private: fs::path buffer_path_; }; PriorityFS::Impl::Impl(const std::string& buffer_directory, const std::string& buffer_parent) { auto parent_path = buffer_parent.empty() ? fs::temp_directory_path() : fs::path{buffer_parent}; if (buffer_directory.empty()) { throw PriorityFSException{"Cannot initialize PriorityFS with an empty buffer path"}; } buffer_path_ = parent_path / fs::path{buffer_directory}; if (fs::equivalent(buffer_path_, parent_path) || fs::equivalent(buffer_path_, parent_path / fs::path{".."})) { throw PriorityFSException{"PriorityFS must be initialized within a valid parent directory"}; } fs::create_directory(buffer_path_); } std::string PriorityFS::Impl::GetFilePath(const std::string& file) { return (buffer_path_ / fs::path{file}).string(); } bool PriorityFS::Impl::GetInput(const std::string& file, std::ifstream& stream) { auto file_path = buffer_path_ / fs::path{file}; if (!fs::is_directory(file_path) && std::string{".."} != file_path.filename().string() && fs::exists(file_path)) { stream.open(file_path.native(), std::ios::in | std::ios::binary); return true; } return false; } bool PriorityFS::Impl::GetOutput(const std::string& file, std::ofstream& stream) { auto file_path = buffer_path_ / fs::path{file}; if (!fs::is_directory(file_path) && std::string{".."} != file_path.filename().string() && !fs::exists(file_path)) { stream.open(file_path.native(), std::ios::out | std::ios::binary); return true; } return false; } bool PriorityFS::Impl::Delete(const std::string& file) { auto file_path = buffer_path_ / fs::path{file}; if (!fs::is_directory(file_path) && std::string{".."} != file_path.filename().string() && fs::exists(file_path)) { return fs::remove(buffer_path_ / fs::path{file}); } return false; } // Bridge PriorityFS::PriorityFS(const std::string& buffer_directory, const std::string& buffer_parent) : pimpl_{ new Impl{buffer_directory, buffer_parent} } {} PriorityFS::~PriorityFS() {} std::string PriorityFS::GetFilePath(const std::string& file) { return pimpl_->GetFilePath(file); } bool PriorityFS::GetInput(const std::string& file, std::ifstream& stream) { return pimpl_->GetInput(file, stream); } bool PriorityFS::GetOutput(const std::string& file, std::ofstream& stream) { return pimpl_->GetOutput(file, stream); } bool PriorityFS::Delete(const std::string& file) { return pimpl_->Delete(file); } <|endoftext|>
<commit_before>#include "proto/spec.pb.h" #include <fstream> #include <iostream> void GetUserInput(std::string prompt, std::string& res) { std::cout << prompt << ": "; getline(std::cin, res); } void OutputToInterface(std::string content, bool isError = false) { if (isError) { std::cerr << content << std::endl; } else { std::cout << content << std::endl; } } int ValidateFile(std::string file_path){ std::fstream input(file_path, std::ios::in | std::ios::binary); if (input) { std::string cont; GetUserInput("File already exists. Overwrite? (y/n)", cont); if (cont != "y") { OutputToInterface("Terminating."); return -1; } } return 0; } int WriteToFile(std::string file_path, io::cloudevents::v1::CloudEvent* event){ std::fstream output(file_path, std::ios::out | std::ios::trunc | std::ios::binary); if (!event -> SerializeToOstream(&output)) { OutputToInterface("Could not write to file given.", true); return -1; } return 0; } int CreateEvent(io::cloudevents::v1::CloudEvent* event){ // TODO (Michelle): Abstract this out to a Buider with validation. GetUserInput("Enter id", *event -> mutable_id()); GetUserInput("Enter source", *event -> mutable_source()); GetUserInput("Enter spec_version", *event -> mutable_spec_version()); GetUserInput("Enter type", *event -> mutable_type()); std::string has_data; GetUserInput("Would you like to enter data (y/n)", has_data); if (has_data=="y") { std::string data_type; // TODO (Michelle): Support Any data GetUserInput("Enter data type (bytes/ string)", data_type); const static std::unordered_map<std::string,int> data_type_to_case{ {"bytes",1}, {"string",2}, {"other", 3} }; if (data_type_to_case.find(data_type ) == data_type_to_case.end()) { OutputToInterface("Data type not recognized", true); return -1; } switch(data_type_to_case.at(data_type)){ case 1: GetUserInput("Enter data", *event -> mutable_binary_data()); break; case 2: GetUserInput("Enter data", *event -> mutable_text_data()); break; case 3: OutputToInterface("Other data not yet supported", true); break; default: { OutputToInterface("Data type not handled", true); return -1; } } } return 0; } int main(int argc, char* argv[]) { GOOGLE_PROTOBUF_VERIFY_VERSION; int program_status = 0; // ensure that a write file is specified if (argc != 2) { OutputToInterface("Incorrect Usage. Please specify a write file.", true); return -1; } io::cloudevents::v1::CloudEvent event; program_status = ValidateFile(argv[1]); if (program_status != 0) { return program_status; } // create an event // TODO (Michelle): handle optional and extension attrs program_status = CreateEvent(&event); if (program_status != 0) { return program_status; } // write to file program_status = WriteToFile(argv[1], &event); if (program_status != 0) { return program_status; } google::protobuf::ShutdownProtobufLibrary(); return 0; } <commit_msg>ref github issues in todos<commit_after>#include "proto/spec.pb.h" #include <fstream> #include <iostream> void GetUserInput(std::string prompt, std::string& res) { std::cout << prompt << ": "; getline(std::cin, res); } void OutputToInterface(std::string content, bool isError = false) { if (isError) { std::cerr << content << std::endl; } else { std::cout << content << std::endl; } } int ValidateFile(std::string file_path){ std::fstream input(file_path, std::ios::in | std::ios::binary); if (input) { std::string cont; GetUserInput("File already exists. Overwrite? (y/n)", cont); if (cont != "y") { OutputToInterface("Terminating."); return -1; } } return 0; } int WriteToFile(std::string file_path, io::cloudevents::v1::CloudEvent* event){ std::fstream output(file_path, std::ios::out | std::ios::trunc | std::ios::binary); if (!event -> SerializeToOstream(&output)) { OutputToInterface("Could not write to file given.", true); return -1; } return 0; } int CreateEvent(io::cloudevents::v1::CloudEvent* event){ // TODO (#7): Abstract this out to a Buider with validation. GetUserInput("Enter id", *event -> mutable_id()); GetUserInput("Enter source", *event -> mutable_source()); GetUserInput("Enter spec_version", *event -> mutable_spec_version()); GetUserInput("Enter type", *event -> mutable_type()); std::string has_data; GetUserInput("Would you like to enter data (y/n)", has_data); if (has_data=="y") { std::string data_type; // TODO (#6): Support Any data GetUserInput("Enter data type (bytes/ string)", data_type); const static std::unordered_map<std::string,int> data_type_to_case{ {"bytes",1}, {"string",2}, {"other", 3} }; if (data_type_to_case.find(data_type ) == data_type_to_case.end()) { OutputToInterface("Data type not recognized", true); return -1; } switch(data_type_to_case.at(data_type)){ case 1: GetUserInput("Enter data", *event -> mutable_binary_data()); break; case 2: GetUserInput("Enter data", *event -> mutable_text_data()); break; case 3: OutputToInterface("Other data not yet supported", true); break; default: { OutputToInterface("Data type not handled", true); return -1; } } } return 0; } int main(int argc, char* argv[]) { GOOGLE_PROTOBUF_VERIFY_VERSION; int program_status = 0; // ensure that a write file is specified if (argc != 2) { OutputToInterface("Incorrect Usage. Please specify a write file.", true); return -1; } io::cloudevents::v1::CloudEvent event; program_status = ValidateFile(argv[1]); if (program_status != 0) { return program_status; } // create an event // TODO (#8): handle optional and extension attrs program_status = CreateEvent(&event); if (program_status != 0) { return program_status; } // write to file program_status = WriteToFile(argv[1], &event); if (program_status != 0) { return program_status; } google::protobuf::ShutdownProtobufLibrary(); return 0; } <|endoftext|>
<commit_before>#ifndef SIMHASH_CYCLIC_H #define SIMHASH_CYCLIC_H #include <vector> namespace Simhash { /* Keep a cyclic hash */ template<typename Int> class Cyclic { public: /* An easy typedef */ typedef Int hash_type; /* Useful elsewhere */ static const size_t bits = sizeof(hash_type) * 8; Cyclic(size_t l=4): length(l), current(0), counter(0), tokens() { /* Initialize all of these to 0 */ tokens.resize(length); for (size_t i = 0; i < l; ++i) { tokens[i] = 0; } } Cyclic(const Cyclic<hash_type>& o): length(o.length), current(o.current), counter(o.counter), tokens(o.tokens) {} const Cyclic<hash_type>& operator=(const Cyclic<hash_type>& o) { length = o.length; current = o.current; counter = o.counter; tokens = o.tokens; return *this; } /* Push a new hash onto the stack and get the return value */ hash_type push(hash_type val) { /* Increment the counter. That's the index of the value we have to * pop off, and the index that we'll replace */ current = rotate(current) ^ rotate(tokens[counter], length) ^ val; tokens[counter] = val; counter = (counter + 1) % length; return current; } /* Rotation shift by 1 */ static inline hash_type rotate(hash_type v) { return (v << 1) | (v >> (bits - 1)); } static inline hash_type rotate(hash_type v, size_t count) { count = count % bits; return (v << count) | (v >> (bits - count)); } private: size_t length; // How many pieces of data to store hash_type current; // Our current value size_t counter; // Where we are in our tokens array std::vector<hash_type> tokens; // Array holding our tokens }; } #endif <commit_msg>Fixed undefined usage of right-shift (shifting by 64).<commit_after>#ifndef SIMHASH_CYCLIC_H #define SIMHASH_CYCLIC_H #include <vector> namespace Simhash { /* Keep a cyclic hash */ template<typename Int> class Cyclic { public: /* An easy typedef */ typedef Int hash_type; /* Useful elsewhere */ static const size_t bits = sizeof(hash_type) * 8; Cyclic(size_t l=4): length(l), current(0), counter(0), tokens() { /* Initialize all of these to 0 */ tokens.resize(length); for (size_t i = 0; i < l; ++i) { tokens[i] = 0; } } Cyclic(const Cyclic<hash_type>& o): length(o.length), current(o.current), counter(o.counter), tokens(o.tokens) {} const Cyclic<hash_type>& operator=(const Cyclic<hash_type>& o) { length = o.length; current = o.current; counter = o.counter; tokens = o.tokens; return *this; } /* Push a new hash onto the stack and get the return value */ hash_type push(hash_type val) { /* Increment the counter. That's the index of the value we have to * pop off, and the index that we'll replace */ current = rotate(current) ^ rotate(tokens[counter], length) ^ val; tokens[counter] = val; counter = (counter + 1) % length; return current; } /* Rotation shift by 1 */ static inline hash_type rotate(hash_type v) { return (v << 1) | (v >> (bits - 1)); } static inline hash_type rotate(hash_type v, size_t count) { count = count % bits; return (v << count) | (v >> ((bits - count) % bits)); } private: size_t length; // How many pieces of data to store hash_type current; // Our current value size_t counter; // Where we are in our tokens array std::vector<hash_type> tokens; // Array holding our tokens }; } #endif <|endoftext|>
<commit_before>/* * ProbeStatsFlagTest.cpp * */ #include <columns/PV_Init.hpp> #include <columns/buildandrun.hpp> #include <cmath> int checkValue( float observed, float expected, float tolerance, int lineno, char const *valueDescription); int main(int argc, char *argv[]) { PV::PV_Init pv_initObj(&argc, &argv, false /*do not allow unrecognized arguments*/); int status = buildandrun(&pv_initObj); if (status != PV_SUCCESS) { return EXIT_FAILURE; } if (pv_initObj.getCommunicator()->commRank() == 0) { char const *probeFile = "output/OutputStats.txt"; char const *checkFile = "input/correctOutputStats.txt"; FILE *probefp = std::fopen(probeFile, "r"); FatalIf(!probefp, "Unable to open probe output \"%s\": %s\n", probeFile, strerror(errno)); FILE *checkfp = std::fopen(checkFile, "r"); FatalIf(!checkfp, "Unable to open checkfile \"%s\": %s\n", checkFile, strerror(errno)); int linenumber = 0; float mintolerance = 2e-7f; float maxtolerance = 2e-7f; float meantolerance = 2e-7f; while (true) { float probet, checkt, probemin, checkmin, probemax, checkmax, probemean, checkmean; linenumber++; int probenumread = fscanf( probefp, "t=%f, min=%f, max=%f, mean=%f\n", &probet, &probemin, &probemax, &probemean); int checknumread = fscanf( checkfp, "t=%f, min=%f, max=%f, mean=%f\n", &checkt, &checkmin, &checkmax, &checkmean); if (probenumread != checknumread) { ErrorLog().printf( "Line %d of \"%s\" does not match \"%s\".\n", linenumber, probeFile, checkFile); break; } if (probenumread == EOF) { break; } if (probenumread != 4) { ErrorLog().printf( "Line %d of \"%s\" does not have the expected format.\n", linenumber, probeFile); status = PV_FAILURE; break; } if (checkValue(probet, checkt, 0.0f, linenumber, "time") != PV_SUCCESS) { status = PV_FAILURE; } if (checkValue(probemin, checkmin, mintolerance, linenumber, "min") != PV_SUCCESS) { status = PV_FAILURE; } if (checkValue(probemax, checkmax, maxtolerance, linenumber, "max") != PV_SUCCESS) { status = PV_FAILURE; } if (checkValue(probemean, checkmean, meantolerance, linenumber, "mean") != PV_SUCCESS) { status = PV_FAILURE; } } } return status == PV_SUCCESS ? EXIT_SUCCESS : EXIT_FAILURE; } int checkValue( float observed, float expected, float tolerance, int lineno, char const *valueDescription) { int status = PV_SUCCESS; if (expected) { float discrepancy = std::fabs(observed - expected); float relError = discrepancy / relError; if (relError > tolerance) { ErrorLog().printf( "Line %d %s value %f does not match expected value %f (discrepancy %g).\n", lineno, valueDescription, (double)observed, (double)expected, (double)discrepancy); status = PV_FAILURE; } } else { if (observed) { ErrorLog().printf( "Line %d %s value %g does not match expected value of zero.\n", lineno, valueDescription, (double)observed); status = PV_FAILURE; } } return status; } <commit_msg>Hotfix: ProbeStatsFlagTest bugfix<commit_after>/* * ProbeStatsFlagTest.cpp * */ #include <columns/PV_Init.hpp> #include <columns/buildandrun.hpp> #include <cmath> int checkValue( float observed, float expected, float tolerance, int lineno, char const *valueDescription); int main(int argc, char *argv[]) { PV::PV_Init pv_initObj(&argc, &argv, false /*do not allow unrecognized arguments*/); int status = buildandrun(&pv_initObj); if (status != PV_SUCCESS) { return EXIT_FAILURE; } if (pv_initObj.getCommunicator()->commRank() == 0) { char const *probeFile = "output/OutputStats.txt"; char const *checkFile = "input/correctOutputStats.txt"; FILE *probefp = std::fopen(probeFile, "r"); FatalIf(!probefp, "Unable to open probe output \"%s\": %s\n", probeFile, strerror(errno)); FILE *checkfp = std::fopen(checkFile, "r"); FatalIf(!checkfp, "Unable to open checkfile \"%s\": %s\n", checkFile, strerror(errno)); int linenumber = 0; float mintolerance = 2e-7f; float maxtolerance = 2e-7f; float meantolerance = 2e-7f; while (true) { float probet, checkt, probemin, checkmin, probemax, checkmax, probemean, checkmean; linenumber++; int probenumread = fscanf( probefp, "t=%f, min=%f, max=%f, mean=%f\n", &probet, &probemin, &probemax, &probemean); int checknumread = fscanf( checkfp, "t=%f, min=%f, max=%f, mean=%f\n", &checkt, &checkmin, &checkmax, &checkmean); if (probenumread != checknumread) { ErrorLog().printf( "Line %d of \"%s\" does not match \"%s\".\n", linenumber, probeFile, checkFile); break; } if (probenumread == EOF) { break; } if (probenumread != 4) { ErrorLog().printf( "Line %d of \"%s\" does not have the expected format.\n", linenumber, probeFile); status = PV_FAILURE; break; } if (checkValue(probet, checkt, 0.0f, linenumber, "time") != PV_SUCCESS) { status = PV_FAILURE; } if (checkValue(probemin, checkmin, mintolerance, linenumber, "min") != PV_SUCCESS) { status = PV_FAILURE; } if (checkValue(probemax, checkmax, maxtolerance, linenumber, "max") != PV_SUCCESS) { status = PV_FAILURE; } if (checkValue(probemean, checkmean, meantolerance, linenumber, "mean") != PV_SUCCESS) { status = PV_FAILURE; } } } return status == PV_SUCCESS ? EXIT_SUCCESS : EXIT_FAILURE; } int checkValue( float observed, float expected, float tolerance, int lineno, char const *valueDescription) { int status = PV_SUCCESS; if (expected) { float discrepancy = std::fabs(observed - expected); float relError = discrepancy / expected; if (relError > tolerance) { ErrorLog().printf( "Line %d %s value %f does not match expected value %f (discrepancy %g).\n", lineno, valueDescription, (double)observed, (double)expected, (double)discrepancy); status = PV_FAILURE; } } else { if (observed) { ErrorLog().printf( "Line %d %s value %g does not match expected value of zero.\n", lineno, valueDescription, (double)observed); status = PV_FAILURE; } } return status; } <|endoftext|>
<commit_before>/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "KAssert.h" #include "Memory.h" #include "Natives.h" #include "KString.h" #include "Porting.h" #include "Types.h" #include "utf8.h" extern "C" { // io/Console.kt void Kotlin_io_Console_print(KString message) { RuntimeAssert(message->type_info() == theStringTypeInfo, "Must use a string"); // TODO: system stdout must be aware about UTF-8. const KChar* utf16 = CharArrayAddressOfElementAt(message, 0); KStdString utf8; // Replace incorrect sequences with a default codepoint (see utf8::with_replacement::default_replacement) utf8::with_replacement::utf16to8(utf16, utf16 + message->count_, back_inserter(utf8)); konan::consoleWriteUtf8(utf8.c_str(), utf8.size()); } void Kotlin_io_Console_println(KString message) { Kotlin_io_Console_print(message); #ifndef KONAN_ANDROID // On Android single print produces logcat entry, so no need in linefeed. Kotlin_io_Console_println0(); #endif } void Kotlin_io_Console_println0() { konan::consoleWriteUtf8("\n", 1); } OBJ_GETTER0(Kotlin_io_Console_readLine) { char data[4096]; if (konan::consoleReadUtf8(data, sizeof(data)) < 0) { RETURN_OBJ(nullptr); } RETURN_RESULT_OF(CreateStringFromCString, data); } } // extern "C" <commit_msg>Fix KT-22752 (#1958)<commit_after>/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "KAssert.h" #include "Memory.h" #include "Natives.h" #include "KString.h" #include "Porting.h" #include "Types.h" #include "Exceptions.h" #include "utf8.h" extern "C" { // io/Console.kt void Kotlin_io_Console_print(KString message) { if (message->type_info() != theStringTypeInfo) { ThrowClassCastException(message->obj(), theStringTypeInfo); } // TODO: system stdout must be aware about UTF-8. const KChar* utf16 = CharArrayAddressOfElementAt(message, 0); KStdString utf8; // Replace incorrect sequences with a default codepoint (see utf8::with_replacement::default_replacement) utf8::with_replacement::utf16to8(utf16, utf16 + message->count_, back_inserter(utf8)); konan::consoleWriteUtf8(utf8.c_str(), utf8.size()); } void Kotlin_io_Console_println(KString message) { Kotlin_io_Console_print(message); #ifndef KONAN_ANDROID // On Android single print produces logcat entry, so no need in linefeed. Kotlin_io_Console_println0(); #endif } void Kotlin_io_Console_println0() { konan::consoleWriteUtf8("\n", 1); } OBJ_GETTER0(Kotlin_io_Console_readLine) { char data[4096]; if (konan::consoleReadUtf8(data, sizeof(data)) < 0) { RETURN_OBJ(nullptr); } RETURN_RESULT_OF(CreateStringFromCString, data); } } // extern "C" <|endoftext|>
<commit_before>#ifndef __CAM_SHIFT_PROCESSOR_HPP__ #define __CAM_SHIFT_PROCESSOR_HPP__ #include <vector> #include "VideoProcessor.hpp" class CamShiftProcessor : public VideoProcessor { public: CamShiftProcessor(VideoCapture &Frames, string WindowName) : VideoProcessor(Frames, WindowName), smin(30), vmin(10), vmax(256), hsize(16), histimg( Mat::zeros(200, 320, CV_8UC3) ), tracking(false), phranges(hranges) { hranges[0] = 0; hranges[1] = 180; } void SetThresholds(int VMin, int VMax, int SMin) { vmin = VMin; vmax = VMax; smin = SMin; } protected: int smin; int vmin; int vmax; int hsize; Mat hsv; Mat hue; Mat mask; Mat hist; Mat histimg; Mat backproj; bool tracking; Rect trackWindow; RotatedRect trackBox; float hranges[2]; const float *phranges; virtual Rect search_window(Mat Image, const RotatedRect &TrackBox, const Rect &TrackWindow) { return TrackWindow; } virtual void track_results(Mat Image, const RotatedRect &TrackBox) { ellipse(Image, TrackBox, Scalar(0,0,255), 3, CV_AA); } virtual void process_frame(Mat image) { int ch[] = {0, 0}; cvtColor(image, hsv, CV_BGR2HSV); inRange( hsv, Scalar(0, smin, min(vmin,vmax)), Scalar(180, 256, max(vmin, vmax)), mask ); hue.create(hsv.size(), hsv.depth()); mixChannels(&hsv, 1, &hue, 1, ch, 1); if (tracking) { calcBackProject(&hue, 1, 0, hist, backproj, &phranges); backproj &= mask; trackWindow = search_window(image, trackBox, trackWindow); trackBox = CamShift(backproj, trackWindow, TermCriteria(CV_TERMCRIT_EPS | CV_TERMCRIT_ITER, 10, 1)); if (trackWindow.area() <= 1) { int cols = backproj.cols, rows = backproj.rows, r = (MIN(cols, rows) + 5)/6; trackWindow = Rect(trackWindow.x - r, trackWindow.y - r, trackWindow.x + r, trackWindow.y + r) & Rect(0, 0, cols, rows); } // todo - fixme if (false) cvtColor(backproj, image, CV_GRAY2BGR); track_results(image, trackBox); } } virtual void region_selected(const Rect &Region) { Mat roi(hue, Region), maskroi(mask, Region); int binW; calcHist(&roi, 1, 0, maskroi, hist, 1, &hsize, &phranges); normalize(hist, hist, 0, 255, CV_MINMAX); trackWindow = Region; histimg = Scalar::all(0); binW = histimg.cols / hsize; Mat buf(1, hsize, CV_8UC3); for (int i = 0; i < hsize; ++i) { buf.at<Vec3b>(i) = Vec3b(saturate_cast<uchar>(i*180./hsize), 255, 255); } cvtColor(buf, buf, CV_HSV2BGR); for (int i = 0; i < hsize; ++i) { int val = saturate_cast<int>(hist.at<float>(i)*histimg.rows/255); rectangle(histimg, Point(i*binW,histimg.rows), Point((i+1)*binW,histimg.rows - val), Scalar(buf.at<Vec3b>(i)), -1, 8); } tracking = true; } }; #endif <commit_msg>Remove unused header<commit_after>#ifndef __CAM_SHIFT_PROCESSOR_HPP__ #define __CAM_SHIFT_PROCESSOR_HPP__ #include "VideoProcessor.hpp" class CamShiftProcessor : public VideoProcessor { public: CamShiftProcessor(VideoCapture &Frames, string WindowName) : VideoProcessor(Frames, WindowName), smin(30), vmin(10), vmax(256), hsize(16), histimg( Mat::zeros(200, 320, CV_8UC3) ), tracking(false), phranges(hranges) { hranges[0] = 0; hranges[1] = 180; } void SetThresholds(int VMin, int VMax, int SMin) { vmin = VMin; vmax = VMax; smin = SMin; } protected: int smin; int vmin; int vmax; int hsize; Mat hsv; Mat hue; Mat mask; Mat hist; Mat histimg; Mat backproj; bool tracking; Rect trackWindow; RotatedRect trackBox; float hranges[2]; const float *phranges; virtual Rect search_window(Mat Image, const RotatedRect &TrackBox, const Rect &TrackWindow) { return TrackWindow; } virtual void track_results(Mat Image, const RotatedRect &TrackBox) { ellipse(Image, TrackBox, Scalar(0,0,255), 3, CV_AA); } virtual void process_frame(Mat image) { int ch[] = {0, 0}; cvtColor(image, hsv, CV_BGR2HSV); inRange( hsv, Scalar(0, smin, min(vmin,vmax)), Scalar(180, 256, max(vmin, vmax)), mask ); hue.create(hsv.size(), hsv.depth()); mixChannels(&hsv, 1, &hue, 1, ch, 1); if (tracking) { calcBackProject(&hue, 1, 0, hist, backproj, &phranges); backproj &= mask; trackWindow = search_window(image, trackBox, trackWindow); trackBox = CamShift(backproj, trackWindow, TermCriteria(CV_TERMCRIT_EPS | CV_TERMCRIT_ITER, 10, 1)); if (trackWindow.area() <= 1) { int cols = backproj.cols, rows = backproj.rows, r = (MIN(cols, rows) + 5)/6; trackWindow = Rect(trackWindow.x - r, trackWindow.y - r, trackWindow.x + r, trackWindow.y + r) & Rect(0, 0, cols, rows); } // todo - fixme if (false) cvtColor(backproj, image, CV_GRAY2BGR); track_results(image, trackBox); } } virtual void region_selected(const Rect &Region) { Mat roi(hue, Region), maskroi(mask, Region); int binW; calcHist(&roi, 1, 0, maskroi, hist, 1, &hsize, &phranges); normalize(hist, hist, 0, 255, CV_MINMAX); trackWindow = Region; histimg = Scalar::all(0); binW = histimg.cols / hsize; Mat buf(1, hsize, CV_8UC3); for (int i = 0; i < hsize; ++i) { buf.at<Vec3b>(i) = Vec3b(saturate_cast<uchar>(i*180./hsize), 255, 255); } cvtColor(buf, buf, CV_HSV2BGR); for (int i = 0; i < hsize; ++i) { int val = saturate_cast<int>(hist.at<float>(i)*histimg.rows/255); rectangle(histimg, Point(i*binW,histimg.rows), Point((i+1)*binW,histimg.rows - val), Scalar(buf.at<Vec3b>(i)), -1, 8); } tracking = true; } }; #endif <|endoftext|>
<commit_before>/* * W.J. van der Laan 2011-2012 */ #include <QApplication> #include "bitcoingui.h" #include "clientmodel.h" #include "walletmodel.h" #include "optionsmodel.h" #include "guiutil.h" #include "guiconstants.h" #include "init.h" #include "util.h" #include "ui_interface.h" #include "paymentserver.h" #include <QMessageBox> #include <QTextCodec> #include <QLocale> #include <QTimer> #include <QTranslator> #include <QSplashScreen> #include <QLibraryInfo> #if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED) #define _BITCOIN_QT_PLUGINS_INCLUDED #define __INSURE__ #include <QtPlugin> Q_IMPORT_PLUGIN(qcncodecs) Q_IMPORT_PLUGIN(qjpcodecs) Q_IMPORT_PLUGIN(qtwcodecs) Q_IMPORT_PLUGIN(qkrcodecs) Q_IMPORT_PLUGIN(qtaccessiblewidgets) #endif // Need a global reference for the notifications to find the GUI static BitcoinGUI *guiref; static QSplashScreen *splashref; static void ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style) { // Message from network thread if(guiref) { bool modal = (style & CClientUIInterface::MODAL); // in case of modal message, use blocking connection to wait for user to click OK QMetaObject::invokeMethod(guiref, "error", modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(caption)), Q_ARG(QString, QString::fromStdString(message)), Q_ARG(bool, modal)); } else { printf("%s: %s\n", caption.c_str(), message.c_str()); fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str()); } } static bool ThreadSafeAskFee(int64_t nFeeRequired, const std::string& strCaption) { if(!guiref) return false; if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon) return true; bool payFee = false; QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(), Q_ARG(qint64, nFeeRequired), Q_ARG(bool*, &payFee)); return payFee; } static void InitMessage(const std::string &message) { if(splashref) { splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(232,186,63)); QApplication::instance()->processEvents(); } } /* Translate string to current locale using Qt. */ static std::string Translate(const char* psz) { return QCoreApplication::translate("bitcoin-core", psz).toStdString(); } /* Handle runaway exceptions. Shows a message box with the problem and quits the program. */ static void handleRunawayException(std::exception *e) { PrintExceptionContinue(e, "Runaway exception"); QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. BlackCoin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning)); exit(1); } /* qDebug() message handler --> debug.log */ #if QT_VERSION < 0x050000 void DebugMessageHandler(QtMsgType type, const char * msg) { OutputDebugStringF("%s\n", msg); } #else void DebugMessageHandler(QtMsgType type, const QMessageLogContext& context, const QString &msg) { OutputDebugStringF("%s\n", qPrintable(msg)); } #endif #ifndef BITCOIN_QT_TEST int main(int argc, char *argv[]) { fHaveGUI = true; // Command-line options take precedence: ParseParameters(argc, argv); #if QT_VERSION < 0x050000 // Internal string conversion is all UTF-8 QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); QTextCodec::setCodecForCStrings(QTextCodec::codecForTr()); #endif Q_INIT_RESOURCE(bitcoin); QApplication app(argc, argv); // Do this early as we don't want to bother initializing if we are just calling IPC // ... but do it after creating app, so QCoreApplication::arguments is initialized: if (PaymentServer::ipcSendCommandLine()) exit(0); PaymentServer* paymentServer = new PaymentServer(&app); // Install global event filter that makes sure that long tooltips can be word-wrapped app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app)); // Command-line options take precedence: ParseParameters(argc, argv); // ... then bitcoin.conf: if (!boost::filesystem::is_directory(GetDataDir(false))) { // This message can not be translated, as translation is not initialized yet // (which not yet possible because lang=XX can be overridden in bitcoin.conf in the data directory) QMessageBox::critical(0, "BlackCoin", QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"]))); return 1; } ReadConfigFile(mapArgs, mapMultiArgs); // Application identification (must be set before OptionsModel is initialized, // as it is used to locate QSettings) app.setOrganizationName("BlackCoin"); //XXX app.setOrganizationDomain(""); if(GetBoolArg("-testnet")) // Separate UI settings for testnet app.setApplicationName("BlackCoin-Qt-testnet"); else app.setApplicationName("BlackCoin-Qt"); // ... then GUI settings: OptionsModel optionsModel; // Get desired locale (e.g. "de_DE") from command line or use system locale QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString())); QString lang = lang_territory; // Convert to "de" only by truncating "_DE" lang.truncate(lang_territory.lastIndexOf('_')); QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator; // Load language files for configured locale: // - First load the translator for the base language, without territory // - Then load the more specific locale translator // Load e.g. qt_de.qm if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) app.installTranslator(&qtTranslatorBase); // Load e.g. qt_de_DE.qm if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) app.installTranslator(&qtTranslator); // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc) if (translatorBase.load(lang, ":/translations/")) app.installTranslator(&translatorBase); // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc) if (translator.load(lang_territory, ":/translations/")) app.installTranslator(&translator); // Subscribe to global signals from core uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox); uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee); uiInterface.InitMessage.connect(InitMessage); uiInterface.Translate.connect(Translate); // Show help message immediately after parsing command-line options (for "-lang") and setting locale, // but before showing splash screen. if (mapArgs.count("-?") || mapArgs.count("--help")) { GUIUtil::HelpMessageBox help; help.showOrPrint(); return 1; } // Install qDebug() message handler to route to debug.log: #if QT_VERSION < 0x050000 qInstallMsgHandler(DebugMessageHandler); #else qInstallMessageHandler(DebugMessageHandler); #endif QSplashScreen splash(QPixmap(":/images/splash"), 0); if (GetBoolArg("-splash", true) && !GetBoolArg("-min")) { splash.show(); splashref = &splash; } app.processEvents(); app.setQuitOnLastWindowClosed(false); try { if (fUseBlackTheme) GUIUtil::SetBlackThemeQSS(app); // Regenerate startup link, to fix links to old versions if (GUIUtil::GetStartOnSystemStartup()) GUIUtil::SetStartOnSystemStartup(true); boost::thread_group threadGroup; BitcoinGUI window; guiref = &window; QTimer* pollShutdownTimer = new QTimer(guiref); QObject::connect(pollShutdownTimer, SIGNAL(timeout()), guiref, SLOT(detectShutdown())); pollShutdownTimer->start(200); if(AppInit2(threadGroup)) { { // Put this in a block, so that the Model objects are cleaned up before // calling Shutdown(). if (splashref) splash.finish(&window); ClientModel clientModel(&optionsModel); WalletModel walletModel(pwalletMain, &optionsModel); window.setClientModel(&clientModel); window.setWalletModel(&walletModel); // If -min option passed, start window minimized. if(GetBoolArg("-min")) { window.showMinimized(); } else { window.show(); } // Now that initialization/startup is done, process any command-line // bitcoin: URIs QObject::connect(paymentServer, SIGNAL(receivedURI(QString)), &window, SLOT(handleURI(QString))); QTimer::singleShot(100, paymentServer, SLOT(uiReady())); app.exec(); window.hide(); window.setClientModel(0); window.setWalletModel(0); guiref = 0; } // Shutdown the core and its threads, but don't exit Bitcoin-Qt here threadGroup.interrupt_all(); threadGroup.join_all(); Shutdown(); } else { return 1; } } catch (std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(NULL); } return 0; } #endif // BITCOIN_QT_TEST <commit_msg>Bitcoin-Qt: allow to differentiate Qt log entries from core<commit_after>/* * W.J. van der Laan 2011-2012 */ #include <QApplication> #include "bitcoingui.h" #include "clientmodel.h" #include "walletmodel.h" #include "optionsmodel.h" #include "guiutil.h" #include "guiconstants.h" #include "init.h" #include "util.h" #include "ui_interface.h" #include "paymentserver.h" #include <QMessageBox> #include <QTextCodec> #include <QLocale> #include <QTimer> #include <QTranslator> #include <QSplashScreen> #include <QLibraryInfo> #if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED) #define _BITCOIN_QT_PLUGINS_INCLUDED #define __INSURE__ #include <QtPlugin> Q_IMPORT_PLUGIN(qcncodecs) Q_IMPORT_PLUGIN(qjpcodecs) Q_IMPORT_PLUGIN(qtwcodecs) Q_IMPORT_PLUGIN(qkrcodecs) Q_IMPORT_PLUGIN(qtaccessiblewidgets) #endif // Need a global reference for the notifications to find the GUI static BitcoinGUI *guiref; static QSplashScreen *splashref; static void ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style) { // Message from network thread if(guiref) { bool modal = (style & CClientUIInterface::MODAL); // in case of modal message, use blocking connection to wait for user to click OK QMetaObject::invokeMethod(guiref, "error", modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(caption)), Q_ARG(QString, QString::fromStdString(message)), Q_ARG(bool, modal)); } else { printf("%s: %s\n", caption.c_str(), message.c_str()); fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str()); } } static bool ThreadSafeAskFee(int64_t nFeeRequired, const std::string& strCaption) { if(!guiref) return false; if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon) return true; bool payFee = false; QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(), Q_ARG(qint64, nFeeRequired), Q_ARG(bool*, &payFee)); return payFee; } static void InitMessage(const std::string &message) { if(splashref) { splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(232,186,63)); QApplication::instance()->processEvents(); } } /* Translate string to current locale using Qt. */ static std::string Translate(const char* psz) { return QCoreApplication::translate("bitcoin-core", psz).toStdString(); } /* Handle runaway exceptions. Shows a message box with the problem and quits the program. */ static void handleRunawayException(std::exception *e) { PrintExceptionContinue(e, "Runaway exception"); QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. BlackCoin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning)); exit(1); } /* qDebug() message handler --> debug.log */ #if QT_VERSION < 0x050000 void DebugMessageHandler(QtMsgType type, const char * msg) { OutputDebugStringF("Bitcoin-Qt: %s\n", msg); } #else void DebugMessageHandler(QtMsgType type, const QMessageLogContext& context, const QString &msg) { OutputDebugStringF("Bitcoin-Qt: %s\n", qPrintable(msg)); } #endif #ifndef BITCOIN_QT_TEST int main(int argc, char *argv[]) { fHaveGUI = true; // Command-line options take precedence: ParseParameters(argc, argv); #if QT_VERSION < 0x050000 // Internal string conversion is all UTF-8 QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); QTextCodec::setCodecForCStrings(QTextCodec::codecForTr()); #endif Q_INIT_RESOURCE(bitcoin); QApplication app(argc, argv); // Do this early as we don't want to bother initializing if we are just calling IPC // ... but do it after creating app, so QCoreApplication::arguments is initialized: if (PaymentServer::ipcSendCommandLine()) exit(0); PaymentServer* paymentServer = new PaymentServer(&app); // Install global event filter that makes sure that long tooltips can be word-wrapped app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app)); // Install qDebug() message handler to route to debug.log #if QT_VERSION < 0x050000 qInstallMsgHandler(DebugMessageHandler); #else qInstallMessageHandler(DebugMessageHandler); #endif // Command-line options take precedence: ParseParameters(argc, argv); // ... then bitcoin.conf: if (!boost::filesystem::is_directory(GetDataDir(false))) { // This message can not be translated, as translation is not initialized yet // (which not yet possible because lang=XX can be overridden in bitcoin.conf in the data directory) QMessageBox::critical(0, "BlackCoin", QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"]))); return 1; } ReadConfigFile(mapArgs, mapMultiArgs); // Application identification (must be set before OptionsModel is initialized, // as it is used to locate QSettings) app.setOrganizationName("BlackCoin"); //XXX app.setOrganizationDomain(""); if(GetBoolArg("-testnet")) // Separate UI settings for testnet app.setApplicationName("BlackCoin-Qt-testnet"); else app.setApplicationName("BlackCoin-Qt"); // ... then GUI settings: OptionsModel optionsModel; // Get desired locale (e.g. "de_DE") from command line or use system locale QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString())); QString lang = lang_territory; // Convert to "de" only by truncating "_DE" lang.truncate(lang_territory.lastIndexOf('_')); QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator; // Load language files for configured locale: // - First load the translator for the base language, without territory // - Then load the more specific locale translator // Load e.g. qt_de.qm if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) app.installTranslator(&qtTranslatorBase); // Load e.g. qt_de_DE.qm if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) app.installTranslator(&qtTranslator); // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc) if (translatorBase.load(lang, ":/translations/")) app.installTranslator(&translatorBase); // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc) if (translator.load(lang_territory, ":/translations/")) app.installTranslator(&translator); // Subscribe to global signals from core uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox); uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee); uiInterface.InitMessage.connect(InitMessage); uiInterface.Translate.connect(Translate); // Show help message immediately after parsing command-line options (for "-lang") and setting locale, // but before showing splash screen. if (mapArgs.count("-?") || mapArgs.count("--help")) { GUIUtil::HelpMessageBox help; help.showOrPrint(); return 1; } QSplashScreen splash(QPixmap(":/images/splash"), 0); if (GetBoolArg("-splash", true) && !GetBoolArg("-min")) { splash.show(); splashref = &splash; } app.processEvents(); app.setQuitOnLastWindowClosed(false); try { if (fUseBlackTheme) GUIUtil::SetBlackThemeQSS(app); // Regenerate startup link, to fix links to old versions if (GUIUtil::GetStartOnSystemStartup()) GUIUtil::SetStartOnSystemStartup(true); boost::thread_group threadGroup; BitcoinGUI window; guiref = &window; QTimer* pollShutdownTimer = new QTimer(guiref); QObject::connect(pollShutdownTimer, SIGNAL(timeout()), guiref, SLOT(detectShutdown())); pollShutdownTimer->start(200); if(AppInit2(threadGroup)) { { // Put this in a block, so that the Model objects are cleaned up before // calling Shutdown(). if (splashref) splash.finish(&window); ClientModel clientModel(&optionsModel); WalletModel walletModel(pwalletMain, &optionsModel); window.setClientModel(&clientModel); window.setWalletModel(&walletModel); // If -min option passed, start window minimized. if(GetBoolArg("-min")) { window.showMinimized(); } else { window.show(); } // Now that initialization/startup is done, process any command-line // bitcoin: URIs QObject::connect(paymentServer, SIGNAL(receivedURI(QString)), &window, SLOT(handleURI(QString))); QTimer::singleShot(100, paymentServer, SLOT(uiReady())); app.exec(); window.hide(); window.setClientModel(0); window.setWalletModel(0); guiref = 0; } // Shutdown the core and its threads, but don't exit Bitcoin-Qt here threadGroup.interrupt_all(); threadGroup.join_all(); Shutdown(); } else { return 1; } } catch (std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(NULL); } return 0; } #endif // BITCOIN_QT_TEST <|endoftext|>
<commit_before>#include "LoadingScene.h" #include "HelloWorldScene.h" #include "SimpleAudioEngine.h" #include "../../current-sdk/Classes/GreedyGameAgent.h" USING_NS_CC; using namespace greedygame; void moveToNextScene() { LoadingScene::getInstance()->label->setString("Tap to start game!"); auto _touchListener = EventListenerTouchOneByOne::create(); _touchListener->onTouchBegan = [](cocos2d::Touch* touch, cocos2d::Event* event) { auto scene = HelloWorld::createScene(); auto director = Director::getInstance(); director->replaceScene(scene); return true; }; LoadingScene::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(_touchListener, LoadingScene::getInstance()); } class AgentListener : public IAgentListener { public: void onAvailable() { /** * TODO: getActivePath can be added to searchpath to renderer all NativeUnits in single hook **/ std::string path = GreedyGameAgent::getCampaignPath(); std::vector<std::string> searchPaths = FileUtils::getInstance ()->getSearchPaths (); searchPaths.insert(searchPaths.begin(),path); FileUtils::getInstance ()->setSearchPaths(searchPaths); moveToNextScene(); } void onUnavailable(){ /** * TODO: New campaign has been loaded, move to next scene **/ moveToNextScene(); } void onProgress(int progress){ /** * TODO: progress will show value from o to 100, * which can be used to render loading bar. **/ } void onPermissionsUnavailable(std::vector<std::string> permissions){ /** * TODO: Prompt user to give required permission **/ for (int i=0; i < permissions.size(); i++) { std::string p = permissions[i]; CCLOG("permission unavailable = %s", p.c_str()); } } }; LoadingScene* LoadingScene::_instance = NULL; LoadingScene::LoadingScene(){ CCLOG("LoadingScene Constructor"); LoadingScene::_instance = this; } LoadingScene* LoadingScene::getInstance(){ return LoadingScene::_instance; } Scene* LoadingScene::createScene() { // 'scene' is an autorelease object auto scene = Scene::create(); // 'layer' is an autorelease object auto layer = LoadingScene::create(); // add layer as a child to scene scene->addChild(layer); // return the scene return scene; } // on "init" you need to initialize your instance bool LoadingScene::init() { ////////////////////////////// // 1. super init first if ( !LayerColor::initWithColor(Color4B(255,255,255,255)) ) { return false; } GreedyGameAgent::init(new AgentListener()); auto visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); ///////////////////////////// // 2. add your codes below... // add a label shows "Hello World" // create and initialize a label this->label = Label::createWithTTF("Loading...", "fonts/Marker Felt.ttf", 24); this->label->setColor(Color3B(0,0,0)); // position the label on the center of the screen this->label->setPosition(Vec2(origin.x + visibleSize.width/2, origin.y + visibleSize.height/2 - label->getContentSize().height)); // add the label as a child to this layer this->addChild(this->label, 1); // add "Loading" splash screen" auto sprite = Sprite::create("loading.jpg"); // position the sprite on the center of the screen sprite->setPosition(Vec2(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y)); // add the sprite as a child to this layer this->addChild(sprite, 0); return true; } <commit_msg>updated game<commit_after>#include "LoadingScene.h" #include "HelloWorldScene.h" #include "SimpleAudioEngine.h" #include "../../current-sdk/Classes/GreedyGameAgent.h" USING_NS_CC; using namespace greedygame; void moveToNextScene() { LoadingScene::getInstance()->label->setString("Tap to start game!"); auto _touchListener = EventListenerTouchOneByOne::create(); _touchListener->onTouchBegan = [](cocos2d::Touch* touch, cocos2d::Event* event) { auto scene = HelloWorld::createScene(); auto director = Director::getInstance(); director->replaceScene(scene); return true; }; LoadingScene::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(_touchListener, LoadingScene::getInstance()); } class AgentListener : public IAgentListener { public: void onAvailable() { /** * TODO: New campaign is available and ready to use for the next scene. **/ moveToNextScene(); } void onUnavailable(){ /** * TODO: New campaign has been loaded, move to next scene **/ moveToNextScene(); } void onProgress(int progress){ /** * TODO: progress will show value from o to 100, * which can be used to render loading bar. **/ } void onPermissionsUnavailable(std::vector<std::string> permissions){ /** * TODO: Prompt user to give required permission **/ for (int i=0; i < permissions.size(); i++) { std::string p = permissions[i]; CCLOG("permission unavailable = %s", p.c_str()); } } }; LoadingScene* LoadingScene::_instance = NULL; LoadingScene::LoadingScene(){ CCLOG("LoadingScene Constructor"); LoadingScene::_instance = this; } LoadingScene* LoadingScene::getInstance(){ return LoadingScene::_instance; } Scene* LoadingScene::createScene() { // 'scene' is an autorelease object auto scene = Scene::create(); // 'layer' is an autorelease object auto layer = LoadingScene::create(); // add layer as a child to scene scene->addChild(layer); // return the scene return scene; } // on "init" you need to initialize your instance bool LoadingScene::init() { ////////////////////////////// // 1. super init first if ( !LayerColor::initWithColor(Color4B(255,255,255,255)) ) { return false; } GreedyGameAgent::init(new AgentListener()); auto visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); ///////////////////////////// // 2. add your codes below... // add a label shows "Hello World" // create and initialize a label this->label = Label::createWithTTF("Loading...", "fonts/Marker Felt.ttf", 24); this->label->setColor(Color3B(0,0,0)); // position the label on the center of the screen this->label->setPosition(Vec2(origin.x + visibleSize.width/2, origin.y + visibleSize.height/2 - label->getContentSize().height)); // add the label as a child to this layer this->addChild(this->label, 1); // add "Loading" splash screen" auto sprite = Sprite::create("loading.jpg"); // position the sprite on the center of the screen sprite->setPosition(Vec2(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y)); // add the sprite as a child to this layer this->addChild(sprite, 0); return true; } <|endoftext|>
<commit_before>#include "guiutil.h" #include "bitcoinaddressvalidator.h" #include "walletmodel.h" #include "bitcoinunits.h" #include "util.h" #include "init.h" #include <QString> #include <QDateTime> #include <QDoubleValidator> #include <QFont> #include <QLineEdit> #include <QUrl> #include <QTextDocument> // For Qt::escape #include <QAbstractItemView> #include <QApplication> #include <QClipboard> #include <QFileDialog> #include <QDesktopServices> #include <QThread> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #ifdef WIN32 #ifdef _WIN32_WINNT #undef _WIN32_WINNT #endif #define _WIN32_WINNT 0x0501 #ifdef _WIN32_IE #undef _WIN32_IE #endif #define _WIN32_IE 0x0501 #define WIN32_LEAN_AND_MEAN 1 #ifndef NOMINMAX #define NOMINMAX #endif #include "shlwapi.h" #include "shlobj.h" #include "shellapi.h" #endif namespace GUIUtil { QString dateTimeStr(const QDateTime &date) { return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm"); } QString dateTimeStr(qint64 nTime) { return dateTimeStr(QDateTime::fromTime_t((qint32)nTime)); } QFont bitcoinAddressFont() { QFont font("Monospace"); #if QT_VERSION >= 0x040800 font.setStyleHint(QFont::Monospace); #else font.setStyleHint(QFont::TypeWriter); #endif return font; } void setupAddressWidget(QLineEdit *widget, QWidget *parent) { widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength); widget->setValidator(new BitcoinAddressValidator(parent)); widget->setFont(bitcoinAddressFont()); } void setupAmountWidget(QLineEdit *widget, QWidget *parent) { QDoubleValidator *amountValidator = new QDoubleValidator(parent); amountValidator->setDecimals(8); amountValidator->setBottom(0.0); widget->setValidator(amountValidator); widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter); } bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out) { // NovaCoin: check prefix if(uri.scheme() != QString("blackcoin")) return false; SendCoinsRecipient rv; rv.address = uri.path(); rv.amount = 0; QList<QPair<QString, QString> > items = uri.queryItems(); for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++) { bool fShouldReturnFalse = false; if (i->first.startsWith("req-")) { i->first.remove(0, 4); fShouldReturnFalse = true; } if (i->first == "label") { rv.label = i->second; fShouldReturnFalse = false; } else if (i->first == "amount") { if(!i->second.isEmpty()) { if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount)) { return false; } } fShouldReturnFalse = false; } if (fShouldReturnFalse) return false; } if(out) { *out = rv; } return true; } bool parseBitcoinURI(QString uri, SendCoinsRecipient *out) { // Convert blackcoin:// to blackcoin: // // Cannot handle this later, because bitcoin:// will cause Qt to see the part after // as host, // which will lower-case it (and thus invalidate the address). if(uri.startsWith("blackcoin://")) { uri.replace(0, 12, "blackcoin:"); } QUrl uriInstance(uri); return parseBitcoinURI(uriInstance, out); } QString HtmlEscape(const QString& str, bool fMultiLine) { QString escaped = Qt::escape(str); if(fMultiLine) { escaped = escaped.replace("\n", "<br>\n"); } return escaped; } QString HtmlEscape(const std::string& str, bool fMultiLine) { return HtmlEscape(QString::fromStdString(str), fMultiLine); } void copyEntryData(QAbstractItemView *view, int column, int role) { if(!view || !view->selectionModel()) return; QModelIndexList selection = view->selectionModel()->selectedRows(column); if(!selection.isEmpty()) { // Copy first item QApplication::clipboard()->setText(selection.at(0).data(role).toString()); } } QString getSaveFileName(QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedSuffixOut) { QString selectedFilter; QString myDir; if(dir.isEmpty()) // Default to user documents location { myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation); } else { myDir = dir; } QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter); /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */ QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]"); QString selectedSuffix; if(filter_re.exactMatch(selectedFilter)) { selectedSuffix = filter_re.cap(1); } /* Add suffix if needed */ QFileInfo info(result); if(!result.isEmpty()) { if(info.suffix().isEmpty() && !selectedSuffix.isEmpty()) { /* No suffix specified, add selected suffix */ if(!result.endsWith(".")) result.append("."); result.append(selectedSuffix); } } /* Return selected suffix if asked to */ if(selectedSuffixOut) { *selectedSuffixOut = selectedSuffix; } return result; } Qt::ConnectionType blockingGUIThreadConnection() { if(QThread::currentThread() != QCoreApplication::instance()->thread()) { return Qt::BlockingQueuedConnection; } else { return Qt::DirectConnection; } } bool checkPoint(const QPoint &p, const QWidget *w) { QWidget *atW = qApp->widgetAt(w->mapToGlobal(p)); if (!atW) return false; return atW->topLevelWidget() == w; } bool isObscured(QWidget *w) { return !(checkPoint(QPoint(0, 0), w) && checkPoint(QPoint(w->width() - 1, 0), w) && checkPoint(QPoint(0, w->height() - 1), w) && checkPoint(QPoint(w->width() - 1, w->height() - 1), w) && checkPoint(QPoint(w->width() / 2, w->height() / 2), w)); } void openDebugLogfile() { boost::filesystem::path pathDebug = GetDataDir() / "debug.log"; /* Open debug.log with the associated application */ if (boost::filesystem::exists(pathDebug)) QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string()))); } ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) : QObject(parent), size_threshold(size_threshold) { } bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt) { if(evt->type() == QEvent::ToolTipChange) { QWidget *widget = static_cast<QWidget*>(obj); QString tooltip = widget->toolTip(); if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt>") && !Qt::mightBeRichText(tooltip)) { // Prefix <qt/> to make sure Qt detects this as rich text // Escape the current message as HTML and replace \n by <br> tooltip = "<qt>" + HtmlEscape(tooltip, true) + "<qt/>"; widget->setToolTip(tooltip); return true; } } return QObject::eventFilter(obj, evt); } #ifdef WIN32 boost::filesystem::path static StartupShortcutPath() { return GetSpecialFolderPath(CSIDL_STARTUP) / "BlackCoin.lnk"; } bool GetStartOnSystemStartup() { // check for Bitcoin.lnk return boost::filesystem::exists(StartupShortcutPath()); } bool SetStartOnSystemStartup(bool fAutoStart) { // If the shortcut exists already, remove it for updating boost::filesystem::remove(StartupShortcutPath()); if (fAutoStart) { CoInitialize(NULL); // Get a pointer to the IShellLink interface. IShellLink* psl = NULL; HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, reinterpret_cast<void**>(&psl)); if (SUCCEEDED(hres)) { // Get the current executable path TCHAR pszExePath[MAX_PATH]; GetModuleFileName(NULL, pszExePath, sizeof(pszExePath)); TCHAR pszArgs[5] = TEXT("-min"); // Set the path to the shortcut target psl->SetPath(pszExePath); PathRemoveFileSpec(pszExePath); psl->SetWorkingDirectory(pszExePath); psl->SetShowCmd(SW_SHOWMINNOACTIVE); psl->SetArguments(pszArgs); // Query IShellLink for the IPersistFile interface for // saving the shortcut in persistent storage. IPersistFile* ppf = NULL; hres = psl->QueryInterface(IID_IPersistFile, reinterpret_cast<void**>(&ppf)); if (SUCCEEDED(hres)) { WCHAR pwsz[MAX_PATH]; // Ensure that the string is ANSI. MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH); // Save the link by calling IPersistFile::Save. hres = ppf->Save(pwsz, TRUE); ppf->Release(); psl->Release(); CoUninitialize(); return true; } psl->Release(); } CoUninitialize(); return false; } return true; } #elif defined(LINUX) // Follow the Desktop Application Autostart Spec: // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html boost::filesystem::path static GetAutostartDir() { namespace fs = boost::filesystem; char* pszConfigHome = getenv("XDG_CONFIG_HOME"); if (pszConfigHome) return fs::path(pszConfigHome) / "autostart"; char* pszHome = getenv("HOME"); if (pszHome) return fs::path(pszHome) / ".config" / "autostart"; return fs::path(); } boost::filesystem::path static GetAutostartFilePath() { return GetAutostartDir() / "blackcoin.desktop"; } bool GetStartOnSystemStartup() { boost::filesystem::ifstream optionFile(GetAutostartFilePath()); if (!optionFile.good()) return false; // Scan through file for "Hidden=true": std::string line; while (!optionFile.eof()) { getline(optionFile, line); if (line.find("Hidden") != std::string::npos && line.find("true") != std::string::npos) return false; } optionFile.close(); return true; } bool SetStartOnSystemStartup(bool fAutoStart) { if (!fAutoStart) boost::filesystem::remove(GetAutostartFilePath()); else { char pszExePath[MAX_PATH+1]; memset(pszExePath, 0, sizeof(pszExePath)); if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1) return false; boost::filesystem::create_directories(GetAutostartDir()); boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc); if (!optionFile.good()) return false; // Write a bitcoin.desktop file to the autostart directory: optionFile << "[Desktop Entry]\n"; optionFile << "Type=Application\n"; optionFile << "Name=BlackCoin\n"; optionFile << "Exec=" << pszExePath << " -min\n"; optionFile << "Terminal=false\n"; optionFile << "Hidden=false\n"; optionFile.close(); } return true; } #else // TODO: OSX startup stuff; see: // https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html bool GetStartOnSystemStartup() { return false; } bool SetStartOnSystemStartup(bool fAutoStart) { return false; } #endif HelpMessageBox::HelpMessageBox(QWidget *parent) : QMessageBox(parent) { header = tr("BlackCoin-Qt") + " " + tr("version") + " " + QString::fromStdString(FormatFullVersion()) + "\n\n" + tr("Usage:") + "\n" + " blackcoin-qt [" + tr("command-line options") + "] " + "\n"; coreOptions = QString::fromStdString(HelpMessage()); uiOptions = tr("UI options") + ":\n" + " -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" + " -min " + tr("Start minimized") + "\n" + " -splash " + tr("Show splash screen on startup (default: 1)") + "\n"; setWindowTitle(tr("BlackCoin-Qt")); setTextFormat(Qt::PlainText); // setMinimumWidth is ignored for QMessageBox so put in non-breaking spaces to make it wider. setText(header + QString(QChar(0x2003)).repeated(50)); setDetailedText(coreOptions + "\n" + uiOptions); } void HelpMessageBox::printToConsole() { // On other operating systems, the expected action is to print the message to the console. QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions; fprintf(stdout, "%s", strUsage.toStdString().c_str()); } void HelpMessageBox::showOrPrint() { #if defined(WIN32) // On Windows, show a message box, as there is no stderr/stdout in windowed applications exec(); #else // On other operating systems, print help text to console printToConsole(); #endif } } // namespace GUIUtil <commit_msg>[Qt] Fix Start bitcoin on system login<commit_after>#include "guiutil.h" #include "bitcoinaddressvalidator.h" #include "walletmodel.h" #include "bitcoinunits.h" #include "util.h" #include "init.h" #include <QString> #include <QDateTime> #include <QDoubleValidator> #include <QFont> #include <QLineEdit> #include <QUrl> #include <QTextDocument> // For Qt::escape #include <QAbstractItemView> #include <QApplication> #include <QClipboard> #include <QFileDialog> #include <QDesktopServices> #include <QThread> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #ifdef WIN32 #ifdef _WIN32_WINNT #undef _WIN32_WINNT #endif #define _WIN32_WINNT 0x0501 #ifdef _WIN32_IE #undef _WIN32_IE #endif #define _WIN32_IE 0x0501 #define WIN32_LEAN_AND_MEAN 1 #ifndef NOMINMAX #define NOMINMAX #endif #include "shlwapi.h" #include "shlobj.h" #include "shellapi.h" #endif namespace GUIUtil { QString dateTimeStr(const QDateTime &date) { return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm"); } QString dateTimeStr(qint64 nTime) { return dateTimeStr(QDateTime::fromTime_t((qint32)nTime)); } QFont bitcoinAddressFont() { QFont font("Monospace"); #if QT_VERSION >= 0x040800 font.setStyleHint(QFont::Monospace); #else font.setStyleHint(QFont::TypeWriter); #endif return font; } void setupAddressWidget(QLineEdit *widget, QWidget *parent) { widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength); widget->setValidator(new BitcoinAddressValidator(parent)); widget->setFont(bitcoinAddressFont()); } void setupAmountWidget(QLineEdit *widget, QWidget *parent) { QDoubleValidator *amountValidator = new QDoubleValidator(parent); amountValidator->setDecimals(8); amountValidator->setBottom(0.0); widget->setValidator(amountValidator); widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter); } bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out) { // NovaCoin: check prefix if(uri.scheme() != QString("blackcoin")) return false; SendCoinsRecipient rv; rv.address = uri.path(); rv.amount = 0; QList<QPair<QString, QString> > items = uri.queryItems(); for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++) { bool fShouldReturnFalse = false; if (i->first.startsWith("req-")) { i->first.remove(0, 4); fShouldReturnFalse = true; } if (i->first == "label") { rv.label = i->second; fShouldReturnFalse = false; } else if (i->first == "amount") { if(!i->second.isEmpty()) { if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount)) { return false; } } fShouldReturnFalse = false; } if (fShouldReturnFalse) return false; } if(out) { *out = rv; } return true; } bool parseBitcoinURI(QString uri, SendCoinsRecipient *out) { // Convert blackcoin:// to blackcoin: // // Cannot handle this later, because bitcoin:// will cause Qt to see the part after // as host, // which will lower-case it (and thus invalidate the address). if(uri.startsWith("blackcoin://")) { uri.replace(0, 12, "blackcoin:"); } QUrl uriInstance(uri); return parseBitcoinURI(uriInstance, out); } QString HtmlEscape(const QString& str, bool fMultiLine) { QString escaped = Qt::escape(str); if(fMultiLine) { escaped = escaped.replace("\n", "<br>\n"); } return escaped; } QString HtmlEscape(const std::string& str, bool fMultiLine) { return HtmlEscape(QString::fromStdString(str), fMultiLine); } void copyEntryData(QAbstractItemView *view, int column, int role) { if(!view || !view->selectionModel()) return; QModelIndexList selection = view->selectionModel()->selectedRows(column); if(!selection.isEmpty()) { // Copy first item QApplication::clipboard()->setText(selection.at(0).data(role).toString()); } } QString getSaveFileName(QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedSuffixOut) { QString selectedFilter; QString myDir; if(dir.isEmpty()) // Default to user documents location { myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation); } else { myDir = dir; } QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter); /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */ QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]"); QString selectedSuffix; if(filter_re.exactMatch(selectedFilter)) { selectedSuffix = filter_re.cap(1); } /* Add suffix if needed */ QFileInfo info(result); if(!result.isEmpty()) { if(info.suffix().isEmpty() && !selectedSuffix.isEmpty()) { /* No suffix specified, add selected suffix */ if(!result.endsWith(".")) result.append("."); result.append(selectedSuffix); } } /* Return selected suffix if asked to */ if(selectedSuffixOut) { *selectedSuffixOut = selectedSuffix; } return result; } Qt::ConnectionType blockingGUIThreadConnection() { if(QThread::currentThread() != QCoreApplication::instance()->thread()) { return Qt::BlockingQueuedConnection; } else { return Qt::DirectConnection; } } bool checkPoint(const QPoint &p, const QWidget *w) { QWidget *atW = qApp->widgetAt(w->mapToGlobal(p)); if (!atW) return false; return atW->topLevelWidget() == w; } bool isObscured(QWidget *w) { return !(checkPoint(QPoint(0, 0), w) && checkPoint(QPoint(w->width() - 1, 0), w) && checkPoint(QPoint(0, w->height() - 1), w) && checkPoint(QPoint(w->width() - 1, w->height() - 1), w) && checkPoint(QPoint(w->width() / 2, w->height() / 2), w)); } void openDebugLogfile() { boost::filesystem::path pathDebug = GetDataDir() / "debug.log"; /* Open debug.log with the associated application */ if (boost::filesystem::exists(pathDebug)) QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string()))); } ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) : QObject(parent), size_threshold(size_threshold) { } bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt) { if(evt->type() == QEvent::ToolTipChange) { QWidget *widget = static_cast<QWidget*>(obj); QString tooltip = widget->toolTip(); if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt>") && !Qt::mightBeRichText(tooltip)) { // Prefix <qt/> to make sure Qt detects this as rich text // Escape the current message as HTML and replace \n by <br> tooltip = "<qt>" + HtmlEscape(tooltip, true) + "<qt/>"; widget->setToolTip(tooltip); return true; } } return QObject::eventFilter(obj, evt); } #ifdef WIN32 boost::filesystem::path static StartupShortcutPath() { return GetSpecialFolderPath(CSIDL_STARTUP) / "BlackCoin.lnk"; } bool GetStartOnSystemStartup() { // check for Bitcoin.lnk return boost::filesystem::exists(StartupShortcutPath()); } bool SetStartOnSystemStartup(bool fAutoStart) { // If the shortcut exists already, remove it for updating boost::filesystem::remove(StartupShortcutPath()); if (fAutoStart) { CoInitialize(NULL); // Get a pointer to the IShellLink interface. IShellLink* psl = NULL; HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, reinterpret_cast<void**>(&psl)); if (SUCCEEDED(hres)) { // Get the current executable path TCHAR pszExePath[MAX_PATH]; GetModuleFileName(NULL, pszExePath, sizeof(pszExePath)); TCHAR pszArgs[5] = TEXT("-min"); // Set the path to the shortcut target psl->SetPath(pszExePath); PathRemoveFileSpec(pszExePath); psl->SetWorkingDirectory(pszExePath); psl->SetShowCmd(SW_SHOWMINNOACTIVE); psl->SetArguments(pszArgs); // Query IShellLink for the IPersistFile interface for // saving the shortcut in persistent storage. IPersistFile* ppf = NULL; hres = psl->QueryInterface(IID_IPersistFile, reinterpret_cast<void**>(&ppf)); if (SUCCEEDED(hres)) { WCHAR pwsz[MAX_PATH]; // Ensure that the string is ANSI. MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH); // Save the link by calling IPersistFile::Save. hres = ppf->Save(pwsz, TRUE); ppf->Release(); psl->Release(); CoUninitialize(); return true; } psl->Release(); } CoUninitialize(); return false; } return true; } #elif defined(Q_OS_LINUX) // Follow the Desktop Application Autostart Spec: // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html boost::filesystem::path static GetAutostartDir() { namespace fs = boost::filesystem; char* pszConfigHome = getenv("XDG_CONFIG_HOME"); if (pszConfigHome) return fs::path(pszConfigHome) / "autostart"; char* pszHome = getenv("HOME"); if (pszHome) return fs::path(pszHome) / ".config" / "autostart"; return fs::path(); } boost::filesystem::path static GetAutostartFilePath() { return GetAutostartDir() / "blackcoin.desktop"; } bool GetStartOnSystemStartup() { boost::filesystem::ifstream optionFile(GetAutostartFilePath()); if (!optionFile.good()) return false; // Scan through file for "Hidden=true": std::string line; while (!optionFile.eof()) { getline(optionFile, line); if (line.find("Hidden") != std::string::npos && line.find("true") != std::string::npos) return false; } optionFile.close(); return true; } bool SetStartOnSystemStartup(bool fAutoStart) { if (!fAutoStart) boost::filesystem::remove(GetAutostartFilePath()); else { char pszExePath[MAX_PATH+1]; memset(pszExePath, 0, sizeof(pszExePath)); if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1) return false; boost::filesystem::create_directories(GetAutostartDir()); boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc); if (!optionFile.good()) return false; // Write a bitcoin.desktop file to the autostart directory: optionFile << "[Desktop Entry]\n"; optionFile << "Type=Application\n"; optionFile << "Name=BlackCoin\n"; optionFile << "Exec=" << pszExePath << " -min\n"; optionFile << "Terminal=false\n"; optionFile << "Hidden=false\n"; optionFile.close(); } return true; } #else // TODO: OSX startup stuff; see: // https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html bool GetStartOnSystemStartup() { return false; } bool SetStartOnSystemStartup(bool fAutoStart) { return false; } #endif HelpMessageBox::HelpMessageBox(QWidget *parent) : QMessageBox(parent) { header = tr("BlackCoin-Qt") + " " + tr("version") + " " + QString::fromStdString(FormatFullVersion()) + "\n\n" + tr("Usage:") + "\n" + " blackcoin-qt [" + tr("command-line options") + "] " + "\n"; coreOptions = QString::fromStdString(HelpMessage()); uiOptions = tr("UI options") + ":\n" + " -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" + " -min " + tr("Start minimized") + "\n" + " -splash " + tr("Show splash screen on startup (default: 1)") + "\n"; setWindowTitle(tr("BlackCoin-Qt")); setTextFormat(Qt::PlainText); // setMinimumWidth is ignored for QMessageBox so put in non-breaking spaces to make it wider. setText(header + QString(QChar(0x2003)).repeated(50)); setDetailedText(coreOptions + "\n" + uiOptions); } void HelpMessageBox::printToConsole() { // On other operating systems, the expected action is to print the message to the console. QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions; fprintf(stdout, "%s", strUsage.toStdString().c_str()); } void HelpMessageBox::showOrPrint() { #if defined(WIN32) // On Windows, show a message box, as there is no stderr/stdout in windowed applications exec(); #else // On other operating systems, print help text to console printToConsole(); #endif } } // namespace GUIUtil <|endoftext|>
<commit_before>/* * MenuLayer.cpp * * Created on: Aug 28, 2014 * Author: zhangchen */ #include "MainLayer.h" #include "AppMacros.h" #include "BgLayer.h" #include "Counter.h" #include "FinishLayer.h" #include "SimpleAudioEngine.h" using namespace CocosDenshion; #define TAG_LEFT 0 #define TAG_RIGHT 1 #define TAG_SCORE 3 #define TAG_ACTION_RUN 1 #define TAG_ACTION_JUMP 2 #define TAG_ACTION_DROP 3 #define TAG_ACTION_MOVE 4 MainLayer::MainLayer() { // TODO Auto-generated constructor stub disappearing = false; speed = 4.0f; ratio = 5.0f; leftJumping = false; rightJumping = false; } bool MainLayer::init() { /*-- 设置整体层属性 --*/ this->setTouchMode(kCCTouchesOneByOne); this->setTouchEnabled(true); this->scheduleUpdate(); CCSize s = CCDirector::sharedDirector()->getWinSize(); this->ignoreAnchorPointForPosition(true); setAnchorPoint(ccp(0.5f, 0.5f)); this->setContentSize(s); setPosition(ccp(s.width / 2, s.height / 2)); CCSize vsize = CCDirector::sharedDirector()->getVisibleSize(); float width = vsize.width / 2; float height = vsize.height / 2; Counter *counter = Counter::sharedCounter(); counter->clearScore(); if (counter->isSound() && !SimpleAudioEngine::sharedEngine()->isBackgroundMusicPlaying()) { SimpleAudioEngine::sharedEngine()->playBackgroundMusic("bgm.mp3", true); } /*-- door --*/ CCAnimation *doorAnimation = CCAnimationCache::sharedAnimationCache()->animationByName("door"); //左侧 CCSprite *leftDoor = CCSprite::createWithSpriteFrameName("door_1.png"); leftDoor->setPosition(ccp(-200, -50)); leftDoor->setAnchorPoint(ccp(0.5, 0.5)); this->addChild(leftDoor); leftDoor->runAction( CCRepeatForever::create(CCAnimate::create(doorAnimation))); //右侧 CCSprite *rightDoor = CCSprite::createWithSpriteFrameName("door_1.png"); rightDoor->setPosition(ccp(200, -50)); rightDoor->setAnchorPoint(ccp(0.5, 0.5)); this->addChild(rightDoor); rightDoor->runAction( CCRepeatForever::create(CCAnimate::create(doorAnimation))); /*-- 分数 --*/ CCLabelTTF *titletxt = CCLabelTTF::create(counter->getStringByKey("score"), counter->getStringByKey("font"), 46); titletxt->setColor(ccc3(98, 104, 191)); titletxt->setAnchorPoint(ccp(0.5, 0.5)); titletxt->setPosition(ccp(0, height - 130)); this->addChild(titletxt); CCNode *scoreLabel = counter->create_label(); scoreLabel->setPosition(ccp(0, height - 200)); scoreLabel->setAnchorPoint(ccp(0.5, 1)); this->addChild(scoreLabel, 3, TAG_SCORE); /*-- role --*/ return true; } void MainLayer::onEnterTransitionDidFinish() { CCLayer::onEnterTransitionDidFinish(); this->createNewRole(); } MainLayer::~MainLayer() { } CCScene * MainLayer::scene() { CCScene *scene = CCScene::create(); if (scene && scene->init()) { if (scene) { /*-- 背景 --*/ CCLayer *bgLayer = BgLayer::create(); scene->addChild(bgLayer); MainLayer *layer = MainLayer::create(); scene->addChild(layer); } return scene; } else { CC_SAFE_DELETE(scene); return NULL; } } void MainLayer::createNewRole() { CCSize vsize = CCDirector::sharedDirector()->getVisibleSize(); float width = vsize.width / 2; float height = vsize.height / 2; CCSprite *left = CCSprite::createWithSpriteFrameName("ultraman_big_1.png"); CCSprite *right = CCSprite::createWithSpriteFrameName("dragon_big_1.png"); if (CCRANDOM_0_1() < 0.5) { left->setScale(0.5f); } else { right->setScale(0.5f); } left->setPosition(ccp(-width, -height + 230)); left->setAnchorPoint(ccp(0, 0)); this->addChild(left, 3, TAG_LEFT); right->setPosition(ccp(width, -height + 230)); right->setAnchorPoint(ccp(1, 0)); this->addChild(right, 3, TAG_RIGHT); CCAction *leftMoving = CCMoveBy::create(speed, ccp(2 * width, 0)); CCAction *rightMoving = CCMoveBy::create(speed, ccp(-2 * width, 0)); leftMoving->setTag(TAG_ACTION_MOVE); rightMoving->setTag(TAG_ACTION_MOVE); left->runAction(leftMoving); right->runAction(rightMoving); disappearing = false; /*-- 走路动画 --*/ playRunAnimation(); } void MainLayer::reCreateNewRole() { this->removeChildByTag(TAG_LEFT); this->removeChildByTag(TAG_RIGHT); this->createNewRole(); } bool MainLayer::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent) { /*-- 跳动作 --*/ //CCDirector::sharedDirector()->replaceScene(FinishLayer::scene()); CCSize vsize = CCDirector::sharedDirector()->getVisibleSize(); CCPoint location = pTouch->getLocation(); CCNode *node = 0; if (location.x < vsize.width / 2) { if (!leftJumping) { node = this->getChildByTag(TAG_LEFT); leftJumping = true; } } else { if (!rightJumping) { node = this->getChildByTag(TAG_RIGHT); rightJumping = true; } } if (node) { CCActionInterval *jump = CCJumpBy::create(speed / ratio, ccp(0, 0), node->getContentSize().height, 1); node->runAction(jump); CCActionInterval *moving = (CCActionInterval*) node->getActionByTag( TAG_ACTION_MOVE); if (moving) { node->runAction(CCSpeed::create(moving, 1.2f)); } playJumpAnimation(node); } return true; } void MainLayer::update(float delta) { if (!disappearing) { CCNode *left = this->getChildByTag(TAG_LEFT); CCNode *right = this->getChildByTag(TAG_RIGHT); if (left && right) { CCRect leftRect = left->boundingBox(); CCRect rightRect = right->boundingBox(); leftRect.size = leftRect.size * 0.85f; rightRect.size = rightRect.size * 0.85f; if (leftRect.intersectsRect(rightRect)) { disappearing = true; /*爆炸*/ playDropAnimation(); } else if (left->getPosition().x > right->getPosition().x) { disappearing = true; leftJumping = false; rightJumping = false; //计分 Counter *counter = Counter::sharedCounter(); (*counter)++; this->reCreateNewRole(); // left->runAction(CCFadeOut::create(0.8f)); // right->runAction( // CCSequence::createWithTwoActions(CCFadeOut::create(0.8f), // CCCallFunc::create(this, // callfunc_selector( // MainLayer::reCreateNewRole)))); } } } } void MainLayer::playRunAnimation() { CCSprite *left = (CCSprite*) this->getChildByTag(TAG_LEFT); CCSprite *right = (CCSprite*) this->getChildByTag(TAG_RIGHT); /*-- 走路动画 --*/ left->stopActionByTag(TAG_ACTION_JUMP); right->stopActionByTag(TAG_ACTION_JUMP); CCAnimation* ultramanAnimation = CCAnimationCache::sharedAnimationCache()->animationByName( "ultraman"); CCAnimation* dragonAnimation = CCAnimationCache::sharedAnimationCache()->animationByName("dragon"); CCAction* ultraman = CCRepeatForever::create( CCAnimate::create(ultramanAnimation)); CCAction* dragon = CCRepeatForever::create( CCAnimate::create(dragonAnimation)); ultraman->setTag(TAG_ACTION_RUN); dragon->setTag(TAG_ACTION_RUN); left->runAction(ultraman); right->runAction(dragon); } void MainLayer::playJumpAnimation(CCNode *node) { /*-- 跳动画 --*/ Counter::sharedCounter()->playEffect("jump.mp3"); node->stopActionByTag(TAG_ACTION_RUN); CCAction* animation; if (node->getTag() == TAG_LEFT) { CCAnimation* ultramanAnimation = CCAnimationCache::sharedAnimationCache()->animationByName( "ultramanjump"); animation = CCAnimate::create(ultramanAnimation); } else { CCAnimation* dragonAnimation = CCAnimationCache::sharedAnimationCache()->animationByName( "dragonjump"); animation = CCAnimate::create(dragonAnimation); } animation->setTag(TAG_ACTION_JUMP); node->runAction(animation); } void MainLayer::playDropAnimation() { CCSprite *left = (CCSprite*) this->getChildByTag(TAG_LEFT); CCSprite *right = (CCSprite*) this->getChildByTag(TAG_RIGHT); /*-- 走路动画 --*/ left->stopAllActions(); right->stopAllActions(); CCPoint la = left->getAnchorPoint(); CCPoint ra = right->getAnchorPoint(); left->initWithSpriteFrameName("ultraman_big_19.png"); right->initWithSpriteFrameName("dragon_big_19.png"); left->setAnchorPoint(la); right->setAnchorPoint(ra); CCSize vsize = CCDirector::sharedDirector()->getVisibleSize(); float width = vsize.width / 2; float height = vsize.height / 2; left->runAction( CCMoveTo::create(0.6f, ccp(left->getPositionX(), -height - left->getContentSize().height))); right->runAction( CCMoveTo::create(0.6f, ccp(right->getPositionX(), -height - right->getContentSize().height))); CCPoint p = (left->getPosition() + ccp(0, left->getContentSize().height / 2) + right->getPosition() + ccp(0, right->getContentSize().height / 2)) / 2.0f; playExplosionAnimation(p); } void MainLayer::playExplosionAnimation(const CCPoint &p) { Counter::sharedCounter()->playEffect("boom.mp3"); CCSprite *explostion = CCSprite::createWithSpriteFrame( CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName( "boom_1.png")); CCAnimation* explostionAnimation = CCAnimationCache::sharedAnimationCache()->animationByName("boom"); explostion->setPosition(p); this->addChild(explostion); explostion->runAction( CCSequence::createWithTwoActions( CCAnimate::create(explostionAnimation), CCCallFunc::create(this, callfunc_selector(MainLayer::gameover)))); } void MainLayer::gameover() { CCDirector* pDirector = CCDirector::sharedDirector(); CCScene *pScene = FinishLayer::scene(); CCScene *reScene = CCTransitionFadeDown::create(0.5f, pScene); pDirector->replaceScene(reScene); } <commit_msg>adjust jumping<commit_after>/* * MenuLayer.cpp * * Created on: Aug 28, 2014 * Author: zhangchen */ #include "MainLayer.h" #include "AppMacros.h" #include "BgLayer.h" #include "Counter.h" #include "FinishLayer.h" #include "SimpleAudioEngine.h" using namespace CocosDenshion; #define TAG_LEFT 0 #define TAG_RIGHT 1 #define TAG_SCORE 3 #define TAG_ACTION_RUN 1 #define TAG_ACTION_JUMP 2 #define TAG_ACTION_DROP 3 #define TAG_ACTION_MOVE 4 MainLayer::MainLayer() { // TODO Auto-generated constructor stub disappearing = false; speed = 3.0f; ratio = 5.3f; leftJumping = false; rightJumping = false; } bool MainLayer::init() { /*-- 设置整体层属性 --*/ this->setTouchMode(kCCTouchesOneByOne); this->setTouchEnabled(true); this->scheduleUpdate(); CCSize s = CCDirector::sharedDirector()->getWinSize(); this->ignoreAnchorPointForPosition(true); setAnchorPoint(ccp(0.5f, 0.5f)); this->setContentSize(s); setPosition(ccp(s.width / 2, s.height / 2)); CCSize vsize = CCDirector::sharedDirector()->getVisibleSize(); float width = vsize.width / 2; float height = vsize.height / 2; Counter *counter = Counter::sharedCounter(); counter->clearScore(); if (counter->isSound() && !SimpleAudioEngine::sharedEngine()->isBackgroundMusicPlaying()) { SimpleAudioEngine::sharedEngine()->playBackgroundMusic("bgm.mp3", true); } /*-- door --*/ CCAnimation *doorAnimation = CCAnimationCache::sharedAnimationCache()->animationByName("door"); //左侧 CCSprite *leftDoor = CCSprite::createWithSpriteFrameName("door_1.png"); leftDoor->setPosition(ccp(-200, -50)); leftDoor->setAnchorPoint(ccp(0.5, 0.5)); this->addChild(leftDoor); leftDoor->runAction( CCRepeatForever::create(CCAnimate::create(doorAnimation))); //右侧 CCSprite *rightDoor = CCSprite::createWithSpriteFrameName("door_1.png"); rightDoor->setPosition(ccp(200, -50)); rightDoor->setAnchorPoint(ccp(0.5, 0.5)); this->addChild(rightDoor); rightDoor->runAction( CCRepeatForever::create(CCAnimate::create(doorAnimation))); /*-- 分数 --*/ CCLabelTTF *titletxt = CCLabelTTF::create(counter->getStringByKey("score"), counter->getStringByKey("font"), 46); titletxt->setColor(ccc3(98, 104, 191)); titletxt->setAnchorPoint(ccp(0.5, 0.5)); titletxt->setPosition(ccp(0, height - 130)); this->addChild(titletxt); CCNode *scoreLabel = counter->create_label(); scoreLabel->setPosition(ccp(0, height - 200)); scoreLabel->setAnchorPoint(ccp(0.5, 1)); this->addChild(scoreLabel, 3, TAG_SCORE); /*-- role --*/ return true; } void MainLayer::onEnterTransitionDidFinish() { CCLayer::onEnterTransitionDidFinish(); this->createNewRole(); } MainLayer::~MainLayer() { } CCScene * MainLayer::scene() { CCScene *scene = CCScene::create(); if (scene && scene->init()) { if (scene) { /*-- 背景 --*/ CCLayer *bgLayer = BgLayer::create(); scene->addChild(bgLayer); MainLayer *layer = MainLayer::create(); scene->addChild(layer); } return scene; } else { CC_SAFE_DELETE(scene); return NULL; } } void MainLayer::createNewRole() { CCSize vsize = CCDirector::sharedDirector()->getVisibleSize(); float width = vsize.width / 2; float height = vsize.height / 2; CCSprite *left = CCSprite::createWithSpriteFrameName("ultraman_big_1.png"); CCSprite *right = CCSprite::createWithSpriteFrameName("dragon_big_1.png"); if (CCRANDOM_0_1() < 0.5) { left->setScale(0.5f); } else { right->setScale(0.5f); } left->setPosition(ccp(-width, -height + 230)); left->setAnchorPoint(ccp(0, 0)); this->addChild(left, 3, TAG_LEFT); right->setPosition(ccp(width, -height + 230)); right->setAnchorPoint(ccp(1, 0)); this->addChild(right, 3, TAG_RIGHT); CCAction *leftMoving = CCMoveBy::create(speed, ccp(2 * width, 0)); CCAction *rightMoving = CCMoveBy::create(speed, ccp(-2 * width, 0)); leftMoving->setTag(TAG_ACTION_MOVE); rightMoving->setTag(TAG_ACTION_MOVE); left->runAction(leftMoving); right->runAction(rightMoving); disappearing = false; /*-- 走路动画 --*/ playRunAnimation(); } void MainLayer::reCreateNewRole() { this->removeChildByTag(TAG_LEFT); this->removeChildByTag(TAG_RIGHT); this->createNewRole(); } bool MainLayer::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent) { /*-- 跳动作 --*/ //CCDirector::sharedDirector()->replaceScene(FinishLayer::scene()); CCSize vsize = CCDirector::sharedDirector()->getVisibleSize(); CCPoint location = pTouch->getLocation(); CCNode *node = 0; if (location.x < vsize.width / 2) { if (!leftJumping) { node = this->getChildByTag(TAG_LEFT); leftJumping = true; } } else { if (!rightJumping) { node = this->getChildByTag(TAG_RIGHT); rightJumping = true; } } if (node) { CCActionInterval *jump = CCJumpBy::create(speed / ratio, ccp(0, 0), node->getContentSize().height, 1); node->runAction(jump); CCActionInterval *moving = (CCActionInterval*) node->getActionByTag( TAG_ACTION_MOVE); if (moving) { node->runAction(CCSpeed::create(moving, 1.2f)); } playJumpAnimation(node); } return true; } void MainLayer::update(float delta) { if (!disappearing) { CCNode *left = this->getChildByTag(TAG_LEFT); CCNode *right = this->getChildByTag(TAG_RIGHT); if (left && right) { CCRect leftRect = left->boundingBox(); CCRect rightRect = right->boundingBox(); leftRect.size = leftRect.size * 0.85f; rightRect.size = rightRect.size * 0.8f; if (leftRect.intersectsRect(rightRect)) { disappearing = true; /*爆炸*/ playDropAnimation(); } else if (left->getPosition().x > right->getPosition().x) { disappearing = true; leftJumping = false; rightJumping = false; //计分 Counter *counter = Counter::sharedCounter(); (*counter)++; this->reCreateNewRole(); // left->runAction(CCFadeOut::create(0.8f)); // right->runAction( // CCSequence::createWithTwoActions(CCFadeOut::create(0.8f), // CCCallFunc::create(this, // callfunc_selector( // MainLayer::reCreateNewRole)))); } } } } void MainLayer::playRunAnimation() { CCSprite *left = (CCSprite*) this->getChildByTag(TAG_LEFT); CCSprite *right = (CCSprite*) this->getChildByTag(TAG_RIGHT); /*-- 走路动画 --*/ left->stopActionByTag(TAG_ACTION_JUMP); right->stopActionByTag(TAG_ACTION_JUMP); CCAnimation* ultramanAnimation = CCAnimationCache::sharedAnimationCache()->animationByName( "ultraman"); CCAnimation* dragonAnimation = CCAnimationCache::sharedAnimationCache()->animationByName("dragon"); CCAction* ultraman = CCRepeatForever::create( CCAnimate::create(ultramanAnimation)); CCAction* dragon = CCRepeatForever::create( CCAnimate::create(dragonAnimation)); ultraman->setTag(TAG_ACTION_RUN); dragon->setTag(TAG_ACTION_RUN); left->runAction(ultraman); right->runAction(dragon); } void MainLayer::playJumpAnimation(CCNode *node) { /*-- 跳动画 --*/ Counter::sharedCounter()->playEffect("jump.mp3"); node->stopActionByTag(TAG_ACTION_RUN); CCAction* animation; if (node->getTag() == TAG_LEFT) { CCAnimation* ultramanAnimation = CCAnimationCache::sharedAnimationCache()->animationByName( "ultramanjump"); animation = CCAnimate::create(ultramanAnimation); } else { CCAnimation* dragonAnimation = CCAnimationCache::sharedAnimationCache()->animationByName( "dragonjump"); animation = CCAnimate::create(dragonAnimation); } animation->setTag(TAG_ACTION_JUMP); node->runAction(animation); } void MainLayer::playDropAnimation() { CCSprite *left = (CCSprite*) this->getChildByTag(TAG_LEFT); CCSprite *right = (CCSprite*) this->getChildByTag(TAG_RIGHT); /*-- 走路动画 --*/ left->stopAllActions(); right->stopAllActions(); CCPoint la = left->getAnchorPoint(); CCPoint ra = right->getAnchorPoint(); left->initWithSpriteFrameName("ultraman_big_19.png"); right->initWithSpriteFrameName("dragon_big_19.png"); left->setAnchorPoint(la); right->setAnchorPoint(ra); CCSize vsize = CCDirector::sharedDirector()->getVisibleSize(); float width = vsize.width / 2; float height = vsize.height / 2; left->runAction( CCMoveTo::create(0.6f, ccp(left->getPositionX(), -height - left->getContentSize().height))); right->runAction( CCMoveTo::create(0.6f, ccp(right->getPositionX(), -height - right->getContentSize().height))); CCPoint p = (left->getPosition() + ccp(0, left->getContentSize().height / 2) + right->getPosition() + ccp(0, right->getContentSize().height / 2)) / 2.0f; playExplosionAnimation(p); } void MainLayer::playExplosionAnimation(const CCPoint &p) { Counter::sharedCounter()->playEffect("boom.mp3"); CCSprite *explostion = CCSprite::createWithSpriteFrame( CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName( "boom_1.png")); CCAnimation* explostionAnimation = CCAnimationCache::sharedAnimationCache()->animationByName("boom"); explostion->setPosition(p); this->addChild(explostion); explostion->runAction( CCSequence::createWithTwoActions( CCAnimate::create(explostionAnimation), CCCallFunc::create(this, callfunc_selector(MainLayer::gameover)))); } void MainLayer::gameover() { CCDirector* pDirector = CCDirector::sharedDirector(); CCScene *pScene = FinishLayer::scene(); CCScene *reScene = CCTransitionFadeDown::create(0.5f, pScene); pDirector->replaceScene(reScene); } <|endoftext|>
<commit_before>/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2018 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * * without restriction, including without limitation the rights to use, copy, modify, * * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * * permit persons to whom the Software is furnished to do so, subject to the following * * conditions: * * * * The above copyright notice and this permission notice shall be included in all copies * * or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ #include <modules/exoplanets/exoplanetsmodule.h> #include <openspace/documentation/documentation.h> #include <openspace/engine/openspaceengine.h> #include <openspace/util/factorymanager.h> #include <openspace/util/time.h> #include <ghoul/misc/assert.h> #include <modules/exoplanets/tasks/exoplanetscsvtobintask.h> #include <fstream> #include <sstream> #include <algorithm> #include <string> namespace openspace { using namespace exoplanets; struct Exoplanet { float A; double AUPPER; double ALOWER; double UA; float BIGOM; float BIGOMUPPER; float BIGOMLOWER; float UBIGOM; bool BINARY; float BMV; float ECC; float ECCUPPER; float ECCLOWER; float UECC; float I; float IUPPER; float ILOWER; float UI; int NCOMP; float OM; float OMUPPER; float OMLOWER; float UOM; double PER; float PERUPPER; float PERLOWER; float UPER; double R; double RUPPER; double RLOWER; double UR; float RSTAR; float RSTARUPPER; float RSTARLOWER; float URSTAR; //float TEFF; //float TEFFUPPER; //float TEFFLOWER; //float UTEFF; double TT; float TTUPPER; float TTLOWER; float UTT; float POSITIONX; float POSITIONY; float POSITIONZ; }; std::string getStarColor(float bv){ std::string colorString; std::ifstream colormap("C:/Users/Karin/Documents/OpenSpace/modules/exoplanets/colorbv.cmap", std::ios::in); if (!colormap.good()) { std::cout << "Failed to open colormap data file"; } int t = round(((bv + 0.4) / (2.0 + 0.4))*255); std::string color; for (size_t i = 0; i < t+12; i++) { getline(colormap, color); } std::istringstream colorstream(color); std::string r, g, b; getline(colorstream, r, ' '); getline(colorstream, g, ' '); getline(colorstream, b, ' '); colorString = "{" + r + ", " + g + ", " + b + "}"; colormap.close(); return colorString; } ExoplanetsModule::ExoplanetsModule() : OpenSpaceModule(Name) {} int addNode(lua_State* L) { const int StringLocation = -1; const std::string starname = luaL_checkstring(L, StringLocation); std::ifstream data("C:/Users/Karin/Documents/OpenSpace/modules/exoplanets/expl_data.bin", std::ios::in | std::ios::binary); if (!data.good()) { std::cout << "Failed to open exoplanets data file"; } std::ifstream lut("C:/Users/Karin/Documents/OpenSpace/modules/exoplanets/lookup.txt"); if (!lut.good()) { std::cout << "Failed to open exoplanets look-up table file"; } //1. search lut for the starname and return the corresponding location //2. go to that location in the data file //3. read sizeof(exoplanet) bytes into an exoplanet object. std::string planetname; size_t len = 0; Exoplanet p; std::string line; bool found = false; std::vector<Exoplanet> plsy; std::vector<std::string> plna; while (getline(lut, line)) { std::istringstream ss(line); getline(ss, planetname, ','); if (planetname.compare(0, planetname.length()-2, starname) == 0) { std::string location_s; getline(ss, location_s); long location = std::stol(location_s.c_str()); data.seekg(location); data.read((char*)&p, sizeof(struct Exoplanet)); plna.push_back(planetname); plsy.push_back(p); found = true; } } data.close(); lut.close(); if (found && !isnan(p.POSITIONX) && !p.BINARY && !isnan(p.A) && !isnan(p.PER)) { Time epoch; double parsec = 0.308567756E17; std::string scriptParent; const std::string starParent = "{" "Name = '" + starname + "'," "Parent = 'SolarSystemBarycenter'," "Transform = {" "Translation = {" "Type = 'StaticTranslation'," "Position = {" + std::to_string(p.POSITIONX * parsec) + ", " + std::to_string(p.POSITIONY * parsec) + ", " + std::to_string(p.POSITIONZ * parsec) + "}" "}" "}" "}"; scriptParent = "openspace.addSceneGraphNode(" + starParent + ");"; if (!isnan(p.RSTAR)) { std::string color = getStarColor(p.BMV); const std::string starGlobe = "{" "Name = '" + starname + "Globe'," "Parent = '" + starname + "'," "Renderable = {" "Type = 'RenderableGlobe'," "Radii = " + std::to_string(p.RSTAR) + " * 6.957E8," "SegmentsPerPatch = 64," "PerformShading = false," "Layers = {" "ColorLayers = {" "{" "Name = 'Star Color'," "Type = 'SolidColor'," "Color = " + color + "," "BlendMode = 'Normal'," "Enabled = true" "}," "{" "Name = 'Star Texture'," "FilePath = 'C:/Users/Karin/Documents/OpenSpace/modules/exoplanets/sun.jpg',"//'C:/Users/Karin/Documents/OpenSpace/modules/exoplanets/test3.jpg'," // adapt texture according to strar-temperature (TEFF) "BlendMode = 'Color'," "Enabled = true" "}" "}" "}" "}" "}"; const std::string starGlare = "{" "Name = '" + starname + "Glare'," "Parent = '" + starname + "'," "Renderable = {" "Type = 'RenderablePlaneImageLocal'," "Size = " + std::to_string(p.RSTAR) + " *(1.3*10^10.5)," //RSTAR. in meters. 1 solar radii = 6.95700×10e8 m "Billboard = true," "Texture = 'C:/Users/Karin/Documents/OpenSpace/modules/exoplanets/halo.png'," "BlendMode = 'Additive'" "}" "}"; scriptParent += "openspace.addSceneGraphNode(" + starGlare + "); openspace.addSceneGraphNode(" + starGlobe + ");"; } OsEng.scriptEngine().queueScript( scriptParent, openspace::scripting::ScriptEngine::RemoteScripting::Yes ); for (size_t i = 0; i < plsy.size(); i++) { scriptParent = ""; if (isnan(plsy[i].ECC)) { plsy[i].ECC = 0; } if (isnan(plsy[i].I)) { plsy[i].I = 90; } if (isnan(plsy[i].BIGOM)) { plsy[i].BIGOM = 0; } if (isnan(plsy[i].OM)) { plsy[i].OM = 90; } std::string sepoch; if (!isnan(plsy[i].TT)) { epoch.setTime("JD " + std::to_string(plsy[i].TT)); sepoch = epoch.ISO8601(); } else sepoch = "2009-05-19T07:11:34.080"; if (!isnan(plsy[i].R)) { const std::string luaTablePlanet = "{" "Name = '" + plna[i] + "'," "Parent = '" + starname + "'," "Renderable = {" "Type = 'RenderableGlobe'," "Radii = " + std::to_string(plsy[i].R) + " *7.1492E7," //R. in meters. 1 jupiter radii = 7.1492×10e7 m "SegmentsPerPatch = 64," "PerformShading = false," "Layers = {" "ColorLayers = {" "{" "Name = 'Exoplanet Texture'," "FilePath = 'C:/Users/Karin/Documents/OpenSpace/modules/exoplanets/test3.jpg'," "Enabled = true" "}" "}" "}" "}," "Transform = {" "Translation = {" "Type = 'KeplerTranslation'," "Eccentricity = " + std::to_string(plsy[i].ECC) + "," //ECC "SemiMajorAxis = " + std::to_string(plsy[i].A) + " * 149597871," // 149 597 871km = 1 AU. A "Inclination = " + std::to_string(plsy[i].I) + "," //I "AscendingNode = " + std::to_string(plsy[i].BIGOM) + "," //BIGOM "ArgumentOfPeriapsis = " + std::to_string(plsy[i].OM) + "," //OM "MeanAnomaly = 0.0," "Epoch = '" + sepoch + "'," //TT. JD to YYYY MM DD hh:mm:ss "Period = " + std::to_string(plsy[i].PER) + "* 86400" //PER. 86 400sec = 1 day. "}" "}," "}"; scriptParent += "openspace.addSceneGraphNode(" + luaTablePlanet + ");"; } const std::string PlanetTrail = "{" "Name = '" + plna[i] + "Trail'," "Parent = '" + starname + "'," "Renderable = {" "Type = 'RenderableTrailOrbit'," "Period = " + std::to_string(plsy[i].PER) + "," "Resolution = 100," "Translation = {" "Type = 'KeplerTranslation'," "Eccentricity = " + std::to_string(plsy[i].ECC) + "," //ECC "SemiMajorAxis = " + std::to_string(plsy[i].A) + " * 149597871," // 149 597 871km = 1 AU. A "Inclination = " + std::to_string(plsy[i].I) + "," //I "AscendingNode = " + std::to_string(plsy[i].BIGOM) + "," //BIGOM "ArgumentOfPeriapsis = " + std::to_string(plsy[i].OM) + "," //OM "MeanAnomaly = 0.0," "Epoch = '" + sepoch + "'," //TT. JD to YYYY MM DD hh:mm:ss "Period = " + std::to_string(plsy[i].PER) + "* 86400" //PER. 86 400sec = 1 day. "}," "Color = { 1, 0, 0 }" "}," "}"; scriptParent += " openspace.addSceneGraphNode(" + PlanetTrail + ");"; OsEng.scriptEngine().queueScript( scriptParent, openspace::scripting::ScriptEngine::RemoteScripting::Yes ); } } else { printf("No star with that name or not enough data about it."); } return 0; } int removeNode(lua_State* L) { const int StringLocation = -1; const std::string starname = luaL_checkstring(L, StringLocation); /*std::ifstream lut("C:/Users/Karin/Documents/OpenSpace/modules/exoplanets/lookup.txt"); if (!lut.good()) { std::cout << "Failed to open exoplanets look-up table file"; } std::string line; std::string planetname; std::vector<std::string> plna; while (getline(lut, line)) { std::istringstream ss(line); getline(ss, planetname, ','); if (planetname.compare(0, planetname.length() - 2, starname) == 0) { plna.push_back(planetname); } }*/ /*std::string scriptParent; for (size_t i = 0; i < plna.size(); i++) { scriptParent += "openspace.removeSceneGraphNode('" + plna[i] + "Trail'); openspace.removeSceneGraphNode('" + plna[i] + "');"; } scriptParent += " openspace.removeSceneGraphNode('" + starname + "Plane'); openspace.removeSceneGraphNode('" + starname + "');";*/ std::string scriptParent = "openspace.removeSceneGraphNode('" + starname + "');"; OsEng.scriptEngine().queueScript( scriptParent, openspace::scripting::ScriptEngine::RemoteScripting::Yes ); return 0; } scripting::LuaLibrary ExoplanetsModule::luaLibrary() const { scripting::LuaLibrary res; res.name = "exoplanets"; res.functions = { { "addNode", &addNode, {}, "string", "Adds two nodes to the scenegraph, one position node and one node to represenet the star." }, { "removeNode", &removeNode, {}, "string", "Removes the node with the name given in the arguments." } }; return res; } void ExoplanetsModule::internalInitialize(const ghoul::Dictionary&) { auto fTask = FactoryManager::ref().factory<Task>(); ghoul_assert(fTask, "No task factory existed"); fTask->registerClass<ExoplanetsCsvToBinTask>("ExoplanetsCsvToBinTask"); } std::vector<documentation::Documentation> ExoplanetsModule::documentations() const { return { ExoplanetsCsvToBinTask::documentation() }; } } // namespace openspace <commit_msg>Changed Name to Identifier in nodes.<commit_after>/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2018 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * * without restriction, including without limitation the rights to use, copy, modify, * * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * * permit persons to whom the Software is furnished to do so, subject to the following * * conditions: * * * * The above copyright notice and this permission notice shall be included in all copies * * or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ #include <modules/exoplanets/exoplanetsmodule.h> #include <openspace/documentation/documentation.h> #include <openspace/engine/openspaceengine.h> #include <openspace/util/factorymanager.h> #include <openspace/util/time.h> #include <ghoul/misc/assert.h> #include <modules/exoplanets/tasks/exoplanetscsvtobintask.h> #include <fstream> #include <sstream> #include <algorithm> #include <string> namespace openspace { using namespace exoplanets; struct Exoplanet { float A; double AUPPER; double ALOWER; double UA; float BIGOM; float BIGOMUPPER; float BIGOMLOWER; float UBIGOM; bool BINARY; float BMV; float ECC; float ECCUPPER; float ECCLOWER; float UECC; float I; float IUPPER; float ILOWER; float UI; int NCOMP; float OM; float OMUPPER; float OMLOWER; float UOM; double PER; float PERUPPER; float PERLOWER; float UPER; double R; double RUPPER; double RLOWER; double UR; float RSTAR; float RSTARUPPER; float RSTARLOWER; float URSTAR; //float TEFF; //float TEFFUPPER; //float TEFFLOWER; //float UTEFF; double TT; float TTUPPER; float TTLOWER; float UTT; float POSITIONX; float POSITIONY; float POSITIONZ; }; std::string getStarColor(float bv){ std::string colorString; std::ifstream colormap("C:/Users/Karin/Documents/OpenSpace/modules/exoplanets/colorbv.cmap", std::ios::in); if (!colormap.good()) { std::cout << "Failed to open colormap data file"; } int t = round(((bv + 0.4) / (2.0 + 0.4))*255); std::string color; for (size_t i = 0; i < t+12; i++) { getline(colormap, color); } std::istringstream colorstream(color); std::string r, g, b; getline(colorstream, r, ' '); getline(colorstream, g, ' '); getline(colorstream, b, ' '); colorString = "{" + r + ", " + g + ", " + b + "}"; colormap.close(); return colorString; } ExoplanetsModule::ExoplanetsModule() : OpenSpaceModule(Name) {} int addNode(lua_State* L) { const int StringLocation = -1; const std::string starname = luaL_checkstring(L, StringLocation); std::ifstream data("C:/Users/Karin/Documents/OpenSpace/modules/exoplanets/expl_data.bin", std::ios::in | std::ios::binary); if (!data.good()) { std::cout << "Failed to open exoplanets data file"; } std::ifstream lut("C:/Users/Karin/Documents/OpenSpace/modules/exoplanets/lookup.txt"); if (!lut.good()) { std::cout << "Failed to open exoplanets look-up table file"; } //1. search lut for the starname and return the corresponding location //2. go to that location in the data file //3. read sizeof(exoplanet) bytes into an exoplanet object. std::string planetname; size_t len = 0; Exoplanet p; std::string line; bool found = false; std::vector<Exoplanet> plsy; std::vector<std::string> plna; while (getline(lut, line)) { std::istringstream ss(line); getline(ss, planetname, ','); if (planetname.compare(0, planetname.length()-2, starname) == 0) { std::string location_s; getline(ss, location_s); long location = std::stol(location_s.c_str()); data.seekg(location); data.read((char*)&p, sizeof(struct Exoplanet)); plna.push_back(planetname); plsy.push_back(p); found = true; } } data.close(); lut.close(); if (found && !isnan(p.POSITIONX) && !p.BINARY && !isnan(p.A) && !isnan(p.PER)) { Time epoch; double parsec = 0.308567756E17; std::string scriptParent; const std::string starParent = "{" "Identifier = '" + starname + "'," "Parent = 'SolarSystemBarycenter'," "Transform = {" "Translation = {" "Type = 'StaticTranslation'," "Position = {" + std::to_string(p.POSITIONX * parsec) + ", " + std::to_string(p.POSITIONY * parsec) + ", " + std::to_string(p.POSITIONZ * parsec) + "}" "}" "}" "}"; scriptParent = "openspace.addSceneGraphNode(" + starParent + ");"; if (!isnan(p.RSTAR)) { std::string color = getStarColor(p.BMV); const std::string starGlobe = "{" "Identifier = '" + starname + "Globe'," "Parent = '" + starname + "'," "Renderable = {" "Type = 'RenderableGlobe'," "Radii = " + std::to_string(p.RSTAR) + " * 6.957E8," "SegmentsPerPatch = 64," "PerformShading = false," "Layers = {" "ColorLayers = {" "{" "Identifier = 'StarColor'," "Type = 'SolidColor'," "Color = " + color + "," "BlendMode = 'Normal'," "Enabled = true" "}," "{" "Identifier = 'StarTexture'," "FilePath = 'C:/Users/Karin/Documents/OpenSpace/modules/exoplanets/sun.jpg',"//'C:/Users/Karin/Documents/OpenSpace/modules/exoplanets/test3.jpg'," // adapt texture according to strar-temperature (TEFF) "BlendMode = 'Color'," "Enabled = true" "}" "}" "}" "}" "}"; const std::string starGlare = "{" "Identifier = '" + starname + "Glare'," "Parent = '" + starname + "'," "Renderable = {" "Type = 'RenderablePlaneImageLocal'," "Size = " + std::to_string(p.RSTAR) + " *(1.3*10^10.5)," //RSTAR. in meters. 1 solar radii = 6.95700×10e8 m "Billboard = true," "Texture = 'C:/Users/Karin/Documents/OpenSpace/modules/exoplanets/halo.png'," "BlendMode = 'Additive'" "}" "}"; scriptParent += "openspace.addSceneGraphNode(" + starGlare + "); openspace.addSceneGraphNode(" + starGlobe + ");"; } OsEng.scriptEngine().queueScript( scriptParent, openspace::scripting::ScriptEngine::RemoteScripting::Yes ); for (size_t i = 0; i < plsy.size(); i++) { scriptParent = ""; if (isnan(plsy[i].ECC)) { plsy[i].ECC = 0; } if (isnan(plsy[i].I)) { plsy[i].I = 90; } if (isnan(plsy[i].BIGOM)) { plsy[i].BIGOM = 0; } if (isnan(plsy[i].OM)) { plsy[i].OM = 90; } std::string sepoch; if (!isnan(plsy[i].TT)) { epoch.setTime("JD " + std::to_string(plsy[i].TT)); sepoch = epoch.ISO8601(); } else sepoch = "2009-05-19T07:11:34.080"; if (!isnan(plsy[i].R)) { const std::string luaTablePlanet = "{" "Identifier = '" + plna[i] + "'," "Parent = '" + starname + "'," "Renderable = {" "Type = 'RenderableGlobe'," "Radii = " + std::to_string(plsy[i].R) + " *7.1492E7," //R. in meters. 1 jupiter radii = 7.1492×10e7 m "SegmentsPerPatch = 64," "PerformShading = false," "Layers = {" "ColorLayers = {" "{" "Identifier = 'ExoplanetTexture'," "FilePath = 'C:/Users/Karin/Documents/OpenSpace/modules/exoplanets/test3.jpg'," "Enabled = true" "}" "}" "}" "}," "Transform = {" "Translation = {" "Type = 'KeplerTranslation'," "Eccentricity = " + std::to_string(plsy[i].ECC) + "," //ECC "SemiMajorAxis = " + std::to_string(plsy[i].A) + " * 149597871," // 149 597 871km = 1 AU. A "Inclination = " + std::to_string(plsy[i].I) + "," //I "AscendingNode = " + std::to_string(plsy[i].BIGOM) + "," //BIGOM "ArgumentOfPeriapsis = " + std::to_string(plsy[i].OM) + "," //OM "MeanAnomaly = 0.0," "Epoch = '" + sepoch + "'," //TT. JD to YYYY MM DD hh:mm:ss "Period = " + std::to_string(plsy[i].PER) + "* 86400" //PER. 86 400sec = 1 day. "}" "}," "}"; scriptParent += "openspace.addSceneGraphNode(" + luaTablePlanet + ");"; } const std::string PlanetTrail = "{" "Identifier = '" + plna[i] + "Trail'," "Parent = '" + starname + "'," "Renderable = {" "Type = 'RenderableTrailOrbit'," "Period = " + std::to_string(plsy[i].PER) + "," "Resolution = 100," "Translation = {" "Type = 'KeplerTranslation'," "Eccentricity = " + std::to_string(plsy[i].ECC) + "," //ECC "SemiMajorAxis = " + std::to_string(plsy[i].A) + " * 149597871," // 149 597 871km = 1 AU. A "Inclination = " + std::to_string(plsy[i].I) + "," //I "AscendingNode = " + std::to_string(plsy[i].BIGOM) + "," //BIGOM "ArgumentOfPeriapsis = " + std::to_string(plsy[i].OM) + "," //OM "MeanAnomaly = 0.0," "Epoch = '" + sepoch + "'," //TT. JD to YYYY MM DD hh:mm:ss "Period = " + std::to_string(plsy[i].PER) + "* 86400" //PER. 86 400sec = 1 day. "}," "Color = { 1, 0, 0 }" "}," "}"; scriptParent += " openspace.addSceneGraphNode(" + PlanetTrail + ");"; OsEng.scriptEngine().queueScript( scriptParent, openspace::scripting::ScriptEngine::RemoteScripting::Yes ); } } else { printf("No star with that name or not enough data about it."); } return 0; } int removeNode(lua_State* L) { const int StringLocation = -1; const std::string starname = luaL_checkstring(L, StringLocation); /*std::ifstream lut("C:/Users/Karin/Documents/OpenSpace/modules/exoplanets/lookup.txt"); if (!lut.good()) { std::cout << "Failed to open exoplanets look-up table file"; } std::string line; std::string planetname; std::vector<std::string> plna; while (getline(lut, line)) { std::istringstream ss(line); getline(ss, planetname, ','); if (planetname.compare(0, planetname.length() - 2, starname) == 0) { plna.push_back(planetname); } }*/ /*std::string scriptParent; for (size_t i = 0; i < plna.size(); i++) { scriptParent += "openspace.removeSceneGraphNode('" + plna[i] + "Trail'); openspace.removeSceneGraphNode('" + plna[i] + "');"; } scriptParent += " openspace.removeSceneGraphNode('" + starname + "Plane'); openspace.removeSceneGraphNode('" + starname + "');";*/ std::string scriptParent = "openspace.removeSceneGraphNode('" + starname + "');"; OsEng.scriptEngine().queueScript( scriptParent, openspace::scripting::ScriptEngine::RemoteScripting::Yes ); return 0; } scripting::LuaLibrary ExoplanetsModule::luaLibrary() const { scripting::LuaLibrary res; res.name = "exoplanets"; res.functions = { { "addNode", &addNode, {}, "string", "Adds two nodes to the scenegraph, one position node and one node to represenet the star." }, { "removeNode", &removeNode, {}, "string", "Removes the node with the name given in the arguments." } }; return res; } void ExoplanetsModule::internalInitialize(const ghoul::Dictionary&) { auto fTask = FactoryManager::ref().factory<Task>(); ghoul_assert(fTask, "No task factory existed"); fTask->registerClass<ExoplanetsCsvToBinTask>("ExoplanetsCsvToBinTask"); } std::vector<documentation::Documentation> ExoplanetsModule::documentations() const { return { ExoplanetsCsvToBinTask::documentation() }; } } // namespace openspace <|endoftext|>
<commit_before>/*********************************************************************** filename: SampleData.cpp created: 4/6/2012 author: Lukas E Meindl *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include "SampleData.h" #include "Sample.h" #include "Samples_xmlHandler.h" #include "CEGUI/DynamicModule.h" #include "CEGUI/Version.h" #include "CEGUI/Exceptions.h" #include "CEGUI/System.h" #include "CEGUI/TextureTarget.h" #include "CEGUI/BasicImage.h" #include "CEGUI/GUIContext.h" #include "CEGUI/Texture.h" #include "CEGUI/ImageManager.h" #include "CEGUI/Window.h" #include "CEGUI/Vector.h" using namespace CEGUI; #define S_(X) #X #define STRINGIZE(X) S_(X) typedef Sample& (*getSampleInstance)(); #define GetSampleInstanceFuncName "getSampleInstance" SampleData::SampleData(CEGUI::String sampleName, CEGUI::String summary, CEGUI::String description, SampleType sampleTypeEnum, CEGUI::String credits) : d_name(sampleName), d_summary(summary), d_description(description), d_type(sampleTypeEnum), d_usedFilesString(""), d_credits(credits), d_sampleWindow(0), d_guiContext(0), d_textureTarget(0), d_textureTargetImage(0) { } SampleData::~SampleData() { } CEGUI::String SampleData::getName() { return d_name; } CEGUI::String SampleData::getSummary() { return "Summary:\n" + d_summary; } CEGUI::String SampleData::getCredits() { return "Credits:\n" + d_credits; } CEGUI::String SampleData::getSampleTypeString() { switch(d_type) { case ST_Module: return SampleDataHandler::SampleTypeCppModule; break; case ST_Lua: return SampleDataHandler::SampleTypeLua; break; case ST_Python: return SampleDataHandler::SampleTypePython; default: return ""; } } CEGUI::String SampleData::getDescription() { return "Description:\n" + d_description; } CEGUI::String SampleData::getUsedFilesString() { return "Used files:\n" + d_usedFilesString; } void SampleData::setSampleWindow(CEGUI::Window* sampleWindow) { d_sampleWindow = sampleWindow; } CEGUI::Window* SampleData::getSampleWindow() { return d_sampleWindow; } void SampleData::initialise(int width, int height) { CEGUI::System& system(System::getSingleton()); CEGUI::Sizef size(static_cast<float>(width), static_cast<float>(height)); d_textureTarget = system.getRenderer()->createTextureTarget(); d_guiContext = &system.createGUIContext((RenderTarget&)*d_textureTarget); d_textureTarget->declareRenderSize(size); CEGUI::String imageName(d_textureTarget->getTexture().getName()); d_textureTargetImage = static_cast<CEGUI::BasicImage*>(&CEGUI::ImageManager::getSingleton().create("BasicImage", "SampleBrowser/" + imageName)); d_textureTargetImage->setTexture(&d_textureTarget->getTexture()); setTextureTargetImageArea(height, width); } void SampleData::deinitialise() { CEGUI::System& system(System::getSingleton()); if(d_guiContext) { system.destroyGUIContext(*d_guiContext); d_guiContext = 0; } if(d_textureTarget) { system.getRenderer()->destroyTextureTarget(d_textureTarget); d_textureTarget = 0; } if(d_textureTargetImage) { CEGUI::ImageManager::getSingleton().destroy(*d_textureTargetImage); d_textureTargetImage = 0; } } GUIContext* SampleData::getGuiContext() { return d_guiContext; } void SampleData::handleNewWindowSize(float width, float height) { setTextureTargetImageArea(height, width); CEGUI::Sizef windowSize(width, height); if(d_textureTarget) { d_textureTarget->declareRenderSize(windowSize); d_sampleWindow->getRenderingSurface()->invalidate(); } } CEGUI::Image& SampleData::getRTTImage() { return *d_textureTargetImage; } void SampleData::setGUIContextRTT() { d_guiContext->setRenderTarget(*d_textureTarget); } void SampleData::clearRTTTexture() { d_textureTarget->clear(); } void SampleData::setTextureTargetImageArea(float height, float width) { if(d_textureTarget) { bool isTextureTargetVerticallyFlipped = d_textureTarget->isRenderingInverted(); CEGUI::Rectf renderArea; if(isTextureTargetVerticallyFlipped) renderArea = CEGUI::Rectf(0.0f, height, width, 0.0f); else renderArea = CEGUI::Rectf(0.0f, 0.0f, width, height); if(d_textureTargetImage) d_textureTargetImage->setArea(renderArea); } } SampleDataModule::SampleDataModule(CEGUI::String sampleName, CEGUI::String summary, CEGUI::String description, SampleType sampleTypeEnum, CEGUI::String credits) : SampleData(sampleName, summary, description, sampleTypeEnum, credits) { } SampleDataModule::~SampleDataModule() { } void SampleDataModule::initialise(int width, int height) { SampleData::initialise(width, height); getSampleInstanceFromDLL(); d_sample->initialise(d_guiContext); d_usedFilesString = d_sample->getUsedFilesString(); } void SampleDataModule::deinitialise() { d_sample->deinitialise(); SampleData::deinitialise(); } void SampleDataModule::getSampleInstanceFromDLL() { // Version suffix for the dlls static const CEGUI::String versionSuffix( "-" STRINGIZE(CEGUI_VERSION_MAJOR) "." STRINGIZE(CEGUI_VERSION_MINOR) ); CEGUI::DynamicModule* sampleModule = new CEGUI::DynamicModule(d_name + versionSuffix); getSampleInstance functionPointerGetSample = (getSampleInstance)sampleModule->getSymbolAddress(CEGUI::String(GetSampleInstanceFuncName)); if(functionPointerGetSample == 0) { CEGUI::String errorMessage = "The sample creation function is not defined in the dynamic library of " + d_name; CEGUI_THROW(CEGUI::InvalidRequestException(errorMessage.c_str())); } d_sample = &(functionPointerGetSample()); } void SampleDataModule::onEnteringSample() { d_sample->onEnteringSample(); } void SampleDataModule::update(float timeSinceLastUpdate) { d_sample->update(timeSinceLastUpdate); }<commit_msg>FIX: CEGUI::DynamicModule automatically handles the version suffix.<commit_after>/*********************************************************************** filename: SampleData.cpp created: 4/6/2012 author: Lukas E Meindl *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include "SampleData.h" #include "Sample.h" #include "Samples_xmlHandler.h" #include "CEGUI/DynamicModule.h" #include "CEGUI/Version.h" #include "CEGUI/Exceptions.h" #include "CEGUI/System.h" #include "CEGUI/TextureTarget.h" #include "CEGUI/BasicImage.h" #include "CEGUI/GUIContext.h" #include "CEGUI/Texture.h" #include "CEGUI/ImageManager.h" #include "CEGUI/Window.h" #include "CEGUI/Vector.h" using namespace CEGUI; #define S_(X) #X #define STRINGIZE(X) S_(X) typedef Sample& (*getSampleInstance)(); #define GetSampleInstanceFuncName "getSampleInstance" SampleData::SampleData(CEGUI::String sampleName, CEGUI::String summary, CEGUI::String description, SampleType sampleTypeEnum, CEGUI::String credits) : d_name(sampleName), d_summary(summary), d_description(description), d_type(sampleTypeEnum), d_usedFilesString(""), d_credits(credits), d_sampleWindow(0), d_guiContext(0), d_textureTarget(0), d_textureTargetImage(0) { } SampleData::~SampleData() { } CEGUI::String SampleData::getName() { return d_name; } CEGUI::String SampleData::getSummary() { return "Summary:\n" + d_summary; } CEGUI::String SampleData::getCredits() { return "Credits:\n" + d_credits; } CEGUI::String SampleData::getSampleTypeString() { switch(d_type) { case ST_Module: return SampleDataHandler::SampleTypeCppModule; break; case ST_Lua: return SampleDataHandler::SampleTypeLua; break; case ST_Python: return SampleDataHandler::SampleTypePython; default: return ""; } } CEGUI::String SampleData::getDescription() { return "Description:\n" + d_description; } CEGUI::String SampleData::getUsedFilesString() { return "Used files:\n" + d_usedFilesString; } void SampleData::setSampleWindow(CEGUI::Window* sampleWindow) { d_sampleWindow = sampleWindow; } CEGUI::Window* SampleData::getSampleWindow() { return d_sampleWindow; } void SampleData::initialise(int width, int height) { CEGUI::System& system(System::getSingleton()); CEGUI::Sizef size(static_cast<float>(width), static_cast<float>(height)); d_textureTarget = system.getRenderer()->createTextureTarget(); d_guiContext = &system.createGUIContext((RenderTarget&)*d_textureTarget); d_textureTarget->declareRenderSize(size); CEGUI::String imageName(d_textureTarget->getTexture().getName()); d_textureTargetImage = static_cast<CEGUI::BasicImage*>(&CEGUI::ImageManager::getSingleton().create("BasicImage", "SampleBrowser/" + imageName)); d_textureTargetImage->setTexture(&d_textureTarget->getTexture()); setTextureTargetImageArea(height, width); } void SampleData::deinitialise() { CEGUI::System& system(System::getSingleton()); if(d_guiContext) { system.destroyGUIContext(*d_guiContext); d_guiContext = 0; } if(d_textureTarget) { system.getRenderer()->destroyTextureTarget(d_textureTarget); d_textureTarget = 0; } if(d_textureTargetImage) { CEGUI::ImageManager::getSingleton().destroy(*d_textureTargetImage); d_textureTargetImage = 0; } } GUIContext* SampleData::getGuiContext() { return d_guiContext; } void SampleData::handleNewWindowSize(float width, float height) { setTextureTargetImageArea(height, width); CEGUI::Sizef windowSize(width, height); if(d_textureTarget) { d_textureTarget->declareRenderSize(windowSize); d_sampleWindow->getRenderingSurface()->invalidate(); } } CEGUI::Image& SampleData::getRTTImage() { return *d_textureTargetImage; } void SampleData::setGUIContextRTT() { d_guiContext->setRenderTarget(*d_textureTarget); } void SampleData::clearRTTTexture() { d_textureTarget->clear(); } void SampleData::setTextureTargetImageArea(float height, float width) { if(d_textureTarget) { bool isTextureTargetVerticallyFlipped = d_textureTarget->isRenderingInverted(); CEGUI::Rectf renderArea; if(isTextureTargetVerticallyFlipped) renderArea = CEGUI::Rectf(0.0f, height, width, 0.0f); else renderArea = CEGUI::Rectf(0.0f, 0.0f, width, height); if(d_textureTargetImage) d_textureTargetImage->setArea(renderArea); } } SampleDataModule::SampleDataModule(CEGUI::String sampleName, CEGUI::String summary, CEGUI::String description, SampleType sampleTypeEnum, CEGUI::String credits) : SampleData(sampleName, summary, description, sampleTypeEnum, credits) { } SampleDataModule::~SampleDataModule() { } void SampleDataModule::initialise(int width, int height) { SampleData::initialise(width, height); getSampleInstanceFromDLL(); d_sample->initialise(d_guiContext); d_usedFilesString = d_sample->getUsedFilesString(); } void SampleDataModule::deinitialise() { d_sample->deinitialise(); SampleData::deinitialise(); } void SampleDataModule::getSampleInstanceFromDLL() { CEGUI::DynamicModule* sampleModule = new CEGUI::DynamicModule(d_name); getSampleInstance functionPointerGetSample = (getSampleInstance)sampleModule->getSymbolAddress(CEGUI::String(GetSampleInstanceFuncName)); if(functionPointerGetSample == 0) { CEGUI::String errorMessage = "The sample creation function is not defined in the dynamic library of " + d_name; CEGUI_THROW(CEGUI::InvalidRequestException(errorMessage.c_str())); } d_sample = &(functionPointerGetSample()); } void SampleDataModule::onEnteringSample() { d_sample->onEnteringSample(); } void SampleDataModule::update(float timeSinceLastUpdate) { d_sample->update(timeSinceLastUpdate); }<|endoftext|>
<commit_before>/* * Copyright 2017 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkCubicMap.h" #include "SkottieJson.h" #include "SkottiePriv.h" #include "SkottieValue.h" #include "SkSGScene.h" #include "SkString.h" #include "SkTArray.h" #include <memory> namespace skottie { namespace internal { namespace { #define LOG SkDebugf bool LogFail(const skjson::Value& json, const char* msg) { const auto dump = json.toString(); LOG("!! %s: %s\n", msg, dump.c_str()); return false; } class KeyframeAnimatorBase : public sksg::Animator { public: int count() const { return fRecs.count(); } protected: KeyframeAnimatorBase() = default; struct KeyframeRec { float t0, t1; int vidx0, vidx1, // v0/v1 indices cmidx; // cubic map index bool contains(float t) const { return t0 <= t && t <= t1; } bool isConstant() const { return vidx0 == vidx1; } bool isValid() const { SkASSERT(t0 <= t1); // Constant frames don't need/use t1 and vidx1. return t0 < t1 || this->isConstant(); } }; const KeyframeRec& frame(float t) { if (!fCachedRec || !fCachedRec->contains(t)) { fCachedRec = findFrame(t); } return *fCachedRec; } float localT(const KeyframeRec& rec, float t) const { SkASSERT(rec.isValid()); SkASSERT(!rec.isConstant()); SkASSERT(t > rec.t0 && t < rec.t1); auto lt = (t - rec.t0) / (rec.t1 - rec.t0); return rec.cmidx < 0 ? lt : SkTPin(fCubicMaps[rec.cmidx].computeYFromX(lt), 0.0f, 1.0f); } virtual int parseValue(const skjson::Value&, const AnimationBuilder* abuilder) = 0; void parseKeyFrames(const skjson::ArrayValue& jframes, const AnimationBuilder* abuilder) { for (const skjson::ObjectValue* jframe : jframes) { if (!jframe) continue; float t0; if (!Parse<float>((*jframe)["t"], &t0)) continue; if (!fRecs.empty()) { if (fRecs.back().t1 >= t0) { LOG("!! Ignoring out-of-order key frame (t:%f < t:%f)\n", t0, fRecs.back().t1); continue; } // Back-fill t1 in prev interval. Note: we do this even if we end up discarding // the current interval (to support "t"-only final frames). fRecs.back().t1 = t0; } // Required start value. const auto v0_idx = this->parseValue((*jframe)["s"], abuilder); if (v0_idx < 0) continue; // Optional end value. const auto v1_idx = this->parseValue((*jframe)["e"], abuilder); if (v1_idx < 0) { // Constant keyframe. fRecs.push_back({t0, t0, v0_idx, v0_idx, -1 }); continue; } // default is linear lerp static constexpr SkPoint kDefaultC0 = { 0, 0 }, kDefaultC1 = { 1, 1 }; const auto c0 = ParseDefault<SkPoint>((*jframe)["i"], kDefaultC0), c1 = ParseDefault<SkPoint>((*jframe)["o"], kDefaultC1); int cm_idx = -1; if (c0 != kDefaultC0 || c1 != kDefaultC1) { // TODO: is it worth de-duping these? cm_idx = fCubicMaps.count(); fCubicMaps.emplace_back(); // TODO: why do we have to plug these inverted? fCubicMaps.back().setPts(c1, c0); } fRecs.push_back({t0, t0, v0_idx, v1_idx, cm_idx }); } // If we couldn't determine a valid t1 for the last frame, discard it. if (!fRecs.empty() && !fRecs.back().isValid()) { fRecs.pop_back(); } SkASSERT(fRecs.empty() || fRecs.back().isValid()); } private: const KeyframeRec* findFrame(float t) const { SkASSERT(!fRecs.empty()); auto f0 = &fRecs.front(), f1 = &fRecs.back(); SkASSERT(f0->isValid()); SkASSERT(f1->isValid()); if (t < f0->t0) { return f0; } if (t > f1->t1) { return f1; } while (f0 != f1) { SkASSERT(f0 < f1); SkASSERT(t >= f0->t0 && t <= f1->t1); const auto f = f0 + (f1 - f0) / 2; SkASSERT(f->isValid()); if (t > f->t1) { f0 = f + 1; } else { f1 = f; } } SkASSERT(f0 == f1); SkASSERT(f0->contains(t)); return f0; } SkTArray<KeyframeRec> fRecs; SkTArray<SkCubicMap> fCubicMaps; const KeyframeRec* fCachedRec = nullptr; using INHERITED = sksg::Animator; }; template <typename T> class KeyframeAnimator final : public KeyframeAnimatorBase { public: static std::unique_ptr<KeyframeAnimator> Make(const skjson::ArrayValue* jv, const AnimationBuilder* abuilder, std::function<void(const T&)>&& apply) { if (!jv) return nullptr; std::unique_ptr<KeyframeAnimator> animator( new KeyframeAnimator(*jv, abuilder, std::move(apply))); if (!animator->count()) return nullptr; return animator; } protected: void onTick(float t) override { fApplyFunc(*this->eval(this->frame(t), t, &fScratch)); } private: KeyframeAnimator(const skjson::ArrayValue& jframes, const AnimationBuilder* abuilder, std::function<void(const T&)>&& apply) : fApplyFunc(std::move(apply)) { this->parseKeyFrames(jframes, abuilder); } int parseValue(const skjson::Value& jv, const AnimationBuilder* abuilder) override { T val; if (!ValueTraits<T>::FromJSON(jv, abuilder, &val) || (!fVs.empty() && !ValueTraits<T>::CanLerp(val, fVs.back()))) { return -1; } // TODO: full deduping? if (fVs.empty() || val != fVs.back()) { fVs.push_back(std::move(val)); } return fVs.count() - 1; } const T* eval(const KeyframeRec& rec, float t, T* v) const { SkASSERT(rec.isValid()); if (rec.isConstant() || t <= rec.t0) { return &fVs[rec.vidx0]; } else if (t >= rec.t1) { return &fVs[rec.vidx1]; } const auto lt = this->localT(rec, t); const auto& v0 = fVs[rec.vidx0]; const auto& v1 = fVs[rec.vidx1]; ValueTraits<T>::Lerp(v0, v1, lt, v); return v; } const std::function<void(const T&)> fApplyFunc; SkTArray<T> fVs; // LERP storage: we use this to temporarily store interpolation results. // Alternatively, the temp result could live on the stack -- but for vector values that would // involve dynamic allocations on each tick. This a trade-off to avoid allocator pressure // during animation. T fScratch; // lerp storage using INHERITED = KeyframeAnimatorBase; }; template <typename T> static inline bool BindPropertyImpl(const skjson::ObjectValue* jprop, const AnimationBuilder* abuilder, AnimatorScope* ascope, std::function<void(const T&)>&& apply, const T* noop = nullptr) { if (!jprop) return false; const auto& jpropA = (*jprop)["a"]; const auto& jpropK = (*jprop)["k"]; if (!(*jprop)["x"].is<skjson::NullValue>()) { LOG("?? Unsupported expression.\n"); } // Older Json versions don't have an "a" animation marker. // For those, we attempt to parse both ways. if (!ParseDefault<bool>(jpropA, false)) { T val; if (ValueTraits<T>::FromJSON(jpropK, abuilder, &val)) { // Static property. if (noop && val == *noop) return false; apply(val); return true; } if (!jpropA.is<skjson::NullValue>()) { return LogFail(*jprop, "Could not parse (explicit) static property"); } } // Keyframe property. auto animator = KeyframeAnimator<T>::Make(jpropK, abuilder, std::move(apply)); if (!animator) { return LogFail(*jprop, "Could not parse keyframed property"); } ascope->push_back(std::move(animator)); return true; } class SplitPointAnimator final : public sksg::Animator { public: static std::unique_ptr<SplitPointAnimator> Make(const skjson::ObjectValue* jprop, const AnimationBuilder* abuilder, std::function<void(const VectorValue&)>&& apply, const VectorValue*) { if (!jprop) return nullptr; std::unique_ptr<SplitPointAnimator> split_animator( new SplitPointAnimator(std::move(apply))); // This raw pointer is captured in lambdas below. But the lambdas are owned by // the object itself, so the scope is bound to the life time of the object. auto* split_animator_ptr = split_animator.get(); if (!BindPropertyImpl<ScalarValue>((*jprop)["x"], abuilder, &split_animator->fAnimators, [split_animator_ptr](const ScalarValue& x) { split_animator_ptr->setX(x); }) || !BindPropertyImpl<ScalarValue>((*jprop)["y"], abuilder, &split_animator->fAnimators, [split_animator_ptr](const ScalarValue& y) { split_animator_ptr->setY(y); })) { LogFail(*jprop, "Could not parse split property"); return nullptr; } if (split_animator->fAnimators.empty()) { // Static split property: commit the (buffered) value and discard. split_animator->onTick(0); return nullptr; } return split_animator; } void onTick(float t) override { for (const auto& animator : fAnimators) { animator->tick(t); } const VectorValue vec = { fX, fY }; fApplyFunc(vec); } void setX(const ScalarValue& x) { fX = x; } void setY(const ScalarValue& y) { fY = y; } private: explicit SplitPointAnimator(std::function<void(const VectorValue&)>&& apply) : fApplyFunc(std::move(apply)) {} const std::function<void(const VectorValue&)> fApplyFunc; sksg::AnimatorList fAnimators; ScalarValue fX = 0, fY = 0; using INHERITED = sksg::Animator; }; bool BindSplitPositionProperty(const skjson::Value& jv, const AnimationBuilder* abuilder, AnimatorScope* ascope, std::function<void(const VectorValue&)>&& apply, const VectorValue* noop) { if (auto split_animator = SplitPointAnimator::Make(jv, abuilder, std::move(apply), noop)) { ascope->push_back(std::unique_ptr<sksg::Animator>(split_animator.release())); return true; } return false; } } // namespace template <> bool AnimationBuilder::bindProperty(const skjson::Value& jv, AnimatorScope* ascope, std::function<void(const ScalarValue&)>&& apply, const ScalarValue* noop) const { return BindPropertyImpl(jv, this, ascope, std::move(apply), noop); } template <> bool AnimationBuilder::bindProperty(const skjson::Value& jv, AnimatorScope* ascope, std::function<void(const VectorValue&)>&& apply, const VectorValue* noop) const { if (!jv.is<skjson::ObjectValue>()) return false; return ParseDefault<bool>(jv.as<skjson::ObjectValue>()["s"], false) ? BindSplitPositionProperty(jv, this, ascope, std::move(apply), noop) : BindPropertyImpl(jv, this, ascope, std::move(apply), noop); } template <> bool AnimationBuilder::bindProperty(const skjson::Value& jv, AnimatorScope* ascope, std::function<void(const ShapeValue&)>&& apply, const ShapeValue* noop) const { return BindPropertyImpl(jv, this, ascope, std::move(apply), noop); } template <> bool AnimationBuilder::bindProperty(const skjson::Value& jv, AnimatorScope* ascope, std::function<void(const TextValue&)>&& apply, const TextValue* noop) const { return BindPropertyImpl(jv, this, ascope, std::move(apply), noop); } } // namespace internal } // namespace skottie <commit_msg>[skottie] SkTArray begone<commit_after>/* * Copyright 2017 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkCubicMap.h" #include "SkottieJson.h" #include "SkottiePriv.h" #include "SkottieValue.h" #include "SkSGScene.h" #include "SkString.h" #include <memory> #include <vector> namespace skottie { namespace internal { namespace { #define LOG SkDebugf bool LogFail(const skjson::Value& json, const char* msg) { const auto dump = json.toString(); LOG("!! %s: %s\n", msg, dump.c_str()); return false; } class KeyframeAnimatorBase : public sksg::Animator { public: size_t count() const { return fRecs.size(); } protected: KeyframeAnimatorBase() = default; struct KeyframeRec { float t0, t1; int vidx0, vidx1, // v0/v1 indices cmidx; // cubic map index bool contains(float t) const { return t0 <= t && t <= t1; } bool isConstant() const { return vidx0 == vidx1; } bool isValid() const { SkASSERT(t0 <= t1); // Constant frames don't need/use t1 and vidx1. return t0 < t1 || this->isConstant(); } }; const KeyframeRec& frame(float t) { if (!fCachedRec || !fCachedRec->contains(t)) { fCachedRec = findFrame(t); } return *fCachedRec; } float localT(const KeyframeRec& rec, float t) const { SkASSERT(rec.isValid()); SkASSERT(!rec.isConstant()); SkASSERT(t > rec.t0 && t < rec.t1); auto lt = (t - rec.t0) / (rec.t1 - rec.t0); return rec.cmidx < 0 ? lt : SkTPin(fCubicMaps[rec.cmidx].computeYFromX(lt), 0.0f, 1.0f); } virtual int parseValue(const skjson::Value&, const AnimationBuilder* abuilder) = 0; void parseKeyFrames(const skjson::ArrayValue& jframes, const AnimationBuilder* abuilder) { for (const skjson::ObjectValue* jframe : jframes) { if (!jframe) continue; float t0; if (!Parse<float>((*jframe)["t"], &t0)) continue; if (!fRecs.empty()) { if (fRecs.back().t1 >= t0) { LOG("!! Ignoring out-of-order key frame (t:%f < t:%f)\n", t0, fRecs.back().t1); continue; } // Back-fill t1 in prev interval. Note: we do this even if we end up discarding // the current interval (to support "t"-only final frames). fRecs.back().t1 = t0; } // Required start value. const auto v0_idx = this->parseValue((*jframe)["s"], abuilder); if (v0_idx < 0) continue; // Optional end value. const auto v1_idx = this->parseValue((*jframe)["e"], abuilder); if (v1_idx < 0) { // Constant keyframe. fRecs.push_back({t0, t0, v0_idx, v0_idx, -1 }); continue; } // default is linear lerp static constexpr SkPoint kDefaultC0 = { 0, 0 }, kDefaultC1 = { 1, 1 }; const auto c0 = ParseDefault<SkPoint>((*jframe)["i"], kDefaultC0), c1 = ParseDefault<SkPoint>((*jframe)["o"], kDefaultC1); int cm_idx = -1; if (c0 != kDefaultC0 || c1 != kDefaultC1) { // TODO: is it worth de-duping these? cm_idx = SkToInt(fCubicMaps.size()); fCubicMaps.emplace_back(); // TODO: why do we have to plug these inverted? fCubicMaps.back().setPts(c1, c0); } fRecs.push_back({t0, t0, v0_idx, v1_idx, cm_idx }); } // If we couldn't determine a valid t1 for the last frame, discard it. if (!fRecs.empty() && !fRecs.back().isValid()) { fRecs.pop_back(); } fRecs.shrink_to_fit(); fCubicMaps.shrink_to_fit(); SkASSERT(fRecs.empty() || fRecs.back().isValid()); } void reserve(size_t frame_count) { fRecs.reserve(frame_count); fCubicMaps.reserve(frame_count); } private: const KeyframeRec* findFrame(float t) const { SkASSERT(!fRecs.empty()); auto f0 = &fRecs.front(), f1 = &fRecs.back(); SkASSERT(f0->isValid()); SkASSERT(f1->isValid()); if (t < f0->t0) { return f0; } if (t > f1->t1) { return f1; } while (f0 != f1) { SkASSERT(f0 < f1); SkASSERT(t >= f0->t0 && t <= f1->t1); const auto f = f0 + (f1 - f0) / 2; SkASSERT(f->isValid()); if (t > f->t1) { f0 = f + 1; } else { f1 = f; } } SkASSERT(f0 == f1); SkASSERT(f0->contains(t)); return f0; } std::vector<KeyframeRec> fRecs; std::vector<SkCubicMap> fCubicMaps; const KeyframeRec* fCachedRec = nullptr; using INHERITED = sksg::Animator; }; template <typename T> class KeyframeAnimator final : public KeyframeAnimatorBase { public: static std::unique_ptr<KeyframeAnimator> Make(const skjson::ArrayValue* jv, const AnimationBuilder* abuilder, std::function<void(const T&)>&& apply) { if (!jv) return nullptr; std::unique_ptr<KeyframeAnimator> animator( new KeyframeAnimator(*jv, abuilder, std::move(apply))); if (!animator->count()) return nullptr; return animator; } protected: void onTick(float t) override { fApplyFunc(*this->eval(this->frame(t), t, &fScratch)); } private: KeyframeAnimator(const skjson::ArrayValue& jframes, const AnimationBuilder* abuilder, std::function<void(const T&)>&& apply) : fApplyFunc(std::move(apply)) { // Generally, each keyframe holds two values (start, end) and a cubic mapper. Except // the last frame, which only holds a marker timestamp. Then, the values series is // contiguous (keyframe[i].end == keyframe[i + 1].start), and we dedupe them. // => we'll store (keyframes.size) values and (keyframe.size - 1) recs and cubic maps. fVs.reserve(jframes.size()); this->reserve(SkTMax<size_t>(jframes.size(), 1) - 1); this->parseKeyFrames(jframes, abuilder); fVs.shrink_to_fit(); } int parseValue(const skjson::Value& jv, const AnimationBuilder* abuilder) override { T val; if (!ValueTraits<T>::FromJSON(jv, abuilder, &val) || (!fVs.empty() && !ValueTraits<T>::CanLerp(val, fVs.back()))) { return -1; } // TODO: full deduping? if (fVs.empty() || val != fVs.back()) { fVs.push_back(std::move(val)); } return SkToInt(fVs.size()) - 1; } const T* eval(const KeyframeRec& rec, float t, T* v) const { SkASSERT(rec.isValid()); if (rec.isConstant() || t <= rec.t0) { return &fVs[rec.vidx0]; } else if (t >= rec.t1) { return &fVs[rec.vidx1]; } const auto lt = this->localT(rec, t); const auto& v0 = fVs[rec.vidx0]; const auto& v1 = fVs[rec.vidx1]; ValueTraits<T>::Lerp(v0, v1, lt, v); return v; } const std::function<void(const T&)> fApplyFunc; std::vector<T> fVs; // LERP storage: we use this to temporarily store interpolation results. // Alternatively, the temp result could live on the stack -- but for vector values that would // involve dynamic allocations on each tick. This a trade-off to avoid allocator pressure // during animation. T fScratch; // lerp storage using INHERITED = KeyframeAnimatorBase; }; template <typename T> static inline bool BindPropertyImpl(const skjson::ObjectValue* jprop, const AnimationBuilder* abuilder, AnimatorScope* ascope, std::function<void(const T&)>&& apply, const T* noop = nullptr) { if (!jprop) return false; const auto& jpropA = (*jprop)["a"]; const auto& jpropK = (*jprop)["k"]; if (!(*jprop)["x"].is<skjson::NullValue>()) { LOG("?? Unsupported expression.\n"); } // Older Json versions don't have an "a" animation marker. // For those, we attempt to parse both ways. if (!ParseDefault<bool>(jpropA, false)) { T val; if (ValueTraits<T>::FromJSON(jpropK, abuilder, &val)) { // Static property. if (noop && val == *noop) return false; apply(val); return true; } if (!jpropA.is<skjson::NullValue>()) { return LogFail(*jprop, "Could not parse (explicit) static property"); } } // Keyframe property. auto animator = KeyframeAnimator<T>::Make(jpropK, abuilder, std::move(apply)); if (!animator) { return LogFail(*jprop, "Could not parse keyframed property"); } ascope->push_back(std::move(animator)); return true; } class SplitPointAnimator final : public sksg::Animator { public: static std::unique_ptr<SplitPointAnimator> Make(const skjson::ObjectValue* jprop, const AnimationBuilder* abuilder, std::function<void(const VectorValue&)>&& apply, const VectorValue*) { if (!jprop) return nullptr; std::unique_ptr<SplitPointAnimator> split_animator( new SplitPointAnimator(std::move(apply))); // This raw pointer is captured in lambdas below. But the lambdas are owned by // the object itself, so the scope is bound to the life time of the object. auto* split_animator_ptr = split_animator.get(); if (!BindPropertyImpl<ScalarValue>((*jprop)["x"], abuilder, &split_animator->fAnimators, [split_animator_ptr](const ScalarValue& x) { split_animator_ptr->setX(x); }) || !BindPropertyImpl<ScalarValue>((*jprop)["y"], abuilder, &split_animator->fAnimators, [split_animator_ptr](const ScalarValue& y) { split_animator_ptr->setY(y); })) { LogFail(*jprop, "Could not parse split property"); return nullptr; } if (split_animator->fAnimators.empty()) { // Static split property: commit the (buffered) value and discard. split_animator->onTick(0); return nullptr; } return split_animator; } void onTick(float t) override { for (const auto& animator : fAnimators) { animator->tick(t); } const VectorValue vec = { fX, fY }; fApplyFunc(vec); } void setX(const ScalarValue& x) { fX = x; } void setY(const ScalarValue& y) { fY = y; } private: explicit SplitPointAnimator(std::function<void(const VectorValue&)>&& apply) : fApplyFunc(std::move(apply)) {} const std::function<void(const VectorValue&)> fApplyFunc; sksg::AnimatorList fAnimators; ScalarValue fX = 0, fY = 0; using INHERITED = sksg::Animator; }; bool BindSplitPositionProperty(const skjson::Value& jv, const AnimationBuilder* abuilder, AnimatorScope* ascope, std::function<void(const VectorValue&)>&& apply, const VectorValue* noop) { if (auto split_animator = SplitPointAnimator::Make(jv, abuilder, std::move(apply), noop)) { ascope->push_back(std::unique_ptr<sksg::Animator>(split_animator.release())); return true; } return false; } } // namespace template <> bool AnimationBuilder::bindProperty(const skjson::Value& jv, AnimatorScope* ascope, std::function<void(const ScalarValue&)>&& apply, const ScalarValue* noop) const { return BindPropertyImpl(jv, this, ascope, std::move(apply), noop); } template <> bool AnimationBuilder::bindProperty(const skjson::Value& jv, AnimatorScope* ascope, std::function<void(const VectorValue&)>&& apply, const VectorValue* noop) const { if (!jv.is<skjson::ObjectValue>()) return false; return ParseDefault<bool>(jv.as<skjson::ObjectValue>()["s"], false) ? BindSplitPositionProperty(jv, this, ascope, std::move(apply), noop) : BindPropertyImpl(jv, this, ascope, std::move(apply), noop); } template <> bool AnimationBuilder::bindProperty(const skjson::Value& jv, AnimatorScope* ascope, std::function<void(const ShapeValue&)>&& apply, const ShapeValue* noop) const { return BindPropertyImpl(jv, this, ascope, std::move(apply), noop); } template <> bool AnimationBuilder::bindProperty(const skjson::Value& jv, AnimatorScope* ascope, std::function<void(const TextValue&)>&& apply, const TextValue* noop) const { return BindPropertyImpl(jv, this, ascope, std::move(apply), noop); } } // namespace internal } // namespace skottie <|endoftext|>
<commit_before>/* * Copyright 2017 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "include/effects/SkGradientShader.h" #include "modules/svg/include/SkSVGRadialGradient.h" #include "modules/svg/include/SkSVGRenderContext.h" #include "modules/svg/include/SkSVGValue.h" SkSVGRadialGradient::SkSVGRadialGradient() : INHERITED(SkSVGTag::kRadialGradient) {} bool SkSVGRadialGradient::parseAndSetAttribute(const char* name, const char* value) { return INHERITED::parseAndSetAttribute(name, value) || this->setCx(SkSVGAttributeParser::parse<SkSVGLength>("cx", name, value)) || this->setCy(SkSVGAttributeParser::parse<SkSVGLength>("cy", name, value)) || this->setR(SkSVGAttributeParser::parse<SkSVGLength>("r", name, value)) || this->setFx(SkSVGAttributeParser::parse<SkSVGLength>("fx", name, value)) || this->setFy(SkSVGAttributeParser::parse<SkSVGLength>("fy", name, value)); } sk_sp<SkShader> SkSVGRadialGradient::onMakeShader(const SkSVGRenderContext& ctx, const SkColor* colors, const SkScalar* pos, int count, SkTileMode tm, const SkMatrix& m) const { const SkSVGLengthContext lctx = this->getGradientUnits().type() == SkSVGObjectBoundingBoxUnits::Type::kObjectBoundingBox ? SkSVGLengthContext({1, 1}) : ctx.lengthContext(); const auto r = lctx.resolve(fR , SkSVGLengthContext::LengthType::kOther); const auto center = SkPoint::Make( lctx.resolve(fCx, SkSVGLengthContext::LengthType::kHorizontal), lctx.resolve(fCy, SkSVGLengthContext::LengthType::kVertical)); const auto focal = SkPoint::Make( fFx.isValid() ? lctx.resolve(*fFx, SkSVGLengthContext::LengthType::kHorizontal) : center.x(), fFy.isValid() ? lctx.resolve(*fFy, SkSVGLengthContext::LengthType::kVertical) : center.y()); // TODO: Handle r == 0 which has a specific meaning according to the spec SkASSERT(r != 0); return center == focal ? SkGradientShader::MakeRadial(center, r, colors, pos, count, tm, 0, &m) : SkGradientShader::MakeTwoPointConical(focal, 0, center, r, colors, pos, count, tm, 0, &m); } <commit_msg>[svg] Handle zero-radius radial gradients<commit_after>/* * Copyright 2017 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "include/effects/SkGradientShader.h" #include "modules/svg/include/SkSVGRadialGradient.h" #include "modules/svg/include/SkSVGRenderContext.h" #include "modules/svg/include/SkSVGValue.h" SkSVGRadialGradient::SkSVGRadialGradient() : INHERITED(SkSVGTag::kRadialGradient) {} bool SkSVGRadialGradient::parseAndSetAttribute(const char* name, const char* value) { return INHERITED::parseAndSetAttribute(name, value) || this->setCx(SkSVGAttributeParser::parse<SkSVGLength>("cx", name, value)) || this->setCy(SkSVGAttributeParser::parse<SkSVGLength>("cy", name, value)) || this->setR(SkSVGAttributeParser::parse<SkSVGLength>("r", name, value)) || this->setFx(SkSVGAttributeParser::parse<SkSVGLength>("fx", name, value)) || this->setFy(SkSVGAttributeParser::parse<SkSVGLength>("fy", name, value)); } sk_sp<SkShader> SkSVGRadialGradient::onMakeShader(const SkSVGRenderContext& ctx, const SkColor* colors, const SkScalar* pos, int count, SkTileMode tm, const SkMatrix& m) const { const SkSVGLengthContext lctx = this->getGradientUnits().type() == SkSVGObjectBoundingBoxUnits::Type::kObjectBoundingBox ? SkSVGLengthContext({1, 1}) : ctx.lengthContext(); const auto r = lctx.resolve(fR , SkSVGLengthContext::LengthType::kOther); const auto center = SkPoint::Make( lctx.resolve(fCx, SkSVGLengthContext::LengthType::kHorizontal), lctx.resolve(fCy, SkSVGLengthContext::LengthType::kVertical)); const auto focal = SkPoint::Make( fFx.isValid() ? lctx.resolve(*fFx, SkSVGLengthContext::LengthType::kHorizontal) : center.x(), fFy.isValid() ? lctx.resolve(*fFy, SkSVGLengthContext::LengthType::kVertical) : center.y()); if (r == 0) { const auto last_color = count > 0 ? colors[count - 1] : SK_ColorBLACK; return SkShaders::Color(last_color); } return center == focal ? SkGradientShader::MakeRadial(center, r, colors, pos, count, tm, 0, &m) : SkGradientShader::MakeTwoPointConical(focal, 0, center, r, colors, pos, count, tm, 0, &m); } <|endoftext|>
<commit_before>/* This file is part of the KDE project Copyright (C) 2005-2006 Matthias Kretz <kretz@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "audiooutput.h" #include "audiooutput_p.h" #include "factory.h" #include "objectdescription.h" #include "audiooutputadaptor.h" #include "globalconfig.h" #include "audiooutputinterface.h" #include "phononnamespace_p.h" #include "platform_p.h" #include <cmath> #define PHONON_CLASSNAME AudioOutput #define PHONON_INTERFACENAME AudioOutputInterface namespace Phonon { AudioOutput::AudioOutput(Phonon::Category category, QObject *parent) : AbstractAudioOutput(*new AudioOutputPrivate, parent) { K_D(AudioOutput); d->init(category); } AudioOutput::AudioOutput(QObject *parent) : AbstractAudioOutput(*new AudioOutputPrivate, parent) { K_D(AudioOutput); d->init(NoCategory); } void AudioOutputPrivate::init(Phonon::Category c) { Q_Q(AudioOutput); category = c; // select hardware device according to the category outputDeviceIndex = GlobalConfig().audioOutputDeviceFor(category); createBackendObject(); #ifndef QT_NO_DBUS new AudioOutputAdaptor(q); static unsigned int number = 0; QDBusConnection::sessionBus().registerObject("/AudioOutputs/" + QString::number(number++), q); #endif q->connect(Factory::sender(), SIGNAL(availableAudioOutputDevicesChanged()), SLOT(_k_deviceListChanged())); } void AudioOutputPrivate::createBackendObject() { if (m_backendObject) return; Q_Q(AudioOutput); m_backendObject = Factory::createAudioOutput(q); if (m_backendObject) { setupBackendObject(); } } QString AudioOutput::name() const { K_D(const AudioOutput); return d->name; } void AudioOutput::setName(const QString &newName) { K_D(AudioOutput); d->name = newName; setVolume(Platform::loadVolume(newName)); } void AudioOutput::setVolume(qreal volume) { K_D(AudioOutput); d->volume = volume; if (k_ptr->backendObject() && !d->muted) { // using Stevens' power law loudness is proportional to (sound pressure)^0.67 // sound pressure is proportional to voltage: // p² \prop P \prop V² // => if a factor for loudness of x is requested INTERFACE_CALL(setVolume(std::pow(volume, 1.4925373))); } else { emit volumeChanged(volume); } Platform::saveVolume(d->name, volume); } qreal AudioOutput::volume() const { K_D(const AudioOutput); if (d->muted || !d->m_backendObject) { return d->volume; } return std::pow(INTERFACE_CALL(volume()), 0.67); } #ifndef PHONON_LOG10OVER20 #define PHONON_LOG10OVER20 static const qreal log10over20 = 0.1151292546497022842; // ln(10) / 20 #endif // PHONON_LOG10OVER20 qreal AudioOutput::volumeDecibel() const { K_D(const AudioOutput); if (d->muted || !d->m_backendObject) { return -std::log(d->volume) / log10over20; } return -0.67 * std::log(INTERFACE_CALL(volume())) / log10over20; } void AudioOutput::setVolumeDecibel(qreal newVolumeDecibel) { setVolume(std::exp(-newVolumeDecibel * log10over20)); } bool AudioOutput::isMuted() const { K_D(const AudioOutput); return d->muted; } void AudioOutput::setMuted(bool mute) { K_D(AudioOutput); if (d->muted != mute) { if (mute) { d->muted = mute; if (k_ptr->backendObject()) { INTERFACE_CALL(setVolume(0.0)); } } else { if (k_ptr->backendObject()) { INTERFACE_CALL(setVolume(std::pow(d->volume, 1.4925373))); } d->muted = mute; } emit mutedChanged(mute); } } Category AudioOutput::category() const { K_D(const AudioOutput); return d->category; } AudioOutputDevice AudioOutput::outputDevice() const { K_D(const AudioOutput); int index; if (d->m_backendObject) index = INTERFACE_CALL(outputDevice()); else index = d->outputDeviceIndex; return AudioOutputDevice::fromIndex(index); } bool AudioOutput::setOutputDevice(const AudioOutputDevice &newAudioOutputDevice) { K_D(AudioOutput); if (!newAudioOutputDevice.isValid()) { d->outputDeviceOverridden = false; d->outputDeviceIndex = GlobalConfig().audioOutputDeviceFor(d->category); } else { d->outputDeviceOverridden = true; d->outputDeviceIndex = newAudioOutputDevice.index(); } if (k_ptr->backendObject()) { return INTERFACE_CALL(setOutputDevice(d->outputDeviceIndex)); } return true; } bool AudioOutputPrivate::aboutToDeleteBackendObject() { if (m_backendObject) { volume = pINTERFACE_CALL(volume()); } return AbstractAudioOutputPrivate::aboutToDeleteBackendObject(); } void AudioOutputPrivate::setupBackendObject() { Q_Q(AudioOutput); Q_ASSERT(m_backendObject); AbstractAudioOutputPrivate::setupBackendObject(); QObject::connect(m_backendObject, SIGNAL(volumeChanged(qreal)), q, SLOT(_k_volumeChanged(qreal))); QObject::connect(m_backendObject, SIGNAL(audioDeviceFailed()), q, SLOT(_k_audioDeviceFailed())); // set up attributes pINTERFACE_CALL(setVolume(std::pow(volume, 1.4925373))); // if the output device is not available and the device was not explicitly set if (!pINTERFACE_CALL(setOutputDevice(outputDeviceIndex)) && !outputDeviceOverridden) { // fall back in the preference list of output devices QList<int> deviceList = GlobalConfig().audioOutputDeviceListFor(category); if (deviceList.isEmpty()) { return; } if (outputDeviceIndex == deviceList.takeFirst()) { // removing the first device so that // if it's the same device as the one we tried we only try all the following foreach (int devIndex, deviceList) { if (pINTERFACE_CALL(setOutputDevice(devIndex))) { handleAutomaticDeviceChange(devIndex, AudioOutputPrivate::FallbackChange); break; // found one that works } } } } } void AudioOutputPrivate::_k_volumeChanged(qreal newVolume) { if (!muted) { Q_Q(AudioOutput); emit q->volumeChanged(std::pow(newVolume, 0.67)); } } void AudioOutputPrivate::_k_revertFallback() { if (deviceBeforeFallback == -1) { return; } outputDeviceIndex = deviceBeforeFallback; pINTERFACE_CALL(setOutputDevice(outputDeviceIndex)); Q_Q(AudioOutput); emit q->outputDeviceChanged(AudioOutputDevice::fromIndex(outputDeviceIndex)); } void AudioOutputPrivate::_k_audioDeviceFailed() { pDebug() << Q_FUNC_INFO; // outputDeviceIndex identifies a failing device // fall back in the preference list of output devices QList<int> deviceList = GlobalConfig().audioOutputDeviceListFor(category); foreach (int devIndex, deviceList) { // if it's the same device as the one that failed, ignore it if (outputDeviceIndex != devIndex) { if (pINTERFACE_CALL(setOutputDevice(devIndex))) { handleAutomaticDeviceChange(devIndex, FallbackChange); break; // found one that works } } } } void AudioOutputPrivate::_k_deviceListChanged() { pDebug() << Q_FUNC_INFO; // let's see if there's a usable device higher in the preference list QList<int> deviceList = GlobalConfig().audioOutputDeviceListFor(category); DeviceChangeType changeType = HigherPreferenceChange; foreach (int devIndex, deviceList) { pDebug() << devIndex; if (outputDeviceIndex == devIndex) { AudioOutputDevice info = AudioOutputDevice::fromIndex(devIndex); if (info.property("available").toBool()) { break; // we've reached the currently used device, nothing to change } changeType = FallbackChange; } if (pINTERFACE_CALL(setOutputDevice(devIndex))) { handleAutomaticDeviceChange(devIndex, changeType); break; // found one with higher preference that works } } } void AudioOutputPrivate::handleAutomaticDeviceChange(int newIndex, DeviceChangeType type) { Q_Q(AudioOutput); deviceBeforeFallback = outputDeviceIndex; outputDeviceIndex = newIndex; emit q->outputDeviceChanged(AudioOutputDevice::fromIndex(outputDeviceIndex)); QString text; AudioOutputDevice device1 = AudioOutputDevice::fromIndex(deviceBeforeFallback); AudioOutputDevice device2 = AudioOutputDevice::fromIndex(outputDeviceIndex); switch (type) { case FallbackChange: text = AudioOutput::tr("<html>The audio playback device <b>%1</b> does not work.<br/>" "Falling back to <b>%2</b>.</html>").arg(device1.name()).arg(device2.name()); Platform::notification("AudioDeviceFallback", text); break; case HigherPreferenceChange: text = AudioOutput::tr("<html>Switching to the audio playback device <b>%1</b><br/>" "which just became available and has higher preference.</html>").arg(device2.name()); Platform::notification("AudioDeviceFallback", text, QStringList(AudioOutput::tr("Revert back to device '%1'").arg(device1.name())), q, SLOT(_k_revertFallback())); break; } } } //namespace Phonon #include "moc_audiooutput.cpp" #undef PHONON_CLASSNAME #undef PHONON_INTERFACENAME // vim: sw=4 ts=4 tw=100 et <commit_msg>qreal and double are not the same on all platforms<commit_after>/* This file is part of the KDE project Copyright (C) 2005-2006 Matthias Kretz <kretz@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "audiooutput.h" #include "audiooutput_p.h" #include "factory.h" #include "objectdescription.h" #include "audiooutputadaptor.h" #include "globalconfig.h" #include "audiooutputinterface.h" #include "phononnamespace_p.h" #include "platform_p.h" #include <cmath> #define PHONON_CLASSNAME AudioOutput #define PHONON_INTERFACENAME AudioOutputInterface namespace Phonon { AudioOutput::AudioOutput(Phonon::Category category, QObject *parent) : AbstractAudioOutput(*new AudioOutputPrivate, parent) { K_D(AudioOutput); d->init(category); } AudioOutput::AudioOutput(QObject *parent) : AbstractAudioOutput(*new AudioOutputPrivate, parent) { K_D(AudioOutput); d->init(NoCategory); } void AudioOutputPrivate::init(Phonon::Category c) { Q_Q(AudioOutput); category = c; // select hardware device according to the category outputDeviceIndex = GlobalConfig().audioOutputDeviceFor(category); createBackendObject(); #ifndef QT_NO_DBUS new AudioOutputAdaptor(q); static unsigned int number = 0; QDBusConnection::sessionBus().registerObject("/AudioOutputs/" + QString::number(number++), q); #endif q->connect(Factory::sender(), SIGNAL(availableAudioOutputDevicesChanged()), SLOT(_k_deviceListChanged())); } void AudioOutputPrivate::createBackendObject() { if (m_backendObject) return; Q_Q(AudioOutput); m_backendObject = Factory::createAudioOutput(q); if (m_backendObject) { setupBackendObject(); } } QString AudioOutput::name() const { K_D(const AudioOutput); return d->name; } void AudioOutput::setName(const QString &newName) { K_D(AudioOutput); d->name = newName; setVolume(Platform::loadVolume(newName)); } void AudioOutput::setVolume(qreal volume) { K_D(AudioOutput); d->volume = volume; if (k_ptr->backendObject() && !d->muted) { // using Stevens' power law loudness is proportional to (sound pressure)^0.67 // sound pressure is proportional to voltage: // p² \prop P \prop V² // => if a factor for loudness of x is requested INTERFACE_CALL(setVolume(std::pow(volume, qreal(1.4925373)))); } else { emit volumeChanged(volume); } Platform::saveVolume(d->name, volume); } qreal AudioOutput::volume() const { K_D(const AudioOutput); if (d->muted || !d->m_backendObject) { return d->volume; } return std::pow(INTERFACE_CALL(volume()), qreal(0.67)); } #ifndef PHONON_LOG10OVER20 #define PHONON_LOG10OVER20 static const qreal log10over20 = 0.1151292546497022842; // ln(10) / 20 #endif // PHONON_LOG10OVER20 qreal AudioOutput::volumeDecibel() const { K_D(const AudioOutput); if (d->muted || !d->m_backendObject) { return -std::log(d->volume) / log10over20; } return -0.67 * std::log(INTERFACE_CALL(volume())) / log10over20; } void AudioOutput::setVolumeDecibel(qreal newVolumeDecibel) { setVolume(std::exp(-newVolumeDecibel * log10over20)); } bool AudioOutput::isMuted() const { K_D(const AudioOutput); return d->muted; } void AudioOutput::setMuted(bool mute) { K_D(AudioOutput); if (d->muted != mute) { if (mute) { d->muted = mute; if (k_ptr->backendObject()) { INTERFACE_CALL(setVolume(0.0)); } } else { if (k_ptr->backendObject()) { INTERFACE_CALL(setVolume(std::pow(d->volume, (qreal) 1.4925373))); } d->muted = mute; } emit mutedChanged(mute); } } Category AudioOutput::category() const { K_D(const AudioOutput); return d->category; } AudioOutputDevice AudioOutput::outputDevice() const { K_D(const AudioOutput); int index; if (d->m_backendObject) index = INTERFACE_CALL(outputDevice()); else index = d->outputDeviceIndex; return AudioOutputDevice::fromIndex(index); } bool AudioOutput::setOutputDevice(const AudioOutputDevice &newAudioOutputDevice) { K_D(AudioOutput); if (!newAudioOutputDevice.isValid()) { d->outputDeviceOverridden = false; d->outputDeviceIndex = GlobalConfig().audioOutputDeviceFor(d->category); } else { d->outputDeviceOverridden = true; d->outputDeviceIndex = newAudioOutputDevice.index(); } if (k_ptr->backendObject()) { return INTERFACE_CALL(setOutputDevice(d->outputDeviceIndex)); } return true; } bool AudioOutputPrivate::aboutToDeleteBackendObject() { if (m_backendObject) { volume = pINTERFACE_CALL(volume()); } return AbstractAudioOutputPrivate::aboutToDeleteBackendObject(); } void AudioOutputPrivate::setupBackendObject() { Q_Q(AudioOutput); Q_ASSERT(m_backendObject); AbstractAudioOutputPrivate::setupBackendObject(); QObject::connect(m_backendObject, SIGNAL(volumeChanged(qreal)), q, SLOT(_k_volumeChanged(qreal))); QObject::connect(m_backendObject, SIGNAL(audioDeviceFailed()), q, SLOT(_k_audioDeviceFailed())); // set up attributes pINTERFACE_CALL(setVolume(std::pow(volume, qreal(1.4925373)))); // if the output device is not available and the device was not explicitly set if (!pINTERFACE_CALL(setOutputDevice(outputDeviceIndex)) && !outputDeviceOverridden) { // fall back in the preference list of output devices QList<int> deviceList = GlobalConfig().audioOutputDeviceListFor(category); if (deviceList.isEmpty()) { return; } if (outputDeviceIndex == deviceList.takeFirst()) { // removing the first device so that // if it's the same device as the one we tried we only try all the following foreach (int devIndex, deviceList) { if (pINTERFACE_CALL(setOutputDevice(devIndex))) { handleAutomaticDeviceChange(devIndex, AudioOutputPrivate::FallbackChange); break; // found one that works } } } } } void AudioOutputPrivate::_k_volumeChanged(qreal newVolume) { if (!muted) { Q_Q(AudioOutput); emit q->volumeChanged(std::pow(newVolume, qreal(0.67))); } } void AudioOutputPrivate::_k_revertFallback() { if (deviceBeforeFallback == -1) { return; } outputDeviceIndex = deviceBeforeFallback; pINTERFACE_CALL(setOutputDevice(outputDeviceIndex)); Q_Q(AudioOutput); emit q->outputDeviceChanged(AudioOutputDevice::fromIndex(outputDeviceIndex)); } void AudioOutputPrivate::_k_audioDeviceFailed() { pDebug() << Q_FUNC_INFO; // outputDeviceIndex identifies a failing device // fall back in the preference list of output devices QList<int> deviceList = GlobalConfig().audioOutputDeviceListFor(category); foreach (int devIndex, deviceList) { // if it's the same device as the one that failed, ignore it if (outputDeviceIndex != devIndex) { if (pINTERFACE_CALL(setOutputDevice(devIndex))) { handleAutomaticDeviceChange(devIndex, FallbackChange); break; // found one that works } } } } void AudioOutputPrivate::_k_deviceListChanged() { pDebug() << Q_FUNC_INFO; // let's see if there's a usable device higher in the preference list QList<int> deviceList = GlobalConfig().audioOutputDeviceListFor(category); DeviceChangeType changeType = HigherPreferenceChange; foreach (int devIndex, deviceList) { pDebug() << devIndex; if (outputDeviceIndex == devIndex) { AudioOutputDevice info = AudioOutputDevice::fromIndex(devIndex); if (info.property("available").toBool()) { break; // we've reached the currently used device, nothing to change } changeType = FallbackChange; } if (pINTERFACE_CALL(setOutputDevice(devIndex))) { handleAutomaticDeviceChange(devIndex, changeType); break; // found one with higher preference that works } } } void AudioOutputPrivate::handleAutomaticDeviceChange(int newIndex, DeviceChangeType type) { Q_Q(AudioOutput); deviceBeforeFallback = outputDeviceIndex; outputDeviceIndex = newIndex; emit q->outputDeviceChanged(AudioOutputDevice::fromIndex(outputDeviceIndex)); QString text; AudioOutputDevice device1 = AudioOutputDevice::fromIndex(deviceBeforeFallback); AudioOutputDevice device2 = AudioOutputDevice::fromIndex(outputDeviceIndex); switch (type) { case FallbackChange: text = AudioOutput::tr("<html>The audio playback device <b>%1</b> does not work.<br/>" "Falling back to <b>%2</b>.</html>").arg(device1.name()).arg(device2.name()); Platform::notification("AudioDeviceFallback", text); break; case HigherPreferenceChange: text = AudioOutput::tr("<html>Switching to the audio playback device <b>%1</b><br/>" "which just became available and has higher preference.</html>").arg(device2.name()); Platform::notification("AudioDeviceFallback", text, QStringList(AudioOutput::tr("Revert back to device '%1'").arg(device1.name())), q, SLOT(_k_revertFallback())); break; } } } //namespace Phonon #include "moc_audiooutput.cpp" #undef PHONON_CLASSNAME #undef PHONON_INTERFACENAME // vim: sw=4 ts=4 tw=100 et <|endoftext|>
<commit_before>/* * csdebugger.cpp: Copyright (C) 2014 Andres Cabrera, Rory Walsh This file is part of Csound. The Csound 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. Csound 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 Csound; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Simple Debugging Application ---------------------------- Simple command line debugger using Andres new csdebugger branch Usage: csdebugger [filename.csd] [instrument number] [ksmps offset] filename.csd = csd file to run with debugger instrument number = instrument to debug ksmps offset] = number of k-cycle before breakpoint is hit */ #include <stdio.h> #include "csound.hpp" #include "csdebug.h" #include <iostream> #include <iomanip> using namespace std; void brkpt_cb(CSOUND *csound, debug_bkpt_info_t *bkpt_info, void *userdata); int main(int argc, char *argv[]) { if (argc == 1) { cout << "Usage:" << endl; cout << argv[0] << " [filename.csd] [instrument number] [ksmps offset]" << endl; return -1; } int ksmpsOffset = atoi(argv[3]); Csound* csound = new Csound(); csound->Compile(2,argv); csound->Start(); csoundDebuggerInit(csound->GetCsound()); csoundSetBreakpointCallback(csound->GetCsound(), brkpt_cb, NULL); cout << "Csound filename: " << argv[1] << '\n'; cout << "Instr number:" << argv[2] << '\n'; csoundSetInstrumentBreakpoint(csound->GetCsound(), 1.1, ksmpsOffset); csound->Perform(); csoundDebuggerClean(csound->GetCsound()); delete csound; } void brkpt_cb(CSOUND *csound, debug_bkpt_info_t *bkpt_info, void *userdata) { cout << "\nBreakpoint at instr " << bkpt_info->breakpointInstr->p1 << "\nNumber of k-cycles into performance: " << bkpt_info->breakpointInstr->kcounter << "\n------------------------------------------------------"; // debug_instr_t *debug_instr = bkpt_info.breakpointInstr; debug_variable_t *vp = bkpt_info->instrVarList; while (vp) { cout << " \n"; if (vp->name[0] != '#') { cout << "VarName:"<< vp->name << "\t";; if (strcmp(vp->typeName, "i") == 0 || strcmp(vp->typeName, "k") == 0) { cout << "value = " << *((MYFLT *) vp->data) << "\t";; } else if(strcmp(vp->typeName, "S") == 0) { cout << "value = " << (char *) vp->data << "\t\t"; } else if (strcmp(vp->typeName, "a") == 0) { MYFLT *data = (MYFLT *) vp->data; cout << "value[0] = "<< data[0] << "\t"; } else { cout << "Unknown type\t"; } cout << " varType[" << vp->typeName << "]"; } vp = vp->next; } } <commit_msg>Set debugger instrument breakpoint from command line for csdebugger application<commit_after>/* * csdebugger.cpp: Copyright (C) 2014 Andres Cabrera, Rory Walsh This file is part of Csound. The Csound 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. Csound 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 Csound; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Simple Debugging Application ---------------------------- Simple command line debugger using Andres new csdebugger branch Usage: csdebugger [filename.csd] [instrument number] [ksmps offset] filename.csd = csd file to run with debugger instrument number = instrument to debug ksmps offset] = number of k-cycle before breakpoint is hit */ #include <stdio.h> #include "csound.hpp" #include "csdebug.h" #include <iostream> #include <iomanip> using namespace std; void brkpt_cb(CSOUND *csound, debug_bkpt_info_t *bkpt_info, void *userdata); int main(int argc, char *argv[]) { if (argc == 1) { cout << "Usage:" << endl; cout << argv[0] << " [filename.csd] [instrument number] [ksmps offset]" << endl; return -1; } int ksmpsOffset = atoi(argv[3]); Csound* csound = new Csound(); csound->Compile(2,argv); csound->Start(); csoundDebuggerInit(csound->GetCsound()); csoundSetBreakpointCallback(csound->GetCsound(), brkpt_cb, NULL); cout << "Csound filename: " << argv[1] << '\n'; cout << "Instr number:" << argv[2] << '\n'; double instr = atof(argv[2]); if (instr >= 1.0) { csoundSetInstrumentBreakpoint(csound->GetCsound(), instr, ksmpsOffset); } else { cout << "Invalid instrument breakpoint: " << instr; } csound->Perform(); csoundDebuggerClean(csound->GetCsound()); delete csound; } void brkpt_cb(CSOUND *csound, debug_bkpt_info_t *bkpt_info, void *userdata) { cout << "\nBreakpoint at instr " << bkpt_info->breakpointInstr->p1 << "\nNumber of k-cycles into performance: " << bkpt_info->breakpointInstr->kcounter << "\n------------------------------------------------------"; // debug_instr_t *debug_instr = bkpt_info.breakpointInstr; debug_variable_t *vp = bkpt_info->instrVarList; while (vp) { cout << " \n"; if (vp->name[0] != '#') { cout << "VarName:"<< vp->name << "\t";; if (strcmp(vp->typeName, "i") == 0 || strcmp(vp->typeName, "k") == 0) { cout << "value = " << *((MYFLT *) vp->data) << "\t";; } else if(strcmp(vp->typeName, "S") == 0) { cout << "value = " << (char *) vp->data << "\t\t"; } else if (strcmp(vp->typeName, "a") == 0) { MYFLT *data = (MYFLT *) vp->data; cout << "value[0] = "<< data[0] << "\t"; } else { cout << "Unknown type\t"; } cout << " varType[" << vp->typeName << "]"; } vp = vp->next; } } <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2015 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <iostream> #include <cstdlib> #include <cstdio> #include <cstring> #include <sys/socket.h> #include <sys/un.h> #include <unistd.h> #include <signal.h> #include "RCSwitch.h" namespace { const std::size_t UNIX_PATH_MAX = 108; const std::size_t gpio_pin = 2; const std::size_t buffer_size = 4096; // Configuration (this should be in a configuration file) const char* server_socket_path = "/tmp/asgard_socket"; const char* client_socket_path = "/tmp/asgard_rf_socket"; //Buffers char write_buffer[buffer_size + 1]; char receive_buffer[buffer_size + 1]; // The socket file descriptor int socket_fd; // The socket addresses struct sockaddr_un client_address; struct sockaddr_un server_address; // The remote IDs int source_id = -1; int temperature_sensor_id = -1; int humidity_sensor_id = -1; int button_actuator_id = -1; void stop(){ std::cout << "asgard:rf: stop the driver" << std::endl; // Unregister the temperature sensor, if necessary if(temperature_sensor_id >= 0){ auto nbytes = snprintf(write_buffer, buffer_size, "UNREG_SENSOR %d %d", source_id, temperature_sensor_id); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); } // Unregister the humidity sensor, if necessary if(temperature_sensor_id >= 0){ auto nbytes = snprintf(write_buffer, buffer_size, "UNREG_SENSOR %d %d", source_id, humidity_sensor_id); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); } // Unregister the button actuator, if necessary if(temperature_sensor_id >= 0){ auto nbytes = snprintf(write_buffer, buffer_size, "UNREG_ACTUATOR %d %d", source_id, button_actuator_id); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); } // Unregister the source, if necessary if(source_id >= 0){ auto nbytes = snprintf(write_buffer, buffer_size, "UNREG_SOURCE %d", source_id); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); } // Unlink the client socket unlink(client_socket_path); // Close the socket close(socket_fd); } void terminate(int){ stop(); std::exit(0); } bool revoke_root(){ if (getuid() == 0) { if (setgid(1000) != 0){ std::cout << "asgard:rf: setgid: Unable to drop group privileges: " << strerror(errno) << std::endl; return false; } if (setuid(1000) != 0){ std::cout << "asgard:rf: setgid: Unable to drop user privileges: " << strerror(errno) << std::endl; return false; } } if (setuid(0) != -1){ std::cout << "asgard:rf: managed to regain root privileges, exiting..." << std::endl; return false; } return true; } void decode_wt450(unsigned long data){ int house=(data>>28) & (0x0f); byte station=((data>>26) & (0x03))+1; int humidity=(data>>16)&(0xff); double temperature=((data>>8) & (0xff)); temperature = temperature - 50; byte tempfraction=(data>>4) & (0x0f); double tempdecimal=((tempfraction>>3 & 1) * 0.5) + ((tempfraction>>2 & 1) * 0.25) + ((tempfraction>>1 & 1) * 0.125) + ((tempfraction & 1) * 0.0625); temperature=temperature+tempdecimal; temperature=(int)(temperature*10); temperature=temperature/10; //Note: House and station can be used to distinguish between different weather stations (void) house; (void) station; //Send the humidity to the server auto nbytes = snprintf(write_buffer, buffer_size, "DATA %d %d %d", source_id, humidity_sensor_id, humidity); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); //Send the temperature to the server nbytes = snprintf(write_buffer, buffer_size, "DATA %d %d %f", source_id, temperature_sensor_id, temperature); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); } void read_data(RCSwitch& rc_switch){ if (rc_switch.available()) { int value = rc_switch.getReceivedValue(); if (value) { if((rc_switch.getReceivedProtocol() == 1 || rc_switch.getReceivedProtocol() == 2) && rc_switch.getReceivedValue() == 1135920){ //Send the event to the server auto nbytes = snprintf(write_buffer, buffer_size, "EVENT %d %d %d", source_id, button_actuator_id, 1); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); } else if(rc_switch.getReceivedProtocol() == 5){ unsigned long value = rc_switch.getReceivedValue(); decode_wt450(value); } else { printf("asgard:rf:received unknown value: %lu\n", rc_switch.getReceivedValue()); printf("asgard:rf:received unknown protocol: %i\n", rc_switch.getReceivedProtocol()); } } else { printf("asgard:rf:received unknown encoding\n"); } rc_switch.resetAvailable(); } } } //end of anonymous namespace int main(){ RCSwitch rc_switch; //Run the wiringPi setup (as root) wiringPiSetup(); rc_switch = RCSwitch(); rc_switch.enableReceive(gpio_pin); //Drop root privileges and run as pi:pi again if(!revoke_root()){ std::cout << "asgard:rf: unable to revoke root privileges, exiting..." << std::endl; return 1; } // Open the socket socket_fd = socket(AF_UNIX, SOCK_DGRAM, 0); if(socket_fd < 0){ std::cerr << "asgard:rf: socket() failed" << std::endl; return 1; } // Init the client address memset(&client_address, 0, sizeof(struct sockaddr_un)); client_address.sun_family = AF_UNIX; snprintf(client_address.sun_path, UNIX_PATH_MAX, client_socket_path); // Unlink the client socket unlink(client_socket_path); // Bind to client socket if(bind(socket_fd, (const struct sockaddr *) &client_address, sizeof(struct sockaddr_un)) < 0){ std::cerr << "asgard:rf: bind() failed" << std::endl; return 1; } //Register signals for "proper" shutdown signal(SIGTERM, terminate); signal(SIGINT, terminate); // Init the server address memset(&server_address, 0, sizeof(struct sockaddr_un)); server_address.sun_family = AF_UNIX; snprintf(server_address.sun_path, UNIX_PATH_MAX, server_socket_path); socklen_t address_length = sizeof(struct sockaddr_un); // Register the source auto nbytes = snprintf(write_buffer, buffer_size, "REG_SOURCE rf"); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); auto bytes_received = recvfrom(socket_fd, receive_buffer, buffer_size, 0, (struct sockaddr *) &(server_address), &address_length); receive_buffer[bytes_received] = '\0'; source_id = atoi(receive_buffer); std::cout << "asgard:rf: remote source: " << source_id << std::endl; // Register the temperature sensor nbytes = snprintf(write_buffer, buffer_size, "REG_SENSOR %d %s %s", source_id, "TEMPERATURE", "rf_weather"); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); bytes_received = recvfrom(socket_fd, receive_buffer, buffer_size, 0, (struct sockaddr *) &(server_address), &address_length); receive_buffer[bytes_received] = '\0'; temperature_sensor_id = atoi(receive_buffer); std::cout << "asgard:rf: remote temperature sensor: " << temperature_sensor_id << std::endl; // Register the humidity sensor nbytes = snprintf(write_buffer, buffer_size, "REG_SENSOR %d %s %s", source_id, "HUMIDITY", "rf_weather"); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); bytes_received = recvfrom(socket_fd, receive_buffer, buffer_size, 0, (struct sockaddr *) &(server_address), &address_length); receive_buffer[bytes_received] = '\0'; humidity_sensor_id = atoi(receive_buffer); std::cout << "asgard:rf: remote humidity sensor: " << temperature_sensor_id << std::endl; // Register the button actuator nbytes = snprintf(write_buffer, buffer_size, "REG_ACTUATOR %d %s", source_id, "rf_button_1"); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); bytes_received = recvfrom(socket_fd, receive_buffer, buffer_size, 0, (struct sockaddr *) &(server_address), &address_length); receive_buffer[bytes_received] = '\0'; button_actuator_id = atoi(receive_buffer); std::cout << "asgard:rf: remote button actuator: " << button_actuator_id << std::endl; //wait for events while(true) { read_data(rc_switch); //wait for 10 time units delay(10); } stop(); return 0; } <commit_msg>Fix the tests for the unregister<commit_after>//======================================================================= // Copyright (c) 2015 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <iostream> #include <cstdlib> #include <cstdio> #include <cstring> #include <sys/socket.h> #include <sys/un.h> #include <unistd.h> #include <signal.h> #include "RCSwitch.h" namespace { const std::size_t UNIX_PATH_MAX = 108; const std::size_t gpio_pin = 2; const std::size_t buffer_size = 4096; // Configuration (this should be in a configuration file) const char* server_socket_path = "/tmp/asgard_socket"; const char* client_socket_path = "/tmp/asgard_rf_socket"; //Buffers char write_buffer[buffer_size + 1]; char receive_buffer[buffer_size + 1]; // The socket file descriptor int socket_fd; // The socket addresses struct sockaddr_un client_address; struct sockaddr_un server_address; // The remote IDs int source_id = -1; int temperature_sensor_id = -1; int humidity_sensor_id = -1; int button_actuator_id = -1; void stop(){ std::cout << "asgard:rf: stop the driver" << std::endl; // Unregister the temperature sensor, if necessary if(temperature_sensor_id >= 0){ auto nbytes = snprintf(write_buffer, buffer_size, "UNREG_SENSOR %d %d", source_id, temperature_sensor_id); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); } // Unregister the humidity sensor, if necessary if(humidity_sensor_id >= 0){ auto nbytes = snprintf(write_buffer, buffer_size, "UNREG_SENSOR %d %d", source_id, humidity_sensor_id); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); } // Unregister the button actuator, if necessary if(button_actuator_id >= 0){ auto nbytes = snprintf(write_buffer, buffer_size, "UNREG_ACTUATOR %d %d", source_id, button_actuator_id); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); } // Unregister the source, if necessary if(source_id >= 0){ auto nbytes = snprintf(write_buffer, buffer_size, "UNREG_SOURCE %d", source_id); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); } // Unlink the client socket unlink(client_socket_path); // Close the socket close(socket_fd); } void terminate(int){ stop(); std::exit(0); } bool revoke_root(){ if (getuid() == 0) { if (setgid(1000) != 0){ std::cout << "asgard:rf: setgid: Unable to drop group privileges: " << strerror(errno) << std::endl; return false; } if (setuid(1000) != 0){ std::cout << "asgard:rf: setgid: Unable to drop user privileges: " << strerror(errno) << std::endl; return false; } } if (setuid(0) != -1){ std::cout << "asgard:rf: managed to regain root privileges, exiting..." << std::endl; return false; } return true; } void decode_wt450(unsigned long data){ int house=(data>>28) & (0x0f); byte station=((data>>26) & (0x03))+1; int humidity=(data>>16)&(0xff); double temperature=((data>>8) & (0xff)); temperature = temperature - 50; byte tempfraction=(data>>4) & (0x0f); double tempdecimal=((tempfraction>>3 & 1) * 0.5) + ((tempfraction>>2 & 1) * 0.25) + ((tempfraction>>1 & 1) * 0.125) + ((tempfraction & 1) * 0.0625); temperature=temperature+tempdecimal; temperature=(int)(temperature*10); temperature=temperature/10; //Note: House and station can be used to distinguish between different weather stations (void) house; (void) station; //Send the humidity to the server auto nbytes = snprintf(write_buffer, buffer_size, "DATA %d %d %d", source_id, humidity_sensor_id, humidity); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); //Send the temperature to the server nbytes = snprintf(write_buffer, buffer_size, "DATA %d %d %f", source_id, temperature_sensor_id, temperature); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); } void read_data(RCSwitch& rc_switch){ if (rc_switch.available()) { int value = rc_switch.getReceivedValue(); if (value) { if((rc_switch.getReceivedProtocol() == 1 || rc_switch.getReceivedProtocol() == 2) && rc_switch.getReceivedValue() == 1135920){ //Send the event to the server auto nbytes = snprintf(write_buffer, buffer_size, "EVENT %d %d %d", source_id, button_actuator_id, 1); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); } else if(rc_switch.getReceivedProtocol() == 5){ unsigned long value = rc_switch.getReceivedValue(); decode_wt450(value); } else { printf("asgard:rf:received unknown value: %lu\n", rc_switch.getReceivedValue()); printf("asgard:rf:received unknown protocol: %i\n", rc_switch.getReceivedProtocol()); } } else { printf("asgard:rf:received unknown encoding\n"); } rc_switch.resetAvailable(); } } } //end of anonymous namespace int main(){ RCSwitch rc_switch; //Run the wiringPi setup (as root) wiringPiSetup(); rc_switch = RCSwitch(); rc_switch.enableReceive(gpio_pin); //Drop root privileges and run as pi:pi again if(!revoke_root()){ std::cout << "asgard:rf: unable to revoke root privileges, exiting..." << std::endl; return 1; } // Open the socket socket_fd = socket(AF_UNIX, SOCK_DGRAM, 0); if(socket_fd < 0){ std::cerr << "asgard:rf: socket() failed" << std::endl; return 1; } // Init the client address memset(&client_address, 0, sizeof(struct sockaddr_un)); client_address.sun_family = AF_UNIX; snprintf(client_address.sun_path, UNIX_PATH_MAX, client_socket_path); // Unlink the client socket unlink(client_socket_path); // Bind to client socket if(bind(socket_fd, (const struct sockaddr *) &client_address, sizeof(struct sockaddr_un)) < 0){ std::cerr << "asgard:rf: bind() failed" << std::endl; return 1; } //Register signals for "proper" shutdown signal(SIGTERM, terminate); signal(SIGINT, terminate); // Init the server address memset(&server_address, 0, sizeof(struct sockaddr_un)); server_address.sun_family = AF_UNIX; snprintf(server_address.sun_path, UNIX_PATH_MAX, server_socket_path); socklen_t address_length = sizeof(struct sockaddr_un); // Register the source auto nbytes = snprintf(write_buffer, buffer_size, "REG_SOURCE rf"); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); auto bytes_received = recvfrom(socket_fd, receive_buffer, buffer_size, 0, (struct sockaddr *) &(server_address), &address_length); receive_buffer[bytes_received] = '\0'; source_id = atoi(receive_buffer); std::cout << "asgard:rf: remote source: " << source_id << std::endl; // Register the temperature sensor nbytes = snprintf(write_buffer, buffer_size, "REG_SENSOR %d %s %s", source_id, "TEMPERATURE", "rf_weather"); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); bytes_received = recvfrom(socket_fd, receive_buffer, buffer_size, 0, (struct sockaddr *) &(server_address), &address_length); receive_buffer[bytes_received] = '\0'; temperature_sensor_id = atoi(receive_buffer); std::cout << "asgard:rf: remote temperature sensor: " << temperature_sensor_id << std::endl; // Register the humidity sensor nbytes = snprintf(write_buffer, buffer_size, "REG_SENSOR %d %s %s", source_id, "HUMIDITY", "rf_weather"); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); bytes_received = recvfrom(socket_fd, receive_buffer, buffer_size, 0, (struct sockaddr *) &(server_address), &address_length); receive_buffer[bytes_received] = '\0'; humidity_sensor_id = atoi(receive_buffer); std::cout << "asgard:rf: remote humidity sensor: " << temperature_sensor_id << std::endl; // Register the button actuator nbytes = snprintf(write_buffer, buffer_size, "REG_ACTUATOR %d %s", source_id, "rf_button_1"); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); bytes_received = recvfrom(socket_fd, receive_buffer, buffer_size, 0, (struct sockaddr *) &(server_address), &address_length); receive_buffer[bytes_received] = '\0'; button_actuator_id = atoi(receive_buffer); std::cout << "asgard:rf: remote button actuator: " << button_actuator_id << std::endl; //wait for events while(true) { read_data(rc_switch); //wait for 10 time units delay(10); } stop(); return 0; } <|endoftext|>
<commit_before>/* * Copyright (C) 2015-2018 Dubalu LLC. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "replication.h" #ifdef XAPIAND_CLUSTERING #include "database_handler.h" #include "fs.hh" // for delete_files #include "io.hh" #include "length.h" #include "server/binary_client.h" // #undef L_DEBUG // #define L_DEBUG L_GREY // #undef L_CALL // #define L_CALL L_STACKED_DIM_GREY // #undef L_REPLICATION // #define L_REPLICATION L_RED // #undef L_CONN // #define L_CONN L_GREEN // #undef L_BINARY_WIRE // #define L_BINARY_WIRE L_ORANGE // #undef L_BINARY // #define L_BINARY L_TEAL // #undef L_BINARY_PROTO // #define L_BINARY_PROTO L_TEAL /* ____ _ _ _ _ * | _ \ ___ _ __ | (_) ___ __ _| |_(_) ___ _ __ * | |_) / _ \ '_ \| | |/ __/ _` | __| |/ _ \| '_ \ * | _ < __/ |_) | | | (_| (_| | |_| | (_) | | | | * |_| \_\___| .__/|_|_|\___\__,_|\__|_|\___/|_| |_| * |_| */ using dispatch_func = void (Replication::*)(const std::string&); Replication::Replication(BinaryClient& client_) : LockableDatabase(), client(client_) { L_OBJ("CREATED REPLICATION OBJ!"); } Replication::~Replication() { if (!switch_database_path.empty()) { if (slave_database) { slave_database->close(); XapiandManager::manager->database_pool.checkin(slave_database); } delete_files(switch_database_path.c_str()); } else { if (slave_database) { XapiandManager::manager->database_pool.checkin(slave_database); } } L_OBJ("DELETED REPLICATION OBJ!"); } bool Replication::init_replication(const Endpoint &src_endpoint, const Endpoint &dst_endpoint) { L_CALL("Replication::init_replication(%s, %s)", repr(src_endpoint.to_string()), repr(dst_endpoint.to_string())); src_endpoints = Endpoints{src_endpoint}; endpoints = Endpoints{dst_endpoint}; L_REPLICATION("init_replication: %s --> %s", repr(src_endpoints.to_string()), repr(endpoints.to_string())); client.temp_directory_template = endpoints[0].path + "/.tmp.XXXXXX"; return true; } void Replication::send_message(ReplicationReplyType type, const std::string& message) { L_CALL("Replication::send_message(%s, <message>)", ReplicationReplyTypeNames(type)); L_BINARY_PROTO("<< send_message (%s): %s", ReplicationReplyTypeNames(type), repr(message)); client.send_message(toUType(type), message); } void Replication::send_file(ReplicationReplyType type, int fd) { L_CALL("Replication::send_file(%s, <fd>)", ReplicationReplyTypeNames(type)); L_BINARY_PROTO("<< send_file (%s): %d", ReplicationReplyTypeNames(type), fd); client.send_file(toUType(type), fd); } void Replication::replication_server(ReplicationMessageType type, const std::string& message) { L_CALL("Replication::replication_server(%s, <message>)", ReplicationMessageTypeNames(type)); static const dispatch_func dispatch[] = { &Replication::msg_get_changesets, }; if (static_cast<size_t>(type) >= sizeof(dispatch) / sizeof(dispatch[0])) { std::string errmsg("Unexpected message type "); errmsg += std::to_string(toUType(type)); THROW(InvalidArgumentError, errmsg); } (this->*(dispatch[static_cast<int>(type)]))(message); } void Replication::msg_get_changesets(const std::string& message) { L_CALL("Replication::msg_get_changesets(<message>)"); L_REPLICATION("Replication::msg_get_changesets"); const char *p = message.c_str(); const char *p_end = p + message.size(); auto remote_uuid = unserialise_string(&p, p_end); auto from_revision = unserialise_length(&p, p_end); endpoints = Endpoints{Endpoint{unserialise_string(&p, p_end)}}; flags = DB_WRITABLE; lock_database lk_db(this); auto uuid = db()->get_uuid(); auto revision = db()->get_revision(); lk_db.unlock(); if (from_revision && uuid != remote_uuid) { from_revision = 0; } // TODO: Implement WAL's has_revision() and iterator // WAL required on a local writable database, open it. wal = std::make_unique<DatabaseWAL>(endpoints[0].path, nullptr); if (from_revision && !wal->has_revision(from_revision).first) { from_revision = 0; } if (from_revision < revision) { if (from_revision == 0) { int whole_db_copies_left = 5; while (true) { // Send the current revision number in the header. send_message(ReplicationReplyType::REPLY_DB_HEADER, serialise_string(uuid) + serialise_length(revision)); static std::array<const std::string, 7> filenames = { "termlist.glass", "synonym.glass", "spelling.glass", "docdata.glass", "position.glass", "postlist.glass", "iamglass" }; for (const auto& filename : filenames) { auto path = endpoints[0].path + "/" + filename; int fd = io::open(path.c_str()); if (fd != -1) { send_message(ReplicationReplyType::REPLY_DB_FILENAME, filename); send_file(ReplicationReplyType::REPLY_DB_FILEDATA, fd); } } lk_db.lock(); auto final_revision = db()->get_revision(); lk_db.unlock(); send_message(ReplicationReplyType::REPLY_DB_FOOTER, serialise_length(final_revision)); if (revision == final_revision) { from_revision = revision; break; } if (whole_db_copies_left == 0) { send_message(ReplicationReplyType::REPLY_FAIL, "Database changing too fast"); return; } else if (--whole_db_copies_left == 0) { lk_db.lock(); uuid = db()->get_uuid(); revision = db()->get_revision(); } else { lk_db.lock(); uuid = db()->get_uuid(); revision = db()->get_revision(); lk_db.unlock(); } } lk_db.unlock(); } // TODO: Implement WAL's has_revision() and iterator int wal_iterations = 5; do { // Send WAL operations. auto wal_it = wal->find(from_revision); for (; wal_it != wal->end(); ++wal_it) { send_message(ReplicationReplyType::REPLY_CHANGESET, wal_it->second); } from_revision = wal_it->first + 1; lk_db.lock(); revision = db()->get_revision(); lk_db.unlock(); } while (from_revision < revision && --wal_iterations != 0); } send_message(ReplicationReplyType::REPLY_END_OF_CHANGES, ""); } void Replication::replication_client(ReplicationReplyType type, const std::string& message) { L_CALL("Replication::replication_client(%s, <message>)", ReplicationReplyTypeNames(type)); static const dispatch_func dispatch[] = { &Replication::reply_welcome, &Replication::reply_end_of_changes, &Replication::reply_fail, &Replication::reply_db_header, &Replication::reply_db_filename, &Replication::reply_db_filedata, &Replication::reply_db_footer, &Replication::reply_changeset, }; if (static_cast<size_t>(type) >= sizeof(dispatch) / sizeof(dispatch[0])) { std::string errmsg("Unexpected message type "); errmsg += std::to_string(toUType(type)); THROW(InvalidArgumentError, errmsg); } (this->*(dispatch[static_cast<int>(type)]))(message); } void Replication::reply_welcome(const std::string&) { std::string message; try { flags = DB_WRITABLE; lock_database lk_db(this); message.append(serialise_string(db()->get_uuid())); message.append(serialise_length(db()->get_revision())); message.append(serialise_string(endpoints[0].path)); } catch (const NotFoundError&) { message.append(serialise_string("")); message.append(serialise_length(0)); message.append(serialise_string(endpoints[0].path)); } send_message(static_cast<ReplicationReplyType>(SWITCH_TO_REPL), message); } void Replication::reply_end_of_changes(const std::string&) { L_CALL("Replication::reply_end_of_changes(<message>)"); L_REPLICATION("Replication::reply_end_of_changes"); if (!switch_database_path.empty()) { if (slave_database) { slave_database->close(); XapiandManager::manager->database_pool.checkin(slave_database); } XapiandManager::manager->database_pool.switch_db(switch_database_path, endpoints[0].path); } else { if (slave_database) { XapiandManager::manager->database_pool.checkin(slave_database); } } client.destroy(); client.detach(); } void Replication::reply_fail(const std::string&) { L_CALL("Replication::reply_fail(<message>)"); L_REPLICATION("Replication::reply_fail"); L_ERR("Replication failure!"); client.destroy(); client.detach(); } void Replication::reply_db_header(const std::string& message) { L_CALL("Replication::reply_db_header(<message>)"); L_REPLICATION("Replication::reply_db_header"); const char *p = message.data(); const char *p_end = p + message.size(); current_uuid = unserialise_string(&p, p_end); current_revision = unserialise_length(&p, p_end); assert(switch_database_path.empty()); char path[PATH_MAX]; strncpy(path, temp_directory_template.c_str(), PATH_MAX); if (io::mkdtemp(path) == nullptr) { L_ERR("Directory %s not created: %s (%d): %s", path, io::strerrno(errno), errno, strerror(errno)); client.destroy(); client.detach(); return; } switch_database_path = path; L_REPLICATION("Replication::reply_db_header %s", repr(switch_database_path)); } void Replication::reply_db_filename(const std::string& filename) { L_CALL("Replication::reply_db_filename(<filename>)"); L_REPLICATION("Replication::reply_db_filename"); assert(!switch_database_path.empty()); file_path = switch_database_path + "/" + filename; } void Replication::reply_db_filedata(const std::string& tmp_file) { L_CALL("Replication::reply_db_filedata(<tmp_file>)"); L_REPLICATION("Replication::reply_db_filedata %s -> %s", repr(tmp_file), repr(file_path)); assert(!switch_database_path.empty()); if (::rename(tmp_file.c_str(), file_path.c_str()) == -1) { L_ERR("Cannot rename temporary file %s to %s: %s (%d): %s", tmp_file, file_path, io::strerrno(errno), errno, strerror(errno)); client.destroy(); client.detach(); return; } } void Replication::reply_db_footer(const std::string& message) { L_CALL("Replication::reply_db_footer(<message>)"); L_REPLICATION("Replication::reply_db_footer"); const char *p = message.data(); const char *p_end = p + message.size(); size_t revision = unserialise_length(&p, p_end); assert(!switch_database_path.empty()); if (revision != current_revision) { delete_files(switch_database_path.c_str()); switch_database_path.clear(); } } void Replication::reply_changeset(const std::string& line) { L_CALL("Replication::reply_changeset(<line>)"); L_REPLICATION("Replication::reply_changeset"); if (!slave_database) { if (!switch_database_path.empty()) { XapiandManager::manager->database_pool.checkout(slave_database, Endpoints{Endpoint{switch_database_path}}, DB_WRITABLE | DB_VOLATILE); } else { XapiandManager::manager->database_pool.checkout(slave_database, endpoints, DB_WRITABLE | DB_VOLATILE); } wal = std::make_unique<DatabaseWAL>(slave_database->endpoints[0].path, slave_database.get()); } wal->execute(line, true); } #endif /* XAPIAND_CLUSTERING */ <commit_msg>>>> Replication: Use temporary directory template<commit_after>/* * Copyright (C) 2015-2018 Dubalu LLC. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "replication.h" #ifdef XAPIAND_CLUSTERING #include "database_handler.h" #include "fs.hh" // for delete_files #include "io.hh" #include "length.h" #include "server/binary_client.h" // #undef L_DEBUG // #define L_DEBUG L_GREY // #undef L_CALL // #define L_CALL L_STACKED_DIM_GREY // #undef L_REPLICATION // #define L_REPLICATION L_RED // #undef L_CONN // #define L_CONN L_GREEN // #undef L_BINARY_WIRE // #define L_BINARY_WIRE L_ORANGE // #undef L_BINARY // #define L_BINARY L_TEAL // #undef L_BINARY_PROTO // #define L_BINARY_PROTO L_TEAL /* ____ _ _ _ _ * | _ \ ___ _ __ | (_) ___ __ _| |_(_) ___ _ __ * | |_) / _ \ '_ \| | |/ __/ _` | __| |/ _ \| '_ \ * | _ < __/ |_) | | | (_| (_| | |_| | (_) | | | | * |_| \_\___| .__/|_|_|\___\__,_|\__|_|\___/|_| |_| * |_| */ using dispatch_func = void (Replication::*)(const std::string&); Replication::Replication(BinaryClient& client_) : LockableDatabase(), client(client_) { L_OBJ("CREATED REPLICATION OBJ!"); } Replication::~Replication() { if (!switch_database_path.empty()) { if (slave_database) { slave_database->close(); XapiandManager::manager->database_pool.checkin(slave_database); } delete_files(switch_database_path.c_str()); } else { if (slave_database) { XapiandManager::manager->database_pool.checkin(slave_database); } } L_OBJ("DELETED REPLICATION OBJ!"); } bool Replication::init_replication(const Endpoint &src_endpoint, const Endpoint &dst_endpoint) { L_CALL("Replication::init_replication(%s, %s)", repr(src_endpoint.to_string()), repr(dst_endpoint.to_string())); src_endpoints = Endpoints{src_endpoint}; endpoints = Endpoints{dst_endpoint}; L_REPLICATION("init_replication: %s --> %s", repr(src_endpoints.to_string()), repr(endpoints.to_string())); client.temp_directory_template = endpoints[0].path + "/.tmp.XXXXXX"; return true; } void Replication::send_message(ReplicationReplyType type, const std::string& message) { L_CALL("Replication::send_message(%s, <message>)", ReplicationReplyTypeNames(type)); L_BINARY_PROTO("<< send_message (%s): %s", ReplicationReplyTypeNames(type), repr(message)); client.send_message(toUType(type), message); } void Replication::send_file(ReplicationReplyType type, int fd) { L_CALL("Replication::send_file(%s, <fd>)", ReplicationReplyTypeNames(type)); L_BINARY_PROTO("<< send_file (%s): %d", ReplicationReplyTypeNames(type), fd); client.send_file(toUType(type), fd); } void Replication::replication_server(ReplicationMessageType type, const std::string& message) { L_CALL("Replication::replication_server(%s, <message>)", ReplicationMessageTypeNames(type)); static const dispatch_func dispatch[] = { &Replication::msg_get_changesets, }; if (static_cast<size_t>(type) >= sizeof(dispatch) / sizeof(dispatch[0])) { std::string errmsg("Unexpected message type "); errmsg += std::to_string(toUType(type)); THROW(InvalidArgumentError, errmsg); } (this->*(dispatch[static_cast<int>(type)]))(message); } void Replication::msg_get_changesets(const std::string& message) { L_CALL("Replication::msg_get_changesets(<message>)"); L_REPLICATION("Replication::msg_get_changesets"); const char *p = message.c_str(); const char *p_end = p + message.size(); auto remote_uuid = unserialise_string(&p, p_end); auto from_revision = unserialise_length(&p, p_end); endpoints = Endpoints{Endpoint{unserialise_string(&p, p_end)}}; flags = DB_WRITABLE; lock_database lk_db(this); auto uuid = db()->get_uuid(); auto revision = db()->get_revision(); lk_db.unlock(); if (from_revision && uuid != remote_uuid) { from_revision = 0; } // TODO: Implement WAL's has_revision() and iterator // WAL required on a local writable database, open it. wal = std::make_unique<DatabaseWAL>(endpoints[0].path, nullptr); if (from_revision && !wal->has_revision(from_revision).first) { from_revision = 0; } if (from_revision < revision) { if (from_revision == 0) { int whole_db_copies_left = 5; while (true) { // Send the current revision number in the header. send_message(ReplicationReplyType::REPLY_DB_HEADER, serialise_string(uuid) + serialise_length(revision)); static std::array<const std::string, 7> filenames = { "termlist.glass", "synonym.glass", "spelling.glass", "docdata.glass", "position.glass", "postlist.glass", "iamglass" }; for (const auto& filename : filenames) { auto path = endpoints[0].path + "/" + filename; int fd = io::open(path.c_str()); if (fd != -1) { send_message(ReplicationReplyType::REPLY_DB_FILENAME, filename); send_file(ReplicationReplyType::REPLY_DB_FILEDATA, fd); } } lk_db.lock(); auto final_revision = db()->get_revision(); lk_db.unlock(); send_message(ReplicationReplyType::REPLY_DB_FOOTER, serialise_length(final_revision)); if (revision == final_revision) { from_revision = revision; break; } if (whole_db_copies_left == 0) { send_message(ReplicationReplyType::REPLY_FAIL, "Database changing too fast"); return; } else if (--whole_db_copies_left == 0) { lk_db.lock(); uuid = db()->get_uuid(); revision = db()->get_revision(); } else { lk_db.lock(); uuid = db()->get_uuid(); revision = db()->get_revision(); lk_db.unlock(); } } lk_db.unlock(); } // TODO: Implement WAL's has_revision() and iterator int wal_iterations = 5; do { // Send WAL operations. auto wal_it = wal->find(from_revision); for (; wal_it != wal->end(); ++wal_it) { send_message(ReplicationReplyType::REPLY_CHANGESET, wal_it->second); } from_revision = wal_it->first + 1; lk_db.lock(); revision = db()->get_revision(); lk_db.unlock(); } while (from_revision < revision && --wal_iterations != 0); } send_message(ReplicationReplyType::REPLY_END_OF_CHANGES, ""); } void Replication::replication_client(ReplicationReplyType type, const std::string& message) { L_CALL("Replication::replication_client(%s, <message>)", ReplicationReplyTypeNames(type)); static const dispatch_func dispatch[] = { &Replication::reply_welcome, &Replication::reply_end_of_changes, &Replication::reply_fail, &Replication::reply_db_header, &Replication::reply_db_filename, &Replication::reply_db_filedata, &Replication::reply_db_footer, &Replication::reply_changeset, }; if (static_cast<size_t>(type) >= sizeof(dispatch) / sizeof(dispatch[0])) { std::string errmsg("Unexpected message type "); errmsg += std::to_string(toUType(type)); THROW(InvalidArgumentError, errmsg); } (this->*(dispatch[static_cast<int>(type)]))(message); } void Replication::reply_welcome(const std::string&) { std::string message; try { flags = DB_WRITABLE; lock_database lk_db(this); message.append(serialise_string(db()->get_uuid())); message.append(serialise_length(db()->get_revision())); message.append(serialise_string(endpoints[0].path)); } catch (const NotFoundError&) { message.append(serialise_string("")); message.append(serialise_length(0)); message.append(serialise_string(endpoints[0].path)); } send_message(static_cast<ReplicationReplyType>(SWITCH_TO_REPL), message); } void Replication::reply_end_of_changes(const std::string&) { L_CALL("Replication::reply_end_of_changes(<message>)"); L_REPLICATION("Replication::reply_end_of_changes"); if (!switch_database_path.empty()) { if (slave_database) { slave_database->close(); XapiandManager::manager->database_pool.checkin(slave_database); } XapiandManager::manager->database_pool.switch_db(switch_database_path, endpoints[0].path); } else { if (slave_database) { XapiandManager::manager->database_pool.checkin(slave_database); } } client.destroy(); client.detach(); } void Replication::reply_fail(const std::string&) { L_CALL("Replication::reply_fail(<message>)"); L_REPLICATION("Replication::reply_fail"); L_ERR("Replication failure!"); client.destroy(); client.detach(); } void Replication::reply_db_header(const std::string& message) { L_CALL("Replication::reply_db_header(<message>)"); L_REPLICATION("Replication::reply_db_header"); const char *p = message.data(); const char *p_end = p + message.size(); current_uuid = unserialise_string(&p, p_end); current_revision = unserialise_length(&p, p_end); assert(switch_database_path.empty()); char path[PATH_MAX]; strncpy(path, client.temp_directory_template.c_str(), PATH_MAX); if (io::mkdtemp(path) == nullptr) { L_ERR("Directory %s not created: %s (%d): %s", path, io::strerrno(errno), errno, strerror(errno)); client.destroy(); client.detach(); return; } switch_database_path = path; L_REPLICATION("Replication::reply_db_header %s", repr(switch_database_path)); } void Replication::reply_db_filename(const std::string& filename) { L_CALL("Replication::reply_db_filename(<filename>)"); L_REPLICATION("Replication::reply_db_filename"); assert(!switch_database_path.empty()); file_path = switch_database_path + "/" + filename; } void Replication::reply_db_filedata(const std::string& tmp_file) { L_CALL("Replication::reply_db_filedata(<tmp_file>)"); L_REPLICATION("Replication::reply_db_filedata %s -> %s", repr(tmp_file), repr(file_path)); assert(!switch_database_path.empty()); if (::rename(tmp_file.c_str(), file_path.c_str()) == -1) { L_ERR("Cannot rename temporary file %s to %s: %s (%d): %s", tmp_file, file_path, io::strerrno(errno), errno, strerror(errno)); client.destroy(); client.detach(); return; } } void Replication::reply_db_footer(const std::string& message) { L_CALL("Replication::reply_db_footer(<message>)"); L_REPLICATION("Replication::reply_db_footer"); const char *p = message.data(); const char *p_end = p + message.size(); size_t revision = unserialise_length(&p, p_end); assert(!switch_database_path.empty()); if (revision != current_revision) { delete_files(switch_database_path.c_str()); switch_database_path.clear(); } } void Replication::reply_changeset(const std::string& line) { L_CALL("Replication::reply_changeset(<line>)"); L_REPLICATION("Replication::reply_changeset"); if (!slave_database) { if (!switch_database_path.empty()) { XapiandManager::manager->database_pool.checkout(slave_database, Endpoints{Endpoint{switch_database_path}}, DB_WRITABLE | DB_VOLATILE); } else { XapiandManager::manager->database_pool.checkout(slave_database, endpoints, DB_WRITABLE | DB_VOLATILE); } wal = std::make_unique<DatabaseWAL>(slave_database->endpoints[0].path, slave_database.get()); } wal->execute(line, true); } #endif /* XAPIAND_CLUSTERING */ <|endoftext|>
<commit_before>/* * FFissionCodec.cpp * Copyright (c) 2006 David Conrad * * This file is part of Perian. * * 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ extern "C" { #include "avcodec.h" } #include "FFissionCodec.h" extern "C" void init_FFmpeg(); FFissionCodec::FFissionCodec(UInt32 inInputBufferByteSize) : ACSimpleCodec(inInputBufferByteSize) { init_FFmpeg(); avContext = avcodec_alloc_context(); avCodec = NULL; } FFissionCodec::~FFissionCodec() { if (avContext) { if (avCodec) { avcodec_close(avContext); } av_free(avContext); } } void FFissionCodec::Initialize(const AudioStreamBasicDescription* inInputFormat, const AudioStreamBasicDescription* inOutputFormat, const void* inMagicCookie, UInt32 inMagicCookieByteSize) { // use the given arguments, if necessary if (inInputFormat != NULL) { SetCurrentInputFormat(*inInputFormat); } if (inOutputFormat != NULL) { SetCurrentOutputFormat(*inOutputFormat); } // make sure the sample rate and number of channels match between the input format and the output format if ((mInputFormat.mSampleRate != mOutputFormat.mSampleRate) || (mInputFormat.mChannelsPerFrame != mOutputFormat.mChannelsPerFrame)) { CODEC_THROW(kAudioCodecUnsupportedFormatError); } ACSimpleCodec::Initialize(inInputFormat, inOutputFormat, inMagicCookie, inMagicCookieByteSize); } void FFissionCodec::GetPropertyInfo(AudioCodecPropertyID inPropertyID, UInt32& outPropertyDataSize, bool& outWritable) { switch(inPropertyID) { case kAudioCodecPropertyMaximumPacketByteSize: outPropertyDataSize = sizeof(UInt32); outWritable = false; break; case kAudioCodecPropertyHasVariablePacketByteSizes: outPropertyDataSize = sizeof(UInt32); outWritable = false; break; case kAudioCodecPropertyPacketFrameSize: outPropertyDataSize = sizeof(UInt32); outWritable = false; break; default: ACSimpleCodec::GetPropertyInfo(inPropertyID, outPropertyDataSize, outWritable); break; } } void FFissionCodec::GetProperty(AudioCodecPropertyID inPropertyID, UInt32& ioPropertyDataSize, void* outPropertyData) { switch(inPropertyID) { case kAudioCodecPropertyManufacturerCFString: if (ioPropertyDataSize != sizeof(CFStringRef)) CODEC_THROW(kAudioCodecBadPropertySizeError); break; case kAudioCodecPropertyMaximumPacketByteSize: case kAudioCodecPropertyRequiresPacketDescription: case kAudioCodecPropertyHasVariablePacketByteSizes: case kAudioCodecPropertyPacketFrameSize: if(ioPropertyDataSize != sizeof(UInt32)) CODEC_THROW(kAudioCodecBadPropertySizeError); break; } switch (inPropertyID) { case kAudioCodecPropertyManufacturerCFString: *(CFStringRef*)outPropertyData = CFCopyLocalizedStringFromTableInBundle(CFSTR("Perian Project"), CFSTR("CodecNames"), GetCodecBundle(), CFSTR("")); break; case kAudioCodecPropertyMaximumPacketByteSize: if (avContext) *reinterpret_cast<UInt32*>(outPropertyData) = avContext->block_align; else *reinterpret_cast<UInt32*>(outPropertyData) = mInputFormat.mBytesPerPacket; break; case kAudioCodecPropertyRequiresPacketDescription: *reinterpret_cast<UInt32*>(outPropertyData) = false; break; case kAudioCodecPropertyHasVariablePacketByteSizes: *reinterpret_cast<UInt32*>(outPropertyData) = false; break; case kAudioCodecPropertyPacketFrameSize: if (avContext && avContext->frame_size) *reinterpret_cast<UInt32*>(outPropertyData) = avContext->frame_size; else if (mInputFormat.mFramesPerPacket) *reinterpret_cast<UInt32*>(outPropertyData) = mInputFormat.mFramesPerPacket; else *reinterpret_cast<UInt32*>(outPropertyData) = 1; break; default: ACSimpleCodec::GetProperty(inPropertyID, ioPropertyDataSize, outPropertyData); } } <commit_msg>FFusion: Make the block_align condition match frame_size<commit_after>/* * FFissionCodec.cpp * Copyright (c) 2006 David Conrad * * This file is part of Perian. * * 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ extern "C" { #include "avcodec.h" } #include "FFissionCodec.h" extern "C" void init_FFmpeg(); FFissionCodec::FFissionCodec(UInt32 inInputBufferByteSize) : ACSimpleCodec(inInputBufferByteSize) { init_FFmpeg(); avContext = avcodec_alloc_context(); avCodec = NULL; } FFissionCodec::~FFissionCodec() { if (avContext) { if (avCodec) { avcodec_close(avContext); } av_free(avContext); } } void FFissionCodec::Initialize(const AudioStreamBasicDescription* inInputFormat, const AudioStreamBasicDescription* inOutputFormat, const void* inMagicCookie, UInt32 inMagicCookieByteSize) { // use the given arguments, if necessary if (inInputFormat != NULL) { SetCurrentInputFormat(*inInputFormat); } if (inOutputFormat != NULL) { SetCurrentOutputFormat(*inOutputFormat); } // make sure the sample rate and number of channels match between the input format and the output format if ((mInputFormat.mSampleRate != mOutputFormat.mSampleRate) || (mInputFormat.mChannelsPerFrame != mOutputFormat.mChannelsPerFrame)) { CODEC_THROW(kAudioCodecUnsupportedFormatError); } ACSimpleCodec::Initialize(inInputFormat, inOutputFormat, inMagicCookie, inMagicCookieByteSize); } void FFissionCodec::GetPropertyInfo(AudioCodecPropertyID inPropertyID, UInt32& outPropertyDataSize, bool& outWritable) { switch(inPropertyID) { case kAudioCodecPropertyMaximumPacketByteSize: outPropertyDataSize = sizeof(UInt32); outWritable = false; break; case kAudioCodecPropertyHasVariablePacketByteSizes: outPropertyDataSize = sizeof(UInt32); outWritable = false; break; case kAudioCodecPropertyPacketFrameSize: outPropertyDataSize = sizeof(UInt32); outWritable = false; break; default: ACSimpleCodec::GetPropertyInfo(inPropertyID, outPropertyDataSize, outWritable); break; } } void FFissionCodec::GetProperty(AudioCodecPropertyID inPropertyID, UInt32& ioPropertyDataSize, void* outPropertyData) { switch(inPropertyID) { case kAudioCodecPropertyManufacturerCFString: if (ioPropertyDataSize != sizeof(CFStringRef)) CODEC_THROW(kAudioCodecBadPropertySizeError); break; case kAudioCodecPropertyMaximumPacketByteSize: case kAudioCodecPropertyRequiresPacketDescription: case kAudioCodecPropertyHasVariablePacketByteSizes: case kAudioCodecPropertyPacketFrameSize: if(ioPropertyDataSize != sizeof(UInt32)) CODEC_THROW(kAudioCodecBadPropertySizeError); break; } switch (inPropertyID) { case kAudioCodecPropertyManufacturerCFString: *(CFStringRef*)outPropertyData = CFCopyLocalizedStringFromTableInBundle(CFSTR("Perian Project"), CFSTR("CodecNames"), GetCodecBundle(), CFSTR("")); break; case kAudioCodecPropertyMaximumPacketByteSize: if (avContext && avContext->block_align) *reinterpret_cast<UInt32*>(outPropertyData) = avContext->block_align; else *reinterpret_cast<UInt32*>(outPropertyData) = mInputFormat.mBytesPerPacket; break; case kAudioCodecPropertyRequiresPacketDescription: *reinterpret_cast<UInt32*>(outPropertyData) = false; break; case kAudioCodecPropertyHasVariablePacketByteSizes: *reinterpret_cast<UInt32*>(outPropertyData) = false; break; case kAudioCodecPropertyPacketFrameSize: if (avContext && avContext->frame_size) *reinterpret_cast<UInt32*>(outPropertyData) = avContext->frame_size; else if (mInputFormat.mFramesPerPacket) *reinterpret_cast<UInt32*>(outPropertyData) = mInputFormat.mFramesPerPacket; else *reinterpret_cast<UInt32*>(outPropertyData) = 1; break; default: ACSimpleCodec::GetProperty(inPropertyID, ioPropertyDataSize, outPropertyData); } } <|endoftext|>
<commit_before>/* * Copyright (C) 2016 Rhys Ulerich * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef DESCENDU_HEXMAP_H #define DESCENDU_HEXMAP_H #include <deque> #include <functional> #include <limits> #include <unordered_map> #include <utility> #include <stdexcept> #include "hex.hpp" #include "optional.hpp" namespace descendu { template <class MappedType> class hexmap : std::unordered_map<hex<int,spec::absolute>,MappedType> { typedef std::unordered_map<hex<int,spec::absolute>,MappedType> base_type; public: // Deliberately no base_type::size as removal of "dead" tiles TBD using typename base_type::const_iterator; using typename base_type::iterator; using typename base_type::key_type; using typename base_type::mapped_type; using base_type::begin; using base_type::cbegin; using base_type::cend; using base_type::end; // Create or retrieve tile at the given hex mapped_type& conjure(const key_type& key) { return base_type::emplace( std::piecewise_construct, std::forward_as_tuple(key), std::forward_as_tuple()).first->second; } // Retrieve tile at the given hex should one exist std::experimental::optional<mapped_type&> lookup(const key_type& key) { const auto& result = this->find(key); return result == this->cend() ? std::experimental::optional<mapped_type&>() : std::experimental::make_optional(std::ref(result->second)); } // Retrieve tile at the given hex should one exist std::experimental::optional<const mapped_type&> lookup(const key_type& key) const { const auto& result = this->find(key); return result == this->cend() ? std::experimental::optional<const mapped_type&>() : std::experimental::make_optional(std::cref(result->second)); } // TODO Cardinality? // TODO Removal? }; // When investigating some tile in the course of a search, should the // tile be included as usable, excluded as unusable, or should the search // stop immediately? enum class search_result { stop, exclude, include }; // TODO Make hexmap<optional<hex>> // TODO Use optional to track attempted visitation // TODO Consider making it optional<pair<hex,distance> // Breadth first search returning a map from destination to source, // which may be traversed back to origin for navigational purposes. // Predicate query(...) is assumed to be inexpensive-- revisit if otherwise. template <class MappedType> hexmap<typename hexmap<MappedType>::key_type> breadth_first_search( const hexmap<MappedType>& map, const typename hexmap<MappedType>::key_type origin, std::function<search_result(const typename hexmap<MappedType>::mapped_type&)> query, const int max_distance = std::numeric_limits<int>::max()) { hexmap<typename hexmap<MappedType>::key_type> retval; // Tracks locations to visit as well as their distance from origin std::deque<std::pair<typename hexmap<MappedType>::key_type,int>> frontier; frontier.emplace_back( std::piecewise_construct, std::forward_as_tuple(origin), std::forward_as_tuple(0)); // Proceed with breadth first search until one of exhaustion criteria met while (frontier.size()) { const auto& current = frontier.front(); const auto& contents = map.lookup(current.first); const auto result = current.second <= max_distance && contents ? query(contents.value()) : search_result::exclude; switch (result) { default: throw std::logic_error("missing case"); case search_result::stop: goto done; case search_result::exclude: break; case search_result::include: for (const auto& neighbor : neighbors(current.first)) { if (retval.find(neighbor) == retval.cend()) { frontier.emplace_back( std::piecewise_construct, std::forward_as_tuple(neighbor), std::forward_as_tuple(current.second + 1)); } } } frontier.pop_front(); } done: return retval; } } // namespace #endif <commit_msg>Correct (hopefully) BFS + make optional<commit_after>/* * Copyright (C) 2016 Rhys Ulerich * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef DESCENDU_HEXMAP_H #define DESCENDU_HEXMAP_H #include <deque> #include <functional> #include <limits> #include <stdexcept> #include <tuple> #include <unordered_map> #include <utility> #include "hex.hpp" #include "optional.hpp" namespace descendu { template <class MappedType> class hexmap : std::unordered_map<hex<int,spec::absolute>,MappedType> { typedef std::unordered_map<hex<int,spec::absolute>,MappedType> base_type; public: // Deliberately no base_type::size as removal of "dead" tiles TBD using typename base_type::const_iterator; using typename base_type::iterator; using typename base_type::key_type; using typename base_type::mapped_type; using base_type::begin; using base_type::cbegin; using base_type::cend; using base_type::end; // Create or retrieve tile at the given hex mapped_type& conjure(const key_type& key) { return base_type::emplace( std::piecewise_construct, std::forward_as_tuple(key), std::forward_as_tuple()).first->second; } // Retrieve tile at the given hex should one exist std::experimental::optional<mapped_type&> lookup(const key_type& key) { const auto& result = this->find(key); return result == this->cend() ? std::experimental::optional<mapped_type&>() : std::experimental::make_optional(std::ref(result->second)); } // Retrieve tile at the given hex should one exist std::experimental::optional<const mapped_type&> lookup(const key_type& key) const { const auto& result = this->find(key); return result == this->cend() ? std::experimental::optional<const mapped_type&>() : std::experimental::make_optional(std::cref(result->second)); } // TODO Cardinality? // TODO Removal? }; // When investigating some tile in the course of a search, should the // tile be included as usable, excluded as unusable, or should the search // stop immediately? enum class search_result { stop, exclude, include }; // Breadth first search returning a map from destination to optional // source, which may be traversed back to origin for navigational purposes. // Destinations with no source value were considered but excluded. template <class T> hexmap<std::experimental::optional<typename hexmap<T>::key_type>> breadth_first_search( const hexmap<T>& map, const typename hexmap<T>::key_type origin, std::function< search_result(const typename hexmap<T>::mapped_type&) > query, const int max_distance = std::numeric_limits<int>::max()) { typedef typename hexmap<T>::key_type key_type; using std::experimental::make_optional; using std::experimental::optional; // Maintains yet-to-be search (location, source, distance-from-origin) std::deque<std::tuple<key_type,key_type,int>> frontier; // Seed search with the neighbors of the origin for (const auto& neighbor : neighbors(origin)) { frontier.emplace_back( std::piecewise_construct, std::forward_as_tuple(neighbor), std::forward_as_tuple(origin), std::forward_as_tuple(1)); } // Accumulates result as well as already-visited status hexmap<optional<key_type>> retval; // Proceed with breadth first search until one of exhaustion criteria met while (!frontier.empty()) { const auto& location = std::get<0>(frontier.front()); const auto& source = std::get<1>(frontier.front()); const auto& distance = std::get<2>(frontier.front()); const auto& contents = map.lookup(location); if (distance <= max_distance && contents) { switch (query(contents.value())) { default: throw std::logic_error("missing case"); case search_result::stop: goto done; case search_result::exclude: retval.conjure(location) = optional<key_type>(); break; case search_result::include: for (const auto& neighbor : neighbors(location)) { if (!retval.lookup(neighbor)) { frontier.emplace_back( std::piecewise_construct, std::forward_as_tuple(neighbor), std::forward_as_tuple(location), std::forward_as_tuple(distance + 1)); } } retval.conjure(location) = make_optional(source); } } frontier.pop_front(); } done: return retval; } } // namespace #endif <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: app.hxx,v $ * $Revision: 1.36 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _DESKTOP_APP_HXX_ #define _DESKTOP_APP_HXX_ // stl includes first #include <map> #include <com/sun/star/lang/XMultiServiceFactory.hpp> #include <vcl/svapp.hxx> #ifndef _VCL_TIMER_HXX_ #include <vcl/timer.hxx> #endif #include <tools/resmgr.hxx> #include <unotools/bootstrap.hxx> #include <com/sun/star/lang/XInitialization.hpp> #include <com/sun/star/task/XStatusIndicator.hpp> #include <com/sun/star/uno/Reference.h> #include <osl/mutex.hxx> using namespace com::sun::star::task; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace rtl; #define DESKTOP_SAVETASKS_MOD 0x1 #define DESKTOP_SAVETASKS_UNMOD 0x2 #define DESKTOP_SAVETASKS_ALL 0x3 namespace desktop { /*-------------------------------------------------------------------- Description: Application-class --------------------------------------------------------------------*/ class IntroWindow_Impl; class CommandLineArgs; class Lockfile; class AcceptorMap : public std::map< OUString, Reference<XInitialization> > {}; struct ConvertData; class Desktop : public Application { friend class UserInstall; public: enum BootstrapError { BE_OK, BE_UNO_SERVICEMANAGER, BE_UNO_SERVICE_CONFIG_MISSING, BE_PATHINFO_MISSING, BE_USERINSTALL_FAILED, BE_LANGUAGE_MISSING, BE_USERINSTALL_NOTENOUGHDISKSPACE, BE_USERINSTALL_NOWRITEACCESS }; enum BootstrapStatus { BS_OK, BS_TERMINATE }; Desktop(); ~Desktop(); virtual void Main( ); virtual void Init(); virtual void DeInit(); virtual BOOL QueryExit(); virtual USHORT Exception(USHORT nError); virtual void SystemSettingsChanging( AllSettings& rSettings, Window* pFrame ); virtual void AppEvent( const ApplicationEvent& rAppEvent ); DECL_LINK( OpenClients_Impl, void* ); static void OpenClients(); static void OpenDefault(); DECL_LINK( EnableAcceptors_Impl, void*); static void HandleAppEvent( const ApplicationEvent& rAppEvent ); static ResMgr* GetDesktopResManager(); static CommandLineArgs* GetCommandLineArgs(); void HandleBootstrapErrors( BootstrapError ); void SetBootstrapError( BootstrapError nError ) { if ( m_aBootstrapError == BE_OK ) m_aBootstrapError = nError; } BootstrapError GetBootstrapError() const { return m_aBootstrapError; } void SetBootstrapStatus( BootstrapStatus nStatus ) { m_aBootstrapStatus = nStatus; } BootstrapStatus GetBootstrapStatus() const { return m_aBootstrapStatus; } static sal_Bool CheckOEM(); static sal_Bool isCrashReporterEnabled(); // first-start (ever) & license relate methods static rtl::OUString GetLicensePath(); static sal_Bool LicenseNeedsAcceptance(); static sal_Bool IsFirstStartWizardNeeded(); private: // Bootstrap methods ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > CreateApplicationServiceManager(); void RegisterServices( ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xSMgr ); void DeregisterServices(); void DestroyApplicationServiceManager( ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xSMgr ); void CreateTemporaryDirectory(); void RemoveTemporaryDirectory(); sal_Bool InitializeInstallation( const rtl::OUString& rAppFilename ); sal_Bool InitializeConfiguration(); sal_Bool InitializeQuickstartMode( com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rSMgr ); void HandleBootstrapPathErrors( ::utl::Bootstrap::Status, const ::rtl::OUString& aMsg ); void StartSetup( const ::rtl::OUString& aParameters ); // Get a resource message string securely e.g. if resource cannot be retrieved return aFaultBackMsg ::rtl::OUString GetMsgString( USHORT nId, const ::rtl::OUString& aFaultBackMsg ); // Create a error message depending on bootstrap failure code and an optional file url ::rtl::OUString CreateErrorMsgString( utl::Bootstrap::FailureCode nFailureCode, const ::rtl::OUString& aFileURL ); static void PreloadModuleData( CommandLineArgs* ); static void PreloadConfigurationData(); static ::rtl::OUString GetProductVersionID(); static ::rtl::OUString GetInstanceUUID( const ::rtl::OUString& rProductVersionID ); static ::rtl::OUString GenerateUUID(); static void StoreInstanceUUID( const ::rtl::OUString& rProductVersionID, const ::rtl::OUString& rUUID ); Reference<XStatusIndicator> m_rSplashScreen; void OpenSplashScreen(); void SetSplashScreenProgress(sal_Int32); void CloseSplashScreen(); void EnableOleAutomation(); DECL_LINK( ImplInitFilterHdl, ConvertData* ); DECL_LINK( AsyncInitFirstRun, void* ); /** checks if the office is run the first time <p>If so, <method>DoFirstRunInitializations</method> is called (asynchronously and delayed) and the respective flag in the configuration is reset.</p> */ void CheckFirstRun( ); /// does initializations which are necessary for the first run of the office void DoFirstRunInitializations(); static sal_Bool SaveTasks(); static sal_Bool _bTasksSaved; static void retrieveCrashReporterState(); // on-demand acceptors static void createAcceptor(const OUString& aDescription); static void enableAcceptors(); static void destroyAcceptor(const OUString& aDescription); sal_Bool m_bMinimized; sal_Bool m_bInvisible; bool m_bServicesRegistered; USHORT m_nAppEvents; BootstrapError m_aBootstrapError; BootstrapStatus m_aBootstrapStatus; Lockfile *m_pLockfile; Timer m_firstRunTimer; static ResMgr* pResMgr; static sal_Bool bSuppressOpenDefault; }; } #endif // _DESKTOP_APP_HXX_ <commit_msg>INTEGRATION: CWS register30 (1.36.64); FILE MERGED 2008/07/03 12:02:34 obr 1.36.64.1: #158122# registration reworked<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: app.hxx,v $ * $Revision: 1.37 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _DESKTOP_APP_HXX_ #define _DESKTOP_APP_HXX_ // stl includes first #include <map> #include <com/sun/star/lang/XMultiServiceFactory.hpp> #include <vcl/svapp.hxx> #ifndef _VCL_TIMER_HXX_ #include <vcl/timer.hxx> #endif #include <tools/resmgr.hxx> #include <unotools/bootstrap.hxx> #include <com/sun/star/lang/XInitialization.hpp> #include <com/sun/star/task/XStatusIndicator.hpp> #include <com/sun/star/uno/Reference.h> #include <osl/mutex.hxx> using namespace com::sun::star::task; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace rtl; #define DESKTOP_SAVETASKS_MOD 0x1 #define DESKTOP_SAVETASKS_UNMOD 0x2 #define DESKTOP_SAVETASKS_ALL 0x3 namespace desktop { /*-------------------------------------------------------------------- Description: Application-class --------------------------------------------------------------------*/ class IntroWindow_Impl; class CommandLineArgs; class Lockfile; class AcceptorMap : public std::map< OUString, Reference<XInitialization> > {}; struct ConvertData; class Desktop : public Application { friend class UserInstall; public: enum BootstrapError { BE_OK, BE_UNO_SERVICEMANAGER, BE_UNO_SERVICE_CONFIG_MISSING, BE_PATHINFO_MISSING, BE_USERINSTALL_FAILED, BE_LANGUAGE_MISSING, BE_USERINSTALL_NOTENOUGHDISKSPACE, BE_USERINSTALL_NOWRITEACCESS }; enum BootstrapStatus { BS_OK, BS_TERMINATE }; Desktop(); ~Desktop(); virtual void Main( ); virtual void Init(); virtual void DeInit(); virtual BOOL QueryExit(); virtual USHORT Exception(USHORT nError); virtual void SystemSettingsChanging( AllSettings& rSettings, Window* pFrame ); virtual void AppEvent( const ApplicationEvent& rAppEvent ); DECL_LINK( OpenClients_Impl, void* ); static void OpenClients(); static void OpenDefault(); DECL_LINK( EnableAcceptors_Impl, void*); static void HandleAppEvent( const ApplicationEvent& rAppEvent ); static ResMgr* GetDesktopResManager(); static CommandLineArgs* GetCommandLineArgs(); void HandleBootstrapErrors( BootstrapError ); void SetBootstrapError( BootstrapError nError ) { if ( m_aBootstrapError == BE_OK ) m_aBootstrapError = nError; } BootstrapError GetBootstrapError() const { return m_aBootstrapError; } void SetBootstrapStatus( BootstrapStatus nStatus ) { m_aBootstrapStatus = nStatus; } BootstrapStatus GetBootstrapStatus() const { return m_aBootstrapStatus; } static sal_Bool CheckOEM(); static sal_Bool isCrashReporterEnabled(); // first-start (ever) & license relate methods static rtl::OUString GetLicensePath(); static sal_Bool LicenseNeedsAcceptance(); static sal_Bool IsFirstStartWizardNeeded(); private: // Bootstrap methods ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > CreateApplicationServiceManager(); void RegisterServices( ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xSMgr ); void DeregisterServices(); void DestroyApplicationServiceManager( ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xSMgr ); void CreateTemporaryDirectory(); void RemoveTemporaryDirectory(); sal_Bool InitializeInstallation( const rtl::OUString& rAppFilename ); sal_Bool InitializeConfiguration(); sal_Bool InitializeQuickstartMode( com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rSMgr ); void HandleBootstrapPathErrors( ::utl::Bootstrap::Status, const ::rtl::OUString& aMsg ); void StartSetup( const ::rtl::OUString& aParameters ); // Get a resource message string securely e.g. if resource cannot be retrieved return aFaultBackMsg ::rtl::OUString GetMsgString( USHORT nId, const ::rtl::OUString& aFaultBackMsg ); // Create a error message depending on bootstrap failure code and an optional file url ::rtl::OUString CreateErrorMsgString( utl::Bootstrap::FailureCode nFailureCode, const ::rtl::OUString& aFileURL ); static void PreloadModuleData( CommandLineArgs* ); static void PreloadConfigurationData(); Reference<XStatusIndicator> m_rSplashScreen; void OpenSplashScreen(); void SetSplashScreenProgress(sal_Int32); void CloseSplashScreen(); void EnableOleAutomation(); DECL_LINK( ImplInitFilterHdl, ConvertData* ); DECL_LINK( AsyncInitFirstRun, void* ); /** checks if the office is run the first time <p>If so, <method>DoFirstRunInitializations</method> is called (asynchronously and delayed) and the respective flag in the configuration is reset.</p> */ void CheckFirstRun( ); /// does initializations which are necessary for the first run of the office void DoFirstRunInitializations(); static sal_Bool SaveTasks(); static sal_Bool _bTasksSaved; static void retrieveCrashReporterState(); // on-demand acceptors static void createAcceptor(const OUString& aDescription); static void enableAcceptors(); static void destroyAcceptor(const OUString& aDescription); sal_Bool m_bMinimized; sal_Bool m_bInvisible; bool m_bServicesRegistered; USHORT m_nAppEvents; BootstrapError m_aBootstrapError; BootstrapStatus m_aBootstrapStatus; Lockfile *m_pLockfile; Timer m_firstRunTimer; static ResMgr* pResMgr; static sal_Bool bSuppressOpenDefault; }; } #endif // _DESKTOP_APP_HXX_ <|endoftext|>
<commit_before>// @(#):$Id$ // Author: Andrei Gheata 01/03/11 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ //////////////////////////////////////////////////////////////////////////// // // TGeoBranchArray - An array of daughter indices making a geometry path. // Can be used to backup/restore a state. To setup an object of this type, // one should use: // TGeoBranchArray *array = new TGeoBranchArray(level); // array->InitFromNavigator(nav); (To initialize from current navigator state) // The navigator can be updated to reflect this path array: // array->UpdateNavigator(); // ///////////////////////////////////////////////////////////////////////////// #include "TGeoBranchArray.h" #include "TMath.h" #include "TString.h" #include "TGeoMatrix.h" #include "TGeoNavigator.h" #include "TGeoManager.h" ClassImp(TGeoBranchArray) //______________________________________________________________________________ TGeoBranchArray::TGeoBranchArray(UShort_t level) :fLevel(level), fArray(NULL), fMatrix(NULL), fClient(NULL) { // Constructor. Alocates the array with a size given by level. fArray = new UShort_t[level]; } //______________________________________________________________________________ TGeoBranchArray::~TGeoBranchArray() { // Destructor. delete [] fArray; delete fMatrix; } //______________________________________________________________________________ TGeoBranchArray::TGeoBranchArray(const TGeoBranchArray& other) :TObject(other), fLevel(other.fLevel), fArray(NULL), fMatrix(NULL) { // Copy constructor. if (fLevel) fArray = new UShort_t[fLevel]; if (other.fMatrix) fMatrix = new TGeoHMatrix(*(other.fMatrix)); } //______________________________________________________________________________ TGeoBranchArray& TGeoBranchArray::operator=(const TGeoBranchArray& other) { // Assignment. if (&other == this) return *this; fLevel = other.fLevel; if (fLevel) fArray = new UShort_t[fLevel]; if (other.fMatrix) { fMatrix = new TGeoHMatrix(); fMatrix->CopyFrom(other.fMatrix); } return *this; } //______________________________________________________________________________ void TGeoBranchArray::AddLevel(UShort_t dindex) { // Add and extra daughter to the current path array. No validity check performed ! if (!fLevel) { Error("AddLevel", "You must initialize from navigator or copy from another branch array first."); return; } fLevel++; UShort_t *array = new UShort_t[fLevel]; memcpy(array, fArray, (fLevel-1)*sizeof(UShort_t)); array[fLevel-1] = dindex; delete [] fArray; fArray = array; } //______________________________________________________________________________ Bool_t TGeoBranchArray::operator ==(const TGeoBranchArray& other) const { // Is equal operator. Int_t value = Compare(&other); if (value==0) return kTRUE; return kFALSE; } //______________________________________________________________________________ Bool_t TGeoBranchArray::operator !=(const TGeoBranchArray& other) const { // Not equal operator. Int_t value = Compare(&other); if (value!=0) return kTRUE; return kFALSE; } //______________________________________________________________________________ Bool_t TGeoBranchArray::operator >(const TGeoBranchArray& other) const { // Is equal operator. Int_t value = Compare(&other); if (value>0) return kTRUE; return kFALSE; } //______________________________________________________________________________ Bool_t TGeoBranchArray::operator <(const TGeoBranchArray& other) const { // Is equal operator. Int_t value = Compare(&other); if (value<0) return kTRUE; return kFALSE; } //______________________________________________________________________________ Bool_t TGeoBranchArray::operator >=(const TGeoBranchArray& other) const { // Is equal operator. Int_t value = Compare(&other); if (value>=0) return kTRUE; return kFALSE; } //______________________________________________________________________________ Bool_t TGeoBranchArray::operator <=(const TGeoBranchArray& other) const { // Is equal operator. Int_t value = Compare(&other); if (value<=0) return kTRUE; return kFALSE; } //______________________________________________________________________________ Long64_t TGeoBranchArray::BinarySearch(Long64_t n, const TGeoBranchArray **array, TGeoBranchArray *value) { // Binary search in an array of n pointers to branch arrays, to locate value. // Returns element index or index of nearest element smaller than value Long64_t nabove, nbelow, middle; const TGeoBranchArray *pind; nabove = n+1; nbelow = 0; while(nabove-nbelow > 1) { middle = (nabove+nbelow)/2; pind = array[middle-1]; if (*value == *pind) return middle-1; if (*value < *pind) nabove = middle; else nbelow = middle; } return nbelow-1; } //______________________________________________________________________________ Int_t TGeoBranchArray::Compare(const TObject *obj) const { // Compare with other object of same type. Returns -1 if this is smaller (first // smaller array value prevails), 0 if equal (size and values) and 1 if this is // larger. UShort_t i; TGeoBranchArray *other = (TGeoBranchArray*)obj; UShort_t otherLevel = other->GetLevel(); UShort_t maxLevel = TMath::Min(fLevel, otherLevel); UShort_t *otherArray = other->GetArray(); for (i=0; i<maxLevel; i++) { if (fArray[i]==otherArray[i]) continue; if (fArray[i]<otherArray[i]) return -1; return 1; } if (fLevel==otherLevel) return 0; if (fLevel<otherLevel) return -1; return 1; } //______________________________________________________________________________ void TGeoBranchArray::CleanMatrix() { // Garbage collect the stored matrix. delete fMatrix; fMatrix = 0; } //______________________________________________________________________________ TGeoNode *TGeoBranchArray::GetNode(UShort_t level) const { TGeoNode *node = gGeoManager->GetTopNode(); if (!level) return node; if (level>fLevel) return NULL; for (Int_t i=0; i<level; i++) node = node->GetVolume()->GetNode(fArray[i]); return node; } //______________________________________________________________________________ void TGeoBranchArray::InitFromNavigator(TGeoNavigator *nav) { // Init the branch array from current navigator state. UShort_t level = (UShort_t)nav->GetLevel(); if (!fMatrix) fMatrix = new TGeoHMatrix(); fMatrix->CopyFrom(nav->GetCurrentMatrix()); if (!level) { // delete [] fArray; fArray = 0; fLevel = 0; return; } if (!fArray || level>fLevel) { delete [] fArray; fArray = new UShort_t[level]; } fLevel = level; TGeoNode *mother = nav->GetMother(fLevel); for (Int_t i=fLevel-1; i>=0; i--) { TGeoNode *node = nav->GetMother(i); Int_t index = mother->GetVolume()->GetIndex(node); fArray[fLevel-i-1] = index; mother = node; } } //______________________________________________________________________________ void TGeoBranchArray::GetPath(TString &path) const { // Fill path pointed by the array. path = "/"; TGeoNode *node = GetNode(0); path += node->GetName(); for (Int_t i=0; i<fLevel; i++) { path += "/"; node = node->GetVolume()->GetNode(fArray[i]); path += node->GetName(); } } //______________________________________________________________________________ void TGeoBranchArray::Print(Option_t *) const { // Print branch information TString path; GetPath(path); printf("branch: %s\n", path.Data()); } //______________________________________________________________________________ void TGeoBranchArray::Sort(Int_t n, TGeoBranchArray **array, Int_t *index, Bool_t down) { // Sorting of an array of branch array pointers. for (Int_t i=0; i<n; i++) index[i] = i; if (down) std::sort(index, index + n, compareBAdesc(array)); else std::sort(index, index + n, compareBAasc(array)); } //______________________________________________________________________________ void TGeoBranchArray::UpdateNavigator(TGeoNavigator *nav) const { // Update the navigator to reflect the branch. nav->CdTop(); for (Int_t i=0; i<fLevel; i++) nav->CdDown(fArray[i]); } <commit_msg>Coverity fix<commit_after>// @(#):$Id$ // Author: Andrei Gheata 01/03/11 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ //////////////////////////////////////////////////////////////////////////// // // TGeoBranchArray - An array of daughter indices making a geometry path. // Can be used to backup/restore a state. To setup an object of this type, // one should use: // TGeoBranchArray *array = new TGeoBranchArray(level); // array->InitFromNavigator(nav); (To initialize from current navigator state) // The navigator can be updated to reflect this path array: // array->UpdateNavigator(); // ///////////////////////////////////////////////////////////////////////////// #include "TGeoBranchArray.h" #include "TMath.h" #include "TString.h" #include "TGeoMatrix.h" #include "TGeoNavigator.h" #include "TGeoManager.h" ClassImp(TGeoBranchArray) //______________________________________________________________________________ TGeoBranchArray::TGeoBranchArray(UShort_t level) :fLevel(level), fArray(NULL), fMatrix(NULL), fClient(NULL) { // Constructor. Alocates the array with a size given by level. fArray = new UShort_t[level]; } //______________________________________________________________________________ TGeoBranchArray::~TGeoBranchArray() { // Destructor. delete [] fArray; delete fMatrix; } //______________________________________________________________________________ TGeoBranchArray::TGeoBranchArray(const TGeoBranchArray& other) :TObject(other), fLevel(other.fLevel), fArray(NULL), fMatrix(NULL), fClient(other.fClient) { // Copy constructor. if (fLevel) fArray = new UShort_t[fLevel]; if (other.fMatrix) fMatrix = new TGeoHMatrix(*(other.fMatrix)); } //______________________________________________________________________________ TGeoBranchArray& TGeoBranchArray::operator=(const TGeoBranchArray& other) { // Assignment. if (&other == this) return *this; fLevel = other.fLevel; if (fLevel) fArray = new UShort_t[fLevel]; if (other.fMatrix) { fMatrix = new TGeoHMatrix(); fMatrix->CopyFrom(other.fMatrix); } fClient = other.fClient; return *this; } //______________________________________________________________________________ void TGeoBranchArray::AddLevel(UShort_t dindex) { // Add and extra daughter to the current path array. No validity check performed ! if (!fLevel) { Error("AddLevel", "You must initialize from navigator or copy from another branch array first."); return; } fLevel++; UShort_t *array = new UShort_t[fLevel]; memcpy(array, fArray, (fLevel-1)*sizeof(UShort_t)); array[fLevel-1] = dindex; delete [] fArray; fArray = array; } //______________________________________________________________________________ Bool_t TGeoBranchArray::operator ==(const TGeoBranchArray& other) const { // Is equal operator. Int_t value = Compare(&other); if (value==0) return kTRUE; return kFALSE; } //______________________________________________________________________________ Bool_t TGeoBranchArray::operator !=(const TGeoBranchArray& other) const { // Not equal operator. Int_t value = Compare(&other); if (value!=0) return kTRUE; return kFALSE; } //______________________________________________________________________________ Bool_t TGeoBranchArray::operator >(const TGeoBranchArray& other) const { // Is equal operator. Int_t value = Compare(&other); if (value>0) return kTRUE; return kFALSE; } //______________________________________________________________________________ Bool_t TGeoBranchArray::operator <(const TGeoBranchArray& other) const { // Is equal operator. Int_t value = Compare(&other); if (value<0) return kTRUE; return kFALSE; } //______________________________________________________________________________ Bool_t TGeoBranchArray::operator >=(const TGeoBranchArray& other) const { // Is equal operator. Int_t value = Compare(&other); if (value>=0) return kTRUE; return kFALSE; } //______________________________________________________________________________ Bool_t TGeoBranchArray::operator <=(const TGeoBranchArray& other) const { // Is equal operator. Int_t value = Compare(&other); if (value<=0) return kTRUE; return kFALSE; } //______________________________________________________________________________ Long64_t TGeoBranchArray::BinarySearch(Long64_t n, const TGeoBranchArray **array, TGeoBranchArray *value) { // Binary search in an array of n pointers to branch arrays, to locate value. // Returns element index or index of nearest element smaller than value Long64_t nabove, nbelow, middle; const TGeoBranchArray *pind; nabove = n+1; nbelow = 0; while(nabove-nbelow > 1) { middle = (nabove+nbelow)/2; pind = array[middle-1]; if (*value == *pind) return middle-1; if (*value < *pind) nabove = middle; else nbelow = middle; } return nbelow-1; } //______________________________________________________________________________ Int_t TGeoBranchArray::Compare(const TObject *obj) const { // Compare with other object of same type. Returns -1 if this is smaller (first // smaller array value prevails), 0 if equal (size and values) and 1 if this is // larger. UShort_t i; TGeoBranchArray *other = (TGeoBranchArray*)obj; UShort_t otherLevel = other->GetLevel(); UShort_t maxLevel = TMath::Min(fLevel, otherLevel); UShort_t *otherArray = other->GetArray(); for (i=0; i<maxLevel; i++) { if (fArray[i]==otherArray[i]) continue; if (fArray[i]<otherArray[i]) return -1; return 1; } if (fLevel==otherLevel) return 0; if (fLevel<otherLevel) return -1; return 1; } //______________________________________________________________________________ void TGeoBranchArray::CleanMatrix() { // Garbage collect the stored matrix. delete fMatrix; fMatrix = 0; } //______________________________________________________________________________ TGeoNode *TGeoBranchArray::GetNode(UShort_t level) const { TGeoNode *node = gGeoManager->GetTopNode(); if (!level) return node; if (level>fLevel) return NULL; for (Int_t i=0; i<level; i++) node = node->GetVolume()->GetNode(fArray[i]); return node; } //______________________________________________________________________________ void TGeoBranchArray::InitFromNavigator(TGeoNavigator *nav) { // Init the branch array from current navigator state. UShort_t level = (UShort_t)nav->GetLevel(); if (!fMatrix) fMatrix = new TGeoHMatrix(); fMatrix->CopyFrom(nav->GetCurrentMatrix()); if (!level) { // delete [] fArray; fArray = 0; fLevel = 0; return; } if (!fArray || level>fLevel) { delete [] fArray; fArray = new UShort_t[level]; } fLevel = level; TGeoNode *mother = nav->GetMother(fLevel); for (Int_t i=fLevel-1; i>=0; i--) { TGeoNode *node = nav->GetMother(i); Int_t index = mother->GetVolume()->GetIndex(node); fArray[fLevel-i-1] = index; mother = node; } } //______________________________________________________________________________ void TGeoBranchArray::GetPath(TString &path) const { // Fill path pointed by the array. path = "/"; TGeoNode *node = GetNode(0); path += node->GetName(); for (Int_t i=0; i<fLevel; i++) { path += "/"; node = node->GetVolume()->GetNode(fArray[i]); path += node->GetName(); } } //______________________________________________________________________________ void TGeoBranchArray::Print(Option_t *) const { // Print branch information TString path; GetPath(path); printf("branch: %s\n", path.Data()); } //______________________________________________________________________________ void TGeoBranchArray::Sort(Int_t n, TGeoBranchArray **array, Int_t *index, Bool_t down) { // Sorting of an array of branch array pointers. for (Int_t i=0; i<n; i++) index[i] = i; if (down) std::sort(index, index + n, compareBAdesc(array)); else std::sort(index, index + n, compareBAasc(array)); } //______________________________________________________________________________ void TGeoBranchArray::UpdateNavigator(TGeoNavigator *nav) const { // Update the navigator to reflect the branch. nav->CdTop(); for (Int_t i=0; i<fLevel; i++) nav->CdDown(fArray[i]); } <|endoftext|>
<commit_before><commit_msg>coverity#708017 Uninitialized scalar field<commit_after><|endoftext|>
<commit_before>#include "engine.h" Engine::Engine(QObject *parent) : QObject(parent), m_reader(new XMLReader), m_dbmanager(new DatabaseManager) { m_dbmanager->setUpDB(); m_seriesListModel = new SeriesListModel(this, m_dbmanager, m_reader); m_searchListModel = new SearchListModel(this, m_dbmanager, m_reader); m_todayListModel = new TodayListModel(this, m_dbmanager, m_reader); m_episodeListModel = new EpisodeListModel(this, m_dbmanager); m_seasonListModel = new SeasonListModel(this, m_dbmanager); connect(m_searchListModel, SIGNAL(updateModels()), this, SLOT(readyToUpdateModels())); connect(m_seriesListModel, SIGNAL(updateModels()), this, SLOT(readyToUpdateModels())); } Engine::~Engine() { delete m_reader; delete m_dbmanager; qDebug() << "destructing Engine"; } SeriesListModel* Engine::getSeriesListModel() { return m_seriesListModel; } SearchListModel *Engine::getSearchModel() { return m_searchListModel; } TodayListModel* Engine::getTodayModel() { return m_todayListModel; } EpisodeListModel* Engine::getEpisodeListModel() { return m_episodeListModel; } SeasonListModel* Engine::getSeasonListModel() { return m_seasonListModel; } void Engine::readyToUpdateModels() { m_todayListModel->populateTodayModel(); m_seriesListModel->populateBannerList(); } void Engine::updateModels() { qDebug() << "update"; m_todayListModel->populateTodayModel(); m_seriesListModel->populateBannerList(); } <commit_msg>continued<commit_after>#include "engine.h" Engine::Engine(QObject *parent) : QObject(parent), m_reader(new XMLReader), m_dbmanager(new DatabaseManager) { m_dbmanager->setUpDB(); m_seriesListModel = new SeriesListModel(this, m_dbmanager, m_reader); m_searchListModel = new SearchListModel(this, m_dbmanager, m_reader); m_todayListModel = new TodayListModel(this, m_dbmanager, m_reader); m_episodeListModel = new EpisodeListModel(this, m_dbmanager); m_seasonListModel = new SeasonListModel(this, m_dbmanager); connect(m_searchListModel, SIGNAL(updateModels()), this, SLOT(readyToUpdateModels())); connect(m_seriesListModel, SIGNAL(updateModels()), this, SLOT(readyToUpdateModels())); } Engine::~Engine() { delete m_reader; delete m_dbmanager; qDebug() << "destructing Engine"; } SeriesListModel* Engine::getSeriesListModel() { return m_seriesListModel; } SearchListModel *Engine::getSearchModel() { return m_searchListModel; } TodayListModel* Engine::getTodayModel() { return m_todayListModel; } EpisodeListModel* Engine::getEpisodeListModel() { return m_episodeListModel; } SeasonListModel* Engine::getSeasonListModel() { return m_seasonListModel; } void Engine::readyToUpdateModels() { m_todayListModel->populateTodayModel(); m_seriesListModel->populateBannerList(); } void Engine::updateModels() { m_todayListModel->populateTodayModel(); m_seriesListModel->populateBannerList(); } <|endoftext|>
<commit_before>#include "zmq.h" #include <iostream> #include "AliHLTDataTypes.h" #include "AliHLTComponent.h" #include "AliHLTMessage.h" #include "TClass.h" #include "TCanvas.h" #include "TMap.h" #include "TPRegexp.h" #include "TObjString.h" #include "TDirectory.h" #include "TList.h" #include "AliZMQhelpers.h" #include "TMessage.h" #include "TSystem.h" #include "TApplication.h" #include "TH1.h" #include "TH1F.h" #include <time.h> #include <string> #include <map> #include "TFile.h" #include "TSystem.h" #include "signal.h" class MySignalHandler; //this is meant to become a class, hence the structure with global vars etc. //Also the code is rather flat - it is a bit of a playground to test ideas. //TODO structure this at some point, e.g. introduce a SIMPLE unified way of handling //zmq payloads, maybe a AliZMQmessage class which would by default be multipart and provide //easy access to payloads based on topic or so (a la HLT GetFirstInputObject() etc...) //methods int ProcessOptionString(TString arguments); int UpdatePad(TObject*); int DumpToFile(TObject* object); void* run(void* arg); //configuration vars Bool_t fVerbose = kFALSE; TString fZMQconfigIN = "PULL>tcp://localhost:60211"; int fZMQsocketModeIN=-1; TString fZMQsubscriptionIN = ""; TString fFilter = ""; TString fFileName=""; TFile* fFile=NULL; int fPollInterval = 0; int fPollTimeout = 1000; //1s //internal state void* fZMQcontext = NULL; //ze zmq context void* fZMQin = NULL; //the in socket - entry point for the data to be merged. TApplication* gApp; TCanvas* fCanvas; TObjArray fDrawables; TPRegexp* fSelectionRegexp = NULL; TString fDrawOptions; ULong64_t iterations=0; const char* fUSAGE = "ZMQhstViewer: Draw() all ROOT drawables in a message\n" "options: \n" " -in : data in\n" " -sleep : how long to sleep in between requests for data in s (if applicable)\n" " -timeout : how long to wait for the server to reply (s)\n" " -Verbose : be verbose\n" " -select : only show selected histograms (by regexp)\n" " -drawoptions : what draw option to use\n" " -file : dump input to file\n" ; //_______________________________________________________________________________________ class MySignalHandler : public TSignalHandler { public: MySignalHandler(ESignals sig) : TSignalHandler(sig) {} Bool_t Notify() { Printf("signal received, exiting"); fgTerminationSignaled = true; return TSignalHandler::Notify(); } static bool TerminationSignaled() { return fgTerminationSignaled; } static bool fgTerminationSignaled; }; bool MySignalHandler::fgTerminationSignaled = false; void sig_handler(int signo) { if (signo == SIGINT) printf("received SIGINT\n"); MySignalHandler::fgTerminationSignaled=true; } //_______________________________________________________________________________________ void* run(void* arg) { //main loop while(!MySignalHandler::TerminationSignaled()) { errno=0; //send a request if we are using REQ if (fZMQsocketModeIN==ZMQ_REQ) { TString request; if (fSelectionRegexp) request = "select="+fSelectionRegexp->GetPattern(); TString requestTopic; if (fSelectionRegexp) requestTopic = "CONFIG"; if (fVerbose) Printf("sending request %s %s",requestTopic.Data(), request.Data()); zmq_send(fZMQin, requestTopic.Data(), requestTopic.Length(), ZMQ_SNDMORE); zmq_send(fZMQin, request.Data(), request.Length(), ZMQ_SNDMORE); zmq_send(fZMQin, "", 0, ZMQ_SNDMORE); zmq_send(fZMQin, "", 0, 0); } //wait for the data zmq_pollitem_t sockets[] = { { fZMQin, 0, ZMQ_POLLIN, 0 }, }; int rc = zmq_poll(sockets, 1, (fZMQsocketModeIN==ZMQ_REQ)?fPollTimeout:-1); if (rc==-1 && errno==ETERM) { Printf("jumping out of main loop"); break; } if (!sockets[0].revents & ZMQ_POLLIN) { //server died Printf("connection timed out, server %s died?", fZMQconfigIN.Data()); fZMQsocketModeIN = alizmq_socket_init(fZMQin, fZMQcontext, fZMQconfigIN.Data()); if (fZMQsocketModeIN < 0) return NULL; continue; } else { //get all data (topic+body), possibly many of them aliZMQmsg message; alizmq_msg_recv(&message, fZMQin, 0); for (aliZMQmsg::iterator i=message.begin(); i!=message.end(); ++i) { TObject* object; alizmq_msg_iter_data(i, object); if (object) UpdatePad(object); if (!fFileName.IsNull()) { DumpToFile(object); } } alizmq_msg_close(&message); }//socket 0 gSystem->ProcessEvents(); usleep(fPollInterval); }//main loop return NULL; } //_______________________________________________________________________________________ int main(int argc, char** argv) { //process args int noptions = ProcessOptionString(AliOptionParser::GetFullArgString(argc,argv)); if (noptions<=0) { printf("%s",fUSAGE); return 1; } TH1::AddDirectory(kFALSE); TDirectory::AddDirectory(kFALSE); gApp = new TApplication("viewer", &argc, argv); gApp->SetReturnFromRun(true); //gApp->Run(); fCanvas = new TCanvas(); gSystem->ProcessEvents(); int mainReturnCode=0; //init stuff //globally enable schema evolution for serializing ROOT objects TMessage::EnableSchemaEvolutionForAll(kTRUE); //ZMQ init fZMQcontext = zmq_ctx_new(); fZMQsocketModeIN = alizmq_socket_init(fZMQin, fZMQcontext, fZMQconfigIN.Data(), -1, 2); if (fZMQsocketModeIN < 0) return 1; gSystem->ResetSignal(kSigPipe); gSystem->ResetSignal(kSigQuit); gSystem->ResetSignal(kSigInterrupt); gSystem->ResetSignal(kSigTermination); //gSystem->AddSignalHandler(new MySignalHandler(kSigPipe)); //gSystem->AddSignalHandler(new MySignalHandler(kSigQuit)); //gSystem->AddSignalHandler(new MySignalHandler(kSigInterrupt)); //gSystem->AddSignalHandler(new MySignalHandler(kSigTermination)); if (signal(SIGINT, sig_handler) == SIG_ERR) printf("\ncan't catch SIGINT\n"); run(NULL); Printf("exiting..."); fFile->Close(); delete fFile; fFile=0; //destroy ZMQ sockets int linger=0; zmq_setsockopt(fZMQin, ZMQ_LINGER, &linger, sizeof(linger)); zmq_close(fZMQin); zmq_ctx_term(fZMQcontext); return mainReturnCode; } //______________________________________________________________________________ int DumpToFile(TObject* object) { Option_t* fileMode="RECREATE"; if (!fFile) fFile = new TFile(fFileName,fileMode); if (fVerbose) Printf("writing object %s to %s",object->GetName(), fFileName.Data()); return object->Write(object->GetName(),TObject::kOverwrite); } //______________________________________________________________________________ int UpdatePad(TObject* object) { if (!object) return -1; const char* name = object->GetName(); TObject* drawable = fDrawables.FindObject(name); int padIndex = fDrawables.IndexOf(drawable); if (fVerbose) Printf("in: %s", name); Bool_t selected = kTRUE; if (fSelectionRegexp) selected = fSelectionRegexp->Match(name); if (!selected) return 0; if (drawable) { //only redraw the one thing if (fVerbose) Printf(" redrawing %s in pad %i", name, padIndex); fCanvas->cd(padIndex+1); gPad->GetListOfPrimitives()->Remove(drawable); gPad->Clear(); fDrawables.RemoveAt(padIndex); delete drawable; fDrawables.AddAt(object, padIndex); object->Draw(fDrawOptions); gPad->Modified(kTRUE); } else { if (fVerbose) Printf(" new object %s", name); //add the new object to the collection, restructure the canvas //and redraw everything fDrawables.AddLast(object); //after we clear the canvas, the pads are gone, clear the pad cache as well fCanvas->Clear(); fCanvas->DivideSquare(fDrawables.GetLast()+1); //redraw all objects at their old places and the new one as last for (int i=0; i<fDrawables.GetLast()+1; i++) { TObject* obj = fDrawables[i]; fCanvas->cd(i+1); if (fVerbose) Printf(" drawing %s in pad %i", obj->GetName(), i); if (obj) obj->Draw(); } } gSystem->ProcessEvents(); fCanvas->Update(); return 0; } //______________________________________________________________________________ int ProcessOptionString(TString arguments) { //process passed options stringMap* options = AliOptionParser::TokenizeOptionString(arguments); int nOptions = 0; for (stringMap::iterator i=options->begin(); i!=options->end(); ++i) { //Printf(" %s : %s", i->first.data(), i->second.data()); const TString& option = i->first; const TString& value = i->second; if (option.EqualTo("PollInterval") || option.EqualTo("sleep")) { fPollInterval = round(value.Atof()*1e6); } else if (option.EqualTo("PollTimeout") || option.EqualTo("timeout")) { fPollTimeout = round(value.Atof()*1e3); } else if (option.EqualTo("ZMQconfigIN") || option.EqualTo("in") ) { fZMQconfigIN = value; } else if (option.EqualTo("Verbose")) { fVerbose=kTRUE; } else if (option.EqualTo("select")) { delete fSelectionRegexp; fSelectionRegexp=new TPRegexp(value); } else if (option.EqualTo("drawoptions")) { fDrawOptions = value; } else if (option.EqualTo("file")) { fFileName = value; } else { nOptions=-1; break; } nOptions++; } delete options; //tidy up return nOptions; } <commit_msg>dump to file and exit<commit_after>#include "zmq.h" #include <iostream> #include "AliHLTDataTypes.h" #include "AliHLTComponent.h" #include "AliHLTMessage.h" #include "TClass.h" #include "TCanvas.h" #include "TMap.h" #include "TPRegexp.h" #include "TObjString.h" #include "TDirectory.h" #include "TList.h" #include "AliZMQhelpers.h" #include "TMessage.h" #include "TSystem.h" #include "TApplication.h" #include "TH1.h" #include "TH1F.h" #include <time.h> #include <string> #include <map> #include "TFile.h" #include "TSystem.h" #include "signal.h" class MySignalHandler; //this is meant to become a class, hence the structure with global vars etc. //Also the code is rather flat - it is a bit of a playground to test ideas. //TODO structure this at some point, e.g. introduce a SIMPLE unified way of handling //zmq payloads, maybe a AliZMQmessage class which would by default be multipart and provide //easy access to payloads based on topic or so (a la HLT GetFirstInputObject() etc...) //methods int ProcessOptionString(TString arguments); int UpdatePad(TObject*); int DumpToFile(TObject* object); void* run(void* arg); //configuration vars Bool_t fVerbose = kFALSE; TString fZMQconfigIN = "PULL>tcp://localhost:60211"; int fZMQsocketModeIN=-1; TString fZMQsubscriptionIN = ""; TString fFilter = ""; TString fFileName=""; TFile* fFile=NULL; int fPollInterval = 0; int fPollTimeout = 1000; //1s //internal state void* fZMQcontext = NULL; //ze zmq context void* fZMQin = NULL; //the in socket - entry point for the data to be merged. TApplication* gApp; TCanvas* fCanvas; TObjArray fDrawables; TPRegexp* fSelectionRegexp = NULL; TString fDrawOptions; ULong64_t iterations=0; const char* fUSAGE = "ZMQhstViewer: Draw() all ROOT drawables in a message\n" "options: \n" " -in : data in\n" " -sleep : how long to sleep in between requests for data in s (if applicable)\n" " -timeout : how long to wait for the server to reply (s)\n" " -Verbose : be verbose\n" " -select : only show selected histograms (by regexp)\n" " -drawoptions : what draw option to use\n" " -file : dump input to file and exit\n" ; //_______________________________________________________________________________________ class MySignalHandler : public TSignalHandler { public: MySignalHandler(ESignals sig) : TSignalHandler(sig) {} Bool_t Notify() { Printf("signal received, exiting"); fgTerminationSignaled = true; return TSignalHandler::Notify(); } static bool TerminationSignaled() { return fgTerminationSignaled; } static bool fgTerminationSignaled; }; bool MySignalHandler::fgTerminationSignaled = false; void sig_handler(int signo) { if (signo == SIGINT) printf("received SIGINT\n"); MySignalHandler::fgTerminationSignaled=true; } //_______________________________________________________________________________________ void* run(void* arg) { //main loop while(!MySignalHandler::TerminationSignaled()) { errno=0; //send a request if we are using REQ if (fZMQsocketModeIN==ZMQ_REQ) { TString request; if (fSelectionRegexp) request = "select="+fSelectionRegexp->GetPattern(); TString requestTopic; if (fSelectionRegexp) requestTopic = "CONFIG"; if (fVerbose) Printf("sending request %s %s",requestTopic.Data(), request.Data()); zmq_send(fZMQin, requestTopic.Data(), requestTopic.Length(), ZMQ_SNDMORE); zmq_send(fZMQin, request.Data(), request.Length(), ZMQ_SNDMORE); zmq_send(fZMQin, "", 0, ZMQ_SNDMORE); zmq_send(fZMQin, "", 0, 0); } //wait for the data zmq_pollitem_t sockets[] = { { fZMQin, 0, ZMQ_POLLIN, 0 }, }; int rc = zmq_poll(sockets, 1, (fZMQsocketModeIN==ZMQ_REQ)?fPollTimeout:-1); if (rc==-1 && errno==ETERM) { Printf("jumping out of main loop"); break; } if (!sockets[0].revents & ZMQ_POLLIN) { //server died Printf("connection timed out, server %s died?", fZMQconfigIN.Data()); fZMQsocketModeIN = alizmq_socket_init(fZMQin, fZMQcontext, fZMQconfigIN.Data()); if (fZMQsocketModeIN < 0) return NULL; continue; } else { //get all data (topic+body), possibly many of them aliZMQmsg message; alizmq_msg_recv(&message, fZMQin, 0); for (aliZMQmsg::iterator i=message.begin(); i!=message.end(); ++i) { TObject* object; alizmq_msg_iter_data(i, object); if (object) UpdatePad(object); if (!fFileName.IsNull()) { DumpToFile(object); } } alizmq_msg_close(&message); }//socket 0 gSystem->ProcessEvents(); usleep(fPollInterval); }//main loop return NULL; } //_______________________________________________________________________________________ int main(int argc, char** argv) { //process args int noptions = ProcessOptionString(AliOptionParser::GetFullArgString(argc,argv)); if (noptions<=0) { printf("%s",fUSAGE); return 1; } TH1::AddDirectory(kFALSE); TDirectory::AddDirectory(kFALSE); gApp = new TApplication("viewer", &argc, argv); gApp->SetReturnFromRun(true); //gApp->Run(); fCanvas = new TCanvas(); gSystem->ProcessEvents(); int mainReturnCode=0; //init stuff //globally enable schema evolution for serializing ROOT objects TMessage::EnableSchemaEvolutionForAll(kTRUE); //ZMQ init fZMQcontext = zmq_ctx_new(); fZMQsocketModeIN = alizmq_socket_init(fZMQin, fZMQcontext, fZMQconfigIN.Data(), -1, 2); if (fZMQsocketModeIN < 0) return 1; gSystem->ResetSignal(kSigPipe); gSystem->ResetSignal(kSigQuit); gSystem->ResetSignal(kSigInterrupt); gSystem->ResetSignal(kSigTermination); //gSystem->AddSignalHandler(new MySignalHandler(kSigPipe)); //gSystem->AddSignalHandler(new MySignalHandler(kSigQuit)); //gSystem->AddSignalHandler(new MySignalHandler(kSigInterrupt)); //gSystem->AddSignalHandler(new MySignalHandler(kSigTermination)); if (signal(SIGINT, sig_handler) == SIG_ERR) printf("\ncan't catch SIGINT\n"); run(NULL); Printf("exiting..."); fFile->Close(); delete fFile; fFile=0; //destroy ZMQ sockets int linger=0; zmq_setsockopt(fZMQin, ZMQ_LINGER, &linger, sizeof(linger)); zmq_close(fZMQin); zmq_ctx_term(fZMQcontext); return mainReturnCode; } //______________________________________________________________________________ int DumpToFile(TObject* object) { Option_t* fileMode="RECREATE"; if (!fFile) fFile = new TFile(fFileName,fileMode); if (fVerbose) Printf("writing object %s to %s",object->GetName(), fFileName.Data()); int rc = object->Write(object->GetName(),TObject::kOverwrite); MySignalHandler::fgTerminationSignaled=true; return rc; } //______________________________________________________________________________ int UpdatePad(TObject* object) { if (!object) return -1; const char* name = object->GetName(); TObject* drawable = fDrawables.FindObject(name); int padIndex = fDrawables.IndexOf(drawable); if (fVerbose) Printf("in: %s", name); Bool_t selected = kTRUE; if (fSelectionRegexp) selected = fSelectionRegexp->Match(name); if (!selected) return 0; if (drawable) { //only redraw the one thing if (fVerbose) Printf(" redrawing %s in pad %i", name, padIndex); fCanvas->cd(padIndex+1); gPad->GetListOfPrimitives()->Remove(drawable); gPad->Clear(); fDrawables.RemoveAt(padIndex); delete drawable; fDrawables.AddAt(object, padIndex); object->Draw(fDrawOptions); gPad->Modified(kTRUE); } else { if (fVerbose) Printf(" new object %s", name); //add the new object to the collection, restructure the canvas //and redraw everything fDrawables.AddLast(object); //after we clear the canvas, the pads are gone, clear the pad cache as well fCanvas->Clear(); fCanvas->DivideSquare(fDrawables.GetLast()+1); //redraw all objects at their old places and the new one as last for (int i=0; i<fDrawables.GetLast()+1; i++) { TObject* obj = fDrawables[i]; fCanvas->cd(i+1); if (fVerbose) Printf(" drawing %s in pad %i", obj->GetName(), i); if (obj) obj->Draw(); } } gSystem->ProcessEvents(); fCanvas->Update(); return 0; } //______________________________________________________________________________ int ProcessOptionString(TString arguments) { //process passed options stringMap* options = AliOptionParser::TokenizeOptionString(arguments); int nOptions = 0; for (stringMap::iterator i=options->begin(); i!=options->end(); ++i) { //Printf(" %s : %s", i->first.data(), i->second.data()); const TString& option = i->first; const TString& value = i->second; if (option.EqualTo("PollInterval") || option.EqualTo("sleep")) { fPollInterval = round(value.Atof()*1e6); } else if (option.EqualTo("PollTimeout") || option.EqualTo("timeout")) { fPollTimeout = round(value.Atof()*1e3); } else if (option.EqualTo("ZMQconfigIN") || option.EqualTo("in") ) { fZMQconfigIN = value; } else if (option.EqualTo("Verbose")) { fVerbose=kTRUE; } else if (option.EqualTo("select")) { delete fSelectionRegexp; fSelectionRegexp=new TPRegexp(value); } else if (option.EqualTo("drawoptions")) { fDrawOptions = value; } else if (option.EqualTo("file")) { fFileName = value; } else { nOptions=-1; break; } nOptions++; } delete options; //tidy up return nOptions; } <|endoftext|>
<commit_before>#include <getopt.h> #include "slave.hpp" #include "slave_webui.hpp" #include "zookeeper_slave.hpp" using namespace std; using namespace nexus::internal::slave; void usage(const char *programName) { cerr << "Usage: " << programName << " [--cpus NUM]" << " [--mem NUM]" << " [--isolation TYPE]" << " [--zookeeper host:port]" << " [--quiet]" << " <master_pid>" << endl; } int main(int argc, char **argv) { if (argc == 2 && string("--help") == argv[1]) { usage(argv[0]); exit(1); } option options[] = { {"cpus", required_argument, 0, 'c'}, {"mem", required_argument, 0, 'm'}, {"isolation", required_argument, 0, 'i'}, {"zookeeper", required_argument, 0, 'z'}, {"quiet", no_argument, 0, 'q'}, }; Resources resources(1, 1 * Gigabyte); string isolation = "process"; string zookeeper = ""; bool quiet = false; int opt; int index; while ((opt = getopt_long(argc, argv, "c:m:i:z:q", options, &index)) != -1) { switch (opt) { case 'c': resources.cpus = atoi(optarg); break; case 'm': resources.mem = atoll(optarg); break; case 'i': isolation = optarg; break; case 'z': zookeeper = optarg; break; case 'q': quiet = true; break; case '?': // Error parsing options; getopt prints an error message, so just exit exit(1); break; default: break; } } if (!quiet) google::SetStderrLogging(google::INFO); else if (isFT) LeaderDetector::setQuiet(true); FLAGS_logbufsecs = 1; google::InitGoogleLogging(argv[0]); // Check that we either have zookeeper as an argument or exactly one // non-option argument (i.e., the master PID). if (zookeeper.empty() && optind != argc - 1) { usage(argv[0]); exit(1); } // Resolve the master PID. PID master; if (!zookeeper.empty()) { Process::wait(Process::spawn(new ZooKeeperProcessForSlave(zookeeper))); master = make_pid(ZooKeeperProcessForSlave::master.c_str()); } else { istringstream iss(argv[optind]); if (!(iss >> master)) { cerr << "Failed to resolve master PID " << argv[optind] << endl; exit(1); } } LOG(INFO) << "Build: " << BUILD_DATE << " by " << BUILD_USER; LOG(INFO) << "Starting Nexus slave"; Slave* slave = new Slave(master, resources, false, isolation); PID pid = Process::spawn(slave); #ifdef NEXUS_WEBUI startSlaveWebUI(pid); #endif Process::wait(pid); return 0; } <commit_msg>bug fix needed to make everything compile<commit_after>#include <getopt.h> #include "slave.hpp" #include "slave_webui.hpp" #include "zookeeper_slave.hpp" using namespace std; using namespace nexus::internal::slave; void usage(const char *programName) { cerr << "Usage: " << programName << " [--cpus NUM]" << " [--mem NUM]" << " [--isolation TYPE]" << " [--zookeeper host:port]" << " [--quiet]" << " <master_pid>" << endl; } int main(int argc, char **argv) { if (argc == 2 && string("--help") == argv[1]) { usage(argv[0]); exit(1); } option options[] = { {"cpus", required_argument, 0, 'c'}, {"mem", required_argument, 0, 'm'}, {"isolation", required_argument, 0, 'i'}, {"zookeeper", required_argument, 0, 'z'}, {"quiet", no_argument, 0, 'q'}, }; Resources resources(1, 1 * Gigabyte); string isolation = "process"; string zookeeper = ""; bool quiet = false; int opt; int index; while ((opt = getopt_long(argc, argv, "c:m:i:z:q", options, &index)) != -1) { switch (opt) { case 'c': resources.cpus = atoi(optarg); break; case 'm': resources.mem = atoll(optarg); break; case 'i': isolation = optarg; break; case 'z': zookeeper = optarg; break; case 'q': quiet = true; break; case '?': // Error parsing options; getopt prints an error message, so just exit exit(1); break; default: break; } } if (!quiet) google::SetStderrLogging(google::INFO); else LeaderDetector::setQuiet(true); FLAGS_logbufsecs = 1; google::InitGoogleLogging(argv[0]); // Check that we either have zookeeper as an argument or exactly one // non-option argument (i.e., the master PID). if (zookeeper.empty() && optind != argc - 1) { usage(argv[0]); exit(1); } // Resolve the master PID. PID master; if (!zookeeper.empty()) { Process::wait(Process::spawn(new ZooKeeperProcessForSlave(zookeeper))); master = make_pid(ZooKeeperProcessForSlave::master.c_str()); } else { istringstream iss(argv[optind]); if (!(iss >> master)) { cerr << "Failed to resolve master PID " << argv[optind] << endl; exit(1); } } LOG(INFO) << "Build: " << BUILD_DATE << " by " << BUILD_USER; LOG(INFO) << "Starting Nexus slave"; Slave* slave = new Slave(master, resources, false, isolation); PID pid = Process::spawn(slave); #ifdef NEXUS_WEBUI startSlaveWebUI(pid); #endif Process::wait(pid); return 0; } <|endoftext|>
<commit_before> #include "../SocketCanPump.hpp" #include "../HuboDescription.hpp" #include "HuboState/State.hpp" #include "HuboCmd/Aggregator.hpp" #include "HuboCmd/AuxReceiver.hpp" using namespace HuboCan; int main(int argc, char* argv[]) { bool virtual_can = false; for(int i=1; i<argc; ++i) { if(strcmp(argv[i],"virtual")==0) { virtual_can = true; } } SocketCanPump can(200, 1e6, 2, virtual_can); HuboDescription desc; if(!desc.parseFile("../HuboCan/devices/DrcHubo.dd")) { std::cout << "Description could not be correctly parsed! Quitting!" << std::endl; return 1; } desc.broadcastInfo(); can.load_description(desc); HuboState::State state(desc); HuboCmd::Aggregator agg(desc); HuboCmd::AuxReceiver aux(&desc); std::cout << state.joints << "\n\n" << std::endl; for(size_t i=0; i<desc.jmcs.size(); ++i) { desc.jmcs[i]->assign_pointers(&agg, &state); } if(!state.initialized()) { std::cout << "State was not initialized correctly, so we are quitting.\n" << " -- Either your ach channels are not open" << " or your HuboDescription was not valid!\n" << std::endl; return 2; } agg.run(); size_t iter=0, count=1; while(can.pump()) { // std::cout << std::endl; state.publish(); aux.update(); agg.update(); if(iter > 600) { bool missed_one = false; for(size_t i=0; i<desc.joints.size(); ++i) { if(desc.joints[i]->dropped_count > 0 && !virtual_can) { std::cout << "Dropped " << desc.joints[i]->info.name << ":" << desc.joints[i]->dropped_count << "\t"; missed_one = true; } } if(missed_one) std::cout << std::endl; iter = 0; } // bool missed_one = false; // for(size_t i=0; i<desc.joints.size(); ++i) // { // if(!desc.joints[i]->updated) // { // std::cout << "Dropped " << desc.joints[i]->info.name << ":" // << desc.joints[i]->dropped_count << "\t"; // missed_one = true; // } // } // if(missed_one) // std::cout << std::endl; ++iter; ++count; } return 0; } <commit_msg>testing command sending<commit_after> #include "../SocketCanPump.hpp" #include "../HuboDescription.hpp" #include "HuboState/State.hpp" #include "HuboCmd/Aggregator.hpp" #include "HuboCmd/AuxReceiver.hpp" using namespace HuboCan; int main(int argc, char* argv[]) { bool virtual_can = false; for(int i=1; i<argc; ++i) { if(strcmp(argv[i],"virtual")==0) { virtual_can = true; } } SocketCanPump can(200, 1e6, 2, virtual_can); HuboDescription desc; if(!desc.parseFile("../HuboCan/devices/DrcHubo.dd")) { std::cout << "Description could not be correctly parsed! Quitting!" << std::endl; return 1; } desc.broadcastInfo(); can.load_description(desc); HuboState::State state(desc); HuboCmd::Aggregator agg(desc); HuboCmd::AuxReceiver aux(&desc); std::cout << state.joints << "\n\n" << std::endl; for(size_t i=0; i<desc.jmcs.size(); ++i) { desc.jmcs[i]->assign_pointers(&agg, &state); } if(!state.initialized()) { std::cout << "State was not initialized correctly, so we are quitting.\n" << " -- Either your ach channels are not open" << " or your HuboDescription was not valid!\n" << std::endl; return 2; } agg.run(); size_t iter=0, count=1; while(can.pump()) { // std::cout << std::endl; state.publish(); aux.update(); agg.update(); if(iter > 3000) { bool missed_one = false; for(size_t i=0; i<desc.joints.size(); ++i) { std::cout << " ----------------------------------- " << std::endl; if(desc.joints[i]->dropped_count > 0 && !virtual_can) { std::cout << desc.joints[i]->info.name << ":" << desc.joints[i]->dropped_count << "(" << desc.joints[i]->dropped_count/count << ")" << "\t"; missed_one = true; } } if(missed_one) std::cout << std::endl; iter = 0; } // bool missed_one = false; // for(size_t i=0; i<desc.joints.size(); ++i) // { // if(!desc.joints[i]->updated) // { // std::cout << "Dropped " << desc.joints[i]->info.name << ":" // << desc.joints[i]->dropped_count << "\t"; // missed_one = true; // } // } // if(missed_one) // std::cout << std::endl; ++iter; ++count; } return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: transactionguard.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: obo $ $Date: 2006-09-16 14:14:21 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_framework.hxx" //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #ifndef __FRAMEWORK_THREADHELP_TRANSACTIONGUARD_HXX_ #include <threadhelp/transactionguard.hxx> #endif //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ //_________________________________________________________________________________________________________________ // other includes //_________________________________________________________________________________________________________________ //_________________________________________________________________________________________________________________ // const //_________________________________________________________________________________________________________________ //_________________________________________________________________________________________________________________ // namespace //_________________________________________________________________________________________________________________ namespace framework{ //_________________________________________________________________________________________________________________ // non exported const //_________________________________________________________________________________________________________________ //_________________________________________________________________________________________________________________ // non exported declarations //_________________________________________________________________________________________________________________ //_________________________________________________________________________________________________________________ // definitions //_________________________________________________________________________________________________________________ /*-************************************************************************************************************//** @short ctors @descr Use these ctor methods to initialize the guard right. Given reference must be valid - otherwise crashes could occure! @attention It's not neccessary to lock any mutex here! Because a ctor should not be called from different threads at the same time ... this class use no refcount mechanism! @seealso - @param "pManager" pointer to transaction manager for using to register a request @param "rManager" same as reference @param "eMode" enable/disable throwing of exceptions for rejected calls @param "eReason" returns reason for rejected calls if "eMode=E_NOEXCEPTIONS"! @return - @onerror - *//*-*************************************************************************************************************/ TransactionGuard::TransactionGuard( ITransactionManager* pManager, EExceptionMode eMode, ERejectReason* eReason ) : m_pManager( pManager ) { // If exception mode is set to E_HARDEXCETIONS we don't need a buffer to return reason! // We handle it private. If a call is rejected, our manager throw some exceptions ... and the reason // could be ignorable ... if( eReason == NULL ) { ERejectReason eMyReason; m_pManager->acquire( eMode, eMyReason ); } else { m_pManager->acquire( eMode, *eReason ); } } //***************************************************************************************************************** TransactionGuard::TransactionGuard( ITransactionManager& rManager, EExceptionMode eMode, ERejectReason* eReason ) : m_pManager( &rManager ) { // If exception mode is set to E_HARDEXCETIONS we don't need a buffer to return reason! // We handle it private. If a call is rejected, our manager throw some exceptions ... and the reason // could be ignorable ... if( eReason == NULL ) { ERejectReason eMyReason; m_pManager->acquire( eMode, eMyReason ); } else { m_pManager->acquire( eMode, *eReason ); } } /*-************************************************************************************************************//** @short dtor @descr We must release the transaction manager and can forget his pointer. @seealso - @param - @return - @onerror - *//*-*************************************************************************************************************/ TransactionGuard::~TransactionGuard() { stop(); } /*-************************************************************************************************************//** @short stop current transaction @descr We must release the transaction manager and can forget his pointer. @attention We don't support any start() method here - because it is not easy to detect if a transaction already started or not! (combination of EExceptionMode and ERejectReason) @seealso - @param - @return - @onerror - *//*-*************************************************************************************************************/ void TransactionGuard::stop() { if( m_pManager != NULL ) { m_pManager->release(); m_pManager = NULL; } } } // namespace framework <commit_msg>INTEGRATION: CWS changefileheader (1.3.262); FILE MERGED 2008/04/01 10:58:14 thb 1.3.262.2: #i85898# Stripping all external header guards 2008/03/28 15:35:30 rt 1.3.262.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: transactionguard.cxx,v $ * $Revision: 1.4 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_framework.hxx" //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #include <threadhelp/transactionguard.hxx> //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ //_________________________________________________________________________________________________________________ // other includes //_________________________________________________________________________________________________________________ //_________________________________________________________________________________________________________________ // const //_________________________________________________________________________________________________________________ //_________________________________________________________________________________________________________________ // namespace //_________________________________________________________________________________________________________________ namespace framework{ //_________________________________________________________________________________________________________________ // non exported const //_________________________________________________________________________________________________________________ //_________________________________________________________________________________________________________________ // non exported declarations //_________________________________________________________________________________________________________________ //_________________________________________________________________________________________________________________ // definitions //_________________________________________________________________________________________________________________ /*-************************************************************************************************************//** @short ctors @descr Use these ctor methods to initialize the guard right. Given reference must be valid - otherwise crashes could occure! @attention It's not neccessary to lock any mutex here! Because a ctor should not be called from different threads at the same time ... this class use no refcount mechanism! @seealso - @param "pManager" pointer to transaction manager for using to register a request @param "rManager" same as reference @param "eMode" enable/disable throwing of exceptions for rejected calls @param "eReason" returns reason for rejected calls if "eMode=E_NOEXCEPTIONS"! @return - @onerror - *//*-*************************************************************************************************************/ TransactionGuard::TransactionGuard( ITransactionManager* pManager, EExceptionMode eMode, ERejectReason* eReason ) : m_pManager( pManager ) { // If exception mode is set to E_HARDEXCETIONS we don't need a buffer to return reason! // We handle it private. If a call is rejected, our manager throw some exceptions ... and the reason // could be ignorable ... if( eReason == NULL ) { ERejectReason eMyReason; m_pManager->acquire( eMode, eMyReason ); } else { m_pManager->acquire( eMode, *eReason ); } } //***************************************************************************************************************** TransactionGuard::TransactionGuard( ITransactionManager& rManager, EExceptionMode eMode, ERejectReason* eReason ) : m_pManager( &rManager ) { // If exception mode is set to E_HARDEXCETIONS we don't need a buffer to return reason! // We handle it private. If a call is rejected, our manager throw some exceptions ... and the reason // could be ignorable ... if( eReason == NULL ) { ERejectReason eMyReason; m_pManager->acquire( eMode, eMyReason ); } else { m_pManager->acquire( eMode, *eReason ); } } /*-************************************************************************************************************//** @short dtor @descr We must release the transaction manager and can forget his pointer. @seealso - @param - @return - @onerror - *//*-*************************************************************************************************************/ TransactionGuard::~TransactionGuard() { stop(); } /*-************************************************************************************************************//** @short stop current transaction @descr We must release the transaction manager and can forget his pointer. @attention We don't support any start() method here - because it is not easy to detect if a transaction already started or not! (combination of EExceptionMode and ERejectReason) @seealso - @param - @return - @onerror - *//*-*************************************************************************************************************/ void TransactionGuard::stop() { if( m_pManager != NULL ) { m_pManager->release(); m_pManager = NULL; } } } // namespace framework <|endoftext|>
<commit_before>/************************************************************ COSC 501 Elliott Plack 13 NOV 2013 Due: 18 NOV 2013 Problem: Develop three functions that must satisfy the Big-O requirements as shown below 1. Develop a function that uses a loop to calculate x^n in O(n) 2. Develop a function that recursively calculates x^n in O(n) 3. Develop a function that recursively calculates x^n in O(log n) 4. Develop a function that has O(2^n) time complexity. Algorithm: Write various loops to satisfy requirements. For the final problem implement a timer to test. ************************************************************/ #include <iostream> #include <time.h> using namespace std; double loopSimple (double,int); // simple loop function double loopRecursion (double,int); // loop using recursion double loopRecursLog (double,int); // loop using recursion and log n void loopExponential (int); // loop using o(2^n) which may take a long time to run. int main () { double x = 0, simpleResult = 0, recursiveResult = 0, recLogNResult = 0; // variables int n = 0, choice = 0; double durationSimple = 0, durationRecursive = 0, durationLogN = 0, durationExpon = 0; // for the clock cout << "To process big O notation for x and n: press 1\n" << "To illustrate time complexity of 2^n : press 2\n"; cin >> choice; switch (choice) { case 1: // big O notation prob. input x & n and all three things will calculate cout << "Enter a value for x and n to process big O notation for. \n"; cout << "Enter x: "; cin >> x; cout << "Enter n: "; cin >> n; // first function //start clock clock_t startSimple; startSimple = clock(); // run function simpleResult = loopSimple(x, n); // go // end clock durationSimple = (clock() - startSimple ) / (double) CLOCKS_PER_SEC; // second function //start clock clock_t startRecurs; startRecurs = clock(); // run function recursiveResult = loopRecursion(x, n); // go // end clock durationRecursive = (clock() - startRecurs ) / (double) CLOCKS_PER_SEC; // third function //start clock clock_t startLogN; startLogN = clock(); // run function recLogNResult = loopRecursLog(x, n); // go // end clock durationLogN = (clock() - startLogN ) / (double) CLOCKS_PER_SEC; cout // all on next line for visualization << "1. Using a loop to calculate x^n yields ........... " << simpleResult << ", which took " << durationSimple << " seconds.\n" << "2. Recursively calculating x^n yields ............. " << recursiveResult << ", which took " << durationRecursive << " seconds.\n" << "3. Recursively calculating x^n using logn yields .. " << recLogNResult << ", which took " << durationLogN << " seconds.\n"; break; case 2: // time complexity, may take a while cout << "Enter a value for n to test time complexity for 2^n: "; cin >> n; //start clock clock_t startExp; startExp = clock(); // run function loopExponential(n); // end clock durationExpon = (clock() - startExp ) / (double) CLOCKS_PER_SEC; cout << "This took " << durationExpon << " seconds.\n"; break; default: break; } return 0; // end } double loopSimple (double x,int n) // simple exponential loop { double result = 1; for (int i = 0; i < n; i++) { result = x * result; } return result; } double loopRecursion (double x,int n) // loop using recursion { if ( n == 0 ) return 1; else return x * loopRecursion (x, n - 1); // call of function in function is recursive } double loopRecursLog (double x,int n) // more efficient calculation because the possibility is cut in half each time { if ( n == 0 ) { return 1; } else if ( n == 1 ) return x; else if (n % 2 == 0) return loopRecursLog (x*x, n/2); else return loopRecursLog (x*x, n/2) * x; } void loopExponential (int n) // long long loop to calculate exponential, can take a long time. { double power = 1, result = 0; double j = 1, k = 1; for(j=1; j <= n; j++) { power = power * 2; for(k=1; k<= power; k++) cout << k << endl; } }<commit_msg>format of header<commit_after>/******************************************************************** COSC 501 Elliott Plack 13 NOV 2013 Due: 18 NOV 2013 Problem: Develop three functions that must satisfy the Big-O requirements as shown below 1. Develop a function that uses a loop to calculate x^n in O(n) 2. Develop a function that recursively calculates x^n in O(n) 3. Develop a function that recursively calculates x^n in O(log n) 4. Develop a function that has O(2^n) time complexity. Algorithm: Write various loops to satisfy requirements. For the final problem implement a timer to test. **********************************************************************/ #include <iostream> #include <time.h> using namespace std; double loopSimple (double,int); // simple loop function double loopRecursion (double,int); // loop using recursion double loopRecursLog (double,int); // loop using recursion and log n void loopExponential (int); // loop using o(2^n) which may take a long time to run. int main () { double x = 0, simpleResult = 0, recursiveResult = 0, recLogNResult = 0; // variables int n = 0, choice = 0; double durationSimple = 0, durationRecursive = 0, durationLogN = 0, durationExpon = 0; // for the clock cout << "To process big O notation for x and n: press 1\n" << "To illustrate time complexity of 2^n : press 2\n"; cin >> choice; switch (choice) { case 1: // big O notation prob. input x & n and all three things will calculate cout << "Enter a value for x and n to process big O notation for. \n"; cout << "Enter x: "; cin >> x; cout << "Enter n: "; cin >> n; // first function //start clock clock_t startSimple; startSimple = clock(); // run function simpleResult = loopSimple(x, n); // go // end clock durationSimple = (clock() - startSimple ) / (double) CLOCKS_PER_SEC; // second function //start clock clock_t startRecurs; startRecurs = clock(); // run function recursiveResult = loopRecursion(x, n); // go // end clock durationRecursive = (clock() - startRecurs ) / (double) CLOCKS_PER_SEC; // third function //start clock clock_t startLogN; startLogN = clock(); // run function recLogNResult = loopRecursLog(x, n); // go // end clock durationLogN = (clock() - startLogN ) / (double) CLOCKS_PER_SEC; cout // all on next line for visualization << "1. Using a loop to calculate x^n yields ........... " << simpleResult << ", which took " << durationSimple << " seconds.\n" << "2. Recursively calculating x^n yields ............. " << recursiveResult << ", which took " << durationRecursive << " seconds.\n" << "3. Recursively calculating x^n using logn yields .. " << recLogNResult << ", which took " << durationLogN << " seconds.\n"; break; case 2: // time complexity, may take a while cout << "Enter a value for n to test time complexity for 2^n: "; cin >> n; //start clock clock_t startExp; startExp = clock(); // run function loopExponential(n); // end clock durationExpon = (clock() - startExp ) / (double) CLOCKS_PER_SEC; cout << "This took " << durationExpon << " seconds.\n"; break; default: break; } return 0; // end } double loopSimple (double x,int n) // simple exponential loop { double result = 1; for (int i = 0; i < n; i++) { result = x * result; } return result; } double loopRecursion (double x,int n) // loop using recursion { if ( n == 0 ) return 1; else return x * loopRecursion (x, n - 1); // call of function in function is recursive } double loopRecursLog (double x,int n) // more efficient calculation because the possibility is cut in half each time { if ( n == 0 ) { return 1; } else if ( n == 1 ) return x; else if (n % 2 == 0) return loopRecursLog (x*x, n/2); else return loopRecursLog (x*x, n/2) * x; } void loopExponential (int n) // long long loop to calculate exponential, can take a long time. { double power = 1, result = 0; double j = 1, k = 1; for(j=1; j <= n; j++) { power = power * 2; for(k=1; k<= power; k++) cout << k << endl; } }<|endoftext|>
<commit_before>/** * @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may find a copy of the License in the LICENCE file. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @file JPetCmdParser.cpp */ #include "JPetCmdParser.h" #include <iostream> #include "../CommonTools/CommonTools.h" #include "../JPetLoggerInclude.h" JPetCmdParser::JPetCmdParser(): fOptionsDescriptions("Allowed options") { std::vector<int> tmp; tmp.push_back(-1); tmp.push_back(-1); fOptionsDescriptions.add_options() ("help,h", "produce help message") ("type,t", po::value<std::string>()->required()->implicit_value(""), "type of file: hld, root or scope") ("file,f", po::value< std::vector<std::string> >()->required()->multitoken(), "File(s) to open") ("range,r", po::value< std::vector<int> >()->multitoken()->default_value(tmp, ""), "Range of events to process.") ("param,p", po::value<std::string>(), "File with TRB numbers.") ("runId,i", po::value<int>(), "Run id.") ("progressBar,b", "Progress bar.") ("localDB,l", po::value<std::string>(), "The file to use as the parameter database.") ("localDBCreate,L", po::value<std::string>(), "Where to save the parameter database."); } JPetCmdParser::~JPetCmdParser() { /**/ } std::vector<JPetOptions> JPetCmdParser::parseAndGenerateOptions(int argc, const char** argv) { po::variables_map variablesMap; if (argc == 1) { ERROR("No options provided."); std::cerr << "No options provided" << "\n"; std::cerr << getOptionsDescription() << "\n"; exit(-1); } po::store(po::parse_command_line(argc, argv, fOptionsDescriptions), variablesMap); /* print out help */ if (variablesMap.count("help")) { std::cout << getOptionsDescription() << "\n"; exit(0); } po::notify(variablesMap); if (!areCorrectOptions(variablesMap)) { exit(-1); } return generateOptions(variablesMap); } bool JPetCmdParser::areCorrectOptions(const po::variables_map& variablesMap) const { /* Parse range of events */ if (variablesMap.count("range")) { if (variablesMap["range"].as< std::vector<int> >().size() != 2) { ERROR("Wrong number of bounds in range."); std::cerr << "Wrong number of bounds in range: " << variablesMap["range"].as< std::vector<int> >().size() << std::endl; return false; } if ( variablesMap["range"].as< std::vector<int> >()[0] > variablesMap["range"].as< std::vector<int> >()[1]) { ERROR("Wrong range of events."); std::cerr << "Wrong range of events." << std::endl; return false; } } if (!isCorrectFileType(getFileType(variablesMap))) { ERROR("Wrong type of file."); std::cerr << "Wrong type of file: " << getFileType(variablesMap) << std::endl; std::cerr << "Possible options: hld, root or scope" << std::endl; return false; } if (isRunNumberSet(variablesMap)) { int l_runId = variablesMap["runId"].as<int>(); if (l_runId <= 0) { ERROR("Wrong number of run id."); std::cerr << "Wrong number of run id: " << l_runId << std::endl; return false; } } if (isProgressBarSet(variablesMap)) { int l_progressBar = variablesMap["progressBar"].as<int>(); if (l_progressBar != 0 && l_progressBar != 1) { ERROR("Wrong parameter of progressbar."); std::cerr << "Wrong parameter of progressbar: " << l_progressBar << std::endl; return false; } } if (isLocalDBSet(variablesMap)) { std::string localDBName = getLocalDBName(variablesMap); if ( ! CommonTools::ifFileExisting(localDBName) ) { ERROR("File : " + localDBName + " does not exist."); std::cerr << "File : " << localDBName << " does not exist" << std::endl; return false; } } std::vector<std::string> fileNames(variablesMap["file"].as< std::vector<std::string> >()); for (unsigned int i = 0; i < fileNames.size(); i++) { if ( ! CommonTools::ifFileExisting(fileNames[i]) ) { std::string fileName = fileNames[i]; ERROR("File : " + fileName + " does not exist."); std::cerr << "File : " << fileNames[i] << " does not exist" << std::endl; return false; } } return true; } std::vector<JPetOptions> JPetCmdParser::generateOptions(const po::variables_map& optsMap) const { std::map<std::string, std::string> options = JPetOptions::getDefaultOptions(); auto fileType = getFileType(optsMap); if (isCorrectFileType(fileType)) { options.at("inputFileType") = fileType; } if (isRunNumberSet(optsMap)) { options.at("runId") = std::to_string(getRunNumber(optsMap)); } if (isProgressBarSet(optsMap)) { options.at("progressBar") = "true"; } if (isLocalDBSet(optsMap)) { options["localDB"] = getLocalDBName(optsMap); } if (isLocalDBCreateSet(optsMap)) { options["localDBCreate"] = getLocalDBCreateName(optsMap); } auto firstEvent = getLowerEventBound(optsMap); auto lastEvent = getHigherEventBound(optsMap); if (firstEvent >= 0) options.at("firstEvent") = std::to_string(firstEvent); if (lastEvent >= 0) options.at("lastEvent") = std::to_string(lastEvent); auto files = getFileNames(optsMap); std::vector<JPetOptions> optionContainer; for (auto file :files) { options.at("inputFile") = file; optionContainer.push_back(JPetOptions(options)); } return optionContainer; } //#endif /* __CINT__ */ <commit_msg>Add JPetScopeReaderConfigParser application to JPetCmdParser.<commit_after>/** * @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may find a copy of the License in the LICENCE file. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @file JPetCmdParser.cpp */ #include "JPetCmdParser.h" #include <iostream> #include "../CommonTools/CommonTools.h" #include "../JPetLoggerInclude.h" #include "../JPetScopeReaderConfigParser/JPetScopeReaderConfigParser.h" JPetCmdParser::JPetCmdParser(): fOptionsDescriptions("Allowed options") { std::vector<int> tmp; tmp.push_back(-1); tmp.push_back(-1); fOptionsDescriptions.add_options() ("help,h", "produce help message") ("type,t", po::value<std::string>()->required()->implicit_value(""), "type of file: hld, root or scope") ("file,f", po::value< std::vector<std::string> >()->required()->multitoken(), "File(s) to open") ("range,r", po::value< std::vector<int> >()->multitoken()->default_value(tmp, ""), "Range of events to process.") ("param,p", po::value<std::string>(), "File with TRB numbers.") ("runId,i", po::value<int>(), "Run id.") ("progressBar,b", "Progress bar.") ("localDB,l", po::value<std::string>(), "The file to use as the parameter database.") ("localDBCreate,L", po::value<std::string>(), "Where to save the parameter database."); } JPetCmdParser::~JPetCmdParser() { /**/ } std::vector<JPetOptions> JPetCmdParser::parseAndGenerateOptions(int argc, const char** argv) { po::variables_map variablesMap; if (argc == 1) { ERROR("No options provided."); std::cerr << "No options provided" << "\n"; std::cerr << getOptionsDescription() << "\n"; exit(-1); } po::store(po::parse_command_line(argc, argv, fOptionsDescriptions), variablesMap); /* print out help */ if (variablesMap.count("help")) { std::cout << getOptionsDescription() << "\n"; exit(0); } po::notify(variablesMap); if (!areCorrectOptions(variablesMap)) { exit(-1); } return generateOptions(variablesMap); } bool JPetCmdParser::areCorrectOptions(const po::variables_map& variablesMap) const { /* Parse range of events */ if (variablesMap.count("range")) { if (variablesMap["range"].as< std::vector<int> >().size() != 2) { ERROR("Wrong number of bounds in range."); std::cerr << "Wrong number of bounds in range: " << variablesMap["range"].as< std::vector<int> >().size() << std::endl; return false; } if ( variablesMap["range"].as< std::vector<int> >()[0] > variablesMap["range"].as< std::vector<int> >()[1]) { ERROR("Wrong range of events."); std::cerr << "Wrong range of events." << std::endl; return false; } } if (!isCorrectFileType(getFileType(variablesMap))) { ERROR("Wrong type of file."); std::cerr << "Wrong type of file: " << getFileType(variablesMap) << std::endl; std::cerr << "Possible options: hld, root or scope" << std::endl; return false; } if (isRunNumberSet(variablesMap)) { int l_runId = variablesMap["runId"].as<int>(); if (l_runId <= 0) { ERROR("Wrong number of run id."); std::cerr << "Wrong number of run id: " << l_runId << std::endl; return false; } } if (isProgressBarSet(variablesMap)) { int l_progressBar = variablesMap["progressBar"].as<int>(); if (l_progressBar != 0 && l_progressBar != 1) { ERROR("Wrong parameter of progressbar."); std::cerr << "Wrong parameter of progressbar: " << l_progressBar << std::endl; return false; } } if (isLocalDBSet(variablesMap)) { std::string localDBName = getLocalDBName(variablesMap); if ( ! CommonTools::ifFileExisting(localDBName) ) { ERROR("File : " + localDBName + " does not exist."); std::cerr << "File : " << localDBName << " does not exist" << std::endl; return false; } } std::vector<std::string> fileNames(variablesMap["file"].as< std::vector<std::string> >()); for (unsigned int i = 0; i < fileNames.size(); i++) { if ( ! CommonTools::ifFileExisting(fileNames[i]) ) { std::string fileName = fileNames[i]; ERROR("File : " + fileName + " does not exist."); std::cerr << "File : " << fileNames[i] << " does not exist" << std::endl; return false; } } return true; } std::vector<JPetOptions> JPetCmdParser::generateOptions(const po::variables_map& optsMap) const { std::map<std::string, std::string> options = JPetOptions::getDefaultOptions(); auto fileType = getFileType(optsMap); if (isCorrectFileType(fileType)) { options.at("inputFileType") = fileType; } if (isRunNumberSet(optsMap)) { options.at("runId") = std::to_string(getRunNumber(optsMap)); } if (isProgressBarSet(optsMap)) { options.at("progressBar") = "true"; } if (isLocalDBSet(optsMap)) { options["localDB"] = getLocalDBName(optsMap); } if (isLocalDBCreateSet(optsMap)) { options["localDBCreate"] = getLocalDBCreateName(optsMap); } auto firstEvent = getLowerEventBound(optsMap); auto lastEvent = getHigherEventBound(optsMap); if (firstEvent >= 0) options.at("firstEvent") = std::to_string(firstEvent); if (lastEvent >= 0) options.at("lastEvent") = std::to_string(lastEvent); /* TODO : Uncomment code if (fileType.compare("scope") == 0) { string inputConfigJsonFileNameTest = "unitTestData/JPetScopeReaderConfigParserTest/example.json"; //TODO Set proper filename JPetScopeReaderConfigParser scopeReaderConfigParser; scopeReaderConfigParser.readData(inputConfigJsonFileNameTest); string scopeFileName = scopeReaderConfigParser.getFileName(); vector<int> scopePositions = scopeReaderConfigParser.getPositions(); options.emplace("scopeFileName", scopeFileName); unsigned int scopePositionNumber = 0; std::string scopePosition = ""; for(auto &position: scopePositions) { ++scopePositionNumber; scopePosition = "scopePosition" + std::to_string(scopePositionNumber); options.emplace(scopePosition, std::to_string(position)); } } */ auto files = getFileNames(optsMap); std::vector<JPetOptions> optionContainer; for (auto file :files) { options.at("inputFile") = file; optionContainer.push_back(JPetOptions(options)); } return optionContainer; } //#endif /* __CINT__ */ <|endoftext|>
<commit_before>#include <opencv2/opencv.hpp> #include <iostream> #include <math.h> float mediandepth(const cv::Mat &m, double bgcoeff) { std::vector<float> depths; depths.reserve(m.cols*m.rows); // Collect all non-nan values. for(size_t y = 0 ; y < m.rows ; ++y) { const float *pix = m.ptr<float>(y); for(size_t x = 0 ; x < m.cols ; ++x, ++pix) { if(!isnan(*pix)) { depths.push_back(*pix); } } } // Sort the first half. std::nth_element(depths.begin(), depths.begin() + depths.size() * bgcoeff, depths.end()); // And there we can access the median. return depths[depths.size() * bgcoeff]; } void subtractbg(cv::Mat &rgb, const cv::Mat &d, float thresh, float bgcoeff) { // We require this, otherwise there's no correspondence! // TODO: Fail better. if(rgb.rows != d.rows || rgb.cols != d.cols) { std::cerr << "Oops from `subtractbg`." << std::endl; return; } float md = mediandepth(d, bgcoeff); std::cout << "Median depth: " << md << std::endl; for(size_t y = 0 ; y < d.rows ; ++y) { const float *dpix = d.ptr<float>(y); cv::Vec3b *rgbpix = rgb.ptr<cv::Vec3b>(y); for(size_t x = 0 ; x < d.cols ; ++x, ++dpix, ++rgbpix) { // Replace pixels whose depth is too far or nan with 0. if(md+thresh < *dpix || isnan(*dpix)) { (*rgbpix)[0] = (*rgbpix)[1] = (*rgbpix)[2] = 0; } } } } <commit_msg>Stop printing median depth.<commit_after>#include <opencv2/opencv.hpp> #include <iostream> #include <math.h> float mediandepth(const cv::Mat &m, double bgcoeff) { std::vector<float> depths; depths.reserve(m.cols*m.rows); // Collect all non-nan values. for(size_t y = 0 ; y < m.rows ; ++y) { const float *pix = m.ptr<float>(y); for(size_t x = 0 ; x < m.cols ; ++x, ++pix) { if(!isnan(*pix)) { depths.push_back(*pix); } } } // Sort the first half. std::nth_element(depths.begin(), depths.begin() + depths.size() * bgcoeff, depths.end()); // And there we can access the median. return depths[depths.size() * bgcoeff]; } void subtractbg(cv::Mat &rgb, const cv::Mat &d, float thresh, float bgcoeff) { // We require this, otherwise there's no correspondence! // TODO: Fail better. if(rgb.rows != d.rows || rgb.cols != d.cols) { std::cerr << "Oops from `subtractbg`." << std::endl; return; } float md = mediandepth(d, bgcoeff); for(size_t y = 0 ; y < d.rows ; ++y) { const float *dpix = d.ptr<float>(y); cv::Vec3b *rgbpix = rgb.ptr<cv::Vec3b>(y); for(size_t x = 0 ; x < d.cols ; ++x, ++dpix, ++rgbpix) { // Replace pixels whose depth is too far or nan with 0. if(md+thresh < *dpix || isnan(*dpix)) { (*rgbpix)[0] = (*rgbpix)[1] = (*rgbpix)[2] = 0; } } } } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * 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$ //mapnik #include <mapnik/symbolizer.hpp> namespace mapnik { symbolizer_with_image::symbolizer_with_image(path_expression_ptr file) : image_filename_( file ) { matrix_[0] = 1.0; matrix_[1] = 0.0; matrix_[2] = 0.0; matrix_[3] = 1.0; matrix_[4] = 0.0; matrix_[5] = 0.0; } symbolizer_with_image::symbolizer_with_image( symbolizer_with_image const& rhs) : image_filename_(rhs.image_filename_), opacity_(rhs.opacity_), matrix_(rhs.matrix_) {} path_expression_ptr symbolizer_with_image::get_filename() const { return image_filename_; } void symbolizer_with_image::set_filename(path_expression_ptr image_filename) { image_filename_ = image_filename; } void symbolizer_with_image::set_transform(transform_type const& matrix) { matrix_ = matrix; } transform_type const& symbolizer_with_image::get_transform() const { return matrix_; } void symbolizer_with_image::set_opacity(float opacity) { opacity_ = opacity; } float symbolizer_with_image::get_opacity() const { return opacity_; } } // end of namespace mapnik <commit_msg>+ fixed ctor<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * 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$ //mapnik #include <mapnik/symbolizer.hpp> namespace mapnik { symbolizer_with_image::symbolizer_with_image(path_expression_ptr file) : image_filename_( file ), opacity_(1.0f) { matrix_[0] = 1.0; matrix_[1] = 0.0; matrix_[2] = 0.0; matrix_[3] = 1.0; matrix_[4] = 0.0; matrix_[5] = 0.0; } symbolizer_with_image::symbolizer_with_image( symbolizer_with_image const& rhs) : image_filename_(rhs.image_filename_), opacity_(rhs.opacity_), matrix_(rhs.matrix_) {} path_expression_ptr symbolizer_with_image::get_filename() const { return image_filename_; } void symbolizer_with_image::set_filename(path_expression_ptr image_filename) { image_filename_ = image_filename; } void symbolizer_with_image::set_transform(transform_type const& matrix) { matrix_ = matrix; } transform_type const& symbolizer_with_image::get_transform() const { return matrix_; } void symbolizer_with_image::set_opacity(float opacity) { opacity_ = opacity; } float symbolizer_with_image::get_opacity() const { return opacity_; } } // end of namespace mapnik <|endoftext|>
<commit_before>/** \file * Implements safer c++ wrappers for the sysctl() interface. */ #ifndef _POWERDXX_SYS_SYSCTL_HPP_ #define _POWERDXX_SYS_SYSCTL_HPP_ #include "error.hpp" /* sys::sc_error */ #include <sys/types.h> /* sysctl() */ #include <sys/sysctl.h> /* sysctl() */ namespace sys { /** * This namespace contains safer c++ wrappers for the sysctl() interface. * * The template class Sysctl represents a sysctl address and offers * handles to retrieve or set the stored value. */ namespace ctl { /** * Management Information Base identifier type (see sysctl(3)). */ typedef int mib_t; /** * Represents a sysctl MIB address. * * @tparam MibDepth * The maximum allowed MIB depth */ template <size_t MibDepth> class Sysctl { private: /** * Stores the MIB address. */ mib_t mib[MibDepth]; public: /** * The default constructor. * * This is available to defer initialisation to a later moment. * This might be useful when initialising global or static * instances by a character string repesented name. */ constexpr Sysctl() : mib{} {} /** * Initialise the MIB address from a character string. * * @param name * The name of the sysctl * @throws sc_error * May throw an exception if the addressed sysct does * not exist or if the address is too long to store */ Sysctl(char const * const name) { size_t length = MibDepth; if (::sysctlnametomib(name, this->mib, &length) == -1) { throw sc_error{errno}; } } /** * Initialise the MIB address directly. * * Some important sysctl values have a fixed address that * can be initialised at compile time with a noexcept guarantee. * * Spliting the MIB address into head and tail makes sure * that `Sysctl(char *)` does not match the template and is * instead implicitly cast to invoke `Sysctl(char const *)`. * * @tparam Tail * The types of the trailing MIB address values (must * be mib_t) * @param head,tail * The mib */ template <typename... Tail> constexpr Sysctl(mib_t const head, Tail const... tail) noexcept : mib{head, tail...} { static_assert(MibDepth >= sizeof...(Tail) + 1, "The number of MIB addresses must not exceed the MIB depth"); } /** * Update the given buffer with a value retrieved from the * sysctl. * * @param buf,bufsize * The target buffer and its size * @throws sc_error * Throws if value retrieval fails or is incomplete, * e.g. because the value does not fit into the target * buffer */ void update(void * const buf, size_t const bufsize) const { auto len = bufsize; if (::sysctl(this->mib, MibDepth, buf, &len, nullptr, 0) == -1) { throw sc_error{errno}; } } /** * Update the given value with a value retreived from the * sysctl. * * @tparam T * The type store the sysctl value in * @param value * A reference to the target value * @throws sc_error * Throws if value retrieval fails or is incomplete, * e.g. because the value does not fit into the target * type */ template <typename T> void update(T & value) const { update(&value, sizeof(T)); } /** * Retrieve an array from the sysctl address. * * This is useful to retrieve variable length sysctls, like * characer strings. * * @tparam T * The type stored in the array * @return * And array of T with the right length to store the * whole sysctl value * @throws sc_error * May throw if the size of the sysctl increases after * the length was queried */ template <typename T> std::unique_ptr<T[]> get() const { size_t len = 0; if (::sysctl(this->mib, MibDepth, nullptr, &len, nullptr, 0) == -1) { throw sc_error{errno}; } auto result = std::unique_ptr<T[]>(new T[len / sizeof(T)]); update(result.get(), len); return result; } /** * Update the the sysctl value with the given buffer. * * @param buf,bufsize * The source buffer * @throws sc_error * If the source buffer cannot be stored in the sysctl */ void set(void const * const buf, size_t const bufsize) { if (::sysctl(this->mib, MibDepth, nullptr, nullptr, buf, bufsize) == -1) { throw sc_error{errno}; } } /** * Update the the sysctl value with the given value. * * @tparam T * The value type * @param value * The value to set the sysctl to */ template <typename T> void set(T const & value) { set(&value, sizeof(T)); } }; template <typename T, class SysctlT> class Sync { private: SysctlT sysctl; public: constexpr Sync(SysctlT const & sysctl) noexcept : sysctl{sysctl} {} Sync & operator =(T const & value) { this->sysctl.set(value); return *this; } operator T () const { T value; this->sysctl.update(value); return value; } }; template <typename T, size_t MibDepth> using SysctlSync = Sync<T, Sysctl<MibDepth>>; template <typename T, class SysctlT> class Once { private: T value; public: Once(T const & value, SysctlT const & sysctl) noexcept { try { sysctl.update(this->value); } catch (sc_error) { this->value = value; } } operator T const &() const { return this->value; } }; template <typename T, size_t MibDepth> using SysctlOnce = Once<T, Sysctl<MibDepth>>; template <typename T, class SysctlT> constexpr Once<T, SysctlT> once(T const & value, SysctlT const & sysctl) noexcept { return {value, sysctl}; } } /* namespace ctl */ } /* namespace sys */ #endif /* _POWERDXX_SYS_SYSCTL_HPP_ */ <commit_msg>Document and rename Sysctl::update() to get()<commit_after>/** \file * Implements safer c++ wrappers for the sysctl() interface. */ #ifndef _POWERDXX_SYS_SYSCTL_HPP_ #define _POWERDXX_SYS_SYSCTL_HPP_ #include "error.hpp" /* sys::sc_error */ #include <sys/types.h> /* sysctl() */ #include <sys/sysctl.h> /* sysctl() */ namespace sys { /** * This namespace contains safer c++ wrappers for the sysctl() interface. * * The template class Sysctl represents a sysctl address and offers * handles to retrieve or set the stored value. */ namespace ctl { /** * Management Information Base identifier type (see sysctl(3)). */ typedef int mib_t; /** * Represents a sysctl MIB address. * * It offers set() and get() methods to access these sysctls. * * There are two ways of initialising a Sysctl instance, by symbolic * name or by directly using the MIB address. The latter one only * makes sense for sysctls with a fixed address, known at compile * time, e.g. `Sysctl<2>{CTL_HW, HW_NCPU}` for "hw.ncpu". Check * `/usr/include/sys/sysctl.h` for predefined MIBs. * * For all other sysctls, symbolic names must be used. E.g. * `Sysctl<4>{"dev.cpu.0.freq"}`. Creating a Sysctl from a symbolic * name may throw. * * A Sysctl instance created with the default constructor is unitialised, * initialisation can be deferred to a later moment by using copy assignment. * This can be used to create globals but construct them inline where * exceptions can be handled. * * @tparam MibDepth * The MIB level, e.g. "hw.ncpu" is two levels deep */ template <size_t MibDepth> class Sysctl { private: /** * Stores the MIB address. */ mib_t mib[MibDepth]; public: /** * The default constructor. * * This is available to defer initialisation to a later moment. * This might be useful when initialising global or static * instances by a character string repesented name. */ constexpr Sysctl() : mib{} {} /** * Initialise the MIB address from a character string. * * @param name * The symbolic name of the sysctl * @throws sc_error * May throw an exception if the addressed sysct does * not exist or if the address is too long to store */ Sysctl(char const * const name) { size_t length = MibDepth; if (::sysctlnametomib(name, this->mib, &length) == -1) { throw sc_error{errno}; } assert(length == MibDepth && "MIB depth mismatch"); } /** * Initialise the MIB address directly. * * Some important sysctl values have a fixed address that * can be initialised at compile time with a noexcept guarantee. * * Spliting the MIB address into head and tail makes sure * that `Sysctl(char *)` does not match the template and is * instead implicitly cast to invoke `Sysctl(char const *)`. * * @tparam Tail * The types of the trailing MIB address values (must * be mib_t) * @param head,tail * The mib */ template <typename... Tail> constexpr Sysctl(mib_t const head, Tail const... tail) noexcept : mib{head, tail...} { static_assert(MibDepth == sizeof...(Tail) + 1, "MIB depth mismatch"); } /** * Update the given buffer with a value retrieved from the * sysctl. * * @param buf,bufsize * The target buffer and its size * @throws sc_error * Throws if value retrieval fails or is incomplete, * e.g. because the value does not fit into the target * buffer */ void get(void * const buf, size_t const bufsize) const { auto len = bufsize; if (::sysctl(this->mib, MibDepth, buf, &len, nullptr, 0) == -1) { throw sc_error{errno}; } } /** * Update the given value with a value retreived from the * sysctl. * * @tparam T * The type store the sysctl value in * @param value * A reference to the target value * @throws sc_error * Throws if value retrieval fails or is incomplete, * e.g. because the value does not fit into the target * type */ template <typename T> void get(T & value) const { get(&value, sizeof(T)); } /** * Retrieve an array from the sysctl address. * * This is useful to retrieve variable length sysctls, like * characer strings. * * @tparam T * The type stored in the array * @return * And array of T with the right length to store the * whole sysctl value * @throws sc_error * May throw if the size of the sysctl increases after * the length was queried */ template <typename T> std::unique_ptr<T[]> get() const { size_t len = 0; if (::sysctl(this->mib, MibDepth, nullptr, &len, nullptr, 0) == -1) { throw sc_error{errno}; } auto result = std::unique_ptr<T[]>(new T[len / sizeof(T)]); get(result.get(), len); return result; } /** * Update the the sysctl value with the given buffer. * * @param buf,bufsize * The source buffer * @throws sc_error * If the source buffer cannot be stored in the sysctl */ void set(void const * const buf, size_t const bufsize) { if (::sysctl(this->mib, MibDepth, nullptr, nullptr, buf, bufsize) == -1) { throw sc_error{errno}; } } /** * Update the the sysctl value with the given value. * * @tparam T * The value type * @param value * The value to set the sysctl to */ template <typename T> void set(T const & value) { set(&value, sizeof(T)); } }; /** * This is a wrapper around Sysctl that allows semantically transparent * use of a sysctl. * * ~~~ c++ * Sync<int, Sysctl<3>> sndUnit{{"hw.snd.default_unit"}}; * if (sndUnit != 3) { // read from sysctl * sndUnit = 3; // assign to sysctl * } * ~~~ * * Note that both assignment and read access (implemented through * type casting to T) may throw an exception. * * @tparam T * The type to represent the sysctl as * @tparam SysctlT * The Sysctl type */ template <typename T, class SysctlT> class Sync { private: /** * A sysctl to represent. */ SysctlT sysctl; public: /** * The constructor copies the given Sysctl instance. * * @param sysctl * The Sysctl instance to represent */ constexpr Sync(SysctlT const & sysctl) noexcept : sysctl{sysctl} {} /** * Transparently assiges values of type T to the represented * Sysctl instance. * * @param value * The value to assign * @return * A self reference */ Sync & operator =(T const & value) { this->sysctl.set(value); return *this; } /** * Implicitly cast to the represented type. * * @return * Returns the value from the sysctl */ operator T () const { T value; this->sysctl.get(value); return value; } }; /** * A convenience alias around Sync. * * ~~~ c++ * // Sync<int, Sysctl<3>> sndUnit{{"hw.snd.default_unit"}}; * SysctlSync<int, 3> sndUnit{{"hw.snd.default_unit"}}; * if (sndUnit != 3) { // read from sysctl * sndUnit = 3; // assign to sysctl * } * ~~~ * * @tparam T * The type to represent the sysctl as * @tparam MibDepth * The maximum allowed MIB depth */ template <typename T, size_t MibDepth> using SysctlSync = Sync<T, Sysctl<MibDepth>>; /** * A read once representation of a Sysctl. * * This reads a sysctl once upon construction and always returns that * value. It does not support assignment. * * This class is intended for sysctls that are not expected to change, * such as hw.ncpu. A special property of this class is that the * constructor does not throw and takes a default value in case reading * the sysctl fails. * * ~~~ c++ * // Read number of CPU cores, assume 1 on failure: * Once<coreid_t, Sysctl<2>> ncpu{1, {CTL_HW, HW_NCPU}}; * // Equivalent: * int hw_ncpu; * try { * Sysctl<2>{CTL_HW, HW_NCPU}.get(hw_ncpu); * } catch (sys::sc_error) { * hw_ncpu = 1; * } * ~~~ * * @tparam T * The type to represent the sysctl as * @tparam SysctlT * The Sysctl type */ template <typename T, class SysctlT> class Once { private: /** * The sysctl value read upon construction. */ T value; public: /** * The constructor tries to read and store the requested sysctl. * * If reading the requested sysctl fails for any reason, * the given value is stored instead. * * @param value * The fallback value * @param sysctl * The sysctl to represent */ Once(T const & value, SysctlT const & sysctl) noexcept { try { sysctl.get(this->value); } catch (sc_error) { this->value = value; } } /** * Return a const reference to the value. * * @return * A const reference to the value */ operator T const &() const { return this->value; } }; /** * A convenience alias around Once. * * ~~~ c++ * // Once<coreid_t, Sysctl<2>> ncpu{0, {CTL_HW, HW_NCPU}}; * SysctlOnce<coreid_t, 2> ncpu{1, {CTL_HW, HW_NCPU}}; * ~~~ * * @tparam T * The type to represent the sysctl as * @tparam MibDepth * The maximum allowed MIB depth */ template <typename T, size_t MibDepth> using SysctlOnce = Once<T, Sysctl<MibDepth>>; /** * This creates a Once instance. * * This is intended for cases when a Once instance is created as a * temporary to retrieve a value, using it's fallback to a default * mechanism. * * @tparam T * The value type * @tparam SysctlT * The Sysctl type * @param value * The default value to fall back to * @param sysctl * The sysctl to try and read from */ template <typename T, class SysctlT> constexpr Once<T, SysctlT> once(T const & value, SysctlT const & sysctl) noexcept { return {value, sysctl}; } } /* namespace ctl */ } /* namespace sys */ #endif /* _POWERDXX_SYS_SYSCTL_HPP_ */ <|endoftext|>
<commit_before>#include "midi.h" #include <algorithm> #include <iostream> #include <sstream> MIDI::MIDI() {} RtMidiIn *MIDI::createMidiIn(const std::string clientName) { // RtMidiIn constructor RtMidiIn *midiin = 0; try { midiin = new RtMidiIn(RtMidi::LINUX_ALSA, clientName); } catch (RtMidiError &error) { // TODO Handle the exception here error.printMessage(); } midiin->ignoreTypes(false, true, true); return midiin; } RtMidiOut * MIDI::createMidiOut(const std::string clientName) { // RtMidiOut constructor RtMidiOut *midiout = 0; try { midiout = new RtMidiOut(RtMidi::LINUX_ALSA, clientName); } catch (RtMidiError &error) { // TODO Handle the exception here error.printMessage(); } return midiout; } unsigned char MIDI::RolandChecksum(BYTE_VECTOR *message) { unsigned int nBytes = message->size(); unsigned int sum = 0; for (unsigned int i = 0; i < nBytes; i++) { sum += (int)message->at(i); if (sum > 127) sum -= 128; } return 128 - sum; } BYTE_VECTOR *MIDI::byteSplit(long val) { return MIDI::byteSplit(val, 0); } BYTE_VECTOR *MIDI::byteSplit(long val, int size) { BYTE_VECTOR *bytes = new BYTE_VECTOR(); bytes->reserve(size); while (val > 0) { unsigned char c = val & 0x7f; val >>= 7; bytes->push_back(c); } if (size > 0) { int nLength = bytes->size(); if (nLength < size) { for (int i = nLength; i < size; i++) bytes->push_back(0x00); } } std::reverse(bytes->begin(), bytes->end()); return bytes; } long MIDI::byteJoin(BYTE_VECTOR *message) { return byteJoin(message, 0, message->size()); } long MIDI::byteJoin(BYTE_VECTOR *message, unsigned int start, unsigned int length) { unsigned int cnt; int current = 0; if (start + length > message->size()) return -1; for (cnt = start; cnt < start + length; cnt++) { current <<= 7; current += message->at(cnt); } return current; } std::string MIDI::decodeIp(BYTE_VECTOR *data, int offset) { long address = MIDI::byteJoin(data, offset, 5); #ifdef __MIO_DEBUG__ std::cout << "Bytes orig: "; MIDI::printMessage( new BYTE_VECTOR(data->begin() + offset, data->begin() + offset + 5)); std::cout << std::hex << address << ": "; #endif int a1 = address & 255; address >>= 8; int a2 = address & 255; address >>= 8; int a3 = address & 255; address >>= 8; int a4 = address & 255; std::stringstream result; result << std::dec << a4 << "." << a3 << "." << a2 << "." << a1; std::string ad = result.str(); #ifdef __MIO_DEBUG__ std::cout << ad << std::endl; encodeIpAddress(ad); #endif return ad; } BYTE_VECTOR *MIDI::encodeIpAddress(std::string ipAddress) { BYTE_VECTOR *result = 0; long lAddress = 0L; std::istringstream ss(ipAddress); std::string token; std::vector<std::string> ipParts; while (std::getline(ss, token, '.')) { ipParts.push_back(std::string(token)); } for (std::vector<std::string>::iterator it = ipParts.begin(); it != ipParts.end(); ++it) { if (it != ipParts.begin()) lAddress <<= 8; token = (*it); lAddress += std::stol(token); } result = MIDI::byteSplit(lAddress, 5); #ifdef __MIO_DEBUG__ std::cout << std::hex << lAddress << " - Bytes enc: "; MIDI::printMessage(result); std::cout << std::endl; #endif return result; } void MIDI::printMessage(BYTE_VECTOR *message) { unsigned int nMessageSize = message->size(); for (unsigned int i = 0; i < nMessageSize; i++) std::cout << std::hex << (int)message->at(i) << " "; std::cout << "\n" << std::flush; } <commit_msg>remove some debug statements<commit_after>#include "midi.h" #include <algorithm> #include <iostream> #include <sstream> MIDI::MIDI() {} RtMidiIn *MIDI::createMidiIn(const std::string clientName) { // RtMidiIn constructor RtMidiIn *midiin = 0; try { midiin = new RtMidiIn(RtMidi::LINUX_ALSA, clientName); } catch (RtMidiError &error) { // TODO Handle the exception here error.printMessage(); } midiin->ignoreTypes(false, true, true); return midiin; } RtMidiOut * MIDI::createMidiOut(const std::string clientName) { // RtMidiOut constructor RtMidiOut *midiout = 0; try { midiout = new RtMidiOut(RtMidi::LINUX_ALSA, clientName); } catch (RtMidiError &error) { // TODO Handle the exception here error.printMessage(); } return midiout; } unsigned char MIDI::RolandChecksum(BYTE_VECTOR *message) { unsigned int nBytes = message->size(); unsigned int sum = 0; for (unsigned int i = 0; i < nBytes; i++) { sum += (int)message->at(i); if (sum > 127) sum -= 128; } return 128 - sum; } BYTE_VECTOR *MIDI::byteSplit(long val) { return MIDI::byteSplit(val, 0); } BYTE_VECTOR *MIDI::byteSplit(long val, int size) { BYTE_VECTOR *bytes = new BYTE_VECTOR(); bytes->reserve(size); while (val > 0) { unsigned char c = val & 0x7f; val >>= 7; bytes->push_back(c); } if (size > 0) { int nLength = bytes->size(); if (nLength < size) { for (int i = nLength; i < size; i++) bytes->push_back(0x00); } } std::reverse(bytes->begin(), bytes->end()); return bytes; } long MIDI::byteJoin(BYTE_VECTOR *message) { return byteJoin(message, 0, message->size()); } long MIDI::byteJoin(BYTE_VECTOR *message, unsigned int start, unsigned int length) { unsigned int cnt; int current = 0; if (start + length > message->size()) return -1; for (cnt = start; cnt < start + length; cnt++) { current <<= 7; current += message->at(cnt); } return current; } std::string MIDI::decodeIp(BYTE_VECTOR *data, int offset) { long address = MIDI::byteJoin(data, offset, 5); int a1 = address & 255; address >>= 8; int a2 = address & 255; address >>= 8; int a3 = address & 255; address >>= 8; int a4 = address & 255; std::stringstream result; result << std::dec << a4 << "." << a3 << "." << a2 << "." << a1; std::string ad = result.str(); return ad; } BYTE_VECTOR *MIDI::encodeIpAddress(std::string ipAddress) { BYTE_VECTOR *result = 0; long lAddress = 0L; std::istringstream ss(ipAddress); std::string token; std::vector<std::string> ipParts; while (std::getline(ss, token, '.')) { ipParts.push_back(std::string(token)); } for (std::vector<std::string>::iterator it = ipParts.begin(); it != ipParts.end(); ++it) { if (it != ipParts.begin()) lAddress <<= 8; token = (*it); lAddress += std::stol(token); } result = MIDI::byteSplit(lAddress, 5); return result; } void MIDI::printMessage(BYTE_VECTOR *message) { unsigned int nMessageSize = message->size(); for (unsigned int i = 0; i < nMessageSize; i++) std::cout << std::hex << (int)message->at(i) << " "; std::cout << "\n" << std::flush; } <|endoftext|>
<commit_before>/* * (C) 2015 Jack Lloyd * * Botan is released under the Simplified BSD License (see license.txt) */ #include "../cli/cli.h" #include "tests.h" #include <iostream> #include <sstream> #include <string> #include <set> #include <deque> #include <thread> #include <future> #include <botan/version.h> #include <botan/loadstor.h> #include <botan/hash.h> #if defined(BOTAN_HAS_HMAC_DRBG) #include <botan/hmac_drbg.h> #endif #if defined(BOTAN_HAS_SYSTEM_RNG) #include <botan/system_rng.h> #endif #if defined(BOTAN_HAS_AUTO_SEEDING_RNG) #include <botan/auto_rng.h> #endif namespace { class Test_Runner : public Botan_CLI::Command { public: Test_Runner() : Command("test --threads=0 --run-long-tests --run-online-tests --test-runs=1 --drbg-seed= --data-dir= --pkcs11-lib= --provider= --log-success *suites") {} std::string help_text() const override { std::ostringstream err; const std::string& spec = cmd_spec(); err << "Usage: botan-test" << spec.substr(spec.find_first_of(' '), std::string::npos) << "\n\nAvailable test suites\n" << "----------------\n"; size_t line_len = 0; for(auto&& test : Botan_Tests::Test::registered_tests()) { err << test << " "; line_len += test.size() + 1; if(line_len > 64) { err << "\n"; line_len = 0; } } if(line_len > 0) { err << "\n"; } return err.str(); } void go() override { const size_t threads = get_arg_sz("threads"); const std::string drbg_seed = get_arg("drbg-seed"); const bool log_success = flag_set("log-success"); const bool run_online_tests = flag_set("run-online-tests"); const bool run_long_tests = flag_set("run-long-tests"); const std::string data_dir = get_arg_or("data-dir", "src/tests/data"); const std::string pkcs11_lib = get_arg("pkcs11-lib"); const std::string provider = get_arg("provider"); const size_t runs = get_arg_sz("test-runs"); std::vector<std::string> req = get_arg_list("suites"); if(req.empty()) { /* If nothing was requested on the command line, run everything. First run the "essentials" to smoke test, then everything else in alphabetical order. */ req = {"block", "stream", "hash", "mac", "modes", "aead" "kdf", "pbkdf", "hmac_drbg", "x931_rng", "util"}; std::set<std::string> all_others = Botan_Tests::Test::registered_tests(); if(pkcs11_lib.empty()) { // do not run pkcs11 tests by default unless pkcs11-lib set for(std::set<std::string>::iterator iter = all_others.begin(); iter != all_others.end();) { if((*iter).find("pkcs11") != std::string::npos) { iter = all_others.erase(iter); } else { ++iter; } } } for(auto f : req) { all_others.erase(f); } req.insert(req.end(), all_others.begin(), all_others.end()); } else if(req.size() == 1 && req.at(0) == "pkcs11") { req = {"pkcs11-manage", "pkcs11-module", "pkcs11-slot", "pkcs11-session", "pkcs11-object", "pkcs11-rsa", "pkcs11-ecdsa", "pkcs11-ecdh", "pkcs11-rng", "pkcs11-x509"}; } else { std::set<std::string> all = Botan_Tests::Test::registered_tests(); for(auto&& r : req) { if(all.find(r) == all.end()) { throw Botan_CLI::CLI_Usage_Error("Unknown test suite: " + r); } } } output() << "Testing " << Botan::version_string() << "\n"; output() << "Starting tests"; if(threads > 1) output() << " threads:" << threads; if(!pkcs11_lib.empty()) { output() << " pkcs11 library:" << pkcs11_lib; } Botan_Tests::Provider_Filter pf; if(!provider.empty()) { output() << " provider:" << provider; pf.set(provider); } std::unique_ptr<Botan::RandomNumberGenerator> rng; #if defined(BOTAN_HAS_HMAC_DRBG) && defined(BOTAN_HAS_SHA2_64) std::vector<uint8_t> seed = Botan::hex_decode(drbg_seed); if(seed.empty()) { const uint64_t ts = Botan_Tests::Test::timestamp(); seed.resize(8); Botan::store_be(ts, seed.data()); } output() << " rng:HMAC_DRBG with seed '" << Botan::hex_encode(seed) << "'"; // Expand out the seed to 512 bits to make the DRBG happy std::unique_ptr<Botan::HashFunction> sha512(Botan::HashFunction::create("SHA-512")); sha512->update(seed); seed.resize(sha512->output_length()); sha512->final(seed.data()); std::unique_ptr<Botan::HMAC_DRBG> drbg(new Botan::HMAC_DRBG("SHA-384")); drbg->initialize_with(seed.data(), seed.size()); rng.reset(new Botan::Serialized_RNG(drbg.release())); #else if(drbg_seed != "") throw Botan_Tests::Test_Error("HMAC_DRBG disabled in build, cannot specify DRBG seed"); #if defined(BOTAN_HAS_SYSTEM_RNG) output() << " rng:system"; rng.reset(new Botan::System_RNG); #elif defined(BOTAN_HAS_AUTO_SEEDING_RNG) output() << " rng:autoseeded"; rng.reset(new Botan::Serialized_RNG(new Botan::AutoSeeded_RNG)); #endif #endif output() << "\n"; Botan_Tests::Test::setup_tests(log_success, run_online_tests, run_long_tests, data_dir, pkcs11_lib, pf, rng.get()); for(size_t i = 0; i != runs; ++i) { const size_t failed = run_tests(req, output(), threads); // Throw so main returns an error if(failed) throw Botan_Tests::Test_Error("Test suite failure"); } } private: std::string report_out(const std::vector<Botan_Tests::Test::Result>& results, size_t& tests_failed, size_t& tests_ran) { std::ostringstream out; std::map<std::string, Botan_Tests::Test::Result> combined; for(auto&& result : results) { const std::string who = result.who(); auto i = combined.find(who); if(i == combined.end()) { combined.insert(std::make_pair(who, Botan_Tests::Test::Result(who))); i = combined.find(who); } i->second.merge(result); } for(auto&& result : combined) { out << result.second.result_string(verbose()); tests_failed += result.second.tests_failed(); tests_ran += result.second.tests_run(); } return out.str(); } size_t run_tests(const std::vector<std::string>& tests_to_run, std::ostream& out, size_t threads) { size_t tests_ran = 0, tests_failed = 0; const uint64_t start_time = Botan_Tests::Test::timestamp(); if(threads <= 1) { for(auto&& test_name : tests_to_run) { try { out << test_name << ':' << std::endl; const auto results = Botan_Tests::Test::run_test(test_name, false); out << report_out(results, tests_failed, tests_ran) << std::flush; } catch(std::exception& e) { out << "Test " << test_name << " failed with exception " << e.what() << std::flush; } } } else { /* We're not doing this in a particularly nice way, and variance in time is high so commonly we'll 'run dry' by blocking on the first future. But plain C++11 <thread> is missing a lot of tools we'd need (like wait_for_any on a set of futures) and there is no point pulling in an additional dependency just for this. In any case it helps somewhat (50-100% speedup) and provides a proof of concept for parallel testing. */ typedef std::future<std::vector<Botan_Tests::Test::Result>> FutureResults; std::deque<FutureResults> fut_results; for(auto&& test_name : tests_to_run) { auto run_it = [test_name]() -> std::vector<Botan_Tests::Test::Result> { try { return Botan_Tests::Test::run_test(test_name, false); } catch(std::exception& e) { Botan_Tests::Test::Result r(test_name); r.test_failure("Exception thrown", e.what()); return std::vector<Botan_Tests::Test::Result>{r}; } }; fut_results.push_back(std::async(std::launch::async, run_it)); while(fut_results.size() > threads) { out << report_out(fut_results[0].get(), tests_failed, tests_ran) << std::flush; fut_results.pop_front(); } } while(fut_results.size() > 0) { out << report_out(fut_results[0].get(), tests_failed, tests_ran) << std::flush; fut_results.pop_front(); } } const uint64_t total_ns = Botan_Tests::Test::timestamp() - start_time; out << "Tests complete ran " << tests_ran << " tests in " << Botan_Tests::Test::format_time(total_ns) << " "; if(tests_failed > 0) { out << tests_failed << " tests failed"; } else if(tests_ran > 0) { out << "all tests ok"; } out << std::endl; return tests_failed; } }; BOTAN_REGISTER_COMMAND("test", Test_Runner); } int main(int argc, char* argv[]) { std::cerr << Botan::runtime_version_check(BOTAN_VERSION_MAJOR, BOTAN_VERSION_MINOR, BOTAN_VERSION_PATCH); try { std::unique_ptr<Botan_CLI::Command> cmd(Botan_CLI::Command::get_cmd("test")); if(!cmd) { std::cout << "Unable to retrieve testing helper (program bug)\n"; // WTF return 1; } std::vector<std::string> args(argv + 1, argv + argc); return cmd->run(args); } catch(Botan::Exception& e) { std::cout << "Exiting with library exception " << e.what() << std::endl; } catch(std::exception& e) { std::cout << "Exiting with std exception " << e.what() << std::endl; } catch(...) { std::cout << "Exiting with unknown exception\n"; } } <commit_msg>Show OpenSSL error messages if test fails.<commit_after>/* * (C) 2015 Jack Lloyd * * Botan is released under the Simplified BSD License (see license.txt) */ #include "../cli/cli.h" #include "tests.h" #include <iostream> #include <sstream> #include <string> #include <set> #include <deque> #include <thread> #include <future> #include <botan/version.h> #include <botan/loadstor.h> #include <botan/hash.h> #if defined(BOTAN_HAS_HMAC_DRBG) #include <botan/hmac_drbg.h> #endif #if defined(BOTAN_HAS_SYSTEM_RNG) #include <botan/system_rng.h> #endif #if defined(BOTAN_HAS_AUTO_SEEDING_RNG) #include <botan/auto_rng.h> #endif #if defined(BOTAN_HAS_OPENSSL) #include <botan/internal/openssl.h> #endif namespace { class Test_Runner : public Botan_CLI::Command { public: Test_Runner() : Command("test --threads=0 --run-long-tests --run-online-tests --test-runs=1 --drbg-seed= --data-dir= --pkcs11-lib= --provider= --log-success *suites") {} std::string help_text() const override { std::ostringstream err; const std::string& spec = cmd_spec(); err << "Usage: botan-test" << spec.substr(spec.find_first_of(' '), std::string::npos) << "\n\nAvailable test suites\n" << "----------------\n"; size_t line_len = 0; for(auto&& test : Botan_Tests::Test::registered_tests()) { err << test << " "; line_len += test.size() + 1; if(line_len > 64) { err << "\n"; line_len = 0; } } if(line_len > 0) { err << "\n"; } return err.str(); } void go() override { const size_t threads = get_arg_sz("threads"); const std::string drbg_seed = get_arg("drbg-seed"); const bool log_success = flag_set("log-success"); const bool run_online_tests = flag_set("run-online-tests"); const bool run_long_tests = flag_set("run-long-tests"); const std::string data_dir = get_arg_or("data-dir", "src/tests/data"); const std::string pkcs11_lib = get_arg("pkcs11-lib"); const std::string provider = get_arg("provider"); const size_t runs = get_arg_sz("test-runs"); std::vector<std::string> req = get_arg_list("suites"); if(req.empty()) { /* If nothing was requested on the command line, run everything. First run the "essentials" to smoke test, then everything else in alphabetical order. */ req = {"block", "stream", "hash", "mac", "modes", "aead" "kdf", "pbkdf", "hmac_drbg", "x931_rng", "util"}; std::set<std::string> all_others = Botan_Tests::Test::registered_tests(); if(pkcs11_lib.empty()) { // do not run pkcs11 tests by default unless pkcs11-lib set for(std::set<std::string>::iterator iter = all_others.begin(); iter != all_others.end();) { if((*iter).find("pkcs11") != std::string::npos) { iter = all_others.erase(iter); } else { ++iter; } } } for(auto f : req) { all_others.erase(f); } req.insert(req.end(), all_others.begin(), all_others.end()); } else if(req.size() == 1 && req.at(0) == "pkcs11") { req = {"pkcs11-manage", "pkcs11-module", "pkcs11-slot", "pkcs11-session", "pkcs11-object", "pkcs11-rsa", "pkcs11-ecdsa", "pkcs11-ecdh", "pkcs11-rng", "pkcs11-x509"}; } else { std::set<std::string> all = Botan_Tests::Test::registered_tests(); for(auto&& r : req) { if(all.find(r) == all.end()) { throw Botan_CLI::CLI_Usage_Error("Unknown test suite: " + r); } } } output() << "Testing " << Botan::version_string() << "\n"; output() << "Starting tests"; if(threads > 1) output() << " threads:" << threads; if(!pkcs11_lib.empty()) { output() << " pkcs11 library:" << pkcs11_lib; } Botan_Tests::Provider_Filter pf; if(!provider.empty()) { output() << " provider:" << provider; pf.set(provider); } #if defined(BOTAN_HAS_OPENSSL) if(provider.empty() || provider == "openssl") { ERR_load_crypto_strings(); } #endif std::unique_ptr<Botan::RandomNumberGenerator> rng; #if defined(BOTAN_HAS_HMAC_DRBG) && defined(BOTAN_HAS_SHA2_64) std::vector<uint8_t> seed = Botan::hex_decode(drbg_seed); if(seed.empty()) { const uint64_t ts = Botan_Tests::Test::timestamp(); seed.resize(8); Botan::store_be(ts, seed.data()); } output() << " rng:HMAC_DRBG with seed '" << Botan::hex_encode(seed) << "'"; // Expand out the seed to 512 bits to make the DRBG happy std::unique_ptr<Botan::HashFunction> sha512(Botan::HashFunction::create("SHA-512")); sha512->update(seed); seed.resize(sha512->output_length()); sha512->final(seed.data()); std::unique_ptr<Botan::HMAC_DRBG> drbg(new Botan::HMAC_DRBG("SHA-384")); drbg->initialize_with(seed.data(), seed.size()); rng.reset(new Botan::Serialized_RNG(drbg.release())); #else if(drbg_seed != "") throw Botan_Tests::Test_Error("HMAC_DRBG disabled in build, cannot specify DRBG seed"); #if defined(BOTAN_HAS_SYSTEM_RNG) output() << " rng:system"; rng.reset(new Botan::System_RNG); #elif defined(BOTAN_HAS_AUTO_SEEDING_RNG) output() << " rng:autoseeded"; rng.reset(new Botan::Serialized_RNG(new Botan::AutoSeeded_RNG)); #endif #endif output() << "\n"; Botan_Tests::Test::setup_tests(log_success, run_online_tests, run_long_tests, data_dir, pkcs11_lib, pf, rng.get()); for(size_t i = 0; i != runs; ++i) { const size_t failed = run_tests(req, output(), threads); // Throw so main returns an error if(failed) throw Botan_Tests::Test_Error("Test suite failure"); } } private: std::string report_out(const std::vector<Botan_Tests::Test::Result>& results, size_t& tests_failed, size_t& tests_ran) { std::ostringstream out; std::map<std::string, Botan_Tests::Test::Result> combined; for(auto&& result : results) { const std::string who = result.who(); auto i = combined.find(who); if(i == combined.end()) { combined.insert(std::make_pair(who, Botan_Tests::Test::Result(who))); i = combined.find(who); } i->second.merge(result); } for(auto&& result : combined) { out << result.second.result_string(verbose()); tests_failed += result.second.tests_failed(); tests_ran += result.second.tests_run(); } return out.str(); } size_t run_tests(const std::vector<std::string>& tests_to_run, std::ostream& out, size_t threads) { size_t tests_ran = 0, tests_failed = 0; const uint64_t start_time = Botan_Tests::Test::timestamp(); if(threads <= 1) { for(auto&& test_name : tests_to_run) { try { out << test_name << ':' << std::endl; const auto results = Botan_Tests::Test::run_test(test_name, false); out << report_out(results, tests_failed, tests_ran) << std::flush; } catch(std::exception& e) { out << "Test " << test_name << " failed with exception " << e.what() << std::flush; } } } else { /* We're not doing this in a particularly nice way, and variance in time is high so commonly we'll 'run dry' by blocking on the first future. But plain C++11 <thread> is missing a lot of tools we'd need (like wait_for_any on a set of futures) and there is no point pulling in an additional dependency just for this. In any case it helps somewhat (50-100% speedup) and provides a proof of concept for parallel testing. */ typedef std::future<std::vector<Botan_Tests::Test::Result>> FutureResults; std::deque<FutureResults> fut_results; for(auto&& test_name : tests_to_run) { auto run_it = [test_name]() -> std::vector<Botan_Tests::Test::Result> { try { return Botan_Tests::Test::run_test(test_name, false); } catch(std::exception& e) { Botan_Tests::Test::Result r(test_name); r.test_failure("Exception thrown", e.what()); return std::vector<Botan_Tests::Test::Result>{r}; } }; fut_results.push_back(std::async(std::launch::async, run_it)); while(fut_results.size() > threads) { out << report_out(fut_results[0].get(), tests_failed, tests_ran) << std::flush; fut_results.pop_front(); } } while(fut_results.size() > 0) { out << report_out(fut_results[0].get(), tests_failed, tests_ran) << std::flush; fut_results.pop_front(); } } const uint64_t total_ns = Botan_Tests::Test::timestamp() - start_time; out << "Tests complete ran " << tests_ran << " tests in " << Botan_Tests::Test::format_time(total_ns) << " "; if(tests_failed > 0) { out << tests_failed << " tests failed"; } else if(tests_ran > 0) { out << "all tests ok"; } out << std::endl; return tests_failed; } }; BOTAN_REGISTER_COMMAND("test", Test_Runner); } int main(int argc, char* argv[]) { std::cerr << Botan::runtime_version_check(BOTAN_VERSION_MAJOR, BOTAN_VERSION_MINOR, BOTAN_VERSION_PATCH); try { std::unique_ptr<Botan_CLI::Command> cmd(Botan_CLI::Command::get_cmd("test")); if(!cmd) { std::cout << "Unable to retrieve testing helper (program bug)\n"; // WTF return 1; } std::vector<std::string> args(argv + 1, argv + argc); return cmd->run(args); } catch(Botan::Exception& e) { std::cout << "Exiting with library exception " << e.what() << std::endl; } catch(std::exception& e) { std::cout << "Exiting with std exception " << e.what() << std::endl; } catch(...) { std::cout << "Exiting with unknown exception\n"; } } <|endoftext|>
<commit_before>// Module: Log4CPLUS // File: timehelper.cxx // Created: 4/2003 // Author: Tad E. Smith // // // Copyright 2003-2010 Tad E. Smith // // 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 <log4cplus/helpers/timehelper.h> #include <log4cplus/helpers/loglog.h> #include <log4cplus/streams.h> #include <log4cplus/helpers/stringhelper.h> #include <log4cplus/internal/internal.h> #include <algorithm> #include <vector> #include <iomanip> #include <cassert> #if ! defined (_WIN32_WCE) #include <cerrno> #endif #if defined (UNICODE) #include <cwchar> #endif #if defined (LOG4CPLUS_HAVE_SYS_TYPES_H) #include <sys/types.h> #endif #if defined(LOG4CPLUS_HAVE_SYS_TIME_H) #include <sys/time.h> #endif #if defined (LOG4CPLUS_HAVE_SYS_TIMEB_H) #include <sys/timeb.h> #endif #if defined(LOG4CPLUS_HAVE_GMTIME_R) && !defined(LOG4CPLUS_SINGLE_THREADED) #define LOG4CPLUS_NEED_GMTIME_R #endif #if defined(LOG4CPLUS_HAVE_LOCALTIME_R) && !defined(LOG4CPLUS_SINGLE_THREADED) #define LOG4CPLUS_NEED_LOCALTIME_R #endif namespace log4cplus { namespace helpers { const int ONE_SEC_IN_USEC = 1000000; #if defined (_WIN32_WCE) using ::mktime; using ::gmtime; using ::localtime; #if defined (UNICODE) using ::wcsftime; #else using ::strftime; #endif #else using std::mktime; using std::gmtime; using std::localtime; #if defined (UNICODE) using std::wcsftime; #else using std::strftime; #endif #endif ////////////////////////////////////////////////////////////////////////////// // Time ctors ////////////////////////////////////////////////////////////////////////////// Time::Time() : tv_sec(0) , tv_usec(0) { } Time::Time(time_t tv_sec_, long tv_usec_) : tv_sec(tv_sec_) , tv_usec(tv_usec_) { assert (tv_usec < ONE_SEC_IN_USEC); } Time::Time(time_t time) : tv_sec(time) , tv_usec(0) { } Time Time::gettimeofday() { #if defined (LOG4CPLUS_HAVE_CLOCK_GETTIME) struct timespec ts; int res = clock_gettime (CLOCK_REALTIME, &ts); assert (res == 0); if (res != 0) LogLog::getLogLog ()->error ( LOG4CPLUS_TEXT("clock_gettime() has failed"), true); return Time (ts.tv_sec, ts.tv_nsec / 1000); #elif defined(LOG4CPLUS_HAVE_GETTIMEOFDAY) struct timeval tp; ::gettimeofday(&tp, 0); return Time(tp.tv_sec, tp.tv_usec); #elif defined(LOG4CPLUS_HAVE_FTIME) struct timeb tp; ftime(&tp); return Time(tp.time, tp.millitm * 1000); #else #warning "Time::gettimeofday()- low resolution timer: gettimeofday and ftime unavailable" return Time(::time(0), 0); #endif } ////////////////////////////////////////////////////////////////////////////// // Time methods ////////////////////////////////////////////////////////////////////////////// time_t Time::setTime(tm* t) { time_t time = helpers::mktime(t); if (time != -1) tv_sec = time; return time; } time_t Time::getTime() const { return tv_sec; } void Time::gmtime(tm* t) const { time_t clock = tv_sec; #if defined (LOG4CPLUS_HAVE_GMTIME_S) && defined (_MSC_VER) gmtime_s (t, &clock); #elif defined (LOG4CPLUS_HAVE_GMTIME_S) && defined (__BORLANDC__) gmtime_s (&clock, t); #elif defined (LOG4CPLUS_NEED_GMTIME_R) gmtime_r (&clock, t); #else tm* tmp = helpers::gmtime(&clock); *t = *tmp; #endif } void Time::localtime(tm* t) const { time_t clock = tv_sec; #ifdef LOG4CPLUS_NEED_LOCALTIME_R ::localtime_r(&clock, t); #else tm* tmp = helpers::localtime(&clock); *t = *tmp; #endif } namespace { static log4cplus::tstring const padding_zeros[4] = { log4cplus::tstring (LOG4CPLUS_TEXT("000")), log4cplus::tstring (LOG4CPLUS_TEXT("00")), log4cplus::tstring (LOG4CPLUS_TEXT("0")), log4cplus::tstring (LOG4CPLUS_TEXT("")) }; static log4cplus::tstring const uc_q_padding_zeros[4] = { log4cplus::tstring (LOG4CPLUS_TEXT(".000")), log4cplus::tstring (LOG4CPLUS_TEXT(".00")), log4cplus::tstring (LOG4CPLUS_TEXT(".0")), log4cplus::tstring (LOG4CPLUS_TEXT(".")) }; static void build_q_value (log4cplus::tstring & q_str, long tv_usec) { convertIntegerToString(q_str, tv_usec / 1000); std::size_t const len = q_str.length(); if (len <= 2) q_str.insert (0, padding_zeros[q_str.length()]); } static void build_uc_q_value (log4cplus::tstring & uc_q_str, long tv_usec, log4cplus::tstring & tmp) { build_q_value (uc_q_str, tv_usec); convertIntegerToString(tmp, tv_usec % 1000); std::size_t const usecs_len = tmp.length(); tmp.insert (0, usecs_len <= 3 ? uc_q_padding_zeros[usecs_len] : uc_q_padding_zeros[3]); uc_q_str.append (tmp); } } // namespace log4cplus::tstring Time::getFormattedTime(const log4cplus::tstring& fmt_orig, bool use_gmtime) const { if (fmt_orig.empty () || fmt_orig[0] == 0) return log4cplus::tstring (); tm time; if (use_gmtime) gmtime(&time); else localtime(&time); enum State { TEXT, PERCENT_SIGN }; internal::gft_scratch_pad & gft_sp = internal::get_gft_scratch_pad (); gft_sp.reset (); gft_sp.fmt.assign (fmt_orig); gft_sp.ret.reserve (static_cast<std::size_t>(gft_sp.fmt.size () * 1.35)); State state = TEXT; // Walk the format string and process all occurences of %q and %Q. for (log4cplus::tstring::const_iterator fmt_it = gft_sp.fmt.begin (); fmt_it != gft_sp.fmt.end (); ++fmt_it) { switch (state) { case TEXT: { if (*fmt_it == LOG4CPLUS_TEXT ('%')) state = PERCENT_SIGN; else gft_sp.ret.push_back (*fmt_it); } break; case PERCENT_SIGN: { switch (*fmt_it) { case LOG4CPLUS_TEXT ('q'): { if (! gft_sp.q_str_valid) { build_q_value (gft_sp.q_str, tv_usec); gft_sp.q_str_valid = true; } gft_sp.ret.append (gft_sp.q_str); state = TEXT; } break; case LOG4CPLUS_TEXT ('Q'): { if (! gft_sp.uc_q_str_valid) { build_uc_q_value (gft_sp.uc_q_str, tv_usec, gft_sp.tmp); gft_sp.uc_q_str_valid = true; } gft_sp.ret.append (gft_sp.uc_q_str); state = TEXT; } break; // Windows do not support %s format specifier // (seconds since epoch). case LOG4CPLUS_TEXT ('s'): { if (! gft_sp.s_str_valid) { convertIntegerToString (gft_sp.s_str, tv_sec); gft_sp.s_str_valid = true; } gft_sp.ret.append (gft_sp.s_str); state = TEXT; } break; default: { gft_sp.ret.push_back (LOG4CPLUS_TEXT ('%')); gft_sp.ret.push_back (*fmt_it); state = TEXT; } } } break; } } // Finally call strftime/wcsftime to format the rest of the string. gft_sp.ret.swap (gft_sp.fmt); std::size_t buffer_size = gft_sp.fmt.size () + 1; std::size_t len; // Limit how far can the buffer grow. This is necessary so that we // catch bad format string. Some implementations of strftime() signal // both too small buffer and invalid format string by returning 0 // without changing errno. std::size_t const buffer_size_max = (std::max) (static_cast<std::size_t>(1024), buffer_size * 16); do { gft_sp.buffer.resize (buffer_size); errno = 0; #ifdef UNICODE len = helpers::wcsftime(&gft_sp.buffer[0], buffer_size, gft_sp.fmt.c_str(), &time); #else len = helpers::strftime(&gft_sp.buffer[0], buffer_size, gft_sp.fmt.c_str(), &time); #endif if (len == 0) { int const eno = errno; buffer_size *= 2; if (buffer_size > buffer_size_max) { LogLog::getLogLog ()->error ( LOG4CPLUS_TEXT("Error in strftime(): ") + convertIntegerToString (eno), true); } } } while (len == 0); return tstring (gft_sp.buffer.begin (), gft_sp.buffer.begin () + len); } Time& Time::operator+=(const Time& rhs) { tv_sec += rhs.tv_sec; tv_usec += rhs.tv_usec; if(tv_usec > ONE_SEC_IN_USEC) { ++tv_sec; tv_usec -= ONE_SEC_IN_USEC; } return *this; } Time& Time::operator-=(const Time& rhs) { tv_sec -= rhs.tv_sec; tv_usec -= rhs.tv_usec; if(tv_usec < 0) { --tv_sec; tv_usec += ONE_SEC_IN_USEC; } return *this; } Time& Time::operator/=(long rhs) { long rem_secs = static_cast<long>(tv_sec % rhs); tv_sec /= rhs; tv_usec /= rhs; tv_usec += static_cast<long>((rem_secs * ONE_SEC_IN_USEC) / rhs); return *this; } Time& Time::operator*=(long rhs) { long new_usec = tv_usec * rhs; long overflow_sec = new_usec / ONE_SEC_IN_USEC; tv_usec = new_usec % ONE_SEC_IN_USEC; tv_sec *= rhs; tv_sec += overflow_sec; return *this; } ////////////////////////////////////////////////////////////////////////////// // Time globals ////////////////////////////////////////////////////////////////////////////// const Time operator+(const Time& lhs, const Time& rhs) { return Time(lhs) += rhs; } const Time operator-(const Time& lhs, const Time& rhs) { return Time(lhs) -= rhs; } const Time operator/(const Time& lhs, long rhs) { return Time(lhs) /= rhs; } const Time operator*(const Time& lhs, long rhs) { return Time(lhs) *= rhs; } bool operator<(const Time& lhs, const Time& rhs) { return ( (lhs.sec() < rhs.sec()) || ( (lhs.sec() == rhs.sec()) && (lhs.usec() < rhs.usec())) ); } bool operator<=(const Time& lhs, const Time& rhs) { return ((lhs < rhs) || (lhs == rhs)); } bool operator>(const Time& lhs, const Time& rhs) { return ( (lhs.sec() > rhs.sec()) || ( (lhs.sec() == rhs.sec()) && (lhs.usec() > rhs.usec())) ); } bool operator>=(const Time& lhs, const Time& rhs) { return ((lhs > rhs) || (lhs == rhs)); } bool operator==(const Time& lhs, const Time& rhs) { return ( lhs.sec() == rhs.sec() && lhs.usec() == rhs.usec()); } bool operator!=(const Time& lhs, const Time& rhs) { return !(lhs == rhs); } } } // namespace log4cplus { namespace helpers { <commit_msg>timehelper.cxx (Time::gettimeofday): Prefer GetSystemTimeAsFileTime() over ftime() on Windows.<commit_after>// Module: Log4CPLUS // File: timehelper.cxx // Created: 4/2003 // Author: Tad E. Smith // // // Copyright 2003-2010 Tad E. Smith // // 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 <log4cplus/helpers/timehelper.h> #include <log4cplus/helpers/loglog.h> #include <log4cplus/streams.h> #include <log4cplus/helpers/stringhelper.h> #include <log4cplus/internal/internal.h> #include <algorithm> #include <vector> #include <iomanip> #include <cassert> #if ! defined (_WIN32_WCE) #include <cerrno> #endif #if defined (UNICODE) #include <cwchar> #endif #if defined (LOG4CPLUS_HAVE_SYS_TYPES_H) #include <sys/types.h> #endif #if defined(LOG4CPLUS_HAVE_SYS_TIME_H) #include <sys/time.h> #endif #if defined (LOG4CPLUS_HAVE_SYS_TIMEB_H) #include <sys/timeb.h> #endif #if defined(LOG4CPLUS_HAVE_GMTIME_R) && !defined(LOG4CPLUS_SINGLE_THREADED) #define LOG4CPLUS_NEED_GMTIME_R #endif #if defined(LOG4CPLUS_HAVE_LOCALTIME_R) && !defined(LOG4CPLUS_SINGLE_THREADED) #define LOG4CPLUS_NEED_LOCALTIME_R #endif namespace log4cplus { namespace helpers { const int ONE_SEC_IN_USEC = 1000000; #if defined (_WIN32_WCE) using ::mktime; using ::gmtime; using ::localtime; #if defined (UNICODE) using ::wcsftime; #else using ::strftime; #endif #else using std::mktime; using std::gmtime; using std::localtime; #if defined (UNICODE) using std::wcsftime; #else using std::strftime; #endif #endif ////////////////////////////////////////////////////////////////////////////// // Time ctors ////////////////////////////////////////////////////////////////////////////// Time::Time() : tv_sec(0) , tv_usec(0) { } Time::Time(time_t tv_sec_, long tv_usec_) : tv_sec(tv_sec_) , tv_usec(tv_usec_) { assert (tv_usec < ONE_SEC_IN_USEC); } Time::Time(time_t time) : tv_sec(time) , tv_usec(0) { } Time Time::gettimeofday() { #if defined (LOG4CPLUS_HAVE_CLOCK_GETTIME) struct timespec ts; int res = clock_gettime (CLOCK_REALTIME, &ts); assert (res == 0); if (res != 0) LogLog::getLogLog ()->error ( LOG4CPLUS_TEXT("clock_gettime() has failed"), true); return Time (ts.tv_sec, ts.tv_nsec / 1000); #elif defined(LOG4CPLUS_HAVE_GETTIMEOFDAY) struct timeval tp; ::gettimeofday(&tp, 0); return Time(tp.tv_sec, tp.tv_usec); #elif defined (_WIN32) FILETIME ft; GetSystemTimeAsFileTime (&ft); typedef unsigned __int64 uint64_type; uint64_type st100ns = uint64_type (ft.dwHighDateTime) << 32 | ft.dwLowDateTime; // Number of 100-ns intervals between UNIX epoch and Windows system time // is 116444736000000000. uint64_type const offset = uint64_type (116444736) * 1000 * 1000 * 1000; uint64_type fixed_time = st100ns - offset; return Time (fixed_time / (10 * 1000 * 1000), fixed_time % (10 * 1000 * 1000) / 10); #elif defined(LOG4CPLUS_HAVE_FTIME) struct timeb tp; ftime(&tp); return Time(tp.time, tp.millitm * 1000); #else #warning "Time::gettimeofday()- low resolution timer: gettimeofday and ftime unavailable" return Time(::time(0), 0); #endif } ////////////////////////////////////////////////////////////////////////////// // Time methods ////////////////////////////////////////////////////////////////////////////// time_t Time::setTime(tm* t) { time_t time = helpers::mktime(t); if (time != -1) tv_sec = time; return time; } time_t Time::getTime() const { return tv_sec; } void Time::gmtime(tm* t) const { time_t clock = tv_sec; #if defined (LOG4CPLUS_HAVE_GMTIME_S) && defined (_MSC_VER) gmtime_s (t, &clock); #elif defined (LOG4CPLUS_HAVE_GMTIME_S) && defined (__BORLANDC__) gmtime_s (&clock, t); #elif defined (LOG4CPLUS_NEED_GMTIME_R) gmtime_r (&clock, t); #else tm* tmp = helpers::gmtime(&clock); *t = *tmp; #endif } void Time::localtime(tm* t) const { time_t clock = tv_sec; #ifdef LOG4CPLUS_NEED_LOCALTIME_R ::localtime_r(&clock, t); #else tm* tmp = helpers::localtime(&clock); *t = *tmp; #endif } namespace { static log4cplus::tstring const padding_zeros[4] = { log4cplus::tstring (LOG4CPLUS_TEXT("000")), log4cplus::tstring (LOG4CPLUS_TEXT("00")), log4cplus::tstring (LOG4CPLUS_TEXT("0")), log4cplus::tstring (LOG4CPLUS_TEXT("")) }; static log4cplus::tstring const uc_q_padding_zeros[4] = { log4cplus::tstring (LOG4CPLUS_TEXT(".000")), log4cplus::tstring (LOG4CPLUS_TEXT(".00")), log4cplus::tstring (LOG4CPLUS_TEXT(".0")), log4cplus::tstring (LOG4CPLUS_TEXT(".")) }; static void build_q_value (log4cplus::tstring & q_str, long tv_usec) { convertIntegerToString(q_str, tv_usec / 1000); std::size_t const len = q_str.length(); if (len <= 2) q_str.insert (0, padding_zeros[q_str.length()]); } static void build_uc_q_value (log4cplus::tstring & uc_q_str, long tv_usec, log4cplus::tstring & tmp) { build_q_value (uc_q_str, tv_usec); convertIntegerToString(tmp, tv_usec % 1000); std::size_t const usecs_len = tmp.length(); tmp.insert (0, usecs_len <= 3 ? uc_q_padding_zeros[usecs_len] : uc_q_padding_zeros[3]); uc_q_str.append (tmp); } } // namespace log4cplus::tstring Time::getFormattedTime(const log4cplus::tstring& fmt_orig, bool use_gmtime) const { if (fmt_orig.empty () || fmt_orig[0] == 0) return log4cplus::tstring (); tm time; if (use_gmtime) gmtime(&time); else localtime(&time); enum State { TEXT, PERCENT_SIGN }; internal::gft_scratch_pad & gft_sp = internal::get_gft_scratch_pad (); gft_sp.reset (); gft_sp.fmt.assign (fmt_orig); gft_sp.ret.reserve (static_cast<std::size_t>(gft_sp.fmt.size () * 1.35)); State state = TEXT; // Walk the format string and process all occurences of %q and %Q. for (log4cplus::tstring::const_iterator fmt_it = gft_sp.fmt.begin (); fmt_it != gft_sp.fmt.end (); ++fmt_it) { switch (state) { case TEXT: { if (*fmt_it == LOG4CPLUS_TEXT ('%')) state = PERCENT_SIGN; else gft_sp.ret.push_back (*fmt_it); } break; case PERCENT_SIGN: { switch (*fmt_it) { case LOG4CPLUS_TEXT ('q'): { if (! gft_sp.q_str_valid) { build_q_value (gft_sp.q_str, tv_usec); gft_sp.q_str_valid = true; } gft_sp.ret.append (gft_sp.q_str); state = TEXT; } break; case LOG4CPLUS_TEXT ('Q'): { if (! gft_sp.uc_q_str_valid) { build_uc_q_value (gft_sp.uc_q_str, tv_usec, gft_sp.tmp); gft_sp.uc_q_str_valid = true; } gft_sp.ret.append (gft_sp.uc_q_str); state = TEXT; } break; // Windows do not support %s format specifier // (seconds since epoch). case LOG4CPLUS_TEXT ('s'): { if (! gft_sp.s_str_valid) { convertIntegerToString (gft_sp.s_str, tv_sec); gft_sp.s_str_valid = true; } gft_sp.ret.append (gft_sp.s_str); state = TEXT; } break; default: { gft_sp.ret.push_back (LOG4CPLUS_TEXT ('%')); gft_sp.ret.push_back (*fmt_it); state = TEXT; } } } break; } } // Finally call strftime/wcsftime to format the rest of the string. gft_sp.ret.swap (gft_sp.fmt); std::size_t buffer_size = gft_sp.fmt.size () + 1; std::size_t len; // Limit how far can the buffer grow. This is necessary so that we // catch bad format string. Some implementations of strftime() signal // both too small buffer and invalid format string by returning 0 // without changing errno. std::size_t const buffer_size_max = (std::max) (static_cast<std::size_t>(1024), buffer_size * 16); do { gft_sp.buffer.resize (buffer_size); errno = 0; #ifdef UNICODE len = helpers::wcsftime(&gft_sp.buffer[0], buffer_size, gft_sp.fmt.c_str(), &time); #else len = helpers::strftime(&gft_sp.buffer[0], buffer_size, gft_sp.fmt.c_str(), &time); #endif if (len == 0) { int const eno = errno; buffer_size *= 2; if (buffer_size > buffer_size_max) { LogLog::getLogLog ()->error ( LOG4CPLUS_TEXT("Error in strftime(): ") + convertIntegerToString (eno), true); } } } while (len == 0); return tstring (gft_sp.buffer.begin (), gft_sp.buffer.begin () + len); } Time& Time::operator+=(const Time& rhs) { tv_sec += rhs.tv_sec; tv_usec += rhs.tv_usec; if(tv_usec > ONE_SEC_IN_USEC) { ++tv_sec; tv_usec -= ONE_SEC_IN_USEC; } return *this; } Time& Time::operator-=(const Time& rhs) { tv_sec -= rhs.tv_sec; tv_usec -= rhs.tv_usec; if(tv_usec < 0) { --tv_sec; tv_usec += ONE_SEC_IN_USEC; } return *this; } Time& Time::operator/=(long rhs) { long rem_secs = static_cast<long>(tv_sec % rhs); tv_sec /= rhs; tv_usec /= rhs; tv_usec += static_cast<long>((rem_secs * ONE_SEC_IN_USEC) / rhs); return *this; } Time& Time::operator*=(long rhs) { long new_usec = tv_usec * rhs; long overflow_sec = new_usec / ONE_SEC_IN_USEC; tv_usec = new_usec % ONE_SEC_IN_USEC; tv_sec *= rhs; tv_sec += overflow_sec; return *this; } ////////////////////////////////////////////////////////////////////////////// // Time globals ////////////////////////////////////////////////////////////////////////////// const Time operator+(const Time& lhs, const Time& rhs) { return Time(lhs) += rhs; } const Time operator-(const Time& lhs, const Time& rhs) { return Time(lhs) -= rhs; } const Time operator/(const Time& lhs, long rhs) { return Time(lhs) /= rhs; } const Time operator*(const Time& lhs, long rhs) { return Time(lhs) *= rhs; } bool operator<(const Time& lhs, const Time& rhs) { return ( (lhs.sec() < rhs.sec()) || ( (lhs.sec() == rhs.sec()) && (lhs.usec() < rhs.usec())) ); } bool operator<=(const Time& lhs, const Time& rhs) { return ((lhs < rhs) || (lhs == rhs)); } bool operator>(const Time& lhs, const Time& rhs) { return ( (lhs.sec() > rhs.sec()) || ( (lhs.sec() == rhs.sec()) && (lhs.usec() > rhs.usec())) ); } bool operator>=(const Time& lhs, const Time& rhs) { return ((lhs > rhs) || (lhs == rhs)); } bool operator==(const Time& lhs, const Time& rhs) { return ( lhs.sec() == rhs.sec() && lhs.usec() == rhs.usec()); } bool operator!=(const Time& lhs, const Time& rhs) { return !(lhs == rhs); } } } // namespace log4cplus { namespace helpers { <|endoftext|>
<commit_before> #include <string.h> #include "boxed.h" #include "function.h" #include "closure.h" #include "gi.h" #include "gobject.h" #include "type.h" #include "util.h" #include "value.h" using v8::Array; using v8::External; using v8::Function; using v8::FunctionTemplate; using v8::Local; using v8::Number; using v8::Object; using v8::String; using v8::Persistent; using Nan::New; using Nan::FunctionCallbackInfo; using Nan::WeakCallbackType; namespace GNodeJS { // Our base template for all GObjects static Nan::Persistent<FunctionTemplate> baseTemplate; static void GObjectDestroyed(const v8::WeakCallbackInfo<GObject> &data); static Local<FunctionTemplate> GetClassTemplateFromGI(GIBaseInfo *info); static bool InitGParameterFromProperty(GParameter *parameter, void *klass, Local<String> name, Local<Value> value) { // XXX js->c name conversion String::Utf8Value name_str (name); GParamSpec *pspec = g_object_class_find_property (G_OBJECT_CLASS (klass), *name_str); if (pspec == NULL) return false; GType value_type = G_PARAM_SPEC_VALUE_TYPE (pspec); parameter->name = pspec->name; g_value_init (&parameter->value, value_type); if (!CanConvertV8ToGValue(&parameter->value, value)) { std::string message = "Cannot convert value for property \""; message += *name_str; message += "\": expected type "; message += g_type_name(value_type); Nan::ThrowTypeError(message.c_str()); return false; } return V8ToGValue (&parameter->value, value); } static bool InitGParametersFromProperty(GParameter **parameters_p, int *n_parameters_p, void *klass, Local<Object> property_hash) { Local<Array> properties = property_hash->GetOwnPropertyNames (); int n_parameters = properties->Length (); GParameter *parameters = g_new0 (GParameter, n_parameters); for (int i = 0; i < n_parameters; i++) { Local<String> name = properties->Get(i)->ToString(); Local<Value> value = property_hash->Get (name); if (!InitGParameterFromProperty (&parameters[i], klass, name->ToString (), value)) g_warning("Couldn't initiate GParameter for property %s", *Nan::Utf8String(name)); } *parameters_p = parameters; *n_parameters_p = n_parameters; return true; } static void ToggleNotify(gpointer user_data, GObject *gobject, gboolean toggle_down) { void *data = g_object_get_qdata (gobject, GNodeJS::object_quark()); g_assert (data != NULL); auto *persistent = (Persistent<Object> *) data; if (toggle_down) { /* We're dropping from 2 refs to 1 ref. We are the last holder. Make * sure that that our weak ref is installed. */ persistent->SetWeak (gobject, GObjectDestroyed, v8::WeakCallbackType::kParameter); } else { /* We're going from 1 ref to 2 refs. We can't let our wrapper be * collected, so make sure that our reference is persistent */ persistent->ClearWeak (); } } static void AssociateGObject(Isolate *isolate, Local<Object> object, GObject *gobject) { object->SetAlignedPointerInInternalField (0, gobject); g_object_ref_sink (gobject); g_object_add_toggle_ref (gobject, ToggleNotify, NULL); Persistent<Object> *persistent = new Persistent<Object>(isolate, object); g_object_set_qdata (gobject, GNodeJS::object_quark(), persistent); } static void GObjectConstructor(const FunctionCallbackInfo<Value> &info) { Isolate *isolate = info.GetIsolate (); /* The flow of this function is a bit twisty. * There's two cases for when this code is called: * user code doing `new Gtk.Widget({ ... })`, and * internal code as part of WrapperFromGObject, where * the constructor is called with one external. */ if (!info.IsConstructCall ()) { Nan::ThrowTypeError("Not a construct call."); return; } Local<Object> self = info.This (); if (info[0]->IsExternal ()) { /* The External case. This is how WrapperFromGObject is called. */ void *data = External::Cast (*info[0])->Value (); GObject *gobject = G_OBJECT (data); AssociateGObject (isolate, self, gobject); Nan::DefineOwnProperty(self, Nan::New<String>("__gtype__").ToLocalChecked(), Nan::New<Number>(G_OBJECT_TYPE(gobject)), (v8::PropertyAttribute)(v8::PropertyAttribute::ReadOnly | v8::PropertyAttribute::DontEnum) ); } else { /* User code calling `new Gtk.Widget({ ... })` */ GObject *gobject; GIBaseInfo *gi_info = (GIBaseInfo *) External::Cast (*info.Data ())->Value (); GType gtype = g_registered_type_info_get_g_type ((GIRegisteredTypeInfo *) gi_info); void *klass = g_type_class_ref (gtype); GParameter *parameters = NULL; int n_parameters = 0; if (info[0]->IsObject ()) { Local<Object> property_hash = info[0]->ToObject (); if (!InitGParametersFromProperty (&parameters, &n_parameters, klass, property_hash)) { Nan::ThrowError("GObjectConstructor: Unable to make GParameters."); goto out; } } gobject = (GObject *) g_object_newv (gtype, n_parameters, parameters); AssociateGObject (isolate, self, gobject); Nan::DefineOwnProperty(self, Nan::New<String>("__gtype__").ToLocalChecked(), Nan::New<Number>(g_registered_type_info_get_g_type(gi_info)), v8::PropertyAttribute::ReadOnly ); out: g_free (parameters); g_type_class_unref (klass); } } static void GObjectDestroyed(const v8::WeakCallbackInfo<GObject> &data) { GObject *gobject = data.GetParameter (); void *type_data = g_object_get_qdata (gobject, GNodeJS::object_quark()); Persistent<Object> *persistent = (Persistent<Object> *) type_data; delete persistent; /* We're destroying the wrapper object, so make sure to clear out * the qdata that points back to us. */ g_object_set_qdata (gobject, GNodeJS::object_quark(), NULL); g_object_unref (gobject); } static gchar * SignalNameFromCamelCase (const gchar *name) { gsize len = strlen (name); GString *real = g_string_new (NULL); for (gsize i = 0; i < len; i++) { if (g_ascii_isupper (name[i])) { g_string_append_c (real, '-'); g_string_append_c (real, g_ascii_tolower (name[i])); } else g_string_append_c (real, name[i]); } return g_string_free (real, FALSE); } static void SignalConnectInternal(const Nan::FunctionCallbackInfo<v8::Value> &args, bool after) { Isolate *isolate = args.GetIsolate (); GObject *gobject = GObjectFromWrapper (args.This ()); if (!gobject) { Nan::ThrowTypeError("Object is not a GObject"); return; } if (!(args[0]->IsString() || args[0]->IsNumber())) { Nan::ThrowTypeError("Signal ID invalid"); return; } if (!args[1]->IsFunction()) { Nan::ThrowTypeError("Signal callback is not a function"); return; } Local<Function> callback = args[1].As<Function>(); GClosure *gclosure = MakeClosure (isolate, callback); ulong handler_id; if (args[0]->IsString()) { String::Utf8Value signal_name (args[0]->ToString ()); if (strchr(*signal_name, '-') != NULL) { gchar *real_name = SignalNameFromCamelCase (*signal_name); handler_id = g_signal_connect_closure (gobject, real_name, gclosure, after); g_free (real_name); } else { handler_id = g_signal_connect_closure (gobject, *signal_name, gclosure, after); } } else { guint signal_id = args[0].As<v8::Uint32>()->Value(); GQuark detail = 0; handler_id = g_signal_connect_closure_by_id (gobject, signal_id, detail, gclosure, after); } // TODO return some sort of cancellation handle? // e.g.: return { disposable: function () {...}, signal_id: ID }; // // auto fn = [&](const Nan::FunctionCallbackInfo<Value>&info) { g_signal_handler_disconnect(gobject, handler_id); }; // Local<Function> dispose = Nan::New<FunctionTemplate>(fn)->GetFunction(); args.GetReturnValue().Set((double)handler_id); } static void SignalDisconnectInternal(const Nan::FunctionCallbackInfo<v8::Value> &info) { GObject *gobject = GObjectFromWrapper (info.This ()); if (!gobject) { Nan::ThrowTypeError("Object is not a GObject"); return; } if (!info[0]->IsNumber()) { Nan::ThrowTypeError("Signal ID invalid"); return; } gpointer instance = static_cast<gpointer>(gobject); ulong handler_id = info[0]->NumberValue(); g_signal_handler_disconnect (instance, handler_id); info.GetReturnValue().Set((double)handler_id); } NAN_METHOD(SignalConnect) { SignalConnectInternal(info, false); } NAN_METHOD(SignalDisconnect) { SignalDisconnectInternal(info); } NAN_METHOD(GObjectToString) { Local<Object> self = info.This(); if (!ValueHasInternalField(self)) { Nan::ThrowTypeError("Object is not a GObject"); return; } GObject* g_object = GObjectFromWrapper(self); GType type = G_OBJECT_TYPE (g_object); const char* typeName = g_type_name(type); char *className = *String::Utf8Value(self->GetConstructorName()); void *address = self->GetAlignedPointerFromInternalField(0); char *str = g_strdup_printf("[%s:%s %#zx]", typeName, className, (unsigned long)address); info.GetReturnValue().Set(UTF8(str)); g_free(str); } Local<FunctionTemplate> GetBaseClassTemplate() { static bool isBaseClassCreated = false; if (!isBaseClassCreated) { isBaseClassCreated = true; Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(); Nan::SetPrototypeMethod(tpl, "connect", SignalConnect); Nan::SetPrototypeMethod(tpl, "disconnect", SignalDisconnect); Nan::SetPrototypeMethod(tpl, "toString", GObjectToString); baseTemplate.Reset(tpl); } // get FunctionTemplate from persistent object Local<FunctionTemplate> tpl = Nan::New(baseTemplate); return tpl; } static Local<FunctionTemplate> NewClassTemplate (GIBaseInfo *info) { const GType gtype = g_registered_type_info_get_g_type (info); g_assert(gtype != G_TYPE_NONE); const char *class_name = g_type_name (gtype); auto tpl = New<FunctionTemplate> (GObjectConstructor, New<External> (info)); Nan::SetTemplate(tpl, "gtype", New((double)gtype)); tpl->SetClassName (UTF8(class_name)); tpl->InstanceTemplate()->SetInternalFieldCount(1); GIObjectInfo *parent_info = g_object_info_get_parent (info); if (parent_info) { auto parent_tpl = GetClassTemplateFromGI ((GIBaseInfo *) parent_info); tpl->Inherit(parent_tpl); } else { tpl->Inherit(GetBaseClassTemplate()); } return tpl; } static Local<FunctionTemplate> GetClassTemplate(GType gtype) { void *data = g_type_get_qdata (gtype, GNodeJS::template_quark()); if (data) { auto *persistent = (Persistent<FunctionTemplate> *) data; auto tpl = New<FunctionTemplate> (*persistent); return tpl; } else { GIBaseInfo *gi_info = g_irepository_find_by_gtype(NULL, gtype); auto tpl = NewClassTemplate(gi_info); auto *persistent = new Persistent<FunctionTemplate>(Isolate::GetCurrent(), tpl); persistent->SetWeak ( g_base_info_ref (gi_info), GNodeJS::ClassDestroyed, WeakCallbackType::kParameter); g_type_set_qdata(gtype, GNodeJS::template_quark(), persistent); return tpl; } } static Local<FunctionTemplate> GetClassTemplateFromGI(GIBaseInfo *info) { GType gtype = g_registered_type_info_get_g_type ((GIRegisteredTypeInfo *) info); return GetClassTemplate(gtype); } Local<Function> MakeClass(GIBaseInfo *info) { auto tpl = GetClassTemplateFromGI (info); return tpl->GetFunction (); } Local<Value> WrapperFromGObject(GObject *gobject) { if (gobject == NULL) return Nan::Null(); void *data = g_object_get_qdata (gobject, GNodeJS::object_quark()); if (data) { /* Easy case: we already have an object. */ auto *persistent = (Persistent<Object> *) data; auto obj = New<Object> (*persistent); return obj; } else { GType gtype = G_OBJECT_TYPE(gobject); g_type_ensure(gtype); //void *klass = g_type_class_ref (type); auto tpl = GetClassTemplate(gtype); Local<Function> constructor = tpl->GetFunction (); Local<Value> gobject_external = New<External> (gobject); Local<Value> args[] = { gobject_external }; Local<Object> obj = Nan::NewInstance(constructor, 1, args).ToLocalChecked(); return obj; } } GObject * GObjectFromWrapper(Local<Value> value) { if (!ValueHasInternalField(value)) return nullptr; Local<Object> object = value->ToObject (); void *ptr = object->GetAlignedPointerFromInternalField (0); GObject *gobject = G_OBJECT (ptr); return gobject; } }; <commit_msg>gobject.cc: remove signal translation from camelCase<commit_after> #include <string.h> #include "boxed.h" #include "function.h" #include "closure.h" #include "gi.h" #include "gobject.h" #include "type.h" #include "util.h" #include "value.h" using v8::Array; using v8::External; using v8::Function; using v8::FunctionTemplate; using v8::Local; using v8::Number; using v8::Object; using v8::String; using v8::Persistent; using Nan::New; using Nan::FunctionCallbackInfo; using Nan::WeakCallbackType; namespace GNodeJS { // Our base template for all GObjects static Nan::Persistent<FunctionTemplate> baseTemplate; static void GObjectDestroyed(const v8::WeakCallbackInfo<GObject> &data); static Local<FunctionTemplate> GetClassTemplateFromGI(GIBaseInfo *info); static bool InitGParameterFromProperty(GParameter *parameter, void *klass, Local<String> name, Local<Value> value) { // XXX js->c name conversion String::Utf8Value name_str (name); GParamSpec *pspec = g_object_class_find_property (G_OBJECT_CLASS (klass), *name_str); if (pspec == NULL) return false; GType value_type = G_PARAM_SPEC_VALUE_TYPE (pspec); parameter->name = pspec->name; g_value_init (&parameter->value, value_type); if (!CanConvertV8ToGValue(&parameter->value, value)) { std::string message = "Cannot convert value for property \""; message += *name_str; message += "\": expected type "; message += g_type_name(value_type); Nan::ThrowTypeError(message.c_str()); return false; } return V8ToGValue (&parameter->value, value); } static bool InitGParametersFromProperty(GParameter **parameters_p, int *n_parameters_p, void *klass, Local<Object> property_hash) { Local<Array> properties = property_hash->GetOwnPropertyNames (); int n_parameters = properties->Length (); GParameter *parameters = g_new0 (GParameter, n_parameters); for (int i = 0; i < n_parameters; i++) { Local<String> name = properties->Get(i)->ToString(); Local<Value> value = property_hash->Get (name); if (!InitGParameterFromProperty (&parameters[i], klass, name->ToString (), value)) g_warning("Couldn't initiate GParameter for property %s", *Nan::Utf8String(name)); } *parameters_p = parameters; *n_parameters_p = n_parameters; return true; } static void ToggleNotify(gpointer user_data, GObject *gobject, gboolean toggle_down) { void *data = g_object_get_qdata (gobject, GNodeJS::object_quark()); g_assert (data != NULL); auto *persistent = (Persistent<Object> *) data; if (toggle_down) { /* We're dropping from 2 refs to 1 ref. We are the last holder. Make * sure that that our weak ref is installed. */ persistent->SetWeak (gobject, GObjectDestroyed, v8::WeakCallbackType::kParameter); } else { /* We're going from 1 ref to 2 refs. We can't let our wrapper be * collected, so make sure that our reference is persistent */ persistent->ClearWeak (); } } static void AssociateGObject(Isolate *isolate, Local<Object> object, GObject *gobject) { object->SetAlignedPointerInInternalField (0, gobject); g_object_ref_sink (gobject); g_object_add_toggle_ref (gobject, ToggleNotify, NULL); Persistent<Object> *persistent = new Persistent<Object>(isolate, object); g_object_set_qdata (gobject, GNodeJS::object_quark(), persistent); } static void GObjectConstructor(const FunctionCallbackInfo<Value> &info) { Isolate *isolate = info.GetIsolate (); /* The flow of this function is a bit twisty. * There's two cases for when this code is called: * user code doing `new Gtk.Widget({ ... })`, and * internal code as part of WrapperFromGObject, where * the constructor is called with one external. */ if (!info.IsConstructCall ()) { Nan::ThrowTypeError("Not a construct call."); return; } Local<Object> self = info.This (); if (info[0]->IsExternal ()) { /* The External case. This is how WrapperFromGObject is called. */ void *data = External::Cast (*info[0])->Value (); GObject *gobject = G_OBJECT (data); AssociateGObject (isolate, self, gobject); Nan::DefineOwnProperty(self, Nan::New<String>("__gtype__").ToLocalChecked(), Nan::New<Number>(G_OBJECT_TYPE(gobject)), (v8::PropertyAttribute)(v8::PropertyAttribute::ReadOnly | v8::PropertyAttribute::DontEnum) ); } else { /* User code calling `new Gtk.Widget({ ... })` */ GObject *gobject; GIBaseInfo *gi_info = (GIBaseInfo *) External::Cast (*info.Data ())->Value (); GType gtype = g_registered_type_info_get_g_type ((GIRegisteredTypeInfo *) gi_info); void *klass = g_type_class_ref (gtype); GParameter *parameters = NULL; int n_parameters = 0; if (info[0]->IsObject ()) { Local<Object> property_hash = info[0]->ToObject (); if (!InitGParametersFromProperty (&parameters, &n_parameters, klass, property_hash)) { Nan::ThrowError("GObjectConstructor: Unable to make GParameters."); goto out; } } gobject = (GObject *) g_object_newv (gtype, n_parameters, parameters); AssociateGObject (isolate, self, gobject); Nan::DefineOwnProperty(self, Nan::New<String>("__gtype__").ToLocalChecked(), Nan::New<Number>(g_registered_type_info_get_g_type(gi_info)), v8::PropertyAttribute::ReadOnly ); out: g_free (parameters); g_type_class_unref (klass); } } static void GObjectDestroyed(const v8::WeakCallbackInfo<GObject> &data) { GObject *gobject = data.GetParameter (); void *type_data = g_object_get_qdata (gobject, GNodeJS::object_quark()); Persistent<Object> *persistent = (Persistent<Object> *) type_data; delete persistent; /* We're destroying the wrapper object, so make sure to clear out * the qdata that points back to us. */ g_object_set_qdata (gobject, GNodeJS::object_quark(), NULL); g_object_unref (gobject); } static void SignalConnectInternal(const Nan::FunctionCallbackInfo<v8::Value> &args, bool after) { Isolate *isolate = args.GetIsolate (); GObject *gobject = GObjectFromWrapper (args.This ()); if (!gobject) { Nan::ThrowTypeError("Object is not a GObject"); return; } if (!(args[0]->IsString() || args[0]->IsNumber())) { Nan::ThrowTypeError("Signal ID invalid"); return; } if (!args[1]->IsFunction()) { Nan::ThrowTypeError("Signal callback is not a function"); return; } Local<Function> callback = args[1].As<Function>(); GClosure *gclosure = MakeClosure (isolate, callback); ulong handler_id; if (args[0]->IsString()) { String::Utf8Value signal_name (args[0]->ToString ()); handler_id = g_signal_connect_closure (gobject, *signal_name, gclosure, after); } else { guint signal_id = args[0].As<v8::Uint32>()->Value(); GQuark detail = 0; handler_id = g_signal_connect_closure_by_id (gobject, signal_id, detail, gclosure, after); } // TODO return some sort of cancellation handle? // e.g.: return { disposable: function () {...}, signal_id: ID }; // // auto fn = [&](const Nan::FunctionCallbackInfo<Value>&info) { g_signal_handler_disconnect(gobject, handler_id); }; // Local<Function> dispose = Nan::New<FunctionTemplate>(fn)->GetFunction(); args.GetReturnValue().Set((double)handler_id); } static void SignalDisconnectInternal(const Nan::FunctionCallbackInfo<v8::Value> &info) { GObject *gobject = GObjectFromWrapper (info.This ()); if (!gobject) { Nan::ThrowTypeError("Object is not a GObject"); return; } if (!info[0]->IsNumber()) { Nan::ThrowTypeError("Signal ID invalid"); return; } gpointer instance = static_cast<gpointer>(gobject); ulong handler_id = info[0]->NumberValue(); g_signal_handler_disconnect (instance, handler_id); info.GetReturnValue().Set((double)handler_id); } NAN_METHOD(SignalConnect) { SignalConnectInternal(info, false); } NAN_METHOD(SignalDisconnect) { SignalDisconnectInternal(info); } NAN_METHOD(GObjectToString) { Local<Object> self = info.This(); if (!ValueHasInternalField(self)) { Nan::ThrowTypeError("Object is not a GObject"); return; } GObject* g_object = GObjectFromWrapper(self); GType type = G_OBJECT_TYPE (g_object); const char* typeName = g_type_name(type); char *className = *String::Utf8Value(self->GetConstructorName()); void *address = self->GetAlignedPointerFromInternalField(0); char *str = g_strdup_printf("[%s:%s %#zx]", typeName, className, (unsigned long)address); info.GetReturnValue().Set(UTF8(str)); g_free(str); } Local<FunctionTemplate> GetBaseClassTemplate() { static bool isBaseClassCreated = false; if (!isBaseClassCreated) { isBaseClassCreated = true; Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(); Nan::SetPrototypeMethod(tpl, "connect", SignalConnect); Nan::SetPrototypeMethod(tpl, "disconnect", SignalDisconnect); Nan::SetPrototypeMethod(tpl, "toString", GObjectToString); baseTemplate.Reset(tpl); } // get FunctionTemplate from persistent object Local<FunctionTemplate> tpl = Nan::New(baseTemplate); return tpl; } static Local<FunctionTemplate> NewClassTemplate (GIBaseInfo *info) { const GType gtype = g_registered_type_info_get_g_type (info); g_assert(gtype != G_TYPE_NONE); const char *class_name = g_type_name (gtype); auto tpl = New<FunctionTemplate> (GObjectConstructor, New<External> (info)); Nan::SetTemplate(tpl, "gtype", New((double)gtype)); tpl->SetClassName (UTF8(class_name)); tpl->InstanceTemplate()->SetInternalFieldCount(1); GIObjectInfo *parent_info = g_object_info_get_parent (info); if (parent_info) { auto parent_tpl = GetClassTemplateFromGI ((GIBaseInfo *) parent_info); tpl->Inherit(parent_tpl); } else { tpl->Inherit(GetBaseClassTemplate()); } return tpl; } static Local<FunctionTemplate> GetClassTemplate(GType gtype) { void *data = g_type_get_qdata (gtype, GNodeJS::template_quark()); if (data) { auto *persistent = (Persistent<FunctionTemplate> *) data; auto tpl = New<FunctionTemplate> (*persistent); return tpl; } else { GIBaseInfo *gi_info = g_irepository_find_by_gtype(NULL, gtype); auto tpl = NewClassTemplate(gi_info); auto *persistent = new Persistent<FunctionTemplate>(Isolate::GetCurrent(), tpl); persistent->SetWeak ( g_base_info_ref (gi_info), GNodeJS::ClassDestroyed, WeakCallbackType::kParameter); g_type_set_qdata(gtype, GNodeJS::template_quark(), persistent); return tpl; } } static Local<FunctionTemplate> GetClassTemplateFromGI(GIBaseInfo *info) { GType gtype = g_registered_type_info_get_g_type ((GIRegisteredTypeInfo *) info); return GetClassTemplate(gtype); } Local<Function> MakeClass(GIBaseInfo *info) { auto tpl = GetClassTemplateFromGI (info); return tpl->GetFunction (); } Local<Value> WrapperFromGObject(GObject *gobject) { if (gobject == NULL) return Nan::Null(); void *data = g_object_get_qdata (gobject, GNodeJS::object_quark()); if (data) { /* Easy case: we already have an object. */ auto *persistent = (Persistent<Object> *) data; auto obj = New<Object> (*persistent); return obj; } else { GType gtype = G_OBJECT_TYPE(gobject); g_type_ensure(gtype); //void *klass = g_type_class_ref (type); auto tpl = GetClassTemplate(gtype); Local<Function> constructor = tpl->GetFunction (); Local<Value> gobject_external = New<External> (gobject); Local<Value> args[] = { gobject_external }; Local<Object> obj = Nan::NewInstance(constructor, 1, args).ToLocalChecked(); return obj; } } GObject * GObjectFromWrapper(Local<Value> value) { if (!ValueHasInternalField(value)) return nullptr; Local<Object> object = value->ToObject (); void *ptr = object->GetAlignedPointerFromInternalField (0); GObject *gobject = G_OBJECT (ptr); return gobject; } }; <|endoftext|>
<commit_before>#include "text.h" #include <algorithm> #include <array> #include <functional> #include <regex> #include <tuple> #include <cstring> #include "ada/string.h" namespace { template<typename T1> // Helper operator shorthand: [enum_t] -> [size_t]. constexpr size_t operator+(T1 some_enum) { return static_cast<size_t>(some_enum); } template<typename T1> std::string create_regex_term(T1 regex_piece, const std::string& keyword) { std::ostringstream os; for(size_t i = 0; i < regex_piece.size()-1; ++i) { os << std::begin(regex_piece)[i] << keyword; } os << std::begin(regex_piece)[regex_piece.size()-1]; return os.str(); }; template<typename T1, typename T2> std::regex make_regex(T1 regex_pattern_check, T2 listings_keyword) { return std::regex{create_regex_term(regex_pattern_check, std::get<1>(listings_keyword))}; }; std::tuple<bool, std::smatch> does_any_of_the_regex_exist(const std::string& _source, std::regex re) { // Split Source code in lines const auto lines = ada::split(_source, '\n'); std::smatch match; const auto match_found = std::any_of(std::begin(lines), std::end(lines) , [&](const std::string& line) { return std::regex_search(line, match, re); }); return { match_found, match }; } using regex_stringdata_t = const char * const; template<typename T1> using regex_string_t = std::tuple<T1, regex_stringdata_t>; enum class regex_check_t { Convolution_Pyramid, Floor, Background, Post_Processing, MAX_KEYWORDS_CHECK_IDS }; using regex_check_string_t = regex_string_t<regex_check_t>; const auto valid_check_keyword_ids = std::array<regex_check_string_t, +(regex_check_t::MAX_KEYWORDS_CHECK_IDS)> {{ {regex_check_t::Convolution_Pyramid, "CONVOLUTION_PYRAMID_ALGORITHM"} , {regex_check_t::Floor,"FLOOR"} , {regex_check_t::Background, "BACKGROUND"} , {regex_check_t::Post_Processing, "POSTPROCESSING"} }}; bool generic_search_check(const std::string& _source, regex_check_t keyword_id ) { const auto regex_pattern_check = { R"((?:^\s*#if|^\s*#elif)(?:\s+)(defined\s*\(\s*)" , R"()(?:\s*\))|(?:^\s*#ifdef\s+)" , R"()|(?:^\s*#ifndef\s+)" , R"())" }; const auto re = make_regex(regex_pattern_check, valid_check_keyword_ids[+(keyword_id)]); return std::get<0>(does_any_of_the_regex_exist(_source, re)); //return only the "result" boolean. } enum class regex_count_t { Buffers, Double_Buffers, Convolution_Pyramid, MAX_KEYWORDS_COUNT_IDS }; using regex_count_string_t = regex_string_t<regex_count_t>; const auto valid_count_keyword_ids = std::array<regex_count_string_t, +(regex_count_t::MAX_KEYWORDS_COUNT_IDS)> {{ {regex_count_t::Buffers, "BUFFER"} , {regex_count_t::Double_Buffers, "DOUBLE_BUFFER"} , {regex_count_t::Convolution_Pyramid, "CONVOLUTION_PYRAMID"} }}; struct is_not_duplicate_number_predicate { // Group results in a vector to check for duplicates std::vector<std::string> results = {}; bool operator()(const std::string &line, const std::regex &re) { std::smatch match = {}; // if there are matches if (std::regex_search(line, match, re)) { // Depending the case can be in the 2nd or 3rd group const auto case_group = [&](size_t index){return std::ssub_match(match[index]).str();}; const auto number = (case_group(2).size() == 0) ? case_group(3) : case_group(2); // Check if it's already defined // If it's not add it if (!std::any_of(std::begin(results), std::end(results) , [&](const std::string& index){ return index == number; })) { results.push_back(number); return true; } } return false; } }; int generic_search_count(const std::string& _source, regex_count_t keyword_id ) { const auto regex_pattern_count = { R"((?:^\s*#if|^\s*#elif)(?:\s+)(defined\s*\(\s*)" , R"(_)(\d+)(?:\s*\))|(?:^\s*#ifdef\s+)" , R"(_)(\d+))" }; // Split Source code in lines const auto lines = ada::split(_source, '\n'); // Regext to search for #ifdef BUFFER_[NUMBER], #if defined( BUFFER_[NUMBER] ) and #elif defined( BUFFER_[NUMBER] ) occurences const auto re = make_regex(regex_pattern_count, valid_count_keyword_ids[+(keyword_id)]); // return the number of results auto predicate_op = is_not_duplicate_number_predicate{}; return std::count_if(std::begin(lines), std::end(lines), [&](const std::string& line) { return std::ref(predicate_op)(line, re); }); } enum class regex_get_t { BufferSize, MAX_KEYWORDS_GET_IDS }; using regex_get_string_t = regex_string_t<regex_get_t>; const auto valid_get_keyword_ids = std::array<regex_get_string_t, +(regex_get_t::MAX_KEYWORDS_GET_IDS)> {{ {regex_get_t::BufferSize, R"(uniform\s*sampler2D\s*(\w*)\;\s*\/\/*\s(\d+)x(\d+))"} }}; bool generic_search_get(const std::string& _source, const std::string& _name, glm::vec2& _size, regex_get_t keyword_id ) { bool result; std::smatch match; const auto re = std::regex{std::get<1>(valid_get_keyword_ids[+(keyword_id)])}; std::tie(result, match) = does_any_of_the_regex_exist(_source, re); // capture both the "result" and the "match" info. if(result) { if (match[1] == _name) { // regex-match result data is valid to spec. _size = {ada::toFloat(match[2]), ada::toFloat(match[3])}; } } return result; } } // Namespace {} // Quickly determine if a shader program contains the specified identifier. bool findId(const std::string& program, const char* id) { return std::strstr(program.c_str(), id) != 0; } // Count how many BUFFERS are in the shader int countBuffers(const std::string& _source) { return generic_search_count(_source, regex_count_t::Buffers); } bool getBufferSize(const std::string& _source, const std::string& _name, glm::vec2& _size) { return generic_search_get(_source, _name, _size, regex_get_t::BufferSize); } // Count how many BUFFERS are in the shader int countDoubleBuffers(const std::string& _source) { return generic_search_count(_source, regex_count_t::Double_Buffers); } // Count how many BUFFERS are in the shader bool checkBackground(const std::string& _source) { return generic_search_check(_source, regex_check_t::Background); } // Count how many BUFFERS are in the shader bool checkFloor(const std::string& _source) { return generic_search_check(_source, regex_check_t::Floor); } bool checkPostprocessing(const std::string& _source) { return generic_search_check(_source, regex_check_t::Post_Processing); } // Count how many CONVOLUTION_PYRAMID_ are in the shader int countConvolutionPyramid(const std::string& _source) { return generic_search_count(_source, regex_count_t::Convolution_Pyramid); } bool checkConvolutionPyramid(const std::string& _source) { return generic_search_check(_source, regex_check_t::Convolution_Pyramid); } std::string getUniformName(const std::string& _str) { std::vector<std::string> values = ada::split(_str, '.'); return "u_" + ada::toLower( ada::toUnderscore( ada::purifyString( values[0] ) ) ); } bool checkPattern(const std::string& _str) { return (_str.find('*') != std::string::npos) || (_str.find('?') != std::string::npos); } <commit_msg>tools: prefer classic variable declaration<commit_after>#include "text.h" #include <algorithm> #include <array> #include <functional> #include <regex> #include <tuple> #include <cstring> #include "ada/string.h" namespace { template<typename T1> // Helper operator shorthand: [enum_t] -> [size_t]. constexpr size_t operator+(T1 some_enum) { return static_cast<size_t>(some_enum); } template<typename T1> std::string create_regex_term(T1 regex_piece, const std::string& keyword) { std::ostringstream os; for(size_t i = 0; i < regex_piece.size()-1; ++i) { os << std::begin(regex_piece)[i] << keyword; } os << std::begin(regex_piece)[regex_piece.size()-1]; return os.str(); }; template<typename T1, typename T2> std::regex make_regex(T1 regex_pattern_check, T2 listings_keyword) { return std::regex{create_regex_term(regex_pattern_check, std::get<1>(listings_keyword))}; }; std::tuple<bool, std::smatch> does_any_of_the_regex_exist(const std::string& _source, std::regex re) { // Split Source code in lines const auto lines = ada::split(_source, '\n'); std::smatch match; const auto match_found = std::any_of(std::begin(lines), std::end(lines) , [&](const std::string& line) { return std::regex_search(line, match, re); }); return { match_found, match }; } using regex_stringdata_t = const char * const; template<typename T1> using regex_string_t = std::tuple<T1, regex_stringdata_t>; enum class regex_check_t { Convolution_Pyramid, Floor, Background, Post_Processing, MAX_KEYWORDS_CHECK_IDS }; using regex_check_string_t = regex_string_t<regex_check_t>; const auto valid_check_keyword_ids = std::array<regex_check_string_t, +(regex_check_t::MAX_KEYWORDS_CHECK_IDS)> {{ {regex_check_t::Convolution_Pyramid, "CONVOLUTION_PYRAMID_ALGORITHM"} , {regex_check_t::Floor,"FLOOR"} , {regex_check_t::Background, "BACKGROUND"} , {regex_check_t::Post_Processing, "POSTPROCESSING"} }}; bool generic_search_check(const std::string& _source, regex_check_t keyword_id ) { const auto regex_pattern_check = { R"((?:^\s*#if|^\s*#elif)(?:\s+)(defined\s*\(\s*)" , R"()(?:\s*\))|(?:^\s*#ifdef\s+)" , R"()|(?:^\s*#ifndef\s+)" , R"())" }; const auto re = make_regex(regex_pattern_check, valid_check_keyword_ids[+(keyword_id)]); return std::get<0>(does_any_of_the_regex_exist(_source, re)); //return only the "result" boolean. } enum class regex_count_t { Buffers, Double_Buffers, Convolution_Pyramid, MAX_KEYWORDS_COUNT_IDS }; using regex_count_string_t = regex_string_t<regex_count_t>; const auto valid_count_keyword_ids = std::array<regex_count_string_t, +(regex_count_t::MAX_KEYWORDS_COUNT_IDS)> {{ {regex_count_t::Buffers, "BUFFER"} , {regex_count_t::Double_Buffers, "DOUBLE_BUFFER"} , {regex_count_t::Convolution_Pyramid, "CONVOLUTION_PYRAMID"} }}; struct is_not_duplicate_number_predicate { // Group results in a vector to check for duplicates std::vector<std::string> results = {}; bool operator()(const std::string &line, const std::regex &re) { std::smatch match; // if there are matches if (std::regex_search(line, match, re)) { // Depending the case can be in the 2nd or 3rd group const auto case_group = [&](size_t index){return std::ssub_match(match[index]).str();}; const auto number = (case_group(2).size() == 0) ? case_group(3) : case_group(2); // Check if it's already defined // If it's not add it if (!std::any_of(std::begin(results), std::end(results) , [&](const std::string& index){ return index == number; })) { results.push_back(number); return true; } } return false; } }; int generic_search_count(const std::string& _source, regex_count_t keyword_id ) { const auto regex_pattern_count = { R"((?:^\s*#if|^\s*#elif)(?:\s+)(defined\s*\(\s*)" , R"(_)(\d+)(?:\s*\))|(?:^\s*#ifdef\s+)" , R"(_)(\d+))" }; // Split Source code in lines const auto lines = ada::split(_source, '\n'); // Regext to search for #ifdef BUFFER_[NUMBER], #if defined( BUFFER_[NUMBER] ) and #elif defined( BUFFER_[NUMBER] ) occurences const auto re = make_regex(regex_pattern_count, valid_count_keyword_ids[+(keyword_id)]); // return the number of results auto predicate_op = is_not_duplicate_number_predicate{}; return std::count_if(std::begin(lines), std::end(lines), [&](const std::string& line) { return std::ref(predicate_op)(line, re); }); } enum class regex_get_t { BufferSize, MAX_KEYWORDS_GET_IDS }; using regex_get_string_t = regex_string_t<regex_get_t>; const auto valid_get_keyword_ids = std::array<regex_get_string_t, +(regex_get_t::MAX_KEYWORDS_GET_IDS)> {{ {regex_get_t::BufferSize, R"(uniform\s*sampler2D\s*(\w*)\;\s*\/\/*\s(\d+)x(\d+))"} }}; bool generic_search_get(const std::string& _source, const std::string& _name, glm::vec2& _size, regex_get_t keyword_id ) { bool result; std::smatch match; const auto re = std::regex{std::get<1>(valid_get_keyword_ids[+(keyword_id)])}; std::tie(result, match) = does_any_of_the_regex_exist(_source, re); // capture both the "result" and the "match" info. if(result) { if (match[1] == _name) { // regex-match result data is valid to spec. _size = {ada::toFloat(match[2]), ada::toFloat(match[3])}; } } return result; } } // Namespace {} // Quickly determine if a shader program contains the specified identifier. bool findId(const std::string& program, const char* id) { return std::strstr(program.c_str(), id) != 0; } // Count how many BUFFERS are in the shader int countBuffers(const std::string& _source) { return generic_search_count(_source, regex_count_t::Buffers); } bool getBufferSize(const std::string& _source, const std::string& _name, glm::vec2& _size) { return generic_search_get(_source, _name, _size, regex_get_t::BufferSize); } // Count how many BUFFERS are in the shader int countDoubleBuffers(const std::string& _source) { return generic_search_count(_source, regex_count_t::Double_Buffers); } // Count how many BUFFERS are in the shader bool checkBackground(const std::string& _source) { return generic_search_check(_source, regex_check_t::Background); } // Count how many BUFFERS are in the shader bool checkFloor(const std::string& _source) { return generic_search_check(_source, regex_check_t::Floor); } bool checkPostprocessing(const std::string& _source) { return generic_search_check(_source, regex_check_t::Post_Processing); } // Count how many CONVOLUTION_PYRAMID_ are in the shader int countConvolutionPyramid(const std::string& _source) { return generic_search_count(_source, regex_count_t::Convolution_Pyramid); } bool checkConvolutionPyramid(const std::string& _source) { return generic_search_check(_source, regex_check_t::Convolution_Pyramid); } std::string getUniformName(const std::string& _str) { std::vector<std::string> values = ada::split(_str, '.'); return "u_" + ada::toLower( ada::toUnderscore( ada::purifyString( values[0] ) ) ); } bool checkPattern(const std::string& _str) { return (_str.find('*') != std::string::npos) || (_str.find('?') != std::string::npos); } <|endoftext|>
<commit_before>#include "control.h" int Curso::codigo = 0; void Control::inicializador() { U = new Universidad(); CE = new Contenedor_Escuelas(); CC = new Contenedor_Cursos(); Escuela* E1 = new Escuela("Ingles"); Escuela* E2 = new Escuela("Matematicas"); Escuela* E3 = new Escuela("Geologia"); Escuela* E4 = new Escuela("Sociales"); CE->insertaralInicio(E1); CE->insertaralInicio(E2); CE->insertaralInicio(E3); CE->insertaralInicio(E4); Curso* CU1 = new Curso("Programacion I", E1->getSiglaEscuela()); Curso* CU2 = new Curso("Programacion II", E2->getSiglaEscuela()); E1->insertarCurso(CU1); E2->insertarCurso(CU2); principal(); } void Control::principal() { Interfaz::vBienvenida(); if (Interfaz::vDatosPrimeraVez(U) == 'S') { Interfaz::vIngresarNombre(U); Interfaz::vIngresarNumero(U); Interfaz::vIngresarDireccion(U); } bool end = false; do { char ans = Interfaz::vMenuPrincipal(); switch (ans) { case '1': { Interfaz::vtoString(U); break; } case '2': { Interfaz::vtoStringEscuelas(U, CE, '1'); break; } case '3': { Interfaz::vtoStringEscuelas(U, CE, '2'); break; } case '4': { ajustes(); break; } case '5': { delete CC; delete CE; //se encarga de eliminar donde estan alojadas las escuelas (composicion) delete U; end = true; break; } default: break; } } while (end == false); } void Control::ajustes() { bool end = false; do { char opcion = Interfaz::vMenuAjustes(U); if (U->getNombre() == "Undefined") { switch (opcion) { case '1': { Interfaz::vIngresarNombre(U); break; } case '2': { Interfaz::vIngresarNumero(U); break; } case '3': { Interfaz::vIngresarDireccion(U); break; } case '4': { end = true; break; } default: break; } } else { switch (opcion) { case '1': { Interfaz::vIngresarNumero(U); break; } case '2': { Interfaz::vIngresarDireccion(U); break; } case '3': { Interfaz::vIngresaEscuela(CE); } case '4': { end = true; break; } default: break; } } } while (end == false); } <commit_msg>Agrego datos de la U para que no me los pida al inicio, esto obviamente debe cambair<commit_after>#include "control.h" int Curso::codigo = 0; void Control::inicializador() { U = new Universidad("Universidad de Costa Rica", "22334455", "San Pedro"); CE = new Contenedor_Escuelas(); CC = new Contenedor_Cursos(); Escuela* E1 = new Escuela("Ingles"); Escuela* E2 = new Escuela("Matematicas"); Escuela* E3 = new Escuela("Geologia"); Escuela* E4 = new Escuela("Sociales"); CE->insertaralInicio(E1); CE->insertaralInicio(E2); CE->insertaralInicio(E3); CE->insertaralInicio(E4); Curso* CU1 = new Curso("Programacion I", E1->getSiglaEscuela()); Curso* CU2 = new Curso("Programacion II", E2->getSiglaEscuela()); E1->insertarCurso(CU1); E2->insertarCurso(CU2); principal(); } void Control::principal() { Interfaz::vBienvenida(); if (Interfaz::vDatosPrimeraVez(U) == 'S') { Interfaz::vIngresarNombre(U); Interfaz::vIngresarNumero(U); Interfaz::vIngresarDireccion(U); } bool end = false; do { char ans = Interfaz::vMenuPrincipal(); switch (ans) { case '1': { Interfaz::vtoString(U); break; } case '2': { Interfaz::vtoStringEscuelas(U, CE, '1'); break; } case '3': { Interfaz::vtoStringEscuelas(U, CE, '2'); break; } case '4': { ajustes(); break; } case '5': { delete CC; delete CE; //se encarga de eliminar donde estan alojadas las escuelas (composicion) delete U; end = true; break; } default: break; } } while (end == false); } void Control::ajustes() { bool end = false; do { char opcion = Interfaz::vMenuAjustes(U); if (U->getNombre() == "Undefined") { switch (opcion) { case '1': { Interfaz::vIngresarNombre(U); break; } case '2': { Interfaz::vIngresarNumero(U); break; } case '3': { Interfaz::vIngresarDireccion(U); break; } case '4': { end = true; break; } default: break; } } else { switch (opcion) { case '1': { Interfaz::vIngresarNumero(U); break; } case '2': { Interfaz::vIngresarDireccion(U); break; } case '3': { Interfaz::vIngresaEscuela(CE); } case '4': { end = true; break; } default: break; } } } while (end == false); } <|endoftext|>
<commit_before>//Full wet 0 //Full Dry 5v (possibly) #include "MoistureSensor.h" class MoistureSensor{ private: const int PROBE; const int SENSOR; int wetVoltage; int dryVoltage; double moistVoltage; bool isDryState; bool isWetState; bool isMoistState; int sensorValue; double sensorVoltage; public: MoistureSensor(const int probePin, const int sensorPin, int wVoltage = 0, int dVoltage = 5, double mVoltage = 2.5) : PROBE(probePin), SENSOR(sensorPin), wetVoltage(wVoltage), dryVoltage(dVoltage), moistVoltage(mVoltage), isDryState(true), isWetState(false), isMoistState(false) { //setMoistVoltage(readSensor()); } ~MoistureSensor(){} /* Power on the Probe, delay to allow stabilisation and return true if successful */ bool turnOnProbe() { digitalWrite(PROBE, HIGH); delay(1000); return digitalRead(PROBE); } /* Power off the Probe and return true if successful */ bool turnOffProbe() { digitalWrite(PROBE, LOW); return !digitalRead(PROBE); } /** Reads the Value of the Water sensor on the PIN it's on and returns a voltage */ double readSensor() { if (!digitalRead(PROBE)){ turnOnProbe(); } //Do I need Setters??? sensorValue = analogRead(PROBE); sensorVoltage = map(sensorValue, 0, 1024, 0, 5); turnOffProbe(); return sensorVoltage; } /* Sets the the flag as to whether the sensor is reading wet, dry or moist. */ void moistureLevel(double sVoltage){ //TODO Fix this Logic...it wrong if(sVoltage >= getWetVoltage()) { setWettness(true, false, false); } else if(sVoltage <= getMoistVoltage() && sVoltage > getWetVoltage()) { setWettness(false, true, false); } else if(sVoltage <= getDryVoltage() and sVoltage > getMoistVoltage()) { setWettness(false, false, true); } else { //sensor failure as voltage below 0v (negative) or above 5v setWettness(false, false, false); } } //Decide what are public and private /** Getters */ int getWetVoltage() { return wetVoltage; } int getDryVoltage() { return dryVoltage; } double getMoistVoltage() { return moistVoltage; } bool isDry() {return isDryState; } bool isMoist() {return isMoistState; } bool isWet() {return isWetState; } /** Setters */ void setWetVoltage(int wetVoltage) { wetVoltage = wetVoltage; } void setDryVoltage(int dryVoltage) { dryVoltage = dryVoltage; } void setMoistVoltage(double moistVoltage) { moistVoltage = moistVoltage; } void setWettness(bool isD, bool isM, bool isW) { isDryState = isD; isMoistState = isM; isWetState = isW; } }; <commit_msg>Single file separate class and methods<commit_after>//Full wet 0 //Full Dry 5v (possibly) #include <Arduino.h> //#include <WProgram.h> class MoistureSensor{ private: const int PROBE; const int SENSOR; int wetVoltage; int dryVoltage; double moistVoltage; bool isDryState; bool isWetState; bool isMoistState; int sensorValue; double sensorVoltage; public: MoistureSensor(const int probePin, const int sensorPin, int wVoltage = 0, int dVoltage = 5, double mVoltage = 2.5); ~MoistureSensor(); bool turnOnProbe(); bool turnOffProbe(); double readSensor(); void moistureLevel(double sVoltage); int getProbe(); int getSensor(); int getWetVoltage(); int getDryVoltage(); double getMoistVoltage(); bool isDry(); bool isMoist(); bool isWet(); /** Setters */ void setWetVoltage(int wetVoltage); void setDryVoltage(int dryVoltage); void setMoistVoltage(double moistVoltage); void setWettness(bool isD, bool isM, bool isW); }; MoistureSensor::MoistureSensor(const int probePin, const int sensorPin, int wVoltage, int dVoltage, double mVoltage) : PROBE(probePin), SENSOR(sensorPin), wetVoltage(wVoltage), dryVoltage(dVoltage), moistVoltage(mVoltage), isDryState(true), isWetState(false), isMoistState(false) { //setMoistVoltage(readSensor()); } //Destructor MoistureSensor::~MoistureSensor(){} /* Power on the Probe, delay to allow stabilisation and return true if successful */ bool MoistureSensor::turnOnProbe() { digitalWrite(PROBE, HIGH); delay(1000); return digitalRead(PROBE); } /* Power off the Probe and return true if successful */ bool MoistureSensor::turnOffProbe() { digitalWrite(PROBE, LOW); return !digitalRead(PROBE); } /** Reads the Value of the Water sensor on the PIN it's on and returns a voltage */ double MoistureSensor::readSensor() { if (!digitalRead(PROBE)){ turnOnProbe(); } //Do I need Setters??? sensorValue = analogRead(PROBE); sensorVoltage = map(sensorValue, 0, 1024, 0, 5); turnOffProbe(); return sensorVoltage; } /* Sets the the flag as to whether the sensor is reading wet, dry or moist. */ void MoistureSensor::moistureLevel(double sVoltage){ //TODO Fix this Logic...it wrong if(sVoltage >= getWetVoltage()) { setWettness(true, false, false); } else if(sVoltage <= getMoistVoltage() && sVoltage > getWetVoltage()) { setWettness(false, true, false); } else if(sVoltage <= getDryVoltage() and sVoltage > getMoistVoltage()) { setWettness(false, false, true); } else { //sensor failure as voltage below 0v (negative) or above 5v setWettness(false, false, false); } } //Decide what are public and private /** Getters */ int MoistureSensor::getProbe() { return PROBE; } int MoistureSensor::getSensor() { return SENSOR; } int MoistureSensor::getWetVoltage() { return wetVoltage; } int MoistureSensor::getDryVoltage() { return dryVoltage; } double MoistureSensor::getMoistVoltage() { return moistVoltage; } bool MoistureSensor::isDry() {return isDryState; } bool MoistureSensor::isMoist() {return isMoistState; } bool MoistureSensor::isWet() {return isWetState; } /** Setters */ void MoistureSensor::setWetVoltage(int wetVoltage) { wetVoltage = wetVoltage; } void MoistureSensor::setDryVoltage(int dryVoltage) { dryVoltage = dryVoltage; } void MoistureSensor::setMoistVoltage(double moistVoltage) { moistVoltage = moistVoltage; } void MoistureSensor::setWettness(bool isD, bool isM, bool isW) { isDryState = isD; isMoistState = isM; isWetState = isW; } <|endoftext|>
<commit_before>/* * Copyright 2010-2011 Fabric Technologies Inc. All rights reserved. */ #include "Extension.h" #include "Client.h" #include <Fabric/Core/Build.h> #include <Fabric/Core/MT/LogCollector.h> #include <Fabric/Core/RT/Manager.h> #include <Fabric/Core/CG/Manager.h> #include <Fabric/Core/DG/Context.h> #include <Fabric/Core/IO/Stream.h> #include <Fabric/Core/IO/Helpers.h> #include <Fabric/Core/IO/Manager.h> #include <Fabric/Core/IO/Dir.h> #include <Fabric/Core/OCL/OCL.h> #include <Fabric/Core/Plug/Manager.h> #include <Fabric/Base/JSON/Object.h> #include <Fabric/Base/JSON/String.h> #include <Fabric/Base/JSON/Value.h> #include <fstream> #include <stdlib.h> namespace Fabric { namespace V8Ext { class IOStream : public IO::Stream { public: static RC::Handle<IOStream> Create( std::string const &url, DataCallback dataCallback, EndCallback endCallback, FailureCallback failureCallback, RC::Handle<RC::Object> const &target, void *userData ) { return new IOStream( url, dataCallback, endCallback, failureCallback, target, userData ); } protected: IOStream( std::string const &url, DataCallback dataCallback, EndCallback endCallback, FailureCallback failureCallback, RC::Handle<RC::Object> const &target, void *userData ) : IO::Stream( dataCallback, endCallback, failureCallback, target, userData ) , m_url( url ) { size_t colonIndex = m_url.find( ':' ); if ( colonIndex == m_url.length() ) onFailure( m_url, "malformed URL" ); else { std::string method = m_url.substr( 0, colonIndex ); if ( method != "file" ) onFailure( m_url, "unsupported method " + _(method) ); else { std::string filename = m_url.substr( colonIndex+1, m_url.length() - colonIndex - 1 ); if ( filename.length() == 0 ) onFailure( m_url, "empty filename" ); else { FILE *fp = fopen( filename.c_str(), "rb" ); if ( fp == NULL ) onFailure( m_url, "unable to open file" ); fseek(fp, 0, SEEK_END); size_t totalSize = ftell(fp); fseek(fp, 0, SEEK_SET); static const size_t maxReadSize = 1<<16;//64K buffers uint8_t *data = static_cast<uint8_t *>( malloc(maxReadSize) ); size_t offset = 0; for (;;) { size_t readSize = fread( &data[0], 1, maxReadSize, fp ); if ( ferror( fp ) ) onFailure( m_url, "error while reading file" ); onData( m_url, "text/plain", totalSize, offset, readSize, data ); if ( readSize < maxReadSize ) break; offset += readSize; } free( data ); fclose( fp ); onEnd( m_url, "text/plain" ); } } } } private: std::string m_url; }; class IOManager : public IO::Manager { public: static RC::Handle<IOManager> Create() { return new IOManager; } virtual RC::Handle<IO::Stream> createStream( std::string const &url, IO::Stream::DataCallback dataCallback, IO::Stream::EndCallback endCallback, IO::Stream::FailureCallback failureCallback, RC::Handle<RC::Object> const &target, void *userData ) const { return IOStream::Create( url, dataCallback, endCallback, failureCallback, target, userData ); } virtual std::string queryUserFilePath( bool existingFile, std::string const &title, std::string const &defaultFilename, std::string const &extension ) const { if ( !IO::DirExists( "TMP" ) ) IO::CreateDir( "TMP" ); if(existingFile) return IO::JoinPath("TMP", "default.txt"); else return IO::JoinPath("TMP", defaultFilename); } virtual RC::ConstHandle<JSON::Value> jsonExec( std::string const &cmd, RC::ConstHandle<JSON::Value> const &arg ) { if ( cmd == "getUserTextFile" ) { //Special bypass to enable unit tests: support "unitTestFile://" directly, without validating that there is no '/../' RC::ConstHandle<JSON::Object> argJSONObject = arg->toObject(); RC::ConstHandle<JSON::Value> val = argJSONObject->maybeGet( "uiOptions" ); if( val ) { RC::ConstHandle<JSON::Object> uiOptionsJSONObject = val->toObject(); val = uiOptionsJSONObject->maybeGet( "title" ); if( val ) { std::string defaultFilename = val->toString()->value(); if(defaultFilename.find("unitTestFile://" == 0)) return JSON::String::Create( unitTestGetTextFileFromPath( defaultFilename.substr(15) ) ); } } } return IO::Manager::jsonExec( cmd, arg ); } std::string unitTestGetTextFileFromPath( std::string path ) const { std::ifstream file( path.c_str(), std::ios::in | std::ios::ate ); if( !file.is_open() ) throw Exception( "Unable to open file " + path ); size_t size = file.tellg(); file.seekg( 0, std::ios::beg ); std::string content( size, 0 ); file.read( (char*)content.data(), size ); return content; } protected: IOManager() { } }; Extension::Extension( std::string const &pluginsDir ) : v8::Extension( "Fabric", "native function createFabricClient();" ) { v8::HandleScope handleScope; m_pluginDirs.push_back( pluginsDir ); m_v8CreateFabricClientFunctionName = v8::Persistent<v8::String>::New( v8::String::New( "createFabricClient" ) ); v8::Handle<v8::FunctionTemplate> v8CreateFabricClientFunctionTemplate = v8::FunctionTemplate::New( &Extension::CreateFabricClient, v8::External::Wrap(this) ); m_v8CreateFabricClientFunctionTemplate = v8::Persistent<v8::FunctionTemplate>::New( v8CreateFabricClientFunctionTemplate ); v8::Handle<v8::ObjectTemplate> v8ClientObjectTemplate = v8::ObjectTemplate::New(); v8ClientObjectTemplate->SetInternalFieldCount( 1 ); v8ClientObjectTemplate->Set( "jsonExec", v8::FunctionTemplate::New( &Client::V8JSONExec ) ); v8ClientObjectTemplate->Set( "setJSONNotifyCallback", v8::FunctionTemplate::New( &Client::V8SetJSONNotifyCallback ) ); v8ClientObjectTemplate->Set( "wrapFabricClient", v8::FunctionTemplate::New( &Client::V8WrapFabricClient ) ); v8ClientObjectTemplate->Set( "dispose", v8::FunctionTemplate::New( &Client::V8Dispose ) ); m_v8ClientObjectTemplate = v8::Persistent<v8::ObjectTemplate>::New( v8ClientObjectTemplate ); } Extension::~Extension() { m_v8CreateFabricClientFunctionTemplate.Dispose(); m_v8CreateFabricClientFunctionName.Dispose(); m_v8ClientObjectTemplate.Dispose(); } v8::Handle<v8::FunctionTemplate> Extension::GetNativeFunction( v8::Handle<v8::String> name ) { if ( name->Equals( m_v8CreateFabricClientFunctionName ) ) return m_v8CreateFabricClientFunctionTemplate; else return v8::Extension::GetNativeFunction( name ); } v8::Handle<v8::Value> Extension::createFabricClient( v8::Arguments const &args ) const { v8::HandleScope handleScope; RC::Handle<IO::Manager> ioManager = IOManager::Create(); RC::Handle<DG::Context> dgContext = DG::Context::Create( ioManager, m_pluginDirs ); OCL::registerTypes( dgContext->getRTManager() ); Client *client = Client::Create( dgContext ).take(); Plug::Manager::Instance()->loadBuiltInPlugins( m_pluginDirs, dgContext->getCGManager() ); v8::Persistent<v8::Object> v8ClientObject = v8::Persistent<v8::Object>::New( m_v8ClientObjectTemplate->NewInstance() ); v8ClientObject->SetPointerInInternalField( 0, client ); v8ClientObject.MakeWeak( 0, &Extension::ClientWeakReferenceCallback ); return handleScope.Close( v8ClientObject ); } v8::Handle<v8::Value> Extension::CreateFabricClient( v8::Arguments const &args ) { return static_cast<Extension const *>( v8::External::Unwrap( args.Data() ) )->createFabricClient( args ); } void Extension::ClientWeakReferenceCallback( v8::Persistent<v8::Value> value, void * ) { v8::Handle<v8::Object> v8ClientObject = v8::Handle<v8::Object>::Cast( value ); Client *client = static_cast<Client *>( v8ClientObject->GetPointerFromInternalField( 0 ) ); client->release(); value.Dispose(); } }; }; <commit_msg>Fix for finding unitTestFile:// in unit test filenames<commit_after>/* * Copyright 2010-2011 Fabric Technologies Inc. All rights reserved. */ #include "Extension.h" #include "Client.h" #include <Fabric/Core/Build.h> #include <Fabric/Core/MT/LogCollector.h> #include <Fabric/Core/RT/Manager.h> #include <Fabric/Core/CG/Manager.h> #include <Fabric/Core/DG/Context.h> #include <Fabric/Core/IO/Stream.h> #include <Fabric/Core/IO/Helpers.h> #include <Fabric/Core/IO/Manager.h> #include <Fabric/Core/IO/Dir.h> #include <Fabric/Core/OCL/OCL.h> #include <Fabric/Core/Plug/Manager.h> #include <Fabric/Base/JSON/Object.h> #include <Fabric/Base/JSON/String.h> #include <Fabric/Base/JSON/Value.h> #include <fstream> #include <stdlib.h> namespace Fabric { namespace V8Ext { class IOStream : public IO::Stream { public: static RC::Handle<IOStream> Create( std::string const &url, DataCallback dataCallback, EndCallback endCallback, FailureCallback failureCallback, RC::Handle<RC::Object> const &target, void *userData ) { return new IOStream( url, dataCallback, endCallback, failureCallback, target, userData ); } protected: IOStream( std::string const &url, DataCallback dataCallback, EndCallback endCallback, FailureCallback failureCallback, RC::Handle<RC::Object> const &target, void *userData ) : IO::Stream( dataCallback, endCallback, failureCallback, target, userData ) , m_url( url ) { size_t colonIndex = m_url.find( ':' ); if ( colonIndex == m_url.length() ) onFailure( m_url, "malformed URL" ); else { std::string method = m_url.substr( 0, colonIndex ); if ( method != "file" ) onFailure( m_url, "unsupported method " + _(method) ); else { std::string filename = m_url.substr( colonIndex+1, m_url.length() - colonIndex - 1 ); if ( filename.length() == 0 ) onFailure( m_url, "empty filename" ); else { FILE *fp = fopen( filename.c_str(), "rb" ); if ( fp == NULL ) onFailure( m_url, "unable to open file" ); fseek(fp, 0, SEEK_END); size_t totalSize = ftell(fp); fseek(fp, 0, SEEK_SET); static const size_t maxReadSize = 1<<16;//64K buffers uint8_t *data = static_cast<uint8_t *>( malloc(maxReadSize) ); size_t offset = 0; for (;;) { size_t readSize = fread( &data[0], 1, maxReadSize, fp ); if ( ferror( fp ) ) onFailure( m_url, "error while reading file" ); onData( m_url, "text/plain", totalSize, offset, readSize, data ); if ( readSize < maxReadSize ) break; offset += readSize; } free( data ); fclose( fp ); onEnd( m_url, "text/plain" ); } } } } private: std::string m_url; }; class IOManager : public IO::Manager { public: static RC::Handle<IOManager> Create() { return new IOManager; } virtual RC::Handle<IO::Stream> createStream( std::string const &url, IO::Stream::DataCallback dataCallback, IO::Stream::EndCallback endCallback, IO::Stream::FailureCallback failureCallback, RC::Handle<RC::Object> const &target, void *userData ) const { return IOStream::Create( url, dataCallback, endCallback, failureCallback, target, userData ); } virtual std::string queryUserFilePath( bool existingFile, std::string const &title, std::string const &defaultFilename, std::string const &extension ) const { if ( !IO::DirExists( "TMP" ) ) IO::CreateDir( "TMP" ); if(existingFile) return IO::JoinPath("TMP", "default.txt"); else return IO::JoinPath("TMP", defaultFilename); } virtual RC::ConstHandle<JSON::Value> jsonExec( std::string const &cmd, RC::ConstHandle<JSON::Value> const &arg ) { if ( cmd == "getUserTextFile" ) { //Special bypass to enable unit tests: support "unitTestFile://" directly, without validating that there is no '/../' RC::ConstHandle<JSON::Object> argJSONObject = arg->toObject(); RC::ConstHandle<JSON::Value> val = argJSONObject->maybeGet( "uiOptions" ); if( val ) { RC::ConstHandle<JSON::Object> uiOptionsJSONObject = val->toObject(); val = uiOptionsJSONObject->maybeGet( "title" ); if( val ) { std::string defaultFilename = val->toString()->value(); if ( defaultFilename.length() >= 15 && defaultFilename.substr(0, 15) == "unitTestFile://" ) return JSON::String::Create( unitTestGetTextFileFromPath( defaultFilename.substr(15) ) ); } } } return IO::Manager::jsonExec( cmd, arg ); } std::string unitTestGetTextFileFromPath( std::string path ) const { std::ifstream file( path.c_str(), std::ios::in | std::ios::ate ); if( !file.is_open() ) throw Exception( "Unable to open file " + path ); size_t size = file.tellg(); file.seekg( 0, std::ios::beg ); std::string content( size, 0 ); file.read( (char*)content.data(), size ); return content; } protected: IOManager() { } }; Extension::Extension( std::string const &pluginsDir ) : v8::Extension( "Fabric", "native function createFabricClient();" ) { v8::HandleScope handleScope; m_pluginDirs.push_back( pluginsDir ); m_v8CreateFabricClientFunctionName = v8::Persistent<v8::String>::New( v8::String::New( "createFabricClient" ) ); v8::Handle<v8::FunctionTemplate> v8CreateFabricClientFunctionTemplate = v8::FunctionTemplate::New( &Extension::CreateFabricClient, v8::External::Wrap(this) ); m_v8CreateFabricClientFunctionTemplate = v8::Persistent<v8::FunctionTemplate>::New( v8CreateFabricClientFunctionTemplate ); v8::Handle<v8::ObjectTemplate> v8ClientObjectTemplate = v8::ObjectTemplate::New(); v8ClientObjectTemplate->SetInternalFieldCount( 1 ); v8ClientObjectTemplate->Set( "jsonExec", v8::FunctionTemplate::New( &Client::V8JSONExec ) ); v8ClientObjectTemplate->Set( "setJSONNotifyCallback", v8::FunctionTemplate::New( &Client::V8SetJSONNotifyCallback ) ); v8ClientObjectTemplate->Set( "wrapFabricClient", v8::FunctionTemplate::New( &Client::V8WrapFabricClient ) ); v8ClientObjectTemplate->Set( "dispose", v8::FunctionTemplate::New( &Client::V8Dispose ) ); m_v8ClientObjectTemplate = v8::Persistent<v8::ObjectTemplate>::New( v8ClientObjectTemplate ); } Extension::~Extension() { m_v8CreateFabricClientFunctionTemplate.Dispose(); m_v8CreateFabricClientFunctionName.Dispose(); m_v8ClientObjectTemplate.Dispose(); } v8::Handle<v8::FunctionTemplate> Extension::GetNativeFunction( v8::Handle<v8::String> name ) { if ( name->Equals( m_v8CreateFabricClientFunctionName ) ) return m_v8CreateFabricClientFunctionTemplate; else return v8::Extension::GetNativeFunction( name ); } v8::Handle<v8::Value> Extension::createFabricClient( v8::Arguments const &args ) const { v8::HandleScope handleScope; RC::Handle<IO::Manager> ioManager = IOManager::Create(); RC::Handle<DG::Context> dgContext = DG::Context::Create( ioManager, m_pluginDirs ); OCL::registerTypes( dgContext->getRTManager() ); Client *client = Client::Create( dgContext ).take(); Plug::Manager::Instance()->loadBuiltInPlugins( m_pluginDirs, dgContext->getCGManager() ); v8::Persistent<v8::Object> v8ClientObject = v8::Persistent<v8::Object>::New( m_v8ClientObjectTemplate->NewInstance() ); v8ClientObject->SetPointerInInternalField( 0, client ); v8ClientObject.MakeWeak( 0, &Extension::ClientWeakReferenceCallback ); return handleScope.Close( v8ClientObject ); } v8::Handle<v8::Value> Extension::CreateFabricClient( v8::Arguments const &args ) { return static_cast<Extension const *>( v8::External::Unwrap( args.Data() ) )->createFabricClient( args ); } void Extension::ClientWeakReferenceCallback( v8::Persistent<v8::Value> value, void * ) { v8::Handle<v8::Object> v8ClientObject = v8::Handle<v8::Object>::Cast( value ); Client *client = static_cast<Client *>( v8ClientObject->GetPointerFromInternalField( 0 ) ); client->release(); value.Dispose(); } }; }; <|endoftext|>
<commit_before>#ifndef VG_HANDLE_HPP_INCLUDED #define VG_HANDLE_HPP_INCLUDED /** \file * Defines a handle type that can refer to oriented nodes of, and be used to * traverse, any backing graph implementation. Not just an ID or a pos_t because * XG (and maybe other implementations) provide more efficient local traversal * mechanisms if you can skip ID lookups. */ #include "types.hpp" #include <functional> #include <cstdint> namespace vg { using namespace std; /// A handle is 8 (assuming id_t is still int64_t) opaque bytes. /// A handle refers to an oriented node. /// Two handles are equal iff they refer to the same orientation of the same node in the same graph. /// Handles have no ordering, but can be hashed. struct handle_t { char data[sizeof(id_t)]; }; // XG is going to store node index in its g-vector and node orientation in there // VG is going to store ID and orientation // Other implementations can store other things (or maybe int indexes into tables) /// View a handle as an integer inline int64_t& as_integer(handle_t& handle) { return reinterpret_cast<int64_t&>(handle); } /// View a const handle as a const integer inline const int64_t& as_integer(const handle_t& handle) { return reinterpret_cast<const int64_t&>(handle); } /// View an integer as a handle inline handle_t& as_handle(int64_t& value) { return reinterpret_cast<handle_t&>(value); } /// View a const integer as a const handle inline const handle_t& as_handle(const int64_t& value) { return reinterpret_cast<const handle_t&>(value); } /// Define equality on handles inline bool operator==(const handle_t& a, const handle_t& b) { return as_integer(a) == as_integer(b); } /// Define inequality on handles inline bool operator!=(const handle_t& a, const handle_t& b) { return as_integer(a) != as_integer(b); } } // This needs to be outside the vg namespace namespace std { /** * Define hashes for handles. */ template<> struct hash<vg::handle_t> { public: inline size_t operator()(const vg::handle_t& handle) const { return std::hash<int64_t>()(vg::as_integer(handle)); } }; } namespace vg { using namespace std; /** * This is the interface that a graph that uses handles needs to support. * It is also the interface that users should code against. */ class HandleGraph { public: /// Look up the handle for the node with the given ID in the given orientation virtual handle_t get_handle(const id_t& node_id, bool is_reverse = false) const = 0; /// Get the ID from a handle virtual id_t get_id(const handle_t& handle) const = 0; /// Get the orientation of a handle virtual bool get_is_reverse(const handle_t& handle) const = 0; /// Invert the orientation of a handle (potentially without getting its ID) virtual handle_t flip(const handle_t& handle) const = 0; /// Get the length of a node virtual size_t get_length(const handle_t& handle) const = 0; /// Get the sequence of a node, presented in the handle's local forward /// orientation. virtual string get_sequence(const handle_t& handle) const = 0; /// Loop over all the handles to next/previous (right/left) nodes. Passes /// them to a callback which returns false to stop iterating and true to /// continue. virtual void follow_edges(const handle_t& handle, bool go_left, const function<bool(const handle_t&)>& iteratee) const = 0; /// Loop over all the nodes in the graph in their local forward /// orientations, in their internal stored order. Stop if the iteratee returns false. virtual void for_each_handle(const function<bool(const handle_t&)>& iteratee) const = 0; /// Loop over all the handles to next/previous (right/left) nodes. Works /// with a callback that just takes all the handles and returns void. /// MUST be pulled into implementing classes with `using` in order to work! template <typename T> auto follow_edges(const handle_t& handle, bool go_left, T&& iteratee) const -> typename std::enable_if<std::is_void<decltype(iteratee(get_handle(0, false)))>::value>::type { // Implementation only for void-returning iteratees // We ought to just overload on the std::function but that's not allowed until C++14. // See <https://stackoverflow.com/q/13811180> // We also can't use result_of<T(handle_t)>::type to sniff the return // type out because that ::type would not exist (since that's what you // get for a void apparently?) and we couldn't check if it's bool or // void. // So we do this nonsense thing with a trailing return type (to get the // actual arg into scope) and a decltype (which is allowed to resolve to // void) and is_void (which is allowed to take void) and a fake // get_handle call (which is the shortest handle_t-typed expression I // could think of). // Make a wrapper that puts a bool return type on. function<bool(const handle_t&)> lambda = [&](const handle_t& found) { iteratee(found); return true; }; // Use that follow_edges(handle, go_left, lambda); // During development I managed to get earlier versions of this template to build infinitely recursive functions. static_assert(!std::is_void<decltype(lambda(get_handle(0, false)))>::value, "can't take our own lambda"); } /// Loop over all the nodes in the graph in their local forward /// orientations, in their internal stored order. Works with void-returning iteratees. /// MUST be pulled into implementing classes with `using` in order to work! template <typename T> auto for_each_handle(T&& iteratee) const -> typename std::enable_if<std::is_void<decltype(iteratee(get_handle(0, false)))>::value>::type { // Make a wrapper that puts a bool return type on. function<bool(const handle_t&)> lambda = [&](const handle_t& found) { iteratee(found); return true; }; // Use that for_each_handle(lambda); } /// Get the locally forward version of a handle inline handle_t forward(const handle_t& handle) const { return this->get_is_reverse(handle) ? this->flip(handle) : handle; } // A pair of handles can be used as an edge. When so used, the handles have a // cannonical order and orientation. inline pair<handle_t, handle_t> edge_handle(const handle_t& left, const handle_t& right) const { // The degeneracy is between any pair and a pair of the same nodes but reversed in order and orientation. // We compare those two pairs and construct the smaller one. auto flipped_right = this->flip(right); if (as_integer(left) > as_integer(flipped_right)) { // The other orientation would be smaller. return make_pair(flipped_right, this->flip(left)); } else if(as_integer(left) == as_integer(flipped_right)) { // Our left and the flipped pair's left would be equal. auto flipped_left = this->flip(left); if (as_integer(right) > as_integer(flipped_left)) { // And our right is too big, so flip. return make_pair(flipped_right, flipped_left); } else { // No difference or we're smaller. return make_pair(left, right); } } else { // We're smaller return make_pair(left, right); } } }; /** * This is the interface for a handle graph that supports modification. If the * graph keeps an index of paths, all operations must also modify the stored * paths. The paths are never allowed to be inconsistent with the graph. */ class MutableHandleGraph : public HandleGraph { public: /// Create a new node with the given sequence and return the handle. virtual handle_t create_handle(const string& sequence) = 0; /// Remove the node belonging to the given handle and all of its edges. virtual void destroy_handle(const handle_t& handle) = 0; /// Create an edge connecting the given handles in the given order and orientations. /// Ignores existing edges. virtual void create_edge(const handle_t& left, const handle_t& right) = 0; /// Remove the edge connecting the given handles in the given order and orientations. /// Ignores nonexistent edges. virtual void destroy_edge(const handle_t& left, const handle_t& right) = 0; /// Swap the nodes corresponding to the given handles, in the ordering used /// by for_each_handle when looping over the graph. Other handles to the /// nodes being swapped must not be invalidated. virtual void swap_handles(const handle_t& a, const handle_t& b) = 0; /// Alter the node that the given handle corresponds to so the orientation /// indicated by the handle becomes the node's local forward orientation. /// Rewrites all edges pointing to the node and the node's sequence to /// reflect this. Invalidates all handles to the node (including the one /// passed). Returns a new, valid handle to the node in its new forward /// orientation. Note that it is possible for the node's ID to change. virtual handle_t apply_orientation(const handle_t& handle) = 0; /// Split a handle's underlying node at the given offsets in the handle's /// orientation. Returns all of the handles to the parts. Other handles to /// the node being split may be invalidated. The split pieces stay in the /// same local forward orientation as the original node, but the returned /// handles come in the order and orientation appropriate for the handle /// passed in. virtual vector<handle_t> divide_handle(const handle_t& handle, const vector<size_t>& offsets) = 0; /// Specialization of divide_handle for a single division point inline pair<handle_t, handle_t> divide_handle(const handle_t& handle, size_t offset) { auto parts = divide_handle(handle, vector<size_t>{offset}); return make_pair(parts.front(), parts.back()); } }; } #endif <commit_msg>Make comments about path updates reflect reality<commit_after>#ifndef VG_HANDLE_HPP_INCLUDED #define VG_HANDLE_HPP_INCLUDED /** \file * Defines a handle type that can refer to oriented nodes of, and be used to * traverse, any backing graph implementation. Not just an ID or a pos_t because * XG (and maybe other implementations) provide more efficient local traversal * mechanisms if you can skip ID lookups. */ #include "types.hpp" #include <functional> #include <cstdint> namespace vg { using namespace std; /// A handle is 8 (assuming id_t is still int64_t) opaque bytes. /// A handle refers to an oriented node. /// Two handles are equal iff they refer to the same orientation of the same node in the same graph. /// Handles have no ordering, but can be hashed. struct handle_t { char data[sizeof(id_t)]; }; // XG is going to store node index in its g-vector and node orientation in there // VG is going to store ID and orientation // Other implementations can store other things (or maybe int indexes into tables) /// View a handle as an integer inline int64_t& as_integer(handle_t& handle) { return reinterpret_cast<int64_t&>(handle); } /// View a const handle as a const integer inline const int64_t& as_integer(const handle_t& handle) { return reinterpret_cast<const int64_t&>(handle); } /// View an integer as a handle inline handle_t& as_handle(int64_t& value) { return reinterpret_cast<handle_t&>(value); } /// View a const integer as a const handle inline const handle_t& as_handle(const int64_t& value) { return reinterpret_cast<const handle_t&>(value); } /// Define equality on handles inline bool operator==(const handle_t& a, const handle_t& b) { return as_integer(a) == as_integer(b); } /// Define inequality on handles inline bool operator!=(const handle_t& a, const handle_t& b) { return as_integer(a) != as_integer(b); } } // This needs to be outside the vg namespace namespace std { /** * Define hashes for handles. */ template<> struct hash<vg::handle_t> { public: inline size_t operator()(const vg::handle_t& handle) const { return std::hash<int64_t>()(vg::as_integer(handle)); } }; } namespace vg { using namespace std; /** * This is the interface that a graph that uses handles needs to support. * It is also the interface that users should code against. */ class HandleGraph { public: /// Look up the handle for the node with the given ID in the given orientation virtual handle_t get_handle(const id_t& node_id, bool is_reverse = false) const = 0; /// Get the ID from a handle virtual id_t get_id(const handle_t& handle) const = 0; /// Get the orientation of a handle virtual bool get_is_reverse(const handle_t& handle) const = 0; /// Invert the orientation of a handle (potentially without getting its ID) virtual handle_t flip(const handle_t& handle) const = 0; /// Get the length of a node virtual size_t get_length(const handle_t& handle) const = 0; /// Get the sequence of a node, presented in the handle's local forward /// orientation. virtual string get_sequence(const handle_t& handle) const = 0; /// Loop over all the handles to next/previous (right/left) nodes. Passes /// them to a callback which returns false to stop iterating and true to /// continue. virtual void follow_edges(const handle_t& handle, bool go_left, const function<bool(const handle_t&)>& iteratee) const = 0; /// Loop over all the nodes in the graph in their local forward /// orientations, in their internal stored order. Stop if the iteratee returns false. virtual void for_each_handle(const function<bool(const handle_t&)>& iteratee) const = 0; /// Loop over all the handles to next/previous (right/left) nodes. Works /// with a callback that just takes all the handles and returns void. /// MUST be pulled into implementing classes with `using` in order to work! template <typename T> auto follow_edges(const handle_t& handle, bool go_left, T&& iteratee) const -> typename std::enable_if<std::is_void<decltype(iteratee(get_handle(0, false)))>::value>::type { // Implementation only for void-returning iteratees // We ought to just overload on the std::function but that's not allowed until C++14. // See <https://stackoverflow.com/q/13811180> // We also can't use result_of<T(handle_t)>::type to sniff the return // type out because that ::type would not exist (since that's what you // get for a void apparently?) and we couldn't check if it's bool or // void. // So we do this nonsense thing with a trailing return type (to get the // actual arg into scope) and a decltype (which is allowed to resolve to // void) and is_void (which is allowed to take void) and a fake // get_handle call (which is the shortest handle_t-typed expression I // could think of). // Make a wrapper that puts a bool return type on. function<bool(const handle_t&)> lambda = [&](const handle_t& found) { iteratee(found); return true; }; // Use that follow_edges(handle, go_left, lambda); // During development I managed to get earlier versions of this template to build infinitely recursive functions. static_assert(!std::is_void<decltype(lambda(get_handle(0, false)))>::value, "can't take our own lambda"); } /// Loop over all the nodes in the graph in their local forward /// orientations, in their internal stored order. Works with void-returning iteratees. /// MUST be pulled into implementing classes with `using` in order to work! template <typename T> auto for_each_handle(T&& iteratee) const -> typename std::enable_if<std::is_void<decltype(iteratee(get_handle(0, false)))>::value>::type { // Make a wrapper that puts a bool return type on. function<bool(const handle_t&)> lambda = [&](const handle_t& found) { iteratee(found); return true; }; // Use that for_each_handle(lambda); } /// Get the locally forward version of a handle inline handle_t forward(const handle_t& handle) const { return this->get_is_reverse(handle) ? this->flip(handle) : handle; } // A pair of handles can be used as an edge. When so used, the handles have a // cannonical order and orientation. inline pair<handle_t, handle_t> edge_handle(const handle_t& left, const handle_t& right) const { // The degeneracy is between any pair and a pair of the same nodes but reversed in order and orientation. // We compare those two pairs and construct the smaller one. auto flipped_right = this->flip(right); if (as_integer(left) > as_integer(flipped_right)) { // The other orientation would be smaller. return make_pair(flipped_right, this->flip(left)); } else if(as_integer(left) == as_integer(flipped_right)) { // Our left and the flipped pair's left would be equal. auto flipped_left = this->flip(left); if (as_integer(right) > as_integer(flipped_left)) { // And our right is too big, so flip. return make_pair(flipped_right, flipped_left); } else { // No difference or we're smaller. return make_pair(left, right); } } else { // We're smaller return make_pair(left, right); } } }; /** * This is the interface for a handle graph that supports modification. */ class MutableHandleGraph : public HandleGraph { public: /// Create a new node with the given sequence and return the handle. virtual handle_t create_handle(const string& sequence) = 0; /// Remove the node belonging to the given handle and all of its edges. /// Does not update any stored paths. virtual void destroy_handle(const handle_t& handle) = 0; /// Create an edge connecting the given handles in the given order and orientations. /// Ignores existing edges. virtual void create_edge(const handle_t& left, const handle_t& right) = 0; /// Remove the edge connecting the given handles in the given order and orientations. /// Ignores nonexistent edges. /// Does not update any stored paths. virtual void destroy_edge(const handle_t& left, const handle_t& right) = 0; /// Swap the nodes corresponding to the given handles, in the ordering used /// by for_each_handle when looping over the graph. Other handles to the /// nodes being swapped must not be invalidated. virtual void swap_handles(const handle_t& a, const handle_t& b) = 0; /// Alter the node that the given handle corresponds to so the orientation /// indicated by the handle becomes the node's local forward orientation. /// Rewrites all edges pointing to the node and the node's sequence to /// reflect this. Invalidates all handles to the node (including the one /// passed). Returns a new, valid handle to the node in its new forward /// orientation. Note that it is possible for the node's ID to change. /// Does not update any stored paths. virtual handle_t apply_orientation(const handle_t& handle) = 0; /// Split a handle's underlying node at the given offsets in the handle's /// orientation. Returns all of the handles to the parts. Other handles to /// the node being split may be invalidated. The split pieces stay in the /// same local forward orientation as the original node, but the returned /// handles come in the order and orientation appropriate for the handle /// passed in. /// Updates stored paths. virtual vector<handle_t> divide_handle(const handle_t& handle, const vector<size_t>& offsets) = 0; /// Specialization of divide_handle for a single division point inline pair<handle_t, handle_t> divide_handle(const handle_t& handle, size_t offset) { auto parts = divide_handle(handle, vector<size_t>{offset}); return make_pair(parts.front(), parts.back()); } }; } #endif <|endoftext|>
<commit_before>// Copyright 2008 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "v8.h" #include "hashmap.h" namespace v8 { namespace internal { Allocator HashMap::DefaultAllocator; HashMap::HashMap() { allocator_ = NULL; match_ = NULL; } HashMap::HashMap(MatchFun match, Allocator* allocator, uint32_t initial_capacity) { allocator_ = allocator; match_ = match; Initialize(initial_capacity); } HashMap::~HashMap() { if (allocator_) { allocator_->Delete(map_); } } HashMap::Entry* HashMap::Lookup(void* key, uint32_t hash, bool insert) { // Find a matching entry. Entry* p = Probe(key, hash); if (p->key != NULL) { return p; } // No entry found; insert one if necessary. if (insert) { p->key = key; p->value = NULL; p->hash = hash; occupancy_++; // Grow the map if we reached >= 80% occupancy. if (occupancy_ + occupancy_/4 >= capacity_) { Resize(); p = Probe(key, hash); } return p; } // No entry found and none inserted. return NULL; } void HashMap::Remove(void* key, uint32_t hash) { // Lookup the entry for the key to remove. Entry *p = Probe(key, hash); if (p->key == NULL) { // Key not found nothing to remove. return; } // To remove the entry we need to ensure that it does not create an empty // entry that will cause search for an entry to stop to soon. If all the // entries between the entry to remove and the next empty slot have their // initial position inside this interval clearing the entry to remove will not // break the search. If while searching for the next empty entry an entry is // encountered which does not have its initial position between the entry to // remove and the position looked at this entry can be moved to the place of // the entry to remove without breaking the search for it and the new entry to // remove will be its previous position. // Algorithm from http://en.wikipedia.org/wiki/Open_addressing. // This guarantees loop termination as there is at least one empty entry so // eventually the removed entyr will have an empty entry after it. ASSERT(occupancy_ < capacity_); // p is the candidate entry to clear. q is used to scan forwards. Entry* q = p; // Start at the entry to remove. while (true) { // Move q to the next entry. q = q + 1; if (q == map_end()) { q = map_; } // All entries between p and q have their initial position between p and q // and the entry p can be cleared without breaking the search for these // entries. if (q->key == NULL) { break; } // Find the initial position for the entry at position q. Entry* r = map_ + (q->hash & (capacity_ - 1)); // If the entry at position q has its initial position outside the range // between p and q it can be moved forward to position p and will still be // found. There is now a new candidate entry for clearing. if (q > p && (r <= p || r > q) || q < p && (r <= p && r > q)) { *p = *q; p = q; } } // Clear the entry which is allowed to en emptied. p->key = NULL; occupancy_--; } void HashMap::Clear() { // Mark all entries as empty. const Entry* end = map_end(); for (Entry* p = map_; p < end; p++) { p->key = NULL; } occupancy_ = 0; } HashMap::Entry* HashMap::Start() const { return Next(map_ - 1); } HashMap::Entry* HashMap::Next(Entry* p) const { const Entry* end = map_end(); ASSERT(map_ - 1 <= p && p < end); for (p++; p < end; p++) { if (p->key != NULL) { return p; } } return NULL; } HashMap::Entry* HashMap::Probe(void* key, uint32_t hash) { ASSERT(key != NULL); ASSERT(IsPowerOf2(capacity_)); Entry* p = map_ + (hash & (capacity_ - 1)); const Entry* end = map_end(); ASSERT(map_ <= p && p < end); ASSERT(occupancy_ < capacity_); // Guarantees loop termination. while (p->key != NULL && (hash != p->hash || !match_(key, p->key))) { p++; if (p >= end) { p = map_; } } return p; } void HashMap::Initialize(uint32_t capacity) { ASSERT(IsPowerOf2(capacity)); map_ = reinterpret_cast<Entry*>(allocator_->New(capacity * sizeof(Entry))); if (map_ == NULL) V8::FatalProcessOutOfMemory("HashMap::Initialize"); capacity_ = capacity; Clear(); } void HashMap::Resize() { Entry* map = map_; uint32_t n = occupancy_; // Allocate larger map. Initialize(capacity_ * 2); // Rehash all current entries. for (Entry* p = map; n > 0; p++) { if (p->key != NULL) { Lookup(p->key, p->hash, true)->value = p->value; n--; } } // Delete old map. allocator_->Delete(map); } } } // namespace v8::internal <commit_msg>Fix compilation on newer gcc by adding () instead of using prescendence. Review URL: http://codereview.chromium.org/113447<commit_after>// Copyright 2008 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "v8.h" #include "hashmap.h" namespace v8 { namespace internal { Allocator HashMap::DefaultAllocator; HashMap::HashMap() { allocator_ = NULL; match_ = NULL; } HashMap::HashMap(MatchFun match, Allocator* allocator, uint32_t initial_capacity) { allocator_ = allocator; match_ = match; Initialize(initial_capacity); } HashMap::~HashMap() { if (allocator_) { allocator_->Delete(map_); } } HashMap::Entry* HashMap::Lookup(void* key, uint32_t hash, bool insert) { // Find a matching entry. Entry* p = Probe(key, hash); if (p->key != NULL) { return p; } // No entry found; insert one if necessary. if (insert) { p->key = key; p->value = NULL; p->hash = hash; occupancy_++; // Grow the map if we reached >= 80% occupancy. if (occupancy_ + occupancy_/4 >= capacity_) { Resize(); p = Probe(key, hash); } return p; } // No entry found and none inserted. return NULL; } void HashMap::Remove(void* key, uint32_t hash) { // Lookup the entry for the key to remove. Entry *p = Probe(key, hash); if (p->key == NULL) { // Key not found nothing to remove. return; } // To remove the entry we need to ensure that it does not create an empty // entry that will cause search for an entry to stop to soon. If all the // entries between the entry to remove and the next empty slot have their // initial position inside this interval clearing the entry to remove will not // break the search. If while searching for the next empty entry an entry is // encountered which does not have its initial position between the entry to // remove and the position looked at this entry can be moved to the place of // the entry to remove without breaking the search for it and the new entry to // remove will be its previous position. // Algorithm from http://en.wikipedia.org/wiki/Open_addressing. // This guarantees loop termination as there is at least one empty entry so // eventually the removed entyr will have an empty entry after it. ASSERT(occupancy_ < capacity_); // p is the candidate entry to clear. q is used to scan forwards. Entry* q = p; // Start at the entry to remove. while (true) { // Move q to the next entry. q = q + 1; if (q == map_end()) { q = map_; } // All entries between p and q have their initial position between p and q // and the entry p can be cleared without breaking the search for these // entries. if (q->key == NULL) { break; } // Find the initial position for the entry at position q. Entry* r = map_ + (q->hash & (capacity_ - 1)); // If the entry at position q has its initial position outside the range // between p and q it can be moved forward to position p and will still be // found. There is now a new candidate entry for clearing. if ((q > p && (r <= p || r > q)) || (q < p && (r <= p && r > q))) { *p = *q; p = q; } } // Clear the entry which is allowed to en emptied. p->key = NULL; occupancy_--; } void HashMap::Clear() { // Mark all entries as empty. const Entry* end = map_end(); for (Entry* p = map_; p < end; p++) { p->key = NULL; } occupancy_ = 0; } HashMap::Entry* HashMap::Start() const { return Next(map_ - 1); } HashMap::Entry* HashMap::Next(Entry* p) const { const Entry* end = map_end(); ASSERT(map_ - 1 <= p && p < end); for (p++; p < end; p++) { if (p->key != NULL) { return p; } } return NULL; } HashMap::Entry* HashMap::Probe(void* key, uint32_t hash) { ASSERT(key != NULL); ASSERT(IsPowerOf2(capacity_)); Entry* p = map_ + (hash & (capacity_ - 1)); const Entry* end = map_end(); ASSERT(map_ <= p && p < end); ASSERT(occupancy_ < capacity_); // Guarantees loop termination. while (p->key != NULL && (hash != p->hash || !match_(key, p->key))) { p++; if (p >= end) { p = map_; } } return p; } void HashMap::Initialize(uint32_t capacity) { ASSERT(IsPowerOf2(capacity)); map_ = reinterpret_cast<Entry*>(allocator_->New(capacity * sizeof(Entry))); if (map_ == NULL) V8::FatalProcessOutOfMemory("HashMap::Initialize"); capacity_ = capacity; Clear(); } void HashMap::Resize() { Entry* map = map_; uint32_t n = occupancy_; // Allocate larger map. Initialize(capacity_ * 2); // Rehash all current entries. for (Entry* p = map; n > 0; p++) { if (p->key != NULL) { Lookup(p->key, p->hash, true)->value = p->value; n--; } } // Delete old map. allocator_->Delete(map); } } } // namespace v8::internal <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file contains definitions for CppVariant. #include <limits> #include "config.h" #include "webkit/glue/cpp_variant.h" #include "base/logging.h" #include "base/string_util.h" #include "npruntime_priv.h" // for NPN_InitializeVariantWithStringCopy #if USE(JSC) #define _NPN_InitializeVariantWithStringCopy NPN_InitializeVariantWithStringCopy #endif CppVariant::CppVariant() { type = NPVariantType_Null; } // Note that Set() performs a deep copy, which is necessary to safely // call FreeData() on the value in the destructor. CppVariant::CppVariant(const CppVariant& original) { type = NPVariantType_Null; Set(original); } // See comment for copy constructor, above. CppVariant& CppVariant::operator=(const CppVariant& original) { if (&original != this) Set(original); return *this; } CppVariant::~CppVariant() { FreeData(); } void CppVariant::FreeData() { NPN_ReleaseVariantValue(this); } bool CppVariant::isEqual(const CppVariant& other) const { if (type != other.type) return false; switch (type) { case NPVariantType_Bool: { return (value.boolValue == other.value.boolValue); } case NPVariantType_Int32: { return (value.intValue == other.value.intValue); } case NPVariantType_Double: { return (value.doubleValue == other.value.doubleValue); } case NPVariantType_String: { const NPString *this_value = &value.stringValue; const NPString *other_value = &other.value.stringValue; uint32_t len = this_value->UTF8Length; return (len == other_value->UTF8Length && !strncmp(this_value->UTF8Characters, other_value->UTF8Characters, len)); } case NPVariantType_Null: case NPVariantType_Void: { return true; } case NPVariantType_Object: { NPObject *this_value = value.objectValue; NPObject *other_value = other.value.objectValue; return (this_value->_class == other_value->_class && this_value->referenceCount == other_value->referenceCount); } } return false; } void CppVariant::CopyToNPVariant(NPVariant* result) const { result->type = type; switch (type) { case NPVariantType_Bool: result->value.boolValue = value.boolValue; break; case NPVariantType_Int32: result->value.intValue = value.intValue; break; case NPVariantType_Double: result->value.doubleValue = value.doubleValue; break; case NPVariantType_String: _NPN_InitializeVariantWithStringCopy(result, &value.stringValue); break; case NPVariantType_Null: case NPVariantType_Void: // Nothing to set. break; case NPVariantType_Object: result->type = NPVariantType_Object; result->value.objectValue = NPN_RetainObject(value.objectValue); break; } } void CppVariant::Set(const NPVariant& new_value) { FreeData(); switch (new_value.type) { case NPVariantType_Bool: Set(new_value.value.boolValue); break; case NPVariantType_Int32: Set(new_value.value.intValue); break; case NPVariantType_Double: Set(new_value.value.doubleValue); break; case NPVariantType_String: Set(new_value.value.stringValue); break; case NPVariantType_Null: case NPVariantType_Void: type = new_value.type; break; case NPVariantType_Object: Set(new_value.value.objectValue); break; } } void CppVariant::SetNull() { FreeData(); type = NPVariantType_Null; } void CppVariant::Set(bool new_value) { FreeData(); type = NPVariantType_Bool; value.boolValue = new_value; } void CppVariant::Set(int32_t new_value) { FreeData(); type = NPVariantType_Int32; value.intValue = new_value; } void CppVariant::Set(double new_value) { FreeData(); type = NPVariantType_Double; value.doubleValue = new_value; } // The new_value must be a null-terminated string. void CppVariant::Set(const char* new_value) { FreeData(); type = NPVariantType_String; NPString new_string = {new_value, static_cast<uint32_t>(strlen(new_value))}; _NPN_InitializeVariantWithStringCopy(this, &new_string); } void CppVariant::Set(const std::string& new_value) { FreeData(); type = NPVariantType_String; NPString new_string = {new_value.data(), static_cast<uint32_t>(new_value.size())}; _NPN_InitializeVariantWithStringCopy(this, &new_string); } void CppVariant::Set(const NPString& new_value) { FreeData(); type = NPVariantType_String; _NPN_InitializeVariantWithStringCopy(this, &new_value); } void CppVariant::Set(NPObject* new_value) { FreeData(); type = NPVariantType_Object; value.objectValue = NPN_RetainObject(new_value); } std::string CppVariant::ToString() const { DCHECK(isString()); return std::string(value.stringValue.UTF8Characters, value.stringValue.UTF8Length); } int32_t CppVariant::ToInt32() const { if (isInt32()) { return value.intValue; } else if (isDouble()) { return static_cast<int32_t>(value.doubleValue); } else { NOTREACHED(); return 0; } } double CppVariant::ToDouble() const { if (isInt32()) { return static_cast<double>(value.intValue); } else if (isDouble()) { return value.doubleValue; } else { NOTREACHED(); return 0.0; } } bool CppVariant::ToBoolean() const { DCHECK(isBool()); return value.boolValue; } std::vector<std::wstring> CppVariant::ToStringVector() const { DCHECK(isObject()); std::vector<std::wstring> wstring_vector; NPObject* np_value = value.objectValue; NPIdentifier length_id = NPN_GetStringIdentifier("length"); if (NPN_HasProperty(NULL, np_value, length_id)) { NPVariant length_value; if (NPN_GetProperty(NULL, np_value, length_id, &length_value)) { int length = 0; // The length is a double in some cases. if (NPVARIANT_IS_DOUBLE(length_value)) length = static_cast<int>(NPVARIANT_TO_DOUBLE(length_value)); else if (NPVARIANT_IS_INT32(length_value)) length = NPVARIANT_TO_INT32(length_value); // For sanity, only allow 100 items. length = std::min(100, length); for (int i = 0; i < length; ++i) { // Get each of the items. std::string index = StringPrintf("%d", i); NPIdentifier index_id = NPN_GetStringIdentifier(index.c_str()); if (NPN_HasProperty(NULL, np_value, index_id)) { NPVariant index_value; if (NPN_GetProperty(NULL, np_value, index_id, &index_value) && NPVARIANT_IS_STRING(index_value)) { std::string string(NPVARIANT_TO_STRING(index_value).UTF8Characters, NPVARIANT_TO_STRING(index_value).UTF8Length); wstring_vector.push_back(UTF8ToWide(string)); } } } } } return wstring_vector; } bool CppVariant::Invoke(const std::string& method, const CppVariant* args, uint32 arg_count, CppVariant& result) const { DCHECK(isObject()); NPIdentifier method_name = NPN_GetStringIdentifier(method.c_str()); NPObject* np_object = value.objectValue; if (NPN_HasMethod(NULL, np_object, method_name)) { NPVariant r; bool status = NPN_Invoke(NULL, np_object, method_name, args, arg_count, &r); result.Set(r); return status; } else { return false; } } <commit_msg>Fix a memory leak found by Valgrind.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file contains definitions for CppVariant. #include <limits> #include "config.h" #include "webkit/glue/cpp_variant.h" #include "base/logging.h" #include "base/string_util.h" #include "npruntime_priv.h" // for NPN_InitializeVariantWithStringCopy #if USE(JSC) #define _NPN_InitializeVariantWithStringCopy NPN_InitializeVariantWithStringCopy #endif CppVariant::CppVariant() { type = NPVariantType_Null; } // Note that Set() performs a deep copy, which is necessary to safely // call FreeData() on the value in the destructor. CppVariant::CppVariant(const CppVariant& original) { type = NPVariantType_Null; Set(original); } // See comment for copy constructor, above. CppVariant& CppVariant::operator=(const CppVariant& original) { if (&original != this) Set(original); return *this; } CppVariant::~CppVariant() { FreeData(); } void CppVariant::FreeData() { NPN_ReleaseVariantValue(this); } bool CppVariant::isEqual(const CppVariant& other) const { if (type != other.type) return false; switch (type) { case NPVariantType_Bool: { return (value.boolValue == other.value.boolValue); } case NPVariantType_Int32: { return (value.intValue == other.value.intValue); } case NPVariantType_Double: { return (value.doubleValue == other.value.doubleValue); } case NPVariantType_String: { const NPString *this_value = &value.stringValue; const NPString *other_value = &other.value.stringValue; uint32_t len = this_value->UTF8Length; return (len == other_value->UTF8Length && !strncmp(this_value->UTF8Characters, other_value->UTF8Characters, len)); } case NPVariantType_Null: case NPVariantType_Void: { return true; } case NPVariantType_Object: { NPObject *this_value = value.objectValue; NPObject *other_value = other.value.objectValue; return (this_value->_class == other_value->_class && this_value->referenceCount == other_value->referenceCount); } } return false; } void CppVariant::CopyToNPVariant(NPVariant* result) const { result->type = type; switch (type) { case NPVariantType_Bool: result->value.boolValue = value.boolValue; break; case NPVariantType_Int32: result->value.intValue = value.intValue; break; case NPVariantType_Double: result->value.doubleValue = value.doubleValue; break; case NPVariantType_String: _NPN_InitializeVariantWithStringCopy(result, &value.stringValue); break; case NPVariantType_Null: case NPVariantType_Void: // Nothing to set. break; case NPVariantType_Object: result->type = NPVariantType_Object; result->value.objectValue = NPN_RetainObject(value.objectValue); break; } } void CppVariant::Set(const NPVariant& new_value) { FreeData(); switch (new_value.type) { case NPVariantType_Bool: Set(new_value.value.boolValue); break; case NPVariantType_Int32: Set(new_value.value.intValue); break; case NPVariantType_Double: Set(new_value.value.doubleValue); break; case NPVariantType_String: Set(new_value.value.stringValue); break; case NPVariantType_Null: case NPVariantType_Void: type = new_value.type; break; case NPVariantType_Object: Set(new_value.value.objectValue); break; } } void CppVariant::SetNull() { FreeData(); type = NPVariantType_Null; } void CppVariant::Set(bool new_value) { FreeData(); type = NPVariantType_Bool; value.boolValue = new_value; } void CppVariant::Set(int32_t new_value) { FreeData(); type = NPVariantType_Int32; value.intValue = new_value; } void CppVariant::Set(double new_value) { FreeData(); type = NPVariantType_Double; value.doubleValue = new_value; } // The new_value must be a null-terminated string. void CppVariant::Set(const char* new_value) { FreeData(); type = NPVariantType_String; NPString new_string = {new_value, static_cast<uint32_t>(strlen(new_value))}; _NPN_InitializeVariantWithStringCopy(this, &new_string); } void CppVariant::Set(const std::string& new_value) { FreeData(); type = NPVariantType_String; NPString new_string = {new_value.data(), static_cast<uint32_t>(new_value.size())}; _NPN_InitializeVariantWithStringCopy(this, &new_string); } void CppVariant::Set(const NPString& new_value) { FreeData(); type = NPVariantType_String; _NPN_InitializeVariantWithStringCopy(this, &new_value); } void CppVariant::Set(NPObject* new_value) { FreeData(); type = NPVariantType_Object; value.objectValue = NPN_RetainObject(new_value); } std::string CppVariant::ToString() const { DCHECK(isString()); return std::string(value.stringValue.UTF8Characters, value.stringValue.UTF8Length); } int32_t CppVariant::ToInt32() const { if (isInt32()) { return value.intValue; } else if (isDouble()) { return static_cast<int32_t>(value.doubleValue); } else { NOTREACHED(); return 0; } } double CppVariant::ToDouble() const { if (isInt32()) { return static_cast<double>(value.intValue); } else if (isDouble()) { return value.doubleValue; } else { NOTREACHED(); return 0.0; } } bool CppVariant::ToBoolean() const { DCHECK(isBool()); return value.boolValue; } std::vector<std::wstring> CppVariant::ToStringVector() const { DCHECK(isObject()); std::vector<std::wstring> wstring_vector; NPObject* np_value = value.objectValue; NPIdentifier length_id = NPN_GetStringIdentifier("length"); if (NPN_HasProperty(NULL, np_value, length_id)) { NPVariant length_value; if (NPN_GetProperty(NULL, np_value, length_id, &length_value)) { int length = 0; // The length is a double in some cases. if (NPVARIANT_IS_DOUBLE(length_value)) length = static_cast<int>(NPVARIANT_TO_DOUBLE(length_value)); else if (NPVARIANT_IS_INT32(length_value)) length = NPVARIANT_TO_INT32(length_value); NPN_ReleaseVariantValue(&length_value); // For sanity, only allow 100 items. length = std::min(100, length); for (int i = 0; i < length; ++i) { // Get each of the items. std::string index = StringPrintf("%d", i); NPIdentifier index_id = NPN_GetStringIdentifier(index.c_str()); if (NPN_HasProperty(NULL, np_value, index_id)) { NPVariant index_value; if (NPN_GetProperty(NULL, np_value, index_id, &index_value)) { if (NPVARIANT_IS_STRING(index_value)) { std::string string( NPVARIANT_TO_STRING(index_value).UTF8Characters, NPVARIANT_TO_STRING(index_value).UTF8Length); wstring_vector.push_back(UTF8ToWide(string)); } NPN_ReleaseVariantValue(&index_value); } } } } } return wstring_vector; } bool CppVariant::Invoke(const std::string& method, const CppVariant* args, uint32 arg_count, CppVariant& result) const { DCHECK(isObject()); NPIdentifier method_name = NPN_GetStringIdentifier(method.c_str()); NPObject* np_object = value.objectValue; if (NPN_HasMethod(NULL, np_object, method_name)) { NPVariant r; bool status = NPN_Invoke(NULL, np_object, method_name, args, arg_count, &r); result.Set(r); return status; } else { return false; } } <|endoftext|>
<commit_before>/* * Copyright (C) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. 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 "config.h" #include "core/html/canvas/WebGLRenderingContext.h" #include "core/frame/LocalFrame.h" #include "core/html/canvas/ANGLEInstancedArrays.h" #include "core/html/canvas/EXTBlendMinMax.h" #include "core/html/canvas/EXTFragDepth.h" #include "core/html/canvas/EXTShaderTextureLOD.h" #include "core/html/canvas/EXTTextureFilterAnisotropic.h" #include "core/html/canvas/EXTsRGB.h" #include "core/html/canvas/OESElementIndexUint.h" #include "core/html/canvas/OESStandardDerivatives.h" #include "core/html/canvas/OESTextureFloat.h" #include "core/html/canvas/OESTextureFloatLinear.h" #include "core/html/canvas/OESTextureHalfFloat.h" #include "core/html/canvas/OESTextureHalfFloatLinear.h" #include "core/html/canvas/OESVertexArrayObject.h" #include "core/html/canvas/WebGLCompressedTextureATC.h" #include "core/html/canvas/WebGLCompressedTextureETC1.h" #include "core/html/canvas/WebGLCompressedTexturePVRTC.h" #include "core/html/canvas/WebGLCompressedTextureS3TC.h" #include "core/html/canvas/WebGLContextAttributes.h" #include "core/html/canvas/WebGLContextEvent.h" #include "core/html/canvas/WebGLDebugRendererInfo.h" #include "core/html/canvas/WebGLDebugShaders.h" #include "core/html/canvas/WebGLDepthTexture.h" #include "core/html/canvas/WebGLDrawBuffers.h" #include "core/html/canvas/WebGLLoseContext.h" #include "core/loader/FrameLoader.h" #include "core/loader/FrameLoaderClient.h" #include "core/frame/Settings.h" #include "core/rendering/RenderBox.h" #include "platform/CheckedInt.h" #include "platform/graphics/gpu/DrawingBuffer.h" #include "public/platform/Platform.h" namespace blink { PassOwnPtrWillBeRawPtr<WebGLRenderingContext> WebGLRenderingContext::create(HTMLCanvasElement* canvas, WebGLContextAttributes* attrs) { Document& document = canvas->document(); LocalFrame* frame = document.frame(); if (!frame) { canvas->dispatchEvent(WebGLContextEvent::create(EventTypeNames::webglcontextcreationerror, false, true, "Web page was not allowed to create a WebGL context.")); return nullptr; } Settings* settings = frame->settings(); // The FrameLoaderClient might block creation of a new WebGL context despite the page settings; in // particular, if WebGL contexts were lost one or more times via the GL_ARB_robustness extension. if (!frame->loader().client()->allowWebGL(settings && settings->webGLEnabled())) { canvas->dispatchEvent(WebGLContextEvent::create(EventTypeNames::webglcontextcreationerror, false, true, "Web page was not allowed to create a WebGL context.")); return nullptr; } // The only situation that attrs is null is through Document::getCSSCanvasContext(). RefPtrWillBeRawPtr<WebGLContextAttributes> defaultAttrs = nullptr; if (!attrs) { defaultAttrs = WebGLContextAttributes::create(); attrs = defaultAttrs.get(); } blink::WebGraphicsContext3D::Attributes attributes = attrs->attributes(document.topDocument().url().string(), settings, 1); OwnPtr<blink::WebGraphicsContext3D> context = adoptPtr(blink::Platform::current()->createOffscreenGraphicsContext3D(attributes, 0)); if (!context) { canvas->dispatchEvent(WebGLContextEvent::create(EventTypeNames::webglcontextcreationerror, false, true, "Could not create a WebGL context.")); return nullptr; } OwnPtr<Extensions3DUtil> extensionsUtil = Extensions3DUtil::create(context.get()); if (!extensionsUtil) return nullptr; if (extensionsUtil->supportsExtension("GL_EXT_debug_marker")) context->pushGroupMarkerEXT("WebGLRenderingContext"); OwnPtrWillBeRawPtr<WebGLRenderingContext> renderingContext = adoptPtrWillBeNoop(new WebGLRenderingContext(canvas, context.release(), attrs)); renderingContext->registerContextExtensions(); renderingContext->suspendIfNeeded(); if (!renderingContext->drawingBuffer()) { canvas->dispatchEvent(WebGLContextEvent::create(EventTypeNames::webglcontextcreationerror, false, true, "Could not create a WebGL context.")); return nullptr; } return renderingContext.release(); } WebGLRenderingContext::WebGLRenderingContext(HTMLCanvasElement* passedCanvas, PassOwnPtr<blink::WebGraphicsContext3D> context, WebGLContextAttributes* requestedAttributes) : WebGLRenderingContextBase(passedCanvas, context, requestedAttributes) { } WebGLRenderingContext::~WebGLRenderingContext() { } void WebGLRenderingContext::registerContextExtensions() { // Register extensions. static const char* const bothPrefixes[] = { "", "WEBKIT_", 0, }; registerExtension<ANGLEInstancedArrays>(m_angleInstancedArrays); registerExtension<EXTBlendMinMax>(m_extBlendMinMax); registerExtension<EXTFragDepth>(m_extFragDepth); registerExtension<EXTShaderTextureLOD>(m_extShaderTextureLOD); registerExtension<EXTsRGB>(m_extsRGB); registerExtension<EXTTextureFilterAnisotropic>(m_extTextureFilterAnisotropic, ApprovedExtension, bothPrefixes); registerExtension<OESElementIndexUint>(m_oesElementIndexUint); registerExtension<OESStandardDerivatives>(m_oesStandardDerivatives); registerExtension<OESTextureFloat>(m_oesTextureFloat); registerExtension<OESTextureFloatLinear>(m_oesTextureFloatLinear); registerExtension<OESTextureHalfFloat>(m_oesTextureHalfFloat); registerExtension<OESTextureHalfFloatLinear>(m_oesTextureHalfFloatLinear); registerExtension<OESVertexArrayObject>(m_oesVertexArrayObject); registerExtension<WebGLCompressedTextureATC>(m_webglCompressedTextureATC, ApprovedExtension, bothPrefixes); registerExtension<WebGLCompressedTextureETC1>(m_webglCompressedTextureETC1); registerExtension<WebGLCompressedTexturePVRTC>(m_webglCompressedTexturePVRTC, ApprovedExtension, bothPrefixes); registerExtension<WebGLCompressedTextureS3TC>(m_webglCompressedTextureS3TC, ApprovedExtension, bothPrefixes); registerExtension<WebGLDebugRendererInfo>(m_webglDebugRendererInfo); registerExtension<WebGLDebugShaders>(m_webglDebugShaders); registerExtension<WebGLDepthTexture>(m_webglDepthTexture, ApprovedExtension, bothPrefixes); registerExtension<WebGLDrawBuffers>(m_webglDrawBuffers); registerExtension<WebGLLoseContext>(m_webglLoseContext, ApprovedExtension, bothPrefixes); } void WebGLRenderingContext::trace(Visitor* visitor) { visitor->trace(m_angleInstancedArrays); visitor->trace(m_extBlendMinMax); visitor->trace(m_extFragDepth); visitor->trace(m_extShaderTextureLOD); visitor->trace(m_extsRGB); visitor->trace(m_extTextureFilterAnisotropic); visitor->trace(m_oesTextureFloat); visitor->trace(m_oesTextureFloatLinear); visitor->trace(m_oesTextureHalfFloat); visitor->trace(m_oesTextureHalfFloatLinear); visitor->trace(m_oesStandardDerivatives); visitor->trace(m_oesVertexArrayObject); visitor->trace(m_oesElementIndexUint); visitor->trace(m_webglLoseContext); visitor->trace(m_webglDebugRendererInfo); visitor->trace(m_webglDebugShaders); visitor->trace(m_webglDrawBuffers); visitor->trace(m_webglCompressedTextureATC); visitor->trace(m_webglCompressedTextureETC1); visitor->trace(m_webglCompressedTexturePVRTC); visitor->trace(m_webglCompressedTextureS3TC); visitor->trace(m_webglDepthTexture); WebGLRenderingContextBase::trace(visitor); } } // namespace blink <commit_msg>[WebGL] Return meaningful information in WebGL context creation error message. For example, vendor, renderer, driver version, etc.This way a developer can gather data on what platforms the app fails to run. This needs changes on both blink and chromium.<commit_after>/* * Copyright (C) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. 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 "config.h" #include "core/html/canvas/WebGLRenderingContext.h" #include "core/frame/LocalFrame.h" #include "core/html/canvas/ANGLEInstancedArrays.h" #include "core/html/canvas/EXTBlendMinMax.h" #include "core/html/canvas/EXTFragDepth.h" #include "core/html/canvas/EXTShaderTextureLOD.h" #include "core/html/canvas/EXTTextureFilterAnisotropic.h" #include "core/html/canvas/EXTsRGB.h" #include "core/html/canvas/OESElementIndexUint.h" #include "core/html/canvas/OESStandardDerivatives.h" #include "core/html/canvas/OESTextureFloat.h" #include "core/html/canvas/OESTextureFloatLinear.h" #include "core/html/canvas/OESTextureHalfFloat.h" #include "core/html/canvas/OESTextureHalfFloatLinear.h" #include "core/html/canvas/OESVertexArrayObject.h" #include "core/html/canvas/WebGLCompressedTextureATC.h" #include "core/html/canvas/WebGLCompressedTextureETC1.h" #include "core/html/canvas/WebGLCompressedTexturePVRTC.h" #include "core/html/canvas/WebGLCompressedTextureS3TC.h" #include "core/html/canvas/WebGLContextAttributes.h" #include "core/html/canvas/WebGLContextEvent.h" #include "core/html/canvas/WebGLDebugRendererInfo.h" #include "core/html/canvas/WebGLDebugShaders.h" #include "core/html/canvas/WebGLDepthTexture.h" #include "core/html/canvas/WebGLDrawBuffers.h" #include "core/html/canvas/WebGLLoseContext.h" #include "core/loader/FrameLoader.h" #include "core/loader/FrameLoaderClient.h" #include "core/frame/Settings.h" #include "core/rendering/RenderBox.h" #include "platform/CheckedInt.h" #include "platform/graphics/gpu/DrawingBuffer.h" #include "public/platform/Platform.h" namespace blink { PassOwnPtrWillBeRawPtr<WebGLRenderingContext> WebGLRenderingContext::create(HTMLCanvasElement* canvas, WebGLContextAttributes* attrs) { Document& document = canvas->document(); LocalFrame* frame = document.frame(); if (!frame) { canvas->dispatchEvent(WebGLContextEvent::create(EventTypeNames::webglcontextcreationerror, false, true, "Web page was not allowed to create a WebGL context.")); return nullptr; } Settings* settings = frame->settings(); // The FrameLoaderClient might block creation of a new WebGL context despite the page settings; in // particular, if WebGL contexts were lost one or more times via the GL_ARB_robustness extension. if (!frame->loader().client()->allowWebGL(settings && settings->webGLEnabled())) { canvas->dispatchEvent(WebGLContextEvent::create(EventTypeNames::webglcontextcreationerror, false, true, "Web page was not allowed to create a WebGL context.")); return nullptr; } // The only situation that attrs is null is through Document::getCSSCanvasContext(). RefPtrWillBeRawPtr<WebGLContextAttributes> defaultAttrs = nullptr; if (!attrs) { defaultAttrs = WebGLContextAttributes::create(); attrs = defaultAttrs.get(); } blink::WebGraphicsContext3D::Attributes attributes = attrs->attributes(document.topDocument().url().string(), settings, 1); blink::WebGLInfo glInfo; OwnPtr<blink::WebGraphicsContext3D> context = adoptPtr(blink::Platform::current()->createOffscreenGraphicsContext3D(attributes, 0, &glInfo)); if (!context) { String statusMessage("Could not create a WebGL context for VendorInfo = "); statusMessage.append(glInfo.vendorInfo); statusMessage.append(", RendererInfo = "); statusMessage.append(glInfo.rendererInfo); statusMessage.append(", DriverInfo = "); statusMessage.append(glInfo.driverVersion); statusMessage.append("."); canvas->dispatchEvent(WebGLContextEvent::create(EventTypeNames::webglcontextcreationerror, false, true, statusMessage)); return nullptr; } OwnPtr<Extensions3DUtil> extensionsUtil = Extensions3DUtil::create(context.get()); if (!extensionsUtil) return nullptr; if (extensionsUtil->supportsExtension("GL_EXT_debug_marker")) context->pushGroupMarkerEXT("WebGLRenderingContext"); OwnPtrWillBeRawPtr<WebGLRenderingContext> renderingContext = adoptPtrWillBeNoop(new WebGLRenderingContext(canvas, context.release(), attrs)); renderingContext->registerContextExtensions(); renderingContext->suspendIfNeeded(); if (!renderingContext->drawingBuffer()) { canvas->dispatchEvent(WebGLContextEvent::create(EventTypeNames::webglcontextcreationerror, false, true, "Could not create a WebGL context.")); return nullptr; } return renderingContext.release(); } WebGLRenderingContext::WebGLRenderingContext(HTMLCanvasElement* passedCanvas, PassOwnPtr<blink::WebGraphicsContext3D> context, WebGLContextAttributes* requestedAttributes) : WebGLRenderingContextBase(passedCanvas, context, requestedAttributes) { } WebGLRenderingContext::~WebGLRenderingContext() { } void WebGLRenderingContext::registerContextExtensions() { // Register extensions. static const char* const bothPrefixes[] = { "", "WEBKIT_", 0, }; registerExtension<ANGLEInstancedArrays>(m_angleInstancedArrays); registerExtension<EXTBlendMinMax>(m_extBlendMinMax); registerExtension<EXTFragDepth>(m_extFragDepth); registerExtension<EXTShaderTextureLOD>(m_extShaderTextureLOD); registerExtension<EXTsRGB>(m_extsRGB); registerExtension<EXTTextureFilterAnisotropic>(m_extTextureFilterAnisotropic, ApprovedExtension, bothPrefixes); registerExtension<OESElementIndexUint>(m_oesElementIndexUint); registerExtension<OESStandardDerivatives>(m_oesStandardDerivatives); registerExtension<OESTextureFloat>(m_oesTextureFloat); registerExtension<OESTextureFloatLinear>(m_oesTextureFloatLinear); registerExtension<OESTextureHalfFloat>(m_oesTextureHalfFloat); registerExtension<OESTextureHalfFloatLinear>(m_oesTextureHalfFloatLinear); registerExtension<OESVertexArrayObject>(m_oesVertexArrayObject); registerExtension<WebGLCompressedTextureATC>(m_webglCompressedTextureATC, ApprovedExtension, bothPrefixes); registerExtension<WebGLCompressedTextureETC1>(m_webglCompressedTextureETC1); registerExtension<WebGLCompressedTexturePVRTC>(m_webglCompressedTexturePVRTC, ApprovedExtension, bothPrefixes); registerExtension<WebGLCompressedTextureS3TC>(m_webglCompressedTextureS3TC, ApprovedExtension, bothPrefixes); registerExtension<WebGLDebugRendererInfo>(m_webglDebugRendererInfo); registerExtension<WebGLDebugShaders>(m_webglDebugShaders); registerExtension<WebGLDepthTexture>(m_webglDepthTexture, ApprovedExtension, bothPrefixes); registerExtension<WebGLDrawBuffers>(m_webglDrawBuffers); registerExtension<WebGLLoseContext>(m_webglLoseContext, ApprovedExtension, bothPrefixes); } void WebGLRenderingContext::trace(Visitor* visitor) { visitor->trace(m_angleInstancedArrays); visitor->trace(m_extBlendMinMax); visitor->trace(m_extFragDepth); visitor->trace(m_extShaderTextureLOD); visitor->trace(m_extsRGB); visitor->trace(m_extTextureFilterAnisotropic); visitor->trace(m_oesTextureFloat); visitor->trace(m_oesTextureFloatLinear); visitor->trace(m_oesTextureHalfFloat); visitor->trace(m_oesTextureHalfFloatLinear); visitor->trace(m_oesStandardDerivatives); visitor->trace(m_oesVertexArrayObject); visitor->trace(m_oesElementIndexUint); visitor->trace(m_webglLoseContext); visitor->trace(m_webglDebugRendererInfo); visitor->trace(m_webglDebugShaders); visitor->trace(m_webglDrawBuffers); visitor->trace(m_webglCompressedTextureATC); visitor->trace(m_webglCompressedTextureETC1); visitor->trace(m_webglCompressedTexturePVRTC); visitor->trace(m_webglCompressedTextureS3TC); visitor->trace(m_webglDepthTexture); WebGLRenderingContextBase::trace(visitor); } } // namespace blink <|endoftext|>
<commit_before>#include "FibRng.h" #include <stdio.h> #include <string.h> #include <time.h> // The tickle variable protects against rapid fire creation of // generators with the default seed. uint32_t FibRng::tickle = 0; const double FibRng::BASE = FibRng::CHOP + 1.0; // A constructor for Fibonacci Psuedo Random Number Generator. // seed - A seed string. // depth - The number of cells to use. Valid values are 2...Are_you_crazy? FibRng::FibRng(char *seed, int _depth) { depth = _depth; ring = new uint32_t[depth + 2]; reseed(seed); } // A constructor for Fibonacci Psuedo Random Number Generator with default seed. // depth - The number of cells to use. Valid values are 2...Are_you_crazy? FibRng::FibRng(int _depth) { char seed_buffer[80]; sprintf_s(seed_buffer, 80, "%d", time(NULL) + tickle); tickle++; depth = _depth; ring = new uint32_t[depth + 2]; reseed(seed_buffer); } // Time to pack up and go home! FibRng::~FibRng() { delete [] ring; } // Roll a dice with the specified number of sides. uint32_t FibRng::dice(uint32_t sides) { uint32_t limit = ((CHOP + 1) / sides) * sides; do { spin(); } while (ring[0] >= limit); return ring[0] % sides; } uint8_t FibRng::byte(void) { spin(); return ring[0] & 0xFF; } uint16_t FibRng::word(void) { spin(); return ring[0] & 0xFFFF; } double FibRng::real(void) { spin(); return ring[0] / BASE; } // Reseed the generator with a new value. void FibRng::reseed(char *seed) { int seed_len = strlen(seed); erase(); for (int i = 0; i < 1024; i++) { unsigned int t = seed[i % seed_len]; unsigned int x = i % depth; ring[x] += t; spin(); } } // Scramble the eggs some more. void FibRng::spin(void) { // Copy over the 'end' values. ring[depth] = ring[0]; ring[depth + 1] = ring[1]; // Spin the wheel! for (int i = 0; i < depth; i++) { uint32_t ring_i_2 = ring[i + 2]; ring[i] = (ring[i + 1] + ((ring_i_2 >> 1) | ((ring_i_2 & 1) ? TOP : 0))) & CHOP; } } // Dump the internal state for test purposes. void FibRng::dump(void) { for (int i = 0; i < depth; i++) { printf("%u ", ring[i]); } printf("\n"); } // Erase the generator's internal state. void FibRng::erase(void) { for (int i = 0; i < depth; i++) { ring[i] = 0; } } <commit_msg>Progressive reseeding ported in.<commit_after>#include "FibRng.h" #include <stdio.h> #include <string.h> #include <time.h> // The tickle variable protects against rapid fire creation of // generators with the default seed. uint32_t FibRng::tickle = 0; const double FibRng::BASE = FibRng::CHOP + 1.0; // A constructor for Fibonacci Psuedo Random Number Generator. // seed - A seed string. // depth - The number of cells to use. Valid values are 2...Are_you_crazy? FibRng::FibRng(char *seed, int _depth) { depth = _depth; ring = new uint32_t[depth + 2]; reseed(seed); } // A constructor for Fibonacci Psuedo Random Number Generator with default seed. // depth - The number of cells to use. Valid values are 2...Are_you_crazy? FibRng::FibRng(int _depth) { char seed_buffer[80]; sprintf_s(seed_buffer, 80, "%d", time(NULL) + tickle); tickle++; depth = _depth; ring = new uint32_t[depth + 2]; reseed(seed_buffer); } // Time to pack up and go home! FibRng::~FibRng() { delete [] ring; } // Roll a dice with the specified number of sides. uint32_t FibRng::dice(uint32_t sides) { uint32_t limit = ((CHOP + 1) / sides) * sides; do { spin(); } while (ring[0] >= limit); return ring[0] % sides; } uint8_t FibRng::byte(void) { spin(); return ring[0] & 0xFF; } uint16_t FibRng::word(void) { spin(); return ring[0] & 0xFFFF; } double FibRng::real(void) { spin(); return ring[0] / BASE; } // Reseed the generator with a new value. void FibRng::reseed(char *seed) { int seed_len = strlen(seed); erase(); int seed_count = 32*depth + 768; for (int i = 0; i < seed_count; i++) { unsigned int t = seed[i % seed_len]; unsigned int x = i % depth; ring[x] += t; spin(); } } // Scramble the eggs some more. void FibRng::spin(void) { // Copy over the 'end' values. ring[depth] = ring[0]; ring[depth + 1] = ring[1]; // Spin the wheel! for (int i = 0; i < depth; i++) { uint32_t ring_i_2 = ring[i + 2]; ring[i] = (ring[i + 1] + ((ring_i_2 >> 1) | ((ring_i_2 & 1) ? TOP : 0))) & CHOP; } } // Dump the internal state for test purposes. void FibRng::dump(void) { for (int i = 0; i < depth; i++) { printf("%u ", ring[i]); } printf("\n"); } // Erase the generator's internal state. void FibRng::erase(void) { for (int i = 0; i < depth; i++) { ring[i] = 0; } } <|endoftext|>
<commit_before>/* * Copyright (C) 2010 The Android Open Source Project * * 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 <string> #include "Test.h" #include "SkPDFCatalog.h" #include "SkPDFStream.h" #include "SkPDFTypes.h" #include "SkScalar.h" #include "SkStream.h" static void CheckObjectOutput(skiatest::Reporter* reporter, SkPDFObject* obj, const std::string& representation, bool indirect) { size_t directSize = obj->getOutputSize(NULL, false); REPORTER_ASSERT(reporter, directSize == representation.size()); SkDynamicMemoryWStream buffer; obj->emitObject(&buffer, NULL, false); REPORTER_ASSERT(reporter, directSize == buffer.getOffset()); REPORTER_ASSERT(reporter, memcmp(buffer.getStream(), representation.c_str(), directSize) == 0); if (indirect) { // Indirect output. static char header[] = "1 0 obj\n"; static size_t headerLen = strlen(header); static char footer[] = "\nendobj\n"; static size_t footerLen = strlen(footer); SkPDFCatalog catalog; catalog.addObject(obj, false); size_t indirectSize = obj->getOutputSize(&catalog, true); REPORTER_ASSERT(reporter, indirectSize == directSize + headerLen + footerLen); buffer.reset(); obj->emitObject(&buffer, &catalog, true); REPORTER_ASSERT(reporter, indirectSize == buffer.getOffset()); REPORTER_ASSERT(reporter, memcmp(buffer.getStream(), header, headerLen) == 0); REPORTER_ASSERT(reporter, memcmp(buffer.getStream() + headerLen, representation.c_str(), directSize) == 0); REPORTER_ASSERT(reporter, memcmp(buffer.getStream() + headerLen + directSize, footer, footerLen) == 0); } } static void TestCatalog(skiatest::Reporter* reporter) { SkPDFCatalog catalog; SkRefPtr<SkPDFInt> int1 = new SkPDFInt(1); int1->unref(); // SkRefPtr and new both took a reference. SkRefPtr<SkPDFInt> int2 = new SkPDFInt(2); int2->unref(); // SkRefPtr and new both took a reference. SkRefPtr<SkPDFInt> int3 = new SkPDFInt(3); int3->unref(); // SkRefPtr and new both took a reference. SkRefPtr<SkPDFInt> int1Again(int1.get()); catalog.addObject(int1.get(), false); catalog.addObject(int2.get(), false); catalog.addObject(int3.get(), false); REPORTER_ASSERT(reporter, catalog.getObjectNumberSize(int1.get()) == 3); REPORTER_ASSERT(reporter, catalog.getObjectNumberSize(int2.get()) == 3); REPORTER_ASSERT(reporter, catalog.getObjectNumberSize(int3.get()) == 3); SkDynamicMemoryWStream buffer; catalog.emitObjectNumber(&buffer, int1.get()); catalog.emitObjectNumber(&buffer, int2.get()); catalog.emitObjectNumber(&buffer, int3.get()); catalog.emitObjectNumber(&buffer, int1Again.get()); char expectedResult[] = "1 02 03 01 0"; REPORTER_ASSERT(reporter, memcmp(buffer.getStream(), expectedResult, strlen(expectedResult)) == 0); } static void TestObjectRef(skiatest::Reporter* reporter) { SkRefPtr<SkPDFInt> int1 = new SkPDFInt(1); int1->unref(); // SkRefPtr and new both took a reference. SkRefPtr<SkPDFInt> int2 = new SkPDFInt(2); int2->unref(); // SkRefPtr and new both took a reference. SkRefPtr<SkPDFObjRef> int2ref = new SkPDFObjRef(int2.get()); int2ref->unref(); // SkRefPtr and new both took a reference. SkPDFCatalog catalog; catalog.addObject(int1.get(), false); catalog.addObject(int2.get(), false); REPORTER_ASSERT(reporter, catalog.getObjectNumberSize(int1.get()) == 3); REPORTER_ASSERT(reporter, catalog.getObjectNumberSize(int2.get()) == 3); char expectedResult[] = "2 0 R"; SkDynamicMemoryWStream buffer; int2ref->emitObject(&buffer, &catalog, false); REPORTER_ASSERT(reporter, buffer.getOffset() == strlen(expectedResult)); REPORTER_ASSERT(reporter, memcmp(buffer.getStream(), expectedResult, buffer.getOffset()) == 0); } static void TestPDFPrimitives(skiatest::Reporter* reporter) { SkRefPtr<SkPDFInt> int42 = new SkPDFInt(42); int42->unref(); // SkRefPtr and new both took a reference. CheckObjectOutput(reporter, int42.get(), "42", true); SkRefPtr<SkPDFScalar> realHalf = new SkPDFScalar(SK_ScalarHalf); realHalf->unref(); // SkRefPtr and new both took a reference. CheckObjectOutput(reporter, realHalf.get(), "0.5", true); SkRefPtr<SkPDFScalar> bigScalar = new SkPDFScalar(110999.75); bigScalar->unref(); // SkRefPtr and new both took a reference. #if defined(SK_SCALAR_IS_FIXED) || !defined(SK_ALLOW_LARGE_PDF_SCALARS) CheckObjectOutput(reporter, bigScalar.get(), "111000", true); #else CheckObjectOutput(reporter, bigScalar.get(), "110999.75", true); #endif #if defined(SK_SCALAR_IS_FLOAT) && defined(SK_ALLOW_LARGE_PDF_SCALARS) SkRefPtr<SkPDFScalar> biggerScalar = new SkPDFScalar(50000000.1); biggerScalar->unref(); // SkRefPtr and new both took a reference. CheckObjectOutput(reporter, biggerScalar.get(), "50000000", true); SkRefPtr<SkPDFScalar> smallestScalar = new SkPDFScalar(1.0/65536); smallestScalar->unref(); // SkRefPtr and new both took a reference. CheckObjectOutput(reporter, smallestScalar.get(), "0.00001526", true); #endif SkRefPtr<SkPDFString> stringSimple = new SkPDFString("test ) string ( foo"); stringSimple->unref(); // SkRefPtr and new both took a reference. CheckObjectOutput(reporter, stringSimple.get(), "(test \\) string \\( foo)", true); SkRefPtr<SkPDFString> stringComplex = new SkPDFString("\ttest ) string ( foo"); stringComplex->unref(); // SkRefPtr and new both took a reference. CheckObjectOutput(reporter, stringComplex.get(), "<0974657374202920737472696E67202820666F6F>", true); SkRefPtr<SkPDFName> name = new SkPDFName("Test name\twith#tab"); name->unref(); // SkRefPtr and new both took a reference. CheckObjectOutput(reporter, name.get(), "/Test#20name#09with#23tab", false); SkRefPtr<SkPDFArray> array = new SkPDFArray; array->unref(); // SkRefPtr and new both took a reference. CheckObjectOutput(reporter, array.get(), "[]", true); array->append(int42.get()); CheckObjectOutput(reporter, array.get(), "[42]", true); array->append(realHalf.get()); CheckObjectOutput(reporter, array.get(), "[42 0.5]", true); SkRefPtr<SkPDFInt> int0 = new SkPDFInt(0); int0->unref(); // SkRefPtr and new both took a reference. array->append(int0.get()); CheckObjectOutput(reporter, array.get(), "[42 0.5 0]", true); SkRefPtr<SkPDFInt> int1 = new SkPDFInt(1); int1->unref(); // SkRefPtr and new both took a reference. array->setAt(0, int1.get()); CheckObjectOutput(reporter, array.get(), "[1 0.5 0]", true); SkRefPtr<SkPDFDict> dict = new SkPDFDict; dict->unref(); // SkRefPtr and new both took a reference. CheckObjectOutput(reporter, dict.get(), "<<>>", true); SkRefPtr<SkPDFName> n1 = new SkPDFName("n1"); n1->unref(); // SkRefPtr and new both took a reference. dict->insert(n1.get(), int42.get()); CheckObjectOutput(reporter, dict.get(), "<</n1 42\n>>", true); SkRefPtr<SkPDFName> n2 = new SkPDFName("n2"); n2->unref(); // SkRefPtr and new both took a reference. SkRefPtr<SkPDFName> n3 = new SkPDFName("n3"); n3->unref(); // SkRefPtr and new both took a reference. dict->insert(n2.get(), realHalf.get()); dict->insert(n3.get(), array.get()); CheckObjectOutput(reporter, dict.get(), "<</n1 42\n/n2 0.5\n/n3 [1 0.5 0]\n>>", true); char streamBytes[] = "Test\nFoo\tBar"; SkRefPtr<SkMemoryStream> streamData = new SkMemoryStream( streamBytes, strlen(streamBytes), true); streamData->unref(); // SkRefPtr and new both took a reference. SkRefPtr<SkPDFStream> stream = new SkPDFStream(streamData.get()); stream->unref(); // SkRefPtr and new both took a reference. CheckObjectOutput(reporter, stream.get(), "<</Length 12\n>> stream\nTest\nFoo\tBar\nendstream", true); stream->insert(n1.get(), int42.get()); CheckObjectOutput(reporter, stream.get(), "<</Length 12\n/n1 42\n>> stream\nTest\nFoo\tBar" "\nendstream", true); TestCatalog(reporter); TestObjectRef(reporter); } #include "TestClassDef.h" DEFINE_TESTCLASS("PDFPrimitives", PDFPrimitivesTestClass, TestPDFPrimitives) <commit_msg>[PDF] Fix PDF primitives test for fixed scalars.<commit_after>/* * Copyright (C) 2010 The Android Open Source Project * * 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 <string> #include "Test.h" #include "SkPDFCatalog.h" #include "SkPDFStream.h" #include "SkPDFTypes.h" #include "SkScalar.h" #include "SkStream.h" static void CheckObjectOutput(skiatest::Reporter* reporter, SkPDFObject* obj, const std::string& representation, bool indirect) { size_t directSize = obj->getOutputSize(NULL, false); REPORTER_ASSERT(reporter, directSize == representation.size()); SkDynamicMemoryWStream buffer; obj->emitObject(&buffer, NULL, false); REPORTER_ASSERT(reporter, directSize == buffer.getOffset()); REPORTER_ASSERT(reporter, memcmp(buffer.getStream(), representation.c_str(), directSize) == 0); if (indirect) { // Indirect output. static char header[] = "1 0 obj\n"; static size_t headerLen = strlen(header); static char footer[] = "\nendobj\n"; static size_t footerLen = strlen(footer); SkPDFCatalog catalog; catalog.addObject(obj, false); size_t indirectSize = obj->getOutputSize(&catalog, true); REPORTER_ASSERT(reporter, indirectSize == directSize + headerLen + footerLen); buffer.reset(); obj->emitObject(&buffer, &catalog, true); REPORTER_ASSERT(reporter, indirectSize == buffer.getOffset()); REPORTER_ASSERT(reporter, memcmp(buffer.getStream(), header, headerLen) == 0); REPORTER_ASSERT(reporter, memcmp(buffer.getStream() + headerLen, representation.c_str(), directSize) == 0); REPORTER_ASSERT(reporter, memcmp(buffer.getStream() + headerLen + directSize, footer, footerLen) == 0); } } static void TestCatalog(skiatest::Reporter* reporter) { SkPDFCatalog catalog; SkRefPtr<SkPDFInt> int1 = new SkPDFInt(1); int1->unref(); // SkRefPtr and new both took a reference. SkRefPtr<SkPDFInt> int2 = new SkPDFInt(2); int2->unref(); // SkRefPtr and new both took a reference. SkRefPtr<SkPDFInt> int3 = new SkPDFInt(3); int3->unref(); // SkRefPtr and new both took a reference. SkRefPtr<SkPDFInt> int1Again(int1.get()); catalog.addObject(int1.get(), false); catalog.addObject(int2.get(), false); catalog.addObject(int3.get(), false); REPORTER_ASSERT(reporter, catalog.getObjectNumberSize(int1.get()) == 3); REPORTER_ASSERT(reporter, catalog.getObjectNumberSize(int2.get()) == 3); REPORTER_ASSERT(reporter, catalog.getObjectNumberSize(int3.get()) == 3); SkDynamicMemoryWStream buffer; catalog.emitObjectNumber(&buffer, int1.get()); catalog.emitObjectNumber(&buffer, int2.get()); catalog.emitObjectNumber(&buffer, int3.get()); catalog.emitObjectNumber(&buffer, int1Again.get()); char expectedResult[] = "1 02 03 01 0"; REPORTER_ASSERT(reporter, memcmp(buffer.getStream(), expectedResult, strlen(expectedResult)) == 0); } static void TestObjectRef(skiatest::Reporter* reporter) { SkRefPtr<SkPDFInt> int1 = new SkPDFInt(1); int1->unref(); // SkRefPtr and new both took a reference. SkRefPtr<SkPDFInt> int2 = new SkPDFInt(2); int2->unref(); // SkRefPtr and new both took a reference. SkRefPtr<SkPDFObjRef> int2ref = new SkPDFObjRef(int2.get()); int2ref->unref(); // SkRefPtr and new both took a reference. SkPDFCatalog catalog; catalog.addObject(int1.get(), false); catalog.addObject(int2.get(), false); REPORTER_ASSERT(reporter, catalog.getObjectNumberSize(int1.get()) == 3); REPORTER_ASSERT(reporter, catalog.getObjectNumberSize(int2.get()) == 3); char expectedResult[] = "2 0 R"; SkDynamicMemoryWStream buffer; int2ref->emitObject(&buffer, &catalog, false); REPORTER_ASSERT(reporter, buffer.getOffset() == strlen(expectedResult)); REPORTER_ASSERT(reporter, memcmp(buffer.getStream(), expectedResult, buffer.getOffset()) == 0); } static void TestPDFPrimitives(skiatest::Reporter* reporter) { SkRefPtr<SkPDFInt> int42 = new SkPDFInt(42); int42->unref(); // SkRefPtr and new both took a reference. CheckObjectOutput(reporter, int42.get(), "42", true); SkRefPtr<SkPDFScalar> realHalf = new SkPDFScalar(SK_ScalarHalf); realHalf->unref(); // SkRefPtr and new both took a reference. CheckObjectOutput(reporter, realHalf.get(), "0.5", true); #if defined(SK_SCALAR_IS_FLOAT) SkRefPtr<SkPDFScalar> bigScalar = new SkPDFScalar(110999.75); bigScalar->unref(); // SkRefPtr and new both took a reference. #if !defined(SK_ALLOW_LARGE_PDF_SCALARS) CheckObjectOutput(reporter, bigScalar.get(), "111000", true); #else CheckObjectOutput(reporter, bigScalar.get(), "110999.75", true); SkRefPtr<SkPDFScalar> biggerScalar = new SkPDFScalar(50000000.1); biggerScalar->unref(); // SkRefPtr and new both took a reference. CheckObjectOutput(reporter, biggerScalar.get(), "50000000", true); SkRefPtr<SkPDFScalar> smallestScalar = new SkPDFScalar(1.0/65536); smallestScalar->unref(); // SkRefPtr and new both took a reference. CheckObjectOutput(reporter, smallestScalar.get(), "0.00001526", true); #endif #endif SkRefPtr<SkPDFString> stringSimple = new SkPDFString("test ) string ( foo"); stringSimple->unref(); // SkRefPtr and new both took a reference. CheckObjectOutput(reporter, stringSimple.get(), "(test \\) string \\( foo)", true); SkRefPtr<SkPDFString> stringComplex = new SkPDFString("\ttest ) string ( foo"); stringComplex->unref(); // SkRefPtr and new both took a reference. CheckObjectOutput(reporter, stringComplex.get(), "<0974657374202920737472696E67202820666F6F>", true); SkRefPtr<SkPDFName> name = new SkPDFName("Test name\twith#tab"); name->unref(); // SkRefPtr and new both took a reference. CheckObjectOutput(reporter, name.get(), "/Test#20name#09with#23tab", false); SkRefPtr<SkPDFArray> array = new SkPDFArray; array->unref(); // SkRefPtr and new both took a reference. CheckObjectOutput(reporter, array.get(), "[]", true); array->append(int42.get()); CheckObjectOutput(reporter, array.get(), "[42]", true); array->append(realHalf.get()); CheckObjectOutput(reporter, array.get(), "[42 0.5]", true); SkRefPtr<SkPDFInt> int0 = new SkPDFInt(0); int0->unref(); // SkRefPtr and new both took a reference. array->append(int0.get()); CheckObjectOutput(reporter, array.get(), "[42 0.5 0]", true); SkRefPtr<SkPDFInt> int1 = new SkPDFInt(1); int1->unref(); // SkRefPtr and new both took a reference. array->setAt(0, int1.get()); CheckObjectOutput(reporter, array.get(), "[1 0.5 0]", true); SkRefPtr<SkPDFDict> dict = new SkPDFDict; dict->unref(); // SkRefPtr and new both took a reference. CheckObjectOutput(reporter, dict.get(), "<<>>", true); SkRefPtr<SkPDFName> n1 = new SkPDFName("n1"); n1->unref(); // SkRefPtr and new both took a reference. dict->insert(n1.get(), int42.get()); CheckObjectOutput(reporter, dict.get(), "<</n1 42\n>>", true); SkRefPtr<SkPDFName> n2 = new SkPDFName("n2"); n2->unref(); // SkRefPtr and new both took a reference. SkRefPtr<SkPDFName> n3 = new SkPDFName("n3"); n3->unref(); // SkRefPtr and new both took a reference. dict->insert(n2.get(), realHalf.get()); dict->insert(n3.get(), array.get()); CheckObjectOutput(reporter, dict.get(), "<</n1 42\n/n2 0.5\n/n3 [1 0.5 0]\n>>", true); char streamBytes[] = "Test\nFoo\tBar"; SkRefPtr<SkMemoryStream> streamData = new SkMemoryStream( streamBytes, strlen(streamBytes), true); streamData->unref(); // SkRefPtr and new both took a reference. SkRefPtr<SkPDFStream> stream = new SkPDFStream(streamData.get()); stream->unref(); // SkRefPtr and new both took a reference. CheckObjectOutput(reporter, stream.get(), "<</Length 12\n>> stream\nTest\nFoo\tBar\nendstream", true); stream->insert(n1.get(), int42.get()); CheckObjectOutput(reporter, stream.get(), "<</Length 12\n/n1 42\n>> stream\nTest\nFoo\tBar" "\nendstream", true); TestCatalog(reporter); TestObjectRef(reporter); } #include "TestClassDef.h" DEFINE_TESTCLASS("PDFPrimitives", PDFPrimitivesTestClass, TestPDFPrimitives) <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: vclxaccessiblecomponent.hxx,v $ * * $Revision: 1.21 $ * * last change: $Author: hr $ $Date: 2003-03-27 17:02:43 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _TOOLKIT_AWT_VCLXACCESSIBLECOMPONENT_HXX_ #define _TOOLKIT_AWT_VCLXACCESSIBLECOMPONENT_HXX_ #ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLE_HPP_ #include <drafts/com/sun/star/accessibility/XAccessible.hpp> #endif #ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLECONTEXT_HPP_ #include <drafts/com/sun/star/accessibility/XAccessibleContext.hpp> #endif #ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLEEXTENDEDCOMPONENT_HPP_ #include <drafts/com/sun/star/accessibility/XAccessibleExtendedComponent.hpp> #endif #ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLEEVENTBROADCASTER_HPP_ #include <drafts/com/sun/star/accessibility/XAccessibleEventBroadcaster.hpp> #endif #ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_ #include <com/sun/star/awt/XWindow.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _CPPUHELPER_COMPBASE3_HXX_ #include <cppuhelper/compbase3.hxx> #endif #ifndef _CPPUHELPER_IMPLBASE1_HXX_ #include <cppuhelper/implbase1.hxx> #endif #ifndef COMPHELPER_ACCIMPLACCESS_HXX #include <comphelper/accimplaccess.hxx> #endif #ifndef COMPHELPER_ACCESSIBLE_COMPONENT_HELPER_HXX #include <comphelper/accessiblecomponenthelper.hxx> #endif #include <tools/gen.hxx> // Size #include <tools/link.hxx> // Size class Window; class VCLXWindow; class VclSimpleEvent; class VclWindowEvent; namespace utl { class AccessibleRelationSetHelper; class AccessibleStateSetHelper; } // ---------------------------------------------------- // class VCLXAccessibleComponent // ---------------------------------------------------- typedef ::comphelper::OAccessibleExtendedComponentHelper AccessibleExtendedComponentHelper_BASE; typedef ::cppu::ImplHelper1< ::com::sun::star::lang::XServiceInfo > VCLXAccessibleComponent_BASE; class VCLExternalSolarLock; class VCLXAccessibleComponent :public AccessibleExtendedComponentHelper_BASE ,public ::comphelper::OAccessibleImplementationAccess ,public VCLXAccessibleComponent_BASE { private: ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow> mxWindow; VCLXWindow* mpVCLXindow; ULONG nDummy1; ULONG nDummy2; void* pDummy1; VCLExternalSolarLock* m_pSolarLock; protected: DECL_LINK( WindowEventListener, VclSimpleEvent* ); DECL_LINK( WindowChildEventListener, VclSimpleEvent* ); virtual void ProcessWindowEvent( const VclWindowEvent& rVclWindowEvent ); virtual void ProcessWindowChildEvent( const VclWindowEvent& rVclWindowEvent ); virtual void FillAccessibleRelationSet( utl::AccessibleRelationSetHelper& rRelationSet ); virtual void FillAccessibleStateSet( utl::AccessibleStateSetHelper& rStateSet ); virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible > GetChildAccessible( const VclWindowEvent& rVclWindowEvent ); public: VCLXAccessibleComponent( VCLXWindow* pVCLXindow ); ~VCLXAccessibleComponent(); VCLXWindow* GetVCLXWindow() const { return mpVCLXindow; } Window* GetWindow() const; virtual void SAL_CALL disposing(); // ::com::sun::star::uno::XInterface DECLARE_XINTERFACE() // ::com::sun::star::lang::XTypeProvider DECLARE_XTYPEPROVIDER() // XServiceInfo virtual ::rtl::OUString SAL_CALL getImplementationName() throw (::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& rServiceName ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw (::com::sun::star::uno::RuntimeException); // ::drafts::com::sun::star::accessibility::XAccessibleContext sal_Int32 SAL_CALL getAccessibleChildCount( ) throw (::com::sun::star::uno::RuntimeException); ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleChild( sal_Int32 i ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleParent( ) throw (::com::sun::star::uno::RuntimeException); sal_Int32 SAL_CALL getAccessibleIndexInParent( ) throw (::com::sun::star::uno::RuntimeException); sal_Int16 SAL_CALL getAccessibleRole( ) throw (::com::sun::star::uno::RuntimeException); ::rtl::OUString SAL_CALL getAccessibleDescription( ) throw (::com::sun::star::uno::RuntimeException); ::rtl::OUString SAL_CALL getAccessibleName( ) throw (::com::sun::star::uno::RuntimeException); ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessibleRelationSet > SAL_CALL getAccessibleRelationSet( ) throw (::com::sun::star::uno::RuntimeException); ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessibleStateSet > SAL_CALL getAccessibleStateSet( ) throw (::com::sun::star::uno::RuntimeException); ::com::sun::star::lang::Locale SAL_CALL getLocale( ) throw (::drafts::com::sun::star::accessibility::IllegalAccessibleComponentStateException, ::com::sun::star::uno::RuntimeException); // ::drafts::com::sun::star::accessibility::XAccessibleComponent ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleAt( const ::com::sun::star::awt::Point& aPoint ) throw (::com::sun::star::uno::RuntimeException); ::com::sun::star::awt::Point SAL_CALL getLocationOnScreen( ) throw (::com::sun::star::uno::RuntimeException); void SAL_CALL grabFocus( ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getForeground( ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getBackground( ) throw (::com::sun::star::uno::RuntimeException); // ::drafts::com::sun::star::accessibility::XAccessibleExtendedComponent virtual ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFont > SAL_CALL getFont( ) throw (::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getTitledBorderText( ) throw (::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getToolTipText( ) throw (::com::sun::star::uno::RuntimeException); protected: // base class overridables ::com::sun::star::awt::Rectangle SAL_CALL implGetBounds( ) throw (::com::sun::star::uno::RuntimeException); private: /** we may be reparented (if external components use OAccessibleImplementationAccess base class), so this method here returns the parent in the VCL world, in opposite to the parent an external component gave us @precond the caller must ensure thread safety, i.e. our mutex must be locked */ ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible > getVclParent() const; }; /* ---------------------------------------------------------- Accessibility only for the Window hierarchy! Maybe derived classes must overwrite these Accessibility interfaces: // XAccessibleContext: sal_Int16 getAccessibleRole() => VCL Window::GetAccessibleRole() OUString getAccessibleDescription() => VCL Window::GetAccessibleDescription OUString getAccessibleName() => VCL Window::GetAccessibleText() => Most windows return Window::GetText() Reference< XAccessibleRelationSet > getAccessibleRelationSet() Reference< XAccessibleStateSet > getAccessibleStateSet() => overload FillAccessibleStateSet( ... ) ---------------------------------------------------------- */ #endif // _TOOLKIT_AWT_VCLXACCESSIBLECOMPONENT_HXX_ <commit_msg>INTEGRATION: CWS uaa02 (1.21.2); FILE MERGED 2003/04/11 17:25:30 mt 1.21.2.1: #108656# Moved accessibility from drafts to final<commit_after>/************************************************************************* * * $RCSfile: vclxaccessiblecomponent.hxx,v $ * * $Revision: 1.22 $ * * last change: $Author: vg $ $Date: 2003-04-24 16:17:00 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _TOOLKIT_AWT_VCLXACCESSIBLECOMPONENT_HXX_ #define _TOOLKIT_AWT_VCLXACCESSIBLECOMPONENT_HXX_ #ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLE_HPP_ #include <com/sun/star/accessibility/XAccessible.hpp> #endif #ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLECONTEXT_HPP_ #include <com/sun/star/accessibility/XAccessibleContext.hpp> #endif #ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLEEXTENDEDCOMPONENT_HPP_ #include <com/sun/star/accessibility/XAccessibleExtendedComponent.hpp> #endif #ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLEEVENTBROADCASTER_HPP_ #include <com/sun/star/accessibility/XAccessibleEventBroadcaster.hpp> #endif #ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_ #include <com/sun/star/awt/XWindow.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _CPPUHELPER_COMPBASE3_HXX_ #include <cppuhelper/compbase3.hxx> #endif #ifndef _CPPUHELPER_IMPLBASE1_HXX_ #include <cppuhelper/implbase1.hxx> #endif #ifndef COMPHELPER_ACCIMPLACCESS_HXX #include <comphelper/accimplaccess.hxx> #endif #ifndef COMPHELPER_ACCESSIBLE_COMPONENT_HELPER_HXX #include <comphelper/accessiblecomponenthelper.hxx> #endif #include <tools/gen.hxx> // Size #include <tools/link.hxx> // Size class Window; class VCLXWindow; class VclSimpleEvent; class VclWindowEvent; namespace utl { class AccessibleRelationSetHelper; class AccessibleStateSetHelper; } // ---------------------------------------------------- // class VCLXAccessibleComponent // ---------------------------------------------------- typedef ::comphelper::OAccessibleExtendedComponentHelper AccessibleExtendedComponentHelper_BASE; typedef ::cppu::ImplHelper1< ::com::sun::star::lang::XServiceInfo > VCLXAccessibleComponent_BASE; class VCLExternalSolarLock; class VCLXAccessibleComponent :public AccessibleExtendedComponentHelper_BASE ,public ::comphelper::OAccessibleImplementationAccess ,public VCLXAccessibleComponent_BASE { private: ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow> mxWindow; VCLXWindow* mpVCLXindow; ULONG nDummy1; ULONG nDummy2; void* pDummy1; VCLExternalSolarLock* m_pSolarLock; protected: DECL_LINK( WindowEventListener, VclSimpleEvent* ); DECL_LINK( WindowChildEventListener, VclSimpleEvent* ); virtual void ProcessWindowEvent( const VclWindowEvent& rVclWindowEvent ); virtual void ProcessWindowChildEvent( const VclWindowEvent& rVclWindowEvent ); virtual void FillAccessibleRelationSet( utl::AccessibleRelationSetHelper& rRelationSet ); virtual void FillAccessibleStateSet( utl::AccessibleStateSetHelper& rStateSet ); virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > GetChildAccessible( const VclWindowEvent& rVclWindowEvent ); public: VCLXAccessibleComponent( VCLXWindow* pVCLXindow ); ~VCLXAccessibleComponent(); VCLXWindow* GetVCLXWindow() const { return mpVCLXindow; } Window* GetWindow() const; virtual void SAL_CALL disposing(); // ::com::sun::star::uno::XInterface DECLARE_XINTERFACE() // ::com::sun::star::lang::XTypeProvider DECLARE_XTYPEPROVIDER() // XServiceInfo virtual ::rtl::OUString SAL_CALL getImplementationName() throw (::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& rServiceName ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw (::com::sun::star::uno::RuntimeException); // ::com::sun::star::accessibility::XAccessibleContext sal_Int32 SAL_CALL getAccessibleChildCount( ) throw (::com::sun::star::uno::RuntimeException); ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleChild( sal_Int32 i ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleParent( ) throw (::com::sun::star::uno::RuntimeException); sal_Int32 SAL_CALL getAccessibleIndexInParent( ) throw (::com::sun::star::uno::RuntimeException); sal_Int16 SAL_CALL getAccessibleRole( ) throw (::com::sun::star::uno::RuntimeException); ::rtl::OUString SAL_CALL getAccessibleDescription( ) throw (::com::sun::star::uno::RuntimeException); ::rtl::OUString SAL_CALL getAccessibleName( ) throw (::com::sun::star::uno::RuntimeException); ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleRelationSet > SAL_CALL getAccessibleRelationSet( ) throw (::com::sun::star::uno::RuntimeException); ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleStateSet > SAL_CALL getAccessibleStateSet( ) throw (::com::sun::star::uno::RuntimeException); ::com::sun::star::lang::Locale SAL_CALL getLocale( ) throw (::com::sun::star::accessibility::IllegalAccessibleComponentStateException, ::com::sun::star::uno::RuntimeException); // ::com::sun::star::accessibility::XAccessibleComponent ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleAtPoint( const ::com::sun::star::awt::Point& aPoint ) throw (::com::sun::star::uno::RuntimeException); ::com::sun::star::awt::Point SAL_CALL getLocationOnScreen( ) throw (::com::sun::star::uno::RuntimeException); void SAL_CALL grabFocus( ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getForeground( ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getBackground( ) throw (::com::sun::star::uno::RuntimeException); // ::com::sun::star::accessibility::XAccessibleExtendedComponent virtual ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFont > SAL_CALL getFont( ) throw (::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getTitledBorderText( ) throw (::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getToolTipText( ) throw (::com::sun::star::uno::RuntimeException); protected: // base class overridables ::com::sun::star::awt::Rectangle SAL_CALL implGetBounds( ) throw (::com::sun::star::uno::RuntimeException); private: /** we may be reparented (if external components use OAccessibleImplementationAccess base class), so this method here returns the parent in the VCL world, in opposite to the parent an external component gave us @precond the caller must ensure thread safety, i.e. our mutex must be locked */ ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > getVclParent() const; }; /* ---------------------------------------------------------- Accessibility only for the Window hierarchy! Maybe derived classes must overwrite these Accessibility interfaces: // XAccessibleContext: sal_Int16 getAccessibleRole() => VCL Window::GetAccessibleRole() OUString getAccessibleDescription() => VCL Window::GetAccessibleDescription OUString getAccessibleName() => VCL Window::GetAccessibleText() => Most windows return Window::GetText() Reference< XAccessibleRelationSet > getAccessibleRelationSet() Reference< XAccessibleStateSet > getAccessibleStateSet() => overload FillAccessibleStateSet( ... ) ---------------------------------------------------------- */ #endif // _TOOLKIT_AWT_VCLXACCESSIBLECOMPONENT_HXX_ <|endoftext|>
<commit_before>#include "Hardware.h" #define PIN_LED_R 14 #define PIN_LED_G 13 #define PIN_LED_B 10 #define PIN_MOTOR_I_PWM 22 #define PIN_MOTOR_I_DIR 27 #define PIN_MOTOR_J_PWM 24 #define PIN_MOTOR_J_DIR 28 #define PIN_MOTOR_K_PWM 25 #define PIN_MOTOR_K_DIR 29 #define PIN_LINE_LED 12 const int Hardware::LINE_SENSORS[] = {6,7,5,3,4,2,0,1}; Hardware::Hardware() { wiringPiSetup(); /// initialize LED software pwms softPwmCreate(PIN_LED_R,0,255); softPwmCreate(PIN_LED_G,0,255); softPwmCreate(PIN_LED_B,0,255); /// initialize motor software pwms softPwmCreate(PIN_MOTOR_I_PWM,0,100); softPwmCreate(PIN_MOTOR_J_PWM,0,100); softPwmCreate(PIN_MOTOR_K_PWM,0,100); /// initialize motor direction outputs pinMode(PIN_MOTOR_I_DIR,OUTPUT); pinMode(PIN_MOTOR_J_DIR,OUTPUT); pinMode(PIN_MOTOR_K_DIR,OUTPUT); // initialize line sensor array LED pinMode(PIN_LINE_LED,OUTPUT); // open serial line serialFileDesc = serialOpen("/dev/ttyAMA0",115200); } void Hardware::setLED(int r, int g, int b) { softPwmWrite(PIN_LED_R,r); softPwmWrite(PIN_LED_G,g); softPwmWrite(PIN_LED_B,b); } int Hardware::readLine() { digitalWrite(PIN_LINE_LED,1); usleep(200); long long longest = 0; int longPin = 0; for (int i=0; i<8; i++) { long long iTime = (readLineSensor(LINE_SENSORS[i]) + readLineSensor(LINE_SENSORS[i]))/2; if (iTime > longest) { longest = iTime; longPin = i; } } return longPin; } long long Hardware::readLineSensor(int i) { pinMode(i,OUTPUT); digitalWrite(i,1); usleep(10); pinMode(i,INPUT); pullUpDnControl(i,PUD_OFF); auto start = std::chrono::high_resolution_clock::now(); while (digitalRead(i)); auto elapsed = std::chrono::high_resolution_clock::now() - start; return std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count(); } void Hardware::goHolonomic(int x, int y, int r) { double i = y*sqrt(3)/2 + x/2 + r; double j = y*sqrt(3)/2 - x/2 - r; double k = x - r; double coef = 100.0/(((i>j)?i:j)>k?((i>j)?i:j):k); setMotors(i*coef,j*coef,k*coef); } void Hardware::setMotors(int i, int j, int k) { digitalWrite(PIN_MOTOR_I_DIR,i>0); softPwmWrite(PIN_MOTOR_I_PWM,abs(i)); digitalWrite(PIN_MOTOR_J_DIR,j>0); softPwmWrite(PIN_MOTOR_J_PWM,abs(j)); digitalWrite(PIN_MOTOR_K_DIR,k>0); softPwmWrite(PIN_MOTOR_K_PWM,abs(k)); } void Hardware::getZX(int& z, int& x) { while (serialGetchar(serialFileDesc) != 0xFA); x = serialGetChar(serialFileDesc); while (serialGetchar(serialFileDesc) != 0xFB); z = serialGetChar(serialFileDesc); } Hardware::~Hardware() { setLED(0,0,0); setMotors(0,0,0); digitalWrite(PIN_LINE_LED,0); serialClose(serialFileDesc); usleep(100000); } <commit_msg>fixed weird caps<commit_after>#include "Hardware.h" #define PIN_LED_R 14 #define PIN_LED_G 13 #define PIN_LED_B 10 #define PIN_MOTOR_I_PWM 22 #define PIN_MOTOR_I_DIR 27 #define PIN_MOTOR_J_PWM 24 #define PIN_MOTOR_J_DIR 28 #define PIN_MOTOR_K_PWM 25 #define PIN_MOTOR_K_DIR 29 #define PIN_LINE_LED 12 const int Hardware::LINE_SENSORS[] = {6,7,5,3,4,2,0,1}; Hardware::Hardware() { wiringPiSetup(); /// initialize LED software pwms softPwmCreate(PIN_LED_R,0,255); softPwmCreate(PIN_LED_G,0,255); softPwmCreate(PIN_LED_B,0,255); /// initialize motor software pwms softPwmCreate(PIN_MOTOR_I_PWM,0,100); softPwmCreate(PIN_MOTOR_J_PWM,0,100); softPwmCreate(PIN_MOTOR_K_PWM,0,100); /// initialize motor direction outputs pinMode(PIN_MOTOR_I_DIR,OUTPUT); pinMode(PIN_MOTOR_J_DIR,OUTPUT); pinMode(PIN_MOTOR_K_DIR,OUTPUT); // initialize line sensor array LED pinMode(PIN_LINE_LED,OUTPUT); // open serial line serialFileDesc = serialOpen("/dev/ttyAMA0",115200); } void Hardware::setLED(int r, int g, int b) { softPwmWrite(PIN_LED_R,r); softPwmWrite(PIN_LED_G,g); softPwmWrite(PIN_LED_B,b); } int Hardware::readLine() { digitalWrite(PIN_LINE_LED,1); usleep(200); long long longest = 0; int longPin = 0; for (int i=0; i<8; i++) { long long iTime = (readLineSensor(LINE_SENSORS[i]) + readLineSensor(LINE_SENSORS[i]))/2; if (iTime > longest) { longest = iTime; longPin = i; } } return longPin; } long long Hardware::readLineSensor(int i) { pinMode(i,OUTPUT); digitalWrite(i,1); usleep(10); pinMode(i,INPUT); pullUpDnControl(i,PUD_OFF); auto start = std::chrono::high_resolution_clock::now(); while (digitalRead(i)); auto elapsed = std::chrono::high_resolution_clock::now() - start; return std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count(); } void Hardware::goHolonomic(int x, int y, int r) { double i = y*sqrt(3)/2 + x/2 + r; double j = y*sqrt(3)/2 - x/2 - r; double k = x - r; double coef = 100.0/(((i>j)?i:j)>k?((i>j)?i:j):k); setMotors(i*coef,j*coef,k*coef); } void Hardware::setMotors(int i, int j, int k) { digitalWrite(PIN_MOTOR_I_DIR,i>0); softPwmWrite(PIN_MOTOR_I_PWM,abs(i)); digitalWrite(PIN_MOTOR_J_DIR,j>0); softPwmWrite(PIN_MOTOR_J_PWM,abs(j)); digitalWrite(PIN_MOTOR_K_DIR,k>0); softPwmWrite(PIN_MOTOR_K_PWM,abs(k)); } void Hardware::getZX(int& z, int& x) { while (serialGetchar(serialFileDesc) != 0xFA); x = serialGetchar(serialFileDesc); while (serialGetchar(serialFileDesc) != 0xFB); z = serialGetchar(serialFileDesc); } Hardware::~Hardware() { setLED(0,0,0); setMotors(0,0,0); digitalWrite(PIN_LINE_LED,0); serialClose(serialFileDesc); usleep(100000); } <|endoftext|>
<commit_before>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2008 Patrick Spendrin <ps_ml@gmx.de> // #include <QtTest/QtTest> #include "MarbleDirs.h" #include "PluginManager.h" namespace Marble { class PluginManagerTest : public QObject { Q_OBJECT private slots: void loadPlugins(); }; void PluginManagerTest::loadPlugins() { MarbleDirs::setMarbleDataPath( DATA_PATH ); MarbleDirs::setMarblePluginPath( PLUGIN_PATH ); int pluginNumber = MarbleDirs::pluginEntryList( "", QDir::Files ).size(); PluginManager *pm = new PluginManager( 0 ); QCOMPARE( pm->createRenderPlugins().size(), pluginNumber ); } } QTEST_MAIN( Marble::PluginManagerTest ) #include "PluginManagerTest.moc" <commit_msg>PluginManagerTest: fix number of plugins<commit_after>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2008 Patrick Spendrin <ps_ml@gmx.de> // #include <QtTest/QtTest> #include "MarbleDirs.h" #include "PluginManager.h" namespace Marble { class PluginManagerTest : public QObject { Q_OBJECT private slots: void loadPlugins(); }; void PluginManagerTest::loadPlugins() { MarbleDirs::setMarbleDataPath( DATA_PATH ); MarbleDirs::setMarblePluginPath( PLUGIN_PATH ); int pluginNumber = MarbleDirs::pluginEntryList( "", QDir::Files ).size(); PluginManager *pm = new PluginManager( 0 ); int renderPlugins = pm->createRenderPlugins().size(); int networkPlugins = pm->createNetworkPlugins().size(); int positionPlugins = pm->createPositionProviderPlugins().size(); int runnerPlugins = pm->runnerPlugins().size(); QCOMPARE( renderPlugins + networkPlugins + positionPlugins + runnerPlugins, pluginNumber ); } } QTEST_MAIN( Marble::PluginManagerTest ) #include "PluginManagerTest.moc" <|endoftext|>
<commit_before>/************************************************************************* * * * Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith. * * All rights reserved. Email: russ@q12.org Web: www.q12.org * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of EITHER: * * (1) 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. The text of the GNU Lesser * * General Public License is included with this library in the * * file LICENSE.TXT. * * (2) The BSD-style license that is included with this library in * * the file LICENSE-BSD.TXT. * * * * 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 files * * LICENSE.TXT and LICENSE-BSD.TXT for more details. * * * *************************************************************************/ #include <ode/config.h> #include <ode/mass.h> #include <ode/odemath.h> #include <ode/matrix.h> #define _I(i,j) I[(i)*4+(j)] // return 1 if ok, 0 if bad static int checkMass (dMass *m) { int i; if (m->mass <= 0) { dDEBUGMSG ("mass must be > 0"); return 0; } if (!dIsPositiveDefinite (m->I,3)) { dDEBUGMSG ("inertia must be positive definite"); return 0; } // verify that the center of mass position is consistent with the mass // and inertia matrix. this is done by checking that the inertia around // the center of mass is also positive definite. from the comment in // dMassTranslate(), if the body is translated so that its center of mass // is at the point of reference, then the new inertia is: // I + mass*crossmat(c)^2 // note that requiring this to be positive definite is exactly equivalent // to requiring that the spatial inertia matrix // [ mass*eye(3,3) M*crossmat(c)^T ] // [ M*crossmat(c) I ] // is positive definite, given that I is PD and mass>0. see the theorem // about partitioned PD matrices for proof. dMatrix3 I2,chat; dSetZero (chat,12); dCROSSMAT (chat,m->c,4,+,-); dMULTIPLY0_333 (I2,chat,chat); for (i=0; i<3; i++) I2[i] = m->I[i] + m->mass*I2[i]; for (i=4; i<7; i++) I2[i] = m->I[i] + m->mass*I2[i]; for (i=8; i<11; i++) I2[i] = m->I[i] + m->mass*I2[i]; if (!dIsPositiveDefinite (I2,3)) { dDEBUGMSG ("center of mass inconsistent with mass parameters"); return 0; } return 1; } void dMassSetZero (dMass *m) { dAASSERT (m); m->mass = REAL(0.0); dSetZero (m->c,sizeof(m->c) / sizeof(dReal)); dSetZero (m->I,sizeof(m->I) / sizeof(dReal)); } void dMassSetParameters (dMass *m, dReal themass, dReal cgx, dReal cgy, dReal cgz, dReal I11, dReal I22, dReal I33, dReal I12, dReal I13, dReal I23) { dAASSERT (m); dMassSetZero (m); m->mass = themass; m->c[0] = cgx; m->c[1] = cgy; m->c[2] = cgz; m->_I(0,0) = I11; m->_I(1,1) = I22; m->_I(2,2) = I33; m->_I(0,1) = I12; m->_I(0,2) = I13; m->_I(1,2) = I23; m->_I(1,0) = I12; m->_I(2,0) = I13; m->_I(2,1) = I23; checkMass (m); } void dMassSetSphere (dMass *m, dReal density, dReal radius) { dAASSERT (m); dMassSetZero (m); m->mass = (REAL(4.0)/REAL(3.0)) * M_PI * radius*radius*radius * density; dReal II = REAL(0.4) * m->mass * radius*radius; m->_I(0,0) = II; m->_I(1,1) = II; m->_I(2,2) = II; # ifndef dNODEBUG checkMass (m); # endif } void dMassSetCappedCylinder (dMass *m, dReal density, int direction, dReal a, dReal b) { dReal M1,M2,Ia,Ib; dAASSERT (m); dUASSERT (direction >= 1 && direction <= 3,"bad direction number"); dMassSetZero (m); M1 = M_PI*a*a*b*density; // cylinder mass M2 = (REAL(4.0)/REAL(3.0))*M_PI*a*a*a*density; // total cap mass m->mass = M1+M2; Ia = M1*(REAL(0.25)*a*a + (REAL(1.0)/REAL(12.0))*b*b) + M2*(REAL(0.4)*a*a + REAL(0.5)*b*b); Ib = (M1*REAL(0.5) + M2*REAL(0.4))*a*a; m->_I(0,0) = Ia; m->_I(1,1) = Ia; m->_I(2,2) = Ia; m->_I(direction-1,direction-1) = Ib; # ifndef dNODEBUG checkMass (m); # endif } void dMassSetCylinder (dMass *m, dReal density, int direction, dReal radius, dReal length) { dReal M,r2,I; dAASSERT (m); dMassSetZero (m); r2 = radius*radius; M = M_PI*r2*length*density; // cylinder mass m->mass = M; I = M*(REAL(0.25)*r2 + (REAL(1.0)/REAL(12.0))*length*length); m->_I(0,0) = I; m->_I(1,1) = I; m->_I(2,2) = I; m->_I(direction-1,direction-1) = M*REAL(0.5)*r2; # ifndef dNODEBUG checkMass (m); # endif } void dMassSetBox (dMass *m, dReal density, dReal lx, dReal ly, dReal lz) { dMassSetBoxTotal(m, lx*ly*lz*density, lx, ly, lz); } void dMassSetBoxTotal (dMass *m, dReal total_mass, dReal lx, dReal ly, dReal lz) { dAASSERT (m); dMassSetZero (m); m->mass = total_mass; m->_I(0,0) = total_mass/REAL(12.0) * (ly*ly + lz*lz); m->_I(1,1) = total_mass/REAL(12.0) * (lx*lx + lz*lz); m->_I(2,2) = total_mass/REAL(12.0) * (lx*lx + ly*ly); # ifndef dNODEBUG checkMass (m); # endif } void dMassAdjust (dMass *m, dReal newmass) { dAASSERT (m); dReal scale = newmass / m->mass; m->mass = newmass; for (int i=0; i<3; i++) for (int j=0; j<3; j++) m->_I(i,j) *= scale; # ifndef dNODEBUG checkMass (m); # endif } void dMassTranslate (dMass *m, dReal x, dReal y, dReal z) { // if the body is translated by `a' relative to its point of reference, // the new inertia about the point of reference is: // // I + mass*(crossmat(c)^2 - crossmat(c+a)^2) // // where c is the existing center of mass and I is the old inertia. int i,j; dMatrix3 ahat,chat,t1,t2; dReal a[3]; dAASSERT (m); // adjust inertia matrix dSetZero (chat,12); dCROSSMAT (chat,m->c,4,+,-); a[0] = x + m->c[0]; a[1] = y + m->c[1]; a[2] = z + m->c[2]; dSetZero (ahat,12); dCROSSMAT (ahat,a,4,+,-); dMULTIPLY0_333 (t1,ahat,ahat); dMULTIPLY0_333 (t2,chat,chat); for (i=0; i<3; i++) for (j=0; j<3; j++) m->_I(i,j) += m->mass * (t2[i*4+j]-t1[i*4+j]); // ensure perfect symmetry m->_I(1,0) = m->_I(0,1); m->_I(2,0) = m->_I(0,2); m->_I(2,1) = m->_I(1,2); // adjust center of mass m->c[0] += x; m->c[1] += y; m->c[2] += z; # ifndef dNODEBUG checkMass (m); # endif } void dMassRotate (dMass *m, const dMatrix3 R) { // if the body is rotated by `R' relative to its point of reference, // the new inertia about the point of reference is: // // R * I * R' // // where I is the old inertia. dMatrix3 t1; dReal t2[3]; dAASSERT (m); // rotate inertia matrix dMULTIPLY2_333 (t1,m->I,R); dMULTIPLY0_333 (m->I,R,t1); // ensure perfect symmetry m->_I(1,0) = m->_I(0,1); m->_I(2,0) = m->_I(0,2); m->_I(2,1) = m->_I(1,2); // rotate center of mass dMULTIPLY0_331 (t2,R,m->c); m->c[0] = t2[0]; m->c[1] = t2[1]; m->c[2] = t2[2]; # ifndef dNODEBUG checkMass (m); # endif } void dMassAdd (dMass *a, const dMass *b) { int i; dAASSERT (a && b); dReal denom = dRecip (a->mass + b->mass); for (i=0; i<3; i++) a->c[i] = (a->c[i]*a->mass + b->c[i]*b->mass)*denom; a->mass += b->mass; for (i=0; i<12; i++) a->I[i] += b->I[i]; } <commit_msg>minor formatting changes<commit_after>/************************************************************************* * * * Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith. * * All rights reserved. Email: russ@q12.org Web: www.q12.org * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of EITHER: * * (1) 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. The text of the GNU Lesser * * General Public License is included with this library in the * * file LICENSE.TXT. * * (2) The BSD-style license that is included with this library in * * the file LICENSE-BSD.TXT. * * * * 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 files * * LICENSE.TXT and LICENSE-BSD.TXT for more details. * * * *************************************************************************/ #include <ode/config.h> #include <ode/mass.h> #include <ode/odemath.h> #include <ode/matrix.h> #define _I(i,j) I[(i)*4+(j)] // return 1 if ok, 0 if bad static int checkMass (dMass *m) { int i; if (m->mass <= 0) { dDEBUGMSG ("mass must be > 0"); return 0; } if (!dIsPositiveDefinite (m->I,3)) { dDEBUGMSG ("inertia must be positive definite"); return 0; } // verify that the center of mass position is consistent with the mass // and inertia matrix. this is done by checking that the inertia around // the center of mass is also positive definite. from the comment in // dMassTranslate(), if the body is translated so that its center of mass // is at the point of reference, then the new inertia is: // I + mass*crossmat(c)^2 // note that requiring this to be positive definite is exactly equivalent // to requiring that the spatial inertia matrix // [ mass*eye(3,3) M*crossmat(c)^T ] // [ M*crossmat(c) I ] // is positive definite, given that I is PD and mass>0. see the theorem // about partitioned PD matrices for proof. dMatrix3 I2,chat; dSetZero (chat,12); dCROSSMAT (chat,m->c,4,+,-); dMULTIPLY0_333 (I2,chat,chat); for (i=0; i<3; i++) I2[i] = m->I[i] + m->mass*I2[i]; for (i=4; i<7; i++) I2[i] = m->I[i] + m->mass*I2[i]; for (i=8; i<11; i++) I2[i] = m->I[i] + m->mass*I2[i]; if (!dIsPositiveDefinite (I2,3)) { dDEBUGMSG ("center of mass inconsistent with mass parameters"); return 0; } return 1; } void dMassSetZero (dMass *m) { dAASSERT (m); m->mass = REAL(0.0); dSetZero (m->c,sizeof(m->c) / sizeof(dReal)); dSetZero (m->I,sizeof(m->I) / sizeof(dReal)); } void dMassSetParameters (dMass *m, dReal themass, dReal cgx, dReal cgy, dReal cgz, dReal I11, dReal I22, dReal I33, dReal I12, dReal I13, dReal I23) { dAASSERT (m); dMassSetZero (m); m->mass = themass; m->c[0] = cgx; m->c[1] = cgy; m->c[2] = cgz; m->_I(0,0) = I11; m->_I(1,1) = I22; m->_I(2,2) = I33; m->_I(0,1) = I12; m->_I(0,2) = I13; m->_I(1,2) = I23; m->_I(1,0) = I12; m->_I(2,0) = I13; m->_I(2,1) = I23; checkMass (m); } void dMassSetSphere (dMass *m, dReal density, dReal radius) { dAASSERT (m); dMassSetZero (m); m->mass = (REAL(4.0)/REAL(3.0)) * M_PI * radius*radius*radius * density; dReal II = REAL(0.4) * m->mass * radius*radius; m->_I(0,0) = II; m->_I(1,1) = II; m->_I(2,2) = II; # ifndef dNODEBUG checkMass (m); # endif } void dMassSetCappedCylinder (dMass *m, dReal density, int direction, dReal a, dReal b) { dReal M1,M2,Ia,Ib; dAASSERT (m); dUASSERT (direction >= 1 && direction <= 3,"bad direction number"); dMassSetZero (m); M1 = M_PI*a*a*b*density; // cylinder mass M2 = (REAL(4.0)/REAL(3.0))*M_PI*a*a*a*density; // total cap mass m->mass = M1+M2; Ia = M1*(REAL(0.25)*a*a + (REAL(1.0)/REAL(12.0))*b*b) + M2*(REAL(0.4)*a*a + REAL(0.5)*b*b); Ib = (M1*REAL(0.5) + M2*REAL(0.4))*a*a; m->_I(0,0) = Ia; m->_I(1,1) = Ia; m->_I(2,2) = Ia; m->_I(direction-1,direction-1) = Ib; # ifndef dNODEBUG checkMass (m); # endif } void dMassSetCylinder (dMass *m, dReal density, int direction, dReal radius, dReal length) { dReal M,r2,I; dAASSERT (m); dMassSetZero (m); r2 = radius*radius; M = M_PI*r2*length*density; // cylinder mass m->mass = M; I = M*(REAL(0.25)*r2 + (REAL(1.0)/REAL(12.0))*length*length); m->_I(0,0) = I; m->_I(1,1) = I; m->_I(2,2) = I; m->_I(direction-1,direction-1) = M*REAL(0.5)*r2; # ifndef dNODEBUG checkMass (m); # endif } void dMassSetBox (dMass *m, dReal density, dReal lx, dReal ly, dReal lz) { dMassSetBoxTotal (m, lx*ly*lz*density, lx, ly, lz); } void dMassSetBoxTotal (dMass *m, dReal total_mass, dReal lx, dReal ly, dReal lz) { dAASSERT (m); dMassSetZero (m); m->mass = total_mass; m->_I(0,0) = total_mass/REAL(12.0) * (ly*ly + lz*lz); m->_I(1,1) = total_mass/REAL(12.0) * (lx*lx + lz*lz); m->_I(2,2) = total_mass/REAL(12.0) * (lx*lx + ly*ly); # ifndef dNODEBUG checkMass (m); # endif } void dMassAdjust (dMass *m, dReal newmass) { dAASSERT (m); dReal scale = newmass / m->mass; m->mass = newmass; for (int i=0; i<3; i++) for (int j=0; j<3; j++) m->_I(i,j) *= scale; # ifndef dNODEBUG checkMass (m); # endif } void dMassTranslate (dMass *m, dReal x, dReal y, dReal z) { // if the body is translated by `a' relative to its point of reference, // the new inertia about the point of reference is: // // I + mass*(crossmat(c)^2 - crossmat(c+a)^2) // // where c is the existing center of mass and I is the old inertia. int i,j; dMatrix3 ahat,chat,t1,t2; dReal a[3]; dAASSERT (m); // adjust inertia matrix dSetZero (chat,12); dCROSSMAT (chat,m->c,4,+,-); a[0] = x + m->c[0]; a[1] = y + m->c[1]; a[2] = z + m->c[2]; dSetZero (ahat,12); dCROSSMAT (ahat,a,4,+,-); dMULTIPLY0_333 (t1,ahat,ahat); dMULTIPLY0_333 (t2,chat,chat); for (i=0; i<3; i++) for (j=0; j<3; j++) m->_I(i,j) += m->mass * (t2[i*4+j]-t1[i*4+j]); // ensure perfect symmetry m->_I(1,0) = m->_I(0,1); m->_I(2,0) = m->_I(0,2); m->_I(2,1) = m->_I(1,2); // adjust center of mass m->c[0] += x; m->c[1] += y; m->c[2] += z; # ifndef dNODEBUG checkMass (m); # endif } void dMassRotate (dMass *m, const dMatrix3 R) { // if the body is rotated by `R' relative to its point of reference, // the new inertia about the point of reference is: // // R * I * R' // // where I is the old inertia. dMatrix3 t1; dReal t2[3]; dAASSERT (m); // rotate inertia matrix dMULTIPLY2_333 (t1,m->I,R); dMULTIPLY0_333 (m->I,R,t1); // ensure perfect symmetry m->_I(1,0) = m->_I(0,1); m->_I(2,0) = m->_I(0,2); m->_I(2,1) = m->_I(1,2); // rotate center of mass dMULTIPLY0_331 (t2,R,m->c); m->c[0] = t2[0]; m->c[1] = t2[1]; m->c[2] = t2[2]; # ifndef dNODEBUG checkMass (m); # endif } void dMassAdd (dMass *a, const dMass *b) { int i; dAASSERT (a && b); dReal denom = dRecip (a->mass + b->mass); for (i=0; i<3; i++) a->c[i] = (a->c[i]*a->mass + b->c[i]*b->mass)*denom; a->mass += b->mass; for (i=0; i<12; i++) a->I[i] += b->I[i]; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: evaluation.hxx,v $ * * $Revision: 1.1 $ * * last change: $Author: cd $ $Date: 2002-11-01 09:43:28 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SOCOMP_EVALUATION_HXX_ #define _SOCOMP_EVALUATION_HXX_ #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_UNO_EXCEPTION_HPP_ #include <com/sun/star/uno/Exception.hpp> #endif #ifndef _COM_SUN_STAR_UNO_REFERENCE_H_ #include <com/sun/star/uno/Reference.h> #endif #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_ #include <com/sun/star/lang/XEventListener.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XEXACTNAME_HPP_ #include <com/sun/star/beans/XExactName.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XMATERIALHOLDER_HPP_ #include <com/sun/star/beans/XMaterialHolder.hpp> #endif #ifndef _CPPUHELPER_IMPLBASE4_HXX_ #include <cppuhelper/implbase4.hxx> #endif #ifndef _CPPUHELPER_INTERFACECONTAINER_H_ #include <cppuhelper/interfacecontainer.h> #endif #include <com/sun/star/lang/XSingleServiceFactory.hpp> #include <osl/mutex.hxx> using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::beans; class SOEvaluation : public ::cppu::WeakImplHelper4< XExactName, XMaterialHolder, XComponent, XServiceInfo > { ::osl::Mutex m_aMutex; ::cppu::OInterfaceContainerHelper m_aListeners; Reference< XMultiServiceFactory > m_xServiceManager; public: SOEvaluation( const Reference < XMultiServiceFactory >& xFactory ); virtual ~SOEvaluation(); static Reference< XSingleServiceFactory > GetSOEvaluationFactory( Reference< XMultiServiceFactory > & xSMgr ); static ::rtl::OUString GetImplementationName(); static Sequence< rtl::OUString > GetSupportedServiceNames(); // XComponent virtual void SAL_CALL dispose() throw ( RuntimeException ); virtual void SAL_CALL addEventListener( const Reference< XEventListener > & aListener) throw ( RuntimeException ); virtual void SAL_CALL removeEventListener(const Reference< XEventListener > & aListener) throw ( RuntimeException ); // XExactName virtual rtl::OUString SAL_CALL getExactName( const rtl::OUString& rApproximateName ) throw ( RuntimeException ); // XMaterialHolder virtual Any SAL_CALL getMaterial() throw ( RuntimeException ); // XServiceInfo virtual ::rtl::OUString SAL_CALL getImplementationName() throw ( RuntimeException ); virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& rServiceName ) throw ( RuntimeException ); virtual Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw ( RuntimeException ); }; #endif // _SOCOMP_EVALUATION_HXX_ <commit_msg>INTEGRATION: CWS mav4 (1.1.90); FILE MERGED 2003/04/09 15:30:59 lo 1.1.90.1: #108766# force dependency for makefile change<commit_after>/************************************************************************* * * $RCSfile: evaluation.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2003-04-24 13:35:57 $ * * 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): _______________________________________ * * ************************************************************************/ /* makefile.mk changed 20030409, LO */ #ifndef _SOCOMP_EVALUATION_HXX_ #define _SOCOMP_EVALUATION_HXX_ #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_UNO_EXCEPTION_HPP_ #include <com/sun/star/uno/Exception.hpp> #endif #ifndef _COM_SUN_STAR_UNO_REFERENCE_H_ #include <com/sun/star/uno/Reference.h> #endif #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_ #include <com/sun/star/lang/XEventListener.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XEXACTNAME_HPP_ #include <com/sun/star/beans/XExactName.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XMATERIALHOLDER_HPP_ #include <com/sun/star/beans/XMaterialHolder.hpp> #endif #ifndef _CPPUHELPER_IMPLBASE4_HXX_ #include <cppuhelper/implbase4.hxx> #endif #ifndef _CPPUHELPER_INTERFACECONTAINER_H_ #include <cppuhelper/interfacecontainer.h> #endif #include <com/sun/star/lang/XSingleServiceFactory.hpp> #include <osl/mutex.hxx> using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::beans; class SOEvaluation : public ::cppu::WeakImplHelper4< XExactName, XMaterialHolder, XComponent, XServiceInfo > { ::osl::Mutex m_aMutex; ::cppu::OInterfaceContainerHelper m_aListeners; Reference< XMultiServiceFactory > m_xServiceManager; public: SOEvaluation( const Reference < XMultiServiceFactory >& xFactory ); virtual ~SOEvaluation(); static Reference< XSingleServiceFactory > GetSOEvaluationFactory( Reference< XMultiServiceFactory > & xSMgr ); static ::rtl::OUString GetImplementationName(); static Sequence< rtl::OUString > GetSupportedServiceNames(); // XComponent virtual void SAL_CALL dispose() throw ( RuntimeException ); virtual void SAL_CALL addEventListener( const Reference< XEventListener > & aListener) throw ( RuntimeException ); virtual void SAL_CALL removeEventListener(const Reference< XEventListener > & aListener) throw ( RuntimeException ); // XExactName virtual rtl::OUString SAL_CALL getExactName( const rtl::OUString& rApproximateName ) throw ( RuntimeException ); // XMaterialHolder virtual Any SAL_CALL getMaterial() throw ( RuntimeException ); // XServiceInfo virtual ::rtl::OUString SAL_CALL getImplementationName() throw ( RuntimeException ); virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& rServiceName ) throw ( RuntimeException ); virtual Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw ( RuntimeException ); }; #endif // _SOCOMP_EVALUATION_HXX_ <|endoftext|>
<commit_before>#include "http2/adapter/header_validator.h" #include "absl/strings/escaping.h" #include "absl/strings/numbers.h" #include "common/platform/api/quiche_logging.h" namespace http2 { namespace adapter { namespace { const absl::string_view kHttp2HeaderNameAllowedChars = "!#$%&\'*+-.0123456789" "^_`abcdefghijklmnopqrstuvwxyz|~"; const absl::string_view kHttp2HeaderValueAllowedChars = "\t " "!\"#$%&'()*+,-./" "0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`" "abcdefghijklmnopqrstuvwxyz{|}~"; const absl::string_view kHttp2StatusValueAllowedChars = "0123456789"; const absl::string_view kValidAuthorityChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~%!$&'()[" "]*+,;=:"; // Returns whether `authority` contains only characters from the `host` ABNF // from RFC 3986 section 3.2.2. bool IsValidAuthority(absl::string_view authority) { static const bool* valid_chars = []() { using ValidCharArray = bool[256]; bool* chars = new ValidCharArray; memset(chars, 0, sizeof(ValidCharArray)); for (char c : kValidAuthorityChars) { chars[static_cast<uint8_t>(c)] = true; } return chars; }(); for (char c : authority) { if (!valid_chars[static_cast<uint8_t>(c)]) { return false; } } return true; } bool ValidateRequestHeaders(const std::vector<std::string>& pseudo_headers, absl::string_view method, absl::string_view path, bool allow_connect) { QUICHE_VLOG(2) << "Request pseudo-headers: [" << absl::StrJoin(pseudo_headers, ", ") << "], allow_connect: " << allow_connect << ", method: " << method << ", path: " << path; if (allow_connect && method == "CONNECT") { static const std::vector<std::string>* kConnectHeaders = new std::vector<std::string>( {":authority", ":method", ":path", ":protocol", ":scheme"}); return pseudo_headers == *kConnectHeaders; } if (path.empty()) { return false; } if (path == "*") { if (method != "OPTIONS") { return false; } } else if (path[0] != '/') { return false; } static const std::vector<std::string>* kRequiredHeaders = new std::vector<std::string>( {":authority", ":method", ":path", ":scheme"}); return pseudo_headers == *kRequiredHeaders; } bool ValidateRequestTrailers(const std::vector<std::string>& pseudo_headers) { return pseudo_headers.empty(); } bool ValidateResponseHeaders(const std::vector<std::string>& pseudo_headers) { static const std::vector<std::string>* kRequiredHeaders = new std::vector<std::string>({":status"}); return pseudo_headers == *kRequiredHeaders; } bool ValidateResponseTrailers(const std::vector<std::string>& pseudo_headers) { return pseudo_headers.empty(); } } // namespace void HeaderValidator::StartHeaderBlock() { pseudo_headers_.clear(); status_.clear(); method_.clear(); path_.clear(); content_length_.reset(); } HeaderValidator::HeaderStatus HeaderValidator::ValidateSingleHeader( absl::string_view key, absl::string_view value) { if (key.empty()) { return HEADER_FIELD_INVALID; } if (max_field_size_.has_value() && key.size() + value.size() > max_field_size_.value()) { QUICHE_VLOG(2) << "Header field size is " << key.size() + value.size() << ", exceeds max size of " << max_field_size_.value(); return HEADER_FIELD_TOO_LONG; } const absl::string_view validated_key = key[0] == ':' ? key.substr(1) : key; if (validated_key.find_first_not_of(kHttp2HeaderNameAllowedChars) != absl::string_view::npos) { QUICHE_VLOG(2) << "invalid chars in header name: [" << absl::CEscape(validated_key) << "]"; return HEADER_FIELD_INVALID; } if (value.find_first_not_of(kHttp2HeaderValueAllowedChars) != absl::string_view::npos) { QUICHE_VLOG(2) << "invalid chars in header value: [" << absl::CEscape(value) << "]"; return HEADER_FIELD_INVALID; } if (key[0] == ':') { if (key == ":status") { if (value.size() != 3 || value.find_first_not_of(kHttp2StatusValueAllowedChars) != absl::string_view::npos) { QUICHE_VLOG(2) << "malformed status value: [" << absl::CEscape(value) << "]"; return HEADER_FIELD_INVALID; } if (value == "101") { // Switching protocols is not allowed on a HTTP/2 stream. return HEADER_FIELD_INVALID; } status_ = std::string(value); } else if (key == ":method") { method_ = std::string(value); } else if (key == ":authority" && !IsValidAuthority(value)) { return HEADER_FIELD_INVALID; } else if (key == ":path") { if (value.empty()) { // For now, reject an empty path regardless of scheme. return HEADER_FIELD_INVALID; } path_ = std::string(value); } pseudo_headers_.push_back(std::string(key)); } else if (key == "content-length") { const bool success = HandleContentLength(value); if (!success) { return HEADER_FIELD_INVALID; } } else if (key == "te" && value != "trailers") { return HEADER_FIELD_INVALID; } return HEADER_OK; } // Returns true if all required pseudoheaders and no extra pseudoheaders are // present for the given header type. bool HeaderValidator::FinishHeaderBlock(HeaderType type) { std::sort(pseudo_headers_.begin(), pseudo_headers_.end()); switch (type) { case HeaderType::REQUEST: return ValidateRequestHeaders(pseudo_headers_, method_, path_, allow_connect_); case HeaderType::REQUEST_TRAILER: return ValidateRequestTrailers(pseudo_headers_); case HeaderType::RESPONSE_100: case HeaderType::RESPONSE: return ValidateResponseHeaders(pseudo_headers_); case HeaderType::RESPONSE_TRAILER: return ValidateResponseTrailers(pseudo_headers_); } return false; } bool HeaderValidator::HandleContentLength(absl::string_view value) { if (value.empty()) { return false; } if (status_ == "204" && value != "0") { // There should be no body in a "204 No Content" response. return false; } if (!status_.empty() && status_[0] == '1' && value != "0") { // There should also be no body in a 1xx response. return false; } size_t content_length = 0; const bool valid = absl::SimpleAtoi(value, &content_length); if (!valid) { return false; } content_length_ = content_length; return true; } } // namespace adapter } // namespace http2 <commit_msg>Automated g4 rollback of changelist 425943183.<commit_after>#include "http2/adapter/header_validator.h" #include <array> #include "absl/strings/escaping.h" #include "absl/strings/numbers.h" #include "common/platform/api/quiche_logging.h" namespace http2 { namespace adapter { namespace { const absl::string_view kHttp2HeaderNameAllowedChars = "!#$%&\'*+-.0123456789" "^_`abcdefghijklmnopqrstuvwxyz|~"; const absl::string_view kHttp2HeaderValueAllowedChars = "\t " "!\"#$%&'()*+,-./" "0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`" "abcdefghijklmnopqrstuvwxyz{|}~"; const absl::string_view kHttp2StatusValueAllowedChars = "0123456789"; const absl::string_view kValidAuthorityChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~%!$&'()[" "]*+,;=:"; using CharMap = std::array<bool, 256>; CharMap BuildValidCharMap(absl::string_view valid_chars) { CharMap map; map.fill(false); for (char c : valid_chars) { // Cast to uint8_t, guaranteed to have 8 bits. A char may have more, leading // to possible indices above 256. map[static_cast<uint8_t>(c)] = true; } return map; } bool AllCharsInMap(absl::string_view str, const CharMap& map) { for (char c : str) { if (!map[static_cast<uint8_t>(c)]) { return false; } } return true; } // Returns whether `authority` contains only characters from the `host` ABNF // from RFC 3986 section 3.2.2. bool IsValidAuthority(absl::string_view authority) { static const CharMap valid_chars = BuildValidCharMap(kValidAuthorityChars); return AllCharsInMap(authority, valid_chars); } bool IsValidHeaderName(absl::string_view name) { static const CharMap valid_chars = BuildValidCharMap(kHttp2HeaderNameAllowedChars); return AllCharsInMap(name, valid_chars); } bool IsValidHeaderValue(absl::string_view value) { static const CharMap valid_chars = BuildValidCharMap(kHttp2HeaderValueAllowedChars); return AllCharsInMap(value, valid_chars); } bool IsValidStatus(absl::string_view status) { static const CharMap valid_chars = BuildValidCharMap(kHttp2StatusValueAllowedChars); return AllCharsInMap(status, valid_chars); } bool ValidateRequestHeaders(const std::vector<std::string>& pseudo_headers, absl::string_view method, absl::string_view path, bool allow_connect) { QUICHE_VLOG(2) << "Request pseudo-headers: [" << absl::StrJoin(pseudo_headers, ", ") << "], allow_connect: " << allow_connect << ", method: " << method << ", path: " << path; if (allow_connect && method == "CONNECT") { static const std::vector<std::string>* kConnectHeaders = new std::vector<std::string>( {":authority", ":method", ":path", ":protocol", ":scheme"}); return pseudo_headers == *kConnectHeaders; } if (path.empty()) { return false; } if (path == "*") { if (method != "OPTIONS") { return false; } } else if (path[0] != '/') { return false; } static const std::vector<std::string>* kRequiredHeaders = new std::vector<std::string>( {":authority", ":method", ":path", ":scheme"}); return pseudo_headers == *kRequiredHeaders; } bool ValidateRequestTrailers(const std::vector<std::string>& pseudo_headers) { return pseudo_headers.empty(); } bool ValidateResponseHeaders(const std::vector<std::string>& pseudo_headers) { static const std::vector<std::string>* kRequiredHeaders = new std::vector<std::string>({":status"}); return pseudo_headers == *kRequiredHeaders; } bool ValidateResponseTrailers(const std::vector<std::string>& pseudo_headers) { return pseudo_headers.empty(); } } // namespace void HeaderValidator::StartHeaderBlock() { pseudo_headers_.clear(); status_.clear(); method_.clear(); path_.clear(); content_length_.reset(); } HeaderValidator::HeaderStatus HeaderValidator::ValidateSingleHeader( absl::string_view key, absl::string_view value) { if (key.empty()) { return HEADER_FIELD_INVALID; } if (max_field_size_.has_value() && key.size() + value.size() > max_field_size_.value()) { QUICHE_VLOG(2) << "Header field size is " << key.size() + value.size() << ", exceeds max size of " << max_field_size_.value(); return HEADER_FIELD_TOO_LONG; } const absl::string_view validated_key = key[0] == ':' ? key.substr(1) : key; if (!IsValidHeaderName(validated_key)) { QUICHE_VLOG(2) << "invalid chars in header name: [" << absl::CEscape(validated_key) << "]"; return HEADER_FIELD_INVALID; } if (!IsValidHeaderValue(value)) { QUICHE_VLOG(2) << "invalid chars in header value: [" << absl::CEscape(value) << "]"; return HEADER_FIELD_INVALID; } if (key[0] == ':') { if (key == ":status") { if (value.size() != 3 || !IsValidStatus(value)) { QUICHE_VLOG(2) << "malformed status value: [" << absl::CEscape(value) << "]"; return HEADER_FIELD_INVALID; } if (value == "101") { // Switching protocols is not allowed on a HTTP/2 stream. return HEADER_FIELD_INVALID; } status_ = std::string(value); } else if (key == ":method") { method_ = std::string(value); } else if (key == ":authority" && !IsValidAuthority(value)) { return HEADER_FIELD_INVALID; } else if (key == ":path") { if (value.empty()) { // For now, reject an empty path regardless of scheme. return HEADER_FIELD_INVALID; } path_ = std::string(value); } pseudo_headers_.push_back(std::string(key)); } else if (key == "content-length") { const bool success = HandleContentLength(value); if (!success) { return HEADER_FIELD_INVALID; } } else if (key == "te" && value != "trailers") { return HEADER_FIELD_INVALID; } return HEADER_OK; } // Returns true if all required pseudoheaders and no extra pseudoheaders are // present for the given header type. bool HeaderValidator::FinishHeaderBlock(HeaderType type) { std::sort(pseudo_headers_.begin(), pseudo_headers_.end()); switch (type) { case HeaderType::REQUEST: return ValidateRequestHeaders(pseudo_headers_, method_, path_, allow_connect_); case HeaderType::REQUEST_TRAILER: return ValidateRequestTrailers(pseudo_headers_); case HeaderType::RESPONSE_100: case HeaderType::RESPONSE: return ValidateResponseHeaders(pseudo_headers_); case HeaderType::RESPONSE_TRAILER: return ValidateResponseTrailers(pseudo_headers_); } return false; } bool HeaderValidator::HandleContentLength(absl::string_view value) { if (value.empty()) { return false; } if (status_ == "204" && value != "0") { // There should be no body in a "204 No Content" response. return false; } if (!status_.empty() && status_[0] == '1' && value != "0") { // There should also be no body in a 1xx response. return false; } size_t content_length = 0; const bool valid = absl::SimpleAtoi(value, &content_length); if (!valid) { return false; } content_length_ = content_length; return true; } } // namespace adapter } // namespace http2 <|endoftext|>
<commit_before>/* This file is part of Bohrium and copyright (c) 2012 the Bohrium team <http://www.bh107.org>. Bohrium 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 3 of the License, or (at your option) any later version. Bohrium 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 Lesser General Public License along with Bohrium. If not, see <http://www.gnu.org/licenses/>. */ #include <bh.h> #include <stdio.h> #include <bh_dag.h> #include <boost/foreach.hpp> using namespace std; using namespace boost; using namespace bohrium::dag; static int64_t sum=0; void filter(const bh_ir &bhir) { if(bhir.kernel_list.size() == 0) return; GraphDW dag; from_kernels(bhir.kernel_list, dag); sum += dag_cost(dag.bglD()); } void shutdown() { cout << "[PRICER-FILTER] total cost: " << sum << endl; } <commit_msg>pricer-filter: now checks for non-fusible kernels in the kernel list<commit_after>/* This file is part of Bohrium and copyright (c) 2012 the Bohrium team <http://www.bh107.org>. Bohrium 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 3 of the License, or (at your option) any later version. Bohrium 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 Lesser General Public License along with Bohrium. If not, see <http://www.gnu.org/licenses/>. */ #include <bh.h> #include <stdio.h> #include <bh_dag.h> #include <boost/foreach.hpp> using namespace std; using namespace boost; using namespace bohrium::dag; static int64_t sum=0; void filter(const bh_ir &bhir) { if(bhir.kernel_list.size() == 0) return; GraphDW dag; from_kernels(bhir.kernel_list, dag); sum += dag_cost(dag.bglD()); BOOST_FOREACH(const bh_ir_kernel &k, bhir.kernel_list) { if(not k.fusible()) { cout << "[PRICER-FILTER] Ilegal non-fusible kernel in the kernel list!" << endl; } } } void shutdown() { cout << "[PRICER-FILTER] total cost: " << sum << endl; } <|endoftext|>
<commit_before>#include <cstdlib> #include <cstdio> #include <cstring> #include <cmath> #include <string> #include <utility> #include <functional> #include <memory> #include <algorithm> #include <iostream> #include <map> #include <chrono> #include <sg14/fixed_point> #include <EASTL/vector.h> #include <EASTL/array.h> using eastl::vector; using eastl::array; using namespace std::chrono; using sg14::fixed_point; #include "RasterizerCommon.h" #include "RaycastCommon.h" #include "Vec2i.h" #include "IMapElement.h" #include "CTeam.h" #include "CItem.h" #include "CActor.h" #include "CGameDelegate.h" #include "CMap.h" #include "IRenderer.h" #include "IFileLoaderDelegate.h" #include "CGame.h" #include "NativeBitmap.h" #include "RasterizerCommon.h" #include "CRenderer.h" #include <SDL/SDL.h> #include <SDL/SDL_mixer.h> #include <cmath> #include "NativeBitmap.h" #include "LoadPNG.h" #ifdef __EMSCRIPTEN__ #include <emscripten/html5.h> #endif namespace odb { SDL_Surface *video; #ifdef __EMSCRIPTEN__ void enterFullScreenMode() { EmscriptenFullscreenStrategy s; memset(&s, 0, sizeof(s)); s.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_ASPECT; s.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_NONE; s.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT; emscripten_enter_soft_fullscreen(0, &s); } #endif CRenderer::CRenderer() { SDL_Init( SDL_INIT_EVERYTHING ); video = SDL_SetVideoMode( 320, 200, 32, 0 ); for ( int r = 0; r < 256; ++r ) { for ( int g = 0; g < 256; ++g ) { for ( int b = 0; b < 256; ++b ) { auto pixel = 0xFF000000 + ( r << 16 ) + ( g << 8 ) + ( b ); auto paletteEntry = getPaletteEntry( pixel ); mPalette[ paletteEntry ] = pixel; } } } #ifdef __EMSCRIPTEN__ enterFullScreenMode(); #endif } void CRenderer::sleep(long ms) { #ifndef __EMSCRIPTEN__ SDL_Delay(33); #endif } void CRenderer::handleSystemEvents() { SDL_Event event; const static FixP delta{2}; while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { #ifndef __EMSCRIPTEN__ exit(0); #endif } if (event.type == SDL_KEYUP) { switch (event.key.keysym.sym) { case SDLK_q: #ifndef __EMSCRIPTEN__ exit(0); #endif default: break; } } if (event.type == SDL_KEYDOWN) { switch (event.key.keysym.sym) { case SDLK_SPACE: exit(0); mNeedsToRedraw = true; break; case SDLK_LEFT: mSpeed.mX += delta; mNeedsToRedraw = true; break; case SDLK_RIGHT: mSpeed.mX -= delta; mNeedsToRedraw = true; break; case SDLK_UP: mSpeed.mY -= delta; mNeedsToRedraw = true; break; case SDLK_DOWN: mSpeed.mY += delta; mNeedsToRedraw = true; break; case SDLK_z: mSpeed.mZ += delta; mNeedsToRedraw = true; break; case SDLK_a: mSpeed.mZ -= delta; mNeedsToRedraw = true; break; default: break; } } } } void CRenderer::putRaw(int16_t x, int16_t y, uint32_t pixel) { if ( x < 0 || x >= 256 || y < 0 || y >= 128 ) { return; } mBuffer[ (320 * y ) + x ] = pixel; } void CRenderer::flip() { for ( int y = 0; y < 128; ++y ) { for ( int x = 0; x < 320; ++x ) { SDL_Rect rect; rect.x = x; rect.y = y; rect.w = 1; rect.h = 1; auto pixel = mPalette[ mBuffer[ (320 * y ) + x ] ]; SDL_FillRect(video, &rect, SDL_MapRGB(video->format, ((pixel & 0x000000FF)), ((pixel & 0x0000FF00) >> 8), ((pixel & 0x00FF0000) >> 16))); } } SDL_Flip(video); } void CRenderer::clear() { const static auto grey = getPaletteEntry(0xFFAAAAAA); auto beginFrame = std::begin( mBuffer ); auto endFrame = std::end( mBuffer ); std::fill( beginFrame, endFrame, grey ); SDL_FillRect(video, nullptr, 0); } } <commit_msg>Double pixels in SDL version of 486 port<commit_after>#include <cstdlib> #include <cstdio> #include <cstring> #include <cmath> #include <string> #include <utility> #include <functional> #include <memory> #include <algorithm> #include <iostream> #include <map> #include <chrono> #include <sg14/fixed_point> #include <EASTL/vector.h> #include <EASTL/array.h> using eastl::vector; using eastl::array; using namespace std::chrono; using sg14::fixed_point; #include "RasterizerCommon.h" #include "RaycastCommon.h" #include "Vec2i.h" #include "IMapElement.h" #include "CTeam.h" #include "CItem.h" #include "CActor.h" #include "CGameDelegate.h" #include "CMap.h" #include "IRenderer.h" #include "IFileLoaderDelegate.h" #include "CGame.h" #include "NativeBitmap.h" #include "RasterizerCommon.h" #include "CRenderer.h" #include <SDL/SDL.h> #include <SDL/SDL_mixer.h> #include <cmath> #include "NativeBitmap.h" #include "LoadPNG.h" #ifdef __EMSCRIPTEN__ #include <emscripten/html5.h> #endif namespace odb { SDL_Surface *video; #ifdef __EMSCRIPTEN__ void enterFullScreenMode() { EmscriptenFullscreenStrategy s; memset(&s, 0, sizeof(s)); s.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_ASPECT; s.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_NONE; s.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT; emscripten_enter_soft_fullscreen(0, &s); } #endif CRenderer::CRenderer() { SDL_Init( SDL_INIT_EVERYTHING ); video = SDL_SetVideoMode( 640, 400, 32, 0 ); for ( int r = 0; r < 256; ++r ) { for ( int g = 0; g < 256; ++g ) { for ( int b = 0; b < 256; ++b ) { auto pixel = 0xFF000000 + ( r << 16 ) + ( g << 8 ) + ( b ); auto paletteEntry = getPaletteEntry( pixel ); mPalette[ paletteEntry ] = pixel; } } } #ifdef __EMSCRIPTEN__ enterFullScreenMode(); #endif } void CRenderer::sleep(long ms) { #ifndef __EMSCRIPTEN__ SDL_Delay(33); #endif } void CRenderer::handleSystemEvents() { SDL_Event event; const static FixP delta{2}; while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { #ifndef __EMSCRIPTEN__ exit(0); #endif } if (event.type == SDL_KEYUP) { switch (event.key.keysym.sym) { case SDLK_q: #ifndef __EMSCRIPTEN__ exit(0); #endif default: break; } } if (event.type == SDL_KEYDOWN) { switch (event.key.keysym.sym) { case SDLK_SPACE: exit(0); mNeedsToRedraw = true; break; case SDLK_LEFT: mSpeed.mX += delta; mNeedsToRedraw = true; break; case SDLK_RIGHT: mSpeed.mX -= delta; mNeedsToRedraw = true; break; case SDLK_UP: mSpeed.mY -= delta; mNeedsToRedraw = true; break; case SDLK_DOWN: mSpeed.mY += delta; mNeedsToRedraw = true; break; case SDLK_z: mSpeed.mZ += delta; mNeedsToRedraw = true; break; case SDLK_a: mSpeed.mZ -= delta; mNeedsToRedraw = true; break; default: break; } } } } void CRenderer::putRaw(int16_t x, int16_t y, uint32_t pixel) { if ( x < 0 || x >= 256 || y < 0 || y >= 128 ) { return; } mBuffer[ (320 * y ) + x ] = pixel; } void CRenderer::flip() { for ( int y = 0; y < 128; ++y ) { for ( int x = 0; x < 320; ++x ) { SDL_Rect rect; rect.x = 2 * x; rect.y = 2 * y; rect.w = 2; rect.h = 2; auto pixel = mPalette[ mBuffer[ (320 * y ) + x ] ]; SDL_FillRect(video, &rect, SDL_MapRGB(video->format, ((pixel & 0x000000FF)), ((pixel & 0x0000FF00) >> 8), ((pixel & 0x00FF0000) >> 16))); } } SDL_Flip(video); } void CRenderer::clear() { const static auto grey = getPaletteEntry(0xFFAAAAAA); auto beginFrame = std::begin( mBuffer ); auto endFrame = std::end( mBuffer ); std::fill( beginFrame, endFrame, grey ); SDL_FillRect(video, nullptr, 0); } } <|endoftext|>
<commit_before>AliAnalysisTask *AddTaskHFEQA(Bool_t useMC, Bool_t isAOD, Int_t icollisionsystem = 2, Int_t icent = 2,Int_t debuglevel = 4,Bool_t tpconlydo = kTRUE,Bool_t trdonlydo = kTRUE,Bool_t toftpcdo = kTRUE,Bool_t tpctrddo = kTRUE,Bool_t tpcemcaldo = kTRUE){ // Name TString appendixx("HFEQA"); //set config file name TString configFile("$ALICE_ROOT/PWGHF/hfe/macros/configs/PbPb/ConfigHFEQA.C"); TString checkconfig="ConfigHFEQA"; if (!gROOT->GetListOfGlobalFunctions()->FindObject(checkconfig.Data())) gROOT->LoadMacro(configFile.Data()); AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer(); AliAnalysisTaskHFEQA *task = ConfigHFEQA(useMC,isAOD,icollisionsystem,icent,tpconlydo,trdonlydo,toftpcdo,tpctrddo,tpcemcaldo); mgr->AddTask(task); mgr->AddClassDebug("AliAnalysisTaskHFEQA",debuglevel); //mgr->AddClassDebug("AliHFEpid",debuglevel); //mgr->AddClassDebug("AliHFEpidTPC",debuglevel); //mgr->AddClassDebug("AliHFEpidTOF",debuglevel); mgr->AddClassDebug("AliHFEpidTRD",debuglevel); mgr->AddClassDebug("AliHFEtrdPIDqaV1",debuglevel); mgr->AddClassDebug("AliPIDResponse",debuglevel); mgr->AddClassDebug("AliTRDPIDResponse",debuglevel); mgr->AddClassDebug("AliTRDPIDReference",debuglevel); mgr->AddClassDebug("AliTRDPIDResponseObject",debuglevel); TString containerName = mgr->GetCommonFileName(); containerName += ":"; containerName += appendixx.Data(); AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer(); mgr->ConnectOutput(task,1, mgr->CreateContainer(Form("list_%s",appendixx.Data()), TList::Class(),AliAnalysisManager::kOutputContainer,containerName.Data())); mgr->ConnectInput(task,0, cinput ); return NULL; } <commit_msg>Fix AddTaskHFEQA.C macro<commit_after>AliAnalysisTask *AddTaskHFEQA(Bool_t useMC, Bool_t isAOD, Int_t icollisionsystem = 2, Int_t icent = 2,Int_t debuglevel = 4,Bool_t tpconlydo = kTRUE,Bool_t trdonlydo = kTRUE,Bool_t toftpcdo = kTRUE,Bool_t tpctrddo = kTRUE,Bool_t tpcemcaldo = kTRUE){ // Name TString appendixx("HFEQA"); //set config file name TString configFile("$ALICE_PHYSICS/PWGHF/hfe/macros/configs/PbPb/ConfigHFEQA.C"); TString checkconfig="ConfigHFEQA"; if (!gROOT->GetListOfGlobalFunctions()->FindObject(checkconfig.Data())) gROOT->LoadMacro(configFile.Data()); AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer(); AliAnalysisTaskHFEQA *task = ConfigHFEQA(useMC,isAOD,icollisionsystem,icent,tpconlydo,trdonlydo,toftpcdo,tpctrddo,tpcemcaldo); mgr->AddTask(task); mgr->AddClassDebug("AliAnalysisTaskHFEQA",debuglevel); //mgr->AddClassDebug("AliHFEpid",debuglevel); //mgr->AddClassDebug("AliHFEpidTPC",debuglevel); //mgr->AddClassDebug("AliHFEpidTOF",debuglevel); mgr->AddClassDebug("AliHFEpidTRD",debuglevel); mgr->AddClassDebug("AliHFEtrdPIDqaV1",debuglevel); mgr->AddClassDebug("AliPIDResponse",debuglevel); mgr->AddClassDebug("AliTRDPIDResponse",debuglevel); mgr->AddClassDebug("AliTRDPIDReference",debuglevel); mgr->AddClassDebug("AliTRDPIDResponseObject",debuglevel); TString containerName = mgr->GetCommonFileName(); containerName += ":"; containerName += appendixx.Data(); AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer(); mgr->ConnectOutput(task,1, mgr->CreateContainer(Form("list_%s",appendixx.Data()), TList::Class(),AliAnalysisManager::kOutputContainer,containerName.Data())); mgr->ConnectInput(task,0, cinput ); return NULL; } <|endoftext|>
<commit_before>/* FLTKKeyboardWidget.hpp: Copyright (C) 2006 Steven Yi This file is part of Csound. The Csound 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. Csound 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 Csound; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "FLTKKeyboardWidget.hpp" static void allNotesOff(Fl_Widget *widget, void * v) { FLTKKeyboardWidget *win = (FLTKKeyboardWidget *)v; win->keyboard->allNotesOff(); } static void channelChange(Fl_Widget *widget, void * v) { Fl_Spinner *spinner = (Fl_Spinner *)widget; FLTKKeyboardWidget *win = (FLTKKeyboardWidget *)v; win->lock(); int channel = (int)spinner->value() - 1; win->keyboardMapping->setCurrentChannel(channel); win->bankChoice->value(win->keyboardMapping->getCurrentBank()); win->setProgramNames(); win->unlock(); } static void bankChange(Fl_Widget *widget, void * v) { Fl_Choice *choice = (Fl_Choice *)widget; FLTKKeyboardWidget *win = (FLTKKeyboardWidget *)v; win->lock(); win->keyboardMapping->setCurrentBank((int)choice->value()); win->setProgramNames(); win->unlock(); } static void programChange(Fl_Widget *widget, void * v) { Fl_Choice *choice = (Fl_Choice *)widget; FLTKKeyboardWidget *win = (FLTKKeyboardWidget *)v; win->lock(); win->keyboardMapping->setCurrentProgram((int)choice->value()); win->unlock(); } FLTKKeyboardWidget::FLTKKeyboardWidget(CSOUND *csound, const char *deviceMap, int X, int Y) : Fl_Group(X, Y, 624, 120) { this->csound = csound; this->mutex = csound->Create_Mutex(0); this->keyboardMapping = new KeyboardMapping(csound, deviceMap); this->begin(); int row1 = 0; int row2 = row1 + 20; int row3 = row2 + 20; this->channelSpinner = new Fl_Spinner(60, row1, 80, 20, "Channel"); channelSpinner->maximum(16); channelSpinner->minimum(1); this->channelSpinner->callback((Fl_Callback*) channelChange, this); this->bankChoice = new Fl_Choice(180, row1, 180, 20, "Bank"); this->programChoice = new Fl_Choice(420, row1, 200, 20, "Program"); bankChoice->clear(); for(unsigned int i = 0; i < keyboardMapping->banks.size(); i++) { bankChoice->add(keyboardMapping->banks[i]->name); } bankChoice->value(0); setProgramNames(); this->bankChoice->callback((Fl_Callback*)bankChange, this); this->programChoice->callback((Fl_Callback*)programChange, this); this->allNotesOffButton = new Fl_Button(0, row2, 623, 20, "All Notes Off"); this->allNotesOffButton->callback((Fl_Callback*) allNotesOff, this); this->keyboard = new FLTKKeyboard(csound, 0, row3, 624, 80, "Keyboard"); this->end(); } FLTKKeyboardWidget::~FLTKKeyboardWidget() { if (mutex) { csound->DestroyMutex(mutex); mutex = (void*) 0; } delete keyboardMapping; } void FLTKKeyboardWidget::setProgramNames() { Bank* bank = keyboardMapping->banks[keyboardMapping->getCurrentBank()]; programChoice->clear(); for( vector<Program>::iterator iter = bank->programs.begin(); iter != bank->programs.end(); iter++ ) { programChoice->add((*iter).name); } programChoice->value(bank->currentProgram); } int FLTKKeyboardWidget::handle(int event) { //this->csound->Message(this->csound, "Keyboard event: %d\n", event); switch(event) { case FL_KEYDOWN: return this->keyboard->handle(event); case FL_KEYUP: return this->keyboard->handle(event); // case FL_DEACTIVATE: // this->keyboard->allNotesOff(); // csound->Message(csound, "Deactivate\n"); // return 1; default: return Fl_Group::handle(event); } } void FLTKKeyboardWidget::lock() { if(mutex) { csound->LockMutex(mutex); } } void FLTKKeyboardWidget::unlock() { if(mutex) { csound->UnlockMutex(mutex); } } <commit_msg>fixes for x and y values<commit_after>/* FLTKKeyboardWidget.hpp: Copyright (C) 2006 Steven Yi This file is part of Csound. The Csound 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. Csound 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 Csound; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "FLTKKeyboardWidget.hpp" static void allNotesOff(Fl_Widget *widget, void * v) { FLTKKeyboardWidget *win = (FLTKKeyboardWidget *)v; win->keyboard->allNotesOff(); } static void channelChange(Fl_Widget *widget, void * v) { Fl_Spinner *spinner = (Fl_Spinner *)widget; FLTKKeyboardWidget *win = (FLTKKeyboardWidget *)v; win->lock(); int channel = (int)spinner->value() - 1; win->keyboardMapping->setCurrentChannel(channel); win->bankChoice->value(win->keyboardMapping->getCurrentBank()); win->setProgramNames(); win->unlock(); } static void bankChange(Fl_Widget *widget, void * v) { Fl_Choice *choice = (Fl_Choice *)widget; FLTKKeyboardWidget *win = (FLTKKeyboardWidget *)v; win->lock(); win->keyboardMapping->setCurrentBank((int)choice->value()); win->setProgramNames(); win->unlock(); } static void programChange(Fl_Widget *widget, void * v) { Fl_Choice *choice = (Fl_Choice *)widget; FLTKKeyboardWidget *win = (FLTKKeyboardWidget *)v; win->lock(); win->keyboardMapping->setCurrentProgram((int)choice->value()); win->unlock(); } FLTKKeyboardWidget::FLTKKeyboardWidget(CSOUND *csound, const char *deviceMap, int X, int Y) : Fl_Group(X, Y, 624, 120) { this->csound = csound; this->mutex = csound->Create_Mutex(0); this->keyboardMapping = new KeyboardMapping(csound, deviceMap); this->begin(); int baseX = this->x(); int baseY = this->y(); int row1 = baseY; int row2 = row1 + 20; int row3 = row2 + 20; this->channelSpinner = new Fl_Spinner(baseX + 60, row1, 80, 20, "Channel"); channelSpinner->maximum(16); channelSpinner->minimum(1); this->channelSpinner->callback((Fl_Callback*) channelChange, this); this->bankChoice = new Fl_Choice(baseX + 180, row1, 180, 20, "Bank"); this->programChoice = new Fl_Choice(baseX + 420, row1, 200, 20, "Program"); bankChoice->clear(); for(unsigned int i = 0; i < keyboardMapping->banks.size(); i++) { bankChoice->add(keyboardMapping->banks[i]->name); } bankChoice->value(0); setProgramNames(); this->bankChoice->callback((Fl_Callback*)bankChange, this); this->programChoice->callback((Fl_Callback*)programChange, this); this->allNotesOffButton = new Fl_Button(baseX, row2, 623, 20, "All Notes Off"); this->allNotesOffButton->callback((Fl_Callback*) allNotesOff, this); this->keyboard = new FLTKKeyboard(csound, baseX, row3, 624, 80, "Keyboard"); this->end(); } FLTKKeyboardWidget::~FLTKKeyboardWidget() { if (mutex) { csound->DestroyMutex(mutex); mutex = (void*) 0; } delete keyboardMapping; } void FLTKKeyboardWidget::setProgramNames() { Bank* bank = keyboardMapping->banks[keyboardMapping->getCurrentBank()]; programChoice->clear(); for( vector<Program>::iterator iter = bank->programs.begin(); iter != bank->programs.end(); iter++ ) { programChoice->add((*iter).name); } programChoice->value(bank->currentProgram); } int FLTKKeyboardWidget::handle(int event) { switch(event) { case FL_KEYDOWN: return this->keyboard->handle(event); case FL_KEYUP: return this->keyboard->handle(event); // case FL_DEACTIVATE: // this->keyboard->allNotesOff(); // csound->Message(csound, "Deactivate\n"); // return 1; default: // this->csound->Message(this->csound, "Keyboard event: %d\n", event); return Fl_Group::handle(event); } } void FLTKKeyboardWidget::lock() { if(mutex) { csound->LockMutex(mutex); } } void FLTKKeyboardWidget::unlock() { if(mutex) { csound->UnlockMutex(mutex); } } <|endoftext|>
<commit_before>#include "tables.h" /*This information was previously in main but was moved out to make test programs */ ///////////////INITIALIZIING//////////////// //////////////////////////////////////////// namespace editor { int WIN_HEIGHT, WIN_WIDTH; WIN *ptrnwin; WIN *instwin; WIN *metawin; WIN *volwin; WIN *wavewin; WIN *pulsewin; WIN *dialog; WIN *wingroup; WIN *inputwin; WIN *lastwin; bool running; int numBuffer; char charBuffer[CHARBUFFER_SIZE]; char charInputBuffer[CMDBAR_SIZE]; char charInputHistory[HISTORY_SIZE][CMDBAR_SIZE]; char history_head; char history_size; char lastSongPath[LASTSONG_SIZE]; char textCursorPos; bool *muted_tracks; float playamp; Song *song; int daemonpid; Song *playback; unsigned char playback_length; unsigned char playback_mark; Instrument *selinst; } //Pattern Editor namespace patternedtr { std::map<int,unsigned int> notemap; Pattern *selptrn; unsigned char viewporttrack; unsigned char viewportrow; unsigned char maxtracksviewport; unsigned char maxrowsviewport; unsigned char selrow; unsigned char seltrack; unsigned char seltrackseg; unsigned char selorder; unsigned char selinstrument; unsigned char edit_step; unsigned char row_underline; unsigned char octave; unsigned char key; unsigned int entryclipboard; //METADATA (Main controls) unsigned char metaobjindex; bool metaobjedit; unsigned char selobjmeta;//x unsigned char selrowmeta;//y } //Instrument Editor namespace instedtr { unsigned short waveclipboard; unsigned short pulseclipboard; unsigned short volclipboard; bool instobjedit; unsigned char selinstrow; unsigned char selinstobj; unsigned short selwavrow; unsigned short selpulrow; unsigned char selpulseg; unsigned char selwavseg; unsigned short viewportwave; unsigned short viewportpulse; unsigned char viewportvol; unsigned char selvolrow; unsigned char selvolseg; } /////////////DONE INITIALIZING///////////// /////////////////////////////////////////// <commit_msg>Added new fields<commit_after>#include "tables.h" /*This information was previously in main but was moved out to make test programs */ ///////////////INITIALIZIING//////////////// //////////////////////////////////////////// namespace editor { int WIN_HEIGHT, WIN_WIDTH; WIN *ptrnwin; WIN *instwin; WIN *metawin; WIN *volwin; WIN *wavewin; WIN *pulsewin; WIN *dialog; WIN *wingroup; WIN *inputwin; WIN *lastwin; bool running; int numBuffer; char charBuffer[CHARBUFFER_SIZE]; char charInputBuffer[CMDBAR_SIZE]; char charInputHistory[HISTORY_SIZE][CMDBAR_SIZE]; char history_head; char history_size; char lastSongPath[LASTSONG_SIZE]; char textCursorPos; bool *muted_tracks; float playamp; Song *song; int daemonpid; Song *playback; unsigned char playback_length; unsigned char playback_mark; Instrument *selinst; } //Pattern Editor namespace patternedtr { std::map<int,unsigned int> notemap; Pattern *selptrn; unsigned char viewporttrack; unsigned char viewportrow; unsigned char maxtracksviewport; unsigned char maxrowsviewport; unsigned char selrow; unsigned char seltrack; unsigned char seltrackseg; unsigned char selorder; unsigned char selinstrument; unsigned char edit_step; unsigned char row_underline; unsigned char octave; unsigned char key; unsigned char scalespinner; unsigned char scaleconst[12];//Scale construction pattern unsigned int entryclipboard; //METADATA (Main controls) unsigned char metaobjindex; bool metaobjedit; unsigned char selobjmeta;//x unsigned char selrowmeta;//y } //Instrument Editor namespace instedtr { unsigned short waveclipboard; unsigned short pulseclipboard; unsigned short volclipboard; bool instobjedit; unsigned char selinstrow; unsigned char selinstobj; unsigned short selwavrow; unsigned short selpulrow; unsigned char selpulseg; unsigned char selwavseg; unsigned short viewportwave; unsigned short viewportpulse; unsigned char viewportvol; unsigned char selvolrow; unsigned char selvolseg; } /////////////DONE INITIALIZING///////////// /////////////////////////////////////////// <|endoftext|>
<commit_before>/* * profiles.cpp * * Created on: Mar 6, 2012 * Author: bmetcalf */ #include <slsimlib.h> /// Gaussian particles double QuadTree::alpha_o(double r2,float sigma){ if(r2==0) return 0.0; if(sigma <= 0.0 ) return -1.0/r2/pi; return ( exp(-r2/sigma/sigma/2) - 1.0 )/r2/pi; } double QuadTree::kappa_o(double r2,float sigma){ if(sigma <= 0.0) return 0.0; return exp(-r2/sigma/sigma/2)/2/pi/sigma/sigma; } double QuadTree::gamma_o(double r2,float sigma){ if(r2==0) return 0.0; if(sigma <= 0.0) return -2.0/pi/pow(r2,2); return (-2.0 + (2.0 + r2/sigma/sigma)*exp(-r2/sigma/sigma/2) )/pi/pow(r2,2); } double QuadTree::phi_o(double r2,float sigma){ ERROR_MESSAGE(); // not yet written exit(1); return 0; } /** power-law profiles * All quantities should be divided by Sigma_crit to get the usual */ double QuadTreePowerLaw::alpha_h(double r2,HaloStructure &par){ if(r2==0) return 0.0; double b=0,r = sqrt(r2); b = -par.mass/r2/pi; if(r < par.Rmax) b *= pow(r/par.Rmax,beta+2); return b; } double QuadTreePowerLaw::kappa_h(double r2,HaloStructure &par){ if(r2 > par.Rmax*par.Rmax) return 0.0; if(r2 < 1.0-20) r2=1.0e-20; return (beta+2)*par.mass*pow(r2/par.Rmax/par.Rmax,beta/2)/(pi*pow(par.Rmax,2)); } double QuadTreePowerLaw::gamma_h(double r2,HaloStructure &par){ double gt=0; if( r2 <= 0.0) return 0.0; gt = -2.0*par.mass/pi/pow(r2,2); if(r2 < par.Rmax*par.Rmax) gt *= -beta*pow(r2/par.Rmax/par.Rmax,beta/2+1)/2; return gt; } double QuadTreePowerLaw::phi_h(double r2,HaloStructure &par){ double b; b=par.mass/pi; double r = sqrt(r2); if(r <= par.Rmax) return b*pow(r/par.Rmax,beta+2); return b*(log(r/par.Rmax) + 1); } // NFW profile // Gives the magnitude of the deflection angle modulo Sigma_crit double QuadTreeNFW::alpha_h(double r2,HaloStructure &par){ double b=0; if(r2 <= 0) return 0.0; b = -par.mass/r2/pi; double r = sqrt(r2); if(r < par.Rmax){ double y; y = par.Rmax/par.rscale; b *= rhos(y); y = r/par.rscale; b*= gfunction(y); } return b; } /// Convergence for an NFW halo double QuadTreeNFW::kappa_h(double r2,HaloStructure &par){ double r = sqrt(r2); if(r >= par.Rmax) return 0.0; if(r < 1.0-20) r=1.0e-20; double y,b; b = par.mass/2/pi/pow(par.rscale,2); y = par.Rmax/par.rscale; b *= rhos(y); y = r/par.rscale; b*= ffunction(y); return b; } /// Shear for and NFW halo. this might have a flaw in it double QuadTreeNFW::gamma_h(double r2,HaloStructure &par){ double gt=0; if(r2 <= 0.0) return 0.0; double r = sqrt(r2); gt = -2.0*par.mass/pi/r2/r2; if(r > par.Rmax){ double y; y = par.Rmax/par.rscale; gt *= rhos(y)*pow(r/par.rscale,2)/8.0; y = r/par.rscale; gt *= g2function(y); } return gt; } double QuadTreeNFW::phi_h(double r2,HaloStructure &par){ ERROR_MESSAGE(); std::cout << "time delay has not been fixed for NFW profile yet." << std::endl; exit(1); return 0.0; } double QuadTreeNFW::gfunction(double x){ double ans; ans=log(x/2); if(x==1.0){ ans += 1.0; return ans;} if(x>1.0){ ans += 2*atan(sqrt((x-1)/(x+1)))/sqrt(x*x-1);; return ans;} if(x<1.0){ ans += 2*atanh(sqrt((1-x)/(x+1)))/sqrt(1-x*x);; return ans;} return 0.0; } double QuadTreeNFW::ffunction(double x){ double ans; if(x==1.0){ return 1.0/3.0;} if(x>1.0){ ans = (1-2*atan(sqrt((x-1)/(x+1)))/sqrt(x*x-1))/(x*x-1); return ans;} if(x<1.0){ ans = (1-2*atanh(sqrt((1-x)/(x+1)))/sqrt(1-x*x))/(x*x-1); return ans;} return 0.0; } double QuadTreeNFW::g2function(double x){ double ans; if(x==1) return 10/3. + 4*log(0.5); ans=4*log(x/2.0)/x/x - 2/(x*x-1); if(x<1.0){ ans+= 4*(2/x/x+1/(x*x-1))*atanh(sqrt((1-x)/(x+1)))/sqrt(1-x*x); return ans;} if(x>1.0){ ans+= 4*(2/x/x+1/(x*x-1))*atan(sqrt((x-1)/(x+1)))/sqrt(x*x-1); return ans;} return 0.0; } double QuadTreeNFW::gfunctionRmax(double rm,double x){ double ans; double xx = sqrt(1-x*x); double xxx = sqrt(x*x-1); double rmm = sqrt(rm*rm-1); double rmx = sqrt(rm*rm+x*x); ans = atanh(rm)-atanh(rmx/rm); if(x==1.0){ ans += rmx/rm - 1/rm; return ans;} if(x>1.0){ ans += (atan(rm/xxx)-atan(rm/xxx/rmx))/xxx; return ans;} if(x<1.0){ ans -= (atanh(rm/xx)-atanh(rm/xx/rmx))/xx; return ans;} return 0.0; } double QuadTreeNFW::ffunctionRmax(double rm,double x){ double ans; double xx = sqrt(1-x*x); double xxx = sqrt(x*x-1); double rmx = sqrt(rm*rm+x*x); if(x==1.0){ ans = (-2-rm*rm+rm*rm*rm*rm+2*rmx)/3.0/rm/rm/rm/rmx; return ans; } ans = rm*(rmx-1)/(rmx*rmx-1)/(x*x-1); if(x>1.0){ ans += ((atan(rm/xxx)-atan(rm/xxx/rmx))/xxx)/(x*x-1); return ans;} if(x<1.0){ ans -= ((atanh(rm/xx)-atanh(rm/xx/rmx))/xx)/(x*x-1); return ans;} return 0.0; } double QuadTreeNFW::g2functionRmax(double rm,double x){ double ans=1.0; if(x==0.0){ans = 1.0; return ans;} double xx = sqrt(1-x*x); double xxx = sqrt(x*x-1); double rmm = sqrt(rm*rm-1); double rmx = sqrt(rm*rm+x*x); if(x==1.0){ans = 4.0*(atanh(rm)-atanh(rmx/rm)+rmx/rm-1/rm)- 2.0*(-2-rm*rm+rm*rm*rm*rm+2*rmx)/3.0/rm/rm/rm/rmx; return ans;} ans = 4.0/x/x*(atanh(rm)-atanh(rmx/rm))-2.0*rm*(rmx-1)/(rmx*rmx-1)/(x*x-1); if(x>1.0){ans += 1/xxx*(4.0/x/x-2.0/(x*x-1.0))*(atan(rm/xxx)-atan(rm/xxx/rmx)); return ans;} if(x<1.0){ans -= 1/xx*(4.0/x/x-2.0/(x*x-1.0))*(atanh(rm/xx)-atanh(rm/xx/rmx)); return ans;} return ans; } double QuadTreeNFW::rhos(double x){ double ans; ans = 1.0; ans /= log(1+x) - x/(1+x); return ans; } /* Profiles with a flat interior and a power-law drop after rscale * All quantities should be divided by Sigma_crit to get the usual lens plane units. */ double QuadTreePseudoNFW::alpha_h(double r2,HaloStructure &par){ if(r2<=0.0) return 0.0; double b=0,r = sqrt(r2); b = -par.mass/r2/pi; if(r < par.Rmax) b *= mhat(r/par.rscale)/mhat(par.Rmax/par.rscale); return b; } double QuadTreePseudoNFW::kappa_h(double r2,HaloStructure &par){ if(r2 > par.Rmax*par.Rmax) return 0.0; if(r2 < 1.0-20) r2=1.0e-20; return par.mass/(2*pi*pow(par.rscale,2)*mhat(par.Rmax/par.rscale))/pow(1+sqrt(r2)/par.rscale,beta); } double QuadTreePseudoNFW::gamma_h(double r2,HaloStructure &par){ double gt=0; if( r2 <= 0.0) return 0.0; gt = -2.0*par.mass/pi/r2/r2; if(r2 < par.Rmax*par.Rmax){ double y = sqrt(r2)/par.rscale; //gt *= (1+2*y)*r2/pow(par.rscale,2)/mhat(par.Rmax/par.rscale)/pow(1+y,beta); gt *= -(y*y/pow(1+y,beta) - 2*mhat(y))/mhat(par.Rmax/par.rscale)/2; } return gt; } double QuadTreePseudoNFW::phi_h(double r2,HaloStructure &par){ ERROR_MESSAGE(); std::cout << "time delay has not been fixed for NFW profile yet." << std::endl; exit(1); return 0.0; } double QuadTreePseudoNFW::mhat(double y){ switch(beta){ case 1: return y - log(1+y); break; case 2: return log(1+y) - y/(1+y); break; default: return ( (1 - beta)*y + pow(1+y,beta-1) - 1)/(beta-2)/(beta-1)/pow(1+y,beta-1); //return - y/(beta-2)/pow(1+y,beta-1) - 1/(beta-2)/(beta-1)/pow(1+y,beta-1); break; } } /* * double QuadTreePseudoNFW::alpha_h(double r2,HaloStructure &par){ if(r2<=0.0) return 0.0; double b=0,r = sqrt(r2); b = -par.mass/r2/pi; if(r < par.Rmax) b *= mhat(r/par.rscale)/mhat(par.Rmax/par.rscale); return b; } double QuadTreePseudoNFW::kappa_h(double r2,HaloStructure &par){ if(r2 > par.Rmax*par.Rmax) return 0.0; if(r2 < 1.0-20) r2=1.0e-20; return par.mass/(2*pi*pow(par.rscale,2)*mhat(par.Rmax/par.rscale))/pow(1+sqrt(r2)/par.rscale,beta); } double QuadTreePseudoNFW::gamma_h(double r2,HaloStructure &par){ double gt=0; if( r2 <= 0.0) return 0.0; gt = -par.mass/pi/pow(r2,2); if(r2 < par.Rmax*par.Rmax){ double y = sqrt(r2)/par.rscale; gt *= (mhat(y) - 0.5*y*y/pow(1+y,beta))/mhat(sqrt(r2)/par.Rmax); } return gt; } double QuadTreePseudoNFW::phi_h(double r2,HaloStructure &par){ ERROR_MESSAGE(); std::cout << "time delay has not been fixed for NFW profile yet." << std::endl; exit(1); return 0.0; } double QuadTreePseudoNFW::mhat(double y){ return (1 + ( 1 + (beta-1)*y)/pow(y+1,beta-1) )/(beta-2)/(beta-1); } */ <commit_msg>corrected the new NFW functions<commit_after>/* * profiles.cpp * * Created on: Mar 6, 2012 * Author: bmetcalf */ #include <slsimlib.h> /// Gaussian particles double QuadTree::alpha_o(double r2,float sigma){ if(r2==0) return 0.0; if(sigma <= 0.0 ) return -1.0/r2/pi; return ( exp(-r2/sigma/sigma/2) - 1.0 )/r2/pi; } double QuadTree::kappa_o(double r2,float sigma){ if(sigma <= 0.0) return 0.0; return exp(-r2/sigma/sigma/2)/2/pi/sigma/sigma; } double QuadTree::gamma_o(double r2,float sigma){ if(r2==0) return 0.0; if(sigma <= 0.0) return -2.0/pi/pow(r2,2); return (-2.0 + (2.0 + r2/sigma/sigma)*exp(-r2/sigma/sigma/2) )/pi/pow(r2,2); } double QuadTree::phi_o(double r2,float sigma){ ERROR_MESSAGE(); // not yet written exit(1); return 0; } /** power-law profiles * All quantities should be divided by Sigma_crit to get the usual */ double QuadTreePowerLaw::alpha_h(double r2,HaloStructure &par){ if(r2==0) return 0.0; double b=0,r = sqrt(r2); b = -par.mass/r2/pi; if(r < par.Rmax) b *= pow(r/par.Rmax,beta+2); return b; } double QuadTreePowerLaw::kappa_h(double r2,HaloStructure &par){ if(r2 > par.Rmax*par.Rmax) return 0.0; if(r2 < 1.0-20) r2=1.0e-20; return (beta+2)*par.mass*pow(r2/par.Rmax/par.Rmax,beta/2)/(pi*pow(par.Rmax,2)); } double QuadTreePowerLaw::gamma_h(double r2,HaloStructure &par){ double gt=0; if( r2 <= 0.0) return 0.0; gt = -2.0*par.mass/pi/pow(r2,2); if(r2 < par.Rmax*par.Rmax) gt *= -beta*pow(r2/par.Rmax/par.Rmax,beta/2+1)/2; return gt; } double QuadTreePowerLaw::phi_h(double r2,HaloStructure &par){ double b; b=par.mass/pi; double r = sqrt(r2); if(r <= par.Rmax) return b*pow(r/par.Rmax,beta+2); return b*(log(r/par.Rmax) + 1); } // NFW profile // Gives the magnitude of the deflection angle modulo Sigma_crit double QuadTreeNFW::alpha_h(double r2,HaloStructure &par){ double b=0; if(r2 <= 0) return 0.0; b = -par.mass/r2/pi; double r = sqrt(r2); if(r < par.Rmax){ double y; y = par.Rmax/par.rscale; b *= rhos(y); y = r/par.rscale; b*= gfunction(y); } return b; } /// Convergence for an NFW halo double QuadTreeNFW::kappa_h(double r2,HaloStructure &par){ double r = sqrt(r2); if(r >= par.Rmax) return 0.0; if(r < 1.0-20) r=1.0e-20; double y,b; b = par.mass/2/pi/pow(par.rscale,2); y = par.Rmax/par.rscale; b *= rhos(y); y = r/par.rscale; b*= ffunction(y); return b; } /// Shear for and NFW halo. this might have a flaw in it double QuadTreeNFW::gamma_h(double r2,HaloStructure &par){ double gt=0; if(r2 <= 0.0) return 0.0; double r = sqrt(r2); gt = -2.0*par.mass/pi/r2/r2; if(r < par.Rmax){ double y; y = par.Rmax/par.rscale; gt *= rhos(y)*pow(r/par.rscale,2)/8.0; y = r/par.rscale; gt *= g2function(y); } return gt; } double QuadTreeNFW::phi_h(double r2,HaloStructure &par){ ERROR_MESSAGE(); std::cout << "time delay has not been fixed for NFW profile yet." << std::endl; exit(1); return 0.0; } double QuadTreeNFW::gfunction(double x){ double ans; ans=log(x/2); if(x==1.0){ ans += 1.0; return ans;} if(x>1.0){ ans += 2*atan(sqrt((x-1)/(x+1)))/sqrt(x*x-1);; return ans;} if(x<1.0){ ans += 2*atanh(sqrt((1-x)/(x+1)))/sqrt(1-x*x);; return ans;} return 0.0; } double QuadTreeNFW::ffunction(double x){ double ans; if(x==1.0){ return 1.0/3.0;} if(x>1.0){ ans = (1-2*atan(sqrt((x-1)/(x+1)))/sqrt(x*x-1))/(x*x-1); return ans;} if(x<1.0){ ans = (1-2*atanh(sqrt((1-x)/(x+1)))/sqrt(1-x*x))/(x*x-1); return ans;} return 0.0; } double QuadTreeNFW::g2function(double x){ double ans; if(x==1) return 10/3. + 4*log(0.5); ans=4*log(x/2.0)/x/x - 2/(x*x-1); if(x<1.0){ ans+= 4*(2/x/x+1/(x*x-1))*atanh(sqrt((1-x)/(x+1)))/sqrt(1-x*x); return ans;} if(x>1.0){ ans+= 4*(2/x/x+1/(x*x-1))*atan(sqrt((x-1)/(x+1)))/sqrt(x*x-1); return ans;} return 0.0; } double QuadTreeNFW::gfunctionRmax(double rm,double x){ double ans; double xx = sqrt(1-x*x); double xxx = sqrt(x*x-1); double rmm = log(rm*rm-1); double rmx = sqrt(rm*rm+x*x); ans = atanh(1.0/rm)-atanh(rm/rmx)+0.5*rmm; if(x==1.0){ ans += rmx/rm - 1/rm; return ans;} if(x>1.0){ ans += (atan(rm/xxx)-atan(rm/xxx/rmx))/xxx; return ans;} if(x<1.0){ ans -= (atanh(xx/rm)-atanh(xx*rmx/rm))/xx; return ans;} return 0.0; } double QuadTreeNFW::ffunctionRmax(double rm,double x){ double ans; double xx = sqrt(1-x*x); double xxx = sqrt(x*x-1); double rmx = sqrt(rm*rm+x*x); if(x==1.0){ ans = (-2-rm*rm+rm*rm*rm*rm+2*rmx)/3.0/rm/rm/rm/rmx; return ans; } ans = rm*(rmx-1)/(rmx*rmx-1)/(x*x-1); if(x>1.0){ ans += ((atan(rm/xxx)-atan(rm/xxx/rmx))/xxx)/(x*x-1); return ans;} if(x<1.0){ ans -= ((atanh(xx/rm)-atanh(xx*rmx/rm))/xx)/(x*x-1); return ans;} return 0.0; } double QuadTreeNFW::g2functionRmax(double rm,double x){ double ans=1.0; if(x==0.0){ans = 1.0; return ans;} double xx = sqrt(1-x*x); double xxx = sqrt(x*x-1); double rmm = log(rm*rm-1); double rmx = sqrt(rm*rm+x*x); if(x==1.0){ans = 2./3.*(-2./rm/rm/rm-6./rm+2./rm/rm/rm/rmx+7./rm/rmx+ 5.*rm/rmx+6.*atanh(1./rm)-6.*atanh(rm/rmx)+3.*rmm); return ans;} ans = 4.0/x/x*(atanh(1.0/rm)-atanh(rm/rmx)+0.5*rmm)-2.0*rm*(rmx-1)/(rmx*rmx-1)/(x*x-1); if(x>1.0){ans += 1/xxx*(4.0/x/x+2.0/(x*x-1.0))*(atan(rm/xxx)-atan(rm/xxx/rmx)); return ans;} if(x<1.0){ans -= 1/xx*(4.0/x/x+2.0/(x*x-1.0))*(atanh(xx/rm)-atanh(xx*rmx/xx)); return ans;} return ans; } double QuadTreeNFW::rhos(double x){ double ans; ans = 1.0; ans /= log(1+x) - x/(1+x); return ans; } /* Profiles with a flat interior and a power-law drop after rscale * All quantities should be divided by Sigma_crit to get the usual lens plane units. */ double QuadTreePseudoNFW::alpha_h(double r2,HaloStructure &par){ if(r2<=0.0) return 0.0; double b=0,r = sqrt(r2); b = -par.mass/r2/pi; if(r < par.Rmax) b *= mhat(r/par.rscale)/mhat(par.Rmax/par.rscale); return b; } double QuadTreePseudoNFW::kappa_h(double r2,HaloStructure &par){ if(r2 > par.Rmax*par.Rmax) return 0.0; if(r2 < 1.0-20) r2=1.0e-20; return par.mass/(2*pi*pow(par.rscale,2)*mhat(par.Rmax/par.rscale))/pow(1+sqrt(r2)/par.rscale,beta); } double QuadTreePseudoNFW::gamma_h(double r2,HaloStructure &par){ double gt=0; if( r2 <= 0.0) return 0.0; gt = -2.0*par.mass/pi/r2/r2; if(r2 < par.Rmax*par.Rmax){ double y = sqrt(r2)/par.rscale; //gt *= (1+2*y)*r2/pow(par.rscale,2)/mhat(par.Rmax/par.rscale)/pow(1+y,beta); gt *= -(y*y/pow(1+y,beta) - 2*mhat(y))/mhat(par.Rmax/par.rscale)/2; } return gt; } double QuadTreePseudoNFW::phi_h(double r2,HaloStructure &par){ ERROR_MESSAGE(); std::cout << "time delay has not been fixed for NFW profile yet." << std::endl; exit(1); return 0.0; } double QuadTreePseudoNFW::mhat(double y){ switch(beta){ case 1: return y - log(1+y); break; case 2: return log(1+y) - y/(1+y); break; default: return ( (1 - beta)*y + pow(1+y,beta-1) - 1)/(beta-2)/(beta-1)/pow(1+y,beta-1); //return - y/(beta-2)/pow(1+y,beta-1) - 1/(beta-2)/(beta-1)/pow(1+y,beta-1); break; } } /* * double QuadTreePseudoNFW::alpha_h(double r2,HaloStructure &par){ if(r2<=0.0) return 0.0; double b=0,r = sqrt(r2); b = -par.mass/r2/pi; if(r < par.Rmax) b *= mhat(r/par.rscale)/mhat(par.Rmax/par.rscale); return b; } double QuadTreePseudoNFW::kappa_h(double r2,HaloStructure &par){ if(r2 > par.Rmax*par.Rmax) return 0.0; if(r2 < 1.0-20) r2=1.0e-20; return par.mass/(2*pi*pow(par.rscale,2)*mhat(par.Rmax/par.rscale))/pow(1+sqrt(r2)/par.rscale,beta); } double QuadTreePseudoNFW::gamma_h(double r2,HaloStructure &par){ double gt=0; if( r2 <= 0.0) return 0.0; gt = -par.mass/pi/pow(r2,2); if(r2 < par.Rmax*par.Rmax){ double y = sqrt(r2)/par.rscale; gt *= (mhat(y) - 0.5*y*y/pow(1+y,beta))/mhat(sqrt(r2)/par.Rmax); } return gt; } double QuadTreePseudoNFW::phi_h(double r2,HaloStructure &par){ ERROR_MESSAGE(); std::cout << "time delay has not been fixed for NFW profile yet." << std::endl; exit(1); return 0.0; } double QuadTreePseudoNFW::mhat(double y){ return (1 + ( 1 + (beta-1)*y)/pow(y+1,beta-1) )/(beta-2)/(beta-1); } */ <|endoftext|>
<commit_before>// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <memory> #include "SurgSim/Physics/PhysicsManager.h" #include "SurgSim/Framework/ApplicationData.h" #include "SurgSim/Framework/BehaviorManager.h" #include "SurgSim/Framework/Runtime.h" #include "SurgSim/Framework/Scene.h" #include "SurgSim/Framework/Log.h" #include "SurgSim/Framework/TransferPropertiesBehavior.h" #include "SurgSim/Graphics/Light.h" #include "SurgSim/Graphics/OsgBoxRepresentation.h" #include "SurgSim/Graphics/OsgSphereRepresentation.h" #include "SurgSim/Graphics/OsgCamera.h" #include "SurgSim/Graphics/OsgGroup.h" #include "SurgSim/Graphics/OsgLight.h" #include "SurgSim/Graphics/OsgManager.h" #include "SurgSim/Graphics/OsgMaterial.h" #include "SurgSim/Graphics/OsgRenderTarget.h" #include "SurgSim/Graphics/OsgShader.h" #include "SurgSim/Graphics/OsgUniform.h" #include "SurgSim/Graphics/OsgTexture2d.h" #include "SurgSim/Graphics/OsgView.h" #include "SurgSim/Graphics/OsgViewElement.h" #include "SurgSim/Graphics/RenderPass.h" #include "SurgSim/Blocks/BasicSceneElement.h" #include "SurgSim/Math/Vector.h" #include "SurgSim/Math/Quaternion.h" #include "SurgSim/Math/RigidTransform.h" #include "SurgSim/Math/Matrix.h" using SurgSim::Math::Vector3d; using SurgSim::Math::Vector4d; using SurgSim::Math::Matrix44f; using SurgSim::Math::Quaterniond; using SurgSim::Math::RigidTransform3d; using SurgSim::Math::makeRigidTransform; using SurgSim::Framework::Logger; using SurgSim::Graphics::OsgUniform; using SurgSim::Graphics::OsgTextureUniform; using SurgSim::Graphics::OsgTexture2d; #include <osg/Matrix> #include <osg/Camera> #include "SurgSim/Blocks/PoseInterpolator.h" /// \file /// This example creates a simple graphics scene and use the RenderPass object to show /// a simple shadowing algorithm. For the algorithm see http://en.wikipedia.org/wiki/Shadow_mapping /// There are two preprocessing passes that use specific shaders, plus a main pass that renders the /// objects using a shaders that can process the output from the preprocessing steps. /// Each shaders output becomes the input for the next shader, some parameters from other scene elements /// is passed into the shaders as uniforms. /// All of the information is kept up to date using a \sa TransferPropertiesBehavior /// Both the light and the main camera are being moved through a \sa PoseInterpolator to demonstrate /// dynamic changes and how to handle them in the rendering pipeline namespace { std::unordered_map<std::string, std::shared_ptr<SurgSim::Graphics::OsgMaterial>> materials; std::shared_ptr<SurgSim::Graphics::OsgMaterial> loadMaterial( const SurgSim::Framework::ApplicationData& data, const std::string& name) { std::string vertexShaderName = name+".vert"; std::string fragmentShaderName = name+".frag"; std::string filename; auto shader(std::make_shared<SurgSim::Graphics::OsgShader>()); bool success = true; filename = data.findFile(vertexShaderName); if (filename == "") { SURGSIM_LOG_WARNING(Logger::getDefaultLogger()) << "Could not find vertex shader " << vertexShaderName; success = false; } else if (! shader->loadVertexShaderSource(filename)) { SURGSIM_LOG_WARNING(Logger::getDefaultLogger()) << "Could not load vertex shader " << vertexShaderName; success = false; } filename = data.findFile(fragmentShaderName); if (filename == "") { SURGSIM_LOG_WARNING(Logger::getDefaultLogger()) << "Could not find fragment shader " << fragmentShaderName; success = false; } if (! shader->loadFragmentShaderSource(filename)) { SURGSIM_LOG_WARNING(Logger::getDefaultLogger()) << "Could not load fragment shader " << fragmentShaderName; success = false; } std::shared_ptr<SurgSim::Graphics::OsgMaterial> material; if (success) { material = std::make_shared<SurgSim::Graphics::OsgMaterial>(); material->setShader(shader); } return material; } std::shared_ptr<SurgSim::Graphics::ViewElement> createView(const std::string& name, int x, int y, int width, int height) { using SurgSim::Graphics::OsgViewElement; std::shared_ptr<OsgViewElement> viewElement = std::make_shared<OsgViewElement>(name); viewElement->getView()->setPosition(x, y); viewElement->getView()->setDimensions(width, height); auto light = std::make_shared<SurgSim::Graphics::OsgLight>("Main Light"); light->setAmbientColor(Vector4d(0.5,0.5,0.5,1.0)); light->setDiffuseColor(Vector4d(0.5,0.5,0.5,1.0)); light->setSpecularColor(Vector4d(0.8,0.8,0.8,1.0)); light->setInitialPose(makeRigidTransform(Vector3d(-4.0, 2.0, -4.0), Vector3d(0.0,0.0,0.0), Vector3d(0.0,1.0,0.0))); viewElement->addComponent(light); // Move the light from left to right over along the scene auto interpolator = std::make_shared<SurgSim::Blocks::PoseInterpolator>("Interpolator"); RigidTransform3d from = makeRigidTransform(Vector3d(4.0, 3.0, -4.0), Vector3d(0.0,0.0,0.0), Vector3d(0.0,1.0,0.0)); RigidTransform3d to = makeRigidTransform(Vector3d(-4.0, 3.0, -4.0), Vector3d(0.0,0.0,0.0), Vector3d(0.0,1.0,0.0)); interpolator->setTarget(light); interpolator->setStartingPose(from); interpolator->setDuration(10.0); interpolator->setEndingPose(to); interpolator->setPingPong(true); viewElement->addComponent(interpolator); return viewElement; } /// Create the pass that renders the scene from the view of the light source /// the identifier 'shadowing' is used in all graphic objects to mark them as used /// in this pass std::shared_ptr<SurgSim::Graphics::RenderPass> createLightMapPass() { auto pass = std::make_shared<SurgSim::Graphics::RenderPass>("shadowing"); auto renderTarget = std::make_shared<SurgSim::Graphics::OsgRenderTarget2d>(1024, 1024, 1.0, 1, false); pass->setRenderTarget(renderTarget); pass->setRenderOrder(SurgSim::Graphics::Camera::RENDER_ORDER_PRE_RENDER, 0); materials["depthMap"]->getShader()->setGlobalScope(true); pass->setMaterial(materials["depthMap"]); return pass; } /// Create the pass that renders shadowed pixels into the scene, /// the identifier 'shadowed' can be used in all graphics objects to mark them /// as used in this pass std::shared_ptr<SurgSim::Graphics::RenderPass> createShadowMapPass() { auto pass = std::make_shared<SurgSim::Graphics::RenderPass>("shadowed"); auto renderTarget = std::make_shared<SurgSim::Graphics::OsgRenderTarget2d>(1024, 1024, 1.0, 1, false); pass->setRenderTarget(renderTarget); pass->setRenderOrder(SurgSim::Graphics::Camera::RENDER_ORDER_PRE_RENDER, 1); materials["shadowMap"]->getShader()->setGlobalScope(true); pass->setMaterial(materials["shadowMap"]); return pass; } /// A simple box as a scenelement class SimpleBox : public SurgSim::Blocks::BasicSceneElement { public: explicit SimpleBox(const std::string& name) : BasicSceneElement(name) { m_box = std::make_shared<SurgSim::Graphics::OsgBoxRepresentation>(getName()+" Graphics"); m_box->setInitialPose(RigidTransform3d::Identity()); // The material that this object uses m_box->setMaterial(materials["basicShadowed"]); // Assign this to the pass for shadowing objects m_box->addGroupReference("shadowing"); // Assign this to the pass for shadowed objects m_box->addGroupReference("shadowed"); } virtual bool doInitialize() override { addComponent(m_box); return true; } void setSize(double width, double height, double length) { m_box->setSize(width, height, length); } void setPose(const RigidTransform3d& pose) { m_box->setPose(pose); } private: std::shared_ptr<SurgSim::Graphics::OsgBoxRepresentation> m_box; }; class SimpleSphere : public SurgSim::Blocks::BasicSceneElement { public: explicit SimpleSphere(const std::string& name) : BasicSceneElement(name) { m_sphere = std::make_shared<SurgSim::Graphics::OsgSphereRepresentation>(getName()+" Graphics"); m_sphere->setInitialPose(RigidTransform3d::Identity()); m_sphere->setMaterial(materials["basicShadowed"]); m_sphere->addGroupReference("shadowing"); m_sphere->addGroupReference("shadowed"); } virtual bool doInitialize() override { addComponent(m_sphere); return true; } void setRadius(double radius) { m_sphere->setRadius(radius); } void setPose(const RigidTransform3d& pose) { m_sphere->setPose(pose); } private: std::shared_ptr<SurgSim::Graphics::OsgSphereRepresentation> m_sphere; }; } // Create an array of spheres void addSpheres(std::shared_ptr<SurgSim::Framework::Scene> scene) { double radius = 0.05; Vector3d origin (-1.0, 0.0, -1.0); Vector3d spacing (0.5, 0.5, 0.5); for (int i=0; i<3; ++i) { for (int j=0; j<3; ++j) { auto sphere = std::make_shared<SimpleSphere>("Sphere_"+std::to_string(i*3+j)); sphere->setRadius(radius); Vector3d position = origin + Vector3d(spacing.array() * Vector3d(i,1.0,j).array()); sphere->setPose(makeRigidTransform(Quaterniond::Identity(), position)); scene->addSceneElement(sphere); } } } void createScene(std::shared_ptr<SurgSim::Framework::Runtime> runtime) { auto scene = runtime->getScene(); auto box = std::make_shared<SimpleBox>("Plane"); box->setSize(3,0.01,3); box->setPose(RigidTransform3d::Identity()); scene->addSceneElement(box); box = std::make_shared<SimpleBox>("Box 1"); box->setSize(1.0,2.0,3.0); box->setPose(RigidTransform3d::Identity()); scene->addSceneElement(box); scene->addSceneElement(createView("View", 0, 0, 1023, 768)); } int main(int argc, char* argv[]) { const SurgSim::Framework::ApplicationData data("config.txt"); materials["basicLit"] = loadMaterial(data, "Shaders/basic_lit"); materials["basicUnlit"] = loadMaterial(data, "Shaders/basic_unlit"); materials["basicShadowed"] = loadMaterial(data, "Shaders/shadowmap_vertexcolor"); materials["depthMap"] = loadMaterial(data, "Shaders/depth_map"); materials["shadowMap"] = loadMaterial(data, "Shaders/shadow_map"); materials["default"] = materials["basic_lit"]; auto runtime(std::make_shared<SurgSim::Framework::Runtime>()); auto graphicsManager = std::make_shared<SurgSim::Graphics::OsgManager>(); graphicsManager->getDefaultCamera()->setInitialPose( SurgSim::Math::makeRigidTransform(SurgSim::Math::Quaterniond::Identity(), Vector3d(0.5, 0.5, 0.5))); runtime->addManager(graphicsManager); runtime->addManager(std::make_shared<SurgSim::Framework::BehaviorManager>()); createScene(runtime); runtime->execute(); return 0; } <commit_msg>Fix build failure in VS 2010 due to std::to_string<commit_after>// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <memory> #include "SurgSim/Physics/PhysicsManager.h" #include "SurgSim/Framework/ApplicationData.h" #include "SurgSim/Framework/BehaviorManager.h" #include "SurgSim/Framework/Runtime.h" #include "SurgSim/Framework/Scene.h" #include "SurgSim/Framework/Log.h" #include "SurgSim/Framework/TransferPropertiesBehavior.h" #include "SurgSim/Graphics/Light.h" #include "SurgSim/Graphics/OsgBoxRepresentation.h" #include "SurgSim/Graphics/OsgSphereRepresentation.h" #include "SurgSim/Graphics/OsgCamera.h" #include "SurgSim/Graphics/OsgGroup.h" #include "SurgSim/Graphics/OsgLight.h" #include "SurgSim/Graphics/OsgManager.h" #include "SurgSim/Graphics/OsgMaterial.h" #include "SurgSim/Graphics/OsgRenderTarget.h" #include "SurgSim/Graphics/OsgShader.h" #include "SurgSim/Graphics/OsgUniform.h" #include "SurgSim/Graphics/OsgTexture2d.h" #include "SurgSim/Graphics/OsgView.h" #include "SurgSim/Graphics/OsgViewElement.h" #include "SurgSim/Graphics/RenderPass.h" #include "SurgSim/Blocks/BasicSceneElement.h" #include "SurgSim/Math/Vector.h" #include "SurgSim/Math/Quaternion.h" #include "SurgSim/Math/RigidTransform.h" #include "SurgSim/Math/Matrix.h" using SurgSim::Math::Vector3d; using SurgSim::Math::Vector4d; using SurgSim::Math::Matrix44f; using SurgSim::Math::Quaterniond; using SurgSim::Math::RigidTransform3d; using SurgSim::Math::makeRigidTransform; using SurgSim::Framework::Logger; using SurgSim::Graphics::OsgUniform; using SurgSim::Graphics::OsgTextureUniform; using SurgSim::Graphics::OsgTexture2d; #include <osg/Matrix> #include <osg/Camera> #include "SurgSim/Blocks/PoseInterpolator.h" /// \file /// This example creates a simple graphics scene and use the RenderPass object to show /// a simple shadowing algorithm. For the algorithm see http://en.wikipedia.org/wiki/Shadow_mapping /// There are two preprocessing passes that use specific shaders, plus a main pass that renders the /// objects using a shaders that can process the output from the preprocessing steps. /// Each shaders output becomes the input for the next shader, some parameters from other scene elements /// is passed into the shaders as uniforms. /// All of the information is kept up to date using a \sa TransferPropertiesBehavior /// Both the light and the main camera are being moved through a \sa PoseInterpolator to demonstrate /// dynamic changes and how to handle them in the rendering pipeline namespace { std::unordered_map<std::string, std::shared_ptr<SurgSim::Graphics::OsgMaterial>> materials; std::shared_ptr<SurgSim::Graphics::OsgMaterial> loadMaterial( const SurgSim::Framework::ApplicationData& data, const std::string& name) { std::string vertexShaderName = name+".vert"; std::string fragmentShaderName = name+".frag"; std::string filename; auto shader(std::make_shared<SurgSim::Graphics::OsgShader>()); bool success = true; filename = data.findFile(vertexShaderName); if (filename == "") { SURGSIM_LOG_WARNING(Logger::getDefaultLogger()) << "Could not find vertex shader " << vertexShaderName; success = false; } else if (! shader->loadVertexShaderSource(filename)) { SURGSIM_LOG_WARNING(Logger::getDefaultLogger()) << "Could not load vertex shader " << vertexShaderName; success = false; } filename = data.findFile(fragmentShaderName); if (filename == "") { SURGSIM_LOG_WARNING(Logger::getDefaultLogger()) << "Could not find fragment shader " << fragmentShaderName; success = false; } if (! shader->loadFragmentShaderSource(filename)) { SURGSIM_LOG_WARNING(Logger::getDefaultLogger()) << "Could not load fragment shader " << fragmentShaderName; success = false; } std::shared_ptr<SurgSim::Graphics::OsgMaterial> material; if (success) { material = std::make_shared<SurgSim::Graphics::OsgMaterial>(); material->setShader(shader); } return material; } std::shared_ptr<SurgSim::Graphics::ViewElement> createView(const std::string& name, int x, int y, int width, int height) { using SurgSim::Graphics::OsgViewElement; std::shared_ptr<OsgViewElement> viewElement = std::make_shared<OsgViewElement>(name); viewElement->getView()->setPosition(x, y); viewElement->getView()->setDimensions(width, height); auto light = std::make_shared<SurgSim::Graphics::OsgLight>("Main Light"); light->setAmbientColor(Vector4d(0.5,0.5,0.5,1.0)); light->setDiffuseColor(Vector4d(0.5,0.5,0.5,1.0)); light->setSpecularColor(Vector4d(0.8,0.8,0.8,1.0)); light->setInitialPose(makeRigidTransform(Vector3d(-4.0, 2.0, -4.0), Vector3d(0.0,0.0,0.0), Vector3d(0.0,1.0,0.0))); viewElement->addComponent(light); // Move the light from left to right over along the scene auto interpolator = std::make_shared<SurgSim::Blocks::PoseInterpolator>("Interpolator"); RigidTransform3d from = makeRigidTransform(Vector3d(4.0, 3.0, -4.0), Vector3d(0.0,0.0,0.0), Vector3d(0.0,1.0,0.0)); RigidTransform3d to = makeRigidTransform(Vector3d(-4.0, 3.0, -4.0), Vector3d(0.0,0.0,0.0), Vector3d(0.0,1.0,0.0)); interpolator->setTarget(light); interpolator->setStartingPose(from); interpolator->setDuration(10.0); interpolator->setEndingPose(to); interpolator->setPingPong(true); viewElement->addComponent(interpolator); return viewElement; } /// Create the pass that renders the scene from the view of the light source /// the identifier 'shadowing' is used in all graphic objects to mark them as used /// in this pass std::shared_ptr<SurgSim::Graphics::RenderPass> createLightMapPass() { auto pass = std::make_shared<SurgSim::Graphics::RenderPass>("shadowing"); auto renderTarget = std::make_shared<SurgSim::Graphics::OsgRenderTarget2d>(1024, 1024, 1.0, 1, false); pass->setRenderTarget(renderTarget); pass->setRenderOrder(SurgSim::Graphics::Camera::RENDER_ORDER_PRE_RENDER, 0); materials["depthMap"]->getShader()->setGlobalScope(true); pass->setMaterial(materials["depthMap"]); return pass; } /// Create the pass that renders shadowed pixels into the scene, /// the identifier 'shadowed' can be used in all graphics objects to mark them /// as used in this pass std::shared_ptr<SurgSim::Graphics::RenderPass> createShadowMapPass() { auto pass = std::make_shared<SurgSim::Graphics::RenderPass>("shadowed"); auto renderTarget = std::make_shared<SurgSim::Graphics::OsgRenderTarget2d>(1024, 1024, 1.0, 1, false); pass->setRenderTarget(renderTarget); pass->setRenderOrder(SurgSim::Graphics::Camera::RENDER_ORDER_PRE_RENDER, 1); materials["shadowMap"]->getShader()->setGlobalScope(true); pass->setMaterial(materials["shadowMap"]); return pass; } /// A simple box as a scenelement class SimpleBox : public SurgSim::Blocks::BasicSceneElement { public: explicit SimpleBox(const std::string& name) : BasicSceneElement(name) { m_box = std::make_shared<SurgSim::Graphics::OsgBoxRepresentation>(getName()+" Graphics"); m_box->setInitialPose(RigidTransform3d::Identity()); // The material that this object uses m_box->setMaterial(materials["basicShadowed"]); // Assign this to the pass for shadowing objects m_box->addGroupReference("shadowing"); // Assign this to the pass for shadowed objects m_box->addGroupReference("shadowed"); } virtual bool doInitialize() override { addComponent(m_box); return true; } void setSize(double width, double height, double length) { m_box->setSize(width, height, length); } void setPose(const RigidTransform3d& pose) { m_box->setPose(pose); } private: std::shared_ptr<SurgSim::Graphics::OsgBoxRepresentation> m_box; }; class SimpleSphere : public SurgSim::Blocks::BasicSceneElement { public: explicit SimpleSphere(const std::string& name) : BasicSceneElement(name) { m_sphere = std::make_shared<SurgSim::Graphics::OsgSphereRepresentation>(getName()+" Graphics"); m_sphere->setInitialPose(RigidTransform3d::Identity()); m_sphere->setMaterial(materials["basicShadowed"]); m_sphere->addGroupReference("shadowing"); m_sphere->addGroupReference("shadowed"); } virtual bool doInitialize() override { addComponent(m_sphere); return true; } void setRadius(double radius) { m_sphere->setRadius(radius); } void setPose(const RigidTransform3d& pose) { m_sphere->setPose(pose); } private: std::shared_ptr<SurgSim::Graphics::OsgSphereRepresentation> m_sphere; }; } // Create an array of spheres void addSpheres(std::shared_ptr<SurgSim::Framework::Scene> scene) { double radius = 0.05; Vector3d origin (-1.0, 0.0, -1.0); Vector3d spacing (0.5, 0.5, 0.5); for (int i=0; i<3; ++i) { for (int j=0; j<3; ++j) { auto sphere = std::make_shared<SimpleSphere>("Sphere_"+std::to_string(static_cast<long long>(i*3+j))); sphere->setRadius(radius); Vector3d position = origin + Vector3d(spacing.array() * Vector3d(i,1.0,j).array()); sphere->setPose(makeRigidTransform(Quaterniond::Identity(), position)); scene->addSceneElement(sphere); } } } void createScene(std::shared_ptr<SurgSim::Framework::Runtime> runtime) { auto scene = runtime->getScene(); auto box = std::make_shared<SimpleBox>("Plane"); box->setSize(3,0.01,3); box->setPose(RigidTransform3d::Identity()); scene->addSceneElement(box); box = std::make_shared<SimpleBox>("Box 1"); box->setSize(1.0,2.0,3.0); box->setPose(RigidTransform3d::Identity()); scene->addSceneElement(box); scene->addSceneElement(createView("View", 0, 0, 1023, 768)); } int main(int argc, char* argv[]) { const SurgSim::Framework::ApplicationData data("config.txt"); materials["basicLit"] = loadMaterial(data, "Shaders/basic_lit"); materials["basicUnlit"] = loadMaterial(data, "Shaders/basic_unlit"); materials["basicShadowed"] = loadMaterial(data, "Shaders/shadowmap_vertexcolor"); materials["depthMap"] = loadMaterial(data, "Shaders/depth_map"); materials["shadowMap"] = loadMaterial(data, "Shaders/shadow_map"); materials["default"] = materials["basic_lit"]; auto runtime(std::make_shared<SurgSim::Framework::Runtime>()); auto graphicsManager = std::make_shared<SurgSim::Graphics::OsgManager>(); graphicsManager->getDefaultCamera()->setInitialPose( SurgSim::Math::makeRigidTransform(SurgSim::Math::Quaterniond::Identity(), Vector3d(0.5, 0.5, 0.5))); runtime->addManager(graphicsManager); runtime->addManager(std::make_shared<SurgSim::Framework::BehaviorManager>()); createScene(runtime); runtime->execute(); return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: unicode.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: vg $ $Date: 2003-04-24 12:25:59 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef INCLUDED_I18NUTIL_UNICODE_HXX #define INCLUDED_I18NUTIL_UNICODE_HXX #include <com/sun/star/i18n/UnicodeScript.hpp> #include <sal/types.h> typedef struct _ScriptTypeList { sal_Int16 from; sal_Int16 to; } ScriptTypeList; class unicode { public: static sal_Int16 SAL_CALL getUnicodeType( const sal_Unicode ch ); static sal_Bool SAL_CALL isUnicodeScriptType( const sal_Unicode ch, sal_Int16 type); static sal_Int16 SAL_CALL getUnicodeScriptType( const sal_Unicode ch, ScriptTypeList *typeList = NULL, sal_Int16 unknownType = 0 ); static sal_uInt8 SAL_CALL getUnicodeDirection( const sal_Unicode ch ); static sal_Int32 SAL_CALL getCharType( const sal_Unicode ch ); static sal_Bool SAL_CALL isUpper( const sal_Unicode ch); static sal_Bool SAL_CALL isLower( const sal_Unicode ch); static sal_Bool SAL_CALL isTitle( const sal_Unicode ch); static sal_Bool SAL_CALL isDigit( const sal_Unicode ch); static sal_Bool SAL_CALL isControl( const sal_Unicode ch); static sal_Bool SAL_CALL isPrint( const sal_Unicode ch); static sal_Bool SAL_CALL isBase( const sal_Unicode ch); static sal_Bool SAL_CALL isAlpha( const sal_Unicode ch); static sal_Bool SAL_CALL isSpace( const sal_Unicode ch); static sal_Bool SAL_CALL isWhiteSpace( const sal_Unicode ch); static sal_Bool SAL_CALL isAlphaDigit( const sal_Unicode ch); static sal_Bool SAL_CALL isPunctuation( const sal_Unicode ch); }; #endif <commit_msg>INTEGRATION: CWS i18n09 (1.2.30); FILE MERGED 2003/11/18 22:30:37 khong 1.2.30.1: #i21290# #i22530# #i14640# extend CTL script support, extend Greek script type<commit_after>/************************************************************************* * * $RCSfile: unicode.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hr $ $Date: 2004-03-08 17:12:43 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef INCLUDED_I18NUTIL_UNICODE_HXX #define INCLUDED_I18NUTIL_UNICODE_HXX #include <com/sun/star/i18n/UnicodeScript.hpp> #include <sal/types.h> typedef struct _ScriptTypeList { sal_Int16 from; sal_Int16 to; sal_Int16 value; } ScriptTypeList; class unicode { public: static sal_Int16 SAL_CALL getUnicodeType( const sal_Unicode ch ); static sal_Bool SAL_CALL isUnicodeScriptType( const sal_Unicode ch, sal_Int16 type); static sal_Int16 SAL_CALL getUnicodeScriptType( const sal_Unicode ch, ScriptTypeList *typeList = NULL, sal_Int16 unknownType = 0 ); static sal_uInt8 SAL_CALL getUnicodeDirection( const sal_Unicode ch ); static sal_Int32 SAL_CALL getCharType( const sal_Unicode ch ); static sal_Bool SAL_CALL isUpper( const sal_Unicode ch); static sal_Bool SAL_CALL isLower( const sal_Unicode ch); static sal_Bool SAL_CALL isTitle( const sal_Unicode ch); static sal_Bool SAL_CALL isDigit( const sal_Unicode ch); static sal_Bool SAL_CALL isControl( const sal_Unicode ch); static sal_Bool SAL_CALL isPrint( const sal_Unicode ch); static sal_Bool SAL_CALL isBase( const sal_Unicode ch); static sal_Bool SAL_CALL isAlpha( const sal_Unicode ch); static sal_Bool SAL_CALL isSpace( const sal_Unicode ch); static sal_Bool SAL_CALL isWhiteSpace( const sal_Unicode ch); static sal_Bool SAL_CALL isAlphaDigit( const sal_Unicode ch); static sal_Bool SAL_CALL isPunctuation( const sal_Unicode ch); }; #endif <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: ImageMutualInformation1.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm 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. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif // Software Guide : BeginLatex // // This example illustrates how to compute the Mutual Information between two // images using classes from the Statistics framework. Note that you could also // use for this purpose the ImageMetrics designed for the image registration // framework. // // For example: // // \doxygen{MutualInformationImageToImageMetric} // \doxygen{MattesMutualInformationImageToImageMetric} // \doxygen{MutualInformationHistogramImageToImageMetric} // \doxygen{MutualInformationImageToImageMetric} // \doxygen{NormalizedMutualInformationHistogramImageToImageMetric} // \doxygen{KullbackLeiblerCompareHistogramImageToImageMetric} // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "itkImageToHistogramGenerator.h" #include "itkImage.h" #include "itkImageFileReader.h" #include "itkJoinImageFilter.h" int main( int argc, char * argv [] ) { if( argc < 3 ) { std::cerr << "Missing command line arguments" << std::endl; std::cerr << "Usage : ImageHistogram1 inputImage1 inputImage2 " << std::endl; return -1; } typedef unsigned char PixelComponentType; const unsigned int Dimension = 2; typedef itk::Image< PixelComponentType, Dimension > ImageType; typedef itk::JoinImageFilter< ImageType, ImageType > JoinFilterType; JoinFilterType::Pointer joinFilter = JoinFilterType::New(); typedef itk::ImageFileReader< ImageType > ReaderType; ReaderType::Pointer reader1 = ReaderType::New(); ReaderType::Pointer reader2 = ReaderType::New(); reader1->SetFileName( argv[1] ); reader2->SetFileName( argv[2] ); joinFilter->SetInput1( reader1->GetOutput() ); joinFilter->SetInput2( reader2->GetOutput() ); try { joinFilter->Update(); } catch( itk::ExceptionObject & excp ) { std::cerr << excp << std::endl; return -1; } typedef JoinFilterType::OutputImageType VectorImageType; typedef itk::Statistics::ImageToHistogramGenerator< VectorImageType > HistogramGeneratorType; typedef HistogramGeneratorType::SizeType SizeType; SizeType size; size[0] = 255; // number of bins for the first channel size[1] = 1; // number of bins for the second channel HistogramGeneratorType::Pointer histogramGenerator = HistogramGeneratorType::New(); histogramGenerator->SetInput( joinFilter->GetOutput() ); histogramGenerator->SetNumberOfBins( size ); histogramGenerator->SetMarginalScale( 10.0 ); histogramGenerator->Compute(); typedef HistogramGeneratorType::HistogramType HistogramType; const HistogramType * histogram = histogramGenerator->GetOutput(); const unsigned int histogramSize = histogram->Size(); std::cout << "Histogram size = " << histogramSize << std::endl; // Compute the Entropy of the distribution of intensities HistogramType::ConstIterator itr = histogram->Begin(); HistogramType::ConstIterator end = histogram->End(); double Sum = histogram->GetTotalFrequency(); double Entropy1 = 0.0; while( itr != end ) { const double probability = itr.GetFrequency() / Sum; if( probability > 1e-16 ) { Entropy1 += - probability * log( probability ) / log( 2.0 ); } ++itr; } std::cout << "Image1 Entropy = " << Entropy1 << " bits " << std::endl; // Now compute the histogram for the second component size[0] = 1; // number of bins for the first channel size[1] = 255; // number of bins for the second channel histogramGenerator->SetNumberOfBins( size ); histogramGenerator->SetMarginalScale( 10.0 ); histogramGenerator->Compute(); itr = histogram->Begin(); end = histogram->End(); Sum = histogram->GetTotalFrequency(); double Entropy2 = 0.0; while( itr != end ) { const double probability = itr.GetFrequency() / Sum; if( probability > 1e-16 ) { Entropy2 += - probability * log( probability ) / log( 2.0 ); } ++itr; } std::cout << "Image2 Entropy = " << Entropy2 << " bits " << std::endl; // Now compute the joint histogram for the two components size[0] = 255; // number of bins for the first channel size[1] = 255; // number of bins for the second channel histogramGenerator->SetNumberOfBins( size ); histogramGenerator->SetMarginalScale( 10.0 ); histogramGenerator->Compute(); itr = histogram->Begin(); end = histogram->End(); Sum = histogram->GetTotalFrequency(); double JointEntropy = 0.0; while( itr != end ) { const double probability = itr.GetFrequency() / Sum; if( probability > 1e-16 ) { JointEntropy += - probability * log( probability ) / log( 2.0 ); } ++itr; } std::cout << "Joint Entropy = " << JointEntropy << " bits " << std::endl; double MutualInformation = Entropy1 + Entropy2 - JointEntropy; std::cout << "Mutual Information = " << MutualInformation << " bits " << std::endl; // Different types of Normalization have been proposed for Mutual Information. double NormalizedMutualInformation1 = 2.0 * MutualInformation / ( Entropy1 + Entropy2 ); std::cout << "Normalized Mutual Information 1 = " << NormalizedMutualInformation1 << std::endl; double NormalizedMutualInformation2 = ( Entropy1 + Entropy2 ) / JointEntropy; std::cout << "Normalized Mutual Information 2 = " << NormalizedMutualInformation2 << std::endl; return 0; // Software Guide : EndCodeSnippet } <commit_msg>STYLE: Adding comments for the Software Guide.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: ImageMutualInformation1.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm 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. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif // Software Guide : BeginLatex // // This example illustrates how to compute the Mutual Information between two // images using classes from the Statistics framework. Note that you could also // use for this purpose the ImageMetrics designed for the image registration // framework. // // For example, you could use: // // \doxygen{MutualInformationImageToImageMetric} // \doxygen{MattesMutualInformationImageToImageMetric} // \doxygen{MutualInformationHistogramImageToImageMetric} // \doxygen{MutualInformationImageToImageMetric} // \doxygen{NormalizedMutualInformationHistogramImageToImageMetric} // \doxygen{KullbackLeiblerCompareHistogramImageToImageMetric} // // Mutual Information as computed in this example, and as commonly used in the // context of image registration provides a measure of how much uncertainty on // the value of a pixel in one image is reduced by measuring the homologous // pixel in the other image. Note that Mutual Information as used here does not // measures the amount of information that one image provides on the other // image, such measure would have required to take into account the spatial // structures in the images as well as the semantics of the image context in // terms of an observer. // // This implies that there is still an enormous unexploited potential on the // use of the Mutual Information concept in the domain of medical images. // Probably the most interesting of which would be the semantic description of // image on terms of anatomical structures. // // \index{Mutual Information!Statistics} // \index{Statistics!Mutual Information} // \index{Joint Entropy!Statistics} // \index{Statistics!Joint Entropy} // \index{Joint Histogram!Statistics} // \index{Statistics!Joint Histogram} // // Software Guide : EndLatex // Software Guide : BeginLatex // // In this particular example we make use of classes from the Statistics // framework in order to compute the measure of Mutual Information between two // images. We assume that both images have the same number of pixels along // every dimension and that they have the same origin and spacing. Therefore // their pixels. // // We must start by including the header files of the image, histogram // generator, reader and Join image filter. We will read both images and use // the Join image filter in order to compose an image of two components using // the information of each one of the input images in one component. This is // the natural way o fusing the Statistics framework in ITK given that the // fundamental statistical classes are expecting to receive multivalued // measured. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "itkImage.h" #include "itkImageFileReader.h" #include "itkJoinImageFilter.h" #include "itkImageToHistogramGenerator.h" // Software Guide : EndCodeSnippet int main( int argc, char * argv [] ) { if( argc < 3 ) { std::cerr << "Missing command line arguments" << std::endl; std::cerr << "Usage : ImageHistogram1 inputImage1 inputImage2 " << std::endl; return -1; } // Software Guide : BeginLatex // // We define the pixel type and dimension of the images to be read. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef unsigned char PixelComponentType; const unsigned int Dimension = 2; typedef itk::Image< PixelComponentType, Dimension > ImageType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Using the image type we proceed to instantiate the readers for both input // images. Then, we take their filesnames from the command line arguments. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef itk::ImageFileReader< ImageType > ReaderType; ReaderType::Pointer reader1 = ReaderType::New(); ReaderType::Pointer reader2 = ReaderType::New(); reader1->SetFileName( argv[1] ); reader2->SetFileName( argv[2] ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Using the \doxyge{JoinImageFilter} we use the two input images and put them // together in an image of two components. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef itk::JoinImageFilter< ImageType, ImageType > JoinFilterType; JoinFilterType::Pointer joinFilter = JoinFilterType::New(); joinFilter->SetInput1( reader1->GetOutput() ); joinFilter->SetInput2( reader2->GetOutput() ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // At this point we trigger the execution of the pipeline by invoking the // \code{Update()} method on the Join filter. We must put the call inside a // try/catch block because the Update() call may potentially result in // exceptions being thrown. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet try { joinFilter->Update(); } catch( itk::ExceptionObject & excp ) { std::cerr << excp << std::endl; return -1; } // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We prepare now the types to be used for the computation of the Joint // histogram. For this purpose, we take the type of the image resulting from // the JoinImageFilter and use it as template argument of the // \doxyge{ImageToHistogramGenerator}. We then construct one by invoking the // \code{New()} method. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef JoinFilterType::OutputImageType VectorImageType; typedef itk::Statistics::ImageToHistogramGenerator< VectorImageType > HistogramGeneratorType; HistogramGeneratorType::Pointer histogramGenerator = HistogramGeneratorType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We pass the multiple components image as input to the histogram generator, // and setup the marginal scale value that will define the precision to be used // for classifying values into the histogram bins. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet histogramGenerator->SetInput( joinFilter->GetOutput() ); histogramGenerator->SetMarginalScale( 10.0 ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We must now define the number of bins to use for each one of the components // in the joint image. For this purpose we take the \code{SizeType} from the // traits of the histogram generator type. The array of number of bins is // passed to the generator and we can then invoke the \code{Compute()} method // in order to trigger the computation of the joint histogram. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef HistogramGeneratorType::SizeType SizeType; SizeType size; size[0] = 255; // number of bins for the first channel size[1] = 255; // number of bins for the second channel histogramGenerator->SetNumberOfBins( size ); histogramGenerator->Compute(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The histogram can be recovered from the generator by creating a variable // with the histogram type taken from the generator traits. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef HistogramGeneratorType::HistogramType HistogramType; const HistogramType * histogram = histogramGenerator->GetOutput(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We now walk over all the bins of the joint histogram and compute their // contribution to the value of the joint Entropy. For this purpose we use // histogram iterators, and the \code{Begin()} and \code{End()} methods. Since // the values returned from the histogram are frequency we must convert them to // an estimation of probability by dividing them over the total sum of // frequencies returned by the \code{GetTotalFrequency()} method. // // Software Guide : EndLatex HistogramType::ConstIterator itr = histogram->Begin(); HistogramType::ConstIterator end = histogram->End(); const double Sum = histogram->GetTotalFrequency(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We initialize to zero the variable to use for accumulating the value of the // joint entropy, and then use the iterator for visiting all the bins of the // joint histogram. At every bin we compute their contribution to the reduction // of uncertainty. Note that in order to avoid logarithmic operations on zero // values, we skip over those bins that have less than one count. The entropy // contribution must be computed using logarithms in base two in order to be // able express entropy in \textbf{bits}. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet double JointEntropy = 0.0; while( itr != end ) { const double count = itr.GetFrequency(); if( count > 0.0 ) { const double probability = count / Sum; JointEntropy += - probability * log( probability ) / log( 2.0 ); } ++itr; } // Software Guide : EndCodeSnippet std::cout << "Joint Entropy = " << JointEntropy << " bits " << std::endl; // Software Guide : BeginLatex // // Now that we have the value of the joint entropy we can proceed to estimate // the values of the entropies for each image independently. This can be done // by simply changing the number of bins and then recomputing the histogram. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet size[0] = 255; // number of bins for the first channel size[1] = 1; // number of bins for the second channel histogramGenerator->SetNumberOfBins( size ); histogramGenerator->Compute(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We initialize to zero another variable in order to start accumulating the // entropy contributions from every bin. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet itr = histogram->Begin(); end = histogram->End(); double Entropy1 = 0.0; while( itr != end ) { const double count = itr.GetFrequency(); if( count > 0.0 ) { const double probability = count / Sum; Entropy1 += - probability * log( probability ) / log( 2.0 ); } ++itr; } // Software Guide : EndCodeSnippet std::cout << "Image1 Entropy = " << Entropy1 << " bits " << std::endl; // Software Guide : BeginLatex // // The same process is used for computing the entropy of the other component. // Simply by swapping the number of bins in the histogram. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet size[0] = 1; // number of bins for the first channel size[1] = 255; // number of bins for the second channel histogramGenerator->SetNumberOfBins( size ); histogramGenerator->Compute(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The entropy is computed in a similar maner, just by visiting all the bins on // the histogram and accumulating their entropy contributions. // // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet itr = histogram->Begin(); end = histogram->End(); double Entropy2 = 0.0; while( itr != end ) { const double count = itr.GetFrequency(); if( count > 0.0 ) { const double probability = count / Sum; Entropy2 += - probability * log( probability ) / log( 2.0 ); } ++itr; } // Software Guide : EndCodeSnippet std::cout << "Image2 Entropy = " << Entropy2 << " bits " << std::endl; // Software Guide : BeginLatex // // At this point we can compute any of the popular measures of Mutual // Information. For example // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet double MutualInformation = Entropy1 + Entropy2 - JointEntropy; // Software Guide : EndCodeSnippet std::cout << "Mutual Information = " << MutualInformation << " bits " << std::endl; // Software Guide : BeginLatex // // or Normalized Mutual Information, where the value of Mutual Information gets // divided by the mean entropy of the input images. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet double NormalizedMutualInformation1 = 2.0 * MutualInformation / ( Entropy1 + Entropy2 ); // Software Guide : EndCodeSnippet std::cout << "Normalized Mutual Information 1 = " << NormalizedMutualInformation1 << std::endl; // Software Guide : BeginLatex // // A second form of Normalized Mutual Information has been defined as the mean // entropy of the two images divided by their joint entropy. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet double NormalizedMutualInformation2 = ( Entropy1 + Entropy2 ) / JointEntropy; // Software Guide : EndCodeSnippet std::cout << "Normalized Mutual Information 2 = " << NormalizedMutualInformation2 << std::endl; // Software Guide : BeginLatex // // You probably will find very interesting how the value of Mutual Information // is strongly dependent on the number of bins over which the histogram is // defined. // // Software Guide : EndLatex return 0; } <|endoftext|>
<commit_before>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2015 ETH Zurich ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ** following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following ** disclaimer. ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the ** following disclaimer in the documentation and/or other materials provided with the distribution. ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ***********************************************************************************************************************/ #include "History.h" #include "GitRepository.h" #include "ChangeDescription.h" #include "../simple/Parser.h" namespace FilePersistence { History::CommitTime::CommitTime(QString sha1, QDateTime dateTime) :commitSHA1_{sha1}, dateTime_{dateTime} {} bool History::CommitTime::operator < (const CommitTime& commitTime) const { return dateTime_ < commitTime.dateTime_; } bool History::CommitTime::operator > (const CommitTime& commitTime) const { return dateTime_ > commitTime.dateTime_; } bool History::CommitTime::later(const CommitTime& left, const CommitTime& right) { return left > right; } History::History(QString relativePath, Model::NodeIdType rootNodeId, const CommitGraph* historyGraph, const GitRepository* repository) { rootNodeId_ = rootNodeId; historyGraph_ = historyGraph; const CommitGraphItem endItem = historyGraph_->end(); QSet<const CommitGraphItem*> visited; QString end = endItem.commitSHA1_; GenericTree initialTree("History"); QSet<Model::NodeIdType> trackedIDs = trackSubtree(end, relativePath, &initialTree, repository); detectRelevantCommits(&endItem, visited, relativePath, trackedIDs, repository); } QList<QString> History::relevantCommitsByTime(const GitRepository* repository, bool reverse) const { QList<CommitTime> commitTimeList; for (auto commit : relevantCommits_) { CommitMetaData info = repository->getCommitInformation(commit); commitTimeList.append(CommitTime(commit, info.dateTime_)); } if (reverse) std::sort(commitTimeList.begin(), commitTimeList.end(), CommitTime::later); else std::sort(commitTimeList.begin(), commitTimeList.end()); QList<QString> orderedCommits; for (auto commitTime : commitTimeList) orderedCommits.append(commitTime.commitSHA1_); return orderedCommits; } void History::detectRelevantCommits(const CommitGraphItem* current, QSet<const CommitGraphItem*> visited, QString relativePathRootNode, QSet<Model::NodeIdType> trackedIDs, const GitRepository* repository) { if (!visited.contains(current) && !trackedIDs.isEmpty()) { visited.insert(current); bool isRelevant = true; for (auto parent : current->parents_) { Diff diff = repository->diff(parent->commitSHA1_, current->commitSHA1_); IdToChangeDescriptionHash changes = diff.changes(); bool subtreeIsAffected = false; for (auto change : changes.values()) { if (trackedIDs.contains(change->nodeId())) { subtreeIsAffected = true; break; } } if (!subtreeIsAffected) isRelevant = false; GenericTree tree("History"); QString parentRelativeRootPath =findRootPath(parent->commitSHA1_, relativePathRootNode, &diff, &tree, repository); if (!parentRelativeRootPath.isNull()) { if (subtreeIsAffected) { QSet<Model::NodeIdType> newTrackedIDs = trackSubtree(parent->commitSHA1_, parentRelativeRootPath, &tree, repository); detectRelevantCommits(parent, visited, parentRelativeRootPath, newTrackedIDs, repository); } else detectRelevantCommits(parent, visited, parentRelativeRootPath, trackedIDs, repository); } } if (isRelevant) relevantCommits_.insert(current->commitSHA1_); } } QString History::findRootPath(QString revision, QString currentPath, const Diff* diff, GenericTree* tree, const GitRepository* repository) { IdToChangeDescriptionHash changes = diff->changes(); // check if rootNode is affected by changes directly if (changes.contains(rootNodeId_)) { auto change = changes.value(rootNodeId_); const GenericNode* rootNode = change->nodeA(); if (rootNode) return rootNode->persistentUnit()->name(); else return QString(); } // check if rootNode is still in current PU if (!tree->persistentUnit(currentPath)) { const CommitFile* file = repository->getCommitFile(revision, currentPath); Parser::load(file->content(), file->size_, false, tree->newPersistentUnit(currentPath)); SAFE_DELETE(file); } GenericNode* rootNode = tree->find(rootNodeId_); if (rootNode) return currentPath; // check if rootNode is in other PU (affected by move) QSet<QString> alreadyChecked; alreadyChecked.insert(currentPath); IdToChangeDescriptionHash moves = diff->changes(ChangeType::Move); for (auto move : moves) { if (currentPath.compare(move->nodeB()->persistentUnit()->name()) == 0) { QString unitName = move->nodeA()->persistentUnit()->name(); if (!alreadyChecked.contains(unitName)) { if (!tree->persistentUnit(unitName)) { const CommitFile* file = repository->getCommitFile(revision, unitName); Parser::load(file->content(), file->size_, false, tree->newPersistentUnit(unitName)); SAFE_DELETE(file); } GenericNode* rootNode = tree->find(rootNodeId_); if (rootNode) return unitName; } } } // rootNodeId can't be found but was not deleted! Q_ASSERT(false); return QString(); } QSet<Model::NodeIdType> History::trackSubtree(QString revision, QString relativePath, GenericTree* tree, const GitRepository* repository) const { QSet<Model::NodeIdType> trackedIDs; QList<const CommitFile*> commitFiles; if (!tree->persistentUnit(relativePath)) { const CommitFile* startFile = repository->getCommitFile(revision, relativePath); commitFiles.append(startFile); Parser::load(startFile->content(), startFile->size_, false, tree->newPersistentUnit(relativePath)); } tree->buildLookupHash(); GenericNode* subtreeRoot = tree->find(rootNodeId_); if (!subtreeRoot) return QSet<Model::NodeIdType>(); Q_ASSERT(subtreeRoot != nullptr); QList<GenericNode*> stack; stack.append(subtreeRoot); while (!stack.empty()) { GenericNode* current = stack.last(); stack.removeLast(); trackedIDs.insert(current->id()); if (current->type() == GenericNode::PERSISTENT_UNIT_TYPE) { QString subUnitrelativePath = current->id().toString(); if (!tree->persistentUnit(subUnitrelativePath)) { const CommitFile* file = repository->getCommitFile(revision, subUnitrelativePath); commitFiles.append(file); Parser::load(file->content(), file->size_, false, tree->newPersistentUnit(subUnitrelativePath)); } GenericNode* subUnitRoot = tree->persistentUnit(subUnitrelativePath)->unitRootNode(); stack.append(subUnitRoot); } for (auto child : current->children()) stack.append(child); } for (auto file : commitFiles) SAFE_DELETE(file); return trackedIDs; } } /* namespace FilePersistence */ <commit_msg>Call builLookupHash before calling find on a tree.<commit_after>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2015 ETH Zurich ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ** following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following ** disclaimer. ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the ** following disclaimer in the documentation and/or other materials provided with the distribution. ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ***********************************************************************************************************************/ #include "History.h" #include "GitRepository.h" #include "ChangeDescription.h" #include "../simple/Parser.h" namespace FilePersistence { History::CommitTime::CommitTime(QString sha1, QDateTime dateTime) :commitSHA1_{sha1}, dateTime_{dateTime} {} bool History::CommitTime::operator < (const CommitTime& commitTime) const { return dateTime_ < commitTime.dateTime_; } bool History::CommitTime::operator > (const CommitTime& commitTime) const { return dateTime_ > commitTime.dateTime_; } bool History::CommitTime::later(const CommitTime& left, const CommitTime& right) { return left > right; } History::History(QString relativePath, Model::NodeIdType rootNodeId, const CommitGraph* historyGraph, const GitRepository* repository) { rootNodeId_ = rootNodeId; historyGraph_ = historyGraph; const CommitGraphItem endItem = historyGraph_->end(); QSet<const CommitGraphItem*> visited; QString end = endItem.commitSHA1_; GenericTree initialTree("History"); QSet<Model::NodeIdType> trackedIDs = trackSubtree(end, relativePath, &initialTree, repository); detectRelevantCommits(&endItem, visited, relativePath, trackedIDs, repository); } QList<QString> History::relevantCommitsByTime(const GitRepository* repository, bool reverse) const { QList<CommitTime> commitTimeList; for (auto commit : relevantCommits_) { CommitMetaData info = repository->getCommitInformation(commit); commitTimeList.append(CommitTime(commit, info.dateTime_)); } if (reverse) std::sort(commitTimeList.begin(), commitTimeList.end(), CommitTime::later); else std::sort(commitTimeList.begin(), commitTimeList.end()); QList<QString> orderedCommits; for (auto commitTime : commitTimeList) orderedCommits.append(commitTime.commitSHA1_); return orderedCommits; } void History::detectRelevantCommits(const CommitGraphItem* current, QSet<const CommitGraphItem*> visited, QString relativePathRootNode, QSet<Model::NodeIdType> trackedIDs, const GitRepository* repository) { if (!visited.contains(current) && !trackedIDs.isEmpty()) { visited.insert(current); bool isRelevant = true; for (auto parent : current->parents_) { Diff diff = repository->diff(parent->commitSHA1_, current->commitSHA1_); IdToChangeDescriptionHash changes = diff.changes(); bool subtreeIsAffected = false; for (auto change : changes.values()) { if (trackedIDs.contains(change->nodeId())) { subtreeIsAffected = true; break; } } if (!subtreeIsAffected) isRelevant = false; GenericTree tree("History"); QString parentRelativeRootPath =findRootPath(parent->commitSHA1_, relativePathRootNode, &diff, &tree, repository); if (!parentRelativeRootPath.isNull()) { if (subtreeIsAffected) { QSet<Model::NodeIdType> newTrackedIDs = trackSubtree(parent->commitSHA1_, parentRelativeRootPath, &tree, repository); detectRelevantCommits(parent, visited, parentRelativeRootPath, newTrackedIDs, repository); } else detectRelevantCommits(parent, visited, parentRelativeRootPath, trackedIDs, repository); } } if (isRelevant) relevantCommits_.insert(current->commitSHA1_); } } QString History::findRootPath(QString revision, QString currentPath, const Diff* diff, GenericTree* tree, const GitRepository* repository) { IdToChangeDescriptionHash changes = diff->changes(); // check if rootNode is affected by changes directly if (changes.contains(rootNodeId_)) { auto change = changes.value(rootNodeId_); const GenericNode* rootNode = change->nodeA(); if (rootNode) return rootNode->persistentUnit()->name(); else return QString(); } // check if rootNode is still in current PU if (!tree->persistentUnit(currentPath)) { const CommitFile* file = repository->getCommitFile(revision, currentPath); Parser::load(file->content(), file->size_, false, tree->newPersistentUnit(currentPath)); SAFE_DELETE(file); } tree->buildLookupHash(); GenericNode* rootNode = tree->find(rootNodeId_); if (rootNode) return currentPath; // check if rootNode is in other PU (affected by move) QSet<QString> alreadyChecked; alreadyChecked.insert(currentPath); IdToChangeDescriptionHash moves = diff->changes(ChangeType::Move); for (auto move : moves) { if (currentPath.compare(move->nodeB()->persistentUnit()->name()) == 0) { QString unitName = move->nodeA()->persistentUnit()->name(); if (!alreadyChecked.contains(unitName)) { if (!tree->persistentUnit(unitName)) { const CommitFile* file = repository->getCommitFile(revision, unitName); Parser::load(file->content(), file->size_, false, tree->newPersistentUnit(unitName)); SAFE_DELETE(file); } GenericNode* rootNode = tree->find(rootNodeId_); if (rootNode) return unitName; } } } // rootNodeId can't be found but was not deleted! Q_ASSERT(false); return QString(); } QSet<Model::NodeIdType> History::trackSubtree(QString revision, QString relativePath, GenericTree* tree, const GitRepository* repository) const { QSet<Model::NodeIdType> trackedIDs; QList<const CommitFile*> commitFiles; if (!tree->persistentUnit(relativePath)) { const CommitFile* startFile = repository->getCommitFile(revision, relativePath); commitFiles.append(startFile); Parser::load(startFile->content(), startFile->size_, false, tree->newPersistentUnit(relativePath)); } tree->buildLookupHash(); GenericNode* subtreeRoot = tree->find(rootNodeId_); if (!subtreeRoot) return QSet<Model::NodeIdType>(); Q_ASSERT(subtreeRoot != nullptr); QList<GenericNode*> stack; stack.append(subtreeRoot); while (!stack.empty()) { GenericNode* current = stack.last(); stack.removeLast(); trackedIDs.insert(current->id()); if (current->type() == GenericNode::PERSISTENT_UNIT_TYPE) { QString subUnitrelativePath = current->id().toString(); if (!tree->persistentUnit(subUnitrelativePath)) { const CommitFile* file = repository->getCommitFile(revision, subUnitrelativePath); commitFiles.append(file); Parser::load(file->content(), file->size_, false, tree->newPersistentUnit(subUnitrelativePath)); } GenericNode* subUnitRoot = tree->persistentUnit(subUnitrelativePath)->unitRootNode(); stack.append(subUnitRoot); } for (auto child : current->children()) stack.append(child); } for (auto file : commitFiles) SAFE_DELETE(file); return trackedIDs; } } /* namespace FilePersistence */ <|endoftext|>
<commit_before> #include <stdio.h> // printf #include <stdlib.h> // exit #include <string.h> // memcpy #include <iostream> // std::cout #include "parseArgs/parseArgs.h" #include "parseArgs/paConfig.h" #include "logMsg/logMsg.h" #include "au/string.h" // au::str() #include "samson/client/SamsonClient.h" // samson::SamsonClient #include "samson/client/SamsonPushBuffer.h" #include "samson/common/coding.h" // KVHeader #include "samson/network/NetworkListener.h" #include "samson/network/SocketConnection.h" #include "SamsonConnector.h" size_t buffer_size; char input[1024]; char output[1024]; char splitter[1024]; bool interactive; static const char* manShortDescription = "samsonConnector is a easy-to-use network tool used for small processing and data transportation in a SAMSON system.\n"; static const char* manSynopsis = "[-help] [-input \"[stdin] [port:X] [connection:server:port] [samson:X:queue]\"] [-output \"[stdout] [port:X] [connection:server:port] [samson:X:queue]\"] [-buffer_size int_size] [-splitter XX]\n"; int default_buffer_size = 64*1024*1024 - sizeof(samson::KVHeader); PaArgument paArgs[] = { { "-input", input, "", PaString, PaOpt, _i "stdin" , PaNL, PaNL, "Input sources " }, { "-output", output, "", PaString, PaOpt, _i "stdout" , PaNL, PaNL, "Output sources " }, { "-buffer_size", &buffer_size, "", PaInt, PaOpt, default_buffer_size, 1, default_buffer_size, "Buffer size in bytes" }, { "-splitter", splitter, "", PaString, PaOpt, _i "system.line", PaNL, PaNL, "Splitter" }, { "-i", &interactive, "", PaBool, PaOpt, false, false, true, "Interactive console" }, PA_END_OF_ARGS }; // Log fg for traces int logFd = -1; // Network connections ( input and output ) samson::SamsonConnector samson_connector; // Instance of the client to connect to SAMSON system samson::SamsonClient *samson_client; void* review_samson_connector(void*p) { // Endless loop waiting for data.... while( true ) { samson_connector.review(); samson_connector.exit_if_necessary(); sleep(5); } } int main( int argC , const char *argV[] ) { paConfig("usage and exit on any warning", (void*) true); paConfig("log to screen", (void*) true); paConfig("log to file", (void*) false); paConfig("screen line format", (void*) "TYPE:EXEC: TEXT"); paConfig("man shortdescription", (void*) manShortDescription); paConfig("man synopsis", (void*) manSynopsis); paConfig("log to stderr", (void*) true); // Parse input arguments paParse(paArgs, argC, (char**) argV, 1, false); logFd = lmFirstDiskFileDescriptor(); // Random initialization srand( time(NULL) ); if( buffer_size == 0) LM_X(1,("Wrong buffer size %lu", buffer_size )); //Init engine engine::Engine::init(); LM_D(("engine::MemoryManager::init")); engine::MemoryManager::init( 1000000 ); // ------------------------------------------------------- // Parsing outputs // ------------------------------------------------------- { au::CommandLine cmdLine; cmdLine.parse(output); if( cmdLine.get_num_arguments() == 0 ) LM_X(1, ("No output specified")); for ( int i = 0 ; i < cmdLine.get_num_arguments() ; i++ ) { std::string input_string = cmdLine.get_argument(i); std::vector<std::string> components = au::split(input_string, ':'); if( components[0] == "stdout" ) { LM_V(("Adding stdout as output channel")); samson_connector.add_stdout(); } else if( components[0] == "stderr" ) { LM_V(("Adding stderr as output channel")); samson_connector.add_stderr(); } else if( components[0] == "port" ) { if( components.size() < 2 ) LM_X(1, ("Output port without number. Please specifiy port to open (ex port:10000)")); int port = atoi( components[1].c_str() ); if( port == 0 ) LM_X(1, ("Wrong input port")); LM_V(("Adding port %d as output port" , port)); samson_connector.add_output_port( port ); } else if( components[0] == "connection" ) { if( components.size() < 3 ) LM_X(1, ("Output connection without host and port. Please specifiy as connection:host:port)")); int port = atoi( components[2].c_str() ); if( port == 0 ) LM_X(1, ("Wrong connection port for %s" , components[1].c_str() )); samson_connector.add_output_connection(components[1], port ); } else if( components[0] == "samson" ) { int port = SAMSON_WORKER_PORT; samson_connector.add_samson_output_connection(components[1], port, components[2] ); } } } // Review to create dedicated connections samson_connector.review(); // ------------------------------------------------------- // Parsing inputs // ------------------------------------------------------- { au::CommandLine cmdLine; cmdLine.parse(input); if( cmdLine.get_num_arguments() == 0 ) LM_X(1, ("No input specified")); for ( int i = 0 ; i < cmdLine.get_num_arguments() ; i++ ) { std::string input_string = cmdLine.get_argument(i); std::vector<std::string> components = au::split(input_string, ':'); if( components[0] == "stdin" ) { LM_V(("Adding stdin as input channel")); samson_connector.add_stdin(); } else if( components[0] == "port" ) { if( components.size() < 2 ) LM_X(1, ("Input port without number. Please specifiy port to open (ex port:10000)")); int port = atoi( components[1].c_str() ); if( port == 0 ) LM_X(1, ("Wrong input port")); LM_V(("Adding port %d as input port" , port)); samson_connector.add_input_port( port ); } else if( components[0] == "connection" ) { if( components.size() < 3 ) LM_X(1, ("Input connection without host and port. Please specifiy as connection:host:port)")); int port = atoi( components[2].c_str() ); if( port == 0 ) LM_X(1, ("Wrong connection port for %s" , components[1].c_str() )); samson_connector.add_input_connection(components[1], port ); } else if( components[0] == "samson" ) { int port = SAMSON_WORKER_PORT; samson_connector.add_samson_input_connection(components[1], port, components[2] ); } } } // Background thread to review connections in samson connector pthread_t t; pthread_create(&t, NULL, review_samson_connector, NULL); // Run console if interactive mode is activated if( interactive ) samson_connector.runConsole(); else while( true ) sleep(10000); return 0; } <commit_msg>Andreu:Fix broken compilation<commit_after> #include <stdio.h> // printf #include <stdlib.h> // exit #include <string.h> // memcpy #include <iostream> // std::cout #include "parseArgs/parseArgs.h" #include "parseArgs/paConfig.h" #include "logMsg/logMsg.h" #include "au/string.h" // au::str() #include "samson/client/SamsonClient.h" // samson::SamsonClient #include "samson/client/SamsonPushBuffer.h" #include "samson/common/coding.h" // KVHeader #include "samson/network/NetworkListener.h" #include "samson/network/SocketConnection.h" #include "SamsonConnector.h" size_t buffer_size; char input[1024]; char output[1024]; char splitter[1024]; bool interactive; static const char* manShortDescription = "samsonConnector is a easy-to-use network tool used for small processing and data transportation in a SAMSON system.\n"; static const char* manSynopsis = "[-help] [-input \"[stdin] [port:X] [connection:server:port] [samson:X:queue]\"] [-output \"[stdout] [port:X] [connection:server:port] [samson:X:queue]\"] [-buffer_size int_size] [-splitter XX]\n"; int default_buffer_size = 64*1024*1024 - sizeof(samson::KVHeader); PaArgument paArgs[] = { { "-input", input, "", PaString, PaOpt, _i "stdin" , PaNL, PaNL, "Input sources " }, { "-output", output, "", PaString, PaOpt, _i "stdout" , PaNL, PaNL, "Output sources " }, { "-buffer_size", &buffer_size, "", PaInt, PaOpt, default_buffer_size, 1, default_buffer_size, "Buffer size in bytes" }, { "-splitter", splitter, "", PaString, PaOpt, _i "system.line", PaNL, PaNL, "Splitter" }, { "-i", &interactive, "", PaBool, PaOpt, false, false, true, "Interactive console" }, PA_END_OF_ARGS }; // Log fg for traces int logFd = -1; // Network connections ( input and output ) samson::SamsonConnector samson_connector; // Instance of the client to connect to SAMSON system samson::SamsonClient *samson_client; void* review_samson_connector(void*p) { // Endless loop waiting for data.... while( true ) { samson_connector.review(); samson_connector.exit_if_necessary(); sleep(5); } return NULL; } int main( int argC , const char *argV[] ) { paConfig("usage and exit on any warning", (void*) true); paConfig("log to screen", (void*) true); paConfig("log to file", (void*) false); paConfig("screen line format", (void*) "TYPE:EXEC: TEXT"); paConfig("man shortdescription", (void*) manShortDescription); paConfig("man synopsis", (void*) manSynopsis); paConfig("log to stderr", (void*) true); // Parse input arguments paParse(paArgs, argC, (char**) argV, 1, false); logFd = lmFirstDiskFileDescriptor(); // Random initialization srand( time(NULL) ); if( buffer_size == 0) LM_X(1,("Wrong buffer size %lu", buffer_size )); //Init engine engine::Engine::init(); LM_D(("engine::MemoryManager::init")); engine::MemoryManager::init( 1000000 ); // ------------------------------------------------------- // Parsing outputs // ------------------------------------------------------- { au::CommandLine cmdLine; cmdLine.parse(output); if( cmdLine.get_num_arguments() == 0 ) LM_X(1, ("No output specified")); for ( int i = 0 ; i < cmdLine.get_num_arguments() ; i++ ) { std::string input_string = cmdLine.get_argument(i); std::vector<std::string> components = au::split(input_string, ':'); if( components[0] == "stdout" ) { LM_V(("Adding stdout as output channel")); samson_connector.add_stdout(); } else if( components[0] == "stderr" ) { LM_V(("Adding stderr as output channel")); samson_connector.add_stderr(); } else if( components[0] == "port" ) { if( components.size() < 2 ) LM_X(1, ("Output port without number. Please specifiy port to open (ex port:10000)")); int port = atoi( components[1].c_str() ); if( port == 0 ) LM_X(1, ("Wrong input port")); LM_V(("Adding port %d as output port" , port)); samson_connector.add_output_port( port ); } else if( components[0] == "connection" ) { if( components.size() < 3 ) LM_X(1, ("Output connection without host and port. Please specifiy as connection:host:port)")); int port = atoi( components[2].c_str() ); if( port == 0 ) LM_X(1, ("Wrong connection port for %s" , components[1].c_str() )); samson_connector.add_output_connection(components[1], port ); } else if( components[0] == "samson" ) { int port = SAMSON_WORKER_PORT; samson_connector.add_samson_output_connection(components[1], port, components[2] ); } } } // Review to create dedicated connections samson_connector.review(); // ------------------------------------------------------- // Parsing inputs // ------------------------------------------------------- { au::CommandLine cmdLine; cmdLine.parse(input); if( cmdLine.get_num_arguments() == 0 ) LM_X(1, ("No input specified")); for ( int i = 0 ; i < cmdLine.get_num_arguments() ; i++ ) { std::string input_string = cmdLine.get_argument(i); std::vector<std::string> components = au::split(input_string, ':'); if( components[0] == "stdin" ) { LM_V(("Adding stdin as input channel")); samson_connector.add_stdin(); } else if( components[0] == "port" ) { if( components.size() < 2 ) LM_X(1, ("Input port without number. Please specifiy port to open (ex port:10000)")); int port = atoi( components[1].c_str() ); if( port == 0 ) LM_X(1, ("Wrong input port")); LM_V(("Adding port %d as input port" , port)); samson_connector.add_input_port( port ); } else if( components[0] == "connection" ) { if( components.size() < 3 ) LM_X(1, ("Input connection without host and port. Please specifiy as connection:host:port)")); int port = atoi( components[2].c_str() ); if( port == 0 ) LM_X(1, ("Wrong connection port for %s" , components[1].c_str() )); samson_connector.add_input_connection(components[1], port ); } else if( components[0] == "samson" ) { int port = SAMSON_WORKER_PORT; samson_connector.add_samson_input_connection(components[1], port, components[2] ); } } } // Background thread to review connections in samson connector pthread_t t; pthread_create(&t, NULL, review_samson_connector, NULL); // Run console if interactive mode is activated if( interactive ) samson_connector.runConsole(); else while( true ) sleep(10000); return 0; } <|endoftext|>
<commit_before>#include "vast/search.h" #include "vast/exception.h" #include "vast/optional.h" #include "vast/query.h" #include "vast/util/make_unique.h" namespace vast { namespace { // Deconstructs an entire query AST into its individual sub-trees and adds // each to the state map. class dissector : public expr::default_const_visitor { public: dissector(std::map<expr::ast, search::state>& state, expr::ast const& base) : state_{state}, base_{base} { } virtual void visit(expr::conjunction const& conj) { expr::ast ast{conj}; if (parent_) state_[ast].parents.insert(parent_); else if (ast == base_) state_.emplace(ast, search::state{}); parent_ = std::move(ast); for (auto& clause : conj.operands) clause->accept(*this); } virtual void visit(expr::disjunction const& disj) { expr::ast ast{disj}; if (parent_) state_[ast].parents.insert(parent_); else if (ast == base_) state_.emplace(ast, search::state{}); parent_ = std::move(ast); for (auto& term : disj.operands) term->accept(*this); } virtual void visit(expr::relation const& rel) { assert(parent_); expr::ast ast{rel}; state_[ast].parents.insert(parent_); } private: expr::ast parent_; std::map<expr::ast, search::state>& state_; expr::ast const& base_; }; struct node_tester : public expr::default_const_visitor { virtual void visit(expr::conjunction const&) { type = logical_and; } virtual void visit(expr::disjunction const&) { type = logical_or; } optional<boolean_operator> type; }; // Computes the result of a conjunction by ANDing the results of all of its // child nodes. struct conjunction_evaluator : public expr::default_const_visitor { conjunction_evaluator(std::map<expr::ast, search::state>& state) : state{state} { } virtual void visit(expr::conjunction const& conj) { for (auto& operand : conj.operands) if (complete) operand->accept(*this); } virtual void visit(expr::disjunction const& disj) { if (complete) update(disj); } virtual void visit(expr::relation const& rel) { if (complete) update(rel); } void update(expr::ast const& child) { auto i = state.find(child); assert(i != state.end()); auto& child_result = i->second.result; if (! child_result) { complete = false; return; } result &= child_result; } bool complete = true; search_result result; std::map<expr::ast, search::state> const& state; }; struct disjunction_evaluator : public expr::default_const_visitor { disjunction_evaluator(std::map<expr::ast, search::state>& state) : state{state} { } virtual void visit(expr::conjunction const& conj) { update(conj); } virtual void visit(expr::disjunction const& disj) { for (auto& operand : disj.operands) operand->accept(*this); } virtual void visit(expr::relation const& rel) { update(rel); } void update(expr::ast const& child) { auto i = state.find(child); assert(i != state.end()); auto& child_result = i->second.result; if (child_result) result |= child_result; } search_result result; std::map<expr::ast, search::state> const& state; }; } // namespace <anonymous> expr::ast search::add_query(std::string const& str) { expr::ast ast{str}; if (! ast) return ast; dissector d{state_, ast}; ast.accept(d); return ast; } std::vector<expr::ast> search::update(expr::ast const& ast, search_result const& result) { assert(result); assert(state_.count(ast)); auto& ast_state = state_[ast]; node_tester nt; ast.accept(nt); // Phase 1: update the current AST node's state. if (nt.type) { if (*nt.type == logical_and) { VAST_LOG_VERBOSE("evaluating conjunction " << ast); conjunction_evaluator ce{state_}; ast.accept(ce); if (ce.complete) ast_state.result = std::move(ce.result); VAST_LOG_DEBUG((ce.complete ? "" : "in") << "complete evaluation"); } else if (*nt.type == logical_or) { VAST_LOG_VERBOSE("evaluating disjunction " << ast); disjunction_evaluator de{state_}; ast.accept(de); if (! ast_state.result || (de.result && de.result != ast_state.result)) ast_state.result = std::move(de.result); } } else if (! ast_state.result) { VAST_LOG_VERBOSE("assigning result to " << ast); ast_state.result = std::move(result); } else if (ast_state.result == result) { assert(ast_state.result.hits()); assert(ast_state.result == result); VAST_LOG_VERBOSE("ignoring unchanged result for " << ast); } else { VAST_LOG_VERBOSE("computing new result for " << ast); ast_state.result |= result; } // Phase 2: Update the parents recursively. std::vector<expr::ast> path; for (auto& parent : ast_state.parents) { auto pp = update(parent, ast_state.result); std::move(pp.begin(), pp.end(), std::back_inserter(path)); } path.push_back(ast); std::sort(path.begin(), path.end()); path.erase(std::unique(path.begin(), path.end()), path.end()); return path; } search_result const* search::result(expr::ast const& ast) const { auto i = state_.find(ast); return i != state_.end() ? &i->second.result : nullptr; } using namespace cppa; search_actor::query_state::query_state(actor_ptr q, actor_ptr c) : query{q}, client{c} { } search_actor::search_actor(actor_ptr archive, actor_ptr index, actor_ptr schema_manager) : archive_{std::move(archive)}, index_{std::move(index)}, schema_manager_{std::move(schema_manager)} { } void search_actor::act() { trap_exit(true); become( on(atom("EXIT"), arg_match) >> [=](uint32_t reason) { std::set<actor_ptr> doomed; for (auto& p : query_state_) { doomed.insert(p.second.query); doomed.insert(p.second.client); } for (auto& d : doomed) send_exit(d, exit::stop); quit(reason); }, on(atom("DOWN"), arg_match) >> [=](uint32_t) { VAST_LOG_ACTOR_DEBUG( "received DOWN from client @" << last_sender()->id()); std::set<actor_ptr> doomed; for (auto& p : query_state_) { if (p.second.client == last_sender()) { doomed.insert(p.second.query); doomed.insert(p.second.client); } } for (auto& d : doomed) send_exit(d, exit::stop); }, on(atom("query"), atom("create"), arg_match) >> [=](std::string const& q) { auto ast = search_.add_query(q); if (! ast) { reply(actor_ptr{}, ast); return; } VAST_LOG_ACTOR_DEBUG("received new query: " << ast); monitor(last_sender()); auto qry = spawn<query_actor>(archive_, last_sender(), ast); query_state_.emplace(ast, query_state{qry, last_sender()}); // TODO: reuse results from existing queries before asking index again. send(index_, ast); reply(std::move(qry), std::move(ast)); }, on_arg_match >> [=](expr::ast const& ast, search_result const& result) { if (! result) { VAST_LOG_ACTOR_DEBUG("ignores empty result for: " << ast); return; } for (auto& node : search_.update(ast, result)) { auto er = query_state_.equal_range(node); for (auto i = er.first; i != er.second; ++i) { auto r = search_.result(node); if (r && *r && *r != i->second.result) { VAST_LOG_ACTOR_DEBUG( "propagates updated result to query @" << i->second.query->id() << " from " << i->first); i->second.result = *r; send(i->second.query, r->hits()); } } } }, others() >> [=] { VAST_LOG_ACTOR_ERROR("got unexpected message from @" << last_sender()->id() << ": " << to_string(last_dequeued())); }); } char const* search_actor::description() const { return "search"; } } // namespace vast <commit_msg>Fix bug in recursive result propagation.<commit_after>#include "vast/search.h" #include "vast/exception.h" #include "vast/optional.h" #include "vast/query.h" #include "vast/util/make_unique.h" namespace vast { namespace { // Deconstructs an entire query AST into its individual sub-trees and adds // each to the state map. class dissector : public expr::default_const_visitor { public: dissector(std::map<expr::ast, search::state>& state, expr::ast const& base) : state_{state}, base_{base} { } virtual void visit(expr::conjunction const& conj) { expr::ast ast{conj}; if (parent_) state_[ast].parents.insert(parent_); else if (ast == base_) state_.emplace(ast, search::state{}); parent_ = std::move(ast); for (auto& clause : conj.operands) clause->accept(*this); } virtual void visit(expr::disjunction const& disj) { expr::ast ast{disj}; if (parent_) state_[ast].parents.insert(parent_); else if (ast == base_) state_.emplace(ast, search::state{}); parent_ = std::move(ast); for (auto& term : disj.operands) term->accept(*this); } virtual void visit(expr::relation const& rel) { assert(parent_); expr::ast ast{rel}; state_[ast].parents.insert(parent_); } private: expr::ast parent_; std::map<expr::ast, search::state>& state_; expr::ast const& base_; }; struct node_tester : public expr::default_const_visitor { virtual void visit(expr::conjunction const&) { type = logical_and; } virtual void visit(expr::disjunction const&) { type = logical_or; } optional<boolean_operator> type; }; // Computes the result of a conjunction by ANDing the results of all of its // child nodes. struct conjunction_evaluator : public expr::default_const_visitor { conjunction_evaluator(std::map<expr::ast, search::state>& state) : state{state} { } virtual void visit(expr::conjunction const& conj) { for (auto& operand : conj.operands) if (complete) operand->accept(*this); } virtual void visit(expr::disjunction const& disj) { if (complete) update(disj); } virtual void visit(expr::relation const& rel) { if (complete) update(rel); } void update(expr::ast const& child) { auto i = state.find(child); assert(i != state.end()); auto& child_result = i->second.result; if (! child_result) { complete = false; return; } result &= child_result; } bool complete = true; search_result result; std::map<expr::ast, search::state> const& state; }; struct disjunction_evaluator : public expr::default_const_visitor { disjunction_evaluator(std::map<expr::ast, search::state>& state) : state{state} { } virtual void visit(expr::conjunction const& conj) { update(conj); } virtual void visit(expr::disjunction const& disj) { for (auto& operand : disj.operands) operand->accept(*this); } virtual void visit(expr::relation const& rel) { update(rel); } void update(expr::ast const& child) { auto i = state.find(child); assert(i != state.end()); auto& child_result = i->second.result; if (child_result) result |= child_result; } search_result result; std::map<expr::ast, search::state> const& state; }; } // namespace <anonymous> expr::ast search::add_query(std::string const& str) { expr::ast ast{str}; if (! ast) return ast; dissector d{state_, ast}; ast.accept(d); return ast; } std::vector<expr::ast> search::update(expr::ast const& ast, search_result const& result) { if (! result) { VAST_LOG_DEBUG("aborting ast propagation due to empty result"); return {}; } assert(state_.count(ast)); auto& ast_state = state_[ast]; node_tester nt; ast.accept(nt); // Phase 1: update the current AST node's state. if (nt.type) { if (*nt.type == logical_and) { VAST_LOG_DEBUG("evaluating conjunction " << ast); conjunction_evaluator ce{state_}; ast.accept(ce); if (ce.complete) ast_state.result = std::move(ce.result); VAST_LOG_DEBUG((ce.complete ? "" : "in") << "complete evaluation"); } else if (*nt.type == logical_or) { VAST_LOG_DEBUG("evaluating disjunction " << ast); disjunction_evaluator de{state_}; ast.accept(de); if (! ast_state.result || (de.result && de.result != ast_state.result)) ast_state.result = std::move(de.result); } } else if (! ast_state.result) { VAST_LOG_DEBUG("assigning result to " << ast); ast_state.result = std::move(result); } else if (ast_state.result == result) { VAST_LOG_DEBUG("ignoring unchanged result for " << ast); } else { VAST_LOG_DEBUG("computing new result for " << ast); ast_state.result |= result; } // Phase 2: Update the parents recursively. std::vector<expr::ast> path; for (auto& parent : ast_state.parents) { auto pp = update(parent, ast_state.result); std::move(pp.begin(), pp.end(), std::back_inserter(path)); } path.push_back(ast); std::sort(path.begin(), path.end()); path.erase(std::unique(path.begin(), path.end()), path.end()); return path; } search_result const* search::result(expr::ast const& ast) const { auto i = state_.find(ast); return i != state_.end() ? &i->second.result : nullptr; } using namespace cppa; search_actor::query_state::query_state(actor_ptr q, actor_ptr c) : query{q}, client{c} { } search_actor::search_actor(actor_ptr archive, actor_ptr index, actor_ptr schema_manager) : archive_{std::move(archive)}, index_{std::move(index)}, schema_manager_{std::move(schema_manager)} { } void search_actor::act() { trap_exit(true); become( on(atom("EXIT"), arg_match) >> [=](uint32_t reason) { std::set<actor_ptr> doomed; for (auto& p : query_state_) { doomed.insert(p.second.query); doomed.insert(p.second.client); } for (auto& d : doomed) send_exit(d, exit::stop); quit(reason); }, on(atom("DOWN"), arg_match) >> [=](uint32_t) { VAST_LOG_ACTOR_DEBUG( "received DOWN from client @" << last_sender()->id()); std::set<actor_ptr> doomed; for (auto& p : query_state_) { if (p.second.client == last_sender()) { doomed.insert(p.second.query); doomed.insert(p.second.client); } } for (auto& d : doomed) send_exit(d, exit::stop); }, on(atom("query"), atom("create"), arg_match) >> [=](std::string const& q) { auto ast = search_.add_query(q); if (! ast) { reply(actor_ptr{}, ast); return; } VAST_LOG_ACTOR_DEBUG("received new query: " << ast); monitor(last_sender()); auto qry = spawn<query_actor>(archive_, last_sender(), ast); query_state_.emplace(ast, query_state{qry, last_sender()}); // TODO: reuse results from existing queries before asking index again. send(index_, ast); reply(std::move(qry), std::move(ast)); }, on_arg_match >> [=](expr::ast const& ast, search_result const& result) { if (! result) { VAST_LOG_ACTOR_DEBUG("ignores empty result for: " << ast); return; } for (auto& node : search_.update(ast, result)) { auto er = query_state_.equal_range(node); for (auto i = er.first; i != er.second; ++i) { auto r = search_.result(node); if (r && *r && *r != i->second.result) { VAST_LOG_ACTOR_DEBUG( "propagates updated result to query @" << i->second.query->id() << " from " << i->first); i->second.result = *r; send(i->second.query, r->hits()); } } } }, others() >> [=] { VAST_LOG_ACTOR_ERROR("got unexpected message from @" << last_sender()->id() << ": " << to_string(last_dequeued())); }); } char const* search_actor::description() const { return "search"; } } // namespace vast <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: TestLinearExtractor3D.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm 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. =========================================================================*/ // .SECTION Thanks // This test was written by Philippe Pebay, Kitware SAS 2011 #include "vtkExtractSelection.h" #include "vtkIdTypeArray.h" #include "vtkInformation.h" #include "vtkLinearExtractor.h" #include "vtkMultiBlockDataSet.h" #include "vtkSelection.h" #include "vtkSelectionNode.h" #include "vtkSmartPointer.h" #include "vtkTestUtilities.h" #include "vtkUnstructuredGrid.h" #include "vtkUnstructuredGridReader.h" // Reference values vtkIdType cardSelection[] = { 53, 53, 106, 44, }; // ------------------------------------------------------------------------------------------------ static int CheckExtractedUGrid( vtkExtractSelection* extract, const char* tag, int testIdx ) { // Output must be a multiblock dataset vtkMultiBlockDataSet* outputMB = vtkMultiBlockDataSet::SafeDownCast( extract->GetOutput() ); if ( ! outputMB ) { vtkGenericWarningMacro("Cannot downcast extracted selection to multiblock dataset."); return 1; } // First block must be an unstructured grid vtkUnstructuredGrid* ugrid = vtkUnstructuredGrid::SafeDownCast( outputMB->GetBlock( 0 ) ); if ( ! ugrid ) { vtkGenericWarningMacro("Cannot downcast extracted selection to unstructured grid."); return 1; } // Initialize test status int testStatus = 0; // Verify selection cardinality vtkIdType nCells = ugrid->GetNumberOfCells(); cout << tag << " contains " << nCells << " cells." << endl; if ( nCells != cardSelection[testIdx] ) { vtkGenericWarningMacro( "Incorrect cardinality: " << nCells << " != " << cardSelection[testIdx] ); testStatus = 1; } return testStatus; } //---------------------------------------------------------------------------- int TestLinearExtractor3D( int argc, char * argv [] ) { // Initialize test value int testIntValue = 0; // Read 3D unstructured input mesh char* fileName = vtkTestUtilities::ExpandDataFileName( argc, argv, "Data/AngularSector.vtk"); vtkSmartPointer<vtkUnstructuredGridReader> reader = vtkSmartPointer<vtkUnstructuredGridReader>::New(); reader->SetFileName( fileName ); reader->Update(); // Create multi-block mesh for linear extractor vtkSmartPointer<vtkMultiBlockDataSet> mesh = vtkSmartPointer<vtkMultiBlockDataSet>::New(); mesh->SetNumberOfBlocks( 1 ); mesh->GetMetaData( static_cast<unsigned>( 0 ) )->Set( vtkCompositeDataSet::NAME(), "Mesh" ); mesh->SetBlock( 0, reader->GetOutput() ); // ***************************************************************************** // 0. Selection along inner segment with endpoints (0,0,0) and (.23, 04,.04) // ***************************************************************************** // Create selection along one line segment vtkSmartPointer<vtkLinearExtractor> le0 = vtkSmartPointer<vtkLinearExtractor>::New(); le0->SetInput( mesh ); le0->SetStartPoint( .0, .0, .0 ); le0->SetEndPoint( .23, .04, .04 ); le0->IncludeVerticesOff(); le0->SetVertexEliminationTolerance( 1.e-12 ); // Extract selection from mesh vtkSmartPointer<vtkExtractSelection> es0 = vtkSmartPointer<vtkExtractSelection>::New(); es0->SetInput( 0, mesh ); es0->SetInputConnection( 1, le0->GetOutputPort() ); es0->Update(); testIntValue += CheckExtractedUGrid( es0, "Selection (0,0,0)-(0.23,0.04,0.04)", 0 ); // ***************************************************************************** // 1. Selection along boundary segment with endpoints (0,0,0) and (.23,0,0) // ***************************************************************************** // Create selection along one line segment vtkSmartPointer<vtkLinearExtractor> le1 = vtkSmartPointer<vtkLinearExtractor>::New(); le1->SetInput( mesh ); le1->SetStartPoint( .0, .0, .0 ); le1->SetEndPoint( .23, .0, .0 ); le1->IncludeVerticesOff(); le1->SetVertexEliminationTolerance( 1.e-12 ); // Extract selection from mesh vtkSmartPointer<vtkExtractSelection> es1 = vtkSmartPointer<vtkExtractSelection>::New(); es1->SetInput( 0, mesh ); es1->SetInputConnection( 1, le1->GetOutputPort() ); es1->Update(); testIntValue += CheckExtractedUGrid( es1, "Selection (0,0,0)-(0.23,0,0)", 1 ); // ***************************************************************************** // 2. Selection along broken line through (.23,0,0), (0,0,0), (.23,.04,.04) // ***************************************************************************** // Create list of points to define broken line vtkSmartPointer<vtkPoints> points2 = vtkSmartPointer<vtkPoints>::New(); points2->InsertNextPoint( .23, .0, .0 ); points2->InsertNextPoint( .0, .0, .0 ); points2->InsertNextPoint( .23, .04, .04 ); // Create selection along this broken line vtkSmartPointer<vtkLinearExtractor> le2 = vtkSmartPointer<vtkLinearExtractor>::New(); le2->SetInput( mesh ); le2->SetPoints( points2 ); le2->IncludeVerticesOff(); le2->SetVertexEliminationTolerance( 1.e-12 ); // Extract selection from mesh vtkSmartPointer<vtkExtractSelection> es2 = vtkSmartPointer<vtkExtractSelection>::New(); es2->SetInput( 0, mesh ); es2->SetInputConnection( 1, le2->GetOutputPort() ); es2->Update(); testIntValue += CheckExtractedUGrid( es2, "Selection (0.23,0,0)-(0,0,0)-(0.23,0.04,0.04)", 2 ); // ***************************************************************************** // 3. Selection along broken line through (.23,0,0), (.1,0,0), (.23,.01,.0033) // ***************************************************************************** // Create list of points to define broken line vtkSmartPointer<vtkPoints> points3 = vtkSmartPointer<vtkPoints>::New(); points3->InsertNextPoint( .23, .0, .0 ); points3->InsertNextPoint( .1, .0, .0 ); points3->InsertNextPoint( .23, .01, .0033 ); // Create selection along this broken line vtkSmartPointer<vtkLinearExtractor> le3 = vtkSmartPointer<vtkLinearExtractor>::New(); le3->SetInput( mesh ); le3->SetPoints( points3 ); le3->IncludeVerticesOff(); le3->SetVertexEliminationTolerance( 1.e-12 ); // Extract selection from mesh vtkSmartPointer<vtkExtractSelection> es3 = vtkSmartPointer<vtkExtractSelection>::New(); es3->SetInput( 0, mesh ); es3->SetInputConnection( 1, le3->GetOutputPort() ); es3->Update(); testIntValue += CheckExtractedUGrid( es3, "Selection (0.23,0,0)-(0.1,0,0)-(0.23,0.01,0.0033)", 3 ); return testIntValue; } <commit_msg>Checking cell vertex indices as well<commit_after>/*========================================================================= Program: Visualization Toolkit Module: TestLinearExtractor3D.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm 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. =========================================================================*/ // .SECTION Thanks // This test was written by Philippe Pebay, Kitware SAS 2011 #include "vtkCellArray.h" #include "vtkExtractSelection.h" #include "vtkIdTypeArray.h" #include "vtkInformation.h" #include "vtkLinearExtractor.h" #include "vtkMultiBlockDataSet.h" #include "vtkSelection.h" #include "vtkSelectionNode.h" #include "vtkSmartPointer.h" #include "vtkTestUtilities.h" #include "vtkUnstructuredGrid.h" #include "vtkUnstructuredGridReader.h" // Reference values vtkIdType cardSelection[] = { 53, 53, 106, 44, }; // ------------------------------------------------------------------------------------------------ static int CheckExtractedUGrid( vtkExtractSelection* extract, const char* tag, int testIdx ) { // Output must be a multiblock dataset vtkMultiBlockDataSet* outputMB = vtkMultiBlockDataSet::SafeDownCast( extract->GetOutput() ); if ( ! outputMB ) { vtkGenericWarningMacro("Cannot downcast extracted selection to multiblock dataset."); return 1; } // First block must be an unstructured grid vtkUnstructuredGrid* ugrid = vtkUnstructuredGrid::SafeDownCast( outputMB->GetBlock( 0 ) ); if ( ! ugrid ) { vtkGenericWarningMacro("Cannot downcast extracted selection to unstructured grid."); return 1; } // Initialize test status int testStatus = 0; // Verify selection cardinality vtkIdType nCells = ugrid->GetNumberOfCells(); cout << tag << " contains " << nCells << " cells." << endl; if ( nCells != cardSelection[testIdx] ) { vtkGenericWarningMacro( "Incorrect cardinality: " << nCells << " != " << cardSelection[testIdx] ); testStatus = 1; } // Verify selection cells vtkCellArray* cells = ugrid->GetCells(); vtkIdTypeArray* pids = cells->GetData(); cerr << "num of tuples: " << pids->GetNumberOfTuples() << endl; vtkIdType cnt = 0; vtkIdType length = 0; vtkIdType cellId = 0; for ( vtkIdType i = 0; i < pids->GetNumberOfTuples(); ++ i ) { vtkIdType val = pids->GetValue( i ); if ( cnt == length ) { length = val; cnt = 0; if ( i ) { cerr << endl; } cerr << "Cell " << cellId << ": "; ++ cellId; } else { cerr << val << " "; ++ cnt; } } return testStatus; } //---------------------------------------------------------------------------- int TestLinearExtractor3D( int argc, char * argv [] ) { // Initialize test value int testIntValue = 0; // Read 3D unstructured input mesh char* fileName = vtkTestUtilities::ExpandDataFileName( argc, argv, "Data/AngularSector.vtk"); vtkSmartPointer<vtkUnstructuredGridReader> reader = vtkSmartPointer<vtkUnstructuredGridReader>::New(); reader->SetFileName( fileName ); reader->Update(); // Create multi-block mesh for linear extractor vtkSmartPointer<vtkMultiBlockDataSet> mesh = vtkSmartPointer<vtkMultiBlockDataSet>::New(); mesh->SetNumberOfBlocks( 1 ); mesh->GetMetaData( static_cast<unsigned>( 0 ) )->Set( vtkCompositeDataSet::NAME(), "Mesh" ); mesh->SetBlock( 0, reader->GetOutput() ); // ***************************************************************************** // 0. Selection along inner segment with endpoints (0,0,0) and (.23, 04,.04) // ***************************************************************************** // Create selection along one line segment vtkSmartPointer<vtkLinearExtractor> le0 = vtkSmartPointer<vtkLinearExtractor>::New(); le0->SetInput( mesh ); le0->SetStartPoint( .0, .0, .0 ); le0->SetEndPoint( .23, .04, .04 ); le0->IncludeVerticesOff(); le0->SetVertexEliminationTolerance( 1.e-12 ); // Extract selection from mesh vtkSmartPointer<vtkExtractSelection> es0 = vtkSmartPointer<vtkExtractSelection>::New(); es0->SetInput( 0, mesh ); es0->SetInputConnection( 1, le0->GetOutputPort() ); es0->Update(); testIntValue += CheckExtractedUGrid( es0, "Selection (0,0,0)-(0.23,0.04,0.04)", 0 ); // ***************************************************************************** // 1. Selection along boundary segment with endpoints (0,0,0) and (.23,0,0) // ***************************************************************************** // Create selection along one line segment vtkSmartPointer<vtkLinearExtractor> le1 = vtkSmartPointer<vtkLinearExtractor>::New(); le1->SetInput( mesh ); le1->SetStartPoint( .0, .0, .0 ); le1->SetEndPoint( .23, .0, .0 ); le1->IncludeVerticesOff(); le1->SetVertexEliminationTolerance( 1.e-12 ); // Extract selection from mesh vtkSmartPointer<vtkExtractSelection> es1 = vtkSmartPointer<vtkExtractSelection>::New(); es1->SetInput( 0, mesh ); es1->SetInputConnection( 1, le1->GetOutputPort() ); es1->Update(); testIntValue += CheckExtractedUGrid( es1, "Selection (0,0,0)-(0.23,0,0)", 1 ); // ***************************************************************************** // 2. Selection along broken line through (.23,0,0), (0,0,0), (.23,.04,.04) // ***************************************************************************** // Create list of points to define broken line vtkSmartPointer<vtkPoints> points2 = vtkSmartPointer<vtkPoints>::New(); points2->InsertNextPoint( .23, .0, .0 ); points2->InsertNextPoint( .0, .0, .0 ); points2->InsertNextPoint( .23, .04, .04 ); // Create selection along this broken line vtkSmartPointer<vtkLinearExtractor> le2 = vtkSmartPointer<vtkLinearExtractor>::New(); le2->SetInput( mesh ); le2->SetPoints( points2 ); le2->IncludeVerticesOff(); le2->SetVertexEliminationTolerance( 1.e-12 ); // Extract selection from mesh vtkSmartPointer<vtkExtractSelection> es2 = vtkSmartPointer<vtkExtractSelection>::New(); es2->SetInput( 0, mesh ); es2->SetInputConnection( 1, le2->GetOutputPort() ); es2->Update(); testIntValue += CheckExtractedUGrid( es2, "Selection (0.23,0,0)-(0,0,0)-(0.23,0.04,0.04)", 2 ); // ***************************************************************************** // 3. Selection along broken line through (.23,0,0), (.1,0,0), (.23,.01,.0033) // ***************************************************************************** // Create list of points to define broken line vtkSmartPointer<vtkPoints> points3 = vtkSmartPointer<vtkPoints>::New(); points3->InsertNextPoint( .23, .0, .0 ); points3->InsertNextPoint( .1, .0, .0 ); points3->InsertNextPoint( .23, .01, .0033 ); // Create selection along this broken line vtkSmartPointer<vtkLinearExtractor> le3 = vtkSmartPointer<vtkLinearExtractor>::New(); le3->SetInput( mesh ); le3->SetPoints( points3 ); le3->IncludeVerticesOff(); le3->SetVertexEliminationTolerance( 1.e-12 ); // Extract selection from mesh vtkSmartPointer<vtkExtractSelection> es3 = vtkSmartPointer<vtkExtractSelection>::New(); es3->SetInput( 0, mesh ); es3->SetInputConnection( 1, le3->GetOutputPort() ); es3->Update(); testIntValue += CheckExtractedUGrid( es3, "Selection (0.23,0,0)-(0.1,0,0)-(0.23,0.01,0.0033)", 3 ); return testIntValue; } <|endoftext|>
<commit_before>#include "vast/search.h" #include "vast/exception.h" #include "vast/optional.h" #include "vast/query.h" #include "vast/util/make_unique.h" namespace vast { namespace { // Deconstructs an entire query AST into its individual sub-trees and adds // each to the state map. class dissector : public expr::default_const_visitor { public: dissector(std::map<expr::ast, search::state>& state, expr::ast const& base) : state_{state}, base_{base} { } virtual void visit(expr::conjunction const& conj) { expr::ast ast{conj}; if (parent_) state_[ast].parents.insert(parent_); else if (ast == base_) state_.emplace(ast, search::state{}); parent_ = std::move(ast); for (auto& clause : conj.operands) clause->accept(*this); } virtual void visit(expr::disjunction const& disj) { expr::ast ast{disj}; if (parent_) state_[ast].parents.insert(parent_); else if (ast == base_) state_.emplace(ast, search::state{}); parent_ = std::move(ast); for (auto& term : disj.operands) term->accept(*this); } virtual void visit(expr::relation const& rel) { assert(parent_); expr::ast ast{rel}; state_[ast].parents.insert(parent_); } private: expr::ast parent_; std::map<expr::ast, search::state>& state_; expr::ast const& base_; }; struct node_tester : public expr::default_const_visitor { virtual void visit(expr::conjunction const&) { type = logical_and; } virtual void visit(expr::disjunction const&) { type = logical_or; } optional<boolean_operator> type; }; // Computes the result of a conjunction by ANDing the results of all of its // child nodes. struct conjunction_evaluator : public expr::default_const_visitor { conjunction_evaluator(std::map<expr::ast, search::state>& state) : state{state} { } virtual void visit(expr::conjunction const& conj) { for (auto& operand : conj.operands) if (complete) operand->accept(*this); } virtual void visit(expr::disjunction const& disj) { if (complete) update(disj); } virtual void visit(expr::relation const& rel) { if (complete) update(rel); } void update(expr::ast const& child) { auto i = state.find(child); assert(i != state.end()); auto& child_result = i->second.result; if (! child_result) { complete = false; return; } result &= child_result; } bool complete = true; search_result result; std::map<expr::ast, search::state> const& state; }; struct disjunction_evaluator : public expr::default_const_visitor { disjunction_evaluator(std::map<expr::ast, search::state>& state) : state{state} { } virtual void visit(expr::conjunction const& conj) { update(conj); } virtual void visit(expr::disjunction const& disj) { for (auto& operand : disj.operands) operand->accept(*this); } virtual void visit(expr::relation const& rel) { update(rel); } void update(expr::ast const& child) { auto i = state.find(child); assert(i != state.end()); auto& child_result = i->second.result; if (child_result) result |= child_result; } search_result result; std::map<expr::ast, search::state> const& state; }; } // namespace <anonymous> expr::ast search::add_query(std::string const& str) { expr::ast ast{str}; if (! ast) return ast; dissector d{state_, ast}; ast.accept(d); return ast; } std::vector<expr::ast> search::update(expr::ast const& ast, search_result const& result) { assert(result); assert(state_.count(ast)); auto& ast_state = state_[ast]; node_tester nt; ast.accept(nt); // Phase 1: update the current AST node's state. if (nt.type) { if (*nt.type == logical_and) { VAST_LOG_VERBOSE("evaluating conjunction " << ast); conjunction_evaluator ce{state_}; ast.accept(ce); if (ce.complete) ast_state.result = std::move(ce.result); VAST_LOG_DEBUG((ce.complete ? "" : "in") << "complete evaluation"); } else if (*nt.type == logical_or) { VAST_LOG_VERBOSE("evaluating disjunction " << ast); disjunction_evaluator de{state_}; ast.accept(de); if (! ast_state.result || (de.result && de.result != ast_state.result)) ast_state.result = std::move(de.result); } } else if (! ast_state.result) { VAST_LOG_VERBOSE("assigning result to " << ast); ast_state.result = std::move(result); } else if (nt.type && *nt.type == logical_or) { } else if (ast_state.result == result) { assert(ast_state.result.hits()); assert(ast_state.result == result); VAST_LOG_VERBOSE("ignoring unchanged result for " << ast); } else { VAST_LOG_VERBOSE("computing new result for " << ast); ast_state.result |= result; } // Phase 2: Update the parents recursively. std::vector<expr::ast> path; for (auto& parent : ast_state.parents) { auto pp = update(parent, ast_state.result); std::move(pp.begin(), pp.end(), std::back_inserter(path)); } path.push_back(ast); std::sort(path.begin(), path.end()); path.erase(std::unique(path.begin(), path.end()), path.end()); return path; } search_result const* search::result(expr::ast const& ast) const { auto i = state_.find(ast); return i != state_.end() ? &i->second.result : nullptr; } using namespace cppa; search_actor::query_state::query_state(actor_ptr q, actor_ptr c) : query{q}, client{c} { } search_actor::search_actor(actor_ptr archive, actor_ptr index, actor_ptr schema_manager) : archive_{std::move(archive)}, index_{std::move(index)}, schema_manager_{std::move(schema_manager)} { } void search_actor::act() { trap_exit(true); become( on(atom("EXIT"), arg_match) >> [=](uint32_t reason) { std::set<actor_ptr> doomed; for (auto& p : query_state_) { doomed.insert(p.second.query); doomed.insert(p.second.client); } for (auto& d : doomed) send_exit(d, exit::stop); quit(reason); }, on(atom("DOWN"), arg_match) >> [=](uint32_t) { VAST_LOG_ACTOR_DEBUG( "received DOWN from client @" << last_sender()->id()); std::set<actor_ptr> doomed; for (auto& p : query_state_) { if (p.second.client == last_sender()) { doomed.insert(p.second.query); doomed.insert(p.second.client); } } for (auto& d : doomed) send_exit(d, exit::stop); }, on(atom("query"), atom("create"), arg_match) >> [=](std::string const& q) { auto ast = search_.add_query(q); if (! ast) { reply(actor_ptr{}, ast); return; } VAST_LOG_ACTOR_DEBUG("received new query: " << ast); monitor(last_sender()); auto qry = spawn<query_actor>(archive_, last_sender(), ast); query_state_.emplace(ast, query_state{qry, last_sender()}); // TODO: reuse results from existing queries before asking index again. send(index_, ast); reply(std::move(qry), std::move(ast)); }, on_arg_match >> [=](expr::ast const& ast, search_result const& result) { if (! result) { VAST_LOG_ACTOR_DEBUG("ignores empty result for: " << ast); return; } for (auto& node : search_.update(ast, result)) { auto er = query_state_.equal_range(node); for (auto i = er.first; i != er.second; ++i) { auto r = search_.result(node); if (r && *r && *r != i->second.result) { VAST_LOG_ACTOR_DEBUG( "propagates updated result to query @" << i->second.query->id() << " from " << i->first); i->second.result = *r; send(i->second.query, r->hits()); } } } }, others() >> [=] { VAST_LOG_ACTOR_ERROR("got unexpected message from @" << last_sender()->id() << ": " << to_string(last_dequeued())); }); } char const* search_actor::description() const { return "search"; } } // namespace vast <commit_msg>Remove stale branch.<commit_after>#include "vast/search.h" #include "vast/exception.h" #include "vast/optional.h" #include "vast/query.h" #include "vast/util/make_unique.h" namespace vast { namespace { // Deconstructs an entire query AST into its individual sub-trees and adds // each to the state map. class dissector : public expr::default_const_visitor { public: dissector(std::map<expr::ast, search::state>& state, expr::ast const& base) : state_{state}, base_{base} { } virtual void visit(expr::conjunction const& conj) { expr::ast ast{conj}; if (parent_) state_[ast].parents.insert(parent_); else if (ast == base_) state_.emplace(ast, search::state{}); parent_ = std::move(ast); for (auto& clause : conj.operands) clause->accept(*this); } virtual void visit(expr::disjunction const& disj) { expr::ast ast{disj}; if (parent_) state_[ast].parents.insert(parent_); else if (ast == base_) state_.emplace(ast, search::state{}); parent_ = std::move(ast); for (auto& term : disj.operands) term->accept(*this); } virtual void visit(expr::relation const& rel) { assert(parent_); expr::ast ast{rel}; state_[ast].parents.insert(parent_); } private: expr::ast parent_; std::map<expr::ast, search::state>& state_; expr::ast const& base_; }; struct node_tester : public expr::default_const_visitor { virtual void visit(expr::conjunction const&) { type = logical_and; } virtual void visit(expr::disjunction const&) { type = logical_or; } optional<boolean_operator> type; }; // Computes the result of a conjunction by ANDing the results of all of its // child nodes. struct conjunction_evaluator : public expr::default_const_visitor { conjunction_evaluator(std::map<expr::ast, search::state>& state) : state{state} { } virtual void visit(expr::conjunction const& conj) { for (auto& operand : conj.operands) if (complete) operand->accept(*this); } virtual void visit(expr::disjunction const& disj) { if (complete) update(disj); } virtual void visit(expr::relation const& rel) { if (complete) update(rel); } void update(expr::ast const& child) { auto i = state.find(child); assert(i != state.end()); auto& child_result = i->second.result; if (! child_result) { complete = false; return; } result &= child_result; } bool complete = true; search_result result; std::map<expr::ast, search::state> const& state; }; struct disjunction_evaluator : public expr::default_const_visitor { disjunction_evaluator(std::map<expr::ast, search::state>& state) : state{state} { } virtual void visit(expr::conjunction const& conj) { update(conj); } virtual void visit(expr::disjunction const& disj) { for (auto& operand : disj.operands) operand->accept(*this); } virtual void visit(expr::relation const& rel) { update(rel); } void update(expr::ast const& child) { auto i = state.find(child); assert(i != state.end()); auto& child_result = i->second.result; if (child_result) result |= child_result; } search_result result; std::map<expr::ast, search::state> const& state; }; } // namespace <anonymous> expr::ast search::add_query(std::string const& str) { expr::ast ast{str}; if (! ast) return ast; dissector d{state_, ast}; ast.accept(d); return ast; } std::vector<expr::ast> search::update(expr::ast const& ast, search_result const& result) { assert(result); assert(state_.count(ast)); auto& ast_state = state_[ast]; node_tester nt; ast.accept(nt); // Phase 1: update the current AST node's state. if (nt.type) { if (*nt.type == logical_and) { VAST_LOG_VERBOSE("evaluating conjunction " << ast); conjunction_evaluator ce{state_}; ast.accept(ce); if (ce.complete) ast_state.result = std::move(ce.result); VAST_LOG_DEBUG((ce.complete ? "" : "in") << "complete evaluation"); } else if (*nt.type == logical_or) { VAST_LOG_VERBOSE("evaluating disjunction " << ast); disjunction_evaluator de{state_}; ast.accept(de); if (! ast_state.result || (de.result && de.result != ast_state.result)) ast_state.result = std::move(de.result); } } else if (! ast_state.result) { VAST_LOG_VERBOSE("assigning result to " << ast); ast_state.result = std::move(result); } else if (ast_state.result == result) { assert(ast_state.result.hits()); assert(ast_state.result == result); VAST_LOG_VERBOSE("ignoring unchanged result for " << ast); } else { VAST_LOG_VERBOSE("computing new result for " << ast); ast_state.result |= result; } // Phase 2: Update the parents recursively. std::vector<expr::ast> path; for (auto& parent : ast_state.parents) { auto pp = update(parent, ast_state.result); std::move(pp.begin(), pp.end(), std::back_inserter(path)); } path.push_back(ast); std::sort(path.begin(), path.end()); path.erase(std::unique(path.begin(), path.end()), path.end()); return path; } search_result const* search::result(expr::ast const& ast) const { auto i = state_.find(ast); return i != state_.end() ? &i->second.result : nullptr; } using namespace cppa; search_actor::query_state::query_state(actor_ptr q, actor_ptr c) : query{q}, client{c} { } search_actor::search_actor(actor_ptr archive, actor_ptr index, actor_ptr schema_manager) : archive_{std::move(archive)}, index_{std::move(index)}, schema_manager_{std::move(schema_manager)} { } void search_actor::act() { trap_exit(true); become( on(atom("EXIT"), arg_match) >> [=](uint32_t reason) { std::set<actor_ptr> doomed; for (auto& p : query_state_) { doomed.insert(p.second.query); doomed.insert(p.second.client); } for (auto& d : doomed) send_exit(d, exit::stop); quit(reason); }, on(atom("DOWN"), arg_match) >> [=](uint32_t) { VAST_LOG_ACTOR_DEBUG( "received DOWN from client @" << last_sender()->id()); std::set<actor_ptr> doomed; for (auto& p : query_state_) { if (p.second.client == last_sender()) { doomed.insert(p.second.query); doomed.insert(p.second.client); } } for (auto& d : doomed) send_exit(d, exit::stop); }, on(atom("query"), atom("create"), arg_match) >> [=](std::string const& q) { auto ast = search_.add_query(q); if (! ast) { reply(actor_ptr{}, ast); return; } VAST_LOG_ACTOR_DEBUG("received new query: " << ast); monitor(last_sender()); auto qry = spawn<query_actor>(archive_, last_sender(), ast); query_state_.emplace(ast, query_state{qry, last_sender()}); // TODO: reuse results from existing queries before asking index again. send(index_, ast); reply(std::move(qry), std::move(ast)); }, on_arg_match >> [=](expr::ast const& ast, search_result const& result) { if (! result) { VAST_LOG_ACTOR_DEBUG("ignores empty result for: " << ast); return; } for (auto& node : search_.update(ast, result)) { auto er = query_state_.equal_range(node); for (auto i = er.first; i != er.second; ++i) { auto r = search_.result(node); if (r && *r && *r != i->second.result) { VAST_LOG_ACTOR_DEBUG( "propagates updated result to query @" << i->second.query->id() << " from " << i->first); i->second.result = *r; send(i->second.query, r->hits()); } } } }, others() >> [=] { VAST_LOG_ACTOR_ERROR("got unexpected message from @" << last_sender()->id() << ": " << to_string(last_dequeued())); }); } char const* search_actor::description() const { return "search"; } } // namespace vast <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: TestMatlabEngineFilter.cxx ------------------------------------------------------------------------- Copyright 2008 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. ------------------------------------------------------------------------- Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm 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 <vtkMatlabEngineFilter.h> #include <vtkSmartPointer.h> #include <vtkCylinderSource.h> #include <vtkDataSet.h> #include <vtkPointData.h> #include <vtkDoubleArray.h> #include <vtkArrayExtents.h> #include <vtkRRandomTableSource.h> #include <vtkTable.h> #include <vtkTableToSparseArray.h> #include <vtkDenseArray.h> #include <vtksys/ios/iostream> #include <vtksys/ios/sstream> #include <vtksys/stl/stdexcept> namespace { #define test_expression(expression) \ { \ if(!(expression)) \ { \ vtksys_ios::ostringstream buffer; \ buffer << "Expression failed at line " << __LINE__ << ": " << #expression; \ throw vtkstd::runtime_error(buffer.str()); \ } \ } bool doubleEquals(double left, double right, double epsilon) { return (fabs(left - right) < epsilon); } } int TestMatlabEngineFilter(int vtkNotUsed(argc), char *vtkNotUsed(argv)[]) { try { int i; vtkCylinderSource* cs = vtkCylinderSource::New(); vtkMatlabEngineFilter* mef = vtkMatlabEngineFilter::New(); vtkRRandomTableSource* rts = vtkRRandomTableSource::New(); vtkMatlabEngineFilter* mef2 = vtkMatlabEngineFilter::New(); vtkDataSet* ds; vtkPointData* pd; vtkDoubleArray* da; vtkDoubleArray* rda; cs->SetResolution(10); mef->SetInputConnection(cs->GetOutputPort()); mef->SetEngineVisible(0); mef->SetEngineOutput(0); mef->PutArray("Normals", "Norm"); mef->PutArray("TCoords", "TCoords"); mef->GetArray("Normalsnew", "Norm"); mef->GetArray("TCoordsnew", "TCoords"); mef->SetMatlabScript("Norm = Norm.^2\nTCoords = TCoords + TCoords\n"); mef->Update(); ds = vtkDataSet::SafeDownCast(mef->GetOutput()); pd = ds->GetPointData(); da = (vtkDoubleArray*) pd->GetArray("Normals"); rda = (vtkDoubleArray*) pd->GetArray("Normalsnew"); for(i=0;i<da->GetNumberOfTuples();i++) { double* itup = da->GetTuple3(i); double* rtup = rda->GetTuple3(i); test_expression(doubleEquals(rtup[0],pow(itup[0],2),0.0001)); test_expression(doubleEquals(rtup[1],pow(itup[1],2),0.0001)); test_expression(doubleEquals(rtup[2],pow(itup[2],2),0.0001)); } da = (vtkDoubleArray*) pd->GetArray("TCoords"); rda = (vtkDoubleArray*) pd->GetArray("TCoordsnew"); for(i=0;i<da->GetNumberOfTuples();i++) { double* itup = da->GetTuple2(i); double* rtup = rda->GetTuple2(i); test_expression(doubleEquals(rtup[0],itup[0]+itup[0],0.0001)); test_expression(doubleEquals(rtup[1],itup[1]+itup[1],0.0001)); } rts->SetNumberOfRows(20); rts->SetStatisticalDistributionForColumn(vtkRRandomTableSource::NORMAL,0.0,1.0,0.0,"Variable One",0); rts->SetStatisticalDistributionForColumn(vtkRRandomTableSource::NORMAL,0.0,1.0,0.0,"Variable Two",1); rts->SetStatisticalDistributionForColumn(vtkRRandomTableSource::NORMAL,0.0,1.0,0.0,"Variable Three",2); rts->SetStatisticalDistributionForColumn(vtkRRandomTableSource::NORMAL,0.0,1.0,0.0,"Variable Four",3); mef2->SetInputConnection(rts->GetOutputPort()); mef2->RemoveAllGetVariables(); mef2->RemoveAllPutVariables(); mef2->SetEngineVisible(0); mef2->SetEngineOutput(0); mef2->PutArray("Variable One", "v1"); mef2->PutArray("Variable Two", "v2"); mef2->PutArray("Variable Three", "v3"); mef2->PutArray("Variable Four", "v4"); mef2->GetArray("Variable One", "v1"); mef2->GetArray("Variable Two", "v2"); mef2->GetArray("Variable Three", "v3"); mef2->GetArray("Variable Four", "v4"); mef2->SetMatlabScript("v1 = (randperm(20) - 1)'\n\ v2 = (randperm(20) - 1)'\n\ v3 = (randperm(20) - 1)'\n"); mef2->Update(); vtkTable* table = vtkTable::SafeDownCast(mef2->GetOutput()); vtkSmartPointer<vtkTableToSparseArray> source = vtkSmartPointer<vtkTableToSparseArray>::New(); source->AddInputConnection(mef2->GetOutputPort()); source->AddCoordinateColumn("Variable One"); source->AddCoordinateColumn("Variable Two"); source->AddCoordinateColumn("Variable Three"); source->SetValueColumn("Variable Four"); mef->SetInputConnection(source->GetOutputPort()); mef->RemoveAllPutVariables(); mef->RemoveAllGetVariables(); mef->PutArray("0","a"); mef->GetArray("1","a"); mef->SetMatlabScript("a = sqrt(a + 5.0);\n"); mef->Update(); vtkDenseArray<double>* const dense_array = vtkDenseArray<double>::SafeDownCast(vtkArrayData::SafeDownCast(mef->GetOutput())->GetArray(1)); test_expression(dense_array); for(i=0;i<table->GetNumberOfColumns();i++) { int ind0 = table->GetValue(i,0).ToInt(); int ind1 = table->GetValue(i,1).ToInt(); int ind2 = table->GetValue(i,2).ToInt(); double table_val = rts->GetOutput()->GetValue(i,3).ToDouble(); double dense_val = dense_array->GetValue(vtkArrayCoordinates(ind0,ind1,ind2)); test_expression(doubleEquals(sqrt(table_val + 5.0),dense_val,0.0001)); } cs->Delete(); rts->Delete(); mef->Delete(); mef2->Delete(); return 0; } catch(vtkstd::exception& e) { cerr << e.what() << endl; return 1; } } <commit_msg>ENH: Removed dependence on vtkRRandomTableSource.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: TestMatlabEngineFilter.cxx ------------------------------------------------------------------------- Copyright 2008 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. ------------------------------------------------------------------------- Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm 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 <vtkMatlabEngineFilter.h> #include <vtkSmartPointer.h> #include <vtkCylinderSource.h> #include <vtkDataSet.h> #include <vtkPointData.h> #include <vtkDoubleArray.h> #include <vtkArrayExtents.h> #include <vtkMath.h> #include <vtkTable.h> #include <vtkTableToSparseArray.h> #include <vtkDenseArray.h> #include <vtksys/ios/iostream> #include <vtksys/ios/sstream> #include <vtksys/stl/stdexcept> namespace { #define test_expression(expression) \ { \ if(!(expression)) \ { \ vtksys_ios::ostringstream buffer; \ buffer << "Expression failed at line " << __LINE__ << ": " << #expression; \ throw vtkstd::runtime_error(buffer.str()); \ } \ } bool doubleEquals(double left, double right, double epsilon) { return (fabs(left - right) < epsilon); } } int TestMatlabEngineFilter(int vtkNotUsed(argc), char *vtkNotUsed(argv)[]) { try { int i; vtkCylinderSource* cs = vtkCylinderSource::New(); vtkMatlabEngineFilter* mef = vtkMatlabEngineFilter::New(); vtkMatlabEngineFilter* mef2 = vtkMatlabEngineFilter::New(); vtkDataSet* ds; vtkPointData* pd; vtkDoubleArray* da; vtkDoubleArray* rda; cs->SetResolution(10); mef->SetInputConnection(cs->GetOutputPort()); mef->SetEngineVisible(0); mef->SetEngineOutput(0); mef->PutArray("Normals", "Norm"); mef->PutArray("TCoords", "TCoords"); mef->GetArray("Normalsnew", "Norm"); mef->GetArray("TCoordsnew", "TCoords"); mef->SetMatlabScript("Norm = Norm.^2\nTCoords = TCoords + TCoords\n"); mef->Update(); ds = vtkDataSet::SafeDownCast(mef->GetOutput()); pd = ds->GetPointData(); da = (vtkDoubleArray*) pd->GetArray("Normals"); rda = (vtkDoubleArray*) pd->GetArray("Normalsnew"); for(i=0;i<da->GetNumberOfTuples();i++) { double* itup = da->GetTuple3(i); double* rtup = rda->GetTuple3(i); test_expression(doubleEquals(rtup[0],pow(itup[0],2),0.0001)); test_expression(doubleEquals(rtup[1],pow(itup[1],2),0.0001)); test_expression(doubleEquals(rtup[2],pow(itup[2],2),0.0001)); } da = (vtkDoubleArray*) pd->GetArray("TCoords"); rda = (vtkDoubleArray*) pd->GetArray("TCoordsnew"); for(i=0;i<da->GetNumberOfTuples();i++) { double* itup = da->GetTuple2(i); double* rtup = rda->GetTuple2(i); test_expression(doubleEquals(rtup[0],itup[0]+itup[0],0.0001)); test_expression(doubleEquals(rtup[1],itup[1]+itup[1],0.0001)); } vtkTable* input_table = vtkTable::New(); vtkDoubleArray* col1 = vtkDoubleArray::New(); vtkDoubleArray* col2 = vtkDoubleArray::New(); vtkDoubleArray* col3 = vtkDoubleArray::New(); vtkDoubleArray* col4 = vtkDoubleArray::New(); col1->SetName("Variable One"); col2->SetName("Variable Two"); col3->SetName("Variable Three"); col4->SetName("Variable Four"); for(i=0;i<20;i++) { col1->InsertNextValue(vtkMath::Gaussian(0.0,1.0)); col2->InsertNextValue(vtkMath::Gaussian(0.0,1.0)); col3->InsertNextValue(vtkMath::Gaussian(0.0,1.0)); col4->InsertNextValue(vtkMath::Gaussian(0.0,1.0)); } input_table->AddColumn(col1); input_table->AddColumn(col2); input_table->AddColumn(col3); input_table->AddColumn(col4); col1->Delete(); col2->Delete(); col3->Delete(); col4->Delete(); mef2->SetInput(0,input_table); mef2->RemoveAllGetVariables(); mef2->RemoveAllPutVariables(); mef2->SetEngineVisible(0); mef2->SetEngineOutput(0); mef2->PutArray("Variable One", "v1"); mef2->PutArray("Variable Two", "v2"); mef2->PutArray("Variable Three", "v3"); mef2->PutArray("Variable Four", "v4"); mef2->GetArray("Variable One", "v1"); mef2->GetArray("Variable Two", "v2"); mef2->GetArray("Variable Three", "v3"); mef2->GetArray("Variable Four", "v4"); mef2->SetMatlabScript("v1 = (randperm(20) - 1)'\n\ v2 = (randperm(20) - 1)'\n\ v3 = (randperm(20) - 1)'\n"); mef2->Update(); vtkTable* table = vtkTable::SafeDownCast(mef2->GetOutput()); vtkSmartPointer<vtkTableToSparseArray> source = vtkSmartPointer<vtkTableToSparseArray>::New(); source->AddInputConnection(mef2->GetOutputPort()); source->AddCoordinateColumn("Variable One"); source->AddCoordinateColumn("Variable Two"); source->AddCoordinateColumn("Variable Three"); source->SetValueColumn("Variable Four"); mef->SetInputConnection(source->GetOutputPort()); mef->RemoveAllPutVariables(); mef->RemoveAllGetVariables(); mef->PutArray("0","a"); mef->GetArray("1","a"); mef->SetMatlabScript("a = sqrt(a + 5.0);\n"); mef->Update(); vtkDenseArray<double>* const dense_array = vtkDenseArray<double>::SafeDownCast(vtkArrayData::SafeDownCast(mef->GetOutput())->GetArray(1)); test_expression(dense_array); for(i=0;i<table->GetNumberOfColumns();i++) { int ind0 = table->GetValue(i,0).ToInt(); int ind1 = table->GetValue(i,1).ToInt(); int ind2 = table->GetValue(i,2).ToInt(); double table_val = input_table->GetValue(i,3).ToDouble(); double dense_val = dense_array->GetValue(vtkArrayCoordinates(ind0,ind1,ind2)); test_expression(doubleEquals(sqrt(table_val + 5.0),dense_val,0.0001)); } cs->Delete(); mef->Delete(); mef2->Delete(); return 0; } catch(vtkstd::exception& e) { cerr << e.what() << endl; return 1; } } <|endoftext|>
<commit_before>#include <string> #include <sys/wait.h> #include <unistd.h> #include <thread> #include <mutex> #include <vector> #include "module.hpp" bool Module::receive(Message* message){ if(!message){return 0;} unsigned int action = message->action; std::string body = message->body; switch(action){ case EXAMPLE_ACTION: //std::cout << "Example Action Received\n"; break; //default: //std::cout << "Unmatching Message Recieved\n"; } return 1; } bool Module::broadcast(Message* message){ if(!message){return 0;} Module::mtx.lock(); messages.addMessage(message); Module::mtx.unlock(); return 1; } bool Module::status(){ return 0; } void Module::taskRunner(void (*task)(), Message* done){ task(); broadcast(done); } void Module::runTask(void (*task)(), Message* done){ std::thread worker([this, task, done] { taskRunner(task, done); }); worker.detach(); } Message* Module::read(){ // Lock down reading from messages vector in case // another thread is also trying to use it. mtx.lock(); Message* temp = messages.readMessages(); mtx.unlock(); return temp; } <commit_msg>removed unused code<commit_after>#include <string> #include <sys/wait.h> #include <unistd.h> #include <thread> #include <mutex> #include <vector> #include "module.hpp" bool Module::receive(Message* message){ if(!message){return 0;} unsigned int action = message->action; std::string body = message->body; switch(action){ case EXAMPLE_ACTION: std::cout << "Example Action Received\n"; break; default: std::cout << "Unmatching Message Recieved\n"; } return 1; } bool Module::broadcast(Message* message){ if(!message){return 0;} Module::mtx.lock(); messages.addMessage(message); Module::mtx.unlock(); return 1; } bool Module::status(){ return 0; } void Module::taskRunner(void (*task)(), Message* done){ task(); broadcast(done); } void Module::runTask(void (*task)(), Message* done){ std::thread worker([this, task, done] { taskRunner(task, done); }); worker.detach(); } Message* Module::read(){ // Lock down reading from messages vector in case // another thread is also trying to use it. mtx.lock(); Message* temp = messages.readMessages(); mtx.unlock(); return temp; } <|endoftext|>
<commit_before>// ProgStatusBar.cpp : ʵļ // #include "stdafx.h" #include "DacrsUI.h" #include "ProgStatusBar.h" #include "afxdialogex.h" // CProgStatusBar Ի IMPLEMENT_DYNAMIC(CProgStatusBar, CDialogBar) CProgStatusBar::CProgStatusBar() { m_pBmp = NULL ; m_bProgressType = false; m_prosshiden = false; m_ProgressWnd = NULL ; m_nSigIndex = 0 ; m_walletui = false; memset(m_bmpsig , 0 , sizeof(CRect)); m_progress.ShowPercent(FALSE); m_progress.ShowDefineText(TRUE); } CProgStatusBar::~CProgStatusBar() { if( NULL != m_pBmp ) { DeleteObject(m_pBmp) ; m_pBmp = NULL ; } if ( NULL != m_ProgressWnd ) { delete m_ProgressWnd ; m_ProgressWnd = NULL ; } } void CProgStatusBar::DoDataExchange(CDataExchange* pDX) { CDialogBar::DoDataExchange(pDX); DDX_Control(pDX, IDC_PROGRESS, m_progress); DDX_Control(pDX, IDC_STATIC_NET_TB, m_strNeting); DDX_Control(pDX, IDC_STATIC_HEIGHT, m_strHeight); DDX_Control(pDX, IDC_STATIC_VERSION, m_strVersion); } BEGIN_MESSAGE_MAP(CProgStatusBar, CDialogBar) ON_WM_ERASEBKGND() ON_WM_CREATE() ON_WM_SIZE() ON_MESSAGE(MSG_USER_UP_PROGRESS , &CProgStatusBar::OnShowProgressCtrl ) ON_WM_PAINT() END_MESSAGE_MAP() // CProgStatusBar Ϣ void CProgStatusBar::SetBkBmpNid( UINT nBitmapIn ) { if( NULL != m_pBmp ) { ::DeleteObject( m_pBmp ) ; m_pBmp = NULL ; } m_pBmp = NULL ; HINSTANCE hInstResource = NULL; hInstResource = AfxFindResourceHandle(MAKEINTRESOURCE(nBitmapIn), RT_BITMAP); if( NULL != hInstResource ) { m_pBmp = (HBITMAP)::LoadImage(hInstResource, MAKEINTRESOURCE(nBitmapIn), IMAGE_BITMAP, 0, 0, 0); } } void CProgStatusBar::LoadGifing( BOOL bState ) { if( NULL != m_ProgressWnd ) { if( m_ProgressWnd->GetSafeHwnd() ) { if( TRUE == bState ) { if( TRUE == ((CGIFControl*)m_ProgressWnd)->Load(theApp.m_ProgressGifFile.GetBuffer()) ) { CRect rc ; GetClientRect( rc ) ; Invalidate() ; m_ProgressWnd->SetWindowPos( NULL , rc.Width()- 18 , (rc.Height()/2)-8 , 0 , 0 , \ SWP_SHOWWINDOW|SWP_NOSIZE ) ; ((CGIFControl*)m_ProgressWnd)->Play(); } }else{ ((CGIFControl*)m_ProgressWnd)->Stop() ; } } } } BOOL CProgStatusBar::OnEraseBkgnd(CDC* pDC) { // TODO: ڴϢ/Ĭֵ CRect rect; GetClientRect(&rect); if(m_pBmp != NULL) { BITMAP bm; CDC dcMem; ::GetObject(m_pBmp,sizeof(BITMAP), (LPVOID)&bm); dcMem.CreateCompatibleDC(NULL); HBITMAP pOldBitmap =(HBITMAP ) dcMem.SelectObject(m_pBmp); pDC-> StretchBlt(rect.left,rect.top-1,rect.Width(),rect.Height(), &dcMem, 0, 0,bm.bmWidth-1,bm.bmHeight-1, SRCCOPY); dcMem.SelectObject(pOldBitmap); dcMem.DeleteDC(); } else CWnd::OnEraseBkgnd(pDC); return 1; } int CProgStatusBar::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CDialogBar::OnCreate(lpCreateStruct) == -1) return -1; // TODO: ڴרõĴ SetBkBmpNid( IDB_BITMAP_BAR3 ) ; ModifyStyle(WS_BORDER, 0); ModifyStyleEx(WS_EX_WINDOWEDGE, 0); return 0; } void CProgStatusBar::OnSize(UINT nType, int cx, int cy) { CDialogBar::OnSize(nType, cx, cy); // TODO: ڴ˴Ϣ } BOOL CProgStatusBar::Create(CWnd* pParentWnd, UINT nIDTemplate, UINT nStyle, UINT nID) { // TODO: ڴרô/û BOOL bRes = CDialogBar::Create(pParentWnd, nIDTemplate, nStyle, nID); if ( bRes ) { UpdateData(0); m_strNeting.SetFont(90, _T("")); //ʾʹС m_strNeting.SetTextColor(RGB(255,255,255)); //ɫ // m_strNeting.SetWindowText(_T("ͬ...")); m_strNeting.SetWindowText(_T("ȡ")) ; m_strHeight.SetFont(90, _T("")); //ʾʹС m_strHeight.SetTextColor(RGB(255,255,255)); //ɫ m_strHeight.SetWindowText(_T("߶:")) ; m_strHeight.ShowWindow(SW_HIDE) ; m_strVersion.SetFont(90, _T("")); //ʾʹС m_strVersion.SetTextColor(RGB(255,255,255)); //ɫ m_strVersion.SetWindowText(_T("汾:V1.0.0.6beta")) ; if ( NULL == m_ProgressWnd ) { m_ProgressWnd = new CGIFControl ; m_ProgressWnd->Create(_T("") , WS_CHILD | SS_OWNERDRAW | WS_VISIBLE | SS_NOTIFY , \ CRect(20,20,36,36) , this, 111 ) ; } m_Sigbmp[0].LoadBitmap(IDB_BITMAP_SIG0); m_Sigbmp[1].LoadBitmap(IDB_BITMAP_SIG1); m_Sigbmp[2].LoadBitmap(IDB_BITMAP_SIG2); m_Sigbmp[3].LoadBitmap(IDB_BITMAP_SIG3); theApp.SubscribeMsg( theApp.GetMtHthrdId() , GetSafeHwnd() , MSG_USER_UP_PROGRESS ) ; m_progress.SendMessage(PBM_SETBKCOLOR, 0, RGB(66, 65, 63));//ɫ m_progress.SendMessage(PBM_SETBARCOLOR, 0, RGB(254, 153, 0));//ǰɫ //CPostMsg postmsg(MSG_USER_UP_PROGRESS,0); //theApp.m_MsgQueue.pushFront(postmsg); } return bRes ; } LRESULT CProgStatusBar::OnShowProgressCtrl( WPARAM wParam, LPARAM lParam ) { TRACE("OnShowProgressCtrl:%s\r\n","OnShowProgressCtrl"); CPostMsg postmsg; if (!theApp.m_UimsgQueue.pop(postmsg)) { return 1; } uistruct::BLOCKCHANGED_t pBlockchanged; string strTemp = postmsg.GetData(); pBlockchanged.JsonToStruct(strTemp.c_str()); if (pBlockchanged.tips <= 0) { return 1; } //// blocktip߶ theApp.blocktipheight = pBlockchanged.tips ; if (!m_bProgressType) { m_strNeting.SetWindowText(_T("ͬ...")); m_strNeting.ShowWindow(SW_HIDE); m_strNeting.ShowWindow(SW_SHOW); m_progress.SetRange32( 0 , 100); int setpos = (pBlockchanged.high*1.0/pBlockchanged.tips)*100; setpos = setpos>100?100:setpos; //ýֵ m_progress.SetPos(setpos); CString strText; strText.AppendFormat("ʣ ~%d ûͬ", pBlockchanged.tips-pBlockchanged.high); m_progress.SetDefinedStr(strText); m_bProgressType = TRUE; m_nSigIndex =pBlockchanged.connections>3?3:pBlockchanged.connections; if ((pBlockchanged.tips-pBlockchanged.high)<10 && !m_walletui) { TRACE("ok:%s\r\n","OnShowProgressCtrl"); //// Ǯͬ CPostMsg postblockmsg(MSG_USER_MAIN_UI,WM_UPWALLET); theApp.m_MsgQueue.pushFront(postblockmsg); LoadGifing(false); m_walletui = true; theApp.IsSyncBlock = true; } Invalidate(); //InvalidateRect(m_bmpsig); // return 1; } m_nSigIndex = pBlockchanged.connections>3?3:pBlockchanged.connections; int setpos = (pBlockchanged.high*1.0/pBlockchanged.tips)*100 ; setpos = setpos>100?100:setpos; //ýֵ m_progress.SetPos(setpos); CString strText; strText.AppendFormat("ʣ ~%d ûͬ", pBlockchanged.tips-pBlockchanged.high); m_progress.SetDefinedStr(strText); if ((pBlockchanged.tips-pBlockchanged.high)<10&& !m_walletui) { TRACE("ok:%s\r\n","OnShowProgressCtrl"); //// Ǯͬ CPostMsg postblockmsg(MSG_USER_MAIN_UI,WM_UPWALLET); theApp.m_MsgQueue.pushFront(postblockmsg); LoadGifing(false); m_walletui = true; theApp.IsSyncBlock = true; } if ( m_walletui && !m_prosshiden) { m_strNeting.SetWindowText(_T("ͬ")) ; m_strNeting.ShowWindow(SW_HIDE); m_strNeting.ShowWindow(SW_SHOW); m_progress.ShowWindow(SW_HIDE); if ( NULL != m_ProgressWnd ) { m_ProgressWnd->ShowWindow(SW_HIDE) ; } m_prosshiden = !m_prosshiden ; } if (m_walletui && m_prosshiden) { CString strTips; strTips.Format(_T("ǰ߶:%d") ,pBlockchanged.tips ) ; m_strHeight.SetWindowText(strTips) ; m_strHeight.ShowWindow(SW_HIDE); m_strHeight.ShowWindow(SW_SHOW); } InvalidateRect(m_bmpsig); return 1; } //Invalidate(); void CProgStatusBar::OnPaint() { CPaintDC dc(this); // device context for painting // TODO: ڴ˴Ϣ // ΪͼϢ CDialogBar::OnPaint() CDC memDC; memDC.CreateCompatibleDC(&dc); CRect rc; GetClientRect(&rc); HBITMAP hOldbmp = (HBITMAP)memDC.SelectObject(m_Sigbmp[m_nSigIndex]); dc.BitBlt(900-60, 0, rc.Width(), rc.Height(), &memDC, 0, 0, SRCCOPY); CRect rc1(900-60, 0, rc.Width(), rc.Height()); m_bmpsig = rc1; memDC.SelectObject(hOldbmp); memDC.DeleteDC(); } <commit_msg>修改调整更新动画显示位置<commit_after>// ProgStatusBar.cpp : ʵļ // #include "stdafx.h" #include "DacrsUI.h" #include "ProgStatusBar.h" #include "afxdialogex.h" // CProgStatusBar Ի IMPLEMENT_DYNAMIC(CProgStatusBar, CDialogBar) CProgStatusBar::CProgStatusBar() { m_pBmp = NULL ; m_bProgressType = false; m_prosshiden = false; m_ProgressWnd = NULL ; m_nSigIndex = 0 ; m_walletui = false; memset(m_bmpsig , 0 , sizeof(CRect)); m_progress.ShowPercent(FALSE); m_progress.ShowDefineText(TRUE); } CProgStatusBar::~CProgStatusBar() { if( NULL != m_pBmp ) { DeleteObject(m_pBmp) ; m_pBmp = NULL ; } if ( NULL != m_ProgressWnd ) { delete m_ProgressWnd ; m_ProgressWnd = NULL ; } } void CProgStatusBar::DoDataExchange(CDataExchange* pDX) { CDialogBar::DoDataExchange(pDX); DDX_Control(pDX, IDC_PROGRESS, m_progress); DDX_Control(pDX, IDC_STATIC_NET_TB, m_strNeting); DDX_Control(pDX, IDC_STATIC_HEIGHT, m_strHeight); DDX_Control(pDX, IDC_STATIC_VERSION, m_strVersion); } BEGIN_MESSAGE_MAP(CProgStatusBar, CDialogBar) ON_WM_ERASEBKGND() ON_WM_CREATE() ON_WM_SIZE() ON_MESSAGE(MSG_USER_UP_PROGRESS , &CProgStatusBar::OnShowProgressCtrl ) ON_WM_PAINT() END_MESSAGE_MAP() // CProgStatusBar Ϣ void CProgStatusBar::SetBkBmpNid( UINT nBitmapIn ) { if( NULL != m_pBmp ) { ::DeleteObject( m_pBmp ) ; m_pBmp = NULL ; } m_pBmp = NULL ; HINSTANCE hInstResource = NULL; hInstResource = AfxFindResourceHandle(MAKEINTRESOURCE(nBitmapIn), RT_BITMAP); if( NULL != hInstResource ) { m_pBmp = (HBITMAP)::LoadImage(hInstResource, MAKEINTRESOURCE(nBitmapIn), IMAGE_BITMAP, 0, 0, 0); } } void CProgStatusBar::LoadGifing( BOOL bState ) { if( NULL != m_ProgressWnd ) { if( m_ProgressWnd->GetSafeHwnd() ) { if( TRUE == bState ) { if( TRUE == ((CGIFControl*)m_ProgressWnd)->Load(theApp.m_ProgressGifFile.GetBuffer()) ) { CRect rc ; GetClientRect( rc ) ; Invalidate() ; m_ProgressWnd->SetWindowPos( NULL , rc.Width()+880 , rc.Height()+8 , 0 , 0 , \ SWP_SHOWWINDOW|SWP_NOSIZE ) ; ((CGIFControl*)m_ProgressWnd)->Play(); } }else{ ((CGIFControl*)m_ProgressWnd)->Stop() ; } } } } BOOL CProgStatusBar::OnEraseBkgnd(CDC* pDC) { // TODO: ڴϢ/Ĭֵ CRect rect; GetClientRect(&rect); if(m_pBmp != NULL) { BITMAP bm; CDC dcMem; ::GetObject(m_pBmp,sizeof(BITMAP), (LPVOID)&bm); dcMem.CreateCompatibleDC(NULL); HBITMAP pOldBitmap =(HBITMAP ) dcMem.SelectObject(m_pBmp); pDC-> StretchBlt(rect.left,rect.top-1,rect.Width(),rect.Height(), &dcMem, 0, 0,bm.bmWidth-1,bm.bmHeight-1, SRCCOPY); dcMem.SelectObject(pOldBitmap); dcMem.DeleteDC(); } else CWnd::OnEraseBkgnd(pDC); return 1; } int CProgStatusBar::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CDialogBar::OnCreate(lpCreateStruct) == -1) return -1; // TODO: ڴרõĴ SetBkBmpNid( IDB_BITMAP_BAR3 ) ; ModifyStyle(WS_BORDER, 0); ModifyStyleEx(WS_EX_WINDOWEDGE, 0); return 0; } void CProgStatusBar::OnSize(UINT nType, int cx, int cy) { CDialogBar::OnSize(nType, cx, cy); // TODO: ڴ˴Ϣ } BOOL CProgStatusBar::Create(CWnd* pParentWnd, UINT nIDTemplate, UINT nStyle, UINT nID) { // TODO: ڴרô/û BOOL bRes = CDialogBar::Create(pParentWnd, nIDTemplate, nStyle, nID); if ( bRes ) { UpdateData(0); m_strNeting.SetFont(90, _T("")); //ʾʹС m_strNeting.SetTextColor(RGB(255,255,255)); //ɫ // m_strNeting.SetWindowText(_T("ͬ...")); m_strNeting.SetWindowText(_T("ȡ")) ; m_strHeight.SetFont(90, _T("")); //ʾʹС m_strHeight.SetTextColor(RGB(255,255,255)); //ɫ m_strHeight.SetWindowText(_T("߶:")) ; m_strHeight.ShowWindow(SW_HIDE) ; m_strVersion.SetFont(90, _T("")); //ʾʹС m_strVersion.SetTextColor(RGB(255,255,255)); //ɫ m_strVersion.SetWindowText(_T("汾:V1.0.0.6beta")) ; if ( NULL == m_ProgressWnd ) { m_ProgressWnd = new CGIFControl ; m_ProgressWnd->Create(_T("") , WS_CHILD | SS_OWNERDRAW | WS_VISIBLE | SS_NOTIFY , \ CRect(20,20,36,36) , this, 111 ) ; } m_Sigbmp[0].LoadBitmap(IDB_BITMAP_SIG0); m_Sigbmp[1].LoadBitmap(IDB_BITMAP_SIG1); m_Sigbmp[2].LoadBitmap(IDB_BITMAP_SIG2); m_Sigbmp[3].LoadBitmap(IDB_BITMAP_SIG3); theApp.SubscribeMsg( theApp.GetMtHthrdId() , GetSafeHwnd() , MSG_USER_UP_PROGRESS ) ; m_progress.SendMessage(PBM_SETBKCOLOR, 0, RGB(66, 65, 63));//ɫ m_progress.SendMessage(PBM_SETBARCOLOR, 0, RGB(254, 153, 0));//ǰɫ LoadGifing(TRUE); //CPostMsg postmsg(MSG_USER_UP_PROGRESS,0); //theApp.m_MsgQueue.pushFront(postmsg); } return bRes ; } LRESULT CProgStatusBar::OnShowProgressCtrl( WPARAM wParam, LPARAM lParam ) { TRACE("OnShowProgressCtrl:%s\r\n","OnShowProgressCtrl"); CPostMsg postmsg; if (!theApp.m_UimsgQueue.pop(postmsg)) { return 1; } uistruct::BLOCKCHANGED_t pBlockchanged; string strTemp = postmsg.GetData(); pBlockchanged.JsonToStruct(strTemp.c_str()); if (pBlockchanged.tips <= 0) { return 1; } //// blocktip߶ theApp.blocktipheight = pBlockchanged.tips ; if (!m_bProgressType) { m_strNeting.SetWindowText(_T("ͬ...")); m_strNeting.ShowWindow(SW_HIDE); m_strNeting.ShowWindow(SW_SHOW); m_progress.SetRange32( 0 , 100); int setpos = (pBlockchanged.high*1.0/pBlockchanged.tips)*100; setpos = setpos>100?100:setpos; //ýֵ m_progress.SetPos(setpos); CString strText; strText.AppendFormat("ʣ ~%d ûͬ", pBlockchanged.tips-pBlockchanged.high); m_progress.SetDefinedStr(strText); m_bProgressType = TRUE; m_nSigIndex =pBlockchanged.connections>3?3:pBlockchanged.connections; if ((pBlockchanged.tips-pBlockchanged.high)<10 && !m_walletui) { TRACE("ok:%s\r\n","OnShowProgressCtrl"); //// Ǯͬ CPostMsg postblockmsg(MSG_USER_MAIN_UI,WM_UPWALLET); theApp.m_MsgQueue.pushFront(postblockmsg); LoadGifing(false); m_walletui = true; theApp.IsSyncBlock = true; } Invalidate(); //InvalidateRect(m_bmpsig); // return 1; } m_nSigIndex = pBlockchanged.connections>3?3:pBlockchanged.connections; int setpos = (pBlockchanged.high*1.0/pBlockchanged.tips)*100 ; setpos = setpos>100?100:setpos; //ýֵ m_progress.SetPos(setpos); CString strText; strText.AppendFormat("ʣ ~%d ûͬ", pBlockchanged.tips-pBlockchanged.high); m_progress.SetDefinedStr(strText); if ((pBlockchanged.tips-pBlockchanged.high)<10&& !m_walletui) { TRACE("ok:%s\r\n","OnShowProgressCtrl"); //// Ǯͬ CPostMsg postblockmsg(MSG_USER_MAIN_UI,WM_UPWALLET); theApp.m_MsgQueue.pushFront(postblockmsg); LoadGifing(false); m_walletui = true; theApp.IsSyncBlock = true; } if ( m_walletui && !m_prosshiden) { m_strNeting.SetWindowText(_T("ͬ")) ; m_strNeting.ShowWindow(SW_HIDE); m_strNeting.ShowWindow(SW_SHOW); m_progress.ShowWindow(SW_HIDE); if ( NULL != m_ProgressWnd ) { m_ProgressWnd->ShowWindow(SW_HIDE) ; } m_prosshiden = !m_prosshiden ; } if (m_walletui && m_prosshiden) { CString strTips; strTips.Format(_T("ǰ߶:%d") ,pBlockchanged.tips ) ; m_strHeight.SetWindowText(strTips) ; m_strHeight.ShowWindow(SW_HIDE); m_strHeight.ShowWindow(SW_SHOW); } InvalidateRect(m_bmpsig); return 1; } //Invalidate(); void CProgStatusBar::OnPaint() { CPaintDC dc(this); // device context for painting // TODO: ڴ˴Ϣ // ΪͼϢ CDialogBar::OnPaint() CDC memDC; memDC.CreateCompatibleDC(&dc); CRect rc; GetClientRect(&rc); HBITMAP hOldbmp = (HBITMAP)memDC.SelectObject(m_Sigbmp[m_nSigIndex]); dc.BitBlt(900-60, 0, rc.Width(), rc.Height(), &memDC, 0, 0, SRCCOPY); CRect rc1(900-60, 0, rc.Width(), rc.Height()); m_bmpsig = rc1; memDC.SelectObject(hOldbmp); memDC.DeleteDC(); } <|endoftext|>
<commit_before>/******************************************************************************\ * LuaUserData.hpp * * A C++ equivalent of a Lua userdata. * * Leandro Motta Barros * \******************************************************************************/ #ifndef _DILUCULUM_LUA_USER_DATA_HPP_ #define _DILUCULUM_LUA_USER_DATA_HPP_ #include <boost/scoped_array.hpp> #include <lua.hpp> #include <Diluculum/Types.hpp> namespace Diluculum { /** A C++ equivalent of a Lua userdata. Or, perhaps more precisely: something * that lives in the C++-space, and that stores data that would normally be * in the Lua-space as userdata. This is used as the value of a \c LuaValue * when it holds userdata. * @note A \c LuaUserData has no counterpart in a Lua state. It is simply a * block of memory that can be (via a \c LuaValue and a \c LuaState) * stored in or read from a userdata in Lua state. * @todo What about metatables? */ class LuaUserData { public: /** Constructs a \c LuaUserData, allocating \c size bytes of memory. * This memory is initially filled with garbage. And this memory is * automatically freed when the \c LuaUserData is destroyed. */ LuaUserData (size_t size); /** The copy constructor. The newly constructed \c LuaUserData will * have its own block of memory, with the same contents as the * \c other. In other words, this constructor allocates and copies * memory. */ LuaUserData (const LuaUserData& other); /** Assigns a \c LuaUserData to this one. The memory currently * allocated for \c this will be freed, new memory will be allocated, * and the data stored in \c rhs will be copied to \c this. */ const LuaUserData& operator= (const LuaUserData& rhs); /** Returns the size, in bytes, of the data stored in this * \c LuaUserData. */ size_t getSize() const { return size_; } /// Returns a pointer to the data stored in this \c LuaUserData. void* getData() { return data_.get(); } /** Returns a \c const pointer to the data stored in this * \c LuaUserData. */ const void* getData() const { return data_.get(); } /** The "greater than" operator for \c LuaUserData. * @note Given two <tt>LuaUserData</tt>s, the decision on which one is * greater is somewhat arbitrary. Here, the userdata with larger * \c size() is considered greater. If both are equal, the * decision is based on the contents of the stored data. * @todo This is currently implemented using \c memcmp(). I think that * this is not part of the C++ standard yet (just of C99). */ bool operator> (const LuaUserData& rhs) const; /** The "less than" operator for \c LuaUserData. * @note Given two <tt>LuaUserData</tt>s, the decision on which one is * lesser is somewhat arbitrary. The criterion is similar to the * described for the "greater than" operator. * @todo This is currently implemented using \c memcmp(). I think that * this is not part of the C++ standard yet (just of C99). */ bool operator< (const LuaUserData& rhs) const; /** The "equal to" operator for \c LuaUserData. * @note Two <tt>LuaUserData</tt>s are considered equal if the data * they store have the same size and the same contents. * @todo In Lua, a userdata is considered equal only to itself. Things * are different here. Does this have a reason to not be like in * Lua? */ bool operator== (const LuaUserData& rhs) const; /// The "different than" operator for \c LuaUserData. bool operator!= (const LuaUserData& rhs) const; private: /// The number of bytes stored "in" \c data_. size_t size_; /// A (smart) pointer to the data owned by this \c LuaUserData. boost::scoped_array<char> data_; }; } // namespace Diluculum #endif // _DILUCULUM_LUA_USER_DATA_HPP_ <commit_msg>Removed a TODO from 'LuaUserData', concerning the possibility of supporting metatables in some special way.<commit_after>/******************************************************************************\ * LuaUserData.hpp * * A C++ equivalent of a Lua userdata. * * Leandro Motta Barros * \******************************************************************************/ #ifndef _DILUCULUM_LUA_USER_DATA_HPP_ #define _DILUCULUM_LUA_USER_DATA_HPP_ #include <boost/scoped_array.hpp> #include <lua.hpp> #include <Diluculum/Types.hpp> namespace Diluculum { /** A C++ equivalent of a Lua userdata. Or, perhaps more precisely: something * that lives in the C++-space, and that stores data that would normally be * in the Lua-space as userdata. This is used as the value of a \c LuaValue * when it holds userdata. * @note A \c LuaUserData has no counterpart in a Lua state. It is simply a * block of memory that can be (via a \c LuaValue and a \c LuaState) * stored in or read from a userdata in Lua state. */ class LuaUserData { public: /** Constructs a \c LuaUserData, allocating \c size bytes of memory. * This memory is initially filled with garbage. And this memory is * automatically freed when the \c LuaUserData is destroyed. */ LuaUserData (size_t size); /** The copy constructor. The newly constructed \c LuaUserData will * have its own block of memory, with the same contents as the * \c other. In other words, this constructor allocates and copies * memory. */ LuaUserData (const LuaUserData& other); /** Assigns a \c LuaUserData to this one. The memory currently * allocated for \c this will be freed, new memory will be allocated, * and the data stored in \c rhs will be copied to \c this. */ const LuaUserData& operator= (const LuaUserData& rhs); /** Returns the size, in bytes, of the data stored in this * \c LuaUserData. */ size_t getSize() const { return size_; } /// Returns a pointer to the data stored in this \c LuaUserData. void* getData() { return data_.get(); } /** Returns a \c const pointer to the data stored in this * \c LuaUserData. */ const void* getData() const { return data_.get(); } /** The "greater than" operator for \c LuaUserData. * @note Given two <tt>LuaUserData</tt>s, the decision on which one is * greater is somewhat arbitrary. Here, the userdata with larger * \c size() is considered greater. If both are equal, the * decision is based on the contents of the stored data. * @todo This is currently implemented using \c memcmp(). I think that * this is not part of the C++ standard yet (just of C99). */ bool operator> (const LuaUserData& rhs) const; /** The "less than" operator for \c LuaUserData. * @note Given two <tt>LuaUserData</tt>s, the decision on which one is * lesser is somewhat arbitrary. The criterion is similar to the * described for the "greater than" operator. * @todo This is currently implemented using \c memcmp(). I think that * this is not part of the C++ standard yet (just of C99). */ bool operator< (const LuaUserData& rhs) const; /** The "equal to" operator for \c LuaUserData. * @note Two <tt>LuaUserData</tt>s are considered equal if the data * they store have the same size and the same contents. * @todo In Lua, a userdata is considered equal only to itself. Things * are different here. Does this have a reason to not be like in * Lua? */ bool operator== (const LuaUserData& rhs) const; /// The "different than" operator for \c LuaUserData. bool operator!= (const LuaUserData& rhs) const; private: /// The number of bytes stored "in" \c data_. size_t size_; /// A (smart) pointer to the data owned by this \c LuaUserData. boost::scoped_array<char> data_; }; } // namespace Diluculum #endif // _DILUCULUM_LUA_USER_DATA_HPP_ <|endoftext|>
<commit_before>#include <cerrno> #include <cstdio> #include <getopt.h> #include "cpu.hpp" int main(int argc, char *argv[]) { const char *const Help = "SOS is boring VM - simple virtual machine\n" "Syntax: vm [arguments] [input file]\n" "Arguments:\n" " -h, --help print this help text\n" " -s SIZE, --size SIZE set memory size in 32-bit words\n" " -u, --usage short usage information\n" " -v, --version display program version"; const struct option LongOptions[] = { {"help", 0, NULL, 'h'}, {"usage", 0, NULL, 'u'}, {"version", 0, NULL, 'v'}, {NULL, 0, NULL, 0} }; u32 mem_size = 16 * 1024; char *input_file = NULL; for (int option, long_option_index; (option = getopt_long(argc, argv, "hs:uv", LongOptions, &long_option_index)) != -1;) switch (option) { case 'h': puts(Help); return 0; case 's': if (sscanf(optarg, "%u", &mem_size) != 1) { fprintf(stderr, "Invalid memory size parameter \"%s\".\n", optarg); return EINVAL; } break; case 'u': puts("Syntax: vm [-s SIZE|--size SIZE] [INPUT_FILE]\n" " [-h|--help] [-u|--usage] [-v|--version]"); return 0; case 'v': puts("vm compiled on " __DATE__ " at " __TIME__ "\n" "Copyright (C) 2016 Deseteral <deseteral@gmail.com>"); return 0; default: return EINVAL; } if (optind == argc - 1) // 1 unknown parameter (input file name) input_file = argv[optind]; else if (optind != argc) // more unknown parameters { fputs("Invalid argument(s) found.\n", stderr); return EINVAL; } FILE *input = (input_file == NULL ? stdin : fopen(input_file, "rb")); if (input == NULL) { fprintf(stderr, "Cannot open file \"%s\" for reading.\n", input_file); return ENOENT; } CPU cpu; if (!cpu.Initialize(mem_size)) { fputs("Cannot allocate memory.\n", stderr); return ENOMEM; } if (!cpu.Load(input)) { fputs("Memory size is to small to store the program.\n", stderr); return 1; } if (input_file) fclose(input); ProgramState state; while ((state = cpu.Tick()) == OK) continue; switch (state) { case HALTED: fputs("Program exited normally.\n", stderr); break; case ERR_ADDRESS_BOUNDARY: fputs("Address boundary error.\n", stderr); return 1; case ERR_INVALID_OPCODE: fputs("Invalid operation error.\n", stderr); return 1; case ERR_ZERO_DIVISION: fputs("Zero division error.\n", stderr); return 1; case ERR_STACK_EMPTY: fputs("POP operation on empty stack.\n", stderr); return 1; case ERR_STACK_OVERFLOW: fputs("PUSH operation on full stack.\n", stderr); return 1; } return 0; } <commit_msg>Typo fixed<commit_after>#include <cerrno> #include <cstdio> #include <getopt.h> #include "cpu.hpp" int main(int argc, char *argv[]) { const char *const Help = "SOS is boring VM - simple virtual machine\n" "Syntax: vm [arguments] [input file]\n" "Arguments:\n" " -h, --help print this help text\n" " -s SIZE, --size SIZE set memory size in 32-bit words\n" " -u, --usage short usage information\n" " -v, --version display program version"; const struct option LongOptions[] = { {"help", 0, NULL, 'h'}, {"usage", 0, NULL, 'u'}, {"version", 0, NULL, 'v'}, {NULL, 0, NULL, 0} }; u32 mem_size = 16 * 1024; char *input_file = NULL; for (int option, long_option_index; (option = getopt_long(argc, argv, "hs:uv", LongOptions, &long_option_index)) != -1;) switch (option) { case 'h': puts(Help); return 0; case 's': if (sscanf(optarg, "%u", &mem_size) != 1) { fprintf(stderr, "Invalid memory size parameter \"%s\".\n", optarg); return EINVAL; } break; case 'u': puts("Syntax: vm [-s SIZE|--size SIZE] [INPUT_FILE]\n" " [-h|--help] [-u|--usage] [-v|--version]"); return 0; case 'v': puts("vm compiled on " __DATE__ " at " __TIME__ "\n" "Copyright (C) 2016 Deseteral <deseteral@gmail.com>"); return 0; default: return EINVAL; } if (optind == argc - 1) // 1 unknown parameter (input file name) input_file = argv[optind]; else if (optind != argc) // more unknown parameters { fputs("Invalid argument(s) found.\n", stderr); return EINVAL; } FILE *input = (input_file == NULL ? stdin : fopen(input_file, "rb")); if (input == NULL) { fprintf(stderr, "Cannot open file \"%s\" for reading.\n", input_file); return ENOENT; } CPU cpu; if (!cpu.Initialize(mem_size)) { fputs("Cannot allocate memory.\n", stderr); return ENOMEM; } if (!cpu.Load(input)) { fputs("Memory size is too small to store the program.\n", stderr); return 1; } if (input_file) fclose(input); ProgramState state; while ((state = cpu.Tick()) == OK) continue; switch (state) { case HALTED: fputs("Program exited normally.\n", stderr); break; case ERR_ADDRESS_BOUNDARY: fputs("Address boundary error.\n", stderr); return 1; case ERR_INVALID_OPCODE: fputs("Invalid operation error.\n", stderr); return 1; case ERR_ZERO_DIVISION: fputs("Zero division error.\n", stderr); return 1; case ERR_STACK_EMPTY: fputs("POP operation on empty stack.\n", stderr); return 1; case ERR_STACK_OVERFLOW: fputs("PUSH operation on full stack.\n", stderr); return 1; } return 0; } <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014-2016 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #pragma once #include "base_conf.hpp" //The configuration helpers #include "rbm_base.hpp" //The base class #include "layer_traits.hpp" //layer_traits #include "util/checks.hpp" //nan_check #include "util/timers.hpp" //auto_timer namespace dll { /*! * \brief Standard version of Convolutional Restricted Boltzmann Machine * * This follows the definition of a CRBM by Honglak Lee. This is an "abstract" class, * using CRTP to inject features into its children. */ template <typename Parent, typename Desc> struct standard_conv_rbm : public rbm_base<Parent, Desc> { using desc = Desc; using parent_t = Parent; using this_type = standard_conv_rbm<parent_t, desc>; using base_type = rbm_base<parent_t, Desc>; using weight = typename desc::weight; using input_one_t = typename rbm_base_traits<parent_t>::input_one_t; using output_one_t = typename rbm_base_traits<parent_t>::output_one_t; using input_t = typename rbm_base_traits<parent_t>::input_t; using output_t = typename rbm_base_traits<parent_t>::output_t; static constexpr const unit_type visible_unit = desc::visible_unit; static constexpr const unit_type hidden_unit = desc::hidden_unit; static_assert(visible_unit == unit_type::BINARY || visible_unit == unit_type::GAUSSIAN, "Only binary and linear visible units are supported"); static_assert(hidden_unit == unit_type::BINARY || is_relu(hidden_unit), "Only binary hidden units are supported"); double std_gaussian = 0.2; double c_sigm = 1.0; //Constructors standard_conv_rbm() { //Note: Convolutional RBM needs lower learning rate than standard RBM //Better initialization of learning rate base_type::learning_rate = visible_unit == unit_type::GAUSSIAN ? 1e-5 : is_relu(hidden_unit) ? 1e-4 : /* Only Gaussian Units needs lower rate */ 1e-3; } parent_t& as_derived() { return *static_cast<parent_t*>(this); } const parent_t& as_derived() const { return *static_cast<const parent_t*>(this); } //Utility functions template <typename Sample> void reconstruct(const Sample& items) { reconstruct(items, as_derived()); } void display_visible_unit_activations() const { display_visible_unit_activations(as_derived()); } void display_visible_unit_samples() const { display_visible_unit_samples(as_derived()); } void display_hidden_unit_activations() const { display_hidden_unit_samples(as_derived()); } void display_hidden_unit_samples() const { display_hidden_unit_samples(as_derived()); } //Various functions double reconstruction_error(const input_one_t& item) { return reconstruction_error(item, as_derived()); } template<typename Input> double reconstruction_error(const Input& item) { decltype(auto) converted_item = converter_one<Input, input_one_t>::convert(as_derived(), item); return reconstruction_error(converted_item, as_derived()); } protected: template <typename L, typename V1, typename VCV, typename W> static void compute_vcv(L& rbm, const V1& v_a, VCV&& v_cv, W&& w) { dll::auto_timer timer("crbm:compute_vcv"); const auto NC = get_nc(rbm); auto w_f = etl::force_temporary(w); w_f.deep_fflip_inplace(); v_cv(1) = 0; for (std::size_t channel = 0; channel < NC; ++channel) { etl::conv_2d_valid_multi(v_a(channel), w_f(channel), v_cv(0)); v_cv(1) += v_cv(0); } nan_check_deep(v_cv); } template <typename L, typename H2, typename HCV, typename W, typename Functor> static void compute_hcv(L& rbm, const H2& h_s, HCV&& h_cv, W&& w, Functor activate) { dll::auto_timer timer("crbm:compute_hcv"); const auto K = get_k(rbm); const auto NC = get_nc(rbm); for (std::size_t channel = 0; channel < NC; ++channel) { h_cv(1) = 0.0; for (std::size_t k = 0; k < K; ++k) { h_cv(0) = etl::conv_2d_full(h_s(k), w(channel)(k)); h_cv(1) += h_cv(0); } activate(channel); } } #ifdef ETL_MKL_MODE template <typename F1, typename F2> static void deep_pad(const F1& in, F2& out) { for (std::size_t outer1 = 0; outer1 < in.template dim<0>(); ++outer1) { for (std::size_t outer2 = 0; outer2 < in.template dim<1>(); ++outer2) { auto* out_m = out(outer1)(outer2).memory_start(); auto* in_m = in(outer1)(outer2).memory_start(); for (std::size_t i = 0; i < in.template dim<2>(); ++i) { for (std::size_t j = 0; j < in.template dim<3>(); ++j) { out_m[i * out.template dim<3>() + j] = in_m[i * in.template dim<3>() + j]; } } } } } template <typename L, typename TP, typename H2, typename HCV, typename W, typename Functor> static void batch_compute_hcv(L& rbm, TP& pool, const H2& h_s, HCV&& h_cv, W&& w, Functor activate) { dll::auto_timer timer("crbm:batch_compute_hcv:mkl"); const auto Batch = get_batch_size(rbm); const auto K = get_k(rbm); const auto NC = get_nc(rbm); const auto NV1 = get_nv1(rbm); const auto NV2 = get_nv2(rbm); etl::dyn_matrix<std::complex<weight>, 4> h_s_padded(Batch, K, NV1, NV2); etl::dyn_matrix<std::complex<weight>, 4> w_padded(NC, K, NV1, NV2); etl::dyn_matrix<std::complex<weight>, 4> tmp_result(Batch, K, NV1, NV2); deep_pad(h_s, h_s_padded); deep_pad(w, w_padded); PARALLEL_SECTION { h_s_padded.fft2_many_inplace(); w_padded.fft2_many_inplace(); } maybe_parallel_foreach_n(pool, 0, Batch, [&](std::size_t batch) { for (std::size_t channel = 0; channel < NC; ++channel) { h_cv(batch)(1) = 0.0; tmp_result(batch) = h_s_padded(batch) >> w_padded(channel); tmp_result(batch).ifft2_many_inplace(); for (std::size_t k = 0; k < K; ++k) { h_cv(batch)(1) += etl::real(tmp_result(batch)(k)); } activate(batch, channel); } }); } #else template <typename L, typename TP, typename H2, typename HCV, typename W, typename Functor> static void batch_compute_hcv(L& rbm, TP& pool, const H2& h_s, HCV&& h_cv, W&& w, Functor activate) { dll::auto_timer timer("crbm:batch_compute_hcv:std"); const auto Batch = get_batch_size(rbm); const auto K = get_k(rbm); const auto NC = get_nc(rbm); maybe_parallel_foreach_n(pool, 0, Batch, [&](std::size_t batch) { for (std::size_t channel = 0; channel < NC; ++channel) { h_cv(batch)(1) = 0.0; for (std::size_t k = 0; k < K; ++k) { h_cv(batch)(0) = etl::conv_2d_full(h_s(batch)(k), w(channel)(k)); h_cv(batch)(1) += h_cv(batch)(0); } activate(batch, channel); } }); } #endif template <typename L, typename TP, typename V1, typename VCV, typename W, typename Functor> static void batch_compute_vcv(L& rbm, TP& pool, const V1& v_a, VCV&& v_cv, W&& w, Functor activate) { dll::auto_timer timer("crbm:batch_compute_vcv"); const auto Batch = get_batch_size(rbm); const auto NC = get_nc(rbm); maybe_parallel_foreach_n(pool, 0, Batch, [&](std::size_t batch) { etl::conv_2d_valid_multi_flipped(v_a(batch)(0), w(0), v_cv(batch)(1)); for (std::size_t channel = 1; channel < NC; ++channel) { etl::conv_2d_valid_multi_flipped(v_a(batch)(channel), w(channel), v_cv(batch)(0)); v_cv(batch)(1) += v_cv(batch)(0); } activate(batch); }); } private: //Since the sub classes do not have the same fields, it is not possible //to put the fields in standard_rbm, therefore, it is necessary to use template //functions to implement the details template <typename Sample> static void reconstruct(const Sample& items, parent_t& rbm) { cpp_assert(items.size() == parent_t::input_size(), "The size of the training sample must match visible units"); cpp::stop_watch<> watch; //Set the state of the visible units rbm.v1 = items; rbm.activate_hidden(rbm.h1_a, rbm.h1_s, rbm.v1, rbm.v1); rbm.activate_visible(rbm.h1_a, rbm.h1_s, rbm.v2_a, rbm.v2_s); rbm.activate_hidden(rbm.h2_a, rbm.h2_s, rbm.v2_a, rbm.v2_s); std::cout << "Reconstruction took " << watch.elapsed() << "ms" << std::endl; } static void display_visible_unit_activations(const parent_t& rbm) { for (std::size_t channel = 0; channel < parent_t::NC; ++channel) { std::cout << "Channel " << channel << std::endl; for (size_t i = 0; i < get_nv1(rbm); ++i) { for (size_t j = 0; j < get_nv2(rbm); ++j) { std::cout << rbm.v2_a(channel, i, j) << " "; } std::cout << std::endl; } } } static void display_visible_unit_samples(const parent_t& rbm) { for (std::size_t channel = 0; channel < parent_t::NC; ++channel) { std::cout << "Channel " << channel << std::endl; for (size_t i = 0; i < get_nv1(rbm); ++i) { for (size_t j = 0; j < get_nv2(rbm); ++j) { std::cout << rbm.v2_s(channel, i, j) << " "; } std::cout << std::endl; } } } static void display_hidden_unit_activations(const parent_t& rbm) { for (size_t k = 0; k < get_k(rbm); ++k) { for (size_t i = 0; i < get_nv1(rbm); ++i) { for (size_t j = 0; j < get_nv2(rbm); ++j) { std::cout << rbm.h2_a(k)(i, j) << " "; } std::cout << std::endl; } std::cout << std::endl << std::endl; } } static void display_hidden_unit_samples(const parent_t& rbm) { for (size_t k = 0; k < get_k(rbm); ++k) { for (size_t i = 0; i < get_nv1(rbm); ++i) { for (size_t j = 0; j < get_nv2(rbm); ++j) { std::cout << rbm.h2_s(k)(i, j) << " "; } std::cout << std::endl; } std::cout << std::endl << std::endl; } } static double reconstruction_error(const input_one_t& items, parent_t& rbm) { cpp_assert(items.size() == input_size(rbm), "The size of the training sample must match visible units"); //Set the state of the visible units rbm.v1 = items; rbm.activate_hidden(rbm.h1_a, rbm.h1_s, rbm.v1, rbm.v1); rbm.activate_visible(rbm.h1_a, rbm.h1_s, rbm.v2_a, rbm.v2_s); return etl::mean((rbm.v1 - rbm.v2_a) >> (rbm.v1 - rbm.v2_a)); } }; } //end of dll namespace <commit_msg>Fix horrendous bug<commit_after>//======================================================================= // Copyright (c) 2014-2016 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #pragma once #include "base_conf.hpp" //The configuration helpers #include "rbm_base.hpp" //The base class #include "layer_traits.hpp" //layer_traits #include "util/checks.hpp" //nan_check #include "util/timers.hpp" //auto_timer namespace dll { /*! * \brief Standard version of Convolutional Restricted Boltzmann Machine * * This follows the definition of a CRBM by Honglak Lee. This is an "abstract" class, * using CRTP to inject features into its children. */ template <typename Parent, typename Desc> struct standard_conv_rbm : public rbm_base<Parent, Desc> { using desc = Desc; using parent_t = Parent; using this_type = standard_conv_rbm<parent_t, desc>; using base_type = rbm_base<parent_t, Desc>; using weight = typename desc::weight; using input_one_t = typename rbm_base_traits<parent_t>::input_one_t; using output_one_t = typename rbm_base_traits<parent_t>::output_one_t; using input_t = typename rbm_base_traits<parent_t>::input_t; using output_t = typename rbm_base_traits<parent_t>::output_t; static constexpr const unit_type visible_unit = desc::visible_unit; static constexpr const unit_type hidden_unit = desc::hidden_unit; static_assert(visible_unit == unit_type::BINARY || visible_unit == unit_type::GAUSSIAN, "Only binary and linear visible units are supported"); static_assert(hidden_unit == unit_type::BINARY || is_relu(hidden_unit), "Only binary hidden units are supported"); double std_gaussian = 0.2; double c_sigm = 1.0; //Constructors standard_conv_rbm() { //Note: Convolutional RBM needs lower learning rate than standard RBM //Better initialization of learning rate base_type::learning_rate = visible_unit == unit_type::GAUSSIAN ? 1e-5 : is_relu(hidden_unit) ? 1e-4 : /* Only Gaussian Units needs lower rate */ 1e-3; } parent_t& as_derived() { return *static_cast<parent_t*>(this); } const parent_t& as_derived() const { return *static_cast<const parent_t*>(this); } //Utility functions template <typename Sample> void reconstruct(const Sample& items) { reconstruct(items, as_derived()); } void display_visible_unit_activations() const { display_visible_unit_activations(as_derived()); } void display_visible_unit_samples() const { display_visible_unit_samples(as_derived()); } void display_hidden_unit_activations() const { display_hidden_unit_samples(as_derived()); } void display_hidden_unit_samples() const { display_hidden_unit_samples(as_derived()); } //Various functions double reconstruction_error(const input_one_t& item) { return reconstruction_error(item, as_derived()); } template<typename Input> double reconstruction_error(const Input& item) { decltype(auto) converted_item = converter_one<Input, input_one_t>::convert(as_derived(), item); return reconstruction_error(converted_item, as_derived()); } protected: template <typename L, typename V1, typename VCV, typename W> static void compute_vcv(L& rbm, const V1& v_a, VCV&& v_cv, W&& w) { dll::auto_timer timer("crbm:compute_vcv"); const auto NC = get_nc(rbm); auto w_f = etl::force_temporary(w); w_f.deep_fflip_inplace(); v_cv(1) = 0; for (std::size_t channel = 0; channel < NC; ++channel) { etl::conv_2d_valid_multi(v_a(channel), w_f(channel), v_cv(0)); v_cv(1) += v_cv(0); } nan_check_deep(v_cv); } template <typename L, typename H2, typename HCV, typename W, typename Functor> static void compute_hcv(L& rbm, const H2& h_s, HCV&& h_cv, W&& w, Functor activate) { dll::auto_timer timer("crbm:compute_hcv"); const auto K = get_k(rbm); const auto NC = get_nc(rbm); for (std::size_t channel = 0; channel < NC; ++channel) { h_cv(1) = 0.0; for (std::size_t k = 0; k < K; ++k) { h_cv(0) = etl::conv_2d_full(h_s(k), w(channel)(k)); h_cv(1) += h_cv(0); } activate(channel); } } #ifdef ETL_MKL_MODE template <typename F1, typename F2> static void deep_pad(const F1& in, F2& out) { for (std::size_t outer1 = 0; outer1 < in.template dim<0>(); ++outer1) { for (std::size_t outer2 = 0; outer2 < in.template dim<1>(); ++outer2) { auto* out_m = out(outer1)(outer2).memory_start(); auto* in_m = in(outer1)(outer2).memory_start(); for (std::size_t i = 0; i < in.template dim<2>(); ++i) { for (std::size_t j = 0; j < in.template dim<3>(); ++j) { out_m[i * out.template dim<3>() + j] = in_m[i * in.template dim<3>() + j]; } } } } } template <typename L, typename TP, typename H2, typename HCV, typename W, typename Functor> static void batch_compute_hcv(L& rbm, TP& pool, const H2& h_s, HCV&& h_cv, W&& w, Functor activate) { dll::auto_timer timer("crbm:batch_compute_hcv:mkl"); const auto Batch = etl::dim<0>(h_cv); const auto K = get_k(rbm); const auto NC = get_nc(rbm); const auto NV1 = get_nv1(rbm); const auto NV2 = get_nv2(rbm); etl::dyn_matrix<std::complex<weight>, 4> h_s_padded(Batch, K, NV1, NV2); etl::dyn_matrix<std::complex<weight>, 4> w_padded(NC, K, NV1, NV2); etl::dyn_matrix<std::complex<weight>, 4> tmp_result(Batch, K, NV1, NV2); deep_pad(h_s, h_s_padded); deep_pad(w, w_padded); PARALLEL_SECTION { h_s_padded.fft2_many_inplace(); w_padded.fft2_many_inplace(); } maybe_parallel_foreach_n(pool, 0, Batch, [&](std::size_t batch) { for (std::size_t channel = 0; channel < NC; ++channel) { h_cv(batch)(1) = 0.0; tmp_result(batch) = h_s_padded(batch) >> w_padded(channel); tmp_result(batch).ifft2_many_inplace(); for (std::size_t k = 0; k < K; ++k) { h_cv(batch)(1) += etl::real(tmp_result(batch)(k)); } activate(batch, channel); } }); } #else template <typename L, typename TP, typename H2, typename HCV, typename W, typename Functor> static void batch_compute_hcv(L& rbm, TP& pool, const H2& h_s, HCV&& h_cv, W&& w, Functor activate) { dll::auto_timer timer("crbm:batch_compute_hcv:std"); const auto Batch = etl::dim<0>(h_cv); const auto K = get_k(rbm); const auto NC = get_nc(rbm); maybe_parallel_foreach_n(pool, 0, Batch, [&](std::size_t batch) { for (std::size_t channel = 0; channel < NC; ++channel) { h_cv(batch)(1) = 0.0; for (std::size_t k = 0; k < K; ++k) { h_cv(batch)(0) = etl::conv_2d_full(h_s(batch)(k), w(channel)(k)); h_cv(batch)(1) += h_cv(batch)(0); } activate(batch, channel); } }); } #endif template <typename L, typename TP, typename V1, typename VCV, typename W, typename Functor> static void batch_compute_vcv(L& rbm, TP& pool, const V1& v_a, VCV&& v_cv, W&& w, Functor activate) { dll::auto_timer timer("crbm:batch_compute_vcv"); const auto Batch = etl::dim<0>(v_cv); const auto NC = get_nc(rbm); maybe_parallel_foreach_n(pool, 0, Batch, [&](std::size_t batch) { etl::conv_2d_valid_multi_flipped(v_a(batch)(0), w(0), v_cv(batch)(1)); for (std::size_t channel = 1; channel < NC; ++channel) { etl::conv_2d_valid_multi_flipped(v_a(batch)(channel), w(channel), v_cv(batch)(0)); v_cv(batch)(1) += v_cv(batch)(0); } activate(batch); }); } private: //Since the sub classes do not have the same fields, it is not possible //to put the fields in standard_rbm, therefore, it is necessary to use template //functions to implement the details template <typename Sample> static void reconstruct(const Sample& items, parent_t& rbm) { cpp_assert(items.size() == parent_t::input_size(), "The size of the training sample must match visible units"); cpp::stop_watch<> watch; //Set the state of the visible units rbm.v1 = items; rbm.activate_hidden(rbm.h1_a, rbm.h1_s, rbm.v1, rbm.v1); rbm.activate_visible(rbm.h1_a, rbm.h1_s, rbm.v2_a, rbm.v2_s); rbm.activate_hidden(rbm.h2_a, rbm.h2_s, rbm.v2_a, rbm.v2_s); std::cout << "Reconstruction took " << watch.elapsed() << "ms" << std::endl; } static void display_visible_unit_activations(const parent_t& rbm) { for (std::size_t channel = 0; channel < parent_t::NC; ++channel) { std::cout << "Channel " << channel << std::endl; for (size_t i = 0; i < get_nv1(rbm); ++i) { for (size_t j = 0; j < get_nv2(rbm); ++j) { std::cout << rbm.v2_a(channel, i, j) << " "; } std::cout << std::endl; } } } static void display_visible_unit_samples(const parent_t& rbm) { for (std::size_t channel = 0; channel < parent_t::NC; ++channel) { std::cout << "Channel " << channel << std::endl; for (size_t i = 0; i < get_nv1(rbm); ++i) { for (size_t j = 0; j < get_nv2(rbm); ++j) { std::cout << rbm.v2_s(channel, i, j) << " "; } std::cout << std::endl; } } } static void display_hidden_unit_activations(const parent_t& rbm) { for (size_t k = 0; k < get_k(rbm); ++k) { for (size_t i = 0; i < get_nv1(rbm); ++i) { for (size_t j = 0; j < get_nv2(rbm); ++j) { std::cout << rbm.h2_a(k)(i, j) << " "; } std::cout << std::endl; } std::cout << std::endl << std::endl; } } static void display_hidden_unit_samples(const parent_t& rbm) { for (size_t k = 0; k < get_k(rbm); ++k) { for (size_t i = 0; i < get_nv1(rbm); ++i) { for (size_t j = 0; j < get_nv2(rbm); ++j) { std::cout << rbm.h2_s(k)(i, j) << " "; } std::cout << std::endl; } std::cout << std::endl << std::endl; } } static double reconstruction_error(const input_one_t& items, parent_t& rbm) { cpp_assert(items.size() == input_size(rbm), "The size of the training sample must match visible units"); //Set the state of the visible units rbm.v1 = items; rbm.activate_hidden(rbm.h1_a, rbm.h1_s, rbm.v1, rbm.v1); rbm.activate_visible(rbm.h1_a, rbm.h1_s, rbm.v2_a, rbm.v2_s); return etl::mean((rbm.v1 - rbm.v2_a) >> (rbm.v1 - rbm.v2_a)); } }; } //end of dll namespace <|endoftext|>
<commit_before>/* Copyright (c) 2006, Arvid Norberg 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 author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/shared_ptr.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include <vector> #include "libtorrent/extensions/logger.hpp" #include "libtorrent/extensions.hpp" #include "libtorrent/entry.hpp" #include "libtorrent/peer_request.hpp" #if TORRENT_USE_IOSTREAM && !defined TORRENT_DISABLE_EXTENSIONS #include <fstream> #include "libtorrent/file.hpp" #include "libtorrent/time.hpp" #include "libtorrent/lazy_entry.hpp" #include "libtorrent/peer_connection.hpp" namespace libtorrent { class peer_connection; namespace { struct logger_peer_plugin : peer_plugin { logger_peer_plugin(std::string const& filename) { error_code ec; std::string dir = complete("libtorrent_ext_logs"); if (!exists(dir)) create_directories(dir, ec); m_file.open(combine_path(dir, filename).c_str() , std::ios_base::out | std::ios_base::out); m_file << "\n\n\n"; log_timestamp(); m_file << "*** starting log ***\n"; } void log_timestamp() { m_file << time_now_string() << ": "; } // can add entries to the extension handshake virtual void add_handshake(entry&) {} // called when the extension handshake from the other end is received virtual bool on_extension_handshake(lazy_entry const& h) { log_timestamp(); m_file << "<== EXTENSION_HANDSHAKE\n" << h; return true; } // returning true from any of the message handlers // indicates that the plugin has handeled the message. // it will break the plugin chain traversing and not let // anyone else handle the message, including the default // handler. virtual bool on_choke() { log_timestamp(); m_file << "<== CHOKE\n"; m_file.flush(); return false; } virtual bool on_unchoke() { log_timestamp(); m_file << "<== UNCHOKE\n"; m_file.flush(); return false; } virtual bool on_interested() { log_timestamp(); m_file << "<== INTERESTED\n"; m_file.flush(); return false; } virtual bool on_not_interested() { log_timestamp(); m_file << "<== NOT_INTERESTED\n"; m_file.flush(); return false; } virtual bool on_have(int index) { log_timestamp(); m_file << "<== HAVE [" << index << "]\n"; m_file.flush(); return false; } virtual bool on_bitfield(bitfield const& bitfield_) { log_timestamp(); m_file << "<== BITFIELD\n"; m_file.flush(); return false; } virtual bool on_request(peer_request const& r) { log_timestamp(); m_file << "<== REQUEST [ piece: " << r.piece << " | s: " << r.start << " | l: " << r.length << " ]\n"; m_file.flush(); return false; } virtual bool on_piece(peer_request const& r, disk_buffer_holder& data) { log_timestamp(); m_file << "<== PIECE [ piece: " << r.piece << " | s: " << r.start << " | l: " << r.length << " ]\n"; m_file.flush(); return false; } virtual bool on_cancel(peer_request const& r) { log_timestamp(); m_file << "<== CANCEL [ piece: " << r.piece << " | s: " << r.start << " | l: " << r.length << " ]\n"; m_file.flush(); return false; } // called when an extended message is received. If returning true, // the message is not processed by any other plugin and if false // is returned the next plugin in the chain will receive it to // be able to handle it virtual bool on_extended(int length , int msg, buffer::const_interval body) { return false; } virtual bool on_unknown_message(int length, int msg , buffer::const_interval body) { if (body.left() < length) return false; log_timestamp(); m_file << "<== UNKNOWN [ msg: " << msg << " | l: " << length << " ]\n"; m_file.flush(); return false; } virtual void on_piece_pass(int index) { log_timestamp(); m_file << "*** HASH PASSED *** [ piece: " << index << " ]\n"; m_file.flush(); } virtual void on_piece_failed(int index) { log_timestamp(); m_file << "*** HASH FAILED *** [ piece: " << index << " ]\n"; m_file.flush(); } private: std::ofstream m_file; }; struct logger_plugin : torrent_plugin { virtual boost::shared_ptr<peer_plugin> new_connection( peer_connection* pc) { error_code ec; return boost::shared_ptr<peer_plugin>(new logger_peer_plugin( pc->remote().address().to_string(ec) + "_" + to_string(pc->remote().port()).elems + ".log")); } }; } } namespace libtorrent { boost::shared_ptr<torrent_plugin> create_logger_plugin(torrent*) { return boost::shared_ptr<torrent_plugin>(new logger_plugin()); } } #endif <commit_msg>fixed typo<commit_after>/* Copyright (c) 2006, Arvid Norberg 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 author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/shared_ptr.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include <vector> #include "libtorrent/extensions/logger.hpp" #include "libtorrent/extensions.hpp" #include "libtorrent/entry.hpp" #include "libtorrent/peer_request.hpp" #if TORRENT_USE_IOSTREAM && !defined TORRENT_DISABLE_EXTENSIONS #include <fstream> #include "libtorrent/file.hpp" #include "libtorrent/time.hpp" #include "libtorrent/lazy_entry.hpp" #include "libtorrent/peer_connection.hpp" namespace libtorrent { class peer_connection; namespace { struct logger_peer_plugin : peer_plugin { logger_peer_plugin(std::string const& filename) { error_code ec; std::string dir = complete("libtorrent_ext_logs"); if (!exists(dir)) create_directories(dir, ec); m_file.open(combine_path(dir, filename).c_str(), std::ios_base::out); m_file << "\n\n\n"; log_timestamp(); m_file << "*** starting log ***\n"; } void log_timestamp() { m_file << time_now_string() << ": "; } // can add entries to the extension handshake virtual void add_handshake(entry&) {} // called when the extension handshake from the other end is received virtual bool on_extension_handshake(lazy_entry const& h) { log_timestamp(); m_file << "<== EXTENSION_HANDSHAKE\n" << h; return true; } // returning true from any of the message handlers // indicates that the plugin has handeled the message. // it will break the plugin chain traversing and not let // anyone else handle the message, including the default // handler. virtual bool on_choke() { log_timestamp(); m_file << "<== CHOKE\n"; m_file.flush(); return false; } virtual bool on_unchoke() { log_timestamp(); m_file << "<== UNCHOKE\n"; m_file.flush(); return false; } virtual bool on_interested() { log_timestamp(); m_file << "<== INTERESTED\n"; m_file.flush(); return false; } virtual bool on_not_interested() { log_timestamp(); m_file << "<== NOT_INTERESTED\n"; m_file.flush(); return false; } virtual bool on_have(int index) { log_timestamp(); m_file << "<== HAVE [" << index << "]\n"; m_file.flush(); return false; } virtual bool on_bitfield(bitfield const& bitfield_) { log_timestamp(); m_file << "<== BITFIELD\n"; m_file.flush(); return false; } virtual bool on_request(peer_request const& r) { log_timestamp(); m_file << "<== REQUEST [ piece: " << r.piece << " | s: " << r.start << " | l: " << r.length << " ]\n"; m_file.flush(); return false; } virtual bool on_piece(peer_request const& r, disk_buffer_holder& data) { log_timestamp(); m_file << "<== PIECE [ piece: " << r.piece << " | s: " << r.start << " | l: " << r.length << " ]\n"; m_file.flush(); return false; } virtual bool on_cancel(peer_request const& r) { log_timestamp(); m_file << "<== CANCEL [ piece: " << r.piece << " | s: " << r.start << " | l: " << r.length << " ]\n"; m_file.flush(); return false; } // called when an extended message is received. If returning true, // the message is not processed by any other plugin and if false // is returned the next plugin in the chain will receive it to // be able to handle it virtual bool on_extended(int length , int msg, buffer::const_interval body) { return false; } virtual bool on_unknown_message(int length, int msg , buffer::const_interval body) { if (body.left() < length) return false; log_timestamp(); m_file << "<== UNKNOWN [ msg: " << msg << " | l: " << length << " ]\n"; m_file.flush(); return false; } virtual void on_piece_pass(int index) { log_timestamp(); m_file << "*** HASH PASSED *** [ piece: " << index << " ]\n"; m_file.flush(); } virtual void on_piece_failed(int index) { log_timestamp(); m_file << "*** HASH FAILED *** [ piece: " << index << " ]\n"; m_file.flush(); } private: std::ofstream m_file; }; struct logger_plugin : torrent_plugin { virtual boost::shared_ptr<peer_plugin> new_connection( peer_connection* pc) { error_code ec; return boost::shared_ptr<peer_plugin>(new logger_peer_plugin( pc->remote().address().to_string(ec) + "_" + to_string(pc->remote().port()).elems + ".log")); } }; } } namespace libtorrent { boost::shared_ptr<torrent_plugin> create_logger_plugin(torrent*) { return boost::shared_ptr<torrent_plugin>(new logger_plugin()); } } #endif <|endoftext|>
<commit_before>/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief IronBee++ &mdash; Memory Pool * * This file defines MemoryPool, a wrapper for ib_mpool_t. * * @author Christopher Alfeld <calfeld@qualys.com> */ #ifndef __IBPP__MEMORY_POOL__ #define __IBPP__MEMORY_POOL__ #include <ironbeepp/common_semantics.hpp> #include <boost/function.hpp> #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdelete-non-virtual-dtor" #endif #include <boost/utility.hpp> #ifdef __clang__ #pragma clang diagnostic pop #endif #include <ostream> // IronBee C typedef struct ib_mpool_t ib_mpool_t; namespace IronBee { /** * Const Memory Pool; equivalent to a const pointer to ib_mpool_t. * * Provides operators ==, !=, <, >, <=, >= and evaluation as a boolean for * singularity via CommonSemantics. * * See MemoryPool for discussion of memory pools. * * @sa MemoryPool * @sa ironbeepp * @sa ib_bytestr_t * @nosubgrouping **/ class ConstMemoryPool : public CommonSemantics<ConstMemoryPool> { public: //! C Type. typedef const ib_mpool_t* ib_type; /** * Construct singular ConstMemoryPool. * * All behavior of a singular ConstMemoryPool is undefined except for * assignment, copying, comparison, and evaluate-as-bool. **/ ConstMemoryPool(); /** * The name of the memory pool. * * @returns Name or NULL if no name is set. **/ const char* name() const; /** * @name C Interoperability * Methods to access underlying C types. **/ ///@{ //! Non-const ib_mpool_t accessor. // Intentionally inlined. const ib_mpool_t* ib() const { return m_ib; } //! Construct MemoryPools from ib_mpool_t. explicit ConstMemoryPool(const ib_mpool_t* ib_mpool); ///@} private: const ib_mpool_t* m_ib; }; /** * Memory pool; equivalent to ib_mpool_t. * * Memory Pools can be treated as ConstMemoryPools. See @ref ironbeepp for * details on IronBee++ object semantics. * * IronBee makes frequent use of memory pools to manage memory and object * lifetime. The engine, each transaction, context, etc. all have associated * memory pools that are used to allocate memory for objects whose lifetime * is a subset of the memory pool holder. This class represents such a * memory pool and provides low level routines. * * As per the IronBee++ reference semantics, an object of this class is best * viewed as a reference to a MemoryPool, i.e., as equivalent to * @c ib_mpool_t* rather than ib_mpool_t. As such, they can not be directly * created. Similarly, destroying one does not destroy the underlying * memory pool. There are static create() methods available to create new * memory pools and a destroy() method to destroy them. * * There is no requirement that you use MemoryPool to allocate memory for * your own C++ objects. And doing so has risks as the (C) memory pool * implementation is not aware of destructors and will not call them on * pool destruction. * * If your goal is to do cleanup tasks when a memory pool is destroyed, use * register_cleanup(). * * Unfortunately, the semantics of IronBee memory pools and the stringent * requirements on standard allocators makes it impossible to write a * conforming standard allocator based on MemoryPool. * * If you want RAII semantics for creating memory pools, see ScopedMemoryPool. * * @sa ironbeepp * @sa ib_mpool_t * @sa ConstMemoryPool * @nosubgrouping **/ class MemoryPool : public ConstMemoryPool // Slicing is intentional; see apidoc.hpp { public: //! C Type. typedef ib_mpool_t* ib_type; /** * Remove the constness of a ConstMemoryPool. * * @warning This is as dangerous as a @c const_cast, use carefully. * * @param[in] const_pool ConstMemoryPool to remove const from. * @returns MemoryPool pointing to same underlying memory pool as * @a const_pool. **/ static MemoryPool remove_const(const ConstMemoryPool& const_pool); /** * Construct singular MemoryPool. * * All behavior of a singular MemoryPool is undefined except for * assignment, copying, comparison, and evaluate-as-bool. **/ MemoryPool(); /** * @name Creation * Routines for creating new memory pools. * * These routines create a new memory pool. The pool must be explicitly * destroyed via destroy(). * * For RAII semantics, see ScopedMemoryPool. **/ //@{ /** * Create MemoryPool with default settings. * * Creates a memory pool with name "MemoryPool", no parent, and the * default page size. * * @returns Memory pool. * @throw Appropriate IronBee++ exception on failure. **/ static MemoryPool create(); /** * Create MemoryPool. * * @param[in] name Name of pool; used for debugging. * @param[in] size Page size if non-0; otherwise uses 1024 byte pages. * @returns Memory pool. * @throw Appropriate IronBee++ exception on failure. **/ static MemoryPool create( const char* name, size_t size = 0 ); /** * Create MemoryPool with parent. * * The MemoryPool will be destroyed when the parent is destroyed. * * @sa create_subpool() * * @param[in] name Name of pool; used for debugging. * @param[in] parent Parent memory pool. * @param[in] size Page size if non-0; otherwise uses 1024 byte pages. * @returns Memory pool. * @throw Appropriate IronBee++ exception on failure. **/ static MemoryPool create( const char* name, MemoryPool parent, size_t size = 0 ); /** * Create a subpool that will be destroyed when this is destroyed. * * Name is "SubPool" and page size is default. * * @returns Memory pool. * @throw Appropriate IronBee++ exception on failure. **/ MemoryPool create_subpool() const; /** * Create a subpool that will be destroyed when this is destroyed. * * @param[in] subpool_name Name of pool; used for debugging. * @param[in] size Page size if non-0; otherwise uses 1024 byte * pages. * @returns Memory pool. * @throw Appropriate IronBee++ exception on failure. **/ MemoryPool create_subpool( const char* subpool_name, size_t size = 0 ) const; //@} /** * @name Allocation * Routines to allocate memory. **/ //@{ /** * Allocate sufficient memory for a @a number @a Ts * * Note: This does not construct any Ts, simply allocates memory. You * will need to use placement new to construct the T. * * @tparam T Type to allocate memory for. * @param[in] number Number of Ts. * @returns Pointer to allocated memory. * @throw ealloc on failure to allocate. **/ template <typename T> T* allocate(size_t number) const; /** * Allocate @a size bytes of memory. * * @param[in] size Number of bytes to allocate. * @returns Pointer to allocated memory. * @throw ealloc on failure to allocate. **/ void* alloc(size_t size) const; /** * Allocate @a count * @a size bytes of memory and sets to 0. * * @param[in] count Number of elements to allocate memory for. * @param[in] size Size of each element. * @returns Pointer to allocated memory. * @throw ealloc on failure to allocate. **/ void* calloc(size_t count, size_t size) const; /** * Allocate @a size bytes and set to 0. * @param[in] size Size of each element. * @returns Pointer to allocated memory. * @throw ealloc on failure to allocate. **/ void* calloc(size_t size) const; //@} /** * Deallocate all memory associated with this pool and all child pools. **/ void clear() const; /** * Destroy this pool and all child pools. **/ void destroy() const; //! Type of a cleanup handler. typedef boost::function<void()> cleanup_t; /** * Register @a f to be called when the pool is destroyed. * * @param[in] f Function to call on destruction. **/ void register_cleanup(cleanup_t f) const; /** * @name C Interoperability * Methods to access underlying C types. **/ ///@{ //! Non-const ib_mpool_t accessor. // Intentionally inlined. ib_mpool_t* ib() const { return m_ib; } //! Construct MemoryPools from ib_mpool_t. explicit MemoryPool(ib_mpool_t* ib_mpool); ///@} private: ib_mpool_t* m_ib; }; /** * Enables RAII semantics for MemoryPool. * * This non-copyable class creates a new MemoryPool on construction and * destroys it on destruction. * * ScopedMemoryPools can not have parents as their destruction is exactly * bound to the object destruction. * * A ScopedMemoryPool can be used anywhere a MemoryPool can be. **/ class ScopedMemoryPool : boost::noncopyable { public: /** * Constructs memory pool with name "ScopedMemoryPool" and default page * size. * * @throw ealloc on failure. **/ ScopedMemoryPool(); /** * Construct memory pool. * * @param[in] name Name of pool; used for debugging. * @param[in] size Page size if non-0; otherwise uses 1024 byte pages. * @throw Appropriate IronBee++ exception on failure. **/ explicit ScopedMemoryPool(const char* name, size_t size = 0); /** * Destroy associated pool. **/ ~ScopedMemoryPool(); //! Implicit conversion to MemoryPool. // Intentionally inlined. operator MemoryPool() const { return m_pool; } private: MemoryPool m_pool; }; //! Ostream output for MemoryPool. std::ostream& operator<<(std::ostream& o, const ConstMemoryPool& pool); // Template Definition template <typename T> T* MemoryPool::allocate(size_t number) const { return static_cast<T*>(alloc(number * sizeof(T))); } }; #endif <commit_msg>IronBee++/MemoryPool: Add default argument to allocate(), i.e., 1.<commit_after>/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief IronBee++ &mdash; Memory Pool * * This file defines MemoryPool, a wrapper for ib_mpool_t. * * @author Christopher Alfeld <calfeld@qualys.com> */ #ifndef __IBPP__MEMORY_POOL__ #define __IBPP__MEMORY_POOL__ #include <ironbeepp/common_semantics.hpp> #include <boost/function.hpp> #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdelete-non-virtual-dtor" #endif #include <boost/utility.hpp> #ifdef __clang__ #pragma clang diagnostic pop #endif #include <ostream> // IronBee C typedef struct ib_mpool_t ib_mpool_t; namespace IronBee { /** * Const Memory Pool; equivalent to a const pointer to ib_mpool_t. * * Provides operators ==, !=, <, >, <=, >= and evaluation as a boolean for * singularity via CommonSemantics. * * See MemoryPool for discussion of memory pools. * * @sa MemoryPool * @sa ironbeepp * @sa ib_bytestr_t * @nosubgrouping **/ class ConstMemoryPool : public CommonSemantics<ConstMemoryPool> { public: //! C Type. typedef const ib_mpool_t* ib_type; /** * Construct singular ConstMemoryPool. * * All behavior of a singular ConstMemoryPool is undefined except for * assignment, copying, comparison, and evaluate-as-bool. **/ ConstMemoryPool(); /** * The name of the memory pool. * * @returns Name or NULL if no name is set. **/ const char* name() const; /** * @name C Interoperability * Methods to access underlying C types. **/ ///@{ //! Non-const ib_mpool_t accessor. // Intentionally inlined. const ib_mpool_t* ib() const { return m_ib; } //! Construct MemoryPools from ib_mpool_t. explicit ConstMemoryPool(const ib_mpool_t* ib_mpool); ///@} private: const ib_mpool_t* m_ib; }; /** * Memory pool; equivalent to ib_mpool_t. * * Memory Pools can be treated as ConstMemoryPools. See @ref ironbeepp for * details on IronBee++ object semantics. * * IronBee makes frequent use of memory pools to manage memory and object * lifetime. The engine, each transaction, context, etc. all have associated * memory pools that are used to allocate memory for objects whose lifetime * is a subset of the memory pool holder. This class represents such a * memory pool and provides low level routines. * * As per the IronBee++ reference semantics, an object of this class is best * viewed as a reference to a MemoryPool, i.e., as equivalent to * @c ib_mpool_t* rather than ib_mpool_t. As such, they can not be directly * created. Similarly, destroying one does not destroy the underlying * memory pool. There are static create() methods available to create new * memory pools and a destroy() method to destroy them. * * There is no requirement that you use MemoryPool to allocate memory for * your own C++ objects. And doing so has risks as the (C) memory pool * implementation is not aware of destructors and will not call them on * pool destruction. * * If your goal is to do cleanup tasks when a memory pool is destroyed, use * register_cleanup(). * * Unfortunately, the semantics of IronBee memory pools and the stringent * requirements on standard allocators makes it impossible to write a * conforming standard allocator based on MemoryPool. * * If you want RAII semantics for creating memory pools, see ScopedMemoryPool. * * @sa ironbeepp * @sa ib_mpool_t * @sa ConstMemoryPool * @nosubgrouping **/ class MemoryPool : public ConstMemoryPool // Slicing is intentional; see apidoc.hpp { public: //! C Type. typedef ib_mpool_t* ib_type; /** * Remove the constness of a ConstMemoryPool. * * @warning This is as dangerous as a @c const_cast, use carefully. * * @param[in] const_pool ConstMemoryPool to remove const from. * @returns MemoryPool pointing to same underlying memory pool as * @a const_pool. **/ static MemoryPool remove_const(const ConstMemoryPool& const_pool); /** * Construct singular MemoryPool. * * All behavior of a singular MemoryPool is undefined except for * assignment, copying, comparison, and evaluate-as-bool. **/ MemoryPool(); /** * @name Creation * Routines for creating new memory pools. * * These routines create a new memory pool. The pool must be explicitly * destroyed via destroy(). * * For RAII semantics, see ScopedMemoryPool. **/ //@{ /** * Create MemoryPool with default settings. * * Creates a memory pool with name "MemoryPool", no parent, and the * default page size. * * @returns Memory pool. * @throw Appropriate IronBee++ exception on failure. **/ static MemoryPool create(); /** * Create MemoryPool. * * @param[in] name Name of pool; used for debugging. * @param[in] size Page size if non-0; otherwise uses 1024 byte pages. * @returns Memory pool. * @throw Appropriate IronBee++ exception on failure. **/ static MemoryPool create( const char* name, size_t size = 0 ); /** * Create MemoryPool with parent. * * The MemoryPool will be destroyed when the parent is destroyed. * * @sa create_subpool() * * @param[in] name Name of pool; used for debugging. * @param[in] parent Parent memory pool. * @param[in] size Page size if non-0; otherwise uses 1024 byte pages. * @returns Memory pool. * @throw Appropriate IronBee++ exception on failure. **/ static MemoryPool create( const char* name, MemoryPool parent, size_t size = 0 ); /** * Create a subpool that will be destroyed when this is destroyed. * * Name is "SubPool" and page size is default. * * @returns Memory pool. * @throw Appropriate IronBee++ exception on failure. **/ MemoryPool create_subpool() const; /** * Create a subpool that will be destroyed when this is destroyed. * * @param[in] subpool_name Name of pool; used for debugging. * @param[in] size Page size if non-0; otherwise uses 1024 byte * pages. * @returns Memory pool. * @throw Appropriate IronBee++ exception on failure. **/ MemoryPool create_subpool( const char* subpool_name, size_t size = 0 ) const; //@} /** * @name Allocation * Routines to allocate memory. **/ //@{ /** * Allocate sufficient memory for a @a number @a Ts * * Note: This does not construct any Ts, simply allocates memory. You * will need to use placement new to construct the T. * * @tparam T Type to allocate memory for. * @param[in] number Number of Ts. * @returns Pointer to allocated memory. * @throw ealloc on failure to allocate. **/ template <typename T> T* allocate(size_t number = 1) const; /** * Allocate @a size bytes of memory. * * @param[in] size Number of bytes to allocate. * @returns Pointer to allocated memory. * @throw ealloc on failure to allocate. **/ void* alloc(size_t size) const; /** * Allocate @a count * @a size bytes of memory and sets to 0. * * @param[in] count Number of elements to allocate memory for. * @param[in] size Size of each element. * @returns Pointer to allocated memory. * @throw ealloc on failure to allocate. **/ void* calloc(size_t count, size_t size) const; /** * Allocate @a size bytes and set to 0. * @param[in] size Size of each element. * @returns Pointer to allocated memory. * @throw ealloc on failure to allocate. **/ void* calloc(size_t size) const; //@} /** * Deallocate all memory associated with this pool and all child pools. **/ void clear() const; /** * Destroy this pool and all child pools. **/ void destroy() const; //! Type of a cleanup handler. typedef boost::function<void()> cleanup_t; /** * Register @a f to be called when the pool is destroyed. * * @param[in] f Function to call on destruction. **/ void register_cleanup(cleanup_t f) const; /** * @name C Interoperability * Methods to access underlying C types. **/ ///@{ //! Non-const ib_mpool_t accessor. // Intentionally inlined. ib_mpool_t* ib() const { return m_ib; } //! Construct MemoryPools from ib_mpool_t. explicit MemoryPool(ib_mpool_t* ib_mpool); ///@} private: ib_mpool_t* m_ib; }; /** * Enables RAII semantics for MemoryPool. * * This non-copyable class creates a new MemoryPool on construction and * destroys it on destruction. * * ScopedMemoryPools can not have parents as their destruction is exactly * bound to the object destruction. * * A ScopedMemoryPool can be used anywhere a MemoryPool can be. **/ class ScopedMemoryPool : boost::noncopyable { public: /** * Constructs memory pool with name "ScopedMemoryPool" and default page * size. * * @throw ealloc on failure. **/ ScopedMemoryPool(); /** * Construct memory pool. * * @param[in] name Name of pool; used for debugging. * @param[in] size Page size if non-0; otherwise uses 1024 byte pages. * @throw Appropriate IronBee++ exception on failure. **/ explicit ScopedMemoryPool(const char* name, size_t size = 0); /** * Destroy associated pool. **/ ~ScopedMemoryPool(); //! Implicit conversion to MemoryPool. // Intentionally inlined. operator MemoryPool() const { return m_pool; } private: MemoryPool m_pool; }; //! Ostream output for MemoryPool. std::ostream& operator<<(std::ostream& o, const ConstMemoryPool& pool); // Template Definition template <typename T> T* MemoryPool::allocate(size_t number) const { return static_cast<T*>(alloc(number * sizeof(T))); } }; #endif <|endoftext|>
<commit_before>#pragma once #include <iostream> #include <fstream> #include "singleton.h" /// It is used to add function name, line number and file name if needed. #define LOG(level) \ Logger::Instance(level, __func__, std::to_string(__LINE__), __FILE__) /// It is used to add function name, line number and file name if needed. #define LOG_MESSAGE(level, message) \ Logger::Log(level, message, __func__, std::to_string(__LINE__), __FILE__) /// Log level. enum class LogLevel { trace, debug, info, warning, error, fatal }; /// It is used to output information /// to the screen or a file. class Logger : public Singleton<Logger> { public: Logger(LogLevel level, std::string const & functionName = "", std::string lineNumber = "", std::string const & fileName = ""); static std::ofstream & GetFile(bool const & isReset = false) { static std::ofstream m_outfile; // If a file is opened then just return it. if (m_outfile.is_open()) { return m_outfile; } // Clean a file if needed otherwise just open it. if (isReset) { m_outfile.open(m_fileName, std::ios::out | std::ios::trunc); m_outfile.close(); } else { m_outfile.open(m_fileName, std::ios::out | std::ios::app); } return m_outfile; } /// Set the current log level. static void SetLogLevel(LogLevel const &type); /// Set output option. static void SetPrintToFile(std::string const & fileName, bool const & isPrintToFile = false); /// Set output option. static void SetPrintFunctionName(bool const & isPrintFunctionName); /// Set output option. static void SetPrintLineNumber(bool const & isPrintLineNumber); /// Set output option. static void SetPrintFileName(bool const & isPrintFileName); /// Get the current log level. static std::string GetLogLevelAsString(LogLevel const &type); /// Output a function name, line number and file name if needed. static void PrintAdditionalParameters( std::string const & functionName, std::string lineNumber, std::string const & fileName); /// It simply output a message with a log level. static void Log(LogLevel const & logLevel, std::string const & message, std::string const & functionName = "", std::string lineNumber = "", std::string const & fileName = ""); static LogLevel GetLogLevel(); /// Output an object to the screen. template<class T> Logger & operator << (T const & obj) { if (m_isPrint) { std::cout << obj; } return *this; } Logger & operator << (std::ostream & (*manip)(std::ostream &)) { manip(std::cout); return *this; } /// Output a collection of objects to the screen. template<typename T, template<typename, typename...> class C, typename... Args> Logger & operator << (C<T, Args...> const & objs) { if (m_isPrint) { for (auto const & obj : objs) { std::cout << obj << " "; } } return *this; } private: /// Otherwise it won't be accessible in parent class Singleton<Logger>. friend class Singleton<Logger>; Logger() = default; /// It is used to store the current log level. static LogLevel m_msgLevel; /// It is used to store the current output message flag. static bool m_isPrint; /// It is used to store the current output function name flag. static bool m_isPrintFunctionName; /// It is used to store the current output line numer flag. static bool m_isPrintLineNumber; /// It is used to store the current output file name flag. static bool m_isPrintFileName; /// It is used to store the current file name. static std::string m_fileName; /// It is used to store the ability to output to a file. static bool m_isPrintToFile; }; <commit_msg>fix codestyle<commit_after>#pragma once #include <iostream> #include <fstream> #include "singleton.h" /// It is used to add function name, line number and file name if needed. #define LOG(level) \ Logger::Instance(level, __func__, std::to_string(__LINE__), __FILE__) /// It is used to add function name, line number and file name if needed. #define LOG_MESSAGE(level, message) \ Logger::Log(level, message, __func__, std::to_string(__LINE__), __FILE__) /// Log level. enum class LogLevel { trace, debug, info, warning, error, fatal }; /// It is used to output information /// to the screen or a file. class Logger : public Singleton<Logger> { public: Logger(LogLevel level, std::string const & functionName = "", std::string lineNumber = "", std::string const & fileName = ""); static std::ofstream & GetFile(bool const & isReset = false) { static std::ofstream m_outfile; // If a file is opened then just return it. if (m_outfile.is_open()) { return m_outfile; } // Clean a file if needed otherwise just open it. if (isReset) { m_outfile.open(m_fileName, std::ios::out | std::ios::trunc); m_outfile.close(); } else { m_outfile.open(m_fileName, std::ios::out | std::ios::app); } return m_outfile; } /// Set the current log level. static void SetLogLevel(LogLevel const &type); /// Set output option. static void SetPrintToFile(std::string const & fileName, bool const & isPrintToFile = false); /// Set output option. static void SetPrintFunctionName(bool const & isPrintFunctionName); /// Set output option. static void SetPrintLineNumber(bool const & isPrintLineNumber); /// Set output option. static void SetPrintFileName(bool const & isPrintFileName); /// Get the current log level. static std::string GetLogLevelAsString(LogLevel const &type); /// Output a function name, line number and file name if needed. static void PrintAdditionalParameters( std::string const & functionName, std::string lineNumber, std::string const & fileName); /// It simply output a message with a log level. static void Log(LogLevel const & logLevel, std::string const & message, std::string const & functionName = "", std::string lineNumber = "", std::string const & fileName = ""); static LogLevel GetLogLevel(); /// Output an object to the screen. template<class T> Logger & operator << (T const & obj) { if (m_isPrint) { std::cout << obj; } return *this; } Logger & operator << (std::ostream & (*manip)(std::ostream &)) { manip(std::cout); return *this; } /// Output a collection of objects to the screen. template<typename T, template<typename, typename...> class C, typename... Args> Logger & operator << (C<T, Args...> const & objs) { if (m_isPrint) { for (auto const & obj : objs) { std::cout << obj << " "; } } return *this; } private: /// Otherwise it won't be accessible in parent class Singleton<Logger>. friend class Singleton<Logger>; Logger() = default; /// It is used to store the current log level. static LogLevel m_msgLevel; /// It is used to store the current output message flag. static bool m_isPrint; /// It is used to store the current output function name flag. static bool m_isPrintFunctionName; /// It is used to store the current output line numer flag. static bool m_isPrintLineNumber; /// It is used to store the current output file name flag. static bool m_isPrintFileName; /// It is used to store the current file name. static std::string m_fileName; /// It is used to store the ability to output to a file. static bool m_isPrintToFile; }; <|endoftext|>
<commit_before>// __BEGIN_LICENSE__ // Copyright (C) 2006-2011 United States Government as represented by // the Administrator of the National Aeronautics and Space Administration. // All Rights Reserved. // __END_LICENSE__ #include <vector> #include <vw/Core/Log.h> #include <vw/Core/Exception.h> #include <vw/Core/Settings.h> // C Standard Library headers ( for stat(2) and getpwuid() ) #include <sys/types.h> #include <sys/stat.h> #include <ctime> #include <vw/config.h> #ifdef VW_HAVE_UNISTD_H #include <unistd.h> #endif #ifdef VW_HAVE_PWD_H #include <pwd.h> #endif #ifdef WIN32 #define stat _stat typedef struct _stat struct_stat; #else typedef struct stat struct_stat; #endif inline std::string current_posix_time_string() { char time_string[2048]; time_t t = time(0); struct tm* time_struct = localtime(&t); strftime(time_string, 2048, "%F %T", time_struct); return std::string(time_string); } namespace { static vw::null_ostream g_null_ostream; } // --------------------------------------------------- // Basic stream support // --------------------------------------------------- std::ostream& vw::vw_out( int log_level, std::string const& log_namespace ) { return vw_log()(log_level, log_namespace); } void vw::set_debug_level( int log_level ) { vw_log().console_log().rule_set().add_rule(log_level, "console"); } void vw::set_output_stream( std::ostream& stream ) { vw_log().set_console_stream(stream); } // --------------------------------------------------- // LogInstance Methods // --------------------------------------------------- vw::LogInstance::LogInstance(std::string const& log_filename, bool prepend_infostamp) : m_prepend_infostamp(prepend_infostamp) { // Open file and place the insertion pointer at the end of the file (ios_base::ate) m_log_ostream_ptr = new std::ofstream(log_filename.c_str(), std::ios::app); if (! static_cast<std::ofstream*>(m_log_ostream_ptr)->is_open()) vw_throw(IOErr() << "Could not open log file " << log_filename << " for writing."); *m_log_ostream_ptr << "\n\n" << "Vision Workbench log started at " << current_posix_time_string() << ".\n\n"; m_log_stream.set_stream(*m_log_ostream_ptr); } vw::LogInstance::LogInstance(std::ostream& log_ostream, bool prepend_infostamp) : m_log_stream(log_ostream), m_log_ostream_ptr(NULL), m_prepend_infostamp(prepend_infostamp) {} std::ostream& vw::LogInstance::operator() (int log_level, std::string const& log_namespace) { if (m_rule_set(log_level, log_namespace)) { if (m_prepend_infostamp) m_log_stream << current_posix_time_string() << " {" << Thread::id() << "} [ " << log_namespace << " ] : "; switch (log_level) { case ErrorMessage: m_log_stream << "Error: "; break; case WarningMessage: m_log_stream << "Warning: "; break; default: break; } return m_log_stream; } else { return g_null_ostream; } } std::ostream& vw::Log::operator() (int log_level, std::string const& log_namespace) { // First, check to see if the rc file has been updated. // Reload the rulesets if it has. vw_settings().reload_config(); { Mutex::Lock multi_ostreams_lock(m_multi_ostreams_mutex); // Check to see if we have an ostream defined yet for this thread. if(m_multi_ostreams.find( Thread::id() ) == m_multi_ostreams.end()) m_multi_ostreams[ Thread::id() ] = boost::shared_ptr<multi_ostream>(new multi_ostream); boost::shared_ptr<multi_ostream>& stream = m_multi_ostreams[ Thread::id() ]; // Reset and add the console log output... stream->clear(); stream->add(m_console_log->operator()(log_level, log_namespace)); // ... and the rest of the active log streams. std::vector<boost::shared_ptr<LogInstance> >::iterator iter = m_logs.begin(); for (;iter != m_logs.end(); ++iter) stream->add((*iter)->operator()(log_level,log_namespace)); return *stream; } } vw::LogRuleSet::LogRuleSet( LogRuleSet const& copy_log) { m_rules = copy_log.m_rules; } vw::LogRuleSet& vw::LogRuleSet::operator=( LogRuleSet const& copy_log) { m_rules = copy_log.m_rules; return *this; } vw::LogRuleSet::LogRuleSet() { } vw::LogRuleSet::~LogRuleSet() { } void vw::LogRuleSet::add_rule(int log_level, std::string const& log_namespace) { ssize_t count = std::count(log_namespace.begin(), log_namespace.end(), '*'); if (count > 1) vw::vw_throw(vw::ArgumentErr() << "Illegal log rule: only one wildcard is supported."); if (count == 1 && *(log_namespace.begin()) != '*' && *(log_namespace.end()-1) != '*') vw::vw_throw(vw::ArgumentErr() << "Illegal log rule: wildcards must be at the beginning or end of a rule"); Mutex::Lock lock(m_mutex); m_rules.push_front(rule_type(log_level, boost::to_lower_copy(log_namespace))); } void vw::LogRuleSet::clear() { Mutex::Lock lock(m_mutex); m_rules.clear(); } namespace { bool wildcard_match(const std::string& pattern, const std::string& str) { // Rules: // * matches anything // *.a matches [first.a, second.a] // a matches just a (ie, no namespace) // a.* matches [a, a.first, a.first.second] // if (pattern == "*") return true; // If there's no wildcard, just do a comparison. size_t idx = pattern.find("*"); if (idx == std::string::npos) return (pattern == str); // There's a wildcard. Try to expand it. if (idx == 0) { // leading *. it's a suffix rule. return boost::ends_with(str, pattern.substr(1)); } else { // add_rule above verifies that the wildcard is first or last, so this // one must be last. if (pattern.size() > 1 && pattern[idx-1] == '.') if (str == pattern.substr(0, idx-1)) return true; return boost::starts_with(str, pattern.substr(0, idx)); } return false; } } // You can overload this method from a subclass to change the // behavior of the LogRuleSet. bool vw::LogRuleSet::operator() (int log_level, std::string const& log_namespace) { Mutex::Lock lock(m_mutex); std::string lower_namespace = boost::to_lower_copy(log_namespace); for (rules_type::iterator it = m_rules.begin(); it != m_rules.end(); ++it) { const int& rule_lvl = it->first; const std::string& rule_ns = it->second; // first rule that matches the namespace spec is applied. if (!wildcard_match(rule_ns, lower_namespace) ) continue; if (rule_lvl == vw::EveryMessage) return true; return log_level <= rule_lvl; } if (log_level <= vw::InfoMessage) if (log_namespace == "console" || wildcard_match("*.progress", lower_namespace)) return true; if (log_level <= vw::WarningMessage) return true; // We reach this line if all of the rules have failed, in // which case we return a NULL stream, which will result in // nothing being logged. return false; } <commit_msg>speed up LogRuleSet slightly<commit_after>// __BEGIN_LICENSE__ // Copyright (C) 2006-2011 United States Government as represented by // the Administrator of the National Aeronautics and Space Administration. // All Rights Reserved. // __END_LICENSE__ #include <vector> #include <vw/Core/Log.h> #include <vw/Core/Exception.h> #include <vw/Core/Settings.h> // C Standard Library headers ( for stat(2) and getpwuid() ) #include <sys/types.h> #include <sys/stat.h> #include <ctime> #include <vw/config.h> #ifdef VW_HAVE_UNISTD_H #include <unistd.h> #endif #ifdef VW_HAVE_PWD_H #include <pwd.h> #endif #ifdef WIN32 #define stat _stat typedef struct _stat struct_stat; #else typedef struct stat struct_stat; #endif inline std::string current_posix_time_string() { char time_string[2048]; time_t t = time(0); struct tm* time_struct = localtime(&t); strftime(time_string, 2048, "%F %T", time_struct); return std::string(time_string); } namespace { static vw::null_ostream g_null_ostream; } // --------------------------------------------------- // Basic stream support // --------------------------------------------------- std::ostream& vw::vw_out( int log_level, std::string const& log_namespace ) { return vw_log()(log_level, log_namespace); } void vw::set_debug_level( int log_level ) { vw_log().console_log().rule_set().add_rule(log_level, "console"); } void vw::set_output_stream( std::ostream& stream ) { vw_log().set_console_stream(stream); } // --------------------------------------------------- // LogInstance Methods // --------------------------------------------------- vw::LogInstance::LogInstance(std::string const& log_filename, bool prepend_infostamp) : m_prepend_infostamp(prepend_infostamp) { // Open file and place the insertion pointer at the end of the file (ios_base::ate) m_log_ostream_ptr = new std::ofstream(log_filename.c_str(), std::ios::app); if (! static_cast<std::ofstream*>(m_log_ostream_ptr)->is_open()) vw_throw(IOErr() << "Could not open log file " << log_filename << " for writing."); *m_log_ostream_ptr << "\n\n" << "Vision Workbench log started at " << current_posix_time_string() << ".\n\n"; m_log_stream.set_stream(*m_log_ostream_ptr); } vw::LogInstance::LogInstance(std::ostream& log_ostream, bool prepend_infostamp) : m_log_stream(log_ostream), m_log_ostream_ptr(NULL), m_prepend_infostamp(prepend_infostamp) {} std::ostream& vw::LogInstance::operator() (int log_level, std::string const& log_namespace) { if (m_rule_set(log_level, log_namespace)) { if (m_prepend_infostamp) m_log_stream << current_posix_time_string() << " {" << Thread::id() << "} [ " << log_namespace << " ] : "; switch (log_level) { case ErrorMessage: m_log_stream << "Error: "; break; case WarningMessage: m_log_stream << "Warning: "; break; default: break; } return m_log_stream; } else { return g_null_ostream; } } std::ostream& vw::Log::operator() (int log_level, std::string const& log_namespace) { // First, check to see if the rc file has been updated. // Reload the rulesets if it has. vw_settings().reload_config(); { Mutex::Lock multi_ostreams_lock(m_multi_ostreams_mutex); // Check to see if we have an ostream defined yet for this thread. if(m_multi_ostreams.find( Thread::id() ) == m_multi_ostreams.end()) m_multi_ostreams[ Thread::id() ] = boost::shared_ptr<multi_ostream>(new multi_ostream); boost::shared_ptr<multi_ostream>& stream = m_multi_ostreams[ Thread::id() ]; // Reset and add the console log output... stream->clear(); stream->add(m_console_log->operator()(log_level, log_namespace)); // ... and the rest of the active log streams. std::vector<boost::shared_ptr<LogInstance> >::iterator iter = m_logs.begin(); for (;iter != m_logs.end(); ++iter) stream->add((*iter)->operator()(log_level,log_namespace)); return *stream; } } vw::LogRuleSet::LogRuleSet( LogRuleSet const& copy_log) { m_rules = copy_log.m_rules; } vw::LogRuleSet& vw::LogRuleSet::operator=( LogRuleSet const& copy_log) { m_rules = copy_log.m_rules; return *this; } vw::LogRuleSet::LogRuleSet() { } vw::LogRuleSet::~LogRuleSet() { } void vw::LogRuleSet::add_rule(int log_level, std::string const& log_namespace) { ssize_t count = std::count(log_namespace.begin(), log_namespace.end(), '*'); if (count > 1) vw::vw_throw(vw::ArgumentErr() << "Illegal log rule: only one wildcard is supported."); if (count == 1 && *(log_namespace.begin()) != '*' && *(log_namespace.end()-1) != '*') vw::vw_throw(vw::ArgumentErr() << "Illegal log rule: wildcards must be at the beginning or end of a rule"); Mutex::Lock lock(m_mutex); m_rules.push_front(rule_type(log_level, boost::to_lower_copy(log_namespace))); } void vw::LogRuleSet::clear() { Mutex::Lock lock(m_mutex); m_rules.clear(); } namespace { bool wildcard_match(const std::string& pattern, const std::string& str) { // Rules: // * matches anything // *.a matches [first.a, second.a] // a matches just a (ie, no namespace) // a.* matches [a, a.first, a.first.second] // if (pattern == "*") return true; // If there's no wildcard, just do a comparison. size_t idx = pattern.find("*"); if (idx == std::string::npos) return (pattern == str); // There's a wildcard. Try to expand it. if (idx == 0) { // leading *. it's a suffix rule. return boost::ends_with(str, pattern.substr(1)); } else { // add_rule above verifies that the wildcard is first or last, so this // one must be last. if (pattern.size() > 1 && pattern[idx-1] == '.') if (str == pattern.substr(0, idx-1)) return true; return boost::starts_with(str, pattern.substr(0, idx)); } return false; } } // You can overload this method from a subclass to change the // behavior of the LogRuleSet. bool vw::LogRuleSet::operator() (int log_level, std::string const& log_namespace) { Mutex::ReadLock lock(m_mutex); std::string lower_namespace = boost::to_lower_copy(log_namespace); for (rules_type::const_iterator it = m_rules.begin(); it != m_rules.end(); ++it) { const int& rule_lvl = it->first; const std::string& rule_ns = it->second; // first rule that matches the namespace spec is applied. if (!wildcard_match(rule_ns, lower_namespace) ) continue; if (rule_lvl == vw::EveryMessage) return true; return log_level <= rule_lvl; } if (log_level <= vw::InfoMessage) if (log_namespace == "console" || wildcard_match("*.progress", lower_namespace)) return true; if (log_level <= vw::WarningMessage) return true; // We reach this line if all of the rules have failed, in // which case we return a NULL stream, which will result in // nothing being logged. return false; } <|endoftext|>
<commit_before>/* * This file is part of otf2xx (https://github.com/tud-zih-energy/otf2xx) * otf2xx - A wrapper for the Open Trace Format 2 library * * Copyright (c) 2013-2016, Technische Universität Dresden, Germany * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef INCLUDE_OTF2XX_CHRONO_CONVERT_HPP #define INCLUDE_OTF2XX_CHRONO_CONVERT_HPP #include <otf2xx/chrono/clock.hpp> #include <otf2xx/chrono/ticks.hpp> #include <otf2xx/chrono/time_point.hpp> #include <cassert> #include <limits> namespace otf2 { namespace chrono { /** * \brief class to convert between ticks and time points * * This class can convert between ticks and time points. * For this, it needs the number of ticks per second. * * \note The time epoch is assumed to be equal between the time point and * time point represented with the number ticks given. */ class convert { const uint64_t ticks_per_second; static_assert(clock::period::num == 1, "Don't mess around with chrono!"); public: /** * \param[in] ticks_per_second Number of ticks per second */ convert(uint64_t ticks_per_second) : ticks_per_second(ticks_per_second) { } /** * \param[in] ticks Number of ticks per second */ convert(otf2::chrono::ticks ticks) : ticks_per_second(ticks.count()) { } /** * \brief converts from ticks to time point * * \param[in] ticks ticks since epoch * \return time_point with a duration equal to the passed time * since the epoch. */ otf2::chrono::time_point operator()(otf2::chrono::ticks ticks) const { // WARNING: Be careful, when changing clock::period::den. // You will have to think about every calculations twice, as there // might be narrowing and rounding anywhere. // We also assumed here, that we have nanoseconds or picoseconds resolution and the // input resolution is about nanoseconds or a few hundred // picoseconds. // These assumptions have to be double checked! double factor = static_cast<double>(clock::period::den) / ticks_per_second; assert(ticks_per_second <= clock::period::den); assert(ticks.count() < static_cast<uint64_t>(std::numeric_limits<int64_t>::max()) / factor); return time_point(otf2::chrono::duration(static_cast<int64_t>(ticks.count() * factor))); } /** * \brief converts from time points to ticks * * \param[in] t a time point * \return number ticks equal to passed time of the duration of the time * point */ otf2::chrono::ticks operator()(time_point t) const { assert(ticks_per_second == clock::period::den); return ticks( otf2::chrono::duration_cast<otf2::chrono::duration>(t.time_since_epoch()).count()); } }; /** * \brief converts from std::chrono::timepoint to otf2::chrono::time_point * * \param[in] tp the std::chrono time point * \return the same time point as otf2::chrono::time_point */ template <typename Clock, typename Duration> otf2::chrono::time_point convert_time_point(std::chrono::time_point<Clock, Duration> tp) { return otf2::chrono::time_point( std::chrono::duration_cast<otf2::chrono::clock::duration>(tp.time_since_epoch())); } } // namespace chrono } // namespace otf2 #endif // INCLUDE_OTF2XX_CHRONO_CONVERT_HPP <commit_msg>convert timestamps back to OTF2 timestamps<commit_after>/* * This file is part of otf2xx (https://github.com/tud-zih-energy/otf2xx) * otf2xx - A wrapper for the Open Trace Format 2 library * * Copyright (c) 2013-2016, Technische Universität Dresden, Germany * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef INCLUDE_OTF2XX_CHRONO_CONVERT_HPP #define INCLUDE_OTF2XX_CHRONO_CONVERT_HPP #include <otf2xx/chrono/clock.hpp> #include <otf2xx/chrono/ticks.hpp> #include <otf2xx/chrono/time_point.hpp> #include <cassert> #include <cmath> #include <limits> namespace otf2 { namespace chrono { /** * \brief class to convert between ticks and time points * * This class can convert between ticks and time points. * For this, it needs the number of ticks per second. * * \note The time epoch is assumed to be equal between the time point and * time point represented with the number ticks given. */ class convert { const uint64_t ticks_per_second; static_assert(clock::period::num == 1, "Don't mess around with chrono!"); public: /** * \param[in] ticks_per_second Number of ticks per second */ convert(uint64_t ticks_per_second) : ticks_per_second(ticks_per_second) { } /** * \param[in] ticks Number of ticks per second */ convert(otf2::chrono::ticks ticks) : ticks_per_second(ticks.count()) { } /** * \brief converts from ticks to time point * * \param[in] ticks ticks since epoch * \return time_point with a duration equal to the passed time * since the epoch. */ otf2::chrono::time_point operator()(otf2::chrono::ticks ticks) const { if (ticks_per_second == clock::period::den) { return time_point(otf2::chrono::duration(static_cast<int64_t>(ticks.count()))); } // WARNING: Be careful, when changing clock::period::den. // You will have to think about every calculations twice, as there // might be narrowing and rounding anywhere. // We also assumed here, that we have nanoseconds or picoseconds resolution and the // input resolution is about nanoseconds or a few hundred // picoseconds. // These assumptions have to be double checked! const double factor = static_cast<double>(clock::period::den) / ticks_per_second; assert(ticks_per_second <= clock::period::den); assert(ticks.count() < static_cast<uint64_t>(std::numeric_limits<int64_t>::max()) / factor); return time_point(otf2::chrono::duration(static_cast<int64_t>(ticks.count() * factor))); } /** * \brief converts from time points to ticks * * \param[in] t a time point * \return number ticks equal to passed time of the duration of the time * point */ otf2::chrono::ticks operator()(time_point t) const { if (ticks_per_second == clock::period::den) { return ticks( otf2::chrono::duration_cast<otf2::chrono::duration>(t.time_since_epoch()).count()); } const double factor = static_cast<double>(clock::period::den) / ticks_per_second; return ticks( std::ceil(otf2::chrono::duration_cast<otf2::chrono::duration>(t.time_since_epoch()).count() / factor)); } }; /** * \brief converts from std::chrono::timepoint to otf2::chrono::time_point * * \param[in] tp the std::chrono time point * \return the same time point as otf2::chrono::time_point */ template <typename Clock, typename Duration> otf2::chrono::time_point convert_time_point(std::chrono::time_point<Clock, Duration> tp) { return otf2::chrono::time_point( std::chrono::duration_cast<otf2::chrono::clock::duration>(tp.time_since_epoch())); } } // namespace chrono } // namespace otf2 #endif // INCLUDE_OTF2XX_CHRONO_CONVERT_HPP <|endoftext|>
<commit_before>// // Copyright (c) 2013-2014 Christoph Malek // See LICENSE for more information. // #ifndef RJ_CORE_RENDER_HPP #define RJ_CORE_RENDER_HPP #include <SFML/Graphics.hpp> namespace rj { namespace render_utl { // render a single object template<typename Game_Handler, typename Drawable> void ro(Game_Handler& gh, const Drawable& drawable) {gh.render_object(drawable);} // render helpers template<typename Game_Handler, typename T, bool is_drawable> struct ro_helper { ro_helper(Game_Handler& gh, const T& obj) {for(auto& a : obj) ro(gh, a);} }; template<typename Game_Handler, typename T> struct ro_helper<Game_Handler, T, true> { ro_helper(Game_Handler& gh, const T& obj) {ro(gh, obj);} }; } template<typename Game_Handler> class render { Game_Handler& m_gamehandler; public: render(Game_Handler& gh) : m_gamehandler{gh} { } template<typename... Args> void operator()(Args&&... args) {this->rmo(std::forward<Args>(args)...);} template<typename... Args> void rmo(Args&&... args) {this->rmo_impl(std::forward<Args>(args)...);} // render multiple objects impl void rmo_impl() { } template<typename Head, typename... Tail> void rmo_impl(const Head& head, Tail&&... tail) { render_utl::ro_helper<Game_Handler, Head, std::is_base_of<sf::Drawable, Head>::value>{m_gamehandler, head}; rmo_impl(std::forward<Tail>(tail)...); } }; } #endif // RJ_CORE_RENDER_HPP <commit_msg>render: added an std::map<T, E> overload<commit_after>// // Copyright (c) 2013-2014 Christoph Malek // See LICENSE for more information. // #ifndef RJ_CORE_RENDER_HPP #define RJ_CORE_RENDER_HPP #include <SFML/Graphics.hpp> namespace rj { namespace render_utl { // render a single object template<typename Game_Handler, typename Drawable> void ro(Game_Handler& gh, const Drawable& drawable) {gh.render_object(drawable);} // render helpers template<typename Game_Handler, typename T, bool is_drawable> struct ro_helper { ro_helper(Game_Handler& gh, const T& obj) {for(auto& a : obj) ro(gh, a);} }; template<typename Game_Handler, typename T, typename E> struct ro_helper<Game_Handler, std::map<T, E>, false> { ro_helper(Game_Handler& gh, const std::map<T, E>& m) {for(auto& a : m) ro(gh, a.second);} }; template<typename Game_Handler, typename T> struct ro_helper<Game_Handler, T, true> { ro_helper(Game_Handler& gh, const T& obj) {ro(gh, obj);} }; } template<typename Game_Handler> class render { Game_Handler& m_gamehandler; public: render(Game_Handler& gh) : m_gamehandler{gh} { } template<typename... Args> void operator()(Args&&... args) {this->rmo(std::forward<Args>(args)...);} template<typename... Args> void rmo(Args&&... args) {this->rmo_impl(std::forward<Args>(args)...);} // render multiple objects impl void rmo_impl() { } template<typename Head, typename... Tail> void rmo_impl(const Head& head, Tail&&... tail) { render_utl::ro_helper<Game_Handler, Head, std::is_base_of<sf::Drawable, Head>::value>{m_gamehandler, head}; rmo_impl(std::forward<Tail>(tail)...); } }; } #endif // RJ_CORE_RENDER_HPP <|endoftext|>
<commit_before>/** * @file tip/pg/db/transaction.hpp * * @date Jul 14, 2015 * @author zmij */ #ifndef TIP_DB_PG_DETAIL_CONNECTION_LOCK_HPP_ #define TIP_DB_PG_DETAIL_CONNECTION_LOCK_HPP_ #include <memory> #include <functional> #include <atomic> #include <tip/db/pg/common.hpp> #include <tip/db/pg/future_config.hpp> namespace tip { namespace db { namespace pg { class basic_connection; namespace detail { template < typename Mutex, typename TransportType, typename SharedType > struct connection_fsm_def; } /* namespace detail */ /** * @brief RAII transaction object. * * It is created by the library internally when a transaction is started. It * will rollback the transaction if it wasn't explicitly committed. * * @warning A tip::db::pg::transaction object shoudn't be stored and accessed * concurrently. */ class transaction : public std::enable_shared_from_this< transaction > { public: using connection_ptr = ::std::shared_ptr<basic_connection>; using pointer = basic_connection*; using const_pointer = basic_connection const*; using notification_callback = ::std::function< void() >; using atomic_flag = ::std::atomic_flag; public: transaction(connection_ptr); ~transaction(); transaction(transaction const&) = delete; transaction& operator = (transaction const&) = delete; transaction(transaction&&) = delete; transaction& operator = (transaction&&) = delete; //@{ /** Access to underlying connection object */ pointer operator-> () { return connection_.get(); } const_pointer operator-> () const { return connection_.get(); } pointer operator* () { return connection_.get(); } const_pointer operator* () const { return connection_.get(); } //@} dbalias const& alias() const; bool in_transaction() const; void commit_async(notification_callback = notification_callback(), error_callback = error_callback()); template < template<typename> class _Promise = promise > auto commit_future() -> decltype(::std::declval<_Promise<void>>().get_future()) { auto promise = ::std::make_shared<_Promise<void>>(); commit_async( [promise]() { promise->set_value(); }, [promise](error::db_error const& err) { promise->set_exception(::std::make_exception_ptr(err)); } ); return promise->get_future(); } template < template<typename> class _Promise = promise > void commit() { auto future = commit_future(); future.get(); } void rollback_async(notification_callback = notification_callback(), error_callback = error_callback()); template < template<typename> class _Promise = promise > auto rollback_future() -> decltype(::std::declval<_Promise<void>>().get_future()) { auto promise = ::std::make_shared<_Promise<void>>(); rollback_async( [promise]() { promise->set_value(); }, [promise](error::db_error const& err) { promise->set_exception(::std::make_exception_ptr(err)); } ); return promise->get_future(); } template < template<typename> class _Promise = promise > void rollback() { auto future = rollback_future(); future.get(); } void execute(std::string const& query, query_result_callback, query_error_callback); void execute(std::string const& query, type_oid_sequence const& param_types, std::vector< byte > params_buffer, query_result_callback, query_error_callback); private: template < typename Mutex, typename TransportType, typename SharedType > friend struct detail::connection_fsm_def; void mark_done() { finished_.test_and_set(); } void handle_results(resultset, bool, query_result_callback); void handle_query_error(error::query_error const&, query_error_callback); connection_ptr connection_; atomic_flag finished_; }; } /* namespace pg */ } /* namespace db */ } /* namespace tip */ #endif /* TIP_DB_PG_DETAIL_CONNECTION_LOCK_HPP_ */ <commit_msg>Include error definitions for promise calls<commit_after>/** * @file tip/pg/db/transaction.hpp * * @date Jul 14, 2015 * @author zmij */ #ifndef TIP_DB_PG_DETAIL_CONNECTION_LOCK_HPP_ #define TIP_DB_PG_DETAIL_CONNECTION_LOCK_HPP_ #include <memory> #include <functional> #include <atomic> #include <tip/db/pg/common.hpp> #include <tip/db/pg/future_config.hpp> #include <tip/db/pg/error.hpp> namespace tip { namespace db { namespace pg { class basic_connection; namespace detail { template < typename Mutex, typename TransportType, typename SharedType > struct connection_fsm_def; } /* namespace detail */ /** * @brief RAII transaction object. * * It is created by the library internally when a transaction is started. It * will rollback the transaction if it wasn't explicitly committed. * * @warning A tip::db::pg::transaction object shoudn't be stored and accessed * concurrently. */ class transaction : public std::enable_shared_from_this< transaction > { public: using connection_ptr = ::std::shared_ptr<basic_connection>; using pointer = basic_connection*; using const_pointer = basic_connection const*; using notification_callback = ::std::function< void() >; using atomic_flag = ::std::atomic_flag; public: transaction(connection_ptr); ~transaction(); transaction(transaction const&) = delete; transaction& operator = (transaction const&) = delete; transaction(transaction&&) = delete; transaction& operator = (transaction&&) = delete; //@{ /** Access to underlying connection object */ pointer operator-> () { return connection_.get(); } const_pointer operator-> () const { return connection_.get(); } pointer operator* () { return connection_.get(); } const_pointer operator* () const { return connection_.get(); } //@} dbalias const& alias() const; bool in_transaction() const; void commit_async(notification_callback = notification_callback(), error_callback = error_callback()); template < template<typename> class _Promise = promise > auto commit_future() -> decltype(::std::declval<_Promise<void>>().get_future()) { auto promise = ::std::make_shared<_Promise<void>>(); commit_async( [promise]() { promise->set_value(); }, [promise](error::db_error const& err) { promise->set_exception(::std::make_exception_ptr(err)); } ); return promise->get_future(); } template < template<typename> class _Promise = promise > void commit() { auto future = commit_future(); future.get(); } void rollback_async(notification_callback = notification_callback(), error_callback = error_callback()); template < template<typename> class _Promise = promise > auto rollback_future() -> decltype(::std::declval<_Promise<void>>().get_future()) { auto promise = ::std::make_shared<_Promise<void>>(); rollback_async( [promise]() { promise->set_value(); }, [promise](error::db_error const& err) { promise->set_exception(::std::make_exception_ptr(err)); } ); return promise->get_future(); } template < template<typename> class _Promise = promise > void rollback() { auto future = rollback_future(); future.get(); } void execute(std::string const& query, query_result_callback, query_error_callback); void execute(std::string const& query, type_oid_sequence const& param_types, std::vector< byte > params_buffer, query_result_callback, query_error_callback); private: template < typename Mutex, typename TransportType, typename SharedType > friend struct detail::connection_fsm_def; void mark_done() { finished_.test_and_set(); } void handle_results(resultset, bool, query_result_callback); void handle_query_error(error::query_error const&, query_error_callback); connection_ptr connection_; atomic_flag finished_; }; } /* namespace pg */ } /* namespace db */ } /* namespace tip */ #endif /* TIP_DB_PG_DETAIL_CONNECTION_LOCK_HPP_ */ <|endoftext|>
<commit_before>/* * Copyright 2015 Cloudius Systems */ #pragma once #include "core/iostream.hh" #include "core/fstream.hh" #include "types.hh" #include "compress.hh" namespace sstables { class file_writer { output_stream<char> _out; size_t _offset = 0; public: file_writer(file f, size_t buffer_size = 8192) : _out(make_file_output_stream(std::move(f), buffer_size)) {} file_writer(output_stream<char>&& out) : _out(std::move(out)) {} virtual ~file_writer() = default; file_writer(file_writer&&) = default; virtual future<> write(const char* buf, size_t n) { _offset += n; return _out.write(buf, n); } virtual future<> write(const bytes& s) { _offset += s.size(); return _out.write(s); } future<> flush() { return _out.flush(); } future<> close() { return _out.close(); } size_t offset() { return _offset; } }; output_stream<char> make_checksummed_file_output_stream(file f, size_t buffer_size, struct checksum& cinfo, uint32_t& full_file_checksum, bool checksum_file); class checksummed_file_writer : public file_writer { checksum _c; uint32_t _full_checksum; public: checksummed_file_writer(file f, size_t buffer_size = 8192, bool checksum_file = false) : file_writer(make_checksummed_file_output_stream(std::move(f), buffer_size, _c, _full_checksum, checksum_file)) , _c({uint32_t(std::min(size_t(DEFAULT_CHUNK_SIZE), buffer_size))}) , _full_checksum(init_checksum_adler32()) {} // Since we are exposing a reference to _full_checksum, we delete the move // constructor. If it is moved, the reference will refer to the old // location. checksummed_file_writer(checksummed_file_writer&&) = delete; checksummed_file_writer(const checksummed_file_writer&) = default; checksum& finalize_checksum() { return _c; } uint32_t full_checksum() { return _full_checksum; } }; class checksummed_file_data_sink_impl : public data_sink_impl { output_stream<char> _out; struct checksum& _c; uint32_t& _full_checksum; bool _checksum_file; public: checksummed_file_data_sink_impl(file f, size_t buffer_size, struct checksum& c, uint32_t& full_file_checksum, bool checksum_file) : _out(make_file_output_stream(std::move(f), buffer_size)) , _c(c) , _full_checksum(full_file_checksum) , _checksum_file(checksum_file) {} future<> put(net::packet data) { abort(); } virtual future<> put(temporary_buffer<char> buf) override { // bufs will usually be a multiple of chunk size, but this won't be the case for // the last buffer being flushed. if (!_checksum_file) { _full_checksum = checksum_adler32(_full_checksum, buf.begin(), buf.size()); } else { for (size_t offset = 0; offset < buf.size(); offset += _c.chunk_size) { size_t size = std::min(size_t(_c.chunk_size), buf.size() - offset); uint32_t per_chunk_checksum = init_checksum_adler32(); per_chunk_checksum = checksum_adler32(per_chunk_checksum, buf.begin() + offset, size); _full_checksum = checksum_adler32_combine(_full_checksum, per_chunk_checksum, size); _c.checksums.push_back(per_chunk_checksum); } } return _out.write(buf.begin(), buf.size()); } virtual future<> close() { // Nothing to do, because close at the file_stream level will call flush on us. return _out.close(); } }; class checksummed_file_data_sink : public data_sink { public: checksummed_file_data_sink(file f, size_t buffer_size, struct checksum& cinfo, uint32_t& full_file_checksum, bool checksum_file) : data_sink(std::make_unique<checksummed_file_data_sink_impl>(std::move(f), buffer_size, cinfo, full_file_checksum, checksum_file)) {} }; inline output_stream<char> make_checksummed_file_output_stream(file f, size_t buffer_size, struct checksum& cinfo, uint32_t& full_file_checksum, bool checksum_file) { return output_stream<char>(checksummed_file_data_sink(std::move(f), buffer_size, cinfo, full_file_checksum, checksum_file), buffer_size, true); } // compressed_file_data_sink_impl works as a filter for a file output stream, // where the buffer flushed will be compressed and its checksum computed, then // the result passed to a regular output stream. class compressed_file_data_sink_impl : public data_sink_impl { output_stream<char> _out; sstables::compression* _compression_metadata; size_t _pos = 0; public: compressed_file_data_sink_impl(file f, sstables::compression* cm, file_output_stream_options options) : _out(make_file_output_stream(std::move(f), options)) , _compression_metadata(cm) {} future<> put(net::packet data) { abort(); } virtual future<> put(temporary_buffer<char> buf) override { auto output_len = _compression_metadata->compress_max_size(buf.size()); // account space for checksum that goes after compressed data. temporary_buffer<char> compressed(output_len + 4); // compress flushed data. auto len = _compression_metadata->compress(buf.get(), buf.size(), compressed.get_write(), output_len); if (len > output_len) { throw std::runtime_error("possible overflow during compression"); } _compression_metadata->offsets.elements.push_back(_pos); // account compressed data + 32-bit checksum. _pos += len + 4; _compression_metadata->set_compressed_file_length(_pos); // total length of the uncompressed data. _compression_metadata->data_len += buf.size(); // compute 32-bit checksum for compressed data. uint32_t per_chunk_checksum = checksum_adler32(compressed.get(), len); _compression_metadata->update_full_checksum(per_chunk_checksum, len); // write checksum into buffer after compressed data. *unaligned_cast<uint32_t*>(compressed.get_write() + len) = htonl(per_chunk_checksum); compressed.trim(len + 4); auto f = _out.write(compressed.get(), compressed.size()); return f.then([compressed = std::move(compressed)] {}); } virtual future<> close() { return _out.close(); } }; class compressed_file_data_sink : public data_sink { public: compressed_file_data_sink(file f, sstables::compression* cm, file_output_stream_options options) : data_sink(std::make_unique<compressed_file_data_sink_impl>( std::move(f), cm, options)) {} }; static inline output_stream<char> make_compressed_file_output_stream(file f, sstables::compression* cm) { file_output_stream_options options; // buffer of output stream is set to chunk length, because flush must // happen every time a chunk was filled up. options.buffer_size = cm->uncompressed_chunk_length(); return output_stream<char>(compressed_file_data_sink(std::move(f), cm, options), options.buffer_size, true); } } <commit_msg>sstables: fix possible use-after-free<commit_after>/* * Copyright 2015 Cloudius Systems */ #pragma once #include "core/iostream.hh" #include "core/fstream.hh" #include "types.hh" #include "compress.hh" namespace sstables { class file_writer { output_stream<char> _out; size_t _offset = 0; public: file_writer(file f, size_t buffer_size = 8192) : _out(make_file_output_stream(std::move(f), buffer_size)) {} file_writer(output_stream<char>&& out) : _out(std::move(out)) {} virtual ~file_writer() = default; file_writer(file_writer&&) = default; virtual future<> write(const char* buf, size_t n) { _offset += n; return _out.write(buf, n); } virtual future<> write(const bytes& s) { _offset += s.size(); return _out.write(s); } future<> flush() { return _out.flush(); } future<> close() { return _out.close(); } size_t offset() { return _offset; } }; output_stream<char> make_checksummed_file_output_stream(file f, size_t buffer_size, struct checksum& cinfo, uint32_t& full_file_checksum, bool checksum_file); class checksummed_file_writer : public file_writer { checksum _c; uint32_t _full_checksum; public: checksummed_file_writer(file f, size_t buffer_size = 8192, bool checksum_file = false) : file_writer(make_checksummed_file_output_stream(std::move(f), buffer_size, _c, _full_checksum, checksum_file)) , _c({uint32_t(std::min(size_t(DEFAULT_CHUNK_SIZE), buffer_size))}) , _full_checksum(init_checksum_adler32()) {} // Since we are exposing a reference to _full_checksum, we delete the move // constructor. If it is moved, the reference will refer to the old // location. checksummed_file_writer(checksummed_file_writer&&) = delete; checksummed_file_writer(const checksummed_file_writer&) = default; checksum& finalize_checksum() { return _c; } uint32_t full_checksum() { return _full_checksum; } }; class checksummed_file_data_sink_impl : public data_sink_impl { output_stream<char> _out; struct checksum& _c; uint32_t& _full_checksum; bool _checksum_file; public: checksummed_file_data_sink_impl(file f, size_t buffer_size, struct checksum& c, uint32_t& full_file_checksum, bool checksum_file) : _out(make_file_output_stream(std::move(f), buffer_size)) , _c(c) , _full_checksum(full_file_checksum) , _checksum_file(checksum_file) {} future<> put(net::packet data) { abort(); } virtual future<> put(temporary_buffer<char> buf) override { // bufs will usually be a multiple of chunk size, but this won't be the case for // the last buffer being flushed. if (!_checksum_file) { _full_checksum = checksum_adler32(_full_checksum, buf.begin(), buf.size()); } else { for (size_t offset = 0; offset < buf.size(); offset += _c.chunk_size) { size_t size = std::min(size_t(_c.chunk_size), buf.size() - offset); uint32_t per_chunk_checksum = init_checksum_adler32(); per_chunk_checksum = checksum_adler32(per_chunk_checksum, buf.begin() + offset, size); _full_checksum = checksum_adler32_combine(_full_checksum, per_chunk_checksum, size); _c.checksums.push_back(per_chunk_checksum); } } auto f = _out.write(buf.begin(), buf.size()); return f.then([buf = std::move(buf)] {}); } virtual future<> close() { // Nothing to do, because close at the file_stream level will call flush on us. return _out.close(); } }; class checksummed_file_data_sink : public data_sink { public: checksummed_file_data_sink(file f, size_t buffer_size, struct checksum& cinfo, uint32_t& full_file_checksum, bool checksum_file) : data_sink(std::make_unique<checksummed_file_data_sink_impl>(std::move(f), buffer_size, cinfo, full_file_checksum, checksum_file)) {} }; inline output_stream<char> make_checksummed_file_output_stream(file f, size_t buffer_size, struct checksum& cinfo, uint32_t& full_file_checksum, bool checksum_file) { return output_stream<char>(checksummed_file_data_sink(std::move(f), buffer_size, cinfo, full_file_checksum, checksum_file), buffer_size, true); } // compressed_file_data_sink_impl works as a filter for a file output stream, // where the buffer flushed will be compressed and its checksum computed, then // the result passed to a regular output stream. class compressed_file_data_sink_impl : public data_sink_impl { output_stream<char> _out; sstables::compression* _compression_metadata; size_t _pos = 0; public: compressed_file_data_sink_impl(file f, sstables::compression* cm, file_output_stream_options options) : _out(make_file_output_stream(std::move(f), options)) , _compression_metadata(cm) {} future<> put(net::packet data) { abort(); } virtual future<> put(temporary_buffer<char> buf) override { auto output_len = _compression_metadata->compress_max_size(buf.size()); // account space for checksum that goes after compressed data. temporary_buffer<char> compressed(output_len + 4); // compress flushed data. auto len = _compression_metadata->compress(buf.get(), buf.size(), compressed.get_write(), output_len); if (len > output_len) { throw std::runtime_error("possible overflow during compression"); } _compression_metadata->offsets.elements.push_back(_pos); // account compressed data + 32-bit checksum. _pos += len + 4; _compression_metadata->set_compressed_file_length(_pos); // total length of the uncompressed data. _compression_metadata->data_len += buf.size(); // compute 32-bit checksum for compressed data. uint32_t per_chunk_checksum = checksum_adler32(compressed.get(), len); _compression_metadata->update_full_checksum(per_chunk_checksum, len); // write checksum into buffer after compressed data. *unaligned_cast<uint32_t*>(compressed.get_write() + len) = htonl(per_chunk_checksum); compressed.trim(len + 4); auto f = _out.write(compressed.get(), compressed.size()); return f.then([compressed = std::move(compressed)] {}); } virtual future<> close() { return _out.close(); } }; class compressed_file_data_sink : public data_sink { public: compressed_file_data_sink(file f, sstables::compression* cm, file_output_stream_options options) : data_sink(std::make_unique<compressed_file_data_sink_impl>( std::move(f), cm, options)) {} }; static inline output_stream<char> make_compressed_file_output_stream(file f, sstables::compression* cm) { file_output_stream_options options; // buffer of output stream is set to chunk length, because flush must // happen every time a chunk was filled up. options.buffer_size = cm->uncompressed_chunk_length(); return output_stream<char>(compressed_file_data_sink(std::move(f), cm, options), options.buffer_size, true); } } <|endoftext|>
<commit_before>#ifndef VSMC_UTILITY_PARALLE_DISPATCH_HPP #define VSMC_UTILITY_PARALLE_DISPATCH_HPP #include <dispatch/dispatch.h> namespace vsmc { namespace gcd { /// \brief Apple GCD dispatch queue informations /// \ingroup Dispatch class DispatchQueue { public : static DispatchQueue &instance () { static DispatchQueue queue; return queue; } dispatch_queue_t queue () const { return queue_; } void queue (dispatch_queue_t new_queue) { queue_ = new_queue; } private : dispatch_queue_t queue_; DispatchQueue () : queue_( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {} DispatchQueue (const DispatchQueue &); DispatchQueue &operator= (const DispatchQueue &); }; // class DispatchQueue } } // namespace vsmc::gcd #endif // VSMC_UTILITY_PARALLE_DISPATCH_HPP <commit_msg>doc update<commit_after>#ifndef VSMC_UTILITY_PARALLE_DISPATCH_HPP #define VSMC_UTILITY_PARALLE_DISPATCH_HPP #include <dispatch/dispatch.h> namespace vsmc { namespace gcd { /// \brief Dispatch queue used by vSMC /// \ingroup Dispatch class DispatchQueue { public : static DispatchQueue &instance () { static DispatchQueue queue; return queue; } dispatch_queue_t queue () const { return queue_; } void queue (dispatch_queue_t new_queue) { queue_ = new_queue; } private : dispatch_queue_t queue_; DispatchQueue () : queue_( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {} DispatchQueue (const DispatchQueue &); DispatchQueue &operator= (const DispatchQueue &); }; // class DispatchQueue } } // namespace vsmc::gcd #endif // VSMC_UTILITY_PARALLE_DISPATCH_HPP <|endoftext|>
<commit_before>//============================================================================ // include/vsmc/utility/progress.hpp //---------------------------------------------------------------------------- // // vSMC: Scalable Monte Carlo // // This file is distribured under the 2-clauses BSD License. // See LICENSE for details. //============================================================================ #ifndef VSMC_UTILITY_PROGRESS_HPP #define VSMC_UTILITY_PROGRESS_HPP #include <vsmc/internal/common.hpp> #include <vsmc/utility/stop_watch.hpp> #include <iostream> #include <string> #if VSMC_HAS_CXX11LIB_CHRONO && VSMC_HAS_CXX11LIB_THREAD #include <cmath> #include <chrono> #include <thread> #endif namespace vsmc { #if VSMC_HAS_CXX11LIB_CHRONO && VSMC_HAS_CXX11LIB_THREAD namespace internal { struct ProgressThisThread { static void sleep (double s) { double ms = std::fmax(1.0, std::floor(s * 1000)); std::this_thread::sleep_for(std::chrono::milliseconds( static_cast<std::chrono::milliseconds::rep>(ms))); } }; // class ProgressThisThread } // namespace vsmc::internal #endif /// \brief Display a progress bar while algorithm proceed /// \ingroup Progress /// /// \tparam ThreadType Any type that (partially) follows C++11 `std::thread` /// interface. In particular, the following calls shal be supported, /// ~~~{.cpp} /// void (task *) (void *); // A function pointer /// void *context; // A void pointer /// ThreadType *thread_ptr_ = new ThreadType(task, context); /// thread_ptr_->joinable(); /// thread_ptr_->join(); /// delete thread_ptr_; /// ~~~ /// \tparam ThisThread This shall be a class that provides a `sleep` static /// member function that allows the calling thread to sleep for a specified /// time in seconds. A simple implementation using C++11 `sleep_for` is as the /// following, /// ~~~{.cpp} /// struct ThisThread /// { /// static void sleep (double s) /// { /// // Make the interval acurate to milliseconds /// double ms = std::max(1.0, std::floor(s * 1000)); /// std::this_thread::sleep_for(std::chrono::milliseconds( /// static_cast<std::chrono::milliseconds::rep>(ms))); /// } /// }; /// ~~~ /// An implementation using Boost is almost the same except for the namespace /// changing from `std` to `boost`. #if VSMC_HAS_CXX11LIB_CHRONO && VSMC_HAS_CXX11LIB_THREAD template <typename ThreadType = std::thread, typename ThisThread = internal::ProgressThisThread> #else template <typename ThreadType, typename ThisThread> #endif class Progress { public : typedef ThreadType thread_type; /// \brief Construct a Progress with an output stream Progress (std::ostream &os = std::cout) : thread_ptr_(VSMC_NULLPTR), iter_(0), total_(0), interval_(0), length_(60), print_first_(true), in_progress_(false), num_equal_(0), percent_(0), seconds_(0), last_iter_(0), display_progress_(), display_percent_(), display_time_(), display_iter_(), os_(os) {} /// \brief Start to print the progress /// /// \param total Total amount of work represented by an integer, for /// example file size or SMC algorithm total number of iterations /// \param message A (short) discreptive message /// \param interval The sleep interval in seconds /// \param length The length of the progress bar between brackets void start (unsigned total, const std::string &message = std::string(), double interval = 0.1, unsigned length = 60) { iter_ = 0; total_ = total; interval_ = interval; length_ = length; print_first_ = true; in_progress_ = true; message_ = message; watch_.reset(); watch_.start(); fork(); } /// \brief Stop to print the progress /// /// \param finished If true, then it is assumed that all work has been /// finished, and at the end the progress will be shown as `100%` and /// `total/total`, where total is the first parameter of `start`. /// Otherwise, whatever progress has been made will be shown. void stop (bool finished = false) { in_progress_ = false; join(); if (finished && iter_ < total_) iter_ = total_; print_stop_(static_cast<void *>(this)); watch_.stop(); } /// \brief Increment the iteration count void increment (unsigned step = 1) {iter_ += step;} private : StopWatch watch_; thread_type *thread_ptr_; unsigned iter_; unsigned total_; double interval_; unsigned length_; bool print_first_; bool in_progress_; unsigned num_equal_; unsigned percent_; unsigned seconds_; unsigned last_iter_; std::string message_; char display_progress_[128]; char display_percent_[32]; char display_time_[32]; char display_iter_[64]; std::ostream &os_; void fork () { join(); thread_ptr_ = new thread_type(print_start_, static_cast<void *>(this)); } void join () { if (thread_ptr_ != VSMC_NULLPTR) { if (thread_ptr_->joinable()) thread_ptr_->join(); delete thread_ptr_; thread_ptr_ = VSMC_NULLPTR; } } static void print_start_ (void *context) { Progress *ptr = static_cast<Progress *>(context); while (ptr->in_progress_) { print_progress(context); ptr->os_ << '\r' << std::flush; ThisThread::sleep(ptr->interval_); } } static void print_stop_ (void *context) { Progress *ptr = static_cast<Progress *>(context); print_progress(context); ptr->os_ << '\n' << std::flush; } static void print_progress (void *context) { Progress *ptr = static_cast<Progress *>(context); ptr->watch_.stop(); ptr->watch_.start(); const unsigned seconds = static_cast<unsigned>(ptr->watch_.seconds()); const unsigned iter = ptr->iter_; const unsigned total = ptr->total_; const unsigned length = ptr->length_; const unsigned display_iter = iter <= total ? iter : total; unsigned num_equal = total == 0 ? length : static_cast<unsigned>( static_cast<double>(length) * static_cast<double>(display_iter) / static_cast<double>(total)); num_equal = num_equal <= length ? num_equal : length; unsigned percent = total == 0 ? 100 : static_cast<unsigned>( static_cast<double>(100) * static_cast<double>(display_iter) / static_cast<double>(total)); percent = percent <= 100 ? percent : 100; if (ptr->print_first_) { ptr->print_first_ = false; ptr->num_equal_ = num_equal + 1; ptr->percent_ = percent + 1; ptr->seconds_ = seconds + 1; ptr->last_iter_ = iter + 1; } if (length == 0) { char *cstr = ptr->display_progress_; cstr[0] = ' '; cstr[1] = '\0'; } else if (ptr->num_equal_ != num_equal) { ptr->num_equal_ = num_equal; unsigned num_space = length - num_equal; unsigned num_dash = 0; if (num_space > 0) { num_dash = 1; --num_space; } char *cstr = ptr->display_progress_; std::size_t offset = 0; cstr[offset++] = ' '; cstr[offset++] = '['; for (unsigned i = 0; i != num_equal; ++i) cstr[offset++] = '='; for (unsigned i = 0; i != num_dash; ++i) cstr[offset++] = '-'; for (unsigned i = 0; i != num_space; ++i) cstr[offset++] = ' '; cstr[offset++] = ']'; cstr[offset++] = '\0'; } if (ptr->percent_ != percent) { ptr->percent_ = percent; const unsigned num_space = 3 - uint_digit(percent); char *cstr = ptr->display_percent_; std::size_t offset = 0; cstr[offset++] = '['; for (unsigned i = 0; i != num_space; ++i) cstr[offset++] = ' '; uint_to_char(percent, cstr, offset); cstr[offset++] = '%'; cstr[offset++] = ']'; cstr[offset++] = '\0'; } if (ptr->seconds_ != seconds) { ptr->seconds_ = seconds; const unsigned display_second = seconds % 60; const unsigned display_minute = (seconds / 60) % 60; const unsigned display_hour = seconds / 3600; char *cstr = ptr->display_time_; std::size_t offset = 0; cstr[offset++] = '['; if (display_hour > 0) { uint_to_char(display_hour, cstr, offset); cstr[offset++] = ':'; } cstr[offset++] = '0' + static_cast<char>(display_minute / 10); cstr[offset++] = '0' + static_cast<char>(display_minute % 10); cstr[offset++] = ':'; cstr[offset++] = '0' + static_cast<char>(display_second / 10); cstr[offset++] = '0' + static_cast<char>(display_second % 10); cstr[offset++] = ']'; cstr[offset++] = '\0'; } if (ptr->last_iter_ != iter) { ptr->last_iter_ = iter; const unsigned dtotal = uint_digit(total); const unsigned diter = uint_digit(iter); const unsigned num_space = dtotal > diter ? dtotal - diter : 0; char *cstr = ptr->display_iter_; std::size_t offset = 0; cstr[offset++] = '['; for (unsigned i = 0; i < num_space; ++i) cstr[offset++] = ' '; uint_to_char(iter, cstr, offset); cstr[offset++] = '/'; uint_to_char(total, cstr, offset); cstr[offset++] = ']'; cstr[offset++] = '\0'; } ptr->os_ << ptr->display_progress_; ptr->os_ << ptr->display_percent_; ptr->os_ << ptr->display_time_; ptr->os_ << ptr->display_iter_; ptr->os_ << '[' << ptr->message_ << ']'; } template <typename UIntType> static void uint_to_char (UIntType num, char *cstr, std::size_t &offset) { if (num == 0) { cstr[offset++] = '0'; return; } char utmp[32]; std::size_t unum = 0; while (num) { utmp[unum++] = '0' + static_cast<char>(num % 10); num /= 10; } for (std::size_t i = unum; i != 0; --i) cstr[offset++] = utmp[i - 1]; } template <typename UIntType> static unsigned uint_digit (UIntType num) { if (num == 0) return 1; unsigned digit = 0; while (num != 0) { ++digit; num /= 10; } return digit; } }; // class Progress } // namespace vsmc #endif // VSMC_UTILITY_PROGRESS_HPP <commit_msg>only print message if it is not empty<commit_after>//============================================================================ // include/vsmc/utility/progress.hpp //---------------------------------------------------------------------------- // // vSMC: Scalable Monte Carlo // // This file is distribured under the 2-clauses BSD License. // See LICENSE for details. //============================================================================ #ifndef VSMC_UTILITY_PROGRESS_HPP #define VSMC_UTILITY_PROGRESS_HPP #include <vsmc/internal/common.hpp> #include <vsmc/utility/stop_watch.hpp> #include <iostream> #include <string> #if VSMC_HAS_CXX11LIB_CHRONO && VSMC_HAS_CXX11LIB_THREAD #include <cmath> #include <chrono> #include <thread> #endif namespace vsmc { #if VSMC_HAS_CXX11LIB_CHRONO && VSMC_HAS_CXX11LIB_THREAD namespace internal { struct ProgressThisThread { static void sleep (double s) { double ms = std::fmax(1.0, std::floor(s * 1000)); std::this_thread::sleep_for(std::chrono::milliseconds( static_cast<std::chrono::milliseconds::rep>(ms))); } }; // class ProgressThisThread } // namespace vsmc::internal #endif /// \brief Display a progress bar while algorithm proceed /// \ingroup Progress /// /// \tparam ThreadType Any type that (partially) follows C++11 `std::thread` /// interface. In particular, the following calls shal be supported, /// ~~~{.cpp} /// void (task *) (void *); // A function pointer /// void *context; // A void pointer /// ThreadType *thread_ptr_ = new ThreadType(task, context); /// thread_ptr_->joinable(); /// thread_ptr_->join(); /// delete thread_ptr_; /// ~~~ /// \tparam ThisThread This shall be a class that provides a `sleep` static /// member function that allows the calling thread to sleep for a specified /// time in seconds. A simple implementation using C++11 `sleep_for` is as the /// following, /// ~~~{.cpp} /// struct ThisThread /// { /// static void sleep (double s) /// { /// // Make the interval acurate to milliseconds /// double ms = std::max(1.0, std::floor(s * 1000)); /// std::this_thread::sleep_for(std::chrono::milliseconds( /// static_cast<std::chrono::milliseconds::rep>(ms))); /// } /// }; /// ~~~ /// An implementation using Boost is almost the same except for the namespace /// changing from `std` to `boost`. #if VSMC_HAS_CXX11LIB_CHRONO && VSMC_HAS_CXX11LIB_THREAD template <typename ThreadType = std::thread, typename ThisThread = internal::ProgressThisThread> #else template <typename ThreadType, typename ThisThread> #endif class Progress { public : typedef ThreadType thread_type; /// \brief Construct a Progress with an output stream Progress (std::ostream &os = std::cout) : thread_ptr_(VSMC_NULLPTR), iter_(0), total_(0), interval_(0), length_(60), print_first_(true), in_progress_(false), num_equal_(0), percent_(0), seconds_(0), last_iter_(0), display_progress_(), display_percent_(), display_time_(), display_iter_(), os_(os) {} /// \brief Start to print the progress /// /// \param total Total amount of work represented by an integer, for /// example file size or SMC algorithm total number of iterations /// \param message A (short) discreptive message /// \param interval The sleep interval in seconds /// \param length The length of the progress bar between brackets void start (unsigned total, const std::string &message = std::string(), double interval = 0.1, unsigned length = 60) { iter_ = 0; total_ = total; interval_ = interval; length_ = length; print_first_ = true; in_progress_ = true; message_ = message; watch_.reset(); watch_.start(); fork(); } /// \brief Stop to print the progress /// /// \param finished If true, then it is assumed that all work has been /// finished, and at the end the progress will be shown as `100%` and /// `total/total`, where total is the first parameter of `start`. /// Otherwise, whatever progress has been made will be shown. void stop (bool finished = false) { in_progress_ = false; join(); if (finished && iter_ < total_) iter_ = total_; print_stop_(static_cast<void *>(this)); watch_.stop(); } /// \brief Increment the iteration count void increment (unsigned step = 1) {iter_ += step;} private : StopWatch watch_; thread_type *thread_ptr_; unsigned iter_; unsigned total_; double interval_; unsigned length_; bool print_first_; bool in_progress_; unsigned num_equal_; unsigned percent_; unsigned seconds_; unsigned last_iter_; std::string message_; char display_progress_[128]; char display_percent_[32]; char display_time_[32]; char display_iter_[64]; std::ostream &os_; void fork () { join(); thread_ptr_ = new thread_type(print_start_, static_cast<void *>(this)); } void join () { if (thread_ptr_ != VSMC_NULLPTR) { if (thread_ptr_->joinable()) thread_ptr_->join(); delete thread_ptr_; thread_ptr_ = VSMC_NULLPTR; } } static void print_start_ (void *context) { Progress *ptr = static_cast<Progress *>(context); while (ptr->in_progress_) { print_progress(context); ptr->os_ << '\r' << std::flush; ThisThread::sleep(ptr->interval_); } } static void print_stop_ (void *context) { Progress *ptr = static_cast<Progress *>(context); print_progress(context); ptr->os_ << '\n' << std::flush; } static void print_progress (void *context) { Progress *ptr = static_cast<Progress *>(context); ptr->watch_.stop(); ptr->watch_.start(); const unsigned seconds = static_cast<unsigned>(ptr->watch_.seconds()); const unsigned iter = ptr->iter_; const unsigned total = ptr->total_; const unsigned length = ptr->length_; const unsigned display_iter = iter <= total ? iter : total; unsigned num_equal = total == 0 ? length : static_cast<unsigned>( static_cast<double>(length) * static_cast<double>(display_iter) / static_cast<double>(total)); num_equal = num_equal <= length ? num_equal : length; unsigned percent = total == 0 ? 100 : static_cast<unsigned>( static_cast<double>(100) * static_cast<double>(display_iter) / static_cast<double>(total)); percent = percent <= 100 ? percent : 100; if (ptr->print_first_) { ptr->print_first_ = false; ptr->num_equal_ = num_equal + 1; ptr->percent_ = percent + 1; ptr->seconds_ = seconds + 1; ptr->last_iter_ = iter + 1; } if (length == 0) { char *cstr = ptr->display_progress_; cstr[0] = ' '; cstr[1] = '\0'; } else if (ptr->num_equal_ != num_equal) { ptr->num_equal_ = num_equal; unsigned num_space = length - num_equal; unsigned num_dash = 0; if (num_space > 0) { num_dash = 1; --num_space; } char *cstr = ptr->display_progress_; std::size_t offset = 0; cstr[offset++] = ' '; cstr[offset++] = '['; for (unsigned i = 0; i != num_equal; ++i) cstr[offset++] = '='; for (unsigned i = 0; i != num_dash; ++i) cstr[offset++] = '-'; for (unsigned i = 0; i != num_space; ++i) cstr[offset++] = ' '; cstr[offset++] = ']'; cstr[offset++] = '\0'; } if (ptr->percent_ != percent) { ptr->percent_ = percent; const unsigned num_space = 3 - uint_digit(percent); char *cstr = ptr->display_percent_; std::size_t offset = 0; cstr[offset++] = '['; for (unsigned i = 0; i != num_space; ++i) cstr[offset++] = ' '; uint_to_char(percent, cstr, offset); cstr[offset++] = '%'; cstr[offset++] = ']'; cstr[offset++] = '\0'; } if (ptr->seconds_ != seconds) { ptr->seconds_ = seconds; const unsigned display_second = seconds % 60; const unsigned display_minute = (seconds / 60) % 60; const unsigned display_hour = seconds / 3600; char *cstr = ptr->display_time_; std::size_t offset = 0; cstr[offset++] = '['; if (display_hour > 0) { uint_to_char(display_hour, cstr, offset); cstr[offset++] = ':'; } cstr[offset++] = '0' + static_cast<char>(display_minute / 10); cstr[offset++] = '0' + static_cast<char>(display_minute % 10); cstr[offset++] = ':'; cstr[offset++] = '0' + static_cast<char>(display_second / 10); cstr[offset++] = '0' + static_cast<char>(display_second % 10); cstr[offset++] = ']'; cstr[offset++] = '\0'; } if (ptr->last_iter_ != iter) { ptr->last_iter_ = iter; const unsigned dtotal = uint_digit(total); const unsigned diter = uint_digit(iter); const unsigned num_space = dtotal > diter ? dtotal - diter : 0; char *cstr = ptr->display_iter_; std::size_t offset = 0; cstr[offset++] = '['; for (unsigned i = 0; i < num_space; ++i) cstr[offset++] = ' '; uint_to_char(iter, cstr, offset); cstr[offset++] = '/'; uint_to_char(total, cstr, offset); cstr[offset++] = ']'; cstr[offset++] = '\0'; } ptr->os_ << ptr->display_progress_; ptr->os_ << ptr->display_percent_; ptr->os_ << ptr->display_time_; ptr->os_ << ptr->display_iter_; if (ptr->message_.size() != 0) ptr->os_ << '[' << ptr->message_ << ']'; } template <typename UIntType> static void uint_to_char (UIntType num, char *cstr, std::size_t &offset) { if (num == 0) { cstr[offset++] = '0'; return; } char utmp[32]; std::size_t unum = 0; while (num) { utmp[unum++] = '0' + static_cast<char>(num % 10); num /= 10; } for (std::size_t i = unum; i != 0; --i) cstr[offset++] = utmp[i - 1]; } template <typename UIntType> static unsigned uint_digit (UIntType num) { if (num == 0) return 1; unsigned digit = 0; while (num != 0) { ++digit; num /= 10; } return digit; } }; // class Progress } // namespace vsmc #endif // VSMC_UTILITY_PROGRESS_HPP <|endoftext|>