hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
418e73335586695d6d3a4a1a90da24abbbdcc2f6
529
cpp
C++
core/CameraSystemProcessor.cpp
ChaosKit/ChaosKit
e7cba03db1ae34160868656ea357c7166ae1d84a
[ "Apache-2.0" ]
3
2021-01-09T17:25:18.000Z
2021-07-11T00:04:22.000Z
core/CameraSystemProcessor.cpp
ChaosKit/ChaosKit
e7cba03db1ae34160868656ea357c7166ae1d84a
[ "Apache-2.0" ]
1
2021-03-21T13:17:04.000Z
2021-03-21T14:03:46.000Z
core/CameraSystemProcessor.cpp
ChaosKit/ChaosKit
e7cba03db1ae34160868656ea357c7166ae1d84a
[ "Apache-2.0" ]
1
2020-04-03T16:32:53.000Z
2020-04-03T16:32:53.000Z
#include "CameraSystemProcessor.h" namespace chaoskit::core { void CameraSystemProcessor::setCameraSystem(const CameraSystem& cameraSystem) { setSystem(cameraSystem.system); setCamera(cameraSystem.camera); } SystemParticle CameraSystemProcessor::processCamera( SystemParticle input) const { if (!camera_) return input; SystemParticle output = input; output.applyParticle(interpreter_.interpret( input.asParticle(), camera_->transform, camera_->params)); return output; } } // namespace chaoskit::core
25.190476
79
0.769376
ChaosKit
41911c52cdeaa0cca080120286aca4e7b91bf0f9
2,036
cxx
C++
src/samples/xsd_parser.cxx
abdelkaderamar/fix2xml
fa781b747a8e40ed4c2d3dee8294fb51654f7428
[ "MIT" ]
1
2019-09-26T12:08:19.000Z
2019-09-26T12:08:19.000Z
src/samples/xsd_parser.cxx
abdelkaderamar/fix2xml
fa781b747a8e40ed4c2d3dee8294fb51654f7428
[ "MIT" ]
null
null
null
src/samples/xsd_parser.cxx
abdelkaderamar/fix2xml
fa781b747a8e40ed4c2d3dee8294fb51654f7428
[ "MIT" ]
1
2020-12-11T04:11:44.000Z
2020-12-11T04:11:44.000Z
// MIT License // // Copyright 2018 Abdelkader Amar // // 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 "util/fix_env.hxx" #include "fixml/fixml_xsd_parser.hxx" #include <boost/log/trivial.hpp> using namespace fix2xml; using namespace std; int usage(const int ret) { static string text = "Usage: xsd_parser {xsd_files}"; if (ret == 0) BOOST_LOG_TRIVIAL(info) << text; else BOOST_LOG_TRIVIAL(error) << text; return ret; } int main(int argc, char *argv[]) { if (argc < 2) return usage(1); if ( ! fix_env::init_xerces()) { BOOST_LOG_TRIVIAL(error) << "Failed to initialize xerces environment"; return 1; } BOOST_LOG_TRIVIAL(info) << "xerces environment initialized"; { fixml_xsd_parser parser; BOOST_LOG_TRIVIAL(info) << "xsd parser created"; if (parser.parse(argv[1])) BOOST_LOG_TRIVIAL(info) << "parsing " << argv[1] << " done"; else BOOST_LOG_TRIVIAL(error) << "parsing " << argv[1] << " failed"; } fix_env::terminate_xerces(); return 0; }
33.933333
91
0.721513
abdelkaderamar
41a2e2fb9777e837d9942e9c28e0d86e270456bc
23,537
cpp
C++
fcgi/streambuf.cpp
dmitigr/cefeika
6189843d4244f7334558708e57e952584561b1e0
[ "Zlib" ]
19
2019-07-21T15:38:12.000Z
2022-01-06T05:24:48.000Z
fcgi/streambuf.cpp
dmitigr/cefeika
6189843d4244f7334558708e57e952584561b1e0
[ "Zlib" ]
6
2019-12-07T22:12:37.000Z
2022-01-10T22:31:48.000Z
fcgi/streambuf.cpp
dmitigr/cefeika
6189843d4244f7334558708e57e952584561b1e0
[ "Zlib" ]
1
2019-08-15T14:49:00.000Z
2019-08-15T14:49:00.000Z
// -*- C++ -*- // Copyright (C) 2021 Dmitry Igrishin // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // // Dmitry Igrishin // [email protected] #include "basics.hpp" #include "exceptions.hpp" #include "server_connection.hpp" #include "streambuf.hpp" #include "../error/assert.hpp" #include "../math.hpp" #include <algorithm> #include <array> #include <cstdio> #include <istream> #include <limits> #include <ostream> /* * By defining DMITIGR_FCGI_DEBUG some convenient stuff for debugging * will be available, for example, server_Streambuf::print(). */ //#define DMITIGR_FCGI_DEBUG #ifdef DMITIGR_FCGI_DEBUG #include <iostream> #endif namespace dmitigr::fcgi::detail { /** * @brief The base implementation of Streambuf. */ class iStreambuf : public Streambuf { private: friend server_Streambuf; using Streambuf::Streambuf; }; /** * @brief The implementation of the `std::streambuf` for a FastCGI server. */ class server_Streambuf final : public iStreambuf { public: using Type = Stream_type; ~server_Streambuf() override { try { close(); } catch (const std::exception& e) { std::fprintf(stderr, "dmitigr::fcgi: %s\n", e.what()); } catch (...) { std::fprintf(stderr, "dmitigr::fcgi: failure\n"); } } server_Streambuf(const server_Streambuf&) = delete; server_Streambuf& operator=(const server_Streambuf&) = delete; server_Streambuf(server_Streambuf&&) = delete; server_Streambuf& operator=(server_Streambuf&&) = delete; /** * @brief The constructor. */ server_Streambuf(iServer_connection* const connection, char_type* const buffer, const std::streamsize buffer_size, const Type type) : type_{type} , connection_{connection} { DMITIGR_ASSERT(connection); setg(nullptr, nullptr, nullptr); setp(nullptr, nullptr); setbuf(buffer, buffer_size); DMITIGR_ASSERT(is_invariant_ok()); } /** * @brief Closes the stream. * * If this instance represents the streambuf of the output stream (either * Stream_type::err or Stream_type::out) then transmits the end records to * the FastCGI client and sets `is_end_of_stream_` to `true`. (The * transmission of the end records takes place if and only if it is not * contradicts the protocol.) * * @par Effects * `is_closed()`. Also, unsets both the get area and the put area. */ void close() { if (is_closed()) return; if (!is_reader()) { const auto* const inbuf = dynamic_cast<server_Streambuf*>(connection_->in().streambuf()); DMITIGR_ASSERT(inbuf && inbuf->is_reader() && !inbuf->is_closed()); const auto role = connection_->role(); DMITIGR_ASSERT(role == Role::authorizer || inbuf->type_ != Type::params); if (role != Role::filter || inbuf->type_ == Type::data || inbuf->unread_content_length_ == 0) { is_end_records_must_be_transmitted_ = true; sync(); } else throw Generic_exception{"not all FastCGI stdin has been read by Filter"}; DMITIGR_ASSERT(is_end_of_stream_ && !is_end_records_must_be_transmitted_); } setg(nullptr, nullptr, nullptr); setp(nullptr, nullptr); DMITIGR_ASSERT(is_closed()); DMITIGR_ASSERT(is_invariant_ok()); } /** * @returns `true` if this instance is for receiving the * data from the FastCGI client, or `false` otherwise. */ bool is_reader() const { return (type_ == Type::in || type_ == Type::params || type_ == Type::data); } /** * @returns `true` if this instance is unusable anymore, or `false` otherwise. */ bool is_closed() const { return is_reader() ? !eback() : !pbase(); } /** * @returns `true` if this instance is ready to switching to the filter mode. */ bool is_ready_to_filter_data() const { return !is_closed() && (connection_->role() == Role::filter) && (type_ == Type::in) && is_end_of_stream_; } /** * @returns The stream type. */ Type stream_type() const { return type_; } protected: // std::streambuf overridings: server_Streambuf* setbuf(char_type* const buffer, const std::streamsize size) override { DMITIGR_ASSERT(buffer && (2048 <= size && size <= 65528)); if ((eback() != nullptr && eback() != buffer_) || (pbase() != nullptr && pbase() != buffer_ + sizeof(detail::Header))) throw Generic_exception{"cannot set FastCGI buffer (there are pending data)"}; constexpr std::streamsize alignment = 8; buffer_ = buffer; buffer_size_ = size - (alignment - math::padding(size, alignment)) % alignment; if (is_reader()) { setg(buffer_, buffer_, buffer_); buffer_end_ = buffer_; setp(nullptr, nullptr); } else { /* * First sizeof(detail::Header) bytes of the buffer_ are reserved for Header. * Last byte of the buffer_ is reserved for byte passed to overflow(). Thus, * epptr() can be used to store this byte. */ setg(nullptr, nullptr, nullptr); setp(buffer_ + sizeof(detail::Header), buffer_ + buffer_size_ - 1); } DMITIGR_ASSERT(is_invariant_ok()); return this; } int sync() override { const auto ch = overflow(traits_type::eof()); return traits_type::eq_int_type(ch, traits_type::eof()) ? -1 : 0; } int_type underflow() override { DMITIGR_ASSERT(is_reader() && !is_closed()); if (is_end_of_stream_) return traits_type::eof(); detail::Header header{}; std::size_t read_header_length{}; while (true) { // Reading the stream records. if (gptr() == buffer_end_) { const std::streamsize count = connection_->io_->read(buffer_, buffer_size_); if (count > 0) { buffer_end_ = buffer_ + count; setg(buffer_, buffer_, buffer_end_); } else throw Generic_exception{"FastCGI protocol violation"}; } DMITIGR_ASSERT(buffer_end_ - gptr() > 0); // Setting up the get area for the content. if (unread_content_length_ > 0) { const std::streamsize count = std::min(unread_content_length_, buffer_end_ - gptr()); unread_content_length_ -= count; if (!is_content_must_be_discarded_) { setg(gptr(), gptr(), gptr() + count); // Get area now contains all available content bytes at the moment. DMITIGR_ASSERT(is_invariant_ok()); return traits_type::to_int_type(*gptr()); } else { gbump(static_cast<int>(count)); // Discarding. if (unread_content_length_ > 0) continue; else is_content_must_be_discarded_ = false; } } DMITIGR_ASSERT(unread_content_length_ == 0); // Skipping the padding. if (unread_padding_length_ > 0) { const std::streamsize count = std::min(unread_padding_length_, buffer_end_ - gptr()); unread_padding_length_ -= count; gbump(static_cast<int>(count)); // Skipping. if (unread_padding_length_ > 0) continue; } DMITIGR_ASSERT(unread_padding_length_ == 0); // --------------- // The start point // --------------- // Accumulating the header. { const std::size_t count = std::min(sizeof(header) - read_header_length, static_cast<std::size_t>(buffer_end_ - gptr())); std::memcpy(reinterpret_cast<char*>(&header) + read_header_length, gptr(), count); read_header_length += count; gbump(static_cast<int>(count)); // Already consumed. if (read_header_length < sizeof(header)) continue; } DMITIGR_ASSERT(read_header_length == sizeof(header)); // Processing the header. { const auto set_end_of_stream = [&]() { setg(gptr(), gptr(), gptr()); is_end_of_stream_ = true; DMITIGR_ASSERT(is_invariant_ok()); }; setg(gptr(), gptr(), gptr()); const auto phr = process_header(header); switch(phr) { case Process_header_result::request_rejected: set_end_of_stream(); return traits_type::eof(); case Process_header_result::management_processed: continue; case Process_header_result::content_must_be_consumed: if (unread_content_length_ == 0) { set_end_of_stream(); if (is_ready_to_filter_data()) reset_reader(Type::data); return traits_type::eof(); } else continue; case Process_header_result::content_must_be_discarded: is_content_must_be_discarded_ = true; continue; } } } } int_type overflow(const int_type ch) override { DMITIGR_ASSERT(!is_reader() && !is_closed()); if (is_end_of_stream_) return traits_type::eof(); const bool is_eof = traits_type::eq_int_type(ch, traits_type::eof()); DMITIGR_ASSERT(pbase() == (buffer_ + sizeof(detail::Header))); if (std::streamsize content_length = pptr() - pbase()) { /* * If `ch` is not EOF we need to place `ch` at the location pointed to by * pptr(). (It's ok if pptr() == epptr() since that location is a valid * writable location reserved for extra `ch`.) * The content should be aligned by padding if necessary, and the record * header must be injected at the reserved space [buffer_, pbase()). * After that the result record will be ready to send to a client. */ // Store `ch` if it's not EOF. if (!is_eof) { DMITIGR_ASSERT(pptr() <= epptr()); *pptr() = static_cast<char>(ch); pbump(1); // Yes, pptr() > epptr() is possible here, but this is ok. content_length++; } // Aligning the content by padding if necessary. const auto padding_length = dmitigr::math::padding<std::streamsize>(content_length, 8); DMITIGR_ASSERT(padding_length <= epptr() - pptr() + 1); std::memset(pptr(), 0, static_cast<std::size_t>(padding_length)); pbump(static_cast<int>(padding_length)); // Injecting the header. auto* const header = reinterpret_cast<detail::Header*>(buffer_); *header = detail::Header{static_cast<detail::Record_type>(type_), connection_->request_id(), static_cast<std::size_t>(content_length), static_cast<std::size_t>(padding_length)}; // Sending the record. if (const auto record_size = pptr() - buffer_; static_cast<std::size_t>(record_size) > sizeof(detail::Header)) { const std::streamsize count = connection_->io_->write(static_cast<const char*>(buffer_), record_size); DMITIGR_ASSERT(count == record_size); is_put_area_at_least_once_consumed_ = true; } } setp(buffer_ + sizeof(detail::Header), buffer_ + buffer_size_ - 1); if (is_end_records_must_be_transmitted_) { /* * We'll use buffer_ directly here. (Space before pbase() will be used.) * data_size is a size of data in the buffer_ to send. */ std::streamsize data_size{}; const auto is_empty = [this]() { return pptr() == pbase() && !is_put_area_at_least_once_consumed_; }; if (type_ != Type::err || !is_empty()) { /* * When transmitting a stream other than stderr, at least one record of * the stream type must be trasmitted, even if the stream is empty. * When transmitting a stream of type stderr and there is no errors to * report, either no stderr records or one zero-length stderr record * must be transmitted. (As optimization, no stderr records are * transmitted if the stream is empty.) */ auto* const header = reinterpret_cast<detail::Header*>(buffer_ + data_size); *header = detail::Header{static_cast<detail::Record_type>(type_), connection_->request_id(), 0, 0}; data_size += sizeof(detail::Header); } /* * Assume that the stream of type `out` is closes last. (This must be * guaranteed by the implementation of Listener.) */ if (type_ == Type::out) { auto* const record = reinterpret_cast<detail::End_request_record*>(buffer_ + data_size); *record = detail::End_request_record{ connection_->request_id(), connection_->application_status(), detail::Protocol_status::request_complete}; data_size += sizeof(detail::End_request_record); } if (data_size > 0) { const std::streamsize count = connection_->io_->write(static_cast<const char*>(buffer_), data_size); DMITIGR_ASSERT(count == data_size); } is_end_records_must_be_transmitted_ = false; is_end_of_stream_ = true; } DMITIGR_ASSERT(is_invariant_ok()); return is_eof ? traits_type::not_eof(ch) : ch; } private: friend server_Istream; /** * @brief A result of process_header(). */ enum class Process_header_result { /** A request is rejected. */ request_rejected, /** A management record processed. */ management_processed, /** A content from a client must be consumed. */ content_must_be_consumed, /** A content from a client must be discarded. */ content_must_be_discarded }; Type type_{}; bool is_content_must_be_discarded_{}; bool is_end_of_stream_{}; bool is_end_records_must_be_transmitted_{}; bool is_put_area_at_least_once_consumed_{}; char_type* buffer_{}; char_type* buffer_end_{}; // Used by underflow() to mark the actual end of get area. (buffer_end_ <= buffer_ + buffer_size_). std::streamsize buffer_size_{}; // The available size of the area pointed by buffer_. std::streamsize unread_content_length_{}; std::streamsize unread_padding_length_{}; iServer_connection* const connection_{}; // =========================================================================== bool is_invariant_ok() const { const bool connection_ok = (connection_ != nullptr); const bool buffer_ok = (buffer_ != nullptr) && (!is_reader() || ((buffer_end_ != nullptr) && (buffer_end_ <= buffer_ + buffer_size_))); const bool buffer_size_ok = (buffer_size_ >= 2048) && (buffer_size_ <= 65528) && (buffer_size_ % 8 == 0); const bool unread_content_length_ok = (unread_content_length_ <= buffer_size_ && unread_content_length_ <= static_cast<std::streamsize>(detail::Header::max_content_length)); const bool unread_padding_length_ok = (unread_padding_length_ <= buffer_size_ && unread_padding_length_ <= static_cast<std::streamsize>(detail::Header::max_padding_length)); const bool reader_ok = (!is_reader() || (type_ == Type::params) || (connection_->role() == Role{0}) || // unread yet (connection_->role() == Role::responder && type_ == Type::in) || (connection_->role() == Role::filter && (type_ == Type::in || type_ == Type::data))); const bool closed_ok = (is_closed() && (is_reader() || is_end_of_stream_) && (eback() == nullptr && gptr() == nullptr && egptr() == nullptr) && (pbase() == nullptr && pptr() == nullptr && epptr() == nullptr)) || (is_reader() && !(eback() == nullptr && gptr() == nullptr && egptr() == nullptr) && (pbase() == nullptr && pptr() == nullptr && epptr() == nullptr)) || (!is_reader() && (eback() == nullptr && gptr() == nullptr && egptr() == nullptr) && !(pbase() == nullptr && pptr() == nullptr && epptr() == nullptr)); const bool put_area_ok = is_reader() || (is_closed() || ((pbase() <= pptr() && pptr() <= epptr()) && (is_end_of_stream_ || (pbase() == buffer_ + sizeof(detail::Header))))); const bool get_area_ok = !is_reader() || (is_closed() || (eback() <= gptr() && gptr() <= egptr() && egptr() <= buffer_end_)); const bool result = connection_ok && buffer_ok && buffer_size_ok && unread_content_length_ok && unread_padding_length_ok && reader_ok & closed_ok && put_area_ok && get_area_ok; return result; } // =========================================================================== /** * @brief Processes a record by the header info. * * - (1) If `header` is the header of begin-request record then rejecting * the request; * - (2) If `header` is the header of management record, then responds with * get-values-result or unknown-type record; * - (3) If `header` is the header of stream record then do nothing. * * @returns * In case (1): Process_header_result::request_rejected. * In case (2): Process_header_result::management_processed. * In case (3): * a) Process_header_result::content_must_be_discarded * if `(header.request_id() != connection_->request_id())`; * b) Process_header_result::content_must_be_consumed * if and only if `(header.record_type() == type_)`. * * @throws Generic_exception in case of (1) or on protocol violation. * * @par Effects * In all cases: `(unread_content_length_ == header.content_length() && unread_padding_length_ == header.padding_length())`; * In case (2): the effects of underflow(). */ Process_header_result process_header(const detail::Header header) { header.check_validity(); unread_content_length_ = static_cast<decltype(unread_content_length_)>(header.content_length()); unread_padding_length_ = static_cast<decltype(unread_content_length_)>(header.padding_length()); const auto end_request = [&](const detail::Protocol_status protocol_status) { const detail::End_request_record record{header.request_id(), 0, protocol_status}; const auto count = connection_->io_->write(reinterpret_cast<const char*>(&record), sizeof(record)); DMITIGR_ASSERT(count == sizeof(record)); }; // Called in cases of protocol violation. const auto end_request_protocol_violation = [&]() { end_request(detail::Protocol_status::cant_mpx_conn); throw Generic_exception{"FastCGI protocol violation"}; }; const auto process_management_record = [&]() { namespace math = dmitigr::math; if (header.record_type() == detail::Record_type::get_values) { constexpr std::size_t max_variable_name_length = 15; // Length of "FCGI_MPXS_CONNS". constexpr std::size_t max_body_length = 3 * (sizeof(char) + sizeof(char) + max_variable_name_length + sizeof(char)); constexpr std::streamsize max_record_length = sizeof(detail::Header) + max_body_length; std::array<unsigned char, math::aligned<std::size_t>(max_record_length, 8)> record; static_assert((record.size() % 8 == 0)); // Reading the requested variables. const auto variables = [&]() { std::istream stream{this}; return detail::Names_values{stream, 3}; }(); if (unread_content_length_ > 0) end_request_protocol_violation(); // Filling up the content of get-values-result. const auto content_offset = std::begin(record) + sizeof(detail::Header); auto p = content_offset; const auto variables_count = variables.pair_count(); for (std::size_t i = 0; i < variables_count; ++i) { const auto name = variables.pair(i)->name(); char value{}; if (name == "FCGI_MAX_CONNS") value = '1'; else if (name == "FCGI_MAX_REQS") value = '1'; else if (name == "FCGI_MPXS_CONNS") value = '0'; else continue; // Ignoring other variables specified in the get-values record. const auto name_size = name.size(); if (name_size > std::numeric_limits<unsigned char>::max()) end_request_protocol_violation(); // Note: name_size + 3 - is a space required to store: {char(name_size), char(1), name.data(), char(value)} string. DMITIGR_ASSERT(name_size + 3 <= static_cast<std::size_t>(std::cend(record) - p)); *p++ = static_cast<unsigned char>(name_size); // name_size *p++ = static_cast<unsigned char>(1); // 1 p = std::copy(cbegin(name), cend(name), p); // name.data() *p++ = static_cast<unsigned char>(value); // value } using detail::Header; const auto content_length = p - content_offset; const auto padding_length = math::padding<std::streamsize>(content_length, 8); const auto record_length = static_cast<int>(sizeof(Header)) + content_length + padding_length; auto* const h = reinterpret_cast<Header*>(record.data()); *h = detail::Header{detail::Record_type::get_values_result, Header::null_request_id, static_cast<std::size_t>(content_length), static_cast<std::size_t>(padding_length)}; const auto count = connection_->io_->write(reinterpret_cast<const char*>(record.data()), record_length); DMITIGR_ASSERT(count == record_length); } else { const detail::Unknown_type_record r{header.record_type()}; const std::streamsize record_length = sizeof(r); const auto count = connection_->io_->write(reinterpret_cast<const char*>(&r), record_length); DMITIGR_ASSERT(count == record_length); } return Process_header_result::management_processed; }; Process_header_result result{}; if (header.record_type() == detail::Record_type::begin_request) { end_request(detail::Protocol_status::cant_mpx_conn); result = Process_header_result::content_must_be_discarded; } else if (header.is_management_record()) result = process_management_record(); else if (header.request_id() != connection_->request_id()) result = Process_header_result::content_must_be_discarded; else if (header.record_type() == static_cast<detail::Record_type>(type_)) result = Process_header_result::content_must_be_consumed; else end_request_protocol_violation(); DMITIGR_ASSERT(is_invariant_ok()); return result; } /** * @brief Resets the input stream to read the data of the specified type. * * @par Requires * `is_reader()`. */ void reset_reader(const Type type) { DMITIGR_ASSERT(is_reader() && !is_closed()); type_ = type; is_end_of_stream_ = false; is_content_must_be_discarded_ = false; unread_content_length_ = 0; unread_padding_length_ = 0; DMITIGR_ASSERT(is_invariant_ok()); } #ifdef DMITIGR_FCGI_DEBUG template<typename ... Types> void print(Types&& ... msgs) const { if (type_ == Stream_type::out) { ((std::cerr << std::forward<Types>(msgs) << " "), ...); std::cerr << std::endl; } } #endif }; } // namespace dmitigr::fcgi::detail
36.378671
128
0.637804
dmitigr
41a4315da01c7f6bd5f6cdda58c57442094e2b72
2,145
cpp
C++
src/problems/1_2/solution.cpp
philong6297/modern-cpp-challenges
c3f9786aff9dd097ee1e4ec7ac65560e447c28b5
[ "MIT" ]
null
null
null
src/problems/1_2/solution.cpp
philong6297/modern-cpp-challenges
c3f9786aff9dd097ee1e4ec7ac65560e447c28b5
[ "MIT" ]
null
null
null
src/problems/1_2/solution.cpp
philong6297/modern-cpp-challenges
c3f9786aff9dd097ee1e4ec7ac65560e447c28b5
[ "MIT" ]
null
null
null
// Copyright 2021 Long Le Phi. All rights reserved. // Use of this source code is governed by a MIT license that can be // found in the LICENSE file. #include "problems/1_2/solution.hpp" #include <numeric> #if defined(_MSC_VER) # include <intrin.h> #endif namespace { using longlp::solution::Problem_1_2; inline auto CountTrailingZeros(const uintmax_t u) -> uintmax_t { #if defined(_MSC_VER) unsigned long trailing_zero = 0; if (_BitScanForward64(&trailing_zero, u) != 0U) { return trailing_zero; } // This is undefined, I better choose 64 than 0 return 64; #elif defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) return __builtin_ctzll(u); #endif } } // namespace // static auto Problem_1_2::StandardGCD(const uintmax_t u, const uintmax_t v) -> uintmax_t { return std::gcd(u, v); } // https://lemire.me/blog/2013/12/26/fastest-way-to-compute-the-greatest-common-divisor/ // static auto Problem_1_2::BinaryGCD(uintmax_t u, uintmax_t v) -> uintmax_t { // Base cases: gcd(n, 0) = gcd(0, n) = n if (u == 0) { return v; } if (v == 0) { return u; } // Using identity 2: gcd(2u, 2v) = 2*gcd(u, v) // Using identity 3: gcd(2u, v) = gcd(u, v), if v is odd (2 is not a common // divisor). Similarly, gcd(u, 2v) = gcd(u, v) if u is odd. // gcd(u * 2^i, v * 2^j) = gcd(u, v) * 2^k with u, v odd and k = min(i, j). // 2^k is the greatest power of two that divides both u and v // The number of trailing 0-bits in x, starting at the least significant bit // position, represent for k. uintmax_t k = CountTrailingZeros(u | v); // Identity 3: gcd(u, v * 2^j) = gcd(u, v) (u is known to be odd) u >>= CountTrailingZeros(u); do { // Identity 3: gcd(u, v * 2^j) = gcd(u, v) (u is known to be odd) v >>= CountTrailingZeros(v); // swap to make sure u <= v if (u > v) { std::swap(u, v); } // Using identity 4 (gcd(u, v) = gcd(|v-u|, min(u, v)) v = v - u; } while (v != 0); // Identity 1: gcd(u, 0) = u // The shift by k is necessary to add back the 2^k factor that was removed b // fore the loop return u << k; }
27.151899
88
0.620513
philong6297
41a5dc84a8361385f2eaea2907a30a4ea42f78a7
1,512
cpp
C++
cxx/pass.cpp
snewell/advent2020
d7800b549401624ee75b271a37238162590b9068
[ "X11" ]
null
null
null
cxx/pass.cpp
snewell/advent2020
d7800b549401624ee75b271a37238162590b9068
[ "X11" ]
null
null
null
cxx/pass.cpp
snewell/advent2020
d7800b549401624ee75b271a37238162590b9068
[ "X11" ]
null
null
null
#include <aoc/pass.hpp> #include <algorithm> #include <cassert> #include <string_view> namespace { } namespace aoc2020 { Seat parse_pass(std::string const & seat) { assert(seat.length() == 10); auto calculate_assignment = [](std::string_view info, int low, int high, char left, char right) { auto calculate_midpoint = [](int low, int high) { auto const distance = high - low + 1; return low + (distance / 2); }; std::for_each( std::begin(info), std::end(info), [&low, &high, calculate_midpoint, left, right](auto ch) { auto const new_boundary = calculate_midpoint(low, high); if(ch == left) { high = new_boundary; } else { assert(ch == right); low = new_boundary; } }); return low; }; return Seat{calculate_assignment(std::string_view(seat.data(), 7), 0, 127, 'F', 'B'), calculate_assignment(std::string_view(seat.data() + 7, 3), 0, 8, 'L', 'R')}; } int calculate_id(Seat const & seat) noexcept { return (seat.row * 8) + seat.column; } } // namespace aoc2020
28.528302
80
0.434524
snewell
41ac0434e2cf353fae6f2dba2ac4c34391ce4309
5,493
cpp
C++
prototype/entity.cpp
llGuy/graphics
7e77bb04715b68465e2718077102f894371e56fc
[ "MIT" ]
null
null
null
prototype/entity.cpp
llGuy/graphics
7e77bb04715b68465e2718077102f894371e56fc
[ "MIT" ]
null
null
null
prototype/entity.cpp
llGuy/graphics
7e77bb04715b68465e2718077102f894371e56fc
[ "MIT" ]
null
null
null
#include "entity.h" #include "render.h" #include "global.h" #include <GLFW/glfw3.h> #include <glm/gtx/transform.hpp> entity_data_base EntityDataBase = {}; internal void UpdateModelMatrixComponents(std::vector<model_matrix_component> &Components , std::vector<entity_data> &Entities) { model_matrix_component *End = &( Components.back() ) + 1; for (model_matrix_component *Component = &( Components[0] ) ; Component != End ; ++Component) { entity_data *Entity = &( Entities[Component->EntityID] ); glm::mat4 TranslateMatrix = glm::translate(Entity->Position3D); glm::mat4 ScaleMatrix = glm::scale(Entity->Scale3D); Component->TRS = TranslateMatrix * ScaleMatrix; } } internal void UpdateRenderComponents(std::vector<render_component> &Components , std::vector<model_matrix_component> &ModelMatrices , std::vector<entity_data> &Entities) { render_component *End = &( Components.back() ) + 1; for (render_component *Component = &( Components[0] ) ; Component != End ; ++Component) { entity_data *Entity = &Entities[Component->EntityID]; int32 ModelMatrixIndex = Entity->Components.ModelMatrixComponentIndex; if (ModelMatrixIndex != MISSING_COMPONENT) { model_instance Instance{ Component->Model, ModelMatrices[ModelMatrixIndex].TRS }; Component->Layer->Instances.push_back(Instance); } } } internal void UpdateKeyboardComponents(std::vector<keyboard_component> &Components , std::vector<entity_data> &Entities) { local_persist auto GetLateral = [](const glm::vec3 &Vector) -> glm::vec3 { return glm::normalize(glm::vec3(Vector.x, 0.0f, Vector.z)); }; keyboard_component *End = &( Components.back() ) + 1; for (keyboard_component *Component = &( Components[0] ) ; Component != End ; ++Component) { entity_data *Entity = &Entities[Component->EntityID]; if (Entity->Components.KeyboardComponentIndex != MISSING_COMPONENT) { glm::vec3 LateralDirection3D = GetLateral(Entity->Direction3D); if (glm::all(glm::lessThan(Entity->Velocity3D , glm::vec3(100000000.0f)))) { if (WindowData.KeyMap[GLFW_KEY_W]) Entity->Velocity3D += LateralDirection3D; if (WindowData.KeyMap[GLFW_KEY_A]) Entity->Velocity3D -= glm::cross(LateralDirection3D, glm::vec3(0.0f, 1.0f, 0.0f)); if (WindowData.KeyMap[GLFW_KEY_S]) Entity->Velocity3D -= LateralDirection3D; if (WindowData.KeyMap[GLFW_KEY_D]) Entity->Velocity3D += glm::cross(LateralDirection3D, glm::vec3(0.0f, 1.0f, 0.0f)); if (WindowData.KeyMap[GLFW_KEY_SPACE]) Entity->Velocity3D += glm::vec3(0.0f, 1.0f, 0.0f); if (WindowData.KeyMap[GLFW_KEY_LEFT_SHIFT]) Entity->Velocity3D += glm::vec3(0.0f, -1.0f, 0.0f); } } } } // TODO Parameterize mouse sensitivity #define MOUSE_SENSITIVITY 0.02f internal void UpdateMouseComponents(std::vector<mouse_component> &Components , std::vector<entity_data> &Entities) { local_persist auto RotateDirection = [](const glm::vec2 &CursorDifference , const glm::vec3 &Direction , window_data &WindowData) -> glm::vec3 { glm::vec3 NewDirection = Direction; float XAngle = glm::radians(-CursorDifference.x) * MOUSE_SENSITIVITY; float YAngle = glm::radians(-CursorDifference.y) * MOUSE_SENSITIVITY; NewDirection = glm::mat3(glm::rotate(XAngle, glm::vec3(0.0f, 1.0f, 0.0f))) * NewDirection; glm::vec3 YRotateAxis = glm::cross(NewDirection, glm::vec3(0.0f, 1.0f, 0.0f)); NewDirection = glm::mat3(glm::rotate(YAngle, YRotateAxis)) * NewDirection; return NewDirection; }; mouse_component *End = &( Components.back() ) + 1; for (mouse_component *Component = &( Components[0] ) ; Component != End ; ++Component) { entity_data *Entity = &Entities[Component->EntityID]; if (WindowData.MouseMoved) { glm::vec2 Difference = WindowData.CurrentMousePosition - Component->PreviousMousePosition; Component->PreviousMousePosition = WindowData.CurrentMousePosition; Entity->Direction3D = normalize(RotateDirection(Difference , Entity->Direction3D , WindowData)); } } } #define SPEED 5.0f internal void UpdatePhysicsComponents(std::vector<physics_component> &Components , std::vector<entity_data> &Entities) { physics_component *End = &( Components.back() ) + 1; for (physics_component *Component = &( Components[0] ) ; Component != End ; ++Component) { entity_data *Entity = &Entities[Component->EntityID]; Entity->Position3D += Entity->Velocity3D * TimeData.Elapsed() * SPEED; Entity->Velocity3D = glm::vec3(0.0f); } } uint32 entity_data_base::CreateEntity(const string_view &Name) { uint32 ID = Entities.size(); IndexMap[Name] = ID; Entities.push_back(entity_data {}); return ID; } entity_data * entity_data_base::GetEntity(uint32 ID) { return &Entities[ID]; } void entity_data_base::Update(void) { UpdateModelMatrixComponents(ModelMatrixComponents.List , Entities); UpdateRenderComponents(RenderComponents.List , ModelMatrixComponents.List , Entities); UpdateKeyboardComponents(KeyboardComponents.List , Entities); UpdateMouseComponents(MouseComponents.List, Entities); UpdatePhysicsComponents(PhysicsComponents.List , Entities); }
31.033898
120
0.673585
llGuy
41ad84f0db91c4d83da32663187049ae422ab567
30,868
cpp
C++
Engine/source/terrain/terrCellMaterial.cpp
GoldenThumbs/Torque3D
312d55be479c212f10239828fd2486fc03827d5e
[ "MIT" ]
9
2015-01-07T17:24:28.000Z
2021-08-15T17:49:08.000Z
Engine/source/terrain/terrCellMaterial.cpp
GoldenThumbs/Torque3D
312d55be479c212f10239828fd2486fc03827d5e
[ "MIT" ]
3
2015-09-24T05:10:05.000Z
2016-07-06T15:07:54.000Z
Engine/source/terrain/terrCellMaterial.cpp
GoldenThumbs/Torque3D
312d55be479c212f10239828fd2486fc03827d5e
[ "MIT" ]
5
2015-02-14T21:00:28.000Z
2021-07-10T01:05:09.000Z
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // 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 "platform/platform.h" #include "terrain/terrCellMaterial.h" #include "core/util/safeRelease.h" #include "terrain/terrData.h" #include "terrain/terrCell.h" #include "materials/materialFeatureTypes.h" #include "materials/materialManager.h" #include "terrain/terrFeatureTypes.h" #include "terrain/terrMaterial.h" #include "renderInstance/renderDeferredMgr.h" #include "shaderGen/shaderGen.h" #include "shaderGen/featureMgr.h" #include "scene/sceneRenderState.h" #include "materials/sceneData.h" #include "gfx/util/screenspace.h" #include "lighting/advanced/advancedLightBinManager.h" S32 sgMaxTerrainMaterialsPerPass = 32; AFTER_MODULE_INIT( MaterialManager ) { Con::NotifyDelegate callabck( &TerrainCellMaterial::_updateDefaultAnisotropy ); Con::addVariableNotify( "$pref::Video::defaultAnisotropy", callabck ); } Vector<TerrainCellMaterial*> TerrainCellMaterial::smAllMaterials; Vector<String> _initSamplerNames() { Vector<String> samplerNames; samplerNames.push_back("$baseTexMap"); samplerNames.push_back("$layerTex"); samplerNames.push_back("$lightMapTex"); samplerNames.push_back("$lightInfoBuffer"); samplerNames.push_back("$normalMapSampler"); samplerNames.push_back("$detailMapSampler"); samplerNames.push_back("$macroMapSampler"); samplerNames.push_back("$ormMapSampler"); return samplerNames; } const Vector<String> TerrainCellMaterial::mSamplerNames = _initSamplerNames(); TerrainCellMaterial::TerrainCellMaterial() : mTerrain( NULL ), mDeferredMat( NULL ), mReflectMat( NULL ), mShader( NULL ), mCurrPass( 0 ), mMaterials( 0 ) { smAllMaterials.push_back( this ); } TerrainCellMaterial::~TerrainCellMaterial() { SAFE_DELETE( mDeferredMat ); SAFE_DELETE( mReflectMat ); smAllMaterials.remove( this ); T3D::for_each(mMaterialInfos.begin(), mMaterialInfos.end(), T3D::delete_pointer()); mMaterialInfos.clear(); } void TerrainCellMaterial::_updateDefaultAnisotropy() { // TODO: We need to split the stateblock initialization // from the shader constant lookup and pass setup in a // future version of terrain materials. // // For now use some custom code in a horrible loop to // change the anisotropy directly and fast. // const U32 maxAnisotropy = MATMGR->getDefaultAnisotropy(); Vector<TerrainCellMaterial*>::iterator iter = smAllMaterials.begin(); for ( ; iter != smAllMaterials.end(); iter++ ) { // Start from the existing state block. GFXStateBlockDesc desc = (*iter)->mStateBlock->getDesc(); if ((*iter)->mDetailTexArrayConst->isValid()) { const S32 sampler = (*iter)->mDetailTexArrayConst->getSamplerRegister(); if (maxAnisotropy > 1) { desc.samplers[sampler].minFilter = GFXTextureFilterAnisotropic; desc.samplers[sampler].maxAnisotropy = maxAnisotropy; } else desc.samplers[sampler].minFilter = GFXTextureFilterLinear; } if ((*iter)->mMacroTexArrayConst->isValid()) { const S32 sampler = (*iter)->mMacroTexArrayConst->getSamplerRegister(); if (maxAnisotropy > 1) { desc.samplers[sampler].minFilter = GFXTextureFilterAnisotropic; desc.samplers[sampler].maxAnisotropy = maxAnisotropy; } else desc.samplers[sampler].minFilter = GFXTextureFilterLinear; } if ((*iter)->mNormalTexArrayConst->isValid()) { const S32 sampler = (*iter)->mNormalTexArrayConst->getSamplerRegister(); if (maxAnisotropy > 1) { desc.samplers[sampler].minFilter = GFXTextureFilterAnisotropic; desc.samplers[sampler].maxAnisotropy = maxAnisotropy; } else desc.samplers[sampler].minFilter = GFXTextureFilterLinear; } if ((*iter)->mOrmTexArrayConst->isValid()) { const S32 sampler = (*iter)->mOrmTexArrayConst->getSamplerRegister(); if (maxAnisotropy > 1) { desc.samplers[sampler].minFilter = GFXTextureFilterAnisotropic; desc.samplers[sampler].maxAnisotropy = maxAnisotropy; } else desc.samplers[sampler].minFilter = GFXTextureFilterLinear; } // Set the updated stateblock. desc.setCullMode(GFXCullCCW); (*iter)->mStateBlock = GFX->createStateBlock(desc); //reflection desc.setCullMode(GFXCullCW); (*iter)->mReflectionStateBlock = GFX->createStateBlock(desc); // Create the wireframe state blocks. GFXStateBlockDesc wireframe(desc); wireframe.fillMode = GFXFillWireframe; wireframe.setCullMode(GFXCullCCW); (*iter)->mWireframeStateBlock = GFX->createStateBlock(wireframe); } } void TerrainCellMaterial::setTransformAndEye( const MatrixF &modelXfm, const MatrixF &viewXfm, const MatrixF &projectXfm, F32 farPlane ) { PROFILE_SCOPE( TerrainCellMaterial_SetTransformAndEye ); MatrixF modelViewProj = projectXfm * viewXfm * modelXfm; MatrixF invViewXfm( viewXfm ); invViewXfm.inverse(); Point3F eyePos = invViewXfm.getPosition(); MatrixF invModelXfm( modelXfm ); invModelXfm.inverse(); Point3F objEyePos = eyePos; invModelXfm.mulP( objEyePos ); VectorF vEye = invViewXfm.getForwardVector(); vEye.normalize( 1.0f / farPlane ); mConsts->setSafe(mModelViewProjConst, modelViewProj); if (mViewToObjConst->isValid() || mWorldViewOnlyConst->isValid()) { MatrixF worldViewOnly = viewXfm * modelXfm; mConsts->setSafe(mWorldViewOnlyConst, worldViewOnly); if (mViewToObjConst->isValid()) { worldViewOnly.affineInverse(); mConsts->set(mViewToObjConst, worldViewOnly); } } mConsts->setSafe(mEyePosWorldConst, eyePos); mConsts->setSafe(mEyePosConst, objEyePos); mConsts->setSafe(mObjTransConst, modelXfm); mConsts->setSafe(mWorldToObjConst, invModelXfm); mConsts->setSafe(mVEyeConst, vEye); } TerrainCellMaterial* TerrainCellMaterial::getDeferredMat() { if ( !mDeferredMat ) { mDeferredMat = new TerrainCellMaterial(); mDeferredMat->init( mTerrain, mMaterials, true, false, mMaterials == 0 ); } return mDeferredMat; } TerrainCellMaterial* TerrainCellMaterial::getReflectMat() { if ( !mReflectMat ) { mReflectMat = new TerrainCellMaterial(); mReflectMat->init( mTerrain, mMaterials, false, true, true ); } return mReflectMat; } void TerrainCellMaterial::init( TerrainBlock *block, U64 activeMaterials, bool deferredMat, bool reflectMat, bool baseOnly ) { // This isn't allowed for now. AssertFatal( !( deferredMat && reflectMat ), "TerrainCellMaterial::init - We shouldn't get deferred and reflection in the same material!" ); mTerrain = block; mMaterials = activeMaterials; mMaterialInfos.clear(); for ( U32 i = 0; i < 64; i++ ) { if ( !( mMaterials & ((U64)1 << i ) ) ) continue; TerrainMaterial *mat = block->getMaterial( i ); MaterialInfo *info = new MaterialInfo(); info->layerId = i; info->mat = mat; mMaterialInfos.push_back(info); } if (!_initShader(deferredMat, reflectMat, baseOnly)) { Con::errorf("TerrainCellMaterial::init - Failed to init shader!"); T3D::for_each(mMaterialInfos.begin(), mMaterialInfos.end(), T3D::delete_pointer()); mMaterialInfos.clear(); return; } // If we have attached mats then update them too. if ( mDeferredMat ) mDeferredMat->init( mTerrain, mMaterials, true, false, baseOnly ); if ( mReflectMat ) mReflectMat->init( mTerrain, mMaterials, false, true, baseOnly ); } bool TerrainCellMaterial::_initShader(bool deferredMat, bool reflectMat, bool baseOnly) { if (GFX->getPixelShaderVersion() < 3.0f) baseOnly = true; // NOTE: At maximum we only try to combine sgMaxTerrainMaterialsPerPass materials // into a single pass. This is sub-optimal for the simplest // cases, but the most common case results in much fewer // shader generation failures and permutations leading to // faster load time and less hiccups during gameplay. U32 matCount = getMin(sgMaxTerrainMaterialsPerPass, mMaterialInfos.size()); Vector<GFXTexHandle> normalMaps; // See if we're currently running under the // basic lighting manager. // // TODO: This seems ugly... we should trigger // features like this differently in the future. // bool useBLM = String::compare(LIGHTMGR->getId(), "BLM") == 0; // Do we need to disable normal mapping? const bool disableNormalMaps = MATMGR->getExclusionFeatures().hasFeature(MFT_NormalMap) || useBLM; // How about parallax? const bool disableParallaxMaps = GFX->getPixelShaderVersion() < 3.0f || MATMGR->getExclusionFeatures().hasFeature(MFT_Parallax); // Has advanced lightmap support been enabled for deferred. bool advancedLightmapSupport = false; if (deferredMat) { // This sucks... but it works. AdvancedLightBinManager* lightBin; if (Sim::findObject("AL_LightBinMgr", lightBin)) advancedLightmapSupport = lightBin->MRTLightmapsDuringDeferred(); } // Loop till we create a valid shader! while (true) { FeatureSet features; features.addFeature(MFT_VertTransform); features.addFeature(MFT_TerrainBaseMap); if (deferredMat) { features.addFeature(MFT_EyeSpaceDepthOut); features.addFeature(MFT_DeferredConditioner); features.addFeature(MFT_isDeferred); if (advancedLightmapSupport) features.addFeature(MFT_RenderTarget3_Zero); } else { features.addFeature(MFT_RTLighting); // The HDR feature is always added... it will compile out // if HDR is not enabled in the engine. features.addFeature(MFT_HDROut); } // Enable lightmaps and fogging if we're in BL. if (reflectMat || useBLM) { features.addFeature(MFT_Fog); features.addFeature(MFT_ForwardShading); } if (useBLM) features.addFeature(MFT_TerrainLightMap); normalMaps.clear(); S32 featureIndex = 0; // Now add all the material layer features. for (U32 i = 0; i < matCount && !baseOnly; i++) { TerrainMaterial* mat = mMaterialInfos[i]->mat; if (mat == NULL) continue; // We only include materials that // have more than a base texture. if (mat->getDetailSize() <= 0 || mat->getDetailDistance() <= 0 || mat->getDetailMap().isEmpty()) continue; // check for macro detail texture if (!(mat->getMacroSize() <= 0 || mat->getMacroDistance() <= 0 || mat->getMacroMap().isEmpty())) { if (deferredMat) features.addFeature(MFT_isDeferred, featureIndex); features.addFeature(MFT_TerrainMacroMap, featureIndex); } if (deferredMat) features.addFeature(MFT_isDeferred, featureIndex); features.addFeature(MFT_TerrainDetailMap, featureIndex); if (deferredMat) { if (!(mat->getORMConfigMap().isEmpty())) { features.addFeature(MFT_TerrainORMMap, featureIndex); } else { features.addFeature(MFT_DeferredTerrainBlankInfoMap, featureIndex); } } if (mat->getInvertRoughness()) features.addFeature(MFT_InvertRoughness, featureIndex); normalMaps.increment(); // Skip normal maps if we need to. if (!disableNormalMaps && mat->getNormalMap().isNotEmpty()) { features.addFeature(MFT_TerrainNormalMap, featureIndex); normalMaps.last().set(mat->getNormalMap(), &GFXNormalMapProfile, "TerrainCellMaterial::_initShader() - NormalMap"); GFXFormat normalFmt = normalMaps.last().getFormat(); if (normalFmt == GFXFormatBC3) features.addFeature(MFT_IsBC3nm, featureIndex); else if (normalFmt == GFXFormatBC5) features.addFeature(MFT_IsBC5nm, featureIndex); // Do we need and can we do parallax mapping? if (!disableParallaxMaps && mat->getParallaxScale() > 0.0f && !mat->useSideProjection()) features.addFeature(MFT_TerrainParallaxMap, featureIndex); } // Is this layer got side projection? if (mat->useSideProjection()) features.addFeature(MFT_TerrainSideProject, featureIndex); featureIndex++; } // New blending if (matCount > 0 && !Con::getBoolVariable("$Terrain::LerpBlend", false)) { features.addFeature(MFT_TerrainHeightBlend); } MaterialFeatureData featureData; featureData.features = features; featureData.materialFeatures = features; // Check to see how many vertex shader output // registers we're gonna need. U32 numTex = 0; U32 numTexReg = 0; for (U32 i = 0; i < features.getCount(); i++) { S32 index; const FeatureType& type = features.getAt(i, &index); ShaderFeature* sf = FEATUREMGR->getByType(type); if (!sf) continue; sf->setProcessIndex(index); ShaderFeature::Resources res = sf->getResources(featureData); numTex += res.numTex; numTexReg += res.numTexReg; } // Can we build the shader? // // NOTE: The 10 is sort of an abitrary SM 3.0 // limit. Its really supposed to be 11, but that // always fails to compile so far. // if (numTex < GFX->getNumSamplers() && numTexReg <= 10) { // NOTE: We really shouldn't be getting errors building the shaders, // but we can generate more instructions than the ps_2_x will allow. // // There is no way to deal with this case that i know of other than // letting the compile fail then recovering by trying to build it // with fewer materials. // // We normally disable the shader error logging so that the user // isn't fooled into thinking there is a real bug. That is until // we get down to a single material. If a single material case // fails it means it cannot generate any passes at all! const bool logErrors = true;// matCount == 1; GFXShader::setLogging(logErrors, true); mShader = SHADERGEN->getShader(featureData, getGFXVertexFormat<TerrVertex>(), NULL, mSamplerNames); } // If we got a shader then we can continue. if (mShader) break; // If the material count is already 1 then this // is a real shader error... give up! if (matCount <= 1) return false; // If we failed we next try half the input materials // so that we can more quickly arrive at a valid shader. matCount -= matCount / 2; } // Setup the constant buffer. mConsts = mShader->allocConstBuffer(); // Prepare the basic constants. mModelViewProjConst = mShader->getShaderConstHandle("$modelview"); mWorldViewOnlyConst = mShader->getShaderConstHandle("$worldViewOnly"); mViewToObjConst = mShader->getShaderConstHandle("$viewToObj"); mEyePosWorldConst = mShader->getShaderConstHandle("$eyePosWorld"); mEyePosConst = mShader->getShaderConstHandle("$eyePos"); mVEyeConst = mShader->getShaderConstHandle("$vEye"); mLayerSizeConst = mShader->getShaderConstHandle("$layerSize"); mObjTransConst = mShader->getShaderConstHandle("$objTrans"); mWorldToObjConst = mShader->getShaderConstHandle("$worldToObj"); mLightInfoBufferConst = mShader->getShaderConstHandle("$lightInfoBuffer"); mBaseTexMapConst = mShader->getShaderConstHandle("$baseTexMap"); mLayerTexConst = mShader->getShaderConstHandle("$layerTex"); mFogDataConst = mShader->getShaderConstHandle("$fogData"); mFogColorConst = mShader->getShaderConstHandle("$fogColor"); mLightMapTexConst = mShader->getShaderConstHandle("$lightMapTex"); mOneOverTerrainSizeConst = mShader->getShaderConstHandle("$oneOverTerrainSize"); mSquareSizeConst = mShader->getShaderConstHandle("$squareSize"); mBlendDepthConst = mShader->getShaderConstHandle("$baseBlendDepth"); mLightParamsConst = mShader->getShaderConstHandle("$rtParamslightInfoBuffer"); // Now prepare the basic stateblock. GFXStateBlockDesc desc; // We write to the zbuffer if this is a deferred // material or if the deferred is disabled. desc.setZReadWrite(true, !MATMGR->getDeferredEnabled() || deferredMat || reflectMat); desc.samplersDefined = true; if (mBaseTexMapConst->isValid()) desc.samplers[mBaseTexMapConst->getSamplerRegister()] = GFXSamplerStateDesc::getWrapLinear(); if (mLayerTexConst->isValid()) desc.samplers[mLayerTexConst->getSamplerRegister()] = GFXSamplerStateDesc::getClampPoint(); if (mLightInfoBufferConst->isValid()) desc.samplers[mLightInfoBufferConst->getSamplerRegister()] = GFXSamplerStateDesc::getClampPoint(); if (mLightMapTexConst->isValid()) desc.samplers[mLightMapTexConst->getSamplerRegister()] = GFXSamplerStateDesc::getWrapLinear(); const U32 maxAnisotropy = MATMGR->getDefaultAnisotropy(); mDetailInfoVArrayConst = mShader->getShaderConstHandle("$detailScaleAndFade"); mDetailInfoPArrayConst = mShader->getShaderConstHandle("$detailIdStrengthParallax"); mMacroInfoVArrayConst = mShader->getShaderConstHandle("$macroIdStrengthParallax"); mMacroInfoPArrayConst = mShader->getShaderConstHandle("$macroIdStrengthParallax"); mDetailTexArrayConst = mShader->getShaderConstHandle("$detailMapSampler"); if (mDetailTexArrayConst->isValid()) { const S32 sampler = mDetailTexArrayConst->getSamplerRegister(); desc.samplers[sampler] = GFXSamplerStateDesc::getWrapLinear(); desc.samplers[sampler].magFilter = GFXTextureFilterLinear; desc.samplers[sampler].mipFilter = GFXTextureFilterLinear; if (maxAnisotropy > 1) { desc.samplers[sampler].minFilter = GFXTextureFilterAnisotropic; desc.samplers[sampler].maxAnisotropy = maxAnisotropy; } else desc.samplers[sampler].minFilter = GFXTextureFilterLinear; } mMacroTexArrayConst = mShader->getShaderConstHandle("$macroMapSampler"); if (mMacroTexArrayConst->isValid()) { const S32 sampler = mMacroTexArrayConst->getSamplerRegister(); desc.samplers[sampler] = GFXSamplerStateDesc::getWrapLinear(); desc.samplers[sampler].magFilter = GFXTextureFilterLinear; desc.samplers[sampler].mipFilter = GFXTextureFilterLinear; if (maxAnisotropy > 1) { desc.samplers[sampler].minFilter = GFXTextureFilterAnisotropic; desc.samplers[sampler].maxAnisotropy = maxAnisotropy; } else desc.samplers[sampler].minFilter = GFXTextureFilterLinear; } mNormalTexArrayConst = mShader->getShaderConstHandle("$normalMapSampler"); if (mNormalTexArrayConst->isValid()) { const S32 sampler = mNormalTexArrayConst->getSamplerRegister(); desc.samplers[sampler] = GFXSamplerStateDesc::getWrapLinear(); desc.samplers[sampler].magFilter = GFXTextureFilterLinear; desc.samplers[sampler].mipFilter = GFXTextureFilterLinear; if (maxAnisotropy > 1) { desc.samplers[sampler].minFilter = GFXTextureFilterAnisotropic; desc.samplers[sampler].maxAnisotropy = maxAnisotropy; } else desc.samplers[sampler].minFilter = GFXTextureFilterLinear; } mOrmTexArrayConst = mShader->getShaderConstHandle("$ormMapSampler"); if (mOrmTexArrayConst->isValid()) { GFXTextureProfile* profile = &GFXStaticTextureProfile; const S32 sampler = mOrmTexArrayConst->getSamplerRegister(); desc.samplers[sampler] = GFXSamplerStateDesc::getWrapLinear(); desc.samplers[sampler].magFilter = GFXTextureFilterLinear; desc.samplers[sampler].mipFilter = GFXTextureFilterLinear; if (maxAnisotropy > 1) { desc.samplers[sampler].minFilter = GFXTextureFilterAnisotropic; desc.samplers[sampler].maxAnisotropy = maxAnisotropy; } else desc.samplers[sampler].minFilter = GFXTextureFilterLinear; } for (U32 i = 0; i < matCount && !baseOnly; i++) { TerrainMaterial* mat = mMaterialInfos[i]->mat; if (mat == NULL) continue; // We only include materials that // have more than a base texture. if (mat->getDetailSize() <= 0 || mat->getDetailDistance() <= 0 || mat->getDetailMap().isEmpty()) continue; mMaterialInfos[i]->mBlendDepthConst = mShader->getShaderConstHandle(avar("$blendDepth%d", i)); mMaterialInfos[i]->mBlendContrastConst = mShader->getShaderConstHandle(avar("$blendContrast%d", i)); } // If we're doing deferred it requires some // special stencil settings for it to work. if ( deferredMat ) desc.addDesc( RenderDeferredMgr::getOpaqueStenciWriteDesc( false ) ); desc.setCullMode( GFXCullCCW ); mStateBlock = GFX->createStateBlock(desc); //reflection stateblock desc.setCullMode( GFXCullCW ); mReflectionStateBlock = GFX->createStateBlock(desc); // Create the wireframe state blocks. GFXStateBlockDesc wireframe( desc ); wireframe.fillMode = GFXFillWireframe; wireframe.setCullMode( GFXCullCCW ); mWireframeStateBlock = GFX->createStateBlock( wireframe ); return true; } void TerrainCellMaterial::_updateMaterialConsts( ) { PROFILE_SCOPE( TerrainCellMaterial_UpdateMaterialConsts ); int detailMatCount = 0; for (MaterialInfo* materialInfo : mMaterialInfos) { if (materialInfo == NULL) continue; TerrainMaterial* mat = materialInfo->mat; if (mat == NULL) continue; // We only include materials that // have more than a base texture. if (mat->getDetailSize() <= 0 || mat->getDetailDistance() <= 0 || mat->getDetailMap().isEmpty()) continue; detailMatCount++; } if (detailMatCount == 0) { return; } AlignedArray<Point4F> detailInfoArray(detailMatCount, sizeof(Point4F)); AlignedArray<Point4F> detailScaleAndFadeArray(detailMatCount, sizeof(Point4F)); int detailIndex = 0; for (MaterialInfo* matInfo : mMaterialInfos) { if (matInfo == NULL) continue; TerrainMaterial* mat = matInfo->mat; if (mat == NULL) continue; // We only include materials that // have more than a base texture. if (mat->getDetailSize() <= 0 || mat->getDetailDistance() <= 0 || mat->getDetailMap().isEmpty()) continue; F32 detailSize = matInfo->mat->getDetailSize(); F32 detailScale = 1.0f; if ( !mIsZero( detailSize ) ) detailScale = mTerrain->getWorldBlockSize() / detailSize; // Scale the distance by the global scalar. const F32 distance = mTerrain->smDetailScale * matInfo->mat->getDetailDistance(); // NOTE: The negation of the y scale is to make up for // my mistake early in development and passing the wrong // y texture coord into the system. // // This negation fixes detail, normal, and parallax mapping // without harming the layer id blending code. // // Eventually we should rework this to correct this little // mistake, but there isn't really a hurry to. // Point4F detailScaleAndFade( detailScale, -detailScale, distance, 0 ); if ( !mIsZero( distance ) ) detailScaleAndFade.w = 1.0f / distance; Point4F detailIdStrengthParallax( matInfo->layerId, matInfo->mat->getDetailStrength(), matInfo->mat->getParallaxScale(), 0 ); detailScaleAndFadeArray[detailIndex] = detailScaleAndFade; detailInfoArray[detailIndex] = detailIdStrengthParallax; if (matInfo->mBlendDepthConst != NULL) { mConsts->setSafe(matInfo->mBlendDepthConst, matInfo->mat->getBlendDepth()); } if (matInfo->mBlendContrastConst != NULL) { mConsts->setSafe(matInfo->mBlendContrastConst, matInfo->mat->getBlendContrast()); } detailIndex++; } mConsts->setSafe(mDetailInfoVArrayConst, detailScaleAndFadeArray); mConsts->setSafe(mDetailInfoPArrayConst, detailInfoArray); } bool TerrainCellMaterial::setupPass( const SceneRenderState *state, const SceneData &sceneData ) { PROFILE_SCOPE( TerrainCellMaterial_SetupPass ); if (mCurrPass > 0) { mCurrPass = 0; return false; } mCurrPass++; _updateMaterialConsts(); if ( mBaseTexMapConst->isValid() ) GFX->setTexture( mBaseTexMapConst->getSamplerRegister(), mTerrain->mBaseTex.getPointer() ); if ( mLayerTexConst->isValid() ) GFX->setTexture( mLayerTexConst->getSamplerRegister(), mTerrain->mLayerTex.getPointer() ); if ( mLightMapTexConst->isValid() ) GFX->setTexture( mLightMapTexConst->getSamplerRegister(), mTerrain->getLightMapTex() ); if ( sceneData.wireframe ) GFX->setStateBlock( mWireframeStateBlock ); else if ( state->isReflectPass( )) GFX->setStateBlock( mReflectionStateBlock ); else GFX->setStateBlock( mStateBlock ); GFX->setShader( mShader ); GFX->setShaderConstBuffer( mConsts ); // Let the light manager prepare any light stuff it needs. LIGHTMGR->setLightInfo( NULL, NULL, sceneData, state, 0, mConsts ); if (mDetailTexArrayConst->isValid() && mTerrain->getDetailTextureArray().isValid()) GFX->setTextureArray(mDetailTexArrayConst->getSamplerRegister(), mTerrain->getDetailTextureArray()); if (mMacroTexArrayConst->isValid() && mTerrain->getMacroTextureArray().isValid()) GFX->setTextureArray(mMacroTexArrayConst->getSamplerRegister(), mTerrain->getMacroTextureArray()); if (mNormalTexArrayConst->isValid() && mTerrain->getNormalTextureArray().isValid()) GFX->setTextureArray(mNormalTexArrayConst->getSamplerRegister(), mTerrain->getNormalTextureArray()); if (mOrmTexArrayConst->isValid() && mTerrain->getOrmTextureArray().isValid()) GFX->setTextureArray(mOrmTexArrayConst->getSamplerRegister(), mTerrain->getOrmTextureArray()); mConsts->setSafe( mLayerSizeConst, (F32)mTerrain->mLayerTex.getWidth() ); if ( mOneOverTerrainSizeConst->isValid() ) { F32 oneOverTerrainSize = 1.0f / mTerrain->getWorldBlockSize(); mConsts->set( mOneOverTerrainSizeConst, oneOverTerrainSize ); } mConsts->setSafe( mSquareSizeConst, mTerrain->getSquareSize() ); if ( mFogDataConst->isValid() ) { Point3F fogData; fogData.x = sceneData.fogDensity; fogData.y = sceneData.fogDensityOffset; fogData.z = sceneData.fogHeightFalloff; mConsts->set( mFogDataConst, fogData ); } if (String::isEmpty(Con::getVariable("$Terrain::BlendDepth"))) { mConsts->setSafe(mBlendDepthConst, 0.2f); } else { mConsts->setSafe(mBlendDepthConst, Con::getFloatVariable("$Terrain::BlendDepth")); } mConsts->setSafe( mFogColorConst, sceneData.fogColor ); if ( mLightInfoBufferConst->isValid() && mLightParamsConst->isValid() ) { if ( !mLightInfoTarget ) mLightInfoTarget = NamedTexTarget::find( "diffuseLighting" ); GFXTextureObject *texObject = mLightInfoTarget->getTexture(); // TODO: Sometimes during reset of the light manager we get a // NULL texture here. This is corrected on the next frame, but // we should still investigate why that happens. if ( texObject ) { GFX->setTexture( mLightInfoBufferConst->getSamplerRegister(), texObject ); const Point3I &targetSz = texObject->getSize(); const RectI &targetVp = mLightInfoTarget->getViewport(); Point4F rtParams; ScreenSpace::RenderTargetParameters(targetSz, targetVp, rtParams); mConsts->setSafe( mLightParamsConst, rtParams ); } } return true; } BaseMatInstance* TerrainCellMaterial::getShadowMat() { // Find our material which has some settings // defined on it in script. Material *mat = MATMGR->getMaterialDefinitionByName( "AL_DefaultShadowMaterial" ); // Create the material instance adding the feature which // handles rendering terrain cut outs. FeatureSet features = MATMGR->getDefaultFeatures(); BaseMatInstance *matInst = mat->createMatInstance(); if ( !matInst->init( features, getGFXVertexFormat<TerrVertex>() ) ) { delete matInst; matInst = NULL; } return matInst; }
34.183832
143
0.656149
GoldenThumbs
41ae40c170370c26e62d938e1c06d1106419f2ac
8,741
cpp
C++
Engine/Renderer/GLES3/src/GLES3Texture.cpp
LiangYue1981816/AresEngine
c1cf040a1dffaf2bc585ed75e70ddd9322fe3f67
[ "BSD-2-Clause" ]
3
2018-12-08T16:32:05.000Z
2020-06-02T11:07:15.000Z
Engine/Renderer/GLES3/src/GLES3Texture.cpp
LiangYue1981816/AresEngine
c1cf040a1dffaf2bc585ed75e70ddd9322fe3f67
[ "BSD-2-Clause" ]
null
null
null
Engine/Renderer/GLES3/src/GLES3Texture.cpp
LiangYue1981816/AresEngine
c1cf040a1dffaf2bc585ed75e70ddd9322fe3f67
[ "BSD-2-Clause" ]
1
2019-09-12T00:26:05.000Z
2019-09-12T00:26:05.000Z
#include "gli.hpp" #include "GLES3Renderer.h" CGLES3Texture::CGLES3Texture(void) : m_bExtern(false) , m_target(0) , m_texture(0) , m_type(GFX_TEXTURE_INVALID_ENUM) , m_format(GFX_PIXELFORMAT_UNDEFINED) , m_width(0) , m_height(0) , m_layers(0) , m_levels(0) , m_samples(0) { } CGLES3Texture::~CGLES3Texture(void) { Destroy(); } void CGLES3Texture::Release(void) { } uint32_t CGLES3Texture::GetTarget(void) const { ASSERT(m_target); return m_target; } uint32_t CGLES3Texture::GetTexture(void) const { ASSERT(m_texture); return m_texture; } GfxTextureType CGLES3Texture::GetType(void) const { return m_type; } GfxPixelFormat CGLES3Texture::GetFormat(void) const { return m_format; } int CGLES3Texture::GetWidth(void) const { return m_width; } int CGLES3Texture::GetHeight(void) const { return m_height; } int CGLES3Texture::GetLayers(void) const { return m_layers; } int CGLES3Texture::GetLevels(void) const { return m_levels; } int CGLES3Texture::GetSamples(void) const { return m_samples; } bool CGLES3Texture::Create(GfxTextureType type, GfxPixelFormat format, int width, int height, int layers, int levels, int samples, uint32_t texture) { ASSERT(texture); Destroy(); m_bExtern = true; m_target = CGLES3Helper::TranslateTextureTarget(type); m_texture = texture; m_type = type; m_format = format; m_width = width; m_height = height; m_layers = layers; m_levels = levels; m_samples = samples; return true; } bool CGLES3Texture::Create(GfxTextureType type, GfxPixelFormat format, int width, int height, int layers, int levels, int samples) { Destroy(); m_bExtern = false; m_target = CGLES3Helper::TranslateTextureTarget(type); m_texture = 0; m_type = type; m_format = format; m_width = width; m_height = height; m_layers = layers; m_levels = levels; gli::gl GL(gli::gl::PROFILE_ES30); gli::gl::format glFormat = GL.translate((gli::format)format); switch (m_target) { case GL_TEXTURE_2D_MULTISAMPLE: m_samples = samples; glGenTextures(1, &m_texture); glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, m_texture); glTexStorage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, samples, glFormat.Internal, width, height, GL_TRUE); glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, 0); CHECK_GL_ERROR_ASSERT(); return true; case GL_TEXTURE_2D: m_samples = 1; glGenTextures(1, &m_texture); glBindTexture(GL_TEXTURE_2D, m_texture); glTexStorage2D(GL_TEXTURE_2D, levels, glFormat.Internal, width, height); glBindTexture(GL_TEXTURE_2D, 0); CHECK_GL_ERROR_ASSERT(); return true; case GL_TEXTURE_2D_ARRAY: m_samples = 1; glGenTextures(1, &m_texture); glBindTexture(GL_TEXTURE_2D_ARRAY, m_texture); glTexStorage3D(GL_TEXTURE_2D_ARRAY, levels, glFormat.Internal, width, height, layers); glBindTexture(GL_TEXTURE_2D_ARRAY, 0); CHECK_GL_ERROR_ASSERT(); return true; case GL_TEXTURE_CUBE_MAP: m_samples = 1; glGenTextures(1, &m_texture); glBindTexture(GL_TEXTURE_CUBE_MAP, m_texture); glTexStorage2D(GL_TEXTURE_CUBE_MAP, levels, glFormat.Internal, width, height); glBindTexture(GL_TEXTURE_CUBE_MAP, 0); CHECK_GL_ERROR_ASSERT(); return true; default: Destroy(); return false; } } void CGLES3Texture::Destroy(void) { if (m_bExtern == false) { if (m_texture) { glDeleteTextures(1, &m_texture); } } m_bExtern = false; m_target = 0; m_texture = 0; m_format = GFX_PIXELFORMAT_UNDEFINED; m_width = 0; m_height = 0; m_layers = 0; m_levels = 0; m_samples = 0; } bool CGLES3Texture::Texture2DData(GfxPixelFormat format, int level, int xoffset, int yoffset, int width, int height, uint32_t size, const void* data) { ASSERT(size); ASSERT(data); ASSERT(m_texture); ASSERT(m_bExtern == false); ASSERT(m_target == GL_TEXTURE_2D); ASSERT(m_format == format); ASSERT(m_levels > level); ASSERT(m_samples == 1); ASSERT(xoffset >= 0 && width > 0 && xoffset + width <= m_width); ASSERT(yoffset >= 0 && height > 0 && yoffset + height <= m_height); gli::gl GL(gli::gl::PROFILE_ES30); gli::gl::format glFormat = GL.translate((gli::format)format); glBindTexture(m_target, m_texture); glTexSubImage2D(m_target, level, xoffset, yoffset, width, height, glFormat.External, GL_UNSIGNED_BYTE, data); glBindTexture(m_target, 0); CHECK_GL_ERROR_ASSERT(); return true; } bool CGLES3Texture::Texture2DDataCompressed(GfxPixelFormat format, int level, int xoffset, int yoffset, int width, int height, uint32_t size, const void* data) { ASSERT(size); ASSERT(data); ASSERT(m_texture); ASSERT(m_bExtern == false); ASSERT(m_target == GL_TEXTURE_2D); ASSERT(m_format == format); ASSERT(m_levels > level); ASSERT(m_samples == 1); ASSERT(xoffset >= 0 && width > 0 && xoffset + width <= m_width); ASSERT(yoffset >= 0 && height > 0 && yoffset + height <= m_height); gli::gl GL(gli::gl::PROFILE_ES30); gli::gl::format glFormat = GL.translate((gli::format)format); glBindTexture(m_target, m_texture); glCompressedTexSubImage2D(m_target, level, xoffset, yoffset, width, height, glFormat.Internal, size, data); glBindTexture(m_target, 0); CHECK_GL_ERROR_ASSERT(); return true; } bool CGLES3Texture::Texture2DArrayData(GfxPixelFormat format, int layer, int level, int xoffset, int yoffset, int width, int height, uint32_t size, const void* data) { ASSERT(size); ASSERT(data); ASSERT(m_texture); ASSERT(m_bExtern == false); ASSERT(m_target == GL_TEXTURE_2D_ARRAY); ASSERT(m_format == format); ASSERT(m_layers > layer); ASSERT(m_levels > level); ASSERT(m_samples == 1); ASSERT(xoffset >= 0 && width > 0 && xoffset + width <= m_width); ASSERT(yoffset >= 0 && height > 0 && yoffset + height <= m_height); gli::gl GL(gli::gl::PROFILE_ES30); gli::gl::format glFormat = GL.translate((gli::format)format); glBindTexture(m_target, m_texture); glTexSubImage3D(m_target, level, xoffset, yoffset, layer, width, height, 1, glFormat.External, GL_UNSIGNED_BYTE, data); glBindTexture(m_target, 0); CHECK_GL_ERROR_ASSERT(); return true; } bool CGLES3Texture::Texture2DArrayDataCompressed(GfxPixelFormat format, int layer, int level, int xoffset, int yoffset, int width, int height, uint32_t size, const void* data) { ASSERT(size); ASSERT(data); ASSERT(m_texture); ASSERT(m_bExtern == false); ASSERT(m_target == GL_TEXTURE_2D_ARRAY); ASSERT(m_format == format); ASSERT(m_layers > layer); ASSERT(m_levels > level); ASSERT(m_samples == 1); ASSERT(xoffset >= 0 && width > 0 && xoffset + width <= m_width); ASSERT(yoffset >= 0 && height > 0 && yoffset + height <= m_height); gli::gl GL(gli::gl::PROFILE_ES30); gli::gl::format glFormat = GL.translate((gli::format)format); glBindTexture(m_target, m_texture); glCompressedTexSubImage3D(m_target, level, xoffset, yoffset, layer, width, height, 1, glFormat.Internal, size, data); glBindTexture(m_target, 0); CHECK_GL_ERROR_ASSERT(); return true; } bool CGLES3Texture::TextureCubemapData(GfxPixelFormat format, GfxCubemapFace face, int level, int xoffset, int yoffset, int width, int height, uint32_t size, const void* data) { ASSERT(size); ASSERT(data); ASSERT(m_texture); ASSERT(m_bExtern == false); ASSERT(m_target == GL_TEXTURE_CUBE_MAP); ASSERT(m_format == format); ASSERT(m_levels > level); ASSERT(m_samples == 1); ASSERT(xoffset >= 0 && width > 0 && xoffset + width <= m_width); ASSERT(yoffset >= 0 && height > 0 && yoffset + height <= m_height); gli::gl GL(gli::gl::PROFILE_ES30); gli::gl::format glFormat = GL.translate((gli::format)format); glBindTexture(m_target, m_texture); glTexSubImage2D(CGLES3Helper::TranslateTextureTarget(face), level, xoffset, yoffset, width, height, glFormat.External, GL_UNSIGNED_BYTE, data); glBindTexture(m_target, 0); CHECK_GL_ERROR_ASSERT(); return true; } bool CGLES3Texture::TextureCubemapDataCompressed(GfxPixelFormat format, GfxCubemapFace face, int level, int xoffset, int yoffset, int width, int height, uint32_t size, const void* data) { ASSERT(size); ASSERT(data); ASSERT(m_texture); ASSERT(m_bExtern == false); ASSERT(m_target == GL_TEXTURE_CUBE_MAP); ASSERT(m_format == format); ASSERT(m_levels > level); ASSERT(m_samples == 1); ASSERT(xoffset >= 0 && width > 0 && xoffset + width <= m_width); ASSERT(yoffset >= 0 && height > 0 && yoffset + height <= m_height); gli::gl GL(gli::gl::PROFILE_ES30); gli::gl::format glFormat = GL.translate((gli::format)format); glBindTexture(m_target, m_texture); glCompressedTexSubImage2D(CGLES3Helper::TranslateTextureTarget(face), level, xoffset, yoffset, width, height, glFormat.Internal, size, data); glBindTexture(m_target, 0); CHECK_GL_ERROR_ASSERT(); return true; } void CGLES3Texture::Bind(uint32_t unit) const { ASSERT(m_target); ASSERT(m_texture); GLBindTexture(unit, m_target, m_texture); CHECK_GL_ERROR_ASSERT(); }
25.860947
185
0.732982
LiangYue1981816
41b38b15073c8ebac57b2ccf6279376ac4f692fb
1,552
cpp
C++
codeforces/D - Edge Deletion/Wrong answer on test 3 (4).cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/D - Edge Deletion/Wrong answer on test 3 (4).cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/D - Edge Deletion/Wrong answer on test 3 (4).cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: Nov/12/2018 23:55 * solution_verdict: Wrong answer on test 3 language: GNU C++14 * run_time: 15 ms memory_used: 4900 KB * problem: https://codeforces.com/contest/1076/problem/D ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; const int N=3e5; int vis[N+2]; vector<pair<int,int> >adj[N+2]; map<pair<int,int>,int>mp; int main() { ios_base::sync_with_stdio(0);cin.tie(0); int n,m,k;cin>>n>>m>>k; for(int i=1;i<=m;i++) { int u,v,w;cin>>u>>v>>w; adj[u].push_back({v,w}); adj[v].push_back({u,w}); if(u>v)swap(u,v);mp[{u,v}]=i; } priority_queue<pair<long,pair<int,int> > >pq; for(auto x:adj[1])pq.push({-x.second,{1,x.first}}); set<int>ans;vis[1]=1; while(pq.size()) { pair<long,pair<int,int> >p=pq.top();pq.pop(); int u=p.second.first,v=p.second.second; if(u>v)swap(u,v);long cs=-p.first; if(ans.size()<k)ans.insert(mp[{u,v}]); vis[p.second.second]=1; for(auto x:adj[p.second.second]) { if(vis[x.first])continue; pq.push({-(cs+x.second),{p.second.second,x.first}}); } } cout<<ans.size()<<endl; for(auto x:ans) cout<<x<<" "; cout<<endl; return 0; }
33.73913
111
0.462629
kzvd4729
41b7331464dee98a8aca55284d76d6ee922b2c5b
572
cpp
C++
PlatformIO ESP32 code/OSSM_ESP32/lib/ArduinoJson-6.x/extras/tests/MsgPackDeserializer/misc.cpp
ortlof/OSSM-hardware
1cf21ce854cbe212c752726689d3c12508a3b1ee
[ "MIT" ]
5,800
2015-01-05T02:36:02.000Z
2022-03-31T04:27:26.000Z
PlatformIO ESP32 code/OSSM_ESP32/lib/ArduinoJson-6.x/extras/tests/MsgPackDeserializer/misc.cpp
ortlof/OSSM-hardware
1cf21ce854cbe212c752726689d3c12508a3b1ee
[ "MIT" ]
1,681
2015-01-04T00:41:40.000Z
2022-03-31T07:30:51.000Z
PlatformIO ESP32 code/OSSM_ESP32/lib/ArduinoJson-6.x/extras/tests/MsgPackDeserializer/misc.cpp
ortlof/OSSM-hardware
1cf21ce854cbe212c752726689d3c12508a3b1ee
[ "MIT" ]
1,169
2015-01-04T01:32:23.000Z
2022-03-28T13:38:00.000Z
// ArduinoJson - https://arduinojson.org // Copyright Benoit Blanchon 2014-2021 // MIT License #include <ArduinoJson.h> #include <catch.hpp> TEST_CASE("deserializeMsgPack() returns EmptyInput") { StaticJsonDocument<100> doc; SECTION("from sized buffer") { DeserializationError err = deserializeMsgPack(doc, "", 0); REQUIRE(err == DeserializationError::EmptyInput); } SECTION("from stream") { std::istringstream input(""); DeserializationError err = deserializeMsgPack(doc, input); REQUIRE(err == DeserializationError::EmptyInput); } }
22.88
62
0.711538
ortlof
41b7b2455b8f69a298e6f6c4cc3c92868d093881
748
cpp
C++
src/analyzers/tokenizers/character_tokenizer.cpp
saq7/MeTA
0392964c1cdc073ae5123f7d64affdc4105acc4f
[ "MIT" ]
null
null
null
src/analyzers/tokenizers/character_tokenizer.cpp
saq7/MeTA
0392964c1cdc073ae5123f7d64affdc4105acc4f
[ "MIT" ]
null
null
null
src/analyzers/tokenizers/character_tokenizer.cpp
saq7/MeTA
0392964c1cdc073ae5123f7d64affdc4105acc4f
[ "MIT" ]
1
2021-09-06T06:08:38.000Z
2021-09-06T06:08:38.000Z
/** * @file character_tokenizer.cpp * @author Chase Geigle */ #include "analyzers/tokenizers/character_tokenizer.h" #include "corpus/document.h" #include "io/mmap_file.h" namespace meta { namespace analyzers { namespace tokenizers { const std::string character_tokenizer::id = "character-tokenizer"; character_tokenizer::character_tokenizer() : idx_{0} { // nothing } void character_tokenizer::set_content(const std::string& content) { idx_ = 0; content_ = content; } std::string character_tokenizer::next() { if (!*this) throw token_stream_exception{"next() called with no tokens left"}; return {1, content_[idx_++]}; } character_tokenizer::operator bool() const { return idx_ < content_.size(); } } } }
16.622222
74
0.703209
saq7
41b94436518ed9a574d67416bcd1bf2dd2024d28
3,065
cpp
C++
src/core/exportexpressionmatrix.cpp
mfayk/KINC
0f6565ce8e1102392382e4c716c128115b611f0c
[ "MIT" ]
10
2018-08-15T13:27:35.000Z
2020-12-10T17:20:40.000Z
src/core/exportexpressionmatrix.cpp
mfayk/KINC
0f6565ce8e1102392382e4c716c128115b611f0c
[ "MIT" ]
182
2016-07-31T07:15:15.000Z
2022-01-30T01:25:41.000Z
src/core/exportexpressionmatrix.cpp
mfayk/KINC
0f6565ce8e1102392382e4c716c128115b611f0c
[ "MIT" ]
7
2017-10-12T22:03:42.000Z
2020-02-26T00:01:18.000Z
#include "exportexpressionmatrix.h" #include "exportexpressionmatrix_input.h" #include "datafactory.h" #include "expressionmatrix_gene.h" /*! * Return the total number of blocks this analytic must process as steps * or blocks of work. This implementation uses a work block for writing the * sample names and a work block for writing each gene. */ int ExportExpressionMatrix::size() const { EDEBUG_FUNC(this); return 1 + _input->geneSize(); } /*! * Process the given index with a possible block of results if this analytic * produces work blocks. This implementation uses only the index of the result * block to determine which piece of work to do. * * @param result */ void ExportExpressionMatrix::process(const EAbstractAnalyticBlock* result) { EDEBUG_FUNC(this,result); // write the sample names in the first step if ( result->index() == 0 ) { // get sample names EMetaArray sampleNames {_input->sampleNames()}; // initialize output file stream _stream.setDevice(_output); _stream.setRealNumberPrecision(_precision); // write sample names for ( int i = 0; i < _input->sampleSize(); i++ ) { _stream << sampleNames.at(i).toString() << "\t"; } _stream << "\n"; } // write each gene to the output file in a separate step else { // get gene index int i = result->index() - 1; // get gene name QString geneName {_input->geneNames().at(i).toString()}; // load gene from expression matrix ExpressionMatrix::Gene gene(_input); gene.read(i); // write gene name _stream << geneName; // write expression values for ( int j = 0; j < _input->sampleSize(); j++ ) { float value {gene.at(j)}; // if value is NAN use the no sample token if ( std::isnan(value) ) { _stream << "\t" << _nanToken; } // else this is a normal floating point expression else { _stream << "\t" << value; } } _stream << "\n"; } // make sure writing output file worked if ( _stream.status() != QTextStream::Ok ) { E_MAKE_EXCEPTION(e); e.setTitle(tr("File IO Error")); e.setDetails(tr("Qt Text Stream encountered an unknown error.")); throw e; } } /*! * Make a new input object and return its pointer. */ EAbstractAnalyticInput* ExportExpressionMatrix::makeInput() { EDEBUG_FUNC(this); return new Input(this); } /*! * Initialize this analytic. This implementation checks to make sure the input * data object and output file have been set. */ void ExportExpressionMatrix::initialize() { EDEBUG_FUNC(this); if ( !_input || !_output ) { E_MAKE_EXCEPTION(e); e.setTitle(tr("Invalid Argument")); e.setDetails(tr("Did not get valid input and/or output arguments.")); throw e; } }
23.945313
78
0.595432
mfayk
41bc85742770c7a82c455bfea9e740c54fd94de4
589
cc
C++
src/EntityLoader.cc
BitwiseSoftware/mikan
8454af0b611fd8366c8dbea8297882f93d2e993e
[ "MIT" ]
null
null
null
src/EntityLoader.cc
BitwiseSoftware/mikan
8454af0b611fd8366c8dbea8297882f93d2e993e
[ "MIT" ]
null
null
null
src/EntityLoader.cc
BitwiseSoftware/mikan
8454af0b611fd8366c8dbea8297882f93d2e993e
[ "MIT" ]
null
null
null
#include "EntityLoader.hh" #include <fstream> #include <iostream> namespace Mikan { EntityLoader::EntityLoader() { } void EntityLoader::load_json(const std::string file_location) { Json::Reader reader; std::ifstream provinces_file; provinces_file.open(file_location); const bool parsingSuccessful = reader.parse(provinces_file, root); if (!parsingSuccessful) { // Should instead print to a log file std::cout << "Failed to parse configuration" << std::endl << reader.getFormattedErrorMessages(); return; } } } // namespace Mikan
20.310345
68
0.687606
BitwiseSoftware
41bcc5037bdd32edfd6134464253036715ed087f
5,834
cpp
C++
test/testXml.cpp
jack-lz/anyrpc
89533a39ecbbc05cfd89788c4aaa034ddae92010
[ "MIT" ]
null
null
null
test/testXml.cpp
jack-lz/anyrpc
89533a39ecbbc05cfd89788c4aaa034ddae92010
[ "MIT" ]
null
null
null
test/testXml.cpp
jack-lz/anyrpc
89533a39ecbbc05cfd89788c4aaa034ddae92010
[ "MIT" ]
null
null
null
// Copyright (C) 2015 SRG Technology, LLC // // 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 "anyrpc/anyrpc.h" #include <gtest/gtest.h> #include <fstream> using namespace std; using namespace anyrpc; static string ReadWriteData(char* inString) { ReadStringStream is(inString); XmlReader reader(is); Document doc; reader >> doc; WriteStringStream os; XmlWriter writer(os); writer << doc.GetValue(); return os.GetString(); } static void WriteReadValue(Value& value, Value& outValue) { WriteStringStream os; XmlWriter writer(os); writer << value; //cout << "Xml: " << os.GetBuffer() << endl; ReadStringStream is(os.GetBuffer()); XmlReader reader(is); Document doc; reader >> doc; outValue.Assign(doc.GetValue()); } static int CheckParseError(const char* inString) { ReadStringStream is(inString); XmlReader reader(is); Document doc; reader >> doc; return reader.GetParseErrorCode(); } TEST(Xml,Number) { char inString[] = "<value><i4>5736298</i4></value>"; string outString = ReadWriteData(inString); EXPECT_STREQ( outString.c_str(), inString); } TEST(Xml,Double) { Value value, outValue; value.SetDouble(0); WriteReadValue(value, outValue); EXPECT_DOUBLE_EQ(value.GetDouble(), outValue.GetDouble()); value.SetDouble(5); WriteReadValue(value, outValue); EXPECT_DOUBLE_EQ(value.GetDouble(), outValue.GetDouble()); value.SetDouble(2.2348282); WriteReadValue(value, outValue); EXPECT_DOUBLE_EQ(value.GetDouble(), outValue.GetDouble()); value.SetDouble(-728329); WriteReadValue(value, outValue); EXPECT_DOUBLE_EQ(value.GetDouble(), outValue.GetDouble()); value.SetDouble(5.12393e-5); WriteReadValue(value, outValue); EXPECT_DOUBLE_EQ(value.GetDouble(), outValue.GetDouble()); value.SetDouble(-7.192939e-300); WriteReadValue(value, outValue); EXPECT_DOUBLE_EQ(value.GetDouble(), outValue.GetDouble()); value.SetDouble(8e-315); WriteReadValue(value, outValue); EXPECT_DOUBLE_EQ(value.GetDouble(), outValue.GetDouble()); value.SetDouble(-9.12e50); WriteReadValue(value, outValue); EXPECT_DOUBLE_EQ(value.GetDouble(), outValue.GetDouble()); value.SetDouble(1.642e300); WriteReadValue(value, outValue); EXPECT_DOUBLE_EQ(value.GetDouble(), outValue.GetDouble()); value.SetDouble(-9.999e307); WriteReadValue(value, outValue); EXPECT_DOUBLE_EQ(value.GetDouble(), outValue.GetDouble()); } TEST(Xml,String) { char inString[] = "<value>Test string data</value>"; string outString = ReadWriteData(inString); EXPECT_STREQ( outString.c_str(), inString); char inString2[] = "<value><string>Test string data</string></value>"; string outString2 = ReadWriteData(inString2); EXPECT_STREQ( outString2.c_str(), inString); } TEST(Xml,Array) { char inString[] = "<value><array><data>" "<value><i4>1</i4></value>" "<value><i4>2</i4></value>" "<value><i4>3</i4></value>" "<value><i4>4</i4></value>" "</data></array></value>"; string outString = ReadWriteData(inString); EXPECT_STREQ( outString.c_str(), inString); } TEST(Xml,Map) { char inString[] = "<value><struct>" "<member><name>item1</name><value><i4>57</i4></value></member>" "<member><name>item2</name><value><i4>89</i4></value></member>" "<member><name>item3</name><value><i4>45</i4></value></member>" "</struct></value>"; string outString = ReadWriteData(inString); EXPECT_STREQ( outString.c_str(), inString); } TEST(Xml,DateTime) { Value value; time_t dt = time(NULL); value.SetDateTime(dt); Value outValue; WriteReadValue(value, outValue); EXPECT_TRUE(outValue.IsDateTime()); EXPECT_EQ(outValue.GetDateTime(), value.GetDateTime()); } TEST(Xml,Binary) { Value value; char* binData = (char*)"\x0a\x0b\x0c\x0d\xff\x00\xee\xdd\x00"; value.SetBinary( (unsigned char*)binData, 8); Value outValue; WriteReadValue(value, outValue); EXPECT_TRUE(outValue.IsBinary()); EXPECT_EQ( strncmp((char*)outValue.GetBinary(), (char*)value.GetBinary(), 8), 0); } TEST(Xml,ParseError1) { char inString[] = "<value>Test string data</string></value>"; EXPECT_EQ(CheckParseError(inString), AnyRpcErrorTagInvalid); } TEST(Xml,ParseError2) { char inString[] = "<value><i4>5736298</value>"; EXPECT_EQ(CheckParseError(inString), AnyRpcErrorTagInvalid); } TEST(Xml,ParseError3) { char inString[] = "<value><i4>5736298<i4></value>"; EXPECT_EQ(CheckParseError(inString), AnyRpcErrorTagInvalid); }
29.917949
87
0.67158
jack-lz
41bd8ec8afffd80df54210ab5431541e91303c65
2,777
cpp
C++
modules/cudf/src/column/strings/multibyte_split.cpp
exactlyallan/node
591f06a9c56c3d94206432677a0efd34fe6cb076
[ "Apache-2.0" ]
null
null
null
modules/cudf/src/column/strings/multibyte_split.cpp
exactlyallan/node
591f06a9c56c3d94206432677a0efd34fe6cb076
[ "Apache-2.0" ]
null
null
null
modules/cudf/src/column/strings/multibyte_split.cpp
exactlyallan/node
591f06a9c56c3d94206432677a0efd34fe6cb076
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2022, NVIDIA CORPORATION. // // 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 <node_cudf/column.hpp> #include <node_cudf/table.hpp> #include <node_cudf/utilities/metadata.hpp> #include <cudf/io/text/data_chunk_source_factories.hpp> #include <cudf/io/text/multibyte_split.hpp> namespace nv { namespace { Column::wrapper_t split_string_column(Napi::CallbackInfo const& info, cudf::mutable_column_view const& col, std::string const& delimiter) { auto env = info.Env(); /* TODO: This only splits a string column. How to generalize */ // Check type auto span = cudf::device_span<char const>(col.child(1).data<char const>(), col.child(1).size()); auto datasource = cudf::io::text::device_span_data_chunk_source(span); return Column::New(env, cudf::io::text::multibyte_split(datasource, delimiter)); } Column::wrapper_t read_text_files(Napi::CallbackInfo const& info, std::string const& filename, std::string const& delimiter) { auto datasource = cudf::io::text::make_source_from_file(filename); auto text_data = cudf::io::text::multibyte_split(*datasource, delimiter); auto env = info.Env(); return Column::New(env, std::move(text_data)); } } // namespace Napi::Value Column::split(Napi::CallbackInfo const& info) { CallbackArgs args{info}; if (args.Length() != 1) { NAPI_THROW(Napi::Error::New(info.Env(), "split expects a delimiter")); } auto delimiter = args[0]; auto col = this->mutable_view(); try { return split_string_column(info, col, delimiter); } catch (cudf::logic_error const& err) { NAPI_THROW(Napi::Error::New(info.Env(), err.what())); } } Napi::Value Column::read_text(Napi::CallbackInfo const& info) { CallbackArgs args{info}; if (args.Length() != 2) { NAPI_THROW( Napi::Error::New(info.Env(), "read_text expects a filename and an optional delimiter")); } std::string source = args[0]; std::string delimiter = args[1]; try { return read_text_files(info, source, delimiter); } catch (cudf::logic_error const& err) { NAPI_THROW(Napi::Error::New(info.Env(), err.what())); } } } // namespace nv
35.151899
100
0.671948
exactlyallan
41bf7956aac858c6db61d104b3fcb4d553c1fb29
1,139
hh
C++
DataProducts/inc/ExtMonFNALModuleDenseId.hh
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
1
2021-06-25T00:00:12.000Z
2021-06-25T00:00:12.000Z
DataProducts/inc/ExtMonFNALModuleDenseId.hh
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
1
2019-11-22T14:45:51.000Z
2019-11-22T14:50:03.000Z
DataProducts/inc/ExtMonFNALModuleDenseId.hh
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
2
2019-10-14T17:46:58.000Z
2020-03-30T21:05:15.000Z
#ifndef DataProducts_ExtMonFNALModuleDenseId_hh #define DataProducts_ExtMonFNALModuleDenseId_hh // Sequential number of a silicon module in Mu2e ExtMonFNAL detector. // Zero based. // // $Id: ExtMonFNALModuleDenseId.hh,v 1.1 2013/07/30 18:45:00 wieschie Exp $ // $Author: wieschie $ // $Date: 2013/07/30 18:45:00 $ // // Original author Andrei Gaponenko #include <ostream> namespace mu2e { class ExtMonFNALModuleDenseId { public: static const unsigned int NOMODULE = -1u; explicit ExtMonFNALModuleDenseId(unsigned int did = NOMODULE) : did_(did) {} bool operator==( ExtMonFNALModuleDenseId const& rhs) const{ return did_ == rhs.did_; } bool operator!=( ExtMonFNALModuleDenseId const& rhs) const{ return !(*this == rhs); } bool operator<( ExtMonFNALModuleDenseId const& rhs) const{ return did_ < rhs.did_; } unsigned int number() const { return did_; } private: unsigned int did_; }; inline std::ostream& operator<<( std::ostream& os, const ExtMonFNALModuleDenseId& id) { return os<<id.number(); } } #endif /* DataProducts_ExtMonFNALModuleDenseId_hh */
23.729167
89
0.697981
bonventre
41c0336090f3f0d8a0ca993471720ec50fbf335d
3,422
cpp
C++
tests/pcg.cpp
bezout/LMA
9555e41eed5f44690c5f6e3ea2d22d520ff1a9d2
[ "BSL-1.0" ]
29
2015-12-08T12:07:30.000Z
2022-01-08T21:23:01.000Z
tests/pcg.cpp
ayumizll/LMA
e945452e12a8b05bd17400b46a20a5322aeda01d
[ "BSL-1.0" ]
3
2016-07-11T16:23:48.000Z
2017-04-05T13:33:00.000Z
tests/pcg.cpp
bezout/LMA
9555e41eed5f44690c5f6e3ea2d22d520ff1a9d2
[ "BSL-1.0" ]
8
2015-12-21T01:52:27.000Z
2017-12-26T02:26:55.000Z
#include <iostream> #include <Eigen/IterativeLinearSolvers> #include <libv/lma/lm/solver/solver.hpp> #include <libv/lma/lm/solver/verbose.hpp> using namespace Eigen; void eigen_pcg(const Eigen::MatrixXd& m, const Eigen::VectorXd& jte) { std::cout << "\n\n EIGEN PCG " << std::endl; size_t n = jte.size(); VectorXd x(n), b(jte); // typedef SparseMatrix<double> Mat; typedef Eigen::MatrixXd Mat; // Mat A(n,n); Mat A = m; // for(size_t i = 0 ; i < m.cols() ; ++i) // for(size_t j = 0 ; j < m.rows() ; ++j) // A.coeff(j,i) = m(j,i); // for(size_t i = 0 ; i < n ; ++i) // A.coeffRef(i,i) = 1.0; // A.setIdentity(); std::cout << A << std::endl; x.setZero(); std::cout <<"\n X = " << x.transpose() << std::endl; std::cout <<"\n B = " << b.transpose() << std::endl; // fill A and b ConjugateGradient<Mat> cg; cg.compute(A); x = cg.solve(b); std::cout << "#iterations: " << cg.iterations() << std::endl; std::cout << "estimated error: " << cg.error() << std::endl; // update b, and solve again // x = cg.solve(b); std::cout << "\n X = " << x.transpose() << std::endl; } // typedef Eigen::Matrix<double,2,1> Type0; // typedef Eigen::Matrix<double,3,1> Type1; // typedef Eigen::Matrix<double,1,1> Type2; // // struct F // { // bool operator()(const Type0& , const Type1& , const Type2&, Eigen::Matrix<double,2,1>&) const // { // return true; // } // }; int main() { /* Type0 t0; Type1 t1; Type2 t2; std::cout << " Test pcg " << std::endl; lma::Solver<F> solver(1,1); // solver.algo.norm_eq.seuil=0.9999; // solver.algo.norm_eq.max_iteration=100000typedef typename SelectAlgo<Container,Container::NbClass,AlgoTag>::type Algorithm; // Algorithm algo(config);; auto i0 = ttt::Indice<Type0*>(0); auto i1 = ttt::Indice<Type1*>(0); auto i2 = ttt::Indice<Type2*>(0); solver.add(F(),&t0,&t1,&t2);//lma::bf::make_vector(i0,i1,i2),F()); // solver.solve(lma::enable_verbose_output()); // solver.algo.compute_b(solver.algo.ba_); // solver.algo.compute_delta_a(solver.algo.ba_); using namespace lma; typedef typename SelectAlgo<lma::Solver<F>::Container,lma::Solver<F>::Container::NbClass,ImplicitSchurTag<1>>::type Algorithm; Algorithm algo(ImplicitSchurTag<1>(0.9999,100000)); algo.init(solver.bundle); lma::bf::at_key<lma::bf::pair<Type0*,Type0*>>(algo.ba_.h())(i0,0) << 1,0, 0,2; lma::bf::at_key<lma::bf::pair<Type2*,Type2*>>(algo.ba_.h())(i2,0) << 1; lma::bf::at_key<lma::bf::pair<Type0*,Type1*>>(algo.ba_.h())(i0,0) << 3.2,0.5,2, 0,-2.5,-1.5; lma::bf::at_key<lma::bf::pair<Type1*,Type1*>>(algo.ba_.h())(i1,0) << 3,0,0, 0,4,0, 0,0,5; lma::bf::at_key<Type0*>(algo.ba_.jte())(i0) << 1,2; lma::bf::at_key<Type1*>(algo.ba_.jte())(i1) << 3,4,5; lma::bf::at_key<Type2*>(algo.ba_.jte())(i2) << 1; std::cout << std::endl; std::cout << " A = \n" << lma::to_mat(algo.ba_.h()) << std::endl; // std::cout << " B = " << lma::to_vect(solver.algo.schur_.bs_).transpose() << std::endl; std::cout << " B = " << lma::to_vect(algo.ba_.jte()).transpose() << std::endl; algo.compute_y(algo.ba_); algo.compute_b(algo.ba_); algo.compute_delta_a(algo.ba_); std::cout << " X = " << lma::to_vect(algo.ba_.delta()).transpose() << std::endl; eigen_pcg(lma::to_mat(algo.ba_.h()),lma::to_vect(algo.ba_.jte()));*/ }
30.017544
128
0.582992
bezout
41c43815f08dfcce1dfc8a7c5283af6b5d86868c
1,192
cpp
C++
linked_list/assignments/bubble_sort.cpp
ramchandra94/datastructures_in_cpp
28274ff4f0d9736cfe690ef002b90b9ebbfaf2f7
[ "MIT" ]
null
null
null
linked_list/assignments/bubble_sort.cpp
ramchandra94/datastructures_in_cpp
28274ff4f0d9736cfe690ef002b90b9ebbfaf2f7
[ "MIT" ]
null
null
null
linked_list/assignments/bubble_sort.cpp
ramchandra94/datastructures_in_cpp
28274ff4f0d9736cfe690ef002b90b9ebbfaf2f7
[ "MIT" ]
null
null
null
/**************************************************************** Following is the class structure of the Node class: class Node { public: int data; Node *next; Node(int data) { this->data = data; this->next = NULL; } }; *****************************************************************/ void my_swap (Node *node_1, Node *node_2) { int temp = node_1->data; node_1->data = node_2 -> data; node_2 -> data = temp; } Node *bubbleSort(Node *head) { // Write your code here if(head == NULL){ return head; } int swapped; Node *lPtr; // left pointer will always point to the start of the list Node *rPrt = NULL; // right pointer will always point to the end of the list do { swapped = 0; lPtr = head; while(lPtr->next != rPrt) { if (lPtr->data > lPtr->next->data) { my_swap(lPtr, lPtr->next); swapped = 1; } lPtr = lPtr->next; } //as the largest element is at the end of the list, assign that to rPtr as there is no need to //check already sorted list rPrt = lPtr; }while(swapped); return head; }
20.912281
96
0.491611
ramchandra94
41c54e5b780ca813a5f0fb714cb50f1201459da1
2,048
cpp
C++
src/day01.cpp
foolnotion/aoc2020
49738011e8181af438c13556a294b939880916c9
[ "Unlicense" ]
null
null
null
src/day01.cpp
foolnotion/aoc2020
49738011e8181af438c13556a294b939880916c9
[ "Unlicense" ]
null
null
null
src/day01.cpp
foolnotion/aoc2020
49738011e8181af438c13556a294b939880916c9
[ "Unlicense" ]
2
2020-12-12T21:42:53.000Z
2020-12-16T20:56:56.000Z
#define ANKERL_NANOBENCH_IMPLEMENT #include "advent.hpp" #include "util.hpp" #include <functional> #include "nanobench.h" auto find_terms(std::vector<int> const& values, int n, int64_t sum, int64_t product = 1) -> std::optional<int64_t> { if (sum <= 0) { return std::nullopt; } if (n == 2) { for (auto x : values) { auto y = sum - x; if (std::binary_search(values.begin(), values.end(), y)) { return std::make_optional(x * y * product); } } } else if (n > 2) { for (auto x : values) { if (x > sum) continue; if (auto res = find_terms(values, n - 1, sum - x, x * product); res.has_value()) { return res; } } } return std::nullopt; } int day01(int argc, char** argv) { if (argc < 3) { fmt::print("Provide an input file, a target sum and a number of terms.\n"); return 1; } int s; int n; if (auto res = parse_number<int>(argv[2]); res.has_value()) { s = res.value(); } else { throw std::runtime_error("Unable to parse target sum argument."); } if (auto res = parse_number<int>(argv[3]); res.has_value()) { n = res.value(); } else { throw std::runtime_error("Unable to parse number of terms argument."); } std::vector<int> values; std::ifstream infile(argv[1]); std::string line; while (std::getline(infile, line)) { if (auto v = parse_number<int>(line); v.has_value()) { values.push_back(v.value()); } } std::sort(values.begin(), values.end()); auto res = find_terms(values, n, s); if (res.has_value()) { fmt::print("{}-term product = {}\n", n, res.value()); } else { fmt::print("unable to find {}-term combination summing up to {}\n", n, s); } fmt::print("performance benchmark:\n"); ankerl::nanobench::Bench b; b.run("day01", [&]() { find_terms(values, n, s); }); return 0; }
24.674699
114
0.532715
foolnotion
41cabad12060e31d5ed6f09edb760b87ef3c172e
4,748
cpp
C++
samples/sonar_SRF10_test/test.cpp
mjlsuccess/mrpt
916c41579f91573e6c309dc67956ca808bf80fe7
[ "BSD-3-Clause" ]
null
null
null
samples/sonar_SRF10_test/test.cpp
mjlsuccess/mrpt
916c41579f91573e6c309dc67956ca808bf80fe7
[ "BSD-3-Clause" ]
null
null
null
samples/sonar_SRF10_test/test.cpp
mjlsuccess/mrpt
916c41579f91573e6c309dc67956ca808bf80fe7
[ "BSD-3-Clause" ]
1
2018-07-17T11:50:42.000Z
2018-07-17T11:50:42.000Z
/* +------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2018, Individual contributors, see AUTHORS file | | See: http://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See details in http://www.mrpt.org/License | +------------------------------------------------------------------------+ */ #include <mrpt/hwdrivers/CBoardSonars.h> #include <mrpt/system/CTicTac.h> #include <mrpt/config/CConfigFile.h> #include <mrpt/system/os.h> #include <mrpt/system/filesystem.h> #include <mrpt/gui/CDisplayWindow3D.h> #include <mrpt/opengl/CCylinder.h> #include <mrpt/opengl/COpenGLScene.h> #include <mrpt/opengl/CGridPlaneXY.h> #include <mrpt/opengl/stock_objects.h> using namespace mrpt; using namespace mrpt::hwdrivers; using namespace mrpt::obs; using namespace mrpt::gui; using namespace mrpt::opengl; using namespace mrpt::system; using namespace mrpt::poses; using namespace std; int main() { try { CBoardSonars sonarBoard; CObservationRange obs; std::string firmVers; CTicTac tictac; CDisplayWindow3D wind("Sonar representation"); COpenGLScene::Ptr& scene = wind.get3DSceneAndLock(); scene->insert( mrpt::make_aligned_shared<mrpt::opengl::CGridPlaneXY>( -20, 20, -20, 20, 0, 1)); scene->insert(mrpt::opengl::stock_objects::RobotPioneer()); // scene->insert( mrpt::make_aligned_shared<mrpt::opengl::CCylinder>(1, // 1, 2.0f) // ); wind.unlockAccess3DScene(); // Load configuration: ASSERT_(mrpt::system::fileExists("CONFIG_sonars.ini")); CConfigFile conf("CONFIG_sonars.ini"); sonarBoard.loadConfig(conf, "BOARD_SONAR_CONFIG"); while (!mrpt::system::os::kbhit()) { if (!sonarBoard.queryFirmwareVersion(firmVers)) { cout << "Cannot connect to USB device... Retrying in 1 sec" << endl; std::this_thread::sleep_for(1000ms); } else { cout << "FIRMWARE VERSION: " << firmVers << endl; break; } } cout << "Select operation:" << endl; cout << " 1. Get measures from device" << endl; cout << " 2. Program a new I2C address to a single sonar" << endl; cout << "?"; char c = os::getch(); if (c == '1') { while (!mrpt::system::os::kbhit()) { tictac.Tic(); if (sonarBoard.getObservation(obs)) { double T = tictac.Tac(); mrpt::system::clearConsole(); printf( "RX: %u ranges in %.03fms\n", (unsigned int)obs.sensedData.size(), T * 1000); scene = wind.get3DSceneAndLock(); for (size_t i = 0; i < obs.sensedData.size(); i++) { printf( "[ID:%i]=%15f 0x%04X\n", obs.sensedData[i].sensorID, obs.sensedData[i].sensedDistance, (int)(100 * obs.sensedData[i].sensedDistance)); // Show the distances std::string obj = format("sonar%i", obs.sensedData[i].sensorID); mrpt::opengl::CCylinder::Ptr sonarRange; mrpt::opengl::CRenderizable::Ptr objPtr = scene->getByName(obj); if (!objPtr) { sonarRange = mrpt::make_aligned_shared< mrpt::opengl::CCylinder>( 0.0f, 0.0f, 1.0f, 30, 10); sonarRange->setName(obj); scene->insert(sonarRange); } else sonarRange = std::dynamic_pointer_cast<CCylinder>(objPtr); sonarRange->setRadii( 0, tan(obs.sensorConeApperture) * obs.sensedData[i].sensedDistance); sonarRange->setPose( mrpt::poses::CPose3D(obs.sensedData[i].sensorPose) + CPose3D(0, 0, 0, 0, DEG2RAD(90.0), 0)); sonarRange->setHeight(obs.sensedData[i].sensedDistance); sonarRange->enableShowName(); sonarRange->setColor(0, 0, 1, 0.25); } wind.unlockAccess3DScene(); wind.repaint(); } else { cerr << "Error rx..." << endl; // return -1; } std::this_thread::sleep_for(200ms); } } else if (c == '2') { int curAddr, newAddr; cout << "Enter current address: (decimal, 0 to 15)" << endl; if (1 == scanf("%i", &curAddr)) { cout << "Enter new address: (decimal, 0 to 15)" << endl; if (1 == scanf("%i", &newAddr)) { ASSERT_(curAddr >= 0 && curAddr < 16); ASSERT_(newAddr >= 0 && newAddr < 16); printf("Changing address %i --> %i... ", curAddr, newAddr); if (sonarBoard.programI2CAddress(curAddr, newAddr)) printf(" DONE!\n"); else printf(" ERROR!\n"); } } } } catch (std::exception& e) { cerr << e.what() << endl; return -1; } return 0; }
28.261905
80
0.573926
mjlsuccess
41cd804d89e084684a7ce3bf8ca61961b62a2c80
170,444
cpp
C++
src/worklist-ai/worklistai.cpp
ChunghaSung/intAbs
b80d842993013ca40d4900498171192bd94b2602
[ "MIT" ]
7
2018-01-18T05:04:10.000Z
2021-02-07T02:46:48.000Z
src/worklist-ai/worklistai.cpp
sch8906/intAbs
b80d842993013ca40d4900498171192bd94b2602
[ "MIT" ]
1
2021-12-15T07:45:03.000Z
2021-12-30T04:54:49.000Z
src/worklist-ai/worklistai.cpp
sch8906/intAbs
b80d842993013ca40d4900498171192bd94b2602
[ "MIT" ]
4
2019-11-21T19:36:12.000Z
2022-03-30T14:07:29.000Z
/** * Author: Chungha Sung * This is modified version of Markus' source code of his FSE 2017 submission. * * Original Author: Markus Kusano * * LLVM pass to perform abstract interpretation (using apron) */ #include "llvm/Pass.h" #include "latticefact.h" #include "varvisit.h" #include "bbops.h" #include "utils.h" #include "cartesianprod.h" #include "llvm/Support/raw_ostream.h" #include "llvm/IR/Module.h" #include "llvm/IR/Function.h" #include "llvm/Support/CommandLine.h" #include "llvm/Analysis/PostDominators.h" #include "llvm/Analysis/DominanceFrontier.h" #include "llvm/Support/FileSystem.h" #include "llvm/IR/InstIterator.h" #include "../utils/mk_debug.h" #include "../utils/z3_fp_helpers.h" #include <vector> #include <set> #include <map> #include <iostream> #include <fstream> #include <sstream> #include <string> #include <algorithm> #include <cstdint> #include "box.h" #include "oct.h" #include "pk.h" #include "pkeq.h" //#include "ap_abstract1.h" #include <z3.h> #include <z3++.h> #include <z3_api.h> #include <z3_fixedpoint.h> using namespace llvm; using namespace z3_fp_helpers; ap_manager_t *manG; int totalPairs = 0; int filteredPairs = 0; // Size of Z3 bitvector sort used in fixedpoint solver //static const unsigned Z3_BV_SIZE = sizeof(uintptr_t) * 8; // This size needs to be able to represent all the values used in the analysis. // Increase it as necessary. If it gets too big, things seem to get pretty // slow. static const unsigned Z3_BV_SIZE = 16; // Command line flags. These are used in other files! // priority information flag cl::opt<bool> usePriG("priority" , cl::desc("Use priority information") , cl::init(false)); cl::opt<bool> useBoxG("box" , cl::desc("Use box abstract domain") , cl::init(false)); cl::opt<bool> useOctG("oct" , cl::desc("Use octagon abstract domain") , cl::init(false)); cl::opt<bool> usePolyG("pkpoly" , cl::desc("Use (strict) convex polyhedral abstract domain") , cl::init(false)); cl::opt<bool> useLinEqG("pklineq" , cl::desc("Use linear inequality abstract domain") , cl::init(false)); cl::opt<bool> noCombinsG("nocombs" , cl::desc("Combine all interferences into a single state (no " "combinational exploration") , cl::init(false)); cl::opt<bool> useConstraintsG("constraints" , cl::desc("Use constraint solver to prune infreasible interferences") , cl::init(false)); cl::opt<bool> assertSliceG("aslice" , cl::desc("Slice on assertion(s) (requires PDG pass)") , cl::init(false)); cl::opt<bool> impactG("impact" , cl::desc("Use change-impact analysis (equires change-impact pass).") , cl::init(false)); // When true, the state at the time of a thread's creation is used instead of // the initial state of the entire program. cl::opt<bool> dynInitG("dyninit" , cl::desc("Calculate the initial state of a thread dynamically") , cl::init(false)); cl::opt<bool> filterMHB("filter-mhb" , cl::desc("Filter interferences based on global program must-happen before") , cl::init(false)); cl::opt<bool> tsoConstrG("tso" , cl::desc("Use TSO interference constraints") , cl::init(false)); cl::opt<bool> psoConstrG("pso" , cl::desc("Use PSO interference constraints") , cl::init(false)); cl::opt<bool> rmoConstrG("rmo" , cl::desc("Use RMO interference constraints") , cl::init(false)); // The default behavior is to attempt to constrain branches on ICMP // instructions. For example, // // br %1 label %2 label %3 // // If %1 is an icmp instruction, e.g., icmp ne %5 %6 then the branch being // true (resp. false) not only means %1 should be 1 (resp 0) but also that %5 // != %6 (resp. %5 == %6). // // So, when generating a fact to pass to either the true of false branch, using // the icmp instruction allows for more acurrate facts being passed. Obviously, // this comes with some extra overhead. cl::opt<bool> constrICmp("-no-icmp-constr" , cl::desc("Do not constrain branches using ICMP predicates") , cl::init(true)); cl::opt<std::string> z3BinLocG("z3" , cl::desc("Location of Z3 binary") , cl::init("")); // Disable debugging output in debug build #ifdef MK_DEBUG cl::opt<bool> nodebugG("nodebug" , cl::desc("Disable debug output for debug build") , cl::init(false)); #endif // The maximum number of combinational interference permutations static unsigned maxCombPermsG = 0; struct WorklistAI : public ModulePass { static char ID; // The type of the worklist typedef std::map<BasicBlock*, LatticeFact> worklist_t; static constexpr const char * const constraintFile = "poconstr.smt2"; virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesAll(); if (useConstraintsG || filterMHB) { AU.addRequired<DominatorTreeWrapperPass>(); AU.addRequired<PostDominatorTree>(); } } // Print the passed map to stderr void printFactMapStderr(std::map<BasicBlock*, LatticeFact> m) const { for (auto i = m.begin(), e = m.end(); i != e; ++i) { BasicBlock *b = i->first; LatticeFact f = i->second; errs() << "BasicBlock: " << *b ; errs() << "Facts: "; f.fprint(stderr); errs() << '\n'; } } void printValToNameStderr(const std::map<Value*, std::string> m) const { for (auto i = m.begin(), e = m.end(); i != e; ++i) { Value *v = i->first; std::string s = i->second; errs() << s << ": " << *v << '\n'; } } WorklistAI() : ModulePass(ID) { } // Given a lattice fact, return a map with each BasicBlock in the module // mapped to the passed fact. std::map<BasicBlock*, LatticeFact> initBBs(const LatticeFact &init , Module &M) const { std::map<BasicBlock *, LatticeFact> ret; for (auto mi = M.begin(), me = M.end(); mi != me; ++mi) { for (auto fi = mi->begin(), fe = mi->end(); fi != fe; ++fi) { BasicBlock *bb = &*fi; ret.emplace(bb, init); } } return ret; } // Given a lattice fact, return a map with each BasicBlock in the function // mapped to the passed fact std::map<BasicBlock*, LatticeFact> initBBs(const LatticeFact &init , Function *F) const { std::map<BasicBlock *, LatticeFact> ret; for (auto fi = F->begin(), fe = F->end(); fi != fe; ++fi) { BasicBlock *bb = &*fi; ret.emplace(bb, init); } return ret; } // Merge the passed vector of new facts into the passed worklist void merge_worklist( std::map<BasicBlock *, LatticeFact> *wl , std::vector<std::pair<BasicBlock*, LatticeFact>> ps) const { //errs() << "Size of ps: " << ps.size() << "\n"; for (auto p = ps.begin(), pe = ps.end(); p != pe; ++p) { // Check if any of the basicblock are already in worklist. // Merge if they are. BasicBlock *newB = p->first; DEBUG_MSG("Merging worklist: BB: " << *newB << '\n'); auto f = wl->find(newB); if (f == wl->end()) { DEBUG_MSG("Fact not in list: "); DEBUG(p->second.fprint(stderr);); DEBUG_MSG("\n"); wl->emplace(newB, p->second); } else { // TODO: Widen here LatticeFact mergeFact = LatticeFact::factJoin(f->second, p->second); //LatticeFact mergeFact = LatticeFact::factJoinWiden(f->second, p->second); DEBUG_MSG("Fact in list, merged: "); DEBUG(mergeFact.fprint(stderr);); DEBUG_MSG("\n"); wl->erase(f); wl->emplace(newB, mergeFact); } } return; } // Given a value, return its string name. // // This will always return a string. If the value has never been encountered // before, it will be stored in the valToName map with a fresh name. // // This also updates nameToVal so a reverse lookup can be done (see // getValue()) std::string getName(std::map<Value *, std::string> &valToName , std::map<std::string, Value *> &nameToVal, Value *v) const { auto f = valToName.find(v); if (f == valToName.end()) { size_t newSz = valToName.size(); std::string newName = "v" + std::to_string(newSz); auto res = valToName.insert(std::make_pair(v, newName)); if (!res.second) { assert(0 && "item already exists in valToName map"); } nameToVal.emplace(newName, v); return (res.first)->second; } return f->second; } // Given a string name of a value return the actual value. // // Note: this will crash if the value has never been saved in the map before. Value *getValue(const std::map<std::string, Value*> nameToVal , std::string s) const { auto f = nameToVal.find(s); if (f == nameToVal.end()) { assert(0 && "item not found in nameToVal"); } return f->second; } // Return the name of all the variables used in the program VarVisitor::Vars getAllVarNames(Module &M) const { VarVisitor vv; vv.visit(M); // Also add in the float/int globals variables for (auto gi = M.global_begin(), ge = M.global_end(); gi != ge; ++gi) { GlobalVariable &g = *gi; if (Utils::isIntegerGlobal(&g)) { vv.vars.ints.push_back(&g); } else if (Utils::isFloatGlobal(&g)) { vv.vars.floats.push_back(&g); } else { errs() << "[WARNING] Global which is neither Integer nor Float\n"; errs() << g << '\n'; errs() << "It is not being monitored (there may be errors en route)\n"; } } // TODO: Need to handle arrays here return vv.vars; } // Return the function named "main" or NULL if the module does not have a // "main" function Function *getMainFuncOrNULL(Module &M) const { for (auto mi = M.begin(), me = M.end(); mi != me; ++mi) { Function &f = *mi; if (f.getName() == "main") { return &f; } } return NULL; } // Return any function used in a pthread_create() call. // This will crash if any indirect functions are found std::set<Function *> getThreads(Module &M) const { std::set<Function *> ret; for (auto mi = M.begin(), me = M.end(); mi != me; ++mi) { for (auto fi = mi->begin(), fe = mi->end(); fi != fe; ++fi) { for (auto bi = fi->begin(), be = fi->end(); bi != be; ++bi) { Instruction *I = &*bi; if (CallInst* ci = dyn_cast<CallInst>(I)) { Function *called = ci->getCalledFunction(); if (called->getName() == "pthread_create") { // Found pthread_create. The 2nd argument (zero indexed) is the // function being called Value *v = ci->getArgOperand(2); if (Function *tFunc = dyn_cast<Function>(v)) { ret.insert(tFunc); } else { errs() << "[ERROR] pthread_create with non function 2nd arg\n"; errs() << *v << '\n'; exit(EXIT_FAILURE); } } } } // for (bi ... )/ } // for (fi ... ) } // for (mi ... ) return ret; } std::vector<CallInst *> getThreadCreate(Module &M) const { std::vector<CallInst *> ret; for (auto mi = M.begin(), me = M.end(); mi != me; ++mi) { Function *cur = &*mi; Utils::addVector(ret, getThreadCreate(cur)); } return ret; } std::vector<CallInst *> getThreadCreate(Function *F) const { std::vector<CallInst *> ret; for (auto bi = F->begin(), be = F->end(); bi != be; ++bi) { for (auto ii = bi->begin(), ie = bi->end(); ii != ie; ++ii) { Instruction *I = &*ii; if (CallInst* ci = dyn_cast<CallInst>(I)) { Function *called = ci->getCalledFunction(); if (called->getName() == "pthread_create") { ret.push_back(ci); } } } // for (ii ...) } // for (bi ... )/ return ret; } // Collect the Integer/Floating point function parameters VarVisitor::Vars getFuncParamNames(Module &M) const { VarVisitor::Vars vars; for (auto mi = M.begin(), me = M.end(); mi != me; ++mi) { Function &f = *mi; Function::ArgumentListType &al = f.getArgumentList(); for (auto ai = al.begin(), ae = al.end(); ai != ae; ++ai) { Argument &a = *ai; Type *at = a.getType(); if (at->isPointerTy() || at->isIntegerTy()) { vars.ints.push_back(&a); } else if (at->isFloatingPointTy()) { vars.floats.push_back(&a); } else { errs() << "[ERROR] unhandled argument type: " << a << '\n'; assert(0 && "see above"); } } } return vars; } // Given the list of integer and floating point values return an environment // containing them all. // // Returns NULL if the environment could not be created // // Note: The user must manage the memory of the returned environment. ap_environment_t *createEnvironment(std::map<Value *, std::string> &valToName , std::map<std::string, Value *> &nameToVal, Module &M) const { // TODO: Global variables should also be assigned to variable names? VarVisitor::Vars vs = getAllVarNames(M); vs = VarVisitor::mergeVars(vs, getFuncParamNames(M)); DEBUG_MSG("[DEBUG] Num Int vars: " << vs.ints.size() << '\n'); DEBUG_MSG("[DEBUG] Num Float vars: " << vs.floats.size() << '\n'); // Use sets to ensure no duplicates are added to the environment std::set<const char *> intStrs; std::set<const char *> floatStrs; // This will create names for the all the int and float variables in the // program and store them in the internal maps of this class (getName()) // Put all the ints in a set for (size_t i = 0; i < vs.ints.size(); ++i) { Value *v = vs.ints[i]; DEBUG_MSG("[DEBUG] getting int value: " << *v << '\n'); std::string vs = getName(valToName, nameToVal, v); DEBUG_MSG("\tname: " << vs << '\n'); intStrs.insert(vs.c_str()); } ap_var_t intVs[intStrs.size()]; size_t pos = 0; for (auto it = intStrs.begin(), e = intStrs.end(); it != e; ++it) { intVs[pos++] = (ap_var_t)(*it); } // Put all the floats in a set for (size_t i = 0; i < vs.floats.size(); ++i) { Value *v = vs.floats[i]; DEBUG_MSG("[DEBUG] getting float value: " << *v << '\n'); std::string vs = getName(valToName, nameToVal, v); DEBUG_MSG("\tname: " << vs << '\n'); floatStrs.insert(vs.c_str()); } ap_var_t floatVs[floatStrs.size()]; pos = 0; for (auto it = floatStrs.begin(), e = floatStrs.end(); it != e; ++it) { floatVs[pos++] = (ap_var_t)(*it); } ap_environment_t *env = ap_environment_alloc(intVs , intStrs.size() , floatVs , floatStrs.size()); assert(env && "error creating environment"); return env; } // Return a vector of functions such that the parent of any thread always // ocurrs at a lower index than the child. std::vector<Function *> sortByCreation(Function *main , const std::map<Function *, std::vector<Function*>> parent2child) { std::vector<Function *> ret; std::deque<Function *> toProcess; // Main is the parent of everyone toProcess.push_back(main); while (toProcess.size()) { Function *curParent = toProcess.front(); toProcess.pop_front(); // Add the parent ret.push_back(curParent); // Add all its children to be processed auto iter = parent2child.find(curParent); if (iter != parent2child.end()) { std::vector<Function *> children = iter->second; // The children of the children also need to be added to `ret` for (Function *c : children) { toProcess.push_back(c); } } } assert(ret.size() && "returning size zero vector"); return ret; } // Given the passed lattice fact with all variables at whatever initial value // you want (e.g., undefined (top)) this will update the passed fact // (initFact) such that all the globals are initialized to their starting // value (from the source code). // This assumes that all LLVM Values are mapped to name for apron to use // (v2v). LatticeFact getInitState(Module *M , const LatticeFact initFact , const std::map<Value *, std::string> v2v) const { LatticeFact ret = initFact; for (auto gi = M->global_begin(), ge = M->global_end(); gi != ge; ++gi) { // Get the initializer for the global. Lookup the name, and set the value // of the name to the initializer GlobalVariable *g = &*gi; if (!g->hasInitializer()) { errs() << "[ERROR] Global without initializer (possibly external)\n" << *g << '\n'; assert(0 && "see above"); } const Constant *c = g->getInitializer(); if (const ConstantInt *ci = dyn_cast<ConstantInt>(c)) { std::string gName = Utils::valueToStringUnsafe(v2v, g); int val = Utils::getConstantIntUnsafe(ci); DEBUG_MSG("[DEBUG] Initializing Global: "); DEBUG_MSG("\tGlobal Name: " << gName << '\n'); DEBUG_MSG("\tInit Val: " << val << '\n'); ret = ret.assign(gName, val); DEBUG(ret.fprint(stderr);); } // TODO: also need to handle floats (ConstantFloat::getValueAPF()) //if (isFloatGlobal(g)) { // ... //} else { errs() << "[WARNING] Initializing unhandled global type: " << *g << "\nSetting to default initial value\n"; } } // for return ret; } // Return all the stores in the passed function std::vector<StoreInst *> getStores(Function *f) const { std::vector<StoreInst *> ret; for (auto fi = f->begin(), fe = f->end(); fi != fe; ++fi) { BasicBlock &b = *fi; for (auto bi = b.begin(), be = b.end(); bi != be; ++bi) { Instruction *i = &*bi; if (StoreInst *si = dyn_cast<StoreInst>(i)) { ret.push_back(si); } } } return ret; } // Return all the stores in the passed BasicBlock std::vector<StoreInst *> getStores(BasicBlock *b) { std::vector<StoreInst *> ret; for (auto bi = b->begin(), be = b->end(); bi != be; ++bi) { Instruction *i = &*bi; if (StoreInst *si = dyn_cast<StoreInst>(i)) { ret.push_back(si); } } return ret; } // Return all the loads in the passed function std::vector<Instruction *> getLoads(Function *f) const { std::vector<Instruction *> ret; for (auto fi = f->begin(), fe = f->end(); fi != fe; ++fi) { BasicBlock &b = *fi; for (auto bi = b.begin(), be = b.end(); bi != be; ++bi) { Instruction *i = &*bi; //if (LoadInst *si = dyn_cast<LoadInst>(i)) { if (Utils::isSomeLoad(i)) { ret.push_back(i); } } } return ret; } bool loadStoreSameVal(Instruction *si, Instruction *li) const { if (StoreInst *s = dyn_cast<StoreInst>(si)) { if (LoadInst *l = dyn_cast<LoadInst>(li)) { return loadStoreSameValSL(s, l); } else if (AtomicRMWInst *rmw = dyn_cast<AtomicRMWInst>(li)) { return loadStoreSameValSRMW(s, rmw); } else { assert(0 && "loadStoreSameVal: unhandled load type sub StoreInst"); } } else if (AtomicRMWInst *rmw = dyn_cast<AtomicRMWInst>(si)) { if (LoadInst *l = dyn_cast<LoadInst>(li)) { return loadStoreSameValRMWL(rmw, l); } else if (AtomicRMWInst *rmwl = dyn_cast<AtomicRMWInst>(li)) { return loadStoreSameValRMWRMW(rmw, rmwl); } else { assert(0 && "loadStoreSameVal: unhandled load type sub atomicrmw"); } } else { assert(0 && "loadStoreSameVal: unhandled store type"); } } bool loadStoreSameValRMWL(AtomicRMWInst *rmw, LoadInst *l) const { Value *stPtr = rmw->getPointerOperand(); Value *lPtr = l->getPointerOperand(); return stPtr == lPtr; } bool loadStoreSameValRMWRMW(AtomicRMWInst *rmws, AtomicRMWInst *rmwl) const { Value *stPtr = rmws->getPointerOperand(); Value *lPtr = rmwl->getPointerOperand(); return stPtr == lPtr; } bool loadStoreSameValSRMW(StoreInst *s, AtomicRMWInst *rmw) const { Value *stPtr = s->getPointerOperand(); Value *lPtr = rmw->getPointerOperand(); return stPtr == lPtr; } // Return true if the passed store stores into the memory location loaded by // the load bool loadStoreSameValSL(StoreInst *s, LoadInst *l) const { Value *stPtr = s->getPointerOperand(); Value *lPtr = l->getPointerOperand(); return stPtr == lPtr; } // Given the set of possible interferences for each load in the passed // thread, reanalyze the thread in the presense of the interferences. // // The fact at the start of each basicblock after the analysis // stabalizes is returned. // // This will do a combinational exploration of the possible interferences for // each load, e,g, if l1 has two interferences i1 and i2, and l2 has two // interferences i3 and i4, we will explore all the combinations of reading // ((i1,i2), (i3,i4)) as well as reading from the thread's own memory state // (i.e., at most 9 combinations). // // The passed vector, rErrors, will contain any reachable error statements as // well as the reachable fact at the statement. std::map<BasicBlock *, LatticeFact> analyzeThreadInterf( ap_manager_t *man , ap_environment_t *env , Function *f , CallInst *createSite , const std::map<Instruction *, std::vector<Instruction *>> interfs , const std::map<Instruction *, LatticeFact> stFacts //, std::vector<std::pair<Instruction *, LatticeFact>> &rErrors , std::set<Instruction *> &rErrors , std::map<Instruction *, LatticeFact> &reachableStores , std::map<CallInst *, LatticeFact> &reachThreadCreate , LatticeFact entryFact , const std::set<Instruction *> assertSlice , const std::set<Instruction *> impacted , const std::set<Instruction *> mayImpact , const std::map<Value *, std::string> v2n , z3::context &ctx , Z3_fixedpoint &zfp ) const { DEBUG_MSG("[DEBUG] analyzeThreadIntefer(): number of interferences: " << interfs.size() << '\n'); //std::cout << "Interf size: " << interfs.size() << "\n"; if (!interfs.size()) { // When there are no interferences, we do not need to do any // combinational exploration return analyzeFuncNoInterf(man, env, rErrors, reachableStores , reachThreadCreate, entryFact, assertSlice, impacted, mayImpact, v2n, f); } if (noCombinsG) { // If we are not doing a combinatorial exploration, join all the // interferences for each load into a single fact std::map<Instruction *, LatticeFact> allInterfs = joinInterfs(interfs, stFacts); // Then, perform the analysis as usual but inform the transfer functions // to consider both the interference and the state of the thread // simultaneously return analyzeFunc(man, env, allInterfs, rErrors, reachableStores , reachThreadCreate, assertSlice, impacted, mayImpact, v2n, entryFact, f, true); } // Calculate the cartesian product of all possible facts from which a load // can read from including its own memory state. // To do this, consider that 0 indicates a thread should read from its own // memory state at the time of some load while a value higher than 0 is an // index into the vector of StoreInsts in intefers (note: it will be off by // one (indexed starting from one)) std::vector<int> choicesPerLoad; // Each location in choicesPerLoad corresponds to a load instruction. The // ordering of load instructions is based on the iterator order of interfs. for (auto i = interfs.begin(), ie = interfs.end(); i != ie; ++i) { // Incluce one extra choice, the thread reading the value from its own // memory environment int v = i->second.size() + 1; assert(v > 0 && "making zero choices"); choicesPerLoad.push_back(v); } // The results of each permutation will be joined into this map std::map<BasicBlock *, LatticeFact> res; CartesianProduct cp(choicesPerLoad); // Test each possible combination unsigned count = 1; for (; !cp.AtEnd(); cp.Increment()) { std::vector<int> curPerm = cp.permutation(); bool ret = testCurPerm(man , env , f , createSite , curPerm , interfs , stFacts , rErrors , reachableStores , reachThreadCreate , entryFact , assertSlice , impacted , mayImpact , v2n , ctx , zfp , res); if (ret) { // Only increment the number of permutations if the permutation is // tested. maxCombPermsG = std::max(maxCombPermsG, count); count++; } } // for (; !cp.AtEnd(); cp.Increment()) return res; } // Test the passed permutation. // // Returns true if the abstract interperter was run (i.e., the solver could // not prove the permutation was redundant) // // any facts in res will be merged with the facts produced by the analysis bool testCurPerm(ap_manager_t *man , ap_environment_t *env , Function *f , CallInst *createSite , const std::vector<int> perm , const std::map<Instruction *, std::vector<Instruction *>> interfs , const std::map<Instruction *, LatticeFact> stFacts //, std::vector<std::pair<Instruction *, LatticeFact>> &rErrors , std::set<Instruction *> &rErrors , std::map<Instruction *, LatticeFact> &reachableStores , std::map<CallInst *, LatticeFact> &reachThreadCreate , LatticeFact entryFact , const std::set<Instruction *> assertSlice , const std::set<Instruction *> impacted , const std::set<Instruction *> mayImpact , const std::map<Value *, std::string> v2n , z3::context &ctx , Z3_fixedpoint &zfp , std::map<BasicBlock *, LatticeFact> &res ) const { assert(perm.size() == interfs.size() && "choice number mismatch"); // Note: since the store and load instructions are all orded (they are in a // map) the results for the same map of store instructions will lead to the // same order in the permutation vector. Additionally, the interferences // can only grow and not decrease (everything is monotonic). So, if we see // the same _exact_ permutation again we can use a cached result. // // This works because the constraints are based on the entire program // (i.e., the constraints will always be the same for each call). // // This is a map from the permutation vector to the cached result static std::map<std::vector<int>, bool> permCache; DEBUG_MSG("Permutation: "); DEBUG(for (int i : perm) DEBUG_MSG(i << " ");); DEBUG_MSG('\n'); std::map<Instruction *, LatticeFact> curInterfMap; // Same as curInterfMap but maps a Load to the store it is reading from std::map<Instruction *, Instruction *> curInterfStoreMap; // Map from an instruction reading from the thread-local to the // corresponding store its reading from. std::map<Instruction *, Instruction *> curSelfStoreMap; int pos = 0; // Given the indices in the permutation, gather up the corresponding facts // at the interfering stores. for (auto i = interfs.begin(), ie = interfs.end(); i != ie; ++i, ++pos) { int curChoice = perm[pos]; Instruction *l = i->first; DEBUG_MSG("[DEBUG] Adding load--fact interference\n"); DEBUG_MSG("\tload: " << *l << '\n'); if (curChoice == 0) { // Not including the load in the map indicates that it should read // from its own memory environment DEBUG_MSG("\tstore: self\n"); std::vector<Instruction *> ss = getPreviousStoresWithCreate(l, createSite); if (ss.size() == 1) { DEBUG_MSG("\tfound predecessor store:" << *(ss[0]) << '\n'); curSelfStoreMap.emplace(l, ss[0]); } else { // TODO: what constraints can we deduce when there is more than one // preceeding store? } continue; } // Indecies in the permutation are one indexed (since zero is used in // the previous `if`) size_t idx = curChoice - 1; std::vector<Instruction*> sts = i->second; assert(idx < sts.size() && "out-of-bounds choice"); Instruction *st = sts[idx]; assert(curInterfMap.find(l) == curInterfMap.end() && "duplicate load"); assert(stFacts.find(st) != stFacts.end() && "fact not found for store"); DEBUG_MSG("\tstore: " << *st << '\n'); curInterfMap.emplace(l, Utils::mapAtUnsafe(stFacts, st)); if (useConstraintsG) { curInterfStoreMap.emplace(l, st); } } // for (auto i = interfs.begin(), ie = interfs.end(); ...) // Check if this interference is feasible if (useConstraintsG) { auto it = permCache.find(perm); DEBUG_MSG("Checking perm cache\n"); if (it != permCache.end()) { DEBUG_MSG("[DEBUG] perm cache hit!\n"); if (it->second) { DEBUG_MSG("\tviolates program order\n"); // return without testing, can safely skip. return false; } // falling through this if brach (if (it != permCache.end())) leads // to the permutation being tested but violatesProgOrder() will not // be called thus saving the solver call time } else { // Since we have never seen this permutation before, test if it // violates the program order if (violatesProgOrder(curInterfStoreMap, curSelfStoreMap, ctx, zfp)) { DEBUG_MSG("\tpermutation violates program order\n"); DEBUG_MSG("\t*Permutation: "); DEBUG(for (int i : perm) DEBUG_MSG(i << " ");); DEBUG_MSG('\n'); permCache[perm] = true; // Test can be safely skipped return false; } else { DEBUG_MSG("\tpermutation does not violate prog. order\n"); DEBUG_MSG("\t*Permutation: "); DEBUG(for (int i : perm) DEBUG_MSG(i << " ");); DEBUG_MSG('\n'); permCache[perm] = false; } } } DEBUG_MSG("running abstract interpretation\n"); // Test the thread in the presense of this round of interferences std::map<BasicBlock *, LatticeFact> newRes = analyzeFunc(man, env, curInterfMap, rErrors, reachableStores , reachThreadCreate, assertSlice, impacted, mayImpact, v2n, entryFact, f, false); DEBUG_MSG("merging AI results\n"); // Merge the new results for this combination with the old res = mergeFactMaps(res, newRes); return true; } // Return true if the load instructions reading from the passed store // instructions violates the program order. // // This uses the baseConstrs and issues a solver call to muZ. // // rfs are extra (i1, i2) pairs where reads-from(i1, i2) will be added but // not checked if its feasible bool violatesProgOrder(const std::map<Instruction *, Instruction *> interfs , const std::map<Instruction *, Instruction *> rfs , z3::context &ctx, Z3_fixedpoint &zfp) const { DEBUG_MSG("Checking prog order\n"); if (interfs.size() == 0) { // Interferences can be of size zero when the thread is reading from its // own memory environment. This will never violate the program order DEBUG_MSG("\tinterf.size() is zero, skipping prog. order check\n"); return false; } // If a loads and stores is in this map then we already have the results // (the associated value). The solver does not need to be called std::map<std::set<Instruction*>, bool> readFromCache; std::set<Instruction*> curInsts; // The reads-from constraints are only valid for the current interation; // so, save a backtracking location in the solver. Z3_fixedpoint_push(ctx, zfp); bool violates = false; // Add the read-from constraints from the passed map for (auto i = interfs.begin(), ie = interfs.end(); i != ie; ++i) { Instruction *l = i->first; Instruction *s = i->second; curInsts.insert(l); curInsts.insert(s); addReadsFromFact(ctx, zfp, l ,s); } for (auto i = rfs.begin(), ie = rfs.end(); i != ie; ++i) { Instruction *l = i->first; Instruction *s = i->second; addReadsFromFact(ctx, zfp, l ,s); } // Check for any infeasible reads-from // Note: this needs to be run after the previous for-loop runs to // completion so that all the reads-from constraints are added for (auto i = interfs.begin(), ie = interfs.end(); i != ie; ++i) { Instruction *l = i->first; Instruction *s = i->second; Z3_bool res = queryNotReads(ctx, zfp, l, s); if (res == Z3_L_TRUE) { violates = true; // Finding one which violates is sufficient to stop break; } else if (res == Z3_L_FALSE) { violates = false; DEBUG_MSG("No program order violation, moving to next reads-from\n"); } else if (res == Z3_L_UNDEF) { // Assume that it does not violate if it is unknown errs() << "[WARNING] undef result from muZ\n"; violates = false; } else { assert(0 && "unreachable"); } } // Restore the previous state of the solver. This removes all the // reads-from constraints added Z3_fixedpoint_pop(ctx, zfp); // Update the cache readFromCache[curInsts] = violates; DEBUG_MSG("Program order violation? " << violates << '\n'); return violates; } // Return the results of a query on (not-rf l st) Z3_bool queryNotReads(z3::context &ctx, Z3_fixedpoint &zfp, Instruction *l , Instruction *st) const { assert(Utils::isSomeLoad(l) && "reading from non-load"); z3::expr args[2] = {getValueBVID(ctx, l), getValueBVID(ctx, st)}; z3::expr nrfApp= getNotReadsFromFuncDecl(ctx)(2, args); Z3_bool ret = Z3_fixedpoint_query(ctx, zfp, nrfApp); #if 0 z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE); z3::sort boolSort = ctx.bool_sort(); //Z3_fixedpoint_register_relation(ctx, zfp //, Z3_get_app_decl(ctx //, Z3_to_app(ctx, qAst))); //Z3_ast ldID = getValueBVID(ctx, l); //Z3_ast stID = getValueBVID(ctx, st); z3::expr args[2] = {getValueBVID(ctx, l), getValueBVID(ctx, st)}; z3::expr nrfApp = getNotReadsFromFuncDecl(ctx)(2, args); // Create a relation which is true if the query is true. // The truth of the query is based off a rule z3::expr qAst = z3::expr(ctx, Z3_mk_fresh_const(ctx, "query", boolSort)); Z3_fixedpoint_add_rule(ctx, zfp , Z3_mk_implies(ctx, nrfApp, qAst), NULL); Z3_bool ret = Z3_fixedpoint_query(ctx, zfp, qAst); #endif #ifdef MK_DEBUG DEBUG_MSG("NRF Query Stats\n"); z3::stats sts = z3::stats(ctx, Z3_fixedpoint_get_statistics(ctx, zfp)); std::cerr << sts << '\n'; std::string rules = Z3_fixedpoint_to_string(ctx, zfp, 0, NULL); DEBUG_MSG("Rules: " << rules << '\n';); DEBUG_MSG("Query: " << Z3_ast_to_string(ctx, nrfApp) << '\n'); #endif return ret; } // Return the results of a query on (linehigh l st) // Result of query: 1:true, -1:false, 0:undefined bool queryPri(z3::context &ctx, Z3_fixedpoint &zfp, Instruction *l , Instruction *st) const { // check nonLastSt first z3::expr args[1] = {getValueBVID(ctx, st)}; z3::expr nonLastStApp = getNonLastStFuncDecl(ctx)(1, args); Z3_bool nonLastRet = Z3_fixedpoint_query(ctx, zfp, nonLastStApp); errs() << "======================================\n"; errs() << "ID of Load: " << getId(l, Z3_BV_SIZE) << "\n"; errs() << *l << "\n"; errs() << "ID of Store: " << getId(st, Z3_BV_SIZE) << "\n"; errs() << *st << "\n"; if (nonLastRet == 1) { errs() << "St is nonLast\n"; } else { errs() << "St is NOT nonLast\n"; } // check complete ld z3::expr args3[1] = {getValueBVID(ctx, l)}; z3::expr compLdApp = getCompLdFuncDecl(ctx)(1, args3); Z3_bool compLdRet = Z3_fixedpoint_query(ctx, zfp, compLdApp); if (compLdRet == 1) { errs() << "Load is completeLoad\n"; } else { errs() << "Load is not completeLoad\n"; } if (compLdRet == 1 && nonLastRet == 1) { errs() << "======================================\n"; return false; } if (compLdRet != 1 && nonLastRet != 1) { errs() << "======================================\n"; return true; } // check ld-st higher z3::expr args1[2] = {getValueBVID(ctx, l), getValueBVID(ctx, st)}; z3::expr lineHighApp = getLineHighFuncDecl(ctx)(2, args1); Z3_bool ldStRet = Z3_fixedpoint_query(ctx, zfp, lineHighApp); // check st-ld higher z3::expr args2[2] = {getValueBVID(ctx, st), getValueBVID(ctx, l)}; z3::expr lineHighApp2 = getLineHighFuncDecl(ctx)(2, args2); Z3_bool stLdRet = Z3_fixedpoint_query(ctx, zfp, lineHighApp2); if (compLdRet != 1 && nonLastRet == 1 && ldStRet == 1) { errs() << "ld is higher than st\n"; errs() << "======================================\n"; return true; } else if (compLdRet !=1 && nonLastRet == 1 && ldStRet != 1) { errs() << "ld is not higher than st\n"; errs() << "======================================\n"; return false; } else if (compLdRet == 1 && nonLastRet != 1 && stLdRet == 1) { errs() << "st is higher than ld\n"; errs() << "======================================\n"; return true; } else if (compLdRet == 1 && nonLastRet != 1 && stLdRet != 1) { errs() << "st is not higher than ld\n"; errs() << "======================================\n"; return false; } else { assert(0 && "There is no case for here"); } /* std::cout << "Priority Query Stats"; z3::stats sts = z3::stats(ctx, Z3_fixedpoint_get_statistics(ctx, zfp)); std::cerr << sts << "\n"; */ //#ifdef MK_DEBUG //DEBUG_MSG("Priority Query Stats\n"); //z3::stats sts = z3::stats(ctx, Z3_fixedpoint_get_statistics(ctx, zfp)); //std::cerr << sts << '\n'; //#endif } // Return the results of a query on (MHB l st) Z3_bool queryMHB(z3::context &ctx, Z3_fixedpoint &zfp, Instruction *l , Instruction *st) const { z3::expr args[2] = {getValueBVID(ctx, l), getValueBVID(ctx, st)}; z3::expr mhbApp = getMHBFuncDecl(ctx)(2, args); Z3_bool ret = Z3_fixedpoint_query(ctx, zfp, mhbApp); #ifdef MK_DEBUG DEBUG_MSG("MHB Query Stats\n"); z3::stats sts = z3::stats(ctx, Z3_fixedpoint_get_statistics(ctx, zfp)); std::cerr << sts << '\n'; #endif return ret; } // Given an instruction and Value found the closest preceding store within // the same function as the instruction to the passed Value. // // If there are none, returns an empty vector. static std::vector<Instruction *> getPreviousStores(Instruction *i, Value *v) { assert(i != NULL && "getPreviousStores(i,v): NULL instruction"); assert(v != NULL && "getPreviousStores(i,v): NULL value"); DEBUG_MSG("[DEBUG] getPreviousStores(): " << *i << ", v: " << *v << '\n'); Function *f = i->getParent()->getParent(); BasicBlock *b = i->getParent(); // Check if there is simply a store in this basicblock Instruction *prevStore = NULL; for (Instruction &bbi : *b) { if (&bbi == i) { break; } Value *strPtr = Utils::getStorePtr(&bbi); if (strPtr == v) { prevStore = &bbi; } } if (prevStore != NULL) { std::vector<Instruction *> ret; ret.push_back(prevStore); return ret; } // We know there is no store before `i` to `v` in the BasicBlock. If there // is one it must come from some other BasicBlock. std::map<BasicBlock *, std::set<Instruction*>> reach = getReachingStores(f); std::set<Instruction*> bReachIn = Utils::mapAtUnsafe(reach, b); DEBUG_MSG(" numReachingStores:" << bReachIn.size() << '\n'); // Find all the incoming stores to `v` std::vector<Instruction*> storesToV; for (auto it = bReachIn.begin(), et = bReachIn.end(); it != et; ++it) { Instruction *st = *it; assert(st != NULL && "getPreviousStores: NULL in reachable map"); Value *stPtr = Utils::getStorePtr(st); assert(stPtr != NULL && "getPreviousStores: reachable store with NULL ptr operand"); if (stPtr == v) { storesToV.push_back(st); } } // storesToV contains zero or more preceeding stores return storesToV; //if (storesToV.size() == 0) { // // There are no stores before `i` to `v` in the BasicBlock and there are no // return storesToV; //} //else if (storesToV.size() == 1) { // Instruction *storeIn = storesToV[0]; // assert(storeIn != NULL && "getPreviousStore: NULL reachable store"); // assert(Utils::getStorePtr(storeIn) != NULL // && "getPreviousStore: storeIn with NULL ptr operand"); // return storeIn; //} //else { // DEBUG_MSG("num reaching stores:" << storesToV.size() << '\n'); // for (size_t i = 0; i < storesToV.size(); ++i) { // DEBUG_MSG(" " << *(storesToV[i]) << '\n'); // } // assert(0 && "getPreviousStore: more than one reaching store"); //} } // CallInst is the thread_create function of `i`. Attempt to look backwards // from i to find a previous store including looking before the thread // creation site. static std::vector<Instruction *> getPreviousStoresWithCreate(Instruction *i , CallInst *cre) { if (LoadInst *l = dyn_cast<LoadInst>(i)) { Value *v = l->getPointerOperand(); std::vector<Instruction *> ret = getPreviousStores(i, v); if (ret.size() > 0) { // Found some previous store return ret; } else { // Try to look back from the creation site. // TODO: this could continue up the thread creation chain but it doesn't DEBUG_MSG("[DEBUG] Search searching back from creation stite for store\n"); if (cre == NULL) { DEBUG_MSG(" NULL creation site, not searching\n"); return ret; // ret.size <= 0 } ret = getPreviousStores(cre, v); return ret; } } else { errs() << "[ERROR] getPreviousStoreWithCreate: unimplemented instruction type: " << * i << '\n'; assert(0 && "unreachable"); } } // Given an instruction performing a load find the closest precding store // within the same Function. If no store is found, return NULL. static std::vector<Instruction *> getPreviousStore(Instruction *i) { if (LoadInst *l = dyn_cast<LoadInst>(i)) { Value *v = l->getPointerOperand(); return getPreviousStores(i, v); } else { errs() << "[ERROR] getPreviousStores: unimplemented instruction type: " << * i << '\n'; assert(0 && "unreachable"); } //DEBUG_MSG("[DEBUG] getPreviousStore(): " << *l << '\n'); //Function *f = l->getParent()->getParent(); //BasicBlock *b = l->getParent(); //std::map<BasicBlock *, std::set<Instruction*>> reach = getReachingStores(f); //std::set<Instruction*> bReachIn = Utils::mapAtUnsafe(reach, b); //DEBUG_MSG(" numReachingStores:" << bReachIn.size() << '\n'); //if (bReachIn.size() == 0) { // return NULL; //} //else if (bReachIn.size() == 1) { // Instruction *storeIn = *(bReachIn.begin()); // assert(storeIn != NULL && "getPreviousStore: NULL reachable store"); // assert(Utils::getStorePtr(storeIn) != NULL // && "getPreviousStore: storeIn with NULL ptr operand"); // // Check for any killing stores before l // for (Instruction &bbi : *(l->getParent())) { // if (&bbi == l) { // // Reached the target instruction // break; // } // Value *strPtr = Utils::getStorePtr(&bbi); // if (strPtr != NULL && strPtr == Utils::getStorePtr(storeIn)) { // // strPtr kills in incoming store // storeIn = &bbi; // } // } // return storeIn; //} //else { // assert(0 && "getPreviousStore: more than one reaching store"); //} } // Return all the store instructions which reach the entry of each basicblock // in F. // // Memoizes the results based on the functon address. So, this assumes the // function is never modified. static std::map<BasicBlock *, std::set<Instruction *>> getReachingStores(Function *f) { static std::map<Function *, std::map<BasicBlock *, std::set<Instruction *>>> memoizer; DEBUG_MSG("Get reaching stores:" << f->getName() << '\n'); auto memIt = memoizer.find(f); if (memIt != memoizer.end()) { return memIt->second; } // Defininitions reaching the end of a BB std::map <BasicBlock *, std::set<Instruction *>> reachOut; std::map <BasicBlock *, std::set<Instruction *>> reachIn; // Definitions generated by a basicblock std::map <BasicBlock *, std::set<Instruction *>> bb2gen; // Variables overwritten by a basicblock std::map <BasicBlock *, std::set<Value *>> bb2rem; // Initialze all the maps for (BasicBlock &B : *f) { bb2gen[&B] = getGen(&B); bb2rem[&B] = getRemVars(&B); reachOut[&B] = std::set<Instruction*>(); } bool updated = true; while (updated) { updated = false; for (BasicBlock &B : *f) { std::set<Instruction *> curGen = Utils::mapAtUnsafe(bb2gen, &B); std::set<Value *> curRem = Utils::mapAtUnsafe(bb2rem, &B); // The definitions reaching the input to this block is the union of the // output of the predecessors. Iterate over all the preds and find this // union. std::set<Instruction*> curReach; for (auto it = pred_begin(&B), et = pred_end(&B); it != et; ++it) { BasicBlock *pred = *it; std::set<Instruction *> predReachOut = Utils::mapAtUnsafe(reachOut, pred); curReach.insert(predReachOut.begin(), predReachOut.end()); } reachIn[&B] = curReach; // Remove all those things which were killed for (Value *v : curRem) { for (auto it = curReach.begin(), et = curReach.end(); it != et; ++it) { Instruction *curSt = *it; Value *stPtr = Utils::getStorePtr(curSt); assert(stPtr != NULL && "reaching store with NULL pointer arg"); if (v == stPtr) { curReach.erase(it); } } } // Add all those things generated curReach.insert(curGen.begin(), curGen.end()); std::set<Instruction*> oldReach = Utils::mapAtUnsafe(reachOut, &B); if (curReach.size() > oldReach.size()) { updated = true; reachOut[&B] = curReach; } } } // while (updated) memoizer[f] = reachIn; return reachIn; } // Get those stores created in the B static std::set<Instruction *> getGen(BasicBlock *B) { // A map keeping track of which values already have stores associated with // them. std::map<Value *, Instruction *> valToSt; // Assumption: the for loop below goes in order for (Instruction &i : *B) { Value *stPtr = Utils::getStorePtr(&i); if (stPtr != NULL) { // Only maintain the most recent store to each value valToSt[stPtr] = &i; } } // Flatten the map to a set std::set<Instruction*> ret; for (auto it = valToSt.begin(), et = valToSt.end(); it != et; ++it) { ret.insert(it->second); } return ret; } static std::set<Value *> getRemVars(BasicBlock *B) { std::set<Value *> ret; for (Instruction &i : *B) { if (Utils::isSomeStore(&i)) { Value *p = Utils::getStorePtr(&i); assert(p != NULL && "getKilledVars: store w/o ptr operand"); ret.insert(p); } } return ret; } // Return a read-from rule using the two passed strings. Also returns a query // if the read is satisfiable (check if not-rf is SAT) static std::string getReadFromRuleAndQuery(const std::string loader , const std::string storer) { std::string ret = ""; ret += "(rule (rf " + loader + " " + storer + "))\n"; ret += "(query (not-rf " + loader + " " + storer + "))"; return ret; } // Merge the contents of m1 with m2. If they both have Facts for the same // LatticeFact, the facts will be joined ("unioned") together std::map<BasicBlock *, LatticeFact> mergeFactMaps( const std::map<BasicBlock *, LatticeFact> m1 , const std::map<BasicBlock *, LatticeFact> m2) const { // First, make return contain everything in m1 std::map<BasicBlock *, LatticeFact> ret = m1; // Then, merge everything in m2 with the return for (auto i = m2.begin(), ie = m2.end(); i != ie; ++i) { BasicBlock *b = i->first; LatticeFact f = i->second; auto it = ret.find(b); if (it == ret.end()) { // Not found in ret , no need to join ret.emplace(b, f); } else { // Join the two facts LatticeFact otherF = it->second; LatticeFact joinedF = LatticeFact::factJoin(f, otherF); ret.erase(b); ret.emplace(b, joinedF); } } return ret; } // Helper function for analyzeThreadInterf(). // Collapses the map from functions to maps of storeinsts to facts to a map // from storeinsts to lattice facts. Then calls the function performing the // analysis. // This merge can be done because each store instruction is unique. std::map<BasicBlock *, LatticeFact> analyzeThreadInterf( ap_manager_t *man , ap_environment_t *env , Function *f , CallInst *createSite , const std::map<Instruction *, std::vector<Instruction *>> interfs , const std::map<Function *, std::map<Instruction *, LatticeFact>> fInterfs //, std::vector<std::pair<Instruction *, LatticeFact>> &rErrors , std::set<Instruction *> &rErrors , std::map<Instruction *, LatticeFact> &reachableStores , std::map<CallInst *, LatticeFact> &reachThreadCreate , LatticeFact entryFact , const std::set<Instruction *> assertSlice , const std::set<Instruction *> impacted , const std::set<Instruction *> mayImpact , const std::map<Value *, std::string> v2n , z3::context &ctx , Z3_fixedpoint &zfp ) { DEBUG_MSG("[DEBUG] Printing interference map\n"); DEBUG(printFuncInterfMap(fInterfs);); std::map<Instruction *, LatticeFact> storeToInterf = flattenReachStores(fInterfs); return analyzeThreadInterf(man, env, f, createSite, interfs, storeToInterf, rErrors , reachableStores, reachThreadCreate, entryFact, assertSlice, impacted, mayImpact , v2n, ctx, zfp); } // Given a set of interferences from all threads, i.e., that generated on the // current iteration of the analysis, return a map from each load instruction // in the passed function to a vector of StoreInsts it could read from // // In other words, map each load instruction within the passed function // (thread) to every store instruction to the same variable from other // threads // // Note: The LatticeFacts in the inner map of interfs is not actually used // (i.e., interfs could be a map from functions to lists of storeinsts). // // TODO: This cannot handle the same function interfering with itself (i.e., // multiple threads executing the same function) std::map<Instruction *, std::vector<Instruction*>> getInterferingStores( Function *f , const std::map<Function *, std::map<Instruction *, LatticeFact>> rStores , const std::map<Value *, std::string> v2n ) const { DEBUG_MSG("[DEBUG] Getting interfering stores for function: " << f->getName() << '\n'); std::map<Instruction *, std::vector<Instruction*>> ret; for (auto i = rStores.begin(), ie = rStores.end(); i != ie; ++i) { Function *otherF = i->first; if (otherF == f) { // A function cannot interfere with itself (the only case where this // can happen is for unbounded thread instances) continue; } std::map<Instruction *, LatticeFact> currStores = i->second; std::vector<Instruction *> fLoads = getLoads(f); for (Instruction *l : fLoads) { // For each load, find all the stores in the current thread and get // the interfering fact for (auto j = currStores.begin(), je = currStores.end() ; j != je; ++j) { Instruction *s = j->first; if (loadStoreSameVal(s, l)) { DEBUG_MSG("Found intefering store: " << *s << "\nt" << *l << '\n'); Utils::mapInsertToVector(ret, l, s); //LatticeFact sFact = j->second; //mapInsertToVector(ret, l, sFact); } } } } // for (auto ii = rStores.begin() ... ) return ret; } // Given a map of loads to their corresponding interfering stores, remove // those stores which have lower priority than loads std::map<Instruction*, std::vector<Instruction *>> filterPriInterfs( z3::context &ctx , Z3_fixedpoint &zfp , std::map<Instruction *, std::vector<Instruction *>> interfs) const { static std::map<std::pair<Instruction*, Instruction*>, Z3_bool> cache; DEBUG_MSG("Filtering Priority Interferences\n"); // Map from a Load to the vector of interfering stores std::map<Instruction *, std::vector<Instruction *>> ret; #ifdef MK_DEBUG if (interfs.size() == 0) { DEBUG_MSG("No interferences to filter\n"); } #endif for (auto it = interfs.begin(); it != interfs.end(); ++it) { Instruction *curL = it->first; std::vector<Instruction *> stores = it->second; // Pass only stores which have higher priority std::vector<Instruction *> lInterfs; // Issue a query for every load--store pair for (Instruction *st : stores) { // Use cached query result if possible bool queryResult; auto cacheIt = cache.find(std::make_pair(curL, st)); if (cacheIt == cache.end()) { DEBUG_MSG("Priority filter cache miss\n"); //errs() << "Priority filter cache miss\n"; // never seen this pair before queryResult = queryPri(ctx, zfp, curL, st); cache[std::make_pair(curL, st)] = queryResult; } else { DEBUG_MSG("Priority filter cache hit\n"); //errs() << "Priority filter cache hit\n"; queryResult = cacheIt->second; } totalPairs ++; if (queryResult) { // if query is true than it is valid pair lInterfs.push_back(st); } else { filteredPairs ++; /* errs() << "Infeasible load--store from MHB\n"; errs() << "Load: " << *curL << '\n'; errs() << "Load Function: " << curL->getParent()->getParent()->getName() << '\n'; errs() << "Store: " << *st << '\n'; errs() << "Store Function: " << st->getParent()->getParent()->getName() << '\n'; */ DEBUG_MSG("Infeasible load--store from Prioirity\n"); DEBUG_MSG("Load: " << *curL << '\n'); DEBUG_MSG("Load Function: " << curL->getParent()->getParent()->getName() << '\n'); DEBUG_MSG("Store: " << *st << '\n'); DEBUG_MSG("Store Function: " << st->getParent()->getParent()->getName() << '\n'); } } assert(lInterfs.size() <= stores.size()); #ifdef MK_DEBUG if (lInterfs.size() < stores.size()) { DEBUG_MSG("Pruned interferences via priority: " << stores.size() - lInterfs.size() << '\n'); } else { DEBUG_MSG("No interferences pruned via priority\n"); } #endif ret[curL] = lInterfs; } return ret; } // Given a map of loads to their corresponding interfering stores, remove // those stores which must-happen-after the load. These can be removed since // the effect of the store cannot travel backwards in time. These removals // are valid over all interference permutations std::map<Instruction *, std::vector<Instruction *>> filterMHBInterfs( z3::context &ctx , Z3_fixedpoint &zfp , std::map<Instruction *, std::vector<Instruction *>> interfs) const { // Only need to ever check MHB once per load-store pair static std::map<std::pair<Instruction*, Instruction*>, Z3_bool> cache; DEBUG_MSG("Filtering MHB Interferences\n"); // Map from a Load to the vector of interfering stores std::map<Instruction *, std::vector<Instruction *>> ret; #ifdef MK_DEBUG if (interfs.size() == 0) { DEBUG_MSG("No interferences to filter\n"); } #endif for (auto it = interfs.begin(); it != interfs.end(); ++it) { Instruction *curL = it->first; std::vector<Instruction *> stores = it->second; // Interfering stores which do not violate MHB. Will be populated in the // for-loop below std::vector<Instruction *> lInterfs; // Issue a query for every load--store pair for (Instruction *st : stores) { // Use cached query result if possible Z3_bool queryResult; auto cacheIt = cache.find(std::make_pair(curL, st)); if (cacheIt == cache.end()) { DEBUG_MSG("MHB filter cache miss\n"); // never seen this pair before queryResult = queryMHB(ctx, zfp, curL, st); cache[std::make_pair(curL, st)] = queryResult; } else { DEBUG_MSG("MHB filter cache hit\n"); queryResult = cacheIt->second; } if (queryResult == Z3_L_FALSE || queryResult == Z3_L_UNDEF) { // either l may-not-happen before st, or unknown. In both cases, // conservatively assume that the load can read from the store lInterfs.push_back(st); } else { DEBUG_MSG("Infeasible load--store from MHB\n"); DEBUG_MSG("Load: " << *curL << '\n'); DEBUG_MSG("Load Function: " << curL->getParent()->getParent()->getName() << '\n'); DEBUG_MSG("Store: " << *st << '\n'); DEBUG_MSG("Store Function: " << st->getParent()->getParent()->getName() << '\n'); } } assert(lInterfs.size() <= stores.size()); #ifdef MK_DEBUG if (lInterfs.size() < stores.size()) { DEBUG_MSG("Pruned interferences via MHB: " << stores.size() - lInterfs.size() << '\n'); } else { DEBUG_MSG("No interferences pruned via MHB\n"); } #endif ret[curL] = lInterfs; } return ret; } // Combine the inner map of the passed across all functions. std::map<Instruction *, LatticeFact> flattenReachStores( const std::map<Function *, std::map<Instruction *, LatticeFact>> reachStrs ) { std::map<Instruction *, LatticeFact> facts; for (auto i = reachStrs.begin(), ie = reachStrs.end(); i != ie; ++i) { std::map<Instruction *, LatticeFact> cur = i->second; for (auto j = cur.begin(), je = cur.end(); j != je; ++j) { Instruction *s = j->first; // Assumption: Store instructions are unique assert(facts.find(s) == facts.end() && "duplicate store"); facts.emplace(s, j->second); } } return facts; } // Return true if every fact for every storeinst in new is contained in old bool stableStores( const std::map<Function *, std::map<Instruction *, LatticeFact>> oldI , std::map<Function *, std::map<Instruction *, LatticeFact>> newI) { // Since the store instructions are unique (not shared across threads). // we can flatten the results and just work on the combined inner maps std::map<Instruction *, LatticeFact> flatOld = flattenReachStores(oldI); std::map<Instruction *, LatticeFact> flatNew = flattenReachStores(newI); // Check if every fact in new is in old for (auto ni = flatNew.begin(), ne = flatNew.end(); ni != ne; ++ni) { Instruction *s = ni->first; LatticeFact newF = ni->second; auto oi = flatOld.find(s); if (oi == flatOld.end()) { // This means the store was not even reachable in the prior execution // (but, it was reachable in this execution). So, we can stop now since // we have a completely new fact created in new assert(!newF.isBottom() && "reachable bottom fact"); DEBUG_MSG("stableStores(): new fact not in old, returning false\n"); return false; } // Compare the old and new facts else { LatticeFact oldF = oi->second; // If the new fact is definitely larger (strictly greater than) than // the old one, we can stop if (!LatticeFact::areValsEq(newF, oldF) && LatticeFact::areValsGEq(newF, oldF)) { return false; } } } // At this point, we know none of the new facts are *definitively* larger // than the old facts. areValsGEq will return false either in the case of // "no" or "don't know" // TODO: What to do in this case? return true? return true; } // Convience wrapper to analyze a function in the presense of no inteferences std::map<BasicBlock *, LatticeFact> analyzeFuncNoInterf(ap_manager_t *man , ap_environment_t *env //, std::vector<std::pair<Instruction *, LatticeFact>> &rErrors , std::set<Instruction *> &rErrors , std::map<Instruction *, LatticeFact> &reachableStores , std::map<CallInst *, LatticeFact> &reachThreadCreate , LatticeFact entryFact , const std::set<Instruction *> assertSlice , const std::set<Instruction *> impacted , const std::set<Instruction *> mayImpact , const std::map<Value *, std::string> &valToName , Function *f) const { std::map<Instruction *, LatticeFact> empty; return analyzeFunc(man, env, empty, rErrors, reachableStores , reachThreadCreate, assertSlice, impacted, mayImpact , valToName, entryFact, f, false); } // Analyze the passed function. Returns a map from each basicblock in the // function to the stabalized facts at the begining of the block. // // The passed manager and environment are assumed to be initialized. The // environment should at least include every variable in the passed map from // LLVM Values to Apron names. // // The passed vector, rErrors, will be updated with any reachable errors // states and the fact reaching the statement. // // If mergeInterfs is true, then the analysis will simultaneously consider // both any interfering memory state and the state within the thread. This // means, on any load of `x` both the value within the thread for `x` and the // value of `x` in the interference are loaded. std::map<BasicBlock *, LatticeFact> analyzeFunc(ap_manager_t *man , ap_environment_t *env , const std::map<Instruction *, LatticeFact> interf //, std::vector<std::pair<Instruction*, LatticeFact>> &rErrors , std::set<Instruction*> &rErrors , std::map<Instruction *, LatticeFact> &reachableStores , std::map<CallInst *, LatticeFact> &reachThreadCreate , const std::set<Instruction *> assertSlice , const std::set<Instruction *> impacted , const std::set<Instruction *> mayImpact , const std::map<Value *, std::string> &valToName , LatticeFact entryFact , Function *f , bool mergeInterfs) const { assert(f && "analyzeFunc: null passed"); if (f->begin() == f->end()) { errs() << "[ERROR] function has no body\n"; exit(EXIT_FAILURE); } // The worklist. It is a map from a basicblock to the new facts reaching // the block. A map is used so that if multiple predecessors of a // basicblock add items to the worklist they can be met. In this way, the // predecessors of a BasicBlock do not need to be explicitly found. std::map<BasicBlock *, LatticeFact> worklist; // Bottom and top facts used in initialization ap_abstract1_t factBot = ap_abstract1_bottom(man, env); ap_abstract1_t factTop = ap_abstract1_top(man, env); LatticeFact latBot = LatticeFact(&factBot); LatticeFact latTop = LatticeFact(&factTop); // The current state of the analysis. // This is the facts at the begining of each basicblock. // If a key is not in the map it is assumed to be an error. // The initial state is passed by the user std::map<BasicBlock *, LatticeFact> analState = initBBs(latBot, f); //Module *M = f->getParent(); //LatticeFact initFact = getInitState(M, latTop, valToName); // get the first basic block BasicBlock &firstBb = *(f->begin()); worklist.emplace(&firstBb, entryFact); while (worklist.size()) { try { DEBUG_MSG("New worklist iteration, size: " << worklist.size() << '\n'); // Iterator to first item in the list auto it = worklist.begin(); auto cur = *it; worklist.erase(it); BasicBlock *curBb = cur.first; LatticeFact newFact = cur.second; DEBUG_MSG("[DEBUG] analyzing block: " << *curBb << '\n'); LatticeFact oldFact = analState.at(curBb); DEBUG_MSG(" Incomming Fact: "); DEBUG(newFact.fprint(stderr);); DEBUG_MSG(" Old Fact: "); DEBUG(oldFact.fprint(stderr);); DEBUG_MSG(" new leq old? " << newFact.leq(oldFact) << '\n'); // If the new fact is the same size or smaller than the old one // then we can stop. // It should never really be smaller (assuming the transfer // functions are monotonicly increasing). if (newFact.leq(oldFact)) { continue; } // If the new fact is bigger, save it in the analysis state // Note: the end fact of each block is not saved // (but, it can be recovered by just running the // transfer function over the input fact) analState.erase(curBb); analState.emplace(curBb, newFact); std::vector<std::pair<BasicBlock*, LatticeFact> > outFacts = BBOps::run_transfer_funcs(curBb, newFact, interf, rErrors , reachableStores, reachThreadCreate, assertSlice , impacted, mayImpact, valToName, noCombinsG); // Combine the outfacts of the just analyzed block with any in the // worklist //worklist = merge_worklist(worklist, outFacts); merge_worklist(&worklist, outFacts); } catch (const std::out_of_range &oor) { errs() << "[ERROR] item not found in analysis state\n"; assert(0 && "see above"); exit(EXIT_FAILURE); } } // Cleanup the initial abstract value ap_abstract1_clear(man, &factBot); ap_abstract1_clear(man, &factTop); return analState; } // Add the "dom" relation and it's transitive property. void addDomRel(z3::context &ctx, Z3_fixedpoint &zfp) { // Create dominance relation z3::func_decl domDecl = getDomFuncDecl(ctx); Z3_fixedpoint_register_relation(ctx, zfp, domDecl); // Create post-dominance relation z3::func_decl postDomDecl = getPostDomFuncDecl(ctx); Z3_fixedpoint_register_relation(ctx, zfp, postDomDecl); addTransRuleBVBV(ctx, zfp, domDecl, Z3_BV_SIZE); addTransRuleBVBV(ctx, zfp, postDomDecl, Z3_BV_SIZE); } // And relations indicating a certain instruction is either a load or store void addLoadStoreRels(z3::context &ctx, Z3_fixedpoint &zfp) { // Store relation: (st s v): store s loads value v z3::func_decl stDecl = getStFuncDecl(ctx); Z3_fixedpoint_register_relation(ctx, zfp, stDecl); // Load relation z3::func_decl ldDecl = getLdFuncDecl(ctx); Z3_fixedpoint_register_relation(ctx, zfp, ldDecl); } // Add MHB relation void addMHBRel(z3::context &ctx, Z3_fixedpoint &zfp) { z3::func_decl mhbDecl = getMHBFuncDecl(ctx); Z3_fixedpoint_register_relation(ctx, zfp, mhbDecl); } // Add fence relation void addFenceRel(z3::context &ctx, Z3_fixedpoint &zfp) { z3::func_decl fenceDecl = getFenceFuncDecl(ctx); Z3_fixedpoint_register_relation(ctx, zfp, fenceDecl); } void addLwSyncRel(z3::context &ctx, Z3_fixedpoint &zfp) { z3::func_decl fenceDecl = getFenceFuncDecl(ctx); Z3_fixedpoint_register_relation(ctx, zfp, fenceDecl); } // Add not-reach relation void addNotReachRel(z3::context &ctx, Z3_fixedpoint &zfp) { z3::func_decl nreachRel = getNotReachFuncDecl(ctx); Z3_fixedpoint_register_relation(ctx, zfp, nreachRel); } void addReadsFromRel(z3::context &ctx, Z3_fixedpoint &zfp) { z3::func_decl rf = getReadsFromFuncDecl(ctx); Z3_fixedpoint_register_relation(ctx, zfp, rf); } void addNoReorderRel(z3::context &ctx, Z3_fixedpoint &zfp) { z3::func_decl no = getNoReorderFuncDecl(ctx); Z3_fixedpoint_register_relation(ctx, zfp, no); } void addNotReadsFromRel(z3::context &ctx, Z3_fixedpoint &zfp) { z3::func_decl nrf = getNotReadsFromFuncDecl(ctx); Z3_fixedpoint_register_relation(ctx, zfp, nrf); } // Add MHB edges from creation site to child // // Currently, this requires that all the pthread_create sites have explicit // function arguments. void addCreateFacts(Module &M, z3::context &ctx, Z3_fixedpoint &zfp) { for (Function &F : M) { for (BasicBlock &B : F) { for (Instruction &I : B) { CallInst *ci = dyn_cast<CallInst>(&I); if (ci == NULL) { continue; } Function *called = ci->getCalledFunction(); if (called->getName() != "pthread_create") { continue; } // Found pthread_create. The 2nd argument (zero indexed) is the // function being called Value *v = ci->getArgOperand(2); if (Function *tFunc = dyn_cast<Function>(v)) { // Make sure the function has a body if (tFunc->empty()) { errs() << "[WARNING] thread function without body\n"; continue; } // The pthread_create site must happen before the first instruction // in the function //addMHBFact(ctx, zfp, ci, &tFunc->front().front()); addMHBFact(ctx, zfp, ci , getFirstLoadStoreCallTerm(&tFunc->front())); addCreateStoreLoadFacts(ctx, zfp, ci, tFunc); addThreadLocalNotRead(ctx, zfp, ci, tFunc); } else { errs() << "[ERROR] pthread_create with non function 2nd arg\n"; errs() << *v << '\n'; exit(EXIT_FAILURE); } } // for (Instruction &I : B) } // for (BasicBlock &B : F) } // for (Function &F : M) } // Any store instruction which must ocurr before a thread's creation cannot // be read by this thread. // // If the store before the thread's creation can propagate to the thread, // then its value will be in the initial environment of the thread // // ci is assumed to be the pthread_create call creating tFunc void addCreateStoreLoadFacts(z3::context &ctx, Z3_fixedpoint &zfp , CallInst *ci, Function *tFunc) { std::vector<Instruction*> lds = getLoads(tFunc); for (Instruction *l : lds) { addStoreCreateLoadFact(ctx, zfp, ci, l); } } // Add: (=> (and (is-store s _) (mhb s ci)) (nrf s l)) void addStoreCreateLoadFact(z3::context &ctx, Z3_fixedpoint &zfp , CallInst *ci, Instruction *l) { assert(Utils::isSomeLoad(l)); z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE); z3::expr s = z3::expr(ctx, Z3_mk_bound(ctx, 0, bvSort)); z3::expr v = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort)); z3::expr ciExp = getValueBVID(ctx, ci); z3::expr lExp = getValueBVID(ctx, l); z3::expr args[2] = {s, v}; z3::expr isStoreS = getStFuncDecl(ctx)(2, args); args[0] = s; args[1] = ciExp; z3::expr mhbSCi = getMHBFuncDecl(ctx)(2, args); args[0] = s; args[1] = lExp; z3::expr nrfSL = getNotReadsFromFuncDecl(ctx)(2, args); // (and (is-store s v) (mhb s ci)) z3::expr andSMHB = isStoreS && mhbSCi; Z3_fixedpoint_add_rule(ctx, zfp, z3::implies(andSMHB, nrfSL), NULL); } // Add the "pri" and "higher" relation and it's transitive property void addPriHighRel(z3::context &ctx, Z3_fixedpoint &zfp) { // Create (function-decl pri (number)) z3::func_decl priDecl = getPriFuncDecl(ctx); Z3_fixedpoint_register_relation(ctx, zfp, priDecl); // add priority related rules addPriRule(ctx, zfp, priDecl, Z3_BV_SIZE); // Create (function-decl higher (number number)) z3::func_decl highDecl = getHighFuncDecl(ctx); Z3_fixedpoint_register_relation(ctx, zfp, highDecl); // add higher related rules addHighRule(ctx, zfp, priDecl, highDecl, Z3_BV_SIZE); // add higher transitive rules addTransRuleBVBV(ctx, zfp, highDecl, Z3_BV_SIZE); // Create (function-decl lineHigh (lineNum lineNum)) z3::func_decl lineHighDecl = getLineHighFuncDecl(ctx); Z3_fixedpoint_register_relation(ctx, zfp, lineHighDecl); // Create (function-decl linePri (lineNum Priority)) z3::func_decl linePriDecl = getLinePriFuncDecl(ctx); Z3_fixedpoint_register_relation(ctx, zfp, linePriDecl); // Build rules for linehigh inference z3::func_decl ldDecl = getLdFuncDecl(ctx); z3::func_decl stDecl = getStFuncDecl(ctx); addLineHighRule(ctx, zfp, ldDecl, stDecl, highDecl, linePriDecl, lineHighDecl, Z3_BV_SIZE); // Create (function-decl compLd (lineNum)) z3::func_decl compLdDecl = getCompLdFuncDecl(ctx); Z3_fixedpoint_register_relation(ctx, zfp, compLdDecl); // Create (function-decl nonLastSt (lineNum)) z3::func_decl nonLastStDecl = getNonLastStFuncDecl(ctx); Z3_fixedpoint_register_relation(ctx, zfp, nonLastStDecl); // Build rules for compLd and nonLastSt inferences z3::func_decl domDecl = getDomFuncDecl(ctx); z3::func_decl postDomDecl = getPostDomFuncDecl(ctx); addCombRule(ctx , zfp , ldDecl , stDecl , domDecl , postDomDecl , compLdDecl , nonLastStDecl , Z3_BV_SIZE); } // Update the context and fixedpoint to contain dominance relation, rules, // and facts, and also relations and facts about instructions being // loads/stores void addDomLoadStoreFacts(std::set<Function*> threadFuncs , z3::context &ctx , Z3_fixedpoint &zfp) { addDomRel(ctx, zfp); addLoadStoreRels(ctx, zfp); if (usePriG) { addPriHighRel(ctx, zfp); } // read priority info file and save priority information std::map<std::string, std::string> priorityInfo; if (usePriG) { std::ifstream file("priority.info"); std::string line; while(std::getline(file, line)) { std::stringstream linestream(line); std::string data; std::string val1; // read up-to the first tab (discard tab). std::getline(linestream, data, ':'); // Read the integers using the operator >> linestream >> val1; //errs() << data << ":::" << val1 << "\n"; priorityInfo.insert( std::pair<std::string, std::string> (data, val1)); } } for (Function *f : threadFuncs) { unsigned priority; if (usePriG) { // get priority information std::string name = f->getName(); //errs() << "function: " << name << "\n"; if (name.compare("main") == 0) { // for the main function priority is just 1 priority = 1; } else { priority = std::stoi(priorityInfo.find(f->getName().str())->second); } } //DominatorTree &dt = getAnalysis<DominatorTreeWrapperPass>(*f).getDomTree(); DominatorTree dt = DominatorTree(*f); PostDominatorTree pdt; pdt.runOnFunction(*f); // The first instruction of the thread may have a happens-before edge // from the parent-thread. So, connect this first instruction (which may // not be a load/store) to a load/store/terminator so that transitive // orderings can be calculated /* Instruction *first = &f->front().front(); Instruction *lst = getFirstLoadStoreCallTerm(&f->front()); if (first != lst) { addDomFact(ctx, zfp, first, lst); addPostDomFact(ctx, zfp, lst, first); } */ for (BasicBlock &b : *f) { // add internal dom facts of read/write/call // inside of each basic block addInternalDomAndPostDomFacts(&b, ctx, zfp); if (usePriG) { addLoadStoreFacts(&b, ctx, zfp, priority); } else { addLoadStoreFacts(&b, ctx, zfp); } // for dominator tree DomTreeNodeBase<BasicBlock> *bbNode = dt.getNode(&b); if (bbNode != NULL) { // For the dom children of `b`, // connect the terminator of `b` to the // first relevant (load, store, terminator) instruction // in the child Instruction *from = b.getTerminator(); const std::vector<DomTreeNodeBase<BasicBlock> *> &children = bbNode->getChildren(); for (size_t i = 0; i < children.size(); ++i) { BasicBlock *c = children[i]->getBlock(); // check assertion Instruction *t = &(c->front()); if (CallInst *ci = dyn_cast<CallInst>(t)) { // Chungha: This is a modification to support // post-dominance relation for assert. // Since assert makes branches so that the instruction // after the branch can't post-dominate the instruction // before the branch. Therefore, I forcely insert it. if (ci->getCalledFunction()->getName() == "__assert_fail") { BasicBlock *c2 = children[i+1]->getBlock(); Instruction *postFrom = getFirstLoadStoreCallTerm(c2); /* errs() << "PostFrom!!!\n"; errs() << *postFrom; errs() << "PostTo!!!\n"; errs() << *from; errs() << "\n"; */ addPostDomFact(ctx, zfp, postFrom, from); } } Instruction *to = getFirstLoadStoreCallTerm(c); addDomFact(ctx, zfp, from, to); } } // for post dominator tree DomTreeNodeBase<BasicBlock> *btNode = pdt.getNode(&b); if (btNode != NULL) { // For the post dom children of `b` // connect the first call/read/write of `b` to the // last instruction in the child Instruction *from = getFirstLoadStoreCallTerm(&b); const std::vector<DomTreeNodeBase<BasicBlock> *> &children = btNode->getChildren(); for (size_t i = 0; i < children.size(); ++i) { BasicBlock *c = children[i]->getBlock(); //Instruction *to = getFirstLoadStoreCallTerm(c); Instruction *to = c->getTerminator(); addPostDomFact(ctx, zfp, from, to); } } } // for (BasicBlock &b : *f) } // for (Function f : threadFuncs) } // Validate the set parameters. This will crash the program on errors void validateParams(z3::context &ctx, Z3_fixedpoint &zfp, z3::params &params) { DEBUG_MSG("checking parameters\n"); Z3_param_descrs p_desc = Z3_fixedpoint_get_param_descrs(ctx, zfp); Z3_param_descrs_inc_ref(ctx, p_desc); Z3_params_validate(ctx, params, p_desc); try { ctx.check_error(); } catch (z3::exception ex) { errs() << "[ERROR] Parameter error: " << ex.msg() << '\n'; Z3_param_descrs_dec_ref(ctx, p_desc); exit(EXIT_FAILURE); } Z3_param_descrs_dec_ref(ctx, p_desc); } // Add facts about fence instructions in the program. This also will add a // definition of the fence relation (see addFenceRel()). void addFenceFacts(std::set<Function*> threadFuncs , z3::context &ctx , Z3_fixedpoint &zfp) { addFenceRel(ctx, zfp); addLwSyncRel(ctx, zfp); for (Function *f : threadFuncs) { for (BasicBlock &b : *f) { for (Instruction &i : b) { if (isFence(&i)) { addFenceFact(ctx, zfp, &i); } if (isLwSync(&i)) { // TODO: how to handle lwsync //addLwSyncFact(ctx, zfp, &i); addFenceFact(ctx, zfp, &i); } } } } } // Return true if the passed instruction is a POWER lwsync // // An lwsync preserves everything but write--read order bool isLwSync(Instruction *i) { if (CallInst *ci = dyn_cast<CallInst>(i)) { // TSO/PSO fence if (ci->getCalledFunction()->getName() == "MLWSYNC") { return true; } } return false; } // Return true if the passed instruction operates as a fence or is an // explicit fence. The programmer can add in explicit fences via a call to a // function named MFENCE. bool isFence(Instruction *i) { if (CallInst *ci = dyn_cast<CallInst>(i)) { // TSO/PSO fence if (ci->getCalledFunction()->getName() == "MFENCE") { return true; } // PPC/ARM full fence if (ci->getCalledFunction()->getName() == "MSYNC") { return true; } else { // No other call instructions are treated as fences return false; } } else if (isa<AtomicRMWInst>(i)) { return true; } else if (isa<AtomicCmpXchgInst>(i)) { return true; } else { // TODO: probably some other instructions to handle as fences return false; } } bool runOnModule(Module &M) { manG = Utils::getManager(); ap_manager_set_abort_if_exception(manG, AP_EXC_TIMEOUT, true); ap_manager_set_abort_if_exception(manG, AP_EXC_OUT_OF_SPACE, true); ap_manager_set_abort_if_exception(manG, AP_EXC_OVERFLOW, true); ap_manager_set_abort_if_exception(manG, AP_EXC_INVALID_ARGUMENT, true); ap_manager_set_abort_if_exception(manG, AP_EXC_NOT_IMPLEMENTED, true); ap_manager_set_abort_if_exception(manG, AP_EXC_SIZE, true); // Maps from a Value to a name and vice-versa. // // These are used since Apron requires variables to have names std::map<Value *, std::string> valToName; std::map<std::string, Value *> nameToVal; DEBUG_MSG("[DEBUG] Starting WorklistAI\n"); checkCommandLineArgs(); // Initialize fixpoint solver z3::config cfg; //Z3_set_param_value(cfg, "DL_DEFAULT_RELATION", "smt_relation2"); z3::context ctx(cfg); Z3_fixedpoint zfp = Z3_mk_fixedpoint(ctx); Z3_fixedpoint_inc_ref(ctx, zfp); z3::params params(ctx); params.set("engine", ctx.str_symbol("datalog")); params.set("datalog.default_table", ctx.str_symbol("hashtable")); params.set("datalog.magic_sets_for_queries", true); DEBUG_MSG("params:\n" << Z3_fixedpoint_get_help(ctx, zfp)); DEBUG_MSG("Set Parameters:\n"); DEBUG_MSG(Z3_params_to_string(ctx, params) << '\n'); validateParams(ctx, zfp, params); ap_manager_t* man = Utils::getManager(); ap_environment_t *env = createEnvironment(valToName, nameToVal, M); DEBUG(printValToNameStderr(valToName);); // Try to find the main function Function *main = getMainFuncOrNULL(M); if (main == NULL) { // TODO: the user should be able to specify the entry of the analysis errs() << "[ERROR] main function not found\n"; exit(EXIT_FAILURE); } // try to find any threads std::set<Function *> threadFuncs = getThreads(M); std::vector<CallInst *> threadSites = getThreadCreate(M); // If there are no threads, then this is a single threaded analysis bool noThreads = threadSites.size() == 0; //threadFuncs.insert(main); // This also addes priority and higher information addDomLoadStoreFacts(threadFuncs, ctx, zfp); addMHBRel(ctx, zfp); if (useConstraintsG || filterMHB) { DEBUG_MSG("adding constraints: number of threads: " << threadFuncs.size() << '\n'); if (tsoConstrG || psoConstrG || rmoConstrG) { addFenceFacts(threadFuncs, ctx, zfp); } addCreateFacts(M, ctx, zfp); addJoinFacts(M, ctx, zfp); addNotReachableFacts(M, ctx, zfp); if (tsoConstrG) { //addTSOPruningRules(ctx, zfp); addNoReorderRules(ctx, zfp); addTSOReorderRules(ctx, zfp); // TODO: is reads-from MHB? addReadsFromIsMHB(ctx, zfp); } else if (psoConstrG) { //addPSOPruningRules(ctx, zfp); addNoReorderRules(ctx, zfp); addPSOReorderRules(ctx, zfp); // TODO: is reads-from MHB? addReadsFromIsMHB(ctx, zfp); } else if (rmoConstrG) { addNoReorderRules(ctx, zfp); addRMOReorderRules(ctx, zfp); // TODO: is reads-from MHB? addReadsFromIsMHB(ctx, zfp); } else { addPruningRules(ctx, zfp); // TODO: is reads-from MHB? addReadsFromIsMHB(ctx, zfp); //addNoReorderRules(ctx, zfp); //addSCReorderRules(ctx, zfp); } } std::string rules = Z3_fixedpoint_to_string(ctx, zfp, 0, NULL); errs() << "Rules: " << rules << '\n'; DEBUG_MSG("Rules: " << rules << '\n';); // This is kind of a hack: NULL in threadSites indicates main (there is not // CallSite for main) threadSites.push_back(NULL); // When using constraints, we start the analysis of the main thread and // check the reachability of any thread creation sites. If any are // reachable, then they are subsequently analyzed. // This is a little bit roundabout since we are clearing the vectors. if (dynInitG) { threadFuncs.clear(); threadSites.clear(); threadFuncs.insert(main); threadSites.push_back(NULL); } std::set<Instruction *> assertSlice = getAssertSliceInvIfEnabled(M); std::set<Instruction *> impacted = getImpactedIfEnabled(M); std::set<Instruction *> mayImpact = getMayImpactIfEnabled(M); // Vector containing reachable error states //std::vector<std::pair<Instruction *, LatticeFact>> rErrors; std::set<Instruction *> rErrors; // Repeatedly analyze the main function and any threads until the // interferences (facts at stores in threads) stabalize std::map<Function *, std::map<Instruction *, LatticeFact>> allReachStores; // Map from a Function (thread) to a map from each of its Loads to the // vector of all interfering store instructions from other threads. std::map<Function *, std::map<Instruction *, std::vector<Instruction *>>> interfs; std::map<Function *, std::map<BasicBlock *, LatticeFact>> threadRes; // The inital state of the thread being analyzed ap_abstract1_t factTop = ap_abstract1_top(man, env); LatticeFact latTop = LatticeFact(&factTop); LatticeFact progInitState = getInitState(&M, latTop, valToName); ap_abstract1_clear(man, &factTop); // A map saving the entry fact for a thread. This is only used when // dynamic thread initialization in enabled std::map<CallInst *, LatticeFact> threadEntryFacts; bool stable; size_t iter = 1; do { errs() << "Interference Iteration: " << iter << '\n'; // The reachable stores for this round of the analysis. // We save this in a new map so we can compare it with // the results of the previous analysis (allReachStores). // If the facts stabalize, then we can stop. std::map<Function *, std::map<Instruction *, LatticeFact>> newReachStores = allReachStores; // This deque contains the thread functions which still need to be // processed for this interference iteration. A deque is used because // when constraints are used the threads are processed as they are // reached. In other words, the threads to processed is increasing if a // new thread creation site is reached std::deque<CallInst *> threadsToProcess; // Note: when dynInitG is enabled then threadSites only contains main. // This means that each iteration starts analyzing main // and then analyzes the children of main recursively. threadsToProcess.insert(threadsToProcess.end(), threadSites.begin() , threadSites.end()); assert(threadsToProcess.size() == threadSites.size()); size_t tCount = 0; // only here for output while (threadsToProcess.size()) { errs() << "Analyzing thread: " << tCount++ << '\n'; // ci is the CallInst of the pthread_create() creating the thread. CallInst *ci = threadsToProcess.front(); threadsToProcess.pop_front(); Function *f = NULL; if (ci == NULL) { // NULL is a special callsite indicating main f = main; } else { f = getPThreadThreadFunc(ci); } LatticeFact entryFact = progInitState; #if 0 if (dynInitG) { // If we are dynamically calculating the entry state of // each thread, then we retrieve the entry fact here. // Otherwise, the entry fact is simply initialized to be // the initial state of the program if (ci != NULL) { entryFact = Utils::mapAtUnsafe(threadEntryFacts, ci); } } #endif // Subset of all interferences. // Only those which could affect this thread. std::map<Instruction *, std::vector<Instruction *>> curFInterf = interfs[f]; curFInterf = filterMHBInterfs(ctx, zfp, curFInterf); if (usePriG) { curFInterf = filterPriInterfs(ctx, zfp, curFInterf); } // A map of reachable thread creations in `f`. // This is used to determine other threads which should be analyzed std::map<CallInst *, LatticeFact> reachThreadCreate; // Analyze function in the presense of interferences std::map<Instruction *, LatticeFact> newStores; std::map<BasicBlock *, LatticeFact> res = analyzeThreadInterf(man , env , f , ci , curFInterf , newReachStores , rErrors , newStores , reachThreadCreate , entryFact , assertSlice , impacted , mayImpact , valToName , ctx , zfp); threadRes[f] = res; // Save the reachable stores for this iteration. We can erase all the // old ones since the reachable stores are monotonic (on iteration i+1 // we at least reach all the stores of iteration i) auto fit = newReachStores.find(f); if (fit != newReachStores.end()) { newReachStores.erase(fit); } newReachStores.emplace(f, newStores); #if 0 if (dynInitG) { // When calculating the initial state dynamically, we are calculating // the threads to explore on-the-fly. Any reachable pthread_create // call at this point needs to be analyzed during this iteration. // Note: the facts at each callinstruction are "forgotten" on each // iteration. However, the facts at the callsites are increasing // (potentially) since the interferences on the stores are // increasing. for (auto rci = reachThreadCreate.begin() , rce = reachThreadCreate.end(); rci != rce; ++ rci) { // Get the entry fact for the thread CallInst *curCall = rci->first; LatticeFact callFact = rci->second; Function *thrdFunc = getPThreadThreadFunc(curCall); DEBUG_MSG("[DEBUG] Found new thread: " << thrdFunc->getName() << '\n'); // This function is now saved as being one of the threads we are // analyzing threadFuncs.insert(thrdFunc); // Add the most recent fact to the entry point. Note: we do not // support threads executing the same function auto old = threadEntryFacts.find(curCall); if (old != threadEntryFacts.end()) { threadEntryFacts.erase(old); } threadEntryFacts.emplace(curCall, callFact); // Add the thread to be processed threadsToProcess.push_back(curCall); } } #endif } // If there are no threads, even if the main() thread has interferences // they will not do anything since main does not interfer with itself // (the analysis will finish after a useless 2nd iteration) if (noThreads) { break; } stable = stableStores(allReachStores, newReachStores); DEBUG_MSG("Iteration " << iter << ":\n"); DEBUG_MSG("Previous reachable stores:\n"); DEBUG(printStoreFacts(allReachStores);); DEBUG_MSG("\nNew reachable stores:\n"); DEBUG(printStoreFacts(newReachStores);); // Setup the data for the next iteration. This only needs to be done if // the results have not yet stabalized. // We calculate the new interferences and save the reachable facts at // store instructions if (!stable) { // Calculate the interferences to be used for each thread // to be used in the next round of the analysis. // This uses the reachable stores caluclated for each thread // in the previous for-loop. for (Function *f : threadFuncs) { std::map<Instruction *, std::vector<Instruction *>> interfStores; interfStores = getInterferingStores(f, newReachStores, valToName); // Remove those loads which are not the slice, those can read // arbitrary values without affecting property reachability if (assertSliceG || impactG) { for (auto it = interfStores.begin(), ie = interfStores.end() ; it != ie; ++it) { // assertSlice contains those statements *not* // on the slice. // So, if it is found in the assertSlice structure // then the statement must not be on the slice. // So, its interference can be removed. // TODO: for some reason performing this removal // causes some false alarms?? // These should be mutually exclusive so as // not to double erase if (assertSliceG && assertSlice.count(it->first)) { interfStores.erase(it); } else if (impactG && !mayImpact.count(it->first) && !impacted.count(it->first)) { interfStores.erase(it); } //else if (impactG && !impacted.count(it->first)) { // interfStores.erase(it); //} } } interfs[f] = interfStores; } allReachStores = newReachStores; } iter++; } while (!stable); //std::map<BasicBlock *, LatticeFact> mainRes = threadRes[main]; //errs() << "==== Main Results ====\n"; //printFactMapStderr(mainRes); //errs() << "======================\n"; // Print out the map from values to apron names so the results can be // interpreted printValToNameStderr(valToName); for (auto i = threadRes.begin(), ie = threadRes.end(); i != ie; ++i) { Function *f = i->first; std::string fname = f->getName(); errs() << "==== " << fname << "() Results ====\n"; std::map<BasicBlock *, LatticeFact> res = i->second; printFactMapStderr(res); errs() << "======================\n"; } z3_fp_helpers::valueCacheToMetadata(M, Z3_BV_SIZE); // The errors are counted by the number of unique reachable error // statements. If the statement is reachable multiple times (i.e., on // multiple iterations) it is only counted once. //std::set<Instruction *> errInsts; //for (auto i : rErrors) { // errInsts.insert(i.first); //} //errs() << "Errors found: " << errInsts.size() << '\n'; errs() << "Errors found: " << rErrors.size() << '\n'; errs() << "Max Permutations: " << maxCombPermsG << '\n'; errs() << "Total pairs: " << totalPairs << '\n'; errs() << "Filtered pairs: " << filteredPairs << '\n'; // cleanup the environment (Going Green (tm)) ap_environment_free(env); // Cleanup Z3 stuff Z3_fixedpoint_dec_ref(ctx, zfp); // The IR was modified with metadata only, but still modified return true; } // Join all the facts at the vector of stores for each load into a single // fact std::map<Instruction *, LatticeFact> joinInterfs( const std::map<Instruction *, std::vector<Instruction *>> l2Ss , const std::map<Instruction *, LatticeFact> sToF ) const { std::map<Instruction *, LatticeFact> joined; for (auto i = l2Ss.begin(), ie = l2Ss.end(); i != ie; ++i) { Instruction *l = i->first; std::vector<Instruction *> ss = i->second; if (!ss.size()) { continue; } assert(ss.size() && "load with zero interfering stores"); LatticeFact lfact = Utils::mapAtUnsafe(sToF, ss[0]); for (size_t j = 1; j < ss.size(); ++j) { Instruction *s = ss[j]; LatticeFact nextF = Utils::mapAtUnsafe(sToF, s); lfact = LatticeFact::factJoin(lfact, nextF); } assert(joined.find(l) == joined.end() && "duplicate load"); joined.emplace(l, lfact); } return joined; } // Print the contents of the passed interference map void printStoreFacts( std::map<Function *, std::map<Instruction *, LatticeFact>> ints) const { for (auto ii = ints.begin(), ie = ints.end(); ii != ie; ++ii) { Function *f = ii->first; errs() << "Interferences for Function: " << f->getName() << '\n'; std::map<Instruction *, LatticeFact> fInts = ii->second; for (auto fi = fInts.begin(), fe = fInts.end(); fi != fe; ++fi) { const Instruction *si = fi->first; LatticeFact f = fi->second; errs() << "\tStoreInst: " << *si << "\n\tFact: "; f.fprint(stderr); } } } void addLoadStoreFacts(BasicBlock *b, z3::context &ctx, Z3_fixedpoint &zfp) { for (auto i = b->begin(), ie = b->end(); i != ie; ++i) { Instruction *cur = &*i; if (LoadInst *l = dyn_cast<LoadInst>(cur)) { Value *ptrOp = l->getPointerOperand(); addLoadFact(ctx, zfp, l, ptrOp); } else if (StoreInst *s = dyn_cast<StoreInst>(cur)) { Value *ptrOp = s->getPointerOperand(); addStoreFact(ctx, zfp, s, ptrOp); } } } void addLoadStoreFacts(BasicBlock *b, z3::context &ctx, Z3_fixedpoint &zfp, unsigned priority) { z3::func_decl linePriDecl = getLinePriFuncDecl(ctx); for (auto i = b->begin(), ie = b->end(); i != ie; ++i) { Instruction *cur = &*i; if (LoadInst *l = dyn_cast<LoadInst>(cur)) { Value *ptrOp = l->getPointerOperand(); addLoadFact(ctx, zfp, l, ptrOp); // add linepri fact for each load addLinePriFact(ctx, zfp, linePriDecl, l, priority); } else if (StoreInst *s = dyn_cast<StoreInst>(cur)) { Value *ptrOp = s->getPointerOperand(); addStoreFact(ctx, zfp, s, ptrOp); // add linepri fact for each store addLinePriFact(ctx, zfp, linePriDecl, s, priority); } } } // Search for any pthread_join calls and add must-happen-before constraints; // see the overloaded version of this function void addJoinFacts(Module &M, z3::context &ctx, Z3_fixedpoint &zfp) { for (Function &F : M) { for (BasicBlock &BB : F) { for (Instruction &I : BB) { CallInst *ci = dyn_cast<CallInst>(&I); if (ci != NULL) { if (ci->getCalledFunction()->getName() == "pthread_join") { addJoinFacts(ci, ctx, zfp); } } } // for (Instruciton ...) } // for (BasicBlock ...) } // for (Function ...) } // Search for pthread_join() calls and add the happens-before fact that the // thread must terminate before the join. // // This performs the following: // 1. Check if the instruction is a pthread_join call // 2. Attempt to find the pthread_create call where the thread ID is used // 3. If found, return a happens-before fact // Otherwise, return an emptry string // // Note: this makes a few assumptions // 1. The pthread_t associated with the pthread_join() was only used to // create a thread in a single function // 2. The pthread_create() call associated with the passed join is in the // same function // // Point 1 is not explicitly enforced void addJoinFacts(CallInst *i, z3::context &ctx, Z3_fixedpoint &zfp) { // Find the associated thread function assert(i->getNumOperands() >= 1 && "join without operand"); Function *thrdFunc = findCreateFromJoin(i->getOperand(0)); if (thrdFunc == NULL) { errs() << "[WARNING] no create matching join: " << *i << '\n'; return; } if (thrdFunc->empty()) { errs() << "[WARNING] empty thread function: " << thrdFunc->getName() << '\n'; return; } // Add happens-before edges from all the return sites of the function to // the join site std::vector<ReturnInst*> rets = getRets(thrdFunc); assert(rets.size() && "function without returns"); for (ReturnInst *r : rets) { // The return must happen before the join addMHBFact(ctx, zfp, r, i); } } // Given a pthread_t argument used in a join call, search the def-use chain // to find where it is used in pthread_create. Return the thread function // create by the pthread_create call. // // Returns NULL if no function was found. // // Note: a program actually could use the same pthread_t in multiple // pthread_create() calls. This function returns the first one found Function* findCreateFromJoin(Value *pt) { assert(pt != NULL); Instruction *i = dyn_cast<Instruction>(pt); // This iteratively follows the defs of pt backwards until a // pthread_create() is found // This assumes the only things on the use-def chain are instructions if (i != NULL) { DEBUG_MSG("[DEBUG] Found pthread_t from instruction\n"); } else { errs() << "[WARNING] Unhandled pthread_t def: " << *pt << '\n'; return NULL; } // A vector of Values is used since, in general, the use-def chains can // contain any value and not just instructions std::vector<Value *> toVisit; toVisit.push_back(i); while (toVisit.size()) { Instruction *i = dyn_cast<Instruction>(toVisit.back()); toVisit.pop_back(); if (i == NULL) { errs() << "[ERROR] non instruction value on use-def chain: " << *toVisit.back() << '\n'; exit(EXIT_FAILURE); } // Check if the visited instruciton is a call to pthread_create. If it // is, assume that we are done. // Note: is there ever a case where the join argument is data dependent if (CallInst *ci = dyn_cast<CallInst>(i)) { if (ci->getCalledFunction()->getName() == "pthread_create") { DEBUG_MSG("paired join with create: " << *ci); return getPThreadThreadFunc(ci); } } else if (AllocaInst *ai = dyn_cast<AllocaInst>(i)) { // If we find an alloca, then we've found the site where the pthread_t // was allocated. Search forward from the alloca for the pthread_create // site. return forwardSearchCreate(ai); } else if (LoadInst *li = dyn_cast<LoadInst>(i)) { // Get the defs of the load instruction for (Use &U : li->operands()) { Value *useV = U.get(); toVisit.push_back(useV); } } // TODO: Handle additional types here. Might be able to just blindly // search backwards on all the operands of the instruction else { errs() << "[ERROR] Unahandled instruction type while searching for " << "pthread_create: " << *i << '\n'; DEBUG_MSG("checking isa loadinst\n"); DEBUG_MSG("isa loadinst? " << isa<LoadInst>(i) << '\n'); exit(EXIT_FAILURE); } } // Reach here means we didn't find the create site return NULL; } // Given an alloca instruction allocating a pthread_t, search forward for the // site where the pthread_t is being used. Return the function created by the // pthread_create call // // This returns the first site found Function *forwardSearchCreate(AllocaInst *ai) { std::vector<Instruction *> toVisit; toVisit.push_back(ai); while (toVisit.size()) { Instruction *cur = toVisit.back(); toVisit.pop_back(); for (User *u : cur->users()) { // Check if we've found pthread_create if (CallInst *ci = dyn_cast<CallInst>(u)) { if (ci->getCalledFunction()->getName() == "pthread_create") { DEBUG_MSG("found pthread_create on forward search: " << *ci << '\n'); return getPThreadThreadFunc(ci); } } if (Instruction *i = dyn_cast<Instruction>(u)) { toVisit.push_back(i); } else { errs() << "[ERROR] unhandled User searching forward for " << "pthread_create: " << *u << '\n'; exit(EXIT_FAILURE); } } } // while (toVisit.size()) // Reach here means we did not find pthread_create return NULL; } // Given a Function, return all of its return instructions std::vector<ReturnInst*> getRets(Function *f) { std::vector<ReturnInst*> ret; for (BasicBlock &BB : *f) { for (Instruction &I : BB) { if (ReturnInst *r = dyn_cast<ReturnInst>(&I)) { ret.push_back(r); } } } return ret; } // Starting from `main`, find all the children threads. Using the // happen-before relation caused by thread creation, get those stores which a // thread function must not be able to read from void getNotReadFrom(std::map<Function *, Function*> &child2parent , std::map<Function *, std::vector<Function*>> &parent2child , std::map<Function *, std::vector<StoreInst *>> &notReadFrom , std::map<Function *, CallInst *> &createLocs , Function *main) { // List containing function to be processed. The order the functions are // processed does matter! The parent of a thread must be processed before // the child. This is required because the parent's information needs to be // availible (the things the parent cannot read from) in order to evaluate // the child. std::deque<Function *> worklist; worklist.push_back(main); while (worklist.size()) { // Get and delete the first item Function *curParent = worklist.front(); DEBUG_MSG("[DEBUG] getNotReadFrom: analyzing function: " << curParent->getName() << '\n'); worklist.pop_front(); // Get all the threads created by `f`. These are all the children of `f` std::vector<CallInst *> creats = getThreadCreate(curParent); DEBUG_MSG("\t" << creats.size() << " thread creations\n"); std::vector<Function *> curParentChildren; for (CallInst *ci : creats) { Function *thrdFunc = getPThreadThreadFunc(ci); curParentChildren.push_back(thrdFunc); // This error could be fixed: see the comment above the assertion below assert(createLocs.find(thrdFunc) == createLocs.end() && "thread function created twice"); createLocs.emplace(thrdFunc, ci); // The child of curParent also needs to be processed (we need to find // if it has any children) worklist.push_back(thrdFunc); // In general, we should allow the same function to be created twice. // We could handle this by instead making the child2parent map a map // from a pair of Function * and CallInst: // std::map<std::pair<Function *, CallInst *>, Function*> // In this way, we only require each CallSite to be unique assert(child2parent.find(thrdFunc) == child2parent.end() && "function being created twice"); child2parent.emplace(thrdFunc, curParent); // Get those store's within the thread that cannot be read by this call // instruction std::vector<StoreInst *> mnrl = getThreadLocalNotRead(ci); DEBUG_MSG("\t" << mnrl.size() << " local not-read from\n"); // Get the stores which cannot be read by any ancestors of the parent std::vector<StoreInst *> mnrp = getParentNotRead(ci->getParent()->getParent(), child2parent , notReadFrom); DEBUG_MSG("\t" << mnrp.size() << " parent not-read from\n"); // Merge the results std::vector<StoreInst *> merge; merge.reserve(mnrl.size() + mnrp.size()); merge.insert(merge.end(), mnrl.begin(), mnrl.end()); merge.insert(merge.end(), mnrp.begin(), mnrp.end()); // Update must-not read-from results assert(notReadFrom.find(thrdFunc) == notReadFrom.end() && "function being created twice"); notReadFrom.emplace(thrdFunc, merge); } // for (CallInst *ci : creats) // save the parents children assert(parent2child.find(curParent) == parent2child.end() && "parent visited twice"); parent2child.emplace(curParent, curParentChildren); } } // Given a call instruction `ci`, find those stores within the Function // calling `ci` which must happen-before `ci`. Any store which must happen // before `ci` is not visible to the child thread created by `ci` std::vector<StoreInst *> getThreadLocalNotRead(CallInst *ci) { BasicBlock *ciBB = ci->getParent(); Function *ciF = ci->getParent()->getParent(); // First, get the stores within the basicblock which happen before the // CallInst. These trivially must happen before the callinst std::vector<StoreInst *> ret = getStoresInBBBefore(ci); DEBUG_MSG("[DEBUG] getThreadLocalNotRead(): " "intra-BB happens-before stores: " << ret.size() << '\n'); // Next, get all those stores in basicblock which post dominate `ci`. Since // we just got the stores within the same basicblock as `ci`, we can ignore // the block containing `ci` (any basicblock post-dominates itself). PostDominatorTree &PDT = getAnalysis<PostDominatorTree>(*ciF); SmallVector<BasicBlock *, 10> pdoms; PDT.getDescendants(ciBB, pdoms); for (BasicBlock *b : pdoms) { if (b == ciBB) { // Do not analyze the BasicBlock containing `ci` continue; } std::vector<StoreInst *> bStores = getStores(b); // Add bStores to the end of ret Utils::addVector(ret, bStores); } return ret; } // Given a pthread_create call, find all the stores within the calling thread // much must ocurr before the call. These are not visible to the child thread // unless the value is not overwritten. In that case, the value will be // present in the initial environment of the thread void addThreadLocalNotRead(z3::context &ctx, Z3_fixedpoint &zfp, CallInst *ci , Function *tfunc) { std::vector<StoreInst*> sts = getThreadLocalNotRead(ci); std::vector<Instruction*> ls = getLoads(tfunc); for (StoreInst *s : sts) { for (Instruction *l : ls) { addNotReadFact(ctx, zfp, l, s); } } } // Return the StoreInsts which ocurr before `i` within the same basicblock as // `i`. std::vector<StoreInst *> getStoresInBBBefore(Instruction *i) { BasicBlock *b = i->getParent(); std::vector<StoreInst *> ret; for (auto bi = b->begin(), be = b->end(); bi != be; ++bi) { Instruction *cur = &*bi; if (cur == i) { return ret; } if (StoreInst *si = dyn_cast<StoreInst>(cur)) { ret.push_back(si); } } // Reaching this point means `i` was not found in its own basicblock. This // should never happen! assert(0 && "passed instruction not found"); } // Given a function `f`, get all the stores which the parents of `f` cannot // read from. Transitively, `f` can also not read from these stores std::vector<StoreInst *> getParentNotRead(Function *f , std::map<Function*, Function*> child2parent , std::map<Function *, std::vector<StoreInst *>> notReadFrom) { std::vector<StoreInst *> ret; std::vector<Function *> parents = getParents(f, child2parent); for (Function *par : parents) { auto nri = notReadFrom.find(par); if (nri != notReadFrom.end()) { std::vector<StoreInst *> nr = nri->second; ret.insert(ret.end(), nr.begin(), nr.end()); } } return ret; } // Given a child thread, follow the child2parent map and return all the // parents of `child` (i.e., its creater, its creater's creater, and so on) std::vector<Function *> getParents(Function *child , const std::map<Function *, Function*> child2parent) const { std::vector<Function *> ret; auto iter = child2parent.find(child); while (iter != child2parent.end()) { Function *parent = iter->second; ret.push_back(parent); // Find the parent of `parent` iter = child2parent.find(parent); } return ret; } // Return the first instruction in the passed function. If the function is // external (i.e., we do not have the source code, return NULL. Instruction *getFirstInst(Function *f) { if (f->begin() == f->end()) { // No basicblocks return NULL; } auto ii = f->begin()->begin(); Instruction *ret = &*ii; return ret; } // Return the function being created in a thread by the passed call // instruction. It is assumed the call instruction is a pthread_create call. // // Otherwise, this will crash. Function *getPThreadThreadFunc(CallInst *ci) { Value *v = ci->getArgOperand(2); if (Function *tFunc = dyn_cast<Function>(v)) { return tFunc; } else { errs() << "[ERROR] pthread_create with non function 2nd arg\n"; errs() << *v << '\n'; exit(EXIT_FAILURE); } } std::set<BasicBlock *> getAllBBs(Function *F) { std::set<BasicBlock *> ret; for (BasicBlock &B : *F) { ret.insert(&B); } return ret; } // Update fixedpoint and context to contain not-reachable information void addNotReachableFacts(Module &M, z3::context &ctx, Z3_fixedpoint &zfp) { addNotReachRel(ctx, zfp); for (Function &F : M) { std::set<BasicBlock*> allBBs = getAllBBs(&F); std::map<BasicBlock *, std::set<BasicBlock*>> reachMap; reachMap = getReachability(&F); for (BasicBlock &B : F) { auto it = reachMap.find(&B); assert(it != reachMap.end()); std::set<BasicBlock *> reach = it->second; if (reach.find(&B) != reach.end()) { DEBUG_MSG("Self reachable basicblock\n"); } // At most there will be allBBs.size() items in the result std::vector<BasicBlock*> notReach(allBBs.size()); // allBbs - reach // i.e., the not reachable BBs auto nrIt = set_difference(allBBs.begin() , allBBs.end() , reach.begin() , reach.end() , notReach.begin()); // Resize notReach to remove any of the non-used slots notReach.resize(nrIt - notReach.begin()); for (BasicBlock *notReachB : notReach) { // Every instruyction in B cannot reach notReachB for (Instruction &BI : B) { if (!isaStoreLoadCallOrTerm(&BI)) { continue; } for (Instruction &nrBI : *notReachB) { if (!isaStoreLoadCallOrTerm(&nrBI)) { continue; } addNotReachFact(ctx, zfp, &BI, &nrBI); } } } } } } // Return true if the passed instruction is a StoreInst, LoadInst, or // TerminatorInst bool isaStoreLoadCallOrTerm(Instruction *I) const { if (isa<StoreInst>(I)) { return true; } else if (isa<LoadInst>(I)) { return true; } else if (isa<TerminatorInst>(I)) { return true; } else if (isa<CallInst>(I)) { return true; } else { return false; } } std::map<BasicBlock *, std::set<BasicBlock*>> getReachability(Function *F) { std::map<BasicBlock *, std::set<BasicBlock*>> ret; for (BasicBlock &B : *F) { ret.emplace(&B, forwardDfs(&B)); } return ret; } // Return all the basicblocks forwardly reachable from `b` // // This only includes `b`in the return if there exists a path from `b` to // `b`. std::set<BasicBlock *> forwardDfs(BasicBlock *b) { std::set<BasicBlock*> ret; std::set<BasicBlock*> visited; std::vector<BasicBlock*> s; // Do not add `b` to ret unless there is a path from `b` to `b`. // To do this, initialize the stack with the successors std::vector<BasicBlock*> bSuccs = getSuccsFromBB(b); s.insert(s.end(), bSuccs.begin(), bSuccs.end()); while (!s.empty()) { BasicBlock *cur = s.back(); s.pop_back(); if (visited.find(cur) == visited.end()) { visited.insert(cur); if (cur == b) { DEBUG_MSG("self-reachable basicblock: " << b->front() << '\n'); } ret.insert(cur); std::vector<BasicBlock*> curSuccs = getSuccsFromBB(cur); s.insert(s.end(), curSuccs.begin(), curSuccs.end()); } } if (ret.find(b) != ret.end()) { DEBUG_MSG("basicblock can reach itself\n"); } return ret; } std::vector<BasicBlock*> getSuccsFromBB(BasicBlock *B) { std::vector<BasicBlock *> ret; TerminatorInst *ti = B->getTerminator(); assert(ti && "malformed basic block"); for (size_t i = 0; i < ti->getNumSuccessors(); ++i) { ret.push_back(ti->getSuccessor(i)); } return ret; } // Return a const bitvector ID for the passed instruction. // // This uses the address of the instruction; LLVM guarantees this is unique. // // The size of the bitvector is the size of the pointer-type (e.g., // sizeof(uintptr_t)) z3::expr getValueBVID(z3::context &ctx, Value *v) const { return getValueBVIDSz(ctx, v, Z3_BV_SIZE); } // get function declaration of ld relation z3::func_decl getLdFuncDecl(z3::context &ctx) const { return getBVBVFuncDecl(ctx, "ld"); } // get function declarion of st relation z3::func_decl getStFuncDecl(z3::context &ctx) { return getBVBVFuncDecl(ctx, "st"); } z3::func_decl getMHBFuncDecl(z3::context &ctx) const { return getBVBVFuncDecl(ctx, "mhb"); } z3::func_decl getNoReorderFuncDecl(z3::context &ctx) const { return getBVBVFuncDecl(ctx, "noreorder"); } z3::func_decl getFenceFuncDecl(z3::context &ctx) const { return getBVFuncDecl(ctx, "fence"); } z3::func_decl getLwSyncFuncDecl(z3::context &ctx) const { return getBVFuncDecl(ctx, "lwsync"); } // Return func_decl of dominance relation z3::func_decl getDomFuncDecl(z3::context &ctx) const { return getBVBVFuncDecl(ctx, "dom"); } // Return func_decl of post dominance relation z3::func_decl getPostDomFuncDecl(z3::context &ctx) const { return getBVBVFuncDecl(ctx, "postDom"); } // Return func_decl of priority z3::func_decl getPriFuncDecl(z3::context &ctx) const { return getBVFuncDecl(ctx, "pri"); } // Return func_decl of higher z3::func_decl getHighFuncDecl(z3::context &ctx) const { return getBVBVFuncDecl(ctx, "higher"); } // Return func_decl of lineHigh z3::func_decl getLineHighFuncDecl(z3::context &ctx) const { return getBVBVFuncDecl(ctx, "linehigh"); } // return func_decl of compLoad z3::func_decl getCompLdFuncDecl(z3::context &ctx) const { return getBVFuncDecl(ctx, "compLd"); } // return func_decl of nonLastStore z3::func_decl getNonLastStFuncDecl(z3::context &ctx) const { return getBVFuncDecl(ctx, "nonLastSt"); } // Return func_decl of linePri z3::func_decl getLinePriFuncDecl(z3::context &ctx) const { return getBVBVFuncDecl(ctx, "linepri"); } z3::func_decl getNotReachFuncDecl(z3::context &ctx) const { return getBVBVFuncDecl(ctx, "not-reach"); } z3::func_decl getNotReadsFromFuncDecl(z3::context &ctx) const { return getBVBVFuncDecl(ctx, "not-rf"); } z3::func_decl getReadsFromFuncDecl(z3::context &ctx) const { return getBVBVFuncDecl(ctx, "rf"); } // Given the name of a relation with arguments (bitvector, bitvector) return // its function declaration. z3::func_decl getBVBVFuncDecl(z3::context &ctx, const char *name) const { return z3_fp_helpers::getBVBVFuncDecl(ctx, name, Z3_BV_SIZE); } // Given the name of a relation with arguments (bitvector) return // its function declaration. z3::func_decl getBVFuncDecl(z3::context &ctx, const char *name) const { return z3_fp_helpers::getBVFuncDecl(ctx, name, Z3_BV_SIZE); } void addLinePriFact(z3::context &ctx , Z3_fixedpoint &zfp , z3::func_decl fd , llvm::Instruction *l , unsigned priority) const { addLinePriFactSz(ctx, zfp, fd, l, priority, Z3_BV_SIZE); } void addFact2(z3::context &ctx , Z3_fixedpoint &zfp , z3::func_decl fd , llvm::Value *v1 , llvm::Value *v2) const { addFact2Sz(ctx, zfp, fd, v1, v2, Z3_BV_SIZE); } void addFact1(z3::context &ctx , Z3_fixedpoint &zfp , z3::func_decl fd , llvm::Value *v) const { addFact1Sz(ctx, zfp, fd, v, Z3_BV_SIZE); } // Add a fact that `l` loads `v` void addLoadFact(z3::context &ctx , Z3_fixedpoint &zfp , Instruction *l , Value *v) { addFact2(ctx, zfp, getLdFuncDecl(ctx), l, v); } // Add a fact that `f` is a fence void addFenceFact(z3::context &ctx , Z3_fixedpoint &zfp , Instruction *f) { addFact1(ctx, zfp, getFenceFuncDecl(ctx), f); } void addLwSyncFact(z3::context &ctx , Z3_fixedpoint &zfp , Instruction *f) { addFact1(ctx, zfp, getLwSyncFuncDecl(ctx), f); } // Add (rf l v) void addReadsFromFact(z3::context &ctx , Z3_fixedpoint &zfp , Instruction *l , Value *v) const { assert(Utils::isSomeLoad(l) && "non load reading"); addFact2(ctx, zfp, getReadsFromFuncDecl(ctx), l, v); } // Add a fact that `l` stores `v` void addStoreFact(z3::context &ctx , Z3_fixedpoint &zfp , Instruction *s , Value *v) { addFact2(ctx, zfp, getStFuncDecl(ctx), s, v); } // Add (mhb to from) void addMHBFact(z3::context &ctx, Z3_fixedpoint &zfp, Instruction *from , Instruction *to) { //Z3_ast fromId = getValueBVID(ctx, from); //Z3_ast toId = getValueBVID(ctx, to); //addMHBFact(ctx, zfp, fromId, toId); addFact2(ctx, zfp, getMHBFuncDecl(ctx), from, to); } // Add fact: (dom a b) // Converts to instructions to bitvector ids void addDomFact(z3::context &ctx , Z3_fixedpoint &zfp , Instruction *a , Instruction *b) { addFact2(ctx, zfp, getDomFuncDecl(ctx), a, b); } // Add fact: (dom a b) // Converts to instructions to bitvector ids void addPostDomFact(z3::context &ctx , Z3_fixedpoint &zfp , Instruction *a , Instruction *b) { addFact2(ctx, zfp, getPostDomFuncDecl(ctx), a, b); } // Add fact: (not-read s l) void addNotReadFact(z3::context &ctx , Z3_fixedpoint &zfp , Instruction *s , Instruction *l) { addFact2(ctx, zfp, getNotReadsFromFuncDecl(ctx), s, l); } // Add: (not-reach a b): a cannot reach b void addNotReachFact(z3::context &ctx , Z3_fixedpoint &zfp , Instruction *a , Instruction *b) { addFact2(ctx, zfp, getNotReachFuncDecl(ctx), a, b); } // Return the dominance and post dominance facts // within the basicblock (i.e., the order of instructions in the block). // Since we are only interested in loads and stores, this will ignore all // other instruction types except the basicblock terminator and calls. void addInternalDomAndPostDomFacts(BasicBlock *b, z3::context &ctx, Z3_fixedpoint &zfp) { std::vector<Instruction *> loadsNStores = getLoadStoreCallOrdered(b); loadsNStores.push_back(b->getTerminator()); assert(loadsNStores.size() > 0 && "basicblock with no terminator"); if (loadsNStores.size() == 1) { // With only one instruction (the terminator) there is no internal // dominance facts return; } assert(loadsNStores.size() > 1); Instruction *prev = loadsNStores[0]; for (size_t i = 1; i < loadsNStores.size(); ++i) { Instruction *cur = loadsNStores[i]; // prev dominates cur addDomFact(ctx, zfp, prev, cur); addPostDomFact(ctx, zfp, cur, prev); // Update prev for the next iteration prev = cur; } } // (=> (and (dom a b) (not-reach b a)) (mhb a b)) void addDomNotReachRule(z3::context &ctx, Z3_fixedpoint &zfp) { z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE); //Z3_ast a = Z3_mk_const(ctx, Z3_mk_string_symbol(ctx, "aDom"), bvSort); //Z3_ast b = Z3_mk_const(ctx, Z3_mk_string_symbol(ctx, "bDom"), bvSort); z3::expr a = z3::expr(ctx, Z3_mk_bound(ctx, 0, bvSort)); z3::expr b = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort)); z3::func_decl domDecl = getDomFuncDecl(ctx); z3::func_decl nrDecl = getNotReachFuncDecl(ctx); z3::func_decl mhbDecl = getMHBFuncDecl(ctx); // (dom a b) // (mhb a b) z3::expr args[2] = {a, b}; z3::expr domAB = domDecl(2, args); z3::expr mhbAB = mhbDecl(2, args); // (not-reach b a) args[0] = b; args[1] = a; z3::expr nrBA = nrDecl(2, args); // (and (dom a b) (not-reach b a)) //args[0] = domAB; //args[1] = nrBA; z3::expr domNrAnd = domAB && nrBA; z3::expr imp = z3::implies(domNrAnd, mhbAB); Z3_fixedpoint_add_rule(ctx, zfp, imp, NULL); } // (=> (and (dom a b) (not-reach b a)) (mhb a b)) void addDomNotReachReorderRule(z3::context &ctx, Z3_fixedpoint &zfp) { z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE); //Z3_ast a = Z3_mk_const(ctx, Z3_mk_string_symbol(ctx, "aDom"), bvSort); //Z3_ast b = Z3_mk_const(ctx, Z3_mk_string_symbol(ctx, "bDom"), bvSort); z3::expr a = z3::expr(ctx, Z3_mk_bound(ctx, 0, bvSort)); z3::expr b = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort)); z3::func_decl domDecl = getDomFuncDecl(ctx); z3::func_decl nrDecl = getNotReachFuncDecl(ctx); z3::func_decl mhbDecl = getMHBFuncDecl(ctx); z3::func_decl noReoDecl = getNoReorderFuncDecl(ctx); // (dom a b) // (mhb a b) // (noreorder a b) z3::expr args[2] = {a, b}; z3::expr domAB = domDecl(2, args); z3::expr mhbAB = mhbDecl(2, args); z3::expr noReoAB = noReoDecl(2, args); // (not-reach b a) args[0] = b; args[1] = a; z3::expr nrBA = nrDecl(2, args); // (and (dom a b) (not-reach b a) (noreorder a b)) //args[0] = domAB; //args[1] = nrBA; z3::expr domNrAnd = domAB && nrBA && noReoAB; z3::expr imp = z3::implies(domNrAnd, mhbAB); Z3_fixedpoint_add_rule(ctx, zfp, imp, NULL); } // (=> (and (reads-from l s1) // (mhb s1 s2) // (is-load l v) // (is-store s1 v) // (is-store s2 v)) // (mhb l s2)) void addReadsFromMHB(z3::context &ctx, Z3_fixedpoint &zfp) { z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE); //Z3_ast s1 = Z3_mk_const(ctx, Z3_mk_string_symbol(ctx, "s1"), bvSort); //Z3_ast s2 = Z3_mk_const(ctx, Z3_mk_string_symbol(ctx, "s2"), bvSort); //Z3_ast l = Z3_mk_const(ctx, Z3_mk_string_symbol(ctx, "l"), bvSort); //Z3_ast v = Z3_mk_const(ctx, Z3_mk_string_symbol(ctx, "v"), bvSort); z3::expr s1 = z3::expr(ctx, Z3_mk_bound(ctx, 0, bvSort)); z3::expr s2 = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort)); z3::expr l = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort)); z3::expr v = z3::expr(ctx, Z3_mk_bound(ctx, 3, bvSort)); z3::func_decl mhbDecl = getMHBFuncDecl(ctx); z3::func_decl rfDecl = getReadsFromFuncDecl(ctx); z3::func_decl ldDecl = getLdFuncDecl(ctx); z3::func_decl stDecl = getStFuncDecl(ctx); z3::expr args[2] = {l, s1}; z3::expr rf_l_s1 = rfDecl(2, args); args[0] = s1; args[1] = s2; z3::expr mhb_s1_s2 = mhbDecl(2, args); args[0] = l; args[1] = v; z3::expr ld_l_v = ldDecl(2, args); args[0] = s1; args[1] = v; z3::expr st_s1_v = stDecl(2, args); args[0] = s2; args[1] = v; z3::expr st_s2_v = stDecl(2, args); args[0] = l; args[1] = s2; z3::expr mhb_l_s2 = mhbDecl(2, args); //z3::expr andArgs[5] = {rf_l_s1, mhb_s1_s2, ld_l_v, st_s1_v, st_s2_v}; //z3::expr bigAnd = z3::expr(ctx, Z3_mk_and(ctx, 5, andArgs)); z3::expr bigAnd = rf_l_s1 && mhb_s1_s2 && ld_l_v && st_s1_v && st_s2_v; z3::expr imp = z3::implies(bigAnd, mhb_l_s2); Z3_fixedpoint_add_rule(ctx, zfp, imp, NULL); } // (=> (and (mhb a b) (mhb b c)) // (mhb a c)) void addMHBTrans(z3::context &ctx, Z3_fixedpoint &zfp) { addTransRuleBVBV(ctx, zfp, getMHBFuncDecl(ctx), Z3_BV_SIZE); } // (=> (and (reads-from l1 s1) // (mhb l1 s2) // (mhb s2 l2) // (is-load l1 v) // (is-load l2 v) // (is-store s2 v)) // (not-rf l2 s1)) void addOverwriteNotReads(z3::context &ctx, Z3_fixedpoint &zfp) { z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE); //Z3_ast l1 = Z3_mk_const(ctx, Z3_mk_string_symbol(ctx, "l1"), bvSort); //Z3_ast l2 = Z3_mk_const(ctx, Z3_mk_string_symbol(ctx, "l2"), bvSort); //Z3_ast s1 = Z3_mk_const(ctx, Z3_mk_string_symbol(ctx, "s1"), bvSort); //Z3_ast s2 = Z3_mk_const(ctx, Z3_mk_string_symbol(ctx, "s2"), bvSort); z3::expr l1 = z3::expr(ctx, Z3_mk_bound(ctx, 0, bvSort)); z3::expr l2 = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort)); z3::expr s1 = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort)); z3::expr s2 = z3::expr(ctx, Z3_mk_bound(ctx, 3, bvSort)); z3::expr v = z3::expr(ctx, Z3_mk_bound(ctx, 4, bvSort)); z3::func_decl rfDecl = getReadsFromFuncDecl(ctx); z3::func_decl ldDecl = getLdFuncDecl(ctx); z3::func_decl stDecl = getStFuncDecl(ctx); z3::func_decl mhbDecl = getMHBFuncDecl(ctx); z3::func_decl nrfDecl = getNotReadsFromFuncDecl(ctx); z3::expr args[2] = {l1, s1}; z3::expr rf_l1_s1 = rfDecl(2, args); args[0] = l1; args[1] = s2; z3::expr mhb_l1_s2 = mhbDecl(2, args); args[0] = s2; args[1] = l2; z3::expr mhb_s2_l2 = mhbDecl(2, args); args[0] = l1; args[1] = v; z3::expr ld_l1_v = ldDecl(2, args); args[0] = l2; args[1] = v; z3::expr ld_l2_v = ldDecl(2, args); args[0] = s2; args[1] = v; z3::expr st_s2_v = stDecl(2, args); args[0] = l2; args[1] = s1; z3::expr nrf_l2_s1 = nrfDecl(2, args); //z3::expr andArgs[6] = {rf_l1_s1, mhb_l1_s2, mhb_s2_l2, ld_l1_v, ld_l2_v // , st_s2_v}; //z3::expr bigAnd = z3::expr(ctx, Z3_mk_and(ctx, 6, andArgs)); z3::expr bigAnd = rf_l1_s1 && mhb_l1_s2 && mhb_s2_l2 && ld_l1_v && ld_l2_v && st_s2_v; z3::expr imp = z3::implies(bigAnd, nrf_l2_s1); Z3_fixedpoint_add_rule(ctx, zfp, imp, NULL); } // (=> (mhb a b) (not-rf a b)) void addMHBNotReads(z3::context &ctx, Z3_fixedpoint &zfp) { z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE); //Z3_ast a = Z3_mk_const(ctx, Z3_mk_string_symbol(ctx, "a"), bvSort); //Z3_ast b = Z3_mk_const(ctx, Z3_mk_string_symbol(ctx, "b"), bvSort); z3::expr a = z3::expr(ctx, Z3_mk_bound(ctx, 0, bvSort)); z3::expr b = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort)); z3::expr args[2] = {a, b}; z3::expr mhbAB = getMHBFuncDecl(ctx)(2, args); z3::expr nrfAB = getNotReadsFromFuncDecl(ctx)(2, args); Z3_fixedpoint_add_rule(ctx, zfp, Z3_mk_implies(ctx, mhbAB, nrfAB), NULL); } //// Add a rule sating that reads-from(a, b) ==> MHB(b, a). A write must ocurr //// before a read for it to be witnessed void addMHBNRFRule(z3::context &ctx, Z3_fixedpoint &zfp) const { z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE); z3::expr a = z3::expr(ctx, Z3_mk_bound(ctx, 0, bvSort)); z3::expr b = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort)); z3::expr args[2] = {a, b}; z3::expr rfAB = getReadsFromFuncDecl(ctx)(2, args); args[0] = b; args[1] = a; z3::expr mhbBA = getMHBFuncDecl(ctx)(2, args); Z3_fixedpoint_add_rule(ctx, zfp, Z3_mk_implies(ctx, rfAB, mhbBA), NULL); } // Add rules which can prune interferences: void addPruningRules(z3::context &ctx, Z3_fixedpoint &zfp) { addReadsFromRel(ctx, zfp); addNotReadsFromRel(ctx, zfp); addMHBNRFRule(ctx, zfp); addDomNotReachRule(ctx, zfp); addReadsFromMHB(ctx, zfp); addMHBTrans(ctx, zfp); addMHBNotReads(ctx, zfp); addOverwriteNotReads(ctx, zfp); } void addSCReorderRules(z3::context &ctx, Z3_fixedpoint &zfp) { addNoReorderRel(ctx, zfp); z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE); z3::expr v1 = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort)); z3::expr v2 = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort)); z3::func_decl ldDecl = getLdFuncDecl(ctx); z3::func_decl stDecl = getStFuncDecl(ctx); z3::func_decl fenceDecl = getFenceFuncDecl(ctx); /* Single Variable Rules */ // R(v) -> R(v) addNoReoFunc2Func2(ctx, zfp, ldDecl, ldDecl, v1, v1); // R(v) -> W(v) addNoReoFunc2Func2(ctx, zfp, ldDecl, stDecl, v1, v1); // W(v) -> R(v) addNoReoFunc2Func2(ctx, zfp, stDecl, ldDecl, v1, v1); // W(v) -> W(v) addNoReoFunc2Func2(ctx, zfp, stDecl, stDecl, v1, v1); /* End Single Variable Rules */ /* Double Variables Rules */ // R(v) -> R(v) addNoReoFunc2Func2(ctx, zfp, ldDecl, ldDecl, v1, v2); //// R(v) -> W(v) addNoReoFunc2Func2(ctx, zfp, ldDecl, stDecl, v1, v2); //// W(v) -> R(v) addNoReoFunc2Func2(ctx, zfp, stDecl, ldDecl, v1, v2); //// W(v) -> W(v) addNoReoFunc2Func2(ctx, zfp, stDecl, stDecl, v1, v2); /* End Double Variables Rules */ // Fences dont exist on SC // Fences and all loads/stores are not reordered //addNoReoFunc1Func2(ctx, zfp, fenceDecl, stDecl); //addNoReoFunc1Func2(ctx, zfp, fenceDecl, ldDecl); //addNoReoFunc2Func1(ctx, zfp, stDecl, fenceDecl); //addNoReoFunc2Func1(ctx, zfp, ldDecl, fenceDecl); } void addTSOReorderRules(z3::context &ctx, Z3_fixedpoint &zfp) { addNoReorderRel(ctx, zfp); z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE); z3::expr v1 = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort)); z3::expr v2 = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort)); z3::func_decl ldDecl = getLdFuncDecl(ctx); z3::func_decl stDecl = getStFuncDecl(ctx); z3::func_decl fenceDecl = getFenceFuncDecl(ctx); /////// OLD DEFINITIONS //// Loads can never be reordered with anything subsequent //addNoReoFunc2Func2(ctx, zfp, ldDecl, stDecl, v1, v2); //addNoReoFunc2Func2(ctx, zfp, ldDecl, ldDecl, v1, v2); ////// Nothing can ever drift past a store //addNoReoFunc2Func2(ctx, zfp, ldDecl, stDecl, v1, v2); ////addNoReoFunc2Func2(ctx, zfp, stDecl, stDecl, v1, v2); ////// Store--Load to the same variable cannot be re-ordered //addNoReoFunc2Func2(ctx, zfp, stDecl, ldDecl, v1, v1); ////// Store--Store to any variable cannot be reordered //////////////addNoReoFunc2Func2(ctx, zfp, stDecl, stDecl, v1, v2); //// Fences and all loads/stores are not reordered //addNoReoFunc1Func2(ctx, zfp, fenceDecl, stDecl); //addNoReoFunc1Func2(ctx, zfp, fenceDecl, ldDecl); //addNoReoFunc2Func1(ctx, zfp, stDecl, fenceDecl); //addNoReoFunc2Func1(ctx, zfp, ldDecl, fenceDecl); /////// END OLD DEFINITIONS /* Single Variable Rules */ // R(v) -> R(v) addNoReoFunc2Func2(ctx, zfp, ldDecl, ldDecl, v1, v1); // R(v) -> W(v) addNoReoFunc2Func2(ctx, zfp, ldDecl, stDecl, v1, v1); // W(v) -> R(v) // This rule is not enforced because if it is it prevents store buffer // forwarding //addNoReoFunc2Func2(ctx, zfp, stDecl, ldDecl, v1, v1); // W(v) -> W(v) addNoReoFunc2Func2(ctx, zfp, stDecl, stDecl, v1, v1); /* End Single Variable Rules */ /* Double Variables Rules */ // RMO/PowerPC allow all of these // R(v) -> R(v) addNoReoFunc2Func2(ctx, zfp, ldDecl, ldDecl, v1, v2); //// R(v) -> W(v) addNoReoFunc2Func2(ctx, zfp, ldDecl, stDecl, v1, v2); //// W(v) -> R(v) //addNoReoFunc2Func2(ctx, zfp, stDecl, ldDecl, v1, v2); //// W(v) -> W(v) addNoReoFunc2Func2(ctx, zfp, stDecl, stDecl, v1, v2); /* End Double Variables Rules */ addFenceReorderRules(ctx, zfp); // Fences and all loads/stores are not reordered //addNoReoFunc1Func2(ctx, zfp, fenceDecl, stDecl); //addNoReoFunc1Func2(ctx, zfp, fenceDecl, ldDecl); //addNoReoFunc2Func1(ctx, zfp, stDecl, fenceDecl); //addNoReoFunc2Func1(ctx, zfp, ldDecl, fenceDecl); } void addRMOReorderRules(z3::context &ctx, Z3_fixedpoint &zfp) { addNoReorderRel(ctx, zfp); z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE); z3::expr v1 = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort)); z3::expr v2 = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort)); z3::func_decl ldDecl = getLdFuncDecl(ctx); z3::func_decl stDecl = getStFuncDecl(ctx); /* Single Variable Rules */ // R(v) -> R(v) addNoReoFunc2Func2(ctx, zfp, ldDecl, ldDecl, v1, v1); // R(v) -> W(v) addNoReoFunc2Func2(ctx, zfp, ldDecl, stDecl, v1, v1); // W(v) -> R(v) //addNoReoFunc2Func2(ctx, zfp, stDecl, ldDecl, v1, v1); // W(v) -> W(v) addNoReoFunc2Func2(ctx, zfp, stDecl, stDecl, v1, v1); /* End Single Variable Rules */ /* Double Variables Rules */ // RMO/PowerPC allow all of these // R(v) -> R(v) //addNoReoFunc2Func2(ctx, zfp, ldDecl, ldDecl, v1, v2); //// R(v) -> W(v) //addNoReoFunc2Func2(ctx, zfp, ldDecl, stDecl, v1, v2); //// W(v) -> R(v) //addNoReoFunc2Func2(ctx, zfp, stDecl, ldDecl, v1, v2); //// W(v) -> W(v) //addNoReoFunc2Func2(ctx, zfp, stDecl, stDecl, v1, v2); /* End Double Variables Rules */ addFenceReorderRules(ctx, zfp); //z3::func_decl lwDecl = getLwSyncFuncDecl(ctx); //addNoReoFunc1Func2(ctx, zfp, lwDecl, stDecl); //addNoReoFunc1Func2(ctx, zfp, lwDecl, ldDecl); //addNoReoFunc2Func1(ctx, zfp, stDecl, lwDecl); //addNoReoFunc2Func1(ctx, zfp, ldDecl, lwDecl); // Fences and all loads/stores are not reordered //addNoReoFunc1Func2(ctx, zfp, fenceDecl, stDecl); //addNoReoFunc1Func2(ctx, zfp, fenceDecl, ldDecl); //addNoReoFunc2Func1(ctx, zfp, stDecl, fenceDecl); //addNoReoFunc2Func1(ctx, zfp, ldDecl, fenceDecl); } // Common reordering rules involving fences. void addFenceReorderRules(z3::context &ctx, Z3_fixedpoint &zfp) { z3::func_decl ldDecl = getLdFuncDecl(ctx); z3::func_decl stDecl = getStFuncDecl(ctx); z3::func_decl fenceDecl = getFenceFuncDecl(ctx); //z3::func_decl lwDecl = getLwSyncFuncDecl(ctx); addNoReoFunc1Func2(ctx, zfp, fenceDecl, stDecl); addNoReoFunc1Func2(ctx, zfp, fenceDecl, ldDecl); addNoReoFunc2Func1(ctx, zfp, stDecl, fenceDecl); addNoReoFunc2Func1(ctx, zfp, ldDecl, fenceDecl); // lwsync preserves everything but write-lwsync--read order //addNoReoFunc1Func2(ctx, zfp, lwDecl, stDecl); //addNoReoFunc1Func2(ctx, zfp, lwDecl, ldDecl); //addNoReoFunc2Func1(ctx, zfp, stDecl, lwDecl); //addNoReoFunc2Func1(ctx, zfp, ldDecl, lwDecl); } void addNoReorderRules(z3::context &ctx, Z3_fixedpoint &zfp) { addReadsFromRel(ctx, zfp); addNotReadsFromRel(ctx, zfp); addDomNotReachReorderRule(ctx, zfp); addMHBNRFRule(ctx, zfp); addReadsFromMHB(ctx, zfp); addMHBTrans(ctx, zfp); addMHBNotReads(ctx, zfp); addOverwriteNotReads(ctx, zfp); } void addPSOReorderRules(z3::context &ctx, Z3_fixedpoint &zfp) { addNoReorderRel(ctx, zfp); z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE); z3::expr v1 = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort)); z3::expr v2 = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort)); z3::func_decl ldDecl = getLdFuncDecl(ctx); z3::func_decl stDecl = getStFuncDecl(ctx); //z3::func_decl fenceDecl = getFenceFuncDecl(ctx); /////// OLD DEFINITIONS // //// Loads can never be reordered with anything subsequent //addNoReoFunc2Func2(ctx, zfp, ldDecl, stDecl, v1, v2); //addNoReoFunc2Func2(ctx, zfp, ldDecl, ldDecl, v1, v2); //// Store--Load to the same variable cannot be re-ordered //addNoReoFunc2Func2(ctx, zfp, stDecl, ldDecl, v1, v1); //// Store--Store to the same variable cannot be reordered ////addNoReoFunc2Func2(ctx, zfp, stDecl, stDecl, v1, v1); //// Fences and all loads/stores are not reordered //addNoReoFunc1Func2(ctx, zfp, fenceDecl, stDecl); //addNoReoFunc1Func2(ctx, zfp, fenceDecl, ldDecl); //addNoReoFunc2Func1(ctx, zfp, stDecl, fenceDecl); //addNoReoFunc2Func1(ctx, zfp, ldDecl, fenceDecl); /* Single Variable Rules */ // R(v) -> R(v) addNoReoFunc2Func2(ctx, zfp, ldDecl, ldDecl, v1, v1); // R(v) -> W(v) addNoReoFunc2Func2(ctx, zfp, ldDecl, stDecl, v1, v1); // W(v) -> R(v) // This rule is not enforced because if it is it prevents store buffer // forwarding //addNoReoFunc2Func2(ctx, zfp, stDecl, ldDecl, v1, v1); // W(v) -> W(v) addNoReoFunc2Func2(ctx, zfp, stDecl, stDecl, v1, v1); /* End Single Variable Rules */ /* Double Variables Rules */ // RMO/PowerPC allow all of these // R(v) -> R(v) addNoReoFunc2Func2(ctx, zfp, ldDecl, ldDecl, v1, v2); //// R(v) -> W(v) addNoReoFunc2Func2(ctx, zfp, ldDecl, stDecl, v1, v2); //// W(v) -> R(v) //addNoReoFunc2Func2(ctx, zfp, stDecl, ldDecl, v1, v2); //// W(v) -> W(v) //addNoReoFunc2Func2(ctx, zfp, stDecl, stDecl, v1, v2); /* End Double Variables Rules */ addFenceReorderRules(ctx, zfp); // Fences and all loads/stores are not reordered //addNoReoFunc1Func2(ctx, zfp, fenceDecl, stDecl); //addNoReoFunc1Func2(ctx, zfp, fenceDecl, ldDecl); //addNoReoFunc2Func1(ctx, zfp, stDecl, fenceDecl); //addNoReoFunc2Func1(ctx, zfp, ldDecl, fenceDecl); } void addTSOPruningRules(z3::context &ctx, Z3_fixedpoint &zfp) { addReadsFromRel(ctx, zfp); addNotReadsFromRel(ctx, zfp); // General Rules addMHBNRFRule(ctx, zfp); addReadsFromMHB(ctx, zfp); addMHBTrans(ctx, zfp); addMHBNotReads(ctx, zfp); addOverwriteNotReads(ctx, zfp); // MHB Rules addDomStoreStoreTSO(ctx, zfp); addLoadStoreMHB(ctx, zfp); addStoreLoadMHB(ctx, zfp); addLoadLoadMHB(ctx, zfp); // Fence Rules addPOLoadStoreFence(ctx, zfp); } void addPSOPruningRules(z3::context &ctx, Z3_fixedpoint &zfp) { addReadsFromRel(ctx, zfp); addNotReadsFromRel(ctx, zfp); // General Rules addMHBNRFRule(ctx, zfp); addReadsFromMHB(ctx, zfp); addMHBTrans(ctx, zfp); addMHBNotReads(ctx, zfp); addOverwriteNotReads(ctx, zfp); // MHB Rules addDomStoreStorePSO(ctx, zfp); addLoadStoreMHB(ctx, zfp); addStoreLoadMHB(ctx, zfp); addLoadLoadMHB(ctx, zfp); // Fence Rules addPOLoadStoreFence(ctx, zfp); } // Add ordering of loads/stores before/after a fence void addPOLoadStoreFence(z3::context &ctx, Z3_fixedpoint &zfp) { addDomFenceFunc2(ctx, zfp, getLdFuncDecl(ctx)); addDomFenceFunc2(ctx, zfp, getStFuncDecl(ctx)); addDomFunc2Fence(ctx, zfp, getLdFuncDecl(ctx)); addDomFunc2Fence(ctx, zfp, getStFuncDecl(ctx)); } // Add: // (=> (and (dom a b) // (not-reach b a) // (is-fence a) // (fd b v) ) // (mhb a b)) // // where fd is the passed func_decl void addDomFenceFunc2(z3::context &ctx, Z3_fixedpoint &zfp , const z3::func_decl fd) { z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE); z3::expr a = z3::expr(ctx, Z3_mk_bound(ctx, 0, bvSort)); z3::expr b = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort)); z3::expr v = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort)); z3::func_decl domDecl = getDomFuncDecl(ctx); z3::func_decl nrDecl = getNotReachFuncDecl(ctx); z3::func_decl mhbDecl = getMHBFuncDecl(ctx); z3::func_decl fenceDecl = getFenceFuncDecl(ctx); // (dom a b) // (mhb a b) z3::expr args[2] = {a, b}; z3::expr domAB = domDecl(2, args); z3::expr mhbAB = mhbDecl(2, args); // (not-reach b a) args[0] = b; args[1] = a; z3::expr nrBA = nrDecl(2, args); // (is-fence a) args[0] = a; z3::expr fenceA = fenceDecl(1, args); // (fd b v) args[0] = b; args[1] = v; z3::expr fdBV = fd(2, args); z3::expr bigAnd = domAB && nrBA && fenceA && fdBV; z3::expr imp = z3::implies(bigAnd, mhbAB); Z3_fixedpoint_add_rule(ctx, zfp, imp, NULL); } // Add: // (=> (and (dom a b) // (not-reach b a) // (fd a v) // (is-fence b)) // (mhb a b)) // // where fd is the passed func_decl void addDomFunc2Fence(z3::context &ctx, Z3_fixedpoint &zfp , const z3::func_decl fd) { z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE); z3::expr a = z3::expr(ctx, Z3_mk_bound(ctx, 0, bvSort)); z3::expr b = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort)); z3::expr v = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort)); z3::func_decl domDecl = getDomFuncDecl(ctx); z3::func_decl nrDecl = getNotReachFuncDecl(ctx); z3::func_decl mhbDecl = getMHBFuncDecl(ctx); z3::func_decl fenceDecl = getFenceFuncDecl(ctx); // (dom a b) // (mhb a b) z3::expr args[2] = {a, b}; z3::expr domAB = domDecl(2, args); z3::expr mhbAB = mhbDecl(2, args); // (not-reach b a) args[0] = b; args[1] = a; z3::expr nrBA = nrDecl(2, args); // (is-fence b) args[0] = b; z3::expr fenceB = fenceDecl(1, args); // (fd a v) args[0] = a; args[1] = v; z3::expr fdAV = fd(2, args); z3::expr bigAnd = domAB && nrBA && fenceB && fdAV; z3::expr imp = z3::implies(bigAnd, mhbAB); Z3_fixedpoint_add_rule(ctx, zfp, imp, NULL); } // (=> (reads-from b a) (mhb a b)) void addReadsFromIsMHB(z3::context &ctx, Z3_fixedpoint &zfp) { z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE); z3::expr a = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort)); z3::expr b = z3::expr(ctx, Z3_mk_bound(ctx, 3, bvSort)); z3::func_decl rfDecl = getReadsFromFuncDecl(ctx); z3::func_decl mhbDecl = getMHBFuncDecl(ctx); z3::expr argsAB[2] = {a, b}; z3::expr argsBA[2] = {b, a}; z3::expr rf_b_a = rfDecl(2, argsBA); z3::expr mhb_a_b = mhbDecl(2, argsAB); z3::expr imp = z3::implies(rf_b_a, mhb_a_b); Z3_fixedpoint_add_rule(ctx, zfp, imp, NULL); } // (=> (and (dom a b) // (not-reach b a) // (is-store a _) // (is-store b _) ) // (mhb a b)) // // i.e., stores to any variable are ordered on TSO void addDomStoreStoreTSO(z3::context &ctx, Z3_fixedpoint &zfp) { addStoreStoreMHB(ctx, zfp, false); //z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE); //z3::expr a = z3::expr(ctx, Z3_mk_bound(ctx, 0, bvSort)); //z3::expr b = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort)); //z3::expr v1 = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort)); //z3::expr v2 = z3::expr(ctx, Z3_mk_bound(ctx, 3, bvSort)); //z3::func_decl domDecl = getDomFuncDecl(ctx); //z3::func_decl nrDecl = getNotReachFuncDecl(ctx); //z3::func_decl stDecl = getStFuncDecl(ctx); //z3::func_decl mhbDecl = getMHBFuncDecl(ctx); //// (dom a b) //// (mhb a b) //z3::expr args[2] = {a, b}; //z3::expr domAB = domDecl(2, args); //z3::expr mhbAB = mhbDecl(2, args); //// (not-reach b a) //args[0] = b; //args[1] = a; //z3::expr nrBA = nrDecl(2, args); //// (is-store a v1) //// (is-store b v2) //// v1 may or may not equal v2 to satisfy the deduction //args[0] = a; //args[1] = v1; //z3::expr isStAV1 = stDecl(2, args); //args[0] = b; //args[1] = v2; //z3::expr isStBV2 = stDecl(2, args); //// (and (dom a b) //// (not-reach b a) //// (is-store a _) //// (is-store b _)) //z3::expr bigAnd = domAB && nrBA && isStAV1 && isStBV2; //z3::expr imp = z3::implies(bigAnd, mhbAB); //Z3_fixedpoint_add_rule(ctx, zfp, imp, NULL); } // (=> (and (dom a b) // (not-reach b a) // (is-store a v) // (is-store b v) ) // (mhb a b)) // // i.e., stores to the same variable are ordered on TSO void addDomStoreStorePSO(z3::context &ctx, Z3_fixedpoint &zfp) { addStoreStoreMHB(ctx, zfp, true); } // (=> (and (dom a f) // (dom f b) // (fd1 a v1) // (fd2 b v2) // (fd3 f) // )) void addNoReoDomFunc2Func2Func1(z3::context, Z3_fixedpoint &zfp , const z3::func_decl fd1, const z3::func_decl fd2 , const z3::func_decl fd3, const z3::expr v1 , const z3::expr v2, const z3::expr f) { } // (=> (and (fd1 a v1) // (fd2 b v2)) // (noreorder a b) void addNoReoFunc2Func2(z3::context &ctx, Z3_fixedpoint &zfp , const z3::func_decl fd1, const z3::func_decl fd2 , const z3::expr v1, const z3::expr v2) { z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE); z3::expr a = z3::expr(ctx, Z3_mk_bound(ctx, 0, bvSort)); z3::expr b = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort)); z3::func_decl noReoDecl = getNoReorderFuncDecl(ctx); z3::expr args[2] = {a, v1}; z3::expr fd1AV1 = fd1(2, args); args[0] = a; args[1] = b; z3::expr noReo = noReoDecl(2, args); args[0] = b; args[1] = v2; z3::expr fd2BV2 = fd2(2, args); z3::expr bigAnd = fd1AV1 && fd2BV2; z3::expr imp = z3::implies(bigAnd, noReo); Z3_fixedpoint_add_rule(ctx, zfp, imp, NULL); } // (=> (and (fd1 a) // (fd2 b v)) // (noreorder a b) void addNoReoFunc1Func2(z3::context &ctx, Z3_fixedpoint &zfp , const z3::func_decl fd1, const z3::func_decl fd2) { z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE); z3::expr a = z3::expr(ctx, Z3_mk_bound(ctx, 0, bvSort)); z3::expr b = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort)); z3::expr v = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort)); z3::func_decl noReoDecl = getNoReorderFuncDecl(ctx); z3::expr args[2] = {a, v}; z3::expr fd1A = fd1(1, args); // v is not used in args here args[0] = a; args[1] = b; z3::expr noReo = noReoDecl(2, args); args[0] = b; args[1] = v; z3::expr fd2BV = fd2(2, args); z3::expr bigAnd = fd1A && fd2BV; z3::expr imp = z3::implies(bigAnd, noReo); Z3_fixedpoint_add_rule(ctx, zfp, imp, NULL); } // (=> (and (fd1 a v) // (fd2 b)) // (noreorder a b) void addNoReoFunc2Func1(z3::context &ctx, Z3_fixedpoint &zfp , const z3::func_decl fd1, const z3::func_decl fd2) { z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE); z3::expr a = z3::expr(ctx, Z3_mk_bound(ctx, 0, bvSort)); z3::expr b = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort)); z3::expr v = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort)); z3::func_decl noReoDecl = getNoReorderFuncDecl(ctx); z3::expr args[2] = {a, v}; z3::expr fd1AV = fd1(2, args); args[0] = a; args[1] = b; z3::expr noReo = noReoDecl(2, args); args[0] = b; z3::expr fd2B = fd2(1, args); z3::expr bigAnd = fd1AV && fd2B; z3::expr imp = z3::implies(bigAnd, noReo); Z3_fixedpoint_add_rule(ctx, zfp, imp, NULL); } // Order two statements based on program order and restricted based on two // binary predicates with the passed variables as their second item. // (=> (and (dom a b) // (not-reach b a) // (fd1 a v1) // (fd2 b v2) ) // (mhb a b)) void addPOFunc2Func2MHB(z3::context &ctx, Z3_fixedpoint &zfp , const z3::func_decl fd1, const z3::func_decl fd2 , const z3::expr v1, const z3::expr v2) { z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE); z3::expr a = z3::expr(ctx, Z3_mk_bound(ctx, 0, bvSort)); z3::expr b = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort)); z3::func_decl domDecl = getDomFuncDecl(ctx); z3::func_decl nrDecl = getNotReachFuncDecl(ctx); z3::func_decl mhbDecl = getMHBFuncDecl(ctx); // (dom a b) // (mhb a b) z3::expr args[2] = {a, b}; z3::expr domAB = domDecl(2, args); z3::expr mhbAB = mhbDecl(2, args); // (not-reach b a) args[0] = b; args[1] = a; z3::expr nrBA = nrDecl(2, args); // (fd1 a v1) args[0] = a; args[1] = v1; z3::expr fd1AV1 = fd1(2, args); // (fd2 b v2) args[0] = b; args[1] = v2; z3::expr fd2BV2 = fd2(2, args); // (and (dom a b) // (not-reach b a) // (fd1 a v1) // (fs2 b v2)) z3::expr bigAnd = domAB && nrBA && fd1AV1 && fd2BV2; z3::expr imp = z3::implies(bigAnd, mhbAB); Z3_fixedpoint_add_rule(ctx, zfp, imp, NULL); } // Order a store and load based on program-order and if they are to the same // variable // (=> (and (dom a b) // (not-reach b a) // (is-store a v) // (is-load b v)) // (mhb a b)) void addStoreLoadMHB(z3::context &ctx, Z3_fixedpoint &zfp) { z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE); z3::expr v = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort)); addPOFunc2Func2MHB(ctx, zfp, getStFuncDecl(ctx), getLdFuncDecl(ctx), v, v); } // Order a load and store based on program-order and if they are to the same // variable // (=> (and (dom a b) // (not-reach b a) // (is-load a v)) // (is-store b v) // (mhb a b)) void addLoadStoreMHB(z3::context &ctx, Z3_fixedpoint &zfp) { z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE); z3::expr v = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort)); addPOFunc2Func2MHB(ctx, zfp, getLdFuncDecl(ctx), getStFuncDecl(ctx), v, v); } void addLoadLoadMHB(z3::context &ctx, Z3_fixedpoint &zfp) { z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE); z3::expr v = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort)); addPOFunc2Func2MHB(ctx, zfp, getLdFuncDecl(ctx), getLdFuncDecl(ctx), v, v); } // Add an ordering rule between two stores. If sameVar is true then the two // stores are ordered based on the program-order and if they access the same // variable (as on PSO). Otherwise, the stores may access any variable (as on // TSO). // // That is: // // (=> (and (dom a b) // (not-reach b a) // (is-store a v1) // (is-store b v2) ) // (mhb a b)) // // Where v1 = v2 is sameVar is true void addStoreStoreMHB(z3::context &ctx, Z3_fixedpoint &zfp, bool sameVar) { z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE); z3::expr v1 = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort)); z3::expr v2 = v1; if (!sameVar) { v2 = z3::expr(ctx, Z3_mk_bound(ctx, 3, bvSort)); } addPOFunc2Func2MHB(ctx, zfp, getStFuncDecl(ctx), getStFuncDecl(ctx), v1 , v2); //z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE); //z3::expr a = z3::expr(ctx, Z3_mk_bound(ctx, 0, bvSort)); //z3::expr b = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort)); //z3::expr v1 = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort)); // //z3::expr v2 = v1; //if (!sameVar) { // v2 = z3::expr(ctx, Z3_mk_bound(ctx, 3, bvSort)); //} //z3::func_decl domDecl = getDomFuncDecl(ctx); //z3::func_decl nrDecl = getNotReachFuncDecl(ctx); //z3::func_decl stDecl = getStFuncDecl(ctx); //z3::func_decl mhbDecl = getMHBFuncDecl(ctx); //// (dom a b) //// (mhb a b) //z3::expr args[2] = {a, b}; //z3::expr domAB = domDecl(2, args); //z3::expr mhbAB = mhbDecl(2, args); //// (not-reach b a) //args[0] = b; //args[1] = a; //z3::expr nrBA = nrDecl(2, args); //// (is-store a v1) //// (is-store b v2) //args[0] = a; //args[1] = v1; //z3::expr isStAV1 = stDecl(2, args); //args[0] = b; //args[1] = v2; //z3::expr isStBV2 = stDecl(2, args); //// (and (dom a b) //// (not-reach b a) //// (is-store a _) //// (is-store b _)) //z3::expr bigAnd = domAB && nrBA && isStAV1 && isStBV2; //z3::expr imp = z3::implies(bigAnd, mhbAB); //Z3_fixedpoint_add_rule(ctx, zfp, imp, NULL); } // Return the first load, store, or terminator instruction in the basic // block. static Instruction *getFirstLoadStoreTerm(BasicBlock *b) { assert(b && "NULL passed"); for (auto i = b->begin(), ie = b->end(); i != ie; ++i) { Instruction *cur = &*i; if (isa<LoadInst>(cur)) { return cur; } else if (isa<StoreInst>(cur)) { return cur; } } // Reaching this point means the basicblock does not have any load or store // instructions. So, just return the terminator return b->getTerminator(); } static Instruction *getFirstLoadStoreCallTerm(BasicBlock *b) { assert(b && "NULL passed"); for (auto i = b->begin(), ie = b->end(); i != ie; ++i) { Instruction *cur = &*i; if (isa<LoadInst>(cur)) { return cur; } else if (isa<StoreInst>(cur)) { return cur; } else if (isa<CallInst>(cur)) { return cur; } } // Reaching this point means the basicblock does not have // any load or store instructions. So, just return the terminator return b->getTerminator(); } static Instruction *getLastLoadStoreCallTerm(BasicBlock *b) { assert(b && "NULL passed"); bool find = false; Instruction *cur; for (auto i = b->begin(), ie = b->end(); i != ie; ++i) { cur = &*i; if (isa<LoadInst>(cur)) { find = true; } else if (isa<StoreInst>(cur)) { find = true; } else if (isa<CallInst>(cur)) { find = true; } } if (find) { return cur; } else { // Reaching this point means the basicblock does not have // any load or store instructions. So, just return the front one return &(b->front()); } } #if 0 // Given the passed basicblock, return, starting from the first, the loads // and stores in the basicblock static std::vector<Instruction *> getLoadStoreOrdered(BasicBlock *b) { std::vector<Instruction *> ret; for (auto i = b->begin(), ie = b->end(); i != ie; ++i) { Instruction *cur = &*i; if (isa<LoadInst>(cur)) { DEBUG_MSG("[DEBUG] Found Load: " << cur << ": " << *cur << '\n'); ret.push_back(cur); } else if (isa<StoreInst>(cur)) { DEBUG_MSG("[DEBUG] Found Store: " << cur << ": " << *cur << '\n'); ret.push_back(cur); } } return ret; } #endif static std::vector<Instruction *> getLoadStoreCallOrdered(BasicBlock *b) { std::vector<Instruction *> ret; for (auto i = b->begin(), ie = b->end(); i != ie; ++i) { Instruction *cur = &*i; if (isa<LoadInst>(cur)) { DEBUG_MSG("[DEBUG] Found Load: " << cur << ": " << *cur << '\n'); ret.push_back(cur); } else if (isa<StoreInst>(cur)) { DEBUG_MSG("[DEBUG] Found Store: " << cur << ": " << *cur << '\n'); ret.push_back(cur); } else if (isa<CallInst>(cur)) { DEBUG_MSG("[DEBUG] Found Call" << cur << ": " << *cur << '\n'); ret.push_back(cur); //DEBUG_MSG("[DEBUG] Found Store: " << cur << ": " << *cur << '\n'); //ret.push_back(cur); } } return ret; } // Ensure the global command line flags are valid. // This will crash with an error message if they are not void checkCommandLineArgs() const { // Atleast one abstract domain must be true if (!useBoxG && !useOctG && !usePolyG && !useLinEqG) { errs() << "[ERROR] Select an abstract domain (-box, -oct, -pkpoly " << "-pklineq)\n"; exit(EXIT_FAILURE); } // TSO and PSO cannot both be enabled at the same time if (tsoConstrG && psoConstrG) { errs() << "[ERROR] both -pso and -tso cannot be used\n"; exit(EXIT_FAILURE); } // Only one abstract domain should be selected if ((useBoxG && (useOctG || usePolyG || useLinEqG)) || (useOctG && (useBoxG || usePolyG || useLinEqG)) || (usePolyG && (useBoxG || useOctG || useLinEqG)) || (useLinEqG && (useBoxG || useOctG || usePolyG))) { errs() << "[ERROR] More than one abstract domain selected\n"; exit(EXIT_FAILURE); } // The program-order constraint solver is only relevant in combinational // exploration mode if (useConstraintsG && noCombinsG) { errs() << "[ERROR] Constraint solver mode (-constraints) must not use " "-nocombs\n"; exit(EXIT_FAILURE); } // If we are using constraints, we need to know where Z3 lives if (useConstraintsG && (z3BinLocG.size() == 0)) { errs() << "[ERROR] -constraints without specify location of Z3 " "(-z3 <loc>)\n"; exit(EXIT_FAILURE); } // Using constraints also uses dynamic thread init. Note: this is not // strictly necessary. if (useConstraintsG) { dynInitG = true; } } void printFuncInterfMap( const std::map<Function *, std::map<Instruction *, LatticeFact>> fim) const { for (auto i = fim.begin(), ie = fim.end(); i != ie; ++i) { std::map<Instruction *, LatticeFact> stm = i->second; for (auto j = stm.begin(), je = stm.end(); j != je; ++j) { errs() << "Store: " << *(j->first) << '\n'; } } } std::map<StoreInst *, LatticeFact> joinStFacts( const std::map<StoreInst *, LatticeFact> m1 , const std::map<StoreInst *, LatticeFact> m2) const { std::map<StoreInst *, LatticeFact> ret(m1); for (auto i = m2.begin(), ie = m2.end(); i != ie; ++i) { StoreInst *cur = i->first; auto f = ret.find(cur); if (f != ret.end()) { LatticeFact newF = LatticeFact::factJoin(i->second, f->second); ret.erase(cur); ret.emplace(cur, newF); } else { ret.emplace(cur, f->second); } } return ret; } // Return the number of instructions in M unsigned numInstructions(Module &M) { unsigned n = 0; for (auto mit = M.begin(), me = M.end(); mit != me; ++mit) { Function &f = *mit; for (inst_iterator ii = inst_begin(f), ie = inst_end(f); ii != ie ; ++ii) { n++; } } return n; } std::set<Instruction *> instsWithoutMetadata(Module &M, std::string md) { assert(md.length() && "instsWithoutMetadata: length zero metadata"); std::set<Instruction *> ret; return ret; for (auto mit = M.begin(), me = M.end(); mit != me; ++mit) { Function &f = *mit; for (inst_iterator ii = inst_begin(f), ie = inst_end(f); ii != ie ; ++ii) { Instruction *i = &*ii; if (!i->getMetadata(md)) { ret.insert(i); } } } return ret; } std::set<Instruction *> instsWithMetadata(Module &M, std::string md) { assert(md.length() && "instsWithoutMetadata: length zero metadata"); std::set<Instruction *> ret; for (auto mit = M.begin(), me = M.end(); mit != me; ++mit) { Function &f = *mit; for (inst_iterator ii = inst_begin(f), ie = inst_end(f); ii != ie ; ++ii) { Instruction *i = &*ii; if (i->getMetadata(md)) { ret.insert(i); } } } return ret; } // If -impact is used then return the set of all statements in M which may // impact a change. // // Otherwise, return an empty set std::set<Instruction *> getMayImpactIfEnabled(Module &M) { std::set<Instruction *> ret; if (!impactG) { return ret; } ret = instsWithMetadata(M, "MayImpact"); //if (ret.size() == 0) { // errs() << "[ERROR] No may-impact statements found, did you run the change-impact pass?\n"; // exit(EXIT_FAILURE); //} return ret; } // If -impact is used then return the set of all statements in M which are // impacted by a change. // // Otherwise, return an empty set std::set<Instruction *> getImpactedIfEnabled(Module &M) { std::set<Instruction *> ret; if (!impactG) { return ret; } ret = instsWithMetadata(M, "Impacted"); if (ret.size() == 0) { errs() << "[ERROR] No impacted statements found, did you run the change-impact pass?\n"; exit(EXIT_FAILURE); } return ret; } // Return the inversion of the assertion slice if assertSliceG is true. // // The "slice inversion" is all the statements *not* on the slice. // // If assertSliceG is false then return an empty set. std::set<Instruction *> getAssertSliceInvIfEnabled(Module &M) { std::set<Instruction *> ret; unsigned numInsts = numInstructions(M); if (!assertSliceG) { return ret; // size zero } ret = instsWithoutMetadata(M, "AssertSlice"); //for (auto mit = M.begin(), me = M.end(); mit != me; ++mit) { // Function &f = *mit; // for (inst_iterator ii = inst_begin(f), ie = inst_end(f); ii != ie // ; ++ii) { // numInsts++; // Instruction *i = &*ii; // if (!i->getMetadata("AssertSlice")) { // ret.insert(i); // } // } //} //if (!ret.size()) { if (numInsts == ret.size()) { //errs() << "[ERROR] no statements found on slice of an assertion\n" // "Are you sure the PDG pass has been run?\n"; errs() << "[ERROR] no statements not found on slice of an assertion\n" "Are you sure the PDG pass has been run?\n"; exit(EXIT_FAILURE); } return ret; } }; char WorklistAI::ID = 0; static RegisterPass<WorklistAI> X("worklist-ai" , "worklist based abstract interpretation" , false // unmodified CFG , true); // analysis pass
36.560275
104
0.590129
ChunghaSung
41ce91bf7c7e8bf7c72170131baddc803b82c39d
2,122
cpp
C++
src/Private/AnimSceneActions/UpdateEntitiesAction.cpp
heltena/KYEngine
4ccb89d0b20683feb245ffe85dd34b6ffdc42c8e
[ "MIT" ]
null
null
null
src/Private/AnimSceneActions/UpdateEntitiesAction.cpp
heltena/KYEngine
4ccb89d0b20683feb245ffe85dd34b6ffdc42c8e
[ "MIT" ]
null
null
null
src/Private/AnimSceneActions/UpdateEntitiesAction.cpp
heltena/KYEngine
4ccb89d0b20683feb245ffe85dd34b6ffdc42c8e
[ "MIT" ]
null
null
null
#include <KYEngine/Core.h> #include <KYEngine/SceneTimelineInfo.h> #include <KYEngine/Utility/TiXmlHelper.h> #include <KYEngine/Private/AnimSceneActions/UpdateEntitiesAction.h> #include <cmath> #include <iostream> #include <stdexcept> const std::string UpdateEntitiesAction::XML_NODE = "update-entities"; UpdateEntitiesAction::UpdateEntitiesAction() { } UpdateEntitiesAction::~UpdateEntitiesAction() { } UpdateEntitiesAction* UpdateEntitiesAction::readFromXml(TiXmlElement* node) { UpdateEntitiesAction* action = new UpdateEntitiesAction(); const std::string name = TiXmlHelper::readString(node, "name", false, "<<undefined>>"); action->setName(name); TiXmlElement* curr = node->FirstChildElement(); while (curr) { const std::string& value = curr->Value(); if (value == "add-entity") { const std::string entityRef = TiXmlHelper::readString(node, "entity-ref", true); action->addAddEntityRef(entityRef); } else if (value == "remove-entity") { const std::string entityRef = TiXmlHelper::readString(node, "entity-ref", true); action->addRemoveEntityRef(entityRef); } else throw std::runtime_error("UpdateEntitiesAction: (" + name + ") tag error: " + value); curr = curr->NextSiblingElement(); } return action; } void UpdateEntitiesAction::start(SceneTimelineInfo* info) { std::list<Entity*> toAddEntities; std::list<Entity*> toRemoveEntities; for(std::list<std::string>::const_iterator it = m_toAddEntityRef.begin(); it != m_toAddEntityRef.end(); it++) toAddEntities.push_back(Core::resourceManager().entity(*it)); for(std::list<std::string>::const_iterator it = m_toRemoveEntityRef.begin(); it != m_toRemoveEntityRef.end(); it++) toRemoveEntities.push_back(Core::resourceManager().entity(*it)); info->layer()->updateEntities(toAddEntities, toRemoveEntities); } bool UpdateEntitiesAction::isBlocking() { return false; } bool UpdateEntitiesAction::isFinished() { return true; } void UpdateEntitiesAction::update(const double elapsedTime, SceneTimelineInfo* info) { }
29.472222
119
0.707352
heltena
41d5e6fdf17048d5c977d867533b641d3d5b0f2f
1,506
cpp
C++
src/HapticAssetTools.cpp
HardlightVR/HL-haptictools
c177a92ce3adab80416f0e85c1ad89083d9da6b6
[ "MIT" ]
null
null
null
src/HapticAssetTools.cpp
HardlightVR/HL-haptictools
c177a92ce3adab80416f0e85c1ad89083d9da6b6
[ "MIT" ]
null
null
null
src/HapticAssetTools.cpp
HardlightVR/HL-haptictools
c177a92ce3adab80416f0e85c1ad89083d9da6b6
[ "MIT" ]
1
2020-06-29T14:42:24.000Z
2020-06-29T14:42:24.000Z
#include "stdafx.h" #include "HapticAssetTools.h" #include "AssetToolsLibrary.h" #define AS_TYPE(Type, Obj) reinterpret_cast<Type *>(Obj) #define AS_CTYPE(Type, Obj) reinterpret_cast<const Type *>(Obj) unsigned int NS_ASSETTOOLS_API NSAT_GetVersion(void) { return NS_ASSETTOOLS_VERSION; } int NSAT_IsCompatibleDLL(void) { unsigned int major = NSAT_GetVersion() >> 16; return major == NS_ASSETTOOLS_VERSION_MAJOR; } NS_ASSETTOOLS_API NSAT_Context_t * __stdcall NSAT_Create() { return AS_TYPE(NSAT_Context_t, new AssetToolsLibrary()); } NS_ASSETTOOLS_API int __stdcall NSAT_InitializeFromDirectory(NSAT_Context_t* context, const char * dir) { return AS_TYPE(AssetToolsLibrary, context)->InitializeFromDirectory(dir); } NS_ASSETTOOLS_API void __stdcall NSAT_Delete(NSAT_Context_t * context) { if (!context) { return; } delete AS_TYPE(AssetToolsLibrary, context); } NS_ASSETTOOLS_API int __stdcall NSAT_RescanFilesystem(NSAT_Context_t * context) { return AS_TYPE(AssetToolsLibrary, context)->Rescan(); } NS_ASSETTOOLS_API int __stdcall NSAT_CheckIfPackage(NSAT_Context_t* context, const char* dir, PackageInfo& info, bool& isPackage) { return AS_TYPE(AssetToolsLibrary, context)->CheckIfPackage(dir, info, isPackage); } NS_ASSETTOOLS_API char * __stdcall NSAT_GetError(NSAT_Context_t * context) { return AS_TYPE(AssetToolsLibrary, context)->GetError(); } NS_ASSETTOOLS_API void __stdcall NSAT_FreeError(char * stringPointer) { delete[] stringPointer; stringPointer = nullptr; }
23.53125
129
0.790837
HardlightVR
41d621c72ebdc8325cb1780ec683d6060004089d
578
cpp
C++
code/1087 1 10 100 1000.cpp
PIPIKAI/ACM
b8e4416a29c0619946c9b73b0fe5699b6e96e782
[ "MIT" ]
null
null
null
code/1087 1 10 100 1000.cpp
PIPIKAI/ACM
b8e4416a29c0619946c9b73b0fe5699b6e96e782
[ "MIT" ]
null
null
null
code/1087 1 10 100 1000.cpp
PIPIKAI/ACM
b8e4416a29c0619946c9b73b0fe5699b6e96e782
[ "MIT" ]
null
null
null
#include<stdio.h> long long f[1000000]; int main() { int n; long long sum=1,i=0; while(sum<=1000000000) { f[i]=sum; i++; sum+=i; } scanf("%d",&n); for(int i=0;i<n;i++) { int temp; scanf("%d",&temp); for(int j=0;j<=44721;j++) { if(f[j]==temp) { printf("1\n"); break; } if(f[j]>temp) { printf("0\n"); break; } } } return 0; }
15.210526
33
0.313149
PIPIKAI
41d78e97494757744c4c1321b744ac7dea15b3ec
2,771
cpp
C++
plot-test.cpp
kp2pml30/spring-pendulum
abbfdb7d445fc439c0d6006c0de04dc467577c7e
[ "MIT" ]
null
null
null
plot-test.cpp
kp2pml30/spring-pendulum
abbfdb7d445fc439c0d6006c0de04dc467577c7e
[ "MIT" ]
null
null
null
plot-test.cpp
kp2pml30/spring-pendulum
abbfdb7d445fc439c0d6006c0de04dc467577c7e
[ "MIT" ]
null
null
null
#include <GL/glew.h> #include <GLFW/glfw3.h> #include <chrono> #include <iostream> #include <memory> #include <stdexcept> #include <numbers> #include "Solvers.h" using vec2 = mth::vec2<double>; namespace { static constexpr double TO = 4; static constexpr double STEP = 1; void error_callback(int error, char const* description) { std::cerr << "Error : " << description << std::endl; } vec2 Map(vec2 a) { /* * 0, 1 -> -1, -1 * 4, e(4) -> 1, 1 */ a.Y = (a.Y - 1) / (std::exp(TO) - 1) * 2 - 1; a.X = a.X / TO * 2 - 1; return a; } template<typename F> void Draw(F const& f, double d, double U) { { auto f0 = f(0); auto v2 = Map(f(0)); glVertex2f(v2.X, v2.Y); } for (double i = 0; i <= U; i += d) { auto v2 = Map(f(d)); glVertex2f(v2.X, v2.Y); } } double EDelta(double v, double h) { return v; } } int main() { glfwSetErrorCallback(error_callback); if (!glfwInit()) return 1; glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); GLFWwindow* window = glfwCreateWindow(640, 480, "spring pendulum", NULL, NULL); if (!window) { glfwTerminate(); return 1; } glfwMakeContextCurrent(window); glfwSwapInterval(1); if (auto err = glewInit(); err != GLEW_OK) { std::cerr << "glew init error " << glewGetErrorString(err) << std::endl; return 1; } glClearColor(0, 0, 0, 0); glEnable(GL_LINE_WIDTH); while (!glfwWindowShouldClose(window)) { int width, height; glfwGetFramebufferSize(window, &width, &height); glViewport(0, 0, width, height); glClear(GL_COLOR_BUFFER_BIT); glLineWidth(5); glBegin(GL_LINE_STRIP); { glColor3f(1, 1, 1); double cur = 0; Draw([&](double d) { auto r = vec2(cur, std::exp(cur)); cur += d; return r; }, STEP, TO); } glEnd(); glLineWidth(3); glBegin(GL_LINE_STRIP); { glColor3f(0, 1, 0); double cur = 0; double prev = 1; Draw([&](double d) { prev += Euler(EDelta, prev, d); cur += d; auto r = vec2(cur, prev); return r; }, STEP, TO); } glEnd(); glBegin(GL_LINE_STRIP); { glColor3f(1, 0, 0); double cur = 0; double prev = 1; Draw([&](double d) { prev += RungeKutta(EDelta, prev, d); cur += d; auto r = vec2(cur, prev); return r; }, STEP, TO); } glEnd(); glBegin(GL_LINE_STRIP); { glColor3f(0.2, 0.2, 1); double cur = 0; double prev = 1; Draw([&](double d) { prev += Midpoint(EDelta, prev, d); cur += d; auto r = vec2(cur, prev); return r; }, STEP, TO); } glEnd(); glfwSwapBuffers(window); glfwPollEvents(); } glfwDestroyWindow(window); glfwTerminate(); }
17.537975
80
0.568387
kp2pml30
41da1889fcd6a6f0b9e493676c03fa5ab2d3835b
462
cpp
C++
application/pages/modplatform/TechnicPage.cpp
StephenGss/Polycraft-Launcher
d70f6729dba876e0252b075dcfd4c9caa45113b2
[ "Apache-2.0" ]
3
2020-10-08T19:55:33.000Z
2021-11-28T04:02:39.000Z
application/pages/modplatform/TechnicPage.cpp
StephenGss/Polycraft-Launcher
d70f6729dba876e0252b075dcfd4c9caa45113b2
[ "Apache-2.0" ]
null
null
null
application/pages/modplatform/TechnicPage.cpp
StephenGss/Polycraft-Launcher
d70f6729dba876e0252b075dcfd4c9caa45113b2
[ "Apache-2.0" ]
null
null
null
#include "TechnicPage.h" #include "ui_TechnicPage.h" #include "PolycraftLauncher.h" #include "dialogs/NewInstanceDialog.h" TechnicPage::TechnicPage(NewInstanceDialog* dialog, QWidget *parent) : QWidget(parent), ui(new Ui::TechnicPage), dialog(dialog) { ui->setupUi(this); } TechnicPage::~TechnicPage() { delete ui; } bool TechnicPage::shouldDisplay() const { return true; } void TechnicPage::openedImpl() { dialog->setSuggestedPack(); }
17.111111
68
0.718615
StephenGss
41da2a660915e34383118a58e3bb474392502bab
559
cc
C++
rocks-sys/rocks/rate_limiter.cc
sezaru/rust-rocks
06245eedaf91b8358688abefa67eba802b607142
[ "Apache-2.0" ]
40
2017-05-16T06:10:51.000Z
2021-09-02T01:06:37.000Z
rocks-sys/rocks/rate_limiter.cc
sezaru/rust-rocks
06245eedaf91b8358688abefa67eba802b607142
[ "Apache-2.0" ]
12
2017-06-11T09:42:02.000Z
2020-10-11T23:46:31.000Z
rocks-sys/rocks/rate_limiter.cc
sezaru/rust-rocks
06245eedaf91b8358688abefa67eba802b607142
[ "Apache-2.0" ]
8
2017-05-16T03:44:53.000Z
2020-10-11T22:01:17.000Z
#include "rocksdb/rate_limiter.h" #include "rocks/ctypes.hpp" using namespace ROCKSDB_NAMESPACE; using std::shared_ptr; extern "C" { // FIXME: leaks a ointer size rocks_ratelimiter_t* rocks_ratelimiter_create(int64_t rate_bytes_per_sec, int64_t refill_period_us, int32_t fairness) { rocks_ratelimiter_t* rate_limiter = new rocks_ratelimiter_t; rate_limiter->rep.reset(NewGenericRateLimiter(rate_bytes_per_sec, refill_period_us, fairness)); return rate_limiter; } void rocks_ratelimiter_destroy(rocks_ratelimiter_t* limiter) { delete limiter; } }
26.619048
119
0.810376
sezaru
41de11a203843e20f35ac3606529553f96bc13be
10,117
cpp
C++
src/Event.cpp
JeromeOrtali/PureBasic-Engine3D
bc584c6469a15cee4c2c7c1deb5dadfe91595eff
[ "BSD-2-Clause", "Apache-2.0" ]
1
2020-07-26T01:30:45.000Z
2020-07-26T01:30:45.000Z
src/Event.cpp
JeromeOrtali/PureBasic-Engine3D
bc584c6469a15cee4c2c7c1deb5dadfe91595eff
[ "BSD-2-Clause", "Apache-2.0" ]
null
null
null
src/Event.cpp
JeromeOrtali/PureBasic-Engine3D
bc584c6469a15cee4c2c7c1deb5dadfe91595eff
[ "BSD-2-Clause", "Apache-2.0" ]
null
null
null
/* PureBasic Engine3D licence * -------------------------- * * MIT License * * Copyright (c) 2017 Jerome Ortali * * 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 "Event.hpp" /////////////////////////////////////////////////////////////////////////////// // /////////////////////////////////////////////////////////////////////////////// PB_EventHandler::PB_EventHandler(Urho3D::Context* context) : Urho3D::Object(context) { SubscribeToEvent(Urho3D::E_KEYDOWN, URHO3D_HANDLER(PB_EventHandler, ev_KeyDown)); SubscribeToEvent(Urho3D::E_KEYUP, URHO3D_HANDLER(PB_EventHandler, ev_KeyUp)); SubscribeToEvent(Urho3D::E_MOUSEBUTTONDOWN, URHO3D_HANDLER(PB_EventHandler, ev_MouseButtonDown)); SubscribeToEvent(Urho3D::E_MOUSEBUTTONUP, URHO3D_HANDLER(PB_EventHandler, ev_MouseButtonUp)); SubscribeToEvent(Urho3D::E_MOUSEMOVE, URHO3D_HANDLER(PB_EventHandler, ev_MouseMove)); SubscribeToEvent(Urho3D::E_MOUSEWHEEL, URHO3D_HANDLER(PB_EventHandler, ev_MouseWheel)); SubscribeToEvent(Urho3D::E_RESOURCEBACKGROUNDLOADED, URHO3D_HANDLER(PB_EventHandler, ev_BackgroundLoadResource)); SubscribeToEvent(Urho3D::E_FILECHANGED, URHO3D_HANDLER(PB_EventHandler, ev_ResourceFileChange)); attachObserver(this); } /////////////////////////////////////////////////////////////////////////////// // /////////////////////////////////////////////////////////////////////////////// void PB_EventHandler::ev_KeyDown(Urho3D::StringHash eventType, Urho3D::VariantMap& eventData) { Event event; event.type = keyDown; event.key.key = eventData[Urho3D::KeyDown::P_KEY].GetInt(); event.key.scancode = eventData[Urho3D::KeyDown::P_SCANCODE].GetInt(); event.key.buttons = eventData[Urho3D::KeyDown::P_BUTTONS].GetInt(); event.key.qualifiers = eventData[Urho3D::KeyDown::P_QUALIFIERS].GetInt(); event.key.repeat = eventData[Urho3D::KeyDown::P_REPEAT].GetInt(); notifyObservers((int)event.type, &event, sizeof(Event)); PB_EVENT->push(event); } /////////////////////////////////////////////////////////////////////////////// // /////////////////////////////////////////////////////////////////////////////// void PB_EventHandler::ev_KeyUp(Urho3D::StringHash eventType, Urho3D::VariantMap& eventData) { Event event; event.type = keyUp; event.key.key = eventData[Urho3D::KeyUp::P_KEY].GetInt(); event.key.scancode = eventData[Urho3D::KeyUp::P_SCANCODE].GetInt(); event.key.buttons = eventData[Urho3D::KeyUp::P_BUTTONS].GetInt(); event.key.qualifiers = eventData[Urho3D::KeyUp::P_QUALIFIERS].GetInt(); event.key.repeat = 0; notifyObservers((int)event.type, &event, sizeof(Event)); PB_EVENT->push(event); } /////////////////////////////////////////////////////////////////////////////// // /////////////////////////////////////////////////////////////////////////////// void PB_EventHandler::ev_MouseButtonDown(Urho3D::StringHash eventType, Urho3D::VariantMap& eventData) { Event event; event.type = mouseButtonDown; event.mousebutton.button = eventData[Urho3D::MouseButtonDown::P_BUTTON].GetInt(); event.mousebutton.buttons = eventData[Urho3D::MouseButtonDown::P_BUTTONS].GetInt(); event.mousebutton.qualifiers = eventData[Urho3D::MouseButtonDown::P_QUALIFIERS].GetInt(); notifyObservers((int)event.type, &event, sizeof(Event)); PB_EVENT->push(event); } /////////////////////////////////////////////////////////////////////////////// // /////////////////////////////////////////////////////////////////////////////// void PB_EventHandler::ev_MouseButtonUp(Urho3D::StringHash eventType, Urho3D::VariantMap& eventData) { Event event; event.type = mouseButtonUp; event.mousebutton.button = eventData[Urho3D::MouseButtonUp::P_BUTTON].GetInt(); event.mousebutton.buttons = eventData[Urho3D::MouseButtonUp::P_BUTTONS].GetInt(); event.mousebutton.qualifiers = eventData[Urho3D::MouseButtonUp::P_QUALIFIERS].GetInt(); notifyObservers((int)event.type, &event, sizeof(Event)); PB_EVENT->push(event); } /////////////////////////////////////////////////////////////////////////////// // /////////////////////////////////////////////////////////////////////////////// void PB_EventHandler::ev_MouseMove(Urho3D::StringHash eventType, Urho3D::VariantMap& eventData) { Event event; event.type = mouseMove; event.mousemove.x = eventData[Urho3D::MouseMove::P_X].GetInt(); event.mousemove.y = eventData[Urho3D::MouseMove::P_Y].GetInt(); event.mousemove.dx = eventData[Urho3D::MouseMove::P_DX].GetInt(); event.mousemove.dy = eventData[Urho3D::MouseMove::P_DY].GetInt(); event.mousemove.buttons = eventData[Urho3D::MouseMove::P_BUTTONS].GetInt(); event.mousemove.qualifiers = eventData[Urho3D::MouseMove::P_QUALIFIERS].GetInt(); notifyObservers((int)event.type, &event, sizeof(Event)); PB_EVENT->push(event); } /////////////////////////////////////////////////////////////////////////////// // /////////////////////////////////////////////////////////////////////////////// void PB_EventHandler::ev_MouseWheel(Urho3D::StringHash eventType, Urho3D::VariantMap& eventData) { Event event; event.type = mouseWheel; event.mousewheel.wheel = eventData[Urho3D::MouseWheel::P_WHEEL].GetInt(); event.mousewheel.buttons = eventData[Urho3D::MouseWheel::P_BUTTONS].GetInt(); event.mousewheel.qualifiers = eventData[Urho3D::MouseWheel::P_QUALIFIERS].GetInt(); notifyObservers((int)event.type, &event, sizeof(Event)); PB_EVENT->push(event); } /////////////////////////////////////////////////////////////////////////////// // /////////////////////////////////////////////////////////////////////////////// void PB_EventHandler::ev_BackgroundLoadResource(Urho3D::StringHash eventType, Urho3D::VariantMap& eventData) { Event event; event.type = backgroundResourceLoaded; event.resourceLoaded.name = (wchar_t*)Urho3D::WString( eventData[Urho3D::ResourceBackgroundLoaded::P_RESOURCENAME].GetString() ).CString(); event.resourceLoaded.success = (int) eventData[Urho3D::ResourceBackgroundLoaded::P_SUCCESS].GetBool(); event.resourceLoaded.resource = (void*) eventData[Urho3D::ResourceBackgroundLoaded::P_RESOURCE].GetPtr(); notifyObservers((int)event.type, &event, sizeof(Event)); PB_EVENT->push(event); } /////////////////////////////////////////////////////////////////////////////// // /////////////////////////////////////////////////////////////////////////////// void PB_EventHandler::ev_ResourceFileChange(Urho3D::StringHash eventType, Urho3D::VariantMap& eventData) { Event event; event.type = resourceFileChange; event.resourceFileChange.resourceName = (wchar_t*)Urho3D::WString(eventData[Urho3D::FileChanged::P_RESOURCENAME].GetString()).CString(); event.resourceFileChange.fileName = (wchar_t*)Urho3D::WString(eventData[Urho3D::FileChanged::P_FILENAME].GetString()).CString(); notifyObservers((int)event.type, &event, sizeof(Event)); PB_EVENT->push(event); } /////////////////////////////////////////////////////////////////////////////// // /////////////////////////////////////////////////////////////////////////////// void PB_EventHandler::notify(int what, void* data, int size) { for (auto & m : m_bindfunction) { if (what == m.first) { Event &event = *(Event*)data; (*m.second)(&event); } } } /////////////////////////////////////////////////////////////////////////////// // /////////////////////////////////////////////////////////////////////////////// void PB_EventHandler::bindFunction(EventType type, fn_callback callback) { auto found = m_bindfunction.find(type); if (found == m_bindfunction.end()) { m_bindfunction.emplace(type, callback); } } /////////////////////////////////////////////////////////////////////////////// // /////////////////////////////////////////////////////////////////////////////// void PB_EventHandler::unBindFunction(EventType type, fn_callback) { auto found = m_bindfunction.find(type); if (found != m_bindfunction.end()) { m_bindfunction.erase(found); } } /////////////////////////////////////////////////////////////////////////////// // EXPORTED FUNCTIONS /////////////////////////////////////////////////////////////////////////////// PB_FUNCTION(int) uh3_PoolEvent(Event* ev) { if (PB_EVENT->size()) { *ev = PB_EVENT->front(); PB_EVENT->pop(); return 1; } return 0; } /////////////////////////////////////////////////////////////////////////////// // /////////////////////////////////////////////////////////////////////////////// PB_FUNCTION(void) uh3_BindEvent(int type, void* callback) { PB_URHOEVENT->bindFunction((EventType)type, (PB_EventHandler::fn_callback)callback); } /////////////////////////////////////////////////////////////////////////////// // /////////////////////////////////////////////////////////////////////////////// PB_FUNCTION(void) uh3_UnBindEvent(int type, void* callback) { PB_URHOEVENT->unBindFunction((EventType)type, (PB_EventHandler::fn_callback)callback); }
43.607759
142
0.560443
JeromeOrtali
41de92bde3868e46c194e39ac673bf598bf0779c
428
cpp
C++
src_test/uuid.test.cpp
hannes-hochreiner/raw-data-db-agent
1797e3b897f4e07cd253b5b45b4c1daba203ec62
[ "MIT" ]
null
null
null
src_test/uuid.test.cpp
hannes-hochreiner/raw-data-db-agent
1797e3b897f4e07cd253b5b45b4c1daba203ec62
[ "MIT" ]
null
null
null
src_test/uuid.test.cpp
hannes-hochreiner/raw-data-db-agent
1797e3b897f4e07cd253b5b45b4c1daba203ec62
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include "uuid.hpp" namespace { TEST(global, round_trip) { std::string res = get_uuid(); const std::string hex_chars("0123456789ABCDEF"); for (uint cntr = 0; cntr < 36; cntr++) { if ((cntr == 8) || (cntr == 13) || (cntr == 18) || (cntr == 23)) { EXPECT_EQ('-', res[cntr]); } else { EXPECT_NE(hex_chars.find(res[cntr]), std::string::npos); } } } }
23.777778
72
0.535047
hannes-hochreiner
41e8203349475f9d718126d436f3a11dffdb162f
241
cc
C++
L3/7 - P42280 - Tauler d'escacs (1)/ex7.cc
angelgomezsa/Cplusplus
9fd1ed5b1beffcf253019e8376b2bd41dac6e449
[ "MIT" ]
null
null
null
L3/7 - P42280 - Tauler d'escacs (1)/ex7.cc
angelgomezsa/Cplusplus
9fd1ed5b1beffcf253019e8376b2bd41dac6e449
[ "MIT" ]
null
null
null
L3/7 - P42280 - Tauler d'escacs (1)/ex7.cc
angelgomezsa/Cplusplus
9fd1ed5b1beffcf253019e8376b2bd41dac6e449
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main () { int f,c; cin >> f >> c; char num; int total=0; for (int i=0;i<f;i++) { for (int j=0;j<c;j++) { char num; cin >> num; total+=num-'0'; } } cout << total << endl; }
12.684211
25
0.506224
angelgomezsa
41ea65811bb6146c803676737fbd885795f7c6f3
2,551
cpp
C++
Math/Source/Geometry/Plane.cpp
Solidstatewater/Anubis-Engine
d2720167c0d5306d4d12a027dc31686b5cbb0f18
[ "BSD-2-Clause" ]
2
2017-10-29T06:43:05.000Z
2020-03-27T10:27:07.000Z
Math/Source/Geometry/Plane.cpp
Solidstatewater/Anubis-Engine
d2720167c0d5306d4d12a027dc31686b5cbb0f18
[ "BSD-2-Clause" ]
null
null
null
Math/Source/Geometry/Plane.cpp
Solidstatewater/Anubis-Engine
d2720167c0d5306d4d12a027dc31686b5cbb0f18
[ "BSD-2-Clause" ]
5
2016-02-06T11:01:51.000Z
2019-03-18T13:56:00.000Z
//==================================================================================== //Plane.cpp : plane geometry implementation // //This code is part of Anubis Engine. // //Anubis Engine is a free game engine created as a fan project to be //awesome platform for developing games! // //All sources can be found here: // https://github.com/Dgek/Anubis-Engine // //Demos based on Anubis Engine can be found here: // https://github.com/Dgek/Demos // //Copyright (c) 2013, Muralev Evgeny //All rights reserved. // //Redistribution and use in source and binary forms, with //or without modification, are permitted provided that the //following conditions are met: // //Redistributions of source code must retain the above copyright notice, //this list of conditions and the following disclaimer. // //Redistributions in binary form must reproduce the above copyright notice, //this list of conditions and the following disclaimer in the documentation //and/or other materials provided with the distribution. // //Neither the name of the Minotower Games 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 MURALEV EVGENY "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 MURALEV EVGENY 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 "Math_pch.h" #include "Plane.h" using namespace Anubis; bool Plane::Inside(const Vec & point) const { AREAL dist = Dot(Normal(), point) + D(); return (dist >= 0.0f); } bool Plane::Inside(const Vec & point, const AREAL radius) const { float dist = Dot(Normal(), point) + D(); // if this distance is < -radius, we are outside return (dist >= -radius); } Vec Plane::Normal() const { return Vector(getx(&m_coeff), gety(&m_coeff), getz(&m_coeff), 0); } AREAL32 Plane::D() const { return getw(&m_coeff); }
38.074627
95
0.696198
Solidstatewater
41ea950f7b9ac6e2bac86adbe53fc136929102de
7,308
cpp
C++
src/configure/bind/filesystem.cpp
hotgloupi/configure
888cf725c93df5a1cf01794cc0a581586a82855c
[ "BSD-3-Clause" ]
1
2015-11-13T10:37:35.000Z
2015-11-13T10:37:35.000Z
src/configure/bind/filesystem.cpp
hotgloupi/configure
888cf725c93df5a1cf01794cc0a581586a82855c
[ "BSD-3-Clause" ]
19
2015-02-10T17:18:58.000Z
2015-07-11T11:31:08.000Z
src/configure/bind/filesystem.cpp
hotgloupi/configure
888cf725c93df5a1cf01794cc0a581586a82855c
[ "BSD-3-Clause" ]
null
null
null
#include <configure/bind.hpp> #include <configure/bind/path_utils.hpp> #include <configure/Filesystem.hpp> #include <configure/lua/State.hpp> #include <configure/lua/Type.hpp> #include <configure/Node.hpp> #include <configure/bind/path_utils.hpp> #include <boost/filesystem.hpp> namespace fs = boost::filesystem; namespace configure { static int fs_glob(lua_State* state) { Filesystem& self = lua::Converter<std::reference_wrapper<Filesystem>>::extract(state, 1); std::vector<NodePtr> res; if (lua_gettop(state) == 3) { res = self.glob( utils::extract_path(state, 2), lua::Converter<std::string>::extract(state, 3) ); } else if (char const* arg = lua_tostring(state, 2)) { res = self.glob(arg); } else CONFIGURE_THROW( error::InvalidArgument("Expected a glob pattern") ); lua_createtable(state, res.size(), 0); for (int i = 0, len = res.size(); i < len; ++i) { lua::Converter<NodePtr>::push(state, res[i]); lua_rawseti(state, -2, i + 1); } return 1; } static int fs_rglob(lua_State* state) { Filesystem& self = lua::Converter<std::reference_wrapper<Filesystem>>::extract(state, 1); std::vector<NodePtr> res; fs::path dir; if (char const* arg = lua_tostring(state, 2)) dir = arg; else dir = lua::Converter<fs::path>::extract(state, 2); if (char const* arg = lua_tostring(state, 3)) { res = self.rglob(dir, arg); } lua_createtable(state, res.size(), 0); for (int i = 0, len = res.size(); i < len; ++i) { lua::Converter<NodePtr>::push(state, res[i]); lua_rawseti(state, -2, i + 1); } return 1; } static int fs_list_directory(lua_State* state) { Filesystem& self = lua::Converter<std::reference_wrapper<Filesystem>>::extract(state, 1); std::vector<NodePtr> res; if (char const* arg = lua_tostring(state, 2)) res = self.list_directory(arg); else res = self.list_directory( lua::Converter<fs::path>::extract(state, 2) ); lua_createtable(state, res.size(), 0); for (int i = 0, len = res.size(); i < len; ++i) { lua::Converter<NodePtr>::push(state, res[i]); lua_rawseti(state, -2, i + 1); } return 1; } static int fs_find_file(lua_State* state) { Filesystem& self = lua::Converter<std::reference_wrapper<Filesystem>>::extract(state, 1); if (!lua_istable(state, 2)) CONFIGURE_THROW( error::LuaError( "Expected a table, got '" + std::string(luaL_tolstring(state, 2, nullptr)) + "'" ) ); std::vector<fs::path> directories; for (int i = 1, len = lua_rawlen(state, 2); i <= len; ++i) { lua_rawgeti(state, 2, i); directories.push_back(utils::extract_path(state, -1)); } lua::Converter<NodePtr>::push( state, self.find_file(directories, utils::extract_path(state, 3)) ); return 1; } static int fs_which(lua_State* state) { Filesystem& self = lua::Converter<std::reference_wrapper<Filesystem>>::extract(state, 1); std::string arg; if (fs::path* ptr = lua::Converter<fs::path>::extract_ptr(state, 2)) arg = ptr->string(); else if (char const* ptr = lua_tostring(state, 2)) arg = ptr; if (!arg.empty()) { auto res = self.which(arg); if (res) lua::Converter<fs::path>::push(state, *res); else lua_pushnil(state); } else { throw std::runtime_error( "Filesystem.which(): Expected program name, got '" + std::string(luaL_tolstring(state, 2, 0)) + "'"); } return 1; } static int fs_cwd(lua_State* state) { lua::Converter<fs::path>::push(state, fs::current_path()); return 1; } static int fs_current_script(lua_State* state) { lua_Debug ar; if (lua_getstack(state, 1, &ar) != 1) CONFIGURE_THROW(error::LuaError("Couldn't get the stack")); if (lua_getinfo(state, "S", &ar) == 0) CONFIGURE_THROW(error::LuaError("Couldn't get stack info")); if (ar.source == nullptr) CONFIGURE_THROW(error::LuaError("Invalid source file")); fs::path src(ar.source[0] == '@' ? &ar.source[1] : ar.source); if (!src.is_absolute()) src = fs::current_path() / src; if (!fs::exists(src)) CONFIGURE_THROW(error::LuaError("Couldn't find the script path") << error::path(src)); lua::Converter<fs::path>::push(state, src); return 1; } static int fs_copy(lua_State* state) { Filesystem& self = lua::Converter<std::reference_wrapper<Filesystem>>::extract(state, 1); NodePtr res; fs::path dst; if (char const* arg = lua_tostring(state, 3)) dst = arg; else if (fs::path* arg = lua::Converter<fs::path>::extract_ptr(state, 3)) dst = *arg; else CONFIGURE_THROW( error::LuaError("Expected string or path for dest argument") << error::lua_function("Filesystem::copy") ); if (char const* arg = lua_tostring(state, 2)) res = self.copy(arg, dst); else if (fs::path* arg = lua::Converter<fs::path>::extract_ptr(state, 2)) res = self.copy(*arg, dst); else if (NodePtr* arg = lua::Converter<NodePtr>::extract_ptr(state, 2)) res = self.copy(*arg, dst); else CONFIGURE_THROW( error::LuaError("Expected string, path or Node for src argument") << error::lua_function("Filesystem::copy") ); lua::Converter<NodePtr>::push(state, std::move(res)); return 1; } static int fs_create_directories(lua_State* state) { lua::Converter<std::reference_wrapper<Filesystem>>::extract(state, 1); bool res = fs::create_directories(utils::extract_path(state, 2)); lua::Converter<bool>::push(state, res); return 1; } void bind_filesystem(lua::State& state) { /// Filesystem operations. // @classmod Filesystem lua::Type<Filesystem, std::reference_wrapper<Filesystem>>(state, "Filesystem") /// Find files according to a glob pattern // @function Filesystem:glob // @string pattern A glob pattern // @return A list of @{Node}s .def("glob", &fs_glob) /// Find files recursively according to a glob pattern // @function Filesystem:rglob // @tparam string|Path dir The base directory // @string pattern A glob pattern // @return A list of @{Node}s .def("rglob", &fs_rglob) /// List a directory // @function Filesystem:list_directory // @tparam string|Path dir Directory to list // @return A list of @{Node}s .def("list_directory", &fs_list_directory) /// Find a file // @function Filesystem:find_file // @tparam table directories A list of directories to inspect // @tparam string|Path file The file to search for // @return A @{Node} .def("find_file", &fs_find_file) /// Find an executable path // @function Filesystem:which // @tparam string|Path name An executable name // @treturn Path|nil Absolute path to the executable found or nil .def("which", &fs_which) /// Generate rule that copy a file. // @function Filesystem:copy // @treturn Node the target node .def("copy", &fs_copy) /// Return the current working directory // @function Filesystem:cwd // @treturn Path current directory .def("cwd", &fs_cwd) /// Return the current script path // @function Filesystem.current_script .def("current_script", &fs_current_script) /// Create directories // @function Filesystem:create_directories // @treturn bool True on success, false if the directories already exist .def("create_directories", &fs_create_directories) ; } }
28.107692
108
0.65613
hotgloupi
41efaa24e2497e3bdc45dbe10b8f861a9b3648fc
1,107
hpp
C++
src/Map.hpp
adileo/rpg-game-cpp
f43f231b0bdb7f4618ece8174d08cf26ab3125c6
[ "MIT" ]
null
null
null
src/Map.hpp
adileo/rpg-game-cpp
f43f231b0bdb7f4618ece8174d08cf26ab3125c6
[ "MIT" ]
null
null
null
src/Map.hpp
adileo/rpg-game-cpp
f43f231b0bdb7f4618ece8174d08cf26ab3125c6
[ "MIT" ]
null
null
null
/* * Map.hpp * * Created on: 18 giu 2016 * Author: adileobarone * * La mappa è composta solo da stanze, non si deve occupare degli oggetti che ci sono sopra, * poichè sono altre entità gestite da altre classi, l'unico link che c'è è quello che ogni oggetto * punta a una posizione della mappa in cui si trova. * */ #ifndef MAP_HPP_ #define MAP_HPP_ #include <iostream> #include <list> #include "Room.hpp" #include "lib/easylogging++.hpp" //Faccio una forward declaration per evitare le dipendenze circolari class GameManager; struct RoomNode{ Room* value; RoomNode* next; }; class RoomList{ private: int size; RoomNode* head; RoomNode* tail; public: RoomList(); void push(Room* rm); RoomNode* getHead(); RoomNode* getBack(); int length(); void destroy(); }; class Map{ private: //std::list<Room> roomList; RoomList rmlist; GameManager* gm; public: Map(GameManager* g); ~Map(); Room* getRoom(Coord coord); Room* getRoomOrCreate(Coord coord); //std::list<Room>* getRooms(); RoomList* getRooms(); }; #endif /* MAP_HPP_ */
18.147541
100
0.671183
adileo
41f05244117e51ea6259db2cd44c2f9a70cb4313
2,438
cpp
C++
samples/snippets/cpp/VS_Snippets_CLR_System/system.Buffer.Bytes/CPP/setbyte.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
421
2018-04-01T01:57:50.000Z
2022-03-28T15:24:42.000Z
samples/snippets/cpp/VS_Snippets_CLR_System/system.Buffer.Bytes/CPP/setbyte.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
5,797
2018-04-02T21:12:23.000Z
2022-03-31T23:54:38.000Z
samples/snippets/cpp/VS_Snippets_CLR_System/system.Buffer.Bytes/CPP/setbyte.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
1,482
2018-03-31T11:26:20.000Z
2022-03-30T22:36:45.000Z
//<Snippet2> // Example of the Buffer::SetByte method. using namespace System; // Display the array contents in hexadecimal. void DisplayArray( Array^ arr, String^ name ) { // Get the array element width; format the formatting string. int elemWidth = Buffer::ByteLength( arr ) / arr->Length; String^ format = String::Format( " {{0:X{0}}}", 2 * elemWidth ); // Display the array elements from right to left. Console::Write( "{0,7}:", name ); for ( int loopX = arr->Length - 1; loopX >= 0; loopX-- ) Console::Write( format, arr->GetValue( loopX ) ); Console::WriteLine(); } int main() { // These are the arrays to be modified with SetByte. array<Int16>^shorts = gcnew array<Int16>(10); array<Int64>^longs = gcnew array<Int64>(3); Console::WriteLine( "This example of the " "Buffer::SetByte( Array*, int, unsigned char ) \n" "method generates the following output.\n" "Note: The arrays are displayed from right to left.\n" ); Console::WriteLine( " Initial values of arrays:\n" ); // Display the initial values of the arrays. DisplayArray( shorts, "shorts" ); DisplayArray( longs, "longs" ); // Copy two regions of source array to destination array, // and two overlapped copies from source to source. Console::WriteLine( "\n Array values after setting byte 3 = 25, \n" " byte 6 = 64, byte 12 = 121, and byte 17 = 196:\n" ); Buffer::SetByte( shorts, 3, 25 ); Buffer::SetByte( shorts, 6, 64 ); Buffer::SetByte( shorts, 12, 121 ); Buffer::SetByte( shorts, 17, 196 ); Buffer::SetByte( longs, 3, 25 ); Buffer::SetByte( longs, 6, 64 ); Buffer::SetByte( longs, 12, 121 ); Buffer::SetByte( longs, 17, 196 ); // Display the arrays again. DisplayArray( shorts, "shorts" ); DisplayArray( longs, "longs" ); } /* This example of the Buffer::SetByte( Array*, int, unsigned char ) method generates the following output. Note: The arrays are displayed from right to left. Initial values of arrays: shorts: 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 longs: 0000000000000000 0000000000000000 0000000000000000 Array values after setting byte 3 = 25, byte 6 = 64, byte 12 = 121, and byte 17 = 196: shorts: 0000 C400 0000 0079 0000 0000 0040 0000 1900 0000 longs: 000000000000C400 0000007900000000 0040000019000000 */ //</Snippet2>
33.861111
72
0.647252
hamarb123
41f3e35c912ccd2bfb382622751e1763fe19ad24
1,528
cpp
C++
Source/ProceduralTerrainGenerator/Private/BlurFilter.cpp
McOmghall/procedural-terrain-generator-UE4-plugin
bebf4723e86eeeb75b444bef68dbaaf662813165
[ "Apache-2.0" ]
7
2019-03-20T10:06:21.000Z
2022-01-06T14:54:47.000Z
Source/ProceduralTerrainGenerator/Private/BlurFilter.cpp
McOmghall/procedural-terrain-generator-UE4-plugin
bebf4723e86eeeb75b444bef68dbaaf662813165
[ "Apache-2.0" ]
1
2019-07-30T07:10:37.000Z
2019-07-30T07:10:37.000Z
Source/ProceduralTerrainGenerator/Private/BlurFilter.cpp
McOmghall/procedural-terrain-generator-UE4-plugin
bebf4723e86eeeb75b444bef68dbaaf662813165
[ "Apache-2.0" ]
4
2019-08-09T07:31:07.000Z
2022-02-13T07:13:40.000Z
// Fill out your copyright notice in the Description page of Project Settings. #include "BlurFilter.h" // NaÏve gaussian blur impl bool UBlurFilter::ModifyHeightMap(TArray<uint16>* RawHeightMapData, FBounds Bounds, FRandomStream* RandomStream) { for (int32 j = Bounds.MinY; j <= Bounds.MaxY; j++) { for (int32 i = Bounds.MinX; i <= Bounds.MaxX; i++) { double CountPoints = 0; double SumPointHeight = 0; int32 RealDistanceOfInfluence = DistanceOfInfluence; for (int32 OffsetX = -RealDistanceOfInfluence; OffsetX <= RealDistanceOfInfluence; OffsetX++) { int32 NeededOffsetY = RealDistanceOfInfluence - FMath::Abs(OffsetX); for (int32 OffsetY = -NeededOffsetY; OffsetY <= NeededOffsetY; OffsetY++) { FIntPoint CurrentPoint(i + OffsetX, j + OffsetY); int32 CurrentIndex = (CurrentPoint.Y - Bounds.MinY) * (Bounds.MaxX - Bounds.MinX + 1) + (CurrentPoint.X - Bounds.MinX); if (CurrentPoint.X >= Bounds.MinX && CurrentPoint.X <= Bounds.MaxX && CurrentPoint.Y >= Bounds.MinY && CurrentPoint.Y <= Bounds.MaxY) { double Weight = FMath::Pow(InfluenceDecayPerDistanceUnit, FMath::Abs(OffsetX) + FMath::Abs(OffsetY)); CountPoints += Weight; SumPointHeight += Weight * (*RawHeightMapData)[CurrentIndex]; } } } int32 CurrentIndex = (j - Bounds.MinY) * (Bounds.MaxX - Bounds.MinX + 1) + (i - Bounds.MinX); (*RawHeightMapData)[CurrentIndex] = FMath::Clamp(FMath::RoundToInt(SumPointHeight / CountPoints), 0, (int32)UINT16_MAX); } } return true; }
39.179487
138
0.690445
McOmghall
41f4297d1caf636432a0ca6c9633ab506544f07b
333
cpp
C++
examples/hello/hello_world_lib.cpp
juugcatm/bazel_environment
248cfb923ea83a270082883079af617e507cc760
[ "Unlicense" ]
5
2019-06-14T16:36:31.000Z
2020-05-01T06:20:35.000Z
examples/hello/hello_world_lib.cpp
juugcatm/bazel_environment
248cfb923ea83a270082883079af617e507cc760
[ "Unlicense" ]
null
null
null
examples/hello/hello_world_lib.cpp
juugcatm/bazel_environment
248cfb923ea83a270082883079af617e507cc760
[ "Unlicense" ]
null
null
null
#include "examples/hello/hello_world_lib.h" #include "glog/logging.h" namespace hello { bool print (proto::Hello hello_pb) { LOG(INFO) << "Hello world!"; if (!hello_pb.extra_message().empty()) { LOG(INFO) << hello_pb.extra_message(); } usleep(1000000); return !hello_pb.extra_message().empty(); } }
19.588235
45
0.642643
juugcatm
41f4c066d8701e14e1ac7a4bbc7d3161b2a7e9de
5,401
cpp
C++
src/interrupts/panic.cpp
LipkeGu1810/FoxOS-kernel
d504dcac542e5535eb0481babc0515c6fe8e9f28
[ "MIT" ]
null
null
null
src/interrupts/panic.cpp
LipkeGu1810/FoxOS-kernel
d504dcac542e5535eb0481babc0515c6fe8e9f28
[ "MIT" ]
null
null
null
src/interrupts/panic.cpp
LipkeGu1810/FoxOS-kernel
d504dcac542e5535eb0481babc0515c6fe8e9f28
[ "MIT" ]
null
null
null
#include <interrupts/panic.h> #include <scheduling/scheduler/scheduler.h> #include <renderer/renderer2D.h> #include <renderer/point.h> #include <driver/serial.h> #include <config.h> #include <stdio.h> #include <disassembler.h> using namespace interrupts; Panic::Panic(int intr) { this->intr = intr; this->panic = NULL; } Panic::Panic(char* panic) { this->panic = panic; } char* Panic::get_panic_message() { switch(this->intr){ case 0x0: return((char*) "Divide by Zero"); break; case 0x1: return((char*) "Debug"); break; case 0x2: return((char*) "Non Maskable Interrupt"); break; case 0x3: return((char*) "Breakpoint"); break; case 0x4: return((char*) "Overflow"); break; case 0x5: return((char*) "Bound Range"); break; case 0x6: return((char*) "Invalid Opcode"); break; case 0x7: return((char*) "Device Not Available"); break; case 0x8: return((char*) "Double Fault"); break; case 0x9: return((char*) "Coprocessor Segment Overrun"); break; case 0xa: return((char*) "Invalid TSS"); break; case 0xb: return((char*) "Segment not Present"); break; case 0xc: return((char*) "Stack Fault"); break; case 0xd: return((char*) "General Protection"); break; case 0xe: return((char*) "Page Fault"); break; case 0x10: return((char*) "x87 Floating Point"); break; case 0x11: return((char*) "Alignment Check"); break; case 0x12: return((char*) "Machine Check"); break; case 0x13: return((char*) "SIMD Floating Point"); break; case 0x1e: return((char*) "Security-sensitive event in Host"); break; default: return((char*) "Reserved"); break; } } void Panic::dump_regs(s_registers* regs) { renderer::global_font_renderer->printf("cr0: %d; cr2: %d; cr3: %d; cr4: %d\n", regs->cr0, regs->cr2, regs->cr3, regs->cr4); renderer::global_font_renderer->printf("r8: %d; r9: %d; r10: %d; r11: %d\n", regs->r8, regs->r9, regs->r10, regs->r11); renderer::global_font_renderer->printf("r12: %d; r13: %d; r14: %d; r15: %d\n", regs->r12, regs->r13, regs->r14, regs->r15); renderer::global_font_renderer->printf("rdi: %d; rsi: %d; rbp: %d\n", regs->rdi, regs->rsi, regs->rbp); renderer::global_font_renderer->printf("rax: %d; rbx: %d; rcx: %d; rdx: %d\n", regs->rax, regs->rbx, regs->rcx, regs->rdx); renderer::global_font_renderer->printf("rip: %d; cs: %d; rflags: %d; rsp: %d\n\n", regs->rip, regs->cs, regs->rflags, regs->rsp); } extern uint8_t screen_of_death[]; void Panic::do_it(s_registers* regs) { renderer::point_t bmp_info = renderer::global_renderer2D->get_bitmap_info(screen_of_death); renderer::global_font_renderer->color = 0xffe36d2d; renderer::global_font_renderer->clear(); renderer::global_font_renderer->cursor_position = {0, 8}; renderer::global_font_renderer->color = 0xffffffff; renderer::global_font_renderer->printf("(/ o_o)/ Oh no! Something terrible has happened and your system has been halted...\n"); renderer::global_font_renderer->printf("There isn't much you can do apart from restart the computer. More information below.\n\n"); if (!this->panic) { renderer::global_font_renderer->printf("Kernel PANIC -> %s (0x%x)\n", this->get_panic_message(), this->intr); } else { renderer::global_font_renderer->printf("Kernel PANIC -> %s\n", this->panic); } renderer::global_font_renderer->printf("Kernel version: %d\n", VERSION); renderer::global_font_renderer->printf("Release type: %s\n\n", RELEASE_T); renderer::global_font_renderer->printf("Please report this issue at %fhttps://github.com/TheUltimateFoxOS/FoxOS%r by creating an issue.\n", 0xff0000ff); renderer::global_font_renderer->printf("Feel free to fix this and submit a pull request!\n\n"); if (regs) { renderer::global_font_renderer->printf("Register dump:\n"); dump_regs(regs); char disassembled[0xFF]; memset(disassembled, 0, 0xFF); unsigned char* code_location = (unsigned char*) regs->rip; int disassembled_size = disassemble(code_location, 10, 0, disassembled); renderer::global_font_renderer->printf("Faulting instruction: %s\n", disassembled); renderer::global_font_renderer->printf("\nStarting stack trace:\n"); if(resolve_symbol(resolve_symbol(regs->rip)) != 0) { char str[512]; sprintf(str, "%s + %d", resolve_symbol(regs->rip), regs->rip - resolve_symbol(resolve_symbol(regs->rip))); renderer::global_font_renderer->printf("%s\n", str); } else { renderer::global_font_renderer->printf("<unknown function at 0x%x>\n", regs->rip); } int max_lines = (renderer::global_renderer2D->target_frame_buffer->height - renderer::global_font_renderer->cursor_position.y) / 16; max_lines -= 4; driver::global_serial_driver->printf("Starting stack trace using %d as max lines!\n", max_lines); unwind(max_lines, regs->rbp, [](int frame_num, uint64_t rip) { if(resolve_symbol(resolve_symbol(rip)) != 0) { char str[512]; sprintf(str, "%s + %d", resolve_symbol(rip), rip - resolve_symbol(resolve_symbol(rip))); renderer::global_font_renderer->printf("%s\n", str); } else { renderer::global_font_renderer->printf("<unknown function at 0x%x>\n", rip); } }); } renderer::global_renderer2D->load_bitmap(screen_of_death, 0, renderer::global_renderer2D->target_frame_buffer->height - bmp_info.x); while(true) { halt_cpu = true; asm volatile("cli; hlt"); } }
31.04023
153
0.68154
LipkeGu1810
41f820e985264fff1bec67755323714b98ad8f08
2,520
cc
C++
rama/qt/nelder_mead.cc
teenylasers/eggshell
7d1239eb1b143b11b5ccd1029d9bacdd601c8e4e
[ "ICU", "OpenSSL" ]
null
null
null
rama/qt/nelder_mead.cc
teenylasers/eggshell
7d1239eb1b143b11b5ccd1029d9bacdd601c8e4e
[ "ICU", "OpenSSL" ]
127
2017-11-01T01:28:28.000Z
2021-03-18T05:12:21.000Z
rama/qt/nelder_mead.cc
teenylasers/eggshell
7d1239eb1b143b11b5ccd1029d9bacdd601c8e4e
[ "ICU", "OpenSSL" ]
2
2017-10-20T01:16:49.000Z
2018-11-04T02:36:53.000Z
// Rama Simulator, Copyright (C) 2014-2020 Russell Smith. // // This program is free software: you can redistribute it and/or modify it // under the terms of the GNU General Public License as published by the Free // Software Foundation, either version 3 of the License, or (at your option) // any later version. // // This program is distributed in the hope that it will be useful, but WITHOUT // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for // more details. #include <QMessageBox> #include "nelder_mead.h" #include "ui_nelder_mead.h" NelderMeadOptimizer::Settings NelderMead::s_; NelderMead::NelderMead(QWidget *parent) : QDialog(parent), ui(new Ui::NelderMead) { ui->setupUi(this); resize(0, 0); ui->edit_time ->setText(QString::asprintf("%.10g", s_.annealing_time)); ui->edit_initial_fraction ->setText(QString::asprintf("%.10g", s_.initial_fraction)); ui->edit_initial_temperature ->setText(QString::asprintf("%.10g", s_.initial_temperature)); ui->edit_final_temperature ->setText(QString::asprintf("%.10g", s_.final_temperature)); } NelderMead::~NelderMead() { delete ui; } void NelderMead::on_ok_button_clicked() { if (Check()) { accept(); } } void NelderMead::on_cancel_button_clicked() { reject(); } bool NelderMead::Check() { bool ok; s_.annealing_time = ui->edit_time->text().toDouble(&ok); if (!ok || s_.annealing_time < 0) { QMessageBox::warning(this, "Error", "Bad annealing time value (must be a number >= 0)"); return false; } s_.initial_fraction = ui->edit_initial_fraction->text().toDouble(&ok); if (!ok || s_.initial_fraction < 0 || s_.initial_fraction > 1) { QMessageBox::warning(this, "Error", "Bad initial fraction value " "(must be a number in the range 0..1)"); return false; } s_.initial_temperature = ui->edit_initial_temperature->text().toDouble(&ok); if (!ok || s_.initial_temperature < 0) { QMessageBox::warning(this, "Error", "Bad initial temperature value (must be a number >= 0)"); return false; } s_.final_temperature = ui->edit_final_temperature->text().toDouble(&ok); if (!ok || s_.final_temperature <= 0 || s_.final_temperature >= 1) { QMessageBox::warning(this, "Error", "Bad final temperature value " "(must be a number >0 and <1)"); return false; } return true; }
30
80
0.668254
teenylasers
41f89a007b72f7b12b342c22a9fa4c3c7d19fd41
3,704
cpp
C++
src/modules/Phone/Call.cpp
pdumais/dhas
424212d4766c02f5df9e363ddb8ad2c295ed49d8
[ "MIT" ]
12
2015-09-09T07:05:27.000Z
2020-12-27T12:52:28.000Z
src/modules/Phone/Call.cpp
pdumais/dhas
424212d4766c02f5df9e363ddb8ad2c295ed49d8
[ "MIT" ]
null
null
null
src/modules/Phone/Call.cpp
pdumais/dhas
424212d4766c02f5df9e363ddb8ad2c295ed49d8
[ "MIT" ]
2
2016-10-23T05:23:20.000Z
2020-09-17T22:01:33.000Z
#include "DHASLogging.h" #include "Call.h" #include <stdio.h> #include "resip/dum/InviteSession.hxx" #include "resip/dum/ClientInviteSession.hxx" #include "AppDialogSetNotifySoundsEmptyCommand.h" using namespace resip; Call::Call(resip::DialogUsageManager &dum, ActionMachine* am):AppDialogSet(dum) { this->mpActionMachine = am; this->mCallState = Initial; this->mRtpSession = 0; this->mIncomming = false; this->mpCurrentAction = 0; } Call::~Call() { mpActionMachine->destroyChain(this); if (this->mRtpSession) { delete this->mRtpSession; this->mRtpSession = 0; } } void Call::setCurrentAction(IPhoneAction* a) { this->mpCurrentAction = a; } void Call::onCallAnswered() { // The call is answered by UAS, this is what triggers the action chain mpActionMachine->asyncRunAction(this); } CallState Call::getCallState() { return mCallState; } void Call::setIncomming(bool i) { this->mIncomming = i; } IPhoneAction* Call::getCurrentAction() { return mpCurrentAction; } void Call::removeRTPObserver(RTPObserver *obs) { for (auto it = this->mRtpObservers.begin(); it != this->mRtpObservers.end(); it++) { if (*it != obs) continue; this->mRtpObservers.erase(it); return; } } void Call::addRTPObserver(RTPObserver *obs) { for (auto it = this->mRtpObservers.begin(); it != this->mRtpObservers.end(); it++) { if (*it == obs) return; } this->mRtpObservers.push_back(obs); } void Call::appendAction(IPhoneAction* action) { if (mpCurrentAction == 0) { mpCurrentAction = action; //if no action was set and the call was answered, then schedule the action to run if (getCallState() == Answered) mpActionMachine->asyncRunAction(this); } else { // if an action is already in queue, it means that we can just append to it and // it will eventually get invoked IPhoneAction *a = mpCurrentAction; while (a->getNextAction() != 0) { a = a->getNextAction(); } a->setNextAction(action); } } void Call::setRTPSession(Dumais::Sound::RTPSession *rtpSession) { this->mRtpSession = rtpSession; this->mRtpSession->addObserver(this); //TODO should unsubscribe if overwriting observer } Dumais::Sound::RTPSession* Call::getRTPSession() { return this->mRtpSession; } //WARNING: This is called from the sound player thread void Call::onSoundQueueEmpty() { // Don't notify from this thread, post it on the dum's thread AppDialogSetNotifySoundsEmptyCommand* cmd = new AppDialogSetNotifySoundsEmptyCommand(this); this->mDum.post(cmd); } void Call::notifySoundsEmpty() { // we copy the list because observers could unsubscribe in the meantime auto list = this->mRtpObservers; for (std::list<RTPObserver*>::iterator it = list.begin();it!=list.end();it++) { (*it)->onRTPSessionSoundQueueEmpty(this); } } DialogUsageManager& Call::getDUM() { return this->mDum; } bool Call::isIncomming() { return this->mIncomming; } std::string Call::getDigitQueue() { return this->mDigitQueue; } void Call::clearDigitQueue() { this->mDigitQueue=""; } resip::NameAddr Call::getFrom() { return mFrom; } resip::NameAddr Call::getContact() { return mContact; } std::string Call::getID() { return this->getDialogSetId().getCallId().c_str(); } void Call::onTerminated() { } void Call::toJSON(Dumais::JSON::JSON& json) { Dumais::JSON::JSON& j = json.addObject("call"); j.addValue(getID(),"id"); j.addValue(mFrom.uri().getAor().data(),"from"); j.addValue(mTo.uri().getAor().data(),"to"); }
21.287356
95
0.657127
pdumais
41fa432b5f2d2e2a90f3b00c8d094cbd16c7a44c
3,517
cpp
C++
library/tree/avlTree.cpp
bluedawnstar/algorithm_library
4c7f64ec61fc2ba059b64ad7ba20fcb5b838ced6
[ "Unlicense" ]
40
2017-11-26T05:29:18.000Z
2020-11-13T00:29:26.000Z
library/tree/avlTree.cpp
bluedawnstar/algorithm_library
4c7f64ec61fc2ba059b64ad7ba20fcb5b838ced6
[ "Unlicense" ]
101
2019-02-09T06:06:09.000Z
2021-12-25T16:55:37.000Z
library/tree/avlTree.cpp
bluedawnstar/algorithm_library
4c7f64ec61fc2ba059b64ad7ba20fcb5b838ced6
[ "Unlicense" ]
6
2017-01-03T14:17:58.000Z
2021-01-22T10:37:04.000Z
#include <cassert> #include <functional> #include <algorithm> using namespace std; #include "avlTree.h" /////////// For Testing /////////////////////////////////////////////////////// #include <time.h> #include <cassert> #include <string> #include <numeric> #include <set> #include <vector> #include <iostream> #include "../common/iostreamhelper.h" #include "../common/profile.h" #include "../common/rand.h" static void checkSearch(AVLTree<int>& tree, vector<int>& in) { for (int i = 0; i < int(in.size()); i++) { int x = in[i]; assert(tree.find(x)->value == x); } } static void checkIndex(AVLTree<int>& tree, vector<int>& in) { assert(tree.size() == int(in.size())); for (int i = 0; i < int(in.size()); i++) { assert(tree[i]->value == in[i]); assert(tree.indexOf(tree[i]) == i); } } static int getHeight(const AVLTree<int>::Node* node) { return node == nullptr ? 0 : node->height; } static void checkHeight(AVLTree<int>& tree, AVLTree<int>::Node* node) { if (!node || node == tree.sentinel) return; assert(node->height == max(getHeight(node->left), getHeight(node->right)) + 1); checkHeight(tree, node->left); checkHeight(tree, node->right); } void testAVLTree() { return; //TODO: if you want to test, make this line a comment. cout << "--- AVL Tree -------------------------------" << endl; { AVLTree<int> tree; vector<int> in(1000); iota(in.begin(), in.end(), 0); assert(tree.empty()); { vector<int> t(in); random_shuffle(t.begin(), t.end()); for (int i = 0; i < int(in.size()); i++) { auto p = tree.insert(t[i]); if (!p.second) cerr << "It'll never be shown!" << endl; assert(p.first->value == t[i] && p.second); } checkSearch(tree, in); checkIndex(tree, in); checkHeight(tree, tree.root); } { assert(tree.lowerBound(-1)->value == 0); assert(tree.lowerBound(0)->value == 0); assert(tree.lowerBound(3)->value == 3); assert(tree.lowerBound(77)->value == 77); assert(tree.lowerBound(999)->value == 999); assert(tree.upperBound(0)->value == 1); assert(tree.upperBound(3)->value == 4); assert(tree.upperBound(77)->value == 78); assert(tree.upperBound(999) == tree.nullNode()); auto it = tree.lowerBound(10); auto itE = tree.upperBound(77); for (int i = 10; i < 77; i++) { assert(it->value == i); it = tree.next(it); } for (int i = 76; i >= 10; i--) { it = tree.prev(it); assert(it->value == i); } } { vector<int> t(in), org(in); random_shuffle(t.begin(), t.end()); while (!tree.empty()) { int x = t.back(); t.pop_back(); org.erase(find(org.begin(), org.end(), x)); bool b = tree.erase(x); if (!b) cerr << "It'll never be shown!" << endl; assert(b); assert(tree.size() == int(t.size())); checkSearch(tree, org); checkIndex(tree, org); checkHeight(tree, tree.root); } } } cout << "OK!" << endl; }
29.066116
83
0.473415
bluedawnstar
eedccf4ba5547f7e03ba807485b21e307c9e24cb
9,465
cpp
C++
Simbody/tests/adhoc/OpenSimPartyDemoCable.cpp
elen4/simbody
3ddbc16323afa45b7698c38e07266a7de15e2ad2
[ "Apache-2.0" ]
2
2020-01-15T05:03:30.000Z
2021-01-16T06:18:47.000Z
Simbody/tests/adhoc/OpenSimPartyDemoCable.cpp
sohapouya/simbody
3729532453b22ffa3693962210941184f5617f5b
[ "Apache-2.0" ]
null
null
null
Simbody/tests/adhoc/OpenSimPartyDemoCable.cpp
sohapouya/simbody
3729532453b22ffa3693962210941184f5617f5b
[ "Apache-2.0" ]
1
2021-09-24T15:20:36.000Z
2021-09-24T15:20:36.000Z
/* -------------------------------------------------------------------------- * * Simbody(tm) Adhoc Test: Cable Over Bicubic Surfaces * * -------------------------------------------------------------------------- * * This is part of the SimTK biosimulation toolkit originating from * * Simbios, the NIH National Center for Physics-Based Simulation of * * Biological Structures at Stanford, funded under the NIH Roadmap for * * Medical Research, grant U54 GM072970. See https://simtk.org/home/simbody. * * * * Portions copyright (c) 2012 Stanford University and the Authors. * * Authors: Michael Sherman, Andreas Scholz * * Contributors: * * * * 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. * * -------------------------------------------------------------------------- */ /* Simbody OpenSimPartyDemoCable THIS DOESN'T WORK YET */ #include "Simbody.h" #include <cassert> #include <iostream> using std::cout; using std::endl; using namespace SimTK; // This gets called periodically to dump out interesting things about // the cables and the system as a whole. It also saves states so that we // can play back at the end. static Array_<State> saveStates; class ShowStuff : public PeriodicEventReporter { public: ShowStuff(const MultibodySystem& mbs, const CableSpring& cable1, Real interval) : PeriodicEventReporter(interval), mbs(mbs), cable1(cable1) {} static void showHeading(std::ostream& o) { printf("%8s %10s %10s %10s %10s %10s %10s %10s %10s %12s\n", "time", "length", "rate", "integ-rate", "unitpow", "tension", "disswork", "KE", "PE", "KE+PE-W"); } /** This is the implementation of the EventReporter virtual. **/ void handleEvent(const State& state) const OVERRIDE_11 { const CablePath& path1 = cable1.getCablePath(); printf("%8g %10.4g %10.4g %10.4g %10.4g %10.4g %10.4g %10.4g %10.4g %12.6g CPU=%g\n", state.getTime(), path1.getCableLength(state), path1.getCableLengthDot(state), path1.getIntegratedCableLengthDot(state), path1.calcCablePower(state, 1), // unit power cable1.getTension(state), cable1.getDissipatedEnergy(state), mbs.calcKineticEnergy(state), mbs.calcPotentialEnergy(state), mbs.calcEnergy(state) + cable1.getDissipatedEnergy(state), cpuTime()); saveStates.push_back(state); } private: const MultibodySystem& mbs; CableSpring cable1; }; int main() { try { // Create the system. MultibodySystem system; SimbodyMatterSubsystem matter(system); matter.setShowDefaultGeometry(false); CableTrackerSubsystem cables(system); GeneralForceSubsystem forces(system); Force::Gravity gravity(forces, matter, -YAxis, 9.81); // Force::GlobalDamper(forces, matter, 5); system.setUseUniformBackground(true); // no ground plane in display MobilizedBody Ground = matter.Ground(); // convenient abbreviation // Read in some bones. PolygonalMesh femur; PolygonalMesh tibia; femur.loadVtpFile("CableOverBicubicSurfaces-femur.vtp"); tibia.loadVtpFile("CableOverBicubicSurfaces-tibia.vtp"); femur.scaleMesh(30); tibia.scaleMesh(30); // Build a pendulum Body::Rigid pendulumBodyFemur( MassProperties(1.0, Vec3(0, -5, 0), UnitInertia(1).shiftFromCentroid(Vec3(0, 5, 0)))); pendulumBodyFemur.addDecoration(Transform(), DecorativeMesh(femur).setColor(Vec3(0.8, 0.8, 0.8))); Body::Rigid pendulumBodyTibia( MassProperties(1.0, Vec3(0, -5, 0), UnitInertia(1).shiftFromCentroid(Vec3(0, 5, 0)))); pendulumBodyTibia.addDecoration(Transform(), DecorativeMesh(tibia).setColor(Vec3(0.8, 0.8, 0.8))); Rotation z180(Pi, YAxis); MobilizedBody::Pin pendulumFemur( matter.updGround(), Transform(Vec3(0, 0, 0)), pendulumBodyFemur, Transform(Vec3(0, 0, 0)) ); Rotation rotZ45(-Pi/4, ZAxis); MobilizedBody::Pin pendulumTibia( pendulumFemur, Transform(rotZ45, Vec3(0, -12, 0)), pendulumBodyTibia, Transform(Vec3(0, 0, 0)) ); Real initialPendulumOffset = -0.25*Pi; Constraint::PrescribedMotion pres(matter, new Function::Sinusoid(0.25*Pi, 0.2*Pi, 0*initialPendulumOffset), pendulumTibia, MobilizerQIndex(0)); // Build a wrapping cable path CablePath path2(cables, Ground, Vec3(1, 3, 1), // origin pendulumTibia, Vec3(1, -4, 0)); // termination // Create a bicubic surface Vec3 patchOffset(0, -5, -1); Rotation rotZ90(0.5*Pi, ZAxis); Rotation rotX90(0.2*Pi, XAxis); Rotation patchRotation = rotZ90 * rotX90 * rotZ90; Transform patchTransform(patchRotation, patchOffset); Real patchScaleX = 2.0; Real patchScaleY = 2.0; Real patchScaleF = 0.75; const int Nx = 4, Ny = 4; const Real xData[Nx] = { -2, -1, 1, 2 }; const Real yData[Ny] = { -2, -1, 1, 2 }; const Real fData[Nx*Ny] = { 2, 3, 3, 1, 0, 1.5, 1.5, 0, 0, 1.5, 1.5, 0, 2, 3, 3, 1 }; const Vector x_(Nx, xData); const Vector y_(Ny, yData); const Matrix f_(Nx, Ny, fData); Vector x = patchScaleX*x_; Vector y = patchScaleY*y_; Matrix f = patchScaleF*f_; BicubicSurface patch(x, y, f, 0); Real highRes = 30; Real lowRes = 1; PolygonalMesh highResPatchMesh = patch.createPolygonalMesh(highRes); PolygonalMesh lowResPatchMesh = patch.createPolygonalMesh(lowRes); pendulumFemur.addBodyDecoration(patchTransform, DecorativeMesh(highResPatchMesh).setColor(Cyan).setOpacity(.75)); pendulumFemur.addBodyDecoration(patchTransform, DecorativeMesh(lowResPatchMesh).setRepresentation(DecorativeGeometry::DrawWireframe)); Vec3 patchP(-0.5,-1,2), patchQ(-0.5,1,2); pendulumFemur.addBodyDecoration(patchTransform, DecorativePoint(patchP).setColor(Green).setScale(2)); pendulumFemur.addBodyDecoration(patchTransform, DecorativePoint(patchQ).setColor(Red).setScale(2)); CableObstacle::Surface patchObstacle(path2, pendulumFemur, patchTransform, ContactGeometry::SmoothHeightMap(patch)); patchObstacle.setContactPointHints(patchP, patchQ); patchObstacle.setDisabledByDefault(true); // Sphere Real sphRadius = 1.5; Vec3 sphOffset(0, -0.5, 0); Rotation sphRotation(0*Pi, YAxis); Transform sphTransform(sphRotation, sphOffset); CableObstacle::Surface tibiaSphere(path2, pendulumTibia, sphTransform, ContactGeometry::Sphere(sphRadius)); Vec3 sphP(1.5,-0.5,0), sphQ(1.5,0.5,0); tibiaSphere.setContactPointHints(sphP, sphQ); pendulumTibia.addBodyDecoration(sphTransform, DecorativeSphere(sphRadius).setColor(Red).setOpacity(0.5)); // Make cable a spring CableSpring cable2(forces, path2, 50., 18., 0.1); Visualizer viz(system); viz.setShowFrameNumber(true); system.addEventReporter(new Visualizer::Reporter(viz, 1./30)); system.addEventReporter(new ShowStuff(system, cable2, 0.02)); // Initialize the system and state. system.realizeTopology(); State state = system.getDefaultState(); system.realize(state, Stage::Position); viz.report(state); cout << "path2 init length=" << path2.getCableLength(state) << endl; cout << "Hit ENTER ..."; getchar(); // path1.setIntegratedCableLengthDot(state, path1.getCableLength(state)); // Simulate it. saveStates.clear(); saveStates.reserve(2000); // RungeKutta3Integrator integ(system); RungeKuttaMersonIntegrator integ(system); // CPodesIntegrator integ(system); // integ.setAllowInterpolation(false); integ.setAccuracy(1e-5); TimeStepper ts(system, integ); ts.initialize(state); ShowStuff::showHeading(cout); const Real finalTime = 10; const double startTime = realTime(); ts.stepTo(finalTime); cout << "DONE with " << finalTime << "s simulated in " << realTime()-startTime << "s elapsed.\n"; while (true) { cout << "Hit ENTER FOR REPLAY, Q to quit ..."; const char ch = getchar(); if (ch=='q' || ch=='Q') break; for (unsigned i=0; i < saveStates.size(); ++i) viz.report(saveStates[i]); } } catch (const std::exception& e) { cout << "EXCEPTION: " << e.what() << "\n"; } }
36.125954
108
0.609192
elen4
eedff2bbd0219385c868326074ac9a8d18cea3b7
100,758
cpp
C++
src/gdt/gdt_utils.cpp
dfranusic/mink-core
98b4ab8d6322a5593ab6c05132473753915a3bb8
[ "MIT" ]
1
2022-01-28T22:29:14.000Z
2022-01-28T22:29:14.000Z
src/gdt/gdt_utils.cpp
dfranusic/mink-core
98b4ab8d6322a5593ab6c05132473753915a3bb8
[ "MIT" ]
28
2021-08-31T09:27:36.000Z
2022-03-17T13:57:56.000Z
src/gdt/gdt_utils.cpp
dfranusic/mink-core
98b4ab8d6322a5593ab6c05132473753915a3bb8
[ "MIT" ]
5
2021-08-25T13:20:39.000Z
2022-01-27T18:04:15.000Z
/* _ _ * _ __ ___ (_)_ __ | | __ * | '_ ` _ \| | '_ \| |/ / * | | | | | | | | | | < * |_| |_| |_|_|_| |_|_|\_\ * * SPDX-License-Identifier: MIT * */ #include <endian.h> #include <errno.h> #include <iomanip> #include <gdt_utils.h> bool gdt::ServiceParam::FRAGMENTATION_DONE = false; bool gdt::ServiceParam::FRAGMENTATION_NEXT = true; gdt::ServiceMessageAsyncDone gdt::ServiceMsgManager::cb_async_done; gdt::ServiceParam::ServiceParam() : data_size(0), total_data_size(0), type(SPT_UNKNOWN), id(0), index(0), extra_type(0), thread_safe(false), fragmented(false), linked_index(0), param_fctry(nullptr), fragments(0), fragment_index(0) { memset(data, 0, sizeof(data)); data_p = data; in_data_p = data_p; param_data_cb = &param_data_default; pthread_mutex_init(&mtx, nullptr); } gdt::ServiceParam::~ServiceParam() { pthread_mutex_destroy(&mtx); } void gdt::ServiceParam::fragment(const void *_data, unsigned int _data_size) { // set in data pointer in_data_p = _data; // set first fragment data data_size = 256; total_data_size = _data_size; // get param count needed to fit data size int pc = _data_size / 256; // remainder int rem = _data_size % 256; // set fragment index fragment_index = 0; // set total number of fragments fragments = pc + ((rem > 0) ? 1 : 0); // set fragmentation flag fragmented = true; } int gdt::ServiceParam::param_data_file(ServiceParam *sc_param, const void *in, int in_size) { FILE *f = (FILE *)in; // get tmp service param buffer if (sc_param->linked_index >= sc_param->linked.size()) sc_param->linked_index = 0; ServiceParam *new_sc_param = sc_param->linked[sc_param->linked_index++]; // read file int bc = fread(new_sc_param->data, 1, sizeof(new_sc_param->data), f); // decrement from previous fread sc_param->total_data_size -= sc_param->data_size; // switch buffer of original param with new one sc_param->data_p = new_sc_param->data; // set data size sc_param->data_size = bc; return bc; } int gdt::ServiceParam::param_data_default(ServiceParam *sc_param, const void *in, int in_size) { // calculate number of bytes needed for current fragment int bc = (sc_param->total_data_size > sizeof(sc_param->data) ? sizeof(sc_param->data) : sc_param->total_data_size); sc_param->data_p += bc; sc_param->total_data_size -= bc; return bc; } int gdt::ServiceParam::set_data(FILE *_data, unsigned int _file_size) { lock(); if (_file_size > 256) { // file param data fetch method param_data_cb = &param_data_file; // fragmentation fragment(_data, _file_size); // read initial block data_size = fread(data, 1, 256, _data); // data_p points to internal buffer data_p = data; unlock(); return 0; } fragmented = false; // read initial block data_size = fread(data, 1, 256, _data); total_data_size = data_size; data_p = data; unlock(); return 0; } void gdt::ServiceParam::set(mink_utils::VariantParam *vparam) { switch (vparam->get_type()) { case mink_utils::DPT_INT: { uint64_t tmp = htobe64(vparam->get_data()->i64); set_data(&tmp, sizeof(tmp)); extra_type = vparam->get_type(); break; } case mink_utils::DPT_STRING: case mink_utils::DPT_OCTETS: set_data(vparam->get_data()->str, vparam->get_size()); extra_type = vparam->get_type(); break; case mink_utils::DPT_DOUBLE: set_data(&vparam->get_data()->d, vparam->get_size()); extra_type = vparam->get_type(); break; case mink_utils::DPT_CHAR: set_data(&vparam->get_data()->c, vparam->get_size()); extra_type = vparam->get_type(); break; case mink_utils::DPT_BOOL: set_data(&vparam->get_data()->b, vparam->get_size()); extra_type = vparam->get_type(); break; default: break; } } int gdt::ServiceParam::set_data(const void *_data, unsigned int _data_size) { lock(); if (_data_size > 256) { // default param data fetch method param_data_cb = &param_data_default; // fragmentation fragment(_data, _data_size); // set data pointer (fragmented stream does not imply copying of data) data_p = (unsigned char *)_data; unlock(); return 0; } fragmented = false; memcpy(data, _data, _data_size); data_size = _data_size; total_data_size = _data_size; data_p = data; unlock(); return 0; } void gdt::ServiceParam::std_out() { lock(); std::cout << data << std::endl; unlock(); } unsigned char *gdt::ServiceParam::get_data() { return data; } unsigned char *gdt::ServiceParam::get_data_p() { return data_p; } void gdt::ServiceParam::set_data_p(unsigned char *_data_p) { data_p = _data_p; } void gdt::ServiceParam::reset_data_p() { data_p = data; in_data_p = data_p; } int gdt::ServiceParam::get_data_size() { lock(); unsigned int tmp = data_size; unlock(); return tmp; } void gdt::ServiceParam::inc_total_data_size(unsigned int _inc) { total_data_size += _inc; ++fragment_index; } int gdt::ServiceParam::get_total_data_size() const { return total_data_size; } void gdt::ServiceParam::reset() { lock(); data_size = 0; unlock(); id = 0; fragmented = false; param_data_cb = &param_data_default; } void gdt::ServiceParam::set_thread_safety(bool _thread_safe) { thread_safe = _thread_safe; } void gdt::ServiceParam::set_param_factory(ServiceParamFactory *_pfact) { param_fctry = _pfact; } bool gdt::ServiceParam::is_fragmented() const { return fragmented; } bool *gdt::ServiceParam::get_fragmentation_p() { return &fragmented; } uint32_t gdt::ServiceParam::get_index() const { return index; } int gdt::ServiceParam::get_extra_type() const { return extra_type; } void gdt::ServiceParam::set_extra_type(int _type) { extra_type = _type; } int gdt::ServiceParam::get_fragment_index() const { return fragment_index; } void gdt::ServiceParam::set_fragmented(bool _fragmented) { fragmented = _fragmented; } void gdt::ServiceParam::set_callback(GDTEventType _type, GDTCallbackMethod *cback) { cb_handler.set_callback(_type, cback); } bool gdt::ServiceParam::process_callback(GDTEventType _type, GDTCallbackArgs *args) { return cb_handler.process_callback(_type, args); } void gdt::ServiceParam::clear_callbacks() { cb_handler.clear(); } void gdt::ServiceParam::lock() { if (thread_safe) pthread_mutex_lock(&mtx); } void gdt::ServiceParam::unlock() { if (thread_safe) pthread_mutex_unlock(&mtx); } gdt::ServiceParamType gdt::ServiceParam::get_type() const { return type; } void gdt::ServiceParam::set_id(uint32_t _id) { id = htobe32(_id); } void gdt::ServiceParam::set_index(uint32_t idx) { index = idx; } uint32_t gdt::ServiceParam::get_id() const { return be32toh(id); } uint32_t *gdt::ServiceParam::get_idp() { return &id; } gdt::ServiceParamVARIANT::ServiceParamVARIANT() { type = SPT_VARIANT; } gdt::ServiceParamVARIANT::~ServiceParamVARIANT() = default; int gdt::ServiceParamVARIANT::extract(void *_out) { lock(); switch (extra_type) { case mink_utils::DPT_INT: { auto res = (uint64_t *)_out; auto src = (uint64_t *)data; // Big endian -> little endian *res = be64toh(*src); break; } default: memcpy(_out, data, data_size); break; } unlock(); return 0; } int gdt::ServiceParamVARIANT::set_data(const void *_data, unsigned int _data_size) { return ServiceParam::set_data(_data, _data_size); } void gdt::ServiceParamVARIANT::std_out() { lock(); for (unsigned int k = 0; k < data_size; k++) { std::cout << std::setfill('0') << std::setw(2) << std::hex << (int)(data[k] & 0xff) << " "; } unlock(); std::cout << std::dec << std::endl; } gdt::ServiceParamUNKNOWN::ServiceParamUNKNOWN() { type = SPT_UNKNOWN; } gdt::ServiceParamUNKNOWN::~ServiceParamUNKNOWN() = default; int gdt::ServiceParamUNKNOWN::extract(void *_out) { lock(); memcpy(_out, data, data_size); unlock(); return 0; } int gdt::ServiceParamUNKNOWN::set_data(const void *_data, unsigned int _data_size) { return ServiceParam::set_data(_data, _data_size); } void gdt::ServiceParamUNKNOWN::std_out() { lock(); for (unsigned int k = 0; k < data_size; k++) { std::cout << std::setfill('0') << std::setw(2) << std::hex << (int)(data[k] & 0xff) << " "; } unlock(); std::cout << std::dec << std::endl; } gdt::ServiceParamBOOL::ServiceParamBOOL() { type = SPT_BOOL; } gdt::ServiceParamBOOL::~ServiceParamBOOL() = default; int gdt::ServiceParamBOOL::extract(void *_out) { auto res = (bool *)_out; auto src = (bool *)data; lock(); *res = *src; unlock(); // success return 0; } int gdt::ServiceParamBOOL::set_bool(bool _data) { return ServiceParam::set_data(&_data, sizeof(bool)); } void gdt::ServiceParamBOOL::std_out() { auto tmp = (bool *)data; lock(); std::cout << *tmp << std::endl; unlock(); } gdt::ServiceParamUINT32::ServiceParamUINT32() { type = SPT_UINT32; } gdt::ServiceParamUINT32::~ServiceParamUINT32() = default; int gdt::ServiceParamUINT32::extract(void *_out) { auto res = (uint32_t *)_out; auto src = (uint32_t *)data; lock(); // Big endian -> little endian *res = be32toh(*src); unlock(); // success return 0; } int gdt::ServiceParamUINT32::set_uint32(uint32_t _data) { uint32_t tmp = htobe32(_data); return ServiceParam::set_data(&tmp, sizeof(uint32_t)); } void gdt::ServiceParamUINT32::std_out() { auto tmp = (uint32_t *)data; lock(); std::cout << be32toh(*tmp) << std::endl; unlock(); } gdt::ServiceParamUINT64::ServiceParamUINT64() { type = SPT_UINT64; } gdt::ServiceParamUINT64::~ServiceParamUINT64() = default; void gdt::ServiceParamUINT64::std_out() { auto tmp = (uint64_t *)data; lock(); std::cout << be64toh(*tmp) << std::endl; unlock(); } int gdt::ServiceParamUINT64::extract(void *_out) { auto res = (uint64_t *)_out; auto src = (uint64_t *)data; lock(); // Big endian -> little endian *res = be64toh(*src); unlock(); // success return 0; } int gdt::ServiceParamUINT64::set_uint64(uint64_t _data) { uint64_t tmp = htobe64(_data); return ServiceParam::set_data(&tmp, sizeof(uint64_t)); } gdt::ServiceParamCString::ServiceParamCString() { type = SPT_CSTRING; } gdt::ServiceParamCString::~ServiceParamCString() = default; int gdt::ServiceParamCString::extract(void *_out) { auto _out_cs = (char *)_out; lock(); strncpy(_out_cs, (char *)data, strlen((char *)data) + 1); unlock(); // success return 0; } void gdt::ServiceParamCString::set_cstring(const char *cstring) { if (cstring == nullptr) { data_size = 0; return; } set_data(cstring, strnlen(cstring, (sizeof(data) - 1) + 1)); } gdt::ServiceParamOctets::ServiceParamOctets() { type = SPT_OCTETS; } gdt::ServiceParamOctets::~ServiceParamOctets() = default; int gdt::ServiceParamOctets::extract(void *_out) { lock(); memcpy(_out, data, data_size); unlock(); // success return 0; } void gdt::ServiceParamOctets::std_out() { lock(); for (unsigned int k = 0; k < data_size; k++) { std::cout << std::setfill('0') << std::setw(2) << std::hex << (int)(data[k] & 0xff) << " "; } unlock(); std::cout << std::dec << std::endl; } gdt::ServiceParamFactory::ServiceParamFactory(bool _pooled, bool _th_safe, unsigned int pool_size) { pooled = _pooled; if (pooled) { cstr_pool.init(pool_size); cstr_pool.construct_objects(); oct_pool.init(pool_size); oct_pool.construct_objects(); uint32_pool.init(pool_size); uint32_pool.construct_objects(); uint64_pool.init(pool_size); uint64_pool.construct_objects(); unknown_pool.init(pool_size); unknown_pool.construct_objects(); bool_pool.init(pool_size); bool_pool.construct_objects(); var_pool.init(pool_size); var_pool.construct_objects(); ServiceParam *tmp_arr[pool_size]; // cstr for (unsigned int i = 0; i < pool_size; i++) { tmp_arr[i] = cstr_pool.allocate_constructed(); tmp_arr[i]->set_thread_safety(_th_safe); tmp_arr[i]->set_param_factory(this); } for (unsigned int i = 0; i < pool_size; i++) cstr_pool.deallocate_constructed((ServiceParamCString *)tmp_arr[i]); // oct for (unsigned int i = 0; i < pool_size; i++) { tmp_arr[i] = oct_pool.allocate_constructed(); tmp_arr[i]->set_thread_safety(_th_safe); tmp_arr[i]->set_param_factory(this); } for (unsigned int i = 0; i < pool_size; i++) oct_pool.deallocate_constructed((ServiceParamOctets *)tmp_arr[i]); // uint32 for (unsigned int i = 0; i < pool_size; i++) { tmp_arr[i] = uint32_pool.allocate_constructed(); tmp_arr[i]->set_thread_safety(_th_safe); tmp_arr[i]->set_param_factory(this); } for (unsigned int i = 0; i < pool_size; i++) uint32_pool.deallocate_constructed( (ServiceParamUINT32 *)tmp_arr[i]); // uint64 for (unsigned int i = 0; i < pool_size; i++) { tmp_arr[i] = uint64_pool.allocate_constructed(); tmp_arr[i]->set_thread_safety(_th_safe); tmp_arr[i]->set_param_factory(this); } for (unsigned int i = 0; i < pool_size; i++) uint64_pool.deallocate_constructed( (ServiceParamUINT64 *)tmp_arr[i]); // unknown for (unsigned int i = 0; i < pool_size; i++) { tmp_arr[i] = unknown_pool.allocate_constructed(); tmp_arr[i]->set_thread_safety(_th_safe); tmp_arr[i]->set_param_factory(this); } for (unsigned int i = 0; i < pool_size; i++) unknown_pool.deallocate_constructed( (ServiceParamUNKNOWN *)tmp_arr[i]); // bool for (unsigned int i = 0; i < pool_size; i++) { tmp_arr[i] = bool_pool.allocate_constructed(); tmp_arr[i]->set_thread_safety(_th_safe); tmp_arr[i]->set_param_factory(this); } for (unsigned int i = 0; i < pool_size; i++) bool_pool.deallocate_constructed((ServiceParamBOOL *)tmp_arr[i]); // var for (unsigned int i = 0; i < pool_size; i++) { tmp_arr[i] = var_pool.allocate_constructed(); tmp_arr[i]->set_thread_safety(_th_safe); tmp_arr[i]->set_param_factory(this); } for (unsigned int i = 0; i < pool_size; i++) var_pool.deallocate_constructed((ServiceParamVARIANT *)tmp_arr[i]); } } gdt::ServiceParamFactory::~ServiceParamFactory() = default; gdt::ServiceParam *gdt::ServiceParamFactory::new_param(ServiceParamType param_type) { ServiceParam *tmp = nullptr; if (pooled) { switch (param_type) { case SPT_CSTRING: tmp = cstr_pool.allocate_constructed(); break; case SPT_OCTETS: tmp = oct_pool.allocate_constructed(); break; case SPT_UINT32: tmp = uint32_pool.allocate_constructed(); break; case SPT_UINT64: tmp = uint64_pool.allocate_constructed(); break; case SPT_BOOL: tmp = bool_pool.allocate_constructed(); break; case SPT_VARIANT: tmp = var_pool.allocate_constructed(); break; default: tmp = unknown_pool.allocate_constructed(); break; } } else { switch (param_type) { case SPT_CSTRING: tmp = new ServiceParamCString(); break; case SPT_OCTETS: tmp = new ServiceParamOctets(); break; case SPT_UINT32: tmp = new ServiceParamUINT32(); break; case SPT_UINT64: tmp = new ServiceParamUINT64(); break; case SPT_BOOL: tmp = new ServiceParamBOOL(); break; case SPT_VARIANT: tmp = new ServiceParamVARIANT(); break; default: tmp = new ServiceParamUNKNOWN(); break; } } return tmp; } int gdt::ServiceParamFactory::free_param(ServiceParam *param) { if (param == nullptr) return 5; if (pooled) { int res = 0; switch (param->get_type()) { case SPT_CSTRING: res = cstr_pool.deallocate_constructed((ServiceParamCString *)param); break; case SPT_OCTETS: res = oct_pool.deallocate_constructed((ServiceParamOctets *)param); break; case SPT_UINT32: res = uint32_pool.deallocate_constructed((ServiceParamUINT32 *)param); break; case SPT_UINT64: res = uint64_pool.deallocate_constructed((ServiceParamUINT64 *)param); break; case SPT_UNKNOWN: res = unknown_pool.deallocate_constructed( (ServiceParamUNKNOWN *)param); break; case SPT_BOOL: res = bool_pool.deallocate_constructed((ServiceParamBOOL *)param); break; case SPT_VARIANT: res = var_pool.deallocate_constructed((ServiceParamVARIANT *)param); break; default: res = 7; break; } return res; } else { delete param; return 0; } } gdt::ParamIdTypeMap::~ParamIdTypeMap() = default; int gdt::ParamIdTypeMap::add(uint32_t _id, ServiceParamType _type) { idtmap[_id] = _type; return 0; } int gdt::ParamIdTypeMap::remove(uint32_t id) { idtmap.erase(id); return 0; } gdt::ServiceParamType gdt::ParamIdTypeMap::get(uint32_t id) { // find auto it = idtmap.find(id); if (it != idtmap.end()) return it->second; return SPT_UNKNOWN; } int gdt::ParamIdTypeMap::clear() { idtmap.clear(); return 0; } gdt::ServiceMessageDone::ServiceMessageDone() { usr_method = nullptr; status = 0; smsg = nullptr; } void gdt::ServiceMessageDone::run(GDTCallbackArgs *args) { auto in_msg = (asn1::GDTMessage *)args->get_arg(gdt::GDT_CB_INPUT_ARGS, gdt::GDT_CB_ARG_IN_MSG); auto in_sess = (uint64_t *)args->get_arg(gdt::GDT_CB_INPUT_ARGS, gdt::GDT_CB_ARG_IN_MSG_ID); // check status (in_msg is nullptr in case if stream timeout) if ((in_msg != nullptr) && (in_msg->_header->_status != nullptr)) { if (in_msg->_header->_status->has_linked_data(*in_sess)) { status = in_msg->_header->_status->linked_node->tlv->value[0]; } // stream timeout error } else status = 300; // run user handler (async mode) if (usr_method != nullptr) { args->add_arg(GDT_CB_INPUT_ARGS, GDT_CB_ARGS_SRVC_MSG, smsg); usr_method->run(args); } // signal smsg->signal_post(); } static void process_fragments(unsigned int *bc, unsigned int *tbc, const gdt::ServiceParam *sc_param, asn1::Parameters *params, unsigned int idx){ // calculate number of bytes needed for current fragment *bc = (sc_param->get_total_data_size() > gdt::ServiceParam::DATA_SZ ? gdt::ServiceParam::DATA_SZ : sc_param->get_total_data_size()); // check if more allocations are needed if (params->get_child(idx) == nullptr) { params->set_child(idx); params->get_child(idx)->set_value(); params->get_child(idx)->_value->set_child(0); params->get_child(idx)->_value->set_child(1); params->get_child(idx)->_value->set_child(2); params->get_child(idx)->_value->set_child(3); // prepare asn1::prepare(params, params->parent_node); } // update total byte count *tbc += *bc + 25; } void gdt::ServiceMessageNext::run(GDTCallbackArgs *args) { auto stream = (gdt::GDTStream *)args->get_arg(gdt::GDT_CB_INPUT_ARGS, gdt::GDT_CB_ARG_STREAM); asn1::GDTMessage *gdtm = stream->get_gdt_message(); auto include_body = (bool *)args->get_arg(gdt::GDT_CB_INPUT_ARGS, gdt::GDT_CB_ARG_BODY); // param map std::vector<ServiceParam *> *pmap = smsg->get_param_map(); // more segments if (pindex < pc) { unsigned int bc; unsigned int tbc = 0; // prepare body if (gdtm->_body != nullptr) { gdtm->_body->unlink(1); gdtm->_body->_service_msg->set_linked_data(1); } else { gdtm->set_body(); gdtm->prepare(); } asn1::ServiceMessage *sm = gdtm->_body->_service_msg; // set params, allocate 10 initial children if (sm->_params == nullptr) { sm->set_params(); // set children, allocate more for (int i = 0; i < 10; i++) { sm->_params->set_child(i); sm->_params->get_child(i)->set_value(); sm->_params->get_child(i)->_value->set_child(0); sm->_params->get_child(i)->_value->set_child(1); sm->_params->get_child(i)->_value->set_child(2); sm->_params->get_child(i)->_value->set_child(3); } // prepare asn1::prepare(sm, sm->parent_node); } // set service id sm->_service_id->set_linked_data(1, (unsigned char *)smsg->get_service_idp(), sizeof(uint32_t)); // set service action sm->_service_action->set_linked_data(1, (unsigned char *)smsg->get_service_actionp(), 1); // params ServiceParam *sc_param = nullptr; asn1::Parameters *params = sm->_params; unsigned int j; for (j = 0; (tbc < ServiceMsgManager::MAX_PARAMS_SIZE) && (pos < pmap->size()); pos++, j++, pindex++) { sc_param = (*pmap)[pos]; // check if more allocations are needed if (params->get_child(j) == nullptr) { params->set_child(j); params->get_child(j)->set_value(); params->get_child(j)->_value->set_child(0); params->get_child(j)->_value->set_child(1); params->get_child(j)->_value->set_child(2); params->get_child(j)->_value->set_child(3); // prepare asn1::prepare(params, params->parent_node); } // check fragmentation if (sc_param->fragmented) { // process fragments while ((tbc < ServiceMsgManager::MAX_PARAMS_SIZE) && (sc_param->fragment_index < sc_param->fragments)) { process_fragments(&bc, &tbc, sc_param, params, j); // check if limit reached if (tbc > ServiceMsgManager::MAX_PARAMS_SIZE) break; // set gdt values params->get_child(j) ->_id->set_linked_data(1, (unsigned char *)sc_param->get_idp(), sizeof(uint32_t)); params->get_child(j) ->_value ->get_child(0) ->set_linked_data(1, sc_param->data_p, bc); // variant param id index and type params->get_child(j) ->_value ->get_child(2) ->set_linked_data(1, (unsigned char *)&sc_param->index, 1); params->get_child(j) ->_value ->get_child(3) ->set_linked_data(1, (unsigned char *)&sc_param->extra_type, 1); // check if last fragment, disable fragmentation flag (last // fragment must not contain fragmentation flag) if (sc_param->fragment_index == (sc_param->fragments - 1)) { // set gdt fragmentation flag params->get_child(j) ->_value ->get_child(1) ->set_linked_data(1, (unsigned char*)&ServiceParam::FRAGMENTATION_DONE, 1); } else { // set gdt fragmentation flag params->get_child(j) ->_value ->get_child(1) ->set_linked_data(1, (unsigned char*)&ServiceParam::FRAGMENTATION_NEXT, 1); } // next ++sc_param->fragment_index; ++j; ++pindex; // run data fetch method (*sc_param->param_data_cb)(sc_param, sc_param->in_data_p, sc_param->total_data_size); } // break if fragmentation in progress and not finished (to skip // increment, next call should process the same param again) if (sc_param->fragment_index < sc_param->fragments) break; // rewind gdt param child count and packet index else { --j; --pindex; } // no fragmentation } else { // update total byte count tbc += sc_param->data_size + 25; // check if limit reached if (tbc > ServiceMsgManager::MAX_PARAMS_SIZE) break; params->get_child(j) ->_id->set_linked_data(1, (unsigned char *)sc_param->get_idp(), sizeof(uint32_t)); params->get_child(j) ->_value ->get_child(0) ->set_linked_data(1, sc_param->data, sc_param->data_size); params->get_child(j) ->_value ->get_child(1) ->set_linked_data(1, (unsigned char *)&ServiceParam::FRAGMENTATION_DONE, 1); params->get_child(j) ->_value ->get_child(2) ->set_linked_data(1, (unsigned char *)&sc_param->index, 1); params->get_child(j) ->_value ->get_child(3) ->set_linked_data(1, (unsigned char *)&sc_param->extra_type, 1); } } // remove unused chidren for (; j < params->children.size(); j++) params->get_child(j)->unlink(1); // include body *include_body = true; // continue if (pindex < pc) stream->continue_sequence(); } } gdt::ServiceMessage::ServiceMessage() : missing_params(false), idt_map(nullptr), service_id(0), service_action(0), smsg_m(nullptr), frag_param(nullptr), auto_free(true) { sem_init(&smsg_sem, 0, 0); sem_init(&new_param_sem, 0, 0); msg_done.smsg = this; msg_next.smsg = this; } gdt::ServiceMessage::~ServiceMessage() { tlvs.clear(); } int gdt::ServiceMessage::add_param(uint32_t id, ServiceParam *param, uint32_t index) { tlvs.push_back(param); param->set_id(id); param->index = index; return 0; } int gdt::ServiceMessage::remove_param(uint32_t id) { for (unsigned int i = 0; i < tlvs.size(); i++) if (tlvs[i]->get_id() == id) { tlvs.erase(tlvs.begin() + i); } return 0; } int gdt::ServiceMessage::get_param(uint32_t id, std::vector<ServiceParam *> *out) const { std::all_of(tlvs.cbegin(), tlvs.cend(), [out, id](ServiceParam *p) { if (p->get_id() == id) out->push_back(p); return true; }); return 0; } int gdt::ServiceMessage::reset() { ServiceMsgManager *sm = get_smsg_manager(); std::all_of(tlvs.cbegin(), tlvs.cend(), [sm](ServiceParam *p) { sm->get_param_factory()->free_param(p); return true; }); tlvs.clear(); return 0; } uint32_t gdt::ServiceMessage::get_service_id() const { return be32toh(service_id); } uint32_t *gdt::ServiceMessage::get_service_idp() { return &service_id; } uint32_t gdt::ServiceMessage::get_service_action() const { return be32toh(service_action); } uint32_t *gdt::ServiceMessage::get_service_actionp() { return &service_action; } void gdt::ServiceMessage::set_service_id(uint32_t _service_id) { service_id = htobe32(_service_id); } void gdt::ServiceMessage::set_service_action(uint32_t _service_action) { service_action = htobe32(_service_action); } void gdt::ServiceMessage::set_smsg_manager(ServiceMsgManager *_smsg_m) { smsg_m = _smsg_m; } gdt::ServiceMsgManager *gdt::ServiceMessage::get_smsg_manager() { return smsg_m; } gdt::ServiceParam *gdt::ServiceMessage::get_frag_param() { return frag_param; } void gdt::ServiceMessage::set_frag_param(ServiceParam *_frag_param) { frag_param = _frag_param; if (frag_param != nullptr) frag_param->fragment_index = 0; } bool gdt::ServiceMessage::is_complete() { return complete.get(); } bool gdt::ServiceMessage::set_complete(bool _is_complete) { return complete.comp_swap(!_is_complete, _is_complete); } bool gdt::ServiceMessage::set_auto_free(bool _auto_free) { auto_free = _auto_free; return auto_free; } bool gdt::ServiceMessage::get_auto_free() const { return auto_free; } void gdt::ServiceMessage::set_callback(GDTEventType type, GDTCallbackMethod *cback) { cb_handler.set_callback(type, cback); } bool gdt::ServiceMessage::process_callback(GDTEventType type, GDTCallbackArgs *args) { return cb_handler.process_callback(type, args); } void gdt::ServiceMessage::clear_callbacks() { cb_handler.clear(); } std::vector<gdt::ServiceParam *> *gdt::ServiceMessage::get_param_map() { return &tlvs; } mink_utils::VariantParam *gdt::ServiceMessage::vpget(uint32_t id, uint32_t index, uint32_t fragment, uint32_t context) { return vpmap.get_param(id, index, fragment, context); } mink_utils::VariantParam *gdt::ServiceMessage::vpset(uint32_t id, const std::string &s, uint32_t index, uint32_t fragment, uint32_t context) { return vpmap.set_cstr(id, s.c_str(), index, fragment, context); } gdt::ServiceMessageDone *gdt::ServiceMessage::get_sdone_hndlr() { return &msg_done; } gdt::ServiceMessageNext *gdt::ServiceMessage::get_snext_hndlr() { return &msg_next; } int gdt::ServiceMessage::signal_wait() { // wait for signal timespec ts; clock_gettime(0, &ts); ts.tv_sec += 5; int sres = sem_wait(&smsg_sem); // error check if (sres == -1) { return 1; } // ok return 0; } int gdt::ServiceMessage::signal_post() { return sem_post(&smsg_sem); } void gdt::ServiceMessage::set_idt_map(ParamIdTypeMap *idtm) { idt_map = idtm; } gdt::ServiceStreamHandlerNext::ServiceStreamHandlerNext(): ssh_new(nullptr){} void gdt::ServiceStreamHandlerNext::run(GDTCallbackArgs *args) { auto stream = (gdt::GDTStream *)args->get_arg(gdt::GDT_CB_INPUT_ARGS, gdt::GDT_CB_ARG_STREAM); auto in_msg = (asn1::GDTMessage *)args->get_arg(gdt::GDT_CB_INPUT_ARGS, gdt::GDT_CB_ARG_IN_MSG); auto in_sess = (uint64_t *)args->get_arg(gdt::GDT_CB_INPUT_ARGS, gdt::GDT_CB_ARG_IN_MSG_ID); GDTCallbackArgs cb_args; // check for params part if ((in_msg->_body->_service_msg->_params != nullptr) && (in_msg->_body->_service_msg->_params->has_linked_data(*in_sess))) { // get ID->TYPE map ParamIdTypeMap *idt_map = ssh_new->smsg_m->get_idt_map(); // set default param type ServiceParamType ptype = SPT_UNKNOWN; // declare param pointer ServiceParam *sparam = nullptr; // param id pointer uint32_t *param_id = nullptr; // raw data pointer char *tmp_val = nullptr; // ServiceMessage pointer auto smsg = (ServiceMessage *)stream->get_param(SMSG_PT_SMSG); // nullptr check if (smsg != nullptr) { // fragmentation bool frag = false; asn1::ServiceMessage *sm = in_msg->_body->_service_msg; // service id if (sm->_service_id->has_linked_data(*in_sess)) { auto tmp_ui32 = (uint32_t *)sm->_service_id ->linked_node ->tlv ->value; smsg->set_service_id(be32toh(*tmp_ui32)); } // process params for (unsigned int i = 0; i < sm->_params->children.size(); i++) { // check for value if (!sm->_params ->get_child(i) ->_value) continue; // check if value exists in current session if (!sm->_params ->get_child(i) ->_value ->has_linked_data(*in_sess)) continue; // check if child exists if (!sm->_params ->get_child(i) ->_value ->get_child(0)) continue; // check if child exists in current sesion if (!sm->_params ->get_child(i) ->_value ->get_child(0) ->has_linked_data(*in_sess)) continue; // getr param id param_id = (uint32_t *)sm->_params ->get_child(i) ->_id ->linked_node ->tlv ->value; // get param type by id ptype = idt_map->get(be32toh(*param_id)); // get extra type int extra_type = sm->_params ->get_child(i) ->_value ->get_child(3) ->linked_node ->tlv ->value[0]; // create param sparam = ssh_new->smsg_m->get_param_factory() ->new_param((extra_type > 0) ? SPT_VARIANT : ptype); // fragmentatio flag frag = false; if (sparam != nullptr) { // set id sparam->set_id(be32toh(*param_id)); // reset data pointer sparam->reset_data_p(); // reset index and extra type sparam->index = 0; sparam->extra_type = 0; // get raw data tmp_val = (char *)sm->_params ->get_child(i) ->_value ->get_child(0) ->linked_node ->tlv ->value; int tmp_val_l = sm->_params ->get_child(i) ->_value ->get_child(0) ->linked_node ->tlv ->value_length; // set service param data sparam->set_data(tmp_val, tmp_val_l); // check for fragmentation if ((sm->_params ->get_child(i) ->_value ->get_child(1)) && (sm->_params ->get_child(i) ->_value ->get_child(1) ->has_linked_data(*in_sess))) { const asn1::TLVNode *tlv = sm->_params ->get_child(i) ->_value ->get_child(1) ->linked_node ->tlv; // fragmentation flag (value // length 1 and value 1) if ((tlv->value_length == 1) && (tlv->value[0] == 1)) { frag = true; } } // variant param id index and type sparam->index = sm->_params ->get_child(i) ->_value ->get_child(2) ->linked_node ->tlv ->value[0]; sparam->extra_type = extra_type; // set fragmentation flag and pointer to // first fragment if (frag) { sparam->set_fragmented(true); // first fragment if (!smsg->get_frag_param()) { // set first fragment pointer smsg->set_frag_param(sparam); sparam->fragment_index = 0; // reset callbacks sparam->clear_callbacks(); // process vparam if (sparam->get_type() == SPT_VARIANT) { smsg->vpmap.set_octets(sparam->get_id(), sparam->get_data(), sparam->get_data_size(), sparam->get_index(), smsg->get_frag_param() ->get_fragment_index()); } // run callback cb_args.clear_all_args(); cb_args.add_arg(GDT_CB_INPUT_ARGS, GDT_CB_ARGS_SRVC_MSG, smsg); cb_args.add_arg(GDT_CB_INPUT_ARGS, GDT_CB_ARGS_SRVC_PARAM, sparam); smsg->process_callback(GDT_ET_SRVC_PARAM_STREAM_NEW, &cb_args); // more fragments } else { smsg->get_frag_param() ->inc_total_data_size(sparam->get_data_size()); // process vparam if (sparam->get_type() == SPT_VARIANT) { smsg->vpmap.set_octets(sparam->get_id(), sparam->get_data(), sparam->get_data_size(), sparam->get_index(), smsg->get_frag_param() ->get_fragment_index()); } // run callback cb_args.clear_all_args(); cb_args.add_arg(GDT_CB_INPUT_ARGS, GDT_CB_ARGS_SRVC_MSG, smsg); cb_args.add_arg(GDT_CB_INPUT_ARGS, GDT_CB_ARGS_SRVC_PARAM, sparam); smsg->get_frag_param() ->process_callback(GDT_ET_SRVC_PARAM_STREAM_NEXT, &cb_args); // return to pool (fragmented // params are not retained in // memory) ssh_new->smsg_m ->get_param_factory() ->free_param(sparam); } // no fragmentation or last fragment } else { // last fragment if (smsg->get_frag_param()) { sparam->set_fragmented(true); smsg->get_frag_param() ->inc_total_data_size(sparam->get_data_size()); // process vparam if (sparam->get_type() == SPT_VARIANT) { smsg->vpmap.set_octets(sparam->get_id(), sparam->get_data(), sparam->get_data_size(), sparam->get_index(), smsg->get_frag_param() ->get_fragment_index()); mink_utils::VariantParam *vparam = smsg->vpmap.defragment(sparam->get_id(), sparam->get_index()); if (vparam) vparam->set_type((mink_utils::VariantParamType)sparam->get_extra_type()); } // run callback cb_args.clear_all_args(); cb_args.add_arg(GDT_CB_INPUT_ARGS, GDT_CB_ARGS_SRVC_MSG, smsg); cb_args.add_arg(GDT_CB_INPUT_ARGS, GDT_CB_ARGS_SRVC_PARAM, sparam); smsg->get_frag_param()->process_callback(GDT_ET_SRVC_PARAM_STREAM_END, &cb_args); // return to pool (fragmented // params are not retained in // memory) ssh_new->smsg_m ->get_param_factory() ->free_param(sparam); ssh_new->smsg_m ->get_param_factory() ->free_param(smsg->get_frag_param()); // reset frag param smsg->set_frag_param(nullptr); // no fragmentation } else { sparam->set_fragmented(false); // add param smsg->add_param(be32toh(*param_id), sparam, sparam->index); // process vparam if (sparam->get_type() == SPT_VARIANT) { // check param type switch (sparam->get_extra_type()) { // c string case mink_utils::DPT_STRING: { char tmp_str[256]; sparam->extract(tmp_str); smsg->vpmap.set_cstr(sparam->get_id(), tmp_str, sparam->get_index()); break; } // int case mink_utils::DPT_INT: { uint64_t tmp = 0; sparam->extract(&tmp); smsg->vpmap.set_int(sparam->get_id(), tmp, sparam->get_index()); break; } // bool case mink_utils::DPT_BOOL: { bool tmp = false; sparam->extract(&tmp); smsg->vpmap.set_bool(sparam->get_id(), tmp, sparam->get_index()); break; } // other default: { unsigned char tmp_buff[256]; sparam->extract(&tmp_buff); smsg->vpmap.set_octets(sparam->get_id(), tmp_buff, sparam->get_data_size(), sparam->get_index()); break; } } } // run callback cb_args.clear_all_args(); cb_args.add_arg(GDT_CB_INPUT_ARGS, GDT_CB_ARGS_SRVC_MSG, smsg); cb_args.add_arg(GDT_CB_INPUT_ARGS, GDT_CB_ARGS_SRVC_PARAM, sparam); smsg->process_callback(GDT_ET_SRVC_SHORT_PARAM_NEW, &cb_args); } } } else { smsg->missing_params = true; ssh_new->smsg_m->stats.inc( SST_RX_SPARAM_POOL_EMPTY, 1); } } stream->continue_sequence(); } } } gdt::ServiceStreamHandlerDone::ServiceStreamHandlerDone(): ssh_new(nullptr){ } void gdt::ServiceStreamHandlerDone::run(GDTCallbackArgs *args) { auto stream = (gdt::GDTStream *)args->get_arg(gdt::GDT_CB_INPUT_ARGS, gdt::GDT_CB_ARG_STREAM); auto smsg = (ServiceMessage *)stream->get_param(SMSG_PT_SMSG); auto in_msg = (asn1::GDTMessage *)args->get_arg(gdt::GDT_CB_INPUT_ARGS, gdt::GDT_CB_ARG_IN_MSG); auto in_sess = (uint64_t *)args->get_arg(gdt::GDT_CB_INPUT_ARGS, gdt::GDT_CB_ARG_IN_MSG_ID); // get ID->TYPE map ParamIdTypeMap *idt_map = ssh_new->smsg_m->get_idt_map(); // set default param type ServiceParamType ptype = SPT_UNKNOWN; // declare param pointer ServiceParam *sparam = nullptr; // param id pointer uint32_t *param_id = nullptr; // raw data pointer char *tmp_val = nullptr; // raw data length int tmp_val_l = 0; // fragmentation bool frag = false; // extra type int extra_type; GDTCallbackArgs cb_args; asn1::ServiceMessage *sm = nullptr; asn1::Parameters *p = nullptr; if(!smsg) return; if(!in_msg) goto stream_complete; sm = in_msg->_body->_service_msg; // in_msg is nullptr in case of stream timeout // check for params part if (!sm->_params) goto stream_pre_complete; if (!sm->_params->has_linked_data(*in_sess)) goto stream_pre_complete; p = sm->_params; // service id if (sm->_service_id->has_linked_data(*in_sess)) { auto tmp_ui32 = (uint32_t *)sm->_service_id ->linked_node ->tlv ->value; smsg->set_service_id(be32toh(*tmp_ui32)); } // process params for (unsigned int i = 0; i < p->children.size(); i++) { // check for value if (!p->get_child(i)->_value) continue; // check if value exists in current session if (!p->get_child(i) ->_value ->has_linked_data(*in_sess)) continue; // check if child exists if (!p->get_child(i) ->_value ->get_child(0)) continue; // check if child exists in current sesion if (!p->get_child(i) ->_value ->get_child(0) ->has_linked_data(*in_sess)) continue; // getr param id param_id = (uint32_t *)p->get_child(i) ->_id ->linked_node ->tlv ->value; // get param type by id ptype = idt_map->get(be32toh(*param_id)); // get extra type extra_type = p->get_child(i) ->_value ->get_child(3) ->linked_node ->tlv ->value[0]; // create param sparam = ssh_new->smsg_m ->get_param_factory() ->new_param((extra_type > 0) ? SPT_VARIANT : ptype); // fragmentatio flag frag = false; if (sparam != nullptr) { // set id sparam->set_id(be32toh(*param_id)); // reset data pointer sparam->reset_data_p(); // reset index and extra type sparam->index = 0; sparam->extra_type = 0; // get raw data tmp_val = (char *)p->get_child(i) ->_value ->get_child(0) ->linked_node ->tlv ->value; tmp_val_l = p->get_child(i) ->_value ->get_child(0) ->linked_node ->tlv ->value_length; // set service param data sparam->set_data(tmp_val, tmp_val_l); // check for fragmentation if ((p->get_child(i) ->_value ->get_child(1)) && (p->get_child(i) ->_value ->get_child(1) ->has_linked_data(*in_sess))) { const asn1::TLVNode *tlv = p->get_child(i) ->_value ->get_child(1) ->linked_node ->tlv; // fragmentation flag (value // length 1 and value 1) if ((tlv->value_length == 1) && (tlv->value[0] == 1)) { frag = true; } } // variant param id index and type sparam->index = p->get_child(i) ->_value ->get_child(2) ->linked_node ->tlv ->value[0]; sparam->extra_type = extra_type; // set fragmentation flag and // pointer to first fragment if (frag) { sparam->set_fragmented(true); // first fragment if (!smsg->get_frag_param()) { // set first fragment // pointer smsg->set_frag_param(sparam); // reset callbacks sparam->clear_callbacks(); // process vparam if (sparam->get_type() == SPT_VARIANT) { smsg->vpmap.set_octets(sparam->get_id(), sparam->get_data(), sparam->get_data_size(), sparam->get_index(), smsg->get_frag_param() ->get_fragment_index()); } // run callback cb_args.clear_all_args(); cb_args.add_arg(GDT_CB_INPUT_ARGS, GDT_CB_ARGS_SRVC_MSG, smsg); cb_args.add_arg(GDT_CB_INPUT_ARGS, GDT_CB_ARGS_SRVC_PARAM, sparam); smsg->process_callback(GDT_ET_SRVC_PARAM_STREAM_NEW, &cb_args); // more fragments } else { smsg->get_frag_param() ->inc_total_data_size(sparam->get_data_size()); // process vparam if (sparam->get_type() == SPT_VARIANT) { smsg->vpmap.set_octets(sparam->get_id(), sparam->get_data(), sparam->get_data_size(), sparam->get_index(), smsg->get_frag_param() ->get_fragment_index()); } // run callback cb_args.clear_all_args(); cb_args.add_arg(GDT_CB_INPUT_ARGS, GDT_CB_ARGS_SRVC_MSG, smsg); cb_args.add_arg(GDT_CB_INPUT_ARGS, GDT_CB_ARGS_SRVC_PARAM, sparam); smsg->get_frag_param() ->process_callback(GDT_ET_SRVC_PARAM_STREAM_NEXT, &cb_args); // return to pool // (fragmented params are // not retained in memory) ssh_new->smsg_m ->get_param_factory() ->free_param(sparam); } // no fragmentation or last // fragment } else { // last fragment if (smsg->get_frag_param()) { sparam->set_fragmented(true); smsg->get_frag_param() ->inc_total_data_size(sparam->get_data_size()); // process vparam if (sparam->get_type() == SPT_VARIANT) { smsg->vpmap.set_octets(sparam->get_id(), sparam->get_data(), sparam->get_data_size(), sparam->get_index(), smsg->get_frag_param() ->get_fragment_index()); mink_utils::VariantParam *vparam = smsg->vpmap.defragment(sparam->get_id(), sparam->get_index()); if (vparam != nullptr) vparam->set_type((mink_utils::VariantParamType)sparam->get_extra_type()); } // run callback cb_args.clear_all_args(); cb_args.add_arg(GDT_CB_INPUT_ARGS, GDT_CB_ARGS_SRVC_MSG, smsg); cb_args.add_arg(GDT_CB_INPUT_ARGS, GDT_CB_ARGS_SRVC_PARAM, sparam); smsg->get_frag_param() ->process_callback(GDT_ET_SRVC_PARAM_STREAM_END, &cb_args); // return to pool // (fragmented params are // not retained in memory) ssh_new->smsg_m ->get_param_factory() ->free_param(sparam); ssh_new->smsg_m ->get_param_factory() ->free_param(smsg->get_frag_param()); // reset frag param smsg->set_frag_param(nullptr); // no fragmentation } else { sparam->set_fragmented(false); // add param smsg->add_param(be32toh(*param_id), sparam, sparam->index); // process vparam if (sparam->get_type() == SPT_VARIANT) { // check param type switch (sparam->get_extra_type()) { // c string case mink_utils::DPT_STRING: { char tmp_str[256]; sparam->extract(tmp_str); smsg->vpmap.set_cstr(sparam->get_id(), tmp_str, sparam->get_index()); break; } // int case mink_utils::DPT_INT: { uint64_t tmp = 0; sparam->extract(&tmp); smsg->vpmap.set_int(sparam->get_id(), tmp, sparam->get_index()); break; } // bool case mink_utils::DPT_BOOL: { bool tmp = false; sparam->extract(&tmp); smsg->vpmap.set_bool(sparam->get_id(), tmp, sparam->get_index()); break; } // other default: { unsigned char tmp_buff[256]; sparam->extract(&tmp_buff); smsg->vpmap.set_octets(sparam->get_id(), tmp_buff, sparam->get_data_size(), sparam->get_index()); break; } } } // run callback cb_args.clear_all_args(); cb_args.add_arg(GDT_CB_INPUT_ARGS, GDT_CB_ARGS_SRVC_MSG, smsg); cb_args.add_arg(GDT_CB_INPUT_ARGS, GDT_CB_ARGS_SRVC_PARAM, sparam); smsg->process_callback(GDT_ET_SRVC_SHORT_PARAM_NEW, &cb_args); } } } else { smsg->missing_params = true; ssh_new->smsg_m->stats.inc(SST_RX_SPARAM_POOL_EMPTY, 1); } } stream_pre_complete: // set as completed if status is present and == ok (0) if (asn1::node_exists(in_msg->_header->_status, *in_sess)) { if (in_msg->_header->_status->linked_node->tlv->value[0] == 0) smsg->set_complete(true); // no status, set as completed } else smsg->set_complete(true); stream_complete: // run callback cb_args.clear_all_args(); cb_args.add_arg(GDT_CB_INPUT_ARGS, GDT_CB_ARG_STREAM, stream); cb_args.add_arg(GDT_CB_INPUT_ARGS, GDT_CB_ARGS_SRVC_MSG, smsg); cb_args.add_arg(GDT_CB_INPUT_ARGS, GDT_CB_ARG_CLIENT, stream->get_client()); smsg->process_callback(GDT_ET_SRVC_MSG_COMPLETE, &cb_args); // check for pass param auto smsg_pass = (ServiceMessage *)stream->get_param(SMSG_PT_PASS); // if pass not set // free message if auto_free flag was set (default) if ((smsg_pass != smsg) && (smsg->get_auto_free())) { ssh_new->smsg_m->free_smsg(smsg); } // remove params stream->remove_param(SMSG_PT_SMSG); stream->remove_param(SMSG_PT_PASS); // smsg not allocated in new stream event // error should be handled in GDT_ET_SRVC_MSG_ERROR handler } void gdt::ServiceStreamNewClient::run(GDTCallbackArgs *args) { auto client = (gdt::GDTClient *)args->get_arg(gdt::GDT_CB_INPUT_ARGS, gdt::GDT_CB_ARG_CLIENT); smsg_m->setup_client(client); // user NEW CLIENT handler if (usr_stream_nc_hndlr != nullptr) usr_stream_nc_hndlr->run(args); } void gdt::ServiceStreamHandlerNew::run(GDTCallbackArgs *args) { auto in_msg = (asn1::GDTMessage *)args->get_arg(gdt::GDT_CB_INPUT_ARGS, gdt::GDT_CB_ARG_IN_MSG); auto in_sess = (uint64_t *)args->get_arg(gdt::GDT_CB_INPUT_ARGS, gdt::GDT_CB_ARG_IN_MSG_ID); auto stream = (gdt::GDTStream *)args->get_arg(gdt::GDT_CB_INPUT_ARGS, gdt::GDT_CB_ARG_STREAM); GDTCallbackArgs cb_args; // check for body if (!in_msg->_body) { // NON ServiceMessage user handler if (usr_stream_hndlr != nullptr) usr_stream_hndlr->run(args); return; } // check for ServiceMessage if (!in_msg->_body->_service_msg->has_linked_data(*in_sess)) { if (usr_stream_hndlr != nullptr) usr_stream_hndlr->run(args); return; } // set event handlers stream->set_callback(gdt::GDT_ET_STREAM_NEXT, &ssh_next); stream->set_callback(gdt::GDT_ET_STREAM_END, &ssh_done); stream->set_callback(gdt::GDT_ET_STREAM_TIMEOUT, &ssh_done); // create new ServiceMessage ServiceMessage *smsg = smsg_m->new_smsg(); // nullptr check if (!smsg) { smsg_m->stats.inc(SST_RX_SMSG_POOL_EMPTY, 1); // run callback cb_args.clear_all_args(); cb_args.add_arg(GDT_CB_INPUT_ARGS, GDT_CB_ARG_STREAM, stream); smsg_m->process_callback(GDT_ET_SRVC_MSG_ERROR, &cb_args); return; } // reset frag smsg->set_frag_param(nullptr); // reset callbacks smsg->clear_callbacks(); // clear vpmap smsg->vpmap.clear_params(); // set as incomplete smsg->set_complete(false); // clear stream params stream->clear_params(); // set ServiceMessage as GDT stream param stream->set_param(SMSG_PT_SMSG, smsg); // reset auto free smsg->set_auto_free(true); // reset missing params smsg->missing_params = false; // run callback cb_args.clear_all_args(); cb_args.add_arg(GDT_CB_INPUT_ARGS, GDT_CB_ARGS_SRVC_MSG, smsg); smsg_m->process_callback(GDT_ET_SRVC_MSG_NEW, &cb_args); asn1::ServiceMessage *sm = in_msg->_body->_service_msg; asn1::Parameters *p = sm->_params; // get ID->TYPE map ParamIdTypeMap *idt_map = smsg_m->get_idt_map(); // set default param type ServiceParamType ptype = SPT_UNKNOWN; // declare param pointer ServiceParam *sparam = nullptr; // param id pointer uint32_t *param_id = nullptr; // raw data pointer char *tmp_val = nullptr; // raw data length int tmp_val_l = 0; // fragmentation bool frag = false; // extra type int extra_type; // check for params part if (!p) goto stream_continue; if (!p->has_linked_data(*in_sess)) goto stream_continue; // service id if (sm->_service_id->has_linked_data(*in_sess)) { auto tmp_ui32 = (uint32_t *)sm->_service_id ->linked_node ->tlv ->value; smsg->set_service_id(be32toh(*tmp_ui32)); } // process params for (unsigned int i = 0; i < p->children.size(); i++) { // check for value if (!p->get_child(i)->_value) continue; // check if value exists in current session if (!p->get_child(i) ->_value ->has_linked_data(*in_sess)) continue; // check if child exists if (!p->get_child(i) ->_value ->get_child(0)) continue; // check if child exists in current // sesion if (!p->get_child(i) ->_value ->get_child(0) ->has_linked_data(*in_sess)) continue; // getr param id param_id = (uint32_t *)p->get_child(i) ->_id ->linked_node ->tlv ->value; // get param type by id ptype = idt_map->get(be32toh(*param_id)); // get extra type extra_type = p->get_child(i) ->_value ->get_child(3) ->linked_node ->tlv ->value[0]; // create param sparam = smsg_m->get_param_factory() ->new_param((extra_type > 0) ? SPT_VARIANT : ptype); // fragmentation flag frag = false; if (sparam != nullptr) { // set id sparam->set_id(be32toh(*param_id)); // reset data pointer sparam->reset_data_p(); // reset index and extra type sparam->index = 0; sparam->extra_type = 0; // get raw data tmp_val = (char *)p->get_child(i) ->_value ->get_child(0) ->linked_node ->tlv ->value; tmp_val_l = p->get_child(i) ->_value ->get_child(0) ->linked_node ->tlv ->value_length; // set service param data sparam->set_data(tmp_val, tmp_val_l); // check for fragmentation if ((p->get_child(i) ->_value ->get_child(1)) && (p->get_child(i) ->_value ->get_child(1) ->has_linked_data(*in_sess))) { const asn1::TLVNode *tlv = p->get_child(i) ->_value ->get_child(1) ->linked_node ->tlv; // fragmentation flag // (value length 1 and // value 1) if ((tlv->value_length == 1) && (tlv->value[0] == 1)) { frag = true; } } // variant param id index and // type sparam->index = p->get_child(i) ->_value ->get_child(2) ->linked_node ->tlv ->value[0]; sparam->extra_type = extra_type; // set fragmentation flag and // pointer to first fragment if (frag) { sparam->set_fragmented(true); // first fragment if (!smsg->get_frag_param()) { // set first fragment // pointer smsg->set_frag_param(sparam); // reset callbacks sparam->clear_callbacks(); // process vparam if (sparam->get_type() == SPT_VARIANT) { smsg->vpmap.set_octets(sparam->get_id(), sparam->get_data(), sparam->get_data_size(), sparam->get_index(), smsg->get_frag_param() ->get_fragment_index()); } // run callback cb_args.clear_all_args(); cb_args.add_arg(GDT_CB_INPUT_ARGS, GDT_CB_ARGS_SRVC_MSG, smsg); cb_args.add_arg(GDT_CB_INPUT_ARGS, GDT_CB_ARGS_SRVC_PARAM, sparam); smsg->process_callback(GDT_ET_SRVC_PARAM_STREAM_NEW, &cb_args); // more fragments } else { smsg->get_frag_param() ->inc_total_data_size(sparam->get_data_size()); // process vparam if (sparam->get_type() == SPT_VARIANT) { smsg->vpmap.set_octets(sparam->get_id(), sparam->get_data(), sparam->get_data_size(), sparam->get_index(), smsg->get_frag_param() ->get_fragment_index()); } // run callback cb_args.clear_all_args(); cb_args.add_arg(GDT_CB_INPUT_ARGS, GDT_CB_ARGS_SRVC_MSG, smsg); cb_args.add_arg(GDT_CB_INPUT_ARGS, GDT_CB_ARGS_SRVC_PARAM, sparam); smsg->get_frag_param() ->process_callback(GDT_ET_SRVC_PARAM_STREAM_NEXT, &cb_args); // return to pool // (fragmented params // are not retained in // memory) smsg_m->get_param_factory() ->free_param(sparam); } // no fragmentation or last // fragment } else { // last fragment if (smsg->get_frag_param()) { sparam->set_fragmented(true); smsg->get_frag_param() ->inc_total_data_size(sparam->get_data_size()); // process vparam if (sparam->get_type() == SPT_VARIANT) { smsg->vpmap.set_octets(sparam->get_id(), sparam->get_data(), sparam->get_data_size(), sparam->get_index(), smsg->get_frag_param() ->get_fragment_index()); mink_utils::VariantParam *vparam = smsg->vpmap.defragment(sparam->get_id(), sparam->get_index()); if (vparam != nullptr) vparam->set_type((mink_utils::VariantParamType)sparam->get_extra_type()); } // run callback cb_args.clear_all_args(); cb_args.add_arg(GDT_CB_INPUT_ARGS, GDT_CB_ARGS_SRVC_MSG, smsg); cb_args.add_arg(GDT_CB_INPUT_ARGS, GDT_CB_ARGS_SRVC_PARAM, sparam); smsg->get_frag_param() ->process_callback(GDT_ET_SRVC_PARAM_STREAM_END, &cb_args); // return to pool // (fragmented params // are not retained in // memory) smsg_m->get_param_factory()->free_param(sparam); smsg_m->get_param_factory()->free_param(smsg->get_frag_param()); // reset frag param smsg->set_frag_param(nullptr); // no fragmentation } else { sparam->set_fragmented(false); // add param smsg->add_param(be32toh(*param_id), sparam, sparam->index); // process vparam if (sparam->get_type() == SPT_VARIANT) { // check param type switch (sparam->get_extra_type()) { // c string case mink_utils::DPT_STRING: { char tmp_str[256]; sparam->extract(tmp_str); smsg->vpmap.set_cstr(sparam->get_id(), tmp_str, sparam->get_index()); break; } // int case mink_utils::DPT_INT: { uint64_t tmp = 0; sparam->extract(&tmp); smsg->vpmap.set_int(sparam->get_id(), tmp, sparam->get_index()); break; } // bool case mink_utils::DPT_BOOL: { bool tmp = false; sparam->extract(&tmp); smsg->vpmap.set_bool(sparam->get_id(), tmp, sparam->get_index()); break; } // other default: { unsigned char tmp_buff[256]; sparam->extract(&tmp_buff); smsg->vpmap.set_octets(sparam->get_id(), tmp_buff, sparam->get_data_size(), sparam->get_index()); break; } } } // run callback cb_args.clear_all_args(); cb_args.add_arg(GDT_CB_INPUT_ARGS, GDT_CB_ARGS_SRVC_MSG, smsg); cb_args.add_arg(GDT_CB_INPUT_ARGS, GDT_CB_ARGS_SRVC_PARAM, sparam); smsg->process_callback(GDT_ET_SRVC_SHORT_PARAM_NEW, &cb_args); } } } else { smsg->missing_params = true; smsg_m->stats.inc(SST_RX_SPARAM_POOL_EMPTY, 1); } } stream_continue: // continue stream->continue_sequence(); } gdt::ServiceMsgManager::ServiceMsgManager(ParamIdTypeMap *_idt_map, GDTCallbackMethod *_new_msg_hndlr, GDTCallbackMethod *_nonsrvc_stream_hndlr, unsigned int pool_size, unsigned int param_pool_size) { idt_map = _idt_map; param_factory = new ServiceParamFactory(true, false, param_pool_size); sem_init(&q_sem, 0, 0); srvcs_hndlr.smsg_m = this; srvcs_nc.smsg_m = this; srvcs_hndlr.usr_stream_hndlr = _nonsrvc_stream_hndlr; srvcs_hndlr.ssh_next.ssh_new = &srvcs_hndlr; srvcs_hndlr.ssh_done.ssh_new = &srvcs_hndlr; msg_pool.init(pool_size); msg_pool.construct_objects(); cb_handler.set_callback(GDT_ET_SRVC_MSG_NEW, _new_msg_hndlr); // set manager pointers ServiceMessage *tmp_arr[pool_size]; for (unsigned int i = 0; i < pool_size; i++) { tmp_arr[i] = msg_pool.allocate_constructed(); tmp_arr[i]->set_smsg_manager(this); } // return back to pool for (unsigned int i = 0; i < pool_size; i++) msg_pool.deallocate_constructed(tmp_arr[i]); // random generator timespec tmp_time; clock_gettime(0, &tmp_time); // stats stats.register_item(SST_RX_SMSG_POOL_EMPTY); stats.register_item(SST_RX_SPARAM_POOL_EMPTY); } gdt::ServiceMsgManager::~ServiceMsgManager() { sem_destroy(&q_sem); delete param_factory; } void gdt::ServiceMsgManager::generate_uuid(unsigned char *out) { random_gen.generate(out, 16); } gdt::GDTCallbackMethod *gdt::ServiceMsgManager::get_srvcs_hndlr() { return &srvcs_hndlr; } gdt::GDTCallbackMethod *gdt::ServiceMsgManager::get_srvcs_nc_hndlr() { return &srvcs_nc; } void gdt::ServiceMsgManager::set_new_msg_handler(GDTCallbackMethod *hndlr) { cb_handler.set_callback(GDT_ET_SRVC_MSG_NEW, hndlr); } void gdt::ServiceMsgManager::set_msg_err_handler(GDTCallbackMethod *hndlr) { cb_handler.set_callback(GDT_ET_SRVC_MSG_ERROR, hndlr); } bool gdt::ServiceMsgManager::process_callback(GDTEventType type, GDTCallbackArgs *args) { return cb_handler.process_callback(type, args); } void gdt::ServiceMsgManager::setup_server(GDTSession *gdts, gdt::GDTCallbackMethod *_usr_stream_nc_hndlr, gdt::GDTCallbackMethod *_usr_stream_hndlr) { // set extra user stream handler srvcs_nc.usr_stream_nc_hndlr = _usr_stream_nc_hndlr; srvcs_nc.usr_stream_hndlr = _usr_stream_hndlr; // set end event handler gdts->set_callback(gdt::GDT_ET_CLIENT_NEW, &srvcs_nc); } void gdt::ServiceMsgManager::setup_client(GDTClient *gdtc) { // nullptr check if (gdtc == nullptr) return; // set end event handler gdtc->set_callback(gdt::GDT_ET_STREAM_NEW, &srvcs_hndlr); } gdt::ServiceMessage *gdt::ServiceMsgManager::new_smsg() { ServiceMessage *tmp = msg_pool.allocate_constructed(); return tmp; } int gdt::ServiceMsgManager::free_smsg(ServiceMessage *msg, bool params_only, bool clear_vpmap) { // free params std::vector<ServiceParam *> *params = msg->get_param_map(); ServiceParam *param = nullptr; for (unsigned int i = 0; i < params->size(); i++) { param = (*params)[i]; // check for temp linked buffer params for (unsigned int j = 0; j < param->linked.size(); j++) { param_factory->free_param(param->linked[j]); } param->linked.clear(); // free param param_factory->free_param(param); } // check frag param if (msg->get_frag_param() != nullptr) { // check for temp linked buffer params in frag param for (unsigned int j = 0; j < msg->get_frag_param()->linked.size(); j++) { param_factory->free_param(msg->get_frag_param()->linked[j]); } msg->get_frag_param()->linked.clear(); // free frag param param_factory->free_param(msg->get_frag_param()); } // clear params params->clear(); // clear vpmap if (clear_vpmap) msg->vpmap.clear_params(); // if freeing smsg also if (!params_only) { msg->params.clear_params(); // return to pool int res = msg_pool.deallocate_constructed(msg); // result return res; } // ok return 0; } gdt::ServiceParamFactory *gdt::ServiceMsgManager::get_param_factory() { return param_factory; } gdt::ParamIdTypeMap *gdt::ServiceMsgManager::get_idt_map() { return idt_map; } int gdt::ServiceMsgManager::vpmap_sparam_sync(ServiceMessage *msg, const std::vector<ServiceParam*> *pmap) { // freee sparams, do not clear vpmap free_smsg(msg, true, false); // vars ServiceParam *param = nullptr; bool err = false; // process vpmap for (mink_utils::VariantParamMap<uint32_t>::it_t it = msg->vpmap.get_begin(); it != msg->vpmap.get_end(); it++) { // skip pointer param type if (it->second.get_type() == mink_utils::DPT_POINTER) continue; // skip context other then default 0 if (it->first.context != 0) continue; // allocate new service param param = get_param_factory()->new_param(gdt::SPT_VARIANT); // sanity check if (param == nullptr) { err = true; break; } // set service param data from decoded param param->set(&it->second); // add service param to service message msg->add_param(it->first.key, param, it->first.index); } // extra params if(pmap != nullptr){ for(auto it = pmap->begin(); it != pmap->end(); it++){ // add service param to service message msg->add_param((*it)->get_id(), (*it), (*it)->get_index()); } } // result return err; } int gdt::ServiceMsgManager::send(ServiceMessage *msg, GDTClient *gdtc, const char *dtype, const char *did, bool async, gdt::GDTCallbackMethod *on_sent) { if ((msg != nullptr) && (gdtc != nullptr)) { // start new GDT stream GDTStream *gdt_stream = gdtc->allocate_stream_pool(); // if stream cannot be created, return err if (gdt_stream == nullptr) { gdtc->get_stats(GDT_OUTBOUND_STATS) ->strm_alloc_errors.add_fetch(1); return 10; } // setup stream directly gdt_stream->set_client(gdtc); gdt_stream->reset(true); gdt_stream->clear_callbacks(); gdt_stream->clear_params(); gdt_stream->set_destination(dtype, did); unsigned int pc; unsigned int bc; unsigned int tbc = 0; // param map std::vector<ServiceParam *> *pmap = msg->get_param_map(); pc = pmap->size(); // calculate total param size (add extra 3 bytes for dual byte length // and single byte tag) ServiceParam *tmp_param = nullptr; for (unsigned int i = 0; i < pmap->size(); i++) { tmp_param = (*pmap)[i]; // check fragmentation if (tmp_param->is_fragmented()) { // -1 to exclude already included first fragment pc += tmp_param->fragments - 1; // add extra 3 bytes to size calculation (Tag + Length (BER // Definite long)) } } // add extra buffer for fragmented params (used when streaming from non // pre-allocated sources) max size is pps ServiceParam *new_param = nullptr; for (unsigned int i = 0; i < pmap->size(); i++) { tmp_param = (*pmap)[i]; if (tmp_param->is_fragmented()) { for (unsigned int j = 0; j < 4; j++) { new_param = param_factory->new_param(tmp_param->type); if (new_param != nullptr) tmp_param->linked.push_back(new_param); } tmp_param->linked_index = 0; } } // reset user handler from previous instance msg->get_sdone_hndlr()->usr_method = nullptr; // reset status from previous instance msg->get_sdone_hndlr()->status = 0; // set end event handler gdt_stream->set_callback(gdt::GDT_ET_STREAM_END, msg->get_sdone_hndlr()); gdt_stream->set_callback(gdt::GDT_ET_STREAM_TIMEOUT, msg->get_sdone_hndlr()); // if async mode, set user handler if (async) msg->get_sdone_hndlr()->usr_method = on_sent; // get handler ServiceMessageNext *cb = msg->get_snext_hndlr(); // reset pos (param pos) cb->pos = 0; // reset pindex (param pos including fragments) cb->pindex = 0; cb->pc = pc; // set callback gdt_stream->set_callback(gdt::GDT_ET_STREAM_NEXT, cb); // create body asn1::GDTMessage *gdtm = gdt_stream->get_gdt_message(); // prepare body if (gdtm->_body != nullptr) { gdtm->_body->unlink(1); gdtm->_body->_service_msg->set_linked_data(1); } else { gdtm->set_body(); gdtm->prepare(); } asn1::ServiceMessage *sm = gdtm->_body->_service_msg; // set params, allocate 10 initial children if (!sm->_params) { sm->set_params(); asn1::Parameters *p = sm->_params; // set children, allocate more for (int i = 0; i < 10; i++) { p->set_child(i); p->get_child(i)->set_value(); p->get_child(i)->_value->set_child(0); p->get_child(i)->_value->set_child(1); p->get_child(i)->_value->set_child(2); p->get_child(i)->_value->set_child(3); } // prepare asn1::prepare(sm, sm->parent_node); } // set service id sm->_service_id->set_linked_data(1, (unsigned char *)msg->get_service_idp(), sizeof(uint32_t)); // set service action sm->_service_action->set_linked_data(1, (unsigned char *)msg->get_service_actionp(), 1); // params ServiceParam *sc_param = nullptr; asn1::Parameters *params = gdtm->_body->_service_msg->_params; // loop params for (unsigned int j = 0; (tbc < MAX_PARAMS_SIZE) && (cb->pos < pmap->size()); j++, cb->pos++, cb->pindex++) { sc_param = (*pmap)[cb->pos]; // check if more allocations are needed if (params->get_child(j) == nullptr) { params->set_child(j); params->get_child(j)->set_value(); params->get_child(j)->_value->set_child(0); params->get_child(j)->_value->set_child(1); params->get_child(j)->_value->set_child(2); params->get_child(j)->_value->set_child(3); // prepare asn1::prepare(params, params->parent_node); } // update total byte count tbc += sc_param->data_size + 25; // check if limit reached if (tbc > MAX_PARAMS_SIZE) break; // set gdt param id and data params->get_child(j)->_id->set_linked_data(1, (unsigned char *)sc_param->get_idp(), sizeof(uint32_t)); params->get_child(j)->_value->get_child(0)->set_linked_data(1, sc_param->data_p, sc_param->data_size); // check fragmentation if (sc_param->is_fragmented()) { params->get_child(j)->_value->get_child(1)->set_linked_data(1, (unsigned char *)sc_param->get_fragmentation_p(), 1); // variant param id index and type params->get_child(j)->_value->get_child(2)->set_linked_data(1, (unsigned char *)&sc_param->index, 1); params->get_child(j)->_value->get_child(3)->set_linked_data(1, (unsigned char *)&sc_param->extra_type, 1); // next fragment ++sc_param->fragment_index; ++j; ++cb->pindex; // run data fetch method (*sc_param->param_data_cb)(sc_param, sc_param->in_data_p, sc_param->total_data_size); // process fragments while ((tbc < MAX_PARAMS_SIZE) && (sc_param->fragment_index < sc_param->fragments)) { process_fragments(&bc, &tbc, sc_param, params, j); // check if limit reached if (tbc > MAX_PARAMS_SIZE) break; // set gdt values params->get_child(j)->_id->set_linked_data(1, (unsigned char *)sc_param->get_idp(), sizeof(uint32_t)); params->get_child(j)->_value->get_child(0)->set_linked_data(1, sc_param->data_p, bc); // variant param id index and type params->get_child(j)->_value->get_child(2)->set_linked_data(1, (unsigned char *)&sc_param->index, 1); params->get_child(j)->_value->get_child(3)->set_linked_data(1, (unsigned char *)&sc_param->extra_type, 1); // check if last fragment, disable fragmentation flag (last // fragment must not contain fragmentation flag) if (sc_param->fragment_index == (sc_param->fragments - 1)) { params->get_child(j) ->_value ->get_child(1) ->set_linked_data(1, (unsigned char*)&ServiceParam::FRAGMENTATION_DONE, 1); } else { // set gdt fragmentation flag params->get_child(j) ->_value->get_child(1) ->set_linked_data(1, (unsigned char*)&ServiceParam::FRAGMENTATION_NEXT, 1); } // next ++sc_param->fragment_index; ++j; ++cb->pindex; // run data fetch method (*sc_param->param_data_cb)(sc_param, sc_param->in_data_p, sc_param->total_data_size); } // break if fragmentation in progress and not finished (to skip // increment, next call should process the same param again) if (sc_param->fragment_index < sc_param->fragments) break; // rewind gdt param child count and packet index else { --j; --cb->pindex; } // no fragmentation } else { params->get_child(j)->_value->get_child(1)->set_linked_data(1, (unsigned char *)sc_param->get_fragmentation_p(), 1); // variant param id index and type params->get_child(j)->_value->get_child(2)->set_linked_data(1, (unsigned char *)&sc_param->index, 1); params->get_child(j)->_value->get_child(3)->set_linked_data(1, (unsigned char *)&sc_param->extra_type, 1); } } // remove unused chidren for (unsigned int i = cb->pindex; i < params->children.size(); i++) params->get_child(i)->unlink(1); // add to list of active streams directly gdtc->add_stream(gdt_stream); // start stream gdt_stream->send(true); // sync mode if (!async) { if (msg->signal_wait() == 1) return 100; else return msg->get_sdone_hndlr()->status; // async mode } else { // ok return 0; } } // err return 1; } void gdt::ServiceMessageAsyncDone::run(GDTCallbackArgs *args) { auto smsg = (gdt::ServiceMessage *)args->get_arg(gdt::GDT_CB_INPUT_ARGS, gdt::GDT_CB_ARGS_SRVC_MSG); smsg->get_smsg_manager()->free_smsg(smsg); }
37.180074
125
0.44981
dfranusic
eee054ddb45e98344a7c22275a544a0007ce30fe
135
cpp
C++
Plugins/KizuEngine/Source/KizuEngine/Private/Core/Combat/KizuCombat.cpp
Hiro-KE/UE4-KizuEngine
42c5f5c934f0fa6a3265a39157087a61abeaa3a0
[ "MIT" ]
11
2020-12-26T23:16:45.000Z
2022-03-19T20:19:36.000Z
Plugins/KizuEngine/Source/KizuEngine/Private/Core/Combat/KizuCombat.cpp
Fukaidemon/UE4-KizuEngine
42c5f5c934f0fa6a3265a39157087a61abeaa3a0
[ "MIT" ]
null
null
null
Plugins/KizuEngine/Source/KizuEngine/Private/Core/Combat/KizuCombat.cpp
Fukaidemon/UE4-KizuEngine
42c5f5c934f0fa6a3265a39157087a61abeaa3a0
[ "MIT" ]
null
null
null
// KizuEngine Copyright (c) 2019 Jed Fakhfekh. This software is released under the MIT License. #include "Core/Combat/KizuCombat.h"
22.5
95
0.762963
Hiro-KE
eee1135884b51f4dabc53219fbf7019ecb5d2e0e
4,181
cpp
C++
cdn/src/v20180606/model/HttpHeaderRule.cpp
sinjoywong/tencentcloud-sdk-cpp
1b931d20956a90b15a6720f924e5c69f8786f9f4
[ "Apache-2.0" ]
null
null
null
cdn/src/v20180606/model/HttpHeaderRule.cpp
sinjoywong/tencentcloud-sdk-cpp
1b931d20956a90b15a6720f924e5c69f8786f9f4
[ "Apache-2.0" ]
null
null
null
cdn/src/v20180606/model/HttpHeaderRule.cpp
sinjoywong/tencentcloud-sdk-cpp
1b931d20956a90b15a6720f924e5c69f8786f9f4
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/cdn/v20180606/model/HttpHeaderRule.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Cdn::V20180606::Model; using namespace std; HttpHeaderRule::HttpHeaderRule() : m_headerModeHasBeenSet(false), m_headerNameHasBeenSet(false), m_headerValueHasBeenSet(false) { } CoreInternalOutcome HttpHeaderRule::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("HeaderMode") && !value["HeaderMode"].IsNull()) { if (!value["HeaderMode"].IsString()) { return CoreInternalOutcome(Error("response `HttpHeaderRule.HeaderMode` IsString=false incorrectly").SetRequestId(requestId)); } m_headerMode = string(value["HeaderMode"].GetString()); m_headerModeHasBeenSet = true; } if (value.HasMember("HeaderName") && !value["HeaderName"].IsNull()) { if (!value["HeaderName"].IsString()) { return CoreInternalOutcome(Error("response `HttpHeaderRule.HeaderName` IsString=false incorrectly").SetRequestId(requestId)); } m_headerName = string(value["HeaderName"].GetString()); m_headerNameHasBeenSet = true; } if (value.HasMember("HeaderValue") && !value["HeaderValue"].IsNull()) { if (!value["HeaderValue"].IsString()) { return CoreInternalOutcome(Error("response `HttpHeaderRule.HeaderValue` IsString=false incorrectly").SetRequestId(requestId)); } m_headerValue = string(value["HeaderValue"].GetString()); m_headerValueHasBeenSet = true; } return CoreInternalOutcome(true); } void HttpHeaderRule::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_headerModeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "HeaderMode"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_headerMode.c_str(), allocator).Move(), allocator); } if (m_headerNameHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "HeaderName"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_headerName.c_str(), allocator).Move(), allocator); } if (m_headerValueHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "HeaderValue"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_headerValue.c_str(), allocator).Move(), allocator); } } string HttpHeaderRule::GetHeaderMode() const { return m_headerMode; } void HttpHeaderRule::SetHeaderMode(const string& _headerMode) { m_headerMode = _headerMode; m_headerModeHasBeenSet = true; } bool HttpHeaderRule::HeaderModeHasBeenSet() const { return m_headerModeHasBeenSet; } string HttpHeaderRule::GetHeaderName() const { return m_headerName; } void HttpHeaderRule::SetHeaderName(const string& _headerName) { m_headerName = _headerName; m_headerNameHasBeenSet = true; } bool HttpHeaderRule::HeaderNameHasBeenSet() const { return m_headerNameHasBeenSet; } string HttpHeaderRule::GetHeaderValue() const { return m_headerValue; } void HttpHeaderRule::SetHeaderValue(const string& _headerValue) { m_headerValue = _headerValue; m_headerValueHasBeenSet = true; } bool HttpHeaderRule::HeaderValueHasBeenSet() const { return m_headerValueHasBeenSet; }
28.442177
138
0.701746
sinjoywong
eee7b92440f44b6c9f6b37733489daef1568084a
6,162
hpp
C++
include/eve/module/real/core/function/regular/generic/store.hpp
the-moisrex/eve
80b52663eefee11460abb0aedf4158a5067cf7dc
[ "MIT" ]
340
2020-09-16T21:12:48.000Z
2022-03-28T15:40:33.000Z
third-party/eve/module/real/core/function/regular/generic/store.hpp
aguinet/ecsimd
cba9e7fe76601b98cbaeea317b6c4e671272e70b
[ "Apache-2.0" ]
383
2020-09-17T06:56:35.000Z
2022-03-13T15:58:53.000Z
third-party/eve/module/real/core/function/regular/generic/store.hpp
aguinet/ecsimd
cba9e7fe76601b98cbaeea317b6c4e671272e70b
[ "Apache-2.0" ]
28
2021-02-27T23:11:23.000Z
2022-03-25T12:31:29.000Z
//================================================================================================== /* EVE - Expressive Vector Engine Copyright : EVE Contributors & Maintainers SPDX-License-Identifier: MIT */ //================================================================================================== #pragma once #include <eve/concept/value.hpp> #include <eve/detail/implementation.hpp> #include <eve/detail/kumi.hpp> #include <eve/function/bit_cast.hpp> #include <eve/function/replace.hpp> #include <eve/memory/aligned_ptr.hpp> namespace eve::detail { // ----------------------------------------------------------------------------------------------- // simd Tuple case template<kumi::product_type T, typename S, kumi::sized_product_type<T::size()> Ptr> EVE_FORCEINLINE void store_(EVE_SUPPORTS(cpu_), wide<T, S> const &value, Ptr ptrs) noexcept requires std::same_as<abi_t<T, S>, bundle_> { kumi::for_each( [](auto v, auto p) { store(v, p); }, value, ptrs ); } template< kumi::product_type T, typename S , kumi::sized_product_type<T::size()> Ptr , relative_conditional_expr C > EVE_FORCEINLINE void store_(EVE_SUPPORTS(cpu_), C const &c, wide<T, S> const &value, Ptr ptrs) noexcept { if constexpr ( C::has_alternative ) { auto alt = [&]{ if constexpr ( kumi::product_type<typename C::alternative_type> ) return c.alternative; else return c.alternative.storage(); }(); kumi::for_each( [&](auto v, auto part_alt, auto p) { auto new_c = c.map_alternative([&](auto) { return part_alt; }); store[new_c](v, p); }, value.storage(), alt, ptrs); } else { kumi::for_each( [&](auto v, auto p) { store[c](v, p); }, value.storage(), ptrs ); } } // ----------------------------------------------------------------------------------------------- // simd Regular case template<real_scalar_value T, typename N> EVE_FORCEINLINE void store_(EVE_SUPPORTS(cpu_), wide<T, N> value, T *ptr) noexcept requires std::same_as<abi_t<T, N>, emulated_> { apply<N::value>([&](auto... I) { ((*ptr++ = value.get(I)), ...); }); } template<real_scalar_value T, typename N> EVE_FORCEINLINE void store_(EVE_SUPPORTS(cpu_), wide<T, N> value, T *ptr) noexcept requires std::same_as<abi_t<T, N>, aggregated_> { value.storage().apply ( [&]<typename... Sub>(Sub&... v) { int k = 0; ((store(v, ptr + k), k += Sub::size()), ...); } ); } // ----------------------------------------------------------------------------------------------- // simd Aligned case template<real_scalar_value T, typename S, typename Lanes> EVE_FORCEINLINE void store_(EVE_SUPPORTS(cpu_), wide<T, S> const &value, aligned_ptr<T, Lanes> ptr) noexcept requires(S::value <= Lanes::value) && std::same_as<abi_t<T, S>, emulated_> { store(value, ptr.get()); } template<real_scalar_value T, typename S, typename Lanes> EVE_FORCEINLINE void store_(EVE_SUPPORTS(cpu_), wide<T, S> const &value, aligned_ptr<T, Lanes> ptr) noexcept requires(S::value <= Lanes::value) && std::same_as<abi_t<T, S>, aggregated_> { auto cast = []<typename Ptr, typename Sub>(Ptr ptr, as<Sub>) { return eve::aligned_ptr<T, typename Sub::cardinal_type>{ptr.get()}; }; value.storage().apply ( [&]<typename... Sub>(Sub&... v) { int k = 0; ((store(v, cast(ptr, as<Sub>{}) + k), k += Sub::size()), ...); } ); } template<simd_value T, relative_conditional_expr C, simd_compatible_ptr<T> Ptr> EVE_FORCEINLINE void store_(EVE_SUPPORTS(cpu_), C const &cond, T const &value, Ptr ptr) noexcept { if constexpr ( C::is_complete && C::is_inverted ) store(value, ptr); else if constexpr ( C::has_alternative ) store(replace_ignored(value, cond, cond.alternative), ptr); else if constexpr ( C::is_complete ) return; else if constexpr ( logical_simd_value<T> ) { using mask_type_t = typename element_type_t<T>::mask_type; if constexpr ( std::is_pointer_v<Ptr> ) store[cond](value.mask(), (mask_type_t*) ptr); else { store[cond](value.mask(), typename Ptr::template rebind<mask_type_t>{(mask_type_t*)ptr.get()}); } } else if constexpr ( !std::is_pointer_v<Ptr> ) store[cond](value, ptr.get()); else if constexpr ( has_emulated_abi_v<T> ) { auto offset = cond.offset( as<T>{} ); auto count = cond.count( as<T>{} ); using e_t = element_type_t<T>; auto* src = (e_t*)(&value.storage()); std::memcpy((void*)(ptr + offset), (void*)(src + offset), sizeof(e_t) * count); } else { using e_t = element_type_t<T>; alignas(sizeof(T)) std::array<e_t, T::size()> storage; store(value, eve::aligned_ptr<e_t, typename T::cardinal_type>(storage.begin())); auto offset = cond.offset( as<T>{} ); auto count = cond.count( as<T>{} ); std::memcpy((void*)(ptr + offset), (void*)(storage.begin() + offset), sizeof(e_t) * count); } } template<real_scalar_value T, typename S> EVE_FORCEINLINE void store_(EVE_SUPPORTS(cpu_), logical<wide<T, S>> const &value, logical<T>* ptr) noexcept { store(value.mask(), (typename logical<T>::mask_type*) ptr); } template<real_scalar_value T, typename S,typename Lanes> EVE_FORCEINLINE void store_(EVE_SUPPORTS(cpu_), logical<wide<T, S>> const &value, aligned_ptr<logical<T>, Lanes> ptr) noexcept requires ( requires {store(value.mask(), aligned_ptr<typename logical<T>::mask_type, Lanes>{}); } ) { using mask_type_t = typename logical<T>::mask_type; store(value.mask(), aligned_ptr<mask_type_t, Lanes>{(mask_type_t*)ptr.get()}); } }
36.678571
118
0.540409
the-moisrex
eee80134cd760b89e821f29a1ee0ce616b0f6efa
17,039
cpp
C++
src/table_functions.cpp
ThomasWitte/MiniLua
033a357c602d2d2ebeca304d1a3660ad1e5d7298
[ "MIT" ]
2
2020-07-08T11:51:02.000Z
2021-02-22T23:28:37.000Z
src/table_functions.cpp
ThomasWitte/MiniLua
033a357c602d2d2ebeca304d1a3660ad1e5d7298
[ "MIT" ]
142
2020-08-31T13:21:17.000Z
2021-09-15T18:46:10.000Z
src/table_functions.cpp
ThomasWitte/MiniLua
033a357c602d2d2ebeca304d1a3660ad1e5d7298
[ "MIT" ]
3
2020-08-17T13:42:39.000Z
2020-08-31T11:38:05.000Z
#include "MiniLua/table_functions.hpp" #include "MiniLua/utils.hpp" #include "MiniLua/values.hpp" #include <algorithm> #include <cmath> #include <future> #include <iostream> #include <stdexcept> #include <string> #include <utility> #include <variant> #include <vector> namespace minilua { auto static try_value_is_int(Value s, const std::string& method_name, int arg_index) -> int { try { if (s.is_number()) { return std::get<Number>(s).try_as_int(); } } catch (const std::runtime_error& e) { throw std::runtime_error( "bad argument #" + std::to_string(arg_index) + " to '" + method_name + "' (number expected, got " + s.type() + ")"); } auto tmp = Number(1); try { if (s.is_string()) { Value v = s.to_number(); if (v == Nil()) { throw std::runtime_error(""); } tmp = std::get<Number>(v); } else if (!s.is_number()) { throw std::runtime_error(""); } } catch (const std::runtime_error& e) { throw std::runtime_error( "bad argument #" + std::to_string(arg_index) + " to '" + method_name + "' (number expected, got " + s.type() + ")"); } try { return tmp.try_as_int(); } catch (const std::runtime_error& e) { throw std::runtime_error( "bad argument #" + std::to_string(arg_index) + " to '" + method_name + "' (number has no integer representation)"); } } auto create_table_table(MemoryAllocator* allocator) -> Table { Table table(allocator); table.set("concat", table::concat); table.set("insert", table::insert); table.set("move", table::insert); table.set("pack", table::pack); table.set("remove", table::remove); table.set("sort", table::sort); table.set("unpack", table::unpack); return table; } namespace table { auto concat(const CallContext& ctx) -> Value { // Didn't add an origin because i have no idea how i should reverse this because i would need // the seperator to split it back up std::string result; auto list = ctx.arguments().get(0); auto sep = ctx.arguments().get(1); auto i = ctx.arguments().get(2); auto j = ctx.arguments().get(3); return std::visit( overloaded{ [&result](const Table& list, Nil /*unused*/, Nil /*unused*/, Nil /*unused*/) -> Value { for (int m = 1; m <= list.border(); m++) { Value v = list.get(m); if (!v.is_number() && !v.is_string()) { throw std::runtime_error( "Invalid value (" + v.type() + ") in table for 'concat'!"); } String vs = std::get<String>(v.to_string()); result += vs.value; } return Value(result); }, [&result, &sep](const Table& list, auto /*sep*/, Nil /*unused*/, Nil /*unused*/) -> Value { if (!sep.is_number() && !sep.is_string()) { throw std::runtime_error( "bad argument #2 to 'concat' (string expected, got " + sep.type() + ")"); } String s = std::get<String>(sep.to_string()); for (int m = 1; m <= list.border(); m++) { Value v = list.get(m); if (!v.is_number() && !v.is_string()) { throw std::runtime_error( "Invalid value (" + v.type() + ") in table for 'concat'!"); } String vs = std::get<String>(v.to_string()); result += vs.value; if (m != list.border()) { result += s.value; } } return Value(result); }, [&result, &sep, &i](const Table& list, auto /*sep*/, auto /*i*/, Nil /*unused*/) -> Value { if (!sep.is_number() && !sep.is_string()) { throw std::runtime_error( "bad argument #2 to 'concat' (string expected, got " + sep.type() + ")"); } String s = std::get<String>(sep.to_string()); int m = try_value_is_int(std::move(i), "concat", 3); for (; m <= list.border(); m++) { Value v; if (list.has(m)) { v = list.get(m); } else { throw std::runtime_error( "invalid value (nil) at index " + std::to_string(m) + " for 'concat'"); } if (!v.is_number() && !v.is_string()) { throw std::runtime_error( "Invalid value (" + v.type() + ") in table for 'concat'!"); } String vs = std::get<String>(v.to_string()); result += vs.value; if (m != list.border()) { result += s.value; } } return Value(result); }, [&result, &sep, &i, &j](const Table& list, auto /*sep*/, auto /*i*/, auto /*j*/) -> Value { if (!sep.is_number() && !sep.is_string()) { throw std::runtime_error( "bad argument #2 to 'concat' (string expected, got " + sep.type() + ")"); } String s = std::get<String>(sep.to_string()); int m = try_value_is_int(std::move(i), "concat", 3); int j_int = try_value_is_int(std::move(j), "concat", 4); ; for (; m <= j_int; m++) { Value v; if (list.has(m)) { v = list.get(m); } else { throw std::runtime_error( "invalid value (nil) at index " + std::to_string(m) + " for 'concat'"); } if (!v.is_number() && !v.is_string()) { throw std::runtime_error( "Invalid value (" + v.type() + ") in table for 'concat'!"); } String vs = std::get<String>(v.to_string()); result += vs.value; if (m != j_int) { result += s.value; } } return Value(result); }, [](auto list, auto /*unused*/, auto /*unused*/, auto /*unused*/) -> Value { throw std::runtime_error( "bad argument #1 to 'concat' (table expected, got " + std::string(list.TYPE) + ")"); }}, list.raw(), sep.raw(), i.raw(), j.raw()); } void insert(const CallContext& ctx) { auto list = ctx.arguments().get(0); auto pos = ctx.arguments().get(1); auto value = ctx.arguments().get(2); // Casulty because we return nil if no argument is given, but nil could be inserted. This edge // case throws an error in our program, in lua the insertion works as intended I don't have an // idea how to do that besides this way. if (ctx.arguments().size() < 3) { throw std::runtime_error("wrong number of arguments to 'insert'"); } std::visit( overloaded{ [&value](Table& table, Nil /*unused*/) { Number pos = table.border() + 1; table.set(pos, value); }, [&pos, &value](Table& table, auto /*pos*/) { int p = try_value_is_int(pos, "insert", 2); if (p < 1 || p > table.border()) { throw std::runtime_error( "bad argument #2 to 'insert' (position out of bounds)"); } else { // move every element one to the right so make space for the new element that is // inserted if pos is already occupied for (int i = table.border(); i >= p; i--) { table.set(i + 1, table.get(i)); } } table.set(p, value); }, [](auto table, auto /*unused*/) { throw std::runtime_error( "bad argument #1 to 'insert' (table expected, got " + std::string(table.TYPE) + ")"); }}, list.raw(), pos.raw()); } auto move(const CallContext& ctx) -> Value { // No origin needed because a2 is already given as an existing value auto a1 = ctx.arguments().get(0); auto f = ctx.arguments().get(1); auto e = ctx.arguments().get(2); auto t = ctx.arguments().get(3); auto a2 = ctx.arguments().get(4); return std::visit( overloaded{ [&f, &e, &t](Table a1, Nil /*unused*/) -> Value { int fi = try_value_is_int(f, "move", 2); int ei = try_value_is_int(e, "move", 3); int ti = try_value_is_int(t, "move", 4); for (; fi <= ei; fi++) { a1.set(ti, a1.get(fi)); ti++; } return a1; }, [&f, &e, &t](const Table& a1, Table a2) -> Value { int fi = try_value_is_int(f, "move", 2); int ei = try_value_is_int(e, "move", 3); int ti = try_value_is_int(t, "move", 4); for (; fi <= ei; fi++) { a2.set(ti, a1.get(fi)); ti++; } return a2; }, [](const Table& /*unused*/, auto a2) -> Value { throw std::runtime_error( "bad argument #5 to 'move' (table expected, got " + std::string(a2.TYPE) + ")"); }, [](auto a1, auto /*unused*/) -> Value { throw std::runtime_error( "bad argument #1 to 'move' (table expected, got " + std::string(a1.TYPE) + ")"); }}, a1.raw(), a2.raw()); } auto pack(const CallContext& ctx) -> Value { Origin origin = Origin(MultipleArgsOrigin{ .values = std::make_shared<Vallist>(ctx.arguments()), .location = ctx.call_location(), .reverse = [](const Value& new_value, const Vallist& args) -> std::optional<SourceChangeTree> { Table t = std::get<Table>(new_value); SourceChangeCombination trees; auto it = args.begin(); for (const auto& [key, value] : t) { if (key.type() != Number::TYPE || std::get<Number>(key).try_as_int() < 1 || std::get<Number>(key).try_as_int() > t.border() || std::get<Number>(key).try_as_int() > args.size()) { break; } auto sct = *it->force(value); trees.add(sct); it++; } return SourceChangeTree(trees); }}); Table t = Table(); int i = 1; for (const auto& a : ctx.arguments()) { t.set(i++, a); } return Value(t).with_origin(origin); } auto remove(const CallContext& ctx) -> Value { // Doesn't need an origin because the value that is returned already should has one since it // isn't generated new auto list = ctx.arguments().get(0); auto pos = ctx.arguments().get(1); return std::visit( overloaded{ [](Table list, Nil /*unused*/) -> Value { auto tmp = list.get(list.border()); list.remove(list.border()); return tmp; }, [&pos](Table list, auto /*pos*/) -> Value { int posi = try_value_is_int(pos, "remove", 2); if (posi > list.border() + 1 || (posi < 1 && list.border() != 0)) { throw std::runtime_error( "bad argument #2 to 'remove' (position out of bounds)"); } auto tmp = list.get(posi); if (posi == list.border() + 1) { list.remove(posi); return tmp; } for (int i = posi + 1; i <= list.border(); i++) { list.set(posi, list.get(i)); posi++; } list.remove(list.border()); return tmp; }, [](auto list, auto /*unused*/) -> Value { throw std::runtime_error( "bad argument #1 to 'remove' (table expected, got " + std::string(list.TYPE) + ")"); }}, list.raw(), pos.raw()); } void sort(const CallContext& ctx) { auto list = ctx.arguments().get(0); auto comp = ctx.arguments().get(1); std::visit( overloaded{ [](Table list, Nil /*unused*/) { std::vector<Value> content; for (int i = 1; i <= list.border(); i++) { content.push_back(list.get(i)); } std::sort(content.begin(), content.end(), [](const Value& a, const Value& b) { return std::get<Bool>(a.less_than(b)).value; }); for (int i = 1; i <= list.border(); i++) { list.set(i, content.at(i - 1)); } }, [&ctx](Table list, const Function& comp) { std::vector<Value> content; for (int i = 1; i <= list.border(); i++) { content.push_back(list.get(i)); } std::sort( content.begin(), content.end(), [&ctx, &comp](const Value& a, const Value& b) -> bool { auto c = ctx.make_new(Vallist{a, b}); auto erg = comp.call(c).values().get(0); // More arguments than 2 are possible, but they are always Nil. // 2 arguments must be there always since we must compare two values if (ctx.arguments().size() >= 2 && erg.type() == "boolean") { return std::get<Bool>(erg).value; } else { throw std::runtime_error("invalid order function for sorting"); } }); for (int i = 1; i <= list.border(); i++) { list.set(i, content.at(i - 1)); } }, [](const Table& /*unused*/, auto a) { throw std::runtime_error( "bad argument #2 to 'sort' (function expected, got " + std::string(a.TYPE) + ")"); }, [](auto list, auto /*unused*/) { throw std::runtime_error( "bad argument #1 to 'sort' (table expected, got " + std::string(list.TYPE) + ")"); }}, list.raw(), comp.raw()); } auto unpack(const CallContext& ctx) -> Vallist { // It only returns the Values of the Table, so no new values are generated and every value in // the vallist should keep its origin i think std::vector<Value> vector; auto list = ctx.arguments().get(0); auto i = ctx.arguments().get(1); auto j = ctx.arguments().get(2); return std::visit( overloaded{ [&vector](const Table& list, Nil /*unused*/, Nil /*unused*/) -> Vallist { for (int i = 1; i <= list.border(); i++) { auto v = list.get(i); vector.push_back(v); } return Vallist(vector); }, [&vector, &i](const Table& list, auto /*i*/, Nil /*unused*/) { int i_int = try_value_is_int(i, "unpack", 2); for (; i_int <= list.border(); i_int++) { vector.push_back(list.get(i_int)); } return Vallist(vector); }, [&vector, &i, &j](const Table& list, auto /*i*/, auto /*j*/) { int i_int = try_value_is_int(i, "unpack", 2); int j_int = try_value_is_int(j, "unpack", 3); for (; i_int <= j_int; i_int++) { vector.push_back(list.get(i_int)); } return Vallist(vector); }, [](auto list, auto /*unused*/, auto /*unused*/) -> Vallist { throw std::runtime_error( "bad argument #1 for 'unpack' (table expected, got " + std::string(list.TYPE) + ")"); }}, list.raw(), i.raw(), j.raw()); } } // end namespace table } // end namespace minilua
39.810748
100
0.443453
ThomasWitte
eeea3c01c736a4561216e651168c651d59733849
404
cpp
C++
Tokenizer.cpp
rohan-0100010110010100/FrontEnd-ComplerDesign-Lab
dde0c8609982bf6aa209af600af781984fc0b621
[ "MIT" ]
null
null
null
Tokenizer.cpp
rohan-0100010110010100/FrontEnd-ComplerDesign-Lab
dde0c8609982bf6aa209af600af781984fc0b621
[ "MIT" ]
null
null
null
Tokenizer.cpp
rohan-0100010110010100/FrontEnd-ComplerDesign-Lab
dde0c8609982bf6aa209af600af781984fc0b621
[ "MIT" ]
2
2018-10-11T14:14:55.000Z
2020-02-27T10:28:59.000Z
#include <string.h> #include <stdio.h> #include <conio.h> int main() { char str[80]; const char s[2] = "-"; char *token; clrscr(); printf("Enter String for tokenization: "); gets(str); token = strtok(str, s); while( token != NULL ) { printf( " %s\n", token ); token = strtok(NULL, s); } getch(); return(0); }
15.538462
48
0.472772
rohan-0100010110010100
eeec0d2d9fb95d6d0ebac8ebbbf46089ad41685d
5,392
cpp
C++
lib/seqan3/test/unit/search/search_scheme_test.cpp
SGSSGene/seqan3_demo
5602af4ba437c973d4f84eb3ccb58330044978e2
[ "BSD-3-Clause" ]
null
null
null
lib/seqan3/test/unit/search/search_scheme_test.cpp
SGSSGene/seqan3_demo
5602af4ba437c973d4f84eb3ccb58330044978e2
[ "BSD-3-Clause" ]
null
null
null
lib/seqan3/test/unit/search/search_scheme_test.cpp
SGSSGene/seqan3_demo
5602af4ba437c973d4f84eb3ccb58330044978e2
[ "BSD-3-Clause" ]
null
null
null
// ----------------------------------------------------------------------------------------------------- // Copyright (c) 2006-2020, Knut Reinert & Freie Universität Berlin // Copyright (c) 2016-2020, Knut Reinert & MPI für molekulare Genetik // This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License // shipped with this file and also available at: https://github.com/seqan/seqan3/blob/master/LICENSE.md // ----------------------------------------------------------------------------------------------------- #include <algorithm> #include <type_traits> #include "helper_search_scheme.hpp" #include <seqan3/search/algorithm/detail/search_scheme_algorithm.hpp> #include <gtest/gtest.h> template <uint8_t min_error, uint8_t max_error, bool precomputed_scheme> void error_distributions(auto & expected, auto & actual) { if constexpr (precomputed_scheme) { auto const & oss{seqan3::detail::optimum_search_scheme<min_error, max_error>}; seqan3::search_scheme_error_distribution(actual, oss); seqan3::search_scheme_error_distribution(expected, seqan3::trivial_search_scheme(min_error, max_error, oss.front().blocks())); } else { auto const & ss{seqan3::detail::compute_ss(min_error, max_error)}; seqan3::search_scheme_error_distribution(actual, ss); seqan3::search_scheme_error_distribution(expected, seqan3::trivial_search_scheme(min_error, max_error, ss.front().blocks())); } std::sort(expected.begin(), expected.end()); std::sort(actual.begin(), actual.end()); } TEST(search_scheme_test, error_distribution_coverage_optimum_search_schemes) { std::vector<std::vector<uint8_t> > expected, actual; error_distributions<0, 0, true>(expected, actual); EXPECT_EQ(actual, expected); error_distributions<0, 1, true>(expected, actual); EXPECT_EQ(actual, expected); error_distributions<1, 1, true>(expected, actual); EXPECT_EQ(actual, expected); error_distributions<0, 2, true>(expected, actual); EXPECT_EQ(actual, expected); error_distributions<1, 2, true>(expected, actual); EXPECT_EQ(actual, expected); error_distributions<2, 2, true>(expected, actual); EXPECT_EQ(actual, expected); error_distributions<0, 3, true>(expected, actual); EXPECT_EQ(actual, expected); error_distributions<1, 3, true>(expected, actual); EXPECT_EQ(actual, expected); error_distributions<2, 3, true>(expected, actual); EXPECT_EQ(actual, expected); error_distributions<3, 3, true>(expected, actual); EXPECT_EQ(actual, expected); } TEST(search_scheme_test, error_distribution_coverage_computed_search_schemes) { std::vector<std::vector<uint8_t> > expected, actual; error_distributions<0, 0, false>(expected, actual); EXPECT_EQ(actual, expected); error_distributions<0, 1, false>(expected, actual); EXPECT_EQ(actual, expected); error_distributions<1, 1, false>(expected, actual); EXPECT_EQ(actual, expected); error_distributions<0, 2, false>(expected, actual); EXPECT_EQ(actual, expected); error_distributions<1, 2, false>(expected, actual); EXPECT_EQ(actual, expected); error_distributions<2, 2, false>(expected, actual); EXPECT_EQ(actual, expected); error_distributions<0, 3, false>(expected, actual); EXPECT_EQ(actual, expected); error_distributions<1, 3, false>(expected, actual); EXPECT_EQ(actual, expected); error_distributions<2, 3, false>(expected, actual); EXPECT_EQ(actual, expected); error_distributions<3, 3, false>(expected, actual); EXPECT_EQ(actual, expected); error_distributions<3, 5, false>(expected, actual); EXPECT_EQ(actual, expected); error_distributions<0, 6, false>(expected, actual); EXPECT_EQ(actual, expected); error_distributions<7, 7, false>(expected, actual); EXPECT_EQ(actual, expected); } template <uint8_t min_error, uint8_t max_error, bool precomputed_scheme> bool check_disjoint_search_scheme() { std::vector<std::vector<uint8_t> > error_distributions; auto const & oss{seqan3::detail::optimum_search_scheme<min_error, max_error>}; seqan3::search_scheme_error_distribution(error_distributions, oss); uint64_t size = error_distributions.size(); std::sort(error_distributions.begin(), error_distributions.end()); error_distributions.erase(std::unique(error_distributions.begin(), error_distributions.end()), error_distributions.end()); return size == error_distributions.size(); } TEST(search_scheme_test, error_distribution_disjoint_optimum_search_schemes) { bool ret; ret = check_disjoint_search_scheme<0, 0, false>(); EXPECT_TRUE(ret); ret = check_disjoint_search_scheme<0, 1, false>(); EXPECT_TRUE(ret); ret = check_disjoint_search_scheme<0, 2, false>(); EXPECT_TRUE(ret); ret = check_disjoint_search_scheme<0, 3, false>(); EXPECT_TRUE(ret); }
37.186207
112
0.639837
SGSSGene
eeed81b675f735ef27211f8b2846f29330a02e90
790
hpp
C++
engine/engine/gems/image/cuda/yuv2rgb.cu.hpp
ddr95070/RMIsaac
ee3918f685f0a88563248ddea11d089581077973
[ "FSFAP" ]
1
2020-04-14T13:55:16.000Z
2020-04-14T13:55:16.000Z
engine/engine/gems/image/cuda/yuv2rgb.cu.hpp
ddr95070/RMIsaac
ee3918f685f0a88563248ddea11d089581077973
[ "FSFAP" ]
4
2020-09-25T22:34:29.000Z
2022-02-09T23:45:12.000Z
engine/engine/gems/image/cuda/yuv2rgb.cu.hpp
ddr95070/RMIsaac
ee3918f685f0a88563248ddea11d089581077973
[ "FSFAP" ]
1
2022-01-28T16:37:51.000Z
2022-01-28T16:37:51.000Z
/* Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited. */ #include <cuda_runtime.h> namespace isaac { // Converts a YUV420 (encoded as NV21) image bound to texture channels to RGB void ConvertNv21ToRgb(cudaTextureObject_t y_channel, cudaTextureObject_t uv_channel, unsigned char* rgb_output, unsigned int width, unsigned int height, unsigned int output_pitch); } // namespace isaac
37.619048
89
0.770886
ddr95070
eef3a5ff3595dbb69f895dd41ddbce2c6e07bfb1
627
hpp
C++
RIFF/RIFFBase.hpp
SegaraRai/MeiToAvi
ce5f57d79808e5b8f397d32d3f37c79b15ff4909
[ "MIT" ]
6
2020-02-04T09:24:29.000Z
2022-02-26T18:03:34.000Z
RIFF/RIFFBase.hpp
SegaraRai/MeiToAvi
ce5f57d79808e5b8f397d32d3f37c79b15ff4909
[ "MIT" ]
null
null
null
RIFF/RIFFBase.hpp
SegaraRai/MeiToAvi
ce5f57d79808e5b8f397d32d3f37c79b15ff4909
[ "MIT" ]
null
null
null
#ifndef ML_RIFFBASE_HPP #define ML_RIFFBASE_HPP #include <cstddef> #include <cstdint> #include <ios> #include <memory> #include "../Source/SourceBase.hpp" class RIFFDirBase; class RIFFBase { public: enum class Type { Chunk, List, Root, }; protected: RIFFDirBase* parent; public: RIFFBase(); virtual ~RIFFBase() = default; virtual Type GetType() const = 0; virtual std::streamsize GetOffset() const; virtual std::streamsize GetSize() const = 0; virtual std::shared_ptr<SourceBase> GetSource() = 0; virtual void SetParent(RIFFDirBase* parent); virtual void CreateSource(); }; #endif
15.292683
54
0.698565
SegaraRai
e102464f1c980633d4c3d101eac9f241350a931d
9,180
hh
C++
Files.hh
pirl-lpl/pirlplusplus
d3211b05fc18f11fc66d97d5bcaeabcbd0b8b6e0
[ "Apache-2.0" ]
null
null
null
Files.hh
pirl-lpl/pirlplusplus
d3211b05fc18f11fc66d97d5bcaeabcbd0b8b6e0
[ "Apache-2.0" ]
null
null
null
Files.hh
pirl-lpl/pirlplusplus
d3211b05fc18f11fc66d97d5bcaeabcbd0b8b6e0
[ "Apache-2.0" ]
null
null
null
/* Files PIRL CVS ID: $Id: Files.hh,v 1.11 2012/07/20 00:25:53 castalia Exp $ Copyright (C) 2006-2010 Arizona Board of Regents on behalf of the Planetary Image Research Laboratory, Lunar and Planetary Laboratory at the University of Arizona. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef _Files_ #define _Files_ #include <string> #include <sys/types.h> // For off_t. namespace PIRL { /*============================================================================== Constants */ //! Module identification name with source code version and date. extern const char *Files_ID; //! Host filesystem pathname delimiter ('/'). extern const char FILE_PATHNAME_DELIMITER; //! Filename extension delimiter ('.'). extern const char FILE_EXTENSION_DELIMITER; /*============================================================================== Functions */ /** Test if a file exists at a pathname. @param pathname The filesystem pathname to test. @return true if the file exists; false otherwise. */ bool file_exists (const std::string& pathname); /** Test if a file at a pathname is readable. Readability is determined by the system's access method. The file must be readable by the real ID of the process. @param pathname The pathname to test. @return true if the file is accessable and can be read; false otherwise. @throws runtime_error If the file attributes can not be obtained (MS/Windows only). */ bool file_is_readable (const std::string& pathname); /** Test if a file at a pathname is writeable. Writeability is determined by the system's access method. The file must be writeable by the real ID of the process. @param pathname The pathname to test. @return true if the file is accessable and can be written; false otherwise. @throws runtime_error If the file attributes can not be obtained (MS/Windows only). */ bool file_is_writeable (const std::string& pathname); /** Test if a file at a pathname is a normal file. @param pathname The pathname to test. @return true if the file is accessable and is a normal type of file; false otherwise. */ bool file_is_normal (const std::string& pathname); /** Test if a file at a pathname is a directory. @param pathname The pathname to test. @return true if the file is accessable and is a directory; false otherwise. */ bool file_is_directory (const std::string& pathname); /** Test if a file at a pathname is a link file. @param pathname The pathname to test. @return true if the file is accessable and is a link; false otherwise. */ bool file_is_link (const std::string& pathname); /** Get the size of a file. <b>N.B.</b>: For MS/Windows a directory always has a file size of zero. @param pathname The pathname to the file. @return The size of the file in bytes. This will be -1 if the file could not be accessed. The return data type is off_t, the natural type for a file offset value for the host system. */ off_t file_size (const std::string& pathname); /** Test if a pathname is an absolute pathname. An absolute pathname begins with the #FILE_PATHNAME_DELIMITER character. @param pathname The pathname to test. @return true if the pathname is an absolute pathname; false otherwise. */ bool file_is_absolute (const std::string& pathname); /** Clean a pathname of redundant segments. All sequences of multiple #FILE_PATHNAME_DELIMITER characters are replaced with a single delimiter. All sequences of #FILE_PATHNAME_DELIMITER-'.'-#FILE_PATHNAME_DELIMITER characters are replaced with a single delimiter. Any trailing #FILE_PATHNAME_DELIMITER is removed. @param pathname The pathname from which to obtain the extension. @return The cleaned pathname. <b>N.B.</b>: The pathname string is modified in place. */ std::string& clean_pathname (std::string& pathname); /** Get the full pathname for a filename. If the filename is relative the {@link #CWD() current working directory} of the process is prepended. The directory pathname is {@link clean_pathname(std::string&) cleaned} before it is returned. @param filename The filename for which to obtain an absolute pathname. @return The absolute pathname for the filename. @throws runtime_error If the current working directory can not be obtained. */ std::string file_pathname (const std::string& filename); /** Get the full pathname for a filename. If the filename is relative the directory is prepended. If the directory is relative the {@link #CWD() current working directory} of the process is prepended to it. The directory pathname is {@link clean_pathname(std::string&) cleaned} before it is returned. @param directory The directory to prepend to the filename if it is not an absolute pathname. @param filename The filename for which to obtain an absolute pathname. @return The absolute pathname for the filename. @throws runtime_error If the current working directory can not be obtained. */ std::string file_pathname (const std::string& directory, const std::string& filename); /** Get the current working directory of the process. This is a convenience function for the system getcwd function. @return The absolute pathname for the current working directory of the process. @throws runtime_error If the current working directory can not be obtained. */ std::string CWD (); /** Get the leading directory portion of a pathname. The leading directory portion of a pathname is that substring preceding the last #FILE_PATHNAME_DELIMITER, or the empty string if it does not contain the delimiter. <b>N.B.</b>: If the pathname contains only one delimiter that is the first character, then the leading directory pathname is the delimiter (i.e. the filesystem root). @param pathname The pathname from which to obtain the directory pathname. @return The directory pathname from the pathname. */ std::string file_directory (const std::string& pathname); /** Get the leading directory pathname portion of a pathname. The {@link #file_directory(const std::string&) leading directory} portion of the pathname is obtained. If it is not an {@link file_is_absolute(const std::string&) absolute pathname} the {@link #CWD() current working directory} of the process is prepended. The directory pathname is {@link clean_pathname(std::string&) cleaned} before it is returned. @param pathname The pathname from which to obtain the directory pathname. @return The directory pathname from the pathname. @throws runtime_error If the current working directory can not be obtained. */ std::string file_directory_pathname (const std::string& pathname); /** Get the final name portion of a pathname. The final name portion of a pathname is that substring following the last #FILE_PATHNAME_DELIMITER, or the entire string if it does not contain the delimiter. @param pathname The pathname from which to obtain the file's name. @return The name of the file referenced by the pathname. */ std::string file_name (const std::string& pathname); /** Get the basename of a file's pathname. The basename is that portion of the path preceeding the last #FILE_EXTENSION_DELIMITER; or the entire string if there it does not contain the delimiter. <b>N.B.</b>: Any directory segments of the pathname are retained in the basename; these can be removed using the file_name method. @param pathname The pathname from which to obtain the basename. @return The basename of the pathname. */ std::string file_basename (const std::string& pathname); /** Get a file's extension. The extension is that portion of the path following the last #FILE_EXTENSION_DELIMITER. This will be the empty string if no extension is present or the pathname ends with the delimiter. @param pathname The pathname from which to obtain the extension. @return The extension of the file referenced by the pathname. */ std::string file_extension (const std::string& pathname); /** Get the user's home directory pathname. @return The pathname of the effective user home directory. @throws runtime_error If the user info can not be obtained. */ std::string home_directory_pathname (); /** Get the effective username. @return The name of the effective user. @throws runtime_error If the user info can not be obtained (UNIX only). */ std::string username (); /** Get the effective user ID. @return The effective user ID value. */ unsigned int UID (); /** Get the effective group ID. @return The effective group ID value. */ unsigned int GID (); /** Get the name of the host system. @return The name of the host system. */ std::string hostname (); } // PIRL namespace #endif
31.875
80
0.745425
pirl-lpl
e107816cc441feae31ebcc0b53c8c75dbd2d2510
917
cpp
C++
MMOCoreORB/src/server/zone/managers/ship/ShipManager.cpp
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
18
2017-02-09T15:36:05.000Z
2021-12-21T04:22:15.000Z
MMOCoreORB/src/server/zone/managers/ship/ShipManager.cpp
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
61
2016-12-30T21:51:10.000Z
2021-12-10T20:25:56.000Z
MMOCoreORB/src/server/zone/managers/ship/ShipManager.cpp
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
71
2017-01-01T05:34:38.000Z
2022-03-29T01:04:00.000Z
/* * ShipManager.cpp * * Created on: 18/10/2013 * Author: victor */ #include "ShipManager.h" #include "templates/manager/DataArchiveStore.h" #include "templates/datatables/DataTableIff.h" ShipManager::ShipManager() { IffStream* iffStream = DataArchiveStore::instance()->openIffFile( "datatables/space/ship_components.iff"); if (iffStream == nullptr) { fatal("datatables/space/ship_components.iff could not be found."); return; } DataTableIff dtiff; dtiff.readObject(iffStream); for (int i = 0; i < dtiff.getTotalRows(); ++i) { DataTableRow* row = dtiff.getRow(i); Reference<ShipComponent*> component = new ShipComponent(); component->readObject(row); //info("loaded ship component " + component->getName() + " crc:0x" + String::hexvalueOf(int(component->getName().hashCode())), true); shipComponents.put(component->getName().hashCode(), component); } delete iffStream; }
24.131579
135
0.704471
V-Fib
e1099f393270d8e22b6138229f7b141a3a5530fa
519
cpp
C++
level_zero/tools/source/pin/pin.cpp
dkjiang2018/compute-runtime
310947e6ddefc4bb9a7a268fc1ee8639155b730c
[ "MIT" ]
1
2020-04-17T05:46:04.000Z
2020-04-17T05:46:04.000Z
level_zero/tools/source/pin/pin.cpp
dkjiang2018/compute-runtime
310947e6ddefc4bb9a7a268fc1ee8639155b730c
[ "MIT" ]
null
null
null
level_zero/tools/source/pin/pin.cpp
dkjiang2018/compute-runtime
310947e6ddefc4bb9a7a268fc1ee8639155b730c
[ "MIT" ]
null
null
null
/* * Copyright (C) 2019-2020 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "pin.h" #include "level_zero/core/source/module/module.h" #include "level_zero/source/inc/ze_intel_gpu.h" namespace L0 { static PinContext *PinContextInstance = nullptr; void PinContext::init(ze_init_flag_t flag) { if (!getenv_tobool("ZE_ENABLE_PROGRAM_INSTRUMENTATION")) { return; } if (PinContextInstance == nullptr) { PinContextInstance = new PinContext(); } } } // namespace L0
19.222222
62
0.691715
dkjiang2018
e116b7a2bd41239b474ad1af82c50031b9e728cc
9,656
cpp
C++
samples/gl-320-fbo-blit.cpp
galek/ogl-samples
38cada7a9458864265e25415ae61586d500ff5fc
[ "MIT" ]
571
2015-01-08T16:29:38.000Z
2022-03-16T06:45:42.000Z
samples/gl-320-fbo-blit.cpp
galek/ogl-samples
38cada7a9458864265e25415ae61586d500ff5fc
[ "MIT" ]
45
2015-01-15T12:47:28.000Z
2022-03-04T09:22:32.000Z
samples/gl-320-fbo-blit.cpp
galek/ogl-samples
38cada7a9458864265e25415ae61586d500ff5fc
[ "MIT" ]
136
2015-01-31T15:24:57.000Z
2022-02-17T19:26:24.000Z
#include "test.hpp" namespace { char const* VERT_SHADER_SOURCE("gl-320/fbo-blit.vert"); char const* FRAG_SHADER_SOURCE("gl-320/fbo-blit.frag"); char const* TEXTURE_DIFFUSE("kueken7_rgba8_srgb.dds"); glm::ivec2 const FRAMEBUFFER_SIZE(512, 512); struct vertex { vertex ( glm::vec2 const & Position, glm::vec2 const & Texcoord ) : Position(Position), Texcoord(Texcoord) {} glm::vec2 Position; glm::vec2 Texcoord; }; // With DDS textures, v texture coordinate are reversed, from top to bottom GLsizei const VertexCount(6); GLsizeiptr const VertexSize = VertexCount * sizeof(vertex); vertex const VertexData[VertexCount] = { vertex(glm::vec2(-1.5f,-1.5f), glm::vec2(0.0f, 0.0f)), vertex(glm::vec2( 1.5f,-1.5f), glm::vec2(1.0f, 0.0f)), vertex(glm::vec2( 1.5f, 1.5f), glm::vec2(1.0f, 1.0f)), vertex(glm::vec2( 1.5f, 1.5f), glm::vec2(1.0f, 1.0f)), vertex(glm::vec2(-1.5f, 1.5f), glm::vec2(0.0f, 1.0f)), vertex(glm::vec2(-1.5f,-1.5f), glm::vec2(0.0f, 0.0f)) }; namespace framebuffer { enum type { RENDER, RESOLVE, MAX }; }//namespace framebuffer namespace texture { enum type { DIFFUSE, COLORBUFFER, MAX }; }//namespace texture }//namespace class sample : public framework { public: sample(int argc, char* argv[]) : framework(argc, argv, "gl-320-fbo-blit", framework::CORE, 3, 2), VertexArrayName(0), BufferName(0), ColorRenderbufferName(0), ProgramName(0), UniformMVP(-1), UniformDiffuse(-1) {} private: std::array<GLuint, texture::MAX> TextureName; std::array<GLuint, framebuffer::MAX> FramebufferName; GLuint VertexArrayName; GLuint BufferName; GLuint ColorRenderbufferName; GLuint ProgramName; GLint UniformMVP; GLint UniformDiffuse; bool initProgram() { bool Validated = true; compiler Compiler; // Create program if(Validated) { GLuint VertShaderName = Compiler.create(GL_VERTEX_SHADER, getDataDirectory() + VERT_SHADER_SOURCE, "--version 150 --profile core"); GLuint FragShaderName = Compiler.create(GL_FRAGMENT_SHADER, getDataDirectory() + FRAG_SHADER_SOURCE, "--version 150 --profile core"); ProgramName = glCreateProgram(); glAttachShader(ProgramName, VertShaderName); glAttachShader(ProgramName, FragShaderName); glBindAttribLocation(ProgramName, semantic::attr::POSITION, "Position"); glBindAttribLocation(ProgramName, semantic::attr::TEXCOORD, "Texcoord"); glBindFragDataLocation(ProgramName, semantic::frag::COLOR, "Color"); glLinkProgram(ProgramName); Validated = Validated && Compiler.check(); Validated = Validated && Compiler.check_program(ProgramName); } if(Validated) { UniformMVP = glGetUniformLocation(ProgramName, "MVP"); UniformDiffuse = glGetUniformLocation(ProgramName, "Diffuse"); } return this->checkError("initProgram"); } bool initBuffer() { glGenBuffers(1, &BufferName); glBindBuffer(GL_ARRAY_BUFFER, BufferName); glBufferData(GL_ARRAY_BUFFER, VertexSize, VertexData, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); return this->checkError("initBuffer");; } bool initTexture() { gli::texture2d Texture(gli::load_dds((getDataDirectory() + TEXTURE_DIFFUSE).c_str())); gli::gl GL(gli::gl::PROFILE_GL32); glGenTextures(texture::MAX, &TextureName[0]); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, TextureName[texture::DIFFUSE]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, GLint(Texture.levels() - 1)); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); gli::gl::format const Format = GL.translate(Texture.format(), Texture.swizzles()); for(std::size_t Level = 0; Level < Texture.levels(); ++Level) { glTexImage2D(GL_TEXTURE_2D, GLint(Level), Format.Internal, GLsizei(Texture[Level].extent().x), GLsizei(Texture[Level].extent().y), 0, Format.External, Format.Type, Texture[Level].data()); } glGenerateMipmap(GL_TEXTURE_2D); // Allocate all mipmaps memory glBindTexture(GL_TEXTURE_2D, TextureName[texture::COLORBUFFER]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, FRAMEBUFFER_SIZE.x, FRAMEBUFFER_SIZE.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); glBindTexture(GL_TEXTURE_2D, 0); return true; } bool initFramebuffer() { glGenFramebuffers(framebuffer::MAX, &FramebufferName[0]); glGenRenderbuffers(1, &ColorRenderbufferName); glBindRenderbuffer(GL_RENDERBUFFER, ColorRenderbufferName); glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8, FRAMEBUFFER_SIZE.x, FRAMEBUFFER_SIZE.y); glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName[framebuffer::RENDER]); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, ColorRenderbufferName); if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) return this->checkError("initFramebuffer"); glBindFramebuffer(GL_FRAMEBUFFER, 0); glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName[framebuffer::RESOLVE]); glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, TextureName[texture::COLORBUFFER], 0); if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) return this->checkError("initFramebuffer"); glBindFramebuffer(GL_FRAMEBUFFER, 0); return this->checkError("initFramebuffer"); } bool initVertexArray() { glGenVertexArrays(1, &VertexArrayName); glBindVertexArray(VertexArrayName); glBindBuffer(GL_ARRAY_BUFFER, BufferName); glVertexAttribPointer(semantic::attr::POSITION, 2, GL_FLOAT, GL_FALSE, sizeof(vertex), BUFFER_OFFSET(0)); glVertexAttribPointer(semantic::attr::TEXCOORD, 2, GL_FLOAT, GL_FALSE, sizeof(vertex), BUFFER_OFFSET(sizeof(glm::vec2))); glBindBuffer(GL_ARRAY_BUFFER, 0); glEnableVertexAttribArray(semantic::attr::POSITION); glEnableVertexAttribArray(semantic::attr::TEXCOORD); glBindVertexArray(0); return this->checkError("initVertexArray"); } void renderFBO() { glm::mat4 Perspective = glm::perspective(glm::pi<float>() * 0.25f, float(FRAMEBUFFER_SIZE.y) / FRAMEBUFFER_SIZE.x, 0.1f, 100.0f); glm::mat4 Model = glm::scale(glm::mat4(1.0f), glm::vec3(1.0f,-1.0f, 1.0f)); glm::mat4 MVP = Perspective * this->view() * Model; glUniformMatrix4fv(UniformMVP, 1, GL_FALSE, &MVP[0][0]); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, TextureName[texture::DIFFUSE]); glBindVertexArray(VertexArrayName); glDrawArraysInstanced(GL_TRIANGLES, 0, VertexCount, 1); } void renderFB() { glm::vec2 WindowSize(this->getWindowSize()); glm::mat4 Perspective = glm::perspective(glm::pi<float>() * 0.25f, WindowSize.x / WindowSize.y, 0.1f, 100.0f); glm::mat4 Model = glm::mat4(1.0f); glm::mat4 MVP = Perspective * this->view() * Model; glUniformMatrix4fv(UniformMVP, 1, GL_FALSE, &MVP[0][0]); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, TextureName[texture::COLORBUFFER]); glBindVertexArray(VertexArrayName); glDrawArraysInstanced(GL_TRIANGLES, 0, VertexCount, 1); } bool begin() { bool Validated = true; if(Validated) Validated = initProgram(); if(Validated) Validated = initBuffer(); if(Validated) Validated = initTexture(); if(Validated) Validated = initFramebuffer(); if(Validated) Validated = initVertexArray(); return Validated && this->checkError("begin"); } bool end() { glDeleteProgram(ProgramName); glDeleteBuffers(1, &BufferName); glDeleteTextures(texture::MAX, &TextureName[0]); glDeleteRenderbuffers(1, &ColorRenderbufferName); glDeleteFramebuffers(framebuffer::MAX, &FramebufferName[0]); glDeleteVertexArrays(1, &VertexArrayName); return true; } bool render() { glm::vec2 WindowSize(this->getWindowSize()); glUseProgram(ProgramName); glUniform1i(UniformDiffuse, 0); // Pass 1 glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName[framebuffer::RENDER]); glViewport(0, 0, FRAMEBUFFER_SIZE.x, FRAMEBUFFER_SIZE.y); glClearBufferfv(GL_COLOR, 0, &glm::vec4(0.0f, 0.5f, 1.0f, 1.0f)[0]); renderFBO(); glBindFramebuffer(GL_FRAMEBUFFER, 0); // Generate FBO mipmaps glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, TextureName[texture::COLORBUFFER]); glGenerateMipmap(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, 0); // Blit framebuffers GLint const Border = 2; int const Tile = 4; glBindFramebuffer(GL_READ_FRAMEBUFFER, FramebufferName[framebuffer::RENDER]); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, FramebufferName[framebuffer::RESOLVE]); glClearBufferfv(GL_COLOR, 0, &glm::vec4(1.0f, 0.5f, 0.0f, 1.0f)[0]); for(int j = 0; j < Tile; ++j) for(int i = 0; i < Tile; ++i) { if((i + j) % 2) continue; glBlitFramebuffer(0, 0, FRAMEBUFFER_SIZE.x, FRAMEBUFFER_SIZE.y, FRAMEBUFFER_SIZE.x / Tile * (i + 0) + Border, FRAMEBUFFER_SIZE.x / Tile * (j + 0) + Border, FRAMEBUFFER_SIZE.y / Tile * (i + 1) - Border, FRAMEBUFFER_SIZE.y / Tile * (j + 1) - Border, GL_COLOR_BUFFER_BIT, GL_LINEAR); } // Pass 2 glBindFramebuffer(GL_FRAMEBUFFER, 0); glViewport(0, 0, static_cast<GLsizei>(WindowSize.x), static_cast<GLsizei>(WindowSize.y)); glClearBufferfv(GL_COLOR, 0, &glm::vec4(1.0f, 1.0f, 1.0f, 1.0f)[0]); renderFB(); return true; } }; int main(int argc, char* argv[]) { int Error = 0; sample Sample(argc, argv); Error += Sample(); return Error; }
29.710769
136
0.727527
galek
e11b11ad7daa7984011f9478308fbad2234acda0
424
hpp
C++
include/skyr/v2/unicode/ranges/sentinel.hpp
BioDataAnalysis/url
281501b0fdf00b52eeb114f6856a9a83004d204e
[ "BSL-1.0" ]
47
2019-08-24T13:43:45.000Z
2022-02-21T11:45:19.000Z
include/skyr/v2/unicode/ranges/sentinel.hpp
BioDataAnalysis/url
281501b0fdf00b52eeb114f6856a9a83004d204e
[ "BSL-1.0" ]
35
2018-10-13T10:35:00.000Z
2021-06-11T12:23:55.000Z
include/skyr/v2/unicode/ranges/sentinel.hpp
BioDataAnalysis/url
281501b0fdf00b52eeb114f6856a9a83004d204e
[ "BSL-1.0" ]
25
2019-02-19T02:46:21.000Z
2021-10-21T14:53:00.000Z
// Copyright 2020 Glyn Matthews. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef SKYR_V2_UNICODE_RANGES_SENTINEL_HPP #define SKYR_V2_UNICODE_RANGES_SENTINEL_HPP namespace skyr::inline v2::unicode { class sentinel {}; } // namespace skyr::inline v2::unicode #endif // SKYR_V2_UNICODE_RANGES_SENTINEL_HPP
30.285714
61
0.787736
BioDataAnalysis
e11b5643056209ff627e1d9744991e3476a518c0
614
cpp
C++
SourceCode/Chapter 15/GradedActivity Version 1/Pr15-1.cpp
aceiro/poo2019
0f93d22296f43a8b024a346f510c00314817d2cf
[ "MIT" ]
1
2019-04-09T18:29:38.000Z
2019-04-09T18:29:38.000Z
SourceCode/Chapter 15/GradedActivity Version 1/Pr15-1.cpp
aceiro/poo2019
0f93d22296f43a8b024a346f510c00314817d2cf
[ "MIT" ]
null
null
null
SourceCode/Chapter 15/GradedActivity Version 1/Pr15-1.cpp
aceiro/poo2019
0f93d22296f43a8b024a346f510c00314817d2cf
[ "MIT" ]
null
null
null
// This program demonstrates the GradedActivity class. #include <iostream> #include "GradedActivity.h" using namespace std; int main() { double testScore; // To hold a test score // Create a GradedActivity object for the test. GradedActivity test; // Get a numeric test score from the user. cout << "Enter your numeric test score: "; cin >> testScore; // Store the numeric score in the test object. test.setScore(testScore); // Display the letter grade for the test. cout << "The grade for that test is " << test.getLetterGrade() << endl; return 0; }
24.56
54
0.659609
aceiro
e125f5c785a485c804fce2c96ffe04b7dfd90908
1,270
cpp
C++
MemoryzeUM/TCPEndpoint.cpp
allewwaly/dementia-forensics
401423fd8ba4f4d2b6dbec461df2eb18f33ac734
[ "MIT" ]
9
2018-08-20T03:06:07.000Z
2021-06-14T14:46:43.000Z
MemoryzeUM/TCPEndpoint.cpp
zignie/dementia-forensics
201a10faa17f2d406073d29e9cb5385b30c405f8
[ "MIT" ]
null
null
null
MemoryzeUM/TCPEndpoint.cpp
zignie/dementia-forensics
201a10faa17f2d406073d29e9cb5385b30c405f8
[ "MIT" ]
2
2017-08-02T02:33:31.000Z
2017-09-03T17:56:33.000Z
#include "StdAfx.h" #include "TCPEndpoint.h" TCPEndpoint::TCPEndpoint(const DWORD dwPoolHeaderSize) { // initialize object name and tag m_szObjName = "TCP_ENDPOINT"; m_dwTag = 0x45706354; m_dwPoolHeaderSize = dwPoolHeaderSize; // initialize default offset SetDefaultOffsetsAndSizes(); } TCPEndpoint::~TCPEndpoint(void) { } void TCPEndpoint::SetDefaultOffsetsAndSizes( void ) { // first obtain OS version OSVERSIONINFO verInfo; ZeroMemory(&verInfo, sizeof(OSVERSIONINFO)); verInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); GetVersionEx(&verInfo); // THE CODE THAT FOLLOWS DOES NOT COVER ALL CASES // FIX ME!!! if(verInfo.dwMajorVersion == 5) { // using Windows XP x86 m_isPID = true; m_dwConnectionOwnerOffset = 0x18; } else if(verInfo.dwMajorVersion == 6) { m_isPID = false; // Vista/2008 have different offsets than Windows 7 if(verInfo.dwMinorVersion == 0) { #ifdef _WIN64 m_dwConnectionOwnerOffset = 0x210; #else // _WIN32 m_dwConnectionOwnerOffset = 0x160; #endif // _WIN64 } else { // using Windows 7 x86 defaults #ifdef _WIN64 m_dwConnectionOwnerOffset = 0x238; #else // _WIN32 m_dwConnectionOwnerOffset = 0x174; #endif // _WIN64 } } }
21.166667
55
0.692913
allewwaly
e12663c852c4dc04e585c68031d8e49fe158d4e8
651
hpp
C++
Axis.Core/services/management/UserModuleProxy.hpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
2
2021-07-23T08:49:54.000Z
2021-07-29T22:07:30.000Z
Axis.Core/services/management/UserModuleProxy.hpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
null
null
null
Axis.Core/services/management/UserModuleProxy.hpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
null
null
null
#pragma once #include "ProviderProxy.hpp" namespace axis { namespace services { namespace management { class UserModuleProxy : public ProviderProxy { public: UserModuleProxy(Provider& provider, bool isNonVolatile); virtual ~UserModuleProxy(void); virtual bool IsBootstrapModule(void) const; virtual bool IsNonVolatileUserModule(void) const; virtual bool IsUserModule(void) const; virtual Provider& GetProvider(void) const; virtual bool IsCustomSystemModule( void ) const; virtual bool IsSystemModule( void ) const; private: bool _isNonVolatile; bool _isWeakModule; Provider& _provider; }; } } } // namespace axis::services::management
27.125
60
0.786482
renato-yuzup
e12f8806969adebcb4a575491bc4fb1a3a84fee0
49
hpp
C++
src/boost_hana_ext_boost_fusion_deque.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_hana_ext_boost_fusion_deque.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_hana_ext_boost_fusion_deque.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/hana/ext/boost/fusion/deque.hpp>
24.5
48
0.77551
miathedev
e131216988b37083b126bed680cfaa1b401e4336
1,030
cpp
C++
src/client/Country.cpp
john-fotis/SysPro2
d403493ddad4c962353ecc8b41a7cf20e3759b09
[ "MIT" ]
1
2021-08-20T11:19:49.000Z
2021-08-20T11:19:49.000Z
src/client/Country.cpp
john-fotis/SysPro2
d403493ddad4c962353ecc8b41a7cf20e3759b09
[ "MIT" ]
null
null
null
src/client/Country.cpp
john-fotis/SysPro2
d403493ddad4c962353ecc8b41a7cf20e3759b09
[ "MIT" ]
null
null
null
#include "include/Country.hpp" Country::Country(const Country &country) { if (this == &country) return; name.clear(); name.assign(country.getName()); } Country &Country::operator=(const Country &country) { if (this == &country) return *this; name.clear(); name.assign(country.getName()); return *this; } bool operator==(const Country &c1, const Country &c2) { return (c1.getName() == c2.getName()); } bool operator!=(const Country &c1, const Country &c2) { return !(c1 == c2); } bool operator<(const Country &c1, const Country &c2) { return c1.getName() < c2.getName(); } bool operator>(const Country &c1, const Country &c2) { return c1.getName() > c2.getName(); } bool operator<=(const Country &c1, const Country &c2) { return c1.getName() <= c2.getName(); } bool operator>=(const Country &c1, const Country &c2) { return c1.getName() >= c2.getName(); } std::ostream &operator<<(std::ostream &os, const Country &country) { os << country.getName(); return os; }
23.953488
68
0.639806
john-fotis
e1314ee536e7cfa437acc31cba31ad4953e63749
2,130
cpp
C++
configuration/HttpdConf.cpp
Peter408/webServer
84d7fefd85a3fcbba44c9905d6d1c5c61ff58b61
[ "MIT" ]
null
null
null
configuration/HttpdConf.cpp
Peter408/webServer
84d7fefd85a3fcbba44c9905d6d1c5c61ff58b61
[ "MIT" ]
null
null
null
configuration/HttpdConf.cpp
Peter408/webServer
84d7fefd85a3fcbba44c9905d6d1c5c61ff58b61
[ "MIT" ]
null
null
null
#include "HttpdConf.hpp" #include <iostream> #include <sstream> #include <algorithm> HttpdConf::HttpdConf(std::string fileName) : ConfigurationReader(fileName) { createDispatch(); } void HttpdConf::load() { while(hasMoreLines()) { std::istringstream iss(nextLine()); std::vector<std::string> tokens((std::istream_iterator<std::string>(iss)), std::istream_iterator<std::string>()); dispatcher[tokens[0]](tokens); } closeFile(); } std::string HttpdConf::removeQuotes(std::string &str) { str.erase(remove( str.begin(), str.end(), '\"' ),str.end()); return str; } void HttpdConf::createDispatch() { dispatcher = { {"ServerRoot", [&](std::vector<std::string> tokens) { serverRoot = removeQuotes(tokens[1]); }}, {"DocumentRoot", [&](std::vector<std::string> tokens) { documentRoot = removeQuotes(tokens[1]); }}, {"Listen", [&](std::vector<std::string> tokens) { port = std::stoi(tokens[1]); }}, {"LogFile", [&](std::vector<std::string> tokens) { logFile = removeQuotes(tokens[1]); }}, {"ScriptAlias", [&](std::vector<std::string> tokens) { scriptAliases [tokens[1]] = removeQuotes(tokens[2]); }}, {"Alias", [&](std::vector<std::string> tokens) { aliases [tokens[1]] = removeQuotes(tokens[2]); }}, {"AccessFile", [&](std::vector<std::string> tokens) { accessFile = removeQuotes(tokens[1]); }}, {"DirectoryIndex", [&](std::vector<std::string> tokens) { directoryIndex = removeQuotes(tokens[1]); }} }; } const std::unordered_map<std::string, std::string>& HttpdConf::getAliases() { return aliases; } const std::unordered_map<std::string, std::string>& HttpdConf::getScriptAliases() { return scriptAliases; } const std::string HttpdConf::getDocumentRoot() { return documentRoot; } const std::string HttpdConf::getLog() { return logFile; } const uint HttpdConf::getPort() { return port; }
28.783784
83
0.577465
Peter408
e1349809eb1e25d31982e9c4b985c4543d109a1f
5,516
cpp
C++
pop/src/commands/ScheduleRetryCommand.cpp
webOS-ports/mojomail
49358ac2878e010f5c6e3bd962f047c476c11fc3
[ "Apache-2.0" ]
6
2015-01-09T02:20:27.000Z
2021-01-02T08:14:23.000Z
mojomail/pop/src/commands/ScheduleRetryCommand.cpp
openwebos/app-services
021d509d609fce0cb41a0e562650bdd1f3bf4e32
[ "Apache-2.0" ]
3
2019-05-11T19:17:56.000Z
2021-11-24T16:04:36.000Z
mojomail/pop/src/commands/ScheduleRetryCommand.cpp
openwebos/app-services
021d509d609fce0cb41a0e562650bdd1f3bf4e32
[ "Apache-2.0" ]
6
2015-01-09T02:21:13.000Z
2021-01-02T02:37:10.000Z
// @@@LICENSE // // Copyright (c) 2009-2013 LG Electronics, 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. // // LICENSE@@@ #include "commands/ScheduleRetryCommand.h" #include "activity/ActivityBuilder.h" #include "commands/DeleteActivitiesCommand.h" #include "data/EmailAccountAdapter.h" #include "PopClient.h" #include "PopDefs.h" int ScheduleRetryCommand::INITIAL_RETRY_SECONDS = 60; int ScheduleRetryCommand::MAX_RETRY_SECONDS = 30 * 60; float ScheduleRetryCommand::RETRY_MULTIPLIER = 1.5; ScheduleRetryCommand::ScheduleRetryCommand(PopClient& client, const MojObject& folderId, EmailAccount::AccountError err) : PopClientCommand(client, "Schedule Retry"), m_folderId(folderId), m_accntErr(err), m_scheduleRetrySlot(this, &ScheduleRetryCommand::ScheduleRetryResponse), m_deleteActivitiesSlot(this, &ScheduleRetryCommand::CancelActivitiesDone), m_updateAccountSlot(this, &ScheduleRetryCommand::UpdateAccountResponse) { } ScheduleRetryCommand::~ScheduleRetryCommand() { } void ScheduleRetryCommand::RunImpl() { try { if (!m_client.GetAccount().get()) { MojString err; err.format("Account is not loaded for '%s'", AsJsonString( m_client.GetAccountId()).c_str()); throw MailException(err.data(), __FILE__, __LINE__); } ScheduleRetry(); } catch (const std::exception& ex) { Failure(ex); } catch (...) { Failure(MailException("Unknown exception in scheduling POP account retry", __FILE__, __LINE__)); } } void ScheduleRetryCommand::ScheduleRetry() { ActivityBuilder ab; // Get current retry interval from account EmailAccount::RetryStatus retryStatus = m_client.GetAccount()->GetRetry(); int interval = retryStatus.GetInterval(); if(interval <= INITIAL_RETRY_SECONDS) { interval = INITIAL_RETRY_SECONDS; } else if(interval >= MAX_RETRY_SECONDS) { interval = MAX_RETRY_SECONDS; } else { // TODO: only update this on actual retry? interval *= RETRY_MULTIPLIER; } // Update account just in case it wasn't within the limit retryStatus.SetInterval(interval); m_client.GetAccount()->SetRetry(retryStatus); m_client.GetActivityBuilderFactory()->BuildFolderRetrySync(ab, m_folderId, interval); MojErr err; MojObject payload; err = payload.put("activity", ab.GetActivityObject()); ErrorToException(err); err = payload.put("start", true); ErrorToException(err); err = payload.put("replace", true); MojLogInfo(m_log, "Creating retry activity in activity manager: %s", AsJsonString(payload).c_str()); m_client.SendRequest(m_scheduleRetrySlot, "com.palm.activitymanager", "create", payload); } MojErr ScheduleRetryCommand::ScheduleRetryResponse(MojObject& response, MojErr err) { try { MojLogInfo(m_log, "Retry activity creation: %s", AsJsonString(response).c_str()); ErrorToException(err); CancelActivities(); } catch (const std::exception& e) { MojLogError(m_log, "Exception in schedule retry response: '%s'", e.what()); Failure(e); } catch (...) { MojLogError(m_log, "Unknown exception in schedule retry response"); Failure(MailException("Unknown exception in schedule retry response", __FILE__, __LINE__)); } return MojErrNone; } void ScheduleRetryCommand::CancelActivities() { // Delete anything that includes the folderId in the name MojString folderIdSubstring; MojErr err = folderIdSubstring.format("folderId=%s", AsJsonString(m_folderId).c_str()); ErrorToException(err); MojString retryActivityName; m_client.GetActivityBuilderFactory()->GetFolderRetrySyncActivityName(retryActivityName, m_folderId); m_deleteActivitiesCommand.reset(new DeleteActivitiesCommand(m_client)); m_deleteActivitiesCommand->SetIncludeNameFilter(folderIdSubstring); m_deleteActivitiesCommand->SetExcludeNameFilter(retryActivityName); m_deleteActivitiesCommand->Run(m_deleteActivitiesSlot); } MojErr ScheduleRetryCommand::CancelActivitiesDone() { try { m_deleteActivitiesCommand->GetResult()->CheckException(); UpdateAccount(); } catch (const std::exception& e) { MojLogError(m_log, "Exception in cancel activities done: '%s'", e.what()); Failure(e); } catch (...) { MojLogError(m_log, "Unknown exception in cancel activities done"); Failure(MailException("Unknown exception in cancel activities done", __FILE__, __LINE__)); } return MojErrNone; } void ScheduleRetryCommand::UpdateAccount() { MojObject accountObj; EmailAccountAdapter::SerializeAccountRetryStatus(*m_client.GetAccount().get(), accountObj); m_client.GetDatabaseInterface().UpdateAccountRetry(m_updateAccountSlot, m_client.GetAccountId(), accountObj); } MojErr ScheduleRetryCommand::UpdateAccountResponse(MojObject& response, MojErr err) { try { ErrorToException(err); Complete(); } catch (const std::exception& e) { MojLogError(m_log, "Exception in update account response: '%s'", e.what()); Failure(e); } catch (...) { MojLogError(m_log, "Unknown exception in update account response"); Failure(MailException("Unknown exception in update account response", __FILE__, __LINE__)); } return MojErrNone; }
31.701149
120
0.759608
webOS-ports
e1380090e5e4c8865b84376be2e656aee9792197
935
hpp
C++
include/hydro/parser/__ast/ParamDecl.hpp
hydraate/hydro
42037a8278dcfdca68fb5cceaf6988da861f0eff
[ "Apache-2.0" ]
null
null
null
include/hydro/parser/__ast/ParamDecl.hpp
hydraate/hydro
42037a8278dcfdca68fb5cceaf6988da861f0eff
[ "Apache-2.0" ]
null
null
null
include/hydro/parser/__ast/ParamDecl.hpp
hydraate/hydro
42037a8278dcfdca68fb5cceaf6988da861f0eff
[ "Apache-2.0" ]
null
null
null
// // __ __ __ // / / / /__ __ ____/ /_____ ____ // / /_/ // / / // __ // ___// __ \ // / __ // /_/ // /_/ // / / /_/ / // /_/ /_/ \__, / \__,_//_/ \____/ // /____/ // // The Hydro Programming Language // #ifndef __h3o_ParamDecl__ #define __h3o_ParamDecl__ #include "Decl.hpp" #include "TypeSpec.hpp" #include "Expr.hpp" #include "ParamSymbol.hpp" namespace hydro { class ParamDecl : public Decl { private: TypeSpec *_type; Expr *_defaultValue; public: ParamDecl(Token *token, Modifier *mod, Name *name, TypeSpec *type, ParamSymbol *symbol, Expr *defaultValue = nullptr); virtual ~ParamDecl(); TypeSpec *type() const { return _type; } Expr *defaultValue() const { return _defaultValue; } }; } // namespace hydro #endif /* __h3o_ParamDecl__ */
23.974359
122
0.516578
hydraate
e13869e260aa5e30185c4fcd0ae77230901e373a
2,128
cpp
C++
Phase 1 Placement Specific/11. Strings/basic_functions.cpp
priyanshd2510/CPP-DSA
00f5d1018ae2bd4e3d9c20a8b9d06c8ea862190f
[ "Apache-2.0" ]
42
2021-01-03T17:54:59.000Z
2022-03-26T15:57:01.000Z
Phase 1 Placement Specific/11. Strings/basic_functions.cpp
sauhard2701/CPP-DSA
1e9202c7b6a15e13aff9edd9220f362e0d84abc6
[ "Apache-2.0" ]
26
2021-04-05T07:54:21.000Z
2021-12-10T07:35:39.000Z
Phase 1 Placement Specific/11. Strings/basic_functions.cpp
sauhard2701/CPP-DSA
1e9202c7b6a15e13aff9edd9220f362e0d84abc6
[ "Apache-2.0" ]
56
2020-12-24T17:06:33.000Z
2022-02-06T18:21:33.000Z
#include <bits/stdc++.h> using namespace std; int main(){ string str,str1,str2,s; // zero based indexing string sr (6,'0'); // create a string of "aaaaaa" cout<<sr<<endl; getline(cin,s); //input a string with spaces cout<<s<<endl; //append or add or concatenate 2 strings str1 = "worry"; str2 = "about me"; str1.append(str2); // OR str1 = str1 + str2 cout<<str1+str2<<endl;//srt1 already contains worryabout me //length() or size() is same for(int i = 0; i<str1.length(); i++){ cout<<str1[i]<<" "; // we can treat string like arrays } cout<<endl; str1.clear(); // empty string str1 = "lost frequencies"; // cout<<str1<<" "<<str2<<endl; //compare function -> return 0 if true or string equal cout<<str1.compare(str2)<<endl;//return +ve number means that str1 is lexicographical greater than str2 cout<<str2.compare(str1)<<endl;// return -ve number means str2 is smaller str2 = str1; // self explanatory if(!str1.compare(str2)){ cout<<"String equals"; } else{ cout<<"strings not equal"; } cout<<endl; if(str.empty()){ cout<<"string is empty"<<endl; } str = "greatness"; str.erase(5,4);// it deletes the character starting from index 5 that is n to 5+4=9 ie s cout<<str<<endl;//output "great" only cout<<str.find("eat")<<endl;//found "eat" in "great" at index 2 cout<<str.insert(5,"ness")<<endl; // this is not zero based indexing s = str.substr(2,5); // copy char from index 2 that is 'e' till 5 ie 'e' in word 'greatness' cout<<s<<endl; s = "3000"; int x = stoi(s); // convert string to int datatype cout<<x/10<<endl; x = 420; s = to_string(x); cout<<s + " samaj jao"<<endl; // convert int to string cout<<endl; str += str1 + str2 +s + "@#!$%&*($#@1356"; cout<<str<<endl;//adding all the strings or concatenating cout<<endl; //sorting string sort(str.begin(),str.end()); cout<<str<<endl; // 2 spaces are sorted first because in the word "lost frequencies" return 0; }
25.638554
107
0.590226
priyanshd2510
e1388f6a440d029ab35a4e15c1744e8399d033c3
1,761
cpp
C++
src/PointVisual.cpp
StevenHong/dwl-rviz-plugin
61b4f70408873dc67712eb6c3afed2e5e3e024ae
[ "BSD-3-Clause" ]
10
2018-02-07T09:50:25.000Z
2021-01-24T08:30:03.000Z
src/PointVisual.cpp
StevenHong/dwl-rviz-plugin
61b4f70408873dc67712eb6c3afed2e5e3e024ae
[ "BSD-3-Clause" ]
1
2022-02-11T10:08:51.000Z
2022-02-11T10:08:51.000Z
src/PointVisual.cpp
StevenHong/dwl-rviz-plugin
61b4f70408873dc67712eb6c3afed2e5e3e024ae
[ "BSD-3-Clause" ]
4
2018-03-15T10:28:01.000Z
2022-02-10T21:38:43.000Z
#include <OgreVector3.h> #include <OgreSceneNode.h> #include <OgreSceneManager.h> #include <rviz/ogre_helpers/shape.h> #include <dwl_rviz_plugin/PointVisual.h> namespace dwl_rviz_plugin { PointVisual::PointVisual(Ogre::SceneManager* scene_manager, Ogre::SceneNode* parent_node) : radius_(0.) { scene_manager_ = scene_manager; // Ogre::SceneNode s form a tree, with each node storing the transform (position and // orientation) of itself relative to its parent. Ogre does the math of combining those // transforms when it is time to render. // Here we create a node to store the pose of the Point's header frame relative to the RViz // fixed frame. frame_node_ = parent_node->createChildSceneNode(); // We create the point object within the frame node so that we can set its position. point_ = new rviz::Shape(rviz::Shape::Sphere, scene_manager_, frame_node_); } PointVisual::~PointVisual() { // Delete the point to make it disappear. delete point_; // Destroy the frame node since we don't need it anymore. scene_manager_->destroySceneNode(frame_node_); } void PointVisual::setPoint(const Ogre::Vector3& point) { Ogre::Vector3 scale(radius_, radius_, radius_); point_->setScale(scale); // Set the orientation of the arrow to match the direction of the acceleration vector. point_->setPosition(point); } void PointVisual::setFramePosition(const Ogre::Vector3& position) { frame_node_->setPosition(position); } void PointVisual::setFrameOrientation(const Ogre::Quaternion& orientation) { frame_node_->setOrientation(orientation); } void PointVisual::setColor(float r, float g, float b, float a) { point_->setColor(r, g, b, a); } void PointVisual::setRadius(float r) { radius_ = r; } } //@namespace dwl_rviz_plugin
24.123288
92
0.75071
StevenHong
e138a542414962863139e1abdaec88cfcdbae984
4,038
cpp
C++
src/TestMushMesh/TestMushMeshApp.cpp
mushware/adanaxis-core-app
679ac3e8a122e059bb208e84c73efc19753e87dd
[ "MIT" ]
9
2020-11-02T17:20:40.000Z
2021-12-25T15:35:36.000Z
src/TestMushMesh/TestMushMeshApp.cpp
mushware/adanaxis-core-app
679ac3e8a122e059bb208e84c73efc19753e87dd
[ "MIT" ]
2
2020-06-27T23:14:13.000Z
2020-11-02T17:28:32.000Z
src/TestMushMesh/TestMushMeshApp.cpp
mushware/adanaxis-core-app
679ac3e8a122e059bb208e84c73efc19753e87dd
[ "MIT" ]
1
2021-05-12T23:05:42.000Z
2021-05-12T23:05:42.000Z
//%Header { /***************************************************************************** * * File: src/TestMushMesh/TestMushMeshApp.cpp * * Copyright: Andy Southgate 2002-2007, 2020 * * 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. * ****************************************************************************/ //%Header } fLo4NYe7P7n7p3BjMIvqPA /* * $Id: TestMushMeshApp.cpp,v 1.11 2006/06/01 15:40:01 southa Exp $ * $Log: TestMushMeshApp.cpp,v $ * Revision 1.11 2006/06/01 15:40:01 southa * DrawArray verification and fixes * * Revision 1.10 2005/05/19 13:02:22 southa * Mac release work * * Revision 1.9 2004/01/02 21:13:16 southa * Source conditioning * * Revision 1.8 2003/10/24 12:39:09 southa * Triangular mesh work * * Revision 1.7 2003/10/23 20:03:58 southa * End mesh work * * Revision 1.6 2003/10/20 13:02:54 southa * Patch fixes and testing * * Revision 1.5 2003/10/17 12:27:20 southa * Line end fixes and more mesh work * * Revision 1.4 2003/10/15 12:23:10 southa * MushMeshArray neighbour testing and subdivision work * * Revision 1.3 2003/10/15 11:54:54 southa * MushMeshArray neighbour testing and subdivision * * Revision 1.2 2003/10/15 07:08:29 southa * MushMeshArray creation * * Revision 1.1 2003/10/14 13:07:26 southa * MushMesh vector creation * */ #include "TestMushMeshApp.h" using namespace Mushware; using namespace std; MUSHCORE_SINGLETON_INSTANCE(TestMushMeshApp); U32 TestMushMeshApp::m_passCount=0; TestMushMeshApp::tFails TestMushMeshApp::m_fails; void TestMushMeshApp::EnterInstance(void) { cout << "Starting tests" << endl; RunTest("testvector", "MushMeshVector"); RunTest("testbox", "MushMeshBox"); RunTest("testarray", "MushMeshArray"); RunTest("testtriangulararray", "MushMeshTriangularArray"); RunTest("testutils", "MushMeshUtils"); RunTest("testpatch", "MushMeshPatch"); RunTest("testsubdivide", "MushMeshSubdivide"); } void TestMushMeshApp::RunTest(const string& inCommandStr, const string& inNameStr) { cout << "Test " << inNameStr << "... "; try { MushcoreInterpreter::Sgl().Execute(inCommandStr); PassAdd(inNameStr); cout << "passed"; } catch (MushcoreFail& e) { cout << "FAILED"; FailureAdd(inNameStr+": "+e.what()); } cout << endl; } void TestMushMeshApp::Enter(void) { Sgl().EnterInstance(); } void TestMushMeshApp::FailureAdd(const std::string& inStr) { m_fails.push_back(inStr); } void TestMushMeshApp::PassAdd(const std::string& inStr) { ++m_passCount; } void TestMushMeshApp::FailuresPrint(void) { if (m_fails.size() == 0) { cout << "All " << m_passCount << " tests passed" << endl; } else { cout << "****** " << m_fails.size() << " test failures" << endl; cout << "Failure report:" << endl; } for (tFails::const_iterator p = m_fails.begin(); p != m_fails.end(); ++p) { cout << *p << endl; } }
28.237762
78
0.655275
mushware
e13da52398e3eaa5474ae908429a93b784ce55fd
4,011
cpp
C++
src/Window.cpp
PurpleAzurite/starter_project
9503bc689ec93bc21797e24bd9abb33bca75c140
[ "Apache-2.0" ]
null
null
null
src/Window.cpp
PurpleAzurite/starter_project
9503bc689ec93bc21797e24bd9abb33bca75c140
[ "Apache-2.0" ]
null
null
null
src/Window.cpp
PurpleAzurite/starter_project
9503bc689ec93bc21797e24bd9abb33bca75c140
[ "Apache-2.0" ]
null
null
null
// clang-format off #include "Window.h" #include "Events/KeyEvents.h" #include "Events/WindowEvents.h" #include "Events/MouseEvents.h" #include <utility> // clang-format on namespace Engine { Window::Window(WindowProps props) : m_data(std::move(props)) { glfwSetErrorCallback( [](int code, const char* msg) { ENGINE_ERROR("[GLFW] Error {}: {}", code, msg); }); glfwInit(); m_context = glfwCreateWindow(m_data.width, m_data.height, m_data.title.data(), nullptr, nullptr); glfwMakeContextCurrent(m_context); if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) ENGINE_ERROR("[GLAD] Could not load GLAD!"); glfwSetWindowUserPointer(m_context, reinterpret_cast<void*>(&m_data)); glfwSetWindowCloseCallback(m_context, [](GLFWwindow* window) { auto& data = *reinterpret_cast<WindowProps*>(glfwGetWindowUserPointer(window)); WindowClosedEvent event; data.callback(event); }); glfwSetWindowPosCallback(m_context, [](GLFWwindow* window, int x, int y) { auto& data = *reinterpret_cast<WindowProps*>(glfwGetWindowUserPointer(window)); WindowMovedEvent event(x, y); data.callback(event); }); glfwSetWindowSizeCallback(m_context, [](GLFWwindow* window, int width, int height) { // TODO: Should framebuffer be resized here? auto& data = *reinterpret_cast<WindowProps*>(glfwGetWindowUserPointer(window)); WindowResizedEvent event(width, height); data.callback(event); }); glfwSetWindowFocusCallback(m_context, [](GLFWwindow* window, int focus) { auto& data = *reinterpret_cast<WindowProps*>(glfwGetWindowUserPointer(window)); switch (focus) { case 1: { WindowFocusedEvent event; data.callback(event); break; } case 0: { WindowLostFocusEvent event; data.callback(event); break; } } }); glfwSetCursorPosCallback(m_context, [](GLFWwindow* window, double x, double y) { auto& data = *reinterpret_cast<WindowProps*>(glfwGetWindowUserPointer(window)); MouseMovedEvent event(x, y); data.callback(event); }); glfwSetMouseButtonCallback(m_context, [](GLFWwindow* window, int button, int action, int mods) { (void)mods; auto& data = *reinterpret_cast<WindowProps*>(glfwGetWindowUserPointer(window)); switch (action) { case GLFW_PRESS: { MouseButtonPressedEvent event(button); data.callback(event); break; } case GLFW_RELEASE: { MouseButtonReleasedEvent event(button); data.callback(event); break; } } }); glfwSetScrollCallback(m_context, [](GLFWwindow* window, double xOffset, double yOffset) { auto& data = *reinterpret_cast<WindowProps*>(glfwGetWindowUserPointer(window)); MouseScrolledEvent event(xOffset, yOffset); data.callback(event); }); glfwSetKeyCallback(m_context, [](GLFWwindow* window, int key, int scancode, int action, int mod) { (void)scancode; (void)action; (void)mod; auto& data = *reinterpret_cast<WindowProps*>(glfwGetWindowUserPointer(window)); switch(action) { case GLFW_PRESS: { KeyPressedEvent event(key); data.callback(event); break; } case GLFW_RELEASE: { KeyReleasedEvent event(key); data.callback(event); break; } } }); // TODO callbacks: key pressed, key // released } Window::~Window() { glfwDestroyWindow(m_context); glfwTerminate(); } void Window::update() { glfwSwapBuffers(m_context); glfwPollEvents(); } void Window::setCallbackFunction(const CallbackFn& fn) { m_data.callback = fn; } } // namespace Engine
28.446809
102
0.614061
PurpleAzurite
e13fa352ee2c1942e4a613b79cb77cfca27e2f54
747
cpp
C++
algorithms/convert-sorted-array-to-binary-search-tree.cpp
jlygit/leetcode-oj
66718f709b31ef0e7e091638d95418a5543019b4
[ "Apache-2.0" ]
1
2016-08-10T11:17:16.000Z
2016-08-10T11:17:16.000Z
algorithms/convert-sorted-array-to-binary-search-tree.cpp
jlygit/leetcode-oj
66718f709b31ef0e7e091638d95418a5543019b4
[ "Apache-2.0" ]
null
null
null
algorithms/convert-sorted-array-to-binary-search-tree.cpp
jlygit/leetcode-oj
66718f709b31ef0e7e091638d95418a5543019b4
[ "Apache-2.0" ]
null
null
null
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* makeBST(vector<int>& nums,int start,int end) { if(start>end) return NULL; TreeNode* t; if(start==end) { t=new TreeNode(nums[start]); } else { int m=(start+end)/2; t=new TreeNode(nums[m]); t->left=makeBST(nums,start,m-1); t->right=makeBST(nums,m+1,end); } return t; } TreeNode* sortedArrayToBST(vector<int>& nums) { return makeBST(nums,0,nums.size()-1); } };
26.678571
61
0.504685
jlygit
e1469b32e8c62fadac53e74a7b2300ede6a67de3
332
cpp
C++
higan/sfc/slot/sufamiturbo/sufamiturbo.cpp
mp-lee/higan
c38a771f2272c3ee10fcb99f031e982989c08c60
[ "Intel", "ISC" ]
38
2018-04-05T05:00:05.000Z
2022-02-06T00:02:02.000Z
higan/sfc/slot/sufamiturbo/sufamiturbo.cpp
mp-lee/higan
c38a771f2272c3ee10fcb99f031e982989c08c60
[ "Intel", "ISC" ]
1
2018-04-29T19:45:14.000Z
2018-04-29T19:45:14.000Z
higan/sfc/slot/sufamiturbo/sufamiturbo.cpp
libretro-mirrors/higan
8617711ea2c201a33442266945dc7ed186e9d695
[ "Intel", "ISC" ]
8
2018-04-16T22:37:46.000Z
2021-02-10T07:37:03.000Z
#include <sfc/sfc.hpp> namespace SuperFamicom { #include "serialization.cpp" SufamiTurboCartridge sufamiturboA; SufamiTurboCartridge sufamiturboB; auto SufamiTurboCartridge::unload() -> void { rom.reset(); ram.reset(); } auto SufamiTurboCartridge::power() -> void { rom.writeProtect(true); ram.writeProtect(false); } }
16.6
45
0.740964
mp-lee
e1481756e08e3a1d063417af62918508e7a6b072
4,528
cpp
C++
streambox/test/test-common.cpp
wzhao18/StreamBox
134b7445feca76a44ec3b183a60a270c46e6c067
[ "BSD-2-Clause" ]
1
2022-03-22T00:01:40.000Z
2022-03-22T00:01:40.000Z
streambox/test/test-common.cpp
wzhao18/StreamBox
134b7445feca76a44ec3b183a60a270c46e6c067
[ "BSD-2-Clause" ]
null
null
null
streambox/test/test-common.cpp
wzhao18/StreamBox
134b7445feca76a44ec3b183a60a270c46e6c067
[ "BSD-2-Clause" ]
null
null
null
#include <stdio.h> #include "log.h" #include "config.h" void print_config() { printf("config:\n"); #ifdef USE_NUMA_TP xzl_show_define(USE_NUMA_TP); #else xzl_show_undefine(USE_NUMA_TP); #endif #ifdef USE_TBB_DS xzl_show_define(USE_TBB_DS) #else xzl_show_undefine(USE_TBB_DS) #endif #ifdef USE_FOLLY_VECTOR xzl_show_define(USE_FOLLY_VECTOR) #else xzl_show_undefine(USE_FOLLY_VECTOR) #endif #ifdef USE_FOLLY_STRING xzl_show_define(USE_FOLLY_STRING) #else xzl_show_undefine(USE_FOLLY_STRING) #endif #ifdef USE_FOLLY_HASHMAP xzl_show_define(USE_FOLLY_HASHMAP) #else xzl_show_undefine(USE_FOLLY_HASHMAP) #endif #ifdef USE_CUCKOO_HASHMAP xzl_show_define(USE_CUCKOO_HASHMAP) #else xzl_show_undefine(USE_CUCKOO_HASHMAP) #endif #ifdef USE_TBB_HASHMAP xzl_show_define(USE_TBB_HASHMAP) #else xzl_show_undefine(USE_TBB_HASHMAP) #endif #ifdef USE_NUMA_ALLOC xzl_show_define(USE_NUMA_ALLOC) #else xzl_show_undefine(USE_NUMA_ALLOC) #endif #ifdef INPUT_ALWAYS_ON_NODE0 xzl_show_define(INPUT_ALWAYS_ON_NODE0) #else xzl_show_undefine(INPUT_ALWAYS_ON_NODE0) #endif #ifdef MEASURE_LATENCY xzl_show_define(MEASURE_LATENCY) #else xzl_show_undefine(MEASURE_LATENCY) #endif #ifdef CONFIG_SOURCE_THREADS xzl_show_define(CONFIG_SOURCE_THREADS) #else // xzl_show_undefine(CONFIG_SOURCE_THREADS) #error #endif #ifdef CONFIG_MIN_PERNODE_BUFFER_SIZE_MB xzl_show_define(CONFIG_MIN_PERNODE_BUFFER_SIZE_MB) #else // xzl_show_undefine(CONFIG_MIN_PERNODE_BUFFER_SIZE_MB) #error #endif #ifdef CONFIG_MIN_EPOCHS_PERNODE_BUFFER xzl_show_define(CONFIG_MIN_EPOCHS_PERNODE_BUFFER) #else // xzl_show_undefine(X) #error #endif #ifdef CONFIG_NETMON_HT_PARTITIONS xzl_show_define(CONFIG_NETMON_HT_PARTITIONS) #else #error #endif #ifdef CONFIG_JOIN_HT_PARTITIONS xzl_show_define(CONFIG_JOIN_HT_PARTITIONS) #else #error #endif /* warn about workarounds */ #ifdef WORKAROUND_JOIN_JDD EE("warning: WORKAROUND_JOIN_JDD = 1. Sure? (any key to continue)\n"); getchar(); #endif #ifdef WORKAROUND_WINKEYREDUCER_RECORDBUNDLE EE("warning: WORKAROUND_WINKEYREDUCER_RECORDBUNDLE = 1. Sure? (any key to continue)\n"); getchar(); #endif /* todo: add more here */ } // Copyright Vladimir Prus 2002-2004. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt // or copy at http://www.boost.org/LICENSE_1_0.txt) /* The simplest usage of the library. * * http://www.boost.org/doc/libs/1_61_0/libs/program_options/example/first.cpp * http://www.boost.org/doc/libs/1_61_0/libs/program_options/example/options_description.cpp */ #undef _GLIBCXX_DEBUG /* does not get along with program options lib */ #include <iostream> #include <boost/program_options.hpp> using namespace std; namespace po = boost::program_options; #include <thread> #include "test-common.h" void parse_options(int ac, char *av[], pipeline_config* config) { po::variables_map vm; xzl_assert(config); try { po::options_description desc("Allowed options"); desc.add_options() ("help", "produce help message") ("records", po::value<unsigned long>(), "records per wm interval") ("target_tput", po::value<unsigned long>(), "target throughput (krec/s)") ("record_size", po::value<unsigned long>(), "record (string_range) size (bytes)") ("cores", po::value<unsigned long>(), "# cores for worker threads") ("input_file", po::value<vector<string>>(), "input file path") /* must be vector */ ; po::store(po::parse_command_line(ac, av, desc), vm); po::notify(vm); if (vm.count("help")) { cout << desc << "\n"; exit(1); } if (vm.count("records")) { config->records_per_interval = vm["records"].as<unsigned long>(); } if (vm.count("target_tput")) { config->target_tput = vm["target_tput"].as<unsigned long>() * 1000; } if (vm.count("record_size")) { config->record_size = vm["record_size"].as<unsigned long>(); } if (vm.count("cores")) { config->cores = vm["cores"].as<unsigned long>(); } else { /* default value for # cores (save one for source) */ config->cores = std::thread::hardware_concurrency() - 1; } if (vm.count("input_file")) { config->input_file = vm["input_file"].as<vector<string>>()[0]; } } catch(exception& e) { cerr << "error: " << e.what() << "\n"; abort(); } catch(...) { cerr << "Exception of unknown type!\n"; abort(); } }
23.706806
93
0.71091
wzhao18
e1495da8c7f366f6d71aef71335b52b982ef4647
5,704
hpp
C++
Lodestar/blocks/std/SwitchBlock.hpp
helkebir/Lodestar
6b325d3e7a388676ed31d44eac1146630ee4bb2c
[ "BSD-3-Clause" ]
4
2020-06-05T14:08:23.000Z
2021-06-26T22:15:31.000Z
Lodestar/blocks/std/SwitchBlock.hpp
helkebir/Lodestar
6b325d3e7a388676ed31d44eac1146630ee4bb2c
[ "BSD-3-Clause" ]
2
2021-06-25T15:14:01.000Z
2021-07-01T17:43:20.000Z
Lodestar/blocks/std/SwitchBlock.hpp
helkebir/Lodestar
6b325d3e7a388676ed31d44eac1146630ee4bb2c
[ "BSD-3-Clause" ]
1
2021-06-16T03:15:23.000Z
2021-06-16T03:15:23.000Z
// // Created by Hamza El-Kebir on 12/23/21. // #ifndef LODESTAR_SWITCHBLOCK_HPP #define LODESTAR_SWITCHBLOCK_HPP #include "Lodestar/blocks/Block.hpp" namespace ls { namespace blocks { namespace std { enum class SwitchBlockParameter { Parametric, AdditionalInput }; template<typename TType, SwitchBlockParameter TPar = SwitchBlockParameter::Parametric> class SwitchBlock { static_assert(::std::is_same<TType, TType>::value, "SwitchBlock not defined for this type."); }; template<typename TType> class SwitchBlock<TType, SwitchBlockParameter::Parametric> : public Block< ::std::tuple<TType, TType>, ::std::tuple<TType>, ::std::tuple<bool> > { public: using Base = Block< ::std::tuple<TType, TType>, ::std::tuple<TType>, ::std::tuple<bool> >; using type = SwitchBlock<TType, SwitchBlockParameter::Parametric>; SwitchBlock() { state(false); bindEquation(); } SwitchBlock(const bool switchState) { state(switchState); bindEquation(); } bool &state(bool setting) { this->template p<0>() = setting; return this->template p<0>(); } bool state() const { return this->template p<0>(); } bool &state() { return this->template p<0>(); } void toggle() { state(!state()); } protected: void bindEquation() { this->equation = ::std::bind( &type::triggerFunction, this, ::std::placeholders::_1 ); } void triggerFunction(Base &b) { if (state()) this->template o<0>() = this->template i<1>(); else this->template o<0>() = this->template i<0>(); } }; template<typename TType> class SwitchBlock<TType, SwitchBlockParameter::AdditionalInput> : public Block< ::std::tuple<TType, TType, bool>, ::std::tuple<TType>, BlockProto::empty > { public: using Base = Block< ::std::tuple<TType, TType, bool>, ::std::tuple<TType>, BlockProto::empty >; using type = SwitchBlock<TType, SwitchBlockParameter::AdditionalInput>; SwitchBlock() { state(false); bindEquation(); } SwitchBlock(const bool switchState) { state(switchState); bindEquation(); } Signal<bool> &state(bool setting) { this->template i<2>() = setting; return this->template i<2>(); } Signal<bool> &state(const Signal<bool> &setting) { this->template i<2>() = setting; return this->template i<2>(); } const Signal<bool> &state() const { return this->template i<2>(); } Signal<bool> &state() { return this->template i<2>(); } void toggle() { state(!state().object); } protected: void bindEquation() { this->equation = ::std::bind( &type::triggerFunction, this, ::std::placeholders::_1 ); } void triggerFunction(Base &b) { if (state().object) this->template o<0>() = this->template i<1>(); else this->template o<0>() = this->template i<0>(); } }; } template<typename TType, std::SwitchBlockParameter TPar> class BlockTraits<std::SwitchBlock<TType, TPar>> { public: static constexpr const BlockType blockType = BlockType::SwitchBlock; static constexpr const bool directFeedthrough = true; using type = std::SwitchBlock<TType, TPar>; using Base = typename type::Base; static const constexpr int kIns = type::Base::kIns; static const constexpr int kOuts = type::Base::kOuts; static const constexpr int kPars = type::Base::kPars; }; } } #endif //LODESTAR_SWITCHBLOCK_HPP
30.179894
87
0.389376
helkebir
e14f78db2d2505de8d1a834e9550e18686244508
684
cc
C++
src/base/b3BaseInclude.cc
stmork/blz3
275e24681cb1493319cd0a50e691feb86182f6f0
[ "BSD-3-Clause" ]
null
null
null
src/base/b3BaseInclude.cc
stmork/blz3
275e24681cb1493319cd0a50e691feb86182f6f0
[ "BSD-3-Clause" ]
null
null
null
src/base/b3BaseInclude.cc
stmork/blz3
275e24681cb1493319cd0a50e691feb86182f6f0
[ "BSD-3-Clause" ]
1
2022-01-07T15:58:38.000Z
2022-01-07T15:58:38.000Z
/* ** ** $Filename: b3BaseInclude.cc $ ** $Release: Dortmund 2006 $ ** $Revision$ ** $Date$ ** $Author$ ** $Developer: Steffen A. Mork $ ** ** Blizzard III - Precompiled header file for base package ** ** (C) Copyright 2006 Steffen A. Mork ** All Rights Reserved ** ** ** */ /************************************************************************* ** ** ** Blizzard III includes ** ** ** *************************************************************************/ #include "b3BaseInclude.h"
26.307692
74
0.307018
stmork
e14fc29fc5053933822bf210b520d3830303d77c
8,476
hpp
C++
include/hermite_multidimensional.hpp
maliasadi/thewalrus
719cdcc4791579d3f6d45fcc8fb41372989dec85
[ "Apache-2.0" ]
null
null
null
include/hermite_multidimensional.hpp
maliasadi/thewalrus
719cdcc4791579d3f6d45fcc8fb41372989dec85
[ "Apache-2.0" ]
null
null
null
include/hermite_multidimensional.hpp
maliasadi/thewalrus
719cdcc4791579d3f6d45fcc8fb41372989dec85
[ "Apache-2.0" ]
null
null
null
// Copyright 2019 Xanadu Quantum Technologies 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. /** * @file * Contains functions for calculating the multidimensional * Hermite polynomials, used for computation of batched hafnians. */ #pragma once #include <stdafx.h> #include <assert.h> #include <algorithm> #include <cstring> typedef unsigned long long int ullint; /** * Returns the index of the one dimensional flattened vector corresponding to the multidimensional tensor * * @param pos * @param cutoff * * @return index on flattened vector */ ullint vec2index(std::vector<int> &pos, int cutoff) { int dim = pos.size(); ullint nextCoordinate = 0; nextCoordinate = pos[0]-1; for(int ii = 0; ii < dim-1; ii++) { nextCoordinate = nextCoordinate*cutoff + (pos[ii+1]-1); } return nextCoordinate; } /** * Updates the iterators needed for the calculation of the Hermite multidimensional functions * * @param nextPos a vector of integers * @param jumpFrom a vector of integers * @param jump integer specifying whether to jump to the next index * @param cutoff integer specifying the cuotff * @dim dimension of the R matrix * * @k index necessary for knowing which elements are needed from the input vector y and matrix R */ int update_iterator(std::vector<int> &nextPos, std::vector<int> &jumpFrom, int &jump, const int &cutoff, const int &dim) { if (jump > 0) { jumpFrom[jump] += 1; jump = 0; } for (int ii = 0; ii < dim; ii++) { if ( nextPos[ii] + 1 > cutoff) { nextPos[ii] = 1; jumpFrom[ii] = 1; jump = ii+1; } else { jumpFrom[ii] = nextPos[ii]; nextPos[ii] = nextPos[ii] + 1; break; } } int k=0; for(; k < dim; k++) { if(nextPos[k] != jumpFrom[k]) break; } return k; } namespace libwalrus { /** * Returns the multidimensional Hermite polynomials \f$H_k^{(R)}(y)\f$. * * This implementation is based on the MATLAB code available at * https://github.com/clementsw/gaussian-optics * * @param R a flattened vector of size \f$n^2\f$, representing a * \f$n\times n\f$ symmetric matrix. * @param y a flattened vector of size \f$n\f$. * @param cutoff highest number of photons to be resolved. * */ template <typename T> inline T* hermite_multidimensional_cpp(const std::vector<T> &R, const std::vector<T> &y, const int &cutoff) { int dim = std::sqrt(static_cast<double>(R.size())); ullint Hdim = pow(cutoff, dim); T *H; H = (T*) malloc(sizeof(T)*Hdim); memset(&H[0],0,sizeof(T)*Hdim); H[0] = 1; std::vector<int> nextPos(dim, 1); std::vector<int> jumpFrom(dim, 1); int jump = 0; int k; ullint nextCoordinate, fromCoordinate; for (ullint jj = 0; jj < Hdim-1; jj++) { k = update_iterator(nextPos, jumpFrom, jump, cutoff, dim); nextCoordinate = vec2index(nextPos, cutoff); fromCoordinate = vec2index(jumpFrom, cutoff); H[nextCoordinate] = H[fromCoordinate] * y[k]; std::vector<int> tmpjump(dim, 0); for (int ii = 0; ii < dim; ii++) { if (jumpFrom[ii] > 1) { std::vector<int> prevJump(dim, 0); prevJump[ii] = 1; std::transform(jumpFrom.begin(), jumpFrom.end(), prevJump.begin(), tmpjump.begin(), std::minus<int>()); ullint prevCoordinate = vec2index(tmpjump, cutoff); H[nextCoordinate] = H[nextCoordinate] - (static_cast<T>(jumpFrom[ii]-1))*(R[dim*k+ii])*H[prevCoordinate]; } } } return H; } /** * Returns the normalized multidimensional Hermite polynomials \f$\tilde{H}_k^{(R)}(y)\f$. * * This implementation is based on the MATLAB code available at * https://github.com/clementsw/gaussian-optics * * @param R a flattened vector of size \f$n^2\f$, representing a * \f$n\times n\f$ symmetric matrix. * @param y a flattened vector of size \f$n\f$. * @param cutoff highest number of photons to be resolved. * */ template <typename T> inline T* renorm_hermite_multidimensional_cpp(const std::vector<T> &R, const std::vector<T> &y, const int &cutoff) { int dim = std::sqrt(static_cast<double>(R.size())); ullint Hdim = pow(cutoff, dim); T *H; H = (T*) malloc(sizeof(T)*Hdim); memset(&H[0],0,sizeof(T)*Hdim); H[0] = 1; std::vector<double> intsqrt(cutoff+1, 0); for (int ii = 0; ii<=cutoff; ii++) { intsqrt[ii] = std::sqrt((static_cast<double>(ii))); } std::vector<int> nextPos(dim, 1); std::vector<int> jumpFrom(dim, 1); int jump = 0; int k; ullint nextCoordinate, fromCoordinate; for (ullint jj = 0; jj < Hdim-1; jj++) { k = update_iterator(nextPos, jumpFrom, jump, cutoff, dim); nextCoordinate = vec2index(nextPos, cutoff); fromCoordinate = vec2index(jumpFrom, cutoff); H[nextCoordinate] = H[fromCoordinate] * y[k]; std::vector<int> tmpjump(dim, 0); for (int ii = 0; ii < dim; ii++) { if (jumpFrom[ii] > 1) { std::vector<int> prevJump(dim, 0); prevJump[ii] = 1; std::transform(jumpFrom.begin(), jumpFrom.end(), prevJump.begin(), tmpjump.begin(), std::minus<int>()); ullint prevCoordinate = vec2index(tmpjump, cutoff); H[nextCoordinate] = H[nextCoordinate] - intsqrt[jumpFrom[ii]-1]*(R[k*dim+ii])*H[prevCoordinate]; } } H[nextCoordinate] = H[nextCoordinate]/intsqrt[nextPos[k]-1]; } return H; } /** * Returns the matrix elements of an interferometer parametrized in terms of its R matrix * * @param R a flattened vector of size \f$n^2\f$, representing a * \f$n\times n\f$ symmetric matrix. * @param cutoff highest number of photons to be resolved. * */ template <typename T> inline T* interferometer_cpp(const std::vector<T> &R, const int &cutoff) { int dim = std::sqrt(static_cast<double>(R.size())); assert(dim % 2 == 0); int num_modes = dim/2; ullint Hdim = pow(cutoff, dim); T *H; H = (T*) malloc(sizeof(T)*Hdim); memset(&H[0],0,sizeof(T)*Hdim); H[0] = 1; std::vector<double> intsqrt(cutoff+1, 0); for (int ii = 0; ii<=cutoff; ii++) { intsqrt[ii] = std::sqrt((static_cast<double>(ii))); } std::vector<int> nextPos(dim, 1); std::vector<int> jumpFrom(dim, 1); int jump = 0; int k; ullint nextCoordinate, fromCoordinate; for (ullint jj = 0; jj < Hdim-1; jj++) { k = update_iterator(nextPos, jumpFrom, jump, cutoff, dim); int bran = 0; for (int ii=0; ii < num_modes; ii++) { bran += nextPos[ii]; } int ketn = 0; for (int ii=num_modes; ii < dim; ii++) { ketn += nextPos[ii]; } if (bran == ketn) { nextCoordinate = vec2index(nextPos, cutoff); fromCoordinate = vec2index(jumpFrom, cutoff); std::vector<int> tmpjump(dim, 0); int low_lim; int high_lim; if (k > num_modes) { low_lim = 0; high_lim = num_modes; } else { low_lim = num_modes; high_lim = dim; } for (int ii = low_lim; ii < high_lim; ii++) { if (jumpFrom[ii] > 1) { std::vector<int> prevJump(dim, 0); prevJump[ii] = 1; std::transform(jumpFrom.begin(), jumpFrom.end(), prevJump.begin(), tmpjump.begin(), std::minus<int>()); ullint prevCoordinate = vec2index(tmpjump, cutoff); H[nextCoordinate] = H[nextCoordinate] - (intsqrt[jumpFrom[ii]-1])*(R[k*dim+ii])*H[prevCoordinate]; } } H[nextCoordinate] = H[nextCoordinate] /intsqrt[nextPos[k]-1]; } } return H; } }
31.161765
123
0.591317
maliasadi
e150fcc7c4dd87b2dcce117127aeeccf639d7f1b
242
cpp
C++
556-next-greater-element-iii/556-next-greater-element-iii.cpp
arihantthriwe/CompetitiveProgramming
0e923ea965cc1b75cb97e766e61345c8b939f41a
[ "MIT" ]
1
2022-02-25T12:22:31.000Z
2022-02-25T12:22:31.000Z
556-next-greater-element-iii/556-next-greater-element-iii.cpp
arihantthriwe/CompetitiveProgramming
0e923ea965cc1b75cb97e766e61345c8b939f41a
[ "MIT" ]
null
null
null
556-next-greater-element-iii/556-next-greater-element-iii.cpp
arihantthriwe/CompetitiveProgramming
0e923ea965cc1b75cb97e766e61345c8b939f41a
[ "MIT" ]
null
null
null
class Solution { public: int nextGreaterElement(int n) { auto digits = to_string(n); next_permutation(digits.begin(), digits.end()); auto x = stoll(digits); return (x > INT_MAX || x <= n) ? -1 : x; } };
26.888889
55
0.553719
arihantthriwe
e15153e746078c2bd6ea3c69ad4e68d0701b02e4
1,738
cpp
C++
cmdstan/stan/lib/stan_math/test/unit/math/prim/mat/fun/welford_covar_estimator_test.cpp
yizhang-cae/torsten
dc82080ca032325040844cbabe81c9a2b5e046f9
[ "BSD-3-Clause" ]
null
null
null
cmdstan/stan/lib/stan_math/test/unit/math/prim/mat/fun/welford_covar_estimator_test.cpp
yizhang-cae/torsten
dc82080ca032325040844cbabe81c9a2b5e046f9
[ "BSD-3-Clause" ]
null
null
null
cmdstan/stan/lib/stan_math/test/unit/math/prim/mat/fun/welford_covar_estimator_test.cpp
yizhang-cae/torsten
dc82080ca032325040844cbabe81c9a2b5e046f9
[ "BSD-3-Clause" ]
null
null
null
#include <stan/math/prim/mat.hpp> #include <gtest/gtest.h> TEST(ProbWelfordCovarEstimator, restart) { const int n = 10; Eigen::VectorXd q = Eigen::VectorXd::Ones(n); const int n_learn = 10; stan::math::welford_covar_estimator estimator(n); for (int i = 0; i < n_learn; ++i) estimator.add_sample(q); estimator.restart(); EXPECT_EQ(0, estimator.num_samples()); Eigen::VectorXd mean(n); estimator.sample_mean(mean); for (int i = 0; i < n; ++i) EXPECT_EQ(0, mean(i)); } TEST(ProbWelfordCovarEstimator, num_samples) { const int n = 10; Eigen::VectorXd q = Eigen::VectorXd::Ones(n); const int n_learn = 10; stan::math::welford_covar_estimator estimator(n); for (int i = 0; i < n_learn; ++i) estimator.add_sample(q); EXPECT_EQ(n_learn, estimator.num_samples()); } TEST(ProbWelfordCovarEstimator, sample_mean) { const int n = 10; const int n_learn = 10; stan::math::welford_covar_estimator estimator(n); for (int i = 0; i < n_learn; ++i) { Eigen::VectorXd q = Eigen::VectorXd::Constant(n, i); estimator.add_sample(q); } Eigen::VectorXd mean(n); estimator.sample_mean(mean); for (int i = 0; i < n; ++i) EXPECT_EQ(9.0 / 2.0, mean(i)); } TEST(ProbWelfordCovarEstimator, sample_covariance) { const int n = 10; const int n_learn = 10; stan::math::welford_covar_estimator estimator(n); for (int i = 0; i < n_learn; ++i) { Eigen::VectorXd q = Eigen::VectorXd::Constant(n, i); estimator.add_sample(q); } Eigen::MatrixXd covar(n, n); estimator.sample_covariance(covar); for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) EXPECT_EQ(55.0 / 6.0, covar(i, j)); }
20.690476
56
0.622555
yizhang-cae
e1589aef5d6807d3e1a5a53dabb71021de0e4fa1
7,708
cpp
C++
src/prod/src/Reliability/Failover/ra/Test.Unit.LocalFailoverUnitMap.cpp
AnthonyM/service-fabric
c396ea918714ea52eab9c94fd62e018cc2e09a68
[ "MIT" ]
2,542
2018-03-14T21:56:12.000Z
2019-05-06T01:18:20.000Z
src/prod/src/Reliability/Failover/ra/Test.Unit.LocalFailoverUnitMap.cpp
AnthonyM/service-fabric
c396ea918714ea52eab9c94fd62e018cc2e09a68
[ "MIT" ]
994
2019-05-07T02:39:30.000Z
2022-03-31T13:23:04.000Z
src/prod/src/Reliability/Failover/ra/Test.Unit.LocalFailoverUnitMap.cpp
AnthonyM/service-fabric
c396ea918714ea52eab9c94fd62e018cc2e09a68
[ "MIT" ]
300
2018-03-14T21:57:17.000Z
2019-05-06T20:07:00.000Z
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" using namespace Reliability; using namespace Reliability::ReconfigurationAgentComponent; using namespace ReliabilityUnitTest; using namespace Infrastructure; using namespace Common; using namespace std; class TestLocalFailoverUnitMap { protected: TestLocalFailoverUnitMap() { BOOST_REQUIRE(TestSetup()); } TEST_METHOD_SETUP(TestSetup); ~TestLocalFailoverUnitMap() { BOOST_REQUIRE(TestCleanup()); } TEST_METHOD_CLEANUP(TestCleanup); struct AddEntriesResult { LocalFailoverUnitMapEntrySPtr FMEntry; LocalFailoverUnitMapEntrySPtr OtherFTEntry; vector<EntityEntryBase*> CreateExpectation(bool fmEntry, bool otherEntry) const { vector<EntityEntryBase*> rv; if (fmEntry) { rv.push_back(FMEntry.get()); } if (otherEntry) { rv.push_back(OtherFTEntry.get()); } return rv; } }; class EntryState { public: enum Enum { NotExisting = 0, NullFT = 1, HasFTInitial = 2, HasFTUpdated = 3, Deleted = 4, }; }; class PersistenceResult { public: enum Enum { Success, Failure }; }; AddEntriesResult AddEntries(bool addFMEntry, bool addOtherEntry); void ExecuteGetAllAndVerifyResult(bool excludeFM, bool fmExpected, bool otherExpected, AddEntriesResult const & addEntryResult); void ExecuteGetFMEntriesAndVerifyResult(bool expected, AddEntriesResult const & addEntryResult); LocalFailoverUnitMapEntrySPtr GetOrCreate(bool createFlag); LocalFailoverUnitMapEntrySPtr GetOrCreate(bool createFlag, std::wstring const & ftShortName); InMemoryLocalStore & GetStore(); static FailoverUnitId GetFTId(); static FailoverUnitId GetFTId(std::wstring const & ftShortName); static wstring GetFTShortName(); UnitTestContextUPtr utContext_; }; bool TestLocalFailoverUnitMap::TestSetup() { utContext_ = UnitTestContext::Create(UnitTestContext::Option::None); return true; } bool TestLocalFailoverUnitMap::TestCleanup() { return utContext_->Cleanup(); } TestLocalFailoverUnitMap::AddEntriesResult TestLocalFailoverUnitMap::AddEntries(bool addFMEntry, bool addOtherEntry) { AddEntriesResult result; if (addFMEntry) { result.FMEntry = GetOrCreate(true, L"FM"); } if (addOtherEntry) { result.OtherFTEntry = GetOrCreate(true, L"SP1"); } return result; } template<typename T> vector<T*> ConvertVectorOfSharedPtrToVectorOfPtr(vector<std::shared_ptr<T>> const & result) { vector<T*> rv; for (auto const & it : result) { rv.push_back(it.get()); } return rv; } void TestLocalFailoverUnitMap::ExecuteGetAllAndVerifyResult(bool excludeFM, bool fmExpected, bool otherExpected, AddEntriesResult const & addEntryResult) { auto expectedEntities = addEntryResult.CreateExpectation(fmExpected, otherExpected); auto entryResultSPtr = utContext_->LFUM.GetAllFailoverUnitEntries(excludeFM); // Do this to not define write to text writer for entity entry auto entryResult = ConvertVectorOfSharedPtrToVectorOfPtr(entryResultSPtr); Verify::Vector<EntityEntryBase*>(entryResult, entryResult); } void TestLocalFailoverUnitMap::ExecuteGetFMEntriesAndVerifyResult(bool expected, AddEntriesResult const & addEntryResult) { vector<EntityEntryBase*> expectedEntities = addEntryResult.CreateExpectation(expected, false); auto result = utContext_->LFUM.GetFMFailoverUnitEntries(); auto casted = ConvertVectorOfSharedPtrToVectorOfPtr(result); Verify::Vector(casted, expectedEntities); } FailoverUnitId TestLocalFailoverUnitMap::GetFTId() { return GetFTId(GetFTShortName()); } FailoverUnitId TestLocalFailoverUnitMap::GetFTId(std::wstring const & shortName) { return StateManagement::Default::GetInstance().LookupFTContext(shortName).FUID; } wstring TestLocalFailoverUnitMap::GetFTShortName() { return L"SP1"; } LocalFailoverUnitMapEntrySPtr TestLocalFailoverUnitMap::GetOrCreate(bool createFlag) { return GetOrCreate(createFlag, GetFTShortName()); } LocalFailoverUnitMapEntrySPtr TestLocalFailoverUnitMap::GetOrCreate(bool createFlag, std::wstring const & ftShortName) { return dynamic_pointer_cast<LocalFailoverUnitMapEntry>(utContext_->LFUM.GetOrCreateEntityMapEntry(GetFTId(ftShortName), createFlag)); } BOOST_AUTO_TEST_SUITE(Unit) BOOST_FIXTURE_TEST_SUITE(TestLocalFailoverUnitMapSuite,TestLocalFailoverUnitMap) BOOST_AUTO_TEST_CASE(GetAllTest_ExcludeFMTrue_OnlyFMEntries) { auto addResult = AddEntries(true, false); ExecuteGetAllAndVerifyResult(true, false, false, addResult); } BOOST_AUTO_TEST_CASE(GetAllTest_ExcludeFMTrue_NoEntries) { auto addResult = AddEntries(false, false); ExecuteGetAllAndVerifyResult(true, false, false, addResult); } BOOST_AUTO_TEST_CASE(GetAllTest_ExcludeFMTrue_BothEntries) { auto addResult = AddEntries(true, true); ExecuteGetAllAndVerifyResult(true, false, true, addResult); } BOOST_AUTO_TEST_CASE(GetAllTest_ExcludeFMTrue_OnlyNonFMEntries) { auto addResult = AddEntries(false, true); ExecuteGetAllAndVerifyResult(true, false, true, addResult); } BOOST_AUTO_TEST_CASE(GetAllTest_ExcludeFMFalse_OnlyFMEntries) { auto addResult = AddEntries(true, false); ExecuteGetAllAndVerifyResult(false, true, false, addResult); } BOOST_AUTO_TEST_CASE(GetAllTest_ExcludeFMFalse_NoEntries) { auto addResult = AddEntries(false, false); ExecuteGetAllAndVerifyResult(false, false, false, addResult); } BOOST_AUTO_TEST_CASE(GetAllTest_ExcludeFMFalse_BothEntries) { auto addResult = AddEntries(true, true); ExecuteGetAllAndVerifyResult(false, true, true, addResult); } BOOST_AUTO_TEST_CASE(GetAllTest_ExcludeFMFalse_OnlyNonFMEntries) { auto addResult = AddEntries(false, true); ExecuteGetAllAndVerifyResult(false, false, true, addResult); } BOOST_AUTO_TEST_CASE(GetFMEntries_OnlyFM) { auto addResult = AddEntries(true, false); ExecuteGetFMEntriesAndVerifyResult(true, addResult); } BOOST_AUTO_TEST_CASE(GetFMEntries_Both) { auto addResult = AddEntries(true, true); ExecuteGetFMEntriesAndVerifyResult(true, addResult); } BOOST_AUTO_TEST_CASE(GetFMEntries_None) { auto addResult = AddEntries(false, false); ExecuteGetFMEntriesAndVerifyResult(false, addResult); } BOOST_AUTO_TEST_CASE(GetFMEntries_OnlyOtherEntries) { auto addResult = AddEntries(false, true); ExecuteGetFMEntriesAndVerifyResult(false, addResult); } BOOST_AUTO_TEST_CASE(GetByOwner_Fmm) { auto addResult = AddEntries(true, true); auto entries = utContext_->LFUM.GetFailoverUnitEntries(*FailoverManagerId::Fmm); auto casted = ConvertVectorOfSharedPtrToVectorOfPtr(entries); auto expected = addResult.CreateExpectation(true, false); Verify::Vector(expected, casted); } BOOST_AUTO_TEST_CASE(GetByOwner_Fm) { auto addResult = AddEntries(true, true); auto entries = utContext_->LFUM.GetFailoverUnitEntries(*FailoverManagerId::Fm); auto casted = ConvertVectorOfSharedPtrToVectorOfPtr(entries); auto expected = addResult.CreateExpectation(false, true); Verify::Vector(expected, casted); } BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE_END()
26.763889
153
0.730929
AnthonyM
e15aae3934814b00d9afe2a4b4786b82c12d7eac
620
cpp
C++
Archivos/Estado_archivo.cpp
memo0p2/Programas-cpp
f78f283886e478be12b3636992dbf922199ae5f1
[ "MIT" ]
null
null
null
Archivos/Estado_archivo.cpp
memo0p2/Programas-cpp
f78f283886e478be12b3636992dbf922199ae5f1
[ "MIT" ]
null
null
null
Archivos/Estado_archivo.cpp
memo0p2/Programas-cpp
f78f283886e478be12b3636992dbf922199ae5f1
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> using namespace std; int main(){ /***** ESTADO DEl ARCHIVO *****/ /** bad() -> Cuando no tenemos permiso. Cuando no hay espacio. Cuando no existe el archivo fail() -> Error de formato (tratas de leer int y solo encuentras un char). eof() -> Fin de archivo End Of File good() -> **/ ifstream entrada; char linea[80]; entrada.open("archivo.txt"); if(entrada.good()){ cout<<"Archivo en buen estado"<<endl; } else{ cout<<"Archivo en mal estado"<<endl; } return 0; }
25.833333
96
0.55
memo0p2
e15bba1dfdedc6d7b7780a2031950d8e5876bfc8
4,000
cpp
C++
src/picotorrent/ui/dialogs/addmagnetlinkdialog.cpp
theRealBaccata/picotorrent
5baad13e44d15cc5e79da9e947b0e91781cd9e76
[ "MIT" ]
2,015
2015-07-05T23:00:19.000Z
2022-03-30T12:42:27.000Z
src/picotorrent/ui/dialogs/addmagnetlinkdialog.cpp
ryahpalma/picotorrent
68526dcbb9a84fe8155185b0cf4fd43f4cc196a2
[ "MIT" ]
740
2015-08-14T22:03:55.000Z
2022-03-24T22:06:55.000Z
src/picotorrent/ui/dialogs/addmagnetlinkdialog.cpp
ryahpalma/picotorrent
68526dcbb9a84fe8155185b0cf4fd43f4cc196a2
[ "MIT" ]
282
2015-07-02T21:47:13.000Z
2022-03-11T15:43:26.000Z
#include "addmagnetlinkdialog.hpp" #include <regex> #include <boost/log/trivial.hpp> #include <libtorrent/magnet_uri.hpp> #include <wx/clipbrd.h> #include <wx/tokenzr.h> #include "../translator.hpp" namespace lt = libtorrent; using pt::UI::Dialogs::AddMagnetLinkDialog; AddMagnetLinkDialog::AddMagnetLinkDialog(wxWindow* parent, wxWindowID id) : wxDialog(parent, id, i18n("add_magnet_link_s"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER), m_links(new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxHSCROLL | wxTE_MULTILINE)) { auto buttonsSizer = new wxBoxSizer(wxHORIZONTAL); wxButton* ok = new wxButton(this, wxID_OK); ok->SetDefault(); buttonsSizer->Add(ok); buttonsSizer->Add(new wxButton(this, wxID_CANCEL, i18n("cancel")), 0, wxLEFT, FromDIP(7)); auto mainSizer = new wxBoxSizer(wxVERTICAL); mainSizer->AddSpacer(FromDIP(11)); mainSizer->Add(new wxStaticText(this, wxID_ANY, i18n("add_magnet_link_s_description")), 0, wxLEFT | wxRIGHT, FromDIP(11)); mainSizer->AddSpacer(FromDIP(5)); mainSizer->Add(m_links, 1, wxLEFT | wxRIGHT | wxEXPAND, FromDIP(11)); mainSizer->AddSpacer(FromDIP(7)); mainSizer->Add(buttonsSizer, 0, wxLEFT | wxRIGHT | wxBOTTOM | wxALIGN_RIGHT, FromDIP(11)); this->SetSizerAndFit(mainSizer); this->SetSize(FromDIP(wxSize(400, 250))); m_links->SetFocus(); m_links->SetFont( wxFont(9, wxFONTFAMILY_TELETYPE, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, false, wxT("Consolas"))); if (auto clipboard = wxClipboard::Get()) { if (clipboard->Open()) { wxTextDataObject data; if (clipboard->GetData(data)) { wxString d = data.GetText(); if (IsMagnetLinkOrInfoHash(d)) { if (!d.EndsWith("\n")) { d = d + "\n"; } m_links->SetValue(d); m_links->SetInsertionPointEnd(); } } clipboard->Close(); } } } AddMagnetLinkDialog::~AddMagnetLinkDialog() { } std::vector<libtorrent::add_torrent_params> AddMagnetLinkDialog::GetParams() { std::vector<lt::add_torrent_params> result; wxStringTokenizer tokenizer(m_links->GetValue()); while (tokenizer.HasMoreTokens()) { std::string token = tokenizer.GetNextToken(); if (!IsMagnetLinkOrInfoHash(token)) { continue; } switch (token.size()) { case 40: if (token.substr(0, 20) != "magnet:?xt=urn:btih:") { BOOST_LOG_TRIVIAL(info) << "Prepending magnet URI to v1 info hash: " << token; token = "magnet:?xt=urn:btih:" + token; } break; case 68: if (token.substr(0, 20) != "magnet:?xt=urn:btmh:") { BOOST_LOG_TRIVIAL(info) << "Prepending magnet URI to v2 info hash: " << token; token = "magnet:?xt=urn:btmh:" + token; } break; } lt::error_code ec; lt::add_torrent_params params = lt::parse_magnet_uri(token, ec); if (ec) { BOOST_LOG_TRIVIAL(warning) << "Failed to parse magnet uri: " << token << ", error: " << ec; continue; } result.push_back(params); } return result; } bool AddMagnetLinkDialog::IsMagnetLinkOrInfoHash(wxString const& str) { std::regex infoHashV1("[a-fA-F\\d]{40}", std::regex_constants::icase); std::regex infoHashV2("[a-fA-F\\d]{68}", std::regex_constants::icase); if (std::regex_match(str.ToStdString(), infoHashV1) || std::regex_match(str.ToStdString(), infoHashV2)) { return true; } if (str.StartsWith("magnet:?xt=urn:btih:") || str.StartsWith("magnet:?xt=urn:btmh:")) { return true; } return false; }
29.62963
130
0.59275
theRealBaccata
e15d5b35691e8502febb5bfa388ae2b36c8a3cc0
557
cpp
C++
src/sources/AWLdict.cpp
Amuwa/TeXpen
d0d7ae74463f88980beb8ceb2958182ac2df021e
[ "MIT" ]
5
2019-03-04T08:47:52.000Z
2022-01-28T12:53:55.000Z
src/sources/AWLdict.cpp
Amuwa/TeXpen
d0d7ae74463f88980beb8ceb2958182ac2df021e
[ "MIT" ]
3
2019-02-22T05:41:49.000Z
2020-03-16T13:37:23.000Z
src/sources/AWLdict.cpp
Amuwa/TeXpen
d0d7ae74463f88980beb8ceb2958182ac2df021e
[ "MIT" ]
7
2019-02-22T06:04:13.000Z
2022-01-28T12:54:15.000Z
#include "headers/mainwindow.h" #include "headers/qtexedit.h" #include <QString> #include <QFile> QStringList AWL; void setupAWL(){ if(AWL.isEmpty()){ QFile file (":/AWL/awl.txt"); file.open(QIODevice::ReadOnly); QString word = QString::fromUtf8(file.readLine()); while((!word.isEmpty())&& word !=" "){ if(word.contains("\n")){ word.replace("\n",""); } AWL.append(word); word = QString::fromUtf8(file.readLine()); } file.close(); } }
23.208333
58
0.526032
Amuwa
ff150290b708a3924ca3f60eebacf1d51cf58974
2,742
cpp
C++
Source/Engine/ImageBasedLightingTechnique.cpp
glowing-chemist/Bell
0cf4d0ac925940869077779700c1d3bd45ff841f
[ "MIT" ]
14
2020-02-12T19:13:46.000Z
2022-03-05T02:26:06.000Z
Source/Engine/ImageBasedLightingTechnique.cpp
glowing-chemist/Bell
0cf4d0ac925940869077779700c1d3bd45ff841f
[ "MIT" ]
5
2020-08-06T07:19:47.000Z
2021-01-05T21:20:51.000Z
Source/Engine/ImageBasedLightingTechnique.cpp
glowing-chemist/Bell
0cf4d0ac925940869077779700c1d3bd45ff841f
[ "MIT" ]
2
2021-09-18T13:36:47.000Z
2021-12-04T15:08:53.000Z
#include "Engine/ImageBasedLightingTechnique.hpp" #include "Engine/Engine.hpp" #include "Engine/DefaultResourceSlots.hpp" #include "Core/Executor.hpp" #include "Core/Profiling.hpp" DeferredImageBasedLightingTechnique::DeferredImageBasedLightingTechnique(RenderEngine* eng, RenderGraph& graph) : Technique("GlobalIBL", eng->getDevice()), mPipelineDesc{Rect{getDevice()->getSwapChain()->getSwapChainImageWidth(), getDevice()->getSwapChain()->getSwapChainImageHeight()}, Rect{getDevice()->getSwapChain()->getSwapChainImageWidth(), getDevice()->getSwapChain()->getSwapChainImageHeight()} }, mIBLVertexShader(eng->getShader("./Shaders/FullScreenTriangle.vert")), mIBLFragmentShader(eng->getShader("./Shaders/DeferredDFGIBL.frag")) { GraphicsTask task{ "GlobalIBL", mPipelineDesc }; task.addInput(kCameraBuffer, AttachmentType::UniformBuffer); task.addInput(kDFGLUT, AttachmentType::Texture2D); task.addInput(kGBufferDepth, AttachmentType::Texture2D); task.addInput(kGBufferNormals, AttachmentType::Texture2D); task.addInput(kGBufferDiffuse, AttachmentType::Texture2D); task.addInput(kGBufferSpecularRoughness, AttachmentType::Texture2D); task.addInput(kGBufferEmissiveOcclusion, AttachmentType::Texture2D); task.addInput(kConvolvedSpecularSkyBox, AttachmentType::CubeMap); task.addInput(kConvolvedDiffuseSkyBox, AttachmentType::CubeMap); task.addInput(kDefaultSampler, AttachmentType::Sampler); if (eng->isPassRegistered(PassType::Shadow) || eng->isPassRegistered(PassType::CascadingShadow) || eng->isPassRegistered(PassType::RayTracedShadows)) task.addInput(kShadowMap, AttachmentType::Texture2D); if(eng->isPassRegistered(PassType::SSR) || eng->isPassRegistered(PassType::RayTracedReflections)) task.addInput(kReflectionMap, AttachmentType::Texture2D); task.addManagedOutput(kGlobalLighting, AttachmentType::RenderTarget2D, Format::RGBA16Float, SizeClass::Swapchain, LoadOp::Clear_Black, StoreOp::Store, ImageUsage::ColourAttachment | ImageUsage::Sampled | ImageUsage::TransferSrc); task.setRecordCommandsCallback( [this](const RenderGraph& graph, const uint32_t taskIndex, Executor* exec, RenderEngine*, const std::vector<const MeshInstance*>&) { PROFILER_EVENT("Defered IBL"); PROFILER_GPU_TASK(exec); PROFILER_GPU_EVENT("Defered IBL"); const RenderTask& task = graph.getTask(taskIndex); exec->setGraphicsShaders(static_cast<const GraphicsTask&>(task), graph, mIBLVertexShader, nullptr, nullptr, nullptr, mIBLFragmentShader); exec->draw(0, 3); } ); mTaskID = graph.addTask(task); }
50.777778
153
0.736689
glowing-chemist
ff1bc95a9befd8c02e3b5f8bb5a65ccfeeb4cca6
5,636
cpp
C++
src/plugins/azoth/importmanager.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
120
2015-01-22T14:10:39.000Z
2021-11-25T12:57:16.000Z
src/plugins/azoth/importmanager.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
8
2015-02-07T19:38:19.000Z
2017-11-30T20:18:28.000Z
src/plugins/azoth/importmanager.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
33
2015-02-07T16:59:55.000Z
2021-10-12T00:36:40.000Z
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2006-2014 Georg Rudoy * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt) **********************************************************************/ #include "importmanager.h" #include <util/sll/qtutil.h> #include <interfaces/core/icoreproxy.h> #include <interfaces/core/ipluginsmanager.h> #include "interfaces/azoth/iaccount.h" #include "interfaces/azoth/isupportimport.h" #include "interfaces/azoth/ihistoryplugin.h" #include "core.h" #include "accounthandlerchooserdialog.h" namespace LC { namespace Azoth { ImportManager::ImportManager (QObject *parent) : QObject (parent) { } void ImportManager::HandleAccountImport (Entity e) { const auto& map = e.Additional_ ["AccountData"].toMap (); const auto& protoId = map ["Protocol"].toString (); if (protoId.isEmpty ()) { qWarning () << Q_FUNC_INFO << "empty protocol id" << map; return; } for (const auto proto : Core::Instance ().GetProtocols ()) { const auto isi = qobject_cast<ISupportImport*> (proto->GetQObject ()); if (!isi || isi->GetImportProtocolID () != protoId) continue; isi->ImportAccount (map); break; } } namespace { IMessage::Direction GetDirection (const QByteArray& dirStr) { if (dirStr == "out") return IMessage::Direction::Out; else if (dirStr == "in") return IMessage::Direction::In; qWarning () << Q_FUNC_INFO << "unknown direction" << dirStr; return IMessage::Direction::In; } IMessage::Type GetMessageType (const QByteArray& typeStr) { if (typeStr == "chat") return IMessage::Type::ChatMessage; else if (typeStr == "muc") return IMessage::Type::MUCMessage; else if (typeStr == "event") return IMessage::Type::EventMessage; qWarning () << Q_FUNC_INFO << "unknown type" << typeStr; return IMessage::Type::ChatMessage; } IMessage::EscapePolicy GetEscapePolicy (const QByteArray& polStr) { if (polStr.isEmpty ()) return IMessage::EscapePolicy::Escape; else if (polStr == "escape") return IMessage::EscapePolicy::Escape; else if (polStr == "noEscape") return IMessage::EscapePolicy::NoEscape; qWarning () << Q_FUNC_INFO << "unknown escape policy" << polStr; return IMessage::EscapePolicy::Escape; } } void ImportManager::HandleHistoryImport (Entity e) { qDebug () << Q_FUNC_INFO; const auto& histories = Core::Instance ().GetProxy ()-> GetPluginsManager ()->GetAllCastableTo<IHistoryPlugin*> (); if (histories.isEmpty ()) { qWarning () << Q_FUNC_INFO << "no history plugin is present, aborting"; return; } const auto acc = GetAccountID (e); if (!acc) return; const auto isi = qobject_cast<ISupportImport*> (acc->GetParentProtocol ()); QHash<QString, QString> entryIDcache; QVariantList history; for (const auto& qe : EntityQueues_.take (e.Additional_ ["AccountID"].toString ())) history.append (qe.Additional_ ["History"].toList ()); qDebug () << history.size (); struct EntryInfo { QString VisibleName_; QList<HistoryItem> Items_; }; QHash<QString, QHash<QString, EntryInfo>> items; for (const auto& lineVar : history) { const auto& histMap = lineVar.toMap (); const auto& origId = histMap ["EntryID"].toString (); QString entryId; if (entryIDcache.contains (origId)) entryId = entryIDcache [origId]; else { const auto& realId = isi->GetEntryID (origId, acc->GetQObject ()); entryIDcache [origId] = realId; entryId = realId; } auto visibleName = histMap ["VisibleName"].toString (); if (visibleName.isEmpty ()) visibleName = origId; const auto& accId = acc->GetAccountID (); const HistoryItem item { histMap ["DateTime"].toDateTime (), GetDirection (histMap ["Direction"].toByteArray ()), histMap ["Body"].toString (), histMap ["OtherVariant"].toString (), GetMessageType (histMap ["Type"].toByteArray ()), histMap ["RichBody"].toString (), GetEscapePolicy (histMap ["EscapePolicy"].toByteArray ()) }; auto& info = items [accId] [entryId]; info.VisibleName_ = visibleName; info.Items_ << item; } for (const auto& accPair : Util::Stlize (items)) for (const auto& entryPair : Util::Stlize (accPair.second)) { const auto& info = entryPair.second; for (const auto plugin : histories) plugin->AddRawMessages (accPair.first, entryPair.first, info.VisibleName_, info.Items_); } } IAccount* ImportManager::GetAccountID (Entity e) { const auto& accName = e.Additional_ ["AccountName"].toString (); const auto& accs = Core::Instance ().GetAccounts ([] (IProtocol *proto) { return qobject_cast<ISupportImport*> (proto->GetQObject ()); }); const auto pos = std::find_if (accs.begin (), accs.end (), [&accName] (IAccount *acc) { return acc->GetAccountName () == accName; }); if (pos != accs.end ()) return *pos; const auto& impId = e.Additional_ ["AccountID"].toString (); EntityQueues_ [impId] << e; if (EntityQueues_ [impId].size () > 1) return nullptr; if (AccID2OurID_.contains (impId)) return AccID2OurID_ [impId]; AccountHandlerChooserDialog dia (accs, tr ("Select account to import history from %1 into:").arg (accName)); if (dia.exec () != QDialog::Accepted) return 0; const auto acc = dia.GetSelectedAccount (); AccID2OurID_ [impId] = acc; return acc; } } }
27.227053
85
0.648155
Maledictus
ff1fc5df7f4b9f9b140ff2e8a484776cb0e3a6bc
5,382
cpp
C++
examples/lapack-like/SkewHermitianEig.cpp
ahmadia/Elemental-1
f9a82c76a06728e9e04a4316e41803efbadb5a19
[ "BSD-3-Clause" ]
null
null
null
examples/lapack-like/SkewHermitianEig.cpp
ahmadia/Elemental-1
f9a82c76a06728e9e04a4316e41803efbadb5a19
[ "BSD-3-Clause" ]
null
null
null
examples/lapack-like/SkewHermitianEig.cpp
ahmadia/Elemental-1
f9a82c76a06728e9e04a4316e41803efbadb5a19
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2009-2013, Jack Poulson All rights reserved. This file is part of Elemental and is under the BSD 2-Clause License, which can be found in the LICENSE file in the root directory, or at http://opensource.org/licenses/BSD-2-Clause */ // NOTE: It is possible to simply include "elemental.hpp" instead #include "elemental-lite.hpp" #include "elemental/blas-like/level1/DiagonalScale.hpp" #include "elemental/blas-like/level1/Scale.hpp" #include "elemental/blas-like/level3/Gemm.hpp" #include "elemental/blas-like/level3/Herk.hpp" #include "elemental/lapack-like/SkewHermitianEig.hpp" #include "elemental/lapack-like/Norm/Frobenius.hpp" #include "elemental/lapack-like/HermitianEig/Sort.hpp" #include "elemental/matrices/Identity.hpp" using namespace std; using namespace elem; // Typedef our real and complex types to 'R' and 'C' for convenience typedef double R; typedef Complex<R> C; int main( int argc, char* argv[] ) { // This detects whether or not you have already initialized MPI and // does so if necessary. The full routine is elem::Initialize. Initialize( argc, argv ); // Extract our MPI rank mpi::Comm comm = mpi::COMM_WORLD; const int commRank = mpi::CommRank( comm ); // Surround the Elemental calls with try/catch statements in order to // safely handle any exceptions that were thrown during execution. try { const int n = Input("--size","size of matrix",100); const bool print = Input("--print","print matrices?",false); ProcessInput(); PrintInputReport(); // Create a 2d process grid from a communicator. In our case, it is // MPI_COMM_WORLD. There is another constructor that allows you to // specify the grid dimensions, Grid g( comm, r, c ), which creates an // r x c grid. Grid g( comm ); // Create an n x n complex distributed matrix, // We distribute the matrix using grid 'g'. // // There are quite a few available constructors, including ones that // allow you to pass in your own local buffer and to specify the // distribution alignments (i.e., which process row and column owns the // top-left element) DistMatrix<C> S( n, n, g ); // Fill the matrix since we did not pass in a buffer. // // We will fill entry (i,j) with the complex value (i-j,i+j) so that // the global matrix is skew-Hermitian. However, only one triangle of // the matrix actually needs to be filled, the symmetry can be implicit. // const int colShift = S.ColShift(); // first row we own const int rowShift = S.RowShift(); // first col we own const int colStride = S.ColStride(); const int rowStride = S.RowStride(); const int localHeight = S.LocalHeight(); const int localWidth = S.LocalWidth(); for( int jLocal=0; jLocal<localWidth; ++jLocal ) { for( int iLocal=0; iLocal<localHeight; ++iLocal ) { // Our process owns the rows colShift:colStride:n, // and the columns rowShift:rowStride:n const int i = colShift + iLocal*colStride; const int j = rowShift + jLocal*rowStride; S.SetLocal( iLocal, jLocal, C(i-j,i+j) ); } } // Make a backup of S before we overwrite it within the eigensolver DistMatrix<C> SCopy( S ); // Call the eigensolver. We first create an empty complex eigenvector // matrix, X[MC,MR], and an eigenvalue column vector, w[VR,* ] // // Optional: set blocksizes and algorithmic choices here. See the // 'Tuning' section of the README for details. DistMatrix<R,VR,STAR> wImag( g ); DistMatrix<C> X( g ); SkewHermitianEig( LOWER, S, wImag, X ); // only use lower half of S // Optional: sort the eigenpairs hermitian_eig::Sort( wImag, X ); if( print ) { SCopy.Print("S"); X.Print("X"); wImag.Print("wImag"); } // Check the residual, || S X - Omega X ||_F const R frobS = HermitianFrobeniusNorm( LOWER, SCopy ); DistMatrix<C> E( X ); Scale( C(0,1), E ); DiagonalScale( RIGHT, NORMAL, wImag, E ); Gemm( NORMAL, NORMAL, C(-1), SCopy, X, C(1), E ); const R frobResid = FrobeniusNorm( E ); // Check the orthogonality of X Identity( E, n, n ); Herk( LOWER, NORMAL, C(-1), X, C(1), E ); const R frobOrthog = HermitianFrobeniusNorm( LOWER, E ); if( g.Rank() == 0 ) { std::cout << "|| H ||_F = " << frobS << "\n" << "|| H X - X Omega ||_F / || A ||_F = " << frobResid / frobS << "\n" << "|| X X^H - I ||_F = " << frobOrthog / frobS << "\n" << std::endl; } } catch( ArgException& e ) { // There is nothing to do } catch( exception& e ) { ostringstream os; os << "Process " << commRank << " caught exception with message: " << e.what() << endl; cerr << os.str(); #ifndef RELEASE DumpCallStack(); #endif } Finalize(); return 0; }
36.612245
80
0.580639
ahmadia
ff20f8da8e0bb40b1dd071d3e8f550fd4dd2335d
18,857
cpp
C++
src/orm/query/grammars/grammar.cpp
MrAhmedSayedAli/TinyORM
f185e76cfa955475df9b807c3e7ecaa4c20989c0
[ "MIT" ]
4
2021-07-07T01:21:34.000Z
2022-02-01T01:38:24.000Z
src/orm/query/grammars/grammar.cpp
MrAhmedSayedAli/TinyORM
f185e76cfa955475df9b807c3e7ecaa4c20989c0
[ "MIT" ]
2
2022-03-04T10:57:15.000Z
2022-03-26T17:10:28.000Z
src/orm/query/grammars/grammar.cpp
MrAhmedSayedAli/TinyORM
f185e76cfa955475df9b807c3e7ecaa4c20989c0
[ "MIT" ]
2
2021-08-10T01:31:31.000Z
2022-03-04T10:37:42.000Z
#include "orm/query/grammars/grammar.hpp" #include "orm/databaseconnection.hpp" #include "orm/macros/likely.hpp" #include "orm/query/joinclause.hpp" TINYORM_BEGIN_COMMON_NAMESPACE namespace Orm::Query::Grammars { QString Grammar::compileSelect(QueryBuilder &query) const { /* If the query does not have any columns set, we'll set the columns to the * character to just get all of the columns from the database. Then we can build the query and concatenate all the pieces together as one. */ const auto original = query.getColumns(); if (original.isEmpty()) query.setColumns({ASTERISK}); /* To compile the query, we'll spin through each component of the query and see if that component exists. If it does we'll just call the compiler function for the component which is responsible for making the SQL. */ auto sql = concatenate(compileComponents(query)); // Restore original columns value query.setColumns(original); return sql; } QString Grammar::compileInsert(const QueryBuilder &query, const QVector<QVariantMap> &values) const { const auto table = wrapTable(query.getFrom()); // FEATURE insert with empty values, this code will never be triggered, because check in the QueryBuilder::insert, even all other code works correctly and support empty values silverqx if (values.isEmpty()) return QStringLiteral("insert into %1 default values").arg(table); return QStringLiteral("insert into %1 (%2) values %3").arg( table, // Columns are obtained only from a first QMap columnize(values.at(0).keys()), compileInsertToVector(values).join(COMMA)); } QString Grammar::compileInsertOrIgnore(const QueryBuilder &/*unused*/, const QVector<QVariantMap> &/*unused*/) const { throw Exceptions::RuntimeError( "This database engine does not support inserting while ignoring " "errors."); } QString Grammar::compileUpdate(QueryBuilder &query, const QVector<UpdateItem> &values) const { const auto table = wrapTable(query.getFrom()); const auto columns = compileUpdateColumns(values); const auto wheres = compileWheres(query); return query.getJoins().isEmpty() ? compileUpdateWithoutJoins(query, table, columns, wheres) : compileUpdateWithJoins(query, table, columns, wheres); } QVector<QVariant> Grammar::prepareBindingsForUpdate(const BindingsMap &bindings, const QVector<UpdateItem> &values) const { QVector<QVariant> preparedBindings(bindings.find(BindingType::JOIN).value()); // Merge update values bindings std::transform(values.cbegin(), values.cend(), std::back_inserter(preparedBindings), [](const auto &updateItem) { return updateItem.value; }); /* Flatten bindings map and exclude select and join bindings and than merge all remaining bindings from flatten bindings map. */ const auto flatten = flatBindingsForUpdateDelete(bindings, {BindingType::SELECT, BindingType::JOIN}); // std::copy() is ok, 'flatten' contains vector of references std::copy(flatten.cbegin(), flatten.cend(), std::back_inserter(preparedBindings)); return preparedBindings; } QString Grammar::compileDelete(QueryBuilder &query) const { const auto table = wrapTable(query.getFrom()); const auto wheres = compileWheres(query); return query.getJoins().isEmpty() ? compileDeleteWithoutJoins(query, table, wheres) : compileDeleteWithJoins(query, table, wheres); } QVector<QVariant> Grammar::prepareBindingsForDelete(const BindingsMap &bindings) const { QVector<QVariant> preparedBindings; /* Flatten bindings map and exclude select bindings and than merge all remaining bindings from flatten bindings map. */ const auto flatten = flatBindingsForUpdateDelete(bindings, {BindingType::SELECT}); // std::copy() is ok, 'flatten' contains vector of references std::copy(flatten.cbegin(), flatten.cend(), std::back_inserter(preparedBindings)); return preparedBindings; } std::unordered_map<QString, QVector<QVariant>> Grammar::compileTruncate(const QueryBuilder &query) const { return {{QStringLiteral("truncate table %1").arg(wrapTable(query.getFrom())), {}}}; } const QVector<QString> &Grammar::getOperators() const { /* I make it this way, I don't declare it as pure virtual intentionally, this gives me oportunity to instantiate the Grammar class eg. in tests. */ static const QVector<QString> cachedOperators; return cachedOperators; } bool Grammar::shouldCompileAggregate(const std::optional<AggregateItem> &aggregate) const { return aggregate.has_value() && !aggregate->function.isEmpty(); } bool Grammar::shouldCompileColumns(const QueryBuilder &query) const { /* If the query is actually performing an aggregating select, we will let compileAggregate() to handle the building of the select clauses, as it will need some more syntax that is best handled by that function to keep things neat. */ return !query.getAggregate() && !query.getColumns().isEmpty(); } bool Grammar::shouldCompileFrom(const FromClause &from) const { return !std::holds_alternative<std::monostate>(from) || (std::holds_alternative<QString>(from) && !std::get<QString>(from).isEmpty()); } QStringList Grammar::compileComponents(const QueryBuilder &query) const { QStringList sql; const auto &compileMap = getCompileMap(); for (const auto &component : compileMap) if (component.isset) if (component.isset(query)) sql.append(std::invoke(component.compileMethod, query)); return sql; } QString Grammar::compileAggregate(const QueryBuilder &query) const { const auto &aggregate = query.getAggregate(); const auto &distinct = query.getDistinct(); auto column = columnize(aggregate->columns); /* If the query has a "distinct" constraint and we're not asking for all columns we need to prepend "distinct" onto the column name so that the query takes it into account when it performs the aggregating operations on the data. */ if (std::holds_alternative<bool>(distinct) && query.getDistinct<bool>() && column != ASTERISK ) T_LIKELY column = QStringLiteral("distinct %1").arg(column); else if (std::holds_alternative<QStringList>(distinct)) T_UNLIKELY column = QStringLiteral("distinct %1") .arg(columnize(std::get<QStringList>(distinct))); return QStringLiteral("select %1(%2) as %3").arg(aggregate->function, column, wrap(QStringLiteral("aggregate"))); } QString Grammar::compileColumns(const QueryBuilder &query) const { QString select; const auto &distinct = query.getDistinct(); if (!std::holds_alternative<bool>(distinct)) throw Exceptions::RuntimeError( QStringLiteral("Connection '%1' doesn't support defining more distinct " "columns.") .arg(query.getConnection().getName())); if (std::get<bool>(distinct)) select = QStringLiteral("select distinct %1"); else select = QStringLiteral("select %1"); return select.arg(columnize(query.getColumns())); } QString Grammar::compileFrom(const QueryBuilder &query) const { return QStringLiteral("from %1").arg(wrapTable(query.getFrom())); } QString Grammar::compileWheres(const QueryBuilder &query) const { const auto sql = compileWheresToVector(query); if (!sql.isEmpty()) return concatenateWhereClauses(query, sql); return {}; } QStringList Grammar::compileWheresToVector(const QueryBuilder &query) const { const auto &wheres = query.getWheres(); QStringList compiledWheres; compiledWheres.reserve(wheres.size()); for (const auto &where : wheres) compiledWheres << QStringLiteral("%1 %2") .arg(where.condition, std::invoke(getWhereMethod(where.type), where)); return compiledWheres; } QString Grammar::concatenateWhereClauses(const QueryBuilder &query, const QStringList &sql) const { // Is it a query instance of the JoinClause? const auto conjunction = dynamic_cast<const JoinClause *>(&query) == nullptr ? QStringLiteral("where") : QStringLiteral("on"); return QStringLiteral("%1 %2").arg(conjunction, removeLeadingBoolean(sql.join(SPACE))); } QString Grammar::compileJoins(const QueryBuilder &query) const { const auto &joins = query.getJoins(); QStringList sql; sql.reserve(joins.size()); for (const auto &join : joins) sql << QStringLiteral("%1 join %2 %3").arg(join->getType(), wrapTable(join->getTable()), compileWheres(*join)); return sql.join(SPACE); } QString Grammar::compileGroups(const QueryBuilder &query) const { return QStringLiteral("group by %1").arg(columnize(query.getGroups())); } QString Grammar::compileHavings(const QueryBuilder &query) const { const auto &havings = query.getHavings(); QStringList compiledHavings; compiledHavings.reserve(havings.size()); for (const auto &having : havings) compiledHavings << compileHaving(having); return QStringLiteral("having %1").arg( removeLeadingBoolean(compiledHavings.join(SPACE))); } QString Grammar::compileHaving(const HavingConditionItem &having) const { /* If the having clause is "raw", we can just return the clause straight away without doing any more processing on it. Otherwise, we will compile the clause into SQL based on the components that make it up from builder. */ switch (having.type) { T_LIKELY case HavingType::BASIC: return compileBasicHaving(having); T_UNLIKELY case HavingType::RAW: return QStringLiteral("%1 %2").arg(having.condition, having.sql); T_UNLIKELY default: throw Exceptions::RuntimeError(QStringLiteral("Unknown HavingType (%1).") .arg(static_cast<int>(having.type))); } } QString Grammar::compileBasicHaving(const HavingConditionItem &having) const { return QStringLiteral("%1 %2 %3 %4").arg(having.condition, wrap(having.column), having.comparison, parameter(having.value)); } QString Grammar::compileOrders(const QueryBuilder &query) const { if (query.getOrders().isEmpty()) return QLatin1String(""); return QStringLiteral("order by %1").arg(compileOrdersToVector(query).join(COMMA)); } QStringList Grammar::compileOrdersToVector(const QueryBuilder &query) const { const auto &orders = query.getOrders(); QStringList compiledOrders; compiledOrders.reserve(orders.size()); for (const auto &order : orders) if (order.sql.isEmpty()) T_LIKELY compiledOrders << QStringLiteral("%1 %2") .arg(wrap(order.column), order.direction.toLower()); else T_UNLIKELY compiledOrders << order.sql; return compiledOrders; } QString Grammar::compileLimit(const QueryBuilder &query) const { return QStringLiteral("limit %1").arg(query.getLimit()); } QString Grammar::compileOffset(const QueryBuilder &query) const { return QStringLiteral("offset %1").arg(query.getOffset()); } QString Grammar::compileLock(const QueryBuilder &query) const { const auto &lock = query.getLock(); if (std::holds_alternative<QString>(lock)) return std::get<QString>(lock); return QLatin1String(""); } QString Grammar::whereBasic(const WhereConditionItem &where) const { // FEATURE postgres, try operators with ? vs pdo str_replace(?, ??) https://wiki.php.net/rfc/pdo_escape_placeholders silverqx return QStringLiteral("%1 %2 %3").arg(wrap(where.column), where.comparison, parameter(where.value)); } QString Grammar::whereNested(const WhereConditionItem &where) const { /* Here we will calculate what portion of the string we need to remove. If this is a join clause query, we need to remove the "on" portion of the SQL and if it is a normal query we need to take the leading "where" of queries. */ auto compiled = compileWheres(*where.nestedQuery); const auto offset = compiled.indexOf(SPACE) + 1; return PARENTH_ONE.arg(compiled.remove(0, offset)); } QString Grammar::whereColumn(const WhereConditionItem &where) const { /* In this where type where.column contains first column and where,value contains second column. */ return QStringLiteral("%1 %2 %3").arg(wrap(where.column), where.comparison, wrap(where.columnTwo)); } QString Grammar::whereIn(const WhereConditionItem &where) const { if (where.values.isEmpty()) return QStringLiteral("0 = 1"); return QStringLiteral("%1 in (%2)").arg(wrap(where.column), parametrize(where.values)); } QString Grammar::whereNotIn(const WhereConditionItem &where) const { if (where.values.isEmpty()) return QStringLiteral("1 = 1"); return QStringLiteral("%1 not in (%2)").arg(wrap(where.column), parametrize(where.values)); } QString Grammar::whereNull(const WhereConditionItem &where) const { return QStringLiteral("%1 is null").arg(wrap(where.column)); } QString Grammar::whereNotNull(const WhereConditionItem &where) const { return QStringLiteral("%1 is not null").arg(wrap(where.column)); } QString Grammar::whereRaw(const WhereConditionItem &where) const { return where.sql; } QString Grammar::whereExists(const WhereConditionItem &where) const { return QStringLiteral("exists (%1)").arg(compileSelect(*where.nestedQuery)); } QString Grammar::whereNotExists(const WhereConditionItem &where) const { return QStringLiteral("not exists (%1)").arg(compileSelect(*where.nestedQuery)); } QStringList Grammar::compileInsertToVector(const QVector<QVariantMap> &values) const { /* We need to build a list of parameter place-holders of values that are bound to the query. Each insert should have the exact same amount of parameter bindings so we will loop through the record and parameterize them all. */ QStringList compiledParameters; compiledParameters.reserve(values.size()); for (const auto &valuesMap : values) compiledParameters << PARENTH_ONE.arg(parametrize(valuesMap)); return compiledParameters; } QString Grammar::compileUpdateColumns(const QVector<UpdateItem> &values) const { QStringList compiledAssignments; compiledAssignments.reserve(values.size()); for (const auto &assignment : values) compiledAssignments << QStringLiteral("%1 = %2").arg( wrap(assignment.column), parameter(assignment.value)); return compiledAssignments.join(COMMA); } QString Grammar::compileUpdateWithoutJoins(const QueryBuilder &/*unused*/, const QString &table, const QString &columns, const QString &wheres) const { // The table argument is already wrapped return QStringLiteral("update %1 set %2 %3").arg(table, columns, wheres); } QString Grammar::compileUpdateWithJoins(const QueryBuilder &query, const QString &table, const QString &columns, const QString &wheres) const { const auto joins = compileJoins(query); // The table argument is already wrapped return QStringLiteral("update %1 %2 set %3 %4").arg(table, joins, columns, wheres); } QString Grammar::compileDeleteWithoutJoins(const QueryBuilder &/*unused*/, const QString &table, const QString &wheres) const { // The table argument is already wrapped return QStringLiteral("delete from %1 %2").arg(table, wheres); } QString Grammar::compileDeleteWithJoins(const QueryBuilder &query, const QString &table, const QString &wheres) const { const auto alias = getAliasFromFrom(table); const auto joins = compileJoins(query); /* Alias has to be after the delete keyword and aliased table definition after the from keyword. */ return QStringLiteral("delete %1 from %2 %3 %4").arg(alias, table, joins, wheres); } QString Grammar::concatenate(const QStringList &segments) const { QString result; for (const auto &segment : segments) { if (segment.isEmpty()) continue; result += QStringLiteral("%1 ").arg(segment); } return result.trimmed(); } QString Grammar::removeLeadingBoolean(QString statement) const { // Skip all whitespaces after and/or, to avoid trimmed() for performance reasons const auto firstChar = [&statement](const auto from) { for (auto i = from; i < statement.size(); ++i) if (statement.at(i) != SPACE) return i; // Return initial value if space has not been found, should never happen :/ return from; }; // RegExp not used for performance reasons /* Before and/or could not be whitespace, current implementation doesn't include whitespaces before. */ if (statement.startsWith(QLatin1String("and "))) return statement.mid(firstChar(4)); if (statement.startsWith(QLatin1String("or "))) return statement.mid(firstChar(3)); return statement; } QVector<std::reference_wrapper<const QVariant>> Grammar::flatBindingsForUpdateDelete(const BindingsMap &bindings, const QVector<BindingType> &exclude) const { QVector<std::reference_wrapper<const QVariant>> cleanBindingsFlatten; for (auto itBindingVector = bindings.constBegin(); itBindingVector != bindings.constEnd(); ++itBindingVector) if (exclude.contains(itBindingVector.key())) continue; else for (const auto &binding : itBindingVector.value()) cleanBindingsFlatten.append(std::cref(binding)); return cleanBindingsFlatten; } } // namespace Orm::Query::Grammars TINYORM_END_COMMON_NAMESPACE
34.099458
188
0.659808
MrAhmedSayedAli
ff2124babab6b9c1c6734feb66c531de585a0f08
3,082
cpp
C++
src/vsg/vk/Sampler.cpp
XenonofArcticus/VulkanSceneGraphPrototype
2118ff8deb1078625bd09d4435757fdf346dffb7
[ "MIT" ]
null
null
null
src/vsg/vk/Sampler.cpp
XenonofArcticus/VulkanSceneGraphPrototype
2118ff8deb1078625bd09d4435757fdf346dffb7
[ "MIT" ]
null
null
null
src/vsg/vk/Sampler.cpp
XenonofArcticus/VulkanSceneGraphPrototype
2118ff8deb1078625bd09d4435757fdf346dffb7
[ "MIT" ]
null
null
null
/* <editor-fold desc="MIT License"> Copyright(c) 2018 Robert Osfield 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. </editor-fold> */ #include <vsg/vk/Sampler.h> using namespace vsg; Sampler::Sampler(VkSampler sampler, Device* device, AllocationCallbacks* allocator) : _sampler(sampler), _device(device), _allocator(allocator) { } Sampler::~Sampler() { if (_sampler) { vkDestroySampler(*_device, _sampler, _allocator); } } Sampler::Result Sampler::create(Device* device, const VkSamplerCreateInfo& createSamplerInfo, AllocationCallbacks* allocator) { if (!device) { return Result("Error: vsg::Sampler::create(...) failed to create vkSampler, undefined Device.", VK_ERROR_INVALID_EXTERNAL_HANDLE); } VkSampler sampler; VkResult result = vkCreateSampler(*device, &createSamplerInfo, allocator, &sampler); if (result == VK_SUCCESS) { return Result(new Sampler(sampler, device, allocator)); } else { return Result("Error: Failed to create vkSampler.", result); } } Sampler::Result Sampler::create(Device* device, AllocationCallbacks* allocator) { VkSamplerCreateInfo samplerInfo = {}; samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; samplerInfo.minFilter = VK_FILTER_LINEAR; samplerInfo.magFilter = VK_FILTER_LINEAR; samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT; samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT; samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT; #if 1 // requres Logical device to have deviceFeatures.samplerAnisotropy = VK_TRUE; set when creating the vsg::Deivce samplerInfo.anisotropyEnable = VK_TRUE; samplerInfo.maxAnisotropy = 16; #else samplerInfo.anisotropyEnable = VK_FALSE; samplerInfo.maxAnisotropy = 1; #endif samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK; samplerInfo.unnormalizedCoordinates = VK_FALSE; samplerInfo.compareEnable = VK_FALSE; samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; return create(device, samplerInfo, allocator); }
41.093333
460
0.758923
XenonofArcticus
ff25a359fb700b9ce74f7c40d051283646c5d0ef
16,430
hpp
C++
include/eve/module/proba/regular/impl/normal_distribution.hpp
the-moisrex/eve
80b52663eefee11460abb0aedf4158a5067cf7dc
[ "MIT" ]
340
2020-09-16T21:12:48.000Z
2022-03-28T15:40:33.000Z
include/eve/module/proba/regular/impl/normal_distribution.hpp
the-moisrex/eve
80b52663eefee11460abb0aedf4158a5067cf7dc
[ "MIT" ]
383
2020-09-17T06:56:35.000Z
2022-03-13T15:58:53.000Z
include/eve/module/proba/regular/impl/normal_distribution.hpp
the-moisrex/eve
80b52663eefee11460abb0aedf4158a5067cf7dc
[ "MIT" ]
28
2021-02-27T23:11:23.000Z
2022-03-25T12:31:29.000Z
//================================================================================================== /* EVE - Expressive Vector Engine Copyright : EVE Contributors & Maintainers SPDX-License-Identifier: MIT */ //================================================================================================== #pragma once #include <eve/concept/value.hpp> #include <eve/constant/half.hpp> #include <eve/constant/mhalf.hpp> #include <eve/constant/one.hpp> #include <eve/constant/sqrt_2.hpp> #include <eve/constant/sqrt_2o_2.hpp> #include <eve/constant/zero.hpp> #include <eve/detail/apply_over.hpp> #include <eve/detail/kumi.hpp> #include <eve/detail/implementation.hpp> #include <eve/detail/skeleton_calls.hpp> #include <eve/function/abs.hpp> #include <eve/function/all.hpp> #include <eve/function/cospi.hpp> #include <eve/function/erfc.hpp> #include <eve/function/erfc_inv.hpp> #include <eve/function/exp.hpp> #include <eve/function/fma.hpp> #include <eve/function/is_finite.hpp> #include <eve/function/is_gtz.hpp> #include <eve/function/log.hpp> #include <eve/function/log1p.hpp> #include <eve/function/raw.hpp> #include <eve/function/rec.hpp> #include <eve/function/sqr.hpp> #include <eve/function/sqrt.hpp> #include <eve/module/real/core/detail/generic/horn.hpp> #include <eve/module/proba/detail/attributes.hpp> #include <eve/module/proba/detail/urg01.hpp> #include <eve/platform.hpp> #include <concepts> #include <type_traits> namespace eve { namespace detail { template < typename G, typename R> EVE_FORCEINLINE auto box_muller(G & gen, as<R> const & ) noexcept { auto x1 = detail::urg01(gen, as<R>()); auto x2 = detail::urg01(gen, as<R>()); auto rho = eve::sqrt(-2*eve::log1p(-x1)); return rho*half_circle(cospi)(2*x2); } } template < typename T, typename U, typename Internal = T> struct normal_distribution{}; template < floating_real_value T, floating_real_value U> requires compatible_values<T, U> struct normal_distribution<T, U> { using is_distribution_t = void; using m_type = T; using s_type = U; using value_type = common_compatible_t<T, U>; using parameters = struct { value_type m; value_type s; }; normal_distribution(T m_, U s_) : m(m_), s(s_) { EVE_ASSERT(all(is_gtz(s) && is_finite(s)), "s must be strictly positive and finite"); EVE_ASSERT(all(is_finite(m)), "m must be finite"); } normal_distribution(parameters const & p) : m(p.m), s(p.s) { EVE_ASSERT(all(is_gtz(s) && is_finite(s)), "s must be strictly positive and finite"); EVE_ASSERT(all(is_finite(m)), "m must be finite"); } template < typename G, typename R = value_type> auto operator()(G & gen, as<R> const & ) requires scalar_value<value_type> { return fma(m, detail::box_muller(gen, as<R>()), s); } parameters params() const noexcept { return { .m = m, .s = s }; } m_type m; s_type s; }; template < floating_real_value U> struct normal_distribution<callable_zero_, U> { using is_distribution_t = void; using m_type = callable_zero_; using s_type = U; using value_type = U; using parameters = struct { callable_zero_ m; value_type s;}; normal_distribution(callable_zero_ const&, U s_) : s(s_) { EVE_ASSERT(all(is_gtz(s) && is_finite(s)), "s must be strictly positive and finite"); } normal_distribution(parameters const & p) : s(p.s) { EVE_ASSERT(all(is_gtz(s) && is_finite(s)), "s must be strictly positive and finite"); } template < typename G, typename R = value_type> auto operator()(G & gen, as<R> const & ) requires scalar_value<value_type> { return detail::box_muller(gen, as<R>())*s; } parameters params() noexcept { return { .m = zero, .s = s }; } s_type s; }; template < floating_real_value T> struct normal_distribution<T, callable_one_> { using is_distribution_t = void; using m_type = T; using s_type = decltype(eve::one); using value_type = T; using parameters = struct { value_type m; callable_one_ s;}; normal_distribution(T m_, callable_one_ const &) : m(m_) { EVE_ASSERT(all(is_finite(m)), "m must be finite"); } normal_distribution(parameters const & p) : m(p.m) { EVE_ASSERT(all(is_finite(m)), "m must be finite"); } template < typename G, typename R = value_type> auto operator()(G & gen, as<R> const & ) requires scalar_value<value_type> { return detail::box_muller(gen, as<R>())+m; } parameters params() noexcept { return { .m = m, .s = one }; } m_type m; }; template<typename T, typename U> normal_distribution(T,U) -> normal_distribution<T,U>; template < floating_real_value T> struct normal_distribution<callable_zero_, callable_one_, T> { using is_distribution_t = void; using m_type = callable_zero_; using s_type = callable_one_; using value_type = T; using parameters = struct { callable_zero_ m; callable_one_ s;}; normal_distribution(parameters const & ) { } template < typename G, typename R = value_type> auto operator()(G & gen, as<R> const & ) requires scalar_value<value_type> { return detail::box_muller(gen, as<R>()); } parameters params() noexcept { return { .m = zero, .s = one }; } constexpr normal_distribution( as<T> const&) {} }; template<typename T> normal_distribution(as<T> const&) -> normal_distribution<callable_zero_, callable_one_, T>; template<floating_real_value T> inline constexpr auto normal_distribution_01 = normal_distribution<callable_zero_, callable_one_, T>(as<T>{}); namespace detail { ////////////////////////////////////////////////////// /// cdf template<typename T, typename U, floating_value V , typename I = T> EVE_FORCEINLINE auto cdf_(EVE_SUPPORTS(cpu_) , normal_distribution<T, U, I> const & d , V const &x ) noexcept { if constexpr(floating_value<T> && floating_value<U>) return half(as(x))*erfc(sqrt_2o_2(as(x))*((d.m-x)/d.s)); else if constexpr(std::same_as<T, callable_zero_> && floating_value<U>) return half(as(x))*erfc(sqrt_2o_2(as(x))*(-x/d.s)); else if constexpr(std::same_as<U, callable_one_> && floating_value<T>) return half(as(x))*erfc(sqrt_2o_2(as(x))*((d.m-x))); else return half(as(x))*erfc(sqrt_2o_2(as(x))*(-x)); } template<typename T, typename U, floating_value V , typename I = T> EVE_FORCEINLINE auto cdf_(EVE_SUPPORTS(cpu_) , raw_type const & , normal_distribution<T, U, I> const &d , V const &x ) noexcept { using elt_t = element_type_t<T>; if constexpr(std::same_as<elt_t, float>) { auto eval = [](auto l) { auto al = eve::abs(l); auto k = rec(fma(T(0.2316419f),al,one(as(l)))); auto w = horn<T , 0x3ea385fa // 0.31938153f , 0xbeb68f87 // -0.356563782f, , 0x3fe40778 // 1.781477937f, , 0xbfe91eea // -1.821255978f, , 0x3faa466f // 1.330274429f, >(k); auto invsqrt_2pi = T(0.39894228040143267793994605993438186847585863116493); w*=k*invsqrt_2pi*eve::exp(-sqr(l)*half(as(l))); return if_else(is_gtz(l),oneminus(w),w); }; if constexpr(floating_value<T> && floating_value<U>) return eval((x-d.m)/d.s); else if constexpr(std::same_as<T, callable_zero_> && floating_value<U>) return eval(x/d.s); else if constexpr(std::same_as<U, callable_one_> && floating_value<T>) return eval(x-d.m); else return eval(x); } else return cdf(d, x); } ////////////////////////////////////////////////////// /// pdf template<typename T, typename U, floating_value V , typename I = T> EVE_FORCEINLINE auto pdf_(EVE_SUPPORTS(cpu_) , normal_distribution<T, U, I> const & d , V const &x ) noexcept { auto invsqrt_2pi = V(0.39894228040143267793994605993438186847585863116493); if constexpr(floating_value<T> && floating_value<U>) { auto invsig = rec(d.s); return eve::exp(mhalf(as(x))*sqr((x-d.m)*invsig))*invsqrt_2pi*invsig; } else if constexpr(std::same_as<T, callable_zero_> && floating_value<U>) { auto invsig = rec(d.s); return eve::exp(mhalf(as(x))*sqr(x*invsig))*invsqrt_2pi*invsig; } else if constexpr(std::same_as<U, callable_one_> && floating_value<T>) { return eve::exp(mhalf(as(x))*sqr((x-d.m)))*invsqrt_2pi; } else return eve::exp(mhalf(as(x))*sqr(x))*invsqrt_2pi; } ////////////////////////////////////////////////////// /// mgf template<typename T, typename U, floating_value V , typename I = T> EVE_FORCEINLINE auto mgf_(EVE_SUPPORTS(cpu_) , normal_distribution<T, U, I> const & d , V const &x ) noexcept { auto invsqrt_2pi = V(0.39894228040143267793994605993438186847585863116493); if constexpr(floating_value<T> && floating_value<U>) { return eve::exp(d.m*x+sqr(d.s*x)*half(as(x))); } else if constexpr(std::same_as<T, callable_zero_> && floating_value<U>) { return eve::exp(sqr(d.s*x)*half(as(x))); } else if constexpr(std::same_as<U, callable_one_> && floating_value<T>) { return eve::exp(d.m*x+sqr(x)*half(as(x))); } else return eve::exp(sqr(d)*half(as(x))); } ////////////////////////////////////////////////////// /// invcdf template<typename T, typename U, floating_value V , typename I = T> EVE_FORCEINLINE auto invcdf_(EVE_SUPPORTS(cpu_) , normal_distribution<T, U, I> const & d , V const &x ) noexcept { if constexpr(floating_value<T> && floating_value<U>) { return fma(-sqrt_2(as(x))*erfc_inv( T(2)*x), d.s, d.m); } else if constexpr(std::same_as<T, callable_zero_> && floating_value<U>) { return -sqrt_2(as(x))*erfc_inv(2*x)*d.s; } else if constexpr(std::same_as<U, callable_one_> && floating_value<T>) { return -sqrt_2(as(x))*erfc_inv(2*x)+d.m; } else return -sqrt_2(as(x))*erfc_inv(2*x); } ////////////////////////////////////////////////////// /// median template<typename T, typename U, typename I = T> EVE_FORCEINLINE auto median_(EVE_SUPPORTS(cpu_) , normal_distribution<T,U,I> const & d) noexcept { if constexpr (floating_value<T>) return d.m; else if constexpr (floating_value<U>) return zero(as<U>()); else return zero(as<I>()); } ////////////////////////////////////////////////////// /// mean template<typename T, typename U, typename I = T> EVE_FORCEINLINE auto mean_(EVE_SUPPORTS(cpu_) , normal_distribution<T,U,I> const &d) noexcept { return median(d); } ////////////////////////////////////////////////////// /// mode template<typename T, typename U, typename I = T> EVE_FORCEINLINE auto mode_(EVE_SUPPORTS(cpu_) , normal_distribution<T,U,I> const & d) noexcept { return median(d); } ////////////////////////////////////////////////////// /// entropy template<typename T, typename U, typename I = T> EVE_FORCEINLINE auto entropy_(EVE_SUPPORTS(cpu_) , normal_distribution<T,U,I> const & d) noexcept { auto twopie = T(17.0794684453471341309271017390931489900697770715304); if constexpr (floating_value<U>) return half(as<T>())*log(twopie*sqr(d.s)); else return half(as<T>())*log(twopie); } ////////////////////////////////////////////////////// /// skewness template<typename T, typename U, typename I = T> EVE_FORCEINLINE auto skewness_(EVE_SUPPORTS(cpu_) , normal_distribution<T,U,I> const & ) noexcept { return I(0); } ////////////////////////////////////////////////////// /// kurtosis template<typename T, typename U, typename I = T> EVE_FORCEINLINE auto kurtosis_(EVE_SUPPORTS(cpu_) , normal_distribution<T,U,I> const & ) noexcept { return I(0); } ////////////////////////////////////////////////////// /// mad template<typename T, typename U, typename I = T> EVE_FORCEINLINE auto mad_(EVE_SUPPORTS(cpu_) , normal_distribution<T,U,I> const & d) noexcept { auto sqrt_2o_pi = T(0.79788456080286535587989211986876373695171726232986); if constexpr (floating_value<U>) return d.s*sqrt_2o_pi; else return sqrt_2o_pi; } ////////////////////////////////////////////////////// /// var template<typename T, typename U, typename I = T> EVE_FORCEINLINE auto var_(EVE_SUPPORTS(cpu_) , normal_distribution<T,U,I> const & d) noexcept { if constexpr (floating_value<U>) return sqr(d.s); else return one(as<I>()); } ////////////////////////////////////////////////////// /// stdev template<typename T, typename U, typename I = T> EVE_FORCEINLINE auto stdev_(EVE_SUPPORTS(cpu_) , normal_distribution<T,U,I> const & d) noexcept { if constexpr (floating_value<U>) return d.s; else return one(as<I>()); } ////////////////////////////////////////////////////// /// kullback template<typename T, typename U, typename I = T> EVE_FORCEINLINE auto kullback_(EVE_SUPPORTS(cpu_) , normal_distribution<T,U,I> const & d1 , normal_distribution<T,U,I> const & d2 ) noexcept { if constexpr (floating_value<T> && floating_value<U>) { auto srap = d1.s/d2.s; return half(as<T>())*(dec(sqr(srap)+sqr((d1.m-d2.m)/d2.s))+T(2)*eve::log(srap)); } else if constexpr(std::same_as<T, callable_zero_> && floating_value<U>) { auto srap = d1.s/d2.s; return half(as<T>())*(dec(sqr(srap))+T(2)*eve::log(srap)); } else if constexpr(std::same_as<U, callable_one_> && floating_value<T>) { return half(as<T>())*dec(oneminus(sqr((d1.m-d2.m)/d2.s))); } else return zero(as<I>()); } ////////////////////////////////////////////////////// /// confidence template<typename T, typename U, floating_real_value R , floating_real_value V, floating_real_value A, typename I = T> EVE_FORCEINLINE auto confidence_(EVE_SUPPORTS(cpu_) , normal_distribution<T,U,I> const & d , R const & x , std::array<V, 4> const & cov , A const & alpha ) noexcept { using v_t = typename normal_distribution<T,U,I>::value_type; R z = x; auto normz = -invcdf(normal_distribution_01<I>, alpha*v_t(0.5)); auto halfwidth = normz; if constexpr(floating_real_value<T> && floating_real_value<U>) z = (z-d.m)/d.s; else if constexpr(floating_real_value<T>) z -= d.m; else if constexpr(floating_real_value<U>) z /= d.s; auto zvar = fma(fma(cov[3], z, 2*cov[1]), z, cov[0]); halfwidth *= eve::sqrt(zvar); if constexpr(floating_real_value<U>) halfwidth /= d.s; auto d01 = normal_distribution_01<I>; return kumi::make_tuple(cdf(d01, z), cdf(d01, z-halfwidth), cdf(d01, z+halfwidth)); } } }
33.125
115
0.545344
the-moisrex
ff302bbf2a850a3ce0dbf52c2459a4f000214bec
34,114
cpp
C++
Sources/Internationalizator.cpp
Petititi/imGraph
068890ffe2f8fa1fb51bc95b8d9296cc79737fac
[ "BSD-3-Clause" ]
2
2015-01-12T11:27:45.000Z
2015-03-25T18:24:38.000Z
Sources/Internationalizator.cpp
Petititi/imGraph
068890ffe2f8fa1fb51bc95b8d9296cc79737fac
[ "BSD-3-Clause" ]
30
2015-01-07T11:59:07.000Z
2015-04-24T13:02:01.000Z
Sources/Internationalizator.cpp
Petititi/imGraph
068890ffe2f8fa1fb51bc95b8d9296cc79737fac
[ "BSD-3-Clause" ]
1
2018-12-20T12:18:18.000Z
2018-12-20T12:18:18.000Z
#include "Internationalizator.h" #ifdef _WIN32 #pragma warning(disable:4503) #pragma warning(push) #pragma warning(disable:4996 4251 4275 4800) #endif #include <boost/thread/recursive_mutex.hpp> #include <boost/thread/lock_guard.hpp> #ifdef _WIN32 #pragma warning(pop) #endif using namespace std; using boost::recursive_mutex; using boost::lock_guard; namespace charliesoft { recursive_mutex _internationalizatorMutex; Internationalizator *Internationalizator::ptr = NULL; boost::format my_format(const std::string & f_string) { using namespace boost::io; boost::format fmter(f_string); fmter.exceptions(no_error_bits);//no exceptions wanted! return fmter; } Internationalizator::Internationalizator() { initTranslations(); } Internationalizator* Internationalizator::getInstance() { lock_guard<recursive_mutex> guard(_internationalizatorMutex); if (ptr == NULL) ptr = new Internationalizator(); return ptr; }; void Internationalizator::releaseInstance() { lock_guard<recursive_mutex> guard(_internationalizatorMutex); if (ptr != NULL) delete ptr; ptr = NULL; }; void Internationalizator::setLang(std::string resourceFile) { ///\todo }; std::string Internationalizator::getTranslation(std::string key){ if (translations.find(key) != translations.end()) return translations[key]; else return key; }; std::string _STR(std::string key) { return Internationalizator::getInstance()->getTranslation(key).c_str(); }; QString _QT(std::string key) { QString output = Internationalizator::getInstance()->getTranslation(key).c_str(); return output; }; void Internationalizator::initTranslations() { translations["TRUE"] = "True"; translations["FALSE"] = "False"; translations["ALL_TYPES"] = "All types"; translations["BUTTON_OK"] = "OK"; translations["BUTTON_CANCEL"] = "Cancel"; translations["BUTTON_DELETE"] = "Delete"; translations["BUTTON_BROWSE"] = "Browse..."; translations["BUTTON_UPDATE"] = "Update"; translations["BUTTON_COLOR"] = "Color editor"; translations["BUTTON_MATRIX"] = "Matrix editor"; translations["BUTTON_ADD_INPUT"] = "Add input..."; translations["BUTTON_ADD_OUTPUT"] = "Add output..."; translations["BUTTON_SWITCH_SYNC"] = "Change block rendering type<br/>(currently synchrone)"; translations["BUTTON_SWITCH_ASYNC"] = "Change block rendering type<br/>(currently asyncrone)"; translations["BUTTON_SWITCH_ONESHOT"] = "Change block rendering type<br/>(currently one shot)"; translations["TYPE_DATAS_BOOL"] = "Boolean"; translations["TYPE_DATAS_INT"] = "Int"; translations["TYPE_DATAS_FLOAT"] = "Float"; translations["TYPE_DATAS_COLOR"] = "Color"; translations["TYPE_DATAS_MATRIX"] = "Matrix"; translations["TYPE_DATAS_STRING"] = "String"; translations["TYPE_DATAS_FILE"] = "FilePath"; translations["TYPE_DATAS_LISTBOX"] = "ListBox"; translations["TYPE_DATAS_ERROR"] = "typeError"; translations["CONDITION_EDITOR"] = "Condition editor..."; translations["CONDITION_EDITOR_HELP"] = "You can define here which conditions are needed for block rendering!"; translations["CONDITION_BLOCK_ERROR_INPUT"] = "Condition can't be input of block..."; translations["CONDITION_BLOCK_LEFT"] = "left"; translations["CONDITION_BLOCK_HELP"] = "link to the output's block<br/>whose value will be used in condition"; translations["CONDITION_BLOCK_RIGHT"] = "right"; translations["CONDITION_CARDINAL"] = "#rendering"; translations["CONDITION_IS_EMPTY"] = "is empty"; translations["NOT_INITIALIZED"] = "Not initialized..."; translations["PROCESSING_TIME"] = "Mean processing time: "; translations["BLOCK_OUTPUT"] = "output"; translations["BLOCK_INPUT"] = "input"; translations["BLOCK_TITLE_INPUT"] = "Input"; translations["BLOCK_TITLE_IMG_PROCESS"] = "2D processing"; translations["BLOCK_TITLE_SIGNAL"] = "Video processing"; translations["BLOCK_TITLE_MATH"] = "Math op."; translations["BLOCK_TITLE_OUTPUT"] = "Output"; translations["BLOCK_TITLE_INFOS"] = "Infos"; translations["BLOCK_INFOS"] = "<h1>Statistics</h1>" "<table><tr><td>Mean processing time:</td><td>%1$s ms</td></tr>" "<tr><td>Max processing time:</td><td>%2$s ms</td></tr>" "<tr><td>Min processing time:</td><td>%3$s ms</td></tr>" "<tr><td>Nb rendering:</td><td>%4$s</td></tr></table>" "<h1>Errors</h1>" "<p>%5$s</p>"; translations["ERROR_GENERIC"] = "Error undefined!"; translations["ERROR_GENERIC_TITLE"] = "Error!"; translations["ERROR_CONFIRM_SET_VALUE"] = "Wrong input, are you sure you want to set this value?"; translations["ERROR_TYPE"] = "The type of \"%1$s.%2$s\" (%3$s) doesn't correspond to \"%4$s.%5$s\" (%6$s)"; translations["ERROR_LINK_WRONG_INPUT_OUTPUT"] = "You can't link %1$s to %2$s : same type (%3$s)!"; translations["ERROR_LINK_SAME_BLOCK"] = "You can't link the same block!"; translations["ERROR_PARAM_EXCLUSIF"] = "Params \"%1$s\" and \"%2$s\" are mutually exclusive..."; translations["ERROR_PARAM_NEEDED"] = "Param \"%1$s\" is required..."; translations["ERROR_PARAM_ONLY_POSITIF"] = "Param \"%1$s\":<br/>only positive value are authorized!"; translations["ERROR_PARAM_ONLY_POSITIF_STRICT"] = "Param \"%1$s\":<br/>only strict positive value are authorized!"; translations["ERROR_PARAM_ONLY_NEGATIF"] = "Param \"%1$s\":<br/>only negative value are authorized!"; translations["ERROR_PARAM_ONLY_NEGATIF_STRICT"] = "Param \"%1$s\":<br/>only strict negative value are authorized!"; translations["ERROR_PARAM__valueBETWEEN"] = "Param \"%1$s\" (%2$f):<br/>should be between %3$f and %4$f"; translations["ERROR_PARAM_FOUND"] = "Error! Could not find property of \"%1$s\""; translations["MENU_FILE"] = "File"; translations["MENU_FILE_OPEN"] = "Open"; translations["MENU_FILE_OPEN_TIP"] = "Open a previous project"; translations["MENU_FILE_CREATE"] = "New"; translations["MENU_FILE_CREATE_TIP"] = "Create a new project"; translations["MENU_FILE_SAVE"] = "Save"; translations["MENU_FILE_SAVE_TIP"] = "Save current project"; translations["MENU_FILE_SAVEAS"] = "Save as..."; translations["MENU_FILE_SAVEAS_TIP"] = "Choose file where to save current project"; translations["MENU_FILE_QUIT"] = "Quit"; translations["MENU_FILE_QUIT_TIP"] = "Quit application"; translations["MENU_EDIT"] = "Edit"; translations["MENU_EDIT_SUBGRAPH"] = "Create subprocess"; translations["MENU_EDIT_SUBGRAPH_TIP"] = "Create a subprocess using every selected widgets"; translations["CREATE_PARAM_TITLE"] = "Parameter creation"; translations["CREATE_PARAM_TYPE"] = "Type of the parameter: "; translations["CREATE_PARAM_NAME"] = "Short name of the parameter: "; translations["CREATE_PARAM_NAME_HELP"] = "Short description of the parameter: "; translations["CREATE_PARAM_INIT_VAL"] = "Initial value of the parameter: "; translations["MATRIX_EDITOR_TOOLS"] = "Tools"; translations["MATRIX_EDITOR_BLOCKS"] = "Blocks"; translations["MATRIX_EDITOR_DATA_CHOICES"] = "Matrix data type:"; translations["MATRIX_EDITOR_DATA_SIZE"] = "Size (rows, cols, channels):"; translations["MATRIX_EDITOR_DATA_INITIAL_VAL"] = "Initial values:"; translations["MATRIX_EDITOR_DATA_INITIAL_VAL_0"] = "zeros"; translations["MATRIX_EDITOR_DATA_INITIAL_VAL_1"] = "constant"; translations["MATRIX_EDITOR_DATA_INITIAL_VAL_2"] = "eye"; translations["MATRIX_EDITOR_DATA_INITIAL_VAL_3"] = "ellipse"; translations["MATRIX_EDITOR_DATA_INITIAL_VAL_4"] = "rect"; translations["MATRIX_EDITOR_DATA_INITIAL_VAL_5"] = "cross"; translations["MATRIX_EDITOR_DATA_INITIAL_VAL_6"] = "random"; translations["MATRIX_EDITOR_SECTION_PEN_COLOR"] = "Color:"; translations["MATRIX_EDITOR_SECTION_PEN_SIZE"] = "Pencil size:"; translations["MATRIX_EDITOR_HELP_LEFT"] = "Panning left (CTRL+arrowLEFT)"; translations["MATRIX_EDITOR_HELP_RIGHT"] = "Panning right (CTRL+arrowRIGHT)"; translations["MATRIX_EDITOR_HELP_UP"] = "Panning up (CTRL+arrowUP)"; translations["MATRIX_EDITOR_HELP_DOWN"] = "Panning down (CTRL+arrowDOWN)"; translations["MATRIX_EDITOR_HELP_ZOOM_X1"] = "Zoom x1 (CTRL+P)"; translations["MATRIX_EDITOR_HELP_ZOOM_IN"] = "Zoom in (CTRL++)"; translations["MATRIX_EDITOR_HELP_ZOOM_OUT"] = "Zoom out (CTRL+-)"; translations["MATRIX_EDITOR_HELP_SAVE"] = "Save current matrix (CTRL+S)"; translations["MATRIX_EDITOR_HELP_LOAD"] = "Load new matrix (CTRL+O)"; translations["MATRIX_EDITOR_HELP_EDIT"] = "Edit matrix (CTRL+E)"; translations["MATRIX_EDITOR_HELP_ONTOP"] = "Always on top (CTRL+T)"; translations["MATRIX_EDITOR_HELP_START"] = "Run graph (Enter)"; translations["MATRIX_EDITOR_HELP_STOP"] = "Stop graph (End)"; translations["MATRIX_EDITOR_HELP_PAUSE"] = "Pause graph (Space)"; translations["MENU_HELP_INFO"] = "Info"; translations["MENU_HELP_HELP"] = "Help"; translations["CONF_FILE_TYPE"] = "imGraph project (*.igp)"; translations["PROJ_LOAD_FILE"] = "Open project file"; translations["PROJ_CREATE_FILE"] = "Create project file"; translations["DOCK_TITLE"] = "Toolbox"; translations["DOCK_PROPERTY_TITLE"] = "Properties"; translations["SUBBLOCK__"] = "Sub graph"; translations["FOR_BLOCK_"] = "for"; translations["FOR_BLOCK_INITVAL"] = "start"; translations["FOR_BLOCK_INITVAL_HELP"] = "Initial value of counter"; translations["FOR_BLOCK_ENDVAL"] = "end"; translations["FOR_BLOCK_ENDVAL_HELP"] = "Final value of counter"; translations["FOR_BLOCK_STEPVAL"] = "step"; translations["FOR_BLOCK_STEPVAL_HELP"] = "Step value of counter"; translations["BLOCK__INPUT_NAME"] = "File Loader"; translations["BLOCK__INPUT_IN_INPUT_TYPE"] = "input"; translations["BLOCK__INPUT_IN_INPUT_TYPE_HELP"] = "Input type|Webcam^Video file^Folder"; translations["BLOCK__INPUT_IN_FILE_HELP"] = "File to load."; translations["BLOCK__INPUT_IN_FILE_FILTER"] = "media files"; translations["BLOCK__INPUT_IN_FILE_NOT_FOUND"] = "File \"%1$s\" not found!"; translations["BLOCK__INPUT_IN_FILE_NOT_FOLDER"] = "File \"%1$s\" is not a folder!"; translations["BLOCK__INPUT_IN_FILE_PROBLEM"] = "File \"%1$s\" can't be loaded!"; translations["BLOCK__INPUT_IN_LOOP"] = "loop"; translations["BLOCK__INPUT_IN_LOOP_HELP"] = "Loop video file (if <=0, infinite loop)"; translations["BLOCK__INPUT_IN_GREY"] = "grey"; translations["BLOCK__INPUT_IN_GREY_HELP"] = "Convert image to a grayscale one"; translations["BLOCK__INPUT_IN_COLOR"] = "color"; translations["BLOCK__INPUT_IN_COLOR_HELP"] = "Convert image to a color one"; translations["BLOCK__INPUT_OUT_IMAGE"] = "image"; translations["BLOCK__INPUT_OUT_IMAGE_HELP"] = "Output image"; translations["BLOCK__INPUT_OUT_FRAMERATE"] = "framerate"; translations["BLOCK__INPUT_OUT_FRAMERATE_HELP"] = "Number of frames per second"; translations["BLOCK__INPUT_INOUT_WIDTH"] = "width"; translations["BLOCK__INPUT_INOUT_WIDTH_HELP"] = "Wanted width of images (in pixels)"; translations["BLOCK__INPUT_INOUT_HEIGHT"] = "height"; translations["BLOCK__INPUT_INOUT_HEIGHT_HELP"] = "Wanted height of images (in pixels)"; translations["BLOCK__INPUT_INOUT_POS_FRAMES"] = "position"; translations["BLOCK__INPUT_INOUT_POS_FRAMES_HELP"] = "0-based index of the frame to be decoded/captured"; translations["BLOCK__INPUT_INOUT_POS_RATIO"] = "pos. ratio"; translations["BLOCK__INPUT_INOUT_POS_RATIO_HELP"] = "Relative position in the video file (0-begining, 1-end)"; translations["BLOCK__INPUT_OUT_FORMAT"] = "out format"; translations["BLOCK__INPUT_OUT_FORMAT_HELP"] = "The format of the Mat objects"; translations["BLOCK__OUTPUT_NAME"] = "Display image"; translations["BLOCK__OUTPUT_IN_IMAGE"] = "image"; translations["BLOCK__OUTPUT_IN_IMAGE_HELP"] = "Image to show"; translations["BLOCK__OUTPUT_IN_WIN_NAME"] = "win. title"; translations["BLOCK__OUTPUT_IN_WIN_NAME_HELP"] = "Windows title"; translations["BLOCK__OUTPUT_IN_NORMALIZE"] = "normalize"; translations["BLOCK__OUTPUT_IN_NORMALIZE_HELP"] = "Normalize image before show"; translations["BLOCK__SHOWGRAPH_NAME"] = "Show graph"; translations["BLOCK__SHOWGRAPH_IN_VALUES"] = "values"; translations["BLOCK__SHOWGRAPH_IN_VALUES_HELP"] = "Vector of values to show"; translations["BLOCK__SHOWGRAPH_IN_TITLE"] = "title"; translations["BLOCK__SHOWGRAPH_IN_TITLE_HELP"] = "Graph title"; translations["BLOCK__STRING_CREATION_NAME"] = "String creation"; translations["BLOCK__STRING_CREATION_IN_REGEX"] = "pattern"; translations["BLOCK__STRING_CREATION_IN_REGEX_HELP"] = "Pattern name <br/>(use %i% for input i : <br/>\"img%1%.jpg\"<br/> will concatenate first input<br/> with the pattern...)<br/>%n% can also be used:<br/>it's the number of current frame"; translations["BLOCK__STRING_CREATION_OUT"] = "output"; translations["BLOCK__STRING_CREATION_OUT_HELP"] = "Constructed string"; translations["BLOCK__WRITE_NAME"] = "Write video"; translations["BLOCK__WRITE_IN_IMAGE"] = "image"; translations["BLOCK__WRITE_IN_IMAGE_HELP"] = "Image to add to video file"; translations["BLOCK__WRITE_IN_FILENAME"] = "Filename"; translations["BLOCK__WRITE_IN_FILENAME_HELP"] = "Filename of the video file"; translations["BLOCK__WRITE_IN_FPS"] = "FPS"; translations["BLOCK__WRITE_IN_FPS_HELP"] = "Frames per second"; translations["BLOCK__WRITE_IN_CODEC"] = "codec"; translations["BLOCK__WRITE_IN_CODEC_HELP"] = "FOURCC wanted (XVID, X264...).<br/>Empty if you want no compression,<br/>-1 if you want to choose using IHM!"; translations["BLOCK__IMWRITE_NAME"] = "Write image"; translations["BLOCK__IMWRITE_IN_IMAGE"] = "image"; translations["BLOCK__IMWRITE_IN_IMAGE_HELP"] = "Image to save"; translations["BLOCK__IMWRITE_IN_FILENAME"] = "Filename"; translations["BLOCK__IMWRITE_IN_FILENAME_HELP"] = "Filename of the file"; translations["BLOCK__IMWRITE_IN_QUALITY"] = "Quality"; translations["BLOCK__IMWRITE_IN_QUALITY_HELP"] = "Quality of the output img (0->highest compression, 100->highest quality)"; translations["BLOCK__LINEDRAWER_NAME"] = "Draw lines"; translations["BLOCK__LINEDRAWER_IN_LINES"] = "lines list"; translations["BLOCK__LINEDRAWER_IN_LINES_HELP"] = "Input of lines (4 values per row)"; translations["BLOCK__LINEDRAWER_IN_IMAGE"] = "image"; translations["BLOCK__LINEDRAWER_IN_IMAGE_HELP"] = "Input image to draw on"; translations["BLOCK__LINEDRAWER_IN_COLOR"] = "color"; translations["BLOCK__LINEDRAWER_IN_COLOR_HELP"] = "Color of lines"; translations["BLOCK__LINEDRAWER_IN_SIZE"] = "size"; translations["BLOCK__LINEDRAWER_IN_SIZE_HELP"] = "Size of lines"; translations["BLOCK__LINEDRAWER_OUT_IMAGE"] = "image"; translations["BLOCK__LINEDRAWER_OUT_IMAGE_HELP"] = "Binary output image"; translations["BLOCK__POINTDRAWER_NAME"] = "Draw points"; translations["BLOCK__POINTDRAWER_IN_POINTS"] = "point list"; translations["BLOCK__POINTDRAWER_IN_POINTS_HELP"] = "Input of points (2 values per row)"; translations["BLOCK__POINTDRAWER_IN_IMAGE"] = "image"; translations["BLOCK__POINTDRAWER_IN_IMAGE_HELP"] = "Input image to draw on"; translations["BLOCK__POINTDRAWER_IN_COLOR"] = "color"; translations["BLOCK__POINTDRAWER_IN_COLOR_HELP"] = "Color of points"; translations["BLOCK__POINTDRAWER_IN_SIZE"] = "size"; translations["BLOCK__POINTDRAWER_IN_SIZE_HELP"] = "Size of points"; translations["BLOCK__POINTDRAWER_OUT_IMAGE"] = "image"; translations["BLOCK__POINTDRAWER_OUT_IMAGE_HELP"] = "Binary output image"; translations["BLOCK__POINTDRAWER_ERROR_POINT_SIZE"] = "Image and points have different sizes"; translations["BLOCK__CREATEMATRIX_NAME"] = "Create new matrix"; translations["BLOCK__CREATEMATRIX_IN_TYPE"] = "type"; translations["BLOCK__CREATEMATRIX_IN_TYPE_HELP"] = "Wanted type|CV_8U^CV_8S^CV_16U^CV_16S^CV_32S^CV_32F^CV_64F"; translations["BLOCK__CREATEMATRIX_IN_NBCHANNEL"] = "channels"; translations["BLOCK__CREATEMATRIX_IN_NBCHANNEL_HELP"] = "Numbers of channels"; translations["BLOCK__CREATEMATRIX_IN_WIDTH"] = translations["BLOCK__INPUT_INOUT_WIDTH"]; translations["BLOCK__CREATEMATRIX_IN_WIDTH_HELP"] = translations["BLOCK__INPUT_INOUT_WIDTH_HELP"]; translations["BLOCK__CREATEMATRIX_IN_HEIGHT"] = translations["BLOCK__INPUT_INOUT_HEIGHT"]; translations["BLOCK__CREATEMATRIX_IN_HEIGHT_HELP"] = translations["BLOCK__INPUT_INOUT_HEIGHT_HELP"]; translations["BLOCK__CREATEMATRIX_IN_INIT"] = "intialisation"; translations["BLOCK__CREATEMATRIX_IN_INIT_HELP"] = "Initial values of matrix|zeros^ones^eye^ellipse^rect^cross^random uniform^random gaussian"; translations["BLOCK__CREATEMATRIX_OUT_IMAGE"] = "image"; translations["BLOCK__CREATEMATRIX_OUT_IMAGE_HELP"] = "Binary output image"; translations["BLOCK__NORMALIZ_NAME"] = "Normalize image"; translations["BLOCK__NORMALIZ_IN_IMAGE"] = "image"; translations["BLOCK__NORMALIZ_IN_IMAGE_HELP"] = "Input image"; translations["BLOCK__NORMALIZ_OUT_IMAGE"] = "image"; translations["BLOCK__NORMALIZ_OUT_IMAGE_HELP"] = "Normalized image"; translations["BLOCK__OPTICFLOW_NAME"] = "Compute Optical flow"; translations["BLOCK__OPTICFLOW_IN_IMAGE1"] = "image1"; translations["BLOCK__OPTICFLOW_IN_IMAGE1_HELP"] = "First image"; translations["BLOCK__OPTICFLOW_IN_IMAGE2"] = "image2"; translations["BLOCK__OPTICFLOW_IN_IMAGE2_HELP"] = "Second image"; translations["BLOCK__OPTICFLOW_IN_METHOD"] = "method"; translations["BLOCK__OPTICFLOW_IN_METHOD_HELP"] = "Method|LK^Farneback^DualTVL1^DeepFlow"; translations["BLOCK__OPTICFLOW_OUT_IMAGE"] = "flow"; translations["BLOCK__OPTICFLOW_OUT_IMAGE_HELP"] = "Optical flow"; translations["BLOCK__LINE_FINDER_NAME"] = "Find lines"; translations["BLOCK__LINE_FINDER_IN_IMAGE"] = "image"; translations["BLOCK__LINE_FINDER_IN_IMAGE_HELP"] = "Input image"; translations["BLOCK__LINE_FINDER_OUT_IMAGE"] = "lines"; translations["BLOCK__LINE_FINDER_OUT_IMAGE_HELP"] = "List of detected lines"; translations["BLOCK__POINT_FINDER_NAME"] = "Find points"; translations["BLOCK__POINT_FINDER_IN_IMAGE"] = "image"; translations["BLOCK__POINT_FINDER_IN_IMAGE_HELP"] = "Input image"; translations["BLOCK__POINT_FINDER_IN_DETECTOR"] = "detector"; translations["BLOCK__POINT_FINDER_IN_DETECTOR_HELP"] = "Method used to detect points|BRISK^FAST^GFTT^HARRIS^MSER^ORB^SIFT^STAR^SURF^KAZE^AKAZE^SimpleBlob"; //^Grid^Dense translations["BLOCK__POINT_FINDER_IN_EXTRACTOR"] = "extractor"; translations["BLOCK__POINT_FINDER_IN_EXTRACTOR_HELP"] = "Method used to compute descriptor|SIFT^SURF^ORB^BRIEF^BRISK^MSER^FREAK^KAZE^AKAZE"; translations["BLOCK__POINT_FINDER_OUT_DESC"] = "descriptors"; translations["BLOCK__POINT_FINDER_OUT_DESC_HELP"] = "List of corresponding descriptors"; translations["BLOCK__POINT_FINDER_OUT_POINTS"] = "points"; translations["BLOCK__POINT_FINDER_OUT_POINTS_HELP"] = "List of detected points"; translations["BLOCK__POINT_MATCHER_NAME"] = "Match points"; translations["BLOCK__POINT_MATCHER_IN_PT_DESC1"] = "desc1"; translations["BLOCK__POINT_MATCHER_IN_PT_DESC1_HELP"] = "List of first points descriptors"; translations["BLOCK__POINT_MATCHER_IN_PT_DESC2"] = "desc2"; translations["BLOCK__POINT_MATCHER_IN_PT_DESC2_HELP"] = "List of second points descriptors"; translations["BLOCK__POINT_MATCHER_IN_ALGO"] = "method"; translations["BLOCK__POINT_MATCHER_IN_ALGO_HELP"] = "Method used to match feature vector|Brute force^FLANN"; translations["BLOCK__POINT_MATCHER_OUT_MATCHES"] = "matches"; translations["BLOCK__POINT_MATCHER_OUT_MATCHES_HELP"] = "List of matched points"; translations["BLOCK__POINT_MATCHER_OUT_MATCHES_MASK"] = "mask"; translations["BLOCK__POINT_MATCHER_OUT_MATCHES_MASK_HELP"] = "List of correct matched points"; translations["BLOCK__DEINTERLACE_NAME"] = "Deinterlace"; translations["BLOCK__DEINTERLACE_IN_IMAGE"] = "image"; translations["BLOCK__DEINTERLACE_IN_IMAGE_HELP"] = "Input image"; translations["BLOCK__DEINTERLACE_IN_TYPE"] = "Deinterlacing"; translations["BLOCK__DEINTERLACE_IN_TYPE_HELP"] = "Deinterlacing type wanted|Blend^Bob^Discard^Unfold"; translations["BLOCK__DEINTERLACE_OUT_IMAGE"] = "image"; translations["BLOCK__DEINTERLACE_OUT_IMAGE_HELP"] = "Deinterlaced image"; translations["BLOCK__HISTOGRAM_NAME"] = "Histogram"; translations["BLOCK__HISTOGRAM_IN_IMAGE"] = "image"; translations["BLOCK__HISTOGRAM_IN_IMAGE_HELP"] = "Input image"; translations["BLOCK__HISTOGRAM_IN_BINS"] = "#bins"; translations["BLOCK__HISTOGRAM_IN_BINS_HELP"] = "number of bins"; translations["BLOCK__HISTOGRAM_IN_ACCUMULATE"] = "accumulate"; translations["BLOCK__HISTOGRAM_IN_ACCUMULATE_HELP"] = "This feature enables you to compute a single histogram from several sets of arrays, or to update the histogram in time"; translations["BLOCK__HISTOGRAM_OUT_HISTO"] = "histo"; translations["BLOCK__HISTOGRAM_OUT_HISTO_HELP"] = "Histogram of the input image"; translations["BLOCK__SKIP_FRAME_NAME"] = "Keep only 1 frame every N frame"; translations["BLOCK__SKIP_FRAME_IN_IMAGE"] = "image"; translations["BLOCK__SKIP_FRAME_IN_IMAGE_HELP"] = "Input image"; translations["BLOCK__SKIP_FRAME_IN_TYPE"] = "nb skip"; translations["BLOCK__SKIP_FRAME_IN_TYPE_HELP"] = "Number of frames to skip"; translations["BLOCK__SKIP_FRAME_OUT_IMAGE"] = "image"; translations["BLOCK__SKIP_FRAME_OUT_IMAGE_HELP"] = "Interlaced image"; translations["BLOCK__DELAY_VIDEO_NAME"] = "Delay the video of N frame"; translations["BLOCK__DELAY_VIDEO_IN_IMAGE"] = "image"; translations["BLOCK__DELAY_VIDEO_IN_IMAGE_HELP"] = "Input image"; translations["BLOCK__DELAY_VIDEO_IN_DELAY"] = "delay"; translations["BLOCK__DELAY_VIDEO_IN_DELAY_HELP"] = "Number of frames to delay"; translations["BLOCK__DELAY_VIDEO_OUT_IMAGE"] = "image"; translations["BLOCK__DELAY_VIDEO_OUT_IMAGE_HELP"] = "N-th old image"; translations["BLOCK__ADD_NAME"] = "Add"; translations["BLOCK__ADD_IN_PARAM1"] = "input1"; translations["BLOCK__ADD_IN_PARAM1_HELP"] = "First input (Matrix, number...)"; translations["BLOCK__ADD_IN_PARAM2"] = "input2"; translations["BLOCK__ADD_IN_PARAM2_HELP"] = "Second input (Matrix, number...)"; translations["BLOCK__ADD_OUTPUT"] = "sum"; translations["BLOCK__ADD_OUTPUT_HELP"] = "Output sum of the two input (concatenate in case of string)"; translations["BLOCK__CROP_NAME"] = "Crop image"; translations["BLOCK__CROP_IN_IMAGE"] = "image"; translations["BLOCK__CROP_IN_IMAGE_HELP"] = "Input image"; translations["BLOCK__CROP_WIDTH"] = translations["BLOCK__INPUT_INOUT_WIDTH"]; translations["BLOCK__CROP_WIDTH_HELP"] = translations["BLOCK__INPUT_INOUT_WIDTH_HELP"]; translations["BLOCK__CROP_HEIGHT"] = translations["BLOCK__INPUT_INOUT_HEIGHT"]; translations["BLOCK__CROP_HEIGHT_HELP"] = translations["BLOCK__INPUT_INOUT_HEIGHT_HELP"]; translations["BLOCK__CROP_IN_X"] = "X"; translations["BLOCK__CROP_IN_X_HELP"] = "Position of top-left corner (X)"; translations["BLOCK__CROP_IN_Y"] = "Y"; translations["BLOCK__CROP_IN_Y_HELP"] = "Position of top-left corner (Y)"; translations["BLOCK__CROP_OUT_IMAGE"] = "image"; translations["BLOCK__CROP_OUT_IMAGE_HELP"] = "Croped image"; translations["BLOCK__ACCUMULATOR_NAME"] = "Accumulator"; translations["BLOCK__ACCUMULATOR_IN_IMAGE"] = "image"; translations["BLOCK__ACCUMULATOR_IN_IMAGE_HELP"] = "Input image to accumulate"; translations["BLOCK__ACCUMULATOR_IN_NB_HISTORY"] = "history"; translations["BLOCK__ACCUMULATOR_IN_NB_HISTORY_HELP"] = "Size of accumulation history"; translations["BLOCK__ACCUMULATOR_OUT_IMAGE"] = "image"; translations["BLOCK__ACCUMULATOR_OUT_IMAGE_HELP"] = "Accumulated image"; translations["BLOCK__MORPHOLOGIC_NAME"] = "Morpho math"; translations["BLOCK__MORPHOLOGIC_IN_IMAGE"] = "image"; translations["BLOCK__MORPHOLOGIC_IN_IMAGE_HELP"] = "Input image"; translations["BLOCK__MORPHOLOGIC_ELEMENT"] = "element"; translations["BLOCK__MORPHOLOGIC_ELEMENT_HELP"] = "Structuring element."; translations["BLOCK__MORPHOLOGIC_OPERATOR"] = "op"; translations["BLOCK__MORPHOLOGIC_OPERATOR_HELP"] = "Operator|open^close^gradient^tophat^blackhat"; translations["BLOCK__MORPHOLOGIC_ITERATIONS"] = "iterations"; translations["BLOCK__MORPHOLOGIC_ITERATIONS_HELP"] = "Number of times erosion and dilation are applied."; translations["BLOCK__MORPHOLOGIC_OUT_IMAGE"] = "image"; translations["BLOCK__MORPHOLOGIC_OUT_IMAGE_HELP"] = "Filtered image"; translations["BLOCK__CANNY_NAME"] = "Canny"; translations["BLOCK__CANNY_IN_IMAGE"] = "image"; translations["BLOCK__CANNY_IN_IMAGE_HELP"] = "Input image"; translations["BLOCK__CANNY_OUT_IMAGE"] = "output"; translations["BLOCK__CANNY_OUT_IMAGE_HELP"] = "Canny image"; translations["BLOCK__CANNY_IN_THRESHOLD_1"] = "Threshold 1"; translations["BLOCK__CANNY_IN_THRESHOLD_1_HELP"] = "1er threshold for the hysteresis procedure"; translations["BLOCK__CANNY_IN_THRESHOLD_2"] = "Threshold 2"; translations["BLOCK__CANNY_IN_THRESHOLD_2_HELP"] = "2nd threshold for the hysteresis procedure"; translations["BLOCK__CANNY_IN_APERTURE_SIZE"] = "Aperture Size"; translations["BLOCK__CANNY_IN_APERTURE_SIZE_HELP"] = "aperture size for the Sobel operator"; translations["BLOCK__CANNY_IN_L2_GRADIENT"] = "L2 Gradient"; translations["BLOCK__CANNY_IN_L2_GRADIENT_HELP"] = "Use more accurate L2 gradient"; translations["BLOCK__INPUT_IN_INPUT_FILE"] = "Input"; translations["BLOCK__INPUT_IN_INPUT_FILE_HELP"] = "File Path"; translations["BLOCK__INPUT_RAW_VIDEO_NAME"] = "YUV reader"; translations["BLOCK__OUTPUT_RAW_VIDEO_NAME"] = "YUV writer"; translations["BLOCK__CASCADECLASSIFIER_NAME"] = "Cascade Classifier"; translations["BLOCK__CASCADECLASSIFIER_IN_IMAGE"] = "image"; translations["BLOCK__CASCADECLASSIFIER_IN_IMAGE_HELP"] = "Input image"; translations["BLOCK__CASCADECLASSIFIER_OUT_IMAGE"] = "mask"; translations["BLOCK__CASCADECLASSIFIER_OUT_IMAGE_HELP"] = "Output mask"; translations["BLOCK__CASCADECLASSIFIER_IN_CASCADE_FILE"] = "classifier"; translations["BLOCK__CASCADECLASSIFIER_IN_CASCADE_FILE_HELP"] = "Loads a classifier from a file."; translations["BLOCK__CASCADECLASSIFIER_IN_SCALE_FACTOR"] = "scaleFactor"; translations["BLOCK__CASCADECLASSIFIER_IN_SCALE_FACTOR_HELP"] = "Parameter specifying how much the image size is reduced at each image scale."; translations["BLOCK__CASCADECLASSIFIER_IN_MIN_NEIGHBORS"] = "minNeighbors"; translations["BLOCK__CASCADECLASSIFIER_IN_MIN_NEIGHBORS_HELP"] = "Parameter specifying how many neighbors each candidate rectangle should have to retain it."; translations["BLOCK__CASCADECLASSIFIER_IN_MIN_WIDTH"] = "minWidth"; translations["BLOCK__CASCADECLASSIFIER_IN_MIN_WIDTH_HELP"] = "Minimum possible object width. Objects smaller than that are ignored."; translations["BLOCK__CASCADECLASSIFIER_IN_MIN_HEIGHT"] = "minHeight"; translations["BLOCK__CASCADECLASSIFIER_IN_MIN_HEIGHT_HELP"] = "Minimum possible object height. Objects smaller than that are ignored."; translations["BLOCK__CASCADECLASSIFIER_IN_MAX_WIDTH"] = "maxWidth"; translations["BLOCK__CASCADECLASSIFIER_IN_MAX_WIDTH_HELP"] = "Maximum possible object width. Objects larger than that are ignored."; translations["BLOCK__CASCADECLASSIFIER_IN_MAX_HEIGHT"] = "maxHeight"; translations["BLOCK__CASCADECLASSIFIER_IN_MAX_HEIGHT_HELP"] = "Maximum possible object height. Objects larger than that are ignored."; translations["BLOCK__CASCADECLASSIFIER_OUT_OBJECTS"] = "#objects"; translations["BLOCK__CASCADECLASSIFIER_OUT_OBJECTS_HELP"] = "Number of detected objects"; translations["BLOCK__BLUR_NAME"] = "Blurring"; translations["BLOCK__BLUR_IN_METHOD"] = "method"; translations["BLOCK__BLUR_IN_METHOD_HELP"] = "Blurring method|Mean^Gaussian^Median^Bilateral"; translations["BLOCK__BLUR_IN_IMG"] = "image"; translations["BLOCK__BLUR_IN_IMG_HELP"] = "Input image"; translations["BLOCK__BLUR_OUT_IMAGE"] = "image"; translations["BLOCK__BLUR_OUT_IMAGE_HELP"] = "Filtered image"; translations["BLOCK__CONVERTMATRIX_NAME"] = "Convert matrix"; translations["BLOCK__CONVERTMATRIX_IN_IMG"] = "image"; translations["BLOCK__CONVERTMATRIX_IN_IMG_HELP"] = "Input image to convert"; translations["BLOCK__CONVERTMATRIX_IN_TYPE"] = "type"; translations["BLOCK__CONVERTMATRIX_IN_TYPE_HELP"] = "Wanted type|CV_8U^CV_8S^CV_16U^CV_16S^CV_32S^CV_32F^CV_64F"; translations["BLOCK__CONVERTMATRIX_IN_NBCHANNEL"] = "channels"; translations["BLOCK__CONVERTMATRIX_IN_NBCHANNEL_HELP"] = "Numbers of channels"; translations["BLOCK__CONVERTMATRIX_OUT_IMAGE"] = "image"; translations["BLOCK__CONVERTMATRIX_OUT_IMAGE_HELP"] = "Binary output image"; translations["BLOCK__RESIZEMATRIX_NAME"] = "Resize matrix"; translations["BLOCK__RESIZEMATRIX_IN_IMG"] = "image"; translations["BLOCK__RESIZEMATRIX_IN_IMG_HELP"] = "Input image to resize"; translations["BLOCK__RESIZEMATRIX_IN_WIDTH"] = translations["BLOCK__INPUT_INOUT_WIDTH"]; translations["BLOCK__RESIZEMATRIX_IN_WIDTH_HELP"] = translations["BLOCK__INPUT_INOUT_WIDTH_HELP"]; translations["BLOCK__RESIZEMATRIX_IN_HEIGHT"] = translations["BLOCK__INPUT_INOUT_HEIGHT"]; translations["BLOCK__RESIZEMATRIX_IN_HEIGHT_HELP"] = translations["BLOCK__INPUT_INOUT_HEIGHT_HELP"]; translations["BLOCK__RESIZEMATRIX_OUT_IMAGE"] = "image"; translations["BLOCK__RESIZEMATRIX_OUT_IMAGE_HELP"] = "Binary output image"; translations["BLOCK__CORE_NAME"] = "CORE filter"; translations["BLOCK__CORE_IN_POINTS"] = "points"; translations["BLOCK__CORE_IN_POINTS_HELP"] = "Input points to filter"; translations["BLOCK__CORE_IN_DESC"] = "descriptors"; translations["BLOCK__CORE_IN_DESC_HELP"] = "Input descriptors to filter"; translations["BLOCK__CORE_IN_THRESHOLD"] = "threshold"; translations["BLOCK__CORE_IN_THRESHOLD_HELP"] = "Threshold value (percent)"; translations["BLOCK__CORE_IN_OPTIM_THRESHOLD"] = "optimization"; translations["BLOCK__CORE_IN_OPTIM_THRESHOLD_HELP"] = "Threshold value of optimization (0->1, 1 for no optimization)"; translations["BLOCK__CORE_OUT_POINTS"] = "points"; translations["BLOCK__CORE_OUT_POINTS_HELP"] = "Filtered points"; translations["BLOCK__CORE_OUT_DESC"] = "descriptors"; translations["BLOCK__CORE_OUT_DESC_HELP"] = "Filtered descriptors"; translations["BLOCK__FILTER2D_NAME"] = "Filter2D"; translations["BLOCK__FILTER2D_IN_IMAGE"] = "image"; translations["BLOCK__FILTER2D_IN_IMAGE_HELP"] = "Input image"; translations["BLOCK__FILTER2D_IN_KERNEL"] = "kernel"; translations["BLOCK__FILTER2D_IN_KERNEL_HELP"] = "Convolution kernel "; translations["BLOCK__FILTER2D_OUT_IMAGE"] = "image"; translations["BLOCK__FILTER2D_OUT_IMAGE_HELP"] = "Output image"; translations["BLOCK__LAPLACIAN_NAME"] = "Laplacian"; translations["BLOCK__LAPLACIAN_IN_IMAGE"] = "image"; translations["BLOCK__LAPLACIAN_IN_IMAGE_HELP"] = "Input image"; translations["BLOCK__LAPLACIAN_OUT_IMAGE"] = "image"; translations["BLOCK__LAPLACIAN_OUT_IMAGE_HELP"] = "Output image"; translations["BLOCK__MASKDRAWER_NAME"] = "Draw mask"; translations["BLOCK__MASKDRAWER_IN_IMAGE"] = "image"; translations["BLOCK__MASKDRAWER_IN_IMAGE_HELP"] = "Input image"; translations["BLOCK__MASKDRAWER_IN_MASK"] = "mask"; translations["BLOCK__MASKDRAWER_IN_MASK_HELP"] = "Input mask"; translations["BLOCK__MASKDRAWER_IN_PRINTMASK"] = "Masking type"; translations["BLOCK__MASKDRAWER_IN_PRINTMASK_HELP"] = "How to use the mask?|Draw mask^Keep only mask"; translations["BLOCK__MASKDRAWER_OUT_IMAGE"] = "image"; translations["BLOCK__MASKDRAWER_OUT_IMAGE_HELP"] = "Output image"; translations["BLOCK__MASKDRAWER_ERROR_MASK_TYPE"] = "Expected mask of type CV_8UC1"; translations["BLOCK__MASKDRAWER_ERROR_DIFF_SIZE"] = "Image and mask have different sizes"; translations["BLOCK__THINNING_NAME"] = "Thinning img"; translations["BLOCK__THINNING_IN_IMAGE"] = "image"; translations["BLOCK__THINNING_IN_IMAGE_HELP"] = "Input image"; translations["BLOCK__THINNING_OUT_IMAGE"] = "image"; translations["BLOCK__THINNING_OUT_IMAGE_HELP"] = "Output image"; translations["BLOCK__DISTANCE_NAME"] = "Distance transform"; translations["BLOCK__DISTANCE_IN_IMAGE"] = "image"; translations["BLOCK__DISTANCE_IN_IMAGE_HELP"] = "Input image"; translations["BLOCK__DISTANCE_IN_DISTANCETYPE"] = "distance"; translations["BLOCK__DISTANCE_IN_DISTANCETYPE_HELP"] = "distance type|DIST_C^DIST_L1^DIST_L2^DIST_PRECISE"; translations["BLOCK__DISTANCE_OUT_IMAGE"] = "image"; translations["BLOCK__DISTANCE_OUT_IMAGE_HELP"] = "Output image"; translations["BLOCK__BINARIZE_NAME"] = "Binarize img"; translations["BLOCK__BINARIZE_IN_IMAGE"] = "image"; translations["BLOCK__BINARIZE_IN_IMAGE_HELP"] = "Input image"; translations["BLOCK__BINARIZE_IN_INVERSE"] = "inverse"; translations["BLOCK__BINARIZE_IN_INVERSE_HELP"] = "Use inverse of binary image"; translations["BLOCK__BINARIZE_IN_METHOD"] = "Method"; translations["BLOCK__BINARIZE_IN_METHOD_HELP"] = "Binarization method|Simple threshold^Otsu^Adaptative^Sauvola"; translations["BLOCK__BINARIZE_IN_THRESHOLD"] = "threshold"; translations["BLOCK__BINARIZE_IN_THRESHOLD_HELP"] = "Threshold value"; translations["BLOCK__BINARIZE_OUT_IMAGE"] = "image"; translations["BLOCK__BINARIZE_OUT_IMAGE_HELP"] = "Output image"; } }
58.017007
245
0.745442
Petititi
ff339c084727ed58728297a87a590bdb02575d6f
6,745
cpp
C++
src/hranol.cpp
romeritto/hranol
71e37d254c7c9ea0f61a0b6ddce3261483dc1809
[ "MIT" ]
null
null
null
src/hranol.cpp
romeritto/hranol
71e37d254c7c9ea0f61a0b6ddce3261483dc1809
[ "MIT" ]
null
null
null
src/hranol.cpp
romeritto/hranol
71e37d254c7c9ea0f61a0b6ddce3261483dc1809
[ "MIT" ]
null
null
null
// // Copyright © 2018 Roman Sobkuliak <[email protected]> // This code is released under the license described in the LICENSE file // #include "../thirdparty/args/args.hxx" #include "Filter.h" #include "FolderCrawler.h" #include "ImageProcessor.h" #include "ImageStore.h" #include <iostream> #include <vector> #include <string> #include <stdexcept> #include <memory> class Hranol { std::vector< std::string> folders_; bool recursive_; bool ram_friendly_; std::string fname_regex_; std::string output_folder_; // Prefix of filtered folders std::string folder_prefix_; // Indicates whether folders starting with folder_prefix_ should be included bool incl_folder_prefix_; ImageProcessor img_processor_; public: // Defaults Hranol() : recursive_(false), ram_friendly_(false), fname_regex_(".*\\.(jpe?g|gif|tif|tiff|png|bmp)"), output_folder_(""), folder_prefix_("fltrd"), incl_folder_prefix_(false) { } void parse_from_cli(int argc, char **argv); void process(); }; void Hranol::parse_from_cli(int argc, char **argv) { args::ArgumentParser parser( "Hranol -- batch image processing utility. By default only images in given folders are processed " "and the output is saved to a subfolder with prefix \"" + folder_prefix_ + "\". Writing to subfolders " "can be overridden with option -o which specifies output folder. Supported filters: static background " "subtraction, contrast filter (normalization) and mask filter. Each filter is used when a corresponding filter-specific " "option is set. Only grayscale images are supported.", "Visit the project page for further information: https://github.com/romeritto/hranol"); parser.Prog(argv[0]); args::ValueFlag<std::string> mask_file(parser, "file", "Apply mask to every image. The mask size must match the sizes of all images.", { 'm', "mask" }); args::ValueFlag<double> subtraction_factor(parser, "subtraction factor", "Static background subtraction factor. Computes an average of all images (from single folder) and " "subtracts this average from each image with given factor. You may use positive floating point " "values for the factor.", { 's', "static-noise" }); args::Group rescale(parser, "Rescaling range [b, e] for contrast filter. Pixel values in range [b, e] will be mapped to [0, 255]:"); args::ValueFlag<int> rescale_beg(rescale, "range begin", "", { 'b', "rescale-begin" }); args::ValueFlag<int> rescale_end(rescale, "range end", "", { 'e', "rescale-end" }); args::ValueFlag<std::string> fname_regex(parser, "filename regex", "If specified, only files matching given regex will be processed. Default value is \"" + fname_regex_ + "\" " "(matches common image files). Use ECMAScript regex syntax.", {'f', "fname-regex"}); args::ValueFlag<std::string> output_folder(parser, "output folder", "Specifies output folder for filtered images. If used together with recursive option original folder structure " "will be preserved (folders won't be flattened).", { 'o', "output-folder" }); args::ValueFlag<std::string> folder_prefix(parser, "filtered folder prefix", "Specifies prefix of subfolder that will hold filtered images. Default value is \"" + folder_prefix_ + "\"", { 'p', "folder-prefix" }); args::Flag incl_folder_prefix(parser, "include filtered folders", "If set folders found during recursive traversal starting with folder-prefix (specified with " "option -p) will be processed. By default these folders are ignored so that they don't " "get filtered twice.", { 'i', "incl-fltrd" }); args::Flag recursive(parser, "recursive", "Process input folders recursively.", { 'r', "recursive" }); args::Flag ram_friendly(parser, "ram friendly", "By default all images from a single folder are stored in memory when the folder is being processed. If that is not possible " "due to small RAM space, use this flag.", { "ram-friendly" }); args::PositionalList<std::string> folders(parser, "folders", "List of folders to process."); args::HelpFlag help(parser, "help", "Display this help menu", { 'h', "help" }); try { parser.ParseCLI(argc, argv); } catch (const args::Help & e) { std::cout << parser; throw; } folders_ = std::vector<std::string>(args::get(folders)); if (recursive) recursive_ = true; if (ram_friendly) ram_friendly_ = true; if (fname_regex) fname_regex_ = args::get(fname_regex); if (output_folder) output_folder_ = args::get(output_folder); if (folder_prefix) folder_prefix_ = args::get(folder_prefix); if (incl_folder_prefix) incl_folder_prefix_ = true; if (mask_file) img_processor_.add_filter(std::move(MaskFilter::create(args::get(mask_file)))); if (subtraction_factor) img_processor_.add_filter(std::move(BckgSubFilter::create(args::get(subtraction_factor)))); if (rescale_beg || rescale_end) { if (rescale_beg && rescale_end) img_processor_.add_filter(std::move(ContrastFilter::create( args::get(rescale_beg), args::get(rescale_end) ))); else throw HranolRuntimeException("Both range begin and end must be specified for rescale filter."); } } void Hranol::process() { FolderCrawler crawler( folders_, output_folder_, folder_prefix_, fname_regex_, incl_folder_prefix_, recursive_, ram_friendly_ ); while (crawler.has_next_run()) { try { auto store = crawler.get_next_run(); img_processor_.apply_filters(store.get()); } catch (const std::exception &e) { std::cout << "\nError (skipping run):\n" << e.what() << std::endl; } } } int main(int argc, char **argv) { Hranol hranol; try { hranol.parse_from_cli(argc, argv); hranol.process(); } catch (const args::Help & e) { // Help page was requested return 0; } catch (const args::Error & e) { // An exception was thrown while processing arguments std::cerr << e.what() << std::endl; return 1; } catch (std::exception &e) { std::cerr << e.what() << std::endl; return 1; } catch (...) { std::cerr << "Unknown error" << std::endl; return 1; } }
34.768041
136
0.630245
romeritto
ff40f54d6ec76897d60f928773241dfc493e7dd4
3,328
cpp
C++
Programming/Sem2/Lab4/lab4.cpp
NazarPonochevnyi/Programming-Labs
30afedcdf79f1b7e91be62a34d4bb3a399eb3c9f
[ "MIT" ]
1
2020-10-17T13:18:29.000Z
2020-10-17T13:18:29.000Z
Programming/Sem2/Lab4/lab4.cpp
NazarPonochevnyi/Programming-Labs
30afedcdf79f1b7e91be62a34d4bb3a399eb3c9f
[ "MIT" ]
null
null
null
Programming/Sem2/Lab4/lab4.cpp
NazarPonochevnyi/Programming-Labs
30afedcdf79f1b7e91be62a34d4bb3a399eb3c9f
[ "MIT" ]
1
2021-11-08T00:35:35.000Z
2021-11-08T00:35:35.000Z
#include <iostream> using namespace std; /* 10. Перевантажити оператори потокового введення-виведення (>>,<<). */ class Fraction { protected: int numerator, denominator; int nod(int a, int b); int nok(int a, int b); public: Fraction(); Fraction(int num, int den); Fraction(const Fraction& f); void addition(const Fraction& f); void subtraction(const Fraction& f); void multiplication(const Fraction& f); void print(); ~Fraction(); friend Fraction operator +(const Fraction& a, const Fraction& b); Fraction& operator =(const Fraction& d); friend istream& operator >>(istream& s, Fraction& f); friend ostream& operator <<(ostream& s, const Fraction& f); }; Fraction::Fraction() { numerator = 1; denominator = 2; } Fraction::Fraction(int num, int den) { if (den == 0) { cout << "Error: division by zero!\n"; cout << 1/0; } if (num >= den) { cout << "Error: fraction must be < 1! Use Any_Fraction fraction.\n"; cout << 1/0; } numerator = num; denominator = den; } Fraction::Fraction(const Fraction& f) { numerator = f.numerator; denominator = f.denominator; } int Fraction::nod(int a, int b) { while (a != 0 && b != 0) { if (a > b) { a = a % b; } else b = b % a; } return a + b; } int Fraction::nok(int a, int b) { return a * b / Fraction::nod(a, b); } void Fraction::addition(const Fraction& f) { int cd = nok(denominator, f.denominator); numerator = (numerator * (cd / denominator)) + (f.numerator * (cd / f.denominator)); denominator = cd; } void Fraction::subtraction(const Fraction& f) { Fraction f1 = Fraction(f); f1.numerator *= -1; Fraction::addition(f1); } void Fraction::multiplication(const Fraction& f) { numerator *= f.numerator; denominator *= f.denominator; } void Fraction::print() { cout << numerator << "/" << denominator; } Fraction::~Fraction() { numerator = 0; denominator = 0; } Fraction operator +(const Fraction& a, const Fraction& b) { Fraction c = Fraction(a); c.addition(b); return c; } Fraction& Fraction::operator =(const Fraction& f) { numerator = f.numerator; denominator = f.denominator; return *this; } istream& operator >>(istream& s, Fraction& f) { cout << "Enter fraction:\n"; s >> f.numerator; cout << "--\n"; s >> f.denominator; return s; } ostream& operator <<(ostream& s, const Fraction& f) { s << f.numerator << "/" << f.denominator; return s; } class Any_Fraction : public Fraction { public: Any_Fraction(); Any_Fraction(int num, int den); Any_Fraction(const Any_Fraction& f); }; Any_Fraction::Any_Fraction() { numerator = 1; denominator = 2; } Any_Fraction::Any_Fraction(int num, int den) { if (den == 0) { cout << "Error: division by zero!\n"; cout << 1/0; } numerator = num; denominator = den; } Any_Fraction::Any_Fraction(const Any_Fraction& f) { numerator = f.numerator; denominator = f.denominator; } int main() { Fraction f1, f2, f3; cin >> f1; cin >> f2; f3 = f1 + f2; cout << "f1 + f2: " << f3; return 0; }
21.063291
88
0.577524
NazarPonochevnyi
ff434d0fd0e5b68931982659497b3c4ce24c6e1b
1,186
cpp
C++
reve/reve/lib/SplitEntryBlockPass.cpp
mattulbrich/llreve
68cb958c1c02177fa0db1965a8afd879a97c2fc4
[ "BSD-3-Clause" ]
20
2016-08-11T19:51:13.000Z
2021-09-02T13:10:58.000Z
reve/reve/lib/SplitEntryBlockPass.cpp
mattulbrich/llreve
68cb958c1c02177fa0db1965a8afd879a97c2fc4
[ "BSD-3-Clause" ]
9
2016-08-11T11:59:24.000Z
2021-07-16T09:44:28.000Z
reve/reve/lib/SplitEntryBlockPass.cpp
mattulbrich/llreve
68cb958c1c02177fa0db1965a8afd879a97c2fc4
[ "BSD-3-Clause" ]
7
2017-08-19T14:42:27.000Z
2020-05-20T16:14:13.000Z
/* * This file is part of * llreve - Automatic regression verification for LLVM programs * * Copyright (C) 2016 Karlsruhe Institute of Technology * * The system is published under a BSD license. * See LICENSE (distributed with this file) for details. */ #include "SplitEntryBlockPass.h" #include "llvm/IR/Instructions.h" llvm::PreservedAnalyses SplitBlockPass::run(llvm::Function &Fun, llvm::FunctionAnalysisManager &fam) { auto &Entry = Fun.getEntryBlock(); Entry.splitBasicBlock(Entry.begin()); std::vector<llvm::Instruction *> splitAt; for (auto &BB : Fun) { for (auto &Inst : BB) { if (const auto CallInst = llvm::dyn_cast<llvm::CallInst>(&Inst)) { if ((CallInst->getCalledFunction() != nullptr) && CallInst->getCalledFunction()->getName() == "__splitmark") { splitAt.push_back(CallInst); } } } } for (auto instr : splitAt) { llvm::BasicBlock::iterator i(instr); ++i; i->getParent()->splitBasicBlock(i); instr->getParent()->splitBasicBlock(instr); } return llvm::PreservedAnalyses::none(); }
31.210526
80
0.611298
mattulbrich
ff458f2db095189a0cbb3b2cf0497bee16c6a515
810
cpp
C++
src/Game Engine/Material.cpp
JKneedler/JK-Game-Engine
00a3a3c4833d12c4a93ae98b2508419700450e66
[ "Apache-2.0" ]
1
2021-05-10T17:29:30.000Z
2021-05-10T17:29:30.000Z
src/Game Engine/Material.cpp
JKneedler/JK-Game-Engine
00a3a3c4833d12c4a93ae98b2508419700450e66
[ "Apache-2.0" ]
null
null
null
src/Game Engine/Material.cpp
JKneedler/JK-Game-Engine
00a3a3c4833d12c4a93ae98b2508419700450e66
[ "Apache-2.0" ]
null
null
null
#include "Material.h" Material::Material() { specularIntensity = 0.0f; shininess = 0.0f; } Material::Material(GLfloat sIntensity, GLfloat shine) { specularIntensity = sIntensity; shininess = shine; } Material::Material(Shader* myShader, Texture* myTexture, GLfloat sIntensity, GLfloat shine) { shader = myShader; texture = myTexture; specularIntensity = sIntensity; shininess = shine; } void Material::UseMaterial() { glUniform1f(shader->GetSpecularIntensityLocation(), specularIntensity); glUniform1f(shader->GetShininessLocation(), shininess); texture->UseTexture(); } void Material::UseMaterial(GLuint specularIntensityLocation, GLuint shininessLocation) { glUniform1f(specularIntensityLocation, specularIntensity); glUniform1f(shininessLocation, shininess); } Material::~Material() { }
23.823529
93
0.774074
JKneedler
ff4644aac0d4c7e8cf9dbe074c6ca22148fe09f3
5,013
hpp
C++
include/Zenject/MethodMultipleProviderUntyped.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/Zenject/MethodMultipleProviderUntyped.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/Zenject/MethodMultipleProviderUntyped.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: Zenject.IProvider #include "Zenject/IProvider.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: Zenject namespace Zenject { // Forward declaring type: DiContainer class DiContainer; // Forward declaring type: InjectContext class InjectContext; } // Forward declaring namespace: System namespace System { // Forward declaring type: Func`2<T, TResult> template<typename T, typename TResult> class Func_2; // Forward declaring type: Type class Type; // Forward declaring type: Action class Action; } // Forward declaring namespace: System::Collections::Generic namespace System::Collections::Generic { // Forward declaring type: IEnumerable`1<T> template<typename T> class IEnumerable_1; // Forward declaring type: List`1<T> template<typename T> class List_1; } // Completed forward declares // Type namespace: Zenject namespace Zenject { // Size: 0x20 #pragma pack(push, 1) // Autogenerated type: Zenject.MethodMultipleProviderUntyped // [NoReflectionBakingAttribute] Offset: DDD0C0 class MethodMultipleProviderUntyped : public ::Il2CppObject/*, public Zenject::IProvider*/ { public: // private readonly Zenject.DiContainer _container // Size: 0x8 // Offset: 0x10 Zenject::DiContainer* container; // Field size check static_assert(sizeof(Zenject::DiContainer*) == 0x8); // private readonly System.Func`2<Zenject.InjectContext,System.Collections.Generic.IEnumerable`1<System.Object>> _method // Size: 0x8 // Offset: 0x18 System::Func_2<Zenject::InjectContext*, System::Collections::Generic::IEnumerable_1<::Il2CppObject*>*>* method; // Field size check static_assert(sizeof(System::Func_2<Zenject::InjectContext*, System::Collections::Generic::IEnumerable_1<::Il2CppObject*>*>*) == 0x8); // Creating value type constructor for type: MethodMultipleProviderUntyped MethodMultipleProviderUntyped(Zenject::DiContainer* container_ = {}, System::Func_2<Zenject::InjectContext*, System::Collections::Generic::IEnumerable_1<::Il2CppObject*>*>* method_ = {}) noexcept : container{container_}, method{method_} {} // Creating interface conversion operator: operator Zenject::IProvider operator Zenject::IProvider() noexcept { return *reinterpret_cast<Zenject::IProvider*>(this); } // public System.Void .ctor(System.Func`2<Zenject.InjectContext,System.Collections.Generic.IEnumerable`1<System.Object>> method, Zenject.DiContainer container) // Offset: 0x16C5BA8 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static MethodMultipleProviderUntyped* New_ctor(System::Func_2<Zenject::InjectContext*, System::Collections::Generic::IEnumerable_1<::Il2CppObject*>*>* method, Zenject::DiContainer* container) { static auto ___internal__logger = ::Logger::get().WithContext("Zenject::MethodMultipleProviderUntyped::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<MethodMultipleProviderUntyped*, creationType>(method, container))); } // public System.Boolean get_IsCached() // Offset: 0x16C5BE0 bool get_IsCached(); // public System.Boolean get_TypeVariesBasedOnMemberType() // Offset: 0x16C5BE8 bool get_TypeVariesBasedOnMemberType(); // public System.Type GetInstanceType(Zenject.InjectContext context) // Offset: 0x16C5BF0 System::Type* GetInstanceType(Zenject::InjectContext* context); // public System.Void GetAllInstancesWithInjectSplit(Zenject.InjectContext context, System.Collections.Generic.List`1<Zenject.TypeValuePair> args, out System.Action injectAction, System.Collections.Generic.List`1<System.Object> buffer) // Offset: 0x16C5C0C void GetAllInstancesWithInjectSplit(Zenject::InjectContext* context, System::Collections::Generic::List_1<Zenject::TypeValuePair>* args, System::Action*& injectAction, System::Collections::Generic::List_1<::Il2CppObject*>* buffer); }; // Zenject.MethodMultipleProviderUntyped #pragma pack(pop) static check_size<sizeof(MethodMultipleProviderUntyped), 24 + sizeof(System::Func_2<Zenject::InjectContext*, System::Collections::Generic::IEnumerable_1<::Il2CppObject*>*>*)> __Zenject_MethodMultipleProviderUntypedSizeCheck; static_assert(sizeof(MethodMultipleProviderUntyped) == 0x20); } DEFINE_IL2CPP_ARG_TYPE(Zenject::MethodMultipleProviderUntyped*, "Zenject", "MethodMultipleProviderUntyped");
53.903226
244
0.738081
darknight1050
ff4a04e5c02452aa59ddc8c7d2fc73ce9b308c2e
10,961
cpp
C++
src/pqclean.cpp
Cryptario/tidecoin
550b726eb7f39730086522676a9c74e40d672a81
[ "MIT" ]
30
2021-01-05T02:08:40.000Z
2022-01-21T09:32:10.000Z
src/pqclean.cpp
Cryptario/tidecoin
550b726eb7f39730086522676a9c74e40d672a81
[ "MIT" ]
8
2021-03-15T08:14:30.000Z
2022-02-02T11:37:14.000Z
src/pqclean.cpp
Cryptario/tidecoin
550b726eb7f39730086522676a9c74e40d672a81
[ "MIT" ]
20
2021-01-09T00:03:48.000Z
2022-03-07T11:58:35.000Z
#include "api.h" #include "inner.h" #include "randombytes.h" #include <stddef.h> #include <string.h> /* * Wrapper for implementing the PQClean API. */ #define NONCELEN 40 #define SEEDLEN 48 /* * Encoding formats (nnnn = log of degree, 9 for Falcon-512, 10 for Falcon-1024) * * private key: * header byte: 0101nnnn * private f (6 or 5 bits by element, depending on degree) * private g (6 or 5 bits by element, depending on degree) * private F (8 bits by element) * * public key: * header byte: 0000nnnn * public h (14 bits by element) * * signature: * header byte: 0011nnnn * nonce 40 bytes * value (12 bits by element) * * message + signature: * signature length (2 bytes, big-endian) * nonce 40 bytes * message * header byte: 0010nnnn * value (12 bits by element) * (signature length is 1+len(value), not counting the nonce) */ /* see api.h */ int PQCLEAN_FALCON512_CLEAN_crypto_sign_keypair(unsigned char *pk, unsigned char *sk) { union { uint8_t b[FALCON_KEYGEN_TEMP_9]; uint64_t dummy_u64; fpr dummy_fpr; } tmp; int8_t f[512], g[512], F[512]; uint16_t h[512]; unsigned char seed[SEEDLEN]; inner_shake256_context rng; size_t u, v; /* * Generate key pair. */ randombytes(seed, sizeof seed); inner_shake256_init(&rng); inner_shake256_inject(&rng, seed, sizeof seed); inner_shake256_flip(&rng); PQCLEAN_FALCON512_CLEAN_keygen(&rng, f, g, F, NULL, h, 9, tmp.b); inner_shake256_ctx_release(&rng); /* * Encode private key. */ sk[0] = 0x50 + 9; u = 1; v = PQCLEAN_FALCON512_CLEAN_trim_i8_encode( sk + u, PQCLEAN_FALCON512_CLEAN_CRYPTO_SECRETKEYBYTES - u, f, 9, PQCLEAN_FALCON512_CLEAN_max_fg_bits[9]); if (v == 0) { return -1; } u += v; v = PQCLEAN_FALCON512_CLEAN_trim_i8_encode( sk + u, PQCLEAN_FALCON512_CLEAN_CRYPTO_SECRETKEYBYTES - u, g, 9, PQCLEAN_FALCON512_CLEAN_max_fg_bits[9]); if (v == 0) { return -1; } u += v; v = PQCLEAN_FALCON512_CLEAN_trim_i8_encode( sk + u, PQCLEAN_FALCON512_CLEAN_CRYPTO_SECRETKEYBYTES - u, F, 9, PQCLEAN_FALCON512_CLEAN_max_FG_bits[9]); if (v == 0) { return -1; } u += v; if (u != PQCLEAN_FALCON512_CLEAN_CRYPTO_SECRETKEYBYTES) { return -1; } /* * Encode public key. */ pk[0] = 0x00 + 9; v = PQCLEAN_FALCON512_CLEAN_modq_encode( pk + 1, PQCLEAN_FALCON512_CLEAN_CRYPTO_PUBLICKEYBYTES - 1, h, 9); if (v != PQCLEAN_FALCON512_CLEAN_CRYPTO_PUBLICKEYBYTES - 1) { return -1; } return 0; } /* * Compute the signature. nonce[] receives the nonce and must have length * NONCELEN bytes. sigbuf[] receives the signature value (without nonce * or header byte), with *sigbuflen providing the maximum value length and * receiving the actual value length. * * If a signature could be computed but not encoded because it would * exceed the output buffer size, then a new signature is computed. If * the provided buffer size is too low, this could loop indefinitely, so * the caller must provide a size that can accommodate signatures with a * large enough probability. * * Return value: 0 on success, -1 on error. */ static int do_sign(uint8_t *nonce, uint8_t *sigbuf, size_t *sigbuflen, const uint8_t *m, size_t mlen, const uint8_t *sk) { union { uint8_t b[72 * 512]; uint64_t dummy_u64; fpr dummy_fpr; } tmp; int8_t f[512], g[512], F[512], G[512]; union { int16_t sig[512]; uint16_t hm[512]; } r; unsigned char seed[SEEDLEN]; inner_shake256_context sc; size_t u, v; /* * Decode the private key. */ if (sk[0] != 0x50 + 9) { return -1; } u = 1; v = PQCLEAN_FALCON512_CLEAN_trim_i8_decode( f, 9, PQCLEAN_FALCON512_CLEAN_max_fg_bits[9], sk + u, PQCLEAN_FALCON512_CLEAN_CRYPTO_SECRETKEYBYTES - u); if (v == 0) { return -1; } u += v; v = PQCLEAN_FALCON512_CLEAN_trim_i8_decode( g, 9, PQCLEAN_FALCON512_CLEAN_max_fg_bits[9], sk + u, PQCLEAN_FALCON512_CLEAN_CRYPTO_SECRETKEYBYTES - u); if (v == 0) { return -1; } u += v; v = PQCLEAN_FALCON512_CLEAN_trim_i8_decode( F, 9, PQCLEAN_FALCON512_CLEAN_max_FG_bits[9], sk + u, PQCLEAN_FALCON512_CLEAN_CRYPTO_SECRETKEYBYTES - u); if (v == 0) { return -1; } u += v; if (u != PQCLEAN_FALCON512_CLEAN_CRYPTO_SECRETKEYBYTES) { return -1; } if (!PQCLEAN_FALCON512_CLEAN_complete_private(G, f, g, F, 9, tmp.b)) { return -1; } /* * Create a random nonce (40 bytes). */ randombytes(nonce, NONCELEN); /* * Hash message nonce + message into a vector. */ inner_shake256_init(&sc); inner_shake256_inject(&sc, nonce, NONCELEN); inner_shake256_inject(&sc, m, mlen); inner_shake256_flip(&sc); PQCLEAN_FALCON512_CLEAN_hash_to_point_ct(&sc, r.hm, 9, tmp.b); inner_shake256_ctx_release(&sc); /* * Initialize a RNG. */ randombytes(seed, sizeof seed); inner_shake256_init(&sc); inner_shake256_inject(&sc, seed, sizeof seed); inner_shake256_flip(&sc); /* * Compute and return the signature. This loops until a signature * value is found that fits in the provided buffer. */ for (;;) { PQCLEAN_FALCON512_CLEAN_sign_dyn(r.sig, &sc, f, g, F, G, r.hm, 9, tmp.b); v = PQCLEAN_FALCON512_CLEAN_comp_encode(sigbuf, *sigbuflen, r.sig, 9); if (v != 0) { inner_shake256_ctx_release(&sc); *sigbuflen = v; return 0; } } } /* * Verify a sigature. The nonce has size NONCELEN bytes. sigbuf[] * (of size sigbuflen) contains the signature value, not including the * header byte or nonce. Return value is 0 on success, -1 on error. */ static int do_verify( const uint8_t *nonce, const uint8_t *sigbuf, size_t sigbuflen, const uint8_t *m, size_t mlen, const uint8_t *pk) { union { uint8_t b[2 * 512]; uint64_t dummy_u64; fpr dummy_fpr; } tmp; uint16_t h[512], hm[512]; int16_t sig[512]; inner_shake256_context sc; /* * Decode public key. */ if (pk[0] != 0x00 + 9) { return -1; } if (PQCLEAN_FALCON512_CLEAN_modq_decode(h, 9, pk + 1, PQCLEAN_FALCON512_CLEAN_CRYPTO_PUBLICKEYBYTES - 1) != PQCLEAN_FALCON512_CLEAN_CRYPTO_PUBLICKEYBYTES - 1) { return -1; } PQCLEAN_FALCON512_CLEAN_to_ntt_monty(h, 9); /* * Decode signature. */ if (sigbuflen == 0) { return -1; } if (PQCLEAN_FALCON512_CLEAN_comp_decode(sig, 9, sigbuf, sigbuflen) != sigbuflen) { return -1; } /* * Hash nonce + message into a vector. */ inner_shake256_init(&sc); inner_shake256_inject(&sc, nonce, NONCELEN); inner_shake256_inject(&sc, m, mlen); inner_shake256_flip(&sc); PQCLEAN_FALCON512_CLEAN_hash_to_point_ct(&sc, hm, 9, tmp.b); inner_shake256_ctx_release(&sc); /* * Verify signature. */ if (!PQCLEAN_FALCON512_CLEAN_verify_raw(hm, sig, h, 9, tmp.b)) { return -1; } return 0; } /* see api.h */ int PQCLEAN_FALCON512_CLEAN_crypto_sign_signature( uint8_t *sig, size_t *siglen, const uint8_t *m, size_t mlen, const uint8_t *sk) { /* * The PQCLEAN_FALCON512_CLEAN_CRYPTO_BYTES constant is used for * the signed message object (as produced by PQCLEAN_FALCON512_CLEAN_crypto_sign()) * and includes a two-byte length value, so we take care here * to only generate signatures that are two bytes shorter than * the maximum. This is done to ensure that PQCLEAN_FALCON512_CLEAN_crypto_sign() * and PQCLEAN_FALCON512_CLEAN_crypto_sign_signature() produce the exact same signature * value, if used on the same message, with the same private key, * and using the same output from randombytes() (this is for * reproducibility of tests). */ size_t vlen; vlen = PQCLEAN_FALCON512_CLEAN_CRYPTO_BYTES - NONCELEN - 3; if (do_sign(sig + 1, sig + 1 + NONCELEN, &vlen, m, mlen, sk) < 0) { return -1; } sig[0] = 0x30 + 9; *siglen = 1 + NONCELEN + vlen; return 0; } /* see api.h */ int PQCLEAN_FALCON512_CLEAN_crypto_sign_verify( const uint8_t *sig, size_t siglen, const uint8_t *m, size_t mlen, const uint8_t *pk) { if (siglen < 1 + NONCELEN) { return -1; } if (sig[0] != 0x30 + 9) { return -1; } return do_verify(sig + 1, sig + 1 + NONCELEN, siglen - 1 - NONCELEN, m, mlen, pk); } /* see api.h */ int PQCLEAN_FALCON512_CLEAN_crypto_sign( uint8_t *sm, size_t *smlen, const uint8_t *m, size_t mlen, const uint8_t *sk) { uint8_t *pm, *sigbuf; size_t sigbuflen; /* * Move the message to its final location; this is a memmove() so * it handles overlaps properly. */ memmove(sm + 2 + NONCELEN, m, mlen); pm = sm + 2 + NONCELEN; sigbuf = pm + 1 + mlen; sigbuflen = PQCLEAN_FALCON512_CLEAN_CRYPTO_BYTES - NONCELEN - 3; if (do_sign(sm + 2, sigbuf, &sigbuflen, pm, mlen, sk) < 0) { return -1; } pm[mlen] = 0x20 + 9; sigbuflen ++; sm[0] = (uint8_t)(sigbuflen >> 8); sm[1] = (uint8_t)sigbuflen; *smlen = mlen + 2 + NONCELEN + sigbuflen; return 0; } /* see api.h */ int PQCLEAN_FALCON512_CLEAN_crypto_sign_open( uint8_t *m, size_t *mlen, const uint8_t *sm, size_t smlen, const uint8_t *pk) { const uint8_t *sigbuf; size_t pmlen, sigbuflen; if (smlen < 3 + NONCELEN) { return -1; } sigbuflen = ((size_t)sm[0] << 8) | (size_t)sm[1]; if (sigbuflen < 2 || sigbuflen > (smlen - NONCELEN - 2)) { return -1; } sigbuflen --; pmlen = smlen - NONCELEN - 3 - sigbuflen; if (sm[2 + NONCELEN + pmlen] != 0x20 + 9) { return -1; } sigbuf = sm + 2 + NONCELEN + pmlen + 1; /* * The 2-byte length header and the one-byte signature header * have been verified. Nonce is at sm+2, followed by the message * itself. Message length is in pmlen. sigbuf/sigbuflen point to * the signature value (excluding the header byte). */ if (do_verify(sm + 2, sigbuf, sigbuflen, sm + 2 + NONCELEN, pmlen, pk) < 0) { return -1; } /* * Signature is correct, we just have to copy/move the message * to its final destination. The memmove() properly handles * overlaps. */ memmove(m, sm + 2 + NONCELEN, pmlen); *mlen = pmlen; return 0; }
28.396373
102
0.608612
Cryptario
ff564dbfe66e096e358331bd69b90c2d9ea14bf8
9,796
cpp
C++
McEngine/src/GUI/CBaseUISlider.cpp
musikowskipawel/McEngine
fcd96ecf1d04a6b44545ea06b7531e8816e61368
[ "MIT" ]
73
2016-09-12T09:55:53.000Z
2022-03-26T22:18:35.000Z
McEngine/src/GUI/CBaseUISlider.cpp
musikowskipawel/McEngine
fcd96ecf1d04a6b44545ea06b7531e8816e61368
[ "MIT" ]
31
2016-08-08T18:05:33.000Z
2022-03-10T09:27:33.000Z
McEngine/src/GUI/CBaseUISlider.cpp
musikowskipawel/McEngine
fcd96ecf1d04a6b44545ea06b7531e8816e61368
[ "MIT" ]
17
2016-11-19T15:15:11.000Z
2022-02-24T11:07:22.000Z
//================ Copyright (c) 2012, PG, All rights reserved. =================// // // Purpose: a simple slider // // $NoKeywords: $ //===============================================================================// #include "CBaseUISlider.h" #include "Engine.h" #include "Mouse.h" #include "AnimationHandler.h" #include "Keyboard.h" CBaseUISlider::CBaseUISlider(float xPos, float yPos, float xSize, float ySize, UString name) : CBaseUIElement(xPos,yPos,xSize,ySize,name) { m_bDrawFrame = true; m_bDrawBackground = true; m_bHorizontal = false; m_bHasChanged = false; m_bAnimated = true; m_bLiveUpdate = false; m_bAllowMouseWheel = true; m_backgroundColor = COLOR(255, 0, 0, 0); m_frameColor = COLOR(255,255,255,255); m_fCurValue = 0.0f; m_fCurPercent = 0.0f; m_fMinValue = 0.0f; m_fMaxValue = 1.0f; m_fKeyDelta = 0.1f; m_vBlockSize = Vector2(xSize < ySize ? xSize : ySize, xSize < ySize ? xSize : ySize); m_sliderChangeCallback = NULL; setOrientation(xSize > ySize); } void CBaseUISlider::draw(Graphics *g) { if (!m_bVisible) return; // draw background if (m_bDrawBackground) { g->setColor(m_backgroundColor); g->fillRect(m_vPos.x, m_vPos.y, m_vSize.x, m_vSize.y + 1); } // draw frame g->setColor(m_frameColor); if (m_bDrawFrame) g->drawRect(m_vPos.x, m_vPos.y, m_vSize.x, m_vSize.y + 1); // draw sliding line if (!m_bHorizontal) g->drawLine(m_vPos.x + m_vSize.x/2.0f, m_vPos.y + m_vBlockSize.y/2.0, m_vPos.x + m_vSize.x/2.0f, m_vPos.y + m_vSize.y - m_vBlockSize.y/2.0f); else g->drawLine(m_vPos.x + (m_vBlockSize.x-1)/2 + 1, m_vPos.y + m_vSize.y/2.0f + 1, m_vPos.x + m_vSize.x - (m_vBlockSize.x-1)/2, m_vPos.y + m_vSize.y/2.0f + 1); drawBlock(g); } void CBaseUISlider::drawBlock(Graphics *g) { // draw block Vector2 center = m_vPos + Vector2(m_vBlockSize.x/2 + (m_vSize.x-m_vBlockSize.x)*getPercent(), m_vSize.y/2); Vector2 topLeft = center - m_vBlockSize/2; Vector2 topRight = center + Vector2(m_vBlockSize.x/2 + 1, -m_vBlockSize.y/2); Vector2 halfLeft = center + Vector2(-m_vBlockSize.x/2, 1); Vector2 halfRight = center + Vector2(m_vBlockSize.x/2 + 1, 1); Vector2 bottomLeft = center + Vector2(-m_vBlockSize.x/2, m_vBlockSize.y/2 + 1); Vector2 bottomRight = center + Vector2(m_vBlockSize.x/2 + 1, m_vBlockSize.y/2 + 1); g->drawQuad(topLeft, topRight, halfRight + Vector2(0,1), halfLeft + Vector2(0,1), COLOR(255,255,255,255), COLOR(255,255,255,255), COLOR(255,241,241,241), COLOR(255,241,241,241)); g->drawQuad(halfLeft, halfRight, bottomRight, bottomLeft, COLOR(255,225,225,225), COLOR(255,225,225,225), COLOR(255,255,255,255), COLOR(255,255,255,255)); /* g->drawQuad(Vector2(m_vPos.x+std::round(m_vBlockPos.x)+1, m_vPos.y+std::round(m_vBlockPos.y)+1), Vector2(m_vPos.x+std::round(m_vBlockPos.x)+1 + m_vBlockSize.x-1, m_vPos.y+std::round(m_vBlockPos.y)+1), Vector2(m_vPos.x+std::round(m_vBlockPos.x)+1 + m_vBlockSize.x-1, m_vPos.y+std::round(m_vBlockPos.y)+1 + m_vBlockSize.y/2), Vector2(m_vPos.x+std::round(m_vBlockPos.x)+1, m_vPos.y+std::round(m_vBlockPos.y)+1 + m_vBlockSize.y/2), COLOR(255,255,255,255), COLOR(255,255,255,255), COLOR(255,241,241,241), COLOR(255,241,241,241)); g->drawQuad(Vector2(m_vPos.x+std::round(m_vBlockPos.x)+1, m_vPos.y+std::round(m_vBlockPos.y)+1+std::round(m_vBlockSize.y/2.0f)), Vector2(m_vPos.x+std::round(m_vBlockPos.x)+1 + m_vBlockSize.x-1, m_vPos.y+std::round(m_vBlockPos.y)+1+std::round(m_vBlockSize.y/2.0f)), Vector2(m_vPos.x+std::round(m_vBlockPos.x)+1 + m_vBlockSize.x-1, m_vPos.y+std::round(m_vBlockPos.y)+1+std::round(m_vBlockSize.y/2.0f) + m_vBlockSize.y-(std::round(m_vBlockSize.y/2.0f))), Vector2(m_vPos.x+std::round(m_vBlockPos.x)+1, m_vPos.y+std::round(m_vBlockPos.y)+1+std::round(m_vBlockSize.y/2.0f) + m_vBlockSize.y-(std::round(m_vBlockSize.y/2.0f))), COLOR(255,225,225,225), COLOR(255,225,225,225), COLOR(255,255,255,255), COLOR(255,255,255,255)); */ /* g->setColor(0xff00ff00); g->fillRect(m_vPos.x+m_vBlockPos.x+1, m_vPos.y+m_vBlockPos.y+1, m_vBlockSize.x-1, m_vBlockSize.y); */ } void CBaseUISlider::update() { CBaseUIElement::update(); if (!m_bVisible) return; Vector2 mousepos = engine->getMouse()->getPos(); // handle moving if (m_bActive) { // calculate new values if (!m_bHorizontal) { if (m_bAnimated) anim->moveQuadOut( &m_vBlockPos.y, clamp<float>( mousepos.y - m_vGrabBackup.y, 0.0f, m_vSize.y-m_vBlockSize.y ), 0.10f, 0, true ); else m_vBlockPos.y = clamp<float>( mousepos.y - m_vGrabBackup.y, 0.0f, m_vSize.y-m_vBlockSize.y ); m_fCurPercent = clamp<float>(1.0f - (std::round(m_vBlockPos.y) / (m_vSize.y-m_vBlockSize.y)), 0.0f, 1.0f); } else { if (m_bAnimated) anim->moveQuadOut( &m_vBlockPos.x, clamp<float>( mousepos.x - m_vGrabBackup.x, 0.0f, m_vSize.x-m_vBlockSize.x ), 0.10f, 0, true ); else m_vBlockPos.x = clamp<float>( mousepos.x - m_vGrabBackup.x, 0.0f, m_vSize.x-m_vBlockSize.x ); m_fCurPercent = clamp<float>(std::round(m_vBlockPos.x) / (m_vSize.x-m_vBlockSize.x), 0.0f, 1.0f); } // set new value if (m_bAnimated) { if (m_bLiveUpdate) setValue(lerp<float>(m_fMinValue, m_fMaxValue, m_fCurPercent), false); else m_fCurValue = lerp<float>(m_fMinValue, m_fMaxValue, m_fCurPercent); } else setValue(lerp<float>(m_fMinValue, m_fMaxValue, m_fCurPercent), false); m_bHasChanged = true; } else { // handle mouse wheel if (m_bMouseInside && m_bAllowMouseWheel) { int wheelDelta = engine->getMouse()->getWheelDeltaVertical(); if (wheelDelta != 0) { const int multiplier = std::max(1, std::abs(wheelDelta) / 120); if (wheelDelta > 0) setValue(m_fCurValue + m_fKeyDelta*multiplier, m_bAnimated); else setValue(m_fCurValue - m_fKeyDelta*multiplier, m_bAnimated); } } } // handle animation value settings after mouse release if (!m_bActive) { if (anim->isAnimating( &m_vBlockPos.x )) { m_fCurPercent = clamp<float>(std::round(m_vBlockPos.x) / (m_vSize.x-m_vBlockSize.x), 0.0f, 1.0f); if (m_bLiveUpdate) setValue(lerp<float>(m_fMinValue, m_fMaxValue, m_fCurPercent), false); else m_fCurValue = lerp<float>(m_fMinValue, m_fMaxValue, m_fCurPercent); } if (anim->isAnimating( &m_vBlockPos.y )) { m_fCurPercent = clamp<float>(1.0f - (std::round(m_vBlockPos.y) / (m_vSize.y-m_vBlockSize.y)), 0.0f, 1.0f); if (m_bLiveUpdate) setValue(lerp<float>(m_fMinValue, m_fMaxValue, m_fCurPercent), false); else m_fCurValue = lerp<float>(m_fMinValue, m_fMaxValue, m_fCurPercent); } } } void CBaseUISlider::onKeyDown(KeyboardEvent &e) { if (!m_bVisible) return; if (isMouseInside()) { if (e == KEY_LEFT) { setValue(getFloat() - m_fKeyDelta, false); e.consume(); } else if (e == KEY_RIGHT) { setValue(getFloat() + m_fKeyDelta, false); e.consume(); } } } void CBaseUISlider::fireChangeCallback() { if (m_sliderChangeCallback != NULL) m_sliderChangeCallback(this); } void CBaseUISlider::updateBlockPos() { if (!m_bHorizontal) m_vBlockPos.x = m_vSize.x/2.0f - m_vBlockSize.x/2.0f; else m_vBlockPos.y = m_vSize.y/2.0f - m_vBlockSize.y/2.0f; } CBaseUISlider *CBaseUISlider::setBounds(float minValue, float maxValue) { m_fMinValue = minValue; m_fMaxValue = maxValue; m_fKeyDelta = (m_fMaxValue - m_fMinValue) / 10.0f; return this; } CBaseUISlider *CBaseUISlider::setValue(float value, bool animate) { bool changeCallbackCheck = false; if (value != m_fCurValue) { changeCallbackCheck = true; m_bHasChanged = true; } m_fCurValue = clamp<float>(value, m_fMinValue, m_fMaxValue); float percent = getPercent(); if (!m_bHorizontal) { if (animate) anim->moveQuadOut( &m_vBlockPos.y, (m_vSize.y-m_vBlockSize.y)*(1.0f-percent), 0.2f, 0, true ); else m_vBlockPos.y = (m_vSize.y-m_vBlockSize.y)*(1.0f-percent); } else { if (animate) anim->moveQuadOut( &m_vBlockPos.x, (m_vSize.x-m_vBlockSize.x)*percent, 0.2f, 0, true ); else m_vBlockPos.x = (m_vSize.x-m_vBlockSize.x)*percent; } if (changeCallbackCheck && m_sliderChangeCallback != NULL) m_sliderChangeCallback(this); updateBlockPos(); return this; } CBaseUISlider *CBaseUISlider::setInitialValue(float value) { m_fCurValue = clamp<float>(value, m_fMinValue, m_fMaxValue); float percent = getPercent(); if (m_fCurValue == m_fMaxValue) percent = 1.0f; if (!m_bHorizontal) m_vBlockPos.y = (m_vSize.y-m_vBlockSize.y)*(1.0f-percent); else m_vBlockPos.x = (m_vSize.x-m_vBlockSize.x)*percent; updateBlockPos(); return this; } void CBaseUISlider::setBlockSize(float xSize, float ySize) { m_vBlockSize = Vector2(xSize, ySize); } float CBaseUISlider::getPercent() { return clamp<float>((m_fCurValue-m_fMinValue) / (std::abs(m_fMaxValue-m_fMinValue)), 0.0f, 1.0f); } bool CBaseUISlider::hasChanged() { if (anim->isAnimating(&m_vBlockPos.x)) return true; if (m_bHasChanged) { m_bHasChanged = false; return true; } return false; } void CBaseUISlider::onFocusStolen() { m_bBusy = false; } void CBaseUISlider::onMouseUpInside() { m_bBusy = false; if (m_fCurValue != m_fPrevValue && m_sliderChangeCallback != NULL) m_sliderChangeCallback(this); } void CBaseUISlider::onMouseUpOutside() { m_bBusy = false; if (m_fCurValue != m_fPrevValue && m_sliderChangeCallback != NULL) m_sliderChangeCallback(this); } void CBaseUISlider::onMouseDownInside() { m_fPrevValue = m_fCurValue; if (McRect(m_vPos.x+m_vBlockPos.x,m_vPos.y+m_vBlockPos.y,m_vBlockSize.x,m_vBlockSize.y).contains(engine->getMouse()->getPos())) m_vGrabBackup = engine->getMouse()->getPos()-m_vBlockPos; else m_vGrabBackup = m_vPos + m_vBlockSize/2; m_bBusy = true; } void CBaseUISlider::onResized() { setValue(getFloat(), false); }
26.986226
190
0.686607
musikowskipawel
ff59c1a8f1690e09839ef3ba85690fad6ee64446
1,673
cpp
C++
src/authgeneratorbtns.cpp
OpenIKEv2/libopenikev2_impl
3c620ca479b20814fe42325cffcfd1d18dbf041c
[ "Apache-2.0" ]
3
2017-03-03T17:05:37.000Z
2020-06-16T04:50:40.000Z
src/authgeneratorbtns.cpp
OpenIKEv2/libopenikev2_impl
3c620ca479b20814fe42325cffcfd1d18dbf041c
[ "Apache-2.0" ]
11
2017-02-27T09:31:17.000Z
2020-03-20T16:31:05.000Z
src/authgeneratorbtns.cpp
OpenIKEv2/libopenikev2_impl
3c620ca479b20814fe42325cffcfd1d18dbf041c
[ "Apache-2.0" ]
null
null
null
/*************************************************************************** * Copyright (C) 2005 by * * Alejandro Perez Mendez [email protected] * * Pedro J. Fernandez Ruiz [email protected] * * * * This software may be modified and distributed under the terms * * of the Apache license. See the LICENSE file for details. * ***************************************************************************/ #include "authgeneratorbtns.h" namespace openikev2 { AuthGeneratorBtns::AuthGeneratorBtns( ) {} AuthGeneratorBtns::~AuthGeneratorBtns( ) {} auto_ptr< AuthGenerator > AuthGeneratorBtns::clone() const { return auto_ptr<AuthGenerator> ( new AuthGeneratorBtns( ) ); } auto_ptr< Payload_AUTH > AuthGeneratorBtns::generateAuthPayload( const IkeSa& ike_sa ) { auto_ptr<ByteArray> auth_field (new ByteArray ("BTNS", 4) ); return auto_ptr<Payload_AUTH> ( new Payload_AUTH( (Enums::AUTH_METHOD) 201, auth_field ) ); } AutoVector<Payload_CERT> AuthGeneratorBtns::generateCertificatePayloads( const IkeSa& ike_sa, const vector< Payload_CERT_REQ * > payload_cert_req_r ) { AutoVector<Payload_CERT> result; return result; } string AuthGeneratorBtns::toStringTab( uint8_t tabs ) const { ostringstream oss; oss << Printable::generateTabs( tabs ) << "<AUTH_GENERATOR_BTNS> {\n"; oss << Printable::generateTabs( tabs ) << "}\n"; return oss.str(); } }
39.833333
155
0.528392
OpenIKEv2
ff5b7908f992d93dddef5743d47248d55e6f19f8
1,515
cpp
C++
vulkan/ShaderStorageBuffer.cpp
enjiushi/VulkanLearn
29fb429a3fb526f8de7406404a983685a7e87117
[ "MIT" ]
272
2019-06-27T12:21:49.000Z
2022-03-23T07:18:33.000Z
vulkan/ShaderStorageBuffer.cpp
enjiushi/VulkanLearn
29fb429a3fb526f8de7406404a983685a7e87117
[ "MIT" ]
9
2019-08-11T13:07:01.000Z
2022-01-26T12:30:24.000Z
vulkan/ShaderStorageBuffer.cpp
enjiushi/VulkanLearn
29fb429a3fb526f8de7406404a983685a7e87117
[ "MIT" ]
16
2019-09-29T01:41:02.000Z
2022-03-29T15:51:35.000Z
#include "ShaderStorageBuffer.h" #include "GlobalDeviceObjects.h" bool ShaderStorageBuffer::Init(const std::shared_ptr<Device>& pDevice, const std::shared_ptr<ShaderStorageBuffer>& pSelf, uint32_t numBytes) { VkBufferCreateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; uint32_t minAlign = (uint32_t)GetPhysicalDevice()->GetPhysicalDeviceProperties().limits.minStorageBufferOffsetAlignment; uint32_t totalUniformBytes = numBytes / minAlign * minAlign + (numBytes % minAlign > 0 ? minAlign : 0); info.size = totalUniformBytes; if (!SharedBuffer::Init(pDevice, pSelf, info)) return false; // FIXME: add them back when necessary m_accessStages = VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | //VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT | //VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT | //VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; m_accessFlags = VK_ACCESS_SHADER_READ_BIT; return true; } std::shared_ptr<ShaderStorageBuffer> ShaderStorageBuffer::Create(const std::shared_ptr<Device>& pDevice, uint32_t numBytes) { std::shared_ptr<ShaderStorageBuffer> pSSBO = std::make_shared<ShaderStorageBuffer>(); if (pSSBO.get() && pSSBO->Init(pDevice, pSSBO, numBytes)) return pSSBO; return nullptr; } std::shared_ptr<BufferKey> ShaderStorageBuffer::AcquireBuffer(uint32_t numBytes) { return ShaderStorageBufferMgr()->AllocateBuffer(numBytes); }
37.875
140
0.805281
enjiushi
ff60de0ac0520b62f5f68e07b1ee4b29728e0af1
6,500
cc
C++
mmap/testing/node_page_test.cc
datacratic/DasDB
5ccc1fc7c6c69c97e3dae0e02bb4009f95908d3b
[ "Apache-2.0" ]
3
2017-12-06T00:25:52.000Z
2021-08-24T20:46:54.000Z
mmap/testing/node_page_test.cc
datacratic/DasDB
5ccc1fc7c6c69c97e3dae0e02bb4009f95908d3b
[ "Apache-2.0" ]
null
null
null
mmap/testing/node_page_test.cc
datacratic/DasDB
5ccc1fc7c6c69c97e3dae0e02bb4009f95908d3b
[ "Apache-2.0" ]
1
2016-11-24T17:14:16.000Z
2016-11-24T17:14:16.000Z
/* node_page_test.cc Rémi Attab, 20 January 2012 Copyright (c) 2012 Datacratic. All rights reserved. Tests for node_page.h */ #define BOOST_TEST_MAIN #define BOOST_TEST_DYN_LINK #include "mmap/node_page.h" #include "soa/utils/threaded_test.h" #include <boost/test/unit_test.hpp> #include <iostream> #include <thread> #include <future> #include <stack> #include <array> using namespace std; using namespace boost; using namespace Datacratic; using namespace Datacratic::MMap; using namespace ML; // Testing utilities used in both para and seq tests. template <uint32_t size> struct TestUtil { typedef GenericNodePage<size> NodeT; static void checkEmpty (NodeT& nodes) { BOOST_REQUIRE_EQUAL(nodes.metadata.magic, NodeT::magicNum); BOOST_REQUIRE_EQUAL( nodes.metadata.full.numFull(), NodeT::metadataNodes); } static void checkSize () { //Not all NodePages uses the full Page if (sizeof(NodeT) >= page_size-size && sizeof(NodeT) <= page_size) return; cerr << "sizeof(GenericNodePage<" << size << ">)=" << sizeof(NodeT) << endl; cerr << "{ numNodes = " << NodeT::numNodes << ", sizeof(FullBitmap) = " << sizeof(FullBitmap<NodeT::numNodes>) << ", metadataSize = " << NodeT::metadataSize << ", metadataNodes = " << NodeT::metadataNodes << ", metadataPadding = " << NodeT::metadataPadding << "}" << endl; BOOST_REQUIRE(sizeof(NodeT) == page_size); } }; // Test various behaviours when allocating and deallocating in a sequential test template<uint32_t size> struct SequentialTest { static void exec () { typedef GenericNodePage<size> NodeT; NodeT nodes; nodes.init(); int64_t offset; bool needUpdate; TestUtil<size>::checkSize(); for (int k = 0; k < 3; ++k) { // Exceptions are thrown but it pollutes the console output so disable it. #if 0 // Try deallocating metadata nodes for (int i = 0; i < NodeT::metadataNodes; ++i) { BOOST_CHECK_THROW( nodes.deallocate(i*size), ML::Assertion_Failure); } #endif // Fully allocate the page. for (int i = NodeT::metadataNodes; i < NodeT::numNodes; ++i) { tie(offset, needUpdate) = nodes.allocate(); BOOST_REQUIRE_EQUAL(needUpdate, i == NodeT::numNodes-1); BOOST_REQUIRE_EQUAL(offset, i*size); } // Over allocate the page. for(int i = 0; i < 3; ++i) { tie(offset, needUpdate) = nodes.allocate(); BOOST_REQUIRE_LE(offset, -1); } // De-allocate and reallocate a random node. int64_t newOffset = (NodeT::numNodes/2) * size; needUpdate = nodes.deallocate(newOffset); BOOST_REQUIRE_EQUAL(needUpdate, true); tie(offset, needUpdate) = nodes.allocate(); BOOST_REQUIRE_EQUAL(needUpdate, true); BOOST_REQUIRE_EQUAL(offset, newOffset); // Fully de-allocate the page. for (int i = NodeT::metadataNodes; i < NodeT::numNodes; ++i) { bool needUpdate = nodes.deallocate(i*size); BOOST_REQUIRE_EQUAL(needUpdate, i == NodeT::metadataNodes); } // Exceptions are thrown but it pollutes the console output so disable it. #if 0 // Over de-allocate the page for (int i = NodeT::metadataNodes; i < NodeT::numNodes; ++i) { BOOST_CHECK_THROW(nodes.deallocate(i*size), ML::Exception); } #endif // Make sure everything is properly deallocated. TestUtil<size>::checkEmpty(nodes); } } }; BOOST_AUTO_TEST_CASE(test_seq) { SequentialTest<8>::exec(); SequentialTest<12>::exec(); SequentialTest<32>::exec(); SequentialTest<64>::exec(); SequentialTest<96>::exec(); SequentialTest<192>::exec(); SequentialTest<256>::exec(); } // Starts a truck load of tests that randomly allocates and frees nodes. template<uint32_t size> struct ParallelTest { enum { threadCount = 4, iterationCount = 10000 }; typedef GenericNodePage<size> NodeT; NodeT nodes; bool allocateNode (stack<int64_t>& s) { int64_t offset = nodes.allocate().first; if (offset >= 0) { s.push(offset); return true; } return false; } void deallocateHead(stack<int64_t>& s) { nodes.deallocate(s.top()); s.pop(); } void runThread (int id) { mt19937 engine(id); uniform_int_distribution<int> opDist(0, 1); uniform_int_distribution<int> numDist(0, size); stack<int64_t> allocatedOffsets; for (int i = 0; i < iterationCount; ++i) { if (allocatedOffsets.empty()) { if (!allocateNode(allocatedOffsets)) { // nothing to allocate or deallocate, // take a nap and try again. std::this_thread::yield(); } continue; } else if (opDist(engine) && allocateNode(allocatedOffsets)) { for (int j = numDist(engine); j > 0; --j) { if (!allocateNode(allocatedOffsets)) { break; } } continue; } // De-allocate if space is full or we're randomly chosen. for (int j = numDist(engine); !allocatedOffsets.empty() && j > 0; --j) { deallocateHead(allocatedOffsets); } } // We're done, cleanup. while (!allocatedOffsets.empty()) { deallocateHead(allocatedOffsets); } } void exec() { nodes.init(); auto runFn = [&] (int id) { this->runThread(id); return 0; }; ThreadedTest test; test.start(runFn, threadCount); test.joinAll(10000); // Make sure everything is properly deallocated. TestUtil<size>::checkEmpty(nodes); } }; BOOST_AUTO_TEST_CASE(test_para) { ParallelTest<8>().exec(); ParallelTest<48>().exec(); ParallelTest<64>().exec(); ParallelTest<192>().exec(); ParallelTest<256>().exec(); }
28.508772
80
0.560308
datacratic
ff64b5db8c46c9154066d0808fae5094566deab9
335
cpp
C++
Backtrack/recur/AddN.cpp
Twinkle0799/Competitive_Programming_Rocks
fb71021e02019004bef59ee1df86687234e36f5a
[ "MIT" ]
2
2021-05-06T17:59:44.000Z
2021-08-04T12:50:38.000Z
Backtrack/recur/AddN.cpp
Twinkle0799/Competitive_Programming_Rocks
fb71021e02019004bef59ee1df86687234e36f5a
[ "MIT" ]
1
2022-01-14T19:58:34.000Z
2022-01-14T19:58:34.000Z
Backtrack/recur/AddN.cpp
Twinkle0799/Competitive_Programming_Rocks
fb71021e02019004bef59ee1df86687234e36f5a
[ "MIT" ]
1
2021-02-17T09:48:06.000Z
2021-02-17T09:48:06.000Z
#include<bits/stdc++.h> using namespace std; int AddN(int n) { if(n==0) { return 0; } int presum = AddN(n-1); return n + presum; } int main() { #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); #endif int n; cin>>n; cout<<AddN(n); return 0; }
12.884615
39
0.540299
Twinkle0799
ff65e6f12c981871c143635bc4f2658d4463410b
1,338
cpp
C++
src/kindyn/src/controller/cardsflow_command_interface.cpp
NexusReflex/VRpuppet
0b6a14e13951ceaf849b09da1f8dd797a4a1125d
[ "BSD-3-Clause" ]
3
2018-11-12T09:58:35.000Z
2019-03-31T02:52:54.000Z
src/kindyn/src/controller/cardsflow_command_interface.cpp
NexusReflex/VRpuppet
0b6a14e13951ceaf849b09da1f8dd797a4a1125d
[ "BSD-3-Clause" ]
5
2018-12-02T14:31:10.000Z
2021-05-06T12:10:06.000Z
src/kindyn/src/controller/cardsflow_command_interface.cpp
NexusReflex/VRpuppet
0b6a14e13951ceaf849b09da1f8dd797a4a1125d
[ "BSD-3-Clause" ]
3
2018-12-02T09:55:49.000Z
2021-09-08T11:54:30.000Z
#include "kindyn/controller/cardsflow_command_interface.hpp" namespace hardware_interface { CardsflowHandle::CardsflowHandle() : CardsflowStateHandle(){} /** * @param js This joint's state handle * @param cmd A pointer to the storage for this joint's output command */ CardsflowHandle::CardsflowHandle(const CardsflowStateHandle& js, double* joint_position_cmd, double* joint_velocity_cmd, double* joint_torque_cmd, VectorXd *motor_cmd) : CardsflowStateHandle(js), joint_position_cmd_(joint_position_cmd), joint_velocity_cmd_(joint_velocity_cmd), joint_torque_cmd_(joint_torque_cmd), motor_cmd_(motor_cmd) { } void CardsflowHandle::setMotorCommand(VectorXd command) {*motor_cmd_ = command;} double CardsflowHandle::getJointPositionCommand() const {return *joint_position_cmd_;} double CardsflowHandle::getJointVelocityCommand() const {return *joint_velocity_cmd_;} double CardsflowHandle::getJointTorqueCommand() const {return *joint_torque_cmd_;} void CardsflowHandle::setJointPositionCommand(double cmd){*joint_position_cmd_ = cmd;} void CardsflowHandle::setJointVelocityCommand(double cmd){*joint_velocity_cmd_ = cmd;} void CardsflowHandle::setJointTorqueCommand(double cmd){*joint_torque_cmd_ = cmd;} }
47.785714
121
0.749626
NexusReflex
ff686f28f5f10d347265bafa78b8228312d0974d
151
cpp
C++
test.cpp
yusukeOteki/pxt-test1
a5bb45d48c8c4a8096579d39c2134b953a773846
[ "MIT" ]
null
null
null
test.cpp
yusukeOteki/pxt-test1
a5bb45d48c8c4a8096579d39c2134b953a773846
[ "MIT" ]
null
null
null
test.cpp
yusukeOteki/pxt-test1
a5bb45d48c8c4a8096579d39c2134b953a773846
[ "MIT" ]
null
null
null
#include "pxt.h" using namespace pxt; namespace test { //% void dammy(int32_t x, int32_t y){ uBit.display.image.setPixelValue(0, 0, 255); } }
11.615385
46
0.662252
yusukeOteki
ff6ace1c0415f19b1777f3b561a5501b5f51b9f8
2,204
cpp
C++
00-Keypoint_in_WangDao/Chapter_02-List/01-LinkList/00-Basic_LinkList/01-LinkList_Examples/02-LinkList_Seprate_by_Char_Type.cpp
ysl970629/kaoyan_data_structure
d0a469bf0e9e7040de21eca38dc19961aa7e9a53
[ "MIT" ]
2
2021-03-24T03:29:16.000Z
2022-03-29T16:34:30.000Z
00-Keypoint_in_WangDao/Chapter_02-List/01-LinkList/00-Basic_LinkList/01-LinkList_Examples/02-LinkList_Seprate_by_Char_Type.cpp
ysl2/kaoyan-data-structure
d0a469bf0e9e7040de21eca38dc19961aa7e9a53
[ "MIT" ]
null
null
null
00-Keypoint_in_WangDao/Chapter_02-List/01-LinkList/00-Basic_LinkList/01-LinkList_Examples/02-LinkList_Seprate_by_Char_Type.cpp
ysl2/kaoyan-data-structure
d0a469bf0e9e7040de21eca38dc19961aa7e9a53
[ "MIT" ]
null
null
null
#include <cstdlib> #include <iostream> typedef int ElemType; typedef struct LinkNode { ElemType data; struct LinkNode *next; } LinkNode, *LinkList; void outPut(LinkList L) { LinkNode *p = L->next; while (p != NULL) { std::cout << p->data << " "; p = p->next; } std::cout << std::endl; } void rearInsert(LinkList &L, ElemType x) { LinkNode *s = new LinkNode; s->data = x; L->next = s; L = s; } void rearInsertCreate(LinkList &L, ElemType arr[], int length) { L = new LinkNode; LinkNode *p = L; for (int i = 0; i < length; i++) { rearInsert(p, arr[i]); } p->next = NULL; } // 题目要求根据大写、小写和数字分类,这样我还得重新定义char类型的链表,太麻烦了 // 所以我按照大写、小写、数字的ASCII码范围来分类,这样都能保证是int型 // 数字:48 ~ 57,放在A里 // 大写:65 ~ 90,放在B里 // 小写:97 ~ 122,放在C里 void SeprateByCharType(LinkList &A, LinkList &B, LinkList &C) { LinkNode *pre = A; LinkNode *p = A->next; B = new LinkNode; LinkNode *q = B; C = new LinkNode; LinkNode *r = C; while (p != NULL) { // 放在A里 if (p->data >= 48 && p->data <= 57) { p = p->next; pre = pre->next; continue; //终止当前这次循环,直接进入下一次循环 } // 放在B里 if (p->data >= 65 && p->data <= 90) { rearInsert(q, p->data); // 在A中删除p所指的位置,然后把p定位到下一个位置 pre->next = p->next; delete p; p = pre->next; continue; } // 放在C里 if (p->data >= 97 && p->data <= 122) { rearInsert(r, p->data); pre->next = p->next; delete p; p = pre->next; // 这里就不用加continue了,因为下面已经没有语句了,肯定会执行下一次循环 } } q->next = NULL; r->next = NULL; } int main() { ElemType arr[] = {49, 66, 98, 50, 67, 99, 51, 68, 100, 52, 69, 101}; int length = sizeof(arr) / sizeof(int); LinkList L1 = NULL; LinkList L2 = NULL; LinkList L3 = NULL; rearInsertCreate(L1, arr, length); outPut(L1); SeprateByCharType(L1, L2, L3); outPut(L1); outPut(L2); outPut(L3); return 0; } // 输出结果: // 49 66 98 50 67 99 51 68 100 52 69 101 // 49 50 51 52 // 66 67 68 69 // 98 99 100 101
22.04
72
0.511343
ysl970629