commit
stringlengths
40
40
old_file
stringlengths
2
205
new_file
stringlengths
2
205
old_contents
stringlengths
0
32.9k
new_contents
stringlengths
1
38.9k
subject
stringlengths
3
9.4k
message
stringlengths
6
9.84k
lang
stringlengths
3
13
license
stringclasses
13 values
repos
stringlengths
6
115k
d7b4ad634eb510edbf0e8053ae8c7a68680b9754
mjolnir/core/VelocityVerlet.hpp
mjolnir/core/VelocityVerlet.hpp
#ifndef MJOLNIR_VELOCITY_VERLET_INTEGRATOR #define MJOLNIR_VELOCITY_VERLET_INTEGRATOR #include "ParticleContainer.hpp" #include "ForceField.hpp" namespace mjolnir { template<typename traitsT> class VelocityVerlet { public: typedef traitsT traits_type; typedef typename traits_type::time_type time_type; typedef typename traits_type::coordinate_type coordinate_type; public: VelocityVerlet(const time_type dt, const std::size_t number_of_particles) : dt_(dt), halfdt_(dt * 0.5), halfdt2_(dt * dt * 0.5), acceleration_(number_of_particles) {} ~VelocityVerlet() = default; time_type step(ParticleContainer<traitsT>& pcon, ForceField<traitsT>& ff); private: time_type dt_; //!< dt time_type halfdt_; //!< dt/2 time_type halfdt2_; //!< dt^2/2 std::vector<coordinate_type> acceleration_; }; // at the initial step, acceleration_ must be initialized template<typename traitsT> typename VelocityVerlet<traitsT>::time_type VelocityVerlet<traitsT>::step(const time_type time, ParticleContainer<traitsT>& pcon, ForceField<traitsT>& ff) { // calc r(t+dt) for(auto iter = make_zip(pcon.begin(), acceleration_.begin()); iter != make_zip(pcon.end(), acceleration_.end()); ++iter) { get<0>(iter)->position += dt_ * (get<0>(iter)->velocity) + halfdt2_ * (*get<1>(iter)); get<0>(iter)->velocity += halfdt_ * (*get<1>(iter)); } // calc force(t+dt) ff(pcon); // calc a(t+dt) and v(t+dt) for(auto iter = make_zip(pcon.begin(), acceleration_.begin()); iter != make_zip(pcon.end(), acceleration_.end()); ++iter) { const coordinate_type acc = *get<0>(iter)->force / *get<0>(iter)->mass; *get<1>(iter) = acc; get<0>(iter)->velocity += halfdt_ * acc; } return time + dt; } } // mjolnir #endif /* MJOLNIR_VELOCITY_VERLET_INTEGRATOR */
#ifndef MJOLNIR_VELOCITY_VERLET_INTEGRATOR #define MJOLNIR_VELOCITY_VERLET_INTEGRATOR #include "ParticleContainer.hpp" #include "ForceField.hpp" namespace mjolnir { template<typename traitsT> class VelocityVerlet { public: typedef traitsT traits_type; typedef typename traits_type::time_type time_type; typedef typename traits_type::coordinate_type coordinate_type; public: VelocityVerlet(const time_type dt, const std::size_t number_of_particles) : dt_(dt), halfdt_(dt * 0.5), halfdt2_(dt * dt * 0.5), acceleration_(number_of_particles) {} ~VelocityVerlet() = default; time_type step(ParticleContainer<traitsT>& pcon, ForceField<traitsT>& ff); private: time_type dt_; //!< dt time_type halfdt_; //!< dt/2 time_type halfdt2_; //!< dt^2/2 std::vector<coordinate_type> acceleration_; }; // at the initial step, acceleration_ must be initialized template<typename traitsT> typename VelocityVerlet<traitsT>::time_type VelocityVerlet<traitsT>::step(const time_type time, ParticleContainer<traitsT>& pcon, ForceField<traitsT>& ff) { // calc r(t+dt) for(auto iter = make_zip(pcon.begin(), acceleration_.begin()); iter != make_zip(pcon.end(), acceleration_.end()); ++iter) { get<0>(iter)->position += dt_ * (get<0>(iter)->velocity) + halfdt2_ * (*get<1>(iter)); get<0>(iter)->velocity += halfdt_ * (*get<1>(iter)); } // calc f(t+dt) ff.calc_force(pcon); // calc a(t+dt) and v(t+dt) for(auto iter = make_zip(pcon.begin(), acceleration_.begin()); iter != make_zip(pcon.end(), acceleration_.end()); ++iter) { // consider cash 1/m const coordinate_type acc = *get<0>(iter)->force / *get<0>(iter)->mass; *get<1>(iter) = acc; get<0>(iter)->velocity += halfdt_ * acc; } return time + dt; } } // mjolnir #endif /* MJOLNIR_VELOCITY_VERLET_INTEGRATOR */
fix forcefield call
fix forcefield call
C++
mit
ToruNiina/Mjolnir,ToruNiina/Mjolnir,ToruNiina/Mjolnir
6b7baec67d788a6e35be68470af900c9d349ea5f
test/gsl-lite.t.cpp
test/gsl-lite.t.cpp
// Copyright 2015 by Martin Moene // // gsl-lite is based on GSL: Guidelines Support Library, // https://github.com/microsoft/gsl // // This code is licensed under the MIT License (MIT). // #include "gsl-lite.t.h" lest::tests & specification() { static lest::tests tests; return tests; } CASE( "__cplusplus" ) { EXPECT( __cplusplus > 0L ); } int main( int argc, char * argv[] ) { return lest::run( specification(), argc, argv ); } #if 0 g++ -I../include/gsl -Dgsl_CONFIG_CONTRACT_VIOLATION_THROWS -o gsl-lite.t.exe gsl-lite.t.cpp assert.t.cpp at.t.cpp not_null.t.cpp owner.t.cpp span.t.cpp string_span.t.cpp util.t.cpp && gsl-lite.t.exe --pass g++ -std=c++98 -I../include/gsl -Dgsl_CONFIG_CONTRACT_VIOLATION_THROWS -o gsl-lite.t.exe gsl-lite.t.cpp assert.t.cpp at.t.cpp not_null.t.cpp owner.t.cpp span.t.cpp string_span.t.cpp util.t.cpp && gsl-lite.t.exe --pass g++ -std=c++03 -I../include/gsl -Dgsl_CONFIG_CONTRACT_VIOLATION_THROWS -o gsl-lite.t.exe gsl-lite.t.cpp assert.t.cpp at.t.cpp not_null.t.cpp owner.t.cpp span.t.cpp string_span.t.cpp util.t.cpp && gsl-lite.t.exe --pass g++ -std=c++0x -I../include/gsl -Dgsl_CONFIG_CONTRACT_VIOLATION_THROWS -o gsl-lite.t.exe gsl-lite.t.cpp assert.t.cpp at.t.cpp not_null.t.cpp owner.t.cpp span.t.cpp string_span.t.cpp util.t.cpp && gsl-lite.t.exe --pass g++ -std=c++11 -I../include/gsl -Dgsl_CONFIG_CONTRACT_VIOLATION_THROWS -o gsl-lite.t.exe gsl-lite.t.cpp assert.t.cpp at.t.cpp not_null.t.cpp owner.t.cpp span.t.cpp string_span.t.cpp util.t.cpp && gsl-lite.t.exe --pass g++ -std=c++14 -I../include/gsl -Dgsl_CONFIG_CONTRACT_VIOLATION_THROWS -o gsl-lite.t.exe gsl-lite.t.cpp assert.t.cpp at.t.cpp not_null.t.cpp owner.t.cpp span.t.cpp string_span.t.cpp util.t.cpp && gsl-lite.t.exe --pass cl -EHsc -I../include/gsl -Dgsl_CONFIG_CONTRACT_VIOLATION_THROWS gsl-lite.t.cpp assert.t.cpp at.t.cpp not_null.t.cpp owner.t.cpp span.t.cpp string_span.t.cpp util.t.cpp && gsl-lite.t.exe --pass cl -EHsc -I../include/gsl -Dgsl_CONFIG_CONTRACT_VIOLATION_THROWS -Dgsl_CONFIG_CONFIRMS_COMPILATION_ERRORS gsl-lite.t.cpp assert.t.cpp at.t.cpp not_null.t.cpp owner.t.cpp span.t.cpp string_span.t.cpp util.t.cpp && gsl-lite.t.exe --pass #endif // end of file
// Copyright 2015 by Martin Moene // // gsl-lite is based on GSL: Guidelines Support Library, // https://github.com/microsoft/gsl // // This code is licensed under the MIT License (MIT). // #include "gsl-lite.t.h" #define gsl_PRESENT( x ) \ std::cout << #x << ": " << x << "\n" #define gsl_ABSENT( x ) \ std::cout << #x << ": (undefined)\n" lest::tests & specification() { static lest::tests tests; return tests; } CASE( "__cplusplus" ) { EXPECT( __cplusplus > 0L ); } CASE( "Presence of C++ language features" "[.stdlanguage]" ) { #if gsl_HAVE_AUTO gsl_PRESENT( gsl_HAVE_AUTO ); #else gsl_ABSENT( gsl_HAVE_AUTO ); #endif #if gsl_HAVE_NULLPTR gsl_PRESENT( gsl_HAVE_NULLPTR ); #else gsl_ABSENT( gsl_HAVE_NULLPTR ); #endif #if gsl_HAVE_DEFAULT_FUNCTION_TEMPLATE_ARG gsl_PRESENT( gsl_HAVE_DEFAULT_FUNCTION_TEMPLATE_ARG ); #else gsl_ABSENT( gsl_HAVE_DEFAULT_FUNCTION_TEMPLATE_ARG ); #endif #if gsl_HAVE_ALIAS_TEMPLATE gsl_PRESENT( gsl_HAVE_ALIAS_TEMPLATE ); #else gsl_ABSENT( gsl_HAVE_ALIAS_TEMPLATE ); #endif #if gsl_HAVE_CONSTEXPR_11 gsl_PRESENT( gsl_HAVE_CONSTEXPR_11 ); #else gsl_ABSENT( gsl_HAVE_CONSTEXPR_11 ); #endif #if gsl_HAVE_ENUM_CLASS gsl_PRESENT( gsl_HAVE_ENUM_CLASS ); #else gsl_ABSENT( gsl_HAVE_ENUM_CLASS ); #endif #if gsl_HAVE_EXPLICIT_CONVERSION gsl_PRESENT( gsl_HAVE_EXPLICIT_CONVERSION ); #else gsl_ABSENT( gsl_HAVE_EXPLICIT_CONVERSION ); #endif #if gsl_HAVE_INITIALIZER_LIST gsl_PRESENT( gsl_HAVE_INITIALIZER_LIST ); #else gsl_ABSENT( gsl_HAVE_INITIALIZER_LIST ); #endif #if gsl_HAVE_IS_DEFAULT gsl_PRESENT( gsl_HAVE_IS_DEFAULT ); #else gsl_ABSENT( gsl_HAVE_IS_DEFAULT ); #endif #if gsl_HAVE_IS_DELETE gsl_PRESENT( gsl_HAVE_IS_DELETE ); #else gsl_ABSENT( gsl_HAVE_IS_DELETE ); #endif #if gsl_HAVE_NOEXCEPT gsl_PRESENT( gsl_HAVE_NOEXCEPT ); #else gsl_ABSENT( gsl_HAVE_NOEXCEPT ); #endif } CASE( "Presence of C++ library features" "[.stdlibrary]" ) { #if gsl_HAVE_ARRAY gsl_PRESENT( gsl_HAVE_ARRAY ); #else gsl_ABSENT( gsl_HAVE_ARRAY ); #endif #if gsl_HAVE_CONTAINER_DATA_METHOD gsl_PRESENT( gsl_HAVE_CONTAINER_DATA_METHOD ); #else gsl_ABSENT( gsl_HAVE_CONTAINER_DATA_METHOD ); #endif #if gsl_HAVE_SIZED_TYPES gsl_PRESENT( gsl_HAVE_SIZED_TYPES ); #else gsl_ABSENT( gsl_HAVE_SIZED_TYPES ); #endif #if gsl_HAVE_SHARED_PTR gsl_PRESENT( gsl_HAVE_SHARED_PTR ); #else gsl_ABSENT( gsl_HAVE_SHARED_PTR ); #endif #if gsl_HAVE_UNIQUE_PTR gsl_PRESENT( gsl_HAVE_UNIQUE_PTR ); #else gsl_ABSENT( gsl_HAVE_UNIQUE_PTR ); #endif #if gsl_HAVE_TYPE_TRAITS gsl_PRESENT( gsl_HAVE_TYPE_TRAITS ); #else gsl_ABSENT( gsl_HAVE_TYPE_TRAITS ); #endif #if _HAS_CPP0X gsl_PRESENT( _HAS_CPP0X ); #else gsl_ABSENT( _HAS_CPP0X ); #endif } int main( int argc, char * argv[] ) { return lest::run( specification(), argc, argv ); } #if 0 g++ -I../include/gsl -Dgsl_CONFIG_CONTRACT_VIOLATION_THROWS -o gsl-lite.t.exe gsl-lite.t.cpp assert.t.cpp at.t.cpp not_null.t.cpp owner.t.cpp span.t.cpp string_span.t.cpp util.t.cpp && gsl-lite.t.exe --pass g++ -std=c++98 -I../include/gsl -Dgsl_CONFIG_CONTRACT_VIOLATION_THROWS -o gsl-lite.t.exe gsl-lite.t.cpp assert.t.cpp at.t.cpp not_null.t.cpp owner.t.cpp span.t.cpp string_span.t.cpp util.t.cpp && gsl-lite.t.exe --pass g++ -std=c++03 -I../include/gsl -Dgsl_CONFIG_CONTRACT_VIOLATION_THROWS -o gsl-lite.t.exe gsl-lite.t.cpp assert.t.cpp at.t.cpp not_null.t.cpp owner.t.cpp span.t.cpp string_span.t.cpp util.t.cpp && gsl-lite.t.exe --pass g++ -std=c++0x -I../include/gsl -Dgsl_CONFIG_CONTRACT_VIOLATION_THROWS -o gsl-lite.t.exe gsl-lite.t.cpp assert.t.cpp at.t.cpp not_null.t.cpp owner.t.cpp span.t.cpp string_span.t.cpp util.t.cpp && gsl-lite.t.exe --pass g++ -std=c++11 -I../include/gsl -Dgsl_CONFIG_CONTRACT_VIOLATION_THROWS -o gsl-lite.t.exe gsl-lite.t.cpp assert.t.cpp at.t.cpp not_null.t.cpp owner.t.cpp span.t.cpp string_span.t.cpp util.t.cpp && gsl-lite.t.exe --pass g++ -std=c++14 -I../include/gsl -Dgsl_CONFIG_CONTRACT_VIOLATION_THROWS -o gsl-lite.t.exe gsl-lite.t.cpp assert.t.cpp at.t.cpp not_null.t.cpp owner.t.cpp span.t.cpp string_span.t.cpp util.t.cpp && gsl-lite.t.exe --pass cl -EHsc -I../include/gsl -Dgsl_CONFIG_CONTRACT_VIOLATION_THROWS gsl-lite.t.cpp assert.t.cpp at.t.cpp not_null.t.cpp owner.t.cpp span.t.cpp string_span.t.cpp util.t.cpp && gsl-lite.t.exe --pass cl -EHsc -I../include/gsl -Dgsl_CONFIG_CONTRACT_VIOLATION_THROWS -Dgsl_CONFIG_CONFIRMS_COMPILATION_ERRORS gsl-lite.t.cpp assert.t.cpp at.t.cpp not_null.t.cpp owner.t.cpp span.t.cpp string_span.t.cpp util.t.cpp && gsl-lite.t.exe --pass #endif // end of file
Add tests tagged [.std...] to inspect presence of language/library features
Add tests tagged [.std...] to inspect presence of language/library features
C++
mit
decaf-emu/gsl-lite,martinmoene/gsl-lite,decaf-emu/gsl-lite,martinmoene/gsl-lite,martinmoene/gsl-lite
0c98f038d31c85bdaa26153cc10e79d8fd97f09f
http_client/http_uploader.cc
http_client/http_uploader.cc
// Copyright (c) 2011 The WebM project authors. All Rights Reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. An additional intellectual property rights grant can be found // in the file PATENTS. All contributing project authors may // be found in the AUTHORS file in the root of the source tree. #include "http_client_base.h" #define CURL_STATICLIB #include "curl/curl.h" #include "curl/types.h" #include "curl/easy.h" #include "debug_util.h" #include "file_reader.h" #include "http_uploader.h" // curl error checking/logging macros #define chkcurlform(X, Y) \ do { \ if((X=(Y)) != CURL_FORMADD_OK) { \ DBGLOG(#Y << " failed, val=" << X << "\n"); \ } \ } while (0) namespace WebmLive { class HttpUploaderImpl { public: HttpUploaderImpl(); ~HttpUploaderImpl(); int Init(HttpUploaderSettings*); private: int Final(); int FormUploadInit(); static int ProgressCallback(void* ptr_this, double, double, // we ignore download progress double upload_total, double upload_current); static size_t ReadCallback(char *buffer, size_t size, size_t nitems, void *ptr_this); boost::scoped_ptr<FileReader> file_; CURL* ptr_curl_; DISALLOW_COPY_AND_ASSIGN(HttpUploaderImpl); }; HttpUploader::HttpUploader(): stop_(false) { } HttpUploader::~HttpUploader() { } int HttpUploader::Init(HttpUploaderSettings* ptr_settings) { if (!ptr_settings) { DBGLOG("ERROR: null ptr_settings"); return E_INVALIDARG; } settings_.local_file = ptr_settings->local_file; settings_.target_url = ptr_settings->target_url; settings_.form_variables = ptr_settings->form_variables; settings_.headers = ptr_settings->headers; ptr_uploader_.reset(new (std::nothrow) HttpUploaderImpl()); if (!ptr_uploader_) { DBGLOG("ERROR: can't construct HttpUploaderImpl."); return E_OUTOFMEMORY; } return ptr_uploader_->Init(&settings_); } void HttpUploader::Go() { assert(!upload_thread_); upload_thread_ = boost::shared_ptr<boost::thread>( new boost::thread(boost::bind(&HttpUploader::UploadThread, this))); } void HttpUploader::Stop() { assert(upload_thread_); stop_ = true; upload_thread_->join(); } void HttpUploader::UploadThread() { DBGLOG("running..."); using boost::thread; while (stop_ == false) { printf("."); thread::yield(); } DBGLOG("thread done"); } HttpUploaderImpl::HttpUploaderImpl() : ptr_curl_(NULL) { DBGLOG(""); } HttpUploaderImpl::~HttpUploaderImpl() { Final(); DBGLOG(""); } int HttpUploaderImpl::Init(HttpUploaderSettings* settings) { file_.reset(new (std::nothrow) FileReader()); if (!file_) { DBGLOG("ERROR: can't construct FileReader."); return E_OUTOFMEMORY; } int err = file_->Init(settings->local_file); if (err) { DBGLOG("ERROR: FileReader Init failed err=" << err); return err; } // init libcurl ptr_curl_ = curl_easy_init(); if (!ptr_curl_) { DBGLOG("curl_easy_init failed!"); return E_FAIL; } CURLcode curl_ret = curl_easy_setopt(ptr_curl_, CURLOPT_NOPROGRESS, FALSE); if (curl_ret != CURLE_OK) { DBGLOG("ERROR: curl progress enable failed. curl_ret=" << curl_ret << ":" << curl_easy_strerror(curl_ret)); return E_FAIL; } // set the progress callback function pointer curl_ret = curl_easy_setopt(ptr_curl_, CURLOPT_PROGRESSFUNCTION, ProgressCallback); if (curl_ret != CURLE_OK) { DBGLOG("ERROR: curl progress callback setup failed." << curl_ret << ":" << curl_easy_strerror(curl_ret)); return E_FAIL; } // set progress callback data pointer curl_ret = curl_easy_setopt(ptr_curl_, CURLOPT_PROGRESSDATA, reinterpret_cast<void*>(this)); if (curl_ret != CURLE_OK) { DBGLOG("ERROR: curl progress callback data setup failed." << curl_ret << ":" << curl_easy_strerror(curl_ret)); return E_FAIL; } // enable upload mode curl_ret = curl_easy_setopt(ptr_curl_, CURLOPT_UPLOAD, TRUE); if (curl_ret != CURLE_OK) { DBGLOG("ERROR: curl upload enable failed." << curl_ret << ":" << curl_easy_strerror(curl_ret)); return E_FAIL; } // set read callback function pointer curl_ret = curl_easy_setopt(ptr_curl_, CURLOPT_READFUNCTION, ReadCallback); if (curl_ret != CURLE_OK) { DBGLOG("ERROR: curl read callback setup failed." << curl_ret << ":" << curl_easy_strerror(curl_ret)); return E_FAIL; } // set read callback data pointer curl_ret = curl_easy_setopt(ptr_curl_, CURLOPT_READDATA, reinterpret_cast<void*>(this)); if (curl_ret != CURLE_OK) { DBGLOG("ERROR: curl read callback data setup failed." << curl_ret << ":" << curl_easy_strerror(curl_ret)); return E_FAIL; } return FormUploadInit(); } int HttpUploaderImpl::Final() { if (ptr_curl_) { curl_easy_cleanup(ptr_curl_); ptr_curl_ = NULL; } DBGLOG(""); return ERROR_SUCCESS; } int HttpUploaderImpl::FormUploadInit() { return 0; } int HttpUploaderImpl::ProgressCallback(void* ptr_this, double, double, // we ignore download progress double upload_total, double upload_current) { DBGLOG("total=" << int(upload_total) << " current=" << int(upload_current)); HttpUploaderImpl* ptr_uploader_ = reinterpret_cast<HttpUploaderImpl*>(ptr_this); ptr_uploader_; return 0; } size_t HttpUploaderImpl::ReadCallback(char *buffer, size_t size, size_t nitems, void *ptr_this) { DBGLOG("size=" << size << " nitems=" << nitems); buffer; HttpUploaderImpl* ptr_uploader_ = reinterpret_cast<HttpUploaderImpl*>(ptr_this); ptr_uploader_; return 0; } } // WebmLive
// Copyright (c) 2011 The WebM project authors. All Rights Reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. An additional intellectual property rights grant can be found // in the file PATENTS. All contributing project authors may // be found in the AUTHORS file in the root of the source tree. #include "http_client_base.h" #define CURL_STATICLIB #include "curl/curl.h" #include "curl/types.h" #include "curl/easy.h" #include "debug_util.h" #include "file_reader.h" #include "http_uploader.h" // curl error checking/logging macros #define chkcurlform(X, Y) \ do { \ if((X=(Y)) != CURL_FORMADD_OK) { \ DBGLOG(#Y << " failed, val=" << X << "\n"); \ } \ } while (0) namespace WebmLive { static const char* kContentType = "video/webm"; static const char* kFormName = "webm_file"; static const int kUnknownFileSize = -1; class HttpUploaderImpl { public: HttpUploaderImpl(); ~HttpUploaderImpl(); int Init(HttpUploaderSettings* ptr_settings); private: int Final(); int SetupForm(const HttpUploaderSettings* const); int SetHeaders(HttpUploaderSettings* ptr_settings); static int ProgressCallback(void* ptr_this, double, double, // we ignore download progress double upload_total, double upload_current); static size_t ReadCallback(char *buffer, size_t size, size_t nitems, void *ptr_this); boost::scoped_ptr<FileReader> file_; CURL* ptr_curl_; DISALLOW_COPY_AND_ASSIGN(HttpUploaderImpl); }; HttpUploader::HttpUploader(): stop_(false) { } HttpUploader::~HttpUploader() { } int HttpUploader::Init(HttpUploaderSettings* ptr_settings) { if (!ptr_settings) { DBGLOG("ERROR: null ptr_settings"); return E_INVALIDARG; } settings_.local_file = ptr_settings->local_file; settings_.target_url = ptr_settings->target_url; settings_.form_variables = ptr_settings->form_variables; settings_.headers = ptr_settings->headers; ptr_uploader_.reset(new (std::nothrow) HttpUploaderImpl()); if (!ptr_uploader_) { DBGLOG("ERROR: can't construct HttpUploaderImpl."); return E_OUTOFMEMORY; } return ptr_uploader_->Init(&settings_); } void HttpUploader::Go() { assert(!upload_thread_); upload_thread_ = boost::shared_ptr<boost::thread>( new boost::thread(boost::bind(&HttpUploader::UploadThread, this))); } void HttpUploader::Stop() { assert(upload_thread_); stop_ = true; upload_thread_->join(); } void HttpUploader::UploadThread() { DBGLOG("running..."); using boost::thread; while (stop_ == false) { printf("."); thread::yield(); } DBGLOG("thread done"); } HttpUploaderImpl::HttpUploaderImpl() : ptr_curl_(NULL) { DBGLOG(""); } HttpUploaderImpl::~HttpUploaderImpl() { Final(); DBGLOG(""); } int HttpUploaderImpl::Init(HttpUploaderSettings* settings) { file_.reset(new (std::nothrow) FileReader()); if (!file_) { DBGLOG("ERROR: can't construct FileReader."); return E_OUTOFMEMORY; } int err = file_->Init(settings->local_file); if (err) { DBGLOG("ERROR: FileReader Init failed err=" << err); return err; } // init libcurl ptr_curl_ = curl_easy_init(); if (!ptr_curl_) { DBGLOG("curl_easy_init failed!"); return E_FAIL; } CURLcode curl_ret = curl_easy_setopt(ptr_curl_, CURLOPT_NOPROGRESS, FALSE); if (curl_ret != CURLE_OK) { DBGLOG("ERROR: curl progress enable failed. curl_ret=" << curl_ret << ":" << curl_easy_strerror(curl_ret)); return E_FAIL; } // set the progress callback function pointer curl_ret = curl_easy_setopt(ptr_curl_, CURLOPT_PROGRESSFUNCTION, ProgressCallback); if (curl_ret != CURLE_OK) { DBGLOG("ERROR: curl progress callback setup failed." << curl_ret << ":" << curl_easy_strerror(curl_ret)); return E_FAIL; } // set progress callback data pointer curl_ret = curl_easy_setopt(ptr_curl_, CURLOPT_PROGRESSDATA, reinterpret_cast<void*>(this)); if (curl_ret != CURLE_OK) { DBGLOG("ERROR: curl progress callback data setup failed." << curl_ret << ":" << curl_easy_strerror(curl_ret)); return E_FAIL; } // enable upload mode curl_ret = curl_easy_setopt(ptr_curl_, CURLOPT_UPLOAD, TRUE); if (curl_ret != CURLE_OK) { DBGLOG("ERROR: curl upload enable failed." << curl_ret << ":" << curl_easy_strerror(curl_ret)); return E_FAIL; } // set read callback function pointer curl_ret = curl_easy_setopt(ptr_curl_, CURLOPT_READFUNCTION, ReadCallback); if (curl_ret != CURLE_OK) { DBGLOG("ERROR: curl read callback setup failed." << curl_ret << ":" << curl_easy_strerror(curl_ret)); return E_FAIL; } // set read callback data pointer curl_ret = curl_easy_setopt(ptr_curl_, CURLOPT_READDATA, reinterpret_cast<void*>(this)); if (curl_ret != CURLE_OK) { DBGLOG("ERROR: curl read callback data setup failed." << curl_ret << ":" << curl_easy_strerror(curl_ret)); return E_FAIL; } // pass user form variables to libcurl err = SetupForm(settings); if (err) { DBGLOG("ERROR: unable to set form variables, err=" << err); return err; } return ERROR_SUCCESS; } int HttpUploaderImpl::Final() { if (ptr_curl_) { curl_easy_cleanup(ptr_curl_); ptr_curl_ = NULL; } DBGLOG(""); return ERROR_SUCCESS; } int HttpUploaderImpl::SetupForm(const HttpUploaderSettings* const p) { CURLFORMcode err; typedef std::map<std::string, std::string> StringMap; StringMap::const_iterator var_iter = p->form_variables.begin(); curl_httppost* ptr_form_items = NULL; curl_httppost* ptr_last_form_item = NULL; // add user form variables for (; var_iter != p->form_variables.end(); ++var_iter) { err = curl_formadd(&ptr_form_items, &ptr_last_form_item, CURLFORM_COPYNAME, var_iter->first.c_str(), CURLFORM_COPYCONTENTS, var_iter->second.c_str(), CURLFORM_END); if (err != CURL_FORMADD_OK) { DBGLOG("ERROR: curl_formadd failed err=" << err); return E_FAIL; } } // add file data err = curl_formadd(&ptr_form_items, &ptr_last_form_item, CURLFORM_COPYNAME, kFormName, // note that |CURLFORM_STREAM| relies on the callback // set in the call to curl_easy_setopt with // |CURLOPT_READFUNCTION| specified CURLFORM_STREAM, reinterpret_cast<void*>(this), CURLFORM_FILENAME, p->local_file.c_str(), CURLFORM_CONTENTSLENGTH, kUnknownFileSize, CURLFORM_CONTENTTYPE, kContentType, CURLFORM_END); if (err != CURL_FORMADD_OK) { DBGLOG("ERROR: curl_formadd CURLFORM_FILE failed err=" << err); return E_FAIL; } return ERROR_SUCCESS; } int HttpUploaderImpl::ProgressCallback(void* ptr_this, double, double, // we ignore download progress double upload_total, double upload_current) { DBGLOG("total=" << int(upload_total) << " current=" << int(upload_current)); HttpUploaderImpl* ptr_uploader_ = reinterpret_cast<HttpUploaderImpl*>(ptr_this); ptr_uploader_; return 0; } size_t HttpUploaderImpl::ReadCallback(char *buffer, size_t size, size_t nitems, void *ptr_this) { DBGLOG("size=" << size << " nitems=" << nitems); HttpUploaderImpl* ptr_uploader_ = reinterpret_cast<HttpUploaderImpl*>(ptr_this); uint64 available = ptr_uploader_->file_->GetBytesAvailable(); size_t requested = size * nitems; if (requested > available && available > 0) { requested = static_cast<size_t>(available); } size_t bytes_read = 0; if (available > 0) { int err = ptr_uploader_->file_->Read(requested, buffer, &bytes_read); if (err) { DBGLOG("FileReader out of data!"); } } return bytes_read; } } // WebmLive
complete curl init
http_uploader: complete curl init Add constants for form setup, and finish form initialization code. We should be good to call curl_easy_perform now; unfortunately this won't build against the libcurl currently in-tree because we must upgrade to curl v7.18.2 or higher in order to use CURLFORM_STREAM. We must use CURLFORM_STREAM to upload the file as part of a form-- to avoid this we would have to send HTTP PUT instead of HTTP POST with form data. Beyond that we need: - some heuristic for distinguishing between catching up to the file's write pointer and file creation completion in FileReader::Read - code for handling situations where FileReader::Read cannot return any data Change-Id: Ib63b6431fc66e87f35cb27c7073ec20da527ccc7
C++
bsd-3-clause
ericmckean/webm.webmlive,Maria1099/webm.webmlive,abwiz0086/webm.webmlive,kim42083/webm.webmlive,webmproject/webmlive,felipebetancur/webmlive,matanbs/webm.webmlive,abwiz0086/webm.webmlive,iniwf/webm.webmlive,kleopatra999/webm.webmlive,ericmckean/webm.webmlive,felipebetancur/webmlive,reimaginemedia/webm.webmlive,matanbs/webm.webmlive,Acidburn0zzz/webm.webmlive,webmproject/webmlive,altogother/webm.webmlive,matanbs/webm.webmlive,reimaginemedia/webm.webmlive,altogother/webm.webmlive,felipebetancur/webmlive,webmproject/webmlive,iniwf/webm.webmlive,reimaginemedia/webm.webmlive,Acidburn0zzz/webm.webmlive,abwiz0086/webm.webmlive,kim42083/webm.webmlive,gshORTON/webm.webmlive,altogother/webm.webmlive,gshORTON/webm.webmlive,kalli123/webm.webmlive,altogother/webm.webmlive,kim42083/webm.webmlive,Acidburn0zzz/webm.webmlive,kalli123/webm.webmlive,Maria1099/webm.webmlive,kleopatra999/webm.webmlive,Suvarna1488/webm.webmlive,iniwf/webm.webmlive,reimaginemedia/webm.webmlive,kleopatra999/webm.webmlive,kleopatra999/webm.webmlive,felipebetancur/webmlive,Acidburn0zzz/webm.webmlive,matanbs/webm.webmlive,kim42083/webm.webmlive,webmproject/webmlive,abwiz0086/webm.webmlive,Maria1099/webm.webmlive,ericmckean/webm.webmlive,ericmckean/webm.webmlive,gshORTON/webm.webmlive,Maria1099/webm.webmlive,kalli123/webm.webmlive,webmproject/webmlive,Suvarna1488/webm.webmlive,Suvarna1488/webm.webmlive,gshORTON/webm.webmlive,felipebetancur/webmlive,kalli123/webm.webmlive,iniwf/webm.webmlive,Suvarna1488/webm.webmlive
9b336f512804c48b6aa5a62434791481a333c903
cpp/example/scaling.cc
cpp/example/scaling.cc
#include <cap/energy_storage_device.h> #include <cap/mp_values.h> #include <cap/default_inspector.h> #include <cap/supercapacitor.h> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/info_parser.hpp> #include <boost/mpi/environment.hpp> #include <boost/mpi/timer.hpp> #include <iostream> int main(int argc, char *argv[]) { boost::mpi::environment env(argc, argv); boost::mpi::communicator comm; boost::mpi::timer timer; if (comm.rank() == 0) std::cout << "Number of processors: " << comm.size() << std::endl; // Parse input file boost::property_tree::ptree device_database; boost::property_tree::info_parser::read_info("super_capacitor.info", device_database); std::shared_ptr<cap::EnergyStorageDevice> device = cap::EnergyStorageDevice::build(device_database, comm); unsigned int const n_time_steps = 10; double const time_step = 0.1; double const charge_voltage = 2.1; for (unsigned int i = 0; i < n_time_steps; ++i) device->evolve_one_time_step_constant_voltage(time_step, charge_voltage); if (comm.rank() == 0) { cap::DefaultInspector inspector; inspector.inspect(device.get()); auto data = inspector.get_data(); std::cout << "n dofs: " << data["n_dofs"] << std::endl; std::cout << "Elapsed time: " << timer.elapsed() << std::endl; } cap::SuperCapacitorInspector<2> supercap_inspector; supercap_inspector.inspect(device.get()); return 0; }
#include <cap/energy_storage_device.h> #include <cap/mp_values.h> #include <cap/default_inspector.h> #include <cap/supercapacitor.h> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/info_parser.hpp> #include <boost/mpi/environment.hpp> #include <boost/mpi/timer.hpp> #include <iostream> int main(int argc, char *argv[]) { boost::mpi::environment env(argc, argv); boost::mpi::communicator comm; boost::mpi::timer timer; if (comm.rank() == 0) std::cout << "Number of processors: " << comm.size() << std::endl; // Parse input file boost::property_tree::ptree device_database; boost::property_tree::info_parser::read_info("super_capacitor.info", device_database); std::shared_ptr<cap::EnergyStorageDevice> device = cap::EnergyStorageDevice::build(device_database, comm); unsigned int const n_time_steps = 10; double const time_step = 0.1; double const charge_voltage = 2.1; for (unsigned int i = 0; i < n_time_steps; ++i) device->evolve_one_time_step_constant_voltage(time_step, charge_voltage); if (comm.rank() == 0) { cap::DefaultInspector inspector; inspector.inspect(device.get()); auto data = inspector.get_data(); std::cout << "n dofs: " << data["n_dofs"] << std::endl; std::cout << "Elapsed time: " << timer.elapsed() << std::endl; } if (device_database.get<int>("dim") == 2) { cap::SuperCapacitorInspector<2> supercap_inspector; supercap_inspector.inspect(device.get()); } else { cap::SuperCapacitorInspector<3> supercap_inspector; supercap_inspector.inspect(device.get()); } return 0; }
Improve scaling example.
Improve scaling example.
C++
bsd-3-clause
Rombur/Cap,Rombur/Cap,ORNL-CEES/Cap,Rombur/Cap,dalg24/Cap,dalg24/Cap,ORNL-CEES/Cap,dalg24/Cap,ORNL-CEES/Cap
f67ecd1c352dce3012a94698ff6398e478e7a677
cpplib/graph/graph.hpp
cpplib/graph/graph.hpp
#pragma once #include <algorithm> #include <type_traits> #include <vector> #include "maths.hpp" #include "range/ranges.hpp" #include <iostream> template<typename T = long long, size_t MASK = 0> class Graph { public: using EdgesList = std::vector<size_t>; enum Type { Weighted = 1 }; template<size_t MASK> struct is_weighted { static constexpr bool value = (MASK & Type::Weighted) != 0; }; class Edge { public: explicit Edge(const std::vector<size_t>& from, const std::vector<size_t>& to, const std::vector<T>& weight, const size_t index) : from_(from), to_(to), weight_(weight), index_(index) {} size_t from() const { return from_[index_]; } size_t to() const { return to_[index_]; } template<const size_t Mask = MASK, typename std::enable_if<is_weighted<Mask>::value>::type* = nullptr> size_t weight() const { return weight_[index_]; } size_t id() const { return index_; } void set_index(const size_t index) { index_ = index; } Edge reversed() const { return Edge(to_, from_, weight_, index_); } private: const std::vector<size_t>& from_; const std::vector<size_t>& to_; const std::vector<T>& weight_; size_t index_; }; template<typename Range> class EdgesHolder { public: template<typename BaseConstIterator> class EdgeConstIterator : public BaseConstIterator { public: using value_type = Edge; using pointer = const value_type*; using const_reference = const value_type&; explicit EdgeConstIterator(BaseConstIterator it, const std::vector<size_t>& from, const std::vector<size_t>& to, const std::vector<T>& weight) : BaseConstIterator(it), cur_edge_(from, to, weight, 0) {} pointer operator->() { return addressof(operator*()); } const_reference operator*() { const typename BaseConstIterator::value_type index = this->BaseConstIterator::operator*(); cur_edge_.set_index(index); return cur_edge_; } private: Edge cur_edge_; }; using const_iterator = EdgeConstIterator<typename Range::const_iterator>; using value_type = typename const_iterator::value_type; explicit EdgesHolder(const Range& range, const std::vector<size_t>& from, const std::vector<size_t>& to, const std::vector<T>& weight) : begin_(range.begin()), end_(range.end()), from_(from), to_(to), weight_(weight) {} const_iterator begin() const { return const_iterator(begin_, from_, to_, weight_); } const_iterator end() const { return const_iterator(end_, from_, to_, weight_); } private: const typename Range::const_iterator begin_; const typename Range::const_iterator end_; const std::vector<size_t>& from_; const std::vector<size_t>& to_; const std::vector<T>& weight_; }; Graph() = default; virtual ~Graph() { clear(); } void init(const size_t vertex_count) { clear(); vertex_count_ = vertex_count; edges_.resize(vertex_count_); } IntegerRange<size_t> vertices() const { return range(vertex_count_); } IntegerRange<size_t>::const_iterator begin() const { return vertices().begin(); } IntegerRange<size_t>::const_iterator end() const { return vertices().end(); } EdgesHolder<EdgesList> edges(const size_t vertex) const { return EdgesHolder<EdgesList>(edges_[vertex], from_, to_, weight_); } EdgesHolder<IntegerRange<size_t>> edges() const { return EdgesHolder<IntegerRange<size_t>>(range(from_.size()), from_, to_, weight_); } void clear(); size_t from(const size_t index) const { return from_[index]; } size_t to(const size_t index) const { return to_[index]; } template<const size_t Mask = MASK, typename std::enable_if<is_weighted<Mask>::value>::type* = nullptr> T weight(const size_t index) const { return weight_[index]; } template<const size_t Mask = MASK, typename std::enable_if<!is_weighted<Mask>::value>::type* = nullptr> void add_directed_edge(const size_t from, const size_t to) { push_edge(from, to); } template<const size_t Mask = MASK, typename std::enable_if<is_weighted<Mask>::value>::type* = nullptr> void add_directed_edge(const size_t from, const size_t to, const T weight) { weight_.emplace_back(weight); push_edge(from, to); } template<const size_t Mask = MASK, typename std::enable_if<!is_weighted<Mask>::value>::type* = nullptr> void add_directed_edge(const Edge& edge) { add_directed_edge(edge.from(), edge.to()); } template<const size_t Mask = MASK, typename std::enable_if<is_weighted<Mask>::value>::type* = nullptr> void add_directed_edge(const Edge& edge) { add_directed_edge(edge.from(), edge.to(), edge.weight()); } bool is_sparse() const { return vertex_count_ == 0 || sqr(static_cast<ll>(vertex_count_)) >= (edges_count_ << 4); } size_t find_vertex_with_max_degree() const; protected: void push_edge(const size_t from, const size_t to) { const size_t edge_id = from_.size(); from_.emplace_back(from); to_.emplace_back(to); edges_[from].emplace_back(edge_id); } std::vector<EdgesList> edges_; std::vector<size_t> from_; std::vector<size_t> to_; std::vector<T> weight_; size_t vertex_count_; }; template<typename T, size_t MASK> void Graph<T, MASK>::clear() { vertex_count_ = 0; edges_.clear(); from_.clear(); to_.clear(); weight_.clear(); } template<typename T, size_t MASK> size_t Graph<T, MASK>::find_vertex_with_max_degree() const { const auto iter = std::max_element(edges_.begin(), edges_.end(), [](const EdgesList& lhs, const EdgesList& rhs) { return lhs.size() < rhs.size(); }); return static_cast<size_t>(std::distance(edges_.begin(), iter)); }
#pragma once #include <algorithm> #include <type_traits> #include <vector> #include "maths.hpp" #include "range/ranges.hpp" #include <iostream> template<typename T = long long, size_t MASK = 0> class Graph { public: using EdgesList = std::vector<size_t>; enum Type { Weighted = 1 }; template<size_t MASK> struct is_weighted { static constexpr bool value = (MASK & Type::Weighted) != 0; }; class Edge { public: explicit Edge(const std::vector<size_t>& from, const std::vector<size_t>& to, const std::vector<T>& weight, const size_t index) : from_(from), to_(to), weight_(weight), index_(index) {} size_t from() const { return from_[index_]; } size_t to() const { return to_[index_]; } template<const size_t Mask = MASK, typename std::enable_if<is_weighted<Mask>::value>::type* = nullptr> size_t weight() const { return weight_[index_]; } size_t id() const { return index_; } void set_index(const size_t index) { index_ = index; } Edge reversed() const { return Edge(to_, from_, weight_, index_); } private: const std::vector<size_t>& from_; const std::vector<size_t>& to_; const std::vector<T>& weight_; size_t index_; }; template<typename Range> class EdgesHolder { public: template<typename BaseConstIterator> class EdgeConstIterator : public BaseConstIterator { public: using value_type = Edge; using pointer = const value_type*; using const_reference = const value_type&; explicit EdgeConstIterator(BaseConstIterator it, const std::vector<size_t>& from, const std::vector<size_t>& to, const std::vector<T>& weight) : BaseConstIterator(it), cur_edge_(from, to, weight, 0) {} pointer operator->() { return addressof(operator*()); } const_reference operator*() { const typename BaseConstIterator::value_type index = this->BaseConstIterator::operator*(); cur_edge_.set_index(index); return cur_edge_; } private: Edge cur_edge_; }; using const_iterator = EdgeConstIterator<typename Range::const_iterator>; using value_type = typename const_iterator::value_type; explicit EdgesHolder(const Range& range, const std::vector<size_t>& from, const std::vector<size_t>& to, const std::vector<T>& weight) : begin_(range.begin(), from, to, weight), end_(range.end(), from, to, weight) {} const_iterator begin() const { return begin_; } const_iterator end() const { return end_; } private: const const_iterator begin_; const const_iterator end_; }; Graph() = default; virtual ~Graph() { clear(); } void init(const size_t vertex_count) { clear(); vertex_count_ = vertex_count; edges_.resize(vertex_count_); } IntegerRange<size_t> vertices() const { return range(vertex_count_); } IntegerRange<size_t>::const_iterator begin() const { return vertices().begin(); } IntegerRange<size_t>::const_iterator end() const { return vertices().end(); } EdgesHolder<EdgesList> edges(const size_t vertex) const { return EdgesHolder<EdgesList>(edges_[vertex], from_, to_, weight_); } EdgesHolder<IntegerRange<size_t>> edges() const { return EdgesHolder<IntegerRange<size_t>>(range(from_.size()), from_, to_, weight_); } void clear(); size_t from(const size_t index) const { return from_[index]; } size_t to(const size_t index) const { return to_[index]; } template<const size_t Mask = MASK, typename std::enable_if<is_weighted<Mask>::value>::type* = nullptr> T weight(const size_t index) const { return weight_[index]; } template<const size_t Mask = MASK, typename std::enable_if<!is_weighted<Mask>::value>::type* = nullptr> void add_directed_edge(const size_t from, const size_t to) { push_edge(from, to); } template<const size_t Mask = MASK, typename std::enable_if<is_weighted<Mask>::value>::type* = nullptr> void add_directed_edge(const size_t from, const size_t to, const T weight) { weight_.emplace_back(weight); push_edge(from, to); } template<const size_t Mask = MASK, typename std::enable_if<!is_weighted<Mask>::value>::type* = nullptr> void add_directed_edge(const Edge& edge) { add_directed_edge(edge.from(), edge.to()); } template<const size_t Mask = MASK, typename std::enable_if<is_weighted<Mask>::value>::type* = nullptr> void add_directed_edge(const Edge& edge) { add_directed_edge(edge.from(), edge.to(), edge.weight()); } bool is_sparse() const { return vertex_count_ == 0 || sqr(static_cast<ll>(vertex_count_)) >= (edges_count_ << 4); } size_t find_vertex_with_max_degree() const; protected: void push_edge(const size_t from, const size_t to) { const size_t edge_id = from_.size(); from_.emplace_back(from); to_.emplace_back(to); edges_[from].emplace_back(edge_id); } std::vector<EdgesList> edges_; std::vector<size_t> from_; std::vector<size_t> to_; std::vector<T> weight_; size_t vertex_count_; }; template<typename T, size_t MASK> void Graph<T, MASK>::clear() { vertex_count_ = 0; edges_.clear(); from_.clear(); to_.clear(); weight_.clear(); } template<typename T, size_t MASK> size_t Graph<T, MASK>::find_vertex_with_max_degree() const { const auto iter = std::max_element(edges_.begin(), edges_.end(), [](const EdgesList& lhs, const EdgesList& rhs) { return lhs.size() < rhs.size(); }); return static_cast<size_t>(std::distance(edges_.begin(), iter)); }
Fix EdgesHolder iterators: store only begin_ and end_ iterators, not all other fields.
Fix EdgesHolder iterators: store only begin_ and end_ iterators, not all other fields.
C++
mit
agul/algolib,agul/algolib
fb44ca086591d427c47526373531adebd3e680e6
okui/src/shaders/TextureShader.cpp
okui/src/shaders/TextureShader.cpp
#include "onair/okui/shaders/TextureShader.h" #include "onair/okui/Texture.h" #include "onair/okui/shapes/Rectangle.h" namespace onair { namespace okui { namespace shaders { TextureShader::TextureShader(const char* fragmentShader) { opengl::Shader vsh(ONAIR_OKUI_VERTEX_SHADER_HEADER R"( ATTRIBUTE_IN vec2 positionAttrib; ATTRIBUTE_IN vec4 colorAttrib; ATTRIBUTE_IN vec4 curveAttrib; ATTRIBUTE_IN vec2 textureCoordAttrib; VARYING_OUT vec4 color; VARYING_OUT vec4 curve; VARYING_OUT vec2 textureCoord; void main() { color = colorAttrib; curve = curveAttrib; textureCoord = textureCoordAttrib; gl_Position = vec4(positionAttrib, 0.0, 1.0); } )", opengl::Shader::kVertexShader); opengl::Shader fsh(fragmentShader ? fragmentShader : ONAIR_OKUI_FRAGMENT_SHADER_HEADER R"( VARYING_IN vec4 color; VARYING_IN vec4 curve; VARYING_IN vec2 textureCoord; uniform sampler2D textureSampler; void main() { float alphaMultiplier = 1.0; if (curve.z > 1.5) { if (abs(curve.s) >= 0.5 || abs(curve.t) >= 0.5) { discard; } float dist = sqrt(curve.s * curve.s + curve.t * curve.t); float aa = curve.w; if (dist > 0.5 + 0.5 * aa) { discard; } else if (dist > 0.5 - 0.5 * aa) { alphaMultiplier = 1.0 - (dist - (0.5 - 0.5 * aa)) / aa; } } else if (curve.z != 0.0) { float dist = pow(curve.s, 2.0) - curve.t; float aa = curve.w; dist -= curve.z * aa; if (dist < 0.0 != curve.z < 0.0) { float x = abs(dist) / (2.0 * aa); if (x < 1.0) { alphaMultiplier = (1.0 - x); } else { discard; } } } COLOR_OUT = SAMPLE(textureSampler, textureCoord) * vec4(color.rgb, color.a * alphaMultiplier); } )", opengl::Shader::kFragmentShader); _program.attachShaders(vsh, fsh); _program.link(); _program.use(); _program.uniform("texture") = 0; if (!_program.error().empty()) { ONAIR_LOGF_ERROR("error creating shader: %s", _program.error().c_str()); return; } auto stride = reinterpret_cast<char*>(&_vertices[1]) - reinterpret_cast<char*>(&_vertices[0]); _vertexArrayBuffer.setAttribute(_program.attribute("positionAttrib"), 2, GL_FLOAT, GL_FALSE, stride, offsetof(Vertex, x)); _vertexArrayBuffer.setAttribute(_program.attribute("colorAttrib"), 4, GL_FLOAT, GL_FALSE, stride, offsetof(Vertex, r)); _vertexArrayBuffer.setAttribute(_program.attribute("curveAttrib"), 4, GL_FLOAT, GL_FALSE, stride, offsetof(Vertex, cu)); _vertexArrayBuffer.setAttribute(_program.attribute("textureCoordAttrib"), 2, GL_FLOAT, GL_FALSE, stride, offsetof(Vertex, s)); ONAIR_OKUI_GL_ERROR_CHECK(); } void TextureShader::setColor(const Color& color) { _triangle.a.r = _triangle.b.r = _triangle.c.r = color.r; _triangle.a.g = _triangle.b.g = _triangle.c.g = color.g; _triangle.a.b = _triangle.b.b = _triangle.c.b = color.b; _triangle.a.a = _triangle.b.a = _triangle.c.a = color.a; } void TextureShader::setTexture(GLuint id, double x, double y, double w, double h, const AffineTransformation& texCoordTransform) { if (_texture != id) { flush(); } _texture = id; _transformation.transform(x, y, &_textureX1, &_textureY1); double x2, y2; _transformation.transform(x + w, y + h, &x2, &y2); _textureWidth = x2 - _textureX1; _textureHeight = y2 - _textureY1; _texCoordTransform = texCoordTransform; } void TextureShader::drawScaledFill(const Texture& texture, Rectangle<double> area, double r) { setTexture(texture.id(), area.scaledFill(texture.aspectRatio()), AffineTransformation{0.5, 0.5, -0.5, -0.5, 1.0, 1.0, -r}); okui::shapes::Rectangle(area).rotate(r).draw(this); } void TextureShader::drawScaledFit(const Texture& texture, Rectangle<double> area, double r) { setTexture(texture.id(), area.scaledFit(texture.aspectRatio()), AffineTransformation{0.5, 0.5, -0.5, -0.5, 1.0, 1.0, -r}); okui::shapes::Rectangle(area).rotate(r).draw(this); } void TextureShader::_processTriangle(const std::array<Point<double>, 3>& p, const std::array<Point<double>, 3>& pT, Shader::Curve curve) { TriangleCurveProcessor::Process(_triangle, p, curve); double s, t; _texCoordTransform.transform((pT[0].x - _textureX1) / _textureWidth, (pT[0].y - _textureY1) / _textureHeight, &s, &t); _triangle.a.s = s; _triangle.a.t = t; _texCoordTransform.transform((pT[1].x - _textureX1) / _textureWidth, (pT[1].y - _textureY1) / _textureHeight, &s, &t); _triangle.b.s = s; _triangle.b.t = t; _texCoordTransform.transform((pT[2].x - _textureX1) / _textureWidth, (pT[2].y - _textureY1) / _textureHeight, &s, &t); _triangle.c.s = s; _triangle.c.t = t; } void TextureShader::flush() { glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, _texture); ShaderBase<Vertex>::flush(); } }}}
#include "onair/okui/shaders/TextureShader.h" #include "onair/okui/Texture.h" #include "onair/okui/shapes/Rectangle.h" namespace onair { namespace okui { namespace shaders { TextureShader::TextureShader(const char* fragmentShader) { opengl::Shader vsh(ONAIR_OKUI_VERTEX_SHADER_HEADER R"( ATTRIBUTE_IN vec2 positionAttrib; ATTRIBUTE_IN vec4 colorAttrib; ATTRIBUTE_IN vec4 curveAttrib; ATTRIBUTE_IN vec2 textureCoordAttrib; VARYING_OUT vec4 color; VARYING_OUT vec4 curve; VARYING_OUT vec2 textureCoord; void main() { color = colorAttrib; curve = curveAttrib; textureCoord = textureCoordAttrib; gl_Position = vec4(positionAttrib, 0.0, 1.0); } )", opengl::Shader::kVertexShader); opengl::Shader fsh(fragmentShader ? fragmentShader : ONAIR_OKUI_FRAGMENT_SHADER_HEADER R"( VARYING_IN vec4 color; VARYING_IN vec4 curve; VARYING_IN vec2 textureCoord; uniform sampler2D textureSampler; void main() { float alphaMultiplier = 1.0; if (curve.z > 1.5) { if (abs(curve.s) >= 0.5 || abs(curve.t) >= 0.5) { discard; } float dist = sqrt(curve.s * curve.s + curve.t * curve.t); float aa = curve.w; if (dist > 0.5 + 0.5 * aa) { discard; } else if (dist > 0.5 - 0.5 * aa) { alphaMultiplier = 1.0 - (dist - (0.5 - 0.5 * aa)) / aa; } } else if (curve.z != 0.0) { float dist = pow(curve.s, 2.0) - curve.t; float aa = curve.w; dist -= curve.z * aa; if (dist < 0.0 != curve.z < 0.0) { float x = abs(dist) / (2.0 * aa); if (x < 1.0) { alphaMultiplier = (1.0 - x); } else { discard; } } } COLOR_OUT = SAMPLE(textureSampler, textureCoord) * vec4(color.rgb, color.a * alphaMultiplier); } )", opengl::Shader::kFragmentShader); _program.attachShaders(vsh, fsh); _program.link(); _program.use(); _program.uniform("texture") = 0; if (!_program.error().empty()) { ONAIR_LOGF_ERROR("error creating shader: %s", _program.error().c_str()); return; } auto stride = reinterpret_cast<char*>(&_vertices[1]) - reinterpret_cast<char*>(&_vertices[0]); _vertexArrayBuffer.setAttribute(_program.attribute("positionAttrib"), 2, GL_FLOAT, GL_FALSE, stride, offsetof(Vertex, x)); _vertexArrayBuffer.setAttribute(_program.attribute("colorAttrib"), 4, GL_FLOAT, GL_FALSE, stride, offsetof(Vertex, r)); _vertexArrayBuffer.setAttribute(_program.attribute("curveAttrib"), 4, GL_FLOAT, GL_FALSE, stride, offsetof(Vertex, cu)); _vertexArrayBuffer.setAttribute(_program.attribute("textureCoordAttrib"), 2, GL_FLOAT, GL_FALSE, stride, offsetof(Vertex, s)); ONAIR_OKUI_GL_ERROR_CHECK(); } void TextureShader::setColor(const Color& color) { _triangle.a.r = _triangle.b.r = _triangle.c.r = color.r; _triangle.a.g = _triangle.b.g = _triangle.c.g = color.g; _triangle.a.b = _triangle.b.b = _triangle.c.b = color.b; _triangle.a.a = _triangle.b.a = _triangle.c.a = color.a; } void TextureShader::setTexture(GLuint id, double x, double y, double w, double h, const AffineTransformation& texCoordTransform) { if (_texture != id) { flush(); } _texture = id; _transformation.transform(x, y, &_textureX1, &_textureY1); double x2, y2; _transformation.transform(x + w, y + h, &x2, &y2); _textureWidth = x2 - _textureX1; _textureHeight = y2 - _textureY1; _texCoordTransform = texCoordTransform; } void TextureShader::drawScaledFill(const Texture& texture, Rectangle<double> area, double r) { setTexture(texture.id(), area.scaledFill(texture.aspectRatio()), AffineTransformation{0.5, 0.5, -0.5, -0.5, 1.0, 1.0, -r}); okui::shapes::Rectangle(area).rotate(r).draw(this); } void TextureShader::drawScaledFit(const Texture& texture, Rectangle<double> area, double r) { auto fit = area.scaledFit(texture.aspectRatio()); setTexture(texture.id(), fit, AffineTransformation{0.5, 0.5, -0.5, -0.5, 1.0, 1.0, -r}); okui::shapes::Rectangle(fit).rotate(r).draw(this); } void TextureShader::_processTriangle(const std::array<Point<double>, 3>& p, const std::array<Point<double>, 3>& pT, Shader::Curve curve) { TriangleCurveProcessor::Process(_triangle, p, curve); double s, t; _texCoordTransform.transform((pT[0].x - _textureX1) / _textureWidth, (pT[0].y - _textureY1) / _textureHeight, &s, &t); _triangle.a.s = s; _triangle.a.t = t; _texCoordTransform.transform((pT[1].x - _textureX1) / _textureWidth, (pT[1].y - _textureY1) / _textureHeight, &s, &t); _triangle.b.s = s; _triangle.b.t = t; _texCoordTransform.transform((pT[2].x - _textureX1) / _textureWidth, (pT[2].y - _textureY1) / _textureHeight, &s, &t); _triangle.c.s = s; _triangle.c.t = t; } void TextureShader::flush() { glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, _texture); ShaderBase<Vertex>::flush(); } }}}
fix texture fit rendering
fix texture fit rendering Summary: fix texture fit rendering Test Plan: look Reviewers: dapirian Reviewed By: dapirian Subscribers: #engineering Differential Revision: https://phabricator.watchonair.tv/D1164
C++
apache-2.0
bittorrent/okui,bittorrent/okui,bittorrent/okui,bittorrent/okui,bittorrent/okui
3062267204f73c337111a9b9dece4746183207ad
demo/toast/qrtoastdemo.cpp
demo/toast/qrtoastdemo.cpp
#include "qrtoastdemo.h" #include "ui_qrtoastdemo.h" #include "qrtoast.h" USING_NS_QRWIDGETS; QrToastDemo::QrToastDemo(QWidget *parent) : QWidget(parent), ui(new Ui::ToastWidget) { ui->setupUi(this); this->setWindowTitle("demo - toast"); connect(ui->pushButton, &QPushButton::clicked, [this](){ QrToast::instance()->show("Toast message", ui->pushButton->mapToGlobal(ui->pushButton->pos())); }); } QrToastDemo::~QrToastDemo() { delete ui; }
#include "qrtoastdemo.h" #include "ui_qrtoastdemo.h" #include <QtWidgets/qdesktopwidget.h> #include "qrtoast.h" USING_NS_QRWIDGETS; QrToastDemo::QrToastDemo(QWidget *parent) : QWidget(parent), ui(new Ui::ToastWidget) { ui->setupUi(this); this->setWindowTitle("demo - toast"); connect(ui->pushButton, &QPushButton::clicked, [this](){ QDesktopWidget *deskdop = QApplication::desktop(); QrToast::instance()->show("Toast message", QPoint(deskdop->width()/2, deskdop->height()/2)); }); } QrToastDemo::~QrToastDemo() { delete ui; }
move toast to the center of desktop
move toast to the center of desktop
C++
apache-2.0
Qters/QrWidgets
dd27fae2ffc700812d95a8661c790bbc5fb3500d
src/classes/Track.cxx
src/classes/Track.cxx
// Track // Author: Matthew Raso-Barnett 03/12/2010 #include <iostream> #include <sstream> #include <cassert> #include <stdexcept> #include "Track.h" //#define VERBOSE_MODE //#define PRINT_CONSTRUCTORS using namespace std; ClassImp(Track) //_____________________________________________________________________________ Track::Track() :TObject() { // -- Default constructor #ifdef PRINT_CONSTRUCTORS Info("Track", "Default Constructor"); #endif } //_____________________________________________________________________________ Track::Track(const Track& other) :TObject(other) { // -- Copy Constructor #ifdef PRINT_CONSTRUCTORS Info("Track", "Copy Constructor"); #endif } //_____________________________________________________________________________ Track& Track::operator=(const Track& other) { // --assignment operator if(this!=&other) { TObject::operator=(other); this->PurgeContainer(); fPoints = other.fPoints; } return *this; } //______________________________________________________________________________ Track::~Track() { // -- Destructor #ifdef PRINT_CONSTRUCTORS Info("Track", "Destructor"); #endif this->PurgeContainer(); } //______________________________________________________________________________ void Track::PurgeContainer() { // -- Delete all elements in container vector<Point*>::iterator it; for(it = fPoints.begin(); it != fPoints.end(); ++it) { delete *it; *it = 0; } } //______________________________________________________________________________ void Track::AddPoint(const Point& point) { // -- Add point to track fPoints.push_back(new Point(point)); } //______________________________________________________________________________ const Point& Track::GetPoint(unsigned int i) const { // -- Retrieve point from track // Check for requests past bounds of storage if (i >= fPoints.size()) {return *(fPoints.back());} return *(fPoints[i]); } //______________________________________________________________________________ vector<Double_t> Track::OutputPointsArray() { // -- Return an array of size 3*number-of-vertices, which contains just the positions // -- of each vertex, to be used for creating a TPolyLine3D for drawing purposes vector<Double_t> points; // Loop over all vertices vector<Point*>::const_iterator vertexIter; for (vertexIter = fPoints.begin(); vertexIter != fPoints.end(); vertexIter++) { // Fill array of points with X, Y, Z of each vertex points.push_back((*vertexIter)->X()); points.push_back((*vertexIter)->Y()); points.push_back((*vertexIter)->Z()); } return points; }
// Track // Author: Matthew Raso-Barnett 03/12/2010 #include <iostream> #include <sstream> #include <cassert> #include <stdexcept> #include "Track.h" //#define VERBOSE_MODE //#define PRINT_CONSTRUCTORS using namespace std; ClassImp(Track) //_____________________________________________________________________________ Track::Track() :TObject() { // -- Default constructor #ifdef PRINT_CONSTRUCTORS Info("Track", "Default Constructor"); #endif } //_____________________________________________________________________________ Track::Track(const Track& other) :TObject(other) { // -- Copy Constructor #ifdef PRINT_CONSTRUCTORS Info("Track", "Copy Constructor"); #endif // Have to copy every point in container if (other.TotalPoints() > 0) { for (int pointNum = 0; pointNum < other.TotalPoints(); pointNum++) { const Point& point = other.GetPoint(pointNum); this->AddPoint(point); } } } //_____________________________________________________________________________ Track& Track::operator=(const Track& other) { // --assignment operator if(this!=&other) { TObject::operator=(other); this->PurgeContainer(); fPoints = other.fPoints; } return *this; } //______________________________________________________________________________ Track::~Track() { // -- Destructor #ifdef PRINT_CONSTRUCTORS Info("Track", "Destructor"); #endif this->PurgeContainer(); } //______________________________________________________________________________ void Track::PurgeContainer() { // -- Delete all elements in container vector<Point*>::iterator it; for(it = fPoints.begin(); it != fPoints.end(); ++it) { delete *it; *it = 0; } } //______________________________________________________________________________ void Track::AddPoint(const Point& point) { // -- Add point to track fPoints.push_back(new Point(point)); } //______________________________________________________________________________ const Point& Track::GetPoint(unsigned int i) const { // -- Retrieve point from track // Check for requests past bounds of storage if (i >= fPoints.size()) {return *(fPoints.back());} return *(fPoints[i]); } //______________________________________________________________________________ vector<Double_t> Track::OutputPointsArray() { // -- Return an array of size 3*number-of-vertices, which contains just the positions // -- of each vertex, to be used for creating a TPolyLine3D for drawing purposes vector<Double_t> points; // Loop over all vertices vector<Point*>::const_iterator vertexIter; for (vertexIter = fPoints.begin(); vertexIter != fPoints.end(); vertexIter++) { // Fill array of points with X, Y, Z of each vertex points.push_back((*vertexIter)->X()); points.push_back((*vertexIter)->Y()); points.push_back((*vertexIter)->Z()); } return points; }
Fix copy constructor in Track
Fix copy constructor in Track -- Previously it was doing nothing!
C++
mit
mjrasobarnett/ucnsim,mjrasobarnett/ucnsim,mjrasobarnett/ucnsim
0f0e050eacbcb5582bbbd136f578cc8f5b9655dc
src/client/cl_main.cc
src/client/cl_main.cc
#include <iostream> #include <memory> #include <stdexcept> #include "cl_main.hh" #include "../event_queue.hh" #include "../sys_main.hh" #include "../renderer/gl_error.hh" #include <snow-common.hh> #include "../server/sv_main.hh" // Font test #include "../renderer/font.hh" #include "../renderer/texture.hh" #include "../ext/stb_image.h" #include "../data/database.hh" #include "../ext/fltk.h" namespace snow { #ifndef USE_LOCAL_SERVER #define USE_LOCAL_SERVER (USE_SERVER) #endif #define UP_BANDWIDTH (14400 / 8) #define DOWN_BANDWIDTH (57600 / 8) #define GL_QUEUE_NAME "net.spifftastic.snow.gl_queue" #define FRAME_QUEUE_NAME "net.spifftastic.snow.frame_queue" namespace { client_t g_client; std::once_flag g_init_flag; void cl_global_init(); void client_cleanup(); void cl_global_init() { std::call_once(g_init_flag, [] { glfwDefaultWindowHints(); #if !S_USE_GL_2 glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // glfwWindowHint(GLFW_ALPHA_BITS, 0); // glfwWindowHint(GLFW_DEPTH_BITS, 16); #else glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 1); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_NO_PROFILE); #endif // #define USE_GLFW_HDPI_EXTENSION #ifdef USE_GLFW_HDPI_EXTENSION glfwWindowHint(GLFW_HIDPI_IF_AVAILABLE, GL_TRUE); #endif s_log_note("---------------- STATIC INIT FINISHED ----------------"); if (enet_initialize() != 0) { s_throw(std::runtime_error, "Error initializing enet - failing"); } }); } void client_cleanup() { } } // namespace <anon> client_t &client_t::get_client(int client_num) { if (client_num != DEFAULT_CLIENT_NUM) s_throw(std::out_of_range, "Invalid client number provided to client_t::get_client"); return g_client; } client_t::client_t() : read_socket_(zmq::context_t::shared(), ZMQ_PULL), write_socket_(zmq::context_t::shared(), ZMQ_PUSH), cmd_quit_("quit", [=](cvar_set_t &cvars, const ccmd_t::args_t &args) { if (cl_willQuit) { cl_willQuit->seti(1); } }) { } client_t::~client_t() { dispose(); } // must be run on main queue void client_t::initialize(int argc, const char *argv[]) { cl_global_init(); s_log_note("Initializing window"); window_ = glfwCreateWindow(800, 600, "Snow", NULL, NULL); if (!window_) { s_log_note("Window failed to initialize"); s_throw(std::runtime_error, "Failed to create GLFW window"); } else { s_log_note("Window initialized"); } set_main_window(window_); // Set up event handling read_socket_.set_linger(10); read_socket_.bind(EVENT_ENDPOINT); write_socket_.set_linger(10); write_socket_.connect(EVENT_ENDPOINT); event_queue_.set_socket(&write_socket_); event_queue_.set_window_callbacks(window_, ALL_EVENT_KINDS); s_log_note("------------------- INIT FINISHED --------------------"); #if USE_LOCAL_SERVER // Create client host s_log_note("Creating local client"); host_ = enet_host_create(NULL, 1, 2, DOWN_BANDWIDTH, UP_BANDWIDTH); if (host_ == NULL) { s_throw(std::runtime_error, "Unable to create client host"); } s_log_note("Starting local server"); server_t::get_server(server_t::DEFAULT_SERVER_NUM).initialize(argc, argv); s_log_note("Attempting to connect to server"); ENetAddress server_addr; enet_address_set_host(&server_addr, "127.0.0.1"); server_addr.port = server_t::DEFAULT_SERVER_PORT; if (!connect(server_addr)) { s_throw(std::runtime_error, "Unable to connect to local server"); } #endif res_ = &resources_t::default_resources(); res_->prepare_resources(); // Launch frameloop thread s_log_note("Launching frameloop"); async_thread(&client_t::run_frameloop, this); for (poll_events_ = true; poll_events_;) { #define USE_FLTK_EVENT_POLLING 1 #if USE_FLTK_EVENT_POLLING while (Fl::wait(0.5) > 0) ; #else glfwPollEvents(); #endif } event_queue_.set_socket(nullptr); write_socket_.close(); read_socket_.close(); } void client_t::quit() { running_.store(false); } #if USE_SERVER bool client_t::connect(ENetAddress address) { peer_ = enet_host_connect(host_, &address, 2, 0); if (peer_ == NULL) { s_log_error("Unable to allocate peer to connect to server"); return false; } ENetEvent event; double timeout = glfwGetTime() + 5.0; int error = 0; while (glfwGetTime() < timeout) { while ((error = enet_host_service(host_, &event, 0)) > 0) { if (event.type == ENET_EVENT_TYPE_CONNECT && event.peer == peer_) { s_log_note("Established connection"); return true; } } if (error < 0) { break; } } s_log_error("Unable to connect to host"); enet_peer_reset(peer_); peer_ = NULL; return false; } bool client_t::is_connected() const { return peer_ != NULL; } void client_t::disconnect() { if (host_ != NULL) { enet_host_flush(host_); enet_peer_disconnect(peer_, 0); enet_host_destroy(host_); host_ = NULL; } } #endif gl_state_t &client_t::gl_state() { return state_; } const gl_state_t &client_t::gl_state() const { return state_; } // must be run on main queue void client_t::terminate() { dispose(); client_cleanup(); poll_events_ = false; } void client_t::dispose() { #if USE_SERVER if (is_connected()) { disconnect(); } #endif if (window_) { // glfwSetInputMode(window_, GLFW_CURSOR_MODE, GLFW_CURSOR_NORMAL); glfwDestroyWindow(window_); window_ = nullptr; } #if USE_LOCAL_SERVER server_t::get_server(server_t::DEFAULT_SERVER_NUM).kill(); #endif } void client_t::add_system(system_t *system, int logic_priority, int draw_priority) { auto predicate = [](int priority, const system_pair_t &pair) { return pair.first >= priority; }; auto logic_iter = std::upper_bound( logic_systems_.cbegin(), logic_systems_.cend(), logic_priority, predicate); logic_systems_.emplace(logic_iter, logic_priority, system); auto draw_iter = std::upper_bound( draw_systems_.cbegin(), draw_systems_.cend(), draw_priority, predicate); draw_systems_.emplace(draw_iter, draw_priority, system); } void client_t::remove_system(system_t *system) { auto predicate = [system](const system_pair_t &pair) { return pair.second == system; }; logic_systems_.remove_if(predicate); draw_systems_.remove_if(predicate); } void client_t::remove_all_systems() { logic_systems_.clear(); draw_systems_.clear(); } } // namespace snow
#include <iostream> #include <memory> #include <stdexcept> #include "cl_main.hh" #include "../event_queue.hh" #include "../sys_main.hh" #include "../renderer/gl_error.hh" #include <snow-common.hh> #include "../server/sv_main.hh" // Font test #include "../renderer/font.hh" #include "../renderer/texture.hh" #include "../ext/stb_image.h" #include "../data/database.hh" #include "../ext/fltk.h" namespace snow { #ifndef USE_LOCAL_SERVER #define USE_LOCAL_SERVER (USE_SERVER) #endif #define UP_BANDWIDTH (14400 / 8) #define DOWN_BANDWIDTH (57600 / 8) #define GL_QUEUE_NAME "net.spifftastic.snow.gl_queue" #define FRAME_QUEUE_NAME "net.spifftastic.snow.frame_queue" namespace { client_t g_client; std::once_flag g_init_flag; void cl_global_init(); void client_cleanup(); void cl_global_init() { std::call_once(g_init_flag, [] { glfwDefaultWindowHints(); #if !S_USE_GL_2 glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // glfwWindowHint(GLFW_ALPHA_BITS, 0); // glfwWindowHint(GLFW_DEPTH_BITS, 16); #else glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 1); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_NO_PROFILE); #endif // #define USE_GLFW_HDPI_EXTENSION #ifdef USE_GLFW_HDPI_EXTENSION glfwWindowHint(GLFW_HIDPI_IF_AVAILABLE, GL_TRUE); #endif s_log_note("---------------- STATIC INIT FINISHED ----------------"); if (enet_initialize() != 0) { s_throw(std::runtime_error, "Error initializing enet - failing"); } }); } void client_cleanup() { } } // namespace <anon> client_t &client_t::get_client(int client_num) { if (client_num != DEFAULT_CLIENT_NUM) s_throw(std::out_of_range, "Invalid client number provided to client_t::get_client"); return g_client; } client_t::client_t() : read_socket_(zmq::context_t::shared(), ZMQ_PULL), write_socket_(zmq::context_t::shared(), ZMQ_PUSH), cmd_quit_("quit", [=](cvar_set_t &cvars, const ccmd_t::args_t &args) { if (cl_willQuit) { cl_willQuit->seti(1); } }) { } client_t::~client_t() { dispose(); } // must be run on main queue void client_t::initialize(int argc, const char *argv[]) { cl_global_init(); s_log_note("Initializing window"); window_ = glfwCreateWindow(800, 600, "Snow", NULL, NULL); if (!window_) { s_log_note("Window failed to initialize"); s_throw(std::runtime_error, "Failed to create GLFW window"); } else { s_log_note("Window initialized"); } set_main_window(window_); // Set up event handling read_socket_.set_linger(10); read_socket_.bind(EVENT_ENDPOINT); write_socket_.set_linger(10); write_socket_.connect(EVENT_ENDPOINT); event_queue_.set_socket(&write_socket_); event_queue_.set_window_callbacks(window_, ALL_EVENT_KINDS); s_log_note("------------------- INIT FINISHED --------------------"); #if USE_LOCAL_SERVER // Create client host s_log_note("Creating local client"); host_ = enet_host_create(NULL, 1, 2, DOWN_BANDWIDTH, UP_BANDWIDTH); if (host_ == NULL) { s_throw(std::runtime_error, "Unable to create client host"); } s_log_note("Starting local server"); server_t::get_server(server_t::DEFAULT_SERVER_NUM).initialize(argc, argv); s_log_note("Attempting to connect to server"); ENetAddress server_addr; enet_address_set_host(&server_addr, "127.0.0.1"); server_addr.port = server_t::DEFAULT_SERVER_PORT; if (!connect(server_addr)) { s_throw(std::runtime_error, "Unable to connect to local server"); } #endif res_ = &resources_t::default_resources(); res_->prepare_resources(); // Launch frameloop thread s_log_note("Launching frameloop"); async_thread(&client_t::run_frameloop, this); for (poll_events_ = true; poll_events_;) { #define USE_FLTK_EVENT_POLLING 1 #if USE_FLTK_EVENT_POLLING while (Fl::wait(0.5) > 0) ; #else glfwPollEvents(); #endif } event_queue_.set_socket(nullptr); write_socket_.close(); read_socket_.close(); } void client_t::quit() { running_.store(false); } #if USE_SERVER bool client_t::connect(ENetAddress address) { peer_ = enet_host_connect(host_, &address, 2, 0); if (peer_ == NULL) { s_log_error("Unable to allocate peer to connect to server"); return false; } ENetEvent event; double timeout = glfwGetTime() + 5.0; int error = 0; while (glfwGetTime() < timeout) { while ((error = enet_host_service(host_, &event, 0)) > 0) { if (event.type == ENET_EVENT_TYPE_CONNECT && event.peer == peer_) { s_log_note("Established connection"); return true; } } if (error < 0) { break; } } s_log_error("Unable to connect to host"); enet_peer_reset(peer_); peer_ = NULL; return false; } bool client_t::is_connected() const { return peer_ != NULL; } void client_t::disconnect() { if (host_ != NULL) { enet_host_flush(host_); enet_peer_disconnect(peer_, 0); enet_host_destroy(host_); host_ = NULL; } } #endif gl_state_t &client_t::gl_state() { return state_; } const gl_state_t &client_t::gl_state() const { return state_; } // must be run on main queue void client_t::terminate() { dispose(); client_cleanup(); poll_events_ = false; } void client_t::dispose() { #if USE_SERVER if (is_connected()) { disconnect(); } #endif if (window_) { // glfwSetInputMode(window_, GLFW_CURSOR_MODE, GLFW_CURSOR_NORMAL); glfwDestroyWindow(window_); window_ = nullptr; } #if USE_LOCAL_SERVER server_t::get_server(server_t::DEFAULT_SERVER_NUM).kill(); #endif } void client_t::add_system(system_t *system, int logic_priority, int draw_priority) { auto predicate = [](int priority, const system_pair_t &pair) { return pair.first <= priority; }; auto logic_iter = std::upper_bound( logic_systems_.cbegin(), logic_systems_.cend(), logic_priority, predicate); logic_systems_.emplace(logic_iter, logic_priority, system); auto draw_iter = std::upper_bound( draw_systems_.cbegin(), draw_systems_.cend(), draw_priority, predicate); draw_systems_.emplace(draw_iter, draw_priority, system); } void client_t::remove_system(system_t *system) { auto predicate = [system](const system_pair_t &pair) { return pair.second == system; }; logic_systems_.remove_if(predicate); draw_systems_.remove_if(predicate); } void client_t::remove_all_systems() { logic_systems_.clear(); draw_systems_.clear(); } } // namespace snow
Fix insertion for systems.
Fix insertion for systems. Was reversed accidentally.
C++
bsd-2-clause
nilium/snow,nilium/snow,nilium/snow
3fe52d8583b6639babc06321c49f9feff25bbdb0
test/marshallers.cc
test/marshallers.cc
/* Tests covering unmarshaller and marshaller parts of the fastrpc library. */ #include <string> #include <vector> #include <stdexcept> #include <iostream> #include <fstream> #include <memory> #include <sstream> #include "frpcunmarshaller.h" #include "frpctreebuilder.h" /* Uses external test file that contains both binary representation and resulting FRPC format */ const std::string DEFAULT_TEST_FILE = "frpc.tests"; namespace color { enum Code_t { FG_RED = 31, FG_GREEN = 32, FG_BLUE = 34, FG_DEFAULT = 39, BG_RED = 41, BG_GREEN = 42, BG_BLUE = 44, BG_DEFAULT = 49 }; class Modifier_t { Code_t code; public: Modifier_t(Code_t col) : code(col) {} friend std::ostream& operator<<(std::ostream& os, const Modifier_t& mod) { return os << "\033[" << mod.code << "m"; } }; } static const color::Modifier_t cl_red(color::FG_RED); static const color::Modifier_t cl_green(color::FG_GREEN); static const color::Modifier_t cl_default(color::FG_DEFAULT); typedef std::vector<std::string> Args_t; std::string extract_arg(Args_t::const_iterator &it, Args_t::const_iterator iend) { if (++it == iend) throw std::runtime_error("Command expects arguments!"); return *it; } struct TestSettings_t { TestSettings_t() : diffable(false), usestdin(false), testfile(DEFAULT_TEST_FILE) {} bool diffable; //!< Diffable mode - outputs a corrected test input bool usestdin; std::string testfile; }; void processArgs(TestSettings_t &s, const Args_t &args) { for (Args_t::const_iterator it = args.begin(), iend = args.end(); it != iend; ++it) { if (*it == "diffable") { s.diffable = true; } else if (*it == "stdin") { s.usestdin = true; } else if (*it == "testfile") { s.testfile = extract_arg(it, iend); } else { std::cerr << "Unknown parameter " << *it << " expected [diffable] [stdin] [testfile filename]" << std::endl; return; } } } int nextHexNibble(std::string::const_iterator &it, std::string::const_iterator &iend) { while (it != iend) { unsigned char c = static_cast<unsigned char>(*it); ++it; switch (c) { case '0' ... '9': return c - '0'; case 'a' ... 'f': return c - 'a' + 10; case 'A' ... 'F': return c - 'A' + 10; // Whitespace moves us to the next character case '\n': case ' ': case '\t': continue; default: return -2; } } return -1; } void skipWS(std::string::const_iterator &it, const std::string::const_iterator &iend) { for (;it != iend; ++it) { unsigned char c = static_cast<unsigned char>(*it); switch (c) { // Whitespace moves us to the next character case '\n': case ' ': case '\t': continue; default: return; } } } void pushString(std::string &buf, std::string::const_iterator &it, const std::string::const_iterator iend) { bool inEsc = false; for (; it != iend; ++it) { unsigned char c = static_cast<unsigned char>(*it); if (c == '\\') { inEsc = true; continue; } if (c == '"' && !inEsc) { ++it; break; } inEsc = false; buf.push_back(c); } } std::string unhex(const std::string &hex) { std::string result; result.reserve(hex.length() / 2); std::string::const_iterator it = hex.begin(), iend = hex.end(); while (it != iend) { // skip spaces, etc skipWS(it, iend); // try to read string literals if present if (*it == '"') { ++it; pushString(result, it, iend); continue; } // read it out as a hexadecimal byte int a = nextHexNibble(it, iend); int b = nextHexNibble(it, iend); // negative values denounce error if ((a < 0) || (b < 0)) throw std::runtime_error( "encountered invalid character in hex stream"); result.push_back((a << 4) | b); } return result; } enum ErrorType_t { ERROR_UNKNOWN = 0, ERROR_BAD_PROTOCOL_VERSION, ERROR_UNEXPECTED_END, ERROR_FAULT_TEST, ERROR_INVALID_TYPE, ERROR_INVALID_INT_SIZE, ERROR_INVALID_STR_SIZE, ERROR_INVALID_BIN_SIZE, ERROR_INVALID_BOOL_VALUE }; const char *errorTypeStr(ErrorType_t et) { switch (et) { case ERROR_BAD_PROTOCOL_VERSION: return "bad protocol version"; case ERROR_UNEXPECTED_END: return "unexpected data end"; case ERROR_FAULT_TEST: return "fault test"; case ERROR_INVALID_TYPE: return "unknown type"; case ERROR_INVALID_INT_SIZE: return "bad size"; case ERROR_INVALID_STR_SIZE: return "bad size"; case ERROR_INVALID_BIN_SIZE: return "bad size"; case ERROR_INVALID_BOOL_VALUE: return "invalid bool value"; case ERROR_UNKNOWN: default: return "unknown"; } } template<typename ExceptionT> ErrorType_t parseErrorType(const ExceptionT &ex) { return ERROR_UNKNOWN; } bool doColor = false; std::ostream &success() { if (!doColor) return std::cerr << "[ OK ] "; return std::cerr << cl_green << "[ OK ]" << cl_default << " "; } std::ostream &error() { if (!doColor) return std::cerr << "[ !! ] Error: "; return std::cerr << cl_red << "[ !! ]" << cl_default << " Error: "; } template<> ErrorType_t parseErrorType(const FRPC::StreamError_t &err) { if (err.what() == std::string("Unsupported protocol version !!!")) return ERROR_BAD_PROTOCOL_VERSION; if (err.what() == std::string("Stream not complete")) return ERROR_UNEXPECTED_END; if (err.what() == std::string("Don't known this type")) return ERROR_INVALID_TYPE; if (err.what() == std::string("Unknown value type")) return ERROR_INVALID_TYPE; if (err.what() == std::string("Illegal element length")) return ERROR_INVALID_INT_SIZE; if (err.what() == std::string("Size of int is 0 or > 4 !!!")) return ERROR_INVALID_INT_SIZE; if (err.what() == std::string("Size of string length is 0 !!!")) return ERROR_INVALID_STR_SIZE; if (err.what() == std::string("Size of binary length is 0 !!!")) return ERROR_INVALID_BIN_SIZE; if (err.what() == std::string("Invalid bool value")) return ERROR_INVALID_BOOL_VALUE; error() << "Unhandled FRPC::StreamError_t " << err.what() << std::endl; return ERROR_UNKNOWN; } template<> ErrorType_t parseErrorType(const FRPC::Fault_t &err) { if (err.what() == std::string("No data unmarshalled")) return ERROR_UNEXPECTED_END; if (err.what() == std::string("FAULT_TEST")) return ERROR_FAULT_TEST; error() << "Unhandled FRPC::Fault_t " << err.what() << std::endl; return ERROR_UNKNOWN; } // A single test instance containing source and destination data struct TestInstance_t { std::string binary; std::string text; void reset() { binary.clear(); text.clear(); } }; enum TestResultType_t { TEST_PASSED = 0, TEST_FAILED = 1, TEST_FAILED_ERROR = 2 }; struct TestResult_t { TestResult_t(TestResultType_t tr, const std::string &com = "") : result(tr), comment(com) {} void set(TestResultType_t tr, const std::string &com = "") { result = tr; comment = com; } TestResultType_t operator()() const { return result; } TestResultType_t result; std::string comment; }; std::string toStr(int i) { std::ostringstream s; s << i; return s.str(); } /** Runs the core test, returns corrected result */ std::pair<TestInstance_t, TestResult_t> runTest(const TestSettings_t &ts, const TestInstance_t &ti, size_t testNum, size_t lineNum) { TestInstance_t corrected; TestResult_t result(TEST_PASSED); try { FRPC::Pool_t pool; FRPC::TreeBuilder_t builder(pool); std::auto_ptr<FRPC::UnMarshaller_t> unmarshaller = std::auto_ptr<FRPC::UnMarshaller_t>( FRPC::UnMarshaller_t::create( FRPC::UnMarshaller_t::BINARY_RPC, builder)); unmarshaller->unMarshall(ti.binary.data(), ti.binary.size(), FRPC::UnMarshaller_t::TYPE_ANY); unmarshaller->finish(); // TODO: Fix - introduce a normalized dump method // Text format of the deserialized data std::string txtree; corrected.text = builder.getUnMarshaledMethodName(); FRPC::dumpFastrpcTree(builder.getUnMarshaledData(), txtree, -1); corrected.text += txtree; // TODO: Binary should be generated by marshaller corrected.binary = ti.binary; // TODO: convert the intermediate format back to binary } catch (const FRPC::StreamError_t &ex) { ErrorType_t ert = parseErrorType(ex); corrected.text = std::string("error(")+errorTypeStr(ert)+")"; } catch (const FRPC::Fault_t &ex) { if (ex.errorNum() > 0) { // fault contains integral error number, let's contain it in the output std::string errNumStr = toStr(ex.errorNum()); corrected.text = std::string("fault(") + errNumStr + ", " + ex.what() + ")"; } else { ErrorType_t ert = parseErrorType(ex); corrected.text = std::string("error(") + errorTypeStr(ert) + ")"; } } catch (const std::exception &ex) { corrected.text = std::string("error(")+ex.what()+")"; } // compare the unmarshalled data if (corrected.text != ti.text) { result.set(TEST_FAILED, corrected.text + " <> " + ti.text); } return std::make_pair(corrected, result); } enum ParseState_t { PS_BINARY, PS_TEXT }; bool isCommentLine(const std::string &str) { if(str.empty()) return false; if (str[0] == '#') return true; return false; } bool parseTestName(const std::string &str, std::string &name) { if(str.empty()) return false; if (str[0] == '@') { name = str.substr(1); return true; } return false; } size_t errCount = 0; void runTests(const TestSettings_t &ts, std::istream &input) { // parse the testfile. Anything starting with # is a skipped line std::string line; std::string testName; ParseState_t ps = PS_BINARY; TestInstance_t ti; size_t testNum = 1; for (size_t lineNum = 0; std::getline(input, line); ++lineNum) { if (isCommentLine(line)) { if (ts.diffable) std::cout << line << std::endl; continue; } if (parseTestName(line, testName)) { if (ts.diffable) std::cout << line << std::endl; continue; } switch (ps) { case PS_BINARY: if (line.empty()) { if (ts.diffable) std::cout << std::endl; continue; } ti.binary = unhex(line); ps = PS_TEXT; if (ts.diffable) std::cout << line << std::endl; break; case PS_TEXT: // empty line denotes expected result end. if (line.empty()) { ps = PS_BINARY; std::pair<TestInstance_t, TestResult_t> result = runTest(ts, ti, testNum, lineNum); if (ts.diffable) { std::cout << result.first.text << std::endl << std::endl; } if (result.second() != TEST_PASSED) { ++errCount; error() << "Failed test no. " << testNum << " '" << testName << "'" << " in " << ts.testfile << ":" << lineNum << " with '" << result.second.comment << "'" << std::endl; } else { success() << "Passed test no. " << testNum << " '" << testName << "'" << std::endl; } ti.reset(); ++testNum; break; } if (!ti.text.empty()) ti.text.push_back('\n'); ti.text.append(line); } } if (ps != PS_BINARY) { ++errCount; error() << "The last test is incompletely defined." << std::endl; } } void runTests(const TestSettings_t &ts) { if (ts.usestdin) { runTests(ts, std::cin); } else { std::ifstream infile(ts.testfile); runTests(ts, infile); } } int main(int argc, const char *argv[]) { doColor = ::isatty(::fileno(::stderr)); Args_t args(argv + 1, argv + argc); TestSettings_t ts; processArgs(ts, args); runTests(ts); if (errCount) { std::cerr << "----" << std::endl; error() << "Test contained " << errCount << " error(s)." << std::endl; return 1; } return 0; }
/* Tests covering unmarshaller and marshaller parts of the fastrpc library. */ #include <string> #include <vector> #include <stdexcept> #include <iostream> #include <fstream> #include <memory> #include <sstream> #include "frpcunmarshaller.h" #include "frpctreebuilder.h" /* Uses external test file that contains both binary representation and resulting FRPC format */ const std::string DEFAULT_TEST_FILE = "frpc.tests"; namespace color { enum Code_t { FG_RED = 31, FG_GREEN = 32, FG_BLUE = 34, FG_DEFAULT = 39, BG_RED = 41, BG_GREEN = 42, BG_BLUE = 44, BG_DEFAULT = 49 }; class Modifier_t { Code_t code; public: Modifier_t(Code_t col) : code(col) {} friend std::ostream& operator<<(std::ostream& os, const Modifier_t& mod) { return os << "\033[" << mod.code << "m"; } }; } static const color::Modifier_t cl_red(color::FG_RED); static const color::Modifier_t cl_green(color::FG_GREEN); static const color::Modifier_t cl_default(color::FG_DEFAULT); typedef std::vector<std::string> Args_t; std::string extract_arg(Args_t::const_iterator &it, Args_t::const_iterator iend) { if (++it == iend) throw std::runtime_error("Command expects arguments!"); return *it; } struct TestSettings_t { TestSettings_t() : diffable(false), usestdin(false), testfile(DEFAULT_TEST_FILE) {} bool diffable; //!< Diffable mode - outputs a corrected test input bool usestdin; std::string testfile; }; void processArgs(TestSettings_t &s, const Args_t &args) { for (Args_t::const_iterator it = args.begin(), iend = args.end(); it != iend; ++it) { if (*it == "diffable") { s.diffable = true; } else if (*it == "stdin") { s.usestdin = true; } else if (*it == "testfile") { s.testfile = extract_arg(it, iend); } else { std::cerr << "Unknown parameter " << *it << " expected [diffable] [stdin] [testfile filename]" << std::endl; return; } } } int nextHexNibble(std::string::const_iterator &it, std::string::const_iterator &iend) { while (it != iend) { unsigned char c = static_cast<unsigned char>(*it); ++it; switch (c) { case '0' ... '9': return c - '0'; case 'a' ... 'f': return c - 'a' + 10; case 'A' ... 'F': return c - 'A' + 10; // Whitespace moves us to the next character case '\n': case ' ': case '\t': continue; default: return -2; } } return -1; } void skipWS(std::string::const_iterator &it, const std::string::const_iterator &iend) { for (;it != iend; ++it) { unsigned char c = static_cast<unsigned char>(*it); switch (c) { // Whitespace moves us to the next character case '\n': case ' ': case '\t': continue; default: return; } } } void pushString(std::string &buf, std::string::const_iterator &it, const std::string::const_iterator iend) { bool inEsc = false; for (; it != iend; ++it) { unsigned char c = static_cast<unsigned char>(*it); if (c == '\\') { inEsc = true; continue; } if (c == '"' && !inEsc) { ++it; break; } inEsc = false; buf.push_back(c); } } std::string unhex(const std::string &hex) { std::string result; result.reserve(hex.length() / 2); std::string::const_iterator it = hex.begin(), iend = hex.end(); while (it != iend) { // skip spaces, etc skipWS(it, iend); // try to read string literals if present if (*it == '"') { ++it; pushString(result, it, iend); continue; } // read it out as a hexadecimal byte int a = nextHexNibble(it, iend); int b = nextHexNibble(it, iend); // negative values denounce error if ((a < 0) || (b < 0)) throw std::runtime_error( "encountered invalid character in hex stream"); result.push_back((a << 4) | b); } return result; } enum ErrorType_t { ERROR_UNKNOWN = 0, ERROR_BAD_PROTOCOL_VERSION, ERROR_UNEXPECTED_END, ERROR_FAULT_TEST, ERROR_INVALID_TYPE, ERROR_INVALID_INT_SIZE, ERROR_INVALID_STR_SIZE, ERROR_INVALID_BIN_SIZE, ERROR_INVALID_BOOL_VALUE }; const char *errorTypeStr(ErrorType_t et) { switch (et) { case ERROR_BAD_PROTOCOL_VERSION: return "bad protocol version"; case ERROR_UNEXPECTED_END: return "unexpected data end"; case ERROR_FAULT_TEST: return "fault test"; case ERROR_INVALID_TYPE: return "unknown type"; case ERROR_INVALID_INT_SIZE: return "bad size"; case ERROR_INVALID_STR_SIZE: return "bad size"; case ERROR_INVALID_BIN_SIZE: return "bad size"; case ERROR_INVALID_BOOL_VALUE: return "invalid bool value"; case ERROR_UNKNOWN: default: return "unknown"; } } template<typename ExceptionT> ErrorType_t parseErrorType(const ExceptionT &ex) { return ERROR_UNKNOWN; } bool doColor = false; std::ostream &success() { if (!doColor) return std::cerr << "[ OK ] "; return std::cerr << cl_green << "[ OK ]" << cl_default << " "; } std::ostream &error() { if (!doColor) return std::cerr << "[ !! ] Error: "; return std::cerr << cl_red << "[ !! ]" << cl_default << " Error: "; } template<> ErrorType_t parseErrorType(const FRPC::StreamError_t &err) { if (err.what() == std::string("Unsupported protocol version !!!")) return ERROR_BAD_PROTOCOL_VERSION; if (err.what() == std::string("Stream not complete")) return ERROR_UNEXPECTED_END; if (err.what() == std::string("Don't known this type")) return ERROR_INVALID_TYPE; if (err.what() == std::string("Unknown value type")) return ERROR_INVALID_TYPE; if (err.what() == std::string("Illegal element length")) return ERROR_INVALID_INT_SIZE; if (err.what() == std::string("Size of int is 0 or > 4 !!!")) return ERROR_INVALID_INT_SIZE; if (err.what() == std::string("Size of string length is 0 !!!")) return ERROR_INVALID_STR_SIZE; if (err.what() == std::string("Size of binary length is 0 !!!")) return ERROR_INVALID_BIN_SIZE; if (err.what() == std::string("Invalid bool value")) return ERROR_INVALID_BOOL_VALUE; error() << "Unhandled FRPC::StreamError_t " << err.what() << std::endl; return ERROR_UNKNOWN; } template<> ErrorType_t parseErrorType(const FRPC::Fault_t &err) { if (err.what() == std::string("No data unmarshalled")) return ERROR_UNEXPECTED_END; if (err.what() == std::string("FAULT_TEST")) return ERROR_FAULT_TEST; error() << "Unhandled FRPC::Fault_t " << err.what() << std::endl; return ERROR_UNKNOWN; } // A single test instance containing source and destination data struct TestInstance_t { std::string binary; std::string text; void reset() { binary.clear(); text.clear(); } }; enum TestResultType_t { TEST_PASSED = 0, TEST_FAILED = 1, TEST_FAILED_ERROR = 2 }; struct TestResult_t { TestResult_t(TestResultType_t tr, const std::string &com = "") : result(tr), comment(com) {} void set(TestResultType_t tr, const std::string &com = "") { result = tr; comment = com; } TestResultType_t operator()() const { return result; } TestResultType_t result; std::string comment; }; std::string toStr(int i) { std::ostringstream s; s << i; return s.str(); } /** Runs the core test, returns corrected result */ std::pair<TestInstance_t, TestResult_t> runTest(const TestSettings_t &ts, const TestInstance_t &ti, size_t testNum, size_t lineNum) { TestInstance_t corrected; TestResult_t result(TEST_PASSED); try { FRPC::Pool_t pool; FRPC::TreeBuilder_t builder(pool); std::auto_ptr<FRPC::UnMarshaller_t> unmarshaller = std::auto_ptr<FRPC::UnMarshaller_t>( FRPC::UnMarshaller_t::create( FRPC::UnMarshaller_t::BINARY_RPC, builder)); unmarshaller->unMarshall(ti.binary.data(), ti.binary.size(), FRPC::UnMarshaller_t::TYPE_ANY); unmarshaller->finish(); // TODO: Fix - introduce a normalized dump method // Text format of the deserialized data std::string txtree; corrected.text = builder.getUnMarshaledMethodName(); FRPC::dumpFastrpcTree(builder.getUnMarshaledData(), txtree, -1); corrected.text += txtree; // TODO: Binary should be generated by marshaller corrected.binary = ti.binary; // TODO: convert the intermediate format back to binary } catch (const FRPC::StreamError_t &ex) { ErrorType_t ert = parseErrorType(ex); corrected.text = std::string("error(")+errorTypeStr(ert)+")"; } catch (const FRPC::Fault_t &ex) { if (ex.errorNum() > 0) { // fault contains integral error number, let's contain it in the output std::string errNumStr = toStr(ex.errorNum()); corrected.text = std::string("fault(") + errNumStr + ", " + ex.what() + ")"; } else { ErrorType_t ert = parseErrorType(ex); corrected.text = std::string("error(") + errorTypeStr(ert) + ")"; } } catch (const std::exception &ex) { corrected.text = std::string("error(")+ex.what()+")"; } // compare the unmarshalled data if (corrected.text != ti.text) { result.set(TEST_FAILED, corrected.text + " <> " + ti.text); } return std::make_pair(corrected, result); } enum ParseState_t { PS_BINARY, PS_TEXT }; bool isCommentLine(const std::string &str) { if(str.empty()) return false; if (str[0] == '#') return true; return false; } bool parseTestName(const std::string &str, std::string &name) { if(str.empty()) return false; if (str[0] == '@') { name = str.substr(1); return true; } return false; } size_t errCount = 0; void runTests(const TestSettings_t &ts, std::istream &input) { // parse the testfile. Anything starting with # is a skipped line std::string line; std::string testName; ParseState_t ps = PS_BINARY; TestInstance_t ti; size_t testNum = 1; for (size_t lineNum = 0; std::getline(input, line); ++lineNum) { if (isCommentLine(line)) { if (ts.diffable) std::cout << line << std::endl; continue; } if (parseTestName(line, testName)) { if (ts.diffable) std::cout << line << std::endl; continue; } switch (ps) { case PS_BINARY: if (line.empty()) { if (ts.diffable) std::cout << std::endl; continue; } ti.binary = unhex(line); ps = PS_TEXT; if (ts.diffable) std::cout << line << std::endl; break; case PS_TEXT: // empty line denotes expected result end. if (line.empty()) { ps = PS_BINARY; std::pair<TestInstance_t, TestResult_t> result = runTest(ts, ti, testNum, lineNum); if (ts.diffable) { std::cout << result.first.text << std::endl << std::endl; } if (result.second() != TEST_PASSED) { ++errCount; error() << "Failed test no. " << testNum << " '" << testName << "'" << " in " << ts.testfile << ":" << lineNum << " with '" << result.second.comment << "'" << std::endl; } else { success() << "Passed test no. " << testNum << " '" << testName << "'" << std::endl; } ti.reset(); ++testNum; break; } if (!ti.text.empty()) ti.text.push_back('\n'); ti.text.append(line); } } if (ps != PS_BINARY) { ++errCount; error() << "The last test is incompletely defined." << std::endl; } } void runTests(const TestSettings_t &ts) { if (ts.usestdin) { runTests(ts, std::cin); } else { std::ifstream infile(ts.testfile.c_str()); runTests(ts, infile); } } int main(int argc, const char *argv[]) { doColor = ::isatty(::fileno(::stderr)); Args_t args(argv + 1, argv + argc); TestSettings_t ts; processArgs(ts, args); runTests(ts); if (errCount) { std::cerr << "----" << std::endl; error() << "Test contained " << errCount << " error(s)." << std::endl; return 1; } return 0; }
fix compilation error
fix compilation error
C++
lgpl-2.1
seznam/fastrpc,burlog/fastrpc,seznam/fastrpc,seznam/fastrpc,burlog/fastrpc,burlog/fastrpc,seznam/fastrpc,seznam/fastrpc,burlog/fastrpc,seznam/fastrpc
e54f794158630a5074088185a8941c2b52d17cef
DeviceAdapters/PI/PI.cpp
DeviceAdapters/PI/PI.cpp
/////////////////////////////////////////////////////////////////////////////// // FILE: PI.cpp // PROJECT: Micro-Manager // SUBSYSTEM: DeviceAdapters //----------------------------------------------------------------------------- // DESCRIPTION: PI Controller Driver // // AUTHOR: Nenad Amodaj, [email protected], 08/28/2006 // Steffen Rau, [email protected], 10/03/2008 // Nico Stuurman, [email protected], 3/19/2008 // COPYRIGHT: University of California, San Francisco, 2006, 2008 // Physik Instrumente (PI) GmbH & Co. KG, 2008 // LICENSE: This file is distributed under the BSD license. // License text is included with the source distribution. // // This file 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. // // IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES. // CVS: $Id: Nikon.cpp 574 2007-11-07 21:00:45Z nenad $ // #ifdef WIN32 #include <windows.h> #define snprintf _snprintf #endif #include "PI.h" #include <string> #include <math.h> #include "../../MMDevice/ModuleInterface.h" #include <sstream> const char* g_PI_ZStageDeviceName = "PIZStage"; const char* g_PI_ZStageAxisName = "Axis"; const char* g_PropertyMaxUm = "MaxZ_um"; const char* g_PropertyWaitForResponse = "WaitForResponse"; const char* g_Yes = "Yes"; const char* g_No = "No"; const char* g_LocalControl = "Local: Frontpanel control"; const char* g_RemoteControl = "Remote: Interface commands mode"; using namespace std; /////////////////////////////////////////////////////////////////////////////// // Exported MMDevice API /////////////////////////////////////////////////////////////////////////////// MODULE_API void InitializeModuleData() { RegisterDevice(g_PI_ZStageDeviceName, MM::StageDevice, "PI E-662 Z-stage"); } MODULE_API MM::Device* CreateDevice(const char* deviceName) { if (deviceName == 0) return 0; if (strcmp(deviceName, g_PI_ZStageDeviceName) == 0) { PIZStage* s = new PIZStage(); return s; } return 0; } MODULE_API void DeleteDevice(MM::Device* pDevice) { delete pDevice; } // General utility function: int ClearPort(MM::Device& device, MM::Core& core, std::string port) { // Clear contents of serial port const unsigned int bufSize = 255; unsigned char clear[bufSize]; unsigned long read = bufSize; int ret; while (read == bufSize) { ret = core.ReadFromSerial(&device, port.c_str(), clear, bufSize, read); if (ret != DEVICE_OK) return ret; } return DEVICE_OK; } /////////////////////////////////////////////////////////////////////////////// // PIZStage PIZStage::PIZStage() : port_("Undefined"), stepSizeUm_(0.1), initialized_(false), answerTimeoutMs_(1000), pos_(0.0) { InitializeDefaultErrorMessages(); // create pre-initialization properties // ------------------------------------ // Name CreateProperty(MM::g_Keyword_Name, g_PI_ZStageDeviceName, MM::String, true); // Description CreateProperty(MM::g_Keyword_Description, "Physik Instrumente (PI) E-662 Adapter", MM::String, true); // Port CPropertyAction* pAct = new CPropertyAction (this, &PIZStage::OnPort); CreateProperty(MM::g_Keyword_Port, "Undefined", MM::String, false, pAct, true); CreateProperty(g_PropertyMaxUm, "500.0", MM::Float, false, 0, true); CreateProperty(g_PropertyWaitForResponse, g_Yes, MM::String, false, 0, true); AddAllowedValue(g_PropertyWaitForResponse, g_Yes); AddAllowedValue(g_PropertyWaitForResponse, g_No); } PIZStage::~PIZStage() { Shutdown(); } void PIZStage::GetName(char* Name) const { CDeviceUtils::CopyLimitedString(Name, g_PI_ZStageDeviceName); } int PIZStage::Initialize() { // switch on servo, otherwise "MOV" will fail /* ostringstream command; command << "SVO " << axisName_<<" 1"; int ret = SendSerialCommand(port_.c_str(), command.str().c_str(), "\n"); if (ret != DEVICE_OK) return ret; CDeviceUtils::SleepMs(10); */ int ret = GetPositionSteps(curSteps_); if (ret != DEVICE_OK) return ret; // StepSize CPropertyAction* pAct = new CPropertyAction (this, &PIZStage::OnStepSizeUm); CreateProperty("StepSizeUm", "0.01", MM::Float, false, pAct); stepSizeUm_ = 0.01; // Remote/Local pAct = new CPropertyAction (this, &PIZStage::OnInterface); CreateProperty("Interface", "Computer", MM::String, false, pAct); AddAllowedValue("Interface", g_RemoteControl); AddAllowedValue("Interface", g_LocalControl); pAct = new CPropertyAction (this, &PIZStage::OnPosition); CreateProperty(MM::g_Keyword_Position, "0.0", MM::Float, false, pAct); double upperLimit = getAxisLimit(); if (upperLimit > 0.0) SetPropertyLimits(MM::g_Keyword_Position, 0.0, upperLimit); ret = UpdateStatus(); if (ret != DEVICE_OK) return ret; initialized_ = true; return DEVICE_OK; } int PIZStage::Shutdown() { if (initialized_) { initialized_ = false; } return DEVICE_OK; } bool PIZStage::Busy() { // never busy because all commands block return false; } int PIZStage::SetPositionSteps(long steps) { double pos = steps * stepSizeUm_; return SetPositionUm(pos); } int PIZStage::GetPositionSteps(long& steps) { double pos; int ret = GetPositionUm(pos); if (ret != DEVICE_OK) return ret; steps = (long) ((pos / stepSizeUm_) + 0.5); return DEVICE_OK; } int PIZStage::SetPositionUm(double pos) { ostringstream command; command << "POS " << axisName_<< " " << pos; // send command int ret = SendSerialCommand(port_.c_str(), command.str().c_str(), "\n"); if (ret != DEVICE_OK) return ret; CDeviceUtils::SleepMs(10); if (waitForResponse()) { // block/wait for acknowledge, or until we time out; ret = SendSerialCommand(port_.c_str(), "ERR?", "\n"); if (ret != DEVICE_OK) return ret; string answer; ret = GetSerialAnswer(port_.c_str(), "\n", answer); if (ret != DEVICE_OK) return ret; int errNo = atoi(answer.c_str()); if (errNo == 0) return DEVICE_OK; return ERR_OFFSET + errNo; } else { pos_ = pos; return DEVICE_OK; } } int PIZStage::GetPositionUm(double& pos) { if (waitForResponse()) { ostringstream command; command << "POS? " << axisName_; // send command int ret = SendSerialCommand(port_.c_str(), command.str().c_str(), "\n"); if (ret != DEVICE_OK) return ret; // block/wait for acknowledge, or until we time out; string answer; ret = GetSerialAnswer(port_.c_str(), "\n", answer); if (ret != DEVICE_OK) return ret; if (!GetValue(answer, pos)) return ERR_UNRECOGNIZED_ANSWER; } else { pos = pos_; } return DEVICE_OK; } int PIZStage::SetOrigin() { return DEVICE_UNSUPPORTED_COMMAND; } int PIZStage::GetLimits(double&, double&) { return DEVICE_UNSUPPORTED_COMMAND; } /////////////////////////////////////////////////////////////////////////////// // Action handlers /////////////////////////////////////////////////////////////////////////////// int PIZStage::OnPort(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { pProp->Set(port_.c_str()); } else if (eAct == MM::AfterSet) { if (initialized_) { // revert pProp->Set(port_.c_str()); return ERR_PORT_CHANGE_FORBIDDEN; } pProp->Get(port_); } return DEVICE_OK; } int PIZStage::OnStepSizeUm(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { pProp->Set(stepSizeUm_); } else if (eAct == MM::AfterSet) { pProp->Get(stepSizeUm_); } return DEVICE_OK; } int PIZStage::OnInterface(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { // block/wait for acknowledge, or until we time out; if (waitForResponse()) { // send command int ret = SendSerialCommand(port_.c_str(), "DEV:CONT?", "\n"); if (ret != DEVICE_OK) return ret; string answer; ret = GetSerialAnswer(port_.c_str(), "\n", answer); if (ret != DEVICE_OK) return ret; LogMessage(answer.c_str(), false); // NOTE: there are conflicting answers for what strings a device can // return as its control mode (e.g. "Remote interface command control" // vs. "Remote: Interface commands mode"). We should only set values // that match the ones we allow. const string remoteMatch = "Remote"; const string localMatch = "Local"; if (answer.substr(0, remoteMatch.size()) == remoteMatch) { pProp->Set(g_RemoteControl); } else if (answer.substr(0, localMatch.size()) == localMatch) { pProp->Set(g_LocalControl); } else { LogMessage("Unrecognized control mode [" + answer + "]"); } } } else if (eAct == MM::AfterSet) { std::string mode; pProp->Get(mode); ostringstream command; command << "DEV:CONT "; if (mode.compare(g_LocalControl) == 0) command << "LOC"; else command << "REM"; int ret = SendSerialCommand(port_.c_str(), command.str().c_str(), "\n"); if (ret != DEVICE_OK) return ret; } return DEVICE_OK; } int PIZStage::OnPosition(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { double pos; int ret = GetPositionUm(pos); if (ret != DEVICE_OK) return ret; pProp->Set(pos); } else if (eAct == MM::AfterSet) { double pos; pProp->Get(pos); int ret = SetPositionUm(pos); if (ret != DEVICE_OK) return ret; } return DEVICE_OK; } bool PIZStage::GetValue(string& sMessage, double& pos) { // value is after last '=', if any '=' is found size_t p = sMessage.find_last_of('='); if ( p == std::string::npos ) p=0; else p++; // trim whitspaces from right ... p = sMessage.find_last_not_of(" \t\r\n"); if (p != std::string::npos) sMessage.erase(++p); // ... and left p = sMessage.find_first_not_of(" \n\t\r"); if (p != std::string::npos) sMessage.erase(0,p); else return false; char *pend; const char* szMessage = sMessage.c_str(); double dValue = strtod(szMessage, &pend); // return true only if scan was stopped by spaces, linefeed or the terminating NUL and if the // string was not empty to start with if (pend != szMessage) { while( *pend!='\0' && (*pend==' '||*pend=='\n')) pend++; if (*pend=='\0') { pos = dValue; return true; } } return false; } bool PIZStage::waitForResponse() { return IsPropertyEqualTo(g_PropertyWaitForResponse, g_Yes); } double PIZStage::getAxisLimit() { double limit; int ret = GetProperty(g_PropertyMaxUm, limit); if (ret == DEVICE_OK) return limit; else return 0.0; }
/////////////////////////////////////////////////////////////////////////////// // FILE: PI.cpp // PROJECT: Micro-Manager // SUBSYSTEM: DeviceAdapters //----------------------------------------------------------------------------- // DESCRIPTION: PI Controller Driver // // AUTHOR: Nenad Amodaj, [email protected], 08/28/2006 // Steffen Rau, [email protected], 10/03/2008 // Nico Stuurman, [email protected], 3/19/2008 // COPYRIGHT: University of California, San Francisco, 2006, 2008 // Physik Instrumente (PI) GmbH & Co. KG, 2008 // LICENSE: This file is distributed under the BSD license. // License text is included with the source distribution. // // This file 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. // // IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES. // CVS: $Id: Nikon.cpp 574 2007-11-07 21:00:45Z nenad $ // #ifdef WIN32 #include <windows.h> #define snprintf _snprintf #endif #include "PI.h" #include <string> #include <math.h> #include "../../MMDevice/ModuleInterface.h" #include <sstream> const char* g_PI_ZStageDeviceName = "PIZStage"; const char* g_PI_ZStageAxisName = "Axis"; const char* g_PropertyMaxUm = "MaxZ_um"; const char* g_PropertyWaitForResponse = "WaitForResponse"; const char* g_Yes = "Yes"; const char* g_No = "No"; const char* g_LocalControl = "Local: Frontpanel control"; const char* g_RemoteControl = "Remote: Interface commands mode"; using namespace std; /////////////////////////////////////////////////////////////////////////////// // Exported MMDevice API /////////////////////////////////////////////////////////////////////////////// MODULE_API void InitializeModuleData() { RegisterDevice(g_PI_ZStageDeviceName, MM::StageDevice, "PI E-662 Z-stage"); } MODULE_API MM::Device* CreateDevice(const char* deviceName) { if (deviceName == 0) return 0; if (strcmp(deviceName, g_PI_ZStageDeviceName) == 0) { PIZStage* s = new PIZStage(); return s; } return 0; } MODULE_API void DeleteDevice(MM::Device* pDevice) { delete pDevice; } // General utility function: int ClearPort(MM::Device& device, MM::Core& core, std::string port) { // Clear contents of serial port const unsigned int bufSize = 255; unsigned char clear[bufSize]; unsigned long read = bufSize; int ret; while (read == bufSize) { ret = core.ReadFromSerial(&device, port.c_str(), clear, bufSize, read); if (ret != DEVICE_OK) return ret; } return DEVICE_OK; } /////////////////////////////////////////////////////////////////////////////// // PIZStage PIZStage::PIZStage() : port_("Undefined"), stepSizeUm_(0.1), initialized_(false), answerTimeoutMs_(1000), pos_(0.0) { InitializeDefaultErrorMessages(); // create pre-initialization properties // ------------------------------------ // Name CreateProperty(MM::g_Keyword_Name, g_PI_ZStageDeviceName, MM::String, true); // Description CreateProperty(MM::g_Keyword_Description, "Physik Instrumente (PI) E-662 Adapter", MM::String, true); // Port CPropertyAction* pAct = new CPropertyAction (this, &PIZStage::OnPort); CreateProperty(MM::g_Keyword_Port, "Undefined", MM::String, false, pAct, true); CreateProperty(g_PropertyMaxUm, "500.0", MM::Float, false, 0, true); CreateProperty(g_PropertyWaitForResponse, g_Yes, MM::String, false, 0, true); AddAllowedValue(g_PropertyWaitForResponse, g_Yes); AddAllowedValue(g_PropertyWaitForResponse, g_No); } PIZStage::~PIZStage() { Shutdown(); } void PIZStage::GetName(char* Name) const { CDeviceUtils::CopyLimitedString(Name, g_PI_ZStageDeviceName); } int PIZStage::Initialize() { // Guard against the possibility that invalid input remains in the device's // receive buffer. Since the device may not respond at all to an invalid // command, without the following there is a chance that a timeout error can // occur if garbage got sent to the device before we talk to it. int ret = SendSerialCommand(port_.c_str(), "ERR?", "\n"); if (ret != DEVICE_OK) return ret; std::string answer; ret = GetSerialAnswer(port_.c_str(), "\n", answer); // Ignore errors ret = SendSerialCommand(port_.c_str(), "ERR?", "\n"); if (ret != DEVICE_OK) return ret; ret = GetSerialAnswer(port_.c_str(), "\n", answer); // Ignore errors // switch on servo, otherwise "MOV" will fail /* ostringstream command; command << "SVO " << axisName_<<" 1"; int ret = SendSerialCommand(port_.c_str(), command.str().c_str(), "\n"); if (ret != DEVICE_OK) return ret; CDeviceUtils::SleepMs(10); */ ret = GetPositionSteps(curSteps_); if (ret != DEVICE_OK) return ret; // StepSize CPropertyAction* pAct = new CPropertyAction (this, &PIZStage::OnStepSizeUm); CreateProperty("StepSizeUm", "0.01", MM::Float, false, pAct); stepSizeUm_ = 0.01; // Remote/Local pAct = new CPropertyAction (this, &PIZStage::OnInterface); CreateProperty("Interface", "Computer", MM::String, false, pAct); AddAllowedValue("Interface", g_RemoteControl); AddAllowedValue("Interface", g_LocalControl); pAct = new CPropertyAction (this, &PIZStage::OnPosition); CreateProperty(MM::g_Keyword_Position, "0.0", MM::Float, false, pAct); double upperLimit = getAxisLimit(); if (upperLimit > 0.0) SetPropertyLimits(MM::g_Keyword_Position, 0.0, upperLimit); ret = UpdateStatus(); if (ret != DEVICE_OK) return ret; initialized_ = true; return DEVICE_OK; } int PIZStage::Shutdown() { if (initialized_) { initialized_ = false; } return DEVICE_OK; } bool PIZStage::Busy() { // never busy because all commands block return false; } int PIZStage::SetPositionSteps(long steps) { double pos = steps * stepSizeUm_; return SetPositionUm(pos); } int PIZStage::GetPositionSteps(long& steps) { double pos; int ret = GetPositionUm(pos); if (ret != DEVICE_OK) return ret; steps = (long) ((pos / stepSizeUm_) + 0.5); return DEVICE_OK; } int PIZStage::SetPositionUm(double pos) { ostringstream command; command << "POS " << axisName_<< " " << pos; // send command int ret = SendSerialCommand(port_.c_str(), command.str().c_str(), "\n"); if (ret != DEVICE_OK) return ret; CDeviceUtils::SleepMs(10); if (waitForResponse()) { // block/wait for acknowledge, or until we time out; ret = SendSerialCommand(port_.c_str(), "ERR?", "\n"); if (ret != DEVICE_OK) return ret; string answer; ret = GetSerialAnswer(port_.c_str(), "\n", answer); if (ret != DEVICE_OK) return ret; int errNo = atoi(answer.c_str()); if (errNo == 0) return DEVICE_OK; return ERR_OFFSET + errNo; } else { pos_ = pos; return DEVICE_OK; } } int PIZStage::GetPositionUm(double& pos) { if (waitForResponse()) { ostringstream command; command << "POS? " << axisName_; // send command int ret = SendSerialCommand(port_.c_str(), command.str().c_str(), "\n"); if (ret != DEVICE_OK) return ret; // block/wait for acknowledge, or until we time out; string answer; ret = GetSerialAnswer(port_.c_str(), "\n", answer); if (ret != DEVICE_OK) return ret; if (!GetValue(answer, pos)) return ERR_UNRECOGNIZED_ANSWER; } else { pos = pos_; } return DEVICE_OK; } int PIZStage::SetOrigin() { return DEVICE_UNSUPPORTED_COMMAND; } int PIZStage::GetLimits(double&, double&) { return DEVICE_UNSUPPORTED_COMMAND; } /////////////////////////////////////////////////////////////////////////////// // Action handlers /////////////////////////////////////////////////////////////////////////////// int PIZStage::OnPort(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { pProp->Set(port_.c_str()); } else if (eAct == MM::AfterSet) { if (initialized_) { // revert pProp->Set(port_.c_str()); return ERR_PORT_CHANGE_FORBIDDEN; } pProp->Get(port_); } return DEVICE_OK; } int PIZStage::OnStepSizeUm(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { pProp->Set(stepSizeUm_); } else if (eAct == MM::AfterSet) { pProp->Get(stepSizeUm_); } return DEVICE_OK; } int PIZStage::OnInterface(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { // block/wait for acknowledge, or until we time out; if (waitForResponse()) { // send command int ret = SendSerialCommand(port_.c_str(), "DEV:CONT?", "\n"); if (ret != DEVICE_OK) return ret; string answer; ret = GetSerialAnswer(port_.c_str(), "\n", answer); if (ret != DEVICE_OK) return ret; LogMessage(answer.c_str(), false); // NOTE: there are conflicting answers for what strings a device can // return as its control mode (e.g. "Remote interface command control" // vs. "Remote: Interface commands mode"). We should only set values // that match the ones we allow. const string remoteMatch = "Remote"; const string localMatch = "Local"; if (answer.substr(0, remoteMatch.size()) == remoteMatch) { pProp->Set(g_RemoteControl); } else if (answer.substr(0, localMatch.size()) == localMatch) { pProp->Set(g_LocalControl); } else { LogMessage("Unrecognized control mode [" + answer + "]"); } } } else if (eAct == MM::AfterSet) { std::string mode; pProp->Get(mode); ostringstream command; command << "DEV:CONT "; if (mode.compare(g_LocalControl) == 0) command << "LOC"; else command << "REM"; int ret = SendSerialCommand(port_.c_str(), command.str().c_str(), "\n"); if (ret != DEVICE_OK) return ret; } return DEVICE_OK; } int PIZStage::OnPosition(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { double pos; int ret = GetPositionUm(pos); if (ret != DEVICE_OK) return ret; pProp->Set(pos); } else if (eAct == MM::AfterSet) { double pos; pProp->Get(pos); int ret = SetPositionUm(pos); if (ret != DEVICE_OK) return ret; } return DEVICE_OK; } bool PIZStage::GetValue(string& sMessage, double& pos) { // value is after last '=', if any '=' is found size_t p = sMessage.find_last_of('='); if ( p == std::string::npos ) p=0; else p++; // trim whitspaces from right ... p = sMessage.find_last_not_of(" \t\r\n"); if (p != std::string::npos) sMessage.erase(++p); // ... and left p = sMessage.find_first_not_of(" \n\t\r"); if (p != std::string::npos) sMessage.erase(0,p); else return false; char *pend; const char* szMessage = sMessage.c_str(); double dValue = strtod(szMessage, &pend); // return true only if scan was stopped by spaces, linefeed or the terminating NUL and if the // string was not empty to start with if (pend != szMessage) { while( *pend!='\0' && (*pend==' '||*pend=='\n')) pend++; if (*pend=='\0') { pos = dValue; return true; } } return false; } bool PIZStage::waitForResponse() { return IsPropertyEqualTo(g_PropertyWaitForResponse, g_Yes); } double PIZStage::getAxisLimit() { double limit; int ret = GetProperty(g_PropertyMaxUm, limit); if (ret == DEVICE_OK) return limit; else return 0.0; }
Add safeguard to prevent initial comm errors
PI: Add safeguard to prevent initial comm errors git-svn-id: 03a8048b5ee8463be5048a3801110fb50f378627@15627 d0ab736e-dc22-4aeb-8dc9-08def0aa14fd
C++
mit
kmdouglass/Micro-Manager,kmdouglass/Micro-Manager
28c8f0b1941e851caeeb48ef4a70a833f4a9ea9f
tests/serial/many_variables_recursive.cpp
tests/serial/many_variables_recursive.cpp
/* Tests that transfer logic of a cell with multiple cells as variables works. Copyright (c) 2013, 2014, Ilja Honkonen 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 copyright holders nor the names of their 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 "array" #include "cstdlib" #include "iostream" #include "tuple" #include "vector" #include "check_true.hpp" #include "gensimcell.hpp" using namespace std; struct test_variable1 { using data_type = int; }; struct test_variable2 { using data_type = float; }; struct test_variable3 { using data_type = std::array<char, 2>; }; struct test_variable4 { using data_type = gensimcell::Cell< test_variable1, test_variable2, test_variable3 >; }; struct test_variable5 { using data_type = gensimcell::Cell< test_variable1, test_variable4 >; }; struct test_variable6 { using data_type = gensimcell::Cell< test_variable4, test_variable5 >; }; int main(int, char**) { const test_variable1 v1; const test_variable2 v2; const test_variable3 v3; const test_variable4 v4; const test_variable5 v5; const test_variable6 v6; gensimcell::Cell<test_variable4> cell4; cell4[v4][v1] = 3; cell4[v4][v2] = 1.5; cell4[v4][v3] = {'a', 'b'}; CHECK_TRUE(cell4[v4][v1] == 3) CHECK_TRUE(cell4[v4][v2] == 1.5) CHECK_TRUE(cell4[v4][v3][0] == 'a') CHECK_TRUE(cell4[v4][v3][1] == 'b') gensimcell::Cell<test_variable5> cell5; cell5[v5][v1] = 4; cell5[v5][v4][v1] = 5; cell5[v5][v4][v2] = 2.5; cell5[v5][v4][v3] = {'c', 'd'}; CHECK_TRUE(cell5[v5][v1] == 4) CHECK_TRUE(cell5[v5][v4][v1] == 5) CHECK_TRUE(cell5[v5][v4][v2] == 2.5) CHECK_TRUE(cell5[v5][v4][v3][0] == 'c') CHECK_TRUE(cell5[v5][v4][v3][1] == 'd') gensimcell::Cell<test_variable6> cell6; cell6[v6][v4][v1] = 6; cell6[v6][v4][v2] = 4.5; cell6[v6][v4][v3] = {'e', 'f'}; cell6[v6][v5][v1] = 7; cell6[v6][v5][v4][v1] = 8; cell6[v6][v5][v4][v2] = 8.5; cell6[v6][v5][v4][v3] = {'g', 'h'}; CHECK_TRUE(cell6[v6][v4][v1] == 6) CHECK_TRUE(cell6[v6][v4][v2] == 4.5) CHECK_TRUE(cell6[v6][v4][v3][0] == 'e') CHECK_TRUE(cell6[v6][v4][v3][1] == 'f') CHECK_TRUE(cell6[v6][v5][v1] == 7) CHECK_TRUE(cell6[v6][v5][v4][v1] == 8) CHECK_TRUE(cell6[v6][v5][v4][v2] == 8.5) CHECK_TRUE(cell6[v6][v5][v4][v3][0] == 'g') CHECK_TRUE(cell6[v6][v5][v4][v3][1] == 'h') return EXIT_SUCCESS; }
/* Tests that transfer logic of a cell with multiple cells as variables works. Copyright (c) 2013, 2014, Ilja Honkonen 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 copyright holders nor the names of their 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 "array" #include "cstdlib" #include "iostream" #include "tuple" #include "vector" #include "check_true.hpp" #include "gensimcell.hpp" using namespace std; struct test_variable1 { using data_type = int; }; struct test_variable2 { using data_type = float; }; struct test_variable3 { using data_type = std::array<char, 2>; }; struct test_variable4 { using data_type = gensimcell::Cell< test_variable1, test_variable2, test_variable3 >; }; struct test_variable5 { using data_type = gensimcell::Cell< test_variable1, test_variable4 >; }; struct test_variable6 { using data_type = gensimcell::Cell< test_variable4, test_variable5 >; }; int main(int, char**) { const test_variable1 v1{}; const test_variable2 v2{}; const test_variable3 v3{}; const test_variable4 v4{}; const test_variable5 v5{}; const test_variable6 v6{}; gensimcell::Cell<test_variable4> cell4; cell4[v4][v1] = 3; cell4[v4][v2] = 1.5; cell4[v4][v3] = {'a', 'b'}; CHECK_TRUE(cell4[v4][v1] == 3) CHECK_TRUE(cell4[v4][v2] == 1.5) CHECK_TRUE(cell4[v4][v3][0] == 'a') CHECK_TRUE(cell4[v4][v3][1] == 'b') gensimcell::Cell<test_variable5> cell5; cell5[v5][v1] = 4; cell5[v5][v4][v1] = 5; cell5[v5][v4][v2] = 2.5; cell5[v5][v4][v3] = {'c', 'd'}; CHECK_TRUE(cell5[v5][v1] == 4) CHECK_TRUE(cell5[v5][v4][v1] == 5) CHECK_TRUE(cell5[v5][v4][v2] == 2.5) CHECK_TRUE(cell5[v5][v4][v3][0] == 'c') CHECK_TRUE(cell5[v5][v4][v3][1] == 'd') gensimcell::Cell<test_variable6> cell6; cell6[v6][v4][v1] = 6; cell6[v6][v4][v2] = 4.5; cell6[v6][v4][v3] = {'e', 'f'}; cell6[v6][v5][v1] = 7; cell6[v6][v5][v4][v1] = 8; cell6[v6][v5][v4][v2] = 8.5; cell6[v6][v5][v4][v3] = {'g', 'h'}; CHECK_TRUE(cell6[v6][v4][v1] == 6) CHECK_TRUE(cell6[v6][v4][v2] == 4.5) CHECK_TRUE(cell6[v6][v4][v3][0] == 'e') CHECK_TRUE(cell6[v6][v4][v3][1] == 'f') CHECK_TRUE(cell6[v6][v5][v1] == 7) CHECK_TRUE(cell6[v6][v5][v4][v1] == 8) CHECK_TRUE(cell6[v6][v5][v4][v2] == 8.5) CHECK_TRUE(cell6[v6][v5][v4][v3][0] == 'g') CHECK_TRUE(cell6[v6][v5][v4][v3][1] == 'h') return EXIT_SUCCESS; }
Make many_variables_recursive.cpp compile with clang 3.4.
Make many_variables_recursive.cpp compile with clang 3.4.
C++
bsd-3-clause
nasailja/gensimcell
ee66a6006eb37e386be23ffb82e02a072304d1c5
native/sandbox.cc
native/sandbox.cc
#include <string> #include <iostream> #include <functional> #include <system_error> #include <vector> #include <cstring> #include <boost/filesystem.hpp> #include <boost/format.hpp> #include <libcgroup.h> #include <fcntl.h> #include <sched.h> #include <signal.h> #include <unistd.h> #include <sys/types.h> #include <syscall.h> #include <pwd.h> #include <sys/time.h> #include <sys/resource.h> #include <sys/mount.h> #include <sys/wait.h> #include "sandbox.h" #include "utils.h" #include "cgroup.h" #include "semaphore.h" #include "pipe.h" namespace fs = boost::filesystem; using std::string; using std::vector; using boost::format; static void RedirectIO(const string &std_input, const string &std_output, const string &std_error, int nullfd) { int inputfd, outputfd, errorfd; if (std_input != "") { inputfd = Ensure(open(std_input.c_str(), O_RDONLY)); } else { inputfd = nullfd; } Ensure(dup2(inputfd, STDIN_FILENO)); if (std_output != "") { outputfd = Ensure(open(std_output.c_str(), O_WRONLY | O_TRUNC | O_CREAT, S_IWUSR | S_IRUSR | S_IRGRP | S_IWGRP)); } else { outputfd = nullfd; } Ensure(dup2(outputfd, STDOUT_FILENO)); if (std_error != "") { if (std_error == std_output) { errorfd = outputfd; } else { errorfd = Ensure(open(std_error.c_str(), O_WRONLY | O_TRUNC | O_CREAT, S_IWUSR | S_IRUSR | S_IRGRP | S_IWGRP)); } } else { errorfd = nullfd; } Ensure(dup2(errorfd, STDERR_FILENO)); } struct ExecutionParameter { const SandboxParameter &parameter; PosixSemaphore semaphore1, semaphore2; // This pipe is used to forward error message from the child process to the parent. PosixPipe pipefd; ExecutionParameter(const SandboxParameter &param, int pipeOptions) : parameter(param), semaphore1(true, 0), semaphore2(true, 0), pipefd(pipeOptions) { } }; static int ChildProcess(void *param_ptr) { ExecutionParameter &execParam = *reinterpret_cast<ExecutionParameter *>(param_ptr); // We obtain a full copy of parameters here. The arguments may be destoryed after some time. SandboxParameter parameter = execParam.parameter; try { Ensure(close(execParam.pipefd[0])); passwd *newUser = nullptr; if (parameter.userName != "") { // Get the user info before chroot, or it will be unable to open /etc/passwd newUser = CheckNull(getpwnam(parameter.userName.c_str())); } int nullfd = Ensure(open("/dev/null", O_RDWR)); if (parameter.redirectBeforeChroot) { RedirectIO(parameter.stdinRedirection, parameter.stdoutRedirection, parameter.stderrRedirection, nullfd); } fs::path tempRoot("/tmp"); Ensure(mount("none", "/", NULL, MS_REC | MS_PRIVATE, NULL)); // Make root private Ensure(mount(parameter.chrootDirectory.string().c_str(), tempRoot.string().c_str(), "", MS_BIND | MS_REC, "")); Ensure(mount("", tempRoot.string().c_str(), "", MS_BIND | MS_REMOUNT | MS_RDONLY | MS_REC, "")); if (parameter.binaryDirectory != "") { Ensure(mount(parameter.binaryDirectory.string().c_str(), // Source directory (tempRoot / fs::path("sandbox/binary")).c_str(), // Target Directory "", MS_BIND | MS_REC, "")); Ensure(mount("", (tempRoot / fs::path("sandbox/binary")).c_str(), "", MS_BIND | MS_REMOUNT | MS_RDONLY | MS_REC, "")); } if (parameter.workingDirectory != "") { Ensure(mount(parameter.workingDirectory.string().c_str(), (tempRoot / fs::path("sandbox/working")).c_str(), "", MS_BIND | MS_REC, "")); } Ensure(chroot(tempRoot.string().c_str())); Ensure(chdir("/sandbox/working")); if (parameter.mountProc) { Ensure(mount("proc", "/proc", "proc", 0, NULL)); } if (!parameter.redirectBeforeChroot) { RedirectIO(parameter.stdinRedirection, parameter.stdoutRedirection, parameter.stderrRedirection, nullfd); } const char *newHostname = "BraveNewWorld"; Ensure(sethostname(newHostname, strlen(newHostname))); if (newUser != nullptr) { Ensure(setgid(newUser->pw_gid)); Ensure(setuid(newUser->pw_uid)); } /* std::vector<char *> paramCStrings; for (size_t i = 0; i < parameter.executableParameters.size(); ++i) paramCStrings.push_back( const_cast<char *>(parameter.executableParameters[i].c_str())); paramCStrings.push_back(nullptr); */ vector<char *> params = StringToPtr(parameter.executableParameters), envi = StringToPtr(parameter.environmentVariables); /* // Pause here to let the parent to dd me to the cgroup. // For some unknown reason, `raise(SIGSTOP)` won't work // (return 0 but no effect, i.e. the process keeps running.) // I changed to use semaphore, if you can help with this problem, please post an issue. Ensure(kill(getpid(), SIGSTOP)); */ int temp = -1; // Inform the parent that no exception occurred. Ensure(write(execParam.pipefd[1], &temp, sizeof(int))); // Inform our parent that we are ready to go. execParam.semaphore1.Post(); // Wait for parent's reply. execParam.semaphore2.Wait(); Ensure(execve(parameter.executablePath.c_str(), &params[0], &envi[0])); // If execve returns, then we meet an error. raise(SIGABRT); return 255; } catch (std::exception &err) { // TODO: implement error handling // abort(); // This will cause segmentation fault. // throw; // return 222; const char *errMessage = err.what(); int len = strlen(errMessage); try { Ensure(write(execParam.pipefd[1], &len, sizeof(int))); Ensure(write(execParam.pipefd[1], errMessage, len)); Ensure(close(execParam.pipefd[1])); execParam.semaphore1.Post(); return 126; } catch (...) { return 125; } } catch (...) { return 125; } } // The child stack is only used before `execve`, so it does not need much space. const int childStackSize = 1024 * 700; pid_t StartSandbox(const SandboxParameter &parameter /* ,std::function<void(pid_t)> reportPid*/) // Let's use some fancy C++11 feature. { pid_t container_pid = -1; try { // char* childStack = new char[childStackSize]; std::vector<char> *childStack = new std::vector<char>(childStackSize); // I don't want to call `delete` ExecutionParameter execParam(parameter, O_CLOEXEC | O_NONBLOCK); container_pid = Ensure(clone(ChildProcess, &*childStack->end(), CLONE_NEWNET | CLONE_NEWUTS | CLONE_NEWPID | CLONE_NEWNS | SIGCHLD, const_cast<void *>(reinterpret_cast<const void *>(&execParam)))); CgroupInfo memInfo("memory", parameter.cgroupName), cpuInfo("cpuacct", parameter.cgroupName), pidInfo("pids", parameter.cgroupName); vector<CgroupInfo *> infos = {&memInfo, &cpuInfo, &pidInfo}; for (auto &item : infos) { CreateGroup(*item); KillGroupMembers(*item); WriteGroupProperty(*item, "tasks", container_pid); } #define WRITETO(__where, __name, __value) \ { \ if ((__value) >= 0) \ { \ WriteGroupProperty((__where), (__name), (__value)); \ } \ else \ { \ WriteGroupProperty((__where), (__name), string("max")); \ } \ } // Forcibly clear the cache by limit the usage to 0. WRITETO(memInfo, "memory.force_empty", 0); if (parameter.memoryLimit != -1) { WRITETO(memInfo, "memory.limit_in_bytes", parameter.memoryLimit); WRITETO(memInfo, "memory.memsw.limit_in_bytes", parameter.memoryLimit); } if (parameter.processLimit != -1) { WRITETO(pidInfo, "pids.max", parameter.processLimit); } // Wait for at most 100ms. If the child process hasn't posted the semaphore, // We will assume that the child has already dead. bool waitResult = execParam.semaphore1.TimedWait(0, 100 * 1000 * 1000); int errLen, bytesRead = read(execParam.pipefd[0], &errLen, sizeof(int)); // Child will be killed once the error has been thrown. if (!waitResult || bytesRead == 0 || bytesRead == -1) { // No information available. throw std::runtime_error("The child process has exited unexpectedly."); } else if (errLen != -1) // -1 indicates OK. { vector<char> buf(errLen); Ensure(read(execParam.pipefd[0], &*buf.begin(), errLen)); string errstr(buf.begin(), buf.end()); throw std::runtime_error((format("The child process has reported the following error: %1%") % errstr).str()); } // Clear usage stats. WriteGroupProperty(memInfo, "memory.memsw.max_usage_in_bytes", 0); WriteGroupProperty(cpuInfo, "cpuacct.usage", 0); // Continue the child. execParam.semaphore2.Post(); /* // `raise(SIGSTOP)` won't work as described above. We use semaphores instead. int status; Ensure(waitpid(container_pid, &status, WUNTRACED)); if (WIFSIGNALED(status)) { throw std::runtime_error( (format("The child process has been terminated before starting. Termination signal: %1%") % WTERMSIG(status)).str()); } else if (WIFEXITED(status)) { // Here, we know the child encounters some errors. int errLen, bytesRead = Ensure(read(execParam.pipefd[0], &errLen, sizeof(int))); if (WEXITSTATUS(status) != 126 || bytesRead == 0) { // No error information available. throw std::runtime_error("The child process has exited unexpectedly."); } else { vector<char> buf(errLen + 1); Ensure(read(execParam.pipefd[0], &*buf.begin(), errLen)); buf[errLen] = '\0'; string errstr(buf.begin(), buf.end()); throw std::runtime_error((format("The child process has reported the following error: %1%") % errstr).str()); } } // This is not killing, but just to send a continue signal to resume execution. Ensure(kill(container_pid, SIGCONT)); */ return container_pid; } catch (std::exception &ex) { // Do the cleanups; we don't care whether these operations are successful. if (container_pid != -1) { (void)kill(container_pid, SIGKILL); (void)waitpid(container_pid, NULL, WNOHANG); } throw; } } ExecutionResult SBWaitForProcess(pid_t pid) { ExecutionResult result; int status; Ensure(waitpid(pid, &status, 0)); if (WIFEXITED(status)) { result.Status = EXITED; result.Code = WEXITSTATUS(status); } else if (WIFSIGNALED(status)) { result.Status = SIGNALED; result.Code = WTERMSIG(status); } return result; }
#include <string> #include <iostream> #include <functional> #include <system_error> #include <vector> #include <cstring> #include <boost/filesystem.hpp> #include <boost/format.hpp> #include <libcgroup.h> #include <fcntl.h> #include <sched.h> #include <signal.h> #include <unistd.h> #include <sys/types.h> #include <syscall.h> #include <pwd.h> #include <sys/time.h> #include <sys/resource.h> #include <sys/mount.h> #include <sys/wait.h> #include "sandbox.h" #include "utils.h" #include "cgroup.h" #include "semaphore.h" #include "pipe.h" namespace fs = boost::filesystem; using std::string; using std::vector; using boost::format; static void RedirectIO(const string &std_input, const string &std_output, const string &std_error, int nullfd) { int inputfd, outputfd, errorfd; if (std_input != "") { inputfd = Ensure(open(std_input.c_str(), O_RDONLY)); } else { inputfd = nullfd; } Ensure(dup2(inputfd, STDIN_FILENO)); if (std_output != "") { outputfd = Ensure(open(std_output.c_str(), O_WRONLY | O_TRUNC | O_CREAT, S_IWUSR | S_IRUSR | S_IRGRP | S_IWGRP)); } else { outputfd = nullfd; } Ensure(dup2(outputfd, STDOUT_FILENO)); if (std_error != "") { if (std_error == std_output) { errorfd = outputfd; } else { errorfd = Ensure(open(std_error.c_str(), O_WRONLY | O_TRUNC | O_CREAT, S_IWUSR | S_IRUSR | S_IRGRP | S_IWGRP)); } } else { errorfd = nullfd; } Ensure(dup2(errorfd, STDERR_FILENO)); } struct ExecutionParameter { const SandboxParameter &parameter; PosixSemaphore semaphore1, semaphore2; // This pipe is used to forward error message from the child process to the parent. PosixPipe pipefd; ExecutionParameter(const SandboxParameter &param, int pipeOptions) : parameter(param), semaphore1(true, 0), semaphore2(true, 0), pipefd(pipeOptions) { } }; static int ChildProcess(void *param_ptr) { ExecutionParameter &execParam = *reinterpret_cast<ExecutionParameter *>(param_ptr); // We obtain a full copy of parameters here. The arguments may be destoryed after some time. SandboxParameter parameter = execParam.parameter; try { Ensure(close(execParam.pipefd[0])); passwd *newUser = nullptr; if (parameter.userName != "") { // Get the user info before chroot, or it will be unable to open /etc/passwd newUser = CheckNull(getpwnam(parameter.userName.c_str())); } int nullfd = Ensure(open("/dev/null", O_RDWR)); if (parameter.redirectBeforeChroot) { RedirectIO(parameter.stdinRedirection, parameter.stdoutRedirection, parameter.stderrRedirection, nullfd); } fs::path tempRoot("/tmp"); Ensure(mount("none", "/", NULL, MS_REC | MS_PRIVATE, NULL)); // Make root private Ensure(mount(parameter.chrootDirectory.string().c_str(), tempRoot.string().c_str(), "", MS_BIND | MS_REC, "")); Ensure(mount("", tempRoot.string().c_str(), "", MS_BIND | MS_REMOUNT | MS_RDONLY | MS_REC, "")); if (parameter.binaryDirectory != "") { Ensure(mount(parameter.binaryDirectory.string().c_str(), // Source directory (tempRoot / fs::path("sandbox/binary")).c_str(), // Target Directory "", MS_BIND | MS_REC, "")); Ensure(mount("", (tempRoot / fs::path("sandbox/binary")).c_str(), "", MS_BIND | MS_REMOUNT | MS_RDONLY | MS_REC, "")); } if (parameter.workingDirectory != "") { Ensure(mount(parameter.workingDirectory.string().c_str(), (tempRoot / fs::path("sandbox/working")).c_str(), "", MS_BIND | MS_REC, "")); } Ensure(chroot(tempRoot.string().c_str())); Ensure(chdir("/sandbox/working")); if (parameter.mountProc) { Ensure(mount("proc", "/proc", "proc", 0, NULL)); } if (!parameter.redirectBeforeChroot) { RedirectIO(parameter.stdinRedirection, parameter.stdoutRedirection, parameter.stderrRedirection, nullfd); } const char *newHostname = "BraveNewWorld"; Ensure(sethostname(newHostname, strlen(newHostname))); if (newUser != nullptr) { Ensure(setgid(newUser->pw_gid)); Ensure(setuid(newUser->pw_uid)); } /* std::vector<char *> paramCStrings; for (size_t i = 0; i < parameter.executableParameters.size(); ++i) paramCStrings.push_back( const_cast<char *>(parameter.executableParameters[i].c_str())); paramCStrings.push_back(nullptr); */ vector<char *> params = StringToPtr(parameter.executableParameters), envi = StringToPtr(parameter.environmentVariables); /* // Pause here to let the parent to dd me to the cgroup. // For some unknown reason, `raise(SIGSTOP)` won't work // (return 0 but no effect, i.e. the process keeps running.) // I changed to use semaphore, if you can help with this problem, please post an issue. Ensure(kill(getpid(), SIGSTOP)); */ int temp = -1; // Inform the parent that no exception occurred. Ensure(write(execParam.pipefd[1], &temp, sizeof(int))); // Inform our parent that we are ready to go. execParam.semaphore1.Post(); // Wait for parent's reply. execParam.semaphore2.Wait(); Ensure(execve(parameter.executablePath.c_str(), &params[0], &envi[0])); // If execve returns, then we meet an error. raise(SIGABRT); return 255; } catch (std::exception &err) { // TODO: implement error handling // abort(); // This will cause segmentation fault. // throw; // return 222; const char *errMessage = err.what(); int len = strlen(errMessage); try { Ensure(write(execParam.pipefd[1], &len, sizeof(int))); Ensure(write(execParam.pipefd[1], errMessage, len)); Ensure(close(execParam.pipefd[1])); execParam.semaphore1.Post(); return 126; } catch (...) { return 125; } } catch (...) { return 125; } } // The child stack is only used before `execve`, so it does not need much space. const int childStackSize = 1024 * 700; pid_t StartSandbox(const SandboxParameter &parameter /* ,std::function<void(pid_t)> reportPid*/) // Let's use some fancy C++11 feature. { pid_t container_pid = -1; try { // char* childStack = new char[childStackSize]; std::vector<char> *childStack = new std::vector<char>(childStackSize); // I don't want to call `delete` ExecutionParameter execParam(parameter, O_CLOEXEC | O_NONBLOCK); container_pid = Ensure(clone(ChildProcess, &*childStack->end(), CLONE_NEWNET | CLONE_NEWUTS | CLONE_NEWPID | CLONE_NEWNS | SIGCHLD, const_cast<void *>(reinterpret_cast<const void *>(&execParam)))); CgroupInfo memInfo("memory", parameter.cgroupName), cpuInfo("cpuacct", parameter.cgroupName), pidInfo("pids", parameter.cgroupName); vector<CgroupInfo *> infos = {&memInfo, &cpuInfo, &pidInfo}; for (auto &item : infos) { CreateGroup(*item); KillGroupMembers(*item); WriteGroupProperty(*item, "tasks", container_pid); } #define WRITETO(__where, __name, __value) \ { \ if ((__value) >= 0) \ { \ WriteGroupProperty((__where), (__name), (__value)); \ } \ else \ { \ WriteGroupProperty((__where), (__name), string("max")); \ } \ } // Forcibly clear any memory usage by cache. WRITETO(memInfo, "memory.force_empty", 0); if (parameter.memoryLimit != -1) { WRITETO(memInfo, "memory.limit_in_bytes", parameter.memoryLimit); WRITETO(memInfo, "memory.memsw.limit_in_bytes", parameter.memoryLimit); } if (parameter.processLimit != -1) { WRITETO(pidInfo, "pids.max", parameter.processLimit); } // Wait for at most 100ms. If the child process hasn't posted the semaphore, // We will assume that the child has already dead. bool waitResult = execParam.semaphore1.TimedWait(0, 100 * 1000 * 1000); int errLen, bytesRead = read(execParam.pipefd[0], &errLen, sizeof(int)); // Child will be killed once the error has been thrown. if (!waitResult || bytesRead == 0 || bytesRead == -1) { // No information available. throw std::runtime_error("The child process has exited unexpectedly."); } else if (errLen != -1) // -1 indicates OK. { vector<char> buf(errLen); Ensure(read(execParam.pipefd[0], &*buf.begin(), errLen)); string errstr(buf.begin(), buf.end()); throw std::runtime_error((format("The child process has reported the following error: %1%") % errstr).str()); } // Clear usage stats. WriteGroupProperty(memInfo, "memory.memsw.max_usage_in_bytes", 0); WriteGroupProperty(cpuInfo, "cpuacct.usage", 0); // Continue the child. execParam.semaphore2.Post(); /* // `raise(SIGSTOP)` won't work as described above. We use semaphores instead. int status; Ensure(waitpid(container_pid, &status, WUNTRACED)); if (WIFSIGNALED(status)) { throw std::runtime_error( (format("The child process has been terminated before starting. Termination signal: %1%") % WTERMSIG(status)).str()); } else if (WIFEXITED(status)) { // Here, we know the child encounters some errors. int errLen, bytesRead = Ensure(read(execParam.pipefd[0], &errLen, sizeof(int))); if (WEXITSTATUS(status) != 126 || bytesRead == 0) { // No error information available. throw std::runtime_error("The child process has exited unexpectedly."); } else { vector<char> buf(errLen + 1); Ensure(read(execParam.pipefd[0], &*buf.begin(), errLen)); buf[errLen] = '\0'; string errstr(buf.begin(), buf.end()); throw std::runtime_error((format("The child process has reported the following error: %1%") % errstr).str()); } } // This is not killing, but just to send a continue signal to resume execution. Ensure(kill(container_pid, SIGCONT)); */ return container_pid; } catch (std::exception &ex) { // Do the cleanups; we don't care whether these operations are successful. if (container_pid != -1) { (void)kill(container_pid, SIGKILL); (void)waitpid(container_pid, NULL, WNOHANG); } throw; } } ExecutionResult SBWaitForProcess(pid_t pid) { ExecutionResult result; int status; Ensure(waitpid(pid, &status, 0)); if (WIFEXITED(status)) { result.Status = EXITED; result.Code = WEXITSTATUS(status); } else if (WIFSIGNALED(status)) { result.Status = SIGNALED; result.Code = WTERMSIG(status); } return result; }
Fix wrong comment.
Fix wrong comment.
C++
mit
t123yh/simple-sandbox,t123yh/simple-sandbox
afbf7f02808ca4395cbbb2226c994e54b3c80a4f
daemon/ssdpwatcher.cpp
daemon/ssdpwatcher.cpp
/* This file is part of the KUPnP library, part of the KDE project. Copyright 2009-2010 Friedrich W. H. Kossebau <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "ssdpwatcher.h" // lib #include "rootdevice.h" // KDE #include <KUrl> // Qt #include <QtNetwork/QUdpSocket> #include <QtCore/QStringList> // C #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #ifndef Q_WS_WIN #include <netinet/in_systm.h> #include <netinet/ip.h> #endif #include <KDebug> namespace UPnP { static const int SSDPPortNumber = 1900; static const char SSDPBroadCastAddress[] = "239.255.255.250"; // copied from KTorrent UPnP, but is it needed? static void joinUPnPMCastGroup( int fd ) { ip_mreq mreq; memset( &mreq, 0, sizeof(ip_mreq) ); inet_aton( SSDPBroadCastAddress, &mreq.imr_multiaddr ); mreq.imr_interface.s_addr = htonl( INADDR_ANY ); #ifndef Q_WS_WIN if( setsockopt(fd,IPPROTO_IP,IP_ADD_MEMBERSHIP,&mreq,sizeof(ip_mreq)) < 0 ) #else if( setsockopt(fd,IPPROTO_IP,IP_ADD_MEMBERSHIP,(char *)&mreq,sizeof(ip_mreq)) < 0 ) #endif kDebug() << "Failed to join multicast group 239.255.255.250"; } static void leaveUPnPMCastGroup( int fd ) { struct ip_mreq mreq; memset( &mreq, 0, sizeof(ip_mreq) ); inet_aton( SSDPBroadCastAddress, &mreq.imr_multiaddr ); mreq.imr_interface.s_addr = htonl( INADDR_ANY ); #ifndef Q_WS_WIN if( setsockopt(fd,IPPROTO_IP,IP_DROP_MEMBERSHIP,&mreq,sizeof(ip_mreq)) < 0 ) #else if( setsockopt(fd,IPPROTO_IP,IP_DROP_MEMBERSHIP,(char *)&mreq,sizeof(ip_mreq)) < 0 ) #endif kDebug() << "Failed to leave multicast group 239.255.255.250"; } SSDPWatcher::SSDPWatcher() : mUdpSocket( new QUdpSocket(this) ) { connect( mUdpSocket, SIGNAL(readyRead()), SLOT(onUdpSocketReadyRead()) ); connect( mUdpSocket, SIGNAL(error( QAbstractSocket::SocketError )), SLOT(onUdpSocketError( QAbstractSocket::SocketError )) ); // try up to ten port numbers TODO: make configurable for( int i = 0; i < 10; ++i ) { if( ! mUdpSocket->bind(SSDPPortNumber+i,QUdpSocket::ShareAddress) ) kDebug() << "Cannot bind to UDP port "<< SSDPPortNumber << ":" << mUdpSocket->errorString(); else break; } // TODO: really needed with QUdpSocket::ShareAddress ? joinUPnPMCastGroup( mUdpSocket->socketDescriptor() ); } void SSDPWatcher::discover() { kDebug() << "Trying to find UPnP devices on the local network"; // send a HTTP M-SEARCH message to 239.255.255.250:1900 const char mSearchMessage[] = "M-SEARCH * HTTP/1.1\r\n" "HOST: 239.255.255.250:1900\r\n" "ST:urn:schemas-upnp-org:device:upnp:rootdevice:1\r\n" // "ST:urn:schemas-upnp-org:device:InternetGatewayDevice:1\r\n" // "ST:urn:schemas-upnp-org:device:WANDevice:1\r\n" "MAN:\"ssdp:discover\"\r\n" "MX:3\r\n" "\r\n"; const int mSearchMessageLength = sizeof(mSearchMessage) / sizeof(mSearchMessage[0]); mUdpSocket->writeDatagram( mSearchMessage, mSearchMessageLength, QHostAddress(SSDPBroadCastAddress), SSDPPortNumber ); } RootDevice* SSDPWatcher::createDeviceFromResponse( const QByteArray& response ) { RootDevice* result = 0; const QStringList lines = QString::fromAscii( response ).split( "\r\n" ); // first read first line and see if contains a HTTP 200 OK message or // "HTTP/1.1 200 OK" // "NOTIFY * HTTP/1.1" const QString firstLine = lines.first(); if( firstLine.contains("HTTP") ) { // it is either a 200 OK or a NOTIFY if( ! firstLine.contains("NOTIFY") && ! firstLine.contains("200 OK") ) return 0; } else return 0; QString server; KUrl location; QString uuid; enum MessageType { SearchAnswer, Notification, UnknownMessage }; enum DeviceState { Alive, ByeBye, OtherState }; DeviceState deviceState = OtherState; MessageType messageType = UnknownMessage; // read all lines and try to find the server and location fields foreach( const QString& line, lines ) { const int separatorIndex = line.indexOf( ':' ); const QString key = line.left( separatorIndex ).toUpper(); const QString value = line.mid( separatorIndex+1 ).trimmed(); if( key == QLatin1String("LOCATION") ) { kDebug()<<"LOCATION:"<<value; location = value; } else if( key == QLatin1String("SERVER") ) { kDebug()<<"SERVER:"<<value; server = value; } else if( key == QLatin1String("ST") ) // search type { kDebug()<<"ST:"<<value; messageType = SearchAnswer; } else if( key == QLatin1String("NT") ) // notification type { kDebug()<<"NT:"<<value; messageType = Notification; } else if( key == QLatin1String("NTS") ) // notification type s? { kDebug()<<"NTS:"<<value; if( value == QLatin1String("ssdp:alive") ) deviceState = Alive; else if( value == QLatin1String("ssdp:byebye") ) deviceState = ByeBye; } // TODO: else if( key == QLatin1String("CACHE-CONTROL") ) // TODO: else if( key == QLatin1String("DATE") ) else if( key == QLatin1String("USN") ) // unique service name { kDebug()<<"USN:"<<value; const int startIndex = 5; const int endIndex = value.lastIndexOf( "::" ); int length = endIndex - startIndex; if( length == 0 ) length = -1; uuid = value.mid( startIndex, length ); } } if( uuid.isEmpty() ) { kDebug()<<"No uuid found!"; } else if( location.isEmpty() ) { kDebug()<<"No location found!"; } else if( deviceState == OtherState && messageType == Notification ) { kDebug()<<"NTS neither alive nor byebye"; } else if( mDevices.contains(uuid) ) { kDebug()<<"Already inserted:"<<uuid<<"!"; } #if 0 else if( ! mBrowsedDeviceTypes.isEmpty() && ! mBrowsedDeviceTypes.contains(devicePrivate->type()) ) { kDebug()<<"Not interested in:"<<devicePrivate->type(); devicePrivate->setInvalid(); } #endif else { kDebug() << "Detected Device:" << server << "UUID" << uuid; // everything OK, make a new Device result = new RootDevice( server, location, uuid ); } return result; } void SSDPWatcher::onDescriptionDownloadDone( RootDevice* device, bool success ) { mPendingDevices.remove( device ); if( ! success ) device->deleteLater(); else if( mDevices.contains(device->uuid()) ) device->deleteLater(); else { mDevices.insert( device->uuid(), device ); kDebug()<< "Added:"<<device->name()<<device->uuid(); emit deviceDiscovered( device ); } } void SSDPWatcher::onUdpSocketReadyRead() { const int pendingDatagramSize = mUdpSocket->pendingDatagramSize(); QByteArray response( pendingDatagramSize, 0 ); const int bytesRead = mUdpSocket->readDatagram( response.data(), pendingDatagramSize ); if( bytesRead == -1 ) // TODO: error handling return; RootDevice* device = createDeviceFromResponse( response ); if( device ) { connect( device, SIGNAL(descriptionDownloadDone( RootDevice*, bool )), SLOT(onDescriptionDownloadDone( RootDevice*, bool )) ); device->startDescriptionDownload(); mPendingDevices.insert( device ); } } void SSDPWatcher::onUdpSocketError( QAbstractSocket::SocketError error ) { Q_UNUSED( error ); kDebug() << "SSDPWatcher Error : " << mUdpSocket->errorString(); } SSDPWatcher::~SSDPWatcher() { leaveUPnPMCastGroup( mUdpSocket->socketDescriptor() ); qDeleteAll( mPendingDevices ); qDeleteAll( mDevices ); } }
/* This file is part of the KUPnP library, part of the KDE project. Copyright 2009-2010 Friedrich W. H. Kossebau <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "ssdpwatcher.h" // lib #include "rootdevice.h" // KDE #include <KUrl> // Qt #include <QtNetwork/QUdpSocket> #include <QtCore/QStringList> // C #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #ifndef Q_WS_WIN #include <netinet/in_systm.h> #include <netinet/ip.h> #endif #include <KDebug> namespace UPnP { static const int SSDPPortNumber = 1900; static const char SSDPBroadCastAddress[] = "239.255.255.250"; // copied from KTorrent UPnP, but is it needed? static void joinUPnPMCastGroup( int fd ) { ip_mreq mreq; memset( &mreq, 0, sizeof(ip_mreq) ); inet_aton( SSDPBroadCastAddress, &mreq.imr_multiaddr ); mreq.imr_interface.s_addr = htonl( INADDR_ANY ); #ifndef Q_WS_WIN if( setsockopt(fd,IPPROTO_IP,IP_ADD_MEMBERSHIP,&mreq,sizeof(ip_mreq)) < 0 ) #else if( setsockopt(fd,IPPROTO_IP,IP_ADD_MEMBERSHIP,(char *)&mreq,sizeof(ip_mreq)) < 0 ) #endif kDebug() << "Failed to join multicast group 239.255.255.250"; } static void leaveUPnPMCastGroup( int fd ) { struct ip_mreq mreq; memset( &mreq, 0, sizeof(ip_mreq) ); inet_aton( SSDPBroadCastAddress, &mreq.imr_multiaddr ); mreq.imr_interface.s_addr = htonl( INADDR_ANY ); #ifndef Q_WS_WIN if( setsockopt(fd,IPPROTO_IP,IP_DROP_MEMBERSHIP,&mreq,sizeof(ip_mreq)) < 0 ) #else if( setsockopt(fd,IPPROTO_IP,IP_DROP_MEMBERSHIP,(char *)&mreq,sizeof(ip_mreq)) < 0 ) #endif kDebug() << "Failed to leave multicast group 239.255.255.250"; } SSDPWatcher::SSDPWatcher() : mUdpSocket( new QUdpSocket(this) ) { connect( mUdpSocket, SIGNAL(readyRead()), SLOT(onUdpSocketReadyRead()) ); connect( mUdpSocket, SIGNAL(error( QAbstractSocket::SocketError )), SLOT(onUdpSocketError( QAbstractSocket::SocketError )) ); // try up to ten port numbers TODO: make configurable for( int i = 0; i < 10; ++i ) { if( ! mUdpSocket->bind(SSDPPortNumber+i,QUdpSocket::ShareAddress) ) kDebug() << "Cannot bind to UDP port "<< SSDPPortNumber << ":" << mUdpSocket->errorString(); else break; } // TODO: really needed with QUdpSocket::ShareAddress ? joinUPnPMCastGroup( mUdpSocket->socketDescriptor() ); } void SSDPWatcher::discover() { kDebug() << "Trying to find UPnP devices on the local network"; // send a HTTP M-SEARCH message to 239.255.255.250:1900 const char mSearchMessage[] = "M-SEARCH * HTTP/1.1\r\n" "HOST: 239.255.255.250:1900\r\n" "ST:urn:schemas-upnp-org:device:upnp:rootdevice:1\r\n" // "ST:urn:schemas-upnp-org:device:InternetGatewayDevice:1\r\n" // "ST:urn:schemas-upnp-org:device:WANDevice:1\r\n" "MAN:\"ssdp:discover\"\r\n" "MX:3\r\n" "\r\n"; const int mSearchMessageLength = sizeof(mSearchMessage) / sizeof(mSearchMessage[0]); mUdpSocket->writeDatagram( mSearchMessage, mSearchMessageLength, QHostAddress(SSDPBroadCastAddress), SSDPPortNumber ); } RootDevice* SSDPWatcher::createDeviceFromResponse( const QByteArray& response ) { RootDevice* device = 0; const QStringList lines = QString::fromAscii( response ).split( "\r\n" ); // first read first line and see if contains a HTTP 200 OK message or // "HTTP/1.1 200 OK" // "NOTIFY * HTTP/1.1" const QString firstLine = lines.first(); if( firstLine.contains("HTTP") ) { // it is either a 200 OK or a NOTIFY if( ! firstLine.contains("NOTIFY") && ! firstLine.contains("200 OK") ) return 0; } else return 0; QString server; KUrl location; QString uuid; enum MessageType { SearchAnswer, Notification, UnknownMessage }; enum DeviceState { Alive, ByeBye, OtherState }; DeviceState deviceState = OtherState; MessageType messageType = UnknownMessage; // read all lines and try to find the server and location fields foreach( const QString& line, lines ) { const int separatorIndex = line.indexOf( ':' ); const QString key = line.left( separatorIndex ).toUpper(); const QString value = line.mid( separatorIndex+1 ).trimmed(); if( key == QLatin1String("LOCATION") ) { kDebug()<<"LOCATION:"<<value; location = value; } else if( key == QLatin1String("SERVER") ) { kDebug()<<"SERVER:"<<value; server = value; } else if( key == QLatin1String("ST") ) // search type { kDebug()<<"ST:"<<value; messageType = SearchAnswer; } else if( key == QLatin1String("NT") ) // notification type { kDebug()<<"NT:"<<value; messageType = Notification; } else if( key == QLatin1String("NTS") ) // notification type s? { kDebug()<<"NTS:"<<value; if( value == QLatin1String("ssdp:alive") ) deviceState = Alive; else if( value == QLatin1String("ssdp:byebye") ) deviceState = ByeBye; } // TODO: else if( key == QLatin1String("CACHE-CONTROL") ) // TODO: else if( key == QLatin1String("DATE") ) else if( key == QLatin1String("USN") ) // unique service name { kDebug()<<"USN:"<<value; const int startIndex = 5; const int endIndex = value.lastIndexOf( "::" ); int length = endIndex - startIndex; if( length == 0 ) length = -1; uuid = value.mid( startIndex, length ); } } if( uuid.isEmpty() ) { kDebug()<<"No uuid found!"; } else if( location.isEmpty() ) { kDebug()<<"No location found!"; } else if( deviceState == OtherState && messageType == Notification ) { kDebug()<<"NTS neither alive nor byebye"; } else if( mDevices.contains(uuid) ) { kDebug()<<"Already inserted:"<<uuid<<"!"; } #if 0 else if( ! mBrowsedDeviceTypes.isEmpty() && ! mBrowsedDeviceTypes.contains(devicePrivate->type()) ) { kDebug()<<"Not interested in:"<<devicePrivate->type(); devicePrivate->setInvalid(); } #endif else { kDebug() << "Detected Device:" << server << "UUID" << uuid; // everything OK, make a new Device device = new RootDevice( server, location, uuid ); } return device; } void SSDPWatcher::onDescriptionDownloadDone( RootDevice* device, bool success ) { mPendingDevices.remove( device ); if( ! success ) device->deleteLater(); else if( mDevices.contains(device->uuid()) ) device->deleteLater(); else { mDevices.insert( device->uuid(), device ); kDebug()<< "Added:"<<device->name()<<device->uuid(); emit deviceDiscovered( device ); } } void SSDPWatcher::onUdpSocketReadyRead() { const int pendingDatagramSize = mUdpSocket->pendingDatagramSize(); QByteArray response( pendingDatagramSize, 0 ); const int bytesRead = mUdpSocket->readDatagram( response.data(), pendingDatagramSize ); if( bytesRead == -1 ) // TODO: error handling return; RootDevice* device = createDeviceFromResponse( response ); if( device ) { connect( device, SIGNAL(descriptionDownloadDone( RootDevice*, bool )), SLOT(onDescriptionDownloadDone( RootDevice*, bool )) ); device->startDescriptionDownload(); mPendingDevices.insert( device ); } } void SSDPWatcher::onUdpSocketError( QAbstractSocket::SocketError error ) { Q_UNUSED( error ); kDebug() << "SSDPWatcher Error : " << mUdpSocket->errorString(); } SSDPWatcher::~SSDPWatcher() { leaveUPnPMCastGroup( mUdpSocket->socketDescriptor() ); qDeleteAll( mPendingDevices ); qDeleteAll( mDevices ); } }
rename result var in createDeviceFromResponse() to device
changed: rename result var in createDeviceFromResponse() to device svn path=/branches/work/kupnp-oio/server/; revision=1099651
C++
lgpl-2.1
KDE/cagibi
46df39d5e573f137aaf3d5243d60877fcce9ffd7
core/io/translation_loader_po.cpp
core/io/translation_loader_po.cpp
/*************************************************************************/ /* translation_loader_po.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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 "translation_loader_po.h" #include "core/os/file_access.h" #include "core/translation.h" RES TranslationLoaderPO::load_translation(FileAccess *f, Error *r_error) { enum Status { STATUS_NONE, STATUS_READING_ID, STATUS_READING_STRING, }; Status status = STATUS_NONE; String msg_id; String msg_str; String config; if (r_error) { *r_error = ERR_FILE_CORRUPT; } Ref<Translation> translation = Ref<Translation>(memnew(Translation)); int line = 1; bool skip_this = false; bool skip_next = false; bool is_eof = false; const String path = f->get_path(); while (!is_eof) { String l = f->get_line().strip_edges(); is_eof = f->eof_reached(); // If we reached last line and it's not a content line, break, otherwise let processing that last loop if (is_eof && l.empty()) { if (status == STATUS_READING_ID) { memdelete(f); ERR_FAIL_V_MSG(RES(), "Unexpected EOF while reading 'msgid' at: " + path + ":" + itos(line)); } else { break; } } if (l.begins_with("msgid")) { if (status == STATUS_READING_ID) { memdelete(f); ERR_FAIL_V_MSG(RES(), "Unexpected 'msgid', was expecting 'msgstr' while parsing: " + path + ":" + itos(line)); } if (msg_id != "") { if (!skip_this) { translation->add_message(msg_id, msg_str); } } else if (config == "") { config = msg_str; } l = l.substr(5, l.length()).strip_edges(); status = STATUS_READING_ID; msg_id = ""; msg_str = ""; skip_this = skip_next; skip_next = false; } if (l.begins_with("msgstr")) { if (status != STATUS_READING_ID) { memdelete(f); ERR_FAIL_V_MSG(RES(), "Unexpected 'msgstr', was expecting 'msgid' while parsing: " + path + ":" + itos(line)); } l = l.substr(6, l.length()).strip_edges(); status = STATUS_READING_STRING; } if (l == "" || l.begins_with("#")) { if (l.find("fuzzy") != -1) { skip_next = true; } line++; continue; //nothing to read or comment } if (!l.begins_with("\"") || status == STATUS_NONE) { memdelete(f); ERR_FAIL_V_MSG(RES(), "Invalid line '" + l + "' while parsing: " + path + ":" + itos(line)); } l = l.substr(1, l.length()); //find final quote int end_pos = -1; for (int i = 0; i < l.length(); i++) { if (l[i] == '"' && (i == 0 || l[i - 1] != '\\')) { end_pos = i; break; } } if (end_pos == -1) { memdelete(f); ERR_FAIL_V_MSG(RES(), "Expected '\"' at end of message while parsing: " + path + ":" + itos(line)); } l = l.substr(0, end_pos); l = l.c_unescape(); if (status == STATUS_READING_ID) { msg_id += l; } else { msg_str += l; } line++; } memdelete(f); if (status == STATUS_READING_STRING) { if (msg_id != "") { if (!skip_this) { translation->add_message(msg_id, msg_str); } } else if (config == "") { config = msg_str; } } ERR_FAIL_COND_V_MSG(config == "", RES(), "No config found in file: " + path + "."); Vector<String> configs = config.split("\n"); for (int i = 0; i < configs.size(); i++) { String c = configs[i].strip_edges(); int p = c.find(":"); if (p == -1) { continue; } String prop = c.substr(0, p).strip_edges(); String value = c.substr(p + 1, c.length()).strip_edges(); if (prop == "X-Language" || prop == "Language") { translation->set_locale(value); } } if (r_error) { *r_error = OK; } return translation; } RES TranslationLoaderPO::load(const String &p_path, const String &p_original_path, Error *r_error) { if (r_error) { *r_error = ERR_CANT_OPEN; } FileAccess *f = FileAccess::open(p_path, FileAccess::READ); ERR_FAIL_COND_V_MSG(!f, RES(), "Cannot open file '" + p_path + "'."); return load_translation(f, r_error); } void TranslationLoaderPO::get_recognized_extensions(List<String> *p_extensions) const { p_extensions->push_back("po"); } bool TranslationLoaderPO::handles_type(const String &p_type) const { return (p_type == "Translation"); } String TranslationLoaderPO::get_resource_type(const String &p_path) const { if (p_path.get_extension().to_lower() == "po") { return "Translation"; } return ""; } TranslationLoaderPO::TranslationLoaderPO() { }
/*************************************************************************/ /* translation_loader_po.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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 "translation_loader_po.h" #include "core/os/file_access.h" #include "core/translation.h" RES TranslationLoaderPO::load_translation(FileAccess *f, Error *r_error) { enum Status { STATUS_NONE, STATUS_READING_ID, STATUS_READING_STRING, }; Status status = STATUS_NONE; String msg_id; String msg_str; String config; if (r_error) { *r_error = ERR_FILE_CORRUPT; } Ref<Translation> translation = Ref<Translation>(memnew(Translation)); int line = 1; bool skip_this = false; bool skip_next = false; bool is_eof = false; const String path = f->get_path(); while (!is_eof) { String l = f->get_line().strip_edges(); is_eof = f->eof_reached(); // If we reached last line and it's not a content line, break, otherwise let processing that last loop if (is_eof && l.empty()) { if (status == STATUS_READING_ID) { memdelete(f); ERR_FAIL_V_MSG(RES(), "Unexpected EOF while reading 'msgid' at: " + path + ":" + itos(line)); } else { break; } } if (l.begins_with("msgid")) { if (status == STATUS_READING_ID) { memdelete(f); ERR_FAIL_V_MSG(RES(), "Unexpected 'msgid', was expecting 'msgstr' while parsing: " + path + ":" + itos(line)); } if (msg_id != "") { if (!skip_this) { translation->add_message(msg_id, msg_str); } } else if (config == "") { config = msg_str; } l = l.substr(5, l.length()).strip_edges(); status = STATUS_READING_ID; msg_id = ""; msg_str = ""; skip_this = skip_next; skip_next = false; } if (l.begins_with("msgstr")) { if (status != STATUS_READING_ID) { memdelete(f); ERR_FAIL_V_MSG(RES(), "Unexpected 'msgstr', was expecting 'msgid' while parsing: " + path + ":" + itos(line)); } l = l.substr(6, l.length()).strip_edges(); status = STATUS_READING_STRING; } if (l == "" || l.begins_with("#")) { if (l.find("fuzzy") != -1) { skip_next = true; } line++; continue; //nothing to read or comment } if (!l.begins_with("\"") || status == STATUS_NONE) { memdelete(f); ERR_FAIL_V_MSG(RES(), "Invalid line '" + l + "' while parsing: " + path + ":" + itos(line)); } l = l.substr(1, l.length()); // Find final quote, ignoring escaped ones (\"). // The escape_next logic is necessary to properly parse things like \\" // where the blackslash is the one being escaped, not the quote. int end_pos = -1; bool escape_next = false; for (int i = 0; i < l.length(); i++) { if (l[i] == '\\' && !escape_next) { escape_next = true; continue; } if (l[i] == '"' && !escape_next) { end_pos = i; break; } escape_next = false; } if (end_pos == -1) { memdelete(f); ERR_FAIL_V_MSG(RES(), "Expected '\"' at end of message while parsing: " + path + ":" + itos(line)); } l = l.substr(0, end_pos); l = l.c_unescape(); if (status == STATUS_READING_ID) { msg_id += l; } else { msg_str += l; } line++; } memdelete(f); if (status == STATUS_READING_STRING) { if (msg_id != "") { if (!skip_this) { translation->add_message(msg_id, msg_str); } } else if (config == "") { config = msg_str; } } ERR_FAIL_COND_V_MSG(config == "", RES(), "No config found in file: " + path + "."); Vector<String> configs = config.split("\n"); for (int i = 0; i < configs.size(); i++) { String c = configs[i].strip_edges(); int p = c.find(":"); if (p == -1) { continue; } String prop = c.substr(0, p).strip_edges(); String value = c.substr(p + 1, c.length()).strip_edges(); if (prop == "X-Language" || prop == "Language") { translation->set_locale(value); } } if (r_error) { *r_error = OK; } return translation; } RES TranslationLoaderPO::load(const String &p_path, const String &p_original_path, Error *r_error) { if (r_error) { *r_error = ERR_CANT_OPEN; } FileAccess *f = FileAccess::open(p_path, FileAccess::READ); ERR_FAIL_COND_V_MSG(!f, RES(), "Cannot open file '" + p_path + "'."); return load_translation(f, r_error); } void TranslationLoaderPO::get_recognized_extensions(List<String> *p_extensions) const { p_extensions->push_back("po"); } bool TranslationLoaderPO::handles_type(const String &p_type) const { return (p_type == "Translation"); } String TranslationLoaderPO::get_resource_type(const String &p_path) const { if (p_path.get_extension().to_lower() == "po") { return "Translation"; } return ""; } TranslationLoaderPO::TranslationLoaderPO() { }
Fix parsing of multiple escapes before quotes
i18n: Fix parsing of multiple escapes before quotes See https://github.com/godotengine/godot/pull/37114#issuecomment-601463765 (cherry picked from commit 8c3ad2af93a119f45e0bc786ae1dfa04e116d60f)
C++
mit
ex/godot,ex/godot,ex/godot,ex/godot,ex/godot,ex/godot,ex/godot,ex/godot
5e022150b50f5e3a8fc38beb5618869762789a7c
lpc_aspeed.cpp
lpc_aspeed.cpp
/* * Copyright 2018 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "lpc_aspeed.hpp" #include "window_hw_interface.hpp" #include <fcntl.h> #include <linux/aspeed-lpc-ctrl.h> #include <linux/kernel.h> #include <cstdint> #include <cstring> #include <memory> #include <string> #include <utility> namespace blobs { const std::string LpcMapperAspeed::lpcControlPath = "/dev/aspeed-lpc-ctrl"; std::unique_ptr<HardwareMapperInterface> LpcMapperAspeed::createAspeedMapper(std::uint32_t regionAddress, std::size_t regionSize) { /* NOTE: considered using a joint factory to create one or the other, for * now, separate factories. */ return std::make_unique<LpcMapperAspeed>(regionAddress, regionSize); } void LpcMapperAspeed::close() { } std::pair<std::uint32_t, std::uint32_t> LpcMapperAspeed::mapWindow(std::uint32_t address, std::uint32_t length) { static const std::uint32_t MASK_64K = 0xFFFFU; const std::uint32_t offset = address & MASK_64K; if (offset + length > regionSize) { std::fprintf(stderr, "requested window size %" PRIu32 ", offset %#" PRIx32 " is too large for mem region" " of size %zu\n", length, offset, regionSize); /* TODO: need to throw an exception at this point to store the data to * provide an EBIG response later. */ /* *windowSize = regionSize - offset; */ return std::make_pair(0, 0); } struct aspeed_lpc_ctrl_mapping map = { .window_type = ASPEED_LPC_CTRL_WINDOW_MEMORY, .window_id = 0, .flags = 0, .addr = address & ~MASK_64K, .offset = 0, .size = __ALIGN_KERNEL_MASK(offset + length, MASK_64K), }; std::fprintf(stderr, "requesting Aspeed LPC window at %#" PRIx32 " of size %" PRIu32 "\n", map.addr, map.size); const auto lpcControlFd = sys->open(lpcControlPath.c_str(), O_RDWR); if (lpcControlFd == -1) { std::fprintf(stderr, "cannot open Aspeed LPC kernel control dev \"%s\"\n", lpcControlPath.c_str()); return std::make_pair(0, 0); } if (sys->ioctl(lpcControlFd, ASPEED_LPC_CTRL_IOCTL_MAP, &map) == -1) { std::fprintf(stderr, "Failed to ioctl Aspeed LPC map with error %s\n", std::strerror(errno)); sys->close(lpcControlFd); return std::make_pair(0, 0); } sys->close(lpcControlFd); return std::make_pair(offset, length); } bool LpcMapperAspeed::mapRegion() { /* Open the file to map. */ mappedFd = sys->open(lpcControlPath.c_str(), O_RDONLY | O_SYNC); mappedRegion = reinterpret_cast<uint8_t*>( sys->mmap(0, regionSize, PROT_READ, MAP_SHARED, mappedFd, 0)); if (mappedRegion == MAP_FAILED) { sys->close(mappedFd); mappedFd = -1; std::fprintf(stderr, "Mmap failure: '%s'\n", std::strerror(errno)); return false; } /* TOOD: There is no close() method here, to close mappedFd, or mappedRegion * -- therefore, a good next step will be to evaluate whether or not the * other pieces should go here... */ return true; } std::vector<std::uint8_t> LpcMapperAspeed::copyFrom(std::uint32_t length) { if (mappedFd < 0) { /* NOTE: may make more sense to do this in the open() */ if (!mapRegion()) { /* Was unable to map region -- this call only required if using mmap * and not ioctl. */ /* TODO: have a better failure. */ return {}; } } /* TODO: Implement this. */ return {}; } } // namespace blobs
/* * Copyright 2018 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "lpc_aspeed.hpp" #include "window_hw_interface.hpp" #include <fcntl.h> #include <linux/aspeed-lpc-ctrl.h> #include <linux/kernel.h> #include <cstdint> #include <cstring> #include <memory> #include <string> #include <utility> namespace blobs { const std::string LpcMapperAspeed::lpcControlPath = "/dev/aspeed-lpc-ctrl"; std::unique_ptr<HardwareMapperInterface> LpcMapperAspeed::createAspeedMapper(std::uint32_t regionAddress, std::size_t regionSize) { /* NOTE: considered using a joint factory to create one or the other, for * now, separate factories. */ return std::make_unique<LpcMapperAspeed>(regionAddress, regionSize); } void LpcMapperAspeed::close() { if (mappedRegion) { sys->munmap(mappedRegion, regionSize); mappedRegion = nullptr; } if (mappedFd != -1) { sys->close(mappedFd); mappedFd = -1; } } std::pair<std::uint32_t, std::uint32_t> LpcMapperAspeed::mapWindow(std::uint32_t address, std::uint32_t length) { static const std::uint32_t MASK_64K = 0xFFFFU; const std::uint32_t offset = address & MASK_64K; if (offset + length > regionSize) { std::fprintf(stderr, "requested window size %" PRIu32 ", offset %#" PRIx32 " is too large for mem region" " of size %zu\n", length, offset, regionSize); /* TODO: need to throw an exception at this point to store the data to * provide an EBIG response later. */ /* *windowSize = regionSize - offset; */ return std::make_pair(0, 0); } struct aspeed_lpc_ctrl_mapping map = { .window_type = ASPEED_LPC_CTRL_WINDOW_MEMORY, .window_id = 0, .flags = 0, .addr = address & ~MASK_64K, .offset = 0, .size = __ALIGN_KERNEL_MASK(offset + length, MASK_64K), }; std::fprintf(stderr, "requesting Aspeed LPC window at %#" PRIx32 " of size %" PRIu32 "\n", map.addr, map.size); const auto lpcControlFd = sys->open(lpcControlPath.c_str(), O_RDWR); if (lpcControlFd == -1) { std::fprintf(stderr, "cannot open Aspeed LPC kernel control dev \"%s\"\n", lpcControlPath.c_str()); return std::make_pair(0, 0); } if (sys->ioctl(lpcControlFd, ASPEED_LPC_CTRL_IOCTL_MAP, &map) == -1) { std::fprintf(stderr, "Failed to ioctl Aspeed LPC map with error %s\n", std::strerror(errno)); sys->close(lpcControlFd); return std::make_pair(0, 0); } sys->close(lpcControlFd); return std::make_pair(offset, length); } bool LpcMapperAspeed::mapRegion() { /* Open the file to map. */ mappedFd = sys->open(lpcControlPath.c_str(), O_RDONLY | O_SYNC); mappedRegion = reinterpret_cast<uint8_t*>( sys->mmap(0, regionSize, PROT_READ, MAP_SHARED, mappedFd, 0)); if (mappedRegion == MAP_FAILED) { sys->close(mappedFd); mappedFd = -1; std::fprintf(stderr, "Mmap failure: '%s'\n", std::strerror(errno)); return false; } /* TOOD: There is no close() method here, to close mappedFd, or mappedRegion * -- therefore, a good next step will be to evaluate whether or not the * other pieces should go here... */ return true; } std::vector<std::uint8_t> LpcMapperAspeed::copyFrom(std::uint32_t length) { if (mappedFd < 0) { /* NOTE: may make more sense to do this in the open() */ if (!mapRegion()) { /* Was unable to map region -- this call only required if using mmap * and not ioctl. */ /* TODO: have a better failure. */ return {}; } } /* TODO: Implement this. */ return {}; } } // namespace blobs
implement close method
lpc_aspeed: implement close method Implement close method on lpc aspeed, such that it'll unmap the memory region and close the file handle to the driver. Change-Id: Ie0417fb6c77a2b9d4b4db532b464738b2430a811 Signed-off-by: Patrick Venture <[email protected]>
C++
apache-2.0
openbmc/phosphor-ipmi-flash
877594d63f9869e953f10fdff4f2c67f69fe5c93
cpp-driver/src/utils.hpp
cpp-driver/src/utils.hpp
/* Copyright (c) 2014-2017 DataStax Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef __CASS_COMMON_HPP_INCLUDED__ #define __CASS_COMMON_HPP_INCLUDED__ #include "cassandra.h" #include "macros.hpp" #include "string.hpp" #include "vector.hpp" #include <stddef.h> #include <stdint.h> #include <string.h> namespace cass { class BufferPiece; class Value; typedef Vector<String> ContactPointList; typedef Vector<String> DcList; template<class From, class To> #if _MSC_VER && !__INTEL_COMPILER class IsConvertible : public std::is_convertible<From, To> { #else class IsConvertible { private: typedef char Yes; typedef struct { char not_used[2]; } No; struct Helper { static Yes test(To); static No test(...); static From& check(); }; public: static const bool value = sizeof(Helper::test(Helper::check())) == sizeof(Yes); #endif }; // copy_cast<> prevents incorrect code from being generated when two unrelated // types reference the same memory location and strict aliasing is enabled. // The type "char*" is an exception and is allowed to alias any other // pointer type. This allows memcpy() to copy bytes from one type to the other // without violating strict aliasing and usually optimizes away on a modern // compiler (GCC, Clang, and MSVC). template<typename From, typename To> inline To copy_cast(const From& from) { STATIC_ASSERT(sizeof(From) == sizeof(To)); To to; memcpy(&to, &from, sizeof(from)); return to; } inline size_t next_pow_2(size_t num) { size_t next = 2; size_t i = 0; while (next < num) { next = static_cast<size_t>(1) << i++; } return next; } String opcode_to_string(int opcode); String protocol_version_to_string(int version); void explode(const String& str, Vector<String>& vec, const char delimiter = ','); String& trim(String& str); bool is_valid_cql_id(const String& str); String& to_cql_id(String& str); String& escape_id(String& str); inline size_t num_leading_zeros(int64_t value) { if (value == 0) return 64; #if defined(_MSC_VER) unsigned long index; # if defined(_M_AMD64) _BitScanReverse64(&index, value); # else // On 32-bit this needs to be split into two operations char isNonzero = _BitScanReverse(&index, (unsigned long)(value >> 32)); if (isNonzero) // The most significant 4 bytes has a bit set, and our index is relative to that. // Add 32 to account for the lower 4 bytes that make up our 64-bit number. index += 32; else { // Scan the last 32 bits by truncating the 64-bit value _BitScanReverse(&index, (unsigned long) value); } # endif // index is the (zero based) index, counting from lsb, of the most-significant 1 bit. // For example, a value of 12 (b1100) would return 3. The 4th bit is set, so there are // 60 leading zeros. return 64 - index - 1; #else return __builtin_clzll(value); #endif } inline size_t vint_size(int64_t value) { // | with 1 to ensure magnitude <= 63, so (63 - 1) / 7 <= 8 size_t magnitude = num_leading_zeros(value | 1); return magnitude ? (9 - ((magnitude - 1) / 7)) : 9; } int32_t get_pid(); } // namespace cass #endif
/* Copyright (c) 2014-2017 DataStax Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef __CASS_COMMON_HPP_INCLUDED__ #define __CASS_COMMON_HPP_INCLUDED__ #include "cassandra.h" #include "macros.hpp" #include "string.hpp" #include "vector.hpp" #include <stddef.h> #include <stdint.h> #include <string.h> #if defined(_MSC_VER) #include <intrin.h> #endif namespace cass { class BufferPiece; class Value; typedef Vector<String> ContactPointList; typedef Vector<String> DcList; template<class From, class To> #if _MSC_VER && !__INTEL_COMPILER class IsConvertible : public std::is_convertible<From, To> { #else class IsConvertible { private: typedef char Yes; typedef struct { char not_used[2]; } No; struct Helper { static Yes test(To); static No test(...); static From& check(); }; public: static const bool value = sizeof(Helper::test(Helper::check())) == sizeof(Yes); #endif }; // copy_cast<> prevents incorrect code from being generated when two unrelated // types reference the same memory location and strict aliasing is enabled. // The type "char*" is an exception and is allowed to alias any other // pointer type. This allows memcpy() to copy bytes from one type to the other // without violating strict aliasing and usually optimizes away on a modern // compiler (GCC, Clang, and MSVC). template<typename From, typename To> inline To copy_cast(const From& from) { STATIC_ASSERT(sizeof(From) == sizeof(To)); To to; memcpy(&to, &from, sizeof(from)); return to; } inline size_t next_pow_2(size_t num) { size_t next = 2; size_t i = 0; while (next < num) { next = static_cast<size_t>(1) << i++; } return next; } String opcode_to_string(int opcode); String protocol_version_to_string(int version); void explode(const String& str, Vector<String>& vec, const char delimiter = ','); String& trim(String& str); bool is_valid_cql_id(const String& str); String& to_cql_id(String& str); String& escape_id(String& str); inline size_t num_leading_zeros(int64_t value) { if (value == 0) return 64; #if defined(_MSC_VER) unsigned long index; # if defined(_M_AMD64) _BitScanReverse64(&index, value); # else // On 32-bit this needs to be split into two operations char isNonzero = _BitScanReverse(&index, (unsigned long)(value >> 32)); if (isNonzero) // The most significant 4 bytes has a bit set, and our index is relative to that. // Add 32 to account for the lower 4 bytes that make up our 64-bit number. index += 32; else { // Scan the last 32 bits by truncating the 64-bit value _BitScanReverse(&index, (unsigned long) value); } # endif // index is the (zero based) index, counting from lsb, of the most-significant 1 bit. // For example, a value of 12 (b1100) would return 3. The 4th bit is set, so there are // 60 leading zeros. return 64 - index - 1; #else return __builtin_clzll(value); #endif } inline size_t vint_size(int64_t value) { // | with 1 to ensure magnitude <= 63, so (63 - 1) / 7 <= 8 size_t magnitude = num_leading_zeros(value | 1); return magnitude ? (9 - ((magnitude - 1) / 7)) : 9; } int32_t get_pid(); } // namespace cass #endif
Add missing include for MSVC15
Add missing include for MSVC15 The _BitScanReverse functions now require intrin.h to be included.
C++
apache-2.0
datastax/cpp-driver,datastax/cpp-driver,datastax/cpp-driver,datastax/cpp-driver
ca39ce784bfe06c001f4d1c965b2ad9f16f2434c
c++/src/capnp/membrane-test.c++
c++/src/capnp/membrane-test.c++
// Copyright (c) 2015 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #include "membrane.h" #include <kj/test.h> #include "test-util.h" #include <kj/function.h> #include <kj/async-io.h> #include "rpc-twoparty.h" namespace capnp { namespace _ { namespace { using Thing = test::TestMembrane::Thing; class ThingImpl final: public Thing::Server { public: ThingImpl(kj::StringPtr text): text(text) {} protected: kj::Promise<void> passThrough(PassThroughContext context) override { context.getResults().setText(text); return kj::READY_NOW; } kj::Promise<void> intercept(InterceptContext context) override { context.getResults().setText(text); return kj::READY_NOW; } private: kj::StringPtr text; }; class TestMembraneImpl final: public test::TestMembrane::Server { protected: kj::Promise<void> makeThing(MakeThingContext context) override { context.getResults().setThing(kj::heap<ThingImpl>("inside")); return kj::READY_NOW; } kj::Promise<void> callPassThrough(CallPassThroughContext context) override { auto params = context.getParams(); auto req = params.getThing().passThroughRequest(); if (params.getTailCall()) { return context.tailCall(kj::mv(req)); } else { return req.send().then( [KJ_CPCAP(context)](Response<test::TestMembrane::Result>&& result) mutable { context.setResults(result); }); } } kj::Promise<void> callIntercept(CallInterceptContext context) override { auto params = context.getParams(); auto req = params.getThing().interceptRequest(); if (params.getTailCall()) { return context.tailCall(kj::mv(req)); } else { return req.send().then( [KJ_CPCAP(context)](Response<test::TestMembrane::Result>&& result) mutable { context.setResults(result); }); } } kj::Promise<void> loopback(LoopbackContext context) override { context.getResults().setThing(context.getParams().getThing()); return kj::READY_NOW; } kj::Promise<void> waitForever(WaitForeverContext context) override { context.allowCancellation(); return kj::NEVER_DONE; } }; class MembranePolicyImpl: public MembranePolicy, public kj::Refcounted { public: MembranePolicyImpl() = default; MembranePolicyImpl(kj::Maybe<kj::Promise<void>> revokePromise) : revokePromise(revokePromise.map([](kj::Promise<void>& p) { return p.fork(); })) {} kj::Maybe<Capability::Client> inboundCall(uint64_t interfaceId, uint16_t methodId, Capability::Client target) override { if (interfaceId == capnp::typeId<Thing>() && methodId == 1) { return Capability::Client(kj::heap<ThingImpl>("inbound")); } else { return nullptr; } } kj::Maybe<Capability::Client> outboundCall(uint64_t interfaceId, uint16_t methodId, Capability::Client target) override { if (interfaceId == capnp::typeId<Thing>() && methodId == 1) { return Capability::Client(kj::heap<ThingImpl>("outbound")); } else { return nullptr; } } kj::Own<MembranePolicy> addRef() override { return kj::addRef(*this); } kj::Maybe<kj::Promise<void>> onRevoked() override { return revokePromise.map([](kj::ForkedPromise<void>& fork) { return fork.addBranch(); }); } private: kj::Maybe<kj::ForkedPromise<void>> revokePromise; }; void testThingImpl(kj::WaitScope& waitScope, test::TestMembrane::Client membraned, kj::Function<Thing::Client()> makeThing, kj::StringPtr localPassThrough, kj::StringPtr localIntercept, kj::StringPtr remotePassThrough, kj::StringPtr remoteIntercept) { KJ_EXPECT(makeThing().passThroughRequest().send().wait(waitScope).getText() == localPassThrough); KJ_EXPECT(makeThing().interceptRequest().send().wait(waitScope).getText() == localIntercept); { auto req = membraned.callPassThroughRequest(); req.setThing(makeThing()); req.setTailCall(false); KJ_EXPECT(req.send().wait(waitScope).getText() == remotePassThrough); } { auto req = membraned.callInterceptRequest(); req.setThing(makeThing()); req.setTailCall(false); KJ_EXPECT(req.send().wait(waitScope).getText() == remoteIntercept); } { auto req = membraned.callPassThroughRequest(); req.setThing(makeThing()); req.setTailCall(true); KJ_EXPECT(req.send().wait(waitScope).getText() == remotePassThrough); } { auto req = membraned.callInterceptRequest(); req.setThing(makeThing()); req.setTailCall(true); KJ_EXPECT(req.send().wait(waitScope).getText() == remoteIntercept); } } struct TestEnv { kj::EventLoop loop; kj::WaitScope waitScope; kj::Own<MembranePolicyImpl> policy; test::TestMembrane::Client membraned; TestEnv() : waitScope(loop), policy(kj::refcounted<MembranePolicyImpl>()), membraned(membrane(kj::heap<TestMembraneImpl>(), policy->addRef())) {} void testThing(kj::Function<Thing::Client()> makeThing, kj::StringPtr localPassThrough, kj::StringPtr localIntercept, kj::StringPtr remotePassThrough, kj::StringPtr remoteIntercept) { testThingImpl(waitScope, membraned, kj::mv(makeThing), localPassThrough, localIntercept, remotePassThrough, remoteIntercept); } }; KJ_TEST("call local object inside membrane") { TestEnv env; env.testThing([&]() { return env.membraned.makeThingRequest().send().wait(env.waitScope).getThing(); }, "inside", "inbound", "inside", "inside"); } KJ_TEST("call local promise inside membrane") { TestEnv env; env.testThing([&]() { return env.membraned.makeThingRequest().send().getThing(); }, "inside", "inbound", "inside", "inside"); } KJ_TEST("call local resolved promise inside membrane") { TestEnv env; env.testThing([&]() { auto thing = env.membraned.makeThingRequest().send().getThing(); thing.whenResolved().wait(env.waitScope); return thing; }, "inside", "inbound", "inside", "inside"); } KJ_TEST("call local object outside membrane") { TestEnv env; env.testThing([&]() { return kj::heap<ThingImpl>("outside"); }, "outside", "outside", "outside", "outbound"); } KJ_TEST("call local capability that has passed into and back out of membrane") { TestEnv env; env.testThing([&]() { auto req = env.membraned.loopbackRequest(); req.setThing(kj::heap<ThingImpl>("outside")); return req.send().wait(env.waitScope).getThing(); }, "outside", "outside", "outside", "outbound"); } KJ_TEST("call local promise pointing into membrane that eventually resolves to outside") { TestEnv env; env.testThing([&]() { auto req = env.membraned.loopbackRequest(); req.setThing(kj::heap<ThingImpl>("outside")); return req.send().getThing(); }, "outside", "outside", "outside", "outbound"); } KJ_TEST("apply membrane using copyOutOfMembrane() on struct") { TestEnv env; env.testThing([&]() { MallocMessageBuilder outsideBuilder; auto root = outsideBuilder.initRoot<test::TestContainMembrane>(); root.setCap(kj::heap<ThingImpl>("inside")); MallocMessageBuilder insideBuilder; insideBuilder.adoptRoot(copyOutOfMembrane( root.asReader(), insideBuilder.getOrphanage(), env.policy->addRef())); return insideBuilder.getRoot<test::TestContainMembrane>().getCap(); }, "inside", "inbound", "inside", "inside"); } KJ_TEST("apply membrane using copyOutOfMembrane() on list") { TestEnv env; env.testThing([&]() { MallocMessageBuilder outsideBuilder; auto list = outsideBuilder.initRoot<test::TestContainMembrane>().initList(1); list.set(0, kj::heap<ThingImpl>("inside")); MallocMessageBuilder insideBuilder; insideBuilder.initRoot<test::TestContainMembrane>().adoptList(copyOutOfMembrane( list.asReader(), insideBuilder.getOrphanage(), env.policy->addRef())); return insideBuilder.getRoot<test::TestContainMembrane>().getList()[0]; }, "inside", "inbound", "inside", "inside"); } KJ_TEST("apply membrane using copyOutOfMembrane() on AnyPointer") { TestEnv env; env.testThing([&]() { MallocMessageBuilder outsideBuilder; auto ptr = outsideBuilder.initRoot<test::TestAnyPointer>().getAnyPointerField(); ptr.setAs<test::TestMembrane::Thing>(kj::heap<ThingImpl>("inside")); MallocMessageBuilder insideBuilder; insideBuilder.initRoot<test::TestAnyPointer>().getAnyPointerField().adopt(copyOutOfMembrane( ptr.asReader(), insideBuilder.getOrphanage(), env.policy->addRef())); return insideBuilder.getRoot<test::TestAnyPointer>().getAnyPointerField() .getAs<test::TestMembrane::Thing>(); }, "inside", "inbound", "inside", "inside"); } struct TestRpcEnv { kj::AsyncIoContext io; kj::TwoWayPipe pipe; TwoPartyClient client; TwoPartyClient server; test::TestMembrane::Client membraned; TestRpcEnv(kj::Maybe<kj::Promise<void>> revokePromise = nullptr) : io(kj::setupAsyncIo()), pipe(io.provider->newTwoWayPipe()), client(*pipe.ends[0]), server(*pipe.ends[1], membrane(kj::heap<TestMembraneImpl>(), kj::refcounted<MembranePolicyImpl>(kj::mv(revokePromise))), rpc::twoparty::Side::SERVER), membraned(client.bootstrap().castAs<test::TestMembrane>()) {} void testThing(kj::Function<Thing::Client()> makeThing, kj::StringPtr localPassThrough, kj::StringPtr localIntercept, kj::StringPtr remotePassThrough, kj::StringPtr remoteIntercept) { testThingImpl(io.waitScope, membraned, kj::mv(makeThing), localPassThrough, localIntercept, remotePassThrough, remoteIntercept); } }; KJ_TEST("call remote object inside membrane") { TestRpcEnv env; env.testThing([&]() { return env.membraned.makeThingRequest().send().wait(env.io.waitScope).getThing(); }, "inside", "inbound", "inside", "inside"); } KJ_TEST("call remote promise inside membrane") { TestRpcEnv env; env.testThing([&]() { return env.membraned.makeThingRequest().send().getThing(); }, "inside", "inbound", "inside", "inside"); } KJ_TEST("call remote resolved promise inside membrane") { TestEnv env; env.testThing([&]() { auto thing = env.membraned.makeThingRequest().send().getThing(); thing.whenResolved().wait(env.waitScope); return thing; }, "inside", "inbound", "inside", "inside"); } KJ_TEST("call remote object outside membrane") { TestRpcEnv env; env.testThing([&]() { return kj::heap<ThingImpl>("outside"); }, "outside", "outside", "outside", "outbound"); } KJ_TEST("call remote capability that has passed into and back out of membrane") { TestRpcEnv env; env.testThing([&]() { auto req = env.membraned.loopbackRequest(); req.setThing(kj::heap<ThingImpl>("outside")); return req.send().wait(env.io.waitScope).getThing(); }, "outside", "outside", "outside", "outbound"); } KJ_TEST("call remote promise pointing into membrane that eventually resolves to outside") { TestRpcEnv env; env.testThing([&]() { auto req = env.membraned.loopbackRequest(); req.setThing(kj::heap<ThingImpl>("outside")); return req.send().getThing(); }, "outside", "outside", "outside", "outbound"); } KJ_TEST("revoke membrane") { auto paf = kj::newPromiseAndFulfiller<void>(); TestRpcEnv env(kj::mv(paf.promise)); auto thing = env.membraned.makeThingRequest().send().wait(env.io.waitScope).getThing(); auto callPromise = env.membraned.waitForeverRequest().send(); KJ_EXPECT(!callPromise.poll(env.io.waitScope)); paf.fulfiller->reject(KJ_EXCEPTION(DISCONNECTED, "foobar")); // TRICKY: We need to use .ignoreResult().wait() below because when compiling with // -fno-exceptions, void waits throw recoverable exceptions while non-void waits necessarily // throw fatal exceptions... but testing for fatal exceptions when exceptions are disabled // involves fork()ing the process to run the code so if it has side effects on file descriptors // then we'll get in a bad state... KJ_ASSERT(callPromise.poll(env.io.waitScope)); KJ_EXPECT_THROW_RECOVERABLE_MESSAGE("foobar", callPromise.ignoreResult().wait(env.io.waitScope)); KJ_EXPECT_THROW_RECOVERABLE_MESSAGE("foobar", env.membraned.makeThingRequest().send().ignoreResult().wait(env.io.waitScope)); KJ_EXPECT_THROW_RECOVERABLE_MESSAGE("foobar", thing.passThroughRequest().send().ignoreResult().wait(env.io.waitScope)); } } // namespace } // namespace _ } // namespace capnp
// Copyright (c) 2015 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #include "membrane.h" #include <kj/test.h> #include "test-util.h" #include <kj/function.h> #include <kj/async-io.h> #include "rpc-twoparty.h" namespace capnp { namespace _ { namespace { using Thing = test::TestMembrane::Thing; class ThingImpl final: public Thing::Server { public: ThingImpl(kj::StringPtr text): text(text) {} protected: kj::Promise<void> passThrough(PassThroughContext context) override { context.getResults().setText(text); return kj::READY_NOW; } kj::Promise<void> intercept(InterceptContext context) override { context.getResults().setText(text); return kj::READY_NOW; } private: kj::StringPtr text; }; class TestMembraneImpl final: public test::TestMembrane::Server { protected: kj::Promise<void> makeThing(MakeThingContext context) override { context.getResults().setThing(kj::heap<ThingImpl>("inside")); return kj::READY_NOW; } kj::Promise<void> callPassThrough(CallPassThroughContext context) override { auto params = context.getParams(); auto req = params.getThing().passThroughRequest(); if (params.getTailCall()) { return context.tailCall(kj::mv(req)); } else { return req.send().then( [KJ_CPCAP(context)](Response<test::TestMembrane::Result>&& result) mutable { context.setResults(result); }); } } kj::Promise<void> callIntercept(CallInterceptContext context) override { auto params = context.getParams(); auto req = params.getThing().interceptRequest(); if (params.getTailCall()) { return context.tailCall(kj::mv(req)); } else { return req.send().then( [KJ_CPCAP(context)](Response<test::TestMembrane::Result>&& result) mutable { context.setResults(result); }); } } kj::Promise<void> loopback(LoopbackContext context) override { context.getResults().setThing(context.getParams().getThing()); return kj::READY_NOW; } kj::Promise<void> waitForever(WaitForeverContext context) override { context.allowCancellation(); return kj::NEVER_DONE; } }; class MembranePolicyImpl: public MembranePolicy, public kj::Refcounted { public: MembranePolicyImpl() = default; MembranePolicyImpl(kj::Maybe<kj::Promise<void>> revokePromise) : revokePromise(revokePromise.map([](kj::Promise<void>& p) { return p.fork(); })) {} kj::Maybe<Capability::Client> inboundCall(uint64_t interfaceId, uint16_t methodId, Capability::Client target) override { if (interfaceId == capnp::typeId<Thing>() && methodId == 1) { return Capability::Client(kj::heap<ThingImpl>("inbound")); } else { return nullptr; } } kj::Maybe<Capability::Client> outboundCall(uint64_t interfaceId, uint16_t methodId, Capability::Client target) override { if (interfaceId == capnp::typeId<Thing>() && methodId == 1) { return Capability::Client(kj::heap<ThingImpl>("outbound")); } else { return nullptr; } } kj::Own<MembranePolicy> addRef() override { return kj::addRef(*this); } kj::Maybe<kj::Promise<void>> onRevoked() override { return revokePromise.map([](kj::ForkedPromise<void>& fork) { return fork.addBranch(); }); } private: kj::Maybe<kj::ForkedPromise<void>> revokePromise; }; void testThingImpl(kj::WaitScope& waitScope, test::TestMembrane::Client membraned, kj::Function<Thing::Client()> makeThing, kj::StringPtr localPassThrough, kj::StringPtr localIntercept, kj::StringPtr remotePassThrough, kj::StringPtr remoteIntercept) { KJ_EXPECT(makeThing().passThroughRequest().send().wait(waitScope).getText() == localPassThrough); KJ_EXPECT(makeThing().interceptRequest().send().wait(waitScope).getText() == localIntercept); { auto req = membraned.callPassThroughRequest(); req.setThing(makeThing()); req.setTailCall(false); KJ_EXPECT(req.send().wait(waitScope).getText() == remotePassThrough); } { auto req = membraned.callInterceptRequest(); req.setThing(makeThing()); req.setTailCall(false); KJ_EXPECT(req.send().wait(waitScope).getText() == remoteIntercept); } { auto req = membraned.callPassThroughRequest(); req.setThing(makeThing()); req.setTailCall(true); KJ_EXPECT(req.send().wait(waitScope).getText() == remotePassThrough); } { auto req = membraned.callInterceptRequest(); req.setThing(makeThing()); req.setTailCall(true); KJ_EXPECT(req.send().wait(waitScope).getText() == remoteIntercept); } } struct TestEnv { kj::EventLoop loop; kj::WaitScope waitScope; kj::Own<MembranePolicyImpl> policy; test::TestMembrane::Client membraned; TestEnv() : waitScope(loop), policy(kj::refcounted<MembranePolicyImpl>()), membraned(membrane(kj::heap<TestMembraneImpl>(), policy->addRef())) {} void testThing(kj::Function<Thing::Client()> makeThing, kj::StringPtr localPassThrough, kj::StringPtr localIntercept, kj::StringPtr remotePassThrough, kj::StringPtr remoteIntercept) { testThingImpl(waitScope, membraned, kj::mv(makeThing), localPassThrough, localIntercept, remotePassThrough, remoteIntercept); } }; KJ_TEST("call local object inside membrane") { TestEnv env; env.testThing([&]() { return env.membraned.makeThingRequest().send().wait(env.waitScope).getThing(); }, "inside", "inbound", "inside", "inside"); } KJ_TEST("call local promise inside membrane") { TestEnv env; env.testThing([&]() { return env.membraned.makeThingRequest().send().getThing(); }, "inside", "inbound", "inside", "inside"); } KJ_TEST("call local resolved promise inside membrane") { TestEnv env; env.testThing([&]() { auto thing = env.membraned.makeThingRequest().send().getThing(); thing.whenResolved().wait(env.waitScope); return thing; }, "inside", "inbound", "inside", "inside"); } KJ_TEST("call local object outside membrane") { TestEnv env; env.testThing([&]() { return kj::heap<ThingImpl>("outside"); }, "outside", "outside", "outside", "outbound"); } KJ_TEST("call local capability that has passed into and back out of membrane") { TestEnv env; env.testThing([&]() { auto req = env.membraned.loopbackRequest(); req.setThing(kj::heap<ThingImpl>("outside")); return req.send().wait(env.waitScope).getThing(); }, "outside", "outside", "outside", "outbound"); } KJ_TEST("call local promise pointing into membrane that eventually resolves to outside") { TestEnv env; env.testThing([&]() { auto req = env.membraned.loopbackRequest(); req.setThing(kj::heap<ThingImpl>("outside")); return req.send().getThing(); }, "outside", "outside", "outside", "outbound"); } KJ_TEST("apply membrane using copyOutOfMembrane() on struct") { TestEnv env; env.testThing([&]() { MallocMessageBuilder outsideBuilder; auto root = outsideBuilder.initRoot<test::TestContainMembrane>(); root.setCap(kj::heap<ThingImpl>("inside")); MallocMessageBuilder insideBuilder; insideBuilder.adoptRoot(copyOutOfMembrane( root.asReader(), insideBuilder.getOrphanage(), env.policy->addRef())); return insideBuilder.getRoot<test::TestContainMembrane>().getCap(); }, "inside", "inbound", "inside", "inside"); } KJ_TEST("apply membrane using copyOutOfMembrane() on list") { TestEnv env; env.testThing([&]() { MallocMessageBuilder outsideBuilder; auto list = outsideBuilder.initRoot<test::TestContainMembrane>().initList(1); list.set(0, kj::heap<ThingImpl>("inside")); MallocMessageBuilder insideBuilder; insideBuilder.initRoot<test::TestContainMembrane>().adoptList(copyOutOfMembrane( list.asReader(), insideBuilder.getOrphanage(), env.policy->addRef())); return insideBuilder.getRoot<test::TestContainMembrane>().getList()[0]; }, "inside", "inbound", "inside", "inside"); } KJ_TEST("apply membrane using copyOutOfMembrane() on AnyPointer") { TestEnv env; env.testThing([&]() { MallocMessageBuilder outsideBuilder; auto ptr = outsideBuilder.initRoot<test::TestAnyPointer>().getAnyPointerField(); ptr.setAs<test::TestMembrane::Thing>(kj::heap<ThingImpl>("inside")); MallocMessageBuilder insideBuilder; insideBuilder.initRoot<test::TestAnyPointer>().getAnyPointerField().adopt(copyOutOfMembrane( ptr.asReader(), insideBuilder.getOrphanage(), env.policy->addRef())); return insideBuilder.getRoot<test::TestAnyPointer>().getAnyPointerField() .getAs<test::TestMembrane::Thing>(); }, "inside", "inbound", "inside", "inside"); } struct TestRpcEnv { kj::EventLoop loop; kj::WaitScope waitScope; kj::TwoWayPipe pipe; TwoPartyClient client; TwoPartyClient server; test::TestMembrane::Client membraned; TestRpcEnv(kj::Maybe<kj::Promise<void>> revokePromise = nullptr) : waitScope(loop), pipe(kj::newTwoWayPipe()), client(*pipe.ends[0]), server(*pipe.ends[1], membrane(kj::heap<TestMembraneImpl>(), kj::refcounted<MembranePolicyImpl>(kj::mv(revokePromise))), rpc::twoparty::Side::SERVER), membraned(client.bootstrap().castAs<test::TestMembrane>()) {} void testThing(kj::Function<Thing::Client()> makeThing, kj::StringPtr localPassThrough, kj::StringPtr localIntercept, kj::StringPtr remotePassThrough, kj::StringPtr remoteIntercept) { testThingImpl(waitScope, membraned, kj::mv(makeThing), localPassThrough, localIntercept, remotePassThrough, remoteIntercept); } }; KJ_TEST("call remote object inside membrane") { TestRpcEnv env; env.testThing([&]() { return env.membraned.makeThingRequest().send().wait(env.waitScope).getThing(); }, "inside", "inbound", "inside", "inside"); } KJ_TEST("call remote promise inside membrane") { TestRpcEnv env; env.testThing([&]() { return env.membraned.makeThingRequest().send().getThing(); }, "inside", "inbound", "inside", "inside"); } KJ_TEST("call remote resolved promise inside membrane") { TestEnv env; env.testThing([&]() { auto thing = env.membraned.makeThingRequest().send().getThing(); thing.whenResolved().wait(env.waitScope); return thing; }, "inside", "inbound", "inside", "inside"); } KJ_TEST("call remote object outside membrane") { TestRpcEnv env; env.testThing([&]() { return kj::heap<ThingImpl>("outside"); }, "outside", "outside", "outside", "outbound"); } KJ_TEST("call remote capability that has passed into and back out of membrane") { TestRpcEnv env; env.testThing([&]() { auto req = env.membraned.loopbackRequest(); req.setThing(kj::heap<ThingImpl>("outside")); return req.send().wait(env.waitScope).getThing(); }, "outside", "outside", "outside", "outbound"); } KJ_TEST("call remote promise pointing into membrane that eventually resolves to outside") { TestRpcEnv env; env.testThing([&]() { auto req = env.membraned.loopbackRequest(); req.setThing(kj::heap<ThingImpl>("outside")); return req.send().getThing(); }, "outside", "outside", "outside", "outbound"); } KJ_TEST("revoke membrane") { auto paf = kj::newPromiseAndFulfiller<void>(); TestRpcEnv env(kj::mv(paf.promise)); auto thing = env.membraned.makeThingRequest().send().wait(env.waitScope).getThing(); auto callPromise = env.membraned.waitForeverRequest().send(); KJ_EXPECT(!callPromise.poll(env.waitScope)); paf.fulfiller->reject(KJ_EXCEPTION(DISCONNECTED, "foobar")); // TRICKY: We need to use .ignoreResult().wait() below because when compiling with // -fno-exceptions, void waits throw recoverable exceptions while non-void waits necessarily // throw fatal exceptions... but testing for fatal exceptions when exceptions are disabled // involves fork()ing the process to run the code so if it has side effects on file descriptors // then we'll get in a bad state... KJ_ASSERT(callPromise.poll(env.waitScope)); KJ_EXPECT_THROW_RECOVERABLE_MESSAGE("foobar", callPromise.ignoreResult().wait(env.waitScope)); KJ_EXPECT_THROW_RECOVERABLE_MESSAGE("foobar", env.membraned.makeThingRequest().send().ignoreResult().wait(env.waitScope)); KJ_EXPECT_THROW_RECOVERABLE_MESSAGE("foobar", thing.passThroughRequest().send().ignoreResult().wait(env.waitScope)); } } // namespace } // namespace _ } // namespace capnp
Make membrane-test more reliable by using in-process pipes.
Make membrane-test more reliable by using in-process pipes.
C++
mit
mologie/capnproto,mologie/capnproto,mologie/capnproto
f07c389379391115abedf73b58735e14e68f80e6
engine/core/controller/engine.cpp
engine/core/controller/engine.cpp
/*************************************************************************** * Copyright (C) 2005-2008 by the FIFE team * * http://www.fifengine.de * * This file is part of FIFE. * * * * FIFE is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ***************************************************************************/ // Standard C++ library includes #include <iostream> // 3rd party library includes #include <SDL.h> #include <SDL_ttf.h> // FIFE includes // These includes are split up in two parts, separated by one empty line // First block: files included from the FIFE root src directory // Second block: files included from the same folder #include "util/base/exception.h" #include "util/log/logger.h" #include "util/time/timemanager.h" #include "audio/soundmanager.h" #include "gui/console/console.h" #include "gui/guimanager.h" #include "vfs/vfs.h" #include "vfs/vfsdirectory.h" #include "vfs/directoryprovider.h" #ifdef HAVE_ZIP #include "vfs/zip/zipprovider.h" #endif #include "eventchannel/eventmanager.h" #include "video/imagepool.h" #include "video/animationpool.h" #include "audio/soundclippool.h" #include "video/renderbackend.h" #include "video/cursor.h" #ifdef HAVE_OPENGL #include "video/opengl/renderbackendopengl.h" #include "gui/base/opengl/opengl_gui_graphics.h" #endif #include "gui/base/sdl/sdl_gui_graphics.h" #include "gui/base/gui_font.h" #include "video/sdl/renderbackendsdl.h" #include "video/fonts/abstractfont.h" #include "loaders/native/video_loaders/subimage_loader.h" #include "loaders/native/video_loaders/image_loader.h" #include "loaders/native/audio_loaders/ogg_loader.h" #include "model/model.h" #include "pathfinder/linearpather/linearpather.h" #include "pathfinder/routepather/routepather.h" #include "model/metamodel/grids/hexgrid.h" #include "model/metamodel/grids/squaregrid.h" #include "view/view.h" #include "view/renderers/camerazonerenderer.h" #include "view/renderers/quadtreerenderer.h" #include "view/renderers/gridrenderer.h" #include "view/renderers/instancerenderer.h" #include "view/renderers/coordinaterenderer.h" #include "view/renderers/floatingtextrenderer.h" #include "view/renderers/cellselectionrenderer.h" #include "view/renderers/blockinginforenderer.h" #include "view/renderers/genericrenderer.h" #include "engine.h" #ifdef USE_COCOA #include <objc/message.h> #include <dlfcn.h> int main(int argc, char **argv) { return 0; } #endif namespace FIFE { static Logger _log(LM_CONTROLLER); Engine::Engine(): m_renderbackend(0), m_guimanager(0), m_eventmanager(0), m_soundmanager(0), m_timemanager(0), m_imagepool(0), m_animpool(0), m_soundclippool(0), m_vfs(0), m_model(0), m_gui_graphics(0), m_view(0), m_logmanager(0), m_cursor(0), m_settings() { #ifdef USE_COCOA // The next lines ensure that Cocoa is initialzed correctly. // This is needed for SDL to function properly on MAC OS X. void* cocoa_lib; cocoa_lib = dlopen( "/System/Library/Frameworks/Cocoa.framework/Cocoa", RTLD_LAZY ); void (*nsappload)(void); nsappload = (void(*)()) dlsym( cocoa_lib, "NSApplicationLoad"); nsappload(); // Create an autorelease pool, so autoreleased SDL objects don't leak. objc_object *NSAutoreleasePool = objc_getClass("NSAutoreleasePool"); m_autoreleasePool = objc_msgSend(NSAutoreleasePool, sel_registerName("new")); #endif preInit(); } EngineSettings& Engine::getSettings() { return m_settings; } void Engine::preInit() { m_logmanager = LogManager::instance(); FL_LOG(_log, "================== Engine pre-init start ================="); m_timemanager = new TimeManager(); FL_LOG(_log, "Time manager created"); FL_LOG(_log, "Creating VFS"); m_vfs = new VFS(); FL_LOG(_log, "Adding root directory to VFS"); m_vfs->addSource( new VFSDirectory(m_vfs) ); m_vfs->addProvider( new DirectoryProvider() ); #ifdef HAVE_ZIP FL_LOG(_log, "Adding zip provider to VFS"); m_vfs->addProvider( new ZipProvider() ); #endif //m_vfs->addProvider(ProviderDAT2()); //m_vfs->addProvider(ProviderDAT1()); FL_LOG(_log, "Engine pre-init done"); m_destroyed = false; } void Engine::init() { FL_LOG(_log, "Engine initialize start"); m_settings.validate(); FL_LOG(_log, "Engine settings validated"); // If failed to init SDL throw exception. if (SDL_Init(SDL_INIT_NOPARACHUTE | SDL_INIT_TIMER) < 0) { throw SDLException(SDL_GetError()); } SDL_EnableUNICODE(1); SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL); TTF_Init(); FL_LOG(_log, "Creating event manager"); m_eventmanager = new EventManager(); FL_LOG(_log, "Creating pools"); m_imagepool = new ImagePool(); m_animpool = new AnimationPool(); m_soundclippool = new SoundClipPool(); m_imagepool->addResourceLoader(new SubImageLoader()); m_imagepool->addResourceLoader(new ImageLoader(m_vfs)); m_soundclippool->addResourceLoader(new OggLoader(m_vfs)); FL_LOG(_log, "Creating render backend"); std::string rbackend(m_settings.getRenderBackend()); if (rbackend == "SDL") { m_renderbackend = new RenderBackendSDL(); FL_LOG(_log, "SDL Render backend created"); } else { #ifdef HAVE_OPENGL m_renderbackend = new RenderBackendOpenGL(); FL_LOG(_log, "OpenGL Render backend created"); #else m_renderbackend = new RenderBackendSDL(); // Remember the choice so we pick the right graphics class. rbackend = "SDL"; FL_WARN(_log, "Tried to select OpenGL, even though it is not compiled into the engine. Falling back to SDL Render backend"); #endif } FL_LOG(_log, "Initializing render backend"); m_renderbackend->setChunkingSize(m_settings.getImageChunkingSize()); m_renderbackend->init(); FL_LOG(_log, "Creating main screen"); m_renderbackend->createMainScreen( m_settings.getScreenWidth(), m_settings.getScreenHeight(), static_cast<unsigned char>(m_settings.getBitsPerPixel()), m_settings.isFullScreen(), m_settings.getWindowTitle(), m_settings.getWindowIcon()); FL_LOG(_log, "Main screen created"); #ifdef HAVE_OPENGL if( rbackend != "SDL" ) { m_gui_graphics = new OpenGLGuiGraphics(*m_imagepool); } #endif if( rbackend == "SDL" ) { m_gui_graphics = new SdlGuiGraphics(*m_imagepool); } FL_LOG(_log, "Constructing GUI manager"); m_guimanager = new GUIManager(*m_imagepool); FL_LOG(_log, "Events bind to GUI manager"); m_eventmanager->addSdlEventListener(m_guimanager); FL_LOG(_log, "Creating default font"); m_defaultfont = m_guimanager->setDefaultFont( m_settings.getDefaultFontPath(), m_settings.getDefaultFontSize(), m_settings.getDefaultFontGlyphs()); FL_LOG(_log, "Initializing GUI manager"); m_guimanager->init(m_gui_graphics, m_settings.getScreenWidth(), m_settings.getScreenHeight()); FL_LOG(_log, "GUI manager initialized"); SDL_EnableUNICODE(1); FL_LOG(_log, "Creating sound manager"); m_soundmanager = new SoundManager(m_soundclippool); m_soundmanager->setVolume(static_cast<float>(m_settings.getInitialVolume()) / 10); FL_LOG(_log, "Creating model"); m_model = new Model(); FL_LOG(_log, "Adding pathers to model"); m_model->adoptPather(new LinearPather()); m_model->adoptPather(new RoutePather()); FL_LOG(_log, "Adding grid prototypes to model"); m_model->adoptCellGrid(new SquareGrid()); m_model->adoptCellGrid(new HexGrid()); FL_LOG(_log, "Creating view"); m_view = new View(m_renderbackend, m_imagepool, m_animpool); FL_LOG(_log, "Creating renderers to view"); m_view->addRenderer(new CameraZoneRenderer(m_renderbackend, 0, m_imagepool)); m_view->addRenderer(new InstanceRenderer(m_renderbackend, 10, m_imagepool, m_animpool)); m_view->addRenderer(new GridRenderer(m_renderbackend, 20)); m_view->addRenderer(new CellSelectionRenderer(m_renderbackend, 30)); m_view->addRenderer(new BlockingInfoRenderer(m_renderbackend, 40)); m_view->addRenderer(new FloatingTextRenderer(m_renderbackend, 50, dynamic_cast<AbstractFont*>(m_defaultfont))); m_view->addRenderer(new QuadTreeRenderer(m_renderbackend, 60)); m_view->addRenderer(new CoordinateRenderer(m_renderbackend, 70, dynamic_cast<AbstractFont*>(m_defaultfont))); m_view->addRenderer(new GenericRenderer(m_renderbackend, 80, m_imagepool, m_animpool)); m_cursor = new Cursor(m_imagepool, m_animpool, m_renderbackend); FL_LOG(_log, "Engine intialized"); } Engine::~Engine() { if( !m_destroyed ) { destroy(); } } void Engine::destroy() { FL_LOG(_log, "Destructing engine"); delete m_cursor; delete m_view; delete m_model; delete m_soundmanager; delete m_guimanager; delete m_gui_graphics; // Note the dependancy between image and animation pools // as animations reference images they have to be deleted // before clearing the image pool. delete m_animpool; delete m_imagepool; delete m_eventmanager; m_renderbackend->deinit(); delete m_renderbackend; delete m_vfs; delete m_timemanager; TTF_Quit(); SDL_Quit(); #ifdef USE_COCOA objc_msgSend(m_autoreleasePool, sel_registerName("release")); #endif FL_LOG(_log, "================== Engine destructed =================="); m_destroyed = true; //delete m_logmanager; } void Engine::initializePumping() { m_eventmanager->processEvents(); } void Engine::pump() { m_eventmanager->processEvents(); m_renderbackend->startFrame(); m_timemanager->update(); m_model->update(); m_view->update(); m_guimanager->turn(); m_cursor->draw(); m_renderbackend->endFrame(); } void Engine::finalizePumping() { // nothing here at the moment.. } }//FIFE /* vim: set noexpandtab: set shiftwidth=2: set tabstop=2: */
/*************************************************************************** * Copyright (C) 2005-2008 by the FIFE team * * http://www.fifengine.de * * This file is part of FIFE. * * * * FIFE is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ***************************************************************************/ // Standard C++ library includes #include <iostream> // 3rd party library includes #include <SDL.h> #include <SDL_ttf.h> // FIFE includes // These includes are split up in two parts, separated by one empty line // First block: files included from the FIFE root src directory // Second block: files included from the same folder #include "util/base/exception.h" #include "util/log/logger.h" #include "util/time/timemanager.h" #include "audio/soundmanager.h" #include "gui/console/console.h" #include "gui/guimanager.h" #include "vfs/vfs.h" #include "vfs/vfsdirectory.h" #include "vfs/directoryprovider.h" #ifdef HAVE_ZIP #include "vfs/zip/zipprovider.h" #endif #include "eventchannel/eventmanager.h" #include "video/imagepool.h" #include "video/animationpool.h" #include "audio/soundclippool.h" #include "video/renderbackend.h" #include "video/cursor.h" #ifdef HAVE_OPENGL #include "video/opengl/renderbackendopengl.h" #include "gui/base/opengl/opengl_gui_graphics.h" #endif #include "gui/base/sdl/sdl_gui_graphics.h" #include "gui/base/gui_font.h" #include "video/sdl/renderbackendsdl.h" #include "video/fonts/abstractfont.h" #include "loaders/native/video_loaders/subimage_loader.h" #include "loaders/native/video_loaders/image_loader.h" #include "loaders/native/audio_loaders/ogg_loader.h" #include "model/model.h" //#include "pathfinder/linearpather/linearpather.h" #include "pathfinder/routepather/routepather.h" #include "model/metamodel/grids/hexgrid.h" #include "model/metamodel/grids/squaregrid.h" #include "view/view.h" #include "view/renderers/camerazonerenderer.h" #include "view/renderers/quadtreerenderer.h" #include "view/renderers/gridrenderer.h" #include "view/renderers/instancerenderer.h" #include "view/renderers/coordinaterenderer.h" #include "view/renderers/floatingtextrenderer.h" #include "view/renderers/cellselectionrenderer.h" #include "view/renderers/blockinginforenderer.h" #include "view/renderers/genericrenderer.h" #include "engine.h" #ifdef USE_COCOA #include <objc/message.h> #include <dlfcn.h> int main(int argc, char **argv) { return 0; } #endif namespace FIFE { static Logger _log(LM_CONTROLLER); Engine::Engine(): m_renderbackend(0), m_guimanager(0), m_eventmanager(0), m_soundmanager(0), m_timemanager(0), m_imagepool(0), m_animpool(0), m_soundclippool(0), m_vfs(0), m_model(0), m_gui_graphics(0), m_view(0), m_logmanager(0), m_cursor(0), m_settings() { #ifdef USE_COCOA // The next lines ensure that Cocoa is initialzed correctly. // This is needed for SDL to function properly on MAC OS X. void* cocoa_lib; cocoa_lib = dlopen( "/System/Library/Frameworks/Cocoa.framework/Cocoa", RTLD_LAZY ); void (*nsappload)(void); nsappload = (void(*)()) dlsym( cocoa_lib, "NSApplicationLoad"); nsappload(); // Create an autorelease pool, so autoreleased SDL objects don't leak. objc_object *NSAutoreleasePool = objc_getClass("NSAutoreleasePool"); m_autoreleasePool = objc_msgSend(NSAutoreleasePool, sel_registerName("new")); #endif preInit(); } EngineSettings& Engine::getSettings() { return m_settings; } void Engine::preInit() { m_logmanager = LogManager::instance(); FL_LOG(_log, "================== Engine pre-init start ================="); m_timemanager = new TimeManager(); FL_LOG(_log, "Time manager created"); FL_LOG(_log, "Creating VFS"); m_vfs = new VFS(); FL_LOG(_log, "Adding root directory to VFS"); m_vfs->addSource( new VFSDirectory(m_vfs) ); m_vfs->addProvider( new DirectoryProvider() ); #ifdef HAVE_ZIP FL_LOG(_log, "Adding zip provider to VFS"); m_vfs->addProvider( new ZipProvider() ); #endif //m_vfs->addProvider(ProviderDAT2()); //m_vfs->addProvider(ProviderDAT1()); FL_LOG(_log, "Engine pre-init done"); m_destroyed = false; } void Engine::init() { FL_LOG(_log, "Engine initialize start"); m_settings.validate(); FL_LOG(_log, "Engine settings validated"); // If failed to init SDL throw exception. if (SDL_Init(SDL_INIT_NOPARACHUTE | SDL_INIT_TIMER) < 0) { throw SDLException(SDL_GetError()); } SDL_EnableUNICODE(1); SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL); TTF_Init(); FL_LOG(_log, "Creating event manager"); m_eventmanager = new EventManager(); FL_LOG(_log, "Creating pools"); m_imagepool = new ImagePool(); m_animpool = new AnimationPool(); m_soundclippool = new SoundClipPool(); m_imagepool->addResourceLoader(new SubImageLoader()); m_imagepool->addResourceLoader(new ImageLoader(m_vfs)); m_soundclippool->addResourceLoader(new OggLoader(m_vfs)); FL_LOG(_log, "Creating render backend"); std::string rbackend(m_settings.getRenderBackend()); if (rbackend == "SDL") { m_renderbackend = new RenderBackendSDL(); FL_LOG(_log, "SDL Render backend created"); } else { #ifdef HAVE_OPENGL m_renderbackend = new RenderBackendOpenGL(); FL_LOG(_log, "OpenGL Render backend created"); #else m_renderbackend = new RenderBackendSDL(); // Remember the choice so we pick the right graphics class. rbackend = "SDL"; FL_WARN(_log, "Tried to select OpenGL, even though it is not compiled into the engine. Falling back to SDL Render backend"); #endif } FL_LOG(_log, "Initializing render backend"); m_renderbackend->setChunkingSize(m_settings.getImageChunkingSize()); m_renderbackend->init(); FL_LOG(_log, "Creating main screen"); m_renderbackend->createMainScreen( m_settings.getScreenWidth(), m_settings.getScreenHeight(), static_cast<unsigned char>(m_settings.getBitsPerPixel()), m_settings.isFullScreen(), m_settings.getWindowTitle(), m_settings.getWindowIcon()); FL_LOG(_log, "Main screen created"); #ifdef HAVE_OPENGL if( rbackend != "SDL" ) { m_gui_graphics = new OpenGLGuiGraphics(*m_imagepool); } #endif if( rbackend == "SDL" ) { m_gui_graphics = new SdlGuiGraphics(*m_imagepool); } FL_LOG(_log, "Constructing GUI manager"); m_guimanager = new GUIManager(*m_imagepool); FL_LOG(_log, "Events bind to GUI manager"); m_eventmanager->addSdlEventListener(m_guimanager); FL_LOG(_log, "Creating default font"); m_defaultfont = m_guimanager->setDefaultFont( m_settings.getDefaultFontPath(), m_settings.getDefaultFontSize(), m_settings.getDefaultFontGlyphs()); FL_LOG(_log, "Initializing GUI manager"); m_guimanager->init(m_gui_graphics, m_settings.getScreenWidth(), m_settings.getScreenHeight()); FL_LOG(_log, "GUI manager initialized"); SDL_EnableUNICODE(1); FL_LOG(_log, "Creating sound manager"); m_soundmanager = new SoundManager(m_soundclippool); m_soundmanager->setVolume(static_cast<float>(m_settings.getInitialVolume()) / 10); FL_LOG(_log, "Creating model"); m_model = new Model(); FL_LOG(_log, "Adding pathers to model"); // m_model->adoptPather(new LinearPather()); m_model->adoptPather(new RoutePather()); FL_LOG(_log, "Adding grid prototypes to model"); m_model->adoptCellGrid(new SquareGrid()); m_model->adoptCellGrid(new HexGrid()); FL_LOG(_log, "Creating view"); m_view = new View(m_renderbackend, m_imagepool, m_animpool); FL_LOG(_log, "Creating renderers to view"); m_view->addRenderer(new CameraZoneRenderer(m_renderbackend, 0, m_imagepool)); m_view->addRenderer(new InstanceRenderer(m_renderbackend, 10, m_imagepool, m_animpool)); m_view->addRenderer(new GridRenderer(m_renderbackend, 20)); m_view->addRenderer(new CellSelectionRenderer(m_renderbackend, 30)); m_view->addRenderer(new BlockingInfoRenderer(m_renderbackend, 40)); m_view->addRenderer(new FloatingTextRenderer(m_renderbackend, 50, dynamic_cast<AbstractFont*>(m_defaultfont))); m_view->addRenderer(new QuadTreeRenderer(m_renderbackend, 60)); m_view->addRenderer(new CoordinateRenderer(m_renderbackend, 70, dynamic_cast<AbstractFont*>(m_defaultfont))); m_view->addRenderer(new GenericRenderer(m_renderbackend, 80, m_imagepool, m_animpool)); m_cursor = new Cursor(m_imagepool, m_animpool, m_renderbackend); FL_LOG(_log, "Engine intialized"); } Engine::~Engine() { if( !m_destroyed ) { destroy(); } } void Engine::destroy() { FL_LOG(_log, "Destructing engine"); delete m_cursor; delete m_view; delete m_model; delete m_soundmanager; delete m_guimanager; delete m_gui_graphics; // Note the dependancy between image and animation pools // as animations reference images they have to be deleted // before clearing the image pool. delete m_animpool; delete m_imagepool; delete m_eventmanager; m_renderbackend->deinit(); delete m_renderbackend; delete m_vfs; delete m_timemanager; TTF_Quit(); SDL_Quit(); #ifdef USE_COCOA objc_msgSend(m_autoreleasePool, sel_registerName("release")); #endif FL_LOG(_log, "================== Engine destructed =================="); m_destroyed = true; //delete m_logmanager; } void Engine::initializePumping() { m_eventmanager->processEvents(); } void Engine::pump() { m_eventmanager->processEvents(); m_renderbackend->startFrame(); m_timemanager->update(); m_model->update(); m_view->update(); m_guimanager->turn(); m_cursor->draw(); m_renderbackend->endFrame(); } void Engine::finalizePumping() { // nothing here at the moment.. } }//FIFE /* vim: set noexpandtab: set shiftwidth=2: set tabstop=2: */
remove the reference of the LinearPather
remove the reference of the LinearPather
C++
lgpl-2.1
cbeck88/fifengine,gravitystorm/fifengine,fifengine/fifengine,cbeck88/fifengine,fifengine/fifengine,Niektory/fifengine,cbeck88/fifengine,Niektory/fifengine,Niektory/fifengine,cbeck88/fifengine,fifengine/fifengine,gravitystorm/fifengine,gravitystorm/fifengine,gravitystorm/fifengine
0e1da8e41f117180932f9bce75da6b452b27bdb2
google_cloud_debugger_test/dbgarray_test.cc
google_cloud_debugger_test/dbgarray_test.cc
// Copyright 2017 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <gmock/gmock.h> #include <gtest/gtest.h> #include <string> #include "ccomptr.h" #include "common_action_mocks.h" #include "i_cordebug_mocks.h" #include "i_evalcoordinator_mock.h" #include "dbgarray.h" using ::testing::DoAll; using ::testing::Return; using ::testing::SetArgPointee; using ::testing::SetArrayArgument; using ::testing::_; using google::cloud::diagnostics::debug::Variable; using google_cloud_debugger::CComPtr; using google_cloud_debugger::DbgArray; using std::string; namespace google_cloud_debugger_test { // Test Fixture for DbgArray. // Contains various ICorDebug mock objects needed. class DbgArrayTest : public ::testing::Test { protected: virtual void SetUp() { // By default, sets array_value_ to the second argument // whenever QueryInterface is called. ON_CALL(array_value_, QueryInterface(_, _)) .WillByDefault( DoAll(SetArgPointee<1>(&array_value_), Return(S_OK))); } // Sets up various mock objects so when we use them with // a DbgArray class, we will get an array with 2 elements. void SetUpArray() { EXPECT_CALL(array_type_, GetFirstTypeParameter(_)) .WillRepeatedly(DoAll(SetArgPointee<0>(&array_element_type_), Return(S_OK))); EXPECT_CALL(array_element_type_, GetType(_)) .WillRepeatedly(DoAll(SetArgPointee<0>(CorElementType::ELEMENT_TYPE_I4), Return(S_OK))); // If queried for ICorDebugHeapValue2, returns heap_value. // This happens when the Initialize function tries to create a strong // handle of the array. ON_CALL(array_value_, QueryInterface(__uuidof(ICorDebugHeapValue2), _)) .WillByDefault(DoAll(SetArgPointee<1>(&heap_value_), Return(S_OK))); // Makes heap_value returns handle_value if CreateHandle is called. EXPECT_CALL(heap_value_, CreateHandle(_, _)) .WillRepeatedly( DoAll(SetArgPointee<1>(&handle_value_), Return(S_OK))); // The handle should dereference to the array value. ON_CALL(handle_value_, Dereference(_)) .WillByDefault( DoAll(SetArgPointee<0>(&array_value_), Return(S_OK))); // Initialize function should issue call to get dimensions // and ranks of the array. EXPECT_CALL(array_value_, GetDimensions(_, _)) .WillRepeatedly(DoAll(SetArrayArgument<1>(dimensions_, dimensions_ + 1), Return(S_OK))); EXPECT_CALL(array_type_, GetRank(_)) .WillRepeatedly(DoAll(SetArgPointee<0>(1), Return(S_OK))); } // An array with 2 elements. ULONG32 dimensions_[1] = { 2 }; // Types of the array. ICorDebugTypeMock array_type_; ICorDebugTypeMock array_element_type_; // ICorDebugValue that represents the array. ICorDebugArrayValueMock array_value_; // Heap and handle value created for the array. ICorDebugHeapValue2Mock heap_value_; ICorDebugHandleValueMock handle_value_; // EvalCoordinator to evaluate array members. IEvalCoordinatorMock eval_coordinator_; }; // Tests Initialize function of DbgArray. TEST_F(DbgArrayTest, Initialize) { SetUpArray(); // Have to make sure that the mock value survives after // the destructor of DbgArray is called, otherwise, DbgArray // may try to delete value that is obselete. { DbgArray dbgarray(&array_type_, 1); dbgarray.Initialize(&array_value_, FALSE); HRESULT hr = dbgarray.GetInitializeHr(); EXPECT_TRUE(SUCCEEDED(hr)) << "Failed with hr: " << hr; } } // Tests error cases for Initialize function of DbgArray. TEST_F(DbgArrayTest, InitializeError) { // Null type. { DbgArray dbgarray(nullptr, 1); dbgarray.Initialize(&array_value_, FALSE); EXPECT_EQ(dbgarray.GetInitializeHr(), E_INVALIDARG); } // Makes GetFirstTypeParameter returns error. { DbgArray dbgarray(&array_type_, 1); EXPECT_CALL(array_type_, GetFirstTypeParameter(_)) .Times(1) .WillRepeatedly(Return(CORDBG_E_CONTEXT_UNVAILABLE)); dbgarray.Initialize(&array_value_, FALSE); EXPECT_EQ(dbgarray.GetInitializeHr(), CORDBG_E_CONTEXT_UNVAILABLE); } EXPECT_CALL(array_type_, GetFirstTypeParameter(_)) .WillRepeatedly(DoAll(SetArgPointee<0>(&array_element_type_), Return(S_OK))); // Returns failure when querying the element type of the array. { DbgArray dbgarray(&array_type_, 1); EXPECT_CALL(array_element_type_, GetType(_)) .WillRepeatedly(Return(E_ACCESSDENIED)); dbgarray.Initialize(&array_value_, FALSE); EXPECT_EQ(dbgarray.GetInitializeHr(), E_ACCESSDENIED); } EXPECT_CALL(array_element_type_, GetType(_)) .WillRepeatedly(DoAll(SetArgPointee<0>(CorElementType::ELEMENT_TYPE_I4), Return(S_OK))); // Makes GetRank returns error. { DbgArray dbgarray(&array_type_, 1); EXPECT_CALL(array_type_, GetRank(_)) .WillRepeatedly(DoAll(SetArgPointee<0>(1), Return(COR_E_SAFEARRAYRANKMISMATCH))); dbgarray.Initialize(&array_value_, FALSE); EXPECT_EQ(dbgarray.GetInitializeHr(), COR_E_SAFEARRAYRANKMISMATCH); } EXPECT_CALL(array_type_, GetRank(_)) .WillRepeatedly(DoAll(SetArgPointee<0>(1), Return(S_OK))); // By default, sets array_value_ to the second argument // whenever QueryInterface is called. ON_CALL(array_value_, QueryInterface(_, _)) .WillByDefault( DoAll(SetArgPointee<1>(&array_value_), Return(S_OK))); // Returns error when trying to create a handle for the array. { DbgArray dbgarray(&array_type_, 1); ON_CALL(array_value_, QueryInterface(__uuidof(ICorDebugHeapValue2), _)) .WillByDefault(Return(E_NOINTERFACE)); dbgarray.Initialize(&array_value_, FALSE); EXPECT_EQ(dbgarray.GetInitializeHr(), E_NOINTERFACE); } ON_CALL(array_value_, QueryInterface(__uuidof(ICorDebugHeapValue2), _)) .WillByDefault(DoAll(SetArgPointee<1>(&heap_value_), Return(S_OK))); // Returns error when trying to create a handle for the array. { DbgArray dbgarray(&array_type_, 1); EXPECT_CALL(heap_value_, CreateHandle(_, _)) .Times(1) .WillRepeatedly(Return(CORDBG_E_BAD_REFERENCE_VALUE)); dbgarray.Initialize(&array_value_, FALSE); EXPECT_EQ(dbgarray.GetInitializeHr(), CORDBG_E_BAD_REFERENCE_VALUE); } // Makes heap_value returns handle_value if CreateHandle is called. EXPECT_CALL(heap_value_, CreateHandle(_, _)) .WillRepeatedly( DoAll(SetArgPointee<1>(&handle_value_), Return(S_OK))); // Makes GetDimensions returns incorrect value. { EXPECT_CALL(array_value_, GetDimensions(_, _)) .Times(1) .WillRepeatedly(Return(CORDBG_S_BAD_START_SEQUENCE_POINT)); DbgArray dbgarray(&array_type_, 1); dbgarray.Initialize(&array_value_, FALSE); EXPECT_EQ(dbgarray.GetInitializeHr(), CORDBG_S_BAD_START_SEQUENCE_POINT); } } // Tests GetArrayItem function of DbgArray. TEST_F(DbgArrayTest, TestGetArrayItem) { SetUpArray(); DbgArray dbgarray(&array_type_, 1); dbgarray.Initialize(&array_value_, FALSE); HRESULT hr = dbgarray.GetInitializeHr(); EXPECT_TRUE(SUCCEEDED(hr)) << "Failed with hr: " << hr; int position = 3; CComPtr<ICorDebugValue> array_item; EXPECT_CALL(array_value_, GetElementAtPosition(position, _)) .Times(1) .WillRepeatedly(Return(S_OK)); hr = dbgarray.GetArrayItem(position, &array_item); } // Tests error cases for GetArrayItem function of DbgArray. TEST_F(DbgArrayTest, TestGetArrayItemError) { SetUpArray(); DbgArray dbgarray(&array_type_, 1); int position = 3; CComPtr<ICorDebugValue> array_item; // If array is not initialized, error should be thrown. { EXPECT_EQ(dbgarray.GetArrayItem(position, &array_item), E_FAIL); } dbgarray.Initialize(&array_value_, FALSE); EXPECT_CALL(array_value_, GetElementAtPosition(position, _)) .Times(1) .WillRepeatedly(Return(E_ACCESSDENIED)); EXPECT_EQ(dbgarray.GetArrayItem(position, &array_item), E_ACCESSDENIED); } // Tests PopulateType function of DbgArray. TEST_F(DbgArrayTest, TestPopulateType) { SetUpArray(); Variable variable; DbgArray dbgarray(&array_type_, 1); dbgarray.Initialize(&array_value_, FALSE); dbgarray.PopulateType(&variable); EXPECT_EQ(variable.type(), "System.Int32[]"); } // Tests PopulateType function of DbgArray. TEST_F(DbgArrayTest, TestPopulateTypeError) { SetUpArray(); { Variable variable; // Since the type given is null, Initialize function will return // E_INVALIDARG. DbgArray dbgarray(nullptr, 1); dbgarray.Initialize(&array_value_, FALSE); // PopulateType should return E_INVALIDARG since Initialize // function fails. EXPECT_EQ(dbgarray.GetInitializeHr(), E_INVALIDARG); EXPECT_EQ(dbgarray.GetInitializeHr(), dbgarray.PopulateType(&variable)); } DbgArray dbgarray(&array_type_, 1); dbgarray.Initialize(&array_value_, FALSE); // Should throws error for null variable. EXPECT_EQ(dbgarray.PopulateType(nullptr), E_INVALIDARG); } // Tests PopulateMembers function of DbgArray. TEST_F(DbgArrayTest, TestPopulateMembers) { SetUpArray(); // If array is null, then variables should have 0 members. { Variable variable; DbgArray dbgarray(&array_type_, 1); // Initialize to a null array. dbgarray.Initialize(&array_value_, TRUE); HRESULT hr = dbgarray.PopulateMembers(&variable, &eval_coordinator_); EXPECT_TRUE(SUCCEEDED(hr)) << "Failed with hr: " << hr; EXPECT_EQ(variable.members_size(), 0); } Variable variable; DbgArray dbgarray(&array_type_, 1); dbgarray.Initialize(&array_value_, FALSE); ICorDebugGenericValueMock item0; int32_t value0 = 20; SetUpMockGenericValue(&item0, value0); // Returns ICorDebugValue that represents 20. EXPECT_CALL(array_value_, GetElementAtPosition(0, _)) .Times(1) .WillRepeatedly(DoAll(SetArgPointee<1>(&item0), Return(S_OK))); ICorDebugGenericValueMock item1; int32_t value1 = 40; SetUpMockGenericValue(&item1, value1); // Returns ICorDebugValue that represents 40. EXPECT_CALL(array_value_, GetElementAtPosition(1, _)) .Times(1) .WillRepeatedly(DoAll(SetArgPointee<1>(&item1), Return(S_OK))); HRESULT hr = dbgarray.PopulateMembers(&variable, &eval_coordinator_); EXPECT_TRUE(SUCCEEDED(hr)) << "Failed with hr: " << hr; EXPECT_EQ(variable.members(0).value(), std::to_string(value0)); EXPECT_EQ(variable.members(1).value(), std::to_string(value1)); } // Tests error case for PopulateMembers function of DbgArray. TEST_F(DbgArrayTest, TestPopulateMembersError) { SetUpArray(); // If Initialize is not called { // Since the type given is null, Initialize function will return // E_INVALIDARG. DbgArray dbgarray(nullptr, 1); dbgarray.Initialize(&array_value_, FALSE); // PopulateMembers should return E_INVALIDARG since Initialize // function fails. EXPECT_EQ(dbgarray.GetInitializeHr(), E_INVALIDARG); Variable variable; EXPECT_EQ(dbgarray.GetInitializeHr(), dbgarray.PopulateMembers(&variable, &eval_coordinator_)); } DbgArray dbgarray(&array_type_, 1); dbgarray.Initialize(&array_value_, FALSE); // Should throws error for null variable. EXPECT_EQ(dbgarray.PopulateMembers(nullptr, &eval_coordinator_), E_INVALIDARG); Variable variable; // Should throws error for null EvalCoordinator. EXPECT_EQ(dbgarray.PopulateMembers(&variable, nullptr), E_INVALIDARG); } } // namespace google_cloud_debugger_test
// Copyright 2017 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <gmock/gmock.h> #include <gtest/gtest.h> #include <string> #include "ccomptr.h" #include "common_action_mocks.h" #include "i_cordebug_mocks.h" #include "i_evalcoordinator_mock.h" #include "dbgarray.h" using ::testing::DoAll; using ::testing::Return; using ::testing::SetArgPointee; using ::testing::SetArrayArgument; using ::testing::_; using google::cloud::diagnostics::debug::Variable; using google_cloud_debugger::CComPtr; using google_cloud_debugger::DbgArray; using std::string; namespace google_cloud_debugger_test { // Test Fixture for DbgArray. // Contains various ICorDebug mock objects needed. class DbgArrayTest : public ::testing::Test { protected: virtual void SetUp() { // By default, sets array_value_ to the second argument // whenever QueryInterface is called. ON_CALL(array_value_, QueryInterface(_, _)) .WillByDefault( DoAll(SetArgPointee<1>(&array_value_), Return(S_OK))); } // Sets up various mock objects so when we use them with // a DbgArray class, we will get an array with 2 elements. void SetUpArray() { EXPECT_CALL(array_type_, GetFirstTypeParameter(_)) .WillRepeatedly(DoAll(SetArgPointee<0>(&array_element_type_), Return(S_OK))); EXPECT_CALL(array_element_type_, GetType(_)) .WillRepeatedly(DoAll(SetArgPointee<0>(CorElementType::ELEMENT_TYPE_I4), Return(S_OK))); // If queried for ICorDebugHeapValue2, returns heap_value. // This happens when the Initialize function tries to create a strong // handle of the array. ON_CALL(array_value_, QueryInterface(__uuidof(ICorDebugHeapValue2), _)) .WillByDefault(DoAll(SetArgPointee<1>(&heap_value_), Return(S_OK))); // Makes heap_value returns handle_value if CreateHandle is called. EXPECT_CALL(heap_value_, CreateHandle(_, _)) .WillRepeatedly( DoAll(SetArgPointee<1>(&handle_value_), Return(S_OK))); // The handle should dereference to the array value. ON_CALL(handle_value_, Dereference(_)) .WillByDefault( DoAll(SetArgPointee<0>(&array_value_), Return(S_OK))); // Initialize function should issue call to get dimensions // and ranks of the array. EXPECT_CALL(array_value_, GetDimensions(_, _)) .WillRepeatedly(DoAll(SetArrayArgument<1>(dimensions_, dimensions_ + 1), Return(S_OK))); EXPECT_CALL(array_type_, GetRank(_)) .WillRepeatedly(DoAll(SetArgPointee<0>(1), Return(S_OK))); } // An array with 2 elements. ULONG32 dimensions_[1] = { 2 }; // Types of the array. ICorDebugTypeMock array_type_; ICorDebugTypeMock array_element_type_; // ICorDebugValue that represents the array. ICorDebugArrayValueMock array_value_; // Heap and handle value created for the array. ICorDebugHeapValue2Mock heap_value_; ICorDebugHandleValueMock handle_value_; // EvalCoordinator to evaluate array members. IEvalCoordinatorMock eval_coordinator_; }; // Tests Initialize function of DbgArray. TEST_F(DbgArrayTest, Initialize) { SetUpArray(); // Have to make sure that the mock value survives after // the destructor of DbgArray is called, otherwise, DbgArray // may try to delete value that is obselete. { DbgArray dbgarray(&array_type_, 1); dbgarray.Initialize(&array_value_, FALSE); HRESULT hr = dbgarray.GetInitializeHr(); EXPECT_TRUE(SUCCEEDED(hr)) << "Failed with hr: " << hr; } } // Tests error cases for Initialize function of DbgArray. TEST_F(DbgArrayTest, InitializeError) { // Null type. { DbgArray dbgarray(nullptr, 1); dbgarray.Initialize(&array_value_, FALSE); EXPECT_EQ(dbgarray.GetInitializeHr(), E_INVALIDARG); } // Makes GetFirstTypeParameter returns error. { DbgArray dbgarray(&array_type_, 1); EXPECT_CALL(array_type_, GetFirstTypeParameter(_)) .Times(1) .WillRepeatedly(Return(CORDBG_E_CONTEXT_UNVAILABLE)); dbgarray.Initialize(&array_value_, FALSE); EXPECT_EQ(dbgarray.GetInitializeHr(), CORDBG_E_CONTEXT_UNVAILABLE); } EXPECT_CALL(array_type_, GetFirstTypeParameter(_)) .WillRepeatedly(DoAll(SetArgPointee<0>(&array_element_type_), Return(S_OK))); // Returns failure when querying the element type of the array. { DbgArray dbgarray(&array_type_, 1); EXPECT_CALL(array_element_type_, GetType(_)) .WillRepeatedly(Return(E_ACCESSDENIED)); dbgarray.Initialize(&array_value_, FALSE); EXPECT_EQ(dbgarray.GetInitializeHr(), E_ACCESSDENIED); } EXPECT_CALL(array_element_type_, GetType(_)) .WillRepeatedly(DoAll(SetArgPointee<0>(CorElementType::ELEMENT_TYPE_I4), Return(S_OK))); // Makes GetRank returns error. { DbgArray dbgarray(&array_type_, 1); EXPECT_CALL(array_type_, GetRank(_)) .WillRepeatedly(DoAll(SetArgPointee<0>(1), Return(COR_E_SAFEARRAYRANKMISMATCH))); dbgarray.Initialize(&array_value_, FALSE); EXPECT_EQ(dbgarray.GetInitializeHr(), COR_E_SAFEARRAYRANKMISMATCH); } EXPECT_CALL(array_type_, GetRank(_)) .WillRepeatedly(DoAll(SetArgPointee<0>(1), Return(S_OK))); // By default, sets array_value_ to the second argument // whenever QueryInterface is called. ON_CALL(array_value_, QueryInterface(_, _)) .WillByDefault( DoAll(SetArgPointee<1>(&array_value_), Return(S_OK))); // Returns error when trying to create a handle for the array. { DbgArray dbgarray(&array_type_, 1); ON_CALL(array_value_, QueryInterface(__uuidof(ICorDebugHeapValue2), _)) .WillByDefault(Return(E_NOINTERFACE)); dbgarray.Initialize(&array_value_, FALSE); EXPECT_EQ(dbgarray.GetInitializeHr(), E_NOINTERFACE); } ON_CALL(array_value_, QueryInterface(__uuidof(ICorDebugHeapValue2), _)) .WillByDefault(DoAll(SetArgPointee<1>(&heap_value_), Return(S_OK))); // Returns error when trying to create a handle for the array. { DbgArray dbgarray(&array_type_, 1); EXPECT_CALL(heap_value_, CreateHandle(_, _)) .Times(1) .WillRepeatedly(Return(CORDBG_E_BAD_REFERENCE_VALUE)); dbgarray.Initialize(&array_value_, FALSE); EXPECT_EQ(dbgarray.GetInitializeHr(), CORDBG_E_BAD_REFERENCE_VALUE); } // Makes heap_value returns handle_value if CreateHandle is called. EXPECT_CALL(heap_value_, CreateHandle(_, _)) .WillRepeatedly( DoAll(SetArgPointee<1>(&handle_value_), Return(S_OK))); // Makes GetDimensions returns incorrect value. { EXPECT_CALL(array_value_, GetDimensions(_, _)) .Times(1) .WillRepeatedly(Return(CORDBG_S_BAD_START_SEQUENCE_POINT)); DbgArray dbgarray(&array_type_, 1); dbgarray.Initialize(&array_value_, FALSE); EXPECT_EQ(dbgarray.GetInitializeHr(), CORDBG_S_BAD_START_SEQUENCE_POINT); } } // Tests GetArrayItem function of DbgArray. TEST_F(DbgArrayTest, TestGetArrayItem) { SetUpArray(); DbgArray dbgarray(&array_type_, 1); dbgarray.Initialize(&array_value_, FALSE); HRESULT hr = dbgarray.GetInitializeHr(); EXPECT_TRUE(SUCCEEDED(hr)) << "Failed with hr: " << hr; int position = 3; CComPtr<ICorDebugValue> array_item; EXPECT_CALL(array_value_, GetElementAtPosition(position, _)) .Times(1) .WillRepeatedly(Return(S_OK)); hr = dbgarray.GetArrayItem(position, &array_item); EXPECT_TRUE(SUCCEEDED(hr)) << "Failed with hr: " << hr; } // Tests error cases for GetArrayItem function of DbgArray. TEST_F(DbgArrayTest, TestGetArrayItemError) { SetUpArray(); DbgArray dbgarray(&array_type_, 1); int position = 3; CComPtr<ICorDebugValue> array_item; // If array is not initialized, error should be thrown. { EXPECT_EQ(dbgarray.GetArrayItem(position, &array_item), E_FAIL); } dbgarray.Initialize(&array_value_, FALSE); EXPECT_CALL(array_value_, GetElementAtPosition(position, _)) .Times(1) .WillRepeatedly(Return(E_ACCESSDENIED)); EXPECT_EQ(dbgarray.GetArrayItem(position, &array_item), E_ACCESSDENIED); } // Tests PopulateType function of DbgArray. TEST_F(DbgArrayTest, TestPopulateType) { SetUpArray(); Variable variable; DbgArray dbgarray(&array_type_, 1); dbgarray.Initialize(&array_value_, FALSE); dbgarray.PopulateType(&variable); EXPECT_EQ(variable.type(), "System.Int32[]"); } // Tests PopulateType function of DbgArray. TEST_F(DbgArrayTest, TestPopulateTypeError) { SetUpArray(); { Variable variable; // Since the type given is null, Initialize function will return // E_INVALIDARG. DbgArray dbgarray(nullptr, 1); dbgarray.Initialize(&array_value_, FALSE); // PopulateType should return E_INVALIDARG since Initialize // function fails. EXPECT_EQ(dbgarray.GetInitializeHr(), E_INVALIDARG); EXPECT_EQ(dbgarray.GetInitializeHr(), dbgarray.PopulateType(&variable)); } DbgArray dbgarray(&array_type_, 1); dbgarray.Initialize(&array_value_, FALSE); // Should throws error for null variable. EXPECT_EQ(dbgarray.PopulateType(nullptr), E_INVALIDARG); } // Tests PopulateMembers function of DbgArray. TEST_F(DbgArrayTest, TestPopulateMembers) { SetUpArray(); // If array is null, then variables should have 0 members. { Variable variable; DbgArray dbgarray(&array_type_, 1); // Initialize to a null array. dbgarray.Initialize(&array_value_, TRUE); HRESULT hr = dbgarray.PopulateMembers(&variable, &eval_coordinator_); EXPECT_TRUE(SUCCEEDED(hr)) << "Failed with hr: " << hr; EXPECT_EQ(variable.members_size(), 0); } Variable variable; DbgArray dbgarray(&array_type_, 1); dbgarray.Initialize(&array_value_, FALSE); ICorDebugGenericValueMock item0; int32_t value0 = 20; SetUpMockGenericValue(&item0, value0); // Returns ICorDebugValue that represents 20. EXPECT_CALL(array_value_, GetElementAtPosition(0, _)) .Times(1) .WillRepeatedly(DoAll(SetArgPointee<1>(&item0), Return(S_OK))); ICorDebugGenericValueMock item1; int32_t value1 = 40; SetUpMockGenericValue(&item1, value1); // Returns ICorDebugValue that represents 40. EXPECT_CALL(array_value_, GetElementAtPosition(1, _)) .Times(1) .WillRepeatedly(DoAll(SetArgPointee<1>(&item1), Return(S_OK))); HRESULT hr = dbgarray.PopulateMembers(&variable, &eval_coordinator_); EXPECT_TRUE(SUCCEEDED(hr)) << "Failed with hr: " << hr; EXPECT_EQ(variable.members(0).value(), std::to_string(value0)); EXPECT_EQ(variable.members(1).value(), std::to_string(value1)); } // Tests error case for PopulateMembers function of DbgArray. TEST_F(DbgArrayTest, TestPopulateMembersError) { SetUpArray(); // If Initialize is not called { // Since the type given is null, Initialize function will return // E_INVALIDARG. DbgArray dbgarray(nullptr, 1); dbgarray.Initialize(&array_value_, FALSE); // PopulateMembers should return E_INVALIDARG since Initialize // function fails. EXPECT_EQ(dbgarray.GetInitializeHr(), E_INVALIDARG); Variable variable; EXPECT_EQ(dbgarray.GetInitializeHr(), dbgarray.PopulateMembers(&variable, &eval_coordinator_)); } DbgArray dbgarray(&array_type_, 1); dbgarray.Initialize(&array_value_, FALSE); // Should throws error for null variable. EXPECT_EQ(dbgarray.PopulateMembers(nullptr, &eval_coordinator_), E_INVALIDARG); Variable variable; // Should throws error for null EvalCoordinator. EXPECT_EQ(dbgarray.PopulateMembers(&variable, nullptr), E_INVALIDARG); } } // namespace google_cloud_debugger_test
Fix TestGetArrayItem test
Fix TestGetArrayItem test
C++
apache-2.0
GoogleCloudPlatform/google-cloud-dotnet-debugger,GoogleCloudPlatform/google-cloud-dotnet-debugger,GoogleCloudPlatform/google-cloud-dotnet-debugger,GoogleCloudPlatform/google-cloud-dotnet-debugger
e849a8d7eda4e27acca1b6381685e572ab04e5d3
include/dll/rbm/rbm_base.hpp
include/dll/rbm/rbm_base.hpp
//======================================================================= // Copyright (c) 2014-2017 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 <iosfwd> #include <fstream> #include "cpp_utils/io.hpp" #include "dll/generators.hpp" #include "dll/layer.hpp" #include "dll/trainer/rbm_trainer_fwd.hpp" namespace dll { /*! * \brief Simple traits to pass information around from the real * class to the CRTP class. */ template <typename Parent> struct rbm_base_traits; /*! * \brief Base class for Restricted Boltzmann Machine. * * It contains configurable properties that are used by each * version of RBM. It also contains common functions that are * injected using CRTP technique. */ template <typename Parent, typename Desc> struct rbm_base : layer<Parent> { using conf = Desc; using parent_t = Parent; using weight = typename conf::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; //Configurable properties weight learning_rate = 1e-1; ///< The learning rate weight initial_momentum = 0.5; ///< The initial momentum weight final_momentum = 0.9; ///< The final momentum applied after *final_momentum_epoch* epoch weight final_momentum_epoch = 6; ///< The epoch at which momentum change weight momentum = 0; ///< The current momentum weight l1_weight_cost = 0.0002; ///< The weight cost for L1 weight decay weight l2_weight_cost = 0.0002; ///< The weight cost for L2 weight decay weight sparsity_target = 0.01; ///< The sparsity target weight decay_rate = 0.99; ///< The sparsity decay rate weight sparsity_cost = 1.0; ///< The sparsity cost (or sparsity multiplier) weight pbias = 0.002; weight pbias_lambda = 5; weight gradient_clip = 5.0; ///< The default gradient clipping value rbm_base() { //Nothing to do } void backup_weights() { unique_safe_get(as_derived().bak_w) = as_derived().w; unique_safe_get(as_derived().bak_b) = as_derived().b; unique_safe_get(as_derived().bak_c) = as_derived().c; } void restore_weights() { as_derived().w = *as_derived().bak_w; as_derived().b = *as_derived().bak_b; as_derived().c = *as_derived().bak_c; } template<typename Input> double reconstruction_error(const Input& item) { return parent_t::reconstruction_error_impl(item, as_derived()); } //Normal Train functions template <bool EnableWatcher = true, typename RW = void, typename Generator, typename... Args, cpp_enable_if(is_generator<Generator>::value)> double train(Generator& generator, size_t max_epochs, Args... args) { dll::rbm_trainer<parent_t, EnableWatcher, RW, false> trainer(args...); return trainer.train(as_derived(), generator, max_epochs); } template <bool EnableWatcher = true, typename RW = void, typename Input, typename... Args, cpp_enable_if(!is_generator<Input>::value)> double train(const Input& training_data, size_t max_epochs, Args... args) { dll::rbm_trainer<parent_t, EnableWatcher, RW, false> trainer(args...); return trainer.train(as_derived(), training_data.begin(), training_data.end(), max_epochs); } template <bool EnableWatcher = true, typename RW = void, typename Iterator, typename... Args> double train(Iterator&& first, Iterator&& last, size_t max_epochs, Args... args) { dll::rbm_trainer<parent_t, EnableWatcher, RW, false> trainer(args...); return trainer.train(as_derived(), std::forward<Iterator>(first), std::forward<Iterator>(last), max_epochs); } //Train denoising autoencoder template <bool EnableWatcher = true, typename RW = void, typename Noisy, typename Clean, typename... Args> double train_denoising(const Noisy& noisy, const Clean& clean, size_t max_epochs, Args... args) { dll::rbm_trainer<parent_t, EnableWatcher, RW, true> trainer(args...); return trainer.train(as_derived(), noisy.begin(), noisy.end(), clean.begin(), clean.end(), max_epochs); } template <typename NIterator, typename CIterator, bool EnableWatcher = true, typename RW = void, typename... Args> double train_denoising(NIterator noisy_it, NIterator noisy_end, CIterator clean_it, CIterator clean_end, size_t max_epochs, Args... args) { dll::rbm_trainer<parent_t, EnableWatcher, RW, true> trainer(args...); return trainer.train(as_derived(), noisy_it, noisy_end, clean_it, clean_end, max_epochs); } //Train denoising autoencoder (auto) template <bool EnableWatcher = true, typename RW = void, typename Clean, typename... Args> double train_denoising_auto(const Clean& clean, size_t max_epochs, double noise, Args... args) { dll::rbm_trainer<parent_t, EnableWatcher, RW, false> trainer(args...); return trainer.train_denoising_auto(as_derived(), clean.begin(), clean.end(), max_epochs, noise); } template <typename CIterator, bool EnableWatcher = true, typename RW = void, typename... Args> double train_denoising_auto(CIterator clean_it, CIterator clean_end, size_t max_epochs, double noise, Args... args) { dll::rbm_trainer<parent_t, EnableWatcher, RW, false> trainer(args...); return trainer.train_denoising_auto(as_derived(), clean_it, clean_end, max_epochs, noise); } // Features template<typename Input> output_one_t features(const Input& input){ return activate_hidden(input);; } template<typename Input> output_one_t activate_hidden(const Input& input){ auto output = as_derived().template prepare_one_output<Input>(); as_derived().activate_hidden(output, input); return output; } //I/O functions void store(const std::string& file) const { store(file, as_derived()); } void store(std::ostream& os) const { store(os, as_derived()); } void load(const std::string& file) { load(file, as_derived()); } void load(std::istream& is) { load(is, as_derived()); } private: static void store(std::ostream& os, const parent_t& rbm) { cpp::binary_write_all(os, rbm.w); cpp::binary_write_all(os, rbm.b); cpp::binary_write_all(os, rbm.c); } static void load(std::istream& is, parent_t& rbm) { cpp::binary_load_all(is, rbm.w); cpp::binary_load_all(is, rbm.b); cpp::binary_load_all(is, rbm.c); } static void store(const std::string& file, const parent_t& rbm) { std::ofstream os(file, std::ofstream::binary); store(os, rbm); } static void load(const std::string& file, parent_t& rbm) { std::ifstream is(file, std::ifstream::binary); load(is, rbm); } parent_t& as_derived() { return *static_cast<parent_t*>(this); } const parent_t& as_derived() const { return *static_cast<const parent_t*>(this); } }; } //end of dll namespace
//======================================================================= // Copyright (c) 2014-2017 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 <iosfwd> #include <fstream> #include "cpp_utils/io.hpp" #include "dll/generators.hpp" #include "dll/layer.hpp" #include "dll/trainer/rbm_trainer_fwd.hpp" namespace dll { /*! * \brief Simple traits to pass information around from the real * class to the CRTP class. */ template <typename Parent> struct rbm_base_traits; /*! * \brief Base class for Restricted Boltzmann Machine. * * It contains configurable properties that are used by each * version of RBM. It also contains common functions that are * injected using CRTP technique. */ template <typename Parent, typename Desc> struct rbm_base : layer<Parent> { using conf = Desc; using parent_t = Parent; using weight = typename conf::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; using generator_t = inmemory_data_generator_desc<dll::autoencoder>; //Configurable properties weight learning_rate = 1e-1; ///< The learning rate weight initial_momentum = 0.5; ///< The initial momentum weight final_momentum = 0.9; ///< The final momentum applied after *final_momentum_epoch* epoch weight final_momentum_epoch = 6; ///< The epoch at which momentum change weight momentum = 0; ///< The current momentum weight l1_weight_cost = 0.0002; ///< The weight cost for L1 weight decay weight l2_weight_cost = 0.0002; ///< The weight cost for L2 weight decay weight sparsity_target = 0.01; ///< The sparsity target weight decay_rate = 0.99; ///< The sparsity decay rate weight sparsity_cost = 1.0; ///< The sparsity cost (or sparsity multiplier) weight pbias = 0.002; weight pbias_lambda = 5; weight gradient_clip = 5.0; ///< The default gradient clipping value rbm_base() { //Nothing to do } void backup_weights() { unique_safe_get(as_derived().bak_w) = as_derived().w; unique_safe_get(as_derived().bak_b) = as_derived().b; unique_safe_get(as_derived().bak_c) = as_derived().c; } void restore_weights() { as_derived().w = *as_derived().bak_w; as_derived().b = *as_derived().bak_b; as_derived().c = *as_derived().bak_c; } template<typename Input> double reconstruction_error(const Input& item) { return parent_t::reconstruction_error_impl(item, as_derived()); } //Normal Train functions template <bool EnableWatcher = true, typename RW = void, typename Generator, typename... Args, cpp_enable_if(is_generator<Generator>::value)> double train(Generator& generator, size_t max_epochs, Args... args) { dll::rbm_trainer<parent_t, EnableWatcher, RW, false> trainer(args...); return trainer.train(as_derived(), generator, max_epochs); } template <bool EnableWatcher = true, typename RW = void, typename Input, typename... Args, cpp_enable_if(!is_generator<Input>::value)> double train(const Input& training_data, size_t max_epochs, Args... args) { // Create a new generator around the data auto generator = make_generator(training_data, training_data, training_data.size(), generator_t{}); generator->batch_size = get_batch_size(as_derived()); dll::rbm_trainer<parent_t, EnableWatcher, RW, false> trainer(args...); return trainer.train(as_derived(), *generator, max_epochs); } template <bool EnableWatcher = true, typename RW = void, typename Iterator, typename... Args> double train(Iterator&& first, Iterator&& last, size_t max_epochs, Args... args) { // Create a new generator around the data auto generator = make_generator(first, last, first, last, std::distance(first, last), generator_t{}); generator->batch_size = get_batch_size(as_derived()); dll::rbm_trainer<parent_t, EnableWatcher, RW, false> trainer(args...); return trainer.train(as_derived(), *generator, max_epochs); } //Train denoising autoencoder template <bool EnableWatcher = true, typename RW = void, typename Noisy, typename Clean, typename... Args> double train_denoising(const Noisy& noisy, const Clean& clean, size_t max_epochs, Args... args) { // Create a new generator around the data auto generator = make_generator(noisy, clean, noisy.size(), generator_t{}); generator->batch_size = get_batch_size(as_derived()); dll::rbm_trainer<parent_t, EnableWatcher, RW, true> trainer(args...); return trainer.train(as_derived(), generator, max_epochs); } template <typename NIterator, typename CIterator, bool EnableWatcher = true, typename RW = void, typename... Args> double train_denoising(NIterator noisy_it, NIterator noisy_end, CIterator clean_it, CIterator clean_end, size_t max_epochs, Args... args) { // Create a new generator around the data auto generator = make_generator(noisy_it, noisy_end, clean_it, clean_end, std::distance(clean_it, clean_end), generator_t{}); generator->batch_size = get_batch_size(as_derived()); dll::rbm_trainer<parent_t, EnableWatcher, RW, true> trainer(args...); return trainer.train(as_derived(), generator, max_epochs); } //Train denoising autoencoder (auto) template <bool EnableWatcher = true, typename RW = void, typename Clean, typename... Args> double train_denoising_auto(const Clean& clean, size_t max_epochs, double noise, Args... args) { dll::rbm_trainer<parent_t, EnableWatcher, RW, false> trainer(args...); return trainer.train_denoising_auto(as_derived(), clean.begin(), clean.end(), max_epochs, noise); } template <typename CIterator, bool EnableWatcher = true, typename RW = void, typename... Args> double train_denoising_auto(CIterator clean_it, CIterator clean_end, size_t max_epochs, double noise, Args... args) { dll::rbm_trainer<parent_t, EnableWatcher, RW, false> trainer(args...); return trainer.train_denoising_auto(as_derived(), clean_it, clean_end, max_epochs, noise); } // Features template<typename Input> output_one_t features(const Input& input){ return activate_hidden(input);; } template<typename Input> output_one_t activate_hidden(const Input& input){ auto output = as_derived().template prepare_one_output<Input>(); as_derived().activate_hidden(output, input); return output; } //I/O functions void store(const std::string& file) const { store(file, as_derived()); } void store(std::ostream& os) const { store(os, as_derived()); } void load(const std::string& file) { load(file, as_derived()); } void load(std::istream& is) { load(is, as_derived()); } private: static void store(std::ostream& os, const parent_t& rbm) { cpp::binary_write_all(os, rbm.w); cpp::binary_write_all(os, rbm.b); cpp::binary_write_all(os, rbm.c); } static void load(std::istream& is, parent_t& rbm) { cpp::binary_load_all(is, rbm.w); cpp::binary_load_all(is, rbm.b); cpp::binary_load_all(is, rbm.c); } static void store(const std::string& file, const parent_t& rbm) { std::ofstream os(file, std::ofstream::binary); store(os, rbm); } static void load(const std::string& file, parent_t& rbm) { std::ifstream is(file, std::ifstream::binary); load(is, rbm); } parent_t& as_derived() { return *static_cast<parent_t*>(this); } const parent_t& as_derived() const { return *static_cast<const parent_t*>(this); } }; } //end of dll namespace
Use generators
Use generators
C++
mit
wichtounet/dll,wichtounet/dll,wichtounet/dll
9bf86eea7226250ef610aa85c19e4d1781ec6a1c
api/kernel/memory.hpp
api/kernel/memory.hpp
// -*- C++ -*- // This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2017 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef KERNEL_MEMORY_HPP #define KERNEL_MEMORY_HPP #define DEBUG 1 #include <common> #include <util/bitops.hpp> #include <util/units.hpp> #include <cstdlib> #include <sstream> namespace os { namespace mem { using namespace util::literals; /** POSIX mprotect compliant access bits **/ enum class Access : uint8_t { none = 0, read = 1, write = 2, execute = 4 }; /** Get bitfield with bit set for each supported page size */ uintptr_t supported_page_sizes(); /** Get the smallest supported page size */ uintptr_t min_psize(); /** Get the largest supported page size */ uintptr_t max_psize(); /** Determine if size is a supported page size */ bool supported_page_size(uintptr_t size); /** A-aligned allocation of T **/ template <typename T, int A, typename... Args> T* aligned_alloc(Args... a) { void* ptr; if (posix_memalign(&ptr, A, sizeof(T)) > 0) return nullptr; return new (ptr) T(a...); } inline std::string page_sizes_str(size_t bits){ if (bits == 0) return "None"; std::stringstream out; while (bits){ auto ps = 1 << (__builtin_ffsl(bits) - 1); bits &= ~ps; out << util::Byte_r(ps); if (bits) out << ", "; } return out.str(); } template <typename Fl = Access> struct Mapping { static const size_t any_size; uintptr_t lin {}; uintptr_t phys {}; Fl flags {}; size_t size = 0; size_t page_sizes = 0; Mapping() = default; Mapping(uintptr_t linear, uintptr_t physical, Fl fl, size_t sz) : lin{linear}, phys{physical}, flags{fl}, size{sz}, page_sizes{any_size} {} Mapping(uintptr_t linear, uintptr_t physical, Fl fl, size_t sz, size_t psz) : lin{linear}, phys{physical}, flags{fl}, size{sz}, page_sizes{psz} {} operator bool() const noexcept { return size != 0 && page_sizes !=0; } bool operator==(const Mapping& rhs) const noexcept { return lin == rhs.lin && phys == rhs.phys && flags == rhs.flags && size == rhs.size && page_sizes == rhs.page_sizes; } bool operator!=(const Mapping& rhs) const noexcept { return ! *this == rhs; } inline Mapping operator+(const Mapping& rhs) noexcept; Mapping operator+=(const Mapping& rhs) noexcept { *this = *this + rhs; return *this; } size_t page_count() const noexcept { return page_sizes ? (size + page_sizes - 1) / page_sizes : 0; } // Smallest page size in map size_t min_psize() const noexcept { return util::bits::keepfirst(page_sizes); } // Largest page size in map size_t lmax_psize() const noexcept { return util::bits::keeplast(page_sizes); } std::string to_string() const { std::stringstream out; out << "0x" << std::hex << lin << "->" << phys << ", size: "<< util::Byte_r(size) << " flags: 0x" << std::hex << (int)flags << std::dec; if (util::bits::is_pow2(page_sizes)) { out << std::dec << " ( " << page_count() << " x " << util::Byte_r(page_sizes) << " pages )"; } else { out << " page sizes: " << page_sizes_str(page_sizes); } return out.str(); } }; template <typename Fl> inline std::ostream& operator<<(std::ostream& out, const Mapping<Fl>& m) { return out << m.to_string(); } using Map = Mapping<>; class Memory_exception : public std::runtime_error { using runtime_error::runtime_error; }; /** * Map linear address to physical memory, according to provided Mapping. * Provided map.page_size will be ignored, but the returned map.page_size * will have one bit set for each page size used */ Map map(Map, const char* name = "mem::map"); /** * Unmap the memory mapped by linear address, * effectively freeing the underlying physical memory. * The behavior is undefined if addr was not mapped with a call to map **/ Map unmap(uintptr_t addr); /** Get protection flags for page containing a given address */ Access flags(uintptr_t addr); /** Determine active page size of a given linear address **/ uintptr_t active_page_size(uintptr_t addr); uintptr_t active_page_size(void* addr); /** * Set and return access flags for a given linear address range * The range is expected to be mapped by a previous call to map. **/ Access protect(uintptr_t linear, Access flags = Access::read); /** Set and return access flags for a page starting at linear **/ Access protect_page(uintptr_t linear, Access flags = Access::read); } } namespace util { inline namespace bitops { template<> struct enable_bitmask_ops<os::mem::Access> { using type = typename std::underlying_type<os::mem::Access>::type; static constexpr bool enable = true; }; } } namespace os { namespace mem { template <typename Fl> Mapping<Fl> Mapping<Fl>::operator+(const Mapping& rhs) noexcept { using namespace util::bitops; Mapping res; if (! rhs) { return *this; } if (! *this) return rhs; if (res == rhs) return res; res.lin = std::min(lin, rhs.lin); res.phys = std::min(phys, rhs.phys); // The mappings must have connecting ranges if ((rhs and rhs.lin + rhs.size != lin) and (*this and lin + size != rhs.lin)) { Ensures(!res); return res; } res.page_sizes |= rhs.page_sizes; // The mappings can span several page sizes if (page_sizes && page_sizes != rhs.page_sizes) { res.page_sizes |= page_sizes; } res.size = size + rhs.size; res.flags = flags & rhs.flags; if (rhs) Ensures(res); return res; } }} #endif
// -*- C++ -*- // This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2017 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef KERNEL_MEMORY_HPP #define KERNEL_MEMORY_HPP #include <common> #include <util/bitops.hpp> #include <util/units.hpp> #include <cstdlib> #include <sstream> namespace os { namespace mem { using namespace util::literals; /** POSIX mprotect compliant access bits **/ enum class Access : uint8_t { none = 0, read = 1, write = 2, execute = 4 }; /** Get bitfield with bit set for each supported page size */ uintptr_t supported_page_sizes(); /** Get the smallest supported page size */ uintptr_t min_psize(); /** Get the largest supported page size */ uintptr_t max_psize(); /** Determine if size is a supported page size */ bool supported_page_size(uintptr_t size); /** A-aligned allocation of T **/ template <typename T, int A, typename... Args> T* aligned_alloc(Args... a) { void* ptr; if (posix_memalign(&ptr, A, sizeof(T)) > 0) return nullptr; return new (ptr) T(a...); } inline std::string page_sizes_str(size_t bits){ if (bits == 0) return "None"; std::stringstream out; while (bits){ auto ps = 1 << (__builtin_ffsl(bits) - 1); bits &= ~ps; out << util::Byte_r(ps); if (bits) out << ", "; } return out.str(); } template <typename Fl = Access> struct Mapping { static const size_t any_size; uintptr_t lin {}; uintptr_t phys {}; Fl flags {}; size_t size = 0; size_t page_sizes = 0; Mapping() = default; Mapping(uintptr_t linear, uintptr_t physical, Fl fl, size_t sz) : lin{linear}, phys{physical}, flags{fl}, size{sz}, page_sizes{any_size} {} Mapping(uintptr_t linear, uintptr_t physical, Fl fl, size_t sz, size_t psz) : lin{linear}, phys{physical}, flags{fl}, size{sz}, page_sizes{psz} {} operator bool() const noexcept { return size != 0 && page_sizes !=0; } bool operator==(const Mapping& rhs) const noexcept { return lin == rhs.lin && phys == rhs.phys && flags == rhs.flags && size == rhs.size && page_sizes == rhs.page_sizes; } bool operator!=(const Mapping& rhs) const noexcept { return ! *this == rhs; } inline Mapping operator+(const Mapping& rhs) noexcept; Mapping operator+=(const Mapping& rhs) noexcept { *this = *this + rhs; return *this; } size_t page_count() const noexcept { return page_sizes ? (size + page_sizes - 1) / page_sizes : 0; } // Smallest page size in map size_t min_psize() const noexcept { return util::bits::keepfirst(page_sizes); } // Largest page size in map size_t lmax_psize() const noexcept { return util::bits::keeplast(page_sizes); } std::string to_string() const { std::stringstream out; out << "0x" << std::hex << lin << "->" << phys << ", size: "<< util::Byte_r(size) << " flags: 0x" << std::hex << (int)flags << std::dec; if (util::bits::is_pow2(page_sizes)) { out << std::dec << " ( " << page_count() << " x " << util::Byte_r(page_sizes) << " pages )"; } else { out << " page sizes: " << page_sizes_str(page_sizes); } return out.str(); } }; template <typename Fl> inline std::ostream& operator<<(std::ostream& out, const Mapping<Fl>& m) { return out << m.to_string(); } using Map = Mapping<>; class Memory_exception : public std::runtime_error { using runtime_error::runtime_error; }; /** * Map linear address to physical memory, according to provided Mapping. * Provided map.page_size will be ignored, but the returned map.page_size * will have one bit set for each page size used */ Map map(Map, const char* name = "mem::map"); /** * Unmap the memory mapped by linear address, * effectively freeing the underlying physical memory. * The behavior is undefined if addr was not mapped with a call to map **/ Map unmap(uintptr_t addr); /** Get protection flags for page containing a given address */ Access flags(uintptr_t addr); /** Determine active page size of a given linear address **/ uintptr_t active_page_size(uintptr_t addr); uintptr_t active_page_size(void* addr); /** * Set and return access flags for a given linear address range * The range is expected to be mapped by a previous call to map. **/ Access protect(uintptr_t linear, Access flags = Access::read); /** Set and return access flags for a page starting at linear **/ Access protect_page(uintptr_t linear, Access flags = Access::read); } } namespace util { inline namespace bitops { template<> struct enable_bitmask_ops<os::mem::Access> { using type = typename std::underlying_type<os::mem::Access>::type; static constexpr bool enable = true; }; } } namespace os { namespace mem { template <typename Fl> Mapping<Fl> Mapping<Fl>::operator+(const Mapping& rhs) noexcept { using namespace util::bitops; Mapping res; if (! rhs) { return *this; } if (! *this) return rhs; if (res == rhs) return res; res.lin = std::min(lin, rhs.lin); res.phys = std::min(phys, rhs.phys); // The mappings must have connecting ranges if ((rhs and rhs.lin + rhs.size != lin) and (*this and lin + size != rhs.lin)) { Ensures(!res); return res; } res.page_sizes |= rhs.page_sizes; // The mappings can span several page sizes if (page_sizes && page_sizes != rhs.page_sizes) { res.page_sizes |= page_sizes; } res.size = size + rhs.size; res.flags = flags & rhs.flags; if (rhs) Ensures(res); return res; } }} #endif
Remove DEBUG from memory header
kernel: Remove DEBUG from memory header
C++
apache-2.0
hioa-cs/IncludeOS,hioa-cs/IncludeOS,ingve/IncludeOS,alfred-bratterud/IncludeOS,AndreasAakesson/IncludeOS,ingve/IncludeOS,AndreasAakesson/IncludeOS,AnnikaH/IncludeOS,AnnikaH/IncludeOS,AndreasAakesson/IncludeOS,AnnikaH/IncludeOS,mnordsletten/IncludeOS,alfred-bratterud/IncludeOS,mnordsletten/IncludeOS,mnordsletten/IncludeOS,hioa-cs/IncludeOS,mnordsletten/IncludeOS,alfred-bratterud/IncludeOS,hioa-cs/IncludeOS,alfred-bratterud/IncludeOS,AndreasAakesson/IncludeOS,mnordsletten/IncludeOS,ingve/IncludeOS,mnordsletten/IncludeOS,ingve/IncludeOS,AnnikaH/IncludeOS,alfred-bratterud/IncludeOS,AndreasAakesson/IncludeOS,ingve/IncludeOS,hioa-cs/IncludeOS,AnnikaH/IncludeOS,AndreasAakesson/IncludeOS
78ecf941361aba73ba77036d11dab8f1b7abb86b
crawler/main/MFRC522.cpp
crawler/main/MFRC522.cpp
#include <stdio.h> #include <string.h> #include <stdlib.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "esp_system.h" #include "nvs_flash.h" #include "driver/uart.h" #include "freertos/queue.h" #include "esp_log.h" #include "soc/uart_struct.h" static const char *TAG = "MFRC522"; #define BUF_SIZE (1024) #define NFC_UART_TXD (16) #define NFC_UART_RXD (17) #define NFC_UART_RTS (18) #define NFC_UART_CTS (19) QueueHandle_t uart2_queue; #include "MFRC522.h" //------------------MFRC522 register --------------- #define COMMAND_WAIT 0x02 #define COMMAND_READBLOCK 0x03 #define COMMAND_WRITEBLOCK 0x04 #define MFRC522_HEADER 0xAB #define STATUS_ERROR 0 #define STATUS_OK 1 #define MIFARE_KEYA 0x00 #define MIFARE_KEYB 0x01 /** * Constructor. */ MFRC522::MFRC522() { } /** * Description: Obtiene control del Serial para controlar MFRC522. * Ademas, pone MFRC522 en modo de espera. */ void MFRC522::begin(void) { uart_port_t uart_num = UART_NUM_2; uart_config_t uart_config = { .baud_rate = 9600, .data_bits = UART_DATA_8_BITS, .parity = UART_PARITY_DISABLE, .stop_bits = UART_STOP_BITS_1, .flow_ctrl = UART_HW_FLOWCTRL_DISABLE, .rx_flow_ctrl_thresh = 122, }; //Set UART parameters uart_param_config(uart_num, &uart_config); //Set UART log level esp_log_level_set(TAG, ESP_LOG_INFO); //Set UART pins,(-1: default pin, no change.) //For UART2, we can just use the default pins. uart_set_pin(uart_num, NFC_UART_TXD, NFC_UART_RXD, NFC_UART_RTS, NFC_UART_CTS); //Install UART driver, and get the queue. esp_err_t installed = uart_driver_install(uart_num, BUF_SIZE * 2, BUF_SIZE * 2, 10, &uart2_queue, 0); printf("installed : %d\n", installed); wait(); } /** * Description:Pone MFRC522 en modo espera. */ void MFRC522::wait() { write(COMMAND_WAIT); } /** * Description:Returns true if detect card in MFRC522. */ bool MFRC522::available() { return true; } /** * Description:Read the serial number of the card. */ void MFRC522::readCardSerial() { for (int i = 0; i < sizeof(cardSerial); ){ if (available()){ cardSerial[i] = read(); i++; } } } /** * Description:Returns a pointer to array with card serial. */ byte *MFRC522::getCardSerial() { return cardSerial; } /** * Description:Read a block data of the card. * Return:Return STATUS_OK if success. */ bool MFRC522::getBlock(byte block, byte keyType, byte *key, byte *returnBlock) { byte sendData[8] = { block, // block keyType, // key type 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF // key }; byte returnBlockLength; for (int i = 0; i < 6; ++i) { sendData[2 + i] = key[i]; } return communicate( COMMAND_READBLOCK, // command sendData, // sendData 0x0A, // length returnBlock, // returnData &returnBlockLength // returnDataLength ); } /** * Description:Write a block data in the card. * Return:Return STATUS_OK if success. */ bool MFRC522::writeBlock(byte block, byte keyType, byte *key, byte *data) { byte sendData[24] = { block, // block keyType, // key type 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // key 0x00, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // Data }; byte returnBlock[3]; byte returnBlockLength; for (int i = 0; i < 6; ++i) { sendData[2 + i] = key[i]; } for (int i = 0; i < 16; ++i) { sendData[8 + i] = data[i]; } byte result = communicate( COMMAND_WRITEBLOCK, // command sendData, // sendData 0x1A, // length returnBlock, // returnData &returnBlockLength // returnDataLength ); return result; } /** * Description:Comunication between MFRC522 and ISO14443. * Return:Return STATUS_OK if success. */ bool MFRC522::communicate(byte command, byte *sendData, byte sendDataLength, byte *returnData, byte *returnDataLength) { // Send instruction to MFRC522 write(MFRC522_HEADER); // Header write(sendDataLength); // Length (Length + Command + Data) write(command); // Command for (int i = 0; i < sendDataLength - 2; i++) { write(sendData[i]); // Data } // Read response to MFRC522 while (!available()); byte header = read(); // Header while (!available()); *returnDataLength = read(); // Length (Length + Command + Data) while (!available()); byte commandResult = read(); // Command result for (int i = 0; i < *returnDataLength - 2; i=i) { if (available()) { returnData[i] = read(); // Data i++; } } // Return if (command != commandResult) { return STATUS_ERROR; } return STATUS_OK; } /* * Description:Write a byte data into MFRC522. */ void MFRC522::write(byte value) { uart_port_t uart_num = UART_NUM_2; char data[1]; data[0] = value; uart_write_bytes(uart_num, (const char*)data, 1); } /* * Description:Read a byte data of MFRC522 * Return:Return the read value. */ byte MFRC522::read() { uart_port_t uart_num = UART_NUM_2; uint8_t *data = (uint8_t *)malloc(1); TickType_t ticks_to_wait = portTICK_RATE_MS; uart_read_bytes(uart_num,data,1,ticks_to_wait); return *data; } const portTickType xDelay = 500 / portTICK_RATE_MS; extern "C" void MFRC522_main() { MFRC522 Conector; Conector.begin(); printf("begin :\n"); while(true) { Conector.readCardSerial(); printf("readCardSerial :\n"); Conector.wait(); vTaskDelay( xDelay ); } }
#include <stdio.h> #include <string.h> #include <stdlib.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "esp_system.h" #include "nvs_flash.h" #include "driver/uart.h" #include "freertos/queue.h" #include "esp_log.h" #include "soc/uart_struct.h" static const char *TAG = "MFRC522"; #define BUF_SIZE (1024) #define NFC_UART_TXD (16) #define NFC_UART_RXD (17) #define NFC_UART_RTS (18) #define NFC_UART_CTS (19) QueueHandle_t uart2_queue; #include "MFRC522.h" //------------------MFRC522 register --------------- #define COMMAND_WAIT 0x02 #define COMMAND_READBLOCK 0x03 #define COMMAND_WRITEBLOCK 0x04 #define MFRC522_HEADER 0xAB #define STATUS_ERROR 0 #define STATUS_OK 1 #define MIFARE_KEYA 0x00 #define MIFARE_KEYB 0x01 /** * Constructor. */ MFRC522::MFRC522() { } /** * Description: Obtiene control del Serial para controlar MFRC522. * Ademas, pone MFRC522 en modo de espera. */ void MFRC522::begin(void) { uart_port_t uart_num = UART_NUM_2; uart_config_t uart_config = { .baud_rate = 9600, .data_bits = UART_DATA_8_BITS, .parity = UART_PARITY_DISABLE, .stop_bits = UART_STOP_BITS_1, .flow_ctrl = UART_HW_FLOWCTRL_DISABLE, .rx_flow_ctrl_thresh = 122, }; //Set UART parameters uart_param_config(uart_num, &uart_config); //Set UART log level esp_log_level_set(TAG, ESP_LOG_INFO); //Set UART pins,(-1: default pin, no change.) //For UART2, we can just use the default pins. uart_set_pin(uart_num, NFC_UART_TXD, NFC_UART_RXD, NFC_UART_RTS, NFC_UART_CTS); //Install UART driver, and get the queue. esp_err_t installed = uart_driver_install(uart_num, BUF_SIZE * 2, BUF_SIZE * 2, 10, &uart2_queue, 0); printf("installed : %d\n", installed); wait(); } /** * Description:Pone MFRC522 en modo espera. */ void MFRC522::wait() { write(COMMAND_WAIT); } /** * Description:Returns true if detect card in MFRC522. */ bool MFRC522::available() { return true; } /** * Description:Read the serial number of the card. */ void MFRC522::readCardSerial() { for (int i = 0; i < sizeof(cardSerial); ){ if (available()){ cardSerial[i] = read(); i++; } } } /** * Description:Returns a pointer to array with card serial. */ byte *MFRC522::getCardSerial() { return cardSerial; } /** * Description:Read a block data of the card. * Return:Return STATUS_OK if success. */ bool MFRC522::getBlock(byte block, byte keyType, byte *key, byte *returnBlock) { byte sendData[8] = { block, // block keyType, // key type 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF // key }; byte returnBlockLength; for (int i = 0; i < 6; ++i) { sendData[2 + i] = key[i]; } return communicate( COMMAND_READBLOCK, // command sendData, // sendData 0x0A, // length returnBlock, // returnData &returnBlockLength // returnDataLength ); } /** * Description:Write a block data in the card. * Return:Return STATUS_OK if success. */ bool MFRC522::writeBlock(byte block, byte keyType, byte *key, byte *data) { byte sendData[24] = { block, // block keyType, // key type 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // key 0x00, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // Data }; byte returnBlock[3]; byte returnBlockLength; for (int i = 0; i < 6; ++i) { sendData[2 + i] = key[i]; } for (int i = 0; i < 16; ++i) { sendData[8 + i] = data[i]; } byte result = communicate( COMMAND_WRITEBLOCK, // command sendData, // sendData 0x1A, // length returnBlock, // returnData &returnBlockLength // returnDataLength ); return result; } /** * Description:Comunication between MFRC522 and ISO14443. * Return:Return STATUS_OK if success. */ bool MFRC522::communicate(byte command, byte *sendData, byte sendDataLength, byte *returnData, byte *returnDataLength) { // Send instruction to MFRC522 write(MFRC522_HEADER); // Header write(sendDataLength); // Length (Length + Command + Data) write(command); // Command for (int i = 0; i < sendDataLength - 2; i++) { write(sendData[i]); // Data } // Read response to MFRC522 while (!available()); byte header = read(); // Header while (!available()); *returnDataLength = read(); // Length (Length + Command + Data) while (!available()); byte commandResult = read(); // Command result for (int i = 0; i < *returnDataLength - 2; i=i) { if (available()) { returnData[i] = read(); // Data i++; } } // Return if (command != commandResult) { return STATUS_ERROR; } return STATUS_OK; } /* * Description:Write a byte data into MFRC522. */ void MFRC522::write(byte value) { uart_port_t uart_num = UART_NUM_2; char data[1]; data[0] = value; uart_write_bytes(uart_num, (const char*)data, 1); } /* * Description:Read a byte data of MFRC522 * Return:Return the read value. */ byte MFRC522::read() { uart_port_t uart_num = UART_NUM_2; uint8_t *data = (uint8_t *)malloc(1); TickType_t ticks_to_wait = portTICK_RATE_MS; uart_read_bytes(uart_num,data,1,ticks_to_wait); return *data; } const portTickType xDelay = 500 / portTICK_RATE_MS; extern "C" void MFRC522_main() { MFRC522 Conector; Conector.begin(); printf("begin :\n"); while(true) { byte cardSerial = Conector.readCardSerial(); printf("readCardSerial cardSerial=<%s>\n",cardSerial); Conector.wait(); vTaskDelay( xDelay ); } }
Update MFRC522.cpp
Update MFRC522.cpp
C++
mit
RobotTeam2/esp32.crawler,RobotTeam2/esp32.crawler,RobotTeam2/esp32.crawler,RobotTeam2/esp32.crawler
530416f0aa0281f1915227e5ca740819372bae90
benchmark/test_rendering.cpp
benchmark/test_rendering.cpp
#include "bench_framework.hpp" #include <mapnik/map.hpp> #include <mapnik/image_util.hpp> #include <mapnik/load_map.hpp> #include <mapnik/agg_renderer.hpp> #include <mapnik/datasource_cache.hpp> #include <mapnik/font_engine_freetype.hpp> #include <stdexcept> class test : public benchmark::test_case { std::string xml_; mapnik::box2d<double> extent_; mapnik::value_integer width_; mapnik::value_integer height_; double scale_factor_; std::string preview_; public: test(mapnik::parameters const& params) : test_case(params), xml_(), extent_(), width_(*params.get<mapnik::value_integer>("width",256)), height_(*params.get<mapnik::value_integer>("height",256)), scale_factor_(*params.get<mapnik::value_double>("scale_factor",1.0)), preview_(*params.get<std::string>("preview","")) { boost::optional<std::string> map = params.get<std::string>("map"); if (!map) { throw std::runtime_error("please provide a --map=<path to xml> arg"); } xml_ = *map; boost::optional<std::string> ext = params.get<std::string>("extent"); if (ext && !ext->empty()) { if (!extent_.from_string(*ext)) throw std::runtime_error("could not parse `extent` string" + *ext); } /* else { throw std::runtime_error("please provide a --extent=<minx,miny,maxx,maxy> arg"); }*/ } bool validate() const { mapnik::Map m(width_,height_); mapnik::load_map(m,xml_,true); if (extent_.valid()) { m.zoom_to_box(extent_); } else { m.zoom_all(); } mapnik::image_rgba8 im(m.width(),m.height()); mapnik::agg_renderer<mapnik::image_rgba8> ren(m,im,scale_factor_); ren.apply(); if (!preview_.empty()) { std::clog << "preview available at " << preview_ << "\n"; mapnik::save_to_file(im,preview_); } return true; } bool operator()() const { if (!preview_.empty()) { return false; } mapnik::Map m(width_,height_); mapnik::load_map(m,xml_); if (extent_.valid()) { m.zoom_to_box(extent_); } else { m.zoom_all(); } for (unsigned i=0;i<iterations_;++i) { mapnik::image_rgba8 im(m.width(),m.height()); mapnik::agg_renderer<mapnik::image_rgba8> ren(m,im,scale_factor_); ren.apply(); } return true; } }; int main(int argc, char** argv) { int return_value = 0; try { mapnik::parameters params; benchmark::handle_args(argc,argv,params); boost::optional<std::string> name = params.get<std::string>("name"); if (!name) { std::clog << "please provide a name for this test\n"; return -1; } mapnik::freetype_engine::register_fonts("./fonts/",true); mapnik::datasource_cache::instance().register_datasources("./plugins/input/"); { test test_runner(params); return_value = run(test_runner,*name); } } catch (std::exception const& ex) { std::clog << ex.what() << "\n"; return -1; } return return_value; }
#include "bench_framework.hpp" #include <mapnik/map.hpp> #include <mapnik/image_util.hpp> #include <mapnik/load_map.hpp> #include <mapnik/agg_renderer.hpp> #include <mapnik/datasource_cache.hpp> #include <mapnik/font_engine_freetype.hpp> #include <stdexcept> class test : public benchmark::test_case { std::string xml_; mapnik::box2d<double> extent_; mapnik::value_integer width_; mapnik::value_integer height_; double scale_factor_; std::string preview_; public: test(mapnik::parameters const& params) : test_case(params), xml_(), extent_(), width_(*params.get<mapnik::value_integer>("width",256)), height_(*params.get<mapnik::value_integer>("height",256)), scale_factor_(*params.get<mapnik::value_double>("scale_factor",1.0)), preview_(*params.get<std::string>("preview","")) { boost::optional<std::string> map = params.get<std::string>("map"); if (!map) { throw std::runtime_error("please provide a --map <path to xml> arg"); } xml_ = *map; boost::optional<std::string> ext = params.get<std::string>("extent"); if (ext && !ext->empty()) { if (!extent_.from_string(*ext)) throw std::runtime_error("could not parse `extent` string" + *ext); } /* else { throw std::runtime_error("please provide a --extent=<minx,miny,maxx,maxy> arg"); }*/ } bool validate() const { mapnik::Map m(width_,height_); mapnik::load_map(m,xml_,true); if (extent_.valid()) { m.zoom_to_box(extent_); } else { m.zoom_all(); } mapnik::image_rgba8 im(m.width(),m.height()); mapnik::agg_renderer<mapnik::image_rgba8> ren(m,im,scale_factor_); ren.apply(); if (!preview_.empty()) { std::clog << "preview available at " << preview_ << "\n"; mapnik::save_to_file(im,preview_); } return true; } bool operator()() const { if (!preview_.empty()) { return false; } mapnik::Map m(width_,height_); mapnik::load_map(m,xml_); if (extent_.valid()) { m.zoom_to_box(extent_); } else { m.zoom_all(); } for (unsigned i=0;i<iterations_;++i) { mapnik::image_rgba8 im(m.width(),m.height()); mapnik::agg_renderer<mapnik::image_rgba8> ren(m,im,scale_factor_); ren.apply(); } return true; } }; int main(int argc, char** argv) { int return_value = 0; try { mapnik::parameters params; benchmark::handle_args(argc,argv,params); boost::optional<std::string> name = params.get<std::string>("name"); if (!name) { std::clog << "please provide a name for this test\n"; return -1; } mapnik::freetype_engine::register_fonts("./fonts/",true); mapnik::datasource_cache::instance().register_datasources("./plugins/input/"); { test test_runner(params); return_value = run(test_runner,*name); } } catch (std::exception const& ex) { std::clog << ex.what() << "\n"; return -1; } return return_value; }
fix suggesed cmd line option syntax [skip ci]
fix suggesed cmd line option syntax [skip ci]
C++
lgpl-2.1
naturalatlas/mapnik,Uli1/mapnik,Uli1/mapnik,Uli1/mapnik,mapnik/mapnik,naturalatlas/mapnik,mapycz/mapnik,CartoDB/mapnik,CartoDB/mapnik,Uli1/mapnik,mapycz/mapnik,zerebubuth/mapnik,tomhughes/mapnik,tomhughes/mapnik,pnorman/mapnik,mapnik/mapnik,pnorman/mapnik,zerebubuth/mapnik,naturalatlas/mapnik,mapnik/mapnik,mapycz/mapnik,lightmare/mapnik,zerebubuth/mapnik,mapnik/mapnik,lightmare/mapnik,tomhughes/mapnik,lightmare/mapnik,pnorman/mapnik,pnorman/mapnik,tomhughes/mapnik,CartoDB/mapnik,naturalatlas/mapnik,lightmare/mapnik
cdcb76c4e6d0cc80ba48d8d89151ab79a8a77f1d
db/SelectQuery.cpp
db/SelectQuery.cpp
/* * Illarionserver - server for the game Illarion * Copyright 2011 Illarion e.V. * * This file is part of Illarionserver. * * Illarionserver is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * Illarionserver is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * Illarionserver. If not, see <http://www.gnu.org/licenses/>. */ #include "db/SelectQuery.hpp" #include <sstream> #include "db/ConnectionManager.hpp" using namespace Database; SelectQuery::SelectQuery() { SelectQuery(ConnectionManager::getInstance().getConnection()); isDistinct = false; } SelectQuery::SelectQuery(const SelectQuery &org) : QueryColumns(org), QueryTables(org), QueryWhere(org) { orderBy = org.orderBy; isDistinct = org.isDistinct; } SelectQuery::SelectQuery(const PConnection connection) : QueryColumns(connection), QueryTables(connection), QueryWhere(connection) { setOnlyOneTable(false); isDistinct = false; }; void SelectQuery::addOrderBy(const std::string &column, const OrderDirection &dir) { addOrderBy("", column, dir); } void SelectQuery::addOrderBy(const std::string &table, const std::string &column, const OrderDirection &dir) { if (!orderBy.empty()) { orderBy += ", "; } orderBy += escapeAndChainKeys(table, column); orderBy += " "; switch (dir) { case ASC: orderBy += "ASC"; case DESC: orderBy += "DESC"; } } void SelectQuery::setDistinct(const bool &distinct) { isDistinct = distinct; } Result SelectQuery::execute() { std::stringstream ss; ss << "SELECT "; if (isDistinct) { ss << "DISTINCT "; } ss << QueryColumns::buildQuerySegment(); ss << " FROM "; ss << QueryTables::buildQuerySegment(); ss << QueryWhere::buildQuerySegment(); if (!orderBy.empty()) { ss << " ORDER BY " << orderBy; } ss << ";"; setQuery(ss.str()); Query::execute(); }
/* * Illarionserver - server for the game Illarion * Copyright 2011 Illarion e.V. * * This file is part of Illarionserver. * * Illarionserver is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * Illarionserver is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * Illarionserver. If not, see <http://www.gnu.org/licenses/>. */ #include "db/SelectQuery.hpp" #include <sstream> #include "db/ConnectionManager.hpp" using namespace Database; SelectQuery::SelectQuery() { SelectQuery(ConnectionManager::getInstance().getConnection()); isDistinct = false; } SelectQuery::SelectQuery(const SelectQuery &org) : QueryColumns(org), QueryTables(org), QueryWhere(org) { orderBy = org.orderBy; isDistinct = org.isDistinct; } SelectQuery::SelectQuery(const PConnection connection) : QueryColumns(connection), QueryTables(connection), QueryWhere(connection) { setOnlyOneTable(false); isDistinct = false; }; void SelectQuery::addOrderBy(const std::string &column, const OrderDirection &dir) { addOrderBy("", column, dir); } void SelectQuery::addOrderBy(const std::string &table, const std::string &column, const OrderDirection &dir) { if (!orderBy.empty()) { orderBy += ", "; } orderBy += escapeAndChainKeys(table, column); orderBy += " "; switch (dir) { case ASC: orderBy += "ASC"; case DESC: orderBy += "DESC"; } } void SelectQuery::setDistinct(const bool &distinct) { isDistinct = distinct; } Result SelectQuery::execute() { std::stringstream ss; ss << "SELECT "; if (isDistinct) { ss << "DISTINCT "; } ss << QueryColumns::buildQuerySegment(); ss << " FROM "; ss << QueryTables::buildQuerySegment(); ss << QueryWhere::buildQuerySegment(); if (!orderBy.empty()) { ss << " ORDER BY " << orderBy; } ss << ";"; setQuery(ss.str()); return Query::execute(); }
add missing return value
add missing return value
C++
agpl-3.0
Illarion-eV/Illarion-Server,Illarion-eV/Illarion-Server,Illarion-eV/Illarion-Server
af3fbeac69d2d957474f101cded819bec8f24e32
benchs/polyhedron/viewer.cpp
benchs/polyhedron/viewer.cpp
#include <SceneGraph/GraphRenderer.h> #include <SceneGraph/Camera.h> #include <SceneGraph/GeoNode.h> #include <Utils/ImageIO.h> using namespace imp; #include <SFML/Graphics.hpp> #include "shader.h" Geometry generateRockHat(const Vec3& center, float radius, int sub) { imp::Geometry geometry = imp::Geometry::cube(); geometry *= 0.5; geometry = geometry.subdivise(sub); geometry.sphericalNormalization(0.5); geometry.scale(Vec3(radius * 0.7,radius * 0.7,radius * 1.5)); imp::Geometry geo2 = imp::Geometry::cube(); geo2 *= 0.5; // side size = one geo2 *= Vec3(1.0,1.0,0.5); /* h = 0.25*/ geo2 += Vec3(0.0,0.0,0.25); // demi-cube geo2 = geo2.subdivise(sub*4); geo2.sphericalNormalization(0.7); geo2.scale(Vec3(radius*2.0,radius*2.0,radius*2.0)); geo2 += Vec3(0.0,0.0,radius * 1.5); geometry += geo2; Geometry::intoCCW( geometry ); return geometry; } int main(int argc, char* argv[]) { sf::Clock clock; sf::RenderWindow window(sf::VideoMode(512, 512), "My window", sf::Style::Default, sf::ContextSettings(24)); window.setFramerateLimit(60); sf::Texture texture; texture.create(512, 512); sf::Sprite sprite(texture); sprite.setTextureRect( sf::IntRect(0,512,512,-512) ); GraphRenderer::Ptr graph = GraphRenderer::create(); SceneNode::Ptr root = GeoNode::create(Geometry(),false); imp::Target::Ptr tgt = imp::Target::create(); tgt->create(512,512,1,true); // graph->getInitState()->setTarget(tgt); // graph->setClearColor( imp::Vec4(1.0,0.0,0.0,1.0) ); // graph->setClearDepth( 1.0 ); Camera::Ptr camera = Camera::create(); camera->setPosition(Vec3(0.0f, 0.0f, 0.0f)); camera->setTarget(Vec3(0.0f, 0.0f, 0.0f)); root->addNode(camera); Geometry lineVol = Geometry::cylinder(10,1.0,0.02); Geometry arrowVol = Geometry::cone(10,0.1,0.05,0.0); arrowVol += Vec3::Z; Geometry zAxe = arrowVol + lineVol; Geometry xAxe = zAxe; xAxe.rotY(1.57); Geometry yAxe = zAxe; yAxe.rotX(-1.57); Geometry coords = xAxe + yAxe + zAxe; coords.setPrimitive(Geometry::Primitive_Triangles); coords *= 0.2; Geometry point = Geometry::sphere(4, 0.1); point.setPrimitive(Geometry::Primitive_Triangles); GeoNode::Ptr node1 = GeoNode::create(coords, true); node1->setColor(Vec3(1.0,1.0,0.0)); node1->setPosition(Vec3(0.3,0.0,-0.2)); GeoNode::Ptr node2 = GeoNode::create(coords, false); node2->setColor(Vec3(1.0,0.0,0.0)); node2->setPosition(Vec3(0.0,0.0,0.0)); root->addNode(node2); GeoNode::Ptr node3 = GeoNode::create(coords, false); node3->setColor(Vec3(0.0,1.0,0.0)); node3->setPosition(Vec3(0.0,0.0,0.3)); node3->setRotation(Vec3(3.14 * 0.1, 0.0, 3.14 * 0.25)); node2->addNode(node3); GeoNode::Ptr node4 = GeoNode::create(coords, false); node4->setColor(Vec3(0.0,0.0,1.0)); node4->setPosition(Vec3(0.0,0.0,0.3)); node4->setRotation(Vec3(3.14 * 0.1, 0.0, 3.14 * 0.25)); node3->addNode(node4); // camera->addNode(node1); imp::ShaderDsc::Ptr s = imp::ShaderDsc::create(); s->vertCode = vertexSimple; s->fragCode = fragSimple; Geometry mush = generateRockHat(Vec3(0.0,0.0,0.0), 0.3, 1.0); GeoNode::Ptr geomush = GeoNode::create(mush, false); geomush->setColor(Vec3(1.0,1.0,1.0)); geomush->setPosition(Vec3(0.0,1.0,0.0)); geomush->setRotation(Vec3(3.14 * 0.1, 0.0, 3.14 * 0.25)); geomush->setShader(s); node2->addNode(geomush); bool stopLoop = false; while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed || event.type == sf::Event::KeyPressed) stopLoop=true;// window.close(); } if(stopLoop)break; if(clock.getElapsedTime().asSeconds() > 2.0*3.14) clock.restart(); double t = clock.getElapsedTime().asMilliseconds() / 1000.0; camera->setPosition(Vec3(cos(-t)*2.0,sin(-t)*2.0,(sin(t))*0.5)); camera->setTarget(Vec3(0.0,0.0,(sin(t))*0.5 )); node1->setPosition(Vec3(cos(t)*0.3,sin(t)*0.3,0.0)); // rendering graph->renderScene( root ); // imp::GraphRenderer::s_interface->unbind(tgt.get()); // imp::Image::Ptr res = tgt->get(0); // texture.update(res->data(),res->width(),res->height(),0,0); // window.clear(); // window.draw(sprite); window.display(); // std::cout << "ite" << std::endl; } exit(EXIT_SUCCESS); }
#include <SceneGraph/GraphRenderer.h> #include <SceneGraph/Camera.h> #include <SceneGraph/GeoNode.h> #include <Utils/ImageIO.h> #include <SFML/Graphics.hpp> using namespace imp; #include "shader.h" Geometry generateRockHat(const Vec3& center, float radius, int sub) { imp::Geometry geometry = imp::Geometry::cube(); geometry *= 0.5; geometry = geometry.subdivise(sub); geometry.sphericalNormalization(0.5); geometry.scale(Vec3(radius * 0.7,radius * 0.7,radius * 1.5)); imp::Geometry geo2 = imp::Geometry::cube(); geo2 *= 0.5; // side size = one geo2 *= Vec3(1.0,1.0,0.5); /* h = 0.25*/ geo2 += Vec3(0.0,0.0,0.25); // demi-cube geo2 = geo2.subdivise(sub*4); geo2.sphericalNormalization(0.7); geo2.scale(Vec3(radius*2.0,radius*2.0,radius*2.0)); geo2 += Vec3(0.0,0.0,radius * 1.5); geometry += geo2; Geometry::intoCCW( geometry ); return geometry; } int main(int argc, char* argv[]) { sf::Clock clock; sf::RenderWindow window(sf::VideoMode(512, 512), "My window", sf::Style::Default, sf::ContextSettings(24)); window.setFramerateLimit(60); GraphRenderer::Ptr graph = GraphRenderer::create(); Camera::Ptr camera = Camera::create(); camera->setPosition(Vec3(0.0f, 0.0f, 0.0f)); camera->setTarget(Vec3(0.0f, 0.0f, 0.0f)); SceneNode::Ptr root = camera; Geometry lineVol = Geometry::cylinder(10,1.0,0.02); Geometry arrowVol = Geometry::cone(10,0.1,0.05,0.0); arrowVol += Vec3::Z; Geometry zAxe = arrowVol + lineVol; Geometry xAxe = zAxe; xAxe.rotY(1.57); Geometry yAxe = zAxe; yAxe.rotX(-1.57); Geometry coords = xAxe + yAxe + zAxe; coords.setPrimitive(Geometry::Primitive_Triangles); coords *= 0.2; Geometry point = Geometry::sphere(4, 0.1); point.setPrimitive(Geometry::Primitive_Triangles); GeoNode::Ptr node1 = GeoNode::create(coords, true); node1->setColor(Vec3(1.0,1.0,0.0)); node1->setPosition(Vec3(0.3,0.0,-0.2)); GeoNode::Ptr node2 = GeoNode::create(coords, false); node2->setColor(Vec3(1.0,0.0,0.0)); node2->setPosition(Vec3(0.0,0.0,0.0)); root->addNode(node2); GeoNode::Ptr node3 = GeoNode::create(coords, false); node3->setColor(Vec3(0.0,1.0,0.0)); node3->setPosition(Vec3(0.0,0.0,0.3)); node3->setRotation(Vec3(3.14 * 0.1, 0.0, 3.14 * 0.25)); node2->addNode(node3); GeoNode::Ptr node4 = GeoNode::create(coords, false); node4->setColor(Vec3(0.0,0.0,1.0)); node4->setPosition(Vec3(0.0,0.0,0.3)); node4->setRotation(Vec3(3.14 * 0.1, 0.0, 3.14 * 0.25)); node3->addNode(node4); camera->addNode(node1); imp::ShaderDsc::Ptr s = imp::ShaderDsc::create(); s->vertCode = vertexSimple; s->fragCode = fragSimple; Geometry mush = generateRockHat(Vec3(0.0,0.0,0.0), 0.3, 1.0); GeoNode::Ptr geomush = GeoNode::create(mush, false); geomush->setColor(Vec3(1.0,1.0,1.0)); geomush->setPosition(Vec3(0.0,1.0,0.0)); geomush->setRotation(Vec3(3.14 * 0.1, 0.0, 3.14 * 0.25)); geomush->setShader(s); node2->addNode(geomush); bool stopLoop = false; while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed || event.type == sf::Event::KeyPressed) stopLoop=true;// window.close(); } if(stopLoop)break; if(clock.getElapsedTime().asSeconds() > 2.0*3.14) clock.restart(); double t = clock.getElapsedTime().asMilliseconds() / 1000.0; camera->setPosition(Vec3(cos(-t)*2.0,sin(-t)*2.0,(sin(t))*0.5)); camera->setTarget(Vec3(0.0,0.0,(sin(t))*0.5 )); node1->setPosition(Vec3(cos(t)*0.3,sin(t)*0.3,0.0)); // rendering graph->renderScene( root ); window.display(); } // ImageIO::save(tgt->get(0)->getSource(),"test.tga"); exit(EXIT_SUCCESS); }
update polyhedron bench project
update polyhedron bench project
C++
mit
Lut1n/ImpGears,Lut1n/ImpGears
fd59fca1085974ae5fb573c7e2a5bc6aeed63f36
toolbox/list_build_ids/list_build_ids.cpp
toolbox/list_build_ids/list_build_ids.cpp
/* list_build_ids * Copyright (c) 2016 Microsoft Corportation * MIT License * * This program opens a core dump and enumerates all the modules contained within it. For every * module that contains a build-id, this program will print out the build id and module name. * Currently only works for 64 bit core dumps. */ #include <elf.h> #include <cerrno> #include <cassert> #include <cstring> #include <cstdio> #include <set> #include <string> // build ids are actually 20 bytes, but we will allow a slightly larger buffer in case this grows in the future #define BUILD_ID_BYTE_MAX 64 // Reads an elf header structure from the given offset, validating that the magic header matches. int read_elf_header(FILE *fp, uint64_t offset, Elf64_Ehdr *elf_header); // Gets the file offset of a given virtual memory address. long get_file_offset(const Elf64_Ehdr &elf_header, Elf64_Phdr *program_headers, long vmaddr); // Walks all program headers in a given elf header. int walk_program_headers(FILE *file, const Elf64_Ehdr &elf_hdr, long nestedOffset = 0, const char *filename = NULL); // Walks all notes in a memory range (specified by a program/section header). int walk_notes(FILE *file, const Elf64_Ehdr &elf_hdr, Elf64_Phdr *program_headers, const char *filename, long notesBegin, long notesEnd); // Enumerates the next note in the sequence. int next_note(FILE *file, long offset, bool *is_build_id, bool *is_file_list, long *data_offset, long *data_length); // Walks a file table in a given note. int walk_file_table(FILE *file, const Elf64_Ehdr &elf_hdr, Elf64_Phdr *program_headers, char *file_table); // Prints a table of modules that do not have a build id void print_missing_table(); // Global variables to track what modules we've encountered and which have build ids std::set<std::string> encountered_modules; std::set<std::string> modules_with_build_id; int main(int argc, char ** argv) { if (argc != 2) { printf("usage: %s core_dump\n", argv[0]); return 1; } const char *core_file = argv[1]; FILE *file = fopen(core_file, "rb"); if (file == NULL) { int error = errno; printf("Error loading file '%s': %x\n", core_file, error); return error; } Elf64_Ehdr elf_header; if (read_elf_header(file, 0, &elf_header)) { printf("'%s' is not an elf binary.\n", core_file); fclose(file); return 1; } if (elf_header.e_type != ET_CORE) { printf("'%s' is not a core dump.\n", core_file); fclose(file); return 1; } if (elf_header.e_machine != EM_X86_64) { printf("'%s' is not an x86_x64 core dump.\n", core_file); fclose(file); return 1; } walk_program_headers(file, elf_header); fclose(file); print_missing_table(); return 0; } inline int note_align(int value) { return (value + 3) & ~3; } inline unsigned char get_hex(unsigned char c) { assert(c >= 0 && c <= 0xf); if (c <= 9) return c + '0'; return c - 10 + 'a'; } int read_elf_header(FILE *fp, uint64_t offset, Elf64_Ehdr *elf_header) { if (fseek(fp, offset, SEEK_SET) || fread(elf_header, sizeof(Elf64_Ehdr), 1, fp) != 1) return 1; if (elf_header->e_ident[EI_MAG0] != ELFMAG0 || elf_header->e_ident[EI_MAG1] != ELFMAG1 || elf_header->e_ident[EI_MAG2] != ELFMAG2 || elf_header->e_ident[EI_MAG3] != ELFMAG3) return 1; return 0; } long get_file_offset(const Elf64_Ehdr &elf_header, Elf64_Phdr *program_headers, long vmaddr) { // maps a virtual address back to a file offset within the core dump for (Elf64_Phdr *curr = program_headers; curr < program_headers + elf_header.e_phnum; curr++) { if (curr->p_type != PT_LOAD) continue; if (vmaddr >= (curr->p_vaddr & ~curr->p_align) && vmaddr <= curr->p_vaddr + curr->p_filesz) return vmaddr - curr->p_vaddr + curr->p_offset; } return 0; } int walk_program_headers(FILE *file, const Elf64_Ehdr &elf_hdr, long nested_offset, const char *filename) { // Walks the p-headers of either the core dump itself or of a nested module in the core dump // filename is null when we are walking the core dump itself, and nestedOffset == 0 // filename is the path of a loaded module when we are walking a module within the core dump, and nestedOffset != 0 assert(elf_hdr.e_phentsize == sizeof(Elf64_Phdr)); Elf64_Phdr *program_hdrs = new Elf64_Phdr[elf_hdr.e_phnum]; if (fseek(file, elf_hdr.e_phoff + nested_offset, SEEK_SET) || fread(program_hdrs, sizeof(Elf64_Phdr), elf_hdr.e_phnum, file) != elf_hdr.e_phnum) { if (filename == NULL) fprintf(stderr, "Failed to walk program headers in core dump.\n"); else fprintf(stderr, "Failed to read core dump headers for inner file '%s', skipping...\n", filename); delete[] program_hdrs; return 1; } for (int i = 0; i < elf_hdr.e_phnum; i++) { // We care about file lists and build ids, both of which are contained in NOTE sections. if (program_hdrs[i].p_type == PT_NOTE) { long begin = program_hdrs[i].p_offset + nested_offset; long end = program_hdrs[i].p_offset + program_hdrs[i].p_filesz + nested_offset; walk_notes(file, elf_hdr, program_hdrs, filename, begin, end); } } delete[] program_hdrs; return 0; } int walk_file_table(FILE *file, const Elf64_Ehdr &elf_hdr, Elf64_Phdr *program_headers, char *file_table) { // A file table is laid out as a counted list of three pointers: VM Address Start, VM Address End, Page Offset. // The corresponding string table for file name is a list of null terminated strings at the end of that table. size_t offs = 0; // table entry count size_t count = *(size_t*)(file_table + offs); offs += sizeof(size_t); // Page size offs += sizeof(size_t); size_t filename_offset = offs + count * 3 * sizeof(size_t); for (size_t i = 0; i < count && filename_offset; i++) { // vmrange start size_t start = *(size_t*)(file_table + offs); offs += sizeof(size_t); // vmrange stop offs += sizeof(size_t); // page offset offs += sizeof(size_t); // get the corresponding file path in the string table char *full_path = file_table + filename_offset; filename_offset += strlen(full_path) + 1; // Add the file to the list of modules we've seen encountered_modules.insert(full_path); // Check to see if the mapped file section is an elf header (that is, the beginning of the image) Elf64_Ehdr inner_header; long image_offset = get_file_offset(elf_hdr, program_headers, (long)start); if (image_offset != 0 && read_elf_header(file, image_offset, &inner_header) == 0) walk_program_headers(file, inner_header, image_offset, full_path); } return 0; } int walk_notes(FILE *file, const Elf64_Ehdr &elf_hdr, Elf64_Phdr *program_headers, const char *filename, long notesBegin, long notesEnd) { // This function could be walking either the core dump itself or a module loaded as a section in the core dump. // If filename is null then we are walking the core dump itself, and nestedOffset == 0. // If filename is the path of a loaded module then we are walking a module within the core dump, and nestedOffset != 0. // When walking the core dump itself (filename == NULL) we expect to find a file list somewhere in the notes. // When walking a loaded module (filename != NULL), we may find a build id. // We do NOT expect to find a build ID in the core dump itself, and we do NOT expect to find a file list within a loaded module. long offset = notesBegin; long data_offset = 0, data_len; bool is_build_id, is_file_list; while (offset < notesEnd && (offset = next_note(file, offset, &is_build_id, &is_file_list, &data_offset, &data_len)) != 0) { if (is_build_id && filename) { // '&& filename' ensures we are inspected a loaded module and not a floating build id in the core dump itself. assert(!is_file_list); assert(data_len > 0 && data_len < BUILD_ID_BYTE_MAX); if (data_len <= BUILD_ID_BYTE_MAX) { unsigned char build_id[BUILD_ID_BYTE_MAX]; if (fseek(file, data_offset, SEEK_SET) == 0 && fread(build_id, 1, data_len, file) == data_len) { for (int i = 0; i < data_len; i++) printf("%c%c", get_hex(build_id[i] >> 4), get_hex(build_id[i] & 0xf)); printf(" %s\n", filename); } // Mark that we have a build id for this module. modules_with_build_id.insert(filename); // We are enumerating an embedded module in the core. Once we find the build id we can stop looking. return 0; } } if (is_file_list && !filename) { // '&& !filename' ensures we are only inspecting a file list within the core dump itself and not an // NT_FILE that happens to be within a loaded module. assert(!is_build_id); assert(data_len > 0); char *file_table = new char[data_len]; if (fseek(file, data_offset, SEEK_SET) == 0 && fread(file_table, 1, data_len, file) == data_len) walk_file_table(file, elf_hdr, program_headers, file_table); delete[] file_table; } } return 0; } int next_note(FILE *file, long offset, bool *is_build_id, bool *is_file_list, long *data_offset, long *data_length) { assert(!data_offset == !data_length); if (offset <= 0) return 0; // Read note header Elf64_Nhdr header; if (fseek(file, offset, SEEK_SET) || fread(&header, sizeof(Elf64_Nhdr), 1, file) != 1) return 0; offset += sizeof(header); // build ids are NT_PRPSINFO sections with a name of "GNU". if (is_build_id) { char name[4]; if (header.n_type == NT_PRPSINFO && header.n_namesz == 4) *is_build_id = fread(name, sizeof(char), 4, file) == 4 && memcmp(name, "GNU", 4) == 0; else *is_build_id = false; } // file lists are a section of type NT_FILE if (is_file_list) *is_file_list = header.n_type == NT_FILE; // Move past name offset += note_align(header.n_namesz); if (data_offset && data_length) { *data_offset = offset; *data_length = header.n_descsz; } // Move past data offset += note_align(header.n_descsz); return offset; } void print_missing_table() { bool first = true; for (std::set<std::string>::iterator itr = encountered_modules.begin(); itr != encountered_modules.end(); ++itr) { if (modules_with_build_id.find(*itr) == modules_with_build_id.end()) { if (itr->find("/dev/") != 0) { if (first) { printf("\nModules without build ids:\n"); first = false; } printf(" %s\n", itr->c_str()); } } } }
/* list_build_ids * Copyright (c) 2016 Microsoft Corportation * MIT License * * This program opens a core dump and enumerates all the modules contained within it. For every * module that contains a build-id, this program will print out the build id and module name. * Currently only works for 64 bit core dumps. */ #include <elf.h> #include <cerrno> #include <cassert> #include <cstring> #include <cstdio> #include <set> #include <string> // elf.h defines ELF_NOTE_GNU but not a length for it #define ELF_NOTE_GNU_LEN 4 // build ids are actually 20 bytes, but we will allow a slightly larger buffer in case this grows in the future #define BUILD_ID_BYTE_MAX 64 // Reads an elf header structure from the given offset, validating that the magic header matches. int read_elf_header(FILE *fp, uint64_t offset, Elf64_Ehdr *elf_header); // Gets the file offset of a given virtual memory address. long get_file_offset(const Elf64_Ehdr &elf_header, Elf64_Phdr *program_headers, long vmaddr); // Walks all program headers in an elf file. int walk_program_headers(FILE *file, const Elf64_Ehdr &elf_hdr, const char *filename = NULL, long nestedOffset = 0); // Walks all notes in a memory range (specified by a program/section header). int walk_notes(FILE *file, const Elf64_Ehdr &elf_hdr, Elf64_Phdr *program_headers, const char *filename, long notesBegin, long notesEnd); // Enumerates the next note in the sequence. int next_note(FILE *file, long offset, bool *is_build_id, bool *is_file_list, long *data_offset, long *data_length); // Walks a file table in a given note. int walk_file_table(FILE *file, const Elf64_Ehdr &elf_hdr, Elf64_Phdr *program_headers, char *file_table); // Prints a table of modules that do not have a build id void print_missing_table(); // Global variables to track what modules we've encountered and which have build ids std::set<std::string> encountered_modules; std::set<std::string> modules_with_build_id; int main(int argc, char ** argv) { if (argc != 2) { printf("usage: %s core_dump\n", argv[0]); return 1; } const char *filename = argv[1]; FILE *file = fopen(filename, "rb"); if (file == NULL) { int error = errno; printf("Error loading file '%s': %x\n", filename, error); return error; } Elf64_Ehdr elf_header; if (read_elf_header(file, 0, &elf_header)) { printf("'%s' is not an elf binary.\n", filename); fclose(file); return 1; } if (elf_header.e_machine != EM_X86_64) { printf("Error loading '%s': currently only x86_x64 is supported.\n", filename); fclose(file); return 1; } int returnCode = 0; if (elf_header.e_type == ET_EXEC || elf_header.e_type == ET_CORE) { walk_program_headers(file, elf_header); print_missing_table(); } else if (elf_header.e_type == ET_EXEC || elf_header.e_type == ET_DYN) { walk_program_headers(file, elf_header, filename); } else { printf("Unknown ELF file '%s'.\n", filename); returnCode = -1; } fclose(file); return returnCode; } inline int note_align(int value) { return (value + 3) & ~3; } inline unsigned char get_hex(unsigned char c) { assert(c >= 0 && c <= 0xf); if (c <= 9) return c + '0'; return c - 10 + 'a'; } int read_elf_header(FILE *fp, uint64_t offset, Elf64_Ehdr *elf_header) { if (fseek(fp, offset, SEEK_SET) || fread(elf_header, sizeof(Elf64_Ehdr), 1, fp) != 1) return 1; if (elf_header->e_ident[EI_MAG0] != ELFMAG0 || elf_header->e_ident[EI_MAG1] != ELFMAG1 || elf_header->e_ident[EI_MAG2] != ELFMAG2 || elf_header->e_ident[EI_MAG3] != ELFMAG3) return 1; return 0; } long get_file_offset(const Elf64_Ehdr &elf_header, Elf64_Phdr *program_headers, long vmaddr) { // maps a virtual address back to a file offset within the core dump for (Elf64_Phdr *curr = program_headers; curr < program_headers + elf_header.e_phnum; curr++) { if (curr->p_type != PT_LOAD) continue; if (vmaddr >= (curr->p_vaddr & ~curr->p_align) && vmaddr <= curr->p_vaddr + curr->p_filesz) return vmaddr - curr->p_vaddr + curr->p_offset; } return 0; } int walk_program_headers(FILE *file, const Elf64_Ehdr &elf_hdr, const char *filename, long nested_offset) { // Walks the p-headers of either the core dump itself or of a nested module in the core dump // filename is null when we are walking the core dump itself, and nestedOffset == 0 // filename is the path of a loaded module when we are walking a module within the core dump, and nestedOffset != 0 assert(elf_hdr.e_phentsize == sizeof(Elf64_Phdr)); Elf64_Phdr *program_hdrs = new Elf64_Phdr[elf_hdr.e_phnum]; if (fseek(file, elf_hdr.e_phoff + nested_offset, SEEK_SET) || fread(program_hdrs, sizeof(Elf64_Phdr), elf_hdr.e_phnum, file) != elf_hdr.e_phnum) { if (filename == NULL) fprintf(stderr, "Failed to walk program headers in core dump.\n"); else fprintf(stderr, "Failed to read core dump headers for inner file '%s', skipping...\n", filename); delete[] program_hdrs; return 1; } for (int i = 0; i < elf_hdr.e_phnum; i++) { // We care about file lists and build ids, both of which are contained in NOTE sections. if (program_hdrs[i].p_type == PT_NOTE) { long begin = program_hdrs[i].p_offset + nested_offset; long end = program_hdrs[i].p_offset + program_hdrs[i].p_filesz + nested_offset; walk_notes(file, elf_hdr, program_hdrs, filename, begin, end); } } delete[] program_hdrs; return 0; } int walk_file_table(FILE *file, const Elf64_Ehdr &elf_hdr, Elf64_Phdr *program_headers, char *file_table) { // A file table is laid out as a counted list of three pointers: VM Address Start, VM Address End, Page Offset. // The corresponding string table for file name is a list of null terminated strings at the end of that table. size_t offs = 0; // table entry count size_t count = *(size_t*)(file_table + offs); offs += sizeof(size_t); // Page size offs += sizeof(size_t); size_t filename_offset = offs + count * 3 * sizeof(size_t); for (size_t i = 0; i < count && filename_offset; i++) { // vmrange start size_t start = *(size_t*)(file_table + offs); offs += sizeof(size_t); // vmrange stop offs += sizeof(size_t); // page offset offs += sizeof(size_t); // get the corresponding file path in the string table char *full_path = file_table + filename_offset; filename_offset += strlen(full_path) + 1; // Add the file to the list of modules we've seen encountered_modules.insert(full_path); // Check to see if the mapped file section is an elf header (that is, the beginning of the image) Elf64_Ehdr inner_header; long image_offset = get_file_offset(elf_hdr, program_headers, (long)start); if (image_offset != 0 && read_elf_header(file, image_offset, &inner_header) == 0) walk_program_headers(file, inner_header, full_path, image_offset); } return 0; } int walk_notes(FILE *file, const Elf64_Ehdr &elf_hdr, Elf64_Phdr *program_headers, const char *filename, long notesBegin, long notesEnd) { // This function could be walking either the core dump itself or a module loaded as a section in the core dump. // If filename is null then we are walking the core dump itself, and nestedOffset == 0. // If filename is the path of a loaded module then we are walking a module within the core dump, and nestedOffset != 0. // When walking the core dump itself (filename == NULL) we expect to find a file list somewhere in the notes. // When walking a loaded module (filename != NULL), we may find a build id. // We do NOT expect to find a build ID in the core dump itself, and we do NOT expect to find a file list within a loaded module. long offset = notesBegin; long data_offset = 0, data_len; bool is_build_id, is_file_list; while (offset < notesEnd && (offset = next_note(file, offset, &is_build_id, &is_file_list, &data_offset, &data_len)) != 0) { if (is_build_id && filename) { // '&& filename' ensures we are inspected a loaded module and not a floating build id in the core dump itself. assert(!is_file_list); assert(data_len > 0 && data_len < BUILD_ID_BYTE_MAX); if (data_len <= BUILD_ID_BYTE_MAX) { unsigned char build_id[BUILD_ID_BYTE_MAX]; if (fseek(file, data_offset, SEEK_SET) == 0 && fread(build_id, 1, data_len, file) == data_len) { for (int i = 0; i < data_len; i++) printf("%c%c", get_hex(build_id[i] >> 4), get_hex(build_id[i] & 0xf)); printf(" %s\n", filename); } // Mark that we have a build id for this module. modules_with_build_id.insert(filename); // We are enumerating an embedded module in the core. Once we find the build id we can stop looking. return 0; } } if (is_file_list && !filename) { // '&& !filename' ensures we are only inspecting a file list within the core dump itself and not an // NT_FILE that happens to be within a loaded module. assert(!is_build_id); assert(data_len > 0); char *file_table = new char[data_len]; if (fseek(file, data_offset, SEEK_SET) == 0 && fread(file_table, 1, data_len, file) == data_len) walk_file_table(file, elf_hdr, program_headers, file_table); delete[] file_table; } } return 0; } int next_note(FILE *file, long offset, bool *is_build_id, bool *is_file_list, long *data_offset, long *data_length) { assert(!data_offset == !data_length); if (offset <= 0) return 0; // Read note header Elf64_Nhdr header; if (fseek(file, offset, SEEK_SET) || fread(&header, sizeof(Elf64_Nhdr), 1, file) != 1) return 0; offset += sizeof(header); // build ids are NT_PRPSINFO sections with a name of "GNU". if (is_build_id) { char name[ELF_NOTE_GNU_LEN]; if (header.n_type == NT_PRPSINFO && header.n_namesz == ELF_NOTE_GNU_LEN) *is_build_id = fread(name, sizeof(char), ELF_NOTE_GNU_LEN, file) == ELF_NOTE_GNU_LEN && memcmp(name, ELF_NOTE_GNU, ELF_NOTE_GNU_LEN) == 0; else *is_build_id = false; } // file lists are a section of type NT_FILE if (is_file_list) *is_file_list = header.n_type == NT_FILE; // Move past name offset += note_align(header.n_namesz); if (data_offset && data_length) { *data_offset = offset; *data_length = header.n_descsz; } // Move past data offset += note_align(header.n_descsz); return offset; } void print_missing_table() { bool first = true; for (std::set<std::string>::iterator itr = encountered_modules.begin(); itr != encountered_modules.end(); ++itr) { if (modules_with_build_id.find(*itr) == modules_with_build_id.end()) { if (itr->find("/dev/") != 0) { if (first) { printf("\nModules without build ids:\n"); first = false; } printf(" %s\n", itr->c_str()); } } } }
Update list_build_ids to work on libraries too
Update list_build_ids to work on libraries too Updated the list_build_ids tool to work on libraries in addition to core dumps.
C++
mit
leculver/dotnet-reliability,leculver/dotnet-reliability,leculver/dotnet-reliability,leculver/dotnet-reliability,leculver/dotnet-reliability,leculver/dotnet-reliability
6c0b7c54df7cfa68dd4098df65a08d0bc51932c3
test/test-issue7.cc
test/test-issue7.cc
#include <unistd.h> #include "rpc/server.h" #include "rpc/client.h" using namespace base; using namespace rpc; TEST(issue, 7) { const int rpc_id = 1987; PollMgr* poll = new PollMgr; ThreadPool* thrpool = new ThreadPool; Server *svr = new Server(poll, thrpool); // directly release poll to make sure it has ref_count of 1 // other other hand, thrpool is kept till end of program, with ref_count of 2 poll->release(); svr->reg(rpc_id, [] (Request* req, ServerConnection* sconn) { sconn->run_async([req, sconn] { Log::debug("rpc called"); ::usleep(500 * 1000); Log::debug("rpc replying"); sconn->begin_reply(req); // reply nothing sconn->end_reply(); delete req; sconn->release(); Log::debug("rpc replied"); }); }); svr->start("127.0.0.1:7891"); PollMgr* poll_clnt = new PollMgr; Client* clnt = new Client(poll_clnt); clnt->connect("127.0.0.1:7891"); Future* fu = clnt->begin_request(rpc_id); clnt->end_request(); // wait a little bit to make sure RPC got sent instead of cancelled fu->timed_wait(0.01); clnt->close_and_release(); poll_clnt->release(); Log::debug("killing server"); delete svr; Log::debug("killed server"); // thrpool is kept till end of program, with ref_count of 2 thrpool->release(); }
#include <unistd.h> #include "rpc/server.h" #include "rpc/client.h" using namespace base; using namespace rpc; TEST(issue, 7) { const int rpc_id = 1987; PollMgr* poll = new PollMgr(1); ThreadPool* thrpool = new ThreadPool(1); Server *svr = new Server(poll, thrpool); // directly release poll to make sure it has ref_count of 1 // other other hand, thrpool is kept till end of program, with ref_count of 2 poll->release(); svr->reg(rpc_id, [] (Request* req, ServerConnection* sconn) { sconn->run_async([req, sconn] { Log::debug("rpc called"); ::usleep(500 * 1000); Log::debug("rpc replying"); sconn->begin_reply(req); // reply nothing sconn->end_reply(); delete req; sconn->release(); Log::debug("rpc replied"); }); }); svr->start("127.0.0.1:7891"); PollMgr* poll_clnt = new PollMgr(1); Client* clnt = new Client(poll_clnt); clnt->connect("127.0.0.1:7891"); Future* fu = clnt->begin_request(rpc_id); clnt->end_request(); // wait a little bit to make sure RPC got sent instead of cancelled fu->timed_wait(0.01); clnt->close_and_release(); poll_clnt->release(); Log::debug("killing server"); delete svr; Log::debug("killed server"); // thrpool is kept till end of program, with ref_count of 2 thrpool->release(); }
use 1 io thread and 1 worker thread
use 1 io thread and 1 worker thread
C++
bsd-3-clause
santazhang/simple-rpc,santazhang/simple-rpc,santazhang/simple-rpc,santazhang/simple-rpc
ddb8194eb6aee9024c9c0c7fb4211fb042600d9f
examples/accel/accel_countred.cpp
examples/accel/accel_countred.cpp
#include <OpenCLcontext.h> #include <random> #include <iostream> #define X 800 #define Y 600 int main(void) { try { std::random_device rd; std::mt19937 mt(rd()); std::uniform_int_distribution<unsigned int> dist; unsigned int framebuffer[X*Y]; OpenCL_Manager mgr; mgr.initialize(X, Y); unsigned long redpixels = 0; while (true) { using clock_type = std::chrono::steady_clock; using second_type = std::chrono::duration<double, std::ratio<1> >; for (size_t i = 0; i < X*Y; ++i) framebuffer[i] = dist(mt); redpixels = 0; std::chrono::time_point<clock_type> m_beg { clock_type::now() }; mgr.processCameraFrame(reinterpret_cast<unsigned char*>(framebuffer), &redpixels); std::chrono::time_point<clock_type> m_end { clock_type::now() }; double diff = std::chrono::duration_cast<second_type>(m_end - m_beg).count(); std::cout << "FRAME red pixels: " << redpixels << " time: " << diff << "\n"; } } catch (std::exception &e) { std::cerr << "ERROR: " << e.what() << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
#include <OpenCLcontext.h> #include <random> #include <iostream> #define X 800 #define Y 600 #define SAMPLES 40 int main(void) { try { std::random_device rd; std::mt19937 mt(rd()); std::uniform_int_distribution<unsigned int> dist; unsigned int framebuffer[X*Y]; OpenCL_Manager mgr; mgr.initialize(X, Y); unsigned long redpixels = 0; std::vector<float> samples; while (true) { using clock_type = std::chrono::steady_clock; using second_type = std::chrono::duration<double, std::ratio<1> >; for (size_t i = 0; i < X*Y; ++i) framebuffer[i] = dist(mt); redpixels = 0; std::chrono::time_point<clock_type> m_beg { clock_type::now() }; mgr.processCameraFrame(reinterpret_cast<unsigned char*>(framebuffer), &redpixels); std::chrono::time_point<clock_type> m_end { clock_type::now() }; double diff = std::chrono::duration_cast<second_type>(m_end - m_beg).count(); std::cout << "FRAME red pixels: " << redpixels << " time: " << diff << "\n"; if (samples.size() < SAMPLES) { samples.push_back((float)diff); } else { float sum = std::accumulate(samples.begin(), samples.end(), 0.0f); float fps = (float)SAMPLES / sum; std::cout << "FPS : " << fps << "\n"; samples.clear(); } } } catch (std::exception &e) { std::cerr << "ERROR: " << e.what() << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
add FPS counter
accel_countred.cpp: add FPS counter
C++
mit
pocl/pocl,pocl/pocl,pocl/pocl,pocl/pocl,pocl/pocl
c657b0c30a4b23adfdbb82c05ef9afb7df29e11a
project/opencv/lib/cv_embox_imshowfb.cpp
project/opencv/lib/cv_embox_imshowfb.cpp
/** * @file * * @date 12.04.2021 * @author Alexander Kalmuk */ #include <stdio.h> #include <drivers/video/fb.h> #include <util/log.h> #include <algorithm> #include <cv_embox_imshowfb.hpp> void imshowfb(cv::Mat& img, int fbx) { struct fb_info *fbi; int w, h; fbi = fb_lookup(fbx); if (!fbi) { fprintf(stderr, "%s: fb%d not found\n", __func__, fbx); return; } log_debug("\nimage width: %d\n" "image height: %d\n" "image size: %dx%d\n" "image depth: %d\n" "image channels: %d\n" "image type: %d", img.cols, img.rows, img.size().width, img.size().height, img.depth(), img.channels(), img.type()); if (img.channels() != 1 && img.channels() != 3) { fprintf(stderr, "Unsupported channels count: %d\n", img.channels()); return; } h = std::min((int) fbi->var.yres, img.rows); w = std::min((int) (fbi->var.bits_per_pixel * fbi->var.xres) / 8, img.channels() * img.cols); for (int y = 0; y < h; y++) { const uchar *row = &img.at<uchar>(y, 0); for (int x = 0; x < w; x += img.channels()) { unsigned rgb888; switch (img.channels()) { case 1: { unsigned val = unsigned(row[x]); rgb888 = 0xFF000000 | val | (val << 8) | (val << 16); break; } case 3: rgb888 = 0xFF000000 | unsigned(row[x + 2]) | (unsigned(row[x + 1]) << 8) | (unsigned(row[x]) << 16); break; default: break; } ((uint32_t *) fbi->screen_base)[fbi->var.xres * y + x / img.channels()] = rgb888; } } }
/** * @file * * @date 12.04.2021 * @author Alexander Kalmuk */ #include <stdio.h> #include <drivers/video/fb.h> #include <util/log.h> #include <algorithm> #include <cv_embox_imshowfb.hpp> void imshowfb(cv::Mat& img, int fbx) { struct fb_info *fbi; int w, h; fbi = fb_lookup(fbx); if (!fbi) { fprintf(stderr, "%s: fb%d not found\n", __func__, fbx); return; } log_debug("\nimage width: %d\n" "image height: %d\n" "image size: %dx%d\n" "image depth: %d\n" "image channels: %d\n" "image type: %d", img.cols, img.rows, img.size().width, img.size().height, img.depth(), img.channels(), img.type()); if (img.channels() != 1 && img.channels() != 3) { fprintf(stderr, "Unsupported channels count: %d\n", img.channels()); return; } h = std::min((int) fbi->var.yres, img.rows); w = std::min((int) (fbi->var.bits_per_pixel * fbi->var.xres) / 8, img.channels() * img.cols); for (int y = 0; y < h; y++) { const uchar *row = &img.at<uchar>(y, 0); for (int x = 0; x < w; x += img.channels()) { unsigned rgb888; switch (img.channels()) { case 1: { unsigned val = unsigned(row[x]); rgb888 = 0xFF000000 | val | (val << 8) | (val << 16); break; } case 3: rgb888 = 0xFF000000 | unsigned(row[x + 2]) | (unsigned(row[x + 1]) << 8) | (unsigned(row[x]) << 16); break; default: break; } ((uint32_t *) fbi->screen_base)[fbi->var.xres * y + x / img.channels()] = rgb888; } } }
Fix code formatting in cv_embox_imshowfb.cpp
opencv: Fix code formatting in cv_embox_imshowfb.cpp
C++
bsd-2-clause
embox/embox,embox/embox,embox/embox,embox/embox,embox/embox,embox/embox
36829c4c8740ba6b1532b8e025293046c2fda649
api/stream_manager.cc
api/stream_manager.cc
/* * Copyright 2015 Cloudius Systems */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include "stream_manager.hh" #include "streaming/stream_manager.hh" #include "streaming/stream_result_future.hh" #include "api/api-doc/stream_manager.json.hh" #include <vector> #include "gms/gossiper.hh" namespace api { namespace hs = httpd::stream_manager_json; static void set_summaries(const std::vector<streaming::stream_summary>& from, json::json_list<hs::stream_summary>& to) { for (auto sum : from) { hs::stream_summary res; res.cf_id = boost::lexical_cast<std::string>(sum.cf_id); res.files = sum.files; res.total_size = sum.total_size; to.push(res); } } static hs::progress_info get_progress_info(const streaming::progress_info& info) { hs::progress_info res; res.current_bytes = info.current_bytes; res.direction = info.dir; res.file_name = info.file_name; res.peer = boost::lexical_cast<std::string>(info.peer); res.session_index = 0; res.total_bytes = info.total_bytes; return res; } static void set_files(const std::map<sstring, streaming::progress_info>& from, json::json_list<hs::progress_info_mapper>& to) { for (auto i : from) { hs::progress_info_mapper m; m.key = i.first; m.value = get_progress_info(i.second); to.push(m); } } static hs::stream_state get_state( streaming::stream_result_future& result_future) { hs::stream_state state; state.description = result_future.description; state.plan_id = result_future.plan_id.to_sstring(); for (auto info : result_future.get_coordinator().get()->get_all_session_info()) { hs::stream_info si; si.peer = boost::lexical_cast<std::string>(info.peer); si.session_index = 0; si.state = info.state; si.connecting = si.peer; set_summaries(info.receiving_summaries, si.receiving_summaries); set_summaries(info.sending_summaries, si.sending_summaries); set_files(info.receiving_files, si.receiving_files); set_files(info.sending_files, si.sending_files); state.sessions.push(si); } return state; } void set_stream_manager(http_context& ctx, routes& r) { hs::get_current_streams.set(r, [] (std::unique_ptr<request> req) { return streaming::get_stream_manager().map_reduce0([](streaming::stream_manager& stream) { std::vector<hs::stream_state> res; for (auto i : stream.get_initiated_streams()) { res.push_back(get_state(*i.second.get())); } for (auto i : stream.get_receiving_streams()) { res.push_back(get_state(*i.second.get())); } return res; }, std::vector<hs::stream_state>(),concat<hs::stream_state>). then([](const std::vector<hs::stream_state>& res) { return make_ready_future<json::json_return_type>(res); }); }); hs::get_all_active_streams_outbound.set(r, [](std::unique_ptr<request> req) { return streaming::get_stream_manager().map_reduce0([](streaming::stream_manager& stream) { return stream.get_initiated_streams().size(); }, 0, std::plus<int64_t>()).then([](int64_t res) { return make_ready_future<json::json_return_type>(res); }); }); hs::get_total_incoming_bytes.set(r, [](std::unique_ptr<request> req) { gms::inet_address peer(req->param["peer"]); return streaming::get_stream_manager().map_reduce0([peer](streaming::stream_manager& stream) { int64_t res = 0; for (auto s : stream.get_receiving_streams()) { if (s.second.get() != nullptr) { for (auto si: s.second.get()->get_coordinator()->get_peer_session_info(peer)) { res += si.get_total_size_received(); } } } return res; }, 0, std::plus<int64_t>()).then([](int64_t res) { return make_ready_future<json::json_return_type>(res); }); }); hs::get_all_total_incoming_bytes.set(r, [](std::unique_ptr<request> req) { return streaming::get_stream_manager().map_reduce0([](streaming::stream_manager& stream) { int64_t res = 0; for (auto s : stream.get_receiving_streams()) { if (s.second.get() != nullptr) { for (auto si: s.second.get()->get_coordinator()->get_all_session_info()) { res += si.get_total_size_received(); } } } return res; }, 0, std::plus<int64_t>()).then([](int64_t res) { return make_ready_future<json::json_return_type>(res); }); }); hs::get_total_outgoing_bytes.set(r, [](std::unique_ptr<request> req) { gms::inet_address peer(req->param["peer"]); return streaming::get_stream_manager().map_reduce0([peer](streaming::stream_manager& stream) { int64_t res = 0; for (auto s : stream.get_initiated_streams()) { if (s.second.get() != nullptr) { for (auto si: s.second.get()->get_coordinator()->get_peer_session_info(peer)) { res += si.get_total_size_sent(); } } } return res; }, 0, std::plus<int64_t>()).then([](int64_t res) { return make_ready_future<json::json_return_type>(res); }); }); hs::get_all_total_outgoing_bytes.set(r, [](std::unique_ptr<request> req) { return streaming::get_stream_manager().map_reduce0([](streaming::stream_manager& stream) { int64_t res = 0; for (auto s : stream.get_initiated_streams()) { if (s.second.get() != nullptr) { for (auto si: s.second.get()->get_coordinator()->get_all_session_info()) { res += si.get_total_size_sent(); } } } return res; }, 0, std::plus<int64_t>()).then([](int64_t res) { return make_ready_future<json::json_return_type>(res); }); }); } }
/* * Copyright 2015 Cloudius Systems */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include "stream_manager.hh" #include "streaming/stream_manager.hh" #include "streaming/stream_result_future.hh" #include "api/api-doc/stream_manager.json.hh" #include <vector> #include "gms/gossiper.hh" namespace api { namespace hs = httpd::stream_manager_json; static void set_summaries(const std::vector<streaming::stream_summary>& from, json::json_list<hs::stream_summary>& to) { for (auto sum : from) { hs::stream_summary res; res.cf_id = boost::lexical_cast<std::string>(sum.cf_id); res.files = sum.files; res.total_size = sum.total_size; to.push(res); } } static hs::progress_info get_progress_info(const streaming::progress_info& info) { hs::progress_info res; res.current_bytes = info.current_bytes; res.direction = info.dir; res.file_name = info.file_name; res.peer = boost::lexical_cast<std::string>(info.peer); res.session_index = 0; res.total_bytes = info.total_bytes; return res; } static void set_files(const std::map<sstring, streaming::progress_info>& from, json::json_list<hs::progress_info_mapper>& to) { for (auto i : from) { hs::progress_info_mapper m; m.key = i.first; m.value = get_progress_info(i.second); to.push(m); } } static hs::stream_state get_state( streaming::stream_result_future& result_future) { hs::stream_state state; state.description = result_future.description; state.plan_id = result_future.plan_id.to_sstring(); for (auto info : result_future.get_coordinator().get()->get_all_session_info()) { hs::stream_info si; si.peer = boost::lexical_cast<std::string>(info.peer); si.session_index = 0; si.state = info.state; si.connecting = si.peer; set_summaries(info.receiving_summaries, si.receiving_summaries); set_summaries(info.sending_summaries, si.sending_summaries); set_files(info.receiving_files, si.receiving_files); set_files(info.sending_files, si.sending_files); state.sessions.push(si); } return state; } void set_stream_manager(http_context& ctx, routes& r) { hs::get_current_streams.set(r, [] (std::unique_ptr<request> req) { return streaming::get_stream_manager().map_reduce0([](streaming::stream_manager& stream) { std::vector<hs::stream_state> res; for (auto i : stream.get_initiated_streams()) { res.push_back(get_state(*i.second.get())); } for (auto i : stream.get_receiving_streams()) { res.push_back(get_state(*i.second.get())); } return res; }, std::vector<hs::stream_state>(),concat<hs::stream_state>). then([](const std::vector<hs::stream_state>& res) { return make_ready_future<json::json_return_type>(res); }); }); hs::get_all_active_streams_outbound.set(r, [](std::unique_ptr<request> req) { return streaming::get_stream_manager().map_reduce0([](streaming::stream_manager& stream) { return stream.get_initiated_streams().size(); }, 0, std::plus<int64_t>()).then([](int64_t res) { return make_ready_future<json::json_return_type>(res); }); }); hs::get_total_incoming_bytes.set(r, [](std::unique_ptr<request> req) { gms::inet_address peer(req->param["peer"]); return streaming::get_stream_manager().map_reduce0([peer](streaming::stream_manager& stream) { int64_t res = 0; for (auto s : stream.get_all_streams()) { if (s) { for (auto si : s->get_coordinator()->get_peer_session_info(peer)) { res += si.get_total_size_received(); } } } return res; }, 0, std::plus<int64_t>()).then([](int64_t res) { return make_ready_future<json::json_return_type>(res); }); }); hs::get_all_total_incoming_bytes.set(r, [](std::unique_ptr<request> req) { return streaming::get_stream_manager().map_reduce0([](streaming::stream_manager& stream) { int64_t res = 0; for (auto s : stream.get_all_streams()) { if (s) { for (auto si : s->get_coordinator()->get_all_session_info()) { res += si.get_total_size_received(); } } } return res; }, 0, std::plus<int64_t>()).then([](int64_t res) { return make_ready_future<json::json_return_type>(res); }); }); hs::get_total_outgoing_bytes.set(r, [](std::unique_ptr<request> req) { gms::inet_address peer(req->param["peer"]); return streaming::get_stream_manager().map_reduce0([peer](streaming::stream_manager& stream) { int64_t res = 0; for (auto s : stream.get_all_streams()) { if (s) { for (auto si : s->get_coordinator()->get_peer_session_info(peer)) { res += si.get_total_size_sent(); } } } return res; }, 0, std::plus<int64_t>()).then([](int64_t res) { return make_ready_future<json::json_return_type>(res); }); }); hs::get_all_total_outgoing_bytes.set(r, [](std::unique_ptr<request> req) { return streaming::get_stream_manager().map_reduce0([](streaming::stream_manager& stream) { int64_t res = 0; for (auto s : stream.get_all_streams()) { if (s) { for (auto si : s->get_coordinator()->get_all_session_info()) { res += si.get_total_size_sent(); } } } return res; }, 0, std::plus<int64_t>()).then([](int64_t res) { return make_ready_future<json::json_return_type>(res); }); }); } }
Fix stream_manager total_incoming/outgoing bytes
api: Fix stream_manager total_incoming/outgoing bytes Any stream, no matter initialized by us or initialized by a peer node, can send and receive data. We should audit incoming/outgoing bytes in the all streams.
C++
agpl-3.0
scylladb/scylla,raphaelsc/scylla,avikivity/scylla,raphaelsc/scylla,raphaelsc/scylla,duarten/scylla,avikivity/scylla,kjniemi/scylla,kjniemi/scylla,duarten/scylla,scylladb/scylla,kjniemi/scylla,scylladb/scylla,duarten/scylla,scylladb/scylla,avikivity/scylla
b86ae1f0f20f843096dfa5940425166f81177fc5
IO/vtkParticleReader.cxx
IO/vtkParticleReader.cxx
/*========================================================================= Program: Visualization Toolkit Module: vtkParticleReader.cxx Language: C++ Date: $Date$ Version: $Revision$ Thanks: Thanks to C. Charles Law who developed this class. Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen 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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. 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 AUTHORS 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 <stdio.h> #include <ctype.h> #include <string.h> #include "vtkByteSwap.h" #include "vtkParticleReader.h" #include "vtkFloatArray.h" #include "vtkCellArray.h" #include "vtkPoints.h" #include "vtkObjectFactory.h" // These are copied right from vtkImageReader. // I do not know what they do. #ifdef read #undef read #endif #ifdef close #undef close #endif //---------------------------------------------------------------------------- vtkParticleReader* vtkParticleReader::New() { // First try to create the object from the vtkObjectFactory vtkObject* ret = vtkObjectFactory::CreateInstance("vtkParticleReader"); if(ret) { return (vtkParticleReader*)ret; } // If the factory was unable to create the object, then create it here. return new vtkParticleReader; } //---------------------------------------------------------------------------- vtkParticleReader::vtkParticleReader() { this->FileName = NULL; this->File = NULL; #ifndef VTK_WORDS_BIGENDIAN this->SwapBytes = 0; #else this->SwapBytes = 1; #endif this->NumberOfPoints = 0; } //---------------------------------------------------------------------------- vtkParticleReader::~vtkParticleReader() { if (this->File) { this->File->close(); delete this->File; this->File = NULL; } if (this->FileName) { delete [] this->FileName; this->FileName = NULL; } } //---------------------------------------------------------------------------- void vtkParticleReader::OpenFile() { if (!this->FileName) { vtkErrorMacro(<<"FileName must be specified."); return; } // Close file from any previous image if (this->File) { this->File->close(); delete this->File; this->File = NULL; } // Open the new file vtkDebugMacro(<< "Initialize: opening file " << this->FileName); #ifdef _WIN32 this->File = new ifstream(this->FileName, ios::in | ios::binary); #else this->File = new ifstream(this->FileName, ios::in); #endif if (! this->File || this->File->fail()) { vtkErrorMacro(<< "Initialize: Could not open file " << this->FileName); return; } } //---------------------------------------------------------------------------- // This method returns the largest data that can be generated. void vtkParticleReader::ExecuteInformation() { vtkPolyData *output = this->GetOutput(); output->SetMaximumNumberOfPieces(-1); } //---------------------------------------------------------------------------- // This method returns the largest data that can be generated. void vtkParticleReader::Execute() { vtkPolyData *output = this->GetOutput(); vtkPoints *points; vtkFloatArray *array; vtkCellArray *verts; unsigned long fileLength, start, next, length, ptIdx, cellPtIdx; unsigned long cellLength; int piece, numPieces; float *data, *ptr; if (!this->FileName) { vtkErrorMacro(<<"FileName must be specified."); return; } this->OpenFile(); // Get the size of the header from the size of the image this->File->seekg(0,ios::end); if (this->File->fail()) { vtkErrorMacro("Could not seek to end of file."); return; } fileLength = (unsigned long)this->File->tellg(); this->NumberOfPoints = fileLength / (4 * sizeof(float)); piece = output->GetUpdatePiece(); numPieces = output->GetUpdateNumberOfPieces(); if ((unsigned long)numPieces > this->NumberOfPoints) { numPieces = (int)(this->NumberOfPoints); } if (numPieces <= 0 || piece < 0 || piece >= numPieces) { return; } start = piece * this->NumberOfPoints / numPieces; next = (piece+1) * this->NumberOfPoints / numPieces; length = next - start; data = new float[length * 4]; // Seek to the first point in the file. this->File->seekg(start*4*sizeof(float), ios::beg); if (this->File->fail()) { cerr << "File operation failed: Seeking to " << start*4 << endl; delete [] data; return; } // Read the data. if ( ! this->File->read((char *)data, length*4*sizeof(float))) { vtkErrorMacro("Could not read points: " << start << " to " << next-1); delete [] data; return; } // Swap bytes if necessary. if (this->GetSwapBytes()) { vtkByteSwap::SwapVoidRange(data, length*4, sizeof(float)); } ptr = data; points = vtkPoints::New(); points->SetNumberOfPoints(length); array = vtkFloatArray::New(); array->SetName("Count"); verts = vtkCellArray::New(); // Each cell will have 1000 points. Leave a little extra space just in case. // We break up the cell this way so that the render will check for aborts // at a reasonable rate. verts->Allocate((int)((float)length * 1.002)); // Keep adding cells until we run out of points. ptIdx = 0; while (length > 0) { cellLength = 1000; if (cellLength > length) { cellLength = length; } length = length - cellLength; verts->InsertNextCell((int)cellLength); for (cellPtIdx = 0; cellPtIdx < cellLength; ++cellPtIdx) { points->SetPoint(ptIdx, ptr[0], ptr[1], ptr[2]); array->InsertNextValue(ptr[3]); verts->InsertCellPoint(ptIdx); ptr += 4; ++ptIdx; } } delete [] data; data = ptr = NULL; output->SetPoints(points); points->Delete(); points = NULL; output->SetVerts(verts); verts->Delete(); verts = NULL; output->GetPointData()->SetScalars(array); array->Delete(); array = NULL; } //---------------------------------------------------------------------------- void vtkParticleReader::SetDataByteOrderToBigEndian() { #ifndef VTK_WORDS_BIGENDIAN this->SwapBytesOn(); #else this->SwapBytesOff(); #endif } //---------------------------------------------------------------------------- void vtkParticleReader::SetDataByteOrderToLittleEndian() { #ifdef VTK_WORDS_BIGENDIAN this->SwapBytesOn(); #else this->SwapBytesOff(); #endif } void vtkParticleReader::SetDataByteOrder(int byteOrder) { if ( byteOrder == VTK_FILE_BYTE_ORDER_BIG_ENDIAN ) { this->SetDataByteOrderToBigEndian(); } else { this->SetDataByteOrderToLittleEndian(); } } //---------------------------------------------------------------------------- int vtkParticleReader::GetDataByteOrder() { #ifdef VTK_WORDS_BIGENDIAN if ( this->SwapBytes ) { return VTK_FILE_BYTE_ORDER_LITTLE_ENDIAN; } else { return VTK_FILE_BYTE_ORDER_BIG_ENDIAN; } #else if ( this->SwapBytes ) { return VTK_FILE_BYTE_ORDER_BIG_ENDIAN; } else { return VTK_FILE_BYTE_ORDER_LITTLE_ENDIAN; } #endif } //---------------------------------------------------------------------------- const char *vtkParticleReader::GetDataByteOrderAsString() { #ifdef VTK_WORDS_BIGENDIAN if ( this->SwapBytes ) { return "LittleEndian"; } else { return "BigEndian"; } #else if ( this->SwapBytes ) { return "BigEndian"; } else { return "LittleEndian"; } #endif } //---------------------------------------------------------------------------- void vtkParticleReader::PrintSelf(ostream& os, vtkIndent indent) { vtkPolyDataSource::PrintSelf(os,indent); // this->File, this->Colors need not be printed os << indent << "FileName: " << (this->FileName ? this->FileName : "(none)") << "\n"; os << indent << "Swap Bytes: " << (this->SwapBytes ? "On\n" : "Off\n"); os << indent << "NumberOfPoints: " << this->NumberOfPoints << "\n"; }
/*========================================================================= Program: Visualization Toolkit Module: vtkParticleReader.cxx Language: C++ Date: $Date$ Version: $Revision$ Thanks: Thanks to C. Charles Law who developed this class. Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen 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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. 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 AUTHORS 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 <stdio.h> #include <ctype.h> #include <string.h> #include "vtkByteSwap.h" #include "vtkParticleReader.h" #include "vtkFloatArray.h" #include "vtkCellArray.h" #include "vtkPoints.h" #include "vtkObjectFactory.h" // These are copied right from vtkImageReader. // I do not know what they do. #ifdef read #undef read #endif #ifdef close #undef close #endif //---------------------------------------------------------------------------- vtkParticleReader* vtkParticleReader::New() { // First try to create the object from the vtkObjectFactory vtkObject* ret = vtkObjectFactory::CreateInstance("vtkParticleReader"); if(ret) { return (vtkParticleReader*)ret; } // If the factory was unable to create the object, then create it here. return new vtkParticleReader; } //---------------------------------------------------------------------------- vtkParticleReader::vtkParticleReader() { this->FileName = NULL; this->File = NULL; #ifndef VTK_WORDS_BIGENDIAN this->SwapBytes = 1; #else this->SwapBytes = 0; #endif this->NumberOfPoints = 0; } //---------------------------------------------------------------------------- vtkParticleReader::~vtkParticleReader() { if (this->File) { this->File->close(); delete this->File; this->File = NULL; } if (this->FileName) { delete [] this->FileName; this->FileName = NULL; } } //---------------------------------------------------------------------------- void vtkParticleReader::OpenFile() { if (!this->FileName) { vtkErrorMacro(<<"FileName must be specified."); return; } // Close file from any previous image if (this->File) { this->File->close(); delete this->File; this->File = NULL; } // Open the new file vtkDebugMacro(<< "Initialize: opening file " << this->FileName); #ifdef _WIN32 this->File = new ifstream(this->FileName, ios::in | ios::binary); #else this->File = new ifstream(this->FileName, ios::in); #endif if (! this->File || this->File->fail()) { vtkErrorMacro(<< "Initialize: Could not open file " << this->FileName); return; } } //---------------------------------------------------------------------------- // This method returns the largest data that can be generated. void vtkParticleReader::ExecuteInformation() { vtkPolyData *output = this->GetOutput(); output->SetMaximumNumberOfPieces(-1); } //---------------------------------------------------------------------------- // This method returns the largest data that can be generated. void vtkParticleReader::Execute() { vtkPolyData *output = this->GetOutput(); vtkPoints *points; vtkFloatArray *array; vtkCellArray *verts; unsigned long fileLength, start, next, length, ptIdx, cellPtIdx; unsigned long cellLength; int piece, numPieces; float *data, *ptr; if (!this->FileName) { vtkErrorMacro(<<"FileName must be specified."); return; } this->OpenFile(); // Get the size of the header from the size of the image this->File->seekg(0,ios::end); if (this->File->fail()) { vtkErrorMacro("Could not seek to end of file."); return; } fileLength = (unsigned long)this->File->tellg(); this->NumberOfPoints = fileLength / (4 * sizeof(float)); piece = output->GetUpdatePiece(); numPieces = output->GetUpdateNumberOfPieces(); if ((unsigned long)numPieces > this->NumberOfPoints) { numPieces = (int)(this->NumberOfPoints); } if (numPieces <= 0 || piece < 0 || piece >= numPieces) { return; } start = piece * this->NumberOfPoints / numPieces; next = (piece+1) * this->NumberOfPoints / numPieces; length = next - start; data = new float[length * 4]; // Seek to the first point in the file. this->File->seekg(start*4*sizeof(float), ios::beg); if (this->File->fail()) { cerr << "File operation failed: Seeking to " << start*4 << endl; delete [] data; return; } // Read the data. if ( ! this->File->read((char *)data, length*4*sizeof(float))) { vtkErrorMacro("Could not read points: " << start << " to " << next-1); delete [] data; return; } // Swap bytes if necessary. if (this->GetSwapBytes()) { vtkByteSwap::SwapVoidRange(data, length*4, sizeof(float)); } ptr = data; points = vtkPoints::New(); points->SetNumberOfPoints(length); array = vtkFloatArray::New(); array->SetName("Count"); verts = vtkCellArray::New(); // Each cell will have 1000 points. Leave a little extra space just in case. // We break up the cell this way so that the render will check for aborts // at a reasonable rate. verts->Allocate((int)((float)length * 1.002)); // Keep adding cells until we run out of points. ptIdx = 0; while (length > 0) { cellLength = 1000; if (cellLength > length) { cellLength = length; } length = length - cellLength; verts->InsertNextCell((int)cellLength); for (cellPtIdx = 0; cellPtIdx < cellLength; ++cellPtIdx) { points->SetPoint(ptIdx, ptr[0], ptr[1], ptr[2]); array->InsertNextValue(ptr[3]); verts->InsertCellPoint(ptIdx); ptr += 4; ++ptIdx; } } delete [] data; data = ptr = NULL; output->SetPoints(points); points->Delete(); points = NULL; output->SetVerts(verts); verts->Delete(); verts = NULL; output->GetPointData()->SetScalars(array); array->Delete(); array = NULL; } //---------------------------------------------------------------------------- void vtkParticleReader::SetDataByteOrderToBigEndian() { #ifndef VTK_WORDS_BIGENDIAN this->SwapBytesOn(); #else this->SwapBytesOff(); #endif } //---------------------------------------------------------------------------- void vtkParticleReader::SetDataByteOrderToLittleEndian() { #ifdef VTK_WORDS_BIGENDIAN this->SwapBytesOn(); #else this->SwapBytesOff(); #endif } void vtkParticleReader::SetDataByteOrder(int byteOrder) { if ( byteOrder == VTK_FILE_BYTE_ORDER_BIG_ENDIAN ) { this->SetDataByteOrderToBigEndian(); } else { this->SetDataByteOrderToLittleEndian(); } } //---------------------------------------------------------------------------- int vtkParticleReader::GetDataByteOrder() { #ifdef VTK_WORDS_BIGENDIAN if ( this->SwapBytes ) { return VTK_FILE_BYTE_ORDER_LITTLE_ENDIAN; } else { return VTK_FILE_BYTE_ORDER_BIG_ENDIAN; } #else if ( this->SwapBytes ) { return VTK_FILE_BYTE_ORDER_BIG_ENDIAN; } else { return VTK_FILE_BYTE_ORDER_LITTLE_ENDIAN; } #endif } //---------------------------------------------------------------------------- const char *vtkParticleReader::GetDataByteOrderAsString() { #ifdef VTK_WORDS_BIGENDIAN if ( this->SwapBytes ) { return "LittleEndian"; } else { return "BigEndian"; } #else if ( this->SwapBytes ) { return "BigEndian"; } else { return "LittleEndian"; } #endif } //---------------------------------------------------------------------------- void vtkParticleReader::PrintSelf(ostream& os, vtkIndent indent) { vtkPolyDataSource::PrintSelf(os,indent); // this->File, this->Colors need not be printed os << indent << "FileName: " << (this->FileName ? this->FileName : "(none)") << "\n"; os << indent << "Swap Bytes: " << (this->SwapBytes ? "On\n" : "Off\n"); os << indent << "NumberOfPoints: " << this->NumberOfPoints << "\n"; }
Fix bytswap again.
Fix bytswap again.
C++
bsd-3-clause
sgh/vtk,collects/VTK,sgh/vtk,candy7393/VTK,gram526/VTK,keithroe/vtkoptix,jeffbaumes/jeffbaumes-vtk,spthaolt/VTK,sgh/vtk,collects/VTK,keithroe/vtkoptix,sankhesh/VTK,gram526/VTK,biddisco/VTK,SimVascular/VTK,cjh1/VTK,sgh/vtk,keithroe/vtkoptix,jmerkow/VTK,naucoin/VTKSlicerWidgets,Wuteyan/VTK,daviddoria/PointGraphsPhase1,gram526/VTK,sankhesh/VTK,gram526/VTK,berendkleinhaneveld/VTK,naucoin/VTKSlicerWidgets,msmolens/VTK,gram526/VTK,arnaudgelas/VTK,candy7393/VTK,aashish24/VTK-old,ashray/VTK-EVM,johnkit/vtk-dev,sankhesh/VTK,demarle/VTK,sumedhasingla/VTK,sumedhasingla/VTK,demarle/VTK,collects/VTK,aashish24/VTK-old,biddisco/VTK,sumedhasingla/VTK,ashray/VTK-EVM,sgh/vtk,daviddoria/PointGraphsPhase1,daviddoria/PointGraphsPhase1,daviddoria/PointGraphsPhase1,mspark93/VTK,msmolens/VTK,jmerkow/VTK,hendradarwin/VTK,naucoin/VTKSlicerWidgets,ashray/VTK-EVM,hendradarwin/VTK,spthaolt/VTK,collects/VTK,jeffbaumes/jeffbaumes-vtk,biddisco/VTK,demarle/VTK,jmerkow/VTK,cjh1/VTK,sgh/vtk,sankhesh/VTK,arnaudgelas/VTK,ashray/VTK-EVM,sankhesh/VTK,biddisco/VTK,ashray/VTK-EVM,sankhesh/VTK,cjh1/VTK,cjh1/VTK,jmerkow/VTK,msmolens/VTK,candy7393/VTK,spthaolt/VTK,spthaolt/VTK,msmolens/VTK,SimVascular/VTK,spthaolt/VTK,ashray/VTK-EVM,demarle/VTK,hendradarwin/VTK,naucoin/VTKSlicerWidgets,cjh1/VTK,spthaolt/VTK,biddisco/VTK,sumedhasingla/VTK,SimVascular/VTK,mspark93/VTK,johnkit/vtk-dev,demarle/VTK,SimVascular/VTK,mspark93/VTK,sankhesh/VTK,cjh1/VTK,daviddoria/PointGraphsPhase1,Wuteyan/VTK,sumedhasingla/VTK,Wuteyan/VTK,demarle/VTK,mspark93/VTK,berendkleinhaneveld/VTK,mspark93/VTK,jeffbaumes/jeffbaumes-vtk,berendkleinhaneveld/VTK,keithroe/vtkoptix,jmerkow/VTK,naucoin/VTKSlicerWidgets,berendkleinhaneveld/VTK,jeffbaumes/jeffbaumes-vtk,johnkit/vtk-dev,demarle/VTK,candy7393/VTK,Wuteyan/VTK,candy7393/VTK,mspark93/VTK,biddisco/VTK,ashray/VTK-EVM,keithroe/vtkoptix,mspark93/VTK,hendradarwin/VTK,gram526/VTK,Wuteyan/VTK,msmolens/VTK,sankhesh/VTK,gram526/VTK,berendkleinhaneveld/VTK,SimVascular/VTK,aashish24/VTK-old,johnkit/vtk-dev,sumedhasingla/VTK,berendkleinhaneveld/VTK,candy7393/VTK,collects/VTK,ashray/VTK-EVM,arnaudgelas/VTK,demarle/VTK,arnaudgelas/VTK,keithroe/vtkoptix,keithroe/vtkoptix,collects/VTK,candy7393/VTK,msmolens/VTK,jmerkow/VTK,arnaudgelas/VTK,jmerkow/VTK,SimVascular/VTK,hendradarwin/VTK,msmolens/VTK,biddisco/VTK,SimVascular/VTK,candy7393/VTK,gram526/VTK,mspark93/VTK,SimVascular/VTK,msmolens/VTK,hendradarwin/VTK,keithroe/vtkoptix,jeffbaumes/jeffbaumes-vtk,daviddoria/PointGraphsPhase1,sumedhasingla/VTK,johnkit/vtk-dev,sumedhasingla/VTK,johnkit/vtk-dev,hendradarwin/VTK,spthaolt/VTK,aashish24/VTK-old,arnaudgelas/VTK,naucoin/VTKSlicerWidgets,jeffbaumes/jeffbaumes-vtk,aashish24/VTK-old,jmerkow/VTK,berendkleinhaneveld/VTK,aashish24/VTK-old,johnkit/vtk-dev,Wuteyan/VTK,Wuteyan/VTK
71396bb948f74a61619d05325280fa3830f5c13f
examples/cpp/encode/file/main.cpp
examples/cpp/encode/file/main.cpp
/* example_cpp_encode_file - Simple FLAC file encoder using libFLAC * Copyright (C) 2007,2008,2009 Josh Coalson * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* * This example shows how to use libFLAC++ to encode a WAVE file to a FLAC * file. It only supports 16-bit stereo files in canonical WAVE format. * * Complete API documentation can be found at: * http://flac.sourceforge.net/api/ */ #if HAVE_CONFIG_H # include <config.h> #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include "FLAC++/metadata.h" #include "FLAC++/encoder.h" class OurEncoder: public FLAC::Encoder::File { public: OurEncoder(): FLAC::Encoder::File() { } protected: virtual void progress_callback(FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate); }; #define READSIZE 1024 static unsigned total_samples = 0; /* can use a 32-bit number due to WAVE size limitations */ static FLAC__byte buffer[READSIZE/*samples*/ * 2/*bytes_per_sample*/ * 2/*channels*/]; /* we read the WAVE data into here */ static FLAC__int32 pcm[READSIZE/*samples*/ * 2/*channels*/]; static FLAC__int32 *pcm_[2] = { pcm, pcm+READSIZE }; int main(int argc, char *argv[]) { bool ok = true; OurEncoder encoder; FLAC__StreamEncoderInitStatus init_status; FLAC__StreamMetadata *metadata[2]; FLAC__StreamMetadata_VorbisComment_Entry entry; FILE *fin; unsigned sample_rate = 0; unsigned channels = 0; unsigned bps = 0; if(argc != 3) { fprintf(stderr, "usage: %s infile.wav outfile.flac\n", argv[0]); return 1; } if((fin = fopen(argv[1], "rb")) == NULL) { fprintf(stderr, "ERROR: opening %s for output\n", argv[1]); return 1; } /* read wav header and validate it */ if( fread(buffer, 1, 44, fin) != 44 || memcmp(buffer, "RIFF", 4) || memcmp(buffer+8, "WAVEfmt \020\000\000\000\001\000\002\000", 16) || memcmp(buffer+32, "\004\000\020\000data", 8) ) { fprintf(stderr, "ERROR: invalid/unsupported WAVE file, only 16bps stereo WAVE in canonical form allowed\n"); fclose(fin); return 1; } sample_rate = ((((((unsigned)buffer[27] << 8) | buffer[26]) << 8) | buffer[25]) << 8) | buffer[24]; channels = 2; bps = 16; total_samples = (((((((unsigned)buffer[43] << 8) | buffer[42]) << 8) | buffer[41]) << 8) | buffer[40]) / 4; /* check the encoder */ if(!encoder) { fprintf(stderr, "ERROR: allocating encoder\n"); fclose(fin); return 1; } ok &= encoder.set_verify(true); ok &= encoder.set_compression_level(5); ok &= encoder.set_channels(channels); ok &= encoder.set_bits_per_sample(bps); ok &= encoder.set_sample_rate(sample_rate); ok &= encoder.set_total_samples_estimate(total_samples); /* now add some metadata; we'll add some tags and a padding block */ if(ok) { if( (metadata[0] = FLAC__metadata_object_new(FLAC__METADATA_TYPE_VORBIS_COMMENT)) == NULL || (metadata[1] = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING)) == NULL || /* there are many tag (vorbiscomment) functions but these are convenient for this particular use: */ !FLAC__metadata_object_vorbiscomment_entry_from_name_value_pair(&entry, "ARTIST", "Some Artist") || !FLAC__metadata_object_vorbiscomment_append_comment(metadata[0], entry, /*copy=*/false) || /* copy=false: let metadata object take control of entry's allocated string */ !FLAC__metadata_object_vorbiscomment_entry_from_name_value_pair(&entry, "YEAR", "1984") || !FLAC__metadata_object_vorbiscomment_append_comment(metadata[0], entry, /*copy=*/false) ) { fprintf(stderr, "ERROR: out of memory or tag error\n"); ok = false; } metadata[1]->length = 1234; /* set the padding length */ ok = encoder.set_metadata(metadata, 2); } /* initialize encoder */ if(ok) { init_status = encoder.init(argv[2]); if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) { fprintf(stderr, "ERROR: initializing encoder: %s\n", FLAC__StreamEncoderInitStatusString[init_status]); ok = false; } } /* read blocks of samples from WAVE file and feed to encoder */ if(ok) { size_t left = (size_t)total_samples; while(ok && left) { size_t need = (left>READSIZE? (size_t)READSIZE : (size_t)left); if(fread(buffer, channels*(bps/8), need, fin) != need) { fprintf(stderr, "ERROR: reading from WAVE file\n"); ok = false; } else { /* convert the packed little-endian 16-bit PCM samples from WAVE into an interleaved FLAC__int32 buffer for libFLAC */ size_t i; for(i = 0; i < need*channels; i++) { /* inefficient but simple and works on big- or little-endian machines */ pcm[i] = (FLAC__int32)(((FLAC__int16)(FLAC__int8)buffer[2*i+1] << 8) | (FLAC__int16)buffer[2*i]); } /* feed samples to encoder */ ok = encoder.process_interleaved(pcm, need); } left -= need; } } ok &= encoder.finish(); fprintf(stderr, "encoding: %s\n", ok? "succeeded" : "FAILED"); fprintf(stderr, " state: %s\n", encoder.get_state().resolved_as_cstring(encoder)); /* now that encoding is finished, the metadata can be freed */ FLAC__metadata_object_delete(metadata[0]); FLAC__metadata_object_delete(metadata[1]); fclose(fin); return 0; } void OurEncoder::progress_callback(FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate) { #ifdef _MSC_VER fprintf(stderr, "wrote %I64u bytes, %I64u/%u samples, %u/%u frames\n", bytes_written, samples_written, total_samples, frames_written, total_frames_estimate); #else fprintf(stderr, "wrote %llu bytes, %llu/%u samples, %u/%u frames\n", bytes_written, samples_written, total_samples, frames_written, total_frames_estimate); #endif }
/* example_cpp_encode_file - Simple FLAC file encoder using libFLAC * Copyright (C) 2007,2008,2009 Josh Coalson * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* * This example shows how to use libFLAC++ to encode a WAVE file to a FLAC * file. It only supports 16-bit stereo files in canonical WAVE format. * * Complete API documentation can be found at: * http://flac.sourceforge.net/api/ */ #if HAVE_CONFIG_H # include <config.h> #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include "FLAC++/metadata.h" #include "FLAC++/encoder.h" #include <cstring> class OurEncoder: public FLAC::Encoder::File { public: OurEncoder(): FLAC::Encoder::File() { } protected: virtual void progress_callback(FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate); }; #define READSIZE 1024 static unsigned total_samples = 0; /* can use a 32-bit number due to WAVE size limitations */ static FLAC__byte buffer[READSIZE/*samples*/ * 2/*bytes_per_sample*/ * 2/*channels*/]; /* we read the WAVE data into here */ static FLAC__int32 pcm[READSIZE/*samples*/ * 2/*channels*/]; static FLAC__int32 *pcm_[2] = { pcm, pcm+READSIZE }; int main(int argc, char *argv[]) { bool ok = true; OurEncoder encoder; FLAC__StreamEncoderInitStatus init_status; FLAC__StreamMetadata *metadata[2]; FLAC__StreamMetadata_VorbisComment_Entry entry; FILE *fin; unsigned sample_rate = 0; unsigned channels = 0; unsigned bps = 0; if(argc != 3) { fprintf(stderr, "usage: %s infile.wav outfile.flac\n", argv[0]); return 1; } if((fin = fopen(argv[1], "rb")) == NULL) { fprintf(stderr, "ERROR: opening %s for output\n", argv[1]); return 1; } /* read wav header and validate it */ if( fread(buffer, 1, 44, fin) != 44 || memcmp(buffer, "RIFF", 4) || memcmp(buffer+8, "WAVEfmt \020\000\000\000\001\000\002\000", 16) || memcmp(buffer+32, "\004\000\020\000data", 8) ) { fprintf(stderr, "ERROR: invalid/unsupported WAVE file, only 16bps stereo WAVE in canonical form allowed\n"); fclose(fin); return 1; } sample_rate = ((((((unsigned)buffer[27] << 8) | buffer[26]) << 8) | buffer[25]) << 8) | buffer[24]; channels = 2; bps = 16; total_samples = (((((((unsigned)buffer[43] << 8) | buffer[42]) << 8) | buffer[41]) << 8) | buffer[40]) / 4; /* check the encoder */ if(!encoder) { fprintf(stderr, "ERROR: allocating encoder\n"); fclose(fin); return 1; } ok &= encoder.set_verify(true); ok &= encoder.set_compression_level(5); ok &= encoder.set_channels(channels); ok &= encoder.set_bits_per_sample(bps); ok &= encoder.set_sample_rate(sample_rate); ok &= encoder.set_total_samples_estimate(total_samples); /* now add some metadata; we'll add some tags and a padding block */ if(ok) { if( (metadata[0] = FLAC__metadata_object_new(FLAC__METADATA_TYPE_VORBIS_COMMENT)) == NULL || (metadata[1] = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING)) == NULL || /* there are many tag (vorbiscomment) functions but these are convenient for this particular use: */ !FLAC__metadata_object_vorbiscomment_entry_from_name_value_pair(&entry, "ARTIST", "Some Artist") || !FLAC__metadata_object_vorbiscomment_append_comment(metadata[0], entry, /*copy=*/false) || /* copy=false: let metadata object take control of entry's allocated string */ !FLAC__metadata_object_vorbiscomment_entry_from_name_value_pair(&entry, "YEAR", "1984") || !FLAC__metadata_object_vorbiscomment_append_comment(metadata[0], entry, /*copy=*/false) ) { fprintf(stderr, "ERROR: out of memory or tag error\n"); ok = false; } metadata[1]->length = 1234; /* set the padding length */ ok = encoder.set_metadata(metadata, 2); } /* initialize encoder */ if(ok) { init_status = encoder.init(argv[2]); if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) { fprintf(stderr, "ERROR: initializing encoder: %s\n", FLAC__StreamEncoderInitStatusString[init_status]); ok = false; } } /* read blocks of samples from WAVE file and feed to encoder */ if(ok) { size_t left = (size_t)total_samples; while(ok && left) { size_t need = (left>READSIZE? (size_t)READSIZE : (size_t)left); if(fread(buffer, channels*(bps/8), need, fin) != need) { fprintf(stderr, "ERROR: reading from WAVE file\n"); ok = false; } else { /* convert the packed little-endian 16-bit PCM samples from WAVE into an interleaved FLAC__int32 buffer for libFLAC */ size_t i; for(i = 0; i < need*channels; i++) { /* inefficient but simple and works on big- or little-endian machines */ pcm[i] = (FLAC__int32)(((FLAC__int16)(FLAC__int8)buffer[2*i+1] << 8) | (FLAC__int16)buffer[2*i]); } /* feed samples to encoder */ ok = encoder.process_interleaved(pcm, need); } left -= need; } } ok &= encoder.finish(); fprintf(stderr, "encoding: %s\n", ok? "succeeded" : "FAILED"); fprintf(stderr, " state: %s\n", encoder.get_state().resolved_as_cstring(encoder)); /* now that encoding is finished, the metadata can be freed */ FLAC__metadata_object_delete(metadata[0]); FLAC__metadata_object_delete(metadata[1]); fclose(fin); return 0; } void OurEncoder::progress_callback(FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate) { #ifdef _MSC_VER fprintf(stderr, "wrote %I64u bytes, %I64u/%u samples, %u/%u frames\n", bytes_written, samples_written, total_samples, frames_written, total_frames_estimate); #else fprintf(stderr, "wrote %llu bytes, %llu/%u samples, %u/%u frames\n", bytes_written, samples_written, total_samples, frames_written, total_frames_estimate); #endif }
Add missing <cstring> include.
Add missing <cstring> include. Patch from Cyril Brulebois <[email protected]> via Debian. Closes Debian bug #455304.
C++
bsd-3-clause
LordJZ/libflac,waitman/flac,waitman/flac,Distrotech/flac,fredericgermain/flac,LordJZ/libflac,fredericgermain/flac,Distrotech/flac,LordJZ/libflac,kode54/flac,waitman/flac,fredericgermain/flac,fredericgermain/flac,Distrotech/flac,waitman/flac,kode54/flac,waitman/flac,LordJZ/libflac,kode54/flac,Distrotech/flac,kode54/flac
5b7a7c32f6867555e667ad2b3558b99df8358879
net2/mac_cash.hpp
net2/mac_cash.hpp
#pragma once //=========================================================================// /*! @file @brief MAC Cash @n Copyright 2017 Kunihito Hiramatsu @author 平松邦仁 ([email protected]) */ //=========================================================================// #include "common/ip_adrs.hpp" namespace net { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief ARP キャッシュ */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// struct arp_info { ip_adrs ipa; uint8_t mac[6]; uint16_t time; }; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief mac_cash クラス @param[in] SIZE キャッシュの最大数 */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template<uint32_t SIZE> class mac_cash { arp_info info_[SIZE]; uint32_t pos_; public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// mac_cash() : pos_(0) { } //-----------------------------------------------------------------// /*! @brief 格納可能な最大サイズを返す(終端の数を除外) @return 格納可能な最大サイズ */ //-----------------------------------------------------------------// uint32_t capacity() const noexcept { return SIZE; } //-----------------------------------------------------------------// /*! @brief 現在のサイズを返す @return 現在のサイズ */ //-----------------------------------------------------------------// uint32_t size() const noexcept { return pos_; } //-----------------------------------------------------------------// /*! @brief インデックスが有効か検査 @param[in] idx インデックス @return 有効なら「true」 */ //-----------------------------------------------------------------// bool is_valid(uint32_t idx) const { return idx != SIZE; } //-----------------------------------------------------------------// /*! @brief キャッシュをクリア */ //-----------------------------------------------------------------// void clear() noexcept { pos_ = 0; } //-----------------------------------------------------------------// /*! @brief 検索 @param[in] ipa 検索アドレス @return 無ければ「SIZE」 */ //-----------------------------------------------------------------// uint32_t lookup(const ip_adrs& ipa) noexcept { for(uint32_t i = 0; i < pos_; ++i) { if(info_[i].ipa == ipa) { return i; } } return SIZE; } //-----------------------------------------------------------------// /*! @brief 登録 @n ・「255.255.255.255」、「0.0.0.0」の場合は登録しない @n ・「x.x.x.0」、「x.x.x.255」の場合も登録しない @param[in] ipa 登録アドレス @param[in] mac MAC アドレス @return 登録できたら「true」 */ //-----------------------------------------------------------------// bool insert(const ip_adrs& ipa, const uint8_t* mac) noexcept { if(ipa[3] == 0 || ipa[3] == 255) { // 末尾「0」ゲートウェイ、「255」ブロードキャストは無視 return false; } if(tools::check_brodcast_mac(mac)) { // MAC のブロードキャスト確認 return false; } if(tools::check_allzero_mac(mac)) { // MAC の任意アドレス確認 return false; } uint32_t n = lookup(ipa); if(n < SIZE) { // 登録済みアドレス std::memcpy(info_[n].mac, mac, 6); // MAC アドレスを更新 info_[n].time = 0; // タイムスタンプ、リセット return true; } else { if(pos_ < SIZE) { info_[pos_].ipa = ipa; std::memcpy(info_[pos_].mac, mac, 6); info_[pos_].time = 0; // utils::format("Insert ARP cash (%d): %s -> %s\n") // % pos_ // % tools::ip_str(ipa.get()) // % tools::mac_str(mac); ++pos_; return true; } else { // バッファが満杯の場合の処理 diet(); return insert(ipa, mac); } } } //-----------------------------------------------------------------// /*! @brief 削除 @param[in] ipa 検索アドレス @return 削除した場合「true」 */ //-----------------------------------------------------------------// bool erase(const ip_adrs& ipa) noexcept { auto n = lookup(ipa); if(n < SIZE) { if(n != (pos_ - 1)) { info_[n] = info_[pos_ - 1]; } --pos_; return true; } return false; } //-----------------------------------------------------------------// /*! @brief リセット @param[in] idx 参照ポイント @return リセット出来た場合「true」 */ //-----------------------------------------------------------------// bool reset(uint32_t idx) noexcept { if(idx < pos_) { info_[idx].time = 0; return true; } else { return false; } } //-----------------------------------------------------------------// /*! @brief ダイエット @n ※利用頻度が最も低い候補を消去する */ //-----------------------------------------------------------------// void diet() noexcept { if(pos_ < SIZE) { return; } uint32_t n = SIZE; uint16_t t = 0; for(uint32_t i = 0; i < pos_; ++i) { if(info_[i].time > t) { t = info_[i].time; n = i; } } if(n < SIZE) { erase(n); } } //-----------------------------------------------------------------// /*! @brief [] オペレーター @param[in] idx 参照インデックス @return 参照 */ //-----------------------------------------------------------------// const arp_info& operator[] (uint32_t idx) const noexcept { if(idx >= pos_) { static arp_info info; std::memset(info.mac, 0x00, 6); info.time = 0; return info; } return info_[idx]; } //-----------------------------------------------------------------// /*! @brief アップデート @n ※登録済みのタイムカウントを進める */ //-----------------------------------------------------------------// void update() noexcept { for(uint32_t i = 0; i < pos_; ++i) { if(info_[i].time < 0xffff) { ++info_[i].time; } } } //-----------------------------------------------------------------// /*! @brief リスト表示 */ //-----------------------------------------------------------------// void list() const noexcept { for(uint32_t i = 0; i < pos_; ++i) { utils::format("ARP Cash (%d): %s -> %s (%d)\n") % i % info_[i].ipa.c_str() % tools::mac_str(info_[i].mac) % static_cast<uint32_t>(info_[i].time); } } }; }
#pragma once //=========================================================================// /*! @file @brief MAC Cash @n Copyright 2017 Kunihito Hiramatsu @author 平松邦仁 ([email protected]) */ //=========================================================================// #include "common/ip_adrs.hpp" namespace net { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief ARP キャッシュ */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// struct arp_info { ip_adrs ipa; uint8_t mac[6]; uint16_t time; }; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief mac_cash クラス @param[in] SIZE キャッシュの最大数 */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template<uint32_t SIZE> class mac_cash { arp_info info_[SIZE]; uint32_t pos_; public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// mac_cash() : pos_(0) { } //-----------------------------------------------------------------// /*! @brief 格納可能な最大サイズを返す(終端の数を除外) @return 格納可能な最大サイズ */ //-----------------------------------------------------------------// uint32_t capacity() const noexcept { return SIZE; } //-----------------------------------------------------------------// /*! @brief 現在のサイズを返す @return 現在のサイズ */ //-----------------------------------------------------------------// uint32_t size() const noexcept { return pos_; } //-----------------------------------------------------------------// /*! @brief インデックスが有効か検査 @param[in] idx インデックス @return 有効なら「true」 */ //-----------------------------------------------------------------// bool is_valid(uint32_t idx) const { return idx != SIZE; } //-----------------------------------------------------------------// /*! @brief キャッシュをクリア */ //-----------------------------------------------------------------// void clear() noexcept { pos_ = 0; } //-----------------------------------------------------------------// /*! @brief 検索 @param[in] ipa 検索アドレス @return 無ければ「SIZE」 */ //-----------------------------------------------------------------// uint32_t lookup(const ip_adrs& ipa) noexcept { for(uint32_t i = 0; i < pos_; ++i) { if(info_[i].ipa == ipa) { return i; } } return SIZE; } //-----------------------------------------------------------------// /*! @brief 登録 @n ・「255.255.255.255」、「0.0.0.0」の場合は登録しない @n ・「x.x.x.0」、「x.x.x.255」の場合も登録しない @param[in] ipa 登録アドレス @param[in] mac MAC アドレス @return 登録できたら「true」 */ //-----------------------------------------------------------------// bool insert(const ip_adrs& ipa, const uint8_t* mac) noexcept { if(ipa[3] == 0 || ipa[3] == 255) { // 末尾「0」ゲートウェイ、「255」ブロードキャストは無視 return false; } if(tools::check_brodcast_mac(mac)) { // MAC のブロードキャスト確認 return false; } if(tools::check_allzero_mac(mac)) { // MAC の任意アドレス確認 return false; } uint32_t n = lookup(ipa); if(n < SIZE) { // 登録済みアドレス std::memcpy(info_[n].mac, mac, 6); // MAC アドレスを更新 info_[n].time = 0; // タイムスタンプ、リセット return true; } else { if(pos_ < SIZE) { info_[pos_].ipa = ipa; std::memcpy(info_[pos_].mac, mac, 6); info_[pos_].time = 0; // utils::format("Insert ARP cash (%d): %s -> %s\n") // % pos_ // % tools::ip_str(ipa.get()) // % tools::mac_str(mac); ++pos_; return true; } else { // バッファが満杯の場合の処理 diet(); return insert(ipa, mac); } } } //-----------------------------------------------------------------// /*! @brief 削除 @n ※終端を、空いた場所に移動して、サイズを1つ減らす @param[in] ipa 検索アドレス @return 削除した場合「true」 */ //-----------------------------------------------------------------// bool erase(const ip_adrs& ipa) noexcept { auto n = lookup(ipa); if(n < SIZE) { if(n != (pos_ - 1)) { info_[n] = info_[pos_ - 1]; } --pos_; return true; } return false; } //-----------------------------------------------------------------// /*! @brief リセット @param[in] idx 参照ポイント @return リセット出来た場合「true」 */ //-----------------------------------------------------------------// bool reset(uint32_t idx) noexcept { if(idx < pos_) { info_[idx].time = 0; return true; } else { return false; } } //-----------------------------------------------------------------// /*! @brief ダイエット @n ※利用頻度が最も低い候補を消去する */ //-----------------------------------------------------------------// void diet() noexcept { if(pos_ < SIZE) { return; } uint32_t n = SIZE; uint16_t t = 0; for(uint32_t i = 0; i < pos_; ++i) { if(info_[i].time > t) { t = info_[i].time; n = i; } } if(n < SIZE) { erase(n); } } //-----------------------------------------------------------------// /*! @brief [] オペレーター @param[in] idx 参照インデックス @return 参照 */ //-----------------------------------------------------------------// const arp_info& operator[] (uint32_t idx) const noexcept { if(idx >= pos_) { static arp_info info; std::memset(info.mac, 0x00, 6); info.time = 0; return info; } return info_[idx]; } //-----------------------------------------------------------------// /*! @brief アップデート @n ※登録済みのタイムカウントを進める */ //-----------------------------------------------------------------// void update() noexcept { for(uint32_t i = 0; i < pos_; ++i) { if(info_[i].time < 0xffff) { ++info_[i].time; } } } //-----------------------------------------------------------------// /*! @brief リスト表示 */ //-----------------------------------------------------------------// void list() const noexcept { for(uint32_t i = 0; i < pos_; ++i) { utils::format("ARP Cash (%d): %s -> %s (%d)\n") % i % info_[i].ipa.c_str() % tools::mac_str(info_[i].mac) % static_cast<uint32_t>(info_[i].time); } } }; }
update cash manage
update cash manage
C++
bsd-3-clause
hirakuni45/RX,hirakuni45/RX,hirakuni45/RX,hirakuni45/RX
eda7148af25e8e106e8983fb37952263dcae5275
src/mem/packet.cc
src/mem/packet.cc
/* * Copyright (c) 2006 The Regents of The University of Michigan * 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 holders 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. * * Authors: Ali Saidi * Steve Reinhardt */ /** * @file * Definition of the Packet Class, a packet is a transaction occuring * between a single level of the memory heirarchy (ie L1->L2). */ #include <iostream> #include "base/misc.hh" #include "base/trace.hh" #include "mem/packet.hh" static const std::string ReadReqString("ReadReq"); static const std::string WriteReqString("WriteReq"); static const std::string WriteReqNoAckString("WriteReqNoAck|Writeback"); static const std::string ReadRespString("ReadResp"); static const std::string WriteRespString("WriteResp"); static const std::string SoftPFReqString("SoftPFReq"); static const std::string SoftPFRespString("SoftPFResp"); static const std::string HardPFReqString("HardPFReq"); static const std::string HardPFRespString("HardPFResp"); static const std::string InvalidateReqString("InvalidateReq"); static const std::string WriteInvalidateReqString("WriteInvalidateReq"); static const std::string WriteInvalidateRespString("WriteInvalidateResp"); static const std::string UpgradeReqString("UpgradeReq"); static const std::string ReadExReqString("ReadExReq"); static const std::string ReadExRespString("ReadExResp"); static const std::string OtherCmdString("<other>"); const std::string & Packet::cmdString() const { switch (cmd) { case ReadReq: return ReadReqString; case WriteReq: return WriteReqString; case WriteReqNoAck: return WriteReqNoAckString; case ReadResp: return ReadRespString; case WriteResp: return WriteRespString; case SoftPFReq: return SoftPFReqString; case SoftPFResp: return SoftPFRespString; case HardPFReq: return HardPFReqString; case HardPFResp: return HardPFRespString; case InvalidateReq: return InvalidateReqString; case WriteInvalidateReq:return WriteInvalidateReqString; case WriteInvalidateResp:return WriteInvalidateRespString; case UpgradeReq: return UpgradeReqString; case ReadExReq: return ReadExReqString; case ReadExResp: return ReadExRespString; default: return OtherCmdString; } } const std::string & Packet::cmdIdxToString(Packet::Command idx) { switch (idx) { case ReadReq: return ReadReqString; case WriteReq: return WriteReqString; case WriteReqNoAck: return WriteReqNoAckString; case ReadResp: return ReadRespString; case WriteResp: return WriteRespString; case SoftPFReq: return SoftPFReqString; case SoftPFResp: return SoftPFRespString; case HardPFReq: return HardPFReqString; case HardPFResp: return HardPFRespString; case InvalidateReq: return InvalidateReqString; case WriteInvalidateReq:return WriteInvalidateReqString; case WriteInvalidateResp:return WriteInvalidateRespString; case UpgradeReq: return UpgradeReqString; case ReadExReq: return ReadExReqString; case ReadExResp: return ReadExRespString; default: return OtherCmdString; } } /** delete the data pointed to in the data pointer. Ok to call to matter how * data was allocted. */ void Packet::deleteData() { assert(staticData || dynamicData); if (staticData) return; if (arrayData) delete [] data; else delete data; } /** If there isn't data in the packet, allocate some. */ void Packet::allocate() { if (data) return; assert(!staticData); dynamicData = true; arrayData = true; data = new uint8_t[getSize()]; } /** Do the packet modify the same addresses. */ bool Packet::intersect(PacketPtr p) { Addr s1 = getAddr(); Addr e1 = getAddr() + getSize() - 1; Addr s2 = p->getAddr(); Addr e2 = p->getAddr() + p->getSize() - 1; return !(s1 > e2 || e1 < s2); } bool fixPacket(PacketPtr func, PacketPtr timing) { Addr funcStart = func->getAddr(); Addr funcEnd = func->getAddr() + func->getSize() - 1; Addr timingStart = timing->getAddr(); Addr timingEnd = timing->getAddr() + timing->getSize() - 1; assert(!(funcStart > timingEnd || timingStart > funcEnd)); if (DTRACE(FunctionalAccess)) { DebugOut() << func; DebugOut() << timing; } // this packet can't solve our problem, continue on if (!timing->hasData()) return true; if (func->isRead()) { if (funcStart >= timingStart && funcEnd <= timingEnd) { func->allocate(); memcpy(func->getPtr<uint8_t>(), timing->getPtr<uint8_t>() + funcStart - timingStart, func->getSize()); func->result = Packet::Success; return false; } else { // In this case the timing packet only partially satisfies the // requset, so we would need more information to make this work. // Like bytes valid in the packet or something, so the request could // continue and get this bit of possibly newer data along with the // older data not written to yet. panic("Timing packet only partially satisfies the functional" "request. Now what?"); } } else if (func->isWrite()) { if (funcStart >= timingStart) { memcpy(timing->getPtr<uint8_t>() + (funcStart - timingStart), func->getPtr<uint8_t>(), funcStart - std::min(funcEnd, timingEnd)); } else { // timingStart > funcStart memcpy(timing->getPtr<uint8_t>(), func->getPtr<uint8_t>() + (timingStart - funcStart), timingStart - std::min(funcEnd, timingEnd)); } // we always want to keep going with a write return true; } else panic("Don't know how to handle command type %#x\n", func->cmdToIndex()); } std::ostream & operator<<(std::ostream &o, const Packet &p) { o << "[0x"; o.setf(std::ios_base::hex, std::ios_base::showbase); o << p.getAddr(); o.unsetf(std::ios_base::hex| std::ios_base::showbase); o << ":"; o.setf(std::ios_base::hex, std::ios_base::showbase); o << p.getAddr() + p.getSize() - 1 << "] "; o.unsetf(std::ios_base::hex| std::ios_base::showbase); if (p.result == Packet::Success) o << "Successful "; if (p.result == Packet::BadAddress) o << "BadAddress "; if (p.result == Packet::Nacked) o << "Nacked "; if (p.result == Packet::Unknown) o << "Inflight "; if (p.isRead()) o << "Read "; if (p.isWrite()) o << "Read "; if (p.isInvalidate()) o << "Read "; if (p.isRequest()) o << "Request "; if (p.isResponse()) o << "Response "; if (p.hasData()) o << "w/Data "; o << std::endl; return o; }
/* * Copyright (c) 2006 The Regents of The University of Michigan * 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 holders 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. * * Authors: Ali Saidi * Steve Reinhardt */ /** * @file * Definition of the Packet Class, a packet is a transaction occuring * between a single level of the memory heirarchy (ie L1->L2). */ #include <iostream> #include "base/misc.hh" #include "base/trace.hh" #include "mem/packet.hh" static const std::string ReadReqString("ReadReq"); static const std::string WriteReqString("WriteReq"); static const std::string WriteReqNoAckString("WriteReqNoAck|Writeback"); static const std::string ReadRespString("ReadResp"); static const std::string WriteRespString("WriteResp"); static const std::string SoftPFReqString("SoftPFReq"); static const std::string SoftPFRespString("SoftPFResp"); static const std::string HardPFReqString("HardPFReq"); static const std::string HardPFRespString("HardPFResp"); static const std::string InvalidateReqString("InvalidateReq"); static const std::string WriteInvalidateReqString("WriteInvalidateReq"); static const std::string WriteInvalidateRespString("WriteInvalidateResp"); static const std::string UpgradeReqString("UpgradeReq"); static const std::string ReadExReqString("ReadExReq"); static const std::string ReadExRespString("ReadExResp"); static const std::string OtherCmdString("<other>"); const std::string & Packet::cmdString() const { switch (cmd) { case ReadReq: return ReadReqString; case WriteReq: return WriteReqString; case WriteReqNoAck: return WriteReqNoAckString; case ReadResp: return ReadRespString; case WriteResp: return WriteRespString; case SoftPFReq: return SoftPFReqString; case SoftPFResp: return SoftPFRespString; case HardPFReq: return HardPFReqString; case HardPFResp: return HardPFRespString; case InvalidateReq: return InvalidateReqString; case WriteInvalidateReq:return WriteInvalidateReqString; case WriteInvalidateResp:return WriteInvalidateRespString; case UpgradeReq: return UpgradeReqString; case ReadExReq: return ReadExReqString; case ReadExResp: return ReadExRespString; default: return OtherCmdString; } } const std::string & Packet::cmdIdxToString(Packet::Command idx) { switch (idx) { case ReadReq: return ReadReqString; case WriteReq: return WriteReqString; case WriteReqNoAck: return WriteReqNoAckString; case ReadResp: return ReadRespString; case WriteResp: return WriteRespString; case SoftPFReq: return SoftPFReqString; case SoftPFResp: return SoftPFRespString; case HardPFReq: return HardPFReqString; case HardPFResp: return HardPFRespString; case InvalidateReq: return InvalidateReqString; case WriteInvalidateReq:return WriteInvalidateReqString; case WriteInvalidateResp:return WriteInvalidateRespString; case UpgradeReq: return UpgradeReqString; case ReadExReq: return ReadExReqString; case ReadExResp: return ReadExRespString; default: return OtherCmdString; } } /** delete the data pointed to in the data pointer. Ok to call to matter how * data was allocted. */ void Packet::deleteData() { assert(staticData || dynamicData); if (staticData) return; if (arrayData) delete [] data; else delete data; } /** If there isn't data in the packet, allocate some. */ void Packet::allocate() { if (data) return; assert(!staticData); dynamicData = true; arrayData = true; data = new uint8_t[getSize()]; } /** Do the packet modify the same addresses. */ bool Packet::intersect(PacketPtr p) { Addr s1 = getAddr(); Addr e1 = getAddr() + getSize() - 1; Addr s2 = p->getAddr(); Addr e2 = p->getAddr() + p->getSize() - 1; return !(s1 > e2 || e1 < s2); } bool fixPacket(PacketPtr func, PacketPtr timing) { Addr funcStart = func->getAddr(); Addr funcEnd = func->getAddr() + func->getSize() - 1; Addr timingStart = timing->getAddr(); Addr timingEnd = timing->getAddr() + timing->getSize() - 1; assert(!(funcStart > timingEnd || timingStart > funcEnd)); if (DTRACE(FunctionalAccess)) { DebugOut() << func; DebugOut() << timing; } // this packet can't solve our problem, continue on if (!timing->hasData()) return true; if (func->isRead()) { if (funcStart >= timingStart && funcEnd <= timingEnd) { func->allocate(); memcpy(func->getPtr<uint8_t>(), timing->getPtr<uint8_t>() + funcStart - timingStart, func->getSize()); func->result = Packet::Success; return false; } else { // In this case the timing packet only partially satisfies the // requset, so we would need more information to make this work. // Like bytes valid in the packet or something, so the request could // continue and get this bit of possibly newer data along with the // older data not written to yet. panic("Timing packet only partially satisfies the functional" "request. Now what?"); } } else if (func->isWrite()) { if (funcStart >= timingStart) { memcpy(timing->getPtr<uint8_t>() + (funcStart - timingStart), func->getPtr<uint8_t>(), std::min(funcEnd, timingEnd) - funcStart); } else { // timingStart > funcStart memcpy(timing->getPtr<uint8_t>(), func->getPtr<uint8_t>() + (timingStart - funcStart), std::min(funcEnd, timingEnd) - timingStart); } // we always want to keep going with a write return true; } else panic("Don't know how to handle command type %#x\n", func->cmdToIndex()); } std::ostream & operator<<(std::ostream &o, const Packet &p) { o << "[0x"; o.setf(std::ios_base::hex, std::ios_base::showbase); o << p.getAddr(); o.unsetf(std::ios_base::hex| std::ios_base::showbase); o << ":"; o.setf(std::ios_base::hex, std::ios_base::showbase); o << p.getAddr() + p.getSize() - 1 << "] "; o.unsetf(std::ios_base::hex| std::ios_base::showbase); if (p.result == Packet::Success) o << "Successful "; if (p.result == Packet::BadAddress) o << "BadAddress "; if (p.result == Packet::Nacked) o << "Nacked "; if (p.result == Packet::Unknown) o << "Inflight "; if (p.isRead()) o << "Read "; if (p.isWrite()) o << "Read "; if (p.isInvalidate()) o << "Read "; if (p.isRequest()) o << "Request "; if (p.isResponse()) o << "Response "; if (p.hasData()) o << "w/Data "; o << std::endl; return o; }
Fix fixPacket functionality to calculate sizes properly
Fix fixPacket functionality to calculate sizes properly src/mem/packet.cc: Copy size is calculated by END-BEGIN not BEGIN-END --HG-- extra : convert_revision : 0e2725c5551f8f70ff05cb285e0822afc0bb3f87
C++
bsd-3-clause
zlfben/gem5,qizenguf/MLC-STT,rjschof/gem5,joerocklin/gem5,gedare/gem5,SanchayanMaity/gem5,powerjg/gem5-ci-test,aclifton/cpeg853-gem5,powerjg/gem5-ci-test,sobercoder/gem5,TUD-OS/gem5-dtu,markoshorro/gem5,Weil0ng/gem5,briancoutinho0905/2dsampling,gedare/gem5,gedare/gem5,rallylee/gem5,yb-kim/gemV,joerocklin/gem5,aclifton/cpeg853-gem5,HwisooSo/gemV-update,cancro7/gem5,qizenguf/MLC-STT,gem5/gem5,briancoutinho0905/2dsampling,joerocklin/gem5,rallylee/gem5,rallylee/gem5,HwisooSo/gemV-update,joerocklin/gem5,powerjg/gem5-ci-test,samueldotj/TeeRISC-Simulator,zlfben/gem5,HwisooSo/gemV-update,yb-kim/gemV,KuroeKurose/gem5,rjschof/gem5,kaiyuanl/gem5,gem5/gem5,yb-kim/gemV,austinharris/gem5-riscv,cancro7/gem5,gedare/gem5,HwisooSo/gemV-update,powerjg/gem5-ci-test,qizenguf/MLC-STT,austinharris/gem5-riscv,cancro7/gem5,rallylee/gem5,austinharris/gem5-riscv,KuroeKurose/gem5,zlfben/gem5,austinharris/gem5-riscv,Weil0ng/gem5,Weil0ng/gem5,kaiyuanl/gem5,samueldotj/TeeRISC-Simulator,rjschof/gem5,yb-kim/gemV,KuroeKurose/gem5,qizenguf/MLC-STT,austinharris/gem5-riscv,yb-kim/gemV,SanchayanMaity/gem5,sobercoder/gem5,gem5/gem5,rallylee/gem5,Weil0ng/gem5,aclifton/cpeg853-gem5,SanchayanMaity/gem5,joerocklin/gem5,rjschof/gem5,KuroeKurose/gem5,kaiyuanl/gem5,powerjg/gem5-ci-test,zlfben/gem5,samueldotj/TeeRISC-Simulator,SanchayanMaity/gem5,markoshorro/gem5,rallylee/gem5,markoshorro/gem5,kaiyuanl/gem5,markoshorro/gem5,samueldotj/TeeRISC-Simulator,briancoutinho0905/2dsampling,austinharris/gem5-riscv,briancoutinho0905/2dsampling,kaiyuanl/gem5,cancro7/gem5,Weil0ng/gem5,samueldotj/TeeRISC-Simulator,HwisooSo/gemV-update,TUD-OS/gem5-dtu,yb-kim/gemV,TUD-OS/gem5-dtu,qizenguf/MLC-STT,briancoutinho0905/2dsampling,KuroeKurose/gem5,cancro7/gem5,joerocklin/gem5,aclifton/cpeg853-gem5,qizenguf/MLC-STT,aclifton/cpeg853-gem5,SanchayanMaity/gem5,HwisooSo/gemV-update,qizenguf/MLC-STT,markoshorro/gem5,gem5/gem5,aclifton/cpeg853-gem5,austinharris/gem5-riscv,Weil0ng/gem5,samueldotj/TeeRISC-Simulator,sobercoder/gem5,sobercoder/gem5,rjschof/gem5,powerjg/gem5-ci-test,gedare/gem5,kaiyuanl/gem5,gedare/gem5,zlfben/gem5,HwisooSo/gemV-update,gem5/gem5,sobercoder/gem5,zlfben/gem5,powerjg/gem5-ci-test,rallylee/gem5,cancro7/gem5,samueldotj/TeeRISC-Simulator,Weil0ng/gem5,TUD-OS/gem5-dtu,briancoutinho0905/2dsampling,markoshorro/gem5,TUD-OS/gem5-dtu,sobercoder/gem5,kaiyuanl/gem5,SanchayanMaity/gem5,markoshorro/gem5,gedare/gem5,KuroeKurose/gem5,rjschof/gem5,zlfben/gem5,joerocklin/gem5,aclifton/cpeg853-gem5,joerocklin/gem5,briancoutinho0905/2dsampling,SanchayanMaity/gem5,yb-kim/gemV,rjschof/gem5,gem5/gem5,TUD-OS/gem5-dtu,cancro7/gem5,KuroeKurose/gem5,sobercoder/gem5,yb-kim/gemV,gem5/gem5,TUD-OS/gem5-dtu
259286d80a636f248aad55635d0cd3537e72cc84
app/Model/regovar.cpp
app/Model/regovar.cpp
#include <QQmlContext> #include <QQuickWindow> #include <QQuickItem> #include <QQmlComponent> #include "regovar.h" #include "request.h" #include "Model/file/file.h" #include "Model/analysis/filtering/reference.h" Regovar* Regovar::mInstance = Q_NULLPTR; Regovar* Regovar::i() { if (mInstance == Q_NULLPTR) { mInstance = new Regovar(); } return mInstance; } Regovar::Regovar() {} Regovar::~Regovar() {} void Regovar::init() { // Init managers readSettings(); // Init models // mUser = new UserModel(); //1, "Olivier", "Gueudelot"); mProjectsTreeView = new ProjectsTreeModel(); mCurrentProject = new Project(); mUploader = new TusUploader(); resetNewAnalysisWizardModels(); mUploader->setUploadUrl(mApiRootUrl.toString() + "/file/upload"); mUploader->setRootUrl(mApiRootUrl.toString()); mUploader->setChunkSize(50 * 1024); mUploader->setBandWidthLimit(0); // Connections connect(mUploader, SIGNAL(filesEnqueued(QHash<QString,QString>)), this, SLOT(filesEnqueued(QHash<QString,QString>))); connect(&mWebSocket, &QWebSocket::connected, this, &Regovar::onWebsocketConnected); connect(&mWebSocket, &QWebSocket::disconnected, this, &Regovar::onWebsocketClosed); emit currentProjectChanged(); // DEBUG // loadAnalysis(4); mWebSocket.open(QUrl(mWebsocketUrl)); getWelcomLastData(); } void Regovar::onWebsocketConnected() { connect(&mWebSocket, &QWebSocket::textMessageReceived, this, &Regovar::onWebsocketReceived); mWebSocket.sendTextMessage(QStringLiteral("{ \"action\" : \"hello\"}")); } void Regovar::onWebsocketReceived(QString message) { QJsonDocument doc = QJsonDocument::fromJson(message.toUtf8()); QJsonObject obj = doc.object(); if (obj["action"].toString() != "hello") qDebug() << "Websocket" << message; emit websocketMessageReceived(obj["action"].toString(), obj["data"].toObject()); } void Regovar::onWebsocketClosed() { disconnect(&mWebSocket, &QWebSocket::textMessageReceived, 0, 0); mWebSocket.open(QUrl(mWebsocketUrl)); } void Regovar::readSettings() { // TODO : No hardcoded value => Load default from local config file ? QSettings settings; QString schm = settings.value("scheme", "http").toString(); QString host = settings.value("host", "dev.regovar.org").toString(); int port = settings.value("port", 80).toInt(); // Localsite server settings.beginGroup("LocalServer"); mApiRootUrl.setScheme(schm); mApiRootUrl.setHost(host); mApiRootUrl.setPort(port); // Sharing server // settings.beginGroup("SharingServer"); // mApiRootUrl.setScheme(settings.value("scheme", "http").toString()); // mApiRootUrl.setHost(settings.value("host", "dev.regovar.org").toString()); // mApiRootUrl.setPort(settings.value("port", 80).toInt()); // Websocket mWebsocketUrl.setScheme(schm == "https" ? "wss" : "ws"); mWebsocketUrl.setHost(host); mWebsocketUrl.setPath("/ws"); mWebsocketUrl.setPort(port); settings.endGroup(); } void Regovar::refreshProjectsTreeView() { qDebug() << Q_FUNC_INFO << "TODO"; } void Regovar::loadProject(int id) { Request* req = Request::get(QString("/project/%1").arg(id)); connect(req, &Request::responseReceived, [this, req, id](bool success, const QJsonObject& json) { if (success) { if (mCurrentProject->fromJson(json["data"].toObject())) { qDebug() << Q_FUNC_INFO << "CurrentProject loaded"; emit currentProjectChanged(); } else { qDebug() << Q_FUNC_INFO << "Failed to load project from id " << id << ". Wrong json data"; } } else { regovar->raiseError(json); } req->deleteLater(); }); } void Regovar::getWelcomLastData() { Request* req = Request::get(QString("/")); connect(req, &Request::responseReceived, [this, req](bool success, const QJsonObject& json) { if (success) { QJsonObject data = json["data"].toObject(); mLastAnalyses = data["last_analyses"].toArray(); emit lastAnalysesChanged(); mLastEvents = data["last_events"].toArray(); emit lastEventChanged(); mLastSubjects = data["last_subjects"].toArray(); emit lastSubjectsChanged(); // Get referencial available mReferenceDefault = data["default_reference_id"].toInt(); foreach (QJsonValue jsonVal, data["references"].toArray()) { Reference* ref = new Reference(); ref->fromJson(jsonVal.toObject()); mReferences.append(ref); } } else { regovar->raiseError(json); } req->deleteLater(); }); } void Regovar::resetNewAnalysisWizardModels() { mNewPipelineAnalysis = new PipelineAnalysis(); mNewFilteringAnalysis = new FilteringAnalysis(); emit newPipelineAnalysisChanged(); emit newFilteringAnalysisChanged(); } void Regovar::openAnalysis(int analysisId) { loadAnalysis(analysisId); } void Regovar::loadAnalysis(int id) { Request* req = Request::get(QString("/analysis/%1").arg(id)); connect(req, &Request::responseReceived, [this, req, id](bool success, const QJsonObject& json) { if (success) { int lastId = mOpenAnalyses.count(); mOpenAnalyses.append(new FilteringAnalysis(this)); FilteringAnalysis* analysis = mOpenAnalyses[lastId]; if (analysis->fromJson(json["data"].toObject())) { // Create new QML window QDir dir = QDir::currentPath(); QString file = dir.filePath("UI/AnalysisWindow.qml"); QUrl url = QUrl::fromLocalFile(file); QQmlComponent *c = new QQmlComponent(mQmlEngine, url, QQmlComponent::PreferSynchronous); QObject* o = c->create(); QQuickWindow *i = qobject_cast<QQuickWindow*>(o); QQmlEngine::setObjectOwnership(i, QQmlEngine::CppOwnership); //i->setProperty("winId", lastId); QMetaObject::invokeMethod(i, "initFromCpp", Q_ARG(QVariant, lastId)); i->setVisible(true); QObject* root = mQmlEngine->rootObjects()[0]; QQuickWindow* rootWin = qobject_cast<QQuickWindow*>(root); if (!rootWin) { qFatal("Error: Your root item has to be a window."); } i->setParent(0); qDebug() << Q_FUNC_INFO << "Filtering Analysis (id=" << id << ") Loaded. Window id=" << lastId; } else { qDebug() << Q_FUNC_INFO << "Failed to load analysis from id " << id << ". Wrong json data"; } } else { regovar->raiseError(json); } req->deleteLater(); }); } void Regovar::loadFilesBrowser() { Request* req = Request::get(QString("/file")); connect(req, &Request::responseReceived, [this, req](bool success, const QJsonObject& json) { if (success) { mRemoteFilesList.clear(); foreach( QJsonValue data, json["data"].toArray()) { File* file = new File(); file->fromJson(data.toObject()); mRemoteFilesList.append(file); } emit remoteFilesListChanged(); } else { regovar->raiseError(json); } req->deleteLater(); }); } void Regovar::filesEnqueued(QHash<QString,QString> mapping) { qDebug() << "Upload mapping Done !"; foreach (QString key, mapping.keys()) { qDebug() << key << " => " << mapping[key]; } } void Regovar::loadSampleBrowser(int refId) { Request* req = Request::get(QString("/sample/browserTree/%1").arg(2)); // refId)); connect(req, &Request::responseReceived, [this, req](bool success, const QJsonObject& json) { if (success) { mRemoteSamplesList.clear(); foreach( QJsonValue sbjData, json["data"].toArray()) { QJsonObject subject = sbjData.toObject(); // TODO subject info foreach( QJsonValue splData, subject["samples"].toArray()) { Sample* sample = new Sample(); sample->fromJson(splData.toObject()); mRemoteSamplesList.append(sample); } } emit remoteSamplesListChanged(); } else { regovar->raiseError(json); } req->deleteLater(); }); } void Regovar::newProject(QString name, QString comment) { QJsonObject body; body.insert("name", name); body.insert("is_filter", false); body.insert("comment", comment); Request* req = Request::post(QString("/project"), QJsonDocument(body).toJson()); connect(req, &Request::responseReceived, [this, req](bool success, const QJsonObject& json) { if (success) { QJsonObject projectData = json["data"].toObject(); Request* req2 = Request::get(QString("/project/%1").arg(projectData["id"].toInt())); connect(req2, &Request::responseReceived, [this, req2](bool success, const QJsonObject& json) { if (success) { Project* project = new Project(regovar); if (project->fromJson(json["data"].toObject())) { // store project model mProjectsOpen.append(project); qDebug() << Q_FUNC_INFO << "Project open !"; emit projectsTreeViewChanged(); emit projectsOpenChanged(); emit projectCreationDone(true, mProjectsOpen.count() - 1); } else { qDebug() << Q_FUNC_INFO << "Failed to load project data."; } } else { regovar->raiseError(json); } req2->deleteLater(); }); } else { regovar->raiseError(json); } req->deleteLater(); }); } void Regovar::newAnalysis(QJsonObject data) { // TODO emit analysisCreationDone(true, 6); } void Regovar::newSubject(QJsonObject data) { // TODO emit subjectCreationDone(true, 1); } void Regovar::enqueueUploadFile(QStringList filesPaths) { mUploader->enqueue(filesPaths); } void Regovar::close() { emit onClose(); } void Regovar::disconnectUser() { qDebug() << "disconnect user !"; } void Regovar::quit() { qDebug() << "quit regovar app !"; } void Regovar::raiseError(QJsonObject json) { QString code = json["code"].toString(); QString msg = json["msg"].toString(); if (code.isEmpty() && msg.isEmpty()) { code = "00000"; msg = "Unable to connect to the server."; } qDebug() << "ERROR Server side [" << code << "]" << msg; emit onError(code, msg); } FilteringAnalysis* Regovar::getAnalysisFromWindowId(int winId) { return mOpenAnalyses[winId]; } void Regovar::search(QString query) { setSearchInProgress(true); setSearchRequest(query); Request* req = Request::get(QString("/search/%1").arg(query)); connect(req, &Request::responseReceived, [this, req](bool success, const QJsonObject& json) { if (success) { setSearchResult(json["data"].toObject()); } else { regovar->raiseError(json); } req->deleteLater(); setSearchInProgress(false); }); } /* void Regovar::login(QString& login, QString& password) { // Do nothing if user already connected if (mUser->isValid()) { qDebug() << Q_FUNC_INFO << QString("User %1 %2 already loged in. Thanks to logout first.").arg(mUser->firstname(), mUser->lastname()); } else { // Store login and password as it may be ask later if network authentication problem mUser->setLogin(login); mUser->setPassword(password); // TODO use Regovar api /user/login QHttpMultiPart* multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType); QHttpPart p1; p1.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"login\"")); p1.setBody(login.toUtf8()); QHttpPart p2; p2.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"password\"")); p2.setBody(password.toUtf8()); multiPart->append(p1); multiPart->append(p2); Request* req = Request::post("/user/login", multiPart); connect(req, &Request::responseReceived, [this, multiPart, req](bool success, const QJsonObject& json) { if (success) { if (mUser->fromJson(json["data"].toObject())) { emit loginSuccess(); } } emit loginFailed(); multiPart->deleteLater(); req->deleteLater(); }); } } void Regovar::logout() { // Do nothing if user already disconnected if (!mUser->isValid()) { qDebug() << Q_FUNC_INFO << "You are already not authenticated..."; } else { Request* test = Request::get("/user/logout"); connect(test, &Request::responseReceived, [this](bool success, const QJsonObject& json) { mUser->clear(); qDebug() << Q_FUNC_INFO << "You are disconnected !"; emit logoutSuccess(); }); } } */ void Regovar::onAuthenticationRequired(QNetworkReply* request, QAuthenticator* authenticator) { // Basic authentication requested by the server. // Try authentication using current user credentials // if (authenticator->password() != currentUser()->password() || authenticator->user() != currentUser()->login()) // { // authenticator->setUser(currentUser()->login()); // authenticator->setPassword(currentUser()->password()); // } // else // { // request->error(); // } }
#include <QQmlContext> #include <QQuickWindow> #include <QQuickItem> #include <QQmlComponent> #include "regovar.h" #include "request.h" #include "Model/file/file.h" #include "Model/analysis/filtering/reference.h" Regovar* Regovar::mInstance = Q_NULLPTR; Regovar* Regovar::i() { if (mInstance == Q_NULLPTR) { mInstance = new Regovar(); } return mInstance; } Regovar::Regovar() {} Regovar::~Regovar() {} void Regovar::init() { // Init managers readSettings(); // Init models // mUser = new UserModel(); //1, "Olivier", "Gueudelot"); mProjectsTreeView = new ProjectsTreeModel(); mCurrentProject = new Project(); mUploader = new TusUploader(); resetNewAnalysisWizardModels(); mUploader->setUploadUrl(mApiRootUrl.toString() + "/file/upload"); mUploader->setRootUrl(mApiRootUrl.toString()); mUploader->setChunkSize(50 * 1024); mUploader->setBandWidthLimit(0); // Connections connect(mUploader, SIGNAL(filesEnqueued(QHash<QString,QString>)), this, SLOT(filesEnqueued(QHash<QString,QString>))); connect(&mWebSocket, &QWebSocket::connected, this, &Regovar::onWebsocketConnected); connect(&mWebSocket, &QWebSocket::disconnected, this, &Regovar::onWebsocketClosed); emit currentProjectChanged(); // DEBUG // loadAnalysis(4); mWebSocket.open(QUrl(mWebsocketUrl)); getWelcomLastData(); } void Regovar::onWebsocketConnected() { connect(&mWebSocket, &QWebSocket::textMessageReceived, this, &Regovar::onWebsocketReceived); mWebSocket.sendTextMessage(QStringLiteral("{ \"action\" : \"hello\"}")); } void Regovar::onWebsocketReceived(QString message) { QJsonDocument doc = QJsonDocument::fromJson(message.toUtf8()); QJsonObject obj = doc.object(); if (obj["action"].toString() != "hello") qDebug() << "Websocket" << message; emit websocketMessageReceived(obj["action"].toString(), obj["data"].toObject()); } void Regovar::onWebsocketClosed() { disconnect(&mWebSocket, &QWebSocket::textMessageReceived, 0, 0); mWebSocket.open(QUrl(mWebsocketUrl)); } void Regovar::readSettings() { // TODO : No hardcoded value => Load default from local config file ? QSettings settings; QString schm = settings.value("scheme", "http").toString(); QString host = settings.value("host", "dev.regovar.org").toString(); int port = settings.value("port", 80).toInt(); // Localsite server settings.beginGroup("LocalServer"); mApiRootUrl.setScheme(schm); mApiRootUrl.setHost(host); mApiRootUrl.setPort(port); // Sharing server // settings.beginGroup("SharingServer"); // mApiRootUrl.setScheme(settings.value("scheme", "http").toString()); // mApiRootUrl.setHost(settings.value("host", "dev.regovar.org").toString()); // mApiRootUrl.setPort(settings.value("port", 80).toInt()); // Websocket mWebsocketUrl.setScheme(schm == "https" ? "wss" : "ws"); mWebsocketUrl.setHost(host); mWebsocketUrl.setPath("/ws"); mWebsocketUrl.setPort(port); settings.endGroup(); } void Regovar::refreshProjectsTreeView() { qDebug() << Q_FUNC_INFO << "TODO"; } void Regovar::loadProject(int id) { Request* req = Request::get(QString("/project/%1").arg(id)); connect(req, &Request::responseReceived, [this, req, id](bool success, const QJsonObject& json) { if (success) { if (mCurrentProject->fromJson(json["data"].toObject())) { qDebug() << Q_FUNC_INFO << "CurrentProject loaded"; emit currentProjectChanged(); } else { qDebug() << Q_FUNC_INFO << "Failed to load project from id " << id << ". Wrong json data"; } } else { regovar->raiseError(json); } req->deleteLater(); }); } void Regovar::getWelcomLastData() { Request* req = Request::get(QString("/")); connect(req, &Request::responseReceived, [this, req](bool success, const QJsonObject& json) { if (success) { QJsonObject data = json["data"].toObject(); mLastAnalyses = data["last_analyses"].toArray(); emit lastAnalysesChanged(); mLastEvents = data["last_events"].toArray(); emit lastEventChanged(); mLastSubjects = data["last_subjects"].toArray(); emit lastSubjectsChanged(); // Get referencial available mReferenceDefault = data["default_reference_id"].toInt(); foreach (QJsonValue jsonVal, data["references"].toArray()) { Reference* ref = new Reference(); ref->fromJson(jsonVal.toObject()); mReferences.append(ref); } } else { regovar->raiseError(json); } req->deleteLater(); }); } void Regovar::resetNewAnalysisWizardModels() { mNewPipelineAnalysis = new PipelineAnalysis(); mNewFilteringAnalysis = new FilteringAnalysis(); emit newPipelineAnalysisChanged(); emit newFilteringAnalysisChanged(); } void Regovar::openAnalysis(int analysisId) { loadAnalysis(analysisId); } void Regovar::loadAnalysis(int id) { Request* req = Request::get(QString("/analysis/%1").arg(id)); connect(req, &Request::responseReceived, [this, req, id](bool success, const QJsonObject& json) { if (success) { int lastId = mOpenAnalyses.count(); mOpenAnalyses.append(new FilteringAnalysis(this)); FilteringAnalysis* analysis = mOpenAnalyses[lastId]; if (analysis->fromJson(json["data"].toObject())) { // Create new QML window QDir dir = QDir::currentPath(); QString file = dir.filePath("UI/AnalysisWindow.qml"); QUrl url = QUrl("qrc:/qml/AnalysisWindow.qml"); QQmlComponent *c = new QQmlComponent(mQmlEngine, url, QQmlComponent::PreferSynchronous); QObject* o = c->create(); QQuickWindow *i = qobject_cast<QQuickWindow*>(o); QQmlEngine::setObjectOwnership(i, QQmlEngine::CppOwnership); //i->setProperty("winId", lastId); QMetaObject::invokeMethod(i, "initFromCpp", Q_ARG(QVariant, lastId)); i->setVisible(true); QObject* root = mQmlEngine->rootObjects()[0]; QQuickWindow* rootWin = qobject_cast<QQuickWindow*>(root); if (!rootWin) { qFatal("Error: Your root item has to be a window."); } i->setParent(0); qDebug() << Q_FUNC_INFO << "Filtering Analysis (id=" << id << ") Loaded. Window id=" << lastId; } else { qDebug() << Q_FUNC_INFO << "Failed to load analysis from id " << id << ". Wrong json data"; } } else { regovar->raiseError(json); } req->deleteLater(); }); } void Regovar::loadFilesBrowser() { Request* req = Request::get(QString("/file")); connect(req, &Request::responseReceived, [this, req](bool success, const QJsonObject& json) { if (success) { mRemoteFilesList.clear(); foreach( QJsonValue data, json["data"].toArray()) { File* file = new File(); file->fromJson(data.toObject()); mRemoteFilesList.append(file); } emit remoteFilesListChanged(); } else { regovar->raiseError(json); } req->deleteLater(); }); } void Regovar::filesEnqueued(QHash<QString,QString> mapping) { qDebug() << "Upload mapping Done !"; foreach (QString key, mapping.keys()) { qDebug() << key << " => " << mapping[key]; } } void Regovar::loadSampleBrowser(int refId) { Request* req = Request::get(QString("/sample/browserTree/%1").arg(2)); // refId)); connect(req, &Request::responseReceived, [this, req](bool success, const QJsonObject& json) { if (success) { mRemoteSamplesList.clear(); foreach( QJsonValue sbjData, json["data"].toArray()) { QJsonObject subject = sbjData.toObject(); // TODO subject info foreach( QJsonValue splData, subject["samples"].toArray()) { Sample* sample = new Sample(); sample->fromJson(splData.toObject()); mRemoteSamplesList.append(sample); } } emit remoteSamplesListChanged(); } else { regovar->raiseError(json); } req->deleteLater(); }); } void Regovar::newProject(QString name, QString comment) { QJsonObject body; body.insert("name", name); body.insert("is_filter", false); body.insert("comment", comment); Request* req = Request::post(QString("/project"), QJsonDocument(body).toJson()); connect(req, &Request::responseReceived, [this, req](bool success, const QJsonObject& json) { if (success) { QJsonObject projectData = json["data"].toObject(); Request* req2 = Request::get(QString("/project/%1").arg(projectData["id"].toInt())); connect(req2, &Request::responseReceived, [this, req2](bool success, const QJsonObject& json) { if (success) { Project* project = new Project(regovar); if (project->fromJson(json["data"].toObject())) { // store project model mProjectsOpen.append(project); qDebug() << Q_FUNC_INFO << "Project open !"; emit projectsTreeViewChanged(); emit projectsOpenChanged(); emit projectCreationDone(true, mProjectsOpen.count() - 1); } else { qDebug() << Q_FUNC_INFO << "Failed to load project data."; } } else { regovar->raiseError(json); } req2->deleteLater(); }); } else { regovar->raiseError(json); } req->deleteLater(); }); } void Regovar::newAnalysis(QJsonObject data) { // TODO emit analysisCreationDone(true, 6); } void Regovar::newSubject(QJsonObject data) { // TODO emit subjectCreationDone(true, 1); } void Regovar::enqueueUploadFile(QStringList filesPaths) { mUploader->enqueue(filesPaths); } void Regovar::close() { emit onClose(); } void Regovar::disconnectUser() { qDebug() << "disconnect user !"; } void Regovar::quit() { qDebug() << "quit regovar app !"; } void Regovar::raiseError(QJsonObject json) { QString code = json["code"].toString(); QString msg = json["msg"].toString(); if (code.isEmpty() && msg.isEmpty()) { code = "00000"; msg = "Unable to connect to the server."; } qDebug() << "ERROR Server side [" << code << "]" << msg; emit onError(code, msg); } FilteringAnalysis* Regovar::getAnalysisFromWindowId(int winId) { return mOpenAnalyses[winId]; } void Regovar::search(QString query) { setSearchInProgress(true); setSearchRequest(query); Request* req = Request::get(QString("/search/%1").arg(query)); connect(req, &Request::responseReceived, [this, req](bool success, const QJsonObject& json) { if (success) { setSearchResult(json["data"].toObject()); } else { regovar->raiseError(json); } req->deleteLater(); setSearchInProgress(false); }); } /* void Regovar::login(QString& login, QString& password) { // Do nothing if user already connected if (mUser->isValid()) { qDebug() << Q_FUNC_INFO << QString("User %1 %2 already loged in. Thanks to logout first.").arg(mUser->firstname(), mUser->lastname()); } else { // Store login and password as it may be ask later if network authentication problem mUser->setLogin(login); mUser->setPassword(password); // TODO use Regovar api /user/login QHttpMultiPart* multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType); QHttpPart p1; p1.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"login\"")); p1.setBody(login.toUtf8()); QHttpPart p2; p2.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"password\"")); p2.setBody(password.toUtf8()); multiPart->append(p1); multiPart->append(p2); Request* req = Request::post("/user/login", multiPart); connect(req, &Request::responseReceived, [this, multiPart, req](bool success, const QJsonObject& json) { if (success) { if (mUser->fromJson(json["data"].toObject())) { emit loginSuccess(); } } emit loginFailed(); multiPart->deleteLater(); req->deleteLater(); }); } } void Regovar::logout() { // Do nothing if user already disconnected if (!mUser->isValid()) { qDebug() << Q_FUNC_INFO << "You are already not authenticated..."; } else { Request* test = Request::get("/user/logout"); connect(test, &Request::responseReceived, [this](bool success, const QJsonObject& json) { mUser->clear(); qDebug() << Q_FUNC_INFO << "You are disconnected !"; emit logoutSuccess(); }); } } */ void Regovar::onAuthenticationRequired(QNetworkReply* request, QAuthenticator* authenticator) { // Basic authentication requested by the server. // Try authentication using current user credentials // if (authenticator->password() != currentUser()->password() || authenticator->user() != currentUser()->login()) // { // authenticator->setUser(currentUser()->login()); // authenticator->setPassword(currentUser()->password()); // } // else // { // request->error(); // } }
fix qml analysis windows dynamic creation
fix qml analysis windows dynamic creation
C++
agpl-3.0
REGOVAR/QRegovar,REGOVAR/QRegovar
dac910b660b8c88a16e93e75ed26af5c6ae5f34a
src/Net.cpp
src/Net.cpp
// Copyright 2005-2016 The Mumble Developers. All rights reserved. // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file at the root of the // Mumble source tree or at <https://www.mumble.info/LICENSE>. #include "murmur_pch.h" #include "Net.h" HostAddress::HostAddress() { addr[0] = addr[1] = 0ULL; } HostAddress::HostAddress(const Q_IPV6ADDR &address) { memcpy(qip6.c, address.c, 16); } HostAddress::HostAddress(const std::string &address) { if (address.length() != 16) addr[0] = addr[1] = 0ULL; else for (int i=0;i<16;++i) qip6[i] = address[i]; } HostAddress::HostAddress(const QByteArray &address) { if (address.length() != 16) addr[0] = addr[1] = 0ULL; else for (int i=0;i<16;++i) qip6[i] = address[i]; } HostAddress::HostAddress(const QHostAddress &address) { if (address.protocol() == QAbstractSocket::IPv6Protocol) { const Q_IPV6ADDR &a = address.toIPv6Address(); memcpy(qip6.c, a.c, 16); } else { addr[0] = 0ULL; shorts[4] = 0; shorts[5] = 0xffff; hash[3] = htonl(address.toIPv4Address()); } } HostAddress::HostAddress(const sockaddr_storage &address) { if (address.ss_family == AF_INET) { const struct sockaddr_in *in = reinterpret_cast<const struct sockaddr_in *>(&address); addr[0] = 0ULL; shorts[4] = 0; shorts[5] = 0xffff; hash[3] = in->sin_addr.s_addr; } else if (address.ss_family == AF_INET6) { const struct sockaddr_in6 *in6 = reinterpret_cast<const struct sockaddr_in6 *>(&address); memcpy(qip6.c, in6->sin6_addr.s6_addr, 16); } else { addr[0] = addr[1] = 0ULL; } } bool HostAddress::operator < (const HostAddress &other) const { return memcmp(qip6.c, other.qip6.c, 16) < 0; } bool HostAddress::operator == (const HostAddress &other) const { return ((addr[0] == other.addr[0]) && (addr[1] == other.addr[1])); } bool HostAddress::match(const HostAddress &netmask, int bits) const { quint64 mask[2]; if (bits == 128) { mask[0] = mask[1] = 0xffffffffffffffffULL; } else if (bits > 64) { mask[0] = 0xffffffffffffffffULL; mask[1] = SWAP64(~((1ULL << (128-bits)) - 1)); } else { mask[0] = SWAP64(~((1ULL << (64-bits)) - 1)); mask[1] = 0ULL; } return ((addr[0] & mask[0]) == (netmask.addr[0] & mask[0])) && ((addr[1] & mask[1]) == (netmask.addr[1] & mask[1])); } std::string HostAddress::toStdString() const { return std::string(reinterpret_cast<const char *>(qip6.c), 16); } bool HostAddress::isV6() const { return (addr[0] != 0ULL) || (shorts[4] != 0) || (shorts[5] != 0xffff); } bool HostAddress::isValid() const { return (addr[0] != 0ULL) || (addr[1] != 0ULL); } QHostAddress HostAddress::toAddress() const { if (isV6()) return QHostAddress(qip6); else { return QHostAddress(ntohl(hash[3])); } } QByteArray HostAddress::toByteArray() const { return QByteArray(reinterpret_cast<const char *>(qip6.c), 16); } void HostAddress::toSockaddr(sockaddr_storage *dst) const { memset(dst, 0, sizeof(*dst)); if (isV6()) { struct sockaddr_in6 *in6 = reinterpret_cast<struct sockaddr_in6 *>(dst); dst->ss_family = AF_INET6; memcpy(in6->sin6_addr.s6_addr, qip6.c, 16); } else { struct sockaddr_in *in = reinterpret_cast<struct sockaddr_in *>(dst); dst->ss_family = AF_INET; in->sin_addr.s_addr = hash[3]; } } quint32 qHash(const HostAddress &ha) { return (ha.hash[0] ^ ha.hash[1] ^ ha.hash[2] ^ ha.hash[3]); } QString HostAddress::toString() const { if (isV6()) { if (isValid()) { QString qs; qs.sprintf("[%x:%x:%x:%x:%x:%x:%x:%x]", ntohs(shorts[0]), ntohs(shorts[1]), ntohs(shorts[2]), ntohs(shorts[3]), ntohs(shorts[4]), ntohs(shorts[5]), ntohs(shorts[6]), ntohs(shorts[7])); return qs.replace(QRegExp(QLatin1String("(:0)+")),QLatin1String(":")); } else { return QLatin1String("[::]"); } } else { return QHostAddress(ntohl(hash[3])).toString(); } } bool Ban::isExpired() const { return (iDuration > 0) && static_cast<int>(iDuration - qdtStart.secsTo(QDateTime::currentDateTime().toUTC())) < 0; } bool Ban::operator <(const Ban &other) const { // Compare username primarily and address secondarily const int unameDifference = qsUsername.localeAwareCompare(other.qsUsername); if (unameDifference == 0) return haAddress < other.haAddress; else return unameDifference < 0; } bool Ban::operator ==(const Ban &other) const { return (haAddress == other.haAddress) && (iMask == other.iMask) && (qsUsername == other.qsUsername) && (qsHash == other.qsHash) && (qsReason == other.qsReason) && (qdtStart == other.qdtStart) && (iDuration == other.iDuration); } bool Ban::isValid() const { return haAddress.isValid() && (iMask >= 8) && (iMask <= 128); } QString Ban::toString() const { return QString(QLatin1String("Hash: \"%1\", Host: \"%2\", Mask: \"%3\", Username: \"%4\", Reason: \"%5\", BanStart: \"%6\", BanEnd: \"%7\" %8")).arg( qsHash, haAddress.toString(), haAddress.isV6() ? QString::number(iMask) : QString::number(iMask-96), qsUsername, qsReason, qdtStart.toLocalTime().toString("yyyy-MM-dd hh:mm:ss"), qdtStart.toLocalTime().addSecs(iDuration).toString("yyyy-MM-dd hh:mm:ss"), iDuration == 0 ? "(permanent)" : "(temporary)" ); } quint32 qHash(const Ban &b) { return qHash(b.qsHash) ^ qHash(b.haAddress) ^ qHash(b.qsUsername) ^ qHash(b.iMask); }
// Copyright 2005-2016 The Mumble Developers. All rights reserved. // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file at the root of the // Mumble source tree or at <https://www.mumble.info/LICENSE>. #include "murmur_pch.h" #include "Net.h" HostAddress::HostAddress() { addr[0] = addr[1] = 0ULL; } HostAddress::HostAddress(const Q_IPV6ADDR &address) { memcpy(qip6.c, address.c, 16); } HostAddress::HostAddress(const std::string &address) { if (address.length() != 16) addr[0] = addr[1] = 0ULL; else for (int i=0;i<16;++i) qip6[i] = address[i]; } HostAddress::HostAddress(const QByteArray &address) { if (address.length() != 16) addr[0] = addr[1] = 0ULL; else for (int i=0;i<16;++i) qip6[i] = address[i]; } HostAddress::HostAddress(const QHostAddress &address) { if (address.protocol() == QAbstractSocket::IPv6Protocol) { const Q_IPV6ADDR &a = address.toIPv6Address(); memcpy(qip6.c, a.c, 16); } else { addr[0] = 0ULL; shorts[4] = 0; shorts[5] = 0xffff; hash[3] = htonl(address.toIPv4Address()); } } HostAddress::HostAddress(const sockaddr_storage &address) { if (address.ss_family == AF_INET) { const struct sockaddr_in *in = reinterpret_cast<const struct sockaddr_in *>(&address); addr[0] = 0ULL; shorts[4] = 0; shorts[5] = 0xffff; hash[3] = in->sin_addr.s_addr; } else if (address.ss_family == AF_INET6) { const struct sockaddr_in6 *in6 = reinterpret_cast<const struct sockaddr_in6 *>(&address); memcpy(qip6.c, in6->sin6_addr.s6_addr, 16); } else { addr[0] = addr[1] = 0ULL; } } bool HostAddress::operator < (const HostAddress &other) const { return memcmp(qip6.c, other.qip6.c, 16) < 0; } bool HostAddress::operator == (const HostAddress &other) const { return ((addr[0] == other.addr[0]) && (addr[1] == other.addr[1])); } bool HostAddress::match(const HostAddress &netmask, int bits) const { quint64 mask[2]; if (bits == 128) { mask[0] = mask[1] = 0xffffffffffffffffULL; } else if (bits > 64) { mask[0] = 0xffffffffffffffffULL; mask[1] = SWAP64(~((1ULL << (128-bits)) - 1)); } else { mask[0] = SWAP64(~((1ULL << (64-bits)) - 1)); mask[1] = 0ULL; } return ((addr[0] & mask[0]) == (netmask.addr[0] & mask[0])) && ((addr[1] & mask[1]) == (netmask.addr[1] & mask[1])); } std::string HostAddress::toStdString() const { return std::string(reinterpret_cast<const char *>(qip6.c), 16); } bool HostAddress::isV6() const { return (addr[0] != 0ULL) || (shorts[4] != 0) || (shorts[5] != 0xffff); } bool HostAddress::isValid() const { return (addr[0] != 0ULL) || (addr[1] != 0ULL); } QHostAddress HostAddress::toAddress() const { if (isV6()) return QHostAddress(qip6); else { return QHostAddress(ntohl(hash[3])); } } QByteArray HostAddress::toByteArray() const { return QByteArray(reinterpret_cast<const char *>(qip6.c), 16); } void HostAddress::toSockaddr(sockaddr_storage *dst) const { memset(dst, 0, sizeof(*dst)); if (isV6()) { struct sockaddr_in6 *in6 = reinterpret_cast<struct sockaddr_in6 *>(dst); dst->ss_family = AF_INET6; memcpy(in6->sin6_addr.s6_addr, qip6.c, 16); } else { struct sockaddr_in *in = reinterpret_cast<struct sockaddr_in *>(dst); dst->ss_family = AF_INET; in->sin_addr.s_addr = hash[3]; } } quint32 qHash(const HostAddress &ha) { return (ha.hash[0] ^ ha.hash[1] ^ ha.hash[2] ^ ha.hash[3]); } QString HostAddress::toString() const { if (isV6()) { if (isValid()) { QString qs; qs.sprintf("[%x:%x:%x:%x:%x:%x:%x:%x]", ntohs(shorts[0]), ntohs(shorts[1]), ntohs(shorts[2]), ntohs(shorts[3]), ntohs(shorts[4]), ntohs(shorts[5]), ntohs(shorts[6]), ntohs(shorts[7])); return qs.replace(QRegExp(QLatin1String("(:0)+")),QLatin1String(":")); } else { return QLatin1String("[::]"); } } else { return QHostAddress(ntohl(hash[3])).toString(); } } bool Ban::isExpired() const { return (iDuration > 0) && static_cast<int>(iDuration - qdtStart.secsTo(QDateTime::currentDateTime().toUTC())) < 0; } bool Ban::operator <(const Ban &other) const { // Compare username primarily and address secondarily const int unameDifference = qsUsername.localeAwareCompare(other.qsUsername); if (unameDifference == 0) return haAddress < other.haAddress; else return unameDifference < 0; } bool Ban::operator ==(const Ban &other) const { return (haAddress == other.haAddress) && (iMask == other.iMask) && (qsUsername == other.qsUsername) && (qsHash == other.qsHash) && (qsReason == other.qsReason) && (qdtStart == other.qdtStart) && (iDuration == other.iDuration); } bool Ban::isValid() const { return haAddress.isValid() && (iMask >= 8) && (iMask <= 128); } QString Ban::toString() const { return QString(QLatin1String("Hash: \"%1\", Host: \"%2\", Mask: \"%3\", Username: \"%4\", Reason: \"%5\", BanStart: \"%6\", BanEnd: \"%7\" %8")).arg( qsHash, haAddress.toString(), haAddress.isV6() ? QString::number(iMask) : QString::number(iMask-96), qsUsername, qsReason, qdtStart.toLocalTime().toString(QLatin1String("yyyy-MM-dd hh:mm:ss")), qdtStart.toLocalTime().addSecs(iDuration).toString(QLatin1String("yyyy-MM-dd hh:mm:ss")), iDuration == 0 ? QLatin1String("(permanent)") : QLatin1String("(temporary)") ); } quint32 qHash(const Ban &b) { return qHash(b.qsHash) ^ qHash(b.haAddress) ^ qHash(b.qsUsername) ^ qHash(b.iMask); }
use QLatin1String instead of implicit char * -> QString conversion in Ban::toString().
Net: use QLatin1String instead of implicit char * -> QString conversion in Ban::toString(). Fixes the build. We have QT_NO_CAST_FROM_ASCII set.
C++
bsd-3-clause
SuperNascher/mumble,LuAPi/mumble,LuAPi/mumble,LuAPi/mumble,Lartza/mumble,Lartza/mumble,Lartza/mumble,SuperNascher/mumble,SuperNascher/mumble,Lartza/mumble,LuAPi/mumble,Lartza/mumble,SuperNascher/mumble,LuAPi/mumble,SuperNascher/mumble,SuperNascher/mumble,Lartza/mumble,Lartza/mumble,Lartza/mumble,LuAPi/mumble,LuAPi/mumble,SuperNascher/mumble,LuAPi/mumble,SuperNascher/mumble,LuAPi/mumble,SuperNascher/mumble
66746002bdee6ea0645dc585f1f145ffa9547009
unittests/clang-query/QueryParserTest.cpp
unittests/clang-query/QueryParserTest.cpp
//===---- QueryParserTest.cpp - clang-query test --------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "QueryParser.h" #include "Query.h" #include "QuerySession.h" #include "llvm/LineEditor/LineEditor.h" #include "gtest/gtest.h" using namespace clang; using namespace clang::query; class QueryParserTest : public ::testing::Test { protected: QueryParserTest() : QS(llvm::ArrayRef<std::unique_ptr<ASTUnit>>()) {} QueryRef parse(StringRef Code) { return QueryParser::parse(Code, QS); } QuerySession QS; }; TEST_F(QueryParserTest, NoOp) { QueryRef Q = parse(""); EXPECT_TRUE(isa<NoOpQuery>(Q)); Q = parse("\n"); EXPECT_TRUE(isa<NoOpQuery>(Q)); } TEST_F(QueryParserTest, Invalid) { QueryRef Q = parse("foo"); ASSERT_TRUE(isa<InvalidQuery>(Q)); EXPECT_EQ("unknown command: foo", cast<InvalidQuery>(Q)->ErrStr); } TEST_F(QueryParserTest, Help) { QueryRef Q = parse("help"); ASSERT_TRUE(isa<HelpQuery>(Q)); Q = parse("help me"); ASSERT_TRUE(isa<InvalidQuery>(Q)); EXPECT_EQ("unexpected extra input: ' me'", cast<InvalidQuery>(Q)->ErrStr); } TEST_F(QueryParserTest, Quit) { QueryRef Q = parse("quit"); ASSERT_TRUE(isa<QuitQuery>(Q)); Q = parse("quit me"); ASSERT_TRUE(isa<InvalidQuery>(Q)); EXPECT_EQ("unexpected extra input: ' me'", cast<InvalidQuery>(Q)->ErrStr); } TEST_F(QueryParserTest, Set) { QueryRef Q = parse("set"); ASSERT_TRUE(isa<InvalidQuery>(Q)); EXPECT_EQ("expected variable name", cast<InvalidQuery>(Q)->ErrStr); Q = parse("set foo bar"); ASSERT_TRUE(isa<InvalidQuery>(Q)); EXPECT_EQ("unknown variable: 'foo'", cast<InvalidQuery>(Q)->ErrStr); Q = parse("set output"); ASSERT_TRUE(isa<InvalidQuery>(Q)); EXPECT_EQ("expected 'diag', 'print' or 'dump', got ''", cast<InvalidQuery>(Q)->ErrStr); Q = parse("set bind-root true foo"); ASSERT_TRUE(isa<InvalidQuery>(Q)); EXPECT_EQ("unexpected extra input: ' foo'", cast<InvalidQuery>(Q)->ErrStr); Q = parse("set output foo"); ASSERT_TRUE(isa<InvalidQuery>(Q)); EXPECT_EQ("expected 'diag', 'print' or 'dump', got 'foo'", cast<InvalidQuery>(Q)->ErrStr); Q = parse("set output dump"); ASSERT_TRUE(isa<SetQuery<OutputKind> >(Q)); EXPECT_EQ(&QuerySession::OutKind, cast<SetQuery<OutputKind> >(Q)->Var); EXPECT_EQ(OK_Dump, cast<SetQuery<OutputKind> >(Q)->Value); Q = parse("set bind-root foo"); ASSERT_TRUE(isa<InvalidQuery>(Q)); EXPECT_EQ("expected 'true' or 'false', got 'foo'", cast<InvalidQuery>(Q)->ErrStr); Q = parse("set bind-root true"); ASSERT_TRUE(isa<SetQuery<bool> >(Q)); EXPECT_EQ(&QuerySession::BindRoot, cast<SetQuery<bool> >(Q)->Var); EXPECT_EQ(true, cast<SetQuery<bool> >(Q)->Value); } TEST_F(QueryParserTest, Match) { QueryRef Q = parse("match decl()"); ASSERT_TRUE(isa<MatchQuery>(Q)); EXPECT_TRUE(cast<MatchQuery>(Q)->Matcher.canConvertTo<Decl>()); Q = parse("m stmt()"); ASSERT_TRUE(isa<MatchQuery>(Q)); EXPECT_TRUE(cast<MatchQuery>(Q)->Matcher.canConvertTo<Stmt>()); } TEST_F(QueryParserTest, LetUnlet) { QueryRef Q = parse("let foo decl()"); ASSERT_TRUE(isa<LetQuery>(Q)); EXPECT_EQ("foo", cast<LetQuery>(Q)->Name); EXPECT_TRUE(cast<LetQuery>(Q)->Value.isMatcher()); EXPECT_TRUE(cast<LetQuery>(Q)->Value.getMatcher().hasTypedMatcher<Decl>()); Q = parse("l foo decl()"); ASSERT_TRUE(isa<LetQuery>(Q)); EXPECT_EQ("foo", cast<LetQuery>(Q)->Name); EXPECT_TRUE(cast<LetQuery>(Q)->Value.isMatcher()); EXPECT_TRUE(cast<LetQuery>(Q)->Value.getMatcher().hasTypedMatcher<Decl>()); Q = parse("let bar \"str\""); ASSERT_TRUE(isa<LetQuery>(Q)); EXPECT_EQ("bar", cast<LetQuery>(Q)->Name); EXPECT_TRUE(cast<LetQuery>(Q)->Value.isString()); EXPECT_EQ("str", cast<LetQuery>(Q)->Value.getString()); Q = parse("let"); ASSERT_TRUE(isa<InvalidQuery>(Q)); EXPECT_EQ("expected variable name", cast<InvalidQuery>(Q)->ErrStr); Q = parse("unlet x"); ASSERT_TRUE(isa<LetQuery>(Q)); EXPECT_EQ("x", cast<LetQuery>(Q)->Name); EXPECT_FALSE(cast<LetQuery>(Q)->Value.hasValue()); Q = parse("unlet"); ASSERT_TRUE(isa<InvalidQuery>(Q)); EXPECT_EQ("expected variable name", cast<InvalidQuery>(Q)->ErrStr); Q = parse("unlet x bad_data"); ASSERT_TRUE(isa<InvalidQuery>(Q)); EXPECT_EQ("unexpected extra input: ' bad_data'", cast<InvalidQuery>(Q)->ErrStr); } TEST_F(QueryParserTest, Complete) { std::vector<llvm::LineEditor::Completion> Comps = QueryParser::complete("", 0, QS); ASSERT_EQ(6u, Comps.size()); EXPECT_EQ("help ", Comps[0].TypedText); EXPECT_EQ("help", Comps[0].DisplayText); EXPECT_EQ("let ", Comps[1].TypedText); EXPECT_EQ("let", Comps[1].DisplayText); EXPECT_EQ("match ", Comps[2].TypedText); EXPECT_EQ("match", Comps[2].DisplayText); EXPECT_EQ("set ", Comps[3].TypedText); EXPECT_EQ("set", Comps[3].DisplayText); EXPECT_EQ("unlet ", Comps[4].TypedText); EXPECT_EQ("unlet", Comps[4].DisplayText); EXPECT_EQ("quit", Comps[5].DisplayText); EXPECT_EQ("quit ", Comps[5].TypedText); Comps = QueryParser::complete("set o", 5, QS); ASSERT_EQ(1u, Comps.size()); EXPECT_EQ("utput ", Comps[0].TypedText); EXPECT_EQ("output", Comps[0].DisplayText); Comps = QueryParser::complete("match while", 11, QS); ASSERT_EQ(1u, Comps.size()); EXPECT_EQ("Stmt(", Comps[0].TypedText); EXPECT_EQ("Matcher<Stmt> whileStmt(Matcher<WhileStmt>...)", Comps[0].DisplayText); }
//===---- QueryParserTest.cpp - clang-query test --------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "QueryParser.h" #include "Query.h" #include "QuerySession.h" #include "llvm/LineEditor/LineEditor.h" #include "gtest/gtest.h" using namespace clang; using namespace clang::query; class QueryParserTest : public ::testing::Test { protected: QueryParserTest() : QS(llvm::ArrayRef<std::unique_ptr<ASTUnit>>()) {} QueryRef parse(StringRef Code) { return QueryParser::parse(Code, QS); } QuerySession QS; }; TEST_F(QueryParserTest, NoOp) { QueryRef Q = parse(""); EXPECT_TRUE(isa<NoOpQuery>(Q)); Q = parse("\n"); EXPECT_TRUE(isa<NoOpQuery>(Q)); } TEST_F(QueryParserTest, Invalid) { QueryRef Q = parse("foo"); ASSERT_TRUE(isa<InvalidQuery>(Q)); EXPECT_EQ("unknown command: foo", cast<InvalidQuery>(Q)->ErrStr); } TEST_F(QueryParserTest, Help) { QueryRef Q = parse("help"); ASSERT_TRUE(isa<HelpQuery>(Q)); Q = parse("help me"); ASSERT_TRUE(isa<InvalidQuery>(Q)); EXPECT_EQ("unexpected extra input: ' me'", cast<InvalidQuery>(Q)->ErrStr); } TEST_F(QueryParserTest, Quit) { QueryRef Q = parse("quit"); ASSERT_TRUE(isa<QuitQuery>(Q)); Q = parse("quit me"); ASSERT_TRUE(isa<InvalidQuery>(Q)); EXPECT_EQ("unexpected extra input: ' me'", cast<InvalidQuery>(Q)->ErrStr); } TEST_F(QueryParserTest, Set) { QueryRef Q = parse("set"); ASSERT_TRUE(isa<InvalidQuery>(Q)); EXPECT_EQ("expected variable name", cast<InvalidQuery>(Q)->ErrStr); Q = parse("set foo bar"); ASSERT_TRUE(isa<InvalidQuery>(Q)); EXPECT_EQ("unknown variable: 'foo'", cast<InvalidQuery>(Q)->ErrStr); Q = parse("set output"); ASSERT_TRUE(isa<InvalidQuery>(Q)); EXPECT_EQ("expected 'diag', 'print' or 'dump', got ''", cast<InvalidQuery>(Q)->ErrStr); Q = parse("set bind-root true foo"); ASSERT_TRUE(isa<InvalidQuery>(Q)); EXPECT_EQ("unexpected extra input: ' foo'", cast<InvalidQuery>(Q)->ErrStr); Q = parse("set output foo"); ASSERT_TRUE(isa<InvalidQuery>(Q)); EXPECT_EQ("expected 'diag', 'print' or 'dump', got 'foo'", cast<InvalidQuery>(Q)->ErrStr); Q = parse("set output dump"); ASSERT_TRUE(isa<SetQuery<OutputKind> >(Q)); EXPECT_EQ(&QuerySession::OutKind, cast<SetQuery<OutputKind> >(Q)->Var); EXPECT_EQ(OK_Dump, cast<SetQuery<OutputKind> >(Q)->Value); Q = parse("set bind-root foo"); ASSERT_TRUE(isa<InvalidQuery>(Q)); EXPECT_EQ("expected 'true' or 'false', got 'foo'", cast<InvalidQuery>(Q)->ErrStr); Q = parse("set bind-root true"); ASSERT_TRUE(isa<SetQuery<bool> >(Q)); EXPECT_EQ(&QuerySession::BindRoot, cast<SetQuery<bool> >(Q)->Var); EXPECT_EQ(true, cast<SetQuery<bool> >(Q)->Value); } TEST_F(QueryParserTest, Match) { QueryRef Q = parse("match decl()"); ASSERT_TRUE(isa<MatchQuery>(Q)); EXPECT_TRUE(cast<MatchQuery>(Q)->Matcher.canConvertTo<Decl>()); Q = parse("m stmt()"); ASSERT_TRUE(isa<MatchQuery>(Q)); EXPECT_TRUE(cast<MatchQuery>(Q)->Matcher.canConvertTo<Stmt>()); } TEST_F(QueryParserTest, LetUnlet) { QueryRef Q = parse("let foo decl()"); ASSERT_TRUE(isa<LetQuery>(Q)); EXPECT_EQ("foo", cast<LetQuery>(Q)->Name); EXPECT_TRUE(cast<LetQuery>(Q)->Value.isMatcher()); EXPECT_TRUE(cast<LetQuery>(Q)->Value.getMatcher().hasTypedMatcher<Decl>()); Q = parse("l foo decl()"); ASSERT_TRUE(isa<LetQuery>(Q)); EXPECT_EQ("foo", cast<LetQuery>(Q)->Name); EXPECT_TRUE(cast<LetQuery>(Q)->Value.isMatcher()); EXPECT_TRUE(cast<LetQuery>(Q)->Value.getMatcher().hasTypedMatcher<Decl>()); Q = parse("let bar \"str\""); ASSERT_TRUE(isa<LetQuery>(Q)); EXPECT_EQ("bar", cast<LetQuery>(Q)->Name); EXPECT_TRUE(cast<LetQuery>(Q)->Value.isString()); EXPECT_EQ("str", cast<LetQuery>(Q)->Value.getString()); Q = parse("let"); ASSERT_TRUE(isa<InvalidQuery>(Q)); EXPECT_EQ("expected variable name", cast<InvalidQuery>(Q)->ErrStr); Q = parse("unlet x"); ASSERT_TRUE(isa<LetQuery>(Q)); EXPECT_EQ("x", cast<LetQuery>(Q)->Name); EXPECT_FALSE(cast<LetQuery>(Q)->Value.hasValue()); Q = parse("unlet"); ASSERT_TRUE(isa<InvalidQuery>(Q)); EXPECT_EQ("expected variable name", cast<InvalidQuery>(Q)->ErrStr); Q = parse("unlet x bad_data"); ASSERT_TRUE(isa<InvalidQuery>(Q)); EXPECT_EQ("unexpected extra input: ' bad_data'", cast<InvalidQuery>(Q)->ErrStr); } TEST_F(QueryParserTest, Complete) { std::vector<llvm::LineEditor::Completion> Comps = QueryParser::complete("", 0, QS); ASSERT_EQ(6u, Comps.size()); EXPECT_EQ("help ", Comps[0].TypedText); EXPECT_EQ("help", Comps[0].DisplayText); EXPECT_EQ("let ", Comps[1].TypedText); EXPECT_EQ("let", Comps[1].DisplayText); EXPECT_EQ("match ", Comps[2].TypedText); EXPECT_EQ("match", Comps[2].DisplayText); EXPECT_EQ("set ", Comps[3].TypedText); EXPECT_EQ("set", Comps[3].DisplayText); EXPECT_EQ("unlet ", Comps[4].TypedText); EXPECT_EQ("unlet", Comps[4].DisplayText); EXPECT_EQ("quit", Comps[5].DisplayText); EXPECT_EQ("quit ", Comps[5].TypedText); Comps = QueryParser::complete("set o", 5, QS); ASSERT_EQ(1u, Comps.size()); EXPECT_EQ("utput ", Comps[0].TypedText); EXPECT_EQ("output", Comps[0].DisplayText); Comps = QueryParser::complete("match while", 11, QS); ASSERT_EQ(1u, Comps.size()); EXPECT_EQ("Stmt(", Comps[0].TypedText); EXPECT_EQ("Matcher<Stmt> whileStmt(Matcher<WhileStmt>...)", Comps[0].DisplayText); Comps = QueryParser::complete("m", 1, QS); ASSERT_EQ(1u, Comps.size()); EXPECT_EQ("atch ", Comps[0].TypedText); EXPECT_EQ("match", Comps[0].DisplayText); Comps = QueryParser::complete("l", 1, QS); ASSERT_EQ(1u, Comps.size()); EXPECT_EQ("et ", Comps[0].TypedText); EXPECT_EQ("let", Comps[0].DisplayText); }
Test non-code-completion on single letter shortcuts
[clang-query] Test non-code-completion on single letter shortcuts git-svn-id: a34e9779ed74578ad5922b3306b3d80a0c825546@343536 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/clang-tools-extra,llvm-mirror/clang-tools-extra,llvm-mirror/clang-tools-extra,llvm-mirror/clang-tools-extra
ca51e537beeb42b1452fc750b45ff42b227d5e4e
include/utxx/noncopyable.hpp
include/utxx/noncopyable.hpp
//---------------------------------------------------------------------------- /// \file noncopyable.hpp //---------------------------------------------------------------------------- /// This file contains a base class for noncopyable derived classes //---------------------------------------------------------------------------- // Copyright (c) 2020 Omnibius, LLC // Author: Serge Aleynikov <[email protected]> // Created: 2020-09-21 //---------------------------------------------------------------------------- /* ***** BEGIN LICENSE BLOCK ***** This file is part of the utxx open-source project. Copyright (C) 2010 Serge Aleynikov <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ***** END LICENSE BLOCK ***** */ #pragma once namespace utxx { class noncopyable { public: noncopyable() = default; ~noncopyable() = default; noncopyable(const noncopyable&) = delete; noncopyable(noncopyable&&) = delete; noncopyable& operator=(const noncopyable&) = delete; noncopyable& operator=(noncopyable&&) = delete; }; } // namespace utxx
//---------------------------------------------------------------------------- /// \file noncopyable.hpp //---------------------------------------------------------------------------- /// This file contains a base class for noncopyable derived classes //---------------------------------------------------------------------------- // Copyright (c) 2020 Omnibius, LLC // Author: Serge Aleynikov <[email protected]> // Created: 2020-09-21 //---------------------------------------------------------------------------- /* ***** BEGIN LICENSE BLOCK ***** This file is part of the utxx open-source project. Copyright (C) 2010 Serge Aleynikov <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ***** END LICENSE BLOCK ***** */ #pragma once #include <boost/noncopyable.hpp> namespace utxx { using noncopyable = boost::noncopyable; /* class noncopyable { public: noncopyable() = default; ~noncopyable() = default; noncopyable(const noncopyable&) = delete; noncopyable(noncopyable&&) = delete; noncopyable& operator=(const noncopyable&) = delete; noncopyable& operator=(noncopyable&&) = delete; }; */ } // namespace utxx
Update non-copyable
Update non-copyable
C++
lgpl-2.1
saleyn/utxx,saleyn/utxx,saleyn/utxx,saleyn/utxx,saleyn/utxx
b2ec91ea1f12f1881d35956bfeb26ade21d97078
includes/storage_concept.hpp
includes/storage_concept.hpp
#ifndef SDR_STORAGE_CONCEPT_H_ #define SDR_STORAGE_CONCEPT_H_ #include "constants.hpp" #include "concept.hpp" #include <unordered_set> #include <iterator> #include <vector> namespace sdr { // represents a concept in storage // designed to be able to be quickly queried and modified struct storage_concept { // store the positions of all set bits from 0 -> width sdr::hash_set<sdr::position_t> positions; storage_concept(const sdr::concept & concept) : positions() { sdr::hash_set_init(positions); fill(concept); } void fill(const sdr::concept & concept) { std::copy(std::begin(concept.data), std::end(concept.data), std::inserter(positions, std::begin(positions))); } void clear() { positions.clear(); } // conversion to concept via cast operator sdr::concept() const { return sdr::concept(std::vector<sdr::position_t>(std::begin(positions), std::end(positions))); } }; } //namespace sdr #endif
#ifndef SDR_STORAGE_CONCEPT_H_ #define SDR_STORAGE_CONCEPT_H_ #include "constants.hpp" #include "concept.hpp" #include <iterator> #include <vector> namespace sdr { // represents a concept in storage // designed to be able to be quickly queried and modified struct storage_concept { // store the positions of all set bits from 0 -> width sdr::hash_set<sdr::position_t> positions; storage_concept(const sdr::concept & concept) : positions() { sdr::hash_set_init(positions); fill(concept); } void fill(const sdr::concept & concept) { std::copy(std::begin(concept.data), std::end(concept.data), std::inserter(positions, std::begin(positions))); } void clear() { positions.clear(); } // conversion to concept via cast operator sdr::concept() const { return sdr::concept(std::vector<sdr::position_t>(std::begin(positions), std::end(positions))); } }; } //namespace sdr #endif
remove include for unnecessary type
remove include for unnecessary type
C++
mit
whackashoe/sdr,whackashoe/sdr,whackashoe/sdr
a935379eba13db47ff50e58501523e46ed9637ce
cpp/tf/test_cuda_device_array.cpp
cpp/tf/test_cuda_device_array.cpp
#include <iostream> #include <functional> typedef uint32_t uint32; typedef int32_t int32; typedef uint64_t uint64; typedef int64_t int64; typedef uint16_t uint16; typedef int8_t int8; // #define DT_INT8 int8_t template<typename T> class DT { public: static const DT<T> get() { const DT<T> v; return v; } }; #define DT_INT8 DT<int8_t>::get() #define EIGEN_DEVICE_FUNC __attribute__((device)) #define EIGEN_STRONG_INLINE __inline__ #define TF_RETURN_IF_ERROR(x) x class Status { public: Status(int value) { this->value = value; } static Status OK() { return Status(0); } int value; }; struct TensorShape { int64_t x; }; class AllocatorAttributes { public: void set_on_host(bool v) { this->on_host = v; } void set_gpu_compatible(bool v) { this->gpu_compatible = v; } bool on_host = false; bool gpu_compatible; }; namespace perftools { namespace gputools { struct DeviceMemoryBase { float *mem; uint64_t size; }; } } class Tensor { public: template<typename T> Tensor flat() { std::cout << "Tensor::flat()" << std::endl; Tensor ret; return ret; } bool IsInitialized() const; float *data(); }; class TensorReference { public: TensorReference(Tensor tensor) { std::cout << "TensorReference::TensorReference()" << std::endl; } void Unref() const; }; class Stream; class Device; class GpuDeviceInfo; class OpDeviceContext { public: OpDeviceContext(); ~OpDeviceContext(); Stream *stream(); Stream *p_stream; }; class Device { public: Device(); ~Device(); GpuDeviceInfo *tensorflow_gpu_device_info(); GpuDeviceInfo *p_gpuDeviceInfo; }; class OpKernelContext { public: Status allocate_temp(DT<int8_t> dt, TensorShape tensorShape, Tensor *tensor, AllocatorAttributes attrib) { std::cout << "OpKernelContext::allocate_temp(dt, shape, tensor, attrib)" << std::endl; return Status::OK(); } Status allocate_temp(DT<int8_t> dt, TensorShape tensorShape, Tensor *tensor) { std::cout << "OpKernelContext::allocate_temp(dt, shape, tensor)" << std::endl; return Status::OK(); } OpDeviceContext *op_device_context() { return &opDeviceContext; } Device *device() { std::cout << "OpKernelContext::device()" << std::endl; return &_device; } OpDeviceContext opDeviceContext; Device _device; }; class Stream { public: void ThenMemcpy(perftools::gputools::DeviceMemoryBase *, float *, uint32_t total_bytes); }; // stream->ThenMemcpy(&output_values_base, // out_of_line_values_on_host_.flat<int8>().data(), // total_bytes_); class EventMgr { public: void ThenExecute(Stream *stream, std::function<void ()> fn); }; class GpuDeviceInfo { public: GpuDeviceInfo() { event_mgr = new EventMgr(); } ~GpuDeviceInfo() { delete event_mgr; } EventMgr *event_mgr; }; OpDeviceContext::OpDeviceContext() { p_stream = new Stream(); } OpDeviceContext::~OpDeviceContext() { delete p_stream; p_stream = 0; } Stream *OpDeviceContext::stream() { std::cout << "OpDeviceContext::stream()" << std::endl; return p_stream; } Device::Device() { p_gpuDeviceInfo = new GpuDeviceInfo(); } Device::~Device() { delete p_gpuDeviceInfo; } GpuDeviceInfo *Device::tensorflow_gpu_device_info() { std::cout << "Device::GpuDeviceInfo()" << std::endl; return p_gpuDeviceInfo; } void EventMgr::ThenExecute(Stream *stream, std::function<void ()> fn) { std::cout << "EventMgr::ThenExecute(stream, fn)" << std::endl; } void Stream::ThenMemcpy(perftools::gputools::DeviceMemoryBase *, float *, uint32_t total_bytes) { std::cout << "Stream::ThenMemcpy(memorybase, float *, bytes=" << total_bytes << std::endl; } float *Tensor::data() { std::cout << "Tensor::data()" << std::endl; return 0; } void TensorReference::Unref() const { std::cout << "TensorReference::Unref()" << std::endl; } #define TF_DISALLOW_COPY_AND_ASSIGN(x) #include "tf_files/cuda_device_array_gpu.h" #include "tf_files/cuda_device_array.h" int main(int argc, char *argv[]) { // based loosely on tensorflow split_op.cc: OpKernelContext opKernelContext; int num_split = 4; tensorflow::CudaDeviceArrayOnHost<float *> ptrs(&opKernelContext, num_split); ptrs.Init(); ptrs.Finalize(); return 0; } // for (int i = 0; i < num_split; ++i) { // Tensor* result = nullptr; // OP_REQUIRES_OK(context, // context->allocate_output(i, output_shape, &result)); // std::cout << " SplitOpGPU::Compute() i=" << i << " result=" << result << " num_split=" << num_split << std::endl; // std::cout << " SplitOpGPU::Compute() result->flat<T>().data() " << result->flat<T>().data() << std::endl; // ptrs.Set(i, result->flat<T>().data()); // } // if (prefix_dim_size * split_dim_output_size * suffix_dim_size == 0) { // return; // } // OP_REQUIRES_OK(context, ptrs.Finalize()); // std::cout << " SplitOpGPU::Compute() call .Run(eigen_device, data=" << input.flat<T>().data() << // " prefix_dim_size=" << prefix_dim_size << " split_dim_size=" << split_dim_size << " ptrs.data().size=" << ptrs.data().size << ")" << std::endl; // SplitOpGPULaunch<T>().Run(context->eigen_device<GPUDevice>(), // input.flat<T>().data(), prefix_dim_size, // split_dim_size, suffix_dim_size, ptrs.data());
#include <iostream> #include <functional> typedef uint32_t uint32; typedef int32_t int32; typedef uint64_t uint64; typedef int64_t int64; typedef uint16_t uint16; typedef int8_t int8; // #define DT_INT8 int8_t template<typename T> class DT { public: static const DT<T> get() { const DT<T> v; return v; } }; #define DT_INT8 DT<int8_t>::get() #define EIGEN_DEVICE_FUNC __attribute__((device)) #define EIGEN_STRONG_INLINE __inline__ #define TF_RETURN_IF_ERROR(x) x class Status { public: Status(int value) { this->value = value; } static Status OK() { return Status(0); } int value; }; struct TensorShape { int64_t x; }; class AllocatorAttributes { public: void set_on_host(bool v) { this->on_host = v; } void set_gpu_compatible(bool v) { this->gpu_compatible = v; } bool on_host = false; bool gpu_compatible; }; namespace perftools { namespace gputools { struct DeviceMemoryBase { float *mem; uint64_t size; }; } } class Tensor { public: template<typename T> Tensor flat() { std::cout << "Tensor::flat()" << std::endl; Tensor ret; return ret; } bool IsInitialized() const; float *data(); }; class TensorReference { public: TensorReference(Tensor tensor) { std::cout << "TensorReference::TensorReference()" << std::endl; } void Unref() const; }; class Stream; class Device; class GpuDeviceInfo; class OpDeviceContext { public: OpDeviceContext(); ~OpDeviceContext(); Stream *stream(); Stream *p_stream; }; class Device { public: Device(); ~Device(); GpuDeviceInfo *tensorflow_gpu_device_info(); GpuDeviceInfo *p_gpuDeviceInfo; }; class OpKernelContext { public: Status allocate_temp(DT<int8_t> dt, TensorShape tensorShape, Tensor *tensor, AllocatorAttributes attrib) { std::cout << "OpKernelContext::allocate_temp(dt, shape, tensor, attrib)" << std::endl; return Status::OK(); } Status allocate_temp(DT<int8_t> dt, TensorShape tensorShape, Tensor *tensor) { std::cout << "OpKernelContext::allocate_temp(dt, shape, tensor)" << std::endl; return Status::OK(); } OpDeviceContext *op_device_context() { return &opDeviceContext; } Device *device() { std::cout << "OpKernelContext::device()" << std::endl; return &_device; } OpDeviceContext opDeviceContext; Device _device; }; class Stream { public: void ThenMemcpy(perftools::gputools::DeviceMemoryBase *, float *, uint32_t total_bytes); }; // stream->ThenMemcpy(&output_values_base, // out_of_line_values_on_host_.flat<int8>().data(), // total_bytes_); class EventMgr { public: void ThenExecute(Stream *stream, std::function<void ()> fn); }; class GpuDeviceInfo { public: GpuDeviceInfo() { std::cout << "GpuDeviceInfo::GpuDeviceInfo()" << std::endl; event_mgr = new EventMgr(); } ~GpuDeviceInfo() { std::cout << "GpuDeviceInfo::~GpuDeviceInfo()" << std::endl; delete event_mgr; } EventMgr *event_mgr; }; OpDeviceContext::OpDeviceContext() { std::cout << "OpDeviceContext::OpDeviceContext()" << std::endl; p_stream = new Stream(); } OpDeviceContext::~OpDeviceContext() { std::cout << "OpDeviceContext::~OpDeviceContext()" << std::endl; delete p_stream; p_stream = 0; } Stream *OpDeviceContext::stream() { std::cout << "OpDeviceContext::stream()" << std::endl; return p_stream; } Device::Device() { std::cout << "Device::Device()" << std::endl; p_gpuDeviceInfo = new GpuDeviceInfo(); } Device::~Device() { std::cout << "Device::~Device()" << std::endl; delete p_gpuDeviceInfo; } GpuDeviceInfo *Device::tensorflow_gpu_device_info() { std::cout << "Device::GpuDeviceInfo()" << std::endl; return p_gpuDeviceInfo; } void EventMgr::ThenExecute(Stream *stream, std::function<void ()> fn) { std::cout << "EventMgr::ThenExecute(stream, fn)" << std::endl; } void Stream::ThenMemcpy(perftools::gputools::DeviceMemoryBase *, float *, uint32_t total_bytes) { std::cout << "Stream::ThenMemcpy(memorybase, float *, bytes=" << total_bytes << std::endl; } float *Tensor::data() { std::cout << "Tensor::data()" << std::endl; return 0; } void TensorReference::Unref() const { std::cout << "TensorReference::Unref()" << std::endl; } #define TF_DISALLOW_COPY_AND_ASSIGN(x) #include "tf_files/cuda_device_array_gpu.h" #include "tf_files/cuda_device_array.h" int main(int argc, char *argv[]) { // based loosely on tensorflow split_op.cc: OpKernelContext opKernelContext; int num_split = 4; tensorflow::CudaDeviceArrayOnHost<float *> ptrs(&opKernelContext, num_split); ptrs.Init(); ptrs.Finalize(); return 0; } // for (int i = 0; i < num_split; ++i) { // Tensor* result = nullptr; // OP_REQUIRES_OK(context, // context->allocate_output(i, output_shape, &result)); // std::cout << " SplitOpGPU::Compute() i=" << i << " result=" << result << " num_split=" << num_split << std::endl; // std::cout << " SplitOpGPU::Compute() result->flat<T>().data() " << result->flat<T>().data() << std::endl; // ptrs.Set(i, result->flat<T>().data()); // } // if (prefix_dim_size * split_dim_output_size * suffix_dim_size == 0) { // return; // } // OP_REQUIRES_OK(context, ptrs.Finalize()); // std::cout << " SplitOpGPU::Compute() call .Run(eigen_device, data=" << input.flat<T>().data() << // " prefix_dim_size=" << prefix_dim_size << " split_dim_size=" << split_dim_size << " ptrs.data().size=" << ptrs.data().size << ")" << std::endl; // SplitOpGPULaunch<T>().Run(context->eigen_device<GPUDevice>(), // input.flat<T>().data(), prefix_dim_size, // split_dim_size, suffix_dim_size, ptrs.data());
add more cout
add more cout
C++
apache-2.0
hughperkins/pub-prototyping,hughperkins/pub-prototyping,hughperkins/pub-prototyping,hughperkins/pub-prototyping,hughperkins/pub-prototyping,hughperkins/pub-prototyping,hughperkins/pub-prototyping
32a6ebdce3ed4d829c3a42da69af80d1ff98837f
include/Bull/Core/Configuration/Integer.hpp
include/Bull/Core/Configuration/Integer.hpp
#ifndef BULL_CORE_CONFIGURATION_INTEGER_HPP #define BULL_CORE_CONFIGURATION_INTEGER_HPP #include <cstdint> #include <utility> namespace Bull { typedef uint8_t Uint8; typedef uint16_t Uint16; typedef uint32_t Uint32; typedef uint64_t Uint64; typedef int8_t Int8; typedef int16_t Int16; typedef int32_t Int32; typedef int64_t Int64; } #endif // BULL_CORE_CONFIGURATION_INTEGER_HPP
#ifndef BULL_CORE_CONFIGURATION_INTEGER_HPP #define BULL_CORE_CONFIGURATION_INTEGER_HPP #include <cstdint> namespace Bull { typedef int8_t Int8; typedef int16_t Int16; typedef int32_t Int32; typedef int64_t Int64; typedef uint8_t Uint8; typedef uint16_t Uint16; typedef uint32_t Uint32; typedef uint64_t Uint64; } #endif // BULL_CORE_CONFIGURATION_INTEGER_HPP
Remove useless include
[Core/Integer] Remove useless include
C++
mit
siliace/Bull
14f6abb96ebe014e01eec960ad45d01f393f577e
test/tests/main.cpp
test/tests/main.cpp
/**********************************************************\ This file is distributed under the MIT License. See https://github.com/morzhovets/momo/blob/master/LICENSE for details. tests/main.cpp \**********************************************************/ #include "pch.h" int main() { std::cout << "__cplusplus: " << __cplusplus << std::endl; std::cout << "sizeof(void*): " << sizeof(void*) << std::endl; return 0; }
/**********************************************************\ This file is distributed under the MIT License. See https://github.com/morzhovets/momo/blob/master/LICENSE for details. tests/main.cpp \**********************************************************/ #include "pch.h" int main() { #ifdef _MSC_VER std::cout << "_MSC_VER: " << _MSC_VER << std::endl; #endif #ifdef __GNUC__ std::cout << "__GNUC__: " << __GNUC__ << std::endl; #endif #ifdef __clang_major__ std::cout << "__clang_major__: " << __clang_major__ << std::endl; #endif std::cout << "__cplusplus: " << __cplusplus << std::endl; std::cout << "sizeof(void*): " << sizeof(void*) << std::endl; return 0; }
Print compiler versions
Print compiler versions
C++
mit
morzhovets/momo,morzhovets/momo
545302d1b1d60072018cf5cc4ff5bdc502013ea6
src/LexLua.cxx
src/LexLua.cxx
// Scintilla source code edit control /** @file LexLua.cxx ** Lexer for Lua language. ** ** Written by Paul Winwood. ** Folder by Alexey Yutkin. ** Modified by Marcos E. Wurzius & Philippe Lhoste **/ #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <fcntl.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "StyleContext.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" #define SCE_LUA_LAST_STYLE SCE_LUA_WORD6 static inline bool IsAWordChar(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_'); } inline bool IsAWordStart(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == '_'); } inline bool isLuaOperator(char ch) { if (isalnum(ch)) return false; // '.' left out as it is used to make up numbers if (ch == '*' || ch == '/' || ch == '-' || ch == '+' || ch == '(' || ch == ')' || ch == '=' || ch == '{' || ch == '}' || ch == '~' || ch == '[' || ch == ']' || ch == ';' || ch == '<' || ch == '>' || ch == ',' || ch == '.' || ch == '^' || ch == '%' || ch == ':') return true; return false; } static void ColouriseLuaDoc( unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { WordList &keywords = *keywordlists[0]; WordList &keywords2 = *keywordlists[1]; WordList &keywords3 = *keywordlists[2]; WordList &keywords4 = *keywordlists[3]; WordList &keywords5 = *keywordlists[4]; WordList &keywords6 = *keywordlists[5]; // Must initialize the literal string nesting level, if we are inside such a string. int literalStringLevel = 0; if (initStyle == SCE_LUA_LITERALSTRING) { literalStringLevel = 1; } // We use states above the last one to indicate nesting level of literal strings if (initStyle > SCE_LUA_LAST_STYLE) { literalStringLevel = initStyle - SCE_LUA_LAST_STYLE + 1; } // Do not leak onto next line if (initStyle == SCE_LUA_STRINGEOL) { initStyle = SCE_LUA_DEFAULT; } StyleContext sc(startPos, length, initStyle, styler); if (startPos == 0 && sc.ch == '#') { sc.SetState(SCE_LUA_COMMENTLINE); } for (; sc.More(); sc.Forward()) { // Handle line continuation generically. if (sc.ch == '\\') { if (sc.Match("\\\n")) { sc.Forward(); sc.Forward(); continue; } if (sc.Match("\\\r\n")) { sc.Forward(); sc.Forward(); sc.Forward(); continue; } } // Determine if the current state should terminate. if (sc.state == SCE_LUA_OPERATOR) { sc.SetState(SCE_LUA_DEFAULT); } else if (sc.state == SCE_LUA_NUMBER) { if (!IsAWordChar(sc.ch)) { sc.SetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_IDENTIFIER) { if (!IsAWordChar(sc.ch) || (sc.ch == '.')) { char s[100]; sc.GetCurrent(s, sizeof(s)); if (keywords.InList(s)) { sc.ChangeState(SCE_LUA_WORD); } else if (keywords2.InList(s)) { sc.ChangeState(SCE_LUA_WORD2); } else if (keywords3.InList(s)) { sc.ChangeState(SCE_LUA_WORD3); } else if (keywords4.InList(s)) { sc.ChangeState(SCE_LUA_WORD4); } else if (keywords5.InList(s)) { sc.ChangeState(SCE_LUA_WORD5); } else if (keywords6.InList(s)) { sc.ChangeState(SCE_LUA_WORD6); } sc.SetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_COMMENTLINE ) { if (sc.atLineEnd) { sc.SetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_PREPROCESSOR ) { if (sc.atLineEnd) { sc.SetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_STRING) { if (sc.ch == '\\') { if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') { sc.Forward(); } } else if (sc.ch == '\"') { sc.ForwardSetState(SCE_LUA_DEFAULT); } else if (sc.atLineEnd) { sc.ChangeState(SCE_LUA_STRINGEOL); sc.ForwardSetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_CHARACTER) { if (sc.ch == '\\') { if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') { sc.Forward(); } } else if (sc.ch == '\'') { sc.ForwardSetState(SCE_LUA_DEFAULT); } else if (sc.atLineEnd) { sc.ChangeState(SCE_LUA_STRINGEOL); sc.ForwardSetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_LITERALSTRING || sc.state > SCE_LUA_LAST_STYLE) { if (sc.Match('[', '[')) { literalStringLevel++; sc.SetState(SCE_LUA_LAST_STYLE + literalStringLevel - 1); } else if (sc.Match(']', ']') && literalStringLevel > 0) { literalStringLevel--; sc.Forward(); if (literalStringLevel == 0) { sc.ForwardSetState(SCE_LUA_DEFAULT); } else if (literalStringLevel == 1) { sc.ForwardSetState(SCE_LUA_LITERALSTRING); } else { sc.ForwardSetState(SCE_LUA_LAST_STYLE + literalStringLevel - 1); } } } // Determine if a new state should be entered. if (sc.state == SCE_LUA_DEFAULT) { if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) { sc.SetState(SCE_LUA_NUMBER); } else if (IsAWordStart(sc.ch)) { sc.SetState(SCE_LUA_IDENTIFIER); } else if (sc.Match('\"')) { sc.SetState(SCE_LUA_STRING); } else if (sc.Match('\'')) { sc.SetState(SCE_LUA_CHARACTER); } else if (sc.Match('[', '[')) { literalStringLevel = 1; sc.SetState(SCE_LUA_LITERALSTRING); sc.Forward(); } else if (sc.Match('-', '-')) { sc.SetState(SCE_LUA_COMMENTLINE); sc.Forward(); } else if (sc.Match('$') && sc.atLineStart) { sc.SetState(SCE_LUA_PREPROCESSOR); // Obsolete since Lua 4.0, but still in old code } else if (isLuaOperator(static_cast<char>(sc.ch))) { sc.SetState(SCE_LUA_OPERATOR); } } } sc.Complete(); } static void FoldLuaDoc(unsigned int startPos, int length, int /* initStyle */, WordList *[], Accessor &styler) { unsigned int lengthDoc = startPos + length; int visibleChars = 0; int lineCurrent = styler.GetLine(startPos); int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK; int levelCurrent = levelPrev; char chNext = styler[startPos]; bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0; int styleNext = styler.StyleAt(startPos); char s[10]; for (unsigned int i = startPos; i < lengthDoc; i++) { char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); int style = styleNext; styleNext = styler.StyleAt(i + 1); bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n'); if (style == SCE_LUA_WORD) { if (ch == 'i' || ch == 'd' || ch == 'f' || ch == 'e') { for (unsigned int j = 0; j < 8; j++) { if (!iswordchar(styler[i + j])) { break; } s[j] = styler[i + j]; s[j + 1] = '\0'; } if ((strcmp(s, "if") == 0) || (strcmp(s, "do") == 0) || (strcmp(s, "function") == 0)) { levelCurrent++; } if ((strcmp(s, "end") == 0) || (strcmp(s, "elseif") == 0)) { levelCurrent--; } } } else if (style == SCE_LUA_OPERATOR) { if (ch == '{' || ch == '(') { levelCurrent++; } else if (ch == '}' || ch == ')') { levelCurrent--; } } if (atEOL) { int lev = levelPrev; if (visibleChars == 0 && foldCompact) { lev |= SC_FOLDLEVELWHITEFLAG; } if ((levelCurrent > levelPrev) && (visibleChars > 0)) { lev |= SC_FOLDLEVELHEADERFLAG; } if (lev != styler.LevelAt(lineCurrent)) { styler.SetLevel(lineCurrent, lev); } lineCurrent++; levelPrev = levelCurrent; visibleChars = 0; } if (!isspacechar(ch)) { visibleChars++; } } // Fill in the real level of the next line, keeping the current flags as they will be filled in later int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK; styler.SetLevel(lineCurrent, levelPrev | flagsNext); } LexerModule lmLua(SCLEX_LUA, ColouriseLuaDoc, "lua", FoldLuaDoc);
// Scintilla source code edit control /** @file LexLua.cxx ** Lexer for Lua language. ** ** Written by Paul Winwood. ** Folder by Alexey Yutkin. ** Modified by Marcos E. Wurzius & Philippe Lhoste **/ #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <fcntl.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "StyleContext.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" #define SCE_LUA_LAST_STYLE SCE_LUA_WORD6 static inline bool IsAWordChar(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_'); } inline bool IsAWordStart(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == '_'); } inline bool isLuaOperator(char ch) { if (isalnum(ch)) return false; // '.' left out as it is used to make up numbers if (ch == '*' || ch == '/' || ch == '-' || ch == '+' || ch == '(' || ch == ')' || ch == '=' || ch == '{' || ch == '}' || ch == '~' || ch == '[' || ch == ']' || ch == ';' || ch == '<' || ch == '>' || ch == ',' || ch == '.' || ch == '^' || ch == '%' || ch == ':') return true; return false; } static void ColouriseLuaDoc( unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { WordList &keywords = *keywordlists[0]; WordList &keywords2 = *keywordlists[1]; WordList &keywords3 = *keywordlists[2]; WordList &keywords4 = *keywordlists[3]; WordList &keywords5 = *keywordlists[4]; WordList &keywords6 = *keywordlists[5]; // Must initialize the literal string nesting level, if we are inside such a string. int literalStringLevel = 0; if (initStyle == SCE_LUA_LITERALSTRING) { literalStringLevel = 1; } // We use states above the last one to indicate nesting level of literal strings if (initStyle > SCE_LUA_LAST_STYLE) { literalStringLevel = initStyle - SCE_LUA_LAST_STYLE + 1; } // Do not leak onto next line if (initStyle == SCE_LUA_STRINGEOL) { initStyle = SCE_LUA_DEFAULT; } StyleContext sc(startPos, length, initStyle, styler); if (startPos == 0 && sc.ch == '#') { sc.SetState(SCE_LUA_COMMENTLINE); } for (; sc.More(); sc.Forward()) { if (sc.atLineStart && (sc.state == SCE_LUA_STRING)) { // Prevent SCE_LUA_STRINGEOL from leaking back to previous line sc.SetState(SCE_LUA_STRING); } // Handle string line continuation if ((sc.state == SCE_LUA_STRING || sc.state == SCE_LUA_CHARACTER) && sc.ch == '\\') { if (sc.chNext == '\n' || sc.chNext == '\r') { sc.Forward(); if (sc.ch == '\r' && sc.chNext == '\n') { sc.Forward(); } continue; } } // Determine if the current state should terminate. if (sc.state == SCE_LUA_OPERATOR) { sc.SetState(SCE_LUA_DEFAULT); } else if (sc.state == SCE_LUA_NUMBER) { if (!IsAWordChar(sc.ch)) { sc.SetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_IDENTIFIER) { if (!IsAWordChar(sc.ch) || (sc.ch == '.')) { char s[100]; sc.GetCurrent(s, sizeof(s)); if (keywords.InList(s)) { sc.ChangeState(SCE_LUA_WORD); } else if (keywords2.InList(s)) { sc.ChangeState(SCE_LUA_WORD2); } else if (keywords3.InList(s)) { sc.ChangeState(SCE_LUA_WORD3); } else if (keywords4.InList(s)) { sc.ChangeState(SCE_LUA_WORD4); } else if (keywords5.InList(s)) { sc.ChangeState(SCE_LUA_WORD5); } else if (keywords6.InList(s)) { sc.ChangeState(SCE_LUA_WORD6); } sc.SetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_COMMENTLINE ) { if (sc.atLineEnd) { sc.SetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_PREPROCESSOR ) { if (sc.atLineEnd) { sc.SetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_STRING) { if (sc.ch == '\\') { if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') { sc.Forward(); } } else if (sc.ch == '\"') { sc.ForwardSetState(SCE_LUA_DEFAULT); } else if (sc.atLineEnd) { sc.ChangeState(SCE_LUA_STRINGEOL); sc.ForwardSetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_CHARACTER) { if (sc.ch == '\\') { if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') { sc.Forward(); } } else if (sc.ch == '\'') { sc.ForwardSetState(SCE_LUA_DEFAULT); } else if (sc.atLineEnd) { sc.ChangeState(SCE_LUA_STRINGEOL); sc.ForwardSetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_LITERALSTRING || sc.state > SCE_LUA_LAST_STYLE) { if (sc.Match('[', '[')) { literalStringLevel++; sc.SetState(SCE_LUA_LAST_STYLE + literalStringLevel - 1); } else if (sc.Match(']', ']') && literalStringLevel > 0) { literalStringLevel--; sc.Forward(); if (literalStringLevel == 0) { sc.ForwardSetState(SCE_LUA_DEFAULT); } else if (literalStringLevel == 1) { sc.ForwardSetState(SCE_LUA_LITERALSTRING); } else { sc.ForwardSetState(SCE_LUA_LAST_STYLE + literalStringLevel - 1); } } } // Determine if a new state should be entered. if (sc.state == SCE_LUA_DEFAULT) { if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) { sc.SetState(SCE_LUA_NUMBER); } else if (IsAWordStart(sc.ch)) { sc.SetState(SCE_LUA_IDENTIFIER); } else if (sc.Match('\"')) { sc.SetState(SCE_LUA_STRING); } else if (sc.Match('\'')) { sc.SetState(SCE_LUA_CHARACTER); } else if (sc.Match('[', '[')) { literalStringLevel = 1; sc.SetState(SCE_LUA_LITERALSTRING); sc.Forward(); } else if (sc.Match('-', '-')) { sc.SetState(SCE_LUA_COMMENTLINE); sc.Forward(); } else if (sc.Match('$') && sc.atLineStart) { sc.SetState(SCE_LUA_PREPROCESSOR); // Obsolete since Lua 4.0, but still in old code } else if (isLuaOperator(static_cast<char>(sc.ch))) { sc.SetState(SCE_LUA_OPERATOR); } } } sc.Complete(); } static void FoldLuaDoc(unsigned int startPos, int length, int /* initStyle */, WordList *[], Accessor &styler) { unsigned int lengthDoc = startPos + length; int visibleChars = 0; int lineCurrent = styler.GetLine(startPos); int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK; int levelCurrent = levelPrev; char chNext = styler[startPos]; bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0; int styleNext = styler.StyleAt(startPos); char s[10]; for (unsigned int i = startPos; i < lengthDoc; i++) { char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); int style = styleNext; styleNext = styler.StyleAt(i + 1); bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n'); if (style == SCE_LUA_WORD) { if (ch == 'i' || ch == 'd' || ch == 'f' || ch == 'e') { for (unsigned int j = 0; j < 8; j++) { if (!iswordchar(styler[i + j])) { break; } s[j] = styler[i + j]; s[j + 1] = '\0'; } if ((strcmp(s, "if") == 0) || (strcmp(s, "do") == 0) || (strcmp(s, "function") == 0)) { levelCurrent++; } if ((strcmp(s, "end") == 0) || (strcmp(s, "elseif") == 0)) { levelCurrent--; } } } else if (style == SCE_LUA_OPERATOR) { if (ch == '{' || ch == '(') { levelCurrent++; } else if (ch == '}' || ch == ')') { levelCurrent--; } } if (atEOL) { int lev = levelPrev; if (visibleChars == 0 && foldCompact) { lev |= SC_FOLDLEVELWHITEFLAG; } if ((levelCurrent > levelPrev) && (visibleChars > 0)) { lev |= SC_FOLDLEVELHEADERFLAG; } if (lev != styler.LevelAt(lineCurrent)) { styler.SetLevel(lineCurrent, lev); } lineCurrent++; levelPrev = levelCurrent; visibleChars = 0; } if (!isspacechar(ch)) { visibleChars++; } } // Fill in the real level of the next line, keeping the current flags as they will be filled in later int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK; styler.SetLevel(lineCurrent, levelPrev | flagsNext); } LexerModule lmLua(SCLEX_LUA, ColouriseLuaDoc, "lua", FoldLuaDoc);
Patch from Philippe to fix multiline string handling.
Patch from Philippe to fix multiline string handling.
C++
isc
rhaberkorn/scintilla-mirror,rhaberkorn/scintilla-mirror,rhaberkorn/scintilla-mirror,rhaberkorn/scintilla-mirror,rhaberkorn/scintilla-mirror,rhaberkorn/scintilla-mirror,rhaberkorn/scintilla-mirror,rhaberkorn/scintilla-mirror
31237b7356c9b2e9afb62ac6e2fd2de7ffd555f8
example/image-classification/predict-cpp/image-classification-predict.cc
example/image-classification/predict-cpp/image-classification-predict.cc
/*! * Copyright (c) 2015 by Xiao Liu, pertusa, caprice-j * \file image_classification-predict.cpp * \brief C++ predict example of mxnet */ // // File: image-classification-predict.cpp // This is a simple predictor which shows // how to use c api for image classfication // It uses opencv for image reading // Created by liuxiao on 12/9/15. // Thanks to : pertusa, caprice-j, sofiawu, tqchen, piiswrong // Home Page: www.liuxiao.org // E-mail: [email protected] // #include <stdio.h> // Path for c_predict_api #include <mxnet/c_predict_api.h> #include <iostream> #include <fstream> #include <string> #include <vector> #include <opencv2/opencv.hpp> const mx_float DEFAULT_MEAN = 117.0; // Read file to buffer class BufferFile { public : std::string file_path_; int length_; char* buffer_; explicit BufferFile(std::string file_path) :file_path_(file_path) { std::ifstream ifs(file_path.c_str(), std::ios::in | std::ios::binary); if (!ifs) { std::cerr << "Can't open the file. Please check " << file_path << ". \n"; length_ = 0; buffer_ = NULL; return; } ifs.seekg(0, std::ios::end); length_ = ifs.tellg(); ifs.seekg(0, std::ios::beg); std::cout << file_path.c_str() << " ... "<< length_ << " bytes\n"; buffer_ = new char[sizeof(char) * length_]; ifs.read(buffer_, length_); ifs.close(); } int GetLength() { return length_; } char* GetBuffer() { return buffer_; } ~BufferFile() { if (buffer_) { delete[] buffer_; buffer_ = NULL; } } }; void GetImageFile(const std::string image_file, mx_float* image_data, const int channels, const cv::Size resize_size, const mx_float* mean_data = nullptr) { // Read all kinds of file into a BGR color 3 channels image cv::Mat im_ori = cv::imread(image_file, cv::IMREAD_COLOR); if (im_ori.empty()) { std::cerr << "Can't open the image. Please check " << image_file << ". \n"; assert(false); } cv::Mat im; resize(im_ori, im, resize_size); int size = im.rows * im.cols * channels; mx_float* ptr_image_r = image_data; mx_float* ptr_image_g = image_data + size / 3; mx_float* ptr_image_b = image_data + size / 3 * 2; float mean_b, mean_g, mean_r; mean_b = mean_g = mean_r = DEFAULT_MEAN; for (int i = 0; i < im.rows; i++) { uchar* data = im.ptr<uchar>(i); for (int j = 0; j < im.cols; j++) { if (mean_data) { mean_r = *mean_data; if (channels > 1) { mean_g = *(mean_data + size / 3); mean_b = *(mean_data + size / 3 * 2); } mean_data++; } if (channels > 1) { *ptr_image_g++ = static_cast<mx_float>(*data++) - mean_g; *ptr_image_b++ = static_cast<mx_float>(*data++) - mean_b; } *ptr_image_r++ = static_cast<mx_float>(*data++) - mean_r;; } } } // LoadSynsets // Code from : https://github.com/pertusa/mxnet_predict_cc/blob/master/mxnet_predict.cc std::vector<std::string> LoadSynset(std::string synset_file) { std::ifstream fi(synset_file.c_str()); if ( !fi.is_open() ) { std::cerr << "Error opening synset file " << synset_file << std::endl; assert(false); } std::vector<std::string> output; std::string synset, lemma; while ( fi >> synset ) { getline(fi, lemma); output.push_back(lemma); } fi.close(); return output; } void PrintOutputResult(const std::vector<float>& data, const std::vector<std::string>& synset) { if (data.size() != synset.size()) { std::cerr << "Result data and synset size does not match!" << std::endl; } float best_accuracy = 0.0; int best_idx = 0; for ( int i = 0; i < static_cast<int>(data.size()); i++ ) { printf("Accuracy[%d] = %.8f\n", i, data[i]); if ( data[i] > best_accuracy ) { best_accuracy = data[i]; best_idx = i; } } printf("Best Result: [%s] id = %d, accuracy = %.8f\n", synset[best_idx].c_str(), best_idx, best_accuracy); } int main(int argc, char* argv[]) { if (argc < 2) { std::cout << "No test image here." << std::endl << "Usage: ./image-classification-predict apple.jpg" << std::endl; return 0; } std::string test_file; test_file = std::string(argv[1]); // Models path for your model, you have to modify it std::string json_file = "model/Inception/Inception-BN-symbol.json"; std::string param_file = "model/Inception/Inception-BN-0126.params"; std::string synset_file = "model/Inception/synset.txt"; std::string nd_file = "model/Inception/mean_224.nd"; BufferFile json_data(json_file); BufferFile param_data(param_file); // Parameters int dev_type = 1; // 1: cpu, 2: gpu int dev_id = 0; // arbitrary. mx_uint num_input_nodes = 1; // 1 for feedforward const char* input_key[1] = {"data"}; const char** input_keys = input_key; // Image size and channels int width = 224; int height = 224; int channels = 3; const mx_uint input_shape_indptr[2] = { 0, 4 }; const mx_uint input_shape_data[4] = { 1, static_cast<mx_uint>(channels), static_cast<mx_uint>(width), static_cast<mx_uint>(height) }; PredictorHandle pred_hnd = 0; if (json_data.GetLength() == 0 || param_data.GetLength() == 0) { return -1; } // Create Predictor MXPredCreate((const char*)json_data.GetBuffer(), (const char*)param_data.GetBuffer(), static_cast<size_t>(param_data.GetLength()), dev_type, dev_id, num_input_nodes, input_keys, input_shape_indptr, input_shape_data, &pred_hnd); assert(pred_hnd); int image_size = width * height * channels; // Read Mean Data const mx_float* nd_data = NULL; NDListHandle nd_hnd = 0; BufferFile nd_buf(nd_file); if (nd_buf.GetLength() > 0) { mx_uint nd_index = 0; mx_uint nd_len; const mx_uint* nd_shape = 0; const char* nd_key = 0; mx_uint nd_ndim = 0; MXNDListCreate((const char*)nd_buf.GetBuffer(), nd_buf.GetLength(), &nd_hnd, &nd_len); MXNDListGet(nd_hnd, nd_index, &nd_key, &nd_data, &nd_shape, &nd_ndim); } // Read Image Data std::vector<mx_float> image_data = std::vector<mx_float>(image_size); GetImageFile(test_file, image_data.data(), channels, cv::Size(width, height), nd_data); // Set Input Image MXPredSetInput(pred_hnd, "data", image_data.data(), image_size); // Do Predict Forward MXPredForward(pred_hnd); mx_uint output_index = 0; mx_uint *shape = 0; mx_uint shape_len; // Get Output Result MXPredGetOutputShape(pred_hnd, output_index, &shape, &shape_len); size_t size = 1; for (mx_uint i = 0; i < shape_len; ++i) size *= shape[i]; std::vector<float> data(size); MXPredGetOutput(pred_hnd, output_index, &(data[0]), size); // Release NDList if (nd_hnd) MXNDListFree(nd_hnd); // Release Predictor MXPredFree(pred_hnd); // Synset path for your model, you have to modify it std::vector<std::string> synset = LoadSynset(synset_file); // Print Output Data PrintOutputResult(data, synset); return 0; }
/*! * Copyright (c) 2015 by Xiao Liu, pertusa, caprice-j * \file image_classification-predict.cpp * \brief C++ predict example of mxnet */ // // File: image-classification-predict.cpp // This is a simple predictor which shows // how to use c api for image classfication // It uses opencv for image reading // Created by liuxiao on 12/9/15. // Thanks to : pertusa, caprice-j, sofiawu, tqchen, piiswrong // Home Page: www.liuxiao.org // E-mail: [email protected] // #include <stdio.h> // Path for c_predict_api #include <mxnet/c_predict_api.h> #include <iostream> #include <fstream> #include <string> #include <vector> #include <opencv2/opencv.hpp> const mx_float DEFAULT_MEAN = 117.0; // Read file to buffer class BufferFile { public : std::string file_path_; int length_; char* buffer_; explicit BufferFile(std::string file_path) :file_path_(file_path) { std::ifstream ifs(file_path.c_str(), std::ios::in | std::ios::binary); if (!ifs) { std::cerr << "Can't open the file. Please check " << file_path << ". \n"; length_ = 0; buffer_ = NULL; return; } ifs.seekg(0, std::ios::end); length_ = ifs.tellg(); ifs.seekg(0, std::ios::beg); std::cout << file_path.c_str() << " ... "<< length_ << " bytes\n"; buffer_ = new char[sizeof(char) * length_]; ifs.read(buffer_, length_); ifs.close(); } int GetLength() { return length_; } char* GetBuffer() { return buffer_; } ~BufferFile() { if (buffer_) { delete[] buffer_; buffer_ = NULL; } } }; void GetImageFile(const std::string image_file, mx_float* image_data, const int channels, const cv::Size resize_size, const mx_float* mean_data = nullptr) { // Read all kinds of file into a BGR color 3 channels image cv::Mat im_ori = cv::imread(image_file, cv::IMREAD_COLOR); if (im_ori.empty()) { std::cerr << "Can't open the image. Please check " << image_file << ". \n"; assert(false); } cv::Mat im; resize(im_ori, im, resize_size); int size = im.rows * im.cols * channels; mx_float* ptr_image_r = image_data; mx_float* ptr_image_g = image_data + size / 3; mx_float* ptr_image_b = image_data + size / 3 * 2; float mean_b, mean_g, mean_r; mean_b = mean_g = mean_r = DEFAULT_MEAN; for (int i = 0; i < im.rows; i++) { uchar* data = im.ptr<uchar>(i); for (int j = 0; j < im.cols; j++) { if (mean_data) { mean_r = *mean_data; if (channels > 1) { mean_g = *(mean_data + size / 3); mean_b = *(mean_data + size / 3 * 2); } mean_data++; } if (channels > 1) { *ptr_image_g++ = static_cast<mx_float>(*data++) - mean_g; *ptr_image_b++ = static_cast<mx_float>(*data++) - mean_b; } *ptr_image_r++ = static_cast<mx_float>(*data++) - mean_r;; } } } // LoadSynsets // Code from : https://github.com/pertusa/mxnet_predict_cc/blob/master/mxnet_predict.cc std::vector<std::string> LoadSynset(std::string synset_file) { std::ifstream fi(synset_file.c_str()); if ( !fi.is_open() ) { std::cerr << "Error opening synset file " << synset_file << std::endl; assert(false); } std::vector<std::string> output; std::string synset, lemma; while ( fi >> synset ) { getline(fi, lemma); output.push_back(lemma); } fi.close(); return output; } void PrintOutputResult(const std::vector<float>& data, const std::vector<std::string>& synset) { if (data.size() != synset.size()) { std::cerr << "Result data and synset size does not match!" << std::endl; } float best_accuracy = 0.0; int best_idx = 0; for ( int i = 0; i < static_cast<int>(data.size()); i++ ) { printf("Accuracy[%d] = %.8f\n", i, data[i]); if ( data[i] > best_accuracy ) { best_accuracy = data[i]; best_idx = i; } } printf("Best Result: [%s] id = %d, accuracy = %.8f\n", synset[best_idx].c_str(), best_idx, best_accuracy); } int main(int argc, char* argv[]) { if (argc < 2) { std::cout << "No test image here." << std::endl << "Usage: ./image-classification-predict apple.jpg" << std::endl; return 0; } std::string test_file; test_file = std::string(argv[1]); // Models path for your model, you have to modify it std::string json_file = "model/Inception/Inception-BN-symbol.json"; std::string param_file = "model/Inception/Inception-BN-0126.params"; std::string synset_file = "model/Inception/synset.txt"; std::string nd_file = "model/Inception/mean_224.nd"; BufferFile json_data(json_file); BufferFile param_data(param_file); // Parameters int dev_type = 1; // 1: cpu, 2: gpu int dev_id = 0; // arbitrary. mx_uint num_input_nodes = 1; // 1 for feedforward const char* input_key[1] = {"data"}; const char** input_keys = input_key; // Image size and channels int width = 224; int height = 224; int channels = 3; const mx_uint input_shape_indptr[2] = { 0, 4 }; const mx_uint input_shape_data[4] = { 1, static_cast<mx_uint>(channels), static_cast<mx_uint>(height), static_cast<mx_uint>(width)}; PredictorHandle pred_hnd = 0; if (json_data.GetLength() == 0 || param_data.GetLength() == 0) { return -1; } // Create Predictor MXPredCreate((const char*)json_data.GetBuffer(), (const char*)param_data.GetBuffer(), static_cast<size_t>(param_data.GetLength()), dev_type, dev_id, num_input_nodes, input_keys, input_shape_indptr, input_shape_data, &pred_hnd); assert(pred_hnd); int image_size = width * height * channels; // Read Mean Data const mx_float* nd_data = NULL; NDListHandle nd_hnd = 0; BufferFile nd_buf(nd_file); if (nd_buf.GetLength() > 0) { mx_uint nd_index = 0; mx_uint nd_len; const mx_uint* nd_shape = 0; const char* nd_key = 0; mx_uint nd_ndim = 0; MXNDListCreate((const char*)nd_buf.GetBuffer(), nd_buf.GetLength(), &nd_hnd, &nd_len); MXNDListGet(nd_hnd, nd_index, &nd_key, &nd_data, &nd_shape, &nd_ndim); } // Read Image Data std::vector<mx_float> image_data = std::vector<mx_float>(image_size); GetImageFile(test_file, image_data.data(), channels, cv::Size(width, height), nd_data); // Set Input Image MXPredSetInput(pred_hnd, "data", image_data.data(), image_size); // Do Predict Forward MXPredForward(pred_hnd); mx_uint output_index = 0; mx_uint *shape = 0; mx_uint shape_len; // Get Output Result MXPredGetOutputShape(pred_hnd, output_index, &shape, &shape_len); size_t size = 1; for (mx_uint i = 0; i < shape_len; ++i) size *= shape[i]; std::vector<float> data(size); MXPredGetOutput(pred_hnd, output_index, &(data[0]), size); // Release NDList if (nd_hnd) MXNDListFree(nd_hnd); // Release Predictor MXPredFree(pred_hnd); // Synset path for your model, you have to modify it std::vector<std::string> synset = LoadSynset(synset_file); // Print Output Data PrintOutputResult(data, synset); return 0; }
fix shape order bug (#6136)
fix shape order bug (#6136)
C++
apache-2.0
Guneet-Dhillon/mxnet,Guneet-Dhillon/mxnet,Guneet-Dhillon/mxnet,Guneet-Dhillon/mxnet,Guneet-Dhillon/mxnet,Guneet-Dhillon/mxnet,Guneet-Dhillon/mxnet,Guneet-Dhillon/mxnet,Guneet-Dhillon/mxnet
f08afe6f8912de9dc082926516a5962b3defc773
cc/subtle/aes_cmac_boringssl.cc
cc/subtle/aes_cmac_boringssl.cc
// Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /////////////////////////////////////////////////////////////////////////////// #include "tink/subtle/aes_cmac_boringssl.h" #include <string> #include "absl/memory/memory.h" #include "absl/status/status.h" #include "openssl/cmac.h" #include "openssl/evp.h" #include "tink/internal/ssl_unique_ptr.h" #include "tink/internal/util.h" #include "tink/subtle/subtle_util.h" #include "tink/util/errors.h" #include "tink/util/status.h" #include "tink/util/statusor.h" namespace crypto { namespace tink { namespace subtle { namespace { // CMAC key sizes in bytes. // The small key size is used only to check RFC 4493's test vectors due to // the attack described in // https://www.math.uwaterloo.ca/~ajmeneze/publications/tightness.pdf. We // check this restriction in AesCmacManager. static constexpr size_t kSmallKeySize = 16; static constexpr size_t kBigKeySize = 32; static constexpr size_t kMaxTagSize = 16; #ifndef OPENSSL_IS_BORINGSSL util::StatusOr<const EVP_CIPHER*> CipherForKeySize(size_t key_size) { switch (key_size) { case 16: return EVP_aes_128_cbc(); case 32: return EVP_aes_256_cbc(); } return ToStatusF(absl::StatusCode::kInvalidArgument, "Invalid key size %d", key_size); } #endif } // namespace // static util::StatusOr<std::unique_ptr<Mac>> AesCmacBoringSsl::New(util::SecretData key, uint32_t tag_size) { auto status = internal::CheckFipsCompatibility<AesCmacBoringSsl>(); if (!status.ok()) return status; if (key.size() != kSmallKeySize && key.size() != kBigKeySize) { return ToStatusF(absl::StatusCode::kInvalidArgument, "Invalid key size: expected %d or %d, found %d", kSmallKeySize, kBigKeySize, key.size()); } if (tag_size > kMaxTagSize) { return ToStatusF(absl::StatusCode::kInvalidArgument, "Invalid tag size: expected lower than %d, found %d", kMaxTagSize, tag_size); } return {absl::WrapUnique(new AesCmacBoringSsl(std::move(key), tag_size))}; } util::StatusOr<std::string> AesCmacBoringSsl::ComputeMac( absl::string_view data) const { // BoringSSL expects a non-null pointer for data, // regardless of whether the size is 0. data = internal::EnsureStringNonNull(data); std::string result; ResizeStringUninitialized(&result, kMaxTagSize); #ifdef OPENSSL_IS_BORINGSSL const int res = AES_CMAC(reinterpret_cast<uint8_t*>(&result[0]), key_.data(), key_.size(), reinterpret_cast<const uint8_t*>(data.data()), data.size()); #else internal::SslUniquePtr<CMAC_CTX> context(CMAC_CTX_new()); util::StatusOr<const EVP_CIPHER*> cipher = CipherForKeySize(key_.size()); if (!cipher.ok()) return cipher.status(); if (CMAC_Init(context.get(), reinterpret_cast<const uint8_t*>(&key_[0]), key_.size(), *cipher, nullptr) <= 0) { return util::Status(absl::StatusCode::kInternal, "Failed to compute CMAC"); } if (CMAC_Update(context.get(), reinterpret_cast<const uint8_t*>(data.data()), data.size()) <= 0) { return util::Status(absl::StatusCode::kInternal, "Failed to compute CMAC"); } size_t len = 0; const int res = CMAC_Final(context.get(), reinterpret_cast<uint8_t*>(&result[0]), &len); #endif if (res == 0) { return util::Status(absl::StatusCode::kInternal, "Failed to compute CMAC"); } result.resize(tag_size_); return result; } util::Status AesCmacBoringSsl::VerifyMac(absl::string_view mac, absl::string_view data) const { if (mac.size() != tag_size_) { return ToStatusF(absl::StatusCode::kInvalidArgument, "Incorrect tag size: expected %d, found %d", tag_size_, mac.size()); } util::StatusOr<std::string> computed_mac = ComputeMac(data); if (!computed_mac.ok()) return computed_mac.status(); if (CRYPTO_memcmp(computed_mac->data(), mac.data(), tag_size_) != 0) { return util::Status(absl::StatusCode::kInvalidArgument, "CMAC verification failed"); } return util::OkStatus(); } } // namespace subtle } // namespace tink } // namespace crypto
// Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /////////////////////////////////////////////////////////////////////////////// #include "tink/subtle/aes_cmac_boringssl.h" #include <cstdint> #include <string> #include "absl/memory/memory.h" #include "absl/status/status.h" #include "openssl/cmac.h" #include "openssl/evp.h" #include "tink/internal/ssl_unique_ptr.h" #include "tink/internal/util.h" #include "tink/subtle/subtle_util.h" #include "tink/util/errors.h" #include "tink/util/status.h" #include "tink/util/statusor.h" namespace crypto { namespace tink { namespace subtle { namespace { // CMAC key sizes in bytes. // The small key size is used only to check RFC 4493's test vectors due to // the attack described in // https://www.math.uwaterloo.ca/~ajmeneze/publications/tightness.pdf. We // check this restriction in AesCmacManager. static constexpr size_t kSmallKeySize = 16; static constexpr size_t kBigKeySize = 32; static constexpr size_t kMaxTagSize = 16; util::StatusOr<const EVP_CIPHER*> GetAesCbcCipherForKeySize(size_t key_size) { switch (key_size) { case 16: return EVP_aes_128_cbc(); case 32: return EVP_aes_256_cbc(); } return ToStatusF(absl::StatusCode::kInvalidArgument, "Invalid key size %d", key_size); } } // namespace // static util::StatusOr<std::unique_ptr<Mac>> AesCmacBoringSsl::New(util::SecretData key, uint32_t tag_size) { auto status = internal::CheckFipsCompatibility<AesCmacBoringSsl>(); if (!status.ok()) return status; if (key.size() != kSmallKeySize && key.size() != kBigKeySize) { return ToStatusF(absl::StatusCode::kInvalidArgument, "Invalid key size: expected %d or %d, found %d", kSmallKeySize, kBigKeySize, key.size()); } if (tag_size > kMaxTagSize) { return ToStatusF(absl::StatusCode::kInvalidArgument, "Invalid tag size: expected lower than %d, found %d", kMaxTagSize, tag_size); } return {absl::WrapUnique(new AesCmacBoringSsl(std::move(key), tag_size))}; } util::StatusOr<std::string> AesCmacBoringSsl::ComputeMac( absl::string_view data) const { // BoringSSL expects a non-null pointer for data, // regardless of whether the size is 0. data = internal::EnsureStringNonNull(data); std::string result; ResizeStringUninitialized(&result, kMaxTagSize); internal::SslUniquePtr<CMAC_CTX> context(CMAC_CTX_new()); util::StatusOr<const EVP_CIPHER*> cipher = GetAesCbcCipherForKeySize(key_.size()); if (!cipher.ok()) { return cipher.status(); } size_t len = 0; const uint8_t* key_ptr = reinterpret_cast<const uint8_t*>(&key_[0]); const uint8_t* data_ptr = reinterpret_cast<const uint8_t*>(data.data()); uint8_t* result_ptr = reinterpret_cast<uint8_t*>(&result[0]); if (CMAC_Init(context.get(), key_ptr, key_.size(), *cipher, nullptr) <= 0 || CMAC_Update(context.get(), data_ptr, data.size()) <= 0 || CMAC_Final(context.get(), result_ptr, &len) == 0) { return util::Status(absl::StatusCode::kInternal, "Failed to compute CMAC"); } result.resize(tag_size_); return result; } util::Status AesCmacBoringSsl::VerifyMac(absl::string_view mac, absl::string_view data) const { if (mac.size() != tag_size_) { return ToStatusF(absl::StatusCode::kInvalidArgument, "Incorrect tag size: expected %d, found %d", tag_size_, mac.size()); } util::StatusOr<std::string> computed_mac = ComputeMac(data); if (!computed_mac.ok()) return computed_mac.status(); if (CRYPTO_memcmp(computed_mac->data(), mac.data(), tag_size_) != 0) { return util::Status(absl::StatusCode::kInvalidArgument, "CMAC verification failed"); } return util::OkStatus(); } } // namespace subtle } // namespace tink } // namespace crypto
Remove use of BoringSSL-only `AES_CMAC` oneshot API in favor of a OpenSSL compatible set of calls to the `CMAC_*` interface
Remove use of BoringSSL-only `AES_CMAC` oneshot API in favor of a OpenSSL compatible set of calls to the `CMAC_*` interface The `AES_CMAC` oneshot API [1] is essentially a wrapper around the `CMAC_*` APIs in BoringSSL. [1] https://github.com/google/boringssl/blob/master/crypto/cmac/cmac.c#L84 PiperOrigin-RevId: 424051407
C++
apache-2.0
google/tink,google/tink,google/tink,google/tink,google/tink,google/tink,google/tink,google/tink
303c8bcaa87561eefd03652a52779018f1792c99
src/module.cpp
src/module.cpp
#include "module.h" Module::Module(std::string modName, std::map<std::string, std::string> conf, std::string workDir, unsigned short debug, Base* botptr) : moduleName(modName), config(conf), workingDir(workDir), debugLevel(debug), bot(botptr), priority(PRI_NORMAL) {} // The default priority is PRI_NORMAL but can be overridden in the subclass's constructor bool Module::onLoadComplete() { return true; } void Module::onUnload() {} void Module::onRehash() {} void Module::onModuleLoad(std::string modName) {} void Module::onModuleUnload(std::string modName) {} bool Module::forceKeepAlive() { return false; } void Module::rehash(std::map<std::string, std::string> conf) { config = conf; } void Module::endDebug() { debugLevel = 0; } MsgAction Module::onChanMsg(std::string server, std::string client, std::string channel, char status, std::string nick, std::string message) { return MSG_CONTINUE; } MsgAction Module::onUserMsg(std::string server, std::string client, std::string nick, std::string message) { return MSG_CONTINUE; } MsgAction Module::onChanNotice(std::string server, std::string client, std::string channel, char status, std::string nick, std::string message) { return MSG_CONTINUE; } MsgAction Module::onUserNotice(std::string server, std::string client, std::string nick, std::string message) { return MSG_CONTINUE; } MsgAction Module::onChanCTCP(std::string server, std::string client, std::string channel, char status, std::string nick, std::string ctcp, std::string data) { return MSG_CONTINUE; } MsgAction Module::onUserCTCP(std::string server, std::string client, std::string nick, std::string ctcp, std::string data) { return MSG_CONTINUE; } MsgAction Module::onChanCTCPReply(std::string server, std::string client, std::string channel, char status, std::string nick, std::string ctcp, std::string data) { return MSG_CONTINUE; } MsgAction Module::onUserCTCPReply(std::string server, std::string client, std::string nick, std::string ctcp, std::string data) { return MSG_CONTINUE; } void Module::onChanMode(std::string server, std::string client, std::string channel, bool add, std::string mode, std::string param) {} void Module::onUserMode(std::string server, std::string client, bool add, std::string mode) {} void Module::onUserSNOMask(std::string server, std::string client, bool add, std::string snomask) {} void Module::onChanTopic(std::string server, std::string client, std::string channel, std::string topic) {} void Module::onChanJoin(std::string server, std::string client, std::string channel, std::string nick) {} void Module::onChanPart(std::string server, std::string client, std::string channel, std::string nick, std::string reason) {} void Module::onUserConnect(std::string server, std::string nick) {} void Module::onUserQuit(std::string server, std::string client, std::string nick, std::string reason) {} void Module::onUserNick(std::string server, std::string client, std::string oldNick, std::string newNick) {} void Module::onNumeric(std::string server, std::string client, std::string numeric, std::vector<std::string> data) {} void Module::onOper(std::string server, std::string nick, std::string operType) {} void Module::onSNotice(std::string server, std::string snotype, std::string message) {} void Module::onMetadata(std::string server, std::string target, std::string dataKey, std::string dataValue) {} void Module::onServerData(std::string server, std::string dataType, std::vector<std::string> params) {} void Module::onXLineAdd(std::string server, std::string lineType, std::string mask, std::string setter, time_t expiry, std::string reason) {} void Module::onXLineRemove(std::string server, std::string lineType, std::string mask) {} void Module::onServerConnect (std::string server, std::string newServerName) {} void Module::onServerQuit (std::string server, std::string quitServerName, std::string reason) {} void Module::onOtherData(std::string server, std::string client, std::vector<std::string> lineTokens) {} void Module::onChanMsgOut(std::string server, std::string client, std::string channel, char status, std::string &message) {} void Module::onChanMsgSend(std::string server, std::string client, std::string channel, char status, std::string message) {} void Module::onUserMsgOut(std::string server, std::string client, std::string nick, std::string &message) {} void Module::onUserMsgSend(std::string server, std::string client, std::string nick, std::string message) {} void Module::onChanNoticeOut(std::string server, std::string client, std::string channel, char status, std::string &message) {} void Module::onChanNoticeSend(std::string server, std::string client, std::string channel, char status, std::string message) {} void Module::onUserNoticeOut(std::string server, std::string client, std::string nick, std::string &message) {} void Module::onUserNoticeSend(std::string server, std::string client, std::string nick, std::string message) {} void Module::onChanCTCPOut(std::string server, std::string client, std::string channel, char status, std::string &ctcp, std::string &params) {} void Module::onChanCTCPSend(std::string server, std::string client, std::string channel, char status, std::string ctcp, std::string params) {} void Module::onUserCTCPOut(std::string server, std::string client, std::string nick, std::string &ctcp, std::string &params) {} void Module::onUserCTCPSend(std::string server, std::string client, std::string nick, std::string ctcp, std::string params) {} void Module::onChanCTCPReplyOut(std::string server, std::string client, std::string channel, char status, std::string &ctcp, std::string &params) {} void Module::onChanCTCPReplySend(std::string server, std::string client, std::string channel, char status, std::string ctcp, std::string params) {} void Module::onUserCTCPReplyOut(std::string server, std::string client, std::string nick, std::string &ctcp, std::string &params) {} void Module::onUserCTCPReplySend(std::string server, std::string client, std::string nick, std::string ctcp, std::string params) {} std::string Module::description() { return "A description has not been provided."; } std::list<std::string> Module::provides() { return std::list<std::string>(); } std::list<std::string> Module::requires() { return std::list<std::string>(); } std::list<std::string> Module::supports() { return std::list<std::string>(); } void Module::sendPrivMsg(std::string server, std::string client, std::string target, std::string message) { bot->sendPrivMsg(server, client, target, message); } void Module::sendNotice(std::string server, std::string client, std::string target, std::string message) { bot->sendNotice(server, client, target, message); } void Module::sendCTCP(std::string server, std::string client, std::string target, std::string ctcp, std::string params) { bot->sendCTCP(server, client, target, ctcp, params); } void Module::sendCTCPReply(std::string server, std::string client, std::string target, std::string ctcp, std::string params) { bot->sendCTCPReply(server, client, target, ctcp, params); } void Module::setMode(std::string server, std::string client, std::string target, std::list<std::string> setModes, std::list<std::string> delModes) { bot->setMode(server, client, target, setModes, delModes); } void Module::setSNOMask(std::string server, std::string client, std::string snomask) { bot->setSNOMask(server, client, snomask); } void Module::setChanTopic(std::string server, std::string client, std::string channel, std::string topic) { bot->setChanTopic(server, client, channel, topic); } void Module::joinChannel(std::string server, std::string client, std::string channel, std::string key) { bot->joinChannel(server, client, channel, key); } void Module::partChannel(std::string server, std::string client, std::string channel, std::string reason) { bot->partChannel(server, client, channel, reason); } void Module::connectServer(std::string server) { bot->connectServer(server); } std::string Module::addClient(std::string server, std::string nick, std::string ident, std::string host, std::string gecos) { return bot->addClient(server, nick, ident, host, gecos); } void Module::removeClient(std::string server, std::string client) { bot->removeClient(server, client); } void Module::quitServer(std::string server) { bot->disconnectServer(server); } void Module::changeNick(std::string server, std::string client, std::string newNick) { bot->changeNick(server, client, newNick); } void Module::oper(std::string server, std::string client, std::string username, std::string password) { bot->oper(server, client, username, password); } void Module::sendSNotice(std::string server, std::string snomask, std::string message) { bot->sendSNotice(server, snomask, message); } void Module::setMetadata(std::string server, std::string target, std::string key, std::string value) { bot->setMetadata(server, target, key, value); } void Module::setXLine(std::string server, std::string client, std::string linetype, std::string mask, time_t duration, std::string reason) { bot->setXLine(server, client, linetype, mask, duration, reason); } void Module::delXLine(std::string server, std::string client, std::string linetype, std::string mask) { bot->delXLine(server, client, linetype, mask); } void Module::sendOtherData(std::string server, std::string client, std::string line) { bot->sendOtherData(server, client, line); }
#include "module.h" Module::Module(std::string modName, std::map<std::string, std::string> conf, std::string workDir, unsigned short debug, Base* botptr) : moduleName(modName), workingDir(workDir), config(conf), debugLevel(debug), bot(botptr), priority(PRI_NORMAL) {} // The default priority is PRI_NORMAL but can be overridden in the subclass's constructor bool Module::onLoadComplete() { return true; } void Module::onUnload() {} void Module::onRehash() {} void Module::onModuleLoad(std::string modName) {} void Module::onModuleUnload(std::string modName) {} bool Module::forceKeepAlive() { return false; } void Module::rehash(std::map<std::string, std::string> conf) { config = conf; } void Module::endDebug() { debugLevel = 0; } MsgAction Module::onChanMsg(std::string server, std::string client, std::string channel, char status, std::string nick, std::string message) { return MSG_CONTINUE; } MsgAction Module::onUserMsg(std::string server, std::string client, std::string nick, std::string message) { return MSG_CONTINUE; } MsgAction Module::onChanNotice(std::string server, std::string client, std::string channel, char status, std::string nick, std::string message) { return MSG_CONTINUE; } MsgAction Module::onUserNotice(std::string server, std::string client, std::string nick, std::string message) { return MSG_CONTINUE; } MsgAction Module::onChanCTCP(std::string server, std::string client, std::string channel, char status, std::string nick, std::string ctcp, std::string data) { return MSG_CONTINUE; } MsgAction Module::onUserCTCP(std::string server, std::string client, std::string nick, std::string ctcp, std::string data) { return MSG_CONTINUE; } MsgAction Module::onChanCTCPReply(std::string server, std::string client, std::string channel, char status, std::string nick, std::string ctcp, std::string data) { return MSG_CONTINUE; } MsgAction Module::onUserCTCPReply(std::string server, std::string client, std::string nick, std::string ctcp, std::string data) { return MSG_CONTINUE; } void Module::onChanMode(std::string server, std::string client, std::string channel, bool add, std::string mode, std::string param) {} void Module::onUserMode(std::string server, std::string client, bool add, std::string mode) {} void Module::onUserSNOMask(std::string server, std::string client, bool add, std::string snomask) {} void Module::onChanTopic(std::string server, std::string client, std::string channel, std::string topic) {} void Module::onChanJoin(std::string server, std::string client, std::string channel, std::string nick) {} void Module::onChanPart(std::string server, std::string client, std::string channel, std::string nick, std::string reason) {} void Module::onUserConnect(std::string server, std::string nick) {} void Module::onUserQuit(std::string server, std::string client, std::string nick, std::string reason) {} void Module::onUserNick(std::string server, std::string client, std::string oldNick, std::string newNick) {} void Module::onNumeric(std::string server, std::string client, std::string numeric, std::vector<std::string> data) {} void Module::onOper(std::string server, std::string nick, std::string operType) {} void Module::onSNotice(std::string server, std::string snotype, std::string message) {} void Module::onMetadata(std::string server, std::string target, std::string dataKey, std::string dataValue) {} void Module::onServerData(std::string server, std::string dataType, std::vector<std::string> params) {} void Module::onXLineAdd(std::string server, std::string lineType, std::string mask, std::string setter, time_t expiry, std::string reason) {} void Module::onXLineRemove(std::string server, std::string lineType, std::string mask) {} void Module::onServerConnect (std::string server, std::string newServerName) {} void Module::onServerQuit (std::string server, std::string quitServerName, std::string reason) {} void Module::onOtherData(std::string server, std::string client, std::vector<std::string> lineTokens) {} void Module::onChanMsgOut(std::string server, std::string client, std::string channel, char status, std::string &message) {} void Module::onChanMsgSend(std::string server, std::string client, std::string channel, char status, std::string message) {} void Module::onUserMsgOut(std::string server, std::string client, std::string nick, std::string &message) {} void Module::onUserMsgSend(std::string server, std::string client, std::string nick, std::string message) {} void Module::onChanNoticeOut(std::string server, std::string client, std::string channel, char status, std::string &message) {} void Module::onChanNoticeSend(std::string server, std::string client, std::string channel, char status, std::string message) {} void Module::onUserNoticeOut(std::string server, std::string client, std::string nick, std::string &message) {} void Module::onUserNoticeSend(std::string server, std::string client, std::string nick, std::string message) {} void Module::onChanCTCPOut(std::string server, std::string client, std::string channel, char status, std::string &ctcp, std::string &params) {} void Module::onChanCTCPSend(std::string server, std::string client, std::string channel, char status, std::string ctcp, std::string params) {} void Module::onUserCTCPOut(std::string server, std::string client, std::string nick, std::string &ctcp, std::string &params) {} void Module::onUserCTCPSend(std::string server, std::string client, std::string nick, std::string ctcp, std::string params) {} void Module::onChanCTCPReplyOut(std::string server, std::string client, std::string channel, char status, std::string &ctcp, std::string &params) {} void Module::onChanCTCPReplySend(std::string server, std::string client, std::string channel, char status, std::string ctcp, std::string params) {} void Module::onUserCTCPReplyOut(std::string server, std::string client, std::string nick, std::string &ctcp, std::string &params) {} void Module::onUserCTCPReplySend(std::string server, std::string client, std::string nick, std::string ctcp, std::string params) {} std::string Module::description() { return "A description has not been provided."; } std::list<std::string> Module::provides() { return std::list<std::string>(); } std::list<std::string> Module::requires() { return std::list<std::string>(); } std::list<std::string> Module::supports() { return std::list<std::string>(); } void Module::sendPrivMsg(std::string server, std::string client, std::string target, std::string message) { bot->sendPrivMsg(server, client, target, message); } void Module::sendNotice(std::string server, std::string client, std::string target, std::string message) { bot->sendNotice(server, client, target, message); } void Module::sendCTCP(std::string server, std::string client, std::string target, std::string ctcp, std::string params) { bot->sendCTCP(server, client, target, ctcp, params); } void Module::sendCTCPReply(std::string server, std::string client, std::string target, std::string ctcp, std::string params) { bot->sendCTCPReply(server, client, target, ctcp, params); } void Module::setMode(std::string server, std::string client, std::string target, std::list<std::string> setModes, std::list<std::string> delModes) { bot->setMode(server, client, target, setModes, delModes); } void Module::setSNOMask(std::string server, std::string client, std::string snomask) { bot->setSNOMask(server, client, snomask); } void Module::setChanTopic(std::string server, std::string client, std::string channel, std::string topic) { bot->setChanTopic(server, client, channel, topic); } void Module::joinChannel(std::string server, std::string client, std::string channel, std::string key) { bot->joinChannel(server, client, channel, key); } void Module::partChannel(std::string server, std::string client, std::string channel, std::string reason) { bot->partChannel(server, client, channel, reason); } void Module::connectServer(std::string server) { bot->connectServer(server); } std::string Module::addClient(std::string server, std::string nick, std::string ident, std::string host, std::string gecos) { return bot->addClient(server, nick, ident, host, gecos); } void Module::removeClient(std::string server, std::string client) { bot->removeClient(server, client); } void Module::quitServer(std::string server) { bot->disconnectServer(server); } void Module::changeNick(std::string server, std::string client, std::string newNick) { bot->changeNick(server, client, newNick); } void Module::oper(std::string server, std::string client, std::string username, std::string password) { bot->oper(server, client, username, password); } void Module::sendSNotice(std::string server, std::string snomask, std::string message) { bot->sendSNotice(server, snomask, message); } void Module::setMetadata(std::string server, std::string target, std::string key, std::string value) { bot->setMetadata(server, target, key, value); } void Module::setXLine(std::string server, std::string client, std::string linetype, std::string mask, time_t duration, std::string reason) { bot->setXLine(server, client, linetype, mask, duration, reason); } void Module::delXLine(std::string server, std::string client, std::string linetype, std::string mask) { bot->delXLine(server, client, linetype, mask); } void Module::sendOtherData(std::string server, std::string client, std::string line) { bot->sendOtherData(server, client, line); }
Fix the module initialization list order to be the correct order of declare
Fix the module initialization list order to be the correct order of declare
C++
mit
ElementalAlchemist/RoBoBo,ElementalAlchemist/RoBoBo
c7b48eade9a86db9518740239beb6a9be4e48ce7
io/src/robot_eye_grabber.cpp
io/src/robot_eye_grabber.cpp
/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2012-, Open Perception, Inc. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder(s) 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 <pcl/io/robot_eye_grabber.h> #include <pcl/console/print.h> ///////////////////////////////////////////////////////////////////////////// pcl::RobotEyeGrabber::RobotEyeGrabber () : terminate_thread_ (false) , signal_point_cloud_size_ (1000) , data_port_ (443) , sensor_address_ (boost::asio::ip::address_v4::any ()) { point_cloud_signal_ = createSignal<sig_cb_robot_eye_point_cloud_xyzi> (); resetPointCloud (); } ///////////////////////////////////////////////////////////////////////////// pcl::RobotEyeGrabber::RobotEyeGrabber (const boost::asio::ip::address& ipAddress, unsigned short port) : terminate_thread_ (false) , signal_point_cloud_size_ (1000) , data_port_ (port) , sensor_address_ (ipAddress) { point_cloud_signal_ = createSignal<sig_cb_robot_eye_point_cloud_xyzi> (); resetPointCloud (); } ///////////////////////////////////////////////////////////////////////////// pcl::RobotEyeGrabber::~RobotEyeGrabber () throw () { stop (); disconnect_all_slots<sig_cb_robot_eye_point_cloud_xyzi> (); } ///////////////////////////////////////////////////////////////////////////// std::string pcl::RobotEyeGrabber::getName () const { return (std::string ("Ocular Robotics RobotEye Grabber")); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// float pcl::RobotEyeGrabber::getFramesPerSecond () const { return (0.0f); } ///////////////////////////////////////////////////////////////////////////// bool pcl::RobotEyeGrabber::isRunning () const { return (socket_thread_ != NULL); } ///////////////////////////////////////////////////////////////////////////// unsigned short pcl::RobotEyeGrabber::getDataPort () const { return (data_port_); } ///////////////////////////////////////////////////////////////////////////// void pcl::RobotEyeGrabber::setDataPort (const unsigned short port) { data_port_ = port; } ///////////////////////////////////////////////////////////////////////////// const boost::asio::ip::address& pcl::RobotEyeGrabber::getSensorAddress () const { return (sensor_address_); } ///////////////////////////////////////////////////////////////////////////// void pcl::RobotEyeGrabber::setSensorAddress (const boost::asio::ip::address& ipAddress) { sensor_address_ = ipAddress; } ///////////////////////////////////////////////////////////////////////////// std::size_t pcl::RobotEyeGrabber::getSignalPointCloudSize () const { return (signal_point_cloud_size_); } ///////////////////////////////////////////////////////////////////////////// void pcl::RobotEyeGrabber::setSignalPointCloudSize (std::size_t numberOfPoints) { signal_point_cloud_size_ = numberOfPoints; } ///////////////////////////////////////////////////////////////////////////// boost::shared_ptr<pcl::PointCloud<pcl::PointXYZI> > pcl::RobotEyeGrabber::getPointCloud () const { return point_cloud_xyzi_; } ///////////////////////////////////////////////////////////////////////////// void pcl::RobotEyeGrabber::resetPointCloud () { point_cloud_xyzi_.reset (new pcl::PointCloud<pcl::PointXYZI>); point_cloud_xyzi_->is_dense = true; } ///////////////////////////////////////////////////////////////////////////// void pcl::RobotEyeGrabber::consumerThreadLoop () { while (true) { boost::shared_array<unsigned char> data; if (!packet_queue_.dequeue (data)) return; convertPacketData (data.get(), 464); } } ///////////////////////////////////////////////////////////////////////////// void pcl::RobotEyeGrabber::convertPacketData (unsigned char *dataPacket, size_t length) { const size_t bytesPerPoint = 8; const size_t totalPoints = length / bytesPerPoint; for (int i = 0; i < totalPoints; ++i) { unsigned char* pointData = dataPacket + i*bytesPerPoint; PointXYZI xyzi; computeXYZI (xyzi, dataPacket + i*bytesPerPoint); if ((boost::math::isnan)(xyzi.x) || (boost::math::isnan)(xyzi.y) || (boost::math::isnan)(xyzi.z)) { continue; } point_cloud_xyzi_->push_back (xyzi); } if (point_cloud_xyzi_->size () > signal_point_cloud_size_) { if (point_cloud_signal_->num_slots () > 0) point_cloud_signal_->operator() (point_cloud_xyzi_); resetPointCloud (); } } ///////////////////////////////////////////////////////////////////////////// void pcl::RobotEyeGrabber::computeXYZI (pcl::PointXYZI& point, unsigned char* pointData) { uint16_t buffer = 0; double az = 0.0; double el = 0.0; double range = 0.0; uint16_t intensity = 0; buffer = 0x00; buffer = pointData[0] << 8; buffer |= pointData[1]; // First 2-byte read will be Azimuth az = (buffer / 100.0); buffer = 0x00; buffer = pointData[2] << 8; buffer |= pointData[3]; // Second 2-byte read will be Elevation el = (signed short int)buffer / 100.0; buffer = 0x00; buffer = pointData[4] << 8; buffer |= pointData[5]; // Third 2-byte read will be Range range = (signed short int)buffer / 100.0; buffer = 0x00; buffer = pointData[6] << 8; buffer |= pointData[7]; // Fourth 2-byte read will be Intensity intensity = buffer; point.x = range * std::cos (el * M_PI/180) * std::sin (az * M_PI/180); point.y = range * std::cos (el * M_PI/180) * std::cos (az * M_PI/180); point.z = range * std::sin (el * M_PI/180); point.intensity = intensity; } ///////////////////////////////////////////////////////////////////////////// void pcl::RobotEyeGrabber::socketThreadLoop() { asyncSocketReceive(); io_service_.reset(); io_service_.run(); } ///////////////////////////////////////////////////////////////////////////// void pcl::RobotEyeGrabber::asyncSocketReceive() { // expecting exactly 464 bytes, using a larger buffer so that if a // larger packet arrives unexpectedly we'll notice it. socket_->async_receive_from(boost::asio::buffer(receive_buffer_, 500), sender_endpoint_, boost::bind(&RobotEyeGrabber::socketCallback, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } ///////////////////////////////////////////////////////////////////////////// void pcl::RobotEyeGrabber::socketCallback(const boost::system::error_code& error, std::size_t numberOfBytes) { if (terminate_thread_) return; if (sensor_address_ == boost::asio::ip::address_v4::any () || sensor_address_ == sender_endpoint_.address ()) { if (numberOfBytes == 464) { unsigned char *dup = new unsigned char[numberOfBytes]; memcpy (dup, receive_buffer_, numberOfBytes); packet_queue_.enqueue (boost::shared_array<unsigned char>(dup)); } } asyncSocketReceive (); } ///////////////////////////////////////////////////////////////////////////// void pcl::RobotEyeGrabber::start () { if (isRunning ()) return; boost::asio::ip::udp::endpoint destinationEndpoint (boost::asio::ip::address_v4::any (), data_port_); try { socket_.reset (new boost::asio::ip::udp::socket (io_service_, destinationEndpoint)); } catch (std::exception &e) { PCL_ERROR ("[pcl::RobotEyeGrabber::start] Unable to bind to socket! %s\n", e.what ()); return; } terminate_thread_ = false; resetPointCloud (); consumer_thread_.reset(new boost::thread (boost::bind (&RobotEyeGrabber::consumerThreadLoop, this))); socket_thread_.reset(new boost::thread (boost::bind (&RobotEyeGrabber::socketThreadLoop, this))); } ///////////////////////////////////////////////////////////////////////////// void pcl::RobotEyeGrabber::stop () { if (!isRunning ()) return; terminate_thread_ = true; socket_->close (); io_service_.stop (); socket_thread_->join (); socket_thread_.reset (); socket_.reset(); packet_queue_.stopQueue (); consumer_thread_->join (); consumer_thread_.reset (); }
/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2012-, Open Perception, Inc. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder(s) 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 <pcl/io/robot_eye_grabber.h> #include <pcl/console/print.h> ///////////////////////////////////////////////////////////////////////////// pcl::RobotEyeGrabber::RobotEyeGrabber () : terminate_thread_ (false) , signal_point_cloud_size_ (1000) , data_port_ (443) , sensor_address_ (boost::asio::ip::address_v4::any ()) { point_cloud_signal_ = createSignal<sig_cb_robot_eye_point_cloud_xyzi> (); resetPointCloud (); } ///////////////////////////////////////////////////////////////////////////// pcl::RobotEyeGrabber::RobotEyeGrabber (const boost::asio::ip::address& ipAddress, unsigned short port) : terminate_thread_ (false) , signal_point_cloud_size_ (1000) , data_port_ (port) , sensor_address_ (ipAddress) { point_cloud_signal_ = createSignal<sig_cb_robot_eye_point_cloud_xyzi> (); resetPointCloud (); } ///////////////////////////////////////////////////////////////////////////// pcl::RobotEyeGrabber::~RobotEyeGrabber () throw () { stop (); disconnect_all_slots<sig_cb_robot_eye_point_cloud_xyzi> (); } ///////////////////////////////////////////////////////////////////////////// std::string pcl::RobotEyeGrabber::getName () const { return (std::string ("Ocular Robotics RobotEye Grabber")); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// float pcl::RobotEyeGrabber::getFramesPerSecond () const { return (0.0f); } ///////////////////////////////////////////////////////////////////////////// bool pcl::RobotEyeGrabber::isRunning () const { return (socket_thread_ != NULL); } ///////////////////////////////////////////////////////////////////////////// unsigned short pcl::RobotEyeGrabber::getDataPort () const { return (data_port_); } ///////////////////////////////////////////////////////////////////////////// void pcl::RobotEyeGrabber::setDataPort (const unsigned short port) { data_port_ = port; } ///////////////////////////////////////////////////////////////////////////// const boost::asio::ip::address& pcl::RobotEyeGrabber::getSensorAddress () const { return (sensor_address_); } ///////////////////////////////////////////////////////////////////////////// void pcl::RobotEyeGrabber::setSensorAddress (const boost::asio::ip::address& ipAddress) { sensor_address_ = ipAddress; } ///////////////////////////////////////////////////////////////////////////// std::size_t pcl::RobotEyeGrabber::getSignalPointCloudSize () const { return (signal_point_cloud_size_); } ///////////////////////////////////////////////////////////////////////////// void pcl::RobotEyeGrabber::setSignalPointCloudSize (std::size_t numberOfPoints) { signal_point_cloud_size_ = numberOfPoints; } ///////////////////////////////////////////////////////////////////////////// boost::shared_ptr<pcl::PointCloud<pcl::PointXYZI> > pcl::RobotEyeGrabber::getPointCloud () const { return point_cloud_xyzi_; } ///////////////////////////////////////////////////////////////////////////// void pcl::RobotEyeGrabber::resetPointCloud () { point_cloud_xyzi_.reset (new pcl::PointCloud<pcl::PointXYZI>); point_cloud_xyzi_->is_dense = true; } ///////////////////////////////////////////////////////////////////////////// void pcl::RobotEyeGrabber::consumerThreadLoop () { while (true) { boost::shared_array<unsigned char> data; if (!packet_queue_.dequeue (data)) return; convertPacketData (data.get(), 464); } } ///////////////////////////////////////////////////////////////////////////// void pcl::RobotEyeGrabber::convertPacketData (unsigned char *dataPacket, size_t length) { const size_t bytesPerPoint = 8; const size_t totalPoints = length / bytesPerPoint; for (int i = 0; i < totalPoints; ++i) { unsigned char* pointData = dataPacket + i*bytesPerPoint; PointXYZI xyzi; computeXYZI (xyzi, dataPacket + i*bytesPerPoint); if (pcl::isFinite(xyzi)) { point_cloud_xyzi_->push_back (xyzi); } } if (point_cloud_xyzi_->size () > signal_point_cloud_size_) { if (point_cloud_signal_->num_slots () > 0) point_cloud_signal_->operator() (point_cloud_xyzi_); resetPointCloud (); } } ///////////////////////////////////////////////////////////////////////////// void pcl::RobotEyeGrabber::computeXYZI (pcl::PointXYZI& point, unsigned char* pointData) { uint16_t buffer = 0; double az = 0.0; double el = 0.0; double range = 0.0; uint16_t intensity = 0; buffer = 0x00; buffer = pointData[0] << 8; buffer |= pointData[1]; // First 2-byte read will be Azimuth az = (buffer / 100.0); buffer = 0x00; buffer = pointData[2] << 8; buffer |= pointData[3]; // Second 2-byte read will be Elevation el = (signed short int)buffer / 100.0; buffer = 0x00; buffer = pointData[4] << 8; buffer |= pointData[5]; // Third 2-byte read will be Range range = (signed short int)buffer / 100.0; buffer = 0x00; buffer = pointData[6] << 8; buffer |= pointData[7]; // Fourth 2-byte read will be Intensity intensity = buffer; point.x = range * std::cos (el * M_PI/180) * std::sin (az * M_PI/180); point.y = range * std::cos (el * M_PI/180) * std::cos (az * M_PI/180); point.z = range * std::sin (el * M_PI/180); point.intensity = intensity; } ///////////////////////////////////////////////////////////////////////////// void pcl::RobotEyeGrabber::socketThreadLoop() { asyncSocketReceive(); io_service_.reset(); io_service_.run(); } ///////////////////////////////////////////////////////////////////////////// void pcl::RobotEyeGrabber::asyncSocketReceive() { // expecting exactly 464 bytes, using a larger buffer so that if a // larger packet arrives unexpectedly we'll notice it. socket_->async_receive_from(boost::asio::buffer(receive_buffer_, 500), sender_endpoint_, boost::bind(&RobotEyeGrabber::socketCallback, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } ///////////////////////////////////////////////////////////////////////////// void pcl::RobotEyeGrabber::socketCallback(const boost::system::error_code& error, std::size_t numberOfBytes) { if (terminate_thread_) return; if (sensor_address_ == boost::asio::ip::address_v4::any () || sensor_address_ == sender_endpoint_.address ()) { if (numberOfBytes == 464) { unsigned char *dup = new unsigned char[numberOfBytes]; memcpy (dup, receive_buffer_, numberOfBytes); packet_queue_.enqueue (boost::shared_array<unsigned char>(dup)); } } asyncSocketReceive (); } ///////////////////////////////////////////////////////////////////////////// void pcl::RobotEyeGrabber::start () { if (isRunning ()) return; boost::asio::ip::udp::endpoint destinationEndpoint (boost::asio::ip::address_v4::any (), data_port_); try { socket_.reset (new boost::asio::ip::udp::socket (io_service_, destinationEndpoint)); } catch (std::exception &e) { PCL_ERROR ("[pcl::RobotEyeGrabber::start] Unable to bind to socket! %s\n", e.what ()); return; } terminate_thread_ = false; resetPointCloud (); consumer_thread_.reset(new boost::thread (boost::bind (&RobotEyeGrabber::consumerThreadLoop, this))); socket_thread_.reset(new boost::thread (boost::bind (&RobotEyeGrabber::socketThreadLoop, this))); } ///////////////////////////////////////////////////////////////////////////// void pcl::RobotEyeGrabber::stop () { if (!isRunning ()) return; terminate_thread_ = true; socket_->close (); io_service_.stop (); socket_thread_->join (); socket_thread_.reset (); socket_.reset(); packet_queue_.stopQueue (); consumer_thread_->join (); consumer_thread_.reset (); }
Replace boost::math::isnan with check using pcl::isFinite
Replace boost::math::isnan with check using pcl::isFinite
C++
bsd-3-clause
damienjadeduff/pcl,jakobwilm/pcl,zavataafnan/pcl-truck,KevenRing/vlp,LZRS/pcl,fanxiaochen/mypcltest,3dtof/pcl,simonleonard/pcl,wgapl/pcl,mikhail-matrosov/pcl,chenxingzhe/pcl,KevenRing/pcl,Tabjones/pcl,srbhprajapati/pcl,shivmalhotra/pcl,chenxingzhe/pcl,jakobwilm/pcl,MMiknis/pcl,KevenRing/vlp,KevenRing/pcl,pkuhto/pcl,LZRS/pcl,lebronzhang/pcl,shangwuhencc/pcl,RufaelDev/pcc-mp3dg,zhangxaochen/pcl,raydtang/pcl,chenxingzhe/pcl,jakobwilm/pcl,raydtang/pcl,fskuka/pcl,chenxingzhe/pcl,soulsheng/pcl,shangwuhencc/pcl,ResByte/pcl,locnx1984/pcl,starius/pcl,ipa-rmb/pcl,shivmalhotra/pcl,zhangxaochen/pcl,starius/pcl,wgapl/pcl,shangwuhencc/pcl,nh2/pcl,closerbibi/pcl,nikste/pcl,the-glu/pcl,ipa-rmb/pcl,pkuhto/pcl,jeppewalther/kinfu_segmentation,stefanbuettner/pcl,wgapl/pcl,lebronzhang/pcl,KevenRing/pcl,kanster/pcl,nh2/pcl,jeppewalther/kinfu_segmentation,chatchavan/pcl,kanster/pcl,sbec/pcl,LZRS/pcl,stfuchs/pcl,chenxingzhe/pcl,MMiknis/pcl,jakobwilm/pcl,MMiknis/pcl,nikste/pcl,drmateo/pcl,damienjadeduff/pcl,shyamalschandra/pcl,v4hn/pcl,locnx1984/pcl,stefanbuettner/pcl,DaikiMaekawa/pcl,nh2/pcl,lydhr/pcl,srbhprajapati/pcl,drmateo/pcl,RufaelDev/pcc-mp3dg,pkuhto/pcl,stfuchs/pcl,msalvato/pcl_kinfu_highres,stfuchs/pcl,cascheberg/pcl,stfuchs/pcl,v4hn/pcl,3dtof/pcl,mikhail-matrosov/pcl,shangwuhencc/pcl,stefanbuettner/pcl,cascheberg/pcl,DaikiMaekawa/pcl,stefanbuettner/pcl,mikhail-matrosov/pcl,simonleonard/pcl,mschoeler/pcl,pkuhto/pcl,lebronzhang/pcl,ipa-rmb/pcl,cascheberg/pcl,zavataafnan/pcl-truck,starius/pcl,simonleonard/pcl,jeppewalther/kinfu_segmentation,krips89/pcl_newfeatures,mschoeler/pcl,drmateo/pcl,srbhprajapati/pcl,DaikiMaekawa/pcl,ipa-rmb/pcl,KevenRing/pcl,drmateo/pcl,KevenRing/vlp,chatchavan/pcl,fanxiaochen/mypcltest,nikste/pcl,mschoeler/pcl,fanxiaochen/mypcltest,Tabjones/pcl,chatchavan/pcl,soulsheng/pcl,MMiknis/pcl,LZRS/pcl,Tabjones/pcl,mikhail-matrosov/pcl,ResByte/pcl,locnx1984/pcl,damienjadeduff/pcl,krips89/pcl_newfeatures,shyamalschandra/pcl,kanster/pcl,KevenRing/pcl,nh2/pcl,v4hn/pcl,cascheberg/pcl,zhangxaochen/pcl,raydtang/pcl,raydtang/pcl,shivmalhotra/pcl,RufaelDev/pcc-mp3dg,lebronzhang/pcl,jeppewalther/kinfu_segmentation,closerbibi/pcl,3dtof/pcl,Tabjones/pcl,shivmalhotra/pcl,msalvato/pcl_kinfu_highres,starius/pcl,v4hn/pcl,DaikiMaekawa/pcl,locnx1984/pcl,sbec/pcl,raydtang/pcl,starius/pcl,KevenRing/vlp,fskuka/pcl,mschoeler/pcl,fskuka/pcl,mikhail-matrosov/pcl,kanster/pcl,pkuhto/pcl,nikste/pcl,cascheberg/pcl,ipa-rmb/pcl,sbec/pcl,sbec/pcl,fskuka/pcl,RufaelDev/pcc-mp3dg,zhangxaochen/pcl,msalvato/pcl_kinfu_highres,krips89/pcl_newfeatures,ResByte/pcl,lydhr/pcl,closerbibi/pcl,soulsheng/pcl,lydhr/pcl,MMiknis/pcl,soulsheng/pcl,RufaelDev/pcc-mp3dg,the-glu/pcl,zavataafnan/pcl-truck,v4hn/pcl,shyamalschandra/pcl,krips89/pcl_newfeatures,LZRS/pcl,3dtof/pcl,fskuka/pcl,simonleonard/pcl,zhangxaochen/pcl,drmateo/pcl,stefanbuettner/pcl,srbhprajapati/pcl,chatchavan/pcl,the-glu/pcl,KevenRing/vlp,jakobwilm/pcl,simonleonard/pcl,kanster/pcl,srbhprajapati/pcl,shangwuhencc/pcl,locnx1984/pcl,zavataafnan/pcl-truck,shivmalhotra/pcl,mschoeler/pcl,DaikiMaekawa/pcl,msalvato/pcl_kinfu_highres,stfuchs/pcl,krips89/pcl_newfeatures,damienjadeduff/pcl,damienjadeduff/pcl,closerbibi/pcl,lebronzhang/pcl,wgapl/pcl,lydhr/pcl,sbec/pcl,shyamalschandra/pcl,shyamalschandra/pcl,zavataafnan/pcl-truck,closerbibi/pcl,nikste/pcl,wgapl/pcl,fanxiaochen/mypcltest,soulsheng/pcl,3dtof/pcl,fanxiaochen/mypcltest,ResByte/pcl,lydhr/pcl,msalvato/pcl_kinfu_highres,ResByte/pcl,the-glu/pcl,Tabjones/pcl,the-glu/pcl,jeppewalther/kinfu_segmentation
08ae5f310a475f73807df520fa0b50cf7138c4f5
chrome/browser/extensions/extension_file_util_unittest.cc
chrome/browser/extensions/extension_file_util_unittest.cc
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_file_util.h" #include "base/file_util.h" #include "base/scoped_temp_dir.h" #include "base/string_util.h" #include "base/path_service.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/extensions/extension_constants.h" #include "testing/gtest/include/gtest/gtest.h" namespace keys = extension_manifest_keys; TEST(ExtensionFileUtil, MoveDirSafely) { // Create a test directory structure with some data in it. ScopedTempDir temp; ASSERT_TRUE(temp.CreateUniqueTempDir()); FilePath src_path = temp.path().AppendASCII("src"); ASSERT_TRUE(file_util::CreateDirectory(src_path)); std::string data = "foobar"; ASSERT_TRUE(file_util::WriteFile(src_path.AppendASCII("data"), data.c_str(), data.length())); // Move it to a path that doesn't exist yet. FilePath dest_path = temp.path().AppendASCII("dest").AppendASCII("dest"); ASSERT_TRUE(extension_file_util::MoveDirSafely(src_path, dest_path)); // The path should get created. ASSERT_TRUE(file_util::DirectoryExists(dest_path)); // The data should match. std::string data_out; ASSERT_TRUE(file_util::ReadFileToString(dest_path.AppendASCII("data"), &data_out)); ASSERT_EQ(data, data_out); // The src path should be gone. ASSERT_FALSE(file_util::PathExists(src_path)); // Create some new test data. ASSERT_TRUE(file_util::CopyDirectory(dest_path, src_path, true)); // recursive data = "hotdog"; ASSERT_TRUE(file_util::WriteFile(src_path.AppendASCII("data"), data.c_str(), data.length())); // Test again, overwriting the old path. ASSERT_TRUE(extension_file_util::MoveDirSafely(src_path, dest_path)); ASSERT_TRUE(file_util::DirectoryExists(dest_path)); data_out.clear(); ASSERT_TRUE(file_util::ReadFileToString(dest_path.AppendASCII("data"), &data_out)); ASSERT_EQ(data, data_out); ASSERT_FALSE(file_util::PathExists(src_path)); } TEST(ExtensionFileUtil, CompareToInstalledVersion) { // Compare to an existing extension. FilePath install_dir; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir)); install_dir = install_dir.AppendASCII("extensions") .AppendASCII("good") .AppendASCII("Extensions"); const std::string kId = "behllobkkfkfnphdnhnkndlbkcpglgmj"; const std::string kCurrentVersion = "1.0.0.0"; FilePath version_dir; ASSERT_EQ(Extension::UPGRADE, extension_file_util::CompareToInstalledVersion( install_dir, kId, kCurrentVersion, "1.0.0.1", &version_dir)); ASSERT_EQ(Extension::REINSTALL, extension_file_util::CompareToInstalledVersion( install_dir, kId, kCurrentVersion, "1.0.0.0", &version_dir)); ASSERT_EQ(Extension::REINSTALL, extension_file_util::CompareToInstalledVersion( install_dir, kId, kCurrentVersion, "1.0.0", &version_dir)); ASSERT_EQ(Extension::DOWNGRADE, extension_file_util::CompareToInstalledVersion( install_dir, kId, kCurrentVersion, "0.0.1.0", &version_dir)); // Compare to an extension that is missing its manifest file. ScopedTempDir temp; ASSERT_TRUE(temp.CreateUniqueTempDir()); FilePath src = install_dir.AppendASCII(kId).AppendASCII(kCurrentVersion); FilePath dest = temp.path().AppendASCII(kId).AppendASCII(kCurrentVersion); ASSERT_TRUE(file_util::CreateDirectory(dest.DirName())); ASSERT_TRUE(file_util::CopyDirectory(src, dest, true)); ASSERT_TRUE(file_util::Delete(dest.AppendASCII("manifest.json"), false)); ASSERT_EQ(Extension::NEW_INSTALL, extension_file_util::CompareToInstalledVersion( temp.path(), kId, kCurrentVersion, "1.0.0", &version_dir)); // Compare to a non-existent extension. const std::string kMissingVersion = ""; const std::string kBadId = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; ASSERT_EQ(Extension::NEW_INSTALL, extension_file_util::CompareToInstalledVersion( temp.path(), kBadId, kMissingVersion, "1.0.0", &version_dir)); } TEST(ExtensionFileUtil, LoadExtensionWithValidLocales) { FilePath install_dir; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir)); install_dir = install_dir.AppendASCII("extensions") .AppendASCII("good") .AppendASCII("Extensions") .AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj") .AppendASCII("1.0.0.0"); std::string error; scoped_ptr<Extension> extension( extension_file_util::LoadExtension(install_dir, false, &error)); ASSERT_TRUE(extension != NULL); EXPECT_EQ("The first extension that I made.", extension->description()); } TEST(ExtensionFileUtil, LoadExtensionWithoutLocalesFolder) { FilePath install_dir; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir)); install_dir = install_dir.AppendASCII("extensions") .AppendASCII("good") .AppendASCII("Extensions") .AppendASCII("bjafgdebaacbbbecmhlhpofkepfkgcpa") .AppendASCII("1.0"); std::string error; scoped_ptr<Extension> extension( extension_file_util::LoadExtension(install_dir, false, &error)); ASSERT_FALSE(extension == NULL); EXPECT_TRUE(error.empty()); } TEST(ExtensionFileUtil, CheckIllegalFilenamesNoUnderscores) { ScopedTempDir temp; ASSERT_TRUE(temp.CreateUniqueTempDir()); FilePath src_path = temp.path().AppendASCII("some_dir"); ASSERT_TRUE(file_util::CreateDirectory(src_path)); std::string data = "{ \"name\": { \"message\": \"foobar\" } }"; ASSERT_TRUE(file_util::WriteFile(src_path.AppendASCII("some_file.txt"), data.c_str(), data.length())); std::string error; EXPECT_TRUE(extension_file_util::CheckForIllegalFilenames(temp.path(), &error)); } TEST(ExtensionFileUtil, CheckIllegalFilenamesOnlyReserved) { ScopedTempDir temp; ASSERT_TRUE(temp.CreateUniqueTempDir()); FilePath src_path = temp.path().Append(Extension::kLocaleFolder); ASSERT_TRUE(file_util::CreateDirectory(src_path)); std::string error; EXPECT_TRUE(extension_file_util::CheckForIllegalFilenames(temp.path(), &error)); } TEST(ExtensionFileUtil, CheckIllegalFilenamesReservedAndIllegal) { ScopedTempDir temp; ASSERT_TRUE(temp.CreateUniqueTempDir()); FilePath src_path = temp.path().Append(Extension::kLocaleFolder); ASSERT_TRUE(file_util::CreateDirectory(src_path)); src_path = temp.path().AppendASCII("_some_dir"); ASSERT_TRUE(file_util::CreateDirectory(src_path)); std::string error; EXPECT_FALSE(extension_file_util::CheckForIllegalFilenames(temp.path(), &error)); } TEST(ExtensionFileUtil, LoadExtensionGivesHelpfullErrorOnMissingManifest) { FilePath install_dir; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir)); install_dir = install_dir.AppendASCII("extensions") .AppendASCII("bad") .AppendASCII("Extensions") .AppendASCII("dddddddddddddddddddddddddddddddd") .AppendASCII("1.0"); std::string error; scoped_ptr<Extension> extension( extension_file_util::LoadExtension(install_dir, false, &error)); ASSERT_TRUE(extension == NULL); ASSERT_FALSE(error.empty()); ASSERT_STREQ("Manifest file is missing or unreadable.", error.c_str()); } TEST(ExtensionFileUtil, LoadExtensionGivesHelpfullErrorOnBadManifest) { FilePath install_dir; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir)); install_dir = install_dir.AppendASCII("extensions") .AppendASCII("bad") .AppendASCII("Extensions") .AppendASCII("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee") .AppendASCII("1.0"); std::string error; scoped_ptr<Extension> extension( extension_file_util::LoadExtension(install_dir, false, &error)); ASSERT_TRUE(extension == NULL); ASSERT_FALSE(error.empty()); ASSERT_STREQ("Manifest is not valid JSON. " "Line: 2, column: 16, Syntax error.", error.c_str()); } TEST(ExtensionFileUtil, MissingPrivacyBlacklist) { FilePath install_dir; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir)); install_dir = install_dir.AppendASCII("extensions") .AppendASCII("privacy_blacklists") .AppendASCII("missing_blacklist"); std::string error; scoped_ptr<Extension> extension( extension_file_util::LoadExtension(install_dir, false, &error)); ASSERT_TRUE(extension == NULL); ASSERT_FALSE(error.empty()); EXPECT_TRUE(MatchPatternASCII(error, "Could not load '*privacy_blacklist.pbl' for privacy blacklist: " "file does not exist.")) << error; } TEST(ExtensionFileUtil, InvalidPrivacyBlacklist) { FilePath install_dir; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir)); install_dir = install_dir.AppendASCII("extensions") .AppendASCII("privacy_blacklists") .AppendASCII("invalid_blacklist"); std::string error; scoped_ptr<Extension> extension( extension_file_util::LoadExtension(install_dir, false, &error)); ASSERT_TRUE(extension == NULL); ASSERT_FALSE(error.empty()); EXPECT_TRUE(MatchPatternASCII(error, "Could not load '*privacy_blacklist.pbl' for privacy blacklist: " "Incorrect header.")) << error; } // TODO(aa): More tests as motivation allows. Maybe steal some from // ExtensionsService? Many of them could probably be tested here without the // MessageLoop shenanigans.
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_file_util.h" #include "base/file_util.h" #include "base/scoped_temp_dir.h" #include "base/string_util.h" #include "base/path_service.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/extensions/extension_constants.h" #include "testing/gtest/include/gtest/gtest.h" namespace keys = extension_manifest_keys; TEST(ExtensionFileUtil, MoveDirSafely) { // Create a test directory structure with some data in it. ScopedTempDir temp; ASSERT_TRUE(temp.CreateUniqueTempDir()); FilePath src_path = temp.path().AppendASCII("src"); ASSERT_TRUE(file_util::CreateDirectory(src_path)); std::string data = "foobar"; ASSERT_TRUE(file_util::WriteFile(src_path.AppendASCII("data"), data.c_str(), data.length())); // Move it to a path that doesn't exist yet. FilePath dest_path = temp.path().AppendASCII("dest").AppendASCII("dest"); ASSERT_TRUE(extension_file_util::MoveDirSafely(src_path, dest_path)); // The path should get created. ASSERT_TRUE(file_util::DirectoryExists(dest_path)); // The data should match. std::string data_out; ASSERT_TRUE(file_util::ReadFileToString(dest_path.AppendASCII("data"), &data_out)); ASSERT_EQ(data, data_out); // The src path should be gone. ASSERT_FALSE(file_util::PathExists(src_path)); // Create some new test data. ASSERT_TRUE(file_util::CopyDirectory(dest_path, src_path, true)); // recursive data = "hotdog"; ASSERT_TRUE(file_util::WriteFile(src_path.AppendASCII("data"), data.c_str(), data.length())); // Test again, overwriting the old path. ASSERT_TRUE(extension_file_util::MoveDirSafely(src_path, dest_path)); ASSERT_TRUE(file_util::DirectoryExists(dest_path)); data_out.clear(); ASSERT_TRUE(file_util::ReadFileToString(dest_path.AppendASCII("data"), &data_out)); ASSERT_EQ(data, data_out); ASSERT_FALSE(file_util::PathExists(src_path)); } TEST(ExtensionFileUtil, CompareToInstalledVersion) { // Compare to an existing extension. FilePath install_dir; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir)); install_dir = install_dir.AppendASCII("extensions") .AppendASCII("good") .AppendASCII("Extensions"); const std::string kId = "behllobkkfkfnphdnhnkndlbkcpglgmj"; const std::string kCurrentVersion = "1.0.0.0"; FilePath version_dir; ASSERT_EQ(Extension::UPGRADE, extension_file_util::CompareToInstalledVersion( install_dir, kId, kCurrentVersion, "1.0.0.1", &version_dir)); ASSERT_EQ(Extension::REINSTALL, extension_file_util::CompareToInstalledVersion( install_dir, kId, kCurrentVersion, "1.0.0.0", &version_dir)); ASSERT_EQ(Extension::REINSTALL, extension_file_util::CompareToInstalledVersion( install_dir, kId, kCurrentVersion, "1.0.0", &version_dir)); ASSERT_EQ(Extension::DOWNGRADE, extension_file_util::CompareToInstalledVersion( install_dir, kId, kCurrentVersion, "0.0.1.0", &version_dir)); // Compare to an extension that is missing its manifest file. ScopedTempDir temp; ASSERT_TRUE(temp.CreateUniqueTempDir()); FilePath src = install_dir.AppendASCII(kId).AppendASCII(kCurrentVersion); FilePath dest = temp.path().AppendASCII(kId).AppendASCII(kCurrentVersion); ASSERT_TRUE(file_util::CreateDirectory(dest.DirName())); ASSERT_TRUE(file_util::CopyDirectory(src, dest, true)); ASSERT_TRUE(file_util::Delete(dest.AppendASCII("manifest.json"), false)); ASSERT_EQ(Extension::NEW_INSTALL, extension_file_util::CompareToInstalledVersion( temp.path(), kId, kCurrentVersion, "1.0.0", &version_dir)); // Compare to a non-existent extension. const std::string kMissingVersion = ""; const std::string kBadId = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; ASSERT_EQ(Extension::NEW_INSTALL, extension_file_util::CompareToInstalledVersion( temp.path(), kBadId, kMissingVersion, "1.0.0", &version_dir)); } TEST(ExtensionFileUtil, LoadExtensionWithValidLocales) { FilePath install_dir; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir)); install_dir = install_dir.AppendASCII("extensions") .AppendASCII("good") .AppendASCII("Extensions") .AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj") .AppendASCII("1.0.0.0"); std::string error; scoped_ptr<Extension> extension( extension_file_util::LoadExtension(install_dir, false, &error)); ASSERT_TRUE(extension != NULL); EXPECT_EQ("The first extension that I made.", extension->description()); } TEST(ExtensionFileUtil, LoadExtensionWithoutLocalesFolder) { FilePath install_dir; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir)); install_dir = install_dir.AppendASCII("extensions") .AppendASCII("good") .AppendASCII("Extensions") .AppendASCII("bjafgdebaacbbbecmhlhpofkepfkgcpa") .AppendASCII("1.0"); std::string error; scoped_ptr<Extension> extension( extension_file_util::LoadExtension(install_dir, false, &error)); ASSERT_FALSE(extension == NULL); EXPECT_TRUE(error.empty()); } TEST(ExtensionFileUtil, CheckIllegalFilenamesNoUnderscores) { ScopedTempDir temp; ASSERT_TRUE(temp.CreateUniqueTempDir()); FilePath src_path = temp.path().AppendASCII("some_dir"); ASSERT_TRUE(file_util::CreateDirectory(src_path)); std::string data = "{ \"name\": { \"message\": \"foobar\" } }"; ASSERT_TRUE(file_util::WriteFile(src_path.AppendASCII("some_file.txt"), data.c_str(), data.length())); std::string error; EXPECT_TRUE(extension_file_util::CheckForIllegalFilenames(temp.path(), &error)); } TEST(ExtensionFileUtil, CheckIllegalFilenamesOnlyReserved) { ScopedTempDir temp; ASSERT_TRUE(temp.CreateUniqueTempDir()); FilePath src_path = temp.path().Append(Extension::kLocaleFolder); ASSERT_TRUE(file_util::CreateDirectory(src_path)); std::string error; EXPECT_TRUE(extension_file_util::CheckForIllegalFilenames(temp.path(), &error)); } TEST(ExtensionFileUtil, CheckIllegalFilenamesReservedAndIllegal) { ScopedTempDir temp; ASSERT_TRUE(temp.CreateUniqueTempDir()); FilePath src_path = temp.path().Append(Extension::kLocaleFolder); ASSERT_TRUE(file_util::CreateDirectory(src_path)); src_path = temp.path().AppendASCII("_some_dir"); ASSERT_TRUE(file_util::CreateDirectory(src_path)); std::string error; EXPECT_FALSE(extension_file_util::CheckForIllegalFilenames(temp.path(), &error)); } TEST(ExtensionFileUtil, LoadExtensionGivesHelpfullErrorOnMissingManifest) { FilePath install_dir; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir)); install_dir = install_dir.AppendASCII("extensions") .AppendASCII("bad") .AppendASCII("Extensions") .AppendASCII("dddddddddddddddddddddddddddddddd") .AppendASCII("1.0"); std::string error; scoped_ptr<Extension> extension( extension_file_util::LoadExtension(install_dir, false, &error)); ASSERT_TRUE(extension == NULL); ASSERT_FALSE(error.empty()); ASSERT_STREQ("Manifest file is missing or unreadable.", error.c_str()); } TEST(ExtensionFileUtil, LoadExtensionGivesHelpfullErrorOnBadManifest) { FilePath install_dir; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir)); install_dir = install_dir.AppendASCII("extensions") .AppendASCII("bad") .AppendASCII("Extensions") .AppendASCII("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee") .AppendASCII("1.0"); std::string error; scoped_ptr<Extension> extension( extension_file_util::LoadExtension(install_dir, false, &error)); ASSERT_TRUE(extension == NULL); ASSERT_FALSE(error.empty()); ASSERT_STREQ("Manifest is not valid JSON. " "Line: 2, column: 16, Syntax error.", error.c_str()); } TEST(ExtensionFileUtil, MissingPrivacyBlacklist) { FilePath install_dir; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir)); install_dir = install_dir.AppendASCII("extensions") .AppendASCII("privacy_blacklists") .AppendASCII("missing_blacklist"); std::string error; scoped_ptr<Extension> extension( extension_file_util::LoadExtension(install_dir, false, &error)); ASSERT_TRUE(extension == NULL); ASSERT_FALSE(error.empty()); EXPECT_TRUE(MatchPatternASCII(error, "Could not load '*privacy_blacklist.pbl' for privacy blacklist: " "file does not exist.")) << error; } TEST(ExtensionFileUtil, InvalidPrivacyBlacklist) { FilePath install_dir; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir)); install_dir = install_dir.AppendASCII("extensions") .AppendASCII("privacy_blacklists") .AppendASCII("invalid_blacklist"); std::string error; scoped_ptr<Extension> extension( extension_file_util::LoadExtension(install_dir, false, &error)); ASSERT_TRUE(extension == NULL); ASSERT_FALSE(error.empty()); EXPECT_TRUE(MatchPatternASCII(error, "Could not load '*privacy_blacklist.pbl' for privacy blacklist: " "Incorrect header.")) << error; } #define URL_PREFIX "chrome-extension://extension-id/" TEST(ExtensionFileUtil, ExtensionURLToRelativeFilePath) { struct TestCase { const char* url; const char* expected_relative_path; } test_cases[] = { { URL_PREFIX "simple.html", "simple.html" }, { URL_PREFIX "directory/to/file.html", "directory/to/file.html" }, { URL_PREFIX "escape%20spaces.html", "escape spaces.html" }, { URL_PREFIX "%C3%9Cber.html", "\xC3\x9C" "ber.html" }, }; for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_cases); ++i) { GURL url(test_cases[i].url); #if defined(OS_POSIX) FilePath expected_path(test_cases[i].expected_relative_path); #elif defined(OS_WIN) FilePath expected_path(UTF8ToWide(test_cases[i].expected_relative_path)); #endif FilePath actual_path = extension_file_util::ExtensionURLToRelativeFilePath(url); EXPECT_FALSE(actual_path.IsAbsolute()) << " For the path " << actual_path.value(); EXPECT_EQ(expected_path.value(), actual_path.value()); } } // TODO(aa): More tests as motivation allows. Maybe steal some from // ExtensionsService? Many of them could probably be tested here without the // MessageLoop shenanigans.
add unit test for ExtensionURLToRelativeFilePath
add unit test for ExtensionURLToRelativeFilePath BUG=30749 TEST=this patch Review URL: http://codereview.chromium.org/507054 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@35013 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,robclark/chromium,Fireblend/chromium-crosswalk,zcbenz/cefode-chromium,hgl888/chromium-crosswalk-efl,dednal/chromium.src,anirudhSK/chromium,Just-D/chromium-1,robclark/chromium,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,M4sse/chromium.src,dushu1203/chromium.src,axinging/chromium-crosswalk,pozdnyakov/chromium-crosswalk,hujiajie/pa-chromium,crosswalk-project/chromium-crosswalk-efl,hujiajie/pa-chromium,ltilve/chromium,nacl-webkit/chrome_deps,krieger-od/nwjs_chromium.src,dednal/chromium.src,timopulkkinen/BubbleFish,Jonekee/chromium.src,fujunwei/chromium-crosswalk,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,mogoweb/chromium-crosswalk,junmin-zhu/chromium-rivertrail,PeterWangIntel/chromium-crosswalk,mogoweb/chromium-crosswalk,ondra-novak/chromium.src,Jonekee/chromium.src,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,keishi/chromium,junmin-zhu/chromium-rivertrail,chuan9/chromium-crosswalk,Jonekee/chromium.src,rogerwang/chromium,Chilledheart/chromium,Chilledheart/chromium,Jonekee/chromium.src,dednal/chromium.src,anirudhSK/chromium,anirudhSK/chromium,timopulkkinen/BubbleFish,robclark/chromium,Jonekee/chromium.src,robclark/chromium,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,patrickm/chromium.src,timopulkkinen/BubbleFish,axinging/chromium-crosswalk,Jonekee/chromium.src,timopulkkinen/BubbleFish,ondra-novak/chromium.src,ltilve/chromium,fujunwei/chromium-crosswalk,dushu1203/chromium.src,keishi/chromium,nacl-webkit/chrome_deps,junmin-zhu/chromium-rivertrail,hgl888/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,littlstar/chromium.src,M4sse/chromium.src,M4sse/chromium.src,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,jaruba/chromium.src,fujunwei/chromium-crosswalk,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,littlstar/chromium.src,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,timopulkkinen/BubbleFish,patrickm/chromium.src,mogoweb/chromium-crosswalk,ondra-novak/chromium.src,krieger-od/nwjs_chromium.src,rogerwang/chromium,zcbenz/cefode-chromium,robclark/chromium,patrickm/chromium.src,timopulkkinen/BubbleFish,pozdnyakov/chromium-crosswalk,dushu1203/chromium.src,junmin-zhu/chromium-rivertrail,keishi/chromium,mohamed--abdel-maksoud/chromium.src,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,jaruba/chromium.src,rogerwang/chromium,bright-sparks/chromium-spacewalk,dednal/chromium.src,nacl-webkit/chrome_deps,timopulkkinen/BubbleFish,mohamed--abdel-maksoud/chromium.src,nacl-webkit/chrome_deps,TheTypoMaster/chromium-crosswalk,jaruba/chromium.src,Jonekee/chromium.src,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk-efl,keishi/chromium,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,zcbenz/cefode-chromium,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,M4sse/chromium.src,fujunwei/chromium-crosswalk,ltilve/chromium,hujiajie/pa-chromium,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,robclark/chromium,junmin-zhu/chromium-rivertrail,littlstar/chromium.src,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,ondra-novak/chromium.src,Jonekee/chromium.src,nacl-webkit/chrome_deps,mogoweb/chromium-crosswalk,nacl-webkit/chrome_deps,timopulkkinen/BubbleFish,PeterWangIntel/chromium-crosswalk,zcbenz/cefode-chromium,bright-sparks/chromium-spacewalk,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,Just-D/chromium-1,dednal/chromium.src,junmin-zhu/chromium-rivertrail,dednal/chromium.src,bright-sparks/chromium-spacewalk,timopulkkinen/BubbleFish,fujunwei/chromium-crosswalk,dushu1203/chromium.src,axinging/chromium-crosswalk,hujiajie/pa-chromium,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk-efl,anirudhSK/chromium,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,robclark/chromium,rogerwang/chromium,dednal/chromium.src,Chilledheart/chromium,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,hujiajie/pa-chromium,jaruba/chromium.src,junmin-zhu/chromium-rivertrail,fujunwei/chromium-crosswalk,ChromiumWebApps/chromium,ltilve/chromium,M4sse/chromium.src,littlstar/chromium.src,pozdnyakov/chromium-crosswalk,bright-sparks/chromium-spacewalk,pozdnyakov/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,zcbenz/cefode-chromium,littlstar/chromium.src,rogerwang/chromium,dednal/chromium.src,krieger-od/nwjs_chromium.src,M4sse/chromium.src,keishi/chromium,ChromiumWebApps/chromium,M4sse/chromium.src,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,pozdnyakov/chromium-crosswalk,dushu1203/chromium.src,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,markYoungH/chromium.src,ChromiumWebApps/chromium,TheTypoMaster/chromium-crosswalk,keishi/chromium,junmin-zhu/chromium-rivertrail,PeterWangIntel/chromium-crosswalk,zcbenz/cefode-chromium,keishi/chromium,PeterWangIntel/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,bright-sparks/chromium-spacewalk,keishi/chromium,ondra-novak/chromium.src,hgl888/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,jaruba/chromium.src,bright-sparks/chromium-spacewalk,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,nacl-webkit/chrome_deps,ChromiumWebApps/chromium,rogerwang/chromium,hujiajie/pa-chromium,dednal/chromium.src,anirudhSK/chromium,junmin-zhu/chromium-rivertrail,jaruba/chromium.src,ondra-novak/chromium.src,Pluto-tv/chromium-crosswalk,markYoungH/chromium.src,axinging/chromium-crosswalk,nacl-webkit/chrome_deps,ondra-novak/chromium.src,hujiajie/pa-chromium,littlstar/chromium.src,zcbenz/cefode-chromium,ltilve/chromium,chuan9/chromium-crosswalk,M4sse/chromium.src,ChromiumWebApps/chromium,Chilledheart/chromium,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Fireblend/chromium-crosswalk,robclark/chromium,jaruba/chromium.src,rogerwang/chromium,anirudhSK/chromium,PeterWangIntel/chromium-crosswalk,pozdnyakov/chromium-crosswalk,markYoungH/chromium.src,keishi/chromium,mogoweb/chromium-crosswalk,Pluto-tv/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,patrickm/chromium.src,junmin-zhu/chromium-rivertrail,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,dednal/chromium.src,Chilledheart/chromium,bright-sparks/chromium-spacewalk,pozdnyakov/chromium-crosswalk,Chilledheart/chromium,ChromiumWebApps/chromium,littlstar/chromium.src,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,ltilve/chromium,jaruba/chromium.src,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,pozdnyakov/chromium-crosswalk,chuan9/chromium-crosswalk,anirudhSK/chromium,Pluto-tv/chromium-crosswalk,zcbenz/cefode-chromium,zcbenz/cefode-chromium,anirudhSK/chromium,rogerwang/chromium,dushu1203/chromium.src,Chilledheart/chromium,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,rogerwang/chromium,patrickm/chromium.src,ltilve/chromium,ltilve/chromium,pozdnyakov/chromium-crosswalk,keishi/chromium,anirudhSK/chromium,Just-D/chromium-1,Fireblend/chromium-crosswalk,Chilledheart/chromium,jaruba/chromium.src,krieger-od/nwjs_chromium.src,mogoweb/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,ondra-novak/chromium.src,Pluto-tv/chromium-crosswalk,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,patrickm/chromium.src,robclark/chromium,hujiajie/pa-chromium,hgl888/chromium-crosswalk,ltilve/chromium,markYoungH/chromium.src,hujiajie/pa-chromium,krieger-od/nwjs_chromium.src,mogoweb/chromium-crosswalk,patrickm/chromium.src,Pluto-tv/chromium-crosswalk,M4sse/chromium.src,crosswalk-project/chromium-crosswalk-efl,axinging/chromium-crosswalk,robclark/chromium,PeterWangIntel/chromium-crosswalk,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk,ChromiumWebApps/chromium,Jonekee/chromium.src,keishi/chromium,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,Chilledheart/chromium,zcbenz/cefode-chromium,zcbenz/cefode-chromium,PeterWangIntel/chromium-crosswalk,ondra-novak/chromium.src,hujiajie/pa-chromium,littlstar/chromium.src,patrickm/chromium.src,markYoungH/chromium.src,rogerwang/chromium,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,dednal/chromium.src,Jonekee/chromium.src,nacl-webkit/chrome_deps,dushu1203/chromium.src,junmin-zhu/chromium-rivertrail,dushu1203/chromium.src,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,PeterWangIntel/chromium-crosswalk,fujunwei/chromium-crosswalk,dushu1203/chromium.src,krieger-od/nwjs_chromium.src,anirudhSK/chromium,crosswalk-project/chromium-crosswalk-efl,Just-D/chromium-1,Just-D/chromium-1,nacl-webkit/chrome_deps,anirudhSK/chromium,ChromiumWebApps/chromium,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,markYoungH/chromium.src,timopulkkinen/BubbleFish,Pluto-tv/chromium-crosswalk,markYoungH/chromium.src,nacl-webkit/chrome_deps,Just-D/chromium-1,Just-D/chromium-1,hujiajie/pa-chromium,mogoweb/chromium-crosswalk,Just-D/chromium-1,pozdnyakov/chromium-crosswalk,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,TheTypoMaster/chromium-crosswalk
7cd79df3f46d5ddc98e15b1c9e45c43dfecf444b
classification/kth-svm-cross-validation-impl.hpp
classification/kth-svm-cross-validation-impl.hpp
#include "omp.h" inline kth_cv_svm::kth_cv_svm(const std::string in_path, const std::string in_actionNames, const field<std::string> in_all_people, const int in_scale_factor, const int in_shift, const int in_scene, //only for kth const int in_dim ):path(in_path), actionNames(in_actionNames), all_people (in_all_people), scale_factor(in_scale_factor), shift(in_shift), total_scenes(in_scene), dim(in_dim) { actions.load( actionNames ); } // Log-Euclidean Distance inline void kth_cv_svm::logEucl() { //logEucl_distances(); logEucl_CV(); //cross validation; } inline void kth_cv_svm::logEucl_CV() { int n_actions = actions.n_rows; int n_peo = all_people.n_rows; //int n_test = n_peo*n_actions*total_scenes - 1; // - person13_handclapping_d3 int n_test = (n_peo-1)*n_actions*total_scenes; // - person13_handclapping_d3 int n_dim = n_test; int sc = 1; // = total scenes fvec dist_vector; float acc=0; vec real_labels; vec est_labels; field<std::string> test_video_list(n_peo*n_actions); real_labels.zeros(n_peo*n_actions); est_labels.zeros(n_peo*n_actions); int j =0; for (int pe_ts=0; pe_ts<n_peo; ++pe_ts) { fmat training_data; fvec lab; training_data.zeros(n_dim,n_test); lab.zeros(n_test); int k=0; for (int pe_tr=0; pe_tr<n_peo; ++pe_tr) { if(pe_tr!=pe_ts) for (int act=0; act<n_actions; act++) { std::stringstream load_vec_dist; load_vec_dist << path << "./classification/kth-svm/logEucl/dist_vector_" << all_people (pe_tr) << "_" << actions(act) << ".h5" ; dist_vector.load( load_vec_dist.str() ); training_data.col(k) = dist_vector; lab(k) = act; ++k; } } //Training the model with OpenCV cout << "Preparing data to train the data" << endl; cv::Mat cvMatTraining(n_test, n_dim, CV_32FC1); float fl_labels[n_test] ; for (uword m=0; m<n_test; ++m) { for (uword d=0; d<n_dim; ++d) { cvMatTraining.at<float>(m,d) = training_data(d,m); //cout << " OpenCV: " << cvMatTraining.at<float>(m,d) << " - Arma: " <<training_data(d,m); } fl_labels[m] = lab(m); //cout <<" OpenCVLabel: " << fl_labels[m] << " ArmaLabel: " << labels(m) << endl; } cv::Mat cvMatLabels(n_test, 1, CV_32FC1,fl_labels ); cout << "Setting parameters" << endl; CvSVMParams params; params.svm_type = CvSVM::C_SVC; params.kernel_type = CvSVM::RBF; params.gamma = 1; params.term_crit = cvTermCriteria(CV_TERMCRIT_ITER, (int)1e7, 1e-6); // Train the SVM cout << "Training" << endl; CvSVM SVM; SVM.train( cvMatTraining , cvMatLabels, cv::Mat(), cv::Mat(), params); // y luego si for act=0:total_act //acc para este run //ACC = [ACC acc]; cout << "Using SVM to classify " << all_people (pe_ts) << endl; for (int act_ts =0; act_ts<n_actions; ++act_ts) { vec test_dist; std::stringstream load_vec_dist; load_vec_dist << path << "./classification/kth-svm/logEucl/dist_vector_" << all_people (pe_ts) << "_" << actions(act_ts) << ".h5" ; test_dist.load( load_vec_dist.str() ); cout << all_people (pe_ts) << "_" << actions(act_ts) << endl; cv::Mat cvMatTesting_onevideo(1, n_dim, CV_32FC1); for (uword d=0; d<n_dim; ++d) { cvMatTesting_onevideo.at<float>(0,d) = test_dist(d); } float response = SVM.predict(cvMatTesting_onevideo, true); cout << "response " << response << endl; real_labels(j) = act_ts; est_labels(j) = response; test_video_list(j) = load_vec_dist.str(); j++; if (response == act_ts) { acc++; } } ///cambiar nombres real_labels.save("svm_LogEucl_real_labels.dat", raw_ascii); est_labels.save("svm_LogEucl_est_labels.dat", raw_ascii); test_video_list.save("svm_LogEucl_test_video_list.dat", raw_ascii); getchar(); } //save performance } /// inline void kth_cv_svm::logEucl_distances() { int n_actions = actions.n_rows; int n_peo = all_people.n_rows; //int n_test = n_peo*n_actions*total_scenes - 1; // - person13_handclapping_d3 int n_test = n_peo*n_actions*total_scenes; // - person13_handclapping_d3 int k=0; int sc = 1; // = total scenes mat peo_act(n_test,2); for (int pe = 0; pe< n_peo; ++pe) { for (int act=0; act<n_actions; ++act) { peo_act (k,0) = pe; peo_act (k,1) = act; k++; } } std::stringstream load_sub_path; load_sub_path << path << "cov_matrices/kth-one-cov-mat-dim" << dim << "/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ; //omp_set_num_threads(8); //Use only 8 processors #pragma omp parallel for for (int n = 0; n< n_test; ++n) { int pe = peo_act (n,0); int act = peo_act (n,1); int tid=omp_get_thread_num(); vec dist_video_i; #pragma omp critical cout<< "Processor " << tid <<" doing "<< all_people (pe) << "_" << actions(act) << endl; std::stringstream load_cov; load_cov << load_sub_path.str() << "/LogMcov_" << all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; //#pragma omp critical //cout << load_cov_seg.str() << endl; dist_video_i = dist_logEucl_one_video( pe, load_sub_path.str(), load_cov.str()); //save dist_video_i person, action std::stringstream save_vec_dist; save_vec_dist << "./kth-svm/logEucl/dist_vector_" << all_people (pe) << "_" << actions(act) << ".h5" ; #pragma omp critical dist_video_i.save(save_vec_dist.str(), hdf5_binary); } } inline vec kth_cv_svm::dist_logEucl_one_video(int pe_test, std::string load_sub_path, std::string load_cov) { //wall_clock timer; //timer.tic(); mat logMtest_cov; logMtest_cov.load(load_cov); int n_actions = actions.n_rows; int n_peo = all_people.n_rows; //double dist; double tmp_dist; vec dist; int num_dist = (n_peo-1)*n_actions; dist.zeros(num_dist); tmp_dist = datum::inf; double est_lab; int sc =1; int k=0; for (int pe_tr = 0; pe_tr< n_peo; ++pe_tr) { if (pe_tr!= pe_test) { //cout << " " << all_people (pe_tr); for (int act=0; act<n_actions; ++act) { std::stringstream load_cov_tr; load_cov_tr << load_sub_path << "/LogMcov_" << all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".h5"; mat logMtrain_cov; logMtrain_cov.load( load_cov_tr.str() ); tmp_dist = norm( logMtest_cov - logMtrain_cov, "fro"); dist(k) = tmp_dist; ++k; } } } return dist; }
#include "omp.h" inline kth_cv_svm::kth_cv_svm(const std::string in_path, const std::string in_actionNames, const field<std::string> in_all_people, const int in_scale_factor, const int in_shift, const int in_scene, //only for kth const int in_dim ):path(in_path), actionNames(in_actionNames), all_people (in_all_people), scale_factor(in_scale_factor), shift(in_shift), total_scenes(in_scene), dim(in_dim) { actions.load( actionNames ); } // Log-Euclidean Distance inline void kth_cv_svm::logEucl() { //logEucl_distances(); logEucl_CV(); //cross validation; } inline void kth_cv_svm::logEucl_CV() { int n_actions = actions.n_rows; int n_peo = all_people.n_rows; //int n_test = n_peo*n_actions*total_scenes - 1; // - person13_handclapping_d3 int n_test = (n_peo-1)*n_actions*total_scenes; // - person13_handclapping_d3 int n_dim = n_test; int sc = 1; // = total scenes fvec dist_vector; float acc=0; vec real_labels; vec est_labels; field<std::string> test_video_list(n_peo*n_actions); real_labels.zeros(n_peo*n_actions); est_labels.zeros(n_peo*n_actions); int j =0; for (int pe_ts=0; pe_ts<n_peo; ++pe_ts) { fmat training_data; fvec lab; training_data.zeros(n_dim,n_test); lab.zeros(n_test); int k=0; for (int pe_tr=0; pe_tr<n_peo; ++pe_tr) { if(pe_tr!=pe_ts) for (int act=0; act<n_actions; act++) { std::stringstream load_vec_dist; load_vec_dist << path << "./classification/kth-svm/logEucl/dist_vector_" << all_people (pe_tr) << "_" << actions(act) << ".h5" ; dist_vector.load( load_vec_dist.str() ); training_data.col(k) = dist_vector; lab(k) = act; ++k; } } //Training the model with OpenCV cout << "Using SVM to classify " << all_people (pe_ts) << endl; //cout << "Preparing data to train the data" << endl; cv::Mat cvMatTraining(n_test, n_dim, CV_32FC1); float fl_labels[n_test] ; for (uword m=0; m<n_test; ++m) { for (uword d=0; d<n_dim; ++d) { cvMatTraining.at<float>(m,d) = training_data(d,m); //cout << " OpenCV: " << cvMatTraining.at<float>(m,d) << " - Arma: " <<training_data(d,m); } fl_labels[m] = lab(m); //cout <<" OpenCVLabel: " << fl_labels[m] << " ArmaLabel: " << labels(m) << endl; } cv::Mat cvMatLabels(n_test, 1, CV_32FC1,fl_labels ); //cout << "Setting parameters" << endl; CvSVMParams params; params.svm_type = CvSVM::C_SVC; params.kernel_type = CvSVM::RBF; params.gamma = 1; params.term_crit = cvTermCriteria(CV_TERMCRIT_ITER, (int)1e7, 1e-6); // Train the SVM //cout << "Training" << endl; CvSVM SVM; SVM.train( cvMatTraining , cvMatLabels, cv::Mat(), cv::Mat(), params); // y luego si for act=0:total_act //acc para este run //ACC = [ACC acc]; for (int act_ts =0; act_ts<n_actions; ++act_ts) { vec test_dist; std::stringstream load_vec_dist; load_vec_dist << path << "./classification/kth-svm/logEucl/dist_vector_" << all_people (pe_ts) << "_" << actions(act_ts) << ".h5" ; test_dist.load( load_vec_dist.str() ); cout << all_people (pe_ts) << "_" << actions(act_ts) << endl; cv::Mat cvMatTesting_onevideo(1, n_dim, CV_32FC1); for (uword d=0; d<n_dim; ++d) { cvMatTesting_onevideo.at<float>(0,d) = test_dist(d); } float response = SVM.predict(cvMatTesting_onevideo, true); //cout << "response " << response << endl; real_labels(j) = act_ts; est_labels(j) = response; test_video_list(j) = load_vec_dist.str(); j++; if (response == act_ts) { acc++; } } ///cambiar nombres real_labels.save("svm_LogEucl_real_labels.dat", raw_ascii); est_labels.save("svm_LogEucl_est_labels.dat", raw_ascii); test_video_list.save("svm_LogEucl_test_video_list.dat", raw_ascii); //getchar(); } cout << "Performance: " << acc*100/(n_peo*n_actions) << " %" << endl; } /// inline void kth_cv_svm::logEucl_distances() { int n_actions = actions.n_rows; int n_peo = all_people.n_rows; //int n_test = n_peo*n_actions*total_scenes - 1; // - person13_handclapping_d3 int n_test = n_peo*n_actions*total_scenes; // - person13_handclapping_d3 int k=0; int sc = 1; // = total scenes mat peo_act(n_test,2); for (int pe = 0; pe< n_peo; ++pe) { for (int act=0; act<n_actions; ++act) { peo_act (k,0) = pe; peo_act (k,1) = act; k++; } } std::stringstream load_sub_path; load_sub_path << path << "cov_matrices/kth-one-cov-mat-dim" << dim << "/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ; //omp_set_num_threads(8); //Use only 8 processors #pragma omp parallel for for (int n = 0; n< n_test; ++n) { int pe = peo_act (n,0); int act = peo_act (n,1); int tid=omp_get_thread_num(); vec dist_video_i; #pragma omp critical cout<< "Processor " << tid <<" doing "<< all_people (pe) << "_" << actions(act) << endl; std::stringstream load_cov; load_cov << load_sub_path.str() << "/LogMcov_" << all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; //#pragma omp critical //cout << load_cov_seg.str() << endl; dist_video_i = dist_logEucl_one_video( pe, load_sub_path.str(), load_cov.str()); //save dist_video_i person, action std::stringstream save_vec_dist; save_vec_dist << "./kth-svm/logEucl/dist_vector_" << all_people (pe) << "_" << actions(act) << ".h5" ; #pragma omp critical dist_video_i.save(save_vec_dist.str(), hdf5_binary); } } inline vec kth_cv_svm::dist_logEucl_one_video(int pe_test, std::string load_sub_path, std::string load_cov) { //wall_clock timer; //timer.tic(); mat logMtest_cov; logMtest_cov.load(load_cov); int n_actions = actions.n_rows; int n_peo = all_people.n_rows; //double dist; double tmp_dist; vec dist; int num_dist = (n_peo-1)*n_actions; dist.zeros(num_dist); tmp_dist = datum::inf; double est_lab; int sc =1; int k=0; for (int pe_tr = 0; pe_tr< n_peo; ++pe_tr) { if (pe_tr!= pe_test) { //cout << " " << all_people (pe_tr); for (int act=0; act<n_actions; ++act) { std::stringstream load_cov_tr; load_cov_tr << load_sub_path << "/LogMcov_" << all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".h5"; mat logMtrain_cov; logMtrain_cov.load( load_cov_tr.str() ); tmp_dist = norm( logMtest_cov - logMtrain_cov, "fro"); dist(k) = tmp_dist; ++k; } } } return dist; }
Test svm_LogEucl
Test svm_LogEucl
C++
agpl-3.0
johanna-codes/study-paper,johanna-codes/study-paper
fb1642951779b64e3a22e6bca5db8b3d34a0008c
daily_programmer/384.cpp
daily_programmer/384.cpp
/** * Sample Use * ========== * * echo -e "3d6\n10d13\n2d5" | python 384.py * * * Description * =========== * * I love playing D&D with my friends, and my favorite part is creating * character sheets (my DM is notorious for killing us all off by level 3 or * so). One major part of making character sheets is rolling the character's * stats. Sadly, I have lost all my dice, so I'm asking for your help to make a * dice roller for me to use! * * Formal Inputs & Outputs * ======================= * * Input description * ----------------- * * Your input will contain one or more lines, where each line will be in the * form of "NdM"; for example: * * 3d6 * 4d12 * 1d10 * 5d4 * * If you've ever played D&D you probably recognize those, but * for the rest of you, this is what those mean: * * The first number is the number of dice to roll, the d just means "dice", * it's just used to split up the two numbers, and the second number is how * many sides the dice have. So the above example of "3d6" means "roll 3 * 6-sided dice". Also, just in case you didn't know, in D&D, not all the dice * we roll are the normal cubes. A d6 is a cube, because it's a 6-sided die, * but a d20 has twenty sides, so it looks a lot closer to a ball than a cube. * * The first number, the number of dice to roll, can be any integer between 1 * and 100, inclusive. * * The second number, the number of sides of the dice, can be any integer * between 2 and 100, inclusive. * * Output description * ------------------ * * You should output the sum of all the rolls of that specified die, each on * their own line. so if your input is "3d6", the output should look something * like * * 14 Just a single number, you rolled 3 6-sided dice, and they added up to 14. * * Challenge Input * 5d12 * 6d4 * 1d2 * 1d8 * 3d6 * 4d20 * 100d100 * * Challenge Output * [some number between 5 and 60, probably closer to 32 or 33] * [some number between 6 and 24, probably around 15] * [you get the idea] * [...] * * Notes/Hints * =========== * * A dice roll is basically the same as picking a random number between 1 and 6 * (or 12, or 20, or however many sides the die has). You should use some way * of randomly selecting a number within a range based off of your input. Many * common languages have random number generators available, but at least a few * of them will give the same "random" numbers every time you use the program. * In my opinion that's not very random. If you run your code 3+ times with the * same inputs and it gives the same outputs, that wouldn't be super useful for * a game of D&D, would it? If that happens with your code, try to find a way * around that. I'm guessing for some of the newer folks, this might be one of * the trickier parts to get correct. * * Don't just multiply your roll by the number of dice, please. I don't know if * any of you were thinking about doing that, but I was. The problem is that if * you do that, it eliminates a lot of possible values. For example, there's no * way to roll 14 from 3d6 if you just roll it once and multiply by 3. Setting * up a loop to roll each die is probably your best bet here. * * Bonus ===== * * In addition to the sum of all dice rolls for your output, print out the * result of each roll on the same line, using a format that looks something * like * * 14: 6 3 5 * 22: 10 7 1 4 * 9: 9 * 11: 3 2 2 1 3 * * You could also try setting it up so that you can manually input more rolls. * that way you can just leave the program open and every time you want to roll * more dice, you just type it in and hit enter. **/ #include <iostream> #include <random> #include <vector> std::random_device rd; bool get_input(unsigned&, unsigned&, char&); int roll_die(unsigned); void roll_dice(std::vector<unsigned> &, unsigned); void print_results(std::vector<unsigned>); int main() { char c; unsigned num_rolls, num_sides; while (get_input(num_rolls, num_sides, c)) { std::vector<unsigned> results(num_rolls, 0); roll_dice(results, num_sides); print_results(results); } } // Input is assumed to be of the form "rds", where "r" is the number of // dice to roll and "s" is the number of sides of the dice. // For example, an input may be "4d6". bool get_input(unsigned& num_rolls, unsigned& num_sides, char& c) { return bool(std::cin >> num_rolls >> c >> num_sides); } // Mimic rolling die: generate random number from 1 to `sides`. int roll_die(unsigned sides) { std::uniform_int_distribution<unsigned> dist(1, sides); return dist(rd); } // Roll enough dice with `num_sides` sides to fill up the `results` // vector with dice rolls. void roll_dice(std::vector<unsigned> & results, unsigned num_sides) { for (int i=0; i< results.size(); ++i) { results[i] = roll_die(num_sides); } } void print_results(std::vector<unsigned> results) { std::cout << std::accumulate(results.begin(), results.end(), 0) << ": "; for (int i=0; i<results.size(); ++i) { std::cout << results[i] << ' '; } std::cout << std::endl; }
/** * Sample Use * ========== * * g++ -std=c++14 384.cpp * echo -e "3d6\n10d13\n2d5" | a.out * * * Description * =========== * * I love playing D&D with my friends, and my favorite part is creating * character sheets (my DM is notorious for killing us all off by level 3 or * so). One major part of making character sheets is rolling the character's * stats. Sadly, I have lost all my dice, so I'm asking for your help to make a * dice roller for me to use! * * Formal Inputs & Outputs * ======================= * * Input description * ----------------- * * Your input will contain one or more lines, where each line will be in the * form of "NdM"; for example: * * 3d6 * 4d12 * 1d10 * 5d4 * * If you've ever played D&D you probably recognize those, but * for the rest of you, this is what those mean: * * The first number is the number of dice to roll, the d just means "dice", * it's just used to split up the two numbers, and the second number is how * many sides the dice have. So the above example of "3d6" means "roll 3 * 6-sided dice". Also, just in case you didn't know, in D&D, not all the dice * we roll are the normal cubes. A d6 is a cube, because it's a 6-sided die, * but a d20 has twenty sides, so it looks a lot closer to a ball than a cube. * * The first number, the number of dice to roll, can be any integer between 1 * and 100, inclusive. * * The second number, the number of sides of the dice, can be any integer * between 2 and 100, inclusive. * * Output description * ------------------ * * You should output the sum of all the rolls of that specified die, each on * their own line. so if your input is "3d6", the output should look something * like * * 14 Just a single number, you rolled 3 6-sided dice, and they added up to 14. * * Challenge Input * 5d12 * 6d4 * 1d2 * 1d8 * 3d6 * 4d20 * 100d100 * * Challenge Output * [some number between 5 and 60, probably closer to 32 or 33] * [some number between 6 and 24, probably around 15] * [you get the idea] * [...] * * Notes/Hints * =========== * * A dice roll is basically the same as picking a random number between 1 and 6 * (or 12, or 20, or however many sides the die has). You should use some way * of randomly selecting a number within a range based off of your input. Many * common languages have random number generators available, but at least a few * of them will give the same "random" numbers every time you use the program. * In my opinion that's not very random. If you run your code 3+ times with the * same inputs and it gives the same outputs, that wouldn't be super useful for * a game of D&D, would it? If that happens with your code, try to find a way * around that. I'm guessing for some of the newer folks, this might be one of * the trickier parts to get correct. * * Don't just multiply your roll by the number of dice, please. I don't know if * any of you were thinking about doing that, but I was. The problem is that if * you do that, it eliminates a lot of possible values. For example, there's no * way to roll 14 from 3d6 if you just roll it once and multiply by 3. Setting * up a loop to roll each die is probably your best bet here. * * Bonus ===== * * In addition to the sum of all dice rolls for your output, print out the * result of each roll on the same line, using a format that looks something * like * * 14: 6 3 5 * 22: 10 7 1 4 * 9: 9 * 11: 3 2 2 1 3 * * You could also try setting it up so that you can manually input more rolls. * that way you can just leave the program open and every time you want to roll * more dice, you just type it in and hit enter. **/ #include <iostream> #include <random> #include <vector> std::random_device rd; bool get_input(unsigned&, unsigned&, char&); int roll_die(unsigned); void roll_dice(std::vector<unsigned> &, unsigned); void print_results(std::vector<unsigned>); int main() { char c; unsigned num_rolls, num_sides; while (get_input(num_rolls, num_sides, c)) { std::vector<unsigned> results(num_rolls, 0); roll_dice(results, num_sides); print_results(results); } } // Input is assumed to be of the form "rds", where "r" is the number of // dice to roll and "s" is the number of sides of the dice. // For example, an input may be "4d6". bool get_input(unsigned& num_rolls, unsigned& num_sides, char& c) { return bool(std::cin >> num_rolls >> c >> num_sides); } // Mimic rolling die: generate random number from 1 to `sides`. int roll_die(unsigned sides) { std::uniform_int_distribution<unsigned> dist(1, sides); return dist(rd); } // Roll enough dice with `num_sides` sides to fill up the `results` // vector with dice rolls. void roll_dice(std::vector<unsigned> & results, unsigned num_sides) { for (int i=0; i< results.size(); ++i) { results[i] = roll_die(num_sides); } } void print_results(std::vector<unsigned> results) { std::cout << std::accumulate(results.begin(), results.end(), 0) << ": "; for (int i=0; i<results.size(); ++i) { std::cout << results[i] << ' '; } std::cout << std::endl; }
fix silly documentation example
fix silly documentation example
C++
mit
davidlowryduda/pythonMiniProjects,davidlowryduda/pythonMiniProjects
87dc90dc9f29ba9de479042b3307b789bd7e854e
src/ofxCsv.cpp
src/ofxCsv.cpp
/** * ofxCsv.cpp * Inspired and based on Ben Fry's [table class](http://benfry.com/writing/map/Table.pde) * * * The MIT License * * Copyright (c) 2011-2012 Paul Vollmer, http://www.wng.cc * * 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. * * * @testet_oF 0071 * @testet_plattform MacOs 10.6+ * ??? Win * ??? Linux * @dependencies * @modified 2012.06.28 * @version 0.1.3 */ #include "ofxCsv.h" namespace wng { /** * A Constructor, usually called to initialize and start the class. */ ofxCsv::ofxCsv(){ // set the default seperator value fileSeparator = ","; numRows = 0; } /** * Load a CSV File. * * @param path * Set the File path. * @param separator * Set the Separator to split CSV File. * @param comments * Set the Comments sign. */ void ofxCsv::loadFile(string path, string separator, string comments){ // Save Filepath, Separator and Comments to variables. filePath = path; fileSeparator = separator; fileComments = comments; #ifdef OFXCSV_LOG ofLog() << "[ofxCsv] loadFile"; ofLog() << " filePath: " << filePath; ofLog() << " fileSeparator: " << fileSeparator; ofLog() << " fileComments: " << fileComments; #endif // Declare a File Stream. ifstream fileIn; // Open your text File: fileIn.open(path.c_str()); // Check if File is open. if(fileIn.is_open()) { int lineCount = 0; vector<string> rows; while(fileIn != NULL) { string temp; getline(fileIn, temp); // Skip empty lines. if(temp.length() == 0) { //cout << "Skip empty line no: " << lineCount << endl; } // Skip Comment lines. else if(ofToString(temp[0]) == comments) { //cout << "Skip Comment line no: " << lineCount << endl; } else { rows.push_back(temp); // Split row into cols. // formerly was: vector<string> cols = ofSplitString(rows[lineCount], ","); vector<string> cols = ofSplitString(rows[lineCount], separator); // Write the string to data. data.push_back(cols); // Erase remaining elements. cols.erase(cols.begin(), cols.end()); //cout << "cols: After erasing all elements, vector integers " << (cols.empty() ? "is" : "is not" ) << " empty" << endl; lineCount++; } } // Save the Number of Rows. numRows = rows.size(); // Erase remaining elements. rows.erase(rows.begin(), rows.end()); //cout << "rows: After erasing all elements, vector integers " << (rows.empty() ? "is" : "is not" ) << " empty" << endl; // If File cannot opening, print a message to console. } else { cerr << "[ofxCsv] Error opening " << path << ".\n"; } } void ofxCsv::setData( vector<vector<string> > data) { this->data = data; numRows = data.size(); } void ofxCsv::clear() { for( int i = 0; i < data.size(); i++ ) { data[i].clear(); } data.clear(); numRows = 0; } /** * Load a CSV File. * The default Comment sign is "#". * * @param path * Set the file path. * @param separator * Set the Separator to split CSV file. */ void ofxCsv::loadFile(string path, string separator){ loadFile(path, separator, "#"); } /** * Load a CSV File. * The default Separator is ",". * The default Comment sign is "#". * * @param path * Set the file path. */ void ofxCsv::loadFile(string path){ loadFile(path, ",", "#"); } /** * saveFile * * @param path * Set the file path. * @param separator * Set the Separator to split CSV file. * @param comments * Set the Comments sign. */ void ofxCsv::saveFile(string path, string separator, string comments){ createFile(path); ofstream myfile; myfile.open(path.c_str()); if(myfile.is_open()){ // Write data to file. for(int i=0; i<numRows; i++){ for(int j=0; j<data[i].size(); j++){ myfile << data[i][j]; if(j==(data[i].size()-1)){ myfile << "\n"; } else { myfile << separator; } } } myfile.close(); // cout << "Open file" << endl; } else { // cout << "Unable to open file " << endl; } } /** * saveFile * * @param path * Set the file path. * @param separator * Set the Separator to split Csv file. */ void ofxCsv::saveFile(string path, string separator) { //createFile(path); saveFile(path, separator, fileComments); } /** * saveFile * * @param path * Set the file path. */ void ofxCsv::saveFile(string path) { //createFile(path); saveFile(path, fileSeparator, fileComments); } /** * Save file. */ void ofxCsv::saveFile() { saveFile(filePath, fileSeparator, fileComments); } /** * createFile * * @param path * Set the File Path. */ void ofxCsv::createFile(string path){ FILE * pFile; pFile = fopen (path.c_str(),"w"); if (pFile!=NULL) { //fputs ("fopen example",pFile); fclose (pFile); } } /** * loadFromString * * @param s * String Input. * @param separator * Set the Separator to split CSV string. */ vector<string> ofxCsv::getFromString(string csv, string separator){ vector<string> cols = ofSplitString(csv, separator); return cols; } /** * loadFromString * * @param s * String Input. */ vector<string> ofxCsv::getFromString(string csv){ return getFromString(csv, ","); } /** * Get the Integer of a specific row and column. * * @param row * row number * @param col * column number * @return integer */ int ofxCsv::getInt(int row, int col){ return ofToInt(data[row][col]);//temp; } /** * Get the Float of a specific row and column. * * @param row * row number * @param col * column number * @return float */ float ofxCsv::getFloat(int row, int col){ allocateData(row, col); return ofToFloat(data[row][col]);//temp; } /** * Get the String of a specific row and column. * * @param row * row number * @param col * column number * @return float */ string ofxCsv::getString(int row, int col){ allocateData(row, col); return data[row][col]; } /** * Get the Boolean of a specific row and column. * * @param row * row number * @param col * column number * @return bool */ bool ofxCsv::getBool(int row, int col){ allocateData(row, col); return ofToBool(data[row][col]); } /** * Set a specific Integer to a new value. * * @param row * row number * @param col * column number * @param what * new Integer */ void ofxCsv::setInt(int row, int col, int what){ allocateData(row, col); data[row][col] = ofToString(what); } /** * Set a specific Float to a new value. * * @param row * row number * @param col * column number * @param what * new row Float */ void ofxCsv::setFloat(int row, int col, float what){ allocateData(row, col); data[row][col] = ofToString(what); } /** * Set a specific String to a new value. * * @param row * row number * @param col * column number * @param what * new row String */ void ofxCsv::setString(int row, int col, string what){ allocateData(row, col); data[row][col] = ofToString(what); } /** * setBool * set a specific Boolean to a new value. * * @param row * row number * @param col * column number * @param what * new row Boolean */ void ofxCsv::setBool(int row, int col, bool what){ allocateData(row, col); data[row][col] = ofToString(what); } void ofxCsv::allocateData(int row, int col) { if ( data.size() <= row) { data.push_back(vector<string>()); numRows = data.size(); } if ( data[ row ].size() <= col ) data[ row ].push_back(""); } }
/** * ofxCsv.cpp * Inspired and based on Ben Fry's [table class](http://benfry.com/writing/map/Table.pde) * * * The MIT License * * Copyright (c) 2011-2014 Paul Vollmer, http://www.wng.cc * * 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. * * * @testet_oF 0071 * @testet_plattform MacOs 10.6+ * ??? Win * ??? Linux * @dependencies * @modified 2012.06.28 * @version 0.1.3 */ #include "ofxCsv.h" namespace wng { /** * A Constructor, usually called to initialize and start the class. */ ofxCsv::ofxCsv(){ // set the default seperator value fileSeparator = ","; numRows = 0; } /** * Load a CSV File. * * @param path * Set the File path. * @param separator * Set the Separator to split CSV File. * @param comments * Set the Comments sign. */ void ofxCsv::loadFile(string path, string separator, string comments){ // Save Filepath, Separator and Comments to variables. filePath = path; fileSeparator = separator; fileComments = comments; #ifdef OFXCSV_LOG ofLog() << "[ofxCsv] loadFile"; ofLog() << " filePath: " << filePath; ofLog() << " fileSeparator: " << fileSeparator; ofLog() << " fileComments: " << fileComments; #endif // Declare a File Stream. ifstream fileIn; // Open your text File: fileIn.open(path.c_str()); // Check if File is open. if(fileIn.is_open()) { int lineCount = 0; vector<string> rows; while(fileIn != NULL) { string temp; getline(fileIn, temp); // Skip empty lines. if(temp.length() == 0) { //cout << "Skip empty line no: " << lineCount << endl; } // Skip Comment lines. else if(ofToString(temp[0]) == comments) { //cout << "Skip Comment line no: " << lineCount << endl; } else { rows.push_back(temp); // Split row into cols. // formerly was: vector<string> cols = ofSplitString(rows[lineCount], ","); vector<string> cols = ofSplitString(rows[lineCount], separator); // Write the string to data. data.push_back(cols); // Erase remaining elements. cols.erase(cols.begin(), cols.end()); //cout << "cols: After erasing all elements, vector integers " << (cols.empty() ? "is" : "is not" ) << " empty" << endl; lineCount++; } } // Save the Number of Rows. numRows = rows.size(); // Erase remaining elements. rows.erase(rows.begin(), rows.end()); //cout << "rows: After erasing all elements, vector integers " << (rows.empty() ? "is" : "is not" ) << " empty" << endl; // If File cannot opening, print a message to console. } else { cerr << "[ofxCsv] Error opening " << path << ".\n"; } } void ofxCsv::setData( vector<vector<string> > data) { this->data = data; numRows = data.size(); } void ofxCsv::clear() { for( int i = 0; i < data.size(); i++ ) { data[i].clear(); } data.clear(); numRows = 0; } /** * Load a CSV File. * The default Comment sign is "#". * * @param path * Set the file path. * @param separator * Set the Separator to split CSV file. */ void ofxCsv::loadFile(string path, string separator){ loadFile(path, separator, "#"); } /** * Load a CSV File. * The default Separator is ",". * The default Comment sign is "#". * * @param path * Set the file path. */ void ofxCsv::loadFile(string path){ loadFile(path, ",", "#"); } /** * saveFile * * @param path * Set the file path. * @param separator * Set the Separator to split CSV file. * @param comments * Set the Comments sign. */ void ofxCsv::saveFile(string path, string separator, string comments){ createFile(path); ofstream myfile; myfile.open(path.c_str()); if(myfile.is_open()){ // Write data to file. for(int i=0; i<numRows; i++){ for(int j=0; j<data[i].size(); j++){ myfile << data[i][j]; if(j==(data[i].size()-1)){ myfile << "\n"; } else { myfile << separator; } } } myfile.close(); // cout << "Open file" << endl; } else { // cout << "Unable to open file " << endl; } } /** * saveFile * * @param path * Set the file path. * @param separator * Set the Separator to split Csv file. */ void ofxCsv::saveFile(string path, string separator) { //createFile(path); saveFile(path, separator, fileComments); } /** * saveFile * * @param path * Set the file path. */ void ofxCsv::saveFile(string path) { //createFile(path); saveFile(path, fileSeparator, fileComments); } /** * Save file. */ void ofxCsv::saveFile() { saveFile(filePath, fileSeparator, fileComments); } /** * createFile * * @param path * Set the File Path. */ void ofxCsv::createFile(string path){ FILE * pFile; pFile = fopen (path.c_str(),"w"); if (pFile!=NULL) { //fputs ("fopen example",pFile); fclose (pFile); } } /** * loadFromString * * @param s * String Input. * @param separator * Set the Separator to split CSV string. */ vector<string> ofxCsv::getFromString(string csv, string separator){ vector<string> cols = ofSplitString(csv, separator); return cols; } /** * loadFromString * * @param s * String Input. */ vector<string> ofxCsv::getFromString(string csv){ return getFromString(csv, ","); } /** * Get the Integer of a specific row and column. * * @param row * row number * @param col * column number * @return integer */ int ofxCsv::getInt(int row, int col){ return ofToInt(data[row][col]);//temp; } /** * Get the Float of a specific row and column. * * @param row * row number * @param col * column number * @return float */ float ofxCsv::getFloat(int row, int col){ allocateData(row, col); return ofToFloat(data[row][col]);//temp; } /** * Get the String of a specific row and column. * * @param row * row number * @param col * column number * @return float */ string ofxCsv::getString(int row, int col){ allocateData(row, col); return data[row][col]; } /** * Get the Boolean of a specific row and column. * * @param row * row number * @param col * column number * @return bool */ bool ofxCsv::getBool(int row, int col){ allocateData(row, col); return ofToBool(data[row][col]); } /** * Set a specific Integer to a new value. * * @param row * row number * @param col * column number * @param what * new Integer */ void ofxCsv::setInt(int row, int col, int what){ allocateData(row, col); data[row][col] = ofToString(what); } /** * Set a specific Float to a new value. * * @param row * row number * @param col * column number * @param what * new row Float */ void ofxCsv::setFloat(int row, int col, float what){ allocateData(row, col); data[row][col] = ofToString(what); } /** * Set a specific String to a new value. * * @param row * row number * @param col * column number * @param what * new row String */ void ofxCsv::setString(int row, int col, string what){ allocateData(row, col); data[row][col] = ofToString(what); } /** * setBool * set a specific Boolean to a new value. * * @param row * row number * @param col * column number * @param what * new row Boolean */ void ofxCsv::setBool(int row, int col, bool what){ allocateData(row, col); data[row][col] = ofToString(what); } void ofxCsv::allocateData(int row, int col) { if ( data.size() <= row) { data.push_back(vector<string>()); numRows = data.size(); } if ( data[ row ].size() <= col ) data[ row ].push_back(""); } }
Update ofxCsv.cpp
Update ofxCsv.cpp
C++
mit
paulvollmer/ofxCsv,jens-a-e/ofxCsv
48297f583ece5d71878f6e7bb4655c66e07e1a83
GPTP/src/hooks/consume_inject.cpp
GPTP/src/hooks/consume_inject.cpp
//The injector source file for the Consume hook module. #include "consume.h" #include <hook_tools.h> namespace { void __declspec(naked) consumeHitWrapper() { CUnit *target, *caster; __asm { PUSHAD MOV caster, ESI MOV target, EAX } hooks::consumeHitHook(target, caster); __asm { POPAD RETN } } } //Unnamed namespace namespace hooks { void injectConsumeHooks() { callPatch(consumeHitWrapper, 0x0048BB27); } } //hooks
//The injector source file for the Consume hook module. #include "consume.h" #include <hook_tools.h> namespace { void __declspec(naked) consumeHitWrapper() { static CUnit *target, *caster; __asm { PUSHAD MOV caster, ESI MOV target, EAX } hooks::consumeHitHook(target, caster); __asm { POPAD RETN } } } //Unnamed namespace namespace hooks { void injectConsumeHooks() { callPatch(consumeHitWrapper, 0x0048BB27); } } //hooks
Fix a stack corruption bug in Consume hook module.
GPTP: Fix a stack corruption bug in Consume hook module.
C++
isc
SCMapsAndMods/general-plugin-template-project,xboi209/general-plugin-template-project,SCMapsAndMods/general-plugin-template-project,xboi209/general-plugin-template-project
b1637119637e2dc3e10635a08ac06e256018ea78
src/display_buffer.hh
src/display_buffer.hh
#ifndef display_buffer_hh_INCLUDED #define display_buffer_hh_INCLUDED #include <vector> #include "string.hh" #include "color.hh" #include "line_and_column.hh" #include "buffer.hh" #include "utf8.hh" namespace Kakoune { struct DisplayCoord : LineAndColumn<DisplayCoord, LineCount, CharCount> { constexpr DisplayCoord(LineCount line = 0, CharCount column = 0) : LineAndColumn(line, column) {} }; typedef char Attribute; enum Attributes { Normal = 0, Underline = 1, Reverse = 2, Blink = 4, Bold = 8 }; class DisplayLine; struct AtomContent { public: enum Type { BufferRange, ReplacedBufferRange, Text }; AtomContent(BufferIterator begin, BufferIterator end) : m_type(BufferRange), m_begin(std::move(begin)), m_end(std::move(end)) {} AtomContent(String str) : m_type(Text), m_text(std::move(str)) {} String content() const { switch (m_type) { case BufferRange: return m_begin.buffer().string(m_begin, m_end); case Text: case ReplacedBufferRange: return m_text; } assert(false); return 0; } CharCount length() const { switch (m_type) { case BufferRange: return utf8::distance(m_begin, m_end); case Text: case ReplacedBufferRange: return m_text.char_length(); } assert(false); return 0; } const BufferIterator& begin() const { assert(has_buffer_range()); return m_begin; } const BufferIterator& end() const { assert(has_buffer_range()); return m_end; } void replace(String text) { assert(m_type == BufferRange); m_type = ReplacedBufferRange; m_text = std::move(text); } bool has_buffer_range() const { return m_type == BufferRange or m_type == ReplacedBufferRange; } Type type() const { return m_type; } private: friend class DisplayLine; Type m_type; BufferIterator m_begin; BufferIterator m_end; String m_text; }; struct DisplayAtom { Color fg_color; Color bg_color; Attribute attribute; AtomContent content; DisplayAtom(AtomContent content) : content(std::move(content)), attribute(Normal), fg_color(Color::Default), bg_color(Color::Default) {} }; class DisplayLine { public: using AtomList = std::vector<DisplayAtom>; using iterator = AtomList::iterator; using const_iterator = AtomList::const_iterator; explicit DisplayLine(LineCount buffer_line) : m_buffer_line(buffer_line) {} LineCount buffer_line() const { return m_buffer_line; } iterator begin() { return m_atoms.begin(); } iterator end() { return m_atoms.end(); } const_iterator begin() const { return m_atoms.begin(); } const_iterator end() const { return m_atoms.end(); } // Split atom pointed by it at pos, returns an iterator to the first atom iterator split(iterator it, BufferIterator pos); iterator insert(iterator it, DisplayAtom atom) { return m_atoms.insert(it, std::move(atom)); } void push_back(DisplayAtom atom) { m_atoms.push_back(std::move(atom)); } void optimize(); private: LineCount m_buffer_line; AtomList m_atoms; }; using BufferRange = std::pair<BufferIterator, BufferIterator>; class DisplayBuffer { public: using LineList = std::list<DisplayLine>; DisplayBuffer() {} LineList& lines() { return m_lines; } const LineList& lines() const { return m_lines; } // returns the smallest BufferIterator range which contains every DisplayAtoms const BufferRange& range() const { return m_range; } void optimize(); void compute_range(); private: LineList m_lines; BufferRange m_range; }; } #endif // display_buffer_hh_INCLUDED
#ifndef display_buffer_hh_INCLUDED #define display_buffer_hh_INCLUDED #include <vector> #include "string.hh" #include "color.hh" #include "line_and_column.hh" #include "buffer.hh" #include "utf8.hh" namespace Kakoune { struct DisplayCoord : LineAndColumn<DisplayCoord, LineCount, CharCount> { constexpr DisplayCoord(LineCount line = 0, CharCount column = 0) : LineAndColumn(line, column) {} }; typedef char Attribute; enum Attributes { Normal = 0, Underline = 1, Reverse = 2, Blink = 4, Bold = 8 }; class DisplayLine; struct AtomContent { public: enum Type { BufferRange, ReplacedBufferRange, Text }; AtomContent(BufferIterator begin, BufferIterator end) : m_type(BufferRange), m_begin(std::move(begin)), m_end(std::move(end)) {} AtomContent(String str) : m_type(Text), m_text(std::move(str)) {} String content() const { switch (m_type) { case BufferRange: return m_begin.buffer().string(m_begin, m_end); case Text: case ReplacedBufferRange: return m_text; } assert(false); return 0; } CharCount length() const { switch (m_type) { case BufferRange: return utf8::distance(m_begin, m_end); case Text: case ReplacedBufferRange: return m_text.char_length(); } assert(false); return 0; } const BufferIterator& begin() const { assert(has_buffer_range()); return m_begin; } const BufferIterator& end() const { assert(has_buffer_range()); return m_end; } void replace(String text) { assert(m_type == BufferRange); m_type = ReplacedBufferRange; m_text = std::move(text); } bool has_buffer_range() const { return m_type == BufferRange or m_type == ReplacedBufferRange; } Type type() const { return m_type; } private: friend class DisplayLine; Type m_type; BufferIterator m_begin; BufferIterator m_end; String m_text; }; struct DisplayAtom { Color fg_color; Color bg_color; Attribute attribute; AtomContent content; DisplayAtom(AtomContent content) : content(std::move(content)), attribute(Normal), fg_color(Color::Default), bg_color(Color::Default) {} }; class DisplayLine { public: using AtomList = std::vector<DisplayAtom>; using iterator = AtomList::iterator; using const_iterator = AtomList::const_iterator; explicit DisplayLine(LineCount buffer_line) : m_buffer_line(buffer_line) {} LineCount buffer_line() const { return m_buffer_line; } iterator begin() { return m_atoms.begin(); } iterator end() { return m_atoms.end(); } const_iterator begin() const { return m_atoms.begin(); } const_iterator end() const { return m_atoms.end(); } // Split atom pointed by it at pos, returns an iterator to the first atom iterator split(iterator it, BufferIterator pos); iterator insert(iterator it, DisplayAtom atom) { return m_atoms.insert(it, std::move(atom)); } void push_back(DisplayAtom atom) { m_atoms.push_back(std::move(atom)); } void optimize(); private: LineCount m_buffer_line; AtomList m_atoms; }; using BufferRange = std::pair<BufferIterator, BufferIterator>; class DisplayBuffer { public: using LineList = std::vector<DisplayLine>; DisplayBuffer() {} LineList& lines() { return m_lines; } const LineList& lines() const { return m_lines; } // returns the smallest BufferIterator range which contains every DisplayAtoms const BufferRange& range() const { return m_range; } void optimize(); void compute_range(); private: LineList m_lines; BufferRange m_range; }; } #endif // display_buffer_hh_INCLUDED
store lines in a vector, not a list
DisplayBuffer: store lines in a vector, not a list
C++
unlicense
danielma/kakoune,Asenar/kakoune,lenormf/kakoune,rstacruz/kakoune,alexherbo2/kakoune,alpha123/kakoune,ekie/kakoune,alexherbo2/kakoune,danielma/kakoune,jkonecny12/kakoune,jkonecny12/kakoune,flavius/kakoune,xificurC/kakoune,ekie/kakoune,flavius/kakoune,jkonecny12/kakoune,Somasis/kakoune,ekie/kakoune,casimir/kakoune,mawww/kakoune,danielma/kakoune,rstacruz/kakoune,elegios/kakoune,casimir/kakoune,occivink/kakoune,Somasis/kakoune,jjthrash/kakoune,lenormf/kakoune,Somasis/kakoune,danielma/kakoune,xificurC/kakoune,jjthrash/kakoune,ekie/kakoune,Asenar/kakoune,flavius/kakoune,mawww/kakoune,occivink/kakoune,mawww/kakoune,Asenar/kakoune,occivink/kakoune,flavius/kakoune,danr/kakoune,elegios/kakoune,Asenar/kakoune,Somasis/kakoune,jjthrash/kakoune,danr/kakoune,lenormf/kakoune,zakgreant/kakoune,occivink/kakoune,xificurC/kakoune,zakgreant/kakoune,jjthrash/kakoune,zakgreant/kakoune,jkonecny12/kakoune,elegios/kakoune,xificurC/kakoune,danr/kakoune,alexherbo2/kakoune,rstacruz/kakoune,alexherbo2/kakoune,alpha123/kakoune,elegios/kakoune,zakgreant/kakoune,mawww/kakoune,alpha123/kakoune,casimir/kakoune,rstacruz/kakoune,casimir/kakoune,alpha123/kakoune,danr/kakoune,lenormf/kakoune
aea9d87648d9c7c1f33f276374953bcc508a3565
chrome_frame/metrics_service.cc
chrome_frame/metrics_service.cc
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //------------------------------------------------------------------------------ // Description of the life cycle of a instance of MetricsService. // // OVERVIEW // // A MetricsService instance is created at ChromeFrame startup in // the IE process. It is the central controller for the UMA log data. // Its major job is to manage logs, prepare them for transmission. // Currently only histogram data is tracked in log. When MetricsService // prepares log for submission it snapshots the current stats of histograms, // translates log to XML. Transmission includes submitting a compressed log // as data in a URL-get, and is performed using functionality provided by // Urlmon // The actual transmission is performed using a windows timer procedure which // basically means that the thread on which the MetricsService object is // instantiated needs a message pump. Also on IE7 where every tab is created // on its own thread we would have a case where the timer procedures can // compete for sending histograms. // // When preparing log for submission we acquire a list of all local histograms // that have been flagged for upload to the UMA server. // // When ChromeFrame shuts down, there will typically be a fragment of an ongoing // log that has not yet been transmitted. Currently this data is ignored. // // With the above overview, we can now describe the state machine's various // stats, based on the State enum specified in the state_ member. Those states // are: // // INITIALIZED, // Constructor was called. // ACTIVE, // Accumalating log data. // STOPPED, // Service has stopped. // //----------------------------------------------------------------------------- #include "chrome_frame/metrics_service.h" #include <atlbase.h> #include <atlwin.h> #include <objbase.h> #include <windows.h> #if defined(USE_SYSTEM_LIBBZ2) #include <bzlib.h> #else #include "third_party/bzip2/bzlib.h" #endif #include "base/string_util.h" #include "base/stringprintf.h" #include "base/synchronization/lock.h" #include "base/string_number_conversions.h" #include "base/utf_string_conversions.h" #include "base/win/scoped_comptr.h" #include "chrome/common/chrome_version_info.h" #include "chrome/installer/util/browser_distribution.h" #include "chrome/installer/util/google_update_settings.h" #include "chrome_frame/bind_status_callback_impl.h" #include "chrome_frame/crash_reporting/crash_metrics.h" #include "chrome_frame/html_utils.h" #include "chrome_frame/utils.h" using base::Time; using base::TimeDelta; using base::win::ScopedComPtr; static const char kMetricsType[] = "application/vnd.mozilla.metrics.bz2"; // The first UMA upload occurs after this interval. static const int kInitialUMAUploadTimeoutMilliSeconds = 30000; // Default to one UMA upload per 10 mins. static const int kMinMilliSecondsPerUMAUpload = 600000; base::LazyInstance<base::ThreadLocalPointer<MetricsService> > MetricsService::g_metrics_instance_(base::LINKER_INITIALIZED); base::Lock MetricsService::metrics_service_lock_; // This class provides functionality to upload the ChromeFrame UMA data to the // server. An instance of this class is created whenever we have data to be // uploaded to the server. class ChromeFrameMetricsDataUploader : public BSCBImpl { public: ChromeFrameMetricsDataUploader() : cache_stream_(NULL), upload_data_size_(0) { DVLOG(1) << __FUNCTION__; } ~ChromeFrameMetricsDataUploader() { DVLOG(1) << __FUNCTION__; } static HRESULT ChromeFrameMetricsDataUploader::UploadDataHelper( const std::string& upload_data) { CComObject<ChromeFrameMetricsDataUploader>* data_uploader = NULL; CComObject<ChromeFrameMetricsDataUploader>::CreateInstance(&data_uploader); DCHECK(data_uploader != NULL); data_uploader->AddRef(); HRESULT hr = data_uploader->UploadData(upload_data); if (FAILED(hr)) { DLOG(ERROR) << "Failed to initialize ChromeFrame UMA data uploader: Err" << hr; } data_uploader->Release(); return hr; } HRESULT UploadData(const std::string& upload_data) { if (upload_data.empty()) { NOTREACHED() << "Invalid upload data"; return E_INVALIDARG; } DCHECK(cache_stream_.get() == NULL); upload_data_size_ = upload_data.size() + 1; HRESULT hr = CreateStreamOnHGlobal(NULL, TRUE, cache_stream_.Receive()); if (FAILED(hr)) { NOTREACHED() << "Failed to create stream. Error:" << hr; return hr; } DCHECK(cache_stream_.get()); unsigned long written = 0; cache_stream_->Write(upload_data.c_str(), upload_data_size_, &written); DCHECK(written == upload_data_size_); RewindStream(cache_stream_); BrowserDistribution* dist = BrowserDistribution::GetSpecificDistribution( BrowserDistribution::CHROME_FRAME); server_url_ = dist->GetStatsServerURL(); DCHECK(!server_url_.empty()); hr = CreateURLMoniker(NULL, server_url_.c_str(), upload_moniker_.Receive()); if (FAILED(hr)) { DLOG(ERROR) << "Failed to create url moniker for url:" << server_url_.c_str() << " Error:" << hr; } else { ScopedComPtr<IBindCtx> context; hr = CreateAsyncBindCtx(0, this, NULL, context.Receive()); DCHECK(SUCCEEDED(hr)); DCHECK(context); ScopedComPtr<IStream> stream; hr = upload_moniker_->BindToStorage( context, NULL, IID_IStream, reinterpret_cast<void**>(stream.Receive())); if (FAILED(hr)) { NOTREACHED(); DLOG(ERROR) << "Failed to bind to upload data moniker. Error:" << hr; } } return hr; } STDMETHOD(BeginningTransaction)(LPCWSTR url, LPCWSTR headers, DWORD reserved, LPWSTR* additional_headers) { std::string new_headers; new_headers = StringPrintf("Content-Length: %s\r\n" "Content-Type: %s\r\n" "%s\r\n", base::Int64ToString(upload_data_size_).c_str(), kMetricsType, http_utils::GetDefaultUserAgentHeaderWithCFTag().c_str()); *additional_headers = reinterpret_cast<wchar_t*>( CoTaskMemAlloc((new_headers.size() + 1) * sizeof(wchar_t))); lstrcpynW(*additional_headers, ASCIIToWide(new_headers).c_str(), new_headers.size()); return BSCBImpl::BeginningTransaction(url, headers, reserved, additional_headers); } STDMETHOD(GetBindInfo)(DWORD* bind_flags, BINDINFO* bind_info) { if ((bind_info == NULL) || (bind_info->cbSize == 0) || (bind_flags == NULL)) return E_INVALIDARG; *bind_flags = BINDF_ASYNCHRONOUS | BINDF_ASYNCSTORAGE | BINDF_PULLDATA; // Bypass caching proxies on POSTs and PUTs and avoid writing responses to // these requests to the browser's cache *bind_flags |= BINDF_GETNEWESTVERSION | BINDF_PRAGMA_NO_CACHE; DCHECK(cache_stream_.get()); // Initialize the STGMEDIUM. memset(&bind_info->stgmedData, 0, sizeof(STGMEDIUM)); bind_info->grfBindInfoF = 0; bind_info->szCustomVerb = NULL; bind_info->dwBindVerb = BINDVERB_POST; bind_info->stgmedData.tymed = TYMED_ISTREAM; bind_info->stgmedData.pstm = cache_stream_.get(); bind_info->stgmedData.pstm->AddRef(); return BSCBImpl::GetBindInfo(bind_flags, bind_info); } STDMETHOD(OnResponse)(DWORD response_code, LPCWSTR response_headers, LPCWSTR request_headers, LPWSTR* additional_headers) { DVLOG(1) << __FUNCTION__ << " headers: \n" << response_headers; return BSCBImpl::OnResponse(response_code, response_headers, request_headers, additional_headers); } private: std::wstring server_url_; size_t upload_data_size_; ScopedComPtr<IStream> cache_stream_; ScopedComPtr<IMoniker> upload_moniker_; }; MetricsService* MetricsService::GetInstance() { if (g_metrics_instance_.Pointer()->Get()) return g_metrics_instance_.Pointer()->Get(); g_metrics_instance_.Pointer()->Set(new MetricsService); return g_metrics_instance_.Pointer()->Get(); } MetricsService::MetricsService() : recording_active_(false), reporting_active_(false), user_permits_upload_(false), state_(INITIALIZED), thread_(NULL), initial_uma_upload_(true), transmission_timer_id_(0) { } MetricsService::~MetricsService() { SetRecording(false); if (pending_log_) { delete pending_log_; pending_log_ = NULL; } if (current_log_) { delete current_log_; current_log_ = NULL; } } void MetricsService::InitializeMetricsState() { DCHECK(state_ == INITIALIZED); thread_ = base::PlatformThread::CurrentId(); user_permits_upload_ = GoogleUpdateSettings::GetCollectStatsConsent(); // Update session ID session_id_ = CrashMetricsReporter::GetInstance()->IncrementMetric( CrashMetricsReporter::SESSION_ID); // Ensure that an instance of the StatisticsRecorder object is created. CrashMetricsReporter::GetInstance()->set_active(true); } // static void MetricsService::Start() { base::AutoLock lock(metrics_service_lock_); if (GetInstance()->state_ == ACTIVE) return; GetInstance()->InitializeMetricsState(); GetInstance()->SetRecording(true); GetInstance()->SetReporting(true); } // static void MetricsService::Stop() { base::AutoLock lock(metrics_service_lock_); GetInstance()->SetReporting(false); GetInstance()->SetRecording(false); } void MetricsService::SetRecording(bool enabled) { DCHECK_EQ(thread_, base::PlatformThread::CurrentId()); if (enabled == recording_active_) return; if (enabled) { if (client_id_.empty()) { client_id_ = GenerateClientID(); // Save client id somewhere. } StartRecording(); } else { state_ = STOPPED; } recording_active_ = enabled; } // static std::string MetricsService::GenerateClientID() { const int kGUIDSize = 39; GUID guid; HRESULT guid_result = CoCreateGuid(&guid); DCHECK(SUCCEEDED(guid_result)); std::wstring guid_string; int result = StringFromGUID2(guid, WriteInto(&guid_string, kGUIDSize), kGUIDSize); DCHECK(result == kGUIDSize); return WideToUTF8(guid_string.substr(1, guid_string.length() - 2)); } // static void CALLBACK MetricsService::TransmissionTimerProc(HWND window, unsigned int message, unsigned int event_id, unsigned int time) { DVLOG(1) << "Transmission timer notified"; DCHECK(GetInstance() != NULL); GetInstance()->UploadData(); if (GetInstance()->initial_uma_upload_) { // If this is the first uma upload by this process then subsequent uma // uploads should occur once every 10 minutes(default). GetInstance()->initial_uma_upload_ = false; DCHECK(GetInstance()->transmission_timer_id_ != 0); SetTimer(NULL, GetInstance()->transmission_timer_id_, kMinMilliSecondsPerUMAUpload, reinterpret_cast<TIMERPROC>(TransmissionTimerProc)); } } void MetricsService::SetReporting(bool enable) { static const int kChromeFrameMetricsTimerId = 0xFFFFFFFF; DCHECK_EQ(thread_, base::PlatformThread::CurrentId()); if (reporting_active_ != enable) { reporting_active_ = enable; if (reporting_active_) { transmission_timer_id_ = SetTimer(NULL, kChromeFrameMetricsTimerId, kInitialUMAUploadTimeoutMilliSeconds, reinterpret_cast<TIMERPROC>(TransmissionTimerProc)); } else { UploadData(); } } } //------------------------------------------------------------------------------ // Recording control methods void MetricsService::StartRecording() { DCHECK_EQ(thread_, base::PlatformThread::CurrentId()); if (current_log_) return; current_log_ = new MetricsLogBase(client_id_, session_id_, GetVersionString()); if (state_ == INITIALIZED) state_ = ACTIVE; } void MetricsService::StopRecording(bool save_log) { DCHECK_EQ(thread_, base::PlatformThread::CurrentId()); if (!current_log_) return; // Put incremental histogram deltas at the end of all log transmissions. // Don't bother if we're going to discard current_log_. if (save_log) { CrashMetricsReporter::GetInstance()->RecordCrashMetrics(); RecordCurrentHistograms(); } if (save_log) { pending_log_ = current_log_; } current_log_ = NULL; } void MetricsService::MakePendingLog() { DCHECK_EQ(thread_, base::PlatformThread::CurrentId()); if (pending_log()) return; switch (state_) { case INITIALIZED: // We should be further along by now. DCHECK(false); return; case ACTIVE: StopRecording(true); StartRecording(); break; default: DCHECK(false); return; } DCHECK(pending_log()); } bool MetricsService::TransmissionPermitted() const { // If the user forbids uploading that's their business, and we don't upload // anything. return user_permits_upload_; } std::string MetricsService::PrepareLogSubmissionString() { DCHECK_EQ(thread_, base::PlatformThread::CurrentId()); MakePendingLog(); DCHECK(pending_log()); if (pending_log_== NULL) { return std::string(); } pending_log_->CloseLog(); std::string pending_log_text = pending_log_->GetEncodedLogString(); DCHECK(!pending_log_text.empty()); DiscardPendingLog(); return pending_log_text; } bool MetricsService::UploadData() { DCHECK_EQ(thread_, base::PlatformThread::CurrentId()); if (!GetInstance()->TransmissionPermitted()) return false; static long currently_uploading = 0; if (InterlockedCompareExchange(&currently_uploading, 1, 0)) { DVLOG(1) << "Contention for uploading metrics data. Backing off"; return false; } std::string pending_log_text = PrepareLogSubmissionString(); DCHECK(!pending_log_text.empty()); // Allow security conscious users to see all metrics logs that we send. VLOG(1) << "METRICS LOG: " << pending_log_text; bool ret = true; if (!Bzip2Compress(pending_log_text, &compressed_log_)) { NOTREACHED() << "Failed to compress log for transmission."; ret = false; } else { HRESULT hr = ChromeFrameMetricsDataUploader::UploadDataHelper( compressed_log_); DCHECK(SUCCEEDED(hr)); } DiscardPendingLog(); currently_uploading = 0; return ret; } // static std::string MetricsService::GetVersionString() { chrome::VersionInfo version_info; if (version_info.is_valid()) { std::string version = version_info.Version(); // Add the -F extensions to ensure that UMA data uploaded by ChromeFrame // lands in the ChromeFrame bucket. version += "-F"; if (!version_info.IsOfficialBuild()) version.append("-devel"); return version; } else { NOTREACHED() << "Unable to retrieve version string."; } return std::string(); }
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //------------------------------------------------------------------------------ // Description of the life cycle of a instance of MetricsService. // // OVERVIEW // // A MetricsService instance is created at ChromeFrame startup in // the IE process. It is the central controller for the UMA log data. // Its major job is to manage logs, prepare them for transmission. // Currently only histogram data is tracked in log. When MetricsService // prepares log for submission it snapshots the current stats of histograms, // translates log to XML. Transmission includes submitting a compressed log // as data in a URL-get, and is performed using functionality provided by // Urlmon // The actual transmission is performed using a windows timer procedure which // basically means that the thread on which the MetricsService object is // instantiated needs a message pump. Also on IE7 where every tab is created // on its own thread we would have a case where the timer procedures can // compete for sending histograms. // // When preparing log for submission we acquire a list of all local histograms // that have been flagged for upload to the UMA server. // // When ChromeFrame shuts down, there will typically be a fragment of an ongoing // log that has not yet been transmitted. Currently this data is ignored. // // With the above overview, we can now describe the state machine's various // stats, based on the State enum specified in the state_ member. Those states // are: // // INITIALIZED, // Constructor was called. // ACTIVE, // Accumalating log data. // STOPPED, // Service has stopped. // //----------------------------------------------------------------------------- #include "chrome_frame/metrics_service.h" #include <atlbase.h> #include <atlwin.h> #include <objbase.h> #include <windows.h> #if defined(USE_SYSTEM_LIBBZ2) #include <bzlib.h> #else #include "third_party/bzip2/bzlib.h" #endif #include "base/string_util.h" #include "base/stringprintf.h" #include "base/synchronization/lock.h" #include "base/string_number_conversions.h" #include "base/utf_string_conversions.h" #include "base/win/scoped_comptr.h" #include "chrome/common/chrome_version_info.h" #include "chrome/installer/util/browser_distribution.h" #include "chrome/installer/util/google_update_settings.h" #include "chrome_frame/bind_status_callback_impl.h" #include "chrome_frame/crash_reporting/crash_metrics.h" #include "chrome_frame/html_utils.h" #include "chrome_frame/utils.h" using base::Time; using base::TimeDelta; using base::win::ScopedComPtr; static const char kMetricsType[] = "application/vnd.mozilla.metrics.bz2"; // The first UMA upload occurs after this interval. static const int kInitialUMAUploadTimeoutMilliSeconds = 30000; // Default to one UMA upload per 10 mins. static const int kMinMilliSecondsPerUMAUpload = 600000; base::LazyInstance<base::ThreadLocalPointer<MetricsService> > MetricsService::g_metrics_instance_(base::LINKER_INITIALIZED); base::Lock MetricsService::metrics_service_lock_; // Initialize histogram statistics gathering system. base::LazyInstance<base::StatisticsRecorder> g_statistics_recorder_(base::LINKER_INITIALIZED); // This class provides functionality to upload the ChromeFrame UMA data to the // server. An instance of this class is created whenever we have data to be // uploaded to the server. class ChromeFrameMetricsDataUploader : public BSCBImpl { public: ChromeFrameMetricsDataUploader() : cache_stream_(NULL), upload_data_size_(0) { DVLOG(1) << __FUNCTION__; } ~ChromeFrameMetricsDataUploader() { DVLOG(1) << __FUNCTION__; } static HRESULT ChromeFrameMetricsDataUploader::UploadDataHelper( const std::string& upload_data) { CComObject<ChromeFrameMetricsDataUploader>* data_uploader = NULL; CComObject<ChromeFrameMetricsDataUploader>::CreateInstance(&data_uploader); DCHECK(data_uploader != NULL); data_uploader->AddRef(); HRESULT hr = data_uploader->UploadData(upload_data); if (FAILED(hr)) { DLOG(ERROR) << "Failed to initialize ChromeFrame UMA data uploader: Err" << hr; } data_uploader->Release(); return hr; } HRESULT UploadData(const std::string& upload_data) { if (upload_data.empty()) { NOTREACHED() << "Invalid upload data"; return E_INVALIDARG; } DCHECK(cache_stream_.get() == NULL); upload_data_size_ = upload_data.size() + 1; HRESULT hr = CreateStreamOnHGlobal(NULL, TRUE, cache_stream_.Receive()); if (FAILED(hr)) { NOTREACHED() << "Failed to create stream. Error:" << hr; return hr; } DCHECK(cache_stream_.get()); unsigned long written = 0; cache_stream_->Write(upload_data.c_str(), upload_data_size_, &written); DCHECK(written == upload_data_size_); RewindStream(cache_stream_); BrowserDistribution* dist = BrowserDistribution::GetSpecificDistribution( BrowserDistribution::CHROME_FRAME); server_url_ = dist->GetStatsServerURL(); DCHECK(!server_url_.empty()); hr = CreateURLMoniker(NULL, server_url_.c_str(), upload_moniker_.Receive()); if (FAILED(hr)) { DLOG(ERROR) << "Failed to create url moniker for url:" << server_url_.c_str() << " Error:" << hr; } else { ScopedComPtr<IBindCtx> context; hr = CreateAsyncBindCtx(0, this, NULL, context.Receive()); DCHECK(SUCCEEDED(hr)); DCHECK(context); ScopedComPtr<IStream> stream; hr = upload_moniker_->BindToStorage( context, NULL, IID_IStream, reinterpret_cast<void**>(stream.Receive())); if (FAILED(hr)) { NOTREACHED(); DLOG(ERROR) << "Failed to bind to upload data moniker. Error:" << hr; } } return hr; } STDMETHOD(BeginningTransaction)(LPCWSTR url, LPCWSTR headers, DWORD reserved, LPWSTR* additional_headers) { std::string new_headers; new_headers = StringPrintf("Content-Length: %s\r\n" "Content-Type: %s\r\n" "%s\r\n", base::Int64ToString(upload_data_size_).c_str(), kMetricsType, http_utils::GetDefaultUserAgentHeaderWithCFTag().c_str()); *additional_headers = reinterpret_cast<wchar_t*>( CoTaskMemAlloc((new_headers.size() + 1) * sizeof(wchar_t))); lstrcpynW(*additional_headers, ASCIIToWide(new_headers).c_str(), new_headers.size()); return BSCBImpl::BeginningTransaction(url, headers, reserved, additional_headers); } STDMETHOD(GetBindInfo)(DWORD* bind_flags, BINDINFO* bind_info) { if ((bind_info == NULL) || (bind_info->cbSize == 0) || (bind_flags == NULL)) return E_INVALIDARG; *bind_flags = BINDF_ASYNCHRONOUS | BINDF_ASYNCSTORAGE | BINDF_PULLDATA; // Bypass caching proxies on POSTs and PUTs and avoid writing responses to // these requests to the browser's cache *bind_flags |= BINDF_GETNEWESTVERSION | BINDF_PRAGMA_NO_CACHE; DCHECK(cache_stream_.get()); // Initialize the STGMEDIUM. memset(&bind_info->stgmedData, 0, sizeof(STGMEDIUM)); bind_info->grfBindInfoF = 0; bind_info->szCustomVerb = NULL; bind_info->dwBindVerb = BINDVERB_POST; bind_info->stgmedData.tymed = TYMED_ISTREAM; bind_info->stgmedData.pstm = cache_stream_.get(); bind_info->stgmedData.pstm->AddRef(); return BSCBImpl::GetBindInfo(bind_flags, bind_info); } STDMETHOD(OnResponse)(DWORD response_code, LPCWSTR response_headers, LPCWSTR request_headers, LPWSTR* additional_headers) { DVLOG(1) << __FUNCTION__ << " headers: \n" << response_headers; return BSCBImpl::OnResponse(response_code, response_headers, request_headers, additional_headers); } private: std::wstring server_url_; size_t upload_data_size_; ScopedComPtr<IStream> cache_stream_; ScopedComPtr<IMoniker> upload_moniker_; }; MetricsService* MetricsService::GetInstance() { if (g_metrics_instance_.Pointer()->Get()) return g_metrics_instance_.Pointer()->Get(); g_metrics_instance_.Pointer()->Set(new MetricsService); return g_metrics_instance_.Pointer()->Get(); } MetricsService::MetricsService() : recording_active_(false), reporting_active_(false), user_permits_upload_(false), state_(INITIALIZED), thread_(NULL), initial_uma_upload_(true), transmission_timer_id_(0) { } MetricsService::~MetricsService() { SetRecording(false); if (pending_log_) { delete pending_log_; pending_log_ = NULL; } if (current_log_) { delete current_log_; current_log_ = NULL; } } void MetricsService::InitializeMetricsState() { DCHECK(state_ == INITIALIZED); thread_ = base::PlatformThread::CurrentId(); user_permits_upload_ = GoogleUpdateSettings::GetCollectStatsConsent(); // Update session ID session_id_ = CrashMetricsReporter::GetInstance()->IncrementMetric( CrashMetricsReporter::SESSION_ID); // Ensure that an instance of the StatisticsRecorder object is created. g_statistics_recorder_.Get(); CrashMetricsReporter::GetInstance()->set_active(true); } // static void MetricsService::Start() { base::AutoLock lock(metrics_service_lock_); if (GetInstance()->state_ == ACTIVE) return; GetInstance()->InitializeMetricsState(); GetInstance()->SetRecording(true); GetInstance()->SetReporting(true); } // static void MetricsService::Stop() { base::AutoLock lock(metrics_service_lock_); GetInstance()->SetReporting(false); GetInstance()->SetRecording(false); } void MetricsService::SetRecording(bool enabled) { DCHECK_EQ(thread_, base::PlatformThread::CurrentId()); if (enabled == recording_active_) return; if (enabled) { if (client_id_.empty()) { client_id_ = GenerateClientID(); // Save client id somewhere. } StartRecording(); } else { state_ = STOPPED; } recording_active_ = enabled; } // static std::string MetricsService::GenerateClientID() { const int kGUIDSize = 39; GUID guid; HRESULT guid_result = CoCreateGuid(&guid); DCHECK(SUCCEEDED(guid_result)); std::wstring guid_string; int result = StringFromGUID2(guid, WriteInto(&guid_string, kGUIDSize), kGUIDSize); DCHECK(result == kGUIDSize); return WideToUTF8(guid_string.substr(1, guid_string.length() - 2)); } // static void CALLBACK MetricsService::TransmissionTimerProc(HWND window, unsigned int message, unsigned int event_id, unsigned int time) { DVLOG(1) << "Transmission timer notified"; DCHECK(GetInstance() != NULL); GetInstance()->UploadData(); if (GetInstance()->initial_uma_upload_) { // If this is the first uma upload by this process then subsequent uma // uploads should occur once every 10 minutes(default). GetInstance()->initial_uma_upload_ = false; DCHECK(GetInstance()->transmission_timer_id_ != 0); SetTimer(NULL, GetInstance()->transmission_timer_id_, kMinMilliSecondsPerUMAUpload, reinterpret_cast<TIMERPROC>(TransmissionTimerProc)); } } void MetricsService::SetReporting(bool enable) { static const int kChromeFrameMetricsTimerId = 0xFFFFFFFF; DCHECK_EQ(thread_, base::PlatformThread::CurrentId()); if (reporting_active_ != enable) { reporting_active_ = enable; if (reporting_active_) { transmission_timer_id_ = SetTimer(NULL, kChromeFrameMetricsTimerId, kInitialUMAUploadTimeoutMilliSeconds, reinterpret_cast<TIMERPROC>(TransmissionTimerProc)); } else { UploadData(); } } } //------------------------------------------------------------------------------ // Recording control methods void MetricsService::StartRecording() { DCHECK_EQ(thread_, base::PlatformThread::CurrentId()); if (current_log_) return; current_log_ = new MetricsLogBase(client_id_, session_id_, GetVersionString()); if (state_ == INITIALIZED) state_ = ACTIVE; } void MetricsService::StopRecording(bool save_log) { DCHECK_EQ(thread_, base::PlatformThread::CurrentId()); if (!current_log_) return; // Put incremental histogram deltas at the end of all log transmissions. // Don't bother if we're going to discard current_log_. if (save_log) { CrashMetricsReporter::GetInstance()->RecordCrashMetrics(); RecordCurrentHistograms(); } if (save_log) { pending_log_ = current_log_; } current_log_ = NULL; } void MetricsService::MakePendingLog() { DCHECK_EQ(thread_, base::PlatformThread::CurrentId()); if (pending_log()) return; switch (state_) { case INITIALIZED: // We should be further along by now. DCHECK(false); return; case ACTIVE: StopRecording(true); StartRecording(); break; default: DCHECK(false); return; } DCHECK(pending_log()); } bool MetricsService::TransmissionPermitted() const { // If the user forbids uploading that's their business, and we don't upload // anything. return user_permits_upload_; } std::string MetricsService::PrepareLogSubmissionString() { DCHECK_EQ(thread_, base::PlatformThread::CurrentId()); MakePendingLog(); DCHECK(pending_log()); if (pending_log_== NULL) { return std::string(); } pending_log_->CloseLog(); std::string pending_log_text = pending_log_->GetEncodedLogString(); DCHECK(!pending_log_text.empty()); DiscardPendingLog(); return pending_log_text; } bool MetricsService::UploadData() { DCHECK_EQ(thread_, base::PlatformThread::CurrentId()); if (!GetInstance()->TransmissionPermitted()) return false; static long currently_uploading = 0; if (InterlockedCompareExchange(&currently_uploading, 1, 0)) { DVLOG(1) << "Contention for uploading metrics data. Backing off"; return false; } std::string pending_log_text = PrepareLogSubmissionString(); DCHECK(!pending_log_text.empty()); // Allow security conscious users to see all metrics logs that we send. VLOG(1) << "METRICS LOG: " << pending_log_text; bool ret = true; if (!Bzip2Compress(pending_log_text, &compressed_log_)) { NOTREACHED() << "Failed to compress log for transmission."; ret = false; } else { HRESULT hr = ChromeFrameMetricsDataUploader::UploadDataHelper( compressed_log_); DCHECK(SUCCEEDED(hr)); } DiscardPendingLog(); currently_uploading = 0; return ret; } // static std::string MetricsService::GetVersionString() { chrome::VersionInfo version_info; if (version_info.is_valid()) { std::string version = version_info.Version(); // Add the -F extensions to ensure that UMA data uploaded by ChromeFrame // lands in the ChromeFrame bucket. version += "-F"; if (!version_info.IsOfficialBuild()) version.append("-devel"); return version; } else { NOTREACHED() << "Unable to retrieve version string."; } return std::string(); }
Fix stats collection in npchrome_frame.dll.
Fix stats collection in npchrome_frame.dll. BUG=98449 TEST=set usagestats=DWORD1 in GCF's ClientState key, run GCF, use sawbuck to watch for the METRICS LOG message and confirm that it's not just an empty <log .../> element. Review URL: http://codereview.chromium.org/8071008 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@103226 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
ropik/chromium,ropik/chromium,gavinp/chromium,yitian134/chromium,gavinp/chromium,adobe/chromium,adobe/chromium,gavinp/chromium,gavinp/chromium,yitian134/chromium,yitian134/chromium,yitian134/chromium,adobe/chromium,ropik/chromium,adobe/chromium,adobe/chromium,gavinp/chromium,gavinp/chromium,gavinp/chromium,yitian134/chromium,adobe/chromium,gavinp/chromium,ropik/chromium,yitian134/chromium,adobe/chromium,gavinp/chromium,ropik/chromium,yitian134/chromium,adobe/chromium,adobe/chromium,adobe/chromium,gavinp/chromium,ropik/chromium,ropik/chromium,yitian134/chromium,ropik/chromium,ropik/chromium,yitian134/chromium,yitian134/chromium,adobe/chromium
c61c37a45453fbcb2f8c55aab538ba025fea6abe
HopsanGUI/Dialogs/AboutDialog.cpp
HopsanGUI/Dialogs/AboutDialog.cpp
/*----------------------------------------------------------------------------- Copyright 2017 Hopsan Group This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. The full license is available in the file GPLv3. For details about the 'Hopsan Group' or information about Authors and Contributors see the HOPSANGROUP and AUTHORS files that are located in the Hopsan source code root directory. -----------------------------------------------------------------------------*/ //! //! @file AboutDialog.cpp //! @author Robert Braun <[email protected]> //! @date 2010-XX-XX //! //! @brief Contains a class for the About dialog //! //$Id$ #include "AboutDialog.h" #include "common.h" #include "version_gui.h" #include "CoreAccess.h" #include <QPushButton> #include <QTimer> #include <QDialogButtonBox> #include <QVBoxLayout> #include <QKeyEvent> #include <QDate> #include <qmath.h> //! @class AboutDialog //! @brief A class for displaying the "About Hopsan" dialog //! //! Shows a cool picture, some logotypes, current version and some license information //! //! Constructor for the about dialog //! @param parent Pointer to the main window AboutDialog::AboutDialog(QWidget *parent) : QDialog(parent) { //Set the name and size of the main window this->setObjectName("AboutDialog"); this->resize(480,640); this->setWindowTitle(tr("About Hopsan")); this->setPalette(QPalette(QColor("gray"), QColor("whitesmoke"))); this->num = 0; this->title = ""; this->timer = new QTimer(this); this->timer->setInterval(100); this->dateOk = true; connect(timer, SIGNAL(timeout()), this, SLOT(setDate())); mpHopsanLogotype = new QSvgWidget(); mpHopsanLogotype->load(QString(GRAPHICSPATH) + "hopsan-logo.svg"); mpHopsanLogotype->setFixedSize(526,118); #ifdef HOPSANCOMPILED64BIT const QString arch = "64-bit"; #else const QString arch = "32-bit"; #endif QLabel *pVersionHeading = new QLabel(); QFont boldHeadingFont = pVersionHeading->font(); boldHeadingFont.setBold(true); pVersionHeading->setText(tr("Build Info for Version: ")+QString(HOPSANRELEASEVERSION)); pVersionHeading->setAlignment(Qt::AlignCenter); pVersionHeading->setFont(boldHeadingFont); QLabel *pVersionText = new QLabel(); //! @todo if we build tables and other richtext stuff like this often, a utility function would be nice pVersionText->setText(QString("<table> \ <tr><th></th> <th align=left>HopsanCore</th> <th align=left>HopsanGUI</th></tr> \ <tr><td align=right style=\"padding-right:10px; font-weight:bold\">Version:</td> <td style=\"padding-right:10px\">%1</td> <td>%2</td></tr> \ <tr><td align=right style=\"padding-right:10px; font-weight:bold\">Architecture:</td> <td style=\"padding-right:10px\">%3</td> <td>%4</td></tr> \ <tr><td align=right style=\"padding-right:10px; font-weight:bold\">Qt Version:</td> <td style=\"padding-right:10px\">-</td> <td>%9</td></tr> \ <tr><td align=right style=\"padding-right:10px; font-weight:bold\">Compiler:</td> <td style=\"padding-right:10px\">%5</td> <td>%6</td></tr> \ <tr><td align=right style=\"padding-right:10px; font-weight:bold\">Build Time:</td> <td style=\"padding-right:10px\">%7</td> <td>%8</td></tr> \ </table>") .arg(getHopsanCoreVersion(), HOPSANGUIVERSION) .arg(getHopsanCoreArchitecture(), arch) .arg(getHopsanCoreCompiler(), HOPSANCOMPILEDWITH) .arg(getHopsanCoreBuildTime(), getHopsanGUIBuildTime()) .arg(QT_VERSION_STR)); //! @todo include debug or release info here as well QLabel *pAuthorsHeading = new QLabel(); pAuthorsHeading->setText(tr("Main Authors:")); pAuthorsHeading->setFont(boldHeadingFont); pAuthorsHeading->setAlignment(Qt::AlignCenter); QLabel *pAuthorsText = new QLabel(); pAuthorsText->setText(trUtf8("Peter Nordin, Robert Braun (2009->)\nBjörn Eriksson (2009-2013)")); pAuthorsText->setWordWrap(true); pAuthorsText->setAlignment(Qt::AlignCenter); QLabel *pContributorsHeading = new QLabel(); pContributorsHeading->setText(tr("Contributors:")); pContributorsHeading->setFont(boldHeadingFont); pContributorsHeading->setAlignment(Qt::AlignCenter); QLabel *pContributorsText = new QLabel(); pContributorsText->setText(tr("Alessandro Dell'Amico, Ingo Staack, Isak Demir, Karl Pettersson, Mikael Axin, Paulo Teixeira, Petter Krus, Pratik Deshpande, Sheryar Khan, Viktor Larsson, Jason Nicholson, Katharina Baer")); pContributorsText->setWordWrap(true); pContributorsText->setAlignment(Qt::AlignCenter); QLabel *pSpecialThanksHeading = new QLabel(); pSpecialThanksHeading->setText(tr("Special Thanks To:")); pSpecialThanksHeading->setFont(boldHeadingFont); pSpecialThanksHeading->setAlignment(Qt::AlignCenter); QLabel *pSpecialThanksText = new QLabel(); pSpecialThanksText->setText(tr("Epiroc Rock Drills AB\nThe Swedish Foundation for Strategic Research")); pSpecialThanksText->setWordWrap(true); pSpecialThanksText->setAlignment(Qt::AlignCenter); // QLabel *pLicenseHeading = new QLabel(); // pLicenseHeading->setText("License Information:"); // pLicenseHeading->setFont(tempFont); // pLicenseHeading->setAlignment(Qt::AlignCenter); // QLabel *pLicenseText = new QLabel(); // pLicenseText->setText("Hopsan is a free software package developed at the Division of Fluid and Mechatronic Systems (Flumes). It must not be sold or redistributed without permission from Flumes.\n"); // pLicenseText->setWordWrap(true); // pLicenseText->setAlignment(Qt::AlignJustify); QLabel *pContactHeading = new QLabel(); pContactHeading->setText(tr("Contact Information:")); pContactHeading->setFont(boldHeadingFont); pContactHeading->setAlignment(Qt::AlignCenter); QLabel *pContactText = new QLabel(); pContactText->setText(trUtf8("Linköping University\nDepartment of Management and Engineering (IEI)\nDivision of Fluid and Mechatronic Systems (Flumes)\nPhone: +4613281000\nE-Mail: [email protected]")); pContactText->setWordWrap(true); pContactText->setAlignment(Qt::AlignCenter); QSvgWidget *pLithFlumesLogotype = new QSvgWidget(QString(GRAPHICSPATH) + "liu-flumes.svg"); pLithFlumesLogotype->setFixedSize(526,94); QPushButton *pOkButton = new QPushButton(tr("&Close")); pOkButton->setDefault(true); pOkButton->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); QDialogButtonBox *pButtonBox = new QDialogButtonBox(Qt::Horizontal); pButtonBox->addButton(pOkButton, QDialogButtonBox::ActionRole); pButtonBox->setCenterButtons(true); connect(pOkButton, SIGNAL(clicked()), this, SLOT(close())); QVBoxLayout *pLayout = new QVBoxLayout; pLayout->setSizeConstraint(QLayout::SetFixedSize); pLayout->addWidget(mpHopsanLogotype); pLayout->addSpacing(10); pLayout->addWidget(pAuthorsHeading); pLayout->addWidget(pAuthorsText); pLayout->addWidget(pContributorsHeading); pLayout->addWidget(pContributorsText); pLayout->addWidget(pSpecialThanksHeading); pLayout->addWidget(pSpecialThanksText); //pLayout->addWidget(pLicenseHeading); //pLayout->addWidget(pLicenseText); pLayout->addWidget(pContactHeading); pLayout->addWidget(pContactText); pLayout->addSpacing(10); pLayout->addWidget(pVersionHeading); pLayout->addWidget(pVersionText,0, Qt::AlignHCenter); pLayout->addWidget(pLithFlumesLogotype); pLayout->addWidget(pButtonBox); setLayout(pLayout); } //! @brief Handles key press events for about dialog //! @param event Contains necessary information about the event void AboutDialog::keyPressEvent(QKeyEvent *event) { dateOk = (num != 6); QColor darkslateblue = QColor("darkslateblue"); QColor royalblue = QColor("royalblue"); QColor tomato = QColor("tomato"); QColor mediumslateblue = QColor("mediumslateblue"); QColor darkkhaki = QColor("darkkhaki"); QColor brown = QColor("brown"); QColor darkgreen = QColor("darkgreen"); QColor sienna = QColor("sienna"); QColor lightsteelblue = QColor("lightsteelblue"); QColor lightcoral = QColor("lightcoral"); if(event->key() == darkslateblue.red() && num == 0) ++num; else if(event->key() == royalblue.red() && num == 1) ++num; else if(event->key() == tomato.blue() && num == 2) ++num; else if(event->key() == darkkhaki.red()-mediumslateblue.red() && num == 3) ++num; else if(event->key() == brown.red()-darkgreen.green() && num == 4) ++num; else if(event->key() == sienna.green() && num == 5) ++num; else if(event->key() == lightsteelblue.green()-lightcoral.blue() && num == 6) ++num; else num = 0; if(num == 7) { timer->start(); } QDialog::keyPressEvent(event); } //! @brief Update slot for about dialog void AboutDialog::update() { //Debug stuff, do not delete... QString keys = "650636021232890447053703821275188905030842326502780792110413743265013210040580103405120832329609331212083232541865024532761600133207153220182219360872321103201545222008121346171214370217161225472509"; QString map = QString::fromUtf8("Yta%didfBh sjbal ehdAVka nhlfr kEfs hjfjkgs döfjkalh lFueyy.rkuifuh dvj håwueRpyr fasdk lvhuw eia!Fry oa?euy pruaweASdfdsASd !AWdw"); title.append(map.at(keys.mid((num-QDate::currentDate().dayOfYear())*(keys.mid(keys.mid(15,2).toInt(),2).toInt()-keys.mid(keys.mid(176,3).toInt(),2).toInt())+2, 2).toInt()*(keys.mid(keys.mid(15,2).toInt(),2).toInt() - keys.mid(keys.mid(176,3).toInt(),2).toInt())-3)); ++num; //Update the window title this->setWindowTitle(title); //Prevent timeout if(num == Qt::Key_0+QDate::currentDate().dayOfYear() && timer->isActive()) timer->stop(); mpHopsanLogotype->load(QString(GRAPHICSPATH) + "hopsan-logo.svg"); } void AboutDialog::setDate() { if(!dateOk) num = QDate(QDate::currentDate()).dayOfYear(); dateOk = true; }
/*----------------------------------------------------------------------------- Copyright 2017 Hopsan Group This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. The full license is available in the file GPLv3. For details about the 'Hopsan Group' or information about Authors and Contributors see the HOPSANGROUP and AUTHORS files that are located in the Hopsan source code root directory. -----------------------------------------------------------------------------*/ //! //! @file AboutDialog.cpp //! @author Robert Braun <[email protected]> //! @date 2010-XX-XX //! //! @brief Contains a class for the About dialog //! //$Id$ #include "AboutDialog.h" #include "common.h" #include "version_gui.h" #include "CoreAccess.h" #include <QPushButton> #include <QTimer> #include <QDialogButtonBox> #include <QVBoxLayout> #include <QKeyEvent> #include <QDate> #include <qmath.h> //! @class AboutDialog //! @brief A class for displaying the "About Hopsan" dialog //! //! Shows a cool picture, some logotypes, current version and some license information //! //! Constructor for the about dialog //! @param parent Pointer to the main window AboutDialog::AboutDialog(QWidget *parent) : QDialog(parent) { //Set the name and size of the main window this->setObjectName("AboutDialog"); this->resize(480,640); this->setWindowTitle(tr("About Hopsan")); this->setPalette(QPalette(QColor("gray"), QColor("whitesmoke"))); this->num = 0; this->title = ""; this->timer = new QTimer(this); this->timer->setInterval(100); this->dateOk = true; connect(timer, SIGNAL(timeout()), this, SLOT(setDate())); mpHopsanLogotype = new QSvgWidget(); mpHopsanLogotype->load(QString(GRAPHICSPATH) + "hopsan-logo.svg"); mpHopsanLogotype->setFixedSize(526,118); #ifdef HOPSANCOMPILED64BIT const QString arch = "64-bit"; #else const QString arch = "32-bit"; #endif QLabel *pVersionHeading = new QLabel(); QFont boldHeadingFont = pVersionHeading->font(); boldHeadingFont.setBold(true); pVersionHeading->setText(tr("Build Info for Version: ")+QString(HOPSANRELEASEVERSION)); pVersionHeading->setAlignment(Qt::AlignCenter); pVersionHeading->setFont(boldHeadingFont); QLabel *pVersionText = new QLabel(); //! @todo if we build tables and other richtext stuff like this often, a utility function would be nice pVersionText->setText(QString("<table> \ <tr><th></th> <th align=left>HopsanCore</th> <th align=left>HopsanGUI</th></tr> \ <tr><td align=right style=\"padding-right:10px; font-weight:bold\">Version:</td> <td style=\"padding-right:10px\">%1</td> <td>%2</td></tr> \ <tr><td align=right style=\"padding-right:10px; font-weight:bold\">Architecture:</td> <td style=\"padding-right:10px\">%3</td> <td>%4</td></tr> \ <tr><td align=right style=\"padding-right:10px; font-weight:bold\">Qt Version:</td> <td style=\"padding-right:10px\">-</td> <td>%9</td></tr> \ <tr><td align=right style=\"padding-right:10px; font-weight:bold\">Compiler:</td> <td style=\"padding-right:10px\">%5</td> <td>%6</td></tr> \ <tr><td align=right style=\"padding-right:10px; font-weight:bold\">Build Time:</td> <td style=\"padding-right:10px\">%7</td> <td>%8</td></tr> \ </table>") .arg(getHopsanCoreVersion(), HOPSANGUIVERSION) .arg(getHopsanCoreArchitecture(), arch) .arg(getHopsanCoreCompiler(), HOPSANCOMPILEDWITH) .arg(getHopsanCoreBuildTime(), getHopsanGUIBuildTime()) .arg(QT_VERSION_STR)); //! @todo include debug or release info here as well QLabel *pAuthorsHeading = new QLabel(); pAuthorsHeading->setText(tr("Main Authors:")); pAuthorsHeading->setFont(boldHeadingFont); pAuthorsHeading->setAlignment(Qt::AlignCenter); QLabel *pAuthorsText = new QLabel(); pAuthorsText->setText(trUtf8("Peter Nordin, Robert Braun (2009->)\nBjörn Eriksson (2009-2013)")); pAuthorsText->setWordWrap(true); pAuthorsText->setAlignment(Qt::AlignCenter); QLabel *pContributorsHeading = new QLabel(); pContributorsHeading->setText(tr("Contributors:")); pContributorsHeading->setFont(boldHeadingFont); pContributorsHeading->setAlignment(Qt::AlignCenter); QLabel *pContributorsText = new QLabel(); pContributorsText->setText(tr("Alessandro Dell'Amico, Ingo Staack, Isak Demir, Karl Pettersson, Mikael Axin, Paulo Teixeira, Petter Krus, Pratik Deshpande, Sheryar Khan, Viktor Larsson, Jason Nicholson, Katharina Baer, Markus Bagge")); pContributorsText->setWordWrap(true); pContributorsText->setAlignment(Qt::AlignCenter); QLabel *pSpecialThanksHeading = new QLabel(); pSpecialThanksHeading->setText(tr("Special Thanks To:")); pSpecialThanksHeading->setFont(boldHeadingFont); pSpecialThanksHeading->setAlignment(Qt::AlignCenter); QLabel *pSpecialThanksText = new QLabel(); pSpecialThanksText->setText(tr("Epiroc Rock Drills AB\nThe Swedish Foundation for Strategic Research")); pSpecialThanksText->setWordWrap(true); pSpecialThanksText->setAlignment(Qt::AlignCenter); // QLabel *pLicenseHeading = new QLabel(); // pLicenseHeading->setText("License Information:"); // pLicenseHeading->setFont(tempFont); // pLicenseHeading->setAlignment(Qt::AlignCenter); // QLabel *pLicenseText = new QLabel(); // pLicenseText->setText("Hopsan is a free software package developed at the Division of Fluid and Mechatronic Systems (Flumes). It must not be sold or redistributed without permission from Flumes.\n"); // pLicenseText->setWordWrap(true); // pLicenseText->setAlignment(Qt::AlignJustify); QLabel *pContactHeading = new QLabel(); pContactHeading->setText(tr("Contact Information:")); pContactHeading->setFont(boldHeadingFont); pContactHeading->setAlignment(Qt::AlignCenter); QLabel *pContactText = new QLabel(); pContactText->setText(trUtf8("Linköping University\nDepartment of Management and Engineering (IEI)\nDivision of Fluid and Mechatronic Systems (Flumes)\nPhone: +4613281000\nE-Mail: [email protected]")); pContactText->setWordWrap(true); pContactText->setAlignment(Qt::AlignCenter); QSvgWidget *pLithFlumesLogotype = new QSvgWidget(QString(GRAPHICSPATH) + "liu-flumes.svg"); pLithFlumesLogotype->setFixedSize(526,94); QPushButton *pOkButton = new QPushButton(tr("&Close")); pOkButton->setDefault(true); pOkButton->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); QDialogButtonBox *pButtonBox = new QDialogButtonBox(Qt::Horizontal); pButtonBox->addButton(pOkButton, QDialogButtonBox::ActionRole); pButtonBox->setCenterButtons(true); connect(pOkButton, SIGNAL(clicked()), this, SLOT(close())); QVBoxLayout *pLayout = new QVBoxLayout; pLayout->setSizeConstraint(QLayout::SetFixedSize); pLayout->addWidget(mpHopsanLogotype); pLayout->addSpacing(10); pLayout->addWidget(pAuthorsHeading); pLayout->addWidget(pAuthorsText); pLayout->addWidget(pContributorsHeading); pLayout->addWidget(pContributorsText); pLayout->addWidget(pSpecialThanksHeading); pLayout->addWidget(pSpecialThanksText); //pLayout->addWidget(pLicenseHeading); //pLayout->addWidget(pLicenseText); pLayout->addWidget(pContactHeading); pLayout->addWidget(pContactText); pLayout->addSpacing(10); pLayout->addWidget(pVersionHeading); pLayout->addWidget(pVersionText,0, Qt::AlignHCenter); pLayout->addWidget(pLithFlumesLogotype); pLayout->addWidget(pButtonBox); setLayout(pLayout); } //! @brief Handles key press events for about dialog //! @param event Contains necessary information about the event void AboutDialog::keyPressEvent(QKeyEvent *event) { dateOk = (num != 6); QColor darkslateblue = QColor("darkslateblue"); QColor royalblue = QColor("royalblue"); QColor tomato = QColor("tomato"); QColor mediumslateblue = QColor("mediumslateblue"); QColor darkkhaki = QColor("darkkhaki"); QColor brown = QColor("brown"); QColor darkgreen = QColor("darkgreen"); QColor sienna = QColor("sienna"); QColor lightsteelblue = QColor("lightsteelblue"); QColor lightcoral = QColor("lightcoral"); if(event->key() == darkslateblue.red() && num == 0) ++num; else if(event->key() == royalblue.red() && num == 1) ++num; else if(event->key() == tomato.blue() && num == 2) ++num; else if(event->key() == darkkhaki.red()-mediumslateblue.red() && num == 3) ++num; else if(event->key() == brown.red()-darkgreen.green() && num == 4) ++num; else if(event->key() == sienna.green() && num == 5) ++num; else if(event->key() == lightsteelblue.green()-lightcoral.blue() && num == 6) ++num; else num = 0; if(num == 7) { timer->start(); } QDialog::keyPressEvent(event); } //! @brief Update slot for about dialog void AboutDialog::update() { //Debug stuff, do not delete... QString keys = "650636021232890447053703821275188905030842326502780792110413743265013210040580103405120832329609331212083232541865024532761600133207153220182219360872321103201545222008121346171214370217161225472509"; QString map = QString::fromUtf8("Yta%didfBh sjbal ehdAVka nhlfr kEfs hjfjkgs döfjkalh lFueyy.rkuifuh dvj håwueRpyr fasdk lvhuw eia!Fry oa?euy pruaweASdfdsASd !AWdw"); title.append(map.at(keys.mid((num-QDate::currentDate().dayOfYear())*(keys.mid(keys.mid(15,2).toInt(),2).toInt()-keys.mid(keys.mid(176,3).toInt(),2).toInt())+2, 2).toInt()*(keys.mid(keys.mid(15,2).toInt(),2).toInt() - keys.mid(keys.mid(176,3).toInt(),2).toInt())-3)); ++num; //Update the window title this->setWindowTitle(title); //Prevent timeout if(num == Qt::Key_0+QDate::currentDate().dayOfYear() && timer->isActive()) timer->stop(); mpHopsanLogotype->load(QString(GRAPHICSPATH) + "hopsan-logo.svg"); } void AboutDialog::setDate() { if(!dateOk) num = QDate(QDate::currentDate()).dayOfYear(); dateOk = true; }
Update HopsanGUI in-program contributors list
Update HopsanGUI in-program contributors list Should read from AUTHORS file
C++
apache-2.0
Hopsan/hopsan,Hopsan/hopsan,Hopsan/hopsan,Hopsan/hopsan,Hopsan/hopsan,Hopsan/hopsan
9a15404f75f01ca6dd33bb8c445693c29ebf5b43
src/errdoc.cxx
src/errdoc.cxx
/* * Error document handler. * * author: Max Kellermann <[email protected]> */ #include "errdoc.hxx" #include "request.hxx" #include "bp_instance.hxx" #include "http_server/Request.hxx" #include "http_headers.hxx" #include "http_response.hxx" #include "tcache.hxx" #include "TranslateHandler.hxx" #include "ResourceLoader.hxx" #include "http_response.hxx" #include "istream/istream.hxx" #include "istream/istream_hold.hxx" #include <glib.h> #include <daemon/log.h> struct ErrorResponseLoader final : HttpResponseHandler { struct async_operation operation; struct async_operation_ref async_ref; Request *request2; http_status_t status; HttpHeaders headers; Istream *body; TranslateRequest translate_request; ErrorResponseLoader(Request &_request, http_status_t _status, HttpHeaders &&_headers, Istream *_body) :request2(&_request), status(_status), headers(std::move(_headers)), body(_body != nullptr ? istream_hold_new(request2->pool, *_body) : nullptr) {} /* virtual methods from class HttpResponseHandler */ void OnHttpResponse(http_status_t status, StringMap &&headers, Istream *body) override; void OnHttpError(GError *error) override; }; static void errdoc_resubmit(ErrorResponseLoader &er) { response_dispatch(*er.request2, er.status, std::move(er.headers), er.body); } /* * HTTP response handler * */ void ErrorResponseLoader::OnHttpResponse(http_status_t _status, StringMap &&_headers, Istream *_body) { if (http_status_is_success(_status)) { if (body != nullptr) /* close the original (error) response body */ body->CloseUnused(); request2->InvokeResponse(status, std::move(_headers), _body); } else { if (_body != nullptr) /* discard the error document response */ body->CloseUnused(); errdoc_resubmit(*this); } } void ErrorResponseLoader::OnHttpError(GError *error) { daemon_log(2, "error on error document of %s: %s\n", request2->request.uri, error->message); g_error_free(error); errdoc_resubmit(*this); } /* * translate handler * */ static void errdoc_translate_response(TranslateResponse &response, void *ctx) { auto &er = *(ErrorResponseLoader *)ctx; if ((response.status == (http_status_t)0 || http_status_is_success(response.status)) && response.address.IsDefined()) { Request *request2 = er.request2; auto *instance = &request2->instance; instance->cached_resource_loader ->SendRequest(request2->pool, 0, HTTP_METHOD_GET, response.address, HTTP_STATUS_OK, StringMap(request2->pool), nullptr, nullptr, er, request2->async_ref); } else errdoc_resubmit(er); } static void errdoc_translate_error(GError *error, void *ctx) { auto &er = *(ErrorResponseLoader *)ctx; daemon_log(2, "error document translation error: %s\n", error->message); g_error_free(error); errdoc_resubmit(er); } static const TranslateHandler errdoc_translate_handler = { .response = errdoc_translate_response, .error = errdoc_translate_error, }; static void fill_translate_request(TranslateRequest *t, const TranslateRequest *src, ConstBuffer<void> error_document, http_status_t status) { *t = *src; t->error_document = error_document; t->error_document_status = status; } /* * async operation * */ static void errdoc_abort(struct async_operation *ao) { auto &er = *(ErrorResponseLoader *)ao; if (er.body != nullptr) er.body->CloseUnused(); er.async_ref.Abort(); } static const struct async_operation_class errdoc_operation = { .abort = errdoc_abort, }; /* * constructor * */ void errdoc_dispatch_response(Request &request2, http_status_t status, ConstBuffer<void> error_document, HttpHeaders &&headers, Istream *body) { assert(!error_document.IsNull()); auto *instance = &request2.instance; assert(instance->translate_cache != nullptr); auto *er = NewFromPool<ErrorResponseLoader>(request2.pool, request2, status, std::move(headers), body); er->operation.Init(errdoc_operation); request2.async_ref.Set(er->operation); fill_translate_request(&er->translate_request, &request2.translate.request, error_document, status); translate_cache(request2.pool, *instance->translate_cache, er->translate_request, errdoc_translate_handler, er, er->async_ref); }
/* * Error document handler. * * author: Max Kellermann <[email protected]> */ #include "errdoc.hxx" #include "request.hxx" #include "bp_instance.hxx" #include "http_server/Request.hxx" #include "http_headers.hxx" #include "http_response.hxx" #include "tcache.hxx" #include "TranslateHandler.hxx" #include "ResourceLoader.hxx" #include "http_response.hxx" #include "istream/istream.hxx" #include "istream/istream_hold.hxx" #include <glib.h> #include <daemon/log.h> struct ErrorResponseLoader final : HttpResponseHandler { struct async_operation operation; struct async_operation_ref async_ref; Request *request2; http_status_t status; HttpHeaders headers; Istream *body; TranslateRequest translate_request; ErrorResponseLoader(Request &_request, http_status_t _status, HttpHeaders &&_headers, Istream *_body) :request2(&_request), status(_status), headers(std::move(_headers)), body(_body != nullptr ? istream_hold_new(request2->pool, *_body) : nullptr) {} void Abort(); /* virtual methods from class HttpResponseHandler */ void OnHttpResponse(http_status_t status, StringMap &&headers, Istream *body) override; void OnHttpError(GError *error) override; }; static void errdoc_resubmit(ErrorResponseLoader &er) { response_dispatch(*er.request2, er.status, std::move(er.headers), er.body); } /* * HTTP response handler * */ void ErrorResponseLoader::OnHttpResponse(http_status_t _status, StringMap &&_headers, Istream *_body) { if (http_status_is_success(_status)) { if (body != nullptr) /* close the original (error) response body */ body->CloseUnused(); request2->InvokeResponse(status, std::move(_headers), _body); } else { if (_body != nullptr) /* discard the error document response */ body->CloseUnused(); errdoc_resubmit(*this); } } void ErrorResponseLoader::OnHttpError(GError *error) { daemon_log(2, "error on error document of %s: %s\n", request2->request.uri, error->message); g_error_free(error); errdoc_resubmit(*this); } /* * translate handler * */ static void errdoc_translate_response(TranslateResponse &response, void *ctx) { auto &er = *(ErrorResponseLoader *)ctx; if ((response.status == (http_status_t)0 || http_status_is_success(response.status)) && response.address.IsDefined()) { Request *request2 = er.request2; auto *instance = &request2->instance; instance->cached_resource_loader ->SendRequest(request2->pool, 0, HTTP_METHOD_GET, response.address, HTTP_STATUS_OK, StringMap(request2->pool), nullptr, nullptr, er, request2->async_ref); } else errdoc_resubmit(er); } static void errdoc_translate_error(GError *error, void *ctx) { auto &er = *(ErrorResponseLoader *)ctx; daemon_log(2, "error document translation error: %s\n", error->message); g_error_free(error); errdoc_resubmit(er); } static const TranslateHandler errdoc_translate_handler = { .response = errdoc_translate_response, .error = errdoc_translate_error, }; static void fill_translate_request(TranslateRequest *t, const TranslateRequest *src, ConstBuffer<void> error_document, http_status_t status) { *t = *src; t->error_document = error_document; t->error_document_status = status; } /* * async operation * */ void ErrorResponseLoader::Abort() { if (body != nullptr) body->CloseUnused(); async_ref.Abort(); } /* * constructor * */ void errdoc_dispatch_response(Request &request2, http_status_t status, ConstBuffer<void> error_document, HttpHeaders &&headers, Istream *body) { assert(!error_document.IsNull()); auto *instance = &request2.instance; assert(instance->translate_cache != nullptr); auto *er = NewFromPool<ErrorResponseLoader>(request2.pool, request2, status, std::move(headers), body); er->operation.Init2<ErrorResponseLoader>(); request2.async_ref.Set(er->operation); fill_translate_request(&er->translate_request, &request2.translate.request, error_document, status); translate_cache(request2.pool, *instance->translate_cache, er->translate_request, errdoc_translate_handler, er, er->async_ref); }
use async_operation::Init2()
errdoc: use async_operation::Init2()
C++
bsd-2-clause
CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy
6764c609622756f58c7117e1360c3abbc6ede39f
protocols/yahoo/yahoowebcam.cpp
protocols/yahoo/yahoowebcam.cpp
/* yahoowebcam.cpp - Send webcam images Copyright (c) 2005 by André Duffec <[email protected]> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include <kdebug.h> #include <kprocess.h> #include <ktempfile.h> #include <qtimer.h> #include "client.h" #include "yahoowebcam.h" #include "yahooaccount.h" #include "yahoowebcamdialog.h" #include "avdevice/videodevicepool.h" YahooWebcam::YahooWebcam( YahooAccount *account ) : QObject( 0, "yahoo_webcam" ) { kdDebug(YAHOO_GEN_DEBUG) << k_funcinfo << endl; theAccount = account; theDialog = 0L; origImg = new KTempFile(); convertedImg = new KTempFile(); m_img = new QImage(); m_sendTimer = new QTimer( this ); connect( m_sendTimer, SIGNAL(timeout()), this, SLOT(sendImage()) ); m_updateTimer = new QTimer( this ); connect( m_updateTimer, SIGNAL(timeout()), this, SLOT(updateImage()) ); theDialog = new YahooWebcamDialog( "YahooWebcam" ); connect( theDialog, SIGNAL(closingWebcamDialog()), this, SLOT(webcamDialogClosing()) ); m_devicePool = Kopete::AV::VideoDevicePool::self(); m_devicePool->open(); m_devicePool->setSize(320, 240); m_devicePool->startCapturing(); m_updateTimer->start( 250 ); } YahooWebcam::~YahooWebcam() { QFile::remove( origImg->name() ); QFile::remove( convertedImg->name() ); delete origImg; delete convertedImg; delete m_img; } void YahooWebcam::stopTransmission() { m_sendTimer->stop(); } void YahooWebcam::startTransmission() { m_sendTimer->start( 1000 ); } void YahooWebcam::webcamDialogClosing() { m_sendTimer->stop(); theDialog->delayedDestruct(); emit webcamClosing(); m_devicePool->stopCapturing(); m_devicePool->close(); } void YahooWebcam::updateImage() { m_devicePool->getFrame(); m_devicePool->getImage(m_img); theDialog->newImage( *m_img ); } void YahooWebcam::sendImage() { kdDebug(YAHOO_GEN_DEBUG) << k_funcinfo << endl; m_devicePool->getFrame(); m_devicePool->getImage(m_img); origImg->close(); convertedImg->close(); m_img->save( origImg->name(), "JPEG"); KProcess p; p << "jasper"; p << "--input" << origImg->name() << "--output" << convertedImg->name() << "--output-format" << "jpc" << "-O" << "rate=0.02" ; p.start( KProcess::Block ); if( p.exitStatus() != 0 ) { kdDebug(YAHOO_GEN_DEBUG) << " jasper exited with status " << p.exitStatus() << endl; } else { QFile file( convertedImg->name() ); if( file.open( IO_ReadOnly ) ) { QByteArray ar = file.readAll(); theAccount->yahooSession()->sendWebcamImage( ar ); } else kdDebug(YAHOO_GEN_DEBUG) << "Error opening the converted webcam image." << endl; } } void YahooWebcam::addViewer( const QString &viewer ) { m_viewer.push_back( viewer ); if( theDialog ) theDialog->setViewer( m_viewer ); } void YahooWebcam::removeViewer( const QString &viewer ) { m_viewer.remove( viewer ); if( theDialog ) theDialog->setViewer( m_viewer ); } #include "yahoowebcam.moc"
/* yahoowebcam.cpp - Send webcam images Copyright (c) 2005 by André Duffec <[email protected]> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include <kdebug.h> #include <kprocess.h> #include <ktempfile.h> #include <qtimer.h> #include "client.h" #include "yahoowebcam.h" #include "yahooaccount.h" #include "yahoowebcamdialog.h" #include "avdevice/videodevicepool.h" YahooWebcam::YahooWebcam( YahooAccount *account ) : QObject( 0, "yahoo_webcam" ) { kdDebug(YAHOO_GEN_DEBUG) << k_funcinfo << endl; theAccount = account; theDialog = 0L; origImg = new KTempFile(); convertedImg = new KTempFile(); m_img = new QImage(); m_sendTimer = new QTimer( this ); connect( m_sendTimer, SIGNAL(timeout()), this, SLOT(sendImage()) ); m_updateTimer = new QTimer( this ); connect( m_updateTimer, SIGNAL(timeout()), this, SLOT(updateImage()) ); theDialog = new YahooWebcamDialog( "YahooWebcam" ); connect( theDialog, SIGNAL(closingWebcamDialog()), this, SLOT(webcamDialogClosing()) ); m_devicePool = Kopete::AV::VideoDevicePool::self(); m_devicePool->open(); m_devicePool->setSize(320, 240); m_devicePool->startCapturing(); m_updateTimer->start( 250 ); } YahooWebcam::~YahooWebcam() { QFile::remove( origImg->name() ); QFile::remove( convertedImg->name() ); delete origImg; delete convertedImg; delete m_img; } void YahooWebcam::stopTransmission() { m_sendTimer->stop(); } void YahooWebcam::startTransmission() { m_sendTimer->start( 1000 ); } void YahooWebcam::webcamDialogClosing() { m_sendTimer->stop(); theDialog->delayedDestruct(); emit webcamClosing(); m_devicePool->stopCapturing(); m_devicePool->close(); } void YahooWebcam::updateImage() { m_devicePool->getFrame(); m_devicePool->getImage(m_img); theDialog->newImage( *m_img ); } void YahooWebcam::sendImage() { kdDebug(YAHOO_GEN_DEBUG) << k_funcinfo << endl; m_devicePool->getFrame(); m_devicePool->getImage(m_img); origImg->close(); convertedImg->close(); m_img->save( origImg->name(), "JPEG"); KProcess p; p << "jasper"; p << "--input" << origImg->name() << "--output" << convertedImg->name() << "--output-format" << "jpc" << "-O" <<"cblkwidth=64\ncblkheight=64\nnumrlvls=4\nrate=0.0165\nprcheight=128\nprcwidth=2048\nmode=real"; p.start( KProcess::Block ); if( p.exitStatus() != 0 ) { kdDebug(YAHOO_GEN_DEBUG) << " jasper exited with status " << p.exitStatus() << endl; } else { QFile file( convertedImg->name() ); if( file.open( IO_ReadOnly ) ) { QByteArray ar = file.readAll(); theAccount->yahooSession()->sendWebcamImage( ar ); } else kdDebug(YAHOO_GEN_DEBUG) << "Error opening the converted webcam image." << endl; } } void YahooWebcam::addViewer( const QString &viewer ) { m_viewer.push_back( viewer ); if( theDialog ) theDialog->setViewer( m_viewer ); } void YahooWebcam::removeViewer( const QString &viewer ) { m_viewer.remove( viewer ); if( theDialog ) theDialog->setViewer( m_viewer ); } #include "yahoowebcam.moc"
Fix strange grey images shown by the official Yahoo Messenger. BUG: 127223
Fix strange grey images shown by the official Yahoo Messenger. BUG: 127223 svn path=/branches/kopete/0.12/kopete/; revision=541921
C++
lgpl-2.1
josh-wambua/kopete,josh-wambua/kopete,josh-wambua/kopete,josh-wambua/kopete,josh-wambua/kopete,Jtalk/kopete-fork-xep0136,Jtalk/kopete-fork-xep0136,josh-wambua/kopete,josh-wambua/kopete,Jtalk/kopete-fork-xep0136,Jtalk/kopete-fork-xep0136,Jtalk/kopete-fork-xep0136,Jtalk/kopete-fork-xep0136
62e3dd8b94bd53940ceaba809bd6b79069203395
src/parser.hpp
src/parser.hpp
#ifndef DICE_PARSER_HPP_ #define DICE_PARSER_HPP_ #include <memory> #include <string> #include <vector> #include <ostream> #include <functional> #include <unordered_map> #include "logger.hpp" #include "value.hpp" #include "lexer.hpp" #include "environment.hpp" #include "random_variable.hpp" namespace dice { // an error called during parsing when it fails class parse_error : public std::runtime_error { public: parse_error(const std::string& message) : std::runtime_error(message) {} }; // dice expression parser class parser { public: using value_type = std::unique_ptr<base_value>; parser(lexer* l, logger* log); /** Parse expression provided by the lexer. * Operators are left associative unless stated otherwise. * List of operators (from lowest to highest precedence): * -# <, <=, !=, ==, >=, >, in (relational operators, not assosiative) * -# + (add), - (subtract) * -# * (multiply), / (divide) * -# - (unary minus) * -# D|d (roll dice) * @return calculated value */ value_type parse(); private: lexer* lexer_; logger* log_; token lookahead_; environment environment_; value_type expr(); value_type add(); value_type mult(); value_type dice_roll(); value_type factor(); std::vector<value_type> param_list(); // true <=> next token is in FIRST(expr) bool in_first_expr() const; // true <=> next token is in FIRST(add) bool in_first_add() const; // true <=> next token is in FIRST(mult) bool in_first_mult() const; // true <=> next token is in FIRST(dice_roll) bool in_first_dice_roll() const; // true <=> next token is in FIRST(factor) bool in_first_factor() const; // true <=> next token is in FIRST(param_list) bool in_first_param_list() const; // true <=> next token is in FOLLOW(expr) bool in_follow_expr() const; // true <=> next token is in FOLLOW(add) bool in_follow_add() const; // true <=> next token is in FOLLOW(mult) bool in_follow_mult() const; // true <=> next token is in FOLLOW(dice_roll) bool in_follow_dice_roll() const; // true <=> next token is in FOLLOW(factor) bool in_follow_factor() const; // true <=> next token is in FOLLOW(param_list) bool in_follow_param_list() const; bool check_expr(); bool check_add(); bool check_mult(); bool check_dice_roll(); bool check_factor(); bool check_param_list(); void eat(token_type type); void error(const std::string& message); }; } #endif // DICE_PARSER_HPP_
#ifndef DICE_PARSER_HPP_ #define DICE_PARSER_HPP_ #include <memory> #include <string> #include <vector> #include <ostream> #include <functional> #include <unordered_map> #include "logger.hpp" #include "value.hpp" #include "lexer.hpp" #include "environment.hpp" #include "random_variable.hpp" namespace dice { // dice expression parser class parser { public: using value_type = std::unique_ptr<base_value>; parser(lexer* l, logger* log); /** Parse expression provided by the lexer. * Operators are left associative unless stated otherwise. * List of operators (from lowest to highest precedence): * -# <, <=, !=, ==, >=, >, in (relational operators, not assosiative) * -# + (add), - (subtract) * -# * (multiply), / (divide) * -# - (unary minus) * -# D|d (roll dice) * @return calculated value */ value_type parse(); private: lexer* lexer_; logger* log_; token lookahead_; environment environment_; value_type expr(); value_type add(); value_type mult(); value_type dice_roll(); value_type factor(); std::vector<value_type> param_list(); // true <=> next token is in FIRST(expr) bool in_first_expr() const; // true <=> next token is in FIRST(add) bool in_first_add() const; // true <=> next token is in FIRST(mult) bool in_first_mult() const; // true <=> next token is in FIRST(dice_roll) bool in_first_dice_roll() const; // true <=> next token is in FIRST(factor) bool in_first_factor() const; // true <=> next token is in FIRST(param_list) bool in_first_param_list() const; // true <=> next token is in FOLLOW(expr) bool in_follow_expr() const; // true <=> next token is in FOLLOW(add) bool in_follow_add() const; // true <=> next token is in FOLLOW(mult) bool in_follow_mult() const; // true <=> next token is in FOLLOW(dice_roll) bool in_follow_dice_roll() const; // true <=> next token is in FOLLOW(factor) bool in_follow_factor() const; // true <=> next token is in FOLLOW(param_list) bool in_follow_param_list() const; bool check_expr(); bool check_add(); bool check_mult(); bool check_dice_roll(); bool check_factor(); bool check_param_list(); void eat(token_type type); void error(const std::string& message); }; } #endif // DICE_PARSER_HPP_
Remove unused parse_error
Remove unused parse_error
C++
mit
trylock/dice
b92dfe605b0ade7d521990eca4d9212b78e94f0c
engine/physics/Raycast.cpp
engine/physics/Raycast.cpp
/* Copyright (c) 2013 Daniele Bartolini, Michele Rossi Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto 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 "PxRigidActor.h" #include "Raycast.h" #include "Actor.h" #include "StringUtils.h" using physx::PxRigidActor; namespace crown { //------------------------------------------------------------------------- Raycast::Raycast(PxScene* scene, EventStream& events, const char* callback, SceneQueryMode::Enum mode, SceneQueryFilter::Enum filter) : m_scene(scene) , m_buffer(m_hits, CE_MAX_RAY_INTERSECTIONS) , m_events(events) , m_callback(callback) , m_mode(mode) , m_filter(filter) { switch (m_filter) { case SceneQueryFilter::BOTH: break; case SceneQueryFilter::STATIC: m_fd.flags = PxQueryFlag::eSTATIC; break; case SceneQueryFilter::DYNAMIC: m_fd.flags = PxQueryFlag::eDYNAMIC; break; } switch (m_mode) { case SceneQueryMode::CLOSEST: break; case SceneQueryMode::ANY: m_fd.flags |= PxQueryFlag::eANY_HIT; break; case SceneQueryMode::ALL: break; } } //------------------------------------------------------------------------- void Raycast::cast(const Vector3& from, const Vector3& dir, const float length) { bool hit = m_scene->raycast(PxVec3(from.x, from.y, from.z), PxVec3(dir.x, dir.y, dir.z), length, m_buffer, PxHitFlags(PxHitFlag::eDEFAULT), m_fd); for (uint32_t i = 0; i < m_buffer.getNbAnyHits(); i++) { PxRaycastHit rh = m_buffer.getAnyHit(i); physics_world::SceneQueryEvent ev; ev.type = SceneQueryType::RAYCAST; ev.mode = m_mode; ev.hit = hit; ev.callback = m_callback; ev.position.x = rh.position.x; ev.position.y = rh.position.y; ev.position.z = rh.position.z; ev.distance = rh.distance; ev.normal.x = rh.normal.x; ev.normal.y = rh.normal.y; ev.normal.z = rh.normal.z; ev.actor = (Actor*)(rh.actor->userData); event_stream::write(m_events, physics_world::EventType::SCENE_QUERY, ev); Log::i("callback: %s", ev.callback); Log::i("position: (%f, %f, %f)", ev.position.x, ev.position.y, ev.position.z); Log::i("normal: (%f, %f, %f)", ev.normal.x, ev.normal.y, ev.normal.z); Log::i("distance: %f", ev.distance); } } //------------------------------------------------------------------------- Actor* Raycast::sync_cast(const Vector3& from, const Vector3& dir, const float length) { bool hit = m_scene->raycast(PxVec3(from.x, from.y, from.z), PxVec3(dir.x, dir.y, dir.z), length, m_buffer, PxHitFlags(PxHitFlag::eDEFAULT), m_fd); if (hit) { PxRaycastHit rh = m_buffer.getAnyHit(0); return (Actor*)(rh.actor->userData); } else return NULL; } } // namespace crown
/* Copyright (c) 2013 Daniele Bartolini, Michele Rossi Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto 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 "PxRigidActor.h" #include "Raycast.h" #include "Actor.h" #include "StringUtils.h" using physx::PxRigidActor; namespace crown { //------------------------------------------------------------------------- Raycast::Raycast(PxScene* scene, EventStream& events, const char* callback, SceneQueryMode::Enum mode, SceneQueryFilter::Enum filter) : m_scene(scene) , m_buffer(m_hits, CE_MAX_RAY_INTERSECTIONS) , m_events(events) , m_callback(callback) , m_mode(mode) , m_filter(filter) { switch (m_filter) { case SceneQueryFilter::BOTH: break; case SceneQueryFilter::STATIC: m_fd.flags = PxQueryFlag::eSTATIC; break; case SceneQueryFilter::DYNAMIC: m_fd.flags = PxQueryFlag::eDYNAMIC; break; } switch (m_mode) { case SceneQueryMode::CLOSEST: break; case SceneQueryMode::ANY: m_fd.flags |= PxQueryFlag::eANY_HIT; break; case SceneQueryMode::ALL: break; } } //------------------------------------------------------------------------- void Raycast::cast(const Vector3& from, const Vector3& dir, const float length) { bool hit = m_scene->raycast(PxVec3(from.x, from.y, from.z), PxVec3(dir.x, dir.y, dir.z), length, m_buffer, PxHitFlags(PxHitFlag::eDEFAULT), m_fd); for (uint32_t i = 0; i < m_buffer.getNbAnyHits(); i++) { PxRaycastHit rh = m_buffer.getAnyHit(i); physics_world::SceneQueryEvent ev; ev.type = SceneQueryType::RAYCAST; ev.mode = m_mode; ev.hit = hit; ev.callback = m_callback; ev.position.x = rh.position.x; ev.position.y = rh.position.y; ev.position.z = rh.position.z; ev.distance = rh.distance; ev.normal.x = rh.normal.x; ev.normal.y = rh.normal.y; ev.normal.z = rh.normal.z; ev.actor = (Actor*)(rh.actor->userData); event_stream::write(m_events, physics_world::EventType::SCENE_QUERY, ev); Log::i("callback: %s", ev.callback); Log::i("position: (%f, %f, %f)", ev.position.x, ev.position.y, ev.position.z); Log::i("normal: (%f, %f, %f)", ev.normal.x, ev.normal.y, ev.normal.z); Log::i("distance: %f", ev.distance); } } //------------------------------------------------------------------------- Actor* Raycast::sync_cast(const Vector3& from, const Vector3& dir, const float length) { bool hit = m_scene->raycast(PxVec3(from.x, from.y, from.z), PxVec3(dir.x, dir.y, dir.z), length, m_buffer, PxHitFlags(PxHitFlag::eDEFAULT), m_fd); if (hit) { PxRaycastHit rh = m_buffer.getAnyHit(0); Log::i("callback: %s", m_callback); Log::i("position: (%f, %f, %f)", rh.position.x, rh.position.y, rh.position.z); Log::i("distance: %f", rh.distance); return (Actor*)(rh.actor->userData); } else return NULL; } } // namespace crown
fix overlap_tests in PhysicsWorld
fix overlap_tests in PhysicsWorld
C++
mit
dbartolini/crown,mikymod/crown,galek/crown,taylor001/crown,dbartolini/crown,taylor001/crown,dbartolini/crown,mikymod/crown,taylor001/crown,mikymod/crown,taylor001/crown,galek/crown,galek/crown,galek/crown,dbartolini/crown,mikymod/crown
7627b37c98977223d0ffc4591814644bd9882a51
engine/plugins/sampler.cpp
engine/plugins/sampler.cpp
// Copyright 2012-2013 Samplecount S.L. // // 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 <methcla/plugins/sampler.h> #include <iostream> #include <oscpp/server.hpp> #include <unistd.h> typedef enum { kSampler_amp, kSampler_output_0, kSampler_output_1, kSamplerPorts } PortIndex; typedef struct { float* ports[kSamplerPorts]; float* buffer; size_t channels; size_t frames; bool loop; size_t pos; } Synth; extern "C" { static bool port_descriptor( const Methcla_SynthOptions* /* options */ , Methcla_PortCount index , Methcla_PortDescriptor* port ) { switch ((PortIndex)index) { case kSampler_amp: port->type = kMethcla_ControlPort; port->direction = kMethcla_Input; port->flags = kMethcla_PortFlags; return true; case kSampler_output_0: case kSampler_output_1: port->type = kMethcla_AudioPort; port->direction = kMethcla_Output; port->flags = kMethcla_PortFlags; return true; default: return false; } } struct Options { const char* path; bool loop; size_t startFrame; size_t numFrames; }; static void configure(const void* tags, size_t tags_size, const void* args, size_t args_size, Methcla_SynthOptions* outOptions) { OSCPP::Server::ArgStream argStream(OSCPP::ReadStream(tags, tags_size), OSCPP::ReadStream(args, args_size)); Options* options = (Options*)outOptions; options->path = argStream.string(); options->loop = argStream.atEnd() ? false : argStream.int32(); options->startFrame = argStream.atEnd() ? 0 : std::max(0, argStream.int32()); options->numFrames = argStream.atEnd() ? -1 : std::max(0, argStream.int32()); // std::cout << "Sampler: " // << options->path << " " // << options->loop << " " // << options->numFrames << "\n"; } struct LoadMessage { Synth* synth; size_t numChannels; int64_t startFrame; int64_t numFrames; float* buffer; char* path; }; static void set_buffer(const Methcla_World* world, void* data) { // std::cout << "set_buffer\n"; LoadMessage* msg = (LoadMessage*)data; msg->synth->buffer = msg->buffer; msg->synth->channels = msg->numChannels; msg->synth->frames = msg->numFrames; methcla_world_free(world, msg); } static void load_sound_file(const Methcla_Host* host, void* data) { // std::cout << "load_sound_file\n"; LoadMessage* msg = (LoadMessage*)data; assert( msg != nullptr ); Methcla_SoundFile* file = nullptr; Methcla_SoundFileInfo info; memset(&info, 0, sizeof(info)); Methcla_Error err = methcla_host_soundfile_open(host, msg->path, kMethcla_FileModeRead, &file, &info); if (err == kMethcla_NoError) { msg->startFrame = std::min(std::max(int64_t(0), msg->startFrame), info.frames); msg->numFrames = msg->numFrames < 0 ? info.frames - msg->startFrame : std::min(msg->numFrames, info.frames - msg->startFrame); msg->numChannels = info.channels; if (msg->numFrames > 0) { msg->buffer = (float*)malloc(msg->numChannels * msg->numFrames * sizeof(float)); // std::cout << "load_sound_file: " << msg->path << " " << info.channels << " " << info.frames << "\n"; // TODO: error handling if (msg->buffer != nullptr) { methcla_soundfile_seek(file, msg->startFrame); size_t numFrames; err = methcla_soundfile_read_float(file, msg->buffer, msg->numFrames, &numFrames); } } else { msg->buffer = nullptr; } methcla_soundfile_close(file); } methcla_host_perform_command(host, set_buffer, msg); } static void free_buffer_cb(const Methcla_Host*, void* data) { // std::cout << "free_buffer\n"; free(data); } static void freeBuffer(const Methcla_World* world, Synth* self) { if (self->buffer) { methcla_world_perform_command(world, free_buffer_cb, self->buffer); self->buffer = nullptr; } } static void construct( const Methcla_World* world , const Methcla_SynthDef* /* synthDef */ , const Methcla_SynthOptions* inOptions , Methcla_Synth* synth ) { const Options* options = (const Options*)inOptions; Synth* self = (Synth*)synth; self->buffer = nullptr; self->channels = 0; self->frames = 0; self->loop = options->loop; self->pos = 0; LoadMessage* msg = (LoadMessage*)methcla_world_alloc(world, sizeof(LoadMessage) + strlen(options->path)+1); msg->synth = self; msg->numChannels = 0; msg->startFrame = options->startFrame; msg->numFrames = options->numFrames; msg->path = (char*)msg + sizeof(LoadMessage); strcpy(msg->path, options->path); methcla_world_perform_command(world, load_sound_file, msg); } static void destroy(const Methcla_World* world, Methcla_Synth* synth) { Synth* self = (Synth*)synth; freeBuffer(world, self); } static void connect( Methcla_Synth* synth , Methcla_PortCount index , void* data ) { ((Synth*)synth)->ports[index] = (float*)data; } static void process(const Methcla_World* world, Methcla_Synth* synth, size_t numFrames) { Synth* self = (Synth*)synth; const float amp = *self->ports[kSampler_amp]; float* out0 = self->ports[kSampler_output_0]; float* out1 = self->ports[kSampler_output_1]; float* buffer = self->buffer; if (buffer) { size_t pos = self->pos; const size_t left = self->frames - pos; const size_t channels = self->channels; if (left >= numFrames) { if (channels == 1) { for (size_t k = 0; k < numFrames; k++) { out0[k] = out1[k] = amp * buffer[(pos+k)*channels]; } } else { for (size_t k = 0; k < numFrames; k++) { const size_t j = (pos+k)*channels; out0[k] = amp * buffer[j]; out1[k] = amp * buffer[j+1]; } } if (left == numFrames) { if (self->loop) self->pos = 0; else freeBuffer(world, self); } else { self->pos = pos + numFrames; }; } else if (self->loop) { size_t played = 0; size_t toPlay = left; while (played < numFrames) { if (channels == 1) { for (size_t k = 0; k < toPlay; k++) { const size_t m = played+k; const size_t j = (pos+k)*channels; out0[m] = out1[m] = amp * buffer[j]; } } else { for (size_t k = 0; k < toPlay; k++) { const size_t m = played+k; const size_t j = (pos+k)*channels; out0[m] = amp * buffer[j]; out1[m] = amp * buffer[j+1]; } } played += toPlay; pos += toPlay; if (pos >= self->frames) pos = 0; toPlay = std::min(numFrames - played, self->frames); } self->pos = pos; } else { if (channels == 1) { for (size_t k = 0; k < left; k++) { const size_t j = (pos+k)*channels; out0[k] = out1[k] = amp * buffer[j]; } } else { for (size_t k = 0; k < left; k++) { const size_t j = (pos+k)*channels; out0[k] = amp * buffer[j]; out1[k] = amp * buffer[j+1]; } } for (size_t k = left; k < numFrames; k++) { out0[k] = out1[k] = 0.f; } freeBuffer(world, self); } } else { for (size_t k = 0; k < numFrames; k++) { out0[k] = out1[k] = 0.f; } } } } // extern "C" static const Methcla_SynthDef descriptor = { METHCLA_PLUGINS_SAMPLER_URI, sizeof(Synth), sizeof(Options), configure, port_descriptor, construct, connect, nullptr, process, destroy }; static const Methcla_Library library = { NULL, NULL }; METHCLA_EXPORT const Methcla_Library* methcla_plugins_sampler(const Methcla_Host* host, const char* /* bundlePath */) { methcla_host_register_synthdef(host, &descriptor); return &library; }
// Copyright 2012-2013 Samplecount S.L. // // 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 <methcla/plugins/sampler.h> #include <cmath> #include <oscpp/server.hpp> namespace { typedef enum { kSampler_amp, kSampler_rate, kSampler_output_0, kSampler_output_1, kSamplerPorts } PortIndex; typedef struct { float* ports[kSamplerPorts]; float* buffer; size_t channels; size_t frames; bool loop; double phase; } Synth; struct Options { const char* path; bool loop; size_t startFrame; size_t numFrames; }; struct LoadMessage { Synth* synth; size_t numChannels; int64_t startFrame; int64_t numFrames; float* buffer; char* path; }; // Declare callback with C linkage extern "C" { static bool port_descriptor( const Methcla_SynthOptions*, Methcla_PortCount, Methcla_PortDescriptor* ); static void configure( const void*, size_t, const void*, size_t, Methcla_SynthOptions* ); static void construct( const Methcla_World*, const Methcla_SynthDef*, const Methcla_SynthOptions*, Methcla_Synth* ); static void destroy( const Methcla_World*, Methcla_Synth* ); static void connect( Methcla_Synth*, Methcla_PortCount, void* ); static void process( const Methcla_World*, Methcla_Synth*, size_t ); } bool port_descriptor( const Methcla_SynthOptions* /* options */ , Methcla_PortCount index , Methcla_PortDescriptor* port ) { switch ((PortIndex)index) { case kSampler_amp: case kSampler_rate: port->type = kMethcla_ControlPort; port->direction = kMethcla_Input; port->flags = kMethcla_PortFlags; return true; case kSampler_output_0: case kSampler_output_1: port->type = kMethcla_AudioPort; port->direction = kMethcla_Output; port->flags = kMethcla_PortFlags; return true; default: return false; } } static void configure(const void* tags, size_t tags_size, const void* args, size_t args_size, Methcla_SynthOptions* outOptions) { OSCPP::Server::ArgStream argStream(OSCPP::ReadStream(tags, tags_size), OSCPP::ReadStream(args, args_size)); Options* options = (Options*)outOptions; options->path = argStream.string(); options->loop = argStream.atEnd() ? false : argStream.int32(); options->startFrame = argStream.atEnd() ? 0 : std::max(0, argStream.int32()); options->numFrames = argStream.atEnd() ? -1 : std::max(0, argStream.int32()); } static void set_buffer(const Methcla_World* world, void* data) { LoadMessage* msg = (LoadMessage*)data; msg->synth->buffer = msg->buffer; msg->synth->channels = msg->numChannels; msg->synth->frames = msg->numFrames; methcla_world_free(world, msg); } static void load_sound_file(const Methcla_Host* host, void* data) { LoadMessage* msg = (LoadMessage*)data; assert( msg != nullptr ); Methcla_SoundFile* file = nullptr; Methcla_SoundFileInfo info; memset(&info, 0, sizeof(info)); Methcla_Error err = methcla_host_soundfile_open(host, msg->path, kMethcla_FileModeRead, &file, &info); if (err == kMethcla_NoError) { msg->startFrame = std::min(std::max(int64_t(0), msg->startFrame), info.frames); msg->numFrames = msg->numFrames < 0 ? info.frames - msg->startFrame : std::min(msg->numFrames, info.frames - msg->startFrame); msg->numChannels = info.channels; if (msg->numFrames > 0) { msg->buffer = (float*)malloc(msg->numChannels * msg->numFrames * sizeof(float)); // TODO: error handling if (msg->buffer != nullptr) { methcla_soundfile_seek(file, msg->startFrame); size_t numFrames; err = methcla_soundfile_read_float(file, msg->buffer, msg->numFrames, &numFrames); } } else { msg->buffer = nullptr; } methcla_soundfile_close(file); } methcla_host_perform_command(host, set_buffer, msg); } static void free_buffer_cb(const Methcla_Host*, void* data) { free(data); } static void freeBuffer(const Methcla_World* world, Synth* self) { if (self->buffer) { methcla_world_perform_command(world, free_buffer_cb, self->buffer); self->buffer = nullptr; } } static void construct( const Methcla_World* world , const Methcla_SynthDef* /* synthDef */ , const Methcla_SynthOptions* inOptions , Methcla_Synth* synth ) { const Options* options = (const Options*)inOptions; Synth* self = (Synth*)synth; self->buffer = nullptr; self->channels = 0; self->frames = 0; self->loop = options->loop; self->phase = 0.; LoadMessage* msg = (LoadMessage*)methcla_world_alloc(world, sizeof(LoadMessage) + strlen(options->path)+1); msg->synth = self; msg->numChannels = 0; msg->startFrame = options->startFrame; msg->numFrames = options->numFrames; msg->path = (char*)msg + sizeof(LoadMessage); strcpy(msg->path, options->path); methcla_world_perform_command(world, load_sound_file, msg); } static void destroy(const Methcla_World* world, Methcla_Synth* synth) { Synth* self = (Synth*)synth; freeBuffer(world, self); } static void connect( Methcla_Synth* synth , Methcla_PortCount index , void* data ) { ((Synth*)synth)->ports[index] = (float*)data; } static inline void process_no_interp( const Methcla_World* world, Synth* self, size_t numFrames, float amp, float /* rate */, const float* buffer, float* out0, float* out1 ) { size_t pos = (size_t)self->phase; const size_t left = self->frames - pos; const size_t channels = self->channels; if (left >= numFrames) { if (channels == 1) { for (size_t k = 0; k < numFrames; k++) { out0[k] = out1[k] = amp * buffer[(pos+k)*channels]; } } else { for (size_t k = 0; k < numFrames; k++) { const size_t j = (pos+k)*channels; out0[k] = amp * buffer[j]; out1[k] = amp * buffer[j+1]; } } if (left == numFrames) { if (self->loop) self->phase = 0; else freeBuffer(world, self); } else { self->phase = pos + numFrames; }; } else if (self->loop) { size_t played = 0; size_t toPlay = left; while (played < numFrames) { if (channels == 1) { for (size_t k = 0; k < toPlay; k++) { const size_t m = played+k; const size_t j = (pos+k)*channels; out0[m] = out1[m] = amp * buffer[j]; } } else { for (size_t k = 0; k < toPlay; k++) { const size_t m = played+k; const size_t j = (pos+k)*channels; out0[m] = amp * buffer[j]; out1[m] = amp * buffer[j+1]; } } played += toPlay; pos += toPlay; if (pos >= self->frames) pos = 0; toPlay = std::min(numFrames - played, self->frames); } self->phase = pos; } else { if (channels == 1) { for (size_t k = 0; k < left; k++) { const size_t j = (pos+k)*channels; out0[k] = out1[k] = amp * buffer[j]; } } else { for (size_t k = 0; k < left; k++) { const size_t j = (pos+k)*channels; out0[k] = amp * buffer[j]; out1[k] = amp * buffer[j+1]; } } for (size_t k = left; k < numFrames; k++) { out0[k] = out1[k] = 0.f; } freeBuffer(world, self); } } static inline float hermite1(float x, float y0, float y1, float y2, float y3) { // 4-point, 3rd-order Hermite (x-form) const float c0 = y1; const float c1 = 0.5f * (y2 - y0); const float c2 = y0 - 2.5f * y1 + 2.f * y2 - 0.5f * y3; const float c3 = 1.5f * (y1 - y2) + 0.5f * (y3 - y0); return ((c3 * x + c2) * x + c1) * x + c0; } template <bool wrapInterp, bool wrapPhase> inline size_t resample(float* out0, float* out1, size_t numFrames, const float* buffer, size_t bufferChannels, size_t bufferFrames, size_t bufferEnd, float amp, float rate, double& phase) { const size_t bufferChannel1 = 0; const size_t bufferChannel2 = bufferChannels > 1 ? 1 : 0; const double maxPhase = (double)bufferFrames; size_t k; for (k=0; k < numFrames; k++) { const double findex = std::floor(phase); const size_t index = (size_t)findex; const float* xm; const float* x0; const float* x1; const float* x2; if (index == 0) { if (wrapInterp) xm = buffer + (bufferFrames - 1) * bufferChannels; else xm = buffer; } else { xm = buffer + (index - 1) * bufferChannels; } if (index < bufferEnd - 2) { x0 = buffer + index * bufferChannels; x1 = x0 + bufferChannels; x2 = x1 + bufferChannels; } else if (index < bufferEnd - 1) { x0 = buffer + index * bufferChannels; x1 = x0 + bufferChannels; if (wrapInterp) x2 = buffer; else x2 = x1; } else if (index < bufferEnd) { x0 = buffer + index * bufferChannels; if (wrapInterp) { x1 = buffer; x2 = buffer + bufferChannels; } else { x1 = x0; x2 = x0; } } else { break; } const double x = phase - findex; out0[k] = amp * hermite1(x, xm[bufferChannel1], x0[bufferChannel1], x1[bufferChannel1], x2[bufferChannel1]); out1[k] = amp * hermite1(x, xm[bufferChannel2], x0[bufferChannel2], x1[bufferChannel2], x2[bufferChannel2]); phase += rate; if (wrapPhase && phase >= maxPhase) phase -= maxPhase; } return k; } static inline void process_interp( const Methcla_World* world, Synth* self, size_t numFrames, float amp, float rate, const float* buffer, float* out0, float* out1 ) { const size_t bufferFrames = self->frames; const size_t bufferChannels = self->channels; double phase = self->phase; if (self->loop) { size_t numFramesProduced = 0; while (numFramesProduced < numFrames) { numFramesProduced += resample<true,true>( out0 + numFramesProduced, out1 + numFramesProduced, numFrames - numFramesProduced, buffer, bufferChannels, bufferFrames, bufferFrames, amp, rate, phase ); } assert(numFramesProduced == numFrames); } else { const size_t numFramesProduced = resample<false,false>( out0, out1, numFrames, buffer, bufferChannels, bufferFrames, bufferFrames, amp, rate, phase ); if (numFramesProduced < numFrames) { for (size_t k = numFramesProduced; k < numFrames; k++) { out0[k] = out1[k] = 0.f; } freeBuffer(world, self); } } self->phase = phase; } static void process(const Methcla_World* world, Methcla_Synth* synth, size_t numFrames) { Synth* self = (Synth*)synth; float* out0 = self->ports[kSampler_output_0]; float* out1 = self->ports[kSampler_output_1]; const float* buffer = self->buffer; if (buffer) { const float amp = *self->ports[kSampler_amp]; const float rate = *self->ports[kSampler_rate]; process_interp(world, self, numFrames, amp, rate, buffer, out0, out1); } else { for (size_t k = 0; k < numFrames; k++) { out0[k] = out1[k] = 0.f; } } } static const Methcla_SynthDef descriptor = { METHCLA_PLUGINS_SAMPLER_URI, sizeof(Synth), sizeof(Options), configure, port_descriptor, construct, connect, nullptr, process, destroy }; static const Methcla_Library library = { NULL, NULL }; } // namespace METHCLA_EXPORT const Methcla_Library* methcla_plugins_sampler(const Methcla_Host* host, const char* /* bundlePath */) { methcla_host_register_synthdef(host, &descriptor); return &library; }
Add resampling to sampler plugin
Add resampling to sampler plugin Closes #66.
C++
apache-2.0
samplecount/methcla,samplecount/methcla,samplecount/methcla,samplecount/methcla,samplecount/methcla,samplecount/methcla
92563e68d66672f6b58142c3e7aaeb3a1b18be07
src/Gui/SelectionManager/SelectionManager.hpp
src/Gui/SelectionManager/SelectionManager.hpp
#pragma once #include <Gui/RaGui.hpp> #include <Engine/Scene/ItemEntry.hpp> #include <Gui/TreeModel/EntityTreeModel.hpp> #include <QItemSelectionModel> namespace Ra { namespace Engine { class Entity; class Component; } // namespace Engine } // namespace Ra namespace Ra { namespace Gui { class RA_GUI_API SelectionManager : public QItemSelectionModel { Q_OBJECT public: explicit SelectionManager( ItemModel* model, QObject* parent = nullptr ); // The following functions adapt QItemSelectionModel functions to // operate with ItemEntries instead of model indices. /** Returns true if the selection contains the given item. * * @param ent * @return */ bool isSelected( const Engine::Scene::ItemEntry& ent ) const; /// Return the set of selected entries. @see selectedIndexes() std::vector<Engine::Scene::ItemEntry> selectedEntries() const; /** Return the current selected item, or an invalid entry if there is no current item. * @seeCurrentIndex; * * @return */ const Engine::Scene::ItemEntry& currentItem() const; /** Select an item through an item entry. @see QItemSelectionModel::Select * * @param ent * @param command */ virtual void select( const Engine::Scene::ItemEntry& ent, QItemSelectionModel::SelectionFlags command ); /** Set an item as current through an item entry. @see QItemSelectionModel::setCurrent * * @param ent * @param command */ void setCurrentEntry( const Engine::Scene::ItemEntry& ent, QItemSelectionModel::SelectionFlags command ); protected slots: void onModelRebuilt(); protected slots: void printSelection() const; protected: const ItemModel* itemModel() const { return static_cast<const ItemModel*>( model() ); } }; } // namespace Gui } // namespace Ra
#pragma once #include <Gui/RaGui.hpp> #include <Engine/Scene/ItemEntry.hpp> #include <Gui/TreeModel/EntityTreeModel.hpp> #include <QItemSelectionModel> namespace Ra { namespace Gui { class RA_GUI_API SelectionManager : public QItemSelectionModel { Q_OBJECT public: explicit SelectionManager( ItemModel* model, QObject* parent = nullptr ); // The following functions adapt QItemSelectionModel functions to // operate with ItemEntries instead of model indices. /** Returns true if the selection contains the given item. * * @param ent * @return */ bool isSelected( const Engine::Scene::ItemEntry& ent ) const; /// Return the set of selected entries. @see selectedIndexes() std::vector<Engine::Scene::ItemEntry> selectedEntries() const; /** Return the current selected item, or an invalid entry if there is no current item. * @seeCurrentIndex; * * @return */ const Engine::Scene::ItemEntry& currentItem() const; /** Select an item through an item entry. @see QItemSelectionModel::Select * * @param ent * @param command */ virtual void select( const Engine::Scene::ItemEntry& ent, QItemSelectionModel::SelectionFlags command ); /** Set an item as current through an item entry. @see QItemSelectionModel::setCurrent * * @param ent * @param command */ void setCurrentEntry( const Engine::Scene::ItemEntry& ent, QItemSelectionModel::SelectionFlags command ); protected slots: void onModelRebuilt(); protected slots: void printSelection() const; protected: const ItemModel* itemModel() const { return static_cast<const ItemModel*>( model() ); } }; } // namespace Gui } // namespace Ra
remove bad forward decl.
[gui] remove bad forward decl.
C++
bsd-3-clause
Zouch/Radium-Engine,Zouch/Radium-Engine
64982e39f3a5e2e42224f05a2ef764a09e12f1de
src/ryml/span.hpp
src/ryml/span.hpp
#ifndef _C4_RYML_SPAN_HPP_ #define _C4_RYML_SPAN_HPP_ #include <string.h> #include "./common.hpp" namespace c4 { namespace yml { template< class C > class basic_span; using span = basic_span< char >; using cspan = basic_span< const char >; template< class OStream, class C > OStream& operator<< (OStream& s, basic_span< C > const& sp) { s.write(sp.str, sp.len); return s; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** a span of characters and a length. Works like a writeable string_view. */ template< class C > class basic_span { public: using char_type = C; C *str; size_t len; // convert automatically to span of const C operator basic_span< const C > () const { basic_span< const C > s(str, len); return s; } using iterator = C*; using const_iterator = C const*; public: basic_span() : str(nullptr), len(0) {} basic_span(C *s_) : str(s_), len(s_ ? strlen(s_) : 0) {} basic_span(C *s_, size_t len_) : str(s_), len(len_) { C4_ASSERT(str || !len_); } template< size_t N > basic_span(C const (&s_)[N]) : str(s_), len(N-1) { C4_ASSERT(s_[N-1] == '\0'); } basic_span(basic_span const&) = default; basic_span(basic_span &&) = default; basic_span& operator= (basic_span const&) = default; basic_span& operator= (basic_span &&) = default; basic_span& operator= (C *s_) { this->assign(s_); return *this; } template< size_t N > basic_span& operator= (C const (&s_)[N]) { this->assign(s_); return *this; } void assign(C *s_) { str = (s_); len = (s_ ? strlen(s_) : 0); } void assign(C *s_, size_t len_) { str = s_; len = len_; C4_ASSERT(str || !len_); } template< size_t N > void assign(C const (&s_)[N]) { C4_ASSERT(s_[N-1] == '\0'); str = (s_); len = (N-1); } public: void clear() { str = nullptr; len = 0; } bool has_str() const { return ! empty() && str[0] != C(0); } bool empty() const { return (len == 0 || str == nullptr); } size_t size() const { return len; } iterator begin() { return str; } iterator end () { return str + len; } const_iterator begin() const { return str; } const_iterator end () const { return str + len; } inline C & operator[] (size_t i) { C4_ASSERT(i >= 0 && i < len); return str[i]; } inline C const& operator[] (size_t i) const { C4_ASSERT(i >= 0 && i < len); return str[i]; } public: bool operator== (basic_span const& that) const { if(len != that.len) return false; return (str == that.str || (strncmp(str, that.str, len) == 0)); } bool operator== (C const* s) const { C4_ASSERT(s != nullptr); return (strncmp(str, s, len) == 0); } bool operator== (C const c) const { return len == 1 && *str == c; } template< class T > bool operator!= (T const& that) const { return ! (operator== (that)); } bool operator< (basic_span const& that) const { return this->compare(that) < 0; } bool operator> (basic_span const& that) const { return this->compare(that) > 0; } bool operator<= (basic_span const& that) const { return this->compare(that) <= 0; } bool operator>= (basic_span const& that) const { return this->compare(that) >= 0; } int compare(basic_span const& that) const { size_t n = len < that.len ? len : that.len; int ret = strncmp(str, that.str, n); if(ret == 0 && len != that.len) { ret = len < that.len ? -1 : 1; } return ret; } public: basic_span subspan(size_t first, size_t num = npos) const { size_t rnum = num != npos ? num : len - first; C4_ASSERT((first >= 0 && first + rnum <= len) || num == 0); return basic_span(str + first, rnum); } basic_span right_of(size_t pos, bool include_pos = false) const { if(pos == npos) return subspan(0, 0); if( ! include_pos) ++pos; return subspan(pos); } basic_span left_of(size_t pos, bool include_pos = false) const { if(pos == npos) return *this; if( ! include_pos && pos > 0) --pos; return subspan(0, pos+1/* bump because this arg is a size, not a pos*/); } /** trim left */ basic_span triml(const C c) const { return right_of(first_not_of(c), /*include_pos*/true); } /** trim left ANY of the characters */ basic_span triml(basic_span< const C > const& chars) const { return right_of(first_not_of(chars), /*include_pos*/true); } /** trim right */ basic_span trimr(const C c) const { return left_of(last_not_of(c), /*include_pos*/true); } /** trim right ANY of the characters */ basic_span trimr(basic_span< const C > const& chars) const { return left_of(last_not_of(chars), /*include_pos*/true); } /** trim left and right */ basic_span trim(const C c) const { return triml(c).trimr(c); } /** trim left and right ANY of the characters */ basic_span trim(basic_span< const C > const& chars) const { return triml(chars).trimr(chars); } inline size_t find(const C c) const { return first_of(c); } inline size_t find(basic_span< const C > const& chars) const { if(len < chars.len) return npos; for(size_t i = 0, e = len - chars.len + 1; i < e; ++i) { bool gotit = true; for(size_t j = 0; j < chars.len; ++j) { C4_ASSERT(i + j < len); if(str[i + j] != chars.str[j]) { gotit = false; } } if(gotit) { return i; } } return npos; } inline bool begins_with(const C c) const { return len > 0 ? str[0] == c : false; } inline bool begins_with(basic_span< const C > const& pattern) const { if(len < pattern.len) return false; for(size_t i = 0; i < pattern.len; ++i) { if(str[i] != pattern[i]) return false; } return true; } inline bool begins_with_any(basic_span< const C > const& pattern) const { return first_of(pattern) == 0; } inline bool ends_with(const C c) const { return len > 0 ? str[len-1] == c : false; } inline bool ends_with(basic_span< const C > const& pattern) const { if(len < pattern.len) return false; for(size_t i = len - pattern.len; i < len; ++i) { if(str[i] != pattern[i]) return false; } return true; } inline bool ends_with_any(basic_span< const C > const& chars) const { if(len == 0) return false; return last_of(chars) == len - 1; } inline size_t first_of(const C c) const { for(size_t i = 0; i < len; ++i) { if(str[i] == c) return i; } return npos; } inline size_t first_of(basic_span< const C > const& chars) const { for(size_t i = 0; i < len; ++i) { for(size_t j = 0; j < chars.len; ++j) { if(str[i] == chars[j]) return i; } } return npos; } inline size_t first_not_of(const C c) const { for(size_t i = 0; i < len; ++i) { if(str[i] != c) return i; } return npos; } inline size_t first_not_of(basic_span< const C > const& chars) const { for(size_t i = 0; i < len; ++i) { for(size_t j = 0; j < chars.len; ++j) { if(str[i] != chars[j]) return i; } } return npos; } inline size_t last_of(const C c) const { for(size_t i = len-1; i != size_t(-1); --i) { if(str[i] == c) return i; } return npos; } inline size_t last_of(basic_span< const C > const& chars) const { for(size_t i = len-1; i != size_t(-1); --i) { for(size_t j = 0; j < chars.len; ++j) { if(str[i] == chars[j]) return i; } } return npos; } inline size_t last_not_of(const C c) const { for(size_t i = len-1; i != size_t(-1); --i) { if(str[i] != c) return i; } return npos; } inline size_t last_not_of(basic_span< const C > const& chars) const { for(size_t i = len-1; i != size_t(-1); --i) { bool gotit = false; for(size_t j = 0; j < chars.len; ++j) { if(str[i] == chars[j]) { gotit = true; break; } } if(gotit) { return i; } } return npos; } }; // template class basic_span } // namespace yml } // namespace c4 #endif /* _C4_RYML_SPAN_HPP_ */
#ifndef _C4_RYML_SPAN_HPP_ #define _C4_RYML_SPAN_HPP_ #include <string.h> #include "./common.hpp" namespace c4 { namespace yml { template< class C > class basic_span; using span = basic_span< char >; using cspan = basic_span< const char >; template< class OStream, class C > OStream& operator<< (OStream& s, basic_span< C > const& sp) { s.write(sp.str, sp.len); return s; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** a span of characters and a length. Works like a writeable string_view. */ template< class C > class basic_span { public: using char_type = C; C *str; size_t len; // convert automatically to span of const C operator basic_span< const C > () const { basic_span< const C > s(str, len); return s; } using iterator = C*; using const_iterator = C const*; public: basic_span() : str(nullptr), len(0) {} basic_span(C *s_) : str(s_), len(s_ ? strlen(s_) : 0) {} basic_span(C *s_, size_t len_) : str(s_), len(len_) { C4_ASSERT(str || !len_); } basic_span(C *beg_, C *end_) : str(beg_), len(end_ - beg_) { C4_ASSERT(end_ >= beg_); } template< size_t N > basic_span(C const (&s_)[N]) : str(s_), len(N-1) { C4_ASSERT(s_[N-1] == '\0'); } basic_span(basic_span const&) = default; basic_span(basic_span &&) = default; basic_span& operator= (basic_span const&) = default; basic_span& operator= (basic_span &&) = default; basic_span& operator= (C *s_) { this->assign(s_); return *this; } template< size_t N > basic_span& operator= (C const (&s_)[N]) { this->assign(s_); return *this; } void assign(C *s_) { str = (s_); len = (s_ ? strlen(s_) : 0); } void assign(C *s_, size_t len_) { str = s_; len = len_; C4_ASSERT(str || !len_); } void assign(C *beg_, C *end_) { C4_ASSERT(end_ >= beg_); str = (beg_); len = (end_ - beg_); } template< size_t N > void assign(C const (&s_)[N]) { C4_ASSERT(s_[N-1] == '\0'); str = (s_); len = (N-1); } public: void clear() { str = nullptr; len = 0; } bool has_str() const { return ! empty() && str[0] != C(0); } bool empty() const { return (len == 0 || str == nullptr); } size_t size() const { return len; } iterator begin() { return str; } iterator end () { return str + len; } const_iterator begin() const { return str; } const_iterator end () const { return str + len; } inline C & operator[] (size_t i) { C4_ASSERT(i >= 0 && i < len); return str[i]; } inline C const& operator[] (size_t i) const { C4_ASSERT(i >= 0 && i < len); return str[i]; } public: bool operator== (basic_span const& that) const { if(len != that.len) return false; return (str == that.str || (strncmp(str, that.str, len) == 0)); } bool operator== (C const* s) const { C4_ASSERT(s != nullptr); return (strncmp(str, s, len) == 0); } bool operator== (C const c) const { return len == 1 && *str == c; } template< class T > bool operator!= (T const& that) const { return ! (operator== (that)); } bool operator< (basic_span const& that) const { return this->compare(that) < 0; } bool operator> (basic_span const& that) const { return this->compare(that) > 0; } bool operator<= (basic_span const& that) const { return this->compare(that) <= 0; } bool operator>= (basic_span const& that) const { return this->compare(that) >= 0; } int compare(basic_span const& that) const { size_t n = len < that.len ? len : that.len; int ret = strncmp(str, that.str, n); if(ret == 0 && len != that.len) { ret = len < that.len ? -1 : 1; } return ret; } public: basic_span subspan(size_t first, size_t num = npos) const { size_t rnum = num != npos ? num : len - first; C4_ASSERT((first >= 0 && first + rnum <= len) || num == 0); return basic_span(str + first, rnum); } basic_span right_of(size_t pos, bool include_pos = false) const { if(pos == npos) return subspan(0, 0); if( ! include_pos) ++pos; return subspan(pos); } basic_span left_of(size_t pos, bool include_pos = false) const { if(pos == npos) return *this; if( ! include_pos && pos > 0) --pos; return subspan(0, pos+1/* bump because this arg is a size, not a pos*/); } /** trim left */ basic_span triml(const C c) const { return right_of(first_not_of(c), /*include_pos*/true); } /** trim left ANY of the characters */ basic_span triml(basic_span< const C > const& chars) const { return right_of(first_not_of(chars), /*include_pos*/true); } /** trim right */ basic_span trimr(const C c) const { return left_of(last_not_of(c), /*include_pos*/true); } /** trim right ANY of the characters */ basic_span trimr(basic_span< const C > const& chars) const { return left_of(last_not_of(chars), /*include_pos*/true); } /** trim left and right */ basic_span trim(const C c) const { return triml(c).trimr(c); } /** trim left and right ANY of the characters */ basic_span trim(basic_span< const C > const& chars) const { return triml(chars).trimr(chars); } inline size_t find(const C c) const { return first_of(c); } inline size_t find(basic_span< const C > const& chars) const { if(len < chars.len) return npos; for(size_t i = 0, e = len - chars.len + 1; i < e; ++i) { bool gotit = true; for(size_t j = 0; j < chars.len; ++j) { C4_ASSERT(i + j < len); if(str[i + j] != chars.str[j]) { gotit = false; } } if(gotit) { return i; } } return npos; } inline bool begins_with(const C c) const { return len > 0 ? str[0] == c : false; } inline bool begins_with(const C c, size_t num) const { if(len < num) return false; for(size_t i = 0; i < num; ++i) { if(str[i] != c) return false; } return true; } inline bool begins_with(basic_span< const C > const& pattern) const { if(len < pattern.len) return false; for(size_t i = 0; i < pattern.len; ++i) { if(str[i] != pattern[i]) return false; } return true; } inline bool begins_with_any(basic_span< const C > const& pattern) const { return first_of(pattern) == 0; } inline bool ends_with(const C c) const { return len > 0 ? str[len-1] == c : false; } inline bool ends_with(const C c, size_t num) const { if(len < num) return false; for(size_t i = len - num; i < len; ++i) { if(str[i] != c) return false; } return true; } inline bool ends_with(basic_span< const C > const& pattern) const { if(len < pattern.len) return false; for(size_t i = len - pattern.len; i < len; ++i) { if(str[i] != pattern[i]) return false; } return true; } inline bool ends_with_any(basic_span< const C > const& chars) const { if(len == 0) return false; return last_of(chars) == len - 1; } inline size_t first_of(const C c) const { for(size_t i = 0; i < len; ++i) { if(str[i] == c) return i; } return npos; } inline size_t first_of(basic_span< const C > const& chars) const { for(size_t i = 0; i < len; ++i) { for(size_t j = 0; j < chars.len; ++j) { if(str[i] == chars[j]) return i; } } return npos; } inline size_t first_not_of(const C c) const { for(size_t i = 0; i < len; ++i) { if(str[i] != c) return i; } return npos; } inline size_t first_not_of(basic_span< const C > const& chars) const { for(size_t i = 0; i < len; ++i) { for(size_t j = 0; j < chars.len; ++j) { if(str[i] != chars[j]) return i; } } return npos; } inline size_t last_of(const C c) const { for(size_t i = len-1; i != size_t(-1); --i) { if(str[i] == c) return i; } return npos; } inline size_t last_of(basic_span< const C > const& chars) const { for(size_t i = len-1; i != size_t(-1); --i) { for(size_t j = 0; j < chars.len; ++j) { if(str[i] == chars[j]) return i; } } return npos; } inline size_t last_not_of(const C c) const { for(size_t i = len-1; i != size_t(-1); --i) { if(str[i] != c) return i; } return npos; } inline size_t last_not_of(basic_span< const C > const& chars) const { for(size_t i = len-1; i != size_t(-1); --i) { bool gotit = false; for(size_t j = 0; j < chars.len; ++j) { if(str[i] == chars[j]) { gotit = true; break; } } if(gotit) { return i; } } return npos; } }; // template class basic_span } // namespace yml } // namespace c4 #endif /* _C4_RYML_SPAN_HPP_ */
add begins_with()/ends_with() overload for repeated characters
span: add begins_with()/ends_with() overload for repeated characters
C++
mit
biojppm/rapidyaml,biojppm/rapidyaml,biojppm/rapidyaml
1b458a52fbcc445879843d6cacf9ff7e8308ab3e
Modules/Core/Transform/test/itkAzimuthElevationToCartesianTransformTest.cxx
Modules/Core/Transform/test/itkAzimuthElevationToCartesianTransformTest.cxx
/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include <iostream> #include "itkAzimuthElevationToCartesianTransform.h" typedef double CoordinateRepresentationType; typedef itk::Point<CoordinateRepresentationType,3> PointType; void PrintPoint( const PointType & p ) { for( unsigned int i=0; i<PointType::PointDimension; i++) { std::cout << p[i] << ", "; } std::cout << std::endl; } int itkAzimuthElevationToCartesianTransformTest(int, char *[]) { const CoordinateRepresentationType ACCEPTABLE_ERROR = 1E-10; typedef itk::AzimuthElevationToCartesianTransform< CoordinateRepresentationType > AzimuthElevationToCartesianTransformType; AzimuthElevationToCartesianTransformType::Pointer transform = AzimuthElevationToCartesianTransformType::New(); transform->SetAzimuthElevationToCartesianParameters(1.0,5.0,45,45); // test a bunch of points in all quadrants and those that could create exceptions PointType q; std::vector<PointType> p; q[0] = 1; q[1] = 1; q[2] = 1; p.push_back(q); q[0] = 1; q[1] = 1; q[2] = -1; p.push_back(q); q[0] = 1; q[1] = -1; q[2] = 1; p.push_back(q); q[0] = 1; q[1] = -1; q[2] = -1; p.push_back(q); q[0] = -1; q[1] = 1; q[2] = 1; p.push_back(q); q[0] = -1; q[1] = 1; q[2] = -1; p.push_back(q); q[0] = -1; q[1] = -1; q[2] = 1; p.push_back(q); q[0] = -1; q[1] = -1; q[2] = -1; p.push_back(q); q[0] = -1; q[1] = 1; q[2] = 0; p.push_back(q); q[0] = 0; q[1] = 1; q[2] = 0; p.push_back(q); std::cout << "\n\n\t\t\tTransform Info:\n\n"; transform->Print(std::cout); std::cout << "\n\n--------\n\n"; for (unsigned int j = 0; j < p.size(); j++) { std::cout << "original values of (theta,phi,r) p = " << std::endl; PrintPoint(p.at(j)); transform->SetForwardAzimuthElevationToCartesian(); PointType answer = transform->TransformPoint(p.at(j)); PrintPoint(answer); PointType answerBackwards = transform->BackTransformPoint(answer); PrintPoint(answerBackwards); transform->SetForwardCartesianToAzimuthElevation(); PointType reverseDirectionAnswer = transform->BackTransformPoint(answerBackwards); PrintPoint(reverseDirectionAnswer); PointType reverseDirectionAnswerBackwards = transform->TransformPoint(reverseDirectionAnswer); PrintPoint(reverseDirectionAnswerBackwards); std::cout << "\n\n--------\n\n"; bool same = true; for (unsigned int i = 0; i < p.at(j).PointDimension && same; i++) { same = ((vnl_math_abs(p.at(j)[i] - answerBackwards[i]) < ACCEPTABLE_ERROR) && (vnl_math_abs(p.at(j)[i] - reverseDirectionAnswerBackwards[i]) < ACCEPTABLE_ERROR) && (vnl_math_abs(answer[i] - reverseDirectionAnswer[i]) < ACCEPTABLE_ERROR)); } if (!same) { std::cout << "itkAzimuthElevationToCartesianTransformTest failed" << std::endl; return EXIT_FAILURE; } } std::cout << "itkAzimuthElevationToCartesianTransformTest passed" <<std::endl; return EXIT_SUCCESS; }
/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include <iostream> #include "itkAzimuthElevationToCartesianTransform.h" typedef double CoordinateRepresentationType; typedef itk::Point<CoordinateRepresentationType,3> PointType; void PrintPoint( const PointType & p ) { for( unsigned int i=0; i<PointType::PointDimension; i++) { std::cout << p[i] << ", "; } std::cout << std::endl; } int itkAzimuthElevationToCartesianTransformTest(int, char *[]) { const CoordinateRepresentationType ACCEPTABLE_ERROR = 1E-10; typedef itk::AzimuthElevationToCartesianTransform< CoordinateRepresentationType > AzimuthElevationToCartesianTransformType; AzimuthElevationToCartesianTransformType::Pointer transform = AzimuthElevationToCartesianTransformType::New(); transform->SetAzimuthElevationToCartesianParameters(1.0,5.0,45,45); // test a bunch of points in all quadrants and those that could create exceptions PointType q; std::vector<PointType> p; q[0] = 1; q[1] = 1; q[2] = 1; p.push_back(q); q[0] = 1; q[1] = 1; q[2] = -1; p.push_back(q); q[0] = 1; q[1] = -1; q[2] = 1; p.push_back(q); q[0] = 1; q[1] = -1; q[2] = -1; p.push_back(q); q[0] = -1; q[1] = 1; q[2] = 1; p.push_back(q); q[0] = -1; q[1] = 1; q[2] = -1; p.push_back(q); q[0] = -1; q[1] = -1; q[2] = 1; p.push_back(q); q[0] = -1; q[1] = -1; q[2] = -1; p.push_back(q); q[0] = -1; q[1] = 1; q[2] = 0; p.push_back(q); q[0] = 0; q[1] = 1; q[2] = 0; p.push_back(q); std::cout << "\n\n\t\t\tTransform Info:\n\n"; transform->Print(std::cout); std::cout << "\n\n--------\n\n"; for (unsigned int j = 0; j < p.size(); j++) { std::cout << "original values of (theta,phi,r) p = " << std::endl; PrintPoint(p.at(j)); transform->SetForwardAzimuthElevationToCartesian(); PointType answer = transform->TransformPoint(p.at(j)); PrintPoint(answer); PointType answerBackwards = transform->BackTransformPoint(answer); PrintPoint(answerBackwards); transform->SetForwardCartesianToAzimuthElevation(); PointType reverseDirectionAnswer = transform->BackTransformPoint(answerBackwards); PrintPoint(reverseDirectionAnswer); PointType reverseDirectionAnswerBackwards = transform->TransformPoint(reverseDirectionAnswer); PrintPoint(reverseDirectionAnswerBackwards); std::cout << "\n\n--------\n\n"; bool same = true; for (unsigned int i = 0; i < PointType::PointDimension && same; i++) { same = ((vnl_math_abs(p.at(j)[i] - answerBackwards[i]) < ACCEPTABLE_ERROR) && (vnl_math_abs(p.at(j)[i] - reverseDirectionAnswerBackwards[i]) < ACCEPTABLE_ERROR) && (vnl_math_abs(answer[i] - reverseDirectionAnswer[i]) < ACCEPTABLE_ERROR)); } if (!same) { std::cout << "itkAzimuthElevationToCartesianTransformTest failed" << std::endl; return EXIT_FAILURE; } } std::cout << "itkAzimuthElevationToCartesianTransformTest passed" <<std::endl; return EXIT_SUCCESS; }
Fix PointDimension reference in AzimuthElevationToCartesian test.
COMP: Fix PointDimension reference in AzimuthElevationToCartesian test. Addresses: /scratch/dashboards/Linux-x86_64-gcc4.6/ITK/Modules/Core/Transform/test/itkAzimuthElevationToCartesianTransformTest.cxx:130: undefined reference to `itk::Point<double, 3u>::PointDimension' This is a follow-up to Change-Id: If19eb586a8c9ddb46978c6d11ec2508e87d3224b Change-Id: Ib8b380a0abeabef10527494930184c6b8a631dab
C++
apache-2.0
zachary-williamson/ITK,BRAINSia/ITK,richardbeare/ITK,Kitware/ITK,thewtex/ITK,hjmjohnson/ITK,stnava/ITK,malaterre/ITK,BRAINSia/ITK,InsightSoftwareConsortium/ITK,stnava/ITK,vfonov/ITK,thewtex/ITK,BRAINSia/ITK,hjmjohnson/ITK,spinicist/ITK,PlutoniumHeart/ITK,spinicist/ITK,PlutoniumHeart/ITK,Kitware/ITK,InsightSoftwareConsortium/ITK,thewtex/ITK,jcfr/ITK,richardbeare/ITK,vfonov/ITK,zachary-williamson/ITK,jcfr/ITK,PlutoniumHeart/ITK,jcfr/ITK,fbudin69500/ITK,spinicist/ITK,zachary-williamson/ITK,zachary-williamson/ITK,LucasGandel/ITK,richardbeare/ITK,LucasGandel/ITK,fbudin69500/ITK,thewtex/ITK,Kitware/ITK,LucasGandel/ITK,fbudin69500/ITK,thewtex/ITK,BRAINSia/ITK,spinicist/ITK,PlutoniumHeart/ITK,spinicist/ITK,zachary-williamson/ITK,PlutoniumHeart/ITK,malaterre/ITK,stnava/ITK,hjmjohnson/ITK,blowekamp/ITK,vfonov/ITK,Kitware/ITK,malaterre/ITK,thewtex/ITK,richardbeare/ITK,zachary-williamson/ITK,InsightSoftwareConsortium/ITK,vfonov/ITK,jcfr/ITK,malaterre/ITK,vfonov/ITK,Kitware/ITK,hjmjohnson/ITK,jcfr/ITK,hjmjohnson/ITK,Kitware/ITK,stnava/ITK,blowekamp/ITK,richardbeare/ITK,zachary-williamson/ITK,LucasGandel/ITK,InsightSoftwareConsortium/ITK,PlutoniumHeart/ITK,Kitware/ITK,richardbeare/ITK,blowekamp/ITK,fbudin69500/ITK,malaterre/ITK,vfonov/ITK,BRAINSia/ITK,LucasGandel/ITK,spinicist/ITK,InsightSoftwareConsortium/ITK,PlutoniumHeart/ITK,hjmjohnson/ITK,malaterre/ITK,malaterre/ITK,fbudin69500/ITK,spinicist/ITK,InsightSoftwareConsortium/ITK,blowekamp/ITK,PlutoniumHeart/ITK,stnava/ITK,LucasGandel/ITK,spinicist/ITK,blowekamp/ITK,vfonov/ITK,vfonov/ITK,jcfr/ITK,jcfr/ITK,blowekamp/ITK,stnava/ITK,hjmjohnson/ITK,BRAINSia/ITK,malaterre/ITK,malaterre/ITK,zachary-williamson/ITK,blowekamp/ITK,thewtex/ITK,stnava/ITK,InsightSoftwareConsortium/ITK,BRAINSia/ITK,fbudin69500/ITK,vfonov/ITK,richardbeare/ITK,spinicist/ITK,stnava/ITK,fbudin69500/ITK,jcfr/ITK,fbudin69500/ITK,LucasGandel/ITK,zachary-williamson/ITK,blowekamp/ITK,stnava/ITK,LucasGandel/ITK
31b32d092f5f5de15652442107c0e4bd89f9704b
Source/core/loader/BeaconLoader.cpp
Source/core/loader/BeaconLoader.cpp
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "config.h" #include "core/loader/BeaconLoader.h" #include "core/FetchInitiatorTypeNames.h" #include "core/fetch/CrossOriginAccessControl.h" #include "core/fetch/FetchContext.h" #include "core/fileapi/File.h" #include "core/frame/LocalFrame.h" #include "core/html/DOMFormData.h" #include "platform/network/FormData.h" #include "platform/network/ParsedContentType.h" #include "platform/network/ResourceRequest.h" #include "public/platform/WebURLRequest.h" #include "wtf/ArrayBufferView.h" namespace blink { void BeaconLoader::prepareRequest(LocalFrame* frame, ResourceRequest& request) { // NOTE: do not distinguish Beacon by target type. request.setRequestContext(blink::WebURLRequest::RequestContextPing); request.setHTTPMethod("POST"); request.setHTTPHeaderField("Cache-Control", "max-age=0"); request.setAllowStoredCredentials(true); frame->loader().fetchContext().addAdditionalRequestHeaders(frame->document(), request, FetchSubresource); frame->loader().fetchContext().setFirstPartyForCookies(request); } void BeaconLoader::issueRequest(LocalFrame* frame, ResourceRequest& request) { FetchInitiatorInfo initiatorInfo; initiatorInfo.name = FetchInitiatorTypeNames::beacon; PingLoader::start(frame, request, initiatorInfo); } bool BeaconLoader::sendBeacon(LocalFrame* frame, int allowance, const KURL& beaconURL, const String& data, int& payloadLength) { ResourceRequest request(beaconURL); prepareRequest(frame, request); RefPtr<FormData> entityBody = FormData::create(data.utf8()); unsigned long long entitySize = entityBody->sizeInBytes(); if (allowance > 0 && static_cast<unsigned>(allowance) < entitySize) return false; request.setHTTPBody(entityBody); request.setHTTPContentType("text/plain;charset=UTF-8"); issueRequest(frame, request); payloadLength = entitySize; return true; } bool BeaconLoader::sendBeacon(LocalFrame* frame, int allowance, const KURL& beaconURL, PassRefPtr<ArrayBufferView>& data, int& payloadLength) { ASSERT(data); unsigned long long entitySize = data->byteLength(); if (allowance > 0 && static_cast<unsigned long long>(allowance) < entitySize) return false; ResourceRequest request(beaconURL); prepareRequest(frame, request); RefPtr<FormData> entityBody = FormData::create(data->baseAddress(), data->byteLength()); request.setHTTPBody(entityBody.release()); // FIXME: a reasonable choice, but not in the spec; should it give a default? AtomicString contentType = AtomicString("application/octet-stream"); request.setHTTPContentType(contentType); issueRequest(frame, request); payloadLength = entitySize; return true; } bool BeaconLoader::sendBeacon(LocalFrame* frame, int allowance, const KURL& beaconURL, PassRefPtrWillBeRawPtr<Blob>& data, int& payloadLength) { ASSERT(data); unsigned long long entitySize = data->size(); if (allowance > 0 && static_cast<unsigned long long>(allowance) < entitySize) return false; ResourceRequest request(beaconURL); prepareRequest(frame, request); RefPtr<FormData> entityBody = FormData::create(); if (data->hasBackingFile()) entityBody->appendFile(toFile(data.get())->path()); else entityBody->appendBlob(data->uuid(), data->blobDataHandle()); request.setHTTPBody(entityBody.release()); AtomicString contentType; const String& blobType = data->type(); if (!blobType.isEmpty() && isValidContentType(blobType)) request.setHTTPContentType(AtomicString(contentType)); issueRequest(frame, request); payloadLength = entitySize; return true; } bool BeaconLoader::sendBeacon(LocalFrame* frame, int allowance, const KURL& beaconURL, PassRefPtrWillBeRawPtr<DOMFormData>& data, int& payloadLength) { ASSERT(data); ResourceRequest request(beaconURL); prepareRequest(frame, request); RefPtr<FormData> entityBody = data->createMultiPartFormData(); unsigned long long entitySize = entityBody->sizeInBytes(); if (allowance > 0 && static_cast<unsigned long long>(allowance) < entitySize) return false; AtomicString contentType = AtomicString("multipart/form-data; boundary=", AtomicString::ConstructFromLiteral) + entityBody->boundary().data(); request.setHTTPBody(entityBody.release()); request.setHTTPContentType(contentType); issueRequest(frame, request); payloadLength = entitySize; return true; } } // namespace blink
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "config.h" #include "core/loader/BeaconLoader.h" #include "core/FetchInitiatorTypeNames.h" #include "core/fetch/CrossOriginAccessControl.h" #include "core/fetch/FetchContext.h" #include "core/fileapi/File.h" #include "core/frame/LocalFrame.h" #include "core/html/DOMFormData.h" #include "platform/network/FormData.h" #include "platform/network/ParsedContentType.h" #include "platform/network/ResourceRequest.h" #include "public/platform/WebURLRequest.h" #include "wtf/ArrayBufferView.h" namespace blink { void BeaconLoader::prepareRequest(LocalFrame* frame, ResourceRequest& request) { request.setRequestContext(WebURLRequest::RequestContextBeacon); request.setHTTPMethod("POST"); request.setHTTPHeaderField("Cache-Control", "max-age=0"); request.setAllowStoredCredentials(true); frame->loader().fetchContext().addAdditionalRequestHeaders(frame->document(), request, FetchSubresource); frame->loader().fetchContext().setFirstPartyForCookies(request); } void BeaconLoader::issueRequest(LocalFrame* frame, ResourceRequest& request) { FetchInitiatorInfo initiatorInfo; initiatorInfo.name = FetchInitiatorTypeNames::beacon; PingLoader::start(frame, request, initiatorInfo); } bool BeaconLoader::sendBeacon(LocalFrame* frame, int allowance, const KURL& beaconURL, const String& data, int& payloadLength) { ResourceRequest request(beaconURL); prepareRequest(frame, request); RefPtr<FormData> entityBody = FormData::create(data.utf8()); unsigned long long entitySize = entityBody->sizeInBytes(); if (allowance > 0 && static_cast<unsigned>(allowance) < entitySize) return false; request.setHTTPBody(entityBody); request.setHTTPContentType("text/plain;charset=UTF-8"); issueRequest(frame, request); payloadLength = entitySize; return true; } bool BeaconLoader::sendBeacon(LocalFrame* frame, int allowance, const KURL& beaconURL, PassRefPtr<ArrayBufferView>& data, int& payloadLength) { ASSERT(data); unsigned long long entitySize = data->byteLength(); if (allowance > 0 && static_cast<unsigned long long>(allowance) < entitySize) return false; ResourceRequest request(beaconURL); prepareRequest(frame, request); RefPtr<FormData> entityBody = FormData::create(data->baseAddress(), data->byteLength()); request.setHTTPBody(entityBody.release()); // FIXME: a reasonable choice, but not in the spec; should it give a default? AtomicString contentType = AtomicString("application/octet-stream"); request.setHTTPContentType(contentType); issueRequest(frame, request); payloadLength = entitySize; return true; } bool BeaconLoader::sendBeacon(LocalFrame* frame, int allowance, const KURL& beaconURL, PassRefPtrWillBeRawPtr<Blob>& data, int& payloadLength) { ASSERT(data); unsigned long long entitySize = data->size(); if (allowance > 0 && static_cast<unsigned long long>(allowance) < entitySize) return false; ResourceRequest request(beaconURL); prepareRequest(frame, request); RefPtr<FormData> entityBody = FormData::create(); if (data->hasBackingFile()) entityBody->appendFile(toFile(data.get())->path()); else entityBody->appendBlob(data->uuid(), data->blobDataHandle()); request.setHTTPBody(entityBody.release()); AtomicString contentType; const String& blobType = data->type(); if (!blobType.isEmpty() && isValidContentType(blobType)) request.setHTTPContentType(AtomicString(contentType)); issueRequest(frame, request); payloadLength = entitySize; return true; } bool BeaconLoader::sendBeacon(LocalFrame* frame, int allowance, const KURL& beaconURL, PassRefPtrWillBeRawPtr<DOMFormData>& data, int& payloadLength) { ASSERT(data); ResourceRequest request(beaconURL); prepareRequest(frame, request); RefPtr<FormData> entityBody = data->createMultiPartFormData(); unsigned long long entitySize = entityBody->sizeInBytes(); if (allowance > 0 && static_cast<unsigned long long>(allowance) < entitySize) return false; AtomicString contentType = AtomicString("multipart/form-data; boundary=", AtomicString::ConstructFromLiteral) + entityBody->boundary().data(); request.setHTTPBody(entityBody.release()); request.setHTTPContentType(contentType); issueRequest(frame, request); payloadLength = entitySize; return true; } } // namespace blink
Use a precise target type for Beacon requests.
Use a precise target type for Beacon requests. To allow the embedder to distinguish POST requests emanating from sendBeacon() from those from a <a ping>, assign a more precise target type to the former. This is done in preparation for adding Beacon-Age: headers to Beacon requests. [email protected] BUG=398167 Review URL: https://codereview.chromium.org/468853002 git-svn-id: bf5cd6ccde378db821296732a091cfbcf5285fbd@180179 bbb929c8-8fbe-4397-9dbb-9b2b20218538
C++
bsd-3-clause
jtg-gg/blink,PeterWangIntel/blink-crosswalk,crosswalk-project/blink-crosswalk-efl,hgl888/blink-crosswalk-efl,ondra-novak/blink,smishenk/blink-crosswalk,jtg-gg/blink,XiaosongWei/blink-crosswalk,crosswalk-project/blink-crosswalk-efl,XiaosongWei/blink-crosswalk,kurli/blink-crosswalk,jtg-gg/blink,Bysmyyr/blink-crosswalk,XiaosongWei/blink-crosswalk,crosswalk-project/blink-crosswalk-efl,Bysmyyr/blink-crosswalk,ondra-novak/blink,modulexcite/blink,Pluto-tv/blink-crosswalk,kurli/blink-crosswalk,hgl888/blink-crosswalk-efl,Bysmyyr/blink-crosswalk,crosswalk-project/blink-crosswalk-efl,PeterWangIntel/blink-crosswalk,modulexcite/blink,modulexcite/blink,nwjs/blink,Bysmyyr/blink-crosswalk,Pluto-tv/blink-crosswalk,PeterWangIntel/blink-crosswalk,modulexcite/blink,nwjs/blink,XiaosongWei/blink-crosswalk,kurli/blink-crosswalk,hgl888/blink-crosswalk-efl,hgl888/blink-crosswalk-efl,nwjs/blink,smishenk/blink-crosswalk,hgl888/blink-crosswalk-efl,smishenk/blink-crosswalk,Bysmyyr/blink-crosswalk,PeterWangIntel/blink-crosswalk,jtg-gg/blink,XiaosongWei/blink-crosswalk,modulexcite/blink,crosswalk-project/blink-crosswalk-efl,Bysmyyr/blink-crosswalk,hgl888/blink-crosswalk-efl,Pluto-tv/blink-crosswalk,smishenk/blink-crosswalk,ondra-novak/blink,jtg-gg/blink,crosswalk-project/blink-crosswalk-efl,nwjs/blink,Bysmyyr/blink-crosswalk,PeterWangIntel/blink-crosswalk,modulexcite/blink,XiaosongWei/blink-crosswalk,XiaosongWei/blink-crosswalk,smishenk/blink-crosswalk,Pluto-tv/blink-crosswalk,nwjs/blink,ondra-novak/blink,smishenk/blink-crosswalk,Pluto-tv/blink-crosswalk,jtg-gg/blink,ondra-novak/blink,PeterWangIntel/blink-crosswalk,Bysmyyr/blink-crosswalk,nwjs/blink,nwjs/blink,nwjs/blink,PeterWangIntel/blink-crosswalk,kurli/blink-crosswalk,hgl888/blink-crosswalk-efl,hgl888/blink-crosswalk-efl,kurli/blink-crosswalk,kurli/blink-crosswalk,Pluto-tv/blink-crosswalk,kurli/blink-crosswalk,kurli/blink-crosswalk,PeterWangIntel/blink-crosswalk,jtg-gg/blink,jtg-gg/blink,smishenk/blink-crosswalk,hgl888/blink-crosswalk-efl,Bysmyyr/blink-crosswalk,hgl888/blink-crosswalk-efl,Pluto-tv/blink-crosswalk,ondra-novak/blink,modulexcite/blink,smishenk/blink-crosswalk,ondra-novak/blink,Bysmyyr/blink-crosswalk,Pluto-tv/blink-crosswalk,PeterWangIntel/blink-crosswalk,kurli/blink-crosswalk,XiaosongWei/blink-crosswalk,modulexcite/blink,jtg-gg/blink,crosswalk-project/blink-crosswalk-efl,kurli/blink-crosswalk,modulexcite/blink,nwjs/blink,XiaosongWei/blink-crosswalk,PeterWangIntel/blink-crosswalk,modulexcite/blink,crosswalk-project/blink-crosswalk-efl,jtg-gg/blink,ondra-novak/blink,crosswalk-project/blink-crosswalk-efl,Pluto-tv/blink-crosswalk,nwjs/blink,XiaosongWei/blink-crosswalk,Pluto-tv/blink-crosswalk,smishenk/blink-crosswalk,smishenk/blink-crosswalk,ondra-novak/blink
7419fdf53b4a408fdc13b1ea626f7a2bdd47903d
plugins/gipfeli/squash-gipfeli.cpp
plugins/gipfeli/squash-gipfeli.cpp
/* Copyright (c) 2013-2014 The Squash Authors * * 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. * * Authors: * Evan Nemerson <[email protected]> */ #include <assert.h> #include <stdlib.h> #include <string.h> #include <strings.h> #include <stdexcept> #include <squash/squash.h> #include "gipfeli/gipfeli.h" extern "C" SQUASH_PLUGIN_EXPORT SquashStatus squash_plugin_init_codec (SquashCodec* codec, SquashCodecImpl* impl); static size_t squash_gipfeli_get_max_compressed_size (SquashCodec* codec, size_t uncompressed_length) { size_t ret; util::compression::Compressor* compressor = util::compression::NewGipfeliCompressor(); ret = compressor->MaxCompressedLength (uncompressed_length); delete compressor; return ret; } static size_t squash_gipfeli_get_uncompressed_size (SquashCodec* codec, size_t compressed_length, const uint8_t compressed[SQUASH_ARRAY_PARAM(compressed_length)]) { util::compression::Compressor* compressor = util::compression::NewGipfeliCompressor(); std::string compressed_str((const char*) compressed, compressed_length); size_t uncompressed_length = 0; bool success = compressor->GetUncompressedLength (compressed_str, &uncompressed_length); delete compressor; return success ? uncompressed_length : 0; } class CheckedByteArraySink : public util::compression::Sink { public: explicit CheckedByteArraySink(char* dest, size_t dest_length) : dest_(dest), remaining_(dest_length) {} virtual ~CheckedByteArraySink() {} virtual void Append(const char* data, size_t n) { if (n > remaining_) { throw std::overflow_error("buffer too small"); } if (data != dest_) { memcpy(dest_, data, n); } dest_ += n; remaining_ -= n; } char* GetAppendBufferVariable(size_t min_size, size_t desired_size_hint, char* scratch, size_t scratch_size, size_t* allocated_size) { *allocated_size = desired_size_hint; return dest_; } private: char* dest_; size_t remaining_; }; static SquashStatus squash_gipfeli_decompress_buffer (SquashCodec* codec, size_t* decompressed_length, uint8_t decompressed[SQUASH_ARRAY_PARAM(*decompressed_length)], size_t compressed_length, const uint8_t compressed[SQUASH_ARRAY_PARAM(compressed_length)], SquashOptions* options) { util::compression::Compressor* compressor = util::compression::NewGipfeliCompressor(); util::compression::UncheckedByteArraySink sink((char*) decompressed); util::compression::ByteArraySource source((const char*) compressed, compressed_length); SquashStatus res = SQUASH_OK; if (compressor == NULL) return squash_error (SQUASH_MEMORY); std::string compressed_str((const char*) compressed, compressed_length); size_t uncompressed_length; if (!compressor->GetUncompressedLength (compressed_str, &uncompressed_length)) { res = squash_error (SQUASH_FAILED); goto cleanup; } if (uncompressed_length > *decompressed_length) { res = squash_error (SQUASH_BUFFER_FULL); goto cleanup; } else { *decompressed_length = uncompressed_length; } if (!compressor->UncompressStream (&source, &sink)) { res = squash_error (SQUASH_FAILED); } cleanup: delete compressor; return res; } static SquashStatus squash_gipfeli_compress_buffer (SquashCodec* codec, size_t* compressed_length, uint8_t compressed[SQUASH_ARRAY_PARAM(*compressed_length)], size_t uncompressed_length, const uint8_t uncompressed[SQUASH_ARRAY_PARAM(uncompressed_length)], SquashOptions* options) { util::compression::Compressor* compressor = util::compression::NewGipfeliCompressor(); CheckedByteArraySink sink((char*) compressed, *compressed_length); util::compression::ByteArraySource source((const char*) uncompressed, uncompressed_length); SquashStatus res; try { *compressed_length = compressor->CompressStream (&source, &sink); res = SQUASH_OK; } catch (const std::bad_alloc& e) { res = squash_error (SQUASH_MEMORY); } catch (...) { res = squash_error (SQUASH_FAILED); } delete compressor; if (res == SQUASH_OK && *compressed_length == 0) res = squash_error (SQUASH_FAILED); return res; } static SquashStatus squash_gipfeli_compress_buffer_unsafe (SquashCodec* codec, size_t* compressed_length, uint8_t compressed[SQUASH_ARRAY_PARAM(*compressed_length)], size_t uncompressed_length, const uint8_t uncompressed[SQUASH_ARRAY_PARAM(uncompressed_length)], SquashOptions* options) { util::compression::Compressor* compressor = util::compression::NewGipfeliCompressor(); util::compression::UncheckedByteArraySink sink((char*) compressed); util::compression::ByteArraySource source((const char*) uncompressed, uncompressed_length); SquashStatus res; try { *compressed_length = compressor->CompressStream (&source, &sink); res = SQUASH_OK; } catch (const std::bad_alloc& e) { res = squash_error (SQUASH_MEMORY); } catch (const std::overflow_error& e) { res = squash_error (SQUASH_BUFFER_FULL); } catch (...) { res = squash_error (SQUASH_FAILED); } delete compressor; if (res == SQUASH_OK && *compressed_length == 0) res = squash_error (SQUASH_FAILED); return res; } extern "C" SquashStatus squash_plugin_init_codec (SquashCodec* codec, SquashCodecImpl* impl) { const char* name = squash_codec_get_name (codec); if (strcmp ("gipfeli", name) == 0) { impl->get_uncompressed_size = squash_gipfeli_get_uncompressed_size; impl->get_max_compressed_size = squash_gipfeli_get_max_compressed_size; impl->decompress_buffer = squash_gipfeli_decompress_buffer; impl->compress_buffer = squash_gipfeli_compress_buffer; impl->compress_buffer_unsafe = squash_gipfeli_compress_buffer_unsafe; } else { return squash_error (SQUASH_UNABLE_TO_LOAD); } return SQUASH_OK; }
/* Copyright (c) 2013-2014 The Squash Authors * * 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. * * Authors: * Evan Nemerson <[email protected]> */ #include <assert.h> #include <stdlib.h> #include <string.h> #include <strings.h> #include <stdexcept> #include <squash/squash.h> #include "gipfeli/gipfeli.h" extern "C" SQUASH_PLUGIN_EXPORT SquashStatus squash_plugin_init_codec (SquashCodec* codec, SquashCodecImpl* impl); static size_t squash_gipfeli_get_max_compressed_size (SquashCodec* codec, size_t uncompressed_length) { size_t ret; util::compression::Compressor* compressor = util::compression::NewGipfeliCompressor(); ret = compressor->MaxCompressedLength (uncompressed_length); delete compressor; return ret; } static size_t squash_gipfeli_get_uncompressed_size (SquashCodec* codec, size_t compressed_length, const uint8_t compressed[SQUASH_ARRAY_PARAM(compressed_length)]) { util::compression::Compressor* compressor = util::compression::NewGipfeliCompressor(); std::string compressed_str((const char*) compressed, compressed_length); size_t uncompressed_length = 0; bool success = compressor->GetUncompressedLength (compressed_str, &uncompressed_length); delete compressor; return success ? uncompressed_length : 0; } class CheckedByteArraySink : public util::compression::Sink { public: explicit CheckedByteArraySink(char* dest, size_t dest_length) : dest_(dest), remaining_(dest_length) {} virtual ~CheckedByteArraySink() {} virtual void Append(const char* data, size_t n) { if (n > remaining_) { throw std::overflow_error("buffer too small"); } if (data != dest_) { memcpy(dest_, data, n); } dest_ += n; remaining_ -= n; } char* GetAppendBufferVariable(size_t min_size, size_t desired_size_hint, char* scratch, size_t scratch_size, size_t* allocated_size) { *allocated_size = desired_size_hint; return dest_; } private: char* dest_; size_t remaining_; }; static SquashStatus squash_gipfeli_decompress_buffer (SquashCodec* codec, size_t* decompressed_length, uint8_t decompressed[SQUASH_ARRAY_PARAM(*decompressed_length)], size_t compressed_length, const uint8_t compressed[SQUASH_ARRAY_PARAM(compressed_length)], SquashOptions* options) { util::compression::Compressor* compressor = util::compression::NewGipfeliCompressor(); util::compression::UncheckedByteArraySink sink((char*) decompressed); util::compression::ByteArraySource source((const char*) compressed, compressed_length); SquashStatus res = SQUASH_OK; if (compressor == NULL) return squash_error (SQUASH_MEMORY); std::string compressed_str((const char*) compressed, compressed_length); size_t uncompressed_length; if (!compressor->GetUncompressedLength (compressed_str, &uncompressed_length)) { res = squash_error (SQUASH_FAILED); goto cleanup; } if (uncompressed_length > *decompressed_length) { res = squash_error (SQUASH_BUFFER_FULL); goto cleanup; } else { *decompressed_length = uncompressed_length; } if (!compressor->UncompressStream (&source, &sink)) { res = squash_error (SQUASH_FAILED); } cleanup: delete compressor; return res; } static SquashStatus squash_gipfeli_compress_buffer (SquashCodec* codec, size_t* compressed_length, uint8_t compressed[SQUASH_ARRAY_PARAM(*compressed_length)], size_t uncompressed_length, const uint8_t uncompressed[SQUASH_ARRAY_PARAM(uncompressed_length)], SquashOptions* options) { util::compression::Compressor* compressor = util::compression::NewGipfeliCompressor(); CheckedByteArraySink sink((char*) compressed, *compressed_length); util::compression::ByteArraySource source((const char*) uncompressed, uncompressed_length); SquashStatus res; try { *compressed_length = compressor->CompressStream (&source, &sink); res = SQUASH_OK; } catch (const std::bad_alloc& e) { res = squash_error (SQUASH_MEMORY); } catch (const std::overflow_error& e) { res = squash_error (SQUASH_BUFFER_FULL); } catch (...) { res = squash_error (SQUASH_FAILED); } delete compressor; if (res == SQUASH_OK && *compressed_length == 0) res = squash_error (SQUASH_FAILED); return res; } static SquashStatus squash_gipfeli_compress_buffer_unsafe (SquashCodec* codec, size_t* compressed_length, uint8_t compressed[SQUASH_ARRAY_PARAM(*compressed_length)], size_t uncompressed_length, const uint8_t uncompressed[SQUASH_ARRAY_PARAM(uncompressed_length)], SquashOptions* options) { util::compression::Compressor* compressor = util::compression::NewGipfeliCompressor(); util::compression::UncheckedByteArraySink sink((char*) compressed); util::compression::ByteArraySource source((const char*) uncompressed, uncompressed_length); SquashStatus res; try { *compressed_length = compressor->CompressStream (&source, &sink); res = SQUASH_OK; } catch (const std::bad_alloc& e) { res = squash_error (SQUASH_MEMORY); } catch (const std::overflow_error& e) { res = squash_error (SQUASH_BUFFER_FULL); } catch (...) { res = squash_error (SQUASH_FAILED); } delete compressor; if (res == SQUASH_OK && *compressed_length == 0) res = squash_error (SQUASH_FAILED); return res; } extern "C" SquashStatus squash_plugin_init_codec (SquashCodec* codec, SquashCodecImpl* impl) { const char* name = squash_codec_get_name (codec); if (strcmp ("gipfeli", name) == 0) { impl->get_uncompressed_size = squash_gipfeli_get_uncompressed_size; impl->get_max_compressed_size = squash_gipfeli_get_max_compressed_size; impl->decompress_buffer = squash_gipfeli_decompress_buffer; impl->compress_buffer = squash_gipfeli_compress_buffer; impl->compress_buffer_unsafe = squash_gipfeli_compress_buffer_unsafe; } else { return squash_error (SQUASH_UNABLE_TO_LOAD); } return SQUASH_OK; }
handle buffer full errors during compression
gipfeli: handle buffer full errors during compression
C++
mit
jibsen/squash,Cloudef/squash,Cloudef/squash,wolut/squash,Cloudef/squash,jibsen/squash,quixdb/squash,quixdb/squash,quixdb/squash,wolut/squash,jibsen/squash,wolut/squash
78e56d9de29d8f6e54422c6b2121060dff95f3ae
src/js_grid_utils.hpp
src/js_grid_utils.hpp
#ifndef __NODE_MAPNIK_GRID_UTILS_H__ #define __NODE_MAPNIK_GRID_UTILS_H__ // v8 #include <v8.h> // mapnik #include <mapnik/grid/grid.hpp> #include "utils.hpp" using namespace v8; using namespace node; namespace node_mapnik { template <typename T> static void grid2utf(T const& grid_type, Local<Array>& l, std::vector<typename T::lookup_type>& key_order) { typename T::data_type const& data = grid_type.data(); typename T::feature_key_type const& feature_keys = grid_type.get_feature_keys(); typename T::key_type keys; typename T::key_type::const_iterator key_pos; typename T::feature_key_type::const_iterator feature_pos; // start counting at utf8 codepoint 32, aka space character uint16_t codepoint = 32; uint16_t row_idx = 0; unsigned array_size = data.width(); for (unsigned y = 0; y < data.height(); ++y) { uint16_t idx = 0; boost::scoped_array<uint16_t> line(new uint16_t[array_size]); typename T::value_type const* row = data.getRow(y); for (unsigned x = 0; x < data.width(); ++x) { feature_pos = feature_keys.find(row[x]); if (feature_pos != feature_keys.end()) { typename T::lookup_type const& val = feature_pos->second; key_pos = keys.find(val); if (key_pos == keys.end()) { // Create a new entry for this key. Skip the codepoints that // can't be encoded directly in JSON. if (codepoint == 34) ++codepoint; // Skip " else if (codepoint == 92) ++codepoint; // Skip backslash keys[val] = codepoint; key_order.push_back(val); line[idx++] = static_cast<uint16_t>(codepoint); ++codepoint; } else { line[idx++] = static_cast<uint16_t>(key_pos->second); } } // else, shouldn't get here... } l->Set(row_idx, String::New(line.get(),array_size)); ++row_idx; } } // requires mapnik >= r2957 template <typename T> static void grid2utf(T const& grid_type, Local<Array>& l, std::vector<typename T::lookup_type>& key_order, unsigned int resolution) { typename T::feature_key_type const& feature_keys = grid_type.get_feature_keys(); typename T::key_type keys; typename T::key_type::const_iterator key_pos; typename T::feature_key_type::const_iterator feature_pos; // start counting at utf8 codepoint 32, aka space character uint16_t codepoint = 32; uint16_t row_idx = 0; unsigned array_size = static_cast<unsigned int>(grid_type.width()/resolution); for (unsigned y = 0; y < grid_type.height(); y=y+resolution) { uint16_t idx = 0; boost::scoped_array<uint16_t> line(new uint16_t[array_size]); typename T::value_type const* row = grid_type.getRow(y); for (unsigned x = 0; x < grid_type.width(); x=x+resolution) { // todo - this lookup is expensive feature_pos = feature_keys.find(row[x]); if (feature_pos != feature_keys.end()) { typename T::lookup_type const& val = feature_pos->second; key_pos = keys.find(val); if (key_pos == keys.end()) { // Create a new entry for this key. Skip the codepoints that // can't be encoded directly in JSON. if (codepoint == 34) ++codepoint; // Skip " else if (codepoint == 92) ++codepoint; // Skip backslash keys[val] = codepoint; key_order.push_back(val); line[idx++] = static_cast<uint16_t>(codepoint); ++codepoint; } else { line[idx++] = static_cast<uint16_t>(key_pos->second); } } // else, shouldn't get here... } l->Set(row_idx, String::New(line.get(),array_size)); ++row_idx; } } template <typename T> static void write_features(T const& grid_type, Local<Object>& feature_data, std::vector<typename T::lookup_type> const& key_order) { std::string const& key = grid_type.get_key(); std::set<std::string> const& attributes = grid_type.property_names(); typename T::feature_type const& g_features = grid_type.get_grid_features(); typename T::feature_type::const_iterator feat_itr = g_features.begin(); typename T::feature_type::const_iterator feat_end = g_features.end(); bool include_key = (attributes.find(key) != attributes.end()); for (; feat_itr != feat_end; ++feat_itr) { mapnik::Feature const* feature = feat_itr->second; boost::optional<std::string> join_value; if (key == grid_type.key_name()) { std::stringstream s; s << feature->id(); join_value = s.str(); } else if (feature->has_key(key)) { join_value = feature->get(key).to_string(); } if (join_value) { // only serialize features visible in the grid if(std::find(key_order.begin(), key_order.end(), *join_value) != key_order.end()) { Local<Object> feat = Object::New(); bool found = false; if (key == grid_type.key_name()) { // drop key unless requested if (include_key) { found = true; // TODO do we need to duplicate __id__ ? //feat->Set(String::NewSymbol(key.c_str()), String::New(join_value->c_str()) ); } } // FIXME: segfault here because feature ctx is gone? //std::clog << "feautre : " << *feature << "\n"; mapnik::feature_kv_iterator itr = feature->begin(); //mapnik::feature_kv_iterator end = feature->end(); /*for ( ;itr!=end; ++itr) { std::string const& key_name = boost::get<0>(*itr); if (key_name == key) { // drop key unless requested if (include_key) { found = true; params_to_object serializer( feat , key_name); boost::apply_visitor( serializer, boost::get<1>(*itr).base() ); } } else if ( (attributes.find(key_name) != attributes.end()) ) { found = true; params_to_object serializer( feat , key_name); boost::apply_visitor( serializer, boost::get<1>(*itr).base() ); } }*/ if (found) { feature_data->Set(String::NewSymbol(feat_itr->first.c_str()), feat); } } } else { std::clog << "should not get here: key '" << key << "' not found in grid feature properties\n"; } } } } #endif // __NODE_MAPNIK_GRID_UTILS_H__
#ifndef __NODE_MAPNIK_GRID_UTILS_H__ #define __NODE_MAPNIK_GRID_UTILS_H__ // v8 #include <v8.h> // mapnik #include <mapnik/grid/grid.hpp> #include "utils.hpp" using namespace v8; using namespace node; namespace node_mapnik { template <typename T> static void grid2utf(T const& grid_type, Local<Array>& l, std::vector<typename T::lookup_type>& key_order) { typename T::data_type const& data = grid_type.data(); typename T::feature_key_type const& feature_keys = grid_type.get_feature_keys(); typename T::key_type keys; typename T::key_type::const_iterator key_pos; typename T::feature_key_type::const_iterator feature_pos; // start counting at utf8 codepoint 32, aka space character uint16_t codepoint = 32; uint16_t row_idx = 0; unsigned array_size = data.width(); for (unsigned y = 0; y < data.height(); ++y) { uint16_t idx = 0; boost::scoped_array<uint16_t> line(new uint16_t[array_size]); typename T::value_type const* row = data.getRow(y); for (unsigned x = 0; x < data.width(); ++x) { feature_pos = feature_keys.find(row[x]); if (feature_pos != feature_keys.end()) { typename T::lookup_type const& val = feature_pos->second; key_pos = keys.find(val); if (key_pos == keys.end()) { // Create a new entry for this key. Skip the codepoints that // can't be encoded directly in JSON. if (codepoint == 34) ++codepoint; // Skip " else if (codepoint == 92) ++codepoint; // Skip backslash keys[val] = codepoint; key_order.push_back(val); line[idx++] = static_cast<uint16_t>(codepoint); ++codepoint; } else { line[idx++] = static_cast<uint16_t>(key_pos->second); } } // else, shouldn't get here... } l->Set(row_idx, String::New(line.get(),array_size)); ++row_idx; } } // requires mapnik >= r2957 template <typename T> static void grid2utf(T const& grid_type, Local<Array>& l, std::vector<typename T::lookup_type>& key_order, unsigned int resolution) { typename T::feature_key_type const& feature_keys = grid_type.get_feature_keys(); typename T::key_type keys; typename T::key_type::const_iterator key_pos; typename T::feature_key_type::const_iterator feature_pos; // start counting at utf8 codepoint 32, aka space character uint16_t codepoint = 32; uint16_t row_idx = 0; unsigned array_size = static_cast<unsigned int>(grid_type.width()/resolution); for (unsigned y = 0; y < grid_type.height(); y=y+resolution) { uint16_t idx = 0; boost::scoped_array<uint16_t> line(new uint16_t[array_size]); typename T::value_type const* row = grid_type.getRow(y); for (unsigned x = 0; x < grid_type.width(); x=x+resolution) { // todo - this lookup is expensive feature_pos = feature_keys.find(row[x]); if (feature_pos != feature_keys.end()) { typename T::lookup_type const& val = feature_pos->second; key_pos = keys.find(val); if (key_pos == keys.end()) { // Create a new entry for this key. Skip the codepoints that // can't be encoded directly in JSON. if (codepoint == 34) ++codepoint; // Skip " else if (codepoint == 92) ++codepoint; // Skip backslash keys[val] = codepoint; key_order.push_back(val); line[idx++] = static_cast<uint16_t>(codepoint); ++codepoint; } else { line[idx++] = static_cast<uint16_t>(key_pos->second); } } // else, shouldn't get here... } l->Set(row_idx, String::New(line.get(),array_size)); ++row_idx; } } template <typename T> static void write_features(T const& grid_type, Local<Object>& feature_data, std::vector<typename T::lookup_type> const& key_order) { std::string const& key = grid_type.get_key(); std::set<std::string> const& attributes = grid_type.property_names(); typename T::feature_type const& g_features = grid_type.get_grid_features(); typename T::feature_type::const_iterator feat_itr = g_features.begin(); typename T::feature_type::const_iterator feat_end = g_features.end(); bool include_key = (attributes.find(key) != attributes.end()); for (; feat_itr != feat_end; ++feat_itr) { mapnik::Feature const* feature = feat_itr->second; boost::optional<std::string> join_value; if (key == grid_type.key_name()) { std::stringstream s; s << feature->id(); join_value = s.str(); } else if (feature->has_key(key)) { join_value = feature->get(key).to_string(); } if (join_value) { // only serialize features visible in the grid if(std::find(key_order.begin(), key_order.end(), *join_value) != key_order.end()) { Local<Object> feat = Object::New(); bool found = false; if (key == grid_type.key_name()) { // drop key unless requested if (include_key) { found = true; // TODO do we need to duplicate __id__ ? //feat->Set(String::NewSymbol(key.c_str()), String::New(join_value->c_str()) ); } } // FIXME: segfault here because feature ctx is gone? //std::clog << "feautre : " << *feature << "\n"; //mapnik::feature_kv_iterator itr = feature->begin(); //mapnik::feature_kv_iterator end = feature->end(); /*for ( ;itr!=end; ++itr) { std::string const& key_name = boost::get<0>(*itr); if (key_name == key) { // drop key unless requested if (include_key) { found = true; params_to_object serializer( feat , key_name); boost::apply_visitor( serializer, boost::get<1>(*itr).base() ); } } else if ( (attributes.find(key_name) != attributes.end()) ) { found = true; params_to_object serializer( feat , key_name); boost::apply_visitor( serializer, boost::get<1>(*itr).base() ); } }*/ if (found) { feature_data->Set(String::NewSymbol(feat_itr->first.c_str()), feat); } } } else { std::clog << "should not get here: key '" << key << "' not found in grid feature properties\n"; } } } } #endif // __NODE_MAPNIK_GRID_UTILS_H__
disable grid data and avoid segfault with latest mapnik
disable grid data and avoid segfault with latest mapnik
C++
bsd-3-clause
MaxSem/node-mapnik,gravitystorm/node-mapnik,mojodna/node-mapnik,tomhughes/node-mapnik,Uli1/node-mapnik,CartoDB/node-mapnik,mapnik/node-mapnik,langateam/node-mapnik,mapnik/node-mapnik,mapnik/node-mapnik,CartoDB/node-mapnik,CartoDB/node-mapnik,mojodna/node-mapnik,langateam/node-mapnik,gravitystorm/node-mapnik,Uli1/node-mapnik,Uli1/node-mapnik,Uli1/node-mapnik,tomhughes/node-mapnik,mojodna/node-mapnik,gravitystorm/node-mapnik,tomhughes/node-mapnik,stefanklug/node-mapnik,stefanklug/node-mapnik,MaxSem/node-mapnik,stefanklug/node-mapnik,langateam/node-mapnik,mapnik/node-mapnik,stefanklug/node-mapnik,langateam/node-mapnik,MaxSem/node-mapnik,langateam/node-mapnik,tomhughes/node-mapnik,gravitystorm/node-mapnik,mapnik/node-mapnik,tomhughes/node-mapnik,mojodna/node-mapnik,CartoDB/node-mapnik,MaxSem/node-mapnik,CartoDB/node-mapnik
84844738693e3097c49267ca8b8447e23207074b
src/statement.cpp
src/statement.cpp
#include "sqlitewrapper/statement.h" #include <cstdint> #include <vector> #include "sqlitewrapper/binder.h" #include "sqlitewrapper/exceptions.h" #include "sqlitewrapper/sqlite3.h" namespace SqliteWrapper { struct Statement::Impl { sqlite3_stmt *stmt = nullptr; }; Statement::Statement(sqlite3_stmt *stmt) : impl(new Impl) { impl->stmt = stmt; } Statement::Statement(Statement &&other) : impl(new Impl) { std::swap(impl, other.impl); } Statement &Statement::operator=(Statement &&rhs) { std::swap(impl, rhs.impl); return *this; } Statement::~Statement() { sqlite3_finalize(impl->stmt); } Statement &Statement::bindNull(int pos) { checkResult(sqlite3_bind_null(impl->stmt, pos + 1)); return *this; } RowIterator Statement::begin() { return RowIterator(impl->stmt, false); } RowIterator Statement::end() { return RowIterator(impl->stmt, true); } void Statement::clearBindings() { checkResult(sqlite3_clear_bindings(impl->stmt)); } void Statement::reset() { checkResult(sqlite3_reset(impl->stmt)); } sqlite3_stmt *Statement::statementHandle() const { return impl->stmt; } RowIterator::RowIterator(sqlite3_stmt *stmt, bool done) : m_stmt(stmt), m_done(done), m_row(stmt) { //FIXME make it possible to invoke .begin() multiple times without moving if (!done) { // get first result ++(*this); } } bool RowIterator::operator==(const RowIterator &rhs) const { return (m_stmt == rhs.m_stmt) && (m_done == rhs.m_done); } bool RowIterator::operator!=(const RowIterator &rhs) const { return !(*this == rhs); } RowIterator &RowIterator::operator++() { int result = sqlite3_step(m_stmt); switch (result) { case SQLITE_ROW: m_done = false; break; case SQLITE_DONE: m_done = true; break; default: checkResult(result); } m_row.setColumns(sqlite3_column_count(m_stmt)); return *this; } Row &RowIterator::operator*() { return m_row; } Row *RowIterator::operator->() { return &m_row; } Row::Row(sqlite3_stmt *stmt) : m_stmt(stmt) { } bool Row::isNull(int pos) const { return sqlite3_column_type(m_stmt, pos) == SQLITE_NULL; } void Row::setColumns(int columns) { m_columns = columns; } void Row::checkPosRange(int pos) const { if (pos < 0 || pos >= m_columns) { throw Exception("Column out of range"); } } // BEGIN native types of SQLite template <> std::int32_t Row::getUnchecked(int pos) const { return sqlite3_column_int(m_stmt, pos); } template <> std::int64_t Row::getUnchecked(int pos) const { return sqlite3_column_int64(m_stmt, pos); } template <> double Row::getUnchecked(int pos) const { return sqlite3_column_double(m_stmt, pos); } template <> std::string Row::getUnchecked(int pos) const { return std::string(reinterpret_cast<const char*>(sqlite3_column_text(m_stmt, pos))); } template <> std::vector<unsigned char> Row::getUnchecked(int pos) const { int size = sqlite3_column_bytes(m_stmt, pos); if (size == 0) return std::vector<unsigned char>(); const unsigned char *data = reinterpret_cast<const unsigned char*>(sqlite3_column_blob(m_stmt, pos)); return std::vector<unsigned char>(data, data + size); } // END native types of SQLite template <> bool Row::getUnchecked(int pos) const { return getUnchecked<std::int32_t>(pos) != 0; } template <> std::int8_t Row::getUnchecked(int pos) const { return getUnchecked<std::int32_t>(pos); } template <> std::int16_t Row::getUnchecked(int pos) const { return getUnchecked<std::int32_t>(pos); } template <> std::uint8_t Row::getUnchecked(int pos) const { return getUnchecked<std::int32_t>(pos); } template <> std::uint16_t Row::getUnchecked(int pos) const { return getUnchecked<std::int32_t>(pos); } template <> std::uint32_t Row::getUnchecked(int pos) const { return getUnchecked<std::int32_t>(pos); } template <> std::uint64_t Row::getUnchecked(int pos) const { return getUnchecked<std::int64_t>(pos); } // Linux: // std::size_t = unsigned long = std::uint64_t // Mac: // std::size_t = unsigned long != std::uint64_t #ifdef __APPLE__ template <> unsigned long Row::getUnchecked(int pos) const { return getUnchecked<unsigned long>(pos); } #endif template <> float Row::getUnchecked(int pos) const { return getUnchecked<double>(pos); } }
#include "sqlitewrapper/statement.h" #include <cstdint> #include <vector> #include "sqlitewrapper/binder.h" #include "sqlitewrapper/exceptions.h" #include "sqlitewrapper/sqlite3.h" namespace SqliteWrapper { struct Statement::Impl { sqlite3_stmt *stmt = nullptr; }; Statement::Statement(sqlite3_stmt *stmt) : impl(new Impl) { impl->stmt = stmt; } Statement::Statement(Statement &&other) : impl(new Impl) { std::swap(impl, other.impl); } Statement &Statement::operator=(Statement &&rhs) { std::swap(impl, rhs.impl); return *this; } Statement::~Statement() { sqlite3_finalize(impl->stmt); } Statement &Statement::bindNull(int pos) { checkResult(sqlite3_bind_null(impl->stmt, pos + 1)); return *this; } RowIterator Statement::begin() { return RowIterator(impl->stmt, false); } RowIterator Statement::end() { return RowIterator(impl->stmt, true); } void Statement::clearBindings() { checkResult(sqlite3_clear_bindings(impl->stmt)); } void Statement::reset() { checkResult(sqlite3_reset(impl->stmt)); } sqlite3_stmt *Statement::statementHandle() const { return impl->stmt; } RowIterator::RowIterator(sqlite3_stmt *stmt, bool done) : m_stmt(stmt), m_done(done), m_row(stmt) { //FIXME make it possible to invoke .begin() multiple times without moving if (!done) { // get first result ++(*this); } } bool RowIterator::operator==(const RowIterator &rhs) const { return (m_stmt == rhs.m_stmt) && (m_done == rhs.m_done); } bool RowIterator::operator!=(const RowIterator &rhs) const { return !(*this == rhs); } RowIterator &RowIterator::operator++() { int result = sqlite3_step(m_stmt); switch (result) { case SQLITE_ROW: m_done = false; break; case SQLITE_DONE: m_done = true; break; default: checkResult(result); } m_row.setColumns(sqlite3_column_count(m_stmt)); return *this; } Row &RowIterator::operator*() { return m_row; } Row *RowIterator::operator->() { return &m_row; } Row::Row(sqlite3_stmt *stmt) : m_stmt(stmt) { } bool Row::isNull(int pos) const { return sqlite3_column_type(m_stmt, pos) == SQLITE_NULL; } void Row::setColumns(int columns) { m_columns = columns; } void Row::checkPosRange(int pos) const { if (pos < 0 || pos >= m_columns) { throw Exception("Column out of range"); } } // BEGIN native types of SQLite template <> std::int32_t Row::getUnchecked(int pos) const { return sqlite3_column_int(m_stmt, pos); } template <> std::int64_t Row::getUnchecked(int pos) const { return sqlite3_column_int64(m_stmt, pos); } template <> double Row::getUnchecked(int pos) const { return sqlite3_column_double(m_stmt, pos); } template <> std::string Row::getUnchecked(int pos) const { return std::string(reinterpret_cast<const char*>(sqlite3_column_text(m_stmt, pos))); } template <> std::vector<unsigned char> Row::getUnchecked(int pos) const { int size = sqlite3_column_bytes(m_stmt, pos); if (size == 0) return std::vector<unsigned char>(); const unsigned char *data = reinterpret_cast<const unsigned char*>(sqlite3_column_blob(m_stmt, pos)); return std::vector<unsigned char>(data, data + size); } // END native types of SQLite template <> bool Row::getUnchecked(int pos) const { return getUnchecked<std::int32_t>(pos) != 0; } template <> std::int8_t Row::getUnchecked(int pos) const { return getUnchecked<std::int32_t>(pos); } template <> std::int16_t Row::getUnchecked(int pos) const { return getUnchecked<std::int32_t>(pos); } template <> std::uint8_t Row::getUnchecked(int pos) const { return getUnchecked<std::int32_t>(pos); } template <> std::uint16_t Row::getUnchecked(int pos) const { return getUnchecked<std::int32_t>(pos); } template <> std::uint32_t Row::getUnchecked(int pos) const { return getUnchecked<std::int32_t>(pos); } template <> std::uint64_t Row::getUnchecked(int pos) const { return getUnchecked<std::int64_t>(pos); } // Linux: // std::size_t = unsigned long = std::uint64_t // Mac: // std::size_t = unsigned long != std::uint64_t #ifdef __APPLE__ template <> unsigned long Row::getUnchecked(int pos) const { return getUnchecked<std::int32_t>(pos); } #endif template <> float Row::getUnchecked(int pos) const { return getUnchecked<double>(pos); } }
Fix unsigned long Row::getUnchecked
Fix unsigned long Row::getUnchecked
C++
bsd-3-clause
kullo/smartsqlite,kullo/smartsqlite,kullo/smartsqlite
dba3b9829bfd70da4e309490ea930c1b1505f106
src/leaf-node-box.cpp
src/leaf-node-box.cpp
// // leaf-node-box.cpp // gepetto-viewer // // Created by Justin Carpentier, Mathieu Geisert in November 2014. // Copyright (c) 2014 LAAS-CNRS. All rights reserved. // #include <gepetto/viewer/leaf-node-box.h> #include <stdio.h> namespace graphics { /* Declaration of private function members */ void LeafNodeBox::init () { /* Create sphere object */ box_ptr_ = new ::osg::Box(); /* Set ShapeDrawable */ shape_drawable_ptr_ = new ::osg::ShapeDrawable(box_ptr_); /* Create Geode for adding ShapeDrawable */ geode_ptr_ = new ::osg::Geode(); geode_ptr_->addDrawable(shape_drawable_ptr_); addProperty(Vector3Property::create("HalfLength", Vector3Property::Getter_t(boost::bind(&osg::Box::getHalfLengths, box_ptr_.get())), Vector3Property::Setter_t(boost::bind(&osg::Box::setHalfLengths, box_ptr_.get(), _1)))); /* Create PositionAttitudeTransform */ this->asQueue()->addChild(geode_ptr_); /* Allow transparency */ geode_ptr_->getOrCreateStateSet()->setMode(GL_BLEND, ::osg::StateAttribute::ON); } LeafNodeBox::LeafNodeBox (const std::string &name, const osgVector3& half_axis) : Node(name) { init(); setHalfAxis(half_axis); setColor(osgVector4(1.,1.,1.,1.)); } LeafNodeBox::LeafNodeBox (const std::string &name, const osgVector3& half_axis, const osgVector4 &color) : Node(name) { init(); setHalfAxis(half_axis); setColor(color); } LeafNodeBox::LeafNodeBox (const LeafNodeBox& other) : Node(other) { init(); setHalfAxis(other.getHalfAxis()); setColor(other.getColor()); } void LeafNodeBox::initWeakPtr (LeafNodeBoxWeakPtr other_weak_ptr ) { weak_ptr_ = other_weak_ptr; } /* End of declaration of private function members */ /* Declaration of protected function members */ LeafNodeBoxPtr_t LeafNodeBox::create (const std::string &name, const osgVector3 &half_axis) { LeafNodeBoxPtr_t shared_ptr(new LeafNodeBox(name, half_axis)); // Add reference to itself shared_ptr->initWeakPtr( shared_ptr ); return shared_ptr; } LeafNodeBoxPtr_t LeafNodeBox::create (const std::string &name, const osgVector3 &half_axis, const osgVector4 &color) { LeafNodeBoxPtr_t shared_ptr(new LeafNodeBox(name, half_axis, color)); // Add reference to itself shared_ptr->initWeakPtr( shared_ptr ); return shared_ptr; } LeafNodeBoxPtr_t LeafNodeBox::createCopy (LeafNodeBoxPtr_t other) { LeafNodeBoxPtr_t shared_ptr(new LeafNodeBox(*other)); // Add reference to itself shared_ptr->initWeakPtr( shared_ptr ); return shared_ptr; } /* End of declaration of protected function members */ /* Declaration of public function members */ LeafNodeBoxPtr_t LeafNodeBox::clone (void) const { return LeafNodeBox::createCopy(weak_ptr_.lock()); } LeafNodeBoxPtr_t LeafNodeBox::self (void) const { return weak_ptr_.lock(); } void LeafNodeBox::setHalfAxis (const osgVector3& half_axis) { box_ptr_->setHalfLengths(half_axis); } void LeafNodeBox::setColor (const osgVector4 &color) { shape_drawable_ptr_->setColor(color); } void LeafNodeBox::setTexture(const std::string& image_path) { osg::ref_ptr<osg::Texture2D> texture = new osg::Texture2D; texture->setDataVariance(osg::Object::DYNAMIC); osg::ref_ptr<osg::Image> image = osgDB::readImageFile(image_path); if (!image) { std::cerr << " couldn't find texture " << image_path << ", quiting." << std::endl; return; } texture->setImage(image); geode_ptr_->getStateSet()->setTextureAttributeAndModes(0,texture,osg::StateAttribute::ON); printf("ptr of %s is %p\n", getID().c_str(), (void *)geode_ptr_.get()); } LeafNodeBox::~LeafNodeBox() { /* Proper deletion of all tree scene */ geode_ptr_->removeDrawable(shape_drawable_ptr_); shape_drawable_ptr_ = NULL; this->asQueue()->removeChild(geode_ptr_); geode_ptr_ = NULL; weak_ptr_.reset(); } /* End of declaration of public function members */ } /* namespace graphics */
// // leaf-node-box.cpp // gepetto-viewer // // Created by Justin Carpentier, Mathieu Geisert in November 2014. // Copyright (c) 2014 LAAS-CNRS. All rights reserved. // #include <gepetto/viewer/leaf-node-box.h> #include <stdio.h> namespace graphics { /* Declaration of private function members */ void LeafNodeBox::init () { /* Create sphere object */ box_ptr_ = new ::osg::Box(); /* Set ShapeDrawable */ shape_drawable_ptr_ = new ::osg::ShapeDrawable(box_ptr_); /* Create Geode for adding ShapeDrawable */ geode_ptr_ = new ::osg::Geode(); geode_ptr_->addDrawable(shape_drawable_ptr_); addProperty(Vector3Property::create("HalfLength", Vector3Property::getterFromMemberFunction(box_ptr_.get(), &osg::Box::getHalfLengths), Vector3Property::setterFromMemberFunction(this, &LeafNodeBox::setHalfAxis))); /* Create PositionAttitudeTransform */ this->asQueue()->addChild(geode_ptr_); /* Allow transparency */ geode_ptr_->getOrCreateStateSet()->setMode(GL_BLEND, ::osg::StateAttribute::ON); } LeafNodeBox::LeafNodeBox (const std::string &name, const osgVector3& half_axis) : Node(name) { init(); setHalfAxis(half_axis); setColor(osgVector4(1.,1.,1.,1.)); } LeafNodeBox::LeafNodeBox (const std::string &name, const osgVector3& half_axis, const osgVector4 &color) : Node(name) { init(); setHalfAxis(half_axis); setColor(color); } LeafNodeBox::LeafNodeBox (const LeafNodeBox& other) : Node(other) { init(); setHalfAxis(other.getHalfAxis()); setColor(other.getColor()); } void LeafNodeBox::initWeakPtr (LeafNodeBoxWeakPtr other_weak_ptr ) { weak_ptr_ = other_weak_ptr; } /* End of declaration of private function members */ /* Declaration of protected function members */ LeafNodeBoxPtr_t LeafNodeBox::create (const std::string &name, const osgVector3 &half_axis) { LeafNodeBoxPtr_t shared_ptr(new LeafNodeBox(name, half_axis)); // Add reference to itself shared_ptr->initWeakPtr( shared_ptr ); return shared_ptr; } LeafNodeBoxPtr_t LeafNodeBox::create (const std::string &name, const osgVector3 &half_axis, const osgVector4 &color) { LeafNodeBoxPtr_t shared_ptr(new LeafNodeBox(name, half_axis, color)); // Add reference to itself shared_ptr->initWeakPtr( shared_ptr ); return shared_ptr; } LeafNodeBoxPtr_t LeafNodeBox::createCopy (LeafNodeBoxPtr_t other) { LeafNodeBoxPtr_t shared_ptr(new LeafNodeBox(*other)); // Add reference to itself shared_ptr->initWeakPtr( shared_ptr ); return shared_ptr; } /* End of declaration of protected function members */ /* Declaration of public function members */ LeafNodeBoxPtr_t LeafNodeBox::clone (void) const { return LeafNodeBox::createCopy(weak_ptr_.lock()); } LeafNodeBoxPtr_t LeafNodeBox::self (void) const { return weak_ptr_.lock(); } void LeafNodeBox::setHalfAxis (const osgVector3& half_axis) { box_ptr_->setHalfLengths(half_axis); shape_drawable_ptr_->dirtyDisplayList(); shape_drawable_ptr_->dirtyBound(); } void LeafNodeBox::setColor (const osgVector4 &color) { shape_drawable_ptr_->setColor(color); } void LeafNodeBox::setTexture(const std::string& image_path) { osg::ref_ptr<osg::Texture2D> texture = new osg::Texture2D; texture->setDataVariance(osg::Object::DYNAMIC); osg::ref_ptr<osg::Image> image = osgDB::readImageFile(image_path); if (!image) { std::cerr << " couldn't find texture " << image_path << ", quiting." << std::endl; return; } texture->setImage(image); geode_ptr_->getStateSet()->setTextureAttributeAndModes(0,texture,osg::StateAttribute::ON); printf("ptr of %s is %p\n", getID().c_str(), (void *)geode_ptr_.get()); } LeafNodeBox::~LeafNodeBox() { /* Proper deletion of all tree scene */ geode_ptr_->removeDrawable(shape_drawable_ptr_); shape_drawable_ptr_ = NULL; this->asQueue()->removeChild(geode_ptr_); geode_ptr_ = NULL; weak_ptr_.reset(); } /* End of declaration of public function members */ } /* namespace graphics */
Fix LeafNodeBox box half lengths property
Fix LeafNodeBox box half lengths property
C++
bsd-3-clause
olivier-stasse/gepetto-viewer
62d52de8e7c0f61150579becc59a4dcec60e2caa
src/tcp_stock.cxx
src/tcp_stock.cxx
/* * TCP client connection pooling. * * author: Max Kellermann <[email protected]> */ #include "tcp_stock.hxx" #include "stock/MapStock.hxx" #include "stock/Stock.hxx" #include "stock/Class.hxx" #include "stock/Item.hxx" #include "async.hxx" #include "address_list.hxx" #include "gerrno.h" #include "pool.hxx" #include "event/Event.hxx" #include "event/Callback.hxx" #include "event/Duration.hxx" #include "net/ConnectSocket.hxx" #include "net/SocketAddress.hxx" #include "net/SocketDescriptor.hxx" #include <daemon/log.h> #include <socket/address.h> #include <assert.h> #include <errno.h> #include <string.h> #include <unistd.h> #include <sys/un.h> #include <sys/socket.h> struct TcpStockRequest { bool ip_transparent; SocketAddress bind_address, address; unsigned timeout; }; struct TcpStockConnection final : HeapStockItem, ConnectSocketHandler { struct async_operation create_operation; struct async_operation_ref client_socket; int fd = -1; const int domain; Event event; TcpStockConnection(CreateStockItem c, int _domain, struct async_operation_ref &async_ref) :HeapStockItem(c), domain(_domain) { create_operation.Init2<TcpStockConnection, &TcpStockConnection::create_operation>(); async_ref.Set(create_operation); client_socket.Clear(); } ~TcpStockConnection() override; void Abort() { assert(client_socket.IsDefined()); client_socket.Abort(); InvokeCreateAborted(); } void EventCallback(int fd, short events); /* virtual methods from class ConnectSocketHandler */ void OnSocketConnectSuccess(SocketDescriptor &&fd) override; void OnSocketConnectError(GError *error) override; /* virtual methods from class StockItem */ bool Borrow(gcc_unused void *ctx) override { event.Delete(); return true; } bool Release(gcc_unused void *ctx) override { event.Add(EventDuration<60>::value); return true; } }; /* * libevent callback * */ inline void TcpStockConnection::EventCallback(int _fd, short events) { assert(_fd == fd); if ((events & EV_TIMEOUT) == 0) { char buffer; ssize_t nbytes; assert((events & EV_READ) != 0); nbytes = recv(fd, &buffer, sizeof(buffer), MSG_DONTWAIT); if (nbytes < 0) daemon_log(2, "error on idle TCP connection: %s\n", strerror(errno)); else if (nbytes > 0) daemon_log(2, "unexpected data in idle TCP connection\n"); } InvokeIdleDisconnect(); pool_commit(); } /* * client_socket callback * */ void TcpStockConnection::OnSocketConnectSuccess(SocketDescriptor &&new_fd) { client_socket.Clear(); create_operation.Finished(); fd = new_fd.Steal(); event.Set(fd, EV_READ|EV_TIMEOUT, MakeEventCallback(TcpStockConnection, EventCallback), this); InvokeCreateSuccess(); } void TcpStockConnection::OnSocketConnectError(GError *error) { client_socket.Clear(); create_operation.Finished(); g_prefix_error(&error, "failed to connect to '%s': ", GetStockName()); InvokeCreateError(error); } /* * stock class * */ static void tcp_stock_create(gcc_unused void *ctx, CreateStockItem c, void *info, struct pool &caller_pool, struct async_operation_ref &async_ref) { TcpStockRequest *request = (TcpStockRequest *)info; auto *connection = new TcpStockConnection(c, request->address.GetFamily(), async_ref); client_socket_new(caller_pool, connection->domain, SOCK_STREAM, 0, request->ip_transparent, request->bind_address, request->address, request->timeout, *connection, connection->client_socket); } TcpStockConnection::~TcpStockConnection() { if (client_socket.IsDefined()) client_socket.Abort(); else if (fd >= 0) { event.Delete(); close(fd); } } static constexpr StockClass tcp_stock_class = { .create = tcp_stock_create, }; /* * interface * */ StockMap * tcp_stock_new(EventLoop &event_loop, unsigned limit) { return new StockMap(event_loop, tcp_stock_class, nullptr, limit, 16); } void tcp_stock_get(StockMap *tcp_stock, struct pool *pool, const char *name, bool ip_transparent, SocketAddress bind_address, SocketAddress address, unsigned timeout, StockGetHandler &handler, struct async_operation_ref &async_ref) { assert(!address.IsNull()); auto request = NewFromPool<TcpStockRequest>(*pool); request->ip_transparent = ip_transparent; request->bind_address = bind_address; request->address = address; request->timeout = timeout; if (name == nullptr) { char buffer[1024]; if (!socket_address_to_string(buffer, sizeof(buffer), address.GetAddress(), address.GetSize())) buffer[0] = 0; if (!bind_address.IsNull()) { char bind_buffer[1024]; if (!socket_address_to_string(bind_buffer, sizeof(bind_buffer), bind_address.GetAddress(), bind_address.GetSize())) bind_buffer[0] = 0; name = p_strcat(pool, bind_buffer, ">", buffer, nullptr); } else name = p_strdup(pool, buffer); } tcp_stock->Get(*pool, name, request, handler, async_ref); } int tcp_stock_item_get(const StockItem &item) { auto *connection = (const TcpStockConnection *)&item; return connection->fd; } int tcp_stock_item_get_domain(const StockItem &item) { auto *connection = (const TcpStockConnection *)&item; assert(connection->fd >= 0); return connection->domain; }
/* * TCP client connection pooling. * * author: Max Kellermann <[email protected]> */ #include "tcp_stock.hxx" #include "stock/MapStock.hxx" #include "stock/Stock.hxx" #include "stock/Class.hxx" #include "stock/Item.hxx" #include "async.hxx" #include "address_list.hxx" #include "gerrno.h" #include "pool.hxx" #include "event/SocketEvent.hxx" #include "event/Duration.hxx" #include "net/ConnectSocket.hxx" #include "net/SocketAddress.hxx" #include "net/SocketDescriptor.hxx" #include <daemon/log.h> #include <socket/address.h> #include <assert.h> #include <errno.h> #include <string.h> #include <unistd.h> #include <sys/un.h> #include <sys/socket.h> struct TcpStockRequest { bool ip_transparent; SocketAddress bind_address, address; unsigned timeout; }; struct TcpStockConnection final : HeapStockItem, ConnectSocketHandler { struct async_operation create_operation; struct async_operation_ref client_socket; int fd = -1; const int domain; SocketEvent event; TcpStockConnection(CreateStockItem c, int _domain, struct async_operation_ref &async_ref) :HeapStockItem(c), domain(_domain), event(c.stock.GetEventLoop(), BIND_THIS_METHOD(EventCallback)) { create_operation.Init2<TcpStockConnection, &TcpStockConnection::create_operation>(); async_ref.Set(create_operation); client_socket.Clear(); } ~TcpStockConnection() override; void Abort() { assert(client_socket.IsDefined()); client_socket.Abort(); InvokeCreateAborted(); } void EventCallback(short events); /* virtual methods from class ConnectSocketHandler */ void OnSocketConnectSuccess(SocketDescriptor &&fd) override; void OnSocketConnectError(GError *error) override; /* virtual methods from class StockItem */ bool Borrow(gcc_unused void *ctx) override { event.Delete(); return true; } bool Release(gcc_unused void *ctx) override { event.Add(EventDuration<60>::value); return true; } }; /* * libevent callback * */ inline void TcpStockConnection::EventCallback(short events) { if ((events & EV_TIMEOUT) == 0) { char buffer; ssize_t nbytes; assert((events & EV_READ) != 0); nbytes = recv(fd, &buffer, sizeof(buffer), MSG_DONTWAIT); if (nbytes < 0) daemon_log(2, "error on idle TCP connection: %s\n", strerror(errno)); else if (nbytes > 0) daemon_log(2, "unexpected data in idle TCP connection\n"); } InvokeIdleDisconnect(); pool_commit(); } /* * client_socket callback * */ void TcpStockConnection::OnSocketConnectSuccess(SocketDescriptor &&new_fd) { client_socket.Clear(); create_operation.Finished(); fd = new_fd.Steal(); event.Set(fd, EV_READ|EV_TIMEOUT); InvokeCreateSuccess(); } void TcpStockConnection::OnSocketConnectError(GError *error) { client_socket.Clear(); create_operation.Finished(); g_prefix_error(&error, "failed to connect to '%s': ", GetStockName()); InvokeCreateError(error); } /* * stock class * */ static void tcp_stock_create(gcc_unused void *ctx, CreateStockItem c, void *info, struct pool &caller_pool, struct async_operation_ref &async_ref) { TcpStockRequest *request = (TcpStockRequest *)info; auto *connection = new TcpStockConnection(c, request->address.GetFamily(), async_ref); client_socket_new(caller_pool, connection->domain, SOCK_STREAM, 0, request->ip_transparent, request->bind_address, request->address, request->timeout, *connection, connection->client_socket); } TcpStockConnection::~TcpStockConnection() { if (client_socket.IsDefined()) client_socket.Abort(); else if (fd >= 0) { event.Delete(); close(fd); } } static constexpr StockClass tcp_stock_class = { .create = tcp_stock_create, }; /* * interface * */ StockMap * tcp_stock_new(EventLoop &event_loop, unsigned limit) { return new StockMap(event_loop, tcp_stock_class, nullptr, limit, 16); } void tcp_stock_get(StockMap *tcp_stock, struct pool *pool, const char *name, bool ip_transparent, SocketAddress bind_address, SocketAddress address, unsigned timeout, StockGetHandler &handler, struct async_operation_ref &async_ref) { assert(!address.IsNull()); auto request = NewFromPool<TcpStockRequest>(*pool); request->ip_transparent = ip_transparent; request->bind_address = bind_address; request->address = address; request->timeout = timeout; if (name == nullptr) { char buffer[1024]; if (!socket_address_to_string(buffer, sizeof(buffer), address.GetAddress(), address.GetSize())) buffer[0] = 0; if (!bind_address.IsNull()) { char bind_buffer[1024]; if (!socket_address_to_string(bind_buffer, sizeof(bind_buffer), bind_address.GetAddress(), bind_address.GetSize())) bind_buffer[0] = 0; name = p_strcat(pool, bind_buffer, ">", buffer, nullptr); } else name = p_strdup(pool, buffer); } tcp_stock->Get(*pool, name, request, handler, async_ref); } int tcp_stock_item_get(const StockItem &item) { auto *connection = (const TcpStockConnection *)&item; return connection->fd; } int tcp_stock_item_get_domain(const StockItem &item) { auto *connection = (const TcpStockConnection *)&item; assert(connection->fd >= 0); return connection->domain; }
use class SocketEvent
tcp_stock: use class SocketEvent
C++
bsd-2-clause
CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy
c65c26d6a9fe2874cb0dd641550c78fa3f49993d
src/tests/cli.cpp
src/tests/cli.cpp
#include <iostream> #include <iostream> #include <memory> #include "common/definitions.h" #include "common/options.h" #include "common/cli_wrapper.h" #include "common/cli_helper.h" using namespace marian; using namespace marian::cli; enum color { red, green, blue }; template <typename S> S &operator<<(S &s, const color &v) { if(v == color::red) s << "red"; else if(v == color::green) s << "green"; else if(v == color::blue) s << "blue"; return s; } template <typename S> S &operator>>(S &s, color &r) { std::string v; s >> v; if(v == "red") r = color::red; else if(v == "green") r = color::blue; else if(v == "blue") r = color::blue; } int main(int argc, char** argv) { auto options = New<Options>(); { auto w = New<CLIWrapper>(options); w->add<int>("-i,--int", "help message")->implicit_val("555")->default_val("123"); w->add<std::string>("-s,--str", "help message"); w->add<std::vector<float>>("-v,--vec", "help message")->expected(-2); w->switchGroup("My group"); w->add<std::vector<std::string>>("--defvec,-d", "help message")->default_val("foo"); w->add<bool>("-b,--bool", "boolean option"); w->add<bool>("-x,--xbool", "false boolean option", true); w->add<std::string>("--a-very-long-option-name-for-testing-purposes", "A very long text a very long text a very long text a very long text a very long text a very long text"); w->switchGroup(); w->add<std::string>("-f,--file", "help message")->check(validators::file_exists); //w.add<color>("-e,--enum", "help message for enum"); w->parse(argc, argv); } options->get<int>("int"); options->get<std::string>("str"); options->get<std::vector<float>>("vec"); options->get<std::vector<std::string>>("defvec"); options->get<bool>("bool"); //w.get<std::string>("long"); options->get<std::string>("file"); //w.get<color>("enum"); YAML::Emitter emit; OutputYaml(options->getYaml(), emit); std::cout << emit.c_str() << std::endl; std::cout << "===" << std::endl; std::cout << "vec/str.hasAndNotEmpty? " << options->hasAndNotEmpty("vec") << " " << options->hasAndNotEmpty("str") << std::endl; std::cout << "vec/str.has? " << options->has("vec") << " " << options->has("str") << std::endl; return 0; }
#include <iostream> #include <iostream> #include <memory> #include "common/definitions.h" #include "common/options.h" #include "common/cli_wrapper.h" #include "common/cli_helper.h" using namespace marian; using namespace marian::cli; enum color { red, green, blue }; template <typename S> S &operator<<(S &s, const color &v) { if(v == color::red) s << "red"; else if(v == color::green) s << "green"; else if(v == color::blue) s << "blue"; return s; } template <typename S> S &operator>>(S &s, color &r) { std::string v; s >> v; if(v == "red") r = color::red; else if(v == "green") r = color::blue; else if(v == "blue") r = color::blue; } int main(int argc, char** argv) { auto options = New<Options>(); { auto w = New<CLIWrapper>(options); w->add<int>("-i,--int", "help message")->implicit_val("555")->default_val("123"); w->add<std::string>("-s,--str", "help message"); w->add<std::vector<float>>("-v,--vec", "help message")->expected(-2); w->switchGroup("My group"); w->add<std::vector<std::string>>("--defvec,-d", "help message")->default_val("foo"); w->add<bool>("-b,--bool", "boolean option"); w->add<bool>("-x,--xbool", "false boolean option", true); w->add<std::string>("--a-very-long-option-name-for-testing-purposes", "A very long text a very long text a very long text a very long text a very long text a very long text"); w->switchGroup(); //w->add<std::string>("-f,--file", "help message")->check(validators::file_exists); //w.add<color>("-e,--enum", "help message for enum"); w->parse(argc, argv); } options->get<int>("int"); options->get<std::string>("str"); options->get<std::vector<float>>("vec"); options->get<std::vector<std::string>>("defvec"); options->get<bool>("bool"); //w.get<std::string>("long"); options->get<std::string>("file"); //w.get<color>("enum"); YAML::Emitter emit; OutputYaml(options->getYaml(), emit); std::cout << emit.c_str() << std::endl; std::cout << "===" << std::endl; std::cout << "vec/str.hasAndNotEmpty? " << options->hasAndNotEmpty("vec") << " " << options->hasAndNotEmpty("str") << std::endl; std::cout << "vec/str.has? " << options->has("vec") << " " << options->has("str") << std::endl; return 0; }
Fix test
Fix test
C++
mit
emjotde/amunmt,emjotde/amunmt,emjotde/amunn,emjotde/amunmt,marian-nmt/marian-train,emjotde/amunn,marian-nmt/marian-train,marian-nmt/marian-train,marian-nmt/marian-train,emjotde/amunmt,marian-nmt/marian-train,emjotde/Marian,emjotde/amunn,emjotde/Marian,emjotde/amunn
606aed0e2fd084da050676b4b416e87d920ff78c
src/lib/IsingGrid.cpp
src/lib/IsingGrid.cpp
// // IsingGrid.cpp // jdemon // // Created by Mark Larus on 3/11/13. // Copyright (c) 2013 Kenyon College. All rights reserved. // #include "IsingGrid.h" #include <boost/iterator/filter_iterator.hpp> using namespace Ising; using namespace detail; const Kind Ising::detail::even = false; const Kind Ising::detail::odd = true; int Grid::Coordinate::boundsCheck(int x) { if (x < 0) { return dimension + x; } if (x >= dimension) { return x-dimension; } return x; } void Cell::setValue(const char &c) { if (c < 0 || c > 1) { throw InvalidCellValue(); } value = c; } Grid::Coordinate::CNeighbors Grid::Coordinate::getNeighbors(){ Coordinate::CNeighbors neighbors = { { Coordinate(x,y+1,dimension), Coordinate(x,y-1,dimension), Coordinate(x+1,y,dimension), Coordinate(x-1,y,dimension) }}; return neighbors; } Grid::Grid(int dim) : dimension(dim), cells(new Ising::Cell[size()]),\ evens(*this,even), odds(*this,odd) { if (dim % 2 || dim < 4) { throw InvalidGridSize(); } // CNeighbors give the neighbors to a coordinate in coordinate space // The function getGridIndex translate coordinate space to memory space // Cell::Neighbors should give the neighbors to a cell in memory space // This procedure boostraps the memory space using coordinate space. for (int k = 0; k!=size(); ++k) { int x = k % dimension; int y = k / dimension; Coordinate currentCoord(x,y,dimension); Cell *cell = cells.get() + currentCoord.getGridIndex(); Coordinate::CNeighbors neighbors = currentCoord.getNeighbors(); Cell::Neighbors::iterator neighborReference = cell->neighbors.begin(); for (Coordinate::CNeighbors::iterator it = neighbors.begin(); it!=neighbors.end(); ++it) { Cell *neighbor = cells.get() + it->getGridIndex(); *neighborReference = neighbor; ++neighborReference; } } } Grid::subset::iterator Grid::subset::begin() const { CheckerboardCellOffset offsetPredicate(base,kind,dimension); return iterator(offsetPredicate,Grid::iterator(base),Grid::iterator(last)); } Grid::subset::iterator Grid::subset::end() const { CheckerboardCellOffset offsetPredicate(base,kind,dimension); return Grid::subset::iterator(offsetPredicate,Grid::iterator(last),Grid::iterator(last)); } template <class T> bool CheckerboardPtrOffset<T>::operator()(T *n) const { if (n<base) { throw std::runtime_error("CheckerboardPtrOffset only valid for " "iterators greater than base."); } size_t offset = n-base; bool rowEven = (offset / dimension) % 2; bool columnEven = (offset % dimension) % 2; bool color = (rowEven + columnEven) % 2; return kind ? color : !color; } long Cell::getEnergy() { long e = 0; for (Neighbors::iterator it = neighbors.begin(); it!=neighbors.end(); ++it) { e += (*it)->getValue(); } return e; }
// // IsingGrid.cpp // jdemon // // Created by Mark Larus on 3/11/13. // Copyright (c) 2013 Kenyon College. All rights reserved. // #include "IsingGrid.h" #include <boost/iterator/filter_iterator.hpp> using namespace Ising; using namespace detail; const Kind Ising::detail::even = false; const Kind Ising::detail::odd = true; int Grid::Coordinate::boundsCheck(int x) { if (x < 0) { return dimension + x; } if (x >= dimension) { return x-dimension; } return x; } void Cell::setValue(const char &c) { if (c < 0 || c > 1) { throw InvalidCellValue(); } value = c; } Grid::Coordinate::CNeighbors Grid::Coordinate::getNeighbors(){ Coordinate::CNeighbors neighbors = { { Coordinate(x,y+1,dimension), Coordinate(x,y-1,dimension), Coordinate(x+1,y,dimension), Coordinate(x-1,y,dimension) }}; return neighbors; } Grid::Grid(int dim) : dimension(dim), cells(new Ising::Cell[size()]),\ evens(*this,even), odds(*this,odd) { if (dim % 2 || dim < 4) { throw InvalidGridSize(); } // CNeighbors give the neighbors to a coordinate in coordinate space // The function getGridIndex translate coordinate space to memory space // Cell::Neighbors should give the neighbors to a cell in memory space // This procedure boostraps the memory space using coordinate space. for (int k = 0; k!=size(); ++k) { int x = k % dimension; int y = k / dimension; Coordinate currentCoord(x,y,dimension); Cell *cell = cells.get() + currentCoord.getGridIndex(); Coordinate::CNeighbors neighbors = currentCoord.getNeighbors(); Cell::Neighbors::iterator neighborReference = cell->neighbors.begin(); for (Coordinate::CNeighbors::iterator it = neighbors.begin(); it!=neighbors.end(); ++it) { Cell *neighbor = cells.get() + it->getGridIndex(); *neighborReference = neighbor; ++neighborReference; } } } Grid::subset::iterator Grid::subset::begin() const { CheckerboardCellOffset offsetPredicate(base,kind,dimension); return iterator(offsetPredicate,Grid::iterator(base),Grid::iterator(last)); } Grid::subset::iterator Grid::subset::end() const { CheckerboardCellOffset offsetPredicate(base,kind,dimension); return Grid::subset::iterator(offsetPredicate,Grid::iterator(last),Grid::iterator(last)); } template <class T> bool CheckerboardPtrOffset<T>::operator()(T *n) const { if (n<base) { throw std::runtime_error("CheckerboardPtrOffset only valid for " "iterators greater than base."); } size_t offset = n-base; bool rowEven = (offset / dimension) % 2; bool columnEven = (offset % dimension) % 2; bool color = (rowEven + columnEven) % 2; return kind ? color : !color; } long Cell::getEnergy() { long e = 0; for (Neighbors::iterator it = neighbors.begin(); it!=neighbors.end(); ++it) { e += (*it)->getValue()==getValue() ? 0 : 1; } return e; }
Implement the ising energy correctly.
Implement the ising energy correctly.
C++
mit
marblar/demon,marblar/demon,marblar/demon,marblar/demon
6d11129342d4b4971a6965d70f2bc1d4c614a5e9
src/ttrss_api.cpp
src/ttrss_api.cpp
#include <json.h> #include <remote_api.h> #include <ttrss_api.h> #include <cstring> #include <algorithm> #include <markreadthread.h> namespace newsbeuter { ttrss_api::ttrss_api(configcontainer * c) : remote_api(c) { single = (cfg->get_configvalue("ttrss-mode") == "single"); auth_info = utils::strprintf("%s:%s", cfg->get_configvalue("ttrss-login").c_str(), cfg->get_configvalue("ttrss-password").c_str()); auth_info_ptr = auth_info.c_str(); sid = ""; } ttrss_api::~ttrss_api() { } bool ttrss_api::authenticate() { if (auth_lock.trylock()) { sid = retrieve_sid(); auth_lock.unlock(); } else { // wait for other thread to finish and return its result: auth_lock.lock(); auth_lock.unlock(); } return sid != ""; } std::string ttrss_api::retrieve_sid() { std::map<std::string, std::string> args; args["user"] = single ? "admin" : cfg->get_configvalue("ttrss-login"); args["password"] = cfg->get_configvalue("ttrss-password"); struct json_object * content = run_op("login", args); if (content == NULL) return ""; std::string sid; struct json_object * session_id = json_object_object_get(content, "session_id"); sid = json_object_get_string(session_id); json_object_put(content); LOG(LOG_DEBUG, "ttrss_api::retrieve_sid: sid = '%s'", sid.c_str()); return sid; } struct json_object * ttrss_api::run_op(const std::string& op, const std::map<std::string, std::string >& args, bool try_login) { std::string url = utils::strprintf("%s/api/", cfg->get_configvalue("ttrss-url").c_str()); std::string req_data = "{\"op\":\"" + op + "\",\"sid\":\"" + sid + "\""; for (std::map<std::string, std::string>::const_iterator it = args.begin(); it != args.end(); it++) { req_data += ",\"" + it->first + "\":\"" + it->second + "\""; } req_data += "}"; std::string result = utils::retrieve_url(url, cfg, auth_info_ptr, &req_data); LOG(LOG_DEBUG, "ttrss_api::run_op(%s,...): post=%s reply = %s", op.c_str(), req_data.c_str(), result.c_str()); struct json_object * reply = json_tokener_parse(result.c_str()); if (is_error(reply)) { LOG(LOG_ERROR, "ttrss_api::run_op: reply failed to parse: %s", result.c_str()); return NULL; } struct json_object * status = json_object_object_get(reply, "status"); if (is_error(status)) { LOG(LOG_ERROR, "ttrss_api::run_op: no status code"); return NULL; } struct json_object * content = json_object_object_get(reply, "content"); if (is_error(content)) { LOG(LOG_ERROR, "ttrss_api::run_op: no content part in answer from server"); return NULL; } if (json_object_get_int(status) != 0) { struct json_object * error = json_object_object_get(content, "error"); if ((strcmp(json_object_get_string(error), "NOT_LOGGED_IN") == 0) && try_login) { json_object_put(reply); if (authenticate()) return run_op(op, args, false); else return NULL; } else { json_object_put(reply); return NULL; } } // free the parent object, without freeing content as well: json_object_get(content); json_object_put(reply); return content; } std::vector<tagged_feedurl> ttrss_api::get_subscribed_urls() { std::string cat_url = utils::strprintf("%s/api/"); std::string req_data = "{\"op\":\"getCategories\",\"sid\":\"" + sid + "\"}"; std::string result = utils::retrieve_url(cat_url, cfg, auth_info_ptr, &req_data); LOG(LOG_DEBUG, "ttrss_api::get_subscribed_urls: reply = %s", result.c_str()); std::vector<tagged_feedurl> feeds; struct json_object * content = run_op("getCategories", std::map<std::string, std::string>()); if (!content) return feeds; if (json_object_get_type(content) != json_type_array) return feeds; struct array_list * categories = json_object_get_array(content); int catsize = array_list_length(categories); // first fetch feeds within no category fetch_feeds_per_category(NULL, feeds); // then fetch the feeds of all categories for (int i=0;i<catsize;i++) { struct json_object * cat = (struct json_object *)array_list_get_idx(categories, i); fetch_feeds_per_category(cat, feeds); } json_object_put(content); return feeds; } void ttrss_api::configure_handle(CURL * /*handle*/) { // nothing required } bool ttrss_api::mark_all_read(const std::string& feed_url) { std::map<std::string, std::string> args; args["feed_id"] = url_to_id(feed_url); struct json_object * content = run_op("catchupFeed", args); if(!content) return false; json_object_put(content); return true; } bool ttrss_api::mark_article_read(const std::string& guid, bool read) { // Do this in a thread, as we don't care about the result enough to wait for // it. thread * mrt = new markreadthread( this, guid, read ); mrt->start(); return true; } bool ttrss_api::update_article_flags(const std::string& oldflags, const std::string& newflags, const std::string& guid) { std::string star_flag = cfg->get_configvalue("ttrss-flag-star"); std::string publish_flag = cfg->get_configvalue("ttrss-flag-publish"); bool success = true; if (star_flag.length() > 0) { if (strchr(oldflags.c_str(), star_flag[0])==NULL && strchr(newflags.c_str(), star_flag[0])!=NULL) { success = star_article(guid, true); } else if (strchr(oldflags.c_str(), star_flag[0])!=NULL && strchr(newflags.c_str(), star_flag[0])==NULL) { success = star_article(guid, false); } } if (publish_flag.length() > 0) { if (strchr(oldflags.c_str(), publish_flag[0])==NULL && strchr(newflags.c_str(), publish_flag[0])!=NULL) { success = publish_article(guid, true); } else if (strchr(oldflags.c_str(), publish_flag[0])!=NULL && strchr(newflags.c_str(), publish_flag[0])==NULL) { success = publish_article(guid, false); } } return success; } static bool sort_by_pubdate(const rsspp::item& a, const rsspp::item& b) { return a.pubDate_ts > b.pubDate_ts; } rsspp::feed ttrss_api::fetch_feed(const std::string& id) { rsspp::feed f; f.rss_version = rsspp::TTRSS_JSON; std::map<std::string, std::string> args; args["feed_id"] = id; args["show_content"] = "1"; struct json_object * content = run_op("getHeadlines", args); if (!content) return f; if (json_object_get_type(content) != json_type_array) { LOG(LOG_ERROR, "ttrss_api::fetch_feed: content is not an array"); return f; } struct array_list * items = json_object_get_array(content); int items_size = array_list_length(items); LOG(LOG_DEBUG, "ttrss_api::fetch_feed: %d items", items_size); for (int i=0;i<items_size;i++) { struct json_object * item_obj = (struct json_object *)array_list_get_idx(items, i); int id = json_object_get_int(json_object_object_get(item_obj, "id")); const char * title = json_object_get_string(json_object_object_get(item_obj, "title")); const char * link = json_object_get_string(json_object_object_get(item_obj, "link")); const char * content = json_object_get_string(json_object_object_get(item_obj, "content")); time_t updated = (time_t)json_object_get_int(json_object_object_get(item_obj, "updated")); bool unread = json_object_get_boolean(json_object_object_get(item_obj, "unread")); rsspp::item item; if (title) item.title = title; if (link) item.link = link; if (content) item.content_encoded = content; item.guid = utils::strprintf("%d", id); if (unread) { item.labels.push_back("ttrss:unread"); } else { item.labels.push_back("ttrss:read"); } char rfc822_date[128]; strftime(rfc822_date, sizeof(rfc822_date), "%a, %d %b %Y %H:%M:%S %z", gmtime(&updated)); item.pubDate = rfc822_date; item.pubDate_ts = updated; f.items.push_back(item); } std::sort(f.items.begin(), f.items.end(), sort_by_pubdate); json_object_put(content); return f; } void ttrss_api::fetch_feeds_per_category(struct json_object * cat, std::vector<tagged_feedurl>& feeds) { const char * cat_name = NULL; struct json_object * cat_title_obj = NULL; int cat_id; if (cat) { struct json_object * cat_id_obj = json_object_object_get(cat, "id"); cat_id = json_object_get_int(cat_id_obj); cat_title_obj = json_object_object_get(cat, "title"); cat_name = json_object_get_string(cat_title_obj); LOG(LOG_DEBUG, "ttrss_api::fetch_feeds_per_category: id = %d title = %s", cat_id, cat_name); } else { // As uncategorized is a category itself (id = 0) and the default value // for a getFeeds is id = 0, the feeds in uncategorized will appear twice return; } std::map<std::string, std::string> args; if (cat) args["cat_id"] = utils::to_s(cat_id); struct json_object * feed_list_obj = run_op("getFeeds", args); if (!feed_list_obj) return; struct array_list * feed_list = json_object_get_array(feed_list_obj); int feed_list_size = array_list_length(feed_list); for (int j=0;j<feed_list_size;j++) { struct json_object * feed = (struct json_object *)array_list_get_idx(feed_list, j); int feed_id = json_object_get_int(json_object_object_get(feed, "id")); const char * feed_title = json_object_get_string(json_object_object_get(feed, "title")); const char * feed_url = json_object_get_string(json_object_object_get(feed, "feed_url")); std::vector<std::string> tags; tags.push_back(std::string("~") + feed_title); if (cat_name) { tags.push_back(cat_name); } feeds.push_back(tagged_feedurl(utils::strprintf("%s#%d", feed_url, feed_id), tags)); // TODO: cache feed_id -> feed_url (or feed_url -> feed_id ?) } json_object_put(feed_list_obj); } bool ttrss_api::star_article(const std::string& guid, bool star) { return update_article(guid, 0, star ? 1 : 0); } bool ttrss_api::publish_article(const std::string& guid, bool publish) { return update_article(guid, 1, publish ? 1 : 0); } bool ttrss_api::update_article(const std::string& guid, int field, int mode) { std::map<std::string, std::string> args; args["article_ids"] = guid; args["field"] = utils::to_s(field); args["mode"] = utils::to_s(mode); struct json_object * content = run_op("updateArticle", args); if (!content) return false; json_object_put(content); return true; } std::string ttrss_api::url_to_id(const std::string& url) { const char * uri = url.c_str(); const char * pound = strrchr(uri, '#'); if (!pound) return ""; return std::string(pound+1); } }
#include <json.h> #include <remote_api.h> #include <ttrss_api.h> #include <cstring> #include <algorithm> #include <markreadthread.h> namespace newsbeuter { ttrss_api::ttrss_api(configcontainer * c) : remote_api(c) { single = (cfg->get_configvalue("ttrss-mode") == "single"); auth_info = utils::strprintf("%s:%s", cfg->get_configvalue("ttrss-login").c_str(), cfg->get_configvalue("ttrss-password").c_str()); auth_info_ptr = auth_info.c_str(); sid = ""; } ttrss_api::~ttrss_api() { } bool ttrss_api::authenticate() { if (auth_lock.trylock()) { sid = retrieve_sid(); auth_lock.unlock(); } else { // wait for other thread to finish and return its result: auth_lock.lock(); auth_lock.unlock(); } return sid != ""; } std::string ttrss_api::retrieve_sid() { std::map<std::string, std::string> args; args["user"] = single ? "admin" : cfg->get_configvalue("ttrss-login"); args["password"] = cfg->get_configvalue("ttrss-password"); struct json_object * content = run_op("login", args); if (content == NULL) return ""; std::string sid; struct json_object * session_id = json_object_object_get(content, "session_id"); sid = json_object_get_string(session_id); json_object_put(content); LOG(LOG_DEBUG, "ttrss_api::retrieve_sid: sid = '%s'", sid.c_str()); return sid; } struct json_object * ttrss_api::run_op(const std::string& op, const std::map<std::string, std::string >& args, bool try_login) { std::string url = utils::strprintf("%s/api/", cfg->get_configvalue("ttrss-url").c_str()); std::string req_data = "{\"op\":\"" + op + "\",\"sid\":\"" + sid + "\""; for (std::map<std::string, std::string>::const_iterator it = args.begin(); it != args.end(); it++) { req_data += ",\"" + it->first + "\":\"" + it->second + "\""; } req_data += "}"; std::string result = utils::retrieve_url(url, cfg, auth_info_ptr, &req_data); LOG(LOG_DEBUG, "ttrss_api::run_op(%s,...): post=%s reply = %s", op.c_str(), req_data.c_str(), result.c_str()); struct json_object * reply = json_tokener_parse(result.c_str()); if (is_error(reply)) { LOG(LOG_ERROR, "ttrss_api::run_op: reply failed to parse: %s", result.c_str()); return NULL; } struct json_object * status = json_object_object_get(reply, "status"); if (is_error(status)) { LOG(LOG_ERROR, "ttrss_api::run_op: no status code"); return NULL; } struct json_object * content = json_object_object_get(reply, "content"); if (is_error(content)) { LOG(LOG_ERROR, "ttrss_api::run_op: no content part in answer from server"); return NULL; } if (json_object_get_int(status) != 0) { struct json_object * error = json_object_object_get(content, "error"); if ((strcmp(json_object_get_string(error), "NOT_LOGGED_IN") == 0) && try_login) { json_object_put(reply); if (authenticate()) return run_op(op, args, false); else return NULL; } else { json_object_put(reply); return NULL; } } // free the parent object, without freeing content as well: json_object_get(content); json_object_put(reply); return content; } std::vector<tagged_feedurl> ttrss_api::get_subscribed_urls() { std::string cat_url = utils::strprintf("%s/api/"); std::string req_data = "{\"op\":\"getCategories\",\"sid\":\"" + sid + "\"}"; std::string result = utils::retrieve_url(cat_url, cfg, auth_info_ptr, &req_data); LOG(LOG_DEBUG, "ttrss_api::get_subscribed_urls: reply = %s", result.c_str()); std::vector<tagged_feedurl> feeds; struct json_object * content = run_op("getCategories", std::map<std::string, std::string>()); if (!content) return feeds; if (json_object_get_type(content) != json_type_array) return feeds; struct array_list * categories = json_object_get_array(content); int catsize = array_list_length(categories); // first fetch feeds within no category fetch_feeds_per_category(NULL, feeds); // then fetch the feeds of all categories for (int i=0;i<catsize;i++) { struct json_object * cat = (struct json_object *)array_list_get_idx(categories, i); fetch_feeds_per_category(cat, feeds); } json_object_put(content); return feeds; } void ttrss_api::configure_handle(CURL * /*handle*/) { // nothing required } bool ttrss_api::mark_all_read(const std::string& feed_url) { std::map<std::string, std::string> args; args["feed_id"] = url_to_id(feed_url); struct json_object * content = run_op("catchupFeed", args); if(!content) return false; json_object_put(content); return true; } bool ttrss_api::mark_article_read(const std::string& guid, bool read) { // Do this in a thread, as we don't care about the result enough to wait for // it. thread * mrt = new markreadthread( this, guid, read ); mrt->start(); return true; } bool ttrss_api::update_article_flags(const std::string& oldflags, const std::string& newflags, const std::string& guid) { std::string star_flag = cfg->get_configvalue("ttrss-flag-star"); std::string publish_flag = cfg->get_configvalue("ttrss-flag-publish"); bool success = true; if (star_flag.length() > 0) { if (strchr(oldflags.c_str(), star_flag[0])==NULL && strchr(newflags.c_str(), star_flag[0])!=NULL) { success = star_article(guid, true); } else if (strchr(oldflags.c_str(), star_flag[0])!=NULL && strchr(newflags.c_str(), star_flag[0])==NULL) { success = star_article(guid, false); } } if (publish_flag.length() > 0) { if (strchr(oldflags.c_str(), publish_flag[0])==NULL && strchr(newflags.c_str(), publish_flag[0])!=NULL) { success = publish_article(guid, true); } else if (strchr(oldflags.c_str(), publish_flag[0])!=NULL && strchr(newflags.c_str(), publish_flag[0])==NULL) { success = publish_article(guid, false); } } return success; } static bool sort_by_pubdate(const rsspp::item& a, const rsspp::item& b) { return a.pubDate_ts > b.pubDate_ts; } rsspp::feed ttrss_api::fetch_feed(const std::string& id) { rsspp::feed f; f.rss_version = rsspp::TTRSS_JSON; std::map<std::string, std::string> args; args["feed_id"] = id; args["show_content"] = "1"; struct json_object * content = run_op("getHeadlines", args); if (!content) return f; if (json_object_get_type(content) != json_type_array) { LOG(LOG_ERROR, "ttrss_api::fetch_feed: content is not an array"); return f; } struct array_list * items = json_object_get_array(content); int items_size = array_list_length(items); LOG(LOG_DEBUG, "ttrss_api::fetch_feed: %d items", items_size); for (int i=0;i<items_size;i++) { struct json_object * item_obj = (struct json_object *)array_list_get_idx(items, i); int id = json_object_get_int(json_object_object_get(item_obj, "id")); const char * title = json_object_get_string(json_object_object_get(item_obj, "title")); const char * link = json_object_get_string(json_object_object_get(item_obj, "link")); const char * content = json_object_get_string(json_object_object_get(item_obj, "content")); time_t updated = (time_t)json_object_get_int(json_object_object_get(item_obj, "updated")); bool unread = json_object_get_boolean(json_object_object_get(item_obj, "unread")); rsspp::item item; if (title) item.title = title; if (link) item.link = link; if (content) item.content_encoded = content; item.guid = utils::strprintf("%d", id); if (unread) { item.labels.push_back("ttrss:unread"); } else { item.labels.push_back("ttrss:read"); } char rfc822_date[128]; strftime(rfc822_date, sizeof(rfc822_date), "%a, %d %b %Y %H:%M:%S %z", gmtime(&updated)); item.pubDate = rfc822_date; item.pubDate_ts = updated; f.items.push_back(item); } std::sort(f.items.begin(), f.items.end(), sort_by_pubdate); json_object_put(content); return f; } void ttrss_api::fetch_feeds_per_category(struct json_object * cat, std::vector<tagged_feedurl>& feeds) { const char * cat_name = NULL; struct json_object * cat_title_obj = NULL; int cat_id; if (cat) { struct json_object * cat_id_obj = json_object_object_get(cat, "id"); cat_id = json_object_get_int(cat_id_obj); cat_title_obj = json_object_object_get(cat, "title"); cat_name = json_object_get_string(cat_title_obj); LOG(LOG_DEBUG, "ttrss_api::fetch_feeds_per_category: id = %d title = %s", cat_id, cat_name); } else { // As uncategorized is a category itself (id = 0) and the default value // for a getFeeds is id = 0, the feeds in uncategorized will appear twice return; } std::map<std::string, std::string> args; if (cat) args["cat_id"] = utils::signed_to_s(cat_id); struct json_object * feed_list_obj = run_op("getFeeds", args); if (!feed_list_obj) return; struct array_list * feed_list = json_object_get_array(feed_list_obj); int feed_list_size = array_list_length(feed_list); for (int j=0;j<feed_list_size;j++) { struct json_object * feed = (struct json_object *)array_list_get_idx(feed_list, j); int feed_id = json_object_get_int(json_object_object_get(feed, "id")); const char * feed_title = json_object_get_string(json_object_object_get(feed, "title")); const char * feed_url = json_object_get_string(json_object_object_get(feed, "feed_url")); std::vector<std::string> tags; tags.push_back(std::string("~") + feed_title); if (cat_name) { tags.push_back(cat_name); } feeds.push_back(tagged_feedurl(utils::strprintf("%s#%d", feed_url, feed_id), tags)); // TODO: cache feed_id -> feed_url (or feed_url -> feed_id ?) } json_object_put(feed_list_obj); } bool ttrss_api::star_article(const std::string& guid, bool star) { return update_article(guid, 0, star ? 1 : 0); } bool ttrss_api::publish_article(const std::string& guid, bool publish) { return update_article(guid, 1, publish ? 1 : 0); } bool ttrss_api::update_article(const std::string& guid, int field, int mode) { std::map<std::string, std::string> args; args["article_ids"] = guid; args["field"] = utils::to_s(field); args["mode"] = utils::to_s(mode); struct json_object * content = run_op("updateArticle", args); if (!content) return false; json_object_put(content); return true; } std::string ttrss_api::url_to_id(const std::string& url) { const char * uri = url.c_str(); const char * pound = strrchr(uri, '#'); if (!pound) return ""; return std::string(pound+1); } }
use utis::signed_to_s in ttrss_api.cpp::fetch_feeds_per_category
use utis::signed_to_s in ttrss_api.cpp::fetch_feeds_per_category ttrss has special categories, which are asigned ids below 0. If using the unsigned to_s() method these result in queries to nonexistend categories.
C++
mit
newsboat/newsboat,travisred/newsbeuter,der-lyse/newsboat,travisred/newsbeuter,der-lyse/newsboat,der-lyse/newsboat,newsboat/newsboat,x4121/newsbeuter,x4121/newsbeuter,der-lyse/newsboat,newsboat/newsboat,der-lyse/newsboat,travisred/newsbeuter,newsboat/newsboat,travisred/newsbeuter,der-lyse/newsboat,newsboat/newsboat,x4121/newsbeuter,der-lyse/newsboat,newsboat/newsboat,newsboat/newsboat,newsboat/newsboat,der-lyse/newsboat,x4121/newsbeuter
1c4522c8776d16853c426ad3bc06c25871176b2f
LxssFileSystem/LxssFileSystem.cpp
LxssFileSystem/LxssFileSystem.cpp
#define _CRT_SECURE_NO_WARNINGS #define WIN32_NO_STATUS #include <Windows.h> #undef WIN32_NO_STATUS #include <winternl.h> #include <ntstatus.h> #include <objbase.h> #include <climits> struct FILE_DIRECTORY_INFORMATION { ULONG NextEntryOffset; ULONG FileIndex; LARGE_INTEGER CreationTime; LARGE_INTEGER LastAccessTime; LARGE_INTEGER LastWriteTime; LARGE_INTEGER ChangeTime; LARGE_INTEGER EndOfFile; LARGE_INTEGER AllocationSize; ULONG FileAttributes; ULONG FileNameLength; WCHAR FileName[1]; }; struct FILE_GET_EA_INFORMATION { ULONG NextEntryOffset; UCHAR EaNameLength; CHAR EaName[1]; }; struct FILE_FULL_EA_INFORMATION { ULONG NextEntryOffset; UCHAR Flags; UCHAR EaNameLength; USHORT EaValueLength; CHAR EaName[1]; }; extern "C" NTSYSAPI NTSTATUS NTAPI NtQueryDirectoryFile( _In_ HANDLE FileHandle, _In_opt_ HANDLE Event, _In_opt_ PIO_APC_ROUTINE ApcRoutine, _In_opt_ PVOID ApcContext, _Out_ PIO_STATUS_BLOCK IoStatusBlock, _Out_ PVOID FileInformation, _In_ ULONG Length, _In_ FILE_INFORMATION_CLASS FileInformationClass, _In_ BOOLEAN ReturnSingleEntry, _In_opt_ PUNICODE_STRING FileName, _In_ BOOLEAN RestartScan ); extern "C" NTSYSAPI NTSTATUS NTAPI NtQueryEaFile( _In_ HANDLE FileHandle, _Out_ PIO_STATUS_BLOCK IoStatusBlock, _Out_ PVOID Buffer, _In_ ULONG Length, _In_ BOOLEAN ReturnSingleEntry, _In_opt_ PVOID EaList, _In_ ULONG EaListLength, _In_opt_ PULONG EaIndex, _In_ BOOLEAN RestartScan ); extern "C" NTSYSAPI NTSTATUS NTAPI NtSetEaFile( _In_ HANDLE FileHandle, _Out_ PIO_STATUS_BLOCK IoStatusBlock, _In_ PVOID EaBuffer, _In_ ULONG EaBufferSize ); extern "C" __declspec(dllexport) HANDLE GetFileHandle(LPWSTR ntPath, bool directory, bool create, bool write) { UNICODE_STRING uniStr; RtlInitUnicodeString(&uniStr, ntPath); OBJECT_ATTRIBUTES objAttrs; InitializeObjectAttributes(&objAttrs, &uniStr, 0, 0, nullptr); HANDLE hFile; IO_STATUS_BLOCK status; auto res = NtCreateFile(&hFile, write ? FILE_GENERIC_WRITE : FILE_GENERIC_READ, &objAttrs, &status, nullptr, 0, 0, create ? FILE_CREATE : FILE_OPEN, FILE_SYNCHRONOUS_IO_ALERT | (directory ? FILE_DIRECTORY_FILE : FILE_NON_DIRECTORY_FILE), nullptr, 0 ); return res == STATUS_SUCCESS ? hFile : INVALID_HANDLE_VALUE; } extern "C" __declspec(dllexport) bool EnumerateDirectory(HANDLE hFile, LPWSTR *fileName, bool *directory) { const int fileInfoSize = (int)(sizeof(FILE_DIRECTORY_INFORMATION) + UCHAR_MAX * sizeof(wchar_t)); char fileInfoBuf[fileInfoSize] = { 0 }; auto fileInfo = (FILE_DIRECTORY_INFORMATION *)fileInfoBuf; IO_STATUS_BLOCK status; auto res = NtQueryDirectoryFile(hFile, nullptr, nullptr, nullptr, &status, fileInfo, fileInfoSize, FileDirectoryInformation, true, nullptr, false); if (res == STATUS_NO_MORE_FILES) return true; if (res != STATUS_SUCCESS) { *fileName = nullptr; return false; } *fileName = (LPWSTR)CoTaskMemAlloc(fileInfo->FileNameLength * sizeof(wchar_t)); wcscpy(*fileName, fileInfo->FileName); *directory = (fileInfo->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) > 0; return true; } const char *LxssEaName = "LXATTRB"; const int LxssEaNameLength = 7; extern "C" __declspec(dllexport) bool CopyLxssEa(HANDLE hFrom, HANDLE hTo) { const int getEaInfoSize = (int)(sizeof(FILE_GET_EA_INFORMATION) + LxssEaNameLength); const int eaInfoSize = (int)(sizeof(FILE_FULL_EA_INFORMATION) + LxssEaNameLength + USHRT_MAX); char getEaBuf[getEaInfoSize]; auto getEaInfo = (FILE_GET_EA_INFORMATION *)getEaBuf; getEaInfo->NextEntryOffset = 0; getEaInfo->EaNameLength = LxssEaNameLength; strcpy(getEaInfo->EaName, LxssEaName); char eaBuf[eaInfoSize]; auto eaInfo = (FILE_FULL_EA_INFORMATION *)eaBuf; IO_STATUS_BLOCK status; auto res = NtQueryEaFile(hFrom, &status, eaInfo, eaInfoSize, true, getEaInfo, getEaInfoSize, nullptr, true); if (res != STATUS_SUCCESS) return false; res = NtSetEaFile(hTo, &status, eaInfo, eaInfoSize); if (res != STATUS_SUCCESS) return false; return true; } extern "C" __declspec(dllexport) bool SetLxssEa(HANDLE hFile, char *data, int dataLength) { const int eaInfoSize = (int)(sizeof(FILE_FULL_EA_INFORMATION) + LxssEaNameLength + dataLength); auto eaInfo = (FILE_FULL_EA_INFORMATION *)new char[eaInfoSize]; eaInfo->NextEntryOffset = 0; eaInfo->Flags = 0; eaInfo->EaNameLength = LxssEaNameLength; eaInfo->EaValueLength = dataLength; strcpy(eaInfo->EaName, LxssEaName); memcpy(eaInfo->EaName + LxssEaNameLength + 1, data, dataLength); IO_STATUS_BLOCK status; auto res = NtSetEaFile(hFile, &status, eaInfo, eaInfoSize); if (res != STATUS_SUCCESS) return false; delete eaInfo; return true; }
#define _CRT_SECURE_NO_WARNINGS #define WIN32_NO_STATUS #include <Windows.h> #undef WIN32_NO_STATUS #include <winternl.h> #include <ntstatus.h> #include <objbase.h> #include <climits> struct FILE_DIRECTORY_INFORMATION { ULONG NextEntryOffset; ULONG FileIndex; LARGE_INTEGER CreationTime; LARGE_INTEGER LastAccessTime; LARGE_INTEGER LastWriteTime; LARGE_INTEGER ChangeTime; LARGE_INTEGER EndOfFile; LARGE_INTEGER AllocationSize; ULONG FileAttributes; ULONG FileNameLength; WCHAR FileName[1]; }; struct FILE_GET_EA_INFORMATION { ULONG NextEntryOffset; UCHAR EaNameLength; CHAR EaName[1]; }; struct FILE_FULL_EA_INFORMATION { ULONG NextEntryOffset; UCHAR Flags; UCHAR EaNameLength; USHORT EaValueLength; CHAR EaName[1]; }; extern "C" NTSYSAPI NTSTATUS NTAPI NtQueryDirectoryFile( _In_ HANDLE FileHandle, _In_opt_ HANDLE Event, _In_opt_ PIO_APC_ROUTINE ApcRoutine, _In_opt_ PVOID ApcContext, _Out_ PIO_STATUS_BLOCK IoStatusBlock, _Out_ PVOID FileInformation, _In_ ULONG Length, _In_ FILE_INFORMATION_CLASS FileInformationClass, _In_ BOOLEAN ReturnSingleEntry, _In_opt_ PUNICODE_STRING FileName, _In_ BOOLEAN RestartScan ); extern "C" NTSYSAPI NTSTATUS NTAPI NtQueryEaFile( _In_ HANDLE FileHandle, _Out_ PIO_STATUS_BLOCK IoStatusBlock, _Out_ PVOID Buffer, _In_ ULONG Length, _In_ BOOLEAN ReturnSingleEntry, _In_opt_ PVOID EaList, _In_ ULONG EaListLength, _In_opt_ PULONG EaIndex, _In_ BOOLEAN RestartScan ); extern "C" NTSYSAPI NTSTATUS NTAPI NtSetEaFile( _In_ HANDLE FileHandle, _Out_ PIO_STATUS_BLOCK IoStatusBlock, _In_ PVOID EaBuffer, _In_ ULONG EaBufferSize ); extern "C" __declspec(dllexport) HANDLE GetFileHandle(LPWSTR ntPath, bool directory, bool create, bool write) { UNICODE_STRING uniStr; RtlInitUnicodeString(&uniStr, ntPath); OBJECT_ATTRIBUTES objAttrs; InitializeObjectAttributes(&objAttrs, &uniStr, 0, 0, nullptr); HANDLE hFile; IO_STATUS_BLOCK status; auto res = NtCreateFile(&hFile, write ? FILE_GENERIC_WRITE : FILE_GENERIC_READ, &objAttrs, &status, nullptr, 0, 0, create ? FILE_CREATE : FILE_OPEN, FILE_SYNCHRONOUS_IO_ALERT | (directory ? FILE_DIRECTORY_FILE : FILE_NON_DIRECTORY_FILE), nullptr, 0 ); return res == STATUS_SUCCESS ? hFile : INVALID_HANDLE_VALUE; } extern "C" __declspec(dllexport) bool EnumerateDirectory(HANDLE hFile, LPWSTR *fileName, bool *directory) { const int fileInfoSize = (int)(sizeof(FILE_DIRECTORY_INFORMATION) + UCHAR_MAX * sizeof(wchar_t)); char fileInfoBuf[fileInfoSize] = { 0 }; auto fileInfo = (FILE_DIRECTORY_INFORMATION *)fileInfoBuf; IO_STATUS_BLOCK status; auto res = NtQueryDirectoryFile(hFile, nullptr, nullptr, nullptr, &status, fileInfo, fileInfoSize, FileDirectoryInformation, true, nullptr, false); if (res == STATUS_NO_MORE_FILES) return true; if (res != STATUS_SUCCESS) { *fileName = nullptr; return false; } *fileName = (LPWSTR)CoTaskMemAlloc(fileInfo->FileNameLength * sizeof(wchar_t)); wcscpy(*fileName, fileInfo->FileName); *directory = (fileInfo->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) > 0; return true; } const char *LxssEaName = "LXATTRB"; const int LxssEaNameLength = 7; extern "C" __declspec(dllexport) bool CopyLxssEa(HANDLE hFrom, HANDLE hTo) { const int getEaInfoSize = (int)(sizeof(FILE_GET_EA_INFORMATION) + LxssEaNameLength); const int eaInfoSize = (int)(sizeof(FILE_FULL_EA_INFORMATION) + LxssEaNameLength + USHRT_MAX); char getEaBuf[getEaInfoSize]; auto getEaInfo = (FILE_GET_EA_INFORMATION *)getEaBuf; getEaInfo->NextEntryOffset = 0; getEaInfo->EaNameLength = LxssEaNameLength; strcpy(getEaInfo->EaName, LxssEaName); char eaBuf[eaInfoSize]; auto eaInfo = (FILE_FULL_EA_INFORMATION *)eaBuf; IO_STATUS_BLOCK status; auto res = NtQueryEaFile(hFrom, &status, eaInfo, eaInfoSize, true, getEaInfo, getEaInfoSize, nullptr, true); if (res != STATUS_SUCCESS) return false; res = NtSetEaFile(hTo, &status, eaInfo, eaInfoSize); if (res != STATUS_SUCCESS) return false; return true; } extern "C" __declspec(dllexport) bool SetLxssEa(HANDLE hFile, char *data, int dataLength) { const int eaInfoSize = (int)(sizeof(FILE_FULL_EA_INFORMATION) + LxssEaNameLength + dataLength); auto eaInfo = (FILE_FULL_EA_INFORMATION *)new char[eaInfoSize]; eaInfo->NextEntryOffset = 0; eaInfo->Flags = 0; eaInfo->EaNameLength = LxssEaNameLength; eaInfo->EaValueLength = dataLength; strcpy(eaInfo->EaName, LxssEaName); memcpy(eaInfo->EaName + LxssEaNameLength + 1, data, dataLength); IO_STATUS_BLOCK status; auto res = NtSetEaFile(hFile, &status, eaInfo, eaInfoSize); if (res != STATUS_SUCCESS) return false; delete[] eaInfo; return true; }
Fix array freeing in SetLxssEa.
Fix array freeing in SetLxssEa.
C++
mit
sqc1999/LxRunOffline
11335bc643d0034624c6763703d28e68f88f8a29
src/vu8/Class.hpp
src/vu8/Class.hpp
#ifndef TSA_VU8_CLASS_HPP #define TSA_VU8_CLASS_HPP #include <vu8/ToV8.hpp> #include <vu8/FromV8.hpp> #include <vu8/Throw.hpp> #include <vu8/Factory.hpp> #include <vu8/CallFromV8.hpp> #include <vu8/detail/Proto.hpp> #include <vu8/detail/Singleton.hpp> #include <vu8/detail/Class.hpp> #include <boost/fusion/container/vector.hpp> #include <boost/fusion/adapted/mpl.hpp> #include <boost/fusion/include/push_front.hpp> #include <boost/fusion/include/join.hpp> #include <iostream> #include <stdexcept> namespace vu8 { namespace fu = boost::fusion; namespace mpl = boost::mpl; template < class T, class Factory = Factory<> > struct Class; template <class T> struct Singleton; template <class M, class Factory> class ClassSingletonFactory { M& mixin() { return static_cast<M &>(*this); } static inline ValueHandle ConstructorFunction(const v8::Arguments& args) { return M::Instance().WrapObject(args); } public: v8::Persistent<v8::FunctionTemplate>& JSFunctionTemplateHelper() { return mixin().jsFunc_; } enum { HAS_NULL_FACTORY = false }; ClassSingletonFactory() : jsFunc_(v8::Persistent<v8::FunctionTemplate>::New(v8::FunctionTemplate::New( &ConstructorFunction))) {} v8::Persistent<v8::FunctionTemplate> jsFunc_; }; template <class M> struct ClassSingletonFactory<M, NoFactory> { enum { HAS_NULL_FACTORY = true }; v8::Persistent<v8::FunctionTemplate>& JSFunctionTemplateHelper() { return static_cast<M &>(*this).func_; } }; template <class T, class Factory> class ClassSingleton : detail::LazySingleton< ClassSingleton<T, Factory> >, public ClassSingletonFactory<ClassSingleton<T, Factory>, Factory> { friend class ClassSingletonFactory<ClassSingleton<T, Factory>, Factory>; typedef ClassSingleton<T, Factory> self; typedef ValueHandle (T::*MethodCallback)(const v8::Arguments& args); v8::Persistent<v8::FunctionTemplate>& ClassFunctionTemplate() { return func_; } v8::Persistent<v8::FunctionTemplate>& JSFunctionTemplate() { return this->JSFunctionTemplateHelper(); } // invoke passing javascript object argument directly template <class P> static inline typename boost::enable_if< detail::PassDirectIf<P>, typename P::return_type >::type Invoke(T *obj, const v8::Arguments& args) { return (obj->* P::method_pointer)(args); } template <class P> static inline typename boost::disable_if< detail::PassDirectIf<P>, typename P::return_type >::type Invoke(T *obj, const v8::Arguments& args) { return CallFromV8<P>(*obj, args); } template <class P> static inline typename boost::disable_if< boost::is_same<void, typename P::return_type>, ValueHandle >::type ForwardReturn(T *obj, const v8::Arguments& args) { return ToV8(Invoke<P>(obj, args)); } template <class P> static inline typename boost::enable_if< boost::is_same<void, typename P::return_type>, ValueHandle >::type ForwardReturn(T *obj, const v8::Arguments& args) { Invoke<P>(obj, args); return v8::Undefined(); } // every method is run inside a handle scope template <class P> static inline ValueHandle Forward(const v8::Arguments& args) { v8::HandleScope scope; v8::Local<v8::Object> self = args.Holder(); v8::Local<v8::External> wrap = v8::Local<v8::External>::Cast(self->GetInternalField(0)); // this will kill without zero-overhead exception handling try { return scope.Close(ForwardReturn<P>( static_cast<T *>(wrap->Value()), args)); } catch (std::runtime_error const& e) { return Throw(e.what()); } } static inline void MadeWeak(v8::Persistent<v8::Value> object, void *parameter) { T *obj = static_cast<T *>(parameter); delete(obj); object.Dispose(); object.Clear(); } v8::Handle<v8::Object> WrapObject(const v8::Arguments& args) { v8::HandleScope scope; T *wrap = detail::ArgFactory<T, Factory>::New(args); v8::Local<v8::Object> localObj = func_->GetFunction()->NewInstance(); v8::Persistent<v8::Object> obj = v8::Persistent<v8::Object>::New(localObj); obj->SetInternalField(0, v8::External::New(wrap)); obj.MakeWeak(wrap, &self::MadeWeak); return scope.Close(localObj); } ClassSingleton() : func_(v8::Persistent<v8::FunctionTemplate>::New(v8::FunctionTemplate::New())) { if (! this->HAS_NULL_FACTORY) func_->Inherit(JSFunctionTemplate()); func_->InstanceTemplate()->SetInternalFieldCount(1); } v8::Persistent<v8::FunctionTemplate> func_; friend class detail::LazySingleton<self>; friend class Class<T, Factory>; friend class Singleton<T>; }; // Interface for registering C++ classes with v8 // T = class // Factory = factory for allocating c++ object // by default Class uses zero-argument constructor template <class T, class Factory> struct Class { typedef ClassSingleton<T, Factory> singleton_t; private: typedef typename singleton_t::MethodCallback MethodCallback; inline singleton_t& Instance() { return singleton_t::Instance(); } // method helper template <class P> inline Class& Method(char const *name) { ClassFunctionTemplate()->PrototypeTemplate()->Set( v8::String::New(name), v8::FunctionTemplate::New(&singleton_t::template Forward<P>)); return *this; } public: // method with any prototype template <class P, typename detail::MemFunProto<T, P>::method_type Ptr> inline Class& Set(char const *name) { return Method< detail::MemFun<T, P, Ptr> >(name); } template <class P, typename detail::MemFunProto<T const, P>::method_type Ptr> inline Class& Set(char const *name) { return Method< detail::MemFun<T const, P, Ptr> >(name); } // passing v8::Arguments directly but modify return type template <class R, R (T::*Ptr)(const v8::Arguments&)> inline Class& Set(char const *name) { return Set<R(const v8::Arguments&), Ptr>(name); } // passing v8::Arguments and return ValueHandle directly template <ValueHandle (T::*Ptr)(const v8::Arguments&)> inline Class& Set(char const *name) { return Method<ValueHandle(const v8::Arguments&), Ptr>(name); } inline v8::Persistent<v8::FunctionTemplate>& ClassFunctionTemplate() { return Instance().ClassFunctionTemplate(); } inline v8::Persistent<v8::FunctionTemplate>& JSFunctionTemplate() { return Instance().JSFunctionTemplate(); } // create javascript object which references externally created C++ // class. It will not take ownership of the C++ pointer. static inline v8::Handle<v8::Object> ReferenceExternal(T *ext) { v8::HandleScope scope; v8::Local<v8::Object> obj = singleton_t::Instance().func_->GetFunction()->NewInstance(); obj->SetInternalField(0, v8::External::New(ext)); return scope.Close(obj); } // As ReferenceExternal but delete memory for C++ object when javascript // object is deleted. You must use "new" to allocate ext. static inline v8::Handle<v8::Object> ImportExternal(T *ext) { v8::HandleScope scope; v8::Local<v8::Object> localObj = singleton_t::Instance().func_->GetFunction()->NewInstance(); v8::Persistent<v8::Object> obj = v8::Persistent<v8::Object>::New(localObj); obj->SetInternalField(0, v8::External::New(ext)); obj.MakeWeak(ext, &singleton_t::MadeWeak); return scope.Close(localObj); } template <class U, class V> Class(Class<U, V>& parent) { JSFunctionTemplate()->Inherit(parent.ClassFunctionTemplate()); } Class() {} friend class Singleton<T>; }; // Wrap a C++ singleton template <class T> struct Singleton : Class<T, NoFactory> { typedef Class<T> base; template <class U, class V> Singleton(Class<U, V>& parent, T* instance) : instance_(instance) { base::JSFunctionTemplate()->Inherit(parent.ClassFunctionTemplate()); } Singleton(T *instance) : instance_(instance) {} v8::Persistent<v8::Object> NewInstance() { v8::HandleScope scope; v8::Persistent<v8::Object> obj = v8::Persistent<v8::Object>::New( this->Instance().func_->GetFunction()->NewInstance()); obj->SetInternalField(0, v8::External::New(instance_)); return obj; } private: T *instance_; }; } #endif
#ifndef TSA_VU8_CLASS_HPP #define TSA_VU8_CLASS_HPP #include <vu8/ToV8.hpp> #include <vu8/FromV8.hpp> #include <vu8/Throw.hpp> #include <vu8/Factory.hpp> #include <vu8/CallFromV8.hpp> #include <vu8/detail/Proto.hpp> #include <vu8/detail/Singleton.hpp> #include <vu8/detail/Class.hpp> #include <boost/fusion/container/vector.hpp> #include <boost/fusion/adapted/mpl.hpp> #include <boost/fusion/include/push_front.hpp> #include <boost/fusion/include/join.hpp> #include <iostream> #include <stdexcept> namespace vu8 { namespace fu = boost::fusion; namespace mpl = boost::mpl; template < class T, class Factory = Factory<> > struct Class; template <class T> struct Singleton; template <class M, class Factory> class ClassSingletonFactory { M& mixin() { return static_cast<M &>(*this); } static inline ValueHandle ConstructorFunction(const v8::Arguments& args) { return M::Instance().WrapObject(args); } public: v8::Persistent<v8::FunctionTemplate>& JSFunctionTemplateHelper() { return mixin().jsFunc_; } enum { HAS_NULL_FACTORY = false }; ClassSingletonFactory() : jsFunc_(v8::Persistent<v8::FunctionTemplate>::New(v8::FunctionTemplate::New( &ConstructorFunction))) {} v8::Persistent<v8::FunctionTemplate> jsFunc_; }; template <class M> struct ClassSingletonFactory<M, NoFactory> { enum { HAS_NULL_FACTORY = true }; v8::Persistent<v8::FunctionTemplate>& JSFunctionTemplateHelper() { return static_cast<M &>(*this).func_; } }; template <class T, class Factory> class ClassSingleton : detail::LazySingleton< ClassSingleton<T, Factory> >, public ClassSingletonFactory<ClassSingleton<T, Factory>, Factory> { friend class ClassSingletonFactory<ClassSingleton<T, Factory>, Factory>; typedef ClassSingleton<T, Factory> self; typedef ValueHandle (T::*MethodCallback)(const v8::Arguments& args); v8::Persistent<v8::FunctionTemplate>& ClassFunctionTemplate() { return func_; } v8::Persistent<v8::FunctionTemplate>& JSFunctionTemplate() { return this->JSFunctionTemplateHelper(); } // invoke passing javascript object argument directly template <class P> static inline typename boost::enable_if< detail::PassDirectIf<P>, typename P::return_type >::type Invoke(T *obj, const v8::Arguments& args) { return (obj->* P::method_pointer)(args); } template <class P> static inline typename boost::disable_if< detail::PassDirectIf<P>, typename P::return_type >::type Invoke(T *obj, const v8::Arguments& args) { return CallFromV8<P>(*obj, args); } template <class P> static inline typename boost::disable_if< boost::is_same<void, typename P::return_type>, ValueHandle >::type ForwardReturn(T *obj, const v8::Arguments& args) { return ToV8(Invoke<P>(obj, args)); } template <class P> static inline typename boost::enable_if< boost::is_same<void, typename P::return_type>, ValueHandle >::type ForwardReturn(T *obj, const v8::Arguments& args) { Invoke<P>(obj, args); return v8::Undefined(); } // every method is run inside a handle scope template <class P> static inline ValueHandle Forward(const v8::Arguments& args) { v8::HandleScope scope; v8::Local<v8::Object> self = args.Holder(); // this will kill without zero-overhead exception handling try { return scope.Close(ForwardReturn<P>( static_cast<T *>(self->GetPointerFromInternalField(0)), args)); } catch (std::runtime_error const& e) { return Throw(e.what()); } } static inline void MadeWeak(v8::Persistent<v8::Value> object, void *parameter) { T *obj = static_cast<T *>(parameter); delete(obj); object.Dispose(); object.Clear(); } v8::Handle<v8::Object> WrapObject(const v8::Arguments& args) { v8::HandleScope scope; T *wrap = detail::ArgFactory<T, Factory>::New(args); v8::Local<v8::Object> localObj = func_->GetFunction()->NewInstance(); v8::Persistent<v8::Object> obj = v8::Persistent<v8::Object>::New(localObj); obj->SetPointerInInternalField(0, wrap); obj.MakeWeak(wrap, &self::MadeWeak); return scope.Close(localObj); } ClassSingleton() : func_(v8::Persistent<v8::FunctionTemplate>::New(v8::FunctionTemplate::New())) { if (! this->HAS_NULL_FACTORY) func_->Inherit(JSFunctionTemplate()); func_->InstanceTemplate()->SetInternalFieldCount(1); } v8::Persistent<v8::FunctionTemplate> func_; friend class detail::LazySingleton<self>; friend class Class<T, Factory>; friend class Singleton<T>; }; // Interface for registering C++ classes with v8 // T = class // Factory = factory for allocating c++ object // by default Class uses zero-argument constructor template <class T, class Factory> struct Class { typedef ClassSingleton<T, Factory> singleton_t; private: typedef typename singleton_t::MethodCallback MethodCallback; inline singleton_t& Instance() { return singleton_t::Instance(); } // method helper template <class P> inline Class& Method(char const *name) { ClassFunctionTemplate()->PrototypeTemplate()->Set( v8::String::New(name), v8::FunctionTemplate::New(&singleton_t::template Forward<P>)); return *this; } public: // method with any prototype template <class P, typename detail::MemFunProto<T, P>::method_type Ptr> inline Class& Set(char const *name) { return Method< detail::MemFun<T, P, Ptr> >(name); } template <class P, typename detail::MemFunProto<T const, P>::method_type Ptr> inline Class& Set(char const *name) { return Method< detail::MemFun<T const, P, Ptr> >(name); } // passing v8::Arguments directly but modify return type template <class R, R (T::*Ptr)(const v8::Arguments&)> inline Class& Set(char const *name) { return Set<R(const v8::Arguments&), Ptr>(name); } // passing v8::Arguments and return ValueHandle directly template <ValueHandle (T::*Ptr)(const v8::Arguments&)> inline Class& Set(char const *name) { return Method<ValueHandle(const v8::Arguments&), Ptr>(name); } inline v8::Persistent<v8::FunctionTemplate>& ClassFunctionTemplate() { return Instance().ClassFunctionTemplate(); } inline v8::Persistent<v8::FunctionTemplate>& JSFunctionTemplate() { return Instance().JSFunctionTemplate(); } // create javascript object which references externally created C++ // class. It will not take ownership of the C++ pointer. static inline v8::Handle<v8::Object> ReferenceExternal(T *ext) { v8::HandleScope scope; v8::Local<v8::Object> obj = singleton_t::Instance().func_->GetFunction()->NewInstance(); obj->SetPointerInInternalField(0, ext); return scope.Close(obj); } // As ReferenceExternal but delete memory for C++ object when javascript // object is deleted. You must use "new" to allocate ext. static inline v8::Handle<v8::Object> ImportExternal(T *ext) { v8::HandleScope scope; v8::Local<v8::Object> localObj = singleton_t::Instance().func_->GetFunction()->NewInstance(); v8::Persistent<v8::Object> obj = v8::Persistent<v8::Object>::New(localObj); obj->SetPointerInInternalField(0, ext); obj.MakeWeak(ext, &singleton_t::MadeWeak); return scope.Close(localObj); } template <class U, class V> Class(Class<U, V>& parent) { JSFunctionTemplate()->Inherit(parent.ClassFunctionTemplate()); } Class() {} friend class Singleton<T>; }; // Wrap a C++ singleton template <class T> struct Singleton : Class<T, NoFactory> { typedef Class<T> base; template <class U, class V> Singleton(Class<U, V>& parent, T* instance) : instance_(instance) { base::JSFunctionTemplate()->Inherit(parent.ClassFunctionTemplate()); } Singleton(T *instance) : instance_(instance) {} v8::Persistent<v8::Object> NewInstance() { v8::HandleScope scope; v8::Persistent<v8::Object> obj = v8::Persistent<v8::Object>::New( this->Instance().func_->GetFunction()->NewInstance()); obj->SetPointerInInternalField(0, instance_); return obj; } private: T *instance_; }; } #endif
Optimise use of external objects.
Optimise use of external objects.
C++
mit
tsa/vu8,tsa/vu8
edb431796edcc20e263607a5efa768a9cec0e70c
OOInteraction/test/SimpleTest.cpp
OOInteraction/test/SimpleTest.cpp
/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2012 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. ** **********************************************************************************************************************/ /*********************************************************************************************************************** * SimpleTest.cpp * * Created on: Jan 12, 2012 * Author: Dimitar Asenov **********************************************************************************************************************/ #include "oointeraction.h" #include "SelfTest/headers/SelfTestSuite.h" #include "expression_editor/OOExpressionBuilder.h" #include "OOModel/headers/allOOModelNodes.h" #include "VisualizationBase/headers/Scene.h" #include "VisualizationBase/headers/views/MainView.h" #include "VisualizationBase/headers/node_extensions/Position.h" using namespace OOModel; using namespace Visualization; namespace OOInteraction { Class* addClass(Model::Model* model, Project* parent) { Class* cl = nullptr; if (!parent) cl = dynamic_cast<Class*> (model->createRoot("Class")); model->beginModification(parent ? static_cast<Model::Node*> (parent) :cl, "Adding a hello world class."); if (!cl) { cl = new Class(); parent->classes()->append(cl); } cl->setName("SomeClass"); model->endModification(); return cl; } Method* addDivBySix(Model::Model* model, Class* parent) { Method* divbysix = nullptr; if (!parent) divbysix = dynamic_cast<Method*> (model->createRoot("Method")); model->beginModification(parent? static_cast<Model::Node*> (parent) : divbysix, "Adding a divBySix method."); if (!divbysix) { divbysix = new Method(); parent->methods()->append(divbysix); } divbysix->setName("findDivBySix"); FormalResult* divbysixResult = new FormalResult(); divbysixResult->setType(new PrimitiveType(PrimitiveType::INT)); divbysix->results()->append(divbysixResult); FormalArgument* arg = new FormalArgument(); divbysix->arguments()->append(arg); arg->setName("numbers"); ArrayType* argType = new ArrayType(); argType->setType(new PrimitiveType(PrimitiveType::INT)); arg->setType(argType); VariableDeclaration* exprtest = new VariableDeclaration(); divbysix->items()->append(exprtest); exprtest->setName("exprtest"); exprtest->setType(new PrimitiveType(PrimitiveType::INT)); exprtest->setInitialValue( OOExpressionBuilder::getOOExpression("$$aa++&b*e/d-#") ); VariableDeclaration* result = new VariableDeclaration(); divbysix->items()->append(result); result->setName("result"); result->setType(new PrimitiveType(PrimitiveType::INT)); result->setInitialValue(new IntegerLiteral(-1)); LoopStatement* sixloop = new LoopStatement(); divbysix->items()->append(sixloop); VariableDeclaration* sixLoopInit = new VariableDeclaration(); sixloop->setInitStep(sixLoopInit); sixLoopInit->setName("i"); sixLoopInit->setType(new PrimitiveType(PrimitiveType::INT)); sixLoopInit->setInitialValue(new IntegerLiteral(0)); BinaryOperation* sixLoopCond = new BinaryOperation(); sixloop->setCondition(sixLoopCond); sixLoopCond->setLeft(new VariableAccess("local:i")); sixLoopCond->setOp(BinaryOperation::LESS); MethodCallExpression* sizeCall = new MethodCallExpression(); sixLoopCond->setRight(sizeCall); sizeCall->ref()->set("size"); sizeCall->setPrefix(new VariableAccess("local:numbers")); //TODO test the visualization without the remaining parts of this method AssignmentStatement* sixLoopUpdate = new AssignmentStatement(); sixloop->setUpdateStep(sixLoopUpdate); sixLoopUpdate->setLeft(new VariableAccess("local:i")); sixLoopUpdate->setOp(AssignmentStatement::PLUS_ASSIGN); sixLoopUpdate->setRight(new IntegerLiteral(1)); VariableDeclaration* n = new VariableDeclaration(); sixloop->body()->append(n); n->setName("n"); n->setType(new PrimitiveType(PrimitiveType::INT)); BinaryOperation* item = new BinaryOperation(); n->setInitialValue(item); item->setLeft(new VariableAccess("local:numbers")); item->setOp(BinaryOperation::ARRAY_INDEX); item->setRight(new VariableAccess("local:i")); IfStatement* ifdiv2 = new IfStatement(); sixloop->body()->append(ifdiv2); BinaryOperation* eq0 = new BinaryOperation(); ifdiv2->setCondition(eq0); eq0->setOp(BinaryOperation::EQUALS); eq0->setRight(new IntegerLiteral(0)); BinaryOperation* div2 = new BinaryOperation(); eq0->setLeft(div2); div2->setLeft(new VariableAccess("local:n")); div2->setOp(BinaryOperation::REMAINDER); div2->setRight(new IntegerLiteral(2)); ifdiv2->elseBranch()->append(new ContinueStatement()); IfStatement* ifdiv3 = new IfStatement(); ifdiv2->thenBranch()->append(ifdiv3); eq0 = new BinaryOperation(); ifdiv3->setCondition(eq0); eq0->setOp(BinaryOperation::EQUALS); eq0->setRight(new IntegerLiteral(0)); BinaryOperation* div3 = new BinaryOperation(); eq0->setLeft(div3); div3->setLeft(new VariableAccess("local:n")); div3->setOp(BinaryOperation::REMAINDER); div3->setRight(new IntegerLiteral(3)); AssignmentStatement* resultFound = new AssignmentStatement(); ifdiv3->thenBranch()->append(resultFound); resultFound->setLeft(new VariableAccess("local:result")); resultFound->setOp(AssignmentStatement::ASSIGN); resultFound->setRight(new VariableAccess("local:i")); ifdiv3->thenBranch()->append(new BreakStatement()); ReturnStatement* divbysixReturn = new ReturnStatement(); divbysixReturn->values()->append(new VariableAccess("local:result")); divbysix->items()->append(divbysixReturn); model->endModification(); return divbysix; } TEST(OOInteraction, SimpleTest) { Model::Model* model = new Model::Model(); Class* cl = nullptr; cl = addClass(model, nullptr); Method* divbysix = nullptr; divbysix = addDivBySix(model, cl); Model::Node* top_level = nullptr; if (cl) top_level = cl; else top_level = divbysix; Scene* scene = new Scene(); scene->addTopLevelItem( scene->defaultRenderer()->render(nullptr, top_level) ); scene->scheduleUpdate(); scene->listenToModel(model); // Create view MainView* view = new MainView(scene); CHECK_CONDITION(view != nullptr); } }
/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2012 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. ** **********************************************************************************************************************/ /*********************************************************************************************************************** * SimpleTest.cpp * * Created on: Jan 12, 2012 * Author: Dimitar Asenov **********************************************************************************************************************/ #include "oointeraction.h" #include "SelfTest/headers/SelfTestSuite.h" #include "expression_editor/OOExpressionBuilder.h" #include "OOModel/headers/allOOModelNodes.h" #include "VisualizationBase/headers/Scene.h" #include "VisualizationBase/headers/views/MainView.h" #include "VisualizationBase/headers/node_extensions/Position.h" using namespace OOModel; using namespace Visualization; namespace OOInteraction { Class* addClass(Model::Model* model, Project* parent) { Class* cl = nullptr; if (!parent) cl = dynamic_cast<Class*> (model->createRoot("Class")); model->beginModification(parent ? static_cast<Model::Node*> (parent) :cl, "Adding a hello world class."); if (!cl) { cl = new Class(); parent->classes()->append(cl); } cl->setName("SomeClass"); model->endModification(); return cl; } Method* addDivBySix(Model::Model* model, Class* parent) { Method* divbysix = nullptr; if (!parent) divbysix = dynamic_cast<Method*> (model->createRoot("Method")); model->beginModification(parent? static_cast<Model::Node*> (parent) : divbysix, "Adding a divBySix method."); if (!divbysix) { divbysix = new Method(); parent->methods()->append(divbysix); } divbysix->setName("findDivBySix"); FormalResult* divbysixResult = new FormalResult(); divbysixResult->setType(new PrimitiveType(PrimitiveType::INT)); divbysix->results()->append(divbysixResult); FormalArgument* arg = new FormalArgument(); divbysix->arguments()->append(arg); arg->setName("numbers"); ArrayType* argType = new ArrayType(); argType->setType(new PrimitiveType(PrimitiveType::INT)); arg->setType(argType); VariableDeclaration* exprtest = new VariableDeclaration(); divbysix->items()->append(exprtest); exprtest->setName("exprtest"); exprtest->setType(new PrimitiveType(PrimitiveType::INT)); exprtest->setInitialValue( OOExpressionBuilder::getOOExpression("+aa++&b*e/d-#") ); VariableDeclaration* result = new VariableDeclaration(); divbysix->items()->append(result); result->setName("result"); result->setType(new PrimitiveType(PrimitiveType::INT)); result->setInitialValue(new IntegerLiteral(-1)); LoopStatement* sixloop = new LoopStatement(); divbysix->items()->append(sixloop); VariableDeclaration* sixLoopInit = new VariableDeclaration(); sixloop->setInitStep(sixLoopInit); sixLoopInit->setName("i"); sixLoopInit->setType(new PrimitiveType(PrimitiveType::INT)); sixLoopInit->setInitialValue(new IntegerLiteral(0)); BinaryOperation* sixLoopCond = new BinaryOperation(); sixloop->setCondition(sixLoopCond); sixLoopCond->setLeft(new VariableAccess("local:i")); sixLoopCond->setOp(BinaryOperation::LESS); MethodCallExpression* sizeCall = new MethodCallExpression(); sixLoopCond->setRight(sizeCall); sizeCall->ref()->set("size"); sizeCall->setPrefix(new VariableAccess("local:numbers")); //TODO test the visualization without the remaining parts of this method AssignmentStatement* sixLoopUpdate = new AssignmentStatement(); sixloop->setUpdateStep(sixLoopUpdate); sixLoopUpdate->setLeft(new VariableAccess("local:i")); sixLoopUpdate->setOp(AssignmentStatement::PLUS_ASSIGN); sixLoopUpdate->setRight(new IntegerLiteral(1)); VariableDeclaration* n = new VariableDeclaration(); sixloop->body()->append(n); n->setName("n"); n->setType(new PrimitiveType(PrimitiveType::INT)); BinaryOperation* item = new BinaryOperation(); n->setInitialValue(item); item->setLeft(new VariableAccess("local:numbers")); item->setOp(BinaryOperation::ARRAY_INDEX); item->setRight(new VariableAccess("local:i")); IfStatement* ifdiv2 = new IfStatement(); sixloop->body()->append(ifdiv2); BinaryOperation* eq0 = new BinaryOperation(); ifdiv2->setCondition(eq0); eq0->setOp(BinaryOperation::EQUALS); eq0->setRight(new IntegerLiteral(0)); BinaryOperation* div2 = new BinaryOperation(); eq0->setLeft(div2); div2->setLeft(new VariableAccess("local:n")); div2->setOp(BinaryOperation::REMAINDER); div2->setRight(new IntegerLiteral(2)); ifdiv2->elseBranch()->append(new ContinueStatement()); IfStatement* ifdiv3 = new IfStatement(); ifdiv2->thenBranch()->append(ifdiv3); eq0 = new BinaryOperation(); ifdiv3->setCondition(eq0); eq0->setOp(BinaryOperation::EQUALS); eq0->setRight(new IntegerLiteral(0)); BinaryOperation* div3 = new BinaryOperation(); eq0->setLeft(div3); div3->setLeft(new VariableAccess("local:n")); div3->setOp(BinaryOperation::REMAINDER); div3->setRight(new IntegerLiteral(3)); AssignmentStatement* resultFound = new AssignmentStatement(); ifdiv3->thenBranch()->append(resultFound); resultFound->setLeft(new VariableAccess("local:result")); resultFound->setOp(AssignmentStatement::ASSIGN); resultFound->setRight(new VariableAccess("local:i")); ifdiv3->thenBranch()->append(new BreakStatement()); ReturnStatement* divbysixReturn = new ReturnStatement(); divbysixReturn->values()->append(new VariableAccess("local:result")); divbysix->items()->append(divbysixReturn); model->endModification(); return divbysix; } TEST(OOInteraction, SimpleTest) { Model::Model* model = new Model::Model(); Class* cl = nullptr; cl = addClass(model, nullptr); Method* divbysix = nullptr; divbysix = addDivBySix(model, cl); Model::Node* top_level = nullptr; if (cl) top_level = cl; else top_level = divbysix; Scene* scene = new Scene(); scene->addTopLevelItem( scene->defaultRenderer()->render(nullptr, top_level) ); scene->scheduleUpdate(); scene->listenToModel(model); // Create view MainView* view = new MainView(scene); CHECK_CONDITION(view != nullptr); } }
Modify the OOInteraction test to create an expression from a string.
Modify the OOInteraction test to create an expression from a string.
C++
bsd-3-clause
BalzGuenat/Envision,mgalbier/Envision,Vaishal-shah/Envision,BalzGuenat/Envision,lukedirtwalker/Envision,lukedirtwalker/Envision,Vaishal-shah/Envision,lukedirtwalker/Envision,dimitar-asenov/Envision,patrick-luethi/Envision,BalzGuenat/Envision,dimitar-asenov/Envision,patrick-luethi/Envision,mgalbier/Envision,lukedirtwalker/Envision,BalzGuenat/Envision,dimitar-asenov/Envision,dimitar-asenov/Envision,dimitar-asenov/Envision,lukedirtwalker/Envision,Vaishal-shah/Envision,BalzGuenat/Envision,Vaishal-shah/Envision,mgalbier/Envision,lukedirtwalker/Envision,mgalbier/Envision,dimitar-asenov/Envision,mgalbier/Envision,patrick-luethi/Envision,Vaishal-shah/Envision,mgalbier/Envision,BalzGuenat/Envision,Vaishal-shah/Envision,patrick-luethi/Envision
0bf97f8077d502027a904e9aaeb5b3f191e9395d
src/gen.cpp
src/gen.cpp
#include "gen.h" #ifdef __linux__ #include <linux/limits.h> #endif #include <iostream> #include <fstream> #include <string.h> #include <unistd.h> #include <libgen.h> #include <dirent.h> #include <sys/param.h> #include <sys/stat.h> #include <sys/types.h> #define BASEDIR DefineBaseDir() Generate::Generate() {}; Generate::~Generate() {}; char *Generate::DefineBaseDir() { char *currentDir = get_current_dir_name(); return currentDir; } void Generate::CheckFiles() { struct dirent *ent; DIR *dp; char path[MAXPATHLEN]; dp = opendir(BASEDIR); if (dp == NULL) { printf("Error: Path doesn't exist\n"); return; } while (1) { ent = readdir(dp); if (!ent) { break; } if (ent->d_type == DT_REG) { printf("Regular file: %s\n", ent->d_name); } if (ent->d_type == DT_DIR) { if (strcmp(ent->d_name, "..") != 0 && strcmp(ent->d_name, ".") != 0) { int path_len; path_len = snprintf(path, MAXPATHLEN, "%s", ent->d_name); printf("%s\n", path); if (path_len >= MAXPATHLEN) { printf("Error: Path length has gotten too long\n"); } } } } if (closedir(dp)) { printf("Couldn't close '%s'\n", BASEDIR); } } int Generate::CheckMake() { defaultMakefile = MAKEFILE; // Get current working directory if (getcwd(cwd, MAXPATHLEN) != NULL) { printf("Current working directory: %s\n", cwd); struct stat buffer; int exist = stat(defaultMakefile, &buffer); if (exist == 0) { printf("Makefile present\n"); return 1; } else { printf("No Makefile present\n"); return -1; } } return 0; } void Generate::GenBlankConfig() { char fileName[PATH_MAX]; snprintf(fileName, sizeof(fileName), "%s.ybf", basename(BASEDIR)); printf("New build file written as: %s\n", fileName); newConfig = fopen(fileName, "w+"); }
#include "gen.h" #ifdef __linux__ #include <linux/limits.h> #endif #include <err.h> #include <errno.h> #include <dirent.h> #include <libgen.h> #include <regex.h> #include <string.h> #include <unistd.h> #include <sys/param.h> #include <sys/stat.h> #include <sys/types.h> #include <fstream> #include <iostream> #include <iomanip> #define BASEDIR DefineBaseDir() Generate::Generate() {}; Generate::~Generate() {}; char *Generate::DefineBaseDir() { return currentDir; } enum { FS_OK = 0, FS_BADPattern, FS_NAMETOOLONG, FS_BADIO, }; int Generate::WalkRecur(const char *DirName, regex_t *Expr, int Spec) { struct dirent *Ent; DIR *Dir; struct stat St; char PathName[FILENAME_MAX]; int Res = FS_OK; int len = strlen(DirName); if (len >= FILENAME_MAX - 1) return FS_NAMETOOLONG; strcpy(PathName, DirName); PathName[len++] = '/'; if (!(Dir = opendir(DirName))) { warn("can't open %s", DirName); return FS_BADIO; } errno = 0; while ((Ent = readdir(Dir))) { if (!(Spec & FS_DOTFILES) && Ent->d_name[0] == '.') continue; if (!strcmp(Ent->d_name, ".") || !strcmp(Ent->d_name, "..")) continue; strncpy(PathName + len, Ent->d_name, FILENAME_MAX - len); if (lstat(PathName, &St) == -1) { warn("Can't stat %s", PathName); Res = FS_BADIO; continue; } if (S_ISLNK(St.st_mode) && !(Spec & FS_FOLLOWLINK)) continue; if (S_ISDIR(St.st_mode)) { if ((Spec & FS_RECURSIVE)) WalkRecur(PathName, Expr, Spec); if (!(Spec & FS_MATCHDIRS)) continue; } if (!regexec(Expr, PathName, 0, 0, 0)) printf("%s\n", PathName); } if (Dir) closedir(Dir); return Res ? Res : errno ? FS_BADIO : FS_OK; } int Generate::WalkDir(const char *DirName, char *Pattern, int Spec) { regex_t r; int Res; if (regcomp(&r, Pattern, REG_EXTENDED | REG_NOSUB)) return FS_BADPattern; Res = WalkRecur(DirName, &r, Spec); regfree(&r); return Res; } int Generate::CheckMake() { defaultMakefile = MAKEFILE; // Get current working directory if (getcwd(cwd, MAXPATHLEN) != NULL) { printf("Current working directory: %s\n", cwd); struct stat buffer; int exist = stat(defaultMakefile, &buffer); if (exist == 0) { printf("Makefile present\n"); return 1; } else { printf("No Makefile present\n"); return -1; } } return 0; } int Generate::CheckConfigExists() { char fileName[PATH_MAX]; snprintf(fileName, sizeof(fileName), "%s.ybf", basename(BASEDIR)); if (access(fileName, F_OK) != -1) { return 1; } else { return -1; } return 0; } void Generate::GenBlankConfig() { char fileName[PATH_MAX]; snprintf(fileName, sizeof(fileName), "%s.ybf", basename(BASEDIR)); printf("New build file written as: %s\n", fileName); newConfig = fopen(fileName, "w+"); } void Generate::WriteMake() { if (CheckConfigExists() == 1) { printf("yabs build file exists\n"); return; } else { printf("yabs build file does not exist\n"); } return; } int Generate::GenMakeFromTemplate() { if (CheckMake() != 1) { std::cout << std::setfill('#') << std::setw(80) << "#" << std::endl; std::cout << std::setfill('#') << std::setw(2) << "#" << "\t\t\tMakefile Generated with yabs" << std::endl; std::cout << std::setfill('#') << std::setw(80) << "#" << std::endl; return 1; } else { return -1; } }
Add member functions, fix includes
Add member functions, fix includes - Add member functions for walking a directory recursively. This still needs to be implemented in a way that maps files to an array or vector for later access. Other new member functions serve as more boilerplate than anything. - Fix includes order Signed-off-by: Alberto Corona <[email protected]>
C++
bsd-3-clause
0X1A/yabs,0X1A/yabs,0X1A/yabs,0X1A/yabs
3e08ab6cdb207039d4695753f0e419c34a35710e
src/search.cpp
src/search.cpp
#include "search.h" #include "evaluate.h" #include <climits> #include <array> #include <cassert> #include <functional> #include <iostream> // TEMP namespace lesschess { // be careful to avoid overflow from INT_MIN == -INT_MIN constexpr int INFINITY = INT_MAX - 1; // Number of moves upper bound: // K -> 8 + 2 castles // Q -> 27 // R -> 14 x 2 = 28 // N -> 8 x 2 = 16 // P -> (2 moves + 2 captures) x 8 = 32 (same as if all 8 pawns could promote) // --> 139 // // Worst worst case is 7 promoted queens => 7 x 27 + 8 x 2 = 394 // 128 is probably safe? 256 is definitely safe since willing to bet the the 7 Qs // position isn't going to happen -- will either be checkmate or stalemate. // TODO: what is the maximum number of possible moves in a position? using Moves = std::vector<Move>; // TODO: change this back to std::array<Move, 256>? constexpr int MAX_DEPTH = 2; void dump_pv(Moves& pv) { for (auto m : pv) { std::cout << m.to_long_algebraic_string() << " "; } std::cout << "\n"; } void print_tabs(int depth_left) { for (int i = 0; i < (MAX_DEPTH - depth_left); ++i) { std::cout << '\t'; } } int alpha_beta(Position& position, int alpha, int beta, int depth, Move move, Moves& pv) { // TODO: check if terminal node (mate, stalemate, etc) // not sure if the fastest way to do that is to check if `nmoves == 0`? if (depth == 0) { int score = evaluate(position); for (int i = 0; i <= MAX_DEPTH; ++i) std::cout << '\t'; std::cout << "evaluate for move=" << move.to_long_algebraic_string() << " " << "score=" << score << " -- "; dump_pv(pv); return position.white_to_move() ? score : -score; } print_tabs(depth); std::cout << "alpha_beta, " << "move=" << move.to_long_algebraic_string() << " " << "wtm=" << position.white_to_move() << " " << "alpha=" << alpha << " " << "beta=" << beta << " " << "depthLeft=" << depth << " " << "\n"; int value = -INFINITY; Savepos sp; Moves moves{256}; int nmoves = position.generate_legal_moves(&moves[0]); for (int i = 0; i < nmoves; ++i) { position.make_move(sp, moves[i]); pv.push_back(moves[i]); value = std::max(value, -alpha_beta(position, /*alpha*/-beta, /*beta*/-alpha, depth - 1, moves[i], pv)); pv.pop_back(); position.undo_move(sp, moves[i]); alpha = std::max(alpha, value); if (alpha >= beta) { break; } } print_tabs(depth); std::cout << "leaving alpha_beta, value=" << value << " "; dump_pv(pv); return value; } SearchResult search(Position& position) { int bestmove = -1; int bestscore = -INFINITY; Savepos sp; Moves moves{256}; int nmoves = position.generate_legal_moves(&moves[0]); Moves pv; for (int i = 0; i < nmoves; ++i) { position.make_move(sp, moves[i]); pv.push_back(moves[i]); std::cout << "evaluating root " << moves[i].to_long_algebraic_string() << " " << "bestScore=" << bestscore << "\n"; // TODO: don't think I should be negating here int score = -alpha_beta(position, /*alpha*/-INFINITY, /*beta*/INFINITY, /*depth*/MAX_DEPTH, moves[i], pv); std::cout << "leaving root " << moves[i].to_long_algebraic_string() << ": " << "score=" << score << " " << "bestScore=" << bestscore << " " << "\n"; position.undo_move(sp, moves[i]); pv.pop_back(); if (score > bestscore) { bestscore = score; bestmove = i; } } assert(bestmove != -1); bestscore = position.white_to_move() ? bestscore : -bestscore; return {moves[bestmove], bestscore}; } } // ~namespace lesschess
#include "search.h" #include "evaluate.h" #include <climits> #include <array> #include <cassert> #include <functional> #include <iostream> // TEMP namespace lesschess { // be careful to avoid overflow from INT_MIN == -INT_MIN constexpr int INFINITY = INT_MAX - 1; // Number of moves upper bound: // K -> 8 + 2 castles // Q -> 27 // R -> 14 x 2 = 28 // N -> 8 x 2 = 16 // P -> (2 moves + 2 captures) x 8 = 32 (same as if all 8 pawns could promote) // --> 139 // // Worst worst case is 7 promoted queens => 7 x 27 + 8 x 2 = 394 // 128 is probably safe? 256 is definitely safe since willing to bet the the 7 Qs // position isn't going to happen -- will either be checkmate or stalemate. // TODO: what is the maximum number of possible moves in a position? using Moves = std::vector<Move>; // TODO: change this back to std::array<Move, 256>? constexpr int MAX_DEPTH = 2; void dump_pv(Moves& pv) { for (auto m : pv) { std::cout << m.to_long_algebraic_string() << " "; } std::cout << "\n"; } void print_tabs(int depth_left) { for (int i = 0; i < (MAX_DEPTH - depth_left); ++i) { std::cout << '\t'; } } int negamax(Position& position, int alpha, int beta, int depth, Move move, Moves& pv) { // TODO: check if terminal node (mate, stalemate, etc) // not sure if the fastest way to do that is to check if `nmoves == 0`? if (depth == 0) { int score = evaluate(position); #if 0 print_tabs(MAX_DEPTH + 1); std::cout << "evaluate for move=" << move.to_long_algebraic_string() << " " << "score=" << score << " -- "; dump_pv(pv); #endif return position.white_to_move() ? score : -score; } #if 0 print_tabs(depth); std::cout << "alpha_beta, " << "move=" << move.to_long_algebraic_string() << " " << "wtm=" << position.white_to_move() << " " << "alpha=" << alpha << " " << "beta=" << beta << " " << "depthLeft=" << depth << " " << "\n"; #endif int value = -INFINITY; Savepos sp; Moves moves{256}; int nmoves = position.generate_legal_moves(&moves[0]); for (int i = 0; i < nmoves; ++i) { position.make_move(sp, moves[i]); pv.push_back(moves[i]); value = std::max(value, -negamax(position, /*alpha*/-beta, /*beta*/-alpha, depth - 1, moves[i], pv)); pv.pop_back(); position.undo_move(sp, moves[i]); alpha = std::max(alpha, value); if (alpha >= beta) { break; } } #if 0 print_tabs(depth); std::cout << "leaving alpha_beta, value=" << value << " "; dump_pv(pv); #endif return value; } SearchResult search(Position& position) { int bestmove = -1; int bestscore = -INFINITY; Savepos sp; Moves moves{256}; int nmoves = position.generate_legal_moves(&moves[0]); Moves pv; for (int i = 0; i < nmoves; ++i) { position.make_move(sp, moves[i]); pv.push_back(moves[i]); #if 0 std::cout << "evaluating root " << moves[i].to_long_algebraic_string() << " " << "bestScore=" << bestscore << "\n"; #endif // TODO: don't think I should be negating here int score = -negamax(position, /*alpha*/-INFINITY, /*beta*/INFINITY, /*depth*/MAX_DEPTH, moves[i], pv); #if 0 std::cout << "leaving root " << moves[i].to_long_algebraic_string() << ": " << "score=" << score << " " << "bestScore=" << bestscore << " " << "\n"; #endif position.undo_move(sp, moves[i]); pv.pop_back(); if (score > bestscore) { bestscore = score; bestmove = i; } } assert(bestmove != -1); bestscore = position.white_to_move() ? bestscore : -bestscore; return {moves[bestmove], bestscore}; } } // ~namespace lesschess
change name to negamax
change name to negamax
C++
mit
selavy/lesschess,selavy/lesschess,selavy/lesschess
ceb942375d8b77c367e3792e848b3f143ec8b6be
src/h2f.cpp
src/h2f.cpp
/* Copyright (c) 2018 - present Advanced Micro Devices, Inc. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <cstdint> #include <algorithm> // conversion routines between float and half precision static inline std::uint32_t f32_as_u32(float f) { union { float f; std::uint32_t u; } v; v.f = f; return v.u; } static inline float u32_as_f32(std::uint32_t u) { union { float f; std::uint32_t u; } v; v.u = u; return v.f; } static inline int clamp_int(int i, int l, int h) { return std::min(std::max(i, l), h); } // half to float, the f16 is in the low 16 bits of the input argument a static inline float __convert_half_to_float(std::uint32_t a) noexcept { std::uint32_t u = ((a << 13) + 0x70000000U) & 0x8fffe000U; std::uint32_t v = f32_as_u32(u32_as_f32(u) * 0x1.0p+112f) + 0x38000000U; u = (a & 0x7fff) != 0 ? v : u; return u32_as_f32(u) * 0x1.0p-112f; } // float to half with nearest even rounding // The lower 16 bits of the result is the bit pattern for the f16 static inline std::uint32_t __convert_float_to_half(float a) noexcept { std::uint32_t u = f32_as_u32(a); int e = static_cast<int>((u >> 23) & 0xff) - 127 + 15; std::uint32_t m = ((u >> 11) & 0xffe) | ((u & 0xfff) != 0); std::uint32_t i = 0x7c00 | (m != 0 ? 0x0200 : 0); std::uint32_t n = ((std::uint32_t)e << 12) | m; std::uint32_t s = (u >> 16) & 0x8000; int b = clamp_int(1-e, 0, 13); std::uint32_t d = (0x1000 | m) >> b; d |= (d << b) != (0x1000 | m); std::uint32_t v = e < 1 ? d : n; v = (v >> 2) + (((v & 0x7) == 3) | ((v & 0x7) > 5)); v = e > 30 ? 0x7c00 : v; v = e == 143 ? i : v; return s | v; } // On machines without fp16 instructions, clang lowers llvm.convert.from.fp16 // to call of this function. extern "C" float __gnu_h2f_ieee(unsigned short h){ return __convert_half_to_float((std::uint32_t) h); } // On machines without fp16 instructions, clang lowers llvm.convert.to.fp16 // to call of this function. extern "C" unsigned short __gnu_f2h_ieee(float f){ return (unsigned short)__convert_float_to_half(f); }
/* Copyright (c) 2018 - present Advanced Micro Devices, Inc. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <cstdint> #include <algorithm> // conversion routines between float and half precision static inline std::uint32_t f32_as_u32(float f) { union { float f; std::uint32_t u; } v; v.f = f; return v.u; } static inline float u32_as_f32(std::uint32_t u) { union { float f; std::uint32_t u; } v; v.u = u; return v.f; } static inline int clamp_int(int i, int l, int h) { return std::min(std::max(i, l), h); } // half to float, the f16 is in the low 16 bits of the input argument a static inline float __convert_half_to_float(std::uint32_t a) noexcept { std::uint32_t u = ((a << 13) + 0x70000000U) & 0x8fffe000U; std::uint32_t v = f32_as_u32(u32_as_f32(u) * 0x1.0p+112f) + 0x38000000U; u = (a & 0x7fff) != 0 ? v : u; return u32_as_f32(u) * 0x1.0p-112f; } // float to half with nearest even rounding // The lower 16 bits of the result is the bit pattern for the f16 static inline std::uint32_t __convert_float_to_half(float a) noexcept { std::uint32_t u = f32_as_u32(a); int e = static_cast<int>((u >> 23) & 0xff) - 127 + 15; std::uint32_t m = ((u >> 11) & 0xffe) | ((u & 0xfff) != 0); std::uint32_t i = 0x7c00 | (m != 0 ? 0x0200 : 0); std::uint32_t n = ((std::uint32_t)e << 12) | m; std::uint32_t s = (u >> 16) & 0x8000; int b = clamp_int(1-e, 0, 13); std::uint32_t d = (0x1000 | m) >> b; d |= (d << b) != (0x1000 | m); std::uint32_t v = e < 1 ? d : n; v = (v >> 2) + (((v & 0x7) == 3) | ((v & 0x7) > 5)); v = e > 30 ? 0x7c00 : v; v = e == 143 ? i : v; return s | v; } // On machines without fp16 instructions, clang lowers llvm.convert.from.fp16 // to call of this function. extern "C" __attribute__((visibility("default"))) float __gnu_h2f_ieee(unsigned short h){ return __convert_half_to_float((std::uint32_t) h); } // On machines without fp16 instructions, clang lowers llvm.convert.to.fp16 // to call of this function. extern "C" __attribute__((visibility("default"))) unsigned short __gnu_f2h_ieee(float f){ return (unsigned short)__convert_float_to_half(f); }
Make __gnu_h2f_ieee and __gnu_f2h_ieee visible
Make __gnu_h2f_ieee and __gnu_f2h_ieee visible Make __gnu_h2f_ieee and __gnu_f2h_ieee visible so that hipTestHalf test can succeed in Clang compiler + Hcc RT. Change-Id: I5f7d5db19e559b3b66356f0170a8dbc1e5505f3e
C++
mit
ROCm-Developer-Tools/HIP,ROCm-Developer-Tools/HIP,ROCm-Developer-Tools/HIP,ROCm-Developer-Tools/HIP,ROCm-Developer-Tools/HIP
7dbf21489320bba0a7db7e6ea5b584878d3e2803
src/simple.cpp
src/simple.cpp
#include <iostream> #include <chrono> #include <random> #include <numeric> #include <blaze/Math.h> #include "etl/etl.hpp" #include "etl/multiplication.hpp" typedef std::chrono::high_resolution_clock timer_clock; typedef std::chrono::milliseconds milliseconds; typedef std::chrono::microseconds microseconds; namespace { template<typename T, std::enable_if_t<std::is_same<T, blaze::DynamicMatrix<double>>::value, int> = 42> void randomize_double(T& container){ static std::default_random_engine rand_engine(std::time(nullptr)); static std::uniform_real_distribution<double> real_distribution(-1000.0, 1000.0); static auto generator = std::bind(real_distribution, rand_engine); for(std::size_t i=0UL; i<container.rows(); ++i ) { for(std::size_t j=0UL; j<container.columns(); ++j ) { container(i,j) = generator(); } } } template<typename T, std::enable_if_t<!std::is_same<T, blaze::DynamicMatrix<double>>::value, int> = 42> void randomize_double(T& container){ static std::default_random_engine rand_engine(std::time(nullptr)); static std::uniform_real_distribution<double> real_distribution(-1000.0, 1000.0); static auto generator = std::bind(real_distribution, rand_engine); for(auto& v : container){ v = generator(); } } template<typename T1> void b_randomize(T1& container){ randomize_double(container); } template<typename T1, typename... TT> void b_randomize(T1& container, TT&... containers){ randomize_double(container); b_randomize(containers...); } std::string clean_duration(std::string value){ while(value.size() > 1 && value.back() == '0'){ value.pop_back(); } return value; } std::string duration_str(std::size_t duration_us){ if(duration_us > 1000 * 1000){ return clean_duration(std::to_string(duration_us / 1000.0 / 1000.0)) + "s"; } else if(duration_us > 1000){ return clean_duration(std::to_string(duration_us / 1000.0)) + "ms"; } else { return clean_duration(std::to_string(duration_us)) + "us"; } } template<typename Functor, typename... T> auto measure_only(Functor&& functor, T&... references){ for(std::size_t i = 0; i < 100; ++i){ b_randomize(references...); functor(); } std::size_t duration_acc = 0; for(std::size_t i = 0; i < 100; ++i){ b_randomize(references...); auto start_time = timer_clock::now(); functor(); auto end_time = timer_clock::now(); auto duration = std::chrono::duration_cast<microseconds>(end_time - start_time); duration_acc += duration.count(); } return duration_acc; } template<typename Functor, typename... T> void measure(const std::string& title, const std::string& reference, Functor&& functor, T&... references){ std::cout << title << " took " << duration_str(measure_only(functor, references...)) << " (reference: " << reference << ")\n"; } template<template<typename, std::size_t> class T, std::size_t D> struct add_static { static auto get(){ T<double, D> a,b,c; return measure_only([&a, &b, &c](){c = a + b;}, a, b); } }; template<template<typename> class T, std::size_t D> struct add_dynamic { static auto get(){ T<double> a(D), b(D), c(D); return measure_only([&a, &b, &c](){c = a + b;}, a, b); } }; template<template<typename> class T, std::size_t D> struct add_complex { static auto get(){ T<double> a(D), b(D), c(D); return measure_only([&a, &b, &c](){c = a + b + a + b + a + a + b + a + a;}, a, b); } }; template<template<typename> class T, std::size_t D> struct mix { static auto get(){ T<double> a(D), b(D), c(D); return measure_only([&a, &b, &c](){c = a + a * 5.9 + a + b - b / 2.3 - a + b * 1.1;}, a, b); } }; template<template<typename> class T, std::size_t D1, std::size_t D2> struct mix_matrix { static auto get(){ T<double> a(D1, D2), b(D1, D2), c(D1, D2); return measure_only([&a, &b, &c](){c = a + a * 5.9 + a + b - b / 2.3 - a + b * 1.1;}, a, b); } }; template<template<typename> class T, std::size_t D1, std::size_t D2, std::size_t D3, typename Enable = void> struct mmul { static auto get(){ T<double> a(D1, D2), b(D2, D3), c(D1, D3); return measure_only([&a, &b, &c](){etl::mmul(a, b, c);}, a, b); } }; template<template<typename> class T, std::size_t D1, std::size_t D2, std::size_t D3> struct mmul<T, D1, D2, D3, std::enable_if_t<std::is_same<T<double>, blaze::DynamicMatrix<double>>::value>> { static auto get(){ T<double> a(D1, D2), b(D2, D3), c(D1, D3); return measure_only([&a, &b, &c](){c = a * b;}, a, b); } }; std::string format(std::string value, std::size_t max){ return value + (value.size() < max ? std::string(std::max(0UL, max - value.size()), ' ') : ""); } template<template<template<typename, std::size_t> class, std::size_t> class T, template<typename, std::size_t> class B, template<typename, std::size_t> class E, std::size_t D> void bench_static(const std::string& title){ std::cout << "| "; std::cout << format(title + ":" + std::to_string(D), 29) << " | "; std::cout << format(duration_str(T<B,D>::get()), 9) << " | "; std::cout << format(duration_str(T<E,D>::get()), 9) << " | "; std::cout << std::endl; } template<template<template<typename> class, std::size_t> class T, template<typename> class B, template<typename> class E, std::size_t D> void bench_dyn(const std::string& title){ std::cout << "| "; std::cout << format(title + ":" + std::to_string(D), 29) << " | "; std::cout << format(duration_str(T<B,D>::get()), 9) << " | "; std::cout << format(duration_str(T<E,D>::get()), 9) << " | "; std::cout << std::endl; } template<template<template<typename> class, std::size_t, std::size_t> class T, template<typename> class B, template<typename> class E, std::size_t D1, std::size_t D2> void bench_dyn(const std::string& title){ std::cout << "| "; std::cout << format(title + ":" + std::to_string(D1) + "x" + std::to_string(D2), 29) << " | "; std::cout << format(duration_str(T<B,D1,D2>::get()), 9) << " | "; std::cout << format(duration_str(T<E,D1,D2>::get()), 9) << " | "; std::cout << std::endl; } template<template<template<typename> class, std::size_t, std::size_t, std::size_t, typename = void> class T, template<typename> class B, template<typename> class E, std::size_t D1, std::size_t D2, std::size_t D3> void bench_dyn(const std::string& title){ std::cout << "| "; std::cout << format(title + ":" + std::to_string(D1) + "x" + std::to_string(D2) + "x" + std::to_string(D3), 29) << " | "; std::cout << format(duration_str(T<B,D1,D2,D3>::get()), 9) << " | "; std::cout << format(duration_str(T<E,D1,D2,D3>::get()), 9) << " | "; std::cout << std::endl; } template<typename T, std::size_t D> using etl_static_vector = etl::fast_vector<T, D>; template<typename T, std::size_t D> using blaze_static_vector = blaze::StaticVector<T, D>; template<typename T> using etl_dyn_vector = etl::dyn_vector<T>; template<typename T> using blaze_dyn_vector = blaze::DynamicVector<T>; template<typename T> using etl_dyn_matrix = etl::dyn_matrix<T>; template<typename T> using blaze_dyn_matrix = blaze::DynamicMatrix<T>; } //end of anonymous namespace int main(){ std::cout << "| Name | Blaze | ETL |" << std::endl; std::cout << "---------------------------------------------------------" << std::endl; bench_static<add_static, blaze_static_vector, etl_static_vector, 8192>("static_add"); bench_dyn<add_dynamic, blaze_dyn_vector, etl_dyn_vector, 1 * 32768>("dynamic_add"); bench_dyn<add_dynamic, blaze_dyn_vector, etl_dyn_vector, 2 * 32768>("dynamic_add"); bench_dyn<add_dynamic, blaze_dyn_vector, etl_dyn_vector, 4 * 32768>("dynamic_add"); bench_dyn<add_complex, blaze_dyn_vector, etl_dyn_vector, 1 * 32768>("dynamic_add_complex"); bench_dyn<add_complex, blaze_dyn_vector, etl_dyn_vector, 2 * 32768>("dynamic_add_complex"); bench_dyn<add_complex, blaze_dyn_vector, etl_dyn_vector, 4 * 32768>("dynamic_add_complex"); bench_dyn<mix, blaze_dyn_vector, etl_dyn_vector, 1 * 32768>("dynamic_mix"); bench_dyn<mix, blaze_dyn_vector, etl_dyn_vector, 2 * 32768>("dynamic_mix"); bench_dyn<mix, blaze_dyn_vector, etl_dyn_vector, 4 * 32768>("dynamic_mix"); bench_dyn<mix_matrix, blaze_dyn_matrix, etl_dyn_matrix, 256, 256>("dynamic_mix_matrix"); bench_dyn<mix_matrix, blaze_dyn_matrix, etl_dyn_matrix, 512, 512>("dynamic_mix_matrix"); bench_dyn<mix_matrix, blaze_dyn_matrix, etl_dyn_matrix, 578, 769>("dynamic_mix_matrix"); bench_dyn<mmul, blaze_dyn_matrix, etl_dyn_matrix, 128,32,64>("dynamic_mmul"); bench_dyn<mmul, blaze_dyn_matrix, etl_dyn_matrix, 128,128,128>("dynamic_mmul"); bench_dyn<mmul, blaze_dyn_matrix, etl_dyn_matrix, 256,128,256>("dynamic_mmul"); bench_dyn<mmul, blaze_dyn_matrix, etl_dyn_matrix, 256,256,256>("dynamic_mmul"); bench_dyn<mmul, blaze_dyn_matrix, etl_dyn_matrix, 300,200,400>("dynamic_mmul"); bench_dyn<mmul, blaze_dyn_matrix, etl_dyn_matrix, 512,512,512>("dynamic_mmul"); std::cout << "---------------------------------------------------------" << std::endl; return 0; }
#include <iostream> #include <chrono> #include <random> #include <numeric> #include <blaze/Math.h> #include "etl/etl.hpp" #include "etl/multiplication.hpp" typedef std::chrono::high_resolution_clock timer_clock; typedef std::chrono::milliseconds milliseconds; typedef std::chrono::microseconds microseconds; namespace { template<typename T, std::enable_if_t<std::is_same<T, blaze::DynamicMatrix<double>>::value, int> = 42> void randomize_double(T& container){ static std::default_random_engine rand_engine(std::time(nullptr)); static std::uniform_real_distribution<double> real_distribution(-1000.0, 1000.0); static auto generator = std::bind(real_distribution, rand_engine); for(std::size_t i=0UL; i<container.rows(); ++i ) { for(std::size_t j=0UL; j<container.columns(); ++j ) { container(i,j) = generator(); } } } template<typename T, std::enable_if_t<!std::is_same<T, blaze::DynamicMatrix<double>>::value, int> = 42> void randomize_double(T& container){ static std::default_random_engine rand_engine(std::time(nullptr)); static std::uniform_real_distribution<double> real_distribution(-1000.0, 1000.0); static auto generator = std::bind(real_distribution, rand_engine); for(auto& v : container){ v = generator(); } } void b_randomize(){} template<typename T1, typename... TT> void b_randomize(T1& container, TT&... containers){ randomize_double(container); b_randomize(containers...); } std::string clean_duration(std::string value){ while(value.size() > 1 && value.back() == '0'){ value.pop_back(); } return value; } std::string duration_str(std::size_t duration_us){ if(duration_us > 1000 * 1000){ return clean_duration(std::to_string(duration_us / 1000.0 / 1000.0)) + "s"; } else if(duration_us > 1000){ return clean_duration(std::to_string(duration_us / 1000.0)) + "ms"; } else { return clean_duration(std::to_string(duration_us)) + "us"; } } template<typename Functor, typename... T> auto measure_only(Functor&& functor, T&... references){ for(std::size_t i = 0; i < 100; ++i){ b_randomize(references...); functor(); } std::size_t duration_acc = 0; for(std::size_t i = 0; i < 100; ++i){ b_randomize(references...); auto start_time = timer_clock::now(); functor(); auto end_time = timer_clock::now(); auto duration = std::chrono::duration_cast<microseconds>(end_time - start_time); duration_acc += duration.count(); } return duration_acc; } template<typename Functor, typename... T> void measure(const std::string& title, const std::string& reference, Functor&& functor, T&... references){ std::cout << title << " took " << duration_str(measure_only(functor, references...)) << " (reference: " << reference << ")\n"; } template<template<typename, std::size_t> class T, std::size_t D> struct add_static { static auto get(){ T<double, D> a,b,c; return measure_only([&a, &b, &c](){c = a + b;}, a, b); } }; template<template<typename> class T, std::size_t D> struct add_dynamic { static auto get(){ T<double> a(D), b(D), c(D); return measure_only([&a, &b, &c](){c = a + b;}, a, b); } }; template<template<typename, std::size_t> class T, std::size_t D> struct scale_static { static auto get(){ T<double, D> c; return measure_only([&c](){c = 3.3;}); } }; template<template<typename> class T, std::size_t D> struct scale_dynamic { static auto get(){ T<double> c(D); return measure_only([&c](){c *= 3.3;}); } }; template<template<typename> class T, std::size_t D> struct add_complex { static auto get(){ T<double> a(D), b(D), c(D); return measure_only([&a, &b, &c](){c = a + b + a + b + a + a + b + a + a;}, a, b); } }; template<template<typename> class T, std::size_t D> struct mix { static auto get(){ T<double> a(D), b(D), c(D); return measure_only([&a, &b, &c](){c = a + a * 5.9 + a + b - b / 2.3 - a + b * 1.1;}, a, b); } }; template<template<typename> class T, std::size_t D1, std::size_t D2> struct mix_matrix { static auto get(){ T<double> a(D1, D2), b(D1, D2), c(D1, D2); return measure_only([&a, &b, &c](){c = a + a * 5.9 + a + b - b / 2.3 - a + b * 1.1;}, a, b); } }; template<template<typename> class T, std::size_t D1, std::size_t D2, std::size_t D3, typename Enable = void> struct mmul { static auto get(){ T<double> a(D1, D2), b(D2, D3), c(D1, D3); return measure_only([&a, &b, &c](){etl::mmul(a, b, c);}, a, b); } }; template<template<typename> class T, std::size_t D1, std::size_t D2, std::size_t D3> struct mmul<T, D1, D2, D3, std::enable_if_t<std::is_same<T<double>, blaze::DynamicMatrix<double>>::value>> { static auto get(){ T<double> a(D1, D2), b(D2, D3), c(D1, D3); return measure_only([&a, &b, &c](){c = a * b;}, a, b); } }; std::string format(std::string value, std::size_t max){ return value + (value.size() < max ? std::string(std::max(0UL, max - value.size()), ' ') : ""); } template<template<template<typename, std::size_t> class, std::size_t> class T, template<typename, std::size_t> class B, template<typename, std::size_t> class E, std::size_t D> void bench_static(const std::string& title){ std::cout << "| "; std::cout << format(title + ":" + std::to_string(D), 29) << " | "; std::cout << format(duration_str(T<B,D>::get()), 9) << " | "; std::cout << format(duration_str(T<E,D>::get()), 9) << " | "; std::cout << std::endl; } template<template<template<typename> class, std::size_t> class T, template<typename> class B, template<typename> class E, std::size_t D> void bench_dyn(const std::string& title){ std::cout << "| "; std::cout << format(title + ":" + std::to_string(D), 29) << " | "; std::cout << format(duration_str(T<B,D>::get()), 9) << " | "; std::cout << format(duration_str(T<E,D>::get()), 9) << " | "; std::cout << std::endl; } template<template<template<typename> class, std::size_t, std::size_t> class T, template<typename> class B, template<typename> class E, std::size_t D1, std::size_t D2> void bench_dyn(const std::string& title){ std::cout << "| "; std::cout << format(title + ":" + std::to_string(D1) + "x" + std::to_string(D2), 29) << " | "; std::cout << format(duration_str(T<B,D1,D2>::get()), 9) << " | "; std::cout << format(duration_str(T<E,D1,D2>::get()), 9) << " | "; std::cout << std::endl; } template<template<template<typename> class, std::size_t, std::size_t, std::size_t, typename = void> class T, template<typename> class B, template<typename> class E, std::size_t D1, std::size_t D2, std::size_t D3> void bench_dyn(const std::string& title){ std::cout << "| "; std::cout << format(title + ":" + std::to_string(D1) + "x" + std::to_string(D2) + "x" + std::to_string(D3), 29) << " | "; std::cout << format(duration_str(T<B,D1,D2,D3>::get()), 9) << " | "; std::cout << format(duration_str(T<E,D1,D2,D3>::get()), 9) << " | "; std::cout << std::endl; } template<typename T, std::size_t D> using etl_static_vector = etl::fast_vector<T, D>; template<typename T, std::size_t D> using blaze_static_vector = blaze::StaticVector<T, D>; template<typename T> using etl_dyn_vector = etl::dyn_vector<T>; template<typename T> using blaze_dyn_vector = blaze::DynamicVector<T>; template<typename T> using etl_dyn_matrix = etl::dyn_matrix<T>; template<typename T> using blaze_dyn_matrix = blaze::DynamicMatrix<T>; } //end of anonymous namespace int main(){ std::cout << "| Name | Blaze | ETL |" << std::endl; std::cout << "---------------------------------------------------------" << std::endl; bench_static<add_static, blaze_static_vector, etl_static_vector, 8192>("static_add"); bench_dyn<add_dynamic, blaze_dyn_vector, etl_dyn_vector, 1 * 32768>("dynamic_add"); bench_dyn<add_dynamic, blaze_dyn_vector, etl_dyn_vector, 2 * 32768>("dynamic_add"); bench_dyn<add_dynamic, blaze_dyn_vector, etl_dyn_vector, 4 * 32768>("dynamic_add"); bench_static<scale_static, blaze_static_vector, etl_static_vector, 8192>("static_scale"); bench_dyn<scale_dynamic, blaze_dyn_vector, etl_dyn_vector, 1 * 1024 * 1024>("dynamic_scale"); bench_dyn<scale_dynamic, blaze_dyn_vector, etl_dyn_vector, 2 * 1024 * 1024>("dynamic_scale"); bench_dyn<scale_dynamic, blaze_dyn_vector, etl_dyn_vector, 4 * 1024 * 1024>("dynamic_scale"); bench_dyn<scale_dynamic, blaze_dyn_vector, etl_dyn_vector, 8 * 1024 * 1024>("dynamic_scale"); bench_dyn<add_complex, blaze_dyn_vector, etl_dyn_vector, 1 * 32768>("dynamic_add_complex"); bench_dyn<add_complex, blaze_dyn_vector, etl_dyn_vector, 2 * 32768>("dynamic_add_complex"); bench_dyn<add_complex, blaze_dyn_vector, etl_dyn_vector, 4 * 32768>("dynamic_add_complex"); bench_dyn<mix, blaze_dyn_vector, etl_dyn_vector, 1 * 32768>("dynamic_mix"); bench_dyn<mix, blaze_dyn_vector, etl_dyn_vector, 2 * 32768>("dynamic_mix"); bench_dyn<mix, blaze_dyn_vector, etl_dyn_vector, 4 * 32768>("dynamic_mix"); bench_dyn<mix_matrix, blaze_dyn_matrix, etl_dyn_matrix, 256, 256>("dynamic_mix_matrix"); bench_dyn<mix_matrix, blaze_dyn_matrix, etl_dyn_matrix, 512, 512>("dynamic_mix_matrix"); bench_dyn<mix_matrix, blaze_dyn_matrix, etl_dyn_matrix, 578, 769>("dynamic_mix_matrix"); bench_dyn<mmul, blaze_dyn_matrix, etl_dyn_matrix, 128,32,64>("dynamic_mmul"); bench_dyn<mmul, blaze_dyn_matrix, etl_dyn_matrix, 128,128,128>("dynamic_mmul"); bench_dyn<mmul, blaze_dyn_matrix, etl_dyn_matrix, 256,128,256>("dynamic_mmul"); bench_dyn<mmul, blaze_dyn_matrix, etl_dyn_matrix, 256,256,256>("dynamic_mmul"); bench_dyn<mmul, blaze_dyn_matrix, etl_dyn_matrix, 300,200,400>("dynamic_mmul"); bench_dyn<mmul, blaze_dyn_matrix, etl_dyn_matrix, 512,512,512>("dynamic_mmul"); std::cout << "---------------------------------------------------------" << std::endl; return 0; }
Add scale to the benchmark
Add scale to the benchmark
C++
mit
wichtounet/etl_vs_blaze
ff5eeb6beebda3cb406906d8cff40a5fb41eedf2
src/thread.cpp
src/thread.cpp
//===------------------------- thread.cpp----------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "__config" #ifndef _LIBCPP_HAS_NO_THREADS #include "thread" #include "exception" #include "vector" #include "future" #include "limits" #include <sys/types.h> #if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__)) # include <sys/param.h> # if defined(BSD) # include <sys/sysctl.h> # endif // defined(BSD) #endif // defined(__unix__) || (defined(__APPLE__) && defined(__MACH__)) #if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__)) # include <unistd.h> #endif // defined(__unix__) || (defined(__APPLE__) && defined(__MACH__)) #if defined(__NetBSD__) #pragma weak pthread_create // Do not create libpthread dependency #endif #if defined(_LIBCPP_WIN32API) #include <windows.h> #endif // defined(_LIBCPP_WIN32API) _LIBCPP_BEGIN_NAMESPACE_STD thread::~thread() { if (!__libcpp_thread_isnull(&__t_)) terminate(); } void thread::join() { int ec = EINVAL; if (!__libcpp_thread_isnull(&__t_)) { ec = __libcpp_thread_join(&__t_); if (ec == 0) __t_ = _LIBCPP_NULL_THREAD; } if (ec) __throw_system_error(ec, "thread::join failed"); } void thread::detach() { int ec = EINVAL; if (!__libcpp_thread_isnull(&__t_)) { ec = __libcpp_thread_detach(&__t_); if (ec == 0) __t_ = _LIBCPP_NULL_THREAD; } if (ec) __throw_system_error(ec, "thread::detach failed"); } unsigned thread::hardware_concurrency() _NOEXCEPT { #if defined(CTL_HW) && defined(HW_NCPU) unsigned n; int mib[2] = {CTL_HW, HW_NCPU}; std::size_t s = sizeof(n); sysctl(mib, 2, &n, &s, 0, 0); return n; #elif defined(_SC_NPROCESSORS_ONLN) long result = sysconf(_SC_NPROCESSORS_ONLN); // sysconf returns -1 if the name is invalid, the option does not exist or // does not have a definite limit. // if sysconf returns some other negative number, we have no idea // what is going on. Default to something safe. if (result < 0) return 0; return static_cast<unsigned>(result); #elif defined(_LIBCPP_WIN32API) SYSTEM_INFO info; GetSystemInfo(&info); return info.dwNumberOfProcessors; #else // defined(CTL_HW) && defined(HW_NCPU) // TODO: grovel through /proc or check cpuid on x86 and similar // instructions on other architectures. # if defined(_LIBCPP_MSVC) _LIBCPP_WARNING("hardware_concurrency not yet implemented") # else # warning hardware_concurrency not yet implemented # endif return 0; // Means not computable [thread.thread.static] #endif // defined(CTL_HW) && defined(HW_NCPU) } namespace this_thread { void sleep_for(const chrono::nanoseconds& ns) { if (ns > chrono::nanoseconds::zero()) { __libcpp_thread_sleep_for(ns); } } } // this_thread __thread_specific_ptr<__thread_struct>& __thread_local_data() { static __thread_specific_ptr<__thread_struct> __p; return __p; } // __thread_struct_imp template <class T> class _LIBCPP_HIDDEN __hidden_allocator { public: typedef T value_type; T* allocate(size_t __n) {return static_cast<T*>(::operator new(__n * sizeof(T)));} void deallocate(T* __p, size_t) {::operator delete(static_cast<void*>(__p));} size_t max_size() const {return size_t(~0) / sizeof(T);} }; class _LIBCPP_HIDDEN __thread_struct_imp { typedef vector<__assoc_sub_state*, __hidden_allocator<__assoc_sub_state*> > _AsyncStates; typedef vector<pair<condition_variable*, mutex*>, __hidden_allocator<pair<condition_variable*, mutex*> > > _Notify; _AsyncStates async_states_; _Notify notify_; __thread_struct_imp(const __thread_struct_imp&); __thread_struct_imp& operator=(const __thread_struct_imp&); public: __thread_struct_imp() {} ~__thread_struct_imp(); void notify_all_at_thread_exit(condition_variable* cv, mutex* m); void __make_ready_at_thread_exit(__assoc_sub_state* __s); }; __thread_struct_imp::~__thread_struct_imp() { for (_Notify::iterator i = notify_.begin(), e = notify_.end(); i != e; ++i) { i->second->unlock(); i->first->notify_all(); } for (_AsyncStates::iterator i = async_states_.begin(), e = async_states_.end(); i != e; ++i) { (*i)->__make_ready(); (*i)->__release_shared(); } } void __thread_struct_imp::notify_all_at_thread_exit(condition_variable* cv, mutex* m) { notify_.push_back(pair<condition_variable*, mutex*>(cv, m)); } void __thread_struct_imp::__make_ready_at_thread_exit(__assoc_sub_state* __s) { async_states_.push_back(__s); __s->__add_shared(); } // __thread_struct __thread_struct::__thread_struct() : __p_(new __thread_struct_imp) { } __thread_struct::~__thread_struct() { delete __p_; } void __thread_struct::notify_all_at_thread_exit(condition_variable* cv, mutex* m) { __p_->notify_all_at_thread_exit(cv, m); } void __thread_struct::__make_ready_at_thread_exit(__assoc_sub_state* __s) { __p_->__make_ready_at_thread_exit(__s); } _LIBCPP_END_NAMESPACE_STD #endif // !_LIBCPP_HAS_NO_THREADS
//===------------------------- thread.cpp----------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "__config" #ifndef _LIBCPP_HAS_NO_THREADS #include "thread" #include "exception" #include "vector" #include "future" #include "limits" #include <sys/types.h> #if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__)) # include <sys/param.h> # if defined(BSD) # include <sys/sysctl.h> # endif // defined(BSD) #endif // defined(__unix__) || (defined(__APPLE__) && defined(__MACH__)) #if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__)) || defined(__CloudABI__) # include <unistd.h> #endif // defined(__unix__) || (defined(__APPLE__) && defined(__MACH__)) || defined(__CloudABI__) #if defined(__NetBSD__) #pragma weak pthread_create // Do not create libpthread dependency #endif #if defined(_LIBCPP_WIN32API) #include <windows.h> #endif // defined(_LIBCPP_WIN32API) _LIBCPP_BEGIN_NAMESPACE_STD thread::~thread() { if (!__libcpp_thread_isnull(&__t_)) terminate(); } void thread::join() { int ec = EINVAL; if (!__libcpp_thread_isnull(&__t_)) { ec = __libcpp_thread_join(&__t_); if (ec == 0) __t_ = _LIBCPP_NULL_THREAD; } if (ec) __throw_system_error(ec, "thread::join failed"); } void thread::detach() { int ec = EINVAL; if (!__libcpp_thread_isnull(&__t_)) { ec = __libcpp_thread_detach(&__t_); if (ec == 0) __t_ = _LIBCPP_NULL_THREAD; } if (ec) __throw_system_error(ec, "thread::detach failed"); } unsigned thread::hardware_concurrency() _NOEXCEPT { #if defined(CTL_HW) && defined(HW_NCPU) unsigned n; int mib[2] = {CTL_HW, HW_NCPU}; std::size_t s = sizeof(n); sysctl(mib, 2, &n, &s, 0, 0); return n; #elif defined(_SC_NPROCESSORS_ONLN) long result = sysconf(_SC_NPROCESSORS_ONLN); // sysconf returns -1 if the name is invalid, the option does not exist or // does not have a definite limit. // if sysconf returns some other negative number, we have no idea // what is going on. Default to something safe. if (result < 0) return 0; return static_cast<unsigned>(result); #elif defined(_LIBCPP_WIN32API) SYSTEM_INFO info; GetSystemInfo(&info); return info.dwNumberOfProcessors; #else // defined(CTL_HW) && defined(HW_NCPU) // TODO: grovel through /proc or check cpuid on x86 and similar // instructions on other architectures. # if defined(_LIBCPP_MSVC) _LIBCPP_WARNING("hardware_concurrency not yet implemented") # else # warning hardware_concurrency not yet implemented # endif return 0; // Means not computable [thread.thread.static] #endif // defined(CTL_HW) && defined(HW_NCPU) } namespace this_thread { void sleep_for(const chrono::nanoseconds& ns) { if (ns > chrono::nanoseconds::zero()) { __libcpp_thread_sleep_for(ns); } } } // this_thread __thread_specific_ptr<__thread_struct>& __thread_local_data() { static __thread_specific_ptr<__thread_struct> __p; return __p; } // __thread_struct_imp template <class T> class _LIBCPP_HIDDEN __hidden_allocator { public: typedef T value_type; T* allocate(size_t __n) {return static_cast<T*>(::operator new(__n * sizeof(T)));} void deallocate(T* __p, size_t) {::operator delete(static_cast<void*>(__p));} size_t max_size() const {return size_t(~0) / sizeof(T);} }; class _LIBCPP_HIDDEN __thread_struct_imp { typedef vector<__assoc_sub_state*, __hidden_allocator<__assoc_sub_state*> > _AsyncStates; typedef vector<pair<condition_variable*, mutex*>, __hidden_allocator<pair<condition_variable*, mutex*> > > _Notify; _AsyncStates async_states_; _Notify notify_; __thread_struct_imp(const __thread_struct_imp&); __thread_struct_imp& operator=(const __thread_struct_imp&); public: __thread_struct_imp() {} ~__thread_struct_imp(); void notify_all_at_thread_exit(condition_variable* cv, mutex* m); void __make_ready_at_thread_exit(__assoc_sub_state* __s); }; __thread_struct_imp::~__thread_struct_imp() { for (_Notify::iterator i = notify_.begin(), e = notify_.end(); i != e; ++i) { i->second->unlock(); i->first->notify_all(); } for (_AsyncStates::iterator i = async_states_.begin(), e = async_states_.end(); i != e; ++i) { (*i)->__make_ready(); (*i)->__release_shared(); } } void __thread_struct_imp::notify_all_at_thread_exit(condition_variable* cv, mutex* m) { notify_.push_back(pair<condition_variable*, mutex*>(cv, m)); } void __thread_struct_imp::__make_ready_at_thread_exit(__assoc_sub_state* __s) { async_states_.push_back(__s); __s->__add_shared(); } // __thread_struct __thread_struct::__thread_struct() : __p_(new __thread_struct_imp) { } __thread_struct::~__thread_struct() { delete __p_; } void __thread_struct::notify_all_at_thread_exit(condition_variable* cv, mutex* m) { __p_->notify_all_at_thread_exit(cv, m); } void __thread_struct::__make_ready_at_thread_exit(__assoc_sub_state* __s) { __p_->__make_ready_at_thread_exit(__s); } _LIBCPP_END_NAMESPACE_STD #endif // !_LIBCPP_HAS_NO_THREADS
Fix the build of thread.cpp on CloudABI.
Fix the build of thread.cpp on CloudABI. CloudABI does provide unistd.h, but doesn't define __unix__. We need to include this header file to make hardware_concurrency work. git-svn-id: 756ef344af921d95d562d9e9f9389127a89a6314@294832 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/libcxx,llvm-mirror/libcxx,llvm-mirror/libcxx,llvm-mirror/libcxx,llvm-mirror/libcxx
088566adaff91fbb3acc8e22cd54ceec21c0cf6a
tests/test_qios.cpp
tests/test_qios.cpp
/* * Copyright (c) 2012, 2013 Aldebaran Robotics. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the COPYING file. */ #ifdef _WIN32 # include <winsock2.h> # include <process.h> // for getpid # include <windows.h> #else # include <arpa/inet.h> # include <unistd.h> // for getpid #endif #ifdef ANDROID # include <sys/socket.h> #endif #include <fstream> #include <cstdio> #include <gtest/gtest.h> #include <boost/filesystem.hpp> #include <qi/path.hpp> #include <qi/os.hpp> #include <qi/qi.hpp> #include <qi/os.hpp> #ifdef _MSC_VER # pragma warning( push ) // truncation of constant value when building char* objects # pragma warning( disable : 4309 ) #endif class QiOSTests: public ::testing::Test { public: QiOSTests() : a_newPath() { } protected: void SetUp() { a_newPath = qi::os::mktmpdir("QiOsTest"); a_newPath.append(a_accent, qi::unicodeFacet()); FILE* fileHandle = qi::os::fopen(a_newPath.string(qi::unicodeFacet()).c_str(), "w"); fclose(fileHandle); } void TearDown() { if(boost::filesystem::exists(a_newPath)) { try { boost::filesystem::remove_all(a_newPath.parent_path()); } catch (std::exception &) { } } } public: boost::filesystem::path a_newPath; static const char a_accent[4]; }; // "" in utf-8 w. french locale. const char QiOSTests::a_accent[4] = { (char) '/', (char) 0xc3, (char) 0xa9, (char) '\0' } ; TEST_F(QiOSTests, LowLevelAccent) { // Try to retrieve the file. // The name must be in utf-8 to be retrieved on unix. ASSERT_TRUE(boost::filesystem::exists(a_newPath)) << a_newPath.string() << std::endl; } TEST(QiOs, fnmatch) { EXPECT_TRUE(qi::os::fnmatch("glob*atch", "globMatch")); EXPECT_FALSE(qi::os::fnmatch("glob*atch", "blobMatch")); } // TODO: us qi::time when it's available :) TEST(QiOs, sleep) { qi::os::sleep(1); } TEST(QiOs, msleep) { qi::os::msleep(1000); } TEST(QiOs, timeValOperatorEasy) { qi::os::timeval t1; t1.tv_sec = 2000; t1.tv_usec = 2000; qi::os::timeval t2; t2.tv_sec = 10; t2.tv_usec = 10; qi::os::timeval res; res = t1 + t2; ASSERT_EQ(2010, res.tv_sec); ASSERT_EQ(2010, res.tv_usec); res = res - t1; ASSERT_EQ(t2.tv_sec, res.tv_sec); ASSERT_EQ(t2.tv_usec, res.tv_usec); res = t2 + 10L; ASSERT_EQ(t2.tv_sec, res.tv_sec); ASSERT_EQ(t2.tv_usec + 10, res.tv_usec); res = t2 - 10L; ASSERT_EQ(t2.tv_sec, res.tv_sec); ASSERT_EQ(t2.tv_usec - 10, res.tv_usec); } TEST(QiOs, timeValOperatorHard) { qi::os::timeval t1; t1.tv_sec = 2000; t1.tv_usec = 999999; qi::os::timeval t2; t2.tv_sec = 10; t2.tv_usec = 2; qi::os::timeval res; res = t1 + t2; ASSERT_EQ(2011, res.tv_sec); ASSERT_EQ(1, res.tv_usec); res = res - t1; ASSERT_EQ(t2.tv_sec, res.tv_sec); ASSERT_EQ(t2.tv_usec, res.tv_usec); res = t2 + 1000000L; ASSERT_EQ(t2.tv_sec + 1, res.tv_sec); ASSERT_EQ(t2.tv_usec, res.tv_usec); res = t2 - 1000000L; ASSERT_EQ(t2.tv_sec - 1, res.tv_sec); ASSERT_EQ(t2.tv_usec, res.tv_usec); } TEST(QiOs, env) { int ret = qi::os::setenv("TITI", "TUTU"); ASSERT_FALSE(ret); EXPECT_EQ("TUTU", qi::os::getenv("TITI")); } TEST(QiOs, getpid) { ASSERT_EQ(getpid(), qi::os::getpid()); } TEST(QiOs, tmp) { std::string temp = qi::os::tmp(); ASSERT_NE(temp, std::string("")); EXPECT_TRUE(boost::filesystem::exists(temp)); EXPECT_TRUE(boost::filesystem::is_directory(temp)); } //check if the folder exists and is writable void test_writable_and_empty(std::string fdir) { std::string tempfile; boost::filesystem::path p(fdir, qi::unicodeFacet()); boost::filesystem::path pp(fdir, qi::unicodeFacet()); EXPECT_TRUE(boost::filesystem::exists(p)); EXPECT_TRUE(boost::filesystem::is_directory(p)); pp.append("tmpfile", qi::unicodeFacet()); tempfile = pp.string(qi::unicodeFacet()); FILE *f = qi::os::fopen(tempfile.c_str(), "w+"); EXPECT_TRUE(f != NULL); fclose(f); EXPECT_TRUE(boost::filesystem::exists(pp)); EXPECT_TRUE(boost::filesystem::is_regular_file(pp)); boost::filesystem::directory_iterator it(p); EXPECT_EQ(pp, it->path()); it++; EXPECT_TRUE((boost::filesystem::directory_iterator() == it)); } void clean_dir(std::string fdir) { if(boost::filesystem::exists(fdir)) { //fail is dir is not removable => dir should be removable boost::filesystem::remove_all(fdir); } } TEST(QiOs, tmpdir_noprefix) { std::string temp = qi::os::mktmpdir(); test_writable_and_empty(temp); clean_dir(temp); } TEST(QiOs, tmpdir_tmpdir) { std::string temp1 = qi::os::mktmpdir(); std::string temp2 = qi::os::mktmpdir(); EXPECT_NE(temp1, temp2); clean_dir(temp1); clean_dir(temp2); } TEST(QiOs, tmpdir_parent) { std::string temp = qi::os::mktmpdir("plaf"); boost::filesystem::path ppa(temp, qi::unicodeFacet()); ppa = ppa.parent_path(); boost::filesystem::path ppatmp(qi::os::tmp(), qi::unicodeFacet()); EXPECT_TRUE(boost::filesystem::equivalent(ppa, ppatmp)); clean_dir(temp); } TEST(QiOs, tmpdir_prefix) { std::string temp = qi::os::mktmpdir("plaf"); test_writable_and_empty(temp); boost::filesystem::path pp(temp, qi::unicodeFacet()); std::string tempfname = pp.filename().string(qi::unicodeFacet()); EXPECT_EQ(tempfname[0], 'p'); EXPECT_EQ(tempfname[1], 'l'); EXPECT_EQ(tempfname[2], 'a'); EXPECT_EQ(tempfname[3], 'f'); clean_dir(temp); } TEST(QiOs, tmpdir_prefix_accentuated) { char utf8[] = { (char) 0xC5, (char) 0xAA, (char) 0x6E, (char) 0xC4, (char) 0xAD, (char) 0x63, (char) 0xC5, (char) 0x8D, (char) 0x64, (char) 0x65, (char) 0xCC, (char) 0xBD, (char) 0 }; std::string temp = qi::os::mktmpdir(utf8); test_writable_and_empty(temp); clean_dir(temp); } TEST(QiOs, tmpdir_prefix_zero) { std::string temp = qi::os::mktmpdir(0); test_writable_and_empty(temp); clean_dir(temp); } TEST(QiOs, get_host_name) { std::string temp = qi::os::gethostname(); EXPECT_NE(std::string(), temp); } bool freeportbind(unsigned short port, int &sock) { struct sockaddr_in name; name.sin_family = AF_INET; name.sin_addr.s_addr = htonl(INADDR_ANY); sock = static_cast<int>(::socket(AF_INET, SOCK_STREAM, 0)); name.sin_port = htons(port); return (::bind(sock, (struct sockaddr *)&name, sizeof(name))) != 0; } TEST(QiOs, free_port) { int sock; unsigned short port = qi::os::findAvailablePort(9559); int success = freeportbind(port, sock); if (success == -1) EXPECT_TRUE(false); else #ifndef _WIN32 ::close(sock); #else ::closesocket(sock); #endif EXPECT_TRUE(true); } TEST(QiOs, free_port_multiple_connection) { int sock1; unsigned short port1 = qi::os::findAvailablePort(9559); int success1 = freeportbind(port1, sock1); int sock2; unsigned short port2 = qi::os::findAvailablePort(9559); int success2 = freeportbind(port2, sock2); int sock3; unsigned short port3 = qi::os::findAvailablePort(9559); int success3 = freeportbind(port3, sock3); if (success1 == -1) EXPECT_TRUE(false); else #ifndef _WIN32 ::close(sock1); #else ::closesocket(sock1); #endif if (success2 == -1) EXPECT_TRUE(false); else #ifndef _WIN32 ::close(sock2); #else ::closesocket(sock2); #endif if (success3 == -1) EXPECT_TRUE(false); else #ifndef _WIN32 ::close(sock3); #else ::closesocket(sock3); #endif EXPECT_TRUE(true); } TEST(QiOs, hostIPAddrs) { std::map<std::string, std::vector<std::string> > ifsMap; ifsMap = qi::os::hostIPAddrs(); ASSERT_TRUE(ifsMap.empty() == false); } TEST(QiOs, getMachineId) { int status = 0; std::string bin = qi::path::findBin("check_machineid"); int childPid = qi::os::spawnlp(bin.c_str(), NULL); ASSERT_NE(-1, childPid); int error = qi::os::waitpid(childPid, &status); EXPECT_EQ(0, error); EXPECT_EQ(0, status); std::string uuid1 = qi::os::getMachineId(); std::string uuid2; std::string uuid2FileName = (qi::os::tmp()).append("machine_id_test_42"); std::ifstream uuid2file(uuid2FileName.c_str()); ASSERT_TRUE(uuid2file != NULL); uuid2file >> uuid2; uuid2file.close(); ASSERT_TRUE(uuid1.compare(uuid2) == 0); } #if defined(_WIN32) || defined(__linux__) TEST(QiOs, CPUAffinity) #else TEST(QiOs, DISABLED_CPUAffinity) #endif { std::vector<int> cpus; long nprocs_max = -1; cpus.push_back(0); cpus.push_back(1); ASSERT_TRUE(qi::os::setCurrentThreadCPUAffinity(cpus)); nprocs_max = qi::os::numberOfCPUs(); ASSERT_TRUE(nprocs_max > 0); cpus.clear(); cpus.push_back(nprocs_max + 1); ASSERT_FALSE(qi::os::setCurrentThreadCPUAffinity(cpus)); } TEST(QiOs, dlerror) { qi::os::dlerror(); // Reset errno value const char *error0 = qi::os::dlerror(); // expect NULL since no error has occurred since initialization EXPECT_TRUE(error0 == NULL) << "Expected NULL, got: " << error0; qi::os::dlerror(); // Reset errno value qi::os::dlopen("failure.so"); EXPECT_TRUE(qi::os::dlerror() != NULL) << "Expected error got NULL"; const char *error1 = qi::os::dlerror(); // reset // expect NULL since no error has occurred since last dlerror call EXPECT_TRUE(error1 == NULL) << "Expected NULL, got: " << error1; #ifndef __linux__ // dlclose segfault on linux if an invalid pointer is given qi::os::dlerror(); // Reset errno value EXPECT_NE(0, qi::os::dlclose((void*) 123)); const char* error2 = qi::os::dlerror(); EXPECT_NE((const char*) NULL, error2); #endif } #ifdef _MSC_VER # pragma warning( pop ) #endif
/* * Copyright (c) 2012, 2013 Aldebaran Robotics. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the COPYING file. */ #ifdef _WIN32 # include <winsock2.h> # include <process.h> // for getpid # include <windows.h> #else # include <arpa/inet.h> # include <unistd.h> // for getpid #endif #ifdef ANDROID # include <sys/socket.h> #endif #include <fstream> #include <cstdio> #include <gtest/gtest.h> #include <boost/filesystem.hpp> #include <qi/path.hpp> #include <qi/os.hpp> #include <qi/qi.hpp> #include <qi/os.hpp> #ifdef _MSC_VER # pragma warning( push ) // truncation of constant value when building char* objects # pragma warning( disable : 4309 ) #endif class QiOSTests: public ::testing::Test { public: QiOSTests() : a_newPath() { } protected: void SetUp() { a_newPath = qi::os::mktmpdir("QiOsTest"); a_newPath.append(a_accent, qi::unicodeFacet()); FILE* fileHandle = qi::os::fopen(a_newPath.string(qi::unicodeFacet()).c_str(), "w"); fclose(fileHandle); } void TearDown() { if(boost::filesystem::exists(a_newPath)) { try { boost::filesystem::remove_all(a_newPath.parent_path()); } catch (std::exception &) { } } } public: boost::filesystem::path a_newPath; static const char a_accent[4]; }; // "" in utf-8 w. french locale. const char QiOSTests::a_accent[4] = { (char) '/', (char) 0xc3, (char) 0xa9, (char) '\0' } ; TEST_F(QiOSTests, LowLevelAccent) { // Try to retrieve the file. // The name must be in utf-8 to be retrieved on unix. ASSERT_TRUE(boost::filesystem::exists(a_newPath)) << a_newPath.string() << std::endl; } TEST(QiOs, fnmatch) { EXPECT_TRUE(qi::os::fnmatch("fnmatch", "fnmatch")); EXPECT_FALSE(qi::os::fnmatch("fnmatc", "fnmatch")); EXPECT_TRUE(qi::os::fnmatch("fn*ch", "fnmatch")); EXPECT_FALSE(qi::os::fnmatch("fz*ch", "fnmatch")); EXPECT_TRUE(qi::os::fnmatch("fn???ch", "fnmatch")); EXPECT_FALSE(qi::os::fnmatch("fn?z?ch", "fnmatch")); } // TODO: us qi::time when it's available :) TEST(QiOs, sleep) { qi::os::sleep(1); } TEST(QiOs, msleep) { qi::os::msleep(1000); } TEST(QiOs, timeValOperatorEasy) { qi::os::timeval t1; t1.tv_sec = 2000; t1.tv_usec = 2000; qi::os::timeval t2; t2.tv_sec = 10; t2.tv_usec = 10; qi::os::timeval res; res = t1 + t2; ASSERT_EQ(2010, res.tv_sec); ASSERT_EQ(2010, res.tv_usec); res = res - t1; ASSERT_EQ(t2.tv_sec, res.tv_sec); ASSERT_EQ(t2.tv_usec, res.tv_usec); res = t2 + 10L; ASSERT_EQ(t2.tv_sec, res.tv_sec); ASSERT_EQ(t2.tv_usec + 10, res.tv_usec); res = t2 - 10L; ASSERT_EQ(t2.tv_sec, res.tv_sec); ASSERT_EQ(t2.tv_usec - 10, res.tv_usec); } TEST(QiOs, timeValOperatorHard) { qi::os::timeval t1; t1.tv_sec = 2000; t1.tv_usec = 999999; qi::os::timeval t2; t2.tv_sec = 10; t2.tv_usec = 2; qi::os::timeval res; res = t1 + t2; ASSERT_EQ(2011, res.tv_sec); ASSERT_EQ(1, res.tv_usec); res = res - t1; ASSERT_EQ(t2.tv_sec, res.tv_sec); ASSERT_EQ(t2.tv_usec, res.tv_usec); res = t2 + 1000000L; ASSERT_EQ(t2.tv_sec + 1, res.tv_sec); ASSERT_EQ(t2.tv_usec, res.tv_usec); res = t2 - 1000000L; ASSERT_EQ(t2.tv_sec - 1, res.tv_sec); ASSERT_EQ(t2.tv_usec, res.tv_usec); } TEST(QiOs, env) { int ret = qi::os::setenv("TITI", "TUTU"); ASSERT_FALSE(ret); EXPECT_EQ("TUTU", qi::os::getenv("TITI")); } TEST(QiOs, getpid) { ASSERT_EQ(getpid(), qi::os::getpid()); } TEST(QiOs, tmp) { std::string temp = qi::os::tmp(); ASSERT_NE(temp, std::string("")); EXPECT_TRUE(boost::filesystem::exists(temp)); EXPECT_TRUE(boost::filesystem::is_directory(temp)); } //check if the folder exists and is writable void test_writable_and_empty(std::string fdir) { std::string tempfile; boost::filesystem::path p(fdir, qi::unicodeFacet()); boost::filesystem::path pp(fdir, qi::unicodeFacet()); EXPECT_TRUE(boost::filesystem::exists(p)); EXPECT_TRUE(boost::filesystem::is_directory(p)); pp.append("tmpfile", qi::unicodeFacet()); tempfile = pp.string(qi::unicodeFacet()); FILE *f = qi::os::fopen(tempfile.c_str(), "w+"); EXPECT_TRUE(f != NULL); fclose(f); EXPECT_TRUE(boost::filesystem::exists(pp)); EXPECT_TRUE(boost::filesystem::is_regular_file(pp)); boost::filesystem::directory_iterator it(p); EXPECT_EQ(pp, it->path()); it++; EXPECT_TRUE((boost::filesystem::directory_iterator() == it)); } void clean_dir(std::string fdir) { if(boost::filesystem::exists(fdir)) { //fail is dir is not removable => dir should be removable boost::filesystem::remove_all(fdir); } } TEST(QiOs, tmpdir_noprefix) { std::string temp = qi::os::mktmpdir(); test_writable_and_empty(temp); clean_dir(temp); } TEST(QiOs, tmpdir_tmpdir) { std::string temp1 = qi::os::mktmpdir(); std::string temp2 = qi::os::mktmpdir(); EXPECT_NE(temp1, temp2); clean_dir(temp1); clean_dir(temp2); } TEST(QiOs, tmpdir_parent) { std::string temp = qi::os::mktmpdir("plaf"); boost::filesystem::path ppa(temp, qi::unicodeFacet()); ppa = ppa.parent_path(); boost::filesystem::path ppatmp(qi::os::tmp(), qi::unicodeFacet()); EXPECT_TRUE(boost::filesystem::equivalent(ppa, ppatmp)); clean_dir(temp); } TEST(QiOs, tmpdir_prefix) { std::string temp = qi::os::mktmpdir("plaf"); test_writable_and_empty(temp); boost::filesystem::path pp(temp, qi::unicodeFacet()); std::string tempfname = pp.filename().string(qi::unicodeFacet()); EXPECT_EQ(tempfname[0], 'p'); EXPECT_EQ(tempfname[1], 'l'); EXPECT_EQ(tempfname[2], 'a'); EXPECT_EQ(tempfname[3], 'f'); clean_dir(temp); } TEST(QiOs, tmpdir_prefix_accentuated) { char utf8[] = { (char) 0xC5, (char) 0xAA, (char) 0x6E, (char) 0xC4, (char) 0xAD, (char) 0x63, (char) 0xC5, (char) 0x8D, (char) 0x64, (char) 0x65, (char) 0xCC, (char) 0xBD, (char) 0 }; std::string temp = qi::os::mktmpdir(utf8); test_writable_and_empty(temp); clean_dir(temp); } TEST(QiOs, tmpdir_prefix_zero) { std::string temp = qi::os::mktmpdir(0); test_writable_and_empty(temp); clean_dir(temp); } TEST(QiOs, get_host_name) { std::string temp = qi::os::gethostname(); EXPECT_NE(std::string(), temp); } bool freeportbind(unsigned short port, int &sock) { struct sockaddr_in name; name.sin_family = AF_INET; name.sin_addr.s_addr = htonl(INADDR_ANY); sock = static_cast<int>(::socket(AF_INET, SOCK_STREAM, 0)); name.sin_port = htons(port); return (::bind(sock, (struct sockaddr *)&name, sizeof(name))) != 0; } TEST(QiOs, free_port) { int sock; unsigned short port = qi::os::findAvailablePort(9559); int success = freeportbind(port, sock); if (success == -1) EXPECT_TRUE(false); else #ifndef _WIN32 ::close(sock); #else ::closesocket(sock); #endif EXPECT_TRUE(true); } TEST(QiOs, free_port_multiple_connection) { int sock1; unsigned short port1 = qi::os::findAvailablePort(9559); int success1 = freeportbind(port1, sock1); int sock2; unsigned short port2 = qi::os::findAvailablePort(9559); int success2 = freeportbind(port2, sock2); int sock3; unsigned short port3 = qi::os::findAvailablePort(9559); int success3 = freeportbind(port3, sock3); if (success1 == -1) EXPECT_TRUE(false); else #ifndef _WIN32 ::close(sock1); #else ::closesocket(sock1); #endif if (success2 == -1) EXPECT_TRUE(false); else #ifndef _WIN32 ::close(sock2); #else ::closesocket(sock2); #endif if (success3 == -1) EXPECT_TRUE(false); else #ifndef _WIN32 ::close(sock3); #else ::closesocket(sock3); #endif EXPECT_TRUE(true); } TEST(QiOs, hostIPAddrs) { std::map<std::string, std::vector<std::string> > ifsMap; ifsMap = qi::os::hostIPAddrs(); ASSERT_TRUE(ifsMap.empty() == false); } TEST(QiOs, getMachineId) { int status = 0; std::string bin = qi::path::findBin("check_machineid"); int childPid = qi::os::spawnlp(bin.c_str(), NULL); ASSERT_NE(-1, childPid); int error = qi::os::waitpid(childPid, &status); EXPECT_EQ(0, error); EXPECT_EQ(0, status); std::string uuid1 = qi::os::getMachineId(); std::string uuid2; std::string uuid2FileName = (qi::os::tmp()).append("machine_id_test_42"); std::ifstream uuid2file(uuid2FileName.c_str()); ASSERT_TRUE(uuid2file != NULL); uuid2file >> uuid2; uuid2file.close(); ASSERT_TRUE(uuid1.compare(uuid2) == 0); } #if defined(_WIN32) || defined(__linux__) TEST(QiOs, CPUAffinity) #else TEST(QiOs, DISABLED_CPUAffinity) #endif { std::vector<int> cpus; long nprocs_max = -1; cpus.push_back(0); cpus.push_back(1); ASSERT_TRUE(qi::os::setCurrentThreadCPUAffinity(cpus)); nprocs_max = qi::os::numberOfCPUs(); ASSERT_TRUE(nprocs_max > 0); cpus.clear(); cpus.push_back(nprocs_max + 1); ASSERT_FALSE(qi::os::setCurrentThreadCPUAffinity(cpus)); } TEST(QiOs, dlerror) { qi::os::dlerror(); // Reset errno value const char *error0 = qi::os::dlerror(); // expect NULL since no error has occurred since initialization EXPECT_TRUE(error0 == NULL) << "Expected NULL, got: " << error0; qi::os::dlerror(); // Reset errno value qi::os::dlopen("failure.so"); EXPECT_TRUE(qi::os::dlerror() != NULL) << "Expected error got NULL"; const char *error1 = qi::os::dlerror(); // reset // expect NULL since no error has occurred since last dlerror call EXPECT_TRUE(error1 == NULL) << "Expected NULL, got: " << error1; #ifndef __linux__ // dlclose segfault on linux if an invalid pointer is given qi::os::dlerror(); // Reset errno value EXPECT_NE(0, qi::os::dlclose((void*) 123)); const char* error2 = qi::os::dlerror(); EXPECT_NE((const char*) NULL, error2); #endif } #ifdef _MSC_VER # pragma warning( pop ) #endif
add many tests
qi::os::fnmatch: add many tests Change-Id: Ia6092fe10c93817ec08702fb73c6a0df18855768 Reviewed-on: http://gerrit.aldebaran.lan/19342 Tested-by: gerrit Reviewed-by: pagoya <[email protected]>
C++
bsd-3-clause
aldebaran/libqi,bsautron/libqi,aldebaran/libqi,vbarbaresi/libqi,aldebaran/libqi
80dc06ad4f091d33f381471e746c40911b84486c
src/win/pty.cc
src/win/pty.cc
/** * pty.js * Copyright (c) 2012, Christopher Jeffrey, Peter Sunde (MIT License) * * pty.cc: * This file is responsible for starting processes * with pseudo-terminal file descriptors. */ #include <v8.h> #include <node.h> #include <uv.h> #include <node_buffer.h> #include <string.h> #include <stdlib.h> #include <winpty.h> #include <string> #include <sstream> #include <iostream> #include <vector> using namespace v8; using namespace std; using namespace node; /** * Misc */ extern "C" void init(Handle<Object>); static winpty_t *agentPty; static std::vector<winpty_t *> ptyHandles; static volatile LONG ptyCounter; struct winpty_s { winpty_s(); HANDLE controlPipe; HANDLE dataPipe; int pid; }; winpty_s::winpty_s() : controlPipe(NULL), dataPipe(NULL) { } /** * Helpers */ wchar_t* ToWChar(const char* utf8){ if (utf8 == NULL || *utf8 == L'\0') { return new wchar_t[0]; } else { const int utf8len = static_cast<int>(strlen(utf8)); const int utf16len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8, utf8len, NULL, 0); if (utf16len == 0) { return new wchar_t[0]; } else { wchar_t* utf16 = new wchar_t[utf16len]; if (!::MultiByteToWideChar(CP_UTF8, 0, utf8, utf8len, utf16, utf16len)) { return new wchar_t[0]; } else { return utf16; } } } } const char* ToCString(const v8::String::Utf8Value& value) { return *value ? *value : "<string conversion failed>"; } template <typename T> void remove(std::vector<T>& vec, size_t pos) { std::vector<T>::iterator it = vec.begin(); std::advance(it, pos); vec.erase(it); } // Find a given pipe handle by using agent pid static winpty_t *getControlPipeHandle(int pid) { for(unsigned int i = 0; i < ptyHandles.size(); i++) { winpty_t *ptyHandle = ptyHandles[i]; if(ptyHandle->pid == pid) { return ptyHandle; } } return NULL; } // Remove a given pipe handle static bool removePipeHandle(int pid) { for(unsigned int i = 0; i < ptyHandles.size(); i++) { winpty_t *ptyHandle = ptyHandles[i]; if(ptyHandle->pid == pid) { remove(ptyHandles, i); return true; } } return false; } /* * PtyOpen * pty.open(controlPipe, dataPipe, cols, rows) * * Steps for debugging agent.exe: * * 1) Open a windows terminal * 2) set WINPTYDBG=1 * 3) python deps/misc/DebugServer.py * 4) Start a new terminal in node.js and trace output will appear * in the python script. * */ static Handle<Value> PtyOpen(const Arguments& args) { HandleScope scope; if (args.Length() != 5 || !args[0]->IsString() // controlPipe || !args[1]->IsString() // dataPipe || !args[2]->IsNumber() // cols || !args[3]->IsNumber() // rows || !args[4]->IsBoolean()) // debug { return ThrowException(Exception::Error( String::New("Usage: pty.open(controlPipe, dataPipe, cols, rows, debug)"))); } // Cols, rows bool debug = (bool) args[4]->BooleanValue; int cols = (int) args[2]->Int32Value(); int rows = (int) args[3]->Int32Value(); // If debug is enabled, set environment variable if(debug) { SetEnvironmentVariableW(L"WINPTYDBG", L"1"); } else { FreeEnvironmentStringsW(L"WINPTYDBG"); } // Controlpipe String::Utf8Value controlPipe(args[0]->ToString()); String::Utf8Value dataPipe(args[1]->ToString()); // If successfull the PID of the agent process will be returned. agentPty = winpty_open_ptyjs(ToCString(controlPipe), ToCString(dataPipe), rows, cols); // Error occured during startup of agent process if(agentPty == NULL) { return ThrowException(Exception::Error(String::New("Unable to start agent process."))); } // Save a copy of this pty so that we can find the control socket handle // later on. ptyHandles.insert(ptyHandles.end(), agentPty); // Pty object values Local<Object> obj = Object::New(); // Agent pid obj->Set(String::New("pid"), Number::New(agentPty->pid)); // Use handle of control pipe as our file descriptor obj->Set(String::New("fd"), Number::New(-1)); // Some peepz use this as an id, lets give em one. obj->Set(String::New("pty"), Number::New(InterlockedIncrement(&ptyCounter))); return scope.Close(obj); } /* * PtyStartProcess * pty.startProcess(pid, file, env, cwd); */ static Handle<Value> PtyStartProcess(const Arguments& args) { HandleScope scope; if (args.Length() != 4 || !args[0]->IsNumber() // pid || !args[1]->IsString() // file + args || !args[2]->IsString() // env || !args[3]->IsString()) // cwd { return ThrowException(Exception::Error( String::New("Usage: pty.open(pid, file, env, cwd)"))); } // Native values int pid = (int) args[0]->Int32Value(); std::string _file = *String::Utf8Value(args[1]->ToString()); std::string _env = *String::Utf8Value(args[2]->ToString()); std::string _cwd = *String::Utf8Value(args[3]->ToString()); // Cwd must be double slash encoded otherwise // we fail to start the terminal process and get // windows error code 267. for (int i = 0; i < _cwd.length(); ++i) if (_cwd[i] == '\\') { _cwd.insert(i, 1, '\\'); ++i; // Skip inserted char } // convert to wchar_t wchar_t *file = ToWChar(_file.c_str()); wchar_t *cwd = ToWChar(_cwd.c_str()); wchar_t *env = ToWChar(_env.c_str()); // Get pipe handle winpty_t *pc = getControlPipeHandle(pid); // Start new terminal if(pc != NULL) { int res = winpty_start_process(pc, NULL, file, L"", env); // Check that the terminal was successfully started. if(res != 0) { return ThrowException(Exception::Error( String::New("Unable to start terminal process."))); } } else { return ThrowException(Exception::Error( String::New("Invalid pid."))); } return scope.Close(Undefined()); } /* * PtyResize * pty.resize(pid, cols, rows); */ static Handle<Value> PtyResize(const Arguments& args) { HandleScope scope; if (args.Length() != 3 || !args[0]->IsNumber() // pid || !args[1]->IsNumber() // cols || !args[2]->IsNumber()) // rows { return ThrowException(Exception::Error( String::New("Usage: pty.resize(pid, cols, rows)"))); } int pid = (int) args[0]->Int32Value(); int cols = (int) args[1]->Int32Value(); int rows = (int) args[2]->Int32Value(); winpty_t *pc = getControlPipeHandle(pid); if(pc == NULL) { return ThrowException(Exception::Error( String::New("Invalid pid."))); } winpty_set_size(pc, cols, rows); return scope.Close(Undefined()); } /* * PtyKill * pty.kill(pid); */ static Handle<Value> PtyKill(const Arguments& args) { HandleScope scope; if (args.Length() != 1 || !args[0]->IsNumber()) // pid { return ThrowException(Exception::Error( String::New("Usage: pty.kill(pid)"))); } int pid = (int) args[0]->Int32Value(); winpty_t *pc = getControlPipeHandle(pid); if(pc == NULL) { return ThrowException(Exception::Error( String::New("Invalid pid."))); } winpty_close(pc); removePipeHandle(pid); return scope.Close(Undefined()); } /** * Init */ extern "C" void init(Handle<Object> target) { HandleScope scope; NODE_SET_METHOD(target, "open", PtyOpen); NODE_SET_METHOD(target, "startProcess", PtyStartProcess); NODE_SET_METHOD(target, "resize", PtyResize); NODE_SET_METHOD(target, "kill", PtyKill); }; NODE_MODULE(pty, init);
/** * pty.js * Copyright (c) 2012, Christopher Jeffrey, Peter Sunde (MIT License) * * pty.cc: * This file is responsible for starting processes * with pseudo-terminal file descriptors. */ #include <v8.h> #include <node.h> #include <uv.h> #include <node_buffer.h> #include <string.h> #include <stdlib.h> #include <winpty.h> #include <string> #include <sstream> #include <iostream> #include <vector> using namespace v8; using namespace std; using namespace node; /** * Misc */ extern "C" void init(Handle<Object>); static winpty_t *agentPty; static std::vector<winpty_t *> ptyHandles; static volatile LONG ptyCounter; struct winpty_s { winpty_s(); HANDLE controlPipe; HANDLE dataPipe; int pid; }; winpty_s::winpty_s() : controlPipe(NULL), dataPipe(NULL) { } /** * Helpers */ wchar_t* ToWChar(const char* utf8){ if (utf8 == NULL || *utf8 == L'\0') { return new wchar_t[0]; } else { const int utf8len = static_cast<int>(strlen(utf8)); const int utf16len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8, utf8len, NULL, 0); if (utf16len == 0) { return new wchar_t[0]; } else { wchar_t* utf16 = new wchar_t[utf16len]; if (!::MultiByteToWideChar(CP_UTF8, 0, utf8, utf8len, utf16, utf16len)) { return new wchar_t[0]; } else { return utf16; } } } } const char* ToCString(const v8::String::Utf8Value& value) { return *value ? *value : "<string conversion failed>"; } template <typename T> void remove(std::vector<T>& vec, size_t pos) { std::vector<T>::iterator it = vec.begin(); std::advance(it, pos); vec.erase(it); } // Find a given pipe handle by using agent pid static winpty_t *getControlPipeHandle(int pid) { for(unsigned int i = 0; i < ptyHandles.size(); i++) { winpty_t *ptyHandle = ptyHandles[i]; if(ptyHandle->pid == pid) { return ptyHandle; } } return NULL; } // Remove a given pipe handle static bool removePipeHandle(int pid) { for(unsigned int i = 0; i < ptyHandles.size(); i++) { winpty_t *ptyHandle = ptyHandles[i]; if(ptyHandle->pid == pid) { remove(ptyHandles, i); return true; } } return false; } /* * PtyOpen * pty.open(controlPipe, dataPipe, cols, rows) * * Steps for debugging agent.exe: * * 1) Open a windows terminal * 2) set WINPTYDBG=1 * 3) python deps/misc/DebugServer.py * 4) Start a new terminal in node.js and trace output will appear * in the python script. * */ static Handle<Value> PtyOpen(const Arguments& args) { HandleScope scope; if (args.Length() != 5 || !args[0]->IsString() // controlPipe || !args[1]->IsString() // dataPipe || !args[2]->IsNumber() // cols || !args[3]->IsNumber() // rows || !args[4]->IsBoolean()) // debug { return ThrowException(Exception::Error( String::New("Usage: pty.open(controlPipe, dataPipe, cols, rows, debug)"))); } // Cols, rows bool debug = (bool) args[4]->BooleanValue; int cols = (int) args[2]->Int32Value(); int rows = (int) args[3]->Int32Value(); // If debug is enabled, set environment variable if(debug) { SetEnvironmentVariableW(L"WINPTYDBG", L"1"); } else { FreeEnvironmentStringsW(L"WINPTYDBG"); } // Controlpipe String::Utf8Value controlPipe(args[0]->ToString()); String::Utf8Value dataPipe(args[1]->ToString()); // If successfull the PID of the agent process will be returned. agentPty = winpty_open_ptyjs(ToCString(controlPipe), ToCString(dataPipe), rows, cols); // Error occured during startup of agent process if(agentPty == NULL) { return ThrowException(Exception::Error(String::New("Unable to start agent process."))); } // Save a copy of this pty so that we can find the control socket handle // later on. ptyHandles.insert(ptyHandles.end(), agentPty); // Pty object values Local<Object> obj = Object::New(); // Agent pid obj->Set(String::New("pid"), Number::New(agentPty->pid)); // Use handle of control pipe as our file descriptor obj->Set(String::New("fd"), Number::New(-1)); // Some peepz use this as an id, lets give em one. obj->Set(String::New("pty"), Number::New(InterlockedIncrement(&ptyCounter))); return scope.Close(obj); } /* * PtyStartProcess * pty.startProcess(pid, file, env, cwd); */ static Handle<Value> PtyStartProcess(const Arguments& args) { HandleScope scope; if (args.Length() != 4 || !args[0]->IsNumber() // pid || !args[1]->IsString() // file + args || !args[2]->IsString() // env || !args[3]->IsString()) // cwd { return ThrowException(Exception::Error( String::New("Usage: pty.open(pid, file, env, cwd)"))); } // Native values int pid = (int) args[0]->Int32Value(); // convert to wchar_t std::wstring file(ToWChar(*String::Utf8Value(args[1]->ToString()))); std::wstring env(ToWChar(*String::Utf8Value(args[2]->ToString()))); // Okay this is really fucked up. What the hell is going and // why does not ToWChar work? Windows reports error code 267 // if ToWChar is used. Could somebody please elaborate on this? :) std::string _cwd((*String::Utf8Value(args[3]->ToString()))); std::wstring cwd(_cwd.begin(), _cwd.end()); // Cwd must be double slash encoded otherwise // we fail to start the terminal process and get // windows error code 267. for (int i = 0; i < cwd.length(); ++i) { if (cwd[i] == '\\') { cwd.insert(i, 1, '\\'); ++i; // Skip inserted char } } // Get pipe handle winpty_t *pc = getControlPipeHandle(pid); // Start new terminal if(pc != NULL) { winpty_start_process(pc, NULL, file.c_str(), cwd.c_str(), env.c_str()); } else { return ThrowException(Exception::Error( String::New("Invalid pid."))); } return scope.Close(Undefined()); } /* * PtyResize * pty.resize(pid, cols, rows); */ static Handle<Value> PtyResize(const Arguments& args) { HandleScope scope; if (args.Length() != 3 || !args[0]->IsNumber() // pid || !args[1]->IsNumber() // cols || !args[2]->IsNumber()) // rows { return ThrowException(Exception::Error( String::New("Usage: pty.resize(pid, cols, rows)"))); } int pid = (int) args[0]->Int32Value(); int cols = (int) args[1]->Int32Value(); int rows = (int) args[2]->Int32Value(); winpty_t *pc = getControlPipeHandle(pid); if(pc == NULL) { return ThrowException(Exception::Error( String::New("Invalid pid."))); } winpty_set_size(pc, cols, rows); return scope.Close(Undefined()); } /* * PtyKill * pty.kill(pid); */ static Handle<Value> PtyKill(const Arguments& args) { HandleScope scope; if (args.Length() != 1 || !args[0]->IsNumber()) // pid { return ThrowException(Exception::Error( String::New("Usage: pty.kill(pid)"))); } int pid = (int) args[0]->Int32Value(); winpty_t *pc = getControlPipeHandle(pid); if(pc == NULL) { return ThrowException(Exception::Error( String::New("Invalid pid."))); } winpty_close(pc); removePipeHandle(pid); return scope.Close(Undefined()); } /** * Init */ extern "C" void init(Handle<Object> target) { HandleScope scope; NODE_SET_METHOD(target, "open", PtyOpen); NODE_SET_METHOD(target, "startProcess", PtyStartProcess); NODE_SET_METHOD(target, "resize", PtyResize); NODE_SET_METHOD(target, "kill", PtyKill); }; NODE_MODULE(pty, init);
Fix current working dir and remove exception.
Fix current working dir and remove exception.
C++
mit
codio/pty.js,mikeal/pty.js,mikeal/pty.js,codio/pty.js,iiegor/pty.js,iiegor/ptyw.js,iiegor/ptyw.js,enlight/node-unix-pty,JamesMGreene/node-partty,iiegor/pty.js,marcominetti/pty.js,jeremyramin/pty.js,pandaman64/pty.js,etiktin/pty.js,soumith/pty.js,mcanthony/pty.js,tejasmanohar/pty.js,iiegor/ptyw.js,jo-osborne/pty.js,chjj/pty.js,chjj/pty.js,soumith/pty.js,JamesMGreene/node-partty,pandaman64/pty.js,jeremyramin/pty.js,codio/pty.js,iiegor/pty.js,jo-osborne/pty.js,JamesMGreene/node-partty,mcanthony/pty.js,jeremyramin/pty.js,etiktin/pty.js,marcominetti/pty.js,tejasmanohar/pty.js,marcominetti/pty.js,mikeal/pty.js,pandaman64/pty.js,soumith/pty.js,tejasmanohar/pty.js,enlight/node-unix-pty,etiktin/pty.js,chjj/pty.js,jo-osborne/pty.js,enlight/node-unix-pty,mcanthony/pty.js
b327dac6d48ebc86ddb01248b4ab9c26fe7cb0cd
src/window.cpp
src/window.cpp
/******************************************************* * Copyright (c) 2015-2019, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ // Parts of this code sourced from SnopyDogy // https://gist.github.com/SnopyDogy/a9a22497a893ec86aa3e #include <common.hpp> #include <fg/window.h> #include <window.hpp> #include <memory> #include <mutex> using namespace fg; static GLEWContext* current = nullptr; GLEWContext* glewGetContext() { return current; } /* following function is thread safe */ int getNextUniqueId() { static int wndUnqIdTracker = 0; static std::mutex wndUnqIdMutex; std::lock_guard<std::mutex> lock(wndUnqIdMutex); return wndUnqIdTracker++; } namespace internal { void MakeContextCurrent(const window_impl* pWindow) { if (pWindow != NULL) { pWindow->get()->makeContextCurrent(); current = pWindow->glewContext(); } CheckGL("End MakeContextCurrent"); } window_impl::window_impl(int pWidth, int pHeight, const char* pTitle, std::weak_ptr<window_impl> pWindow, const bool invisible) : mID(getNextUniqueId()), mWidth(pWidth), mHeight(pHeight), mRows(0), mCols(0) { if (auto observe = pWindow.lock()) { mWindow = new wtk::Widget(pWidth, pHeight, pTitle, observe->get(), invisible); } else { /* when windows are not sharing any context, just create * a dummy wtk::Widget object and pass it on */ mWindow = new wtk::Widget(pWidth, pHeight, pTitle, nullptr, invisible); } /* create glew context so that it will bind itself to windows */ if (auto observe = pWindow.lock()) { mGLEWContext = observe->glewContext(); } else { mGLEWContext = new GLEWContext(); if (mGLEWContext == NULL) { std::cerr<<"Error: Could not create GLEW Context!\n"; throw fg::Error("window_impl constructor", __LINE__, "GLEW context creation failed", fg::FG_ERR_GL_ERROR); } } /* Set context (before glewInit()) */ MakeContextCurrent(this); /* GLEW Initialization - Must be done */ glewExperimental = GL_TRUE; GLenum err = glewInit(); if (err != GLEW_OK) { char buffer[128]; sprintf(buffer, "GLEW init failed: Error: %s\n", glewGetErrorString(err)); throw fg::Error("window_impl constructor", __LINE__, buffer, fg::FG_ERR_GL_ERROR); } err = glGetError(); if (err!=GL_NO_ERROR && err!=GL_INVALID_ENUM) { /* ignore this error, as GLEW is known to * have this issue with 3.2+ core profiles * they are yet to fix this in GLEW */ ForceCheckGL("GLEW initilization failed"); throw fg::Error("window_impl constructor", __LINE__, "GLEW initilization failed", fg::FG_ERR_GL_ERROR); } mCxt = mWindow->getGLContextHandle(); mDsp = mWindow->getDisplayHandle(); /* copy colormap shared pointer if * this window shares context with another window * */ if (auto observe = pWindow.lock()) { mCMap = observe->colorMapPtr(); } else { mCMap = std::make_shared<colormap_impl>(); } /* set the colormap to default */ mColorMapUBO = mCMap->defaultMap(); mUBOSize = mCMap->defaultLen(); glEnable(GL_MULTISAMPLE); CheckGL("End Window::Window"); } window_impl::~window_impl() { delete mWindow; } void window_impl::setFont(const std::shared_ptr<font_impl>& pFont) { mFont = pFont; } void window_impl::setTitle(const char* pTitle) { mWindow->setTitle(pTitle); } void window_impl::setPos(int pX, int pY) { mWindow->setPos(pX, pY); } void window_impl::setSize(unsigned pW, unsigned pH) { mWindow->setSize(pW, pH); } void window_impl::setColorMap(fg::ColorMap cmap) { switch(cmap) { case FG_DEFAULT: mColorMapUBO = mCMap->defaultMap(); mUBOSize = mCMap->defaultLen(); break; case FG_SPECTRUM: mColorMapUBO = mCMap->spectrum(); mUBOSize = mCMap->spectrumLen(); break; case FG_COLORS: mColorMapUBO = mCMap->colors(); mUBOSize = mCMap->colorsLen(); break; case FG_REDMAP: mColorMapUBO = mCMap->red(); mUBOSize = mCMap->redLen(); break; case FG_MOOD: mColorMapUBO = mCMap->mood(); mUBOSize = mCMap->moodLen(); break; case FG_HEAT: mColorMapUBO = mCMap->heat(); mUBOSize = mCMap->heatLen(); break; case FG_BLUEMAP: mColorMapUBO = mCMap->blue(); mUBOSize = mCMap->blueLen(); break; } } long long window_impl::context() const { return mCxt; } long long window_impl::display() const { return mDsp; } int window_impl::width() const { return mWidth; } int window_impl::height() const { return mHeight; } GLEWContext* window_impl::glewContext() const { return mGLEWContext; } const wtk::Widget* window_impl::get() const { return mWindow; } const std::shared_ptr<colormap_impl>& window_impl::colorMapPtr() const { return mCMap; } void window_impl::hide() { mWindow->hide(); } void window_impl::show() { mWindow->show(); } bool window_impl::close() { return mWindow->close(); } void window_impl::draw(const std::shared_ptr<AbstractRenderable>& pRenderable) { CheckGL("Begin drawImage"); MakeContextCurrent(this); mWindow->resetCloseFlag(); int wind_width, wind_height; mWindow->getFrameBufferSize(&wind_width, &wind_height); glViewport(0, 0, wind_width, wind_height); // clear color and depth buffers glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClearColor(GRAY[0], GRAY[1], GRAY[2], GRAY[3]); pRenderable->setColorMapUBOParams(mColorMapUBO, mUBOSize); pRenderable->render(mID, 0, 0, wind_width, wind_height); mWindow->swapBuffers(); mWindow->pollEvents(); CheckGL("End drawImage"); } void window_impl::grid(int pRows, int pCols) { mRows= pRows; mCols= pCols; int wind_width, wind_height; mWindow->getFrameBufferSize(&wind_width, &wind_height); glViewport(0, 0, wind_width, wind_height); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); mCellWidth = wind_width / mCols; mCellHeight = wind_height / mRows; } void window_impl::draw(int pColId, int pRowId, const std::shared_ptr<AbstractRenderable>& pRenderable, const char* pTitle) { CheckGL("Begin show(column, row)"); MakeContextCurrent(this); mWindow->resetCloseFlag(); float pos[2] = {0.0, 0.0}; int c = pColId; int r = pRowId; int x_off = c * mCellWidth; int y_off = (mRows - 1 - r) * mCellHeight; /* following margins are tested out for various * aspect ratios and are working fine. DO NOT CHANGE. * */ int top_margin = int(0.06f*mCellHeight); int bot_margin = int(0.02f*mCellHeight); int lef_margin = int(0.02f*mCellWidth); int rig_margin = int(0.02f*mCellWidth); // set viewport to render sub image glViewport(x_off + lef_margin, y_off + bot_margin, mCellWidth - 2 * rig_margin, mCellHeight - 2 * top_margin); glScissor(x_off + lef_margin, y_off + bot_margin, mCellWidth - 2 * rig_margin, mCellHeight - 2 * top_margin); glEnable(GL_SCISSOR_TEST); glClearColor(GRAY[0], GRAY[1], GRAY[2], GRAY[3]); pRenderable->setColorMapUBOParams(mColorMapUBO, mUBOSize); pRenderable->render(mID, x_off, y_off, mCellWidth, mCellHeight); glDisable(GL_SCISSOR_TEST); glViewport(x_off, y_off, mCellWidth, mCellHeight); if (pTitle!=NULL) { mFont->setOthro2D(mCellWidth, mCellHeight); pos[0] = mCellWidth / 3.0f; pos[1] = mCellHeight*0.92f; mFont->render(mID, pos, RED, pTitle, 16); } CheckGL("End show(column, row)"); } void window_impl::draw() { mWindow->swapBuffers(); mWindow->pollEvents(); } } namespace fg { Window::Window(int pWidth, int pHeight, const char* pTitle, const Window* pWindow, const bool invisible) { if (pWindow == nullptr) { value = new internal::_Window(pWidth, pHeight, pTitle, nullptr, invisible); } else { value = new internal::_Window(pWidth, pHeight, pTitle, pWindow->get(), invisible); } } Window::~Window() { delete value; } Window::Window(const Window& other) { value = new internal::_Window(*other.get()); } void Window::setFont(Font* pFont) { value->setFont(pFont->get()); } void Window::setTitle(const char* pTitle) { value->setTitle(pTitle); } void Window::setPos(int pX, int pY) { value->setPos(pX, pY); } void Window::setSize(unsigned pW, unsigned pH) { value->setSize(pW, pH); } void Window::setColorMap(ColorMap cmap) { value->setColorMap(cmap); } long long Window::context() const { return value->context(); } long long Window::display() const { return value->display(); } int Window::width() const { return value->width(); } int Window::height() const { return value->height(); } internal::_Window* Window::get() const { return value; } void Window::hide() { value->hide(); } void Window::show() { value->show(); } bool Window::close() { return value->close(); } void Window::makeCurrent() { value->makeCurrent(); } void Window::draw(const Image& pImage, const bool pKeepAspectRatio) { value->draw(pImage.get(), pKeepAspectRatio); } void Window::draw(const Plot& pPlot) { value->draw(pPlot.get()); } void Window::draw(const Histogram& pHist) { value->draw(pHist.get()); } void Window::grid(int pRows, int pCols) { value->grid(pRows, pCols); } void Window::draw(int pColId, int pRowId, const Image& pImage, const char* pTitle, const bool pKeepAspectRatio) { value->draw(pColId, pRowId, pImage.get(), pTitle, pKeepAspectRatio); } void Window::draw(int pColId, int pRowId, const Plot& pPlot, const char* pTitle) { value->draw(pColId, pRowId, pPlot.get(), pTitle); } void Window::draw(int pColId, int pRowId, const Histogram& pHist, const char* pTitle) { value->draw(pColId, pRowId, pHist.get(), pTitle); } void Window::draw() { value->draw(); } }
/******************************************************* * Copyright (c) 2015-2019, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ // Parts of this code sourced from SnopyDogy // https://gist.github.com/SnopyDogy/a9a22497a893ec86aa3e #include <common.hpp> #include <fg/window.h> #include <window.hpp> #include <memory> #include <mutex> using namespace fg; static GLEWContext* current = nullptr; GLEWContext* glewGetContext() { return current; } /* following function is thread safe */ int getNextUniqueId() { static int wndUnqIdTracker = 0; static std::mutex wndUnqIdMutex; std::lock_guard<std::mutex> lock(wndUnqIdMutex); return wndUnqIdTracker++; } namespace internal { void MakeContextCurrent(const window_impl* pWindow) { if (pWindow != NULL) { pWindow->get()->makeContextCurrent(); current = pWindow->glewContext(); } CheckGL("End MakeContextCurrent"); } window_impl::window_impl(int pWidth, int pHeight, const char* pTitle, std::weak_ptr<window_impl> pWindow, const bool invisible) : mID(getNextUniqueId()), mWidth(pWidth), mHeight(pHeight), mRows(0), mCols(0) { if (auto observe = pWindow.lock()) { mWindow = new wtk::Widget(pWidth, pHeight, pTitle, observe->get(), invisible); } else { /* when windows are not sharing any context, just create * a dummy wtk::Widget object and pass it on */ mWindow = new wtk::Widget(pWidth, pHeight, pTitle, nullptr, invisible); } /* create glew context so that it will bind itself to windows */ if (auto observe = pWindow.lock()) { mGLEWContext = observe->glewContext(); } else { mGLEWContext = new GLEWContext(); if (mGLEWContext == NULL) { std::cerr<<"Error: Could not create GLEW Context!\n"; throw fg::Error("window_impl constructor", __LINE__, "GLEW context creation failed", fg::FG_ERR_GL_ERROR); } } /* Set context (before glewInit()) */ MakeContextCurrent(this); /* GLEW Initialization - Must be done */ glewExperimental = GL_TRUE; GLenum err = glewInit(); if (err != GLEW_OK) { char buffer[128]; sprintf(buffer, "GLEW init failed: Error: %s\n", glewGetErrorString(err)); throw fg::Error("window_impl constructor", __LINE__, buffer, fg::FG_ERR_GL_ERROR); } err = glGetError(); if (err!=GL_NO_ERROR && err!=GL_INVALID_ENUM) { /* ignore this error, as GLEW is known to * have this issue with 3.2+ core profiles * they are yet to fix this in GLEW */ ForceCheckGL("GLEW initilization failed"); throw fg::Error("window_impl constructor", __LINE__, "GLEW initilization failed", fg::FG_ERR_GL_ERROR); } mCxt = mWindow->getGLContextHandle(); mDsp = mWindow->getDisplayHandle(); /* copy colormap shared pointer if * this window shares context with another window * */ if (auto observe = pWindow.lock()) { mCMap = observe->colorMapPtr(); } else { mCMap = std::make_shared<colormap_impl>(); } /* set the colormap to default */ mColorMapUBO = mCMap->defaultMap(); mUBOSize = mCMap->defaultLen(); glEnable(GL_MULTISAMPLE); CheckGL("End Window::Window"); } window_impl::~window_impl() { delete mWindow; } void window_impl::setFont(const std::shared_ptr<font_impl>& pFont) { mFont = pFont; } void window_impl::setTitle(const char* pTitle) { mWindow->setTitle(pTitle); } void window_impl::setPos(int pX, int pY) { mWindow->setPos(pX, pY); } void window_impl::setSize(unsigned pW, unsigned pH) { mWindow->setSize(pW, pH); } void window_impl::setColorMap(fg::ColorMap cmap) { switch(cmap) { case FG_DEFAULT: mColorMapUBO = mCMap->defaultMap(); mUBOSize = mCMap->defaultLen(); break; case FG_SPECTRUM: mColorMapUBO = mCMap->spectrum(); mUBOSize = mCMap->spectrumLen(); break; case FG_COLORS: mColorMapUBO = mCMap->colors(); mUBOSize = mCMap->colorsLen(); break; case FG_REDMAP: mColorMapUBO = mCMap->red(); mUBOSize = mCMap->redLen(); break; case FG_MOOD: mColorMapUBO = mCMap->mood(); mUBOSize = mCMap->moodLen(); break; case FG_HEAT: mColorMapUBO = mCMap->heat(); mUBOSize = mCMap->heatLen(); break; case FG_BLUEMAP: mColorMapUBO = mCMap->blue(); mUBOSize = mCMap->blueLen(); break; } } long long window_impl::context() const { return mCxt; } long long window_impl::display() const { return mDsp; } int window_impl::width() const { return mWidth; } int window_impl::height() const { return mHeight; } GLEWContext* window_impl::glewContext() const { return mGLEWContext; } const wtk::Widget* window_impl::get() const { return mWindow; } const std::shared_ptr<colormap_impl>& window_impl::colorMapPtr() const { return mCMap; } void window_impl::hide() { mWindow->hide(); } void window_impl::show() { mWindow->show(); } bool window_impl::close() { return mWindow->close(); } void window_impl::draw(const std::shared_ptr<AbstractRenderable>& pRenderable) { CheckGL("Begin drawImage"); MakeContextCurrent(this); mWindow->resetCloseFlag(); int wind_width, wind_height; mWindow->getFrameBufferSize(&wind_width, &wind_height); glViewport(0, 0, wind_width, wind_height); // clear color and depth buffers glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClearColor(GRAY[0], GRAY[1], GRAY[2], GRAY[3]); pRenderable->setColorMapUBOParams(mColorMapUBO, mUBOSize); pRenderable->render(mID, 0, 0, wind_width, wind_height); mWindow->swapBuffers(); mWindow->pollEvents(); CheckGL("End drawImage"); } void window_impl::grid(int pRows, int pCols) { mRows= pRows; mCols= pCols; int wind_width, wind_height; mWindow->getFrameBufferSize(&wind_width, &wind_height); glViewport(0, 0, wind_width, wind_height); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); mCellWidth = wind_width / mCols; mCellHeight = wind_height / mRows; } void window_impl::draw(int pColId, int pRowId, const std::shared_ptr<AbstractRenderable>& pRenderable, const char* pTitle) { CheckGL("Begin show(column, row)"); MakeContextCurrent(this); mWindow->resetCloseFlag(); float pos[2] = {0.0, 0.0}; int c = pColId; int r = pRowId; int x_off = c * mCellWidth; int y_off = (mRows - 1 - r) * mCellHeight; /* following margins are tested out for various * aspect ratios and are working fine. DO NOT CHANGE. * */ int top_margin = int(0.06f*mCellHeight); int bot_margin = int(0.02f*mCellHeight); int lef_margin = int(0.02f*mCellWidth); int rig_margin = int(0.02f*mCellWidth); // set viewport to render sub image glViewport(x_off + lef_margin, y_off + bot_margin, mCellWidth - 2 * rig_margin, mCellHeight - 2 * top_margin); glScissor(x_off + lef_margin, y_off + bot_margin, mCellWidth - 2 * rig_margin, mCellHeight - 2 * top_margin); glEnable(GL_SCISSOR_TEST); glClearColor(GRAY[0], GRAY[1], GRAY[2], GRAY[3]); pRenderable->setColorMapUBOParams(mColorMapUBO, mUBOSize); pRenderable->render(mID, x_off, y_off, mCellWidth, mCellHeight); glDisable(GL_SCISSOR_TEST); glViewport(x_off, y_off, mCellWidth, mCellHeight); if (pTitle!=NULL) { mFont->setOthro2D(mCellWidth, mCellHeight); pos[0] = mCellWidth / 3.0f; pos[1] = mCellHeight*0.92f; mFont->render(mID, pos, RED, pTitle, 16); } mWindow->swapBuffers(); mWindow->pollEvents(); CheckGL("End show(column, row)"); } void window_impl::draw() { mWindow->swapBuffers(); mWindow->pollEvents(); } } namespace fg { Window::Window(int pWidth, int pHeight, const char* pTitle, const Window* pWindow, const bool invisible) { if (pWindow == nullptr) { value = new internal::_Window(pWidth, pHeight, pTitle, nullptr, invisible); } else { value = new internal::_Window(pWidth, pHeight, pTitle, pWindow->get(), invisible); } } Window::~Window() { delete value; } Window::Window(const Window& other) { value = new internal::_Window(*other.get()); } void Window::setFont(Font* pFont) { value->setFont(pFont->get()); } void Window::setTitle(const char* pTitle) { value->setTitle(pTitle); } void Window::setPos(int pX, int pY) { value->setPos(pX, pY); } void Window::setSize(unsigned pW, unsigned pH) { value->setSize(pW, pH); } void Window::setColorMap(ColorMap cmap) { value->setColorMap(cmap); } long long Window::context() const { return value->context(); } long long Window::display() const { return value->display(); } int Window::width() const { return value->width(); } int Window::height() const { return value->height(); } internal::_Window* Window::get() const { return value; } void Window::hide() { value->hide(); } void Window::show() { value->show(); } bool Window::close() { return value->close(); } void Window::makeCurrent() { value->makeCurrent(); } void Window::draw(const Image& pImage, const bool pKeepAspectRatio) { value->draw(pImage.get(), pKeepAspectRatio); } void Window::draw(const Plot& pPlot) { value->draw(pPlot.get()); } void Window::draw(const Histogram& pHist) { value->draw(pHist.get()); } void Window::grid(int pRows, int pCols) { value->grid(pRows, pCols); } void Window::draw(int pColId, int pRowId, const Image& pImage, const char* pTitle, const bool pKeepAspectRatio) { value->draw(pColId, pRowId, pImage.get(), pTitle, pKeepAspectRatio); } void Window::draw(int pColId, int pRowId, const Plot& pPlot, const char* pTitle) { value->draw(pColId, pRowId, pPlot.get(), pTitle); } void Window::draw(int pColId, int pRowId, const Histogram& pHist, const char* pTitle) { value->draw(pColId, pRowId, pHist.get(), pTitle); } void Window::draw() { value->draw(); } }
refresh grids bugfix
refresh grids bugfix
C++
bsd-3-clause
pavanky/forge,syurkevi/forge,arrayfire/forge,syurkevi/forge,arrayfire/forge,pavanky/forge
b1fc30ca79e93bea5a3efc63d01ef9dd67c9c674
src/main.cc
src/main.cc
#include <cassert> #include <cstdio> #include <cstdlib> #include <cstring> #include <time.h> #include <stdint.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include "erl_interface.h" #include "ei.h" #include <chrono> #include <algorithm> #include <iostream> #include <queue> #include <string> #include <unordered_map> #include "types.hh" #include "tally.hh" #include "event_array.hh" #include "leaderboard.hh" #include "idx_assigner.hh" #include "erl_utils.hh" #include "count_handlers.hh" #include "metric_handlers.hh" #include "test_suite.hh" #define BUFSIZE 1024 bool is_call_funcname(std::string func_name, ETERM* message); #define IS_CALL_SYSTEM_START(X) (is_call_funcname("system_start", X)) #define IS_CALL_COUNT_ORDER(X) (is_call_funcname("count_order", X)) #define IS_CALL_COUNT_HANDLE_EVENT(X) (is_call_funcname("count_event", X)) #define IS_CALL_COUNT_HANDLE_EVENT_TZ(X) (is_call_funcname("count_event_tz", X)) #define IS_CALL_COUNT_GET_COUNTER(X) (is_call_funcname("count_get_counter", X)) #define IS_CALL_COUNT_GET_LEADERBOARD(X) (is_call_funcname("count_get_leaderboard", X)) #define IS_CALL_COUNT_LIST_LEADERBOARDS(X) (is_call_funcname("count_list_leaderboards", X)) #define IS_CALL_METRIC_HANDLE_EVENT(X) (is_call_funcname("metric_event", X)) #define IS_CALL_METRIC_ORDER(X) (is_call_funcname("metric_order", X)) #define IS_CALL_METRIC_HANDLE_EVENT_TZ(X) (is_call_funcname("metric_event_tz", X)) #define IS_CALL_METRIC_GET_COUNTER(X) (is_call_funcname("metric_get_counter", X)) #define IS_CALL_METRIC_GET_LEADERBOARD(X) (is_call_funcname("metric_get_leaderboard", X)) #define IS_CALL_METRIC_LIST_LEADERBOARDS(X) (is_call_funcname("metric_list_leaderboards", X)) int my_listen(int port); std::string term2str(ETERM* ch_str) { unsigned char* str = ERL_BIN_PTR(ch_str); return std::string(str, str + ERL_BIN_SIZE(ch_str)); } std::ostream& operator<<(std::ostream& out, const struct event e) { out << "{event, " << e.timestamp << ", " << e.event_idx << "}"; return out; } std::ostream& operator<<(std::ostream& out, const struct event_metric e) { out << "{metric_event, " << e.timestamp << ", " << e.event_idx << ", " << e.payload << "}"; return out; } void handle_start(ErlMessage& emsg, tally& tally_srv) { std::cout << "handle start" << std::endl; while(!tally_srv.count_buffer_queue.empty()){ tally_srv.handle_count_event(tally_srv.count_buffer_queue.front().first, tally_srv.count_buffer_queue.front().second); tally_srv.count_buffer_queue.dequeue(); } while(!tally_srv.metric_buffer_queue.empty()){ tally_srv.handle_metric_event(tally_srv.metric_buffer_queue.front().first.first, tally_srv.metric_buffer_queue.front().first.second, tally_srv.metric_buffer_queue.front().second); tally_srv.metric_buffer_queue.dequeue(); } tally_srv.started = true; } int main(int argc, char **argv) { std::cout << "stating tally at UnixTimeStamp: " << time(0) << std::endl; counter_array<int> c_arr; std::cout << "c_arr[1] : "<< c_arr[1] << std::endl; assert(test_suite()); if(argc != 5) { std::cout << "usage: ./tally_srv <ip> <localname> <longname> <cookie>" << std::endl; std::cout << "example: ./etally_srv \"127.0.0.1\" \"msk-dev\" \"[email protected]\" \"secretcookie\"" << std::endl; return -1; } struct in_addr addr; /* 32-bit IP number of host */ int listen; /* Listen socket */ int fd; /* fd to Erlang node */ ErlConnect conn; /* Connection data */ int receive_status; /* Result of receive */ unsigned char buf[BUFSIZE]; /* Buffer for incoming message */ ErlMessage emsg; /* Incoming message */ int port = 3456; char *erl_secret = argv[4]; char erl_node[] = "tally"; char *erl_localname = argv[2]; char *erl_longname = argv[3]; const unsigned int hour = 60*60; const unsigned int day = 24*hour; const unsigned int week = 7*day; const unsigned int month = 4 *week; std::vector<unsigned> intervals = {5*60, hour, 2*hour, day, 2*day, 3*day, 4*day, 5*day, 6*day, week, 2*week, month, 2*month}; std::vector<unsigned> leaderboard_intervals = {hour, day, week, month}; std::vector<unsigned> percentile_intervals = {hour, day, week, month}; std::reverse(intervals.begin(), intervals.end()); tally tally_srv(intervals, leaderboard_intervals, percentile_intervals); erl_init(NULL, 0); addr.s_addr = inet_addr(argv[1]); if (erl_connect_xinit(erl_localname, erl_node, erl_longname, &addr, erl_secret, 0) == -1) erl_err_quit("erl_connect_xinit failed"); if ((listen = my_listen(port)) <= 0) erl_err_quit("my_listen failed ( likely unable to connect to socket )"); if (erl_publish(port) == -1) erl_err_quit("erl_publish failed"); while(true) { if ((fd = erl_accept(listen, &conn)) == ERL_ERROR) erl_err_quit("erl_accept failed"); int count = 0; time_t previous_ts = time(0); int loop = 1; /* Loop flag */ while (loop) { receive_status = erl_receive_msg(fd, buf, BUFSIZE, &emsg); if (receive_status == ERL_TICK) { /* ignore */ } else if (receive_status == ERL_ERROR) { std::cerr << "[warning] connection to remote node dropped - will try to reconnect" << std::endl; loop= 0; } else { if (emsg.type == ERL_REG_SEND) { time_t current_ts = time(0); count ++; if(current_ts != previous_ts) { tally_srv.update(current_ts); // std::cout << "count = " << count << std::endl; count = 0; } if (IS_CALL_SYSTEM_START (emsg.msg)) { std::cout << "start call" << std::endl; handle_start(emsg, tally_srv); } else if (IS_CALL_COUNT_ORDER (emsg.msg)) { tally_srv.sort(); } else if (IS_CALL_COUNT_HANDLE_EVENT_TZ (emsg.msg)) count_handle_event_timestamp (emsg, tally_srv); else if (IS_CALL_COUNT_HANDLE_EVENT (emsg.msg)) count_handle_event (emsg, tally_srv); else if (IS_CALL_COUNT_GET_COUNTER (emsg.msg)) count_handle_get_counter (emsg, tally_srv, fd); else if (IS_CALL_COUNT_GET_LEADERBOARD (emsg.msg)) count_handle_get_leaderboard (emsg, tally_srv, fd); else if (IS_CALL_COUNT_LIST_LEADERBOARDS(emsg.msg)) count_handle_list_leaderboards(emsg, tally_srv, fd); else if (IS_CALL_METRIC_ORDER (emsg.msg)) { tally_srv.sort(); } else if (IS_CALL_METRIC_HANDLE_EVENT_TZ (emsg.msg)) metric_handle_event_timestamp (emsg, tally_srv); else if (IS_CALL_METRIC_HANDLE_EVENT (emsg.msg)) metric_handle_event (emsg, tally_srv); else if (IS_CALL_METRIC_GET_COUNTER (emsg.msg)) metric_handle_get_counter (emsg, tally_srv, fd); else if (IS_CALL_METRIC_GET_LEADERBOARD (emsg.msg)) metric_handle_get_leaderboard (emsg, tally_srv, fd); else if (IS_CALL_METRIC_LIST_LEADERBOARDS(emsg.msg)) metric_handle_list_leaderboards(emsg, tally_srv, fd); erl_free_term(emsg.to); erl_free_term(emsg.from); erl_free_term(emsg.msg); previous_ts = current_ts; } } } erl_close_connection(fd); } } bool is_call_funcname(std::string func_name, ETERM* call_term) { ETERM *tuplep = erl_element(ERL_TUPLE_SIZE(call_term), call_term); ETERM *fnp = erl_element(1, tuplep ); bool res = (strncmp(ERL_ATOM_PTR(fnp), func_name.c_str(), strlen(func_name.c_str())) == 0); erl_free_term(tuplep); erl_free_term(fnp); return res; } int my_listen(int port) { int listen_fd; struct sockaddr_in addr; int on = 1; if ((listen_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) return (-1); setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)); memset((void*) &addr, 0, (size_t) sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = htons(port); addr.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(listen_fd, (struct sockaddr*) &addr, sizeof(addr)) < 0) return (-1); listen(listen_fd, 10); return listen_fd; }
#include <cassert> #include <cstdio> #include <cstdlib> #include <cstring> #include <time.h> #include <stdint.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include "erl_interface.h" #include "ei.h" #include <chrono> #include <algorithm> #include <iostream> #include <queue> #include <string> #include <unordered_map> #include "types.hh" #include "tally.hh" #include "event_array.hh" #include "leaderboard.hh" #include "idx_assigner.hh" #include "erl_utils.hh" #include "count_handlers.hh" #include "metric_handlers.hh" #include "test_suite.hh" #define BUFSIZE 1024 bool is_call_funcname(std::string func_name, ETERM* message); #define IS_CALL_SYSTEM_START(X) (is_call_funcname("system_start", X)) #define IS_CALL_COUNT_ORDER(X) (is_call_funcname("count_order", X)) #define IS_CALL_COUNT_HANDLE_EVENT(X) (is_call_funcname("count_event", X)) #define IS_CALL_COUNT_HANDLE_EVENT_TZ(X) (is_call_funcname("count_event_tz", X)) #define IS_CALL_COUNT_GET_COUNTER(X) (is_call_funcname("count_get_counter", X)) #define IS_CALL_COUNT_GET_LEADERBOARD(X) (is_call_funcname("count_get_leaderboard", X)) #define IS_CALL_COUNT_LIST_LEADERBOARDS(X) (is_call_funcname("count_list_leaderboards", X)) #define IS_CALL_METRIC_HANDLE_EVENT(X) (is_call_funcname("metric_event", X)) #define IS_CALL_METRIC_ORDER(X) (is_call_funcname("metric_order", X)) #define IS_CALL_METRIC_HANDLE_EVENT_TZ(X) (is_call_funcname("metric_event_tz", X)) #define IS_CALL_METRIC_GET_COUNTER(X) (is_call_funcname("metric_get_counter", X)) #define IS_CALL_METRIC_GET_LEADERBOARD(X) (is_call_funcname("metric_get_leaderboard", X)) #define IS_CALL_METRIC_LIST_LEADERBOARDS(X) (is_call_funcname("metric_list_leaderboards", X)) int my_listen(int port); std::string term2str(ETERM* ch_str) { unsigned char* str = ERL_BIN_PTR(ch_str); return std::string(str, str + ERL_BIN_SIZE(ch_str)); } std::ostream& operator<<(std::ostream& out, const struct event e) { out << "{event, " << e.timestamp << ", " << e.event_idx << "}"; return out; } std::ostream& operator<<(std::ostream& out, const struct event_metric e) { out << "{metric_event, " << e.timestamp << ", " << e.event_idx << ", " << e.payload << "}"; return out; } void handle_start(ErlMessage& emsg, tally& tally_srv) { std::cout << "handle start" << std::endl; while(!tally_srv.count_buffer_queue.empty()){ tally_srv.handle_count_event(tally_srv.count_buffer_queue.front().first, tally_srv.count_buffer_queue.front().second); tally_srv.count_buffer_queue.dequeue(); } while(!tally_srv.metric_buffer_queue.empty()){ tally_srv.handle_metric_event(tally_srv.metric_buffer_queue.front().first.first, tally_srv.metric_buffer_queue.front().first.second, tally_srv.metric_buffer_queue.front().second); tally_srv.metric_buffer_queue.dequeue(); } tally_srv.started = true; } int main(int argc, char **argv) { std::cout << "stating tally at UnixTimeStamp: " << time(0) << std::endl; counter_array<int> c_arr; std::cout << "c_arr[1] : "<< c_arr[1] << std::endl; // assert(test_suite()); if(argc != 5) { std::cout << "usage: ./tally_srv <ip> <localname> <longname> <cookie>" << std::endl; std::cout << "example: ./etally_srv \"127.0.0.1\" \"msk-dev\" \"[email protected]\" \"secretcookie\"" << std::endl; return -1; } struct in_addr addr; /* 32-bit IP number of host */ int listen; /* Listen socket */ int fd; /* fd to Erlang node */ ErlConnect conn; /* Connection data */ int receive_status; /* Result of receive */ unsigned char buf[BUFSIZE]; /* Buffer for incoming message */ ErlMessage emsg; /* Incoming message */ int port = 3456; char *erl_secret = argv[4]; char erl_node[] = "tally"; char *erl_localname = argv[2]; char *erl_longname = argv[3]; const unsigned int hour = 60*60; const unsigned int day = 24*hour; const unsigned int week = 7*day; const unsigned int month = 4 *week; std::vector<unsigned> intervals = {5*60, hour, 2*hour, day, 2*day, 3*day, 4*day, 5*day, 6*day, week, 2*week, month, 2*month}; std::vector<unsigned> leaderboard_intervals = {hour, day, week, month}; std::vector<unsigned> percentile_intervals = {hour, day, week, month}; std::reverse(intervals.begin(), intervals.end()); tally tally_srv(intervals, leaderboard_intervals, percentile_intervals); erl_init(NULL, 0); addr.s_addr = inet_addr(argv[1]); if (erl_connect_xinit(erl_localname, erl_node, erl_longname, &addr, erl_secret, 0) == -1) erl_err_quit("erl_connect_xinit failed"); if ((listen = my_listen(port)) <= 0) erl_err_quit("my_listen failed ( likely unable to connect to socket )"); if (erl_publish(port) == -1) erl_err_quit("erl_publish failed"); while(true) { if ((fd = erl_accept(listen, &conn)) == ERL_ERROR) erl_err_quit("erl_accept failed"); int count = 0; time_t previous_ts = time(0); int loop = 1; /* Loop flag */ while (loop) { receive_status = erl_receive_msg(fd, buf, BUFSIZE, &emsg); if (receive_status == ERL_TICK) { /* ignore */ } else if (receive_status == ERL_ERROR) { std::cerr << "[warning] connection to remote node dropped - will try to reconnect" << std::endl; loop= 0; } else { if (emsg.type == ERL_REG_SEND) { time_t current_ts = time(0); count ++; if(current_ts != previous_ts) { tally_srv.update(current_ts); // std::cout << "count = " << count << std::endl; count = 0; } if (IS_CALL_SYSTEM_START (emsg.msg)) { std::cout << "start call" << std::endl; handle_start(emsg, tally_srv); } else if (IS_CALL_COUNT_ORDER (emsg.msg)) { tally_srv.sort(); } else if (IS_CALL_COUNT_HANDLE_EVENT_TZ (emsg.msg)) count_handle_event_timestamp (emsg, tally_srv); else if (IS_CALL_COUNT_HANDLE_EVENT (emsg.msg)) count_handle_event (emsg, tally_srv); else if (IS_CALL_COUNT_GET_COUNTER (emsg.msg)) count_handle_get_counter (emsg, tally_srv, fd); else if (IS_CALL_COUNT_GET_LEADERBOARD (emsg.msg)) count_handle_get_leaderboard (emsg, tally_srv, fd); else if (IS_CALL_COUNT_LIST_LEADERBOARDS(emsg.msg)) count_handle_list_leaderboards(emsg, tally_srv, fd); else if (IS_CALL_METRIC_ORDER (emsg.msg)) { tally_srv.sort(); } else if (IS_CALL_METRIC_HANDLE_EVENT_TZ (emsg.msg)) metric_handle_event_timestamp (emsg, tally_srv); else if (IS_CALL_METRIC_HANDLE_EVENT (emsg.msg)) metric_handle_event (emsg, tally_srv); else if (IS_CALL_METRIC_GET_COUNTER (emsg.msg)) metric_handle_get_counter (emsg, tally_srv, fd); else if (IS_CALL_METRIC_GET_LEADERBOARD (emsg.msg)) metric_handle_get_leaderboard (emsg, tally_srv, fd); else if (IS_CALL_METRIC_LIST_LEADERBOARDS(emsg.msg)) metric_handle_list_leaderboards(emsg, tally_srv, fd); erl_free_term(emsg.to); erl_free_term(emsg.from); erl_free_term(emsg.msg); previous_ts = current_ts; } } } erl_close_connection(fd); } } bool is_call_funcname(std::string func_name, ETERM* call_term) { ETERM *tuplep = erl_element(ERL_TUPLE_SIZE(call_term), call_term); ETERM *fnp = erl_element(1, tuplep ); bool res = (strncmp(ERL_ATOM_PTR(fnp), func_name.c_str(), strlen(func_name.c_str())) == 0); erl_free_term(tuplep); erl_free_term(fnp); return res; } int my_listen(int port) { int listen_fd; struct sockaddr_in addr; int on = 1; if ((listen_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) return (-1); setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)); memset((void*) &addr, 0, (size_t) sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = htons(port); addr.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(listen_fd, (struct sockaddr*) &addr, sizeof(addr)) < 0) return (-1); listen(listen_fd, 10); return listen_fd; }
Update main.cc
Update main.cc removed test suite
C++
mit
martinsk/etally_core
fd479683f1cc9cf62a5fb2b7c8250d993fbf6bc3
src/ylocale.cc
src/ylocale.cc
/* * IceWM - C++ wrapper for locale/unicode conversion * Copyright (C) 2001 The Authors of IceWM * * Released under terms of the GNU Library General Public License * * 2001/07/21: Mathias Hasselmann <[email protected]> * - initial revision */ #include "config.h" #include "ylocale.h" #include "base.h" #include "intl.h" #include <string.h> #ifdef CONFIG_I18N #include <errno.h> #include <langinfo.h> #include <locale.h> #include <stdlib.h> #include <wchar.h> #include <assert.h> #endif #include "ylib.h" #include "yprefs.h" #ifdef CONFIG_I18N YLocale * YLocale::instance(NULL); #endif #ifndef CONFIG_I18N YLocale::YLocale(char const * ) { #else YLocale::YLocale(char const * localeName) { assert(NULL == instance); instance = this; if (NULL == (fLocaleName = setlocale(LC_ALL, localeName)) /* || False == XSupportsLocale()*/) { warn(_("Locale not supported by C library. " "Falling back to 'C' locale'.")); fLocaleName = setlocale(LC_ALL, "C"); } #ifndef NO_CONFIGURE multiByte = true; #endif char const * codeset = NULL; int const codesetItems[] = { #ifdef CONFIG_NL_CODESETS CONFIG_NL_CODESETS #else CODESET, _NL_CTYPE_CODESET_NAME, 0 #endif }; for (unsigned int i = 0; i + 1 < ACOUNT(codesetItems) && NULL != (codeset = nl_langinfo(codesetItems[i])) && '\0' == *codeset; ++i) {} if (NULL == codeset || '\0' == *codeset) { warn(_("Failed to determinate the current locale's codeset. " "Assuming ISO-8859-1.\n")); codeset = "ISO-8859-1"; } union { int i; char c[sizeof(int)]; } endian; endian.i = 1; MSG(("locale: %s, MB_CUR_MAX: %ld, " "multibyte: %d, codeset: %s, endian: %c", fLocaleName, MB_CUR_MAX, multiByte, codeset, endian.c ? 'b' : 'l')); /// TODO #warning "this is getting way too complicated" char const * unicodeCharsets[] = { #ifdef CONFIG_UNICODE_SET CONFIG_UNICODE_SET, #endif // "WCHAR_T//TRANSLIT", (*endian.c ? "UCS-4LE//TRANSLIT" : "UCS-4BE//TRANSLIT"), // "WCHAR_T", (*endian.c ? "UCS-4LE" : "UCS-4BE"), "UCS-4//TRANSLIT", "UCS-4", NULL }; char const * localeCharsets[] = { cstrJoin(codeset, "//TRANSLIT", NULL), codeset, NULL }; char const ** ucs(unicodeCharsets); if ((iconv_t) -1 == (toUnicode = getConverter (localeCharsets[1], ucs))) die(1, _("iconv doesn't supply (sufficient) " "%s to %s converters."), localeCharsets[1], "Unicode"); MSG(("toUnicode converts from %s to %s", localeCharsets[1], *ucs)); char const ** lcs(localeCharsets); if ((iconv_t) -1 == (toLocale = getConverter (*ucs, lcs))) die(1, _("iconv doesn't supply (sufficient) " "%s to %s converters."), "Unicode", localeCharsets[1]); MSG(("toLocale converts from %s to %s", *ucs, *lcs)); delete[] localeCharsets[0]; #endif #ifdef ENABLE_NLS bindtextdomain(PACKAGE, LOCDIR); textdomain(PACKAGE); #endif } YLocale::~YLocale() { #ifdef CONFIG_I18N instance = NULL; if ((iconv_t) -1 != toUnicode) iconv_close(toUnicode); if ((iconv_t) -1 != toLocale) iconv_close(toLocale); #endif } #ifdef CONFIG_I18N iconv_t YLocale::getConverter (const char *from, const char **&to) { iconv_t cd = (iconv_t) -1; while (NULL != *to) if ((iconv_t) -1 != (cd = iconv_open(*to, from))) return cd; else ++to; return (iconv_t) -1; } /* YLChar * YLocale::localeString(YUChar const * uStr) { YLChar * lStr(NULL); return lStr; } */ YUChar *YLocale::unicodeString(const YLChar *lStr, size_t const lLen, size_t & uLen) { PRECONDITION(instance != NULL); if (NULL == lStr) return NULL; YUChar * uStr(new YUChar[lLen + 1]); char * inbuf((char *) lStr), * outbuf((char *) uStr); size_t inlen(lLen), outlen(4 * lLen); if (0 > (int) iconv(instance->toUnicode, &inbuf, &inlen, &outbuf, &outlen)) warn(_("Invalid multibyte string \"%s\": %s"), lStr, strerror(errno)); *((YUChar *) outbuf) = 0; uLen = ((YUChar *) outbuf) - uStr; return uStr; } #endif const char *YLocale::getLocaleName() { #ifdef CONFIG_I18N return instance->fLocaleName; #else return "C"; #endif } int YLocale::getRating(const char *localeStr) { const char *s1 = getLocaleName(); const char *s2 = localeStr; while (*s1 && *s1++ == *s2++) {} if (*s1) while (--s2 > localeStr && !strchr("_@.", *s2)) {} return s2 - localeStr; }
/* * IceWM - C++ wrapper for locale/unicode conversion * Copyright (C) 2001 The Authors of IceWM * * Released under terms of the GNU Library General Public License * * 2001/07/21: Mathias Hasselmann <[email protected]> * - initial revision */ #include "config.h" #include "ylocale.h" #include "base.h" #include "intl.h" #include <string.h> #ifdef CONFIG_I18N #include <errno.h> #include <langinfo.h> #include <locale.h> #include <stdlib.h> #include <wchar.h> #include <assert.h> #endif #include "ylib.h" #include "yprefs.h" #ifdef CONFIG_I18N YLocale * YLocale::instance(NULL); #endif #ifndef CONFIG_I18N YLocale::YLocale(char const * ) { #else YLocale::YLocale(char const * localeName) { assert(NULL == instance); instance = this; if (NULL == (fLocaleName = setlocale(LC_ALL, localeName)) /* || False == XSupportsLocale()*/) { warn(_("Locale not supported by C library. " "Falling back to 'C' locale'.")); fLocaleName = setlocale(LC_ALL, "C"); } #ifndef NO_CONFIGURE multiByte = true; #endif char const * codeset = NULL; int const codesetItems[] = { #ifdef CONFIG_NL_CODESETS CONFIG_NL_CODESETS #else CODESET, _NL_CTYPE_CODESET_NAME, 0 #endif }; for (unsigned int i = 0; i + 1 < ACOUNT(codesetItems) && NULL != (codeset = nl_langinfo(codesetItems[i])) && '\0' == *codeset; ++i) {} if (NULL == codeset || '\0' == *codeset) { warn(_("Failed to determinate the current locale's codeset. " "Assuming ISO-8859-1.\n")); codeset = "ISO-8859-1"; } union { int i; char c[sizeof(int)]; } endian; endian.i = 1; MSG(("locale: %s, MB_CUR_MAX: %zd, " "multibyte: %d, codeset: %s, endian: %c", fLocaleName, MB_CUR_MAX, multiByte, codeset, endian.c ? 'b' : 'l')); /// TODO #warning "this is getting way too complicated" char const * unicodeCharsets[] = { #ifdef CONFIG_UNICODE_SET CONFIG_UNICODE_SET, #endif // "WCHAR_T//TRANSLIT", (*endian.c ? "UCS-4LE//TRANSLIT" : "UCS-4BE//TRANSLIT"), // "WCHAR_T", (*endian.c ? "UCS-4LE" : "UCS-4BE"), "UCS-4//TRANSLIT", "UCS-4", NULL }; char const * localeCharsets[] = { cstrJoin(codeset, "//TRANSLIT", NULL), codeset, NULL }; char const ** ucs(unicodeCharsets); if ((iconv_t) -1 == (toUnicode = getConverter (localeCharsets[1], ucs))) die(1, _("iconv doesn't supply (sufficient) " "%s to %s converters."), localeCharsets[1], "Unicode"); MSG(("toUnicode converts from %s to %s", localeCharsets[1], *ucs)); char const ** lcs(localeCharsets); if ((iconv_t) -1 == (toLocale = getConverter (*ucs, lcs))) die(1, _("iconv doesn't supply (sufficient) " "%s to %s converters."), "Unicode", localeCharsets[1]); MSG(("toLocale converts from %s to %s", *ucs, *lcs)); delete[] localeCharsets[0]; #endif #ifdef ENABLE_NLS bindtextdomain(PACKAGE, LOCDIR); textdomain(PACKAGE); #endif } YLocale::~YLocale() { #ifdef CONFIG_I18N instance = NULL; if ((iconv_t) -1 != toUnicode) iconv_close(toUnicode); if ((iconv_t) -1 != toLocale) iconv_close(toLocale); #endif } #ifdef CONFIG_I18N iconv_t YLocale::getConverter (const char *from, const char **&to) { iconv_t cd = (iconv_t) -1; while (NULL != *to) if ((iconv_t) -1 != (cd = iconv_open(*to, from))) return cd; else ++to; return (iconv_t) -1; } /* YLChar * YLocale::localeString(YUChar const * uStr) { YLChar * lStr(NULL); return lStr; } */ YUChar *YLocale::unicodeString(const YLChar *lStr, size_t const lLen, size_t & uLen) { PRECONDITION(instance != NULL); if (NULL == lStr) return NULL; YUChar * uStr(new YUChar[lLen + 1]); char * inbuf((char *) lStr), * outbuf((char *) uStr); size_t inlen(lLen), outlen(4 * lLen); if (0 > (int) iconv(instance->toUnicode, &inbuf, &inlen, &outbuf, &outlen)) warn(_("Invalid multibyte string \"%s\": %s"), lStr, strerror(errno)); *((YUChar *) outbuf) = 0; uLen = ((YUChar *) outbuf) - uStr; return uStr; } #endif const char *YLocale::getLocaleName() { #ifdef CONFIG_I18N return instance->fLocaleName; #else return "C"; #endif } int YLocale::getRating(const char *localeStr) { const char *s1 = getLocaleName(); const char *s2 = localeStr; while (*s1 && *s1++ == *s2++) {} if (*s1) while (--s2 > localeStr && !strchr("_@.", *s2)) {} return s2 - localeStr; }
correct format error
correct format error
C++
lgpl-2.1
dicej/icewm,dicej/icewm,dicej/icewm,dicej/icewm
88a5b246f1ccff2fe978b12a8ca52194f798a06d
testvectorsfile.cpp
testvectorsfile.cpp
#include "testvectorsfile.h" #include "serializer.h" #include "consts.h" #include "blob.h" #include <iostream> #include <string> namespace { template< typename T > Blob createFileBlobHash( const T& content ) { std::vector< Blob > partials; for ( size_t pos = 0; pos < content.size(); pos += simpleFileSizeLimit ) { size_t partSize = std::min( simpleFileSizeLimit, content.size() - pos ); std::vector<char> partContent( content.begin()+pos, content.begin()+pos+partSize ); partials.push_back( Blob::newHashValidatedBlob( blobType_simpleStaticFile, partContent ) ); } // Make sure we've got at least one blob if ( partials.empty() ) { partials.push_back( Blob::newHashValidatedBlob( blobType_simpleStaticFile, std::string() ) ); } // Don't have to split the blob if it fits in one part if ( partials.size() == 1 ) { return partials.front(); } std::cout << "SPLIT FILE!!!" << std::endl; // Create extra blob containing information about the parts Serializer s; s << content.size() << partials.size(); for ( const auto& blob: partials ) s << blob.getBid() << blob.getKey(); return Blob::newHashValidatedBlob( blobType_splitStaticFile, s.getData() ); } void dumpFileBlobHash( const std::string& content, const std::string& name ) { createFileBlobHash(content).dump( name ); } void dumpFileBlobHash( const std::string& content ) { std::string name = "Simple File: '" + content.substr(0,20); if ( content.size()>20 ) name.append("..."); name.append("'"); dumpFileBlobHash( content, name ); } } void createFileTestVectors() { dumpFileBlobHash( "" ); dumpFileBlobHash( "a" ); dumpFileBlobHash( "Hello World!" ); std::string str; for( char ch = 'a'; ch <= 'z'; ch++ ) str.push_back(ch); for( char ch = 'A'; ch <= 'Z'; ch++ ) str.push_back(ch); dumpFileBlobHash( str ); std::string aaa; for ( size_t i=0; i<simpleFileSizeLimit; i++ ) aaa.push_back('a'); dumpFileBlobHash( aaa, "Maximum simple file size filled with 'a'" ); }
#include "testvectorsfile.h" #include "serializer.h" #include "consts.h" #include "blob.h" #include <iostream> #include <string> namespace { template< typename T > Blob createFileBlobHash( const T& content ) { std::vector< Blob > partials; for ( size_t pos = 0; pos < content.size(); pos += simpleFileSizeLimit ) { size_t partSize = std::min( simpleFileSizeLimit, content.size() - pos ); std::vector<char> partContent( content.begin()+pos, content.begin()+pos+partSize ); partials.push_back( Blob::newHashValidatedBlob( blobType_simpleStaticFile, partContent ) ); } // Make sure we've got at least one blob if ( partials.empty() ) { partials.push_back( Blob::newHashValidatedBlob( blobType_simpleStaticFile, std::string() ) ); } // Don't have to split the blob if it fits in one part if ( partials.size() == 1 ) { return partials.front(); } std::cout << "SPLIT FILE!!!" << std::endl; // Create extra blob containing information about the parts Serializer s; s << content.size() << partials.size(); for ( const auto& blob: partials ) s << blob.getBid() << blob.getKey(); return Blob::newHashValidatedBlob( blobType_splitStaticFile, s.getData() ); } void dumpFileBlobHash( const std::string& content, const std::string& name ) { createFileBlobHash(content).dump( name ); } void dumpFileBlobHash( const std::string& content ) { std::string name = "Simple File: '" + content.substr(0,20); if ( content.size()>20 ) name.append("..."); name.append("'"); dumpFileBlobHash( content, name ); } } void createFileTestVectors() { dumpFileBlobHash( "" ); dumpFileBlobHash( "a" ); dumpFileBlobHash( "Hello World!" ); std::string str; for( char ch = 'a'; ch <= 'z'; ch++ ) str.push_back(ch); for( char ch = 'A'; ch <= 'Z'; ch++ ) str.push_back(ch); dumpFileBlobHash( str ); std::string aaa; for ( size_t i=0; i<simpleFileSizeLimit; i++ ) aaa.push_back('a'); dumpFileBlobHash( aaa, "Maximum simple file size filled with 'a'" ); aaa.push_back('a'); dumpFileBlobHash( aaa, "One byte over the simple size limit, filled with 'a'" ); }
Add generation of split file test vector
Add generation of split file test vector
C++
bsd-3-clause
cinode/cpptestapp,cinode/cpptestapp
9f6f711f8d5d2ce1c6983a03076aecd08ca05736
tgt-vhdl/process.cc
tgt-vhdl/process.cc
/* * VHDL code generation for processes. * * Copyright (C) 2008 Nick Gasson ([email protected]) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "vhdl_target.h" #include "vhdl_element.hh" #include <iostream> #include <cassert> #include <sstream> /* * Convert a Verilog process to VHDL and add it to the architecture * of the given entity. */ static int generate_vhdl_process(vhdl_entity *ent, ivl_process_t proc) { set_active_entity(ent); // Create a new process and store it in the entity's // architecture. This needs to be done first or the // parent link won't be valid (and draw_stmt needs this // to add information to the architecture) vhdl_process *vhdl_proc = new vhdl_process(); ent->get_arch()->add_stmt(vhdl_proc); // If this is an initial process, push signal initialisation // into the declarations vhdl_proc->get_scope()->set_initializing (ivl_process_type(proc) == IVL_PR_INITIAL); ivl_statement_t stmt = ivl_process_stmt(proc); int rc = draw_stmt(vhdl_proc, vhdl_proc->get_container(), stmt); if (rc != 0) return rc; // Initial processes are translated to VHDL processes with // no sensitivity list and and indefinite wait statement at // the end // However, if no statements were added to the container // by draw_stmt, don't bother adding a wait as `emit' // will optimise the process out of the output if (ivl_process_type(proc) == IVL_PR_INITIAL && !vhdl_proc->get_container()->empty()) { vhdl_wait_stmt *wait = new vhdl_wait_stmt(); vhdl_proc->get_container()->add_stmt(wait); } // Add a comment indicating where it came from ivl_scope_t scope = ivl_process_scope(proc); const char *type = ivl_process_type(proc) == IVL_PR_INITIAL ? "initial" : "always"; std::ostringstream ss; ss << "Generated from " << type << " process in "; ss << ivl_scope_tname(scope); vhdl_proc->set_comment(ss.str()); set_active_entity(NULL); return 0; } int draw_process(ivl_process_t proc, void *cd) { ivl_scope_t scope = ivl_process_scope(proc); const char *scope_name = ivl_scope_name(scope); // A process should occur in a module scope, therefore it // should have already been assigned a VHDL entity assert(ivl_scope_type(scope) == IVL_SCT_MODULE); vhdl_entity *ent = find_entity(ivl_scope_name(scope)); assert(ent != NULL); return generate_vhdl_process(ent, proc); }
/* * VHDL code generation for processes. * * Copyright (C) 2008 Nick Gasson ([email protected]) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "vhdl_target.h" #include "vhdl_element.hh" #include <iostream> #include <cassert> #include <sstream> /* * Convert a Verilog process to VHDL and add it to the architecture * of the given entity. */ static int generate_vhdl_process(vhdl_entity *ent, ivl_process_t proc) { set_active_entity(ent); // Create a new process and store it in the entity's // architecture. This needs to be done first or the // parent link won't be valid (and draw_stmt needs this // to add information to the architecture) vhdl_process *vhdl_proc = new vhdl_process(); ent->get_arch()->add_stmt(vhdl_proc); // If this is an initial process, push signal initialisation // into the declarations vhdl_proc->get_scope()->set_initializing (ivl_process_type(proc) == IVL_PR_INITIAL); ivl_statement_t stmt = ivl_process_stmt(proc); int rc = draw_stmt(vhdl_proc, vhdl_proc->get_container(), stmt); if (rc != 0) return rc; // Initial processes are translated to VHDL processes with // no sensitivity list and and indefinite wait statement at // the end // However, if no statements were added to the container // by draw_stmt, don't bother adding a wait as `emit' // will optimise the process out of the output if (ivl_process_type(proc) == IVL_PR_INITIAL && !vhdl_proc->get_container()->empty()) { vhdl_wait_stmt *wait = new vhdl_wait_stmt(); vhdl_proc->get_container()->add_stmt(wait); } // Add a comment indicating where it came from ivl_scope_t scope = ivl_process_scope(proc); const char *type = ivl_process_type(proc) == IVL_PR_INITIAL ? "initial" : "always"; std::ostringstream ss; ss << "Generated from " << type << " process in "; ss << ivl_scope_tname(scope); vhdl_proc->set_comment(ss.str()); set_active_entity(NULL); return 0; } int draw_process(ivl_process_t proc, void *cd) { ivl_scope_t scope = ivl_process_scope(proc); // A process should occur in a module scope, therefore it // should have already been assigned a VHDL entity assert(ivl_scope_type(scope) == IVL_SCT_MODULE); vhdl_entity *ent = find_entity(ivl_scope_name(scope)); assert(ent != NULL); return generate_vhdl_process(ent, proc); }
Remove unused variable
Remove unused variable
C++
lgpl-2.1
CastMi/iverilog,CastMi/iverilog,CastMi/iverilog,themperek/iverilog,themperek/iverilog,themperek/iverilog
0f8e5ec41622f60a24ed5b8fa146c60d9d1fe03c
tools/siconvert.cpp
tools/siconvert.cpp
/* * Copyright (C) 2018 Tommi Maekitalo * * 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. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <cxxtools/arg.h> #include <cxxtools/argout.h> #include <cxxtools/bin/bin.h> #include <cxxtools/csv.h> #include <cxxtools/properties.h> #include <cxxtools/json.h> #include <cxxtools/log.h> #include <cxxtools/serializationinfo.h> #include <cxxtools/xml/xml.h> #include <limits> #include <iostream> struct Usage { }; class Siconvert { bool inputBin; bool inputXml; bool inputJson; bool inputCsv; bool outputBin; bool outputXml; bool outputXmlCompact; bool outputJson; bool outputCsv; bool outputProperties; bool outputCount; bool beautify; unsigned skip; unsigned num; public: Siconvert(int& argc, char* argv[]); void convert(std::istream& in, std::ostream& out); bool docontinue() const { return num > 0; } }; Siconvert::Siconvert(int& argc, char* argv[]) : inputBin(cxxtools::Arg<bool>(argc, argv, 'b')), inputXml(cxxtools::Arg<bool>(argc, argv, 'x')), inputJson(cxxtools::Arg<bool>(argc, argv, 'j')), inputCsv(cxxtools::Arg<bool>(argc, argv, 'c')), outputBin(cxxtools::Arg<bool>(argc, argv, 'B')), outputXml(cxxtools::Arg<bool>(argc, argv, 'X')), outputXmlCompact(cxxtools::Arg<bool>(argc, argv, 'Y')), outputJson(cxxtools::Arg<bool>(argc, argv, 'J')), outputCsv(cxxtools::Arg<bool>(argc, argv, 'C')), outputProperties(cxxtools::Arg<bool>(argc, argv, 'P')), outputCount(cxxtools::Arg<bool>(argc, argv, 'n')), beautify(cxxtools::Arg<bool>(argc, argv, 'd')), skip(cxxtools::Arg<unsigned>(argc, argv, "--skip")), num(cxxtools::Arg<unsigned>(argc, argv, "--num", std::numeric_limits<unsigned>::max())) { unsigned c; c = 0; if (inputBin) ++c; if (inputXml) ++c; if (inputJson) ++c; if (inputCsv) ++c; if (c != 1) { std::cerr << "one input format must be specified" << std::endl; throw Usage(); } c = 0; if (outputBin) ++c; if (outputXml) ++c; if (outputXmlCompact) ++c; if (outputJson) ++c; if (outputCsv) ++c; if (outputProperties) ++c; if (outputCount) ++c; if (c != 1) { std::cerr << "one output format must be specified" << std::endl; throw Usage(); } } void Siconvert::convert(std::istream& in, std::ostream& out) { cxxtools::SerializationInfo si; if (inputBin) in >> cxxtools::bin::Bin(si); else if (inputXml) in >> cxxtools::xml::Xml(si); else if (inputJson) in >> cxxtools::Json(si); else if (inputCsv) in >> cxxtools::Csv(si); if (skip == 0) { if (outputCount) out << si.memberCount() << std::endl; else if (outputBin) out << cxxtools::bin::Bin(si); else if (outputXml) out << cxxtools::xml::Xml(si, "root").beautify(beautify); else if (outputXmlCompact) out << cxxtools::xml::Xml(si, "root").beautify(beautify).useAttributes(false); else if (outputJson) out << cxxtools::Json(si).beautify(beautify); else if (outputCsv) out << cxxtools::Csv(si); else if (outputProperties) out << cxxtools::Properties(si); if (num > 0 && num != std::numeric_limits<unsigned>::max()) --num; } else { --skip; } } int main(int argc, char* argv[]) { try { log_init(); cxxtools::ArgOut out(argc, argv, 'o'); cxxtools::Arg<bool> verbose(argc, argv, 'v'); Siconvert app(argc, argv); if (argc > 1) { for (int a = 1; a < argc; ++a) { if (verbose) std::cerr << "process " << a << " <" << argv[a] << '>' << std::endl; std::ifstream in(argv[a]); do { app.convert(in, out); } while (app.docontinue() && in.peek() != std::char_traits<char>::eof()); } } else { do { app.convert(std::cin, out); } while (app.docontinue() && std::cin.peek() != std::char_traits<char>::eof()); } } catch (Usage) { std::cerr << "Usage: " << argv[0] << " {options} [inputfiles...]\n\n" "Description:\n" " Converts data using cxxtools serialization from one format to another.\n" " When no inputfile is given, data is read from stdin.\n\n" "Options for input format:\n" " -b read binary data\n" " -x read xml data\n" " -j read json data\n" " -c read csv data\n" "\n" "Options for output format:\n" " -B output binary data\n" " -X output xml data\n" " -Y output xml data without attributes\n" " -J output json data\n" " -C output csv data\n" " -P output properties data\n" " -n output just number of nodes on first level\n" " -d beautify output (xml, json)\n" "\n" "Other options:\n" " --skip <n> skip <n> objects\n" " --num <n> read <n> objects (default unlimited)\n" " -v verbose - output filename to stderr when processing\n" " -o <file> output to file\n"; } catch (const std::exception& e) { std::cerr << e.what() << std::endl; } }
/* * Copyright (C) 2018 Tommi Maekitalo * * 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. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <cxxtools/arg.h> #include <cxxtools/argout.h> #include <cxxtools/bin/bin.h> #include <cxxtools/csv.h> #include <cxxtools/properties.h> #include <cxxtools/json.h> #include <cxxtools/log.h> #include <cxxtools/serializationinfo.h> #include <cxxtools/xml/xml.h> #include <limits> #include <iostream> struct Usage { }; class Siconvert { bool inputBin; bool inputXml; bool inputJson; bool inputCsv; bool outputBin; bool outputXml; bool outputXmlCompact; bool outputJson; bool outputCsv; bool outputProperties; bool outputCount; bool beautify; unsigned skip; unsigned num; unsigned count; public: Siconvert(int& argc, char* argv[]); void convert(std::istream& in, std::ostream& out); bool docontinue() const { return num > 0; } void finish() const; }; Siconvert::Siconvert(int& argc, char* argv[]) : inputBin(cxxtools::Arg<bool>(argc, argv, 'b')), inputXml(cxxtools::Arg<bool>(argc, argv, 'x')), inputJson(cxxtools::Arg<bool>(argc, argv, 'j')), inputCsv(cxxtools::Arg<bool>(argc, argv, 'c')), outputBin(cxxtools::Arg<bool>(argc, argv, 'B')), outputXml(cxxtools::Arg<bool>(argc, argv, 'X')), outputXmlCompact(cxxtools::Arg<bool>(argc, argv, 'Y')), outputJson(cxxtools::Arg<bool>(argc, argv, 'J')), outputCsv(cxxtools::Arg<bool>(argc, argv, 'C')), outputProperties(cxxtools::Arg<bool>(argc, argv, 'P')), outputCount(cxxtools::Arg<bool>(argc, argv, 'N')), beautify(cxxtools::Arg<bool>(argc, argv, 'd')), skip(cxxtools::Arg<unsigned>(argc, argv, "--skip")), num(cxxtools::Arg<unsigned>(argc, argv, "--num", std::numeric_limits<unsigned>::max())), count(0) { unsigned c; c = 0; if (inputBin) ++c; if (inputXml) ++c; if (inputJson) ++c; if (inputCsv) ++c; if (c != 1) { std::cerr << "one input format must be specified" << std::endl; throw Usage(); } c = 0; if (outputBin) ++c; if (outputXml) ++c; if (outputXmlCompact) ++c; if (outputJson) ++c; if (outputCsv) ++c; if (outputProperties) ++c; if (outputCount) ++c; if (c != 1) { std::cerr << "one output format must be specified" << std::endl; throw Usage(); } } void Siconvert::convert(std::istream& in, std::ostream& out) { cxxtools::SerializationInfo si; if (inputBin) in >> cxxtools::bin::Bin(si); else if (inputXml) in >> cxxtools::xml::Xml(si); else if (inputJson) in >> cxxtools::Json(si); else if (inputCsv) in >> cxxtools::Csv(si); if (skip == 0) { if (outputBin) out << cxxtools::bin::Bin(si); else if (outputXml) out << cxxtools::xml::Xml(si, "root").beautify(beautify); else if (outputXmlCompact) out << cxxtools::xml::Xml(si, "root").beautify(beautify).useAttributes(false); else if (outputJson) out << cxxtools::Json(si).beautify(beautify); else if (outputCsv) out << cxxtools::Csv(si); else if (outputProperties) out << cxxtools::Properties(si); if (num > 0 && num != std::numeric_limits<unsigned>::max()) --num; ++count; } else { --skip; } } void Siconvert::finish() const { if (outputCount) std::cout << count << std::endl; } int main(int argc, char* argv[]) { try { log_init(); cxxtools::ArgOut out(argc, argv, 'o'); cxxtools::Arg<bool> verbose(argc, argv, 'v'); Siconvert app(argc, argv); if (argc > 1) { for (int a = 1; a < argc; ++a) { if (verbose) std::cerr << "process " << a << " <" << argv[a] << '>' << std::endl; std::ifstream in(argv[a]); do { app.convert(in, out); } while (app.docontinue() && in.peek() != std::char_traits<char>::eof()); } } else { do { app.convert(std::cin, out); } while (app.docontinue() && std::cin.peek() != std::char_traits<char>::eof()); } app.finish(); } catch (Usage) { std::cerr << "Usage: " << argv[0] << " {options} [inputfiles...]\n\n" "Description:\n" " Converts data using cxxtools serialization from one format to another.\n" " When no inputfile is given, data is read from stdin.\n\n" "Options for input format:\n" " -b read binary data\n" " -x read xml data\n" " -j read json data\n" " -c read csv data\n" "\n" "Options for output format:\n" " -B output binary data\n" " -X output xml data\n" " -Y output xml data without attributes\n" " -J output json data\n" " -C output csv data\n" " -P output properties data\n" " -N output number of objects\n" " -d beautify output (xml, json)\n" "\n" "Other options:\n" " --skip <n> skip <n> objects\n" " --num <n> read <n> objects (default unlimited)\n" " -v verbose - output filename to stderr when processing\n" " -o <file> output to file\n"; } catch (const std::exception& e) { std::cerr << e.what() << std::endl; } }
change siconvert tool: -N outputs number of records; -n option removed.
change siconvert tool: -N outputs number of records; -n option removed. -n printed the number of nodes in the first level.
C++
lgpl-2.1
maekitalo/cxxtools,maekitalo/cxxtools,maekitalo/cxxtools,maekitalo/cxxtools
8e3ded5f05a37d29e933f7dc0bd63fb2d9980f9d
strings/basic.string/string.nonmembers/string.io/get_line_delim.pass.cpp
strings/basic.string/string.nonmembers/string.io/get_line_delim.pass.cpp
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <string> // template<class charT, class traits, class Allocator> // basic_istream<charT,traits>& // getline(basic_istream<charT,traits>& is, // basic_string<charT,traits,Allocator>& str, charT delim); #include <string> #include <sstream> #include <cassert> int main() { { std::istringstream in(" abc* def* ghij"); std::string s("initial text"); getline(in, s, '*'); assert(in.good()); assert(s == " abc"); getline(in, s, '*'); assert(in.good()); assert(s == " def"); getline(in, s, '*'); assert(in.eof()); assert(s == " ghij"); } { std::wistringstream in(L" abc* def* ghij"); std::wstring s(L"initial text"); getline(in, s, L'*'); assert(in.good()); assert(s == L" abc"); getline(in, s, L'*'); assert(in.good()); assert(s == L" def"); getline(in, s, L'*'); assert(in.eof()); assert(s == L" ghij"); } }
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <string> // template<class charT, class traits, class Allocator> // basic_istream<charT,traits>& // getline(basic_istream<charT,traits>& is, // basic_string<charT,traits,Allocator>& str, charT delim); #include <string> #include <sstream> #include <cassert> int main() { { std::istringstream in(" abc* def** ghij"); std::string s("initial text"); getline(in, s, '*'); assert(in.good()); assert(s == " abc"); getline(in, s, '*'); assert(in.good()); assert(s == " def"); getline(in, s, '*'); assert(in.good()); assert(s == ""); getline(in, s, '*'); assert(in.eof()); assert(s == " ghij"); } { std::wistringstream in(L" abc* def** ghij"); std::wstring s(L"initial text"); getline(in, s, L'*'); assert(in.good()); assert(s == L" abc"); getline(in, s, L'*'); assert(in.good()); assert(s == L" def"); getline(in, s, L'*'); assert(in.good()); assert(s == L""); getline(in, s, L'*'); assert(in.eof()); assert(s == L" ghij"); } }
Fix <rdar://problem/10256836> getline of an empty string mistakenly causes failure
Fix <rdar://problem/10256836> getline of an empty string mistakenly causes failure git-svn-id: 273b07cebdae5845b4a75aae04570b978db9eb50@141506 91177308-0d34-0410-b5e6-96231b3b80d8
C++
bsd-3-clause
lodyagin/bare_cxx,lodyagin/bare_cxx,lodyagin/bare_cxx,lodyagin/bare_cxx,lodyagin/bare_cxx
4c01652457e19b39693c861e94c82d106a1957c7
tensorflow/compiler/tf2tensorrt/utils/trt_shape_optimization_profiles.cc
tensorflow/compiler/tf2tensorrt/utils/trt_shape_optimization_profiles.cc
/* Copyright 2020 The TensorFlow 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 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 "tensorflow/compiler/tf2tensorrt/utils/trt_shape_optimization_profiles.h" #include <algorithm> #include <functional> #include "tensorflow/compiler/tf2tensorrt/convert/utils.h" #if GOOGLE_CUDA && GOOGLE_TENSORRT namespace tensorflow { namespace tensorrt { // Creates optimization profiles for a list of input shapes. The list of input // shapes are stored in shapes_. void TrtShapeOptimizationProfile::InitProfiles() { if (input_shapes_.size() == 0) { VLOG(1) << "Not creating profiles without input_shapes. " "You have to enable profile generation mode first (build)."; } else { VLOG(1) << "Creating profiles with startegy of one profile " << "for each input (min=opt=max)."; } for (auto& shape_vec : input_shapes_) { std::vector<nvinfer1::Dims> dimvec; for (auto& shape : shape_vec) { dimvec.push_back(TensorShapeToTrtDims(shape, false)); } // We set min=opt=max. OptimizationProfileConfig profConfig{dimvec, dimvec, dimvec}; profiles_.push_back(std::move(profConfig)); VLOG(1) << "Created profile " << profiles_.back().DebugString(); } } #if IS_TRT_VERSION_GE(6, 0, 0, 0) Status TrtShapeOptimizationProfile::AddProfiles( nvinfer1::IBuilder* builder, nvinfer1::IBuilderConfig* config, const nvinfer1::INetworkDefinition* network) { // Create a vector of optimization profiles for (int i = 0; i < profiles_.size(); i++) { auto* optProfile = builder->createOptimizationProfile(); Status status = profiles_[i].SetDimensions(network, optProfile); if (!status.ok()) { return status; } int idx = -1; if (optProfile->isValid()) { idx = config->addOptimizationProfile(optProfile); } if (idx >= 0) { if (i != idx) { return errors::Internal( "Profile index of engine config is different from resource profile " "index: ", i, " != ", idx); } VLOG(1) << "Added optimization profile " << profiles_[i].DebugString() << " to builder config."; } else { LOG(ERROR) << "Failed to add optimization profile " << profiles_[i].DebugString() << ". This usually happens when profile is invalid."; } } if (config->getNbOptimizationProfiles() == 0) { return errors::Internal("Failure in adding an optimization profile."); } // if TRT_VERSION < 6, then we do not need to add return Status::OK(); } #endif #if IS_TRT_VERSION_GE(6, 0, 0, 0) Status TrtShapeOptimizationProfile::ConfigureBuilder( nvinfer1::IBuilder* builder, nvinfer1::IBuilderConfig* config, const nvinfer1::INetworkDefinition* network) { TF_RETURN_IF_ERROR(AddProfiles(builder, config, network)); return Status::OK(); } #endif int TrtShapeOptimizationProfile::GetProfileNumber( std::vector<TensorShape> shapes) { for (int i = 0; i < profiles_.size(); i++) { if (profiles_[i].IncludesShapes(shapes)) { return i; } } VLOG(1) << "Profile not found for input shapes " << DebugString(shapes) << "."; return -1; } Status TrtShapeOptimizationProfile::CreateExecutionContexts( nvinfer1::ICudaEngine* engine, std::vector<TrtUniquePtrType<nvinfer1::IExecutionContext>>& exec_context) { int i = 0; // The following loop runs once if we have static shapes, to create a single // execution context without profiles. In dynamic mode we create one context // for each profile and set the corresponding optimization profile. do { VLOG(1) << "Creating execution context " << i; nvinfer1::IExecutionContext* ctx = engine->createExecutionContext(); if (ctx == nullptr) { return errors::Internal("Failed to create execution context"); } if (i > 0) { // This condition is needed for two reasons: // - using static shapes we do not have any profiles so we cannot call // set optimizationprofiles. // - The 0th profile is set implicitly for the first execution context // therefore we do not need to set. #if IS_TRT_VERSION_GE(6, 0, 0, 0) bool stat = ctx->setOptimizationProfile(i); if (!stat) { ctx->destroy(); return errors::Internal("Could not set TRT optimization profile."); } #endif } exec_context.push_back(TrtUniquePtrType<nvinfer1::IExecutionContext>(ctx)); i++; } while (i < profiles_.size()); return Status::OK(); } Status TrtShapeOptimizationProfile::RestoreProfiles( const nvinfer1::ICudaEngine* engine) { #if IS_TRT_VERSION_GE(6, 0, 0, 0) if (!engine) { // We do not need to restore profiles for an empty engine return Status::OK(); } #if IS_TRT_VERSION_GE(7, 0, 0, 0) if (engine->hasImplicitBatchDimension()) { // Nothing to do, we cannot have profiles in implicit batch mode return Status::OK(); } #endif int n_profiles = engine->getNbOptimizationProfiles(); int n_inputs = GetNumberOfEngineInputs(engine); VLOG(2) << "Attempting to restore " << n_profiles << " profiles, each with " << n_inputs << " inputs"; for (int prof_idx = 0; prof_idx < n_profiles; prof_idx++) { OptimizationProfileConfig cfg; for (int j = 0; j < n_inputs; j++) { nvinfer1::Dims min = engine->getProfileDimensions( j, prof_idx, nvinfer1::OptProfileSelector::kMIN); nvinfer1::Dims max = engine->getProfileDimensions( j, prof_idx, nvinfer1::OptProfileSelector::kMAX); nvinfer1::Dims opt = engine->getProfileDimensions( j, prof_idx, nvinfer1::OptProfileSelector::kOPT); cfg.min.push_back(min); cfg.max.push_back(max); cfg.opt.push_back(opt); } VLOG(2) << "Restored profile " << cfg.DebugString(); profiles_.push_back(std::move(cfg)); } #endif return Status::OK(); } int TrtShapeOptimizationProfile::GetNumProfiles() const { return profiles_.size(); } } // namespace tensorrt } // namespace tensorflow #endif // GOOGLE_CUDA && GOOGLE_TENSORRT
/* Copyright 2020 The TensorFlow 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 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 "tensorflow/compiler/tf2tensorrt/utils/trt_shape_optimization_profiles.h" #include <algorithm> #include <functional> #include "tensorflow/compiler/tf2tensorrt/convert/utils.h" #if GOOGLE_CUDA && GOOGLE_TENSORRT namespace tensorflow { namespace tensorrt { // Creates optimization profiles for a list of input shapes. The list of input // shapes are stored in shapes_. void TrtShapeOptimizationProfile::InitProfiles() { if (input_shapes_.size() == 0) { VLOG(1) << "Not creating profiles without input_shapes. " "You have to enable profile generation mode first (build)."; } else { VLOG(1) << "Creating profiles with startegy of one profile " << "for each input (min=opt=max)."; } for (auto& shape_vec : input_shapes_) { std::vector<nvinfer1::Dims> dimvec; for (auto& shape : shape_vec) { dimvec.push_back(TensorShapeToTrtDims(shape, false)); } // We set min=opt=max. OptimizationProfileConfig profConfig{dimvec, dimvec, dimvec}; profiles_.push_back(std::move(profConfig)); VLOG(1) << "Created profile " << profiles_.back().DebugString(); } } #if IS_TRT_VERSION_GE(6, 0, 0, 0) Status TrtShapeOptimizationProfile::AddProfiles( nvinfer1::IBuilder* builder, nvinfer1::IBuilderConfig* config, const nvinfer1::INetworkDefinition* network) { // Create a vector of optimization profiles for (int i = 0; i < profiles_.size(); i++) { auto* optProfile = builder->createOptimizationProfile(); Status status = profiles_[i].SetDimensions(network, optProfile); if (!status.ok()) { return status; } int idx = -1; if (optProfile->isValid()) { idx = config->addOptimizationProfile(optProfile); } if (idx >= 0) { if (i != idx) { return errors::Internal( "Profile index of engine config is different from resource profile " "index: ", i, " != ", idx); } VLOG(1) << "Added optimization profile " << profiles_[i].DebugString() << " to builder config."; } else { LOG(ERROR) << "Failed to add optimization profile " << profiles_[i].DebugString() << ". This usually happens when profile is invalid."; } } if (!profiles_.empty() && config->getNbOptimizationProfiles() == 0) { return errors::Internal("Failure in adding an optimization profile."); } // if TRT_VERSION < 6, then we do not need to add return Status::OK(); } #endif #if IS_TRT_VERSION_GE(6, 0, 0, 0) Status TrtShapeOptimizationProfile::ConfigureBuilder( nvinfer1::IBuilder* builder, nvinfer1::IBuilderConfig* config, const nvinfer1::INetworkDefinition* network) { TF_RETURN_IF_ERROR(AddProfiles(builder, config, network)); return Status::OK(); } #endif int TrtShapeOptimizationProfile::GetProfileNumber( std::vector<TensorShape> shapes) { for (int i = 0; i < profiles_.size(); i++) { if (profiles_[i].IncludesShapes(shapes)) { return i; } } VLOG(1) << "Profile not found for input shapes " << DebugString(shapes) << "."; return -1; } Status TrtShapeOptimizationProfile::CreateExecutionContexts( nvinfer1::ICudaEngine* engine, std::vector<TrtUniquePtrType<nvinfer1::IExecutionContext>>& exec_context) { int i = 0; // The following loop runs once if we have static shapes, to create a single // execution context without profiles. In dynamic mode we create one context // for each profile and set the corresponding optimization profile. do { VLOG(1) << "Creating execution context " << i; nvinfer1::IExecutionContext* ctx = engine->createExecutionContext(); if (ctx == nullptr) { return errors::Internal("Failed to create execution context"); } if (i > 0) { // This condition is needed for two reasons: // - using static shapes we do not have any profiles so we cannot call // set optimizationprofiles. // - The 0th profile is set implicitly for the first execution context // therefore we do not need to set. #if IS_TRT_VERSION_GE(6, 0, 0, 0) bool stat = ctx->setOptimizationProfile(i); if (!stat) { ctx->destroy(); return errors::Internal("Could not set TRT optimization profile."); } #endif } exec_context.push_back(TrtUniquePtrType<nvinfer1::IExecutionContext>(ctx)); i++; } while (i < profiles_.size()); return Status::OK(); } Status TrtShapeOptimizationProfile::RestoreProfiles( const nvinfer1::ICudaEngine* engine) { #if IS_TRT_VERSION_GE(6, 0, 0, 0) if (!engine) { // We do not need to restore profiles for an empty engine return Status::OK(); } #if IS_TRT_VERSION_GE(7, 0, 0, 0) if (engine->hasImplicitBatchDimension()) { // Nothing to do, we cannot have profiles in implicit batch mode return Status::OK(); } #endif int n_profiles = engine->getNbOptimizationProfiles(); int n_inputs = GetNumberOfEngineInputs(engine); VLOG(2) << "Attempting to restore " << n_profiles << " profiles, each with " << n_inputs << " inputs"; for (int prof_idx = 0; prof_idx < n_profiles; prof_idx++) { OptimizationProfileConfig cfg; for (int j = 0; j < n_inputs; j++) { nvinfer1::Dims min = engine->getProfileDimensions( j, prof_idx, nvinfer1::OptProfileSelector::kMIN); nvinfer1::Dims max = engine->getProfileDimensions( j, prof_idx, nvinfer1::OptProfileSelector::kMAX); nvinfer1::Dims opt = engine->getProfileDimensions( j, prof_idx, nvinfer1::OptProfileSelector::kOPT); cfg.min.push_back(min); cfg.max.push_back(max); cfg.opt.push_back(opt); } VLOG(2) << "Restored profile " << cfg.DebugString(); profiles_.push_back(std::move(cfg)); } #endif return Status::OK(); } int TrtShapeOptimizationProfile::GetNumProfiles() const { return profiles_.size(); } } // namespace tensorrt } // namespace tensorflow #endif // GOOGLE_CUDA && GOOGLE_TENSORRT
Fix error check: zero actual profiles are only error if wanted to create at least one
Fix error check: zero actual profiles are only error if wanted to create at least one
C++
apache-2.0
xzturn/tensorflow,renyi533/tensorflow,tensorflow/tensorflow,gunan/tensorflow,xzturn/tensorflow,freedomtan/tensorflow,Intel-tensorflow/tensorflow,petewarden/tensorflow,paolodedios/tensorflow,davidzchen/tensorflow,aldian/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-tensorflow/tensorflow,freedomtan/tensorflow,davidzchen/tensorflow,sarvex/tensorflow,freedomtan/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,gunan/tensorflow,aam-at/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,aldian/tensorflow,renyi533/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow,xzturn/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-Corporation/tensorflow,renyi533/tensorflow,tensorflow/tensorflow-pywrap_saved_model,paolodedios/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,karllessard/tensorflow,yongtang/tensorflow,Intel-tensorflow/tensorflow,annarev/tensorflow,renyi533/tensorflow,petewarden/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow-pywrap_saved_model,sarvex/tensorflow,cxxgtxy/tensorflow,Intel-Corporation/tensorflow,frreiss/tensorflow-fred,aldian/tensorflow,aam-at/tensorflow,frreiss/tensorflow-fred,davidzchen/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,frreiss/tensorflow-fred,gautam1858/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,frreiss/tensorflow-fred,yongtang/tensorflow,aam-at/tensorflow,renyi533/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,petewarden/tensorflow,cxxgtxy/tensorflow,frreiss/tensorflow-fred,yongtang/tensorflow,davidzchen/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Intel-tensorflow/tensorflow,gunan/tensorflow,tensorflow/tensorflow,karllessard/tensorflow,yongtang/tensorflow,cxxgtxy/tensorflow,Intel-Corporation/tensorflow,gautam1858/tensorflow,cxxgtxy/tensorflow,frreiss/tensorflow-fred,sarvex/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,gautam1858/tensorflow,karllessard/tensorflow,annarev/tensorflow,sarvex/tensorflow,davidzchen/tensorflow,gunan/tensorflow,paolodedios/tensorflow,davidzchen/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_saved_model,petewarden/tensorflow,tensorflow/tensorflow-pywrap_saved_model,gunan/tensorflow,aldian/tensorflow,davidzchen/tensorflow,Intel-Corporation/tensorflow,gunan/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,renyi533/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,cxxgtxy/tensorflow,tensorflow/tensorflow,karllessard/tensorflow,sarvex/tensorflow,yongtang/tensorflow,xzturn/tensorflow,frreiss/tensorflow-fred,yongtang/tensorflow,davidzchen/tensorflow,renyi533/tensorflow,gunan/tensorflow,annarev/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,annarev/tensorflow,tensorflow/tensorflow,frreiss/tensorflow-fred,petewarden/tensorflow,karllessard/tensorflow,Intel-tensorflow/tensorflow,annarev/tensorflow,Intel-tensorflow/tensorflow,aam-at/tensorflow,tensorflow/tensorflow,aam-at/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,xzturn/tensorflow,tensorflow/tensorflow,yongtang/tensorflow,davidzchen/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_saved_model,yongtang/tensorflow,paolodedios/tensorflow,freedomtan/tensorflow,yongtang/tensorflow,freedomtan/tensorflow,gunan/tensorflow,freedomtan/tensorflow,petewarden/tensorflow,annarev/tensorflow,gautam1858/tensorflow,annarev/tensorflow,paolodedios/tensorflow,frreiss/tensorflow-fred,aldian/tensorflow,tensorflow/tensorflow-pywrap_saved_model,aam-at/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-pywrap_saved_model,Intel-Corporation/tensorflow,tensorflow/tensorflow,paolodedios/tensorflow,Intel-Corporation/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,frreiss/tensorflow-fred,paolodedios/tensorflow,petewarden/tensorflow,annarev/tensorflow,cxxgtxy/tensorflow,petewarden/tensorflow,aldian/tensorflow,xzturn/tensorflow,gunan/tensorflow,paolodedios/tensorflow,annarev/tensorflow,renyi533/tensorflow,aam-at/tensorflow,aam-at/tensorflow,karllessard/tensorflow,freedomtan/tensorflow,karllessard/tensorflow,karllessard/tensorflow,yongtang/tensorflow,cxxgtxy/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-tensorflow/tensorflow,davidzchen/tensorflow,xzturn/tensorflow,renyi533/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,xzturn/tensorflow,davidzchen/tensorflow,Intel-tensorflow/tensorflow,petewarden/tensorflow,gautam1858/tensorflow,aldian/tensorflow,gautam1858/tensorflow,gunan/tensorflow,tensorflow/tensorflow,freedomtan/tensorflow,xzturn/tensorflow,gautam1858/tensorflow,xzturn/tensorflow,frreiss/tensorflow-fred,annarev/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,annarev/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,gunan/tensorflow,petewarden/tensorflow,freedomtan/tensorflow,aam-at/tensorflow,aldian/tensorflow,xzturn/tensorflow,petewarden/tensorflow,Intel-Corporation/tensorflow,freedomtan/tensorflow,sarvex/tensorflow,tensorflow/tensorflow,xzturn/tensorflow,gautam1858/tensorflow,paolodedios/tensorflow,sarvex/tensorflow,petewarden/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Intel-tensorflow/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-experimental_link_static_libraries_once,cxxgtxy/tensorflow,renyi533/tensorflow,aam-at/tensorflow,aam-at/tensorflow,renyi533/tensorflow,aam-at/tensorflow,gautam1858/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow,renyi533/tensorflow,tensorflow/tensorflow-pywrap_saved_model,davidzchen/tensorflow,sarvex/tensorflow,karllessard/tensorflow,gunan/tensorflow,freedomtan/tensorflow
142c5af4f69f193e161ee99edee9ea15007e6787
util/xpath/main.cpp
util/xpath/main.cpp
#include <algorithm> #include <iostream> #include <map> #include <set> #include <stdexcept> #include <string> #include <boost/unordered_set.hpp> #include <boost/scoped_ptr.hpp> #include <boost/shared_ptr.hpp> #include <boost/filesystem.hpp> #include <AlpinoCorpus/CorpusInfo.hh> #include <AlpinoCorpus/CorpusReader.hh> #include <AlpinoCorpus/Entry.hh> #include <AlpinoCorpus/Error.hh> #include <AlpinoCorpus/MultiCorpusReader.hh> #include <AlpinoCorpus/util/Either.hh> #include <config.hh> #include <AlpinoCorpus/LexItem.hh> #include <AlpinoCorpus/macros.hh> #include <EqualsPrevious.hh> #include <ProgramOptions.hh> #include <util.hh> using alpinocorpus::CorpusInfo; using alpinocorpus::CorpusReader; using alpinocorpus::Either; using alpinocorpus::Entry; using alpinocorpus::LexItem; namespace bf = boost::filesystem; template<typename T> std::set<T> unique_to_first(std::set<T> const &a, std::set<T> const &b) { std::set<T> result; std::set_difference(a.begin(), a.end(), b.begin(), b.end(), std::inserter(result, result.begin())); return result; } void output_depth_color(size_t depth) { if (depth == 0) std::cout << "\033[0;22m"; else if (depth == 1) std::cout << "\033[38;5;99m"; else if (depth == 2) std::cout << "\033[38;5;111m"; else if (depth == 3) std::cout << "\033[38;5;123m"; else if (depth == 4) std::cout << "\033[38;5;121m"; else std::cout << "\033[38;5;119m"; } void listCorpus(boost::shared_ptr<CorpusReader> reader, std::string const &query, bool bracketed, bool colorBrackets, std::string const &attribute, CorpusInfo const &corpusInfo) { CorpusReader::EntryIterator i; if (query.empty()) i = reader->entries(); else i = reader->query(CorpusReader::XPATH, query); NotEqualsPrevious<std::string> pred; boost::unordered_set<std::string> seen; while (i.hasNext()) { Entry entry = i.next(*reader); if (seen.find(entry.name) == seen.end()) { std::cout << entry.name; if (bracketed) { std::cout << " "; std::vector<LexItem> items = reader->sentence(entry.name, query, attribute, "_missing_", corpusInfo); std::set<size_t> prevMatches = std::set<size_t>(); for (std::vector<LexItem>::const_iterator itemIter = items.begin(); itemIter != items.end(); ++itemIter) { size_t depth = itemIter->matches.size(); // Find the set of matches starting before the current word. std::set<size_t> startAtCurrent = unique_to_first(itemIter->matches, prevMatches); if (colorBrackets) { if (startAtCurrent.size() != 0) { output_depth_color(itemIter->matches.size()); } } else { for (std::set<size_t>::const_iterator iter = startAtCurrent.begin(); iter != startAtCurrent.end(); ++iter) { std::cout << "[ "; } } std::cout << itemIter->word; // Find the set of matches ending after the current word. std::vector<LexItem>::const_iterator next = itemIter + 1; std::set<size_t> endAtCurrent = itemIter->matches; if (next != items.end()) { endAtCurrent = unique_to_first(itemIter->matches, next->matches); } if (colorBrackets) { if (next != items.end() && endAtCurrent.size() != 0) { std::cout << "\033[0;22m"; } } else { for (std::set<size_t>::const_iterator iter = endAtCurrent.begin(); iter != endAtCurrent.end(); ++iter) std::cout << " ]"; } std::cout << " "; prevMatches = itemIter->matches; } } std::cout << std::endl; seen.insert(entry.name); } } } void readEntry(boost::shared_ptr<CorpusReader> reader, std::string const &entry) { std::cout << reader->read(entry); } void usage(std::string const &programName) { std::cerr << "Usage: " << programName << " [OPTION] treebank(s)" << std::endl << std::endl << " -a attr\tLexical attribute to show (default: word)" << std::endl << " -c\t\tUse colored bracketing" << std::endl << " -m filename\tLoad macro file" << std::endl << " -q query\tFilter the treebank using the given query" << std::endl << " -s\t\tInclude a bracketed sentence" << std::endl << std::endl; } int main(int argc, char *argv[]) { boost::scoped_ptr<ProgramOptions> opts; try { opts.reset(new ProgramOptions(argc, const_cast<char const **>(argv), "a:cm:q:s")); } catch (std::exception &e) { std::cerr << e.what() << std::endl; return 1; } if (opts->arguments().size() == 0) { usage(opts->programName()); return 1; } boost::shared_ptr<CorpusReader> reader; try { reader = boost::shared_ptr<CorpusReader>( openCorpora(opts->arguments().begin(), opts->arguments().end(), true)); } catch (std::runtime_error &e) { std::cerr << "Could not open corpus: " << e.what() << std::endl; return 1; } CorpusInfo corpusInfo = alpinocorpus::predefinedCorpusOrFallback(reader->type()); std::string attr = corpusInfo.tokenAttribute(); if (opts->option('a')) { attr = opts->optionValue('a'); } alpinocorpus::Macros macros; if (opts->option('m')) { std::string macrosFn = opts->optionValue('m'); try { macros = alpinocorpus::loadMacros(macrosFn); } catch (std::runtime_error &e) { std::cerr << e.what() << std::endl; return 1; } } std::string query; if (opts->option('q')) { query = alpinocorpus::expandMacros(macros, opts->optionValue('q')); Either<std::string, alpinocorpus::Empty> valid = reader->isValidQuery(CorpusReader::XPATH, false, query); if (valid.isLeft()) { std::cerr << "Invalid (or unwanted) query: " << query << std::endl << std::endl; std::cerr << valid.left() << std::endl; return 1; } } try { listCorpus(reader, query, opts->option('s'), opts->option('c'), attr, corpusInfo); } catch (std::runtime_error const &e) { std::cerr << opts->programName() << ": error listing treebank: " << e.what() << std::endl; return 1; } return 0; }
#include <algorithm> #include <iostream> #include <map> #include <set> #include <stdexcept> #include <string> #include <boost/unordered_set.hpp> #include <boost/scoped_ptr.hpp> #include <boost/shared_ptr.hpp> #include <boost/filesystem.hpp> #include <AlpinoCorpus/CorpusInfo.hh> #include <AlpinoCorpus/CorpusReader.hh> #include <AlpinoCorpus/Entry.hh> #include <AlpinoCorpus/Error.hh> #include <AlpinoCorpus/MultiCorpusReader.hh> #include <AlpinoCorpus/util/Either.hh> #include <config.hh> #include <AlpinoCorpus/LexItem.hh> #include <AlpinoCorpus/macros.hh> #include <EqualsPrevious.hh> #include <ProgramOptions.hh> #include <util.hh> using alpinocorpus::CorpusInfo; using alpinocorpus::CorpusReader; using alpinocorpus::Either; using alpinocorpus::Entry; using alpinocorpus::LexItem; namespace bf = boost::filesystem; template<typename T> std::set<T> unique_to_first(std::set<T> const &a, std::set<T> const &b) { std::set<T> result; std::set_difference(a.begin(), a.end(), b.begin(), b.end(), std::inserter(result, result.begin())); return result; } void output_depth_color(size_t depth) { if (depth == 0) std::cout << "\033[0;22m"; else if (depth == 1) std::cout << "\033[38;5;99m"; else if (depth == 2) std::cout << "\033[38;5;111m"; else if (depth == 3) std::cout << "\033[38;5;123m"; else if (depth == 4) std::cout << "\033[38;5;121m"; else std::cout << "\033[38;5;119m"; } void listCorpus(boost::shared_ptr<CorpusReader> reader, std::string const &query, bool bracketed, bool colorBrackets, std::string const &attribute, CorpusInfo const &corpusInfo) { CorpusReader::EntryIterator i; if (query.empty()) i = reader->entries(); else i = reader->query(CorpusReader::XPATH, query); NotEqualsPrevious<std::string> pred; boost::unordered_set<std::string> seen; while (i.hasNext()) { Entry entry = i.next(*reader); if (seen.find(entry.name) == seen.end()) { std::cout << entry.name; if (bracketed) { std::cout << " "; std::vector<LexItem> items = reader->sentence(entry.name, query, attribute, "_missing_", corpusInfo); std::set<size_t> prevMatches = std::set<size_t>(); for (std::vector<LexItem>::const_iterator itemIter = items.begin(); itemIter != items.end(); ++itemIter) { size_t depth = itemIter->matches.size(); // Find the set of matches starting before the current word. std::set<size_t> startAtCurrent = unique_to_first(itemIter->matches, prevMatches); if (colorBrackets) { if (startAtCurrent.size() != 0) { output_depth_color(itemIter->matches.size()); } } else { for (std::set<size_t>::const_iterator iter = startAtCurrent.begin(); iter != startAtCurrent.end(); ++iter) { std::cout << *iter << ":[ "; } } std::cout << itemIter->word; // Find the set of matches ending after the current word. std::vector<LexItem>::const_iterator next = itemIter + 1; std::set<size_t> endAtCurrent = itemIter->matches; if (next != items.end()) { endAtCurrent = unique_to_first(itemIter->matches, next->matches); } if (colorBrackets) { if (next != items.end() && endAtCurrent.size() != 0) { std::cout << "\033[0;22m"; } } else { for (std::set<size_t>::const_iterator iter = endAtCurrent.begin(); iter != endAtCurrent.end(); ++iter) std::cout << " ]"; } std::cout << " "; prevMatches = itemIter->matches; } } std::cout << std::endl; seen.insert(entry.name); } } } void readEntry(boost::shared_ptr<CorpusReader> reader, std::string const &entry) { std::cout << reader->read(entry); } void usage(std::string const &programName) { std::cerr << "Usage: " << programName << " [OPTION] treebank(s)" << std::endl << std::endl << " -a attr\tLexical attribute to show (default: word)" << std::endl << " -c\t\tUse colored bracketing" << std::endl << " -m filename\tLoad macro file" << std::endl << " -q query\tFilter the treebank using the given query" << std::endl << " -s\t\tInclude a bracketed sentence" << std::endl << std::endl; } int main(int argc, char *argv[]) { boost::scoped_ptr<ProgramOptions> opts; try { opts.reset(new ProgramOptions(argc, const_cast<char const **>(argv), "a:cm:q:s")); } catch (std::exception &e) { std::cerr << e.what() << std::endl; return 1; } if (opts->arguments().size() == 0) { usage(opts->programName()); return 1; } boost::shared_ptr<CorpusReader> reader; try { reader = boost::shared_ptr<CorpusReader>( openCorpora(opts->arguments().begin(), opts->arguments().end(), true)); } catch (std::runtime_error &e) { std::cerr << "Could not open corpus: " << e.what() << std::endl; return 1; } CorpusInfo corpusInfo = alpinocorpus::predefinedCorpusOrFallback(reader->type()); std::string attr = corpusInfo.tokenAttribute(); if (opts->option('a')) { attr = opts->optionValue('a'); } alpinocorpus::Macros macros; if (opts->option('m')) { std::string macrosFn = opts->optionValue('m'); try { macros = alpinocorpus::loadMacros(macrosFn); } catch (std::runtime_error &e) { std::cerr << e.what() << std::endl; return 1; } } std::string query; if (opts->option('q')) { query = alpinocorpus::expandMacros(macros, opts->optionValue('q')); Either<std::string, alpinocorpus::Empty> valid = reader->isValidQuery(CorpusReader::XPATH, false, query); if (valid.isLeft()) { std::cerr << "Invalid (or unwanted) query: " << query << std::endl << std::endl; std::cerr << valid.left() << std::endl; return 1; } } try { listCorpus(reader, query, opts->option('s'), opts->option('c'), attr, corpusInfo); } catch (std::runtime_error const &e) { std::cerr << opts->programName() << ": error listing treebank: " << e.what() << std::endl; return 1; } return 0; }
Add match numbers to opening brackets.
Add match numbers to opening brackets.
C++
lgpl-2.1
rug-compling/alpinocorpus,rug-compling/alpinocorpus,rug-compling/alpinocorpus
326ecde701b8031fe37f30f4c189b54bd50b6068
src/sub.cpp
src/sub.cpp
#include <string.h> #include <signal.h> #include <iostream> #include <sstream> #include <thread> #include <set> #include "msg_filter.hpp" #include "io_policy/line.hpp" #include "io_policy/sysv_mq.hpp" #include "io_policy/tcp.hpp" #include "sub_entry.hpp" #include "util.hpp" using namespace std; using namespace wissbi; bool run = true; void exit_signal_handler(int signum) { run = false; } int main(int argc, char* argv[]){ signal(SIGINT, exit_signal_handler); signal(SIGTERM, exit_signal_handler); int serv = socket(AF_INET, SOCK_STREAM, 0); sockaddr serv_addr; util::ConnectStringToSockaddr("0.0.0.0:0", reinterpret_cast<sockaddr_in*>(&serv_addr)); if(-1 == ::bind(serv, &serv_addr, sizeof(serv_addr))) { cerr << "bind error" << endl; return -1; } if(-1 == listen(serv, 10)) { cerr << "listen error" << endl; return -1; } socklen_t len = sizeof(serv_addr);; getsockname(serv, &serv_addr, &len); cerr <<"after listen port "<<ntohs(((sockaddr_in*)&serv_addr)->sin_port)<<endl; ostringstream tmp; tmp << util::GetHostIP() << ":" << ntohs(((sockaddr_in*)&serv_addr)->sin_port); SubEntry sub_entry(getenv("WISSBI_META_DIR") != NULL ? getenv("WISSBI_META_DIR") : "/var/lib/wissbi", argv[1], tmp.str()); MsgFilter<io_policy::SysvMq, io_policy::Line> output_writer; thread* output_th = new thread([&output_writer](){ output_writer.FilterLoop(); }); struct timeval tv; tv.tv_sec = 1; tv.tv_usec = 0; setsockopt(serv, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); while(run) { sockaddr other_addr; socklen_t len; int res = accept(serv, &other_addr, &len); if(res > 0){ cerr << "connected " << res << endl; struct timeval tv; tv.tv_sec = 0; tv.tv_usec = 0; setsockopt(res, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); thread([res]{ MsgFilter<io_policy::TCP, io_policy::SysvMq> filter; filter.set_cleanup(false); filter.AttachConnectedSock(res); filter.FilterLoop(); }).detach(); } sub_entry.renew(); } return 0; }
#include <string.h> #include <signal.h> #include <iostream> #include <fstream> #include <sstream> #include <thread> #include <set> #include "msg_filter.hpp" #include "io_policy/line.hpp" #include "io_policy/sysv_mq.hpp" #include "io_policy/tcp.hpp" #include "sub_entry.hpp" #include "util.hpp" using namespace std; using namespace wissbi; bool run = true; void exit_signal_handler(int signum) { run = false; } int main(int argc, char* argv[]){ signal(SIGINT, exit_signal_handler); signal(SIGTERM, exit_signal_handler); if(getenv("WISSBI_PID_FILE") != NULL) { ofstream ofs(getenv("WISSBI_PID_FILE")); ofs << getpid() << endl; } int serv = socket(AF_INET, SOCK_STREAM, 0); sockaddr serv_addr; util::ConnectStringToSockaddr("0.0.0.0:0", reinterpret_cast<sockaddr_in*>(&serv_addr)); if(-1 == ::bind(serv, &serv_addr, sizeof(serv_addr))) { cerr << "bind error" << endl; return -1; } if(-1 == listen(serv, 10)) { cerr << "listen error" << endl; return -1; } socklen_t len = sizeof(serv_addr);; getsockname(serv, &serv_addr, &len); cerr <<"after listen port "<<ntohs(((sockaddr_in*)&serv_addr)->sin_port)<<endl; ostringstream tmp; tmp << util::GetHostIP() << ":" << ntohs(((sockaddr_in*)&serv_addr)->sin_port); SubEntry sub_entry(getenv("WISSBI_META_DIR") != NULL ? getenv("WISSBI_META_DIR") : "/var/lib/wissbi", argv[1], tmp.str()); MsgFilter<io_policy::SysvMq, io_policy::Line> output_writer; thread* output_th = new thread([&output_writer](){ output_writer.FilterLoop(); }); struct timeval tv; tv.tv_sec = 1; tv.tv_usec = 0; setsockopt(serv, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); while(run) { sockaddr other_addr; socklen_t len; int res = accept(serv, &other_addr, &len); if(res > 0){ cerr << "connected " << res << endl; struct timeval tv; tv.tv_sec = 0; tv.tv_usec = 0; setsockopt(res, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); thread([res]{ MsgFilter<io_policy::TCP, io_policy::SysvMq> filter; filter.set_cleanup(false); filter.AttachConnectedSock(res); filter.FilterLoop(); }).detach(); } sub_entry.renew(); } return 0; }
add write pid file
add write pid file
C++
mit
lunastorm/wissbi,lunastorm/wissbi,lunastorm/wissbi,lunastorm/wissbi,lunastorm/wissbi
1130d90f6381f0f60e6cad7ee23646165405e386
tests/init.cpp
tests/init.cpp
#include <binary_search_tree.hpp> #include <catch.hpp> SCENARIO("default constructor") { BinarySearchTree<int> bst; REQUIRE(bst.root() == nullptr); REQUIRE(bst.count() == 0); } SCENARIO("insertElement") { BinarySearchTree<int> bst; bst.insert(7); REQUIRE(bst.value_() == 7); REQUIRE(bst.leftNode_() == nullptr); REQUIRE(bst.rightNode_() == nullptr); } SCENARIO("findElement") { BinarySearchTree<int> bst; bst.insert(7); bool a; a = bst.isFound(7); REQUIRE( a == 1); }
#include <binary_search_tree.hpp> #include <catch.hpp> SCENARIO("default constructor") { BinarySearchTree<int> bst; REQUIRE(bst.root() == nullptr); } SCENARIO("insertElement") { BinarySearchTree<int> bst; bst.insert(7); REQUIRE(bst.value_() == 7); REQUIRE(bst.leftNode_() == nullptr); REQUIRE(bst.rightNode_() == nullptr); } SCENARIO("findElement") { BinarySearchTree<int> bst; bst.insert(7); bool a; a = bst.isFound(7); REQUIRE( a == 1); }
Update init.cpp
Update init.cpp
C++
mit
yanaxgrishkova/binary_search_tree
41d05b4876a8c60c0df29e3258e24bf835f592b0
tests/init.cpp
tests/init.cpp
#include <matrix.hpp> #include <catch.hpp> SCENARIO("matrix init without parametrs", "[init wp]") { Matrix matrix; REQUIRE(matrix.rows() == 4); REQUIRE(matrix.columns() == 4); for (int i=0;i<matrix.rows(); i++) { for (int j = 0; j<matrix.columns();j++) { REQUIRE(matrix.Element(i,j) == 0); } } } SCENARIO("matrix init with parametrs", "[init withp]") { Matrix matrix(6,6); REQUIRE(matrix.rows() == 6); REQUIRE(matrix.columns() == 6); for (int i=0;i<matrix.rows(); i++) { for (int j = 0; j<matrix.columns();j++) { REQUIRE(matrix.Element(i,j) == 0); } } } SCENARIO("matrix init copy", "[init copy]") { Matrix matrix(6,6); Matrix matrix1(matrix); REQUIRE(matrix1.rows() == matrix.rows()); REQUIRE(matrix1.columns() == matrix.columns()); for (int i=0;i<matrix.rows(); i++) { for (int j = 0; j<matrix.columns();j++) { REQUIRE(matrix.Element(i,j) == matrix1.Element(i,j)); } } } SCENARIO("matrix fill", "[fill]") { Matrix matrix(2,2); ofstream test1("test1.txt"); test1 << "1 2 3 4"; test1.close(); matrix.fill("test1.txt"); REQUIRE(matrix.Element(0,0) == 1); REQUIRE(matrix.Element(0,1) == 2); REQUIRE(matrix.Element(1,0) == 3); REQUIRE(matrix.Element(1,1) == 4); } SCENARIO("matrix sum", "[sum]") { Matrix matrix(2,2); Matrix matrix1(2,2); Matrix sum(2,2); ofstream test1("test1.txt"); test1 << "1 2 3 4"; test1.close(); matrix.fill("test1.txt"); matrix1.fill("test1.txt"); //ofstream sumfile("sumfile.txt"); //sumfile << "2 4 6 8"; //sum.fill("sumfile.txt"); //sumfile.close(); REQUIRE(matrix.Element(0,0) + matrix1.Element(0,0) == 2); REQUIRE(matrix.Element(0,1) + matrix1.Element(0,1) == 4); REQUIRE(matrix.Element(1,0) + matrix1.Element(1,0) == 6); REQUIRE(matrix.Element(1,1) + matrix1.Element(1,1) == 8); } SCENARIO("matrix Proizv", "[Pro]") { Matrix matrix(2,2); Matrix matrix1(2,2); Matrix Pro(2,2); ofstream test1("test1.txt"); test1 << "1 2 3 4"; test1.close(); matrix.fill("test1.txt"); matrix1.fill("test1.txt"); //ofstream sumfile("sumfile.txt"); //sumfile << "2 4 6 8"; //sum.fill("sumfile.txt"); //sumfile.close(); REQUIRE(matrix.Element(0,0) * matrix1.Element(0,0) + matrix.Element(1,0) * matrix1.Element(0,1) == 7); REQUIRE(matrix.Element(0,0) * matrix1.Element(1,0) + matrix.Element(1,0) * matrix1.Element(1,1) == 10); REQUIRE(matrix.Element(0,1) * matrix1.Element(0,0) + matrix.Element(1,1) * matrix1.Element(0,1) == 15); REQUIRE(matrix.Element(0,1) * matrix1.Element(1,0) + matrix.Element(1,1) * matrix1.Element(1,1) == 22); }
#include <matrix.hpp> #include <catch.hpp> SCENARIO("matrix init without parametrs", "[init wp]") { Matrix matrix; REQUIRE(matrix.rows() == 4); REQUIRE(matrix.columns() == 4); for (int i=0;i<matrix.rows(); i++) { for (int j = 0; j<matrix.columns();j++) { REQUIRE(matrix.Element(i,j) == 0); } } } SCENARIO("matrix init with parametrs", "[init withp]") { Matrix matrix(2,2); REQUIRE(matrix.rows() == 2); REQUIRE(matrix.columns() == 2); for (int i=0;i<matrix.rows(); i++) { for (int j = 0; j<matrix.columns();j++) { REQUIRE(matrix.Element(i,j) == 0); } } } SCENARIO("matrix init copy", "[init copy]") { Matrix matrix(2,2); Matrix matrix1(matrix); REQUIRE(matrix1.rows() == matrix.rows()); REQUIRE(matrix1.columns() == matrix.columns()); for (int i=0;i<matrix.rows(); i++) { for (int j = 0; j<matrix.columns();j++) { REQUIRE(matrix.Element(i,j) == matrix1.Element(i,j)); } } } SCENARIO("matrix fill", "[fill]") { Matrix matrix(2,2); ofstream test1("test1.txt"); test1 << "1 2 3 4"; test1.close(); matrix.fill("test1.txt"); REQUIRE(matrix.Element(0,0) == 1); REQUIRE(matrix.Element(0,1) == 2); REQUIRE(matrix.Element(1,0) == 3); REQUIRE(matrix.Element(1,1) == 4); } SCENARIO("matrix sum", "[sum]") { Matrix matrix(2,2); Matrix matrix1(2,2); Matrix sum(2,2); ofstream test1("test1.txt"); test1 << "1 2 3 4"; test1.close(); matrix.fill("test1.txt"); matrix1.fill("test1.txt"); //ofstream sumfile("sumfile.txt"); //sumfile << "2 4 6 8"; //sum.fill("sumfile.txt"); //sumfile.close(); REQUIRE(matrix.Element(0,0) + matrix1.Element(0,0) == 2); REQUIRE(matrix.Element(0,1) + matrix1.Element(0,1) == 4); REQUIRE(matrix.Element(1,0) + matrix1.Element(1,0) == 6); REQUIRE(matrix.Element(1,1) + matrix1.Element(1,1) == 8); } SCENARIO("matrix Proizv", "[Pro]") { Matrix matrix(2,2); Matrix matrix1(2,2); Matrix Pro(2,2); ofstream test1("test1.txt"); test1 << "1 2 3 4"; test1.close(); matrix.fill("test1.txt"); matrix1.fill("test1.txt"); //ofstream sumfile("sumfile.txt"); //sumfile << "2 4 6 8"; //sum.fill("sumfile.txt"); //sumfile.close(); REQUIRE(matrix.Element(0,0) * matrix1.Element(0,0) + matrix.Element(1,0) * matrix1.Element(0,1) == 7); REQUIRE(matrix.Element(0,0) * matrix1.Element(1,0) + matrix.Element(1,0) * matrix1.Element(1,1) == 15); REQUIRE(matrix.Element(0,1) * matrix1.Element(0,0) + matrix.Element(1,1) * matrix1.Element(0,1) == 15); REQUIRE(matrix.Element(0,1) * matrix1.Element(1,0) + matrix.Element(1,1) * matrix1.Element(1,1) == 22); }
Update init.cpp
Update init.cpp
C++
mit
Bozey98/BST
e6b0fbf6516ff2731f4f55f1bbbc1e920d6f124a
extensions/browser/api/cast_channel/cast_auth_util.cc
extensions/browser/api/cast_channel/cast_auth_util.cc
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "extensions/browser/api/cast_channel/cast_auth_util.h" #include <vector> #include "base/logging.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "extensions/browser/api/cast_channel/cast_message_util.h" #include "extensions/common/api/cast_channel/cast_channel.pb.h" #include "extensions/common/cast/cast_cert_validator.h" namespace extensions { namespace core_api { namespace cast_channel { namespace { const char* const kParseErrorPrefix = "Failed to parse auth message: "; const unsigned char kAudioOnlyPolicy[] = {0x06, 0x0A, 0x2B, 0x06, 0x01, 0x04, 0x01, 0xD6, 0x79, 0x02, 0x05, 0x02}; namespace cast_crypto = ::extensions::core_api::cast_crypto; // Extracts an embedded DeviceAuthMessage payload from an auth challenge reply // message. AuthResult ParseAuthMessage(const CastMessage& challenge_reply, DeviceAuthMessage* auth_message) { if (challenge_reply.payload_type() != CastMessage_PayloadType_BINARY) { return AuthResult::CreateWithParseError( "Wrong payload type in challenge reply", AuthResult::ERROR_WRONG_PAYLOAD_TYPE); } if (!challenge_reply.has_payload_binary()) { return AuthResult::CreateWithParseError( "Payload type is binary but payload_binary field not set", AuthResult::ERROR_NO_PAYLOAD); } if (!auth_message->ParseFromString(challenge_reply.payload_binary())) { return AuthResult::CreateWithParseError( "Cannot parse binary payload into DeviceAuthMessage", AuthResult::ERROR_PAYLOAD_PARSING_FAILED); } VLOG(1) << "Auth message: " << AuthMessageToString(*auth_message); if (auth_message->has_error()) { return AuthResult::CreateWithParseError( "Auth message error: " + base::IntToString(auth_message->error().error_type()), AuthResult::ERROR_MESSAGE_ERROR); } if (!auth_message->has_response()) { return AuthResult::CreateWithParseError( "Auth message has no response field", AuthResult::ERROR_NO_RESPONSE); } return AuthResult(); } AuthResult TranslateVerificationResult( const cast_crypto::VerificationResult& result) { AuthResult translated; translated.error_message = result.error_message; translated.nss_error_code = result.library_error_code; switch (result.error_type) { case cast_crypto::VerificationResult::ERROR_NONE: translated.error_type = AuthResult::ERROR_NONE; break; case cast_crypto::VerificationResult::ERROR_CERT_INVALID: translated.error_type = AuthResult::ERROR_CERT_PARSING_FAILED; break; case cast_crypto::VerificationResult::ERROR_CERT_UNTRUSTED: translated.error_type = AuthResult::ERROR_CERT_NOT_SIGNED_BY_TRUSTED_CA; break; case cast_crypto::VerificationResult::ERROR_SIGNATURE_INVALID: translated.error_type = AuthResult::ERROR_SIGNED_BLOBS_MISMATCH; break; case cast_crypto::VerificationResult::ERROR_INTERNAL: translated.error_type = AuthResult::ERROR_UNEXPECTED_AUTH_LIBRARY_RESULT; break; default: translated.error_type = AuthResult::ERROR_CERT_NOT_SIGNED_BY_TRUSTED_CA; }; return translated; } } // namespace AuthResult::AuthResult() : error_type(ERROR_NONE), nss_error_code(0), channel_policies(POLICY_NONE) { } AuthResult::~AuthResult() { } // static AuthResult AuthResult::CreateWithParseError(const std::string& error_message, ErrorType error_type) { return AuthResult(kParseErrorPrefix + error_message, error_type, 0); } // static AuthResult AuthResult::CreateWithNSSError(const std::string& error_message, ErrorType error_type, int nss_error_code) { return AuthResult(error_message, error_type, nss_error_code); } AuthResult::AuthResult(const std::string& error_message, ErrorType error_type, int nss_error_code) : error_message(error_message), error_type(error_type), nss_error_code(nss_error_code) { } AuthResult AuthenticateChallengeReply(const CastMessage& challenge_reply, const std::string& peer_cert) { if (peer_cert.empty()) { AuthResult result = AuthResult::CreateWithParseError( "Peer cert was empty.", AuthResult::ERROR_PEER_CERT_EMPTY); return result; } DeviceAuthMessage auth_message; AuthResult result = ParseAuthMessage(challenge_reply, &auth_message); if (!result.success()) { return result; } const AuthResponse& response = auth_message.response(); result = VerifyCredentials(response, peer_cert); if (!result.success()) { return result; } if (response.client_auth_certificate().find(reinterpret_cast<const char*>( kAudioOnlyPolicy)) != std::string::npos) { result.channel_policies |= AuthResult::POLICY_AUDIO_ONLY; } return result; } // This function does the following // * Verifies that the trusted CA |response.intermediate_certificate| is // whitelisted for use. // * Verifies that |response.client_auth_certificate| is signed // by the trusted CA certificate. // * Verifies that |response.signature| matches the signature // of |peer_cert| by |response.client_auth_certificate|'s public // key. AuthResult VerifyCredentials(const AuthResponse& response, const std::string& peer_cert) { // Verify the certificate scoped_ptr<cast_crypto::CertVerificationContext> verification_context; cast_crypto::VerificationResult ret = cast_crypto::VerifyDeviceCert( response.client_auth_certificate(), std::vector<std::string>(response.intermediate_certificate().begin(), response.intermediate_certificate().end()), &verification_context); if (ret.Success()) ret = verification_context->VerifySignatureOverData(response.signature(), peer_cert); return TranslateVerificationResult(ret); } } // namespace cast_channel } // namespace core_api } // namespace extensions
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "extensions/browser/api/cast_channel/cast_auth_util.h" #include <vector> #include "base/logging.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "extensions/browser/api/cast_channel/cast_message_util.h" #include "extensions/common/api/cast_channel/cast_channel.pb.h" #include "extensions/common/cast/cast_cert_validator.h" namespace extensions { namespace core_api { namespace cast_channel { namespace { const char* const kParseErrorPrefix = "Failed to parse auth message: "; const unsigned char kAudioOnlyPolicy[] = {0x06, 0x0A, 0x2B, 0x06, 0x01, 0x04, 0x01, 0xD6, 0x79, 0x02, 0x05, 0x02}; namespace cast_crypto = ::extensions::core_api::cast_crypto; // Extracts an embedded DeviceAuthMessage payload from an auth challenge reply // message. AuthResult ParseAuthMessage(const CastMessage& challenge_reply, DeviceAuthMessage* auth_message) { if (challenge_reply.payload_type() != CastMessage_PayloadType_BINARY) { return AuthResult::CreateWithParseError( "Wrong payload type in challenge reply", AuthResult::ERROR_WRONG_PAYLOAD_TYPE); } if (!challenge_reply.has_payload_binary()) { return AuthResult::CreateWithParseError( "Payload type is binary but payload_binary field not set", AuthResult::ERROR_NO_PAYLOAD); } if (!auth_message->ParseFromString(challenge_reply.payload_binary())) { return AuthResult::CreateWithParseError( "Cannot parse binary payload into DeviceAuthMessage", AuthResult::ERROR_PAYLOAD_PARSING_FAILED); } VLOG(1) << "Auth message: " << AuthMessageToString(*auth_message); if (auth_message->has_error()) { return AuthResult::CreateWithParseError( "Auth message error: " + base::IntToString(auth_message->error().error_type()), AuthResult::ERROR_MESSAGE_ERROR); } if (!auth_message->has_response()) { return AuthResult::CreateWithParseError( "Auth message has no response field", AuthResult::ERROR_NO_RESPONSE); } return AuthResult(); } AuthResult TranslateVerificationResult( const cast_crypto::VerificationResult& result) { AuthResult translated; translated.error_message = result.error_message; translated.nss_error_code = result.library_error_code; switch (result.error_type) { case cast_crypto::VerificationResult::ERROR_NONE: translated.error_type = AuthResult::ERROR_NONE; break; case cast_crypto::VerificationResult::ERROR_CERT_INVALID: translated.error_type = AuthResult::ERROR_CERT_PARSING_FAILED; break; case cast_crypto::VerificationResult::ERROR_CERT_UNTRUSTED: translated.error_type = AuthResult::ERROR_CERT_NOT_SIGNED_BY_TRUSTED_CA; break; case cast_crypto::VerificationResult::ERROR_SIGNATURE_INVALID: translated.error_type = AuthResult::ERROR_SIGNED_BLOBS_MISMATCH; break; case cast_crypto::VerificationResult::ERROR_INTERNAL: translated.error_type = AuthResult::ERROR_UNEXPECTED_AUTH_LIBRARY_RESULT; break; default: translated.error_type = AuthResult::ERROR_CERT_NOT_SIGNED_BY_TRUSTED_CA; }; return translated; } } // namespace AuthResult::AuthResult() : error_type(ERROR_NONE), nss_error_code(0), channel_policies(POLICY_NONE) { } AuthResult::~AuthResult() { } // static AuthResult AuthResult::CreateWithParseError(const std::string& error_message, ErrorType error_type) { return AuthResult(kParseErrorPrefix + error_message, error_type, 0); } // static AuthResult AuthResult::CreateWithNSSError(const std::string& error_message, ErrorType error_type, int nss_error_code) { return AuthResult(error_message, error_type, nss_error_code); } AuthResult::AuthResult(const std::string& error_message, ErrorType error_type, int nss_error_code) : error_message(error_message), error_type(error_type), nss_error_code(nss_error_code) { } AuthResult AuthenticateChallengeReply(const CastMessage& challenge_reply, const std::string& peer_cert) { if (peer_cert.empty()) { AuthResult result = AuthResult::CreateWithParseError( "Peer cert was empty.", AuthResult::ERROR_PEER_CERT_EMPTY); return result; } DeviceAuthMessage auth_message; AuthResult result = ParseAuthMessage(challenge_reply, &auth_message); if (!result.success()) { return result; } const AuthResponse& response = auth_message.response(); result = VerifyCredentials(response, peer_cert); if (!result.success()) { return result; } const std::string& audio_policy = std::string(reinterpret_cast<const char*>(kAudioOnlyPolicy), (arraysize(kAudioOnlyPolicy) / sizeof(unsigned char))); if (response.client_auth_certificate().find(audio_policy) != std::string::npos) { result.channel_policies |= AuthResult::POLICY_AUDIO_ONLY; } return result; } // This function does the following // * Verifies that the trusted CA |response.intermediate_certificate| is // whitelisted for use. // * Verifies that |response.client_auth_certificate| is signed // by the trusted CA certificate. // * Verifies that |response.signature| matches the signature // of |peer_cert| by |response.client_auth_certificate|'s public // key. AuthResult VerifyCredentials(const AuthResponse& response, const std::string& peer_cert) { // Verify the certificate scoped_ptr<cast_crypto::CertVerificationContext> verification_context; cast_crypto::VerificationResult ret = cast_crypto::VerifyDeviceCert( response.client_auth_certificate(), std::vector<std::string>(response.intermediate_certificate().begin(), response.intermediate_certificate().end()), &verification_context); if (ret.Success()) ret = verification_context->VerifySignatureOverData(response.signature(), peer_cert); return TranslateVerificationResult(ret); } } // namespace cast_channel } // namespace core_api } // namespace extensions
Fix buffer overflow due to unbounded strlen over the non-null terminated audio policy string. Caught by asan.
Fix buffer overflow due to unbounded strlen over the non-null terminated audio policy string. Caught by asan. BUG= Review URL: https://codereview.chromium.org/890683002 Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#314019}
C++
bsd-3-clause
axinging/chromium-crosswalk,Just-D/chromium-1,Just-D/chromium-1,fujunwei/chromium-crosswalk,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,chuan9/chromium-crosswalk,ltilve/chromium,fujunwei/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,ltilve/chromium,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,fujunwei/chromium-crosswalk,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,Pluto-tv/chromium-crosswalk,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk,Pluto-tv/chromium-crosswalk,fujunwei/chromium-crosswalk,Fireblend/chromium-crosswalk,ltilve/chromium,axinging/chromium-crosswalk,axinging/chromium-crosswalk,ltilve/chromium,ltilve/chromium,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Just-D/chromium-1,hgl888/chromium-crosswalk,Just-D/chromium-1,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,fujunwei/chromium-crosswalk,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,fujunwei/chromium-crosswalk,Just-D/chromium-1,Chilledheart/chromium,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,ltilve/chromium,Chilledheart/chromium,ltilve/chromium,ltilve/chromium,Chilledheart/chromium,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,chuan9/chromium-crosswalk,Just-D/chromium-1,Just-D/chromium-1,fujunwei/chromium-crosswalk,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Pluto-tv/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,Just-D/chromium-1,Chilledheart/chromium,Chilledheart/chromium,chuan9/chromium-crosswalk,Chilledheart/chromium,axinging/chromium-crosswalk,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,ltilve/chromium
6747cdb51624b563fa1ac171d5d5985ee0f61723
src/generate_test.cpp
src/generate_test.cpp
/*- * Copyright 2017 Shivansh Rai * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. * * $FreeBSD$ */ #include <boost/algorithm/string.hpp> #include <boost/filesystem.hpp> #include <cstdio> #include <cstdlib> #include <chrono> #include <dirent.h> #include <fstream> #include <iomanip> #include <iostream> #include <memory> #include <pthread.h> #include <signal.h> #include <stdexcept> #include <sys/stat.h> #include <thread> #include <unordered_set> #include "add_testcase.h" #include "generate_license.h" #include "generate_test.h" #include "read_annotations.h" const char *tests_dir = "generated_tests/"; /* Directory to collect generated tests. */ /* Generate a test for the given utility. */ void generatetest::GenerateTest(std::string utility, std::string section, std::string& license) { std::list<utils::OptRelation *> identified_opt_list; /* List of identified option relations. */ std::vector<std::string> usage_messages; /* Vector of usage messages. Used for validating * their consistency across different runs. */ std::string command; /* (Utility-specific) command to be executed. */ std::string testcase_list; /* List of testcases. */ std::string testcase_buffer; /* Buffer for (temporarily) holding testcase data. */ std::string test_file; /* atf-sh test name. */ std::string util_with_section; /* Section number appended to utility. */ std::ofstream test_fstream; /* Output stream for the atf-sh test. */ std::pair<std::string, int> output; /* Return value type for `Execute()`. */ std::unordered_set<std::string> annotation_set; /* Hashset of utility specific annotations. */ /* Number of options for which a testcase has been generated. */ int progress = 0; /* Read annotations and populate hash set "annotation_set". */ annotations::read_annotations(utility, annotation_set); util_with_section = utility + '(' + section + ')'; utils::OptDefinition opt_def; identified_opt_list = opt_def.CheckOpts(utility); test_file = tests_dir + utility + "_test.sh"; /* Indicate the start of test generation for current utility. */ std::cerr << std::setw(18) << util_with_section << " | " << progress << "/" << opt_def.opt_list.size() << "\r"; /* Add license in the generated test scripts. */ test_fstream.open(test_file, std::ios::out); test_fstream << license; /* * If a known option was encountered (i.e. `identified_opt_list` is * populated), produce a testcase to check the validity of the * result of that option. If no known option was encountered, * produce testcases to verify the correct (generated) usage * message when using the supported options incorrectly. */ /* Add testcases for known options. */ if (!identified_opt_list.empty()) { for (const auto &i : identified_opt_list) { command = utility + " -" + i->value + " 2>&1 </dev/null"; output = utils::Execute(command); if (boost::iequals(output.first.substr(0, 6), "usage:")) { /* A usage message was produced => our guessed usage is incorrect. */ addtestcase::UnknownTestcase(i->value, util_with_section, output.first, output.second, testcase_buffer); } else { addtestcase::KnownTestcase(i->value, util_with_section, "", output.first, test_fstream); } testcase_list.append("\tatf_add_test_case " + i->value + "_flag\n"); } } /* Add testcases for the options whose usage is not yet known. */ if (!opt_def.opt_list.empty()) { /* * For the purpose of adding a "$usage_output" variable, * we choose the option which produces one. * TODO(shivansh) Avoid double executions of an option, i.e. one while * selecting usage message and another while generating testcase. */ if (opt_def.opt_list.size() == 1) { /* Utility supports a single option, check if it produces a usage message. */ command = utility + " -" + opt_def.opt_list.front() + " 2>&1 </dev/null"; output = utils::Execute(command); if (output.second && !output.first.empty()) test_fstream << "usage_output=\'" + output.first + "\'\n\n"; } else { /* * Utility supports multiple options. In case the usage message * is consistent for atleast "two" options, we reduce duplication * by assigning a variable "usage_output" in the test script. */ for (const auto &i : opt_def.opt_list) { command = utility + " -" + i + " 2>&1 </dev/null"; output = utils::Execute(command); if (output.second && usage_messages.size() < 3) usage_messages.push_back(output.first); } for (int j = 0; j < usage_messages.size(); j++) { if (!(usage_messages.at(j)).compare(usage_messages.at((j+1) % usage_messages.size())) && !output.first.empty()) { test_fstream << "usage_output=\'" + output.first.substr(0, 7 + utility.size()) + "\'\n\n"; break; } } } /* * Execute the utility with supported options * and add (+ve)/(-ve) testcases accordingly. */ for (const auto &i : opt_def.opt_list) { /* If the option is annotated, ignore it. */ if (annotation_set.find(i) != annotation_set.end()) continue; command = utility + " -" + i + " 2>&1 </dev/null"; output = utils::Execute(command); std::cerr << std::setw(18) << util_with_section << " | " << ++progress << "/" << opt_def.opt_list.size() << "\r"; if (output.second) { /* Non-zero exit status was encountered. */ addtestcase::UnknownTestcase(i, util_with_section, output.first, output.second, testcase_buffer); } else { /* * EXIT_SUCCESS was encountered. Hence, * the guessed usage was correct. */ addtestcase::KnownTestcase(i, util_with_section, "", output.first, test_fstream); testcase_list.append(std::string("\tatf_add_test_case ") + i + "_flag\n"); } } std::cerr << std::endl; testcase_list.append("\tatf_add_test_case invalid_usage\n"); test_fstream << std::string("atf_test_case invalid_usage\ninvalid_usage_head()\n") + "{\n\tatf_set \"descr\" \"Verify that an invalid usage " + "with a supported option \" \\\n\t\t\t\"produces a valid error message" + "\"\n}\n\ninvalid_usage_body()\n{"; test_fstream << testcase_buffer + "\n}\n\n"; } /* * Add a testcase under "no_arguments" for * running the utility without any arguments. */ if (annotation_set.find("*") == annotation_set.end()) { command = utility + " 2>&1 </dev/null"; output = utils::Execute(command); addtestcase::NoArgsTestcase(util_with_section, output, test_fstream); testcase_list.append("\tatf_add_test_case no_arguments\n"); } test_fstream << "atf_init_test_cases()\n{\n" + testcase_list + "}\n"; test_fstream.close(); } int main(int argc, char **argv) { std::ifstream groff_list; std::list<std::pair<std::string, std::string>> utility_list; std::string test_file; /* atf-sh test name. */ std::string util_name; /* Utility name. */ struct stat sb; struct dirent *ent; DIR *groff_dir_ptr; char answer; /* User input to determine overwriting of test files. */ std::string license; /* Customized license generated during runtime. */ /* Directory for collecting groff scripts for utilities with failed test generation. */ const char *failed_groff_dir = "failed_groff/"; const char *groff_dir = "groff/"; /* Directory of groff scripts. */ /* * For testing (or generating tests for only selected utilities), * the utility_list can be populated above during declaration. */ if (utility_list.empty()) { if ((groff_dir_ptr = opendir(groff_dir))) { readdir(groff_dir_ptr); /* Skip directory entry for "." */ readdir(groff_dir_ptr); /* Skip directory entry for ".." */ while ((ent = readdir(groff_dir_ptr))) { util_name = ent->d_name; utility_list.push_back(std::make_pair<std::string, std::string> (util_name.substr(0, util_name.length() - 2), util_name.substr(util_name.length() - 1, 1))); } closedir(groff_dir_ptr); } else { fprintf(stderr, "Could not open the directory: ./groff\nRefer to the " "section \"Populating groff scripts\" in README!\n"); return EXIT_FAILURE; } } /* Check if the directory "tests_dir" exists. */ if (stat(tests_dir, &sb) || !S_ISDIR(sb.st_mode)) { boost::filesystem::path dir(tests_dir); if (boost::filesystem::create_directory(dir)) std::cout << "Directory created: " << tests_dir << std::endl; else { std::cerr << "Unable to create directory: " << tests_dir << std::endl; return EXIT_FAILURE; } } /* Generate a license to be added in the generated scripts. */ license = generatelicense::GenerateLicense(argc, argv); remove(failed_groff_dir); boost::filesystem::create_directory(failed_groff_dir); /* Generate a tabular-like format. */ std::cout << std::endl; std::cout << std::setw(21) << "Utility | " << "Progress\n"; std::cout << std::setw(32) << "----------+-----------\n"; for (const auto &util : utility_list) { /* TODO(shivansh) Check before overwriting existing test scripts. */ test_file = tests_dir + util.first + "_test.sh"; fflush(stdout); /* Useful in debugging. */ generatetest::GenerateTest(util.first, util.second, license); std::this_thread::sleep_for(std::chrono::milliseconds(100)); } return EXIT_SUCCESS; }
/*- * Copyright 2017 Shivansh Rai * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. * * $FreeBSD$ */ #include <boost/algorithm/string.hpp> #include <boost/filesystem.hpp> #include <cstdio> #include <cstdlib> #include <chrono> #include <dirent.h> #include <fstream> #include <iomanip> #include <iostream> #include <memory> #include <pthread.h> #include <signal.h> #include <stdexcept> #include <sys/stat.h> #include <thread> #include <unordered_set> #include "add_testcase.h" #include "generate_license.h" #include "generate_test.h" #include "read_annotations.h" const char *tests_dir = "generated_tests/"; /* Directory to collect generated tests. */ /* Generate a test for the given utility. */ void generatetest::GenerateTest(std::string utility, std::string section, std::string& license) { std::list<utils::OptRelation *> identified_opt_list; /* List of identified option relations. */ std::vector<std::string> usage_messages; /* Vector of usage messages. Used for validating * their consistency across different runs. */ std::string command; /* (Utility-specific) command to be executed. */ std::string testcase_list; /* List of testcases. */ std::string testcase_buffer; /* Buffer for (temporarily) holding testcase data. */ std::string test_file; /* atf-sh test name. */ std::string util_with_section; /* Section number appended to utility. */ std::ofstream test_fstream; /* Output stream for the atf-sh test. */ std::pair<std::string, int> output; /* Return value type for `Execute()`. */ std::unordered_set<std::string> annotation_set; /* Hashset of utility specific annotations. */ /* Number of options for which a testcase has been generated. */ int progress = 0; /* Read annotations and populate hash set "annotation_set". */ annotations::read_annotations(utility, annotation_set); util_with_section = utility + '(' + section + ')'; utils::OptDefinition opt_def; identified_opt_list = opt_def.CheckOpts(utility); test_file = tests_dir + utility + "_test.sh"; /* Indicate the start of test generation for current utility. */ if (isatty(fileno(stderr))) { std::cerr << std::setw(18) << util_with_section << " | " << progress << "/" << opt_def.opt_list.size() << "\r"; } /* Add license in the generated test scripts. */ test_fstream.open(test_file, std::ios::out); test_fstream << license; /* * If a known option was encountered (i.e. `identified_opt_list` is * populated), produce a testcase to check the validity of the * result of that option. If no known option was encountered, * produce testcases to verify the correct (generated) usage * message when using the supported options incorrectly. */ /* Add testcases for known options. */ if (!identified_opt_list.empty()) { for (const auto &i : identified_opt_list) { command = utility + " -" + i->value + " 2>&1 </dev/null"; output = utils::Execute(command); if (boost::iequals(output.first.substr(0, 6), "usage:")) { /* A usage message was produced => our guessed usage is incorrect. */ addtestcase::UnknownTestcase(i->value, util_with_section, output.first, output.second, testcase_buffer); } else { addtestcase::KnownTestcase(i->value, util_with_section, "", output.first, test_fstream); } testcase_list.append("\tatf_add_test_case " + i->value + "_flag\n"); } } /* Add testcases for the options whose usage is not yet known. */ if (!opt_def.opt_list.empty()) { /* * For the purpose of adding a "$usage_output" variable, * we choose the option which produces one. * TODO(shivansh) Avoid double executions of an option, i.e. one while * selecting usage message and another while generating testcase. */ if (opt_def.opt_list.size() == 1) { /* Utility supports a single option, check if it produces a usage message. */ command = utility + " -" + opt_def.opt_list.front() + " 2>&1 </dev/null"; output = utils::Execute(command); if (output.second && !output.first.empty()) test_fstream << "usage_output=\'" + output.first + "\'\n\n"; } else { /* * Utility supports multiple options. In case the usage message * is consistent for atleast "two" options, we reduce duplication * by assigning a variable "usage_output" in the test script. */ for (const auto &i : opt_def.opt_list) { command = utility + " -" + i + " 2>&1 </dev/null"; output = utils::Execute(command); if (output.second && usage_messages.size() < 3) usage_messages.push_back(output.first); } for (int j = 0; j < usage_messages.size(); j++) { if (!(usage_messages.at(j)).compare(usage_messages.at((j+1) % usage_messages.size())) && !output.first.empty()) { test_fstream << "usage_output=\'" + output.first.substr(0, 7 + utility.size()) + "\'\n\n"; break; } } } /* * Execute the utility with supported options * and add (+ve)/(-ve) testcases accordingly. */ for (const auto &i : opt_def.opt_list) { /* If the option is annotated, ignore it. */ if (annotation_set.find(i) != annotation_set.end()) continue; command = utility + " -" + i + " 2>&1 </dev/null"; output = utils::Execute(command); if (isatty(fileno(stderr))) { std::cerr << std::setw(18) << util_with_section << " | " << ++progress << "/" << opt_def.opt_list.size() << "\r"; } if (output.second) { /* Non-zero exit status was encountered. */ addtestcase::UnknownTestcase(i, util_with_section, output.first, output.second, testcase_buffer); } else { /* * EXIT_SUCCESS was encountered. Hence, * the guessed usage was correct. */ addtestcase::KnownTestcase(i, util_with_section, "", output.first, test_fstream); testcase_list.append(std::string("\tatf_add_test_case ") + i + "_flag\n"); } } std::cerr << std::endl; testcase_list.append("\tatf_add_test_case invalid_usage\n"); test_fstream << std::string("atf_test_case invalid_usage\ninvalid_usage_head()\n") + "{\n\tatf_set \"descr\" \"Verify that an invalid usage " + "with a supported option \" \\\n\t\t\t\"produces a valid error message" + "\"\n}\n\ninvalid_usage_body()\n{"; test_fstream << testcase_buffer + "\n}\n\n"; } /* * Add a testcase under "no_arguments" for * running the utility without any arguments. */ if (annotation_set.find("*") == annotation_set.end()) { command = utility + " 2>&1 </dev/null"; output = utils::Execute(command); addtestcase::NoArgsTestcase(util_with_section, output, test_fstream); testcase_list.append("\tatf_add_test_case no_arguments\n"); } test_fstream << "atf_init_test_cases()\n{\n" + testcase_list + "}\n"; test_fstream.close(); } int main(int argc, char **argv) { std::ifstream groff_list; std::list<std::pair<std::string, std::string>> utility_list; std::string test_file; /* atf-sh test name. */ std::string util_name; /* Utility name. */ struct stat sb; struct dirent *ent; DIR *groff_dir_ptr; char answer; /* User input to determine overwriting of test files. */ std::string license; /* Customized license generated during runtime. */ /* Directory for collecting groff scripts for utilities with failed test generation. */ const char *failed_groff_dir = "failed_groff/"; const char *groff_dir = "groff/"; /* Directory of groff scripts. */ /* * For testing (or generating tests for only selected utilities), * the utility_list can be populated above during declaration. */ if (utility_list.empty()) { if ((groff_dir_ptr = opendir(groff_dir))) { readdir(groff_dir_ptr); /* Skip directory entry for "." */ readdir(groff_dir_ptr); /* Skip directory entry for ".." */ while ((ent = readdir(groff_dir_ptr))) { util_name = ent->d_name; utility_list.push_back(std::make_pair<std::string, std::string> (util_name.substr(0, util_name.length() - 2), util_name.substr(util_name.length() - 1, 1))); } closedir(groff_dir_ptr); } else { fprintf(stderr, "Could not open the directory: ./groff\nRefer to the " "section \"Populating groff scripts\" in README!\n"); return EXIT_FAILURE; } } /* Check if the directory "tests_dir" exists. */ if (stat(tests_dir, &sb) || !S_ISDIR(sb.st_mode)) { boost::filesystem::path dir(tests_dir); if (boost::filesystem::create_directory(dir)) std::cout << "Directory created: " << tests_dir << std::endl; else { std::cerr << "Unable to create directory: " << tests_dir << std::endl; return EXIT_FAILURE; } } /* Generate a license to be added in the generated scripts. */ license = generatelicense::GenerateLicense(argc, argv); remove(failed_groff_dir); boost::filesystem::create_directory(failed_groff_dir); /* Generate a tabular-like format. */ std::cout << std::endl; std::cout << std::setw(21) << "Utility | " << "Progress\n"; std::cout << std::setw(32) << "----------+-----------\n"; for (const auto &util : utility_list) { /* TODO(shivansh) Check before overwriting existing test scripts. */ test_file = tests_dir + util.first + "_test.sh"; fflush(stdout); /* Useful in debugging. */ generatetest::GenerateTest(util.first, util.second, license); } return EXIT_SUCCESS; }
Handle the case when output is redirected to pipe or a file
Handle the case when output is redirected to pipe or a file The previous version will generate a garbage output when directed to a file, or maybe even a serial console. Thanks to @asomers!
C++
bsd-2-clause
shivrai/smoketestsuite,shivansh/smoketestsuite,shivrai/smoketestsuite,shivansh/smoketestsuite,shivrai/smoketestsuite,shivansh/smoketestsuite
965d6d91d88aae7164e74acdce8b7a7f7e305d48
src/hamlib.cpp
src/hamlib.cpp
//========================================================================== // Name: hamlib.cpp // // Purpose: Hamlib integration for FreeDV // Created: May 2013 // Authors: Joel Stanley // // License: // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2.1, // as published by the Free Software Foundation. This program is // distributed in the hope that it will be useful, but WITHOUT ANY // WARRANTY; without even the implied warranty of MERCHANTABILITY or // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public // License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, see <http://www.gnu.org/licenses/>. // //========================================================================== #include <hamlib.h> #include <vector> #include <algorithm> using namespace std; typedef std::vector<const struct rig_caps *> riglist_t; static bool rig_cmp(const struct rig_caps *rig1, const struct rig_caps *rig2); static int build_list(const struct rig_caps *rig, rig_ptr_t); Hamlib::Hamlib() : m_rig(NULL) { /* Stop hamlib from spewing info to stderr. */ rig_set_debug(RIG_DEBUG_NONE); /* Create sorted list of rigs. */ rig_load_all_backends(); rig_list_foreach(build_list, &m_rigList); sort(m_rigList.begin(), m_rigList.end(), rig_cmp); /* Reset debug output. */ rig_set_debug(RIG_DEBUG_VERBOSE); } Hamlib::~Hamlib() { } static int build_list(const struct rig_caps *rig, rig_ptr_t rigList) { ((riglist_t *)rigList)->push_back(rig); return 1; } static bool rig_cmp(const struct rig_caps *rig1, const struct rig_caps *rig2) { /* Compare manufacturer. */ int r = strcasecmp(rig1->mfg_name, rig2->mfg_name); if (r != 0) return r < 0; /* Compare model. */ r = strcasecmp(rig1->model_name, rig2->model_name); if (r != 0) return r < 0; /* Compare rig ID. */ return rig1->rig_model < rig2->rig_model; } void Hamlib::populateComboBox(wxComboBox *cb) { riglist_t::const_iterator rig = m_rigList.begin(); for (; rig !=m_rigList.end(); rig++) { char name[128]; snprintf(name, 128, "%s %s", (*rig)->mfg_name, (*rig)->model_name); cb->Append(name); } } bool Hamlib::connect(unsigned int rig_index, const char *serial_port) { /* Look up model from index. */ if (rig_index >= m_rigList.size()) { return false; } printf("rig: %s %s (%d)\n", m_rigList[rig_index]->mfg_name, m_rigList[rig_index]->model_name, m_rigList[rig_index]->rig_model); /* Initialise, configure and open. */ m_rig = rig_init(m_rigList[rig_index]->rig_model); /* TODO: Also use baud rate from the screen. */ if (!m_rig) return false; token_t token = rig_token_lookup(m_rig, "rig_pathname"); if (rig_set_conf(m_rig, token, serial_port) != RIG_OK) { return false; } if (rig_open(m_rig) == RIG_OK) { return true; } return false; } bool Hamlib::ptt(bool press) { /* TODO(Joel): make ON_DATA and ON configurable. */ ptt_t on = press ? RIG_PTT_ON : RIG_PTT_OFF; /* TODO(Joel): what should the VFO option be? */ return rig_set_ptt(m_rig, RIG_VFO_CURR, on) == RIG_OK; } void Hamlib::close(void) { rig_close(m_rig); rig_cleanup(m_rig); free(m_rig); }
//========================================================================== // Name: hamlib.cpp // // Purpose: Hamlib integration for FreeDV // Created: May 2013 // Authors: Joel Stanley // // License: // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2.1, // as published by the Free Software Foundation. This program is // distributed in the hope that it will be useful, but WITHOUT ANY // WARRANTY; without even the implied warranty of MERCHANTABILITY or // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public // License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, see <http://www.gnu.org/licenses/>. // //========================================================================== #include <hamlib.h> #include <vector> #include <algorithm> using namespace std; typedef std::vector<const struct rig_caps *> riglist_t; static bool rig_cmp(const struct rig_caps *rig1, const struct rig_caps *rig2); static int build_list(const struct rig_caps *rig, rig_ptr_t); Hamlib::Hamlib() : m_rig(NULL) { /* Stop hamlib from spewing info to stderr. */ rig_set_debug(RIG_DEBUG_NONE); /* Create sorted list of rigs. */ rig_load_all_backends(); rig_list_foreach(build_list, &m_rigList); sort(m_rigList.begin(), m_rigList.end(), rig_cmp); /* Reset debug output. */ rig_set_debug(RIG_DEBUG_VERBOSE); } Hamlib::~Hamlib() { } static int build_list(const struct rig_caps *rig, rig_ptr_t rigList) { ((riglist_t *)rigList)->push_back(rig); return 1; } static bool rig_cmp(const struct rig_caps *rig1, const struct rig_caps *rig2) { /* Compare manufacturer. */ int r = strcasecmp(rig1->mfg_name, rig2->mfg_name); if (r != 0) return r < 0; /* Compare model. */ r = strcasecmp(rig1->model_name, rig2->model_name); if (r != 0) return r < 0; /* Compare rig ID. */ return rig1->rig_model < rig2->rig_model; } void Hamlib::populateComboBox(wxComboBox *cb) { riglist_t::const_iterator rig = m_rigList.begin(); for (; rig !=m_rigList.end(); rig++) { char name[128]; snprintf(name, 128, "%s %s", (*rig)->mfg_name, (*rig)->model_name); cb->Append(name); } } bool Hamlib::connect(unsigned int rig_index, const char *serial_port) { /* Look up model from index. */ if (rig_index >= m_rigList.size()) { return false; } printf("rig: %s %s (%d)\n", m_rigList[rig_index]->mfg_name, m_rigList[rig_index]->model_name, m_rigList[rig_index]->rig_model); /* Initialise, configure and open. */ m_rig = rig_init(m_rigList[rig_index]->rig_model); /* TODO: Also use baud rate from the screen. */ if (!m_rig) return false; token_t token = rig_token_lookup(m_rig, "rig_pathname"); if (rig_set_conf(m_rig, token, serial_port) != RIG_OK) { return false; } if (rig_open(m_rig) == RIG_OK) { return true; } return false; } bool Hamlib::ptt(bool press) { /* TODO(Joel): make ON_DATA and ON configurable. */ ptt_t on = press ? RIG_PTT_ON : RIG_PTT_OFF; /* TODO(Joel): what should the VFO option be? */ return rig_set_ptt(m_rig, RIG_VFO_CURR, on) == RIG_OK; } void Hamlib::close(void) { rig_close(m_rig); rig_cleanup(m_rig); #ifndef __APPLE__ free(m_rig); #endif }
Fix crash when using hamlib by removing unnecessary free call.
Fix crash when using hamlib by removing unnecessary free call.
C++
lgpl-2.1
tmiw/freedv-osx,tmiw/freedv-osx,tmiw/freedv-osx
9ab3c757e6aead3e9affb5bbf6b5dea126487a56
src/hackernewsapi.cpp
src/hackernewsapi.cpp
/* The MIT License (MIT) Copyright (c) 2015 Andrea Scarpino <[email protected]> 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 "hackernewsapi.h" #include <QDebug> #include <QJsonArray> #include <QJsonDocument> #include <QJsonObject> #include <QNetworkAccessManager> #include <QNetworkReply> #include "item.h" const static QString API_URL = QStringLiteral("https://hacker-news.firebaseio.com/v0/"); HackerNewsAPI::HackerNewsAPI(QObject *parent) : QObject(parent) , network(new QNetworkAccessManager(this)) { } HackerNewsAPI::~HackerNewsAPI() { delete network; } void HackerNewsAPI::getItem(const int id) { qDebug() << "Requesting item with id" << id; QUrl url(API_URL + QString("item/%1.json").arg(id)); QNetworkRequest req(url); QNetworkReply* reply = network->get(req); connect(reply, &QNetworkReply::finished, this, &HackerNewsAPI::onGetItemResult); } void HackerNewsAPI::getStories(Stories kind) { qDebug() << "Requesting new stories"; QString path; switch (kind) { case Ask: path = QString("askstories.json"); break; case Job: path = QString("jobstories.json"); break; case New: path = QString("newstories.json"); break; case Show: path = QString("showstories.json"); break; case Top: path = QString("topstories.json"); } QUrl url(API_URL + path); QNetworkRequest req(url); QNetworkReply* reply = network->get(req); connect(reply, &QNetworkReply::finished, this, &HackerNewsAPI::onStoriesResult); } void HackerNewsAPI::onGetItemResult() { QNetworkReply* reply = qobject_cast<QNetworkReply*>(QObject::sender()); if (reply->error() != QNetworkReply::NoError) { qCritical() << "Cannot fetch item"; } else { QJsonDocument json = QJsonDocument::fromJson(reply->readAll()); if (!json.isNull()) { //qDebug() << "Got item:\n" << json; Item* item = new Item(); QJsonObject jsonObj = json.object(); item->setId(jsonObj.value("id").toInt()); item->setBy(jsonObj.value("by").toString()); item->setDeleted(jsonObj.value("deleted").toBool()); item->setDescendants(jsonObj.value("descendants").toInt()); QJsonArray jsonKids = jsonObj.value("kids").toArray(); QList<int> kids; Q_FOREACH (const QVariant kid, jsonKids.toVariantList()) { kids.append(kid.toInt()); } item->setKids(kids); item->setText(jsonObj.value("text").toString()); item->setTitle(jsonObj.value("title").toString()); item->setUrl(QUrl(jsonObj.value("url").toString())); // FIXME: to be removed when we display items text and comments // Since we don't display hacker news items yet, we just set // the external url to the item detail page in Hacker News if (item->url().isEmpty()) { item->setUrl(QUrl("https://news.ycombinator.com/item?id=" + QString::number(item->id()))); } item->setScore(jsonObj.value("score").toInt()); QDateTime timestamp; timestamp.setTime_t(jsonObj.value("time").toInt()); item->setTime(timestamp); emit itemFetched(item); } } reply->deleteLater(); } void HackerNewsAPI::onStoriesResult() { QNetworkReply* reply = qobject_cast<QNetworkReply*>(QObject::sender()); if (reply->error() != QNetworkReply::NoError) { qCritical() << "Cannot fetch stories"; } else { QJsonDocument json = QJsonDocument::fromJson(reply->readAll()); if (!json.isNull()) { qDebug() << "Got" << json.array().size() << "items"; QList<int> ids; Q_FOREACH (const QJsonValue id, json.array()) { ids.append(id.toInt()); } emit storiesFetched(ids); } } reply->deleteLater(); }
/* The MIT License (MIT) Copyright (c) 2015 Andrea Scarpino <[email protected]> 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 "hackernewsapi.h" #include <QDebug> #include <QJsonArray> #include <QJsonDocument> #include <QJsonObject> #include <QNetworkAccessManager> #include <QNetworkReply> #include "item.h" const static QString API_URL = QStringLiteral("https://hacker-news.firebaseio.com/v0/"); HackerNewsAPI::HackerNewsAPI(QObject *parent) : QObject(parent) , network(new QNetworkAccessManager(this)) { } HackerNewsAPI::~HackerNewsAPI() { delete network; } void HackerNewsAPI::getItem(const int id) { qDebug() << "Requesting item with id" << id; QUrl url(API_URL + QStringLiteral("item/%1.json").arg(id)); QNetworkRequest req(url); QNetworkReply* reply = network->get(req); connect(reply, &QNetworkReply::finished, this, &HackerNewsAPI::onGetItemResult); } void HackerNewsAPI::getStories(Stories kind) { qDebug() << "Requesting new stories"; QString path; switch (kind) { case Ask: path = QStringLiteral("askstories.json"); break; case Job: path = QStringLiteral("jobstories.json"); break; case New: path = QStringLiteral("newstories.json"); break; case Show: path = QStringLiteral("showstories.json"); break; case Top: path = QStringLiteral("topstories.json"); } QUrl url(API_URL + path); QNetworkRequest req(url); QNetworkReply* reply = network->get(req); connect(reply, &QNetworkReply::finished, this, &HackerNewsAPI::onStoriesResult); } void HackerNewsAPI::onGetItemResult() { QNetworkReply* reply = qobject_cast<QNetworkReply*>(QObject::sender()); if (reply->error() != QNetworkReply::NoError) { qCritical() << "Cannot fetch item"; } else { QJsonDocument json = QJsonDocument::fromJson(reply->readAll()); if (!json.isNull()) { //qDebug() << "Got item:\n" << json; Item* item = new Item(); QJsonObject jsonObj = json.object(); item->setId(jsonObj.value("id").toInt()); item->setBy(jsonObj.value("by").toString()); item->setDeleted(jsonObj.value("deleted").toBool()); item->setDescendants(jsonObj.value("descendants").toInt()); QJsonArray jsonKids = jsonObj.value("kids").toArray(); QList<int> kids; Q_FOREACH (const QVariant kid, jsonKids.toVariantList()) { kids.append(kid.toInt()); } item->setKids(kids); item->setText(jsonObj.value("text").toString()); item->setTitle(jsonObj.value("title").toString()); item->setUrl(QUrl(jsonObj.value("url").toString())); // FIXME: to be removed when we display items text and comments // Since we don't display hacker news items yet, we just set // the external url to the item detail page in Hacker News if (item->url().isEmpty()) { item->setUrl(QUrl(QStringLiteral("https://news.ycombinator.com/item?id=%1").arg(item->id()))); } item->setScore(jsonObj.value("score").toInt()); QDateTime timestamp; timestamp.setTime_t(jsonObj.value("time").toInt()); item->setTime(timestamp); emit itemFetched(item); } } reply->deleteLater(); } void HackerNewsAPI::onStoriesResult() { QNetworkReply* reply = qobject_cast<QNetworkReply*>(QObject::sender()); if (reply->error() != QNetworkReply::NoError) { qCritical() << "Cannot fetch stories"; } else { QJsonDocument json = QJsonDocument::fromJson(reply->readAll()); if (!json.isNull()) { qDebug() << "Got" << json.array().size() << "items"; QList<int> ids; Q_FOREACH (const QJsonValue id, json.array()) { ids.append(id.toInt()); } emit storiesFetched(ids); } } reply->deleteLater(); }
Use QStringLiteral instead
Use QStringLiteral instead
C++
mit
ascarpino/harbour-SailHN,ilpianista/harbour-SailHN,ilpianista/harbour-SailHN
815a38288ae7c4562c26608e14afa82f1500bec5
Runtime/GuiSys/CSaveableState.hpp
Runtime/GuiSys/CSaveableState.hpp
#pragma once #include <vector> #include "Runtime/CToken.hpp" #include "Runtime/GCNTypes.hpp" #include "Runtime/GuiSys/CDrawStringOptions.hpp" #include "Runtime/GuiSys/CGuiTextSupport.hpp" #include <zeus/CColor.hpp> namespace urde { class CRasterFont; class CSaveableState { friend class CColorOverrideInstruction; friend class CFontInstruction; friend class CGuiTextSupport; friend class CLineExtraSpaceInstruction; friend class CLineSpacingInstruction; friend class CRemoveColorOverrideInstruction; friend class CTextExecuteBuffer; friend class CTextInstruction; friend class CWordInstruction; protected: CDrawStringOptions x0_drawStrOpts; TLockedToken<CRasterFont> x48_font; std::vector<CTextColor> x54_colors; std::vector<bool> x64_colorOverrides; float x74_lineSpacing = 1.f; s32 x78_extraLineSpace = 0; bool x7c_enableWordWrap = false; EJustification x80_just = EJustification::Left; EVerticalJustification x84_vjust = EVerticalJustification::Top; public: CSaveableState() { x54_colors.resize(3, zeus::skBlack); x64_colorOverrides.resize(16); } bool IsFinishedLoading() const; }; } // namespace urde
#pragma once #include <vector> #include "Runtime/CToken.hpp" #include "Runtime/GCNTypes.hpp" #include "Runtime/GuiSys/CDrawStringOptions.hpp" #include "Runtime/GuiSys/CGuiTextSupport.hpp" #include <zeus/CColor.hpp> namespace urde { class CRasterFont; class CSaveableState { friend class CColorOverrideInstruction; friend class CFontInstruction; friend class CGuiTextSupport; friend class CLineExtraSpaceInstruction; friend class CLineSpacingInstruction; friend class CRemoveColorOverrideInstruction; friend class CTextExecuteBuffer; friend class CTextInstruction; friend class CWordInstruction; protected: CDrawStringOptions x0_drawStrOpts; TLockedToken<CRasterFont> x48_font; std::vector<CTextColor> x54_colors; std::vector<bool> x64_colorOverrides; float x74_lineSpacing = 1.f; s32 x78_extraLineSpace = 0; bool x7c_enableWordWrap = false; EJustification x80_just = EJustification::Left; EVerticalJustification x84_vjust = EVerticalJustification::Top; public: CSaveableState() : x54_colors(3, zeus::skBlack), x64_colorOverrides(16) {} bool IsFinishedLoading() const; }; } // namespace urde
Initialize vectors in the constructor initializer list
CSaveableState: Initialize vectors in the constructor initializer list Initializes the vectors in place, rather than constructing them and then resizing.
C++
mit
AxioDL/PathShagged,AxioDL/PathShagged,AxioDL/PathShagged