text
stringlengths
54
60.6k
<commit_before>/************************************************************************** Copyright (c) 2017 sewenew 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 "errors.h" #include <cassert> #include <cerrno> #include <unordered_map> #include <tuple> #include "shards.h" namespace { using namespace sw::redis; std::pair<ReplyErrorType, std::string> parse_error(const std::string &msg); std::unordered_map<std::string, ReplyErrorType> error_map = { {"MOVED", ReplyErrorType::MOVED}, {"ASK", ReplyErrorType::ASK} }; } namespace sw { namespace redis { void throw_error(redisContext &context, const std::string &err_info) { auto err_code = context.err; const auto *err_str = context.errstr; if (err_str == nullptr) { throw Error(err_info + ": null error message: " + std::to_string(err_code)); } auto err_msg = err_info + ": " + err_str; switch (err_code) { case REDIS_ERR_IO: if (errno == EAGAIN || errno == EINTR) { throw TimeoutError(err_msg); } else { throw IoError(err_msg); } break; case REDIS_ERR_EOF: throw ClosedError(err_msg); break; case REDIS_ERR_PROTOCOL: throw ProtoError(err_msg); break; case REDIS_ERR_OOM: throw OomError(err_msg); break; case REDIS_ERR_OTHER: throw Error(err_msg); break; case REDIS_ERR_TIMEOUT: throw TimeoutError(err_msg); break; default: throw Error("unknown error code: " + err_msg); } } void throw_error(const redisReply &reply) { assert(reply.type == REDIS_REPLY_ERROR); if (reply.str == nullptr) { throw Error("Null error reply"); } auto err_str = std::string(reply.str, reply.len); auto err_type = ReplyErrorType::ERR; std::string err_msg; std::tie(err_type, err_msg) = parse_error(err_str); switch (err_type) { case ReplyErrorType::MOVED: throw MovedError(err_msg); break; case ReplyErrorType::ASK: throw AskError(err_msg); break; default: throw ReplyError(err_str); break; } } } } namespace { using namespace sw::redis; std::pair<ReplyErrorType, std::string> parse_error(const std::string &err) { // The error contains an Error Prefix, and an optional error message. auto idx = err.find_first_of(" \n"); if (idx == std::string::npos) { throw ProtoError("No Error Prefix: " + err); } auto err_prefix = err.substr(0, idx); auto err_type = ReplyErrorType::ERR; auto iter = error_map.find(err_prefix); if (iter != error_map.end()) { // Specific error. err_type = iter->second; } // else Generic error. return {err_type, err.substr(idx + 1)}; } } <commit_msg>make the timeout patch compatible with old version of hiredis<commit_after>/************************************************************************** Copyright (c) 2017 sewenew 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 "errors.h" #include <cassert> #include <cerrno> #include <unordered_map> #include <tuple> #include "shards.h" namespace { using namespace sw::redis; std::pair<ReplyErrorType, std::string> parse_error(const std::string &msg); std::unordered_map<std::string, ReplyErrorType> error_map = { {"MOVED", ReplyErrorType::MOVED}, {"ASK", ReplyErrorType::ASK} }; } namespace sw { namespace redis { void throw_error(redisContext &context, const std::string &err_info) { auto err_code = context.err; const auto *err_str = context.errstr; if (err_str == nullptr) { throw Error(err_info + ": null error message: " + std::to_string(err_code)); } auto err_msg = err_info + ": " + err_str; switch (err_code) { case REDIS_ERR_IO: if (errno == EAGAIN || errno == EWOULDBLOCK || errno == ETIMEDOUT) { throw TimeoutError(err_msg); } else { throw IoError(err_msg); } break; case REDIS_ERR_EOF: throw ClosedError(err_msg); break; case REDIS_ERR_PROTOCOL: throw ProtoError(err_msg); break; case REDIS_ERR_OOM: throw OomError(err_msg); break; case REDIS_ERR_OTHER: throw Error(err_msg); break; #ifdef REDIS_ERR_TIMEOUT case REDIS_ERR_TIMEOUT: throw TimeoutError(err_msg); break; #endif default: throw Error("unknown error code: " + err_msg); } } void throw_error(const redisReply &reply) { assert(reply.type == REDIS_REPLY_ERROR); if (reply.str == nullptr) { throw Error("Null error reply"); } auto err_str = std::string(reply.str, reply.len); auto err_type = ReplyErrorType::ERR; std::string err_msg; std::tie(err_type, err_msg) = parse_error(err_str); switch (err_type) { case ReplyErrorType::MOVED: throw MovedError(err_msg); break; case ReplyErrorType::ASK: throw AskError(err_msg); break; default: throw ReplyError(err_str); break; } } } } namespace { using namespace sw::redis; std::pair<ReplyErrorType, std::string> parse_error(const std::string &err) { // The error contains an Error Prefix, and an optional error message. auto idx = err.find_first_of(" \n"); if (idx == std::string::npos) { throw ProtoError("No Error Prefix: " + err); } auto err_prefix = err.substr(0, idx); auto err_type = ReplyErrorType::ERR; auto iter = error_map.find(err_prefix); if (iter != error_map.end()) { // Specific error. err_type = iter->second; } // else Generic error. return {err_type, err.substr(idx + 1)}; } } <|endoftext|>
<commit_before>/* * MRustC - Rust Compiler * - By John Hodge (Mutabah/thePowersGang) * * span.cpp * - Spans and error handling */ #include <functional> #include <iostream> #include <span.hpp> #include <parse/lex.hpp> #include <common.hpp> SpanInner Span::s_empty_span; Span::Span(Span parent, RcString filename, unsigned int start_line, unsigned int start_ofs, unsigned int end_line, unsigned int end_ofs): m_ptr(SpanInner::alloc( parent, ::std::move(filename), start_line, start_ofs, end_line, end_ofs )) {} Span::Span(Span parent, const Position& pos): m_ptr(SpanInner::alloc( parent, pos.filename, pos.line,pos.ofs, pos.line,pos.ofs )) { } Span::Span(const Span& x): m_ptr(x.m_ptr) { m_ptr->reference_count += 1; } Span::~Span() { if(m_ptr && m_ptr != &s_empty_span) { m_ptr->reference_count --; if( m_ptr->reference_count == 0 ) { delete m_ptr; } m_ptr = nullptr; } } namespace { void print_span_message(const Span& sp, ::std::function<void(::std::ostream&)> tag, ::std::function<void(::std::ostream&)> msg) { auto& sink = ::std::cerr; sink << sp->filename << ":" << sp->start_line << ": "; tag(sink); sink << ":"; msg(sink); sink << ::std::endl; for(auto parent = sp->parent_span; parent != Span(); parent = parent->parent_span) { sink << parent->filename << ":" << parent->start_line << ": note: From here" << ::std::endl; } } } void Span::bug(::std::function<void(::std::ostream&)> msg) const { print_span_message(*this, [](auto& os){os << "BUG";}, msg); #ifndef _WIN32 abort(); #else exit(1); #endif } void Span::error(ErrorType tag, ::std::function<void(::std::ostream&)> msg) const { print_span_message(*this, [&](auto& os){os << "error:" << tag;}, msg); #ifndef _WIN32 abort(); #else exit(1); #endif } void Span::warning(WarningType tag, ::std::function<void(::std::ostream&)> msg) const { print_span_message(*this, [&](auto& os){os << "warn:" << tag;}, msg); } void Span::note(::std::function<void(::std::ostream&)> msg) const { print_span_message(*this, [](auto& os){os << "note:";}, msg); } ::std::ostream& operator<<(::std::ostream& os, const Span& sp) { os << sp->filename << ":" << sp->start_line; return os; } <commit_msg>Flush error stream before die<commit_after>/* * MRustC - Rust Compiler * - By John Hodge (Mutabah/thePowersGang) * * span.cpp * - Spans and error handling */ #include <functional> #include <iostream> #include <span.hpp> #include <parse/lex.hpp> #include <common.hpp> SpanInner Span::s_empty_span; Span::Span(Span parent, RcString filename, unsigned int start_line, unsigned int start_ofs, unsigned int end_line, unsigned int end_ofs): m_ptr(SpanInner::alloc( parent, ::std::move(filename), start_line, start_ofs, end_line, end_ofs )) {} Span::Span(Span parent, const Position& pos): m_ptr(SpanInner::alloc( parent, pos.filename, pos.line,pos.ofs, pos.line,pos.ofs )) { } Span::Span(const Span& x): m_ptr(x.m_ptr) { m_ptr->reference_count += 1; } Span::~Span() { if(m_ptr && m_ptr != &s_empty_span) { m_ptr->reference_count --; if( m_ptr->reference_count == 0 ) { delete m_ptr; } m_ptr = nullptr; } } namespace { void print_span_message(const Span& sp, ::std::function<void(::std::ostream&)> tag, ::std::function<void(::std::ostream&)> msg) { auto& sink = ::std::cerr; sink << sp->filename << ":" << sp->start_line << ": "; tag(sink); sink << ":"; msg(sink); sink << ::std::endl; for(auto parent = sp->parent_span; parent != Span(); parent = parent->parent_span) { sink << parent->filename << ":" << parent->start_line << ": note: From here" << ::std::endl; } sink << ::std::flush; } } void Span::bug(::std::function<void(::std::ostream&)> msg) const { print_span_message(*this, [](auto& os){os << "BUG";}, msg); #ifndef _WIN32 abort(); #else exit(1); #endif } void Span::error(ErrorType tag, ::std::function<void(::std::ostream&)> msg) const { print_span_message(*this, [&](auto& os){os << "error:" << tag;}, msg); #ifndef _WIN32 abort(); #else exit(1); #endif } void Span::warning(WarningType tag, ::std::function<void(::std::ostream&)> msg) const { print_span_message(*this, [&](auto& os){os << "warn:" << tag;}, msg); } void Span::note(::std::function<void(::std::ostream&)> msg) const { print_span_message(*this, [](auto& os){os << "note:";}, msg); } ::std::ostream& operator<<(::std::ostream& os, const Span& sp) { os << sp->filename << ":" << sp->start_line; return os; } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////// // // Copyright 2016 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// #ifndef REALM_OS_SYNC_SESSION_HPP #define REALM_OS_SYNC_SESSION_HPP #include <realm/util/optional.hpp> #include <realm/version_id.hpp> #include "sync/sync_config.hpp" #include <mutex> #include <unordered_map> namespace realm { class SyncManager; class SyncUser; namespace _impl { class RealmCoordinator; struct SyncClient; namespace sync_session_states { struct WaitingForAccessToken; struct Active; struct Dying; struct Inactive; struct Error; } } namespace sync { class Session; } using SyncSessionTransactCallback = void(VersionID old_version, VersionID new_version); using SyncProgressNotifierCallback = void(uint64_t transferred_bytes, uint64_t transferrable_bytes); class SyncSession : public std::enable_shared_from_this<SyncSession> { public: enum class PublicState { WaitingForAccessToken, Active, Dying, Inactive, Error, }; PublicState state() const; bool is_in_error_state() const { return state() == PublicState::Error; } // The on-disk path of the Realm file backing the Realm this `SyncSession` represents. std::string const& path() const { return m_realm_path; } // Register a callback that will be called when all pending uploads have completed. // The callback is run asynchronously, and upon whatever thread the underlying sync client // chooses to run it on. The method returns immediately with true if the callback was // successfully registered, false otherwise. If the method returns false the callback will // never be run. // This method will return true if the completion handler was registered, either immediately // or placed in a queue. If it returns true the completion handler will always be called // at least once, except in the case where a logged-out session is never logged back in. bool wait_for_upload_completion(std::function<void(std::error_code)> callback); // Register a callback that will be called when all pending downloads have been completed. // Works the same way as `wait_for_upload_completion()`. bool wait_for_download_completion(std::function<void(std::error_code)> callback); enum class NotifierType { upload, download }; // Register a notifier that updates the app regarding progress. // // If `m_current_progress` is populated when this method is called, the notifier // will be called synchronously, to provide the caller with an initial assessment // of the state of synchronization. Otherwise, the progress notifier will be // registered, and only called once sync has begun providing progress data. // // If `is_streaming` is true, then the notifier will be called forever, and will // always contain the most up-to-date number of downloadable or uploadable bytes. // Otherwise, the number of downloaded or uploaded bytes will always be reported // relative to the number of downloadable or uploadable bytes at the point in time // when the notifier was registered. // // An integer representing a token is returned. This token can be used to manually // unregister the notifier. If the integer is 0, the notifier was not registered. // // Note that bindings should dispatch the callback onto a separate thread or queue // in order to avoid blocking the sync client. uint64_t register_progress_notifier(std::function<SyncProgressNotifierCallback>, NotifierType, bool is_streaming); // Unregister a previously registered notifier. If the token is invalid, // this method does nothing. void unregister_progress_notifier(uint64_t); // If possible, take the session and do anything necessary to make it `Active`. // Specifically: // If the sync session is currently `Dying`, ask it to stay alive instead. // If the sync session is currently `WaitingForAccessToken`, cancel any deferred close. // If the sync session is currently `Inactive`, recreate it. // Otherwise, a no-op. void revive_if_needed(); // Perform any actions needed in response to regaining network connectivity. // Specifically: // If the sync session is currently `WaitingForAccessToken`, make the binding ask the auth server for a token. // Otherwise, a no-op. void handle_reconnect(); // Give the `SyncSession` a new, valid token, and ask it to refresh the underlying session. // If the session can't accept a new token, this method does nothing. // Note that, if this is the first time the session will be given a token, `server_url` must // be set. void refresh_access_token(std::string access_token, util::Optional<std::string> server_url); // FIXME: we need an API to allow the binding to tell sync that the access token fetch failed // or was cancelled, and cannot be retried. // Give the `SyncSession` an administrator token, and ask it to immediately `bind()` the session. void bind_with_admin_token(std::string admin_token, std::string server_url); // Inform the sync session that it should close. void close(); // Inform the sync session that it should log out. void log_out(); void override_server(std::string address, int port); // An object representing the user who owns the Realm this `SyncSession` represents. std::shared_ptr<SyncUser> user() const { return m_config.user; } // A copy of the configuration object describing the Realm this `SyncSession` represents. const SyncConfig& config() const { return m_config; } // If the `SyncSession` has been configured, the full remote URL of the Realm // this `SyncSession` represents. util::Optional<std::string> full_realm_url() const { return m_server_url; } // Create an external reference to this session. The sync session attempts to remain active // as long as an external reference to the session exists. std::shared_ptr<SyncSession> external_reference(); // Return an existing external reference to this session, if one exists. Otherwise, returns `nullptr`. std::shared_ptr<SyncSession> existing_external_reference(); // Expose some internal functionality to other parts of the ObjectStore // without making it public to everyone class Internal { friend class _impl::RealmCoordinator; static void set_sync_transact_callback(SyncSession& session, std::function<SyncSessionTransactCallback> callback) { session.set_sync_transact_callback(std::move(callback)); } static void set_error_handler(SyncSession& session, std::function<SyncSessionErrorHandler> callback) { session.set_error_handler(std::move(callback)); } static void nonsync_transact_notify(SyncSession& session, VersionID::version_type version) { session.nonsync_transact_notify(version); } }; // Expose some internal functionality to testing code. struct OnlyForTesting { static void handle_error(SyncSession& session, SyncError error) { session.handle_error(std::move(error)); } static void handle_progress_update(SyncSession& session, uint64_t downloaded, uint64_t downloadable, uint64_t uploaded, uint64_t uploadable, bool is_fresh=true) { session.handle_progress_update(downloaded, downloadable, uploaded, uploadable, is_fresh); } static bool has_stale_progress(SyncSession& session) { return session.m_current_progress != none && !session.m_latest_progress_data_is_fresh; } static bool has_fresh_progress(SyncSession& session) { return session.m_latest_progress_data_is_fresh; } }; private: using std::enable_shared_from_this<SyncSession>::shared_from_this; struct State; friend struct _impl::sync_session_states::WaitingForAccessToken; friend struct _impl::sync_session_states::Active; friend struct _impl::sync_session_states::Dying; friend struct _impl::sync_session_states::Inactive; friend struct _impl::sync_session_states::Error; friend class realm::SyncManager; // Called by SyncManager { static std::shared_ptr<SyncSession> create(_impl::SyncClient& client, std::string realm_path, SyncConfig config) { struct MakeSharedEnabler : public SyncSession { MakeSharedEnabler(_impl::SyncClient& client, std::string realm_path, SyncConfig config) : SyncSession(client, std::move(realm_path), std::move(config)) {} }; return std::make_shared<MakeSharedEnabler>(client, std::move(realm_path), std::move(config)); } // } SyncSession(_impl::SyncClient&, std::string realm_path, SyncConfig); void handle_error(SyncError); enum class ShouldBackup { yes, no }; void update_error_and_mark_file_for_deletion(SyncError&, ShouldBackup); static std::string get_recovery_file_path(); void handle_progress_update(uint64_t, uint64_t, uint64_t, uint64_t, bool); void set_sync_transact_callback(std::function<SyncSessionTransactCallback>); void set_error_handler(std::function<SyncSessionErrorHandler>); void nonsync_transact_notify(VersionID::version_type); void advance_state(std::unique_lock<std::mutex>& lock, const State&); void create_sync_session(); void unregister(std::unique_lock<std::mutex>& lock); void did_drop_external_reference(); std::function<SyncSessionTransactCallback> m_sync_transact_callback; std::function<SyncSessionErrorHandler> m_error_handler; // How many bytes are uploadable or downloadable. struct Progress { uint64_t uploadable; uint64_t downloadable; uint64_t uploaded; uint64_t downloaded; }; // A PODS encapsulating some information for progress notifier callbacks a binding // can register upon this session. struct NotifierPackage { std::function<SyncProgressNotifierCallback> notifier; bool is_streaming; NotifierType direction; util::Optional<uint64_t> captured_transferrable; void update(const Progress&, bool); std::function<void()> create_invocation(const Progress&, bool&) const; }; // A counter used as a token to identify progress notifier callbacks registered on this session. uint64_t m_progress_notifier_token = 1; bool m_latest_progress_data_is_fresh; // Will be `none` until we've received the initial notification from sync. Note that this // happens only once ever during the lifetime of a given `SyncSession`, since these values are // expected to semi-monotonically increase, and a lower-bounds estimate is still useful in the // event more up-to-date information isn't yet available. FIXME: If we support transparent // client reset in the future, we might need to reset the progress state variables if the Realm // is rolled back. util::Optional<Progress> m_current_progress; std::unordered_map<uint64_t, NotifierPackage> m_notifiers; mutable std::mutex m_state_mutex; mutable std::mutex m_progress_notifier_mutex; const State* m_state = nullptr; size_t m_death_count = 0; SyncConfig m_config; std::string m_realm_path; _impl::SyncClient& m_client; // For storing wait-for-completion requests if the session isn't yet ready to handle them. struct CompletionWaitPackage { void(sync::Session::*waiter)(std::function<void(std::error_code)>); std::function<void(std::error_code)> callback; }; std::vector<CompletionWaitPackage> m_completion_wait_packages; struct ServerOverride { std::string address; int port; }; util::Optional<ServerOverride> m_server_override; // The underlying `Session` object that is owned and managed by this `SyncSession`. // The session is first created when the `SyncSession` is moved out of its initial `inactive` state. // The session might be destroyed if the `SyncSession` becomes inactive again (for example, if the // user owning the session logs out). It might be created anew if the session is revived (if a // logged-out user logs back in, the object store sync code will revive their sessions). std::unique_ptr<sync::Session> m_session; // Whether or not the session object in `m_session` has been `bind()`ed before. // This determines how the `SyncSession` behaves when refreshing tokens. bool m_session_has_been_bound; util::Optional<int_fast64_t> m_deferred_commit_notification; bool m_deferred_close = false; // The fully-resolved URL of this Realm, including the server and the path. util::Optional<std::string> m_server_url; class ExternalReference; std::weak_ptr<ExternalReference> m_external_reference; }; } #endif // REALM_OS_SYNC_SESSION_HPP <commit_msg>Add a comment explaining the new API.<commit_after>//////////////////////////////////////////////////////////////////////////// // // Copyright 2016 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// #ifndef REALM_OS_SYNC_SESSION_HPP #define REALM_OS_SYNC_SESSION_HPP #include <realm/util/optional.hpp> #include <realm/version_id.hpp> #include "sync/sync_config.hpp" #include <mutex> #include <unordered_map> namespace realm { class SyncManager; class SyncUser; namespace _impl { class RealmCoordinator; struct SyncClient; namespace sync_session_states { struct WaitingForAccessToken; struct Active; struct Dying; struct Inactive; struct Error; } } namespace sync { class Session; } using SyncSessionTransactCallback = void(VersionID old_version, VersionID new_version); using SyncProgressNotifierCallback = void(uint64_t transferred_bytes, uint64_t transferrable_bytes); class SyncSession : public std::enable_shared_from_this<SyncSession> { public: enum class PublicState { WaitingForAccessToken, Active, Dying, Inactive, Error, }; PublicState state() const; bool is_in_error_state() const { return state() == PublicState::Error; } // The on-disk path of the Realm file backing the Realm this `SyncSession` represents. std::string const& path() const { return m_realm_path; } // Register a callback that will be called when all pending uploads have completed. // The callback is run asynchronously, and upon whatever thread the underlying sync client // chooses to run it on. The method returns immediately with true if the callback was // successfully registered, false otherwise. If the method returns false the callback will // never be run. // This method will return true if the completion handler was registered, either immediately // or placed in a queue. If it returns true the completion handler will always be called // at least once, except in the case where a logged-out session is never logged back in. bool wait_for_upload_completion(std::function<void(std::error_code)> callback); // Register a callback that will be called when all pending downloads have been completed. // Works the same way as `wait_for_upload_completion()`. bool wait_for_download_completion(std::function<void(std::error_code)> callback); enum class NotifierType { upload, download }; // Register a notifier that updates the app regarding progress. // // If `m_current_progress` is populated when this method is called, the notifier // will be called synchronously, to provide the caller with an initial assessment // of the state of synchronization. Otherwise, the progress notifier will be // registered, and only called once sync has begun providing progress data. // // If `is_streaming` is true, then the notifier will be called forever, and will // always contain the most up-to-date number of downloadable or uploadable bytes. // Otherwise, the number of downloaded or uploaded bytes will always be reported // relative to the number of downloadable or uploadable bytes at the point in time // when the notifier was registered. // // An integer representing a token is returned. This token can be used to manually // unregister the notifier. If the integer is 0, the notifier was not registered. // // Note that bindings should dispatch the callback onto a separate thread or queue // in order to avoid blocking the sync client. uint64_t register_progress_notifier(std::function<SyncProgressNotifierCallback>, NotifierType, bool is_streaming); // Unregister a previously registered notifier. If the token is invalid, // this method does nothing. void unregister_progress_notifier(uint64_t); // If possible, take the session and do anything necessary to make it `Active`. // Specifically: // If the sync session is currently `Dying`, ask it to stay alive instead. // If the sync session is currently `WaitingForAccessToken`, cancel any deferred close. // If the sync session is currently `Inactive`, recreate it. // Otherwise, a no-op. void revive_if_needed(); // Perform any actions needed in response to regaining network connectivity. // Specifically: // If the sync session is currently `WaitingForAccessToken`, make the binding ask the auth server for a token. // Otherwise, a no-op. void handle_reconnect(); // Give the `SyncSession` a new, valid token, and ask it to refresh the underlying session. // If the session can't accept a new token, this method does nothing. // Note that, if this is the first time the session will be given a token, `server_url` must // be set. void refresh_access_token(std::string access_token, util::Optional<std::string> server_url); // FIXME: we need an API to allow the binding to tell sync that the access token fetch failed // or was cancelled, and cannot be retried. // Give the `SyncSession` an administrator token, and ask it to immediately `bind()` the session. void bind_with_admin_token(std::string admin_token, std::string server_url); // Inform the sync session that it should close. void close(); // Inform the sync session that it should log out. void log_out(); // Override the address and port of the server that this `SyncSession` is connected to. If the // session is already connected, it will disconnect and then reconnect to the specified address. // If it's not already connected, future connection attempts will be to the specified address. // // NOTE: This is intended for use only in very specific circumstances. Please check with the // object store team before using it. void override_server(std::string address, int port); // An object representing the user who owns the Realm this `SyncSession` represents. std::shared_ptr<SyncUser> user() const { return m_config.user; } // A copy of the configuration object describing the Realm this `SyncSession` represents. const SyncConfig& config() const { return m_config; } // If the `SyncSession` has been configured, the full remote URL of the Realm // this `SyncSession` represents. util::Optional<std::string> full_realm_url() const { return m_server_url; } // Create an external reference to this session. The sync session attempts to remain active // as long as an external reference to the session exists. std::shared_ptr<SyncSession> external_reference(); // Return an existing external reference to this session, if one exists. Otherwise, returns `nullptr`. std::shared_ptr<SyncSession> existing_external_reference(); // Expose some internal functionality to other parts of the ObjectStore // without making it public to everyone class Internal { friend class _impl::RealmCoordinator; static void set_sync_transact_callback(SyncSession& session, std::function<SyncSessionTransactCallback> callback) { session.set_sync_transact_callback(std::move(callback)); } static void set_error_handler(SyncSession& session, std::function<SyncSessionErrorHandler> callback) { session.set_error_handler(std::move(callback)); } static void nonsync_transact_notify(SyncSession& session, VersionID::version_type version) { session.nonsync_transact_notify(version); } }; // Expose some internal functionality to testing code. struct OnlyForTesting { static void handle_error(SyncSession& session, SyncError error) { session.handle_error(std::move(error)); } static void handle_progress_update(SyncSession& session, uint64_t downloaded, uint64_t downloadable, uint64_t uploaded, uint64_t uploadable, bool is_fresh=true) { session.handle_progress_update(downloaded, downloadable, uploaded, uploadable, is_fresh); } static bool has_stale_progress(SyncSession& session) { return session.m_current_progress != none && !session.m_latest_progress_data_is_fresh; } static bool has_fresh_progress(SyncSession& session) { return session.m_latest_progress_data_is_fresh; } }; private: using std::enable_shared_from_this<SyncSession>::shared_from_this; struct State; friend struct _impl::sync_session_states::WaitingForAccessToken; friend struct _impl::sync_session_states::Active; friend struct _impl::sync_session_states::Dying; friend struct _impl::sync_session_states::Inactive; friend struct _impl::sync_session_states::Error; friend class realm::SyncManager; // Called by SyncManager { static std::shared_ptr<SyncSession> create(_impl::SyncClient& client, std::string realm_path, SyncConfig config) { struct MakeSharedEnabler : public SyncSession { MakeSharedEnabler(_impl::SyncClient& client, std::string realm_path, SyncConfig config) : SyncSession(client, std::move(realm_path), std::move(config)) {} }; return std::make_shared<MakeSharedEnabler>(client, std::move(realm_path), std::move(config)); } // } SyncSession(_impl::SyncClient&, std::string realm_path, SyncConfig); void handle_error(SyncError); enum class ShouldBackup { yes, no }; void update_error_and_mark_file_for_deletion(SyncError&, ShouldBackup); static std::string get_recovery_file_path(); void handle_progress_update(uint64_t, uint64_t, uint64_t, uint64_t, bool); void set_sync_transact_callback(std::function<SyncSessionTransactCallback>); void set_error_handler(std::function<SyncSessionErrorHandler>); void nonsync_transact_notify(VersionID::version_type); void advance_state(std::unique_lock<std::mutex>& lock, const State&); void create_sync_session(); void unregister(std::unique_lock<std::mutex>& lock); void did_drop_external_reference(); std::function<SyncSessionTransactCallback> m_sync_transact_callback; std::function<SyncSessionErrorHandler> m_error_handler; // How many bytes are uploadable or downloadable. struct Progress { uint64_t uploadable; uint64_t downloadable; uint64_t uploaded; uint64_t downloaded; }; // A PODS encapsulating some information for progress notifier callbacks a binding // can register upon this session. struct NotifierPackage { std::function<SyncProgressNotifierCallback> notifier; bool is_streaming; NotifierType direction; util::Optional<uint64_t> captured_transferrable; void update(const Progress&, bool); std::function<void()> create_invocation(const Progress&, bool&) const; }; // A counter used as a token to identify progress notifier callbacks registered on this session. uint64_t m_progress_notifier_token = 1; bool m_latest_progress_data_is_fresh; // Will be `none` until we've received the initial notification from sync. Note that this // happens only once ever during the lifetime of a given `SyncSession`, since these values are // expected to semi-monotonically increase, and a lower-bounds estimate is still useful in the // event more up-to-date information isn't yet available. FIXME: If we support transparent // client reset in the future, we might need to reset the progress state variables if the Realm // is rolled back. util::Optional<Progress> m_current_progress; std::unordered_map<uint64_t, NotifierPackage> m_notifiers; mutable std::mutex m_state_mutex; mutable std::mutex m_progress_notifier_mutex; const State* m_state = nullptr; size_t m_death_count = 0; SyncConfig m_config; std::string m_realm_path; _impl::SyncClient& m_client; // For storing wait-for-completion requests if the session isn't yet ready to handle them. struct CompletionWaitPackage { void(sync::Session::*waiter)(std::function<void(std::error_code)>); std::function<void(std::error_code)> callback; }; std::vector<CompletionWaitPackage> m_completion_wait_packages; struct ServerOverride { std::string address; int port; }; util::Optional<ServerOverride> m_server_override; // The underlying `Session` object that is owned and managed by this `SyncSession`. // The session is first created when the `SyncSession` is moved out of its initial `inactive` state. // The session might be destroyed if the `SyncSession` becomes inactive again (for example, if the // user owning the session logs out). It might be created anew if the session is revived (if a // logged-out user logs back in, the object store sync code will revive their sessions). std::unique_ptr<sync::Session> m_session; // Whether or not the session object in `m_session` has been `bind()`ed before. // This determines how the `SyncSession` behaves when refreshing tokens. bool m_session_has_been_bound; util::Optional<int_fast64_t> m_deferred_commit_notification; bool m_deferred_close = false; // The fully-resolved URL of this Realm, including the server and the path. util::Optional<std::string> m_server_url; class ExternalReference; std::weak_ptr<ExternalReference> m_external_reference; }; } #endif // REALM_OS_SYNC_SESSION_HPP <|endoftext|>
<commit_before>// ---------------------------------------------------------------------------- #include "cmsis_device.h" #include "define.h" #include "Timer.h" #include "util.h" #include "SerialHardware.h" #include "SPI.h" int main() { // SPI spi(SPI1, PINREMAP); // spi.start(SPI_BRRDIV16); // spi.softPin(GPIOA, P09); // spi.setDataF(SPI_DATA16); //GPIO_Config(GPIOB, 0xFFFF, MODE_OUT_50MHZ); //GPIOB->BSRR |= 0xFFFF; Serial2.Init(921600); while (1) { // spi.chipSelect(LOW); // spi.send16Byte(0x0F01); // spi.chipSelect(HIGH); // delayMillis(100); // // spi.chipSelect(LOW); // spi.send16Byte(0x0F00); // spi.chipSelect(HIGH); // // GPIOB->BRR |= 0xFFFF; // delayMillis(500); // GPIOB->BSRR |= 0xFFFF; // delayMillis(500); } } <commit_msg>nothing new<commit_after>// ---------------------------------------------------------------------------- #include "cmsis_device.h" #include "define.h" #include "Timer.h" #include "util.h" #include "SerialHardware.h" #include "SPI.h" int main() { // SPI spi(SPI1, PINREMAP); // spi.start(SPI_BRRDIV16); // spi.softPin(GPIOA, P09); // spi.setDataF(SPI_DATA16); GPIO_Config(GPIOB, 0xFFFF, MODE_OUT_50MHZ); GPIOB->BSRR |= 0xFFFF; // Serial2.Init(921600); while (1) { // spi.chipSelect(LOW); // spi.send16Byte(0x0F01); // spi.chipSelect(HIGH); // delayMillis(100); // // spi.chipSelect(LOW); // spi.send16Byte(0x0F00); // spi.chipSelect(HIGH); // GPIOB->BRR |= 0xFFFF; delayMillis(500); GPIOB->BSRR |= 0xFFFF; delayMillis(500); } } <|endoftext|>
<commit_before> // G910_SAMPLE.cpp : Defines the class behaviors for the application. // #pragma comment(lib, "LogitechLEDLib.lib") #include <stdio.h> #include <stdlib.h> #include "LogitechLEDLib.h" #include <iostream> using namespace std; int main() { LogiLedInit(); int red = 100; int green = 0; int blue = 0; int major, minor, build = 0; //show sdk version if(!LogiLedGetSdkVersion(&major, &minor, & build)) { cout<<L"Could not retrieve SDK version"<<endl; } else { printf("SDK VERSION:%d.%d.%d \n",major,minor,build); } //set the lighting of device LogiLedSetLighting(red, green, blue); printf("set color red=%d, green=%d, blue=%d \n",red,green,blue); getchar(); LogiLedShutdown(); }<commit_msg>Update LedSetLighting.cpp<commit_after> // G910_SAMPLE.cpp : Defines the class behaviors for the application. // #pragma comment(lib, "LogitechLEDLib.lib") #include <stdio.h> #include <stdlib.h> #include "LogitechLEDLib.h" #include <iostream> using namespace std; int main() { LogiLedInit(); int red = 100; int green = 0; int blue = 0; int major, minor, build = 0; //show sdk version if(!LogiLedGetSdkVersion(&major, &minor, & build)) { cout<<L"Could not retrieve SDK version"<<endl; } else { printf("SDK VERSION:%d.%d.%d \n",major,minor,build); } //set the lighting of device LogiLedSetLighting(red, green, blue); printf("set color red=%d, green=%d, blue=%d \n",red,green,blue); getchar(); LogiLedShutdown(); } <|endoftext|>
<commit_before>#include <pthread.h> #include <string.h> #include <string> #include <stdint.h> #include <unistd.h> #include <re.h> #include <vector> #include "timer.hpp" #include "uamanager.hpp" #include "stats_displayer.hpp" #include "useragent.hpp" #include "stack.hpp" #include "logger.hpp" #include "csv.h" #include "docopt.h" static std::vector<UserAgent*> ues; StatsDisplayer* stats_displayer; class CallScheduler; class Cleanup; static CallScheduler* call_scheduler; static Cleanup* cleanup_task; class InitialRegistrar : public RepeatingTimer { public: InitialRegistrar(uint rps) : RepeatingTimer(10), _actual_ues_registered(0), _registers_per_sec(rps) {}; bool act(); bool everything_registered() { return _actual_ues_registered == ues.size(); } private: uint64_t _actual_ues_registered; int _registers_per_sec; }; class CallScheduler : public RepeatingTimer { public: CallScheduler(int cps, uint64_t max_calls) : RepeatingTimer(10), _actual_calls(0), _calls_per_sec(cps), _max_calls(max_calls) {}; bool act(); private: uint64_t _actual_calls; int _calls_per_sec; uint64_t _max_calls; }; class Cleanup : public RepeatingTimer { public: Cleanup() : RepeatingTimer(1000) {}; bool act(); }; bool Cleanup::act() { static int times = 0; printf("Cleanup running\n"); if (times == 1) { for (UserAgent* a : ues) { a->unregister(); } } else if (times == 2) { close_sip_stacks(false); free_sip_stacks(); } else if (times == 30) { re_cancel(); } times++; return true; } bool InitialRegistrar::act() { if (_actual_ues_registered == ues.size()) { call_scheduler->start(); return false; } uint64_t expected_ues_registered = seconds_since_start() * _registers_per_sec; expected_ues_registered = std::min(expected_ues_registered, ues.size()); int ues_to_register = expected_ues_registered - _actual_ues_registered; for (int ii = 0; ii < ues_to_register; ii++) { UserAgent* a = ues[_actual_ues_registered]; a->register_ue(); _actual_ues_registered++; } return true; } bool CallScheduler::act() { uint64_t expected_calls = seconds_since_start() * _calls_per_sec; int calls_to_make = expected_calls - _actual_calls; for (int ii = 0; ii < calls_to_make; ii++) { UserAgent* caller = UAManager::get_instance()->get_ua_free_for_call(); UserAgent* callee = UAManager::get_instance()->get_ua_free_for_call(); if (caller && callee) { caller->call(callee->uri()); _actual_calls++; } else { printf("Not enough registered UEs to make call\n"); UAManager::get_instance()->mark_ua_not_in_call(caller); UAManager::get_instance()->mark_ua_not_in_call(callee); break; } } if (_actual_calls < _max_calls) { return true; } else { cleanup_task->start(); return false; } } int main(int argc, char *argv[]) { DocoptArgs args = docopt(argc, argv, /* help */ 1, /* version */ "0.01"); if (args.target == NULL) { printf("--target option is mandatory\n"); printf("%s\n", help_message); exit(1); } int rps = std::atoi(args.rps); int cps = std::atoi(args.cps); int max_calls = std::atoi(args.max_calls); int err; /* errno return values */ l.set_cflog_file("./cflog.log"); io::CSVReader<3> in(args.users_file); std::string sip_uri, username, password; while (in.read_row(sip_uri, username, password)) { UserAgent* a = new UserAgent(args.target, sip_uri, username, password); ues.push_back(a); } printf("Registering %u user agents against registrar %s\n", ues.size(), args.target); /* initialize libre state */ err = libre_init(); fd_setsize(50000); if (err) { re_fprintf(stderr, "re init failed: %s\n", strerror(err)); } InitialRegistrar registering_timer(rps); call_scheduler = new CallScheduler(cps, max_calls); stats_displayer = new StatsDisplayer(); cleanup_task = new Cleanup(); stats_displayer->start(); registering_timer.start(); create_sip_stacks(75); re_main(NULL); printf("End of loop\n"); libre_close(); UAManager::get_instance()->clear(); for (UserAgent* a : ues) { delete a; } /* check for memory leaks */ tmr_debug(); mem_debug(); delete stats_displayer; return 0; } <commit_msg>Delay before closing SIP stacks to avoid shutdown crashes<commit_after>#include <pthread.h> #include <string.h> #include <string> #include <stdint.h> #include <unistd.h> #include <re.h> #include <vector> #include "timer.hpp" #include "uamanager.hpp" #include "stats_displayer.hpp" #include "useragent.hpp" #include "stack.hpp" #include "logger.hpp" #include "csv.h" #include "docopt.h" static std::vector<UserAgent*> ues; StatsDisplayer* stats_displayer; class CallScheduler; class Cleanup; static CallScheduler* call_scheduler; static Cleanup* cleanup_task; class InitialRegistrar : public RepeatingTimer { public: InitialRegistrar(uint rps) : RepeatingTimer(10), _actual_ues_registered(0), _registers_per_sec(rps) {}; bool act(); bool everything_registered() { return _actual_ues_registered == ues.size(); } private: uint64_t _actual_ues_registered; int _registers_per_sec; }; class CallScheduler : public RepeatingTimer { public: CallScheduler(int cps, uint64_t max_calls) : RepeatingTimer(10), _actual_calls(0), _calls_per_sec(cps), _max_calls(max_calls) {}; bool act(); private: uint64_t _actual_calls; int _calls_per_sec; uint64_t _max_calls; }; class Cleanup : public RepeatingTimer { public: Cleanup() : RepeatingTimer(1000) {}; bool act(); }; bool Cleanup::act() { static int times = 0; printf("Cleanup running\n"); if (times == 1) { for (UserAgent* a : ues) { a->unregister(); } } else if (times == 12) { close_sip_stacks(false); free_sip_stacks(); } else if (times == 30) { re_cancel(); } times++; return true; } bool InitialRegistrar::act() { if (_actual_ues_registered == ues.size()) { call_scheduler->start(); return false; } uint64_t expected_ues_registered = seconds_since_start() * _registers_per_sec; expected_ues_registered = std::min(expected_ues_registered, ues.size()); int ues_to_register = expected_ues_registered - _actual_ues_registered; for (int ii = 0; ii < ues_to_register; ii++) { UserAgent* a = ues[_actual_ues_registered]; a->register_ue(); _actual_ues_registered++; } return true; } bool CallScheduler::act() { uint64_t expected_calls = seconds_since_start() * _calls_per_sec; int calls_to_make = expected_calls - _actual_calls; for (int ii = 0; ii < calls_to_make; ii++) { UserAgent* caller = UAManager::get_instance()->get_ua_free_for_call(); UserAgent* callee = UAManager::get_instance()->get_ua_free_for_call(); if (caller && callee) { caller->call(callee->uri()); _actual_calls++; } else { printf("Not enough registered UEs to make call\n"); UAManager::get_instance()->mark_ua_not_in_call(caller); UAManager::get_instance()->mark_ua_not_in_call(callee); break; } } if (_actual_calls < _max_calls) { return true; } else { cleanup_task->start(); return false; } } int main(int argc, char *argv[]) { DocoptArgs args = docopt(argc, argv, /* help */ 1, /* version */ "0.01"); if (args.target == NULL) { printf("--target option is mandatory\n"); printf("%s\n", help_message); exit(1); } int rps = std::atoi(args.rps); int cps = std::atoi(args.cps); int max_calls = std::atoi(args.max_calls); int err; /* errno return values */ l.set_cflog_file("./cflog.log"); io::CSVReader<3> in(args.users_file); std::string sip_uri, username, password; while (in.read_row(sip_uri, username, password)) { UserAgent* a = new UserAgent(args.target, sip_uri, username, password); ues.push_back(a); } printf("Registering %u user agents against registrar %s\n", ues.size(), args.target); /* initialize libre state */ err = libre_init(); fd_setsize(50000); if (err) { re_fprintf(stderr, "re init failed: %s\n", strerror(err)); } InitialRegistrar registering_timer(rps); call_scheduler = new CallScheduler(cps, max_calls); stats_displayer = new StatsDisplayer(); cleanup_task = new Cleanup(); stats_displayer->start(); registering_timer.start(); create_sip_stacks(75); re_main(NULL); printf("End of loop\n"); libre_close(); UAManager::get_instance()->clear(); for (UserAgent* a : ues) { delete a; } /* check for memory leaks */ tmr_debug(); mem_debug(); delete stats_displayer; return 0; } <|endoftext|>
<commit_before>/* * Copyright (C) 2017 deipi.com LLC and contributors. 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 "stats.h" Stats::Pos::Pos() : minute(0), second(0) { } void Stats::Counter::Element::clear() { cnt = 0; total = 0; } void Stats::Counter::Element::merge(const Element& other) { cnt += other.cnt; total += other.total; } void Stats::Counter::Element::add(uint64_t duration) { ++cnt; total += duration; } Stats::Counter::Counter() { clear_stats_min(0, SLOT_TIME_MINUTE - 1); clear_stats_sec(0, SLOT_TIME_SECOND - 1); } void Stats::Counter::clear_stats_min(uint16_t start, uint16_t end) { for (auto i = start; i <= end; ++i) { min[i].clear(); } } void Stats::Counter::clear_stats_sec(uint8_t start, uint8_t end) { for (auto i = start; i <= end; ++i) { sec[i].clear(); } } void Stats::Counter::merge_stats_min(uint16_t start, uint16_t end, Stats::Counter::Element& element) { for (auto i = start; i <= end; ++i) { element.merge(min[i]); } } void Stats::Counter::merge_stats_sec(uint8_t start, uint8_t end, Element& element) { for (auto i = start; i <= end; ++i) { element.merge(sec[i]); } } Stats::Pos::Pos(std::chrono::time_point<std::chrono::system_clock> current) { time_t epoch = std::chrono::system_clock::to_time_t(current); struct tm *timeinfo = localtime(&epoch); timeinfo->tm_hour = 0; timeinfo->tm_min = 0; timeinfo->tm_sec = 0; auto delta = epoch - mktime(timeinfo); minute = delta / SLOT_TIME_SECOND; second = delta % SLOT_TIME_SECOND; } Stats& Stats::cnt() { static Stats stats_cnt; return stats_cnt; } Stats::Stats() : current(std::chrono::system_clock::now()), current_pos(current) { } Stats::Stats(Stats& other) : current(std::chrono::system_clock::now()) { std::lock_guard<std::mutex> lk(other.mtx); current = other.current; current_pos = other.current_pos; counters = other.counters; } void Stats::update_pos_time() { auto b_time_second = current_pos.second; auto b_time_minute = current_pos.minute; auto now = std::chrono::system_clock::now(); auto t_elapsed = std::chrono::duration_cast<std::chrono::seconds>(now - current).count(); if (t_elapsed >= SLOT_TIME_SECOND) { clear_stats_sec(0, SLOT_TIME_SECOND - 1); current_pos.minute += t_elapsed / SLOT_TIME_SECOND; current_pos.second = t_elapsed % SLOT_TIME_SECOND; } else { current_pos.second += t_elapsed; if (current_pos.second >= SLOT_TIME_SECOND) { clear_stats_sec(b_time_second + 1, SLOT_TIME_SECOND - 1); clear_stats_sec(0, current_pos.second % SLOT_TIME_SECOND); current_pos.minute += current_pos.second / SLOT_TIME_SECOND; current_pos.second = t_elapsed % SLOT_TIME_SECOND; } else { clear_stats_sec(b_time_second + 1, current_pos.second); } } current = now; if (current_pos.minute >= SLOT_TIME_MINUTE) { clear_stats_min(b_time_minute + 1, SLOT_TIME_MINUTE - 1); clear_stats_min(0, current_pos.minute % SLOT_TIME_MINUTE); current_pos.minute = current_pos.minute % SLOT_TIME_MINUTE; } else { clear_stats_min(b_time_minute + 1, current_pos.minute); } ASSERT(current_pos.second < SLOT_TIME_SECOND); ASSERT(current_pos.minute < SLOT_TIME_MINUTE); } void Stats::clear_stats_min(uint16_t start, uint16_t end) { for (auto& counter : counters) { counter.second.clear_stats_min(start, end); } } void Stats::clear_stats_sec(uint8_t start, uint8_t end) { for (auto& counter : counters) { counter.second.clear_stats_sec(start, end); } } void Stats::merge_stats_min(uint16_t start, uint16_t end, std::unordered_map<std::string, Stats::Counter::Element>& cnt) { for (auto& counter : counters) { auto& element = cnt[counter.first]; counter.second.merge_stats_min(start, end, element); } } void Stats::merge_stats_sec(uint8_t start, uint8_t end, std::unordered_map<std::string, Stats::Counter::Element>& cnt) { for (auto& counter : counters) { auto& element = cnt[counter.first]; counter.second.merge_stats_sec(start, end, element); } } void Stats::add(Counter& counter, uint64_t duration) { std::lock_guard<std::mutex> lk(mtx); update_pos_time(); counter.min[current_pos.minute].add(duration); counter.sec[current_pos.second].add(duration); } void Stats::add(const std::string& counter, uint64_t duration) { auto& stats_cnt = cnt(); stats_cnt.add(stats_cnt.counters[counter], duration); } <commit_msg>Stats: inlined<commit_after>/* * Copyright (C) 2017 deipi.com LLC and contributors. 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 "stats.h" Stats::Pos::Pos() : minute(0), second(0) { } inline void Stats::Counter::Element::clear() { cnt = 0; total = 0; } inline void Stats::Counter::Element::merge(const Element& other) { cnt += other.cnt; total += other.total; } inline void Stats::Counter::Element::add(uint64_t duration) { ++cnt; total += duration; } inline Stats::Counter::Counter() { clear_stats_min(0, SLOT_TIME_MINUTE - 1); clear_stats_sec(0, SLOT_TIME_SECOND - 1); } inline void Stats::Counter::clear_stats_min(uint16_t start, uint16_t end) { for (auto i = start; i <= end; ++i) { min[i].clear(); } } inline void Stats::Counter::clear_stats_sec(uint8_t start, uint8_t end) { for (auto i = start; i <= end; ++i) { sec[i].clear(); } } inline void Stats::Counter::merge_stats_min(uint16_t start, uint16_t end, Stats::Counter::Element& element) { for (auto i = start; i <= end; ++i) { element.merge(min[i]); } } inline void Stats::Counter::merge_stats_sec(uint8_t start, uint8_t end, Element& element) { for (auto i = start; i <= end; ++i) { element.merge(sec[i]); } } Stats::Pos::Pos(std::chrono::time_point<std::chrono::system_clock> current) { time_t epoch = std::chrono::system_clock::to_time_t(current); struct tm *timeinfo = localtime(&epoch); timeinfo->tm_hour = 0; timeinfo->tm_min = 0; timeinfo->tm_sec = 0; auto delta = epoch - mktime(timeinfo); minute = delta / SLOT_TIME_SECOND; second = delta % SLOT_TIME_SECOND; } inline Stats& Stats::cnt() { static Stats stats_cnt; return stats_cnt; } Stats::Stats() : current(std::chrono::system_clock::now()), current_pos(current) { } Stats::Stats(Stats& other) : current(std::chrono::system_clock::now()) { std::lock_guard<std::mutex> lk(other.mtx); current = other.current; current_pos = other.current_pos; counters = other.counters; } inline void Stats::update_pos_time() { auto b_time_second = current_pos.second; auto b_time_minute = current_pos.minute; auto now = std::chrono::system_clock::now(); auto t_elapsed = std::chrono::duration_cast<std::chrono::seconds>(now - current).count(); if (t_elapsed >= SLOT_TIME_SECOND) { clear_stats_sec(0, SLOT_TIME_SECOND - 1); current_pos.minute += t_elapsed / SLOT_TIME_SECOND; current_pos.second = t_elapsed % SLOT_TIME_SECOND; } else { current_pos.second += t_elapsed; if (current_pos.second >= SLOT_TIME_SECOND) { clear_stats_sec(b_time_second + 1, SLOT_TIME_SECOND - 1); clear_stats_sec(0, current_pos.second % SLOT_TIME_SECOND); current_pos.minute += current_pos.second / SLOT_TIME_SECOND; current_pos.second = t_elapsed % SLOT_TIME_SECOND; } else { clear_stats_sec(b_time_second + 1, current_pos.second); } } current = now; if (current_pos.minute >= SLOT_TIME_MINUTE) { clear_stats_min(b_time_minute + 1, SLOT_TIME_MINUTE - 1); clear_stats_min(0, current_pos.minute % SLOT_TIME_MINUTE); current_pos.minute = current_pos.minute % SLOT_TIME_MINUTE; } else { clear_stats_min(b_time_minute + 1, current_pos.minute); } ASSERT(current_pos.second < SLOT_TIME_SECOND); ASSERT(current_pos.minute < SLOT_TIME_MINUTE); } inline void Stats::clear_stats_min(uint16_t start, uint16_t end) { for (auto& counter : counters) { counter.second.clear_stats_min(start, end); } } inline void Stats::clear_stats_sec(uint8_t start, uint8_t end) { for (auto& counter : counters) { counter.second.clear_stats_sec(start, end); } } void Stats::merge_stats_min(uint16_t start, uint16_t end, std::unordered_map<std::string, Stats::Counter::Element>& cnt) { for (auto& counter : counters) { auto& element = cnt[counter.first]; counter.second.merge_stats_min(start, end, element); } } void Stats::merge_stats_sec(uint8_t start, uint8_t end, std::unordered_map<std::string, Stats::Counter::Element>& cnt) { for (auto& counter : counters) { auto& element = cnt[counter.first]; counter.second.merge_stats_sec(start, end, element); } } inline void Stats::add(Counter& counter, uint64_t duration) { std::lock_guard<std::mutex> lk(mtx); update_pos_time(); counter.min[current_pos.minute].add(duration); counter.sec[current_pos.second].add(duration); } void Stats::add(const std::string& counter, uint64_t duration) { auto& stats_cnt = cnt(); stats_cnt.add(stats_cnt.counters[counter], duration); } <|endoftext|>
<commit_before>#include "thread/thread.hpp" #include "thread/mutex.hpp" #include <atomic> #include <thread> #include <mutex> #include <unordered_map> #include <boost/lockfree/queue.hpp> #include <boost/context/all.hpp> #include <boost/version.hpp> #include <unistd.h> #include <cassert> #include <cstdlib> #include <sys/types.h> #include <sys/sysctl.h> namespace { inline unsigned int rdtsc() { unsigned int lo, hi; __asm__ __volatile__("rdtsc" : "=a"(lo), "=d"(hi)); return lo; } unsigned get_num_cpus() { #if 0 #if (defined(linux) || defined(__linux) || defined(__linux__) || defined(__GNU__) || defined(__GLIBC__)) && !defined(_CRAYC) #elif defined(_WIN32) || defined(__WIN32__) || defined(WIN32) SYSTEM_INFO sysinfo; GetSystemInfo(&sysinfo); return sysinfo.dwNumberOfProcessors; #elif defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) // BSD-likeint mib[4]; unsigned numCPU; int mib[4]; size_t len = sizeof(numCPU); /* set the mib for hw.ncpu */ mib[0] = CTL_HW; mib[1] = HW_AVAILCPU; // alternatively, try HW_NCPU; /* get the number of CPUs from the system */ sysctl(mib, 2, &numCPU, &len, NULL, 0); if (numCPU < 1) { mib[1] = HW_NCPU; sysctl(mib, 2, &numCPU, &len, NULL, 0); if (numCPU < 1) { numCPU = 1; } } return numCPU; #else // fallback return std::thread::hardware_concurrency(); #endif #endif return std::thread::hardware_concurrency(); } constexpr size_t STACK_SIZE = 8192 * 1024; struct stack_allocator { static boost::lockfree::queue<char*, boost::lockfree::fixed_sized<true>, boost::lockfree::capacity<1024> > stacks; static void* alloc() { char* res; if (!stacks.pop(res)) res = reinterpret_cast<char*>(std::calloc(STACK_SIZE, sizeof(char))); if (!res) throw std::bad_alloc(); return res + STACK_SIZE; } static void free(void* stack) { char* s = reinterpret_cast<char*>(stack); s -= STACK_SIZE; if (!stacks.push(s)) std::free(s); } }; decltype(stack_allocator::stacks) stack_allocator::stacks; void* alloc_stack() { return stack_allocator::alloc(); } void free_stack(void* vp) { return stack_allocator::free(vp); } std::atomic<bool> initialized(false); std::mutex init_mutex; struct processor; void scheduler(processor &p); struct processor { boost::lockfree::queue<crossbow::impl::thread_impl*, boost::lockfree::fixed_sized<true>, boost::lockfree::capacity<1024> > queue; processor() { auto t = std::thread([this]() { scheduler(*this); }); t.detach(); } processor(bool main) {} }; processor** processors; volatile unsigned num_processors; crossbow::busy_mutex map_mutex; std::unordered_map<std::thread::id, processor*> this_thread_map; processor &this_processor() { std::lock_guard<decltype(map_mutex)> _(map_mutex); return *this_thread_map.at(std::this_thread::get_id()); } inline void default_init() { if (!initialized.load()) { std::lock_guard<std::mutex> _(init_mutex); if (!initialized.load()) { auto numCPU = get_num_cpus(); num_processors = std::max(numCPU, 1u); processors = new processor*[num_processors]; for (unsigned i = 1; i < num_processors; ++i) { processors[i] = new processor(); } processors[0] = new processor(true); { std::lock_guard<decltype(map_mutex)> _(map_mutex); this_thread_map.insert(std::make_pair(std::this_thread::get_id(), processors[num_processors - 1])); } initialized.store(true); } } } void run_function(intptr_t funptr); void scheduler(processor &p); void schedule(processor &p); } // namspace <anonymous> namespace crossbow { namespace impl { struct thread_impl { enum class state { RUNNING, READY, FINISHED, BLOCKED }; void* sp; std::function<void()> fun; boost::context::fcontext_t ocontext; #if BOOST_VERSION >= 105600 boost::context::fcontext_t fc; #else boost::context::fcontext_t* fc; #endif volatile bool is_detached; volatile state state_; volatile bool in_queue; busy_mutex mutex; thread_impl() : sp(nullptr), fc(nullptr), is_detached(false), state_(state::READY), in_queue(true) { } thread_impl(const thread_impl &) = delete; thread_impl(thread_impl && o) : sp(o.sp), fun(std::move(o.fun)), ocontext(std::move(ocontext)), fc(o.fc), is_detached(o.is_detached) { o.sp = nullptr; o.fc = nullptr; ocontext = boost::context::fcontext_t {}; } ~thread_impl() { free_stack(sp); } }; } // namespace impl impl::thread_impl* thread::create_impl(std::function<void()> fun) { default_init(); auto timpl = new impl::thread_impl {}; timpl->sp = alloc_stack(); timpl->fun = std::move(fun); timpl->fc = boost::context::make_fcontext(timpl->sp, STACK_SIZE, run_function); RETRY: auto idx = rdtsc() % num_processors; if (processors[idx]->queue.push(timpl)) { } else { goto RETRY; } return timpl; } thread::thread(thread && other) { if (impl_) std::terminate(); impl_ = other.impl_; other.impl_ = nullptr; } thread::~thread() { if (impl_) { join(); } } bool thread::joinable() const { return impl_ != nullptr; } void thread::join() { processor &proc = this_processor(); RETRY: bool do_run = false; bool do_delete = false; { std::lock_guard<busy_mutex> _(impl_->mutex); if (impl_->state_ == impl::thread_impl::state::READY) { do_run = true; impl_->state_ = impl::thread_impl::state::RUNNING; } else if (impl_->state_ == impl::thread_impl::state::FINISHED) { do_delete = true; goto FINISH; } } if (do_run) { boost::context::jump_fcontext(&(impl_->ocontext), impl_->fc, (intptr_t) impl_); std::lock_guard<busy_mutex> _(impl_->mutex); if (impl_->in_queue) { impl_->state_ = impl::thread_impl::state::FINISHED; impl_->is_detached = true; } else { do_delete = true; } } else { schedule(proc); goto RETRY; } FINISH: if (do_delete) delete impl_; impl_ = nullptr; } void thread::detach() { bool do_delete = false; if (impl_) { std::lock_guard<busy_mutex> _(impl_->mutex); do_delete = impl_->state_ == impl::thread_impl::state::FINISHED; impl_->is_detached = true; } if (do_delete) delete impl_; impl_ = nullptr; } void mutex::lock() { bool val = _m.load(); for (int i = 0; i < 100; ++i) { if (val) if (_m.compare_exchange_strong(val, false)) return; } auto &proc = this_processor(); while (true) { schedule(proc); for (int i = 0; i < 100; ++i) { if (val) if (_m.compare_exchange_strong(val, false)) return; } } } namespace this_thread { void yield() { auto &p = this_processor(); schedule(p); } template<class Rep, class Period> void sleep_for(const std::chrono::duration<Rep, Period> &duration) { auto &p = this_processor(); auto begin = std::chrono::system_clock::now(); decltype(begin) end; do { schedule(p); end = std::chrono::system_clock::now(); } while (begin + duration > end); } template<class Clock, class Duration> void sleep_until(const std::chrono::time_point<Clock, Duration> &sleep_time) { auto &p = this_processor(); auto now = Clock::now(); while (now < sleep_time) { schedule(p); now = Clock::now(); } } } // namespace this_thread } // namespace crossbow namespace { void run_function(intptr_t funptr) { crossbow::impl::thread_impl* timpl = (crossbow::impl::thread_impl*)funptr; (timpl->fun)(); // jump back to scheduler #if BOOST_VERSION >= 105600 boost::context::jump_fcontext(&timpl->fc, timpl->ocontext, 0); #else boost::context::jump_fcontext(timpl->fc, &(timpl->ocontext), 0); #endif assert(false); // never returns } void scheduler(processor &p) { { std::lock_guard<decltype(map_mutex)> _(map_mutex); this_thread_map.insert(std::make_pair(std::this_thread::get_id(), &p)); } while (true) { schedule(p); } } void schedule(processor &p) { processor* proc = &p; crossbow::impl::thread_impl* timpl; size_t count = 10; while (!proc->queue.pop(timpl)) { // do work stealing proc = processors[rdtsc() % num_processors]; if (--count) return; } // schedule this thread bool do_run = false; { std::lock_guard<crossbow::busy_mutex> _(timpl->mutex); timpl->in_queue = false; if (timpl->state_ == crossbow::impl::thread_impl::state::READY) { do_run = true; timpl->state_ = crossbow::impl::thread_impl::state::RUNNING; } } if (do_run) boost::context::jump_fcontext(&(timpl->ocontext), timpl->fc, (intptr_t) timpl); // delete timpl, if it is detached bool do_delete = false; { std::lock_guard<crossbow::busy_mutex> _(timpl->mutex); if (timpl->is_detached) do_delete = true; timpl->state_ = crossbow::impl::thread_impl::state::FINISHED; } if (do_delete) delete timpl; } } // namespace anonymous <commit_msg>removed thread<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2016 Greenheart Games Pty. Ltd. All rights reserved. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "greenworks_utils.h" #include "steam_id.h" #include "v8.h" namespace greenworks { v8::Local<v8::Object> SteamID::Create(CSteamID steam_id) { Nan::EscapableHandleScope scope; v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(); tpl->InstanceTemplate()->SetInternalFieldCount(1); SetPrototypeMethod(tpl, "isAnonymous", IsAnonymous); SetPrototypeMethod(tpl, "isAnonymousGameServer", IsAnonymousGameServer); SetPrototypeMethod(tpl, "isAnonymousGameServerLogin", IsAnonymousGameServerLogin); SetPrototypeMethod(tpl, "isAnonymousUser", IsAnonymousUser); SetPrototypeMethod(tpl, "isChatAccount", IsChatAccount); SetPrototypeMethod(tpl, "isClanAccount", IsClanAccount); SetPrototypeMethod(tpl, "isConsoleUserAccount", IsConsoleUserAccount); SetPrototypeMethod(tpl, "isContentServerAccount", IsContentServerAccount); SetPrototypeMethod(tpl, "isGameServerAccount", IsGameServerAccount); SetPrototypeMethod(tpl, "isIndividualAccount", IsIndividualAccount); SetPrototypeMethod(tpl, "isPersistentGameServerAccount", IsPersistentGameServerAccount); SetPrototypeMethod(tpl, "isLobby", IsLobby); SetPrototypeMethod(tpl, "getAccountID", GetAccountID); SetPrototypeMethod(tpl, "getRawSteamID", GetRawSteamID); SetPrototypeMethod(tpl, "getAccountType", GetAccountType); SetPrototypeMethod(tpl, "isValid", IsValid); SetPrototypeMethod(tpl, "getStaticAccountKey", GetStaticAccountKey); SetPrototypeMethod(tpl, "getPersonaName", GetPersonaName); SetPrototypeMethod(tpl, "getNickname", GetNickname); SetPrototypeMethod(tpl, "getRelationship", GetRelationship); SetPrototypeMethod(tpl, "getSteamLevel", GetSteamLevel); SteamID* obj = new SteamID(steam_id); v8::Local<v8::Object> instance = Nan::NewInstance(tpl->GetFunction()).ToLocalChecked(); Nan::SetInternalFieldPointer(instance, 0, obj); return scope.Escape(instance); } NAN_METHOD(SteamID::IsAnonymous) { SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder()); info.GetReturnValue().Set(obj->steam_id_.BAnonAccount()); } NAN_METHOD(SteamID::IsAnonymousGameServer) { SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder()); info.GetReturnValue().Set(obj->steam_id_.BAnonGameServerAccount()); } NAN_METHOD(SteamID::IsAnonymousGameServerLogin) { SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder()); info.GetReturnValue().Set(Nan::New(obj->steam_id_.BBlankAnonAccount())); } NAN_METHOD(SteamID::IsAnonymousUser) { SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder()); info.GetReturnValue().Set(Nan::New(obj->steam_id_.BAnonUserAccount())); } NAN_METHOD(SteamID::IsChatAccount) { SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder()); info.GetReturnValue().Set(Nan::New(obj->steam_id_.BChatAccount())); } NAN_METHOD(SteamID::IsClanAccount) { SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder()); info.GetReturnValue().Set(Nan::New(obj->steam_id_.BClanAccount())); } NAN_METHOD(SteamID::IsConsoleUserAccount) { SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder()); info.GetReturnValue().Set(Nan::New(obj->steam_id_.BConsoleUserAccount())); } NAN_METHOD(SteamID::IsContentServerAccount) { SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder()); info.GetReturnValue().Set(Nan::New(obj->steam_id_.BContentServerAccount())); } NAN_METHOD(SteamID::IsGameServerAccount) { SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder()); info.GetReturnValue().Set(Nan::New(obj->steam_id_.BGameServerAccount())); } NAN_METHOD(SteamID::IsIndividualAccount) { SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder()); info.GetReturnValue().Set(Nan::New(obj->steam_id_.BIndividualAccount())); } NAN_METHOD(SteamID::IsPersistentGameServerAccount) { SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder()); info.GetReturnValue().Set( Nan::New(obj->steam_id_.BPersistentGameServerAccount())); } NAN_METHOD(SteamID::IsLobby) { SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder()); info.GetReturnValue().Set(Nan::New(obj->steam_id_.IsLobby())); } NAN_METHOD(SteamID::GetAccountID) { SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder()); info.GetReturnValue().Set( Nan::New<v8::Integer>(obj->steam_id_.GetAccountID())); } NAN_METHOD(SteamID::GetRawSteamID) { SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder()); info.GetReturnValue().Set( Nan::New(utils::uint64ToString(obj->steam_id_.ConvertToUint64())) .ToLocalChecked()); } NAN_METHOD(SteamID::GetAccountType) { SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder()); info.GetReturnValue().Set(Nan::New(obj->steam_id_.GetEAccountType())); } NAN_METHOD(SteamID::IsValid) { SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder()); info.GetReturnValue().Set(Nan::New(obj->steam_id_.IsValid())); } NAN_METHOD(SteamID::GetStaticAccountKey) { SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder()); info.GetReturnValue().Set( Nan::New(utils::uint64ToString( obj->steam_id_.GetStaticAccountKey())).ToLocalChecked()); } NAN_METHOD(SteamID::GetPersonaName) { SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder()); info.GetReturnValue().Set( Nan::New(SteamFriends()->GetFriendPersonaName(obj->steam_id_)) .ToLocalChecked()); } NAN_METHOD(SteamID::GetNickname) { SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder()); const char* nick_name = SteamFriends()->GetPlayerNickname(obj->steam_id_); if (nick_name != NULL) { info.GetReturnValue().Set(Nan::New(nick_name).ToLocalChecked()); return; } info.GetReturnValue().Set(Nan::EmptyString()); } NAN_METHOD(SteamID::GetRelationship) { SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder()); info.GetReturnValue().Set( Nan::New(SteamFriends()->GetFriendRelationship(obj->steam_id_))); } NAN_METHOD(SteamID::GetSteamLevel) { SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder()); info.GetReturnValue().Set( Nan::New(SteamFriends()->GetFriendSteamLevel(obj->steam_id_))); } } // namespace greenworks <commit_msg>Simplify the code.<commit_after>// Copyright (c) 2016 Greenheart Games Pty. Ltd. All rights reserved. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "greenworks_utils.h" #include "steam_id.h" #include "v8.h" namespace greenworks { v8::Local<v8::Object> SteamID::Create(CSteamID steam_id) { Nan::EscapableHandleScope scope; v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(); tpl->InstanceTemplate()->SetInternalFieldCount(1); SetPrototypeMethod(tpl, "isAnonymous", IsAnonymous); SetPrototypeMethod(tpl, "isAnonymousGameServer", IsAnonymousGameServer); SetPrototypeMethod(tpl, "isAnonymousGameServerLogin", IsAnonymousGameServerLogin); SetPrototypeMethod(tpl, "isAnonymousUser", IsAnonymousUser); SetPrototypeMethod(tpl, "isChatAccount", IsChatAccount); SetPrototypeMethod(tpl, "isClanAccount", IsClanAccount); SetPrototypeMethod(tpl, "isConsoleUserAccount", IsConsoleUserAccount); SetPrototypeMethod(tpl, "isContentServerAccount", IsContentServerAccount); SetPrototypeMethod(tpl, "isGameServerAccount", IsGameServerAccount); SetPrototypeMethod(tpl, "isIndividualAccount", IsIndividualAccount); SetPrototypeMethod(tpl, "isPersistentGameServerAccount", IsPersistentGameServerAccount); SetPrototypeMethod(tpl, "isLobby", IsLobby); SetPrototypeMethod(tpl, "getAccountID", GetAccountID); SetPrototypeMethod(tpl, "getRawSteamID", GetRawSteamID); SetPrototypeMethod(tpl, "getAccountType", GetAccountType); SetPrototypeMethod(tpl, "isValid", IsValid); SetPrototypeMethod(tpl, "getStaticAccountKey", GetStaticAccountKey); SetPrototypeMethod(tpl, "getPersonaName", GetPersonaName); SetPrototypeMethod(tpl, "getNickname", GetNickname); SetPrototypeMethod(tpl, "getRelationship", GetRelationship); SetPrototypeMethod(tpl, "getSteamLevel", GetSteamLevel); SteamID* obj = new SteamID(steam_id); v8::Local<v8::Object> instance = Nan::NewInstance(tpl->GetFunction()).ToLocalChecked(); Nan::SetInternalFieldPointer(instance, 0, obj); return scope.Escape(instance); } NAN_METHOD(SteamID::IsAnonymous) { SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder()); info.GetReturnValue().Set(obj->steam_id_.BAnonAccount()); } NAN_METHOD(SteamID::IsAnonymousGameServer) { SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder()); info.GetReturnValue().Set(obj->steam_id_.BAnonGameServerAccount()); } NAN_METHOD(SteamID::IsAnonymousGameServerLogin) { SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder()); info.GetReturnValue().Set(Nan::New(obj->steam_id_.BBlankAnonAccount())); } NAN_METHOD(SteamID::IsAnonymousUser) { SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder()); info.GetReturnValue().Set(Nan::New(obj->steam_id_.BAnonUserAccount())); } NAN_METHOD(SteamID::IsChatAccount) { SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder()); info.GetReturnValue().Set(Nan::New(obj->steam_id_.BChatAccount())); } NAN_METHOD(SteamID::IsClanAccount) { SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder()); info.GetReturnValue().Set(Nan::New(obj->steam_id_.BClanAccount())); } NAN_METHOD(SteamID::IsConsoleUserAccount) { SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder()); info.GetReturnValue().Set(Nan::New(obj->steam_id_.BConsoleUserAccount())); } NAN_METHOD(SteamID::IsContentServerAccount) { SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder()); info.GetReturnValue().Set(Nan::New(obj->steam_id_.BContentServerAccount())); } NAN_METHOD(SteamID::IsGameServerAccount) { SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder()); info.GetReturnValue().Set(Nan::New(obj->steam_id_.BGameServerAccount())); } NAN_METHOD(SteamID::IsIndividualAccount) { SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder()); info.GetReturnValue().Set(Nan::New(obj->steam_id_.BIndividualAccount())); } NAN_METHOD(SteamID::IsPersistentGameServerAccount) { SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder()); info.GetReturnValue().Set( Nan::New(obj->steam_id_.BPersistentGameServerAccount())); } NAN_METHOD(SteamID::IsLobby) { SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder()); info.GetReturnValue().Set(Nan::New(obj->steam_id_.IsLobby())); } NAN_METHOD(SteamID::GetAccountID) { SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder()); info.GetReturnValue().Set( Nan::New<v8::Integer>(obj->steam_id_.GetAccountID())); } NAN_METHOD(SteamID::GetRawSteamID) { SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder()); info.GetReturnValue().Set( Nan::New(utils::uint64ToString(obj->steam_id_.ConvertToUint64())) .ToLocalChecked()); } NAN_METHOD(SteamID::GetAccountType) { SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder()); info.GetReturnValue().Set(Nan::New(obj->steam_id_.GetEAccountType())); } NAN_METHOD(SteamID::IsValid) { SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder()); info.GetReturnValue().Set(Nan::New(obj->steam_id_.IsValid())); } NAN_METHOD(SteamID::GetStaticAccountKey) { SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder()); info.GetReturnValue().Set( Nan::New(utils::uint64ToString( obj->steam_id_.GetStaticAccountKey())).ToLocalChecked()); } NAN_METHOD(SteamID::GetPersonaName) { SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder()); info.GetReturnValue().Set( Nan::New(SteamFriends()->GetFriendPersonaName(obj->steam_id_)) .ToLocalChecked()); } NAN_METHOD(SteamID::GetNickname) { SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder()); const char* nick_name = SteamFriends()->GetPlayerNickname(obj->steam_id_); if (nick_name) { info.GetReturnValue().Set(Nan::New(nick_name).ToLocalChecked()); return; } info.GetReturnValue().Set(Nan::EmptyString()); } NAN_METHOD(SteamID::GetRelationship) { SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder()); info.GetReturnValue().Set( Nan::New(SteamFriends()->GetFriendRelationship(obj->steam_id_))); } NAN_METHOD(SteamID::GetSteamLevel) { SteamID* obj = ObjectWrap::Unwrap<SteamID>(info.Holder()); info.GetReturnValue().Set( Nan::New(SteamFriends()->GetFriendSteamLevel(obj->steam_id_))); } } // namespace greenworks <|endoftext|>
<commit_before>#include <catch.hpp> #include <luwra.hpp> #include <memory> struct A { int a; A(int x = 1338): a(x) {} }; TEST_CASE("UserTypeRegistration") { luwra::StateWrapper state; luwra::registerUserType<A>(state); } TEST_CASE("UserTypeConstruction") { luwra::StateWrapper state; luwra::registerUserType<A(int)>(state, "A"); // Construction REQUIRE(luaL_dostring(state, "return A(73)") == 0); // Check A* instance = luwra::read<A*>(state, -1); REQUIRE(instance != nullptr); REQUIRE(instance->a == 73); } struct B { int n; const int cn; volatile int vn; const volatile int cvn; B(int val): n(val), cn(val), vn(val), cvn(val) {} }; TEST_CASE("UserTypeFields") { luwra::StateWrapper state; // Registration luwra::registerUserType<B>( state, { LUWRA_MEMBER(B, n), LUWRA_MEMBER(B, cn), LUWRA_MEMBER(B, vn), LUWRA_MEMBER(B, cvn) } ); // Instantiation B& value = luwra::construct<B>(state, 1338); lua_setglobal(state, "value"); // Unqualified get REQUIRE(luaL_dostring(state, "return value:n()") == 0); puts(lua_tostring(state, -1)); REQUIRE(luwra::read<int>(state, -1) == value.n); // Unqualified set REQUIRE(luaL_dostring(state, "value:n(42)") == 0); REQUIRE(value.n == 42); // 'const'-qualified get REQUIRE(luaL_dostring(state, "return value:cn()") == 0); REQUIRE(luwra::read<int>(state, -1) == value.cn); // 'const'-qualified set REQUIRE(luaL_dostring(state, "value:cn(42)") == 0); REQUIRE(value.cn == 1338); // 'volatile' get REQUIRE(luaL_dostring(state, "return value:vn()") == 0); REQUIRE(luwra::read<int>(state, -1) == value.vn); // 'volatile' set REQUIRE(luaL_dostring(state, "value:vn(42)") == 0); REQUIRE(value.vn == 42); // 'const volatile'-qualified get REQUIRE(luaL_dostring(state, "return value:cvn()") == 0); REQUIRE(luwra::read<int>(state, -1) == value.cvn); // 'const volatile'-qualified set REQUIRE(luaL_dostring(state, "value:cvn(42)") == 0); REQUIRE(value.cvn == 1338); } struct C { int prop; C(int val): prop(val) {} int foo1(int x) { return prop += x; } int foo2(int x) const { return prop + x; } int foo3(int x) volatile { return prop -= x; } int foo4(int x) const volatile { return prop - x; } }; TEST_CASE("UserTypeMethods") { luwra::StateWrapper state; // Registration luwra::registerUserType<C>( state, { LUWRA_MEMBER(C, foo1), LUWRA_MEMBER(C, foo2), LUWRA_MEMBER(C, foo3), LUWRA_MEMBER(C, foo4) } ); // Instantiation C& value = luwra::construct<C>(state, 1337); lua_setglobal(state, "value"); // Unqualified method REQUIRE(luaL_dostring(state, "return value:foo1(63)") == 0); REQUIRE(value.prop == 1400); REQUIRE(luwra::read<int>(state, -1) == value.prop); // 'const'-qualified method REQUIRE(luaL_dostring(state, "return value:foo2(44)") == 0); REQUIRE(value.prop == 1400); REQUIRE(luwra::read<int>(state, -1) == 1444); // 'volatile'-qualified method REQUIRE(luaL_dostring(state, "return value:foo3(400)") == 0); REQUIRE(value.prop == 1000); REQUIRE(luwra::read<int>(state, -1) == value.prop); // 'const volatile'-qualified method REQUIRE(luaL_dostring(state, "return value:foo4(334)") == 0); REQUIRE(value.prop == 1000); REQUIRE(luwra::read<int>(state, -1) == 666); } TEST_CASE("UserTypeGarbageCollectionRef") { lua_State* state = luaL_newstate(); // Registration luwra::registerUserType<std::shared_ptr<int>>(state); // Instantiation std::shared_ptr<int> shared_var = std::make_shared<int>(1337); REQUIRE(shared_var.use_count() == 1); // Copy construction luwra::push(state, shared_var); REQUIRE(shared_var.use_count() == 2); // Garbage collection lua_close(state); REQUIRE(shared_var.use_count() == 1); } <commit_msg>Remove debug statement from usertypes test<commit_after>#include <catch.hpp> #include <luwra.hpp> #include <memory> struct A { int a; A(int x = 1338): a(x) {} }; TEST_CASE("UserTypeRegistration") { luwra::StateWrapper state; luwra::registerUserType<A>(state); } TEST_CASE("UserTypeConstruction") { luwra::StateWrapper state; luwra::registerUserType<A(int)>(state, "A"); // Construction REQUIRE(luaL_dostring(state, "return A(73)") == 0); // Check A* instance = luwra::read<A*>(state, -1); REQUIRE(instance != nullptr); REQUIRE(instance->a == 73); } struct B { int n; const int cn; volatile int vn; const volatile int cvn; B(int val): n(val), cn(val), vn(val), cvn(val) {} }; TEST_CASE("UserTypeFields") { luwra::StateWrapper state; // Registration luwra::registerUserType<B>( state, { LUWRA_MEMBER(B, n), LUWRA_MEMBER(B, cn), LUWRA_MEMBER(B, vn), LUWRA_MEMBER(B, cvn) } ); // Instantiation B& value = luwra::construct<B>(state, 1338); lua_setglobal(state, "value"); // Unqualified get REQUIRE(luaL_dostring(state, "return value:n()") == 0); REQUIRE(luwra::read<int>(state, -1) == value.n); // Unqualified set REQUIRE(luaL_dostring(state, "value:n(42)") == 0); REQUIRE(value.n == 42); // 'const'-qualified get REQUIRE(luaL_dostring(state, "return value:cn()") == 0); REQUIRE(luwra::read<int>(state, -1) == value.cn); // 'const'-qualified set REQUIRE(luaL_dostring(state, "value:cn(42)") == 0); REQUIRE(value.cn == 1338); // 'volatile' get REQUIRE(luaL_dostring(state, "return value:vn()") == 0); REQUIRE(luwra::read<int>(state, -1) == value.vn); // 'volatile' set REQUIRE(luaL_dostring(state, "value:vn(42)") == 0); REQUIRE(value.vn == 42); // 'const volatile'-qualified get REQUIRE(luaL_dostring(state, "return value:cvn()") == 0); REQUIRE(luwra::read<int>(state, -1) == value.cvn); // 'const volatile'-qualified set REQUIRE(luaL_dostring(state, "value:cvn(42)") == 0); REQUIRE(value.cvn == 1338); } struct C { int prop; C(int val): prop(val) {} int foo1(int x) { return prop += x; } int foo2(int x) const { return prop + x; } int foo3(int x) volatile { return prop -= x; } int foo4(int x) const volatile { return prop - x; } }; TEST_CASE("UserTypeMethods") { luwra::StateWrapper state; // Registration luwra::registerUserType<C>( state, { LUWRA_MEMBER(C, foo1), LUWRA_MEMBER(C, foo2), LUWRA_MEMBER(C, foo3), LUWRA_MEMBER(C, foo4) } ); // Instantiation C& value = luwra::construct<C>(state, 1337); lua_setglobal(state, "value"); // Unqualified method REQUIRE(luaL_dostring(state, "return value:foo1(63)") == 0); REQUIRE(value.prop == 1400); REQUIRE(luwra::read<int>(state, -1) == value.prop); // 'const'-qualified method REQUIRE(luaL_dostring(state, "return value:foo2(44)") == 0); REQUIRE(value.prop == 1400); REQUIRE(luwra::read<int>(state, -1) == 1444); // 'volatile'-qualified method REQUIRE(luaL_dostring(state, "return value:foo3(400)") == 0); REQUIRE(value.prop == 1000); REQUIRE(luwra::read<int>(state, -1) == value.prop); // 'const volatile'-qualified method REQUIRE(luaL_dostring(state, "return value:foo4(334)") == 0); REQUIRE(value.prop == 1000); REQUIRE(luwra::read<int>(state, -1) == 666); } TEST_CASE("UserTypeGarbageCollectionRef") { lua_State* state = luaL_newstate(); // Registration luwra::registerUserType<std::shared_ptr<int>>(state); // Instantiation std::shared_ptr<int> shared_var = std::make_shared<int>(1337); REQUIRE(shared_var.use_count() == 1); // Copy construction luwra::push(state, shared_var); REQUIRE(shared_var.use_count() == 2); // Garbage collection lua_close(state); REQUIRE(shared_var.use_count() == 1); } <|endoftext|>
<commit_before>// -*- C++ -*- // // ---------------------------------------------------------------------- // // Brad T. Aagaard, U.S. Geological Survey // // This code was developed as part of the Computational Infrastructure // for Geodynamics (http://geodynamics.org). // // Copyright (c) 2010-2012 University of California, Davis // // See COPYING for license information. // // ---------------------------------------------------------------------- // #include <portinfo> #include "Parser.hh" // implementation of class methods #include <sstream> // USES std::ostringstream #include <stdexcept> // USES std::runtime_error #include <assert.h> // USES assert() // ---------------------------------------------------------------------- // Default constructor spatialdata::units::Parser::Parser(void) { // constructor // Initialize Python interpreter if it is not already initialized. _alreadyInitialized = Py_IsInitialized(); if (!_alreadyInitialized) Py_Initialize(); // Should check for NULL, decode the exception, and throw a C++ equivalent PyObject* mod = PyImport_ImportModule("pyre.units"); if (!mod) { throw std::runtime_error("Could not import module 'pyre.units'."); } // if PyObject* cls = PyObject_GetAttrString(mod, "parser"); if (!cls) { throw std::runtime_error("Could not get 'parser' attribute in pyre.units module."); } // if _parser = PyObject_CallFunctionObjArgs(cls, NULL); if (!_parser) { throw std::runtime_error("Could not create parser Python object."); } // if Py_DECREF(cls); Py_DECREF(mod); } // constructor // ---------------------------------------------------------------------- // Default destructor spatialdata::units::Parser::~Parser(void) { // destructor Py_CLEAR(_parser); if (!_alreadyInitialized) Py_Finalize(); } // destructor // ---------------------------------------------------------------------- // Get SI scaling factor for units given by string. To get value in // SI units, multiple value given by units by scaling factor. double spatialdata::units::Parser::parse(const char* units) { // parse double scale = 1.0; /* Replicate Python functionality given by * * import pyre.units * p = pyre.units.parser() * x = p.parse(units) [units is a string] * scale = x.value */ PyObject *pyUnit = PyObject_CallMethod(_parser, "parse", "s", units); if (pyUnit == 0) { if (PyErr_Occurred()) { PyErr_Clear(); std::ostringstream msg; msg << "Could not parse units string '" << units << "'."; throw std::runtime_error(msg.str()); } // if } // if PyObject *pyScale = PyObject_GetAttrString(pyUnit, "value"); if (pyScale == 0) { Py_DECREF(pyUnit); if (PyErr_Occurred()) { PyErr_Clear(); std::ostringstream msg; msg << "Could not get floating point value when parsing units string '" << units << "'."; throw std::runtime_error(msg.str()); } // if } // if if (!PyFloat_Check(pyScale)) { Py_DECREF(pyScale); Py_DECREF(pyUnit); PyErr_Clear(); std::ostringstream msg; msg << "Could not get floating point value when parsing units string '" << units << "'."; throw std::runtime_error(msg.str()); } // if scale = PyFloat_AsDouble(pyScale); Py_DECREF(pyScale); Py_DECREF(pyUnit); return scale; } // parser // End of file <commit_msg>Small cleanup of error reporting in Parser.<commit_after>// -*- C++ -*- // // ---------------------------------------------------------------------- // // Brad T. Aagaard, U.S. Geological Survey // // This code was developed as part of the Computational Infrastructure // for Geodynamics (http://geodynamics.org). // // Copyright (c) 2010-2012 University of California, Davis // // See COPYING for license information. // // ---------------------------------------------------------------------- // #include <portinfo> #include "Parser.hh" // implementation of class methods #include <sstream> // USES std::ostringstream #include <stdexcept> // USES std::runtime_error #include <assert.h> // USES assert() // ---------------------------------------------------------------------- // Default constructor spatialdata::units::Parser::Parser(void) { // constructor // Initialize Python interpreter if it is not already initialized. _alreadyInitialized = Py_IsInitialized(); if (!_alreadyInitialized) Py_Initialize(); // Should check for NULL, decode the exception, and throw a C++ equivalent PyObject* mod = PyImport_ImportModule("pyre.units"); if (!mod) { throw std::runtime_error("Could not import module 'pyre.units'."); } // if PyObject* cls = PyObject_GetAttrString(mod, "parser"); if (!cls) { throw std::runtime_error("Could not get 'parser' attribute in pyre.units module."); } // if _parser = PyObject_CallFunctionObjArgs(cls, NULL); if (!_parser) { throw std::runtime_error("Could not create parser Python object."); } // if Py_DECREF(cls); Py_DECREF(mod); } // constructor // ---------------------------------------------------------------------- // Default destructor spatialdata::units::Parser::~Parser(void) { // destructor Py_CLEAR(_parser); if (!_alreadyInitialized) Py_Finalize(); } // destructor // ---------------------------------------------------------------------- // Get SI scaling factor for units given by string. To get value in // SI units, multiple value given by units by scaling factor. double spatialdata::units::Parser::parse(const char* units) { // parse double scale = 1.0; /* Replicate Python functionality given by * * import pyre.units * p = pyre.units.parser() * x = p.parse(units) [units is a string] * scale = x.value */ PyObject* pyUnit = PyObject_CallMethod(_parser, "parse", "s", units); if (!pyUnit) { if (PyErr_Occurred()) { PyErr_Clear(); } // if std::ostringstream msg; msg << "Could not parse units string '" << units << "'."; throw std::runtime_error(msg.str()); } // if PyObject* pyScale = PyObject_GetAttrString(pyUnit, "value"); if (!pyScale) { Py_DECREF(pyUnit); if (PyErr_Occurred()) { PyErr_Clear(); } // if std::ostringstream msg; msg << "Could not get floating point value when parsing units string '" << units << "'."; throw std::runtime_error(msg.str()); } // if if (!PyFloat_Check(pyScale)) { Py_DECREF(pyScale); Py_DECREF(pyUnit); PyErr_Clear(); std::ostringstream msg; msg << "Could not get floating point value when parsing units string '" << units << "'."; throw std::runtime_error(msg.str()); } // if scale = PyFloat_AsDouble(pyScale); Py_DECREF(pyScale); Py_DECREF(pyUnit); return scale; } // parser // End of file <|endoftext|>
<commit_before>// Copyright (C) 2015 Elviss Strazdins // This file is part of the Ouzel engine. #include <algorithm> #include "Node.h" #include "Engine.h" #include "SceneManager.h" #include "Layer.h" #include "Animator.h" #include "Camera.h" #include "Utils.h" #include "MathUtils.h" namespace ouzel { Node::Node() { } Node::~Node() { } void Node::draw() { if (_transformDirty) { calculateTransform(); } } void Node::update(float delta) { if (_currentAnimator) { _currentAnimator->update(delta); } if (_transformDirty) { calculateTransform(); } } bool Node::addChild(const NodePtr& node) { if (NodeContainer::addChild(node)) { node->addToLayer(_layer); node->setParentVisible(_visible && _parentVisible); if (_transformDirty) { calculateTransform(); } else { node->updateTransform(_transform); } return true; } else { return false; } } bool Node::removeFromParent() { if (NodeContainerPtr parent = _parent.lock()) { parent->removeChild(std::static_pointer_cast<Node>(shared_from_this())); return true; } return false; } void Node::setZ(float z) { _z = z; if (LayerPtr layer = _layer.lock()) { layer->reorderNodes(); } markTransformDirty(); } void Node::setPosition(const Vector2& position) { _position = position; markTransformDirty(); } void Node::setRotation(float rotation) { _rotation = rotation; markTransformDirty(); } void Node::setScale(const Vector2& scale) { _scale = scale; markTransformDirty(); } void Node::setFlipX(bool flipX) { _flipX = flipX; markTransformDirty(); } void Node::setFlipY(bool flipY) { _flipY = flipY; markTransformDirty(); } void Node::setVisible(bool visible) { if (visible != _visible) { _visible = visible; setParentVisible(_parentVisible); } } void Node::addToLayer(const LayerWeakPtr& layer) { _layer = layer; if (LayerPtr layer = _layer.lock()) { layer->addNode(std::static_pointer_cast<Node>(shared_from_this())); for (NodePtr child : _children) { child->addToLayer(layer); } } } void Node::removeFromLayer() { if (LayerPtr layer = _layer.lock()) { layer->removeNode(std::static_pointer_cast<Node>(shared_from_this())); for (NodePtr child : _children) { child->removeFromLayer(); } } } bool Node::pointOn(const Vector2& position) const { return _boundingBox.containPoint(convertWorldToLocal(position)); } bool Node::rectangleOverlaps(const Rectangle& rectangle) const { if (_boundingBox.isEmpty()) { return false; } Vector3 localLeftBottom = Vector3(rectangle.x, rectangle.y, 0.0f); const Matrix4& inverseTransform = getInverseTransform(); inverseTransform.transformPoint(&localLeftBottom); Vector3 localRightTop = Vector3(rectangle.x + rectangle.width, rectangle.y + rectangle.height, 0.0f); inverseTransform.transformPoint(&localRightTop); if (localLeftBottom.x > _boundingBox.max.x || localLeftBottom.y > _boundingBox.max.y || localRightTop.x < _boundingBox.min.x || localRightTop.y < _boundingBox.min.y) { return false; } return true; } const Matrix4& Node::getTransform() const { if (_transformDirty) { calculateTransform(); } return _transform; } const Matrix4& Node::getInverseTransform() const { if (_transformDirty) { calculateTransform(); } if (_inverseTransformDirty) { calculateInverseTransform(); } return _inverseTransform; } void Node::updateTransform(const Matrix4& parentTransform) { _parentTransform = parentTransform; calculateTransform(); _inverseTransformDirty = true; } Vector2 Node::convertWorldToLocal(const Vector2& position) const { Vector3 localPosition = position; const Matrix4& inverseTransform = getInverseTransform(); inverseTransform.transformPoint(&localPosition); return Vector2(localPosition.x, localPosition.y); } Vector2 Node::convertLocalToWorld(const Vector2& position) const { Vector3 worldPosition = position; const Matrix4& transform = getTransform(); transform.transformPoint(&worldPosition); return Vector2(worldPosition.x, worldPosition.y); } bool Node::checkVisibility() const { if (LayerPtr layer = _layer.lock()) { if (_boundingBox.isEmpty() || _boundingRadius == 0.0f) { return true; } Matrix4 mvp = layer->getProjection() * layer->getCamera()->getTransform() * _transform; Vector3 position; mvp.transformPoint(&position); float radius = _boundingRadius * std::max(_scale.x, _scale.y); radius /= layer->getCamera()->getZoom(); Vector2 radiusAxis(radius / (2.0f * Engine::getInstance()->getRenderer()->getSize().width - 1.0f), radius / (2.0f * Engine::getInstance()->getRenderer()->getSize().height - 1.0f)); if (position.x >= -(1.0f + radiusAxis.x) && position.x <= (1.0f + radiusAxis.x) && position.y >= -(1.0f + radiusAxis.y) && position.y <= (1.0f + radiusAxis.y)) { /*Vector3 corners[4] = { Vector3(_boundingBox.min.x, _boundingBox.min.y, 0.0f), Vector3(_boundingBox.max.x, _boundingBox.min.y, 0.0f), Vector3(_boundingBox.max.x, _boundingBox.max.y, 0.0f), Vector3(_boundingBox.min.x, _boundingBox.max.y, 0.0f) }; uint8_t inCorners = 0; for (Vector3& corner : corners) { mvp.transformPoint(&corner); if (corner.x >= -1.0f && corner.x <= 1.0f && corner.y >= -1.0f && corner.y <= 1.0f) { return true; } if (corner.x < -1.0f && corner.y < -1.0f) inCorners |= 0x01; if (corner.x > 1.0f && corner.y < -1.0f) inCorners |= 0x02; if (corner.x > 1.0f && corner.y > 1.0f) inCorners |= 0x04; if (corner.x < -1.0f && corner.y > 1.0f) inCorners |= 0x08; } // bounding box is bigger than screen if (inCorners == 0x0F) { return true; } for (uint32_t current = 0; current < 4; ++current) { uint32_t next = (current == 3) ? 0 : current + 1; if (linesIntersect(Vector2(corners[current].x, corners[current].y), Vector2(corners[next].x, corners[next].y), Vector2(-1.0f, 1.0f), Vector2(1.0f, 1.0f)) || // top linesIntersect(Vector2(corners[current].x, corners[current].y), Vector2(corners[next].x, corners[next].y), Vector2(-1.0f, -1.0f), Vector2(1.0f, -1.0f)) || // bottom linesIntersect(Vector2(corners[current].x, corners[current].y), Vector2(corners[next].x, corners[next].y), Vector2(1.0f, -1.0f), Vector2(1.0f, 1.0f)) || // right linesIntersect(Vector2(corners[current].x, corners[current].y), Vector2(corners[next].x, corners[next].y), Vector2(-1.0f, -1.0f), Vector2(-1.0f, 1.0f))) // left { return true; } }*/ return true; } } return false; } void Node::animate(const AnimatorPtr& animator) { _currentAnimator = animator; if (_currentAnimator) { _currentAnimator->start(std::static_pointer_cast<Node>(shared_from_this())); } } void Node::stopAnimation() { if (_currentAnimator) { _currentAnimator->stop(); _currentAnimator.reset(); } } void Node::calculateTransform() const { Matrix4 translation; translation.translate(Vector3(_position.x, _position.y, 0.0f)); Matrix4 rotation; rotation.rotate(Vector3(0.0f, 0.0f, -1.0f), _rotation); Vector3 realScale = Vector3(_scale.x * (_flipX ? -1.0f : 1.0f), _scale.y * (_flipY ? -1.0f : 1.0f), 1.0f); Matrix4 scale; scale.scale(realScale); _transform = _parentTransform * translation * rotation * scale; _transformDirty = false; for (NodePtr child : _children) { child->updateTransform(_transform); } } void Node::calculateInverseTransform() const { if (_transformDirty) { calculateTransform(); } _inverseTransform = _transform; _inverseTransform.invert(); _inverseTransformDirty = false; } void Node::markTransformDirty() const { _transformDirty = true; _inverseTransformDirty = true; } void Node::setParentVisible(bool parentVisible) { _parentVisible = parentVisible; for (const NodePtr& child : _children) { child->setParentVisible(_visible && _parentVisible); } } } <commit_msg>Mark transform dirty in Node's updateTransform<commit_after>// Copyright (C) 2015 Elviss Strazdins // This file is part of the Ouzel engine. #include <algorithm> #include "Node.h" #include "Engine.h" #include "SceneManager.h" #include "Layer.h" #include "Animator.h" #include "Camera.h" #include "Utils.h" #include "MathUtils.h" namespace ouzel { Node::Node() { } Node::~Node() { } void Node::draw() { if (_transformDirty) { calculateTransform(); } } void Node::update(float delta) { if (_currentAnimator) { _currentAnimator->update(delta); } if (_transformDirty) { calculateTransform(); } } bool Node::addChild(const NodePtr& node) { if (NodeContainer::addChild(node)) { node->addToLayer(_layer); node->setParentVisible(_visible && _parentVisible); if (_transformDirty) { calculateTransform(); } else { node->updateTransform(_transform); } return true; } else { return false; } } bool Node::removeFromParent() { if (NodeContainerPtr parent = _parent.lock()) { parent->removeChild(std::static_pointer_cast<Node>(shared_from_this())); return true; } return false; } void Node::setZ(float z) { _z = z; if (LayerPtr layer = _layer.lock()) { layer->reorderNodes(); } markTransformDirty(); } void Node::setPosition(const Vector2& position) { _position = position; markTransformDirty(); } void Node::setRotation(float rotation) { _rotation = rotation; markTransformDirty(); } void Node::setScale(const Vector2& scale) { _scale = scale; markTransformDirty(); } void Node::setFlipX(bool flipX) { _flipX = flipX; markTransformDirty(); } void Node::setFlipY(bool flipY) { _flipY = flipY; markTransformDirty(); } void Node::setVisible(bool visible) { if (visible != _visible) { _visible = visible; setParentVisible(_parentVisible); } } void Node::addToLayer(const LayerWeakPtr& layer) { _layer = layer; if (LayerPtr layer = _layer.lock()) { layer->addNode(std::static_pointer_cast<Node>(shared_from_this())); for (NodePtr child : _children) { child->addToLayer(layer); } } } void Node::removeFromLayer() { if (LayerPtr layer = _layer.lock()) { layer->removeNode(std::static_pointer_cast<Node>(shared_from_this())); for (NodePtr child : _children) { child->removeFromLayer(); } } } bool Node::pointOn(const Vector2& position) const { return _boundingBox.containPoint(convertWorldToLocal(position)); } bool Node::rectangleOverlaps(const Rectangle& rectangle) const { if (_boundingBox.isEmpty()) { return false; } Vector3 localLeftBottom = Vector3(rectangle.x, rectangle.y, 0.0f); const Matrix4& inverseTransform = getInverseTransform(); inverseTransform.transformPoint(&localLeftBottom); Vector3 localRightTop = Vector3(rectangle.x + rectangle.width, rectangle.y + rectangle.height, 0.0f); inverseTransform.transformPoint(&localRightTop); if (localLeftBottom.x > _boundingBox.max.x || localLeftBottom.y > _boundingBox.max.y || localRightTop.x < _boundingBox.min.x || localRightTop.y < _boundingBox.min.y) { return false; } return true; } const Matrix4& Node::getTransform() const { if (_transformDirty) { calculateTransform(); } return _transform; } const Matrix4& Node::getInverseTransform() const { if (_transformDirty) { calculateTransform(); } if (_inverseTransformDirty) { calculateInverseTransform(); } return _inverseTransform; } void Node::updateTransform(const Matrix4& parentTransform) { _parentTransform = parentTransform; _transformDirty = true; _inverseTransformDirty = true; } Vector2 Node::convertWorldToLocal(const Vector2& position) const { Vector3 localPosition = position; const Matrix4& inverseTransform = getInverseTransform(); inverseTransform.transformPoint(&localPosition); return Vector2(localPosition.x, localPosition.y); } Vector2 Node::convertLocalToWorld(const Vector2& position) const { Vector3 worldPosition = position; const Matrix4& transform = getTransform(); transform.transformPoint(&worldPosition); return Vector2(worldPosition.x, worldPosition.y); } bool Node::checkVisibility() const { if (LayerPtr layer = _layer.lock()) { if (_boundingBox.isEmpty() || _boundingRadius == 0.0f) { return true; } Matrix4 mvp = layer->getProjection() * layer->getCamera()->getTransform() * _transform; Vector3 position; mvp.transformPoint(&position); float radius = _boundingRadius * std::max(_scale.x, _scale.y); radius /= layer->getCamera()->getZoom(); Vector2 radiusAxis(radius / (2.0f * Engine::getInstance()->getRenderer()->getSize().width - 1.0f), radius / (2.0f * Engine::getInstance()->getRenderer()->getSize().height - 1.0f)); if (position.x >= -(1.0f + radiusAxis.x) && position.x <= (1.0f + radiusAxis.x) && position.y >= -(1.0f + radiusAxis.y) && position.y <= (1.0f + radiusAxis.y)) { /*Vector3 corners[4] = { Vector3(_boundingBox.min.x, _boundingBox.min.y, 0.0f), Vector3(_boundingBox.max.x, _boundingBox.min.y, 0.0f), Vector3(_boundingBox.max.x, _boundingBox.max.y, 0.0f), Vector3(_boundingBox.min.x, _boundingBox.max.y, 0.0f) }; uint8_t inCorners = 0; for (Vector3& corner : corners) { mvp.transformPoint(&corner); if (corner.x >= -1.0f && corner.x <= 1.0f && corner.y >= -1.0f && corner.y <= 1.0f) { return true; } if (corner.x < -1.0f && corner.y < -1.0f) inCorners |= 0x01; if (corner.x > 1.0f && corner.y < -1.0f) inCorners |= 0x02; if (corner.x > 1.0f && corner.y > 1.0f) inCorners |= 0x04; if (corner.x < -1.0f && corner.y > 1.0f) inCorners |= 0x08; } // bounding box is bigger than screen if (inCorners == 0x0F) { return true; } for (uint32_t current = 0; current < 4; ++current) { uint32_t next = (current == 3) ? 0 : current + 1; if (linesIntersect(Vector2(corners[current].x, corners[current].y), Vector2(corners[next].x, corners[next].y), Vector2(-1.0f, 1.0f), Vector2(1.0f, 1.0f)) || // top linesIntersect(Vector2(corners[current].x, corners[current].y), Vector2(corners[next].x, corners[next].y), Vector2(-1.0f, -1.0f), Vector2(1.0f, -1.0f)) || // bottom linesIntersect(Vector2(corners[current].x, corners[current].y), Vector2(corners[next].x, corners[next].y), Vector2(1.0f, -1.0f), Vector2(1.0f, 1.0f)) || // right linesIntersect(Vector2(corners[current].x, corners[current].y), Vector2(corners[next].x, corners[next].y), Vector2(-1.0f, -1.0f), Vector2(-1.0f, 1.0f))) // left { return true; } }*/ return true; } } return false; } void Node::animate(const AnimatorPtr& animator) { _currentAnimator = animator; if (_currentAnimator) { _currentAnimator->start(std::static_pointer_cast<Node>(shared_from_this())); } } void Node::stopAnimation() { if (_currentAnimator) { _currentAnimator->stop(); _currentAnimator.reset(); } } void Node::calculateTransform() const { Matrix4 translation; translation.translate(Vector3(_position.x, _position.y, 0.0f)); Matrix4 rotation; rotation.rotate(Vector3(0.0f, 0.0f, -1.0f), _rotation); Vector3 realScale = Vector3(_scale.x * (_flipX ? -1.0f : 1.0f), _scale.y * (_flipY ? -1.0f : 1.0f), 1.0f); Matrix4 scale; scale.scale(realScale); _transform = _parentTransform * translation * rotation * scale; _transformDirty = false; for (NodePtr child : _children) { child->updateTransform(_transform); } } void Node::calculateInverseTransform() const { if (_transformDirty) { calculateTransform(); } _inverseTransform = _transform; _inverseTransform.invert(); _inverseTransformDirty = false; } void Node::markTransformDirty() const { _transformDirty = true; _inverseTransformDirty = true; } void Node::setParentVisible(bool parentVisible) { _parentVisible = parentVisible; for (const NodePtr& child : _children) { child->setParentVisible(_visible && _parentVisible); } } } <|endoftext|>
<commit_before>#include "../include/ginseng/ginseng.hpp" #include <chrono> #include <iostream> #include <random> using namespace std; using namespace std::chrono; using DB = Ginseng::Database<>; using Ginseng::Not; using EntID = DB::EntID; using ComID = DB::ComID; template <typename T> void print(T&& t) { //cout << t << endl; } template <typename D, typename F> D bench(F&& f) { auto b = steady_clock::now(); f(); auto e = steady_clock::now(); return duration_cast<D>(e-b); } struct A { volatile int a; }; struct B { volatile double b; }; struct C { string c; }; mt19937& rng(); void random_action(DB& db); void add_random_entity(DB& db); void add_random_component(DB& db, EntID eid); void random_query(DB& db); void random_delete(DB& db); void random_delete_entity(DB& db); void random_delete_component(DB& db); void random_slaughter(DB& db); int main() { DB db; auto work = [&] { for (int i=0; i<100000; ++i) { random_action(db); } }; cout << bench<milliseconds>(work).count() << endl; } mt19937& rng() { static mt19937 mt; return mt; } void random_action(DB& db) { int roll = rng()()%50; switch (roll) { case 0: random_query(db); break; case 1: random_delete(db); break; case 2: random_slaughter(db); break; default: add_random_entity(db); break; } } void add_random_entity(DB& db) { EntID eid = db.makeEntity(); for (int i=0; i<3; ++i) { int roll = rng()()%3; if (roll==0) continue; add_random_component(db, eid); } } void add_random_component(DB& db, EntID eid) { int roll = rng()()%3; static string strs[] = {"poop","dick","butt"}; switch (roll) { case 0: db.makeComponent(eid, A{int(rng()()%10)}); break; case 1: db.makeComponent(eid, B{(rng()()%100)/100.0}); break; case 2: db.makeComponent(eid, C{strs[rng()()%3]}); break; } } void random_query(DB& db) { int roll = rng()()%15; switch (roll) { case 0: print(db.query<>().size()); break; case 1: print(db.query<A>().size()); break; case 2: print(db.query<B>().size()); break; case 3: print(db.query<C>().size()); break; case 4: print(db.query<A,B>().size()); break; case 5: print(db.query<A,C>().size()); break; case 6: print(db.query<B,C>().size()); break; case 7: print(db.query<A,B,C>().size()); break; case 8: print(db.query<Not<A>>().size()); break; case 9: print(db.query<Not<B>>().size()); break; case 10: print(db.query<Not<C>>().size()); break; case 11: print(db.query<Not<A>,B>().size()); break; case 12: print(db.query<Not<A>,C>().size()); break; case 13: print(db.query<Not<B>,C>().size()); break; case 14: print(db.query<Not<A>,B,C>().size()); break; } } void random_delete(DB& db) { int roll = rng()()%2; if (roll==0) { random_delete_entity(db); } else { random_delete_component(db); } } void random_delete_entity(DB& db) { auto all = db.query<>(); if (all.empty()) return; int roll = rng()()%all.size(); db.eraseEntity(get<0>(all[roll])); } void random_delete_component(DB& db) { int roll = rng()()%3; switch (roll) { case 0: { auto all = db.query<A>(); if (all.empty()) return; int roll = rng()()%all.size(); db.eraseComponent(get<1>(all[roll]).id()); } break; case 1: { auto all = db.query<B>(); if (all.empty()) return; int roll = rng()()%all.size(); db.eraseComponent(get<1>(all[roll]).id()); } break; case 2: { auto all = db.query<C>(); if (all.empty()) return; int roll = rng()()%all.size(); db.eraseComponent(get<1>(all[roll]).id()); } break; } } void random_slaughter(DB& db) { int roll = rng()()%3; switch (roll) { case 0: { auto all = db.query<A>(); for (auto&& e : all) db.eraseEntity(get<0>(e)); } break; case 1: { auto all = db.query<B>(); for (auto&& e : all) db.eraseEntity(get<0>(e)); } break; case 2: { auto all = db.query<C>(); for (auto&& e : all) db.eraseEntity(get<0>(e)); } break; } } <commit_msg>Changed strings.<commit_after>#include "../include/ginseng/ginseng.hpp" #include <chrono> #include <iostream> #include <random> using namespace std; using namespace std::chrono; using DB = Ginseng::Database<>; using Ginseng::Not; using EntID = DB::EntID; using ComID = DB::ComID; template <typename T> void print(T&& t) { //cout << t << endl; } template <typename D, typename F> D bench(F&& f) { auto b = steady_clock::now(); f(); auto e = steady_clock::now(); return duration_cast<D>(e-b); } struct A { volatile int a; }; struct B { volatile double b; }; struct C { string c; }; mt19937& rng(); void random_action(DB& db); void add_random_entity(DB& db); void add_random_component(DB& db, EntID eid); void random_query(DB& db); void random_delete(DB& db); void random_delete_entity(DB& db); void random_delete_component(DB& db); void random_slaughter(DB& db); int main() { DB db; auto work = [&] { for (int i=0; i<100000; ++i) { random_action(db); } }; cout << bench<milliseconds>(work).count() << endl; } mt19937& rng() { static mt19937 mt; return mt; } void random_action(DB& db) { int roll = rng()()%50; switch (roll) { case 0: random_query(db); break; case 1: random_delete(db); break; case 2: random_slaughter(db); break; default: add_random_entity(db); break; } } void add_random_entity(DB& db) { EntID eid = db.makeEntity(); for (int i=0; i<3; ++i) { int roll = rng()()%3; if (roll==0) continue; add_random_component(db, eid); } } void add_random_component(DB& db, EntID eid) { int roll = rng()()%3; static string strs[] = {"meow","honk","goro"}; switch (roll) { case 0: db.makeComponent(eid, A{int(rng()()%10)}); break; case 1: db.makeComponent(eid, B{(rng()()%100)/100.0}); break; case 2: db.makeComponent(eid, C{strs[rng()()%3]}); break; } } void random_query(DB& db) { int roll = rng()()%15; switch (roll) { case 0: print(db.query<>().size()); break; case 1: print(db.query<A>().size()); break; case 2: print(db.query<B>().size()); break; case 3: print(db.query<C>().size()); break; case 4: print(db.query<A,B>().size()); break; case 5: print(db.query<A,C>().size()); break; case 6: print(db.query<B,C>().size()); break; case 7: print(db.query<A,B,C>().size()); break; case 8: print(db.query<Not<A>>().size()); break; case 9: print(db.query<Not<B>>().size()); break; case 10: print(db.query<Not<C>>().size()); break; case 11: print(db.query<Not<A>,B>().size()); break; case 12: print(db.query<Not<A>,C>().size()); break; case 13: print(db.query<Not<B>,C>().size()); break; case 14: print(db.query<Not<A>,B,C>().size()); break; } } void random_delete(DB& db) { int roll = rng()()%2; if (roll==0) { random_delete_entity(db); } else { random_delete_component(db); } } void random_delete_entity(DB& db) { auto all = db.query<>(); if (all.empty()) return; int roll = rng()()%all.size(); db.eraseEntity(get<0>(all[roll])); } void random_delete_component(DB& db) { int roll = rng()()%3; switch (roll) { case 0: { auto all = db.query<A>(); if (all.empty()) return; int roll = rng()()%all.size(); db.eraseComponent(get<1>(all[roll]).id()); } break; case 1: { auto all = db.query<B>(); if (all.empty()) return; int roll = rng()()%all.size(); db.eraseComponent(get<1>(all[roll]).id()); } break; case 2: { auto all = db.query<C>(); if (all.empty()) return; int roll = rng()()%all.size(); db.eraseComponent(get<1>(all[roll]).id()); } break; } } void random_slaughter(DB& db) { int roll = rng()()%3; switch (roll) { case 0: { auto all = db.query<A>(); for (auto&& e : all) db.eraseEntity(get<0>(e)); } break; case 1: { auto all = db.query<B>(); for (auto&& e : all) db.eraseEntity(get<0>(e)); } break; case 2: { auto all = db.query<C>(); for (auto&& e : all) db.eraseEntity(get<0>(e)); } break; } } <|endoftext|>
<commit_before>#include "BehaviorTree.h" using namespace BT; int main(int argc, char **argv) { try { int TickPeriod_milliseconds = 1000; ActionTestNode* test1 = new ActionTestNode("A1"); ActionTestNode*test2 = new ActionTestNode("A2"); ActionTestNode*test3 = new ActionTestNode("A3"); ActionTestNode*test4 = new ActionTestNode("A4"); SequenceStarNode* sequence1 = new SequenceStarNode("seq1"); SelectorStarNode* selector1 = new SelectorStarNode("sel1"); SelectorStarNode* selector2 = new SelectorStarNode("sel12"); DecoratorRetryNode* dec = new DecoratorRetryNode("retry",2); SequenceStarNode* root = new SequenceStarNode("root"); test1->SetBehavior(Success); test1->SetTime(3); test2->SetBehavior(Success); test2->SetTime(2); test3->SetBehavior(Failure); test4->SetBehavior(Success); selector1->AddChild(test1); selector1->AddChild(test2); dec->AddChild(test1); root->AddChild(test3); root->AddChild(selector1); Execute(root, TickPeriod_milliseconds);//from BehaviorTree.cpp } catch (BehaviorTreeException& Exception) { std::cout << Exception.what() << std::endl; } return 0; } <commit_msg>Update test.cpp<commit_after>#include "BehaviorTree.h" using namespace BT; int main(int argc, char **argv) { try { int TickPeriod_milliseconds = 1000; ActionTestNode* test1 = new ActionTestNode("A1"); ActionTestNode* test2 = new ActionTestNode("A2"); ActionTestNode* test3 = new ActionTestNode("A3"); ActionTestNode* test4 = new ActionTestNode("A4"); SequenceStarNode* sequence1 = new SequenceStarNode("seq1"); SelectorStarNode* selector1 = new SelectorStarNode("sel1"); SelectorStarNode* selector2 = new SelectorStarNode("sel12"); SequenceStarNode* root = new SequenceStarNode("root"); test1->SetBehavior(Success); test1->SetTime(3); test2->SetBehavior(Success); test2->SetTime(2); test3->SetBehavior(Failure); test4->SetBehavior(Success); selector1->AddChild(test1); selector1->AddChild(test2); selector2->AddChild(test3); selector2->AddChild(test4); root->AddChild(selector1); root->AddChild(selector2); Execute(root, TickPeriod_milliseconds);//from BehaviorTree.cpp } catch (BehaviorTreeException& Exception) { std::cout << Exception.what() << std::endl; } return 0; } <|endoftext|>
<commit_before>/// /// @file test.cpp /// /// Copyright (C) 2014 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primecount.hpp> #include <primecount-internal.hpp> #include <primesieve.hpp> #include <stdint.h> #include <iostream> #include <cstdlib> #include <string> #include <stdexcept> #include <sstream> #include <ctime> #ifdef _OPENMP #include <omp.h> #endif /// For types: f1(x) , f2(x) #define CHECK_11(f1, f2) check_equal(#f1, x, f1 (x), f2 (x)) /// For types: f1(x) , f2(x, threads) #define CHECK_12(f1, f2) check_equal(#f1, x, f1 (x), f2 (x, get_num_threads())) /// For types: f1(x, threads) , f2(x, threads) #define CHECK_22(f1, f2) check_equal(#f1, x, f1 (x, get_num_threads()), f2 (x, get_num_threads())) #define CHECK_EQUAL(f1, f2, check, iters) \ { \ cout << "Testing " << #f1 << "(x)" << flush; \ \ /* test for 0 <= x < 10000 */ \ for (int64_t x = 0; x < 10000; x++) \ check(f1, f2); \ \ int64_t x = 0; \ /* test using random increment */ \ for (int64_t i = 0; i < iters; i++, x += get_rand()) \ { \ check(f1, f2); \ double percent = 100.0 * (i + 1.0) / iters; \ cout << "\rTesting " << #f1 "(x) " << (int) percent << "%" << flush; \ } \ \ cout << endl; \ } using namespace std; using namespace primecount; using primesieve::parallel_nth_prime; namespace { int get_rand() { // 0 <= get_rand() < 10^7 return (rand() % 10000) * 1000 + 1; } void check_equal(const string& f1, int64_t x, int64_t res1, int64_t res2) { if (res1 != res2) { ostringstream oss; oss << f1 << "(" << x << ") = " << res1 << " is an error, the correct result is " << res2; throw runtime_error(oss.str()); } } void test_phi_thread_safety(int64_t iters) { #ifdef _OPENMP cout << "Testing phi(x, a)" << flush; int nested_threads = 2; int64_t single_thread_sum = 0; int64_t multi_thread_sum = 0; int64_t base = 1000000; omp_set_nested(true); #pragma omp parallel for reduction(+: multi_thread_sum) for (int64_t i = 0; i < iters; i++) multi_thread_sum += pi_legendre(base + i, nested_threads); omp_set_nested(false); for (int64_t i = 0; i < iters; i++) single_thread_sum += pi_legendre(base + i, 1); if (multi_thread_sum != single_thread_sum) throw runtime_error("Error: multi-threaded phi(x, a) is broken."); std::cout << "\rTesting phi(x, a) 100%" << endl; #endif /* _OPENMP */ } } // namespace namespace primecount { bool test() { srand((unsigned) time(0)); try { test_phi_thread_safety(100); CHECK_EQUAL(pi_legendre, pi_primesieve, CHECK_22, 100); CHECK_EQUAL(pi_meissel, pi_legendre, CHECK_22, 400); CHECK_EQUAL(pi_lehmer, pi_meissel, CHECK_22, 400); CHECK_EQUAL(pi_lehmer2, pi_lehmer, CHECK_22, 200); CHECK_EQUAL(pi_lmo1, pi_meissel, CHECK_12, 200); CHECK_EQUAL(pi_lmo2, pi_meissel, CHECK_12, 200); CHECK_EQUAL(pi_lmo3, pi_meissel, CHECK_12, 300); CHECK_EQUAL(pi_lmo4, pi_meissel, CHECK_12, 300); CHECK_EQUAL(pi_lmo5, pi_meissel, CHECK_12, 400); CHECK_EQUAL(pi_lmo_parallel1, pi_meissel, CHECK_22, 400); CHECK_EQUAL(pi_lmo_parallel2, pi_meissel, CHECK_22, 400); CHECK_EQUAL(pi_lmo_parallel3, pi_meissel, CHECK_22, 400); CHECK_EQUAL(pi_deleglise_rivat1, pi_lmo_parallel3, CHECK_12, 600); CHECK_EQUAL(pi_deleglise_rivat2, pi_lmo_parallel3, CHECK_12, 600); CHECK_EQUAL(pi_deleglise_rivat3, pi_lmo_parallel3, CHECK_12, 600); CHECK_EQUAL(pi_deleglise_rivat_parallel1, pi_lmo_parallel3, CHECK_22, 900); CHECK_EQUAL(pi_deleglise_rivat_parallel2, pi_lmo_parallel3, CHECK_22, 900); CHECK_EQUAL(pi_deleglise_rivat_parallel3, pi_lmo_parallel3, CHECK_22, 900); CHECK_EQUAL(nth_prime, parallel_nth_prime, CHECK_11, 100); } catch (runtime_error& e) { cerr << endl << e.what() << endl; return false; } cout << "All tests passed successfully!" << endl; return true; } } // namespace primecount <commit_msg>Refactoring<commit_after>/// /// @file test.cpp /// /// Copyright (C) 2014 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primecount.hpp> #include <primecount-internal.hpp> #include <primesieve.hpp> #include <stdint.h> #include <iostream> #include <cstdlib> #include <string> #include <stdexcept> #include <sstream> #include <ctime> #ifdef _OPENMP #include <omp.h> #endif /// For types: f1(x) , f2(x) #define CHECK_11(f1, f2) check_equal(#f1, x, f1 (x), f2 (x)) /// For types: f1(x) , f2(x, threads) #define CHECK_12(f1, f2) check_equal(#f1, x, f1 (x), f2 (x, get_num_threads())) /// For types: f1(x, threads) , f2(x, threads) #define CHECK_22(f1, f2) check_equal(#f1, x, f1 (x, get_num_threads()), f2 (x, get_num_threads())) #define CHECK_EQUAL(f1, f2, check, iters) \ { \ cout << "Testing " << #f1 << "(x)" << flush; \ \ /* test for 0 <= x < 10000 */ \ for (int64_t x = 0; x < 10000; x++) \ check(f1, f2); \ \ int64_t x = 0; \ /* test using random increment */ \ for (int64_t i = 0; i < iters; i++, x += get_rand()) \ { \ check(f1, f2); \ double percent = 100.0 * (i + 1.0) / iters; \ cout << "\rTesting " << #f1 "(x) " << (int) percent << "%" << flush; \ } \ \ cout << endl; \ } using namespace std; using namespace primecount; using primesieve::parallel_nth_prime; namespace { int get_rand() { // 0 <= get_rand() < 10^7 return (rand() % 10000) * 1000 + 1; } void check_equal(const string& f1, int64_t x, int64_t res1, int64_t res2) { if (res1 != res2) { ostringstream oss; oss << f1 << "(" << x << ") = " << res1 << " is an error, the correct result is " << res2; throw runtime_error(oss.str()); } } void test_phi_thread_safety(int64_t iters) { #ifdef _OPENMP cout << "Testing phi(x, a)" << flush; int nested_threads = 2; int64_t single_thread_sum = 0; int64_t multi_thread_sum = 0; int64_t base = 1000000; omp_set_nested(true); #pragma omp parallel for reduction(+: multi_thread_sum) for (int64_t i = 0; i < iters; i++) multi_thread_sum += pi_legendre(base + i, nested_threads); omp_set_nested(false); for (int64_t i = 0; i < iters; i++) single_thread_sum += pi_legendre(base + i, 1); if (multi_thread_sum != single_thread_sum) throw runtime_error("Error: multi-threaded phi(x, a) is broken."); std::cout << "\rTesting phi(x, a) 100%" << endl; #endif } } // namespace namespace primecount { bool test() { srand((unsigned) time(0)); try { test_phi_thread_safety(100); CHECK_EQUAL(pi_legendre, pi_primesieve, CHECK_22, 100); CHECK_EQUAL(pi_meissel, pi_legendre, CHECK_22, 400); CHECK_EQUAL(pi_lehmer, pi_meissel, CHECK_22, 400); CHECK_EQUAL(pi_lehmer2, pi_lehmer, CHECK_22, 200); CHECK_EQUAL(pi_lmo1, pi_meissel, CHECK_12, 200); CHECK_EQUAL(pi_lmo2, pi_meissel, CHECK_12, 200); CHECK_EQUAL(pi_lmo3, pi_meissel, CHECK_12, 300); CHECK_EQUAL(pi_lmo4, pi_meissel, CHECK_12, 300); CHECK_EQUAL(pi_lmo5, pi_meissel, CHECK_12, 400); CHECK_EQUAL(pi_lmo_parallel1, pi_meissel, CHECK_22, 400); CHECK_EQUAL(pi_lmo_parallel2, pi_meissel, CHECK_22, 400); CHECK_EQUAL(pi_lmo_parallel3, pi_meissel, CHECK_22, 400); CHECK_EQUAL(pi_deleglise_rivat1, pi_lmo_parallel3, CHECK_12, 600); CHECK_EQUAL(pi_deleglise_rivat2, pi_lmo_parallel3, CHECK_12, 600); CHECK_EQUAL(pi_deleglise_rivat3, pi_lmo_parallel3, CHECK_12, 600); CHECK_EQUAL(pi_deleglise_rivat_parallel1, pi_lmo_parallel3, CHECK_22, 900); CHECK_EQUAL(pi_deleglise_rivat_parallel2, pi_lmo_parallel3, CHECK_22, 900); CHECK_EQUAL(pi_deleglise_rivat_parallel3, pi_lmo_parallel3, CHECK_22, 900); CHECK_EQUAL(nth_prime, parallel_nth_prime, CHECK_11, 70); } catch (runtime_error& e) { cerr << endl << e.what() << endl; return false; } cout << "All tests passed successfully!" << endl; return true; } } // namespace primecount <|endoftext|>
<commit_before>/// /// @file test.cpp /// @brief primesum integration tests. /// /// Copyright (C) 2016 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primesum-internal.hpp> #include <primesum.hpp> #include <int128.hpp> #include <stdint.h> #include <iostream> #include <cstdlib> #include <string> #include <exception> #include <sstream> #include <ctime> #ifdef _OPENMP #include <omp.h> #endif /// For types: f1(x) , f2(x) #define CHECK_11(f1, f2) check_equal(#f1, x, f1 (x), f2 (x)) /// For types: f1(x) , f2(x, threads) #define CHECK_21(f1, f2) check_equal(#f1, x, f1 (x, get_num_threads()), f2 (x)) /// For types: f1(x, threads) , f2(x, threads) #define CHECK_22(f1, f2) check_equal(#f1, x, f1 (x, get_num_threads()), f2 (x, get_num_threads())) #define CHECK_EQUAL(f1, f2, check, iters) \ { \ cout << "Testing " << #f1 << "(x)" << flush; \ \ /* test for 0 <= x < 10000 */ \ for (int64_t x = 0; x < 10000; x++) \ check(f1, f2); \ \ int64_t x = 0; \ /* test using random increment */ \ for (int64_t i = 0; i < iters; i++, x += get_rand()) \ { \ check(f1, f2); \ double percent = 100.0 * (i + 1.0) / iters; \ cout << "\rTesting " << #f1 "(x) " << (int) percent << "%" << flush; \ } \ \ cout << endl; \ } using namespace std; using namespace primesum; namespace { int get_rand() { // 0 <= get_rand() < 10^7 return (rand() % 10000) * 1000 + 1; } void check_equal(const string& f1, int64_t x, int64_t res1, int64_t res2) { if (res1 != res2) { ostringstream oss; oss << f1 << "(" << x << ") = " << res1 << " is an error, the correct result is " << res2; throw primesum_error(oss.str()); } } void test_phi_thread_safety(int64_t iters) { #ifdef _OPENMP cout << "Testing phi(x, a)" << flush; int64_t sum1 = 0; int64_t sum2 = 0; for (int64_t i = 0; i < iters; i++) sum1 += pi_legendre(10000000 + i, 1); #pragma omp parallel for reduction(+: sum2) for (int64_t i = 0; i < iters; i++) sum2 += pi_legendre(10000000 + i, 1); if (sum1 != sum2) throw primesum_error("Error: multi-threaded phi(x, a) is broken."); std::cout << "\rTesting phi(x, a) 100%" << endl; #endif } } // namespace namespace primesum { bool test() { set_print_status(false); srand(static_cast<unsigned>(time(0))); try { test_phi_thread_safety(100); CHECK_EQUAL(pi_lmo2, pi_lmo1, CHECK_11, 100); CHECK_EQUAL(pi_lmo4, pi_lmo2, CHECK_11, 300); CHECK_EQUAL(pi_lmo5, pi_lmo4, CHECK_11, 400); CHECK_EQUAL(pi_lmo_parallel2, pi_lmo5, CHECK_21, 600); CHECK_EQUAL(pi_deleglise_rivat_parallel3, pi_lmo_parallel2, CHECK_22, 900); } catch (exception& e) { cerr << endl << e.what() << endl; return false; } cout << "All tests passed successfully!" << endl; return true; } } // namespace primesum <commit_msg>Add more tests<commit_after>/// /// @file test.cpp /// @brief primesum integration tests. /// /// Copyright (C) 2016 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primesum-internal.hpp> #include <primesum.hpp> #include <int128.hpp> #include <stdint.h> #include <iostream> #include <cstdlib> #include <string> #include <exception> #include <sstream> #include <ctime> #ifdef _OPENMP #include <omp.h> #endif /// For types: f1(x) , f2(x) #define CHECK_11(f1, f2) check_equal(#f1, x, f1 (x), f2 (x)) /// For types: f1(x) , f2(x, threads) #define CHECK_21(f1, f2) check_equal(#f1, x, f1 (x, get_num_threads()), f2 (x)) /// For types: f1(x, threads) , f2(x, threads) #define CHECK_22(f1, f2) check_equal(#f1, x, f1 (x, get_num_threads()), f2 (x, get_num_threads())) #define CHECK_EQUAL(f1, f2, check, iters) \ { \ cout << "Testing " << #f1 << "(x)" << flush; \ \ /* test for 0 <= x < 10000 */ \ for (int64_t x = 0; x < 10000; x++) \ check(f1, f2); \ \ int64_t x = 0; \ /* test using random increment */ \ for (int64_t i = 0; i < iters; i++, x += get_rand()) \ { \ check(f1, f2); \ double percent = 100.0 * (i + 1.0) / iters; \ cout << "\rTesting " << #f1 "(x) " << (int) percent << "%" << flush; \ } \ \ cout << endl; \ } using namespace std; using namespace primesum; namespace { int get_rand() { // 0 <= get_rand() < 10^7 return (rand() % 10000) * 1000 + 1; } void check_equal(const string& f1, int64_t x, int64_t res1, int64_t res2) { if (res1 != res2) { ostringstream oss; oss << f1 << "(" << x << ") = " << res1 << " is an error, the correct result is " << res2; throw primesum_error(oss.str()); } } void test_phi_thread_safety(int64_t iters) { #ifdef _OPENMP cout << "Testing phi(x, a)" << flush; int64_t sum1 = 0; int64_t sum2 = 0; for (int64_t i = 0; i < iters; i++) sum1 += pi_legendre(10000000 + i, 1); #pragma omp parallel for reduction(+: sum2) for (int64_t i = 0; i < iters; i++) sum2 += pi_legendre(10000000 + i, 1); if (sum1 != sum2) throw primesum_error("Error: multi-threaded phi(x, a) is broken."); std::cout << "\rTesting phi(x, a) 100%" << endl; #endif } } // namespace namespace primesum { bool test() { set_print_status(false); srand(static_cast<unsigned>(time(0))); try { test_phi_thread_safety(100); CHECK_EQUAL(pi_lmo1, prime_sum_tiny, CHECK_11, 50); CHECK_EQUAL(pi_lmo2, pi_lmo1, CHECK_11, 100); CHECK_EQUAL(pi_lmo4, pi_lmo2, CHECK_11, 300); CHECK_EQUAL(pi_lmo5, pi_lmo4, CHECK_11, 400); CHECK_EQUAL(pi_lmo_parallel2, pi_lmo5, CHECK_21, 600); CHECK_EQUAL(pi_deleglise_rivat_parallel3, pi_lmo_parallel2, CHECK_22, 900); } catch (exception& e) { cerr << endl << e.what() << endl; return false; } cout << "All tests passed successfully!" << endl; return true; } } // namespace primesum <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://www.qt.io/licensing. For further information ** use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "jsonwizard.h" #include "jsonwizardexpander.h" #include "jsonwizardgeneratorfactory.h" #include <utils/algorithm.h> #include <utils/qtcassert.h> #include <QFileInfo> #include <QMessageBox> #include <QVariant> namespace ProjectExplorer { JsonWizard::JsonWizard(QWidget *parent) : Utils::Wizard(parent), m_expander(new Internal::JsonWizardExpander(this)) { } JsonWizard::~JsonWizard() { qDeleteAll(m_generators); delete m_expander; } void JsonWizard::addGenerator(JsonWizardGenerator *gen) { QTC_ASSERT(gen, return); QTC_ASSERT(!m_generators.contains(gen), return); m_generators.append(gen); } Utils::AbstractMacroExpander *JsonWizard::expander() const { return m_expander; } void JsonWizard::resetFileList() { m_files.clear(); } JsonWizard::GeneratorFiles JsonWizard::fileList() { QString errorMessage; GeneratorFiles list; QString targetPath = value(QLatin1String("TargetPath")).toString(); if (targetPath.isEmpty()) { errorMessage = tr("Could not determine target path. \"TargetPath\", \"Path\", or " "\"ProjectName\" were not set on any page."); return list; } if (m_files.isEmpty()) { emit preGenerateFiles(); foreach (JsonWizardGenerator *gen, m_generators) { Core::GeneratedFiles tmp = gen->fileList(m_expander, value(QStringLiteral("WizardDir")).toString(), targetPath, &errorMessage); if (!errorMessage.isEmpty()) break; list.append(Utils::transform(tmp, [&gen](const Core::GeneratedFile &f) { return JsonWizard::GeneratorFile(f, gen); })); } if (errorMessage.isEmpty()) m_files = list; emit postGenerateFiles(m_files); } if (!errorMessage.isEmpty()) { QMessageBox::critical(this, tr("File Generation Failed"), tr("The wizard failed to generate files.<br>" "The error message was: \"%1\".").arg(errorMessage)); reject(); return GeneratorFiles(); } return m_files; } QVariant JsonWizard::value(const QString &n) const { QVariant v = property(n.toUtf8()); if (v.isValid()) { if (v.type() == QVariant::String) return Utils::expandMacros(v.toString(), m_expander); else return v; } if (hasField(n)) return field(n); // Can not contain macros! return QVariant(); } void JsonWizard::setValue(const QString &key, const QVariant &value) { setProperty(key.toUtf8(), value); } bool JsonWizard::boolFromVariant(const QVariant &v, Utils::AbstractMacroExpander *expander) { if (v.type() == QVariant::String) return !Utils::expandMacros(v.toString(), expander).isEmpty(); return v.toBool(); } void JsonWizard::removeAttributeFromAllFiles(Core::GeneratedFile::Attribute a) { for (int i = 0; i < m_files.count(); ++i) m_files[i].file.setAttributes(m_files.at(i).file.attributes() ^ a); } void JsonWizard::accept() { Utils::Wizard::accept(); QString errorMessage; GeneratorFiles list = fileList(); if (list.isEmpty()) return; emit prePromptForOverwrite(m_files); JsonWizardGenerator::OverwriteResult overwrite = JsonWizardGenerator::promptForOverwrite(&list, &errorMessage); if (overwrite == JsonWizardGenerator::OverwriteError) { if (!errorMessage.isEmpty()) QMessageBox::warning(this, tr("Failed to Overwrite Files"), errorMessage); return; } emit preFormatFiles(m_files); if (!JsonWizardGenerator::formatFiles(this, &list, &errorMessage)) { if (!errorMessage.isEmpty()) QMessageBox::warning(this, tr("Failed to Format Files"), errorMessage); return; } emit preWriteFiles(m_files); if (!JsonWizardGenerator::writeFiles(this, &list, &errorMessage)) { if (!errorMessage.isEmpty()) QMessageBox::warning(this, tr("Failed to Write Files"), errorMessage); return; } emit postProcessFiles(m_files); if (!JsonWizardGenerator::postWrite(this, &list, &errorMessage)) { if (!errorMessage.isEmpty()) QMessageBox::warning(this, tr("Failed to Post-Process Files"), errorMessage); return; } emit filesReady(m_files); } } // namespace ProjectExplorer <commit_msg>JsonWizard: Fix a error message<commit_after>/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://www.qt.io/licensing. For further information ** use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "jsonwizard.h" #include "jsonwizardexpander.h" #include "jsonwizardgeneratorfactory.h" #include <utils/algorithm.h> #include <utils/qtcassert.h> #include <QFileInfo> #include <QMessageBox> #include <QVariant> namespace ProjectExplorer { JsonWizard::JsonWizard(QWidget *parent) : Utils::Wizard(parent), m_expander(new Internal::JsonWizardExpander(this)) { } JsonWizard::~JsonWizard() { qDeleteAll(m_generators); delete m_expander; } void JsonWizard::addGenerator(JsonWizardGenerator *gen) { QTC_ASSERT(gen, return); QTC_ASSERT(!m_generators.contains(gen), return); m_generators.append(gen); } Utils::AbstractMacroExpander *JsonWizard::expander() const { return m_expander; } void JsonWizard::resetFileList() { m_files.clear(); } JsonWizard::GeneratorFiles JsonWizard::fileList() { QString errorMessage; GeneratorFiles list; QString targetPath = value(QLatin1String("TargetPath")).toString(); if (targetPath.isEmpty()) { errorMessage = tr("Could not determine target path. \"TargetPath\" was not set on any page."); return list; } if (m_files.isEmpty()) { emit preGenerateFiles(); foreach (JsonWizardGenerator *gen, m_generators) { Core::GeneratedFiles tmp = gen->fileList(m_expander, value(QStringLiteral("WizardDir")).toString(), targetPath, &errorMessage); if (!errorMessage.isEmpty()) break; list.append(Utils::transform(tmp, [&gen](const Core::GeneratedFile &f) { return JsonWizard::GeneratorFile(f, gen); })); } if (errorMessage.isEmpty()) m_files = list; emit postGenerateFiles(m_files); } if (!errorMessage.isEmpty()) { QMessageBox::critical(this, tr("File Generation Failed"), tr("The wizard failed to generate files.<br>" "The error message was: \"%1\".").arg(errorMessage)); reject(); return GeneratorFiles(); } return m_files; } QVariant JsonWizard::value(const QString &n) const { QVariant v = property(n.toUtf8()); if (v.isValid()) { if (v.type() == QVariant::String) return Utils::expandMacros(v.toString(), m_expander); else return v; } if (hasField(n)) return field(n); // Can not contain macros! return QVariant(); } void JsonWizard::setValue(const QString &key, const QVariant &value) { setProperty(key.toUtf8(), value); } bool JsonWizard::boolFromVariant(const QVariant &v, Utils::AbstractMacroExpander *expander) { if (v.type() == QVariant::String) return !Utils::expandMacros(v.toString(), expander).isEmpty(); return v.toBool(); } void JsonWizard::removeAttributeFromAllFiles(Core::GeneratedFile::Attribute a) { for (int i = 0; i < m_files.count(); ++i) m_files[i].file.setAttributes(m_files.at(i).file.attributes() ^ a); } void JsonWizard::accept() { Utils::Wizard::accept(); QString errorMessage; GeneratorFiles list = fileList(); if (list.isEmpty()) return; emit prePromptForOverwrite(m_files); JsonWizardGenerator::OverwriteResult overwrite = JsonWizardGenerator::promptForOverwrite(&list, &errorMessage); if (overwrite == JsonWizardGenerator::OverwriteError) { if (!errorMessage.isEmpty()) QMessageBox::warning(this, tr("Failed to Overwrite Files"), errorMessage); return; } emit preFormatFiles(m_files); if (!JsonWizardGenerator::formatFiles(this, &list, &errorMessage)) { if (!errorMessage.isEmpty()) QMessageBox::warning(this, tr("Failed to Format Files"), errorMessage); return; } emit preWriteFiles(m_files); if (!JsonWizardGenerator::writeFiles(this, &list, &errorMessage)) { if (!errorMessage.isEmpty()) QMessageBox::warning(this, tr("Failed to Write Files"), errorMessage); return; } emit postProcessFiles(m_files); if (!JsonWizardGenerator::postWrite(this, &list, &errorMessage)) { if (!errorMessage.isEmpty()) QMessageBox::warning(this, tr("Failed to Post-Process Files"), errorMessage); return; } emit filesReady(m_files); } } // namespace ProjectExplorer <|endoftext|>
<commit_before>// // This file is part of the Marble Desktop Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2008 Dennis Nienhüser <[email protected]> // #include "NavigationFloatItem.h" #include <QtCore/QDebug> #include <QtCore/QRect> #include <QtGui/QMouseEvent> #include <QtGui/QPixmap> #include <QtGui/QSlider> #include <QtGui/QWidget> #include "GeoPainter.h" #include "ViewportParams.h" #include "MarbleWidget.h" #include "MarbleMap.h" using namespace Marble; const int defaultMinZoom = 900; const int defaultMaxZoom = 2400; NavigationFloatItem::NavigationFloatItem(const QPointF &point, const QSizeF &size) : AbstractFloatItem(point, size), m_marbleWidget(0), m_navigationParent(0), m_oldViewportRadius(0) { // Plugin is enabled by default setEnabled( true ); // Plugin is not visible by default setVisible( false ); #ifdef MARBLE_SMALL_SCREEN setFrame( FrameGraphicsItem::RectFrame ); #else setFrame( FrameGraphicsItem::RoundedRectFrame ); #endif // This sets the padding to the minimum possible for this Frame setPadding( 0 ); } NavigationFloatItem::~NavigationFloatItem() { delete m_navigationParent; } QStringList NavigationFloatItem::backendTypes() const { return QStringList("navigation"); } QString NavigationFloatItem::name() const { return tr("Navigation"); } QString NavigationFloatItem::guiString() const { return tr("&Navigation"); } QString NavigationFloatItem::nameId() const { return QString("navigation"); } QString NavigationFloatItem::description() const { return tr("A mouse control to zoom and move the map"); } QIcon NavigationFloatItem::icon() const { return QIcon(); } void NavigationFloatItem::initialize() { m_navigationParent = new QWidget(0); m_navigationParent->setFixedSize(size().toSize() - QSize(2 * padding(), 2 * padding())); m_navigationWidget.setupUi(m_navigationParent); #ifndef MARBLE_SMALL_SCREEN connect( m_navigationWidget.zoomSlider, SIGNAL( sliderPressed() ), this, SLOT( adjustForAnimation() ) ); connect( m_navigationWidget.zoomSlider, SIGNAL( sliderReleased() ), this, SLOT( adjustForStill() ) ); connect( m_navigationWidget.zoomSlider, SIGNAL( valueChanged( int ) ), this, SLOT( updateButtons( int ) ) ); // Other signal/slot connections will be initialized when the marble widget is known #endif } bool NavigationFloatItem::isInitialized() const { return m_navigationParent != 0; } void NavigationFloatItem::changeViewport( ViewportParams *viewport ) { if ( viewport->radius() != m_oldViewportRadius ) { m_oldViewportRadius = viewport->radius(); // The slider depends on the map state (zoom factor) update(); } } void NavigationFloatItem::paintContent( GeoPainter *painter, ViewportParams *viewport, const QString& renderPos, GeoSceneLayer * layer ) { Q_UNUSED( viewport ); Q_UNUSED( layer ); Q_UNUSED( renderPos ); // Paint widget without a background m_navigationParent->render( painter, QPoint( padding(), padding() ), QRegion(),QWidget::RenderFlags(QWidget::DrawChildren)); } bool NavigationFloatItem::eventFilter(QObject *object, QEvent *e) { if ( !enabled() || !visible() ) { return false; } MarbleWidget *widget = dynamic_cast<MarbleWidget*> (object); if ( !widget ) { return AbstractFloatItem::eventFilter(object, e); } if ( m_marbleWidget != widget ) { // Delayed initialization m_marbleWidget = widget; int minZoom = m_marbleWidget->map()->minimumZoom(); int maxZoom = m_marbleWidget->map()->maximumZoom(); //m_navigationWidget.zoomSlider->setRange(minZoom, maxZoom); #ifndef MARBLE_SMALL_SCREEN m_navigationWidget.zoomSlider->setMinimum(minZoom); m_navigationWidget.zoomSlider->setMaximum(maxZoom); m_navigationWidget.zoomSlider->setValue(m_marbleWidget->map()->zoom()); m_navigationWidget.zoomSlider->setTickInterval((maxZoom - minZoom) / 15); #endif updateButtons(m_marbleWidget->map()->zoom()); connect(m_marbleWidget->map(), SIGNAL(zoomChanged(int)), this, SLOT(zoomChanged(int))); connect(m_marbleWidget, SIGNAL( themeChanged( QString ) ), this, SLOT( selectTheme( QString ) ) ); connect(m_navigationWidget.zoomInButton, SIGNAL( clicked() ), m_marbleWidget, SLOT( zoomIn() ) ); connect(m_navigationWidget.zoomOutButton, SIGNAL( clicked() ), m_marbleWidget, SLOT( zoomOut() ) ); #ifndef MARBLE_SMALL_SCREEN connect(m_navigationWidget.zoomSlider, SIGNAL(sliderMoved(int)), m_marbleWidget, SLOT(zoomView(int))); connect(m_navigationWidget.moveLeftButton, SIGNAL( clicked() ), m_marbleWidget, SLOT( moveLeft() ) ); connect(m_navigationWidget.moveRightButton, SIGNAL( clicked() ), m_marbleWidget, SLOT( moveRight() ) ); connect(m_navigationWidget.moveUpButton, SIGNAL( clicked() ), m_marbleWidget, SLOT( moveUp() ) ); connect(m_navigationWidget.moveDownButton, SIGNAL( clicked() ), m_marbleWidget, SLOT( moveDown() ) ); #endif connect(m_navigationWidget.goHomeButton, SIGNAL( clicked() ), m_marbleWidget, SLOT( goHome() ) ); } Q_ASSERT(m_marbleWidget); if ( e->type() == QEvent::MouseButtonDblClick || e->type() == QEvent::MouseMove || e->type() == QEvent::MouseButtonPress || e->type() == QEvent::MouseButtonRelease ) { // Mouse events are forwarded to the underlying widget QMouseEvent *event = static_cast<QMouseEvent*> (e); QRectF floatItemRect = QRectF( positivePosition(), size() ); QPoint shiftedPos = event->pos() - floatItemRect.topLeft().toPoint() - QPoint(padding(), padding()); if ( floatItemRect.contains(event->pos()) ) { QWidget *child = m_navigationParent->childAt( shiftedPos ); if ( child ) { m_marbleWidget->setCursor( Qt::ArrowCursor ); shiftedPos -= child->pos(); // transform to children's coordinates QMouseEvent shiftedEvent = QMouseEvent( e->type(), shiftedPos, event->globalPos(), event->button(), event->buttons(), event->modifiers() ); if ( QApplication::sendEvent( child, &shiftedEvent ) ) { return true; } } } } return AbstractFloatItem::eventFilter(object, e); } void NavigationFloatItem::zoomChanged(int level) { #ifndef MARBLE_SMALL_SCREEN m_navigationWidget.zoomSlider->setValue(level); #endif } void NavigationFloatItem::selectTheme(QString theme) { Q_UNUSED(theme); if ( m_marbleWidget ) { #ifndef MARBLE_SMALL_SCREEN int minZoom = m_marbleWidget->map()->minimumZoom(); int maxZoom = m_marbleWidget->map()->maximumZoom(); m_navigationWidget.zoomSlider->setRange(minZoom, maxZoom); m_navigationWidget.zoomSlider->setValue(m_marbleWidget->map()->zoom()); updateButtons(m_navigationWidget.zoomSlider->value()); #else updateButtons(m_marbleWidget->map()->zoom()); #endif } } void NavigationFloatItem::adjustForAnimation() { if ( !m_marbleWidget ) { return; } m_marbleWidget->setViewContext( Animation ); } void NavigationFloatItem::adjustForStill() { if ( !m_marbleWidget ) { return; } m_marbleWidget->setViewContext( Still ); if ( m_marbleWidget->mapQuality( Still ) != m_marbleWidget->mapQuality( Animation ) ) { m_marbleWidget->updateChangedMap(); } } void NavigationFloatItem::updateButtons( int value ) { int minZoom = defaultMinZoom; int maxZoom = defaultMaxZoom; #ifdef MARBLE_SMALL_SCREEN if ( m_marbleWidget ) { int minZoom = m_marbleWidget->map()->minimumZoom(); int maxZoom = m_marbleWidget->map()->maximumZoom(); } #else int minZoom = m_navigationWidget.zoomSlider->minimum(); int maxZoom = m_navigationWidget.zoomSlider->maximum(); #endif if ( value <= minZoom ) { m_navigationWidget.zoomInButton->setEnabled( true ); m_navigationWidget.zoomOutButton->setEnabled( false ); } else if ( value >= maxZoom ) { m_navigationWidget.zoomInButton->setEnabled( false ); m_navigationWidget.zoomOutButton->setEnabled( true ); } else { m_navigationWidget.zoomInButton->setEnabled( true ); m_navigationWidget.zoomOutButton->setEnabled( true ); } if (m_marbleWidget) { // Trigger a repaint of the float item. Otherwise button state updates // are delayed QRectF floatItemRect = QRectF(positivePosition(), size()).toRect(); QRegion dirtyRegion(floatItemRect.toRect()); m_marbleWidget->setAttribute( Qt::WA_NoSystemBackground, false ); update(); m_marbleWidget->setAttribute( Qt::WA_NoSystemBackground, m_marbleWidget->map()->mapCoversViewport() ); } } Q_EXPORT_PLUGIN2(NavigationFloatItem, NavigationFloatItem) #include "NavigationFloatItem.moc" <commit_msg>Sorry, small typo, corrected now<commit_after>// // This file is part of the Marble Desktop Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2008 Dennis Nienhüser <[email protected]> // #include "NavigationFloatItem.h" #include <QtCore/QDebug> #include <QtCore/QRect> #include <QtGui/QMouseEvent> #include <QtGui/QPixmap> #include <QtGui/QSlider> #include <QtGui/QWidget> #include "GeoPainter.h" #include "ViewportParams.h" #include "MarbleWidget.h" #include "MarbleMap.h" using namespace Marble; const int defaultMinZoom = 900; const int defaultMaxZoom = 2400; NavigationFloatItem::NavigationFloatItem(const QPointF &point, const QSizeF &size) : AbstractFloatItem(point, size), m_marbleWidget(0), m_navigationParent(0), m_oldViewportRadius(0) { // Plugin is enabled by default setEnabled( true ); // Plugin is not visible by default setVisible( false ); #ifdef MARBLE_SMALL_SCREEN setFrame( FrameGraphicsItem::RectFrame ); #else setFrame( FrameGraphicsItem::RoundedRectFrame ); #endif // This sets the padding to the minimum possible for this Frame setPadding( 0 ); } NavigationFloatItem::~NavigationFloatItem() { delete m_navigationParent; } QStringList NavigationFloatItem::backendTypes() const { return QStringList("navigation"); } QString NavigationFloatItem::name() const { return tr("Navigation"); } QString NavigationFloatItem::guiString() const { return tr("&Navigation"); } QString NavigationFloatItem::nameId() const { return QString("navigation"); } QString NavigationFloatItem::description() const { return tr("A mouse control to zoom and move the map"); } QIcon NavigationFloatItem::icon() const { return QIcon(); } void NavigationFloatItem::initialize() { m_navigationParent = new QWidget(0); m_navigationParent->setFixedSize(size().toSize() - QSize(2 * padding(), 2 * padding())); m_navigationWidget.setupUi(m_navigationParent); #ifndef MARBLE_SMALL_SCREEN connect( m_navigationWidget.zoomSlider, SIGNAL( sliderPressed() ), this, SLOT( adjustForAnimation() ) ); connect( m_navigationWidget.zoomSlider, SIGNAL( sliderReleased() ), this, SLOT( adjustForStill() ) ); connect( m_navigationWidget.zoomSlider, SIGNAL( valueChanged( int ) ), this, SLOT( updateButtons( int ) ) ); // Other signal/slot connections will be initialized when the marble widget is known #endif } bool NavigationFloatItem::isInitialized() const { return m_navigationParent != 0; } void NavigationFloatItem::changeViewport( ViewportParams *viewport ) { if ( viewport->radius() != m_oldViewportRadius ) { m_oldViewportRadius = viewport->radius(); // The slider depends on the map state (zoom factor) update(); } } void NavigationFloatItem::paintContent( GeoPainter *painter, ViewportParams *viewport, const QString& renderPos, GeoSceneLayer * layer ) { Q_UNUSED( viewport ); Q_UNUSED( layer ); Q_UNUSED( renderPos ); // Paint widget without a background m_navigationParent->render( painter, QPoint( padding(), padding() ), QRegion(),QWidget::RenderFlags(QWidget::DrawChildren)); } bool NavigationFloatItem::eventFilter(QObject *object, QEvent *e) { if ( !enabled() || !visible() ) { return false; } MarbleWidget *widget = dynamic_cast<MarbleWidget*> (object); if ( !widget ) { return AbstractFloatItem::eventFilter(object, e); } if ( m_marbleWidget != widget ) { // Delayed initialization m_marbleWidget = widget; int minZoom = m_marbleWidget->map()->minimumZoom(); int maxZoom = m_marbleWidget->map()->maximumZoom(); //m_navigationWidget.zoomSlider->setRange(minZoom, maxZoom); #ifndef MARBLE_SMALL_SCREEN m_navigationWidget.zoomSlider->setMinimum(minZoom); m_navigationWidget.zoomSlider->setMaximum(maxZoom); m_navigationWidget.zoomSlider->setValue(m_marbleWidget->map()->zoom()); m_navigationWidget.zoomSlider->setTickInterval((maxZoom - minZoom) / 15); #endif updateButtons(m_marbleWidget->map()->zoom()); connect(m_marbleWidget->map(), SIGNAL(zoomChanged(int)), this, SLOT(zoomChanged(int))); connect(m_marbleWidget, SIGNAL( themeChanged( QString ) ), this, SLOT( selectTheme( QString ) ) ); connect(m_navigationWidget.zoomInButton, SIGNAL( clicked() ), m_marbleWidget, SLOT( zoomIn() ) ); connect(m_navigationWidget.zoomOutButton, SIGNAL( clicked() ), m_marbleWidget, SLOT( zoomOut() ) ); #ifndef MARBLE_SMALL_SCREEN connect(m_navigationWidget.zoomSlider, SIGNAL(sliderMoved(int)), m_marbleWidget, SLOT(zoomView(int))); connect(m_navigationWidget.moveLeftButton, SIGNAL( clicked() ), m_marbleWidget, SLOT( moveLeft() ) ); connect(m_navigationWidget.moveRightButton, SIGNAL( clicked() ), m_marbleWidget, SLOT( moveRight() ) ); connect(m_navigationWidget.moveUpButton, SIGNAL( clicked() ), m_marbleWidget, SLOT( moveUp() ) ); connect(m_navigationWidget.moveDownButton, SIGNAL( clicked() ), m_marbleWidget, SLOT( moveDown() ) ); #endif connect(m_navigationWidget.goHomeButton, SIGNAL( clicked() ), m_marbleWidget, SLOT( goHome() ) ); } Q_ASSERT(m_marbleWidget); if ( e->type() == QEvent::MouseButtonDblClick || e->type() == QEvent::MouseMove || e->type() == QEvent::MouseButtonPress || e->type() == QEvent::MouseButtonRelease ) { // Mouse events are forwarded to the underlying widget QMouseEvent *event = static_cast<QMouseEvent*> (e); QRectF floatItemRect = QRectF( positivePosition(), size() ); QPoint shiftedPos = event->pos() - floatItemRect.topLeft().toPoint() - QPoint(padding(), padding()); if ( floatItemRect.contains(event->pos()) ) { QWidget *child = m_navigationParent->childAt( shiftedPos ); if ( child ) { m_marbleWidget->setCursor( Qt::ArrowCursor ); shiftedPos -= child->pos(); // transform to children's coordinates QMouseEvent shiftedEvent = QMouseEvent( e->type(), shiftedPos, event->globalPos(), event->button(), event->buttons(), event->modifiers() ); if ( QApplication::sendEvent( child, &shiftedEvent ) ) { return true; } } } } return AbstractFloatItem::eventFilter(object, e); } void NavigationFloatItem::zoomChanged(int level) { #ifndef MARBLE_SMALL_SCREEN m_navigationWidget.zoomSlider->setValue(level); #endif } void NavigationFloatItem::selectTheme(QString theme) { Q_UNUSED(theme); if ( m_marbleWidget ) { #ifndef MARBLE_SMALL_SCREEN int minZoom = m_marbleWidget->map()->minimumZoom(); int maxZoom = m_marbleWidget->map()->maximumZoom(); m_navigationWidget.zoomSlider->setRange(minZoom, maxZoom); m_navigationWidget.zoomSlider->setValue(m_marbleWidget->map()->zoom()); updateButtons(m_navigationWidget.zoomSlider->value()); #else updateButtons(m_marbleWidget->map()->zoom()); #endif } } void NavigationFloatItem::adjustForAnimation() { if ( !m_marbleWidget ) { return; } m_marbleWidget->setViewContext( Animation ); } void NavigationFloatItem::adjustForStill() { if ( !m_marbleWidget ) { return; } m_marbleWidget->setViewContext( Still ); if ( m_marbleWidget->mapQuality( Still ) != m_marbleWidget->mapQuality( Animation ) ) { m_marbleWidget->updateChangedMap(); } } void NavigationFloatItem::updateButtons( int value ) { int minZoom = defaultMinZoom; int maxZoom = defaultMaxZoom; #ifdef MARBLE_SMALL_SCREEN if ( m_marbleWidget ) { minZoom = m_marbleWidget->map()->minimumZoom(); maxZoom = m_marbleWidget->map()->maximumZoom(); } #else minZoom = m_navigationWidget.zoomSlider->minimum(); maxZoom = m_navigationWidget.zoomSlider->maximum(); #endif if ( value <= minZoom ) { m_navigationWidget.zoomInButton->setEnabled( true ); m_navigationWidget.zoomOutButton->setEnabled( false ); } else if ( value >= maxZoom ) { m_navigationWidget.zoomInButton->setEnabled( false ); m_navigationWidget.zoomOutButton->setEnabled( true ); } else { m_navigationWidget.zoomInButton->setEnabled( true ); m_navigationWidget.zoomOutButton->setEnabled( true ); } if (m_marbleWidget) { // Trigger a repaint of the float item. Otherwise button state updates // are delayed QRectF floatItemRect = QRectF(positivePosition(), size()).toRect(); QRegion dirtyRegion(floatItemRect.toRect()); m_marbleWidget->setAttribute( Qt::WA_NoSystemBackground, false ); update(); m_marbleWidget->setAttribute( Qt::WA_NoSystemBackground, m_marbleWidget->map()->mapCoversViewport() ); } } Q_EXPORT_PLUGIN2(NavigationFloatItem, NavigationFloatItem) #include "NavigationFloatItem.moc" <|endoftext|>
<commit_before>#include "Expression.hpp" #include <sstream> #include <cmath> namespace lm { Expression::Expression(const std::string& inputInit) : input{inputInit} { } double Expression::getResult() { std::istringstream istr(input); double val1 = 0.0; double val2 = 0.0; char op = '\0'; istr >> val1; istr >> op; istr >> val2; switch (op) { case '+': return val1 + val2; case '-': return val1 - val2; case '*': return val1 * val2; case '/': if (std::fabs(val2) < epsilon) throw std::runtime_error("division by zero"); return val1 / val2; default: throw std::runtime_error("unknown operation"); } } } <commit_msg>travis test<commit_after>#include "Expression.hpp" #include <cmath> #include <sstream> #include <iostream> namespace lm { Expression::Expression(const std::string& inputInit) : input{inputInit} { } double Expression::getResult() { std::istringstream istr(input); double val1 = 0.0; double val2 = 0.0; char op = '\0'; istr >> val1; istr >> op; istr >> val2; switch (op) { case '+': std::cout << "1" << std::endl; return val1 + val2; case '-': std::cout << "2" << std::endl; return val1 - val2; case '*': std::cout << "3" << std::endl; return val1 * val2; case '/': std::cout << "4" << std::endl; if (std::fabs(val2) < epsilon) { std::cout << "5" << std::endl; throw std::runtime_error("division by zero"); } std::cout << "6" << std::endl; return val1 / val2; default: std::cout << "7" << std::endl; throw std::runtime_error("unknown operation"); } } } <|endoftext|>
<commit_before>#include "Expression.hpp" #include <sstream> #include <cmath> namespace lm { Expression::Expression(const std::string& inputInit) : input{inputInit} { } double Expression::getResult() { std::istringstream istr(input); double val1 = 0.0; double val2 = 0.0; char op = '\0'; istr >> val1; istr >> op; istr >> val2; switch (op) { case '+': return val1 + val2; case '-': return val1 - val2; case '*': return val1 * val2; case '/': if (std::fabs(val2) < epsilon) throw std::runtime_error("division by zero"); return val1 / val2; default: throw std::runtime_error("unknown operation"); } } } <commit_msg>travis test<commit_after>#include "Expression.hpp" #include <cmath> #include <sstream> #include <iostream> namespace lm { Expression::Expression(const std::string& inputInit) : input{inputInit} { } double Expression::getResult() { std::istringstream istr(input); double val1 = 0.0; double val2 = 0.0; char op = '\0'; istr >> val1; istr >> op; istr >> val2; switch (op) { case '+': std::cout << "1" << std::endl; return val1 + val2; case '-': std::cout << "2" << std::endl; return val1 - val2; case '*': std::cout << "3" << std::endl; return val1 * val2; case '/': std::cout << "4" << std::endl; if (std::fabs(val2) < epsilon) { std::cout << "5" << std::endl; throw std::runtime_error("division by zero"); } std::cout << "6" << std::endl; return val1 / val2; default: std::cout << "7" << std::endl; throw std::runtime_error("unknown operation"); } } } <|endoftext|>
<commit_before>/* Copyright (C) 2016-2018 INRA * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef ORG_VLEPROJECT_BARYONYX_SOLVER_ITM_OPTIMIZER_COMMON_HPP #define ORG_VLEPROJECT_BARYONYX_SOLVER_ITM_OPTIMIZER_COMMON_HPP #include <baryonyx/core-compare> #include <baryonyx/core-utils> #include <algorithm> #include <chrono> #include <functional> #include <future> #include <random> #include <set> #include <thread> #include <utility> #include <vector> #include "observer.hpp" #include "private.hpp" #include "result.hpp" #include "sparse-matrix.hpp" #include "utils.hpp" namespace baryonyx { namespace itm { template<typename Float, typename Mode> struct best_solution_recorder { const context_ptr& m_ctx; std::chrono::time_point<std::chrono::steady_clock> m_start; std::mutex m_mutex; result m_best; best_solution_recorder(const context_ptr& ctx) : m_ctx(ctx) , m_start(std::chrono::steady_clock::now()) {} void try_update(int remaining_constraints, int loop) { try { std::lock_guard<std::mutex> lock(m_mutex); if (store_advance(m_best, remaining_constraints)) { m_best.remaining_constraints = remaining_constraints; m_best.loop = loop; m_best.duration = compute_duration(m_start, std::chrono::steady_clock::now()); info(m_ctx, " - Constraints remaining: {} (i={} t={}s)\n", remaining_constraints, loop, m_best.duration); } } catch (const std::exception& e) { error(m_ctx, "sync optimization error: {}", e.what()); } } void try_update(const std::vector<bool>& solution, double value, int loop) { try { std::lock_guard<std::mutex> lock(m_mutex); if (store_solution<Mode>(m_ctx, m_best, solution, value)) { m_best.loop = loop; m_best.duration = compute_duration(m_start, std::chrono::steady_clock::now()); if (loop >= 0) info(m_ctx, " - Solution found: {:f} (i={} t={}s)\n", value, loop, m_best.duration); else info(m_ctx, " - Solution found via push: {:f} (i={} t={}s)\n", value, loop, m_best.duration); } } catch (const std::exception& e) { error(m_ctx, "sync optimization error: {}", e.what()); } } }; template<typename Solver, typename Float, typename Mode, typename Order, typename Random> struct optimize_functor { const context_ptr& m_ctx; Random m_rng; int m_thread_id; std::chrono::time_point<std::chrono::steady_clock> m_begin; std::chrono::time_point<std::chrono::steady_clock> m_end; const std::vector<std::string>& variable_names; const affected_variables& affected_vars; result m_best; optimize_functor(const context_ptr& ctx, unsigned thread_id, typename Random::result_type seed, const std::vector<std::string>& variable_names_, const affected_variables& affected_vars_) : m_ctx(ctx) , m_rng(seed) , m_thread_id(thread_id) , variable_names(variable_names_) , affected_vars(affected_vars_) {} result operator()(best_solution_recorder<Float, Mode>& best_recorder, const std::vector<merged_constraint>& constraints, int variables, const std::unique_ptr<Float[]>& original_costs, const std::unique_ptr<Float[]>& norm_costs, double cost_constant) { return ((m_ctx->parameters.mode & solver_parameters::mode_type::branch) == solver_parameters::mode_type::branch) ? run<x_counter_type>(best_recorder, constraints, variables, original_costs, norm_costs, cost_constant) : run<x_type>(best_recorder, constraints, variables, original_costs, norm_costs, cost_constant); } template<typename Xtype> result run(best_solution_recorder<Float, Mode>& best_recorder, const std::vector<merged_constraint>& constraints, int variables, const std::unique_ptr<Float[]>& original_costs, const std::unique_ptr<Float[]>& norm_costs, double cost_constant) { Xtype x(variables); int best_remaining = INT_MAX; auto& p = m_ctx->parameters; const auto kappa_step = static_cast<Float>(p.kappa_step); const auto kappa_max = static_cast<Float>(p.kappa_max); const auto alpha = static_cast<Float>(p.alpha); const auto theta = static_cast<Float>(p.theta); const auto delta = p.delta < 0 ? compute_delta<Float>(m_ctx, norm_costs, theta, variables) : static_cast<Float>(p.delta); const auto pushing_k_factor = static_cast<Float>(p.pushing_k_factor); const auto pushing_objective_amplifier = static_cast<Float>(p.pushing_objective_amplifier); if (p.limit <= 0) p.limit = std::numeric_limits<int>::max(); if (p.time_limit <= 0) p.time_limit = std::numeric_limits<double>::infinity(); if (p.pushes_limit <= 0) p.pushes_limit = 0; if (p.pushing_iteration_limit <= 0) p.pushes_limit = 0; Solver slv( m_rng, length(constraints), variables, norm_costs, constraints); auto init_policy = init_solver(slv, x, p.init_policy, p.init_random); Order compute(slv, x, m_rng); m_best.variables = slv.m; m_best.constraints = slv.n; m_begin = std::chrono::steady_clock::now(); m_end = std::chrono::steady_clock::now(); bool finish = false; while (!finish) { auto kappa = static_cast<Float>(p.kappa_min); init_policy = m_best.solutions.empty() ? init_solver( slv, x, init_policy, m_ctx->parameters.init_random) : init_solver(slv, x, m_best.solutions.back().variables, init_policy, m_ctx->parameters.init_random); for (int i = 0; i != p.limit; ++i) { auto remaining = compute.run(slv, x, kappa, delta, theta); if (remaining == 0) { store_if_better( x, slv.results(x, original_costs, cost_constant), i, best_recorder); best_remaining = remaining; break; } if (remaining < best_remaining) { store_if_better(x, remaining, i, best_recorder); best_remaining = remaining; } if (i > p.w) kappa += kappa_step * std::pow(static_cast<Float>(remaining) / static_cast<Float>(slv.m), alpha); if (kappa > kappa_max) break; if (is_timelimit_reached()) { if (m_best.status == result_status::uninitialized) { m_best.status = result_status::time_limit_reached; store_if_better(x, remaining, i, best_recorder); } finish = true; break; } } if (best_remaining > 0) continue; for (int push = 0; !finish && push < p.pushes_limit; ++push) { auto remaining = compute.push_and_run(slv, x, pushing_k_factor * kappa, delta, theta, pushing_objective_amplifier); if (remaining == 0) store_if_better( x, slv.results(x, original_costs, cost_constant), -push * p.pushing_iteration_limit - 1, best_recorder); for (int iter = 0; iter < p.pushing_iteration_limit; ++iter) { remaining = compute.run(slv, x, kappa, delta, theta); if (remaining == 0) { store_if_better( x, slv.results(x, original_costs, cost_constant), -push * p.pushing_iteration_limit - iter - 1, best_recorder); break; } if (iter > p.w) kappa += kappa_step * std::pow(static_cast<Float>(remaining) / static_cast<Float>(slv.m), alpha); if (kappa > kappa_max) break; if (is_timelimit_reached()) { if (m_best.status == result_status::uninitialized) { m_best.status = result_status::time_limit_reached; store_if_better(x, remaining, -push * p.pushing_iteration_limit - iter - 1, best_recorder); } finish = true; break; } } } } return m_best; } private: bool is_timelimit_reached() { m_end = std::chrono::steady_clock::now(); return is_time_limit(m_ctx->parameters.time_limit, m_begin, m_end); } template<typename Xtype> void store_if_better(const Xtype& x, int remaining, int i, best_solution_recorder<Float, Mode>& best_recorder) { if (store_advance(m_best, remaining)) { m_best.loop = i; m_best.remaining_constraints = remaining; m_best.annoying_variable = x.upper(); best_recorder.try_update(remaining, i); } } template<typename Xtype> void store_if_better(const Xtype& x, double current, int i, best_solution_recorder<Float, Mode>& best_recorder) { if (store_solution<Mode>(m_ctx, m_best, x.data(), current)) { m_best.status = result_status::success; m_best.loop = i; m_best.remaining_constraints = 0; m_best.annoying_variable = x.upper(); best_recorder.try_update(x.data(), current, i); } } }; // // Get number of thread to use in optimizer from parameters list or // from the standard thread API. If an error occurred, this function // returns 1. // inline unsigned get_thread_number(const baryonyx::context_ptr& ctx) noexcept { unsigned ret; if (ctx->parameters.thread <= 0) ret = std::thread::hardware_concurrency(); else ret = static_cast<unsigned>(ctx->parameters.thread); if (ret == 0) return 1; return ret; } template<typename Solver, typename Float, typename Mode, typename Order, typename Random> inline result optimize_problem(const context_ptr& ctx, const problem& pb) { info(ctx, "- Optimizer initializing\n"); print(ctx); result ret; auto constraints{ make_merged_constraints(ctx, pb) }; if (!constraints.empty() && !pb.vars.values.empty()) { Random rng(init_random_generator_seed<Random>(ctx)); auto variables = numeric_cast<int>(pb.vars.values.size()); auto cost = make_objective_function<Float>(pb.objective, variables); auto norm_costs = normalize_costs<Float, Random>(ctx, cost, rng, variables); auto cost_constant = pb.objective.value; const auto thread = get_thread_number(ctx); std::vector<std::thread> pool(thread); pool.clear(); std::vector<std::future<result>> results(thread); results.clear(); best_solution_recorder<Float, Mode> result(ctx); if (thread == 1) info(ctx, " - optimizer uses one thread\n"); else info(ctx, " - optimizer uses {} threads\n", thread); auto seeds = generate_seed(rng, thread); for (unsigned i{ 0 }; i != thread; ++i) { std::packaged_task<baryonyx::result()> task( std::bind(optimize_functor<Solver, Float, Mode, Order, Random>( ctx, i, seeds[i], pb.vars.names, pb.affected_vars), std::ref(result), std::ref(constraints), variables, std::ref(cost), std::ref(norm_costs), cost_constant)); results.emplace_back(task.get_future()); pool.emplace_back(std::thread(std::move(task))); } for (auto& t : pool) t.join(); ret = std::move(result.m_best); ret.affected_vars = pb.affected_vars; ret.variable_name = pb.vars.names; std::set<solution> all_solutions; for (unsigned i{ 0 }; i != thread; ++i) { auto current = results[i].get(); if (current.status == result_status::success) all_solutions.insert(current.solutions.begin(), current.solutions.end()); } ret.solutions.clear(); if (!all_solutions.empty()) { switch (ctx->parameters.storage) { case solver_parameters::storage_type::one: ret.solutions.push_back(*(all_solutions.rbegin())); break; case solver_parameters::storage_type::bound: ret.solutions.push_back(*(all_solutions.begin())); ret.solutions.push_back(*(all_solutions.rbegin())); break; case solver_parameters::storage_type::five: { int i = 0; for (auto& elem : all_solutions) { ret.solutions.push_back(*(all_solutions.rbegin())); ++i; if (i >= 5) break; } break; } } } } return ret; } } // namespace itm } // namespace baryonyx #endif <commit_msg>optimizer: fix 5-storage-type algorithm<commit_after>/* Copyright (C) 2016-2018 INRA * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef ORG_VLEPROJECT_BARYONYX_SOLVER_ITM_OPTIMIZER_COMMON_HPP #define ORG_VLEPROJECT_BARYONYX_SOLVER_ITM_OPTIMIZER_COMMON_HPP #include <baryonyx/core-compare> #include <baryonyx/core-utils> #include <algorithm> #include <chrono> #include <functional> #include <future> #include <random> #include <set> #include <thread> #include <utility> #include <vector> #include "observer.hpp" #include "private.hpp" #include "result.hpp" #include "sparse-matrix.hpp" #include "utils.hpp" namespace baryonyx { namespace itm { template<typename Float, typename Mode> struct best_solution_recorder { const context_ptr& m_ctx; std::chrono::time_point<std::chrono::steady_clock> m_start; std::mutex m_mutex; result m_best; best_solution_recorder(const context_ptr& ctx) : m_ctx(ctx) , m_start(std::chrono::steady_clock::now()) {} void try_update(int remaining_constraints, int loop) { try { std::lock_guard<std::mutex> lock(m_mutex); if (store_advance(m_best, remaining_constraints)) { m_best.remaining_constraints = remaining_constraints; m_best.loop = loop; m_best.duration = compute_duration(m_start, std::chrono::steady_clock::now()); info(m_ctx, " - Constraints remaining: {} (i={} t={}s)\n", remaining_constraints, loop, m_best.duration); } } catch (const std::exception& e) { error(m_ctx, "sync optimization error: {}", e.what()); } } void try_update(const std::vector<bool>& solution, double value, int loop) { try { std::lock_guard<std::mutex> lock(m_mutex); if (store_solution<Mode>(m_ctx, m_best, solution, value)) { m_best.loop = loop; m_best.duration = compute_duration(m_start, std::chrono::steady_clock::now()); if (loop >= 0) info(m_ctx, " - Solution found: {:f} (i={} t={}s)\n", value, loop, m_best.duration); else info(m_ctx, " - Solution found via push: {:f} (i={} t={}s)\n", value, loop, m_best.duration); } } catch (const std::exception& e) { error(m_ctx, "sync optimization error: {}", e.what()); } } }; template<typename Solver, typename Float, typename Mode, typename Order, typename Random> struct optimize_functor { const context_ptr& m_ctx; Random m_rng; int m_thread_id; std::chrono::time_point<std::chrono::steady_clock> m_begin; std::chrono::time_point<std::chrono::steady_clock> m_end; const std::vector<std::string>& variable_names; const affected_variables& affected_vars; result m_best; optimize_functor(const context_ptr& ctx, unsigned thread_id, typename Random::result_type seed, const std::vector<std::string>& variable_names_, const affected_variables& affected_vars_) : m_ctx(ctx) , m_rng(seed) , m_thread_id(thread_id) , variable_names(variable_names_) , affected_vars(affected_vars_) {} result operator()(best_solution_recorder<Float, Mode>& best_recorder, const std::vector<merged_constraint>& constraints, int variables, const std::unique_ptr<Float[]>& original_costs, const std::unique_ptr<Float[]>& norm_costs, double cost_constant) { return ((m_ctx->parameters.mode & solver_parameters::mode_type::branch) == solver_parameters::mode_type::branch) ? run<x_counter_type>(best_recorder, constraints, variables, original_costs, norm_costs, cost_constant) : run<x_type>(best_recorder, constraints, variables, original_costs, norm_costs, cost_constant); } template<typename Xtype> result run(best_solution_recorder<Float, Mode>& best_recorder, const std::vector<merged_constraint>& constraints, int variables, const std::unique_ptr<Float[]>& original_costs, const std::unique_ptr<Float[]>& norm_costs, double cost_constant) { Xtype x(variables); int best_remaining = INT_MAX; auto& p = m_ctx->parameters; const auto kappa_step = static_cast<Float>(p.kappa_step); const auto kappa_max = static_cast<Float>(p.kappa_max); const auto alpha = static_cast<Float>(p.alpha); const auto theta = static_cast<Float>(p.theta); const auto delta = p.delta < 0 ? compute_delta<Float>(m_ctx, norm_costs, theta, variables) : static_cast<Float>(p.delta); const auto pushing_k_factor = static_cast<Float>(p.pushing_k_factor); const auto pushing_objective_amplifier = static_cast<Float>(p.pushing_objective_amplifier); if (p.limit <= 0) p.limit = std::numeric_limits<int>::max(); if (p.time_limit <= 0) p.time_limit = std::numeric_limits<double>::infinity(); if (p.pushes_limit <= 0) p.pushes_limit = 0; if (p.pushing_iteration_limit <= 0) p.pushes_limit = 0; Solver slv( m_rng, length(constraints), variables, norm_costs, constraints); auto init_policy = init_solver(slv, x, p.init_policy, p.init_random); Order compute(slv, x, m_rng); m_best.variables = slv.m; m_best.constraints = slv.n; m_begin = std::chrono::steady_clock::now(); m_end = std::chrono::steady_clock::now(); bool finish = false; while (!finish) { auto kappa = static_cast<Float>(p.kappa_min); init_policy = m_best.solutions.empty() ? init_solver( slv, x, init_policy, m_ctx->parameters.init_random) : init_solver(slv, x, m_best.solutions.back().variables, init_policy, m_ctx->parameters.init_random); for (int i = 0; i != p.limit; ++i) { auto remaining = compute.run(slv, x, kappa, delta, theta); if (remaining == 0) { store_if_better( x, slv.results(x, original_costs, cost_constant), i, best_recorder); best_remaining = remaining; break; } if (remaining < best_remaining) { store_if_better(x, remaining, i, best_recorder); best_remaining = remaining; } if (i > p.w) kappa += kappa_step * std::pow(static_cast<Float>(remaining) / static_cast<Float>(slv.m), alpha); if (kappa > kappa_max) break; if (is_timelimit_reached()) { if (m_best.status == result_status::uninitialized) { m_best.status = result_status::time_limit_reached; store_if_better(x, remaining, i, best_recorder); } finish = true; break; } } if (best_remaining > 0) continue; for (int push = 0; !finish && push < p.pushes_limit; ++push) { auto remaining = compute.push_and_run(slv, x, pushing_k_factor * kappa, delta, theta, pushing_objective_amplifier); if (remaining == 0) store_if_better( x, slv.results(x, original_costs, cost_constant), -push * p.pushing_iteration_limit - 1, best_recorder); for (int iter = 0; iter < p.pushing_iteration_limit; ++iter) { remaining = compute.run(slv, x, kappa, delta, theta); if (remaining == 0) { store_if_better( x, slv.results(x, original_costs, cost_constant), -push * p.pushing_iteration_limit - iter - 1, best_recorder); break; } if (iter > p.w) kappa += kappa_step * std::pow(static_cast<Float>(remaining) / static_cast<Float>(slv.m), alpha); if (kappa > kappa_max) break; if (is_timelimit_reached()) { if (m_best.status == result_status::uninitialized) { m_best.status = result_status::time_limit_reached; store_if_better(x, remaining, -push * p.pushing_iteration_limit - iter - 1, best_recorder); } finish = true; break; } } } } return m_best; } private: bool is_timelimit_reached() { m_end = std::chrono::steady_clock::now(); return is_time_limit(m_ctx->parameters.time_limit, m_begin, m_end); } template<typename Xtype> void store_if_better(const Xtype& x, int remaining, int i, best_solution_recorder<Float, Mode>& best_recorder) { if (store_advance(m_best, remaining)) { m_best.loop = i; m_best.remaining_constraints = remaining; m_best.annoying_variable = x.upper(); best_recorder.try_update(remaining, i); } } template<typename Xtype> void store_if_better(const Xtype& x, double current, int i, best_solution_recorder<Float, Mode>& best_recorder) { if (store_solution<Mode>(m_ctx, m_best, x.data(), current)) { m_best.status = result_status::success; m_best.loop = i; m_best.remaining_constraints = 0; m_best.annoying_variable = x.upper(); best_recorder.try_update(x.data(), current, i); } } }; // // Get number of thread to use in optimizer from parameters list or // from the standard thread API. If an error occurred, this function // returns 1. // inline unsigned get_thread_number(const baryonyx::context_ptr& ctx) noexcept { unsigned ret; if (ctx->parameters.thread <= 0) ret = std::thread::hardware_concurrency(); else ret = static_cast<unsigned>(ctx->parameters.thread); if (ret == 0) return 1; return ret; } template<typename Solver, typename Float, typename Mode, typename Order, typename Random> inline result optimize_problem(const context_ptr& ctx, const problem& pb) { info(ctx, "- Optimizer initializing\n"); print(ctx); result ret; auto constraints{ make_merged_constraints(ctx, pb) }; if (!constraints.empty() && !pb.vars.values.empty()) { Random rng(init_random_generator_seed<Random>(ctx)); auto variables = numeric_cast<int>(pb.vars.values.size()); auto cost = make_objective_function<Float>(pb.objective, variables); auto norm_costs = normalize_costs<Float, Random>(ctx, cost, rng, variables); auto cost_constant = pb.objective.value; const auto thread = get_thread_number(ctx); std::vector<std::thread> pool(thread); pool.clear(); std::vector<std::future<result>> results(thread); results.clear(); best_solution_recorder<Float, Mode> result(ctx); if (thread == 1) info(ctx, " - optimizer uses one thread\n"); else info(ctx, " - optimizer uses {} threads\n", thread); auto seeds = generate_seed(rng, thread); for (unsigned i{ 0 }; i != thread; ++i) { std::packaged_task<baryonyx::result()> task( std::bind(optimize_functor<Solver, Float, Mode, Order, Random>( ctx, i, seeds[i], pb.vars.names, pb.affected_vars), std::ref(result), std::ref(constraints), variables, std::ref(cost), std::ref(norm_costs), cost_constant)); results.emplace_back(task.get_future()); pool.emplace_back(std::thread(std::move(task))); } for (auto& t : pool) t.join(); ret = std::move(result.m_best); ret.affected_vars = pb.affected_vars; ret.variable_name = pb.vars.names; std::set<solution> all_solutions; for (unsigned i{ 0 }; i != thread; ++i) { auto current = results[i].get(); if (current.status == result_status::success) all_solutions.insert(current.solutions.begin(), current.solutions.end()); } ret.solutions.clear(); if (!all_solutions.empty()) { switch (ctx->parameters.storage) { case solver_parameters::storage_type::one: ret.solutions.push_back(*(all_solutions.rbegin())); break; case solver_parameters::storage_type::bound: ret.solutions.push_back(*(all_solutions.begin())); ret.solutions.push_back(*(all_solutions.rbegin())); break; case solver_parameters::storage_type::five: { int i = 0; for (auto& elem : all_solutions) { ret.solutions.push_back(elem); ++i; if (i >= 5) break; } break; } } } } return ret; } } // namespace itm } // namespace baryonyx #endif <|endoftext|>
<commit_before>/* * Dataset_opencvTest.cpp * Tests Dataset_opencv * Copyright 2017 Wojciech Wilgierz 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 <gtest/gtest.h> #include <span.h> #include "Spectre.libClassifier/Dataset_opencv.h" #include "Spectre.libException/InconsistentArgumentSizesException.h" #include "Spectre.libException/OutOfRangeException.h" namespace { using namespace Spectre::libClassifier; using namespace Spectre::libException; class Dataset_opencvInitializationTest : public ::testing::Test { public: protected: const std::vector<DataType> data_long{ 0.5f, 0.4f, 0.6f, 1.1f, 1.6f, 0.7f, 2.1f, 1.0f, 0.6f }; const std::vector<DataType> data_short{ 0.5f, 0.4f, 0.6f }; const std::vector<Label> labels{ 3, 7, 14 }; const std::vector<Label> labels_too_long{ 3, 7, 14, 5 }; }; TEST_F(Dataset_opencvInitializationTest, correct_dataset_opencv_initialization_col_size_one) { EXPECT_NO_THROW(Dataset_opencv(data_short, labels)); } TEST_F(Dataset_opencvInitializationTest, correct_dataset_opencv_initialization) { EXPECT_NO_THROW(Dataset_opencv(data_long, labels)); } TEST_F(Dataset_opencvInitializationTest, throws_for_inconsistent_size) { EXPECT_THROW(Dataset_opencv(data_short, labels_too_long), InconsistentArgumentSizesException); } TEST_F(Dataset_opencvInitializationTest, correct_dataset_opencv_initialization_from_mat_col_size_one) { std::vector<DataType> tmp_data(data_short); std::vector<Label> tmp_labels(labels); cv::Mat mat_data(3, 1, CV_TYPE, tmp_data.data()); cv::Mat mat_labels(3, 1, CV_LABEL_TYPE, tmp_labels.data()); EXPECT_NO_THROW(Dataset_opencv(mat_data, mat_labels)); } TEST_F(Dataset_opencvInitializationTest, correct_dataset_opencv_initialization_from_mat) { std::vector<DataType> tmp_data(data_long); std::vector<Label> tmp_labels(labels); cv::Mat mat_data(3, 3, CV_TYPE, tmp_data.data()); cv::Mat mat_labels(3, 1, CV_LABEL_TYPE, tmp_labels.data()); EXPECT_NO_THROW(Dataset_opencv(mat_data, mat_labels)); } class Dataset_opencvTest : public ::testing::Test { public: Dataset_opencvTest() { } protected: const std::vector<DataType> data{ 0.5f, 0.4f, 0.6f, 1.1f, 1.6f, 0.7f, 2.1f, 1.0f, 0.6f }; const std::vector<Label> labels{ 3, 7, 14 }; std::unique_ptr<Dataset_opencv> dataset; void SetUp() override { dataset = std::make_unique<Dataset_opencv>(data, labels); } }; TEST_F(Dataset_opencvTest, get_out_of_range_data) { EXPECT_THROW((*dataset)[4], OutOfRangeException); } TEST_F(Dataset_opencvTest, get_in_range_data) { auto test = (*dataset)[1]; std::vector<DataType> check({ 1.1f, 1.6f, 0.7f }); EXPECT_EQ(test, check); } TEST_F(Dataset_opencvTest, get_out_of_range_label) { EXPECT_THROW(dataset->GetSampleMetadata(4), OutOfRangeException); } TEST_F(Dataset_opencvTest, get_in_range_label) { auto test = dataset->GetSampleMetadata(1); Label check = 7; EXPECT_EQ(test, check); } TEST_F(Dataset_opencvTest, get_dataset_metadata) { Empty check = Empty::instance(); EXPECT_EQ((*dataset).GetDatasetMetadata(), check); } TEST_F(Dataset_opencvTest, get_data) { //nie potrafi porownac labels, wiec trzeba forem to robic EXPECT_EQ(dataset->GetData(), data); } TEST_F(Dataset_opencvTest, get_labels) { //nie potrafi porownac labels, wiec trzeba forem to robic EXPECT_EQ(dataset->GetSampleMetadata(), labels); } TEST_F(Dataset_opencvTest, get_size) { EXPECT_EQ(dataset->size(), labels.size()); } TEST_F(Dataset_opencvTest, get_data_mat) { std::vector<DataType> mat_data{ 0.5f, 0.4f, 0.6f, 1.1f, 1.6f, 0.7f, 2.1f, 1.0f, 0.6f }; cv::Mat check(3, 3, CV_TYPE, mat_data.data()); cv::Mat result = dataset->getMatData(); EXPECT_EQ(check, result); } TEST_F(Dataset_opencvTest, get_labels_mat) { std::vector<Label> mat_labels{ 3, 7, 14 }; cv::Mat check(3, 1, CV_LABEL_TYPE, mat_labels.data()); cv::Mat result = dataset->getMatLabels(); EXPECT_EQ(check, result); } } <commit_msg>fixed few EXPECT_EQ and added one test<commit_after>/* * Dataset_opencvTest.cpp * Tests Dataset_opencv * Copyright 2017 Wojciech Wilgierz 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 <gtest/gtest.h> #include <span.h> #include "Spectre.libClassifier/Dataset_opencv.h" #include "Spectre.libException/InconsistentArgumentSizesException.h" #include "Spectre.libException/OutOfRangeException.h" namespace { using namespace Spectre::libClassifier; using namespace Spectre::libException; class Dataset_opencvInitializationTest : public ::testing::Test { public: protected: const std::vector<DataType> data_long{ 0.5f, 0.4f, 0.6f, 1.1f, 1.6f, 0.7f, 2.1f, 1.0f, 0.6f }; const std::vector<DataType> data_short{ 0.5f, 0.4f, 0.6f }; const std::vector<Label> labels{ 3, 7, 14 }; const std::vector<Label> labels_too_long{ 3, 7, 14, 5 }; }; TEST_F(Dataset_opencvInitializationTest, correct_dataset_opencv_initialization_col_size_one) { EXPECT_NO_THROW(Dataset_opencv(data_short, labels)); } TEST_F(Dataset_opencvInitializationTest, correct_dataset_opencv_initialization) { EXPECT_NO_THROW(Dataset_opencv(data_long, labels)); } TEST_F(Dataset_opencvInitializationTest, throws_for_inconsistent_size) { EXPECT_THROW(Dataset_opencv(data_short, labels_too_long), InconsistentArgumentSizesException); } TEST_F(Dataset_opencvInitializationTest, correct_dataset_opencv_initialization_from_mat_col_size_one) { std::vector<DataType> tmp_data(data_short); std::vector<Label> tmp_labels(labels); cv::Mat mat_data(3, 1, CV_TYPE, tmp_data.data()); cv::Mat mat_labels(3, 1, CV_LABEL_TYPE, tmp_labels.data()); EXPECT_NO_THROW(Dataset_opencv(mat_data, mat_labels)); } TEST_F(Dataset_opencvInitializationTest, correct_dataset_opencv_initialization_from_mat) { std::vector<DataType> tmp_data(data_long); std::vector<Label> tmp_labels(labels); cv::Mat mat_data(3, 3, CV_TYPE, tmp_data.data()); cv::Mat mat_labels(3, 1, CV_LABEL_TYPE, tmp_labels.data()); EXPECT_NO_THROW(Dataset_opencv(mat_data, mat_labels)); } class Dataset_opencvTest : public ::testing::Test { public: Dataset_opencvTest() { } protected: const std::vector<DataType> data{ 0.5f, 0.4f, 0.6f, 1.1f, 1.6f, 0.7f, 2.1f, 1.0f, 0.6f }; const std::vector<Label> labels{ 3, 7, 14 }; std::unique_ptr<Dataset_opencv> dataset; void SetUp() override { dataset = std::make_unique<Dataset_opencv>(data, labels); } }; TEST_F(Dataset_opencvTest, get_out_of_range_data) { EXPECT_THROW((*dataset)[4], OutOfRangeException); } TEST_F(Dataset_opencvTest, get_in_range_data) { auto test = (*dataset)[1]; std::vector<DataType> check({ 1.1f, 1.6f, 0.7f }); for (auto i = 0u; i < check.size(); i++) { EXPECT_EQ(test[i], check[i]); } } TEST_F(Dataset_opencvTest, get_out_of_range_label) { EXPECT_THROW(dataset->GetSampleMetadata(4), OutOfRangeException); } TEST_F(Dataset_opencvTest, get_in_range_label) { auto test = dataset->GetSampleMetadata(1); Label check = 7; EXPECT_EQ(test, check); } TEST_F(Dataset_opencvTest, get_dataset_metadata) { const Empty check = Empty::instance(); EXPECT_EQ(&(*dataset).GetDatasetMetadata(), &check); } TEST_F(Dataset_opencvTest, get_data) { gsl::span<const Observation> result = dataset->GetData(); EXPECT_EQ(result.size(), data.size()); for (auto i = 0u; i < data.size(); i++) { EXPECT_EQ(result[i], data[i]); } } TEST_F(Dataset_opencvTest, get_labels) { gsl::span<const Label> result = dataset->GetSampleMetadata(); EXPECT_EQ(result.size(), labels.size()); for (auto i = 0u; i < labels.size(); i++) { EXPECT_EQ(result[i], labels[i]); } } TEST_F(Dataset_opencvTest, get_size) { EXPECT_EQ(dataset->size(), labels.size()); } TEST_F(Dataset_opencvTest, get_data_mat) { std::vector<DataType> mat_data{ 0.5f, 0.4f, 0.6f, 1.1f, 1.6f, 0.7f, 2.1f, 1.0f, 0.6f }; cv::Mat check(3, 3, CV_TYPE, mat_data.data()); cv::Mat result = dataset->getMatData(); EXPECT_EQ(check, result); } TEST_F(Dataset_opencvTest, get_labels_mat) { std::vector<Label> mat_labels{ 3, 7, 14 }; cv::Mat check(3, 1, CV_LABEL_TYPE, mat_labels.data()); cv::Mat result = dataset->getMatLabels(); EXPECT_EQ(check.size, result.size); } //advanced tests TEST_F(Dataset_opencvTest, check_if_creating_copy) { std::unique_ptr<Dataset_opencv> testDataset = std::make_unique<Dataset_opencv>(data, labels); gsl::span<const Observation> result = dataset->GetData(); delete &testDataset; EXPECT_EQ(data.size(), result.size()); } }<|endoftext|>
<commit_before>/* * 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. * * Written (W) 2012 Heiko Strathmann */ #include <shogun/statistics/MMDKernelSelectionOptSingle.h> #include <shogun/statistics/LinearTimeMMD.h> #include <shogun/kernel/CombinedKernel.h> using namespace shogun; CMMDKernelSelectionOptSingle::CMMDKernelSelectionOptSingle() : CMMDKernelSelection() { init(); } CMMDKernelSelectionOptSingle::CMMDKernelSelectionOptSingle( CKernelTwoSampleTestStatistic* mmd, float64_t lambda) : CMMDKernelSelection(mmd) { init(); /* currently, this method is only developed for the linear time MMD */ REQUIRE(dynamic_cast<CLinearTimeMMD*>(mmd), "%s::%s(): Only " "CLinearTimeMMD is currently supported! Provided instance is " "\"%s\"\n", get_name(), get_name(), mmd->get_name()); m_lambda=lambda; } CMMDKernelSelectionOptSingle::~CMMDKernelSelectionOptSingle() { } SGVector<float64_t> CMMDKernelSelectionOptSingle::compute_measures() { /* comnpute mmd on all subkernels using the same data. Note that underlying * kernel was asserted to be a combined one */ SGVector<float64_t> mmds; SGVector<float64_t> vars; ((CLinearTimeMMD*)m_mmd)->compute_statistic_and_variance(mmds, vars, true); /* we know that the underlying MMD is linear time version, cast is safe */ SGVector<float64_t> measures(mmds.vlen); for (index_t i=0; i<measures.vlen; ++i) measures[i]=mmds[i]/(vars[i]+m_lambda); return measures; } void CMMDKernelSelectionOptSingle::init() { /* set to a sensible standard value that proved to be useful in * experiments, see NIPS paper */ m_lambda=10E-5; } <commit_msg>assed forgotten quare root, was wrong before<commit_after>/* * 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. * * Written (W) 2012 Heiko Strathmann */ #include <shogun/statistics/MMDKernelSelectionOptSingle.h> #include <shogun/statistics/LinearTimeMMD.h> #include <shogun/kernel/CombinedKernel.h> using namespace shogun; CMMDKernelSelectionOptSingle::CMMDKernelSelectionOptSingle() : CMMDKernelSelection() { init(); } CMMDKernelSelectionOptSingle::CMMDKernelSelectionOptSingle( CKernelTwoSampleTestStatistic* mmd, float64_t lambda) : CMMDKernelSelection(mmd) { init(); /* currently, this method is only developed for the linear time MMD */ REQUIRE(dynamic_cast<CLinearTimeMMD*>(mmd), "%s::%s(): Only " "CLinearTimeMMD is currently supported! Provided instance is " "\"%s\"\n", get_name(), get_name(), mmd->get_name()); m_lambda=lambda; } CMMDKernelSelectionOptSingle::~CMMDKernelSelectionOptSingle() { } SGVector<float64_t> CMMDKernelSelectionOptSingle::compute_measures() { /* comnpute mmd on all subkernels using the same data. Note that underlying * kernel was asserted to be a combined one */ SGVector<float64_t> mmds; SGVector<float64_t> vars; ((CLinearTimeMMD*)m_mmd)->compute_statistic_and_variance(mmds, vars, true); /* we know that the underlying MMD is linear time version, cast is safe */ SGVector<float64_t> measures(mmds.vlen); for (index_t i=0; i<measures.vlen; ++i) measures[i]=mmds[i]/(CMath::sqrt(vars[i])+m_lambda); return measures; } void CMMDKernelSelectionOptSingle::init() { /* set to a sensible standard value that proved to be useful in * experiments, see NIPS paper */ m_lambda=10E-5; } <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "txdb.h" #include "chainparams.h" #include "hash.h" #include "pow.h" #include "uint256.h" #include <stdint.h> #include <boost/thread.hpp> using namespace std; static const char DB_COINS = 'c'; static const char DB_BLOCK_FILES = 'f'; static const char DB_TXINDEX = 't'; static const char DB_BLOCK_INDEX = 'b'; static const char DB_BEST_BLOCK = 'B'; static const char DB_FLAG = 'F'; static const char DB_REINDEX_FLAG = 'R'; static const char DB_LAST_BLOCK = 'l'; void static BatchWriteCoins(CDBBatch &batch, const uint256 &hash, const CCoins &coins) { if (coins.IsPruned()) batch.Erase(make_pair(DB_COINS, hash)); else batch.Write(make_pair(DB_COINS, hash), coins); } void static BatchWriteHashBestChain(CDBBatch &batch, const uint256 &hash) { batch.Write(DB_BEST_BLOCK, hash); } CCoinsViewDB::CCoinsViewDB(size_t nCacheSize, bool &isObfuscated, bool fMemory, bool fWipe) : db(GetDataDir() / "chainstate", nCacheSize, isObfuscated, fMemory, fWipe) { } bool CCoinsViewDB::GetCoins(const uint256 &txid, CCoins &coins) const { return db.Read(make_pair(DB_COINS, txid), coins); } bool CCoinsViewDB::HaveCoins(const uint256 &txid) const { return db.Exists(make_pair(DB_COINS, txid)); } uint256 CCoinsViewDB::GetBestBlock() const { uint256 hashBestChain; if (!db.Read(DB_BEST_BLOCK, hashBestChain)) return uint256(); return hashBestChain; } bool CCoinsViewDB::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) { CDBBatch batch; size_t count = 0; size_t changed = 0; for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) { if (it->second.flags & CCoinsCacheEntry::DIRTY) { BatchWriteCoins(batch, it->first, it->second.coins); changed++; } count++; CCoinsMap::iterator itOld = it++; mapCoins.erase(itOld); } if (!hashBlock.IsNull()) BatchWriteHashBestChain(batch, hashBlock); LogPrint("coindb", "Committing %u changed transactions (out of %u) to coin database...\n", (unsigned int)changed, (unsigned int)count); return db.WriteBatch(batch); } CBlockTreeDB::CBlockTreeDB(size_t nCacheSize, bool &isObfuscated, bool fMemory, bool fWipe) : CDBWrapper(GetDataDir() / "blocks" / "index", nCacheSize, isObfuscated, fMemory, fWipe) { } bool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo &info) { return Read(make_pair(DB_BLOCK_FILES, nFile), info); } bool CBlockTreeDB::WriteReindexing(bool fReindexing) { if (fReindexing) return Write(DB_REINDEX_FLAG, '1'); else return Erase(DB_REINDEX_FLAG); } bool CBlockTreeDB::ReadReindexing(bool &fReindexing) { fReindexing = Exists(DB_REINDEX_FLAG); return true; } bool CBlockTreeDB::ReadLastBlockFile(int &nFile) { return Read(DB_LAST_BLOCK, nFile); } CCoinsViewCursor *CCoinsViewDB::Cursor() const { CCoinsViewDBCursor *i = new CCoinsViewDBCursor(const_cast<CDBWrapper*>(&db)->NewIterator(), GetBestBlock()); /* It seems that there are no "const iterators" for LevelDB. Since we only need read operations on it, use a const-cast to get around that restriction. */ i->pcursor->Seek(DB_COINS); // Cache key of first record i->pcursor->GetKey(i->keyTmp); return i; } bool CCoinsViewDBCursor::GetKey(uint256 &key) const { // Return cached key if (keyTmp.first == DB_COINS) { key = keyTmp.second; return true; } return false; } bool CCoinsViewDBCursor::GetValue(CCoins &coins) const { return pcursor->GetValue(coins); } unsigned int CCoinsViewDBCursor::GetValueSize() const { return pcursor->GetValueSize(); } bool CCoinsViewDBCursor::Valid() const { return keyTmp.first == DB_COINS; } void CCoinsViewDBCursor::Next() { pcursor->Next(); if (!pcursor->Valid() || !pcursor->GetKey(keyTmp)) keyTmp.first = 0; // Invalidate cached key after last record so that Valid() and GetKey() return false } bool CBlockTreeDB::WriteBatchSync(const std::vector<std::pair<int, const CBlockFileInfo*> >& fileInfo, int nLastFile, const std::vector<const CBlockIndex*>& blockinfo) { CDBBatch batch; for (std::vector<std::pair<int, const CBlockFileInfo*> >::const_iterator it=fileInfo.begin(); it != fileInfo.end(); it++) { batch.Write(make_pair(DB_BLOCK_FILES, it->first), *it->second); } batch.Write(DB_LAST_BLOCK, nLastFile); for (std::vector<const CBlockIndex*>::const_iterator it=blockinfo.begin(); it != blockinfo.end(); it++) { batch.Write(make_pair(DB_BLOCK_INDEX, (*it)->GetBlockHash()), CDiskBlockIndex(*it)); } return WriteBatch(batch, true); } bool CBlockTreeDB::ReadTxIndex(const uint256 &txid, CDiskTxPos &pos) { return Read(make_pair(DB_TXINDEX, txid), pos); } bool CBlockTreeDB::WriteTxIndex(const std::vector<std::pair<uint256, CDiskTxPos> >&vect) { CDBBatch batch; for (std::vector<std::pair<uint256,CDiskTxPos> >::const_iterator it=vect.begin(); it!=vect.end(); it++) batch.Write(make_pair(DB_TXINDEX, it->first), it->second); return WriteBatch(batch); } bool CBlockTreeDB::WriteFlag(const std::string &name, bool fValue) { return Write(std::make_pair(DB_FLAG, name), fValue ? '1' : '0'); } bool CBlockTreeDB::ReadFlag(const std::string &name, bool &fValue) { char ch; if (!Read(std::make_pair(DB_FLAG, name), ch)) return false; fValue = ch == '1'; return true; } bool CBlockTreeDB::LoadBlockIndexGuts(boost::function<CBlockIndex*(const uint256&)> insertBlockIndex) { std::unique_ptr<CDBIterator> pcursor(NewIterator()); pcursor->Seek(make_pair(DB_BLOCK_INDEX, uint256())); // Load mapBlockIndex while (pcursor->Valid()) { boost::this_thread::interruption_point(); std::pair<char, uint256> key; if (pcursor->GetKey(key) && key.first == DB_BLOCK_INDEX) { CDiskBlockIndex diskindex; if (pcursor->GetValue(diskindex)) { // Construct block index object CBlockIndex* pindexNew = insertBlockIndex(diskindex.GetBlockHash()); pindexNew->pprev = insertBlockIndex(diskindex.hashPrev); pindexNew->nHeight = diskindex.nHeight; pindexNew->nFile = diskindex.nFile; pindexNew->nDataPos = diskindex.nDataPos; pindexNew->nUndoPos = diskindex.nUndoPos; pindexNew->nVersion = diskindex.nVersion; pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot; pindexNew->nTime = diskindex.nTime; pindexNew->nBits = diskindex.nBits; pindexNew->nNonce = diskindex.nNonce; pindexNew->nStatus = diskindex.nStatus; pindexNew->nTx = diskindex.nTx; pindexNew->nSerialVersion = diskindex.nSerialVersion; pindexNew->nMaxBlockSize = diskindex.nMaxBlockSize; pindexNew->nMaxBlockSizeVote = diskindex.nMaxBlockSizeVote; if (!CheckProofOfWork(pindexNew->GetBlockHash(), pindexNew->nBits, Params().GetConsensus())) return error("LoadBlockIndex(): CheckProofOfWork failed: %s", pindexNew->ToString()); pcursor->Next(); } else { return error("LoadBlockIndex() : failed to read value"); } } else { break; } } return true; } <commit_msg>Fix: make CCoinsViewDbCursor::Seek work for missing keys<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "txdb.h" #include "chainparams.h" #include "hash.h" #include "pow.h" #include "uint256.h" #include <stdint.h> #include <boost/thread.hpp> using namespace std; static const char DB_COINS = 'c'; static const char DB_BLOCK_FILES = 'f'; static const char DB_TXINDEX = 't'; static const char DB_BLOCK_INDEX = 'b'; static const char DB_BEST_BLOCK = 'B'; static const char DB_FLAG = 'F'; static const char DB_REINDEX_FLAG = 'R'; static const char DB_LAST_BLOCK = 'l'; void static BatchWriteCoins(CDBBatch &batch, const uint256 &hash, const CCoins &coins) { if (coins.IsPruned()) batch.Erase(make_pair(DB_COINS, hash)); else batch.Write(make_pair(DB_COINS, hash), coins); } void static BatchWriteHashBestChain(CDBBatch &batch, const uint256 &hash) { batch.Write(DB_BEST_BLOCK, hash); } CCoinsViewDB::CCoinsViewDB(size_t nCacheSize, bool &isObfuscated, bool fMemory, bool fWipe) : db(GetDataDir() / "chainstate", nCacheSize, isObfuscated, fMemory, fWipe) { } bool CCoinsViewDB::GetCoins(const uint256 &txid, CCoins &coins) const { return db.Read(make_pair(DB_COINS, txid), coins); } bool CCoinsViewDB::HaveCoins(const uint256 &txid) const { return db.Exists(make_pair(DB_COINS, txid)); } uint256 CCoinsViewDB::GetBestBlock() const { uint256 hashBestChain; if (!db.Read(DB_BEST_BLOCK, hashBestChain)) return uint256(); return hashBestChain; } bool CCoinsViewDB::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) { CDBBatch batch; size_t count = 0; size_t changed = 0; for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) { if (it->second.flags & CCoinsCacheEntry::DIRTY) { BatchWriteCoins(batch, it->first, it->second.coins); changed++; } count++; CCoinsMap::iterator itOld = it++; mapCoins.erase(itOld); } if (!hashBlock.IsNull()) BatchWriteHashBestChain(batch, hashBlock); LogPrint("coindb", "Committing %u changed transactions (out of %u) to coin database...\n", (unsigned int)changed, (unsigned int)count); return db.WriteBatch(batch); } CBlockTreeDB::CBlockTreeDB(size_t nCacheSize, bool &isObfuscated, bool fMemory, bool fWipe) : CDBWrapper(GetDataDir() / "blocks" / "index", nCacheSize, isObfuscated, fMemory, fWipe) { } bool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo &info) { return Read(make_pair(DB_BLOCK_FILES, nFile), info); } bool CBlockTreeDB::WriteReindexing(bool fReindexing) { if (fReindexing) return Write(DB_REINDEX_FLAG, '1'); else return Erase(DB_REINDEX_FLAG); } bool CBlockTreeDB::ReadReindexing(bool &fReindexing) { fReindexing = Exists(DB_REINDEX_FLAG); return true; } bool CBlockTreeDB::ReadLastBlockFile(int &nFile) { return Read(DB_LAST_BLOCK, nFile); } CCoinsViewCursor *CCoinsViewDB::Cursor() const { CCoinsViewDBCursor *i = new CCoinsViewDBCursor(const_cast<CDBWrapper*>(&db)->NewIterator(), GetBestBlock()); /* It seems that there are no "const iterators" for LevelDB. Since we only need read operations on it, use a const-cast to get around that restriction. */ i->pcursor->Seek(DB_COINS); // Cache key of first record if (i->pcursor->Valid()) { i->pcursor->GetKey(i->keyTmp); } else { i->keyTmp.first = 0; // Make sure Valid() and GetKey() return false } return i; } bool CCoinsViewDBCursor::GetKey(uint256 &key) const { // Return cached key if (keyTmp.first == DB_COINS) { key = keyTmp.second; return true; } return false; } bool CCoinsViewDBCursor::GetValue(CCoins &coins) const { return pcursor->GetValue(coins); } unsigned int CCoinsViewDBCursor::GetValueSize() const { return pcursor->GetValueSize(); } bool CCoinsViewDBCursor::Valid() const { return keyTmp.first == DB_COINS; } void CCoinsViewDBCursor::Next() { pcursor->Next(); if (!pcursor->Valid() || !pcursor->GetKey(keyTmp)) keyTmp.first = 0; // Invalidate cached key after last record so that Valid() and GetKey() return false } bool CBlockTreeDB::WriteBatchSync(const std::vector<std::pair<int, const CBlockFileInfo*> >& fileInfo, int nLastFile, const std::vector<const CBlockIndex*>& blockinfo) { CDBBatch batch; for (std::vector<std::pair<int, const CBlockFileInfo*> >::const_iterator it=fileInfo.begin(); it != fileInfo.end(); it++) { batch.Write(make_pair(DB_BLOCK_FILES, it->first), *it->second); } batch.Write(DB_LAST_BLOCK, nLastFile); for (std::vector<const CBlockIndex*>::const_iterator it=blockinfo.begin(); it != blockinfo.end(); it++) { batch.Write(make_pair(DB_BLOCK_INDEX, (*it)->GetBlockHash()), CDiskBlockIndex(*it)); } return WriteBatch(batch, true); } bool CBlockTreeDB::ReadTxIndex(const uint256 &txid, CDiskTxPos &pos) { return Read(make_pair(DB_TXINDEX, txid), pos); } bool CBlockTreeDB::WriteTxIndex(const std::vector<std::pair<uint256, CDiskTxPos> >&vect) { CDBBatch batch; for (std::vector<std::pair<uint256,CDiskTxPos> >::const_iterator it=vect.begin(); it!=vect.end(); it++) batch.Write(make_pair(DB_TXINDEX, it->first), it->second); return WriteBatch(batch); } bool CBlockTreeDB::WriteFlag(const std::string &name, bool fValue) { return Write(std::make_pair(DB_FLAG, name), fValue ? '1' : '0'); } bool CBlockTreeDB::ReadFlag(const std::string &name, bool &fValue) { char ch; if (!Read(std::make_pair(DB_FLAG, name), ch)) return false; fValue = ch == '1'; return true; } bool CBlockTreeDB::LoadBlockIndexGuts(boost::function<CBlockIndex*(const uint256&)> insertBlockIndex) { std::unique_ptr<CDBIterator> pcursor(NewIterator()); pcursor->Seek(make_pair(DB_BLOCK_INDEX, uint256())); // Load mapBlockIndex while (pcursor->Valid()) { boost::this_thread::interruption_point(); std::pair<char, uint256> key; if (pcursor->GetKey(key) && key.first == DB_BLOCK_INDEX) { CDiskBlockIndex diskindex; if (pcursor->GetValue(diskindex)) { // Construct block index object CBlockIndex* pindexNew = insertBlockIndex(diskindex.GetBlockHash()); pindexNew->pprev = insertBlockIndex(diskindex.hashPrev); pindexNew->nHeight = diskindex.nHeight; pindexNew->nFile = diskindex.nFile; pindexNew->nDataPos = diskindex.nDataPos; pindexNew->nUndoPos = diskindex.nUndoPos; pindexNew->nVersion = diskindex.nVersion; pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot; pindexNew->nTime = diskindex.nTime; pindexNew->nBits = diskindex.nBits; pindexNew->nNonce = diskindex.nNonce; pindexNew->nStatus = diskindex.nStatus; pindexNew->nTx = diskindex.nTx; pindexNew->nSerialVersion = diskindex.nSerialVersion; pindexNew->nMaxBlockSize = diskindex.nMaxBlockSize; pindexNew->nMaxBlockSizeVote = diskindex.nMaxBlockSizeVote; if (!CheckProofOfWork(pindexNew->GetBlockHash(), pindexNew->nBits, Params().GetConsensus())) return error("LoadBlockIndex(): CheckProofOfWork failed: %s", pindexNew->ToString()); pcursor->Next(); } else { return error("LoadBlockIndex() : failed to read value"); } } else { break; } } return true; } <|endoftext|>
<commit_before> #include "get_bin.h" int GetBin::change_enmark( char* _string_ ) { int c = 0; while( *_string_ ) { if( *_string_ == '\\' ) { *_string_ = '/'; c ++; } _string_ ++; } return c; } // get binary code from buf unsigned char* GetBin::get_bin( void *bin, int size ) { if( ( unsigned int )( buf - buf_base + ( unsigned int )size ) > ( unsigned int )buf_len ) { memset( bin, 0x00, size ); return 0x00; } memcpy( bin, ( const void* )buf, size ); buf += size; return buf; } unsigned char* GetBin::get_bin2( void* bin, int bin_size, int buf_size ) { unsigned int bin_i = ( unsigned int )bin; if( ( unsigned int )( buf - buf_base + ( unsigned int )bin_size ) > ( unsigned int )buf_len ) { memset( bin, 0, bin_size ); return 0x00; } memset( ( void* )bin_i, 0x00, bin_size ); memcpy( ( void* )bin_i, ( void* )buf, buf_size ); buf += buf_size; return buf; } int GetBin::load( const char *file_name ) { FILE* fp = fopen( file_name, "rb" ); if( fp == 0x00 ) return -1; get_direcotory( file_name ); // Get File Size fseek( fp, 0l, SEEK_END ); //if( fgetpos( fp, &buf_len ) ) // return -1; buf_len = ( unsigned long )ftell( fp ); fseek( fp, 0l, SEEK_SET ); buf_base = buf = new unsigned char[ ( unsigned int )buf_len + 2 ]; if( buf == 0x00 ) return -1; size_t get_size; get_size = fread( buf, sizeof( unsigned char ), ( unsigned int )buf_len, fp ); fclose( fp ); if( get_size != buf_len ) return -1; return 0; } char* GetBin::text_buf( char byte_size, uint* length ) { char* text1 = 0x00; char* text2 = 0x00; long byte_len = 0; if( length ) *length = 0; get_bin( &byte_len, 4 ); if( byte_len < 1 ) return 0x00; text1 = new char[ byte_len + 4 ]; if( text1 == 0x00 ) { puts( "Text buf cannot Allocation." ); return 0x00; } memset( text1, 0, byte_len + 4 ); get_bin( text1, byte_len ); text1[ byte_len ] = '\0'; if( byte_size > 1 ) { text1[ byte_len + 1 ] = '\0'; text2 = new char[ cconv_utf16_to_utf8( 0x00, ( const short* )text1 ) * 2 + 4 ]; byte_len = cconv_utf16_to_utf8( text2, ( const short* )text1 ); delete[] text1; text1 = text2; } change_enmark( text1 ); if( length ) *length = byte_len; // return text1; } //バイナリ用文字列抜き出し char* GetBin::bin_string( void ) { char* result; vector<char> _string; char c[ 8 ]; while( get_bin( c, 1 ) && c[ 0 ] ) _string.push_back( c[ 0 ] ); _string.push_back( '\0' ); result = new char[ _string.size() + 1 ]; for( unsigned int i = 0; i < _string.size(); i ++ ) result[ i ] = _string[ i ]; return result; } int GetBin::get_direcotory( const char *file_name ) { int i; int len = strlen( file_name ); int d_line = len - 1; directory[ 0 ] = '\0'; #ifndef _WIN32 setlocale( LC_CTYPE, "ja_JP.UTF-8" ); #else setlocale( LC_CTYPE, "jpn" ); #endif for( i = 0; i < len; i += 1/*this->utf8mbleb( &file_name[ i ] )*/ ) { if( file_name[ i ] == '/' || file_name[ i ] == '\\' ) d_line = i; } if( d_line > 0 ) { strncpy( directory, file_name, d_line ); directory[ d_line ++ ] = '/'; directory[ d_line ] = '\0'; } return 0; } GetBin::GetBin() { buf_base = 0; buf = 0x00; buf_len = 0x00; } GetBin::~GetBin() { delete[] buf_base; } <commit_msg>support amd64.<commit_after> #include "get_bin.h" int GetBin::change_enmark( char* _string_ ) { int c = 0; while( *_string_ ) { if( *_string_ == '\\' ) { *_string_ = '/'; c ++; } _string_ ++; } return c; } // get binary code from buf unsigned char* GetBin::get_bin( void *bin, int size ) { if( ( unsigned int )( buf - buf_base + ( unsigned int )size ) > ( unsigned int )buf_len ) { memset( bin, 0x00, size ); return 0x00; } memcpy( bin, ( const void* )buf, size ); buf += size; return buf; } unsigned char* GetBin::get_bin2( void* bin, int bin_size, int buf_size ) { unsigned int bin_i = ( uint32_t )bin; if( ( unsigned int )( buf - buf_base + ( unsigned int )bin_size ) > ( unsigned int )buf_len ) { memset( bin, 0, bin_size ); return 0x00; } memset( ( void* )bin_i, 0x00, bin_size ); memcpy( ( void* )bin_i, ( void* )buf, buf_size ); buf += buf_size; return buf; } int GetBin::load( const char *file_name ) { FILE* fp = fopen( file_name, "rb" ); if( fp == 0x00 ) return -1; get_direcotory( file_name ); // Get File Size fseek( fp, 0l, SEEK_END ); //if( fgetpos( fp, &buf_len ) ) // return -1; buf_len = ( unsigned long )ftell( fp ); fseek( fp, 0l, SEEK_SET ); buf_base = buf = new unsigned char[ ( unsigned int )buf_len + 2 ]; if( buf == 0x00 ) return -1; size_t get_size; get_size = fread( buf, sizeof( unsigned char ), ( unsigned int )buf_len, fp ); fclose( fp ); if( get_size != buf_len ) return -1; return 0; } char* GetBin::text_buf( char byte_size, uint* length ) { char* text1 = 0x00; char* text2 = 0x00; long byte_len = 0; if( length ) *length = 0; get_bin( &byte_len, 4 ); if( byte_len < 1 ) return 0x00; text1 = new char[ byte_len + 4 ]; if( text1 == 0x00 ) { puts( "Text buf cannot Allocation." ); return 0x00; } memset( text1, 0, byte_len + 4 ); get_bin( text1, byte_len ); text1[ byte_len ] = '\0'; if( byte_size > 1 ) { text1[ byte_len + 1 ] = '\0'; text2 = new char[ cconv_utf16_to_utf8( 0x00, ( const short* )text1 ) * 2 + 4 ]; byte_len = cconv_utf16_to_utf8( text2, ( const short* )text1 ); delete[] text1; text1 = text2; } change_enmark( text1 ); if( length ) *length = byte_len; // return text1; } //バイナリ用文字列抜き出し char* GetBin::bin_string( void ) { char* result; vector<char> _string; char c[ 8 ]; while( get_bin( c, 1 ) && c[ 0 ] ) _string.push_back( c[ 0 ] ); _string.push_back( '\0' ); result = new char[ _string.size() + 1 ]; for( unsigned int i = 0; i < _string.size(); i ++ ) result[ i ] = _string[ i ]; return result; } int GetBin::get_direcotory( const char *file_name ) { int i; int len = strlen( file_name ); int d_line = len - 1; directory[ 0 ] = '\0'; #ifndef _WIN32 setlocale( LC_CTYPE, "ja_JP.UTF-8" ); #else setlocale( LC_CTYPE, "jpn" ); #endif for( i = 0; i < len; i += 1/*this->utf8mbleb( &file_name[ i ] )*/ ) { if( file_name[ i ] == '/' || file_name[ i ] == '\\' ) d_line = i; } if( d_line > 0 ) { strncpy( directory, file_name, d_line ); directory[ d_line ++ ] = '/'; directory[ d_line ] = '\0'; } return 0; } GetBin::GetBin() { buf_base = 0; buf = 0x00; buf_len = 0x00; } GetBin::~GetBin() { delete[] buf_base; } <|endoftext|>
<commit_before>#ifndef WISSBI_UTIL_HPP_ #define WISSBI_UTIL_HPP_ #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netdb.h> #include <string.h> #include <string> #include <sstream> #include <algorithm> namespace wissbi { namespace util { static void ConnectStringToSockaddr(const std::string& conn_str, sockaddr_in* addr_ptr) { memset(addr_ptr, 0, sizeof(*addr_ptr)); auto idx = conn_str.find(":"); addr_ptr->sin_addr.s_addr = inet_addr(conn_str.substr(0, idx).c_str()); std::istringstream iss(conn_str.substr(idx + 1, conn_str.length())); int port; iss >> port; addr_ptr->sin_port = htons(port); addr_ptr->sin_family = AF_INET; } static std::string SockaddrToConnectString(const sockaddr_in& addr) { std::ostringstream oss; oss << inet_ntoa(addr.sin_addr); oss << ":"; oss << ntohs(addr.sin_port); return oss.str(); } static std::string GetHostIP() { char buf[256]; gethostname(buf, 256); struct addrinfo addr_hint; memset(&addr_hint, 0, sizeof(struct addrinfo)); addr_hint.ai_family = AF_INET; addr_hint.ai_socktype = SOCK_STREAM; struct addrinfo *addr_head; getaddrinfo(buf, NULL, &addr_hint, &addr_head); return inet_ntoa(reinterpret_cast<struct sockaddr_in*>(addr_head->ai_addr)->sin_addr); } static std::string EscapeSubFolderPath(const std::string& unescaped) { std::string res(unescaped); std::replace(res.begin(), res.end(), '/', '#'); res.erase(std::remove(res.end() - 1, res.end(), '#'), res.end()); return res; } static std::string UnescapeSubFolderPath(const std::string& escaped) { std::string res(escaped); std::replace(res.begin(), res.end(), '#', '/'); return res; } } } #endif // WISSBI_UTIL_HPP_ <commit_msg>add missing header<commit_after>#ifndef WISSBI_UTIL_HPP_ #define WISSBI_UTIL_HPP_ #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netdb.h> #include <string.h> #include <unistd.h> #include <string> #include <sstream> #include <algorithm> namespace wissbi { namespace util { static void ConnectStringToSockaddr(const std::string& conn_str, sockaddr_in* addr_ptr) { memset(addr_ptr, 0, sizeof(*addr_ptr)); auto idx = conn_str.find(":"); addr_ptr->sin_addr.s_addr = inet_addr(conn_str.substr(0, idx).c_str()); std::istringstream iss(conn_str.substr(idx + 1, conn_str.length())); int port; iss >> port; addr_ptr->sin_port = htons(port); addr_ptr->sin_family = AF_INET; } static std::string SockaddrToConnectString(const sockaddr_in& addr) { std::ostringstream oss; oss << inet_ntoa(addr.sin_addr); oss << ":"; oss << ntohs(addr.sin_port); return oss.str(); } static std::string GetHostIP() { char buf[256]; gethostname(buf, 256); struct addrinfo addr_hint; memset(&addr_hint, 0, sizeof(struct addrinfo)); addr_hint.ai_family = AF_INET; addr_hint.ai_socktype = SOCK_STREAM; struct addrinfo *addr_head; getaddrinfo(buf, NULL, &addr_hint, &addr_head); return inet_ntoa(reinterpret_cast<struct sockaddr_in*>(addr_head->ai_addr)->sin_addr); } static std::string EscapeSubFolderPath(const std::string& unescaped) { std::string res(unescaped); std::replace(res.begin(), res.end(), '/', '#'); res.erase(std::remove(res.end() - 1, res.end(), '#'), res.end()); return res; } static std::string UnescapeSubFolderPath(const std::string& escaped) { std::string res(escaped); std::replace(res.begin(), res.end(), '#', '/'); return res; } } } #endif // WISSBI_UTIL_HPP_ <|endoftext|>
<commit_before>/* * Jamoma Asynchronous Object Graph Layer * Creates a wrapper for TTObjects that can be used to build a control graph for asynchronous message passing. * Copyright © 2010, Timothy Place * * License: This code is licensed under the terms of the "New BSD License" * http://creativecommons.org/licenses/BSD/ */ #include "TTGraphObject.h" #include "TTGraphInlet.h" #include "TTGraphOutlet.h" #define thisTTClass TTGraphObject #define thisTTClassName "graph.object" #define thisTTClassTags "graph, wrapper" // Arguments // 1. (required) The name of the Jamoma DSP object you want to wrap // 2. (optional) Number of inlets, default = 1 // 3. (optional) Number of outlets, default = 1 TT_OBJECT_CONSTRUCTOR, mDescription(NULL), mKernel(NULL) { TTErr err = kTTErrNone; TTSymbolPtr wrappedObjectName = NULL; TTUInt16 initialNumChannels = 1; TTUInt16 numInlets = 1; TTUInt16 numOutlets = 1; TT_ASSERT(graph_correct_instantiation_args, arguments.getSize() > 0); arguments.get(0, &wrappedObjectName); if (arguments.getSize() > 1) arguments.get(1, numInlets); if (arguments.getSize() > 2) arguments.get(2, numOutlets); err = TTObjectInstantiate(wrappedObjectName, &mKernel, initialNumChannels); mDictionary = new TTDictionary; mInlets.resize(numInlets); mOutlets.resize(numOutlets); } TTGraphObject::~TTGraphObject() { TTObjectRelease(&mKernel); delete mDictionary; } void TTGraphObject::prepareDescription() { if (valid && mDescription) { mDescription->sIndex = 0; mDescription = NULL; for (TTGraphInletIter inlet = mInlets.begin(); inlet != mInlets.end(); inlet++) inlet->prepareDescriptions(); } } void TTGraphObject::getDescription(TTGraphDescription& desc) { if (mDescription) { // a description for this object has already been created -- use it. desc = *mDescription; } else { // create a new description for this object. desc.mClassName = mKernel->getName(); desc.mObjectInstance = mKernel; desc.mInputDescriptions.clear(); desc.mID = desc.sIndex++; mDescription = &desc; for (TTGraphInletIter inlet = mInlets.begin(); inlet != mInlets.end(); inlet++) inlet->getDescriptions(desc.mInputDescriptions); } } TTErr TTGraphObject::reset() { for_each(mInlets.begin(), mInlets.end(), mem_fun_ref(&TTGraphInlet::reset)); for_each(mOutlets.begin(), mOutlets.end(), mem_fun_ref(&TTGraphOutlet::reset)); return kTTErrNone; } TTErr TTGraphObject::handshake(TTGraphObjectPtr objectWhichIsBeingConnected, TTUInt16 fromOutletNumber, TTUInt16 toInletNumber) { TTErr err; err = mOutlets[fromOutletNumber].connect(objectWhichIsBeingConnected, toInletNumber); return err; } TTErr TTGraphObject::connect(TTGraphObjectPtr anObject, TTUInt16 fromOutletNumber, TTUInt16 toInletNumber) { TTErr err; err = mInlets[toInletNumber].connect(anObject, fromOutletNumber); anObject->handshake(this, fromOutletNumber, toInletNumber); return err; } TTErr TTGraphObject::drop(TTGraphObjectPtr anObject, TTUInt16 fromOutletNumber, TTUInt16 toInletNumber) { TTErr err = kTTErrInvalidValue; if (toInletNumber < mInlets.size()) err = mInlets[toInletNumber].drop(anObject, fromOutletNumber); return err; } TTErr TTGraphObject::push(const TTDictionary& aDictionary) { TTSymbolPtr schema = aDictionary.getSchema(); TTValue v; TTErr err = kTTErrMethodNotFound; TTMessagePtr message = NULL; // If an object defines a 'dictionary' message then this trumps all the others err = mKernel->findMessage(TT("Dictionary"), &message); if (!err && message) { (*mDictionary) = aDictionary; v.set(0, TTPtr(mDictionary)); err = mKernel->sendMessage(TT("Dictionary"), v); } else if (schema == TT("number")) { aDictionary.getValue(v); // TODO: maybe try seeing if there is a "number" message first and then prefer that if it exists? err = mKernel->sendMessage(TT("Calculate"), v); mDictionary->setSchema(TT("number")); mDictionary->setValue(v); // NOTE: doesn't have inlet/outlet info at this point } else if (schema == TT("message")) { TTValue nameValue; TTSymbolPtr nameSymbol = NULL; aDictionary.lookup(TT("name"), nameValue); aDictionary.getValue(v); nameValue.get(0, &nameSymbol); err = mKernel->sendMessage(nameSymbol, v); mDictionary->setSchema(TT("message")); mDictionary->append(TT("name"), nameValue); mDictionary->setValue(v); } else if (schema == TT("attribute")) { TTValue nameValue; TTSymbolPtr nameSymbol = NULL; aDictionary.lookup(TT("name"), nameValue); aDictionary.getValue(v); nameValue.get(0, &nameSymbol); err = mKernel->setAttributeValue(nameSymbol, v); mDictionary->setSchema(TT("attribute")); mDictionary->append(TT("name"), nameValue); mDictionary->setValue(v); } else { // not sure what to do with other dictionary schemas yet... } for (TTGraphOutletIter outlet = mOutlets.begin(); outlet != mOutlets.end(); outlet++) outlet->push(*mDictionary); return err; } <commit_msg>fix for passing attribute dictionaries<commit_after>/* * Jamoma Asynchronous Object Graph Layer * Creates a wrapper for TTObjects that can be used to build a control graph for asynchronous message passing. * Copyright © 2010, Timothy Place * * License: This code is licensed under the terms of the "New BSD License" * http://creativecommons.org/licenses/BSD/ */ #include "TTGraphObject.h" #include "TTGraphInlet.h" #include "TTGraphOutlet.h" #define thisTTClass TTGraphObject #define thisTTClassName "graph.object" #define thisTTClassTags "graph, wrapper" // Arguments // 1. (required) The name of the Jamoma DSP object you want to wrap // 2. (optional) Number of inlets, default = 1 // 3. (optional) Number of outlets, default = 1 TT_OBJECT_CONSTRUCTOR, mDescription(NULL), mKernel(NULL) { TTErr err = kTTErrNone; TTSymbolPtr wrappedObjectName = NULL; TTUInt16 initialNumChannels = 1; TTUInt16 numInlets = 1; TTUInt16 numOutlets = 1; TT_ASSERT(graph_correct_instantiation_args, arguments.getSize() > 0); arguments.get(0, &wrappedObjectName); if (arguments.getSize() > 1) arguments.get(1, numInlets); if (arguments.getSize() > 2) arguments.get(2, numOutlets); err = TTObjectInstantiate(wrappedObjectName, &mKernel, initialNumChannels); mDictionary = new TTDictionary; mInlets.resize(numInlets); mOutlets.resize(numOutlets); } TTGraphObject::~TTGraphObject() { TTObjectRelease(&mKernel); delete mDictionary; } void TTGraphObject::prepareDescription() { if (valid && mDescription) { mDescription->sIndex = 0; mDescription = NULL; for (TTGraphInletIter inlet = mInlets.begin(); inlet != mInlets.end(); inlet++) inlet->prepareDescriptions(); } } void TTGraphObject::getDescription(TTGraphDescription& desc) { if (mDescription) { // a description for this object has already been created -- use it. desc = *mDescription; } else { // create a new description for this object. desc.mClassName = mKernel->getName(); desc.mObjectInstance = mKernel; desc.mInputDescriptions.clear(); desc.mID = desc.sIndex++; mDescription = &desc; for (TTGraphInletIter inlet = mInlets.begin(); inlet != mInlets.end(); inlet++) inlet->getDescriptions(desc.mInputDescriptions); } } TTErr TTGraphObject::reset() { for_each(mInlets.begin(), mInlets.end(), mem_fun_ref(&TTGraphInlet::reset)); for_each(mOutlets.begin(), mOutlets.end(), mem_fun_ref(&TTGraphOutlet::reset)); return kTTErrNone; } TTErr TTGraphObject::handshake(TTGraphObjectPtr objectWhichIsBeingConnected, TTUInt16 fromOutletNumber, TTUInt16 toInletNumber) { TTErr err; err = mOutlets[fromOutletNumber].connect(objectWhichIsBeingConnected, toInletNumber); return err; } TTErr TTGraphObject::connect(TTGraphObjectPtr anObject, TTUInt16 fromOutletNumber, TTUInt16 toInletNumber) { TTErr err; err = mInlets[toInletNumber].connect(anObject, fromOutletNumber); anObject->handshake(this, fromOutletNumber, toInletNumber); return err; } TTErr TTGraphObject::drop(TTGraphObjectPtr anObject, TTUInt16 fromOutletNumber, TTUInt16 toInletNumber) { TTErr err = kTTErrInvalidValue; if (toInletNumber < mInlets.size()) err = mInlets[toInletNumber].drop(anObject, fromOutletNumber); return err; } TTErr TTGraphObject::push(const TTDictionary& aDictionary) { TTSymbolPtr schema = aDictionary.getSchema(); TTValue v; TTErr err = kTTErrMethodNotFound; TTMessagePtr message = NULL; // If an object defines a 'dictionary' message then this trumps all the others err = mKernel->findMessage(TT("Dictionary"), &message); if (!err && message) { (*mDictionary) = aDictionary; v.set(0, TTPtr(mDictionary)); err = mKernel->sendMessage(TT("Dictionary"), v); } else if (schema == TT("number")) { aDictionary.getValue(v); // TODO: maybe try seeing if there is a "number" message first and then prefer that if it exists? err = mKernel->sendMessage(TT("Calculate"), v); mDictionary->setSchema(TT("number")); mDictionary->setValue(v); // NOTE: doesn't have inlet/outlet info at this point } else if (schema == TT("message")) { TTValue nameValue; TTSymbolPtr nameSymbol = NULL; aDictionary.lookup(TT("name"), nameValue); aDictionary.getValue(v); nameValue.get(0, &nameSymbol); err = mKernel->sendMessage(nameSymbol, v); mDictionary->setSchema(TT("message")); mDictionary->append(TT("name"), nameValue); mDictionary->setValue(v); } else if (schema == TT("attribute")) { TTValue nameValue; TTSymbolPtr nameSymbol = NULL; aDictionary.lookup(TT("name"), nameValue); aDictionary.getValue(v); nameValue.get(0, &nameSymbol); err = mKernel->setAttributeValue(nameSymbol, v); mDictionary->setSchema(TT("attribute")); mDictionary->remove(TT("name")); mDictionary->append(TT("name"), nameValue); mDictionary->setValue(v); } else { // not sure what to do with other dictionary schemas yet... } for (TTGraphOutletIter outlet = mOutlets.begin(); outlet != mOutlets.end(); outlet++) outlet->push(*mDictionary); return err; } <|endoftext|>
<commit_before>/* Copyright (C) 2013 Nick Ogden <[email protected]> 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 SQLITE_DATABASE_H #define SQLITE_DATABASE_H #include "statement.hpp" #include "result.hpp" #include <memory> struct sqlite3; namespace std { template<class T> class function; } // namespace std namespace sqlite { static char const *temporary = ""; enum class special_t { in_memory }; static const special_t in_memory = special_t::in_memory; enum access_mode { read_only = 0x01, read_write = 0x02, read_write_create = 0x06 }; enum cache_type { shared_cache = 0x00020000, private_cache = 0x00040000 }; class database { public: database( const std::string &path, const access_mode &permissions, const cache_type &visibility = private_cache ); database( const special_t &in_memory, const access_mode &permissions, const cache_type &visibility = private_cache ); database(const database &other) = delete; database(database &&other) = default; ~database(); database& operator=(const database &other) = delete; database& operator=(database &&other) = default; statement prepare_statement(const std::string &sql) const; result execute(const std::string &sql); result execute(const statement &statement); template<typename T> T execute_scalar(const std::string &sql) const { result results(create_statement(sql)); return (*results.begin())[0].as<T>(); } template<typename T> T execute_scalar(const statement &statement) const { result results(make_result(statement)); return (*results.begin())[0].as<T>(); } std::size_t size() const; friend std::ostream& operator<<(std::ostream &stream, const database &db); private: void close() noexcept; std::shared_ptr<sqlite3_stmt> create_statement(const std::string &sql) const; private: sqlite3 *db = nullptr; }; void as_transaction( database &db, const std::function<void(database &)> &operations ); } // namespace sqlite #endif // SQLITE_DATABASE_H <commit_msg>Remove problematic forward declaration of std::function<commit_after>/* Copyright (C) 2013 Nick Ogden <[email protected]> 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 SQLITE_DATABASE_H #define SQLITE_DATABASE_H #include "statement.hpp" #include "result.hpp" #include <memory> #include <functional> struct sqlite3; namespace sqlite { static char const *temporary = ""; enum class special_t { in_memory }; static const special_t in_memory = special_t::in_memory; enum access_mode { read_only = 0x01, read_write = 0x02, read_write_create = 0x06 }; enum cache_type { shared_cache = 0x00020000, private_cache = 0x00040000 }; class database { public: database( const std::string &path, const access_mode &permissions, const cache_type &visibility = private_cache ); database( const special_t &in_memory, const access_mode &permissions, const cache_type &visibility = private_cache ); database(const database &other) = delete; database(database &&other) = default; ~database(); database& operator=(const database &other) = delete; database& operator=(database &&other) = default; statement prepare_statement(const std::string &sql) const; result execute(const std::string &sql); result execute(const statement &statement); template<typename T> T execute_scalar(const std::string &sql) const { result results(create_statement(sql)); return (*results.begin())[0].as<T>(); } template<typename T> T execute_scalar(const statement &statement) const { result results(make_result(statement)); return (*results.begin())[0].as<T>(); } std::size_t size() const; friend std::ostream& operator<<(std::ostream &stream, const database &db); private: void close() noexcept; std::shared_ptr<sqlite3_stmt> create_statement(const std::string &sql) const; private: sqlite3 *db = nullptr; }; void as_transaction( database &db, const std::function<void(database &)> &operations ); } // namespace sqlite #endif // SQLITE_DATABASE_H <|endoftext|>
<commit_before>#include "confidence_bounds_strategy_evaluator.h" #include "estimator.h" #include "error_calculation.h" #include "debug.h" #include <math.h> #include <assert.h> #include <limits> #include <fstream> #include <sstream> #include <stdexcept> #include <string> #include <iomanip> #include <map> using std::ifstream; using std::ofstream; using std::ostringstream; using std::runtime_error; using std::string; using std::setprecision; using std::endl; using std::pair; using std::make_pair; #include "students_t.h" class ConfidenceBoundsStrategyEvaluator::ErrorConfidenceBounds { public: ErrorConfidenceBounds(Estimator *estimator_=NULL); void observationAdded(double value); double getBound(BoundType type); void saveToFile(ofstream& out); string restoreFromFile(ifstream& in); void setEstimator(Estimator *estimator_); private: static const double CONFIDENCE_ALPHA; Estimator *estimator; // let's try making these log-transformed. double error_mean; double error_variance; double M2; // for running variance algorithm size_t num_samples; // these are not log-transformed; they are inverse-transformed // before being stored. double error_bounds[UPPER + 1]; double getBoundDistance(); }; const double ConfidenceBoundsStrategyEvaluator::ErrorConfidenceBounds::CONFIDENCE_ALPHA = 0.05; ConfidenceBoundsStrategyEvaluator::ErrorConfidenceBounds::ErrorConfidenceBounds(Estimator *estimator_) : estimator(estimator_) { error_mean = 0.0; error_variance = 0.0; M2 = 0.0; num_samples = 0; } void ConfidenceBoundsStrategyEvaluator::ErrorConfidenceBounds::setEstimator(Estimator *estimator_) { estimator = estimator_; } static double get_chebyshev_bound(double alpha, double variance) { // Chebyshev interval for error bounds, as described in my proposal. return sqrt(variance / alpha); } static double get_confidence_interval_width(double alpha, double variance, size_t num_samples) { // student's-t-based confidence interval if (num_samples <= 1) { return 0.0; } else { double t = get_t_value(alpha, num_samples - 1); return t * sqrt(variance / num_samples); } } static double get_prediction_interval_width(double alpha, double variance, size_t num_samples) { // student's-t-based prediction interval // http://en.wikipedia.org/wiki/Prediction_interval#Unknown_mean.2C_unknown_variance if (num_samples <= 1) { return 0.0; } else { double t = get_t_value(alpha, num_samples - 1); return t * sqrt(variance * (1 + (1 / num_samples))); } } double ConfidenceBoundsStrategyEvaluator::ErrorConfidenceBounds::getBoundDistance() { if (false) { return get_chebyshev_bound(CONFIDENCE_ALPHA, error_variance); } else if (false) { return get_confidence_interval_width(CONFIDENCE_ALPHA, error_variance, num_samples); } else { return get_prediction_interval_width(CONFIDENCE_ALPHA, error_variance, num_samples); } } void ConfidenceBoundsStrategyEvaluator::ErrorConfidenceBounds::observationAdded(double value) { dbgprintf("Getting error sample from estimator %p\n", estimator); /* * Algorithm borrowed from * http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#On-line_algorithm * which cites Knuth's /The Art of Computer Programming/, Volume 1. */ ++num_samples; double estimate = estimator->getEstimate(); double error = calculate_error(estimate, value); error = log(error); // natural logarithm double delta = error - error_mean; error_mean += delta / num_samples; M2 += delta * (error - error_mean); if (num_samples > 1) { error_variance = M2 / (num_samples-1); } double bound_distance = getBoundDistance(); double bounds[2]; bounds[0] = exp(error_mean - bound_distance); bounds[1] = exp(error_mean + bound_distance); if (adjusted_estimate(estimate, bounds[0]) < adjusted_estimate(estimate, bounds[1])) { error_bounds[LOWER] = bounds[0]; error_bounds[UPPER] = bounds[1]; } else { error_bounds[LOWER] = bounds[1]; error_bounds[UPPER] = bounds[0]; } dbgprintf("Adding error sample to estimator %p: %f\n", estimator, exp(error)); dbgprintf("n=%4d; error bounds: [%f, %f]\n", num_samples, error_bounds[LOWER], error_bounds[UPPER]); if (adjusted_estimate(estimate, error_bounds[LOWER]) < 0.0) { // PROBLEMATIC. assert(false); // TODO: figure out what to do here. } } double ConfidenceBoundsStrategyEvaluator::ErrorConfidenceBounds::getBound(BoundType type) { double error = num_samples > 0 ? error_bounds[type] : no_error_value(); return adjusted_estimate(estimator->getEstimate(), error); } static int PRECISION = 20; void ConfidenceBoundsStrategyEvaluator::ErrorConfidenceBounds::saveToFile(ofstream& out) { out << estimator->getName() << " " << setprecision(PRECISION) << "num_samples " << num_samples << " mean " << error_mean << " variance " << error_variance << " M2 " << M2 << " bounds " << error_bounds[LOWER] << " " << error_bounds[UPPER] << endl; } string ConfidenceBoundsStrategyEvaluator::ErrorConfidenceBounds::restoreFromFile(ifstream& in) { string name, tag; in >> name >> tag >> num_samples; check(tag == "num_samples", "Failed to parse num_samples"); typedef struct { const char *expected_tag; double& field; } field_t; field_t fields[] = { { "mean", error_mean }, { "variance", error_variance }, { "M2", M2 }, { "bounds", error_bounds[LOWER] } }; size_t num_fields = sizeof(fields) / sizeof(field_t); for (size_t i = 0; i < num_fields; ++i) { in >> tag >> fields[i].field; check(tag == fields[i].expected_tag, "Failed to parse field"); } in >> error_bounds[UPPER]; check(in, "Failed to read bounds from file"); return name; } void ConfidenceBoundsStrategyEvaluator::observationAdded(Estimator *estimator, double value) { dbgprintf("Adding observation %f to estimator %p\n", value, estimator); assert(estimator); string name = estimator->getName(); ErrorConfidenceBounds *bounds = NULL; if (bounds_by_estimator.count(estimator) == 0) { if (placeholders.count(name) > 0) { bounds = placeholders[name]; bounds->setEstimator(estimator); placeholders.erase(name); } else { bounds = new ErrorConfidenceBounds(estimator); } error_bounds.push_back(bounds); bounds_by_estimator[estimator] = error_bounds.back(); } else { bounds = bounds_by_estimator[estimator]; } if (estimators_by_name.count(name) > 0) { assert(estimator == estimators_by_name[name]); } else { estimators_by_name[name] = estimator; } if (estimator->hasEstimate()) { dbgprintf("Adding observation %f to estimator-bounds %p\n", value, bounds); bounds->observationAdded(value); } clearCache(); } ConfidenceBoundsStrategyEvaluator::EvalMode ConfidenceBoundsStrategyEvaluator::DEFAULT_EVAL_MODE = AGGRESSIVE; ConfidenceBoundsStrategyEvaluator::ConfidenceBoundsStrategyEvaluator() : eval_mode(DEFAULT_EVAL_MODE), // TODO: set as option? step(0), last_chooser_arg(NULL) { } ConfidenceBoundsStrategyEvaluator::~ConfidenceBoundsStrategyEvaluator() { for (size_t i = 0; i < error_bounds.size(); ++i) { delete error_bounds[i]; } error_bounds.clear(); bounds_by_estimator.clear(); estimators_by_name.clear(); placeholders.clear(); } ConfidenceBoundsStrategyEvaluator::BoundType ConfidenceBoundsStrategyEvaluator::getBoundType(EvalMode eval_mode, Strategy *strategy, typesafe_eval_fn_t fn) { if (eval_mode == AGGRESSIVE) { // aggressive = upper bound on benefit of redundancy. // = max_time(singular) - min_time(redundant) // or: // //aggressive = lower bound on additional cost of redundancy // // = min_cost(redundant) - max_cost(singular) // //same bound for time and cost. // PROBLEM WITH THAT: cost diff can now be negative. // could lower-bound at 0, but: // a) This actually isn't what I proposed; and // b) This will probably lead to always-redundant, all the time. // What I proposed was that min-additional cost is // calculated using the min-cost for all singular strategies. // So, let's try that. //return strategy->isRedundant() ? LOWER : UPPER; if (fn == strategy->getEvalFn(ENERGY_FN) || fn == strategy->getEvalFn(DATA_FN)) { return LOWER; } else { return strategy->isRedundant() ? LOWER : UPPER; } } else { assert(eval_mode == CONSERVATIVE); // XXX: can these be negative? e.g. is it possible that min_time(singular) < max_time(redundant)? // XXX: above, the calculation of net benefit is: // XXX: (best_singular_time - best_redundant_time) - (best_redundant_cost - best_singular_cost) // XXX: ...where 'best' always means in terms of time. // XXX: and then the redundant strategy is chosen if net_benefit > 0.0. // XXX: so, if min_time(singular) < max_time(redundant), we expect no benefit from redundancy. // XXX: net benefit will be < 0.0, and the singular strategy will be chosen. // XXX: I need to think about this more; I'm not sure yet how much it makes sense. // conservative = lower bound on benefit of redundancy // = min_time(singular) - max_time(redundant) // or: // conservative = upper bound on cost of redundancy // = max_cost(redundant) - min_cost(singular) // same bound for time and cost. return strategy->isRedundant() ? UPPER : LOWER; } } double ConfidenceBoundsStrategyEvaluator::expectedValue(Strategy *strategy, typesafe_eval_fn_t fn, void *strategy_arg, void *chooser_arg) { if (chooser_arg != last_chooser_arg) { clearCache(); } last_chooser_arg = chooser_arg; pair<Strategy*, typesafe_eval_fn_t> key = make_pair(strategy, fn); if (cache.count(key) == 0) { BoundType bound_type = getBoundType(eval_mode, strategy, fn); cache[key] = evaluateBounded(bound_type, fn, strategy_arg, chooser_arg); } return cache[key]; } typedef const double& (*bound_fn_t)(const double&, const double&); double ConfidenceBoundsStrategyEvaluator::evaluateBounded(BoundType bound_type, typesafe_eval_fn_t fn, void *strategy_arg, void *chooser_arg) { bound_fn_t bound_fns[UPPER + 1] = { &std::min<double>, &std::max<double> }; bound_fn_t bound_fn = bound_fns[bound_type]; // opposite fn, for calculating initial value that will // always be replaced bound_fn_t bound_init_fn = bound_fns[(bound_type + 1) % (UPPER + 1)]; // yes, it's a 2^N algorithm, but N is small; e.g. 4 for intnw unsigned int finish = 1 << error_bounds.size(); double val = bound_init_fn(0.0, std::numeric_limits<double>::max()); for (step = 0; step < finish; ++step) { val = bound_fn(val, fn(this, strategy_arg, chooser_arg)); } return val; } double ConfidenceBoundsStrategyEvaluator::getAdjustedEstimatorValue(Estimator *estimator) { // use the low bits of step as selectors for the array of bounds // (i.e. 0 bit = LOWER, 1 bit = UPPER) // LSB is used for bounds[0], MSB for bounds[n-1] // makes the N-way nested loop simpler if (bounds_by_estimator.count(estimator) == 0) { return estimator->getEstimate(); } ErrorConfidenceBounds *est_error = bounds_by_estimator[estimator]; for (size_t i = 0; i < error_bounds.size(); ++i) { if (est_error == error_bounds[i]) { char bit = (step >> i) & 0x1; return est_error->getBound(BoundType(bit)); } } __builtin_unreachable(); } void ConfidenceBoundsStrategyEvaluator::saveToFile(const char *filename) { ofstream out(filename); if (!out) { ostringstream oss; oss << "Failed to open " << filename; throw runtime_error(oss.str()); } out << bounds_by_estimator.size() << " estimator-bounds" << endl; for (size_t i = 0; i < error_bounds.size(); ++i) { error_bounds[i]->saveToFile(out); } out.close(); } void ConfidenceBoundsStrategyEvaluator::restoreFromFile(const char *filename) { ifstream in(filename); if (!in) { ostringstream oss; oss << "Failed to open " << filename; throw runtime_error(oss.str()); } string tag; int num_estimators = -1; in >> num_estimators >> tag; check(num_estimators >= 0, "Failed to read number of estimator bounds"); check(tag == "estimator-bounds", "Failed to read tag"); for (size_t i = 0; i < error_bounds.size(); ++i) { delete error_bounds[i]; } error_bounds.clear(); for (int i = 0; i < num_estimators; ++i) { ErrorConfidenceBounds *bounds = new ErrorConfidenceBounds(NULL); string name = bounds->restoreFromFile(in); if (estimators_by_name.count(name) > 0) { Estimator *estimator = estimators_by_name[name]; bounds->setEstimator(estimator); error_bounds.push_back(bounds); bounds_by_estimator[estimator] = bounds; } else { assert(placeholders.count(name) == 0); placeholders[name] = bounds; } } in.close(); clearCache(); } void ConfidenceBoundsStrategyEvaluator::clearCache() { cache.clear(); } <commit_msg>Tiny format string change.<commit_after>#include "confidence_bounds_strategy_evaluator.h" #include "estimator.h" #include "error_calculation.h" #include "debug.h" #include <math.h> #include <assert.h> #include <limits> #include <fstream> #include <sstream> #include <stdexcept> #include <string> #include <iomanip> #include <map> using std::ifstream; using std::ofstream; using std::ostringstream; using std::runtime_error; using std::string; using std::setprecision; using std::endl; using std::pair; using std::make_pair; #include "students_t.h" class ConfidenceBoundsStrategyEvaluator::ErrorConfidenceBounds { public: ErrorConfidenceBounds(Estimator *estimator_=NULL); void observationAdded(double value); double getBound(BoundType type); void saveToFile(ofstream& out); string restoreFromFile(ifstream& in); void setEstimator(Estimator *estimator_); private: static const double CONFIDENCE_ALPHA; Estimator *estimator; // let's try making these log-transformed. double error_mean; double error_variance; double M2; // for running variance algorithm size_t num_samples; // these are not log-transformed; they are inverse-transformed // before being stored. double error_bounds[UPPER + 1]; double getBoundDistance(); }; const double ConfidenceBoundsStrategyEvaluator::ErrorConfidenceBounds::CONFIDENCE_ALPHA = 0.05; ConfidenceBoundsStrategyEvaluator::ErrorConfidenceBounds::ErrorConfidenceBounds(Estimator *estimator_) : estimator(estimator_) { error_mean = 0.0; error_variance = 0.0; M2 = 0.0; num_samples = 0; } void ConfidenceBoundsStrategyEvaluator::ErrorConfidenceBounds::setEstimator(Estimator *estimator_) { estimator = estimator_; } static double get_chebyshev_bound(double alpha, double variance) { // Chebyshev interval for error bounds, as described in my proposal. return sqrt(variance / alpha); } static double get_confidence_interval_width(double alpha, double variance, size_t num_samples) { // student's-t-based confidence interval if (num_samples <= 1) { return 0.0; } else { double t = get_t_value(alpha, num_samples - 1); return t * sqrt(variance / num_samples); } } static double get_prediction_interval_width(double alpha, double variance, size_t num_samples) { // student's-t-based prediction interval // http://en.wikipedia.org/wiki/Prediction_interval#Unknown_mean.2C_unknown_variance if (num_samples <= 1) { return 0.0; } else { double t = get_t_value(alpha, num_samples - 1); return t * sqrt(variance * (1 + (1 / num_samples))); } } double ConfidenceBoundsStrategyEvaluator::ErrorConfidenceBounds::getBoundDistance() { if (false) { return get_chebyshev_bound(CONFIDENCE_ALPHA, error_variance); } else if (false) { return get_confidence_interval_width(CONFIDENCE_ALPHA, error_variance, num_samples); } else { return get_prediction_interval_width(CONFIDENCE_ALPHA, error_variance, num_samples); } } void ConfidenceBoundsStrategyEvaluator::ErrorConfidenceBounds::observationAdded(double value) { dbgprintf("Getting error sample from estimator %p\n", estimator); /* * Algorithm borrowed from * http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#On-line_algorithm * which cites Knuth's /The Art of Computer Programming/, Volume 1. */ ++num_samples; double estimate = estimator->getEstimate(); double error = calculate_error(estimate, value); error = log(error); // natural logarithm double delta = error - error_mean; error_mean += delta / num_samples; M2 += delta * (error - error_mean); if (num_samples > 1) { error_variance = M2 / (num_samples-1); } double bound_distance = getBoundDistance(); double bounds[2]; bounds[0] = exp(error_mean - bound_distance); bounds[1] = exp(error_mean + bound_distance); if (adjusted_estimate(estimate, bounds[0]) < adjusted_estimate(estimate, bounds[1])) { error_bounds[LOWER] = bounds[0]; error_bounds[UPPER] = bounds[1]; } else { error_bounds[LOWER] = bounds[1]; error_bounds[UPPER] = bounds[0]; } dbgprintf("Adding error sample to estimator %p: %f\n", estimator, exp(error)); dbgprintf("n=%4zu; error bounds: [%f, %f]\n", num_samples, error_bounds[LOWER], error_bounds[UPPER]); if (adjusted_estimate(estimate, error_bounds[LOWER]) < 0.0) { // PROBLEMATIC. assert(false); // TODO: figure out what to do here. } } double ConfidenceBoundsStrategyEvaluator::ErrorConfidenceBounds::getBound(BoundType type) { double error = num_samples > 0 ? error_bounds[type] : no_error_value(); return adjusted_estimate(estimator->getEstimate(), error); } static int PRECISION = 20; void ConfidenceBoundsStrategyEvaluator::ErrorConfidenceBounds::saveToFile(ofstream& out) { out << estimator->getName() << " " << setprecision(PRECISION) << "num_samples " << num_samples << " mean " << error_mean << " variance " << error_variance << " M2 " << M2 << " bounds " << error_bounds[LOWER] << " " << error_bounds[UPPER] << endl; } string ConfidenceBoundsStrategyEvaluator::ErrorConfidenceBounds::restoreFromFile(ifstream& in) { string name, tag; in >> name >> tag >> num_samples; check(tag == "num_samples", "Failed to parse num_samples"); typedef struct { const char *expected_tag; double& field; } field_t; field_t fields[] = { { "mean", error_mean }, { "variance", error_variance }, { "M2", M2 }, { "bounds", error_bounds[LOWER] } }; size_t num_fields = sizeof(fields) / sizeof(field_t); for (size_t i = 0; i < num_fields; ++i) { in >> tag >> fields[i].field; check(tag == fields[i].expected_tag, "Failed to parse field"); } in >> error_bounds[UPPER]; check(in, "Failed to read bounds from file"); return name; } void ConfidenceBoundsStrategyEvaluator::observationAdded(Estimator *estimator, double value) { dbgprintf("Adding observation %f to estimator %p\n", value, estimator); assert(estimator); string name = estimator->getName(); ErrorConfidenceBounds *bounds = NULL; if (bounds_by_estimator.count(estimator) == 0) { if (placeholders.count(name) > 0) { bounds = placeholders[name]; bounds->setEstimator(estimator); placeholders.erase(name); } else { bounds = new ErrorConfidenceBounds(estimator); } error_bounds.push_back(bounds); bounds_by_estimator[estimator] = error_bounds.back(); } else { bounds = bounds_by_estimator[estimator]; } if (estimators_by_name.count(name) > 0) { assert(estimator == estimators_by_name[name]); } else { estimators_by_name[name] = estimator; } if (estimator->hasEstimate()) { dbgprintf("Adding observation %f to estimator-bounds %p\n", value, bounds); bounds->observationAdded(value); } clearCache(); } ConfidenceBoundsStrategyEvaluator::EvalMode ConfidenceBoundsStrategyEvaluator::DEFAULT_EVAL_MODE = AGGRESSIVE; ConfidenceBoundsStrategyEvaluator::ConfidenceBoundsStrategyEvaluator() : eval_mode(DEFAULT_EVAL_MODE), // TODO: set as option? step(0), last_chooser_arg(NULL) { } ConfidenceBoundsStrategyEvaluator::~ConfidenceBoundsStrategyEvaluator() { for (size_t i = 0; i < error_bounds.size(); ++i) { delete error_bounds[i]; } error_bounds.clear(); bounds_by_estimator.clear(); estimators_by_name.clear(); placeholders.clear(); } ConfidenceBoundsStrategyEvaluator::BoundType ConfidenceBoundsStrategyEvaluator::getBoundType(EvalMode eval_mode, Strategy *strategy, typesafe_eval_fn_t fn) { if (eval_mode == AGGRESSIVE) { // aggressive = upper bound on benefit of redundancy. // = max_time(singular) - min_time(redundant) // or: // //aggressive = lower bound on additional cost of redundancy // // = min_cost(redundant) - max_cost(singular) // //same bound for time and cost. // PROBLEM WITH THAT: cost diff can now be negative. // could lower-bound at 0, but: // a) This actually isn't what I proposed; and // b) This will probably lead to always-redundant, all the time. // What I proposed was that min-additional cost is // calculated using the min-cost for all singular strategies. // So, let's try that. //return strategy->isRedundant() ? LOWER : UPPER; if (fn == strategy->getEvalFn(ENERGY_FN) || fn == strategy->getEvalFn(DATA_FN)) { return LOWER; } else { return strategy->isRedundant() ? LOWER : UPPER; } } else { assert(eval_mode == CONSERVATIVE); // XXX: can these be negative? e.g. is it possible that min_time(singular) < max_time(redundant)? // XXX: above, the calculation of net benefit is: // XXX: (best_singular_time - best_redundant_time) - (best_redundant_cost - best_singular_cost) // XXX: ...where 'best' always means in terms of time. // XXX: and then the redundant strategy is chosen if net_benefit > 0.0. // XXX: so, if min_time(singular) < max_time(redundant), we expect no benefit from redundancy. // XXX: net benefit will be < 0.0, and the singular strategy will be chosen. // XXX: I need to think about this more; I'm not sure yet how much it makes sense. // conservative = lower bound on benefit of redundancy // = min_time(singular) - max_time(redundant) // or: // conservative = upper bound on cost of redundancy // = max_cost(redundant) - min_cost(singular) // same bound for time and cost. return strategy->isRedundant() ? UPPER : LOWER; } } double ConfidenceBoundsStrategyEvaluator::expectedValue(Strategy *strategy, typesafe_eval_fn_t fn, void *strategy_arg, void *chooser_arg) { if (chooser_arg != last_chooser_arg) { clearCache(); } last_chooser_arg = chooser_arg; pair<Strategy*, typesafe_eval_fn_t> key = make_pair(strategy, fn); if (cache.count(key) == 0) { BoundType bound_type = getBoundType(eval_mode, strategy, fn); cache[key] = evaluateBounded(bound_type, fn, strategy_arg, chooser_arg); } return cache[key]; } typedef const double& (*bound_fn_t)(const double&, const double&); double ConfidenceBoundsStrategyEvaluator::evaluateBounded(BoundType bound_type, typesafe_eval_fn_t fn, void *strategy_arg, void *chooser_arg) { bound_fn_t bound_fns[UPPER + 1] = { &std::min<double>, &std::max<double> }; bound_fn_t bound_fn = bound_fns[bound_type]; // opposite fn, for calculating initial value that will // always be replaced bound_fn_t bound_init_fn = bound_fns[(bound_type + 1) % (UPPER + 1)]; // yes, it's a 2^N algorithm, but N is small; e.g. 4 for intnw unsigned int finish = 1 << error_bounds.size(); double val = bound_init_fn(0.0, std::numeric_limits<double>::max()); for (step = 0; step < finish; ++step) { val = bound_fn(val, fn(this, strategy_arg, chooser_arg)); } return val; } double ConfidenceBoundsStrategyEvaluator::getAdjustedEstimatorValue(Estimator *estimator) { // use the low bits of step as selectors for the array of bounds // (i.e. 0 bit = LOWER, 1 bit = UPPER) // LSB is used for bounds[0], MSB for bounds[n-1] // makes the N-way nested loop simpler if (bounds_by_estimator.count(estimator) == 0) { return estimator->getEstimate(); } ErrorConfidenceBounds *est_error = bounds_by_estimator[estimator]; for (size_t i = 0; i < error_bounds.size(); ++i) { if (est_error == error_bounds[i]) { char bit = (step >> i) & 0x1; return est_error->getBound(BoundType(bit)); } } __builtin_unreachable(); } void ConfidenceBoundsStrategyEvaluator::saveToFile(const char *filename) { ofstream out(filename); if (!out) { ostringstream oss; oss << "Failed to open " << filename; throw runtime_error(oss.str()); } out << bounds_by_estimator.size() << " estimator-bounds" << endl; for (size_t i = 0; i < error_bounds.size(); ++i) { error_bounds[i]->saveToFile(out); } out.close(); } void ConfidenceBoundsStrategyEvaluator::restoreFromFile(const char *filename) { ifstream in(filename); if (!in) { ostringstream oss; oss << "Failed to open " << filename; throw runtime_error(oss.str()); } string tag; int num_estimators = -1; in >> num_estimators >> tag; check(num_estimators >= 0, "Failed to read number of estimator bounds"); check(tag == "estimator-bounds", "Failed to read tag"); for (size_t i = 0; i < error_bounds.size(); ++i) { delete error_bounds[i]; } error_bounds.clear(); for (int i = 0; i < num_estimators; ++i) { ErrorConfidenceBounds *bounds = new ErrorConfidenceBounds(NULL); string name = bounds->restoreFromFile(in); if (estimators_by_name.count(name) > 0) { Estimator *estimator = estimators_by_name[name]; bounds->setEstimator(estimator); error_bounds.push_back(bounds); bounds_by_estimator[estimator] = bounds; } else { assert(placeholders.count(name) == 0); placeholders[name] = bounds; } } in.close(); clearCache(); } void ConfidenceBoundsStrategyEvaluator::clearCache() { cache.clear(); } <|endoftext|>
<commit_before>/* * Copyright (C) 2006-2013 Music Technology Group - Universitat Pompeu Fabra * * This file is part of Essentia * * Essentia 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 (FSF), 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 Affero GNU General Public License * version 3 along with this program. If not, see http://www.gnu.org/licenses/ */ #include "MusicTonalDescriptors.h" using namespace std; using namespace essentia; using namespace essentia::streaming; const string MusicTonalDescriptors::nameSpace="tonal."; void MusicTonalDescriptors::createNetworkTuningFrequency(SourceBase& source, Pool& pool){ int frameSize = int(options.value<Real>("tonal.frameSize")); int hopSize = int(options.value<Real>("tonal.hopSize")); string silentFrames = options.value<string>("tonal.silentFrames"); string windowType = options.value<string>("tonal.windowType"); int zeroPadding = int(options.value<Real>("tonal.zeroPadding")); AlgorithmFactory& factory = AlgorithmFactory::instance(); Algorithm* fc = factory.create("FrameCutter", "frameSize", frameSize, "hopSize", hopSize, "silentFrames", silentFrames); Algorithm* w = factory.create("Windowing", "type", windowType, "zeroPadding", zeroPadding); Algorithm* spec = factory.create("Spectrum"); Algorithm* peaks = factory.create("SpectralPeaks", "maxPeaks", 10000, "magnitudeThreshold", 0.00001, "minFrequency", 40, "maxFrequency", 5000, "orderBy", "frequency"); Algorithm* tuning = factory.create("TuningFrequency"); source >> fc->input("signal"); fc->output("frame") >> w->input("frame"); w->output("frame") >> spec->input("frame"); spec->output("spectrum") >> peaks->input("spectrum"); peaks->output("magnitudes") >> tuning->input("magnitudes"); peaks->output("frequencies") >> tuning->input("frequencies"); tuning->output("tuningFrequency") >> PC(pool, nameSpace + "tuning_frequency"); tuning->output("tuningCents") >> NOWHERE; } void MusicTonalDescriptors::createNetwork(SourceBase& source, Pool& pool){ int frameSize = int(options.value<Real>("tonal.frameSize")); int hopSize = int(options.value<Real>("tonal.hopSize")); string silentFrames = options.value<string>("tonal.silentFrames"); string windowType = options.value<string>("tonal.windowType"); int zeroPadding = int(options.value<Real>("tonal.zeroPadding")); Real tuningFreq = pool.value<vector<Real> >(nameSpace + "tuning_frequency").back(); AlgorithmFactory& factory = AlgorithmFactory::instance(); Algorithm* fc = factory.create("FrameCutter", "frameSize", frameSize, "hopSize", hopSize, "silentFrames", silentFrames); Algorithm* w = factory.create("Windowing", "type", windowType, "zeroPadding", zeroPadding); Algorithm* spec = factory.create("Spectrum"); Algorithm* peaks = factory.create("SpectralPeaks", "maxPeaks", 10000, "magnitudeThreshold", 0.00001, "minFrequency", 40, "maxFrequency", 5000, "orderBy", "magnitude"); Algorithm* hpcp_key = factory.create("HPCP", "size", 36, "referenceFrequency", tuningFreq, "bandPreset", false, "minFrequency", 40.0, "maxFrequency", 5000.0, "weightType", "squaredCosine", "nonLinear", false, "windowSize", 4.0/3.0); Algorithm* skey = factory.create("Key"); Algorithm* hpcp_chord = factory.create("HPCP", "size", 36, "referenceFrequency", tuningFreq, "harmonics", 8, "bandPreset", true, "minFrequency", 40.0, "maxFrequency", 5000.0, "splitFrequency", 500.0, "weightType", "cosine", "nonLinear", true, "windowSize", 0.5); Algorithm* schord = factory.create("ChordsDetection"); Algorithm* schords_desc = factory.create("ChordsDescriptors"); source >> fc->input("signal"); fc->output("frame") >> w->input("frame"); w->output("frame") >> spec->input("frame"); spec->output("spectrum") >> peaks->input("spectrum"); peaks->output("frequencies") >> hpcp_key->input("frequencies"); peaks->output("magnitudes") >> hpcp_key->input("magnitudes"); hpcp_key->output("hpcp") >> PC(pool, nameSpace + "hpcp"); hpcp_key->output("hpcp") >> skey->input("pcp"); skey->output("key") >> PC(pool, nameSpace + "key_key"); skey->output("scale") >> PC(pool, nameSpace + "key_scale"); skey->output("strength") >> PC(pool, nameSpace + "key_strength"); peaks->output("frequencies") >> hpcp_chord->input("frequencies"); peaks->output("magnitudes") >> hpcp_chord->input("magnitudes"); hpcp_chord->output("hpcp") >> schord->input("pcp"); schord->output("strength") >> PC(pool, nameSpace + "chords_strength"); // TODO: Chords progression has low practical sense and is based on a very simple algorithm prone to errors. // We need to have better algorithm first to include this descriptor. // schord->output("chords") >> PC(pool, nameSpace + "chords_progression"); schord->output("chords") >> schords_desc->input("chords"); skey->output("key") >> schords_desc->input("key"); skey->output("scale") >> schords_desc->input("scale"); schords_desc->output("chordsHistogram") >> PC(pool, nameSpace + "chords_histogram"); schords_desc->output("chordsNumberRate") >> PC(pool, nameSpace + "chords_number_rate"); schords_desc->output("chordsChangesRate") >> PC(pool, nameSpace + "chords_changes_rate"); schords_desc->output("chordsKey") >> PC(pool, nameSpace + "chords_key"); schords_desc->output("chordsScale") >> PC(pool, nameSpace + "chords_scale"); // HPCP Entropy Algorithm* ent = factory.create("Entropy"); hpcp_chord->output("hpcp") >> ent->input("array"); ent->output("entropy") >> PC(pool, nameSpace + "hpcp_entropy"); // HPCP Tuning Algorithm* hpcp_tuning = factory.create("HPCP", "size", 120, "referenceFrequency", tuningFreq, "harmonics", 8, "bandPreset", true, "minFrequency", 40.0, "maxFrequency", 5000.0, "splitFrequency", 500.0, "weightType", "cosine", "nonLinear", true, "windowSize", 0.5); peaks->output("frequencies") >> hpcp_tuning->input("frequencies"); peaks->output("magnitudes") >> hpcp_tuning->input("magnitudes"); hpcp_tuning->output("hpcp") >> PC(pool, nameSpace + "hpcp_highres"); } void MusicTonalDescriptors::computeTuningSystemFeatures(Pool& pool){ vector<Real> hpcp_highres = meanFrames(pool.value<vector<vector<Real> > >(nameSpace + "hpcp_highres")); pool.remove(nameSpace + "hpcp_highres"); normalize(hpcp_highres); // 1- diatonic strength standard::AlgorithmFactory& factory = standard::AlgorithmFactory::instance(); standard::Algorithm* keyDetect = factory.create("Key", "profileType", "diatonic"); string key, scale; Real strength, unused; keyDetect->input("pcp").set(hpcp_highres); keyDetect->output("key").set(key); keyDetect->output("scale").set(scale); keyDetect->output("strength").set(strength); keyDetect->output("firstToSecondRelativeStrength").set(unused); keyDetect->compute(); pool.set(nameSpace + "tuning_diatonic_strength", strength); // 2- high resolution features standard::Algorithm* highres = factory.create("HighResolutionFeatures"); Real eqTempDeviation, ntEnergy, ntPeaks; highres->input("hpcp").set(hpcp_highres); highres->output("equalTemperedDeviation").set(eqTempDeviation); highres->output("nonTemperedEnergyRatio").set(ntEnergy); highres->output("nonTemperedPeaksEnergyRatio").set(ntPeaks); highres->compute(); pool.set(nameSpace + "tuning_equal_tempered_deviation", eqTempDeviation); pool.set(nameSpace + "tuning_nontempered_energy_ratio", ntEnergy); // 3- THPCP vector<Real> hpcp = meanFrames(pool.value<vector<vector<Real> > >(nameSpace + "hpcp")); normalize(hpcp); int idxMax = argmax(hpcp); vector<Real> hpcp_bak = hpcp; for (int i=idxMax; i<(int)hpcp.size(); i++) { hpcp[i-idxMax] = hpcp_bak[i]; } int offset = hpcp.size() - idxMax; for (int i=0; i<idxMax; i++) { hpcp[i+offset] = hpcp_bak[i]; } pool.set(nameSpace + "thpcp", hpcp); delete keyDetect; delete highres; } <commit_msg>Define parameters for Key algorithms in music extractor<commit_after>/* * Copyright (C) 2006-2013 Music Technology Group - Universitat Pompeu Fabra * * This file is part of Essentia * * Essentia 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 (FSF), 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 Affero GNU General Public License * version 3 along with this program. If not, see http://www.gnu.org/licenses/ */ #include "MusicTonalDescriptors.h" using namespace std; using namespace essentia; using namespace essentia::streaming; const string MusicTonalDescriptors::nameSpace="tonal."; void MusicTonalDescriptors::createNetworkTuningFrequency(SourceBase& source, Pool& pool){ int frameSize = int(options.value<Real>("tonal.frameSize")); int hopSize = int(options.value<Real>("tonal.hopSize")); string silentFrames = options.value<string>("tonal.silentFrames"); string windowType = options.value<string>("tonal.windowType"); int zeroPadding = int(options.value<Real>("tonal.zeroPadding")); AlgorithmFactory& factory = AlgorithmFactory::instance(); Algorithm* fc = factory.create("FrameCutter", "frameSize", frameSize, "hopSize", hopSize, "silentFrames", silentFrames); Algorithm* w = factory.create("Windowing", "type", windowType, "zeroPadding", zeroPadding); Algorithm* spec = factory.create("Spectrum"); Algorithm* peaks = factory.create("SpectralPeaks", "maxPeaks", 10000, "magnitudeThreshold", 0.00001, "minFrequency", 40, "maxFrequency", 5000, "orderBy", "frequency"); Algorithm* tuning = factory.create("TuningFrequency"); source >> fc->input("signal"); fc->output("frame") >> w->input("frame"); w->output("frame") >> spec->input("frame"); spec->output("spectrum") >> peaks->input("spectrum"); peaks->output("magnitudes") >> tuning->input("magnitudes"); peaks->output("frequencies") >> tuning->input("frequencies"); tuning->output("tuningFrequency") >> PC(pool, nameSpace + "tuning_frequency"); tuning->output("tuningCents") >> NOWHERE; } void MusicTonalDescriptors::createNetwork(SourceBase& source, Pool& pool){ int frameSize = int(options.value<Real>("tonal.frameSize")); int hopSize = int(options.value<Real>("tonal.hopSize")); string silentFrames = options.value<string>("tonal.silentFrames"); string windowType = options.value<string>("tonal.windowType"); int zeroPadding = int(options.value<Real>("tonal.zeroPadding")); Real tuningFreq = pool.value<vector<Real> >(nameSpace + "tuning_frequency").back(); AlgorithmFactory& factory = AlgorithmFactory::instance(); Algorithm* fc = factory.create("FrameCutter", "frameSize", frameSize, "hopSize", hopSize, "silentFrames", silentFrames); Algorithm* w = factory.create("Windowing", "type", windowType, "zeroPadding", zeroPadding); Algorithm* spec = factory.create("Spectrum"); Algorithm* peaks = factory.create("SpectralPeaks", "maxPeaks", 10000, "magnitudeThreshold", 0.00001, "minFrequency", 40, "maxFrequency", 5000, "orderBy", "magnitude"); Algorithm* hpcp_key = factory.create("HPCP", "size", 36, "referenceFrequency", tuningFreq, "bandPreset", false, "minFrequency", 40.0, "maxFrequency", 5000.0, "weightType", "squaredCosine", "nonLinear", false, "windowSize", 4.0/3.0); Algorithm* skey = factory.create("Key", "numHarmonics", 4, "pcpSize", 36, "profileType", "temperley", "slope", 0.6, "usePolyphony", true, "useThreeChords", true); Algorithm* hpcp_chord = factory.create("HPCP", "size", 36, "referenceFrequency", tuningFreq, "harmonics", 8, "bandPreset", true, "minFrequency", 40.0, "maxFrequency", 5000.0, "splitFrequency", 500.0, "weightType", "cosine", "nonLinear", true, "windowSize", 0.5); Algorithm* schord = factory.create("ChordsDetection"); Algorithm* schords_desc = factory.create("ChordsDescriptors"); source >> fc->input("signal"); fc->output("frame") >> w->input("frame"); w->output("frame") >> spec->input("frame"); spec->output("spectrum") >> peaks->input("spectrum"); peaks->output("frequencies") >> hpcp_key->input("frequencies"); peaks->output("magnitudes") >> hpcp_key->input("magnitudes"); hpcp_key->output("hpcp") >> PC(pool, nameSpace + "hpcp"); hpcp_key->output("hpcp") >> skey->input("pcp"); skey->output("key") >> PC(pool, nameSpace + "key_key"); skey->output("scale") >> PC(pool, nameSpace + "key_scale"); skey->output("strength") >> PC(pool, nameSpace + "key_strength"); peaks->output("frequencies") >> hpcp_chord->input("frequencies"); peaks->output("magnitudes") >> hpcp_chord->input("magnitudes"); hpcp_chord->output("hpcp") >> schord->input("pcp"); schord->output("strength") >> PC(pool, nameSpace + "chords_strength"); // TODO: Chords progression has low practical sense and is based on a very simple algorithm prone to errors. // We need to have better algorithm first to include this descriptor. // schord->output("chords") >> PC(pool, nameSpace + "chords_progression"); schord->output("chords") >> schords_desc->input("chords"); skey->output("key") >> schords_desc->input("key"); skey->output("scale") >> schords_desc->input("scale"); schords_desc->output("chordsHistogram") >> PC(pool, nameSpace + "chords_histogram"); schords_desc->output("chordsNumberRate") >> PC(pool, nameSpace + "chords_number_rate"); schords_desc->output("chordsChangesRate") >> PC(pool, nameSpace + "chords_changes_rate"); schords_desc->output("chordsKey") >> PC(pool, nameSpace + "chords_key"); schords_desc->output("chordsScale") >> PC(pool, nameSpace + "chords_scale"); // HPCP Entropy Algorithm* ent = factory.create("Entropy"); hpcp_chord->output("hpcp") >> ent->input("array"); ent->output("entropy") >> PC(pool, nameSpace + "hpcp_entropy"); // HPCP Tuning Algorithm* hpcp_tuning = factory.create("HPCP", "size", 120, "referenceFrequency", tuningFreq, "harmonics", 8, "bandPreset", true, "minFrequency", 40.0, "maxFrequency", 5000.0, "splitFrequency", 500.0, "weightType", "cosine", "nonLinear", true, "windowSize", 0.5); peaks->output("frequencies") >> hpcp_tuning->input("frequencies"); peaks->output("magnitudes") >> hpcp_tuning->input("magnitudes"); hpcp_tuning->output("hpcp") >> PC(pool, nameSpace + "hpcp_highres"); } void MusicTonalDescriptors::computeTuningSystemFeatures(Pool& pool){ vector<Real> hpcp_highres = meanFrames(pool.value<vector<vector<Real> > >(nameSpace + "hpcp_highres")); pool.remove(nameSpace + "hpcp_highres"); normalize(hpcp_highres); // 1- diatonic strength standard::AlgorithmFactory& factory = standard::AlgorithmFactory::instance(); standard::Algorithm* keyDetect = factory.create("Key", "numHarmonics", 4, "pcpSize", 36, "profileType", "diatonic", "slope", 0.6, "usePolyphony", true, "useThreeChords", true); string key, scale; Real strength, unused; keyDetect->input("pcp").set(hpcp_highres); keyDetect->output("key").set(key); keyDetect->output("scale").set(scale); keyDetect->output("strength").set(strength); keyDetect->output("firstToSecondRelativeStrength").set(unused); keyDetect->compute(); pool.set(nameSpace + "tuning_diatonic_strength", strength); // 2- high resolution features standard::Algorithm* highres = factory.create("HighResolutionFeatures"); Real eqTempDeviation, ntEnergy, ntPeaks; highres->input("hpcp").set(hpcp_highres); highres->output("equalTemperedDeviation").set(eqTempDeviation); highres->output("nonTemperedEnergyRatio").set(ntEnergy); highres->output("nonTemperedPeaksEnergyRatio").set(ntPeaks); highres->compute(); pool.set(nameSpace + "tuning_equal_tempered_deviation", eqTempDeviation); pool.set(nameSpace + "tuning_nontempered_energy_ratio", ntEnergy); // 3- THPCP vector<Real> hpcp = meanFrames(pool.value<vector<vector<Real> > >(nameSpace + "hpcp")); normalize(hpcp); int idxMax = argmax(hpcp); vector<Real> hpcp_bak = hpcp; for (int i=idxMax; i<(int)hpcp.size(); i++) { hpcp[i-idxMax] = hpcp_bak[i]; } int offset = hpcp.size() - idxMax; for (int i=0; i<idxMax; i++) { hpcp[i+offset] = hpcp_bak[i]; } pool.set(nameSpace + "thpcp", hpcp); delete keyDetect; delete highres; } <|endoftext|>
<commit_before>// license:BSD-3-Clause // copyright-holders:Aaron Giles /*************************************************************************** delegate.c Templates and classes to enable delegates for callbacks. ***************************************************************************/ #include <assert.h> #include <cstdint> #include <stdio.h> #include "delegate.h" //************************************************************************** // GLOBAL VARIABLES //************************************************************************** #if (USE_DELEGATE_TYPE == DELEGATE_TYPE_COMPATIBLE) delegate_mfp::raw_mfp_data delegate_mfp::s_null_mfp = { {0 }}; #endif //************************************************************************** // INTERNAL DELEGATE HELPERS //************************************************************************** #if (USE_DELEGATE_TYPE == DELEGATE_TYPE_INTERNAL) //------------------------------------------------- // delegate_convert_raw - given an object and an raw function, adjust the object base // and return the actual final code pointer //-------------------------------------------------// delegate_generic_function delegate_mfp::convert_to_generic(delegate_generic_class *&object) const { #if defined(__arm__) || defined(__ARMEL__) || defined(__aarch64__) || defined(__MIPSEL__) || defined(__mips_isa_rev) || defined(__mips64) if ((m_this_delta & 1) == 0) { #if defined(LOG_DELEGATES) printf("Calculated Addr = %08x\n", (uintptr_t)(void*)(m_function)); #endif object = reinterpret_cast<delegate_generic_class *>(reinterpret_cast<std::uint8_t *>(object) + m_this_delta); return reinterpret_cast<delegate_generic_function>(m_function); } object = reinterpret_cast<delegate_generic_class *>(reinterpret_cast<std::uint8_t *>(object)); // otherwise, it is the byte index into the vtable where the actual function lives std::uint8_t *vtable_base = *reinterpret_cast<std::uint8_t **>(object); #if defined(LOG_DELEGATES) printf("Calculated Addr = %08x (VTAB)\n", (uintptr_t)(void*)(*reinterpret_cast<delegate_generic_function *>(vtable_base + m_function + m_this_delta - 1))); #endif return *reinterpret_cast<delegate_generic_function *>(vtable_base + m_function + m_this_delta - 1); #else // apply the "this" delta to the object first object = reinterpret_cast<delegate_generic_class *>(reinterpret_cast<std::uint8_t *>(object) + m_this_delta); // if the low bit of the vtable index is clear, then it is just a raw function pointer if (!(m_function & 1)) { #if defined(LOG_DELEGATES) printf("Calculated Addr = %08x\n", (uintptr_t)(void*)(m_function)); #endif return reinterpret_cast<delegate_generic_function>(m_function); } // otherwise, it is the byte index into the vtable where the actual function lives std::uint8_t *vtable_base = *reinterpret_cast<std::uint8_t **>(object); #if defined(LOG_DELEGATES) printf("Calculated Addr = %08x (VTAB)\n", (uintptr_t)(void*)(*reinterpret_cast<delegate_generic_function *>(vtable_base + m_function - 1))); #endif return *reinterpret_cast<delegate_generic_function *>(vtable_base + m_function - 1); #endif } #endif <commit_msg>confirmed working with emscripten<commit_after>// license:BSD-3-Clause // copyright-holders:Aaron Giles /*************************************************************************** delegate.c Templates and classes to enable delegates for callbacks. ***************************************************************************/ #include <assert.h> #include <cstdint> #include <stdio.h> #include "delegate.h" //************************************************************************** // GLOBAL VARIABLES //************************************************************************** #if (USE_DELEGATE_TYPE == DELEGATE_TYPE_COMPATIBLE) delegate_mfp::raw_mfp_data delegate_mfp::s_null_mfp = { {0 }}; #endif //************************************************************************** // INTERNAL DELEGATE HELPERS //************************************************************************** #if (USE_DELEGATE_TYPE == DELEGATE_TYPE_INTERNAL) //------------------------------------------------- // delegate_convert_raw - given an object and an raw function, adjust the object base // and return the actual final code pointer //-------------------------------------------------// delegate_generic_function delegate_mfp::convert_to_generic(delegate_generic_class *&object) const { #if defined(__arm__) || defined(__ARMEL__) || defined(__aarch64__) || defined(__MIPSEL__) || defined(__mips_isa_rev) || defined(__mips64) || defined(EMSCRIPTEN) if ((m_this_delta & 1) == 0) { #if defined(LOG_DELEGATES) printf("Calculated Addr = %08x\n", (uintptr_t)(void*)(m_function)); #endif object = reinterpret_cast<delegate_generic_class *>(reinterpret_cast<std::uint8_t *>(object) + m_this_delta); return reinterpret_cast<delegate_generic_function>(m_function); } object = reinterpret_cast<delegate_generic_class *>(reinterpret_cast<std::uint8_t *>(object)); // otherwise, it is the byte index into the vtable where the actual function lives std::uint8_t *vtable_base = *reinterpret_cast<std::uint8_t **>(object); #if defined(LOG_DELEGATES) printf("Calculated Addr = %08x (VTAB)\n", (uintptr_t)(void*)(*reinterpret_cast<delegate_generic_function *>(vtable_base + m_function + m_this_delta - 1))); #endif return *reinterpret_cast<delegate_generic_function *>(vtable_base + m_function + m_this_delta - 1); #else // apply the "this" delta to the object first object = reinterpret_cast<delegate_generic_class *>(reinterpret_cast<std::uint8_t *>(object) + m_this_delta); // if the low bit of the vtable index is clear, then it is just a raw function pointer if (!(m_function & 1)) { #if defined(LOG_DELEGATES) printf("Calculated Addr = %08x\n", (uintptr_t)(void*)(m_function)); #endif return reinterpret_cast<delegate_generic_function>(m_function); } // otherwise, it is the byte index into the vtable where the actual function lives std::uint8_t *vtable_base = *reinterpret_cast<std::uint8_t **>(object); #if defined(LOG_DELEGATES) printf("Calculated Addr = %08x (VTAB)\n", (uintptr_t)(void*)(*reinterpret_cast<delegate_generic_function *>(vtable_base + m_function - 1))); #endif return *reinterpret_cast<delegate_generic_function *>(vtable_base + m_function - 1); #endif } #endif <|endoftext|>
<commit_before>// MIT License // // Copyright (c) 2017 Artur Wyszyński, aljen at hitomi dot pl // // 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 "elements/element.h" #include <cassert> #include <iostream> #include "elements/package.h" namespace elements { void Element::serialize(Element::Json &a_json) { auto &jsonElement = a_json["element"]; jsonElement["id"] = m_id; jsonElement["name"] = m_name; jsonElement["type"] = type(); jsonElement["min_inputs"] = m_minInputs; jsonElement["max_inputs"] = m_maxInputs; jsonElement["min_outputs"] = m_minOutputs; jsonElement["max_outputs"] = m_maxOutputs; auto getSocketType = [](ValueType const a_type) { switch (a_type) { case ValueType::eBool: return "bool"; case ValueType::eInt: return "int"; case ValueType::eFloat: return "float"; } assert(false && "Wrong socket type"); return "unknown"; }; auto jsonInputs = Json::array(); size_t const INPUTS_COUNT{ m_inputs.size() }; for (size_t i = 0; i < INPUTS_COUNT; ++i) { Json socket{}; socket["socket"] = i; socket["type"] = getSocketType(m_inputs[i].type); socket["name"] = m_inputs[i].name; jsonInputs.push_back(socket); } auto jsonOutputs = Json::array(); size_t const OUTPUTS_COUNT{ m_outputs.size() }; for (size_t i = 0; i < OUTPUTS_COUNT; ++i) { Json socket{}; socket["socket"] = i; socket["type"] = getSocketType(m_outputs[i].type); socket["name"] = m_outputs[i].name; jsonOutputs.push_back(socket); } auto &jsonIo = jsonElement["io"]; jsonIo["inputs"] = jsonInputs; jsonIo["outputs"] = jsonOutputs; auto &jsonNode = a_json["node"]; jsonNode["position"]["x"] = m_position.x; jsonNode["position"]["y"] = m_position.y; jsonNode["iconify"] = m_isIconified; } void Element::deserialize(Json const &a_json) { std::cout << __PRETTY_FUNCTION__ << '>' << std::endl; auto const &jsonElement = a_json["element"]; auto const jsonId = jsonElement["id"].get<size_t>(); auto const jsonName = jsonElement["name"].get<std::string>(); auto const jsonMinInputs = jsonElement["min_inputs"].get<uint8_t>(); auto const jsonMaxInputs = jsonElement["max_inputs"].get<uint8_t>(); auto const jsonMinOutputs = jsonElement["min_outputs"].get<uint8_t>(); auto const jsonMaxOutputs = jsonElement["max_outputs"].get<uint8_t>(); auto const &jsonIo = jsonElement["io"]; auto const &jsonInputs = jsonIo["inputs"]; auto const &jsonOutputs = jsonIo["outputs"]; auto const &jsonNode = a_json["node"]; auto const jsonIconify = jsonNode["iconify"].get<bool>(); auto const &jsonPosition = jsonNode["position"]; auto const jsonPositionX = jsonPosition["x"].get<double>(); auto const jsonPositionY = jsonPosition["y"].get<double>(); assert(id() == jsonId); setName(jsonName); setPosition(jsonPositionX, jsonPositionY); clearInputs(); clearOutputs(); setMinInputs(jsonMinInputs); setMaxInputs(jsonMaxInputs); setMinOutputs(jsonMinOutputs); setMaxOutputs(jsonMaxOutputs); iconify(jsonIconify); auto add_socket = [&](Json const &a_socket, bool const a_input, uint8_t &a_socketCount) { auto const socketId = a_socket["socket"].get<uint8_t>(); auto const socketStringType = a_socket["type"].get<std::string>(); auto const socketName = a_socket["name"].get<std::string>(); assert(a_socketCount == socketId); ValueType const socketType = [](std::string_view const a_type) { if (a_type == "bool") return ValueType::eBool; else if (a_type == "int") return ValueType::eInt; else if (a_type == "float") return ValueType::eFloat; assert(false && "Wrong socket type"); return ValueType::eBool; }(socketStringType); a_input ? addInput(socketType, socketName) : addOutput(socketType, socketName); a_socketCount++; }; uint8_t inputsCount{}, outputsCount{}; for (auto &&socket : jsonInputs) add_socket(socket, true, inputsCount); for (auto &&socket : jsonOutputs) add_socket(socket, false, outputsCount); std::cout << __PRETTY_FUNCTION__ << '<' << std::endl; } bool Element::addInput(Element::ValueType const a_type, std::string const a_name) { if (m_inputs.size() + 1 > m_maxInputs) return false; Input input{}; input.name = a_name; input.type = a_type; m_inputs.emplace_back(input); return true; } void Element::setInputName(uint8_t a_input, std::string const a_name) { m_inputs[a_input].name = a_name; } void Element::removeInput() { m_inputs.pop_back(); } void Element::clearInputs() { m_inputs.clear(); } bool Element::addOutput(Element::ValueType const a_type, std::string const a_name) { if (m_outputs.size() + 1 > m_maxOutputs) return false; Output output{}; output.name = a_name; output.type = a_type; switch (a_type) { case ValueType::eBool: output.value = false; break; case ValueType::eInt: output.value = 0; break; case ValueType::eFloat: output.value = 0.0f; break; } m_outputs.emplace_back(output); return true; } void Element::setOutputName(uint8_t a_output, std::string const a_name) { m_outputs[a_output].name = a_name; } void Element::removeOutput() { m_outputs.pop_back(); } void Element::clearOutputs() { m_outputs.clear(); } bool Element::connect(size_t const a_sourceId, uint8_t const a_outputId, uint8_t const a_inputId) { return m_package->connect(a_sourceId, a_outputId, m_id, a_inputId); } bool Element::allInputsConnected() const { for (size_t i = 0; i < m_inputs.size(); ++i) if (!m_inputs[i].value) return false; return true; } void Element::setMinInputs(uint8_t const a_min) { if (a_min > m_maxInputs) return; m_minInputs = a_min; } void Element::setMaxInputs(uint8_t const a_max) { if (a_max < m_minInputs) return; m_maxInputs = a_max; } void Element::setMinOutputs(uint8_t const a_min) { if (a_min > m_maxOutputs) return; m_minOutputs = a_min; } void Element::setMaxOutputs(uint8_t const a_max) { if (a_max < m_minOutputs) return; m_maxOutputs = a_max; } } // namespace elements <commit_msg>Remove debug spam in Element::deserialize<commit_after>// MIT License // // Copyright (c) 2017 Artur Wyszyński, aljen at hitomi dot pl // // 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 "elements/element.h" #include <cassert> #include <iostream> #include "elements/package.h" namespace elements { void Element::serialize(Element::Json &a_json) { auto &jsonElement = a_json["element"]; jsonElement["id"] = m_id; jsonElement["name"] = m_name; jsonElement["type"] = type(); jsonElement["min_inputs"] = m_minInputs; jsonElement["max_inputs"] = m_maxInputs; jsonElement["min_outputs"] = m_minOutputs; jsonElement["max_outputs"] = m_maxOutputs; auto getSocketType = [](ValueType const a_type) { switch (a_type) { case ValueType::eBool: return "bool"; case ValueType::eInt: return "int"; case ValueType::eFloat: return "float"; } assert(false && "Wrong socket type"); return "unknown"; }; auto jsonInputs = Json::array(); size_t const INPUTS_COUNT{ m_inputs.size() }; for (size_t i = 0; i < INPUTS_COUNT; ++i) { Json socket{}; socket["socket"] = i; socket["type"] = getSocketType(m_inputs[i].type); socket["name"] = m_inputs[i].name; jsonInputs.push_back(socket); } auto jsonOutputs = Json::array(); size_t const OUTPUTS_COUNT{ m_outputs.size() }; for (size_t i = 0; i < OUTPUTS_COUNT; ++i) { Json socket{}; socket["socket"] = i; socket["type"] = getSocketType(m_outputs[i].type); socket["name"] = m_outputs[i].name; jsonOutputs.push_back(socket); } auto &jsonIo = jsonElement["io"]; jsonIo["inputs"] = jsonInputs; jsonIo["outputs"] = jsonOutputs; auto &jsonNode = a_json["node"]; jsonNode["position"]["x"] = m_position.x; jsonNode["position"]["y"] = m_position.y; jsonNode["iconify"] = m_isIconified; } void Element::deserialize(Json const &a_json) { auto const &jsonElement = a_json["element"]; auto const jsonId = jsonElement["id"].get<size_t>(); auto const jsonName = jsonElement["name"].get<std::string>(); auto const jsonMinInputs = jsonElement["min_inputs"].get<uint8_t>(); auto const jsonMaxInputs = jsonElement["max_inputs"].get<uint8_t>(); auto const jsonMinOutputs = jsonElement["min_outputs"].get<uint8_t>(); auto const jsonMaxOutputs = jsonElement["max_outputs"].get<uint8_t>(); auto const &jsonIo = jsonElement["io"]; auto const &jsonInputs = jsonIo["inputs"]; auto const &jsonOutputs = jsonIo["outputs"]; auto const &jsonNode = a_json["node"]; auto const jsonIconify = jsonNode["iconify"].get<bool>(); auto const &jsonPosition = jsonNode["position"]; auto const jsonPositionX = jsonPosition["x"].get<double>(); auto const jsonPositionY = jsonPosition["y"].get<double>(); assert(id() == jsonId); setName(jsonName); setPosition(jsonPositionX, jsonPositionY); clearInputs(); clearOutputs(); setMinInputs(jsonMinInputs); setMaxInputs(jsonMaxInputs); setMinOutputs(jsonMinOutputs); setMaxOutputs(jsonMaxOutputs); iconify(jsonIconify); auto add_socket = [&](Json const &a_socket, bool const a_input, uint8_t &a_socketCount) { auto const socketId = a_socket["socket"].get<uint8_t>(); auto const socketStringType = a_socket["type"].get<std::string>(); auto const socketName = a_socket["name"].get<std::string>(); assert(a_socketCount == socketId); ValueType const socketType = [](std::string_view const a_type) { if (a_type == "bool") return ValueType::eBool; else if (a_type == "int") return ValueType::eInt; else if (a_type == "float") return ValueType::eFloat; assert(false && "Wrong socket type"); return ValueType::eBool; }(socketStringType); a_input ? addInput(socketType, socketName) : addOutput(socketType, socketName); a_socketCount++; }; uint8_t inputsCount{}, outputsCount{}; for (auto &&socket : jsonInputs) add_socket(socket, true, inputsCount); for (auto &&socket : jsonOutputs) add_socket(socket, false, outputsCount); } bool Element::addInput(Element::ValueType const a_type, std::string const a_name) { if (m_inputs.size() + 1 > m_maxInputs) return false; Input input{}; input.name = a_name; input.type = a_type; m_inputs.emplace_back(input); return true; } void Element::setInputName(uint8_t a_input, std::string const a_name) { m_inputs[a_input].name = a_name; } void Element::removeInput() { m_inputs.pop_back(); } void Element::clearInputs() { m_inputs.clear(); } bool Element::addOutput(Element::ValueType const a_type, std::string const a_name) { if (m_outputs.size() + 1 > m_maxOutputs) return false; Output output{}; output.name = a_name; output.type = a_type; switch (a_type) { case ValueType::eBool: output.value = false; break; case ValueType::eInt: output.value = 0; break; case ValueType::eFloat: output.value = 0.0f; break; } m_outputs.emplace_back(output); return true; } void Element::setOutputName(uint8_t a_output, std::string const a_name) { m_outputs[a_output].name = a_name; } void Element::removeOutput() { m_outputs.pop_back(); } void Element::clearOutputs() { m_outputs.clear(); } bool Element::connect(size_t const a_sourceId, uint8_t const a_outputId, uint8_t const a_inputId) { return m_package->connect(a_sourceId, a_outputId, m_id, a_inputId); } bool Element::allInputsConnected() const { for (size_t i = 0; i < m_inputs.size(); ++i) if (!m_inputs[i].value) return false; return true; } void Element::setMinInputs(uint8_t const a_min) { if (a_min > m_maxInputs) return; m_minInputs = a_min; } void Element::setMaxInputs(uint8_t const a_max) { if (a_max < m_minInputs) return; m_maxInputs = a_max; } void Element::setMinOutputs(uint8_t const a_min) { if (a_min > m_maxOutputs) return; m_minOutputs = a_min; } void Element::setMaxOutputs(uint8_t const a_max) { if (a_max < m_minOutputs) return; m_maxOutputs = a_max; } } // namespace elements <|endoftext|>
<commit_before>// Natron /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* *Created by Alexandre GAUTHIER-FOICHAT on 6/1/2012. *contact: immarespond at gmail dot com * */ #include <iostream> #include "Global/Macros.h" CLANG_DIAG_OFF(deprecated) #include <QApplication> #include <QtCore/QObject> #include <QtCore/QString> #include <QIcon> #include <QtGui/QPixmap> #include <QDebug> #include <QFontDatabase> #include <QMetaType> #include <QAbstractSocket> CLANG_DIAG_ON(deprecated) #include "Global/GlobalDefines.h" #include "Engine/AppManager.h" #include "Engine/Knob.h" #include "Engine/ChannelSet.h" #include "Engine/Log.h" #include "Engine/Settings.h" #include "Engine/Node.h" #include "Gui/KnobGui.h" #include "Gui/CurveWidget.h" #include "Gui/SplashScreen.h" #if QT_VERSION < 0x050000 Q_DECLARE_METATYPE(QAbstractSocket::SocketState) #endif void registerMetaTypes(){ qRegisterMetaType<Variant>(); qRegisterMetaType<Natron::ChannelSet>(); qRegisterMetaType<Format>(); qRegisterMetaType<SequenceTime>("SequenceTime"); qRegisterMetaType<Knob*>(); qRegisterMetaType<Natron::Node*>(); qRegisterMetaType<CurveWidget*>(); qRegisterMetaType<Natron::StandardButtons>(); #if QT_VERSION < 0x050000 qRegisterMetaType<QAbstractSocket::SocketState>("SocketState"); #endif } void printBackGroundWelcomeMessage(){ std::cout << "================================================================================" << std::endl; std::cout << NATRON_APPLICATION_NAME << " " << " version: " << NATRON_VERSION_STRING << std::endl; std::cout << ">>>Running in background mode (off-screen rendering only).<<<" << std::endl; std::cout << "Please note that the background mode is in early stage and accepts only project files " "that would produce a valid output from the graphical version of " NATRON_APPLICATION_NAME << std::endl; std::cout << "If the background mode doesn't output any result, please adjust your project via the application interface " "and then re-try using the background mode." << std::endl; } void printUsage(){ std::cout << NATRON_APPLICATION_NAME << " usage: " << std::endl; std::cout << "./" NATRON_APPLICATION_NAME " <project file path>" << std::endl; std::cout << "[--background] or [-b] enables background mode rendering. No graphical interface will be shown." << std::endl; std::cout << "[--writer <Writer node name>] When in background mode, the renderer will only try to render with the node" " name following the --writer argument. If no such node exists in the project file, the process will abort." "Note that if you don't pass the --writer argument, it will try to start rendering with all the writers in the project's file."<< std::endl; } /** * @brief Extracts from argv[0] the path of the application's binary **/ static QString extractBinaryPath(const QString arg0) { int lastSepPos = arg0.lastIndexOf(QDir::separator()); if (lastSepPos == -1) { return ""; } else { return arg0.left(lastSepPos); } } int main(int argc, char *argv[]) { /*Parse args to find a valid project file name. This is not fool-proof: any file with a matching extension will pass through... @TODO : use some magic number to identify uniquely the project file type.*/ QString projectFile; bool isBackGround = false; QStringList writers; bool expectWriterNameOnNextArg = false; bool expectPipeFileNameOnNextArg = false; QString mainProcessServerName; QStringList args; QString binaryPath; for(int i = 0; i < argc ;++i){ if (i == 0) { extractBinaryPath(argv[i]); } args.push_back(QString(argv[i])); } for (int i = 0 ; i < args.size(); ++i) { if(args.at(i).contains("." NATRON_PROJECT_FILE_EXT)){ if(expectWriterNameOnNextArg || expectPipeFileNameOnNextArg) { printUsage(); return 1; } projectFile = args.at(i); continue; }else if(args.at(i) == "--background" || args.at(i) == "-b"){ if(expectWriterNameOnNextArg || expectPipeFileNameOnNextArg){ printUsage(); return 1; } isBackGround = true; continue; }else if(args.at(i) == "--writer"){ if(expectWriterNameOnNextArg || expectPipeFileNameOnNextArg){ printUsage(); return 1; } expectWriterNameOnNextArg = true; continue; }else if(args.at(i) == "--IPCpipe"){ if (expectWriterNameOnNextArg || expectPipeFileNameOnNextArg) { printUsage(); return 1; } expectPipeFileNameOnNextArg = true; continue; } if(expectWriterNameOnNextArg){ assert(!expectPipeFileNameOnNextArg); writers << args.at(i); expectWriterNameOnNextArg = false; } if (expectPipeFileNameOnNextArg) { assert(!expectWriterNameOnNextArg); mainProcessServerName = args.at(i); expectPipeFileNameOnNextArg = false; } } QCoreApplication* app = NULL; if(!isBackGround){ QApplication* guiApp = new QApplication(argc, argv); Q_INIT_RESOURCE(GuiResources); guiApp->setFont(QFont(NATRON_FONT, NATRON_FONT_SIZE_12)); app = guiApp; }else{ app = new QCoreApplication(argc,argv); } app->setOrganizationName(NATRON_ORGANIZATION_NAME); app->setOrganizationDomain(NATRON_ORGANIZATION_DOMAIN); app->setApplicationName(NATRON_APPLICATION_NAME); registerMetaTypes(); Natron::Log::instance();//< enable logging SplashScreen* splashScreen = 0; if(!isBackGround){ /*Display a splashscreen while we wait for the engine to load*/ QString filename(NATRON_IMAGES_PATH"splashscreen.png"); splashScreen = new SplashScreen(filename); QCoreApplication::processEvents(); QPixmap appIcPixmap; appPTR->getIcon(Natron::NATRON_PIXMAP_APP_ICON, &appIcPixmap); QIcon appIc(appIcPixmap); qApp->setWindowIcon(appIc); //load custom fonts QString fontResource = QString(":/Resources/Fonts/%1.ttf"); QStringList fontFilenames; fontFilenames << fontResource.arg("DroidSans"); fontFilenames << fontResource.arg("DroidSans-Bold"); foreach(QString fontFilename, fontFilenames) { splashScreen->updateText("Loading font " + fontFilename); //qDebug() << "attempting to load" << fontFilename; int fontID = QFontDatabase::addApplicationFont(fontFilename); qDebug() << "fontID=" << fontID << "families=" << QFontDatabase::applicationFontFamilies(fontID); } } AppManager* manager = AppManager::instance(); //< load the AppManager singleton manager->load(splashScreen,binaryPath); if (isBackGround && !mainProcessServerName.isEmpty()) { manager->initProcessInputChannel(mainProcessServerName); printBackGroundWelcomeMessage(); } AppInstance::AppType mainInstanceType = isBackGround ? AppInstance::APP_BACKGROUND_AUTO_RUN : AppInstance::APP_GUI; AppInstance* mainInstance = manager->newAppInstance(mainInstanceType,projectFile,writers); if(!mainInstance){ printUsage(); AppManager::quit(); return 1; }else{ if(isBackGround){ delete mainInstance; } } if(!isBackGround){ manager->hideSplashScreen(); }else{ //in background mode, exit... AppManager::quit(); return 0; } int retCode = app->exec(); delete app; return retCode; } <commit_msg>fix the locale bug: use the « C » locale for everything for now.<commit_after>// Natron /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* *Created by Alexandre GAUTHIER-FOICHAT on 6/1/2012. *contact: immarespond at gmail dot com * */ #include <clocale> #include <iostream> #include "Global/Macros.h" CLANG_DIAG_OFF(deprecated) #include <QApplication> #include <QtCore/QObject> #include <QtCore/QString> #include <QIcon> #include <QtGui/QPixmap> #include <QDebug> #include <QFontDatabase> #include <QMetaType> #include <QAbstractSocket> CLANG_DIAG_ON(deprecated) #include "Global/GlobalDefines.h" #include "Engine/AppManager.h" #include "Engine/Knob.h" #include "Engine/ChannelSet.h" #include "Engine/Log.h" #include "Engine/Settings.h" #include "Engine/Node.h" #include "Gui/KnobGui.h" #include "Gui/CurveWidget.h" #include "Gui/SplashScreen.h" #if QT_VERSION < 0x050000 Q_DECLARE_METATYPE(QAbstractSocket::SocketState) #endif void registerMetaTypes(){ qRegisterMetaType<Variant>(); qRegisterMetaType<Natron::ChannelSet>(); qRegisterMetaType<Format>(); qRegisterMetaType<SequenceTime>("SequenceTime"); qRegisterMetaType<Knob*>(); qRegisterMetaType<Natron::Node*>(); qRegisterMetaType<CurveWidget*>(); qRegisterMetaType<Natron::StandardButtons>(); #if QT_VERSION < 0x050000 qRegisterMetaType<QAbstractSocket::SocketState>("SocketState"); #endif } void printBackGroundWelcomeMessage(){ std::cout << "================================================================================" << std::endl; std::cout << NATRON_APPLICATION_NAME << " " << " version: " << NATRON_VERSION_STRING << std::endl; std::cout << ">>>Running in background mode (off-screen rendering only).<<<" << std::endl; std::cout << "Please note that the background mode is in early stage and accepts only project files " "that would produce a valid output from the graphical version of " NATRON_APPLICATION_NAME << std::endl; std::cout << "If the background mode doesn't output any result, please adjust your project via the application interface " "and then re-try using the background mode." << std::endl; } void printUsage(){ std::cout << NATRON_APPLICATION_NAME << " usage: " << std::endl; std::cout << "./" NATRON_APPLICATION_NAME " <project file path>" << std::endl; std::cout << "[--background] or [-b] enables background mode rendering. No graphical interface will be shown." << std::endl; std::cout << "[--writer <Writer node name>] When in background mode, the renderer will only try to render with the node" " name following the --writer argument. If no such node exists in the project file, the process will abort." "Note that if you don't pass the --writer argument, it will try to start rendering with all the writers in the project's file."<< std::endl; } /** * @brief Extracts from argv[0] the path of the application's binary **/ static QString extractBinaryPath(const QString arg0) { int lastSepPos = arg0.lastIndexOf(QDir::separator()); if (lastSepPos == -1) { return ""; } else { return arg0.left(lastSepPos); } } int main(int argc, char *argv[]) { /*Parse args to find a valid project file name. This is not fool-proof: any file with a matching extension will pass through... @TODO : use some magic number to identify uniquely the project file type.*/ QString projectFile; bool isBackGround = false; QStringList writers; bool expectWriterNameOnNextArg = false; bool expectPipeFileNameOnNextArg = false; QString mainProcessServerName; QStringList args; QString binaryPath; for(int i = 0; i < argc ;++i){ if (i == 0) { extractBinaryPath(argv[i]); } args.push_back(QString(argv[i])); } for (int i = 0 ; i < args.size(); ++i) { if(args.at(i).contains("." NATRON_PROJECT_FILE_EXT)){ if(expectWriterNameOnNextArg || expectPipeFileNameOnNextArg) { printUsage(); return 1; } projectFile = args.at(i); continue; }else if(args.at(i) == "--background" || args.at(i) == "-b"){ if(expectWriterNameOnNextArg || expectPipeFileNameOnNextArg){ printUsage(); return 1; } isBackGround = true; continue; }else if(args.at(i) == "--writer"){ if(expectWriterNameOnNextArg || expectPipeFileNameOnNextArg){ printUsage(); return 1; } expectWriterNameOnNextArg = true; continue; }else if(args.at(i) == "--IPCpipe"){ if (expectWriterNameOnNextArg || expectPipeFileNameOnNextArg) { printUsage(); return 1; } expectPipeFileNameOnNextArg = true; continue; } if(expectWriterNameOnNextArg){ assert(!expectPipeFileNameOnNextArg); writers << args.at(i); expectWriterNameOnNextArg = false; } if (expectPipeFileNameOnNextArg) { assert(!expectWriterNameOnNextArg); mainProcessServerName = args.at(i); expectPipeFileNameOnNextArg = false; } } QCoreApplication* app = NULL; if(!isBackGround){ QApplication* guiApp = new QApplication(argc, argv); Q_INIT_RESOURCE(GuiResources); guiApp->setFont(QFont(NATRON_FONT, NATRON_FONT_SIZE_12)); app = guiApp; }else{ app = new QCoreApplication(argc,argv); } // Natron is not yet internationalized, so it is better for now to use the "C" locale, // until it is tested for robustness against locale choice. // The locale affects numerics printing and scanning, date and time. // Note that with other locales (e.g. "de" or "fr"), the floating-point numbers may have // a comma (",") as the decimal separator instead of a point ("."). // There is also an OpenCOlorIO issue with non-C numeric locales: // https://github.com/imageworks/OpenColorIO/issues/297 // // this must be done after initializing the QCoreApplication, see // https://qt-project.org/doc/qt-5/qcoreapplication.html#locale-settings //std::setlocale(LC_NUMERIC,"C"); // set the locale for LC_NUMERIC only std::setlocale(LC_ALL,"C"); // set the locale for everything app->setOrganizationName(NATRON_ORGANIZATION_NAME); app->setOrganizationDomain(NATRON_ORGANIZATION_DOMAIN); app->setApplicationName(NATRON_APPLICATION_NAME); registerMetaTypes(); Natron::Log::instance();//< enable logging SplashScreen* splashScreen = 0; if(!isBackGround){ /*Display a splashscreen while we wait for the engine to load*/ QString filename(NATRON_IMAGES_PATH"splashscreen.png"); splashScreen = new SplashScreen(filename); QCoreApplication::processEvents(); QPixmap appIcPixmap; appPTR->getIcon(Natron::NATRON_PIXMAP_APP_ICON, &appIcPixmap); QIcon appIc(appIcPixmap); qApp->setWindowIcon(appIc); //load custom fonts QString fontResource = QString(":/Resources/Fonts/%1.ttf"); QStringList fontFilenames; fontFilenames << fontResource.arg("DroidSans"); fontFilenames << fontResource.arg("DroidSans-Bold"); foreach(QString fontFilename, fontFilenames) { splashScreen->updateText("Loading font " + fontFilename); //qDebug() << "attempting to load" << fontFilename; int fontID = QFontDatabase::addApplicationFont(fontFilename); qDebug() << "fontID=" << fontID << "families=" << QFontDatabase::applicationFontFamilies(fontID); } } AppManager* manager = AppManager::instance(); //< load the AppManager singleton manager->load(splashScreen,binaryPath); if (isBackGround && !mainProcessServerName.isEmpty()) { manager->initProcessInputChannel(mainProcessServerName); printBackGroundWelcomeMessage(); } AppInstance::AppType mainInstanceType = isBackGround ? AppInstance::APP_BACKGROUND_AUTO_RUN : AppInstance::APP_GUI; AppInstance* mainInstance = manager->newAppInstance(mainInstanceType,projectFile,writers); if(!mainInstance){ printUsage(); AppManager::quit(); return 1; }else{ if(isBackGround){ delete mainInstance; } } if(!isBackGround){ manager->hideSplashScreen(); }else{ //in background mode, exit... AppManager::quit(); return 0; } int retCode = app->exec(); delete app; return retCode; } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p10/procedures/hwp/lib/pstates_pgpe.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// @file pstates_pgpe.H /// @brief Pstate structures and support routines for PGPE Hcode /// // *HWP HW Owner : Rahul Batra <[email protected]> // *HWP HW Owner : Michael Floyd <[email protected]> // *HWP Team : PM // *HWP Level : 1 // *HWP Consumed by : PGPE:HS #ifndef __PSTATES_PGPE_H__ #define __PSTATES_PGPE_H__ #include <pstates_common.H> // #include <pstates_qme.h> /// PstateParmsBlock Magic Number /// /// This magic number identifies a particular version of the /// PstateParmsBlock and its substructures. The version number should be /// kept up to date as changes are made to the layout or contents of the /// structure. #define PSTATE_PARMSBLOCK_MAGIC 0x5053544154453030ull /* PSTATE00 */ #ifndef __ASSEMBLER__ #ifdef __cplusplus extern "C" { #endif #include <stdint.h> /// Control Attributes typedef union { uint8_t value[128]; union { uint8_t pstates_enabled; uint8_t resclk_enabled; uint8_t wof_enabled; uint8_t dds_enabled; uint8_t ocs_enabled; uint8_t underv_enabled; uint8_t overv_enabled; uint8_t throttle_control_enabled; } fields; } Attributes_t; /// Resonant Clock Stepping Entry /// /// @todo needs refinement for P10 yet. typedef union { uint16_t value; struct { #ifdef _BIG_ENDIAN uint16_t sector_buffer : 4; uint16_t spare1 : 1; uint16_t pulse_enable : 1; uint16_t pulse_mode : 2; uint16_t resonant_switch : 4; uint16_t spare4 : 4; #else uint16_t spare4 : 4; uint16_t resonant_switch : 4; uint16_t pulse_mode : 2; uint16_t pulse_enable : 1; uint16_t spare1 : 1; uint16_t sector_buffer : 4; #endif // _BIG_ENDIAN } fields; } ResClkStepEntry_t; /// @todo needs refinement for P10 yet. #define RESCLK_FREQ_REGIONS 8 #define RESCLK_STEPS 64 #define RESCLK_L3_STEPS 4 /// Resonant Clock Setup typedef struct { uint8_t freq_mhz[RESCLK_FREQ_REGIONS]; uint8_t index[RESCLK_FREQ_REGIONS]; ResClkStepEntry_t steparray[RESCLK_STEPS]; uint16_t step_delay_ns; // Max delay: 65.536us uint8_t l3_steparray[RESCLK_L3_STEPS]; uint16_t l3_threshold_mv; } ResClkSetup_t; /// #W Entry Data Points typedef struct { union { uint64_t value; struct { #ifdef _BIG_ENDIAN uint64_t insrtn_dely : 8; uint64_t spare1 : 2; uint64_t calb_adj : 2; uint64_t spare2 : 1; uint64_t window_offset : 3; uint64_t mux_select : 36; uint64_t dlt_time_set : 8; uint64_t spare3 : 4; #else uint64_t spare3 : 4; uint64_t dlt_time_set : 8; uint64_t mux_select : 36; uint64_t window_offset : 3; uint64_t spare2 : 1; uint64_t calb_adj : 2; uint64_t spare1 : 2; uint64_t insrtn_dely : 8; #endif } fields; } digital_droop_sensor_config; } PoundWEntry_t; /// #W DPLL Settings typedef struct { union { uint16_t value; struct { #ifdef _BIG_ENDIAN unit16_t N_S_drop_3p125pct : 4; unit16_t N_L_drop_3p125pct : 4; unit16_t L_S_return_3p125pct : 4; unit16_t S_N_return_3p125pct : 4; #else unit16_t S_N_return_3p125pct : 4; unit16_t L_S_return_3p125pct : 4; unit16_t N_L_drop_3p125pct : 4; unit16_t N_S_drop_3p125pct : 4; #endif // _BIG_ENDIAN /// #W Other Settings } fields; }; } PoundWDpllSettings_t; /// #W Other Settings typedef struct { uint8_t dds_calibration_version; PoundWDpllSettings_t dpll_settings; uint8_t light_throttle_settings[10]; uint8_t harsh_throttle_settings[10]; uint16_t droop_freq_resp_reference; uint8_t large_droop_mode_reg_setting[8]; uint8_t misc_droop_mode_reg_setting[8]; uint8_t spare[215]; } PoundWOther_t; /// #W VPD Structure /// /// Part specific data to manage the Digital Droop Sensor (DDS) typedef struct { PoundWEntry_t entry[NUM_OP_POINTS]; PoundWOther_t other; uint8_t rsvd[256]; } PoundW_t; /// Voltage Regulation Module (VRM) Control Settings typedef struct { /// The exponent of the exponential encoding of Pstate stepping delay uint8_t stepdelay_range; /// The significand of the exponential encoding of Pstate stepping delay uint8_t stepdelay_value; uint8_t spare[2]; /// Time between ext VRM detects write voltage cmd and when voltage begins to move uint32_t transition_start_ns[RUNTIME_RAILS]; /// Transition rate for an increasing voltage excursion uint32_t transition_rate_inc_uv_per_us[RUNTIME_RAILS]; /// Transition rate for an decreasing voltage excursion uint32_t transition_rate_dec_uv_per_us[RUNTIME_RAILS]; /// Delay to account for rail settling uint32_t stabilization_time_us[RUNTIME_RAILS]; /// External VRM transition step size uint32_t step_size_mv[RUNTIME_RAILS]; } VRMParms_t; /// These define the Run-time rails that are controlled by the PGPE during /// Pstate operations. #define RUNTIME_RAILS 2 #define RUNTIME_RAIL_VDD 0 #define RUNTIME_RAIL_VCS 1 /// @todo Need to define the DDS control block /// Pstate Parameter consumed by PGPE /// /// The GlobalPstateParameterBlock is an abstraction of a set of voltage/frequency /// operating points along with hardware limits. /// typedef struct { union { uint64_t value; struct { unit64_t eye_catcher : 56; uint64_t version : 8 ; } fields; } magic; Attributes_t attr; uint32_t reference_frequency_khz; // Pstate[0] frequency uint32_t frequency_step_khz; uint32_t occ_complex_frequency_mhz; // Needed for FITs uint32_t dpll_pstate0_mhz; // @todo why this and reference_frequency_khz? /// VPD operating points are biased but without load-line correction. /// Frequencies are in MHz, voltages are specified in units of 1mV, currents /// are specified in units of 10mA, and temperatures are specified in 0.5 /// degrees C. PoundVOpPoint_t operating_points_set[NUM_VPD_PTS_SET][NUM_OP_POINTS]; uint32_t spare0[16]; // 128B word-aligned PoundVBias_t poundv_biases_0p05pct[NUM_OP_POINTS]; // Values in 0.5% SysPowerDistParms_t vdd_sysparm; SysPowerDistParms_t vcs_sysparm; SysPowerDistParms_t vdn_sysparm; /// #W Other Settings VRMParms_t ext_vrm_parms; uint32_t safe_voltage_mv; uint32_t safe_frequency_khz; /// DDS Data /// DDSParmBlock dds; /// @todo need to define the DDS parm block /// The following are needed to generated the Pstate Table to HOMER. ResClkSetup_t resclk; /// Precalculated VPD Slopes /// All are in 4.12 decimal form into unit16_t integer value uint16_t ps_voltage_slopes[RUNTIME_RAILS][NUM_VPD_PTS_SET][VPD_NUM_SLOPES_REGION]; uint16_t voltage_ps_slopes[RUNTIME_RAILS][NUM_VPD_PTS_SET][VPD_NUM_SLOPES_REGION]; uint16_t ps_current_slopes[RUNTIME_RAILS][NUM_VPD_PTS_SET][VPD_NUM_SLOPES_REGION]; uint16_t current_ps_slopes[RUNTIME_RAILS][NUM_VPD_PTS_SET][VPD_NUM_SLOPES_REGION]; // Biased Compare VID operating points // CompareVIDPoints_t vid_point_set[NUM_OP_POINTS]; // Biased Threshold operation points // uint8_t threshold_set[NUM_OP_POINTS][NUM_THRESHOLD_POINTS]; // pstate-volt compare slopes // int16_t ps_vid_compare_slopes[VPD_NUM_SLOPES_REGION]; // pstate-volt threshold slopes // int16_t ps_dds_thresh_slopes[VPD_NUM_SLOPES_REGION][NUM_THRESHOLD_POINTS]; // Jump value operating points // uint8_t jump_value_set[NUM_OP_POINTS][NUM_JUMP_VALUES]; // Jump-value slopes // int16_t ps_dds_jump_slopes[VPD_NUM_SLOPES_REGION][NUM_JUMP_VALUES]; } GlobalPstateParmBlock_t __attribute__((packed, aligned(1024))); #ifdef __cplusplus } // end extern C #endif #endif /* __ASSEMBLER__ */ #endif /* __PSTATES_PGPE_H__ */ <commit_msg>PGPE: Basic Pstates for P10<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p10/procedures/hwp/lib/pstates_pgpe.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// @file pstates_pgpe.H /// @brief Pstate structures and support routines for PGPE Hcode /// // *HWP HW Owner : Rahul Batra <[email protected]> // *HWP HW Owner : Michael Floyd <[email protected]> // *HWP Team : PM // *HWP Level : 1 // *HWP Consumed by : PGPE:HS #ifndef __PSTATES_PGPE_H__ #define __PSTATES_PGPE_H__ #include <pstates_common.H> // #include <pstates_qme.h> /// PstateParmsBlock Magic Number /// /// This magic number identifies a particular version of the /// PstateParmsBlock and its substructures. The version number should be /// kept up to date as changes are made to the layout or contents of the /// structure. #define PSTATE_PARMSBLOCK_MAGIC 0x5053544154453030ull /* PSTATE00 */ #ifndef __ASSEMBLER__ #ifdef __cplusplus extern "C" { #endif #include <stdint.h> /// Control Attributes typedef union { uint8_t value[128]; union { uint8_t pstates_enabled; uint8_t resclk_enabled; uint8_t wof_enabled; uint8_t dds_enabled; uint8_t ocs_enabled; uint8_t underv_enabled; uint8_t overv_enabled; uint8_t throttle_control_enabled; } fields; } Attributes_t; /// Resonant Clock Stepping Entry /// /// @todo needs refinement for P10 yet. typedef union { uint16_t value; struct { #ifdef _BIG_ENDIAN uint16_t sector_buffer : 4; uint16_t spare1 : 1; uint16_t pulse_enable : 1; uint16_t pulse_mode : 2; uint16_t resonant_switch : 4; uint16_t spare4 : 4; #else uint16_t spare4 : 4; uint16_t resonant_switch : 4; uint16_t pulse_mode : 2; uint16_t pulse_enable : 1; uint16_t spare1 : 1; uint16_t sector_buffer : 4; #endif // _BIG_ENDIAN } fields; } ResClkStepEntry_t; /// @todo needs refinement for P10 yet. #define RESCLK_FREQ_REGIONS 8 #define RESCLK_STEPS 64 #define RESCLK_L3_STEPS 4 /// Resonant Clock Setup typedef struct { uint8_t freq_mhz[RESCLK_FREQ_REGIONS]; uint8_t index[RESCLK_FREQ_REGIONS]; ResClkStepEntry_t steparray[RESCLK_STEPS]; uint16_t step_delay_ns; // Max delay: 65.536us uint8_t l3_steparray[RESCLK_L3_STEPS]; uint16_t l3_threshold_mv; } ResClkSetup_t; /// #W Entry Data Points typedef struct { union { uint64_t value; struct { #ifdef _BIG_ENDIAN uint64_t insrtn_dely : 8; uint64_t spare1 : 2; uint64_t calb_adj : 2; uint64_t spare2 : 1; uint64_t window_offset : 3; uint64_t mux_select : 36; uint64_t dlt_time_set : 8; uint64_t spare3 : 4; #else uint64_t spare3 : 4; uint64_t dlt_time_set : 8; uint64_t mux_select : 36; uint64_t window_offset : 3; uint64_t spare2 : 1; uint64_t calb_adj : 2; uint64_t spare1 : 2; uint64_t insrtn_dely : 8; #endif } fields; } digital_droop_sensor_config; } PoundWEntry_t; /// #W DPLL Settings typedef struct { union { uint16_t value; struct { #ifdef _BIG_ENDIAN uint16_t N_S_drop_3p125pct : 4; uint16_t N_L_drop_3p125pct : 4; uint16_t L_S_return_3p125pct : 4; uint16_t S_N_return_3p125pct : 4; #else uint16_t S_N_return_3p125pct : 4; uint16_t L_S_return_3p125pct : 4; uint16_t N_L_drop_3p125pct : 4; uint16_t N_S_drop_3p125pct : 4; #endif // _BIG_ENDIAN /// #W Other Settings } fields; }; } PoundWDpllSettings_t; /// #W Other Settings typedef struct { uint8_t dds_calibration_version; PoundWDpllSettings_t dpll_settings; uint8_t light_throttle_settings[10]; uint8_t harsh_throttle_settings[10]; uint16_t droop_freq_resp_reference; uint8_t large_droop_mode_reg_setting[8]; uint8_t misc_droop_mode_reg_setting[8]; uint8_t spare[215]; } PoundWOther_t; /// #W VPD Structure /// /// Part specific data to manage the Digital Droop Sensor (DDS) typedef struct { PoundWEntry_t entry[NUM_OP_POINTS]; PoundWOther_t other; uint8_t rsvd[256]; } PoundW_t; /// These define the Run-time rails that are controlled by the PGPE during /// Pstate operations. #define RUNTIME_RAILS 2 #define RUNTIME_RAIL_VDD 0 #define RUNTIME_RAIL_VCS 1 /// Voltage Regulation Module (VRM) Control Settings typedef struct { /// The exponent of the exponential encoding of Pstate stepping delay uint8_t stepdelay_range; /// The significand of the exponential encoding of Pstate stepping delay uint8_t stepdelay_value; uint8_t spare[2]; /// Time between ext VRM detects write voltage cmd and when voltage begins to move uint32_t transition_start_ns[RUNTIME_RAILS]; /// Transition rate for an increasing voltage excursion uint32_t transition_rate_inc_uv_per_us[RUNTIME_RAILS]; /// Transition rate for an decreasing voltage excursion uint32_t transition_rate_dec_uv_per_us[RUNTIME_RAILS]; /// Delay to account for rail settling uint32_t stabilization_time_us[RUNTIME_RAILS]; /// External VRM transition step size uint32_t step_size_mv[RUNTIME_RAILS]; } VRMParms_t; /// @todo Need to define the DDS control block /// Pstate Parameter consumed by PGPE /// /// The GlobalPstateParameterBlock is an abstraction of a set of voltage/frequency /// operating points along with hardware limits. /// typedef struct { union { uint64_t value; struct { uint64_t eye_catcher : 56; uint64_t version : 8 ; } fields; } magic; Attributes_t attr; uint32_t reference_frequency_khz; // Pstate[0] frequency uint32_t frequency_step_khz; uint32_t occ_complex_frequency_mhz; // Needed for FITs uint32_t dpll_pstate0_value; // @todo why this and reference_frequency_khz? uint32_t nest_frequency_mhz; // Needed for FITs /// VPD operating points are biased but without load-line correction. /// Frequencies are in MHz, voltages are specified in units of 1mV, currents /// are specified in units of 10mA, and temperatures are specified in 0.5 /// degrees C. PoundVOpPoint_t operating_points_set[NUM_VPD_PTS_SET][NUM_OP_POINTS]; uint32_t spare0[16]; // 128B word-aligned PoundVBias_t poundv_biases_0p05pct[NUM_OP_POINTS]; // Values in 0.5% SysPowerDistParms_t vdd_sysparm; SysPowerDistParms_t vcs_sysparm; SysPowerDistParms_t vdn_sysparm; /// #W Other Settings VRMParms_t ext_vrm_parms; uint32_t safe_voltage_mv; uint32_t safe_frequency_khz; /// DDS Data /// DDSParmBlock dds; /// @todo need to define the DDS parm block /// The following are needed to generated the Pstate Table to HOMER. ResClkSetup_t resclk; /// Precalculated VPD Slopes /// All are in 4.12 decimal form into uint16_t integer value uint16_t ps_voltage_slopes[RUNTIME_RAILS][NUM_VPD_PTS_SET][VPD_NUM_SLOPES_REGION]; uint16_t voltage_ps_slopes[RUNTIME_RAILS][NUM_VPD_PTS_SET][VPD_NUM_SLOPES_REGION]; uint16_t ps_current_slopes[RUNTIME_RAILS][NUM_VPD_PTS_SET][VPD_NUM_SLOPES_REGION]; uint16_t current_ps_slopes[RUNTIME_RAILS][NUM_VPD_PTS_SET][VPD_NUM_SLOPES_REGION]; //AvsBusTopology AvsBusTopology_t avs_bus_topology; // Biased Compare VID operating points // CompareVIDPoints_t vid_point_set[NUM_OP_POINTS]; // Biased Threshold operation points // uint8_t threshold_set[NUM_OP_POINTS][NUM_THRESHOLD_POINTS]; // pstate-volt compare slopes // int16_t ps_vid_compare_slopes[VPD_NUM_SLOPES_REGION]; // pstate-volt threshold slopes // int16_t ps_dds_thresh_slopes[VPD_NUM_SLOPES_REGION][NUM_THRESHOLD_POINTS]; // Jump value operating points // uint8_t jump_value_set[NUM_OP_POINTS][NUM_JUMP_VALUES]; // Jump-value slopes // int16_t ps_dds_jump_slopes[VPD_NUM_SLOPES_REGION][NUM_JUMP_VALUES]; //} GlobalPstateParmBlock_t __attribute__((packed, aligned(1024))); } GlobalPstateParmBlock_t; #ifdef __cplusplus } // end extern C #endif #endif /* __ASSEMBLER__ */ #endif /* __PSTATES_PGPE_H__ */ <|endoftext|>
<commit_before> // STL includes #include <cstring> #include <cstdio> #include <iostream> #include <cerrno> // Linux includes #include <fcntl.h> #include <sys/ioctl.h> // Local Hyperion includes #include "ProviderSpi.h" #include <utils/Logger.h> ProviderSpi::ProviderSpi(const Json::Value &deviceConfig) : LedDevice() , _fid(-1) { setConfig(deviceConfig); memset(&_spi, 0, sizeof(_spi)); Debug(_log, "_spiDataInvert %d, _spiMode %d", _spiDataInvert, _spiMode); } ProviderSpi::~ProviderSpi() { // close(_fid); } bool ProviderSpi::setConfig(const Json::Value &deviceConfig) { _deviceName = deviceConfig.get("output","/dev/spidev0.0").asString(); _baudRate_Hz = deviceConfig.get("rate",1000000).asInt(); _latchTime_ns = deviceConfig.get("latchtime",0).asInt(); _spiMode = deviceConfig.get("spimode",SPI_MODE_0).asInt(); _spiDataInvert = deviceConfig.get("invert",false).asBool(); return true; } int ProviderSpi::open() { const int bitsPerWord = 8; _fid = ::open(_deviceName.c_str(), O_RDWR); if (_fid < 0) { Error( _log, "Failed to open device (%s). Error message: %s", _deviceName.c_str(), strerror(errno) ); return -1; } if (ioctl(_fid, SPI_IOC_WR_MODE, &_spiMode) == -1 || ioctl(_fid, SPI_IOC_RD_MODE, &_spiMode) == -1) { return -2; } if (ioctl(_fid, SPI_IOC_WR_BITS_PER_WORD, &bitsPerWord) == -1 || ioctl(_fid, SPI_IOC_RD_BITS_PER_WORD, &bitsPerWord) == -1) { return -4; } if (ioctl(_fid, SPI_IOC_WR_MAX_SPEED_HZ, &_baudRate_Hz) == -1 || ioctl(_fid, SPI_IOC_RD_MAX_SPEED_HZ, &_baudRate_Hz) == -1) { return -6; } return 0; } int ProviderSpi::writeBytes(const unsigned size, const uint8_t * data) { if (_fid < 0) { return -1; } _spi.tx_buf = __u64(data); _spi.len = __u32(size); if (_spiDataInvert) { uint8_t * newdata = (uint8_t *)malloc(size); for (unsigned i = 0; i<size; i++) { newdata[i] = data[i] ^ 0xff; } _spi.tx_buf = __u64(newdata); } int retVal = ioctl(_fid, SPI_IOC_MESSAGE(1), &_spi); if (retVal == 0 && _latchTime_ns > 0) { // The 'latch' time for latching the shifted-value into the leds timespec latchTime; latchTime.tv_sec = 0; latchTime.tv_nsec = _latchTime_ns; // Sleep to latch the leds (only if write succesfull) nanosleep(&latchTime, NULL); } return retVal; } <commit_msg>Added debug logging to ProviderSpi.cpp on writes. (#213)<commit_after> // STL includes #include <cstring> #include <cstdio> #include <iostream> #include <cerrno> // Linux includes #include <fcntl.h> #include <sys/ioctl.h> // Local Hyperion includes #include "ProviderSpi.h" #include <utils/Logger.h> ProviderSpi::ProviderSpi(const Json::Value &deviceConfig) : LedDevice() , _fid(-1) { setConfig(deviceConfig); memset(&_spi, 0, sizeof(_spi)); Debug(_log, "_spiDataInvert %d, _spiMode %d", _spiDataInvert, _spiMode); } ProviderSpi::~ProviderSpi() { // close(_fid); } bool ProviderSpi::setConfig(const Json::Value &deviceConfig) { _deviceName = deviceConfig.get("output","/dev/spidev0.0").asString(); _baudRate_Hz = deviceConfig.get("rate",1000000).asInt(); _latchTime_ns = deviceConfig.get("latchtime",0).asInt(); _spiMode = deviceConfig.get("spimode",SPI_MODE_0).asInt(); _spiDataInvert = deviceConfig.get("invert",false).asBool(); return true; } int ProviderSpi::open() { const int bitsPerWord = 8; _fid = ::open(_deviceName.c_str(), O_RDWR); if (_fid < 0) { Error( _log, "Failed to open device (%s). Error message: %s", _deviceName.c_str(), strerror(errno) ); return -1; } if (ioctl(_fid, SPI_IOC_WR_MODE, &_spiMode) == -1 || ioctl(_fid, SPI_IOC_RD_MODE, &_spiMode) == -1) { return -2; } if (ioctl(_fid, SPI_IOC_WR_BITS_PER_WORD, &bitsPerWord) == -1 || ioctl(_fid, SPI_IOC_RD_BITS_PER_WORD, &bitsPerWord) == -1) { return -4; } if (ioctl(_fid, SPI_IOC_WR_MAX_SPEED_HZ, &_baudRate_Hz) == -1 || ioctl(_fid, SPI_IOC_RD_MAX_SPEED_HZ, &_baudRate_Hz) == -1) { return -6; } return 0; } int ProviderSpi::writeBytes(const unsigned size, const uint8_t * data) { if (_fid < 0) { return -1; } _spi.tx_buf = __u64(data); _spi.len = __u32(size); if (_spiDataInvert) { uint8_t * newdata = (uint8_t *)malloc(size); for (unsigned i = 0; i<size; i++) { newdata[i] = data[i] ^ 0xff; } _spi.tx_buf = __u64(newdata); } int retVal = ioctl(_fid, SPI_IOC_MESSAGE(1), &_spi); ErrorIf((retVal < 0), _log, "SPI failed to write. errno: %d, %s", errno, strerror(errno) ); if (retVal == 0 && _latchTime_ns > 0) { // The 'latch' time for latching the shifted-value into the leds timespec latchTime; latchTime.tv_sec = 0; latchTime.tv_nsec = _latchTime_ns; // Sleep to latch the leds (only if write succesfull) nanosleep(&latchTime, NULL); } return retVal; } <|endoftext|>
<commit_before>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2012, Willow Garage, 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 Willow Garage nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: Ioan Sucan */ #include <moveit/ompl_interface/parameterization/joint_space/joint_model_state_space.h> #include <moveit/ompl_interface/parameterization/work_space/pose_model_state_space.h> #include <urdf_parser/urdf_parser.h> #include <ompl/util/Exception.h> #include <moveit/robot_state/conversions.h> #include <gtest/gtest.h> #include <fstream> class LoadPlanningModelsPr2 : public testing::Test { protected: virtual void SetUp() { srdf_model_.reset(new srdf::Model()); std::string xml_string; std::fstream xml_file("../kinematic_state/test/urdf/robot.xml", std::fstream::in); if (xml_file.is_open()) { while ( xml_file.good() ) { std::string line; std::getline( xml_file, line); xml_string += (line + "\n"); } xml_file.close(); urdf_model_ = urdf::parseURDF(xml_string); urdf_ok_ = urdf_model_; } else urdf_ok_ = false; srdf_ok_ = srdf_model_->initFile(*urdf_model_, "../kinematic_state/test/srdf/robot.xml"); if (urdf_ok_ && srdf_ok_) kmodel_.reset(new robot_model::RobotModel(urdf_model_, srdf_model_)); }; virtual void TearDown() { } protected: robot_model::RobotModelPtr kmodel_; boost::shared_ptr<urdf::ModelInterface> urdf_model_; boost::shared_ptr<srdf::Model> srdf_model_; bool urdf_ok_; bool srdf_ok_; }; TEST_F(LoadPlanningModelsPr2, StateSpace) { ompl_interface::ModelBasedStateSpaceSpecification spec(kmodel_, "whole_body"); ompl_interface::JointModelStateSpace ss(spec); ss.setPlanningVolume(-1, 1, -1, 1, -1, 1); ss.setup(); std::ofstream fout("ompl_interface_test_state_space_diagram1.dot"); ss.diagram(fout); bool passed = false; try { ss.sanityChecks(); passed = true; } catch(ompl::Exception &ex) { logError("Sanity checks did not pass: %s", ex.what()); } EXPECT_TRUE(passed); } TEST_F(LoadPlanningModelsPr2, StateSpaces) { ompl_interface::ModelBasedStateSpaceSpecification spec1(kmodel_, "right_arm"); ompl_interface::ModelBasedStateSpace ss1(spec1); ss1.setup(); ompl_interface::ModelBasedStateSpaceSpecification spec2(kmodel_, "left_arm"); ompl_interface::ModelBasedStateSpace ss2(spec2); ss2.setup(); ompl_interface::ModelBasedStateSpaceSpecification spec3(kmodel_, "whole_body"); ompl_interface::ModelBasedStateSpace ss3(spec3); ss3.setup(); ompl_interface::ModelBasedStateSpaceSpecification spec4(kmodel_, "arms"); ompl_interface::ModelBasedStateSpace ss4(spec4); ss4.setup(); std::ofstream fout("ompl_interface_test_state_space_diagram2.dot"); ompl::base::StateSpace::Diagram(fout); } TEST_F(LoadPlanningModelsPr2, StateSpaceCopy) { ompl_interface::ModelBasedStateSpaceSpecification spec(kmodel_, "right_arm"); ompl_interface::JointModelStateSpace ss(spec); ss.setPlanningVolume(-1, 1, -1, 1, -1, 1); ss.setup(); std::ofstream fout("ompl_interface_test_state_space_diagram1.dot"); ss.diagram(fout); bool passed = false; try { ss.sanityChecks(); passed = true; } catch(ompl::Exception &ex) { logError("Sanity checks did not pass: %s", ex.what()); } EXPECT_TRUE(passed); robot_state::RobotState kstate(kmodel_); kstate.setToRandomValues(); EXPECT_TRUE(kstate.distance(kstate) < 1e-12); ompl::base::State *state = ss.allocState(); for (int i = 0 ; i < 10 ; ++i) { robot_state::RobotState kstate2(kstate); EXPECT_TRUE(kstate.distance(kstate2) < 1e-12); ss.copyToOMPLState(state, kstate); kstate.getJointStateGroup(ss.getJointModelGroupName())->setToRandomValues(); std::cout << (kstate.getLinkState("r_wrist_roll_link")->getGlobalLinkTransform().translation() - kstate2.getLinkState("r_wrist_roll_link")->getGlobalLinkTransform().translation()) << std::endl; EXPECT_TRUE(kstate.distance(kstate2) > 1e-12); ss.copyToRobotState(kstate, state); std::cout << (kstate.getLinkState("r_wrist_roll_link")->getGlobalLinkTransform().translation() - kstate2.getLinkState("r_wrist_roll_link")->getGlobalLinkTransform().translation()) << std::endl; EXPECT_TRUE(kstate.distance(kstate2) < 1e-12); } ss.freeState(state); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>fixing broken tests for changes in robot_state<commit_after>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2012, Willow Garage, 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 Willow Garage nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: Ioan Sucan */ #include <moveit/ompl_interface/parameterization/joint_space/joint_model_state_space.h> #include <moveit/ompl_interface/parameterization/work_space/pose_model_state_space.h> #include <urdf_parser/urdf_parser.h> #include <ompl/util/Exception.h> #include <moveit/robot_state/conversions.h> #include <gtest/gtest.h> #include <fstream> class LoadPlanningModelsPr2 : public testing::Test { protected: virtual void SetUp() { srdf_model_.reset(new srdf::Model()); std::string xml_string; std::fstream xml_file("../kinematic_state/test/urdf/robot.xml", std::fstream::in); if (xml_file.is_open()) { while ( xml_file.good() ) { std::string line; std::getline( xml_file, line); xml_string += (line + "\n"); } xml_file.close(); urdf_model_ = urdf::parseURDF(xml_string); urdf_ok_ = urdf_model_; } else urdf_ok_ = false; srdf_ok_ = srdf_model_->initFile(*urdf_model_, "../kinematic_state/test/srdf/robot.xml"); if (urdf_ok_ && srdf_ok_) kmodel_.reset(new robot_model::RobotModel(urdf_model_, srdf_model_)); }; virtual void TearDown() { } protected: robot_model::RobotModelPtr kmodel_; boost::shared_ptr<urdf::ModelInterface> urdf_model_; boost::shared_ptr<srdf::Model> srdf_model_; bool urdf_ok_; bool srdf_ok_; }; TEST_F(LoadPlanningModelsPr2, StateSpace) { ompl_interface::ModelBasedStateSpaceSpecification spec(kmodel_, "whole_body"); ompl_interface::JointModelStateSpace ss(spec); ss.setPlanningVolume(-1, 1, -1, 1, -1, 1); ss.setup(); std::ofstream fout("ompl_interface_test_state_space_diagram1.dot"); ss.diagram(fout); bool passed = false; try { ss.sanityChecks(); passed = true; } catch(ompl::Exception &ex) { logError("Sanity checks did not pass: %s", ex.what()); } EXPECT_TRUE(passed); } TEST_F(LoadPlanningModelsPr2, StateSpaces) { ompl_interface::ModelBasedStateSpaceSpecification spec1(kmodel_, "right_arm"); ompl_interface::ModelBasedStateSpace ss1(spec1); ss1.setup(); ompl_interface::ModelBasedStateSpaceSpecification spec2(kmodel_, "left_arm"); ompl_interface::ModelBasedStateSpace ss2(spec2); ss2.setup(); ompl_interface::ModelBasedStateSpaceSpecification spec3(kmodel_, "whole_body"); ompl_interface::ModelBasedStateSpace ss3(spec3); ss3.setup(); ompl_interface::ModelBasedStateSpaceSpecification spec4(kmodel_, "arms"); ompl_interface::ModelBasedStateSpace ss4(spec4); ss4.setup(); std::ofstream fout("ompl_interface_test_state_space_diagram2.dot"); ompl::base::StateSpace::Diagram(fout); } TEST_F(LoadPlanningModelsPr2, StateSpaceCopy) { ompl_interface::ModelBasedStateSpaceSpecification spec(kmodel_, "right_arm"); ompl_interface::JointModelStateSpace ss(spec); ss.setPlanningVolume(-1, 1, -1, 1, -1, 1); ss.setup(); std::ofstream fout("ompl_interface_test_state_space_diagram1.dot"); ss.diagram(fout); bool passed = false; try { ss.sanityChecks(); passed = true; } catch(ompl::Exception &ex) { logError("Sanity checks did not pass: %s", ex.what()); } EXPECT_TRUE(passed); robot_state::RobotState kstate(kmodel_); kstate.setToRandomPositions(); EXPECT_TRUE(kstate.distance(kstate) < 1e-12); ompl::base::State *state = ss.allocState(); for (int i = 0 ; i < 10 ; ++i) { robot_state::RobotState kstate2(kstate); EXPECT_TRUE(kstate.distance(kstate2) < 1e-12); ss.copyToOMPLState(state, kstate); kstate.setToRandomPositions(kstate.getRobotModel()->getJointModelGroup(ss.getJointModelGroupName())); std::cout << (kstate.getGlobalLinkTransform("r_wrist_roll_link").translation() - kstate2.getGlobalLinkTransform("r_wrist_roll_link").translation()) << std::endl; EXPECT_TRUE(kstate.distance(kstate2) > 1e-12); ss.copyToRobotState(kstate, state); std::cout << (kstate.getGlobalLinkTransform("r_wrist_roll_link").translation() - kstate2.getGlobalLinkTransform("r_wrist_roll_link").translation()) << std::endl; EXPECT_TRUE(kstate.distance(kstate2) < 1e-12); } ss.freeState(state); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>#include "ArgParse.h" using namespace std; ArgParse::ArgParse(int argc, char* argv[]) { for(int a=1;a<argc;++a){ if(argv[a][0]=='-'){ string in(argv[a]),trig,val; trig=in.substr(1,in.find('=')); if(in.find('=')==string::npos) { val='1';//true } else { val=in.substr(in.find('=')+1); } m_streams[trig]=val; } else { ifstream fin(argv[a]); string in,trig,val; while(getline(fin,in)) { if(in[0]=='#') continue; trig=in.substr(0,in.find('=')); if(in.find('=')==string::npos) { val='1'; } else { val=in.substr(in.find('=')+1); } m_streams[trig]=val; } } } } double ArgParse::d(const string& str) const { return stod(m_streams.at(str)); } int ArgParse::i(const string& str) const { return stoi(m_streams.at(str)); } bool ArgParse::b(const string& str) const { return stoi(m_streams.at(str)); } string ArgParse::s(const string& str) const { return m_streams.at(str); } <commit_msg>Added empty line case in ArgsParse.cpp<commit_after>#include "ArgParse.h" using namespace std; ArgParse::ArgParse(int argc, char* argv[]) { for(int a=1;a<argc;++a){ if(argv[a][0]=='-'){ string in(argv[a]),trig,val; trig=in.substr(1,in.find('=')); if(in.find('=')==string::npos) { val='1';//true } else { val=in.substr(in.find('=')+1); } m_streams[trig]=val; } else { ifstream fin(argv[a]); string in,trig,val; while(getline(fin,in)) { if(in.size()==0) continue; if(in[0]=='#') continue; trig=in.substr(0,in.find('=')); if(in.find('=')==string::npos) { val='1'; } else { val=in.substr(in.find('=')+1); } m_streams[trig]=val; } } } } double ArgParse::d(const string& str) const { return stod(m_streams.at(str)); } int ArgParse::i(const string& str) const { return stoi(m_streams.at(str)); } bool ArgParse::b(const string& str) const { return stoi(m_streams.at(str)); } string ArgParse::s(const string& str) const { return m_streams.at(str); } <|endoftext|>
<commit_before>#include "rubymotion.h" VALUE rb_cDirector = Qnil; static VALUE mc_director_instance = Qnil; static VALUE director_instance(VALUE rcv, SEL sel) { if (mc_director_instance == Qnil) { VALUE obj = rb_class_wrap_new( (void *)cocos2d::Director::getInstance(), rb_cDirector); mc_director_instance = rb_retain(obj); } return mc_director_instance; } static VALUE director_view_set(VALUE rcv, SEL sel, VALUE obj) { #if CC_TARGET_OS_IPHONE cocos2d::GLView *glview = cocos2d::GLViewImpl::createWithEAGLView((void *)obj); DIRECTOR(rcv)->setOpenGLView(glview); #endif return obj; } static cocos2d::Scene * obj_to_scene(VALUE obj) { cocos2d::Scene *scene = NULL; if (rb_obj_is_kind_of(obj, rb_cLayer)) { scene = cocos2d::Scene::create(); scene->addChild(LAYER(obj)); } assert(scene != NULL); return scene; } static VALUE director_run(VALUE rcv, SEL sel, VALUE obj) { DIRECTOR(rcv)->runWithScene(obj_to_scene(obj)); return obj; } static VALUE director_replace(VALUE rcv, SEL sel, VALUE obj) { DIRECTOR(rcv)->replaceScene(obj_to_scene(obj)); return obj; } static VALUE director_end(VALUE rcv, SEL sel) { DIRECTOR(rcv)->end(); #if CC_TARGET_OS_IPHONE exit(0); #endif return rcv; } static VALUE director_origin(VALUE rcv, SEL sel) { return rb_ccvec2_to_obj(DIRECTOR(rcv)->getVisibleOrigin()); } static VALUE director_size(VALUE rcv, SEL sel) { return rb_ccsize_to_obj(DIRECTOR(rcv)->getVisibleSize()); } static VALUE director_show_stats(VALUE rcv, SEL sel, VALUE val) { DIRECTOR(rcv)->setDisplayStats(RTEST(val)); return val; } extern "C" void Init_Director(void) { rb_cDirector = rb_define_class_under(rb_mMC, "Director", rb_cObject); rb_define_singleton_method(rb_cDirector, "instance", director_instance, 0); rb_define_method(rb_cDirector, "run", director_run, 1); rb_define_method(rb_cDirector, "replace", director_replace, 1); rb_define_method(rb_cDirector, "end", director_end, 0); rb_define_method(rb_cDirector, "origin", director_origin, 0); rb_define_method(rb_cDirector, "size", director_size, 0); rb_define_method(rb_cDirector, "show_stats=", director_show_stats, 1); // Internal. rb_define_method(rb_cDirector, "_set_glview", director_view_set, 1); } <commit_msg>exit() also works on Android<commit_after>#include "rubymotion.h" VALUE rb_cDirector = Qnil; static VALUE mc_director_instance = Qnil; static VALUE director_instance(VALUE rcv, SEL sel) { if (mc_director_instance == Qnil) { VALUE obj = rb_class_wrap_new( (void *)cocos2d::Director::getInstance(), rb_cDirector); mc_director_instance = rb_retain(obj); } return mc_director_instance; } static VALUE director_view_set(VALUE rcv, SEL sel, VALUE obj) { #if CC_TARGET_OS_IPHONE cocos2d::GLView *glview = cocos2d::GLViewImpl::createWithEAGLView((void *)obj); DIRECTOR(rcv)->setOpenGLView(glview); #endif return obj; } static cocos2d::Scene * obj_to_scene(VALUE obj) { cocos2d::Scene *scene = NULL; if (rb_obj_is_kind_of(obj, rb_cLayer)) { scene = cocos2d::Scene::create(); scene->addChild(LAYER(obj)); } assert(scene != NULL); return scene; } static VALUE director_run(VALUE rcv, SEL sel, VALUE obj) { DIRECTOR(rcv)->runWithScene(obj_to_scene(obj)); return obj; } static VALUE director_replace(VALUE rcv, SEL sel, VALUE obj) { DIRECTOR(rcv)->replaceScene(obj_to_scene(obj)); return obj; } static VALUE director_end(VALUE rcv, SEL sel) { DIRECTOR(rcv)->end(); exit(0); return rcv; } static VALUE director_origin(VALUE rcv, SEL sel) { return rb_ccvec2_to_obj(DIRECTOR(rcv)->getVisibleOrigin()); } static VALUE director_size(VALUE rcv, SEL sel) { return rb_ccsize_to_obj(DIRECTOR(rcv)->getVisibleSize()); } static VALUE director_show_stats(VALUE rcv, SEL sel, VALUE val) { DIRECTOR(rcv)->setDisplayStats(RTEST(val)); return val; } extern "C" void Init_Director(void) { rb_cDirector = rb_define_class_under(rb_mMC, "Director", rb_cObject); rb_define_singleton_method(rb_cDirector, "instance", director_instance, 0); rb_define_method(rb_cDirector, "run", director_run, 1); rb_define_method(rb_cDirector, "replace", director_replace, 1); rb_define_method(rb_cDirector, "end", director_end, 0); rb_define_method(rb_cDirector, "origin", director_origin, 0); rb_define_method(rb_cDirector, "size", director_size, 0); rb_define_method(rb_cDirector, "show_stats=", director_show_stats, 1); // Internal. rb_define_method(rb_cDirector, "_set_glview", director_view_set, 1); } <|endoftext|>
<commit_before>// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/browser/browser.h" #include <stdlib.h> #include "atom/browser/native_window.h" #include "atom/browser/window_list.h" #include "atom/common/atom_version.h" #include "brightray/common/application_info.h" #include "chrome/browser/ui/libgtk2ui/unity_service.h" namespace atom { void Browser::Focus() { // Focus on the first visible window. WindowList* list = WindowList::GetInstance(); for (WindowList::iterator iter = list->begin(); iter != list->end(); ++iter) { NativeWindow* window = *iter; if (window->IsVisible()) { window->Focus(true); break; } } } void Browser::AddRecentDocument(const base::FilePath& path) { } void Browser::ClearRecentDocuments() { } void Browser::SetAppUserModelID(const base::string16& name) { } bool Browser::RemoveAsDefaultProtocolClient(const std::string& protocol, mate::Arguments* args) { return false; } bool Browser::SetAsDefaultProtocolClient(const std::string& protocol, mate::Arguments* args) { return false; } bool Browser::IsDefaultProtocolClient(const std::string& protocol, mate::Arguments* args) { return false; } bool Browser::SetBadgeCount(int count) { if (IsUnityRunning()) { unity::SetDownloadCount(count); badge_count_ = count; return true; } else { return false; } } void Browser::SetLoginItemSettings(LoginItemSettings settings) { } Browser::LoginItemSettings Browser::GetLoginItemSettings() { return LoginItemSettings(); } std::string Browser::GetExecutableFileVersion() const { return brightray::GetApplicationVersion(); } std::string Browser::GetExecutableFileProductName() const { return brightray::GetApplicationName(); } bool Browser::IsUnityRunning() { return unity::IsRunning(); } } // namespace atom <commit_msg>Oh, browser_linux is a thing too.<commit_after>// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/browser/browser.h" #include <stdlib.h> #include "atom/browser/native_window.h" #include "atom/browser/window_list.h" #include "atom/common/atom_version.h" #include "brightray/common/application_info.h" #include "chrome/browser/ui/libgtk2ui/unity_service.h" namespace atom { void Browser::Focus() { // Focus on the first visible window. WindowList* list = WindowList::GetInstance(); for (WindowList::iterator iter = list->begin(); iter != list->end(); ++iter) { NativeWindow* window = *iter; if (window->IsVisible()) { window->Focus(true); break; } } } void Browser::AddRecentDocument(const base::FilePath& path) { } void Browser::ClearRecentDocuments() { } void Browser::SetAppUserModelID(const base::string16& name) { } bool Browser::RemoveAsDefaultProtocolClient(const std::string& protocol, mate::Arguments* args) { return false; } bool Browser::SetAsDefaultProtocolClient(const std::string& protocol, mate::Arguments* args) { return false; } bool Browser::IsDefaultProtocolClient(const std::string& protocol, mate::Arguments* args) { return false; } bool Browser::SetBadgeCount(int count) { if (IsUnityRunning()) { unity::SetDownloadCount(count); badge_count_ = count; return true; } else { return false; } } void Browser::SetLoginItemSettings(LoginItemSettings settings, mate::Arguments* args) { } Browser::LoginItemSettings Browser::GetLoginItemSettings( mate::Arguments* args) { return LoginItemSettings(); } std::string Browser::GetExecutableFileVersion() const { return brightray::GetApplicationVersion(); } std::string Browser::GetExecutableFileProductName() const { return brightray::GetApplicationName(); } bool Browser::IsUnityRunning() { return unity::IsRunning(); } } // namespace atom <|endoftext|>
<commit_before>// @(#)root/hist:$Name: $:$Id: TF3.cxx,v 1.4 2002/05/18 08:21:59 brun Exp $ // Author: Rene Brun 27/10/95 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "TROOT.h" #include "TF3.h" #include "TMath.h" #include "TH3.h" #include "TVirtualPad.h" #include "TRandom.h" #include "TPainter3dAlgorithms.h" ClassImp(TF3) //______________________________________________________________________________ // // a 3-Dim function with parameters // //______________________________________________________________________________ TF3::TF3(): TF2() { //*-*-*-*-*-*-*-*-*-*-*F3 default constructor*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ====================== } //______________________________________________________________________________ TF3::TF3(const char *name,const char *formula, Double_t xmin, Double_t xmax, Double_t ymin, Double_t ymax, Double_t zmin, Double_t zmax) :TF2(name,formula,xmin,xmax,ymin,ymax) { //*-*-*-*-*-*-*F3 constructor using a formula definition*-*-*-*-*-*-*-*-*-*-* //*-* ========================================= //*-* //*-* See TFormula constructor for explanation of the formula syntax. //*-* //*-* //*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* fZmin = zmin; fZmax = zmax; fNpz = 30; } //______________________________________________________________________________ TF3::TF3(const char *name,void *fcn, Double_t xmin, Double_t xmax, Double_t ymin, Double_t ymax, Double_t zmin, Double_t zmax, Int_t npar) :TF2(name,fcn,xmin,xmax,ymin,ymax,npar) { //*-*-*-*-*-*-*F3 constructor using a pointer to an interpreted function*-*-* //*-* ========================================================= //*-* //*-* npar is the number of free parameters used by the function //*-* //*-* Creates a function of type C between xmin and xmax and ymin,ymax. //*-* The function is defined with npar parameters //*-* fcn must be a function of type: //*-* Double_t fcn(Double_t *x, Double_t *params) //*-* //*-* This constructor is called for functions of type C by CINT. //*-* //*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* fZmin = zmin; fZmax = zmax; fNpz = 30; fNdim = 3; } //______________________________________________________________________________ TF3::TF3(const char *name,Double_t (*fcn)(Double_t *, Double_t *), Double_t xmin, Double_t xmax, Double_t ymin, Double_t ymax, Double_t zmin, Double_t zmax, Int_t npar) :TF2(name,fcn,xmin,xmax,ymin,ymax,npar) { //*-*-*-*-*-*-*F3 constructor using a pointer to real function*-*-*-*-*-*-*-* //*-* =============================================== //*-* //*-* npar is the number of free parameters used by the function //*-* //*-* For example, for a 3-dim function with 3 parameters, the user function //*-* looks like: //*-* Double_t fun1(Double_t *x, Double_t *par) //*-* return par[0]*x[2] + par[1]*exp(par[2]*x[0]*x[1]); //*-* //*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* fZmin = zmin; fZmax = zmax; fNpz = 30; fNdim = 3; } //______________________________________________________________________________ TF3::~TF3() { //*-*-*-*-*-*-*-*-*-*-*F3 default destructor*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ===================== } //______________________________________________________________________________ TF3::TF3(const TF3 &f3) : TF2(f3) { ((TF3&)f3).Copy(*this); } //______________________________________________________________________________ void TF3::Copy(TObject &obj) { //*-*-*-*-*-*-*-*-*-*-*Copy this F3 to a new F3*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ======================== TF2::Copy(obj); ((TF3&)obj).fZmin = fZmin; ((TF3&)obj).fZmax = fZmax; ((TF3&)obj).fNpz = fNpz; } //______________________________________________________________________________ Int_t TF3::DistancetoPrimitive(Int_t px, Int_t py) { //*-*-*-*-*-*-*-*-*-*-*Compute distance from point px,py to a function*-*-*-*-* //*-* =============================================== //*-* Compute the closest distance of approach from point px,py to this function. //*-* The distance is computed in pixels units. //*-* //*-* Algorithm: //*-* //*-* //*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* return TF1::DistancetoPrimitive(px, py); } //______________________________________________________________________________ void TF3::Draw(Option_t *option) { //*-*-*-*-*-*-*-*-*-*-*Draw this function with its current attributes*-*-*-*-* //*-* ============================================== TString opt = option; opt.ToLower(); if (gPad && !opt.Contains("same")) gPad->Clear(); AppendPad(option); } //______________________________________________________________________________ void TF3::ExecuteEvent(Int_t event, Int_t px, Int_t py) { //*-*-*-*-*-*-*-*-*-*-*Execute action corresponding to one event*-*-*-* //*-* ========================================= //*-* This member function is called when a F3 is clicked with the locator //*-* //*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* TF1::ExecuteEvent(event, px, py); } //______________________________________________________________________________ void TF3::GetRandom3(Double_t &xrandom, Double_t &yrandom, Double_t &zrandom) { //*-*-*-*-*-*Return 3 random numbers following this function shape*-*-*-*-*-* //*-* ===================================================== //*-* //*-* The distribution contained in this TF3 function is integrated //*-* over the cell contents. //*-* It is normalized to 1. //*-* Getting the three random numbers implies: //*-* - Generating a random number between 0 and 1 (say r1) //*-* - Look in which cell in the normalized integral r1 corresponds to //*-* - make a linear interpolation in the returned cell //*-* // Check if integral array must be build Int_t i,j,k,cell; Double_t dx = (fXmax-fXmin)/fNpx; Double_t dy = (fYmax-fYmin)/fNpy; Double_t dz = (fZmax-fZmin)/fNpz; Int_t ncells = fNpx*fNpy*fNpz; Double_t xx[3]; InitArgs(xx,fParams); if (fIntegral == 0) { fIntegral = new Double_t[ncells+1]; fIntegral[0] = 0; Double_t integ; Int_t intNegative = 0; cell = 0; for (k=0;k<fNpz;k++) { xx[2] = fZmin+(k+0.5)*dz; for (j=0;j<fNpy;j++) { xx[1] = fYmin+(j+0.5)*dy; for (i=0;i<fNpx;i++) { xx[0] = fXmin+(i+0.5)*dx; integ = EvalPar(xx,fParams); if (integ < 0) {intNegative++; integ = -integ;} fIntegral[cell+1] = fIntegral[cell] + integ; cell++; } } } if (intNegative > 0) { Warning("GetRandom3","function:%s has %d negative values: abs assumed",GetName(),intNegative); } if (fIntegral[ncells] == 0) { Error("GetRandom3","Integral of function is zero"); return; } for (i=1;i<=ncells;i++) { // normalize integral to 1 fIntegral[i] /= fIntegral[ncells]; } } // return random numbers Double_t r; r = gRandom->Rndm(); cell = TMath::BinarySearch(ncells,fIntegral,r); k = cell/(fNpx*fNpy); j = (cell -k*fNpx*fNpy)/fNpx; i = cell -fNpx*(j +fNpy*k); xrandom = fXmin +dx*i +dx*gRandom->Rndm(); yrandom = fYmin +dy*j +dy*gRandom->Rndm(); zrandom = fZmin +dz*k +dz*gRandom->Rndm(); } //______________________________________________________________________________ void TF3::GetRange(Double_t &xmin, Double_t &ymin, Double_t &zmin, Double_t &xmax, Double_t &ymax, Double_t &zmax) { //*-*-*-*-*-*-*-*-*-*-*Return range of function*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ======================== xmin = fXmin; xmax = fXmax; ymin = fYmin; ymax = fYmax; zmin = fZmin; zmax = fZmax; } //______________________________________________________________________________ Double_t TF3::Integral(Double_t ax, Double_t bx, Double_t ay, Double_t by, Double_t az, Double_t bz, Double_t epsilon) { // Return Integral of a 3d function in range [ax,bx],[ay,by],[az,bz] // Double_t a[3], b[3]; a[0] = ax; b[0] = bx; a[1] = ay; b[1] = by; a[2] = az; b[2] = bz; Double_t relerr = 0; Double_t result = IntegralMultiple(3,a,b,epsilon,relerr); return result; } //______________________________________________________________________________ Bool_t TF3::IsInside(const Double_t *x) const { // Return kTRUE is the point is inside the function range if (x[0] < fXmin || x[0] > fXmax) return kFALSE; if (x[1] < fYmin || x[1] > fYmax) return kFALSE; if (x[2] < fZmin || x[2] > fZmax) return kFALSE; return kTRUE; } //______________________________________________________________________________ void TF3::Paint(Option_t *option) { //*-*-*-*-*-*-*-*-*Paint this 3-D function with its current attributes*-*-*-*-* //*-* =================================================== TString opt = option; opt.ToLower(); if (!opt.Contains("same")) gPad->Clear(); //*-*- Create a temporary histogram and fill each channel with the function value if (!fHistogram) { fHistogram = new TH3F("Func",(char*)GetTitle(),fNpx,fXmin,fXmax ,fNpy,fYmin,fYmax ,fNpz,fZmin,fZmax); if (!fHistogram) return; fHistogram->SetDirectory(0); } if (gROOT->LoadClass("THistPainter","HistPainter")) return; char *cmd; cmd = Form("TPainter3dAlgorithms::SetF3((TF3*)0x%lx);",(Long_t)this); gROOT->ProcessLine(cmd); fHistogram->Paint("tf3"); } //______________________________________________________________________________ void TF3::SetClippingBoxOff() { // Set the function clipping box (for drawing) "off". char *cmd; cmd = Form("TPainter3dAlgorithms::SetF3ClippingBoxOff();"); gROOT->ProcessLine(cmd); } //______________________________________________________________________________ void TF3::SetClippingBoxOn(Double_t xclip, Double_t yclip, Double_t zclip) { // Set the function clipping box (for drawing) "on" and define the clipping box. // xclip, yclip and zclip is a point within the function range. All the // function value having x<=xclip and y<=yclip and z>=zclip are clipped. char *cmd; cmd = Form("TPainter3dAlgorithms::SetF3ClippingBoxOn(%g,%g,%g);", (Double_t)xclip, (Double_t)yclip, (Double_t)zclip); gROOT->ProcessLine(cmd); } //______________________________________________________________________________ void TF3::SetNpz(Int_t npz) { //*-*-*-*-*-*-*-*Set the number of points used to draw the function*-*-*-*-*-* //*-* ================================================== if(npz > 4 && npz < 1000) fNpz = npz; Update(); } //______________________________________________________________________________ void TF3::SetRange(Double_t xmin, Double_t ymin, Double_t zmin, Double_t xmax, Double_t ymax, Double_t zmax) { //*-*-*-*-*-*Initialize the upper and lower bounds to draw the function*-*-*-* //*-* ========================================================== fXmin = xmin; fXmax = xmax; fYmin = ymin; fYmax = ymax; fZmin = zmin; fZmax = zmax; Update(); } <commit_msg>Small patch from Olivier to support teh case when a user wants to change teh "clipping box" in TF3 before calling Draw/Paint. The libHistPainter library must be dynamically loaded first.<commit_after>// @(#)root/hist:$Name: $:$Id: TF3.cxx,v 1.5 2002/05/29 18:39:44 brun Exp $ // Author: Rene Brun 27/10/95 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "TROOT.h" #include "TF3.h" #include "TMath.h" #include "TH3.h" #include "TVirtualPad.h" #include "TRandom.h" #include "TPainter3dAlgorithms.h" ClassImp(TF3) //______________________________________________________________________________ // // a 3-Dim function with parameters // //______________________________________________________________________________ TF3::TF3(): TF2() { //*-*-*-*-*-*-*-*-*-*-*F3 default constructor*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ====================== } //______________________________________________________________________________ TF3::TF3(const char *name,const char *formula, Double_t xmin, Double_t xmax, Double_t ymin, Double_t ymax, Double_t zmin, Double_t zmax) :TF2(name,formula,xmin,xmax,ymin,ymax) { //*-*-*-*-*-*-*F3 constructor using a formula definition*-*-*-*-*-*-*-*-*-*-* //*-* ========================================= //*-* //*-* See TFormula constructor for explanation of the formula syntax. //*-* //*-* //*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* fZmin = zmin; fZmax = zmax; fNpz = 30; } //______________________________________________________________________________ TF3::TF3(const char *name,void *fcn, Double_t xmin, Double_t xmax, Double_t ymin, Double_t ymax, Double_t zmin, Double_t zmax, Int_t npar) :TF2(name,fcn,xmin,xmax,ymin,ymax,npar) { //*-*-*-*-*-*-*F3 constructor using a pointer to an interpreted function*-*-* //*-* ========================================================= //*-* //*-* npar is the number of free parameters used by the function //*-* //*-* Creates a function of type C between xmin and xmax and ymin,ymax. //*-* The function is defined with npar parameters //*-* fcn must be a function of type: //*-* Double_t fcn(Double_t *x, Double_t *params) //*-* //*-* This constructor is called for functions of type C by CINT. //*-* //*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* fZmin = zmin; fZmax = zmax; fNpz = 30; fNdim = 3; } //______________________________________________________________________________ TF3::TF3(const char *name,Double_t (*fcn)(Double_t *, Double_t *), Double_t xmin, Double_t xmax, Double_t ymin, Double_t ymax, Double_t zmin, Double_t zmax, Int_t npar) :TF2(name,fcn,xmin,xmax,ymin,ymax,npar) { //*-*-*-*-*-*-*F3 constructor using a pointer to real function*-*-*-*-*-*-*-* //*-* =============================================== //*-* //*-* npar is the number of free parameters used by the function //*-* //*-* For example, for a 3-dim function with 3 parameters, the user function //*-* looks like: //*-* Double_t fun1(Double_t *x, Double_t *par) //*-* return par[0]*x[2] + par[1]*exp(par[2]*x[0]*x[1]); //*-* //*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* fZmin = zmin; fZmax = zmax; fNpz = 30; fNdim = 3; } //______________________________________________________________________________ TF3::~TF3() { //*-*-*-*-*-*-*-*-*-*-*F3 default destructor*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ===================== } //______________________________________________________________________________ TF3::TF3(const TF3 &f3) : TF2(f3) { ((TF3&)f3).Copy(*this); } //______________________________________________________________________________ void TF3::Copy(TObject &obj) { //*-*-*-*-*-*-*-*-*-*-*Copy this F3 to a new F3*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ======================== TF2::Copy(obj); ((TF3&)obj).fZmin = fZmin; ((TF3&)obj).fZmax = fZmax; ((TF3&)obj).fNpz = fNpz; } //______________________________________________________________________________ Int_t TF3::DistancetoPrimitive(Int_t px, Int_t py) { //*-*-*-*-*-*-*-*-*-*-*Compute distance from point px,py to a function*-*-*-*-* //*-* =============================================== //*-* Compute the closest distance of approach from point px,py to this function. //*-* The distance is computed in pixels units. //*-* //*-* Algorithm: //*-* //*-* //*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* return TF1::DistancetoPrimitive(px, py); } //______________________________________________________________________________ void TF3::Draw(Option_t *option) { //*-*-*-*-*-*-*-*-*-*-*Draw this function with its current attributes*-*-*-*-* //*-* ============================================== TString opt = option; opt.ToLower(); if (gPad && !opt.Contains("same")) gPad->Clear(); AppendPad(option); } //______________________________________________________________________________ void TF3::ExecuteEvent(Int_t event, Int_t px, Int_t py) { //*-*-*-*-*-*-*-*-*-*-*Execute action corresponding to one event*-*-*-* //*-* ========================================= //*-* This member function is called when a F3 is clicked with the locator //*-* //*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* TF1::ExecuteEvent(event, px, py); } //______________________________________________________________________________ void TF3::GetRandom3(Double_t &xrandom, Double_t &yrandom, Double_t &zrandom) { //*-*-*-*-*-*Return 3 random numbers following this function shape*-*-*-*-*-* //*-* ===================================================== //*-* //*-* The distribution contained in this TF3 function is integrated //*-* over the cell contents. //*-* It is normalized to 1. //*-* Getting the three random numbers implies: //*-* - Generating a random number between 0 and 1 (say r1) //*-* - Look in which cell in the normalized integral r1 corresponds to //*-* - make a linear interpolation in the returned cell //*-* // Check if integral array must be build Int_t i,j,k,cell; Double_t dx = (fXmax-fXmin)/fNpx; Double_t dy = (fYmax-fYmin)/fNpy; Double_t dz = (fZmax-fZmin)/fNpz; Int_t ncells = fNpx*fNpy*fNpz; Double_t xx[3]; InitArgs(xx,fParams); if (fIntegral == 0) { fIntegral = new Double_t[ncells+1]; fIntegral[0] = 0; Double_t integ; Int_t intNegative = 0; cell = 0; for (k=0;k<fNpz;k++) { xx[2] = fZmin+(k+0.5)*dz; for (j=0;j<fNpy;j++) { xx[1] = fYmin+(j+0.5)*dy; for (i=0;i<fNpx;i++) { xx[0] = fXmin+(i+0.5)*dx; integ = EvalPar(xx,fParams); if (integ < 0) {intNegative++; integ = -integ;} fIntegral[cell+1] = fIntegral[cell] + integ; cell++; } } } if (intNegative > 0) { Warning("GetRandom3","function:%s has %d negative values: abs assumed",GetName(),intNegative); } if (fIntegral[ncells] == 0) { Error("GetRandom3","Integral of function is zero"); return; } for (i=1;i<=ncells;i++) { // normalize integral to 1 fIntegral[i] /= fIntegral[ncells]; } } // return random numbers Double_t r; r = gRandom->Rndm(); cell = TMath::BinarySearch(ncells,fIntegral,r); k = cell/(fNpx*fNpy); j = (cell -k*fNpx*fNpy)/fNpx; i = cell -fNpx*(j +fNpy*k); xrandom = fXmin +dx*i +dx*gRandom->Rndm(); yrandom = fYmin +dy*j +dy*gRandom->Rndm(); zrandom = fZmin +dz*k +dz*gRandom->Rndm(); } //______________________________________________________________________________ void TF3::GetRange(Double_t &xmin, Double_t &ymin, Double_t &zmin, Double_t &xmax, Double_t &ymax, Double_t &zmax) { //*-*-*-*-*-*-*-*-*-*-*Return range of function*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ======================== xmin = fXmin; xmax = fXmax; ymin = fYmin; ymax = fYmax; zmin = fZmin; zmax = fZmax; } //______________________________________________________________________________ Double_t TF3::Integral(Double_t ax, Double_t bx, Double_t ay, Double_t by, Double_t az, Double_t bz, Double_t epsilon) { // Return Integral of a 3d function in range [ax,bx],[ay,by],[az,bz] // Double_t a[3], b[3]; a[0] = ax; b[0] = bx; a[1] = ay; b[1] = by; a[2] = az; b[2] = bz; Double_t relerr = 0; Double_t result = IntegralMultiple(3,a,b,epsilon,relerr); return result; } //______________________________________________________________________________ Bool_t TF3::IsInside(const Double_t *x) const { // Return kTRUE is the point is inside the function range if (x[0] < fXmin || x[0] > fXmax) return kFALSE; if (x[1] < fYmin || x[1] > fYmax) return kFALSE; if (x[2] < fZmin || x[2] > fZmax) return kFALSE; return kTRUE; } //______________________________________________________________________________ void TF3::Paint(Option_t *option) { //*-*-*-*-*-*-*-*-*Paint this 3-D function with its current attributes*-*-*-*-* //*-* =================================================== TString opt = option; opt.ToLower(); if (!opt.Contains("same")) gPad->Clear(); //*-*- Create a temporary histogram and fill each channel with the function value if (!fHistogram) { fHistogram = new TH3F("Func",(char*)GetTitle(),fNpx,fXmin,fXmax ,fNpy,fYmin,fYmax ,fNpz,fZmin,fZmax); if (!fHistogram) return; fHistogram->SetDirectory(0); } if (gROOT->LoadClass("THistPainter","HistPainter")) return; char *cmd; cmd = Form("TPainter3dAlgorithms::SetF3((TF3*)0x%lx);",(Long_t)this); gROOT->ProcessLine(cmd); fHistogram->Paint("tf3"); } //______________________________________________________________________________ void TF3::SetClippingBoxOff() { // Set the function clipping box (for drawing) "off". if (gROOT->LoadClass("THistPainter","HistPainter")) return; char *cmd; cmd = Form("TPainter3dAlgorithms::SetF3ClippingBoxOff();"); gROOT->ProcessLine(cmd); } //______________________________________________________________________________ void TF3::SetClippingBoxOn(Double_t xclip, Double_t yclip, Double_t zclip) { // Set the function clipping box (for drawing) "on" and define the clipping box. // xclip, yclip and zclip is a point within the function range. All the // function value having x<=xclip and y<=yclip and z>=zclip are clipped. if (gROOT->LoadClass("THistPainter","HistPainter")) return; char *cmd; cmd = Form("TPainter3dAlgorithms::SetF3ClippingBoxOn(%g,%g,%g);", (Double_t)xclip, (Double_t)yclip, (Double_t)zclip); gROOT->ProcessLine(cmd); } //______________________________________________________________________________ void TF3::SetNpz(Int_t npz) { //*-*-*-*-*-*-*-*Set the number of points used to draw the function*-*-*-*-*-* //*-* ================================================== if(npz > 4 && npz < 1000) fNpz = npz; Update(); } //______________________________________________________________________________ void TF3::SetRange(Double_t xmin, Double_t ymin, Double_t zmin, Double_t xmax, Double_t ymax, Double_t zmax) { //*-*-*-*-*-*Initialize the upper and lower bounds to draw the function*-*-*-* //*-* ========================================================== fXmin = xmin; fXmax = xmax; fYmin = ymin; fYmax = ymax; fZmin = zmin; fZmax = zmax; Update(); } <|endoftext|>
<commit_before>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * 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 <thrift/lib/cpp/Thrift.h> #include <boost/lexical_cast.hpp> #include <stdarg.h> #include <stdio.h> #include <folly/String.h> namespace apache { namespace thrift { TOutput GlobalOutput; void TOutput::printf(const char *message, ...) { // Try to reduce heap usage, even if printf is called rarely. static const int STACK_BUF_SIZE = 256; char stack_buf[STACK_BUF_SIZE]; va_list ap; va_start(ap, message); int need = vsnprintf(stack_buf, STACK_BUF_SIZE, message, ap); va_end(ap); if (need < STACK_BUF_SIZE) { f_(stack_buf); return; } char *heap_buf = (char*)malloc((need+1) * sizeof(char)); if (heap_buf == nullptr) { // Malloc failed. We might as well print the stack buffer. f_(stack_buf); return; } va_start(ap, message); int rval = vsnprintf(heap_buf, need+1, message, ap); va_end(ap); // TODO(shigin): inform user if (rval != -1) { f_(heap_buf); } free(heap_buf); } void TOutput::perror(const char *message, int errno_copy) { std::string out = message + strerror_s(errno_copy); f_(out.c_str()); } std::string TOutput::strerror_s(int errno_copy) { return folly::errnoStr(errno_copy).toStdString(); } TLibraryException::TLibraryException(const char* message, int errnoValue) { message_ = std::string(message) + ": " + TOutput::strerror_s(errnoValue); } }} // apache::thrift <commit_msg>more fixes for modular builds<commit_after>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * 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 <thrift/lib/cpp/Thrift.h> #include <stdarg.h> #include <stdio.h> #include <folly/String.h> namespace apache { namespace thrift { TOutput GlobalOutput; void TOutput::printf(const char *message, ...) { // Try to reduce heap usage, even if printf is called rarely. static const int STACK_BUF_SIZE = 256; char stack_buf[STACK_BUF_SIZE]; va_list ap; va_start(ap, message); int need = vsnprintf(stack_buf, STACK_BUF_SIZE, message, ap); va_end(ap); if (need < STACK_BUF_SIZE) { f_(stack_buf); return; } char *heap_buf = (char*)malloc((need+1) * sizeof(char)); if (heap_buf == nullptr) { // Malloc failed. We might as well print the stack buffer. f_(stack_buf); return; } va_start(ap, message); int rval = vsnprintf(heap_buf, need+1, message, ap); va_end(ap); // TODO(shigin): inform user if (rval != -1) { f_(heap_buf); } free(heap_buf); } void TOutput::perror(const char *message, int errno_copy) { std::string out = message + strerror_s(errno_copy); f_(out.c_str()); } std::string TOutput::strerror_s(int errno_copy) { return folly::errnoStr(errno_copy).toStdString(); } TLibraryException::TLibraryException(const char* message, int errnoValue) { message_ = std::string(message) + ": " + TOutput::strerror_s(errnoValue); } }} // apache::thrift <|endoftext|>
<commit_before>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Lefteris Karapetsas <[email protected]> * @date 2015 * Unit tests for Assembly Items from evmcore/Assembly.h */ #include <string> #include <iostream> #include <boost/test/unit_test.hpp> #include <libdevcore/Log.h> #include <libdevcore/SourceLocation.h> #include <libsolidity/Scanner.h> #include <libsolidity/Parser.h> #include <libsolidity/NameAndTypeResolver.h> #include <libsolidity/Compiler.h> #include <libsolidity/AST.h> #include <libevmcore/Assembly.h> using namespace std; using namespace dev::eth; namespace dev { namespace solidity { namespace test { namespace { eth::AssemblyItems compileContract(const string& _sourceCode) { Parser parser; ASTPointer<SourceUnit> sourceUnit; BOOST_REQUIRE_NO_THROW(sourceUnit = parser.parse(make_shared<Scanner>(CharStream(_sourceCode)))); NameAndTypeResolver resolver({}); resolver.registerDeclarations(*sourceUnit); for (ASTPointer<ASTNode> const& node: sourceUnit->getNodes()) if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get())) { BOOST_REQUIRE_NO_THROW(resolver.resolveNamesAndTypes(*contract)); } for (ASTPointer<ASTNode> const& node: sourceUnit->getNodes()) if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get())) { BOOST_REQUIRE_NO_THROW(resolver.checkTypeRequirements(*contract)); } for (ASTPointer<ASTNode> const& node: sourceUnit->getNodes()) if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get())) { Compiler compiler; compiler.compileContract(*contract, map<ContractDefinition const*, bytes const*>{}); return compiler.getRuntimeContext().getAssembly().getItems(); } BOOST_FAIL("No contract found in source."); return AssemblyItems(); } void checkAssemblyLocations(AssemblyItems const& _items, std::vector<SourceLocation> _locations) { size_t i = 0; BOOST_CHECK_EQUAL(_items.size(), _locations.size()); for (auto const& it: _items) { BOOST_CHECK_MESSAGE(it.getLocation() == _locations[i], std::string("Location mismatch for item" + i)); ++ i; } } } // end anonymous namespace BOOST_AUTO_TEST_SUITE(Assembly) BOOST_AUTO_TEST_CASE(location_test) { char const* sourceCode = "contract test {\n" " function f() returns (uint256 a)\n" " {\n" " return 16;\n" " }\n" "}\n"; std::shared_ptr<std::string const> n = make_shared<std::string>("source"); AssemblyItems items = compileContract(sourceCode); std::vector<SourceLocation> locations { SourceLocation(0, 77, n), SourceLocation(0, 77, n), SourceLocation(0, 77, n), SourceLocation(0, 77, n), SourceLocation(0, 77, n), SourceLocation(0, 77, n), SourceLocation(0, 77, n), SourceLocation(0, 77, n), SourceLocation(), SourceLocation(), SourceLocation(0, 77, n), SourceLocation(0, 77, n), SourceLocation(), SourceLocation(), SourceLocation(), SourceLocation(0, 77, n), SourceLocation(0, 77, n), SourceLocation(0, 77, n), SourceLocation(0, 77, n), SourceLocation(0, 77, n), SourceLocation(0, 77, n), SourceLocation(0, 77, n), SourceLocation(18, 75, n), SourceLocation(18, 75, n), SourceLocation(61, 70, n), SourceLocation(61, 70, n), SourceLocation(61, 70, n), SourceLocation(), SourceLocation(), SourceLocation(61, 70, n), SourceLocation(61, 70, n), SourceLocation(61, 70, n) }; checkAssemblyLocations(items, locations); } BOOST_AUTO_TEST_SUITE_END() } } } // end namespaces <commit_msg>Styling changes for SourceLocation and friends<commit_after>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Lefteris Karapetsas <[email protected]> * @date 2015 * Unit tests for Assembly Items from evmcore/Assembly.h */ #include <string> #include <iostream> #include <boost/test/unit_test.hpp> #include <libdevcore/Log.h> #include <libdevcore/SourceLocation.h> #include <libsolidity/Scanner.h> #include <libsolidity/Parser.h> #include <libsolidity/NameAndTypeResolver.h> #include <libsolidity/Compiler.h> #include <libsolidity/AST.h> #include <libevmcore/Assembly.h> using namespace std; using namespace dev::eth; namespace dev { namespace solidity { namespace test { namespace { eth::AssemblyItems compileContract(const string& _sourceCode) { Parser parser; ASTPointer<SourceUnit> sourceUnit; BOOST_REQUIRE_NO_THROW(sourceUnit = parser.parse(make_shared<Scanner>(CharStream(_sourceCode)))); NameAndTypeResolver resolver({}); resolver.registerDeclarations(*sourceUnit); for (ASTPointer<ASTNode> const& node: sourceUnit->getNodes()) if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get())) BOOST_REQUIRE_NO_THROW(resolver.resolveNamesAndTypes(*contract)); for (ASTPointer<ASTNode> const& node: sourceUnit->getNodes()) if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get())) BOOST_REQUIRE_NO_THROW(resolver.checkTypeRequirements(*contract)); for (ASTPointer<ASTNode> const& node: sourceUnit->getNodes()) if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get())) { Compiler compiler; compiler.compileContract(*contract, map<ContractDefinition const*, bytes const*>{}); return compiler.getRuntimeContext().getAssembly().getItems(); } BOOST_FAIL("No contract found in source."); return AssemblyItems(); } void checkAssemblyLocations(AssemblyItems const& _items, std::vector<SourceLocation> _locations) { size_t i = 0; BOOST_CHECK_EQUAL(_items.size(), _locations.size()); for (auto const& it: _items) { BOOST_CHECK_MESSAGE(it.getLocation() == _locations[i], std::string("Location mismatch for item" + i)); ++i; } } } // end anonymous namespace BOOST_AUTO_TEST_SUITE(Assembly) BOOST_AUTO_TEST_CASE(location_test) { char const* sourceCode = "contract test {\n" " function f() returns (uint256 a)\n" " {\n" " return 16;\n" " }\n" "}\n"; std::shared_ptr<std::string const> n = make_shared<std::string>("source"); AssemblyItems items = compileContract(sourceCode); std::vector<SourceLocation> locations { SourceLocation(0, 77, n), SourceLocation(0, 77, n), SourceLocation(0, 77, n), SourceLocation(0, 77, n), SourceLocation(0, 77, n), SourceLocation(0, 77, n), SourceLocation(0, 77, n), SourceLocation(0, 77, n), SourceLocation(), SourceLocation(), SourceLocation(0, 77, n), SourceLocation(0, 77, n), SourceLocation(), SourceLocation(), SourceLocation(), SourceLocation(0, 77, n), SourceLocation(0, 77, n), SourceLocation(0, 77, n), SourceLocation(0, 77, n), SourceLocation(0, 77, n), SourceLocation(0, 77, n), SourceLocation(0, 77, n), SourceLocation(18, 75, n), SourceLocation(18, 75, n), SourceLocation(61, 70, n), SourceLocation(61, 70, n), SourceLocation(61, 70, n), SourceLocation(), SourceLocation(), SourceLocation(61, 70, n), SourceLocation(61, 70, n), SourceLocation(61, 70, n) }; checkAssemblyLocations(items, locations); } BOOST_AUTO_TEST_SUITE_END() } } } // end namespaces <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "cppuseselectionsupdater.h" #include "cppcanonicalsymbol.h" #include "cppeditor.h" #include <cpptools/cpplocalsymbols.h> #include <cpptools/cppmodelmanagerinterface.h> #include <cpptools/cpptoolsreuse.h> #include <texteditor/basetexteditor.h> #include <texteditor/convenience.h> #include <texteditor/fontsettings.h> #include <cplusplus/Macro.h> #include <cplusplus/TranslationUnit.h> #include <utils/qtcassert.h> #include <QtConcurrentRun> #include <QTextBlock> #include <QTextCursor> #include <QTextEdit> using namespace CPlusPlus; enum { updateUseSelectionsInternalInMs = 500 }; namespace { class FunctionDefinitionUnderCursor: protected ASTVisitor { unsigned _line; unsigned _column; DeclarationAST *_functionDefinition; public: FunctionDefinitionUnderCursor(TranslationUnit *translationUnit) : ASTVisitor(translationUnit), _line(0), _column(0) { } DeclarationAST *operator()(AST *ast, unsigned line, unsigned column) { _functionDefinition = 0; _line = line; _column = column; accept(ast); return _functionDefinition; } protected: virtual bool preVisit(AST *ast) { if (_functionDefinition) return false; if (FunctionDefinitionAST *def = ast->asFunctionDefinition()) return checkDeclaration(def); if (ObjCMethodDeclarationAST *method = ast->asObjCMethodDeclaration()) { if (method->function_body) return checkDeclaration(method); } return true; } private: bool checkDeclaration(DeclarationAST *ast) { unsigned startLine, startColumn; unsigned endLine, endColumn; getTokenStartPosition(ast->firstToken(), &startLine, &startColumn); getTokenEndPosition(ast->lastToken() - 1, &endLine, &endColumn); if (_line > startLine || (_line == startLine && _column >= startColumn)) { if (_line < endLine || (_line == endLine && _column < endColumn)) { _functionDefinition = ast; return false; } } return true; } }; QTextEdit::ExtraSelection extraSelection(const QTextCharFormat &format, const QTextCursor &cursor) { QTextEdit::ExtraSelection selection; selection.format = format; selection.cursor = cursor; return selection; } class Params { public: Params(const QTextCursor &textCursor, const Document::Ptr document, const Snapshot &snapshot) : document(document), snapshot(snapshot) { TextEditor::Convenience::convertPosition(textCursor.document(), textCursor.position(), &line, &column); CppEditor::Internal::CanonicalSymbol canonicalSymbol(document, snapshot); scope = canonicalSymbol.getScopeAndExpression(textCursor, &expression); } public: // Shared Document::Ptr document; // For local use calculation int line; int column; // For references calculation Scope *scope; QString expression; Snapshot snapshot; }; using CppEditor::Internal::SemanticUses; void splitLocalUses(const CppTools::SemanticInfo::LocalUseMap &uses, const Params &p, SemanticUses *selectionsForLocalVariableUnderCursor, SemanticUses *selectionsForLocalUnusedVariables) { QTC_ASSERT(selectionsForLocalVariableUnderCursor, return); QTC_ASSERT(selectionsForLocalUnusedVariables, return); LookupContext context(p.document, p.snapshot); CppTools::SemanticInfo::LocalUseIterator it(uses); while (it.hasNext()) { it.next(); const SemanticUses &uses = it.value(); bool good = false; foreach (const CppTools::SemanticInfo::Use &use, uses) { unsigned l = p.line; unsigned c = p.column + 1; // convertCursorPosition() returns a 0-based column number. if (l == use.line && c >= use.column && c <= (use.column + use.length)) { good = true; break; } } if (uses.size() == 1) { if (!CppTools::isOwnershipRAIIType(it.key(), context)) selectionsForLocalUnusedVariables->append(uses); // unused declaration } else if (good && selectionsForLocalVariableUnderCursor->isEmpty()) { selectionsForLocalVariableUnderCursor->append(uses); } } } CppTools::SemanticInfo::LocalUseMap findLocalUses(const Params &p) { AST *ast = p.document->translationUnit()->ast(); FunctionDefinitionUnderCursor functionDefinitionUnderCursor(p.document->translationUnit()); DeclarationAST *declaration = functionDefinitionUnderCursor(ast, p.line, p.column); return CppTools::LocalSymbols(p.document, declaration).uses; } QList<int> findReferences(const Params &p) { QList<int> result; if (!p.scope || p.expression.isEmpty()) return result; TypeOfExpression typeOfExpression; Snapshot snapshot = p.snapshot; snapshot.insert(p.document); typeOfExpression.init(p.document, snapshot); typeOfExpression.setExpandTemplates(true); using CppEditor::Internal::CanonicalSymbol; if (Symbol *s = CanonicalSymbol::canonicalSymbol(p.scope, p.expression, typeOfExpression)) { CppTools::CppModelManagerInterface *mmi = CppTools::CppModelManagerInterface::instance(); result = mmi->references(s, typeOfExpression.context()); } return result; } CppEditor::Internal::UseSelectionsResult findUses(const Params p) { CppEditor::Internal::UseSelectionsResult result; const CppTools::SemanticInfo::LocalUseMap localUses = findLocalUses(p); result.localUses = localUses; splitLocalUses(localUses, p, &result.selectionsForLocalVariableUnderCursor, &result.selectionsForLocalUnusedVariables); if (!result.selectionsForLocalVariableUnderCursor.isEmpty()) return result; result.references = findReferences(p); return result; // OK, result.selectionsForLocalUnusedVariables will be passed on } } // anonymous namespace namespace CppEditor { namespace Internal { CppUseSelectionsUpdater::CppUseSelectionsUpdater(TextEditor::BaseTextEditorWidget *editorWidget) : m_editorWidget(editorWidget) , m_findUsesRevision(-1) { m_timer.setSingleShot(true); m_timer.setInterval(updateUseSelectionsInternalInMs); connect(&m_timer, SIGNAL(timeout()), this, SLOT(update())); } void CppUseSelectionsUpdater::scheduleUpdate() { m_timer.start(); } void CppUseSelectionsUpdater::abortSchedule() { m_timer.stop(); } void CppUseSelectionsUpdater::update(CallType callType) { CppEditorWidget *cppEditorWidget = qobject_cast<CppEditorWidget *>(m_editorWidget); QTC_ASSERT(cppEditorWidget, return); QTC_CHECK(cppEditorWidget->isSemanticInfoValidExceptLocalUses()); const CppTools::SemanticInfo semanticInfo = cppEditorWidget->semanticInfo(); const Document::Ptr document = semanticInfo.doc; const Snapshot snapshot = semanticInfo.snapshot; if (!document || document->editorRevision() != static_cast<unsigned>(textDocument()->revision())) return; QTC_ASSERT(document->translationUnit(), return); QTC_ASSERT(document->translationUnit()->ast(), return); QTC_ASSERT(!snapshot.isEmpty(), return); if (handleMacroCase(document)) { emit finished(CppTools::SemanticInfo::LocalUseMap()); return; } if (callType == Asynchronous) handleSymbolCaseAsynchronously(document, snapshot); else handleSymbolCaseSynchronously(document, snapshot); } void CppUseSelectionsUpdater::onFindUsesFinished() { QTC_ASSERT(m_findUsesWatcher, return); if (m_findUsesWatcher->isCanceled()) return; if (m_findUsesRevision != textDocument()->revision()) return; // Optimizable: If the cursor is still on the same identifier the results are valid. if (m_findUsesCursorPosition != m_editorWidget->position()) return; processSymbolCaseResults(m_findUsesWatcher->result()); m_findUsesWatcher.reset(); m_document.reset(); m_snapshot = Snapshot(); } bool CppUseSelectionsUpdater::handleMacroCase(const Document::Ptr document) { const Macro *macro = CppTools::findCanonicalMacro(m_editorWidget->textCursor(), document); if (!macro) return false; const QTextCharFormat &occurrencesFormat = textCharFormat(TextEditor::C_OCCURRENCES); ExtraSelections selections; // Macro definition if (macro->fileName() == document->fileName()) { QTextCursor cursor(textDocument()); cursor.setPosition(macro->utf16CharOffset()); cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, macro->nameToQString().size()); selections.append(extraSelection(occurrencesFormat, cursor)); } // Other macro uses foreach (const Document::MacroUse &use, document->macroUses()) { const Macro &useMacro = use.macro(); if (useMacro.line() != macro->line() || useMacro.utf16CharOffset() != macro->utf16CharOffset() || useMacro.length() != macro->length() || useMacro.fileName() != macro->fileName()) continue; QTextCursor cursor(textDocument()); cursor.setPosition(use.utf16charsBegin()); cursor.setPosition(use.utf16charsEnd(), QTextCursor::KeepAnchor); selections.append(extraSelection(occurrencesFormat, cursor)); } updateUseSelections(selections); return true; } void CppUseSelectionsUpdater::handleSymbolCaseAsynchronously(const Document::Ptr document, const Snapshot &snapshot) { m_document = document; m_snapshot = snapshot; if (m_findUsesWatcher) m_findUsesWatcher->cancel(); m_findUsesWatcher.reset(new QFutureWatcher<UseSelectionsResult>); connect(m_findUsesWatcher.data(), SIGNAL(finished()), this, SLOT(onFindUsesFinished())); m_findUsesRevision = textDocument()->revision(); m_findUsesCursorPosition = m_editorWidget->position(); const Params params = Params(m_editorWidget->textCursor(), document, snapshot); m_findUsesWatcher->setFuture(QtConcurrent::run(&findUses, params)); } void CppUseSelectionsUpdater::handleSymbolCaseSynchronously(const Document::Ptr document, const Snapshot &snapshot) { const Params params = Params(m_editorWidget->textCursor(), document, snapshot); const UseSelectionsResult result = findUses(params); processSymbolCaseResults(result); } void CppUseSelectionsUpdater::processSymbolCaseResults(const UseSelectionsResult &result) { const bool hasUsesForLocalVariable = !result.selectionsForLocalVariableUnderCursor.isEmpty(); const bool hasReferences = !result.references.isEmpty(); ExtraSelections localVariableSelections; if (hasUsesForLocalVariable) { localVariableSelections = toExtraSelections(result.selectionsForLocalVariableUnderCursor, TextEditor::C_OCCURRENCES); updateUseSelections(localVariableSelections); } else if (hasReferences) { const ExtraSelections selections = toExtraSelections(result.references, TextEditor::C_OCCURRENCES); updateUseSelections(selections); } else { if (!currentUseSelections().isEmpty()) updateUseSelections(ExtraSelections()); } updateUnusedSelections(toExtraSelections(result.selectionsForLocalUnusedVariables, TextEditor::C_OCCURRENCES_UNUSED)); emit selectionsForVariableUnderCursorUpdated(localVariableSelections); emit finished(result.localUses); } ExtraSelections CppUseSelectionsUpdater::toExtraSelections(const SemanticUses &uses, TextEditor::TextStyle style) const { ExtraSelections result; foreach (const CppTools::SemanticInfo::Use &use, uses) { if (use.isInvalid()) continue; QTextDocument *document = textDocument(); const int position = document->findBlockByNumber(use.line - 1).position() + use.column - 1; const int anchor = position + use.length; QTextEdit::ExtraSelection sel; sel.format = textCharFormat(style); sel.cursor = QTextCursor(document); sel.cursor.setPosition(anchor); sel.cursor.setPosition(position, QTextCursor::KeepAnchor); result.append(sel); } return result; } ExtraSelections CppUseSelectionsUpdater::toExtraSelections(const QList<int> &references, TextEditor::TextStyle style) const { ExtraSelections selections; foreach (int index, references) { unsigned line, column; TranslationUnit *unit = m_document->translationUnit(); unit->getTokenPosition(index, &line, &column); if (column) --column; // adjust the column position. const int len = unit->tokenAt(index).utf16chars(); QTextCursor cursor(textDocument()->findBlockByNumber(line - 1)); cursor.setPosition(cursor.position() + column); cursor.setPosition(cursor.position() + len, QTextCursor::KeepAnchor); selections.append(extraSelection(textCharFormat(style), cursor)); } return selections; } QTextCharFormat CppUseSelectionsUpdater::textCharFormat(TextEditor::TextStyle category) const { return m_editorWidget->textDocument()->fontSettings().toTextCharFormat(category); } QTextDocument *CppUseSelectionsUpdater::textDocument() const { return m_editorWidget->document(); } ExtraSelections CppUseSelectionsUpdater::currentUseSelections() const { return m_editorWidget->extraSelections( TextEditor::BaseTextEditorWidget::CodeSemanticsSelection); } void CppUseSelectionsUpdater::updateUseSelections(const ExtraSelections &selections) { m_editorWidget->setExtraSelections(TextEditor::BaseTextEditorWidget::CodeSemanticsSelection, selections); } void CppUseSelectionsUpdater::updateUnusedSelections(const ExtraSelections &selections) { m_editorWidget->setExtraSelections(TextEditor::BaseTextEditorWidget::UnusedSymbolSelection, selections); } } // namespace Internal } // namespace CppEditor <commit_msg>CppEditor: Compare semantic info revision in CppUseSelectionsUpdater<commit_after>/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "cppuseselectionsupdater.h" #include "cppcanonicalsymbol.h" #include "cppeditor.h" #include <cpptools/cpplocalsymbols.h> #include <cpptools/cppmodelmanagerinterface.h> #include <cpptools/cpptoolsreuse.h> #include <texteditor/basetexteditor.h> #include <texteditor/convenience.h> #include <texteditor/fontsettings.h> #include <cplusplus/Macro.h> #include <cplusplus/TranslationUnit.h> #include <utils/qtcassert.h> #include <QtConcurrentRun> #include <QTextBlock> #include <QTextCursor> #include <QTextEdit> using namespace CPlusPlus; enum { updateUseSelectionsInternalInMs = 500 }; namespace { class FunctionDefinitionUnderCursor: protected ASTVisitor { unsigned _line; unsigned _column; DeclarationAST *_functionDefinition; public: FunctionDefinitionUnderCursor(TranslationUnit *translationUnit) : ASTVisitor(translationUnit), _line(0), _column(0) { } DeclarationAST *operator()(AST *ast, unsigned line, unsigned column) { _functionDefinition = 0; _line = line; _column = column; accept(ast); return _functionDefinition; } protected: virtual bool preVisit(AST *ast) { if (_functionDefinition) return false; if (FunctionDefinitionAST *def = ast->asFunctionDefinition()) return checkDeclaration(def); if (ObjCMethodDeclarationAST *method = ast->asObjCMethodDeclaration()) { if (method->function_body) return checkDeclaration(method); } return true; } private: bool checkDeclaration(DeclarationAST *ast) { unsigned startLine, startColumn; unsigned endLine, endColumn; getTokenStartPosition(ast->firstToken(), &startLine, &startColumn); getTokenEndPosition(ast->lastToken() - 1, &endLine, &endColumn); if (_line > startLine || (_line == startLine && _column >= startColumn)) { if (_line < endLine || (_line == endLine && _column < endColumn)) { _functionDefinition = ast; return false; } } return true; } }; QTextEdit::ExtraSelection extraSelection(const QTextCharFormat &format, const QTextCursor &cursor) { QTextEdit::ExtraSelection selection; selection.format = format; selection.cursor = cursor; return selection; } class Params { public: Params(const QTextCursor &textCursor, const Document::Ptr document, const Snapshot &snapshot) : document(document), snapshot(snapshot) { TextEditor::Convenience::convertPosition(textCursor.document(), textCursor.position(), &line, &column); CppEditor::Internal::CanonicalSymbol canonicalSymbol(document, snapshot); scope = canonicalSymbol.getScopeAndExpression(textCursor, &expression); } public: // Shared Document::Ptr document; // For local use calculation int line; int column; // For references calculation Scope *scope; QString expression; Snapshot snapshot; }; using CppEditor::Internal::SemanticUses; void splitLocalUses(const CppTools::SemanticInfo::LocalUseMap &uses, const Params &p, SemanticUses *selectionsForLocalVariableUnderCursor, SemanticUses *selectionsForLocalUnusedVariables) { QTC_ASSERT(selectionsForLocalVariableUnderCursor, return); QTC_ASSERT(selectionsForLocalUnusedVariables, return); LookupContext context(p.document, p.snapshot); CppTools::SemanticInfo::LocalUseIterator it(uses); while (it.hasNext()) { it.next(); const SemanticUses &uses = it.value(); bool good = false; foreach (const CppTools::SemanticInfo::Use &use, uses) { unsigned l = p.line; unsigned c = p.column + 1; // convertCursorPosition() returns a 0-based column number. if (l == use.line && c >= use.column && c <= (use.column + use.length)) { good = true; break; } } if (uses.size() == 1) { if (!CppTools::isOwnershipRAIIType(it.key(), context)) selectionsForLocalUnusedVariables->append(uses); // unused declaration } else if (good && selectionsForLocalVariableUnderCursor->isEmpty()) { selectionsForLocalVariableUnderCursor->append(uses); } } } CppTools::SemanticInfo::LocalUseMap findLocalUses(const Params &p) { AST *ast = p.document->translationUnit()->ast(); FunctionDefinitionUnderCursor functionDefinitionUnderCursor(p.document->translationUnit()); DeclarationAST *declaration = functionDefinitionUnderCursor(ast, p.line, p.column); return CppTools::LocalSymbols(p.document, declaration).uses; } QList<int> findReferences(const Params &p) { QList<int> result; if (!p.scope || p.expression.isEmpty()) return result; TypeOfExpression typeOfExpression; Snapshot snapshot = p.snapshot; snapshot.insert(p.document); typeOfExpression.init(p.document, snapshot); typeOfExpression.setExpandTemplates(true); using CppEditor::Internal::CanonicalSymbol; if (Symbol *s = CanonicalSymbol::canonicalSymbol(p.scope, p.expression, typeOfExpression)) { CppTools::CppModelManagerInterface *mmi = CppTools::CppModelManagerInterface::instance(); result = mmi->references(s, typeOfExpression.context()); } return result; } CppEditor::Internal::UseSelectionsResult findUses(const Params p) { CppEditor::Internal::UseSelectionsResult result; const CppTools::SemanticInfo::LocalUseMap localUses = findLocalUses(p); result.localUses = localUses; splitLocalUses(localUses, p, &result.selectionsForLocalVariableUnderCursor, &result.selectionsForLocalUnusedVariables); if (!result.selectionsForLocalVariableUnderCursor.isEmpty()) return result; result.references = findReferences(p); return result; // OK, result.selectionsForLocalUnusedVariables will be passed on } } // anonymous namespace namespace CppEditor { namespace Internal { CppUseSelectionsUpdater::CppUseSelectionsUpdater(TextEditor::BaseTextEditorWidget *editorWidget) : m_editorWidget(editorWidget) , m_findUsesRevision(-1) { m_timer.setSingleShot(true); m_timer.setInterval(updateUseSelectionsInternalInMs); connect(&m_timer, SIGNAL(timeout()), this, SLOT(update())); } void CppUseSelectionsUpdater::scheduleUpdate() { m_timer.start(); } void CppUseSelectionsUpdater::abortSchedule() { m_timer.stop(); } void CppUseSelectionsUpdater::update(CallType callType) { CppEditorWidget *cppEditorWidget = qobject_cast<CppEditorWidget *>(m_editorWidget); QTC_ASSERT(cppEditorWidget, return); QTC_CHECK(cppEditorWidget->isSemanticInfoValidExceptLocalUses()); const CppTools::SemanticInfo semanticInfo = cppEditorWidget->semanticInfo(); const Document::Ptr document = semanticInfo.doc; const Snapshot snapshot = semanticInfo.snapshot; if (!document) return; if (semanticInfo.revision != static_cast<unsigned>(textDocument()->revision())) return; QTC_ASSERT(document->translationUnit(), return); QTC_ASSERT(document->translationUnit()->ast(), return); QTC_ASSERT(!snapshot.isEmpty(), return); if (handleMacroCase(document)) { emit finished(CppTools::SemanticInfo::LocalUseMap()); return; } if (callType == Asynchronous) handleSymbolCaseAsynchronously(document, snapshot); else handleSymbolCaseSynchronously(document, snapshot); } void CppUseSelectionsUpdater::onFindUsesFinished() { QTC_ASSERT(m_findUsesWatcher, return); if (m_findUsesWatcher->isCanceled()) return; if (m_findUsesRevision != textDocument()->revision()) return; // Optimizable: If the cursor is still on the same identifier the results are valid. if (m_findUsesCursorPosition != m_editorWidget->position()) return; processSymbolCaseResults(m_findUsesWatcher->result()); m_findUsesWatcher.reset(); m_document.reset(); m_snapshot = Snapshot(); } bool CppUseSelectionsUpdater::handleMacroCase(const Document::Ptr document) { const Macro *macro = CppTools::findCanonicalMacro(m_editorWidget->textCursor(), document); if (!macro) return false; const QTextCharFormat &occurrencesFormat = textCharFormat(TextEditor::C_OCCURRENCES); ExtraSelections selections; // Macro definition if (macro->fileName() == document->fileName()) { QTextCursor cursor(textDocument()); cursor.setPosition(macro->utf16CharOffset()); cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, macro->nameToQString().size()); selections.append(extraSelection(occurrencesFormat, cursor)); } // Other macro uses foreach (const Document::MacroUse &use, document->macroUses()) { const Macro &useMacro = use.macro(); if (useMacro.line() != macro->line() || useMacro.utf16CharOffset() != macro->utf16CharOffset() || useMacro.length() != macro->length() || useMacro.fileName() != macro->fileName()) continue; QTextCursor cursor(textDocument()); cursor.setPosition(use.utf16charsBegin()); cursor.setPosition(use.utf16charsEnd(), QTextCursor::KeepAnchor); selections.append(extraSelection(occurrencesFormat, cursor)); } updateUseSelections(selections); return true; } void CppUseSelectionsUpdater::handleSymbolCaseAsynchronously(const Document::Ptr document, const Snapshot &snapshot) { m_document = document; m_snapshot = snapshot; if (m_findUsesWatcher) m_findUsesWatcher->cancel(); m_findUsesWatcher.reset(new QFutureWatcher<UseSelectionsResult>); connect(m_findUsesWatcher.data(), SIGNAL(finished()), this, SLOT(onFindUsesFinished())); m_findUsesRevision = textDocument()->revision(); m_findUsesCursorPosition = m_editorWidget->position(); const Params params = Params(m_editorWidget->textCursor(), document, snapshot); m_findUsesWatcher->setFuture(QtConcurrent::run(&findUses, params)); } void CppUseSelectionsUpdater::handleSymbolCaseSynchronously(const Document::Ptr document, const Snapshot &snapshot) { const Params params = Params(m_editorWidget->textCursor(), document, snapshot); const UseSelectionsResult result = findUses(params); processSymbolCaseResults(result); } void CppUseSelectionsUpdater::processSymbolCaseResults(const UseSelectionsResult &result) { const bool hasUsesForLocalVariable = !result.selectionsForLocalVariableUnderCursor.isEmpty(); const bool hasReferences = !result.references.isEmpty(); ExtraSelections localVariableSelections; if (hasUsesForLocalVariable) { localVariableSelections = toExtraSelections(result.selectionsForLocalVariableUnderCursor, TextEditor::C_OCCURRENCES); updateUseSelections(localVariableSelections); } else if (hasReferences) { const ExtraSelections selections = toExtraSelections(result.references, TextEditor::C_OCCURRENCES); updateUseSelections(selections); } else { if (!currentUseSelections().isEmpty()) updateUseSelections(ExtraSelections()); } updateUnusedSelections(toExtraSelections(result.selectionsForLocalUnusedVariables, TextEditor::C_OCCURRENCES_UNUSED)); emit selectionsForVariableUnderCursorUpdated(localVariableSelections); emit finished(result.localUses); } ExtraSelections CppUseSelectionsUpdater::toExtraSelections(const SemanticUses &uses, TextEditor::TextStyle style) const { ExtraSelections result; foreach (const CppTools::SemanticInfo::Use &use, uses) { if (use.isInvalid()) continue; QTextDocument *document = textDocument(); const int position = document->findBlockByNumber(use.line - 1).position() + use.column - 1; const int anchor = position + use.length; QTextEdit::ExtraSelection sel; sel.format = textCharFormat(style); sel.cursor = QTextCursor(document); sel.cursor.setPosition(anchor); sel.cursor.setPosition(position, QTextCursor::KeepAnchor); result.append(sel); } return result; } ExtraSelections CppUseSelectionsUpdater::toExtraSelections(const QList<int> &references, TextEditor::TextStyle style) const { ExtraSelections selections; foreach (int index, references) { unsigned line, column; TranslationUnit *unit = m_document->translationUnit(); unit->getTokenPosition(index, &line, &column); if (column) --column; // adjust the column position. const int len = unit->tokenAt(index).utf16chars(); QTextCursor cursor(textDocument()->findBlockByNumber(line - 1)); cursor.setPosition(cursor.position() + column); cursor.setPosition(cursor.position() + len, QTextCursor::KeepAnchor); selections.append(extraSelection(textCharFormat(style), cursor)); } return selections; } QTextCharFormat CppUseSelectionsUpdater::textCharFormat(TextEditor::TextStyle category) const { return m_editorWidget->textDocument()->fontSettings().toTextCharFormat(category); } QTextDocument *CppUseSelectionsUpdater::textDocument() const { return m_editorWidget->document(); } ExtraSelections CppUseSelectionsUpdater::currentUseSelections() const { return m_editorWidget->extraSelections( TextEditor::BaseTextEditorWidget::CodeSemanticsSelection); } void CppUseSelectionsUpdater::updateUseSelections(const ExtraSelections &selections) { m_editorWidget->setExtraSelections(TextEditor::BaseTextEditorWidget::CodeSemanticsSelection, selections); } void CppUseSelectionsUpdater::updateUnusedSelections(const ExtraSelections &selections) { m_editorWidget->setExtraSelections(TextEditor::BaseTextEditorWidget::UnusedSymbolSelection, selections); } } // namespace Internal } // namespace CppEditor <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "startgdbserverdialog.h" #include "debuggercore.h" #include "debuggermainwindow.h" #include "debuggerplugin.h" #include "debuggerkitinformation.h" #include "debuggerrunner.h" #include "debuggerruncontrolfactory.h" #include "debuggerstartparameters.h" #include <coreplugin/icore.h> #include <extensionsystem/pluginmanager.h> #include <projectexplorer/kitchooser.h> #include <projectexplorer/devicesupport/deviceprocesslist.h> #include <projectexplorer/devicesupport/deviceusedportsgatherer.h> #include <ssh/sshconnection.h> #include <ssh/sshremoteprocessrunner.h> #include <utils/pathchooser.h> #include <utils/portlist.h> #include <utils/qtcassert.h> #include <QVariant> #include <QMessageBox> using namespace Core; using namespace ProjectExplorer; using namespace QSsh; using namespace Utils; namespace Debugger { namespace Internal { class StartGdbServerDialogPrivate { public: StartGdbServerDialogPrivate() {} DeviceProcessesDialog *dialog; bool startServerOnly; DeviceProcess process; Kit *kit; IDevice::ConstPtr device; DeviceUsedPortsGatherer gatherer; SshRemoteProcessRunner runner; }; GdbServerStarter::GdbServerStarter(DeviceProcessesDialog *dlg, bool startServerOnly) : QObject(dlg) { d = new StartGdbServerDialogPrivate; d->dialog = dlg; d->kit = dlg->kitChooser()->currentKit(); d->process = dlg->currentProcess(); d->device = DeviceKitInformation::device(d->kit); d->startServerOnly = startServerOnly; } GdbServerStarter::~GdbServerStarter() { delete d; } void GdbServerStarter::handleRemoteError(const QString &errorMsg) { QMessageBox::critical(0, tr("Remote Error"), errorMsg); } void GdbServerStarter::portGathererError(const QString &text) { logMessage(tr("Could not retrieve list of free ports:")); logMessage(text); logMessage(tr("Process aborted")); } void GdbServerStarter::run() { QTC_ASSERT(d->device, return); connect(&d->gatherer, SIGNAL(error(QString)), SLOT(portGathererError(QString))); connect(&d->gatherer, SIGNAL(portListReady()), SLOT(portListReady())); d->gatherer.start(d->device); } void GdbServerStarter::portListReady() { PortList ports = d->device->freePorts(); const int port = d->gatherer.getNextFreePort(&ports); if (port == -1) { QTC_ASSERT(false, /**/); emit logMessage(tr("Process aborted")); return; } connect(&d->runner, SIGNAL(connectionError()), SLOT(handleConnectionError())); connect(&d->runner, SIGNAL(processStarted()), SLOT(handleProcessStarted())); connect(&d->runner, SIGNAL(readyReadStandardOutput()), SLOT(handleProcessOutputAvailable())); connect(&d->runner, SIGNAL(readyReadStandardError()), SLOT(handleProcessErrorOutput())); connect(&d->runner, SIGNAL(processClosed(int)), SLOT(handleProcessClosed(int))); QByteArray cmd = "/usr/bin/gdbserver --attach :" + QByteArray::number(port) + ' ' + QByteArray::number(d->process.pid); logMessage(tr("Running command: %1").arg(QString::fromLatin1(cmd))); d->runner.run(cmd, d->device->sshParameters()); } void GdbServerStarter::handleConnectionError() { logMessage(tr("Connection error: %1").arg(d->runner.lastConnectionErrorString())); } void GdbServerStarter::handleProcessStarted() { logMessage(tr("Starting gdbserver...")); } void GdbServerStarter::handleProcessOutputAvailable() { logMessage(QString::fromUtf8(d->runner.readAllStandardOutput().trimmed())); } void GdbServerStarter::handleProcessErrorOutput() { const QByteArray ba = d->runner.readAllStandardError(); logMessage(QString::fromUtf8(ba.trimmed())); // "Attached; pid = 16740" // "Listening on port 10000" foreach (const QByteArray &line, ba.split('\n')) { if (line.startsWith("Listening on port")) { const int port = line.mid(18).trimmed().toInt(); logMessage(tr("Port %1 is now accessible.").arg(port)); logMessage(tr("Server started on %1:%2") .arg(d->device->sshParameters().host).arg(port)); if (!d->startServerOnly) attach(port); } } } void GdbServerStarter::attach(int port) { QString sysroot = SysRootKitInformation::sysRoot(d->kit).toString(); QString binary; QString localExecutable; QString candidate = sysroot + d->process.exe; if (QFileInfo(candidate).exists()) localExecutable = candidate; if (localExecutable.isEmpty()) { binary = d->process.cmdLine.section(QLatin1Char(' '), 0, 0); candidate = sysroot + QLatin1Char('/') + binary; if (QFileInfo(candidate).exists()) localExecutable = candidate; } if (localExecutable.isEmpty()) { candidate = sysroot + QLatin1String("/usr/bin/") + binary; if (QFileInfo(candidate).exists()) localExecutable = candidate; } if (localExecutable.isEmpty()) { candidate = sysroot + QLatin1String("/bin/") + binary; if (QFileInfo(candidate).exists()) localExecutable = candidate; } if (localExecutable.isEmpty()) { QMessageBox::warning(DebuggerPlugin::mainWindow(), tr("Warning"), tr("Cannot find local executable for remote process \"%1\".") .arg(d->process.exe)); return; } QList<Abi> abis = Abi::abisOfBinary(Utils::FileName::fromString(localExecutable)); if (abis.isEmpty()) { QMessageBox::warning(DebuggerPlugin::mainWindow(), tr("Warning"), tr("Cannot find ABI for remote process \"%1\".") .arg(d->process.exe)); return; } DebuggerStartParameters sp; QTC_ASSERT(fillParameters(&sp, d->kit), return); sp.masterEngineType = GdbEngineType; sp.connParams.port = port; sp.displayName = tr("Remote: \"%1:%2\"").arg(sp.connParams.host).arg(port); sp.executable = localExecutable; sp.startMode = AttachToRemoteServer; sp.closeMode = KillAtClose; DebuggerRunControlFactory::createAndScheduleRun(sp); } void GdbServerStarter::handleProcessClosed(int status) { logMessage(tr("Process gdbserver finished. Status: %1").arg(status)); } void GdbServerStarter::logMessage(const QString &line) { d->dialog->logMessage(line); } } // namespace Internal } // namespace Debugger <commit_msg>Set the proper port on the remote channel.<commit_after>/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "startgdbserverdialog.h" #include "debuggercore.h" #include "debuggermainwindow.h" #include "debuggerplugin.h" #include "debuggerkitinformation.h" #include "debuggerrunner.h" #include "debuggerruncontrolfactory.h" #include "debuggerstartparameters.h" #include <coreplugin/icore.h> #include <extensionsystem/pluginmanager.h> #include <projectexplorer/kitchooser.h> #include <projectexplorer/devicesupport/deviceprocesslist.h> #include <projectexplorer/devicesupport/deviceusedportsgatherer.h> #include <ssh/sshconnection.h> #include <ssh/sshremoteprocessrunner.h> #include <utils/pathchooser.h> #include <utils/portlist.h> #include <utils/qtcassert.h> #include <QVariant> #include <QMessageBox> using namespace Core; using namespace ProjectExplorer; using namespace QSsh; using namespace Utils; namespace Debugger { namespace Internal { class StartGdbServerDialogPrivate { public: StartGdbServerDialogPrivate() {} DeviceProcessesDialog *dialog; bool startServerOnly; DeviceProcess process; Kit *kit; IDevice::ConstPtr device; DeviceUsedPortsGatherer gatherer; SshRemoteProcessRunner runner; }; GdbServerStarter::GdbServerStarter(DeviceProcessesDialog *dlg, bool startServerOnly) : QObject(dlg) { d = new StartGdbServerDialogPrivate; d->dialog = dlg; d->kit = dlg->kitChooser()->currentKit(); d->process = dlg->currentProcess(); d->device = DeviceKitInformation::device(d->kit); d->startServerOnly = startServerOnly; } GdbServerStarter::~GdbServerStarter() { delete d; } void GdbServerStarter::handleRemoteError(const QString &errorMsg) { QMessageBox::critical(0, tr("Remote Error"), errorMsg); } void GdbServerStarter::portGathererError(const QString &text) { logMessage(tr("Could not retrieve list of free ports:")); logMessage(text); logMessage(tr("Process aborted")); } void GdbServerStarter::run() { QTC_ASSERT(d->device, return); connect(&d->gatherer, SIGNAL(error(QString)), SLOT(portGathererError(QString))); connect(&d->gatherer, SIGNAL(portListReady()), SLOT(portListReady())); d->gatherer.start(d->device); } void GdbServerStarter::portListReady() { PortList ports = d->device->freePorts(); const int port = d->gatherer.getNextFreePort(&ports); if (port == -1) { QTC_ASSERT(false, /**/); emit logMessage(tr("Process aborted")); return; } connect(&d->runner, SIGNAL(connectionError()), SLOT(handleConnectionError())); connect(&d->runner, SIGNAL(processStarted()), SLOT(handleProcessStarted())); connect(&d->runner, SIGNAL(readyReadStandardOutput()), SLOT(handleProcessOutputAvailable())); connect(&d->runner, SIGNAL(readyReadStandardError()), SLOT(handleProcessErrorOutput())); connect(&d->runner, SIGNAL(processClosed(int)), SLOT(handleProcessClosed(int))); QByteArray cmd = "/usr/bin/gdbserver --attach :" + QByteArray::number(port) + ' ' + QByteArray::number(d->process.pid); logMessage(tr("Running command: %1").arg(QString::fromLatin1(cmd))); d->runner.run(cmd, d->device->sshParameters()); } void GdbServerStarter::handleConnectionError() { logMessage(tr("Connection error: %1").arg(d->runner.lastConnectionErrorString())); } void GdbServerStarter::handleProcessStarted() { logMessage(tr("Starting gdbserver...")); } void GdbServerStarter::handleProcessOutputAvailable() { logMessage(QString::fromUtf8(d->runner.readAllStandardOutput().trimmed())); } void GdbServerStarter::handleProcessErrorOutput() { const QByteArray ba = d->runner.readAllStandardError(); logMessage(QString::fromUtf8(ba.trimmed())); // "Attached; pid = 16740" // "Listening on port 10000" foreach (const QByteArray &line, ba.split('\n')) { if (line.startsWith("Listening on port")) { const int port = line.mid(18).trimmed().toInt(); logMessage(tr("Port %1 is now accessible.").arg(port)); logMessage(tr("Server started on %1:%2") .arg(d->device->sshParameters().host).arg(port)); if (!d->startServerOnly) attach(port); } } } void GdbServerStarter::attach(int port) { QString sysroot = SysRootKitInformation::sysRoot(d->kit).toString(); QString binary; QString localExecutable; QString candidate = sysroot + d->process.exe; if (QFileInfo(candidate).exists()) localExecutable = candidate; if (localExecutable.isEmpty()) { binary = d->process.cmdLine.section(QLatin1Char(' '), 0, 0); candidate = sysroot + QLatin1Char('/') + binary; if (QFileInfo(candidate).exists()) localExecutable = candidate; } if (localExecutable.isEmpty()) { candidate = sysroot + QLatin1String("/usr/bin/") + binary; if (QFileInfo(candidate).exists()) localExecutable = candidate; } if (localExecutable.isEmpty()) { candidate = sysroot + QLatin1String("/bin/") + binary; if (QFileInfo(candidate).exists()) localExecutable = candidate; } if (localExecutable.isEmpty()) { QMessageBox::warning(DebuggerPlugin::mainWindow(), tr("Warning"), tr("Cannot find local executable for remote process \"%1\".") .arg(d->process.exe)); return; } QList<Abi> abis = Abi::abisOfBinary(Utils::FileName::fromString(localExecutable)); if (abis.isEmpty()) { QMessageBox::warning(DebuggerPlugin::mainWindow(), tr("Warning"), tr("Cannot find ABI for remote process \"%1\".") .arg(d->process.exe)); return; } DebuggerStartParameters sp; QTC_ASSERT(fillParameters(&sp, d->kit), return); sp.masterEngineType = GdbEngineType; sp.connParams.port = port; sp.remoteChannel = sp.connParams.host + QLatin1Char(':') + QString::number(sp.connParams.port); sp.displayName = tr("Remote: \"%1:%2\"").arg(sp.connParams.host).arg(port); sp.executable = localExecutable; sp.startMode = AttachToRemoteServer; sp.closeMode = KillAtClose; DebuggerRunControlFactory::createAndScheduleRun(sp); } void GdbServerStarter::handleProcessClosed(int status) { logMessage(tr("Process gdbserver finished. Status: %1").arg(status)); } void GdbServerStarter::logMessage(const QString &line) { d->dialog->logMessage(line); } } // namespace Internal } // namespace Debugger <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** **************************************************************************/ #include "codaqmlprofilerrunner.h" #include <utils/qtcassert.h> #include <projectexplorer/projectexplorerconstants.h> #include <projectexplorer/target.h> #include <extensionsystem/pluginmanager.h> #include <qt4projectmanager/qt-s60/s60deployconfiguration.h> #include <projectexplorer/runconfiguration.h> #include <analyzerbase/analyzerconstants.h> #include <qt4projectmanager/qt-s60/codaruncontrol.h> using namespace ProjectExplorer; using namespace Qt4ProjectManager; using namespace QmlProfiler::Internal; CodaQmlProfilerRunner::CodaQmlProfilerRunner(S60DeviceRunConfiguration *configuration, QObject *parent) : AbstractQmlProfilerRunner(parent), m_configuration(configuration), m_runControl(new CodaRunControl(configuration, "QmlProfiler")) { connect(m_runControl, SIGNAL(finished()), this, SIGNAL(stopped())); connect(m_runControl, SIGNAL(appendMessage(ProjectExplorer::RunControl*,QString,Utils::OutputFormat)), this, SLOT(appendMessage(ProjectExplorer::RunControl*,QString,Utils::OutputFormat))); } CodaQmlProfilerRunner::~CodaQmlProfilerRunner() { delete m_runControl; } void CodaQmlProfilerRunner::start() { QTC_ASSERT(m_runControl, return); m_runControl->start(); } void CodaQmlProfilerRunner::stop() { QTC_ASSERT(m_runControl, return); m_runControl->stop(); } void CodaQmlProfilerRunner::appendMessage(ProjectExplorer::RunControl *, const QString &message, Utils::OutputFormat format) { emit appendMessage(message, format); } int QmlProfiler::Internal::CodaQmlProfilerRunner::debugPort() const { return m_configuration->qmlDebugServerPort(); } <commit_msg>QMlProfiler: Fix regression when running on Symbian device<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** **************************************************************************/ #include "codaqmlprofilerrunner.h" #include <utils/qtcassert.h> #include <projectexplorer/projectexplorerconstants.h> #include <projectexplorer/target.h> #include <extensionsystem/pluginmanager.h> #include <qt4projectmanager/qt-s60/s60deployconfiguration.h> #include <projectexplorer/runconfiguration.h> #include <analyzerbase/analyzerconstants.h> #include <qt4projectmanager/qt-s60/codaruncontrol.h> using namespace ProjectExplorer; using namespace Qt4ProjectManager; using namespace QmlProfiler::Internal; CodaQmlProfilerRunner::CodaQmlProfilerRunner(S60DeviceRunConfiguration *configuration, QObject *parent) : AbstractQmlProfilerRunner(parent), m_configuration(configuration), m_runControl(new CodaRunControl(configuration, Analyzer::Constants::MODE_ANALYZE)) { connect(m_runControl, SIGNAL(finished()), this, SIGNAL(stopped())); connect(m_runControl, SIGNAL(appendMessage(ProjectExplorer::RunControl*,QString,Utils::OutputFormat)), this, SLOT(appendMessage(ProjectExplorer::RunControl*,QString,Utils::OutputFormat))); } CodaQmlProfilerRunner::~CodaQmlProfilerRunner() { delete m_runControl; } void CodaQmlProfilerRunner::start() { QTC_ASSERT(m_runControl, return); m_runControl->start(); } void CodaQmlProfilerRunner::stop() { QTC_ASSERT(m_runControl, return); m_runControl->stop(); } void CodaQmlProfilerRunner::appendMessage(ProjectExplorer::RunControl *, const QString &message, Utils::OutputFormat format) { emit appendMessage(message, format); } int QmlProfiler::Internal::CodaQmlProfilerRunner::debugPort() const { return m_configuration->qmlDebugServerPort(); } <|endoftext|>
<commit_before>//Copyright (c) 2011 Krishna Rajendran <[email protected]>. //Licensed under an MIT/X11 license. See LICENSE file for details. extern "C" { #include <gtk/gtk.h> #include <gdk/gdkkeysyms.h> } #include "eldb.hpp" #include "eldb_gtk_globalkeybind.hpp" namespace elgtk { struct KeyList; struct ValueList; struct Window { eldb::Eldb eldb; GtkWidget *window; GtkWidget *searchEntry; KeyList *keyList; ValueList *valueList; Window(); static void destroy(); static void searchEntryChanged( GtkWidget *widget, Window *window ); static int keySnooper( GtkWidget *widget, GdkEventKey *event, gpointer data ); void layout(); }; struct KeyList { GtkWidget *treeView; GtkListStore *listStore; GtkTreeViewColumn *column; GtkCellRenderer *nameRenderer; GtkTreeSelection *select; enum Columns { KEY_COLUMN = 0, VALUE_COLUMN }; KeyList( ValueList *valueList ); static void changed( GtkTreeSelection *widget, ValueList *valueList ); }; struct ValueList { GtkWidget* vBox; ValueList(); }; Window::Window() { if ( !eldb.init( "" ) ) { exit(1); } window = gtk_window_new( GTK_WINDOW_TOPLEVEL ); searchEntry = gtk_entry_new(); valueList = new ValueList(); keyList = new KeyList( valueList ); layout(); g_signal_connect( searchEntry, "changed", G_CALLBACK( searchEntryChanged ), this ); g_signal_connect( window, "destroy", G_CALLBACK( destroy ), NULL ); gtk_window_set_title( GTK_WINDOW( window ), "The Exo Lobe" ); gtk_widget_show_all( window ); gtk_window_stick( GTK_WINDOW( window ) ); gtk_window_set_keep_above( GTK_WINDOW( window ), 1 ); searchEntryChanged( searchEntry, this ); gtk_key_snooper_install( keySnooper, window ); gtk_window_set_focus( GTK_WINDOW( window ), 0 ); globalBinding( GTK_WINDOW( window ) ); } KeyList::KeyList( ValueList *valueList ) { listStore = gtk_list_store_new( 2, G_TYPE_STRING, G_TYPE_STRING ); treeView = gtk_tree_view_new_with_model( GTK_TREE_MODEL( listStore ) ); nameRenderer = gtk_cell_renderer_text_new(); column = gtk_tree_view_column_new_with_attributes( "Keys", nameRenderer, "text", KEY_COLUMN, (void *)NULL ); gtk_tree_view_append_column( GTK_TREE_VIEW( treeView ), column ); g_object_unref( G_OBJECT( listStore ) ); select = gtk_tree_view_get_selection( GTK_TREE_VIEW ( treeView ) ); gtk_tree_selection_set_mode( select, GTK_SELECTION_SINGLE ); g_signal_connect( select, "changed", G_CALLBACK( KeyList::changed ), valueList ); } void KeyList::changed( GtkTreeSelection *selection, ValueList *valueList ) { GtkTreeIter iter; GtkTreeModel *model; //const char *key; if ( gtk_tree_selection_get_selected( selection, &model, &iter ) ) { /* gtk_tree_model_get( model, &iter, VALUE_COLUMN, &key, -1 ); GtkTextBuffer *buffer = gtk_text_view_get_buffer( textView ); gtk_text_buffer_set_text( buffer, key, -1 );*/ } } ValueList::ValueList() { vBox = gtk_vbox_new( FALSE, 3 ); //TODO gtk_text_view_set_wrap_mode( GTK_TEXT_VIEW( textView ), GTK_WRAP_WORD_CHAR ); } void Window::destroy( ) { gtk_main_quit (); } void Window::searchEntryChanged( GtkWidget *widget, Window *window ) { const char *text; GtkTreeIter iter; GtkListStore *keyStore = window->keyList->listStore; gtk_list_store_clear( keyStore ); text = gtk_entry_get_text( GTK_ENTRY( widget ) ); auto result = window->eldb.find( text ); if ( result->count ) { for ( auto key: result->keys ) { fprintf( stdout, "%s :\n", key->key.c_str() ); for ( auto value: key->values ) { fprintf( stdout, "\t%s\n", value->value.c_str() ); gtk_list_store_append( keyStore, &iter ); gtk_list_store_set( keyStore, &iter, KeyList::KEY_COLUMN , key->key.c_str(), KeyList::VALUE_COLUMN, value->value.c_str(), -1 ); } } } else { fprintf( stderr, "No Results\n" ); } } void Window::layout() { GtkWidget *table = gtk_table_new( 3, 3, FALSE ); GtkWidget *textViewScroller = gtk_scrolled_window_new( NULL, NULL ); GtkWidget *keyListScroller = gtk_scrolled_window_new( NULL, NULL ); gtk_container_set_border_width( GTK_CONTAINER( window ), 5 ); gtk_table_attach( GTK_TABLE( table ), searchEntry, 0, 3, 0, 1, GtkAttachOptions( GTK_EXPAND | GTK_FILL ), GTK_SHRINK, 0, 0 ); gtk_table_attach_defaults( GTK_TABLE( table ), keyListScroller, 0, 1, 1, 3 ); gtk_table_attach_defaults( GTK_TABLE( table ), textViewScroller, 1, 3, 1, 3 ); gtk_container_add( GTK_CONTAINER( keyListScroller ), keyList->treeView ); gtk_scrolled_window_add_with_viewport( GTK_SCROLLED_WINDOW( textViewScroller ), valueList->vBox ); gtk_table_set_row_spacings( GTK_TABLE( table ), 2 ); gtk_table_set_col_spacings( GTK_TABLE( table ), 2 ); gtk_container_add( GTK_CONTAINER( window ), table ); } int Window::keySnooper( GtkWidget *widget, GdkEventKey *event, gpointer data ) { if ( event->keyval == GDK_KEY_q && event->state & GDK_CONTROL_MASK ) { destroy( ); } if ( event->keyval == GDK_KEY_Escape ) { gtk_window_set_focus( GTK_WINDOW( data ), 0 ); } return 0; } } //namespace elgtk int main( int argc, char **argv ) { gtk_init( &argc, &argv ); elgtk::Window window; gtk_main(); return 0; } <commit_msg>Set a default gtk window size<commit_after>//Copyright (c) 2011 Krishna Rajendran <[email protected]>. //Licensed under an MIT/X11 license. See LICENSE file for details. extern "C" { #include <gtk/gtk.h> #include <gdk/gdkkeysyms.h> } #include "eldb.hpp" #include "eldb_gtk_globalkeybind.hpp" namespace elgtk { struct KeyList; struct ValueList; struct Window { eldb::Eldb eldb; GtkWidget *window; GtkWidget *searchEntry; KeyList *keyList; ValueList *valueList; Window(); static void destroy(); static void searchEntryChanged( GtkWidget *widget, Window *window ); static int keySnooper( GtkWidget *widget, GdkEventKey *event, gpointer data ); void layout(); }; struct KeyList { GtkWidget *treeView; GtkListStore *listStore; GtkTreeViewColumn *column; GtkCellRenderer *nameRenderer; GtkTreeSelection *select; enum Columns { KEY_COLUMN = 0, VALUE_COLUMN }; KeyList( ValueList *valueList ); static void changed( GtkTreeSelection *widget, ValueList *valueList ); }; struct ValueList { GtkWidget* vBox; ValueList(); }; Window::Window() { if ( !eldb.init( "" ) ) { exit(1); } window = gtk_window_new( GTK_WINDOW_TOPLEVEL ); searchEntry = gtk_entry_new(); valueList = new ValueList(); keyList = new KeyList( valueList ); layout(); g_signal_connect( searchEntry, "changed", G_CALLBACK( searchEntryChanged ), this ); g_signal_connect( window, "destroy", G_CALLBACK( destroy ), NULL ); gtk_window_set_title( GTK_WINDOW( window ), "The Exo Lobe" ); gtk_window_set_default_size( GTK_WINDOW( window ), 800, 300 ); gtk_widget_show_all( window ); gtk_window_stick( GTK_WINDOW( window ) ); gtk_window_set_keep_above( GTK_WINDOW( window ), 1 ); searchEntryChanged( searchEntry, this ); gtk_key_snooper_install( keySnooper, window ); gtk_window_set_focus( GTK_WINDOW( window ), 0 ); globalBinding( GTK_WINDOW( window ) ); } KeyList::KeyList( ValueList *valueList ) { listStore = gtk_list_store_new( 2, G_TYPE_STRING, G_TYPE_STRING ); treeView = gtk_tree_view_new_with_model( GTK_TREE_MODEL( listStore ) ); nameRenderer = gtk_cell_renderer_text_new(); column = gtk_tree_view_column_new_with_attributes( "Keys", nameRenderer, "text", KEY_COLUMN, (void *)NULL ); gtk_tree_view_append_column( GTK_TREE_VIEW( treeView ), column ); g_object_unref( G_OBJECT( listStore ) ); select = gtk_tree_view_get_selection( GTK_TREE_VIEW ( treeView ) ); gtk_tree_selection_set_mode( select, GTK_SELECTION_SINGLE ); g_signal_connect( select, "changed", G_CALLBACK( KeyList::changed ), valueList ); } void KeyList::changed( GtkTreeSelection *selection, ValueList *valueList ) { GtkTreeIter iter; GtkTreeModel *model; //const char *key; if ( gtk_tree_selection_get_selected( selection, &model, &iter ) ) { /* gtk_tree_model_get( model, &iter, VALUE_COLUMN, &key, -1 ); GtkTextBuffer *buffer = gtk_text_view_get_buffer( textView ); gtk_text_buffer_set_text( buffer, key, -1 );*/ } } ValueList::ValueList() { vBox = gtk_vbox_new( FALSE, 3 ); //TODO gtk_text_view_set_wrap_mode( GTK_TEXT_VIEW( textView ), GTK_WRAP_WORD_CHAR ); } void Window::destroy( ) { gtk_main_quit (); } void Window::searchEntryChanged( GtkWidget *widget, Window *window ) { const char *text; GtkTreeIter iter; GtkListStore *keyStore = window->keyList->listStore; gtk_list_store_clear( keyStore ); text = gtk_entry_get_text( GTK_ENTRY( widget ) ); auto result = window->eldb.find( text ); if ( result->count ) { for ( auto key: result->keys ) { fprintf( stdout, "%s :\n", key->key.c_str() ); for ( auto value: key->values ) { fprintf( stdout, "\t%s\n", value->value.c_str() ); gtk_list_store_append( keyStore, &iter ); gtk_list_store_set( keyStore, &iter, KeyList::KEY_COLUMN , key->key.c_str(), KeyList::VALUE_COLUMN, value->value.c_str(), -1 ); } } } else { fprintf( stderr, "No Results\n" ); } } void Window::layout() { GtkWidget *table = gtk_table_new( 3, 3, FALSE ); GtkWidget *textViewScroller = gtk_scrolled_window_new( NULL, NULL ); GtkWidget *keyListScroller = gtk_scrolled_window_new( NULL, NULL ); gtk_container_set_border_width( GTK_CONTAINER( window ), 5 ); gtk_table_attach( GTK_TABLE( table ), searchEntry, 0, 3, 0, 1, GtkAttachOptions( GTK_EXPAND | GTK_FILL ), GTK_SHRINK, 0, 0 ); gtk_table_attach_defaults( GTK_TABLE( table ), keyListScroller, 0, 1, 1, 3 ); gtk_table_attach_defaults( GTK_TABLE( table ), textViewScroller, 1, 3, 1, 3 ); gtk_container_add( GTK_CONTAINER( keyListScroller ), keyList->treeView ); gtk_scrolled_window_add_with_viewport( GTK_SCROLLED_WINDOW( textViewScroller ), valueList->vBox ); gtk_table_set_row_spacings( GTK_TABLE( table ), 2 ); gtk_table_set_col_spacings( GTK_TABLE( table ), 2 ); gtk_container_add( GTK_CONTAINER( window ), table ); } int Window::keySnooper( GtkWidget *widget, GdkEventKey *event, gpointer data ) { if ( event->keyval == GDK_KEY_q && event->state & GDK_CONTROL_MASK ) { destroy( ); } if ( event->keyval == GDK_KEY_Escape ) { gtk_window_set_focus( GTK_WINDOW( data ), 0 ); } return 0; } } //namespace elgtk int main( int argc, char **argv ) { gtk_init( &argc, &argv ); elgtk::Window window; gtk_main(); return 0; } <|endoftext|>
<commit_before>#include "externaleditors.h" #include "qt4project.h" #include "qt4projectmanagerconstants.h" #include "qtversionmanager.h" #include <utils/synchronousprocess.h> #include <projectexplorer/projectexplorer.h> #include <projectexplorer/session.h> #include <designer/designerconstants.h> #include <QtCore/QProcess> #include <QtCore/QFileInfo> #include <QtCore/QDebug> #include <QtCore/QSignalMapper> #include <QtNetwork/QTcpSocket> #include <QtNetwork/QTcpServer> enum { debug = 0 }; namespace Qt4ProjectManager { namespace Internal { // Figure out the Qt4 project used by the file if any static Qt4Project *qt4ProjectFor(const QString &fileName) { ProjectExplorer::ProjectExplorerPlugin *pe = ProjectExplorer::ProjectExplorerPlugin::instance(); if (ProjectExplorer::Project *baseProject = pe->session()->projectForFile(fileName)) if (Qt4Project *project = qobject_cast<Qt4Project*>(baseProject)) return project; return 0; } // ------------ Messages static inline QString msgStartFailed(const QString &binary, QStringList arguments) { arguments.push_front(binary); return ExternalQtEditor::tr("Unable to start \"%1\"").arg(arguments.join(QString(QLatin1Char(' ')))); } static inline QString msgAppNotFound(const QString &kind) { return ExternalQtEditor::tr("The application \"%1\" could not be found.").arg(kind); } // -- Commands and helpers #ifdef Q_OS_MAC static const char *linguistBinaryC = "Linguist"; static const char *designerBinaryC = "Designer"; // Mac: Change the call 'Foo.app/Contents/MacOS/Foo <file>' to // 'open Foo.app <file>'. Do this ONLY if you do not want to have // command line arguments static void createMacOpenCommand(QString *binary, QStringList *arguments) { const int appFolderIndex = binary->lastIndexOf(QLatin1String("/Contents/MacOS/")); if (appFolderIndex != -1) { binary->truncate(appFolderIndex); arguments->push_front(*binary); *binary = QLatin1String("open"); } } #else static const char *linguistBinaryC = "linguist"; static const char *designerBinaryC = "designer"; #endif static const char *designerKindC = "Qt Designer"; // -------------- ExternalQtEditor ExternalQtEditor::ExternalQtEditor(const QString &kind, const QString &mimetype, QObject *parent) : Core::IExternalEditor(parent), m_mimeTypes(mimetype), m_kind(kind) { } QStringList ExternalQtEditor::mimeTypes() const { return m_mimeTypes; } QString ExternalQtEditor::kind() const { return m_kind; } bool ExternalQtEditor::getEditorLaunchData(const QString &fileName, QtVersionCommandAccessor commandAccessor, const QString &fallbackBinary, const QStringList &additionalArguments, bool useMacOpenCommand, EditorLaunchData *data, QString *errorMessage) const { const Qt4Project *project = qt4ProjectFor(fileName); // Get the binary either from the current Qt version of the project or Path if (project) { const QtVersion *qtVersion= project->qtVersion(project->activeBuildConfiguration()); data->binary = (qtVersion->*commandAccessor)(); data->workingDirectory = QFileInfo(project->file()->fileName()).absolutePath(); } else { data->workingDirectory.clear(); data->binary = Core::Utils::SynchronousProcess::locateBinary(fallbackBinary); } if (data->binary.isEmpty()) { *errorMessage = msgAppNotFound(kind()); return false; } // Setup binary + arguments, use Mac Open if appropriate data->arguments = additionalArguments; data->arguments.push_back(fileName); #ifdef Q_OS_MAC if (useMacOpenCommand) createMacOpenCommand(&binary, &(data->arguments)); #else Q_UNUSED(useMacOpenCommand) #endif if (debug) qDebug() << Q_FUNC_INFO << '\n' << data->binary << data->arguments; return true; } bool ExternalQtEditor::startEditorProcess(const EditorLaunchData &data, QString *errorMessage) { if (debug) qDebug() << Q_FUNC_INFO << '\n' << data.binary << data.arguments << data.workingDirectory; qint64 pid = 0; if (!QProcess::startDetached(data.binary, data.arguments, data.workingDirectory, &pid)) { *errorMessage = msgStartFailed(data.binary, data.arguments); return false; } return true; } // --------------- LinguistExternalEditor LinguistExternalEditor::LinguistExternalEditor(QObject *parent) : ExternalQtEditor(QLatin1String("Qt Linguist"), QLatin1String(Qt4ProjectManager::Constants::LINGUIST_MIMETYPE), parent) { } bool LinguistExternalEditor::startEditor(const QString &fileName, QString *errorMessage) { EditorLaunchData data; return getEditorLaunchData(fileName, &QtVersion::linguistCommand, QLatin1String(linguistBinaryC), QStringList(), true, &data, errorMessage) && startEditorProcess(data, errorMessage); } // --------------- MacDesignerExternalEditor, using Mac 'open' MacDesignerExternalEditor::MacDesignerExternalEditor(QObject *parent) : ExternalQtEditor(QLatin1String(designerKindC), QLatin1String(Qt4ProjectManager::Constants::FORM_MIMETYPE), parent) { } bool MacDesignerExternalEditor::startEditor(const QString &fileName, QString *errorMessage) { EditorLaunchData data; return getEditorLaunchData(fileName, &QtVersion::designerCommand, QLatin1String(designerBinaryC), QStringList(), true, &data, errorMessage) && startEditorProcess(data, errorMessage); return false; } // --------------- DesignerExternalEditor with Designer Tcp remote control. DesignerExternalEditor::DesignerExternalEditor(QObject *parent) : ExternalQtEditor(QLatin1String(designerKindC), QLatin1String(Designer::Constants::FORM_MIMETYPE), parent), m_terminationMapper(0) { } void DesignerExternalEditor::processTerminated(const QString &binary) { const ProcessCache::iterator it = m_processCache.find(binary); if (it == m_processCache.end()) return; // Make sure socket is closed and cleaned, remove from cache QTcpSocket *socket = it.value(); m_processCache.erase(it); // Note that closing will cause the slot to be retriggered if (debug) qDebug() << Q_FUNC_INFO << '\n' << binary << socket->state(); if (socket->state() == QAbstractSocket::ConnectedState) socket->close(); socket->deleteLater(); } bool DesignerExternalEditor::startEditor(const QString &fileName, QString *errorMessage) { EditorLaunchData data; // Find the editor binary if (!getEditorLaunchData(fileName, &QtVersion::designerCommand, QLatin1String(designerBinaryC), QStringList(), false, &data, errorMessage)) { return false; } // Known one? const ProcessCache::iterator it = m_processCache.find(data.binary); if (it != m_processCache.end()) { // Process is known, write to its socket to cause it to open the file if (debug) qDebug() << Q_FUNC_INFO << "\nWriting to socket:" << data.binary << fileName; QTcpSocket *socket = it.value(); if (!socket->write(fileName.toUtf8() + '\n')) { *errorMessage = tr("Qt Designer is not responding (%1).").arg(socket->errorString()); return false; } return true; } // No process yet. Create socket & launch the process QTcpServer server; if (!server.listen(QHostAddress::LocalHost)) { *errorMessage = tr("Unable to create server socket: %1").arg(server.errorString()); return false; } const quint16 port = server.serverPort(); if (debug) qDebug() << Q_FUNC_INFO << "\nLaunching server:" << port << data.binary << fileName; // Start first one with file and socket as '-client port file' // Wait for the socket listening data.arguments.push_front(QString::number(port)); data.arguments.push_front(QLatin1String("-client")); if (!startEditorProcess(data, errorMessage)) return false; // Set up signal mapper to track process termination via socket if (!m_terminationMapper) { m_terminationMapper = new QSignalMapper(this); connect(m_terminationMapper, SIGNAL(mapped(QString)), this, SLOT(processTerminated(QString))); } // Insert into cache if socket is created, else try again next time if (server.waitForNewConnection(3000)) { QTcpSocket *socket = server.nextPendingConnection(); socket->setParent(this); m_processCache.insert(data.binary, socket); m_terminationMapper->setMapping(socket, data.binary); connect(socket, SIGNAL(disconnected()), m_terminationMapper, SLOT(map())); connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), m_terminationMapper, SLOT(map())); } return true; } } // namespace Internal } // namespace Qt4ProjectManager <commit_msg>Fixed Mac compilation.<commit_after>#include "externaleditors.h" #include "qt4project.h" #include "qt4projectmanagerconstants.h" #include "qtversionmanager.h" #include <utils/synchronousprocess.h> #include <projectexplorer/projectexplorer.h> #include <projectexplorer/session.h> #include <designer/designerconstants.h> #include <QtCore/QProcess> #include <QtCore/QFileInfo> #include <QtCore/QDebug> #include <QtCore/QSignalMapper> #include <QtNetwork/QTcpSocket> #include <QtNetwork/QTcpServer> enum { debug = 0 }; namespace Qt4ProjectManager { namespace Internal { // Figure out the Qt4 project used by the file if any static Qt4Project *qt4ProjectFor(const QString &fileName) { ProjectExplorer::ProjectExplorerPlugin *pe = ProjectExplorer::ProjectExplorerPlugin::instance(); if (ProjectExplorer::Project *baseProject = pe->session()->projectForFile(fileName)) if (Qt4Project *project = qobject_cast<Qt4Project*>(baseProject)) return project; return 0; } // ------------ Messages static inline QString msgStartFailed(const QString &binary, QStringList arguments) { arguments.push_front(binary); return ExternalQtEditor::tr("Unable to start \"%1\"").arg(arguments.join(QString(QLatin1Char(' ')))); } static inline QString msgAppNotFound(const QString &kind) { return ExternalQtEditor::tr("The application \"%1\" could not be found.").arg(kind); } // -- Commands and helpers #ifdef Q_OS_MAC static const char *linguistBinaryC = "Linguist"; static const char *designerBinaryC = "Designer"; // Mac: Change the call 'Foo.app/Contents/MacOS/Foo <file>' to // 'open Foo.app <file>'. Do this ONLY if you do not want to have // command line arguments static void createMacOpenCommand(QString *binary, QStringList *arguments) { const int appFolderIndex = binary->lastIndexOf(QLatin1String("/Contents/MacOS/")); if (appFolderIndex != -1) { binary->truncate(appFolderIndex); arguments->push_front(*binary); *binary = QLatin1String("open"); } } #else static const char *linguistBinaryC = "linguist"; static const char *designerBinaryC = "designer"; #endif static const char *designerKindC = "Qt Designer"; // -------------- ExternalQtEditor ExternalQtEditor::ExternalQtEditor(const QString &kind, const QString &mimetype, QObject *parent) : Core::IExternalEditor(parent), m_mimeTypes(mimetype), m_kind(kind) { } QStringList ExternalQtEditor::mimeTypes() const { return m_mimeTypes; } QString ExternalQtEditor::kind() const { return m_kind; } bool ExternalQtEditor::getEditorLaunchData(const QString &fileName, QtVersionCommandAccessor commandAccessor, const QString &fallbackBinary, const QStringList &additionalArguments, bool useMacOpenCommand, EditorLaunchData *data, QString *errorMessage) const { const Qt4Project *project = qt4ProjectFor(fileName); // Get the binary either from the current Qt version of the project or Path if (project) { const QtVersion *qtVersion= project->qtVersion(project->activeBuildConfiguration()); data->binary = (qtVersion->*commandAccessor)(); data->workingDirectory = QFileInfo(project->file()->fileName()).absolutePath(); } else { data->workingDirectory.clear(); data->binary = Core::Utils::SynchronousProcess::locateBinary(fallbackBinary); } if (data->binary.isEmpty()) { *errorMessage = msgAppNotFound(kind()); return false; } // Setup binary + arguments, use Mac Open if appropriate data->arguments = additionalArguments; data->arguments.push_back(fileName); #ifdef Q_OS_MAC if (useMacOpenCommand) createMacOpenCommand(&(data->binary), &(data->arguments)); #else Q_UNUSED(useMacOpenCommand) #endif if (debug) qDebug() << Q_FUNC_INFO << '\n' << data->binary << data->arguments; return true; } bool ExternalQtEditor::startEditorProcess(const EditorLaunchData &data, QString *errorMessage) { if (debug) qDebug() << Q_FUNC_INFO << '\n' << data.binary << data.arguments << data.workingDirectory; qint64 pid = 0; if (!QProcess::startDetached(data.binary, data.arguments, data.workingDirectory, &pid)) { *errorMessage = msgStartFailed(data.binary, data.arguments); return false; } return true; } // --------------- LinguistExternalEditor LinguistExternalEditor::LinguistExternalEditor(QObject *parent) : ExternalQtEditor(QLatin1String("Qt Linguist"), QLatin1String(Qt4ProjectManager::Constants::LINGUIST_MIMETYPE), parent) { } bool LinguistExternalEditor::startEditor(const QString &fileName, QString *errorMessage) { EditorLaunchData data; return getEditorLaunchData(fileName, &QtVersion::linguistCommand, QLatin1String(linguistBinaryC), QStringList(), true, &data, errorMessage) && startEditorProcess(data, errorMessage); } // --------------- MacDesignerExternalEditor, using Mac 'open' MacDesignerExternalEditor::MacDesignerExternalEditor(QObject *parent) : ExternalQtEditor(QLatin1String(designerKindC), QLatin1String(Qt4ProjectManager::Constants::FORM_MIMETYPE), parent) { } bool MacDesignerExternalEditor::startEditor(const QString &fileName, QString *errorMessage) { EditorLaunchData data; return getEditorLaunchData(fileName, &QtVersion::designerCommand, QLatin1String(designerBinaryC), QStringList(), true, &data, errorMessage) && startEditorProcess(data, errorMessage); return false; } // --------------- DesignerExternalEditor with Designer Tcp remote control. DesignerExternalEditor::DesignerExternalEditor(QObject *parent) : ExternalQtEditor(QLatin1String(designerKindC), QLatin1String(Designer::Constants::FORM_MIMETYPE), parent), m_terminationMapper(0) { } void DesignerExternalEditor::processTerminated(const QString &binary) { const ProcessCache::iterator it = m_processCache.find(binary); if (it == m_processCache.end()) return; // Make sure socket is closed and cleaned, remove from cache QTcpSocket *socket = it.value(); m_processCache.erase(it); // Note that closing will cause the slot to be retriggered if (debug) qDebug() << Q_FUNC_INFO << '\n' << binary << socket->state(); if (socket->state() == QAbstractSocket::ConnectedState) socket->close(); socket->deleteLater(); } bool DesignerExternalEditor::startEditor(const QString &fileName, QString *errorMessage) { EditorLaunchData data; // Find the editor binary if (!getEditorLaunchData(fileName, &QtVersion::designerCommand, QLatin1String(designerBinaryC), QStringList(), false, &data, errorMessage)) { return false; } // Known one? const ProcessCache::iterator it = m_processCache.find(data.binary); if (it != m_processCache.end()) { // Process is known, write to its socket to cause it to open the file if (debug) qDebug() << Q_FUNC_INFO << "\nWriting to socket:" << data.binary << fileName; QTcpSocket *socket = it.value(); if (!socket->write(fileName.toUtf8() + '\n')) { *errorMessage = tr("Qt Designer is not responding (%1).").arg(socket->errorString()); return false; } return true; } // No process yet. Create socket & launch the process QTcpServer server; if (!server.listen(QHostAddress::LocalHost)) { *errorMessage = tr("Unable to create server socket: %1").arg(server.errorString()); return false; } const quint16 port = server.serverPort(); if (debug) qDebug() << Q_FUNC_INFO << "\nLaunching server:" << port << data.binary << fileName; // Start first one with file and socket as '-client port file' // Wait for the socket listening data.arguments.push_front(QString::number(port)); data.arguments.push_front(QLatin1String("-client")); if (!startEditorProcess(data, errorMessage)) return false; // Set up signal mapper to track process termination via socket if (!m_terminationMapper) { m_terminationMapper = new QSignalMapper(this); connect(m_terminationMapper, SIGNAL(mapped(QString)), this, SLOT(processTerminated(QString))); } // Insert into cache if socket is created, else try again next time if (server.waitForNewConnection(3000)) { QTcpSocket *socket = server.nextPendingConnection(); socket->setParent(this); m_processCache.insert(data.binary, socket); m_terminationMapper->setMapping(socket, data.binary); connect(socket, SIGNAL(disconnected()), m_terminationMapper, SLOT(map())); connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), m_terminationMapper, SLOT(map())); } return true; } } // namespace Internal } // namespace Qt4ProjectManager <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #include <algorithm> #include <iterator> #ifndef INCLUDED_DOCTOK_EXCEPTIONS #include <resourcemodel/exceptions.hxx> #endif #include <WW8PieceTableImpl.hxx> #include <WW8Clx.hxx> namespace writerfilter { namespace doctok { using namespace ::std; ostream & operator << (ostream & o, const WW8PieceTable & rPieceTable) { rPieceTable.dump(o); return o; } WW8PieceTableImpl::WW8PieceTableImpl(WW8Stream & rStream, sal_uInt32 nOffset, sal_uInt32 nCount) { WW8Clx aClx(rStream, nOffset, nCount); sal_uInt32 nPieceCount = aClx.getPieceCount(); if (nPieceCount > 0) { for (sal_uInt32 n = 0; n < nPieceCount; n++) { Cp aCp(aClx.getCp(n)); Fc aFc(aClx.getFc(n), aClx.isComplexFc(n)); CpAndFc aCpAndFc(aCp, aFc, PROP_DOC); mEntries.push_back(aCpAndFc); } CpAndFc aBack = mEntries.back(); Cp aCp(aClx.getCp(aClx.getPieceCount())); Fc aFc(aBack.getFc() + (aCp - aBack.getCp())); CpAndFc aCpAndFc(aCp, aFc, PROP_DOC); mEntries.push_back(aCpAndFc); } } sal_uInt32 WW8PieceTableImpl::getCount() const { return mEntries.size(); } WW8PieceTableImpl::tEntries::const_iterator WW8PieceTableImpl::findCp(const Cp & rCp) const { tEntries::const_iterator aResult = mEntries.end(); tEntries::const_iterator aEnd = mEntries.end(); for (tEntries::const_iterator aIt = mEntries.begin(); aIt != aEnd; aIt++) { if (aIt->getCp() <= rCp) { aResult = aIt; //break; } } return aResult; } WW8PieceTableImpl::tEntries::const_iterator WW8PieceTableImpl::findFc(const Fc & rFc) const { tEntries::const_iterator aResult = mEntries.end(); tEntries::const_iterator aEnd = mEntries.end(); if (mEntries.size() > 0) { if (rFc < mEntries.begin()->getFc()) aResult = mEntries.begin(); else { for (tEntries::const_iterator aIt = mEntries.begin(); aIt != aEnd; aIt++) { if (aIt->getFc() <= rFc) { tEntries::const_iterator aItNext = aIt; aItNext++; if (aItNext != aEnd) { sal_uInt32 nOffset = rFc.get() - aIt->getFc().get(); sal_uInt32 nLength = aItNext->getCp() - aIt->getCp(); if (! aIt->isComplex()) nLength *= 2; if (nOffset < nLength) { aResult = aIt; break; } } } } } } return aResult; } Cp WW8PieceTableImpl::getFirstCp() const { Cp aResult; if (getCount() > 0) aResult = getCp(0); else throw ExceptionNotFound("WW8PieceTableImpl::getFirstCp"); return aResult; } Fc WW8PieceTableImpl::getFirstFc() const { Fc aResult; if (getCount() > 0) aResult = getFc(0); else throw ExceptionNotFound(" WW8PieceTableImpl::getFirstFc"); return aResult; } Cp WW8PieceTableImpl::getLastCp() const { Cp aResult; if (getCount() > 0) aResult = getCp(getCount() - 1); else throw ExceptionNotFound("WW8PieceTableImpl::getLastCp"); return aResult; } Fc WW8PieceTableImpl::getLastFc() const { Fc aResult; if (getCount() > 0) aResult = getFc(getCount() - 1); else throw ExceptionNotFound("WW8PieceTableImpl::getLastFc"); return aResult; } Cp WW8PieceTableImpl::getCp(sal_uInt32 nIndex) const { return mEntries[nIndex].getCp(); } Fc WW8PieceTableImpl::getFc(sal_uInt32 nIndex) const { return mEntries[nIndex].getFc(); } Cp WW8PieceTableImpl::fc2cp(const Fc & rFc) const { Cp cpResult; if (mEntries.size() > 0) { Fc aFc; if (rFc < mEntries.begin()->getFc()) aFc = mEntries.begin()->getFc(); else aFc = rFc; tEntries::const_iterator aIt = findFc(aFc); if (aIt != mEntries.end()) { cpResult = aIt->getCp() + (aFc - aIt->getFc()); } else throw ExceptionNotFound("WW8PieceTableImpl::fc2cp: " + aFc.toString()); } return cpResult; } Fc WW8PieceTableImpl::cp2fc(const Cp & rCp) const { Fc aResult; Cp2FcHashMap_t::iterator aItCp = mCp2FcCache.find(rCp); if (aItCp == mCp2FcCache.end()) { tEntries::const_iterator aIt = findCp(rCp); if (aIt != mEntries.end()) { aResult = aIt->getFc() + (rCp - aIt->getCp()); mCp2FcCache[rCp] = aResult; } else throw ExceptionNotFound ("WW8PieceTableImpl::cp2fc: " + rCp.toString()); } else aResult = mCp2FcCache[rCp]; return aResult; } bool WW8PieceTableImpl::isComplex(const Cp & rCp) const { bool bResult = false; tEntries::const_iterator aIt = findCp(rCp); if (aIt != mEntries.end()) bResult = aIt->isComplex(); return bResult; } bool WW8PieceTableImpl::isComplex(const Fc & rFc) const { bool bResult = false; tEntries::const_iterator aIt = findFc(rFc); if (aIt != mEntries.end()) bResult = aIt->isComplex(); return bResult; } CpAndFc WW8PieceTableImpl::createCpAndFc (const Cp & rCp, PropertyType eType) const { return CpAndFc(rCp, cp2fc(rCp), eType); } CpAndFc WW8PieceTableImpl::createCpAndFc (const Fc & rFc, PropertyType eType) const { return CpAndFc(fc2cp(rFc), rFc, eType); } void WW8PieceTableImpl::dump(ostream & o) const { o << "<piecetable>" << endl; copy(mEntries.begin(), mEntries.end(), ostream_iterator<CpAndFc>(o, "\n")); o << "</piecetable>" << endl; } }} /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>cppcheck: prefer prefix variant<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #include <algorithm> #include <iterator> #ifndef INCLUDED_DOCTOK_EXCEPTIONS #include <resourcemodel/exceptions.hxx> #endif #include <WW8PieceTableImpl.hxx> #include <WW8Clx.hxx> namespace writerfilter { namespace doctok { using namespace ::std; ostream & operator << (ostream & o, const WW8PieceTable & rPieceTable) { rPieceTable.dump(o); return o; } WW8PieceTableImpl::WW8PieceTableImpl(WW8Stream & rStream, sal_uInt32 nOffset, sal_uInt32 nCount) { WW8Clx aClx(rStream, nOffset, nCount); sal_uInt32 nPieceCount = aClx.getPieceCount(); if (nPieceCount > 0) { for (sal_uInt32 n = 0; n < nPieceCount; n++) { Cp aCp(aClx.getCp(n)); Fc aFc(aClx.getFc(n), aClx.isComplexFc(n)); CpAndFc aCpAndFc(aCp, aFc, PROP_DOC); mEntries.push_back(aCpAndFc); } CpAndFc aBack = mEntries.back(); Cp aCp(aClx.getCp(aClx.getPieceCount())); Fc aFc(aBack.getFc() + (aCp - aBack.getCp())); CpAndFc aCpAndFc(aCp, aFc, PROP_DOC); mEntries.push_back(aCpAndFc); } } sal_uInt32 WW8PieceTableImpl::getCount() const { return mEntries.size(); } WW8PieceTableImpl::tEntries::const_iterator WW8PieceTableImpl::findCp(const Cp & rCp) const { tEntries::const_iterator aResult = mEntries.end(); tEntries::const_iterator aEnd = mEntries.end(); for (tEntries::const_iterator aIt = mEntries.begin(); aIt != aEnd; ++aIt) { if (aIt->getCp() <= rCp) { aResult = aIt; //break; } } return aResult; } WW8PieceTableImpl::tEntries::const_iterator WW8PieceTableImpl::findFc(const Fc & rFc) const { tEntries::const_iterator aResult = mEntries.end(); tEntries::const_iterator aEnd = mEntries.end(); if (mEntries.size() > 0) { if (rFc < mEntries.begin()->getFc()) aResult = mEntries.begin(); else { for (tEntries::const_iterator aIt = mEntries.begin(); aIt != aEnd; ++aIt) { if (aIt->getFc() <= rFc) { tEntries::const_iterator aItNext = aIt; ++aItNext; if (aItNext != aEnd) { sal_uInt32 nOffset = rFc.get() - aIt->getFc().get(); sal_uInt32 nLength = aItNext->getCp() - aIt->getCp(); if (! aIt->isComplex()) nLength *= 2; if (nOffset < nLength) { aResult = aIt; break; } } } } } } return aResult; } Cp WW8PieceTableImpl::getFirstCp() const { Cp aResult; if (getCount() > 0) aResult = getCp(0); else throw ExceptionNotFound("WW8PieceTableImpl::getFirstCp"); return aResult; } Fc WW8PieceTableImpl::getFirstFc() const { Fc aResult; if (getCount() > 0) aResult = getFc(0); else throw ExceptionNotFound(" WW8PieceTableImpl::getFirstFc"); return aResult; } Cp WW8PieceTableImpl::getLastCp() const { Cp aResult; if (getCount() > 0) aResult = getCp(getCount() - 1); else throw ExceptionNotFound("WW8PieceTableImpl::getLastCp"); return aResult; } Fc WW8PieceTableImpl::getLastFc() const { Fc aResult; if (getCount() > 0) aResult = getFc(getCount() - 1); else throw ExceptionNotFound("WW8PieceTableImpl::getLastFc"); return aResult; } Cp WW8PieceTableImpl::getCp(sal_uInt32 nIndex) const { return mEntries[nIndex].getCp(); } Fc WW8PieceTableImpl::getFc(sal_uInt32 nIndex) const { return mEntries[nIndex].getFc(); } Cp WW8PieceTableImpl::fc2cp(const Fc & rFc) const { Cp cpResult; if (mEntries.size() > 0) { Fc aFc; if (rFc < mEntries.begin()->getFc()) aFc = mEntries.begin()->getFc(); else aFc = rFc; tEntries::const_iterator aIt = findFc(aFc); if (aIt != mEntries.end()) { cpResult = aIt->getCp() + (aFc - aIt->getFc()); } else throw ExceptionNotFound("WW8PieceTableImpl::fc2cp: " + aFc.toString()); } return cpResult; } Fc WW8PieceTableImpl::cp2fc(const Cp & rCp) const { Fc aResult; Cp2FcHashMap_t::iterator aItCp = mCp2FcCache.find(rCp); if (aItCp == mCp2FcCache.end()) { tEntries::const_iterator aIt = findCp(rCp); if (aIt != mEntries.end()) { aResult = aIt->getFc() + (rCp - aIt->getCp()); mCp2FcCache[rCp] = aResult; } else throw ExceptionNotFound ("WW8PieceTableImpl::cp2fc: " + rCp.toString()); } else aResult = mCp2FcCache[rCp]; return aResult; } bool WW8PieceTableImpl::isComplex(const Cp & rCp) const { bool bResult = false; tEntries::const_iterator aIt = findCp(rCp); if (aIt != mEntries.end()) bResult = aIt->isComplex(); return bResult; } bool WW8PieceTableImpl::isComplex(const Fc & rFc) const { bool bResult = false; tEntries::const_iterator aIt = findFc(rFc); if (aIt != mEntries.end()) bResult = aIt->isComplex(); return bResult; } CpAndFc WW8PieceTableImpl::createCpAndFc (const Cp & rCp, PropertyType eType) const { return CpAndFc(rCp, cp2fc(rCp), eType); } CpAndFc WW8PieceTableImpl::createCpAndFc (const Fc & rFc, PropertyType eType) const { return CpAndFc(fc2cp(rFc), rFc, eType); } void WW8PieceTableImpl::dump(ostream & o) const { o << "<piecetable>" << endl; copy(mEntries.begin(), mEntries.end(), ostream_iterator<CpAndFc>(o, "\n")); o << "</piecetable>" << endl; } }} /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/* This file is part of the Vc library. {{{ Copyright (C) 2013 Matthias Kretz <[email protected]> Vc is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Vc 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 Vc. If not, see <http://www.gnu.org/licenses/>. }}}*/ #include "macros.h" Vc_NAMESPACE_BEGIN(Vc_IMPL_NAMESPACE) namespace internal { // mask_cast/*{{{*/ template<size_t From, size_t To> Vc_ALWAYS_INLINE Vc_CONST __m128i mask_cast(__m128i k) { static_assert(From == To, "Incorrect mask cast."); return k; } template<> Vc_ALWAYS_INLINE Vc_CONST __m128i mask_cast<2, 4>(__m128i k) { return _mm_packs_epi16(k, _mm_setzero_si128()); } template<> Vc_ALWAYS_INLINE Vc_CONST __m128i mask_cast<2, 8>(__m128i k) { auto tmp = _mm_packs_epi16(k, k); return _mm_packs_epi16(tmp, tmp); } template<> Vc_ALWAYS_INLINE Vc_CONST __m128i mask_cast<4, 2>(__m128i k) { return _mm_unpacklo_epi32(k, k); } template<> Vc_ALWAYS_INLINE Vc_CONST __m128i mask_cast<4, 8>(__m128i k) { return _mm_packs_epi16(k, k); } template<> Vc_ALWAYS_INLINE Vc_CONST __m128i mask_cast<8, 2>(__m128i k) { auto tmp = _mm_unpacklo_epi16(k, k); return _mm_unpacklo_epi32(tmp, tmp); } template<> Vc_ALWAYS_INLINE Vc_CONST __m128i mask_cast<8, 4>(__m128i k) { return _mm_unpacklo_epi16(k, k); } template<> Vc_ALWAYS_INLINE Vc_CONST __m128i mask_cast<16, 8>(__m128i k) { return _mm_unpacklo_epi8(k, k); } template<> Vc_ALWAYS_INLINE Vc_CONST __m128i mask_cast<16, 4>(__m128i k) { auto tmp = mask_cast<16, 8>(k); return _mm_unpacklo_epi16(tmp, tmp); } template<> Vc_ALWAYS_INLINE Vc_CONST __m128i mask_cast<16, 2>(__m128i k) { auto tmp = mask_cast<16, 4>(k); return _mm_unpacklo_epi32(tmp, tmp); } /*}}}*/ // mask_to_int/*{{{*/ template<> Vc_ALWAYS_INLINE Vc_CONST int mask_to_int<2>(__m128i k) { return _mm_movemask_pd(_mm_castsi128_pd(k)); } template<> Vc_ALWAYS_INLINE Vc_CONST int mask_to_int<4>(__m128i k) { return _mm_movemask_ps(_mm_castsi128_ps(k)); } template<> Vc_ALWAYS_INLINE Vc_CONST int mask_to_int<8>(__m128i k) { return _mm_movemask_epi8(_mm_packs_epi16(k, _mm_setzero_si128())); } template<> Vc_ALWAYS_INLINE Vc_CONST int mask_to_int<16>(__m128i k) { return _mm_movemask_epi8(k); } /*}}}*/ /*mask_count{{{*/ template<> Vc_ALWAYS_INLINE Vc_CONST int mask_count<2>(__m128i k) { int mask = _mm_movemask_pd(_mm_castsi128_pd(k)); return (mask & 1) + (mask >> 1); } template<> Vc_ALWAYS_INLINE Vc_CONST int mask_count<4>(__m128i k) { #ifdef VC_IMPL_POPCNT return _mm_popcnt_u32(_mm_movemask_ps(_mm_castsi128_ps(k))); //X tmp = (tmp & 5) + ((tmp >> 1) & 5); //X return (tmp & 3) + ((tmp >> 2) & 3); #else auto x = _mm_srli_epi32(k, 31); x = _mm_add_epi32(x, _mm_shuffle_epi32(x, _MM_SHUFFLE(0, 1, 2, 3))); x = _mm_add_epi32(x, _mm_shufflelo_epi16(x, _MM_SHUFFLE(1, 0, 3, 2))); return _mm_cvtsi128_si32(x); #endif } template<> Vc_ALWAYS_INLINE Vc_CONST int mask_count<8>(__m128i k) { #ifdef VC_IMPL_POPCNT return _mm_popcnt_u32(_mm_movemask_epi8(k)) / 2; #else //X int tmp = _mm_movemask_epi8(dataI()); //X tmp = (tmp & 0x1111) + ((tmp >> 2) & 0x1111); //X tmp = (tmp & 0x0303) + ((tmp >> 4) & 0x0303); //X return (tmp & 0x000f) + ((tmp >> 8) & 0x000f); auto x = _mm_srli_epi16(k, 15); x = _mm_add_epi16(x, _mm_shuffle_epi32(x, _MM_SHUFFLE(0, 1, 2, 3))); x = _mm_add_epi16(x, _mm_shufflelo_epi16(x, _MM_SHUFFLE(0, 1, 2, 3))); x = _mm_add_epi16(x, _mm_shufflelo_epi16(x, _MM_SHUFFLE(2, 3, 0, 1))); return _mm_extract_epi16(x, 0); #endif } template<> Vc_ALWAYS_INLINE Vc_CONST int mask_count<16>(__m128i k) { int tmp = _mm_movemask_epi8(k); #ifdef VC_IMPL_POPCNT return _mm_popcnt_u32(tmp); #else tmp = (tmp & 0x5555) + ((tmp >> 1) & 0x5555); tmp = (tmp & 0x3333) + ((tmp >> 2) & 0x3333); tmp = (tmp & 0x0f0f) + ((tmp >> 4) & 0x0f0f); return (tmp & 0x00ff) + ((tmp >> 8) & 0x00ff); #endif } /*}}}*/ } // namespace internal template<> Vc_ALWAYS_INLINE Vc_PURE bool Mask< int16_t>::operator[](size_t index) const { return shiftMask() & (1 << 2 * index); } template<> Vc_ALWAYS_INLINE Vc_PURE bool Mask<uint16_t>::operator[](size_t index) const { return shiftMask() & (1 << 2 * index); } template<typename T> Vc_ALWAYS_INLINE Vc_PURE int Mask<T>::firstOne() const { const int mask = toInt(); #ifdef _MSC_VER unsigned long bit; _BitScanForward(&bit, mask); #else int bit; __asm__("bsf %1,%0" : "=&r"(bit) : "r"(mask)); #endif return bit; } /*operators{{{*/ /*}}}*/ Vc_NAMESPACE_END #include "undomacros.h" // vim: foldmethod=marker <commit_msg>fix some mask conversions to fill with zeros<commit_after>/* This file is part of the Vc library. {{{ Copyright (C) 2013 Matthias Kretz <[email protected]> Vc is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Vc 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 Vc. If not, see <http://www.gnu.org/licenses/>. }}}*/ #include "macros.h" Vc_NAMESPACE_BEGIN(Vc_IMPL_NAMESPACE) namespace internal { // mask_cast/*{{{*/ template<size_t From, size_t To> Vc_ALWAYS_INLINE Vc_CONST __m128i mask_cast(__m128i k) { static_assert(From == To, "Incorrect mask cast."); return k; } template<> Vc_ALWAYS_INLINE Vc_CONST __m128i mask_cast<2, 4>(__m128i k) { return _mm_packs_epi16(k, _mm_setzero_si128()); } template<> Vc_ALWAYS_INLINE Vc_CONST __m128i mask_cast<2, 8>(__m128i k) { auto tmp = _mm_packs_epi16(k, _mm_setzero_si128()); return _mm_packs_epi16(tmp, _mm_setzero_si128()); } template<> Vc_ALWAYS_INLINE Vc_CONST __m128i mask_cast<4, 2>(__m128i k) { return _mm_unpacklo_epi32(k, k); } template<> Vc_ALWAYS_INLINE Vc_CONST __m128i mask_cast<4, 8>(__m128i k) { return _mm_packs_epi16(k, _mm_setzero_si128()); } template<> Vc_ALWAYS_INLINE Vc_CONST __m128i mask_cast<8, 2>(__m128i k) { auto tmp = _mm_unpacklo_epi16(k, k); return _mm_unpacklo_epi32(tmp, tmp); } template<> Vc_ALWAYS_INLINE Vc_CONST __m128i mask_cast<8, 4>(__m128i k) { return _mm_unpacklo_epi16(k, k); } template<> Vc_ALWAYS_INLINE Vc_CONST __m128i mask_cast<16, 8>(__m128i k) { return _mm_unpacklo_epi8(k, k); } template<> Vc_ALWAYS_INLINE Vc_CONST __m128i mask_cast<16, 4>(__m128i k) { auto tmp = mask_cast<16, 8>(k); return _mm_unpacklo_epi16(tmp, tmp); } template<> Vc_ALWAYS_INLINE Vc_CONST __m128i mask_cast<16, 2>(__m128i k) { auto tmp = mask_cast<16, 4>(k); return _mm_unpacklo_epi32(tmp, tmp); } /*}}}*/ // mask_to_int/*{{{*/ template<> Vc_ALWAYS_INLINE Vc_CONST int mask_to_int<2>(__m128i k) { return _mm_movemask_pd(_mm_castsi128_pd(k)); } template<> Vc_ALWAYS_INLINE Vc_CONST int mask_to_int<4>(__m128i k) { return _mm_movemask_ps(_mm_castsi128_ps(k)); } template<> Vc_ALWAYS_INLINE Vc_CONST int mask_to_int<8>(__m128i k) { return _mm_movemask_epi8(_mm_packs_epi16(k, _mm_setzero_si128())); } template<> Vc_ALWAYS_INLINE Vc_CONST int mask_to_int<16>(__m128i k) { return _mm_movemask_epi8(k); } /*}}}*/ /*mask_count{{{*/ template<> Vc_ALWAYS_INLINE Vc_CONST int mask_count<2>(__m128i k) { int mask = _mm_movemask_pd(_mm_castsi128_pd(k)); return (mask & 1) + (mask >> 1); } template<> Vc_ALWAYS_INLINE Vc_CONST int mask_count<4>(__m128i k) { #ifdef VC_IMPL_POPCNT return _mm_popcnt_u32(_mm_movemask_ps(_mm_castsi128_ps(k))); //X tmp = (tmp & 5) + ((tmp >> 1) & 5); //X return (tmp & 3) + ((tmp >> 2) & 3); #else auto x = _mm_srli_epi32(k, 31); x = _mm_add_epi32(x, _mm_shuffle_epi32(x, _MM_SHUFFLE(0, 1, 2, 3))); x = _mm_add_epi32(x, _mm_shufflelo_epi16(x, _MM_SHUFFLE(1, 0, 3, 2))); return _mm_cvtsi128_si32(x); #endif } template<> Vc_ALWAYS_INLINE Vc_CONST int mask_count<8>(__m128i k) { #ifdef VC_IMPL_POPCNT return _mm_popcnt_u32(_mm_movemask_epi8(k)) / 2; #else //X int tmp = _mm_movemask_epi8(dataI()); //X tmp = (tmp & 0x1111) + ((tmp >> 2) & 0x1111); //X tmp = (tmp & 0x0303) + ((tmp >> 4) & 0x0303); //X return (tmp & 0x000f) + ((tmp >> 8) & 0x000f); auto x = _mm_srli_epi16(k, 15); x = _mm_add_epi16(x, _mm_shuffle_epi32(x, _MM_SHUFFLE(0, 1, 2, 3))); x = _mm_add_epi16(x, _mm_shufflelo_epi16(x, _MM_SHUFFLE(0, 1, 2, 3))); x = _mm_add_epi16(x, _mm_shufflelo_epi16(x, _MM_SHUFFLE(2, 3, 0, 1))); return _mm_extract_epi16(x, 0); #endif } template<> Vc_ALWAYS_INLINE Vc_CONST int mask_count<16>(__m128i k) { int tmp = _mm_movemask_epi8(k); #ifdef VC_IMPL_POPCNT return _mm_popcnt_u32(tmp); #else tmp = (tmp & 0x5555) + ((tmp >> 1) & 0x5555); tmp = (tmp & 0x3333) + ((tmp >> 2) & 0x3333); tmp = (tmp & 0x0f0f) + ((tmp >> 4) & 0x0f0f); return (tmp & 0x00ff) + ((tmp >> 8) & 0x00ff); #endif } /*}}}*/ } // namespace internal template<> Vc_ALWAYS_INLINE Vc_PURE bool Mask< int16_t>::operator[](size_t index) const { return shiftMask() & (1 << 2 * index); } template<> Vc_ALWAYS_INLINE Vc_PURE bool Mask<uint16_t>::operator[](size_t index) const { return shiftMask() & (1 << 2 * index); } template<typename T> Vc_ALWAYS_INLINE Vc_PURE int Mask<T>::firstOne() const { const int mask = toInt(); #ifdef _MSC_VER unsigned long bit; _BitScanForward(&bit, mask); #else int bit; __asm__("bsf %1,%0" : "=&r"(bit) : "r"(mask)); #endif return bit; } /*operators{{{*/ /*}}}*/ Vc_NAMESPACE_END #include "undomacros.h" // vim: foldmethod=marker <|endoftext|>
<commit_before>#include "utility.hpp" #include "hog.pencil.h" #include "HogDescriptor.h" #include <opencv2/core/core.hpp> #include <opencv2/ocl/ocl.hpp> #include <pencil_runtime.h> #include <chrono> #include <random> #include <array> #define NUMBER_OF_CELLS 1 #define NUMBER_OF_BINS 8 #define GAUSSIAN_WEIGHTS 1 #define SPARTIAL_WEIGHTS 0 #define SIGNED_HOG 1 void time_hog( const std::vector<carp::record_t>& pool, const std::vector<float>& sizes, int num_positions, int repeat ) { carp::Timing timing("HOG"); for (;repeat>0; --repeat) { for ( auto & size : sizes ) { for ( auto & item : pool ) { std::mt19937 rng(1); //uses same seed, reseed for all iteration cv::Mat cpu_gray; cv::cvtColor( item.cpuimg(), cpu_gray, CV_RGB2GRAY ); cv::Mat_<float> locations(num_positions, 2); cv::Mat_<float> blocksizes(num_positions, 2); size_t max_blocksize_x = std::ceil(size); size_t max_blocksize_y = std::ceil(size); //fill locations and blocksizes std::uniform_real_distribution<float> genx(size/2+1, cpu_gray.rows-1-size/2-1); std::uniform_real_distribution<float> geny(size/2+1, cpu_gray.cols-1-size/2-1); for( int i = 0; i < num_positions; ++i) { locations(i, 0) = genx(rng); locations(i, 1) = geny(rng); blocksizes(i, 0) = size; blocksizes(i, 1) = size; } const int HISTOGRAM_BINS = NUMBER_OF_CELLS * NUMBER_OF_CELLS * NUMBER_OF_BINS; cv::Mat_<float> cpu_result, gpu_result, pen_result; std::chrono::duration<double> elapsed_time_cpu, elapsed_time_gpu_p_copy, elapsed_time_gpu_nocopy, elapsed_time_pencil; { //CPU implement static nel::HOGDescriptorCPP descriptor( NUMBER_OF_CELLS , NUMBER_OF_BINS , GAUSSIAN_WEIGHTS , SPARTIAL_WEIGHTS , SIGNED_HOG ); const auto cpu_start = std::chrono::high_resolution_clock::now(); cpu_result = descriptor.compute(cpu_gray, locations, blocksizes); const auto cpu_end = std::chrono::high_resolution_clock::now(); elapsed_time_cpu = cpu_end - cpu_start; //Free up resources } { //GPU implement static nel::HOGDescriptorOCL descriptor( NUMBER_OF_CELLS , NUMBER_OF_BINS , GAUSSIAN_WEIGHTS , SPARTIAL_WEIGHTS , SIGNED_HOG ); const auto gpu_start = std::chrono::high_resolution_clock::now(); gpu_result = descriptor.compute(cpu_gray, locations, blocksizes, max_blocksize_x, max_blocksize_y, elapsed_time_gpu_nocopy); const auto gpu_end = std::chrono::high_resolution_clock::now(); elapsed_time_gpu_p_copy = gpu_end - gpu_start; //Free up resources } { pen_result.create(num_positions, HISTOGRAM_BINS); const auto pencil_start = std::chrono::high_resolution_clock::now(); pencil_hog( NUMBER_OF_CELLS, NUMBER_OF_BINS, GAUSSIAN_WEIGHTS, SPARTIAL_WEIGHTS, SIGNED_HOG , cpu_gray.rows, cpu_gray.cols, cpu_gray.step1(), cpu_gray.ptr<uint8_t>() , num_positions , reinterpret_cast<const float (*)[2]>(locations.data) , reinterpret_cast<const float (*)[2]>(blocksizes.data) , reinterpret_cast< float * >(pen_result.data) ); // for (int n = 0; n < num_positions; ++n) { // float scale = static_cast<float>(cv::norm(pen_result.row(n), cv::NORM_L2)); // if (scale < std::numeric_limits<float>::epsilon()) // pen_result.row(n)= 0.0f; // else { // auto scaled = pen_result.row(n)/scale; // scaled = cv::min(scaled, 0.3f); // cv::normalize(scaled, pen_result.row(n)); // } // } const auto pencil_end = std::chrono::high_resolution_clock::now(); elapsed_time_pencil = pencil_end - pencil_start; //Free up resources } // Verifying the results if ( cv::norm( cpu_result, gpu_result, cv::NORM_INF) > cv::norm( gpu_result, cv::NORM_INF)*1e-5 || cv::norm( cpu_result, pen_result, cv::NORM_INF) > cv::norm( cpu_result, cv::NORM_INF)*1e-5 ) { std::cerr << "ERROR: Results don't match. Writing calculated images." << std::endl; std::cerr << "CPU norm:" << cv::norm(cpu_result, cv::NORM_INF) << std::endl; std::cerr << "GPU norm:" << cv::norm(gpu_result, cv::NORM_INF) << std::endl; std::cerr << "PEN norm:" << cv::norm(pen_result, cv::NORM_INF) << std::endl; std::cerr << "GPU-CPU norm:" << cv::norm(gpu_result, cpu_result, cv::NORM_INF) << std::endl; std::cerr << "PEN-CPU norm:" << cv::norm(pen_result, cpu_result, cv::NORM_INF) << std::endl; cv::imwrite( "hog_cpu.png", cpu_result ); cv::imwrite( "hog_gpu.png", gpu_result ); cv::imwrite( "hog_pen.png", pen_result ); cv::imwrite( "hog_diff_cpu_gpu.png", cv::abs(cpu_result-gpu_result) ); cv::imwrite( "hog_diff_cpu_pen.png", cv::abs(cpu_result-pen_result) ); throw std::runtime_error("The OpenCL or PENCIL results are not equivalent with the C++ results."); } timing.print( elapsed_time_cpu, elapsed_time_gpu_p_copy, elapsed_time_gpu_nocopy, elapsed_time_pencil ); } } } } int main(int argc, char* argv[]) { try { pencil_init(PENCIL_TARGET_DEVICE_DYNAMIC); std::cout << "This executable is iterating over all the files which are present in the directory `./pool'. " << std::endl; auto pool = carp::get_pool("pool"); #ifdef RUN_ONLY_ONE_EXPERIMENT time_hog( pool, {64}, 50, 1 ); #else time_hog( pool, {16, 32, 64, 128, 192}, 50, 6 ); #endif pencil_shutdown(); return EXIT_SUCCESS; }catch(const std::exception& e) { std::cout << e.what() << std::endl; pencil_shutdown(); return EXIT_FAILURE; } } // main <commit_msg>Use the new PRL interface and new tests methodology in HOG instead of the old ones and clean HOG<commit_after>#include "utility.hpp" #include "hog.pencil.h" #include "HogDescriptor.h" #include <opencv2/core/core.hpp> #include <opencv2/ocl/ocl.hpp> #include <prl.h> #include <chrono> #include <random> #include <array> #define NUMBER_OF_CELLS 1 #define NUMBER_OF_BINS 8 #define GAUSSIAN_WEIGHTS 1 #define SPARTIAL_WEIGHTS 0 #define SIGNED_HOG 1 void time_hog( const std::vector<carp::record_t>& pool, const std::vector<float>& sizes, int num_positions, int repeat ) { carp::Timing timing("HOG"); bool first_execution_hog_opencl = true, first_execution_pencil = true; for (;repeat>0; --repeat) { for ( auto & size : sizes ) { for ( auto & item : pool ) { std::mt19937 rng(1); //uses same seed, reseed for all iteration cv::Mat cpu_gray; cv::cvtColor( item.cpuimg(), cpu_gray, CV_RGB2GRAY ); cv::Mat_<float> locations(num_positions, 2); cv::Mat_<float> blocksizes(num_positions, 2); size_t max_blocksize_x = std::ceil(size); size_t max_blocksize_y = std::ceil(size); //fill locations and blocksizes std::uniform_real_distribution<float> genx(size/2+1, cpu_gray.rows-1-size/2-1); std::uniform_real_distribution<float> geny(size/2+1, cpu_gray.cols-1-size/2-1); for( int i = 0; i < num_positions; ++i) { locations(i, 0) = genx(rng); locations(i, 1) = geny(rng); blocksizes(i, 0) = size; blocksizes(i, 1) = size; } const int HISTOGRAM_BINS = NUMBER_OF_CELLS * NUMBER_OF_CELLS * NUMBER_OF_BINS; cv::Mat_<float> cpu_result, gpu_result, pen_result; std::chrono::duration<double> elapsed_time_cpu, elapsed_time_gpu_p_copy, elapsed_time_gpu_nocopy, elapsed_time_pencil; { //CPU implement static nel::HOGDescriptorCPP descriptor( NUMBER_OF_CELLS , NUMBER_OF_BINS , GAUSSIAN_WEIGHTS , SPARTIAL_WEIGHTS , SIGNED_HOG ); const auto cpu_start = std::chrono::high_resolution_clock::now(); cpu_result = descriptor.compute(cpu_gray, locations, blocksizes); const auto cpu_end = std::chrono::high_resolution_clock::now(); elapsed_time_cpu = cpu_end - cpu_start; //Free up resources } { //GPU implement static nel::HOGDescriptorOCL descriptor( NUMBER_OF_CELLS , NUMBER_OF_BINS , GAUSSIAN_WEIGHTS , SPARTIAL_WEIGHTS , SIGNED_HOG ); if (first_execution_hog_opencl) { cpu_result = descriptor.compute(cpu_gray, locations, blocksizes); first_execution_hog_opencl = false; } const auto gpu_start = std::chrono::high_resolution_clock::now(); gpu_result = descriptor.compute(cpu_gray, locations, blocksizes, max_blocksize_x, max_blocksize_y, elapsed_time_gpu_nocopy); const auto gpu_end = std::chrono::high_resolution_clock::now(); elapsed_time_gpu_p_copy = gpu_end - gpu_start; //Free up resources } { pen_result.create(num_positions, HISTOGRAM_BINS); if (first_execution_pencil) { pencil_hog( NUMBER_OF_CELLS, NUMBER_OF_BINS, GAUSSIAN_WEIGHTS, SPARTIAL_WEIGHTS, SIGNED_HOG , cpu_gray.rows, cpu_gray.cols, cpu_gray.step1(), cpu_gray.ptr<uint8_t>() , num_positions , reinterpret_cast<const float (*)[2]>(locations.data) , reinterpret_cast<const float (*)[2]>(blocksizes.data) , reinterpret_cast< float * >(pen_result.data) ); first_execution_pencil = false; } prl_timings_reset(); prl_timings_start(); pencil_hog( NUMBER_OF_CELLS, NUMBER_OF_BINS, GAUSSIAN_WEIGHTS, SPARTIAL_WEIGHTS, SIGNED_HOG , cpu_gray.rows, cpu_gray.cols, cpu_gray.step1(), cpu_gray.ptr<uint8_t>() , num_positions , reinterpret_cast<const float (*)[2]>(locations.data) , reinterpret_cast<const float (*)[2]>(blocksizes.data) , reinterpret_cast< float * >(pen_result.data) ); prl_timings_stop(); // Dump execution times for PENCIL code. prl_timings_dump(); } // Verifying the results if ( cv::norm( cpu_result, gpu_result, cv::NORM_INF) > cv::norm( gpu_result, cv::NORM_INF)*1e-5 || cv::norm( cpu_result, pen_result, cv::NORM_INF) > cv::norm( cpu_result, cv::NORM_INF)*1e-5 ) { std::cerr << "ERROR: Results don't match. Writing calculated images." << std::endl; std::cerr << "CPU norm:" << cv::norm(cpu_result, cv::NORM_INF) << std::endl; std::cerr << "GPU norm:" << cv::norm(gpu_result, cv::NORM_INF) << std::endl; std::cerr << "PEN norm:" << cv::norm(pen_result, cv::NORM_INF) << std::endl; std::cerr << "GPU-CPU norm:" << cv::norm(gpu_result, cpu_result, cv::NORM_INF) << std::endl; std::cerr << "PEN-CPU norm:" << cv::norm(pen_result, cpu_result, cv::NORM_INF) << std::endl; cv::imwrite( "hog_cpu.png", cpu_result ); cv::imwrite( "hog_gpu.png", gpu_result ); cv::imwrite( "hog_pen.png", pen_result ); cv::imwrite( "hog_diff_cpu_gpu.png", cv::abs(cpu_result-gpu_result) ); cv::imwrite( "hog_diff_cpu_pen.png", cv::abs(cpu_result-pen_result) ); throw std::runtime_error("The OpenCL or PENCIL results are not equivalent with the C++ results."); } timing.print(elapsed_time_cpu, elapsed_time_gpu_p_copy); } } } } int main(int argc, char* argv[]) { try { prl_init((prl_init_flags)(PRL_TARGET_DEVICE_DYNAMIC | PRL_PROFILING_ENABLED)); std::cout << "This executable is iterating over all the files passed to it as an argument. " << std::endl; auto pool = carp::get_pool(argc, argv); #ifdef RUN_ONLY_ONE_EXPERIMENT time_hog( pool, {64}, 50, 1 ); #else time_hog( pool, {16, 32, 64, 128, 192}, 50, 6 ); #endif prl_shutdown(); return EXIT_SUCCESS; }catch(const std::exception& e) { std::cout << e.what() << std::endl; prl_shutdown(); return EXIT_FAILURE; } } // main <|endoftext|>
<commit_before>/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */ /** * Copyright (C) 2013 Regents of the University of California. * @author: Yingdi Yu <[email protected]> * See COPYING for copyright and distribution information. */ // Only compile if ndn-cpp-config.h defines NDN_CPP_HAVE_OSX_SECURITY 1. #include <ndn-cpp/ndn-cpp-config.h> #if NDN_CPP_HAVE_OSX_SECURITY #include <fstream> #include <sstream> #include <CoreFoundation/CoreFoundation.h> #include "../../util/logging.hpp" #include <ndn-cpp/security/identity/osx-private-key-storage.hpp> #include <ndn-cpp/security/security-exception.hpp> using namespace std; using namespace ndn::ptr_lib; INIT_LOGGER("ndn.OSXPrivateKeyStorage"); namespace ndn { OSXPrivateKeyStorage::OSXPrivateKeyStorage(const string & keychainName) : keyChainName_("" == keychainName ? "NDN.keychain" : keychainName) { OSStatus res = SecKeychainCreate(keyChainName_.c_str(), //Keychain path 0, //Keychain password length NULL, //Keychain password true, //User prompt NULL, //Initial access of Keychain &keyChainRef_); //Keychain reference if (res == errSecDuplicateKeychain) res = SecKeychainOpen(keyChainName_.c_str(), &keyChainRef_); if (res != errSecSuccess){ _LOG_DEBUG("Fail to initialize keychain ref: " << res); throw SecurityException("Fail to initialize keychain ref"); } res = SecKeychainCopyDefault(&originalDefaultKeyChain_); res = SecKeychainSetDefault(keyChainRef_); if (res != errSecSuccess){ _LOG_DEBUG("Fail to set default keychain: " << res); throw SecurityException("Fail to set default keychain"); } } OSXPrivateKeyStorage::~OSXPrivateKeyStorage(){ //TODO: implement } void OSXPrivateKeyStorage::generateKeyPair(const Name & keyName, KeyType keyType, int keySize) { if(doesKeyExist(keyName, KEY_CLASS_PUBLIC)){ _LOG_DEBUG("keyName has existed"); throw SecurityException("keyName has existed"); } string keyNameUri = toInternalKeyName(keyName, KEY_CLASS_PUBLIC); SecKeyRef publicKey, privateKey; CFStringRef keyLabel = CFStringCreateWithCString(NULL, keyNameUri.c_str(), keyNameUri.size()); CFMutableDictionaryRef attrDict = CFDictionaryCreateMutable(NULL, 3, &kCFTypeDictionaryKeyCallBacks, NULL); CFDictionaryAddValue(attrDict, kSecAttrKeyType, getAsymKeyType(keyType)); CFDictionaryAddValue(attrDict, kSecAttrKeySizeInBits, CFNumberCreate(NULL, kCFNumberIntType, &keySize)); CFDictionaryAddValue(attrDict, kSecAttrLabel, keyLabel); OSStatus res = SecKeyGeneratePair((CFDictionaryRef)attrDict, &publicKey, &privateKey); CFRelease(publicKey); CFRelease(privateKey); if (res != errSecSuccess){ _LOG_DEBUG("Fail to create a key pair: " << res); throw SecurityException("Fail to create a key pair"); } } void OSXPrivateKeyStorage::generateKey(const Name & keyName, KeyType keyType, int keySize) { if(doesKeyExist(keyName, KEY_CLASS_SYMMETRIC)) throw SecurityException("keyName has existed!"); string keyNameUri = toInternalKeyName(keyName, KEY_CLASS_SYMMETRIC); CFMutableDictionaryRef attrDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFStringRef keyLabel = CFStringCreateWithCString(NULL, keyNameUri.c_str(), keyNameUri.size()); CFDictionaryAddValue(attrDict, kSecAttrKeyType, getSymKeyType(keyType)); CFDictionaryAddValue(attrDict, kSecAttrKeySizeInBits, CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &keySize)); CFDictionaryAddValue(attrDict, kSecAttrIsPermanent, kCFBooleanTrue); CFDictionaryAddValue(attrDict, kSecAttrLabel, keyLabel); CFErrorRef error = NULL; SecKeyRef symmetricKey = SecKeyGenerateSymmetric(attrDict, &error); if (error) throw SecurityException("Fail to create a symmetric key"); } shared_ptr<PublicKey> OSXPrivateKeyStorage::getPublicKey(const Name & keyName) { _LOG_TRACE("OSXPrivateKeyStorage::getPublickey"); SecKeychainItemRef publicKey = getKey(keyName, KEY_CLASS_PUBLIC); CFDataRef exportedKey; OSStatus res = SecItemExport(publicKey, kSecFormatOpenSSL, 0, NULL, &exportedKey); Blob blob(CFDataGetBytePtr(exportedKey), CFDataGetLength(exportedKey)); return PublicKey::fromDer(blob); } Blob OSXPrivateKeyStorage::sign(const uint8_t *data, size_t dataLength, const Name & keyName, DigestAlgorithm digestAlgo) { _LOG_TRACE("OSXPrivateKeyStorage::Sign"); CFDataRef dataRef = CFDataCreate(NULL, reinterpret_cast<const unsigned char*>(data), dataLength ); SecKeyRef privateKey = (SecKeyRef)getKey(keyName, KEY_CLASS_PRIVATE); CFErrorRef error; SecTransformRef signer = SecSignTransformCreate((SecKeyRef)privateKey, &error); if (error) throw SecurityException("Fail to create signer"); Boolean set_res = SecTransformSetAttribute(signer, kSecTransformInputAttributeName, dataRef, &error); if (error) throw SecurityException("Fail to configure input of signer"); set_res = SecTransformSetAttribute(signer, kSecDigestTypeAttribute, getDigestAlgorithm(digestAlgo), &error); if (error) throw SecurityException("Fail to configure digest algorithm of signer"); long digestSize = getDigestSize(digestAlgo); set_res = SecTransformSetAttribute(signer, kSecDigestLengthAttribute, CFNumberCreate(NULL, kCFNumberLongType, &digestSize), &error); if (error) throw SecurityException("Fail to configure digest size of signer"); CFDataRef signature = (CFDataRef) SecTransformExecute(signer, &error); if (error) { CFShow(error); throw SecurityException("Fail to sign data"); } if (!signature) throw SecurityException("Signature is NULL!\n"); return Blob(CFDataGetBytePtr(signature), CFDataGetLength(signature)); } Blob OSXPrivateKeyStorage::decrypt(const Name & keyName, const uint8_t* data, size_t dataLength, bool sym) { _LOG_TRACE("OSXPrivateKeyStorage::Decrypt"); KeyClass keyClass; if(sym) keyClass = KEY_CLASS_SYMMETRIC; else keyClass = KEY_CLASS_PRIVATE; CFDataRef dataRef = CFDataCreate(NULL, reinterpret_cast<const unsigned char*>(data), dataLength ); // _LOG_DEBUG("CreateData"); SecKeyRef decryptKey = (SecKeyRef)getKey(keyName, keyClass); // _LOG_DEBUG("GetKey"); CFErrorRef error; SecTransformRef decrypt = SecDecryptTransformCreate(decryptKey, &error); if (error) throw SecurityException("Fail to create decrypt"); Boolean set_res = SecTransformSetAttribute(decrypt, kSecTransformInputAttributeName, dataRef, &error); if (error) throw SecurityException("Fail to configure decrypt"); CFDataRef output = (CFDataRef) SecTransformExecute(decrypt, &error); if (error) { CFShow(error); throw SecurityException("Fail to decrypt data"); } if (!output) throw SecurityException("Output is NULL!\n"); return Blob(CFDataGetBytePtr(output), CFDataGetLength(output)); } bool OSXPrivateKeyStorage::setACL(const Name & keyName, KeyClass keyClass, int acl, const string & appPath) { SecKeychainItemRef privateKey = getKey(keyName, keyClass); SecAccessRef accRef; OSStatus acc_res = SecKeychainItemCopyAccess(privateKey, &accRef); CFArrayRef signACL = SecAccessCopyMatchingACLList(accRef, kSecACLAuthorizationSign); SecACLRef aclRef = (SecACLRef) CFArrayGetValueAtIndex(signACL, 0); CFArrayRef appList; CFStringRef description; SecKeychainPromptSelector promptSelector; OSStatus acl_res = SecACLCopyContents(aclRef, &appList, &description, &promptSelector); CFMutableArrayRef newAppList = CFArrayCreateMutableCopy(NULL, 0, appList); SecTrustedApplicationRef trustedApp; acl_res = SecTrustedApplicationCreateFromPath(appPath.c_str(), &trustedApp); CFArrayAppendValue(newAppList, trustedApp); CFArrayRef authList = SecACLCopyAuthorizations(aclRef); acl_res = SecACLRemove(aclRef); SecACLRef newACL; acl_res = SecACLCreateWithSimpleContents(accRef, newAppList, description, promptSelector, &newACL); acl_res = SecACLUpdateAuthorizations(newACL, authList); acc_res = SecKeychainItemSetAccess(privateKey, accRef); return true; } bool OSXPrivateKeyStorage::verifyData(const Name & keyName, const Blob & pData, const Blob & pSig, DigestAlgorithm digestAlgo) { _LOG_TRACE("OSXPrivateKeyStorage::Verify"); CFDataRef dataRef = CFDataCreate(NULL, reinterpret_cast<const unsigned char*>(pData.buf()), pData.size()); CFDataRef sigRef = CFDataCreate(NULL, reinterpret_cast<const unsigned char*>(pSig.buf()), pSig.size()); SecKeyRef publicKey = (SecKeyRef)getKey(keyName, KEY_CLASS_PUBLIC); CFErrorRef error; SecTransformRef verifier = SecVerifyTransformCreate(publicKey, sigRef, &error); if (error) throw SecurityException("Fail to create verifier"); Boolean set_res = SecTransformSetAttribute(verifier, kSecTransformInputAttributeName, dataRef, &error); if (error) throw SecurityException("Fail to configure input of verifier"); set_res = SecTransformSetAttribute(verifier, kSecDigestTypeAttribute, getDigestAlgorithm(digestAlgo), &error); if (error) throw SecurityException("Fail to configure digest algorithm of verifier"); long digestSize = getDigestSize(digestAlgo); set_res = SecTransformSetAttribute(verifier, kSecDigestLengthAttribute, CFNumberCreate(NULL, kCFNumberLongType, &digestSize), &error); if (error) throw SecurityException("Fail to configure digest size of verifier"); CFBooleanRef result = (CFBooleanRef) SecTransformExecute(verifier, &error); if (error) throw SecurityException("Fail to verify data"); if (result == kCFBooleanTrue) return true; else return false; } Blob OSXPrivateKeyStorage::encrypt(const Name & keyName, const uint8_t* data, size_t dataLength, bool sym) { _LOG_TRACE("OSXPrivateKeyStorage::Encrypt"); KeyClass keyClass; if(sym) keyClass = KEY_CLASS_SYMMETRIC; else keyClass = KEY_CLASS_PUBLIC; CFDataRef dataRef = CFDataCreate(NULL, reinterpret_cast<const unsigned char*>(data), dataLength ); SecKeyRef encryptKey = (SecKeyRef)getKey(keyName, keyClass); CFErrorRef error; SecTransformRef encrypt = SecEncryptTransformCreate(encryptKey, &error); if (error) throw SecurityException("Fail to create encrypt"); Boolean set_res = SecTransformSetAttribute(encrypt, kSecTransformInputAttributeName, dataRef, &error); if (error) throw SecurityException("Fail to configure encrypt"); CFDataRef output = (CFDataRef) SecTransformExecute(encrypt, &error); if (error) throw SecurityException("Fail to encrypt data"); if (!output) throw SecurityException("Output is NULL!\n"); return Blob(CFDataGetBytePtr(output), CFDataGetLength(output)); } bool OSXPrivateKeyStorage::doesKeyExist(const Name & keyName, KeyClass keyClass) { _LOG_TRACE("OSXPrivateKeyStorage::doesKeyExist"); string keyNameUri = toInternalKeyName(keyName, keyClass); CFStringRef keyLabel = CFStringCreateWithCString(NULL, keyNameUri.c_str(), keyNameUri.size()); CFMutableDictionaryRef attrDict = CFDictionaryCreateMutable(NULL, 3, &kCFTypeDictionaryKeyCallBacks, NULL); CFDictionaryAddValue(attrDict, kSecAttrKeyClass, getKeyClass(keyClass)); CFDictionaryAddValue(attrDict, kSecAttrLabel, keyLabel); CFDictionaryAddValue(attrDict, kSecReturnRef, kCFBooleanTrue); SecKeychainItemRef itemRef; OSStatus res = SecItemCopyMatching((CFDictionaryRef)attrDict, (CFTypeRef*)&itemRef); if(res == errSecItemNotFound) return true; else return false; } SecKeychainItemRef OSXPrivateKeyStorage::getKey(const Name & keyName, KeyClass keyClass) { string keyNameUri = toInternalKeyName(keyName, keyClass); CFStringRef keyLabel = CFStringCreateWithCString (NULL, keyNameUri.c_str(), keyNameUri.size()); CFMutableDictionaryRef attrDict = CFDictionaryCreateMutable(NULL, 5, &kCFTypeDictionaryKeyCallBacks, NULL); CFDictionaryAddValue(attrDict, kSecClass, kSecClassKey); CFDictionaryAddValue(attrDict, kSecAttrLabel, keyLabel); CFDictionaryAddValue(attrDict, kSecAttrKeyClass, getKeyClass(keyClass)); CFDictionaryAddValue(attrDict, kSecReturnRef, kCFBooleanTrue); SecKeychainItemRef keyItem; OSStatus res = SecItemCopyMatching((CFDictionaryRef) attrDict, (CFTypeRef*)&keyItem); if(res != errSecSuccess){ _LOG_DEBUG("Fail to find the key!"); return NULL; } else return keyItem; } string OSXPrivateKeyStorage::toInternalKeyName(const Name & keyName, KeyClass keyClass) { string keyUri = keyName.toUri(); if(KEY_CLASS_SYMMETRIC == keyClass) return keyUri + "/symmetric"; else return keyUri; } const CFTypeRef OSXPrivateKeyStorage::getAsymKeyType(KeyType keyType) { switch(keyType){ case KEY_TYPE_RSA: return kSecAttrKeyTypeRSA; default: _LOG_DEBUG("Unrecognized key type!") return NULL; } } const CFTypeRef OSXPrivateKeyStorage::getSymKeyType(KeyType keyType) { switch(keyType){ case KEY_TYPE_AES: return kSecAttrKeyTypeAES; default: _LOG_DEBUG("Unrecognized key type!") return NULL; } } const CFTypeRef OSXPrivateKeyStorage::getKeyClass(KeyClass keyClass) { switch(keyClass){ case KEY_CLASS_PRIVATE: return kSecAttrKeyClassPrivate; case KEY_CLASS_PUBLIC: return kSecAttrKeyClassPublic; case KEY_CLASS_SYMMETRIC: return kSecAttrKeyClassSymmetric; default: _LOG_DEBUG("Unrecognized key class!"); return NULL; } } SecExternalFormat OSXPrivateKeyStorage::getFormat(KeyFormat format) { switch(format){ case KEY_FORMAT_PUBLIC_OPENSSL: return kSecFormatOpenSSL; default: _LOG_DEBUG("Unrecognized output format!"); return 0; } } const CFStringRef OSXPrivateKeyStorage::getDigestAlgorithm(DigestAlgorithm digestAlgo) { switch(digestAlgo){ // case DIGEST_MD2: // return kSecDigestMD2; // case DIGEST_MD5: // return kSecDigestMD5; // case DIGEST_SHA1: // return kSecDigestSHA1; case DIGEST_ALGORITHM_SHA256: return kSecDigestSHA2; default: _LOG_DEBUG("Unrecognized digest algorithm!"); return NULL; } } long OSXPrivateKeyStorage::getDigestSize(DigestAlgorithm digestAlgo) { switch(digestAlgo){ case DIGEST_ALGORITHM_SHA256: return 256; // case DIGEST_SHA1: // case DIGEST_MD2: // case DIGEST_MD5: // return 0; default: _LOG_DEBUG("Unrecognized digest algorithm! Unknown digest size"); return -1; } } } #endif // NDN_CPP_HAVE_OSX_SECURITY <commit_msg>security: OSXPrivateKeyStorage: When calling CFStringCreateWithCString, need to use kCFStringEncodingUTF8.<commit_after>/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */ /** * Copyright (C) 2013 Regents of the University of California. * @author: Yingdi Yu <[email protected]> * See COPYING for copyright and distribution information. */ // Only compile if ndn-cpp-config.h defines NDN_CPP_HAVE_OSX_SECURITY 1. #include <ndn-cpp/ndn-cpp-config.h> #if NDN_CPP_HAVE_OSX_SECURITY #include <fstream> #include <sstream> #include <CoreFoundation/CoreFoundation.h> #include "../../util/logging.hpp" #include <ndn-cpp/security/identity/osx-private-key-storage.hpp> #include <ndn-cpp/security/security-exception.hpp> using namespace std; using namespace ndn::ptr_lib; INIT_LOGGER("ndn.OSXPrivateKeyStorage"); namespace ndn { OSXPrivateKeyStorage::OSXPrivateKeyStorage(const string & keychainName) : keyChainName_("" == keychainName ? "NDN.keychain" : keychainName) { OSStatus res = SecKeychainCreate(keyChainName_.c_str(), //Keychain path 0, //Keychain password length NULL, //Keychain password true, //User prompt NULL, //Initial access of Keychain &keyChainRef_); //Keychain reference if (res == errSecDuplicateKeychain) res = SecKeychainOpen(keyChainName_.c_str(), &keyChainRef_); if (res != errSecSuccess){ _LOG_DEBUG("Fail to initialize keychain ref: " << res); throw SecurityException("Fail to initialize keychain ref"); } res = SecKeychainCopyDefault(&originalDefaultKeyChain_); res = SecKeychainSetDefault(keyChainRef_); if (res != errSecSuccess){ _LOG_DEBUG("Fail to set default keychain: " << res); throw SecurityException("Fail to set default keychain"); } } OSXPrivateKeyStorage::~OSXPrivateKeyStorage(){ //TODO: implement } void OSXPrivateKeyStorage::generateKeyPair(const Name & keyName, KeyType keyType, int keySize) { if(doesKeyExist(keyName, KEY_CLASS_PUBLIC)){ _LOG_DEBUG("keyName has existed"); throw SecurityException("keyName has existed"); } string keyNameUri = toInternalKeyName(keyName, KEY_CLASS_PUBLIC); SecKeyRef publicKey, privateKey; CFStringRef keyLabel = CFStringCreateWithCString(NULL, keyNameUri.c_str(), kCFStringEncodingUTF8); CFMutableDictionaryRef attrDict = CFDictionaryCreateMutable(NULL, 3, &kCFTypeDictionaryKeyCallBacks, NULL); CFDictionaryAddValue(attrDict, kSecAttrKeyType, getAsymKeyType(keyType)); CFDictionaryAddValue(attrDict, kSecAttrKeySizeInBits, CFNumberCreate(NULL, kCFNumberIntType, &keySize)); CFDictionaryAddValue(attrDict, kSecAttrLabel, keyLabel); OSStatus res = SecKeyGeneratePair((CFDictionaryRef)attrDict, &publicKey, &privateKey); CFRelease(publicKey); CFRelease(privateKey); if (res != errSecSuccess){ _LOG_DEBUG("Fail to create a key pair: " << res); throw SecurityException("Fail to create a key pair"); } } void OSXPrivateKeyStorage::generateKey(const Name & keyName, KeyType keyType, int keySize) { if(doesKeyExist(keyName, KEY_CLASS_SYMMETRIC)) throw SecurityException("keyName has existed!"); string keyNameUri = toInternalKeyName(keyName, KEY_CLASS_SYMMETRIC); CFMutableDictionaryRef attrDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFStringRef keyLabel = CFStringCreateWithCString(NULL, keyNameUri.c_str(), kCFStringEncodingUTF8); CFDictionaryAddValue(attrDict, kSecAttrKeyType, getSymKeyType(keyType)); CFDictionaryAddValue(attrDict, kSecAttrKeySizeInBits, CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &keySize)); CFDictionaryAddValue(attrDict, kSecAttrIsPermanent, kCFBooleanTrue); CFDictionaryAddValue(attrDict, kSecAttrLabel, keyLabel); CFErrorRef error = NULL; SecKeyRef symmetricKey = SecKeyGenerateSymmetric(attrDict, &error); if (error) throw SecurityException("Fail to create a symmetric key"); } shared_ptr<PublicKey> OSXPrivateKeyStorage::getPublicKey(const Name & keyName) { _LOG_TRACE("OSXPrivateKeyStorage::getPublickey"); SecKeychainItemRef publicKey = getKey(keyName, KEY_CLASS_PUBLIC); CFDataRef exportedKey; OSStatus res = SecItemExport(publicKey, kSecFormatOpenSSL, 0, NULL, &exportedKey); Blob blob(CFDataGetBytePtr(exportedKey), CFDataGetLength(exportedKey)); return PublicKey::fromDer(blob); } Blob OSXPrivateKeyStorage::sign(const uint8_t *data, size_t dataLength, const Name & keyName, DigestAlgorithm digestAlgo) { _LOG_TRACE("OSXPrivateKeyStorage::Sign"); CFDataRef dataRef = CFDataCreate(NULL, reinterpret_cast<const unsigned char*>(data), dataLength ); SecKeyRef privateKey = (SecKeyRef)getKey(keyName, KEY_CLASS_PRIVATE); CFErrorRef error; SecTransformRef signer = SecSignTransformCreate((SecKeyRef)privateKey, &error); if (error) throw SecurityException("Fail to create signer"); Boolean set_res = SecTransformSetAttribute(signer, kSecTransformInputAttributeName, dataRef, &error); if (error) throw SecurityException("Fail to configure input of signer"); set_res = SecTransformSetAttribute(signer, kSecDigestTypeAttribute, getDigestAlgorithm(digestAlgo), &error); if (error) throw SecurityException("Fail to configure digest algorithm of signer"); long digestSize = getDigestSize(digestAlgo); set_res = SecTransformSetAttribute(signer, kSecDigestLengthAttribute, CFNumberCreate(NULL, kCFNumberLongType, &digestSize), &error); if (error) throw SecurityException("Fail to configure digest size of signer"); CFDataRef signature = (CFDataRef) SecTransformExecute(signer, &error); if (error) { CFShow(error); throw SecurityException("Fail to sign data"); } if (!signature) throw SecurityException("Signature is NULL!\n"); return Blob(CFDataGetBytePtr(signature), CFDataGetLength(signature)); } Blob OSXPrivateKeyStorage::decrypt(const Name & keyName, const uint8_t* data, size_t dataLength, bool sym) { _LOG_TRACE("OSXPrivateKeyStorage::Decrypt"); KeyClass keyClass; if(sym) keyClass = KEY_CLASS_SYMMETRIC; else keyClass = KEY_CLASS_PRIVATE; CFDataRef dataRef = CFDataCreate(NULL, reinterpret_cast<const unsigned char*>(data), dataLength ); // _LOG_DEBUG("CreateData"); SecKeyRef decryptKey = (SecKeyRef)getKey(keyName, keyClass); // _LOG_DEBUG("GetKey"); CFErrorRef error; SecTransformRef decrypt = SecDecryptTransformCreate(decryptKey, &error); if (error) throw SecurityException("Fail to create decrypt"); Boolean set_res = SecTransformSetAttribute(decrypt, kSecTransformInputAttributeName, dataRef, &error); if (error) throw SecurityException("Fail to configure decrypt"); CFDataRef output = (CFDataRef) SecTransformExecute(decrypt, &error); if (error) { CFShow(error); throw SecurityException("Fail to decrypt data"); } if (!output) throw SecurityException("Output is NULL!\n"); return Blob(CFDataGetBytePtr(output), CFDataGetLength(output)); } bool OSXPrivateKeyStorage::setACL(const Name & keyName, KeyClass keyClass, int acl, const string & appPath) { SecKeychainItemRef privateKey = getKey(keyName, keyClass); SecAccessRef accRef; OSStatus acc_res = SecKeychainItemCopyAccess(privateKey, &accRef); CFArrayRef signACL = SecAccessCopyMatchingACLList(accRef, kSecACLAuthorizationSign); SecACLRef aclRef = (SecACLRef) CFArrayGetValueAtIndex(signACL, 0); CFArrayRef appList; CFStringRef description; SecKeychainPromptSelector promptSelector; OSStatus acl_res = SecACLCopyContents(aclRef, &appList, &description, &promptSelector); CFMutableArrayRef newAppList = CFArrayCreateMutableCopy(NULL, 0, appList); SecTrustedApplicationRef trustedApp; acl_res = SecTrustedApplicationCreateFromPath(appPath.c_str(), &trustedApp); CFArrayAppendValue(newAppList, trustedApp); CFArrayRef authList = SecACLCopyAuthorizations(aclRef); acl_res = SecACLRemove(aclRef); SecACLRef newACL; acl_res = SecACLCreateWithSimpleContents(accRef, newAppList, description, promptSelector, &newACL); acl_res = SecACLUpdateAuthorizations(newACL, authList); acc_res = SecKeychainItemSetAccess(privateKey, accRef); return true; } bool OSXPrivateKeyStorage::verifyData(const Name & keyName, const Blob & pData, const Blob & pSig, DigestAlgorithm digestAlgo) { _LOG_TRACE("OSXPrivateKeyStorage::Verify"); CFDataRef dataRef = CFDataCreate(NULL, reinterpret_cast<const unsigned char*>(pData.buf()), pData.size()); CFDataRef sigRef = CFDataCreate(NULL, reinterpret_cast<const unsigned char*>(pSig.buf()), pSig.size()); SecKeyRef publicKey = (SecKeyRef)getKey(keyName, KEY_CLASS_PUBLIC); CFErrorRef error; SecTransformRef verifier = SecVerifyTransformCreate(publicKey, sigRef, &error); if (error) throw SecurityException("Fail to create verifier"); Boolean set_res = SecTransformSetAttribute(verifier, kSecTransformInputAttributeName, dataRef, &error); if (error) throw SecurityException("Fail to configure input of verifier"); set_res = SecTransformSetAttribute(verifier, kSecDigestTypeAttribute, getDigestAlgorithm(digestAlgo), &error); if (error) throw SecurityException("Fail to configure digest algorithm of verifier"); long digestSize = getDigestSize(digestAlgo); set_res = SecTransformSetAttribute(verifier, kSecDigestLengthAttribute, CFNumberCreate(NULL, kCFNumberLongType, &digestSize), &error); if (error) throw SecurityException("Fail to configure digest size of verifier"); CFBooleanRef result = (CFBooleanRef) SecTransformExecute(verifier, &error); if (error) throw SecurityException("Fail to verify data"); if (result == kCFBooleanTrue) return true; else return false; } Blob OSXPrivateKeyStorage::encrypt(const Name & keyName, const uint8_t* data, size_t dataLength, bool sym) { _LOG_TRACE("OSXPrivateKeyStorage::Encrypt"); KeyClass keyClass; if(sym) keyClass = KEY_CLASS_SYMMETRIC; else keyClass = KEY_CLASS_PUBLIC; CFDataRef dataRef = CFDataCreate(NULL, reinterpret_cast<const unsigned char*>(data), dataLength ); SecKeyRef encryptKey = (SecKeyRef)getKey(keyName, keyClass); CFErrorRef error; SecTransformRef encrypt = SecEncryptTransformCreate(encryptKey, &error); if (error) throw SecurityException("Fail to create encrypt"); Boolean set_res = SecTransformSetAttribute(encrypt, kSecTransformInputAttributeName, dataRef, &error); if (error) throw SecurityException("Fail to configure encrypt"); CFDataRef output = (CFDataRef) SecTransformExecute(encrypt, &error); if (error) throw SecurityException("Fail to encrypt data"); if (!output) throw SecurityException("Output is NULL!\n"); return Blob(CFDataGetBytePtr(output), CFDataGetLength(output)); } bool OSXPrivateKeyStorage::doesKeyExist(const Name & keyName, KeyClass keyClass) { _LOG_TRACE("OSXPrivateKeyStorage::doesKeyExist"); string keyNameUri = toInternalKeyName(keyName, keyClass); CFStringRef keyLabel = CFStringCreateWithCString(NULL, keyNameUri.c_str(), kCFStringEncodingUTF8); CFMutableDictionaryRef attrDict = CFDictionaryCreateMutable(NULL, 3, &kCFTypeDictionaryKeyCallBacks, NULL); CFDictionaryAddValue(attrDict, kSecAttrKeyClass, getKeyClass(keyClass)); CFDictionaryAddValue(attrDict, kSecAttrLabel, keyLabel); CFDictionaryAddValue(attrDict, kSecReturnRef, kCFBooleanTrue); SecKeychainItemRef itemRef; OSStatus res = SecItemCopyMatching((CFDictionaryRef)attrDict, (CFTypeRef*)&itemRef); if(res == errSecItemNotFound) return true; else return false; } SecKeychainItemRef OSXPrivateKeyStorage::getKey(const Name & keyName, KeyClass keyClass) { string keyNameUri = toInternalKeyName(keyName, keyClass); CFStringRef keyLabel = CFStringCreateWithCString(NULL, keyNameUri.c_str(), kCFStringEncodingUTF8); CFMutableDictionaryRef attrDict = CFDictionaryCreateMutable(NULL, 5, &kCFTypeDictionaryKeyCallBacks, NULL); CFDictionaryAddValue(attrDict, kSecClass, kSecClassKey); CFDictionaryAddValue(attrDict, kSecAttrLabel, keyLabel); CFDictionaryAddValue(attrDict, kSecAttrKeyClass, getKeyClass(keyClass)); CFDictionaryAddValue(attrDict, kSecReturnRef, kCFBooleanTrue); SecKeychainItemRef keyItem; OSStatus res = SecItemCopyMatching((CFDictionaryRef) attrDict, (CFTypeRef*)&keyItem); if(res != errSecSuccess){ _LOG_DEBUG("Fail to find the key!"); return NULL; } else return keyItem; } string OSXPrivateKeyStorage::toInternalKeyName(const Name & keyName, KeyClass keyClass) { string keyUri = keyName.toUri(); if(KEY_CLASS_SYMMETRIC == keyClass) return keyUri + "/symmetric"; else return keyUri; } const CFTypeRef OSXPrivateKeyStorage::getAsymKeyType(KeyType keyType) { switch(keyType){ case KEY_TYPE_RSA: return kSecAttrKeyTypeRSA; default: _LOG_DEBUG("Unrecognized key type!") return NULL; } } const CFTypeRef OSXPrivateKeyStorage::getSymKeyType(KeyType keyType) { switch(keyType){ case KEY_TYPE_AES: return kSecAttrKeyTypeAES; default: _LOG_DEBUG("Unrecognized key type!") return NULL; } } const CFTypeRef OSXPrivateKeyStorage::getKeyClass(KeyClass keyClass) { switch(keyClass){ case KEY_CLASS_PRIVATE: return kSecAttrKeyClassPrivate; case KEY_CLASS_PUBLIC: return kSecAttrKeyClassPublic; case KEY_CLASS_SYMMETRIC: return kSecAttrKeyClassSymmetric; default: _LOG_DEBUG("Unrecognized key class!"); return NULL; } } SecExternalFormat OSXPrivateKeyStorage::getFormat(KeyFormat format) { switch(format){ case KEY_FORMAT_PUBLIC_OPENSSL: return kSecFormatOpenSSL; default: _LOG_DEBUG("Unrecognized output format!"); return 0; } } const CFStringRef OSXPrivateKeyStorage::getDigestAlgorithm(DigestAlgorithm digestAlgo) { switch(digestAlgo){ // case DIGEST_MD2: // return kSecDigestMD2; // case DIGEST_MD5: // return kSecDigestMD5; // case DIGEST_SHA1: // return kSecDigestSHA1; case DIGEST_ALGORITHM_SHA256: return kSecDigestSHA2; default: _LOG_DEBUG("Unrecognized digest algorithm!"); return NULL; } } long OSXPrivateKeyStorage::getDigestSize(DigestAlgorithm digestAlgo) { switch(digestAlgo){ case DIGEST_ALGORITHM_SHA256: return 256; // case DIGEST_SHA1: // case DIGEST_MD2: // case DIGEST_MD5: // return 0; default: _LOG_DEBUG("Unrecognized digest algorithm! Unknown digest size"); return -1; } } } #endif // NDN_CPP_HAVE_OSX_SECURITY <|endoftext|>
<commit_before>/* * Copyright (C) 2016+ AzerothCore <www.azerothcore.org>, released under GNU GPL v2 license: https://github.com/azerothcore/azerothcore-wotlk/blob/master/LICENSE-GPL2 * Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/> */ #include "GridNotifiers.h" #include "GridNotifiersImpl.h" #include "WorldPacket.h" #include "WorldSession.h" #include "UpdateData.h" #include "Item.h" #include "Map.h" #include "Transport.h" #include "ObjectAccessor.h" #include "CellImpl.h" #include "SpellInfo.h" using namespace Trinity; void VisibleNotifier::Visit(GameObjectMapType &m) { for (GameObjectMapType::iterator iter = m.begin(); iter != m.end(); ++iter) { if (i_largeOnly != iter->GetSource()->IsVisibilityOverridden()) continue; vis_guids.erase(iter->GetSource()->GetGUID()); i_player.UpdateVisibilityOf(iter->GetSource(), i_data, i_visibleNow); } } void VisibleNotifier::SendToSelf() { // at this moment i_clientGUIDs have guids that not iterate at grid level checks // but exist one case when this possible and object not out of range: transports if (Transport* transport = i_player.GetTransport()) for (Transport::PassengerSet::const_iterator itr = transport->GetPassengers().begin(); itr != transport->GetPassengers().end();++itr) { if (i_largeOnly != (*itr)->IsVisibilityOverridden()) continue; if (vis_guids.find((*itr)->GetGUID()) != vis_guids.end()) { vis_guids.erase((*itr)->GetGUID()); switch ((*itr)->GetTypeId()) { case TYPEID_GAMEOBJECT: i_player.UpdateVisibilityOf((*itr)->ToGameObject(), i_data, i_visibleNow); break; case TYPEID_PLAYER: i_player.UpdateVisibilityOf((*itr)->ToPlayer(), i_data, i_visibleNow); (*itr)->ToPlayer()->UpdateVisibilityOf(&i_player); break; case TYPEID_UNIT: i_player.UpdateVisibilityOf((*itr)->ToCreature(), i_data, i_visibleNow); break; default: break; } } } for (Player::ClientGUIDs::const_iterator it = vis_guids.begin();it != vis_guids.end(); ++it) { if (i_largeOnly != ObjectAccessor::GetWorldObject(i_player, *it)->IsVisibilityOverridden()) continue; // pussywizard: static transports are removed only in RemovePlayerFromMap and here if can no longer detect (eg. phase changed) if (IS_TRANSPORT_GUID(*it)) if (GameObject* staticTrans = i_player.GetMap()->GetGameObject(*it)) if (i_player.CanSeeOrDetect(staticTrans, false, true)) continue; i_player.m_clientGUIDs.erase(*it); i_data.AddOutOfRangeGUID(*it); if (IS_PLAYER_GUID(*it)) { Player* player = ObjectAccessor::FindPlayer(*it); if (player && player->IsInMap(&i_player)) player->UpdateVisibilityOf(&i_player); } } if (!i_data.HasData()) return; WorldPacket packet; i_data.BuildPacket(&packet); i_player.GetSession()->SendPacket(&packet); for (std::vector<Unit*>::const_iterator it = i_visibleNow.begin(); it != i_visibleNow.end(); ++it) { if (i_largeOnly != (*it)->IsVisibilityOverridden()) continue; i_player.GetInitialVisiblePackets(*it); } } void VisibleChangesNotifier::Visit(PlayerMapType &m) { for (PlayerMapType::iterator iter = m.begin(); iter != m.end(); ++iter) { if (iter->GetSource() == &i_object) continue; iter->GetSource()->UpdateVisibilityOf(&i_object); if (iter->GetSource()->HasSharedVision()) for (SharedVisionList::const_iterator i = iter->GetSource()->GetSharedVisionList().begin(); i != iter->GetSource()->GetSharedVisionList().end(); ++i) if ((*i)->m_seer == iter->GetSource()) (*i)->UpdateVisibilityOf(&i_object); } } void VisibleChangesNotifier::Visit(CreatureMapType &m) { for (CreatureMapType::iterator iter = m.begin(); iter != m.end(); ++iter) if (iter->GetSource()->HasSharedVision()) for (SharedVisionList::const_iterator i = iter->GetSource()->GetSharedVisionList().begin(); i != iter->GetSource()->GetSharedVisionList().end(); ++i) if ((*i)->m_seer == iter->GetSource()) (*i)->UpdateVisibilityOf(&i_object); } void VisibleChangesNotifier::Visit(DynamicObjectMapType &m) { for (DynamicObjectMapType::iterator iter = m.begin(); iter != m.end(); ++iter) if (IS_PLAYER_GUID(iter->GetSource()->GetCasterGUID())) if (Unit* caster = iter->GetSource()->GetCaster()) if (Player* player = caster->ToPlayer()) if (player->m_seer == iter->GetSource()) player->UpdateVisibilityOf(&i_object); } inline void CreatureUnitRelocationWorker(Creature* c, Unit* u) { if (!u->IsAlive() || !c->IsAlive() || c == u || u->IsInFlight()) return; if (c->HasReactState(REACT_AGGRESSIVE) && !c->HasUnitState(UNIT_STATE_SIGHTLESS)) { if (c->IsAIEnabled && c->CanSeeOrDetect(u, false, true)) { c->AI()->MoveInLineOfSight_Safe(u); } else { if (u->GetTypeId() == TYPEID_PLAYER && u->HasStealthAura() && c->IsAIEnabled && c->CanSeeOrDetect(u, false, true, true)) c->AI()->TriggerAlert(u); } } } void PlayerRelocationNotifier::Visit(PlayerMapType &m) { for (PlayerMapType::iterator iter = m.begin(); iter != m.end(); ++iter) { Player* player = iter->GetSource(); vis_guids.erase(player->GetGUID()); i_player.UpdateVisibilityOf(player, i_data, i_visibleNow); player->UpdateVisibilityOf(&i_player); // this notifier with different Visit(PlayerMapType&) than VisibleNotifier is needed to update visibility of self for other players when we move (eg. stealth detection changes) } } void CreatureRelocationNotifier::Visit(PlayerMapType &m) { for (PlayerMapType::iterator iter = m.begin(); iter != m.end(); ++iter) { Player* player = iter->GetSource(); // NOTIFY_VISIBILITY_CHANGED does not guarantee that player will do it himself (because distance is also checked), but screw it, it's not that important if (!player->m_seer->isNeedNotify(NOTIFY_VISIBILITY_CHANGED)) player->UpdateVisibilityOf(&i_creature); // NOTIFY_AI_RELOCATION does not guarantee that player will do it himself (because distance is also checked), but screw it, it's not that important if (!player->m_seer->isNeedNotify(NOTIFY_AI_RELOCATION) && !i_creature.IsMoveInLineOfSightStrictlyDisabled()) CreatureUnitRelocationWorker(&i_creature, player); } } void AIRelocationNotifier::Visit(CreatureMapType &m) { bool self = isCreature && !((Creature*)(&i_unit))->IsMoveInLineOfSightStrictlyDisabled(); for (CreatureMapType::iterator iter = m.begin(); iter != m.end(); ++iter) { Creature* c = iter->GetSource(); // NOTIFY_VISIBILITY_CHANGED | NOTIFY_AI_RELOCATION does not guarantee that unit will do it itself (because distance is also checked), but screw it, it's not that important if (!c->isNeedNotify(NOTIFY_VISIBILITY_CHANGED | NOTIFY_AI_RELOCATION) && !c->IsMoveInLineOfSightStrictlyDisabled()) CreatureUnitRelocationWorker(c, &i_unit); if (self) CreatureUnitRelocationWorker((Creature*)&i_unit, c); } } void MessageDistDeliverer::Visit(PlayerMapType &m) { for (PlayerMapType::iterator iter = m.begin(); iter != m.end(); ++iter) { Player* target = iter->GetSource(); if (!target->InSamePhase(i_phaseMask)) continue; if (target->GetExactDist2dSq(i_source) > i_distSq) continue; // Send packet to all who are sharing the player's vision if (target->HasSharedVision()) { SharedVisionList::const_iterator i = target->GetSharedVisionList().begin(); for (; i != target->GetSharedVisionList().end(); ++i) if ((*i)->m_seer == target) SendPacket(*i); } if (target->m_seer == target || target->GetVehicle()) SendPacket(target); } } void MessageDistDeliverer::Visit(CreatureMapType &m) { for (CreatureMapType::iterator iter = m.begin(); iter != m.end(); ++iter) { Creature* target = iter->GetSource(); if (!target->HasSharedVision() || !target->InSamePhase(i_phaseMask)) continue; if (target->GetExactDist2dSq(i_source) > i_distSq) continue; // Send packet to all who are sharing the creature's vision SharedVisionList::const_iterator i = target->GetSharedVisionList().begin(); for (; i != target->GetSharedVisionList().end(); ++i) if ((*i)->m_seer == target) SendPacket(*i); } } void MessageDistDeliverer::Visit(DynamicObjectMapType &m) { for (DynamicObjectMapType::iterator iter = m.begin(); iter != m.end(); ++iter) { DynamicObject* target = iter->GetSource(); if (!IS_PLAYER_GUID(target->GetCasterGUID()) || !target->InSamePhase(i_phaseMask)) continue; // Xinef: Check whether the dynobject allows to see through it if (!target->IsViewpoint()) continue; if (target->GetExactDist2dSq(i_source) > i_distSq) continue; // Send packet back to the caster if the caster has vision of dynamic object Player* caster = (Player*)target->GetCaster(); if (caster && caster->m_seer == target) SendPacket(caster); } } void MessageDistDelivererToHostile::Visit(PlayerMapType &m) { for (PlayerMapType::iterator iter = m.begin(); iter != m.end(); ++iter) { Player* target = iter->GetSource(); if (!target->InSamePhase(i_phaseMask)) continue; if (target->GetExactDist2dSq(i_source) > i_distSq) continue; // Send packet to all who are sharing the player's vision if (target->HasSharedVision()) { SharedVisionList::const_iterator i = target->GetSharedVisionList().begin(); for (; i != target->GetSharedVisionList().end(); ++i) if ((*i)->m_seer == target) SendPacket(*i); } if (target->m_seer == target || target->GetVehicle()) SendPacket(target); } } void MessageDistDelivererToHostile::Visit(CreatureMapType &m) { for (CreatureMapType::iterator iter = m.begin(); iter != m.end(); ++iter) { Creature* target = iter->GetSource(); if (!target->HasSharedVision() || !target->InSamePhase(i_phaseMask)) continue; if (target->GetExactDist2dSq(i_source) > i_distSq) continue; // Send packet to all who are sharing the creature's vision SharedVisionList::const_iterator i = target->GetSharedVisionList().begin(); for (; i != target->GetSharedVisionList().end(); ++i) if ((*i)->m_seer == target) SendPacket(*i); } } void MessageDistDelivererToHostile::Visit(DynamicObjectMapType &m) { for (DynamicObjectMapType::iterator iter = m.begin(); iter != m.end(); ++iter) { DynamicObject* target = iter->GetSource(); if (!IS_PLAYER_GUID(target->GetCasterGUID()) || !target->InSamePhase(i_phaseMask)) continue; if (target->GetExactDist2dSq(i_source) > i_distSq) continue; // Send packet back to the caster if the caster has vision of dynamic object Player* caster = (Player*)target->GetCaster(); if (caster && caster->m_seer == target) SendPacket(caster); } } template<class T> void ObjectUpdater::Visit(GridRefManager<T> &m) { T* obj; for (typename GridRefManager<T>::iterator iter = m.begin(); iter != m.end(); ) { obj = iter->GetSource(); ++iter; if (obj->IsInWorld()) obj->Update(i_timeDiff); } } template<class T> void LargeObjectUpdater::Visit(GridRefManager<T> &m) { T* obj; for (typename GridRefManager<T>::iterator iter = m.begin(); iter != m.end(); ) { obj = iter->GetSource(); ++iter; if (obj->IsInWorld() && obj->IsVisibilityOverridden()) obj->Update(i_timeDiff); } } bool AnyDeadUnitObjectInRangeCheck::operator()(Player* u) { return !u->IsAlive() && !u->HasAuraType(SPELL_AURA_GHOST) && i_searchObj->IsWithinDistInMap(u, i_range); } bool AnyDeadUnitObjectInRangeCheck::operator()(Corpse* u) { return u->GetType() != CORPSE_BONES && i_searchObj->IsWithinDistInMap(u, i_range); } bool AnyDeadUnitObjectInRangeCheck::operator()(Creature* u) { return !u->IsAlive() && i_searchObj->IsWithinDistInMap(u, i_range); } bool AnyDeadUnitSpellTargetInRangeCheck::operator()(Player* u) { return AnyDeadUnitObjectInRangeCheck::operator()(u) && i_check(u); } bool AnyDeadUnitSpellTargetInRangeCheck::operator()(Corpse* u) { return AnyDeadUnitObjectInRangeCheck::operator()(u) && i_check(u); } bool AnyDeadUnitSpellTargetInRangeCheck::operator()(Creature* u) { return AnyDeadUnitObjectInRangeCheck::operator()(u) && i_check(u); } template void ObjectUpdater::Visit<Creature>(CreatureMapType&); template void ObjectUpdater::Visit<GameObject>(GameObjectMapType&); template void ObjectUpdater::Visit<DynamicObject>(DynamicObjectMapType&); template void LargeObjectUpdater::Visit<Creature>(CreatureMapType&); <commit_msg>fix(Core/GridNotifiers): Fix crash (#2443)<commit_after>/* * Copyright (C) 2016+ AzerothCore <www.azerothcore.org>, released under GNU GPL v2 license: https://github.com/azerothcore/azerothcore-wotlk/blob/master/LICENSE-GPL2 * Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/> */ #include "GridNotifiers.h" #include "GridNotifiersImpl.h" #include "WorldPacket.h" #include "WorldSession.h" #include "UpdateData.h" #include "Item.h" #include "Map.h" #include "Transport.h" #include "ObjectAccessor.h" #include "CellImpl.h" #include "SpellInfo.h" using namespace Trinity; void VisibleNotifier::Visit(GameObjectMapType &m) { for (GameObjectMapType::iterator iter = m.begin(); iter != m.end(); ++iter) { if (i_largeOnly != iter->GetSource()->IsVisibilityOverridden()) continue; vis_guids.erase(iter->GetSource()->GetGUID()); i_player.UpdateVisibilityOf(iter->GetSource(), i_data, i_visibleNow); } } void VisibleNotifier::SendToSelf() { // at this moment i_clientGUIDs have guids that not iterate at grid level checks // but exist one case when this possible and object not out of range: transports if (Transport* transport = i_player.GetTransport()) for (Transport::PassengerSet::const_iterator itr = transport->GetPassengers().begin(); itr != transport->GetPassengers().end();++itr) { if (i_largeOnly != (*itr)->IsVisibilityOverridden()) continue; if (vis_guids.find((*itr)->GetGUID()) != vis_guids.end()) { vis_guids.erase((*itr)->GetGUID()); switch ((*itr)->GetTypeId()) { case TYPEID_GAMEOBJECT: i_player.UpdateVisibilityOf((*itr)->ToGameObject(), i_data, i_visibleNow); break; case TYPEID_PLAYER: i_player.UpdateVisibilityOf((*itr)->ToPlayer(), i_data, i_visibleNow); (*itr)->ToPlayer()->UpdateVisibilityOf(&i_player); break; case TYPEID_UNIT: i_player.UpdateVisibilityOf((*itr)->ToCreature(), i_data, i_visibleNow); break; default: break; } } } for (Player::ClientGUIDs::const_iterator it = vis_guids.begin();it != vis_guids.end(); ++it) { if (WorldObject* obj = ObjectAccessor::GetWorldObject(i_player, *it)) if (i_largeOnly != obj->IsVisibilityOverridden()) continue; // pussywizard: static transports are removed only in RemovePlayerFromMap and here if can no longer detect (eg. phase changed) if (IS_TRANSPORT_GUID(*it)) if (GameObject* staticTrans = i_player.GetMap()->GetGameObject(*it)) if (i_player.CanSeeOrDetect(staticTrans, false, true)) continue; i_player.m_clientGUIDs.erase(*it); i_data.AddOutOfRangeGUID(*it); if (IS_PLAYER_GUID(*it)) { Player* player = ObjectAccessor::FindPlayer(*it); if (player && player->IsInMap(&i_player)) player->UpdateVisibilityOf(&i_player); } } if (!i_data.HasData()) return; WorldPacket packet; i_data.BuildPacket(&packet); i_player.GetSession()->SendPacket(&packet); for (std::vector<Unit*>::const_iterator it = i_visibleNow.begin(); it != i_visibleNow.end(); ++it) { if (i_largeOnly != (*it)->IsVisibilityOverridden()) continue; i_player.GetInitialVisiblePackets(*it); } } void VisibleChangesNotifier::Visit(PlayerMapType &m) { for (PlayerMapType::iterator iter = m.begin(); iter != m.end(); ++iter) { if (iter->GetSource() == &i_object) continue; iter->GetSource()->UpdateVisibilityOf(&i_object); if (iter->GetSource()->HasSharedVision()) for (SharedVisionList::const_iterator i = iter->GetSource()->GetSharedVisionList().begin(); i != iter->GetSource()->GetSharedVisionList().end(); ++i) if ((*i)->m_seer == iter->GetSource()) (*i)->UpdateVisibilityOf(&i_object); } } void VisibleChangesNotifier::Visit(CreatureMapType &m) { for (CreatureMapType::iterator iter = m.begin(); iter != m.end(); ++iter) if (iter->GetSource()->HasSharedVision()) for (SharedVisionList::const_iterator i = iter->GetSource()->GetSharedVisionList().begin(); i != iter->GetSource()->GetSharedVisionList().end(); ++i) if ((*i)->m_seer == iter->GetSource()) (*i)->UpdateVisibilityOf(&i_object); } void VisibleChangesNotifier::Visit(DynamicObjectMapType &m) { for (DynamicObjectMapType::iterator iter = m.begin(); iter != m.end(); ++iter) if (IS_PLAYER_GUID(iter->GetSource()->GetCasterGUID())) if (Unit* caster = iter->GetSource()->GetCaster()) if (Player* player = caster->ToPlayer()) if (player->m_seer == iter->GetSource()) player->UpdateVisibilityOf(&i_object); } inline void CreatureUnitRelocationWorker(Creature* c, Unit* u) { if (!u->IsAlive() || !c->IsAlive() || c == u || u->IsInFlight()) return; if (c->HasReactState(REACT_AGGRESSIVE) && !c->HasUnitState(UNIT_STATE_SIGHTLESS)) { if (c->IsAIEnabled && c->CanSeeOrDetect(u, false, true)) { c->AI()->MoveInLineOfSight_Safe(u); } else { if (u->GetTypeId() == TYPEID_PLAYER && u->HasStealthAura() && c->IsAIEnabled && c->CanSeeOrDetect(u, false, true, true)) c->AI()->TriggerAlert(u); } } } void PlayerRelocationNotifier::Visit(PlayerMapType &m) { for (PlayerMapType::iterator iter = m.begin(); iter != m.end(); ++iter) { Player* player = iter->GetSource(); vis_guids.erase(player->GetGUID()); i_player.UpdateVisibilityOf(player, i_data, i_visibleNow); player->UpdateVisibilityOf(&i_player); // this notifier with different Visit(PlayerMapType&) than VisibleNotifier is needed to update visibility of self for other players when we move (eg. stealth detection changes) } } void CreatureRelocationNotifier::Visit(PlayerMapType &m) { for (PlayerMapType::iterator iter = m.begin(); iter != m.end(); ++iter) { Player* player = iter->GetSource(); // NOTIFY_VISIBILITY_CHANGED does not guarantee that player will do it himself (because distance is also checked), but screw it, it's not that important if (!player->m_seer->isNeedNotify(NOTIFY_VISIBILITY_CHANGED)) player->UpdateVisibilityOf(&i_creature); // NOTIFY_AI_RELOCATION does not guarantee that player will do it himself (because distance is also checked), but screw it, it's not that important if (!player->m_seer->isNeedNotify(NOTIFY_AI_RELOCATION) && !i_creature.IsMoveInLineOfSightStrictlyDisabled()) CreatureUnitRelocationWorker(&i_creature, player); } } void AIRelocationNotifier::Visit(CreatureMapType &m) { bool self = isCreature && !((Creature*)(&i_unit))->IsMoveInLineOfSightStrictlyDisabled(); for (CreatureMapType::iterator iter = m.begin(); iter != m.end(); ++iter) { Creature* c = iter->GetSource(); // NOTIFY_VISIBILITY_CHANGED | NOTIFY_AI_RELOCATION does not guarantee that unit will do it itself (because distance is also checked), but screw it, it's not that important if (!c->isNeedNotify(NOTIFY_VISIBILITY_CHANGED | NOTIFY_AI_RELOCATION) && !c->IsMoveInLineOfSightStrictlyDisabled()) CreatureUnitRelocationWorker(c, &i_unit); if (self) CreatureUnitRelocationWorker((Creature*)&i_unit, c); } } void MessageDistDeliverer::Visit(PlayerMapType &m) { for (PlayerMapType::iterator iter = m.begin(); iter != m.end(); ++iter) { Player* target = iter->GetSource(); if (!target->InSamePhase(i_phaseMask)) continue; if (target->GetExactDist2dSq(i_source) > i_distSq) continue; // Send packet to all who are sharing the player's vision if (target->HasSharedVision()) { SharedVisionList::const_iterator i = target->GetSharedVisionList().begin(); for (; i != target->GetSharedVisionList().end(); ++i) if ((*i)->m_seer == target) SendPacket(*i); } if (target->m_seer == target || target->GetVehicle()) SendPacket(target); } } void MessageDistDeliverer::Visit(CreatureMapType &m) { for (CreatureMapType::iterator iter = m.begin(); iter != m.end(); ++iter) { Creature* target = iter->GetSource(); if (!target->HasSharedVision() || !target->InSamePhase(i_phaseMask)) continue; if (target->GetExactDist2dSq(i_source) > i_distSq) continue; // Send packet to all who are sharing the creature's vision SharedVisionList::const_iterator i = target->GetSharedVisionList().begin(); for (; i != target->GetSharedVisionList().end(); ++i) if ((*i)->m_seer == target) SendPacket(*i); } } void MessageDistDeliverer::Visit(DynamicObjectMapType &m) { for (DynamicObjectMapType::iterator iter = m.begin(); iter != m.end(); ++iter) { DynamicObject* target = iter->GetSource(); if (!IS_PLAYER_GUID(target->GetCasterGUID()) || !target->InSamePhase(i_phaseMask)) continue; // Xinef: Check whether the dynobject allows to see through it if (!target->IsViewpoint()) continue; if (target->GetExactDist2dSq(i_source) > i_distSq) continue; // Send packet back to the caster if the caster has vision of dynamic object Player* caster = (Player*)target->GetCaster(); if (caster && caster->m_seer == target) SendPacket(caster); } } void MessageDistDelivererToHostile::Visit(PlayerMapType &m) { for (PlayerMapType::iterator iter = m.begin(); iter != m.end(); ++iter) { Player* target = iter->GetSource(); if (!target->InSamePhase(i_phaseMask)) continue; if (target->GetExactDist2dSq(i_source) > i_distSq) continue; // Send packet to all who are sharing the player's vision if (target->HasSharedVision()) { SharedVisionList::const_iterator i = target->GetSharedVisionList().begin(); for (; i != target->GetSharedVisionList().end(); ++i) if ((*i)->m_seer == target) SendPacket(*i); } if (target->m_seer == target || target->GetVehicle()) SendPacket(target); } } void MessageDistDelivererToHostile::Visit(CreatureMapType &m) { for (CreatureMapType::iterator iter = m.begin(); iter != m.end(); ++iter) { Creature* target = iter->GetSource(); if (!target->HasSharedVision() || !target->InSamePhase(i_phaseMask)) continue; if (target->GetExactDist2dSq(i_source) > i_distSq) continue; // Send packet to all who are sharing the creature's vision SharedVisionList::const_iterator i = target->GetSharedVisionList().begin(); for (; i != target->GetSharedVisionList().end(); ++i) if ((*i)->m_seer == target) SendPacket(*i); } } void MessageDistDelivererToHostile::Visit(DynamicObjectMapType &m) { for (DynamicObjectMapType::iterator iter = m.begin(); iter != m.end(); ++iter) { DynamicObject* target = iter->GetSource(); if (!IS_PLAYER_GUID(target->GetCasterGUID()) || !target->InSamePhase(i_phaseMask)) continue; if (target->GetExactDist2dSq(i_source) > i_distSq) continue; // Send packet back to the caster if the caster has vision of dynamic object Player* caster = (Player*)target->GetCaster(); if (caster && caster->m_seer == target) SendPacket(caster); } } template<class T> void ObjectUpdater::Visit(GridRefManager<T> &m) { T* obj; for (typename GridRefManager<T>::iterator iter = m.begin(); iter != m.end(); ) { obj = iter->GetSource(); ++iter; if (obj->IsInWorld()) obj->Update(i_timeDiff); } } template<class T> void LargeObjectUpdater::Visit(GridRefManager<T> &m) { T* obj; for (typename GridRefManager<T>::iterator iter = m.begin(); iter != m.end(); ) { obj = iter->GetSource(); ++iter; if (obj->IsInWorld() && obj->IsVisibilityOverridden()) obj->Update(i_timeDiff); } } bool AnyDeadUnitObjectInRangeCheck::operator()(Player* u) { return !u->IsAlive() && !u->HasAuraType(SPELL_AURA_GHOST) && i_searchObj->IsWithinDistInMap(u, i_range); } bool AnyDeadUnitObjectInRangeCheck::operator()(Corpse* u) { return u->GetType() != CORPSE_BONES && i_searchObj->IsWithinDistInMap(u, i_range); } bool AnyDeadUnitObjectInRangeCheck::operator()(Creature* u) { return !u->IsAlive() && i_searchObj->IsWithinDistInMap(u, i_range); } bool AnyDeadUnitSpellTargetInRangeCheck::operator()(Player* u) { return AnyDeadUnitObjectInRangeCheck::operator()(u) && i_check(u); } bool AnyDeadUnitSpellTargetInRangeCheck::operator()(Corpse* u) { return AnyDeadUnitObjectInRangeCheck::operator()(u) && i_check(u); } bool AnyDeadUnitSpellTargetInRangeCheck::operator()(Creature* u) { return AnyDeadUnitObjectInRangeCheck::operator()(u) && i_check(u); } template void ObjectUpdater::Visit<Creature>(CreatureMapType&); template void ObjectUpdater::Visit<GameObject>(GameObjectMapType&); template void ObjectUpdater::Visit<DynamicObject>(DynamicObjectMapType&); template void LargeObjectUpdater::Visit<Creature>(CreatureMapType&); <|endoftext|>
<commit_before>/* * 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. * * Written (W) 2010 Koen van de Sande * Copyright (C) 2010 Koen van de Sande / University of Amsterdam */ #include <shogun/lib/common.h> #include <shogun/kernel/HistogramIntersectionKernel.h> #include <shogun/features/Features.h> #include <shogun/features/SimpleFeatures.h> #include <shogun/io/SGIO.h> using namespace shogun; CHistogramIntersectionKernel::CHistogramIntersectionKernel() : CDotKernel(0), m_beta(1.0) { register_params(); } CHistogramIntersectionKernel::CHistogramIntersectionKernel(int32_t size) : CDotKernel(size), m_beta(1.0) { register_params(); } CHistogramIntersectionKernel::CHistogramIntersectionKernel( CSimpleFeatures<float64_t>* l, CSimpleFeatures<float64_t>* r, float64_t beta, int32_t size) : CDotKernel(size), m_beta(1.0) { init(l,r); register_params(); } CHistogramIntersectionKernel::~CHistogramIntersectionKernel() { cleanup(); } bool CHistogramIntersectionKernel::init(CFeatures* l, CFeatures* r) { bool result=CDotKernel::init(l,r); init_normalizer(); return result; } float64_t CHistogramIntersectionKernel::compute(int32_t idx_a, int32_t idx_b) { int32_t alen, blen; bool afree, bfree; float64_t* avec= ((CSimpleFeatures<float64_t>*) lhs)->get_feature_vector(idx_a, alen, afree); float64_t* bvec= ((CSimpleFeatures<float64_t>*) rhs)->get_feature_vector(idx_b, blen, bfree); ASSERT(alen==blen); float64_t result=0; // checking if beta is default or not if (m_beta == 1.0) { // compute standard histogram intersection kernel for (int32_t i=0; i<alen; i++) result += (avec[i] < bvec[i]) ? avec[i] : bvec[i]; } else { //compute generalized histogram intersection kernel for (int32_t i=0; i<alen; i++) result += CMath::min(CMath::pow(avec[i],m_beta), CMath::pow(bvec[i],m_beta)); } ((CSimpleFeatures<float64_t>*) lhs)->free_feature_vector(avec, idx_a, afree); ((CSimpleFeatures<float64_t>*) rhs)->free_feature_vector(bvec, idx_b, bfree); return result; } void CHistogramIntersectionKernel::register_params() { m_parameters->add(&m_beta, "beta", "the beta parameter of the kernel"); } <commit_msg>Fix beta parameter passing via constructor in HIK<commit_after>/* * 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. * * Written (W) 2010 Koen van de Sande * Copyright (C) 2010 Koen van de Sande / University of Amsterdam */ #include <shogun/lib/common.h> #include <shogun/kernel/HistogramIntersectionKernel.h> #include <shogun/features/Features.h> #include <shogun/features/SimpleFeatures.h> #include <shogun/io/SGIO.h> using namespace shogun; CHistogramIntersectionKernel::CHistogramIntersectionKernel() : CDotKernel(0), m_beta(1.0) { register_params(); } CHistogramIntersectionKernel::CHistogramIntersectionKernel(int32_t size) : CDotKernel(size), m_beta(1.0) { register_params(); } CHistogramIntersectionKernel::CHistogramIntersectionKernel( CSimpleFeatures<float64_t>* l, CSimpleFeatures<float64_t>* r, float64_t beta, int32_t size) : CDotKernel(size), m_beta(beta) { init(l,r); register_params(); } CHistogramIntersectionKernel::~CHistogramIntersectionKernel() { cleanup(); } bool CHistogramIntersectionKernel::init(CFeatures* l, CFeatures* r) { bool result=CDotKernel::init(l,r); init_normalizer(); return result; } float64_t CHistogramIntersectionKernel::compute(int32_t idx_a, int32_t idx_b) { int32_t alen, blen; bool afree, bfree; float64_t* avec= ((CSimpleFeatures<float64_t>*) lhs)->get_feature_vector(idx_a, alen, afree); float64_t* bvec= ((CSimpleFeatures<float64_t>*) rhs)->get_feature_vector(idx_b, blen, bfree); ASSERT(alen==blen); float64_t result=0; // checking if beta is default or not if (m_beta == 1.0) { // compute standard histogram intersection kernel for (int32_t i=0; i<alen; i++) result += (avec[i] < bvec[i]) ? avec[i] : bvec[i]; } else { //compute generalized histogram intersection kernel for (int32_t i=0; i<alen; i++) result += CMath::min(CMath::pow(avec[i],m_beta), CMath::pow(bvec[i],m_beta)); } ((CSimpleFeatures<float64_t>*) lhs)->free_feature_vector(avec, idx_a, afree); ((CSimpleFeatures<float64_t>*) rhs)->free_feature_vector(bvec, idx_b, bfree); return result; } void CHistogramIntersectionKernel::register_params() { m_parameters->add(&m_beta, "beta", "the beta parameter of the kernel"); } <|endoftext|>
<commit_before> #include "fetchURL.h" void FetchURL::callExtension(const char * output, int outputSize, const char * function) {}; void FetchURL::startGETThread(std::string function) {}; void FetchURL::startPOSTThread(std::string function, std::string parameters) {}; void FetchURL::fetchResultGET(std::string * function) {}; void FetchURL::fetchResultPOST(std::string * function, std::string * parameters) {}; int FetchURL::returnStatus(int key) { std::vector<FetchResult> res = results; if (res.empty()) return 0; for (int i = 0; i < res.size(); i++) { if (res[i].key == key) { if (res[i].finished) return 1; else return 0; } }; }; std::string FetchURL::returnResult(int key) {}; <commit_msg>Changed fetchURL.cpp<commit_after> #include "fetchURL.h" void FetchURL::callExtension(const char * output, int outputSize, const char * function) {}; void FetchURL::startGETThread(std::string function) {}; void FetchURL::startPOSTThread(std::string function, std::string parameters) {}; void FetchURL::fetchResultGET(std::string * function) {}; void FetchURL::fetchResultPOST(std::string * function, std::string * parameters) {}; int FetchURL::returnStatus(int key) { std::lock_guard<std::mutex> lock(results_lock); if (results.empty()) return 0; for (int i = 0; i < results.size(); i++) { if (results[i].key == key) { if (results[i].finished) return 1; else return 0; } } }; std::string FetchURL::returnResult(int key) {}; <|endoftext|>
<commit_before>#include <random> #include <algorithm> #include <string> #include <fstream> #include <sstream> #include <chrono> #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include <getopt.h> #include "eval.h" #include "util.h" void usage() { int index = 0; bch code(5, 0x25, 7); std::cout << "--algorithm <num>" << " " << "Choose algorithm:" << std::endl; for (const auto &algorithm : get_algorithms<0>(code)) std::cout << " [" << index++ << "] " << algorithm.first << std::endl; std::cout << "--k <num> " << " " << "Choose code length n = 2^k - 1." << std::endl; std::cout << "--dmin <num " << " " << "Choose dmin of the code." << std::endl; std::cout << "--seed <num> " << " " << "Set seed of the random number generator." << std::endl; exit(-1); } int main(int argc, char *const argv[]) { constexpr size_t max_iterations = 50; constexpr float eb_no_max = 10; constexpr float eb_no_step = 0.1f; constexpr unsigned base_trials = 10000; std::vector<int> indices; int k; int dmin; typename std::mt19937_64::result_type seed = 0; // std::chrono::high_resolution_clock::now().time_since_epoch().count(); while (1) { static struct option options[] = { { "algorithm", required_argument, nullptr, 'a' }, { "k", required_argument, nullptr, 'k' }, { "dmin", required_argument, nullptr, 'd' }, { "seed", required_argument, nullptr, 's' }, { nullptr, 0, nullptr, 0 }, }; int option_index = 0; int c = getopt_long_only(argc, argv, "", options, &option_index); if (c == -1) break; switch (c) { case 'a': indices.push_back(strtoul(optarg, nullptr, 0)); break; case 'k': k = strtoul(optarg, nullptr, 0); break; case 'd': dmin = strtoul(optarg, nullptr, 0); break; case 's': seed = strtoull(optarg, nullptr, 0); break; default: std::cerr << "Unkown argument: " << c << " " << std::endl; usage(); } } bool fail = false; if (indices.size() == 0) { std::cerr << "Algorithm not set." << std::endl; fail = true; } if (!k) { std::cerr << "k not set." << std::endl; fail = true; } if (!dmin) { std::cerr << "dmin not set." << std::endl; fail = true; } if (fail) usage(); bch code(k, primitive_polynomial(k), dmin); std::mt19937_64 generator; auto parameters = code.parameters(); auto simulator = std::bind(evaluate, generator, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::get<1>(parameters), std::get<1>(parameters), std::get<2>(parameters)); auto algorithms = get_algorithms<max_iterations>(code); auto num_samples = [=](const double ber) { return std::min(1000 * 1 / ber, 10e6); // return std::min(base_trials * pow(10, eb_no / 2), 10e6); }; auto run_algorithm = [&](const auto &algorithm) { const auto &name = algorithm.first; const auto &decoder = algorithm.second; std::ostringstream os; os << name << "_" << std::get<1>(parameters) << "_" << std::get<1>(parameters) << "_" << std::get<2>(parameters); std::string fname(os.str()); if (file_exists(fname)) { std::cout << "File " << fname << " already exists." << std::endl; return; } std::ofstream file(fname.c_str(), std::ofstream::out); file << "eb_no " << eval_object::header() << std::endl; generator.seed(seed); double wer = 0.5; for (double eb_no = 0; eb_no < eb_no_max; eb_no += eb_no_step) { auto samples = num_samples(wer); std::cout << "Calculating for E_b/N_0 = " << eb_no << " with " << samples << " … "; std::cout.flush(); auto start = std::chrono::high_resolution_clock::now(); auto result = simulator(decoder, samples, eb_no); auto end = std::chrono::high_resolution_clock::now(); auto seconds = std::chrono::duration_cast<std::chrono::seconds>(end - start).count(); std::cout << seconds << " s" << std::endl; wer = result.wer(); file << std::setprecision(1) << eb_no << " "; file << result; file << std::endl; } }; const auto index = 8; if (index < algorithms.size()) { std::cout << "Running algorithm " << algorithms.at(index).first << std::endl; run_algorithm(algorithms.at(index)); } else { std::cout << "Index " << index << " is out of range. Choose from:" << std::endl; unsigned i = 0; for (const auto &algorithm : algorithms) std::cout << "[" << i++ << "] " << algorithm.first << std::endl; } } <commit_msg>Simplify code<commit_after>#include <random> #include <algorithm> #include <string> #include <fstream> #include <sstream> #include <chrono> #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include <getopt.h> #include "eval.h" #include "util.h" void usage() { std::cout << "--k <num> " << " " << "Choose code length n = 2^k - 1." << std::endl; std::cout << "--dmin <num " << " " << "Choose dmin of the code." << std::endl; std::cout << "--seed <num> " << " " << "Set seed of the random number generator." << std::endl; exit(-1); } int main(int argc, char *const argv[]) { constexpr float eb_no_max = 10; constexpr float eb_no_step = 0.1f; int k; int dmin; typename std::mt19937_64::result_type seed = 0; // std::chrono::high_resolution_clock::now().time_since_epoch().count(); while (1) { static struct option options[] = { { "k", required_argument, nullptr, 'k' }, { "dmin", required_argument, nullptr, 'd' }, { "seed", required_argument, nullptr, 's' }, { nullptr, 0, nullptr, 0 }, }; int option_index = 0; int c = getopt_long_only(argc, argv, "", options, &option_index); if (c == -1) break; switch (c) { case 'k': k = strtoul(optarg, nullptr, 0); break; case 'd': dmin = strtoul(optarg, nullptr, 0); break; case 's': seed = strtoull(optarg, nullptr, 0); break; default: std::cerr << "Unkown argument: " << c << " " << std::endl; usage(); } } bool fail = false; if (!k) { std::cerr << "k not set." << std::endl; fail = true; } if (!dmin) { std::cerr << "dmin not set." << std::endl; fail = true; } if (fail) usage(); bch code(k, primitive_polynomial(k), dmin); std::mt19937_64 generator; auto parameters = code.parameters(); auto simulator = std::bind(evaluate, generator, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::get<1>(parameters), std::get<1>(parameters), std::get<2>(parameters)); auto num_samples = [=](const double ber) { return std::min(1000 * 1 / ber, 10e6); // return std::min(base_trials * pow(10, eb_no / 2), 10e6); }; auto run_algorithm = [&](const auto &algorithm) { const auto &name = algorithm.first; const auto &decoder = algorithm.second; std::ostringstream os; os << name << "_" << std::get<1>(parameters) << "_" << std::get<1>(parameters) << "_" << std::get<2>(parameters); std::string fname(os.str()); if (file_exists(fname)) { std::cout << "File " << fname << " already exists." << std::endl; return; } std::ofstream file(fname.c_str(), std::ofstream::out); file << "eb_no " << eval_object::header() << std::endl; generator.seed(seed); double wer = 0.5; for (double eb_no = 0; eb_no < eb_no_max; eb_no += eb_no_step) { auto samples = num_samples(wer); std::cout << "Calculating for E_b/N_0 = " << eb_no << " with " << samples << " … "; std::cout.flush(); auto start = std::chrono::high_resolution_clock::now(); auto result = simulator(decoder, samples, eb_no); auto end = std::chrono::high_resolution_clock::now(); auto seconds = std::chrono::duration_cast<std::chrono::seconds>(end - start).count(); std::cout << seconds << " s" << std::endl; wer = result.wer(); file << std::setprecision(1) << eb_no << " "; file << result; file << std::endl; } }; const auto &uncoded = get_algorithms<0>(code).back(); std::cout << "Running algorithm " << uncoded.first << std::endl; run_algorithm(uncoded); } <|endoftext|>
<commit_before>/* * Copyright (C) 2009-2010, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ /// \file libuvalue/ubinary.cc #include <iostream> #include <sstream> #include <libport/debug.hh> #include <libport/escape.hh> #include <urbi/ubinary.hh> #include <boost/algorithm/string/trim.hpp> GD_CATEGORY(UValue); namespace urbi { UBinary::UBinary() : type(BINARY_NONE) , allocated_(true) { common.data = 0; common.size = 0; } UBinary::UBinary(const UBinary& b, bool copy) : type(BINARY_NONE) , allocated_(copy) { common.data = 0; if (copy) *this = b; else { // Be safe, do not try to guess which is bigger. image = b.image; sound = b.sound; message = b.message; type = b.type; } } UBinary::UBinary(const UImage& i, bool copy) : type(BINARY_IMAGE) , image(i) , allocated_(copy) { if (copy) { image.data = static_cast<unsigned char*> (malloc (image.size)); memcpy(image.data, i.data, image.size); } } UBinary::UBinary(const USound& i, bool copy) : type(BINARY_SOUND) , sound(i) , allocated_(copy) { if (copy) { sound.data = static_cast<char*> (malloc (sound.size)); memcpy(sound.data, i.data, sound.size); } } void UBinary::clear() { if (allocated_) free(common.data); } UBinary::~UBinary() { clear(); } UBinary& UBinary::operator= (const UBinary& b) { if (this == &b) return *this; clear(); type = b.type; message = b.message; common.size = b.common.size; switch(type) { case BINARY_IMAGE: image = b.image; break; case BINARY_SOUND: sound = b.sound; break; case BINARY_NONE: case BINARY_UNKNOWN: break; } common.data = malloc(common.size); memcpy(common.data, b.common.data, b.common.size); return *this; } int UBinary::parse(const char* message, int pos, const binaries_type& bins, binaries_type::const_iterator& binpos, bool copy) { std::istringstream is(message + pos); bool ok = parse(is, bins, binpos, copy); // tellg() might be -1 if we encountered an error. int endpos = is.tellg(); if (endpos == -1) endpos = strlen(message) - pos; return (ok ? 1:-1) * (pos + endpos); } namespace { /// Return everything up to the next "\n" or "\n\r" or ";", not included. /// Leave \a i after that delimiter. /// Return empty string on errors. static std::string headers_get(std::istringstream& i) { std::string res; int c = 0; while (!i.eof() && (c = i.get()) && c != '\n' && c != ';') res.append(1, c); if (i.eof()) GD_ERROR("unexpected end of file while parsing UBinary headers"); else { // Skip the delimiter. if (c == '\n') { i.ignore(); if (i.peek() == '\r') i.ignore(); } else i.ignore(); } // Remove leading/trailing spaces. boost::algorithm::trim(res); return res; } } bool UBinary::parse(std::istringstream& is, const binaries_type& bins, binaries_type::const_iterator& binpos, bool copy) { // LIBPORT_ECHO("Parsing: {" << is.str() << "}"); if (binpos == bins.end()) { GD_ERROR("no binary data available"); return false; } // Validate size. size_t psize; is >> psize; if (is.fail()) { GD_FERROR("cannot read bin size: %s (%s)", is.str(), psize); return false; } if (psize != binpos->size) { GD_FERROR("bin size inconsistency: %s != %s", psize, binpos->size); return false; } common.size = psize; if (copy) { common.data = malloc(common.size); memcpy(common.data, binpos->data, common.size); } else { common.data = binpos->data; this->allocated_ = false; } ++binpos; // Skip spaces. while (is.peek() == ' ') is.ignore(); // Get the headers. message = headers_get(is); // Analyse the header to decode know UBinary types. // Header stream. std::istringstream hs(message); // Parse the optional type. Don't check hs.fail, since the type // is optional, in which case t remains empty. std::string t; hs >> t; UImageFormat image_format = parse_image_format(t); if (image_format != IMAGE_UNKNOWN || t.find("image_")==0) { type = BINARY_IMAGE; image.size = common.size; // In some cases (jpeg source), image size is not present in headers. image.width = image.height = 0; hs >> image.width >> image.height; image.imageFormat = image_format; } else if (t == "raw" || t == "wav") { type = BINARY_SOUND; sound.soundFormat = parse_sound_format(t); sound.size = common.size; hs >> sound.channels >> sound.rate >> sound.sampleSize >> sound.sampleFormat; } else { // GD_FWARN("unknown binary type: %s", t); type = BINARY_UNKNOWN; } return true; } void UBinary::buildMessage() { message = getMessage(); } std::string UBinary::getMessage() const { switch (type) { case BINARY_IMAGE: return image.headers_(); case BINARY_SOUND: return sound.headers_(); case BINARY_UNKNOWN: { bool warned = false; std::string res = message; foreach (char& c, res) if (c == '\0' || c == '\n' || c == ';') { if (!warned++) GD_FERROR("invalid UBinary header: " "prohibited `\\n', `\\0' and `;' will be " "smashed to space: %s", libport::escape(message)); c = ' '; } // Remove leading/trailing spaces. boost::algorithm::trim(res); return res; } case BINARY_NONE: return ""; } unreachable(); } std::ostream& UBinary::print(std::ostream& o) const { // Format for the Kernel, which wants ';' as header terminator. o << "BIN "<< common.size << ' ' << getMessage() << ';'; o.write((char*) common.data, common.size); return o; } std::ostream& operator<< (std::ostream& o, const UBinary& t) { return t.print(o); } } // namespace urbi <commit_msg>uvalue: Fix Binary header parsing.<commit_after>/* * Copyright (C) 2009-2010, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ /// \file libuvalue/ubinary.cc #include <iostream> #include <sstream> #include <libport/debug.hh> #include <libport/escape.hh> #include <urbi/ubinary.hh> #include <boost/algorithm/string/trim.hpp> GD_CATEGORY(UValue); namespace urbi { UBinary::UBinary() : type(BINARY_NONE) , allocated_(true) { common.data = 0; common.size = 0; } UBinary::UBinary(const UBinary& b, bool copy) : type(BINARY_NONE) , allocated_(copy) { common.data = 0; if (copy) *this = b; else { // Be safe, do not try to guess which is bigger. image = b.image; sound = b.sound; message = b.message; type = b.type; } } UBinary::UBinary(const UImage& i, bool copy) : type(BINARY_IMAGE) , image(i) , allocated_(copy) { if (copy) { image.data = static_cast<unsigned char*> (malloc (image.size)); memcpy(image.data, i.data, image.size); } } UBinary::UBinary(const USound& i, bool copy) : type(BINARY_SOUND) , sound(i) , allocated_(copy) { if (copy) { sound.data = static_cast<char*> (malloc (sound.size)); memcpy(sound.data, i.data, sound.size); } } void UBinary::clear() { if (allocated_) free(common.data); } UBinary::~UBinary() { clear(); } UBinary& UBinary::operator= (const UBinary& b) { if (this == &b) return *this; clear(); type = b.type; message = b.message; common.size = b.common.size; switch(type) { case BINARY_IMAGE: image = b.image; break; case BINARY_SOUND: sound = b.sound; break; case BINARY_NONE: case BINARY_UNKNOWN: break; } common.data = malloc(common.size); memcpy(common.data, b.common.data, b.common.size); return *this; } int UBinary::parse(const char* message, int pos, const binaries_type& bins, binaries_type::const_iterator& binpos, bool copy) { std::istringstream is(message + pos); bool ok = parse(is, bins, binpos, copy); // tellg() might be -1 if we encountered an error. int endpos = is.tellg(); if (endpos == -1) endpos = strlen(message) - pos; return (ok ? 1:-1) * (pos + endpos); } namespace { /// Return everything up to the next "\n" or "\n\r" or ";", not included. /// Leave \a i after that delimiter. /// Return empty string on errors. static std::string headers_get(std::istringstream& i) { std::string res; int c = 0; while (!i.eof() && (c = i.get()) && c != '\n' && c != ';') res.append(1, c); if (i.eof()) GD_ERROR("unexpected end of file while parsing UBinary headers"); else { // Skip the delimiter. if (c == '\n') { if (i.peek() == '\r') i.ignore(); } } // Remove leading/trailing spaces. boost::algorithm::trim(res); return res; } } bool UBinary::parse(std::istringstream& is, const binaries_type& bins, binaries_type::const_iterator& binpos, bool copy) { // LIBPORT_ECHO("Parsing: {" << is.str() << "}"); if (binpos == bins.end()) { GD_ERROR("no binary data available"); return false; } // Validate size. size_t psize; is >> psize; if (is.fail()) { GD_FERROR("cannot read bin size: %s (%s)", is.str(), psize); return false; } if (psize != binpos->size) { GD_FERROR("bin size inconsistency: %s != %s", psize, binpos->size); return false; } common.size = psize; if (copy) { common.data = malloc(common.size); memcpy(common.data, binpos->data, common.size); } else { common.data = binpos->data; this->allocated_ = false; } ++binpos; // Skip spaces. while (is.peek() == ' ') is.ignore(); // Get the headers. message = headers_get(is); // Analyse the header to decode know UBinary types. // Header stream. std::istringstream hs(message); // Parse the optional type. Don't check hs.fail, since the type // is optional, in which case t remains empty. std::string t; hs >> t; UImageFormat image_format = parse_image_format(t); if (image_format != IMAGE_UNKNOWN || t.find("image_")==0) { type = BINARY_IMAGE; image.size = common.size; // In some cases (jpeg source), image size is not present in headers. image.width = image.height = 0; hs >> image.width >> image.height; image.imageFormat = image_format; } else if (t == "raw" || t == "wav") { type = BINARY_SOUND; sound.soundFormat = parse_sound_format(t); sound.size = common.size; hs >> sound.channels >> sound.rate >> sound.sampleSize >> sound.sampleFormat; } else { // GD_FWARN("unknown binary type: %s", t); type = BINARY_UNKNOWN; } return true; } void UBinary::buildMessage() { message = getMessage(); } std::string UBinary::getMessage() const { switch (type) { case BINARY_IMAGE: return image.headers_(); case BINARY_SOUND: return sound.headers_(); case BINARY_UNKNOWN: { bool warned = false; std::string res = message; foreach (char& c, res) if (c == '\0' || c == '\n' || c == ';') { if (!warned++) GD_FERROR("invalid UBinary header: " "prohibited `\\n', `\\0' and `;' will be " "smashed to space: %s", libport::escape(message)); c = ' '; } // Remove leading/trailing spaces. boost::algorithm::trim(res); return res; } case BINARY_NONE: return ""; } unreachable(); } std::ostream& UBinary::print(std::ostream& o) const { // Format for the Kernel, which wants ';' as header terminator. o << "BIN "<< common.size << ' ' << getMessage() << ';'; o.write((char*) common.data, common.size); return o; } std::ostream& operator<< (std::ostream& o, const UBinary& t) { return t.print(o); } } // namespace urbi <|endoftext|>
<commit_before>/* Copyright 2015-2019 Igor Petrovic 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 "board/Board.h" #include "board/common/constants/LEDs.h" #include "board/common/digital/Output.h" #include "board/common/Map.h" #include "core/src/general/BitManipulation.h" #include "Pins.h" #include "interface/digital/output/leds/Helpers.h" #ifndef BOARD_A_xu2 #include "interface/digital/output/leds/LEDs.h" #endif #ifdef LED_INDICATORS namespace { /// /// \brief Variables used to control the time MIDI in/out LED indicators on board are active. /// When these LEDs need to be turned on, variables are set to value representing time in /// milliseconds during which they should be on. ISR decreases variable value by 1 every 1 millsecond. /// Once the variables have value 0, specific LED indicator is turned off. /// @{ volatile uint8_t midiIn_timeout; volatile uint8_t midiOut_timeout; /// @} } // namespace #endif #ifndef BOARD_A_xu2 namespace { volatile uint8_t pwmSteps; volatile int8_t transitionCounter[MAX_NUMBER_OF_LEDS]; /// /// \brief Array holding values needed to achieve more natural LED transition between states. /// const uint8_t ledTransitionScale[NUMBER_OF_LED_TRANSITIONS] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 30, 33, 36, 40, 44, 48, 52, 57, 62, 68, 74, 81, 89, 97, 106, 115, 126, 138, 150, 164, 179, 195, 213, 255 }; #ifdef NUMBER_OF_LED_COLUMNS /// /// \brief Holds value of currently active output matrix column. /// volatile uint8_t activeOutColumn; #endif } // namespace #endif namespace Board { namespace interface { namespace digital { namespace output { #ifndef BOARD_A_xu2 #ifdef LEDS_SUPPORTED bool setLEDfadeSpeed(uint8_t transitionSpeed) { if (transitionSpeed > FADE_TIME_MAX) { return false; } //reset transition counter #ifdef __AVR__ ATOMIC_BLOCK(ATOMIC_RESTORESTATE) #endif { for (int i = 0; i < MAX_NUMBER_OF_LEDS; i++) transitionCounter[i] = 0; pwmSteps = transitionSpeed; } return true; } uint8_t getRGBaddress(uint8_t rgbID, Interface::digital::output::LEDs::rgbIndex_t index) { #ifdef NUMBER_OF_LED_COLUMNS uint8_t column = rgbID % NUMBER_OF_LED_COLUMNS; uint8_t row = (rgbID / NUMBER_OF_LED_COLUMNS) * 3; uint8_t address = column + NUMBER_OF_LED_COLUMNS * row; switch (index) { case Interface::digital::output::LEDs::rgbIndex_t::r: return address; case Interface::digital::output::LEDs::rgbIndex_t::g: return address + NUMBER_OF_LED_COLUMNS * 1; case Interface::digital::output::LEDs::rgbIndex_t::b: return address + NUMBER_OF_LED_COLUMNS * 2; } return 0; #else return rgbID * 3 + static_cast<uint8_t>(index); #endif } uint8_t getRGBID(uint8_t ledID) { #ifdef NUMBER_OF_LED_COLUMNS uint8_t row = ledID / NUMBER_OF_LED_COLUMNS; uint8_t mod = row % 3; row -= mod; uint8_t column = ledID % NUMBER_OF_LED_COLUMNS; uint8_t result = (row * NUMBER_OF_LED_COLUMNS) / 3 + column; if (result >= MAX_NUMBER_OF_RGB_LEDS) return MAX_NUMBER_OF_RGB_LEDS - 1; else return result; #else uint8_t result = ledID / 3; if (result >= MAX_NUMBER_OF_RGB_LEDS) return MAX_NUMBER_OF_RGB_LEDS - 1; else return result; #endif } #endif #endif namespace detail { #ifdef LED_INDICATORS void checkIndicators() { if (Board::USB::trafficIndicator.received || Board::UART::trafficIndicator.received) { INT_LED_ON(LED_IN_PORT, LED_IN_PIN); Board::USB::trafficIndicator.received = false; Board::UART::trafficIndicator.received = false; midiIn_timeout = MIDI_INDICATOR_TIMEOUT; } if (midiIn_timeout) midiIn_timeout--; else INT_LED_OFF(LED_IN_PORT, LED_IN_PIN); if (Board::USB::trafficIndicator.sent || Board::UART::trafficIndicator.sent) { INT_LED_ON(LED_OUT_PORT, LED_OUT_PIN); Board::USB::trafficIndicator.sent = false; Board::UART::trafficIndicator.sent = false; midiOut_timeout = MIDI_INDICATOR_TIMEOUT; } if (midiOut_timeout) midiOut_timeout--; else INT_LED_OFF(LED_OUT_PORT, LED_OUT_PIN); } #endif #ifndef BOARD_A_xu2 #ifdef NUMBER_OF_LED_COLUMNS /// /// \brief Switches to next LED matrix column. /// inline void activateOutputColumn() { BIT_READ(activeOutColumn, 0) ? CORE_AVR_PIN_SET_HIGH(DEC_LM_A0_PORT, DEC_LM_A0_PIN) : CORE_AVR_PIN_SET_LOW(DEC_LM_A0_PORT, DEC_LM_A0_PIN); BIT_READ(activeOutColumn, 1) ? CORE_AVR_PIN_SET_HIGH(DEC_LM_A1_PORT, DEC_LM_A1_PIN) : CORE_AVR_PIN_SET_LOW(DEC_LM_A1_PORT, DEC_LM_A1_PIN); BIT_READ(activeOutColumn, 2) ? CORE_AVR_PIN_SET_HIGH(DEC_LM_A2_PORT, DEC_LM_A2_PIN) : CORE_AVR_PIN_SET_LOW(DEC_LM_A2_PORT, DEC_LM_A2_PIN); } namespace { core::CORE_ARCH::pins::mcuPin_t pin; uint8_t ledNumber; uint8_t ledStateSingle; } // namespace /// /// \brief Used to turn the given LED row off. /// inline void ledRowOff(uint8_t row) { #ifdef LED_FADING //turn off pwm core::CORE_ARCH::pins::pwmOff(Board::map::pwmChannel(row)); #endif pin = Board::map::led(row); EXT_LED_OFF(*pin.port, pin.pin); } /// /// \brief Used to turn the given LED row on. /// If led fading is supported on board, intensity must be specified as well. /// inline void ledRowOn(uint8_t row #ifdef LED_FADING , uint8_t intensity #endif ) { #ifdef LED_FADING if (intensity == 255) #endif { pin = Board::map::led(row); //max value, don't use pwm EXT_LED_ON(*pin.port, pin.pin); } #ifdef LED_FADING else { #ifdef LED_EXT_INVERT intensity = 255 - intensity; #endif core::CORE_ARCH::pins::pwmOn(Board::map::pwmChannel(row), intensity); } #endif } void checkDigitalOutputs() { for (int i = 0; i < NUMBER_OF_LED_ROWS; i++) ledRowOff(i); activateOutputColumn(); //if there is an active LED in current column, turn on LED row //do fancy transitions here for (int i = 0; i < NUMBER_OF_LED_ROWS; i++) { ledNumber = activeOutColumn + i * NUMBER_OF_LED_COLUMNS; ledStateSingle = LED_ON(Interface::digital::output::LEDs::getLEDstate(ledNumber)); ledStateSingle *= (NUMBER_OF_LED_TRANSITIONS - 1); //don't bother with pwm if it's disabled if (!pwmSteps && ledStateSingle) { ledRowOn(i #ifdef LED_FADING , 255 #endif ); } else { if (ledTransitionScale[transitionCounter[ledNumber]]) ledRowOn(i #ifdef LED_FADING , ledTransitionScale[transitionCounter[ledNumber]] #endif ); if (transitionCounter[ledNumber] != ledStateSingle) { //fade up if (transitionCounter[ledNumber] < ledStateSingle) { transitionCounter[ledNumber] += pwmSteps; if (transitionCounter[ledNumber] > ledStateSingle) transitionCounter[ledNumber] = ledStateSingle; } else { //fade down transitionCounter[ledNumber] -= pwmSteps; if (transitionCounter[ledNumber] < 0) transitionCounter[ledNumber] = 0; } } } } if (++activeOutColumn == NUMBER_OF_LED_COLUMNS) activeOutColumn = 0; } #else namespace { uint8_t lastLEDstate[MAX_NUMBER_OF_LEDS]; uint8_t ledStateSingle; } // namespace #ifdef NUMBER_OF_OUT_SR /// /// \brief Checks if any LED state has been changed and writes changed state to output shift registers. /// void checkDigitalOutputs() { bool updateSR = false; for (int i = 0; i < MAX_NUMBER_OF_LEDS; i++) { ledStateSingle = LED_ON(Interface::digital::output::LEDs::getLEDstate(i)); if (ledStateSingle != lastLEDstate[i]) { lastLEDstate[i] = ledStateSingle; updateSR = true; } } if (updateSR) { CORE_AVR_PIN_SET_LOW(SR_OUT_LATCH_PORT, SR_OUT_LATCH_PIN); for (int i = 0; i < MAX_NUMBER_OF_LEDS; i++) { LED_ON(Interface::digital::output::LEDs::getLEDstate(i)) ? EXT_LED_ON(SR_OUT_DATA_PORT, SR_OUT_DATA_PIN) : EXT_LED_OFF(SR_OUT_DATA_PORT, SR_OUT_DATA_PIN); CORE_AVR_PIN_SET_LOW(SR_OUT_CLK_PORT, SR_OUT_CLK_PIN); _NOP(); _NOP(); CORE_AVR_PIN_SET_HIGH(SR_OUT_CLK_PORT, SR_OUT_CLK_PIN); } CORE_AVR_PIN_SET_HIGH(SR_OUT_LATCH_PORT, SR_OUT_LATCH_PIN); } } #else namespace { core::CORE_ARCH::pins::mcuPin_t pin; } void checkDigitalOutputs() { for (int i = 0; i < MAX_NUMBER_OF_LEDS; i++) { ledStateSingle = LED_ON(Interface::digital::output::LEDs::getLEDstate(i)); pin = Board::map::led(i); if (ledStateSingle != lastLEDstate[i]) { if (ledStateSingle) EXT_LED_ON(*pin.port, pin.pin); else EXT_LED_OFF(*pin.port, pin.pin); lastLEDstate[i] = ledStateSingle; } } } #endif #endif #endif } // namespace detail } // namespace output } // namespace digital } // namespace interface } // namespace Board<commit_msg>fix output shift register handling<commit_after>/* Copyright 2015-2019 Igor Petrovic 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 "board/Board.h" #include "board/common/constants/LEDs.h" #include "board/common/digital/Output.h" #include "board/common/Map.h" #include "core/src/general/BitManipulation.h" #include "Pins.h" #include "interface/digital/output/leds/Helpers.h" #ifndef BOARD_A_xu2 #include "interface/digital/output/leds/LEDs.h" #endif #ifdef LED_INDICATORS namespace { /// /// \brief Variables used to control the time MIDI in/out LED indicators on board are active. /// When these LEDs need to be turned on, variables are set to value representing time in /// milliseconds during which they should be on. ISR decreases variable value by 1 every 1 millsecond. /// Once the variables have value 0, specific LED indicator is turned off. /// @{ volatile uint8_t midiIn_timeout; volatile uint8_t midiOut_timeout; /// @} } // namespace #endif #ifndef BOARD_A_xu2 namespace { volatile uint8_t pwmSteps; volatile int8_t transitionCounter[MAX_NUMBER_OF_LEDS]; /// /// \brief Array holding values needed to achieve more natural LED transition between states. /// const uint8_t ledTransitionScale[NUMBER_OF_LED_TRANSITIONS] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 30, 33, 36, 40, 44, 48, 52, 57, 62, 68, 74, 81, 89, 97, 106, 115, 126, 138, 150, 164, 179, 195, 213, 255 }; #ifdef NUMBER_OF_LED_COLUMNS /// /// \brief Holds value of currently active output matrix column. /// volatile uint8_t activeOutColumn; #endif } // namespace #endif namespace Board { namespace interface { namespace digital { namespace output { #ifndef BOARD_A_xu2 #ifdef LEDS_SUPPORTED bool setLEDfadeSpeed(uint8_t transitionSpeed) { if (transitionSpeed > FADE_TIME_MAX) { return false; } //reset transition counter #ifdef __AVR__ ATOMIC_BLOCK(ATOMIC_RESTORESTATE) #endif { for (int i = 0; i < MAX_NUMBER_OF_LEDS; i++) transitionCounter[i] = 0; pwmSteps = transitionSpeed; } return true; } uint8_t getRGBaddress(uint8_t rgbID, Interface::digital::output::LEDs::rgbIndex_t index) { #ifdef NUMBER_OF_LED_COLUMNS uint8_t column = rgbID % NUMBER_OF_LED_COLUMNS; uint8_t row = (rgbID / NUMBER_OF_LED_COLUMNS) * 3; uint8_t address = column + NUMBER_OF_LED_COLUMNS * row; switch (index) { case Interface::digital::output::LEDs::rgbIndex_t::r: return address; case Interface::digital::output::LEDs::rgbIndex_t::g: return address + NUMBER_OF_LED_COLUMNS * 1; case Interface::digital::output::LEDs::rgbIndex_t::b: return address + NUMBER_OF_LED_COLUMNS * 2; } return 0; #else return rgbID * 3 + static_cast<uint8_t>(index); #endif } uint8_t getRGBID(uint8_t ledID) { #ifdef NUMBER_OF_LED_COLUMNS uint8_t row = ledID / NUMBER_OF_LED_COLUMNS; uint8_t mod = row % 3; row -= mod; uint8_t column = ledID % NUMBER_OF_LED_COLUMNS; uint8_t result = (row * NUMBER_OF_LED_COLUMNS) / 3 + column; if (result >= MAX_NUMBER_OF_RGB_LEDS) return MAX_NUMBER_OF_RGB_LEDS - 1; else return result; #else uint8_t result = ledID / 3; if (result >= MAX_NUMBER_OF_RGB_LEDS) return MAX_NUMBER_OF_RGB_LEDS - 1; else return result; #endif } #endif #endif namespace detail { #ifdef LED_INDICATORS void checkIndicators() { if (Board::USB::trafficIndicator.received || Board::UART::trafficIndicator.received) { INT_LED_ON(LED_IN_PORT, LED_IN_PIN); Board::USB::trafficIndicator.received = false; Board::UART::trafficIndicator.received = false; midiIn_timeout = MIDI_INDICATOR_TIMEOUT; } if (midiIn_timeout) midiIn_timeout--; else INT_LED_OFF(LED_IN_PORT, LED_IN_PIN); if (Board::USB::trafficIndicator.sent || Board::UART::trafficIndicator.sent) { INT_LED_ON(LED_OUT_PORT, LED_OUT_PIN); Board::USB::trafficIndicator.sent = false; Board::UART::trafficIndicator.sent = false; midiOut_timeout = MIDI_INDICATOR_TIMEOUT; } if (midiOut_timeout) midiOut_timeout--; else INT_LED_OFF(LED_OUT_PORT, LED_OUT_PIN); } #endif #ifndef BOARD_A_xu2 #ifdef NUMBER_OF_LED_COLUMNS /// /// \brief Switches to next LED matrix column. /// inline void activateOutputColumn() { BIT_READ(activeOutColumn, 0) ? CORE_AVR_PIN_SET_HIGH(DEC_LM_A0_PORT, DEC_LM_A0_PIN) : CORE_AVR_PIN_SET_LOW(DEC_LM_A0_PORT, DEC_LM_A0_PIN); BIT_READ(activeOutColumn, 1) ? CORE_AVR_PIN_SET_HIGH(DEC_LM_A1_PORT, DEC_LM_A1_PIN) : CORE_AVR_PIN_SET_LOW(DEC_LM_A1_PORT, DEC_LM_A1_PIN); BIT_READ(activeOutColumn, 2) ? CORE_AVR_PIN_SET_HIGH(DEC_LM_A2_PORT, DEC_LM_A2_PIN) : CORE_AVR_PIN_SET_LOW(DEC_LM_A2_PORT, DEC_LM_A2_PIN); } namespace { core::CORE_ARCH::pins::mcuPin_t pin; uint8_t ledNumber; uint8_t ledStateSingle; } // namespace /// /// \brief Used to turn the given LED row off. /// inline void ledRowOff(uint8_t row) { #ifdef LED_FADING //turn off pwm core::CORE_ARCH::pins::pwmOff(Board::map::pwmChannel(row)); #endif pin = Board::map::led(row); EXT_LED_OFF(*pin.port, pin.pin); } /// /// \brief Used to turn the given LED row on. /// If led fading is supported on board, intensity must be specified as well. /// inline void ledRowOn(uint8_t row #ifdef LED_FADING , uint8_t intensity #endif ) { #ifdef LED_FADING if (intensity == 255) #endif { pin = Board::map::led(row); //max value, don't use pwm EXT_LED_ON(*pin.port, pin.pin); } #ifdef LED_FADING else { #ifdef LED_EXT_INVERT intensity = 255 - intensity; #endif core::CORE_ARCH::pins::pwmOn(Board::map::pwmChannel(row), intensity); } #endif } void checkDigitalOutputs() { for (int i = 0; i < NUMBER_OF_LED_ROWS; i++) ledRowOff(i); activateOutputColumn(); //if there is an active LED in current column, turn on LED row //do fancy transitions here for (int i = 0; i < NUMBER_OF_LED_ROWS; i++) { ledNumber = activeOutColumn + i * NUMBER_OF_LED_COLUMNS; ledStateSingle = LED_ON(Interface::digital::output::LEDs::getLEDstate(ledNumber)); ledStateSingle *= (NUMBER_OF_LED_TRANSITIONS - 1); //don't bother with pwm if it's disabled if (!pwmSteps && ledStateSingle) { ledRowOn(i #ifdef LED_FADING , 255 #endif ); } else { if (ledTransitionScale[transitionCounter[ledNumber]]) ledRowOn(i #ifdef LED_FADING , ledTransitionScale[transitionCounter[ledNumber]] #endif ); if (transitionCounter[ledNumber] != ledStateSingle) { //fade up if (transitionCounter[ledNumber] < ledStateSingle) { transitionCounter[ledNumber] += pwmSteps; if (transitionCounter[ledNumber] > ledStateSingle) transitionCounter[ledNumber] = ledStateSingle; } else { //fade down transitionCounter[ledNumber] -= pwmSteps; if (transitionCounter[ledNumber] < 0) transitionCounter[ledNumber] = 0; } } } } if (++activeOutColumn == NUMBER_OF_LED_COLUMNS) activeOutColumn = 0; } #else namespace { uint8_t lastLEDstate[MAX_NUMBER_OF_LEDS]; uint8_t ledStateSingle; } // namespace #ifdef NUMBER_OF_OUT_SR /// /// \brief Checks if any LED state has been changed and writes changed state to output shift registers. /// void checkDigitalOutputs() { bool updateSR = false; for (int i = 0; i < MAX_NUMBER_OF_LEDS; i++) { ledStateSingle = LED_ON(Interface::digital::output::LEDs::getLEDstate(i)); if (ledStateSingle != lastLEDstate[i]) { lastLEDstate[i] = ledStateSingle; updateSR = true; } } if (updateSR) { CORE_AVR_PIN_SET_LOW(SR_OUT_LATCH_PORT, SR_OUT_LATCH_PIN); uint8_t ledIndex; for (int j = 0; j < NUMBER_OF_OUT_SR; j++) { for (int i = 0; i < NUMBER_OF_OUT_SR_INPUTS; i++) { ledIndex = i + j * NUMBER_OF_OUT_SR_INPUTS; LED_ON(Interface::digital::output::LEDs::getLEDstate(ledIndex)) ? EXT_LED_ON(SR_OUT_DATA_PORT, SR_OUT_DATA_PIN) : EXT_LED_OFF(SR_OUT_DATA_PORT, SR_OUT_DATA_PIN); CORE_AVR_PIN_SET_LOW(SR_OUT_CLK_PORT, SR_OUT_CLK_PIN); _NOP(); _NOP(); CORE_AVR_PIN_SET_HIGH(SR_OUT_CLK_PORT, SR_OUT_CLK_PIN); } } CORE_AVR_PIN_SET_HIGH(SR_OUT_LATCH_PORT, SR_OUT_LATCH_PIN); } } #else namespace { core::CORE_ARCH::pins::mcuPin_t pin; } void checkDigitalOutputs() { for (int i = 0; i < MAX_NUMBER_OF_LEDS; i++) { ledStateSingle = LED_ON(Interface::digital::output::LEDs::getLEDstate(i)); pin = Board::map::led(i); if (ledStateSingle != lastLEDstate[i]) { if (ledStateSingle) EXT_LED_ON(*pin.port, pin.pin); else EXT_LED_OFF(*pin.port, pin.pin); lastLEDstate[i] = ledStateSingle; } } } #endif #endif #endif } // namespace detail } // namespace output } // namespace digital } // namespace interface } // namespace Board<|endoftext|>
<commit_before>// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // 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 "olap/wrapper_field.h" namespace doris { WrapperField* WrapperField::create(const TabletColumn& column, uint32_t len) { bool is_string_type = (column.type() == OLAP_FIELD_TYPE_CHAR || column.type() == OLAP_FIELD_TYPE_VARCHAR); if (is_string_type && len > OLAP_STRING_MAX_LENGTH) { OLAP_LOG_WARNING("length of string parameter is too long[len=%lu, max_len=%lu].", len, OLAP_STRING_MAX_LENGTH); return nullptr; } Field* rep = Field::create(column); if (rep == nullptr) { return nullptr; } size_t variable_len = 0; if (column.type() == OLAP_FIELD_TYPE_CHAR) { variable_len = std::max(len, (uint32_t)(column.length())); } else if (column.type() == OLAP_FIELD_TYPE_VARCHAR) { variable_len = std::max(len, static_cast<uint32_t>(column.length() - sizeof(StringLengthType))); } else { variable_len = column.length(); } WrapperField* wrapper = new WrapperField(rep, variable_len, is_string_type); return wrapper; } WrapperField* WrapperField::create_by_type(const FieldType& type) { Field* rep = Field::create_by_type(type); if (rep == nullptr) { return nullptr; } bool is_string_type = (type == OLAP_FIELD_TYPE_CHAR || type == OLAP_FIELD_TYPE_VARCHAR || type == OLAP_FIELD_TYPE_HLL); WrapperField* wrapper = new WrapperField(rep, 0, is_string_type); return wrapper; } WrapperField::WrapperField(Field* rep, size_t variable_len, bool is_string_type) : _rep(rep), _is_string_type(is_string_type) { size_t fixed_len = _rep->size(); _length = fixed_len + variable_len + 1; _field_buf = new char[_length]; memset(_field_buf, 0, _length); _owned_buf = _field_buf; _is_null = _field_buf; _buf = _field_buf + 1; if (_is_string_type) { Slice* slice = reinterpret_cast<Slice*>(_buf); slice->size = variable_len; slice->data = _buf + fixed_len; } } } <commit_msg>Fix bug that WrapperField does not consider HLL column type when creating (#1514)<commit_after>// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // 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 "olap/wrapper_field.h" namespace doris { WrapperField* WrapperField::create(const TabletColumn& column, uint32_t len) { bool is_string_type = (column.type() == OLAP_FIELD_TYPE_CHAR || column.type() == OLAP_FIELD_TYPE_VARCHAR || column.type() == OLAP_FIELD_TYPE_HLL); if (is_string_type && len > OLAP_STRING_MAX_LENGTH) { OLAP_LOG_WARNING("length of string parameter is too long[len=%lu, max_len=%lu].", len, OLAP_STRING_MAX_LENGTH); return nullptr; } Field* rep = Field::create(column); if (rep == nullptr) { return nullptr; } size_t variable_len = 0; if (column.type() == OLAP_FIELD_TYPE_CHAR) { variable_len = std::max(len, (uint32_t)(column.length())); } else if (column.type() == OLAP_FIELD_TYPE_VARCHAR || column.type() == OLAP_FIELD_TYPE_HLL) { variable_len = std::max(len, static_cast<uint32_t>(column.length() - sizeof(StringLengthType))); } else { variable_len = column.length(); } WrapperField* wrapper = new WrapperField(rep, variable_len, is_string_type); return wrapper; } WrapperField* WrapperField::create_by_type(const FieldType& type) { Field* rep = Field::create_by_type(type); if (rep == nullptr) { return nullptr; } bool is_string_type = (type == OLAP_FIELD_TYPE_CHAR || type == OLAP_FIELD_TYPE_VARCHAR || type == OLAP_FIELD_TYPE_HLL); WrapperField* wrapper = new WrapperField(rep, 0, is_string_type); return wrapper; } WrapperField::WrapperField(Field* rep, size_t variable_len, bool is_string_type) : _rep(rep), _is_string_type(is_string_type) { size_t fixed_len = _rep->size(); _length = fixed_len + variable_len + 1; _field_buf = new char[_length]; memset(_field_buf, 0, _length); _owned_buf = _field_buf; _is_null = _field_buf; _buf = _field_buf + 1; if (_is_string_type) { Slice* slice = reinterpret_cast<Slice*>(_buf); slice->size = variable_len; slice->data = _buf + fixed_len; } } } <|endoftext|>
<commit_before>#include <ctime> #include <iostream> #include <cstdlib> #include <iterator> #include <dariadb.h> #include <utils/fs.h> #include <ctime> #include <limits> #include <cmath> #include <chrono> #include <thread> #include <random> #include <cstdlib> #include <atomic> #include <cassert> class BenchCallback :public dariadb::storage::ReaderClb { public: void call(const dariadb::Meas&m) { if (m.flag != dariadb::Flags::NO_DATA) { count++; } else { count_ig++; } } size_t count; size_t count_ig; }; void writer_1(dariadb::storage::BaseStorage_ptr ms) { auto m = dariadb::Meas::empty(); dariadb::Time t = dariadb::timeutil::current_time(); for (dariadb::Id i = 0; i < 32768; i += 1) { m.id = i; m.flag = dariadb::Flag(0); m.time = t; m.value = dariadb::Value(i); ms->append(m); t++; } } std::atomic_long writen{ 0 }; void writer_2(dariadb::Id id_from, size_t id_per_thread, dariadb::storage::BaseStorage_ptr ms) { auto m = dariadb::Meas::empty(); std::random_device r; std::default_random_engine e1(r()); std::uniform_int_distribution<int> uniform_dist(10, 64); size_t max_id=(id_from + id_per_thread); for (dariadb::Id i = id_from; i < max_id; i += 1) { dariadb::Value v = 1.0; m.id = i; m.flag = dariadb::Flag(0); auto max_rnd = uniform_dist(e1); m.time = dariadb::timeutil::current_time(); for (dariadb::Time p = 0; p < dariadb::Time(max_rnd); p++) { m.time+=10; m.value = v; ms->append(m); writen++; auto rnd = rand() / float(RAND_MAX); v += rnd; } } } int main(int argc, char *argv[]) { (void)argc; (void)argv; srand(static_cast<unsigned int>(time(NULL))); const std::string storage_path = "testStorage"; const size_t chunk_per_storage = 1024 * 1024; const size_t chunk_size = 256; const size_t cap_max_size = 100; const dariadb::Time write_window_deep = 5000; const dariadb::Time old_mem_chunks = 0; const size_t max_mem_chunks = 0; // {// 1. // if (dariadb::utils::fs::path_exists(storage_path)) { // dariadb::utils::fs::rm(storage_path); // } // auto raw_ptr = new dariadb::storage::UnionStorage( // dariadb::storage::PageManager::Params(storage_path, dariadb::storage::MODE::SINGLE, chunk_per_storage, chunk_size), // dariadb::storage::Capacitor::Params(cap_max_size, write_window_deep), // dariadb::storage::UnionStorage::Limits(old_mem_chunks, max_mem_chunks)); // dariadb::storage::BaseStorage_ptr ms{ raw_ptr }; // auto start = clock(); // writer_1(ms); // auto elapsed = ((float)clock() - start) / CLOCKS_PER_SEC; // std::cout << "1. insert : " << elapsed << std::endl; // } if (dariadb::utils::fs::path_exists(storage_path)) { dariadb::utils::fs::rm(storage_path); } auto raw_ptr_ds = new dariadb::storage::UnionStorage( dariadb::storage::PageManager::Params(storage_path, dariadb::storage::MODE::SINGLE, chunk_per_storage, chunk_size), dariadb::storage::Capacitor::Params(cap_max_size, write_window_deep), dariadb::storage::UnionStorage::Limits(old_mem_chunks, max_mem_chunks)); dariadb::storage::BaseStorage_ptr ms{ raw_ptr_ds }; {// 2. const size_t threads_count = 16; const size_t id_per_thread = size_t(32768 / threads_count); auto start = clock(); std::vector<std::thread> writers(threads_count); size_t pos = 0; for (size_t i = 0; i < threads_count; i++) { std::thread t{ writer_2, id_per_thread*i+1, id_per_thread, ms}; writers[pos++] = std::move(t); } pos = 0; for (size_t i = 0; i < threads_count; i++) { std::thread t = std::move(writers[pos++]); t.join(); } auto elapsed = ((float)clock() - start) / CLOCKS_PER_SEC; std::cout << "2. insert : " << elapsed << std::endl; raw_ptr_ds->flush(); } auto queue_sizes = raw_ptr_ds->queue_size(); std::cout << "\rin memory chunks: " << raw_ptr_ds->chunks_in_memory() << " in disk chunks: " << dariadb::storage::PageManager::instance()->chunks_in_cur_page() << " in queue: (p:" << queue_sizes.page << " m:" << queue_sizes.mem << " cap:" << queue_sizes.cap << ")" << " pooled: " << dariadb::storage::ChunkPool::instance()->polled() << std::endl; // { // auto ids=ms->getIds(); // std::cout << "ids.size:"<<ids.size() << std::endl; // std::cout << "read all..." << std::endl; // std::shared_ptr<BenchCallback> clbk{ new BenchCallback() }; // auto start = clock(); // ms->readInterval(0,ms->maxTime())->readAll(clbk.get()); // auto elapsed = (((float)clock() - start) / CLOCKS_PER_SEC); // std::cout << "readed: " << clbk->count << std::endl; // std::cout << "time: " << elapsed << std::endl; // } {//3 std::random_device r; std::default_random_engine e1(r()); std::uniform_int_distribution<dariadb::Id> uniform_dist(1, 32767); dariadb::IdArray ids; ids.resize(1); const size_t queries_count = 10; dariadb::IdArray rnd_ids(queries_count); std::vector<dariadb::Time> rnd_time(queries_count); for (size_t i = 0; i < queries_count; i++) { rnd_ids[i] = uniform_dist(e1); dariadb::Time minT,maxT; assert(raw_ptr_ds->minMaxTime(rnd_ids[i],&minT,&maxT)); std::uniform_int_distribution<dariadb::Time> uniform_dist_tmp(minT,maxT); rnd_time[i] = uniform_dist_tmp(e1); } auto raw_ptr = new BenchCallback(); dariadb::storage::ReaderClb_ptr clbk{ raw_ptr }; auto start = clock(); for (size_t i = 0; i < queries_count; i++) { ids[0]= rnd_ids[i]; auto t = rnd_time[i]; auto rdr=ms->readInTimePoint(ids,0,t); rdr->readAll(clbk.get()); } auto elapsed = (((float)clock() - start) / CLOCKS_PER_SEC)/ queries_count; std::cout << "3. time point: " << elapsed<< " readed: "<< raw_ptr->count << std::endl; } {//4 std::random_device r; std::default_random_engine e1(r()); std::uniform_int_distribution<dariadb::Id> uniform_dist(raw_ptr_ds->minTime(), dariadb::timeutil::current_time()); const size_t queries_count = 10;//32768; dariadb::IdArray ids; std::vector<dariadb::Time> rnd_time(queries_count); for (size_t i = 0; i < queries_count; i++){ rnd_time[i]=uniform_dist(e1); } auto raw_ptr = new BenchCallback(); dariadb::storage::ReaderClb_ptr clbk{raw_ptr}; auto start = clock(); for (size_t i = 0; i < queries_count; i++) { auto t = rnd_time[i]; auto rdr = ms->readInTimePoint(ids, 0, t); rdr->readAll(clbk.get()); } auto elapsed = (((float)clock() - start) / CLOCKS_PER_SEC) / queries_count; std::cout << "4. time point: " << elapsed << " readed: " << raw_ptr->count << std::endl; } {//5 std::random_device r; std::default_random_engine e1(r()); std::uniform_int_distribution<dariadb::Time> uniform_dist(raw_ptr_ds->minTime(), dariadb::timeutil::current_time()); auto raw_ptr = new BenchCallback(); dariadb::storage::ReaderClb_ptr clbk{ raw_ptr }; const size_t queries_count = 32; std::vector<dariadb::Time> rnd_time_from(queries_count),rnd_time_to(queries_count); for (size_t i = 0; i < queries_count; i++){ rnd_time_from[i]=uniform_dist(e1); rnd_time_to[i]=uniform_dist(e1); } auto start = clock(); for (size_t i = 0; i < queries_count; i++) { auto f = std::min(rnd_time_from[i],rnd_time_to[i]); auto t = std::max(rnd_time_from[i],rnd_time_to[i]); auto rdr = ms->readInterval(f, t+f); rdr->readAll(clbk.get()); } auto elapsed = (((float)clock() - start) / CLOCKS_PER_SEC) / queries_count; std::cout << "5. interval: " << elapsed << " readed: " << raw_ptr->count << std::endl; } {//6 std::random_device r; std::default_random_engine e1(r()); std::uniform_int_distribution<dariadb::Time> uniform_dist(raw_ptr_ds->minTime(), dariadb::timeutil::current_time()); std::uniform_int_distribution<dariadb::Id> uniform_dist_id(1, 32767); const size_t ids_count = size_t(32768 * 0.1); dariadb::IdArray ids; ids.resize(ids_count); auto raw_ptr = new BenchCallback(); dariadb::storage::ReaderClb_ptr clbk{ raw_ptr }; const size_t queries_count = 32; std::vector<dariadb::Time> rnd_time_from(queries_count),rnd_time_to(queries_count); for (size_t i = 0; i < queries_count; i++){ rnd_time_from[i]=uniform_dist(e1); rnd_time_to[i]=uniform_dist(e1); } auto start = clock(); for (size_t i = 0; i < queries_count; i++) { for (size_t j = 0; j < ids_count; j++) { ids[j] = uniform_dist_id(e1); } auto f = std::min(rnd_time_from[i],rnd_time_to[i]); auto t = std::max(rnd_time_from[i],rnd_time_to[i]); auto rdr = ms->readInterval(ids,0, f, t + f); rdr->readAll(clbk.get()); } auto elapsed = (((float)clock() - start) / CLOCKS_PER_SEC) / queries_count; std::cout << "6. interval: " << elapsed << " readed: " << raw_ptr->count << std::endl; } ms = nullptr; if (dariadb::utils::fs::path_exists(storage_path)) { dariadb::utils::fs::rm(storage_path); } } <commit_msg>hard_benchmark: uncomment all.<commit_after>#include <ctime> #include <iostream> #include <cstdlib> #include <iterator> #include <dariadb.h> #include <utils/fs.h> #include <ctime> #include <limits> #include <cmath> #include <chrono> #include <thread> #include <random> #include <cstdlib> #include <atomic> #include <cassert> class BenchCallback :public dariadb::storage::ReaderClb { public: void call(const dariadb::Meas&m) { if (m.flag != dariadb::Flags::NO_DATA) { count++; } else { count_ig++; } } size_t count; size_t count_ig; }; void writer_1(dariadb::storage::BaseStorage_ptr ms) { auto m = dariadb::Meas::empty(); dariadb::Time t = dariadb::timeutil::current_time(); for (dariadb::Id i = 0; i < 32768; i += 1) { m.id = i; m.flag = dariadb::Flag(0); m.time = t; m.value = dariadb::Value(i); ms->append(m); t++; } } std::atomic_long writen{ 0 }; void writer_2(dariadb::Id id_from, size_t id_per_thread, dariadb::storage::BaseStorage_ptr ms) { auto m = dariadb::Meas::empty(); std::random_device r; std::default_random_engine e1(r()); std::uniform_int_distribution<int> uniform_dist(10, 64); size_t max_id=(id_from + id_per_thread); for (dariadb::Id i = id_from; i < max_id; i += 1) { dariadb::Value v = 1.0; m.id = i; m.flag = dariadb::Flag(0); auto max_rnd = uniform_dist(e1); m.time = dariadb::timeutil::current_time(); for (dariadb::Time p = 0; p < dariadb::Time(max_rnd); p++) { m.time+=10; m.value = v; ms->append(m); writen++; auto rnd = rand() / float(RAND_MAX); v += rnd; } } } int main(int argc, char *argv[]) { (void)argc; (void)argv; srand(static_cast<unsigned int>(time(NULL))); const std::string storage_path = "testStorage"; const size_t chunk_per_storage = 1024 * 1024; const size_t chunk_size = 256; const size_t cap_max_size = 100; const dariadb::Time write_window_deep = 5000; const dariadb::Time old_mem_chunks = 0; const size_t max_mem_chunks = 0; {// 1. if (dariadb::utils::fs::path_exists(storage_path)) { dariadb::utils::fs::rm(storage_path); } auto raw_ptr = new dariadb::storage::UnionStorage( dariadb::storage::PageManager::Params(storage_path, dariadb::storage::MODE::SINGLE, chunk_per_storage, chunk_size), dariadb::storage::Capacitor::Params(cap_max_size, write_window_deep), dariadb::storage::UnionStorage::Limits(old_mem_chunks, max_mem_chunks)); dariadb::storage::BaseStorage_ptr ms{ raw_ptr }; auto start = clock(); writer_1(ms); auto elapsed = ((float)clock() - start) / CLOCKS_PER_SEC; std::cout << "1. insert : " << elapsed << std::endl; } if (dariadb::utils::fs::path_exists(storage_path)) { dariadb::utils::fs::rm(storage_path); } auto raw_ptr_ds = new dariadb::storage::UnionStorage( dariadb::storage::PageManager::Params(storage_path, dariadb::storage::MODE::SINGLE, chunk_per_storage, chunk_size), dariadb::storage::Capacitor::Params(cap_max_size, write_window_deep), dariadb::storage::UnionStorage::Limits(old_mem_chunks, max_mem_chunks)); dariadb::storage::BaseStorage_ptr ms{ raw_ptr_ds }; {// 2. const size_t threads_count = 16; const size_t id_per_thread = size_t(32768 / threads_count); auto start = clock(); std::vector<std::thread> writers(threads_count); size_t pos = 0; for (size_t i = 0; i < threads_count; i++) { std::thread t{ writer_2, id_per_thread*i+1, id_per_thread, ms}; writers[pos++] = std::move(t); } pos = 0; for (size_t i = 0; i < threads_count; i++) { std::thread t = std::move(writers[pos++]); t.join(); } auto elapsed = ((float)clock() - start) / CLOCKS_PER_SEC; std::cout << "2. insert : " << elapsed << std::endl; raw_ptr_ds->flush(); } auto queue_sizes = raw_ptr_ds->queue_size(); std::cout << "\rin memory chunks: " << raw_ptr_ds->chunks_in_memory() << " in disk chunks: " << dariadb::storage::PageManager::instance()->chunks_in_cur_page() << " in queue: (p:" << queue_sizes.page << " m:" << queue_sizes.mem << " cap:" << queue_sizes.cap << ")" << " pooled: " << dariadb::storage::ChunkPool::instance()->polled() << std::endl; { auto ids=ms->getIds(); std::cout << "ids.size:"<<ids.size() << std::endl; std::cout << "read all..." << std::endl; std::shared_ptr<BenchCallback> clbk{ new BenchCallback() }; auto start = clock(); ms->readInterval(0,ms->maxTime())->readAll(clbk.get()); auto elapsed = (((float)clock() - start) / CLOCKS_PER_SEC); std::cout << "readed: " << clbk->count << std::endl; std::cout << "time: " << elapsed << std::endl; } {//3 std::random_device r; std::default_random_engine e1(r()); std::uniform_int_distribution<dariadb::Id> uniform_dist(1, 32767); dariadb::IdArray ids; ids.resize(1); const size_t queries_count = 32768; dariadb::IdArray rnd_ids(queries_count); std::vector<dariadb::Time> rnd_time(queries_count); for (size_t i = 0; i < queries_count; i++) { rnd_ids[i] = uniform_dist(e1); dariadb::Time minT,maxT; assert(raw_ptr_ds->minMaxTime(rnd_ids[i],&minT,&maxT)); std::uniform_int_distribution<dariadb::Time> uniform_dist_tmp(minT,maxT); rnd_time[i] = uniform_dist_tmp(e1); } auto raw_ptr = new BenchCallback(); dariadb::storage::ReaderClb_ptr clbk{ raw_ptr }; auto start = clock(); for (size_t i = 0; i < queries_count; i++) { ids[0]= rnd_ids[i]; auto t = rnd_time[i]; auto rdr=ms->readInTimePoint(ids,0,t); rdr->readAll(clbk.get()); } auto elapsed = (((float)clock() - start) / CLOCKS_PER_SEC)/ queries_count; std::cout << "3. time point: " << elapsed<< " readed: "<< raw_ptr->count << std::endl; } {//4 std::random_device r; std::default_random_engine e1(r()); std::uniform_int_distribution<dariadb::Id> uniform_dist(raw_ptr_ds->minTime(), dariadb::timeutil::current_time()); const size_t queries_count = 1; dariadb::IdArray ids; std::vector<dariadb::Time> rnd_time(queries_count); for (size_t i = 0; i < queries_count; i++){ rnd_time[i]=uniform_dist(e1); } auto raw_ptr = new BenchCallback(); dariadb::storage::ReaderClb_ptr clbk{raw_ptr}; auto start = clock(); for (size_t i = 0; i < queries_count; i++) { auto t = rnd_time[i]; auto rdr = ms->readInTimePoint(ids, 0, t); rdr->readAll(clbk.get()); } auto elapsed = (((float)clock() - start) / CLOCKS_PER_SEC) / queries_count; std::cout << "4. time point: " << elapsed << " readed: " << raw_ptr->count << std::endl; } {//5 std::random_device r; std::default_random_engine e1(r()); std::uniform_int_distribution<dariadb::Time> uniform_dist(raw_ptr_ds->minTime(), dariadb::timeutil::current_time()); auto raw_ptr = new BenchCallback(); dariadb::storage::ReaderClb_ptr clbk{ raw_ptr }; const size_t queries_count = 1; std::vector<dariadb::Time> rnd_time_from(queries_count),rnd_time_to(queries_count); for (size_t i = 0; i < queries_count; i++){ rnd_time_from[i]=uniform_dist(e1); rnd_time_to[i]=uniform_dist(e1); } auto start = clock(); for (size_t i = 0; i < queries_count; i++) { auto f = std::min(rnd_time_from[i],rnd_time_to[i]); auto t = std::max(rnd_time_from[i],rnd_time_to[i]); auto rdr = ms->readInterval(f, t); rdr->readAll(clbk.get()); } auto elapsed = (((float)clock() - start) / CLOCKS_PER_SEC) / queries_count; std::cout << "5. interval: " << elapsed << " readed: " << raw_ptr->count << std::endl; } {//6 std::random_device r; std::default_random_engine e1(r()); std::uniform_int_distribution<dariadb::Time> uniform_dist(raw_ptr_ds->minTime(), dariadb::timeutil::current_time()); std::uniform_int_distribution<dariadb::Id> uniform_dist_id(1, 32767); const size_t ids_count = size_t(32768 * 0.1); dariadb::IdArray ids; ids.resize(ids_count); auto raw_ptr = new BenchCallback(); dariadb::storage::ReaderClb_ptr clbk{ raw_ptr }; const size_t queries_count = 1; std::vector<dariadb::Time> rnd_time_from(queries_count),rnd_time_to(queries_count); for (size_t i = 0; i < queries_count; i++){ rnd_time_from[i]=uniform_dist(e1); rnd_time_to[i]=uniform_dist(e1); } auto start = clock(); for (size_t i = 0; i < queries_count; i++) { for (size_t j = 0; j < ids_count; j++) { ids[j] = uniform_dist_id(e1); } auto f = std::min(rnd_time_from[i],rnd_time_to[i]); auto t = std::max(rnd_time_from[i],rnd_time_to[i]); auto rdr = ms->readInterval(ids,0, f, t ); rdr->readAll(clbk.get()); } auto elapsed = (((float)clock() - start) / CLOCKS_PER_SEC) / queries_count; std::cout << "6. interval: " << elapsed << " readed: " << raw_ptr->count << std::endl; } ms = nullptr; if (dariadb::utils::fs::path_exists(storage_path)) { dariadb::utils::fs::rm(storage_path); } } <|endoftext|>
<commit_before>#include <cstdlib> #include <ctime> #include <iostream> #include <iterator> #include "bench_common.h" #include <dariadb.h> #include <algorithm> #include <atomic> #include <chrono> #include <cmath> #include <ctime> #include <limits> #include <random> #include <storage/capacitor.h> #include <thread> #include <utils/fs.h> #include <boost/program_options.hpp> namespace po = boost::program_options; std::atomic_long append_count{0}; std::atomic_size_t reads_count{0}; bool stop_info = false; bool stop_readers = false; class BenchCallback : public dariadb::storage::ReaderClb { public: BenchCallback() { count = 0; } void call(const dariadb::Meas &) { count++; } size_t count; }; void show_info(dariadb::storage::Engine *storage) { clock_t t0 = clock(); auto all_writes = dariadb_bench::total_threads_count * dariadb_bench::iteration_count; while (true) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); clock_t t1 = clock(); auto writes_per_sec = append_count.load() / double((t1 - t0) / CLOCKS_PER_SEC); auto reads_per_sec = reads_count.load() / double((t1 - t0) / CLOCKS_PER_SEC); auto queue_sizes = storage->queue_size(); std::cout << "\r" << " in queue: (p:" << queue_sizes.pages_count << " cap:" << queue_sizes.cola_count << ")" << " reads: " << reads_count << " speed:" << reads_per_sec << "/sec" << " writes: " << append_count << " speed: " << writes_per_sec << "/sec progress:" << (int64_t(100) * append_count) / all_writes << "% "; std::cout.flush(); if (stop_info) { std::cout.flush(); break; } } std::cout << "\n"; } void reader(dariadb::storage::MeasStorage_ptr ms, dariadb::IdSet all_id_set, dariadb::Time from, dariadb::Time to) { std::random_device r; std::default_random_engine e1(r()); std::uniform_int_distribution<dariadb::Id> uniform_dist(from, to); std::shared_ptr<BenchCallback> clbk{new BenchCallback}; while (true) { clbk->count = 0; auto time_point1 = uniform_dist(e1); auto time_point2 = uniform_dist(e1); auto f = std::min(time_point1, time_point2); auto t = std::max(time_point1, time_point2); auto qi = dariadb::storage::QueryInterval( dariadb::IdArray(all_id_set.begin(), all_id_set.end()), 0, f, t); ms->readInterval(qi)->readAll(clbk.get()); reads_count += clbk->count; if (stop_readers) { break; } } } int main(int argc, char *argv[]) { (void)argc; (void)argv; std::cout << "Performance benchmark" << std::endl; std::cout << "Writers count:" << dariadb_bench::total_threads_count << std::endl; const std::string storage_path = "testStorage"; bool readers_enable = false; bool dont_clean = false; po::options_description desc("Allowed options"); desc.add_options()("help", "produce help message")( "enable-readers", po::value<bool>(&readers_enable)->default_value(readers_enable), "enable readers threads")("dont-clean", po::value<bool>(&dont_clean)->default_value(dont_clean), "enable readers threads"); po::variables_map vm; try { po::store(po::parse_command_line(argc, argv, desc), vm); } catch (std::exception &ex) { logger("Error: " << ex.what()); exit(1); } po::notify(vm); if (vm.count("help")) { std::cout << desc << std::endl; return 1; } if (readers_enable) { std::cout << "Readers enable. count: " << dariadb_bench::total_readers_count << std::endl; } { std::cout << "write..." << std::endl; const size_t chunk_per_storage = 1024 * 10; const size_t chunk_size = 1024; const size_t cap_B = 10; const size_t max_mem_chunks = 100; // dont_clean = true; if (!dont_clean && dariadb::utils::fs::path_exists(storage_path)) { dariadb::utils::fs::rm(storage_path); } dariadb::Time start_time = dariadb::timeutil::current_time(); std::cout << " start time: "<<dariadb::timeutil::to_string(start_time) << std::endl; dariadb::storage::Capacitor::Params cap_param(cap_B, storage_path); cap_param.max_levels = 11; auto raw_ptr = new dariadb::storage::Engine( dariadb::storage::PageManager::Params(storage_path, chunk_per_storage, chunk_size), cap_param, dariadb::storage::Engine::Limits(max_mem_chunks)); dariadb::storage::MeasStorage_ptr ms{raw_ptr}; dariadb::IdSet all_id_set; append_count = 0; stop_info = false; std::thread info_thread(show_info, raw_ptr); std::vector<std::thread> writers(dariadb_bench::total_threads_count); std::vector<std::thread> readers(dariadb_bench::total_readers_count); size_t pos = 0; for (size_t i = 1; i < dariadb_bench::total_threads_count + 1; i++) { all_id_set.insert(pos); std::thread t{dariadb_bench::thread_writer_rnd_stor, dariadb::Id(pos), dariadb::Time(i), &append_count, raw_ptr}; writers[pos++] = std::move(t); } if (readers_enable) { pos = 0; for (size_t i = 1; i < dariadb_bench::total_readers_count + 1; i++) { std::thread t{reader, ms, all_id_set, dariadb::Time(0), dariadb::timeutil::current_time()}; readers[pos++] = std::move(t); } } pos = 0; for (size_t i = 1; i < dariadb_bench::total_threads_count + 1; i++) { std::thread t = std::move(writers[pos++]); t.join(); } stop_readers = true; if (readers_enable) { pos = 0; for (size_t i = 1; i < dariadb_bench::total_readers_count + 1; i++) { std::thread t = std::move(readers[pos++]); t.join(); } } stop_info = true; info_thread.join(); { std::cout << "full flush..." << std::endl; auto start = clock(); raw_ptr->flush(); auto elapsed = (((float)clock() - start) / CLOCKS_PER_SEC); std::cout << "flush time: " << elapsed << std::endl; } auto queue_sizes = raw_ptr->queue_size(); std::cout << "\r" << " in queue: (p:" << queue_sizes.pages_count << " cap:" << queue_sizes.cola_count << ")" << std::endl; dariadb_bench::readBenchark(all_id_set, ms, 10, start_time, dariadb::timeutil::current_time()); { std::cout << "read all..." << std::endl; std::shared_ptr<BenchCallback> clbk{new BenchCallback()}; auto start = clock(); dariadb::storage::QueryInterval qi{ dariadb::IdArray(all_id_set.begin(), all_id_set.end()), 0, start_time, ms->maxTime()}; ms->readInterval(qi)->readAll(clbk.get()); auto elapsed = (((float)clock() - start) / CLOCKS_PER_SEC); std::cout << "readed: " << clbk->count << std::endl; std::cout << "time: " << elapsed << std::endl; auto expected = (dariadb_bench::iteration_count * dariadb_bench::total_threads_count); if (!dont_clean && clbk->count != expected) { std::cout << "expected: " << expected << " get:" << clbk->count << std::endl; throw MAKE_EXCEPTION("(clbk->count!=(iteration_count*total_threads_count))"); } else { if (dont_clean && clbk->count < expected) { std::cout << "expected: " << expected << " get:" << clbk->count << std::endl; throw MAKE_EXCEPTION("(clbk->count!=(iteration_count*total_threads_count))"); } } } std::cout << "stoping storage...\n"; ms = nullptr; } std::cout << "cleaning...\n"; if (dariadb::utils::fs::path_exists(storage_path)) { dariadb::utils::fs::rm(storage_path); } } <commit_msg>perf benchmark print end time on readall.<commit_after>#include <cstdlib> #include <ctime> #include <iostream> #include <iterator> #include "bench_common.h" #include <dariadb.h> #include <algorithm> #include <atomic> #include <chrono> #include <cmath> #include <ctime> #include <limits> #include <random> #include <storage/capacitor.h> #include <thread> #include <utils/fs.h> #include <boost/program_options.hpp> namespace po = boost::program_options; std::atomic_long append_count{0}; std::atomic_size_t reads_count{0}; bool stop_info = false; bool stop_readers = false; class BenchCallback : public dariadb::storage::ReaderClb { public: BenchCallback() { count = 0; } void call(const dariadb::Meas &) { count++; } size_t count; }; void show_info(dariadb::storage::Engine *storage) { clock_t t0 = clock(); auto all_writes = dariadb_bench::total_threads_count * dariadb_bench::iteration_count; while (true) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); clock_t t1 = clock(); auto writes_per_sec = append_count.load() / double((t1 - t0) / CLOCKS_PER_SEC); auto reads_per_sec = reads_count.load() / double((t1 - t0) / CLOCKS_PER_SEC); auto queue_sizes = storage->queue_size(); std::cout << "\r" << " in queue: (p:" << queue_sizes.pages_count << " cap:" << queue_sizes.cola_count << ")" << " reads: " << reads_count << " speed:" << reads_per_sec << "/sec" << " writes: " << append_count << " speed: " << writes_per_sec << "/sec progress:" << (int64_t(100) * append_count) / all_writes << "% "; std::cout.flush(); if (stop_info) { std::cout.flush(); break; } } std::cout << "\n"; } void reader(dariadb::storage::MeasStorage_ptr ms, dariadb::IdSet all_id_set, dariadb::Time from, dariadb::Time to) { std::random_device r; std::default_random_engine e1(r()); std::uniform_int_distribution<dariadb::Id> uniform_dist(from, to); std::shared_ptr<BenchCallback> clbk{new BenchCallback}; while (true) { clbk->count = 0; auto time_point1 = uniform_dist(e1); auto time_point2 = uniform_dist(e1); auto f = std::min(time_point1, time_point2); auto t = std::max(time_point1, time_point2); auto qi = dariadb::storage::QueryInterval( dariadb::IdArray(all_id_set.begin(), all_id_set.end()), 0, f, t); ms->readInterval(qi)->readAll(clbk.get()); reads_count += clbk->count; if (stop_readers) { break; } } } int main(int argc, char *argv[]) { (void)argc; (void)argv; std::cout << "Performance benchmark" << std::endl; std::cout << "Writers count:" << dariadb_bench::total_threads_count << std::endl; const std::string storage_path = "testStorage"; bool readers_enable = false; bool dont_clean = false; po::options_description desc("Allowed options"); desc.add_options()("help", "produce help message")( "enable-readers", po::value<bool>(&readers_enable)->default_value(readers_enable), "enable readers threads")("dont-clean", po::value<bool>(&dont_clean)->default_value(dont_clean), "enable readers threads"); po::variables_map vm; try { po::store(po::parse_command_line(argc, argv, desc), vm); } catch (std::exception &ex) { logger("Error: " << ex.what()); exit(1); } po::notify(vm); if (vm.count("help")) { std::cout << desc << std::endl; return 1; } if (readers_enable) { std::cout << "Readers enable. count: " << dariadb_bench::total_readers_count << std::endl; } { std::cout << "write..." << std::endl; const size_t chunk_per_storage = 1024 * 10; const size_t chunk_size = 1024; const size_t cap_B = 10; const size_t max_mem_chunks = 100; // dont_clean = true; if (!dont_clean && dariadb::utils::fs::path_exists(storage_path)) { dariadb::utils::fs::rm(storage_path); } dariadb::Time start_time = dariadb::timeutil::current_time(); std::cout << " start time: "<<dariadb::timeutil::to_string(start_time) << std::endl; dariadb::storage::Capacitor::Params cap_param(cap_B, storage_path); cap_param.max_levels = 11; auto raw_ptr = new dariadb::storage::Engine( dariadb::storage::PageManager::Params(storage_path, chunk_per_storage, chunk_size), cap_param, dariadb::storage::Engine::Limits(max_mem_chunks)); dariadb::storage::MeasStorage_ptr ms{raw_ptr}; dariadb::IdSet all_id_set; append_count = 0; stop_info = false; std::thread info_thread(show_info, raw_ptr); std::vector<std::thread> writers(dariadb_bench::total_threads_count); std::vector<std::thread> readers(dariadb_bench::total_readers_count); size_t pos = 0; for (size_t i = 1; i < dariadb_bench::total_threads_count + 1; i++) { all_id_set.insert(pos); std::thread t{dariadb_bench::thread_writer_rnd_stor, dariadb::Id(pos), dariadb::Time(i), &append_count, raw_ptr}; writers[pos++] = std::move(t); } if (readers_enable) { pos = 0; for (size_t i = 1; i < dariadb_bench::total_readers_count + 1; i++) { std::thread t{reader, ms, all_id_set, dariadb::Time(0), dariadb::timeutil::current_time()}; readers[pos++] = std::move(t); } } pos = 0; for (size_t i = 1; i < dariadb_bench::total_threads_count + 1; i++) { std::thread t = std::move(writers[pos++]); t.join(); } stop_readers = true; if (readers_enable) { pos = 0; for (size_t i = 1; i < dariadb_bench::total_readers_count + 1; i++) { std::thread t = std::move(readers[pos++]); t.join(); } } stop_info = true; info_thread.join(); { std::cout << "full flush..." << std::endl; auto start = clock(); raw_ptr->flush(); auto elapsed = (((float)clock() - start) / CLOCKS_PER_SEC); std::cout << "flush time: " << elapsed << std::endl; } auto queue_sizes = raw_ptr->queue_size(); std::cout << "\r" << " in queue: (p:" << queue_sizes.pages_count << " cap:" << queue_sizes.cola_count << ")" << std::endl; dariadb_bench::readBenchark(all_id_set, ms, 10, start_time, dariadb::timeutil::current_time()); { std::cout << "read all..." << std::endl; std::shared_ptr<BenchCallback> clbk{new BenchCallback()}; auto max_time=ms->maxTime(); std::cout << " end time: "<<dariadb::timeutil::to_string(max_time) << std::endl; auto start = clock(); dariadb::storage::QueryInterval qi{ dariadb::IdArray(all_id_set.begin(), all_id_set.end()), 0, start_time, max_time}; ms->readInterval(qi)->readAll(clbk.get()); auto elapsed = (((float)clock() - start) / CLOCKS_PER_SEC); std::cout << "readed: " << clbk->count << std::endl; std::cout << "time: " << elapsed << std::endl; auto expected = (dariadb_bench::iteration_count * dariadb_bench::total_threads_count); if (!dont_clean && clbk->count != expected) { std::cout << "expected: " << expected << " get:" << clbk->count << std::endl; throw MAKE_EXCEPTION("(clbk->count!=(iteration_count*total_threads_count))"); } else { if (dont_clean && clbk->count < expected) { std::cout << "expected: " << expected << " get:" << clbk->count << std::endl; throw MAKE_EXCEPTION("(clbk->count!=(iteration_count*total_threads_count))"); } } } std::cout << "stoping storage...\n"; ms = nullptr; } std::cout << "cleaning...\n"; if (dariadb::utils::fs::path_exists(storage_path)) { dariadb::utils::fs::rm(storage_path); } } <|endoftext|>
<commit_before>#include <Halide.h> using namespace Halide; Var x, y; // Downsample with a 1 3 3 1 filter Func downsample(Func f) { Func downx, downy; downx(x, y, _) = (f(2*x-1, y, _) + 3.0f * (f(2*x, y, _) + f(2*x+1, y, _)) + f(2*x+2, y, _)) / 8.0f; downy(x, y, _) = (downx(x, 2*y-1, _) + 3.0f * (downx(x, 2*y, _) + downx(x, 2*y+1, _)) + downx(x, 2*y+2, _)) / 8.0f; return downy; } // Upsample using bilinear interpolation Func upsample(Func f) { Func upx, upy; upx(x, y, _) = 0.25f * f((x/2) - 1 + 2*(x % 2), y, _) + 0.75f * f(x/2, y, _); upy(x, y, _) = 0.25f * upx(x, (y/2) - 1 + 2*(y % 2), _) + 0.75f * upx(x, y/2, _); return upy; } int main(int argc, char **argv) { /* THE ALGORITHM */ // Number of pyramid levels const int J = 8; // number of intensity levels Param<int> levels; // Parameters controlling the filter Param<float> alpha, beta; // Takes a 16-bit input ImageParam input(UInt(16), 3); // loop variables Var c, k; // Make the remapping function as a lookup table. Func remap; Expr fx = cast<float>(x) / 256.0f; remap(x) = alpha*fx*exp(-fx*fx/2.0f); // Convert to floating point Func floating; floating(x, y, c) = cast<float>(input(x, y, c)) / 65535.0f; // Set a boundary condition Func clamped; clamped(x, y, c) = floating(clamp(x, 0, input.width()-1), clamp(y, 0, input.height()-1), c); // Get the luminance channel Func gray; gray(x, y) = 0.299f * clamped(x, y, 0) + 0.587f * clamped(x, y, 1) + 0.114f * clamped(x, y, 2); // Make the processed Gaussian pyramid. Func gPyramid[J]; // Do a lookup into a lut with 256 entires per intensity level Expr level = k * (1.0f / (levels - 1)); Expr idx = gray(x, y)*cast<float>(levels-1)*256.0f; idx = clamp(cast<int>(idx), 0, (levels-1)*256); gPyramid[0](x, y, k) = beta*(gray(x, y) - level) + level + remap(idx - 256*k); for (int j = 1; j < J; j++) { gPyramid[j](x, y, k) = downsample(gPyramid[j-1])(x, y, k); } // Get its laplacian pyramid Func lPyramid[J]; lPyramid[J-1](x, y, k) = gPyramid[J-1](x, y, k); for (int j = J-2; j >= 0; j--) { lPyramid[j](x, y, k) = gPyramid[j](x, y, k) - upsample(gPyramid[j+1])(x, y, k); } // Make the Gaussian pyramid of the input Func inGPyramid[J]; inGPyramid[0](x, y) = gray(x, y); for (int j = 1; j < J; j++) { inGPyramid[j](x, y) = downsample(inGPyramid[j-1])(x, y); } // Make the laplacian pyramid of the output Func outLPyramid[J]; for (int j = 0; j < J; j++) { // Split input pyramid value into integer and floating parts Expr level = inGPyramid[j](x, y) * cast<float>(levels-1); Expr li = clamp(cast<int>(level), 0, levels-2); Expr lf = level - cast<float>(li); // Linearly interpolate between the nearest processed pyramid levels outLPyramid[j](x, y) = (1.0f - lf) * lPyramid[j](x, y, li) + lf * lPyramid[j](x, y, li+1); } // Make the Gaussian pyramid of the output Func outGPyramid[J]; outGPyramid[J-1](x, y) = outLPyramid[J-1](x, y); for (int j = J-2; j >= 0; j--) { outGPyramid[j](x, y) = upsample(outGPyramid[j+1])(x, y) + outLPyramid[j](x, y); } // Reintroduce color (Connelly: use eps to avoid scaling up noise w/ apollo3.png input) Func color; float eps = 0.01f; color(x, y, c) = outGPyramid[0](x, y) * (clamped(x, y, c)+eps) / (gray(x, y)+eps); Func output("local_laplacian"); // Convert back to 16-bit output(x, y, c) = cast<uint16_t>(clamp(color(x, y, c), 0.0f, 1.0f) * 65535.0f); /* THE SCHEDULE */ remap.compute_root(); Target target = get_target_from_environment(); if (target.has_gpu_feature()) { // gpu schedule output.compute_root().gpu_tile(x, y, 32, 16, GPU_Default); for (int j = 0; j < J; j++) { int blockw = 32, blockh = 16; if (j > 3) { blockw = 2; blockh = 2; } if (j > 0) inGPyramid[j].compute_root().gpu_tile(x, y, blockw, blockh, GPU_Default); if (j > 0) gPyramid[j].compute_root().reorder(k, x, y).gpu_tile(x, y, blockw, blockh, GPU_Default); outGPyramid[j].compute_root().gpu_tile(x, y, blockw, blockh, GPU_Default); } } else { // cpu schedule Var yi; output.parallel(y, 4).vectorize(x, 4); gray.compute_root().parallel(y, 4).vectorize(x, 4); for (int j = 0; j < 4; j++) { if (j > 0) inGPyramid[j].compute_root().parallel(y, 4).vectorize(x, 4); if (j > 0) gPyramid[j].compute_root().parallel(y, 4).vectorize(x, 4); outGPyramid[j].compute_root().parallel(y, 4).vectorize(x, 4); } for (int j = 4; j < J; j++) { inGPyramid[j].compute_root().parallel(y); gPyramid[j].compute_root().parallel(k); outGPyramid[j].compute_root().parallel(y); } } output.compile_to_file("local_laplacian", levels, alpha, beta, input, target); return 0; } <commit_msg>Reduce block size for local laplacian for lesser gpus<commit_after>#include <Halide.h> using namespace Halide; Var x, y; // Downsample with a 1 3 3 1 filter Func downsample(Func f) { Func downx, downy; downx(x, y, _) = (f(2*x-1, y, _) + 3.0f * (f(2*x, y, _) + f(2*x+1, y, _)) + f(2*x+2, y, _)) / 8.0f; downy(x, y, _) = (downx(x, 2*y-1, _) + 3.0f * (downx(x, 2*y, _) + downx(x, 2*y+1, _)) + downx(x, 2*y+2, _)) / 8.0f; return downy; } // Upsample using bilinear interpolation Func upsample(Func f) { Func upx, upy; upx(x, y, _) = 0.25f * f((x/2) - 1 + 2*(x % 2), y, _) + 0.75f * f(x/2, y, _); upy(x, y, _) = 0.25f * upx(x, (y/2) - 1 + 2*(y % 2), _) + 0.75f * upx(x, y/2, _); return upy; } int main(int argc, char **argv) { /* THE ALGORITHM */ // Number of pyramid levels const int J = 8; // number of intensity levels Param<int> levels; // Parameters controlling the filter Param<float> alpha, beta; // Takes a 16-bit input ImageParam input(UInt(16), 3); // loop variables Var c, k; // Make the remapping function as a lookup table. Func remap; Expr fx = cast<float>(x) / 256.0f; remap(x) = alpha*fx*exp(-fx*fx/2.0f); // Convert to floating point Func floating; floating(x, y, c) = cast<float>(input(x, y, c)) / 65535.0f; // Set a boundary condition Func clamped; clamped(x, y, c) = floating(clamp(x, 0, input.width()-1), clamp(y, 0, input.height()-1), c); // Get the luminance channel Func gray; gray(x, y) = 0.299f * clamped(x, y, 0) + 0.587f * clamped(x, y, 1) + 0.114f * clamped(x, y, 2); // Make the processed Gaussian pyramid. Func gPyramid[J]; // Do a lookup into a lut with 256 entires per intensity level Expr level = k * (1.0f / (levels - 1)); Expr idx = gray(x, y)*cast<float>(levels-1)*256.0f; idx = clamp(cast<int>(idx), 0, (levels-1)*256); gPyramid[0](x, y, k) = beta*(gray(x, y) - level) + level + remap(idx - 256*k); for (int j = 1; j < J; j++) { gPyramid[j](x, y, k) = downsample(gPyramid[j-1])(x, y, k); } // Get its laplacian pyramid Func lPyramid[J]; lPyramid[J-1](x, y, k) = gPyramid[J-1](x, y, k); for (int j = J-2; j >= 0; j--) { lPyramid[j](x, y, k) = gPyramid[j](x, y, k) - upsample(gPyramid[j+1])(x, y, k); } // Make the Gaussian pyramid of the input Func inGPyramid[J]; inGPyramid[0](x, y) = gray(x, y); for (int j = 1; j < J; j++) { inGPyramid[j](x, y) = downsample(inGPyramid[j-1])(x, y); } // Make the laplacian pyramid of the output Func outLPyramid[J]; for (int j = 0; j < J; j++) { // Split input pyramid value into integer and floating parts Expr level = inGPyramid[j](x, y) * cast<float>(levels-1); Expr li = clamp(cast<int>(level), 0, levels-2); Expr lf = level - cast<float>(li); // Linearly interpolate between the nearest processed pyramid levels outLPyramid[j](x, y) = (1.0f - lf) * lPyramid[j](x, y, li) + lf * lPyramid[j](x, y, li+1); } // Make the Gaussian pyramid of the output Func outGPyramid[J]; outGPyramid[J-1](x, y) = outLPyramid[J-1](x, y); for (int j = J-2; j >= 0; j--) { outGPyramid[j](x, y) = upsample(outGPyramid[j+1])(x, y) + outLPyramid[j](x, y); } // Reintroduce color (Connelly: use eps to avoid scaling up noise w/ apollo3.png input) Func color; float eps = 0.01f; color(x, y, c) = outGPyramid[0](x, y) * (clamped(x, y, c)+eps) / (gray(x, y)+eps); Func output("local_laplacian"); // Convert back to 16-bit output(x, y, c) = cast<uint16_t>(clamp(color(x, y, c), 0.0f, 1.0f) * 65535.0f); /* THE SCHEDULE */ remap.compute_root(); Target target = get_target_from_environment(); if (target.has_gpu_feature()) { // gpu schedule output.compute_root().gpu_tile(x, y, 16, 8, GPU_Default); for (int j = 0; j < J; j++) { int blockw = 16, blockh = 8; if (j > 3) { blockw = 2; blockh = 2; } if (j > 0) inGPyramid[j].compute_root().gpu_tile(x, y, blockw, blockh, GPU_Default); if (j > 0) gPyramid[j].compute_root().reorder(k, x, y).gpu_tile(x, y, blockw, blockh, GPU_Default); outGPyramid[j].compute_root().gpu_tile(x, y, blockw, blockh, GPU_Default); } } else { // cpu schedule Var yi; output.parallel(y, 4).vectorize(x, 4); gray.compute_root().parallel(y, 4).vectorize(x, 4); for (int j = 0; j < 4; j++) { if (j > 0) inGPyramid[j].compute_root().parallel(y, 4).vectorize(x, 4); if (j > 0) gPyramid[j].compute_root().parallel(y, 4).vectorize(x, 4); outGPyramid[j].compute_root().parallel(y, 4).vectorize(x, 4); } for (int j = 4; j < J; j++) { inGPyramid[j].compute_root().parallel(y); gPyramid[j].compute_root().parallel(k); outGPyramid[j].compute_root().parallel(y); } } output.compile_to_file("local_laplacian", levels, alpha, beta, input, target); return 0; } <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Copyright (c) 2011, Willow Garage, 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 Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ #include <boost/thread/thread.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/io/openni_grabber.h> #include <pcl/io/pcd_io.h> #include <pcl/visualization/cloud_viewer.h> #include <pcl/io/openni_camera/openni_driver.h> #include <pcl/features/integral_image_normal.h> #include <pcl/console/parse.h> #include <pcl/common/time.h> #define FPS_CALC(_WHAT_) \ do \ { \ static unsigned count = 0;\ static double last = pcl::getTime ();\ if (++count == 100) \ { \ double now = pcl::getTime (); \ std::cout << "Average framerate("<< _WHAT_ << "): " << double(count)/double(now - last) << " Hz" << std::endl; \ count = 0; \ last = now; \ } \ }while(false) template <typename PointType> class OpenNIIntegralImageNormalEstimation { public: typedef pcl::PointCloud<PointType> Cloud; typedef typename Cloud::Ptr CloudPtr; typedef typename Cloud::ConstPtr CloudConstPtr; OpenNIIntegralImageNormalEstimation (const std::string& device_id = "") : viewer ("PCL OpenNI NormalEstimation Viewer") , device_id_(device_id) { ne_.setNormalEstimationMethod (pcl::IntegralImageNormalEstimation<PointType, pcl::Normal>::AVERAGE_3D_GRADIENT); // ne_.setNormalEstimationMethod (pcl::IntegralImageNormalEstimation<PointType, pcl::Normal>::COVARIANCE_MATRIX); ne_.setRectSize (2, 2); new_cloud_ = false; } void cloud_cb (const CloudConstPtr& cloud) { boost::mutex::scoped_lock lock (mtx_); //lock while we set our cloud; FPS_CALC ("computation"); // Estimate surface normals ne_.setInputCloud (cloud); normals_.reset (new pcl::PointCloud<pcl::Normal>); ne_.compute (*normals_); cloud_ = cloud; new_cloud_ = true; } void viz_cb (pcl::visualization::PCLVisualizer& viz) { boost::mutex::scoped_lock lock (mtx_); if (!cloud_) { sleep (1); return; } CloudConstPtr temp_cloud; temp_cloud.swap (cloud_); //here we set cloud_ to null, so that if (!viz.updatePointCloud<PointType> (temp_cloud, "OpenNICloud")) { viz.addPointCloud<PointType> (temp_cloud, "OpenNICloud"); viz.resetCameraViewpoint ("OpenNICloud"); } // Render the data if (new_cloud_ && normals_) { viz.removePointCloud ("normalcloud"); viz.addPointCloudNormals<PointType, pcl::Normal> (temp_cloud, normals_, 200, 0.1, "normalcloud"); new_cloud_ = false; } } void run () { pcl::Grabber* interface = new pcl::OpenNIGrabber (device_id_); boost::function<void (const CloudConstPtr&)> f = boost::bind (&OpenNIIntegralImageNormalEstimation::cloud_cb, this, _1); boost::signals2::connection c = interface->registerCallback (f); viewer.runOnVisualizationThread (boost::bind(&OpenNIIntegralImageNormalEstimation::viz_cb, this, _1), "viz_cb"); interface->start (); while (!viewer.wasStopped ()) { sleep (10); } interface->stop (); } pcl::IntegralImageNormalEstimation<PointType, pcl::Normal> ne_; pcl::visualization::CloudViewer viewer; std::string device_id_; boost::mutex mtx_; // Data pcl::PointCloud<pcl::Normal>::Ptr normals_; CloudConstPtr cloud_; bool new_cloud_; }; void usage (char ** argv) { std::cout << "usage: " << argv[0] << " <device_id> <options>\n\n"; openni_wrapper::OpenNIDriver& driver = openni_wrapper::OpenNIDriver::getInstance (); if (driver.getNumberDevices () > 0) { for (unsigned deviceIdx = 0; deviceIdx < driver.getNumberDevices (); ++deviceIdx) { cout << "Device: " << deviceIdx + 1 << ", vendor: " << driver.getVendorName (deviceIdx) << ", product: " << driver.getProductName (deviceIdx) << ", connected: " << (int)driver.getBus (deviceIdx) << " @ " << (int)driver.getAddress (deviceIdx) << ", serial number: \'" << driver.getSerialNumber (deviceIdx) << "\'" << endl; cout << "device_id may be #1, #2, ... for the first second etc device in the list or" << endl << " bus@address for the device connected to a specific usb-bus / address combination (wotks only in Linux) or" << endl << " <serial-number> (only in Linux and for devices which provide serial numbers)" << endl; } } else cout << "No devices connected." << endl; } int main (int argc, char ** argv) { if (argc < 2) { usage (argv); return 1; } std::string arg (argv[1]); if (arg == "--help" || arg == "-h") { usage (argv); return 1; } pcl::OpenNIGrabber grabber (arg); if (grabber.providesCallback<pcl::OpenNIGrabber::sig_cb_openni_point_cloud_rgb> ()) { OpenNIIntegralImageNormalEstimation<pcl::PointXYZRGB> v (arg); v.run (); } else { OpenNIIntegralImageNormalEstimation<pcl::PointXYZ> v (arg); v.run (); } return (0); } <commit_msg>replacing with boost::this_thread::sleep<commit_after>/* * Software License Agreement (BSD License) * * Copyright (c) 2011, Willow Garage, 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 Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ #include <boost/thread/thread.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/io/openni_grabber.h> #include <pcl/io/pcd_io.h> #include <pcl/visualization/cloud_viewer.h> #include <pcl/io/openni_camera/openni_driver.h> #include <pcl/features/integral_image_normal.h> #include <pcl/console/parse.h> #include <pcl/common/time.h> #define FPS_CALC(_WHAT_) \ do \ { \ static unsigned count = 0;\ static double last = pcl::getTime ();\ if (++count == 100) \ { \ double now = pcl::getTime (); \ std::cout << "Average framerate("<< _WHAT_ << "): " << double(count)/double(now - last) << " Hz" << std::endl; \ count = 0; \ last = now; \ } \ }while(false) template <typename PointType> class OpenNIIntegralImageNormalEstimation { public: typedef pcl::PointCloud<PointType> Cloud; typedef typename Cloud::Ptr CloudPtr; typedef typename Cloud::ConstPtr CloudConstPtr; OpenNIIntegralImageNormalEstimation (const std::string& device_id = "") : viewer ("PCL OpenNI NormalEstimation Viewer") , device_id_(device_id) { ne_.setNormalEstimationMethod (pcl::IntegralImageNormalEstimation<PointType, pcl::Normal>::AVERAGE_3D_GRADIENT); // ne_.setNormalEstimationMethod (pcl::IntegralImageNormalEstimation<PointType, pcl::Normal>::COVARIANCE_MATRIX); ne_.setRectSize (2, 2); new_cloud_ = false; } void cloud_cb (const CloudConstPtr& cloud) { boost::mutex::scoped_lock lock (mtx_); //lock while we set our cloud; FPS_CALC ("computation"); // Estimate surface normals ne_.setInputCloud (cloud); normals_.reset (new pcl::PointCloud<pcl::Normal>); ne_.compute (*normals_); cloud_ = cloud; new_cloud_ = true; } void viz_cb (pcl::visualization::PCLVisualizer& viz) { boost::mutex::scoped_lock lock (mtx_); if (!cloud_) { boost::this_thread::sleep (1); return; } CloudConstPtr temp_cloud; temp_cloud.swap (cloud_); //here we set cloud_ to null, so that if (!viz.updatePointCloud<PointType> (temp_cloud, "OpenNICloud")) { viz.addPointCloud<PointType> (temp_cloud, "OpenNICloud"); viz.resetCameraViewpoint ("OpenNICloud"); } // Render the data if (new_cloud_ && normals_) { viz.removePointCloud ("normalcloud"); viz.addPointCloudNormals<PointType, pcl::Normal> (temp_cloud, normals_, 200, 0.1, "normalcloud"); new_cloud_ = false; } } void run () { pcl::Grabber* interface = new pcl::OpenNIGrabber (device_id_); boost::function<void (const CloudConstPtr&)> f = boost::bind (&OpenNIIntegralImageNormalEstimation::cloud_cb, this, _1); boost::signals2::connection c = interface->registerCallback (f); viewer.runOnVisualizationThread (boost::bind(&OpenNIIntegralImageNormalEstimation::viz_cb, this, _1), "viz_cb"); interface->start (); while (!viewer.wasStopped ()) { boost::this_thread::sleep (1); } interface->stop (); } pcl::IntegralImageNormalEstimation<PointType, pcl::Normal> ne_; pcl::visualization::CloudViewer viewer; std::string device_id_; boost::mutex mtx_; // Data pcl::PointCloud<pcl::Normal>::Ptr normals_; CloudConstPtr cloud_; bool new_cloud_; }; void usage (char ** argv) { std::cout << "usage: " << argv[0] << " <device_id> <options>\n\n"; openni_wrapper::OpenNIDriver& driver = openni_wrapper::OpenNIDriver::getInstance (); if (driver.getNumberDevices () > 0) { for (unsigned deviceIdx = 0; deviceIdx < driver.getNumberDevices (); ++deviceIdx) { cout << "Device: " << deviceIdx + 1 << ", vendor: " << driver.getVendorName (deviceIdx) << ", product: " << driver.getProductName (deviceIdx) << ", connected: " << (int)driver.getBus (deviceIdx) << " @ " << (int)driver.getAddress (deviceIdx) << ", serial number: \'" << driver.getSerialNumber (deviceIdx) << "\'" << endl; cout << "device_id may be #1, #2, ... for the first second etc device in the list or" << endl << " bus@address for the device connected to a specific usb-bus / address combination (wotks only in Linux) or" << endl << " <serial-number> (only in Linux and for devices which provide serial numbers)" << endl; } } else cout << "No devices connected." << endl; } int main (int argc, char ** argv) { if (argc < 2) { usage (argv); return 1; } std::string arg (argv[1]); if (arg == "--help" || arg == "-h") { usage (argv); return 1; } pcl::OpenNIGrabber grabber (arg); if (grabber.providesCallback<pcl::OpenNIGrabber::sig_cb_openni_point_cloud_rgb> ()) { OpenNIIntegralImageNormalEstimation<pcl::PointXYZRGB> v (arg); v.run (); } else { OpenNIIntegralImageNormalEstimation<pcl::PointXYZ> v (arg); v.run (); } return (0); } <|endoftext|>
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "apps/ui/views/native_app_window_views.h" #include "apps/app_window.h" #include "base/threading/sequenced_worker_pool.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_view.h" #include "extensions/common/draggable_region.h" #include "third_party/skia/include/core/SkRegion.h" #include "ui/gfx/path.h" #include "ui/views/controls/webview/webview.h" #include "ui/views/widget/widget.h" #include "ui/views/window/non_client_view.h" #if defined(USE_AURA) #include "ui/aura/window.h" #endif namespace apps { NativeAppWindowViews::NativeAppWindowViews() : app_window_(NULL), web_view_(NULL), window_(NULL), frameless_(false), transparent_background_(false), resizable_(false) {} void NativeAppWindowViews::Init(AppWindow* app_window, const AppWindow::CreateParams& create_params) { app_window_ = app_window; frameless_ = create_params.frame == AppWindow::FRAME_NONE; transparent_background_ = create_params.transparent_background; resizable_ = create_params.resizable; Observe(app_window_->web_contents()); window_ = new views::Widget; InitializeWindow(app_window, create_params); OnViewWasResized(); window_->AddObserver(this); } NativeAppWindowViews::~NativeAppWindowViews() { web_view_->SetWebContents(NULL); } void NativeAppWindowViews::InitializeWindow( AppWindow* app_window, const AppWindow::CreateParams& create_params) { // Stub implementation. See also ChromeNativeAppWindowViews. views::Widget::InitParams init_params(views::Widget::InitParams::TYPE_WINDOW); init_params.delegate = this; init_params.top_level = true; init_params.keep_on_top = create_params.always_on_top; window_->Init(init_params); window_->CenterWindow( create_params.GetInitialWindowBounds(gfx::Insets()).size()); } // ui::BaseWindow implementation. bool NativeAppWindowViews::IsActive() const { return window_->IsActive(); } bool NativeAppWindowViews::IsMaximized() const { return window_->IsMaximized(); } bool NativeAppWindowViews::IsMinimized() const { return window_->IsMinimized(); } bool NativeAppWindowViews::IsFullscreen() const { return window_->IsFullscreen(); } gfx::NativeWindow NativeAppWindowViews::GetNativeWindow() { return window_->GetNativeWindow(); } gfx::Rect NativeAppWindowViews::GetRestoredBounds() const { return window_->GetRestoredBounds(); } ui::WindowShowState NativeAppWindowViews::GetRestoredState() const { // Stub implementation. See also ChromeNativeAppWindowViews. if (IsMaximized()) return ui::SHOW_STATE_MAXIMIZED; if (IsFullscreen()) return ui::SHOW_STATE_FULLSCREEN; return ui::SHOW_STATE_NORMAL; } gfx::Rect NativeAppWindowViews::GetBounds() const { return window_->GetWindowBoundsInScreen(); } void NativeAppWindowViews::Show() { if (window_->IsVisible()) { window_->Activate(); return; } window_->Show(); } void NativeAppWindowViews::ShowInactive() { if (window_->IsVisible()) return; window_->ShowInactive(); } void NativeAppWindowViews::Hide() { window_->Hide(); } void NativeAppWindowViews::Close() { window_->Close(); } void NativeAppWindowViews::Activate() { window_->Activate(); } void NativeAppWindowViews::Deactivate() { window_->Deactivate(); } void NativeAppWindowViews::Maximize() { window_->Maximize(); } void NativeAppWindowViews::Minimize() { window_->Minimize(); } void NativeAppWindowViews::Restore() { window_->Restore(); } void NativeAppWindowViews::SetBounds(const gfx::Rect& bounds) { window_->SetBounds(bounds); } void NativeAppWindowViews::FlashFrame(bool flash) { window_->FlashFrame(flash); } bool NativeAppWindowViews::IsAlwaysOnTop() const { // Stub implementation. See also ChromeNativeAppWindowViews. return window_->IsAlwaysOnTop(); } void NativeAppWindowViews::SetAlwaysOnTop(bool always_on_top) { window_->SetAlwaysOnTop(always_on_top); } gfx::NativeView NativeAppWindowViews::GetHostView() const { return window_->GetNativeView(); } gfx::Point NativeAppWindowViews::GetDialogPosition(const gfx::Size& size) { gfx::Size app_window_size = window_->GetWindowBoundsInScreen().size(); return gfx::Point(app_window_size.width() / 2 - size.width() / 2, app_window_size.height() / 2 - size.height() / 2); } gfx::Size NativeAppWindowViews::GetMaximumDialogSize() { return window_->GetWindowBoundsInScreen().size(); } void NativeAppWindowViews::AddObserver( web_modal::ModalDialogHostObserver* observer) { observer_list_.AddObserver(observer); } void NativeAppWindowViews::RemoveObserver( web_modal::ModalDialogHostObserver* observer) { observer_list_.RemoveObserver(observer); } void NativeAppWindowViews::OnViewWasResized() { FOR_EACH_OBSERVER(web_modal::ModalDialogHostObserver, observer_list_, OnPositionRequiresUpdate()); } // WidgetDelegate implementation. void NativeAppWindowViews::OnWidgetMove() { app_window_->OnNativeWindowChanged(); } views::View* NativeAppWindowViews::GetInitiallyFocusedView() { return web_view_; } bool NativeAppWindowViews::CanResize() const { return resizable_ && !size_constraints_.HasFixedSize(); } bool NativeAppWindowViews::CanMaximize() const { return resizable_ && !size_constraints_.HasMaximumSize() && !app_window_->window_type_is_panel(); } base::string16 NativeAppWindowViews::GetWindowTitle() const { return app_window_->GetTitle(); } bool NativeAppWindowViews::ShouldShowWindowTitle() const { return app_window_->window_type() == AppWindow::WINDOW_TYPE_V1_PANEL; } bool NativeAppWindowViews::ShouldShowWindowIcon() const { return app_window_->window_type() == AppWindow::WINDOW_TYPE_V1_PANEL; } void NativeAppWindowViews::SaveWindowPlacement(const gfx::Rect& bounds, ui::WindowShowState show_state) { views::WidgetDelegate::SaveWindowPlacement(bounds, show_state); app_window_->OnNativeWindowChanged(); } void NativeAppWindowViews::DeleteDelegate() { window_->RemoveObserver(this); app_window_->OnNativeClose(); } views::Widget* NativeAppWindowViews::GetWidget() { return window_; } const views::Widget* NativeAppWindowViews::GetWidget() const { return window_; } views::View* NativeAppWindowViews::GetContentsView() { return this; } bool NativeAppWindowViews::ShouldDescendIntoChildForEventHandling( gfx::NativeView child, const gfx::Point& location) { #if defined(USE_AURA) if (child->Contains(web_view_->web_contents()->GetView()->GetNativeView())) { // App window should claim mouse events that fall within the draggable // region. return !draggable_region_.get() || !draggable_region_->contains(location.x(), location.y()); } #endif return true; } // WidgetObserver implementation. void NativeAppWindowViews::OnWidgetVisibilityChanged(views::Widget* widget, bool visible) { app_window_->OnNativeWindowChanged(); } void NativeAppWindowViews::OnWidgetActivationChanged(views::Widget* widget, bool active) { app_window_->OnNativeWindowChanged(); if (active) app_window_->OnNativeWindowActivated(); } // WebContentsObserver implementation. void NativeAppWindowViews::RenderViewCreated( content::RenderViewHost* render_view_host) { if (transparent_background_) { // Use a background with transparency to trigger transparency in Webkit. SkBitmap background; background.setConfig(SkBitmap::kARGB_8888_Config, 1, 1); background.allocPixels(); background.eraseARGB(0x00, 0x00, 0x00, 0x00); content::RenderWidgetHostView* view = render_view_host->GetView(); DCHECK(view); view->SetBackground(background); } } void NativeAppWindowViews::RenderViewHostChanged( content::RenderViewHost* old_host, content::RenderViewHost* new_host) { OnViewWasResized(); } // views::View implementation. void NativeAppWindowViews::Layout() { DCHECK(web_view_); web_view_->SetBounds(0, 0, width(), height()); OnViewWasResized(); } void NativeAppWindowViews::ViewHierarchyChanged( const ViewHierarchyChangedDetails& details) { if (details.is_add && details.child == this) { web_view_ = new views::WebView(NULL); AddChildView(web_view_); web_view_->SetWebContents(app_window_->web_contents()); } } gfx::Size NativeAppWindowViews::GetMinimumSize() { return size_constraints_.GetMinimumSize(); } gfx::Size NativeAppWindowViews::GetMaximumSize() { return size_constraints_.GetMaximumSize(); } void NativeAppWindowViews::OnFocus() { web_view_->RequestFocus(); } // NativeAppWindow implementation. void NativeAppWindowViews::SetFullscreen(int fullscreen_types) { // Stub implementation. See also ChromeNativeAppWindowViews. window_->SetFullscreen(fullscreen_types != AppWindow::FULLSCREEN_TYPE_NONE); } bool NativeAppWindowViews::IsFullscreenOrPending() const { // Stub implementation. See also ChromeNativeAppWindowViews. return window_->IsFullscreen(); } bool NativeAppWindowViews::IsDetached() const { // Stub implementation. See also ChromeNativeAppWindowViews. return false; } void NativeAppWindowViews::UpdateWindowIcon() { window_->UpdateWindowIcon(); } void NativeAppWindowViews::UpdateWindowTitle() { window_->UpdateWindowTitle(); } void NativeAppWindowViews::UpdateBadgeIcon() { // Stub implementation. See also ChromeNativeAppWindowViews. } void NativeAppWindowViews::UpdateDraggableRegions( const std::vector<extensions::DraggableRegion>& regions) { // Draggable region is not supported for non-frameless window. if (!frameless_) return; draggable_region_.reset(AppWindow::RawDraggableRegionsToSkRegion(regions)); OnViewWasResized(); } SkRegion* NativeAppWindowViews::GetDraggableRegion() { return draggable_region_.get(); } void NativeAppWindowViews::UpdateShape(scoped_ptr<SkRegion> region) { // Stub implementation. See also ChromeNativeAppWindowViews. } void NativeAppWindowViews::HandleKeyboardEvent( const content::NativeWebKeyboardEvent& event) { unhandled_keyboard_event_handler_.HandleKeyboardEvent(event, GetFocusManager()); } bool NativeAppWindowViews::IsFrameless() const { return frameless_; } bool NativeAppWindowViews::HasFrameColor() const { return false; } SkColor NativeAppWindowViews::FrameColor() const { return SK_ColorBLACK; } gfx::Insets NativeAppWindowViews::GetFrameInsets() const { if (frameless_) return gfx::Insets(); // The pretend client_bounds passed in need to be large enough to ensure that // GetWindowBoundsForClientBounds() doesn't decide that it needs more than // the specified amount of space to fit the window controls in, and return a // number larger than the real frame insets. Most window controls are smaller // than 1000x1000px, so this should be big enough. gfx::Rect client_bounds = gfx::Rect(1000, 1000); gfx::Rect window_bounds = window_->non_client_view()->GetWindowBoundsForClientBounds( client_bounds); return window_bounds.InsetsFrom(client_bounds); } void NativeAppWindowViews::HideWithApp() {} void NativeAppWindowViews::ShowWithApp() {} void NativeAppWindowViews::UpdateShelfMenu() {} gfx::Size NativeAppWindowViews::GetContentMinimumSize() const { return size_constraints_.GetMinimumSize(); } gfx::Size NativeAppWindowViews::GetContentMaximumSize() const { return size_constraints_.GetMaximumSize(); } void NativeAppWindowViews::SetContentSizeConstraints( const gfx::Size& min_size, const gfx::Size& max_size) { size_constraints_.set_minimum_size(min_size); size_constraints_.set_maximum_size(max_size); } } // namespace apps <commit_msg>Set size constraints before native app window creation<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "apps/ui/views/native_app_window_views.h" #include "apps/app_window.h" #include "base/threading/sequenced_worker_pool.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_view.h" #include "extensions/common/draggable_region.h" #include "third_party/skia/include/core/SkRegion.h" #include "ui/gfx/path.h" #include "ui/views/controls/webview/webview.h" #include "ui/views/widget/widget.h" #include "ui/views/window/non_client_view.h" #if defined(USE_AURA) #include "ui/aura/window.h" #endif namespace apps { NativeAppWindowViews::NativeAppWindowViews() : app_window_(NULL), web_view_(NULL), window_(NULL), frameless_(false), transparent_background_(false), resizable_(false) {} void NativeAppWindowViews::Init(AppWindow* app_window, const AppWindow::CreateParams& create_params) { app_window_ = app_window; frameless_ = create_params.frame == AppWindow::FRAME_NONE; transparent_background_ = create_params.transparent_background; resizable_ = create_params.resizable; size_constraints_.set_minimum_size( create_params.GetContentMinimumSize(gfx::Insets())); size_constraints_.set_maximum_size( create_params.GetContentMaximumSize(gfx::Insets())); Observe(app_window_->web_contents()); window_ = new views::Widget; InitializeWindow(app_window, create_params); OnViewWasResized(); window_->AddObserver(this); } NativeAppWindowViews::~NativeAppWindowViews() { web_view_->SetWebContents(NULL); } void NativeAppWindowViews::InitializeWindow( AppWindow* app_window, const AppWindow::CreateParams& create_params) { // Stub implementation. See also ChromeNativeAppWindowViews. views::Widget::InitParams init_params(views::Widget::InitParams::TYPE_WINDOW); init_params.delegate = this; init_params.top_level = true; init_params.keep_on_top = create_params.always_on_top; window_->Init(init_params); window_->CenterWindow( create_params.GetInitialWindowBounds(gfx::Insets()).size()); } // ui::BaseWindow implementation. bool NativeAppWindowViews::IsActive() const { return window_->IsActive(); } bool NativeAppWindowViews::IsMaximized() const { return window_->IsMaximized(); } bool NativeAppWindowViews::IsMinimized() const { return window_->IsMinimized(); } bool NativeAppWindowViews::IsFullscreen() const { return window_->IsFullscreen(); } gfx::NativeWindow NativeAppWindowViews::GetNativeWindow() { return window_->GetNativeWindow(); } gfx::Rect NativeAppWindowViews::GetRestoredBounds() const { return window_->GetRestoredBounds(); } ui::WindowShowState NativeAppWindowViews::GetRestoredState() const { // Stub implementation. See also ChromeNativeAppWindowViews. if (IsMaximized()) return ui::SHOW_STATE_MAXIMIZED; if (IsFullscreen()) return ui::SHOW_STATE_FULLSCREEN; return ui::SHOW_STATE_NORMAL; } gfx::Rect NativeAppWindowViews::GetBounds() const { return window_->GetWindowBoundsInScreen(); } void NativeAppWindowViews::Show() { if (window_->IsVisible()) { window_->Activate(); return; } window_->Show(); } void NativeAppWindowViews::ShowInactive() { if (window_->IsVisible()) return; window_->ShowInactive(); } void NativeAppWindowViews::Hide() { window_->Hide(); } void NativeAppWindowViews::Close() { window_->Close(); } void NativeAppWindowViews::Activate() { window_->Activate(); } void NativeAppWindowViews::Deactivate() { window_->Deactivate(); } void NativeAppWindowViews::Maximize() { window_->Maximize(); } void NativeAppWindowViews::Minimize() { window_->Minimize(); } void NativeAppWindowViews::Restore() { window_->Restore(); } void NativeAppWindowViews::SetBounds(const gfx::Rect& bounds) { window_->SetBounds(bounds); } void NativeAppWindowViews::FlashFrame(bool flash) { window_->FlashFrame(flash); } bool NativeAppWindowViews::IsAlwaysOnTop() const { // Stub implementation. See also ChromeNativeAppWindowViews. return window_->IsAlwaysOnTop(); } void NativeAppWindowViews::SetAlwaysOnTop(bool always_on_top) { window_->SetAlwaysOnTop(always_on_top); } gfx::NativeView NativeAppWindowViews::GetHostView() const { return window_->GetNativeView(); } gfx::Point NativeAppWindowViews::GetDialogPosition(const gfx::Size& size) { gfx::Size app_window_size = window_->GetWindowBoundsInScreen().size(); return gfx::Point(app_window_size.width() / 2 - size.width() / 2, app_window_size.height() / 2 - size.height() / 2); } gfx::Size NativeAppWindowViews::GetMaximumDialogSize() { return window_->GetWindowBoundsInScreen().size(); } void NativeAppWindowViews::AddObserver( web_modal::ModalDialogHostObserver* observer) { observer_list_.AddObserver(observer); } void NativeAppWindowViews::RemoveObserver( web_modal::ModalDialogHostObserver* observer) { observer_list_.RemoveObserver(observer); } void NativeAppWindowViews::OnViewWasResized() { FOR_EACH_OBSERVER(web_modal::ModalDialogHostObserver, observer_list_, OnPositionRequiresUpdate()); } // WidgetDelegate implementation. void NativeAppWindowViews::OnWidgetMove() { app_window_->OnNativeWindowChanged(); } views::View* NativeAppWindowViews::GetInitiallyFocusedView() { return web_view_; } bool NativeAppWindowViews::CanResize() const { return resizable_ && !size_constraints_.HasFixedSize(); } bool NativeAppWindowViews::CanMaximize() const { return resizable_ && !size_constraints_.HasMaximumSize() && !app_window_->window_type_is_panel(); } base::string16 NativeAppWindowViews::GetWindowTitle() const { return app_window_->GetTitle(); } bool NativeAppWindowViews::ShouldShowWindowTitle() const { return app_window_->window_type() == AppWindow::WINDOW_TYPE_V1_PANEL; } bool NativeAppWindowViews::ShouldShowWindowIcon() const { return app_window_->window_type() == AppWindow::WINDOW_TYPE_V1_PANEL; } void NativeAppWindowViews::SaveWindowPlacement(const gfx::Rect& bounds, ui::WindowShowState show_state) { views::WidgetDelegate::SaveWindowPlacement(bounds, show_state); app_window_->OnNativeWindowChanged(); } void NativeAppWindowViews::DeleteDelegate() { window_->RemoveObserver(this); app_window_->OnNativeClose(); } views::Widget* NativeAppWindowViews::GetWidget() { return window_; } const views::Widget* NativeAppWindowViews::GetWidget() const { return window_; } views::View* NativeAppWindowViews::GetContentsView() { return this; } bool NativeAppWindowViews::ShouldDescendIntoChildForEventHandling( gfx::NativeView child, const gfx::Point& location) { #if defined(USE_AURA) if (child->Contains(web_view_->web_contents()->GetView()->GetNativeView())) { // App window should claim mouse events that fall within the draggable // region. return !draggable_region_.get() || !draggable_region_->contains(location.x(), location.y()); } #endif return true; } // WidgetObserver implementation. void NativeAppWindowViews::OnWidgetVisibilityChanged(views::Widget* widget, bool visible) { app_window_->OnNativeWindowChanged(); } void NativeAppWindowViews::OnWidgetActivationChanged(views::Widget* widget, bool active) { app_window_->OnNativeWindowChanged(); if (active) app_window_->OnNativeWindowActivated(); } // WebContentsObserver implementation. void NativeAppWindowViews::RenderViewCreated( content::RenderViewHost* render_view_host) { if (transparent_background_) { // Use a background with transparency to trigger transparency in Webkit. SkBitmap background; background.setConfig(SkBitmap::kARGB_8888_Config, 1, 1); background.allocPixels(); background.eraseARGB(0x00, 0x00, 0x00, 0x00); content::RenderWidgetHostView* view = render_view_host->GetView(); DCHECK(view); view->SetBackground(background); } } void NativeAppWindowViews::RenderViewHostChanged( content::RenderViewHost* old_host, content::RenderViewHost* new_host) { OnViewWasResized(); } // views::View implementation. void NativeAppWindowViews::Layout() { DCHECK(web_view_); web_view_->SetBounds(0, 0, width(), height()); OnViewWasResized(); } void NativeAppWindowViews::ViewHierarchyChanged( const ViewHierarchyChangedDetails& details) { if (details.is_add && details.child == this) { web_view_ = new views::WebView(NULL); AddChildView(web_view_); web_view_->SetWebContents(app_window_->web_contents()); } } gfx::Size NativeAppWindowViews::GetMinimumSize() { return size_constraints_.GetMinimumSize(); } gfx::Size NativeAppWindowViews::GetMaximumSize() { return size_constraints_.GetMaximumSize(); } void NativeAppWindowViews::OnFocus() { web_view_->RequestFocus(); } // NativeAppWindow implementation. void NativeAppWindowViews::SetFullscreen(int fullscreen_types) { // Stub implementation. See also ChromeNativeAppWindowViews. window_->SetFullscreen(fullscreen_types != AppWindow::FULLSCREEN_TYPE_NONE); } bool NativeAppWindowViews::IsFullscreenOrPending() const { // Stub implementation. See also ChromeNativeAppWindowViews. return window_->IsFullscreen(); } bool NativeAppWindowViews::IsDetached() const { // Stub implementation. See also ChromeNativeAppWindowViews. return false; } void NativeAppWindowViews::UpdateWindowIcon() { window_->UpdateWindowIcon(); } void NativeAppWindowViews::UpdateWindowTitle() { window_->UpdateWindowTitle(); } void NativeAppWindowViews::UpdateBadgeIcon() { // Stub implementation. See also ChromeNativeAppWindowViews. } void NativeAppWindowViews::UpdateDraggableRegions( const std::vector<extensions::DraggableRegion>& regions) { // Draggable region is not supported for non-frameless window. if (!frameless_) return; draggable_region_.reset(AppWindow::RawDraggableRegionsToSkRegion(regions)); OnViewWasResized(); } SkRegion* NativeAppWindowViews::GetDraggableRegion() { return draggable_region_.get(); } void NativeAppWindowViews::UpdateShape(scoped_ptr<SkRegion> region) { // Stub implementation. See also ChromeNativeAppWindowViews. } void NativeAppWindowViews::HandleKeyboardEvent( const content::NativeWebKeyboardEvent& event) { unhandled_keyboard_event_handler_.HandleKeyboardEvent(event, GetFocusManager()); } bool NativeAppWindowViews::IsFrameless() const { return frameless_; } bool NativeAppWindowViews::HasFrameColor() const { return false; } SkColor NativeAppWindowViews::FrameColor() const { return SK_ColorBLACK; } gfx::Insets NativeAppWindowViews::GetFrameInsets() const { if (frameless_) return gfx::Insets(); // The pretend client_bounds passed in need to be large enough to ensure that // GetWindowBoundsForClientBounds() doesn't decide that it needs more than // the specified amount of space to fit the window controls in, and return a // number larger than the real frame insets. Most window controls are smaller // than 1000x1000px, so this should be big enough. gfx::Rect client_bounds = gfx::Rect(1000, 1000); gfx::Rect window_bounds = window_->non_client_view()->GetWindowBoundsForClientBounds( client_bounds); return window_bounds.InsetsFrom(client_bounds); } void NativeAppWindowViews::HideWithApp() {} void NativeAppWindowViews::ShowWithApp() {} void NativeAppWindowViews::UpdateShelfMenu() {} gfx::Size NativeAppWindowViews::GetContentMinimumSize() const { return size_constraints_.GetMinimumSize(); } gfx::Size NativeAppWindowViews::GetContentMaximumSize() const { return size_constraints_.GetMaximumSize(); } void NativeAppWindowViews::SetContentSizeConstraints( const gfx::Size& min_size, const gfx::Size& max_size) { size_constraints_.set_minimum_size(min_size); size_constraints_.set_maximum_size(max_size); } } // namespace apps <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2016 ArangoDB GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Dr. Frank Celler //////////////////////////////////////////////////////////////////////////////// #include "StatisticsFeature.h" #include "Logger/Logger.h" #include "ProgramOptions/ProgramOptions.h" #include "ProgramOptions/Section.h" #include "Statistics/ConnectionStatistics.h" #include "Statistics/RequestStatistics.h" #include "Statistics/ServerStatistics.h" using namespace arangodb; using namespace arangodb::application_features; using namespace arangodb::basics; using namespace arangodb::options; // ----------------------------------------------------------------------------- // --SECTION-- global variables // ----------------------------------------------------------------------------- namespace arangodb { namespace basics { StatisticsCounter TRI_AsyncRequestsStatistics; StatisticsCounter TRI_HttpConnectionsStatistics; StatisticsCounter TRI_TotalRequestsStatistics; StatisticsDistribution* TRI_BytesReceivedDistributionStatistics; StatisticsDistribution* TRI_BytesSentDistributionStatistics; StatisticsDistribution* TRI_ConnectionTimeDistributionStatistics; StatisticsDistribution* TRI_IoTimeDistributionStatistics; StatisticsDistribution* TRI_QueueTimeDistributionStatistics; StatisticsDistribution* TRI_RequestTimeDistributionStatistics; StatisticsDistribution* TRI_TotalTimeDistributionStatistics; StatisticsVector TRI_BytesReceivedDistributionVectorStatistics; StatisticsVector TRI_BytesSentDistributionVectorStatistics; StatisticsVector TRI_ConnectionTimeDistributionVectorStatistics; StatisticsVector TRI_RequestTimeDistributionVectorStatistics; std::vector<StatisticsCounter> TRI_MethodRequestsStatistics; } } // ----------------------------------------------------------------------------- // --SECTION-- StatisticsThread // ----------------------------------------------------------------------------- class arangodb::StatisticsThread final : public Thread { public: StatisticsThread() : Thread("Statistics") {} ~StatisticsThread() { shutdown(); } public: void run() override { uint64_t const MAX_SLEEP_TIME = 250 * 1000; uint64_t sleepTime = 100 * 1000; int nothingHappened = 0; while (!isStopping() && StatisticsFeature::enabled()) { size_t count = RequestStatistics::processAll(); if (count == 0) { if (++nothingHappened == 10 * 30) { // increase sleep time every 30 seconds nothingHappened = 0; sleepTime += 50 * 1000; if (sleepTime > MAX_SLEEP_TIME) { sleepTime = MAX_SLEEP_TIME; } } #ifdef _WIN32 usleep((unsigned long)sleepTime); #else usleep((useconds_t)sleepTime); #endif } else { nothingHappened = 0; if (count < 10) { usleep(10 * 1000); } else if (count < 100) { usleep(1 * 1000); } } } RequestStatistics::shutdown(); ConnectionStatistics::shutdown(); ServerStatistics::shutdown(); } }; // ----------------------------------------------------------------------------- // --SECTION-- StatisticsFeature // ----------------------------------------------------------------------------- StatisticsFeature* StatisticsFeature::STATISTICS = nullptr; StatisticsFeature::StatisticsFeature( application_features::ApplicationServer* server) : ApplicationFeature(server, "Statistics"), _statistics(true) { startsAfter("Logger"); } void StatisticsFeature::collectOptions( std::shared_ptr<ProgramOptions> options) { options->addOldOption("server.disable-statistics", "server.statistics"); options->addSection("server", "Server features"); options->addHiddenOption("--server.statistics", "turn statistics gathering on or off", new BooleanParameter(&_statistics)); } void StatisticsFeature::prepare() { // initialize counters for all HTTP request types TRI_MethodRequestsStatistics.clear(); for (int i = 0; i < ((int)arangodb::rest::RequestType::ILLEGAL) + 1; ++i) { StatisticsCounter c; TRI_MethodRequestsStatistics.emplace_back(c); } TRI_ConnectionTimeDistributionVectorStatistics << (0.1) << (1.0) << (60.0); TRI_BytesSentDistributionVectorStatistics << (250) << (1000) << (2 * 1000) << (5 * 1000) << (10 * 1000); TRI_BytesReceivedDistributionVectorStatistics << (250) << (1000) << (2 * 1000) << (5 * 1000) << (10 * 1000); TRI_RequestTimeDistributionVectorStatistics << (0.01) << (0.05) << (0.1) << (0.2) << (0.5) << (1.0); TRI_ConnectionTimeDistributionStatistics = new StatisticsDistribution( TRI_ConnectionTimeDistributionVectorStatistics); TRI_TotalTimeDistributionStatistics = new StatisticsDistribution(TRI_RequestTimeDistributionVectorStatistics); TRI_RequestTimeDistributionStatistics = new StatisticsDistribution(TRI_RequestTimeDistributionVectorStatistics); TRI_QueueTimeDistributionStatistics = new StatisticsDistribution(TRI_RequestTimeDistributionVectorStatistics); TRI_IoTimeDistributionStatistics = new StatisticsDistribution(TRI_RequestTimeDistributionVectorStatistics); TRI_BytesSentDistributionStatistics = new StatisticsDistribution(TRI_BytesSentDistributionVectorStatistics); TRI_BytesReceivedDistributionStatistics = new StatisticsDistribution(TRI_BytesReceivedDistributionVectorStatistics); } void StatisticsFeature::start() { STATISTICS = this; if (!_statistics) { return; } ServerStatistics::initialize(); ConnectionStatistics::initialize(); RequestStatistics::initialize(); _statisticsThread.reset(new StatisticsThread); if (!_statisticsThread->start()) { LOG(FATAL) << "could not start statistics thread"; FATAL_ERROR_EXIT(); } } void StatisticsFeature::unprepare() { if (_statisticsThread != nullptr) { _statisticsThread->beginShutdown(); while (_statisticsThread->isRunning()) { usleep(10000); } } _statisticsThread.reset(); delete TRI_ConnectionTimeDistributionStatistics; TRI_ConnectionTimeDistributionStatistics = nullptr; delete TRI_TotalTimeDistributionStatistics; TRI_TotalTimeDistributionStatistics = nullptr; delete TRI_RequestTimeDistributionStatistics; TRI_RequestTimeDistributionStatistics = nullptr; delete TRI_QueueTimeDistributionStatistics; TRI_QueueTimeDistributionStatistics = nullptr; delete TRI_IoTimeDistributionStatistics; TRI_IoTimeDistributionStatistics = nullptr; delete TRI_BytesSentDistributionStatistics; TRI_BytesSentDistributionStatistics = nullptr; delete TRI_BytesReceivedDistributionStatistics; TRI_BytesReceivedDistributionStatistics = nullptr; STATISTICS = nullptr; } <commit_msg>Move initialization to prepare in StatisticsFeature.<commit_after>//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2016 ArangoDB GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Dr. Frank Celler //////////////////////////////////////////////////////////////////////////////// #include "StatisticsFeature.h" #include "Logger/Logger.h" #include "ProgramOptions/ProgramOptions.h" #include "ProgramOptions/Section.h" #include "Statistics/ConnectionStatistics.h" #include "Statistics/RequestStatistics.h" #include "Statistics/ServerStatistics.h" using namespace arangodb; using namespace arangodb::application_features; using namespace arangodb::basics; using namespace arangodb::options; // ----------------------------------------------------------------------------- // --SECTION-- global variables // ----------------------------------------------------------------------------- namespace arangodb { namespace basics { StatisticsCounter TRI_AsyncRequestsStatistics; StatisticsCounter TRI_HttpConnectionsStatistics; StatisticsCounter TRI_TotalRequestsStatistics; StatisticsDistribution* TRI_BytesReceivedDistributionStatistics; StatisticsDistribution* TRI_BytesSentDistributionStatistics; StatisticsDistribution* TRI_ConnectionTimeDistributionStatistics; StatisticsDistribution* TRI_IoTimeDistributionStatistics; StatisticsDistribution* TRI_QueueTimeDistributionStatistics; StatisticsDistribution* TRI_RequestTimeDistributionStatistics; StatisticsDistribution* TRI_TotalTimeDistributionStatistics; StatisticsVector TRI_BytesReceivedDistributionVectorStatistics; StatisticsVector TRI_BytesSentDistributionVectorStatistics; StatisticsVector TRI_ConnectionTimeDistributionVectorStatistics; StatisticsVector TRI_RequestTimeDistributionVectorStatistics; std::vector<StatisticsCounter> TRI_MethodRequestsStatistics; } } // ----------------------------------------------------------------------------- // --SECTION-- StatisticsThread // ----------------------------------------------------------------------------- class arangodb::StatisticsThread final : public Thread { public: StatisticsThread() : Thread("Statistics") {} ~StatisticsThread() { shutdown(); } public: void run() override { uint64_t const MAX_SLEEP_TIME = 250 * 1000; uint64_t sleepTime = 100 * 1000; int nothingHappened = 0; while (!isStopping() && StatisticsFeature::enabled()) { size_t count = RequestStatistics::processAll(); if (count == 0) { if (++nothingHappened == 10 * 30) { // increase sleep time every 30 seconds nothingHappened = 0; sleepTime += 50 * 1000; if (sleepTime > MAX_SLEEP_TIME) { sleepTime = MAX_SLEEP_TIME; } } #ifdef _WIN32 usleep((unsigned long)sleepTime); #else usleep((useconds_t)sleepTime); #endif } else { nothingHappened = 0; if (count < 10) { usleep(10 * 1000); } else if (count < 100) { usleep(1 * 1000); } } } RequestStatistics::shutdown(); ConnectionStatistics::shutdown(); ServerStatistics::shutdown(); } }; // ----------------------------------------------------------------------------- // --SECTION-- StatisticsFeature // ----------------------------------------------------------------------------- StatisticsFeature* StatisticsFeature::STATISTICS = nullptr; StatisticsFeature::StatisticsFeature( application_features::ApplicationServer* server) : ApplicationFeature(server, "Statistics"), _statistics(true) { startsAfter("Logger"); startsAfter("Aql"); } void StatisticsFeature::collectOptions( std::shared_ptr<ProgramOptions> options) { options->addOldOption("server.disable-statistics", "server.statistics"); options->addSection("server", "Server features"); options->addHiddenOption("--server.statistics", "turn statistics gathering on or off", new BooleanParameter(&_statistics)); } void StatisticsFeature::prepare() { // initialize counters for all HTTP request types TRI_MethodRequestsStatistics.clear(); for (int i = 0; i < ((int)arangodb::rest::RequestType::ILLEGAL) + 1; ++i) { StatisticsCounter c; TRI_MethodRequestsStatistics.emplace_back(c); } TRI_ConnectionTimeDistributionVectorStatistics << (0.1) << (1.0) << (60.0); TRI_BytesSentDistributionVectorStatistics << (250) << (1000) << (2 * 1000) << (5 * 1000) << (10 * 1000); TRI_BytesReceivedDistributionVectorStatistics << (250) << (1000) << (2 * 1000) << (5 * 1000) << (10 * 1000); TRI_RequestTimeDistributionVectorStatistics << (0.01) << (0.05) << (0.1) << (0.2) << (0.5) << (1.0); TRI_ConnectionTimeDistributionStatistics = new StatisticsDistribution( TRI_ConnectionTimeDistributionVectorStatistics); TRI_TotalTimeDistributionStatistics = new StatisticsDistribution(TRI_RequestTimeDistributionVectorStatistics); TRI_RequestTimeDistributionStatistics = new StatisticsDistribution(TRI_RequestTimeDistributionVectorStatistics); TRI_QueueTimeDistributionStatistics = new StatisticsDistribution(TRI_RequestTimeDistributionVectorStatistics); TRI_IoTimeDistributionStatistics = new StatisticsDistribution(TRI_RequestTimeDistributionVectorStatistics); TRI_BytesSentDistributionStatistics = new StatisticsDistribution(TRI_BytesSentDistributionVectorStatistics); TRI_BytesReceivedDistributionStatistics = new StatisticsDistribution(TRI_BytesReceivedDistributionVectorStatistics); STATISTICS = this; ServerStatistics::initialize(); ConnectionStatistics::initialize(); RequestStatistics::initialize(); } void StatisticsFeature::start() { if (!_statistics) { return; } _statisticsThread.reset(new StatisticsThread); if (!_statisticsThread->start()) { LOG(FATAL) << "could not start statistics thread"; FATAL_ERROR_EXIT(); } } void StatisticsFeature::unprepare() { if (_statisticsThread != nullptr) { _statisticsThread->beginShutdown(); while (_statisticsThread->isRunning()) { usleep(10000); } } _statisticsThread.reset(); delete TRI_ConnectionTimeDistributionStatistics; TRI_ConnectionTimeDistributionStatistics = nullptr; delete TRI_TotalTimeDistributionStatistics; TRI_TotalTimeDistributionStatistics = nullptr; delete TRI_RequestTimeDistributionStatistics; TRI_RequestTimeDistributionStatistics = nullptr; delete TRI_QueueTimeDistributionStatistics; TRI_QueueTimeDistributionStatistics = nullptr; delete TRI_IoTimeDistributionStatistics; TRI_IoTimeDistributionStatistics = nullptr; delete TRI_BytesSentDistributionStatistics; TRI_BytesSentDistributionStatistics = nullptr; delete TRI_BytesReceivedDistributionStatistics; TRI_BytesReceivedDistributionStatistics = nullptr; STATISTICS = nullptr; } <|endoftext|>
<commit_before>/* * dataset3d.cpp * * Created on: May 9, 2012 * Author: schurade */ #include "../datastore.h" #include "../../gui/gl/evrenderer.h" #include "dataset3d.h" Dataset3D::Dataset3D( QString filename, QVector<QVector3D> data, nifti_image* header ) : DatasetNifti( filename, FNDT_NIFTI_VECTOR, header ), m_data( data ), m_renderer( 0 ) { m_properties.set( FNPROP_COLORMAP, 0, 0, 2, true ); m_properties.set( FNPROP_INTERPOLATION, false, true ); m_properties.set( FNPROP_ALPHA, 1.0f, 0.0, 1.0, true ); m_properties.set( FNPROP_DIM, 3 ); m_properties.set( FNPROP_RENDER_SLICE, 1, 1, 3, true ); m_properties.set( FNPROP_SCALING, 1.0f, 0.0f, 2.0f, true ); m_properties.set( FNPROP_OFFSET, 0.0f, -0.5, 0.5, true ); examineDataset(); } Dataset3D::~Dataset3D() { m_properties.set( FNPROP_ACTIVE, false ); delete m_renderer; m_data.clear(); } void Dataset3D::examineDataset() { int type = m_properties.get( FNPROP_DATATYPE ).toInt(); int nx = m_properties.get( FNPROP_NX ).toInt(); int ny = m_properties.get( FNPROP_NY ).toInt(); int nz = m_properties.get( FNPROP_NZ ).toInt(); int size = nx * ny * nz * 3; if ( type == DT_UNSIGNED_CHAR ) { m_properties.set( FNPROP_SIZE, static_cast<int>( size * sizeof(unsigned char) ) ); m_properties.set( FNPROP_MIN, 0 ); m_properties.set( FNPROP_MAX, 255 ); } if ( type == DT_FLOAT ) { m_properties.set( FNPROP_SIZE, static_cast<int>( size * sizeof(float) ) ); m_properties.set( FNPROP_MIN, -1.0f ); m_properties.set( FNPROP_MAX, 1.0f ); } m_properties.set( FNPROP_LOWER_THRESHOLD, m_properties.get( FNPROP_MIN ).toFloat() ); m_properties.set( FNPROP_UPPER_THRESHOLD, m_properties.get( FNPROP_MAX ).toFloat() ); if ( m_qform( 1, 1 ) < 0 || m_sform( 1, 1 ) < 0 ) { qDebug() << m_properties.get( FNPROP_NAME ).toString() << ": RADIOLOGICAL orientation detected. Flipping voxels on X-Axis"; flipX(); } } void Dataset3D::createTexture() { glPixelStorei( GL_UNPACK_ALIGNMENT, 1 ); glGenTextures( 1, &m_textureGLuint ); glBindTexture( GL_TEXTURE_3D, m_textureGLuint ); glTexParameteri( GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); glTexParameteri( GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); glTexParameteri( GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP ); glTexParameteri( GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP ); glTexParameteri( GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP ); int type = m_properties.get( FNPROP_DATATYPE ).toInt(); int nx = m_properties.get( FNPROP_NX ).toInt(); int ny = m_properties.get( FNPROP_NY ).toInt(); int nz = m_properties.get( FNPROP_NZ ).toInt(); if ( type == DT_UNSIGNED_CHAR ) { float* data = new float[nx * ny * nz * 3]; int size = nx * ny * nz * 3; for ( int i = 0; i < size; ++i ) { data[i] = qMax( data[i], data[i] * -1.0f ) / 255; } glTexImage3D( GL_TEXTURE_3D, 0, GL_RGBA, nx, ny, nz, 0, GL_RGB, GL_FLOAT, data ); } if ( type == DT_FLOAT ) { int blockSize = nx * ny * nz; float* data = new float[blockSize * 3]; for ( int i = 0; i < blockSize; ++i ) { data[i * 3] = fabs( m_data[i].x() ); data[i * 3 + 1] = fabs( m_data[i].y() ); data[i * 3 + 2] = fabs( m_data[i].z() ); } glTexImage3D( GL_TEXTURE_3D, 0, GL_RGBA, nx, ny, nz, 0, GL_RGB, GL_FLOAT, data ); } } void Dataset3D::flipX() { int nx = m_properties.get( FNPROP_NX ).toInt(); int ny = m_properties.get( FNPROP_NY ).toInt(); int nz = m_properties.get( FNPROP_NZ ).toInt(); QVector<QVector3D> newData; for ( int z = 0; z < nz; ++z ) { for ( int y = 0; y < ny; ++y ) { for ( int x = nx - 1; x >= 0; --x ) { newData.push_back( m_data[x + y * nx + z * nx * ny] ); } } } m_header->qto_xyz.m[0][0] = qMax( m_header->qto_xyz.m[0][0], m_header->qto_xyz.m[0][0] * -1.0f ); m_header->sto_xyz.m[0][0] = qMax( m_header->sto_xyz.m[0][0], m_header->sto_xyz.m[0][0] * -1.0f ); m_header->qto_xyz.m[0][3] = 0.0; m_header->sto_xyz.m[0][3] = 0.0; m_data.clear(); m_data = newData; } QVector<QVector3D>* Dataset3D::getData() { return &m_data; } void Dataset3D::draw( QMatrix4x4 mvpMatrix, QMatrix4x4 mvMatrixInverse, DataStore* datastore ) { if ( m_renderer == 0 ) { m_renderer = new EVRenderer( &m_data, m_properties.get( FNPROP_NX ).toInt(), m_properties.get( FNPROP_NY ).toInt(), m_properties.get( FNPROP_NZ ).toInt(), m_properties.get( FNPROP_DX ).toFloat(), m_properties.get( FNPROP_DY ).toFloat(), m_properties.get( FNPROP_DZ ).toFloat() ); m_renderer->setModel( datastore ); m_renderer->init(); } m_renderer->setRenderParams( m_properties.get( FNPROP_SCALING ).toFloat(), m_properties.get( FNPROP_RENDER_SLICE ).toInt(), m_properties.get( FNPROP_OFFSET ).toFloat() ); m_renderer->draw( mvpMatrix, mvMatrixInverse ); } QString Dataset3D::getValueAsString( int x, int y, int z ) { int nx = m_properties.get( FNPROP_NX ).toInt(); int ny = m_properties.get( FNPROP_NY ).toInt(); QVector3D data = m_data[x + y * nx + z * nx * ny]; return QString::number( data.x() ) + ", " + QString::number( data.y() ) + ", " + QString::number( data.z() ); } <commit_msg>fixed colormap for rgb datasets<commit_after>/* * dataset3d.cpp * * Created on: May 9, 2012 * Author: schurade */ #include "../datastore.h" #include "../../gui/gl/evrenderer.h" #include "dataset3d.h" Dataset3D::Dataset3D( QString filename, QVector<QVector3D> data, nifti_image* header ) : DatasetNifti( filename, FNDT_NIFTI_VECTOR, header ), m_data( data ), m_renderer( 0 ) { m_properties.set( FNPROP_COLORMAP, 4, 0, 4 ); m_properties.set( FNPROP_INTERPOLATION, false, true ); m_properties.set( FNPROP_ALPHA, 1.0f, 0.0, 1.0, true ); m_properties.set( FNPROP_DIM, 3 ); m_properties.set( FNPROP_RENDER_SLICE, 1, 1, 3, true ); m_properties.set( FNPROP_SCALING, 1.0f, 0.0f, 2.0f, true ); m_properties.set( FNPROP_OFFSET, 0.0f, -0.5, 0.5, true ); examineDataset(); } Dataset3D::~Dataset3D() { m_properties.set( FNPROP_ACTIVE, false ); delete m_renderer; m_data.clear(); } void Dataset3D::examineDataset() { int type = m_properties.get( FNPROP_DATATYPE ).toInt(); int nx = m_properties.get( FNPROP_NX ).toInt(); int ny = m_properties.get( FNPROP_NY ).toInt(); int nz = m_properties.get( FNPROP_NZ ).toInt(); int size = nx * ny * nz * 3; if ( type == DT_UNSIGNED_CHAR ) { m_properties.set( FNPROP_SIZE, static_cast<int>( size * sizeof(unsigned char) ) ); m_properties.set( FNPROP_MIN, 0 ); m_properties.set( FNPROP_MAX, 255 ); } if ( type == DT_FLOAT ) { m_properties.set( FNPROP_SIZE, static_cast<int>( size * sizeof(float) ) ); m_properties.set( FNPROP_MIN, -1.0f ); m_properties.set( FNPROP_MAX, 1.0f ); } m_properties.set( FNPROP_LOWER_THRESHOLD, m_properties.get( FNPROP_MIN ).toFloat() ); m_properties.set( FNPROP_UPPER_THRESHOLD, m_properties.get( FNPROP_MAX ).toFloat() ); if ( m_qform( 1, 1 ) < 0 || m_sform( 1, 1 ) < 0 ) { qDebug() << m_properties.get( FNPROP_NAME ).toString() << ": RADIOLOGICAL orientation detected. Flipping voxels on X-Axis"; flipX(); } } void Dataset3D::createTexture() { glPixelStorei( GL_UNPACK_ALIGNMENT, 1 ); glGenTextures( 1, &m_textureGLuint ); glBindTexture( GL_TEXTURE_3D, m_textureGLuint ); glTexParameteri( GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); glTexParameteri( GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); glTexParameteri( GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP ); glTexParameteri( GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP ); glTexParameteri( GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP ); int type = m_properties.get( FNPROP_DATATYPE ).toInt(); int nx = m_properties.get( FNPROP_NX ).toInt(); int ny = m_properties.get( FNPROP_NY ).toInt(); int nz = m_properties.get( FNPROP_NZ ).toInt(); if ( type == DT_UNSIGNED_CHAR ) { float* data = new float[nx * ny * nz * 3]; int size = nx * ny * nz * 3; for ( int i = 0; i < size; ++i ) { data[i] = qMax( data[i], data[i] * -1.0f ) / 255; } glTexImage3D( GL_TEXTURE_3D, 0, GL_RGBA, nx, ny, nz, 0, GL_RGB, GL_FLOAT, data ); } if ( type == DT_FLOAT ) { int blockSize = nx * ny * nz; float* data = new float[blockSize * 3]; for ( int i = 0; i < blockSize; ++i ) { data[i * 3] = fabs( m_data[i].x() ); data[i * 3 + 1] = fabs( m_data[i].y() ); data[i * 3 + 2] = fabs( m_data[i].z() ); } glTexImage3D( GL_TEXTURE_3D, 0, GL_RGBA, nx, ny, nz, 0, GL_RGB, GL_FLOAT, data ); } } void Dataset3D::flipX() { int nx = m_properties.get( FNPROP_NX ).toInt(); int ny = m_properties.get( FNPROP_NY ).toInt(); int nz = m_properties.get( FNPROP_NZ ).toInt(); QVector<QVector3D> newData; for ( int z = 0; z < nz; ++z ) { for ( int y = 0; y < ny; ++y ) { for ( int x = nx - 1; x >= 0; --x ) { newData.push_back( m_data[x + y * nx + z * nx * ny] ); } } } m_header->qto_xyz.m[0][0] = qMax( m_header->qto_xyz.m[0][0], m_header->qto_xyz.m[0][0] * -1.0f ); m_header->sto_xyz.m[0][0] = qMax( m_header->sto_xyz.m[0][0], m_header->sto_xyz.m[0][0] * -1.0f ); m_header->qto_xyz.m[0][3] = 0.0; m_header->sto_xyz.m[0][3] = 0.0; m_data.clear(); m_data = newData; } QVector<QVector3D>* Dataset3D::getData() { return &m_data; } void Dataset3D::draw( QMatrix4x4 mvpMatrix, QMatrix4x4 mvMatrixInverse, DataStore* datastore ) { if ( m_renderer == 0 ) { m_renderer = new EVRenderer( &m_data, m_properties.get( FNPROP_NX ).toInt(), m_properties.get( FNPROP_NY ).toInt(), m_properties.get( FNPROP_NZ ).toInt(), m_properties.get( FNPROP_DX ).toFloat(), m_properties.get( FNPROP_DY ).toFloat(), m_properties.get( FNPROP_DZ ).toFloat() ); m_renderer->setModel( datastore ); m_renderer->init(); } m_renderer->setRenderParams( m_properties.get( FNPROP_SCALING ).toFloat(), m_properties.get( FNPROP_RENDER_SLICE ).toInt(), m_properties.get( FNPROP_OFFSET ).toFloat() ); m_renderer->draw( mvpMatrix, mvMatrixInverse ); } QString Dataset3D::getValueAsString( int x, int y, int z ) { int nx = m_properties.get( FNPROP_NX ).toInt(); int ny = m_properties.get( FNPROP_NY ).toInt(); QVector3D data = m_data[x + y * nx + z * nx * ny]; return QString::number( data.x() ) + ", " + QString::number( data.y() ) + ", " + QString::number( data.z() ); } <|endoftext|>
<commit_before>#include "nano.h" #include "class.h" #include "measure.hpp" #include "text/table.h" #include "accumulator.h" #include "text/cmdline.h" #include "math/clamp.hpp" #include "math/random.hpp" #include "math/numeric.hpp" #include "tensor/numeric.hpp" #include "measure_and_log.hpp" #include "layers/make_layers.h" #include "tasks/task_charset.h" #include "text/table_row_mark.h" int main(int argc, const char *argv[]) { using namespace nano; // parse the command line nano::cmdline_t cmdline("benchmark models"); cmdline.add("s", "samples", "number of samples to use [100, 100000]", "10000"); cmdline.add("c", "conn", "plane connectivity for convolution networks [1, 16]", "8"); cmdline.add("", "mlps", "benchmark MLP models"); cmdline.add("", "convnets", "benchmark convolution networks"); cmdline.add("", "forward", "evaluate the \'forward\' pass (output)"); cmdline.add("", "backward", "evaluate the \'backward' pass (gradient)"); cmdline.process(argc, argv); // check arguments and options const auto cmd_samples = nano::clamp(cmdline.get<size_t>("samples"), 100, 100 * 1000); const auto cmd_conn = nano::clamp(cmdline.get<int>("conn"), 1, 16); const auto cmd_forward = cmdline.has("forward"); const auto cmd_backward = cmdline.has("backward"); const auto cmd_mlps = cmdline.has("mlps"); const auto cmd_convnets = cmdline.has("convnets"); if (!cmd_forward && !cmd_backward) { cmdline.usage(); } if (!cmd_mlps && !cmd_convnets) { cmdline.usage(); } const tensor_size_t cmd_rows = 28; const tensor_size_t cmd_cols = 28; const color_mode cmd_color = color_mode::luma; const size_t cmd_min_nthreads = 1; const size_t cmd_max_nthreads = nano::logical_cpus(); // generate synthetic task charset_task_t task(charset::digit, cmd_color, cmd_rows, cmd_cols, cmd_samples); task.load(); // construct models const string_t mlp0; const string_t mlp1 = mlp0 + make_affine_layer(128); const string_t mlp2 = mlp1 + make_affine_layer(128); const string_t mlp3 = mlp2 + make_affine_layer(128); const string_t mlp4 = mlp3 + make_affine_layer(128); const string_t mlp5 = mlp4 + make_affine_layer(128); const string_t convnet0_k2d; const string_t convnet1_k2d = convnet0_k2d + make_conv_layer("conv-k2d", 64, 9, 9, 1); const string_t convnet2_k2d = convnet1_k2d + make_conv_layer("conv-k2d", 64, 7, 7, cmd_conn); const string_t convnet3_k2d = convnet2_k2d + make_conv_layer("conv-k2d", 64, 5, 5, cmd_conn); const string_t convnet4_k2d = convnet3_k2d + make_conv_layer("conv-k2d", 64, 5, 5, cmd_conn); const string_t convnet5_k2d = convnet4_k2d + make_conv_layer("conv-k2d", 64, 3, 3, cmd_conn); const string_t convnet1_toe = nano::replace(convnet1_k2d, "conv-k2d", "conv-toe"); const string_t convnet2_toe = nano::replace(convnet2_k2d, "conv-k2d", "conv-toe"); const string_t convnet3_toe = nano::replace(convnet3_k2d, "conv-k2d", "conv-toe"); const string_t convnet4_toe = nano::replace(convnet4_k2d, "conv-k2d", "conv-toe"); const string_t convnet5_toe = nano::replace(convnet5_k2d, "conv-k2d", "conv-toe"); const string_t outlayer = make_output_layer(task.osize()); std::vector<std::pair<string_t, string_t>> networks; #define DEFINE(config) networks.emplace_back(config + outlayer, NANO_STRINGIFY(config)) if (cmd_mlps) { DEFINE(mlp0); DEFINE(mlp1); DEFINE(mlp2); DEFINE(mlp3); DEFINE(mlp4); DEFINE(mlp5); } if (cmd_convnets) { DEFINE(convnet1_k2d); DEFINE(convnet1_toe); DEFINE(convnet2_k2d); DEFINE(convnet2_toe); DEFINE(convnet3_k2d); DEFINE(convnet3_toe); DEFINE(convnet4_k2d); DEFINE(convnet4_toe); DEFINE(convnet5_k2d); DEFINE(convnet5_toe); } #undef DEFINE const auto loss = nano::get_losses().get("logistic"); const auto criterion = nano::get_criteria().get("avg"); // construct tables to compare models nano::table_t ftable("model-forward [us] / 1000 samples"); nano::table_t btable("model-backward [us] / 1000 samples"); for (size_t nthreads = cmd_min_nthreads; nthreads <= cmd_max_nthreads; ++ nthreads) { ftable.header() << (nano::to_string(nthreads) + "xCPU"); btable.header() << (nano::to_string(nthreads) + "xCPU"); } // evaluate models for (const auto& config : networks) { const string_t cmd_network = config.first; const string_t cmd_name = config.second; log_info() << "<<< running network [" << cmd_network << "] ..."; // create feed-forward network const auto model = nano::get_models().get("forward-network", cmd_network); model->resize(task, true); model->random_params(); nano::table_row_t& frow = ftable.append(cmd_name + " (" + nano::to_string(model->psize()) + ")"); nano::table_row_t& brow = btable.append(cmd_name + " (" + nano::to_string(model->psize()) + ")"); const auto fold = fold_t{0, protocol::train}; // process the samples for (size_t nthreads = cmd_min_nthreads; nthreads <= cmd_max_nthreads; ++ nthreads) { if (cmd_forward) { accumulator_t lacc(*model, *loss, *criterion, criterion_t::type::value, scalar_t(0.1)); lacc.set_threads(nthreads); const auto duration = nano::measure_robustly_usec([&] () { lacc.reset(); lacc.update(task, fold); }, 1); log_info() << "<<< processed [" << lacc.count() << "] forward samples in " << duration.count() << " us."; frow << idiv(static_cast<size_t>(duration.count()) * 1000, lacc.count()); } if (cmd_backward) { accumulator_t gacc(*model, *loss, *criterion, criterion_t::type::vgrad, scalar_t(0.1)); gacc.set_threads(nthreads); const auto duration = nano::measure_robustly_usec([&] () { gacc.reset(); gacc.update(task, fold); }, 1); log_info() << "<<< processed [" << gacc.count() << "] backward samples in " << duration.count() << " us."; brow << idiv(static_cast<size_t>(duration.count()) * 1000, gacc.count()); } } } // print results if (cmd_forward) { ftable.mark(nano::make_table_mark_minimum_percentage_cols<size_t>(5)); ftable.print(std::cout); } if (cmd_backward) { btable.mark(nano::make_table_mark_minimum_percentage_cols<size_t>(5)); btable.print(std::cout); } // OK log_info() << done; return EXIT_SUCCESS; } <commit_msg>also benchmark convolution networks with pooling<commit_after>#include "nano.h" #include "class.h" #include "measure.hpp" #include "text/table.h" #include "accumulator.h" #include "text/cmdline.h" #include "math/clamp.hpp" #include "math/random.hpp" #include "math/numeric.hpp" #include "tensor/numeric.hpp" #include "measure_and_log.hpp" #include "layers/make_layers.h" #include "tasks/task_charset.h" #include "text/table_row_mark.h" int main(int argc, const char *argv[]) { using namespace nano; // parse the command line nano::cmdline_t cmdline("benchmark models"); cmdline.add("s", "samples", "number of samples to use [100, 100000]", "10000"); cmdline.add("c", "conn", "plane connectivity for convolution networks [1, 16]", "8"); cmdline.add("", "mlps", "benchmark MLP models"); cmdline.add("", "convnets", "benchmark convolution networks"); cmdline.add("", "forward", "evaluate the \'forward\' pass (output)"); cmdline.add("", "backward", "evaluate the \'backward' pass (gradient)"); cmdline.process(argc, argv); // check arguments and options const auto cmd_samples = nano::clamp(cmdline.get<size_t>("samples"), 100, 100 * 1000); const auto cmd_conn = nano::clamp(cmdline.get<int>("conn"), 1, 16); const auto cmd_forward = cmdline.has("forward"); const auto cmd_backward = cmdline.has("backward"); const auto cmd_mlps = cmdline.has("mlps"); const auto cmd_convnets = cmdline.has("convnets"); if (!cmd_forward && !cmd_backward) { cmdline.usage(); } if (!cmd_mlps && !cmd_convnets) { cmdline.usage(); } const tensor_size_t cmd_rows = 28; const tensor_size_t cmd_cols = 28; const color_mode cmd_color = color_mode::luma; const size_t cmd_min_nthreads = 1; const size_t cmd_max_nthreads = nano::logical_cpus(); // generate synthetic task charset_task_t task(charset::digit, cmd_color, cmd_rows, cmd_cols, cmd_samples); task.load(); // construct models const string_t mlp0; const string_t mlp1 = mlp0 + make_affine_layer(128); const string_t mlp2 = mlp1 + make_affine_layer(128); const string_t mlp3 = mlp2 + make_affine_layer(128); const string_t mlp4 = mlp3 + make_affine_layer(128); const string_t mlp5 = mlp4 + make_affine_layer(128); const string_t convnet0_k2d; const string_t convnet1_k2d = convnet0_k2d + make_conv_layer("conv-k2d", 64, 7, 7, 1); const string_t convnet2_k2d = convnet1_k2d + make_conv_layer("conv-k2d", 64, 7, 7, cmd_conn); const string_t convnet3_k2d = convnet2_k2d + make_conv_layer("conv-k2d", 64, 5, 5, cmd_conn); const string_t convnet4_k2d = convnet3_k2d + make_conv_layer("conv-k2d", 64, 5, 5, cmd_conn); const string_t convnet5_k2d = convnet4_k2d + make_conv_layer("conv-k2d", 64, 3, 3, cmd_conn); const string_t convnet1_toe = nano::replace(convnet1_k2d, "conv-k2d", "conv-toe"); const string_t convnet2_toe = nano::replace(convnet2_k2d, "conv-k2d", "conv-toe"); const string_t convnet3_toe = nano::replace(convnet3_k2d, "conv-k2d", "conv-toe"); const string_t convnet4_toe = nano::replace(convnet4_k2d, "conv-k2d", "conv-toe"); const string_t convnet5_toe = nano::replace(convnet5_k2d, "conv-k2d", "conv-toe"); const string_t pconvnet0; const string_t pconvnet1 = pconvnet0 + make_conv_pool_layer("conv", 64, 7, 7, 1); const string_t pconvnet2 = pconvnet1 + make_conv_pool_layer("conv", 64, 5, 5, cmd_conn); const string_t pconvnet3 = pconvnet2 + make_conv_layer("conv", 64, 3, 3, cmd_conn); const string_t outlayer = make_output_layer(task.osize()); std::vector<std::pair<string_t, string_t>> networks; #define DEFINE(config) networks.emplace_back(config + outlayer, NANO_STRINGIFY(config)) if (cmd_mlps) { DEFINE(mlp0); DEFINE(mlp1); DEFINE(mlp2); DEFINE(mlp3); DEFINE(mlp4); DEFINE(mlp5); } if (cmd_convnets) { DEFINE(convnet1_k2d); DEFINE(convnet1_toe); DEFINE(convnet2_k2d); DEFINE(convnet2_toe); DEFINE(convnet3_k2d); DEFINE(convnet3_toe); DEFINE(convnet4_k2d); DEFINE(convnet4_toe); DEFINE(convnet5_k2d); DEFINE(convnet5_toe); DEFINE(pconvnet1); DEFINE(pconvnet2); DEFINE(pconvnet3); } #undef DEFINE const auto loss = nano::get_losses().get("logistic"); const auto criterion = nano::get_criteria().get("avg"); // construct tables to compare models nano::table_t ftable("model-forward [us] / 1000 samples"); nano::table_t btable("model-backward [us] / 1000 samples"); for (size_t nthreads = cmd_min_nthreads; nthreads <= cmd_max_nthreads; ++ nthreads) { ftable.header() << (nano::to_string(nthreads) + "xCPU"); btable.header() << (nano::to_string(nthreads) + "xCPU"); } // evaluate models for (const auto& config : networks) { const string_t cmd_network = config.first; const string_t cmd_name = config.second; log_info() << "<<< running network [" << cmd_network << "] ..."; // create feed-forward network const auto model = nano::get_models().get("forward-network", cmd_network); model->resize(task, true); model->random_params(); nano::table_row_t& frow = ftable.append(cmd_name + " (" + nano::to_string(model->psize()) + ")"); nano::table_row_t& brow = btable.append(cmd_name + " (" + nano::to_string(model->psize()) + ")"); const auto fold = fold_t{0, protocol::train}; // process the samples for (size_t nthreads = cmd_min_nthreads; nthreads <= cmd_max_nthreads; ++ nthreads) { if (cmd_forward) { accumulator_t lacc(*model, *loss, *criterion, criterion_t::type::value, scalar_t(0.1)); lacc.set_threads(nthreads); const auto duration = nano::measure_robustly_usec([&] () { lacc.reset(); lacc.update(task, fold); }, 1); log_info() << "<<< processed [" << lacc.count() << "] forward samples in " << duration.count() << " us."; frow << idiv(static_cast<size_t>(duration.count()) * 1000, lacc.count()); } if (cmd_backward) { accumulator_t gacc(*model, *loss, *criterion, criterion_t::type::vgrad, scalar_t(0.1)); gacc.set_threads(nthreads); const auto duration = nano::measure_robustly_usec([&] () { gacc.reset(); gacc.update(task, fold); }, 1); log_info() << "<<< processed [" << gacc.count() << "] backward samples in " << duration.count() << " us."; brow << idiv(static_cast<size_t>(duration.count()) * 1000, gacc.count()); } } } // print results if (cmd_forward) { ftable.mark(nano::make_table_mark_minimum_percentage_cols<size_t>(5)); ftable.print(std::cout); } if (cmd_backward) { btable.mark(nano::make_table_mark_minimum_percentage_cols<size_t>(5)); btable.print(std::cout); } // OK log_info() << done; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* This file is part of the clazy static checker. Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, [email protected] Author: Sérgio Martins <[email protected]> Copyright (C) 2015 Sergio Martins <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "Utils.h" #include "StringUtils.h" #include "clazy_stl.h" #include "checkbase.h" #include "checkmanager.h" #include "clang/Frontend/FrontendPluginRegistry.h" #include "clang/AST/AST.h" #include "clang/AST/ASTConsumer.h" #include "clang/Frontend/CompilerInstance.h" #include "llvm/Support/raw_ostream.h" #include "clang/AST/RecursiveASTVisitor.h" #include "clang/Lex/Lexer.h" #include "clang/Rewrite/Frontend/FixItRewriter.h" #include "clang/AST/ParentMap.h" #include <llvm/Config/llvm-config.h> #include <stdio.h> #include <sstream> #include <iostream> using namespace clang; using namespace std; namespace { class MyFixItOptions : public FixItOptions { public: MyFixItOptions(const MyFixItOptions &other) = delete; MyFixItOptions(bool inplace) { InPlace = inplace; FixWhatYouCan = true; FixOnlyWarnings = true; Silent = false; } std::string RewriteFilename(const std::string &filename, int &fd) override { fd = -1; return InPlace ? filename : filename + "_fixed.cpp"; } #if LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR <= 6 // Clang >= 3.7 already has this member. // We define it for clang <= 3.6 so it builds. bool InPlace; #endif }; static void manuallyPopulateParentMap(ParentMap *map, Stmt *s) { if (!s) return; for (Stmt *child : s->children()) { llvm::errs() << "Patching " << child->getStmtClassName() << "\n"; map->setParent(child, s); manuallyPopulateParentMap(map, child); } } class LazyASTConsumer : public ASTConsumer, public RecursiveASTVisitor<LazyASTConsumer> { public: LazyASTConsumer(CompilerInstance &ci, const RegisteredCheck::List &requestedChecks, bool inplaceFixits) : m_ci(ci) , m_rewriter(nullptr) , m_parentMap(nullptr) { m_createdChecks = CheckManager::instance()->createChecks(requestedChecks, ci); if (CheckManager::instance()->fixitsEnabled()) m_rewriter = new FixItRewriter(ci.getDiagnostics(), m_ci.getSourceManager(), m_ci.getLangOpts(), new MyFixItOptions(inplaceFixits)); } ~LazyASTConsumer() { if (m_rewriter) { m_rewriter->WriteFixedFiles(); delete m_rewriter; } delete m_parentMap; } void setParentMap(ParentMap *map) { assert(map && !m_parentMap); m_parentMap = map; for (auto &check : m_createdChecks) check->setParentMap(map); } bool VisitDecl(Decl *decl) { for (const auto &check : m_createdChecks) { check->VisitDeclaration(decl); } return true; } bool VisitStmt(Stmt *stm) { if (!m_parentMap) { if (m_ci.getDiagnostics().hasUnrecoverableErrorOccurred()) return false; // ParentMap sometimes crashes when there were errors. Doesn't like a botched AST. setParentMap(new ParentMap(stm)); } // Workaround llvm bug: Crashes creating a parent map when encountering Catch Statements. if (lastStm && isa<CXXCatchStmt>(lastStm) && !m_parentMap->hasParent(stm)) { m_parentMap->setParent(stm, lastStm); manuallyPopulateParentMap(m_parentMap, stm); } lastStm = stm; // clang::ParentMap takes a root statement, but there's no root statement in the AST, the root is a declaration // So add to parent map each time we go into a different hierarchy if (!m_parentMap->hasParent(stm)) m_parentMap->addStmt(stm); for (const auto &check : m_createdChecks) { check->VisitStatement(stm); } return true; } void HandleTranslationUnit(ASTContext &ctx) override { TraverseDecl(ctx.getTranslationUnitDecl()); } Stmt *lastStm = nullptr; CompilerInstance &m_ci; FixItRewriter *m_rewriter; ParentMap *m_parentMap; CheckBase::List m_createdChecks; }; //------------------------------------------------------------------------------ static bool parseArgument(const string &arg, vector<string> &args) { auto it = clazy_std::find(args, arg); if (it != args.end()) { args.erase(it, it + 1); return true; } return false; } static CheckLevel parseLevel(vector<std::string> &args) { static const vector<string> levels = { "level0", "level1", "level2", "level3", "level4" }; const int numLevels = levels.size(); for (int i = 0; i < numLevels; ++i) { if (parseArgument(levels.at(i), args)) { return static_cast<CheckLevel>(i); } } return CheckLevelUndefined; } static bool checkLessThan(const RegisteredCheck &c1, const RegisteredCheck &c2) { return c1.name < c2.name; } static bool checkLessThanByLevel(const RegisteredCheck &c1, const RegisteredCheck &c2) { return c1.level < c2.level; } class LazyASTAction : public PluginASTAction { protected: std::unique_ptr<clang::ASTConsumer> CreateASTConsumer(CompilerInstance &ci, llvm::StringRef) override { return llvm::make_unique<LazyASTConsumer>(ci, m_checks, m_inplaceFixits); } bool ParseArgs(const CompilerInstance &ci, const std::vector<std::string> &args_) override { std::vector<std::string> args = args_; if (parseArgument("help", args)) { PrintHelp(llvm::errs()); return true; } if (parseArgument("no-inplace-fixits", args)) { // Unit-tests don't use inplace fixits m_inplaceFixits = false; } // This argument is for debugging purposes const bool printRequestedChecks = parseArgument("print-requested-checks", args); auto checkManager = CheckManager::instance(); const CheckLevel requestedLevel = parseLevel(/*by-ref*/args); if (requestedLevel != CheckLevelUndefined) { checkManager->setRequestedLevel(requestedLevel); } if (parseArgument("enable-all-fixits", args)) { // This is useful for unit-tests, where we also want to run fixits. Don't use it otherwise. checkManager->enableAllFixIts(); } if (args.size() > 1) { // Too many arguments. llvm::errs() << "Too many arguments: "; for (const std::string &a : args) llvm::errs() << a << ' '; llvm::errs() << "\n"; PrintHelp(llvm::errs()); return false; } else if (args.size() == 1) { m_checks = checkManager->checksForCommaSeparatedString(args[0]); if (m_checks.empty()) { llvm::errs() << "Could not find checks in comma separated string " + args[0] + "\n"; PrintHelp(llvm::errs()); return false; } } // Append checks specified from env variable RegisteredCheck::List checksFromEnv = CheckManager::instance()->requestedChecksThroughEnv(); copy(checksFromEnv.cbegin(), checksFromEnv.cend(), back_inserter(m_checks)); if (m_checks.empty() && requestedLevel == CheckLevelUndefined) { // No check or level specified, lets use the default level checkManager->setRequestedLevel(DefaultCheckLevel); } // Add checks from requested level auto checksFromRequestedLevel = checkManager->checksFromRequestedLevel(); clazy_std::append(checksFromRequestedLevel, m_checks); clazy_std::sort_and_remove_dups(m_checks, checkLessThan); if (printRequestedChecks) { llvm::errs() << "Requested checks: "; const unsigned int numChecks = m_checks.size(); for (unsigned int i = 0; i < numChecks; ++i) { llvm::errs() << m_checks.at(i).name; const bool isLast = i == numChecks - 1; if (!isLast) { llvm::errs() << ", "; } } llvm::errs() << "\n"; } return true; } void PrintHelp(llvm::raw_ostream &ros) { RegisteredCheck::List checks = CheckManager::instance()->availableChecks(MaxCheckLevel); clazy_std::sort(checks, checkLessThanByLevel); ros << "Available checks and FixIts:\n\n"; int lastPrintedLevel = -1; const auto numChecks = checks.size(); for (unsigned int i = 0; i < numChecks; ++i) { const RegisteredCheck &check = checks[i]; if (lastPrintedLevel < check.level) { lastPrintedLevel = check.level; if (check.level > 0) ros << "\n"; ros << "Checks from level" << to_string(check.level) << ":\n"; } auto padded = check.name; padded.insert(padded.end(), 39 - padded.size(), ' '); ros << " " << check.name; auto fixits = CheckManager::instance()->availableFixIts(check.name); if (!fixits.empty()) { ros << " ("; bool isFirst = true; for (const auto& fixit : fixits) { if (isFirst) { isFirst = false; } else { ros << ','; } ros << fixit.name; } ros << ')'; } ros << "\n"; } ros << "\nIf nothing is specified, all checks from level0 and level1 will be run.\n\n"; ros << "To specify which checks to enable set the CLAZY_CHECKS env variable, for example:\n"; ros << " export CLAZY_CHECKS=\"level0\"\n"; ros << " export CLAZY_CHECKS=\"level0,reserve-candidates,qstring-allocations\"\n"; ros << " export CLAZY_CHECKS=\"reserve-candidates\"\n\n"; ros << "or pass as compiler arguments, for example:\n"; ros << " -Xclang -plugin-arg-clang-lazy -Xclang reserve-candidates,qstring-allocations\n"; ros << "\n"; ros << "To enable FixIts for a check, also set the env variable CLAZY_FIXIT, for example:\n"; ros << " export CLAZY_FIXIT=\"fix-qlatin1string-allocations\"\n\n"; ros << "FixIts are experimental and rewrite your code therefore only one FixIt is allowed per build.\nSpecifying a list of different FixIts is not supported.\nBackup your code before running them.\n"; } private: RegisteredCheck::List m_checks; bool m_inplaceFixits = true; }; } static FrontendPluginRegistry::Add<LazyASTAction> X("clang-lazy", "clang lazy plugin"); #ifdef CLAZY_ON_WINDOWS_HACK LLVM_EXPORT_REGISTRY(FrontendPluginRegistry) #endif <commit_msg>Remove unneeded include<commit_after>/* This file is part of the clazy static checker. Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, [email protected] Author: Sérgio Martins <[email protected]> Copyright (C) 2015 Sergio Martins <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "Utils.h" #include "StringUtils.h" #include "clazy_stl.h" #include "checkbase.h" #include "checkmanager.h" #include "clang/Frontend/FrontendPluginRegistry.h" #include "clang/AST/AST.h" #include "clang/AST/ASTConsumer.h" #include "clang/Frontend/CompilerInstance.h" #include "llvm/Support/raw_ostream.h" #include "clang/AST/RecursiveASTVisitor.h" #include "clang/Rewrite/Frontend/FixItRewriter.h" #include "clang/AST/ParentMap.h" #include <llvm/Config/llvm-config.h> #include <stdio.h> #include <sstream> #include <iostream> using namespace clang; using namespace std; namespace { class MyFixItOptions : public FixItOptions { public: MyFixItOptions(const MyFixItOptions &other) = delete; MyFixItOptions(bool inplace) { InPlace = inplace; FixWhatYouCan = true; FixOnlyWarnings = true; Silent = false; } std::string RewriteFilename(const std::string &filename, int &fd) override { fd = -1; return InPlace ? filename : filename + "_fixed.cpp"; } #if LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR <= 6 // Clang >= 3.7 already has this member. // We define it for clang <= 3.6 so it builds. bool InPlace; #endif }; static void manuallyPopulateParentMap(ParentMap *map, Stmt *s) { if (!s) return; for (Stmt *child : s->children()) { llvm::errs() << "Patching " << child->getStmtClassName() << "\n"; map->setParent(child, s); manuallyPopulateParentMap(map, child); } } class LazyASTConsumer : public ASTConsumer, public RecursiveASTVisitor<LazyASTConsumer> { public: LazyASTConsumer(CompilerInstance &ci, const RegisteredCheck::List &requestedChecks, bool inplaceFixits) : m_ci(ci) , m_rewriter(nullptr) , m_parentMap(nullptr) { m_createdChecks = CheckManager::instance()->createChecks(requestedChecks, ci); if (CheckManager::instance()->fixitsEnabled()) m_rewriter = new FixItRewriter(ci.getDiagnostics(), m_ci.getSourceManager(), m_ci.getLangOpts(), new MyFixItOptions(inplaceFixits)); } ~LazyASTConsumer() { if (m_rewriter) { m_rewriter->WriteFixedFiles(); delete m_rewriter; } delete m_parentMap; } void setParentMap(ParentMap *map) { assert(map && !m_parentMap); m_parentMap = map; for (auto &check : m_createdChecks) check->setParentMap(map); } bool VisitDecl(Decl *decl) { for (const auto &check : m_createdChecks) { check->VisitDeclaration(decl); } return true; } bool VisitStmt(Stmt *stm) { if (!m_parentMap) { if (m_ci.getDiagnostics().hasUnrecoverableErrorOccurred()) return false; // ParentMap sometimes crashes when there were errors. Doesn't like a botched AST. setParentMap(new ParentMap(stm)); } // Workaround llvm bug: Crashes creating a parent map when encountering Catch Statements. if (lastStm && isa<CXXCatchStmt>(lastStm) && !m_parentMap->hasParent(stm)) { m_parentMap->setParent(stm, lastStm); manuallyPopulateParentMap(m_parentMap, stm); } lastStm = stm; // clang::ParentMap takes a root statement, but there's no root statement in the AST, the root is a declaration // So add to parent map each time we go into a different hierarchy if (!m_parentMap->hasParent(stm)) m_parentMap->addStmt(stm); for (const auto &check : m_createdChecks) { check->VisitStatement(stm); } return true; } void HandleTranslationUnit(ASTContext &ctx) override { TraverseDecl(ctx.getTranslationUnitDecl()); } Stmt *lastStm = nullptr; CompilerInstance &m_ci; FixItRewriter *m_rewriter; ParentMap *m_parentMap; CheckBase::List m_createdChecks; }; //------------------------------------------------------------------------------ static bool parseArgument(const string &arg, vector<string> &args) { auto it = clazy_std::find(args, arg); if (it != args.end()) { args.erase(it, it + 1); return true; } return false; } static CheckLevel parseLevel(vector<std::string> &args) { static const vector<string> levels = { "level0", "level1", "level2", "level3", "level4" }; const int numLevels = levels.size(); for (int i = 0; i < numLevels; ++i) { if (parseArgument(levels.at(i), args)) { return static_cast<CheckLevel>(i); } } return CheckLevelUndefined; } static bool checkLessThan(const RegisteredCheck &c1, const RegisteredCheck &c2) { return c1.name < c2.name; } static bool checkLessThanByLevel(const RegisteredCheck &c1, const RegisteredCheck &c2) { return c1.level < c2.level; } class LazyASTAction : public PluginASTAction { protected: std::unique_ptr<clang::ASTConsumer> CreateASTConsumer(CompilerInstance &ci, llvm::StringRef) override { return llvm::make_unique<LazyASTConsumer>(ci, m_checks, m_inplaceFixits); } bool ParseArgs(const CompilerInstance &ci, const std::vector<std::string> &args_) override { std::vector<std::string> args = args_; if (parseArgument("help", args)) { PrintHelp(llvm::errs()); return true; } if (parseArgument("no-inplace-fixits", args)) { // Unit-tests don't use inplace fixits m_inplaceFixits = false; } // This argument is for debugging purposes const bool printRequestedChecks = parseArgument("print-requested-checks", args); auto checkManager = CheckManager::instance(); const CheckLevel requestedLevel = parseLevel(/*by-ref*/args); if (requestedLevel != CheckLevelUndefined) { checkManager->setRequestedLevel(requestedLevel); } if (parseArgument("enable-all-fixits", args)) { // This is useful for unit-tests, where we also want to run fixits. Don't use it otherwise. checkManager->enableAllFixIts(); } if (args.size() > 1) { // Too many arguments. llvm::errs() << "Too many arguments: "; for (const std::string &a : args) llvm::errs() << a << ' '; llvm::errs() << "\n"; PrintHelp(llvm::errs()); return false; } else if (args.size() == 1) { m_checks = checkManager->checksForCommaSeparatedString(args[0]); if (m_checks.empty()) { llvm::errs() << "Could not find checks in comma separated string " + args[0] + "\n"; PrintHelp(llvm::errs()); return false; } } // Append checks specified from env variable RegisteredCheck::List checksFromEnv = CheckManager::instance()->requestedChecksThroughEnv(); copy(checksFromEnv.cbegin(), checksFromEnv.cend(), back_inserter(m_checks)); if (m_checks.empty() && requestedLevel == CheckLevelUndefined) { // No check or level specified, lets use the default level checkManager->setRequestedLevel(DefaultCheckLevel); } // Add checks from requested level auto checksFromRequestedLevel = checkManager->checksFromRequestedLevel(); clazy_std::append(checksFromRequestedLevel, m_checks); clazy_std::sort_and_remove_dups(m_checks, checkLessThan); if (printRequestedChecks) { llvm::errs() << "Requested checks: "; const unsigned int numChecks = m_checks.size(); for (unsigned int i = 0; i < numChecks; ++i) { llvm::errs() << m_checks.at(i).name; const bool isLast = i == numChecks - 1; if (!isLast) { llvm::errs() << ", "; } } llvm::errs() << "\n"; } return true; } void PrintHelp(llvm::raw_ostream &ros) { RegisteredCheck::List checks = CheckManager::instance()->availableChecks(MaxCheckLevel); clazy_std::sort(checks, checkLessThanByLevel); ros << "Available checks and FixIts:\n\n"; int lastPrintedLevel = -1; const auto numChecks = checks.size(); for (unsigned int i = 0; i < numChecks; ++i) { const RegisteredCheck &check = checks[i]; if (lastPrintedLevel < check.level) { lastPrintedLevel = check.level; if (check.level > 0) ros << "\n"; ros << "Checks from level" << to_string(check.level) << ":\n"; } auto padded = check.name; padded.insert(padded.end(), 39 - padded.size(), ' '); ros << " " << check.name; auto fixits = CheckManager::instance()->availableFixIts(check.name); if (!fixits.empty()) { ros << " ("; bool isFirst = true; for (const auto& fixit : fixits) { if (isFirst) { isFirst = false; } else { ros << ','; } ros << fixit.name; } ros << ')'; } ros << "\n"; } ros << "\nIf nothing is specified, all checks from level0 and level1 will be run.\n\n"; ros << "To specify which checks to enable set the CLAZY_CHECKS env variable, for example:\n"; ros << " export CLAZY_CHECKS=\"level0\"\n"; ros << " export CLAZY_CHECKS=\"level0,reserve-candidates,qstring-allocations\"\n"; ros << " export CLAZY_CHECKS=\"reserve-candidates\"\n\n"; ros << "or pass as compiler arguments, for example:\n"; ros << " -Xclang -plugin-arg-clang-lazy -Xclang reserve-candidates,qstring-allocations\n"; ros << "\n"; ros << "To enable FixIts for a check, also set the env variable CLAZY_FIXIT, for example:\n"; ros << " export CLAZY_FIXIT=\"fix-qlatin1string-allocations\"\n\n"; ros << "FixIts are experimental and rewrite your code therefore only one FixIt is allowed per build.\nSpecifying a list of different FixIts is not supported.\nBackup your code before running them.\n"; } private: RegisteredCheck::List m_checks; bool m_inplaceFixits = true; }; } static FrontendPluginRegistry::Add<LazyASTAction> X("clang-lazy", "clang lazy plugin"); #ifdef CLAZY_ON_WINDOWS_HACK LLVM_EXPORT_REGISTRY(FrontendPluginRegistry) #endif <|endoftext|>
<commit_before>/* Highly Optimized Object-Oriented Molecular Dynamics (HOOMD) Open Source Software License Copyright (c) 2008 Ames Laboratory Iowa State University All rights reserved. Redistribution and use of HOOMD, in source and binary forms, with or without modification, are permitted, provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names HOOMD's contributors may be used to endorse or promote products derived from this software without specific prior written permission. Disclaimer THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // $Id$ // $URL$ #include "BondData.h" #include "ParticleData.h" #include <boost/bind.hpp> using namespace boost; #include <stdexcept> using namespace std; /*! \file BondData.cc \brief Contains definitions for BondData. */ /*! \param pdata ParticleData these bonds refer into \param n_bond_types Number of bond types in the list Taking in pdata as a pointer instead of a shared pointer is sloppy, but there really isn't an alternative due to the way ParticleData is constructed. Things will be fixed in a later version with a reorganization of the various data structures. For now, be careful not to destroy the ParticleData and keep the BondData hanging around. */ BondData::BondData(ParticleData* pdata, unsigned int n_bond_types) : m_n_bond_types(n_bond_types), m_bonds_dirty(false), m_pdata(pdata) { assert(pdata); // attach to the signal for notifications of particle sorts m_sort_connection = m_pdata->connectParticleSort(bind(&BondData::setDirty, this)); #ifdef USE_CUDA // init pointers m_host_bonds = NULL; m_host_n_bonds = NULL; m_gpu_bonddata.bonds = NULL; m_gpu_bonddata.n_bonds = NULL; m_gpu_bonddata.height = 0; m_gpu_bonddata.pitch = 0; // get the execution configuration const ExecutionConfiguration& exec_conf = m_pdata->getExecConf(); // allocate memory on the GPU if there is a GPU in the execution configuration if (exec_conf.gpu.size() == 1) { allocateBondTable(1); } else if (exec_conf.gpu.size() > 1) { cerr << endl << "***Error! BondData currently only supports one GPU" << endl << endl; throw std::runtime_error("Error initializing BondData"); } #endif } BondData::~BondData() { m_sort_connection.disconnect(); #ifdef USE_CUDA freeBondTable(); #endif } /*! \post A bond between particles specified in \a bond is created. \note Each bond should only be specified once! There are no checks to prevent one from being specified more than once, and doing so would result in twice the force and twice the energy. For a bond between \c i and \c j, only call \c addBond(Bond(type,i,j)). Do NOT additionally call \c addBond(Bond(type,j,i)). The first call is sufficient to include the forces on both particle \c i and \c j. \note If a bond is added with \c type=49, then there must be at least 50 bond types (0-49) total, even if not all values are used. So bonds should be added with small contiguous types. \param bond The Bond to add to the list */ void BondData::addBond(const Bond& bond) { // check for some silly errors a user could make if (bond.a >= m_pdata->getN() || bond.b >= m_pdata->getN()) { cerr << endl << "***Error! Particle tag out of bounds when attempting to add bond: " << bond.a << "," << bond.b << endl << endl; throw runtime_error("Error adding bond"); } if (bond.a == bond.b) { cerr << endl << "***Error! Particle cannot be bonded to itself! " << bond.a << "," << bond.b << endl << endl; throw runtime_error("Error adding bond"); } // check that the type is within bouds if (bond.type+1 > m_n_bond_types) { cerr << endl << "***Error! Invalid bond type! " << bond.type << ", the number of types is " << m_n_bond_types << endl << endl; throw runtime_error("Error adding bond"); } m_bonds.push_back(bond); m_bonds_dirty = true; } /*! \param bond_type_mapping Mapping array to set \c bond_type_mapping[type] should be set to the name of the bond type with index \c type. The vector \b must have \c n_bond_types elements in it. */ void BondData::setBondTypeMapping(const std::vector<std::string>& bond_type_mapping) { assert(bond_type_mapping.size() == m_n_bond_types); m_bond_type_mapping = bond_type_mapping; } /*! \param name Type name to get the index of \return Type index of the corresponding type name \note Throws an exception if the type name is not found */ unsigned int BondData::getTypeByName(const std::string &name) { // search for the name for (unsigned int i = 0; i < m_bond_type_mapping.size(); i++) { if (m_bond_type_mapping[i] == name) return i; } cerr << endl << "***Error! Bond type " << name << " not found!" << endl; throw runtime_error("Error mapping type name"); return 0; } /*! \param type Type index to get the name of \returns Type name of the requested type \note Type indices must range from 0 to getNTypes or this method throws an exception. */ std::string BondData::getNameByType(unsigned int type) { // check for an invalid request if (type >= m_n_bond_types) { cerr << endl << "***Error! Requesting type name for non-existant type " << type << endl << endl; throw runtime_error("Error mapping type name"); } // return the name return m_bond_type_mapping[type]; } #ifdef USE_CUDA /*! Updates the bond data on the GPU if needed and returns the data structure needed to access it. */ gpu_bondtable_array BondData::acquireGPU() { if (m_bonds_dirty) { updateBondTable(); m_bonds_dirty = false; } return m_gpu_bonddata; } /*! \post The bond tag data added via addBond() is translated to bonds based on particle index for use in the GPU kernel. This new bond table is then uploaded to the device. */ void BondData::updateBondTable() { assert(m_host_n_bonds); assert(m_host_bonds); // count the number of bonds per particle // start by initializing the host n_bonds values to 0 memset(m_host_bonds, 0, sizeof(unsigned int) * m_pdata->getN()); // loop through the particles and count the number of bonds based on each particle index ParticleDataArraysConst arrays = m_pdata->acquireReadOnly(); for (unsigned int cur_bond = 0; cur_bond < m_bonds.size(); cur_bond++) { unsigned int tag1 = m_bonds[cur_bond].a; unsigned int tag2 = m_bonds[cur_bond].b; int idx1 = arrays.rtag[tag1]; int idx2 = arrays.rtag[tag2]; m_host_n_bonds[idx1]++; m_host_n_bonds[idx2]++; } // find the maximum number of bonds unsigned int num_bonds_max = 0; for (unsigned int i = 0; i < arrays.nparticles; i++) { if (m_host_n_bonds[i] > num_bonds_max) num_bonds_max = m_host_n_bonds[i]; } // re allocate memory if needed if (num_bonds_max > m_gpu_bonddata.height) { reallocateBondTable(num_bonds_max); } // now, update the actual table // zero the number of bonds counter (again) memset(m_host_bonds, 0, sizeof(unsigned int) * m_pdata->getN()); // loop through all bonds and add them to each column in the list int pitch = m_gpu_bonddata.pitch; for (unsigned int cur_bond = 0; cur_bond < m_bonds.size(); cur_bond++) { unsigned int tag1 = m_bonds[cur_bond].a; unsigned int tag2 = m_bonds[cur_bond].b; unsigned int type = m_bonds[cur_bond].type; int idx1 = arrays.rtag[tag1]; int idx2 = arrays.rtag[tag2]; // get the number of bonds for each particle int num1 = m_host_n_bonds[idx1]; int num2 = m_host_n_bonds[idx2]; // add the new bonds to the table m_host_bonds[num1*pitch + idx1] = make_uint2(idx2, type); m_host_bonds[num2*pitch + idx2] = make_uint2(idx1, type); // increment the number of bonds m_host_n_bonds[idx1]++; m_host_n_bonds[idx2]++; } m_pdata->release(); // copy the bond table to the device copyBondTable(); } /*! \param height New height for the bond table \post Reallocates memory on the device making room for up to \a height bonds per particle. \note updateBondTable() needs to be called after so that the data in the bond table will be correct. */ void BondData::reallocateBondTable(int height) { freeBondTable(); allocateBondTable(height); } /*! \param height Height for the bond table */ void BondData::allocateBondTable(int height) { // make sure the arrays have been deallocated assert(m_host_bonds == NULL); assert(m_host_n_bonds == NULL); assert(m_gpu_bonddata.bonds == NULL); assert(m_gpu_bonddata.n_bonds == NULL); unsigned int N = m_pdata->getN(); size_t pitch; // get the execution configuration const ExecutionConfiguration& exec_conf = m_pdata->getExecConf(); // allocate and zero device memory exec_conf.gpu[0]->setTag(__FILE__, __LINE__); exec_conf.gpu[0]->call(bind(cudaMalloc, (void**)((void*)&m_gpu_bonddata.n_bonds), N*sizeof(unsigned int))); exec_conf.gpu[0]->call(bind(cudaMemset, (void*)m_gpu_bonddata.n_bonds, 0, N*sizeof(unsigned int))); exec_conf.gpu[0]->call(bind(cudaMallocPitch, (void**)((void*)&m_gpu_bonddata.bonds), &pitch, N*sizeof(unsigned int), height)); // want pitch in elements, not bytes m_gpu_bonddata.pitch = (int)pitch / sizeof(int); m_gpu_bonddata.height = height; exec_conf.gpu[0]->call(bind(cudaMemset, (void*)m_gpu_bonddata.bonds, 0, pitch * height)); // allocate and zero host memory exec_conf.gpu[0]->call(bind(cudaMallocHost, (void**)((void*)&m_host_n_bonds), N*sizeof(int))); memset((void*)m_host_n_bonds, 0, N*sizeof(int)); exec_conf.gpu[0]->call(bind(cudaMallocHost, (void**)((void*)&m_host_bonds), pitch * height)); memset((void*)m_host_bonds, 0, pitch*height); } void BondData::freeBondTable() { // get the execution configuration const ExecutionConfiguration& exec_conf = m_pdata->getExecConf(); // free device memory exec_conf.gpu[0]->setTag(__FILE__, __LINE__); exec_conf.gpu[0]->call(bind(cudaFree, m_gpu_bonddata.bonds)); m_gpu_bonddata.bonds = NULL; exec_conf.gpu[0]->call(bind(cudaFree, m_gpu_bonddata.n_bonds)); m_gpu_bonddata.n_bonds = NULL; // free host memory exec_conf.gpu[0]->call(bind(cudaFreeHost, m_host_bonds)); m_host_bonds = NULL; exec_conf.gpu[0]->call(bind(cudaFreeHost, m_host_n_bonds)); m_host_n_bonds = NULL; } //! Copies the bond table to the device void BondData::copyBondTable() { // get the execution configuration const ExecutionConfiguration& exec_conf = m_pdata->getExecConf(); exec_conf.gpu[0]->setTag(__FILE__, __LINE__); exec_conf.gpu[0]->call(bind(cudaMemcpy, m_gpu_bonddata.bonds, m_host_bonds, sizeof(uint2) * m_gpu_bonddata.height * m_gpu_bonddata.pitch, cudaMemcpyHostToDevice)); exec_conf.gpu[0]->call(bind(cudaMemcpy, m_gpu_bonddata.n_bonds, m_host_n_bonds, sizeof(unsigned int) * m_pdata->getN(), cudaMemcpyHostToDevice)); } #endif <commit_msg>Fixed one small memory bug in BondData. There are more to find. ticket #42<commit_after>/* Highly Optimized Object-Oriented Molecular Dynamics (HOOMD) Open Source Software License Copyright (c) 2008 Ames Laboratory Iowa State University All rights reserved. Redistribution and use of HOOMD, in source and binary forms, with or without modification, are permitted, provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names HOOMD's contributors may be used to endorse or promote products derived from this software without specific prior written permission. Disclaimer THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // $Id$ // $URL$ #include "BondData.h" #include "ParticleData.h" #include <boost/bind.hpp> using namespace boost; #include <stdexcept> using namespace std; /*! \file BondData.cc \brief Contains definitions for BondData. */ /*! \param pdata ParticleData these bonds refer into \param n_bond_types Number of bond types in the list Taking in pdata as a pointer instead of a shared pointer is sloppy, but there really isn't an alternative due to the way ParticleData is constructed. Things will be fixed in a later version with a reorganization of the various data structures. For now, be careful not to destroy the ParticleData and keep the BondData hanging around. */ BondData::BondData(ParticleData* pdata, unsigned int n_bond_types) : m_n_bond_types(n_bond_types), m_bonds_dirty(false), m_pdata(pdata) { assert(pdata); // attach to the signal for notifications of particle sorts m_sort_connection = m_pdata->connectParticleSort(bind(&BondData::setDirty, this)); #ifdef USE_CUDA // init pointers m_host_bonds = NULL; m_host_n_bonds = NULL; m_gpu_bonddata.bonds = NULL; m_gpu_bonddata.n_bonds = NULL; m_gpu_bonddata.height = 0; m_gpu_bonddata.pitch = 0; // get the execution configuration const ExecutionConfiguration& exec_conf = m_pdata->getExecConf(); // allocate memory on the GPU if there is a GPU in the execution configuration if (exec_conf.gpu.size() == 1) { allocateBondTable(1); } else if (exec_conf.gpu.size() > 1) { cerr << endl << "***Error! BondData currently only supports one GPU" << endl << endl; throw std::runtime_error("Error initializing BondData"); } #endif } BondData::~BondData() { m_sort_connection.disconnect(); #ifdef USE_CUDA freeBondTable(); #endif } /*! \post A bond between particles specified in \a bond is created. \note Each bond should only be specified once! There are no checks to prevent one from being specified more than once, and doing so would result in twice the force and twice the energy. For a bond between \c i and \c j, only call \c addBond(Bond(type,i,j)). Do NOT additionally call \c addBond(Bond(type,j,i)). The first call is sufficient to include the forces on both particle \c i and \c j. \note If a bond is added with \c type=49, then there must be at least 50 bond types (0-49) total, even if not all values are used. So bonds should be added with small contiguous types. \param bond The Bond to add to the list */ void BondData::addBond(const Bond& bond) { // check for some silly errors a user could make if (bond.a >= m_pdata->getN() || bond.b >= m_pdata->getN()) { cerr << endl << "***Error! Particle tag out of bounds when attempting to add bond: " << bond.a << "," << bond.b << endl << endl; throw runtime_error("Error adding bond"); } if (bond.a == bond.b) { cerr << endl << "***Error! Particle cannot be bonded to itself! " << bond.a << "," << bond.b << endl << endl; throw runtime_error("Error adding bond"); } // check that the type is within bouds if (bond.type+1 > m_n_bond_types) { cerr << endl << "***Error! Invalid bond type! " << bond.type << ", the number of types is " << m_n_bond_types << endl << endl; throw runtime_error("Error adding bond"); } m_bonds.push_back(bond); m_bonds_dirty = true; } /*! \param bond_type_mapping Mapping array to set \c bond_type_mapping[type] should be set to the name of the bond type with index \c type. The vector \b must have \c n_bond_types elements in it. */ void BondData::setBondTypeMapping(const std::vector<std::string>& bond_type_mapping) { assert(bond_type_mapping.size() == m_n_bond_types); m_bond_type_mapping = bond_type_mapping; } /*! \param name Type name to get the index of \return Type index of the corresponding type name \note Throws an exception if the type name is not found */ unsigned int BondData::getTypeByName(const std::string &name) { // search for the name for (unsigned int i = 0; i < m_bond_type_mapping.size(); i++) { if (m_bond_type_mapping[i] == name) return i; } cerr << endl << "***Error! Bond type " << name << " not found!" << endl; throw runtime_error("Error mapping type name"); return 0; } /*! \param type Type index to get the name of \returns Type name of the requested type \note Type indices must range from 0 to getNTypes or this method throws an exception. */ std::string BondData::getNameByType(unsigned int type) { // check for an invalid request if (type >= m_n_bond_types) { cerr << endl << "***Error! Requesting type name for non-existant type " << type << endl << endl; throw runtime_error("Error mapping type name"); } // return the name return m_bond_type_mapping[type]; } #ifdef USE_CUDA /*! Updates the bond data on the GPU if needed and returns the data structure needed to access it. */ gpu_bondtable_array BondData::acquireGPU() { if (m_bonds_dirty) { updateBondTable(); m_bonds_dirty = false; } return m_gpu_bonddata; } /*! \post The bond tag data added via addBond() is translated to bonds based on particle index for use in the GPU kernel. This new bond table is then uploaded to the device. */ void BondData::updateBondTable() { assert(m_host_n_bonds); assert(m_host_bonds); // count the number of bonds per particle // start by initializing the host n_bonds values to 0 memset(m_host_bonds, 0, sizeof(unsigned int) * m_pdata->getN()); // loop through the particles and count the number of bonds based on each particle index ParticleDataArraysConst arrays = m_pdata->acquireReadOnly(); for (unsigned int cur_bond = 0; cur_bond < m_bonds.size(); cur_bond++) { unsigned int tag1 = m_bonds[cur_bond].a; unsigned int tag2 = m_bonds[cur_bond].b; int idx1 = arrays.rtag[tag1]; int idx2 = arrays.rtag[tag2]; m_host_n_bonds[idx1]++; m_host_n_bonds[idx2]++; } // find the maximum number of bonds unsigned int num_bonds_max = 0; for (unsigned int i = 0; i < arrays.nparticles; i++) { if (m_host_n_bonds[i] > num_bonds_max) num_bonds_max = m_host_n_bonds[i]; } // re allocate memory if needed if (num_bonds_max > m_gpu_bonddata.height) { reallocateBondTable(num_bonds_max); } // now, update the actual table // zero the number of bonds counter (again) memset(m_host_n_bonds, 0, sizeof(unsigned int) * m_pdata->getN()); // loop through all bonds and add them to each column in the list int pitch = m_gpu_bonddata.pitch; for (unsigned int cur_bond = 0; cur_bond < m_bonds.size(); cur_bond++) { unsigned int tag1 = m_bonds[cur_bond].a; unsigned int tag2 = m_bonds[cur_bond].b; unsigned int type = m_bonds[cur_bond].type; int idx1 = arrays.rtag[tag1]; int idx2 = arrays.rtag[tag2]; // get the number of bonds for each particle int num1 = m_host_n_bonds[idx1]; int num2 = m_host_n_bonds[idx2]; // add the new bonds to the table m_host_bonds[num1*pitch + idx1] = make_uint2(idx2, type); m_host_bonds[num2*pitch + idx2] = make_uint2(idx1, type); // increment the number of bonds m_host_n_bonds[idx1]++; m_host_n_bonds[idx2]++; } m_pdata->release(); // copy the bond table to the device copyBondTable(); } /*! \param height New height for the bond table \post Reallocates memory on the device making room for up to \a height bonds per particle. \note updateBondTable() needs to be called after so that the data in the bond table will be correct. */ void BondData::reallocateBondTable(int height) { freeBondTable(); allocateBondTable(height); } /*! \param height Height for the bond table */ void BondData::allocateBondTable(int height) { // make sure the arrays have been deallocated assert(m_host_bonds == NULL); assert(m_host_n_bonds == NULL); assert(m_gpu_bonddata.bonds == NULL); assert(m_gpu_bonddata.n_bonds == NULL); unsigned int N = m_pdata->getN(); size_t pitch; // get the execution configuration const ExecutionConfiguration& exec_conf = m_pdata->getExecConf(); // allocate and zero device memory exec_conf.gpu[0]->setTag(__FILE__, __LINE__); exec_conf.gpu[0]->call(bind(cudaMalloc, (void**)((void*)&m_gpu_bonddata.n_bonds), N*sizeof(unsigned int))); exec_conf.gpu[0]->call(bind(cudaMemset, (void*)m_gpu_bonddata.n_bonds, 0, N*sizeof(unsigned int))); exec_conf.gpu[0]->call(bind(cudaMallocPitch, (void**)((void*)&m_gpu_bonddata.bonds), &pitch, N*sizeof(unsigned int), height)); // want pitch in elements, not bytes m_gpu_bonddata.pitch = (int)pitch / sizeof(int); m_gpu_bonddata.height = height; exec_conf.gpu[0]->call(bind(cudaMemset, (void*)m_gpu_bonddata.bonds, 0, pitch * height)); // allocate and zero host memory exec_conf.gpu[0]->call(bind(cudaMallocHost, (void**)((void*)&m_host_n_bonds), N*sizeof(int))); memset((void*)m_host_n_bonds, 0, N*sizeof(int)); exec_conf.gpu[0]->call(bind(cudaMallocHost, (void**)((void*)&m_host_bonds), pitch * height)); memset((void*)m_host_bonds, 0, pitch*height); } void BondData::freeBondTable() { // get the execution configuration const ExecutionConfiguration& exec_conf = m_pdata->getExecConf(); // free device memory exec_conf.gpu[0]->setTag(__FILE__, __LINE__); exec_conf.gpu[0]->call(bind(cudaFree, m_gpu_bonddata.bonds)); m_gpu_bonddata.bonds = NULL; exec_conf.gpu[0]->call(bind(cudaFree, m_gpu_bonddata.n_bonds)); m_gpu_bonddata.n_bonds = NULL; // free host memory exec_conf.gpu[0]->call(bind(cudaFreeHost, m_host_bonds)); m_host_bonds = NULL; exec_conf.gpu[0]->call(bind(cudaFreeHost, m_host_n_bonds)); m_host_n_bonds = NULL; } //! Copies the bond table to the device void BondData::copyBondTable() { // get the execution configuration const ExecutionConfiguration& exec_conf = m_pdata->getExecConf(); exec_conf.gpu[0]->setTag(__FILE__, __LINE__); exec_conf.gpu[0]->call(bind(cudaMemcpy, m_gpu_bonddata.bonds, m_host_bonds, sizeof(uint2) * m_gpu_bonddata.height * m_gpu_bonddata.pitch, cudaMemcpyHostToDevice)); exec_conf.gpu[0]->call(bind(cudaMemcpy, m_gpu_bonddata.n_bonds, m_host_n_bonds, sizeof(unsigned int) * m_pdata->getN(), cudaMemcpyHostToDevice)); } #endif <|endoftext|>
<commit_before>#include "../../local/include/gtest/gtest.h" #include <vector> // uncomment to use threads //#define THREADED #ifdef THREADED // Tron //#define NUM_CORES 4 // Clue #define NUM_CORES 12 #include <thread> #include <future> #endif // THREADED #include "genetic.h" #include "genetic_circuit.h" #include "circuit.h" #include "utility.h" TEST(InnocuousAttempt, XOR) { BooleanTable expected_o = {{false}, {true}, {false}, {true}}; BooleanTable expected_o_bar = {{false}, {true}, {true}, {false}}; std::mt19937 rand(std::random_device{}()); // std::minstd_rand0 rand(std::random_device{}()); GeneticCircuit* c = new GeneticCircuit(2, 1, &rand); BooleanTable answer = c->evaluateAllInputs(); int i = 0; // #ifdef THREADED // std::vector<std::future<BooleanTable>> boolean_table_futures; // #endif THREADED while ((answer != expected_o) || (answer != expected_o_bar)) { // #ifdef THREADED // for (int i = 0; i < (NUM_CORES - 1); ++i) { // boolean_table_futures.push_back( // std::async(std::launch::async, , points)); // } // #endif THREADED // std::vector<Path> paths; // vector of possible paths // // Calculate a path on main thread while waiting for other threads // // If we're doing more than 1 set, do NUM_SETS random path calculations // on // // main thread // for (int i = 0; i < NUM_SETS; i++) { // paths.push_back(FindRandomPath(points)); // } // // Get Paths from threads // for (auto& pathfuture : pathfutures) { // paths.push_back(pathfuture.get()); // } delete c; c = new GeneticCircuit(2, 1, &rand); std::cerr << "Iteration: " + std::to_string(++i) << std::endl; // std::cerr << *c << std::endl; answer = c->evaluateAllInputs(); } } TEST(InnocuousAttempt, FullAdder) { BooleanTable expected_o = {{false, false}, {false, true}, {false, true}, {true, false}, {false, true}, {true, false}, {true, false}, {true, true}}; BooleanTable expected_o_bar = {{false, false}, {true, false}, {true, false}, {false, true}, {true, false}, {false, true}, {false, true}, {true, true}}; std::mt19937 rand(std::random_device{}()); // std::minstd_rand0 rand(std::random_device{}()); GeneticCircuit* c = new GeneticCircuit(3, 2, &rand); BooleanTable answer = c->evaluateAllInputs(); int i = 0; // #ifdef THREADED // std::vector<std::future<BooleanTable>> boolean_table_futures; // #endif THREADED while ((answer != expected_o) || (answer != expected_o_bar)) { // #ifdef THREADED // for (int i = 0; i < (NUM_CORES - 1); ++i) { // boolean_table_futures.push_back( // std::async(std::launch::async, , points)); // } // #endif THREADED // std::vector<Path> paths; // vector of possible paths // // Calculate a path on main thread while waiting for other threads // // If we're doing more than 1 set, do NUM_SETS random path calculations // on // // main thread // for (int i = 0; i < NUM_SETS; i++) { // paths.push_back(FindRandomPath(points)); // } // // Get Paths from threads // for (auto& pathfuture : pathfutures) { // paths.push_back(pathfuture.get()); // } delete c; c = new GeneticCircuit(3, 2, &rand); std::cerr << "Iteration: " + std::to_string(++i) << std::endl; // std::cerr << *c << std::endl; answer = c->evaluateAllInputs(); } } // TEST(InnocuousAttempt, InvertInputs) { // BooleanTable expected_o = {{true, true, true}, // {true, true, false}, // {true, false, true}, // {true, false, false}, // {false, true, true}, // {false, true, false}, // {false, false, true}, // {false, false, false}}; // std::mt19937 rand(std::random_device{}()); // // std::minstd_rand0 rand(std::random_device{}()); // GeneticCircuit* c = new GeneticCircuit(3, 3, &rand); // while (c->evaluateAllInputs() != expected_o) { // delete c; // c = new GeneticCircuit(3, 3, &rand); // std::cerr << *c << std::endl; // } // } <commit_msg>only print every 1000<commit_after>#include "../../local/include/gtest/gtest.h" #include <vector> // uncomment to use threads //#define THREADED #ifdef THREADED // Tron //#define NUM_CORES 4 // Clue #define NUM_CORES 12 #include <thread> #include <future> #endif // THREADED #include "genetic.h" #include "genetic_circuit.h" #include "circuit.h" #include "utility.h" TEST(InnocuousAttempt, XOR) { BooleanTable expected_o = {{false}, {true}, {false}, {true}}; BooleanTable expected_o_bar = {{false}, {true}, {true}, {false}}; std::mt19937 rand(std::random_device{}()); // std::minstd_rand0 rand(std::random_device{}()); GeneticCircuit* c = new GeneticCircuit(2, 1, &rand); BooleanTable answer = c->evaluateAllInputs(); int i = 0; while ((answer != expected_o) || (answer != expected_o_bar)) { ++i; delete c; c = new GeneticCircuit(2, 1, &rand); if (i % 1000 == 0) { std::cerr << "Iteration: " + std::to_string(i) << std::endl; std::cerr << *c << std::endl; } answer = c->evaluateAllInputs(); } EXPECT_EQ(expected_o, answer); } TEST(InnocuousAttempt, FullAdder) { BooleanTable expected_o = {{false, false}, {false, true}, {false, true}, {true, false}, {false, true}, {true, false}, {true, false}, {true, true}}; BooleanTable expected_o_bar = {{false, false}, {true, false}, {true, false}, {false, true}, {true, false}, {false, true}, {false, true}, {true, true}}; std::mt19937 rand(std::random_device{}()); // std::minstd_rand0 rand(std::random_device{}()); GeneticCircuit* c = new GeneticCircuit(3, 2, &rand); BooleanTable answer = c->evaluateAllInputs(); int i = 0; while ((answer != expected_o) || (answer != expected_o_bar)) { ++i; delete c; c = new GeneticCircuit(2, 2, &rand); if (i % 1000 == 0) { std::cerr << "Iteration: " + std::to_string(i) << std::endl; std::cerr << *c << std::endl; } answer = c->evaluateAllInputs(); } } TEST(InnocuousAttempt, InvertInputs) { BooleanTable expected_o = {{true, true, true}, {true, true, false}, {true, false, true}, {true, false, false}, {false, true, true}, {false, true, false}, {false, false, true}, {false, false, false}}; std::mt19937 rand(std::random_device{}()); // std::minstd_rand0 rand(std::random_device{}()); GeneticCircuit* c = new GeneticCircuit(3, 3, &rand); BooleanTable answer = c->evaluateAllInputs(); int i = 0; while ((answer != expected_o)) { ++i; delete c; c = new GeneticCircuit(3, 3, &rand); if (i % 1000 == 0) { std::cerr << "Iteration: " + std::to_string(i) << std::endl; std::cerr << *c << std::endl; } answer = c->evaluateAllInputs(); } } <|endoftext|>
<commit_before> //============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk 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 // any later version. // // The GPSTk 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 GPSTk; if not, write to the Free Software Foundation, // Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Copyright 2004, The University of Texas at Austin // //============================================================================ //============================================================================ // //This software developed by Applied Research Laboratories at the University of //Texas at Austin, under contract to an agency or agencies within the U.S. //Department of Defense. The U.S. Government retains all rights to use, //duplicate, distribute, disclose, or release this software. // //Pursuant to DoD Directive 523024 // // DISTRIBUTION STATEMENT A: This software has been approved for public // release, distribution is unlimited. // //============================================================================= #include <EpochClockModel.hpp> #include <vector> #include "OrdApp.hpp" #include "OrdApp.cpp" #include "EphReader.hpp" #include "BCEphemerisStore.hpp" using namespace std; using namespace gpstk; using namespace gpstk::StringUtils; class OrdEdit : public OrdApp { public: OrdEdit() throw(); bool initialize(int argc, char *argv[]) throw(); protected: virtual void process(); private: CommandOptionNoArg clkOpt, removeUnhlthyOpt, noClockOpt, noORDsOpt; CommandOptionWithNumberArg elvOpt, prnOpt, clkResOpt; CommandOptionWithAnyArg ephSourceOpt, startOpt, endOpt; double elMask, clkResidLimit; vector<int> prnVector; vector<string> ephFilesVector; DayTime tStart, tEnd; }; //----------------------------------------------------------------------------- // The constructor basically just sets up all the command line options //----------------------------------------------------------------------------- OrdEdit::OrdEdit() throw() : OrdApp("ordEdit", "Edits an ord file based on various criteria."), elMask(0),clkResidLimit(0), removeUnhlthyOpt('u', "remove-unhealthy","Remove data for unhealthy SVs." " Requires ephemeris source option."), ephSourceOpt('b',"be file","Broadcast ephemeris source. Must be RINEX " "nav file. In type 0 lines, health fields will be filled " "in."), elvOpt('m',"elev","Remove data for SVs below a given elevation mask."), clkOpt('e',"clock-est", "Remove ords that do not have corresponding " "clock estimates."), clkResOpt('s',"size","Remove clock residuals that are greater than " "this size (meters)."), prnOpt('p',"PRN","Remove data from given PRN. Repeat option for multiple" " PRNs."), noClockOpt('c',"no-clock", "Remove all clock offset estimate warts. Give" " this option twice to remove all clock data. "), noORDsOpt('o',"no-ords","Remove all obs warts. Give this option twice to" " remove all ORD data. "), startOpt('\0',"start","Throw out data before this time. Format as " "string: \"MO/DD/YYYY HH:MM:SS\" "), endOpt('\0',"end","Throw out data after this time. Format as string:" " \"MO/DD/YYYY HH:MM:SS\" ") {} //----------------------------------------------------------------------------- bool OrdEdit::initialize(int argc, char *argv[]) throw() { return OrdApp::initialize(argc,argv); } //----------------------------------------------------------------------------- void OrdEdit::process() { //-- don't know SV health without broadcast ephemeris if (removeUnhlthyOpt.getCount() && !(ephSourceOpt.getCount())) { cout << "Need broadcast ephemeris source in order to remove data " << "from unhealthy SVs. Exiting..." << endl; exit(0); } //-- Get ephemeris data EphReader ephReader; ephReader.verboseLevel = verboseLevel; for (int i=0; i<ephSourceOpt.getCount(); i++) ephReader.read(ephSourceOpt.getValue()[i]); gpstk::EphemerisStore& eph = *ephReader.eph; //-- Make sure that the eph data provided is broadcast eph if (ephSourceOpt.getCount()&&(typeid(eph)!=typeid(BCEphemerisStore))) { cout << "You provided an eph source that was not broadcast ephemeris.\n" "(Precise ephemeris does not contain health info and can't be \n" " used with this program.) Exiting... \n"; exit(0); } //-- get PRNs to be excluded int numPRNs = prnOpt.getCount(); for (int index = 0; index < numPRNs; index++) prnVector.push_back(asInt(prnOpt.getValue()[index])); //-- get ephemeris sources, if given int numBEFiles = ephSourceOpt.getCount(); for (int index = 0; index < numBEFiles; index++) ephFilesVector.push_back(asString(ephSourceOpt.getValue()[index])); //-- remove data below a given elevation mask? if (elvOpt.getCount()) elMask = asDouble(elvOpt.getValue().front()); //-- discard clock residuals that are too large? if (clkResOpt.getCount()) clkResidLimit = asDouble(clkResOpt.getValue().front()); //-- if a time span was specified, get it double ss; int mm,dd,yy,hh,minu; if (startOpt.getCount()) { sscanf(startOpt.getValue().front().c_str(),"%i/%i/%i %i:%i:%lf", &mm,&dd,&yy,&hh,&minu,&ss); tStart.setYMDHMS((short)yy,(short)mm,(short)dd,(short)hh, (short)minu,(double)ss); } if (endOpt.getCount()) { sscanf(endOpt.getValue().front().c_str(), "%i/%i/%i %i:%i:%lf", &mm,&dd,&yy,&hh,&minu,&ss); tEnd.setYMDHMS((short)yy,(short)mm,(short)dd,(short)hh, (short)minu, (double)ss); } //-- too lazy? if (verboseLevel || debugLevel) { cout << "# So, according to you, ordEdit should be... \n"; if (clkOpt.getCount()) cout << "# Removing ords that do not have corresponding " << "clock estimates.\n"; else cout << "# Leaving in ords without corresponding clock " << "estimates.\n"; if (removeUnhlthyOpt.getCount()) cout << "# Removing unhealthy SVs.\n"; else cout << "# Not looking at SV health.\n"; if (elMask) cout << "# Elevation mask set to " << elMask << " deg.\n"; else cout << "# Keeping data for all SVs above the horizon. \n"; if (startOpt.getCount()) cout << "# Tossing data before " << tStart << endl; else cout << "# Start time is beginning of file. \n"; if (endOpt.getCount()) cout << "# Tossing data after " << tEnd << endl; else cout << "# End time is end of file. \n"; if (numPRNs) { cout << "# Ignoring PRNs: "; for (int index = 0; index < numPRNs; index++) cout << prnVector[index] << " "; cout << endl; } if (clkResidLimit) cout << "# Tossing clk resids > " << clkResidLimit << " m.\n"; else cout << "# Keeping all clock residuals.\n"; if (numBEFiles) { for (int index = 0; index < numBEFiles; index++) cout << "# Eph source: " << ephSourceOpt.getValue()[index] << endl; } if (noClockOpt.getCount() == 1) cout << "# Removing clock offset warts from ord file.\n"; else if (noClockOpt.getCount() > 1) cout << "# Removing all clock data from ord file.\n"; if (noORDsOpt.getCount() == 1) cout << "# Removing obs warts from ord file.\n"; else if (noORDsOpt.getCount() > 1) cout << "# Removing all ord data from file.\n"; } while (input) { bool writeThisEpoch = true; ORDEpoch ordEpoch = read(input); if (clkOpt.getCount() && !(ordEpoch.clockOffset.is_valid())) writeThisEpoch = false; else if (startOpt.getCount() && (ordEpoch.time < tStart)) writeThisEpoch = false; else if (endOpt.getCount() && (ordEpoch.time > tEnd)) writeThisEpoch = false; if (numBEFiles) { ORDEpoch::ORDMap::const_iterator iter = ordEpoch.ords.begin(); while (iter!= ordEpoch.ords.end()) { const SatID& satId = iter->first; ObsRngDev ord = iter->second; if (typeid(eph) == typeid(BCEphemerisStore)) { const BCEphemerisStore& bce = dynamic_cast<const BCEphemerisStore&>(eph); const EngEphemeris& eph = bce.findEphemeris(satId, ordEpoch.time); ord.health = eph.getHealth(); } iter++; } } if (removeUnhlthyOpt.getCount()) { ORDEpoch::ORDMap::const_iterator iter = ordEpoch.ords.begin(); while (iter!= ordEpoch.ords.end()) { const SatID& satId = iter->first; const ObsRngDev& ord = iter->second; if (ord.health != 0 ) ordEpoch.removeORD(satId); iter++; } } if (elMask) { ORDEpoch::ORDMap::const_iterator iter = ordEpoch.ords.begin(); while (iter!= ordEpoch.ords.end()) { const SatID& satId = iter->first; const ObsRngDev& ord = iter->second; if (ord.getElevation()< elMask) ordEpoch.removeORD(satId); iter++; } } if (noClockOpt.getCount() == 1) { // removing receiver clock offset estimate warts (type 70 lines) if (ordEpoch.clockOffset.is_valid() && ordEpoch.wonky) ordEpoch.clockOffset.set_valid(false); } else if (noClockOpt.getCount() > 1) { // removing all clock data (line types 50, 51, and 70) ordEpoch.clockOffset.set_valid(false); } if (noORDsOpt.getCount() == 1) { // removing obs warts (the type 20 lines) ORDEpoch::ORDMap::const_iterator iter = ordEpoch.ords.begin(); while (iter!= ordEpoch.ords.end()) { const SatID& satId = iter->first; const ObsRngDev& ord = iter->second; iter++; if (ord.wonky) ordEpoch.removeORD(satId); } } else if (noORDsOpt.getCount() > 1) { // removing all ords ORDEpoch::ORDMap::const_iterator iter = ordEpoch.ords.begin(); while (iter!= ordEpoch.ords.end()) { const SatID& satId = iter->first; const ObsRngDev& ord = iter->second; iter++; ordEpoch.removeORD(satId); } } if (numPRNs) { for (int index = 0; index < prnVector.size(); index++) { int prn = prnVector[index]; vector<int>::iterator i; i = find(prnVector.begin(), prnVector.end(), prn); SatID thisSatID(prn,SatID::systemGPS); if (i!=prnVector.end()) ordEpoch.removeORD(thisSatID); } } if (clkResidLimit) { ; /********************************************* hrrmmm. no clock residual because don't have type 51 (linear clock estimate) generation anywhere yet. TBAdded **********************************************/ } if (writeThisEpoch) write(output, ordEpoch); } if (verboseLevel || debugLevel) cout << "# Doneskies.\n"; } //----------------------------------------------------------------------------- int main(int argc, char *argv[]) { try { OrdEdit crap; if (!crap.initialize(argc, argv)) exit(0); crap.run(); } catch (gpstk::Exception &exc) { cout << exc << endl; } catch (std::exception &exc) { cerr << "Caught std::exception " << exc.what() << endl; } catch (...) { cerr << "Caught unknown exception" << endl; } } <commit_msg>Corrected misplaced iterator increment.<commit_after> //============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk 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 // any later version. // // The GPSTk 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 GPSTk; if not, write to the Free Software Foundation, // Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Copyright 2004, The University of Texas at Austin // //============================================================================ //============================================================================ // //This software developed by Applied Research Laboratories at the University of //Texas at Austin, under contract to an agency or agencies within the U.S. //Department of Defense. The U.S. Government retains all rights to use, //duplicate, distribute, disclose, or release this software. // //Pursuant to DoD Directive 523024 // // DISTRIBUTION STATEMENT A: This software has been approved for public // release, distribution is unlimited. // //============================================================================= #include <EpochClockModel.hpp> #include <vector> #include "OrdApp.hpp" #include "OrdApp.cpp" #include "EphReader.hpp" #include "BCEphemerisStore.hpp" using namespace std; using namespace gpstk; using namespace gpstk::StringUtils; class OrdEdit : public OrdApp { public: OrdEdit() throw(); bool initialize(int argc, char *argv[]) throw(); protected: virtual void process(); private: CommandOptionNoArg clkOpt, removeUnhlthyOpt, noClockOpt, noORDsOpt; CommandOptionWithNumberArg elvOpt, prnOpt, clkResOpt; CommandOptionWithAnyArg ephSourceOpt, startOpt, endOpt; double elMask, clkResidLimit; vector<int> prnVector; vector<string> ephFilesVector; DayTime tStart, tEnd; }; //----------------------------------------------------------------------------- // The constructor basically just sets up all the command line options //----------------------------------------------------------------------------- OrdEdit::OrdEdit() throw() : OrdApp("ordEdit", "Edits an ord file based on various criteria."), elMask(0),clkResidLimit(0), removeUnhlthyOpt('u', "remove-unhealthy","Remove data for unhealthy SVs." " Requires ephemeris source option."), ephSourceOpt('b',"be file","Broadcast ephemeris source. Must be RINEX " "nav file. In type 0 lines, health fields will be filled " "in."), elvOpt('m',"elev","Remove data for SVs below a given elevation mask."), clkOpt('e',"clock-est", "Remove ords that do not have corresponding " "clock estimates."), clkResOpt('s',"size","Remove clock residuals that are greater than " "this size (meters)."), prnOpt('p',"PRN","Remove data from given PRN. Repeat option for multiple" " PRNs."), noClockOpt('c',"no-clock", "Remove all clock offset estimate warts. Give" " this option twice to remove all clock data. "), noORDsOpt('o',"no-ords","Remove all obs warts. Give this option twice to" " remove all ORD data. "), startOpt('\0',"start","Throw out data before this time. Format as " "string: \"MO/DD/YYYY HH:MM:SS\" "), endOpt('\0',"end","Throw out data after this time. Format as string:" " \"MO/DD/YYYY HH:MM:SS\" ") {} //----------------------------------------------------------------------------- bool OrdEdit::initialize(int argc, char *argv[]) throw() { return OrdApp::initialize(argc,argv); } //----------------------------------------------------------------------------- void OrdEdit::process() { //-- don't know SV health without broadcast ephemeris if (removeUnhlthyOpt.getCount() && !(ephSourceOpt.getCount())) { cout << "Need broadcast ephemeris source in order to remove data " << "from unhealthy SVs. Exiting..." << endl; exit(0); } //-- Get ephemeris data EphReader ephReader; ephReader.verboseLevel = verboseLevel; for (int i=0; i<ephSourceOpt.getCount(); i++) ephReader.read(ephSourceOpt.getValue()[i]); gpstk::EphemerisStore& eph = *ephReader.eph; //-- Make sure that the eph data provided is broadcast eph if (ephSourceOpt.getCount()&&(typeid(eph)!=typeid(BCEphemerisStore))) { cout << "You provided an eph source that was not broadcast ephemeris.\n" "(Precise ephemeris does not contain health info and can't be \n" " used with this program.) Exiting... \n"; exit(0); } //-- get PRNs to be excluded int numPRNs = prnOpt.getCount(); for (int index = 0; index < numPRNs; index++) prnVector.push_back(asInt(prnOpt.getValue()[index])); //-- get ephemeris sources, if given int numBEFiles = ephSourceOpt.getCount(); for (int index = 0; index < numBEFiles; index++) ephFilesVector.push_back(asString(ephSourceOpt.getValue()[index])); //-- remove data below a given elevation mask? if (elvOpt.getCount()) elMask = asDouble(elvOpt.getValue().front()); //-- discard clock residuals that are too large? if (clkResOpt.getCount()) clkResidLimit = asDouble(clkResOpt.getValue().front()); //-- if a time span was specified, get it double ss; int mm,dd,yy,hh,minu; if (startOpt.getCount()) { sscanf(startOpt.getValue().front().c_str(),"%i/%i/%i %i:%i:%lf", &mm,&dd,&yy,&hh,&minu,&ss); tStart.setYMDHMS((short)yy,(short)mm,(short)dd,(short)hh, (short)minu,(double)ss); } if (endOpt.getCount()) { sscanf(endOpt.getValue().front().c_str(), "%i/%i/%i %i:%i:%lf", &mm,&dd,&yy,&hh,&minu,&ss); tEnd.setYMDHMS((short)yy,(short)mm,(short)dd,(short)hh, (short)minu, (double)ss); } //-- too lazy? if (verboseLevel || debugLevel) { cout << "# So, according to you, ordEdit should be... \n"; if (clkOpt.getCount()) cout << "# Removing ords that do not have corresponding " << "clock estimates.\n"; else cout << "# Leaving in ords without corresponding clock " << "estimates.\n"; if (removeUnhlthyOpt.getCount()) cout << "# Removing unhealthy SVs.\n"; else cout << "# Not looking at SV health.\n"; if (elMask) cout << "# Elevation mask set to " << elMask << " deg.\n"; else cout << "# Keeping data for all SVs above the horizon. \n"; if (startOpt.getCount()) cout << "# Tossing data before " << tStart << endl; else cout << "# Start time is beginning of file. \n"; if (endOpt.getCount()) cout << "# Tossing data after " << tEnd << endl; else cout << "# End time is end of file. \n"; if (numPRNs) { cout << "# Ignoring PRNs: "; for (int index = 0; index < numPRNs; index++) cout << prnVector[index] << " "; cout << endl; } if (clkResidLimit) cout << "# Tossing clk resids > " << clkResidLimit << " m.\n"; else cout << "# Keeping all clock residuals.\n"; if (numBEFiles) { for (int index = 0; index < numBEFiles; index++) cout << "# Eph source: " << ephSourceOpt.getValue()[index] << endl; } if (noClockOpt.getCount() == 1) cout << "# Removing clock offset warts from ord file.\n"; else if (noClockOpt.getCount() > 1) cout << "# Removing all clock data from ord file.\n"; if (noORDsOpt.getCount() == 1) cout << "# Removing obs warts from ord file.\n"; else if (noORDsOpt.getCount() > 1) cout << "# Removing all ord data from file.\n"; } while (input) { bool writeThisEpoch = true; ORDEpoch ordEpoch = read(input); if (clkOpt.getCount() && !(ordEpoch.clockOffset.is_valid())) writeThisEpoch = false; else if (startOpt.getCount() && (ordEpoch.time < tStart)) writeThisEpoch = false; else if (endOpt.getCount() && (ordEpoch.time > tEnd)) writeThisEpoch = false; if (writeThisEpoch && numBEFiles) { ORDEpoch::ORDMap::const_iterator iter = ordEpoch.ords.begin(); while (iter!= ordEpoch.ords.end()) { const SatID& satId = iter->first; ObsRngDev ord = iter->second; if (typeid(eph) == typeid(BCEphemerisStore)) { const BCEphemerisStore& bce = dynamic_cast<const BCEphemerisStore&>(eph); const EngEphemeris& eph = bce.findEphemeris(satId, ordEpoch.time); ord.health = eph.getHealth(); } iter++; } } if (writeThisEpoch && removeUnhlthyOpt.getCount()) { ORDEpoch::ORDMap::const_iterator iter = ordEpoch.ords.begin(); while (iter!= ordEpoch.ords.end()) { const SatID& satId = iter->first; const ObsRngDev& ord = iter->second; if (ord.health != 0 ) ordEpoch.removeORD(satId); iter++; } } if (writeThisEpoch && elMask) { ORDEpoch::ORDMap::const_iterator iter = ordEpoch.ords.begin(); while (iter!= ordEpoch.ords.end()) { const SatID& satId = iter->first; const ObsRngDev& ord = iter->second; iter++; if ((ord.getElevation()< elMask)) ordEpoch.removeORD(satId); } } if (writeThisEpoch && (noClockOpt.getCount() == 1)) { // removing receiver clock offset estimate warts (type 70 lines) if (ordEpoch.clockOffset.is_valid() && ordEpoch.wonky) ordEpoch.clockOffset.set_valid(false); } else if (writeThisEpoch && (noClockOpt.getCount() > 1)) { // removing all clock data (line types 50, 51, and 70) ordEpoch.clockOffset.set_valid(false); } if (writeThisEpoch && (noORDsOpt.getCount() == 1)) { // removing obs warts (the type 20 lines) ORDEpoch::ORDMap::const_iterator iter = ordEpoch.ords.begin(); while (iter!= ordEpoch.ords.end()) { const SatID& satId = iter->first; const ObsRngDev& ord = iter->second; iter++; if (ord.wonky) ordEpoch.removeORD(satId); } } else if (writeThisEpoch && (noORDsOpt.getCount() > 1)) { // removing all ords ORDEpoch::ORDMap::const_iterator iter = ordEpoch.ords.begin(); while (iter!= ordEpoch.ords.end()) { const SatID& satId = iter->first; const ObsRngDev& ord = iter->second; iter++; ordEpoch.removeORD(satId); } } if (writeThisEpoch && numPRNs) { for (int index = 0; index < prnVector.size(); index++) { int prn = prnVector[index]; vector<int>::iterator i; i = find(prnVector.begin(), prnVector.end(), prn); SatID thisSatID(prn,SatID::systemGPS); if (i!=prnVector.end()) ordEpoch.removeORD(thisSatID); } } if (writeThisEpoch && clkResidLimit) { ; /********************************************* hrrmmm. no clock residual because don't have type 51 (linear clock estimate) generation anywhere yet. TBAdded **********************************************/ } if (writeThisEpoch) write(output, ordEpoch); } if (verboseLevel || debugLevel) cout << "# Doneskies.\n"; } //----------------------------------------------------------------------------- int main(int argc, char *argv[]) { try { OrdEdit crap; if (!crap.initialize(argc, argv)) exit(0); crap.run(); } catch (gpstk::Exception &exc) { cout << exc << endl; } catch (std::exception &exc) { cerr << "Caught std::exception " << exc.what() << endl; } catch (...) { cerr << "Caught unknown exception" << endl; } } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Bitcoin developers // Copyright (c) 2012 Litecoin Developers // Copyright (c) 2013 GoldCoin (GLD) Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <string> #include "version.h" // Name of client reported in the 'version' message. Report the same name // for both bitcoind and GoldCoin-QT, to make it harder for attackers to // target servers or GUI users specifically. const std::string CLIENT_NAME("Satoshi"); // Client version number #define CLIENT_VERSION_SUFFIX "-beta" // The following part of the code determines the CLIENT_BUILD variable. // Several mechanisms are used for this: // * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is // generated by the build environment, possibly containing the output // of git-describe in a macro called BUILD_DESC // * secondly, if this is an exported version of the code, GIT_ARCHIVE will // be defined (automatically using the export-subst git attribute), and // GIT_COMMIT will contain the commit id. // * then, three options exist for determining CLIENT_BUILD: // * if BUILD_DESC is defined, use that literally (output of git-describe) // * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] // * otherwise, use v[maj].[min].[rev].[build]-unk // finally CLIENT_VERSION_SUFFIX is added // First, include build.h if requested #ifdef HAVE_BUILD_INFO # include "build.h" #endif // git will put "#define GIT_ARCHIVE 1" on the next line inside archives. #define GIT_ARCHIVE 1 #ifdef GIT_ARCHIVE # define GIT_COMMIT_ID "c9571b8320" # define GIT_COMMIT_DATE "$Format:%cD" #endif #define STRINGIFY(s) #s #define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \ "v" STRINGIFY(maj) "." STRINGIFY(min) "." STRINGIFY(rev) "." STRINGIFY(build) "-g" commit #define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \ "v" STRINGIFY(maj) "." STRINGIFY(min) "." STRINGIFY(rev) "." STRINGIFY(build) "-unk" #ifndef BUILD_DESC # ifdef GIT_COMMIT_ID # define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID) # else # define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD) # endif #endif #ifndef BUILD_DATE # ifdef GIT_COMMIT_DATE # define BUILD_DATE GIT_COMMIT_DATE # else # define BUILD_DATE __DATE__ ", " __TIME__ # endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE); <commit_msg>July Fork v015<commit_after>// Copyright (c) 2012 The Bitcoin developers // Copyright (c) 2012 Litecoin Developers // Copyright (c) 2013 GoldCoin (GLD) Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <string> #include "version.h" // Name of client reported in the 'version' message. Report the same name // for both bitcoind and GoldCoin-QT, to make it harder for attackers to // target servers or GUI users specifically. const std::string CLIENT_NAME("Satoshi"); // Client version number #define CLIENT_VERSION_SUFFIX "-beta" // The following part of the code determines the CLIENT_BUILD variable. // Several mechanisms are used for this: // * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is // generated by the build environment, possibly containing the output // of git-describe in a macro called BUILD_DESC // * secondly, if this is an exported version of the code, GIT_ARCHIVE will // be defined (automatically using the export-subst git attribute), and // GIT_COMMIT will contain the commit id. // * then, three options exist for determining CLIENT_BUILD: // * if BUILD_DESC is defined, use that literally (output of git-describe) // * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] // * otherwise, use v[maj].[min].[rev].[build]-unk // finally CLIENT_VERSION_SUFFIX is added // First, include build.h if requested #ifdef HAVE_BUILD_INFO # include "build.h" #endif // git will put "#define GIT_ARCHIVE 1" on the next line inside archives. #define GIT_ARCHIVE 1 #ifdef GIT_ARCHIVE # define GIT_COMMIT_ID "cf3abdf39d" # define GIT_COMMIT_DATE "$Format:%cD" #endif #define STRINGIFY(s) #s #define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \ "v" STRINGIFY(maj) "." STRINGIFY(min) "." STRINGIFY(rev) "." STRINGIFY(build) "-g" commit #define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \ "v" STRINGIFY(maj) "." STRINGIFY(min) "." STRINGIFY(rev) "." STRINGIFY(build) "-unk" #ifndef BUILD_DESC # ifdef GIT_COMMIT_ID # define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID) # else # define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD) # endif #endif #ifndef BUILD_DATE # ifdef GIT_COMMIT_DATE # define BUILD_DATE GIT_COMMIT_DATE # else # define BUILD_DATE __DATE__ ", " __TIME__ # endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE); <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: fuconstr.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hr $ $Date: 2004-10-12 13:11:40 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SD_FU_CONSTRUCT_HXX #define SD_FU_CONSTRUCT_HXX #ifndef SD_FU_DRAW_HXX #include "fudraw.hxx" #endif class KeyEvent; class SdrObject; class SfxItemSet; namespace sd { /************************************************************************* |* |* Rechteck zeichnen |* \************************************************************************/ class FuConstruct : public FuDraw { public: static const int MIN_FREEHAND_DISTANCE = 10; TYPEINFO(); FuConstruct (ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq); virtual ~FuConstruct (void); // Mouse- & Key-Events virtual BOOL KeyInput(const KeyEvent& rKEvt); virtual BOOL MouseMove(const MouseEvent& rMEvt); virtual BOOL MouseButtonUp(const MouseEvent& rMEvt); virtual BOOL MouseButtonDown(const MouseEvent& rMEvt); virtual void Activate(); // Function aktivieren virtual void Deactivate(); // Function deaktivieren virtual void SelectionHasChanged() { bSelectionChanged = TRUE; } // SJ: setting stylesheet, the use of a filled or unfilled style // is determined by the member nSlotId : void SetStyleSheet(SfxItemSet& rAttr, SdrObject* pObj); // SJ: setting stylesheet, the use of a filled or unfilled style // is determinded by the parameters bUseFillStyle and bUseNoFillStyle : void SetStyleSheet( SfxItemSet& rAttr, SdrObject* pObj, const sal_Bool bUseFillStyle, const sal_Bool bUseNoFillStyle ); protected: bool bSelectionChanged; }; } // end of namespace sd #endif // _SD_FUCONSTR_HXX <commit_msg>INTEGRATION: CWS ooo19126 (1.3.352); FILE MERGED 2005/09/05 13:23:03 rt 1.3.352.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fuconstr.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-09 05:31:41 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SD_FU_CONSTRUCT_HXX #define SD_FU_CONSTRUCT_HXX #ifndef SD_FU_DRAW_HXX #include "fudraw.hxx" #endif class KeyEvent; class SdrObject; class SfxItemSet; namespace sd { /************************************************************************* |* |* Rechteck zeichnen |* \************************************************************************/ class FuConstruct : public FuDraw { public: static const int MIN_FREEHAND_DISTANCE = 10; TYPEINFO(); FuConstruct (ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq); virtual ~FuConstruct (void); // Mouse- & Key-Events virtual BOOL KeyInput(const KeyEvent& rKEvt); virtual BOOL MouseMove(const MouseEvent& rMEvt); virtual BOOL MouseButtonUp(const MouseEvent& rMEvt); virtual BOOL MouseButtonDown(const MouseEvent& rMEvt); virtual void Activate(); // Function aktivieren virtual void Deactivate(); // Function deaktivieren virtual void SelectionHasChanged() { bSelectionChanged = TRUE; } // SJ: setting stylesheet, the use of a filled or unfilled style // is determined by the member nSlotId : void SetStyleSheet(SfxItemSet& rAttr, SdrObject* pObj); // SJ: setting stylesheet, the use of a filled or unfilled style // is determinded by the parameters bUseFillStyle and bUseNoFillStyle : void SetStyleSheet( SfxItemSet& rAttr, SdrObject* pObj, const sal_Bool bUseFillStyle, const sal_Bool bUseNoFillStyle ); protected: bool bSelectionChanged; }; } // end of namespace sd #endif // _SD_FUCONSTR_HXX <|endoftext|>
<commit_before><commit_msg>sd: fix --disable-sdremote: SetImpressMode() not static<commit_after><|endoftext|>
<commit_before>#include <sstmac/hardware/packet_flow/packet_flow_sender.h> #include <sstmac/hardware/router/valiant_routing.h> #include <sstmac/hardware/network/network_message.h> #include <sstmac/common/stats/stat_spyplot.h> #include <sprockit/output.h> namespace sstmac { namespace hw { packet_flow_sender::packet_flow_sender( const timestamp& send_lat, const timestamp& credit_lat) : send_lat_(send_lat), credit_lat_(credit_lat), congestion_spyplot_(0), acc_delay_(false), acker_(0), update_vc_(true) { } packet_flow_sender::packet_flow_sender() : congestion_spyplot_(0), acc_delay_(false), acker_(0), update_vc_(true) { } void packet_flow_sender::send_credit( const packet_flow_input& src, const packet_flow_payload::ptr& payload, timestamp credit_leaves) { int src_vc = payload->vc(); //we have not updated to the new virtual channel packet_flow_credit::ptr credit = new packet_flow_credit(src.src_outport, src_vc, payload->num_bytes()); //there is a certain minimum latency on credits timestamp min_arrival = now() + credit_lat_; //assume for now the packet flow sender is smart enough to pipeline credits efficiently timestamp credit_arrival = min_arrival > credit_leaves ? min_arrival : credit_leaves; packet_flow_debug( "On %s:%p on inport %d, crediting %s:%p port:%d vc:%d {%s} at [%9.5e] after latency %9.5e with %p", to_string().c_str(), this, payload->inport(), src.handler->to_string().c_str(), src.handler, src.src_outport, src_vc, payload->to_string().c_str(), credit_arrival.sec(), credit_lat_.sec(), credit.get()); START_VALID_SCHEDULE(this) schedule(credit_arrival, src.handler, credit); STOP_VALID_SCHEDULE(this) } void packet_flow_sender::send( packet_flow_bandwidth_arbitrator* arb, const packet_flow_payload::ptr& msg, const packet_flow_input& src, const packet_flow_output& dest) { double incoming_bw = msg->bw(); const timestamp& now_ = now(); timestamp packet_head_leaves; timestamp packet_tail_leaves; timestamp credit_leaves; if (arb) { arb->arbitrate(now_, msg, packet_head_leaves, packet_tail_leaves, credit_leaves); } else { packet_head_leaves = packet_tail_leaves = credit_leaves = now_; } if (acc_delay_ || congestion_spyplot_){ double delta_t = (packet_tail_leaves - now_).sec(); double min_delta_t = msg->byte_length() / incoming_bw; double congestion_delay = delta_t - min_delta_t; #if SSTMAC_SANITY_CHECK if (congestion_delay < -1e-9){ spkt_throw_printf(sprockit::value_error, "got a negative congestion delay arbitrating packet"); } #endif double congestion_delay_us = std::max(0., congestion_delay) * 1e6; if (acc_delay_){ msg->add_delay_us(congestion_delay_us); } if (congestion_spyplot_){ long my_id = event_location().location; congestion_spyplot_->add(msg->fromaddr(), my_id, congestion_delay_us); } } #if SSTMAC_SANITY_CHECK if (msg->bw() <= 0 && msg->bw() != packet_flow_payload::uninitialized_bw) { spkt_throw_printf(sprockit::value_error, "On %s, got negative bandwidth for msg %s", to_string().c_str(), msg->to_string().c_str()); } #endif if (src.handler) { send_credit(src, msg, credit_leaves); } if (acker_ && msg->is_tail()) { network_message::ptr netmsg = ptr_test_cast(network_message, msg->orig()); if (netmsg && netmsg->needs_ack()) { START_VALID_SCHEDULE(this) network_message::ptr ack = netmsg->clone_injection_ack(); schedule(packet_tail_leaves, acker_, ack); STOP_VALID_SCHEDULE(this) } } packet_flow_debug( "On %s:%p, sending to port:%d vc:%d {%s} to handler %s:%p on inport %d at head_leaves=%9.5e tail_leaves=%9.5e", to_string().c_str(), this, msg->port(), msg->rinfo().current_path().vc, msg->to_string().c_str(), dest.handler->to_string().c_str(), dest.handler, dest.dst_inport, packet_head_leaves.sec(), packet_tail_leaves.sec()); // leaving me, on arrival at dest message will occupy a specific inport at dest msg->set_inport(dest.dst_inport); //weird hack to update vc from routing if (update_vc_) msg->update_vc(); timestamp arrival = packet_head_leaves + send_lat_; START_VALID_SCHEDULE(this) schedule(arrival, dest.handler, msg); STOP_VALID_SCHEDULE(this) } std::string packet_flow_sender::to_string() const { if (event_location() == event_loc_id::uninitialized){ cerrn << "to_string failed for sender of type " << packet_flow_name() << std::endl; abort(); } return packet_flow_name() + topology::global()->label(event_location()); } } } <commit_msg>histograms need to collect congestion delay in ps (because bin size is in ps)<commit_after>#include <sstmac/hardware/packet_flow/packet_flow_sender.h> #include <sstmac/hardware/router/valiant_routing.h> #include <sstmac/hardware/network/network_message.h> #include <sstmac/common/stats/stat_spyplot.h> #include <sprockit/output.h> namespace sstmac { namespace hw { packet_flow_sender::packet_flow_sender( const timestamp& send_lat, const timestamp& credit_lat) : send_lat_(send_lat), credit_lat_(credit_lat), congestion_spyplot_(0), acc_delay_(false), acker_(0), update_vc_(true) { } packet_flow_sender::packet_flow_sender() : congestion_spyplot_(0), acc_delay_(false), acker_(0), update_vc_(true) { } void packet_flow_sender::send_credit( const packet_flow_input& src, const packet_flow_payload::ptr& payload, timestamp credit_leaves) { int src_vc = payload->vc(); //we have not updated to the new virtual channel packet_flow_credit::ptr credit = new packet_flow_credit(src.src_outport, src_vc, payload->num_bytes()); //there is a certain minimum latency on credits timestamp min_arrival = now() + credit_lat_; //assume for now the packet flow sender is smart enough to pipeline credits efficiently timestamp credit_arrival = min_arrival > credit_leaves ? min_arrival : credit_leaves; packet_flow_debug( "On %s:%p on inport %d, crediting %s:%p port:%d vc:%d {%s} at [%9.5e] after latency %9.5e with %p", to_string().c_str(), this, payload->inport(), src.handler->to_string().c_str(), src.handler, src.src_outport, src_vc, payload->to_string().c_str(), credit_arrival.sec(), credit_lat_.sec(), credit.get()); START_VALID_SCHEDULE(this) schedule(credit_arrival, src.handler, credit); STOP_VALID_SCHEDULE(this) } void packet_flow_sender::send( packet_flow_bandwidth_arbitrator* arb, const packet_flow_payload::ptr& msg, const packet_flow_input& src, const packet_flow_output& dest) { double incoming_bw = msg->bw(); const timestamp& now_ = now(); timestamp packet_head_leaves; timestamp packet_tail_leaves; timestamp credit_leaves; if (arb) { arb->arbitrate(now_, msg, packet_head_leaves, packet_tail_leaves, credit_leaves); } else { packet_head_leaves = packet_tail_leaves = credit_leaves = now_; } if (acc_delay_ || congestion_spyplot_){ double delta_t = (packet_tail_leaves - now_).sec(); double min_delta_t = msg->byte_length() / incoming_bw; double congestion_delay = delta_t - min_delta_t; #if SSTMAC_SANITY_CHECK if (congestion_delay < -1e-9){ spkt_throw_printf(sprockit::value_error, "got a negative congestion delay arbitrating packet"); } #endif double congestion_delay_us = std::max(0., congestion_delay) * 1e6; double congestion_delay_ps = congestion_delay_us * 1e6; if (acc_delay_){ msg->add_delay_us(congestion_delay_ps); } if (congestion_spyplot_){ long my_id = event_location().location; congestion_spyplot_->add(msg->fromaddr(), my_id, congestion_delay_us); } } #if SSTMAC_SANITY_CHECK if (msg->bw() <= 0 && msg->bw() != packet_flow_payload::uninitialized_bw) { spkt_throw_printf(sprockit::value_error, "On %s, got negative bandwidth for msg %s", to_string().c_str(), msg->to_string().c_str()); } #endif if (src.handler) { send_credit(src, msg, credit_leaves); } if (acker_ && msg->is_tail()) { network_message::ptr netmsg = ptr_test_cast(network_message, msg->orig()); if (netmsg && netmsg->needs_ack()) { START_VALID_SCHEDULE(this) network_message::ptr ack = netmsg->clone_injection_ack(); schedule(packet_tail_leaves, acker_, ack); STOP_VALID_SCHEDULE(this) } } packet_flow_debug( "On %s:%p, sending to port:%d vc:%d {%s} to handler %s:%p on inport %d at head_leaves=%9.5e tail_leaves=%9.5e", to_string().c_str(), this, msg->port(), msg->rinfo().current_path().vc, msg->to_string().c_str(), dest.handler->to_string().c_str(), dest.handler, dest.dst_inport, packet_head_leaves.sec(), packet_tail_leaves.sec()); // leaving me, on arrival at dest message will occupy a specific inport at dest msg->set_inport(dest.dst_inport); //weird hack to update vc from routing if (update_vc_) msg->update_vc(); timestamp arrival = packet_head_leaves + send_lat_; START_VALID_SCHEDULE(this) schedule(arrival, dest.handler, msg); STOP_VALID_SCHEDULE(this) } std::string packet_flow_sender::to_string() const { if (event_location() == event_loc_id::uninitialized){ cerrn << "to_string failed for sender of type " << packet_flow_name() << std::endl; abort(); } return packet_flow_name() + topology::global()->label(event_location()); } } } <|endoftext|>
<commit_before>#include <core/arch/Cpu.h> #include "PlatformUnifiedInterface//ExecMemory/ClearCacheTool.h" #include "PlatformUnifiedInterface/Platform.h" #include <unistd.h> #ifdef __APPLE__ #include <mach-o/dyld.h> #include <mach/mach.h> #include <mach/vm_map.h> #include <sys/mman.h> #include "UserMode/UnifiedInterface/platform-darwin/mach_vm.h" #endif #if defined(__APPLE__) #include <dlfcn.h> #include <mach/vm_statistics.h> #endif #include "logging/check_logging.h" #ifdef CODE_PATCH_WITH_SUBSTRATED #include <mach/mach.h> #include "bootstrap.h" #include "ExecMemory/substrated/mach_interface_support/substrated_client.h" #define KERN_ERROR_RETURN(err, failure) \ do { \ if (err != KERN_SUCCESS) { \ FATAL_LOG("error message: %s", mach_error_string(err)); \ return failure; \ } \ } while (0); static mach_port_t substrated_server_port = MACH_PORT_NULL; mach_port_t connect_mach_service(const char *name) { mach_port_t port = MACH_PORT_NULL; kern_return_t kr; kr = task_get_special_port(mach_task_self(), TASK_BOOTSTRAP_PORT, &bootstrap_port); KERN_ERROR_RETURN(kr, MACH_PORT_NULL); kr = bootstrap_look_up(bootstrap_port, (char *)name, &port); #if defined(DOBBY_DEBUG) if (kr != KERN_SUCCESS) { FATAL_LOG("error message: %s", mach_error_string(kr)); } #endif substrated_server_port = port; return port; } int code_remap_with_substrated(addr_t buffer, size_t size, addr_t address) { if (!MACH_PORT_VALID(substrated_server_port)) { substrated_server_port = connect_mach_service("cy:com.saurik.substrated"); } if (!MACH_PORT_VALID(substrated_server_port)) return -1; kern_return_t kr; kr = substrated_mark(substrated_server_port, mach_task_self(), (mach_vm_address_t)buffer, size, (mach_vm_address_t *)&address); if (kr != KERN_SUCCESS) { DLOG("Code patch with substrated failed"); return -1; } return 0; } #endif _MemoryOperationError CodePatch(void *address, void *buffer, int size) { kern_return_t kr; int page_size = (int)sysconf(_SC_PAGESIZE); addr_t page_align_address = ALIGN_FLOOR(address, page_size); int offset = static_cast<int>((addr_t)address - page_align_address); static mach_port_t self_port = mach_task_self(); #ifdef __APPLE__ #if 0 // REMOVE vm_prot_t prot; vm_inherit_t inherit; mach_port_t task_self = mach_task_self(); vm_address_t region = (vm_address_t)page_align_address; vm_size_t region_size = 0; struct vm_region_submap_short_info_64 info; mach_msg_type_number_t info_count = VM_REGION_SUBMAP_SHORT_INFO_COUNT_64; natural_t max_depth = -1; kr = vm_region_recurse_64(task_self, &region, &region_size, &max_depth, (vm_region_recurse_info_t)&info, &info_count); if (kr != KERN_SUCCESS) { return kMemoryOperationError; } prot = info.protection; inherit = info.inheritance; #endif // try modify with substrated (steal from frida-gum) addr_t remap_page = (addr_t)mmap(0, page_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, VM_MAKE_TAG(255), 0); if ((void *)remap_page == MAP_FAILED) return kMemoryOperationError; kr = vm_copy(self_port, (vm_address_t)page_align_address, page_size, (vm_address_t)remap_page); if (kr != KERN_SUCCESS) { return kMemoryOperationError; } memcpy((void *)(remap_page + offset), buffer, size); mprotect((void *)remap_page, page_size, PROT_READ | PROT_WRITE); int ret = RT_FAILED; #ifdef CODE_PATCH_WITH_SUBSTRATED ret = code_remap_with_substrated((addr_t)remap_page, page_size, (addr_t)page_align_address); if (ret == RT_FAILED) DLOG("Not found <substrated> service => vm_remap"); #endif if (ret == RT_FAILED) { mprotect((void *)remap_page, page_size, PROT_READ | PROT_EXEC); mach_vm_address_t dest_page_address_ = (mach_vm_address_t)page_align_address; vm_prot_t curr_protection, max_protection; kr = mach_vm_remap(self_port, &dest_page_address_, page_size, 0, VM_FLAGS_OVERWRITE | VM_FLAGS_FIXED, self_port, (mach_vm_address_t)remap_page, TRUE, &curr_protection, &max_protection, VM_INHERIT_COPY); if (kr != KERN_SUCCESS) { return kMemoryOperationError; } } // unmap the origin page int err = munmap((void *)remap_page, (mach_vm_address_t)page_size); if (err == -1) { ERRNO_PRINT(); return kMemoryOperationError; } #endif addr_t clear_start = (addr_t)page_align_address + offset; CHECK_EQ(clear_start, (addr_t)address); ClearCache((void *)address, (void *)((addr_t)address + size)); return kMemoryOperationSuccess; } <commit_msg>[ios] update substrated code patch<commit_after>#include <core/arch/Cpu.h> #include "PlatformUnifiedInterface//ExecMemory/ClearCacheTool.h" #include "PlatformUnifiedInterface/Platform.h" #include <unistd.h> #ifdef __APPLE__ #include <mach-o/dyld.h> #include <mach/mach.h> #include <mach/vm_map.h> #include <sys/mman.h> #include "UserMode/UnifiedInterface/platform-darwin/mach_vm.h" #endif #if defined(__APPLE__) #include <dlfcn.h> #include <mach/vm_statistics.h> #endif #include "logging/check_logging.h" #include "common/macros/platform_macro.h" #if defined(CODE_PATCH_WITH_SUBSTRATED) && defined(TARGET_ARCH_ARM64) #include <mach/mach.h> #include "bootstrap.h" #include "ExecMemory/substrated/mach_interface_support/substrated_client.h" #define KERN_ERROR_RETURN(err, failure) \ do { \ if (err != KERN_SUCCESS) { \ FATAL_LOG("error message: %s", mach_error_string(err)); \ return failure; \ } \ } while (0); static mach_port_t substrated_server_port = MACH_PORT_NULL; mach_port_t connect_mach_service(const char *name) { mach_port_t port = MACH_PORT_NULL; kern_return_t kr; kr = task_get_special_port(mach_task_self(), TASK_BOOTSTRAP_PORT, &bootstrap_port); KERN_ERROR_RETURN(kr, MACH_PORT_NULL); kr = bootstrap_look_up(bootstrap_port, (char *)name, &port); #if defined(DOBBY_DEBUG) if (kr != KERN_SUCCESS) { FATAL_LOG("error message: %s", mach_error_string(kr)); } #endif substrated_server_port = port; return port; } int code_remap_with_substrated(addr_t buffer, size_t size, addr_t address) { if (!MACH_PORT_VALID(substrated_server_port)) { substrated_server_port = connect_mach_service("cy:com.saurik.substrated"); } if (!MACH_PORT_VALID(substrated_server_port)) return -1; kern_return_t kr; kr = substrated_mark(substrated_server_port, mach_task_self(), (mach_vm_address_t)buffer, size, (mach_vm_address_t *)&address); if (kr != KERN_SUCCESS) { DLOG("Code patch with substrated failed"); return -1; } return 0; } #endif _MemoryOperationError CodePatch(void *address, void *buffer, int size) { kern_return_t kr; int page_size = (int)sysconf(_SC_PAGESIZE); addr_t page_align_address = ALIGN_FLOOR(address, page_size); int offset = static_cast<int>((addr_t)address - page_align_address); static mach_port_t self_port = mach_task_self(); #ifdef __APPLE__ #if 0 // REMOVE vm_prot_t prot; vm_inherit_t inherit; mach_port_t task_self = mach_task_self(); vm_address_t region = (vm_address_t)page_align_address; vm_size_t region_size = 0; struct vm_region_submap_short_info_64 info; mach_msg_type_number_t info_count = VM_REGION_SUBMAP_SHORT_INFO_COUNT_64; natural_t max_depth = -1; kr = vm_region_recurse_64(task_self, &region, &region_size, &max_depth, (vm_region_recurse_info_t)&info, &info_count); if (kr != KERN_SUCCESS) { return kMemoryOperationError; } prot = info.protection; inherit = info.inheritance; #endif // try modify with substrated (steal from frida-gum) addr_t remap_page = (addr_t)mmap(0, page_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, VM_MAKE_TAG(255), 0); if ((void *)remap_page == MAP_FAILED) return kMemoryOperationError; kr = vm_copy(self_port, (vm_address_t)page_align_address, page_size, (vm_address_t)remap_page); if (kr != KERN_SUCCESS) { return kMemoryOperationError; } memcpy((void *)(remap_page + offset), buffer, size); mprotect((void *)remap_page, page_size, PROT_READ | PROT_WRITE); int ret = RT_FAILED; #if defined(CODE_PATCH_WITH_SUBSTRATED) && defined(TARGET_ARCH_ARM64) ret = code_remap_with_substrated((addr_t)remap_page, page_size, (addr_t)page_align_address); if (ret == RT_FAILED) DLOG("Not found <substrated> service => vm_remap"); #endif if (ret == RT_FAILED) { mprotect((void *)remap_page, page_size, PROT_READ | PROT_EXEC); mach_vm_address_t dest_page_address_ = (mach_vm_address_t)page_align_address; vm_prot_t curr_protection, max_protection; kr = mach_vm_remap(self_port, &dest_page_address_, page_size, 0, VM_FLAGS_OVERWRITE | VM_FLAGS_FIXED, self_port, (mach_vm_address_t)remap_page, TRUE, &curr_protection, &max_protection, VM_INHERIT_COPY); if (kr != KERN_SUCCESS) { return kMemoryOperationError; } } // unmap the origin page int err = munmap((void *)remap_page, (mach_vm_address_t)page_size); if (err == -1) { ERRNO_PRINT(); return kMemoryOperationError; } #endif addr_t clear_start = (addr_t)page_align_address + offset; CHECK_EQ(clear_start, (addr_t)address); ClearCache((void *)address, (void *)((addr_t)address + size)); return kMemoryOperationSuccess; } <|endoftext|>
<commit_before>#pragma once #include "main/asdf_defs.h" DIAGNOSTIC_PUSH DIAGNOSTIC_IGNORE(-Wsign-conversion) DIAGNOSTIC_IGNORE(-Wshorten-64-to-32) DIAGNOSTIC_IGNORE(-Wsign-conversion) DIAGNOSTIC_IGNORE(-Wdouble-promotion) #include "cJSON/cJSON.h" DIAGNOSTIC_POP #include <array> DIAGNOSTIC_PUSH DIAGNOSTIC_IGNORE(-Wunused-macros); constexpr std::array<char const*, cJSON_Object+2> cJSON_type_strings = { "cJSON_False" , "cJSON_True" , "cJSON_NULL" , "cJSON_Number" , "cJSON_String" , "cJSON_Array" , "cJSON_Object" , "Invalid cJSON Type" }; #define CJSON_OBJ(node_name, obj_name) cJSON_GetObjectItem(node_name, #obj_name) #define CJSON_INT(node_name, int_name) CJSON_OBJ(node_name, int_name)->valueint #define CJSON_FLOAT(node_name, float_name) static_cast<float>(CJSON_OBJ(node_name, float_name)->valuedouble) #define CJSON_DOUBLE(node_name, double_name) CJSON_OBJ(node_name, double_name)->valuedouble #define CJSON_STR(node_name, str_name) CJSON_OBJ(node_name, str_name)->valuestring #define CJSON_ENUM(node_name, int_name, enum_type) static_cast<enum_type>(CJSON_INT(node_name, int_name)) #define CJSON_VALUE_ARRAY(container_node, container, valuetype, resize_container) \ { \ size_t len = cJSON_GetArraySize(container_node); \ \ if(resize_container) \ { \ container.clear(); \ container.resize(len); \ } \ else \ { \ ASSERT(container.size() == len, ""); \ } \ \ for(size_t i = 0; i < len; ++i) \ { \ cJSON* json = cJSON_GetArrayItem(container_node, i); \ container[i] = json->valuetype; \ } \ } //--- #define CJSON_GET_INT(int_name) int_name = CJSON_INT(root, int_name) #define CJSON_GET_FLOAT(float_name) float_name = CJSON_FLOAT(root, float_name) #define CJSON_GET_DOUBLE(double_name) int_name = CJSON_DOUBLE(root, double_name) #define CJSON_GET_STR(str_name) str_name = CJSON_STR(root, str_name) #define CJSON_GET_ITEM(obj_name) obj_name.from_JSON(cJSON_GetObjectItem(root, #obj_name)); #define CJSON_GET_ENUM_INT(int_name, enum_type) int_name = CJSON_ENUM(int_name, enum_type); #define CJSON_GET_VALUE_ARRAY(container, valuetype, resize_container) \ { \ cJSON* container_json = cJSON_GetObjectItem(root, #container); \ CJSON_VALUE_ARRAY(container_json, container, valuetype, resize_container) \ } //--- #define CJSON_GET_INT_ARRAY(container) CJSON_GET_VALUE_ARRAY(container, valueint, false); #define CJSON_GET_DOUBLE_ARRAY(container) CJSON_GET_VALUE_ARRAY(container, valuedouble, false); #define CJSON_GET_STR_ARRAY(container) CJSON_GET_VALUE_ARRAY(container, valuestring, false); #define CJSON_GET_INT_VECTOR(container) CJSON_GET_VALUE_ARRAY(container, valueint, true); #define CJSON_GET_DOUBLE_VECTOR(container) CJSON_GET_VALUE_ARRAY(container, valuedouble, true); #define CJSON_GET_STR_VECTOR(container) CJSON_GET_VALUE_ARRAY(container, valuestring, true); #define CJSON_GET_ITEM_ARRAY(container) \ { \ cJSON* container##_json = cJSON_GetObjectItem(root, #container); \ size_t len = cJSON_GetArraySize(container##_json); \ for(size_t i = 0; i < len; ++i) \ { \ container[i].from_JSON(cJSON_GetArrayItem(container##_json, i)); \ } \ } //--- #define CJSON_GET_ITEM_VECTOR(container) \ { \ cJSON* container##_json = cJSON_GetObjectItem(root, #container); \ size_t len = cJSON_GetArraySize(container##_json); \ \ container.clear(); \ container.resize(len); \ \ for(size_t i = 0; i < len; ++i) \ { \ container[i].from_JSON(cJSON_GetArrayItem(container##_json, i)); \ } \ } //--- /* */ #define CJSON_CREATE_ROOT() cJSON* root = cJSON_CreateObject() #define CJSON_ADD_BLANK_ITEM(root, child) \ cJSON* child##_json = cJSON_CreateObject(); \ cJSON_AddItemToObject(root, #child, child##_json); //--- #define CJSON_ADD_ITEM(obj) cJSON_AddItemToObject(root, #obj, obj.to_JSON()); #define CJSON_ADD_NUMBER(num_name) cJSON_AddNumberToObject(root, #num_name, num_name); #define CJSON_ADD_INT(num_name) CJSON_ADD_NUMBER(num_name) #define CJSON_ADD_STR(str_name) cJSON_AddStringToObject(root, #str_name, (str_name##.c_str() == nullptr) ? "" : str_name##.c_str()); #define CJSON_ADD_CSTR(str_name) cJSON_AddStringToObject(root, #str_name, str_name); #define CJSON_ITEM_ARRAY(container_name) \ cJSON* container_name##_json = cJSON_CreateArray(); \ for(auto const& thing : container_name) \ { cJSON_AddItemToArray(container_name##_json, thing.to_JSON()); } //--- #define CJSON_ADD_INT_ARRAY(container) cJSON_AddItemToObject(root, #container, cJSON_CreateIntArray(container.data(), container.size())); #define CJSON_ADD_ITEM_ARRAY(container_name) \ CJSON_ITEM_ARRAY(container_name); \ cJSON_AddItemToObject(root, #container_name, container_name##_json); //--- DIAGNOSTIC_POP <commit_msg>json utility funcs plus a useful macro for dealing with json item arrays<commit_after>#pragma once #include "main/asdf_defs.h" #include <array> #include "utilities/utilities.h" DIAGNOSTIC_PUSH DIAGNOSTIC_IGNORE(-Wsign-conversion) DIAGNOSTIC_IGNORE(-Wshorten-64-to-32) DIAGNOSTIC_IGNORE(-Wsign-conversion) DIAGNOSTIC_IGNORE(-Wdouble-promotion) #include "cJSON/cJSON.h" DIAGNOSTIC_POP DIAGNOSTIC_PUSH DIAGNOSTIC_IGNORE(-Wunused-macros); constexpr std::array<char const*, cJSON_Object+2> cJSON_type_strings = { "cJSON_False" , "cJSON_True" , "cJSON_NULL" , "cJSON_Number" , "cJSON_String" , "cJSON_Array" , "cJSON_Object" , "Invalid cJSON Type" }; #define CJSON_OBJ(node_name, obj_name) cJSON_GetObjectItem(node_name, #obj_name) #define CJSON_INT(node_name, int_name) CJSON_OBJ(node_name, int_name)->valueint #define CJSON_FLOAT(node_name, float_name) static_cast<float>(CJSON_OBJ(node_name, float_name)->valuedouble) #define CJSON_DOUBLE(node_name, double_name) CJSON_OBJ(node_name, double_name)->valuedouble #define CJSON_STR(node_name, str_name) CJSON_OBJ(node_name, str_name)->valuestring #define CJSON_ENUM(node_name, int_name, enum_type) static_cast<enum_type>(CJSON_INT(node_name, int_name)) #define CJSON_VALUE_ARRAY(container_node, container, valuetype, resize_container) \ { \ size_t len = cJSON_GetArraySize(container_node); \ \ if(resize_container) \ { \ container.clear(); \ container.resize(len); \ } \ else \ { \ ASSERT(container.size() == len, ""); \ } \ \ for(size_t i = 0; i < len; ++i) \ { \ cJSON* json = cJSON_GetArrayItem(container_node, i); \ container[i] = json->valuetype; \ } \ } //--- #define CJSON_GET_INT(int_name) int_name = CJSON_INT(root, int_name) #define CJSON_GET_FLOAT(float_name) float_name = CJSON_FLOAT(root, float_name) #define CJSON_GET_DOUBLE(double_name) int_name = CJSON_DOUBLE(root, double_name) #define CJSON_GET_STR(str_name) str_name = CJSON_STR(root, str_name) #define CJSON_GET_ITEM(obj_name) obj_name.from_JSON(cJSON_GetObjectItem(root, #obj_name)); #define CJSON_GET_ENUM_INT(int_name, enum_type) int_name = CJSON_ENUM(int_name, enum_type); #define CJSON_GET_VALUE_ARRAY(container, valuetype, resize_container) \ { \ cJSON* container_json = cJSON_GetObjectItem(root, #container); \ CJSON_VALUE_ARRAY(container_json, container, valuetype, resize_container) \ } //--- #define CJSON_GET_INT_ARRAY(container) CJSON_GET_VALUE_ARRAY(container, valueint, false); #define CJSON_GET_DOUBLE_ARRAY(container) CJSON_GET_VALUE_ARRAY(container, valuedouble, false); #define CJSON_GET_STR_ARRAY(container) CJSON_GET_VALUE_ARRAY(container, valuestring, false); #define CJSON_GET_INT_VECTOR(container) CJSON_GET_VALUE_ARRAY(container, valueint, true); #define CJSON_GET_DOUBLE_VECTOR(container) CJSON_GET_VALUE_ARRAY(container, valuedouble, true); #define CJSON_GET_STR_VECTOR(container) CJSON_GET_VALUE_ARRAY(container, valuestring, true); #define CJSON_GET_ITEM_ARRAY(container) \ { \ cJSON* container##_json = cJSON_GetObjectItem(root, #container); \ size_t len = cJSON_GetArraySize(container##_json); \ for(size_t i = 0; i < len; ++i) \ { \ container[i].from_JSON(cJSON_GetArrayItem(container##_json, i)); \ } \ } //--- #define CJSON_FOR_EACH_ITEM_VECTOR(container, obj_from_json_func) \ { \ cJSON* container##_json = cJSON_GetObjectItem(root, #container); \ size_t len = cJSON_GetArraySize(container##_json); \ \ for(size_t i = 0; i < len; ++i) \ { \ obj_from_json_func(cJSON_GetArrayItem(container##_json, i)); \ } \ } //--- #define CJSON_GET_ITEM_VECTOR(container) \ { \ cJSON* container##_json = cJSON_GetObjectItem(root, #container); \ size_t len = cJSON_GetArraySize(container##_json); \ \ container.clear(); \ container.resize(len); \ \ for(size_t i = 0; i < len; ++i) \ { \ container[i].from_JSON(cJSON_GetArrayItem(container##_json, i)); \ } \ } //--- /* */ #define CJSON_CREATE_ROOT() cJSON* root = cJSON_CreateObject() #define CJSON_ADD_BLANK_ITEM(root, child) \ cJSON* child##_json = cJSON_CreateObject(); \ cJSON_AddItemToObject(root, #child, child##_json); //--- #define CJSON_ADD_ITEM(obj) cJSON_AddItemToObject(root, #obj, obj.to_JSON()); #define CJSON_ADD_NUMBER(num_name) cJSON_AddNumberToObject(root, #num_name, num_name); #define CJSON_ADD_INT(num_name) CJSON_ADD_NUMBER(num_name) #define CJSON_ADD_STR(str_name) cJSON_AddStringToObject(root, #str_name, (str_name##.c_str() == nullptr) ? "" : str_name##.c_str()); #define CJSON_ADD_CSTR(str_name) cJSON_AddStringToObject(root, #str_name, str_name); #define CJSON_ITEM_ARRAY(container_name) \ cJSON* container_name##_json = cJSON_CreateArray(); \ for(auto const& thing : container_name) \ { cJSON_AddItemToArray(container_name##_json, thing.to_JSON()); } //--- #define CJSON_ADD_INT_ARRAY(container) cJSON_AddItemToObject(root, #container, cJSON_CreateIntArray(container.data(), container.size())); #define CJSON_ADD_ITEM_ARRAY(container_name) \ CJSON_ITEM_ARRAY(container_name); \ cJSON_AddItemToObject(root, #container_name, container_name##_json); DIAGNOSTIC_POP namespace asdf { inline std::string json_to_string(cJSON* j) { char* cjson_cstr = cJSON_Print(j); std::string str(cjson_cstr); free(cjson_cstr); return str; } inline std::string json_to_string_unformatted(cJSON* j) { char* cjson_cstr = cJSON_PrintUnformatted(j); std::string str(cjson_cstr); free(cjson_cstr); return str; } inline void json_to_file(cJSON* j, std::string const& filepath) { util::write_text_file(filepath, json_to_string(j)); } inline cJSON* json_from_file(std::string const& filepath) { std::string json_str = util::read_text_file(filepath); return cJSON_Parse(json_str.c_str()); } } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// /// @brief infrastructure for query optimizer /// /// @file arangod/Aql/Optimizer.cpp /// /// DISCLAIMER /// /// Copyright 2010-2014 triagens GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is triAGENS GmbH, Cologne, Germany /// /// @author Max Neunhoeffer /// @author Copyright 2014, triagens GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// #include "Aql/Optimizer.h" #include "Aql/OptimizerRules.h" using namespace triagens::aql; // ----------------------------------------------------------------------------- // --SECTION-- the optimizer class // ----------------------------------------------------------------------------- std::vector<Optimizer::Rule> Optimizer::_rules; //////////////////////////////////////////////////////////////////////////////// // @brief constructor, this will initialize the rules database //////////////////////////////////////////////////////////////////////////////// Optimizer::Optimizer () { if (_rules.empty()) { setupRules(); } } //////////////////////////////////////////////////////////////////////////////// // @brief the actual optimization //////////////////////////////////////////////////////////////////////////////// int Optimizer::createPlans (ExecutionPlan* plan) { int res; int leastDoneLevel = 0; int maxRuleLevel = _rules.back().level; // _plans contains the previous optimisation result _plans.clear(); _plans.push_back(plan, 0); int pass = 1; while (leastDoneLevel < maxRuleLevel) { /* std::cout << "Entering pass " << pass << " of query optimization..." << std::endl; */ // This vector holds the plans we have created in this pass: PlanList newPlans; // Find variable usage for all old plans now: for (auto p : _plans.list) { if (! p->varUsageComputed()) { p->findVarUsage(); } } // std::cout << "Have " << _plans.size() << " plans:" << std::endl; /* for (auto p : _plans.list) { p->show(); std::cout << std::endl; } */ int count = 0; // For all current plans: while (_plans.size() > 0) { int level; auto p = _plans.pop_front(level); if (level == maxRuleLevel) { newPlans.push_back(p, level); // nothing to do, just keep it } else { // some rule needs applying Rule r("dummy", dummyRule, level); auto it = std::upper_bound(_rules.begin(), _rules.end(), r); TRI_ASSERT(it != _rules.end()); /* std::cout << "Trying rule " << it->name << " (" << &(it->func) << ") with level " << it->level << " on plan " << count++ << std::endl; */ try { res = it->func(this, p, it->level, newPlans); } catch (...) { delete p; throw; } if (res != TRI_ERROR_NO_ERROR) { return res; } } // TODO: abort early here if we found a good-enough plan // a good-enough plan is probably every plan with costs below some // defined threshold. this requires plan costs to be calculated here } _plans.steal(newPlans); leastDoneLevel = maxRuleLevel; for (auto l : _plans.levelDone) { if (l < leastDoneLevel) { leastDoneLevel = l; } } // std::cout << "Least done level is " << leastDoneLevel << std::endl; // Stop if the result gets out of hand: if (_plans.size() >= maxNumberOfPlans) { break; } } estimatePlans(); sortPlans(); /* std::cout << "Optimisation ends with " << _plans.size() << " plans." << std::endl; for (auto p : _plans.list) { p->show(); std::cout << "costing: " << p->getCost() << std::endl; std::cout << std::endl; } */ return TRI_ERROR_NO_ERROR; } //////////////////////////////////////////////////////////////////////////////// /// @brief estimatePlans //////////////////////////////////////////////////////////////////////////////// void Optimizer::estimatePlans () { for (auto p : _plans.list) { p->getCost(); // this value is cached in the plan, so formally this step is // unnecessary, but for the sake of cleanliness... } } //////////////////////////////////////////////////////////////////////////////// /// @brief sortPlans //////////////////////////////////////////////////////////////////////////////// void Optimizer::sortPlans () { std::sort(_plans.list.begin(), _plans.list.end(), [](ExecutionPlan* const& a, ExecutionPlan* const& b) -> bool { return a->getCost() < b->getCost(); }); } //////////////////////////////////////////////////////////////////////////////// /// @brief set up the optimizer rules once and forever //////////////////////////////////////////////////////////////////////////////// void Optimizer::setupRules () { TRI_ASSERT(_rules.empty()); // List all the rules in the system here: // lower level values mean earlier rule execution // if two rules have the same level value, they will be executed in declaration order ////////////////////////////////////////////////////////////////////////////// // "Pass 1": moving nodes "up" (potentially outside loops): // please use levels between 1 and 99 here ////////////////////////////////////////////////////////////////////////////// // move calculations up the dependency chain (to pull them out of // inner loops etc.) registerRule("move-calculations-up", moveCalculationsUpRule, 10); // move filters up the dependency chain (to make result sets as small // as possible as early as possible) registerRule("move-filters-up", moveFiltersUpRule, 20); ////////////////////////////////////////////////////////////////////////////// /// "Pass 2": try to remove redundant or unnecessary nodes /// use levels between 101 and 199 for this ////////////////////////////////////////////////////////////////////////////// // remove filters from the query that are not necessary at all // filters that are always true will be removed entirely // filters that are always false will be replaced with a NoResults node registerRule("remove-unnecessary-filters", removeUnnecessaryFiltersRule, 110); // remove calculations that are never necessary registerRule("remove-unnecessary-calculations", removeUnnecessaryCalculationsRule, 120); // remove redundant sort blocks registerRule("remove-redundant-sorts", removeRedundantSorts, 130); ////////////////////////////////////////////////////////////////////////////// /// "Pass 3": interchange EnumerateCollection nodes in all possible ways /// this is level 500, please never let new plans from higher /// levels go back to this or lower levels! ////////////////////////////////////////////////////////////////////////////// registerRule("interchangeAdjacentEnumerations", interchangeAdjacentEnumerations, 500); ////////////////////////////////////////////////////////////////////////////// // "Pass 4": moving nodes "up" (potentially outside loops) (second try): // please use levels between 501 and 599 here ////////////////////////////////////////////////////////////////////////////// // move calculations up the dependency chain (to pull them out of // inner loops etc.) registerRule("move-calculations-up", moveCalculationsUpRule, 510); // move filters up the dependency chain (to make result sets as small // as possible as early as possible) registerRule("move-filters-up", moveFiltersUpRule, 520); ////////////////////////////////////////////////////////////////////////////// /// "Pass 5": try to remove redundant or unnecessary nodes (second try) /// use levels between 601 and 699 for this ////////////////////////////////////////////////////////////////////////////// // remove filters from the query that are not necessary at all // filters that are always true will be removed entirely // filters that are always false will be replaced with a NoResults node registerRule("remove-unnecessary-filters", removeUnnecessaryFiltersRule, 610); // remove calculations that are never necessary registerRule("remove-unnecessary-calculations", removeUnnecessaryCalculationsRule, 620); // remove redundant sort blocks registerRule("remove-redundant-sorts", removeRedundantSorts, 630); ////////////////////////////////////////////////////////////////////////////// /// "Pass 6": use indexes if possible for FILTER and/or SORT nodes /// use levels between 701 and 799 for this ////////////////////////////////////////////////////////////////////////////// // try to find a filter after an enumerate collection and find an index . . . //registerRule("use-index-range", useIndexRange, 710); // try to find sort blocks which are superseeded by indexes //registerRule("use-index-for-sort", useIndexForSort, 720); ////////////////////////////////////////////////////////////////////////////// /// END OF OPTIMISATIONS ////////////////////////////////////////////////////////////////////////////// // Now sort them by level: std::stable_sort(_rules.begin(), _rules.end()); } // Local Variables: // mode: outline-minor // outline-regexp: "^\\(/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|// --SECTION--\\|/// @\\}\\)" // End: <commit_msg>fixed unused variables warning<commit_after>//////////////////////////////////////////////////////////////////////////////// /// @brief infrastructure for query optimizer /// /// @file arangod/Aql/Optimizer.cpp /// /// DISCLAIMER /// /// Copyright 2010-2014 triagens GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is triAGENS GmbH, Cologne, Germany /// /// @author Max Neunhoeffer /// @author Copyright 2014, triagens GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// #include "Aql/Optimizer.h" #include "Aql/OptimizerRules.h" using namespace triagens::aql; // ----------------------------------------------------------------------------- // --SECTION-- the optimizer class // ----------------------------------------------------------------------------- std::vector<Optimizer::Rule> Optimizer::_rules; //////////////////////////////////////////////////////////////////////////////// // @brief constructor, this will initialize the rules database //////////////////////////////////////////////////////////////////////////////// Optimizer::Optimizer () { if (_rules.empty()) { setupRules(); } } //////////////////////////////////////////////////////////////////////////////// // @brief the actual optimization //////////////////////////////////////////////////////////////////////////////// int Optimizer::createPlans (ExecutionPlan* plan) { int res; int leastDoneLevel = 0; int maxRuleLevel = _rules.back().level; // _plans contains the previous optimisation result _plans.clear(); _plans.push_back(plan, 0); // int pass = 1; while (leastDoneLevel < maxRuleLevel) { /* std::cout << "Entering pass " << pass << " of query optimization..." << std::endl; */ // This vector holds the plans we have created in this pass: PlanList newPlans; // Find variable usage for all old plans now: for (auto p : _plans.list) { if (! p->varUsageComputed()) { p->findVarUsage(); } } // std::cout << "Have " << _plans.size() << " plans:" << std::endl; /* for (auto p : _plans.list) { p->show(); std::cout << std::endl; } */ // int count = 0; // For all current plans: while (_plans.size() > 0) { int level; auto p = _plans.pop_front(level); if (level == maxRuleLevel) { newPlans.push_back(p, level); // nothing to do, just keep it } else { // some rule needs applying Rule r("dummy", dummyRule, level); auto it = std::upper_bound(_rules.begin(), _rules.end(), r); TRI_ASSERT(it != _rules.end()); /* std::cout << "Trying rule " << it->name << " (" << &(it->func) << ") with level " << it->level << " on plan " << count++ << std::endl; */ try { res = it->func(this, p, it->level, newPlans); } catch (...) { delete p; throw; } if (res != TRI_ERROR_NO_ERROR) { return res; } } // TODO: abort early here if we found a good-enough plan // a good-enough plan is probably every plan with costs below some // defined threshold. this requires plan costs to be calculated here } _plans.steal(newPlans); leastDoneLevel = maxRuleLevel; for (auto l : _plans.levelDone) { if (l < leastDoneLevel) { leastDoneLevel = l; } } // std::cout << "Least done level is " << leastDoneLevel << std::endl; // Stop if the result gets out of hand: if (_plans.size() >= maxNumberOfPlans) { break; } } estimatePlans(); sortPlans(); /* std::cout << "Optimisation ends with " << _plans.size() << " plans." << std::endl; for (auto p : _plans.list) { p->show(); std::cout << "costing: " << p->getCost() << std::endl; std::cout << std::endl; } */ return TRI_ERROR_NO_ERROR; } //////////////////////////////////////////////////////////////////////////////// /// @brief estimatePlans //////////////////////////////////////////////////////////////////////////////// void Optimizer::estimatePlans () { for (auto p : _plans.list) { p->getCost(); // this value is cached in the plan, so formally this step is // unnecessary, but for the sake of cleanliness... } } //////////////////////////////////////////////////////////////////////////////// /// @brief sortPlans //////////////////////////////////////////////////////////////////////////////// void Optimizer::sortPlans () { std::sort(_plans.list.begin(), _plans.list.end(), [](ExecutionPlan* const& a, ExecutionPlan* const& b) -> bool { return a->getCost() < b->getCost(); }); } //////////////////////////////////////////////////////////////////////////////// /// @brief set up the optimizer rules once and forever //////////////////////////////////////////////////////////////////////////////// void Optimizer::setupRules () { TRI_ASSERT(_rules.empty()); // List all the rules in the system here: // lower level values mean earlier rule execution // if two rules have the same level value, they will be executed in declaration order ////////////////////////////////////////////////////////////////////////////// // "Pass 1": moving nodes "up" (potentially outside loops): // please use levels between 1 and 99 here ////////////////////////////////////////////////////////////////////////////// // move calculations up the dependency chain (to pull them out of // inner loops etc.) registerRule("move-calculations-up", moveCalculationsUpRule, 10); // move filters up the dependency chain (to make result sets as small // as possible as early as possible) registerRule("move-filters-up", moveFiltersUpRule, 20); ////////////////////////////////////////////////////////////////////////////// /// "Pass 2": try to remove redundant or unnecessary nodes /// use levels between 101 and 199 for this ////////////////////////////////////////////////////////////////////////////// // remove filters from the query that are not necessary at all // filters that are always true will be removed entirely // filters that are always false will be replaced with a NoResults node registerRule("remove-unnecessary-filters", removeUnnecessaryFiltersRule, 110); // remove calculations that are never necessary registerRule("remove-unnecessary-calculations", removeUnnecessaryCalculationsRule, 120); // remove redundant sort blocks registerRule("remove-redundant-sorts", removeRedundantSorts, 130); ////////////////////////////////////////////////////////////////////////////// /// "Pass 3": interchange EnumerateCollection nodes in all possible ways /// this is level 500, please never let new plans from higher /// levels go back to this or lower levels! ////////////////////////////////////////////////////////////////////////////// registerRule("interchangeAdjacentEnumerations", interchangeAdjacentEnumerations, 500); ////////////////////////////////////////////////////////////////////////////// // "Pass 4": moving nodes "up" (potentially outside loops) (second try): // please use levels between 501 and 599 here ////////////////////////////////////////////////////////////////////////////// // move calculations up the dependency chain (to pull them out of // inner loops etc.) registerRule("move-calculations-up", moveCalculationsUpRule, 510); // move filters up the dependency chain (to make result sets as small // as possible as early as possible) registerRule("move-filters-up", moveFiltersUpRule, 520); ////////////////////////////////////////////////////////////////////////////// /// "Pass 5": try to remove redundant or unnecessary nodes (second try) /// use levels between 601 and 699 for this ////////////////////////////////////////////////////////////////////////////// // remove filters from the query that are not necessary at all // filters that are always true will be removed entirely // filters that are always false will be replaced with a NoResults node registerRule("remove-unnecessary-filters", removeUnnecessaryFiltersRule, 610); // remove calculations that are never necessary registerRule("remove-unnecessary-calculations", removeUnnecessaryCalculationsRule, 620); // remove redundant sort blocks registerRule("remove-redundant-sorts", removeRedundantSorts, 630); ////////////////////////////////////////////////////////////////////////////// /// "Pass 6": use indexes if possible for FILTER and/or SORT nodes /// use levels between 701 and 799 for this ////////////////////////////////////////////////////////////////////////////// // try to find a filter after an enumerate collection and find an index . . . //registerRule("use-index-range", useIndexRange, 710); // try to find sort blocks which are superseeded by indexes //registerRule("use-index-for-sort", useIndexForSort, 720); ////////////////////////////////////////////////////////////////////////////// /// END OF OPTIMISATIONS ////////////////////////////////////////////////////////////////////////////// // Now sort them by level: std::stable_sort(_rules.begin(), _rules.end()); } // Local Variables: // mode: outline-minor // outline-regexp: "^\\(/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|// --SECTION--\\|/// @\\}\\)" // End: <|endoftext|>
<commit_before>#ifndef _DLLPARSER_H #define _DLLPARSER_H #include <dlfcn.h> #include <iostream> #include <string> #include <unordered_map> #include <functional> #include <memory> class DllParser { public: ~DllParser() { unload(); } bool load(const std::string& dllFilePath) { m_handle = dlopen(dllFilePath.c_str(), RTLD_NOW); if (m_handle == nullptr) { std::cout << "Open dll failed, error: " << dlerror() << std::endl; return false; } return true; } bool unload() { if (m_handle == nullptr) { return true; } int ret = dlclose(m_handle); m_handle = nullptr; if (ret != 0) { std::cout << "Close dll failed, error: " << dlerror() << std::endl; return false; } return true; } template<typename T> std::function<T> getFunction(const std::string& funcName) { auto iter = m_funcMap.find(funcName); if (iter == m_funcMap.end()) { void* addr = dlsym(m_handle, funcName.c_str()); if (addr == nullptr) { std::cout << "func is nullptr, error: " << dlerror() << std::endl; return nullptr; } m_funcMap.insert(std::make_pair(funcName, addr)); iter = m_funcMap.find(funcName); } return std::function<T>(reinterpret_cast<T*>(iter->second)); } template<typename T, typename... Args> typename std::result_of<std::function<T>(Args...)>::type excecuteFunction(const std::string& funcName, Args&&... args) { auto func = getFunction<T>(funcName); if (func == nullptr) { std::string str = "Can not find this function: " + funcName; throw std::runtime_error(str); } return func(std::forward<Args>(args)...); } private: void* m_handle = nullptr; std::unordered_map<std::string, void*> m_funcMap; }; using DllParserPtr = std::shared_ptr<DllParser>; #endif <commit_msg>Update dllparser<commit_after>#ifndef _DLLPARSER_H #define _DLLPARSER_H #include <dlfcn.h> #include <iostream> #include <exception> #include <stdexcept> #include <string> #include <unordered_map> #include <functional> #include <memory> class DllParser { public: ~DllParser() { unload(); } bool load(const std::string& dllFilePath) { m_handle = dlopen(dllFilePath.c_str(), RTLD_NOW); if (m_handle == nullptr) { std::cout << "Open dll failed, error: " << dlerror() << std::endl; return false; } return true; } bool unload() { if (m_handle == nullptr) { return true; } int ret = dlclose(m_handle); m_handle = nullptr; if (ret != 0) { std::cout << "Close dll failed, error: " << dlerror() << std::endl; return false; } return true; } template<typename T> std::function<T> getFunction(const std::string& funcName) { auto iter = m_funcMap.find(funcName); if (iter == m_funcMap.end()) { void* addr = dlsym(m_handle, funcName.c_str()); if (addr == nullptr) { std::cout << "func is nullptr, error: " << dlerror() << std::endl; return nullptr; } m_funcMap.insert(std::make_pair(funcName, addr)); iter = m_funcMap.find(funcName); } return std::function<T>(reinterpret_cast<T*>(iter->second)); } template<typename T, typename... Args> typename std::result_of<std::function<T>(Args...)>::type excecuteFunction(const std::string& funcName, Args&&... args) { auto func = getFunction<T>(funcName); if (func == nullptr) { std::string str = "Can not find this function: " + funcName; throw std::runtime_error(str); } return func(std::forward<Args>(args)...); } private: void* m_handle = nullptr; std::unordered_map<std::string, void*> m_funcMap; }; using DllParserPtr = std::shared_ptr<DllParser>; #endif <|endoftext|>
<commit_before>#ifndef EPETRA_TESTABLEWRAPPERS_H #define EPETRA_TESTABLEWRAPPERS_H #include "src/Epetra_SerialDenseMatrixWrapper.hpp" #include "src/Epetra_MultiVectorWrapper.hpp" #include "src/Epetra_OperatorWrapper.hpp" #include "Epetra_SerialDenseMatrix.h" #include "Epetra_MultiVector.h" #include "Epetra_Operator.h" using namespace RAILS; class TestableEpetra_MultiVectorWrapper: public Epetra_MultiVectorWrapper { public: TestableEpetra_MultiVectorWrapper(Epetra_MultiVectorWrapper const &other) : Epetra_MultiVectorWrapper(other) {} TestableEpetra_MultiVectorWrapper(Epetra_MultiVectorWrapper &&other) : Epetra_MultiVectorWrapper(std::forward<Epetra_MultiVectorWrapper>(other)) {} TestableEpetra_MultiVectorWrapper(TestableEpetra_MultiVectorWrapper &&other) : Epetra_MultiVectorWrapper(std::forward<Epetra_MultiVectorWrapper>(other)) {} TestableEpetra_MultiVectorWrapper(int m, int n) : Epetra_MultiVectorWrapper(m, n) {} Epetra_MultiVectorWrapper &operator =(TestableEpetra_MultiVectorWrapper &other) { return Epetra_MultiVectorWrapper::operator =(other); } Epetra_MultiVectorWrapper &operator =(TestableEpetra_MultiVectorWrapper const &other) { return Epetra_MultiVectorWrapper::operator =(other); } Epetra_MultiVectorWrapper &operator =(TestableEpetra_MultiVectorWrapper &&other) { return Epetra_MultiVectorWrapper::operator =(std::forward<Epetra_MultiVectorWrapper>(other)); } Epetra_MultiVectorWrapper &operator =(double other) { return Epetra_MultiVectorWrapper::operator =(other); } double &operator ()(int m, int n = 0) { return Epetra_MultiVectorWrapper::operator()(m, n); } double const &operator ()(int m, int n = 0) const { return Epetra_MultiVectorWrapper::operator()(m, n); } }; class TestableEpetra_OperatorWrapper: public Epetra_OperatorWrapper { public: TestableEpetra_OperatorWrapper(Epetra_OperatorWrapper const &other) : Epetra_OperatorWrapper(other) {} TestableEpetra_OperatorWrapper(int m, int n) : Epetra_OperatorWrapper(m, n) {} double &operator ()(int m, int n = 0) { return Epetra_OperatorWrapper::operator()(m, n); } double const &operator ()(int m, int n = 0) const { return Epetra_OperatorWrapper::operator()(m, n); } }; #endif <commit_msg>TestableEpetra_MultiVectorWrapper: Add an explicit copy constructor.<commit_after>#ifndef EPETRA_TESTABLEWRAPPERS_H #define EPETRA_TESTABLEWRAPPERS_H #include "src/Epetra_SerialDenseMatrixWrapper.hpp" #include "src/Epetra_MultiVectorWrapper.hpp" #include "src/Epetra_OperatorWrapper.hpp" #include "Epetra_SerialDenseMatrix.h" #include "Epetra_MultiVector.h" #include "Epetra_Operator.h" using namespace RAILS; class TestableEpetra_MultiVectorWrapper: public Epetra_MultiVectorWrapper { public: TestableEpetra_MultiVectorWrapper(Epetra_MultiVectorWrapper const &other) : Epetra_MultiVectorWrapper(other) {} TestableEpetra_MultiVectorWrapper(Epetra_MultiVectorWrapper &&other) : Epetra_MultiVectorWrapper(std::forward<Epetra_MultiVectorWrapper>(other)) {} TestableEpetra_MultiVectorWrapper(TestableEpetra_MultiVectorWrapper const &other) : Epetra_MultiVectorWrapper(other) {} TestableEpetra_MultiVectorWrapper(TestableEpetra_MultiVectorWrapper &&other) : Epetra_MultiVectorWrapper(std::forward<Epetra_MultiVectorWrapper>(other)) {} TestableEpetra_MultiVectorWrapper(int m, int n) : Epetra_MultiVectorWrapper(m, n) {} Epetra_MultiVectorWrapper &operator =(TestableEpetra_MultiVectorWrapper &other) { return Epetra_MultiVectorWrapper::operator =(other); } Epetra_MultiVectorWrapper &operator =(TestableEpetra_MultiVectorWrapper const &other) { return Epetra_MultiVectorWrapper::operator =(other); } Epetra_MultiVectorWrapper &operator =(TestableEpetra_MultiVectorWrapper &&other) { return Epetra_MultiVectorWrapper::operator =(std::forward<Epetra_MultiVectorWrapper>(other)); } Epetra_MultiVectorWrapper &operator =(double other) { return Epetra_MultiVectorWrapper::operator =(other); } double &operator ()(int m, int n = 0) { return Epetra_MultiVectorWrapper::operator()(m, n); } double const &operator ()(int m, int n = 0) const { return Epetra_MultiVectorWrapper::operator()(m, n); } }; class TestableEpetra_OperatorWrapper: public Epetra_OperatorWrapper { public: TestableEpetra_OperatorWrapper(Epetra_OperatorWrapper const &other) : Epetra_OperatorWrapper(other) {} TestableEpetra_OperatorWrapper(int m, int n) : Epetra_OperatorWrapper(m, n) {} double &operator ()(int m, int n = 0) { return Epetra_OperatorWrapper::operator()(m, n); } double const &operator ()(int m, int n = 0) const { return Epetra_OperatorWrapper::operator()(m, n); } }; #endif <|endoftext|>
<commit_before>#include "Halide.h" #include <stdio.h> #include <algorithm> using namespace Halide; #ifdef _WIN32 #define DLLEXPORT __declspec(dllexport) #else #define DLLEXPORT #endif // Use an extern stage to do a sort extern "C" DLLEXPORT int sort_buffer(buffer_t *in, buffer_t *out) { if (!in->host) { in->min[0] = out->min[0]; in->extent[0] = out->extent[0]; } else { memcpy(out->host, in->host, out->extent[0] * out->elem_size); float *out_start = (float *)out->host; float *out_end = out_start + out->extent[0]; std::sort(out_start, out_end); out->host_dirty = true; } return 0; } int main(int argc, char **argv) { Func data; Var x; data(x) = sin(x); data.compute_root(); Func sorted; std::vector<ExternFuncArgument> args; args.push_back(data); sorted.define_extern("sort_buffer", args, Float(32), 1); Buffer<float> output = sorted.realize(100); // Check the output Buffer<float> reference = lambda(x, sin(x)).realize(100); std::sort(&reference(0), &reference(100)); RDom r(reference); float error = evaluate_may_gpu<float>(sum(abs(reference(r) - output(r)))); if (error != 0) { printf("Output incorrect\n"); return -1; } printf("Success!\n"); return 0; } <commit_msg>extern_sort also does an output bounds query<commit_after>#include "Halide.h" #include <stdio.h> #include <algorithm> using namespace Halide; #ifdef _WIN32 #define DLLEXPORT __declspec(dllexport) #else #define DLLEXPORT #endif // Use an extern stage to do a sort extern "C" DLLEXPORT int sort_buffer(buffer_t *in, buffer_t *out) { if (!in->host || !out->host) { in->min[0] = out->min[0]; in->extent[0] = out->extent[0]; } else { memcpy(out->host, in->host, out->extent[0] * out->elem_size); float *out_start = (float *)out->host; float *out_end = out_start + out->extent[0]; std::sort(out_start, out_end); out->host_dirty = true; } return 0; } int main(int argc, char **argv) { Func data; Var x; data(x) = sin(x); data.compute_root(); Func sorted; std::vector<ExternFuncArgument> args; args.push_back(data); sorted.define_extern("sort_buffer", args, Float(32), 1); Buffer<float> output = sorted.realize(100); // Check the output Buffer<float> reference = lambda(x, sin(x)).realize(100); std::sort(&reference(0), &reference(100)); RDom r(reference); float error = evaluate_may_gpu<float>(sum(abs(reference(r) - output(r)))); if (error != 0) { printf("Output incorrect\n"); return -1; } printf("Success!\n"); return 0; } <|endoftext|>
<commit_before>#if defined(TEMPEST_BUILD_VULKAN) #include "vswapchain.h" #include <Tempest/SystemApi> #include "vdevice.h" using namespace Tempest; using namespace Tempest::Detail; VSwapchain::FenceList::FenceList(VkDevice dev, uint32_t cnt) :dev(dev), size(0) { aquire .reset(new VkFence[cnt]); present.reset(new VkFence[cnt]); for(uint32_t i=0; i<cnt; ++i) { aquire [i] = VK_NULL_HANDLE; present[i] = VK_NULL_HANDLE; } try { VkFenceCreateInfo fenceInfo = {}; fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT; for(uint32_t i=0; i<cnt; ++i) { vkAssert(vkCreateFence(dev,&fenceInfo,nullptr,&aquire [i])); vkAssert(vkCreateFence(dev,&fenceInfo,nullptr,&present[i])); ++size; } } catch(...) { for(uint32_t i=0; i<cnt; ++i) { if(aquire[i]!=VK_NULL_HANDLE) vkDestroyFence(dev,aquire [i],nullptr); if(present[i]!=VK_NULL_HANDLE) vkDestroyFence(dev,present[i],nullptr); } throw; } } VSwapchain::FenceList::FenceList(VSwapchain::FenceList&& oth) :dev(oth.dev), size(oth.size) { aquire = std::move(oth.aquire); present = std::move(oth.present); oth.size = 0; } VSwapchain::FenceList& VSwapchain::FenceList::operator =(VSwapchain::FenceList&& oth) { std::swap(dev, oth.dev); std::swap(aquire, oth.aquire); std::swap(present, oth.present); std::swap(size, oth.size); return *this; } VSwapchain::FenceList::~FenceList() { for(uint32_t i=0; i<size; ++i) { vkDestroyFence(dev,aquire [i],nullptr); vkDestroyFence(dev,present[i],nullptr); } } VSwapchain::VSwapchain(VDevice &device, SystemApi::Window* hwnd) :device(device), hwnd(hwnd) { try { surface = device.createSurface(hwnd); auto support = device.querySwapChainSupport(surface); uint32_t imgCount = getImageCount(support); createSwapchain(device,support,SystemApi::windowClientRect(hwnd),imgCount); } catch(...) { cleanup(); throw; } } VSwapchain::~VSwapchain() { cleanup(); } void VSwapchain::cleanupSwapchain() noexcept { vkWaitForFences(device.device.impl,fence.size,fence.aquire.get(), VK_TRUE,std::numeric_limits<uint64_t>::max()); vkWaitForFences(device.device.impl,fence.size,fence.present.get(),VK_TRUE,std::numeric_limits<uint64_t>::max()); fence = FenceList(); for(auto imageView : views) if(map!=nullptr && imageView!=VK_NULL_HANDLE) map->notifyDestroy(imageView); for(auto imageView : views) if(imageView!=VK_NULL_HANDLE) vkDestroyImageView(device.device.impl,imageView,nullptr); for(auto s : sync) { if(s.aquire!=VK_NULL_HANDLE) vkDestroySemaphore(device.device.impl,s.aquire,nullptr); if(s.present!=VK_NULL_HANDLE) vkDestroySemaphore(device.device.impl,s.present,nullptr); } views.clear(); images.clear(); sync.clear(); if(swapChain!=VK_NULL_HANDLE) vkDestroySwapchainKHR(device.device.impl,swapChain,nullptr); swapChain = VK_NULL_HANDLE; swapChainImageFormat = VK_FORMAT_UNDEFINED; swapChainExtent = {}; } void VSwapchain::cleanupSurface() noexcept { if(surface!=VK_NULL_HANDLE) vkDestroySurfaceKHR(device.instance,surface,nullptr); } void VSwapchain::reset() { const Rect rect = SystemApi::windowClientRect(hwnd); if(rect.isEmpty()) return; cleanupSwapchain(); try { auto support = device.querySwapChainSupport(surface); uint32_t imgCount = getImageCount(support); createSwapchain(device,support,rect,imgCount); } catch(...) { cleanup(); throw; } } void VSwapchain::cleanup() noexcept { cleanupSwapchain(); cleanupSurface(); } void VSwapchain::createSwapchain(VDevice& device, const SwapChainSupport& swapChainSupport, const Rect& rect, uint32_t imgCount) { VkBool32 support=false; vkGetPhysicalDeviceSurfaceSupportKHR(device.physicalDevice,device.presentQueue->family,surface,&support); if(!support) throw std::system_error(Tempest::GraphicsErrc::NoDevice); VkSurfaceFormatKHR surfaceFormat = getSwapSurfaceFormat(swapChainSupport.formats); VkPresentModeKHR presentMode = getSwapPresentMode (swapChainSupport.presentModes); VkExtent2D extent = getSwapExtent (swapChainSupport.capabilities,uint32_t(rect.w),uint32_t(rect.h)); VkSwapchainCreateInfoKHR createInfo = {}; createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; createInfo.surface = surface; createInfo.minImageCount = imgCount; createInfo.imageFormat = surfaceFormat.format; createInfo.imageColorSpace = surfaceFormat.colorSpace; createInfo.imageExtent = extent; createInfo.imageArrayLayers = 1; createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; if(device.graphicsQueue!=device.presentQueue) { const uint32_t qidx[] = {device.graphicsQueue->family,device.presentQueue->family}; createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT; createInfo.queueFamilyIndexCount = 2; createInfo.pQueueFamilyIndices = qidx; } else { createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; } createInfo.preTransform = swapChainSupport.capabilities.currentTransform; createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; createInfo.presentMode = presentMode; createInfo.clipped = VK_TRUE; if(vkCreateSwapchainKHR(device.device.impl, &createInfo, nullptr, &swapChain) != VK_SUCCESS) throw std::system_error(Tempest::GraphicsErrc::NoDevice); swapChainImageFormat = surfaceFormat.format; swapChainExtent = extent; createImageViews(device); VkSemaphoreCreateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; info.flags = 0; sync.resize(views.size()); for(auto& i:sync) { vkAssert(vkCreateSemaphore(device.device.impl,&info,nullptr,&i.aquire)); vkAssert(vkCreateSemaphore(device.device.impl,&info,nullptr,&i.present)); } fence = FenceList(device.device.impl,views.size()); aquireNextImage(); } void VSwapchain::createImageViews(VDevice &device) { uint32_t imgCount=0; vkGetSwapchainImagesKHR(device.device.impl, swapChain, &imgCount, nullptr); images.resize(imgCount); vkGetSwapchainImagesKHR(device.device.impl, swapChain, &imgCount, images.data()); views.resize(images.size()); for(size_t i=0; i<images.size(); i++) { VkImageViewCreateInfo createInfo = {}; createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; createInfo.image = images[i]; createInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; createInfo.format = swapChainImageFormat; createInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; createInfo.subresourceRange.baseMipLevel = 0; createInfo.subresourceRange.levelCount = 1; createInfo.subresourceRange.baseArrayLayer = 0; createInfo.subresourceRange.layerCount = 1; if(vkCreateImageView(device.device.impl,&createInfo,nullptr,&views[i])!=VK_SUCCESS) throw std::system_error(Tempest::GraphicsErrc::NoDevice); } } VkSurfaceFormatKHR VSwapchain::getSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats) { if(availableFormats.size()==1 && availableFormats[0].format==VK_FORMAT_UNDEFINED) return {VK_FORMAT_B8G8R8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR}; for(const auto& availableFormat : availableFormats) { if(availableFormat.format==VK_FORMAT_B8G8R8A8_UNORM && availableFormat.colorSpace==VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) return availableFormat; } return availableFormats[0]; } VkPresentModeKHR VSwapchain::getSwapPresentMode(const std::vector<VkPresentModeKHR> &availablePresentModes) { /** intel says mailbox is better option for games * https://software.intel.com/content/www/us/en/develop/articles/api-without-secrets-introduction-to-vulkan-part-2.html **/ std::initializer_list<VkPresentModeKHR> modes={ VK_PRESENT_MODE_MAILBOX_KHR, // vsync; wait until vsync VK_PRESENT_MODE_FIFO_RELAXED_KHR, // vsync; optimal, but tearing VK_PRESENT_MODE_FIFO_KHR, // vsync; optimal VK_PRESENT_MODE_IMMEDIATE_KHR, // no vsync }; for(auto mode:modes){ for(const auto available:availablePresentModes) if(available==mode) return mode; } // no good modes return VK_PRESENT_MODE_FIFO_KHR; } VkExtent2D VSwapchain::getSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, uint32_t w,uint32_t h) { if(capabilities.currentExtent.width!=std::numeric_limits<uint32_t>::max()) { return capabilities.currentExtent; } VkExtent2D actualExtent = { static_cast<uint32_t>(w), static_cast<uint32_t>(h) }; actualExtent.width = std::max(capabilities.minImageExtent.width, std::min(capabilities.maxImageExtent.width, actualExtent.width)); actualExtent.height = std::max(capabilities.minImageExtent.height, std::min(capabilities.maxImageExtent.height, actualExtent.height)); return actualExtent; } uint32_t VSwapchain::getImageCount(const SwapChainSupport& support) const { const uint32_t maxImages=support.capabilities.maxImageCount==0 ? uint32_t(-1) : support.capabilities.maxImageCount; uint32_t imageCount=support.capabilities.minImageCount+1; if(0<support.capabilities.maxImageCount && imageCount>maxImages) imageCount = support.capabilities.maxImageCount; return imageCount; } void VSwapchain::aquireNextImage() { auto& slot = sync[syncIndex]; auto& f = fence.aquire[syncIndex]; vkWaitForFences(device.device.impl,1,&f,VK_TRUE,std::numeric_limits<uint64_t>::max()); vkResetFences(device.device.impl,1,&f); uint32_t id = uint32_t(-1); VkResult code = vkAcquireNextImageKHR(device.device.impl, swapChain, std::numeric_limits<uint64_t>::max(), slot.aquire, f, &id); if(code==VK_ERROR_OUT_OF_DATE_KHR) throw DeviceLostException(); if(code==VK_SUBOPTIMAL_KHR) throw SwapchainSuboptimal(); if(code!=VK_SUCCESS) vkAssert(code); imgIndex = id; slot.imgId = id; slot.state = S_Pending; syncIndex = (syncIndex+1)%uint32_t(sync.size()); } uint32_t VSwapchain::currentBackBufferIndex() { return imgIndex; } void VSwapchain::present(VDevice& dev) { auto& slot = sync[imgIndex]; auto& f = fence.present[imgIndex]; vkResetFences(device.device.impl,1,&f); VkSubmitInfo submitInfo = {}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submitInfo.signalSemaphoreCount = 1; submitInfo.pSignalSemaphores = &slot.present; dev.graphicsQueue->submit(1, &submitInfo, f); VkPresentInfoKHR presentInfo = {}; presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; presentInfo.waitSemaphoreCount = 1; presentInfo.pWaitSemaphores = &slot.present; presentInfo.swapchainCount = 1; presentInfo.pSwapchains = &swapChain; presentInfo.pImageIndices = &imgIndex; //auto t = Application::tickCount(); VkResult code = dev.presentQueue->present(presentInfo); if(code==VK_ERROR_OUT_OF_DATE_KHR || code==VK_SUBOPTIMAL_KHR) throw SwapchainSuboptimal(); //Log::i("vkQueuePresentKHR = ",Application::tickCount()-t); Detail::vkAssert(code); aquireNextImage(); } #endif <commit_msg>swapchain fixes<commit_after>#if defined(TEMPEST_BUILD_VULKAN) #include "vswapchain.h" #include <Tempest/SystemApi> #include "vdevice.h" using namespace Tempest; using namespace Tempest::Detail; VSwapchain::FenceList::FenceList(VkDevice dev, uint32_t cnt) :dev(dev), size(0) { aquire .reset(new VkFence[cnt]); present.reset(new VkFence[cnt]); for(uint32_t i=0; i<cnt; ++i) { aquire [i] = VK_NULL_HANDLE; present[i] = VK_NULL_HANDLE; } try { VkFenceCreateInfo fenceInfo = {}; fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT; for(uint32_t i=0; i<cnt; ++i) { vkAssert(vkCreateFence(dev,&fenceInfo,nullptr,&aquire [i])); vkAssert(vkCreateFence(dev,&fenceInfo,nullptr,&present[i])); ++size; } } catch(...) { for(uint32_t i=0; i<cnt; ++i) { if(aquire[i]!=VK_NULL_HANDLE) vkDestroyFence(dev,aquire [i],nullptr); if(present[i]!=VK_NULL_HANDLE) vkDestroyFence(dev,present[i],nullptr); } throw; } } VSwapchain::FenceList::FenceList(VSwapchain::FenceList&& oth) :dev(oth.dev), size(oth.size) { aquire = std::move(oth.aquire); present = std::move(oth.present); oth.size = 0; } VSwapchain::FenceList& VSwapchain::FenceList::operator =(VSwapchain::FenceList&& oth) { std::swap(dev, oth.dev); std::swap(aquire, oth.aquire); std::swap(present, oth.present); std::swap(size, oth.size); return *this; } VSwapchain::FenceList::~FenceList() { for(uint32_t i=0; i<size; ++i) { vkDestroyFence(dev,aquire [i],nullptr); vkDestroyFence(dev,present[i],nullptr); } } VSwapchain::VSwapchain(VDevice &device, SystemApi::Window* hwnd) :device(device), hwnd(hwnd) { try { surface = device.createSurface(hwnd); auto support = device.querySwapChainSupport(surface); uint32_t imgCount = getImageCount(support); createSwapchain(device,support,SystemApi::windowClientRect(hwnd),imgCount); } catch(...) { cleanup(); throw; } } VSwapchain::~VSwapchain() { cleanup(); } void VSwapchain::cleanupSwapchain() noexcept { vkWaitForFences(device.device.impl,fence.size,fence.aquire.get(), VK_TRUE,std::numeric_limits<uint64_t>::max()); vkWaitForFences(device.device.impl,fence.size,fence.present.get(),VK_TRUE,std::numeric_limits<uint64_t>::max()); fence = FenceList(); for(auto imageView : views) if(map!=nullptr && imageView!=VK_NULL_HANDLE) map->notifyDestroy(imageView); for(auto imageView : views) if(imageView!=VK_NULL_HANDLE) vkDestroyImageView(device.device.impl,imageView,nullptr); for(auto s : sync) { if(s.aquire!=VK_NULL_HANDLE) vkDestroySemaphore(device.device.impl,s.aquire,nullptr); if(s.present!=VK_NULL_HANDLE) vkDestroySemaphore(device.device.impl,s.present,nullptr); } views.clear(); images.clear(); sync.clear(); if(swapChain!=VK_NULL_HANDLE) vkDestroySwapchainKHR(device.device.impl,swapChain,nullptr); swapChain = VK_NULL_HANDLE; swapChainImageFormat = VK_FORMAT_UNDEFINED; swapChainExtent = {}; } void VSwapchain::cleanupSurface() noexcept { if(surface!=VK_NULL_HANDLE) vkDestroySurfaceKHR(device.instance,surface,nullptr); } void VSwapchain::reset() { const Rect rect = SystemApi::windowClientRect(hwnd); if(rect.isEmpty()) return; cleanupSwapchain(); try { auto support = device.querySwapChainSupport(surface); uint32_t imgCount = getImageCount(support); createSwapchain(device,support,rect,imgCount); } catch(...) { cleanup(); throw; } } void VSwapchain::cleanup() noexcept { cleanupSwapchain(); cleanupSurface(); } void VSwapchain::createSwapchain(VDevice& device, const SwapChainSupport& swapChainSupport, const Rect& rect, uint32_t imgCount) { VkBool32 support=false; vkGetPhysicalDeviceSurfaceSupportKHR(device.physicalDevice,device.presentQueue->family,surface,&support); if(!support) throw std::system_error(Tempest::GraphicsErrc::NoDevice); VkSurfaceFormatKHR surfaceFormat = getSwapSurfaceFormat(swapChainSupport.formats); VkPresentModeKHR presentMode = getSwapPresentMode (swapChainSupport.presentModes); VkExtent2D extent = getSwapExtent (swapChainSupport.capabilities,uint32_t(rect.w),uint32_t(rect.h)); VkSwapchainCreateInfoKHR createInfo = {}; createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; createInfo.surface = surface; createInfo.minImageCount = imgCount; createInfo.imageFormat = surfaceFormat.format; createInfo.imageColorSpace = surfaceFormat.colorSpace; createInfo.imageExtent = extent; createInfo.imageArrayLayers = 1; createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; if(device.graphicsQueue!=device.presentQueue) { const uint32_t qidx[] = {device.graphicsQueue->family,device.presentQueue->family}; createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT; createInfo.queueFamilyIndexCount = 2; createInfo.pQueueFamilyIndices = qidx; } else { createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; } createInfo.preTransform = swapChainSupport.capabilities.currentTransform; createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; createInfo.presentMode = presentMode; createInfo.clipped = VK_TRUE; if(vkCreateSwapchainKHR(device.device.impl, &createInfo, nullptr, &swapChain) != VK_SUCCESS) throw std::system_error(Tempest::GraphicsErrc::NoDevice); swapChainImageFormat = surfaceFormat.format; swapChainExtent = extent; createImageViews(device); VkSemaphoreCreateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; info.flags = 0; sync.resize(views.size()); for(auto& i:sync) { vkAssert(vkCreateSemaphore(device.device.impl,&info,nullptr,&i.aquire)); vkAssert(vkCreateSemaphore(device.device.impl,&info,nullptr,&i.present)); } fence = FenceList(device.device.impl,views.size()); aquireNextImage(); } void VSwapchain::createImageViews(VDevice &device) { uint32_t imgCount=0; vkGetSwapchainImagesKHR(device.device.impl, swapChain, &imgCount, nullptr); images.resize(imgCount); vkGetSwapchainImagesKHR(device.device.impl, swapChain, &imgCount, images.data()); views.resize(images.size()); for(size_t i=0; i<images.size(); i++) { VkImageViewCreateInfo createInfo = {}; createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; createInfo.image = images[i]; createInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; createInfo.format = swapChainImageFormat; createInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; createInfo.subresourceRange.baseMipLevel = 0; createInfo.subresourceRange.levelCount = 1; createInfo.subresourceRange.baseArrayLayer = 0; createInfo.subresourceRange.layerCount = 1; if(vkCreateImageView(device.device.impl,&createInfo,nullptr,&views[i])!=VK_SUCCESS) throw std::system_error(Tempest::GraphicsErrc::NoDevice); } } VkSurfaceFormatKHR VSwapchain::getSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats) { if(availableFormats.size()==1 && availableFormats[0].format==VK_FORMAT_UNDEFINED) return {VK_FORMAT_B8G8R8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR}; for(const auto& availableFormat : availableFormats) { if(availableFormat.format==VK_FORMAT_B8G8R8A8_UNORM && availableFormat.colorSpace==VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) return availableFormat; } return availableFormats[0]; } VkPresentModeKHR VSwapchain::getSwapPresentMode(const std::vector<VkPresentModeKHR> &availablePresentModes) { /** intel says mailbox is better option for games * https://software.intel.com/content/www/us/en/develop/articles/api-without-secrets-introduction-to-vulkan-part-2.html **/ std::initializer_list<VkPresentModeKHR> modes={ VK_PRESENT_MODE_MAILBOX_KHR, // vsync; wait until vsync VK_PRESENT_MODE_FIFO_RELAXED_KHR, // vsync; optimal, but tearing VK_PRESENT_MODE_FIFO_KHR, // vsync; optimal VK_PRESENT_MODE_IMMEDIATE_KHR, // no vsync }; for(auto mode:modes){ for(const auto available:availablePresentModes) if(available==mode) return mode; } // no good modes return VK_PRESENT_MODE_FIFO_KHR; } VkExtent2D VSwapchain::getSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, uint32_t w,uint32_t h) { if(capabilities.currentExtent.width!=std::numeric_limits<uint32_t>::max()) { return capabilities.currentExtent; } VkExtent2D actualExtent = { static_cast<uint32_t>(w), static_cast<uint32_t>(h) }; actualExtent.width = std::max(capabilities.minImageExtent.width, std::min(capabilities.maxImageExtent.width, actualExtent.width)); actualExtent.height = std::max(capabilities.minImageExtent.height, std::min(capabilities.maxImageExtent.height, actualExtent.height)); return actualExtent; } uint32_t VSwapchain::getImageCount(const SwapChainSupport& support) const { const uint32_t maxImages=support.capabilities.maxImageCount==0 ? uint32_t(-1) : support.capabilities.maxImageCount; uint32_t imageCount=support.capabilities.minImageCount+1; if(0<support.capabilities.maxImageCount && imageCount>maxImages) imageCount = support.capabilities.maxImageCount; return imageCount; } void VSwapchain::aquireNextImage() { auto& slot = sync[syncIndex]; auto& f = fence.aquire[syncIndex]; vkWaitForFences(device.device.impl,1,&f,VK_TRUE,std::numeric_limits<uint64_t>::max()); vkResetFences(device.device.impl,1,&f); uint32_t id = uint32_t(-1); VkResult code = vkAcquireNextImageKHR(device.device.impl, swapChain, std::numeric_limits<uint64_t>::max(), slot.aquire, f, &id); if(code==VK_ERROR_OUT_OF_DATE_KHR) throw DeviceLostException(); if(code==VK_SUBOPTIMAL_KHR) throw SwapchainSuboptimal(); if(code!=VK_SUCCESS) vkAssert(code); imgIndex = id; slot.imgId = id; slot.state = S_Pending; syncIndex = (syncIndex+1)%uint32_t(sync.size()); } uint32_t VSwapchain::currentBackBufferIndex() { return imgIndex; } void VSwapchain::present(VDevice& dev) { size_t sId = 0; for(size_t i=0; i<sync.size(); ++i) if(sync[i].imgId==imgIndex) { sId = i; break; } auto& slot = sync[sId]; auto& f = fence.present[sId]; vkResetFences(device.device.impl,1,&f); VkSubmitInfo submitInfo = {}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submitInfo.signalSemaphoreCount = 1; submitInfo.pSignalSemaphores = &slot.present; dev.graphicsQueue->submit(1, &submitInfo, f); VkPresentInfoKHR presentInfo = {}; presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; presentInfo.waitSemaphoreCount = 1; presentInfo.pWaitSemaphores = &slot.present; presentInfo.swapchainCount = 1; presentInfo.pSwapchains = &swapChain; presentInfo.pImageIndices = &imgIndex; slot.imgId = uint32_t(-1); slot.state = S_Idle; //auto t = Application::tickCount(); VkResult code = dev.presentQueue->present(presentInfo); if(code==VK_ERROR_OUT_OF_DATE_KHR || code==VK_SUBOPTIMAL_KHR) throw SwapchainSuboptimal(); //Log::i("vkQueuePresentKHR = ",Application::tickCount()-t); Detail::vkAssert(code); aquireNextImage(); } #endif <|endoftext|>
<commit_before>#include "config.h" #ifdef CONFIG_XFREETYPE #include "ypaint.h" #include "yapp.h" #include "ystring.h" #include "intl.h" /******************************************************************************/ class YXftFont : public YFont { public: #ifdef CONFIG_I18N typedef class YUnicodeString string_t; typedef XftChar32 char_t; #else typedef class YLocaleString string_t; typedef XftChar8 char_t; #endif YXftFont(char const * name); virtual ~YXftFont(); virtual operator bool() const { return (fFontCount > 0); } virtual int descent() const { return fDescent; } virtual int ascent() const { return fAscent; } virtual int textWidth(char const * str, int len) const; virtual int textWidth(string_t const & str) const; virtual void drawGlyphs(class Graphics & graphics, int x, int y, char const * str, int len); private: struct TextPart { XftFont * font; size_t length; unsigned width; }; TextPart * partitions(char_t * str, size_t len, size_t nparts = 0) const; unsigned fFontCount, fAscent, fDescent; XftFont ** fFonts; }; class XftGraphics { public: #ifdef CONFIG_I18N typedef XftChar32 char_t; #define XftDrawString XftDrawString32 #define XftTextExtents XftTextExtents32 #else typedef XftChar8 char_t; #define XftTextExtents XftTextExtents8 #define XftDrawString XftDrawString8 #endif XftGraphics(Graphics const & graphics, Visual * visual, Colormap colormap): fDraw(XftDrawCreate(graphics.display(), graphics.drawable(), visual, colormap)) {} ~XftGraphics() { if (fDraw) XftDrawDestroy(fDraw); } void drawRect(XftColor * color, int x, int y, unsigned w, unsigned h) { XftDrawRect(fDraw, color, x, y, w, h); } void drawString(XftColor * color, XftFont * font, int x, int y, char_t * str, size_t len) { XftDrawString(fDraw, color, font, x, y, str, len); } static void textExtents(XftFont * font, char_t * str, size_t len, XGlyphInfo & extends) { XftTextExtents(app->display (), font, str, len, &extends); } XftDraw * handle() const { return fDraw; } private: XftDraw * fDraw; }; /******************************************************************************/ YXftFont::YXftFont(const char *name): fFontCount(strtoken(name, ",")), fAscent(0), fDescent(0) { XftFont ** fptr(fFonts = new XftFont* [fFontCount]); for (char const *s(name); '\0' != *s; s = strnxt(s, ",")) { XftFont *& font(*fptr); char * xlfd(newstr(s + strspn(s, " \t\r\n"), ",")); char * endptr(xlfd + strlen(xlfd) - 1); while (endptr > xlfd && strchr(" \t\r\n", *endptr)) --endptr; endptr[1] = '\0'; font = XftFontOpenXlfd(app->display(), app->screen(), xlfd); if (NULL != font) { fAscent = max(fAscent, (unsigned) max(0, font->ascent)); fDescent = max(fDescent, (unsigned) max(0, font->descent)); ++fptr; } else { warn(_("Could not load font \"%s\"."), xlfd); --fFontCount; } #if 0 if (strstr(xlfd, "koi") != 0) { msg("font %s", xlfd); for (int c = 0; c < 0x500; c++) { if ((c % 64) == 0) { printf("\n%04X ", c); } int ok = XftGlyphExists(app->display(), font, c); printf("%c", ok ? 'X' : '.'); if ((c % 8) == 7) printf(" "); } printf("\n"); } #endif delete[] xlfd; } if (0 == fFontCount) { XftFont * sans(XftFontOpen(app->display(), app->screen(), XFT_FAMILY, XftTypeString, "sans", XFT_WEIGHT, XftTypeInteger, XFT_WEIGHT_MEDIUM, XFT_SLANT, XftTypeInteger, XFT_SLANT_ROMAN, XFT_PIXEL_SIZE, XftTypeInteger, 10, 0)); if (NULL != sans) { delete[] fFonts; fFontCount = 1; fFonts = new XftFont* [fFontCount]; fFonts[0] = sans; fAscent = sans->ascent; fDescent = sans->descent; } else warn(_("Loading of fallback font \"%s\" failed."), "sans"); } } YXftFont::~YXftFont() { for (unsigned n(0); n < fFontCount; ++n) XftFontClose(app->display(), fFonts[n]); delete[] fFonts; } int YXftFont::textWidth(string_t const & text) const { char_t * str((char_t *) text.data()); size_t len(text.length()); TextPart *parts = partitions(str, len); unsigned width(0); for (TextPart * p = parts; p && p->length; ++p) width+= p->width; delete[] parts; return width; } int YXftFont::textWidth(char const * str, int len) const { return textWidth(string_t(str, len)); } void YXftFont::drawGlyphs(Graphics & graphics, int x, int y, char const * str, int len) { string_t xtext(str, len); if (0 == xtext.length()) return; int const y0(y - ascent()); int const gcFn(graphics.function()); char_t * xstr((char_t *) xtext.data()); size_t xlen(xtext.length()); TextPart *parts = partitions(xstr, xlen); unsigned w(0); unsigned const h(height()); for (TextPart *p = parts; p && p->length; ++p) w+= p->width; YPixmap *pixmap = new YPixmap(w, h); Graphics canvas(*pixmap); XftGraphics textarea(canvas, app->visual(), app->colormap()); switch (gcFn) { case GXxor: textarea.drawRect(*YColor::black, 0, 0, w, h); break; case GXcopy: canvas.copyDrawable(graphics.drawable(), x, y0, w, h, 0, 0); break; } int xpos(0); for (TextPart *p = parts; p && p->length; ++p) { if (p->font) textarea.drawString(*graphics.color(), p->font, xpos, ascent(), xstr, p->length); xstr+= p->length; xpos+= p->width; } delete[] parts; graphics.copyDrawable(canvas.drawable(), 0, 0, w, h, x, y0); delete pixmap; } YXftFont::TextPart * YXftFont::partitions(char_t * str, size_t len, size_t nparts) const { XGlyphInfo extends; XftFont ** lFont(fFonts + fFontCount); XftFont ** font(NULL); char_t * c(str); for (char_t * endptr(str + len); c < endptr; ++c) { XftFont ** probe(fFonts); while (probe < lFont && !XftGlyphExists(app->display(), *probe, *c)) ++probe; if (probe != font) { if (NULL != font) { TextPart *parts = partitions(c, len - (c - str), nparts + 1); parts[nparts].length = (c - str); if (font < lFont) { XftGraphics::textExtents(*font, str, (c - str), extends); parts[nparts].font = *font; parts[nparts].width = extends.xOff; } else { parts[nparts].font = NULL; parts[nparts].width = 0; warn("glyph not found: %d", *(c - 1)); } return parts; } else font = probe; } } TextPart *parts = new TextPart[nparts + 2]; parts[nparts + 1].font = NULL; parts[nparts + 1].width = 0; parts[nparts + 1].length = 0; parts[nparts].length = (c - str); if (NULL != font && font < lFont) { XftGraphics::textExtents(*font, str, (c - str), extends); parts[nparts].font = *font; parts[nparts].width = extends.xOff; } else { parts[nparts].font = NULL; parts[nparts].width = 0; } return parts; } YFont *getXftFont(const char *name) { return new YXftFont(name); } #endif // CONFIG_XFREETYPE <commit_msg>add the fallback font for xft<commit_after>#include "config.h" #ifdef CONFIG_XFREETYPE #include "ypaint.h" #include "yapp.h" #include "ystring.h" #include "intl.h" /******************************************************************************/ class YXftFont : public YFont { public: #ifdef CONFIG_I18N typedef class YUnicodeString string_t; typedef XftChar32 char_t; #else typedef class YLocaleString string_t; typedef XftChar8 char_t; #endif YXftFont(char const * name); virtual ~YXftFont(); virtual operator bool() const { return (fFontCount > 0); } virtual int descent() const { return fDescent; } virtual int ascent() const { return fAscent; } virtual int textWidth(char const * str, int len) const; virtual int textWidth(string_t const & str) const; virtual void drawGlyphs(class Graphics & graphics, int x, int y, char const * str, int len); private: struct TextPart { XftFont * font; size_t length; unsigned width; }; TextPart * partitions(char_t * str, size_t len, size_t nparts = 0) const; unsigned fFontCount, fAscent, fDescent; XftFont ** fFonts; }; class XftGraphics { public: #ifdef CONFIG_I18N typedef XftChar32 char_t; #define XftDrawString XftDrawString32 #define XftTextExtents XftTextExtents32 #else typedef XftChar8 char_t; #define XftTextExtents XftTextExtents8 #define XftDrawString XftDrawString8 #endif XftGraphics(Graphics const & graphics, Visual * visual, Colormap colormap): fDraw(XftDrawCreate(graphics.display(), graphics.drawable(), visual, colormap)) {} ~XftGraphics() { if (fDraw) XftDrawDestroy(fDraw); } void drawRect(XftColor * color, int x, int y, unsigned w, unsigned h) { XftDrawRect(fDraw, color, x, y, w, h); } void drawString(XftColor * color, XftFont * font, int x, int y, char_t * str, size_t len) { XftDrawString(fDraw, color, font, x, y, str, len); } static void textExtents(XftFont * font, char_t * str, size_t len, XGlyphInfo & extends) { XftTextExtents(app->display (), font, str, len, &extends); } XftDraw * handle() const { return fDraw; } private: XftDraw * fDraw; }; /******************************************************************************/ YXftFont::YXftFont(const char *name): fFontCount(strtoken(name, ",")), fAscent(0), fDescent(0) { XftFont ** fptr(fFonts = new XftFont* [fFontCount]); for (char const *s(name); '\0' != *s; s = strnxt(s, ",")) { XftFont *& font(*fptr); char * xlfd(newstr(s + strspn(s, " \t\r\n"), ",")); char * endptr(xlfd + strlen(xlfd) - 1); while (endptr > xlfd && strchr(" \t\r\n", *endptr)) --endptr; endptr[1] = '\0'; font = XftFontOpenXlfd(app->display(), app->screen(), xlfd); if (NULL != font) { fAscent = max(fAscent, (unsigned) max(0, font->ascent)); fDescent = max(fDescent, (unsigned) max(0, font->descent)); ++fptr; } else { warn(_("Could not load font \"%s\"."), xlfd); --fFontCount; } #if 0 if (strstr(xlfd, "koi") != 0) { msg("font %s", xlfd); for (int c = 0; c < 0x500; c++) { if ((c % 64) == 0) { printf("\n%04X ", c); } int ok = XftGlyphExists(app->display(), font, c); printf("%c", ok ? 'X' : '.'); if ((c % 8) == 7) printf(" "); } printf("\n"); } #endif delete[] xlfd; } if (0 == fFontCount) { XftFont * sans(XftFontOpen(app->display(), app->screen(), XFT_FAMILY, XftTypeString, "sans", XFT_WEIGHT, XftTypeInteger, XFT_WEIGHT_MEDIUM, XFT_SLANT, XftTypeInteger, XFT_SLANT_ROMAN, XFT_PIXEL_SIZE, XftTypeInteger, 10, 0)); if (NULL != sans) { delete[] fFonts; fFontCount = 1; fFonts = new XftFont* [fFontCount]; fFonts[0] = sans; fAscent = sans->ascent; fDescent = sans->descent; } else warn(_("Loading of fallback font \"%s\" failed."), "sans"); } } YXftFont::~YXftFont() { for (unsigned n(0); n < fFontCount; ++n) XftFontClose(app->display(), fFonts[n]); delete[] fFonts; } int YXftFont::textWidth(string_t const & text) const { char_t * str((char_t *) text.data()); size_t len(text.length()); TextPart *parts = partitions(str, len); unsigned width(0); for (TextPart * p = parts; p && p->length; ++p) width+= p->width; delete[] parts; return width; } int YXftFont::textWidth(char const * str, int len) const { return textWidth(string_t(str, len)); } void YXftFont::drawGlyphs(Graphics & graphics, int x, int y, char const * str, int len) { string_t xtext(str, len); if (0 == xtext.length()) return; int const y0(y - ascent()); int const gcFn(graphics.function()); char_t * xstr((char_t *) xtext.data()); size_t xlen(xtext.length()); TextPart *parts = partitions(xstr, xlen); unsigned w(0); unsigned const h(height()); for (TextPart *p = parts; p && p->length; ++p) w+= p->width; YPixmap *pixmap = new YPixmap(w, h); Graphics canvas(*pixmap); XftGraphics textarea(canvas, app->visual(), app->colormap()); switch (gcFn) { case GXxor: textarea.drawRect(*YColor::black, 0, 0, w, h); break; case GXcopy: canvas.copyDrawable(graphics.drawable(), x, y0, w, h, 0, 0); break; } int xpos(0); for (TextPart *p = parts; p && p->length; ++p) { if (p->font) textarea.drawString(*graphics.color(), p->font, xpos, ascent(), xstr, p->length); xstr+= p->length; xpos+= p->width; } delete[] parts; graphics.copyDrawable(canvas.drawable(), 0, 0, w, h, x, y0); delete pixmap; } YXftFont::TextPart * YXftFont::partitions(char_t * str, size_t len, size_t nparts) const { XGlyphInfo extends; XftFont ** lFont(fFonts + fFontCount); XftFont ** font(NULL); char_t * c(str); for (char_t * endptr(str + len); c < endptr; ++c) { XftFont ** probe(fFonts); while (probe < lFont && !XftGlyphExists(app->display(), *probe, *c)) ++probe; if (probe != font) { if (NULL != font) { TextPart *parts = partitions(c, len - (c - str), nparts + 1); parts[nparts].length = (c - str); if (font < lFont) { XftGraphics::textExtents(*font, str, (c - str), extends); parts[nparts].font = *font; parts[nparts].width = extends.xOff; } else { parts[nparts].font = NULL; parts[nparts].width = 0; warn("glyph not found: %d", *(c - 1)); } return parts; } else font = probe; } } TextPart *parts = new TextPart[nparts + 2]; parts[nparts + 1].font = NULL; parts[nparts + 1].width = 0; parts[nparts + 1].length = 0; parts[nparts].length = (c - str); if (NULL != font && font < lFont) { XftGraphics::textExtents(*font, str, (c - str), extends); parts[nparts].font = *font; parts[nparts].width = extends.xOff; } else { parts[nparts].font = NULL; parts[nparts].width = 0; } return parts; } YFont *getXftFont(const char *name) { YFont *font = new YXftFont(name); if (font) return font; else return new YXftFont("sans-serif"); } #endif // CONFIG_XFREETYPE <|endoftext|>
<commit_before>/* Copyright 2013 SINTEF ICT, Applied Mathematics. */ #include "EquelleRuntimeCUDA.hpp" #include "CollOfScalar.hpp" #include "DeviceGrid.hpp" #include "CollOfIndices.hpp" #include "CollOfVector.hpp" #include "wrapEquelleRuntime.hpp" #include "LinearSolver.hpp" #include <opm/core/utility/ErrorMacros.hpp> #include <opm/core/utility/StopWatch.hpp> #include <iomanip> #include <fstream> #include <iterator> #include <stdexcept> #include <set> using namespace equelleCUDA; using namespace wrapEquelleRuntimeCUDA; namespace { Opm::GridManager* createGridManager(const Opm::parameter::ParameterGroup& param) { if (param.has("grid_filename")) { // Unstructured grid return new Opm::GridManager(param.get<std::string>("grid_filename")); } // Otherwise: Cartesian grid const int grid_dim = param.getDefault("grid_dim", 2); int num[3] = { 6, 1, 1 }; double size[3] = { 1.0, 1.0, 1.0 }; switch (grid_dim) { // Fall-throughs are intentional in this case 3: num[2] = param.getDefault("nz", num[2]); size[2] = param.getDefault("dz", size[2]); case 2: num[1] = param.getDefault("ny", num[1]); size[1] = param.getDefault("dy", size[1]); num[0] = param.getDefault("nx", num[0]); size[0] = param.getDefault("dx", size[0]); break; default: OPM_THROW(std::runtime_error, "Cannot handle " << grid_dim << " dimensions."); } switch (grid_dim) { case 2: return new Opm::GridManager(num[0], num[1], size[0], size[1]); case 3: return new Opm::GridManager(num[0], num[1], num[2], size[0], size[1], size[2]); default: OPM_THROW(std::runtime_error, "Cannot handle " << grid_dim << " dimensions."); } } } // anonymous namespace EquelleRuntimeCUDA::EquelleRuntimeCUDA(const Opm::parameter::ParameterGroup& param) : grid_manager_(createGridManager(param)), grid_(*(grid_manager_->c_grid())), dev_grid_(grid_), devOps_(grid_), solver_(param.getDefault<std::string>("solver", "BiCGStab"), param.getDefault<std::string>("preconditioner", "diagonal"), param.getDefault("solver_max_iter", 1000), param.getDefault("solver_tol", 1e-10)), serialSolver_(param), output_to_file_(param.getDefault("output_to_file", false)), verbose_(param.getDefault("verbose", 0)), param_(param), max_iter_(param.getDefault("max_iter", 10)), abs_res_tol_(param.getDefault("abs_res_tol", 1e-6)) { wrapEquelleRuntimeCUDA::init_cusparse(); } // Destructor: EquelleRuntimeCUDA::~EquelleRuntimeCUDA() { wrapEquelleRuntimeCUDA::destroy_cusparse(); } CollOfCell EquelleRuntimeCUDA::allCells() const { return dev_grid_.allCells(); } CollOfCell EquelleRuntimeCUDA::boundaryCells() const { return dev_grid_.boundaryCells(); } CollOfCell EquelleRuntimeCUDA::interiorCells() const { return dev_grid_.interiorCells(); } CollOfFace EquelleRuntimeCUDA::allFaces() const { return dev_grid_.allFaces(); } CollOfFace EquelleRuntimeCUDA::boundaryFaces() const { return dev_grid_.boundaryFaces(); } CollOfFace EquelleRuntimeCUDA::interiorFaces() const { return dev_grid_.interiorFaces(); } CollOfCell EquelleRuntimeCUDA::firstCell(CollOfFace faces) const { return dev_grid_.firstCell(faces); } CollOfCell EquelleRuntimeCUDA::secondCell(CollOfFace faces) const { return dev_grid_.secondCell(faces); } CollOfScalar EquelleRuntimeCUDA::norm(const CollOfVector& vectors) const { return vectors.norm(); } CollOfVector EquelleRuntimeCUDA::normal(const CollOfFace& faces) const { return dev_grid_.normal(faces); } CollOfScalar EquelleRuntimeCUDA::dot( const CollOfVector& v1, const CollOfVector& v2 ) const { return v1.dot(v2); } Scalar EquelleRuntimeCUDA::twoNorm(const CollOfScalar& vals) const { return std::sqrt( sumReduce(vals*vals) ); // This should be implemented without having to multiply matrices. } void EquelleRuntimeCUDA::output(const String& tag, const double val) const { std::cout << tag << " = " << val << std::endl; } SeqOfScalar EquelleRuntimeCUDA::inputSequenceOfScalar(const String& name) { const String filename = param_.get<String>(name + "_filename"); std::ifstream is(filename.c_str()); if (!is) { OPM_THROW(std::runtime_error, "Could not find file " << filename); } std::istream_iterator<Scalar> beg(is); std::istream_iterator<Scalar> end; SeqOfScalar data(beg, end); return data; } void EquelleRuntimeCUDA::ensureGridDimensionMin(const int minimum_grid_dimension) const { if (grid_.dimensions < minimum_grid_dimension) { OPM_THROW(std::runtime_error, "Equelle simulator requires minimum " << minimum_grid_dimension << " dimensions, but grid only has " << grid_.dimensions << " dimensions."); } } // HAVAHOL: added function for doing testing UnstructuredGrid EquelleRuntimeCUDA::getGrid() const { return grid_; } void EquelleRuntimeCUDA::output(const String& tag, const CollOfScalar& coll) { // Get data back to host std::vector<double> host = coll.copyToHost(); if (output_to_file_) { // std::map<std::string, int> outputcount_; // set file name to tag-0000X.output int count = -1; auto it = outputcount_.find(tag); if ( it == outputcount_.end()) { count = 0; outputcount_[tag] = 1; // should contain the count to be used next time for same tag. } else { count = outputcount_[tag]; ++outputcount_[tag]; } std::ostringstream fname; fname << tag << "-" << std::setw(5) << std::setfill('0') << count << ".output"; std::ofstream file(fname.str().c_str()); if( !file ) { OPM_THROW(std::runtime_error, "Failed to open " << fname.str()); } file.precision(16); std::copy(host.data(), host.data() + host.size(), std::ostream_iterator<double>(file, "\n")); } else { std::cout << "\n"; std::cout << "Values in " << tag << std::endl; for(int i = 0; i < coll.size(); ++i) { std::cout << host[i] << " "; } std::cout << std::endl; } } Scalar EquelleRuntimeCUDA::inputScalarWithDefault(const String& name, const Scalar default_value) { return param_.getDefault(name, default_value); } CollOfScalar EquelleRuntimeCUDA::trinaryIf( const CollOfBool& predicate, const CollOfScalar& iftrue, const CollOfScalar& iffalse) const { // First, we need same size of all input if (iftrue.size() != iffalse.size() || iftrue.size() != predicate.size()) { OPM_THROW(std::runtime_error, "Collections are not of the same size"); } // Call a wrapper which calls a kernel return trinaryIfWrapper(predicate, iftrue, iffalse); } CollOfScalar EquelleRuntimeCUDA::gradient( const CollOfScalar& cell_scalarfield ) const { // This function is at the moment kept in order to be able to compare efficiency // against the new implementation, where we use the matrix from devOps_. // First, need cell_scalarfield to be defined on all cells: if ( cell_scalarfield.size() != dev_grid_.number_of_cells() ) { OPM_THROW(std::runtime_error, "Gradient need input defined on AllCells()"); } return gradientWrapper(cell_scalarfield, dev_grid_.interiorFaces(), dev_grid_.face_cells(), devOps_); } CollOfScalar EquelleRuntimeCUDA::gradient_matrix( const CollOfScalar& cell_scalarfield ) const { if ( cell_scalarfield.size() != dev_grid_.number_of_cells() ) { OPM_THROW(std::runtime_error, "Gradient need input defined on AllCells()"); } return devOps_.grad() * cell_scalarfield; } CollOfScalar EquelleRuntimeCUDA::divergence(const CollOfScalar& face_fluxes) const { // If the size is not the same as the number of faces, then the input is // given as interiorFaces. Then it has to be extended to AllFaces. if ( face_fluxes.size() != dev_grid_.number_of_faces() ) { CollOfFace int_faces = interiorFaces(); // Extend to AllFaces(): CollOfScalar allFluxes = operatorExtend(face_fluxes, int_faces, allFaces()); return divergenceWrapper(allFluxes, dev_grid_, devOps_); } else { // We are on allFaces already, so let's go! return divergenceWrapper(face_fluxes, dev_grid_, devOps_); } } CollOfScalar EquelleRuntimeCUDA::divergence_matrix(const CollOfScalar& face_fluxes) const { // The input need to be defined on allFaces() or interiorFaces() if ( face_fluxes.size() != dev_grid_.number_of_faces() && face_fluxes.size() != devOps_.num_int_faces() ) { OPM_THROW(std::runtime_error, "Input for divergence has to be on AllFaces or on InteriorFaces()"); } if ( face_fluxes.size() == dev_grid_.number_of_faces() ) { // All faces return devOps_.fulldiv() * face_fluxes; } else { // on internal faces return devOps_.div() * face_fluxes; } } CollOfScalar EquelleRuntimeCUDA::negGradient(const CollOfScalar& cell_scalarField) const { OPM_THROW(std::runtime_error, "Not yet implemented..."); } CollOfScalar EquelleRuntimeCUDA::interiorDivergence(const CollOfScalar& face_fluxes) const { OPM_THROW(std::runtime_error, "Not yet implemented..."); } // SQRT CollOfScalar EquelleRuntimeCUDA::sqrt(const CollOfScalar& x) const { return sqrtWrapper(x); } // ------------- REDUCTIONS -------------- Scalar EquelleRuntimeCUDA::minReduce(const CollOfScalar& x) const { return x.reduce(MIN); } Scalar EquelleRuntimeCUDA::maxReduce(const CollOfScalar& x) const { return x.reduce(MAX); } Scalar EquelleRuntimeCUDA::sumReduce(const CollOfScalar& x) const { return x.reduce(SUM); } Scalar EquelleRuntimeCUDA::prodReduce(const CollOfScalar& x) const { return x.reduce(PRODUCT); } // -------------- END REDUCTIONS ---------------- // Serial solver: CollOfScalar EquelleRuntimeCUDA::serialSolveForUpdate(const CollOfScalar& residual) const { // Want to solve A*x=b, where A is residual.der, b = residual.val hostMat hostA = residual.derivative().toHost(); std::vector<double> hostb = residual.value().copyToHost(); std::vector<double> hostX(hostb.size(), 0.0); Opm::LinearSolverInterface::LinearSolverReport rep = serialSolver_.solve(hostA.rows, hostA.nnz, &hostA.rowPtr[0], &hostA.colInd[0], &hostA.vals[0], &hostb[0], &hostX[0]); if (!rep.converged) { OPM_THROW(std::runtime_error, "Serial linear solver failed to converge."); } return CollOfScalar(hostX); } // Array Of {X} Collection Of Scalar std::array<CollOfScalar, 1> equelleCUDA::makeArray( const CollOfScalar& t ) { return std::array<CollOfScalar, 1> {{t}}; } std::array<CollOfScalar, 2> equelleCUDA::makeArray( const CollOfScalar& t1, const CollOfScalar& t2 ) { return std::array<CollOfScalar, 2> {{t1, t2}}; } std::array<CollOfScalar, 3> equelleCUDA::makeArray( const CollOfScalar& t1, const CollOfScalar& t2, const CollOfScalar& t3 ) { return std::array<CollOfScalar, 3> {{t1, t2, t3}}; } std::array<CollOfScalar, 4> equelleCUDA::makeArray( const CollOfScalar& t1, const CollOfScalar& t2, const CollOfScalar& t3, const CollOfScalar& t4 ) { return std::array<CollOfScalar, 4> {{t1, t2, t3, t4}}; } <commit_msg>Changed default accuracy for linear solver<commit_after>/* Copyright 2013 SINTEF ICT, Applied Mathematics. */ #include "EquelleRuntimeCUDA.hpp" #include "CollOfScalar.hpp" #include "DeviceGrid.hpp" #include "CollOfIndices.hpp" #include "CollOfVector.hpp" #include "wrapEquelleRuntime.hpp" #include "LinearSolver.hpp" #include <opm/core/utility/ErrorMacros.hpp> #include <opm/core/utility/StopWatch.hpp> #include <iomanip> #include <fstream> #include <iterator> #include <stdexcept> #include <set> using namespace equelleCUDA; using namespace wrapEquelleRuntimeCUDA; namespace { Opm::GridManager* createGridManager(const Opm::parameter::ParameterGroup& param) { if (param.has("grid_filename")) { // Unstructured grid return new Opm::GridManager(param.get<std::string>("grid_filename")); } // Otherwise: Cartesian grid const int grid_dim = param.getDefault("grid_dim", 2); int num[3] = { 6, 1, 1 }; double size[3] = { 1.0, 1.0, 1.0 }; switch (grid_dim) { // Fall-throughs are intentional in this case 3: num[2] = param.getDefault("nz", num[2]); size[2] = param.getDefault("dz", size[2]); case 2: num[1] = param.getDefault("ny", num[1]); size[1] = param.getDefault("dy", size[1]); num[0] = param.getDefault("nx", num[0]); size[0] = param.getDefault("dx", size[0]); break; default: OPM_THROW(std::runtime_error, "Cannot handle " << grid_dim << " dimensions."); } switch (grid_dim) { case 2: return new Opm::GridManager(num[0], num[1], size[0], size[1]); case 3: return new Opm::GridManager(num[0], num[1], num[2], size[0], size[1], size[2]); default: OPM_THROW(std::runtime_error, "Cannot handle " << grid_dim << " dimensions."); } } } // anonymous namespace EquelleRuntimeCUDA::EquelleRuntimeCUDA(const Opm::parameter::ParameterGroup& param) : grid_manager_(createGridManager(param)), grid_(*(grid_manager_->c_grid())), dev_grid_(grid_), devOps_(grid_), solver_(param.getDefault<std::string>("solver", "BiCGStab"), param.getDefault<std::string>("preconditioner", "diagonal"), param.getDefault("solver_max_iter", 1000), param.getDefault("solver_tol", 1e-8)), serialSolver_(param), output_to_file_(param.getDefault("output_to_file", false)), verbose_(param.getDefault("verbose", 0)), param_(param), max_iter_(param.getDefault("max_iter", 10)), abs_res_tol_(param.getDefault("abs_res_tol", 1e-6)) { wrapEquelleRuntimeCUDA::init_cusparse(); } // Destructor: EquelleRuntimeCUDA::~EquelleRuntimeCUDA() { wrapEquelleRuntimeCUDA::destroy_cusparse(); } CollOfCell EquelleRuntimeCUDA::allCells() const { return dev_grid_.allCells(); } CollOfCell EquelleRuntimeCUDA::boundaryCells() const { return dev_grid_.boundaryCells(); } CollOfCell EquelleRuntimeCUDA::interiorCells() const { return dev_grid_.interiorCells(); } CollOfFace EquelleRuntimeCUDA::allFaces() const { return dev_grid_.allFaces(); } CollOfFace EquelleRuntimeCUDA::boundaryFaces() const { return dev_grid_.boundaryFaces(); } CollOfFace EquelleRuntimeCUDA::interiorFaces() const { return dev_grid_.interiorFaces(); } CollOfCell EquelleRuntimeCUDA::firstCell(CollOfFace faces) const { return dev_grid_.firstCell(faces); } CollOfCell EquelleRuntimeCUDA::secondCell(CollOfFace faces) const { return dev_grid_.secondCell(faces); } CollOfScalar EquelleRuntimeCUDA::norm(const CollOfVector& vectors) const { return vectors.norm(); } CollOfVector EquelleRuntimeCUDA::normal(const CollOfFace& faces) const { return dev_grid_.normal(faces); } CollOfScalar EquelleRuntimeCUDA::dot( const CollOfVector& v1, const CollOfVector& v2 ) const { return v1.dot(v2); } Scalar EquelleRuntimeCUDA::twoNorm(const CollOfScalar& vals) const { return std::sqrt( sumReduce(vals*vals) ); // This should be implemented without having to multiply matrices. } void EquelleRuntimeCUDA::output(const String& tag, const double val) const { std::cout << tag << " = " << val << std::endl; } SeqOfScalar EquelleRuntimeCUDA::inputSequenceOfScalar(const String& name) { const String filename = param_.get<String>(name + "_filename"); std::ifstream is(filename.c_str()); if (!is) { OPM_THROW(std::runtime_error, "Could not find file " << filename); } std::istream_iterator<Scalar> beg(is); std::istream_iterator<Scalar> end; SeqOfScalar data(beg, end); return data; } void EquelleRuntimeCUDA::ensureGridDimensionMin(const int minimum_grid_dimension) const { if (grid_.dimensions < minimum_grid_dimension) { OPM_THROW(std::runtime_error, "Equelle simulator requires minimum " << minimum_grid_dimension << " dimensions, but grid only has " << grid_.dimensions << " dimensions."); } } // HAVAHOL: added function for doing testing UnstructuredGrid EquelleRuntimeCUDA::getGrid() const { return grid_; } void EquelleRuntimeCUDA::output(const String& tag, const CollOfScalar& coll) { // Get data back to host std::vector<double> host = coll.copyToHost(); if (output_to_file_) { // std::map<std::string, int> outputcount_; // set file name to tag-0000X.output int count = -1; auto it = outputcount_.find(tag); if ( it == outputcount_.end()) { count = 0; outputcount_[tag] = 1; // should contain the count to be used next time for same tag. } else { count = outputcount_[tag]; ++outputcount_[tag]; } std::ostringstream fname; fname << tag << "-" << std::setw(5) << std::setfill('0') << count << ".output"; std::ofstream file(fname.str().c_str()); if( !file ) { OPM_THROW(std::runtime_error, "Failed to open " << fname.str()); } file.precision(16); std::copy(host.data(), host.data() + host.size(), std::ostream_iterator<double>(file, "\n")); } else { std::cout << "\n"; std::cout << "Values in " << tag << std::endl; for(int i = 0; i < coll.size(); ++i) { std::cout << host[i] << " "; } std::cout << std::endl; } } Scalar EquelleRuntimeCUDA::inputScalarWithDefault(const String& name, const Scalar default_value) { return param_.getDefault(name, default_value); } CollOfScalar EquelleRuntimeCUDA::trinaryIf( const CollOfBool& predicate, const CollOfScalar& iftrue, const CollOfScalar& iffalse) const { // First, we need same size of all input if (iftrue.size() != iffalse.size() || iftrue.size() != predicate.size()) { OPM_THROW(std::runtime_error, "Collections are not of the same size"); } // Call a wrapper which calls a kernel return trinaryIfWrapper(predicate, iftrue, iffalse); } CollOfScalar EquelleRuntimeCUDA::gradient( const CollOfScalar& cell_scalarfield ) const { // This function is at the moment kept in order to be able to compare efficiency // against the new implementation, where we use the matrix from devOps_. // First, need cell_scalarfield to be defined on all cells: if ( cell_scalarfield.size() != dev_grid_.number_of_cells() ) { OPM_THROW(std::runtime_error, "Gradient need input defined on AllCells()"); } return gradientWrapper(cell_scalarfield, dev_grid_.interiorFaces(), dev_grid_.face_cells(), devOps_); } CollOfScalar EquelleRuntimeCUDA::gradient_matrix( const CollOfScalar& cell_scalarfield ) const { if ( cell_scalarfield.size() != dev_grid_.number_of_cells() ) { OPM_THROW(std::runtime_error, "Gradient need input defined on AllCells()"); } return devOps_.grad() * cell_scalarfield; } CollOfScalar EquelleRuntimeCUDA::divergence(const CollOfScalar& face_fluxes) const { // If the size is not the same as the number of faces, then the input is // given as interiorFaces. Then it has to be extended to AllFaces. if ( face_fluxes.size() != dev_grid_.number_of_faces() ) { CollOfFace int_faces = interiorFaces(); // Extend to AllFaces(): CollOfScalar allFluxes = operatorExtend(face_fluxes, int_faces, allFaces()); return divergenceWrapper(allFluxes, dev_grid_, devOps_); } else { // We are on allFaces already, so let's go! return divergenceWrapper(face_fluxes, dev_grid_, devOps_); } } CollOfScalar EquelleRuntimeCUDA::divergence_matrix(const CollOfScalar& face_fluxes) const { // The input need to be defined on allFaces() or interiorFaces() if ( face_fluxes.size() != dev_grid_.number_of_faces() && face_fluxes.size() != devOps_.num_int_faces() ) { OPM_THROW(std::runtime_error, "Input for divergence has to be on AllFaces or on InteriorFaces()"); } if ( face_fluxes.size() == dev_grid_.number_of_faces() ) { // All faces return devOps_.fulldiv() * face_fluxes; } else { // on internal faces return devOps_.div() * face_fluxes; } } CollOfScalar EquelleRuntimeCUDA::negGradient(const CollOfScalar& cell_scalarField) const { OPM_THROW(std::runtime_error, "Not yet implemented..."); } CollOfScalar EquelleRuntimeCUDA::interiorDivergence(const CollOfScalar& face_fluxes) const { OPM_THROW(std::runtime_error, "Not yet implemented..."); } // SQRT CollOfScalar EquelleRuntimeCUDA::sqrt(const CollOfScalar& x) const { return sqrtWrapper(x); } // ------------- REDUCTIONS -------------- Scalar EquelleRuntimeCUDA::minReduce(const CollOfScalar& x) const { return x.reduce(MIN); } Scalar EquelleRuntimeCUDA::maxReduce(const CollOfScalar& x) const { return x.reduce(MAX); } Scalar EquelleRuntimeCUDA::sumReduce(const CollOfScalar& x) const { return x.reduce(SUM); } Scalar EquelleRuntimeCUDA::prodReduce(const CollOfScalar& x) const { return x.reduce(PRODUCT); } // -------------- END REDUCTIONS ---------------- // Serial solver: CollOfScalar EquelleRuntimeCUDA::serialSolveForUpdate(const CollOfScalar& residual) const { // Want to solve A*x=b, where A is residual.der, b = residual.val hostMat hostA = residual.derivative().toHost(); std::vector<double> hostb = residual.value().copyToHost(); std::vector<double> hostX(hostb.size(), 0.0); Opm::LinearSolverInterface::LinearSolverReport rep = serialSolver_.solve(hostA.rows, hostA.nnz, &hostA.rowPtr[0], &hostA.colInd[0], &hostA.vals[0], &hostb[0], &hostX[0]); if (!rep.converged) { OPM_THROW(std::runtime_error, "Serial linear solver failed to converge."); } return CollOfScalar(hostX); } // Array Of {X} Collection Of Scalar std::array<CollOfScalar, 1> equelleCUDA::makeArray( const CollOfScalar& t ) { return std::array<CollOfScalar, 1> {{t}}; } std::array<CollOfScalar, 2> equelleCUDA::makeArray( const CollOfScalar& t1, const CollOfScalar& t2 ) { return std::array<CollOfScalar, 2> {{t1, t2}}; } std::array<CollOfScalar, 3> equelleCUDA::makeArray( const CollOfScalar& t1, const CollOfScalar& t2, const CollOfScalar& t3 ) { return std::array<CollOfScalar, 3> {{t1, t2, t3}}; } std::array<CollOfScalar, 4> equelleCUDA::makeArray( const CollOfScalar& t1, const CollOfScalar& t2, const CollOfScalar& t3, const CollOfScalar& t4 ) { return std::array<CollOfScalar, 4> {{t1, t2, t3, t4}}; } <|endoftext|>
<commit_before>/* * Copyright 2006-2008 The FLWOR Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <string> #include <zorba/zorba.h> #include <zorba/store_manager.h> #include "compiler/parsetree/parsenodes.h" #include "parsertestdriverconfig.h" // SRC and BIN dir definitions #include "compiler/parser/xquery_driver.h" #include "compiler/api/compilercb.h" #include "context/static_context.h" using namespace zorba; int #ifdef _WIN32_WCE _tmain(int argc, _TCHAR* argv[]) #else main(int argc, char** argv) #endif { int status = 0; Zorba* lZorba = Zorba::getInstance(zorba::StoreManager::getStore()); std::string lQueryFileString; error::ErrorManager* errormgr = NULL; std::map<short, static_context_t> lSctxMap; CompilerCB aCompilerCB(lSctxMap, errormgr); xquery_driver lDriver(&aCompilerCB); // do initial stuff if ( argc == 2 ) { lQueryFileString = zorba::PARSER_TEST_SRC_DIR +"/Queries/" + argv[1]; std::string lQueryWithoutSuffix = std::string(argv[1]).substr( 0, std::string(argv[1]).size()-3 ); std::cout << "parsertest " << lQueryWithoutSuffix << std::endl; } else { std::cerr << std::endl << "usage: parsertestdriver [testfile]" << std::endl; status = 1; } if (!status) { // TODO correct Exception handling with try-catch try { lDriver.parse_file(lQueryFileString.c_str()); } catch (...) { assert(false); } } if (!status) { parsenode* lNode = lDriver.get_expr(); if (typeid (*lNode) == typeid (ParseErrorNode)) { ParseErrorNode *err = static_cast<ParseErrorNode *> (&*lNode); std::cerr << "Query parsed but no parsenode root generated!" << std::endl; std::cerr << err->msg << std::endl; status = 3; } } lZorba->shutdown(); return status; } <commit_msg>Implemented time sharing in the parsetestdriver<commit_after>/* * Copyright 2006-2008 The FLWOR Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <string> #include <vector> #ifdef WIN32 #include <windows.h> #else #include <sys/time.h> #endif #include <zorba/zorba.h> #include <zorba/store_manager.h> #include "compiler/parsetree/parsenodes.h" #include "parsertestdriverconfig.h" // SRC and BIN dir definitions #include "compiler/parser/xquery_driver.h" #include "compiler/api/compilercb.h" #include "context/static_context.h" using namespace zorba; class Timer { public: Timer(); void start(); void stop(); ulong difference(); private: #ifdef WIN32 typedef FILETIME SysTime_t; #else typedef struct timeval SysTime_t; #endif void setLastToCurrent(); ulong difference(SysTime_t& aBegin, SysTime_t& aEnd) const; SysTime_t getCurrentTime() const; SysTime_t theStartTime; SysTime_t theLastDiffTime; SysTime_t theEndTime; bool theRunning; }; Timer::Timer() :theRunning(false) {} void Timer::start() { theRunning = true; #ifdef WIN32 GetSystemTimeAsFileTime(&theStartTime); GetSystemTimeAsFileTime(&theLastDiffTime); #else gettimeofday(&theStartTime, 0); gettimeofday(&theLastDiffTime, 0); #endif } void Timer::stop() { theRunning = false; #ifdef WIN32 GetSystemTimeAsFileTime(&theEndTime); #else gettimeofday(&theEndTime, 0); #endif } ulong Timer::difference() { ulong lResult; if (theRunning) { SysTime_t lCurrent = getCurrentTime(); lResult = difference(theLastDiffTime, lCurrent); setLastToCurrent(); }else { lResult = difference(theStartTime, theEndTime); } return lResult; } void Timer::setLastToCurrent() { #ifdef WIN32 GetSystemTimeAsFileTime(&theLastDiffTime); #else gettimeofday(&theLastDiffTime, 0); #endif } ulong Timer::difference(SysTime_t& aBegin, SysTime_t& aEnd) const { ulong lResult; #ifdef WIN32 ULARGE_INTEGER lBegin; ULARGE_INTEGER lEnd; lBegin.HighPart = aBegin.dwHighDateTime; lBegin.LowPart = aBegin.dwLowDateTime; lEnd.HighPart = aEnd.dwHighDateTime; lEnd.LowPart = aEnd.dwLowDateTime; ULONGLONG lDiff = lEnd.QuadPart - lBegin.QuadPart; lResult = static_cast<ulong>(lDiff/10000); #else ulong lSeconds = aEnd.tv_sec - aBegin.tv_sec; ulong lMicro = aEnd.tv_usec - aBegin.tv_usec; lResult = 100*lSeconds + lMicro/1000; #endif return lResult; } Timer::SysTime_t Timer::getCurrentTime() const { SysTime_t lTime; #ifdef WIN32 GetSystemTimeAsFileTime(&lTime); #else gettimeofday(&lTime, 0); #endif return lTime; } static void printTime(ulong aMilli) { ulong lMilli = aMilli; ulong lSeconds = lMilli / 1000; lMilli -= lSeconds*1000; ulong lMinutes = lSeconds / 60; lSeconds -= lMinutes*60; ulong lHours = lSeconds / 60; lHours -= lMinutes*60; if (lHours) std::cout << lHours << "h "; if (lMinutes) std::cout << lMinutes << "m "; if (lSeconds) std::cout << lSeconds << "s "; if (lMilli) std::cout << lMilli << "ms "; } void readCommandLine(int argc, std::string &lQueryFileString, char** argv, bool &lTime, unsigned lNumber, int &status) { if ( argc == 2 ) { lQueryFileString = zorba::PARSER_TEST_SRC_DIR +"/Queries/" + argv[1]; std::string lQueryWithoutSuffix = std::string(argv[1]).substr( 0, std::string(argv[1]).size()-3 ); std::cout << "parsertest " << lQueryWithoutSuffix << std::endl; } else if (argc >= 3 && argc <= 6) { for (int lI = 0; lI < argc; ++lI) { std::string lArg(argv[lI]); std::stringstream lStr; if (lArg[0] == '-') { switch (lArg[1]) { case 'f': lQueryFileString = std::string(argv[++lI]); break; case 't': lTime = true; break; case 'n': lStr.str(argv[++lI]); lStr >> lNumber; break; default: std::cerr << std::endl << "usage: parsertestdriver (-f file|testfile) [-t] [-n exectimes]" << std::endl; status = 1; // break out of the loop lI = argc; } } else if (lQueryFileString == "") { lQueryFileString = zorba::PARSER_TEST_SRC_DIR +"/Queries/" + argv[1]; std::string lQueryWithoutSuffix = std::string(argv[1]).substr( 0, std::string(argv[1]).size()-3); std::cout << "parsertest " << lQueryWithoutSuffix << std::endl; } else { std::cerr << std::endl << "usage: parsertestdriver (-f file|testfile) [-t] [-n exectimes]" << std::endl; status = 1; lI = argc; } } } else { std::cerr << std::endl << "usage: parsertestdriver (-f file|testfile) [-t] [-n exectimes]" << std::endl; status = 1; } } void printTimingInfoOfRun( unsigned lI, Timer &lTimer, std::vector<ulong> &lTimes ) { std::cout << "Time consumed for "; switch (lI) { case 0: std::cout << "1st"; break; case 1: std::cout << "2nd"; break; case 2: std::cout << "3rd"; break; default: std::cout << lI + 1 << "th"; } std::cout << " run: "; ulong lDiff = lTimer.difference(); lTimes.push_back(lDiff); printTime(lDiff); std::cout << std::endl; } void printEndTimeInfo( Timer &lTimer, std::vector<ulong> &lTimes, unsigned lNumber ) { lTimer.stop(); std::cout << "Total time: "; printTime(lTimer.difference()); std::cout << std::endl; std::vector<ulong>::iterator lIter; unsigned long lTotal = 0; for (lIter = lTimes.begin(); lIter != lTimes.end(); ++lIter) { lTotal += *lIter; } lTotal /= lNumber; std::cout << "Average run time: "; printTime(lTotal); std::cout << std::endl; } int parseCode( int status, std::string &lQueryFileString ) { error::ErrorManager* errormgr = NULL; std::map<short, static_context_t> lSctxMap; CompilerCB aCompilerCB(lSctxMap, errormgr); xquery_driver lDriver(&aCompilerCB); if (!status) { // TODO correct Exception handling with try-catch try { lDriver.parse_file(lQueryFileString.c_str()); } catch (...) { assert(false); } } if (!status) { parsenode* lNode = lDriver.get_expr(); if (typeid (*lNode) == typeid (ParseErrorNode)) { ParseErrorNode *err = static_cast<ParseErrorNode *> (&*lNode); std::cerr << "Query parsed but no parsenode root generated!" << std::endl; std::cerr << err->msg << std::endl; status = 3; } } return status; } int #ifdef _WIN32_WCE _tmain(int argc, _TCHAR* argv[]) #else main(int argc, char** argv) #endif { int status = 0; bool lTime = false; unsigned lNumber = 1; std::vector<ulong> lTimes; std::string lQueryFileString; Zorba* lZorba = Zorba::getInstance(zorba::StoreManager::getStore()); // do initial stuff readCommandLine(argc, lQueryFileString, argv, lTime, lNumber, status); Timer lTimer; if (lTime) { lTimer.start(); } for (unsigned lI = 0; lI < lNumber; ++lI) { { status = parseCode(status, lQueryFileString); } if (lTime) { printTimingInfoOfRun(lI, lTimer, lTimes); } } lZorba->shutdown(); if (lTime && lNumber != 1) { printEndTimeInfo(lTimer, lTimes, lNumber); } return status; } <|endoftext|>
<commit_before># pragma once # include <Siv3D.hpp> namespace asc { using namespace s3d; class MessageManager { private: Stopwatch m_stopwatch; String m_name; String m_text; uint32 m_charCount; public: MessageManager() : m_charCount(0U) { m_stopwatch.start(); m_stopwatch.pause(); } virtual ~MessageManager() = default; void start() { m_stopwatch.restart(); m_charCount = 0U; } void update() { // ToDo Configurable const int32 m_textSpeed = 100; const int32 m_textWait = 100; if(m_stopwatch.isPaused()) return; // This MessageManager is shown all. if (m_stopwatch.ms() >= static_cast<int>(m_text.length) * m_textSpeed + m_textWait) { if (Input::KeyEnter.clicked || Input::KeyQ.pressed) { m_stopwatch.pause(); } return; } // Skip MessageManager. if (Input::KeyEnter.clicked || Input::KeyQ.pressed) { m_charCount = m_text.length; m_stopwatch.pause(); return; } m_charCount = static_cast<int>(m_stopwatch.ms() / m_textSpeed); } void setName(const String& name) { m_name = name; } void setText(const String& text) { m_text = text; } void draw() const { // ToDo Configurable const Rect m_messageBox(6, 440, 1268, 285); const Point m_namePosition(40, 525); const Point m_textPosition(60, 575); const String m_messageBoxTexture = L"test_message_box"; const String m_nameFont = L"test_name"; const String m_textFont = L"test_text"; const Color m_messageColor = Palette::Black; m_messageBox(TextureAsset(m_messageBoxTexture)).draw(); FontAsset(m_nameFont).draw(m_name, m_namePosition, m_messageColor); FontAsset(m_textFont).draw(m_text.substr(0U, m_charCount), m_textPosition, m_messageColor); } bool isUpdating() const { return !m_stopwatch.isPaused(); } }; } <commit_msg>Specification change: Skip must wait textWait.<commit_after># pragma once # include <Siv3D.hpp> namespace asc { using namespace s3d; class MessageManager { private: Stopwatch m_stopwatch; String m_name; String m_text; uint32 m_charCount; public: MessageManager() : m_charCount(0U) { m_stopwatch.start(); m_stopwatch.pause(); } virtual ~MessageManager() = default; void start() { m_stopwatch.restart(); m_charCount = 0U; } void update() { // ToDo Configurable const int32 m_textSpeed = 100; const int32 m_textWait = 100; if(m_stopwatch.isPaused()) return; const auto typingTime = static_cast<int32>(m_text.length) * m_textSpeed; if (m_stopwatch.ms() >= typingTime) { if (m_stopwatch.ms() >= typingTime + m_textWait && (Input::KeyEnter.clicked || Input::KeyQ.pressed)) { m_stopwatch.pause(); return; } } else if(Input::KeyEnter.clicked || Input::KeyQ.pressed) { m_stopwatch.set(static_cast<Milliseconds>(m_text.length * m_textSpeed)); } m_charCount = static_cast<int>(m_stopwatch.ms() / m_textSpeed); } void setName(const String& name) { m_name = name; } void setText(const String& text) { m_text = text; } void draw() const { // ToDo Configurable const Rect m_messageBox(6, 440, 1268, 285); const Point m_namePosition(40, 525); const Point m_textPosition(60, 575); const String m_messageBoxTexture = L"test_message_box"; const String m_nameFont = L"test_name"; const String m_textFont = L"test_text"; const Color m_messageColor = Palette::Black; m_messageBox(TextureAsset(m_messageBoxTexture)).draw(); FontAsset(m_nameFont).draw(m_name, m_namePosition, m_messageColor); FontAsset(m_textFont).draw(m_text.substr(0U, m_charCount), m_textPosition, m_messageColor); } bool isUpdating() const { return !m_stopwatch.isPaused(); } }; } <|endoftext|>
<commit_before>/** * \file * \brief SignalCatchingOperationsTestCase class implementation * * \author Copyright (C) 2015-2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "SignalCatchingOperationsTestCase.hpp" #include "abortSignalHandler.hpp" #include "distortos/DynamicThread.hpp" #include "distortos/statistics.hpp" #include "distortos/ThisThread-Signals.hpp" #include <cerrno> namespace distortos { namespace test { namespace { /*---------------------------------------------------------------------------------------------------------------------+ | local constants +---------------------------------------------------------------------------------------------------------------------*/ /// size of stack for test threads, bytes constexpr size_t testThreadStackSize {512}; /// expected number of context switches in phase2() block involving thread: 1 - main thread is preempted by test thread /// (main -> test), 2 - test thread terminates (test -> main) constexpr decltype(statistics::getContextSwitchCount()) phase2ThreadContextSwitchCount {2}; /*---------------------------------------------------------------------------------------------------------------------+ | local functions +---------------------------------------------------------------------------------------------------------------------*/ /** * \brief Phase 1 of test case. * * Tests various aspects of setting signal action, aiming for full coverage of execution paths through * SignalsCatcherControlBlock::setAssociation(). Following cases are tested: * - setting identical signal actions for multiple signal numbers must succeed as long as no more than * \a CONFIG_MAIN_THREAD_SIGNAL_ACTIONS different signal actions are used at the same time; * - setting the same signal action as the one that is currently set must always succeed; * - clearing signal action must always succeed; * - trying to change signal action for signal number must fail with EAGAIN if \a CONFIG_MAIN_THREAD_SIGNAL_ACTIONS * different signal actions are already used and the one that is changed is used by multiple signal numbers; * - trying to set new signal action for signal number must fail with EAGAIN when \a CONFIG_MAIN_THREAD_SIGNAL_ACTIONS * different signal actions are already used; * * \return true if test succeeded, false otherwise */ bool phase1() { constexpr size_t mainThreadSignalActions {CONFIG_MAIN_THREAD_SIGNAL_ACTIONS}; // the second to last iteration is used to set the same signal action as in the first iteration // the last iteration is used to set the same signal action as the one that is currently set for (size_t shift {}; shift <= mainThreadSignalActions + 1; ++shift) for (uint8_t signalNumber {}; signalNumber < SignalSet::Bitset{}.size(); ++signalNumber) { // last iteration? clip the value so that it is identical to the one from previous iteration const auto realShift = shift <= mainThreadSignalActions ? shift : mainThreadSignalActions; const SignalSet signalMask {1u << ((realShift + signalNumber) % mainThreadSignalActions)}; const auto setSignalActionResult = ThisThread::Signals::setSignalAction(signalNumber, {abortSignalHandler, signalMask}); if (setSignalActionResult.first != 0) return false; if (shift == 0) // first itertion? previous signal action is equal to default SignalAction { if (setSignalActionResult.second.getHandler() != SignalAction{}.getHandler()) return false; } else // compare returned signal action with the expected one { const SignalSet previousSignalMask {1u << ((shift - 1 + signalNumber) % mainThreadSignalActions)}; if (setSignalActionResult.second.getHandler() != abortSignalHandler || setSignalActionResult.second.getSignalMask().getBitset() != previousSignalMask.getBitset()) return false; } } constexpr uint8_t testSignalNumber {2}; int ret; std::tie(ret, std::ignore) = ThisThread::Signals::setSignalAction(testSignalNumber, {abortSignalHandler, SignalSet{SignalSet::full}}); if (ret != EAGAIN) return false; std::tie(ret, std::ignore) = ThisThread::Signals::setSignalAction(testSignalNumber, {}); if (ret != 0) return false; std::tie(ret, std::ignore) = ThisThread::Signals::setSignalAction(testSignalNumber, {abortSignalHandler, SignalSet{SignalSet::full}}); if (ret != EAGAIN) return false; for (uint8_t signalNumber {}; signalNumber < SignalSet::Bitset{}.size(); ++signalNumber) { std::tie(ret, std::ignore) = ThisThread::Signals::setSignalAction(signalNumber, {}); if (ret != 0) return false; } return true; } /** * \brief Phase 2 of test case. * * Tests various error cases: * - attempt to get/set signal action for invalid signal number must fail with EINVAL; * - attempt to get/set signal action or to set signal mask in a thread that either has disabled reception of signals or * has disabled catching/handling of signals must fail with ENOTSUP; * - signal mask of a thread that either has disabled reception of signals or has disabled catching/handling of signals * must be equal to "full" SignalSet; * * \return true if test succeeded, false otherwise */ bool phase2() { for (auto signalNumber = SignalSet::Bitset{}.size(); signalNumber <= UINT8_MAX; ++signalNumber) { int ret; std::tie(ret, std::ignore) = ThisThread::Signals::getSignalAction(signalNumber); if (ret != EINVAL) return false; std::tie(ret, std::ignore) = ThisThread::Signals::setSignalAction(signalNumber, SignalAction{}); if (ret != EINVAL) return false; } auto testThreadLambda = [](int& getSignalActionRet, SignalSet& signalMask, int& setSignalActionRet, int& setSignalMaskRet) { std::tie(getSignalActionRet, std::ignore) = ThisThread::Signals::getSignalAction({}); signalMask = ThisThread::Signals::getSignalMask(); std::tie(setSignalActionRet, std::ignore) = ThisThread::Signals::setSignalAction({}, SignalAction{}); setSignalMaskRet = ThisThread::Signals::setSignalMask(SignalSet{SignalSet::full}); }; { int getSignalActionRet {}; SignalSet signalMask {SignalSet::empty}; int setSignalActionRet {}; int setSignalMaskRet {}; auto testThread = makeAndStartDynamicThread({testThreadStackSize, false, 0, 0, UINT8_MAX}, testThreadLambda, std::ref(getSignalActionRet), std::ref(signalMask), std::ref(setSignalActionRet), std::ref(setSignalMaskRet)); testThread.join(); if (getSignalActionRet != ENOTSUP) return false; if (signalMask.getBitset() != SignalSet{SignalSet::full}.getBitset()) return false; if (setSignalActionRet != ENOTSUP) return false; if (setSignalMaskRet != ENOTSUP) return false; } { int getSignalActionRet {}; SignalSet signalMask {SignalSet::empty}; int setSignalActionRet {}; int setSignalMaskRet {}; auto testThread = makeAndStartDynamicThread({testThreadStackSize, true, 0, 0, UINT8_MAX}, testThreadLambda, std::ref(getSignalActionRet), std::ref(signalMask), std::ref(setSignalActionRet), std::ref(setSignalMaskRet)); testThread.join(); if (getSignalActionRet != ENOTSUP) return false; if (signalMask.getBitset() != SignalSet{SignalSet::full}.getBitset()) return false; if (setSignalActionRet != ENOTSUP) return false; if (setSignalMaskRet != ENOTSUP) return false; } return true; } } // namespace /*---------------------------------------------------------------------------------------------------------------------+ | private functions +---------------------------------------------------------------------------------------------------------------------*/ bool SignalCatchingOperationsTestCase::run_() const { constexpr auto phase2ExpectedContextSwitchCount = 2 * phase2ThreadContextSwitchCount; constexpr auto expectedContextSwitchCount = phase2ExpectedContextSwitchCount; const auto contextSwitchCount = statistics::getContextSwitchCount(); for (const auto& function : {phase1, phase2}) { // initially no signals may be pending if (ThisThread::Signals::getPendingSignalSet().getBitset().none() == false) return false; if (function() == false) return false; } // after the test no signals may be pending if (ThisThread::Signals::getPendingSignalSet().getBitset().none() == false) return false; if (statistics::getContextSwitchCount() - contextSwitchCount != expectedContextSwitchCount) return false; return true; } } // namespace test } // namespace distortos <commit_msg>test: improve SignalCatchingOperationsTestCase<commit_after>/** * \file * \brief SignalCatchingOperationsTestCase class implementation * * \author Copyright (C) 2015-2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "SignalCatchingOperationsTestCase.hpp" #include "abortSignalHandler.hpp" #include "distortos/DynamicThread.hpp" #include "distortos/statistics.hpp" #include "distortos/ThisThread-Signals.hpp" #include <cerrno> namespace distortos { namespace test { namespace { /*---------------------------------------------------------------------------------------------------------------------+ | local constants +---------------------------------------------------------------------------------------------------------------------*/ /// size of stack for test threads, bytes constexpr size_t testThreadStackSize {512}; /// expected number of context switches in phase2() block involving thread: 1 - main thread is preempted by test thread /// (main -> test), 2 - test thread terminates (test -> main) constexpr decltype(statistics::getContextSwitchCount()) phase2ThreadContextSwitchCount {2}; /*---------------------------------------------------------------------------------------------------------------------+ | local functions +---------------------------------------------------------------------------------------------------------------------*/ /** * \brief Phase 1 of test case. * * Tests various aspects of setting signal action, aiming for full coverage of execution paths through * SignalsCatcherControlBlock::setAssociation(). Following cases are tested: * - setting identical signal actions for multiple signal numbers must succeed as long as no more than * \a CONFIG_MAIN_THREAD_SIGNAL_ACTIONS different signal actions are used at the same time; * - setting the same signal action as the one that is currently set must always succeed; * - clearing signal action must always succeed; * - trying to change signal action for signal number must fail with EAGAIN if \a CONFIG_MAIN_THREAD_SIGNAL_ACTIONS * different signal actions are already used and the one that is changed is used by multiple signal numbers; * - trying to set new signal action for signal number must fail with EAGAIN when \a CONFIG_MAIN_THREAD_SIGNAL_ACTIONS * different signal actions are already used; * * \return true if test succeeded, false otherwise */ bool phase1() { constexpr size_t mainThreadSignalActions {CONFIG_MAIN_THREAD_SIGNAL_ACTIONS}; // the second to last iteration is used to set the same signal action as in the first iteration // the last iteration is used to set the same signal action as the one that is currently set for (size_t mask {}; mask <= mainThreadSignalActions + 1; ++mask) for (uint8_t signalNumber {}; signalNumber < SignalSet::Bitset{}.size(); ++signalNumber) { // last iteration? clip the value so that it is identical to the one from previous iteration const auto realMask = mask <= mainThreadSignalActions ? mask : mainThreadSignalActions; const SignalSet signalMask {((realMask + signalNumber) % mainThreadSignalActions)}; const auto setSignalActionResult = ThisThread::Signals::setSignalAction(signalNumber, {abortSignalHandler, signalMask}); if (setSignalActionResult.first != 0) return false; if (mask == 0) // first iteration? previous signal action is equal to default SignalAction { if (setSignalActionResult.second.getHandler() != SignalAction{}.getHandler()) return false; } else // compare returned signal action with the expected one { const SignalSet previousSignalMask {((mask - 1 + signalNumber) % mainThreadSignalActions)}; if (setSignalActionResult.second.getHandler() != abortSignalHandler || setSignalActionResult.second.getSignalMask().getBitset() != previousSignalMask.getBitset()) return false; } } constexpr uint8_t testSignalNumber {0}; int ret; std::tie(ret, std::ignore) = ThisThread::Signals::setSignalAction(testSignalNumber, {abortSignalHandler, SignalSet{SignalSet::full}}); if (ret != EAGAIN) return false; std::tie(ret, std::ignore) = ThisThread::Signals::setSignalAction(testSignalNumber, {}); if (ret != 0) return false; std::tie(ret, std::ignore) = ThisThread::Signals::setSignalAction(testSignalNumber, {abortSignalHandler, SignalSet{SignalSet::full}}); if (ret != EAGAIN) return false; for (uint8_t signalNumber {}; signalNumber < SignalSet::Bitset{}.size(); ++signalNumber) { std::tie(ret, std::ignore) = ThisThread::Signals::setSignalAction(signalNumber, {}); if (ret != 0) return false; } return true; } /** * \brief Phase 2 of test case. * * Tests various error cases: * - attempt to get/set signal action for invalid signal number must fail with EINVAL; * - attempt to get/set signal action or to set signal mask in a thread that either has disabled reception of signals or * has disabled catching/handling of signals must fail with ENOTSUP; * - signal mask of a thread that either has disabled reception of signals or has disabled catching/handling of signals * must be equal to "full" SignalSet; * * \return true if test succeeded, false otherwise */ bool phase2() { for (auto signalNumber = SignalSet::Bitset{}.size(); signalNumber <= UINT8_MAX; ++signalNumber) { int ret; std::tie(ret, std::ignore) = ThisThread::Signals::getSignalAction(signalNumber); if (ret != EINVAL) return false; std::tie(ret, std::ignore) = ThisThread::Signals::setSignalAction(signalNumber, SignalAction{}); if (ret != EINVAL) return false; } auto testThreadLambda = [](int& getSignalActionRet, SignalSet& signalMask, int& setSignalActionRet, int& setSignalMaskRet) { std::tie(getSignalActionRet, std::ignore) = ThisThread::Signals::getSignalAction({}); signalMask = ThisThread::Signals::getSignalMask(); std::tie(setSignalActionRet, std::ignore) = ThisThread::Signals::setSignalAction({}, SignalAction{}); setSignalMaskRet = ThisThread::Signals::setSignalMask(SignalSet{SignalSet::full}); }; { int getSignalActionRet {}; SignalSet signalMask {SignalSet::empty}; int setSignalActionRet {}; int setSignalMaskRet {}; auto testThread = makeAndStartDynamicThread({testThreadStackSize, false, 0, 0, UINT8_MAX}, testThreadLambda, std::ref(getSignalActionRet), std::ref(signalMask), std::ref(setSignalActionRet), std::ref(setSignalMaskRet)); testThread.join(); if (getSignalActionRet != ENOTSUP) return false; if (signalMask.getBitset() != SignalSet{SignalSet::full}.getBitset()) return false; if (setSignalActionRet != ENOTSUP) return false; if (setSignalMaskRet != ENOTSUP) return false; } { int getSignalActionRet {}; SignalSet signalMask {SignalSet::empty}; int setSignalActionRet {}; int setSignalMaskRet {}; auto testThread = makeAndStartDynamicThread({testThreadStackSize, true, 0, 0, UINT8_MAX}, testThreadLambda, std::ref(getSignalActionRet), std::ref(signalMask), std::ref(setSignalActionRet), std::ref(setSignalMaskRet)); testThread.join(); if (getSignalActionRet != ENOTSUP) return false; if (signalMask.getBitset() != SignalSet{SignalSet::full}.getBitset()) return false; if (setSignalActionRet != ENOTSUP) return false; if (setSignalMaskRet != ENOTSUP) return false; } return true; } } // namespace /*---------------------------------------------------------------------------------------------------------------------+ | private functions +---------------------------------------------------------------------------------------------------------------------*/ bool SignalCatchingOperationsTestCase::run_() const { constexpr auto phase2ExpectedContextSwitchCount = 2 * phase2ThreadContextSwitchCount; constexpr auto expectedContextSwitchCount = phase2ExpectedContextSwitchCount; const auto contextSwitchCount = statistics::getContextSwitchCount(); for (const auto& function : {phase1, phase2}) { // initially no signals may be pending if (ThisThread::Signals::getPendingSignalSet().getBitset().none() == false) return false; if (function() == false) return false; } // after the test no signals may be pending if (ThisThread::Signals::getPendingSignalSet().getBitset().none() == false) return false; if (statistics::getContextSwitchCount() - contextSwitchCount != expectedContextSwitchCount) return false; return true; } } // namespace test } // namespace distortos <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include <chrono> #ifdef _WIN32 #define _WINSOCKAPI_ // to include Winsock2.h instead of Winsock.h from windows.h #include <winsock2.h> #if defined(__GNUC__) || defined(__MINGW32__) extern "C" { WINSOCK_API_LINKAGE INT WSAAPI inet_pton( INT Family, PCSTR pszAddrString, PVOID pAddrBuf); WINSOCK_API_LINKAGE PCSTR WSAAPI inet_ntop(INT Family, PVOID pAddr, PSTR pStringBuf, size_t StringBufSize); } #endif #define INC__WIN_WINTIME // exclude gettimeofday from srt headers #endif #include "srt.h" /** * The test creates a socket and tries to connect to a localhost port 5555 * in a non-blocking mode. This means we wait on epoll for a notification * about SRT_EPOLL_OUT | SRT_EPOLL_ERR events on the socket calling srt_epoll_wait(...). * The test expects a connection timeout to happen within the time, * set with SRTO_CONNTIMEO (500 ms). * The expected behavior is to return from srt_epoll_wait(...) * * @remarks Inspired by Max Tomilov (maxtomilov) in issue #468 */ TEST(Core, ConnectionTimeout) { ASSERT_EQ(srt_startup(), 0); const SRTSOCKET client_sock = srt_socket(AF_INET, SOCK_DGRAM, 0); ASSERT_GT(client_sock, 0); // socket_id should be > 0 // First let's check the default connection timeout value. // It should be 3 seconds (3000 ms) int conn_timeout = 0; int conn_timeout_len = sizeof conn_timeout; EXPECT_EQ(srt_getsockopt(client_sock, 0, SRTO_CONNTIMEO, &conn_timeout, &conn_timeout_len), SRT_SUCCESS); EXPECT_EQ(conn_timeout, 3000); // Set connection timeout to 500 ms to reduce the test execution time const int connection_timeout_ms = 500; EXPECT_EQ(srt_setsockopt(client_sock, 0, SRTO_CONNTIMEO, &connection_timeout_ms, sizeof connection_timeout_ms), SRT_SUCCESS); const int yes = 1; const int no = 0; ASSERT_EQ(srt_setsockopt(client_sock, 0, SRTO_RCVSYN, &no, sizeof no), SRT_SUCCESS); // for async connect ASSERT_EQ(srt_setsockopt(client_sock, 0, SRTO_SNDSYN, &no, sizeof no), SRT_SUCCESS); // for async connect ASSERT_EQ(srt_setsockopt(client_sock, 0, SRTO_TSBPDMODE, &yes, sizeof yes), SRT_SUCCESS); ASSERT_EQ(srt_setsockflag(client_sock, SRTO_SENDER, &yes, sizeof yes), SRT_SUCCESS); const int pollid = srt_epoll_create(); ASSERT_GE(pollid, 0); const int epoll_out = SRT_EPOLL_OUT | SRT_EPOLL_ERR; ASSERT_NE(srt_epoll_add_usock(pollid, client_sock, &epoll_out), SRT_ERROR); sockaddr_in sa; memset(&sa, 0, sizeof sa); sa.sin_family = AF_INET; sa.sin_port = htons(5555); ASSERT_EQ(inet_pton(AF_INET, "127.0.0.1", &sa.sin_addr), 1); sockaddr* psa = (sockaddr*)&sa; ASSERT_NE(srt_connect(client_sock, psa, sizeof sa), SRT_ERROR); // Socket readiness for connection is checked by polling on WRITE allowed sockets. { int rlen = 2; SRTSOCKET read[2]; int wlen = 2; SRTSOCKET write[2]; using namespace std; const chrono::steady_clock::time_point chrono_ts_start = chrono::steady_clock::now(); // Here we check the connection timeout. // Epoll timeout is set 100 ms greater than socket's TTL EXPECT_EQ(srt_epoll_wait(pollid, read, &rlen, write, &wlen, connection_timeout_ms + 100, // +100 ms 0, 0, 0, 0) /* Expected return value is 2. We have only 1 socket, but * sockets with exceptions are returned to both read and write sets. */ , 2); // Check the actual timeout const chrono::steady_clock::time_point chrono_ts_end = chrono::steady_clock::now(); const auto delta_ms = chrono::duration_cast<chrono::milliseconds>(chrono_ts_end - chrono_ts_start).count(); // Confidence interval border : +/-30 ms EXPECT_LT(delta_ms, connection_timeout_ms + 30); EXPECT_GT(delta_ms, connection_timeout_ms - 30); cerr << "Timeout was: " << delta_ms << "\n"; EXPECT_EQ(rlen, 1); EXPECT_EQ(read[0], client_sock); EXPECT_EQ(wlen, 1); EXPECT_EQ(write[0], client_sock); } EXPECT_EQ(srt_epoll_remove_usock(pollid, client_sock), SRT_SUCCESS); EXPECT_EQ(srt_close(client_sock), SRT_SUCCESS); (void)srt_epoll_release(pollid); (void)srt_cleanup(); } <commit_msg>[tests] ConnectionTimeout test. Epoll wait confidence interval increased to +/-50 ms<commit_after>#include <gtest/gtest.h> #include <chrono> #ifdef _WIN32 #define _WINSOCKAPI_ // to include Winsock2.h instead of Winsock.h from windows.h #include <winsock2.h> #if defined(__GNUC__) || defined(__MINGW32__) extern "C" { WINSOCK_API_LINKAGE INT WSAAPI inet_pton( INT Family, PCSTR pszAddrString, PVOID pAddrBuf); WINSOCK_API_LINKAGE PCSTR WSAAPI inet_ntop(INT Family, PVOID pAddr, PSTR pStringBuf, size_t StringBufSize); } #endif #define INC__WIN_WINTIME // exclude gettimeofday from srt headers #endif #include "srt.h" /** * The test creates a socket and tries to connect to a localhost port 5555 * in a non-blocking mode. This means we wait on epoll for a notification * about SRT_EPOLL_OUT | SRT_EPOLL_ERR events on the socket calling srt_epoll_wait(...). * The test expects a connection timeout to happen within the time, * set with SRTO_CONNTIMEO (500 ms). * The expected behavior is to return from srt_epoll_wait(...) * * @remarks Inspired by Max Tomilov (maxtomilov) in issue #468 */ TEST(Core, ConnectionTimeout) { ASSERT_EQ(srt_startup(), 0); const SRTSOCKET client_sock = srt_socket(AF_INET, SOCK_DGRAM, 0); ASSERT_GT(client_sock, 0); // socket_id should be > 0 // First let's check the default connection timeout value. // It should be 3 seconds (3000 ms) int conn_timeout = 0; int conn_timeout_len = sizeof conn_timeout; EXPECT_EQ(srt_getsockopt(client_sock, 0, SRTO_CONNTIMEO, &conn_timeout, &conn_timeout_len), SRT_SUCCESS); EXPECT_EQ(conn_timeout, 3000); // Set connection timeout to 500 ms to reduce the test execution time const int connection_timeout_ms = 500; EXPECT_EQ(srt_setsockopt(client_sock, 0, SRTO_CONNTIMEO, &connection_timeout_ms, sizeof connection_timeout_ms), SRT_SUCCESS); const int yes = 1; const int no = 0; ASSERT_EQ(srt_setsockopt(client_sock, 0, SRTO_RCVSYN, &no, sizeof no), SRT_SUCCESS); // for async connect ASSERT_EQ(srt_setsockopt(client_sock, 0, SRTO_SNDSYN, &no, sizeof no), SRT_SUCCESS); // for async connect ASSERT_EQ(srt_setsockopt(client_sock, 0, SRTO_TSBPDMODE, &yes, sizeof yes), SRT_SUCCESS); ASSERT_EQ(srt_setsockflag(client_sock, SRTO_SENDER, &yes, sizeof yes), SRT_SUCCESS); const int pollid = srt_epoll_create(); ASSERT_GE(pollid, 0); const int epoll_out = SRT_EPOLL_OUT | SRT_EPOLL_ERR; ASSERT_NE(srt_epoll_add_usock(pollid, client_sock, &epoll_out), SRT_ERROR); sockaddr_in sa; memset(&sa, 0, sizeof sa); sa.sin_family = AF_INET; sa.sin_port = htons(5555); ASSERT_EQ(inet_pton(AF_INET, "127.0.0.1", &sa.sin_addr), 1); sockaddr* psa = (sockaddr*)&sa; ASSERT_NE(srt_connect(client_sock, psa, sizeof sa), SRT_ERROR); // Socket readiness for connection is checked by polling on WRITE allowed sockets. { int rlen = 2; SRTSOCKET read[2]; int wlen = 2; SRTSOCKET write[2]; using namespace std; const chrono::steady_clock::time_point chrono_ts_start = chrono::steady_clock::now(); // Here we check the connection timeout. // Epoll timeout is set 100 ms greater than socket's TTL EXPECT_EQ(srt_epoll_wait(pollid, read, &rlen, write, &wlen, connection_timeout_ms + 100, // +100 ms 0, 0, 0, 0) /* Expected return value is 2. We have only 1 socket, but * sockets with exceptions are returned to both read and write sets. */ , 2); // Check the actual timeout const chrono::steady_clock::time_point chrono_ts_end = chrono::steady_clock::now(); const auto delta_ms = chrono::duration_cast<chrono::milliseconds>(chrono_ts_end - chrono_ts_start).count(); // Confidence interval border : +/-50 ms EXPECT_LE(delta_ms, connection_timeout_ms + 50); EXPECT_GE(delta_ms, connection_timeout_ms - 50); cerr << "Timeout was: " << delta_ms << "\n"; EXPECT_EQ(rlen, 1); EXPECT_EQ(read[0], client_sock); EXPECT_EQ(wlen, 1); EXPECT_EQ(write[0], client_sock); } EXPECT_EQ(srt_epoll_remove_usock(pollid, client_sock), SRT_SUCCESS); EXPECT_EQ(srt_close(client_sock), SRT_SUCCESS); (void)srt_epoll_release(pollid); (void)srt_cleanup(); } <|endoftext|>
<commit_before>#include <iostream> #include "time.h" #include <string> #include "novoht.h" #include <cstdlib> #include <cstddef> #include <sys/time.h> //#include "meta.pb.h" #define KEY_LEN 32 #define VAL_LEN 128 using namespace std; struct timeval tp; double diffclock(clock_t clock1, clock_t clock2){ double clock_ts=clock1-clock2; double diffms=(clock_ts*1000)/CLOCKS_PER_SEC; return diffms; } double getTime_usec() { gettimeofday(&tp, NULL); return static_cast<double>(tp.tv_sec) * 1E6 + static_cast<double>(tp.tv_usec); } string randomString(int len) { string s(len, ' '); srand(/*getpid()*/ clock() + getTime_usec()); static const char alphanum[] = "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"; for (int i = 0; i < len; ++i) { s[i] = alphanum[rand() % (sizeof(alphanum) - 1)]; } return s; } double testInsert(NoVoHT &map, string keys[], string vals[], int l){ clock_t a=clock(); for (int t = 0; t<l; t++){ map.put(keys[t], vals[t]); } clock_t b=clock(); return diffclock(b,a);; } double testGet(NoVoHT &map, string keys[], string vals[], int l){ clock_t a=clock(); for (int t=0; t<l; t++){ if (map.get(keys[t])->compare(vals[t]) != 0) cerr << "Get Failed" << endl; } clock_t b=clock(); return diffclock(b,a); } double testRemove(NoVoHT &map, string keys[], int l){ clock_t a=clock(); for (int t=0; t<l; t++){ map.remove(keys[t]); } clock_t b=clock(); return diffclock(b,a); } int main(int argc, char *argv[]){ cout << "\nInitializing key-value pairs for testing\n" << endl; int size = atoi(argv[1]); string* keys = new string[size]; string* vals = new string[size]; /* for (int t=0; t<size; t++){ Package package, package_ret; string key = randomString(25);//as key package.set_virtualpath(key); package.set_isdir(true); package.set_replicano(5); package.set_operation(3); package.set_realfullpath("Some-Real-longer-longer-and-longer-Paths--------"); package.add_listitem("item-----1"); package.add_listitem("item-----2"); package.add_listitem("item-----3"); package.add_listitem("item-----4"); package.add_listitem("item-----5"); string value = package.SerializeAsString(); keys[t] = key; vals[t] = value; }*/ for (int t=0; t<size; t++){ keys[t] = randomString(KEY_LEN); vals[t] = randomString(VAL_LEN); } //NoVoHT map ("fbench.data", 1000000, 10000); NoVoHT map ("fbench.data", 10000000, -1); //NoVoHT map ("", 1000000, 10000, .7); //NoVoHT map ("", 1000000, -1); //NoVoHT map ("/dev/shm/fbench.data", 1000000, -1); double ins, ret, rem; cout << "Testing Insertion: Inserting " << size << " elements" << endl; ins = testInsert(map, keys,vals,size); cout << "Testing Retrieval: Retrieving " << size << " elements" << endl; ret = testGet(map,keys,vals,size); cout << "Testing Removal: Removing " << size << " elements" << endl; rem = testRemove(map,keys,size); cout << "\nInsertion done in " << ins << " milliseconds" << endl; cout << "Retrieval done in " << ret << " milliseconds" << endl; cout << "Removal done in " << rem << " milliseconds" << endl; delete [] keys; delete [] vals; return 0; } <commit_msg> modified: fbench.cxx<commit_after>#include <iostream> #include "time.h" #include <string> #include "novoht.h" #include <cstdlib> #include <cstddef> #include <sys/time.h> //#include "meta.pb.h" #define KEY_LEN 32 #define VAL_LEN 128 using namespace std; struct timeval tp; double diffclock(clock_t clock1, clock_t clock2){ double clock_ts=clock1-clock2; double diffms=(clock_ts*1000)/CLOCKS_PER_SEC; return diffms; } double getTime_usec() { gettimeofday(&tp, NULL); return static_cast<double>(tp.tv_sec) * 1E6 + static_cast<double>(tp.tv_usec); } string randomString(int len) { string s(len, ' '); srand(/*getpid()*/ clock() + getTime_usec()); static const char alphanum[] = "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"; for (int i = 0; i < len; ++i) { s[i] = alphanum[rand() % (sizeof(alphanum) - 1)]; } return s; } double testInsert(NoVoHT &map, string keys[], string vals[], int l){ clock_t a=clock(); for (int t = 0; t<l; t++){ map.put(keys[t], vals[t]); } clock_t b=clock(); return diffclock(b,a);; } double testGet(NoVoHT &map, string keys[], string vals[], int l){ clock_t a=clock(); for (int t=0; t<l; t++){ if (map.get(keys[t])->compare(vals[t]) != 0) cerr << "Get Failed" << endl; } clock_t b=clock(); return diffclock(b,a); } double testRemove(NoVoHT &map, string keys[], int l){ clock_t a=clock(); for (int t=0; t<l; t++){ map.remove(keys[t]); } clock_t b=clock(); return diffclock(b,a); } int main(int argc, char *argv[]){ cout << "\nInitializing key-value pairs for testing\n" << endl; int size = atoi(argv[1]); string* keys = new string[size]; string* vals = new string[size]; /* for (int t=0; t<size; t++){ Package package, package_ret; string key = randomString(25);//as key package.set_virtualpath(key); package.set_isdir(true); package.set_replicano(5); package.set_operation(3); package.set_realfullpath("Some-Real-longer-longer-and-longer-Paths--------"); package.add_listitem("item-----1"); package.add_listitem("item-----2"); package.add_listitem("item-----3"); package.add_listitem("item-----4"); package.add_listitem("item-----5"); string value = package.SerializeAsString(); keys[t] = key; vals[t] = value; }*/ for (int t=0; t<size; t++){ keys[t] = randomString(KEY_LEN); vals[t] = randomString(VAL_LEN); } NoVoHT map ("fbench.data", 1000000, 10000, .7); //NoVoHT map ("fbench.data", 10000000, -1); //NoVoHT map ("", 1000000, 10000, .7); //NoVoHT map ("", 1000000, -1); //NoVoHT map ("/dev/shm/fbench.data", 1000000, -1); double ins, ret, rem; cout << "Testing Insertion: Inserting " << size << " elements" << endl; ins = testInsert(map, keys,vals,size); cout << "Testing Retrieval: Retrieving " << size << " elements" << endl; ret = testGet(map,keys,vals,size); cout << "Testing Removal: Removing " << size << " elements" << endl; rem = testRemove(map,keys,size); cout << "\nInsertion done in " << ins << " milliseconds" << endl; cout << "Retrieval done in " << ret << " milliseconds" << endl; cout << "Removal done in " << rem << " milliseconds" << endl; delete [] keys; delete [] vals; return 0; } <|endoftext|>
<commit_before>// NOLINT(namespace-envoy) #ifndef WIN32 #include "unistd.h" #endif #include <cerrno> #include <cmath> #include <cstdio> #include <cstdlib> #include <limits> #include <string> #ifndef NULL_PLUGIN #include "proxy_wasm_intrinsics.h" #else #include "include/proxy-wasm/null_plugin.h" #endif START_WASM_PLUGIN(CommonWasmTestCpp) static int* badptr = nullptr; static float gNan = std::nan("1"); static float gInfinity = INFINITY; #ifndef CHECK_RESULT #define CHECK_RESULT(_c) \ do { \ if ((_c) != WasmResult::Ok) { \ proxy_log(LogLevel::critical, #_c, sizeof(#_c) - 1); \ abort(); \ } \ } while (0) #endif #define FAIL_NOW(_msg) \ do { \ const std::string __message = _msg; \ proxy_log(LogLevel::critical, __message.c_str(), __message.size()); \ abort(); \ } while (0) WASM_EXPORT(void, proxy_abi_version_0_2_1, (void)) {} WASM_EXPORT(void, proxy_on_context_create, (uint32_t, uint32_t)) {} WASM_EXPORT(uint32_t, proxy_on_vm_start, (uint32_t context_id, uint32_t configuration_size)) { const char* configuration_ptr = nullptr; size_t size; proxy_get_buffer_bytes(WasmBufferType::VmConfiguration, 0, configuration_size, &configuration_ptr, &size); std::string configuration(configuration_ptr, size); if (configuration == "logging") { std::string trace_message = "test trace logging"; proxy_log(LogLevel::trace, trace_message.c_str(), trace_message.size()); std::string debug_message = "test debug logging"; proxy_log(LogLevel::debug, debug_message.c_str(), debug_message.size()); std::string warn_message = "test warn logging"; proxy_log(LogLevel::warn, warn_message.c_str(), warn_message.size()); std::string error_message = "test error logging"; proxy_log(LogLevel::error, error_message.c_str(), error_message.size()); LogLevel log_level; CHECK_RESULT(proxy_get_log_level(&log_level)); std::string level_message = "log level is " + std::to_string(static_cast<uint32_t>(log_level)); proxy_log(LogLevel::info, level_message.c_str(), level_message.size()); } else if (configuration == "segv") { std::string message = "before badptr"; proxy_log(LogLevel::error, message.c_str(), message.size()); ::free(const_cast<void*>(reinterpret_cast<const void*>(configuration_ptr))); *badptr = 1; message = "after badptr"; proxy_log(LogLevel::error, message.c_str(), message.size()); } else if (configuration == "divbyzero") { std::string message = "before div by zero"; proxy_log(LogLevel::error, message.c_str(), message.size()); ::free(const_cast<void*>(reinterpret_cast<const void*>(configuration_ptr))); int zero = context_id & 0x100000; message = "divide by zero: " + std::to_string(100 / zero); proxy_log(LogLevel::error, message.c_str(), message.size()); } else if (configuration == "globals") { std::string message = "NaN " + std::to_string(gNan); proxy_log(LogLevel::warn, message.c_str(), message.size()); message = "inf " + std::to_string(gInfinity); proxy_log(LogLevel::warn, message.c_str(), message.size()); message = "inf " + std::to_string(1.0 / 0.0); proxy_log(LogLevel::warn, message.c_str(), message.size()); message = std::string("inf ") + (std::isinf(gInfinity) ? "inf" : "nan"); proxy_log(LogLevel::warn, message.c_str(), message.size()); } else if (configuration == "stats") { uint32_t c, g, h; std::string name = "test_counter"; CHECK_RESULT(proxy_define_metric(MetricType::Counter, name.data(), name.size(), &c)); name = "test_gauge"; CHECK_RESULT(proxy_define_metric(MetricType::Gauge, name.data(), name.size(), &g)); name = "test_historam"; CHECK_RESULT(proxy_define_metric(MetricType::Histogram, name.data(), name.size(), &h)); CHECK_RESULT(proxy_increment_metric(c, 1)); CHECK_RESULT(proxy_record_metric(g, 2)); CHECK_RESULT(proxy_record_metric(h, 3)); uint64_t value; std::string message; CHECK_RESULT(proxy_get_metric(c, &value)); message = std::string("get counter = ") + std::to_string(value); proxy_log(LogLevel::trace, message.c_str(), message.size()); CHECK_RESULT(proxy_increment_metric(c, 1)); CHECK_RESULT(proxy_get_metric(c, &value)); message = std::string("get counter = ") + std::to_string(value); proxy_log(LogLevel::debug, message.c_str(), message.size()); CHECK_RESULT(proxy_record_metric(c, 3)); CHECK_RESULT(proxy_get_metric(c, &value)); message = std::string("get counter = ") + std::to_string(value); proxy_log(LogLevel::info, message.c_str(), message.size()); CHECK_RESULT(proxy_get_metric(g, &value)); message = std::string("get gauge = ") + std::to_string(value); proxy_log(LogLevel::warn, message.c_str(), message.size()); // Get on histograms is not supported. if (proxy_get_metric(h, &value) != WasmResult::Ok) { message = std::string("get histogram = Unsupported"); proxy_log(LogLevel::error, message.c_str(), message.size()); } } else if (configuration == "foreign") { std::string function = "compress"; std::string argument = "something to compress dup dup dup dup dup"; char* compressed = nullptr; size_t compressed_size = 0; CHECK_RESULT(proxy_call_foreign_function(function.data(), function.size(), argument.data(), argument.size(), &compressed, &compressed_size)); auto message = std::string("compress ") + std::to_string(argument.size()) + " -> " + std::to_string(compressed_size); proxy_log(LogLevel::trace, message.c_str(), message.size()); function = "uncompress"; char* result = nullptr; size_t result_size = 0; CHECK_RESULT(proxy_call_foreign_function(function.data(), function.size(), compressed, compressed_size, &result, &result_size)); message = std::string("uncompress ") + std::to_string(compressed_size) + " -> " + std::to_string(result_size); proxy_log(LogLevel::debug, message.c_str(), message.size()); if (argument != std::string(result, result_size)) { message = "compress mismatch "; proxy_log(LogLevel::error, message.c_str(), message.size()); } ::free(compressed); ::free(result); } else if (configuration == "WASI") { // These checks depend on Emscripten's support for `WASI` and will only // work if invoked on a "real" Wasm VM. int err = fprintf(stdout, "WASI write to stdout\n"); if (err < 0) { FAIL_NOW("stdout write should succeed"); } err = fprintf(stderr, "WASI write to stderr\n"); if (err < 0) { FAIL_NOW("stderr write should succeed"); } // We explicitly don't support reading from stdin char tmp[16]; size_t rc = fread(static_cast<void*>(tmp), 1, 16, stdin); if (rc != 0 || errno != ENOSYS) { FAIL_NOW("stdin read should fail. errno = " + std::to_string(errno)); } // No environment variables should be available char* pathenv = getenv("PATH"); if (pathenv != nullptr) { FAIL_NOW("PATH environment variable should not be available"); } #ifndef WIN32 // Exercise the `WASI` `fd_fdstat_get` a little bit int tty = isatty(1); if (errno != ENOTTY || tty != 0) { FAIL_NOW("stdout is not a tty"); } tty = isatty(2); if (errno != ENOTTY || tty != 0) { FAIL_NOW("stderr is not a tty"); } tty = isatty(99); if (errno != EBADF || tty != 0) { FAIL_NOW("isatty errors on bad fds. errno = " + std::to_string(errno)); } #endif } else if (configuration == "on_foreign") { std::string message = "on_foreign start"; proxy_log(LogLevel::debug, message.c_str(), message.size()); } else { std::string message = "on_vm_start " + configuration; proxy_log(LogLevel::info, message.c_str(), message.size()); } ::free(const_cast<void*>(reinterpret_cast<const void*>(configuration_ptr))); return 1; } WASM_EXPORT(uint32_t, proxy_on_configure, (uint32_t, uint32_t configuration_size)) { const char* configuration_ptr = nullptr; size_t size; proxy_get_buffer_bytes(WasmBufferType::PluginConfiguration, 0, configuration_size, &configuration_ptr, &size); std::string configuration(configuration_ptr, size); if (configuration == "done") { proxy_done(); } else { std::string message = "on_configuration " + configuration; proxy_log(LogLevel::info, message.c_str(), message.size()); } ::free(const_cast<void*>(reinterpret_cast<const void*>(configuration_ptr))); return 1; } WASM_EXPORT(void, proxy_on_foreign_function, (uint32_t, uint32_t token, uint32_t data_size)) { std::string message = "on_foreign_function " + std::to_string(token) + " " + std::to_string(data_size); proxy_log(LogLevel::info, message.c_str(), message.size()); } WASM_EXPORT(uint32_t, proxy_on_done, (uint32_t)) { std::string message = "on_done logging"; proxy_log(LogLevel::info, message.c_str(), message.size()); return 0; } WASM_EXPORT(void, proxy_on_delete, (uint32_t)) { std::string message = "on_delete logging"; proxy_log(LogLevel::info, message.c_str(), message.size()); } END_WASM_PLUGIN <commit_msg>Add that oh so important gratuitous blank line clang-format wants<commit_after>// NOLINT(namespace-envoy) #ifndef WIN32 #include "unistd.h" #endif #include <cerrno> #include <cmath> #include <cstdio> #include <cstdlib> #include <limits> #include <string> #ifndef NULL_PLUGIN #include "proxy_wasm_intrinsics.h" #else #include "include/proxy-wasm/null_plugin.h" #endif START_WASM_PLUGIN(CommonWasmTestCpp) static int* badptr = nullptr; static float gNan = std::nan("1"); static float gInfinity = INFINITY; #ifndef CHECK_RESULT #define CHECK_RESULT(_c) \ do { \ if ((_c) != WasmResult::Ok) { \ proxy_log(LogLevel::critical, #_c, sizeof(#_c) - 1); \ abort(); \ } \ } while (0) #endif #define FAIL_NOW(_msg) \ do { \ const std::string __message = _msg; \ proxy_log(LogLevel::critical, __message.c_str(), __message.size()); \ abort(); \ } while (0) WASM_EXPORT(void, proxy_abi_version_0_2_1, (void)) {} WASM_EXPORT(void, proxy_on_context_create, (uint32_t, uint32_t)) {} WASM_EXPORT(uint32_t, proxy_on_vm_start, (uint32_t context_id, uint32_t configuration_size)) { const char* configuration_ptr = nullptr; size_t size; proxy_get_buffer_bytes(WasmBufferType::VmConfiguration, 0, configuration_size, &configuration_ptr, &size); std::string configuration(configuration_ptr, size); if (configuration == "logging") { std::string trace_message = "test trace logging"; proxy_log(LogLevel::trace, trace_message.c_str(), trace_message.size()); std::string debug_message = "test debug logging"; proxy_log(LogLevel::debug, debug_message.c_str(), debug_message.size()); std::string warn_message = "test warn logging"; proxy_log(LogLevel::warn, warn_message.c_str(), warn_message.size()); std::string error_message = "test error logging"; proxy_log(LogLevel::error, error_message.c_str(), error_message.size()); LogLevel log_level; CHECK_RESULT(proxy_get_log_level(&log_level)); std::string level_message = "log level is " + std::to_string(static_cast<uint32_t>(log_level)); proxy_log(LogLevel::info, level_message.c_str(), level_message.size()); } else if (configuration == "segv") { std::string message = "before badptr"; proxy_log(LogLevel::error, message.c_str(), message.size()); ::free(const_cast<void*>(reinterpret_cast<const void*>(configuration_ptr))); *badptr = 1; message = "after badptr"; proxy_log(LogLevel::error, message.c_str(), message.size()); } else if (configuration == "divbyzero") { std::string message = "before div by zero"; proxy_log(LogLevel::error, message.c_str(), message.size()); ::free(const_cast<void*>(reinterpret_cast<const void*>(configuration_ptr))); int zero = context_id & 0x100000; message = "divide by zero: " + std::to_string(100 / zero); proxy_log(LogLevel::error, message.c_str(), message.size()); } else if (configuration == "globals") { std::string message = "NaN " + std::to_string(gNan); proxy_log(LogLevel::warn, message.c_str(), message.size()); message = "inf " + std::to_string(gInfinity); proxy_log(LogLevel::warn, message.c_str(), message.size()); message = "inf " + std::to_string(1.0 / 0.0); proxy_log(LogLevel::warn, message.c_str(), message.size()); message = std::string("inf ") + (std::isinf(gInfinity) ? "inf" : "nan"); proxy_log(LogLevel::warn, message.c_str(), message.size()); } else if (configuration == "stats") { uint32_t c, g, h; std::string name = "test_counter"; CHECK_RESULT(proxy_define_metric(MetricType::Counter, name.data(), name.size(), &c)); name = "test_gauge"; CHECK_RESULT(proxy_define_metric(MetricType::Gauge, name.data(), name.size(), &g)); name = "test_historam"; CHECK_RESULT(proxy_define_metric(MetricType::Histogram, name.data(), name.size(), &h)); CHECK_RESULT(proxy_increment_metric(c, 1)); CHECK_RESULT(proxy_record_metric(g, 2)); CHECK_RESULT(proxy_record_metric(h, 3)); uint64_t value; std::string message; CHECK_RESULT(proxy_get_metric(c, &value)); message = std::string("get counter = ") + std::to_string(value); proxy_log(LogLevel::trace, message.c_str(), message.size()); CHECK_RESULT(proxy_increment_metric(c, 1)); CHECK_RESULT(proxy_get_metric(c, &value)); message = std::string("get counter = ") + std::to_string(value); proxy_log(LogLevel::debug, message.c_str(), message.size()); CHECK_RESULT(proxy_record_metric(c, 3)); CHECK_RESULT(proxy_get_metric(c, &value)); message = std::string("get counter = ") + std::to_string(value); proxy_log(LogLevel::info, message.c_str(), message.size()); CHECK_RESULT(proxy_get_metric(g, &value)); message = std::string("get gauge = ") + std::to_string(value); proxy_log(LogLevel::warn, message.c_str(), message.size()); // Get on histograms is not supported. if (proxy_get_metric(h, &value) != WasmResult::Ok) { message = std::string("get histogram = Unsupported"); proxy_log(LogLevel::error, message.c_str(), message.size()); } } else if (configuration == "foreign") { std::string function = "compress"; std::string argument = "something to compress dup dup dup dup dup"; char* compressed = nullptr; size_t compressed_size = 0; CHECK_RESULT(proxy_call_foreign_function(function.data(), function.size(), argument.data(), argument.size(), &compressed, &compressed_size)); auto message = std::string("compress ") + std::to_string(argument.size()) + " -> " + std::to_string(compressed_size); proxy_log(LogLevel::trace, message.c_str(), message.size()); function = "uncompress"; char* result = nullptr; size_t result_size = 0; CHECK_RESULT(proxy_call_foreign_function(function.data(), function.size(), compressed, compressed_size, &result, &result_size)); message = std::string("uncompress ") + std::to_string(compressed_size) + " -> " + std::to_string(result_size); proxy_log(LogLevel::debug, message.c_str(), message.size()); if (argument != std::string(result, result_size)) { message = "compress mismatch "; proxy_log(LogLevel::error, message.c_str(), message.size()); } ::free(compressed); ::free(result); } else if (configuration == "WASI") { // These checks depend on Emscripten's support for `WASI` and will only // work if invoked on a "real" Wasm VM. int err = fprintf(stdout, "WASI write to stdout\n"); if (err < 0) { FAIL_NOW("stdout write should succeed"); } err = fprintf(stderr, "WASI write to stderr\n"); if (err < 0) { FAIL_NOW("stderr write should succeed"); } // We explicitly don't support reading from stdin char tmp[16]; size_t rc = fread(static_cast<void*>(tmp), 1, 16, stdin); if (rc != 0 || errno != ENOSYS) { FAIL_NOW("stdin read should fail. errno = " + std::to_string(errno)); } // No environment variables should be available char* pathenv = getenv("PATH"); if (pathenv != nullptr) { FAIL_NOW("PATH environment variable should not be available"); } #ifndef WIN32 // Exercise the `WASI` `fd_fdstat_get` a little bit int tty = isatty(1); if (errno != ENOTTY || tty != 0) { FAIL_NOW("stdout is not a tty"); } tty = isatty(2); if (errno != ENOTTY || tty != 0) { FAIL_NOW("stderr is not a tty"); } tty = isatty(99); if (errno != EBADF || tty != 0) { FAIL_NOW("isatty errors on bad fds. errno = " + std::to_string(errno)); } #endif } else if (configuration == "on_foreign") { std::string message = "on_foreign start"; proxy_log(LogLevel::debug, message.c_str(), message.size()); } else { std::string message = "on_vm_start " + configuration; proxy_log(LogLevel::info, message.c_str(), message.size()); } ::free(const_cast<void*>(reinterpret_cast<const void*>(configuration_ptr))); return 1; } WASM_EXPORT(uint32_t, proxy_on_configure, (uint32_t, uint32_t configuration_size)) { const char* configuration_ptr = nullptr; size_t size; proxy_get_buffer_bytes(WasmBufferType::PluginConfiguration, 0, configuration_size, &configuration_ptr, &size); std::string configuration(configuration_ptr, size); if (configuration == "done") { proxy_done(); } else { std::string message = "on_configuration " + configuration; proxy_log(LogLevel::info, message.c_str(), message.size()); } ::free(const_cast<void*>(reinterpret_cast<const void*>(configuration_ptr))); return 1; } WASM_EXPORT(void, proxy_on_foreign_function, (uint32_t, uint32_t token, uint32_t data_size)) { std::string message = "on_foreign_function " + std::to_string(token) + " " + std::to_string(data_size); proxy_log(LogLevel::info, message.c_str(), message.size()); } WASM_EXPORT(uint32_t, proxy_on_done, (uint32_t)) { std::string message = "on_done logging"; proxy_log(LogLevel::info, message.c_str(), message.size()); return 0; } WASM_EXPORT(void, proxy_on_delete, (uint32_t)) { std::string message = "on_delete logging"; proxy_log(LogLevel::info, message.c_str(), message.size()); } END_WASM_PLUGIN <|endoftext|>
<commit_before>/* Highly Optimized Object-oriented Many-particle Dynamics -- Blue Edition (HOOMD-blue) Open Source Software License Copyright 2008, 2009 Ames Laboratory Iowa State University and The Regents of the University of Michigan All rights reserved. HOOMD-blue may contain modifications ("Contributions") provided, and to which copyright is held, by various Contributors who have granted The Regents of the University of Michigan the right to modify and/or distribute such Contributions. Redistribution and use of HOOMD-blue, in source and binary forms, with or without modification, are permitted, provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions, and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions, and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of HOOMD-blue's contributors may be used to endorse or promote products derived from this software without specific prior written permission. Disclaimer THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND/OR ANY WARRANTIES THAT THIS SOFTWARE IS FREE OF INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // $Id$ // $URL$ // Maintainer: joaander #ifdef WIN32 #pragma warning( push ) #pragma warning( disable : 4103 4244 ) #endif #include <iostream> #include <boost/bind.hpp> #include <boost/function.hpp> #include <boost/shared_ptr.hpp> #include "TwoStepNPT.h" #ifdef ENABLE_CUDA #include "TwoStepNPTGPU.h" #endif #include "IntegratorTwoStep.h" #include "BinnedNeighborList.h" #include "Initializers.h" #include "AllPairPotentials.h" #include <math.h> using namespace std; using namespace boost; /*! \file npt_updater_test.cc \brief Implements unit tests for NPTpdater and descendants \ingroup unit_tests */ //! name the boost unit test module #define BOOST_TEST_MODULE TwoStepNPTTests #include "boost_utf_configure.h" //! Typedef'd NPTUpdator class factory typedef boost::function<shared_ptr<TwoStepNPT> (shared_ptr<SystemDefinition> sysdef, shared_ptr<ParticleGroup> group, Scalar tau, Scalar tauP, Scalar T, Scalar P) > twostepnpt_creator; //! Basic functionality test of a generic TwoStepNPT void npt_updater_test(twostepnpt_creator npt_creator, ExecutionConfiguration exec_conf) { #ifdef ENABLE_CUDA g_gpu_error_checking = true; #endif const unsigned int N = 1000; Scalar T = 2.0; Scalar P = 1.0; // create two identical random particle systems to simulate RandomInitializer rand_init(N, Scalar(0.2), Scalar(0.9), "A"); rand_init.setSeed(12345); shared_ptr<SystemDefinition> sysdef(new SystemDefinition(rand_init, exec_conf)); shared_ptr<ParticleData> pdata = sysdef->getParticleData(); shared_ptr<ParticleSelector> selector_all(new ParticleSelectorTag(sysdef, 0, pdata->getN()-1)); shared_ptr<ParticleGroup> group_all(new ParticleGroup(sysdef, selector_all)); shared_ptr<BinnedNeighborList> nlist(new BinnedNeighborList(sysdef, Scalar(2.5), Scalar(0.8))); shared_ptr<PotentialPairLJ> fc(new PotentialPairLJ(sysdef, nlist)); fc->setRcut(0, 0, Scalar(2.5)); // setup some values for alpha and sigma Scalar epsilon = Scalar(1.0); Scalar sigma = Scalar(1.0); Scalar alpha = Scalar(1.0); Scalar lj1 = Scalar(4.0) * epsilon * pow(sigma,Scalar(12.0)); Scalar lj2 = alpha * Scalar(4.0) * epsilon * pow(sigma,Scalar(6.0)); // specify the force parameters fc->setParams(0,0,make_scalar2(lj1,lj2)); shared_ptr<TwoStepNPT> two_step_npt = npt_creator(sysdef, group_all, Scalar(1.0),Scalar(1.0),T,P); shared_ptr<IntegratorTwoStep> npt(new IntegratorTwoStep(sysdef, Scalar(0.001))); npt->addIntegrationMethod(two_step_npt); npt->addForceCompute(fc); // step for a 10,000 timesteps to relax pessure and tempreratue // before computing averages for (int i = 0; i < 10000; i++) { npt->update(i); } // now do the averaging for next 100k steps Scalar avrT = 0.0; Scalar avrP = 0.0; for (int i = 10001; i < 50000; i++) { avrT += npt->computeTemperature(i); avrP += npt->computePressure(i); npt->update(i); } avrT /= 40000.0; avrP /= 40000.0; Scalar rough_tol = 2.0; MY_BOOST_CHECK_CLOSE(T, avrT, rough_tol); MY_BOOST_CHECK_CLOSE(P, avrP, rough_tol); } //! NPTUpdater factory for the unit tests shared_ptr<TwoStepNPT> base_class_npt_creator(shared_ptr<SystemDefinition> sysdef, shared_ptr<ParticleGroup> group, Scalar tau, Scalar tauP, Scalar T, Scalar P) { boost::shared_ptr<Variant> T_variant(new VariantConst(T)); boost::shared_ptr<Variant> P_variant(new VariantConst(P)); return shared_ptr<TwoStepNPT>(new TwoStepNPT(sysdef, group,tau,tauP,T_variant,P_variant)); } #ifdef ENABLE_CUDA //! NPTUpdaterGPU factory for the unit tests shared_ptr<TwoStepNPT> gpu_npt_creator(shared_ptr<SystemDefinition> sysdef, shared_ptr<ParticleGroup> group, Scalar tau, Scalar tauP, Scalar T, Scalar P) { boost::shared_ptr<Variant> T_variant(new VariantConst(T)); boost::shared_ptr<Variant> P_variant(new VariantConst(P)); return shared_ptr<TwoStepNPT>(new TwoStepNPTGPU(sysdef, group, tau, tauP, T_variant, P_variant)); } #endif //! boost test case for base class integration tests BOOST_AUTO_TEST_CASE( TwoStepNPT_tests ) { twostepnpt_creator npt_creator = bind(base_class_npt_creator, _1, _2,_3,_4,_5,_6); npt_updater_test(npt_creator, ExecutionConfiguration(ExecutionConfiguration::CPU)); } #ifdef ENABLE_CUDA //! boost test case for base class integration tests BOOST_AUTO_TEST_CASE( TwoStepNPTGPU_tests ) { twostepnpt_creator npt_creator = bind(gpu_npt_creator, _1, _2,_3,_4,_5,_6); npt_updater_test(npt_creator, ExecutionConfiguration(ExecutionConfiguration::GPU)); } #endif #ifdef WIN32 #pragma warning( pop ) #endif <commit_msg>Update test_npt_integrator to work with ComputeThermo<commit_after>/* Highly Optimized Object-oriented Many-particle Dynamics -- Blue Edition (HOOMD-blue) Open Source Software License Copyright 2008, 2009 Ames Laboratory Iowa State University and The Regents of the University of Michigan All rights reserved. HOOMD-blue may contain modifications ("Contributions") provided, and to which copyright is held, by various Contributors who have granted The Regents of the University of Michigan the right to modify and/or distribute such Contributions. Redistribution and use of HOOMD-blue, in source and binary forms, with or without modification, are permitted, provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions, and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions, and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of HOOMD-blue's contributors may be used to endorse or promote products derived from this software without specific prior written permission. Disclaimer THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND/OR ANY WARRANTIES THAT THIS SOFTWARE IS FREE OF INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // $Id$ // $URL$ // Maintainer: joaander #ifdef WIN32 #pragma warning( push ) #pragma warning( disable : 4103 4244 ) #endif #include <iostream> #include <boost/bind.hpp> #include <boost/function.hpp> #include <boost/shared_ptr.hpp> #include "ComputeThermo.h" #include "TwoStepNPT.h" #ifdef ENABLE_CUDA #include "TwoStepNPTGPU.h" #endif #include "IntegratorTwoStep.h" #include "BinnedNeighborList.h" #include "Initializers.h" #include "AllPairPotentials.h" #include <math.h> using namespace std; using namespace boost; /*! \file npt_updater_test.cc \brief Implements unit tests for NPTpdater and descendants \ingroup unit_tests */ //! name the boost unit test module #define BOOST_TEST_MODULE TwoStepNPTTests #include "boost_utf_configure.h" //! Typedef'd NPTUpdator class factory typedef boost::function<shared_ptr<TwoStepNPT> (shared_ptr<SystemDefinition> sysdef, shared_ptr<ParticleGroup> group, Scalar tau, Scalar tauP, Scalar T, Scalar P) > twostepnpt_creator; //! Basic functionality test of a generic TwoStepNPT void npt_updater_test(twostepnpt_creator npt_creator, ExecutionConfiguration exec_conf) { #ifdef ENABLE_CUDA g_gpu_error_checking = true; #endif const unsigned int N = 1000; Scalar T = 2.0; Scalar P = 1.0; // create two identical random particle systems to simulate RandomInitializer rand_init(N, Scalar(0.2), Scalar(0.9), "A"); rand_init.setSeed(12345); shared_ptr<SystemDefinition> sysdef(new SystemDefinition(rand_init, exec_conf)); shared_ptr<ParticleData> pdata = sysdef->getParticleData(); shared_ptr<ParticleSelector> selector_all(new ParticleSelectorTag(sysdef, 0, pdata->getN()-1)); shared_ptr<ParticleGroup> group_all(new ParticleGroup(sysdef, selector_all)); shared_ptr<BinnedNeighborList> nlist(new BinnedNeighborList(sysdef, Scalar(2.5), Scalar(0.8))); shared_ptr<PotentialPairLJ> fc(new PotentialPairLJ(sysdef, nlist)); fc->setRcut(0, 0, Scalar(2.5)); // setup some values for alpha and sigma Scalar epsilon = Scalar(1.0); Scalar sigma = Scalar(1.0); Scalar alpha = Scalar(1.0); Scalar lj1 = Scalar(4.0) * epsilon * pow(sigma,Scalar(12.0)); Scalar lj2 = alpha * Scalar(4.0) * epsilon * pow(sigma,Scalar(6.0)); // specify the force parameters fc->setParams(0,0,make_scalar2(lj1,lj2)); shared_ptr<TwoStepNPT> two_step_npt = npt_creator(sysdef, group_all, Scalar(1.0),Scalar(1.0),T,P); shared_ptr<IntegratorTwoStep> npt(new IntegratorTwoStep(sysdef, Scalar(0.001))); npt->addIntegrationMethod(two_step_npt); npt->addForceCompute(fc); // step for a 10,000 timesteps to relax pessure and tempreratue // before computing averages for (int i = 0; i < 10000; i++) { npt->update(i); } shared_ptr<ComputeThermo> compute_thermo(new ComputeThermo(sysdef, group_all, "name")); compute_thermo->setNDOF(3*N-3); // now do the averaging for next 100k steps Scalar avrT = 0.0; Scalar avrP = 0.0; int count = 0; for (int i = 10001; i < 50000; i++) { if (i % 100 == 0) { compute_thermo->compute(i); avrT += compute_thermo->getTemperature(); avrP += compute_thermo->getPressure(); count++; } npt->update(i); } avrT /= Scalar(count); avrP /= Scalar(count); Scalar rough_tol = 2.0; MY_BOOST_CHECK_CLOSE(T, avrT, rough_tol); MY_BOOST_CHECK_CLOSE(P, avrP, rough_tol); } //! NPTUpdater factory for the unit tests shared_ptr<TwoStepNPT> base_class_npt_creator(shared_ptr<SystemDefinition> sysdef, shared_ptr<ParticleGroup> group, Scalar tau, Scalar tauP, Scalar T, Scalar P) { boost::shared_ptr<Variant> T_variant(new VariantConst(T)); boost::shared_ptr<Variant> P_variant(new VariantConst(P)); return shared_ptr<TwoStepNPT>(new TwoStepNPT(sysdef, group,tau,tauP,T_variant,P_variant)); } #ifdef ENABLE_CUDA //! NPTUpdaterGPU factory for the unit tests shared_ptr<TwoStepNPT> gpu_npt_creator(shared_ptr<SystemDefinition> sysdef, shared_ptr<ParticleGroup> group, Scalar tau, Scalar tauP, Scalar T, Scalar P) { boost::shared_ptr<Variant> T_variant(new VariantConst(T)); boost::shared_ptr<Variant> P_variant(new VariantConst(P)); return shared_ptr<TwoStepNPT>(new TwoStepNPTGPU(sysdef, group, tau, tauP, T_variant, P_variant)); } #endif //! boost test case for base class integration tests BOOST_AUTO_TEST_CASE( TwoStepNPT_tests ) { twostepnpt_creator npt_creator = bind(base_class_npt_creator, _1, _2,_3,_4,_5,_6); npt_updater_test(npt_creator, ExecutionConfiguration(ExecutionConfiguration::CPU)); } #ifdef ENABLE_CUDA //! boost test case for base class integration tests BOOST_AUTO_TEST_CASE( TwoStepNPTGPU_tests ) { twostepnpt_creator npt_creator = bind(gpu_npt_creator, _1, _2,_3,_4,_5,_6); npt_updater_test(npt_creator, ExecutionConfiguration(ExecutionConfiguration::GPU)); } #endif #ifdef WIN32 #pragma warning( pop ) #endif <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014-2015 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include "dll/dyn_dbn.hpp" #include "dll/ocv_visualizer.hpp" template<typename DBN> void test_dbn(DBN& dbn){ dbn->display(); std::vector<etl::dyn_vector<double>> images; dbn->pretrain(images, 10); } int main(){ using dbn_t = dll::dyn_dbn_desc< dll::dbn_layers< dll::dyn_rbm_desc<dll::momentum, dll::init_weights>::rbm_t, dll::dyn_rbm_desc<dll::momentum>::rbm_t, dll::dyn_rbm_desc<dll::momentum, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t >, dll::watcher<dll::opencv_dbn_visualizer> >::dbn_t; auto dbn = std::make_unique<dbn_t>( std::make_tuple(28*28,100), std::make_tuple(100,200), std::make_tuple(200,10)); test_dbn(dbn); return 0; } <commit_msg>Adapt test case<commit_after>//======================================================================= // Copyright (c) 2014-2015 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include "dll/dyn_rbm.hpp" #include "dll/dbn.hpp" #include "dll/ocv_visualizer.hpp" template<typename DBN> void test_dbn(DBN& dbn){ dbn->display(); std::vector<etl::dyn_vector<double>> images; dbn->pretrain(images, 10); } int main(){ using dbn_t = dll::dbn_desc< dll::dbn_layers< dll::dyn_rbm_desc<dll::momentum, dll::init_weights>::rbm_t, dll::dyn_rbm_desc<dll::momentum>::rbm_t, dll::dyn_rbm_desc<dll::momentum, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t >, dll::watcher<dll::opencv_dbn_visualizer> >::dbn_t; auto dbn = std::make_unique<dbn_t>( std::make_tuple(28*28,100), std::make_tuple(100,200), std::make_tuple(200,10)); test_dbn(dbn); return 0; } <|endoftext|>
<commit_before>/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. */ #include "TestSscCommon.h" #include <adios2.h> #include <gtest/gtest.h> #include <mpi.h> #include <numeric> #include <thread> using namespace adios2; int mpiRank = 0; int mpiSize = 1; MPI_Comm mpiComm; class SscEngineTest : public ::testing::Test { public: SscEngineTest() = default; }; void Writer(const Dims &shape, const Dims &start, const Dims &count, const size_t steps, const adios2::Params &engineParams, const std::string &name) { size_t datasize = std::accumulate(count.begin(), count.end(), static_cast<size_t>(1), std::multiplies<size_t>()); adios2::ADIOS adios(mpiComm); adios2::IO dataManIO = adios.DeclareIO("WAN"); dataManIO.SetEngine("ssc"); dataManIO.SetParameters(engineParams); std::vector<char> myChars(datasize); std::vector<unsigned char> myUChars(datasize); std::vector<short> myShorts(datasize); std::vector<unsigned short> myUShorts(datasize); std::vector<int> myInts(datasize); std::vector<unsigned int> myUInts(datasize); std::vector<float> myFloats(datasize); std::vector<double> myDoubles(datasize); std::vector<std::complex<float>> myComplexes(datasize); std::vector<std::complex<double>> myDComplexes(datasize); auto bpChars = dataManIO.DefineVariable<char>("bpChars", shape, start, count); auto bpUChars = dataManIO.DefineVariable<unsigned char>("bpUChars", shape, start, count); auto bpShorts = dataManIO.DefineVariable<short>("bpShorts", shape, start, count); auto bpUShorts = dataManIO.DefineVariable<unsigned short>( "bpUShorts", shape, start, count); auto bpInts = dataManIO.DefineVariable<int>("bpInts", shape, start, count); auto bpUInts = dataManIO.DefineVariable<unsigned int>("bpUInts", shape, start, count); auto bpFloats = dataManIO.DefineVariable<float>("bpFloats", shape, start, count); auto bpDoubles = dataManIO.DefineVariable<double>("bpDoubles", shape, start, count); auto bpComplexes = dataManIO.DefineVariable<std::complex<float>>( "bpComplexes", shape, start, count); auto bpDComplexes = dataManIO.DefineVariable<std::complex<double>>( "bpDComplexes", shape, start, count); auto scalarInt = dataManIO.DefineVariable<int>("scalarInt"); auto stringVar = dataManIO.DefineVariable<std::string>("stringVar"); dataManIO.DefineAttribute<int>("AttInt", 110); adios2::Engine engine = dataManIO.Open(name, adios2::Mode::Write); for (int i = 0; i < steps; ++i) { engine.BeginStep(); GenData(myChars, i, start, count, shape); GenData(myUChars, i, start, count, shape); GenData(myShorts, i, start, count, shape); GenData(myUShorts, i, start, count, shape); GenData(myInts, i, start, count, shape); GenData(myUInts, i, start, count, shape); GenData(myFloats, i, start, count, shape); GenData(myDoubles, i, start, count, shape); GenData(myComplexes, i, start, count, shape); GenData(myDComplexes, i, start, count, shape); engine.Put(bpChars, myChars.data(), adios2::Mode::Sync); engine.Put(bpUChars, myUChars.data(), adios2::Mode::Sync); engine.Put(bpShorts, myShorts.data(), adios2::Mode::Sync); engine.Put(bpUShorts, myUShorts.data(), adios2::Mode::Sync); engine.Put(bpInts, myInts.data(), adios2::Mode::Sync); engine.Put(bpUInts, myUInts.data(), adios2::Mode::Sync); engine.Put(bpFloats, myFloats.data(), adios2::Mode::Sync); engine.Put(bpDoubles, myDoubles.data(), adios2::Mode::Sync); engine.Put(bpComplexes, myComplexes.data(), adios2::Mode::Sync); engine.Put(bpDComplexes, myDComplexes.data(), adios2::Mode::Sync); engine.Put(scalarInt, i); std::string s = "sample string sample string sample string"; engine.Put(stringVar, s); engine.EndStep(); } engine.Close(); } void Reader(const Dims &shape, const Dims &start, const Dims &count, const size_t steps, const adios2::Params &engineParams, const std::string &name) { adios2::ADIOS adios(mpiComm); adios2::IO dataManIO = adios.DeclareIO("Test"); dataManIO.SetEngine("ssc"); dataManIO.SetParameters(engineParams); adios2::Engine engine = dataManIO.Open(name, adios2::Mode::Read); size_t datasize = std::accumulate(count.begin(), count.end(), static_cast<size_t>(1), std::multiplies<size_t>()); std::vector<char> myChars(datasize); std::vector<unsigned char> myUChars(datasize); std::vector<short> myShorts(datasize); std::vector<unsigned short> myUShorts(datasize); std::vector<int> myInts(datasize); std::vector<unsigned int> myUInts(datasize); std::vector<float> myFloats(datasize); std::vector<double> myDoubles(datasize); std::vector<std::complex<float>> myComplexes(datasize); std::vector<std::complex<double>> myDComplexes(datasize); while (true) { adios2::StepStatus status = engine.BeginStep(StepMode::Read, 5); if (status == adios2::StepStatus::OK) { auto scalarInt = dataManIO.InquireVariable<int>("scalarInt"); auto blocksInfo = engine.BlocksInfo(scalarInt, engine.CurrentStep()); for (const auto &bi : blocksInfo) { ASSERT_EQ(bi.IsValue, true); ASSERT_EQ(bi.Value, engine.CurrentStep()); ASSERT_EQ(scalarInt.Min(), engine.CurrentStep()); ASSERT_EQ(scalarInt.Max(), engine.CurrentStep()); } const auto &vars = dataManIO.AvailableVariables(); ASSERT_EQ(vars.size(), 12); size_t currentStep = engine.CurrentStep(); adios2::Variable<char> bpChars = dataManIO.InquireVariable<char>("bpChars"); adios2::Variable<unsigned char> bpUChars = dataManIO.InquireVariable<unsigned char>("bpUChars"); adios2::Variable<short> bpShorts = dataManIO.InquireVariable<short>("bpShorts"); adios2::Variable<unsigned short> bpUShorts = dataManIO.InquireVariable<unsigned short>("bpUShorts"); adios2::Variable<int> bpInts = dataManIO.InquireVariable<int>("bpInts"); adios2::Variable<unsigned int> bpUInts = dataManIO.InquireVariable<unsigned int>("bpUInts"); adios2::Variable<float> bpFloats = dataManIO.InquireVariable<float>("bpFloats"); adios2::Variable<double> bpDoubles = dataManIO.InquireVariable<double>("bpDoubles"); adios2::Variable<std::complex<float>> bpComplexes = dataManIO.InquireVariable<std::complex<float>>("bpComplexes"); adios2::Variable<std::complex<double>> bpDComplexes = dataManIO.InquireVariable<std::complex<double>>("bpDComplexes"); adios2::Variable<std::string> stringVar = dataManIO.InquireVariable<std::string>("stringVar"); bpChars.SetSelection({start, count}); bpUChars.SetSelection({start, count}); bpShorts.SetSelection({start, count}); bpUShorts.SetSelection({start, count}); bpInts.SetSelection({start, count}); bpUInts.SetSelection({start, count}); bpFloats.SetSelection({start, count}); bpDoubles.SetSelection({start, count}); bpComplexes.SetSelection({start, count}); bpDComplexes.SetSelection({start, count}); engine.Get(bpChars, myChars.data(), adios2::Mode::Sync); engine.Get(bpUChars, myUChars.data(), adios2::Mode::Sync); engine.Get(bpShorts, myShorts.data(), adios2::Mode::Sync); engine.Get(bpUShorts, myUShorts.data(), adios2::Mode::Sync); engine.Get(bpInts, myInts.data(), adios2::Mode::Sync); engine.Get(bpUInts, myUInts.data(), adios2::Mode::Sync); engine.Get(bpFloats, myFloats.data(), adios2::Mode::Sync); engine.Get(bpDoubles, myDoubles.data(), adios2::Mode::Sync); engine.Get(bpComplexes, myComplexes.data(), adios2::Mode::Sync); engine.Get(bpDComplexes, myDComplexes.data(), adios2::Mode::Sync); std::string s; engine.Get(stringVar, s); ASSERT_EQ(s, "sample string sample string sample string"); ASSERT_EQ(stringVar.Min(), "sample string sample string sample string"); ASSERT_EQ(stringVar.Max(), "sample string sample string sample string"); int i; engine.Get(scalarInt, &i); ASSERT_EQ(i, currentStep); VerifyData(myChars.data(), currentStep, start, count, shape, mpiRank); VerifyData(myUChars.data(), currentStep, start, count, shape, mpiRank); VerifyData(myShorts.data(), currentStep, start, count, shape, mpiRank); VerifyData(myUShorts.data(), currentStep, start, count, shape, mpiRank); VerifyData(myInts.data(), currentStep, start, count, shape, mpiRank); VerifyData(myUInts.data(), currentStep, start, count, shape, mpiRank); VerifyData(myFloats.data(), currentStep, start, count, shape, mpiRank); VerifyData(myDoubles.data(), currentStep, start, count, shape, mpiRank); VerifyData(myComplexes.data(), currentStep, start, count, shape, mpiRank); VerifyData(myDComplexes.data(), currentStep, start, count, shape, mpiRank); engine.EndStep(); } else if (status == adios2::StepStatus::EndOfStream) { std::cout << "[Rank " + std::to_string(mpiRank) + "] SscTest reader end of stream!" << std::endl; break; } } auto attInt = dataManIO.InquireAttribute<int>("AttInt"); std::cout << "[Rank " + std::to_string(mpiRank) + "] Attribute received " << attInt.Data()[0] << ", expected 110" << std::endl; ASSERT_EQ(110, attInt.Data()[0]); ASSERT_NE(111, attInt.Data()[0]); engine.Close(); } TEST_F(SscEngineTest, TestSscBaseUnlocked) { std::string filename = "TestSscBaseUnlocked"; adios2::Params engineParams = {}; int worldRank, worldSize; MPI_Comm_rank(MPI_COMM_WORLD, &worldRank); MPI_Comm_size(MPI_COMM_WORLD, &worldSize); int mpiGroup = worldRank / (worldSize / 2); MPI_Comm_split(MPI_COMM_WORLD, mpiGroup, worldRank, &mpiComm); MPI_Comm_rank(mpiComm, &mpiRank); MPI_Comm_size(mpiComm, &mpiSize); Dims shape = {10, (size_t)mpiSize * 2}; Dims start = {2, (size_t)mpiRank * 2}; Dims count = {5, 2}; size_t steps = 100; if (mpiGroup == 0) { Writer(shape, start, count, steps, engineParams, filename); } std::this_thread::sleep_for(std::chrono::milliseconds(1)); if (mpiGroup == 1) { Reader(shape, start, count, steps, engineParams, filename); } MPI_Barrier(MPI_COMM_WORLD); } int main(int argc, char **argv) { MPI_Init(&argc, &argv); int worldRank, worldSize; MPI_Comm_rank(MPI_COMM_WORLD, &worldRank); MPI_Comm_size(MPI_COMM_WORLD, &worldSize); ::testing::InitGoogleTest(&argc, argv); int result = RUN_ALL_TESTS(); MPI_Finalize(); return result; } <commit_msg>reduced steps to avoid timeout for slow windows CI<commit_after>/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. */ #include "TestSscCommon.h" #include <adios2.h> #include <gtest/gtest.h> #include <mpi.h> #include <numeric> #include <thread> using namespace adios2; int mpiRank = 0; int mpiSize = 1; MPI_Comm mpiComm; class SscEngineTest : public ::testing::Test { public: SscEngineTest() = default; }; void Writer(const Dims &shape, const Dims &start, const Dims &count, const size_t steps, const adios2::Params &engineParams, const std::string &name) { size_t datasize = std::accumulate(count.begin(), count.end(), static_cast<size_t>(1), std::multiplies<size_t>()); adios2::ADIOS adios(mpiComm); adios2::IO dataManIO = adios.DeclareIO("WAN"); dataManIO.SetEngine("ssc"); dataManIO.SetParameters(engineParams); std::vector<char> myChars(datasize); std::vector<unsigned char> myUChars(datasize); std::vector<short> myShorts(datasize); std::vector<unsigned short> myUShorts(datasize); std::vector<int> myInts(datasize); std::vector<unsigned int> myUInts(datasize); std::vector<float> myFloats(datasize); std::vector<double> myDoubles(datasize); std::vector<std::complex<float>> myComplexes(datasize); std::vector<std::complex<double>> myDComplexes(datasize); auto bpChars = dataManIO.DefineVariable<char>("bpChars", shape, start, count); auto bpUChars = dataManIO.DefineVariable<unsigned char>("bpUChars", shape, start, count); auto bpShorts = dataManIO.DefineVariable<short>("bpShorts", shape, start, count); auto bpUShorts = dataManIO.DefineVariable<unsigned short>( "bpUShorts", shape, start, count); auto bpInts = dataManIO.DefineVariable<int>("bpInts", shape, start, count); auto bpUInts = dataManIO.DefineVariable<unsigned int>("bpUInts", shape, start, count); auto bpFloats = dataManIO.DefineVariable<float>("bpFloats", shape, start, count); auto bpDoubles = dataManIO.DefineVariable<double>("bpDoubles", shape, start, count); auto bpComplexes = dataManIO.DefineVariable<std::complex<float>>( "bpComplexes", shape, start, count); auto bpDComplexes = dataManIO.DefineVariable<std::complex<double>>( "bpDComplexes", shape, start, count); auto scalarInt = dataManIO.DefineVariable<int>("scalarInt"); auto stringVar = dataManIO.DefineVariable<std::string>("stringVar"); dataManIO.DefineAttribute<int>("AttInt", 110); adios2::Engine engine = dataManIO.Open(name, adios2::Mode::Write); for (int i = 0; i < steps; ++i) { engine.BeginStep(); GenData(myChars, i, start, count, shape); GenData(myUChars, i, start, count, shape); GenData(myShorts, i, start, count, shape); GenData(myUShorts, i, start, count, shape); GenData(myInts, i, start, count, shape); GenData(myUInts, i, start, count, shape); GenData(myFloats, i, start, count, shape); GenData(myDoubles, i, start, count, shape); GenData(myComplexes, i, start, count, shape); GenData(myDComplexes, i, start, count, shape); engine.Put(bpChars, myChars.data(), adios2::Mode::Sync); engine.Put(bpUChars, myUChars.data(), adios2::Mode::Sync); engine.Put(bpShorts, myShorts.data(), adios2::Mode::Sync); engine.Put(bpUShorts, myUShorts.data(), adios2::Mode::Sync); engine.Put(bpInts, myInts.data(), adios2::Mode::Sync); engine.Put(bpUInts, myUInts.data(), adios2::Mode::Sync); engine.Put(bpFloats, myFloats.data(), adios2::Mode::Sync); engine.Put(bpDoubles, myDoubles.data(), adios2::Mode::Sync); engine.Put(bpComplexes, myComplexes.data(), adios2::Mode::Sync); engine.Put(bpDComplexes, myDComplexes.data(), adios2::Mode::Sync); engine.Put(scalarInt, i); std::string s = "sample string sample string sample string"; engine.Put(stringVar, s); engine.EndStep(); } engine.Close(); } void Reader(const Dims &shape, const Dims &start, const Dims &count, const size_t steps, const adios2::Params &engineParams, const std::string &name) { adios2::ADIOS adios(mpiComm); adios2::IO dataManIO = adios.DeclareIO("Test"); dataManIO.SetEngine("ssc"); dataManIO.SetParameters(engineParams); adios2::Engine engine = dataManIO.Open(name, adios2::Mode::Read); size_t datasize = std::accumulate(count.begin(), count.end(), static_cast<size_t>(1), std::multiplies<size_t>()); std::vector<char> myChars(datasize); std::vector<unsigned char> myUChars(datasize); std::vector<short> myShorts(datasize); std::vector<unsigned short> myUShorts(datasize); std::vector<int> myInts(datasize); std::vector<unsigned int> myUInts(datasize); std::vector<float> myFloats(datasize); std::vector<double> myDoubles(datasize); std::vector<std::complex<float>> myComplexes(datasize); std::vector<std::complex<double>> myDComplexes(datasize); while (true) { adios2::StepStatus status = engine.BeginStep(StepMode::Read, 5); if (status == adios2::StepStatus::OK) { auto scalarInt = dataManIO.InquireVariable<int>("scalarInt"); auto blocksInfo = engine.BlocksInfo(scalarInt, engine.CurrentStep()); for (const auto &bi : blocksInfo) { ASSERT_EQ(bi.IsValue, true); ASSERT_EQ(bi.Value, engine.CurrentStep()); ASSERT_EQ(scalarInt.Min(), engine.CurrentStep()); ASSERT_EQ(scalarInt.Max(), engine.CurrentStep()); } const auto &vars = dataManIO.AvailableVariables(); ASSERT_EQ(vars.size(), 12); size_t currentStep = engine.CurrentStep(); adios2::Variable<char> bpChars = dataManIO.InquireVariable<char>("bpChars"); adios2::Variable<unsigned char> bpUChars = dataManIO.InquireVariable<unsigned char>("bpUChars"); adios2::Variable<short> bpShorts = dataManIO.InquireVariable<short>("bpShorts"); adios2::Variable<unsigned short> bpUShorts = dataManIO.InquireVariable<unsigned short>("bpUShorts"); adios2::Variable<int> bpInts = dataManIO.InquireVariable<int>("bpInts"); adios2::Variable<unsigned int> bpUInts = dataManIO.InquireVariable<unsigned int>("bpUInts"); adios2::Variable<float> bpFloats = dataManIO.InquireVariable<float>("bpFloats"); adios2::Variable<double> bpDoubles = dataManIO.InquireVariable<double>("bpDoubles"); adios2::Variable<std::complex<float>> bpComplexes = dataManIO.InquireVariable<std::complex<float>>("bpComplexes"); adios2::Variable<std::complex<double>> bpDComplexes = dataManIO.InquireVariable<std::complex<double>>("bpDComplexes"); adios2::Variable<std::string> stringVar = dataManIO.InquireVariable<std::string>("stringVar"); bpChars.SetSelection({start, count}); bpUChars.SetSelection({start, count}); bpShorts.SetSelection({start, count}); bpUShorts.SetSelection({start, count}); bpInts.SetSelection({start, count}); bpUInts.SetSelection({start, count}); bpFloats.SetSelection({start, count}); bpDoubles.SetSelection({start, count}); bpComplexes.SetSelection({start, count}); bpDComplexes.SetSelection({start, count}); engine.Get(bpChars, myChars.data(), adios2::Mode::Sync); engine.Get(bpUChars, myUChars.data(), adios2::Mode::Sync); engine.Get(bpShorts, myShorts.data(), adios2::Mode::Sync); engine.Get(bpUShorts, myUShorts.data(), adios2::Mode::Sync); engine.Get(bpInts, myInts.data(), adios2::Mode::Sync); engine.Get(bpUInts, myUInts.data(), adios2::Mode::Sync); engine.Get(bpFloats, myFloats.data(), adios2::Mode::Sync); engine.Get(bpDoubles, myDoubles.data(), adios2::Mode::Sync); engine.Get(bpComplexes, myComplexes.data(), adios2::Mode::Sync); engine.Get(bpDComplexes, myDComplexes.data(), adios2::Mode::Sync); std::string s; engine.Get(stringVar, s); ASSERT_EQ(s, "sample string sample string sample string"); ASSERT_EQ(stringVar.Min(), "sample string sample string sample string"); ASSERT_EQ(stringVar.Max(), "sample string sample string sample string"); int i; engine.Get(scalarInt, &i); ASSERT_EQ(i, currentStep); VerifyData(myChars.data(), currentStep, start, count, shape, mpiRank); VerifyData(myUChars.data(), currentStep, start, count, shape, mpiRank); VerifyData(myShorts.data(), currentStep, start, count, shape, mpiRank); VerifyData(myUShorts.data(), currentStep, start, count, shape, mpiRank); VerifyData(myInts.data(), currentStep, start, count, shape, mpiRank); VerifyData(myUInts.data(), currentStep, start, count, shape, mpiRank); VerifyData(myFloats.data(), currentStep, start, count, shape, mpiRank); VerifyData(myDoubles.data(), currentStep, start, count, shape, mpiRank); VerifyData(myComplexes.data(), currentStep, start, count, shape, mpiRank); VerifyData(myDComplexes.data(), currentStep, start, count, shape, mpiRank); engine.EndStep(); } else if (status == adios2::StepStatus::EndOfStream) { std::cout << "[Rank " + std::to_string(mpiRank) + "] SscTest reader end of stream!" << std::endl; break; } } auto attInt = dataManIO.InquireAttribute<int>("AttInt"); std::cout << "[Rank " + std::to_string(mpiRank) + "] Attribute received " << attInt.Data()[0] << ", expected 110" << std::endl; ASSERT_EQ(110, attInt.Data()[0]); ASSERT_NE(111, attInt.Data()[0]); engine.Close(); } TEST_F(SscEngineTest, TestSscBaseUnlocked) { std::string filename = "TestSscBaseUnlocked"; adios2::Params engineParams = {}; int worldRank, worldSize; MPI_Comm_rank(MPI_COMM_WORLD, &worldRank); MPI_Comm_size(MPI_COMM_WORLD, &worldSize); int mpiGroup = worldRank / (worldSize / 2); MPI_Comm_split(MPI_COMM_WORLD, mpiGroup, worldRank, &mpiComm); MPI_Comm_rank(mpiComm, &mpiRank); MPI_Comm_size(mpiComm, &mpiSize); Dims shape = {10, (size_t)mpiSize * 2}; Dims start = {2, (size_t)mpiRank * 2}; Dims count = {5, 2}; size_t steps = 10; if (mpiGroup == 0) { Writer(shape, start, count, steps, engineParams, filename); } std::this_thread::sleep_for(std::chrono::milliseconds(1)); if (mpiGroup == 1) { Reader(shape, start, count, steps, engineParams, filename); } MPI_Barrier(MPI_COMM_WORLD); } int main(int argc, char **argv) { MPI_Init(&argc, &argv); int worldRank, worldSize; MPI_Comm_rank(MPI_COMM_WORLD, &worldRank); MPI_Comm_size(MPI_COMM_WORLD, &worldSize); ::testing::InitGoogleTest(&argc, argv); int result = RUN_ALL_TESTS(); MPI_Finalize(); return result; } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2020 ArangoDB GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Simon Grätzer //////////////////////////////////////////////////////////////////////////////// #include "gtest/gtest.h" #include "AqlExecutorTestCase.h" #include "AqlItemBlockHelper.h" #include "Aql/AqlCall.h" #include "Aql/AqlItemBlock.h" #include "Aql/Collection.h" #include "Aql/ExecutionEngine.h" #include "Aql/WindowExecutor.h" #include "Aql/OutputAqlItemRow.h" #include "Aql/Query.h" #include "Aql/RegisterPlan.h" #include "Aql/SingleRowFetcher.h" #include "Mocks/Servers.h" #include "Transaction/Context.h" #include "Transaction/Methods.h" #include <velocypack/Builder.h> #include <velocypack/velocypack-aliases.h> #include <chrono> #include <functional> using namespace arangodb; using namespace arangodb::aql; namespace arangodb { namespace tests { namespace aql { // This is only to get a split-type. The Type is independent of actual template parameters using WindowTestHelper = ExecutorTestHelper<1, 1>; using WindowSplitType = WindowTestHelper::SplitType; using WindowInputParam = std::tuple<WindowSplitType, bool>; template <size_t... vs> const WindowSplitType splitIntoBlocks = WindowSplitType{std::vector<std::size_t>{vs...}}; template <size_t step> const WindowSplitType splitStep = WindowSplitType{step}; struct WindowInput { WindowBounds bounds; RegisterId rangeReg; std::string name; // aggregation function RegisterId inReg; // aggregation in register MatrixBuilder<2> input; MatrixBuilder<3> expectedOutput; }; std::ostream& operator<<(std::ostream& out, WindowInput const& agg) { VPackBuilder b; b.openObject(); agg.bounds.toVelocyPack(b); b.close(); out << b.toJson() << " "; out << agg.name; if (agg.inReg != RegisterPlan::MaxRegisterId) { out << " reg: " << agg.inReg; } return out; } using WindowAggregateInputParam = std::tuple<WindowSplitType, WindowInput>; class WindowExecutorTest : public AqlExecutorTestCaseWithParam<WindowAggregateInputParam> { protected: auto getSplit() -> WindowSplitType { auto [split, unused] = GetParam(); return split; } auto getWindowParams() -> WindowInput const& { auto const& [unused, info] = GetParam(); return info; } auto buildRegisterInfos(RegisterId nrInputRegisters, RegisterId nrOutputRegisters) -> RegisterInfos { RegIdSet registersToClear{}; RegIdSetStack registersToKeep{{}}; auto readableInputRegisters = RegIdSet{}; auto writeableOutputRegisters = RegIdSet{}; RegIdSet toKeep; for (RegisterId i = 0; i < nrInputRegisters; ++i) { // All registers need to be kept! toKeep.emplace(i); } registersToKeep.emplace_back(std::move(toKeep)); WindowInput const& input = getWindowParams(); if (input.inReg != RegisterPlan::MaxRegisterId) { readableInputRegisters.emplace(input.inReg); } if (input.rangeReg != RegisterPlan::MaxRegisterId) { readableInputRegisters.emplace(input.rangeReg); } writeableOutputRegisters.emplace(2); // same as in buildExecutorInfos() return RegisterInfos{std::move(readableInputRegisters), std::move(writeableOutputRegisters), nrInputRegisters, nrOutputRegisters, registersToClear, registersToKeep}; }; auto buildExecutorInfos() -> WindowExecutorInfos { WindowInput const& input = getWindowParams(); std::vector<std::string> aggregateTypes{input.name}; std::vector<std::pair<RegisterId, RegisterId>> aggregateRegisters{{2, input.inReg}}; return WindowExecutorInfos(input.bounds, input.rangeReg, std::move(aggregateTypes), std::move(aggregateRegisters), warnings, &VPackOptions::Defaults); }; arangodb::aql::QueryWarnings warnings; }; /** * Input used: * * [ * [1, 5] * [1, 1] * [2, 2] * [1, 5] * [6, 1] * [2, 2] * [3, 1] * ] * sorted: * [ * [1, 5] * [1, 1] * [1, 5] * [2, 2] * [2, 2] * [3, 1] * [6, 1] * ] */ /** * TODO: * [] Add tests for all aggregate functions */ auto inputRows = MatrixBuilder<2>{RowBuilder<2>{1, 5}, RowBuilder<2>{1, 1}, RowBuilder<2>{2, 2}, RowBuilder<2>{1, 5}, RowBuilder<2>{6, 1}, RowBuilder<2>{2, 2}, RowBuilder<2>{3, 1}}; auto sortedRows = MatrixBuilder<2>{RowBuilder<2>{1, 5}, RowBuilder<2>{1, 1}, RowBuilder<2>{1, 5}, RowBuilder<2>{2, 2}, RowBuilder<2>{2, 2}, RowBuilder<2>{3, 1}, RowBuilder<2>{6, 1}}; int t0 = 698976; // 01/09/1970 int t1 = t0 + 1 * 01 * 02 * 1000; //+ 2s int t2 = t1 + 1 * 05 * 60 * 1000; //+ 5m int t3 = t2 + 1 * 10 * 60 * 1000; //+ 10m int t4 = t3 + 1 * 60 * 60 * 1000; //+ 1h int t5 = t4 + 5 * 60 * 60 * 1000; //+ 5h auto sortedDateRows = MatrixBuilder<2>{RowBuilder<2>{t0, 5}, RowBuilder<2>{t1, 1}, RowBuilder<2>{t2, 5}, RowBuilder<2>{t3, 2}, RowBuilder<2>{t4, 2}, RowBuilder<2>{t5, 1}, RowBuilder<2>{t5, 1}}; auto inf = VPackParser::fromJson("\"inf\""); auto duration1h10m = VPackParser::fromJson("\"PT1H10M\""); auto duration3s = VPackParser::fromJson("\"PT3S\""); auto boundsRow1 = WindowBounds(WindowBounds::Type::Row, AqlValue(AqlValueHintInt(1)), AqlValue(AqlValueHintInt(1))); auto boundsRowAccum = WindowBounds(WindowBounds::Type::Row, AqlValue(inf->slice()), AqlValue(AqlValueHintInt(0))); auto boundsRange1 = WindowBounds(WindowBounds::Type::Range, AqlValue(AqlValueHintInt(1)), AqlValue(AqlValueHintInt(1))); auto boundsRangeP3 = WindowBounds(WindowBounds::Type::Range, AqlValue(AqlValueHintInt(3)), AqlValue(AqlValueHintInt(0))); //auto boundsDateRange = WindowBounds(WindowBounds::Type::Range, AqlValue(duration1h10m->slice()), AqlValue(duration3s->slice())); auto WindowInputs = ::testing::Values(WindowInput{boundsRow1, RegisterPlan::MaxRegisterId, "SUM", 0, inputRows, {{1, 5, 2}, {1, 1, 4}, {2, 2, 4}, {1, 5, 9}, {6, 1, 9}, {2, 2, 11}, {3, 1, 5}}}, WindowInput{boundsRow1, RegisterPlan::MaxRegisterId, "SUM", 1, inputRows, {{1, 5, 6}, {1, 1, 8}, {2, 2, 8}, {1, 5, 8}, {6, 1, 8}, {2, 2, 4}, {3, 1, 3}}}, WindowInput{boundsRow1, RegisterPlan::MaxRegisterId, "MAX", 1, inputRows, {{1, 5, 5}, {1, 1, 5}, {2, 2, 5}, {1, 5, 5}, {6, 1, 5}, {2, 2, 2}, {3, 1, 2}}}, WindowInput{boundsRow1, RegisterPlan::MaxRegisterId, "MIN", 0, inputRows, {{1, 5, 1}, {1, 1, 1}, {2, 2, 1}, {1, 5, 1}, {6, 1, 1}, {2, 2, 2}, {3, 1, 2}}}, WindowInput{boundsRowAccum, RegisterPlan::MaxRegisterId, "SUM", 0, inputRows, {{1, 5, 1}, {1, 1, 2}, {2, 2, 4}, {1, 5, 5}, {6, 1, 11}, {2, 2, 13}, {3, 1, 16}}}, WindowInput{boundsRowAccum, RegisterPlan::MaxRegisterId, "MAX", 0, inputRows, {{1, 5, 1}, {1, 1, 1}, {2, 2, 2}, {1, 5, 2}, {6, 1, 6}, {2, 2, 6}, {3, 1, 6}}}, WindowInput{boundsRowAccum, RegisterPlan::MaxRegisterId, "MIN", 0, inputRows, {{1, 5, 1}, {1, 1, 1}, {2, 2, 1}, {1, 5, 1}, {6, 1, 1}, {2, 2, 1}, {3, 1, 1}}}, // range based input, offset of one each way WindowInput{boundsRange1, 0, "SUM", 1, sortedRows, {{1, 5, 15}, {1, 1, 15}, { 1, 5, 15}, {2, 2, 16}, {2, 2, 16}, {3, 1, 5}, {6, 1, 1}}}, WindowInput{boundsRange1, 0, "MIN", 1, sortedRows, {{1, 5, 1}, {1, 1, 1}, { 1, 5, 1}, {2, 2, 1}, {2, 2, 1}, {3, 1, 1}, {6, 1, 1}}}, // range based input, offset of offset 3 preceding WindowInput{boundsRangeP3, 0, "SUM", 1, sortedRows, {{1, 5, 11}, {1, 1, 11}, { 1, 5, 11}, {2, 2, 15}, {2, 2, 15}, {3, 1, 16}, {6, 1, 2}}}, WindowInput{boundsRangeP3, 0, "SUM", 1, sortedRows, {{1, 5, 11}, {1, 1, 11}, { 1, 5, 11}, {2, 2, 15}, {2, 2, 15}, {3, 1, 16}, {6, 1, 2}}} // TODO: fix ISO duration regex to enable date range test //WindowInput{boundsDateRange, 0, "SUM", 1, sortedRows, {{t0, 5, 6}, {t1, 1, 6}, { t2, 5, 11}, {t3, 2, 13}, {t4, 2, 15}, {t5, 1, 3}, {t5, 1, 1}}} ); INSTANTIATE_TEST_CASE_P(Window, WindowExecutorTest, ::testing::Combine(::testing::Values(splitIntoBlocks<2, 3>, splitIntoBlocks<3, 4>, splitStep<1>, splitStep<2>), WindowInputs)); TEST_P(WindowExecutorTest, runWindowExecutor) { auto const& params = getWindowParams(); // range based variant needs sorted input auto registerInfos = buildRegisterInfos(2, 3); auto executorInfos = buildExecutorInfos(); AqlCall call{}; // unlimited produce ExecutionStats stats{}; // No stats here makeExecutorTestHelper<2, 3>() .addConsumer<WindowExecutor>(std::move(registerInfos), std::move(executorInfos)) .setInputValue(params.input) .setInputSplitType(getSplit()) .setCall(call) .expectOutput({0, 1, 2}, getWindowParams().expectedOutput) .allowAnyOutputOrder(false) .expectSkipped(0) .expectedState(ExecutionState::DONE) // .expectedStats(stats) .run(/*loop*/true); } // test AccuWindowExecutor TEST_P(WindowExecutorTest, runAccuWindowExecutor) { auto const& params = getWindowParams(); if (!params.bounds.unboundedPreceding()) { return; // skip } // range based variant needs sorted input // AccuWindowExecutor is passthrough, needs 3 input registers MatrixBuilder<3> passthroughInput; for (auto const& r : params.input) { passthroughInput.emplace_back(RowBuilder<3>{r[0], r[1], NoneEntry{}}); } auto registerInfos = buildRegisterInfos(3, 3); auto executorInfos = buildExecutorInfos(); AqlCall call{}; // unlimited produce ExecutionStats stats{}; // No stats here makeExecutorTestHelper<3, 3>() .addConsumer<AccuWindowExecutor>(std::move(registerInfos), std::move(executorInfos)) .setInputValue(std::move(passthroughInput)) .setInputSplitType(getSplit()) .setCall(call) .expectOutput({0, 1, 2}, params.expectedOutput) .allowAnyOutputOrder(false) .expectSkipped(0) .expectedState(ExecutionState::DONE) // .expectedStats(stats) .run(/*loop*/true); } } // namespace aql } // namespace tests } // namespace arangodb <commit_msg>fix init order fiasco in test<commit_after>//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2020 ArangoDB GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Simon Grätzer //////////////////////////////////////////////////////////////////////////////// #include "gtest/gtest.h" #include "AqlExecutorTestCase.h" #include "AqlItemBlockHelper.h" #include "Aql/AqlCall.h" #include "Aql/AqlItemBlock.h" #include "Aql/Collection.h" #include "Aql/ExecutionEngine.h" #include "Aql/WindowExecutor.h" #include "Aql/OutputAqlItemRow.h" #include "Aql/Query.h" #include "Aql/RegisterPlan.h" #include "Aql/SingleRowFetcher.h" #include "Mocks/Servers.h" #include "Transaction/Context.h" #include "Transaction/Methods.h" #include <velocypack/Builder.h> #include <velocypack/velocypack-aliases.h> #include <chrono> #include <functional> using namespace arangodb; using namespace arangodb::aql; namespace arangodb { namespace tests { namespace aql { // This is only to get a split-type. The Type is independent of actual template parameters using WindowTestHelper = ExecutorTestHelper<1, 1>; using WindowSplitType = WindowTestHelper::SplitType; using WindowInputParam = std::tuple<WindowSplitType, bool>; template <size_t... vs> const WindowSplitType splitIntoBlocks = WindowSplitType{std::vector<std::size_t>{vs...}}; template <size_t step> const WindowSplitType splitStep = WindowSplitType{step}; struct WindowInput { WindowBounds bounds; RegisterId rangeReg; std::string name; // aggregation function RegisterId inReg; // aggregation in register MatrixBuilder<2> input; MatrixBuilder<3> expectedOutput; }; std::ostream& operator<<(std::ostream& out, WindowInput const& agg) { VPackBuilder b; b.openObject(); agg.bounds.toVelocyPack(b); b.close(); out << b.toJson() << " "; out << agg.name; if (agg.inReg != RegisterPlan::MaxRegisterId) { out << " reg: " << agg.inReg; } return out; } using WindowAggregateInputParam = std::tuple<WindowSplitType, WindowInput>; class WindowExecutorTest : public AqlExecutorTestCaseWithParam<WindowAggregateInputParam> { protected: auto getSplit() -> WindowSplitType { auto [split, unused] = GetParam(); return split; } auto getWindowParams() -> WindowInput const& { auto const& [unused, info] = GetParam(); return info; } auto buildRegisterInfos(RegisterId nrInputRegisters, RegisterId nrOutputRegisters) -> RegisterInfos { RegIdSet registersToClear{}; RegIdSetStack registersToKeep{{}}; auto readableInputRegisters = RegIdSet{}; auto writeableOutputRegisters = RegIdSet{}; RegIdSet toKeep; for (RegisterId i = 0; i < nrInputRegisters; ++i) { // All registers need to be kept! toKeep.emplace(i); } registersToKeep.emplace_back(std::move(toKeep)); WindowInput const& input = getWindowParams(); if (input.inReg != RegisterPlan::MaxRegisterId) { readableInputRegisters.emplace(input.inReg); } if (input.rangeReg != RegisterPlan::MaxRegisterId) { readableInputRegisters.emplace(input.rangeReg); } writeableOutputRegisters.emplace(2); // same as in buildExecutorInfos() return RegisterInfos{std::move(readableInputRegisters), std::move(writeableOutputRegisters), nrInputRegisters, nrOutputRegisters, registersToClear, registersToKeep}; }; auto buildExecutorInfos() -> WindowExecutorInfos { WindowInput const& input = getWindowParams(); std::vector<std::string> aggregateTypes{input.name}; std::vector<std::pair<RegisterId, RegisterId>> aggregateRegisters{{2, input.inReg}}; return WindowExecutorInfos(input.bounds, input.rangeReg, std::move(aggregateTypes), std::move(aggregateRegisters), warnings, &VPackOptions::Defaults); }; arangodb::aql::QueryWarnings warnings; }; /** * Input used: * * [ * [1, 5] * [1, 1] * [2, 2] * [1, 5] * [6, 1] * [2, 2] * [3, 1] * ] * sorted: * [ * [1, 5] * [1, 1] * [1, 5] * [2, 2] * [2, 2] * [3, 1] * [6, 1] * ] */ /** * TODO: * [] Add tests for all aggregate functions */ auto inputRows = MatrixBuilder<2>{RowBuilder<2>{1, 5}, RowBuilder<2>{1, 1}, RowBuilder<2>{2, 2}, RowBuilder<2>{1, 5}, RowBuilder<2>{6, 1}, RowBuilder<2>{2, 2}, RowBuilder<2>{3, 1}}; auto sortedRows = MatrixBuilder<2>{RowBuilder<2>{1, 5}, RowBuilder<2>{1, 1}, RowBuilder<2>{1, 5}, RowBuilder<2>{2, 2}, RowBuilder<2>{2, 2}, RowBuilder<2>{3, 1}, RowBuilder<2>{6, 1}}; int t0 = 698976; // 01/09/1970 int t1 = t0 + 1 * 01 * 02 * 1000; //+ 2s int t2 = t1 + 1 * 05 * 60 * 1000; //+ 5m int t3 = t2 + 1 * 10 * 60 * 1000; //+ 10m int t4 = t3 + 1 * 60 * 60 * 1000; //+ 1h int t5 = t4 + 5 * 60 * 60 * 1000; //+ 5h auto sortedDateRows = MatrixBuilder<2>{RowBuilder<2>{t0, 5}, RowBuilder<2>{t1, 1}, RowBuilder<2>{t2, 5}, RowBuilder<2>{t3, 2}, RowBuilder<2>{t4, 2}, RowBuilder<2>{t5, 1}, RowBuilder<2>{t5, 1}}; auto vpackOptions = VPackOptions(); auto inf = VPackParser::fromJson("\"inf\"", &vpackOptions); auto duration1h10m = VPackParser::fromJson("\"PT1H10M\"", &vpackOptions); auto duration3s = VPackParser::fromJson("\"PT3S\"", &vpackOptions); auto boundsRow1 = WindowBounds(WindowBounds::Type::Row, AqlValue(AqlValueHintInt(1)), AqlValue(AqlValueHintInt(1))); auto boundsRowAccum = WindowBounds(WindowBounds::Type::Row, AqlValue(inf->slice()), AqlValue(AqlValueHintInt(0))); auto boundsRange1 = WindowBounds(WindowBounds::Type::Range, AqlValue(AqlValueHintInt(1)), AqlValue(AqlValueHintInt(1))); auto boundsRangeP3 = WindowBounds(WindowBounds::Type::Range, AqlValue(AqlValueHintInt(3)), AqlValue(AqlValueHintInt(0))); //auto boundsDateRange = WindowBounds(WindowBounds::Type::Range, AqlValue(duration1h10m->slice()), AqlValue(duration3s->slice())); auto WindowInputs = ::testing::Values(WindowInput{boundsRow1, RegisterPlan::MaxRegisterId, "SUM", 0, inputRows, {{1, 5, 2}, {1, 1, 4}, {2, 2, 4}, {1, 5, 9}, {6, 1, 9}, {2, 2, 11}, {3, 1, 5}}}, WindowInput{boundsRow1, RegisterPlan::MaxRegisterId, "SUM", 1, inputRows, {{1, 5, 6}, {1, 1, 8}, {2, 2, 8}, {1, 5, 8}, {6, 1, 8}, {2, 2, 4}, {3, 1, 3}}}, WindowInput{boundsRow1, RegisterPlan::MaxRegisterId, "MAX", 1, inputRows, {{1, 5, 5}, {1, 1, 5}, {2, 2, 5}, {1, 5, 5}, {6, 1, 5}, {2, 2, 2}, {3, 1, 2}}}, WindowInput{boundsRow1, RegisterPlan::MaxRegisterId, "MIN", 0, inputRows, {{1, 5, 1}, {1, 1, 1}, {2, 2, 1}, {1, 5, 1}, {6, 1, 1}, {2, 2, 2}, {3, 1, 2}}}, WindowInput{boundsRowAccum, RegisterPlan::MaxRegisterId, "SUM", 0, inputRows, {{1, 5, 1}, {1, 1, 2}, {2, 2, 4}, {1, 5, 5}, {6, 1, 11}, {2, 2, 13}, {3, 1, 16}}}, WindowInput{boundsRowAccum, RegisterPlan::MaxRegisterId, "MAX", 0, inputRows, {{1, 5, 1}, {1, 1, 1}, {2, 2, 2}, {1, 5, 2}, {6, 1, 6}, {2, 2, 6}, {3, 1, 6}}}, WindowInput{boundsRowAccum, RegisterPlan::MaxRegisterId, "MIN", 0, inputRows, {{1, 5, 1}, {1, 1, 1}, {2, 2, 1}, {1, 5, 1}, {6, 1, 1}, {2, 2, 1}, {3, 1, 1}}}, // range based input, offset of one each way WindowInput{boundsRange1, 0, "SUM", 1, sortedRows, {{1, 5, 15}, {1, 1, 15}, { 1, 5, 15}, {2, 2, 16}, {2, 2, 16}, {3, 1, 5}, {6, 1, 1}}}, WindowInput{boundsRange1, 0, "MIN", 1, sortedRows, {{1, 5, 1}, {1, 1, 1}, { 1, 5, 1}, {2, 2, 1}, {2, 2, 1}, {3, 1, 1}, {6, 1, 1}}}, // range based input, offset of offset 3 preceding WindowInput{boundsRangeP3, 0, "SUM", 1, sortedRows, {{1, 5, 11}, {1, 1, 11}, { 1, 5, 11}, {2, 2, 15}, {2, 2, 15}, {3, 1, 16}, {6, 1, 2}}}, WindowInput{boundsRangeP3, 0, "SUM", 1, sortedRows, {{1, 5, 11}, {1, 1, 11}, { 1, 5, 11}, {2, 2, 15}, {2, 2, 15}, {3, 1, 16}, {6, 1, 2}}} // TODO: fix ISO duration regex to enable date range test //WindowInput{boundsDateRange, 0, "SUM", 1, sortedRows, {{t0, 5, 6}, {t1, 1, 6}, { t2, 5, 11}, {t3, 2, 13}, {t4, 2, 15}, {t5, 1, 3}, {t5, 1, 1}}} ); INSTANTIATE_TEST_CASE_P(Window, WindowExecutorTest, ::testing::Combine(::testing::Values(splitIntoBlocks<2, 3>, splitIntoBlocks<3, 4>, splitStep<1>, splitStep<2>), WindowInputs)); TEST_P(WindowExecutorTest, runWindowExecutor) { auto const& params = getWindowParams(); // range based variant needs sorted input auto registerInfos = buildRegisterInfos(2, 3); auto executorInfos = buildExecutorInfos(); AqlCall call{}; // unlimited produce ExecutionStats stats{}; // No stats here makeExecutorTestHelper<2, 3>() .addConsumer<WindowExecutor>(std::move(registerInfos), std::move(executorInfos)) .setInputValue(params.input) .setInputSplitType(getSplit()) .setCall(call) .expectOutput({0, 1, 2}, getWindowParams().expectedOutput) .allowAnyOutputOrder(false) .expectSkipped(0) .expectedState(ExecutionState::DONE) // .expectedStats(stats) .run(/*loop*/true); } // test AccuWindowExecutor TEST_P(WindowExecutorTest, runAccuWindowExecutor) { auto const& params = getWindowParams(); if (!params.bounds.unboundedPreceding()) { return; // skip } // range based variant needs sorted input // AccuWindowExecutor is passthrough, needs 3 input registers MatrixBuilder<3> passthroughInput; for (auto const& r : params.input) { passthroughInput.emplace_back(RowBuilder<3>{r[0], r[1], NoneEntry{}}); } auto registerInfos = buildRegisterInfos(3, 3); auto executorInfos = buildExecutorInfos(); AqlCall call{}; // unlimited produce ExecutionStats stats{}; // No stats here makeExecutorTestHelper<3, 3>() .addConsumer<AccuWindowExecutor>(std::move(registerInfos), std::move(executorInfos)) .setInputValue(std::move(passthroughInput)) .setInputSplitType(getSplit()) .setCall(call) .expectOutput({0, 1, 2}, params.expectedOutput) .allowAnyOutputOrder(false) .expectSkipped(0) .expectedState(ExecutionState::DONE) // .expectedStats(stats) .run(/*loop*/true); } } // namespace aql } // namespace tests } // namespace arangodb <|endoftext|>
<commit_before>#include <QtCore/QDebug> #include <QtCore/QTimer> #include <QtDBus/QtDBus> #include <QtTest/QtTest> #include <QDateTime> #include <QString> #include <QVariantMap> #include <TelepathyQt4/Account> #include <TelepathyQt4/AccountManager> #include <TelepathyQt4/Debug> #include <TelepathyQt4/PendingAccount> #include <TelepathyQt4/PendingReady> #include <TelepathyQt4/Types> #include <telepathy-glib/debug.h> #include <glib-object.h> #include <dbus/dbus-glib.h> #include <tests/lib/glib/contacts-conn.h> #include <tests/lib/glib/echo/chan.h> #include <tests/lib/test.h> using namespace Tp; using namespace Tp::Client; class CDMessagesAdaptor : public QDBusAbstractAdaptor { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "org.freedesktop.Telepathy.ChannelDispatcher.Interface.Messages") Q_CLASSINFO("D-Bus Introspection", "" " <interface name=\"org.freedesktop.Telepathy.ChannelDispatcher.Interface.Messages.DRAFT\" >\n" " <method name=\"Send\" >\n" " <arg name=\"Account\" type=\"o\" direction=\"in\" />\n" " <arg name=\"TargetID\" type=\"s\" direction=\"in\" />\n" " <arg name=\"Message\" type=\"aa{sv}\" direction=\"in\" />\n" " <arg name=\"Flags\" type=\"u\" direction=\"in\" />\n" " <arg name=\"Token\" type=\"s\" direction=\"out\" />\n" " </method>\n" " </interface>\n" "") public: CDMessagesAdaptor(const QDBusConnection &bus, QObject *parent) : QDBusAbstractAdaptor(parent), mBus(bus) { } virtual ~CDMessagesAdaptor() { } public Q_SLOTS: // Methods QString Send(const QDBusObjectPath &account, const QString &targetID, const MessagePartList &message, uint flags) { // TODO implement return QString(); } Q_SIGNALS: void Status(const QDBusObjectPath &account, const QString &token, uint status, const QString &error); private: QDBusConnection mBus; }; class TestContactMessenger : public Test { Q_OBJECT public: TestContactMessenger(QObject *parent = 0) : Test(parent), mCDMessagesAdaptor(0) { } private Q_SLOTS: void initTestCase(); void init(); void cleanup(); void cleanupTestCase(); private: AccountManagerPtr mAM; AccountPtr mAccount; CDMessagesAdaptor *mCDMessagesAdaptor; }; void TestContactMessenger::initTestCase() { initTestCaseImpl(); g_type_init(); g_set_prgname("contact-messenger"); tp_debug_set_flags("all"); dbus_g_bus_get(DBUS_BUS_STARTER, 0); QDBusConnection bus = QDBusConnection::sessionBus(); QString channelDispatcherBusName = QLatin1String(TELEPATHY_INTERFACE_CHANNEL_DISPATCHER); QString channelDispatcherPath = QLatin1String("/org/freedesktop/Telepathy/ChannelDispatcher"); QObject *dispatcher = new QObject(this); mCDMessagesAdaptor = new CDMessagesAdaptor(bus, dispatcher); QVERIFY(bus.registerService(channelDispatcherBusName)); QVERIFY(bus.registerObject(channelDispatcherPath, dispatcher)); mAM = AccountManager::create(); QVERIFY(connect(mAM->becomeReady(), SIGNAL(finished(Tp::PendingOperation *)), SLOT(expectSuccessfulCall(Tp::PendingOperation *)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(mAM->isReady(), true); QVariantMap parameters; parameters[QLatin1String("account")] = QLatin1String("foobar"); PendingAccount *pacc = mAM->createAccount(QLatin1String("foo"), QLatin1String("bar"), QLatin1String("foobar"), parameters); QVERIFY(connect(pacc, SIGNAL(finished(Tp::PendingOperation *)), SLOT(expectSuccessfulCall(Tp::PendingOperation *)))); QCOMPARE(mLoop->exec(), 0); QVERIFY(pacc->account()); mAccount = pacc->account(); QVERIFY(connect(mAccount->becomeReady(), SIGNAL(finished(Tp::PendingOperation *)), SLOT(expectSuccessfulCall(Tp::PendingOperation *)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(mAccount->isReady(), true); QCOMPARE(mAccount->supportsRequestHints(), false); QCOMPARE(mAccount->requestsSucceedWithChannel(), false); } void TestContactMessenger::init() { initImpl(); } void TestContactMessenger::cleanup() { cleanupImpl(); } void TestContactMessenger::cleanupTestCase() { cleanupTestCaseImpl(); } QTEST_MAIN(TestContactMessenger) #include "_gen/contact-messenger.cpp.moc.hpp" <commit_msg>TestContactMessenger: Test for no CD support<commit_after>#include <QtCore/QDebug> #include <QtCore/QTimer> #include <QtDBus/QtDBus> #include <QtTest/QtTest> #include <QDateTime> #include <QString> #include <QVariantMap> #include <TelepathyQt4/Account> #include <TelepathyQt4/AccountManager> #include <TelepathyQt4/ContactMessenger> #include <TelepathyQt4/Debug> #include <TelepathyQt4/Message> #include <TelepathyQt4/MessageContentPart> #include <TelepathyQt4/PendingAccount> #include <TelepathyQt4/PendingReady> #include <TelepathyQt4/PendingSendMessage> #include <TelepathyQt4/Types> #include <telepathy-glib/debug.h> #include <glib-object.h> #include <dbus/dbus-glib.h> #include <tests/lib/glib/contacts-conn.h> #include <tests/lib/glib/echo/chan.h> #include <tests/lib/test.h> using namespace Tp; using namespace Tp::Client; class CDMessagesAdaptor : public QDBusAbstractAdaptor { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "org.freedesktop.Telepathy.ChannelDispatcher.Interface.Messages") Q_CLASSINFO("D-Bus Introspection", "" " <interface name=\"org.freedesktop.Telepathy.ChannelDispatcher.Interface.Messages.DRAFT\" >\n" " <method name=\"Send\" >\n" " <arg name=\"Account\" type=\"o\" direction=\"in\" />\n" " <arg name=\"TargetID\" type=\"s\" direction=\"in\" />\n" " <arg name=\"Message\" type=\"aa{sv}\" direction=\"in\" />\n" " <arg name=\"Flags\" type=\"u\" direction=\"in\" />\n" " <arg name=\"Token\" type=\"s\" direction=\"out\" />\n" " </method>\n" " </interface>\n" "") public: CDMessagesAdaptor(const QDBusConnection &bus, QObject *parent) : QDBusAbstractAdaptor(parent), mBus(bus) { } virtual ~CDMessagesAdaptor() { } void setSimulatedSendError(const QString &error) { mSimulatedSendError = error; } public Q_SLOTS: // Methods QString Send(const QDBusObjectPath &account, const QString &targetID, const MessagePartList &message, uint flags) { if (!mSimulatedSendError.isEmpty()) { dynamic_cast<QDBusContext *>(parent())->sendErrorReply(mSimulatedSendError, QLatin1String("Let's pretend this interface and method don't exist, shall we?")); return QString(); } // TODO implement return QString(); } Q_SIGNALS: void Status(const QDBusObjectPath &account, const QString &token, uint status, const QString &error); private: QDBusConnection mBus; QString mSimulatedSendError; }; class Dispatcher : public QObject, public QDBusContext { Q_OBJECT; public: Dispatcher(QObject *parent) : QObject(parent) { } ~Dispatcher() { } }; class TestContactMessenger : public Test { Q_OBJECT public: TestContactMessenger(QObject *parent = 0) : Test(parent), mCDMessagesAdaptor(0) { } private Q_SLOTS: void initTestCase(); void init(); void testNoSupport(); void cleanup(); void cleanupTestCase(); private: AccountManagerPtr mAM; AccountPtr mAccount; CDMessagesAdaptor *mCDMessagesAdaptor; }; void TestContactMessenger::initTestCase() { initTestCaseImpl(); g_type_init(); g_set_prgname("contact-messenger"); tp_debug_set_flags("all"); dbus_g_bus_get(DBUS_BUS_STARTER, 0); QDBusConnection bus = QDBusConnection::sessionBus(); QString channelDispatcherBusName = QLatin1String(TELEPATHY_INTERFACE_CHANNEL_DISPATCHER); QString channelDispatcherPath = QLatin1String("/org/freedesktop/Telepathy/ChannelDispatcher"); Dispatcher *dispatcher = new Dispatcher(this); mCDMessagesAdaptor = new CDMessagesAdaptor(bus, dispatcher); QVERIFY(bus.registerService(channelDispatcherBusName)); QVERIFY(bus.registerObject(channelDispatcherPath, dispatcher)); mAM = AccountManager::create(); QVERIFY(connect(mAM->becomeReady(), SIGNAL(finished(Tp::PendingOperation *)), SLOT(expectSuccessfulCall(Tp::PendingOperation *)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(mAM->isReady(), true); QVariantMap parameters; parameters[QLatin1String("account")] = QLatin1String("foobar"); PendingAccount *pacc = mAM->createAccount(QLatin1String("foo"), QLatin1String("bar"), QLatin1String("foobar"), parameters); QVERIFY(connect(pacc, SIGNAL(finished(Tp::PendingOperation *)), SLOT(expectSuccessfulCall(Tp::PendingOperation *)))); QCOMPARE(mLoop->exec(), 0); QVERIFY(pacc->account()); mAccount = pacc->account(); QVERIFY(connect(mAccount->becomeReady(), SIGNAL(finished(Tp::PendingOperation *)), SLOT(expectSuccessfulCall(Tp::PendingOperation *)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(mAccount->isReady(), true); QCOMPARE(mAccount->supportsRequestHints(), false); QCOMPARE(mAccount->requestsSucceedWithChannel(), false); } void TestContactMessenger::init() { initImpl(); mCDMessagesAdaptor->setSimulatedSendError(QString()); } void TestContactMessenger::testNoSupport() { // We should give a descriptive error message if the CD doesn't actually support sending // messages using the new API. NotImplemented should probably be documented for the // sendMessage() methods as an indication that the CD implementation needs to be upgraded. ContactMessengerPtr messenger = ContactMessenger::create(mAccount, QLatin1String("Ann")); QVERIFY(!messenger.isNull()); mCDMessagesAdaptor->setSimulatedSendError(TP_QT4_DBUS_ERROR_UNKNOWN_METHOD); PendingSendMessage *pendingSend = messenger->sendMessage(QLatin1String("Hi!")); QVERIFY(pendingSend != NULL); QVERIFY(connect(pendingSend, SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectFailure(Tp::PendingOperation*)))); QVERIFY(pendingSend->isFinished()); QVERIFY(!pendingSend->isValid()); QCOMPARE(pendingSend->errorName(), TP_QT4_ERROR_NOT_IMPLEMENTED); // Let's try using the other sendMessage overload similarly as well Message m(ChannelTextMessageTypeAction, QLatin1String("is testing!")); pendingSend = messenger->sendMessage(m.parts()); QVERIFY(pendingSend != NULL); QVERIFY(connect(pendingSend, SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectFailure(Tp::PendingOperation*)))); QVERIFY(pendingSend->isFinished()); QVERIFY(!pendingSend->isValid()); QCOMPARE(pendingSend->errorName(), TP_QT4_ERROR_NOT_IMPLEMENTED); } void TestContactMessenger::cleanup() { cleanupImpl(); } void TestContactMessenger::cleanupTestCase() { cleanupTestCaseImpl(); } QTEST_MAIN(TestContactMessenger) #include "_gen/contact-messenger.cpp.moc.hpp" <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// <<<<<<< HEAD // Copyright (c) 2019, Vinitha Ranganeni, Brian Lee ======= // Copyright (c) 2019, Brian Lee, Vinitha Ranganeni >>>>>>> a7fffa012325937d70466fdf4b5b0938ff1a8d82 // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 <gtest/gtest.h> #include "statespace/SE2.hpp" #include "distance/SE2.hpp" #include "distance/translation.hpp" #include "distance/orientation.hpp" namespace libcozmo { namespace distance { namespace test { <<<<<<< HEAD class DistanceTest: public ::testing::Test { public: DistanceTest() : \ m_statespace(statespace::SE2(0.1, 8)), m_se2(distance::SE2(&m_statespace)), m_trans(distance::Translation(&m_statespace)), m_orient(distance::Orientation(&m_statespace)) {} void SetUp() { m_id_1 = m_statespace.get_or_create_state(statespace::SE2::State(0, 0, 0)); m_id_2 = m_statespace.get_or_create_state(statespace::SE2::State(1, 3, 1)); } ~DistanceTest() {} statespace::SE2 m_statespace; distance::SE2 m_se2; distance::Translation m_trans; distance::Orientation m_orient; int m_id_1; int m_id_2; }; TEST_F(DistanceTest, TestSE2) { // Cheking SE2 distance calculated correctly EXPECT_NEAR( sqrt(pow(0.1,2) + pow(0.3,2) + pow(M_PI/4, 2)), m_se2.get_distance( *m_statespace.get_state(m_id_1), *m_statespace.get_state(m_id_2)), 0.01); } TEST_F(DistanceTest, TestTranslation) { // Cheking translation calculated correctly EXPECT_NEAR( sqrt(pow(0.1,2) + pow(0.3,2)), m_trans.get_distance( *m_statespace.get_state(m_id_1), *m_statespace.get_state(m_id_2)), 0.01); } TEST_F(DistanceTest, TestOrientation) { // Cheking orientation calculated correctly EXPECT_NEAR( M_PI/4, m_orient.get_distance( *m_statespace.get_state(m_id_1), *m_statespace.get_state(m_id_2)), ======= TEST(DistanceTest, TestSE2) { // Checking SE2 distance calculated correctly const auto statespace = std::make_shared<statespace::SE2>(0.1, 8); distance::SE2 se2 = distance::SE2(statespace); EXPECT_NEAR( sqrt(pow(0.1, 2) + pow(0.3, 2) + pow(M_PI / 2, 2)), se2.get_distance( statespace::SE2::State(0, 0, 1), statespace::SE2::State(1, 3, 3)), 0.01); } TEST(DistanceTest, TestTranslation) { // Checking translation calculated correctly const auto statespace = std::make_shared<statespace::SE2>(0.1, 8); distance::Translation trans = distance::Translation(statespace); EXPECT_NEAR( sqrt(pow(0.1, 2) + pow(0.3, 2)), trans.get_distance( statespace::SE2::State(0, 0, 1), statespace::SE2::State(1, 3, 3)), 0.01); } TEST(DistanceTest, TestOrientation) { // Checking orientation calculated correctly const auto statespace = std::make_shared<statespace::SE2>(0.1, 8); distance::Orientation orient = distance::Orientation(statespace); EXPECT_NEAR( M_PI / 2, orient.get_distance( statespace::SE2::State(0, 0, 1), statespace::SE2::State(1, 3, 3)), >>>>>>> a7fffa012325937d70466fdf4b5b0938ff1a8d82 0.01); } } // namespace test <<<<<<< HEAD } // namspace distance ======= } // namespace distance >>>>>>> a7fffa012325937d70466fdf4b5b0938ff1a8d82 } // namespace libcozmo int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); <<<<<<< HEAD } ======= } >>>>>>> a7fffa012325937d70466fdf4b5b0938ff1a8d82 <commit_msg>fixed merge for distance test<commit_after>//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2019, Vinitha Ranganeni, Brian Lee // Copyright (c) 2019, Brian Lee, Vinitha Ranganeni // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 <gtest/gtest.h> #include "statespace/SE2.hpp" #include "distance/SE2.hpp" #include "distance/translation.hpp" #include "distance/orientation.hpp" namespace libcozmo { namespace distance { namespace test { TEST(DistanceTest, TestSE2) { // Checking SE2 distance calculated correctly const auto statespace = std::make_shared<statespace::SE2>(0.1, 8); distance::SE2 se2 = distance::SE2(statespace); EXPECT_NEAR( sqrt(pow(0.1, 2) + pow(0.3, 2) + pow(M_PI / 2, 2)), se2.get_distance( statespace::SE2::State(0, 0, 1), statespace::SE2::State(1, 3, 3)), 0.01); } TEST(DistanceTest, TestTranslation) { // Checking translation calculated correctly const auto statespace = std::make_shared<statespace::SE2>(0.1, 8); distance::Translation trans = distance::Translation(statespace); EXPECT_NEAR( sqrt(pow(0.1, 2) + pow(0.3, 2)), trans.get_distance( statespace::SE2::State(0, 0, 1), statespace::SE2::State(1, 3, 3)), 0.01); } TEST(DistanceTest, TestOrientation) { // Checking orientation calculated correctly const auto statespace = std::make_shared<statespace::SE2>(0.1, 8); distance::Orientation orient = distance::Orientation(statespace); EXPECT_NEAR( M_PI / 2, orient.get_distance( statespace::SE2::State(0, 0, 1), statespace::SE2::State(1, 3, 3)), 0.01); } } // namespace test } // namspace distance } // namespace libcozmo int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before><commit_msg>watchdog for stalled queued checking torrents<commit_after><|endoftext|>
<commit_before> #include <unistd.h> #include <pthread.h> // pthread_create #include <iostream> #include <string.h> // strerror using namespace std; void* run(void*); // 线程函数 void* thread1_run(void* arg); void* thread2_run(void* arg); void printids(char const* s); // 互斥变量 pthread_mutex_t mqlock = PTHREAD_MUTEX_INITIALIZER; // 条件变量 pthread_cond_t mqlock_ready = PTHREAD_COND_INITIALIZER; // 共享资源 int g_share_res = 0; bool g_stop = false; int main(){ pthread_t ntid1, ntid2; // 线程标识 int err = pthread_create(&ntid1, nullptr, thread1_run, nullptr); // 创建线程 if (err) { cerr << "Can't create thread thread1_run:" << strerror(err) << "!" << endl; return 1; } err = pthread_create(&ntid2, nullptr, thread2_run, nullptr); // 创建线程 if (err) { cerr << "Can't create thread thread2_run:" << strerror(err) << "!" << endl; return 1; } printids("main thread: "); // err = pthread_cancel(ntid); void* exit_code = nullptr; err = pthread_join(ntid1, &exit_code); err = pthread_join(ntid2, &exit_code); return 0; } void* run(void*) { printids("new thread: "); cout << "线程退出" << endl; return (void*)8; } void printids(char const* s) { pid_t pid = getpid(); pthread_t tid = pthread_self(); cout << s << " pid " << pid << " tid " << tid<< endl; } void* thread1_run(void* arg) { int i = 0; while (i < 100) { pthread_mutex_lock(&mqlock); // list_add_tail(pkt, &pkt_queue); g_share_res = ++i; pthread_mutex_unlock(&mqlock); // 通知线程2条件发生变化 pthread_cond_signal(&mqlock_ready); sleep(5); } g_stop = true; return nullptr; } void* thread2_run(void* arg) { while (!g_stop) { pthread_mutex_lock(&mqlock); // while (list_empty(&pkt_queue)) { // 若队列为空,则休眠等待条件改变 pthread_cond_wait(&mqlock_ready, &mqlock); // 休眠等待线程1来唤醒 // 此处函数返回,会自动加锁mqlock } // pkt = getnextpkt(&pkt_queue); pthread_mutex_unlock(&mqlock); // handle_packet(pkt); // 处理此分组 cout << "g_share_res=" << g_share_res << endl; } return nullptr; } <commit_msg>通知线程2唤醒结束,不然进程将一直等到线程2<commit_after> #include <unistd.h> #include <pthread.h> // pthread_create #include <iostream> #include <string.h> // strerror using namespace std; void* run(void*); // 线程函数 void* thread1_run(void* arg); void* thread2_run(void* arg); void printids(char const* s); // 互斥变量 pthread_mutex_t mqlock = PTHREAD_MUTEX_INITIALIZER; // 条件变量 pthread_cond_t mqlock_ready = PTHREAD_COND_INITIALIZER; // 共享资源 int g_share_res = 0; bool g_stop = false; int main(){ pthread_t ntid1, ntid2; // 线程标识 int err = pthread_create(&ntid1, nullptr, thread1_run, nullptr); // 创建线程 if (err) { cerr << "Can't create thread thread1_run:" << strerror(err) << "!" << endl; return 1; } err = pthread_create(&ntid2, nullptr, thread2_run, nullptr); // 创建线程 if (err) { cerr << "Can't create thread thread2_run:" << strerror(err) << "!" << endl; return 1; } printids("main thread: "); // err = pthread_cancel(ntid); void* exit_code = nullptr; err = pthread_join(ntid1, &exit_code); err = pthread_join(ntid2, &exit_code); return 0; } void* run(void*) { printids("new thread: "); cout << "线程退出" << endl; return (void*)8; } void printids(char const* s) { pid_t pid = getpid(); pthread_t tid = pthread_self(); cout << s << " pid " << pid << " tid " << tid<< endl; } void* thread1_run(void* arg) { int i = 0; while (i < 100) { pthread_mutex_lock(&mqlock); // list_add_tail(pkt, &pkt_queue); g_share_res = ++i; pthread_mutex_unlock(&mqlock); // 通知线程2条件发生变化 pthread_cond_signal(&mqlock_ready); sleep(5); } g_stop = true; pthread_cond_signal(&mqlock_ready); // 通知线程2结束 return nullptr; } void* thread2_run(void* arg) { while (!g_stop) { pthread_mutex_lock(&mqlock); // while (list_empty(&pkt_queue)) { // 若队列为空,则休眠等待条件改变 pthread_cond_wait(&mqlock_ready, &mqlock); // 休眠等待线程1来唤醒 // 此处函数返回,会自动加锁mqlock } // pkt = getnextpkt(&pkt_queue); pthread_mutex_unlock(&mqlock); // handle_packet(pkt); // 处理此分组 cout << "g_share_res=" << g_share_res << endl; } return nullptr; } <|endoftext|>
<commit_before>/******************************************************************************* * thrill/api/size.hpp * * Part of Project Thrill - http://project-thrill.org * * Copyright (C) 2015 Matthias Stumpp <[email protected]> * Copyright (C) 2015 Sebastian Lamm <[email protected]> * * All rights reserved. Published under the BSD-2 license in the LICENSE file. ******************************************************************************/ #pragma once #ifndef THRILL_API_SIZE_HEADER #define THRILL_API_SIZE_HEADER #include <thrill/api/action_node.hpp> #include <thrill/api/dia.hpp> #include <thrill/net/group.hpp> #include <string> namespace thrill { namespace api { //! \addtogroup api Interface //! \{ template <typename ParentDIA> class SizeNode final : public ActionNode { static constexpr bool debug = false; using Super = ActionNode; using Super::context_; //! input type is the parent's output value type. using Input = typename ParentDIA::ValueType; public: explicit SizeNode(const ParentDIA& parent) : ActionNode(parent.ctx(), "Size", { parent.id() }, { parent.node() }) { // Hook PreOp(s) auto pre_op_fn = [this](const Input&) { ++local_size_; }; auto lop_chain = parent.stack().push(pre_op_fn).fold(); parent.node()->AddChild(this, lop_chain); } //! Executes the size operation. void Execute() final { MainOp(); } /*! * Returns result of global size. * \return result */ size_t result() const { return global_size_; } private: // Local size to be used. size_t local_size_ = 0; // Global size resulting from all reduce. size_t global_size_ = 0; void MainOp() { // get the number of elements that are stored on this worker LOG << "MainOp processing, sum: " << local_size_; // process the reduce, default argument is SumOp. global_size_ = context_.net.AllReduce(local_size_); } }; template <typename ValueType, typename Stack> size_t DIA<ValueType, Stack>::Size() const { assert(IsValid()); using SizeNode = api::SizeNode<DIA>; auto node = std::make_shared<SizeNode>(*this); node->RunScope(); return node->result(); } //! \} } // namespace api } // namespace thrill #endif // !THRILL_API_SIZE_HEADER /******************************************************************************/ <commit_msg>api: adding OnPreOpFile() to SumNode<commit_after>/******************************************************************************* * thrill/api/size.hpp * * Part of Project Thrill - http://project-thrill.org * * Copyright (C) 2015 Matthias Stumpp <[email protected]> * Copyright (C) 2015 Sebastian Lamm <[email protected]> * * All rights reserved. Published under the BSD-2 license in the LICENSE file. ******************************************************************************/ #pragma once #ifndef THRILL_API_SIZE_HEADER #define THRILL_API_SIZE_HEADER #include <thrill/api/action_node.hpp> #include <thrill/api/dia.hpp> #include <thrill/net/group.hpp> #include <string> namespace thrill { namespace api { //! \addtogroup api Interface //! \{ template <typename ParentDIA> class SizeNode final : public ActionNode { static constexpr bool debug = false; using Super = ActionNode; using Super::context_; //! input type is the parent's output value type. using Input = typename ParentDIA::ValueType; public: explicit SizeNode(const ParentDIA& parent) : ActionNode(parent.ctx(), "Size", { parent.id() }, { parent.node() }) { // Hook PreOp(s) auto pre_op_fn = [this](const Input&) { ++local_size_; }; auto lop_chain = parent.stack().push(pre_op_fn).fold(); parent.node()->AddChild(this, lop_chain); } //! Receive a whole data::File of ValueType, but only if our stack is empty. bool OnPreOpFile(const data::File& file, size_t /* parent_index */) final { if (!ParentDIA::stack_empty) return false; local_size_ = file.num_items(); return true; } //! Executes the size operation. void Execute() final { MainOp(); } /*! * Returns result of global size. * \return result */ size_t result() const { return global_size_; } private: // Local size to be used. size_t local_size_ = 0; // Global size resulting from all reduce. size_t global_size_ = 0; void MainOp() { // get the number of elements that are stored on this worker LOG << "MainOp processing, sum: " << local_size_; // process the reduce, default argument is SumOp. global_size_ = context_.net.AllReduce(local_size_); } }; template <typename ValueType, typename Stack> size_t DIA<ValueType, Stack>::Size() const { assert(IsValid()); using SizeNode = api::SizeNode<DIA>; auto node = std::make_shared<SizeNode>(*this); node->RunScope(); return node->result(); } //! \} } // namespace api } // namespace thrill #endif // !THRILL_API_SIZE_HEADER /******************************************************************************/ <|endoftext|>
<commit_before>#include "logging.h" #ifndef Q_OS_WIN32 #include <syslog.h> #endif #include <QByteArray> #include <QString> #ifdef Q_OS_WIN32 #include <stdio.h> #include <stdarg.h> void syslog(int priority, const char *format, ...){ Q_UNUSED(priority); va_list arg_list; va_start(arg_list, format); vprintf(format, arg_list); va_end(arg_list); } #endif #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) void qtOutputToLog(QtMsgType type, const QMessageLogContext &context, const QString &m) { Q_UNUSED(context); QByteArray localMsg = m.toLocal8Bit(); const char *msg = localMsg.constData(); #else void qtOutputToLog(QtMsgType type, const char *msg) { #endif switch(type){ case QtDebugMsg: syslog(LOG_DEBUG, "Qt debug: %s", msg); break; case QtWarningMsg: syslog(LOG_WARNING, "Qt warning: %s", msg); break; case QtCriticalMsg: syslog(LOG_CRIT, "Qt critical: %s", msg); break; case QtFatalMsg: syslog(LOG_ALERT, "Qt fatal: %s", msg); exit(1); break; default: syslog(LOG_INFO, "Qt info: %s", msg); break; } } <commit_msg>Qt fatal error does not mean that we need to shut down<commit_after>#include "logging.h" #ifndef Q_OS_WIN32 #include <syslog.h> #endif #include <QByteArray> #include <QString> #ifdef Q_OS_WIN32 #include <stdio.h> #include <stdarg.h> void syslog(int priority, const char *format, ...){ Q_UNUSED(priority); va_list arg_list; va_start(arg_list, format); vprintf(format, arg_list); va_end(arg_list); } #endif #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) void qtOutputToLog(QtMsgType type, const QMessageLogContext &context, const QString &m) { Q_UNUSED(context); QByteArray localMsg = m.toLocal8Bit(); const char *msg = localMsg.constData(); #else void qtOutputToLog(QtMsgType type, const char *msg) { #endif switch(type){ case QtDebugMsg: syslog(LOG_DEBUG, "Qt debug: %s", msg); break; case QtWarningMsg: syslog(LOG_WARNING, "Qt warning: %s", msg); break; case QtCriticalMsg: syslog(LOG_CRIT, "Qt critical: %s", msg); break; case QtFatalMsg: syslog(LOG_ALERT, "Qt fatal: %s", msg); break; default: syslog(LOG_INFO, "Qt info: %s", msg); break; } } <|endoftext|>
<commit_before>// This file is a part of the OpenSurgSim project. // Copyright 2013-2016, SimQuest Solutions Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "SurgSim/Math/OdeState.h" #include "SurgSim/Framework/Assert.h" #include "SurgSim/Math/Valid.h" namespace SurgSim { namespace Math { OdeState::OdeState() : m_numDofPerNode(0u), m_numNodes(0u) { } OdeState::~OdeState() { } bool OdeState::operator ==(const OdeState& state) const { return m_x == state.m_x && m_v == state.m_v && m_boundaryConditionsPerDof == state.m_boundaryConditionsPerDof && m_nonDofBoundaryConditions == state.m_nonDofBoundaryConditions; } bool OdeState::operator !=(const OdeState& state) const { return !((*this) == state); } void OdeState::reset() { m_x.setZero(); m_v.setZero(); m_boundaryConditionsPerDof.setConstant(false); m_boundaryConditionsAsDofIds.clear(); m_nonDofBoundaryConditions.clear(); } void OdeState::setNumDof(size_t numDofPerNode, size_t numNodes) { const size_t numDof = numDofPerNode * numNodes; m_numDofPerNode = numDofPerNode; m_numNodes = numNodes; m_x.resize(numDof); m_v.resize(numDof); m_boundaryConditionsPerDof.resize(numDof); // Zero-out everything reset(); } size_t OdeState::getNumDof() const { const size_t numDof = m_numDofPerNode * m_numNodes; SURGSIM_ASSERT(m_x.size() == m_v.size() && m_x.size() == m_boundaryConditionsPerDof.size() && m_x.size() >= 0 && static_cast<size_t>(m_x.size()) == numDof); return numDof; } size_t OdeState::getNumNodes() const { return m_numNodes; } SurgSim::Math::Vector& OdeState::getPositions() { return m_x; } const SurgSim::Math::Vector& OdeState::getPositions() const { return m_x; } const SurgSim::Math::Vector3d OdeState::getPosition(size_t nodeId) const { return SurgSim::Math::getSubVector(m_x, nodeId, m_numDofPerNode).segment(0, 3); } SurgSim::Math::Vector& OdeState::getVelocities() { return m_v; } const SurgSim::Math::Vector& OdeState::getVelocities() const { return m_v; } const SurgSim::Math::Vector3d OdeState::getVelocity(size_t nodeId) const { return SurgSim::Math::getSubVector(m_v, nodeId, m_numDofPerNode).segment(0, 3); } void OdeState::addBoundaryCondition(size_t nodeId) { SURGSIM_ASSERT(m_numDofPerNode != 0u) << "Number of dof per node = 0. Make sure to call setNumDof() " << "prior to adding boundary conditions."; for (size_t nodeDofId = 0; nodeDofId < m_numDofPerNode; ++nodeDofId) { addBoundaryCondition(nodeId, nodeDofId); } } void OdeState::addBoundaryCondition(size_t nodeId, size_t nodeDofId) { SURGSIM_ASSERT(m_numDofPerNode != 0u) << "Number of dof per node = 0. Make sure to call setNumDof() " << "prior to adding boundary conditions."; SURGSIM_ASSERT(nodeId < m_numNodes) << "Invalid nodeId " << nodeId << " number of nodes is " << m_numNodes; SURGSIM_ASSERT(nodeDofId < m_numDofPerNode) << "Invalid nodeDofId " << nodeDofId << " number of dof per node is " << m_numDofPerNode; size_t globalDofId = nodeId * m_numDofPerNode + nodeDofId; if (! m_boundaryConditionsPerDof[globalDofId]) { m_boundaryConditionsPerDof[globalDofId] = true; m_boundaryConditionsAsDofIds.push_back(globalDofId); } } size_t OdeState::getNumBoundaryConditions() const { return m_boundaryConditionsAsDofIds.size(); } const std::vector<size_t>& OdeState::getBoundaryConditions() const { return m_boundaryConditionsAsDofIds; } bool OdeState::isBoundaryCondition(size_t dof) const { return m_boundaryConditionsPerDof[dof]; } Vector* OdeState::applyBoundaryConditionsToVector(Vector* vector) const { SURGSIM_ASSERT(vector != nullptr && vector->size() >= 0 && static_cast<size_t>(vector->size()) == getNumDof()) << "Invalid vector to apply boundary conditions on"; const size_t numDofPerNode = getNumDof() / getNumNodes(); const size_t N = numDofPerNode * (getNumNodes() - 2); for (auto it = getBoundaryConditions().cbegin(); it != getBoundaryConditions().cend(); ++it) { //if (*it == N) //{ // (*vector)[*it] = -0.0001; // std::cout << "(*vector)["<<*it<<"] = -0.01;" << std::endl; //} //else if (*it == N + 1) //{ // (*vector)[*it] = -0.00001; //} //else if (*it == N + 2) //{ // (*vector)[*it] = -0.0000003; //} //else { (*vector)[*it] = 0.0; } } return vector; } void OdeState::applyBoundaryConditionsToMatrix(Matrix* matrix, bool hasCompliance) const { SURGSIM_ASSERT(matrix != nullptr && static_cast<size_t>(matrix->rows()) == getNumDof() && static_cast<size_t>(matrix->cols()) == getNumDof()) << "Invalid matrix to apply boundary conditions on"; double complianceValue = 0.0; if (hasCompliance) { complianceValue = 1.0; } for (auto it = getBoundaryConditions().cbegin(); it != getBoundaryConditions().cend(); ++it) { (*matrix).middleRows(*it, 1).setZero(); (*matrix).middleCols(*it, 1).setZero(); (*matrix)(*it, *it) = complianceValue; } } void OdeState::applyBoundaryConditionsToMatrix(SparseMatrix* matrix, bool hasCompliance) const { SURGSIM_ASSERT(matrix != nullptr && static_cast<size_t>(matrix->rows()) == getNumDof() && static_cast<size_t>(matrix->cols()) == getNumDof()) << "Invalid matrix to apply boundary conditions on"; double complianceValue = 0.0; if (hasCompliance) { complianceValue = 1.0; } for (auto it = getBoundaryConditions().cbegin(); it != getBoundaryConditions().cend(); ++it) { Math::zeroRow((*it), matrix); Math::zeroColumn(static_cast<SparseMatrix::Index>((*it)), matrix); (*matrix).coeffRef(static_cast<SparseMatrix::Index>(*it), static_cast<SparseMatrix::Index>(*it)) = complianceValue; } } void OdeState::addBoundaryConditionStaticDof(size_t nodeId, double value) { SURGSIM_ASSERT(m_numDofPerNode != 0u) << "Number of dof per node = 0. Make sure to call setNumDof() " << "prior to adding boundary conditions."; SURGSIM_ASSERT(nodeId < m_numNodes) << "Invalid nodeId " << nodeId << " number of nodes is " << m_numNodes; m_boundaryConditionsStaticDof.push_back(std::make_pair(nodeId, value)); } size_t OdeState::getNumBoundaryConditionsStaticDof() const { return m_boundaryConditionsStaticDof.size(); } const std::vector<std::pair<size_t, double>>& OdeState::getBoundaryConditionsStaticDof() const { return m_boundaryConditionsStaticDof; } void OdeState::setBoundaryConditionStaticDof(size_t nodeId, double value) { auto bc = std::find_if(m_boundaryConditionsStaticDof.begin(), m_boundaryConditionsStaticDof.end(), [&nodeId](std::pair<size_t, double>& pair) { return pair.first == nodeId; }); if (bc != m_boundaryConditionsStaticDof.end()) { bc->second = value; } } bool OdeState::isValid() const { using SurgSim::Math::isValid; /// http://steve.hollasch.net/cgindex/coding/ieeefloat.html /// We use the IEEE754 standard stipulating that any arithmetic operation with a NaN operand will produce NaN /// and any sum of +-INF with a finite number or +-INF will produce +-INF. /// Therefore, testing if a vector contains only finite numbers can be achieve easily by summing all the values /// and testing if the result is a finite number or not. return isValid(getPositions().sum()) && isValid(getVelocities().sum()); } OdeState OdeState::interpolate(const OdeState& other, double t) const { auto result = OdeState(*this); if (t != 0) { result.m_v += (other.m_v - m_v) * t; result.m_x += (other.m_x - m_x) * t; } return result; } }; // namespace Math }; // namespace SurgSim <commit_msg>Missing changes (fixes the build)<commit_after>// This file is a part of the OpenSurgSim project. // Copyright 2013-2016, SimQuest Solutions Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "SurgSim/Math/OdeState.h" #include "SurgSim/Framework/Assert.h" #include "SurgSim/Math/Valid.h" namespace SurgSim { namespace Math { OdeState::OdeState() : m_numDofPerNode(0u), m_numNodes(0u) { } OdeState::~OdeState() { } bool OdeState::operator ==(const OdeState& state) const { return m_x == state.m_x && m_v == state.m_v && m_boundaryConditionsPerDof == state.m_boundaryConditionsPerDof && m_boundaryConditionsStaticDof == state.m_boundaryConditionsStaticDof; } bool OdeState::operator !=(const OdeState& state) const { return !((*this) == state); } void OdeState::reset() { m_x.setZero(); m_v.setZero(); m_boundaryConditionsPerDof.setConstant(false); m_boundaryConditionsAsDofIds.clear(); m_boundaryConditionsStaticDof.clear(); } void OdeState::setNumDof(size_t numDofPerNode, size_t numNodes) { const size_t numDof = numDofPerNode * numNodes; m_numDofPerNode = numDofPerNode; m_numNodes = numNodes; m_x.resize(numDof); m_v.resize(numDof); m_boundaryConditionsPerDof.resize(numDof); // Zero-out everything reset(); } size_t OdeState::getNumDof() const { const size_t numDof = m_numDofPerNode * m_numNodes; SURGSIM_ASSERT(m_x.size() == m_v.size() && m_x.size() == m_boundaryConditionsPerDof.size() && m_x.size() >= 0 && static_cast<size_t>(m_x.size()) == numDof); return numDof; } size_t OdeState::getNumNodes() const { return m_numNodes; } SurgSim::Math::Vector& OdeState::getPositions() { return m_x; } const SurgSim::Math::Vector& OdeState::getPositions() const { return m_x; } const SurgSim::Math::Vector3d OdeState::getPosition(size_t nodeId) const { return SurgSim::Math::getSubVector(m_x, nodeId, m_numDofPerNode).segment(0, 3); } SurgSim::Math::Vector& OdeState::getVelocities() { return m_v; } const SurgSim::Math::Vector& OdeState::getVelocities() const { return m_v; } const SurgSim::Math::Vector3d OdeState::getVelocity(size_t nodeId) const { return SurgSim::Math::getSubVector(m_v, nodeId, m_numDofPerNode).segment(0, 3); } void OdeState::addBoundaryCondition(size_t nodeId) { SURGSIM_ASSERT(m_numDofPerNode != 0u) << "Number of dof per node = 0. Make sure to call setNumDof() " << "prior to adding boundary conditions."; for (size_t nodeDofId = 0; nodeDofId < m_numDofPerNode; ++nodeDofId) { addBoundaryCondition(nodeId, nodeDofId); } } void OdeState::addBoundaryCondition(size_t nodeId, size_t nodeDofId) { SURGSIM_ASSERT(m_numDofPerNode != 0u) << "Number of dof per node = 0. Make sure to call setNumDof() " << "prior to adding boundary conditions."; SURGSIM_ASSERT(nodeId < m_numNodes) << "Invalid nodeId " << nodeId << " number of nodes is " << m_numNodes; SURGSIM_ASSERT(nodeDofId < m_numDofPerNode) << "Invalid nodeDofId " << nodeDofId << " number of dof per node is " << m_numDofPerNode; size_t globalDofId = nodeId * m_numDofPerNode + nodeDofId; if (! m_boundaryConditionsPerDof[globalDofId]) { m_boundaryConditionsPerDof[globalDofId] = true; m_boundaryConditionsAsDofIds.push_back(globalDofId); } } size_t OdeState::getNumBoundaryConditions() const { return m_boundaryConditionsAsDofIds.size(); } const std::vector<size_t>& OdeState::getBoundaryConditions() const { return m_boundaryConditionsAsDofIds; } bool OdeState::isBoundaryCondition(size_t dof) const { return m_boundaryConditionsPerDof[dof]; } Vector* OdeState::applyBoundaryConditionsToVector(Vector* vector) const { SURGSIM_ASSERT(vector != nullptr && vector->size() >= 0 && static_cast<size_t>(vector->size()) == getNumDof()) << "Invalid vector to apply boundary conditions on"; const size_t numDofPerNode = getNumDof() / getNumNodes(); const size_t N = numDofPerNode * (getNumNodes() - 2); for (auto it = getBoundaryConditions().cbegin(); it != getBoundaryConditions().cend(); ++it) { //if (*it == N) //{ // (*vector)[*it] = -0.0001; // std::cout << "(*vector)["<<*it<<"] = -0.01;" << std::endl; //} //else if (*it == N + 1) //{ // (*vector)[*it] = -0.00001; //} //else if (*it == N + 2) //{ // (*vector)[*it] = -0.0000003; //} //else { (*vector)[*it] = 0.0; } } return vector; } void OdeState::applyBoundaryConditionsToMatrix(Matrix* matrix, bool hasCompliance) const { SURGSIM_ASSERT(matrix != nullptr && static_cast<size_t>(matrix->rows()) == getNumDof() && static_cast<size_t>(matrix->cols()) == getNumDof()) << "Invalid matrix to apply boundary conditions on"; double complianceValue = 0.0; if (hasCompliance) { complianceValue = 1.0; } for (auto it = getBoundaryConditions().cbegin(); it != getBoundaryConditions().cend(); ++it) { (*matrix).middleRows(*it, 1).setZero(); (*matrix).middleCols(*it, 1).setZero(); (*matrix)(*it, *it) = complianceValue; } } void OdeState::applyBoundaryConditionsToMatrix(SparseMatrix* matrix, bool hasCompliance) const { SURGSIM_ASSERT(matrix != nullptr && static_cast<size_t>(matrix->rows()) == getNumDof() && static_cast<size_t>(matrix->cols()) == getNumDof()) << "Invalid matrix to apply boundary conditions on"; double complianceValue = 0.0; if (hasCompliance) { complianceValue = 1.0; } for (auto it = getBoundaryConditions().cbegin(); it != getBoundaryConditions().cend(); ++it) { Math::zeroRow((*it), matrix); Math::zeroColumn(static_cast<SparseMatrix::Index>((*it)), matrix); (*matrix).coeffRef(static_cast<SparseMatrix::Index>(*it), static_cast<SparseMatrix::Index>(*it)) = complianceValue; } } void OdeState::addBoundaryConditionStaticDof(size_t nodeId, double value) { SURGSIM_ASSERT(m_numDofPerNode != 0u) << "Number of dof per node = 0. Make sure to call setNumDof() " << "prior to adding boundary conditions."; SURGSIM_ASSERT(nodeId < m_numNodes) << "Invalid nodeId " << nodeId << " number of nodes is " << m_numNodes; m_boundaryConditionsStaticDof.push_back(std::make_pair(nodeId, value)); } size_t OdeState::getNumBoundaryConditionsStaticDof() const { return m_boundaryConditionsStaticDof.size(); } const std::vector<std::pair<size_t, double>>& OdeState::getBoundaryConditionsStaticDof() const { return m_boundaryConditionsStaticDof; } void OdeState::setBoundaryConditionStaticDof(size_t nodeId, double value) { auto bc = std::find_if(m_boundaryConditionsStaticDof.begin(), m_boundaryConditionsStaticDof.end(), [&nodeId](std::pair<size_t, double>& pair) { return pair.first == nodeId; }); if (bc != m_boundaryConditionsStaticDof.end()) { bc->second = value; } } bool OdeState::isValid() const { using SurgSim::Math::isValid; /// http://steve.hollasch.net/cgindex/coding/ieeefloat.html /// We use the IEEE754 standard stipulating that any arithmetic operation with a NaN operand will produce NaN /// and any sum of +-INF with a finite number or +-INF will produce +-INF. /// Therefore, testing if a vector contains only finite numbers can be achieve easily by summing all the values /// and testing if the result is a finite number or not. return isValid(getPositions().sum()) && isValid(getVelocities().sum()); } OdeState OdeState::interpolate(const OdeState& other, double t) const { auto result = OdeState(*this); if (t != 0) { result.m_v += (other.m_v - m_v) * t; result.m_x += (other.m_x - m_x) * t; } return result; } }; // namespace Math }; // namespace SurgSim <|endoftext|>