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
6183d7e0f10638ed0f108e7028832da1b0eb4f3d
438
hpp
C++
src/stan/lang/ast/node/statements_def.hpp
ludkinm/stan
c318114f875266f22c98cf0bebfff928653727cb
[ "CC-BY-3.0", "BSD-3-Clause" ]
null
null
null
src/stan/lang/ast/node/statements_def.hpp
ludkinm/stan
c318114f875266f22c98cf0bebfff928653727cb
[ "CC-BY-3.0", "BSD-3-Clause" ]
null
null
null
src/stan/lang/ast/node/statements_def.hpp
ludkinm/stan
c318114f875266f22c98cf0bebfff928653727cb
[ "CC-BY-3.0", "BSD-3-Clause" ]
null
null
null
#ifndef STAN_LANG_AST_NODE_STATEMENTS_DEF_HPP #define STAN_LANG_AST_NODE_STATEMENTS_DEF_HPP #include <stan/lang/ast.hpp> #include <vector> namespace stan { namespace lang { statements::statements() {} statements::statements(const std::vector<local_var_decl>& local_decl, const std::vector<statement>& stmts) : local_decl_(local_decl), statements_(stmts) {} } // namespace lang } // namespace stan #endif
23.052632
69
0.730594
ludkinm
6185703358aa674ed503d3dd3f260a2d8c52a524
5,736
cpp
C++
core/ilwisobjects/operation/symboltable.cpp
ridoo/IlwisCore
9d9837507d804a4643545a03fd40d9b4d0eaee45
[ "Apache-2.0" ]
null
null
null
core/ilwisobjects/operation/symboltable.cpp
ridoo/IlwisCore
9d9837507d804a4643545a03fd40d9b4d0eaee45
[ "Apache-2.0" ]
null
null
null
core/ilwisobjects/operation/symboltable.cpp
ridoo/IlwisCore
9d9837507d804a4643545a03fd40d9b4d0eaee45
[ "Apache-2.0" ]
null
null
null
#include <QString> #include <QFileInfo> #include <QVector> #include <QUrl> #include <QRegExp> #include <QStringList> #include "kernel.h" #include "raster.h" #include "catalog.h" #include "ilwiscontext.h" #include "mastercatalog.h" #include "symboltable.h" using namespace Ilwis; quint64 SymbolTable::_symbolid = 0; SymbolTable::SymbolTable() //: //QHash<QString, Symbol>() { } SymbolTable::~SymbolTable(){ _symbols.clear(); } void SymbolTable::addSymbol(const QString &name, int scope, quint64 tp, const QVariant& v) { QVariant var = getValue(name,scope); // do we already have it? if (var.isValid()){ _symbols[name]._var = v; _symbols[name]._type = tp; return; } if ( tp == 0) { if ( isRealNumerical(v)) tp = itDOUBLE; else if (isIntegerNumerical(v)) tp = itINT32; else { if ( v.type() == QMetaType::QString) tp = itSTRING; QString typname = v.typeName(); if ( typname == "Coordinate") tp = itCOORDINATE; } } Symbol sym(scope, tp, v); _symbols[name] = sym; } QVariant SymbolTable::getValue(const QString &name, int scope) const { if ( name.isNull() || name.isEmpty()) return QVariant(); QHash<QString, Symbol>::const_iterator iter = _symbols.find(name); while (iter != _symbols.end() && iter.key() == name) { if ( iter.value()._scope == scope) { QString tp = iter.value()._var.typeName(); if ( tp == "QVariantList"){ QVariantList lst = iter.value()._var.value<QVariantList>(); return lst[0]; } return iter.value()._var; } ++iter; } return QVariant(); } Symbol SymbolTable::getSymbol(const QString &name, GetAction act, int scope) { if ( name.isNull() || name.isEmpty()) return Symbol(); QHash<QString, Symbol>::iterator iter = _symbols.find(name); while (iter != _symbols.end() && iter.key() == name) { if ( iter.value()._scope <= scope) { Symbol sym = iter.value(); bool isAnonymous = name.indexOf(ANONYMOUS_PREFIX) == 0; if ((isAnonymous && act == gaREMOVEIFANON) || act == gaREMOVE) _symbols.erase(iter); return sym; } ++iter; } return Symbol(); } Symbol SymbolTable::getSymbol(const QString &name, int scope) const { QHash<QString, Symbol>::const_iterator iter = _symbols.find(name); while (iter != _symbols.end() && iter.key() == name) { if ( iter.value()._scope == scope) { return iter.value(); } ++iter; } return Symbol(); } void SymbolTable::unloadRasters() { for(Symbol& sym: _symbols) { if ( sym._type == itRASTER) { IRasterCoverage raster = sym._var.value<IRasterCoverage>(); if ( raster.isValid()) raster->unloadBinary(); } } } IlwisTypes SymbolTable::ilwisType(const QVariant &value, const QString& symname) const { if ( symname == sUNDEF) { // not a referenced value return Domain::ilwType(value); } auto iter = _symbols.find(symname); if ( iter != _symbols.end()) { return iter.value()._type; } IlwisTypes tp = IlwisObject::findType(symname); if ( tp != itUNKNOWN) return tp; quint64 id = mastercatalog()->name2id(symname); if ( id != i64UNDEF){ IIlwisObject obj = mastercatalog()->get(id); if ( obj.isValid()){ return obj->ilwisType(); } } return itUNKNOWN; } bool SymbolTable::isNumerical(const QVariant& var) { return isRealNumerical(var) || isIntegerNumerical(var); } bool SymbolTable::isString(const QVariant& var) { return var.canConvert<QString>(); } bool SymbolTable::isRealNumerical(const QVariant& var) { bool ok = var.type() == QMetaType::Float || var.type() == QMetaType::Double; if ( ok) return true; var.toDouble(&ok); return ok; } bool SymbolTable::isIndex(int index, const QVariantList& var) { QString tpname = var[index].typeName(); if ( tpname == "std::vector<quint32>" || tpname == "Indices") return true; return false; } bool SymbolTable::isIntegerNumerical(const QVariant& var) { QMetaType::Type tp = static_cast<QMetaType::Type>(var.type()); bool ok = tp == QMetaType::Int || tp == QMetaType::UInt || tp == QMetaType::LongLong || tp == QMetaType::ULongLong || tp == QMetaType::Long || tp == QMetaType::ULong || tp == QMetaType::Short || tp == QMetaType::UShort || tp == QMetaType::Char || tp == QMetaType::UChar; if ( ok) return true; var.toLongLong(&ok); if ( ok) return true; var.toULongLong(&ok); return ok; } bool SymbolTable::isDataLink(const QVariant& value) { QString resolvedv = value.toString(); if ( !resolvedv.contains(QRegExp("\\\\|/"))) { bool ok; resolvedv.toDouble(&ok); if (ok) return false; resolvedv = Ilwis::context()->workingCatalog()->resolve(resolvedv); if ( resolvedv == sUNDEF) { quint64 id = mastercatalog()->name2id(resolvedv); if ( id != i64UNDEF) return true; return false; } } return true; } QString SymbolTable::newAnonym() { _symbolid++; return QString("%1%2").arg(ANONYMOUS_PREFIX).arg(_symbolid); } Symbol::Symbol(int scope, quint64 tp, const QVariant &v) : _type(tp), _scope(scope), _var(v) { } Symbol::~Symbol() { } bool Symbol::isValid() const { return _var.isValid() && _scope != iUNDEF; }
26.072727
92
0.577929
ridoo
61884d929592e3869d83fb49c3b76a72c1be0e1c
21,767
hpp
C++
windows/include/boost/asio/detail/reactive_descriptor_service.hpp
jaredhoberock/gotham
e3551cc355646530574d086d7cc2b82e41e8f798
[ "Apache-2.0" ]
6
2015-12-29T07:21:01.000Z
2020-05-29T10:47:38.000Z
windows/include/boost/asio/detail/reactive_descriptor_service.hpp
jaredhoberock/gotham
e3551cc355646530574d086d7cc2b82e41e8f798
[ "Apache-2.0" ]
null
null
null
windows/include/boost/asio/detail/reactive_descriptor_service.hpp
jaredhoberock/gotham
e3551cc355646530574d086d7cc2b82e41e8f798
[ "Apache-2.0" ]
null
null
null
// // reactive_descriptor_service.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2008 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // 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 BOOST_ASIO_DETAIL_REACTIVE_DESCRIPTOR_SERVICE_HPP #define BOOST_ASIO_DETAIL_REACTIVE_DESCRIPTOR_SERVICE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/push_options.hpp> #include <boost/asio/buffer.hpp> #include <boost/asio/error.hpp> #include <boost/asio/io_service.hpp> #include <boost/asio/detail/bind_handler.hpp> #include <boost/asio/detail/handler_base_from_member.hpp> #include <boost/asio/detail/noncopyable.hpp> #include <boost/asio/detail/service_base.hpp> #include <boost/asio/detail/descriptor_ops.hpp> #if !defined(BOOST_WINDOWS) && !defined(__CYGWIN__) namespace boost { namespace asio { namespace detail { template <typename Reactor> class reactive_descriptor_service : public boost::asio::detail::service_base< reactive_descriptor_service<Reactor> > { public: // The native type of a descriptor. typedef int native_type; // The implementation type of the descriptor. class implementation_type : private boost::asio::detail::noncopyable { public: // Default constructor. implementation_type() : descriptor_(-1), flags_(0) { } private: // Only this service will have access to the internal values. friend class reactive_descriptor_service<Reactor>; // The native descriptor representation. int descriptor_; enum { user_set_non_blocking = 1, // The user wants a non-blocking descriptor. internal_non_blocking = 2 // The descriptor has been set non-blocking. }; // Flags indicating the current state of the descriptor. unsigned char flags_; // Per-descriptor data used by the reactor. typename Reactor::per_descriptor_data reactor_data_; }; // The maximum number of buffers to support in a single operation. enum { max_buffers = 64 < max_iov_len ? 64 : max_iov_len }; // Constructor. reactive_descriptor_service(boost::asio::io_service& io_service) : boost::asio::detail::service_base< reactive_descriptor_service<Reactor> >(io_service), reactor_(boost::asio::use_service<Reactor>(io_service)) { } // Destroy all user-defined handler objects owned by the service. void shutdown_service() { } // Construct a new descriptor implementation. void construct(implementation_type& impl) { impl.descriptor_ = -1; impl.flags_ = 0; } // Destroy a descriptor implementation. void destroy(implementation_type& impl) { if (impl.descriptor_ != -1) { reactor_.close_descriptor(impl.descriptor_, impl.reactor_data_); if (impl.flags_ & implementation_type::internal_non_blocking) { ioctl_arg_type non_blocking = 0; boost::system::error_code ignored_ec; descriptor_ops::ioctl(impl.descriptor_, FIONBIO, &non_blocking, ignored_ec); impl.flags_ &= ~implementation_type::internal_non_blocking; } boost::system::error_code ignored_ec; descriptor_ops::close(impl.descriptor_, ignored_ec); impl.descriptor_ = -1; } } // Assign a native descriptor to a descriptor implementation. boost::system::error_code assign(implementation_type& impl, const native_type& native_descriptor, boost::system::error_code& ec) { if (is_open(impl)) { ec = boost::asio::error::already_open; return ec; } if (int err = reactor_.register_descriptor( native_descriptor, impl.reactor_data_)) { ec = boost::system::error_code(err, boost::asio::error::get_system_category()); return ec; } impl.descriptor_ = native_descriptor; impl.flags_ = 0; ec = boost::system::error_code(); return ec; } // Determine whether the descriptor is open. bool is_open(const implementation_type& impl) const { return impl.descriptor_ != -1; } // Destroy a descriptor implementation. boost::system::error_code close(implementation_type& impl, boost::system::error_code& ec) { if (is_open(impl)) { reactor_.close_descriptor(impl.descriptor_, impl.reactor_data_); if (impl.flags_ & implementation_type::internal_non_blocking) { ioctl_arg_type non_blocking = 0; boost::system::error_code ignored_ec; descriptor_ops::ioctl(impl.descriptor_, FIONBIO, &non_blocking, ignored_ec); impl.flags_ &= ~implementation_type::internal_non_blocking; } if (descriptor_ops::close(impl.descriptor_, ec) == -1) return ec; impl.descriptor_ = -1; } ec = boost::system::error_code(); return ec; } // Get the native descriptor representation. native_type native(const implementation_type& impl) const { return impl.descriptor_; } // Cancel all operations associated with the descriptor. boost::system::error_code cancel(implementation_type& impl, boost::system::error_code& ec) { if (!is_open(impl)) { ec = boost::asio::error::bad_descriptor; return ec; } reactor_.cancel_ops(impl.descriptor_, impl.reactor_data_); ec = boost::system::error_code(); return ec; } // Perform an IO control command on the descriptor. template <typename IO_Control_Command> boost::system::error_code io_control(implementation_type& impl, IO_Control_Command& command, boost::system::error_code& ec) { if (!is_open(impl)) { ec = boost::asio::error::bad_descriptor; return ec; } if (command.name() == static_cast<int>(FIONBIO)) { if (command.get()) impl.flags_ |= implementation_type::user_set_non_blocking; else impl.flags_ &= ~implementation_type::user_set_non_blocking; ec = boost::system::error_code(); } else { descriptor_ops::ioctl(impl.descriptor_, command.name(), static_cast<ioctl_arg_type*>(command.data()), ec); } return ec; } // Write some data to the descriptor. template <typename ConstBufferSequence> size_t write_some(implementation_type& impl, const ConstBufferSequence& buffers, boost::system::error_code& ec) { if (!is_open(impl)) { ec = boost::asio::error::bad_descriptor; return 0; } // Copy buffers into array. descriptor_ops::buf bufs[max_buffers]; typename ConstBufferSequence::const_iterator iter = buffers.begin(); typename ConstBufferSequence::const_iterator end = buffers.end(); size_t i = 0; size_t total_buffer_size = 0; for (; iter != end && i < max_buffers; ++iter, ++i) { boost::asio::const_buffer buffer(*iter); descriptor_ops::init_buf(bufs[i], boost::asio::buffer_cast<const void*>(buffer), boost::asio::buffer_size(buffer)); total_buffer_size += boost::asio::buffer_size(buffer); } // A request to read_some 0 bytes on a stream is a no-op. if (total_buffer_size == 0) { ec = boost::system::error_code(); return 0; } // Make descriptor non-blocking if user wants non-blocking. if (impl.flags_ & implementation_type::user_set_non_blocking) { if (!(impl.flags_ & implementation_type::internal_non_blocking)) { ioctl_arg_type non_blocking = 1; if (descriptor_ops::ioctl(impl.descriptor_, FIONBIO, &non_blocking, ec)) return 0; impl.flags_ |= implementation_type::internal_non_blocking; } } // Send the data. for (;;) { // Try to complete the operation without blocking. int bytes_sent = descriptor_ops::gather_write( impl.descriptor_, bufs, i, ec); // Check if operation succeeded. if (bytes_sent >= 0) return bytes_sent; // Operation failed. if ((impl.flags_ & implementation_type::user_set_non_blocking) || (ec != boost::asio::error::would_block && ec != boost::asio::error::try_again)) return 0; // Wait for descriptor to become ready. if (descriptor_ops::poll_write(impl.descriptor_, ec) < 0) return 0; } } // Wait until data can be written without blocking. size_t write_some(implementation_type& impl, const null_buffers&, boost::system::error_code& ec) { if (!is_open(impl)) { ec = boost::asio::error::bad_descriptor; return 0; } // Wait for descriptor to become ready. descriptor_ops::poll_write(impl.descriptor_, ec); return 0; } template <typename ConstBufferSequence, typename Handler> class write_operation : public handler_base_from_member<Handler> { public: write_operation(int descriptor, boost::asio::io_service& io_service, const ConstBufferSequence& buffers, Handler handler) : handler_base_from_member<Handler>(handler), descriptor_(descriptor), io_service_(io_service), work_(io_service), buffers_(buffers) { } bool perform(boost::system::error_code& ec, std::size_t& bytes_transferred) { // Check whether the operation was successful. if (ec) { bytes_transferred = 0; return true; } // Copy buffers into array. descriptor_ops::buf bufs[max_buffers]; typename ConstBufferSequence::const_iterator iter = buffers_.begin(); typename ConstBufferSequence::const_iterator end = buffers_.end(); size_t i = 0; for (; iter != end && i < max_buffers; ++iter, ++i) { boost::asio::const_buffer buffer(*iter); descriptor_ops::init_buf(bufs[i], boost::asio::buffer_cast<const void*>(buffer), boost::asio::buffer_size(buffer)); } // Write the data. int bytes = descriptor_ops::gather_write(descriptor_, bufs, i, ec); // Check if we need to run the operation again. if (ec == boost::asio::error::would_block || ec == boost::asio::error::try_again) return false; bytes_transferred = (bytes < 0 ? 0 : bytes); return true; } void complete(const boost::system::error_code& ec, std::size_t bytes_transferred) { io_service_.post(bind_handler(this->handler_, ec, bytes_transferred)); } private: int descriptor_; boost::asio::io_service& io_service_; boost::asio::io_service::work work_; ConstBufferSequence buffers_; }; // Start an asynchronous write. The data being sent must be valid for the // lifetime of the asynchronous operation. template <typename ConstBufferSequence, typename Handler> void async_write_some(implementation_type& impl, const ConstBufferSequence& buffers, Handler handler) { if (!is_open(impl)) { this->get_io_service().post(bind_handler(handler, boost::asio::error::bad_descriptor, 0)); } else { // Determine total size of buffers. typename ConstBufferSequence::const_iterator iter = buffers.begin(); typename ConstBufferSequence::const_iterator end = buffers.end(); size_t i = 0; size_t total_buffer_size = 0; for (; iter != end && i < max_buffers; ++iter, ++i) { boost::asio::const_buffer buffer(*iter); total_buffer_size += boost::asio::buffer_size(buffer); } // A request to read_some 0 bytes on a stream is a no-op. if (total_buffer_size == 0) { this->get_io_service().post(bind_handler(handler, boost::system::error_code(), 0)); return; } // Make descriptor non-blocking. if (!(impl.flags_ & implementation_type::internal_non_blocking)) { ioctl_arg_type non_blocking = 1; boost::system::error_code ec; if (descriptor_ops::ioctl(impl.descriptor_, FIONBIO, &non_blocking, ec)) { this->get_io_service().post(bind_handler(handler, ec, 0)); return; } impl.flags_ |= implementation_type::internal_non_blocking; } reactor_.start_write_op(impl.descriptor_, impl.reactor_data_, write_operation<ConstBufferSequence, Handler>( impl.descriptor_, this->get_io_service(), buffers, handler)); } } template <typename Handler> class null_buffers_operation : public handler_base_from_member<Handler> { public: null_buffers_operation(boost::asio::io_service& io_service, Handler handler) : handler_base_from_member<Handler>(handler), work_(io_service) { } bool perform(boost::system::error_code&, std::size_t& bytes_transferred) { bytes_transferred = 0; return true; } void complete(const boost::system::error_code& ec, std::size_t bytes_transferred) { work_.get_io_service().post(bind_handler( this->handler_, ec, bytes_transferred)); } private: boost::asio::io_service::work work_; }; // Start an asynchronous wait until data can be written without blocking. template <typename Handler> void async_write_some(implementation_type& impl, const null_buffers&, Handler handler) { if (!is_open(impl)) { this->get_io_service().post(bind_handler(handler, boost::asio::error::bad_descriptor, 0)); } else { reactor_.start_write_op(impl.descriptor_, impl.reactor_data_, null_buffers_operation<Handler>(this->get_io_service(), handler), false); } } // Read some data from the stream. Returns the number of bytes read. template <typename MutableBufferSequence> size_t read_some(implementation_type& impl, const MutableBufferSequence& buffers, boost::system::error_code& ec) { if (!is_open(impl)) { ec = boost::asio::error::bad_descriptor; return 0; } // Copy buffers into array. descriptor_ops::buf bufs[max_buffers]; typename MutableBufferSequence::const_iterator iter = buffers.begin(); typename MutableBufferSequence::const_iterator end = buffers.end(); size_t i = 0; size_t total_buffer_size = 0; for (; iter != end && i < max_buffers; ++iter, ++i) { boost::asio::mutable_buffer buffer(*iter); descriptor_ops::init_buf(bufs[i], boost::asio::buffer_cast<void*>(buffer), boost::asio::buffer_size(buffer)); total_buffer_size += boost::asio::buffer_size(buffer); } // A request to read_some 0 bytes on a stream is a no-op. if (total_buffer_size == 0) { ec = boost::system::error_code(); return 0; } // Make descriptor non-blocking if user wants non-blocking. if (impl.flags_ & implementation_type::user_set_non_blocking) { if (!(impl.flags_ & implementation_type::internal_non_blocking)) { ioctl_arg_type non_blocking = 1; if (descriptor_ops::ioctl(impl.descriptor_, FIONBIO, &non_blocking, ec)) return 0; impl.flags_ |= implementation_type::internal_non_blocking; } } // Read some data. for (;;) { // Try to complete the operation without blocking. int bytes_read = descriptor_ops::scatter_read( impl.descriptor_, bufs, i, ec); // Check if operation succeeded. if (bytes_read > 0) return bytes_read; // Check for EOF. if (bytes_read == 0) { ec = boost::asio::error::eof; return 0; } // Operation failed. if ((impl.flags_ & implementation_type::user_set_non_blocking) || (ec != boost::asio::error::would_block && ec != boost::asio::error::try_again)) return 0; // Wait for descriptor to become ready. if (descriptor_ops::poll_read(impl.descriptor_, ec) < 0) return 0; } } // Wait until data can be read without blocking. size_t read_some(implementation_type& impl, const null_buffers&, boost::system::error_code& ec) { if (!is_open(impl)) { ec = boost::asio::error::bad_descriptor; return 0; } // Wait for descriptor to become ready. descriptor_ops::poll_read(impl.descriptor_, ec); return 0; } template <typename MutableBufferSequence, typename Handler> class read_operation : public handler_base_from_member<Handler> { public: read_operation(int descriptor, boost::asio::io_service& io_service, const MutableBufferSequence& buffers, Handler handler) : handler_base_from_member<Handler>(handler), descriptor_(descriptor), io_service_(io_service), work_(io_service), buffers_(buffers) { } bool perform(boost::system::error_code& ec, std::size_t& bytes_transferred) { // Check whether the operation was successful. if (ec) { bytes_transferred = 0; return true; } // Copy buffers into array. descriptor_ops::buf bufs[max_buffers]; typename MutableBufferSequence::const_iterator iter = buffers_.begin(); typename MutableBufferSequence::const_iterator end = buffers_.end(); size_t i = 0; for (; iter != end && i < max_buffers; ++iter, ++i) { boost::asio::mutable_buffer buffer(*iter); descriptor_ops::init_buf(bufs[i], boost::asio::buffer_cast<void*>(buffer), boost::asio::buffer_size(buffer)); } // Read some data. int bytes = descriptor_ops::scatter_read(descriptor_, bufs, i, ec); if (bytes == 0) ec = boost::asio::error::eof; // Check if we need to run the operation again. if (ec == boost::asio::error::would_block || ec == boost::asio::error::try_again) return false; bytes_transferred = (bytes < 0 ? 0 : bytes); return true; } void complete(const boost::system::error_code& ec, std::size_t bytes_transferred) { io_service_.post(bind_handler(this->handler_, ec, bytes_transferred)); } private: int descriptor_; boost::asio::io_service& io_service_; boost::asio::io_service::work work_; MutableBufferSequence buffers_; }; // Start an asynchronous read. The buffer for the data being read must be // valid for the lifetime of the asynchronous operation. template <typename MutableBufferSequence, typename Handler> void async_read_some(implementation_type& impl, const MutableBufferSequence& buffers, Handler handler) { if (!is_open(impl)) { this->get_io_service().post(bind_handler(handler, boost::asio::error::bad_descriptor, 0)); } else { // Determine total size of buffers. typename MutableBufferSequence::const_iterator iter = buffers.begin(); typename MutableBufferSequence::const_iterator end = buffers.end(); size_t i = 0; size_t total_buffer_size = 0; for (; iter != end && i < max_buffers; ++iter, ++i) { boost::asio::mutable_buffer buffer(*iter); total_buffer_size += boost::asio::buffer_size(buffer); } // A request to read_some 0 bytes on a stream is a no-op. if (total_buffer_size == 0) { this->get_io_service().post(bind_handler(handler, boost::system::error_code(), 0)); return; } // Make descriptor non-blocking. if (!(impl.flags_ & implementation_type::internal_non_blocking)) { ioctl_arg_type non_blocking = 1; boost::system::error_code ec; if (descriptor_ops::ioctl(impl.descriptor_, FIONBIO, &non_blocking, ec)) { this->get_io_service().post(bind_handler(handler, ec, 0)); return; } impl.flags_ |= implementation_type::internal_non_blocking; } reactor_.start_read_op(impl.descriptor_, impl.reactor_data_, read_operation<MutableBufferSequence, Handler>( impl.descriptor_, this->get_io_service(), buffers, handler)); } } // Wait until data can be read without blocking. template <typename Handler> void async_read_some(implementation_type& impl, const null_buffers&, Handler handler) { if (!is_open(impl)) { this->get_io_service().post(bind_handler(handler, boost::asio::error::bad_descriptor, 0)); } else { reactor_.start_read_op(impl.descriptor_, impl.reactor_data_, null_buffers_operation<Handler>(this->get_io_service(), handler), false); } } private: // The selector that performs event demultiplexing for the service. Reactor& reactor_; }; } // namespace detail } // namespace asio } // namespace boost #endif // !defined(BOOST_WINDOWS) && !defined(__CYGWIN__) #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_DETAIL_REACTIVE_DESCRIPTOR_SERVICE_HPP
30.571629
81
0.629255
jaredhoberock
6188edef579f180c3aea754f87d73ca67d383c12
1,626
cpp
C++
modules/usbcamera/HotplugThread.cpp
lighthouse-os/hardware_libhardware
c6fa046a69d9b1adf474cf5de58318b677801e49
[ "Apache-2.0" ]
null
null
null
modules/usbcamera/HotplugThread.cpp
lighthouse-os/hardware_libhardware
c6fa046a69d9b1adf474cf5de58318b677801e49
[ "Apache-2.0" ]
null
null
null
modules/usbcamera/HotplugThread.cpp
lighthouse-os/hardware_libhardware
c6fa046a69d9b1adf474cf5de58318b677801e49
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ //#define LOG_NDEBUG 0 #define LOG_TAG "HotplugThread" #include <log/log.h> #include "HotplugThread.h" namespace usb_camera_hal { HotplugThread::HotplugThread(CameraHAL *hal) : mModule(hal) { } HotplugThread::~HotplugThread() { } void HotplugThread::requestExit() { // Call parent to set up shutdown Thread::requestExit(); // Cleanup other states? } bool HotplugThread::threadLoop() { (void)mModule; // silence warning about unused member. /** * Check camera connection status change, if connected, do below: * 1. Create camera device, add to mCameras. * 2. Init static info (mCameras[id]->initStaticInfo()) * 3. Notify on_status_change callback * * If unconnected, similarly, do below: * 1. Destroy camera device and remove it from mCameras. * 2. Notify on_status_change callback * * DO NOT have a tight polling loop here, to avoid excessive CPU utilization. */ return true; } } // namespace usb_camera_hal
26.225806
81
0.699877
lighthouse-os
618ae31d3060c4c2702b0fd5aaf626eccaedd790
1,481
cpp
C++
third party/openRTMFP-Cumulus/CumulusLib/sources/Trigger.cpp
Patrick-Bay/SocialCastr
888a57ca63037e566f6c0bf03a646ae91b484086
[ "MIT" ]
5
2015-04-30T09:08:30.000Z
2018-08-13T05:00:39.000Z
third party/openRTMFP-Cumulus/CumulusLib/sources/Trigger.cpp
Patrick-Bay/SocialCastr
888a57ca63037e566f6c0bf03a646ae91b484086
[ "MIT" ]
null
null
null
third party/openRTMFP-Cumulus/CumulusLib/sources/Trigger.cpp
Patrick-Bay/SocialCastr
888a57ca63037e566f6c0bf03a646ae91b484086
[ "MIT" ]
null
null
null
/* Copyright 2010 OpenRTMFP 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 received along this program for more details (or else see http://www.gnu.org/licenses/). This file is a part of Cumulus. */ #include "Trigger.h" #include "Poco/Exception.h" using namespace std; using namespace Poco; namespace Cumulus { Trigger::Trigger() : _time(0),_cycle(-1),_running(false) { } Trigger::~Trigger() { } void Trigger::reset() { _timeInit.update(); _time=0; _cycle=-1; } void Trigger::start() { if(_running) return; reset(); _running=true; } bool Trigger::raise() { if(!_running) return false; // Wait at least 1 sec before to begin the repeat cycle, it means that it will be between 1 and 3 sec in truth (freg mangement is set to 2) if(_time==0 && !_timeInit.isElapsed(1000000)) return false; ++_time; if(_time>=_cycle) { _time=0; ++_cycle; if(_cycle==7) throw Exception("Repeat trigger failed"); DEBUG("Repeat trigger cycle %02x",_cycle+1); return true; } return false; } } // namespace Cumulus
21.463768
140
0.704929
Patrick-Bay
618af940f1f6b3310b382040a07bae92e6fa94d7
3,334
cpp
C++
ChainIDE/popwidget/AboutWidgetGit.cpp
AnyChainIO/AnyChainIDE
283c4743f0f2484fcf6dd5528af8ab15c6e35011
[ "MIT" ]
3
2019-05-09T13:56:10.000Z
2019-06-14T08:25:42.000Z
ChainIDE/popwidget/AboutWidgetGit.cpp
AnyChainIO/AnyChainIDE
283c4743f0f2484fcf6dd5528af8ab15c6e35011
[ "MIT" ]
null
null
null
ChainIDE/popwidget/AboutWidgetGit.cpp
AnyChainIO/AnyChainIDE
283c4743f0f2484fcf6dd5528af8ab15c6e35011
[ "MIT" ]
2
2019-04-27T20:39:24.000Z
2019-07-11T05:13:27.000Z
#include "AboutWidgetGit.h" #include "ui_AboutWidgetGit.h" #include <QNetworkAccessManager> #include <QNetworkReply> #include <QRegExp> #include <QDesktopServices> #include "update/UpdateProgressUtil.h" static const QString IDE_VERSION = "1.0.24"; static const QString UPDATE_SERVER_URL = "https://github.com/AnyChainOrg/AnyChainIDE/releases"; #ifdef WIN32 static const QString VERSION_DOWNLOAD_PATTERN = "/AnyChainOrg/AnyChainIDE/releases/download/v(\\d+\\.\\d+\\.\\d+)/([0-9a-zA-Z_]+\\.zip)"; #elif defined(TARGET_OS_MAC) static const QString VERSION_DOWNLOAD_PATTERN = "/AnyChainOrg/AnyChainIDE/releases/download/v(\\d+\\.\\d+\\.\\d+)/([0-9a-zA-Z_]+\\.dmg)"; #endif class AboutWidgetGit::DataPrivate { public: DataPrivate() :networkManager(new QNetworkAccessManager()) { } QNetworkAccessManager *networkManager; }; AboutWidgetGit::AboutWidgetGit(QWidget *parent) : MoveableDialog(parent), ui(new Ui::AboutWidgetGit), _p(new DataPrivate()) { ui->setupUi(this); InitWidget(); } AboutWidgetGit::~AboutWidgetGit() { delete _p; delete ui; } void AboutWidgetGit::checkNewVersion() { ui->label_updatetip->setText(tr("Start check version, please wait...")); ui->label_updatetip->setVisible(true); QNetworkReply *reply = _p->networkManager->get(QNetworkRequest(UPDATE_SERVER_URL)); connect(reply,static_cast<void (QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error),[this](){ QString text = tr("Check update wrong! Please manually check update, click here." ); this->ui->label_updatetip->setText(tr("<a style='color: red;'href=\"%1\">%2").arg(UPDATE_SERVER_URL).arg(text)); this->ui->label_updatetip->setText(tr("Check update wrong!")); // this->ui->label_updatetip->setVisible(true); }); connect(reply,&QNetworkReply::finished,[reply,this](){ QString result(reply->readAll()); QRegExp rx(VERSION_DOWNLOAD_PATTERN); if(result.indexOf(rx) >= 0) { QString serverVersion(rx.cap(1)); if(UpdateProgressUtil::AFTER!=UpdateProgressUtil::CompareVersion(IDE_VERSION,serverVersion)) { this->ui->label_updatetip->setText(tr("No new version!")); } else { QString text = tr("New version found! v" )+ serverVersion; this->ui->label_updatetip->setText(tr("<a style='color: red;'href=\"%1\">%2").arg(UPDATE_SERVER_URL).arg(text)); } } else { this->ui->label_updatetip->setText(tr("No release found!")); } // this->ui->label_updatetip->setVisible(true); }); } void AboutWidgetGit::InitWidget() { setWindowFlags(windowFlags()| Qt::FramelessWindowHint); ui->label_updatetip->setVisible(false); #ifdef WIN64 ui->label_version->setText(QString("windows 64bit v") + IDE_VERSION); #elif defined(TARGET_OS_MAC) ui->label_version->setText(QString("mac v") + IDE_VERSION); #else ui->label_version->setText(QString("windows 32bit v") + IDE_VERSION); #endif connect(ui->closeBtn,&QToolButton::clicked,this,&AboutWidgetGit::close); connect(ui->toolButton_checkUpdate,&QToolButton::clicked,this,&AboutWidgetGit::checkNewVersion); ui->label_updatetip->setOpenExternalLinks(true); }
34.371134
137
0.670366
AnyChainIO
618e0ee23293de678a125f90204935f2362aaef8
24,060
hpp
C++
pancake.hpp
MattBolitho/Pancake
34c939abd48619cd53e4c1c8d0df1da12dc3902e
[ "MIT" ]
null
null
null
pancake.hpp
MattBolitho/Pancake
34c939abd48619cd53e4c1c8d0df1da12dc3902e
[ "MIT" ]
null
null
null
pancake.hpp
MattBolitho/Pancake
34c939abd48619cd53e4c1c8d0df1da12dc3902e
[ "MIT" ]
null
null
null
// Copyright (c) 2021 Matt Bolitho // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #ifndef PANCAKE_HPP #define PANCAKE_HPP #define PANCAKE #define PANCAKE_VERSION "0.2.0" #include <cstdint> #include <cstdio> #include <string> #include <stack> #include <unordered_map> #include <unordered_set> #include <iostream> #include <stdexcept> #include <algorithm> #include <functional> namespace Pancake { /// The size of a single word in the stack. using Word = uint64_t; /// The type used for the operand stack. using Stack = std::stack<Word>; /// Memory is a store of named values. using Memory = std::unordered_map<std::string, Word>; /// The type of the instruction pointer. using InstructionPointer = std::string::size_type; /// Maps strings to instruction pointers. using InstructionPointerMap = std::unordered_map<std::string, InstructionPointer>; /// Enumerates the different types of PANics. enum class PanicType { /// Thrown when there are not enough values on the stack for /// the requested operation. StackExhaustion, /// Thrown when attempting to load an undefined variable. UndefinedVariable, /// Thrown when attempting to jump to an undefined label. UndefinedLabel, /// Thrown when no valid opcode is matched during dispatch. UnrecognisedOpcode, /// Thrown when the result of a PANic would attempt to jump to multiple addresses. MultiplePanicHandlers, /// Thrown when a string does not conform to the Pancake language. InvalidLanguage, /// Thrown by the user using the PANic (p{}) instruction. User }; /// Thrown when the Pancake virtual machine or interpreter PANics. class PancakePanic final : public std::runtime_error { public: /// Initializes a new instance of the PancakePanic class. /// @param type The PANic type. /// @param message The message. explicit PancakePanic(PanicType const type, char const* message) : _type(type), std::runtime_error(message) { } /// Initializes a new instance of the PancakePanic class. /// @param type The PANic type. /// @param message The message. explicit PancakePanic(PanicType const type, std::string const& message) : _type(type), std::runtime_error(message) { } /// Gets the PANic type. /// @returns The PANic type. PanicType GetPanicType() const noexcept { return _type; } private: PanicType _type; }; /// A stack virtual machine architecture for the Pancake programming language. class PancakeVirtualMachine final { public: /// Gets a value indicating whether or not a program is running on the virtual machine. bool IsRunning() const noexcept { return _running; } /// Gets the current value of the instruction pointer. std::string::size_type GetInstructionPointer() const noexcept { return _instructionPointer; } /// Initializes the virtual machine ready for instructions to be dispatched. void InitializeForNewProgram(std::string const& program) { _running = true; _instructionPointer = 0; _program = program; _stack = Stack(); _memory = Memory(); _labels = InstructionPointerMap(); _panicHandlers = InstructionPointerMap(); } /// Dispatches the opcode with no arguments to the virtual machine. /// @param opcode The opcode to dispatch. void DispatchInstruction(char const opcode) { switch (opcode) { case '|': _running = false; break; case '^': _stack.push(0); break; case ';': VerifyUnaryOperation(); _stack.pop(); break; case '&': VerifyUnaryOperation(); _stack.push(_stack.top()); break; case '$': { VerifyBinaryOperation(); auto const top = _stack.top(); _stack.pop(); auto const second = _stack.top(); _stack.pop(); _stack.push(top); _stack.push(second); break; } case '~': ReverseStack(); break; case '\'': { VerifyBinaryOperation(); auto const top = _stack.top(); _stack.pop(); auto const second = _stack.top(); _stack.push(top); _stack.push(second); break; } case '+': { PerformBinaryOperation([](auto a, auto b) { return a + b; }); break; } case '-': { PerformBinaryOperation([](auto a, auto b) { return a - b; }); break; } case '*': { PerformBinaryOperation([](auto a, auto b) { return a * b; }); break; } case '/': { PerformBinaryOperation([](auto a, auto b) { return a / b; }); break; } case '%': { PerformBinaryOperation([](auto a, auto b) { return a % b; }); break; } case '>': VerifyUnaryOperation(); ++_stack.top(); break; case '<': VerifyUnaryOperation(); --_stack.top(); break; case '[': VerifyBinaryOperation(); PerformBinaryOperation([](auto a, auto b) { return a << b; }); break; case ']': VerifyBinaryOperation(); PerformBinaryOperation([](auto a, auto b) { return a >> b; }); break; case 'n': { VerifyUnaryOperation(); auto const top = _stack.top(); _stack.pop(); _stack.push(~top); break; } case 'a': VerifyBinaryOperation(); PerformBinaryOperation([](auto a, auto b) { return a & b; }); break; case 'o': VerifyBinaryOperation(); PerformBinaryOperation([](auto a, auto b) { return a | b; }); break; case 'x': VerifyBinaryOperation(); PerformBinaryOperation([](auto a, auto b) { return a ^ b; }); break; case 'E': VerifyBinaryOperation(); PerformBinaryOperation([](auto a, auto b) { return ((Word)a == (Word)b); }); break; case 'G': PerformBinaryOperation([](auto a, auto b) { return ((Word)a > (Word)b); }); break; case 'L': VerifyBinaryOperation(); PerformBinaryOperation([](auto a, auto b) { return ((Word)a < (Word)b); }); break; case 'g': VerifyBinaryOperation(); PerformBinaryOperation([](auto a, auto b) { return ((Word)a >= (Word)b); }); break; case 'l': VerifyBinaryOperation(); PerformBinaryOperation([](auto a, auto b) { return ((Word)a <= (Word)b); }); break; case 'N': { VerifyUnaryOperation(); auto const value = _stack.top(); _stack.pop(); _stack.push(!((Word)value)); break; } case 'A': VerifyBinaryOperation(); PerformBinaryOperation([](auto a, auto b) { return ((Word)a && (Word)b); }); break; case 'O': VerifyBinaryOperation(); PerformBinaryOperation([](auto a, auto b) { return ((Word)a || (Word)b); }); break; case 'X': VerifyBinaryOperation(); PerformBinaryOperation([](auto a, auto b) { return (!((Word)a) != !((Word)b)); }); break; case '.': VerifyUnaryOperation(); std::cout << static_cast<char>(_stack.top()); _stack.pop(); break; case '_': VerifyUnaryOperation(); std::cout << std::to_string(_stack.top()); _stack.pop(); break; case ',': { std::string value; std::cin >> value; _stack.push(static_cast<Word>(std::stoull(value))); break; } default: ThrowForUnrecognisedOpcode(opcode); break; } ++_instructionPointer; } /// Dispatches the opcode with a byte argument to the virtual machine. /// @param opcode The opcode to dispatch. /// @param value The byte value in the instruction. void DispatchWordInstruction(char const opcode, Word const value) { if (opcode == '^') { _stack.push(value); _instructionPointer += std::to_string(value).size() + 3; // todo - improve this } else { ThrowForUnrecognisedOpcode(opcode); } } /// Dispatches the opcode with a label argument to the virtual machine. /// @param opcode The opcode to dispatch. /// @param label The label in the instruction. void DispatchLabelInstruction(char const opcode, std::string const& label) { switch (opcode) { case 'p': if (!HandlePanic(label)) { throw PancakePanic(PanicType::User, label); } break; case 'h': RegisterPanicHandler(label); break; case ':': { auto const jumpAddress = _instructionPointer + label.size() + 3; _labels[label] = jumpAddress; _instructionPointer = jumpAddress; break; } case 'j': Jump(label); break; case 'z': VerifyUnaryOperation(); ConditionalJump(_stack.top() == 0, label); break; case 'e': { VerifyBinaryOperation(); auto const top = _stack.top(); _stack.pop(); ConditionalJump(top == _stack.top(), label); _stack.push(top); break; } case '!': VerifyUnaryOperation(); _memory[label] = _stack.top(); _stack.pop(); _instructionPointer += label.size() + 3; break; case '?': VerifyRead(label); _stack.push(_memory[label]); _instructionPointer += label.size() + 3; break; default: ThrowForUnrecognisedOpcode(opcode); break; } } private: bool _running = false; InstructionPointer _instructionPointer = 0; std::string _program; Stack _stack{}; Memory _memory{}; InstructionPointerMap _labels{}; InstructionPointerMap _panicHandlers{}; void VerifyUnaryOperation() const { if (_stack.empty()) { throw PancakePanic(PanicType::StackExhaustion, "Attempted to perform unary operation on empty stack."); } } void VerifyBinaryOperation() const { if (_stack.size() < 2) { throw PancakePanic(PanicType::StackExhaustion, "Attempted to perform binary operation with fewer than 2 values on the stack."); } } void VerifyRead(std::string const& label) const { if (_memory.find(label) == _memory.end()) { std::stringstream errorStream; errorStream << "No value stored with name '" << label << "' could be found in memory.\n"; throw PancakePanic(PanicType::UndefinedVariable, errorStream.str()); } } void PerformBinaryOperation(std::function<Word(Word, Word)> const& operation) { // Note: the function operands are given in the order (top, second). VerifyBinaryOperation(); auto const a = _stack.top(); _stack.pop(); auto const b = _stack.top(); _stack.pop(); _stack.push(operation(a, b)); } void ReverseStack() { std::stack<Word> newStack{}; while (!_stack.empty()) { newStack.push(_stack.top()); _stack.pop(); } _stack = newStack; } void Jump(std::string const& label) { if (_labels.find(label) != _labels.end()) { _instructionPointer = _labels[label]; return; } std::stringstream expectedLabelStringStream; expectedLabelStringStream << ":{" << label << "}"; auto labelInstruction = expectedLabelStringStream.str(); auto foundIndex = _program.find(labelInstruction); if (foundIndex == std::string::npos) { throw PancakePanic(PanicType::UndefinedLabel, std::string("Cannot jump to label '") + label + "' as it does not exist."); } auto jumpIndex = foundIndex + labelInstruction.size(); _labels[label] = jumpIndex; _instructionPointer = jumpIndex; } void ConditionalJump(bool const condition, std::string const& label) { // If the condition is true, we need to find the label and jump there. // Otherwise we need to do the usual instruction pointer arithmetic // over the current instruction, label and curly brace characters. if (condition) { Jump(label); } else { _instructionPointer += label.size() + 3; } } bool HandlePanic(std::string const& panic) { if (_panicHandlers.find(panic) != _panicHandlers.end()) { _instructionPointer = _panicHandlers[panic]; return true; } std::stringstream expectedHandlerStringStream; expectedHandlerStringStream << "h{" << panic << "}"; auto handlerInstruction = expectedHandlerStringStream.str(); auto foundIndex = _program.find(expectedHandlerStringStream.str()); if (foundIndex == std::string::npos) { return false; } auto jumpIndex = foundIndex + handlerInstruction.size(); _panicHandlers[panic] = jumpIndex; _instructionPointer = jumpIndex; return true; } void RegisterPanicHandler(std::string const& handlerLabel) { auto const handlerAddress = _instructionPointer + handlerLabel.size() + 3; if (_panicHandlers.find(handlerLabel) != _panicHandlers.end()) { throw PancakePanic(PanicType::MultiplePanicHandlers, std::string("Multiple PANic handlers for '") + handlerLabel + "'."); } _panicHandlers[handlerLabel] = handlerAddress; _instructionPointer = handlerAddress; } static void ThrowForUnrecognisedOpcode(char const opcode) { std::stringstream errorStream; errorStream << "Unrecognised opcode - '" << opcode << "'.\n"; throw PancakePanic(PanicType::UnrecognisedOpcode, errorStream.str()); } }; /// Interprets Pancake programs. class PancakeInterpreter final { public: /// Runs the instructions in the given program until they /// are exhausted or an error is encountered. /// @param program The string containing the program. void Interpret(std::string& program) { try { PreProcessProgram(program); _virtualMachine.InitializeForNewProgram(program); while (_virtualMachine.IsRunning()) { auto const instructionPointer = _virtualMachine.GetInstructionPointer(); auto const instruction = program[instructionPointer]; if (instruction == '\0') { break; } if (program[instructionPointer + 1] == '{') { auto nextClosingBraceIndex = program.find('}', instructionPointer); if (nextClosingBraceIndex == std::string::npos) { throw PancakePanic(PanicType::InvalidLanguage, "Unmatched braces for argument instruction."); } auto argumentStartIndex = instructionPointer + 2; auto argument = program.substr(argumentStartIndex, nextClosingBraceIndex - argumentStartIndex); if (instruction == '^') { auto value = static_cast<Pancake::Word>(std::stoull(argument)); _virtualMachine.DispatchWordInstruction(instruction, value); } else { _virtualMachine.DispatchLabelInstruction(instruction, argument); } } else { _virtualMachine.DispatchInstruction(instruction); } } } catch (PancakePanic const& pancakeException) { std::cerr << "Pancake runtime error: " << pancakeException.what() << std::endl; } catch (...) { std::cerr << "Unspecified error." << std::endl; } } private: PancakeVirtualMachine _virtualMachine{}; static void PreProcessProgram(std::string& program) { /// Remove standard whitespace characters. std::unordered_set<char> charactersToRemove = { '\n', '\r', ' ', '\t' }; auto removeWhitespaceFunction = [&](char const c) { return charactersToRemove.find(c) != charactersToRemove.end(); }; auto endPosition = std::remove_if(program.begin(), program. end(), removeWhitespaceFunction); program.erase(endPosition, program.end()); // Remove comments. while (true) { auto const commentStart = program.find('`'); if (commentStart == std::string::npos) { break; } auto const commentEnd = program.find('`', commentStart + 1); if (commentEnd == std::string::npos) { throw PancakePanic(PanicType::InvalidLanguage, "Unmatched comment."); } program.erase(commentStart, commentEnd - commentStart + 1); } } }; } #endif
36.958525
147
0.44655
MattBolitho
618ed408c257072ce00f0b9db8161a43f2bb82f5
14,922
cpp
C++
src/voxel_grid_plugin.cpp
kanishkaganguly/UR10VoxelGrid
b57d7b2a064f6a6dc6415c49d30546ad190fb119
[ "BSD-3-Clause" ]
null
null
null
src/voxel_grid_plugin.cpp
kanishkaganguly/UR10VoxelGrid
b57d7b2a064f6a6dc6415c49d30546ad190fb119
[ "BSD-3-Clause" ]
null
null
null
src/voxel_grid_plugin.cpp
kanishkaganguly/UR10VoxelGrid
b57d7b2a064f6a6dc6415c49d30546ad190fb119
[ "BSD-3-Clause" ]
null
null
null
// // Created by Kanishka Ganguly on 6/4/19. // Copyright (c) 2019 Amazon Robotics. All rights reserved. // #include "../include/voxel_grid_plugin.hpp" namespace gazebo { void VoxelGridPlugin::Load(physics::WorldPtr _world, sdf::ElementPtr _sdf) { spdlog::get("file_logger")->info("[{}]: {}.", __FUNCTION__, "Starting Voxel Grid Plugin"); // Store the pointer to the world, model and SDF VoxelGridPlugin::world = _world; VoxelGridPlugin::sdf = _sdf; // Setup visualization VoxelGridPlugin::grid_visualizer = VoxelGridVisualizer(); // Start VoxelGridInterface voxel_grid_interface.Init(grid_ptr); // Start ModelControlInterface model_control_interface.Init(VoxelGridPlugin::world); // WorldUpdate event VoxelGridPlugin::update_connection = event::Events::ConnectWorldUpdateEnd( std::bind(&VoxelGridPlugin::OnUpdate, this)); } void VoxelGridPlugin::IsRobotLoaded() { // Wait for robot model to be spawned in Gazebo for (auto model:VoxelGridPlugin::world->GetModels()) { if (VoxelGridPlugin::robot_model_name.compare(model->GetName()) == 0) { spdlog::get("file_logger")->info("[{}]: {}.", __FUNCTION__, "Robot has been loaded"); VoxelGridPlugin::robot_loaded = true; } } } void VoxelGridPlugin::OnWorldReady() { // Access robot model and get all links in model spdlog::get("file_logger")->info("[{}]: {}.", __FUNCTION__, "Setting up robot"); VoxelGridPlugin::robot_model = VoxelGridPlugin::world->GetModel(robot_model_name); // Setup robot VoxelGridPlugin::InitializeRobotState(); // Update robot map VoxelGridPlugin::UpdateRobotMap(true); // Done VoxelGridPlugin::world_ready = true; } void VoxelGridPlugin::InitializeRobotState() { spdlog::get("file_logger")->info("[{}]: {}.", __FUNCTION__, "Initializing robot state"); for (auto &link:VoxelGridPlugin::robot_model->GetLinks()) { spdlog::get("file_logger")->info("[{}]: Initializing link {}.", __FUNCTION__, link->GetName()); // Empty box with some default data std::shared_ptr<Box> box_ptr = std::make_shared<Box>(); box_ptr->SetName(link->GetName()); // Right face placeholder std::array<Eigen::Vector4f, 4> right_face; // Left face placeholder std::array<Eigen::Vector4f, 4> left_face; // Get bounding box for link math::Box cbox = link->GetCollisionBoundingBox(); // Get canonical positions utils.GetCanonicalPositionsWithAxisMapping(link->GetName(), cbox, left_face, right_face); // Set all the data box_ptr->SetCanonical("left", left_face); box_ptr->SetCanonical("right", right_face); // Set box data VoxelGridPlugin::robot_state.push_back(box_ptr); } } void VoxelGridPlugin::InitializeObstacleState() { // Update every iteration_skip times if (VoxelGridPlugin::world->GetIterations() % VoxelGridPlugin::iteration_skip == 0) { spdlog::get("file_logger")->info("[{}]: {}.", __FUNCTION__, "Updating obstacle list"); // Make a list of all models that are "obstacles" VoxelGridPlugin::world_obstacle_set.clear(); for (auto &model:VoxelGridPlugin::world->GetModels()) { std::string model_name = model->GetName(); // Check if model is an obstacle std::size_t is_obstacle = model_name.find(VoxelGridPlugin::obstacle_model_prefix); if (is_obstacle != std::string::npos) { // Find attached contact sensor sensors::Sensor_V sensors = mgr->GetSensors(); for (const auto &sensor:sensors) { sensors::ContactSensorPtr contact_sensor = std::dynamic_pointer_cast<sensors::ContactSensor>(sensor); VoxelGridPlugin::update_sensor = contact_sensor->ConnectUpdated(std::bind(&VoxelGridPlugin::OnSensorUpdate, this)); spdlog::get("file_logger")->info("[{}]: {} {}.", __FUNCTION__, "Registering callback for", contact_sensor->Name()); } // Save filtered obstacles to list VoxelGridPlugin::world_obstacle_set.insert(model_name); } } // Compare local set and world set, both ways std::set<std::string> diff_world_local, diff_local_world; // Items in world, not in local utils.CompareSets(VoxelGridPlugin::world_obstacle_set, VoxelGridPlugin::local_obstacle_set, diff_world_local); // Items in local, not in world utils.CompareSets(VoxelGridPlugin::local_obstacle_set, VoxelGridPlugin::world_obstacle_set, diff_local_world); // Check whether to add from local list or remove // Synchronizes both world and local obstacle lists if (diff_world_local.size() > 0) { spdlog::get("file_logger")->info("[{}]: {}.", __FUNCTION__, "Adding to local obstacle set"); utils.UpdateList(VoxelGridPlugin::local_obstacle_set, diff_world_local, true); } else if (diff_local_world.size() > 0) { spdlog::get("file_logger")->info("[{}]: {}.", __FUNCTION__, "Removing from local obstacle set"); utils.UpdateList(VoxelGridPlugin::local_obstacle_set, diff_local_world, false); } assert(VoxelGridPlugin::local_obstacle_set.size() == VoxelGridPlugin::world_obstacle_set.size()); spdlog::get("file_logger")->info("[{}]: {}.", __FUNCTION__, "Synchronized local and world obstacles"); // Compare local list of obstacles and list of obstacles in voxel grid std::vector<std::string> diff_list_state, diff_state_list; // Items in state, not in list utils.CompareSets(VoxelGridPlugin::obstacle_state, VoxelGridPlugin::local_obstacle_set, diff_state_list); // Items in list, not in state utils.CompareSets(VoxelGridPlugin::local_obstacle_set, VoxelGridPlugin::obstacle_state, diff_list_state); // Check whether to add to grid or remove // Synchronizes both local list of obstacles and voxel grid if (diff_state_list.size() > 0) { spdlog::get("file_logger")->info("[{}]: {}.", __FUNCTION__, "Removing from state vector"); // Make sure to clear voxel grid before deleting object for (const std::string &to_delete:diff_state_list) { std::shared_ptr<Box> box_ptr = utils.GetBoxStateByName(to_delete, VoxelGridPlugin::obstacle_state); std::vector<Eigen::Vector3i> nodes_hit = box_ptr->GetNodesHit(); for (auto &hit:nodes_hit) { VoxelGridPlugin::grid_ptr->SetVoxelState(hit, VoxelGridPlugin::grid_ptr->CELL_STATE::FREE); } } // Now delete the obstacle utils.UpdateList(VoxelGridPlugin::obstacle_state, diff_state_list, false); } else if (diff_list_state.size() > 0) { spdlog::get("file_logger")->info("[{}]: {}.", __FUNCTION__, "Adding to state vector"); utils.UpdateList(VoxelGridPlugin::obstacle_state, diff_list_state, true); // Set canonical positions for left and right faces for (const auto &box_ptr:VoxelGridPlugin::obstacle_state) { // Get bounding box for obstacle math::Box cbox = VoxelGridPlugin::world->GetModel(box_ptr->GetName())->GetCollisionBoundingBox(); // Right and left face placeholder std::array<Eigen::Vector4f, 4> left_face, right_face; // Get canonical positions utils.GetCanonicalPositionsNoAxisMapping(box_ptr->GetName(), cbox, left_face, right_face); // Set all the data box_ptr->SetCanonical("left", left_face); box_ptr->SetCanonical("right", right_face); } spdlog::get("file_logger")->info("[{}]: {}.", __FUNCTION__, "Updated canonical poses"); } spdlog::get("file_logger")->info("[{}]: {}.", __FUNCTION__, "Synchronized local obstacles and voxel grid objects"); } } void VoxelGridPlugin::UpdateObstacleMap(const bool &force) { if (force || VoxelGridPlugin::world->GetIterations() % VoxelGridPlugin::iteration_skip == 0) { spdlog::get("file_logger")->info("[{}]: {}.", __FUNCTION__, "Updating obstacle map"); for (const auto &box_ptr:VoxelGridPlugin::obstacle_state) { spdlog::get("file_logger")->info("[{}]: Processing link {}.", __FUNCTION__, box_ptr->GetName()); // Get model and pose from Gazebo physics::ModelPtr model = VoxelGridPlugin::world->GetModel(box_ptr->GetName()); physics::Link_V links = model->GetLinks(); physics::LinkPtr link = links[0]; math::Pose obstacle_pose = link->GetWorldPose(); math::Box obstacle_box = link->GetCollisionBoundingBox(); // ================ Transform canonical positions to world positions =======================// std::array<Eigen::Vector4f, 4> transformed_left_corners, transformed_right_corners; utils.TransformCanonicalToWorld(obstacle_pose.rot, obstacle_box.GetCenter(), box_ptr->GetCanonical("left"), box_ptr->GetCanonical("right"), transformed_left_corners, transformed_right_corners); // ================ Raycast from corners of left face to right face ========================// // Clear voxel grid for (auto &hit:box_ptr->GetNodesHit()) { VoxelGridPlugin::grid_ptr->SetVoxelState(hit, VoxelGridPlugin::grid_ptr->CELL_STATE::FREE); } // Raycast from corners of left face to corresponding corner in right face std::vector<Eigen::Vector3i> hit_nodes; Eigen::Vector3f left_point, right_point; assert(transformed_left_corners.size() == transformed_right_corners.size()); for (int i = 0; i < transformed_left_corners.size(); ++i) { // Get translation component from transformation matrix left_point = transformed_left_corners[i].head(3); right_point = transformed_right_corners[i].head(3); try { // Convert points from world coordinates to grid coordinates Eigen::Vector3i start_point = VoxelGridPlugin::grid_ptr->WorldToGrid(left_point); Eigen::Vector3i end_point = VoxelGridPlugin::grid_ptr->WorldToGrid(right_point); // Does raycasting VoxelGridPlugin::grid_ptr->GetHitNodes(start_point, end_point, hit_nodes); } catch (std::string &e) { spdlog::get("file_logger")->error("[{}]: {}.", __FUNCTION__, e); } // Set new raycast hits to occupied for (auto &hit:hit_nodes) { VoxelGridPlugin::grid_ptr->SetVoxelState(hit, VoxelGridPlugin::grid_ptr->CELL_STATE::OCCUPIED); } // Update nodes hit box_ptr->SetNodesHit(hit_nodes); } } } } void VoxelGridPlugin::UpdateRobotMap(const bool &force) { if (force || VoxelGridPlugin::world->GetIterations() % VoxelGridPlugin::iteration_skip == 0) { spdlog::get("file_logger")->info("[{}]: {}.", __FUNCTION__, "Updating robot map"); Eigen::IOFormat CleanFmt(4, 0, ", ", "\n", "[", "]"); // Loop through all link states for (const auto &box_ptr:VoxelGridPlugin::robot_state) { spdlog::get("file_logger")->info("[{}]: Processing link {}.", __FUNCTION__, box_ptr->GetName()); // Get link pose from Gazebo physics::LinkPtr link = VoxelGridPlugin::robot_model->GetLink(box_ptr->GetName()); math::Pose link_pose = link->GetWorldPose(); math::Box link_box = link->GetCollisionBoundingBox(); // ================ Transform canonical positions to world positions =======================// std::array<Eigen::Vector4f, 4> transformed_left_corners, transformed_right_corners; utils.TransformCanonicalToWorld(link_pose.rot, link_box.GetCenter(), box_ptr->GetCanonical("left"), box_ptr->GetCanonical("right"), transformed_left_corners, transformed_right_corners); // ================ Raycast from corners of left face to right face ========================// // Clear voxel grid for (auto &hit:box_ptr->GetNodesHit()) { VoxelGridPlugin::grid_ptr->SetVoxelState(hit, VoxelGridPlugin::grid_ptr->CELL_STATE::FREE); } // Raycast from corners of left face to corresponding corner in right face std::vector<Eigen::Vector3i> hit_nodes; Eigen::Vector3f left_point, right_point; assert(transformed_left_corners.size() == transformed_right_corners.size()); for (int i = 0; i < transformed_left_corners.size(); ++i) { // Get translation component from transformation matrix left_point = transformed_left_corners[i].head(3); right_point = transformed_right_corners[i].head(3); try { // Convert points from world coordinates to grid coordinates Eigen::Vector3i start_point = VoxelGridPlugin::grid_ptr->WorldToGrid(left_point); Eigen::Vector3i end_point = VoxelGridPlugin::grid_ptr->WorldToGrid(right_point); // Does raycasting VoxelGridPlugin::grid_ptr->GetHitNodes(start_point, end_point, hit_nodes); } catch (std::string &e) { spdlog::get("file_logger")->error("[{}]: {}.", __FUNCTION__, e); } // Set new raycast hits to occupied for (auto &hit:hit_nodes) { VoxelGridPlugin::grid_ptr->SetVoxelState(hit, VoxelGridPlugin::grid_ptr->CELL_STATE::ROBOT); } // Update nodes hit box_ptr->SetNodesHit(hit_nodes); } } spdlog::get("file_logger")->info("[{}]: \n", __FUNCTION__); } } void VoxelGridPlugin::OnSensorUpdate() { // Update collision data sensors::Sensor_V sensors = VoxelGridPlugin::mgr->GetSensors(); for (const auto &sensor:sensors) { sensors::ContactSensorPtr contact_sensor = std::dynamic_pointer_cast<sensors::ContactSensor>(sensor); for (int i = 0; i < contact_sensor->GetCollisionCount(); i++) { spdlog::get("file_logger")->info("[{}]: Fetching contact data for {}.", __FUNCTION__, contact_sensor->Name()); std::string collision_name = contact_sensor->GetCollisionName(i); std::map<std::string, physics::Contact> contacts = contact_sensor->Contacts(collision_name); if (contacts.size() == 0) { spdlog::get("file_logger")->info("[{}]: No contacts detected", __FUNCTION__); } else { for (const auto &contact:contacts) { physics::Collision *first_body = contact.second.collision1; physics::Collision *second_body = contact.second.collision2; spdlog::get("file_logger")->error("[{}]: Detected contact between {} and {}.", __FUNCTION__, first_body->GetName(), second_body->GetName()); } } } } } void VoxelGridPlugin::OnUpdate() { int iters = VoxelGridPlugin::world->GetIterations(); if (iters % 5000 == 0) { spdlog::get("file_logger")->info("[{}]: {} = {}.", __FUNCTION__, "Simulator iterations", std::to_string(iters)); } // Check if robot has been loaded if (!VoxelGridPlugin::robot_loaded) { VoxelGridPlugin::IsRobotLoaded(); } // If robot is loaded, initialize everything if (iters > VoxelGridPlugin::iteration_skip && VoxelGridPlugin::robot_loaded) { std::call_once(VoxelGridPlugin::world_ready_flag, std::bind(&VoxelGridPlugin::OnWorldReady, this)); } // Main update logic goes here if (VoxelGridPlugin::robot_loaded && VoxelGridPlugin::world_ready) { // Check for and update obstacles VoxelGridPlugin::InitializeObstacleState(); // Update map with new robot state VoxelGridPlugin::UpdateRobotMap(); // Update map with new obstacle states VoxelGridPlugin::UpdateObstacleMap(); // Convert voxel grid to cloud VoxelGridPlugin::grid_visualizer.VoxelGridToPointCloud(*VoxelGridPlugin::grid_ptr); VoxelGridPlugin::grid_visualizer.ShowGrid(); } } GZ_REGISTER_WORLD_PLUGIN(VoxelGridPlugin); };
46.341615
146
0.69689
kanishkaganguly
61938a6b137e556efc0e4f6500451c0377c1f496
9,871
cpp
C++
test/test_softmax.in.cpp
kthur/he-transformer
5d3294473edba10f2789197043b8d8704409719e
[ "Apache-2.0" ]
null
null
null
test/test_softmax.in.cpp
kthur/he-transformer
5d3294473edba10f2789197043b8d8704409719e
[ "Apache-2.0" ]
null
null
null
test/test_softmax.in.cpp
kthur/he-transformer
5d3294473edba10f2789197043b8d8704409719e
[ "Apache-2.0" ]
null
null
null
//***************************************************************************** // Copyright 2018-2019 Intel 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 "he_op_annotations.hpp" #include "ngraph/ngraph.hpp" #include "seal/he_seal_backend.hpp" #include "test_util.hpp" #include "util/all_close.hpp" #include "util/ndarray.hpp" #include "util/test_control.hpp" #include "util/test_tools.hpp" static std::string s_manifest = "${MANIFEST}"; auto softmax_test = [](const ngraph::Shape& shape_a, const ngraph::AxisSet& axes, const std::vector<float>& input_a, const std::vector<float>& output, const bool arg1_encrypted, const bool complex_packing, const bool packed) { auto backend = ngraph::runtime::Backend::create("${BACKEND_NAME}"); auto he_backend = static_cast<ngraph::he::HESealBackend*>(backend.get()); if (complex_packing) { he_backend->update_encryption_parameters( ngraph::he::HESealEncryptionParameters:: default_complex_packing_parms()); } auto a = std::make_shared<ngraph::op::Parameter>(ngraph::element::f32, shape_a); auto t = std::make_shared<ngraph::op::Softmax>(a, axes); auto f = std::make_shared<ngraph::Function>(t, ngraph::ParameterVector{a}); a->set_op_annotations( ngraph::test::he::annotation_from_flags(false, arg1_encrypted, packed)); auto t_a = ngraph::test::he::tensor_from_flags(*he_backend, shape_a, arg1_encrypted, packed); auto t_result = ngraph::test::he::tensor_from_flags( *he_backend, t->get_shape(), arg1_encrypted, packed); copy_data(t_a, input_a); auto handle = backend->compile(f); if (packed && (axes.find(0) != axes.end())) { EXPECT_ANY_THROW((handle->call_with_validate({t_result}, {t_a}))); } else { handle->call_with_validate({t_result}, {t_a}); EXPECT_TRUE(ngraph::test::he::all_close(read_vector<float>(t_result), output, 1e-3f)); } }; NGRAPH_TEST(${BACKEND_NAME}, softmax_all_plain_real_unpacked) { auto d = expf(-3) + expf(-2) + expf(-1) + expf(0) + expf(1) + expf(2); softmax_test(ngraph::Shape{2, 3}, ngraph::AxisSet{0, 1}, std::vector<float>{-3, -2, -1, 0, 1, 2}, std::vector<float>{expf(-3) / d, expf(-2) / d, expf(-1) / d, expf(0) / d, expf(1) / d, expf(2) / d}, false, false, false); } NGRAPH_TEST(${BACKEND_NAME}, softmax_all_plain_real_packed) { auto d = expf(-3) + expf(-2) + expf(-1) + expf(0) + expf(1) + expf(2); softmax_test(ngraph::Shape{2, 3}, ngraph::AxisSet{0, 1}, std::vector<float>{-3, -2, -1, 0, 1, 2}, std::vector<float>{expf(-3) / d, expf(-2) / d, expf(-1) / d, expf(0) / d, expf(1) / d, expf(2) / d}, false, false, true); } NGRAPH_TEST(${BACKEND_NAME}, softmax_all_plain_complex_unpacked) { auto d = expf(-3) + expf(-2) + expf(-1) + expf(0) + expf(1) + expf(2); softmax_test(ngraph::Shape{2, 3}, ngraph::AxisSet{0, 1}, std::vector<float>{-3, -2, -1, 0, 1, 2}, std::vector<float>{expf(-3) / d, expf(-2) / d, expf(-1) / d, expf(0) / d, expf(1) / d, expf(2) / d}, false, true, false); } NGRAPH_TEST(${BACKEND_NAME}, softmax_all_plain_complex_packed) { auto d = expf(-3) + expf(-2) + expf(-1) + expf(0) + expf(1) + expf(2); softmax_test(ngraph::Shape{2, 3}, ngraph::AxisSet{0, 1}, std::vector<float>{-3, -2, -1, 0, 1, 2}, std::vector<float>{expf(-3) / d, expf(-2) / d, expf(-1) / d, expf(0) / d, expf(1) / d, expf(2) / d}, false, true, true); } NGRAPH_TEST(${BACKEND_NAME}, softmax_all_cipher_real_unpacked) { auto d = expf(-3) + expf(-2) + expf(-1) + expf(0) + expf(1) + expf(2); softmax_test(ngraph::Shape{2, 3}, ngraph::AxisSet{0, 1}, std::vector<float>{-3, -2, -1, 0, 1, 2}, std::vector<float>{expf(-3) / d, expf(-2) / d, expf(-1) / d, expf(0) / d, expf(1) / d, expf(2) / d}, true, false, false); } NGRAPH_TEST(${BACKEND_NAME}, softmax_all_cipher_real_packed) { auto d = expf(-3) + expf(-2) + expf(-1) + expf(0) + expf(1) + expf(2); softmax_test(ngraph::Shape{2, 3}, ngraph::AxisSet{0, 1}, std::vector<float>{-3, -2, -1, 0, 1, 2}, std::vector<float>{expf(-3) / d, expf(-2) / d, expf(-1) / d, expf(0) / d, expf(1) / d, expf(2) / d}, true, false, true); } NGRAPH_TEST(${BACKEND_NAME}, softmax_all_cipher_complex_unpacked) { auto d = expf(-3) + expf(-2) + expf(-1) + expf(0) + expf(1) + expf(2); softmax_test(ngraph::Shape{2, 3}, ngraph::AxisSet{0, 1}, std::vector<float>{-3, -2, -1, 0, 1, 2}, std::vector<float>{expf(-3) / d, expf(-2) / d, expf(-1) / d, expf(0) / d, expf(1) / d, expf(2) / d}, true, true, false); } NGRAPH_TEST(${BACKEND_NAME}, softmax_all_cipher_complex_packed) { auto d = expf(-3) + expf(-2) + expf(-1) + expf(0) + expf(1) + expf(2); softmax_test(ngraph::Shape{2, 3}, ngraph::AxisSet{0, 1}, std::vector<float>{-3, -2, -1, 0, 1, 2}, std::vector<float>{expf(-3) / d, expf(-2) / d, expf(-1) / d, expf(0) / d, expf(1) / d, expf(2) / d}, true, true, true); } NGRAPH_TEST(${BACKEND_NAME}, softmax_axis_plain_real_unpacked) { auto d0 = expf(-10) + expf(-20) + expf(-30); auto d1 = expf(-40) + expf(-50) + expf(-60); softmax_test( ngraph::Shape{2, 3}, ngraph::AxisSet{1}, std::vector<float>{-10, -20, -30, -40, -50, -60}, std::vector<float>{expf(-10) / d0, expf(-20) / d0, expf(-30) / d0, expf(-40) / d1, expf(-50) / d1, expf(-60) / d1}, false, false, false); } NGRAPH_TEST(${BACKEND_NAME}, softmax_axis_plain_real_packed) { auto d0 = expf(-10) + expf(-20) + expf(-30); auto d1 = expf(-40) + expf(-50) + expf(-60); softmax_test( ngraph::Shape{2, 3}, ngraph::AxisSet{1}, std::vector<float>{-10, -20, -30, -40, -50, -60}, std::vector<float>{expf(-10) / d0, expf(-20) / d0, expf(-30) / d0, expf(-40) / d1, expf(-50) / d1, expf(-60) / d1}, false, false, true); } NGRAPH_TEST(${BACKEND_NAME}, softmax_axis_plain_complex_unpacked) { auto d0 = expf(-10) + expf(-20) + expf(-30); auto d1 = expf(-40) + expf(-50) + expf(-60); softmax_test( ngraph::Shape{2, 3}, ngraph::AxisSet{1}, std::vector<float>{-10, -20, -30, -40, -50, -60}, std::vector<float>{expf(-10) / d0, expf(-20) / d0, expf(-30) / d0, expf(-40) / d1, expf(-50) / d1, expf(-60) / d1}, false, true, false); } NGRAPH_TEST(${BACKEND_NAME}, softmax_axis_plain_complex_packed) { auto d0 = expf(-10) + expf(-20) + expf(-30); auto d1 = expf(-40) + expf(-50) + expf(-60); softmax_test( ngraph::Shape{2, 3}, ngraph::AxisSet{1}, std::vector<float>{-10, -20, -30, -40, -50, -60}, std::vector<float>{expf(-10) / d0, expf(-20) / d0, expf(-30) / d0, expf(-40) / d1, expf(-50) / d1, expf(-60) / d1}, false, true, true); } NGRAPH_TEST(${BACKEND_NAME}, softmax_axis_cipher_real_unpacked) { auto d0 = expf(-10) + expf(-20) + expf(-30); auto d1 = expf(-40) + expf(-50) + expf(-60); softmax_test( ngraph::Shape{2, 3}, ngraph::AxisSet{1}, std::vector<float>{-10, -20, -30, -40, -50, -60}, std::vector<float>{expf(-10) / d0, expf(-20) / d0, expf(-30) / d0, expf(-40) / d1, expf(-50) / d1, expf(-60) / d1}, true, false, false); } NGRAPH_TEST(${BACKEND_NAME}, softmax_axis_cipher_real_packed) { auto d0 = expf(-10) + expf(-20) + expf(-30); auto d1 = expf(-40) + expf(-50) + expf(-60); softmax_test( ngraph::Shape{2, 3}, ngraph::AxisSet{1}, std::vector<float>{-10, -20, -30, -40, -50, -60}, std::vector<float>{expf(-10) / d0, expf(-20) / d0, expf(-30) / d0, expf(-40) / d1, expf(-50) / d1, expf(-60) / d1}, true, false, true); } NGRAPH_TEST(${BACKEND_NAME}, softmax_axis_cipher_complex_unpacked) { auto d0 = expf(-10) + expf(-20) + expf(-30); auto d1 = expf(-40) + expf(-50) + expf(-60); softmax_test( ngraph::Shape{2, 3}, ngraph::AxisSet{1}, std::vector<float>{-10, -20, -30, -40, -50, -60}, std::vector<float>{expf(-10) / d0, expf(-20) / d0, expf(-30) / d0, expf(-40) / d1, expf(-50) / d1, expf(-60) / d1}, true, true, false); } NGRAPH_TEST(${BACKEND_NAME}, softmax_axis_cipher_complex_packed) { auto d0 = expf(-10) + expf(-20) + expf(-30); auto d1 = expf(-40) + expf(-50) + expf(-60); softmax_test( ngraph::Shape{2, 3}, ngraph::AxisSet{1}, std::vector<float>{-10, -20, -30, -40, -50, -60}, std::vector<float>{expf(-10) / d0, expf(-20) / d0, expf(-30) / d0, expf(-40) / d1, expf(-50) / d1, expf(-60) / d1}, true, true, true); }
43.484581
79
0.541283
kthur
6193b98bb028afd79134bbc3da1300e651f7e23c
13,473
cpp
C++
src/core/FlagHandler.cpp
hirre/maptag
9d855c5773128596a5ffed351518709775fbaca8
[ "MIT" ]
null
null
null
src/core/FlagHandler.cpp
hirre/maptag
9d855c5773128596a5ffed351518709775fbaca8
[ "MIT" ]
1
2020-05-17T17:34:51.000Z
2020-05-17T17:34:51.000Z
src/core/FlagHandler.cpp
hirre/maptag
9d855c5773128596a5ffed351518709775fbaca8
[ "MIT" ]
null
null
null
/* * FlagHandler.cpp * * Handler class that handles input from the command line. * Handles: * - write (K,V) * - delete (K,V) * - print (K,V) * * Created on: 5 maj 2013 * Author: Hirad Asadi * E-mail: hirad.asadi@gmail.com */ #include <stdlib.h> #include <sstream> #include <boost/filesystem.hpp> #include "FlagHandler.hpp" #include "Debug.hpp" #include "Helper.hpp" using namespace std; namespace maptag { /* * Main constructor. */ FlagHandler::FlagHandler() { // Init db to null database_ = NULL; // No error per default e_.err = NO_ERROR; e_.msg = ""; // Home folder path + database stringstream ss; ss << getHomeFolder() << PATH_SEPARATOR << ".maptag"; path_ = new string(ss.str()); #ifdef DEBUG debug::dbgPrint("Database: " + *path_); #endif } /* * Destructor. */ FlagHandler::~FlagHandler() { // Close if not closed if (database_) sqlite3_close(database_); // Delete path delete path_; } /* * Initialize the database. Creates the needed tables if they do not exist. */ bool FlagHandler::initDB() { const char* createTableSQL = "CREATE TABLE IF NOT EXISTS " "key_val(id INTEGER PRIMARY KEY, " "key TEXT COLLATE NOCASE, " "val TEXT COLLATE NOCASE, " "path TEXT COLLATE NOCASE, " "dt TEXT, UNIQUE(key, path));"; const char* createIndexSQL = "CREATE INDEX IF NOT EXISTS key_val_idx ON key_val (key, path);"; sqlite3_stmt* statement; // Prepare to create table tag if not exists if (sqlite3_prepare_v2(database_, createTableSQL, -1, &statement, 0) != SQLITE_OK) return false; // Execute sqlite3_step(statement); // Prepare to create index tag if not exists if (sqlite3_prepare_v2(database_, createIndexSQL, -1, &statement, 0) != SQLITE_OK) return false; // Execute sqlite3_step(statement); // Finalize sqlite3_finalize(statement); return true; } /* * Method to process input from the command line. Returns true on success. */ bool FlagHandler::processInput(const vector<string>& argVec, const Flag& flag, const vector<Flag>& extraFlags) { // Check if database can be opened if (sqlite3_open(path_->c_str(), &database_) != SQLITE_OK) { e_.err = DB_CONNECTION_OR_CREATION_ERROR; e_.msg = "Could not connect or create DB in home folder"; return false; } // Init db if (!initDB()) { e_.err = DB_CONNECTION_OR_CREATION_ERROR; e_.msg = "Could not initialize DB"; return false; } bool error = false; switch (flag) { case WRITE_KEY_VALUE: #ifdef DEBUG debug::dbgPrint("PROCESSING: write key-value"); #endif // Write key-value if (!writeKV(argVec, extraFlags)) error = true; break; case DELETE_KEY_VALUE: #ifdef DEBUG debug::dbgPrint("PROCESSING: delete key-value"); #endif // Delete key-value if (!deleteKV(argVec, extraFlags)) error = true; break; case PRINT_KEY_VALUE: #ifdef DEBUG debug::dbgPrint("PROCESSING: print key-value"); #endif // Print key-value if (!printKV(argVec, extraFlags)) error = true; break; // Ignore case ALL: break; } // Close db sqlite3_close(database_); return !error; } /* * This method writes a key-value to the database associated with file(s)/folder(s). */ bool FlagHandler::writeKV(const vector<string>& fVec, const vector<Flag>& extraFlags) { // Key string key = fVec[0]; // Value string value = fVec[1]; // Verify key string if (!verifyInput(key, REGEX_MAIN)) { e_.err = VERIFICATION_ERROR; e_.msg = "Key can only contain numbers, letters and \"_\""; return false; } unsigned int i = 2; // Value empty if (fVec.size() == 2) { i = 1; value = ""; } // Go through path(s) for (; i < fVec.size(); i++) { // File/folder string string f = fVec[i]; // Path which is to be associated with key boost::filesystem::path p(f); // Check if path exists if (boost::filesystem::is_directory(p) || boost::filesystem::exists(p)) { sqlite3_stmt* statement; stringstream ss; ss << "INSERT INTO key_val (key, val, path, dt) VALUES('" << key << "', '" << value << "', '" << boost::filesystem::canonical(p).string() << "', datetime('now'));"; // Prepare statement if (sqlite3_prepare_v2(database_, ss.str().c_str(), -1, &statement, 0) != SQLITE_OK) { e_.err = STATEMENT_PREPARATION_ERROR; e_.msg = string("Could not prepare statement [") + ss.str() + string("]"); return false; } // Execute sqlite3_step(statement); // Finalize sqlite3_finalize(statement); } // NO PATH else { e_.err = PATH_DOES_NOT_EXIST_ERROR; e_.msg = string("Path (") + p.string() + string(") does not exist"); return false; } } // FOR return true; } /* * This method deletes a key-value in the database associated with file(s)/folder(s). */bool FlagHandler::deleteKV(const vector<string>& fVec, const vector<Flag>& extraFlags) { // "All" flag set bool all = find(extraFlags.begin(), extraFlags.end(), ALL) != extraFlags.end(); // Removed rows bool removedRows = false; // Key string key = (all) ? "" : fVec[0]; // Verify key string if (!verifyInput(key, REGEX_MAIN_ALLOW_PERCENTAGE)) { e_.err = VERIFICATION_ERROR; e_.msg = "Key can only contain numbers, letters and \"_\""; return false; } #ifndef TEST // Safety question if (!q()) return false; #endif // Remove key with no path if (fVec.size() == 1 && !all) { sqlite3_stmt* statement; stringstream ss; ss << "DELETE FROM key_val WHERE key LIKE '" << key << "'"; // Prepare statement if (sqlite3_prepare_v2(database_, ss.str().c_str(), -1, &statement, 0) != SQLITE_OK) { e_.err = STATEMENT_PREPARATION_ERROR; e_.msg = string("Could not prepare statement [") + ss.str() + string("]"); return false; } // Execute sqlite3_step(statement); if (sqlite3_changes(database_) != 0) removedRows = true; // Finalize sqlite3_finalize(statement); return (removedRows) ? true : false; } // IF NO PATH unsigned int i = (all) ? 0 : 1; // Remove keys with paths // Go through path(s) for (; i < fVec.size(); i++) { // File/folder string string f = fVec[i]; // Path which is to be removed boost::filesystem::path p(f); // Check if path exists if (boost::filesystem::is_directory(p) || boost::filesystem::exists(p)) { sqlite3_stmt* statement; stringstream ss; // Delete all keys if (all) ss << "DELETE FROM key_val WHERE path = '" << boost::filesystem::canonical(p).string() << "';"; else // Delete specific tags from file(s)/folder(s) ss << "DELETE FROM key_val WHERE key LIKE '" << key << "' AND path = '" << boost::filesystem::canonical(p).string() << "';"; // Prepare statement if (sqlite3_prepare_v2(database_, ss.str().c_str(), -1, &statement, 0) != SQLITE_OK) { e_.err = STATEMENT_PREPARATION_ERROR; e_.msg = string("Could not prepare statement [") + ss.str() + string("]"); return false; } // Execute sqlite3_step(statement); if (sqlite3_changes(database_) != 0) removedRows = true; // Finalize sqlite3_finalize(statement); } // NO PATH else { e_.err = PATH_DOES_NOT_EXIST_ERROR; e_.msg = string("Path (") + p.string() + string(") does not exist"); return false; } } // FOR return (removedRows) ? true : false; } /* * This method prints key-values associated with file(s)/folder(s). */ bool FlagHandler::printKV(const vector<string>& fVec, const vector<Flag>& extraFlags) { // "All" flag set bool all = find(extraFlags.begin(), extraFlags.end(), ALL) != extraFlags.end(); bool foundKey = false; // Key string key = (all) ? "" : fVec[0]; // Verify key string if (!verifyInput(key, REGEX_MAIN_ALLOW_PERCENTAGE)) { e_.err = VERIFICATION_ERROR; e_.msg = "Key can only contain numbers, letters and \"_\""; return false; } // Print key-value with no path if (fVec.size() == 1 && !all) { sqlite3_stmt* statement; stringstream ss; ss << "SELECT * FROM key_val WHERE key LIKE '" << key << "' ORDER BY dt COLLATE NOCASE DESC"; // Prepare statement if (sqlite3_prepare_v2(database_, ss.str().c_str(), -1, &statement, 0) != SQLITE_OK) { e_.err = STATEMENT_PREPARATION_ERROR; e_.msg = string("Could not prepare statement [") + ss.str() + string("]"); return false; } int result = 0; while (true) { // Execute result = sqlite3_step(statement); // Found row if (result == SQLITE_ROW) { foundKey = true; print_kv(statement); } else { break; } } // WHILE // Finalize sqlite3_finalize(statement); return (!foundKey) ? false : true; } // IF NO PATH unsigned int i = (all) ? 0 : 1; // Print key-value with path(s) // Go through path(s) for (; i < fVec.size(); i++) { // File/folder string string f = fVec[i]; // Path which is to be printed boost::filesystem::path p(f); // Check if path exists if (boost::filesystem::is_directory(p) || boost::filesystem::exists(p)) { sqlite3_stmt* statement; stringstream ss; // Select all if (all) ss << "SELECT * FROM key_val WHERE path = '" << boost::filesystem::canonical(p).string() << "' ORDER BY dt COLLATE NOCASE DESC"; else // Select specific key ss << "SELECT * FROM key_val WHERE key LIKE '" << key << "' AND path = '" << boost::filesystem::canonical(p).string() << "' ORDER BY dt COLLATE NOCASE DESC"; // Prepare statement if (sqlite3_prepare_v2(database_, ss.str().c_str(), -1, &statement, 0) != SQLITE_OK) { e_.err = STATEMENT_PREPARATION_ERROR; e_.msg = string("Could not prepare statement [") + ss.str() + string("]"); return false; } int result = 0; while (true) { // Execute result = sqlite3_step(statement); // Found row if (result == SQLITE_ROW) { foundKey = true; print_kv(statement); } else { break; } } // WHILE // Finalize sqlite3_finalize(statement); } // NO PATH else { e_.err = PATH_DOES_NOT_EXIST_ERROR; e_.msg = string("Path (") + p.string() + string(") does not exist"); return false; } } // FOR return (!foundKey) ? false : true; } /* * This method prints key-values. */ void FlagHandler::print_kv(sqlite3_stmt* statement) { if (statement == NULL) return; // Key string keyStr = (char*) sqlite3_column_text(statement, 1); // Value string valueStr = (char*) sqlite3_column_text(statement, 2); // Path string pathStr = (char*) sqlite3_column_text(statement, 3); // Datetime string dt = (char*) sqlite3_column_text(statement, 4); // Print path(s) found for specific key cout << "@" << keyStr << "\t\"" << valueStr << "\"\t" << pathStr << "\t[" << dt << "]" << endl; } /* * Prints question. */ bool FlagHandler::q() { char yn; cout << "Are you sure (y/n)? "; cin >> yn; if (tolower(yn) != 'y') return false; return true; } /* * Get error, if an error occurred. */ Error FlagHandler::getError() { return e_; } } /* namespace maptag */
24.540984
85
0.514362
hirre
619bfb5d4c420eb3643dc6511f4e921321432617
7,718
cpp
C++
src/dlib/threads/threaded_object_extension.cpp
prathyusha12924/eye-gaze
a80ad54b46e9cef4e743b53aaff035de83f27154
[ "MIT" ]
2,695
2015-01-01T21:13:47.000Z
2022-03-31T04:45:32.000Z
src/dlib/threads/threaded_object_extension.cpp
prathyusha12924/eye-gaze
a80ad54b46e9cef4e743b53aaff035de83f27154
[ "MIT" ]
208
2015-01-23T19:29:07.000Z
2022-02-08T02:55:17.000Z
src/dlib/threads/threaded_object_extension.cpp
prathyusha12924/eye-gaze
a80ad54b46e9cef4e743b53aaff035de83f27154
[ "MIT" ]
567
2015-01-06T19:22:19.000Z
2022-03-21T17:01:04.000Z
// Copyright (C) 2007 Davis E. King (davis@dlib.net) // License: Boost Software License See LICENSE.txt for the full license. #ifndef DLIB_THREADED_OBJECT_EXTENSIOn_CPP #define DLIB_THREADED_OBJECT_EXTENSIOn_CPP #include "threaded_object_extension.h" #include "create_new_thread_extension.h" namespace dlib { // ---------------------------------------------------------------------------------------- threaded_object:: threaded_object ( ): s(m_), id1(0), is_running_(false), is_alive_(false), should_stop_(false), id_valid(false) { } // ---------------------------------------------------------------------------------------- threaded_object:: ~threaded_object ( ) { DLIB_ASSERT(is_alive() == false, "\tthreaded_object::~threaded_object()" << "\n\tYou have let a threaded object destruct itself before terminating its thread" << "\n\tthis: " << this ); } // ---------------------------------------------------------------------------------------- bool threaded_object:: is_running ( ) const { auto_mutex M(m_); DLIB_ASSERT(id1 != get_thread_id() || id_valid == false, "\tbool threaded_object::is_running()" << "\n\tYou can NOT call this function from the thread that executes threaded_object::thread" << "\n\tthis: " << this ); return is_running_; } // ---------------------------------------------------------------------------------------- bool threaded_object:: is_alive ( ) const { auto_mutex M(m_); DLIB_ASSERT(id1 != get_thread_id() || id_valid == false, "\tbool threaded_object::is_alive()" << "\n\tYou can NOT call this function from the thread that executes threaded_object::thread" << "\n\tthis: " << this ); return is_alive_; } // ---------------------------------------------------------------------------------------- void threaded_object:: wait ( ) const { auto_mutex M(m_); DLIB_ASSERT(id1 != get_thread_id() || id_valid == false, "\tvoid threaded_object::wait()" << "\n\tYou can NOT call this function from the thread that executes threaded_object::thread" << "\n\tthis: " << this ); while (is_alive_) s.wait(); } // ---------------------------------------------------------------------------------------- void threaded_object:: start ( ) { auto_mutex M(m_); DLIB_ASSERT(id1 != get_thread_id() || id_valid == false, "\tvoid threaded_object::start()" << "\n\tYou can NOT call this function from the thread that executes threaded_object::thread" << "\n\tthis: " << this ); if (is_alive_ == false) { if (create_new_thread<threaded_object,&threaded_object::thread_helper>(*this) == false) { is_running_ = false; throw thread_error(); } } is_alive_ = true; is_running_ = true; should_stop_ = false; s.broadcast(); } // ---------------------------------------------------------------------------------------- void threaded_object:: restart ( ) { auto_mutex M(m_); DLIB_ASSERT(id1 != get_thread_id() || id_valid == false, "\tvoid threaded_object::restart()" << "\n\tYou can NOT call this function from the thread that executes threaded_object::thread" << "\n\tthis: " << this ); if (is_alive_ == false) { if (create_new_thread<threaded_object,&threaded_object::thread_helper>(*this) == false) { is_running_ = false; throw thread_error(); } should_respawn_ = false; } else { should_respawn_ = true; } is_alive_ = true; is_running_ = true; should_stop_ = false; s.broadcast(); } // ---------------------------------------------------------------------------------------- void threaded_object:: set_respawn ( ) { auto_mutex M(m_); DLIB_ASSERT(id1 != get_thread_id() || id_valid == false, "\tvoid threaded_object::set_respawn()" << "\n\tYou can NOT call this function from the thread that executes threaded_object::thread" << "\n\tthis: " << this ); should_respawn_ = true; } // ---------------------------------------------------------------------------------------- bool threaded_object:: should_respawn ( ) const { auto_mutex M(m_); DLIB_ASSERT(id1 != get_thread_id() || id_valid == false, "\tbool threaded_object::should_respawn()" << "\n\tYou can NOT call this function from the thread that executes threaded_object::thread" << "\n\tthis: " << this ); return should_respawn_; } // ---------------------------------------------------------------------------------------- void threaded_object:: pause ( ) { auto_mutex M(m_); DLIB_ASSERT(id1 != get_thread_id() || id_valid == false, "\tvoid threaded_object::pause()" << "\n\tYou can NOT call this function from the thread that executes threaded_object::thread" << "\n\tthis: " << this ); is_running_ = false; } // ---------------------------------------------------------------------------------------- void threaded_object:: stop ( ) { auto_mutex M(m_); DLIB_ASSERT(id1 != get_thread_id() || id_valid == false, "\tvoid threaded_object::stop()" << "\n\tYou can NOT call this function from the thread that executes threaded_object::thread" << "\n\tthis: " << this ); should_stop_ = true; is_running_ = false; should_respawn_ = false; s.broadcast(); } // ---------------------------------------------------------------------------------------- bool threaded_object:: should_stop ( ) const { auto_mutex M(m_); DLIB_ASSERT(is_alive_ && id1 == get_thread_id() && id_valid == true, "\tbool threaded_object::should_stop()" << "\n\tYou can only call this function from the thread that executes threaded_object::thread" << "\n\tthis: " << this ); while (is_running_ == false && should_stop_ == false) s.wait(); return should_stop_; } // ---------------------------------------------------------------------------------------- void threaded_object:: thread_helper( ) { #ifdef ENABLE_ASSERTS id1 = get_thread_id(); id_valid = true; #endif while (true) { m_.lock(); should_respawn_ = false; m_.unlock(); thread(); auto_mutex M(m_); if (should_respawn_) continue; #ifdef ENABLE_ASSERTS id_valid = false; #endif is_alive_ = false; is_running_ = false; should_stop_ = false; s.broadcast(); return; } } // ---------------------------------------------------------------------------------------- } #endif // DLIB_THREADED_OBJECT_EXTENSIOn_CPP
27.368794
109
0.438974
prathyusha12924
619ef451f677e592bbe54ddb98f5d5ff7b68faa6
14,882
hpp
C++
Graphics/GraphicsEngineOpenGL/include/ShaderResourceCacheGL.hpp
Zone-organization/DiligentCore
a9091a1848492ae1aecece3a955badf9367b189f
[ "Apache-2.0" ]
398
2016-04-21T03:38:50.000Z
2022-03-23T15:27:31.000Z
Graphics/GraphicsEngineOpenGL/include/ShaderResourceCacheGL.hpp
Zone-organization/DiligentCore
a9091a1848492ae1aecece3a955badf9367b189f
[ "Apache-2.0" ]
275
2017-12-27T04:11:55.000Z
2022-03-30T07:35:11.000Z
Graphics/GraphicsEngineOpenGL/include/ShaderResourceCacheGL.hpp
Zone-organization/DiligentCore
a9091a1848492ae1aecece3a955badf9367b189f
[ "Apache-2.0" ]
139
2017-09-13T06:19:49.000Z
2022-03-28T15:01:20.000Z
/* * Copyright 2019-2021 Diligent Graphics LLC * Copyright 2015-2019 Egor Yusov * * 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. * * In no event and under no legal theory, whether in tort (including negligence), * contract, or otherwise, unless required by applicable law (such as deliberate * and grossly negligent acts) or agreed to in writing, shall any Contributor be * liable for any damages, including any direct, indirect, special, incidental, * or consequential damages of any character arising as a result of this License or * out of the use or inability to use the software (including but not limited to damages * for loss of goodwill, work stoppage, computer failure or malfunction, or any and * all other commercial damages or losses), even if such Contributor has been advised * of the possibility of such damages. */ #pragma once #include <array> #include <vector> #include "BufferGLImpl.hpp" #include "TextureBaseGL.hpp" #include "SamplerGLImpl.hpp" #include "ShaderResourceCacheCommon.hpp" namespace Diligent { // All resources are stored in the continuous memory using the following layout: // // | Cached UBs | Cached Textures | Cached Images | Cached Storage Blocks | // |----------------------------------------------------|--------------------------|---------------------------| // | 0 | 1 | ... | UBCount-1 | 0 | 1 | ...| SmpCount-1 | 0 | 1 | ... | ImgCount-1 | 0 | 1 | ... | SBOCount-1 | // ----------------------------------------------------------------------------------------------------------- // class ShaderResourceCacheGL : public ShaderResourceCacheBase { public: explicit ShaderResourceCacheGL(ResourceCacheContentType ContentType) noexcept : m_ContentType{ContentType} {} ~ShaderResourceCacheGL(); // clang-format off ShaderResourceCacheGL (const ShaderResourceCacheGL&) = delete; ShaderResourceCacheGL& operator = (const ShaderResourceCacheGL&) = delete; ShaderResourceCacheGL (ShaderResourceCacheGL&&) = delete; ShaderResourceCacheGL& operator = (ShaderResourceCacheGL&&) = delete; // clang-format on /// Describes a resource bound to a uniform buffer slot struct CachedUB { /// Strong reference to the buffer RefCntAutoPtr<BufferGLImpl> pBuffer; Uint32 BaseOffset = 0; Uint32 RangeSize = 0; Uint32 DynamicOffset = 0; // In OpenGL dynamic buffers are only those that are not bound as a whole and // can use a dynamic offset, irrespective of the variable type or whether the // buffer is USAGE_DYNAMIC or not. bool IsDynamic() const { return pBuffer && RangeSize < pBuffer->GetDesc().Size; } }; /// Describes a resource bound to a sampler or an image slot struct CachedResourceView { /// We keep strong reference to the view instead of the reference /// to the texture or buffer because this is more efficient from /// performance point of view: this avoids one pair of /// AddStrongRef()/ReleaseStrongRef(). The view holds a strong reference /// to the texture or the buffer, so it makes no difference. RefCntAutoPtr<IDeviceObject> pView; TextureBaseGL* pTexture = nullptr; union { BufferGLImpl* pBuffer = nullptr; // When pTexture == nullptr SamplerGLImpl* pSampler; // When pTexture != nullptr }; CachedResourceView() noexcept {} void Set(RefCntAutoPtr<TextureViewGLImpl>&& pTexView, bool SetSampler) { // Do not null out pSampler as it could've been initialized by PipelineResourceSignatureGLImpl::InitSRBResourceCache! // pSampler = nullptr; // Avoid unnecessary virtual call pTexture = pTexView ? pTexView->GetTexture<TextureBaseGL>() : nullptr; if (pTexView && SetSampler) { pSampler = pTexView->GetSampler<SamplerGLImpl>(); } pView = std::move(pTexView); } void Set(RefCntAutoPtr<BufferViewGLImpl>&& pBufView) { pTexture = nullptr; // Avoid unnecessary virtual call pBuffer = pBufView ? pBufView->GetBuffer<BufferGLImpl>() : nullptr; pView = std::move(pBufView); } }; struct CachedSSBO { /// Strong reference to the buffer RefCntAutoPtr<BufferViewGLImpl> pBufferView; Uint32 DynamicOffset = 0; bool IsDynamic() const { if (pBufferView) { const auto* pBuff = pBufferView->GetBuffer<const BufferGLImpl>(); return pBufferView->GetDesc().ByteWidth < pBuff->GetDesc().Size; } return false; } }; using TResourceCount = std::array<Uint16, 4>; // same as PipelineResourceSignatureGLImpl::TBindings. static size_t GetRequiredMemorySize(const TResourceCount& ResCount); void Initialize(const TResourceCount& Count, IMemoryAllocator& MemAllocator, Uint64 DynamicUBOSlotMask, Uint64 DynamicSSBOSlotMask); void SetUniformBuffer(Uint32 CacheOffset, RefCntAutoPtr<BufferGLImpl>&& pBuff, Uint64 BaseOffset, Uint64 RangeSize) { DEV_CHECK_ERR(BaseOffset + RangeSize <= (pBuff ? pBuff->GetDesc().Size : 0), "The range is out of buffer bounds"); if (pBuff) { if (RangeSize == 0) RangeSize = pBuff->GetDesc().Size - BaseOffset; } auto& UB = GetUB(CacheOffset); UB.pBuffer = std::move(pBuff); UB.BaseOffset = StaticCast<Uint32>(BaseOffset); UB.RangeSize = StaticCast<Uint32>(RangeSize); UB.DynamicOffset = 0; Uint64 UBBit = Uint64{1} << Uint64{CacheOffset}; if (m_DynamicUBOSlotMask & UBBit) { // Only set the flag for those slots that allow dynamic buffers // (i.e. the variable was not created with NO_DYNAMIC_BUFFERS flag). if (UB.IsDynamic()) m_DynamicUBOMask |= UBBit; else m_DynamicUBOMask &= ~UBBit; } else { VERIFY((m_DynamicUBOMask & UBBit) == 0, "Dynamic UBO bit should never be set when corresponding bit in m_DynamicUBOSlotMask is not set"); } UpdateRevision(); } void SetDynamicUBOffset(Uint32 CacheOffset, Uint32 DynamicOffset) { DEV_CHECK_ERR((m_DynamicUBOSlotMask & (Uint64{1} << Uint64{CacheOffset})) != 0, "Attempting to set dynamic offset for a non-dynamic UBO slot"); GetUB(CacheOffset).DynamicOffset = DynamicOffset; } void SetTexture(Uint32 CacheOffset, RefCntAutoPtr<TextureViewGLImpl>&& pTexView, bool SetSampler) { GetTexture(CacheOffset).Set(std::move(pTexView), SetSampler); UpdateRevision(); } void SetSampler(Uint32 CacheOffset, ISampler* pSampler) { GetTexture(CacheOffset).pSampler = ClassPtrCast<SamplerGLImpl>(pSampler); UpdateRevision(); } void SetTexelBuffer(Uint32 CacheOffset, RefCntAutoPtr<BufferViewGLImpl>&& pBuffView) { GetTexture(CacheOffset).Set(std::move(pBuffView)); UpdateRevision(); } void SetTexImage(Uint32 CacheOffset, RefCntAutoPtr<TextureViewGLImpl>&& pTexView) { GetImage(CacheOffset).Set(std::move(pTexView), false); UpdateRevision(); } void SetBufImage(Uint32 CacheOffset, RefCntAutoPtr<BufferViewGLImpl>&& pBuffView) { GetImage(CacheOffset).Set(std::move(pBuffView)); UpdateRevision(); } void SetSSBO(Uint32 CacheOffset, RefCntAutoPtr<BufferViewGLImpl>&& pBuffView) { auto& SSBO = GetSSBO(CacheOffset); SSBO.pBufferView = std::move(pBuffView); SSBO.DynamicOffset = 0; Uint64 SSBOBit = Uint64{1} << Uint64{CacheOffset}; if (m_DynamicSSBOSlotMask & SSBOBit) { // Only set the flag for those slots that allow dynamic buffers // (i.e. the variable was not created with NO_DYNAMIC_BUFFERS flag). if (SSBO.IsDynamic()) m_DynamicSSBOMask |= SSBOBit; else m_DynamicSSBOMask &= ~SSBOBit; } else { VERIFY((m_DynamicSSBOMask & SSBOBit) == 0, "Dynamic SSBO bit should never be set when corresponding bit in m_DynamicSSBOSlotMask is not set"); } UpdateRevision(); } void SetDynamicSSBOOffset(Uint32 CacheOffset, Uint32 DynamicOffset) { DEV_CHECK_ERR((m_DynamicSSBOSlotMask & (Uint64{1} << Uint64{CacheOffset})) != 0, "Attempting to set dynamic offset for a non-dynamic SSBO slot"); GetSSBO(CacheOffset).DynamicOffset = DynamicOffset; } bool IsUBBound(Uint32 CacheOffset) const { if (CacheOffset >= GetUBCount()) return false; const auto& UB = GetConstUB(CacheOffset); return UB.pBuffer; } bool IsTextureBound(Uint32 CacheOffset, bool dbgIsTextureView) const { if (CacheOffset >= GetTextureCount()) return false; const auto& Texture = GetConstTexture(CacheOffset); VERIFY_EXPR(dbgIsTextureView || Texture.pTexture == nullptr); return Texture.pView; } bool IsImageBound(Uint32 CacheOffset, bool dbgIsTextureView) const { if (CacheOffset >= GetImageCount()) return false; const auto& Image = GetConstImage(CacheOffset); VERIFY_EXPR(dbgIsTextureView || Image.pTexture == nullptr); return Image.pView; } bool IsSSBOBound(Uint32 CacheOffset) const { if (CacheOffset >= GetSSBOCount()) return false; const auto& SSBO = GetConstSSBO(CacheOffset); return SSBO.pBufferView; } // clang-format off Uint32 GetUBCount() const { return (m_TexturesOffset - m_UBsOffset) / sizeof(CachedUB); } Uint32 GetTextureCount() const { return (m_ImagesOffset - m_TexturesOffset) / sizeof(CachedResourceView); } Uint32 GetImageCount() const { return (m_SSBOsOffset - m_ImagesOffset) / sizeof(CachedResourceView); } Uint32 GetSSBOCount() const { return (m_MemoryEndOffset - m_SSBOsOffset) / sizeof(CachedSSBO); } // clang-format on const CachedUB& GetConstUB(Uint32 CacheOffset) const { VERIFY(CacheOffset < GetUBCount(), "Uniform buffer index (", CacheOffset, ") is out of range"); return reinterpret_cast<CachedUB*>(m_pResourceData.get() + m_UBsOffset)[CacheOffset]; } const CachedResourceView& GetConstTexture(Uint32 CacheOffset) const { VERIFY(CacheOffset < GetTextureCount(), "Texture index (", CacheOffset, ") is out of range"); return reinterpret_cast<CachedResourceView*>(m_pResourceData.get() + m_TexturesOffset)[CacheOffset]; } const CachedResourceView& GetConstImage(Uint32 CacheOffset) const { VERIFY(CacheOffset < GetImageCount(), "Image buffer index (", CacheOffset, ") is out of range"); return reinterpret_cast<CachedResourceView*>(m_pResourceData.get() + m_ImagesOffset)[CacheOffset]; } const CachedSSBO& GetConstSSBO(Uint32 CacheOffset) const { VERIFY(CacheOffset < GetSSBOCount(), "Shader storage block index (", CacheOffset, ") is out of range"); return reinterpret_cast<CachedSSBO*>(m_pResourceData.get() + m_SSBOsOffset)[CacheOffset]; } bool IsInitialized() const { return m_MemoryEndOffset != InvalidResourceOffset; } ResourceCacheContentType GetContentType() const { return m_ContentType; } #ifdef DILIGENT_DEVELOPMENT void SetStaticResourcesInitialized() { m_bStaticResourcesInitialized = true; } bool StaticResourcesInitialized() const { return m_bStaticResourcesInitialized; } #endif // Binds all resources void BindResources(GLContextState& GLState, const std::array<Uint16, 4>& BaseBindings, std::vector<TextureBaseGL*>& WritableTextures, std::vector<BufferGLImpl*>& WritableBuffers) const; // Binds uniform and storage buffers with dynamic offsets only void BindDynamicBuffers(GLContextState& GLState, const std::array<Uint16, 4>& BaseBindings) const; bool HasDynamicResources() const { return m_DynamicUBOMask != 0 || m_DynamicSSBOMask != 0; } #ifdef DILIGENT_DEBUG void DbgVerifyDynamicBufferMasks() const; #endif private: CachedUB& GetUB(Uint32 CacheOffset) { return const_cast<CachedUB&>(const_cast<const ShaderResourceCacheGL*>(this)->GetConstUB(CacheOffset)); } CachedResourceView& GetTexture(Uint32 CacheOffset) { return const_cast<CachedResourceView&>(const_cast<const ShaderResourceCacheGL*>(this)->GetConstTexture(CacheOffset)); } CachedResourceView& GetImage(Uint32 CacheOffset) { return const_cast<CachedResourceView&>(const_cast<const ShaderResourceCacheGL*>(this)->GetConstImage(CacheOffset)); } CachedSSBO& GetSSBO(Uint32 CacheOffset) { return const_cast<CachedSSBO&>(const_cast<const ShaderResourceCacheGL*>(this)->GetConstSSBO(CacheOffset)); } private: static constexpr const Uint16 InvalidResourceOffset = 0xFFFF; static constexpr const Uint16 m_UBsOffset = 0; Uint16 m_TexturesOffset = InvalidResourceOffset; Uint16 m_ImagesOffset = InvalidResourceOffset; Uint16 m_SSBOsOffset = InvalidResourceOffset; Uint16 m_MemoryEndOffset = InvalidResourceOffset; std::unique_ptr<Uint8, STDDeleter<Uint8, IMemoryAllocator>> m_pResourceData; // Indicates at which positions dynamic UBOs or SSBOs may be bound Uint64 m_DynamicUBOSlotMask = 0; Uint64 m_DynamicSSBOSlotMask = 0; // Indicates slot at which dynamic buffers are actually bound Uint64 m_DynamicUBOMask = 0; Uint64 m_DynamicSSBOMask = 0; // Indicates what types of resources are stored in the cache const ResourceCacheContentType m_ContentType; #ifdef DILIGENT_DEVELOPMENT bool m_bStaticResourcesInitialized = false; #endif }; } // namespace Diligent
37.112219
154
0.648569
Zone-organization
61a0983082a566660b4fbde622ec4353df0a3fcb
5,109
hpp
C++
bahamut/tools/compressor.hpp
higan-emu/bahamut-lagoon-translation-kit
6f08de5b92b597c0b9ecebd485cc975b99acfc13
[ "0BSD" ]
2
2021-08-15T04:10:10.000Z
2021-08-15T20:14:13.000Z
bahamut/tools/compressor.hpp
higan-emu/bahamut-lagoon-translation-kit
6f08de5b92b597c0b9ecebd485cc975b99acfc13
[ "0BSD" ]
1
2022-02-16T02:46:39.000Z
2022-02-16T04:30:29.000Z
bahamut/tools/compressor.hpp
higan-emu/bahamut-lagoon-translation-kit
6f08de5b92b597c0b9ecebd485cc975b99acfc13
[ "0BSD" ]
1
2021-12-25T11:34:57.000Z
2021-12-25T11:34:57.000Z
#pragma once auto compressBlockLZ77(array_view<u8> input) -> vector<u8> { vector<u8> output; output.resize(256 * 1024, 0x00); u32 source = 0; u32 target = 0; while(source < input.size()) { u32 longestOffset = 0; u32 longestLength = 0; for(u32 window = 1; window < 2048; window++) { u32 length = 0; while(true) { if(length >= 63) break; //maximum dictionary length if(source + length >= input.size()) break; //do not read past end of input buffer if(source + length < window) break; //do not read past start of sliding window if(input[source + length] != input[source + length - window]) break; //stop at first mismatch length++; } if(length >= longestLength) { longestOffset = window; longestLength = length; } } if(longestLength >= 4) { output[target++] = 0x1a | (longestOffset >> 10 & 1); output[target++] = (longestLength & 0x3f) | (longestOffset >> 2 & 0xc0); output[target++] = (longestOffset & 0xff); source += longestLength; } else { u8 byte = input[source++]; output[target++] = byte; if(byte == 0x1a || byte == 0x1b) { output[target++] = 0x00; output[target++] = 0x00; } } } output[target++] = 0x1b; output[target++] = 0x00; output[target++] = 0x01; output.resize(target); return output; } auto compressLZ77(u8 mode, array_view<u8> input) -> vector<u8> { vector<u8> data; if(mode == 0x00) { data.append(0x00); data.append(compressBlockLZ77(input)); return data; } if(mode == 0x03) { vector<u8> lower; lower.resize(input.size() >> 1); for(u32 address : range(lower.size())) { lower[address] = input[address * 2]; } vector<u8> upper; upper.resize(3 + (data.size() >> 3)); upper[0] = 0x04; //mode upper[1] = (upper.size() - 3) >> 0; upper[2] = (upper.size() - 3) >> 8; for(u32 address : range(upper.size())) { u8 byte = 0x00; byte |= (input[lower.size() + address * 8 + 1] >> 6) << 0; byte |= (input[lower.size() + address * 8 + 3] >> 6) << 2; byte |= (input[lower.size() + address * 8 + 5] >> 6) << 4; byte |= (input[lower.size() + address * 8 + 7] >> 6) << 6; upper[3 + address] = byte; } data.append(0x03); data.append(compressBlockLZ77(lower)); data.append(0x00); data.append(0x03); data.append(compressBlockLZ77(upper)); return data; } if(mode == 0x06) { vector<u8> lower; vector<u8> upper; lower.resize(input.size() >> 1); upper.resize(input.size() >> 1); for(u32 address : range(input.size() >> 1)) { lower[address] = input[address * 2 + 0]; upper[address] = input[address * 2 + 1]; } data.append(0x06); data.append(compressBlockLZ77(lower)); data.append(0x00); data.append(0x06); data.append(compressBlockLZ77(upper)); return data; } return {}; } auto compressLZSS(array_view<u8> input) -> vector<u8> { vector<u8> output; output.resize(256 * 1024, 0xff); //default all unassigned flag bits to set struct Codepoint { u16 offset = 0; u8 length = 1; u8 byte = 0x00; }; vector<Codepoint> codepoints; u32 offset = 0; while(offset < input.size()) { Codepoint codepoint; codepoint.byte = input[offset]; for(u32 window = 1; window < 4096; window++) { u32 length = 0; while(true) { if(length >= 15 + 3) break; //maximum dictionary length if(offset + length >= input.size()) break; //do not read past end of input buffer if(offset + length < window) break; //do not read past start of sliding window if(input[offset + length] != input[offset + length - window]) break; //stop at first mismatch length++; } if(length >= codepoint.length && length >= 3) { codepoint.offset = window; codepoint.length = length; } } codepoints.append(codepoint); offset += codepoint.length; } //the first flag block must encode eight codepoints, even if the input size is smaller while(codepoints.size() < 8) { Codepoint codepoint; codepoints.append(codepoint); } u32 origin = 0; u32 target = 2; while(codepoints) { u32 flag = target++; for(u32 bit : range(8)) { if(!codepoints) continue; auto codepoint = codepoints.takeFirst(); if(codepoint.length < 3) { output[flag] &= ~(1 << bit); output[target++] = codepoint.byte; } else { u16 code = codepoint.length - 3 << 12 | codepoint.offset; output[target++] = code >> 0; output[target++] = code >> 8; } } if(codepoints.size() >= 8) continue; //for an unknown reason, only the first block adds 2 to size when decompressing ... output[origin + 0] = target - (!origin ? 2 : 0) >> 0; output[origin + 1] = target - (!origin ? 2 : 0) >> 8; output[target++] = codepoints.size(); origin = target; target += 2; if(!codepoints) break; } output.resize(target - 2); return output; }
28.702247
102
0.575259
higan-emu
61a1ad087c09ffa125219230189328595b843150
20,045
hpp
C++
include/lbann/layers/layer.hpp
andy-yoo/lbann-andy
237c45c392e7a5548796ac29537ab0a374e7e825
[ "Apache-2.0" ]
null
null
null
include/lbann/layers/layer.hpp
andy-yoo/lbann-andy
237c45c392e7a5548796ac29537ab0a374e7e825
[ "Apache-2.0" ]
null
null
null
include/lbann/layers/layer.hpp
andy-yoo/lbann-andy
237c45c392e7a5548796ac29537ab0a374e7e825
[ "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2014-2016, Lawrence Livermore National Security, LLC. // Produced at the Lawrence Livermore National Laboratory. // Written by the LBANN Research Team (B. Van Essen, et al.) listed in // the CONTRIBUTORS file. <lbann-dev@llnl.gov> // // LLNL-CODE-697807. // All rights reserved. // // This file is part of LBANN: Livermore Big Artificial Neural Network // Toolkit. For details, see http://software.llnl.gov/LBANN or // https://github.com/LLNL/LBANN. // // Licensed under the Apache License, Version 2.0 (the "Licensee"); you // may not use this file except in compliance with the License. You may // obtain a copy of the License at: // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the license. //////////////////////////////////////////////////////////////////////////////// #ifndef LBANN_LAYER_HPP_INCLUDED #define LBANN_LAYER_HPP_INCLUDED #include "lbann/base.hpp" #include "lbann/comm.hpp" #include "lbann/utils/summary.hpp" #include "lbann/optimizers/optimizer.hpp" #include "lbann/utils/exception.hpp" #include "lbann/utils/timer.hpp" #include "lbann/io/persist.hpp" #include <lbann.pb.h> #include <string> #include <vector> namespace lbann { // Forward declarations class model; class weights; class lbann_callback_sync_layers; /** Abstract base class for neural network layers. * A layer takes input tensors ("previous activations") and applies a * mathematical operation to obtain output tensors * ("activations"). This operation often has trainable parameters * called "weights." The previous activations are recieved from * "parent layers" and the activations are sent to "child layers," * making each layer a node in a directed graph. The layer graph and * the weights are managed by a neural network model class. A layer * should also be able to take objective function gradients * w.r.t. the activations ("previous error signals") and compute the * objective function gradients w.r.t. the previous activations * ("error signals") and w.r.t. the weights. This allows the model to * perform automatic differentiation and to apply first-order * optimization methods to the weights. */ class Layer { friend class lbann_callback_sync_layers; friend class lbann_callback_sync_selected; public: Layer(lbann_comm *comm); Layer(const Layer& other); Layer& operator=(const Layer& other); virtual ~Layer() = default; /** Copy function. * This function dynamically allocates memory for a layer instance * and instantiates a copy. The caller is responsible for * deallocating the instance. */ virtual Layer* copy() const = 0; /** Get the layer type's name. * A layer type name should be brief, human-readable description of * the layer's mathematical operation. */ virtual std::string get_type() const = 0; /** Get the layer instance's name. * Each layer in a model should have a unique, preferably * human-readable, name. */ inline std::string get_name() const { return m_name; } /** Set the layer instance's name. * Each layer in a model should have a unique, preferably * human-readable, name. */ inline void set_name(const std::string name) { m_name = name; } /** Get a human-readable description of the layer parameters. */ virtual std::string get_description() const; /** Get a human-readable description of the activation tensors. * Activation tensors are stored in distributed matrices where each * column corresponds to a mini-batch sample. Within each column, * the data is packed w.r.t. the last tensor dimension, then * w.r.t. the penultimate dimension, and so on. 3D tensors are * assumed to be 2D images in NCHW format. */ virtual std::string get_topo_description() const; /** Forward propagation step. * Apply a mathematical operation to input tensors to obtain output * tensors. */ virtual void forward_prop(); /** Backward propagation step. * Given the objective function gradients w.r.t. the output * tensors, compute the gradients w.r.t. the input tensors and * w.r.t. the weights. This is essentially an application of the * chain rule. */ virtual void back_prop(); /** Update step. * Update the layer's internal members. Note that the optimization * step for the weights happens elsewhere. */ virtual bool update(); virtual void summarize_stats(lbann_summary& summarizer, int step); virtual void summarize_matrices(lbann_summary& summarizer, int step); /** Setup layer members. * This calls the 'setup_pointers', 'setup_dims', 'setup_matrices', * 'setup_data', and 'setup_gpu' (if needed) functions. It is * assumed that pointers to parent/child layers have already been * initialized. */ virtual void setup(); /** Check that the setup is reasonable. */ virtual void check_setup(); /** Get data layout of the data tensors. * We assume that the data layouts of the previous activations, * activations, previous error signals, and error signals are the * same. Each concrete layer that is templated on its data layout * should override this function to return its template parameter. */ virtual data_layout get_data_layout() const = 0; /** Get the device allocation for the data tensors. * We assume that the decice allocation of the previous activations, * activations, previous error signals, and error signals are the * same. Each concrete layer that is templated on its device allocation * should override this function to return its template parameter. */ virtual El::Device get_device_allocation() const = 0; /** Get a human-readable description of the data_layout */ std::string get_data_layout_string(data_layout d) const; /** Get a human-readable description of the device allocation */ std::string get_device_allocation_string(El::Device dev) const; /** Get a short human-readable description of the device allocation */ std::string get_device_allocation_string_short(El::Device dev) const; /** Reset layer stat counters. */ virtual void reset_counters(); /** Whether the layer is using a GPU implementation. */ inline bool using_gpus() const { #ifdef LBANN_HAS_GPU return get_device_allocation() == El::Device::GPU; #else return false; #endif // LBANN_HAS_GPU } /** Get expected number of parent layers. * A negative value indicates no limit. */ inline int get_expected_num_parent_layers() const { return m_expected_num_parent_layers; } /** Get expected number of child layers. * A negative value indicates no limit. */ inline int get_expected_num_child_layers() const { return m_expected_num_child_layers; } /** Return the model that manages this layer. */ inline model* get_model() const { return m_model; } /** Set the model that manages this layer. */ inline void set_model(model* m) { m_model = m; } virtual El::Matrix<El::Int>* get_sample_indices_per_mb() { return nullptr; }; virtual bool save_to_checkpoint_shared(persist& p) const; virtual bool load_from_checkpoint_shared(persist& p); virtual bool save_to_checkpoint_distributed(persist& p) const; virtual bool load_from_checkpoint_distributed(persist& p); /** Write layer to proto file */ virtual void write_proto(lbann_data::Layer* proto) const; /** Get parent layers. */ inline std::vector<const Layer*>& get_parent_layers() { return m_parent_layers; } /** Get parent layers. (const) */ inline const std::vector<const Layer*>& get_parent_layers() const { return m_parent_layers; } /** Get child layers. */ inline std::vector<const Layer*>& get_child_layers() { return m_child_layers; } /** Get child layers. (const) */ inline const std::vector<const Layer*>& get_child_layers() const { return m_child_layers; } /** Get number of parent layers. */ inline int get_num_parents() const { return get_parent_layers().size(); } /** Get number of child layers. */ inline int get_num_children() const { return get_child_layers().size(); } /** Get names in a particular list of layers */ static std::string get_layer_names(const std::vector<const Layer*>& list); std::string get_child_names() const { return get_layer_names(m_child_layers); } std::string get_parent_names() const { return get_layer_names(m_parent_layers); } // =========================================================== // Layer pointer manipulation functions // =========================================================== /** Add a parent layer. * Does nothing if parent is a null pointer, the same layer, or * already a parent. */ void add_parent_layer(const Layer* parent); /** Add a child layer. * Does nothing if child is a null pointer, the same layer, or * already a child. */ void add_child_layer(const Layer* child); /** Remove all parent layers. * Parent layers are not deallocated. */ void clear_parent_layers() { get_parent_layers().clear(); } /** Remove all child layers. * Child layers are not deallocated. */ void clear_child_layers() { get_child_layers().clear(); } /** Get list of pointers to other layers. */ virtual std::vector<Layer*> get_layer_pointers(); /** Set list of pointers to other layers. */ virtual void set_layer_pointers(std::vector<Layer*> layers); // =========================================================== // Weights access functions // =========================================================== /** Get references to weights. */ inline std::vector<weights*>& get_weights() { return m_weights; } /** Get references to weights. (const) */ inline const std::vector<weights*>& get_weights() const { return m_weights; } /** Set list of pointers to weights. */ inline void set_weights(std::vector<weights*> w) { get_weights() = w; } /** Replace weights with another Layer's weights*/ void replace_weights(Layer* other_layer); // =========================================================== // Tensor dimension access functions // =========================================================== /** Get dimensions of an input tensor. * E.g. get the dimensions of a "previous activations tensor" or * the "previous neuron dimensions." */ std::vector<int> get_input_dims(int input_index = 0) const; /** Get size of an input tensor. * E.g. get the size of a "previous activations tensor" or * the number of "previous neurons." */ int get_input_size(int input_index = 0) const; /** Get dimensions of an output tensor. * E.g. get the dimensions of an "activations tensor" or the * "neuron dimensions." */ std::vector<int> get_output_dims(int output_index = 0) const; /** Get size of an output tensor. * E.g. get the size of an "activations tensor" or the number of * "neurons." */ int get_output_size(int output_index = 0) const; // =========================================================== // Tensor access functions // =========================================================== /** Get activation tensor. */ AbsDistMat& get_activations(int child_index = 0); /** Get error signal tensor. */ AbsDistMat& get_error_signals(int parent_index = 0); /** Get previous activation tensor. */ const AbsDistMat& get_prev_activations(int parent_index = 0) const; /** Get activation tensor. */ const AbsDistMat& get_activations(int child_index = 0) const; /** Get previous error signal tensor. */ const AbsDistMat& get_prev_error_signals(int child_index = 0) const; /** Get error signal tensor. */ const AbsDistMat& get_error_signals(int parent_index = 0) const; /** Get local portion of activation tensor. */ AbsMat& get_local_activations(int child_index = 0); /** Get local portion of error signal tensor. */ AbsMat& get_local_error_signals(int parent_index = 0); /** Get local portion of previous activation tensor. */ const AbsMat& get_local_prev_activations(int parent_index = 0) const; /** Get local portion of activation tensor. */ const AbsMat& get_local_activations(int child_index = 0) const; /** Get local portion of previous error signal tensor. */ const AbsMat& get_local_prev_error_signals(int child_index = 0) const; /** Get local portion of error signal tensor. */ const AbsMat& get_local_error_signals(int parent_index = 0) const; /** Get reference to LBANN communicator. */ lbann_comm* get_comm() const { return m_comm; } // =========================================================== // Freeze management functions // =========================================================== void freeze(); void unfreeze(); bool is_frozen() const; protected: /** Set dimensions of an output tensor. * E.g. set the dimensions of an "activations tensor" or the * "neuron dimensions." */ void set_output_dims(std::vector<int> dims, int output_index = 0); // =========================================================== // Setup helper functions // =========================================================== /** Setup layer pointers. * Called by the 'setup' function. Pointers to parent/child layers * are assumed to be already initialized. */ virtual void setup_pointers(); /** Setup tensor dimensions * Called by the 'setup' function. If there are any input tensors, * the base method sets all uninitialized output tensor dimensions * equal to the first input tensor dimensions. */ virtual void setup_dims(); /** Setup distributed matrices. * Called by the 'setup' function. Each column of these distributed * matrices is interpreted as the flattened tensor for a mini-batch * sample. The matrices themselves are constructed by calling the * 'construct_matrix' function. If any matrices have already been * setup, they are destroyed and reinstantiated. */ virtual void setup_matrices(const El::Grid& grid); /** Construct distributed matrix. * Called by the 'setup_matrices' function. 'type' is one of the * following: "input", "output", "gradient_wrt_output", * "gradient_wrt_input". */ virtual std::unique_ptr<AbsDistMat> construct_matrix(const El::Grid& grid, std::string type, El::Int index); /** Setup layer data. * Called by the 'setup' function. Memory is allocated for * distributed matrices. */ virtual void setup_data(); /** Setup GPU objects. * Called by the 'setup' function if the layer is on GPUs. */ virtual void setup_gpu() {} // =========================================================== // Forward prop step helper functions // =========================================================== /** Setup input tensors. * Called by the 'forward_prop' function. Each input tensor is * setup as a view or copy of the corresponding parent layer's * output tensor. */ virtual void fp_setup_inputs(El::Int mini_batch_size); /** Setup output tensors. * Called by the 'forward_prop' function. Each output tensor is * resized to match the mini-batch size. */ virtual void fp_setup_outputs(El::Int mini_batch_size); /** Apply layer operation. * Called by the 'forward_prop' function. Given the input tensors, * the output tensors are populated with computed values. */ virtual void fp_compute() = 0; // =========================================================== // Back prop step helper functions // =========================================================== /** Setup gradient w.r.t. output tensors. * Called by the 'back_prop' function. Each gradient w.r.t. output * tensor is setup as a view or copy of the corresponding child * layer's gradient w.r.t. input tensor. */ virtual void bp_setup_gradient_wrt_outputs(El::Int mini_batch_size); /** Setup gradient w.r.t. input tensors. * Called by the 'back_prop' function. Each gradient w.r.t. input * tensor is resized to match the mini-batch size. */ virtual void bp_setup_gradient_wrt_inputs(El::Int mini_batch_size); /** Compute objective funciton gradients. * Called by the 'back_prop' function. Given the input, output, and * gradient w.r.t. output tensors, the gradient w.r.t. input * tensors are populated with the computed values and the gradients * w.r.t. the weights are sent to the appropriate optimizers. */ virtual void bp_compute(); // =========================================================== // Update step helper functions // =========================================================== /** Perform the computation for the update step. * Returns false if the layer must reset for a new training epoch. */ virtual bool update_compute() { return true; } // =========================================================== // Protected class members // =========================================================== /** Reference to LBANN communicator. */ lbann_comm *m_comm; /** References to layer weights. */ std::vector<weights*> m_weights; /** References to parent layers. */ std::vector<const Layer*> m_parent_layers; /** References to child layers. */ std::vector<const Layer*> m_child_layers; /** Expected number of parent layers. * A negative value indicates no limit. */ int m_expected_num_parent_layers = 1; /** Expected number of child layers. * A negative value indicates no limit. */ int m_expected_num_child_layers = 1; /** Reference to model managing this layer. */ model *m_model = nullptr; /** Avoid back prop if frozen */ bool m_frozen; /** Time spent in forward propagation. */ EvalType m_fp_time; /** Time spent in the forward propagation computation. */ EvalType m_fp_compute_time; /** Time spent in backward propagation. */ EvalType m_bp_time; /** Time spent in the backward propagation computation. */ EvalType m_bp_compute_time; /** Time spent in updates. */ EvalType m_update_time; /** Layer instance's name. * Each layer in a model should have a unique, preferably * human-readable, name. */ std::string m_name; private: // =========================================================== // Private access functions // =========================================================== /** Get activation tensor corresponding to child layer. */ const AbsDistMat& get_activations(const Layer& child) const; /** Get error signal tensor corresponding to parent layer. */ const AbsDistMat& get_error_signals(const Layer& parent) const; // =========================================================== // Private class members // =========================================================== /** Dimensions of output tensors. */ std::vector<std::vector<int>> m_output_dims_list; /** Input tensors. * Each matrix column corresponds to a flattened mini-batch sample. */ std::vector<std::unique_ptr<AbsDistMat>> m_inputs; /** Output tensors. * Each matrix column corresponds to a flattened mini-batch sample. */ std::vector<std::unique_ptr<AbsDistMat>> m_outputs; /** Objective function gradients w.r.t. the output tensors. * Each matrix column corresponds to a flattened mini-batch sample. */ std::vector<std::unique_ptr<AbsDistMat>> m_gradient_wrt_outputs; /** Objective function gradients w.r.t. the input tensors. * Each matrix column corresponds to a flattened mini-batch sample. */ std::vector<std::unique_ptr<AbsDistMat>> m_gradient_wrt_inputs; }; } // namespace lbann #endif // LBANN_LAYER_HPP_INCLUDED
39.227006
95
0.648192
andy-yoo
61a2bd169d6cf4bb7313eeb2798bb599a998693f
6,401
cpp
C++
ToolKit/ReportControl/XTPReportRecord.cpp
11Zero/DemoBCG
8f41d5243899cf1c82990ca9863fb1cb9f76491c
[ "MIT" ]
2
2018-03-30T06:40:08.000Z
2022-02-23T12:40:13.000Z
ToolKit/ReportControl/XTPReportRecord.cpp
11Zero/DemoBCG
8f41d5243899cf1c82990ca9863fb1cb9f76491c
[ "MIT" ]
null
null
null
ToolKit/ReportControl/XTPReportRecord.cpp
11Zero/DemoBCG
8f41d5243899cf1c82990ca9863fb1cb9f76491c
[ "MIT" ]
1
2020-08-11T05:48:02.000Z
2020-08-11T05:48:02.000Z
// XTPReportRecord.cpp : implementation of the CXTPReportRecord class. // // This file is a part of the XTREME REPORTCONTROL MFC class library. // (c)1998-2011 Codejock Software, All Rights Reserved. // // THIS SOURCE FILE IS THE PROPERTY OF CODEJOCK SOFTWARE AND IS NOT TO BE // RE-DISTRIBUTED BY ANY MEANS WHATSOEVER WITHOUT THE EXPRESSED WRITTEN // CONSENT OF CODEJOCK SOFTWARE. // // THIS SOURCE CODE CAN ONLY BE USED UNDER THE TERMS AND CONDITIONS OUTLINED // IN THE XTREME TOOLKIT PRO LICENSE AGREEMENT. CODEJOCK SOFTWARE GRANTS TO // YOU (ONE SOFTWARE DEVELOPER) THE LIMITED RIGHT TO USE THIS SOFTWARE ON A // SINGLE COMPUTER. // // CONTACT INFORMATION: // support@codejock.com // http://www.codejock.com // ///////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "XTPReportRecordItem.h" #include "XTPReportRecordItemText.h" #include "XTPReportColumn.h" #include "XTPReportInplaceControls.h" #include "XTPReportRecord.h" #include "XTPReportRecords.h" #include "Common/XTPPropExchange.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif IMPLEMENT_SERIAL(CXTPReportRecord, CCmdTarget, VERSIONABLE_SCHEMA | _XTP_SCHEMA_CURRENT) CXTPReportRecord::CXTPReportRecord() : m_bVisible(TRUE), m_bLocked(FALSE), m_pPreviewItem(NULL) { m_pChildren = NULL; m_bExpanded = FALSE; m_bEditable = TRUE; m_bSelectedAsChildFlag = FALSE; m_nIndex = -1; m_pRecords = NULL; m_vtBookmark.vt = VT_EMPTY; //<<TC>> m_nFreeHeight = 0; //<<TC>> } CXTPReportRecord::~CXTPReportRecord() { RemoveAll(); if (m_pChildren) m_pChildren->InternalRelease(); } void CXTPReportRecord::RemoveAll() { for (int nItem = GetItemCount() - 1; nItem >= 0; nItem--) { CXTPReportRecordItem* pItem = m_arrItems.GetAt(nItem); if (pItem) pItem->InternalRelease(); } m_arrItems.RemoveAll(); CMDTARGET_RELEASE(m_pPreviewItem); } void CXTPReportRecord::Delete() { ASSERT(m_pRecords); if (m_pRecords) m_pRecords->RemoveAt(m_nIndex); } BOOL CXTPReportRecord::HasChildren() const { return m_pChildren && (m_pChildren->GetCount() > 0); } CXTPReportRecords* CXTPReportRecord::GetChilds() { if (m_pChildren == NULL) m_pChildren = new CXTPReportRecords(this); if (GetRecords()) { BOOL bCase = GetRecords()->IsCaseSensitive(); m_pChildren->SetCaseSensitive(bCase); } return m_pChildren; } CXTPReportRecordItem* CXTPReportRecord::GetItem(CXTPReportColumn* pColumn) const { if (this == NULL) return NULL; return GetItem(pColumn->GetItemIndex()); } int CXTPReportRecord::IndexOf(const CXTPReportRecordItem* pItem) const { for (int nItem = 0; nItem < GetItemCount(); nItem++) { if (GetItem(nItem) == pItem) return nItem; } return -1; } CXTPReportRecordItem* CXTPReportRecord::AddItem(CXTPReportRecordItem* pItem) { m_arrItems.Add(pItem); pItem->m_pRecord = this; return pItem; } CXTPReportRecordItemPreview* CXTPReportRecord::GetItemPreview() const { return m_pPreviewItem; } void CXTPReportRecord::SetEditable(BOOL bEditable) { m_bEditable = bEditable; } void CXTPReportRecord::SetPreviewItem(CXTPReportRecordItemPreview* pItemPreview) { if (m_pPreviewItem) m_pPreviewItem->InternalRelease(); m_pPreviewItem = pItemPreview; m_pPreviewItem->m_pRecord = this; } BOOL CXTPReportRecord::IsFiltered() const { return FALSE; } int CXTPReportRecord::GetIndex() const { return m_nIndex; } void CXTPReportRecord::DoPropExchange(CXTPPropExchange* pPX) { PX_Bool(pPX, _T("Locked"), m_bLocked); PX_Bool(pPX, _T("Editable"), m_bEditable); BOOL bPreview = m_pPreviewItem != NULL; PX_Bool(pPX, _T("Preview"), bPreview); int nCount = GetItemCount(); CXTPPropExchangeEnumeratorPtr pEnumItems(pPX->GetEnumerator(_T("Item"))); if (pPX->IsStoring()) { POSITION posItem = pEnumItems->GetPosition((DWORD)nCount); for (int i = 0; i < nCount; i++) { CXTPReportRecordItem* pItem = GetItem(i); ASSERT(pItem); if (!pItem) AfxThrowArchiveException(CArchiveException::badClass); CXTPPropExchangeSection secItem(pEnumItems->GetNext(posItem)); PX_Object(&secItem, pItem, RUNTIME_CLASS(CXTPReportRecordItem)); } } else { RemoveAll(); POSITION posItem = pEnumItems->GetPosition(); while (posItem) { CXTPReportRecordItem* pItem = NULL; CXTPPropExchangeSection sec(pEnumItems->GetNext(posItem)); PX_Object(&sec, pItem, RUNTIME_CLASS(CXTPReportRecordItem)); if (!pItem) AfxThrowArchiveException(CArchiveException::badClass); AddItem(pItem); } } //------------------------------------------------------------ if (bPreview) { CXTPPropExchangeSection secPreviewItem(pPX->GetSection(_T("PreviewItem"))); if (pPX->IsLoading()) { CMDTARGET_RELEASE(m_pPreviewItem); } PX_Object(&secPreviewItem, m_pPreviewItem, RUNTIME_CLASS(CXTPReportRecordItemPreview)); if (m_pPreviewItem && pPX->IsLoading()) { m_pPreviewItem->m_pRecord = this; } } //------------------------------------------------------------ if (pPX->GetSchema() > _XTP_SCHEMA_1041) { BOOL bHasChildren = HasChildren(); PX_Bool(pPX, _T("HasChildren"), bHasChildren, FALSE); if (bHasChildren) { CXTPPropExchangeSection secChildren(pPX->GetSection(_T("Children"))); GetChilds()->_DoPropExchange(&secChildren); } else if (m_pChildren) { m_pChildren->RemoveAll(); } } } void CXTPReportRecord::TreeAddRef() { InternalAddRef(); if (HasChildren()) { for (int nChild = 0; nChild < GetChilds()->GetCount(); nChild++) { GetChilds()->GetAt(nChild)->TreeAddRef(); } } } void CXTPReportRecord::TreeRelease() { if (HasChildren()) { for (int nChild = 0; nChild < GetChilds()->GetCount(); nChild++) { GetChilds()->GetAt(nChild)->TreeRelease(); } } InternalRelease(); } CXTPMarkupContext* CXTPReportRecord::GetMarkupContext() const { CXTPReportRecords* pRecords = m_pRecords; while (pRecords != NULL) { CXTPMarkupContext* pMarkupContext = pRecords->GetMarkupContext(); if (pMarkupContext) return pMarkupContext; if (pRecords->m_pOwnerRecord) pRecords = pRecords->m_pOwnerRecord->GetRecords(); else return NULL; } return NULL; } CXTPReportRecord* CXTPReportRecord::GetParentRecord() const { if (m_pRecords && m_pRecords->GetOwnerRecord()) return m_pRecords->GetOwnerRecord(); return NULL; } void CXTPReportRecord::SetExpanded(BOOL bExpanded) { m_bExpanded = bExpanded; }
21.408027
89
0.706452
11Zero
61a7a6c6221e8a210af071f49de32a12791be2d0
2,182
cpp
C++
src/widgets/settingspages/AccountsPage.cpp
CommName/chatterino2
05469d1bbadbef9269705057830680745bf64c1d
[ "MIT" ]
null
null
null
src/widgets/settingspages/AccountsPage.cpp
CommName/chatterino2
05469d1bbadbef9269705057830680745bf64c1d
[ "MIT" ]
null
null
null
src/widgets/settingspages/AccountsPage.cpp
CommName/chatterino2
05469d1bbadbef9269705057830680745bf64c1d
[ "MIT" ]
null
null
null
#include "AccountsPage.hpp" #include "Application.hpp" #include "controllers/accounts/AccountController.hpp" #include "controllers/accounts/AccountModel.hpp" #include "providers/twitch/TwitchCommon.hpp" #include "util/LayoutCreator.hpp" #include "widgets/dialogs/LoginDialog.hpp" #include "widgets/helper/EditableModelView.hpp" #include <QDialogButtonBox> #include <QHeaderView> #include <QTableView> #include <QVBoxLayout> #include <algorithm> namespace chatterino { AccountsPage::AccountsPage() { auto *app = getApp(); LayoutCreator<AccountsPage> layoutCreator(this); auto layout = layoutCreator.emplace<QVBoxLayout>().withoutMargin(); EditableModelView *view = layout .emplace<EditableModelView>(app->accounts->createModel(nullptr), false) .getElement(); view->getTableView()->horizontalHeader()->setVisible(false); view->getTableView()->horizontalHeader()->setStretchLastSection(true); view->addButtonPressed.connect([] { static auto loginWidget = new LoginWidget(); loginWidget->show(); loginWidget->raise(); }); view->getTableView()->setStyleSheet("background: #333"); // auto buttons = layout.emplace<QDialogButtonBox>(); // { // this->addButton = buttons->addButton("Add", // QDialogButtonBox::YesRole); this->removeButton = // buttons->addButton("Remove", QDialogButtonBox::NoRole); // } // layout.emplace<AccountSwitchWidget>(this).assign(&this->accSwitchWidget); // ---- // QObject::connect(this->addButton, &QPushButton::clicked, []() { // static auto loginWidget = new LoginWidget(); // loginWidget->show(); // }); // QObject::connect(this->removeButton, &QPushButton::clicked, [this] { // auto selectedUser = this->accSwitchWidget->currentItem()->text(); // if (selectedUser == ANONYMOUS_USERNAME_LABEL) { // // Do nothing // return; // } // getApp()->accounts->Twitch.removeUser(selectedUser); // }); } } // namespace chatterino
30.732394
83
0.629698
CommName
61a7aa4447803ff2140f5cc5c9a40ea943f211af
10,795
cc
C++
lite/kernels/opencl/elementwise_sub_image_compute_test.cc
wanglei91/Paddle-Lite
8b2479f4cdd6970be507203d791bede5a453c09d
[ "Apache-2.0" ]
1,799
2019-08-19T03:29:38.000Z
2022-03-31T14:30:50.000Z
lite/kernels/opencl/elementwise_sub_image_compute_test.cc
wanglei91/Paddle-Lite
8b2479f4cdd6970be507203d791bede5a453c09d
[ "Apache-2.0" ]
3,767
2019-08-19T03:36:04.000Z
2022-03-31T14:37:26.000Z
lite/kernels/opencl/elementwise_sub_image_compute_test.cc
wanglei91/Paddle-Lite
8b2479f4cdd6970be507203d791bede5a453c09d
[ "Apache-2.0" ]
798
2019-08-19T02:28:23.000Z
2022-03-31T08:31:54.000Z
// Copyright (c) 2019 PsublePsuble Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <gtest/gtest.h> #include <algorithm> #include <random> #include "lite/backends/opencl/target_wrapper.h" #include "lite/core/op_registry.h" #include "lite/core/tensor.h" namespace paddle { namespace lite { template <typename dtype> void fill_data(dtype *x, const int length, int set_value = -1) { if (set_value == -1) { for (size_t idx = 0; idx < length; ++idx) { x[idx] = idx; } } else if (set_value != -1) { for (size_t idx = 0; idx < length; ++idx) { x[idx] = set_value; } } } template <typename dtype> void elementwise_compute_ref(const dtype *x_data, const dtype *y_data, dtype *out_data, const DDim &x_dims, const DDim &y_dims, int axis, const std::string elt_type, bool use_relu = false) { if (axis < 0) { axis = x_dims.size() - y_dims.size(); } int batch = 1; int channels = 1; int num = 1; for (int i = 0; i < axis; ++i) { batch *= x_dims[i]; } for (int i = 0; i < y_dims.size(); ++i) { channels *= y_dims[i]; } for (int i = y_dims.size() + axis; i < x_dims.size(); ++i) { num *= x_dims[i]; } VLOG(4) << "axis:" << axis; VLOG(4) << "batch:" << batch; VLOG(4) << "cahnnels:" << channels; VLOG(4) << "num:" << num; // do elementwise sub/sub/max/... if (elt_type == "sub" && axis == 1 && y_dims.size() == 1) { for (int i = 0; i < x_dims.production(); ++i) { auto w = i % y_dims.production(); out_data[i] = x_data[i] - y_data[w]; } } else if (elt_type == "sub") { for (int i = 0; i < batch; ++i) { for (int j = 0; j < channels; ++j) { int offset = (i * channels + j) * num; const dtype *din_ptr = x_data + offset; const dtype diny_data = y_data[j]; dtype *dout_ptr = out_data + offset; for (int k = 0; k < num; ++k) { *dout_ptr = *din_ptr - diny_data; if (use_relu) { *dout_ptr = std::max(*dout_ptr, static_cast<dtype>(0)); } dout_ptr++; din_ptr++; } } } } else { LOG(FATAL) << "unsupported Elementwise type: " << elt_type; } } // #define PRINT_RESULT // image TEST(elementwise_sub_image, compute) { LOG(INFO) << "main steps of test: host -> layout(buf2img on cpu) -> " "elementwise_sub(img) -> " "layout(img2buf on cpu) " "-> host"; // elementwise_sub's 3 kernels selection routing strategy: // -------------------------------------------------------- // 1. elementwise_sub: Need y_dim.size() == 4 // 2. elementwise_sub (used by fuse_elementwise_activation op): // Need y_dim.size() == 4 && act_type == "relu" // 3. width_sub: Need y_dim.size() == 1 && x_dim.size() == 4 && axis == // 3 // 4. channel_sub: Need y_dim.size() == 1 && x_dim.size() == 4 && axis == // 1 // dims const int n = 1; const int c = 3; const int h = 2; const int w = 2; const DDim x_dim = DDim(std::vector<DDim::value_type>{n, c, h, w}); auto out_dim = x_dim; // y_dim / axis / relu_flag std::vector<DDim> y_dim_v{DDim(std::vector<DDim::value_type>{n, c, h, w}), DDim(std::vector<DDim::value_type>{n, c, h, w}), DDim(std::vector<DDim::value_type>{w}), DDim(std::vector<DDim::value_type>{w})}; std::vector<int> axis_v{-1, -1, 3, 1}; std::vector<bool> relu_flag_v{false, true, false, false}; CHECK(y_dim_v.size() == axis_v.size() && axis_v.size() == relu_flag_v.size()) << "y_dim_v.size() == axis_v.size() == relu_flag_v.size() should be " "same, and be corresponding " "one by one"; // start loop for (size_t case_idx = 0; case_idx < y_dim_v.size(); ++case_idx) { auto y_dim = y_dim_v[case_idx]; auto axis = axis_v[case_idx]; auto relu_flag = relu_flag_v[case_idx]; LOG(INFO) << "================== elementwise_sub, case_idx:" << case_idx + 1 << "/" << y_dim_v.size() << " ==================="; LOG(INFO) << "x_dim:" << x_dim; LOG(INFO) << "y_dim:" << y_dim; LOG(INFO) << "out_dim:" << out_dim; LOG(INFO) << "axis:" << axis; LOG(INFO) << "relu_flag:" << relu_flag; // tensor VLOG(4) << "set tensors about op param"; lite::Tensor elesub_x, elesub_y, elesub_out; elesub_x.Resize(x_dim); elesub_y.Resize(y_dim); elesub_out.Resize(out_dim); // initialize tensors VLOG(4) << "initialize tensors"; paddle::lite::CLImageConverterDefault default_convertor; // x std::vector<float> x_v(x_dim.production()); fill_data<float>(x_v.data(), x_v.size()); // fill with index value auto x_img_shape = default_convertor.InitImageDimInfoWith(x_dim); // w, h auto x_img_w = x_img_shape[0]; auto x_img_h = x_img_shape[1]; std::vector<half_t> x_img_v(x_img_w * x_img_h * 4); // 4: RGBA default_convertor.NCHWToImage(x_v.data(), x_img_v.data(), x_dim); elesub_x.mutable_data<half_t, cl::Image2D>( x_img_w, x_img_h, x_img_v.data()); // y std::vector<float> y_v(y_dim.production()); fill_data<float>(y_v.data(), y_v.size()); // fill with index value auto y_img_shape = default_convertor.InitImageDimInfoWith(y_dim); // w, h auto y_img_w = y_img_shape[0]; auto y_img_h = y_img_shape[1]; std::vector<half_t> y_img_v(y_img_shape[0] * y_img_shape[1] * 4); // 4: RGBA default_convertor.NCHWToImage(y_v.data(), y_img_v.data(), y_dim); elesub_y.mutable_data<half_t, cl::Image2D>( y_img_w, y_img_h, y_img_v.data()); // out auto out_img_shape = default_convertor.InitImageDimInfoWith(out_dim); // w, h auto out_img_w = out_img_shape[0]; auto out_img_h = out_img_shape[1]; elesub_out.mutable_data<half_t, cl::Image2D>(out_img_w, out_img_h); std::vector<half_t> out_img_v(out_img_w * out_img_h * 4); fill_data<half_t>( out_img_v.data(), out_img_v.size(), 0); // fill with zero value std::vector<float> out_v(out_dim.production()); // operator param operators::FusionElementwiseActivationParam fuseElesubParam; // enabled if relu_flag is true fuseElesubParam.X = &elesub_x; fuseElesubParam.Y = &elesub_y; fuseElesubParam.Out = &elesub_out; fuseElesubParam.axis = axis; fuseElesubParam.act_type = relu_flag ? "relu" : ""; operators::ElementwiseParam elesubParam; elesubParam.X = &elesub_x; elesubParam.Y = &elesub_y; elesubParam.Out = &elesub_out; elesubParam.axis = axis; auto op_param = relu_flag ? fuseElesubParam : elesubParam; // set kernel auto elesub_img_kernels = KernelRegistry::Global().Create("elementwise_sub", TARGET(kOpenCL), PRECISION(kFP16), DATALAYOUT(kImageDefault)); ASSERT_FALSE(elesub_img_kernels.empty()); auto elesub_img_kernel = std::move(elesub_img_kernels.front()); VLOG(4) << "get elesub kernel: " << elesub_img_kernel->doc(); // set context and kernel args VLOG(4) << "set context and kernel args"; std::unique_ptr<KernelContext> context(new KernelContext); context->As<OpenCLContext>().InitOnce(); elesub_img_kernel->SetParam(op_param); std::unique_ptr<KernelContext> elesub_img_context(new KernelContext); context->As<OpenCLContext>().CopySharedTo( &(elesub_img_context->As<OpenCLContext>())); elesub_img_kernel->SetContext(std::move(elesub_img_context)); // run kernel VLOG(4) << "run kernel"; elesub_img_kernel->Launch(); // download gpu result to cpu const size_t cl_image2d_row_pitch{0}; const size_t cl_image2d_slice_pitch{0}; TargetWrapperCL::ImgcpySync(out_img_v.data(), elesub_out.data<half_t, cl::Image2D>(), out_img_w, out_img_h, cl_image2d_row_pitch, cl_image2d_slice_pitch, IoDirection::DtoH); default_convertor.ImageToNCHW( out_img_v.data(), out_v.data(), out_img_shape, out_dim); // compute cpu reference std::unique_ptr<float[]> out_ref(new float[out_dim.production()]); elementwise_compute_ref<float>(x_v.data(), y_v.data(), out_ref.get(), x_dim, y_dim, op_param.axis, "sub", relu_flag); #ifdef PRINT_RESULT // enable to check value of x and y for (int eidx = 0; eidx < out_dim.production(); eidx++) { auto value = out_v[eidx]; auto ref_value = out_ref.get()[eidx]; LOG(INFO) << "1st diff in this case at eidx[from 0]:" << eidx << " / " << out_dim.production() << ", x_v[" << eidx << "]:" << x_v[eidx] << ", value[" << eidx << "]:" << value << ", ref_value[" << eidx << "]:" << ref_value; } for (int i = 0; i < y_v.size(); i++) { LOG(INFO) << "y_v[" << i << "]:" << y_v[i]; } #endif for (int eidx = 0; eidx < out_dim.production(); eidx++) { auto value = out_v[eidx]; auto ref_value = out_ref.get()[eidx]; EXPECT_NEAR(value, ref_value, 1e-6); if (abs(value - ref_value) > 1e-6) { LOG(INFO) << "1st diff in this case at eidx[from 0]:" << eidx << " / " << out_dim.production() << ", value[" << eidx << "]:" << value << ", ref_value[" << eidx << "]:" << ref_value; break; } } } } } // namespace lite } // namespace paddle USE_LITE_KERNEL(elementwise_sub, kOpenCL, kFP16, kImageDefault, def); USE_LITE_KERNEL( fusion_elementwise_sub_activation, kOpenCL, kFP16, kImageDefault, def);
36.843003
80
0.562205
wanglei91
61ab6d7f866021d66ed1c43f1cbb698721bd894a
4,386
hpp
C++
include/stringConversion.hpp
SavAct/TokenSale
abef25c70ccc62edc9ef019ee16a5f8b4e3b4fdf
[ "MIT" ]
null
null
null
include/stringConversion.hpp
SavAct/TokenSale
abef25c70ccc62edc9ef019ee16a5f8b4e3b4fdf
[ "MIT" ]
null
null
null
include/stringConversion.hpp
SavAct/TokenSale
abef25c70ccc62edc9ef019ee16a5f8b4e3b4fdf
[ "MIT" ]
null
null
null
#pragma once #include "base58.hpp" #include <vector> using namespace eosio; using namespace std; class MemoParams { public: std::vector<std::variant<name, ecc_public_key>> user; std::variant<name, ecc_public_key> affiliate; int donationAccNumber = 0; bool hasAffiliate = false; /** Holds the parameters: user and affiliate name or public key and the donationNumber * @param memo A string which contains the parameters seperated whit the chars of the static const parasigns property */ MemoParams(const string& memo) { // Trim the start and the end of the memo string _memo(Trim(memo)); // Get all parameters which are defined in the memo GetParams(_memo); } /** The signs to seperate the memo. The sequence of the chars are importend. */ inline static const string parasigns = "- #@"; /** Set a parameter from string * @param parameter Parameter as string * @param type The type of the parameter */ void SetParameter(const string& parameter, int type){ if(parameter.size() > 0){ // Switch between the order of chars in parasigns switch(type){ case 0: case 1: // User name or key user.push_back(GetUser(parameter)); break; case 2: // Affiliate name or key affiliate = GetUser(parameter); hasAffiliate = true; break; case 3: // Donation account number donationAccNumber = stoi(parameter); break; } } } /** Get a user parameter from string * @param para_str User parameter as string * @return The user parameter as variant of an account name or a public key */ static std::variant<name, ecc_public_key> GetUser(const string& para_str){ if (para_str.length() > 12) return string_to_ecc_public_key(para_str); else return name(para_str); } /** Get all parameters which are defined in a string * @param memo The string with all parameters */ void GetParams(const string& memo) { int type, lastType = 0; string::const_iterator it = memo.begin(); string::const_iterator last_it = memo.begin(); for(; it != memo.end(); ++it) { type = parasigns.find(*it); if(type != string::npos) { SetParameter(string(last_it, it), lastType); last_it = it + 1; lastType = type; } } SetParameter(std::string(last_it, it), lastType); } /** Trim a string at the start and the end * @return The trimmed string */ static string Trim(const string& str) { static const string whitespaces(" \t\f\v\n\r"); auto strStart = str.find_first_not_of(whitespaces); auto strEnd = str.find_last_not_of(whitespaces); if (strStart != string::npos) { if (strEnd != string::npos) return str.substr(strStart, strEnd + 1); else return str.substr(strStart); } else { if (strEnd != string::npos) return str.substr(0, strEnd + 1); else return str; } } /** Convert a string to a name and check if it exists * @return The trimmed string */ static name getCheckedName(const string& str) { name Name(str); check(is_account(Name), "Account does not exist"); return Name; } /** Convert the pulic key from string to array<char, 33> * @return The public key */ static ecc_public_key string_to_ecc_public_key(const string& public_key_str) { check(public_key_str.length() == 53, "Length of public key should be 53 but is " + to_string(public_key_str.length()) + "."); // Check the prefix "EOS" currently for "K1" and "R1" key type string pubkey_prefix("EOS"); auto result = mismatch(pubkey_prefix.begin(), pubkey_prefix.end(), public_key_str.begin()); check(result.first == pubkey_prefix.end(), "Public key should be prefixed with 'EOS'."); // Remove the prefix auto base58substr = public_key_str.substr(pubkey_prefix.length()); // Decode the string with base 58 vector<unsigned char> vch; check(Base58::decode_base58(base58substr, vch), "Decoding of public key failed."); check(vch.size() == 37, "Invalid public key"); // Store the first 33 byte in an array ecc_public_key pubkey_data; //array<unsigned char,33> pubkey_data; copy_n(vch.begin(), 33, pubkey_data.begin()); // Check checksum checksum160 checksum2 = ripemd160(reinterpret_cast<char*>(pubkey_data.data()), 33); int res = memcmp(checksum2.extract_as_byte_array().data(), &vch.end()[-4], 4); check(res == 0, "ERROR: Wrong checksum, check your public key for typos."); return pubkey_data; } };
28.855263
127
0.688098
SavAct
61b07784b3e7efdb6c84e4ab7a9516e22ac470e8
1,119
cpp
C++
dataStructure/SqQueue/main.cpp
Duan-You/C-C-
c64e477889178efdb9b4e32a0f20cd76d39e937c
[ "Apache-2.0" ]
null
null
null
dataStructure/SqQueue/main.cpp
Duan-You/C-C-
c64e477889178efdb9b4e32a0f20cd76d39e937c
[ "Apache-2.0" ]
null
null
null
dataStructure/SqQueue/main.cpp
Duan-You/C-C-
c64e477889178efdb9b4e32a0f20cd76d39e937c
[ "Apache-2.0" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #define MAXSIZE 10 typedef int ElemType; typedef struct { ElemType *base; int front,rear; } SqQueue; void InitQueue(SqQueue &Q) { Q.base=(ElemType*)malloc(MAXSIZE*sizeof(ElemType)); if(!Q.base) exit(0); Q.rear=0; Q.front=Q.rear; } int QueueLength(SqQueue Q) { return (Q.rear-Q.front+MAXSIZE)%MAXSIZE; } bool QueueEmpty(SqQueue Q) { if(Q.front==Q.rear) return true; return false; } bool QueueFull(SqQueue Q) { if((Q.rear+1)%MAXSIZE==Q.front) return true; return false; } bool EnQueue(SqQueue &Q,ElemType e) { if((Q.rear+1)%MAXSIZE==Q.front) return false; Q.base[Q.rear]=e; Q.rear=(Q.rear+1)%MAXSIZE; return true; } bool DeQueue(SqQueue &Q,ElemType &e) { if(Q.front==Q.rear) return false; e=Q.base[Q.front]; Q.front=(Q.front+1)%MAXSIZE; return true; } int main() { SqQueue Q; InitQueue(Q); EnQueue(Q,1); EnQueue(Q,2); EnQueue(Q,3); EnQueue(Q,4); printf("%d ",Q.base[3]); ElemType e; DeQueue(Q,e); printf("%d ",e); }
15.328767
55
0.588919
Duan-You
61b0d6ddad2895b642ead9b0a8ce7134023de248
35,616
cpp
C++
src/monster_lichfire.cpp
PegasusEpsilon/Barony
6311f7e5da4835eaea65a95b5cc258409bb0dfa4
[ "FTL", "Zlib", "MIT" ]
373
2016-06-28T06:56:46.000Z
2022-03-23T02:32:54.000Z
src/monster_lichfire.cpp
PegasusEpsilon/Barony
6311f7e5da4835eaea65a95b5cc258409bb0dfa4
[ "FTL", "Zlib", "MIT" ]
361
2016-07-06T19:09:25.000Z
2022-03-26T14:14:19.000Z
src/monster_lichfire.cpp
PegasusEpsilon/Barony
6311f7e5da4835eaea65a95b5cc258409bb0dfa4
[ "FTL", "Zlib", "MIT" ]
129
2016-06-29T09:02:49.000Z
2022-01-23T09:56:06.000Z
/*------------------------------------------------------------------------------- BARONY File: monster_lich.cpp Desc: implements all of the lich monster's code Copyright 2013-2016 (c) Turning Wheel LLC, all rights reserved. See LICENSE for details. -------------------------------------------------------------------------------*/ #include "main.hpp" #include "game.hpp" #include "stat.hpp" #include "entity.hpp" #include "monster.hpp" #include "sound.hpp" #include "items.hpp" #include "net.hpp" #include "collision.hpp" #include "player.hpp" #include "magic/magic.hpp" static const int LICH_BODY = 0; static const int LICH_RIGHTARM = 2; static const int LICH_LEFTARM = 3; static const int LICH_HEAD = 4; static const int LICH_WEAPON = 5; void initLichFire(Entity* my, Stat* myStats) { my->initMonster(646); if ( multiplayer != CLIENT ) { MONSTER_SPOTSND = 372; MONSTER_SPOTVAR = 4; MONSTER_IDLESND = -1; MONSTER_IDLEVAR = 1; } if ( multiplayer != CLIENT && !MONSTER_INIT ) { if ( myStats != nullptr ) { if ( !myStats->leader_uid ) { myStats->leader_uid = 0; } // apply random stat increases if set in stat_shared.cpp or editor setRandomMonsterStats(myStats); for ( int c = 1; c < MAXPLAYERS; ++c ) { if ( !client_disconnected[c] ) { myStats->MAXHP += 500; } } myStats->HP = myStats->MAXHP; myStats->OLDHP = myStats->HP; // generate 6 items max, less if there are any forced items from boss variants int customItemsToGenerate = ITEM_CUSTOM_SLOT_LIMIT; // boss variants // random effects myStats->EFFECTS[EFF_LEVITATING] = true; myStats->EFFECTS_TIMERS[EFF_LEVITATING] = 0; // generates equipment and weapons if available from editor createMonsterEquipment(myStats); // create any custom inventory items from editor if available createCustomInventory(myStats, customItemsToGenerate); // count if any custom inventory items from editor int customItems = countCustomItems(myStats); //max limit of 6 custom items per entity. // count any inventory items set to default in edtior int defaultItems = countDefaultItems(myStats); my->setHardcoreStats(*myStats); // generate the default inventory items for the monster, provided the editor sprite allowed enough default slots switch ( defaultItems ) { case 6: case 5: case 4: case 3: case 2: case 1: default: break; } //give weapon if ( myStats->weapon == NULL && myStats->EDITOR_ITEMS[ITEM_SLOT_WEAPON] == 1 ) { myStats->weapon = newItem(CRYSTAL_SWORD, EXCELLENT, -5, 1, rand(), false, NULL); } } } // right arm Entity* entity = newEntity(649, 0, map.entities, nullptr); entity->sizex = 4; entity->sizey = 4; entity->skill[2] = my->getUID(); entity->flags[PASSABLE] = true; entity->flags[NOUPDATE] = true; entity->flags[USERFLAG2] = my->flags[USERFLAG2]; entity->focalx = limbs[LICH_FIRE][1][0]; // 0 entity->focaly = limbs[LICH_FIRE][1][1]; // 0 entity->focalz = limbs[LICH_FIRE][1][2]; // 2 entity->behavior = &actLichFireLimb; entity->parent = my->getUID(); node_t* node = list_AddNodeLast(&my->children); node->element = entity; node->deconstructor = &emptyDeconstructor; node->size = sizeof(Entity*); my->bodyparts.push_back(entity); // left arm entity = newEntity(648, 0, map.entities, nullptr); entity->sizex = 4; entity->sizey = 4; entity->skill[2] = my->getUID(); entity->flags[PASSABLE] = true; entity->flags[NOUPDATE] = true; entity->flags[USERFLAG2] = my->flags[USERFLAG2]; entity->focalx = limbs[LICH_FIRE][2][0]; // 0 entity->focaly = limbs[LICH_FIRE][2][1]; // 0 entity->focalz = limbs[LICH_FIRE][2][2]; // 2 entity->behavior = &actLichFireLimb; entity->parent = my->getUID(); node = list_AddNodeLast(&my->children); node->element = entity; node->deconstructor = &emptyDeconstructor; node->size = sizeof(Entity*); my->bodyparts.push_back(entity); // head entity = newEntity(647, 0, map.entities, nullptr); entity->yaw = my->yaw; entity->sizex = 4; entity->sizey = 4; entity->skill[2] = my->getUID(); entity->flags[PASSABLE] = true; entity->flags[NOUPDATE] = true; entity->flags[USERFLAG2] = my->flags[USERFLAG2]; entity->focalx = limbs[LICH_FIRE][3][0]; // 0 entity->focaly = limbs[LICH_FIRE][3][1]; // 0 entity->focalz = limbs[LICH_FIRE][3][2]; // -2 entity->behavior = &actLichFireLimb; entity->parent = my->getUID(); node = list_AddNodeLast(&my->children); node->element = entity; node->deconstructor = &emptyDeconstructor; node->size = sizeof(Entity*); my->bodyparts.push_back(entity); // world weapon entity = newEntity(-1, 0, map.entities, nullptr); entity->sizex = 4; entity->sizey = 4; entity->skill[2] = my->getUID(); entity->flags[PASSABLE] = true; entity->flags[NOUPDATE] = true; entity->flags[USERFLAG2] = my->flags[USERFLAG2]; entity->focalx = limbs[LICH_FIRE][4][0]; // 1.5 entity->focaly = limbs[LICH_FIRE][4][1]; // 0 entity->focalz = limbs[LICH_FIRE][4][2]; // -.5 entity->behavior = &actLichFireLimb; entity->parent = my->getUID(); entity->pitch = .25; node = list_AddNodeLast(&my->children); node->element = entity; node->deconstructor = &emptyDeconstructor; node->size = sizeof(Entity*); my->bodyparts.push_back(entity); } void lichFireDie(Entity* my) { if ( !my ) { return; } node_t* node, *nextnode; int c; for ( c = 0; c < 20; c++ ) { Entity* entity = spawnGib(my); if ( entity ) { switch ( c ) { case 0: entity->sprite = 230; break; case 1: entity->sprite = 231; break; case 2: entity->sprite = 233; break; case 3: entity->sprite = 235; break; case 4: entity->sprite = 236; break; case 5: entity->sprite = 646; break; case 6: entity->sprite = 647; break; case 7: entity->sprite = 648; break; case 8: entity->sprite = 649; break; default: break; } serverSpawnGibForClient(entity); } } my->removeMonsterDeathNodes(); playSoundEntity(my, 94, 128); my->removeLightField(); // kill all other monsters on the level for ( node = map.creatures->first; my->monsterLichAllyStatus == LICH_ALLY_DEAD && node != NULL; node = nextnode ) { nextnode = node->next; Entity* entity = (Entity*)node->element; if ( entity ) { if ( entity == my || entity->sprite == 650 ) { continue; } if ( entity->behavior == &actMonster ) { spawnExplosion(entity->x, entity->y, entity->z); Stat* stats = entity->getStats(); if ( stats ) { if ( stats->type != HUMAN ) { stats->HP = 0; } } } } } spawnExplosion(my->x, my->y, my->z); list_RemoveNode(my->mynode); return; } void actLichFireLimb(Entity* my) { my->actMonsterLimb(); } void lichFireAnimate(Entity* my, Stat* myStats, double dist) { node_t* node; Entity* entity = nullptr, *entity2 = nullptr; Entity* rightbody = nullptr; Entity* weaponarm = nullptr; Entity* head = nullptr; Entity* spellarm = nullptr; int bodypart; bool wearingring = false; // remove old light field my->removeLightField(); // obtain head entity node = list_Node(&my->children, LICH_HEAD); if ( node ) { head = (Entity*)node->element; } // set invisibility //TODO: isInvisible()? if ( multiplayer != CLIENT ) { if ( myStats->ring != nullptr ) if ( myStats->ring->type == RING_INVISIBILITY ) { wearingring = true; } if ( myStats->cloak != nullptr ) if ( myStats->cloak->type == CLOAK_INVISIBILITY ) { wearingring = true; } if ( myStats->EFFECTS[EFF_INVISIBLE] == true || wearingring == true ) { my->flags[INVISIBLE] = true; my->flags[BLOCKSIGHT] = false; bodypart = 0; for ( node = my->children.first; node != nullptr; node = node->next ) { if ( bodypart < LICH_RIGHTARM ) { bodypart++; continue; } if ( bodypart >= LICH_WEAPON ) { break; } entity = (Entity*)node->element; if ( !entity->flags[INVISIBLE] ) { entity->flags[INVISIBLE] = true; serverUpdateEntityBodypart(my, bodypart); } bodypart++; } } else { my->flags[INVISIBLE] = false; my->flags[BLOCKSIGHT] = true; bodypart = 0; for ( node = my->children.first; node != nullptr; node = node->next ) { if ( bodypart < LICH_RIGHTARM ) { bodypart++; continue; } if ( bodypart >= LICH_WEAPON ) { break; } entity = (Entity*)node->element; if ( entity->flags[INVISIBLE] ) { entity->flags[INVISIBLE] = false; serverUpdateEntityBodypart(my, bodypart); serverUpdateEntityFlag(my, INVISIBLE); } bodypart++; } } if ( my->monsterLichBattleState == LICH_BATTLE_IMMOBILE && my->ticks > TICKS_PER_SECOND ) { int sides = 0; int my_x = static_cast<int>(my->x) >> 4; int my_y = static_cast<int>(my->y) >> 4; int mapIndex = (my_y)* MAPLAYERS + (my_x + 1) * MAPLAYERS * map.height; if ( map.tiles[OBSTACLELAYER + mapIndex] ) // wall { ++sides; } mapIndex = (my_y)* MAPLAYERS + (my_x - 1) * MAPLAYERS * map.height; if ( map.tiles[OBSTACLELAYER + mapIndex] ) // wall { ++sides; } mapIndex = (my_y + 1) * MAPLAYERS + (my_x)* MAPLAYERS * map.height; if ( map.tiles[OBSTACLELAYER + mapIndex] ) // wall { ++sides; } mapIndex = (my_y - 1) * MAPLAYERS + (my_x)* MAPLAYERS * map.height; if ( map.tiles[OBSTACLELAYER + mapIndex] ) // wall { ++sides; } if ( sides != 4 ) { my->monsterLichBattleState = LICH_BATTLE_READY; real_t distToPlayer = 0; int c, playerToChase = -1; for ( c = 0; c < MAXPLAYERS; c++ ) { if ( players[c] && players[c]->entity ) { if ( !distToPlayer ) { distToPlayer = sqrt(pow(my->x - players[c]->entity->x, 2) + pow(my->y - players[c]->entity->y, 2)); playerToChase = c; } else { double newDistToPlayer = sqrt(pow(my->x - players[c]->entity->x, 2) + pow(my->y - players[c]->entity->y, 2)); if ( newDistToPlayer < distToPlayer ) { distToPlayer = newDistToPlayer; playerToChase = c; } } } } if ( playerToChase >= 0 ) { if ( players[playerToChase] && players[playerToChase]->entity ) { my->monsterAcquireAttackTarget(*players[playerToChase]->entity, MONSTER_STATE_PATH); } } } } // passive floating effect, server only. if ( my->monsterState == MONSTER_STATE_LICHFIRE_DIE ) { my->z -= 0.03; } else if ( my->monsterAttack == 0 ) { if ( my->monsterAnimationLimbOvershoot == ANIMATE_OVERSHOOT_NONE ) { if ( my->z < -1.2 ) { my->z += 0.25; } else { my->z = -1.2; my->monsterAnimationLimbOvershoot = ANIMATE_OVERSHOOT_TO_SETPOINT; } } if ( dist < 0.1 ) { // not moving, float. limbAnimateWithOvershoot(my, ANIMATE_Z, 0.005, -1.5, 0.005, -1.2, ANIMATE_DIR_NEGATIVE); } } else if ( my->monsterAttack == 1 || my->monsterAttack == 3 ) { if ( my->z < -1.2 ) { my->z += 0.25; } else { my->z = -1.2; my->monsterAnimationLimbOvershoot = ANIMATE_OVERSHOOT_NONE; } } } else { } if ( !my->light ) { my->light = lightSphereShadow(my->x / 16, my->y / 16, 4, 192); } //Lich stares you down while he does his special ability windup, and any of his spellcasting animations. if ( (my->monsterAttack == MONSTER_POSE_MAGIC_WINDUP1 || my->monsterAttack == MONSTER_POSE_MAGIC_WINDUP2 || my->monsterAttack == MONSTER_POSE_SPECIAL_WINDUP1 || my->monsterAttack == MONSTER_POSE_MAGIC_CAST1 || my->monsterState == MONSTER_STATE_LICH_CASTSPELLS) && my->monsterState != MONSTER_STATE_LICHFIRE_DIE ) { //Always turn to face the target. Entity* target = uidToEntity(my->monsterTarget); if ( target ) { my->lookAtEntity(*target); my->monsterRotate(); } } // move arms Entity* rightarm = nullptr; for (bodypart = 0, node = my->children.first; node != NULL; node = node->next, bodypart++) { if ( bodypart < LICH_RIGHTARM ) { if ( bodypart == 0 ) // insert head/body animation here. { if ( my->monsterAttack == MONSTER_POSE_SPECIAL_WINDUP1 ) { if ( multiplayer != CLIENT && my->monsterAnimationLimbOvershoot >= ANIMATE_OVERSHOOT_TO_SETPOINT ) { // handle z movement on windup limbAnimateWithOvershoot(my, ANIMATE_Z, 0.2, -0.6, 0.1, -3.2, ANIMATE_DIR_POSITIVE); // default z is -1.2 if ( my->z > -0.5 ) { my->z = -0.6; //failsafe for floating too low sometimes? } } } else if ( my->monsterAttack == MONSTER_POSE_MELEE_WINDUP3 ) { if ( multiplayer != CLIENT && my->monsterAnimationLimbOvershoot >= ANIMATE_OVERSHOOT_TO_SETPOINT ) { // handle z movement on windup limbAnimateWithOvershoot(my, ANIMATE_Z, 0.3, -0.6, 0.3, -4.0, ANIMATE_DIR_POSITIVE); // default z is -1.2 if ( my->z > -0.5 ) { my->z = -0.6; //failsafe for floating too low sometimes? } } } else { if ( head && head->pitch > PI ) { limbAnimateToLimit(head, ANIMATE_PITCH, 0.1, 0, false, 0.0); // return head to a neutral position. } } } continue; } entity = (Entity*)node->element; entity->x = my->x; entity->y = my->y; entity->z = my->z; if ( bodypart != LICH_HEAD ) { // lich head turns to track player, other limbs will rotate as normal. if ( bodypart == LICH_LEFTARM && my->monsterAttack == MONSTER_POSE_MAGIC_WINDUP1 ) { // don't rotate leftarm here during spellcast. } else { entity->yaw = my->yaw; } } else { } if ( bodypart == LICH_RIGHTARM ) { // weapon holding arm. weaponarm = entity; if ( my->monsterAttack == 0 ) { entity->pitch = PI / 8; // default arm pitch when not attacking. } else { // vertical chop windup if ( my->monsterAttack == MONSTER_POSE_MELEE_WINDUP1 ) { if ( my->monsterAttackTime == 0 ) { // init rotations my->monsterWeaponYaw = 0; weaponarm->roll = 0; weaponarm->skill[1] = 0; } limbAnimateToLimit(weaponarm, ANIMATE_PITCH, -0.4, 5 * PI / 4, false, 0.0); if ( my->monsterAttackTime >= 6 / (monsterGlobalAnimationMultiplier / 10.0) ) { if ( multiplayer != CLIENT ) { my->attack(1, 0, nullptr); } } } // vertical chop attack else if ( my->monsterAttack == 1 ) { if ( weaponarm->skill[1] == 0 ) { // chop forwards if ( limbAnimateToLimit(weaponarm, ANIMATE_PITCH, 0.4, PI / 2, false, 0.0) ) { weaponarm->skill[1] = 1; } } else if ( weaponarm->skill[1] == 1 ) { if ( limbAnimateToLimit(weaponarm, ANIMATE_PITCH, -0.25, PI / 8, false, 0.0) ) { my->monsterWeaponYaw = 0; weaponarm->pitch = PI / 8; weaponarm->roll = 0; my->monsterAttack = 0; if ( multiplayer != CLIENT ) { if ( my->monsterLichFireMeleePrev == LICH_ATK_VERTICAL_QUICK ) { my->monsterHitTime = HITRATE; } } } } } // horizontal chop windup else if ( my->monsterAttack == MONSTER_POSE_MELEE_WINDUP2 ) { int windupDuration = (my->monsterState == MONSTER_STATE_LICH_CASTSPELLS) ? 10 : 6; if ( my->monsterAttackTime == 0 ) { // init rotations weaponarm->pitch = PI / 4; weaponarm->roll = 0; my->monsterArmbended = 1; // don't actually bend the arm, we're just using this to adjust the limb offsets in the weapon code. weaponarm->skill[1] = 0; my->monsterWeaponYaw = 6 * PI / 4; if ( my->monsterState == MONSTER_STATE_LICH_CASTSPELLS ) { createParticleDot(my); } } limbAnimateToLimit(weaponarm, ANIMATE_ROLL, -0.3, 3 * PI / 2, false, 0.0); limbAnimateToLimit(weaponarm, ANIMATE_PITCH, -0.3, 0, false, 0.0); if ( my->monsterAttackTime >= windupDuration / (monsterGlobalAnimationMultiplier / 10.0) ) { if ( multiplayer != CLIENT ) { my->attack(2, 0, nullptr); } } } // horizontal chop attack else if ( my->monsterAttack == 2 ) { if ( weaponarm->skill[1] == 0 ) { // swing // this->weaponyaw is OK to change for clients, as server doesn't update it for them. if ( limbAnimateToLimit(my, ANIMATE_WEAPON_YAW, 0.3, 2 * PI / 8, false, 0.0) ) { weaponarm->skill[1] = 1; } } else if ( weaponarm->skill[1] == 1 ) { // post-swing return to normal weapon yaw if ( limbAnimateToLimit(my, ANIMATE_WEAPON_YAW, -0.5, 0, false, 0.0) ) { // restore pitch and roll after yaw is set if ( limbAnimateToLimit(weaponarm, ANIMATE_ROLL, 0.4, 0, false, 0.0) && limbAnimateToLimit(weaponarm, ANIMATE_PITCH, 0.4, PI / 8, false, 0.0) ) { weaponarm->skill[1] = 0; my->monsterWeaponYaw = 0; weaponarm->pitch = PI / 8; weaponarm->roll = 0; my->monsterArmbended = 0; my->monsterAttack = 0; if ( multiplayer != CLIENT ) { if ( my->monsterLichFireMeleePrev == LICH_ATK_HORIZONTAL_QUICK ) { my->monsterHitTime = HITRATE; } } } } } } else if ( my->monsterAttack == MONSTER_POSE_SPECIAL_WINDUP1 ) { if ( my->monsterAttackTime == 0 ) { // init rotations my->monsterWeaponYaw = 0; weaponarm->roll = 0; weaponarm->skill[1] = 0; if ( my->monsterState == MONSTER_STATE_LICH_CASTSPELLS || my->monsterState == MONSTER_STATE_LICHFIRE_DIE ) { createParticleDropRising(my, 672, 0.7); } else { createParticleDropRising(my, 607, 1.0); } if ( multiplayer != CLIENT ) { if ( my->monsterState != MONSTER_STATE_LICHFIRE_DIE ) { my->monsterAnimationLimbOvershoot = ANIMATE_OVERSHOOT_TO_SETPOINT; // lich can't be paralyzed, use EFF_STUNNED instead. myStats->EFFECTS[EFF_STUNNED] = true; myStats->EFFECTS_TIMERS[EFF_STUNNED] = 50; } else { myStats->EFFECTS[EFF_STUNNED] = true; myStats->EFFECTS_TIMERS[EFF_STUNNED] = 25; } } } // only do the following during 2nd + end stage of overshoot animation. if ( my->monsterAnimationLimbOvershoot != ANIMATE_OVERSHOOT_TO_SETPOINT ) { limbAnimateToLimit(head, ANIMATE_PITCH, -0.1, 11 * PI / 6, true, 0.05); limbAnimateToLimit(weaponarm, ANIMATE_PITCH, -0.3, 5 * PI / 4, false, 0.0); if ( my->monsterAttackTime >= 50 / (monsterGlobalAnimationMultiplier / 10.0) ) { if ( multiplayer != CLIENT ) { if ( my->monsterState != MONSTER_STATE_LICHFIRE_DIE ) { my->attack(1, 0, nullptr); //optional? } else { my->monsterAttackTime = 20; //reset this attack time to allow successive strikes } real_t dir = 0.f; Entity* target = uidToEntity(my->monsterTarget); if ( my->monsterState == MONSTER_STATE_LICH_CASTSPELLS ) { if ( target ) { real_t targetDist = std::max(8.0, entityDist(my, target) - 48.0); for ( int i = 0; i < 5; ++i ) { my->castFallingMagicMissile(SPELL_FIREBALL, targetDist -4 + rand() % 9 + i * 16, 0.f, i * 20); } } } else if ( my->monsterState == MONSTER_STATE_LICHFIRE_DIE ) { real_t randomAngle = (PI / 180.f) * (rand() % 360); for ( int i = 0; i < 5; ++i ) { my->castFallingMagicMissile(SPELL_FIREBALL, 16.f - 4 + rand() % 9 + i * 16, randomAngle, i * 20); } for ( int i = 0; i < 5; ++i ) { my->castFallingMagicMissile(SPELL_FIREBALL, 16.f - 4 + rand() % 9 + i * 16, randomAngle + PI / 2, i * 20); } for ( int i = 0; i < 5; ++i ) { my->castFallingMagicMissile(SPELL_FIREBALL, 16.f - 4 + rand() % 9 + i * 16, randomAngle + PI, i * 20); } for ( int i = 0; i < 5; ++i ) { my->castFallingMagicMissile(SPELL_FIREBALL, 16.f - 4 + rand() % 9 + i * 16, randomAngle + 3 * PI / 2, i * 20); } } else { if ( target ) { real_t targetDist = std::min(entityDist(my, target), 32.0); for ( int i = 0; i < 8; ++i ) { my->castFallingMagicMissile(SPELL_FIREBALL, std::max(targetDist - 8 + rand() % 8, 4.0), dir + i * PI / 4, 0); } } else { for ( int i = 0; i < 8; ++i ) { my->castFallingMagicMissile(SPELL_FIREBALL, 16 + rand() % 8, dir + i * PI / 4, 0); } } } } } } } else if ( my->monsterAttack == MONSTER_POSE_MELEE_WINDUP3 ) { int windupDuration = (my->monsterState == MONSTER_STATE_LICH_CASTSPELLS) ? 20 : 40; if ( multiplayer != CLIENT && myStats->EFFECTS[EFF_VAMPIRICAURA] ) { windupDuration = 20; } if ( my->monsterAttackTime == 0 ) { // init rotations my->monsterWeaponYaw = 10 * PI / 6; weaponarm->roll = 0; weaponarm->skill[1] = 0; createParticleDot(my); if ( multiplayer != CLIENT ) { my->monsterAnimationLimbOvershoot = ANIMATE_OVERSHOOT_TO_SETPOINT; // // lich can't be paralyzed, use EFF_STUNNED instead. myStats->EFFECTS[EFF_STUNNED] = true; myStats->EFFECTS_TIMERS[EFF_STUNNED] = windupDuration; } } // only do the following during 2nd + end stage of overshoot animation. if ( my->monsterAnimationLimbOvershoot != ANIMATE_OVERSHOOT_TO_SETPOINT ) { limbAnimateToLimit(head, ANIMATE_PITCH, -0.1, 11 * PI / 6, true, 0.05); limbAnimateToLimit(weaponarm, ANIMATE_PITCH, -0.3, 5 * PI / 4, false, 0.0); if ( my->monsterAttackTime >= windupDuration / (monsterGlobalAnimationMultiplier / 10.0) ) { if ( multiplayer != CLIENT ) { my->attack(3, 0, nullptr); } } } } // vertical chop after melee3 else if ( my->monsterAttack == 3 ) { if ( weaponarm->skill[1] == 0 ) { // chop forwards if ( limbAnimateToLimit(weaponarm, ANIMATE_PITCH, 0.4, PI / 2, false, 0.0) ) { weaponarm->skill[1] = 1; } limbAnimateToLimit(my, ANIMATE_WEAPON_YAW, 0.15, 1 * PI / 6, false, 0.0); // swing across the body } else if ( weaponarm->skill[1] == 1 ) { if ( limbAnimateToLimit(weaponarm, ANIMATE_PITCH, -0.25, PI / 8, false, 0.0) ) { my->monsterWeaponYaw = 0; weaponarm->pitch = PI / 8; weaponarm->roll = 0; my->monsterAttack = 0; } } } } } else if ( bodypart == LICH_LEFTARM ) { spellarm = entity; if ( my->monsterAttack == MONSTER_POSE_SPECIAL_WINDUP1 || my->monsterAttack == MONSTER_POSE_MELEE_WINDUP3 ) { spellarm->pitch = weaponarm->pitch; } else if ( my->monsterAttack == MONSTER_POSE_MAGIC_WINDUP1 ) { if ( my->monsterAttackTime == 0 ) { // init rotations spellarm->roll = 0; spellarm->skill[1] = 0; spellarm->pitch = 12 * PI / 8; spellarm->yaw = my->yaw; createParticleDot(my); playSoundEntityLocal(my, 170, 32); if ( multiplayer != CLIENT ) { myStats->EFFECTS[EFF_STUNNED] = true; myStats->EFFECTS_TIMERS[EFF_STUNNED] = 20; } } double animationYawSetpoint = normaliseAngle2PI(my->yaw + 1 * PI / 8); double animationYawEndpoint = normaliseAngle2PI(my->yaw - 1 * PI / 8); double armSwingRate = 0.15; double animationPitchSetpoint = 13 * PI / 8; double animationPitchEndpoint = 11 * PI / 8; if ( spellarm->skill[1] == 0 ) { if ( limbAnimateToLimit(spellarm, ANIMATE_PITCH, armSwingRate, animationPitchSetpoint, false, 0.0) ) { if ( limbAnimateToLimit(spellarm, ANIMATE_YAW, armSwingRate, animationYawSetpoint, false, 0.0) ) { spellarm->skill[1] = 1; } } } else { if ( limbAnimateToLimit(spellarm, ANIMATE_PITCH, -armSwingRate, animationPitchEndpoint, false, 0.0) ) { if ( limbAnimateToLimit(spellarm, ANIMATE_YAW, -armSwingRate, animationYawEndpoint, false, 0.0) ) { spellarm->skill[1] = 0; } } } if ( my->monsterAttackTime >= 1 * ANIMATE_DURATION_WINDUP / (monsterGlobalAnimationMultiplier / 10.0) ) { if ( multiplayer != CLIENT ) { // swing the arm after we prepped the spell //my->castFallingMagicMissile(SPELL_FIREBALL, 16.0, 0.0); my->attack(MONSTER_POSE_MAGIC_WINDUP2, 0, nullptr); } } } // raise arm to cast spell else if ( my->monsterAttack == MONSTER_POSE_MAGIC_WINDUP2 ) { if ( my->monsterAttackTime == 0 ) { // init rotations spellarm->pitch = 0; spellarm->roll = 0; } spellarm->skill[1] = 0; if ( limbAnimateToLimit(spellarm, ANIMATE_PITCH, -0.3, 5 * PI / 4, false, 0.0) ) { if ( multiplayer != CLIENT ) { my->attack(MONSTER_POSE_MAGIC_CAST1, 0, nullptr); } } } // vertical spell attack else if ( my->monsterAttack == MONSTER_POSE_MAGIC_CAST1 ) { if ( spellarm->skill[1] == 0 ) { // chop forwards if ( limbAnimateToLimit(spellarm, ANIMATE_PITCH, 0.4, PI / 2, false, 0.0) ) { spellarm->skill[1] = 1; if ( multiplayer != CLIENT ) { //my->castOrbitingMagicMissile(SPELL_FIREBALL, 16.0, 0.0); if ( rand() % 2 ) { if ( my->monsterLichAllyStatus == LICH_ALLY_DEAD && !myStats->EFFECTS[EFF_VAMPIRICAURA] && my->monsterState != MONSTER_STATE_LICH_CASTSPELLS ) { createParticleDropRising(my, 600, 0.7); serverSpawnMiscParticles(my, PARTICLE_EFFECT_VAMPIRIC_AURA, 600); myStats->EFFECTS[EFF_VAMPIRICAURA] = true; myStats->EFFECTS_TIMERS[EFF_VAMPIRICAURA] = 600; } else { castSpell(my->getUID(), getSpellFromID(SPELL_FIREBALL), true, false); } } else { castSpell(my->getUID(), getSpellFromID(SPELL_BLEED), true, false); } } } } else if ( spellarm->skill[1] == 1 ) { if ( limbAnimateToLimit(spellarm, ANIMATE_PITCH, -0.25, PI / 8, false, 0.0) ) { spellarm->pitch = 0; spellarm->roll = 0; my->monsterAttack = 0; } } } else { entity->pitch = 0; } } switch ( bodypart ) { // right arm case LICH_RIGHTARM: entity->x += 2.75 * cos(my->yaw + PI / 2); entity->y += 2.75 * sin(my->yaw + PI / 2); entity->z -= 3.25; entity->yaw += MONSTER_WEAPONYAW; break; // left arm case LICH_LEFTARM: entity->x -= 2.75 * cos(my->yaw + PI / 2); entity->y -= 2.75 * sin(my->yaw + PI / 2); entity->z -= 3.25; if ( !(my->monsterAttack == MONSTER_POSE_MELEE_WINDUP2 || my->monsterAttack == 2 || my->monsterAttack == MONSTER_POSE_MAGIC_WINDUP1 || my->monsterAttack == 3) ) { entity->yaw -= MONSTER_WEAPONYAW; } break; // head case LICH_HEAD: { entity->z -= 4.25; node_t* tempNode; Entity* playertotrack = NULL; double disttoplayer = 0.0; Entity* target = uidToEntity(my->monsterTarget); if ( target && my->monsterAttack == 0 ) { entity->lookAtEntity(*target); entity->monsterRotate(); } else { // align head as normal if attacking. entity->yaw = my->yaw; } break; } case LICH_WEAPON: // set sprites, invisibility check etc. if ( multiplayer != CLIENT ) { if ( myStats->weapon == nullptr || myStats->EFFECTS[EFF_INVISIBLE] || wearingring ) //TODO: isInvisible()? { entity->flags[INVISIBLE] = true; } else { entity->sprite = itemModel(myStats->weapon); if ( itemCategory(myStats->weapon) == SPELLBOOK ) { entity->flags[INVISIBLE] = true; } else { entity->flags[INVISIBLE] = false; } } if ( multiplayer == SERVER ) { // update sprites for clients if ( entity->skill[10] != entity->sprite ) { entity->skill[10] = entity->sprite; serverUpdateEntityBodypart(my, bodypart); } if ( entity->skill[11] != entity->flags[INVISIBLE] ) { entity->skill[11] = entity->flags[INVISIBLE]; serverUpdateEntityBodypart(my, bodypart); } if ( entity->getUID() % (TICKS_PER_SECOND * 10) == ticks % (TICKS_PER_SECOND * 10) ) { serverUpdateEntityBodypart(my, bodypart); } } } else { if ( entity->sprite <= 0 ) { entity->flags[INVISIBLE] = true; } } // animation if ( entity != nullptr ) { if ( weaponarm == nullptr ) { return; } entity->x = weaponarm->x;// +1.5 * cos(weaponarm->yaw);// *(my->monsterAttack == 0); entity->y = weaponarm->y;// +1.5 * sin(weaponarm->yaw);// * (my->monsterAttack == 0); entity->z = weaponarm->z;// -.5 * (my->monsterAttack == 0); entity->pitch = weaponarm->pitch; entity->yaw = weaponarm->yaw + 0.1 * (my->monsterAttack == 0); entity->roll = weaponarm->roll; if ( my->monsterAttack == 2 || my->monsterAttack == MONSTER_POSE_MELEE_WINDUP2 ) { // don't boost pitch during side-swipe } else { entity->pitch += PI / 2 + 0.25; } entity->focalx = limbs[LICH_FIRE][4][0]; entity->focaly = limbs[LICH_FIRE][4][1]; entity->focalz = limbs[LICH_FIRE][4][2]; if ( my->monsterArmbended ) { // adjust focal points during side swing entity->focalx = limbs[LICH_FIRE][4][0] - 0.8; entity->focalz = limbs[LICH_FIRE][4][2] + 1; entity->pitch += cos(weaponarm->roll) * PI / 2; entity->yaw -= sin(weaponarm->roll) * PI / 2; } } break; default: break; } } if ( my->monsterAttack > 0 && my->monsterAttack <= MONSTER_POSE_MAGIC_CAST3 ) { my->monsterAttackTime++; } else if ( my->monsterAttack == 0 ) { my->monsterAttackTime = 0; } else { // do nothing, don't reset attacktime or increment it. } } void Entity::lichFireSetNextAttack(Stat& myStats) { monsterLichFireMeleePrev = monsterLichFireMeleeSeq; //messagePlayer(0, "melee: %d, magic %d", monsterLichMeleeSwingCount, monsterLichMagicCastCount); switch ( monsterLichFireMeleeSeq ) { case LICH_ATK_VERTICAL_SINGLE: ++monsterLichMeleeSwingCount; switch ( rand() % 8 ) { case 0: case 1: case 2: if ( monsterLichMeleeSwingCount < 5 ) { monsterLichFireMeleeSeq = LICH_ATK_VERTICAL_SINGLE; } else { monsterLichFireMeleeSeq = LICH_ATK_VERTICAL_QUICK; monsterLichMeleeSwingCount = 0; } break; case 3: case 4: case 5: if ( monsterLichMeleeSwingCount < 5 ) { monsterLichFireMeleeSeq = LICH_ATK_HORIZONTAL_SINGLE; } else { monsterLichFireMeleeSeq = LICH_ATK_HORIZONTAL_QUICK; monsterLichMeleeSwingCount = 0; } break; case 6: monsterLichFireMeleeSeq = LICH_ATK_VERTICAL_QUICK; monsterLichMeleeSwingCount = 0; break; case 7: monsterLichFireMeleeSeq = LICH_ATK_HORIZONTAL_QUICK; monsterLichMeleeSwingCount = 0; break; default: break; } break; case LICH_ATK_HORIZONTAL_SINGLE: ++monsterLichMeleeSwingCount; switch ( rand() % 4 ) { case 0: case 1: case 2: monsterLichFireMeleeSeq = LICH_ATK_VERTICAL_SINGLE; break; case 3: monsterLichFireMeleeSeq = LICH_ATK_RISING_RAIN; monsterLichMeleeSwingCount = 0; break; default: break; } break; case LICH_ATK_RISING_RAIN: switch ( rand() % 4 ) { case 0: case 1: case 2: monsterLichFireMeleeSeq = LICH_ATK_VERTICAL_SINGLE; break; case 3: monsterLichFireMeleeSeq = LICH_ATK_HORIZONTAL_SINGLE; break; default: break; } break; case LICH_ATK_BASICSPELL_SINGLE: ++monsterLichMagicCastCount; if ( monsterLichMagicCastCount > 2 || rand() % 2 == 0 ) { monsterLichFireMeleeSeq = LICH_ATK_VERTICAL_SINGLE; monsterLichMagicCastCount = 0; } break; case LICH_ATK_RISING_SINGLE: switch ( rand() % 4 ) { case 0: case 1: case 2: monsterLichFireMeleeSeq = LICH_ATK_VERTICAL_SINGLE; break; case 3: monsterLichFireMeleeSeq = LICH_ATK_HORIZONTAL_SINGLE; break; default: break; } break; case LICH_ATK_VERTICAL_QUICK: monsterLichFireMeleeSeq = LICH_ATK_HORIZONTAL_RETURN; break; case LICH_ATK_HORIZONTAL_RETURN: switch ( rand() % 4 ) { case 0: case 1: case 2: monsterLichFireMeleeSeq = LICH_ATK_VERTICAL_SINGLE; break; case 3: monsterLichFireMeleeSeq = LICH_ATK_HORIZONTAL_SINGLE; break; default: break; } break; case LICH_ATK_HORIZONTAL_QUICK: monsterLichFireMeleeSeq = LICH_ATK_RISING_SINGLE; break; default: break; } } void Entity::lichFireTeleport() { monsterLichTeleportTimer = 0; Entity* spellTimer = createParticleTimer(this, 40, 593); if ( monsterState == MONSTER_STATE_LICHFIRE_TELEPORT_STATIONARY ) { spellTimer->particleTimerEndAction = PARTICLE_EFFECT_LICHFIRE_TELEPORT_STATIONARY; // teleport behavior of timer. } else { spellTimer->particleTimerEndAction = PARTICLE_EFFECT_LICH_TELEPORT_ROAMING; // teleport behavior of timer. } spellTimer->particleTimerEndSprite = 593; // sprite to use for end of timer function. spellTimer->particleTimerCountdownAction = PARTICLE_TIMER_ACTION_SHOOT_PARTICLES; spellTimer->particleTimerCountdownSprite = 593; if ( multiplayer == SERVER ) { serverSpawnMiscParticles(this, spellTimer->particleTimerEndAction, 593); } } void Entity::lichFireSummonMonster(Monster creature) { Entity* target = nullptr; for ( node_t* searchNode = map.entities->first; searchNode != nullptr; searchNode = searchNode->next ) { target = (Entity*)searchNode->element; if ( target->behavior == &actDevilTeleport && target->sprite == 128 ) { break; // found specified center of map } } if ( target ) { int tries = 25; // max iteration in while loop, fail safe. long spawn_x = (target->x / 16) - 11 + rand() % 23; long spawn_y = (target->y / 16) - 11 + rand() % 23; int index = (spawn_x)* MAPLAYERS + (spawn_y)* MAPLAYERS * map.height; while ( tries > 0 && (map.tiles[OBSTACLELAYER + index] == 1 || map.tiles[index] == 0 || swimmingtiles[map.tiles[index]] || lavatiles[map.tiles[index]]) ) { // find a spot that isn't wall, no floor or lava/water tiles. spawn_x = (target->x / 16) - 11 + rand() % 23; spawn_y = (target->y / 16) - 11 + rand() % 23; index = (spawn_x)* MAPLAYERS + (spawn_y)* MAPLAYERS * map.height; --tries; } if ( tries > 0 ) { Entity* timer = createParticleTimer(this, 70, 174); timer->x = spawn_x * 16.0 + 8; timer->y = spawn_y * 16.0 + 8; timer->z = 0; timer->particleTimerCountdownAction = PARTICLE_TIMER_ACTION_SUMMON_MONSTER; timer->particleTimerCountdownSprite = 174; timer->particleTimerEndAction = PARTICLE_EFFECT_SUMMON_MONSTER; timer->particleTimerVariable1 = creature; serverSpawnMiscParticlesAtLocation(spawn_x, spawn_y, 0, PARTICLE_EFFECT_SUMMON_MONSTER, 174); } } }
27.146341
132
0.594789
PegasusEpsilon
61b1d64c5eb0868d6632193924e2bf5af52bc0f7
2,236
cpp
C++
practica1/main.cpp
Martincho07/IG-mini-PT
673a039e1ae352a42cf745ff661343355d924e41
[ "BSD-3-Clause" ]
3
2021-05-12T21:54:48.000Z
2021-12-20T02:59:00.000Z
practica1/main.cpp
Martincho07/IG-mini-PT
673a039e1ae352a42cf745ff661343355d924e41
[ "BSD-3-Clause" ]
null
null
null
practica1/main.cpp
Martincho07/IG-mini-PT
673a039e1ae352a42cf745ff661343355d924e41
[ "BSD-3-Clause" ]
null
null
null
/********************************************************************************* * Main * * File: main.cpp * Author: Fernando Peña (NIA: 756012) * Author: Jose Daniel Subias Sarrato (NIA: 759533) * Date: 22/10/2020 * Coms: Informática Gráfica, curso 2020-2021 **********************************************************************************/ #include <fstream> #include <iostream> #include "geometry.hpp" #include "planet.hpp" Planet readStation(std::istream &is, bool interactive) { Vector3 axis; Point3 center, refCity; float inclination, azimuth; float x, y, z; // If interactive is false, supress the ouput if (!interactive) { std::cout.setstate(std::ios::failbit); } std::cout << "Enter a station:" << std::endl; std::cout << "\tPlanet center: "; is >> x >> y >> z; center = Point3(x, y, z); std::cout << "\tPlanet axis: "; is >> x >> y >> z; axis = Vector3(x, y, z); std::cout << "\tReference city: "; is >> x >> y >> z; refCity = Point3(x, y, z); std::cout << "\tStation inclination: "; is >> inclination; std::cout << "\tStation azimuth: "; is >> azimuth; // Restore cout status std::cout.clear(); std::cout << center << axis << refCity << inclination << azimuth << std::endl; return Planet(center, refCity, axis, inclination, azimuth); } int main(int argc, char **argv) { Planet planet1, planet2; // If there's a file as argument, read it // Else, ask for the stations from standard input if (argc > 1) { std::filebuf fb; if (fb.open(argv[1], std::ios::in)) { std::istream is(&fb); planet1 = readStation(is, false); planet2 = readStation(is, false); } else { std::cout << "No se ha podido abrir el fichero: " << argv[1] << std::endl; return 1; } } else { std::cout << "Origin planet" << std::endl; planet1 = readStation(std::cin, true); std::cout << "\nDestination planet" << std::endl; planet2 = readStation(std::cin, true); } std::cout << std::endl << "Trayectorias" << std::endl; launch(planet1, planet2); return 0; }
28.303797
86
0.518336
Martincho07
ba0d31e39ef4f85c0e2dfa6afda08a143e037513
1,252
cpp
C++
tests/SES_Variable_Mult_Div_Constructor_Tests.cpp
dolovnyak/simple-equation-solver
a10b44cb6f6de86441c3216c07c7ec8b761d97ae
[ "Unlicense" ]
null
null
null
tests/SES_Variable_Mult_Div_Constructor_Tests.cpp
dolovnyak/simple-equation-solver
a10b44cb6f6de86441c3216c07c7ec8b761d97ae
[ "Unlicense" ]
null
null
null
tests/SES_Variable_Mult_Div_Constructor_Tests.cpp
dolovnyak/simple-equation-solver
a10b44cb6f6de86441c3216c07c7ec8b761d97ae
[ "Unlicense" ]
null
null
null
#include "utilities.hpp" #include <gtest/gtest.h> #include "SES_Variable.hpp" class SES_Variable_Mult_Div_Constructor_Tests : public ::testing::Test { }; TEST_F(SES_Variable_Mult_Div_Constructor_Tests, SES_Var_Constructor_Test) { try { SES_Variable var0(2, 0); ASSERT_TRUE(var0.GetDegree() == 0); ASSERT_TRUE(var0.GetCoefficient() == 2); SES_Variable var1(512.53, 1); ASSERT_TRUE(var1.GetDegree() == 1); ASSERT_TRUE(var1.GetCoefficient() == 512.53); SES_Variable var2(51.2, 2); ASSERT_TRUE(var2.GetDegree() == 2); ASSERT_TRUE(var2.GetCoefficient() == 51.2); } catch (const std::exception& exception) { std::cout << exception.what() << std::endl; ASSERT_TRUE(false); } try{ SES_Variable varMult1(2, 2); varMult1 = varMult1 * SES_Variable(-2, 0); ASSERT_TRUE(varMult1.GetCoefficient() == -4); ASSERT_TRUE(varMult1.GetDegree() == 2); varMult1 = varMult1 / SES_Variable(-8, 2); ASSERT_TRUE(varMult1.GetCoefficient() == 0.5); ASSERT_TRUE(varMult1.GetDegree() == 0); varMult1 = varMult1 * SES_Variable(-2, 1); ASSERT_TRUE(varMult1.GetCoefficient() == -1); ASSERT_TRUE(varMult1.GetDegree() == 1); } catch (const std::exception& exception) { std::cout << exception.what() << std::endl; ASSERT_TRUE(false); } }
27.822222
75
0.699681
dolovnyak
ba0d36a910a9713b8e48b75253d87a9fbcf54538
8,896
cpp
C++
src/test/cstdint.cpp
danitzarqp106/Prueba
06635ca46a68306073e542b7cb4b519858e44dc2
[ "BSL-1.0" ]
null
null
null
src/test/cstdint.cpp
danitzarqp106/Prueba
06635ca46a68306073e542b7cb4b519858e44dc2
[ "BSL-1.0" ]
null
null
null
src/test/cstdint.cpp
danitzarqp106/Prueba
06635ca46a68306073e542b7cb4b519858e44dc2
[ "BSL-1.0" ]
null
null
null
// Copyright John McFarlane 2015 - 2016. // 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) //#include <limits> #include <sg14/cstdint> #include <sg14/limits> #include <sg14/type_traits> using sg14::_type_traits_impl::first_fit; using std::is_same; using sg14::make_signed; using sg14::make_unsigned; //////////////////////////////////////////////////////////////////////////////// // sg14::width using sg14::width; static_assert(width<std::int8_t>::value == 8, "sg14::width test failed"); static_assert(width<std::uint8_t>::value == 8, "sg14::width test failed"); static_assert(width<std::int16_t>::value == 16, "sg14::width test failed"); static_assert(width<std::uint16_t>::value == 16, "sg14::width test failed"); static_assert(width<std::int32_t>::value == 32, "sg14::width test failed"); static_assert(width<std::uint32_t>::value == 32, "sg14::width test failed"); static_assert(width<std::int64_t>::value == 64, "sg14::width test failed"); static_assert(width<std::uint64_t>::value == 64, "sg14::width test failed"); #if defined(SG14_INT128_ENABLED) static_assert(width<SG14_INT128>::value == 128, "sg14::width test failed"); static_assert(width<SG14_UINT128>::value == 128, "sg14::width test failed"); #endif //////////////////////////////////////////////////////////////////////////////// // sg14::width_v #if (__cplusplus >= 201402L) using sg14::width_v; static_assert(width_v<std::int8_t> == 8, "sg14::width_v test failed"); static_assert(width_v<std::uint8_t> == 8, "sg14::width_v test failed"); static_assert(width_v<std::int16_t> == 16, "sg14::width_v test failed"); static_assert(width_v<std::uint16_t> == 16, "sg14::width_v test failed"); static_assert(width_v<std::int32_t> == 32, "sg14::width_v test failed"); static_assert(width_v<std::uint32_t> == 32, "sg14::width_v test failed"); static_assert(width_v<std::int64_t> == 64, "sg14::width_v test failed"); static_assert(width_v<std::uint64_t> == 64, "sg14::width_v test failed"); #if defined(SG14_INT128_ENABLED) static_assert(width_v<SG14_INT128> == 128, "sg14::width_v test failed"); static_assert(width_v<SG14_UINT128> == 128, "sg14::width_v test failed"); #endif #endif //////////////////////////////////////////////////////////////////////////////// // sg14::_type_traits_impl::first_fit_t static_assert( std::is_same<typename first_fit<16, std::tuple<std::int8_t, std::int16_t, std::int32_t>>::type, std::int16_t>::value, ""); static_assert( std::is_same<typename first_fit<16, std::tuple<std::int32_t, std::int16_t, std::int8_t>>::type, std::int32_t>::value, ""); //////////////////////////////////////////////////////////////////////////////// // some random sg14::set_width #if defined(SG14_INT128_ENABLED) static_assert(is_same<sg14::set_width<unsigned long, 78>::type, SG14_UINT128>::value, "sg14::set_width_t test failed"); #endif //////////////////////////////////////////////////////////////////////////////// // sg14::set_width_t using sg14::set_width_t; static_assert(is_same<set_width_t<std::uint8_t, 8>, std::uint8_t>::value, "sg14::set_width_t test failed"); static_assert(is_same<set_width_t<std::int8_t, 16>, std::int16_t>::value, "sg14::set_width_t test failed"); static_assert(is_same<set_width_t<std::uint16_t, 24>, std::uint32_t>::value, "sg14::set_width_t test failed"); static_assert(is_same<set_width_t<std::int16_t, 32>, std::int32_t>::value, "sg14::set_width_t test failed"); static_assert(is_same<set_width_t<std::uint32_t, 40>, std::uint64_t>::value, "sg14::set_width_t test failed"); static_assert(is_same<set_width_t<std::int32_t, 48>, std::int64_t>::value, "sg14::set_width_t test failed"); static_assert(is_same<set_width_t<std::uint64_t, 56>, std::uint64_t>::value, "sg14::set_width_t test failed"); static_assert(is_same<set_width_t<std::int64_t, 64>, std::int64_t>::value, "sg14::set_width_t test failed"); #if defined(SG14_INT128_ENABLED) static_assert(is_same<set_width_t<std::uint8_t, 72>, SG14_UINT128>::value, "sg14::set_width_t test failed"); static_assert(is_same<set_width_t<std::int8_t, 80>, SG14_INT128>::value, "sg14::set_width_t test failed"); static_assert(is_same<set_width_t<std::uint16_t, 88>, SG14_UINT128>::value, "sg14::set_width_t test failed"); static_assert(is_same<set_width_t<std::int16_t, 96>, SG14_INT128>::value, "sg14::set_width_t test failed"); static_assert(is_same<set_width_t<std::uint32_t, 104>, SG14_UINT128>::value, "sg14::set_width_t test failed"); static_assert(is_same<set_width_t<std::int32_t, 112>, SG14_INT128>::value, "sg14::set_width_t test failed"); static_assert(is_same<set_width_t<std::uint64_t, 120>, SG14_UINT128>::value, "sg14::set_width_t test failed"); static_assert(is_same<set_width_t<std::int64_t, 128>, SG14_INT128>::value, "sg14::set_width_t test failed"); #endif static_assert(is_same<set_width_t<double, 8>, float>::value, "sg14::set_width_t test failed"); static_assert(is_same<set_width_t<double, 16>, float>::value, "sg14::set_width_t test failed"); static_assert(is_same<set_width_t<double, 24>, float>::value, "sg14::set_width_t test failed"); static_assert(is_same<set_width_t<float, 32>, float>::value, "sg14::set_width_t test failed"); static_assert(is_same<set_width_t<double, 40>, double>::value, "sg14::set_width_t test failed"); static_assert(is_same<set_width_t<float, 48>, double>::value, "sg14::set_width_t test failed"); static_assert(is_same<set_width_t<float, 56>, double>::value, "sg14::set_width_t test failed"); static_assert(is_same<set_width_t<double, 64>, double>::value, "sg14::set_width_t test failed"); #if !defined(_MSC_VER) static_assert(is_same<set_width_t<long double, 72>, long double>::value, "sg14::set_width_t test failed"); static_assert(is_same<set_width_t<float, 80>, long double>::value, "sg14::set_width_t test failed"); static_assert(is_same<set_width_t<double, 88>, long double>::value, "sg14::set_width_t test failed"); static_assert(is_same<set_width_t<long double, 96>, long double>::value, "sg14::set_width_t test failed"); static_assert(is_same<set_width_t<float, 104>, long double>::value, "sg14::set_width_t test failed"); static_assert(is_same<set_width_t<double, 112>, long double>::value, "sg14::set_width_t test failed"); static_assert(is_same<set_width_t<long double, 120>, long double>::value, "sg14::set_width_t test failed"); static_assert(is_same<set_width_t<float, 128>, long double>::value, "sg14::set_width_t test failed"); #endif //////////////////////////////////////////////////////////////////////////////// // lots more width / set_width template<typename T, int NumBits> struct test_built_in_set_width; template<typename T> struct test_built_in_set_width<T, 0> { }; template<typename T, int NumBits> struct test_built_in_set_width : test_built_in_set_width<T, NumBits-1> { // get alias to result using result_type = set_width_t<T, NumBits>; static_assert(width<result_type>::value >= NumBits, "result of set_width must be at least the desired width in bits"); static_assert(std::numeric_limits<result_type>::is_specialized, "numeric_limits<result_type> is not specialized"); static_assert(std::numeric_limits<T>::is_signed==std::numeric_limits<result_type>::is_signed, "incorrect signage in result of set_width_t (according to numeric_limits)"); static_assert(is_same<typename make_signed<result_type>::type, set_width_t<typename make_signed<T>::type, NumBits>>::value, "incorrect signage in result of set_width_t"); static_assert(is_same<typename make_unsigned<result_type>::type, set_width_t<typename make_unsigned<T>::type, NumBits>>::value, "incorrect signage in result of set_width_t"); }; template<typename T> struct test_built_in_width { static_assert(width<T>::value==sizeof(T)*CHAR_BIT, "incorrect assumption about width of built-in integral type, T"); }; template<typename T> struct test_built_in : test_built_in_width<T>, #if defined(SG14_INT128_ENABLED) test_built_in_set_width<T, 128> #else test_built_in_set_width<T, 64> #endif { static_assert(std::numeric_limits<T>::is_specialized, "numeric_limits<T> is not specialized"); }; template struct test_built_in<char>; template struct test_built_in<unsigned char>; template struct test_built_in<signed char>; template struct test_built_in<unsigned short>; template struct test_built_in<signed short>; template struct test_built_in<unsigned>; template struct test_built_in<signed>; template struct test_built_in<unsigned long>; template struct test_built_in<signed long>; template struct test_built_in<unsigned long long>; template struct test_built_in<signed long long>; #if defined(SG14_INT128_ENABLED) template struct test_built_in<SG14_UINT128>; template struct test_built_in<SG14_INT128>; #endif
46.333333
131
0.712005
danitzarqp106
ba0fd13a575d76dea574f1dab4f55ebc2ee0478d
1,879
cpp
C++
vnext/Shared/Logging.cpp
Thristhart/react-native-windows
0fed997227c8702c089e64f3276bcab073e80c0c
[ "MIT" ]
null
null
null
vnext/Shared/Logging.cpp
Thristhart/react-native-windows
0fed997227c8702c089e64f3276bcab073e80c0c
[ "MIT" ]
null
null
null
vnext/Shared/Logging.cpp
Thristhart/react-native-windows
0fed997227c8702c089e64f3276bcab073e80c0c
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "pch.h" #include "Logging.h" #include "../Chakra/ChakraPlatform.h" #include <chrono> #if !defined(OSS_RN) #include <cxxreact/Platform.h> #endif #if !defined(NOJSC) #include <jschelpers/Value.h> #endif namespace facebook { namespace react { namespace { NativeLoggingHook g_nativeLogHook; void LogHook(RCTLogLevel logLevel, const char* message) { g_nativeLogHook(logLevel, message); } static double nativePerformanceNow() { return std::chrono::duration<double, std::milli>( std::chrono::steady_clock::now().time_since_epoch()).count(); } #if !defined(OSS_RN) void logMarker(const ReactMarker::ReactMarkerId /*id*/, const char* /*tag*/) { } #endif #if !defined(NOJSC) JSValueRef nativePerformanceNowJSC( JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef *exception) { // TODO return Value::makeNumber(ctx, 0); } JSValueRef nativeLoggingHookJSC( JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef *exception) { // TODO return Value::makeUndefined(ctx); } #endif // !defined(NOJSC) } // end anonymous namespace void InitializeLogging(NativeLoggingHook&& hook) { g_nativeLogHook = std::move(hook); JSNativeHooks::loggingHook = LogHook; JSNativeHooks::nowHook = nativePerformanceNow; #if !defined(NOJSC) JSCNativeHooks::loggingHook = nativeLoggingHookJSC; JSCNativeHooks::nowHook = nativePerformanceNowJSC; // JSCNativeHooks::installPerfHooks = addNativePerfLoggingHooksJSC; #endif #if !defined(OSS_RN) ReactMarker::logTaggedMarker = logMarker; #endif } }}
22.914634
79
0.70942
Thristhart
ba11641eb569cee126f8af43f5ad1c3a79db3611
2,003
hpp
C++
lib/src/Delphi/Syntax/DelphiCompilationUnitSyntax.hpp
henrikfroehling/polyglot
955fb37c2f54ebbaf933c16bf9e0e4bcca8a4142
[ "MIT" ]
null
null
null
lib/src/Delphi/Syntax/DelphiCompilationUnitSyntax.hpp
henrikfroehling/polyglot
955fb37c2f54ebbaf933c16bf9e0e4bcca8a4142
[ "MIT" ]
50
2021-06-30T20:01:50.000Z
2021-11-28T16:21:26.000Z
lib/src/Delphi/Syntax/DelphiCompilationUnitSyntax.hpp
henrikfroehling/polyglot
955fb37c2f54ebbaf933c16bf9e0e4bcca8a4142
[ "MIT" ]
null
null
null
#ifndef INTERLINCK_DELPHI_SYNTAX_DELPHICOMPILATIONUNITSYNTAX_H #define INTERLINCK_DELPHI_SYNTAX_DELPHICOMPILATIONUNITSYNTAX_H #include "interlinck/Core/Syntax/SyntaxKinds.hpp" #include "interlinck/Core/Types.hpp" #include "Core/Basic/Macros.hpp" #include "Delphi/Syntax/DelphiSyntaxNode.hpp" namespace interlinck::Core::Support { class SyntaxFactory; } // end namespace interlinck::Core::Support namespace interlinck::Core::Syntax { class ISyntaxToken; } // end namespace interlinck::Core::Syntax namespace interlinck::Delphi::Syntax { class DelphiCompilationUnitSyntax : public DelphiSyntaxNode { public: explicit DelphiCompilationUnitSyntax(Core::Syntax::SyntaxKind syntaxKind, const Core::Syntax::ISyntaxToken* EOFToken) noexcept; ~DelphiCompilationUnitSyntax() noexcept override = default; inline virtual bool isUnitModule() const noexcept { return false; } inline virtual bool isPackageModule() const noexcept { return false; } inline virtual bool isProgramModule() const noexcept { return false; } inline const Core::Syntax::ISyntaxToken* EOFToken() const noexcept { return _EOFToken; } inline Core::Syntax::SyntaxVariant first() const noexcept override { return Core::Syntax::SyntaxVariant::empty(); } inline Core::Syntax::SyntaxVariant last() const noexcept override { return Core::Syntax::SyntaxVariant::asToken(_EOFToken); } inline il_string typeName() const noexcept override { CREATE_TYPENAME(DelphiCompilationUnitSyntax) } static const DelphiCompilationUnitSyntax* create(Core::Support::SyntaxFactory& syntaxFactory, const Core::Syntax::SyntaxKind syntaxKind, const Core::Syntax::ISyntaxToken* EOFToken) noexcept; protected: const Core::Syntax::ISyntaxToken* _EOFToken; }; } // end namespace interlinck::Delphi::Syntax #endif // INTERLINCK_DELPHI_SYNTAX_DELPHICOMPILATIONUNITSYNTAX_H
37.792453
129
0.731902
henrikfroehling
ba138cc0cd52f2ab06e57c59c26c9671f93abf6e
1,760
hpp
C++
srcs/common/syncsamplebox.hpp
Reflectioner/heif
bdac2fc9c66d8c1e8994eaf81f1a5db116b863ab
[ "BSD-3-Clause" ]
null
null
null
srcs/common/syncsamplebox.hpp
Reflectioner/heif
bdac2fc9c66d8c1e8994eaf81f1a5db116b863ab
[ "BSD-3-Clause" ]
null
null
null
srcs/common/syncsamplebox.hpp
Reflectioner/heif
bdac2fc9c66d8c1e8994eaf81f1a5db116b863ab
[ "BSD-3-Clause" ]
null
null
null
/* This file is part of Nokia HEIF library * * Copyright (c) 2015-2020 Nokia Corporation and/or its subsidiary(-ies). All rights reserved. * * Contact: heif@nokia.com * * This software, including documentation, is protected by copyright controlled by Nokia Corporation and/ or its * subsidiaries. All rights are reserved. * * Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior * written consent of Nokia. */ #ifndef SYNCSAMPLEBOX_HPP #define SYNCSAMPLEBOX_HPP #include "customallocator.hpp" #include "fullbox.hpp" /** @brief SyncSampleBox class. Extends from FullBox. * @details 'stss' box contains Sync sample entries as defined in the ISOBMFF standard. */ class SyncSampleBox : public FullBox { public: SyncSampleBox(); ~SyncSampleBox() override = default; /** @brief Add a sample as a sync sample. * @param [in] sampleNumber 1-based sample number in the track to be added as a sync sample. */ void addSample(std::uint32_t sampleNumber); const Vector<std::uint32_t>& getSyncSampleIds() const; void setSampleCountMaxSafety(int64_t sampleCountMax); /** @brief Creates the bitstream that represents the box in the ISOBMFF file * @param [out] bitstr Bitstream that contains the box data. */ void writeBox(ISOBMFF::BitStream& bitstr) const override; /** @brief Parses a SyncSampleBox bitstream and fills in the necessary member variables * @param [in] bitstr Bitstream that contains the box data */ void parseBox(ISOBMFF::BitStream& bitstr) override; private: Vector<std::uint32_t> mSampleNumber; ///< Vector of sync sample Ids int64_t mSampleCountMax; }; #endif /* end of include guard: SYNCSAMPLEBOX_HPP */
34.509804
115
0.731818
Reflectioner
ba150ce15d40f32b9d8f1d879118afbb252cffe4
1,218
cpp
C++
windows/RNSVG/LinearGradientViewManager.cpp
kathigeiger42/react-native-svg
a652d0eca8a97821c56c02550ecb89d06c40d2c6
[ "MIT" ]
null
null
null
windows/RNSVG/LinearGradientViewManager.cpp
kathigeiger42/react-native-svg
a652d0eca8a97821c56c02550ecb89d06c40d2c6
[ "MIT" ]
null
null
null
windows/RNSVG/LinearGradientViewManager.cpp
kathigeiger42/react-native-svg
a652d0eca8a97821c56c02550ecb89d06c40d2c6
[ "MIT" ]
null
null
null
#include "pch.h" #include "LinearGradientViewManager.h" #include "LinearGradientViewManager.g.cpp" using namespace winrt; using namespace Microsoft::ReactNative; namespace winrt::RNSVG::implementation { LinearGradientViewManager::LinearGradientViewManager() { m_class = RNSVG::SVGClass::RNSVGLinearGradient; m_name = L"RNSVGLinearGradient"; } IMapView<hstring, ViewManagerPropertyType> LinearGradientViewManager::NativeProps() { auto const& parentProps{__super::NativeProps()}; auto const &nativeProps{winrt::single_threaded_map<hstring, ViewManagerPropertyType>()}; for (auto const &prop : parentProps) { nativeProps.Insert(prop.Key(), prop.Value()); } nativeProps.Insert(L"x1", ViewManagerPropertyType::String); nativeProps.Insert(L"y1", ViewManagerPropertyType::String); nativeProps.Insert(L"x2", ViewManagerPropertyType::String); nativeProps.Insert(L"y2", ViewManagerPropertyType::String); nativeProps.Insert(L"gradient", ViewManagerPropertyType::Array); nativeProps.Insert(L"gradientUnits", ViewManagerPropertyType::Number); nativeProps.Insert(L"gradientTransform", ViewManagerPropertyType::Array); return nativeProps.GetView(); } } // namespace winrt::RNSVG::implementation
36.909091
90
0.785714
kathigeiger42
ba16aed512c12bf834dbb6e41ef8351c6efa73e6
9,649
cpp
C++
src/gluon/widgets/widget.cpp
cmourglia/gluon-old
9c9a55e86cd8878c0e90917882965c87c84969eb
[ "MIT" ]
null
null
null
src/gluon/widgets/widget.cpp
cmourglia/gluon-old
9c9a55e86cd8878c0e90917882965c87c84969eb
[ "MIT" ]
null
null
null
src/gluon/widgets/widget.cpp
cmourglia/gluon-old
9c9a55e86cd8878c0e90917882965c87c84969eb
[ "MIT" ]
2
2022-02-21T19:09:02.000Z
2022-02-21T19:09:51.000Z
#include "gluon/widgets/widget.h" #include <beard/containers/hash_map.h> #include <beard/misc/hash.h> #include <filesystem> #include <loguru.hpp> #include "gluon/widgets/hashes.h" namespace utils { glm::vec4 ExtractColor(const beard::array<Token>& tokens) { glm::vec4 color = {}; if (!tokens.is_empty()) { Token first_token = tokens.first(); switch (first_token.token_type) { case TokenType::kString: { ASSERT(tokens.element_count() == 1, "A Color as a string can only be defined by one token"); first_token.text.erase( std::remove_if(first_token.text.begin(), first_token.text.end(), [](const char c) { return c == '"'; }), first_token.text.end()); color = color::FromString(first_token.text); } break; case TokenType::kIdentifier: { static constexpr auto kRgbHash = beard::crc32::hash("rgb"); static constexpr auto kRgbaHash = beard::crc32::hash("rgba"); static constexpr auto kHslHash = beard::crc32::hash("hsl"); static constexpr auto kHslaHash = beard::crc32::hash("hsla"); const auto hash = beard::crc32::hash(first_token.text); beard::array<f32> values; for (const auto& t : tokens) { if (t.token_type == TokenType::kNumber) { values.add(t.number); } } switch (hash) { case kRgbHash: { if (values.element_count() == 3) { color = color::FromRGBA((i32)values[0], (i32)values[1], (i32)values[2]); } else { LOG_F(ERROR, "Line %d: Malformed rgb() call, should be " "rgb(red, green, blue)", first_token.line); } } break; case kRgbaHash: { if (values.element_count() == 4) { color = color::FromRGBA((i32)values[0], (i32)values[1], (i32)values[2], values[3]); } else { LOG_F(ERROR, "Line %d: Malformed rgba() call, should be " "rgba(red, green, blue, alpha)", first_token.line); } } break; case kHslHash: { if (values.element_count() == 3) { color = color::FromHSLA((i32)values[0], (i32)values[1], (i32)values[2]); } else { LOG_F(ERROR, "Line %d: Malformed hsl() call, should be " "hsl(hue, saturation, lightness)", first_token.line); } } break; case kHslaHash: { if (values.element_count() == 4) { color = color::FromHSLA((i32)values[0], (i32)values[1], (i32)values[2], values[3]); } else { LOG_F(ERROR, "Line %d: Malformed hsla() call, should be " "hsla(hue, saturation, lightness, alpha", first_token.line); } } break; default: { if (first_token.text.compare("Color") == 0) { ASSERT(tokens.element_count() == 3 && tokens[2].token_type == TokenType::kIdentifier, "We are looking for `Color.ColorName`"); if (auto it = color::kColorsByName.find(tokens[2].text); it != color::kColorsByName.end()) { color = it->second; } else { LOG_F(ERROR, "ling %d: Color '%s' is not a valid " "Color Name. See " "https://www.w3schools.com/colors/" "colors_names.asp for a complete list.", first_token.line, tokens[2].text.c_str()); } } else { LOG_F(ERROR, "Line %d: Could not parse Color given '%s' " "value", first_token.line, first_token.text.c_str()); } } break; } } } } return color; } } // namespace utils beard::array<Widget*> Widget::s_widget_map = {}; extern beard::string_hash_map<WidgetFactory*> s_widget_factories; Widget::~Widget() { s_widget_map.remove( std::find(s_widget_map.begin(), s_widget_map.end(), this)); for (auto&& c : children) { delete c; } children.clear(); } void Widget::deserialize(parser::Node::Ptr node) { s_widget_map.add(this); for (auto c : node->children) { if (c->node_type == parser::NodeType::kStructure) { auto child = (*s_widget_factories[c->name])(); children.add(child); child->parent = this; child->deserialize(c); } else if (c->node_type == parser::NodeType::kProperty) { ParseProperty(c); } } } void Widget::BuildRenderInfos(beard::array<RectangleInfo>* result) { BuildRenderInfosInternal(result); for (auto c : children) { c->BuildRenderInfos(result); } } void Widget::Evaluate() { for (auto&& w : s_widget_map) { w->PreEvaluate(); } for (auto&& w : s_widget_map) { w->EvaluateInternal(); } for (auto&& w : s_widget_map) { w->PostEvaluate(); } } void Widget::EvaluateInternal() { if (is_dirty) { for (auto d : dependencies) { d->EvaluateInternal(); } for (auto&& eval : evaluators) { *eval.first = eval.second.Evaluate(); } is_dirty = false; } } void Widget::touch() { is_dirty = true; for (auto d : dependees) { d->touch(); } } bool Widget::WindowResized(i32 new_width, i32 new_height) { bool needUpdate = false; for (auto c : children) { needUpdate |= c->WindowResized(new_width, new_height); } return needUpdate; } void Widget::ParseProperty(parser::Node::Ptr node) { const auto node_hash = beard::crc32::hash(node->name); switch (node_hash) { case static_cast<u32>(NodeHash::kId): { ASSERT(node->children.element_count() == 1, "ID: <ID>"); id = node->children[0]->name; } break; case static_cast<u32>(NodeHash::kX): case static_cast<u32>(NodeHash::kY): case static_cast<u32>(NodeHash::kWidth): case static_cast<u32>(NodeHash::kHeight): { auto infos = node->children[0]; geometry_expressions[node_hash] = infos->associated_tokens; for (i32 i = 0; i < infos->associated_tokens.element_count() - 1; ++i) { if (infos->associated_tokens[i].token_type == TokenType::kIdentifier && infos->associated_tokens[i + 1].token_type == TokenType::kDot) { dependency_ids.add(infos->associated_tokens[i].text); } } } break; case static_cast<u32>(NodeHash::kAnchors): { LOG_F(WARNING, "Anchors not handled yet"); } break; case static_cast<u32>(NodeHash::kPadding): { LOG_F(WARNING, "Padding not handled yet"); } break; case static_cast<u32>(NodeHash::kMargins): { LOG_F(WARNING, "Margins not handled yet"); } break; default: { ParserPropertyInternal(node, node_hash); } break; } } Widget* GetWidgetById(Widget* root_widget, const std::string& name) { if (root_widget->id == name) { return root_widget; } for (auto child : root_widget->children) { if (auto Node = GetWidgetById(child, name); Node != nullptr) { return Node; } } return nullptr; } void BuildDependencyGraph(Widget* root_widget, Widget* current_widget) { for (auto id : current_widget->dependency_ids) { Widget* dep = id == "Parent" ? current_widget->parent : GetWidgetById(root_widget, id); if (dep != nullptr) { current_widget->dependencies.add(dep); dep->dependees.add(current_widget); } } for (auto c : current_widget->children) { BuildDependencyGraph(root_widget, c); } } void BuildExpressionEvaluators(Widget* root_widget, Widget* current_widget) { auto get_hash_index = [](u32 hash) { switch (hash) { case static_cast<u32>(NodeHash::kX): return 0; case static_cast<u32>(NodeHash::kY): return 1; case static_cast<u32>(NodeHash::kWidth): return 2; case static_cast<u32>(NodeHash::kHeight): return 3; default: ASSERT_UNREACHABLE(); return -1; } }; auto get_property_ptr = [&current_widget](u32 hash) -> f32* { switch (hash) { case static_cast<u32>(NodeHash::kX): return &current_widget->pos.x; case static_cast<u32>(NodeHash::kY): return &current_widget->pos.y; case static_cast<u32>(NodeHash::kWidth): return &current_widget->size.x; case static_cast<u32>(NodeHash::kHeight): return &current_widget->size.y; default: ASSERT_UNREACHABLE(); return nullptr; } }; beard::hash_set<u32> remaining_attributes = { static_cast<u32>(NodeHash::kX), static_cast<u32>(NodeHash::kY), static_cast<u32>(NodeHash::kWidth), static_cast<u32>(NodeHash::kHeight), }; for (auto expr : current_widget->geometry_expressions) { remaining_attributes.remove((u32)expr.first); auto expression = shunting_yard::Expression::Build(expr.second, root_widget, current_widget); current_widget->evaluators.add( std::make_pair(get_property_ptr(expr.first), expression)); } for (auto c : current_widget->children) { BuildExpressionEvaluators(root_widget, c); } }
28.717262
80
0.555809
cmourglia
ba1e0761241ad122b7c59b6720fab5b18b557639
4,714
hpp
C++
include/callisto/framework/templates/handlers/shared_handler.hpp
Anton-Vasyaev/callisto.framework
4013fcfdae4adbee4c3b368fd3a43468dc287918
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
include/callisto/framework/templates/handlers/shared_handler.hpp
Anton-Vasyaev/callisto.framework
4013fcfdae4adbee4c3b368fd3a43468dc287918
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
include/callisto/framework/templates/handlers/shared_handler.hpp
Anton-Vasyaev/callisto.framework
4013fcfdae4adbee4c3b368fd3a43468dc287918
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
#ifndef SHARED_SCOPE_HANDLER_HPP #define SHARED_SCOPE_HANDLER_HPP // std #include <utility> #include <mutex> // project #include "default_disposer.hpp" namespace callisto::framework { template< typename _data_type, typename _disposer_type=default_disposer<_data_type> > class shared_handler { private: using data_type = _data_type; using disposer_type = _disposer_type; data_type data; disposer_type disposer; size_t* ref_counter = nullptr; std::mutex* mutex = nullptr; bool has_handler = false; #pragma region private_methods inline void destroy() { if (!(this->has_handler)) return; size_t current_counter = 0; { std::unique_lock<std::mutex> locker(*(this->mutex)); (*(this->ref_counter))--; if (*(this->ref_counter) == 0) { disposer(this->data); } current_counter = *(this->ref_counter); } if (current_counter == 0) { if (this->mutex != nullptr) { delete this->mutex; this->mutex = nullptr; } if (this->ref_counter != nullptr) { delete this->ref_counter; this->ref_counter = nullptr; } } this->has_handler = false; } inline void copy_from( shared_handler& other_handler ) { std::unique_lock(*(other_handler.mutex)); this->destroy(); this->data = other_handler.data; this->ref_counter = other_handler.ref_counter; this->mutex = other_handler.mutex; this->has_handler = other_handler.has_handler; (*(this->ref_counter))++; } inline void move_from( shared_handler&& other_handler ) { this->destroy(); this->data = other_handler.data; this->ref_counter = other_handler.ref_counter; this->mutex = other_handler.mutex; this->has_handler = other_handler.has_handler; other_handler.ref_counter = nullptr; other_handler.mutex = nullptr; other_handler.has_handler = false; } inline void create_new( data_type data ) { this->destroy(); try { this->ref_counter = new size_t; this->mutex = new std::mutex(); this->data = data; } catch (...) { if (this->ref_counter != nullptr) delete this->ref_counter; if (this->mutex != nullptr) delete this->mutex; throw; } (*(this->ref_counter)) = 1; this->data = data; this->has_handler = true; } #pragma endregion public: #pragma region construct_and_destruct shared_handler() { }; shared_handler( data_type data ) { this->create_new(data); } shared_handler( shared_handler& other_handler ) { this->copy_from(other_handler); } shared_handler( shared_handler&& other_handler ) { this->move_from(other_handler); } ~shared_handler() { this->destroy(); } #pragma endregion #pragma region methods void reset(data_type data) { this->create_new(data); } #pragma endregion #pragma region operators shared_handler& operator=(shared_handler& other_handler) { this->copy_from(other_handler); return *this; } shared_handler& operator=(shared_handler&& other_handler) { this->move_from(std::move(other_handler)); return *this; } #pragma endregion #pragma region getters_and_setters data_type& get_data() { return this->data; } const data_type& get_data() const { return this->data; } size_t count() const { return *(this->ref_counter); } bool has_handler_status() const { return this->has_handler; } #pragma endregion }; } #endif
21.723502
75
0.485363
Anton-Vasyaev
ba1e9698d1d5c042d7347687b25253f501dfc7e5
6,171
cpp
C++
Backends/System/Windows/Sources/kinc/backend/video.cpp
IbrahimHindawi/Kinc
4dd1b313d0b6ebfeb5b21df75563d3e6bf0b9b8b
[ "Zlib" ]
null
null
null
Backends/System/Windows/Sources/kinc/backend/video.cpp
IbrahimHindawi/Kinc
4dd1b313d0b6ebfeb5b21df75563d3e6bf0b9b8b
[ "Zlib" ]
null
null
null
Backends/System/Windows/Sources/kinc/backend/video.cpp
IbrahimHindawi/Kinc
4dd1b313d0b6ebfeb5b21df75563d3e6bf0b9b8b
[ "Zlib" ]
null
null
null
#include "pch.h" #include <kinc/video.h> #include <streams.h> namespace { IGraphBuilder *graphBuilder; IMediaControl *mediaControl; IMediaPosition *mediaPosition; IMediaEvent *mediaEvent; struct __declspec(uuid("{71771540-2017-11cf-ae24-0020afd79767}")) CLSID_TextureRenderer; } class CTextureRenderer : public CBaseVideoRenderer { public: CTextureRenderer(LPUNKNOWN pUnk, HRESULT *phr); ~CTextureRenderer(); public: HRESULT CheckMediaType(const CMediaType *pmt); // Format acceptable? HRESULT SetMediaType(const CMediaType *pmt); // Video format notification HRESULT DoRenderSample(IMediaSample *pMediaSample); // New video sample // BOOL m_bUseDynamicTextures; // LONG m_lVidWidth; // Video width // LONG m_lVidHeight; // Video Height // LONG m_lVidPitch; // Video Pitch kinc_g4_texture_t image; int width; int height; uint8_t *pixels; }; CTextureRenderer::CTextureRenderer(LPUNKNOWN pUnk, HRESULT *phr) : CBaseVideoRenderer(__uuidof(CLSID_TextureRenderer), TEXT("Texture Renderer"), pUnk, phr) { // Store and AddRef the texture for our use. ASSERT(phr); if (phr) *phr = S_OK; } CTextureRenderer::~CTextureRenderer() { // Do nothing } HRESULT CTextureRenderer::CheckMediaType(const CMediaType *pmt) { HRESULT hr = E_FAIL; VIDEOINFO *pvi = 0; CheckPointer(pmt, E_POINTER); // Reject the connection if this is not a video type if (*pmt->FormatType() != FORMAT_VideoInfo) { return E_INVALIDARG; } // Only accept RGB24 video pvi = (VIDEOINFO *)pmt->Format(); if (IsEqualGUID(*pmt->Type(), MEDIATYPE_Video) && IsEqualGUID(*pmt->Subtype(), MEDIASUBTYPE_RGB24)) { hr = S_OK; } return hr; } HRESULT CTextureRenderer::SetMediaType(const CMediaType *pmt) { VIDEOINFO *info = (VIDEOINFO *)pmt->Format(); width = info->bmiHeader.biWidth; height = abs(info->bmiHeader.biHeight); kinc_g4_texture_init(&image, width, height, KINC_IMAGE_FORMAT_RGBA32); pixels = (uint8_t *)malloc(width * height * 3); for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { pixels[y * width * 3 + x * 3 + 0] = 0; pixels[y * width * 3 + x * 3 + 1] = 0; pixels[y * width * 3 + x * 3 + 2] = 0; } } return S_OK; } HRESULT CTextureRenderer::DoRenderSample(IMediaSample *sample) { BYTE *videoPixels; sample->GetPointer(&videoPixels); int videoPitch = (width * 3 + 3) & ~(3); for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { pixels[y * width * 3 + x * 3 + 0] = videoPixels[(height - y - 1) * videoPitch + x * 3 + 2]; pixels[y * width * 3 + x * 3 + 1] = videoPixels[(height - y - 1) * videoPitch + x * 3 + 1]; pixels[y * width * 3 + x * 3 + 2] = videoPixels[(height - y - 1) * videoPitch + x * 3 + 0]; } } return S_OK; } void kinc_video_init(kinc_video_t *video, const char *filename) { video->impl.duration = 1000 * 10; video->impl.position = 0; video->impl.finished = false; video->impl.paused = false; // image = new Graphics4::Texture(100, 100, Graphics4::Image::RGBA32, false); HRESULT hr = S_OK; IBaseFilter *pFSrc; // Source Filter IPin *pFSrcPinOut; // Source Filter Output Pin hr = CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC, __uuidof(IGraphBuilder), (void **)&graphBuilder); video->impl.renderer = new CTextureRenderer(NULL, &hr); hr = graphBuilder->AddFilter((CTextureRenderer *)video->impl.renderer, L"TEXTURERENDERER"); wchar_t wideFilename[2048]; mbstowcs(wideFilename, filename, 2048 - 1); hr = graphBuilder->AddSourceFilter(wideFilename, L"SOURCE", &pFSrc); hr = pFSrc->FindPin(L"Output", &pFSrcPinOut); hr = graphBuilder->Render(pFSrcPinOut); graphBuilder->QueryInterface(&mediaControl); graphBuilder->QueryInterface(&mediaPosition); graphBuilder->QueryInterface(&mediaEvent); mediaPosition->get_Duration(&video->impl.duration); video->impl.position = 0; } void kinc_video_destroy(kinc_video_t *video) {} kinc_g4_texture_t *kinc_video_current_image(kinc_video_t *video) { CTextureRenderer *renderer = (CTextureRenderer *)video->impl.renderer; uint8_t *pixels = kinc_g4_texture_lock(&renderer->image); int stride = kinc_g4_texture_stride(&renderer->image); for (int y = 0; y < renderer->height; ++y) { for (int x = 0; x < renderer->width; ++x) { pixels[y * stride + x * 4 + 0] = renderer->pixels[y * renderer->width * 3 + x * 3 + 0]; pixels[y * stride + x * 4 + 1] = renderer->pixels[y * renderer->width * 3 + x * 3 + 1]; pixels[y * stride + x * 4 + 2] = renderer->pixels[y * renderer->width * 3 + x * 3 + 2]; pixels[y * stride + x * 4 + 3] = 255; } } kinc_g4_texture_unlock(&renderer->image); mediaPosition->get_CurrentPosition(&video->impl.position); return &renderer->image; } int kinc_video_width(kinc_video_t *video) { CTextureRenderer *renderer = (CTextureRenderer *)video->impl.renderer; return renderer->width; } int kinc_video_height(kinc_video_t *video) { CTextureRenderer *renderer = (CTextureRenderer *)video->impl.renderer; return renderer->height; } void kinc_video_play(kinc_video_t *video) { mediaControl->Run(); } void kinc_video_pause(kinc_video_t *video) { mediaControl->Pause(); } void kinc_video_stop(kinc_video_t *video) { mediaControl->Stop(); } void kinc_video_update(kinc_video_t *video, double time) { mediaPosition->put_CurrentPosition(time); } double kinc_video_duration(kinc_video_t *video) { return video->impl.duration; } double kinc_video_position(kinc_video_t *video) { return video->impl.position; } bool kinc_video_finished(kinc_video_t *video) { return video->impl.finished; } bool kinc_video_paused(kinc_video_t *video) { return video->impl.paused; } void kinc_internal_video_sound_stream_init(kinc_internal_video_sound_stream_t *stream, int channel_count, int frequency) {} void kinc_internal_video_sound_stream_destroy(kinc_internal_video_sound_stream_t *stream) {} void kinc_internal_video_sound_stream_insert_data(kinc_internal_video_sound_stream_t *stream, float *data, int sample_count) {} float kinc_internal_video_sound_stream_next_sample(kinc_internal_video_sound_stream_t *stream) { return 0.0f; } bool kinc_internal_video_sound_stream_ended(kinc_internal_video_sound_stream_t *stream) { return true; }
30.25
157
0.71674
IbrahimHindawi
ba1e9bcb61d2d3cbb5440645d5278160e0a2e66a
1,895
cpp
C++
tests/Packets/Tag60.cpp
httese/OpenPGP
7dce08dc8b72eeb0dcbf3df56d64606a6b957938
[ "MIT" ]
99
2015-01-06T01:53:26.000Z
2022-01-31T18:18:27.000Z
tests/Packets/Tag60.cpp
httese/OpenPGP
7dce08dc8b72eeb0dcbf3df56d64606a6b957938
[ "MIT" ]
27
2015-03-09T05:46:53.000Z
2020-05-06T02:52:18.000Z
tests/Packets/Tag60.cpp
httese/OpenPGP
7dce08dc8b72eeb0dcbf3df56d64606a6b957938
[ "MIT" ]
42
2015-03-18T03:44:43.000Z
2022-03-31T21:34:06.000Z
#include <gtest/gtest.h> #include "Packets/Tag60.h" static const std::string stream("\x00\x01\x02\x03\x04\x05\x06\x07", 8); static void TAG60_FILL(OpenPGP::Packet::Tag60 & tag60) { tag60.set_stream(stream); } #define TAG60_EQ(tag60) \ EXPECT_EQ((tag60).get_stream(), stream); \ EXPECT_EQ((tag60).valid(true), OpenPGP::Status::SUCCESS); TEST(Tag60, Constructor) { // Default constructor OpenPGP::Packet::Tag60 tag60; EXPECT_EQ(tag60.raw(), ""); EXPECT_NO_THROW(TAG60_FILL(tag60)); // String Constructor { OpenPGP::Packet::Tag60 str(tag60.raw()); TAG60_EQ(str); } // Copy Constructor { OpenPGP::Packet::Tag60 copy(tag60); TAG60_EQ(copy); } // Move Constructor { OpenPGP::Packet::Tag60 move(std::move(tag60)); TAG60_EQ(move); } } TEST(Tag60, Assignment) { OpenPGP::Packet::Tag60 tag60; EXPECT_NO_THROW(TAG60_FILL(tag60)); // Assignment { OpenPGP::Packet::Tag60 copy; copy = tag60; TAG60_EQ(copy); } // Move Assignment { OpenPGP::Packet::Tag60 move; move = std::move(tag60); TAG60_EQ(move); } } TEST(Tag60, read_write) { OpenPGP::Packet::Tag60 tag60(stream); TAG60_EQ(tag60); EXPECT_EQ(tag60.raw(), stream); } TEST(Tag60, show) { OpenPGP::Packet::Tag60 tag60; EXPECT_NO_THROW(TAG60_FILL(tag60)); EXPECT_NO_THROW(tag60.show()); } TEST(Tag60, set_get) { OpenPGP::Packet::Tag60 tag60; EXPECT_NO_THROW(TAG60_FILL(tag60)); TAG60_EQ(tag60); } TEST(Tag60, clone) { OpenPGP::Packet::Tag60 tag60; EXPECT_NO_THROW(TAG60_FILL(tag60)); OpenPGP::Packet::Tag::Ptr clone = tag60.clone(); EXPECT_NE(&tag60, clone.get()); TAG60_EQ(*std::static_pointer_cast<OpenPGP::Packet::Tag60>(clone)); }
22.034884
71
0.604749
httese
ba22a032f9a8fcb7fc224b77a9f54ad8bd431b89
66
cpp
C++
unit_test/serial/Test_Serial_Batched_VectorView.cpp
dialecticDolt/kokkos-kernels
00189c0be23a70979aeaa162f0abd4c0e4d1c479
[ "BSD-3-Clause" ]
156
2017-03-01T23:38:10.000Z
2022-03-27T21:28:03.000Z
unit_test/serial/Test_Serial_Batched_VectorView.cpp
dialecticDolt/kokkos-kernels
00189c0be23a70979aeaa162f0abd4c0e4d1c479
[ "BSD-3-Clause" ]
1,257
2017-03-03T15:25:16.000Z
2022-03-31T19:46:09.000Z
unit_test/serial/Test_Serial_Batched_VectorView.cpp
dialecticDolt/kokkos-kernels
00189c0be23a70979aeaa162f0abd4c0e4d1c479
[ "BSD-3-Clause" ]
76
2017-03-01T17:03:59.000Z
2022-03-03T21:04:41.000Z
#include "Test_Serial.hpp" #include "Test_Batched_VectorView.hpp"
22
38
0.818182
dialecticDolt
ba2451fefd4833b4c09790781fdf0cdc73b67599
235
hpp
C++
py-bindings/bindings/app/QuadrotorPlanning.pypp.hpp
SZanlongo/omplapp
c56679337e2a71d266359450afbe63d700c0a666
[ "BSD-3-Clause" ]
null
null
null
py-bindings/bindings/app/QuadrotorPlanning.pypp.hpp
SZanlongo/omplapp
c56679337e2a71d266359450afbe63d700c0a666
[ "BSD-3-Clause" ]
null
null
null
py-bindings/bindings/app/QuadrotorPlanning.pypp.hpp
SZanlongo/omplapp
c56679337e2a71d266359450afbe63d700c0a666
[ "BSD-3-Clause" ]
null
null
null
// This file has been generated by Py++. #ifndef QuadrotorPlanning_hpp__pyplusplus_wrapper #define QuadrotorPlanning_hpp__pyplusplus_wrapper void register_QuadrotorPlanning_class(); #endif//QuadrotorPlanning_hpp__pyplusplus_wrapper
26.111111
49
0.868085
SZanlongo
ba29a95570c4487efb91832c0c46d94504ef3a27
8,578
cpp
C++
isis/src/base/objs/PlaneShape/PlaneShape.cpp
kdl222/ISIS3
aab0e63088046690e6c031881825596c1c2cc380
[ "CC0-1.0" ]
134
2018-01-18T00:16:24.000Z
2022-03-24T03:53:33.000Z
isis/src/base/objs/PlaneShape/PlaneShape.cpp
kdl222/ISIS3
aab0e63088046690e6c031881825596c1c2cc380
[ "CC0-1.0" ]
3,825
2017-12-11T21:27:34.000Z
2022-03-31T21:45:20.000Z
isis/src/base/objs/PlaneShape/PlaneShape.cpp
jlaura/isis3
2c40e08caed09968ea01d5a767a676172ad20080
[ "CC0-1.0" ]
164
2017-11-30T21:15:44.000Z
2022-03-23T10:22:29.000Z
/** This is free and unencumbered software released into the public domain. The authors of ISIS do not claim copyright on the contents of this file. For more details about the LICENSE terms and the AUTHORS, you will find files of those names at the top level of this repository. **/ /* SPDX-License-Identifier: CC0-1.0 */ #include <algorithm> #include <cfloat> #include <string> #include <vector> #include <cmath> #include <iomanip> #include "PlaneShape.h" #include "Distance.h" #include "IException.h" #include "Latitude.h" #include "Longitude.h" #include "NaifStatus.h" #include "ShapeModel.h" #include "SurfacePoint.h" namespace Isis { /** * Initialize the PlaneShape. * * @param pvl Valid ISIS cube label. */ PlaneShape::PlaneShape(Target *target, Pvl &pvl) : ShapeModel (target) { setName("Plane"); // set surface normal // setNormal(0.0, 0.0, 1.0); } /** * Initialize the PlaneShape. * * @param pvl Valid ISIS cube label. */ PlaneShape::PlaneShape(Target *target) : ShapeModel (target) { setName("Plane"); // set normal vector // setNormal(0.0, 0.0, 1.0); } /** * Initialize the PlaneShape. * * @param pvl Valid ISIS cube label. */ PlaneShape::PlaneShape() : ShapeModel () { setName("Plane"); } /** * Destructor */ PlaneShape::~PlaneShape() { } /** Find the intersection point * * @param observerPos: observer (likely a spacecraft) position in Body-Fixed * coordinates. * * @param lookDirection: observer (likely a spacecraft) look vector in Body- * Fixed coordinates. */ bool PlaneShape::intersectSurface (std::vector<double> observerPos, std::vector<double> lookDirection) { NaifStatus::CheckErrors(); SpiceDouble zvec[3]; SpicePlane plane; SpiceInt nxpts; SpiceDouble xpt[3]; // std::vector<double> n = normal(); // zvec[0] = n[0]; // zvec[1] = n[1]; // zvec[2] = n[2]; zvec[0] = 0.0; zvec[1] = 0.0; zvec[2] = 1.0; if (observerPos[2] < 0.0) zvec[2] = -zvec[2]; // NAIF routine to "Make a CSPICE plane from a normal vector and a constant" // see http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/nvc2pl_c.html nvc2pl_c(zvec, 0.0, &plane); SpiceDouble position[3]; SpiceDouble lookvector[3]; position[0] = observerPos[0]; position[1] = observerPos[1]; position[2] = observerPos[2]; lookvector[0] = lookDirection[0]; lookvector[1] = lookDirection[1]; lookvector[2] = lookDirection[2]; // NAIF routine to "find the intersection of a ray and a plane" // see http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/inrypl_c.html inrypl_c(&position, &lookvector, &plane, &nxpts, xpt); if (nxpts != 1 ) { setHasIntersection(false); return false; } setHasIntersection(true); setNormal(0.0,0.0,1.0); surfaceIntersection()->FromNaifArray(xpt); NaifStatus::CheckErrors(); return true; } /** * Indicates that this shape model is not from a DEM. Since this method * returns false for this class, the Camera class will not calculate the * local normal using neighbor points. * * @return bool Indicates that this is not a DEM shape model. */ bool PlaneShape::isDEM() const { return false; } /** * There is no implementation for this method. */ void PlaneShape::calculateSurfaceNormal() { } /** * There is no implementation for this method. */ void PlaneShape::calculateDefaultNormal() { } /** * There is no implementation for this method. */ void PlaneShape::calculateLocalNormal(QVector<double *> cornerNeighborPoints) { } /** * Computes and returns emission angle in degrees given the observer position. * * Emission Angle: The angle between the surface normal vector at the * intersection point and a vector from the intersection point to the * spacecraft. The emission angle varies from 0 degrees when the spacecraft is * viewing the sub-spacecraft point (nadir viewing) to 90 degrees when the * intercept is tangent to the surface of the target body. Thus, higher values * of emission angle indicate more oblique viewing of the target. * * @param sB: Spacecraft position in body-fixed coordinates * * @return Emmision angle in decimal degrees * */ double PlaneShape::emissionAngle(const std::vector<double> & sB) { SpiceDouble pB[3]; // surface intersection in body-fixed coordinates SpiceDouble psB[3]; // vector from spacecraft to surface intersection SpiceDouble upsB[3]; // unit vector from spacecraft to surface intersection SpiceDouble dist; // vector magnitude // Get vector from center of body to surface point pB[0] = surfaceIntersection()->GetX().kilometers(); pB[1] = surfaceIntersection()->GetY().kilometers(); pB[2] = surfaceIntersection()->GetZ().kilometers(); // Get vector from surface intersect point to observer and normalize it vsub_c((ConstSpiceDouble *) &sB[0], pB, psB); unorm_c(psB, upsB, &dist); // temporary normal vector SpiceDouble n[3]; n[0] = 0.0; n[1] = 0.0; n[2] = 1.0; // flip normal if observer is "below" the plane, assuming that the target // body north pole defines the "up" direction if (sB[2] < 0.0) n[2] = -n[2]; // dot product of surface normal and observer-surface intersection vector double angle = vdot_c(n, upsB); if (angle > 1.0) return 0.0; if (angle < -1.0) return 180.0; return acos(angle) * RAD2DEG; } /** * Computes and returns incidence angle in degrees given the sun position. * * Incidence Angle: The incidence angle provides a measure of the lighting * condition at the surface intersection point. The angle between the surface * normal vector at the intersection point and a vector from the intersection * point to the sun. The incidence angle varies from 0 degrees when the * intersection point coincides with the sub-solar point to 90 degrees when * the intersection point is at the terminator (i.e., in the shadowed or dark * portion of the target body). Thus, higher values of incidence angles * indicate the existence of a greater number of surface shadows. * * @param uB: Sun position in body-fixed coordinates * * @return Incidence angle in decimal degrees * */ double PlaneShape::incidenceAngle(const std::vector<double> &uB) { SpiceDouble pB[3]; // surface intersection in body-fixed coordinates SpiceDouble puB[3]; // vector from sun to surface intersection SpiceDouble upuB[3]; // unit vector from sun to surface intersection SpiceDouble dist; // vector magnitude // Get vector from center of body to surface point pB[0] = surfaceIntersection()->GetX().kilometers(); pB[1] = surfaceIntersection()->GetY().kilometers(); pB[2] = surfaceIntersection()->GetZ().kilometers(); // Get vector from surface intersect point to sun and normalize it vsub_c((SpiceDouble *) &uB[0], pB, puB); unorm_c(puB, upuB, &dist); // temporary normal vector SpiceDouble n[3]; n[0] = 0.0; n[1] = 0.0; n[2] = 1.0; // flip normal if sun is "below" the plane, assuming that the target // body north pole defines the "up" direction if (uB[2] < 0.0) n[2] = -n[2]; double angle = vdot_c((SpiceDouble *) &n[0], upuB); if (angle > 1.0) return 0.0; if(angle < -1.0) return 180.0; return acos(angle) * RAD2DEG; } /** * Gets the local radius for the given latitude/longitude coordinate. For the * plane shape model, this is calculated by finding the distance of the * surface intersection point from the plane's origin. * * @return Distance The distance from the center of the body to its surface at * the given lat/lon location. * */ // TODO: what should this do in the case of a ring plane (or any other plane // for that matter)? Distance PlaneShape::localRadius(const Latitude &lat, const Longitude &lon) { SpiceDouble pB[3]; // surface intersection in body-fixed coordinates // Get vector from center of body to surface point pB[0] = surfaceIntersection()->GetX().kilometers(); pB[1] = surfaceIntersection()->GetY().kilometers(); pB[2] = surfaceIntersection()->GetZ().kilometers(); double radius = sqrt(pB[0]*pB[0] + pB[1]*pB[1] + pB[2]*pB[2]); return Distance(radius, Distance::Kilometers); } }
28.688963
81
0.657846
kdl222
ba2f0a853cce49c6556889e00228d415b67e6732
23,964
cpp
C++
Example_CPP/Screen_Capture_Example.cpp
Intro-Ventors/screen_capture_lite
5a39deda85d6f444d9c99c72da711be73ce68055
[ "MIT" ]
null
null
null
Example_CPP/Screen_Capture_Example.cpp
Intro-Ventors/screen_capture_lite
5a39deda85d6f444d9c99c72da711be73ce68055
[ "MIT" ]
null
null
null
Example_CPP/Screen_Capture_Example.cpp
Intro-Ventors/screen_capture_lite
5a39deda85d6f444d9c99c72da711be73ce68055
[ "MIT" ]
null
null
null
#include "ScreenCapture.h" #include "ScreenCapture_C_API.h" #include "internal/SCCommon.h" //DONT USE THIS HEADER IN PRODUCTION CODE!!!! ITS INTERNAL FOR A REASON IT WILL CHANGE!!! ITS HERE FOR TESTS ONLY!!! #include <algorithm> #include <atomic> #include <chrono> #include <climits> #include <iostream> #include <locale> #include <string> #include <thread> #include <vector> // THESE LIBRARIES ARE HERE FOR CONVINIENCE!! They are SLOW and ONLY USED FOR // HOW THE LIBRARY WORKS! #define TJE_IMPLEMENTATION #include "tiny_jpeg.h" #define LODEPNG_COMPILE_PNG #define LODEPNG_COMPILE_DISK #include "lodepng.h" ///////////////////////////////////////////////////////////////////////// void TestCopyContiguous() { constexpr auto VALID(static_cast<unsigned char>(0xFF)); constexpr auto INVALID(static_cast<unsigned char>(0xFE)); constexpr auto PIXEL_DEPTH(sizeof(SL::Screen_Capture::ImageBGRA)); constexpr unsigned WIDTH(256), HEIGHT(256); std::vector<SL::Screen_Capture::ImageBGRA> strided; for (unsigned row(0); row < HEIGHT; ++row) { for (unsigned col(0); col < WIDTH; ++col) { strided.push_back(SL::Screen_Capture::ImageBGRA{VALID, VALID, VALID, VALID}); } } auto bytes = strided.size() * PIXEL_DEPTH; std::vector<unsigned char> contiguous(bytes, static_cast<unsigned char>(0)); auto image = SL::Screen_Capture::Image{{0, 0, WIDTH, HEIGHT}, 0, true, strided.data()}; auto result = SCL_Utility_CopyToContiguous(contiguous.data(), &image); auto distance = std::distance(contiguous.data(), static_cast<unsigned char *>(result)); if (distance != (WIDTH * HEIGHT * PIXEL_DEPTH)) std::abort(); auto const begin(contiguous.begin()), end(contiguous.end()); for (auto current(begin); current != end; ++current) { if (*current != VALID) std::abort(); } } void TestCopyNonContiguous() { constexpr auto VALID(static_cast<unsigned char>(0xFF)); constexpr auto INVALID(static_cast<unsigned char>(0xFE)); constexpr auto PIXEL_DEPTH(sizeof(SL::Screen_Capture::ImageBGRA)); constexpr unsigned WIDTH(256), HEIGHT(256), PADDING(64), STRIDE_IN_BYTES((WIDTH + PADDING) * PIXEL_DEPTH); std::vector<SL::Screen_Capture::ImageBGRA> strided; for (unsigned row(0); row < HEIGHT; ++row) { for (unsigned col(0); col < WIDTH; ++col) { strided.push_back(SL::Screen_Capture::ImageBGRA{VALID, VALID, VALID, VALID}); } for (unsigned pad(0); pad < PADDING; ++pad) { strided.push_back(SL::Screen_Capture::ImageBGRA{INVALID, INVALID, INVALID, INVALID}); } } auto bytes = strided.size() * PIXEL_DEPTH; std::vector<unsigned char> contiguous(bytes, static_cast<unsigned char>(0)); auto image = SL::Screen_Capture::Image{{0, 0, WIDTH, HEIGHT}, STRIDE_IN_BYTES, false, strided.data()}; auto result = SCL_Utility_CopyToContiguous(contiguous.data(), &image); auto distance = std::distance(contiguous.data(), static_cast<unsigned char *>(result)); // Ensures that the pointer incremented by only the amount written. if (distance != (WIDTH * HEIGHT * PIXEL_DEPTH)) std::abort(); auto const begin(contiguous.begin()); auto contiguousEnd(begin), absoluteEnd(contiguous.end()); std::advance(contiguousEnd, WIDTH * HEIGHT * PIXEL_DEPTH); for (auto current(begin); current != contiguousEnd; ++current) { if (*current != VALID) std::abort(); } for (auto current(contiguousEnd); current != absoluteEnd; ++current) { if (*current != 0) std::abort(); } } void ExtractAndConvertToRGBA(const SL::Screen_Capture::Image &img, unsigned char *dst, size_t dst_size) { assert(dst_size >= static_cast<size_t>(SL::Screen_Capture::Width(img) * SL::Screen_Capture::Height(img) * sizeof(SL::Screen_Capture::ImageBGRA))); auto imgsrc = StartSrc(img); auto imgdist = dst; for (auto h = 0; h < Height(img); h++) { auto startimgsrc = imgsrc; for (auto w = 0; w < Width(img); w++) { *imgdist++ = imgsrc->R; *imgdist++ = imgsrc->G; *imgdist++ = imgsrc->B; *imgdist++ = 0; // alpha should be zero imgsrc++; } imgsrc = SL::Screen_Capture::GotoNextRow(img, startimgsrc); } } using namespace std::chrono_literals; std::shared_ptr<SL::Screen_Capture::IScreenCaptureManager> framgrabber; std::atomic<int> realcounter; std::atomic<int> onNewFramecounter; inline std::ostream &operator<<(std::ostream &os, const SL::Screen_Capture::ImageRect &p) { return os << "left=" << p.left << " top=" << p.top << " right=" << p.right << " bottom=" << p.bottom; } inline std::ostream &operator<<(std::ostream &os, const SL::Screen_Capture::Monitor &p) { return os << "Id=" << p.Id << " Index=" << p.Index << " Height=" << p.Height << " Width=" << p.Width << " OffsetX=" << p.OffsetX << " OffsetY=" << p.OffsetY << " Name=" << p.Name; } auto onNewFramestart = std::chrono::high_resolution_clock::now(); void createframegrabber() { realcounter = 0; onNewFramecounter = 0; framgrabber = nullptr; framgrabber = SL::Screen_Capture::CreateCaptureConfiguration([]() { auto mons = SL::Screen_Capture::GetMonitors(); std::cout << "Library is requesting the list of monitors to capture!" << std::endl; for (auto &m : mons) { std::cout << m << std::endl; } return mons; }) ->onFrameChanged([&](const SL::Screen_Capture::Image &img, const SL::Screen_Capture::Monitor &monitor) { // std::cout << "Difference detected! " << img.Bounds << std::endl; // Uncomment the below code to write the image to disk for debugging /* auto r = realcounter.fetch_add(1); auto s = std::to_string(r) + std::string("MONITORDIF_") + std::string(".jpg"); auto size = Width(img) * Height(img) * sizeof(SL::Screen_Capture::ImageBGRA); auto imgbuffer(std::make_unique<unsigned char[]>(size)); ExtractAndConvertToRGBA(img, imgbuffer.get(), size); tje_encode_to_file(s.c_str(), Width(img), Height(img), 4, (const unsigned char*)imgbuffer.get()); */ }) ->onNewFrame([&](const SL::Screen_Capture::Image &img, const SL::Screen_Capture::Monitor &monitor) { // Uncomment the below code to write the image to disk for debugging // auto r = realcounter.fetch_add(1); // auto s = std::to_string(r) + std::string("MONITORNEW_") + std::string(".jpg"); // auto size = Width(img) * Height(img) * sizeof(SL::Screen_Capture::ImageBGRA); // auto imgbuffer(std::make_unique<unsigned char[]>(size)); // ExtractAndConvertToRGBA(img, imgbuffer.get(), size); // tje_encode_to_file(s.c_str(), Width(img), Height(img), 4, (const unsigned char *)imgbuffer.get()); if (std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - onNewFramestart).count() >= 1000) { std::cout << "onNewFrame fps" << onNewFramecounter << std::endl; onNewFramecounter = 0; onNewFramestart = std::chrono::high_resolution_clock::now(); } onNewFramecounter += 1; }) ->onMouseChanged([&](const SL::Screen_Capture::Image *img, const SL::Screen_Capture::MousePoint &mousepoint) { // Uncomment the below code to write the image to disk for debugging /* auto r = realcounter.fetch_add(1); auto s = std::to_string(r) + std::string(" M") + std::string(".png"); if (img) { std::cout << "New mouse coordinates AND NEW Image received." << " x= " << mousepoint.Position.x << " y= " << mousepoint.Position.y << std::endl; lodepng::encode(s, (unsigned char *)StartSrc(*img), Width(*img), Height(*img)); } else { std::cout << "New mouse coordinates received." << " x= " << mousepoint.Position.x << " y= " << mousepoint.Position.y << " The mouse image is still the same as the last " << std::endl; } */ }) ->start_capturing(); framgrabber->setFrameChangeInterval(std::chrono::milliseconds(100)); framgrabber->setMouseChangeInterval(std::chrono::milliseconds(100)); } void createpartialframegrabber() { realcounter = 0; onNewFramecounter = 0; framgrabber = nullptr; framgrabber = SL::Screen_Capture::CreateCaptureConfiguration([]() { auto mons = SL::Screen_Capture::GetMonitors(); auto newmons = std::vector<SL::Screen_Capture::Monitor>(); std::cout << "Library is requesting the list of monitors to capture!" << std::endl; for (auto &m : mons) { if (SL::Screen_Capture::Height(m) >= 512 * 2 && SL::Screen_Capture::Width(m) >= 512 * 2) { SL::Screen_Capture::Height(m, 512); SL::Screen_Capture::Width(m, 512); std::cout << m << std::endl; newmons.push_back(m); } } return newmons; }) ->onFrameChanged([&](const SL::Screen_Capture::Image &img, const SL::Screen_Capture::Monitor &monitor) { // Uncomment the below code to write the image to disk for debugging // std::cout << "Difference detected! " << img.Bounds << std::endl; /* auto r = realcounter.fetch_add(1); auto s = std::to_string(r) + std::string("MONITORDIF_") + std::string(".jpg"); auto size = Width(img) * Height(img) * sizeof(SL::Screen_Capture::ImageBGRA); auto imgbuffer(std::make_unique<unsigned char[]>(size)); ExtractAndConvertToRGBA(img, imgbuffer.get(), size); tje_encode_to_file(s.c_str(), Width(img), Height(img), 4, (const unsigned char*)imgbuffer.get()); */ }) ->onNewFrame([&](const SL::Screen_Capture::Image &img, const SL::Screen_Capture::Monitor &monitor) { // Uncomment the below code to write the image to disk for debugging /* auto r = realcounter.fetch_add(1); auto s = std::to_string(r) + std::string("MONITORNEW_") + std::string(".jpg"); auto size = Width(img) * Height(img) * sizeof(SL::Screen_Capture::ImageBGRA); assert(Height(img) == 512); assert(Width(img) == 512); auto imgbuffer(std::make_unique<unsigned char[]>(size)); ExtractAndConvertToRGBA(img, imgbuffer.get(), size); tje_encode_to_file(s.c_str(), Width(img), Height(img), 4, (const unsigned char*)imgbuffer.get()); */ if (std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - onNewFramestart).count() >= 1000) { std::cout << "onNewFrame fps" << onNewFramecounter << std::endl; onNewFramecounter = 0; onNewFramestart = std::chrono::high_resolution_clock::now(); } onNewFramecounter += 1; }) ->onMouseChanged([&](const SL::Screen_Capture::Image *img, const SL::Screen_Capture::MousePoint &mousepoint) { // Uncomment the below code to write the image to disk for debugging /* auto r = realcounter.fetch_add(1); auto s = std::to_string(r) + std::string(" M") + std::string(".png"); if (img) { std::cout << "New mouse coordinates AND NEW Image received." << " x= " << mousepoint.Position.x << " y= " << mousepoint.Position.y << std::endl; lodepng::encode(s, (unsigned char *)StartSrc(*img), Width(*img), Height(*img)); } else { std::cout << "New mouse coordinates received." << " x= " << mousepoint.Position.x << " y= " << mousepoint.Position.y << " The mouse image is still the same as the last" << std::endl; } */ }) ->start_capturing(); framgrabber->setFrameChangeInterval(std::chrono::milliseconds(100)); framgrabber->setMouseChangeInterval(std::chrono::milliseconds(100)); } auto getWindowToCapture(std::string window_to_search_for = "blizzard") { auto windows = SL::Screen_Capture::GetWindows(); // convert to lower case for easier comparisons std::transform(window_to_search_for.begin(), window_to_search_for.end(), window_to_search_for.begin(), [](char c) { return std::tolower(c, std::locale()); }); decltype(windows) filtereditems; for (auto &a : windows) { std::string name = a.Name; std::transform(name.begin(), name.end(), name.begin(), [](char c) { return std::tolower(c, std::locale()); }); if (name.find(window_to_search_for) != std::string::npos) { filtereditems.push_back(a); std::cout << "ADDING WINDOW Height " << a.Size.y << " Width " << a.Size.x << " " << a.Name << std::endl; } } return filtereditems; } void createwindowgrabber() { auto w = getWindowToCapture(); if (w.empty()) { std::cout << "In order to test window capturing, you must modify the getWindowToCapture() function to search for a window that actually exists!" << std::endl; return; } realcounter = 0; onNewFramecounter = 0; framgrabber = nullptr; framgrabber = SL::Screen_Capture::CreateCaptureConfiguration([]() { auto filtereditems = getWindowToCapture(); return filtereditems; }) ->onNewFrame([&](const SL::Screen_Capture::Image &img, const SL::Screen_Capture::Window &window) { // Uncomment the below code to write the image to disk for debugging /* auto r = realcounter.fetch_add(1); auto s = std::to_string(r) + std::string("WINNEW_") + std::string(".jpg"); auto size = Width(img) * Height(img) * sizeof(SL::Screen_Capture::ImageBGRA); auto imgbuffer(std::make_unique<unsigned char[]>(size)); ExtractAndConvertToRGBA(img, imgbuffer.get(), size); tje_encode_to_file(s.c_str(), Width(img), Height(img), 4, (const unsigned char*)imgbuffer.get()); */ if (std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - onNewFramestart).count() >= 1000) { std::cout << "onNewFrame fps" << onNewFramecounter << std::endl; onNewFramecounter = 0; onNewFramestart = std::chrono::high_resolution_clock::now(); } onNewFramecounter += 1; }) ->onMouseChanged([&](const SL::Screen_Capture::Image *img, const SL::Screen_Capture::MousePoint &mousepoint) { // Uncomment the below code to write the image to disk for debugging /* auto r = realcounter.fetch_add(1); auto s = std::to_string(r) + std::string(" M") + std::string(".png"); if (img) { std::cout << "New mouse coordinates AND NEW Image received." << " x= " << mousepoint.Position.x << " y= " << mousepoint.Position.y << std::endl; lodepng::encode(s, (unsigned char *)StartSrc(*img), Width(*img), Height(*img)); } else { std::cout << "New mouse coordinates received." << " x= " << mousepoint.Position.x << " y= " << mousepoint.Position.y << " The mouse image is still the same as the last " << std::endl; } */ }) ->start_capturing(); framgrabber->setFrameChangeInterval(std::chrono::milliseconds(100)); framgrabber->setMouseChangeInterval(std::chrono::milliseconds(100)); } int main() { std::srand(std::time(nullptr)); std::cout << "Starting Capture Demo/Test" << std::endl; std::cout << "Testing captured monitor bounds check" << std::endl; TestCopyContiguous(); TestCopyNonContiguous(); std::cout << "Checking for Permission to capture the screen" << std::endl; if (SL::Screen_Capture::IsScreenCaptureEnabled()) { std::cout << "Application Allowed to Capture the screen!" << std::endl; } else if (SL::Screen_Capture::CanRequestScreenCapture()) { std::cout << "Application Not Allowed to Capture the screen. Waiting for permission " << std::endl; while (!SL::Screen_Capture::IsScreenCaptureEnabled()) { SL::Screen_Capture::RequestScreenCapture(); std::cout << " . "; std::this_thread::sleep_for(std::chrono::seconds(1)); } } else { std::cout << "Cannot Capture the screen due to permission issues. Exiting" << std::endl; return 0; } auto goodmonitors = SL::Screen_Capture::GetMonitors(); for (auto &m : goodmonitors) { std::cout << m << std::endl; assert(SL::Screen_Capture::isMonitorInsideBounds(goodmonitors, m)); } auto badmonitors = SL::Screen_Capture::GetMonitors(); for (auto m : badmonitors) { m.Height += 1; std::cout << m << std::endl; assert(!SL::Screen_Capture::isMonitorInsideBounds(goodmonitors, m)); } for (auto m : badmonitors) { m.Width += 1; std::cout << m << std::endl; assert(!SL::Screen_Capture::isMonitorInsideBounds(goodmonitors, m)); } std::cout << "Running display capturing for 10 seconds" << std::endl; createframegrabber(); std::this_thread::sleep_for(std::chrono::seconds(10)); std::cout << "Running window capturing for 10 seconds" << std::endl; createwindowgrabber(); std::this_thread::sleep_for(std::chrono::seconds(10)); std::cout << "Running Partial display capturing for 10 seconds" << std::endl; createpartialframegrabber(); std::this_thread::sleep_for(std::chrono::seconds(10)); std::cout << "Pausing for 10 seconds. " << std::endl; framgrabber->pause(); auto counti = 0; while (counti++ < 10) { assert(framgrabber->isPaused()); std::cout << " . "; std::this_thread::sleep_for(std::chrono::seconds(1)); } std::cout << std::endl << "Resuming . . . for 5 seconds" << std::endl; framgrabber->resume(); std::this_thread::sleep_for(std::chrono::seconds(5)); std::cout << "Testing changing the interval during runtime for race conditions " << std::endl; // HAMMER THE SET FRAME INTERVAL FOR RACE CONDITIONS!! auto start = std::chrono::high_resolution_clock::now(); while (std::chrono::duration_cast<std::chrono::seconds>(std::chrono::high_resolution_clock::now() - start).count() < 10) { for (auto t = 0; t < 100; t++) { framgrabber->setFrameChangeInterval(std::chrono::microseconds(100)); framgrabber->setMouseChangeInterval(std::chrono::microseconds(100)); } } std::cout << "Changing the cpature rate to 1 second" << std::endl; framgrabber->setFrameChangeInterval(std::chrono::seconds(1)); std::this_thread::sleep_for(std::chrono::seconds(5)); std::cout << "Setting timer using chrono literals" << std::endl; // You can use chron's literals as well! framgrabber->setFrameChangeInterval(10ms); std::this_thread::sleep_for(std::chrono::seconds(5)); std::cout << "Testing recreating" << std::endl; createframegrabber(); std::this_thread::sleep_for(std::chrono::seconds(5)); std::cout << "Testing destroy" << std::endl; framgrabber = nullptr; std::cout << "Testing recreating" << std::endl; createframegrabber(); std::this_thread::sleep_for(std::chrono::seconds(5)); // 4k image int height = 2160; int width = 3840; std::vector<SL::Screen_Capture::ImageBGRA> image1, image2; image1.resize(height * width); for (auto &a : image1) { a.B = static_cast<unsigned short>(std::rand() % 255); a.A = static_cast<unsigned short>(std::rand() % 255); a.G = static_cast<unsigned short>(std::rand() % 255); a.R = static_cast<unsigned short>(std::rand() % 255); } image2.resize(height * width); for (auto &a : image2) { a.B = static_cast<unsigned short>(std::rand() % 255); a.A = static_cast<unsigned short>(std::rand() % 255); a.G = static_cast<unsigned short>(std::rand() % 255); a.R = static_cast<unsigned short>(std::rand() % 255); } long long durationaverage = 0; long long smallestduration = INT_MAX; for (auto i = 0; i < 100; i++) { // run a few times to get an average auto starttime = std::chrono::high_resolution_clock::now(); auto difs = SL::Screen_Capture::GetDifs(SL::Screen_Capture::CreateImage(SL::Screen_Capture::ImageRect(0, 0, width, height), 0, image1.data()), SL::Screen_Capture::CreateImage(SL::Screen_Capture::ImageRect(0, 0, width, height), 0, image2.data())); long long d = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - starttime).count(); smallestduration = std::min(d, smallestduration); durationaverage += std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - starttime).count(); } durationaverage /= 100; std::cout << "Best Case -- Time to get diffs " << durationaverage << " microseconds" << std::endl; std::cout << "Best Case -- Lowest Time " << smallestduration << " microseconds" << std::endl; memset(image1.data(), 5, image1.size() * sizeof(SL::Screen_Capture::ImageBGRA)); memset(image2.data(), 5, image2.size() * sizeof(SL::Screen_Capture::ImageBGRA)); durationaverage = 0; smallestduration = INT_MAX; for (auto i = 0; i < 100; i++) { // run a few times to get an average auto starttime = std::chrono::high_resolution_clock::now(); auto difs = SL::Screen_Capture::GetDifs(SL::Screen_Capture::CreateImage(SL::Screen_Capture::ImageRect(0, 0, width, height), 0, image1.data()), SL::Screen_Capture::CreateImage(SL::Screen_Capture::ImageRect(0, 0, width, height), 0, image2.data())); long long d = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - starttime).count(); smallestduration = std::min(d, smallestduration); durationaverage += std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - starttime).count(); } durationaverage /= 100; std::cout << "Worst Case -- Time to get diffs " << durationaverage << " microseconds" << std::endl; std::cout << "Worst Case -- Lowest Time " << smallestduration << " microseconds" << std::endl; return 0; }
46.532039
166
0.580454
Intro-Ventors
ba33731e7e6c072d1bbfc4638939077f363d4dff
3,490
hpp
C++
src/beast/include/beast/core/buffer_cat.hpp
Py9595/Backpack-Travel-Underlying-Code
c5758792eba7cdd62cb6ff46e642e8e4e4e5417e
[ "BSL-1.0" ]
5
2018-02-02T04:50:43.000Z
2020-10-14T08:15:01.000Z
src/beast/include/beast/core/buffer_cat.hpp
Py9595/Backpack-Travel-Underlying-Code
c5758792eba7cdd62cb6ff46e642e8e4e4e5417e
[ "BSL-1.0" ]
10
2019-01-07T05:33:34.000Z
2020-07-15T00:09:26.000Z
src/beast/include/beast/core/buffer_cat.hpp
Py9595/Backpack-Travel-Underlying-Code
c5758792eba7cdd62cb6ff46e642e8e4e4e5417e
[ "BSL-1.0" ]
3
2017-07-19T11:39:47.000Z
2019-08-06T07:52:21.000Z
// // Copyright (c) 2013-2017 Vinnie Falco (vinnie dot falco at gmail dot com) // // 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 BEAST_BUFFER_CAT_HPP #define BEAST_BUFFER_CAT_HPP #include <beast/config.hpp> #include <beast/core/detail/type_traits.hpp> #include <tuple> namespace beast { /** A buffer sequence representing a concatenation of buffer sequences. @see @ref buffer_cat */ template<class... Buffers> class buffer_cat_view { #if 0 static_assert( detail::is_all_const_buffer_sequence<Buffers...>::value, "BufferSequence requirements not met"); #endif std::tuple<Buffers...> bn_; public: /** The type of buffer returned when dereferencing an iterator. If every buffer sequence in the view is a @b MutableBufferSequence, then `value_type` will be `boost::asio::mutable_buffer`. Otherwise, `value_type` will be `boost::asio::const_buffer`. */ using value_type = #if BEAST_DOXYGEN implementation_defined; #else typename detail::common_buffers_type<Buffers...>::type; #endif /// The type of iterator used by the concatenated sequence class const_iterator; /// Move constructor buffer_cat_view(buffer_cat_view&&) = default; /// Copy constructor buffer_cat_view(buffer_cat_view const&) = default; /// Move assignment buffer_cat_view& operator=(buffer_cat_view&&) = default; // Copy assignment buffer_cat_view& operator=(buffer_cat_view const&) = default; /** Constructor @param buffers The list of buffer sequences to concatenate. Copies of the arguments will be made; however, the ownership of memory is not transferred. */ explicit buffer_cat_view(Buffers const&... buffers); /// Return an iterator to the beginning of the concatenated sequence. const_iterator begin() const; /// Return an iterator to the end of the concatenated sequence. const_iterator end() const; }; /** Concatenate 2 or more buffer sequences. This function returns a constant or mutable buffer sequence which, when iterated, efficiently concatenates the input buffer sequences. Copies of the arguments passed will be made; however, the returned object does not take ownership of the underlying memory. The application is still responsible for managing the lifetime of the referenced memory. @param buffers The list of buffer sequences to concatenate. @return A new buffer sequence that represents the concatenation of the input buffer sequences. This buffer sequence will be a @b MutableBufferSequence if each of the passed buffer sequences is also a @b MutableBufferSequence; otherwise the returned buffer sequence will be a @b ConstBufferSequence. @see @ref buffer_cat_view */ #if BEAST_DOXYGEN template<class... BufferSequence> buffer_cat_view<BufferSequence...> buffer_cat(BufferSequence const&... buffers) #else template<class B1, class B2, class... Bn> inline buffer_cat_view<B1, B2, Bn...> buffer_cat(B1 const& b1, B2 const& b2, Bn const&... bn) #endif { static_assert( detail::is_all_const_buffer_sequence<B1, B2, Bn...>::value, "BufferSequence requirements not met"); return buffer_cat_view<B1, B2, Bn...>{b1, b2, bn...}; } } // beast #include <beast/core/impl/buffer_cat.ipp> #endif
29.083333
79
0.711461
Py9595
ba3523a390724f4ff7a0a2856fac71cd5669994a
6,642
hpp
C++
cppcache/src/statistics/HostStatSampler.hpp
onichols-pivotal/geode-native
4513e9771918ceb7e222bfd7ac614d54dc3114cb
[ "Apache-2.0" ]
48
2017-02-08T22:24:07.000Z
2022-02-06T02:47:56.000Z
cppcache/src/statistics/HostStatSampler.hpp
onichols-pivotal/geode-native
4513e9771918ceb7e222bfd7ac614d54dc3114cb
[ "Apache-2.0" ]
388
2017-02-13T17:09:45.000Z
2022-03-29T22:18:39.000Z
cppcache/src/statistics/HostStatSampler.hpp
onichols-pivotal/geode-native
4513e9771918ceb7e222bfd7ac614d54dc3114cb
[ "Apache-2.0" ]
68
2017-02-09T18:43:15.000Z
2022-03-14T22:59:13.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #ifndef GEODE_STATISTICS_HOSTSTATSAMPLER_H_ #define GEODE_STATISTICS_HOSTSTATSAMPLER_H_ #include <atomic> #include <chrono> #include <memory> #include <mutex> #include <string> #include <thread> #include <vector> #include <boost/filesystem/path.hpp> #include <geode/ExceptionTypes.hpp> #include <geode/internal/geode_globals.hpp> #include "StatArchiveWriter.hpp" #include "StatSamplerStats.hpp" #include "StatisticDescriptor.hpp" #include "Statistics.hpp" #include "StatisticsManager.hpp" #include "StatisticsType.hpp" class TestableHostStatSampler; namespace apache { namespace geode { namespace statistics { using apache::geode::client::CacheImpl; using std::chrono::system_clock; class StatArchiveWriter; class StatisticsManager; /** * HostStatSampler implements a thread which will monitor, sample and archive * statistics. It only has the common functionalities which any sampler needs. */ class HostStatSampler { public: HostStatSampler(boost::filesystem::path filePath, std::chrono::milliseconds sampleRate, StatisticsManager* statMngr, CacheImpl* cache, size_t statFileLimit = 0, size_t statDiskSpaceLimit = 0); ~HostStatSampler() noexcept; HostStatSampler(const HostStatSampler&) = delete; HostStatSampler& operator=(const HostStatSampler&) = delete; /** * Adds the pid to the archive file passed to it. */ const boost::filesystem::path& createArchiveFilename(); /** * Returns the archiveFileName */ const boost::filesystem::path& getArchiveFilename() const; /** * Gets the archive size limit in bytes. */ size_t getArchiveFileSizeLimit() const; /** * Gets the archive disk space limit in bytes. */ size_t getArchiveDiskSpaceLimit() const; /** * Gets the sample rate in milliseconds */ std::chrono::milliseconds getSampleRate() const; /** * Called when this sampler has spent some time working and wants * it to be accounted for. */ void accountForTimeSpentWorking(int64_t nanosSpentWorking); /** * Gets list mutex for synchronization */ std::recursive_mutex& getStatListMutex(); /** * Returns a vector of ptrs to all the current statistic resource instances. */ std::vector<Statistics*>& getStatistics(); /** * Returns a vector of ptrs to all the newly added statistics resource * instances. */ std::vector<Statistics*>& getNewStatistics(); /** * Returns a unique id for the sampler's system. */ int64_t getSystemId(); /** * Returns the time this sampler's system was started. */ system_clock::time_point getSystemStartTime(); /** * Returns the path to this sampler's system directory; if it has one. */ const std::string& getSystemDirectoryPath(); /** * Returns a description of the product that the stats are on */ const std::string& getProductDescription() const; /** * If the size of the archive file exceeds the size limit then the sampler * starts writing in a new file. The path of the new file need to be * obtained from the manager. */ void changeArchive(boost::filesystem::path); void writeGfs(); void forceSample(); void doSample(const boost::filesystem::path& archiveFilename); /** * If the total size of all the archive files exceeds the archive disk space * limit then the older files are deleted. */ void checkDiskLimit(); /** * Starts the main thread for this service. */ void start(); /** * Tell this service's main thread to terminate. */ void stop(); /** * The function executed by the thread */ void svc(void); /** * Method to know whether the sampling thread is running or not. */ bool isRunning() const; private: std::recursive_mutex m_samplingLock; bool m_adminError; std::thread m_thread; std::atomic<bool> m_running; std::atomic<bool> m_stopRequested; std::atomic<bool> m_isStatDiskSpaceEnabled; std::unique_ptr<StatArchiveWriter> m_archiver; std::unique_ptr<StatSamplerStats> m_samplerStats; const char* m_durableClientId; std::chrono::seconds m_durableTimeout; boost::filesystem::path m_archiveFileName; size_t m_archiveFileSizeLimit; size_t m_archiveDiskSpaceLimit; size_t m_spaceUsed = 0; std::chrono::milliseconds m_sampleRate; StatisticsManager* m_statMngr; CacheImpl* m_cache; int64_t m_pid; system_clock::time_point m_startTime; /** * For testing only. */ explicit HostStatSampler(boost::filesystem::path filePath, std::chrono::milliseconds sampleRate, size_t statFileLimit, size_t statDiskSpaceLimit); boost::filesystem::path initStatFileWithExt(); /** * The archiveFile, after it exceeds archiveFileSizeLimit should be rolled * to a new file name. This integer rollIndex will be used to format the * file name into which the current archiveFile will be renamed. */ int32_t m_rollIndex; /** * This function rolls the existing archive file. * Create new file only if current file has some data, otherwise reuse it. */ void rollArchive(const boost::filesystem::path& filename); /** * This function check whether the filename has gfs ext or not * If it is not there it adds and then returns the new filename. */ boost::filesystem::path chkForGFSExt( const boost::filesystem::path& filename) const; /** * Update New Stats in Admin Region. */ void putStatsInAdminRegion(); void initStatDiskSpaceEnabled(); static const char* NC_HSS_Thread; friend TestableHostStatSampler; void initRollIndex(); template <typename _Function> void forEachIndexStatFile(_Function function) const; }; } // namespace statistics } // namespace geode } // namespace apache #endif // GEODE_STATISTICS_HOSTSTATSAMPLER_H_
28.144068
78
0.715598
onichols-pivotal
ba37a9cebd0d3805034e6b678fe965b1cdd7b5be
8,835
cpp
C++
source/ualgobase.cpp
fincs/uSTL-FeOS
6493f68b5c22df1dcbd2b07652fdffaf76e878e4
[ "MIT" ]
1
2019-04-27T20:16:18.000Z
2019-04-27T20:16:18.000Z
source/ualgobase.cpp
fincs/uSTL-FeOS
6493f68b5c22df1dcbd2b07652fdffaf76e878e4
[ "MIT" ]
null
null
null
source/ualgobase.cpp
fincs/uSTL-FeOS
6493f68b5c22df1dcbd2b07652fdffaf76e878e4
[ "MIT" ]
null
null
null
// This file is part of the uSTL library, an STL implementation. // // Copyright (c) 2005 by Mike Sharov <msharov@users.sourceforge.net> // This file is free software, distributed under the MIT License. #ifndef NDEBUG // Optimized code here. asserts slow it down, and are checked elsewhere. #define NDEBUG #endif #pragma GCC visibility push(default) #include "ualgo.h" namespace ustl { // Generic version for implementing fill_nX_fast on non-i386 architectures. template <typename T> static inline void stosv (T*& p, size_t n, T v) { while (n--) *p++ = v; } #if defined(__i386__) || defined(__x86_64__) //---------------------------------------------------------------------- // Copy functions //---------------------------------------------------------------------- static inline void movsb_dir_up (void) { asm volatile ("cld"); } static inline void movsb_dir_down (void) { asm volatile ("std"); } static inline void movsb (const void*& src, size_t nBytes, void*& dest) { asm volatile ("rep;\n\tmovsb" : "=&S"(src), "=&D"(dest), "=&c"(nBytes) : "0"(src), "1"(dest), "2"(nBytes) : "memory"); } static inline void movsd (const void*& src, size_t nWords, void*& dest) { asm volatile ("rep;\n\tmovsl" : "=&S"(src), "=&D"(dest), "=&c"(nWords) : "0"(src), "1"(dest), "2"(nWords) : "memory"); } template <> inline void stosv (uint8_t*& p, size_t n, uint8_t v) { asm volatile ("rep;\n\tstosb" : "=&D"(p), "=c"(n) : "0"(p), "1"(n), "a"(v) : "memory"); } template <> inline void stosv (uint16_t*& p, size_t n, uint16_t v) { asm volatile ("rep;\n\tstosw" : "=&D"(p), "=c"(n) : "0"(p), "1"(n), "a"(v) : "memory"); } template <> inline void stosv (uint32_t*& p, size_t n, uint32_t v) { asm volatile ("rep;\n\tstosl" : "=&D"(p), "=c"(n) : "0"(p), "1"(n), "a"(v) : "memory"); } #if CPU_HAS_MMX #define MMX_ALIGN 16U // Data must be aligned on this grain #define MMX_BS 32U // Assembly routines copy data this many bytes at a time. static inline void simd_block_copy (const void* src, void* dest) { const char* csrc ((const char*) src); char* cdest ((char*) dest); #if CPU_HAS_SSE asm ( "movaps\t%2, %%xmm0 \n\t" "movaps\t%3, %%xmm1 \n\t" "movntps\t%%xmm0, %0 \n\t" "movntps\t%%xmm1, %1" : "=m"(cdest[0]), "=m"(cdest[16]) : "m"(csrc[0]), "m"(csrc[16]) : "xmm0", "xmm1", "memory"); #else asm ( "movq %4, %%mm0 \n\t" "movq %5, %%mm1 \n\t" "movq %6, %%mm2 \n\t" "movq %7, %%mm3 \n\t" "movq %%mm0, %0 \n\t" "movq %%mm1, %1 \n\t" "movq %%mm2, %2 \n\t" "movq %%mm3, %3" : "=m"(cdest[0]), "=m"(cdest[8]), "=m"(cdest[16]), "=m"(cdest[24]) : "m"(csrc[0]), "m"(csrc[8]), "m"(csrc[16]), "m"(csrc[24]) : "mm0", "mm1", "mm2", "mm3", "st", "st(1)", "st(2)", "st(3)", "memory"); #endif } static inline void simd_block_store (uint8_t* dest) { #if CPU_HAS_SSE asm volatile ( "movntq %%mm0, %0\n\t" "movntq %%mm0, %1\n\t" "movntq %%mm0, %2\n\t" "movntq %%mm0, %3" : "=m"(dest[0]), "=m"(dest[8]), "=m"(dest[16]), "=m"(dest[24]) :: "memory"); #else asm volatile ( "movq %%mm0, %0 \n\t" "movq %%mm0, %1 \n\t" "movq %%mm0, %2 \n\t" "movq %%mm0, %3" : "=m"(dest[0]), "=m"(dest[8]), "=m"(dest[16]), "=m"(dest[24]) :: "memory"); #endif } static inline void simd_block_cleanup (void) { #if !CPU_HAS_SSE simd::reset_mmx(); #endif asm volatile ("sfence"); } /// The fastest optimized raw memory copy. void copy_n_fast (const void* src, size_t nBytes, void* dest) throw() { movsb_dir_up(); size_t nHeadBytes = Align(uintptr_t(src), MMX_ALIGN) - uintptr_t(src); nHeadBytes = min (nHeadBytes, nBytes); movsb (src, nHeadBytes, dest); nBytes -= nHeadBytes; if (!(uintptr_t(dest) % MMX_ALIGN)) { const size_t nMiddleBlocks = nBytes / MMX_BS; for (uoff_t i = 0; i < nMiddleBlocks; ++ i) { prefetch (advance (src, 512), 0, 0); simd_block_copy (src, dest); src = advance (src, MMX_BS); dest = advance (dest, MMX_BS); } simd_block_cleanup(); nBytes %= MMX_BS; } movsb (src, nBytes, dest); } #endif // CPU_HAS_MMX /// The fastest optimized backwards raw memory copy. void copy_backward_fast (const void* first, const void* last, void* result) throw() { prefetch (first, 0, 0); prefetch (result, 1, 0); size_t nBytes (distance (first, last)); movsb_dir_down(); size_t nHeadBytes = uintptr_t(last) % 4; last = advance (last, -1); result = advance (result, -1); movsb (last, nHeadBytes, result); nBytes -= nHeadBytes; if (uintptr_t(result) % 4 == 3) { const size_t nMiddleBlocks = nBytes / 4; last = advance (last, -3); result = advance (result, -3); movsd (last, nMiddleBlocks, result); nBytes %= 4; } movsb (last, nBytes, result); movsb_dir_up(); } #endif // __i386__ //---------------------------------------------------------------------- // Fill functions //---------------------------------------------------------------------- #if CPU_HAS_MMX template <typename T> static inline void build_block (T) {} template <> inline void build_block (uint8_t v) { asm volatile ( "movd %0, %%mm0\n\tpunpcklbw %%mm0, %%mm0\n\tpshufw $0, %%mm0, %%mm0" : : "g"(uint32_t(v)) : "mm0"); } template <> inline void build_block (uint16_t v) { asm volatile ( "movd %0, %%mm0\n\tpshufw $0, %%mm0, %%mm0" : : "g"(uint32_t(v)) : "mm0"); } template <> inline void build_block (uint32_t v) { asm volatile ( "movd %0, %%mm0\n\tpunpckldq %%mm0, %%mm0" : : "g"(uint32_t(v)) : "mm0"); } static inline void simd_block_fill_loop (uint8_t*& dest, size_t count) { prefetch (advance (dest, 512), 1, 0); for (const uint8_t* destEnd = dest + count * MMX_BS; dest < destEnd; dest += MMX_BS) simd_block_store (dest); simd_block_cleanup(); simd::reset_mmx(); } template <typename T> static inline void fill_n_fast (T* dest, size_t count, T v) { size_t nHead = Align(uintptr_t(dest), MMX_ALIGN) - uintptr_t(dest) / sizeof(T); nHead = min (nHead, count); stosv (dest, nHead, v); count -= nHead; build_block (v); uint8_t* bdest = (uint8_t*) dest; simd_block_fill_loop (bdest, count * sizeof(T) / MMX_BS); count %= MMX_BS; dest = (T*) bdest; stosv (dest, count, v); } void fill_n8_fast (uint8_t* dest, size_t count, uint8_t v) throw() { fill_n_fast (dest, count, v); } void fill_n16_fast (uint16_t* dest, size_t count, uint16_t v) throw() { fill_n_fast (dest, count, v); } void fill_n32_fast (uint32_t* dest, size_t count, uint32_t v) throw() { fill_n_fast (dest, count, v); } #else void fill_n8_fast (uint8_t* dest, size_t count, uint8_t v) throw() { memset (dest, v, count); } void fill_n16_fast (uint16_t* dest, size_t count, uint16_t v) throw() { stosv (dest, count, v); } void fill_n32_fast (uint32_t* dest, size_t count, uint32_t v) throw() { stosv (dest, count, v); } #endif // CPU_HAS_MMX /// Exchanges ranges [first, middle) and [middle, last) void rotate_fast (void* first, void* middle, void* last) throw() { #if HAVE_ALLOCA_H const size_t half1 (distance (first, middle)), half2 (distance (middle, last)); const size_t hmin (min (half1, half2)); if (!hmin) return; void* buf = alloca (hmin); if (buf) { if (half2 < half1) { copy_n_fast (middle, half2, buf); copy_backward_fast (first, middle, last); copy_n_fast (buf, half2, first); } else { copy_n_fast (first, half1, buf); copy_n_fast (middle, half2, first); copy_n_fast (buf, half1, advance (first, half2)); } } else #else if (first == middle || middle == last) return; #endif { char* f = (char*) first; char* m = (char*) middle; char* l = (char*) last; reverse (f, m); reverse (m, l); while (f != m && m != l) iter_swap (f++, --l); reverse (f, (f == m ? l : m)); } } #if __GNUC__ < 4 size_t popcount (uint32_t v) { const uint32_t w = v - ((v >> 1) & 0x55555555); // Algorithm from AMD optimization guide const uint32_t x = (w & 0x33333333) + ((w >> 2) & 0x33333333); return (((x + (x >> 4) & 0x0F0F0F0F) * 0x01010101) >> 24); } #if HAVE_INT64_T /// \brief Returns the number of 1s in \p v in binary. size_t popcount (uint64_t v) { v -= (v >> 1) & UINT64_C(0x5555555555555555); // Algorithm from Wikipedia v = (v & UINT64_C(0x3333333333333333)) + ((v >> 2) & UINT64_C(0x3333333333333333)); v = (v + (v >> 4)) & UINT64_C(0x0F0F0F0F0F0F0F0F); return ((v * UINT64_C(0x0101010101010101)) >> 56); } #endif // HAVE_INT64_T #endif // !__GNUC__ //---------------------------------------------------------------------- // Miscellaneous instantiated stuff from headers which don't have enough // to warrant creation of a separate file.cc //---------------------------------------------------------------------- // Used in uspecial to print printable characters const char _FmtPrtChr[2][8]={"'%c'","%d"}; } // namespace ustl
30.783972
97
0.584493
fincs
ba3b53bb750f240122a4e459cf808f7b965d0e88
3,546
cpp
C++
C++/RPNC.cpp
Jamboii/misc-projects
3f7201212a0aab00fe5021343e296d3c47957f1e
[ "MIT" ]
1
2020-03-07T19:41:14.000Z
2020-03-07T19:41:14.000Z
C++/RPNC.cpp
Jamboii/misc-projects
3f7201212a0aab00fe5021343e296d3c47957f1e
[ "MIT" ]
null
null
null
C++/RPNC.cpp
Jamboii/misc-projects
3f7201212a0aab00fe5021343e296d3c47957f1e
[ "MIT" ]
null
null
null
#include <stdio.h> #include <vector> #include <string> #include <sstream> #include <iostream> #include <fstream> #include <cmath> #include <algorithm> #include <iterator> #include <cstdlib> #include <stdint.h> #include <stdlib.h> #include "stack.hpp" using namespace std; int rpn(const string &expr) { Stack values(10); // double stack with 10 values max istringstream iss(expr); // input string stream to operate on expression string token; int tokens = 0; while (iss >> token) { double tokenNum; if (istringstream(token) >> tokenNum) // if input of string classifies as double { values.push(tokenNum); tokens++; } else if (tokens < 2) // reached operation but not enough operands { cerr << "RPNC ERROR Invalid Expression: " << expr << endl; return 0; } else // reached operation and have enough operands { // pop last 2 operand inputs double secondOp = values.peek(); values.pop(); double firstOp = values.peek(); values.pop(); // perform operation based on token if (token == "*") values.push(firstOp * secondOp); else if (token == "/") values.push(firstOp / secondOp); else if (token == "+") values.push(firstOp + secondOp); else if (token == "-") values.push(firstOp - secondOp); else if (token == "^") values.push(pow(firstOp,secondOp)); else // operation not applicable { cerr << "RPNC ERROR Invalid Expression: " << expr << endl; return 0; } // set tokens to amount of operands still in the stack tokens = values.size(); } } if (values.size() == 1) cout << expr << "\t\t\t = " << values.peek() << endl; else cerr << "RPNC ERROR Invalid Expression: " << expr << endl; return 0; } int main(int argc, char *argv[]) { ifstream fin; string src_filename; // Set up failsafe for correct usage of parameters if (argc > 2) { fprintf( stderr, "\nUsage: FileParser <src_filename>\n" ); fprintf( stderr, " where src_filename contains the file names to be processed\n" ); exit(-1); } else if (argc == 2) // filename src_filename = argv[1]; else // prompt user for input of file { cout << "Input an expressions file: "; cin >> src_filename; } // check to make sure file input is correct fin.open(src_filename); if (fin.fail()) { cout << "Input file opening failed. Make sure you input the name of the file that contains the names of files to be processed" << endl; return 1; } // Display opening message cout << "-----------------------------------------------------" << endl; cout << "File " << src_filename << " opened successfully" << endl; cout << "-----------------------------------------------------" << endl; string expr; // get expression cout << "+++++++++++++++++++++++++++++++" << endl; while (getline(fin,expr)) { cout << "Evaluating expression: " << expr << endl; rpn(expr); // Evaluate expression in text file using Reverse Polish Notation cout << "+++++++++++++++++++++++++++++++" << endl; } return 0; }
30.307692
143
0.511844
Jamboii
ba428a58e66d17b0b335a8f52ba6fc5459e29039
28,546
cpp
C++
cocos2dx/base_nodes/CCNode.cpp
nickflink/cocos2d-x
2a2730bf842567c2b8d460006abf06035243602d
[ "Zlib", "libtiff", "BSD-2-Clause", "Apache-2.0", "MIT", "Libpng", "curl", "BSD-3-Clause" ]
null
null
null
cocos2dx/base_nodes/CCNode.cpp
nickflink/cocos2d-x
2a2730bf842567c2b8d460006abf06035243602d
[ "Zlib", "libtiff", "BSD-2-Clause", "Apache-2.0", "MIT", "Libpng", "curl", "BSD-3-Clause" ]
null
null
null
cocos2dx/base_nodes/CCNode.cpp
nickflink/cocos2d-x
2a2730bf842567c2b8d460006abf06035243602d
[ "Zlib", "libtiff", "BSD-2-Clause", "Apache-2.0", "MIT", "Libpng", "curl", "BSD-3-Clause" ]
null
null
null
/**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2009 Valentin Milea Copyright (c) 2011 Zynga Inc. http://www.cocos2d-x.org 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 "cocoa/CCString.h" #include "CCNode.h" #include "support/CCPointExtension.h" #include "support/TransformUtils.h" #include "CCCamera.h" #include "effects/CCGrid.h" #include "CCDirector.h" #include "CCScheduler.h" #include "touch_dispatcher/CCTouch.h" #include "actions/CCActionManager.h" #include "script_support/CCScriptSupport.h" #include "shaders/CCGLProgram.h" // externals #include "kazmath/GL/matrix.h" #if CC_NODE_RENDER_SUBPIXEL #define RENDER_IN_SUBPIXEL #else #define RENDER_IN_SUBPIXEL (__ARGS__) (ceil(__ARGS__)) #endif NS_CC_BEGIN // XXX: Yes, nodes might have a sort problem once every 15 days if the game runs at 60 FPS and each frame sprites are reordered. static int s_globalOrderOfArrival = 1; CCNode::CCNode(void) : m_nZOrder(0) , m_fVertexZ(0.0f) , m_fRotationX(0.0f) , m_fRotationY(0.0f) , m_fScaleX(1.0f) , m_fScaleY(1.0f) , m_obPosition(CCPointZero) , m_fSkewX(0.0f) , m_fSkewY(0.0f) // children (lazy allocs) , m_pChildren(NULL) // lazy alloc , m_pCamera(NULL) , m_pGrid(NULL) , m_bVisible(true) , m_obAnchorPoint(CCPointZero) , m_obAnchorPointInPoints(CCPointZero) , m_obContentSize(CCSizeZero) , m_bRunning(false) , m_pParent(NULL) // "whole screen" objects. like Scenes and Layers, should set m_bIgnoreAnchorPointForPosition to false , m_bIgnoreAnchorPointForPosition(false) , m_nTag(kCCNodeTagInvalid) // userData is always inited as nil , m_pUserData(NULL) , m_pUserObject(NULL) , m_bTransformDirty(true) , m_bInverseDirty(true) , m_nScriptHandler(0) , m_pShaderProgram(NULL) , m_uOrderOfArrival(0) , m_eGLServerState(ccGLServerState(0)) , m_bReorderChildDirty(false) { // set default scheduler and actionManager CCDirector *director = CCDirector::sharedDirector(); m_pActionManager = director->getActionManager(); m_pActionManager->retain(); m_pScheduler = director->getScheduler(); m_pScheduler->retain(); CCScriptEngineProtocol* pEngine = CCScriptEngineManager::sharedManager()->getScriptEngine(); m_eScriptType = pEngine != NULL ? pEngine->getScriptType() : kScriptTypeNone; } CCNode::~CCNode(void) { CCLOGINFO( "cocos2d: deallocing" ); unregisterScriptHandler(); CC_SAFE_RELEASE(m_pActionManager); CC_SAFE_RELEASE(m_pScheduler); // attributes CC_SAFE_RELEASE(m_pCamera); CC_SAFE_RELEASE(m_pGrid); CC_SAFE_RELEASE(m_pShaderProgram); CC_SAFE_RELEASE(m_pUserObject); if(m_pChildren && m_pChildren->count() > 0) { CCObject* child; CCARRAY_FOREACH(m_pChildren, child) { CCNode* pChild = (CCNode*) child; if (pChild) { pChild->m_pParent = NULL; } } } // children CC_SAFE_RELEASE(m_pChildren); } float CCNode::getSkewX() { return m_fSkewX; } void CCNode::setSkewX(float newSkewX) { m_fSkewX = newSkewX; m_bTransformDirty = m_bInverseDirty = true; } float CCNode::getSkewY() { return m_fSkewY; } void CCNode::setSkewY(float newSkewY) { m_fSkewY = newSkewY; m_bTransformDirty = m_bInverseDirty = true; } /// zOrder getter int CCNode::getZOrder() { return m_nZOrder; } /// zOrder setter : private method /// used internally to alter the zOrder variable. DON'T call this method manually void CCNode::_setZOrder(int z) { m_nZOrder = z; } void CCNode::setZOrder(int z) { _setZOrder(z); if (m_pParent) { m_pParent->reorderChild(this, z); } } /// vertexZ getter float CCNode::getVertexZ() { return m_fVertexZ; } /// vertexZ setter void CCNode::setVertexZ(float var) { m_fVertexZ = var; } /// rotation getter float CCNode::getRotation() { #ifdef NFHACK_ASSERT_ON_CONFLICTING_ROTATION CCAssert(m_fRotationX == m_fRotationY, "CCNode#rotation. RotationX != RotationY. Don't know which one to return"); #endif return m_fRotationX; } /// rotation setter void CCNode::setRotation(float newRotation) { m_fRotationX = m_fRotationY = newRotation; m_bTransformDirty = m_bInverseDirty = true; } float CCNode::getRotationX() { return m_fRotationX; } void CCNode::setRotationX(float fRotationX) { m_fRotationX = fRotationX; m_bTransformDirty = m_bInverseDirty = true; } float CCNode::getRotationY() { return m_fRotationY; } void CCNode::setRotationY(float fRotationY) { m_fRotationY = fRotationY; m_bTransformDirty = m_bInverseDirty = true; } /// scale getter float CCNode::getScale(void) { CCAssert( m_fScaleX == m_fScaleY, "CCNode#scale. ScaleX != ScaleY. Don't know which one to return"); return m_fScaleX; } /// scale setter void CCNode::setScale(float scale) { m_fScaleX = m_fScaleY = scale; m_bTransformDirty = m_bInverseDirty = true; } /// scaleX getter float CCNode::getScaleX() { return m_fScaleX; } /// scaleX setter void CCNode::setScaleX(float newScaleX) { m_fScaleX = newScaleX; m_bTransformDirty = m_bInverseDirty = true; } /// scaleY getter float CCNode::getScaleY() { return m_fScaleY; } /// scaleY setter void CCNode::setScaleY(float newScaleY) { m_fScaleY = newScaleY; m_bTransformDirty = m_bInverseDirty = true; } /// position getter CCPoint CCNode::getPosition() { return m_obPosition; } /// position setter void CCNode::setPosition(const CCPoint& newPosition) { m_obPosition = newPosition; m_bTransformDirty = m_bInverseDirty = true; } const CCPoint& CCNode::getPositionLua(void) { return m_obPosition; } void CCNode::getPosition(float* x, float* y) { *x = m_obPosition.x; *y = m_obPosition.y; } float CCNode::getPositionX(void) { return m_obPosition.x; } float CCNode::getPositionY(void) { return m_obPosition.y; } void CCNode::setPositionX(float x) { setPosition(ccp(x, m_obPosition.y)); } void CCNode::setPositionY(float y) { setPosition(ccp(m_obPosition.x, y)); } void CCNode::setPosition(float x, float y) { setPosition(ccp(x, y)); } /// children getter CCArray* CCNode::getChildren() { return m_pChildren; } unsigned int CCNode::getChildrenCount(void) { return m_pChildren ? m_pChildren->count() : 0; } /// camera getter: lazy alloc CCCamera* CCNode::getCamera() { if (!m_pCamera) { m_pCamera = new CCCamera(); } return m_pCamera; } /// grid getter CCGridBase* CCNode::getGrid() { return m_pGrid; } /// grid setter void CCNode::setGrid(CCGridBase* pGrid) { CC_SAFE_RETAIN(pGrid); CC_SAFE_RELEASE(m_pGrid); m_pGrid = pGrid; } /// isVisible getter bool CCNode::isVisible() { return m_bVisible; } /// isVisible setter void CCNode::setVisible(bool var) { m_bVisible = var; } CCPoint CCNode::getAnchorPointInPoints() { return m_obAnchorPointInPoints; } /// anchorPoint getter CCPoint CCNode::getAnchorPoint() { return m_obAnchorPoint; } void CCNode::setAnchorPoint(const CCPoint& point) { if( ! point.equals(m_obAnchorPoint)) { m_obAnchorPoint = point; m_obAnchorPointInPoints = ccp(m_obContentSize.width * m_obAnchorPoint.x, m_obContentSize.height * m_obAnchorPoint.y ); m_bTransformDirty = m_bInverseDirty = true; } } /// contentSize getter CCSize CCNode::getContentSize() { return m_obContentSize; } void CCNode::setContentSize(const CCSize & size) { if ( ! size.equals(m_obContentSize)) { m_obContentSize = size; m_obAnchorPointInPoints = ccp(m_obContentSize.width * m_obAnchorPoint.x, m_obContentSize.height * m_obAnchorPoint.y ); m_bTransformDirty = m_bInverseDirty = true; } } // isRunning getter bool CCNode::isRunning() { return m_bRunning; } /// parent getter CCNode * CCNode::getParent() { return m_pParent; } /// parent setter void CCNode::setParent(CCNode * var) { m_pParent = var; } /// isRelativeAnchorPoint getter bool CCNode::isIgnoreAnchorPointForPosition() { return m_bIgnoreAnchorPointForPosition; } /// isRelativeAnchorPoint setter void CCNode::ignoreAnchorPointForPosition(bool newValue) { if (newValue != m_bIgnoreAnchorPointForPosition) { m_bIgnoreAnchorPointForPosition = newValue; m_bTransformDirty = m_bInverseDirty = true; } } /// tag getter int CCNode::getTag() { return m_nTag; } /// tag setter void CCNode::setTag(int var) { m_nTag = var; } /// userData getter void * CCNode::getUserData() { return m_pUserData; } /// userData setter void CCNode::setUserData(void *var) { m_pUserData = var; } unsigned int CCNode::getOrderOfArrival() { return m_uOrderOfArrival; } void CCNode::setOrderOfArrival(unsigned int uOrderOfArrival) { m_uOrderOfArrival = uOrderOfArrival; } CCGLProgram* CCNode::getShaderProgram() { return m_pShaderProgram; } CCObject* CCNode::getUserObject() { return m_pUserObject; } ccGLServerState CCNode::getGLServerState() { return m_eGLServerState; } void CCNode::setGLServerState(ccGLServerState glServerState) { m_eGLServerState = glServerState; } void CCNode::setUserObject(CCObject *pUserObject) { CC_SAFE_RELEASE(m_pUserObject); CC_SAFE_RETAIN(pUserObject); m_pUserObject = pUserObject; } void CCNode::setShaderProgram(CCGLProgram *pShaderProgram) { CC_SAFE_RELEASE(m_pShaderProgram); m_pShaderProgram = pShaderProgram; CC_SAFE_RETAIN(m_pShaderProgram); } CCRect CCNode::boundingBox() { CCRect rect = CCRectMake(0, 0, m_obContentSize.width, m_obContentSize.height); return CCRectApplyAffineTransform(rect, nodeToParentTransform()); } CCNode * CCNode::node(void) { return CCNode::create(); } CCNode * CCNode::create(void) { CCNode * pRet = new CCNode(); pRet->autorelease(); return pRet; } void CCNode::cleanup() { // actions this->stopAllActions(); this->unscheduleAllSelectors(); if ( m_eScriptType != kScriptTypeNone) { CCScriptEngineManager::sharedManager()->getScriptEngine()->executeNodeEvent(this, kCCNodeOnCleanup); } // timers arrayMakeObjectsPerformSelector(m_pChildren, cleanup, CCNode*); } const char* CCNode::description() { return CCString::createWithFormat("<CCNode | Tag = %d>", m_nTag)->getCString(); } // lazy allocs void CCNode::childrenAlloc(void) { m_pChildren = CCArray::createWithCapacity(4); m_pChildren->retain(); } CCNode* CCNode::getChildByTag(int aTag) { CCAssert( aTag != kCCNodeTagInvalid, "Invalid tag"); if(m_pChildren && m_pChildren->count() > 0) { CCObject* child; CCARRAY_FOREACH(m_pChildren, child) { CCNode* pNode = (CCNode*) child; if(pNode && pNode->m_nTag == aTag) return pNode; } } return NULL; } /* "add" logic MUST only be on this method * If a class want's to extend the 'addChild' behavior it only needs * to override this method */ void CCNode::addChild(CCNode *child, int zOrder, int tag) { CCAssert( child != NULL, "Argument must be non-nil"); CCAssert( child->m_pParent == NULL, "child already added. It can't be added again"); if( ! m_pChildren ) { this->childrenAlloc(); } this->insertChild(child, zOrder); child->m_nTag = tag; child->setParent(this); child->setOrderOfArrival(s_globalOrderOfArrival++); if( m_bRunning ) { child->onEnter(); child->onEnterTransitionDidFinish(); } } void CCNode::addChild(CCNode *child, int zOrder) { CCAssert( child != NULL, "Argument must be non-nil"); this->addChild(child, zOrder, child->m_nTag); } void CCNode::addChild(CCNode *child) { CCAssert( child != NULL, "Argument must be non-nil"); this->addChild(child, child->m_nZOrder, child->m_nTag); } void CCNode::removeFromParent() { this->removeFromParentAndCleanup(true); } void CCNode::removeFromParentAndCleanup(bool cleanup) { if (m_pParent != NULL) { m_pParent->removeChild(this,cleanup); } } void CCNode::removeChild(CCNode* child) { this->removeChild(child, true); } /* "remove" logic MUST only be on this method * If a class want's to extend the 'removeChild' behavior it only needs * to override this method */ void CCNode::removeChild(CCNode* child, bool cleanup) { // explicit nil handling if (m_pChildren == NULL) { return; } if ( m_pChildren->containsObject(child) ) { this->detachChild(child,cleanup); } } void CCNode::removeChildByTag(int tag) { this->removeChildByTag(tag, true); } void CCNode::removeChildByTag(int tag, bool cleanup) { CCAssert( tag != kCCNodeTagInvalid, "Invalid tag"); CCNode *child = this->getChildByTag(tag); if (child == NULL) { CCLOG("cocos2d: removeChildByTag: child not found!"); } else { this->removeChild(child, cleanup); } } void CCNode::removeAllChildren() { this->removeAllChildrenWithCleanup(true); } void CCNode::removeAllChildrenWithCleanup(bool cleanup) { // not using detachChild improves speed here if ( m_pChildren && m_pChildren->count() > 0 ) { CCObject* child; CCARRAY_FOREACH(m_pChildren, child) { CCNode* pNode = (CCNode*) child; if (pNode) { // IMPORTANT: // -1st do onExit // -2nd cleanup if(m_bRunning) { pNode->onExitTransitionDidStart(); pNode->onExit(); } if (cleanup) { pNode->cleanup(); } // set parent nil at the end pNode->setParent(NULL); } } m_pChildren->removeAllObjects(); } } void CCNode::detachChild(CCNode *child, bool doCleanup) { // IMPORTANT: // -1st do onExit // -2nd cleanup if (m_bRunning) { child->onExitTransitionDidStart(); child->onExit(); } // If you don't do cleanup, the child's actions will not get removed and the // its scheduledSelectors_ dict will not get released! if (doCleanup) { child->cleanup(); } // set parent nil at the end child->setParent(NULL); m_pChildren->removeObject(child); } // helper used by reorderChild & add void CCNode::insertChild(CCNode* child, int z) { m_bReorderChildDirty = true; ccArrayAppendObjectWithResize(m_pChildren->data, child); child->_setZOrder(z); } void CCNode::reorderChild(CCNode *child, int zOrder) { CCAssert( child != NULL, "Child must be non-nil"); m_bReorderChildDirty = true; child->setOrderOfArrival(s_globalOrderOfArrival++); child->_setZOrder(zOrder); } void CCNode::sortAllChildren() { if (m_bReorderChildDirty) { int i,j,length = m_pChildren->data->num; CCNode ** x = (CCNode**)m_pChildren->data->arr; CCNode *tempItem; // insertion sort for(i=1; i<length; i++) { tempItem = x[i]; j = i-1; //continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller while(j>=0 && ( tempItem->m_nZOrder < x[j]->m_nZOrder || ( tempItem->m_nZOrder== x[j]->m_nZOrder && tempItem->m_uOrderOfArrival < x[j]->m_uOrderOfArrival ) ) ) { x[j+1] = x[j]; j = j-1; } x[j+1] = tempItem; } //don't need to check children recursively, that's done in visit of each child m_bReorderChildDirty = false; } } void CCNode::draw() { //CCAssert(0); // override me // Only use- this function to draw your stuff. // DON'T draw your stuff outside this method } void CCNode::visit() { // quick return if not visible. children won't be drawn. if (!m_bVisible) { return; } kmGLPushMatrix(); if (m_pGrid && m_pGrid->isActive()) { m_pGrid->beforeDraw(); } this->transform(); CCNode* pNode = NULL; unsigned int i = 0; if(m_pChildren && m_pChildren->count() > 0) { sortAllChildren(); // draw children zOrder < 0 ccArray *arrayData = m_pChildren->data; for( ; i < arrayData->num; i++ ) { pNode = (CCNode*) arrayData->arr[i]; if ( pNode && pNode->m_nZOrder < 0 ) { pNode->visit(); } else { break; } } // self draw this->draw(); for( ; i < arrayData->num; i++ ) { pNode = (CCNode*) arrayData->arr[i]; if (pNode) { pNode->visit(); } } } else { this->draw(); } // reset for next frame m_uOrderOfArrival = 0; if (m_pGrid && m_pGrid->isActive()) { m_pGrid->afterDraw(this); } kmGLPopMatrix(); } void CCNode::transformAncestors() { if( m_pParent != NULL ) { m_pParent->transformAncestors(); m_pParent->transform(); } } void CCNode::transform() { kmMat4 transfrom4x4; // Convert 3x3 into 4x4 matrix CCAffineTransform tmpAffine = this->nodeToParentTransform(); CGAffineToGL(&tmpAffine, transfrom4x4.mat); // Update Z vertex manually transfrom4x4.mat[14] = m_fVertexZ; kmGLMultMatrix( &transfrom4x4 ); // XXX: Expensive calls. Camera should be integrated into the cached affine matrix if ( m_pCamera != NULL && !(m_pGrid != NULL && m_pGrid->isActive()) ) { bool translate = (m_obAnchorPointInPoints.x != 0.0f || m_obAnchorPointInPoints.y != 0.0f); if( translate ) kmGLTranslatef(RENDER_IN_SUBPIXEL(m_obAnchorPointInPoints.x), RENDER_IN_SUBPIXEL(m_obAnchorPointInPoints.y), 0 ); m_pCamera->locate(); if( translate ) kmGLTranslatef(RENDER_IN_SUBPIXEL(-m_obAnchorPointInPoints.x), RENDER_IN_SUBPIXEL(-m_obAnchorPointInPoints.y), 0 ); } } void CCNode::onEnter() { arrayMakeObjectsPerformSelector(m_pChildren, onEnter, CCNode*); this->resumeSchedulerAndActions(); m_bRunning = true; if (m_eScriptType != kScriptTypeNone) { CCScriptEngineManager::sharedManager()->getScriptEngine()->executeNodeEvent(this, kCCNodeOnEnter); } } void CCNode::onEnterTransitionDidFinish() { arrayMakeObjectsPerformSelector(m_pChildren, onEnterTransitionDidFinish, CCNode*); if (m_eScriptType == kScriptTypeJavascript) { CCScriptEngineManager::sharedManager()->getScriptEngine()->executeNodeEvent(this, kCCNodeOnEnterTransitionDidFinish); } } void CCNode::onExitTransitionDidStart() { arrayMakeObjectsPerformSelector(m_pChildren, onExitTransitionDidStart, CCNode*); if (m_eScriptType == kScriptTypeJavascript) { CCScriptEngineManager::sharedManager()->getScriptEngine()->executeNodeEvent(this, kCCNodeOnExitTransitionDidStart); } } void CCNode::onExit() { this->pauseSchedulerAndActions(); m_bRunning = false; if ( m_eScriptType != kScriptTypeNone) { CCScriptEngineManager::sharedManager()->getScriptEngine()->executeNodeEvent(this, kCCNodeOnExit); } arrayMakeObjectsPerformSelector(m_pChildren, onExit, CCNode*); } void CCNode::registerScriptHandler(int nHandler) { unregisterScriptHandler(); m_nScriptHandler = nHandler; LUALOG("[LUA] Add CCNode event handler: %d", m_nScriptHandler); } void CCNode::unregisterScriptHandler(void) { if (m_nScriptHandler) { CCScriptEngineManager::sharedManager()->getScriptEngine()->removeScriptHandler(m_nScriptHandler); LUALOG("[LUA] Remove CCNode event handler: %d", m_nScriptHandler); m_nScriptHandler = 0; } } void CCNode::setActionManager(CCActionManager* actionManager) { if( actionManager != m_pActionManager ) { this->stopAllActions(); CC_SAFE_RETAIN(actionManager); CC_SAFE_RELEASE(m_pActionManager); m_pActionManager = actionManager; } } CCActionManager* CCNode::getActionManager() { return m_pActionManager; } CCAction * CCNode::runAction(CCAction* action) { CCAssert( action != NULL, "Argument must be non-nil"); m_pActionManager->addAction(action, this, !m_bRunning); return action; } void CCNode::stopAllActions() { m_pActionManager->removeAllActionsFromTarget(this); } void CCNode::stopAction(CCAction* action) { m_pActionManager->removeAction(action); } void CCNode::stopActionByTag(int tag) { CCAssert( tag != kCCActionTagInvalid, "Invalid tag"); m_pActionManager->removeActionByTag(tag, this); } CCAction * CCNode::getActionByTag(int tag) { CCAssert( tag != kCCActionTagInvalid, "Invalid tag"); return m_pActionManager->getActionByTag(tag, this); } unsigned int CCNode::numberOfRunningActions() { return m_pActionManager->numberOfRunningActionsInTarget(this); } // CCNode - Callbacks void CCNode::setScheduler(CCScheduler* scheduler) { if( scheduler != m_pScheduler ) { this->unscheduleAllSelectors(); CC_SAFE_RETAIN(scheduler); CC_SAFE_RELEASE(m_pScheduler); m_pScheduler = scheduler; } } CCScheduler* CCNode::getScheduler() { return m_pScheduler; } void CCNode::scheduleUpdate() { scheduleUpdateWithPriority(0); } void CCNode::scheduleUpdateWithPriority(int priority) { m_pScheduler->scheduleUpdateForTarget(this, priority, !m_bRunning); } void CCNode::unscheduleUpdate() { m_pScheduler->unscheduleUpdateForTarget(this); } void CCNode::schedule(SEL_SCHEDULE selector) { this->schedule(selector, 0.0f, kCCRepeatForever, 0.0f); } void CCNode::schedule(SEL_SCHEDULE selector, float interval) { this->schedule(selector, interval, kCCRepeatForever, 0.0f); } void CCNode::schedule(SEL_SCHEDULE selector, float interval, unsigned int repeat, float delay) { CCAssert( selector, "Argument must be non-nil"); CCAssert( interval >=0, "Argument must be positive"); m_pScheduler->scheduleSelector(selector, this, interval , repeat, delay, !m_bRunning); } void CCNode::scheduleOnce(SEL_SCHEDULE selector, float delay) { this->schedule(selector, 0.0f, 0, delay); } void CCNode::unschedule(SEL_SCHEDULE selector) { // explicit nil handling if (selector == 0) return; m_pScheduler->unscheduleSelector(selector, this); } void CCNode::unscheduleAllSelectors() { m_pScheduler->unscheduleAllForTarget(this); } void CCNode::resumeSchedulerAndActions() { m_pScheduler->resumeTarget(this); m_pActionManager->resumeTarget(this); } void CCNode::pauseSchedulerAndActions() { m_pScheduler->pauseTarget(this); m_pActionManager->pauseTarget(this); } // override me void CCNode::update(float fDelta) { } CCAffineTransform CCNode::nodeToParentTransform(void) { if (m_bTransformDirty) { // Translate values float x = m_obPosition.x; float y = m_obPosition.y; if (m_bIgnoreAnchorPointForPosition) { x += m_obAnchorPointInPoints.x; y += m_obAnchorPointInPoints.y; } // Rotation values // Change rotation code to handle X and Y // If we skew with the exact same value for both x and y then we're simply just rotating float cx = 1, sx = 0, cy = 1, sy = 0; if (m_fRotationX || m_fRotationY) { float radiansX = -CC_DEGREES_TO_RADIANS(m_fRotationX); float radiansY = -CC_DEGREES_TO_RADIANS(m_fRotationY); cx = cosf(radiansX); sx = sinf(radiansX); cy = cosf(radiansY); sy = sinf(radiansY); } bool needsSkewMatrix = ( m_fSkewX || m_fSkewY ); // optimization: // inline anchor point calculation if skew is not needed // Adjusted transform calculation for rotational skew if (! needsSkewMatrix && !m_obAnchorPointInPoints.equals(CCPointZero)) { x += cy * -m_obAnchorPointInPoints.x * m_fScaleX + -sx * -m_obAnchorPointInPoints.y * m_fScaleY; y += sy * -m_obAnchorPointInPoints.x * m_fScaleX + cx * -m_obAnchorPointInPoints.y * m_fScaleY; } // Build Transform Matrix // Adjusted transform calculation for rotational skew m_sTransform = CCAffineTransformMake( cy * m_fScaleX, sy * m_fScaleX, -sx * m_fScaleY, cx * m_fScaleY, x, y ); // XXX: Try to inline skew // If skew is needed, apply skew and then anchor point if (needsSkewMatrix) { CCAffineTransform skewMatrix = CCAffineTransformMake(1.0f, tanf(CC_DEGREES_TO_RADIANS(m_fSkewY)), tanf(CC_DEGREES_TO_RADIANS(m_fSkewX)), 1.0f, 0.0f, 0.0f ); m_sTransform = CCAffineTransformConcat(skewMatrix, m_sTransform); // adjust anchor point if (!m_obAnchorPointInPoints.equals(CCPointZero)) { m_sTransform = CCAffineTransformTranslate(m_sTransform, -m_obAnchorPointInPoints.x, -m_obAnchorPointInPoints.y); } } m_bTransformDirty = false; } return m_sTransform; } CCAffineTransform CCNode::parentToNodeTransform(void) { if ( m_bInverseDirty ) { m_sInverse = CCAffineTransformInvert(this->nodeToParentTransform()); m_bInverseDirty = false; } return m_sInverse; } CCAffineTransform CCNode::nodeToWorldTransform() { CCAffineTransform t = this->nodeToParentTransform(); for (CCNode *p = m_pParent; p != NULL; p = p->getParent()) t = CCAffineTransformConcat(t, p->nodeToParentTransform()); return t; } CCAffineTransform CCNode::worldToNodeTransform(void) { return CCAffineTransformInvert(this->nodeToWorldTransform()); } CCPoint CCNode::convertToNodeSpace(const CCPoint& worldPoint) { CCPoint ret = CCPointApplyAffineTransform(worldPoint, worldToNodeTransform()); return ret; } CCPoint CCNode::convertToWorldSpace(const CCPoint& nodePoint) { CCPoint ret = CCPointApplyAffineTransform(nodePoint, nodeToWorldTransform()); return ret; } CCPoint CCNode::convertToNodeSpaceAR(const CCPoint& worldPoint) { CCPoint nodePoint = convertToNodeSpace(worldPoint); return ccpSub(nodePoint, m_obAnchorPointInPoints); } CCPoint CCNode::convertToWorldSpaceAR(const CCPoint& nodePoint) { CCPoint pt = ccpAdd(nodePoint, m_obAnchorPointInPoints); return convertToWorldSpace(pt); } CCPoint CCNode::convertToWindowSpace(const CCPoint& nodePoint) { CCPoint worldPoint = this->convertToWorldSpace(nodePoint); return CCDirector::sharedDirector()->convertToUI(worldPoint); } // convenience methods which take a CCTouch instead of CCPoint CCPoint CCNode::convertTouchToNodeSpace(CCTouch *touch) { CCPoint point = touch->getLocation(); return this->convertToNodeSpace(point); } CCPoint CCNode::convertTouchToNodeSpaceAR(CCTouch *touch) { CCPoint point = touch->getLocation(); return this->convertToNodeSpaceAR(point); } // MARMALADE ADDED void CCNode::updateTransform() { // Recursively iterate over children arrayMakeObjectsPerformSelector(m_pChildren, updateTransform, CCNode*); } NS_CC_END
23.076799
171
0.667519
nickflink
ba45aa35ad891de7f37766013ed7d0667ec66a28
2,808
cpp
C++
src/Externals/cleaver/test/backup/volumeMesh.cpp
benjaminlarson/SCIRunGUIPrototype
ed34ee11cda114e3761bd222a71a9f397517914d
[ "Unlicense" ]
1
2019-05-30T06:00:15.000Z
2019-05-30T06:00:15.000Z
src/Externals/cleaver/test/backup/volumeMesh.cpp
manual123/SCIRun
3816b1dc4ebd0c5bd4539b7e50e08592acdac903
[ "MIT" ]
null
null
null
src/Externals/cleaver/test/backup/volumeMesh.cpp
manual123/SCIRun
3816b1dc4ebd0c5bd4539b7e50e08592acdac903
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <string> #include <Cleaver/Cleaver.h> #include <Cleaver/InverseField.h> #include <Cleaver/FloatField.h> //#include "nrrd2cleaver.h" using namespace std; //using namespace Cleaver; const std::string scirun = "scirun"; const std::string tetgen = "tetgen"; const std::string matlab = "matlab"; int main(int argc, char *argv[]) { cerr<<"THIS IS VOLUMEMESH"<<endl; int dim_x=30; int dim_y=30; int dim_z=30; float v_x=1.0; float v_y=1.0; float v_z=1.0; bool verbose=true; string format="tetgen"; string outputFileName="meshOutput"; //vector<float> outsideVec(dim_x*dim_y*dim_x,0); vector<float> insideVec(dim_x*dim_y*dim_x,0.0); int idx=0; //filling volumetric mateiral definition - a sphere centered in the middle of the lattice for (int x = 0 ; x < dim_x ; ++x ){ for (int y = 0 ; y < dim_y ; ++y ){ for (int z = 0 ; z < dim_z ; ++z ){ if(x < 2 || y < 2 || z < 2 || x > (dim_x - 2) || y > (dim_y - 2) || z > (dim_z - 2)) { insideVec[idx]=1.0; ++idx; continue; } if ((x-dim_x/2)*(x-dim_x/2)+(y-dim_y/2)*(y-dim_y/2)+(z-dim_z/2)<0.4*dim_x){ insideVec[idx]=1.0; }else{ insideVec[idx]=0.0; //insideVec[idx]=1; //outsideVec[idx]=0; } std::cout << insideVec[idx] << std::endl; ++idx; } } } Cleaver::FloatField insideField=Cleaver::FloatField(dim_x,dim_y,dim_z,&insideVec[0]); //Cleaver::FloatField outsideField=Cleaver::FloatField(dim_x,dim_y,dim_z,&outsideVec[0]); Cleaver::InverseField inverseField=Cleaver::InverseField(&insideField); std::vector<Cleaver::ScalarField*> fields; fields.push_back(&insideField); fields.push_back(&inverseField); Cleaver::Volume volume(fields); Cleaver::TetMesh *mesh = Cleaver::createMeshFromVolume(volume, verbose); //------------------ // Compute Angles //------------------ mesh->computeAngles(); if(verbose){ std::cout.precision(12); std::cout << "Worst Angles:" << std::endl; std::cout << "min: " << mesh->min_angle << std::endl; std::cout << "max: " << mesh->max_angle << std::endl; } //---------------------- // Write Info File //---------------------- mesh->writeInfo(outputFileName, verbose); //---------------------- // Write Tet Mesh Files //---------------------- if(format == tetgen) mesh->writeNodeEle(outputFileName, verbose); else if(format == scirun) mesh->writePtsEle(outputFileName, verbose); else if(format == matlab) mesh->writeMatlab(outputFileName, verbose); //---------------------- // Write Surface Files //---------------------- mesh->constructFaces(); mesh->writePly(outputFileName, verbose); }
23.79661
90
0.573362
benjaminlarson
ba4927f2adf024b91af61bd4e846ebf82820fda0
3,643
cpp
C++
UTL/tokenbuf.cpp
yingtaohu/ogs5
3ebcbbc209e2306e0721d408a699ecaea52b89d1
[ "BSD-4-Clause" ]
1
2018-07-28T01:46:45.000Z
2018-07-28T01:46:45.000Z
UTL/tokenbuf.cpp
yingtaohu/ogs5
3ebcbbc209e2306e0721d408a699ecaea52b89d1
[ "BSD-4-Clause" ]
1
2016-08-03T14:13:54.000Z
2016-08-03T14:13:54.000Z
UTL/tokenbuf.cpp
yingtaohu/ogs5
3ebcbbc209e2306e0721d408a699ecaea52b89d1
[ "BSD-4-Clause" ]
2
2016-06-27T15:30:02.000Z
2021-06-15T08:30:31.000Z
/** * \copyright * Copyright (c) 2015, OpenGeoSys Community (http://www.opengeosys.org) * Distributed under a Modified BSD License. * See accompanying file LICENSE.txt or * http://www.opengeosys.org/project/license * */ #include <iostream> #include <string> #include "tokenbuf.h" TokenBuf::TokenBuf(std::istream& stream, int internal_buf_size) : input_stream(stream), buf_max_size(internal_buf_size), buf_read_pos(0), buf_num_bytes(0), last_token_valid(false) { buf = new char[buf_max_size]; } TokenBuf::~TokenBuf() { delete[] buf; } bool TokenBuf::done() { if ((buf_read_pos == buf_num_bytes && !last_token_valid && input_stream.eof()) || input_stream.bad()) return true; else return false; } void TokenBuf::readBuf() { buf_read_pos = 0; input_stream.read(buf, buf_max_size); buf_num_bytes = input_stream.gcount(); } void TokenBuf::getNextToken(bool ignore_line_break) { int i; bool got_it = false; int status = 0; last_token = ""; // Skip non token characters while (status == 0) { for (i = buf_read_pos; i < buf_num_bytes; i++, buf_read_pos++) if ((buf[i] != ' ' && buf[i] != '\t')) { if (ignore_line_break) { if (buf[i] != '\r' && buf[i] != '\n') { status = 1; break; } } else { status = 1; break; } } if (status == 0) { if (input_stream.eof()) status = 4; readBuf(); if (input_stream.bad()) status = 255; } } // And copy token characters to 'last_token' if (!ignore_line_break && (buf[buf_read_pos] == '\r' || buf[buf_read_pos] == '\n')) { last_token += buf[buf_read_pos]; buf_read_pos++; status = 2; } while (status == 1) { for (i = buf_read_pos; i < buf_num_bytes; i++, buf_read_pos++) { if (buf[i] != ' ' && buf[i] != '\t' && buf[i] != '\r' && buf[i] != '\n') { printf("%d ", buf[i]); last_token += buf[i]; } else { status = 2; break; } } if (status == 1) { if (input_stream.eof()) status = 4; readBuf(); if (input_stream.bad()) status = 255; } } if (status == 2) last_token_valid = true; } TokenBuf::Types TokenBuf::type() { Types rv; int i; int status; return NONE; } std::string TokenBuf::peek(bool ignore_line_break) { int i; if (!last_token_valid) { getNextToken(ignore_line_break); last_token_valid = true; } return last_token; } std::string TokenBuf::consume(bool ignore_line_break) { std::string rv; if (last_token_valid) rv = last_token; else rv = peek(ignore_line_break); last_token_valid = false; return rv; } void TokenBuf::getline(char* linebuf, int max_num) { int i, pos; bool reading = true; pos = 0; if (last_token_valid) { if (last_token[0] != '\n' && last_token[0] != '\r') { for (i = 0; i < last_token.size() && i < max_num - 1; i++) linebuf[i] = last_token[i]; pos = i; } last_token_valid = false; } // If there is a rest of input buffer handle that first... do { for (i = buf_read_pos; i < buf_num_bytes && pos < max_num - 1; i++) { if (buf[i] != '\r' && buf[i] != '\n') { linebuf[pos] = buf[i]; pos++; } else { reading = false; break; } } buf_read_pos = i + 1; if (reading) { readBuf(); reading = !done(); } } while (reading); linebuf[pos] = '\0'; } bool TokenBuf::get_non_empty_line(char* linebuf, int max_num) { bool valid = true; if (!done()) { do { getline(linebuf, max_num); } while (!done() && linebuf[0] == '\0'); valid = (!input_stream.bad()) && linebuf[0] != '\0'; } else valid = false; return valid; }
16.484163
119
0.582212
yingtaohu
ba4b2ca0da77241e930f6524dd8cc66a92faa3b6
765
cpp
C++
Short Notes/dataTypes.cpp
Darklaneanjana/Cpp-programming
bd00e402f51877c7b62b508f9125fb2436a04806
[ "MIT" ]
19
2021-04-28T13:32:15.000Z
2022-03-08T11:52:59.000Z
Short Notes/dataTypes.cpp
Darklaneanjana/Cpp-programming
bd00e402f51877c7b62b508f9125fb2436a04806
[ "MIT" ]
5
2021-03-03T08:06:15.000Z
2021-12-26T18:14:45.000Z
Short Notes/dataTypes.cpp
Darklaneanjana/Cpp-programming
bd00e402f51877c7b62b508f9125fb2436a04806
[ "MIT" ]
27
2021-01-18T22:35:01.000Z
2022-02-22T19:52:19.000Z
#include <iostream> int main () { // std::cout << "LuciferX" << std::endl; // Numerical Data Types // int i = 10; // Size = 4 // short int j = 20; // Size = 2 // long int k = 300; // std::cout << "Integer (int) : " << sizeof(int) << std::endl; // // unsigned short s = 65535; // +0 to +65535 // signed short t = 32767; // -32768 to + 32767 // std::cout << s << " " << t << std::endl; // float i = 60.75; // double j = 90.876512; // long double k = 9.1867548967; // std::cout << i << std::endl; // Textual Data Types // char c = 'A'; // char d = 97; // std::cout << c << d << std::endl; // // std::string s = "LuciferX"; // std::cout << s << std::endl; // Boolean // bool t = true; // Output: 1 // std::cout << t << std::endl; return 0; }
18.658537
63
0.509804
Darklaneanjana
ba54bf372e58b0c7b39e1752323331fd7bab8a9e
3,184
cc
C++
modules/prediction/submodules/predictor_submodule.cc
Inertial-Labs/apollo
1c101673a85ab69981b85952fb1dd52acde1ccbd
[ "Apache-2.0" ]
1
2018-09-13T03:37:20.000Z
2018-09-13T03:37:20.000Z
modules/prediction/submodules/predictor_submodule.cc
Inertial-Labs/apollo
1c101673a85ab69981b85952fb1dd52acde1ccbd
[ "Apache-2.0" ]
1
2018-10-30T05:53:11.000Z
2018-10-30T05:53:11.000Z
modules/prediction/submodules/predictor_submodule.cc
Inertial-Labs/apollo
1c101673a85ab69981b85952fb1dd52acde1ccbd
[ "Apache-2.0" ]
null
null
null
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/prediction/submodules/predictor_submodule.h" #include <utility> #include "modules/common/adapters/adapter_gflags.h" #include "modules/common/adapters/proto/adapter_config.pb.h" #include "modules/common/time/time.h" #include "modules/common/util/message_util.h" #include "modules/prediction/common/prediction_system_gflags.h" #include "modules/prediction/predictor/predictor_manager.h" namespace apollo { namespace prediction { using apollo::common::time::Clock; PredictorSubmodule::~PredictorSubmodule() {} std::string PredictorSubmodule::Name() const { return FLAGS_evaluator_submodule_name; } bool PredictorSubmodule::Init() { if (!MessageProcess::InitPredictors()) { return false; } predictor_writer_ = node_->CreateWriter<PredictionObstacles>(FLAGS_prediction_topic); return true; } bool PredictorSubmodule::Proc( const std::shared_ptr<ADCTrajectoryContainer>& adc_trajectory_container, const std::shared_ptr<EvaluatorOutput>& evaluator_output) { const apollo::common::Header& perception_header = evaluator_output->submodule_output().perception_header(); const apollo::common::ErrorCode& perception_error_code = evaluator_output->submodule_output().perception_error_code(); const double frame_start_time = evaluator_output->submodule_output().frame_start_time(); ObstaclesContainer obstacles_container(evaluator_output->submodule_output()); PredictorManager::Instance()->Run(adc_trajectory_container.get(), &obstacles_container); PredictionObstacles prediction_obstacles = PredictorManager::Instance()->prediction_obstacles(); prediction_obstacles.set_end_timestamp(Clock::NowInSeconds()); prediction_obstacles.mutable_header()->set_lidar_timestamp( perception_header.lidar_timestamp()); prediction_obstacles.mutable_header()->set_camera_timestamp( perception_header.camera_timestamp()); prediction_obstacles.mutable_header()->set_radar_timestamp( perception_header.radar_timestamp()); prediction_obstacles.set_perception_error_code(perception_error_code); prediction_obstacles.set_start_timestamp(frame_start_time); common::util::FillHeader(node_->Name(), &prediction_obstacles); predictor_writer_->Write( std::make_shared<PredictionObstacles>(prediction_obstacles)); return true; } } // namespace prediction } // namespace apollo
38.829268
79
0.735867
Inertial-Labs
ba59c30d0d0a2af9ced28e264d53e6ab5ba15a1f
14,004
cpp
C++
src/lunar-master/eart2000.cpp
TehSnappy/lib_lunar_ex
a4cd4a3cdec44c2adaefbf1791b8863db568cbbd
[ "MIT" ]
1
2019-03-11T14:46:04.000Z
2019-03-11T14:46:04.000Z
lib/net/src/nrun/astro/eart2000.cpp
lcityd/paragon
47a43872a5656a8c431c774d353ed214f9d0ed1d
[ "MIT" ]
null
null
null
lib/net/src/nrun/astro/eart2000.cpp
lcityd/paragon
47a43872a5656a8c431c774d353ed214f9d0ed1d
[ "MIT" ]
1
2019-10-12T03:23:41.000Z
2019-10-12T03:23:41.000Z
/* eart2000.cpp: functions for computing Earth coordinates Copyright (C) 2010, Project Pluto This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <math.h> /* EART2000.CPP This computes a heliocentric J2000 position of the Earth, using the VSOP theory. I don't use it very often, since the VSOP theory for all the planets is given in the file VSOP.BIN on the Guide CD-ROM. (This is the truncated VSOP used in Meeus' _Astronomical Algorithms_. The full VSOP is in BIG_VSOP.BIN.) The input is a time in millennia from J2000 = JD 2451545. The output fills an array of six doubles with the X, Y, Z, ecliptic longitude, ecliptic latitude, and distance, all in J2000 coords. */ int get_earth_loc( const double t_millennia, double *results); static const int count[18] = {64, 34, 20, 7, 2, 0, /* 127 */ 5, 7, 4, 3, 2, 0, /* +21 = 148 */ 40, 10, 6, 2, 1, 0}; /* +59 = 207 */ static const double coeffs[207 * 3] = { 175347046., 0.000000000, 0.000000000, 3341656., 4.669256804, 6283.075849991, 34894., 4.626102422, 12566.151699983, 3497., 2.744117834, 5753.384884897, 3418., 2.828865798, 3.523118349, 3136., 3.627670418, 77713.771468121, 2676., 4.418083454, 7860.419392439, 2343., 6.135162144, 3930.209696220, 1324., 0.742463417, 11506.769769794, 1273., 2.037096579, 529.690965095, 1199., 1.109629462, 1577.343542448, 990., 5.232680721, 5884.926846583, 902., 2.045054465, 26.298319800, 857., 3.508491523, 398.149003408, 780., 1.178826820, 5223.693919802, 753., 2.533390528, 5507.553238667, 505., 4.582926000, 18849.227549974, 492., 4.205057118, 775.522611324, 357., 2.919541145, 0.067310303, 317., 5.849019485, 11790.629088659, 284., 1.898692409, 796.298006816, 271., 0.314862554, 10977.078804699, 243., 0.344814459, 5486.777843175, 206., 4.806466315, 2544.314419883, 205., 1.869537703, 5573.142801433, 202., 2.457677902, 6069.776754553, 156., 0.833060846, 213.299095438, 132., 3.411182927, 2942.463423292, 126., 1.082954595, 20.775395492, 115., 0.645449117, 0.980321068, 103., 0.635998456, 4694.002954708, 102., 0.975692803, 15720.838784878, 102., 4.266798020, 7.113547001, 99., 6.209929269, 2146.165416475, 98., 0.681013424, 155.420399434, 86., 5.983226313, 161000.685737674, 85., 1.298707648, 6275.962302991, 85., 3.670800930, 71430.695618129, 80., 1.807912871, 17260.154654690, 79., 3.036974587, 12036.460734888, 75., 1.755089133, 5088.628839767, 74., 3.503194150, 3154.687084896, 74., 4.679266339, 801.820931124, 70., 0.832976214, 9437.762934887, 62., 3.977639128, 8827.390269875, 61., 1.818398930, 7084.896781115, 57., 2.784304586, 6286.598968340, 56., 4.386948654, 14143.495242431, 56., 3.470060599, 6279.552731642, 52., 0.189149472, 12139.553509107, 52., 1.332827399, 1748.016413067, 51., 0.283068329, 5856.477659115, 49., 0.487350142, 1194.447010225, 41., 5.368175929, 8429.241266467, 41., 2.398509387, 19651.048481098, 39., 6.168330210, 10447.387839604, 37., 6.041338632, 10213.285546211, 37., 2.569574818, 1059.381930189, 36., 1.708758088, 2352.866153772, 36., 1.775968892, 6812.766815086, 33., 0.593102786, 17789.845619785, 30., 0.442944642, 83996.847318112, 30., 2.739751241, 1349.867409659, 25., 3.164708917, 4690.479836359, 628307584999., 0.000000000, 0.000000000, 206059., 2.678234558, 6283.075849991, 4303., 2.635122335, 12566.151699983, 425., 1.590469820, 3.523118349, 119., 5.795557656, 26.298319800, 109., 2.966310107, 1577.343542448, 93., 2.592111095, 18849.227549974, 72., 1.138405812, 529.690965095, 68., 1.874533003, 398.149003408, 67., 4.409328320, 5507.553238667, 59., 2.888157906, 5223.693919802, 56., 2.174717400, 155.420399434, 45., 0.397995029, 796.298006816, 36., 0.468754372, 775.522611324, 29., 2.647322546, 7.113547001, 21., 5.341382751, 0.980321068, 19., 1.846283760, 5486.777843175, 19., 4.968551795, 213.299095438, 17., 2.991167606, 6275.962302991, 16., 0.032165873, 2544.314419883, 16., 1.430493013, 2146.165416475, 15., 1.204697937, 10977.078804699, 12., 2.834322821, 1748.016413067, 12., 3.258050820, 5088.628839767, 12., 5.273797604, 1194.447010225, 12., 2.075020801, 4694.002954708, 11., 0.766147230, 553.569402842, 10., 1.302634234, 6286.598968340, 10., 4.239258653, 1349.867409659, 9., 2.699568270, 242.728603974, 9., 5.644760860, 951.718406251, 8., 5.300561729, 2352.866153772, 6., 2.650345140, 9437.762934887, 6., 4.666337263, 4690.479836359, 8722., 1.072536356, 6283.075849991, 991., 3.141592654, 0.000000000, 295., 0.437173503, 12566.151699983, 27., 0.052956361, 3.523118349, 16., 5.188202157, 26.298319800, 16., 3.685047122, 155.420399434, 9., 0.296671147, 18849.227549974, 9., 2.057063196, 77713.771468121, 7., 0.826915410, 775.522611324, 5., 4.662432317, 1577.343542448, 4., 1.030670323, 7.113547001, 4., 3.440433695, 5573.142801433, 3., 5.140212246, 796.298006816, 3., 6.054793185, 5507.553238667, 3., 1.192400085, 242.728603974, 3., 6.117058654, 529.690965095, 3., 0.303632482, 398.149003408, 3., 2.279664343, 553.569402842, 2., 4.376661180, 5223.693919802, 2., 3.754350955, 0.980321068, 289., 5.841731497, 6283.075849991, 21., 6.049839390, 12566.151699983, 3., 5.195605796, 155.420399434, 3., 3.141592654, 0.000000000, 1., 4.721976120, 3.523118349, 1., 5.969048992, 242.728603974, 1., 5.541829032, 18849.227549974, 8., 4.141173214, 6283.075849991, 1., 3.275736442, 12566.151699983, 280., 3.198701560, 84334.661581308, 102., 5.422486193, 5507.553238667, 80., 3.880132045, 5223.693919802, 44., 3.704446898, 2352.866153772, 32., 4.000263698, 1577.343542448, 227778., 3.413766205, 6283.075849991, 3806., 3.370634238, 12566.151699983, 3620., 0.000000000, 0.000000000, 72., 3.327775497, 18849.227549974, 8., 3.891904036, 5507.553238667, 8., 1.794896072, 5223.693919802, 6., 5.197894248, 2352.866153772, 9721., 5.151928099, 6283.075849991, 233., 3.141592654, 0.000000000, 134., 0.644062130, 12566.151699983, 7., 1.073333978, 18849.227549974, 276., 0.594800971, 6283.075849991, 17., 3.141592654, 0.000000000, 4., 0.117505753, 12566.151699983, 6., 2.267340298, 6283.075849991, 1., 0.000000000, 0.000000000, 100013989., 0.000000000, 0.000000000, 1670700., 3.098463503, 6283.075849991, 13956., 3.055246095, 12566.151699983, 3084., 5.198466744, 77713.771468121, 1628., 1.173875581, 5753.384884897, 1576., 2.846852149, 7860.419392439, 925., 5.452922367, 11506.769769794, 542., 4.564091515, 3930.209696220, 472., 3.661000221, 5884.926846583, 346., 0.963686273, 5507.553238667, 329., 5.899836861, 5223.693919802, 307., 0.298671395, 5573.142801433, 243., 4.273495308, 11790.629088659, 212., 5.847144613, 1577.343542448, 186., 5.021997107, 10977.078804699, 175., 3.011936367, 18849.227549974, 110., 5.055106359, 5486.777843175, 98., 0.886813113, 6069.776754553, 87., 5.689564189, 15720.838784878, 86., 1.270791253, 161000.685737674, 65., 0.272513414, 17260.154654690, 63., 0.921770540, 529.690965095, 57., 2.013742922, 83996.847318112, 56., 5.241597992, 71430.695618129, 49., 3.245012404, 2544.314419883, 47., 2.577998532, 775.522611324, 45., 5.537156638, 9437.762934887, 43., 6.011102580, 6275.962302991, 39., 5.360638329, 4694.002954708, 38., 2.392553440, 8827.390269875, 37., 0.829612818, 19651.048481098, 37., 4.901075873, 12139.553509107, 36., 1.674471358, 12036.460734888, 35., 1.842706933, 2942.463423292, 33., 0.243702217, 7084.896781115, 32., 0.183682999, 5088.628839767, 32., 1.777756421, 398.149003408, 28., 1.213448875, 6286.598968340, 28., 1.899344278, 6279.552731642, 26., 4.588968631, 10447.387839604, 103019., 1.107489682, 6283.075849991, 1721., 1.064423004, 12566.151699983, 702., 3.141592654, 0.000000000, 32., 1.021685833, 18849.227549974, 31., 2.843584440, 5507.553238667, 25., 1.319065703, 5223.693919802, 18., 1.424287091, 1577.343542448, 10., 5.913852484, 10977.078804699, 9., 1.420468544, 6275.962302991, 9., 0.271581929, 5486.777843175, 4359., 5.784551338, 6283.075849991, 124., 5.579354280, 12566.151699983, 12., 3.141592654, 0.000000000, 9., 3.627778931, 77713.771468121, 6., 1.869589051, 5573.142801433, 3., 5.470348797, 18849.227549974, 145., 4.273194339, 6283.075849991, 7., 3.917062617, 12566.151699983, 4., 2.563890163, 6283.075849991 }; int get_earth_loc( const double t_millennia, double *results) { int i, j, k; double const *tptr = coeffs; double power, sum; double val[3]; for( i = 0; i < 3; i++) { val[i] = 0; power = 1.; for( j = 0; j < 6; j++) { sum = 0.; for( k = 0; k < count[j + i * 6]; k++, tptr += 3) sum += tptr[0] * cos( tptr[1] + tptr[2] * t_millennia); val[i] += sum * power; power *= t_millennia; } val[i] *= 1.e-8; } *results++ = val[2] * cos( val[0]) * cos( val[1]); *results++ = val[2] * sin( val[0]) * cos( val[1]); *results++ = val[2] * sin( val[1]); *results++ = val[0]; *results++ = val[1]; *results++ = val[2]; return( 0); }
50.193548
70
0.479506
TehSnappy
ba5a5bd0ffd3d2c69cd341fd78272f02cd76f043
21,406
cpp
C++
test/crypto/test_webauthn.cpp
celes-dev/fc
0732c19245fad322b8785f9d43efda2117066490
[ "MIT" ]
37
2018-06-14T07:17:36.000Z
2022-02-18T18:03:42.000Z
test/crypto/test_webauthn.cpp
celes-dev/fc
0732c19245fad322b8785f9d43efda2117066490
[ "MIT" ]
36
2018-07-14T16:18:20.000Z
2021-12-24T01:45:26.000Z
test/crypto/test_webauthn.cpp
celes-dev/fc
0732c19245fad322b8785f9d43efda2117066490
[ "MIT" ]
131
2017-05-31T02:15:02.000Z
2022-03-23T12:19:35.000Z
#define BOOST_TEST_MODULE webauthn_test_mod #include <boost/test/included/unit_test.hpp> #include <boost/algorithm/string.hpp> #include <fc/crypto/public_key.hpp> #include <fc/crypto/private_key.hpp> #include <fc/crypto/signature.hpp> #include <fc/utility.hpp> using namespace fc::crypto; using namespace fc; using namespace std::literals; static fc::crypto::webauthn::signature make_webauthn_sig(const fc::crypto::r1::private_key& priv_key, std::vector<uint8_t>& auth_data, const std::string& json) { //webauthn signature is sha256(auth_data || client_data_hash) fc::sha256 client_data_hash = fc::sha256::hash(json); fc::sha256::encoder e; e.write((char*)auth_data.data(), auth_data.size()); e.write(client_data_hash.data(), client_data_hash.data_size()); r1::compact_signature sig = priv_key.sign_compact(e.result()); char buff[8192]; datastream<char*> ds(buff, sizeof(buff)); fc::raw::pack(ds, sig); fc::raw::pack(ds, auth_data); fc::raw::pack(ds, json); ds.seekp(0); fc::crypto::webauthn::signature ret; fc::raw::unpack(ds, ret); return ret; } //used for many below static const r1::private_key priv = fc::crypto::r1::private_key::generate(); static const r1::public_key pub = priv.get_public_key(); static const fc::sha256 d = fc::sha256::hash("sup"s); static const fc::sha256 origin_hash = fc::sha256::hash("fctesting.invalid"s); BOOST_AUTO_TEST_SUITE(webauthn_suite) //Good signature BOOST_AUTO_TEST_CASE(good) try { webauthn::public_key wa_pub(pub.serialize(), webauthn::public_key::user_presence_t::USER_PRESENCE_NONE, "fctesting.invalid"); std::string json = "{\"origin\":\"https://fctesting.invalid\",\"type\":\"webauthn.get\",\"challenge\":\"" + fc::base64url_encode(d.data(), d.data_size()) + "\"}"; std::vector<uint8_t> auth_data(37); memcpy(auth_data.data(), origin_hash.data(), sizeof(origin_hash)); BOOST_CHECK_EQUAL(wa_pub, make_webauthn_sig(priv, auth_data, json).recover(d, true)); } FC_LOG_AND_RETHROW(); //A valid signature but shouldn't match public key due to presence difference BOOST_AUTO_TEST_CASE(mismatch_presence) try { webauthn::public_key wa_pub(pub.serialize(), webauthn::public_key::user_presence_t::USER_PRESENCE_PRESENT, "fctesting.invalid"); std::string json = "{\"origin\":\"https://fctesting.invalid\",\"type\":\"webauthn.get\",\"challenge\":\"" + fc::base64url_encode(d.data(), d.data_size()) + "\"}"; std::vector<uint8_t> auth_data(37); memcpy(auth_data.data(), origin_hash.data(), sizeof(origin_hash)); auth_data[32] |= 0x04; //User presence verified BOOST_CHECK_NE(wa_pub, make_webauthn_sig(priv, auth_data, json).recover(d, true)); } FC_LOG_AND_RETHROW(); //A valid signature but shouldn't match public key due to origin difference BOOST_AUTO_TEST_CASE(mismatch_origin) try { webauthn::public_key wa_pub(pub.serialize(), webauthn::public_key::user_presence_t::USER_PRESENCE_PRESENT, "fctesting.invalid"); std::string json = "{\"origin\":\"https://mallory.invalid\",\"type\":\"webauthn.get\",\"challenge\":\"" + fc::base64url_encode(d.data(), d.data_size()) + "\"}"; std::vector<uint8_t> auth_data(37); fc::sha256 mallory_origin_hash = fc::sha256::hash("mallory.invalid"s); memcpy(auth_data.data(), mallory_origin_hash.data(), sizeof(mallory_origin_hash)); BOOST_CHECK_NE(wa_pub, make_webauthn_sig(priv, auth_data, json).recover(d, true)); } FC_LOG_AND_RETHROW(); //A valid signature but shouldn't recover because http was in use instead of https BOOST_AUTO_TEST_CASE(non_https) try { webauthn::public_key wa_pub(pub.serialize(), webauthn::public_key::user_presence_t::USER_PRESENCE_NONE, "fctesting.invalid"); std::string json = "{\"origin\":\"http://fctesting.invalid\",\"type\":\"webauthn.get\",\"challenge\":\"" + fc::base64url_encode(d.data(), d.data_size()) + "\"}"; std::vector<uint8_t> auth_data(37); memcpy(auth_data.data(), origin_hash.data(), sizeof(origin_hash)); BOOST_CHECK_EXCEPTION(make_webauthn_sig(priv, auth_data, json).recover(d, true), fc::assert_exception, [](const fc::assert_exception& e) { return e.to_detail_string().find("webauthn origin must begin with https://") != std::string::npos; }); } FC_LOG_AND_RETHROW(); //A valid signature but shouldn't recover because there is no origin scheme BOOST_AUTO_TEST_CASE(lacking_scheme) try { webauthn::public_key wa_pub(pub.serialize(), webauthn::public_key::user_presence_t::USER_PRESENCE_NONE, "fctesting.invalid"); std::string json = "{\"origin\":\"fctesting.invalid\",\"type\":\"webauthn.get\",\"challenge\":\"" + fc::base64url_encode(d.data(), d.data_size()) + "\"}"; std::vector<uint8_t> auth_data(37); memcpy(auth_data.data(), origin_hash.data(), sizeof(origin_hash)); BOOST_CHECK_EXCEPTION(make_webauthn_sig(priv, auth_data, json).recover(d, true), fc::assert_exception, [](const fc::assert_exception& e) { return e.to_detail_string().find("webauthn origin must begin with https://") != std::string::npos; }); } FC_LOG_AND_RETHROW(); //A valid signature but shouldn't recover because empty origin BOOST_AUTO_TEST_CASE(empty_origin) try { webauthn::public_key wa_pub(pub.serialize(), webauthn::public_key::user_presence_t::USER_PRESENCE_NONE, "fctesting.invalid"); std::string json = "{\"origin\":\"\",\"type\":\"webauthn.get\",\"challenge\":\"" + fc::base64url_encode(d.data(), d.data_size()) + "\"}"; std::vector<uint8_t> auth_data(37); memcpy(auth_data.data(), origin_hash.data(), sizeof(origin_hash)); BOOST_CHECK_EXCEPTION(make_webauthn_sig(priv, auth_data, json).recover(d, true), fc::assert_exception, [](const fc::assert_exception& e) { return e.to_detail_string().find("webauthn origin must begin with https://") != std::string::npos; }); } FC_LOG_AND_RETHROW(); //Good signature with a port BOOST_AUTO_TEST_CASE(good_port) try { webauthn::public_key wa_pub(pub.serialize(), webauthn::public_key::user_presence_t::USER_PRESENCE_NONE, "fctesting.invalid"); std::string json = "{\"origin\":\"https://fctesting.invalid:123456\",\"type\":\"webauthn.get\",\"challenge\":\"" + fc::base64url_encode(d.data(), d.data_size()) + "\"}"; std::vector<uint8_t> auth_data(37); memcpy(auth_data.data(), origin_hash.data(), sizeof(origin_hash)); BOOST_CHECK_EQUAL(wa_pub, make_webauthn_sig(priv, auth_data, json).recover(d, true)); } FC_LOG_AND_RETHROW(); //Good signature with an empty port BOOST_AUTO_TEST_CASE(empty_port) try { webauthn::public_key wa_pub(pub.serialize(), webauthn::public_key::user_presence_t::USER_PRESENCE_NONE, "fctesting.invalid"); std::string json = "{\"origin\":\"https://fctesting.invalid:\",\"type\":\"webauthn.get\",\"challenge\":\"" + fc::base64url_encode(d.data(), d.data_size()) + "\"}"; std::vector<uint8_t> auth_data(37); memcpy(auth_data.data(), origin_hash.data(), sizeof(origin_hash)); BOOST_CHECK_EQUAL(wa_pub, make_webauthn_sig(priv, auth_data, json).recover(d, true)); } FC_LOG_AND_RETHROW(); //valid signature but with misc junk in challenge BOOST_AUTO_TEST_CASE(challenge_junk) try { webauthn::public_key wa_pub(pub.serialize(), webauthn::public_key::user_presence_t::USER_PRESENCE_NONE, "fctesting.invalid"); std::string json = "{\"origin\":\"https://fctesting.invalid\",\"type\":\"webauthn.get\",\"challenge\":\"" + "blahBLAH"s + "\"}"; std::vector<uint8_t> auth_data(37); memcpy(auth_data.data(), origin_hash.data(), sizeof(origin_hash)); BOOST_CHECK_EXCEPTION(make_webauthn_sig(priv, auth_data, json).recover(d, true), fc::exception, [](const fc::exception& e) { return e.to_detail_string().find("sha256: size mismatch") != std::string::npos; }); } FC_LOG_AND_RETHROW(); //valid signature but with non base64 in challenge BOOST_AUTO_TEST_CASE(challenge_non_base64) try { webauthn::public_key wa_pub(pub.serialize(), webauthn::public_key::user_presence_t::USER_PRESENCE_NONE, "fctesting.invalid"); std::string json = "{\"origin\":\"https://fctesting.invalid\",\"type\":\"webauthn.get\",\"challenge\":\"" + "hello@world$"s + "\"}"; std::vector<uint8_t> auth_data(37); memcpy(auth_data.data(), origin_hash.data(), sizeof(origin_hash)); BOOST_CHECK_EXCEPTION(make_webauthn_sig(priv, auth_data, json).recover(d, true), fc::exception, [](const fc::exception& e) { return e.to_detail_string().find("encountered non-base64 character") != std::string::npos; }); } FC_LOG_AND_RETHROW(); //valid signature but with some other digest in the challenge that is not the one we are recovering from BOOST_AUTO_TEST_CASE(challenge_wrong) try { webauthn::public_key wa_pub(pub.serialize(), webauthn::public_key::user_presence_t::USER_PRESENCE_NONE, "fctesting.invalid"); fc::sha256 other_digest = fc::sha256::hash("yo"s); std::string json = "{\"origin\":\"https://fctesting.invalid\",\"type\":\"webauthn.get\",\"challenge\":\"" + fc::base64url_encode(other_digest.data(), other_digest.data_size()) + "\"}"; std::vector<uint8_t> auth_data(37); memcpy(auth_data.data(), origin_hash.data(), sizeof(origin_hash)); BOOST_CHECK_EXCEPTION(make_webauthn_sig(priv, auth_data, json).recover(d, true), fc::assert_exception, [](const fc::assert_exception& e) { return e.to_detail_string().find("Wrong webauthn challenge") != std::string::npos; }); } FC_LOG_AND_RETHROW(); //valid signature but wrong webauthn type BOOST_AUTO_TEST_CASE(wrong_type) try { webauthn::public_key wa_pub(pub.serialize(), webauthn::public_key::user_presence_t::USER_PRESENCE_NONE, "fctesting.invalid"); std::string json = "{\"origin\":\"https://fctesting.invalid\",\"type\":\"webauthn.meh\",\"challenge\":\"" + fc::base64url_encode(d.data(), d.data_size()) + "\"}"; std::vector<uint8_t> auth_data(37); memcpy(auth_data.data(), origin_hash.data(), sizeof(origin_hash)); BOOST_CHECK_EXCEPTION(make_webauthn_sig(priv, auth_data, json).recover(d, true), fc::assert_exception, [](const fc::assert_exception& e) { return e.to_detail_string().find("webauthn signature type not an assertion") != std::string::npos; }); } FC_LOG_AND_RETHROW(); //signature if good but the auth_data rpid hash is not what is expected for origin BOOST_AUTO_TEST_CASE(auth_data_rpid_hash_bad) try { webauthn::public_key wa_pub(pub.serialize(), webauthn::public_key::user_presence_t::USER_PRESENCE_NONE, "fctesting.invalid"); std::string json = "{\"origin\":\"https://fctesting.invalid\",\"type\":\"webauthn.get\",\"challenge\":\"" + fc::base64url_encode(d.data(), d.data_size()) + "\"}"; std::vector<uint8_t> auth_data(37); fc::sha256 origin_hash_corrupt = fc::sha256::hash("fctesting.invalid"s); memcpy(auth_data.data(), origin_hash_corrupt.data(), sizeof(origin_hash_corrupt)); auth_data[4]++; BOOST_CHECK_EXCEPTION(make_webauthn_sig(priv, auth_data, json).recover(d, true), fc::assert_exception, [](const fc::assert_exception& e) { return e.to_detail_string().find("webauthn rpid hash doesn't match origin") != std::string::npos; }); } FC_LOG_AND_RETHROW(); //signature if good but auth_data too short to store what needs to be stored BOOST_AUTO_TEST_CASE(auth_data_too_short) try { webauthn::public_key wa_pub(pub.serialize(), webauthn::public_key::user_presence_t::USER_PRESENCE_NONE, "fctesting.invalid"); std::string json = "{\"origin\":\"https://fctesting.invalid\",\"type\":\"webauthn.get\",\"challenge\":\"" + fc::base64url_encode(d.data(), d.data_size()) + "\"}"; std::vector<uint8_t> auth_data(1); BOOST_CHECK_EXCEPTION(make_webauthn_sig(priv, auth_data, json).recover(d, true), fc::assert_exception, [](const fc::assert_exception& e) { return e.to_detail_string().find("auth_data not as large as required") != std::string::npos; }); } FC_LOG_AND_RETHROW(); //Good signature but missing origin completely BOOST_AUTO_TEST_CASE(missing_origin) try { webauthn::public_key wa_pub(pub.serialize(), webauthn::public_key::user_presence_t::USER_PRESENCE_NONE, "fctesting.invalid"); std::string json = "{\"type\":\"webauthn.get\",\"challenge\":\"" + fc::base64url_encode(d.data(), d.data_size()) + "\"}"; std::vector<uint8_t> auth_data(37); memcpy(auth_data.data(), origin_hash.data(), sizeof(origin_hash)); BOOST_CHECK_EXCEPTION(make_webauthn_sig(priv, auth_data, json).recover(d, true), fc::assert_exception, [](const fc::assert_exception& e) { return e.to_detail_string().find("webauthn origin must begin with https://") != std::string::npos; }); } FC_LOG_AND_RETHROW(); //Good signature but missing type completely BOOST_AUTO_TEST_CASE(missing_type) try { webauthn::public_key wa_pub(pub.serialize(), webauthn::public_key::user_presence_t::USER_PRESENCE_NONE, "fctesting.invalid"); std::string json = "{\"origin\":\"https://fctesting.invalid\",\"challenge\":\"" + fc::base64url_encode(d.data(), d.data_size()) + "\"}"; std::vector<uint8_t> auth_data(37); memcpy(auth_data.data(), origin_hash.data(), sizeof(origin_hash)); BOOST_CHECK_EXCEPTION(make_webauthn_sig(priv, auth_data, json).recover(d, true), fc::assert_exception, [](const fc::assert_exception& e) { return e.to_detail_string().find("webauthn signature type not an assertion") != std::string::npos; }); } FC_LOG_AND_RETHROW(); //Good signature but missing challenge completely BOOST_AUTO_TEST_CASE(missing_challenge) try { webauthn::public_key wa_pub(pub.serialize(), webauthn::public_key::user_presence_t::USER_PRESENCE_NONE, "fctesting.invalid"); std::string json = "{\"origin\":\"https://fctesting.invalid\",\"type\":\"webauthn.get\"}"; std::vector<uint8_t> auth_data(37); memcpy(auth_data.data(), origin_hash.data(), sizeof(origin_hash)); BOOST_CHECK_EXCEPTION(make_webauthn_sig(priv, auth_data, json).recover(d, true), fc::exception, [](const fc::exception& e) { return e.to_detail_string().find("sha256: size mismatch") != std::string::npos; }); } FC_LOG_AND_RETHROW(); //Good signature with some extra stuff sprinkled in the json BOOST_AUTO_TEST_CASE(good_extrajunk) try { webauthn::public_key wa_pub(pub.serialize(), webauthn::public_key::user_presence_t::USER_PRESENCE_NONE, "fctesting.invalid"); std::string json = "{\"origin\":\"https://fctesting.invalid\",\"cool\":\"beans\",\"obj\":{\"array\":[4, 5, 6]}," "\"type\":\"webauthn.get\",\"answer\": 42 ,\"challenge\":\"" + fc::base64url_encode(d.data(), d.data_size()) + "\"}"; std::vector<uint8_t> auth_data(37); memcpy(auth_data.data(), origin_hash.data(), sizeof(origin_hash)); BOOST_CHECK_EQUAL(wa_pub, make_webauthn_sig(priv, auth_data, json).recover(d, true)); } FC_LOG_AND_RETHROW(); //Good signature but it's not a JSON object! BOOST_AUTO_TEST_CASE(not_json_object) try { webauthn::public_key wa_pub(pub.serialize(), webauthn::public_key::user_presence_t::USER_PRESENCE_NONE, "fctesting.invalid"); std::string json = "hey man"s; std::vector<uint8_t> auth_data(37); memcpy(auth_data.data(), origin_hash.data(), sizeof(origin_hash)); BOOST_CHECK_EXCEPTION(make_webauthn_sig(priv, auth_data, json).recover(d, true), fc::assert_exception, [](const fc::assert_exception& e) { return e.to_detail_string().find("Failed to parse client data JSON") != std::string::npos; }); } FC_LOG_AND_RETHROW(); //damage the r/s portion of the signature BOOST_AUTO_TEST_CASE(damage_sig) try { webauthn::public_key wa_pub(pub.serialize(), webauthn::public_key::user_presence_t::USER_PRESENCE_NONE, "fctesting.invalid"); std::string json = "{\"origin\":\"https://fctesting.invalid\",\"type\":\"webauthn.get\",\"challenge\":\"" + fc::base64url_encode(d.data(), d.data_size()) + "\"}"; std::vector<uint8_t> auth_data(37); memcpy(auth_data.data(), origin_hash.data(), sizeof(origin_hash)); webauthn::signature sig = make_webauthn_sig(priv, auth_data, json); char buff[8192]; datastream<char*> ds(buff, sizeof(buff)); fc::raw::pack(ds, sig); buff[4]++; ds.seekp(0); fc::raw::unpack(ds, sig); bool failed_recovery = false; bool failed_compare = false; webauthn::public_key recovered_pub; try { recovered_pub = sig.recover(d, true); failed_compare = !(wa_pub == recovered_pub); } catch(fc::exception& e) { failed_recovery = e.to_detail_string().find("unable to reconstruct public key from signature") != std::string::npos; } //We can fail either by failing to recover any key, or recovering the wrong key. Check that at least one of these failed BOOST_CHECK_EQUAL(failed_recovery || failed_compare, true); } FC_LOG_AND_RETHROW(); //damage the recovery index portion of the sig BOOST_AUTO_TEST_CASE(damage_sig_idx) try { webauthn::public_key wa_pub(pub.serialize(), webauthn::public_key::user_presence_t::USER_PRESENCE_NONE, "fctesting.invalid"); std::string json = "{\"origin\":\"https://fctesting.invalid\",\"type\":\"webauthn.get\",\"challenge\":\"" + fc::base64url_encode(d.data(), d.data_size()) + "\"}"; std::vector<uint8_t> auth_data(37); memcpy(auth_data.data(), origin_hash.data(), sizeof(origin_hash)); webauthn::signature sig = make_webauthn_sig(priv, auth_data, json); char buff[8192]; datastream<char*> ds(buff, sizeof(buff)); fc::raw::pack(ds, sig); buff[0]++; ds.seekp(0); fc::raw::unpack(ds, sig); bool failed_recovery = false; bool failed_compare = false; webauthn::public_key recovered_pub; try { recovered_pub = sig.recover(d, true); failed_compare = !(wa_pub == recovered_pub); } catch(fc::exception& e) { failed_recovery = e.to_detail_string().find("unable to reconstruct public key from signature") != std::string::npos; } //We can fail either by failing to recover any key, or recovering the wrong key. Check that at least one of these failed BOOST_CHECK_EQUAL(failed_recovery || failed_compare, true); } FC_LOG_AND_RETHROW(); //Good signature but with a different private key than was expecting BOOST_AUTO_TEST_CASE(different_priv_key) try { r1::private_key other_priv = fc::crypto::r1::private_key::generate(); webauthn::public_key wa_pub(pub.serialize(), webauthn::public_key::user_presence_t::USER_PRESENCE_NONE, "fctesting.invalid"); std::string json = "{\"origin\":\"https://fctesting.invalid\",\"type\":\"webauthn.get\",\"challenge\":\"" + fc::base64url_encode(d.data(), d.data_size()) + "\"}"; std::vector<uint8_t> auth_data(37); memcpy(auth_data.data(), origin_hash.data(), sizeof(origin_hash)); BOOST_CHECK_NE(wa_pub, make_webauthn_sig(other_priv, auth_data, json).recover(d, true)); } FC_LOG_AND_RETHROW(); //Good signature but has empty json BOOST_AUTO_TEST_CASE(empty_json) try { webauthn::public_key wa_pub(pub.serialize(), webauthn::public_key::user_presence_t::USER_PRESENCE_NONE, "fctesting.invalid"); std::string json; std::vector<uint8_t> auth_data(37); memcpy(auth_data.data(), origin_hash.data(), sizeof(origin_hash)); BOOST_CHECK_EXCEPTION(make_webauthn_sig(priv, auth_data, json).recover(d, true), fc::assert_exception, [](const fc::assert_exception& e) { return e.to_detail_string().find("Failed to parse client data JSON") != std::string::npos; }); } FC_LOG_AND_RETHROW(); //empty rpid not allowed for pub key BOOST_AUTO_TEST_CASE(empty_rpid) try { char data[67] = {}; datastream<char*> ds(data, sizeof(data)); webauthn::public_key pubkey; BOOST_CHECK_EXCEPTION(fc::raw::unpack(ds, pubkey), fc::assert_exception, [](const fc::assert_exception& e) { return e.to_detail_string().find("webauthn pubkey must have non empty rpid") != std::string::npos; }); } FC_LOG_AND_RETHROW(); //good sig but remove the trailing =, should still be accepted BOOST_AUTO_TEST_CASE(good_no_trailing_equal) try { webauthn::public_key wa_pub(pub.serialize(), webauthn::public_key::user_presence_t::USER_PRESENCE_NONE, "fctesting.invalid"); std::string json = "{\"origin\":\"https://fctesting.invalid\",\"type\":\"webauthn.get\",\"challenge\":\"" + fc::base64url_encode(d.data(), d.data_size()) + "\"}"; boost::erase_all(json, "="); std::vector<uint8_t> auth_data(37); memcpy(auth_data.data(), origin_hash.data(), sizeof(origin_hash)); BOOST_CHECK_EQUAL(wa_pub, make_webauthn_sig(priv, auth_data, json).recover(d, true)); } FC_LOG_AND_RETHROW(); //Before the base64 decoder was adjusted to throw in error (pre-webauthn-merge), it would simply stop when encountering //a non-base64 char. This means it was possible for the following JSON & challenge to validate completely correctly. Now it //should not pass. BOOST_AUTO_TEST_CASE(base64_wonky) try { webauthn::public_key wa_pub(pub.serialize(), webauthn::public_key::user_presence_t::USER_PRESENCE_NONE, "fctesting.invalid"); std::string json = "{\"origin\":\"https://fctesting.invalid\",\"type\":\"webauthn.get\",\"challenge\":\"" + fc::base64url_encode(d.data(), d.data_size()) + "!@#$\"}"; boost::erase_all(json, "="); std::vector<uint8_t> auth_data(37); memcpy(auth_data.data(), origin_hash.data(), sizeof(origin_hash)); BOOST_CHECK_EXCEPTION(make_webauthn_sig(priv, auth_data, json).recover(d, true), fc::exception, [](const fc::exception& e) { return e.to_detail_string().find("encountered non-base64 character") != std::string::npos; }); } FC_LOG_AND_RETHROW(); BOOST_AUTO_TEST_SUITE_END()
50.845606
187
0.710408
celes-dev
ba60f7154d7273af690b7770c8521ec96c6cf1fb
2,358
cpp
C++
solved/i-k/jogging-trails/uva/jogging.cpp
abuasifkhan/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
13
2015-09-30T19:18:04.000Z
2021-06-26T21:11:30.000Z
solved/i-k/jogging-trails/uva/jogging.cpp
sbmaruf/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
null
null
null
solved/i-k/jogging-trails/uva/jogging.cpp
sbmaruf/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
13
2015-01-04T09:49:54.000Z
2021-06-03T13:18:44.000Z
#include <cstdio> #include <cstring> #define MAXN 15 #define INF (1 << 30) #define Neg(v) memset((v), -1, sizeof(v)) #define GetFS(b) ((b) & -(b)) #define ClrFS(b) (b &= ~GetFS(b)) static const int m37pos[] = { 32, 0, 1, 26, 2, 23, 27, 0, 3, 16, 24, 30, 28, 11, 0, 13, 4, 7, 17, 0, 25, 22, 31, 15, 29, 10, 12, 6, 0, 21, 14, 9, 5, 20, 8, 19, 18 }; #define Ctz(x) (m37pos[(x) % 37]) typedef unsigned int u32; int n, m; int g[MAXN][MAXN]; // pv[i]: true if vertex i has an even degree bool pv[MAXN]; int memo[1 << MAXN]; void floyd() { for (int k = 0; k < n; k++) for(int i = 0; i < n; i++) for (int j = 0; j < n; j++) { if (g[i][k] == INF || g[k][j] == INF) continue; int t = g[i][k] + g[k][j]; if (t < g[i][j]) g[i][j] = t; } } void init_graph() { for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) g[i][j] = i == j ? 0 : INF; } // minimum cost of increasing the degree of vertices "b" by one int f(u32 b) { if (b == 0) return 0; if (memo[b] >= 0) return memo[b]; int best = INF; int nv = 0; int vs[MAXN]; for (u32 r = b; r; ClrFS(r)) { u32 x = GetFS(r); vs[nv++] = Ctz(x); } for (int i = 0; i < nv; ++i) for (int j = i + 1; j < nv; ++j) { u32 p = (1 << vs[i]) | (1 << vs[j]); int cur = g[vs[i]][vs[j]] + f(b & ~p); if (cur < best) best = cur; } return memo[b] = best; } int cost_euler_cycle() { int odds = 0; u32 bmask = 0; for (int i = 0; i < n; ++i) if (! pv[i]) { ++odds; bmask |= 1 << i; } if (odds == 0) return 0; floyd(); Neg(memo); return f(bmask); } int main() { while (true) { scanf("%d", &n); if (n == 0) break; scanf("%d", &m); int ans = 0; init_graph(); for (int i = 0; i < n; ++i) pv[i] = true; for (int i = 0; i < m; ++i) { int u, v, w; scanf("%d%d%d", &u, &v, &w); --u; --v; ans += w; if (w < g[u][v]) g[u][v] = g[v][u] = w; pv[u] = !pv[u]; pv[v] = !pv[v]; } ans += cost_euler_cycle(); printf("%d\n", ans); } return 0; }
19.170732
63
0.39313
abuasifkhan
ba62178787cfae7bd6cf381337288b92faf94f45
840
cpp
C++
src/PathTracing/Materials/Metal.cpp
agordeevw/pathtracer
85340f398d34b79e757a6341af9a448f033884db
[ "MIT" ]
null
null
null
src/PathTracing/Materials/Metal.cpp
agordeevw/pathtracer
85340f398d34b79e757a6341af9a448f033884db
[ "MIT" ]
1
2019-01-08T15:11:47.000Z
2019-01-08T15:11:47.000Z
src/PathTracing/Materials/Metal.cpp
agordeevw/pathtracer
85340f398d34b79e757a6341af9a448f033884db
[ "MIT" ]
null
null
null
#include <glm/geometric.hpp> #include "PathTracing/Hitable.h" #include "PathTracing/Materials/Metal.h" #include "PathTracing/Ray.h" #include "Util/Random.h" namespace PathTracing { namespace Materials { Metal::Metal(const Texture& albedo, float fuzziness) : albedo(albedo), fuzziness(std::min(std::max(fuzziness, 0.0f), 1.0f)) {} bool Metal::scatter(const Ray& rayIn, const HitRecord& rec, glm::vec3& attenuation, Ray& scattered) const { glm::vec3 reflected = glm::reflect(glm::normalize(rayIn.direction), rec.normal); scattered = Ray{rec.point, reflected + fuzziness * Util::Random::randInUnitSphere(), rayIn.time}; attenuation = albedo.sample(rec.u, rec.v, rec.point); return glm::dot(scattered.direction, rec.normal) > 0.0f; } } // namespace Materials } // namespace PathTracing
35
78
0.694048
agordeevw
ba698c2da270c7a494ce4045928a3280e4e611c0
8,371
cpp
C++
tests/Unit/DataStructures/DataBox/Test_TagName.cpp
tomwlodarczyk/spectre
086aaee002f2f07eb812cf17b8e1ba54052feb71
[ "MIT" ]
null
null
null
tests/Unit/DataStructures/DataBox/Test_TagName.cpp
tomwlodarczyk/spectre
086aaee002f2f07eb812cf17b8e1ba54052feb71
[ "MIT" ]
null
null
null
tests/Unit/DataStructures/DataBox/Test_TagName.cpp
tomwlodarczyk/spectre
086aaee002f2f07eb812cf17b8e1ba54052feb71
[ "MIT" ]
1
2019-01-03T21:47:04.000Z
2019-01-03T21:47:04.000Z
// Distributed under the MIT License. // See LICENSE.txt for details. #include "Framework/TestingFramework.hpp" #include <string> #include "DataStructures/DataBox/Tag.hpp" #include "DataStructures/DataBox/TagName.hpp" #include "Helpers/DataStructures/DataBox/TestTags.hpp" namespace { struct NamedSimple : db::SimpleTag { static std::string name() noexcept { return "NameOfSimple"; } }; struct NamedBase : db::BaseTag { static std::string name() noexcept { return "NameOfBase"; } }; struct NamedSimpleWithBase : TestHelpers::db::Tags::Base, db::SimpleTag { static std::string name() noexcept { return "NameOfSimpleWithBase"; } }; struct SimpleWithNamedBase : NamedBase, db::SimpleTag {}; struct NamedSimpleWithNamedBase : NamedBase, db::SimpleTag { static std::string name() noexcept { return "NameOfSimpleWithNamedBase"; } }; struct SimpleNamedCompute : TestHelpers::db::Tags::Simple, db::ComputeTag { static std::string name() noexcept { return "NameOfSimpleCompute"; } }; struct NamedSimpleNamedCompute : NamedSimple, db::ComputeTag { static std::string name() noexcept { return "NameOfNamedSimpleCompute"; } }; struct NamedSimpleCompute : NamedSimple, db::ComputeTag { using base = NamedSimple; }; struct SimpleWithBaseNamedCompute : TestHelpers::db::Tags::SimpleWithBase, db::ComputeTag { static std::string name() noexcept { return "NameOfSimpleWithBaseCompute"; } }; struct NamedSimpleWithBaseNamedCompute : NamedSimpleWithBase, db::ComputeTag { static std::string name() noexcept { return "NameOfNamedSimpleWithBaseCompute"; } }; struct NamedSimpleWithBaseCompute : NamedSimpleWithBase, db::ComputeTag { using base = NamedSimpleWithBase; }; struct SimpleWithNamedBaseNamedCompute : SimpleWithNamedBase, db::ComputeTag { static std::string name() noexcept { return "NameOfSimpleWithNamedBaseCompute"; } }; struct SimpleWithNamedBaseCompute : SimpleWithNamedBase, db::ComputeTag { using base = SimpleWithNamedBase; }; struct NamedSimpleWithNamedBaseNamedCompute : NamedSimpleWithNamedBase, db::ComputeTag { static std::string name() noexcept { return "NameOfNamedSimpleWithNamedBaseCompute"; } }; struct NamedSimpleWithNamedBaseCompute : NamedSimpleWithNamedBase, db::ComputeTag { using base = NamedSimpleWithNamedBase; }; template <typename Tag> struct NamedLabel : db::PrefixTag, db::SimpleTag { using tag = Tag; static std::string name() noexcept { return "NameOfLabel(" + db::tag_name<Tag>() + ")"; } }; template <typename Tag> struct LabelNamedCompute : TestHelpers::db::Tags::Label<Tag>, db::ComputeTag { using tag = Tag; static std::string name() noexcept { return "NameOfLabelCompute(" + db::tag_name<Tag>() + ")"; } }; template <typename Tag> struct NamedLabelCompute : NamedLabel<Tag>, db::ComputeTag { using base = NamedLabel<Tag>; using tag = Tag; }; template <typename Tag> struct NamedLabelNamedCompute : NamedLabel<Tag>, db::ComputeTag { using tag = Tag; static std::string name() noexcept { return "NameOfNamedLabelCompute(" + db::tag_name<Tag>() + ")"; } }; } // namespace SPECTRE_TEST_CASE("Unit.DataStructures.DataBox.TagName", "[Unit][DataStructures]") { CHECK(db::tag_name<TestHelpers::db::Tags::Base>() == "Base"); CHECK(db::tag_name<TestHelpers::db::Tags::Simple>() == "Simple"); CHECK(db::tag_name<TestHelpers::db::Tags::SimpleWithBase>() == "SimpleWithBase"); CHECK(db::tag_name<TestHelpers::db::Tags::SimpleCompute>() == "Simple"); CHECK(db::tag_name<TestHelpers::db::Tags::SimpleWithBaseCompute>() == "SimpleWithBase"); CHECK(db::tag_name<NamedSimple>() == "NameOfSimple"); CHECK(db::tag_name<NamedBase>() == "NameOfBase"); CHECK(db::tag_name<NamedSimpleWithBase>() == "NameOfSimpleWithBase"); CHECK(db::tag_name<SimpleWithNamedBase>() == "NameOfBase"); CHECK(db::tag_name<NamedSimpleWithNamedBase>() == "NameOfSimpleWithNamedBase"); CHECK(db::tag_name<SimpleNamedCompute>() == "NameOfSimpleCompute"); CHECK(db::tag_name<NamedSimpleNamedCompute>() == "NameOfNamedSimpleCompute"); CHECK(db::tag_name<NamedSimpleCompute>() == "NameOfSimple"); CHECK(db::tag_name<SimpleWithBaseNamedCompute>() == "NameOfSimpleWithBaseCompute"); CHECK(db::tag_name<NamedSimpleWithBaseNamedCompute>() == "NameOfNamedSimpleWithBaseCompute"); CHECK(db::tag_name<NamedSimpleWithBaseCompute>() == "NameOfSimpleWithBase"); CHECK(db::tag_name<SimpleWithNamedBaseNamedCompute>() == "NameOfSimpleWithNamedBaseCompute"); CHECK(db::tag_name<SimpleWithNamedBaseCompute>() == "NameOfBase"); CHECK(db::tag_name<NamedSimpleWithNamedBaseNamedCompute>() == "NameOfNamedSimpleWithNamedBaseCompute"); CHECK(db::tag_name<NamedSimpleWithNamedBaseCompute>() == "NameOfSimpleWithNamedBase"); CHECK(db::tag_name< TestHelpers::db::Tags::Label<TestHelpers::db::Tags::Base>>() == "Label(Base)"); CHECK(db::tag_name< TestHelpers::db::Tags::Label<TestHelpers::db::Tags::Simple>>() == "Label(Simple)"); CHECK(db::tag_name<TestHelpers::db::Tags::Label< TestHelpers::db::Tags::SimpleWithBase>>() == "Label(SimpleWithBase)"); CHECK(db::tag_name<TestHelpers::db::Tags::Label< TestHelpers::db::Tags::SimpleCompute>>() == "Label(Simple)"); CHECK(db::tag_name<TestHelpers::db::Tags::Label< TestHelpers::db::Tags::SimpleWithBaseCompute>>() == "Label(SimpleWithBase)"); CHECK(db::tag_name<TestHelpers::db::Tags::Label<NamedSimple>>() == "Label(NameOfSimple)"); CHECK(db::tag_name<TestHelpers::db::Tags::Label<NamedBase>>() == "Label(NameOfBase)"); CHECK(db::tag_name<TestHelpers::db::Tags::Label<NamedSimpleWithBase>>() == "Label(NameOfSimpleWithBase)"); CHECK(db::tag_name<TestHelpers::db::Tags::Label<SimpleWithNamedBase>>() == "Label(NameOfBase)"); CHECK( db::tag_name<TestHelpers::db::Tags::Label<NamedSimpleWithNamedBase>>() == "Label(NameOfSimpleWithNamedBase)"); CHECK(db::tag_name<TestHelpers::db::Tags::Label<SimpleNamedCompute>>() == "Label(NameOfSimpleCompute)"); CHECK(db::tag_name<TestHelpers::db::Tags::Label<NamedSimpleNamedCompute>>() == "Label(NameOfNamedSimpleCompute)"); CHECK(db::tag_name<TestHelpers::db::Tags::Label<NamedSimpleCompute>>() == "Label(NameOfSimple)"); CHECK(db::tag_name< TestHelpers::db::Tags::Label<SimpleWithBaseNamedCompute>>() == "Label(NameOfSimpleWithBaseCompute)"); CHECK(db::tag_name< TestHelpers::db::Tags::Label<NamedSimpleWithBaseNamedCompute>>() == "Label(NameOfNamedSimpleWithBaseCompute)"); CHECK(db::tag_name< TestHelpers::db::Tags::Label<NamedSimpleWithBaseCompute>>() == "Label(NameOfSimpleWithBase)"); CHECK(db::tag_name< TestHelpers::db::Tags::Label<SimpleWithNamedBaseNamedCompute>>() == "Label(NameOfSimpleWithNamedBaseCompute)"); CHECK(db::tag_name< TestHelpers::db::Tags::Label<SimpleWithNamedBaseCompute>>() == "Label(NameOfBase)"); CHECK(db::tag_name<TestHelpers::db::Tags::Label< NamedSimpleWithNamedBaseNamedCompute>>() == "Label(NameOfNamedSimpleWithNamedBaseCompute)"); CHECK(db::tag_name< TestHelpers::db::Tags::Label<NamedSimpleWithNamedBaseCompute>>() == "Label(NameOfSimpleWithNamedBase)"); CHECK(db::tag_name<NamedLabel<TestHelpers::db::Tags::Simple>>() == "NameOfLabel(Simple)"); CHECK(db::tag_name<LabelNamedCompute<TestHelpers::db::Tags::Simple>>() == "NameOfLabelCompute(Simple)"); CHECK(db::tag_name<NamedLabelCompute<TestHelpers::db::Tags::Simple>>() == "NameOfLabel(Simple)"); CHECK(db::tag_name<NamedLabelNamedCompute<TestHelpers::db::Tags::Simple>>() == "NameOfNamedLabelCompute(Simple)"); CHECK(db::tag_name<NamedLabel<NamedSimple>>() == "NameOfLabel(NameOfSimple)"); CHECK(db::tag_name<LabelNamedCompute<NamedSimple>>() == "NameOfLabelCompute(NameOfSimple)"); CHECK(db::tag_name<NamedLabelCompute<NamedSimple>>() == "NameOfLabel(NameOfSimple)"); CHECK(db::tag_name<NamedLabelNamedCompute<NamedSimple>>() == "NameOfNamedLabelCompute(NameOfSimple)"); }
39.300469
80
0.691315
tomwlodarczyk
ba6d1798bcfa767be300d256ad0526cbcaf2e85e
167,969
cpp
C++
src/AssemblyGraph2.cpp
chanzuckerberg/shasta
a8933d5aade5c8cc8b92852bf3092fb32bf30b22
[ "BSD-3-Clause-Open-MPI" ]
267
2018-07-31T16:12:24.000Z
2022-03-29T13:57:53.000Z
src/AssemblyGraph2.cpp
chanzuckerberg/shasta
a8933d5aade5c8cc8b92852bf3092fb32bf30b22
[ "BSD-3-Clause-Open-MPI" ]
140
2018-08-10T14:14:19.000Z
2022-02-18T22:05:05.000Z
src/AssemblyGraph2.cpp
chanzuckerberg/shasta
a8933d5aade5c8cc8b92852bf3092fb32bf30b22
[ "BSD-3-Clause-Open-MPI" ]
47
2018-09-28T18:29:37.000Z
2022-02-21T02:45:40.000Z
// Shasta. #include "AssemblyGraph2.hpp" #include "AssembledSegment.hpp" #include "assembleMarkerGraphPath.hpp" #include "computeLayout.hpp" #include "copyNumber.hpp" #include "deduplicate.hpp" #include "dominatorTree.hpp" #include "enumeratePaths.hpp" #include "findLinearChains.hpp" #include "findMarkerId.hpp" #include "GfaAssemblyGraph.hpp" #include "orderPairs.hpp" #include "ReadFlags.hpp" #include "writeGraph.hpp" using namespace shasta; // Boost libraries. #include <boost/graph/dominator_tree.hpp> #include <boost/graph/connected_components.hpp> #include <boost/graph/filtered_graph.hpp> #include <boost/graph/kruskal_min_spanning_tree.hpp> #include <boost/graph/iteration_macros.hpp> #include <boost/graph/reverse_graph.hpp> #include <boost/multi_index_container.hpp> #include <boost/multi_index/ordered_index.hpp> #include <boost/multi_index/ranked_index.hpp> #include <boost/pending/disjoint_sets.hpp> // Standard library. #include "fstream.hpp" #include <limits> #include <map> #include <numeric> // The constructor creates an edge for each linear path // in the marker graph. Therefore, immediately after construction, // each edge has a single MarkerGraphPath (no bubbles). AssemblyGraph2::AssemblyGraph2( uint64_t readRepresentation, uint64_t k, // Marker length const MemoryMapped::Vector<ReadFlags>& readFlags, const MemoryMapped::VectorOfVectors<CompressedMarker, uint64_t>& markers, const MarkerGraph& markerGraph, double bubbleRemovalDiscordantRatioThreshold, double bubbleRemovalAmbiguityThreshold, uint64_t bubbleRemovalMaxPeriod, uint64_t superbubbleRemovalEdgeLengthThreshold, uint64_t phasingMinReadCount, bool suppressGfaOutput, bool suppressFastaOutput, bool suppressDetailedOutput, bool suppressPhasedOutput, bool suppressHaploidOutput, size_t threadCount ) : MultithreadedObject<AssemblyGraph2>(*this), readRepresentation(readRepresentation), k(k), readFlags(readFlags), markers(markers), markerGraph(markerGraph) { #if 0 // Length threshold (in markers) for cleanupSecondaryEdges // and removeSecondaryBubbles. Assembly graph edges // longer than this are excluded from removal. // EXPOSE WHEN CODE STABILIZES. const uint64_t secondaryEdgeCleanupThreshold = 6; #endif // Threshold that defines a strong branch. // A branch if strong if it is supported by at least this number of // distinct oriented reads. // Weak branches are subject to removal by removeWeakBranches // (but at least one branch in each bubble will always be kept). // EXPOSE WHEN CODE STABILIZES. const uint64_t strongBranchThreshold = 2; // Because of the way we write the GFA file (without overlaps), // k is required to be even. SHASTA_ASSERT((k % 2) == 0); // Create the assembly graph. create(); writePloidyHistogram(cout); writeDetailedEarly("0"); #if 0 // Remove secondary edges, making sure to not introduce any dead ends. cleanupSecondaryEdges(secondaryEdgeCleanupThreshold); merge(false, false); writeDetailedEarly("1"); #endif // Gather parallel edges into bubbles. gatherBubbles(false); writeDetailedEarly("2"); // Handle superbubbles. handleSuperbubbles(superbubbleRemovalEdgeLengthThreshold); merge(false, false); writeDetailedEarly("3"); // Store the reads supporting each branch of each edges. storeReadInformation(); // Remove weak branches. // removeSecondaryBubbles(secondaryEdgeCleanupThreshold); OLD removeWeakBranches(strongBranchThreshold); merge(true, false); gatherBubbles(true); // So we get the bubbles that appear since we last did this. writeDetailedEarly("4"); // Assemble sequence. assemble(); // Remove degenerate edges (both branches have the same sequence). removeDegenerateBranches(); merge(true, true); writeDetailedEarly("5"); #if 0 // Find bubbles caused by copy number changes in repeats // with period up to maxPeriod, then remove them. findCopyNumberBubbles(bubbleRemovalMaxPeriod); removeCopyNumberBubbles(); merge(true, true); writeDetailedEarly("6"); #endif // Create the bubble graph. createBubbleGraph(markers.size()/2, phasingMinReadCount, threadCount); cout << "The initial bubble graph has " << num_vertices(bubbleGraph) << " vertices and " << num_edges(bubbleGraph) << " edges." << endl; // Cleanup the bubble graph. // This marks as bad the bubbles corresponding to bubble graph vertices // that are removed. cleanupBubbleGraph( markers.size()/2, phasingMinReadCount, bubbleRemovalDiscordantRatioThreshold, bubbleRemovalAmbiguityThreshold); // Compute connected components of the bubble graph. bubbleGraph.computeConnectedComponents(); // Use each connected component of the bubble graph to phase the bubbles. phase(threadCount); #if 0 // Remove from the AssemblyGraph2 the bubbles marked isBad // (only keep the strongest branch). removeBadBubbles(); merge(true, true); #endif // Find chains of bubbles. // These are linear chains of edges of length at least 2. findBubbleChains(); writeBubbleChains(); findPhasingRegions(); writePhasingRegions(); // Write out what we have. storeGfaSequence(); if(not suppressDetailedOutput) { writeDetailed("Assembly-Detailed", true, false, true, not suppressGfaOutput, not suppressFastaOutput); if(not suppressGfaOutput) { writeDetailed("Assembly-Detailed-NoSequence", false, false, false, true, false); } } if(not suppressHaploidOutput) { writeHaploid("Assembly-Haploid", true, true, not suppressGfaOutput, not suppressFastaOutput); if(not suppressGfaOutput) { writeHaploid("Assembly-Haploid-NoSequence", false, false, true, false); } } if(not suppressPhasedOutput) { writePhased("Assembly-Phased", true, true, not suppressGfaOutput, not suppressFastaOutput); if(not suppressGfaOutput) { writePhased("Assembly-Phased-NoSequence", false, false, true, false); } } // Het snp statistics. uint64_t transitionCount, transversionCount; hetSnpStatistics(transitionCount, transversionCount); cout << transitionCount << " heterozygous transitions, " << transversionCount << " heterozygous transversions.\n" << "Transition/transversion ratio is " << double(transitionCount) / double(transversionCount) << endl; cout << "The number of heterozygous SNPs is underestimated " "and the transition/transversion ratio is overestimated " "due to SNPs that are invisible in RLE space. " "Work is in progress to correct this. " "Phasing is effective even without access to those " "missing heterozygous loci." << endl; } void AssemblyGraph2::cleanupBubbleGraph( uint64_t readCount, uint64_t phasingMinReadCount, double discordantRatioThreshold, double ambiguityThreshold) { cout << timestamp << "cleanupBubbleGraph begins." << endl; G& g = *this; const bool debug = false; // Create a table the contains the discordant ratio of each // vertex and that can be updated dynamically when we add or remove vertices. // Vertices are removed when bad bubbles are found. // In turn, the removal of these bubbles can cause new bubbles to be found. using namespace boost::multi_index; using DiscordantRatioTableEntry = pair<BubbleGraph::vertex_descriptor, double>; using DiscordantRatioTable = multi_index_container< DiscordantRatioTableEntry, indexed_by< ordered_unique< member<DiscordantRatioTableEntry, BubbleGraph::vertex_descriptor, &DiscordantRatioTableEntry::first> >, ranked_non_unique< member<DiscordantRatioTableEntry, double, &DiscordantRatioTableEntry::second>, std::greater<double> > > >; DiscordantRatioTable discordantRatioTable; BGL_FORALL_VERTICES(v, bubbleGraph, BubbleGraph) { discordantRatioTable.insert(make_pair(v, bubbleGraph.discordantRatio(v))); } // Create the dynamic oriented read table. // It will be updated below as we add and remove bubble graph vertices. bubbleGraph.createDynamicOrientedReadsTable(readCount); // Main loop. // We find in the discordantRatioTable the vertex with the worst discordance. // If this is less than discordantRatioThreshold, we are done. // Otherwise we remove that vertex and mark the corresponding bubble as bad, // then update the discordantRatioTable. // LATER, WE WILL ALSO CHECK IF ANY NEW BUBBLES WERE CREATED. uint64_t removedCount = 0; uint64_t addedCount = 0; while(true) { // Find the vertex with highest discordance ratio. if(discordantRatioTable.empty()) { break; } const auto it = discordantRatioTable.get<1>().nth(0); // If the discordantio is less than our threshold, we are done. const double discordantRatio = it->second; if(discordantRatio < discordantRatioThreshold) { break; } // Locate the vertex to be removed. const vertex_descriptor v = it->first; // Before removing it, find all of its neighbors, // so we can update their discordant ratio after removing the vertex. vector<BubbleGraph::vertex_descriptor> neighbors; BGL_FORALL_OUTEDGES(v, e, bubbleGraph, BubbleGraph) { neighbors.push_back(target(e, bubbleGraph)); } deduplicate(neighbors); // Mark this bubble as bad, update the dynamic oriented reads table, // and remove the bubble graph vertex. const AssemblyGraph2::edge_descriptor e = bubbleGraph[v].e; E& assemblyGraphEdge = g[e]; // cout << "Removing " << assemblyGraphEdge.id << " with discordant ratio " << discordantRatio << endl; assemblyGraphEdge.isBad = true; bubbleGraph.updateDynamicOrientedReadsTableForRemoval(v); clear_vertex(v, bubbleGraph); remove_vertex(v, bubbleGraph); discordantRatioTable.get<1>().erase(it); ++removedCount; // Update the discordant ratio table for the neighbors. for(const BubbleGraph::vertex_descriptor neighbor: neighbors) { const double discordantRatio = bubbleGraph.discordantRatio(neighbor); const auto it = discordantRatioTable.get<0>().find(neighbor); SHASTA_ASSERT(it != discordantRatioTable.get<0>().end()); discordantRatioTable.get<0>().replace(it, make_pair(neighbor, discordantRatio)); } // In the bubble we marked as bad, only keep the strongest branch. g[e].removeAllBranchesExceptStrongest(); const uint64_t eId = g[e].id; // See if can do any merging. edge_descriptor eMerged = mergeWithPreviousIfPossible(e); eMerged = mergeWithFollowingIfPossible(eMerged); // If some merging happened, check if a new bubble was created. if(g[eMerged].id == eId) { continue; } const vertex_descriptor v0 = source(eMerged, g); const vertex_descriptor v1 = target(eMerged, g); // Find all edges between v0 and v1. vector<edge_descriptor> edges01; BGL_FORALL_OUTEDGES(v0, e, g, G) { if(target(e, g) == v1) { edges01.push_back(e); } } SHASTA_ASSERT(not edges01.empty()); // If not exactly two, it is not a bubble. if(edges01.size() != 2) { continue; } ++addedCount; /* cout << "New candidate bubble at "; for(const edge_descriptor e: edges01) { cout << " " << g[e].id; } cout << endl; */ // Combine these edges into a new bubble. edge_descriptor eNew; tie(eNew, ignore )= add_edge(v0, v1, E(nextId++), g); for(const edge_descriptor e: edges01) { for(const E::Branch& branch: g[e].branches) { g[eNew].branches.push_back(branch); } boost::remove_edge(e, g); } g[eNew].findStrongestBranch(); assemble(eNew); g[eNew].storeReadInformation(markerGraph); // If diploid, add a new bubble graph vertex for this bubble. if(g[eNew].ploidy() != 2) { continue; } const BubbleGraph::vertex_descriptor vNew = add_vertex(BubbleGraphVertex(eNew, g[eNew]), bubbleGraph); bubbleGraph.updateDynamicOrientedReadsTableForAddition(vNew); bubbleGraph.createNewEdges(vNew, phasingMinReadCount); // Update the discordant ratio table. discordantRatioTable.insert(make_pair(vNew, bubbleGraph.discordantRatio(vNew))); BGL_FORALL_OUTEDGES(vNew, e, bubbleGraph, BubbleGraph) { const BubbleGraph::vertex_descriptor neighbor = target(e, bubbleGraph); const double discordantRatio = bubbleGraph.discordantRatio(neighbor); const auto it = discordantRatioTable.get<0>().find(neighbor); SHASTA_ASSERT(it != discordantRatioTable.get<0>().end()); discordantRatioTable.get<0>().replace(it, make_pair(neighbor, discordantRatio)); } } cout << "Marked " << removedCount << " bubbles as bad." << endl; cout << "Found " << addedCount << " new candidate bubbles." << endl; bubbleGraph.dynamicOrientedReadsTable.clear(); #if 0 // Remove weak vertices of the bubble graph // and flag the corresponding bubbles as bad. for(uint64_t iteration=0; ; iteration++) { if(debug) { bubbleGraph.writeGraphviz("BubbleGraph-Iteration-" + to_string(iteration) + ".dot"); bubbleGraph.writeVerticesCsv("BubbleGraphVertices-Iteration-" + to_string(iteration) + ".csv"); bubbleGraph.writeEdgesCsv("BubbleGraphEdges-Iteration-" + to_string(iteration) + ".csv"); } vector<AssemblyGraph2::edge_descriptor> badBubbles; bubbleGraph.removeWeakVertices(discordantRatioThreshold, badBubbles); if(badBubbles.empty()) { break; } for(const AssemblyGraph2::edge_descriptor e: badBubbles) { g[e].isBad = true; } cout << "After removing " << badBubbles.size() << " weak vertices, the bubble graph has " << num_vertices(bubbleGraph) << " vertices and " << num_edges(bubbleGraph) << " edges." << endl; } #endif // Finally, remove edges with high ambiguity. vector<BubbleGraph::edge_descriptor> edgesToBeRemoved; #if 1 BGL_FORALL_EDGES(e, bubbleGraph, BubbleGraph) { if(bubbleGraph[e].ambiguity() > ambiguityThreshold) { edgesToBeRemoved.push_back(e); } } #else // Try a different criterion here. BGL_FORALL_EDGES(e, bubbleGraph, BubbleGraph) { const BubbleGraphEdge& edge = bubbleGraph[e]; if(edge.concordantCount() - edge.discordantCount() < phasingMinReadCount) { edgesToBeRemoved.push_back(e); } } #endif for(const BubbleGraph::edge_descriptor e: edgesToBeRemoved) { boost::remove_edge(e, bubbleGraph); } cout << "Removed " << edgesToBeRemoved.size() << " bubble graph edges with ambiguity greater than " << ambiguityThreshold << endl; if(debug) { bubbleGraph.writeGraphviz("BubbleGraph-Final.dot"); bubbleGraph.writeVerticesCsv("BubbleGraphVertices-Final.csv"); bubbleGraph.writeEdgesCsv("BubbleGraphEdges-Final.csv"); } cout << timestamp << "cleanupBubbleGraph ends." << endl; } // Initial creation of vertices and edges. void AssemblyGraph2::create() { const bool debug = false; ofstream debugOut; if(debug) { debugOut.open("AssemblyGraph2-Constructor.txt"); } const MarkerGraph::EdgeId edgeCount = markerGraph.edges.size(); vector<bool> wasFound(edgeCount, false); MarkerGraphPath nextEdges; MarkerGraphPath previousEdges; MarkerGraphPath path; MarkerGraphPath reverseComplementedPath; // Main loop over all edges of the marker graph. // At each iteration we find a new linear path of edges. for(MarkerGraph::EdgeId startEdgeId=0; startEdgeId<edgeCount; startEdgeId++) { if(debug) { const MarkerGraph::Edge& startEdge = markerGraph.edges[startEdgeId]; debugOut << "Starting a new path at edge " << startEdgeId << " " << startEdge.source << "->" << startEdge.target << endl; } // If we already found this edge, skip it. // It is part of a path we already found. if(wasFound[startEdgeId]) { continue; } // Follow the path forward. nextEdges.clear(); MarkerGraph::EdgeId edgeId = startEdgeId; bool isCircular = false; while(true) { const MarkerGraph::Edge edge = markerGraph.edges[edgeId]; const MarkerGraph::VertexId v1 = edge.target; const auto outEdges = markerGraph.edgesBySource[v1]; if(outEdges.size() != 1) { break; } const auto inEdges = markerGraph.edgesByTarget[v1]; if(inEdges.size() != 1) { break; } edgeId = outEdges[0]; if(debug) { debugOut << "Forward " << edgeId << " " << edge.source << "->" << edge.target << endl; } if(edgeId == startEdgeId) { isCircular = true; if(debug) { cout << "Found a circular edge." << endl; debugOut << "Found a circular edge." << endl; } break; } nextEdges.push_back(edgeId); SHASTA_ASSERT(not wasFound[edgeId]); } // Follow the path backward. previousEdges.clear(); if(!isCircular) { edgeId = startEdgeId; while(true) { const MarkerGraph::Edge edge = markerGraph.edges[edgeId]; const MarkerGraph::VertexId v0 = edge.source; const auto outEdges = markerGraph.edgesBySource[v0]; if(outEdges.size() != 1) { break; } const auto inEdges = markerGraph.edgesByTarget[v0]; if(inEdges.size() != 1) { break; } edgeId = inEdges[0]; if(debug) { debugOut << "Backward " << edgeId << " " << edge.source << "->" << edge.target << endl; } previousEdges.push_back(edgeId); SHASTA_ASSERT(not wasFound[edgeId]); } } // Gather the path. path.clear(); copy(previousEdges.rbegin(), previousEdges.rend(), back_inserter(path)); path.push_back(startEdgeId); copy(nextEdges.begin(), nextEdges.end(), back_inserter(path)); if(debug) { for(const MarkerGraph::EdgeId edgeId: path) { const MarkerGraph::Edge& edge = markerGraph.edges[edgeId]; debugOut << "Path " << edgeId << " " << edge.source << "->" << edge.target << endl; } } // Mark all the edges in the path as found. for(const MarkerGraph::EdgeId edgeId: path) { if(wasFound[edgeId]) { cout << "Assertion failed at " << edgeId << endl; if(debug) { debugOut << "Assertion failed at " << edgeId << endl; } SHASTA_ASSERT(0); } wasFound[edgeId] = true; } // Check if this path originated from one of the read graph // components that we want to assemble // (one of each reverse complemented pair). // If not, don't store it. // This way we do a single-stranded assembly. { const MarkerGraph::Edge& edge = markerGraph.edges[path.front()]; const MarkerGraphVertexId vertexId = edge.source; const span<const MarkerId> markerIds = markerGraph.getVertexMarkerIds(vertexId); const MarkerId markerId = markerIds[0]; const OrientedReadId orientedReadId = findMarkerId(markerId, markers).first; const ReadId readId = orientedReadId.getReadId(); const Strand strand = orientedReadId.getStrand(); if(readFlags[readId].strand != strand) { continue; } } // See if this path contains secondary edges. bool containsSecondaryEdges = false; for(const MarkerGraph::EdgeId edgeId: path) { const MarkerGraph::Edge& edge = markerGraph.edges[edgeId]; if(edge.isSecondary) { containsSecondaryEdges = true; break; } } // Store this path as a new edge of the assembly graph. addEdge(path, containsSecondaryEdges); } // Check that all edges of the marker graph were found. SHASTA_ASSERT(find(wasFound.begin(), wasFound.end(), false) == wasFound.end()); } // Remove secondary edges making sure to not introduce any dead ends. // This must be called early, when there are no bubbles. void AssemblyGraph2::cleanupSecondaryEdges(uint64_t secondaryEdgeCleanupThreshold) { G& g = *this; // Create a table of secondary edges. // For each edge also store the minimum secondary coverage, // that is, the minimum edge coverage of all secondary marker graph edges // that correspond to the edge. vector< pair<edge_descriptor, uint64_t> > edgeTable; BGL_FORALL_EDGES(e, g, G) { const E& edge = g[e]; // This must be called early, when there are no bubbles. // Each edge has a single branch. SHASTA_ASSERT(not edge.isBubble()); SHASTA_ASSERT(edge.branches.size() == 1); const E::Branch& branch = edge.branches.front(); // If the branch does not contain secondary edges, skip it. if(not branch.containsSecondaryEdges) { continue; } // If the branch is long, skip it. if(branch.path.size() > secondaryEdgeCleanupThreshold) { continue; } // Find minimum edge coverage for secondary edges of this branch. uint64_t minimumSecondaryCoverage = std::numeric_limits<uint64_t>::max(); for(const MarkerGraphEdgeId mId: branch.path) { const MarkerGraph::Edge& mEdge = markerGraph.edges[mId]; if(mEdge.isSecondary) { minimumSecondaryCoverage = min(minimumSecondaryCoverage, uint64_t(mEdge.coverage)); } } SHASTA_ASSERT(minimumSecondaryCoverage != std::numeric_limits<uint64_t>::max()); edgeTable.push_back(make_pair(e, minimumSecondaryCoverage)); } // Sort the edge table by increasing coverage. sort(edgeTable.begin(), edgeTable.end(), OrderPairsBySecondOnly<edge_descriptor, uint64_t>()); // Process the edges in this order. // Remove an edge if removal does not create a dead end. uint64_t removedCount = 0; for(const auto& p: edgeTable) { const edge_descriptor e = p.first; const vertex_descriptor v0 = source(e, g); if(out_degree(v0, g) == 1) { continue; } const vertex_descriptor v1 = target(e, g); if(in_degree(v1, g) == 1) { continue; } boost::remove_edge(e, g); ++removedCount; } cout << "Removed " << removedCount << " secondary edges." << endl; } // Get the vertex descriptor for the vertex corresponding to // a given MarkerGraph::VertexId, creating the vertex if necessary. AssemblyGraph2::vertex_descriptor AssemblyGraph2::getVertex(MarkerGraph::VertexId vertexId) { const auto it = vertexMap.find(vertexId); if(it == vertexMap.end()) { const vertex_descriptor v = add_vertex(V(vertexId), *this); vertexMap.insert(make_pair(vertexId, v)); return v; } else { return it->second; } } // Create a new edges corresponding to the given path. // Also create the vertices if necessary. AssemblyGraph2::edge_descriptor AssemblyGraph2::addEdge( const MarkerGraphPath& path, bool containsSecondaryEdges) { // Get the first and last edge of the path. const MarkerGraph::EdgeId edgeId0 = path.front(); const MarkerGraph::EdgeId edgeId1 = path.back(); const MarkerGraph::Edge edge0 = markerGraph.edges[edgeId0]; const MarkerGraph::Edge edge1 = markerGraph.edges[edgeId1]; // Get the first and last vertex of the path. // This creates the vertices if necessary. const MarkerGraph::VertexId vertexId0 = edge0.source; const MarkerGraph::VertexId vertexId1 = edge1.target; const vertex_descriptor v0 = getVertex(vertexId0); const vertex_descriptor v1 = getVertex(vertexId1); // Create the edge. edge_descriptor e; bool edgeWasAdded = false; tie(e, edgeWasAdded) = add_edge(v0, v1, E(nextId++, path, containsSecondaryEdges), *this); SHASTA_ASSERT(edgeWasAdded); return e; } void AssemblyGraph2::writeCsv(const string& baseName) const { writeVerticesCsv(baseName + "-Vertices.csv"); writeEdgesCsv(baseName + "-Edges.csv"); writeEdgeDetailsCsv(baseName + "-EdgeDetails.csv"); } void AssemblyGraph2::writeVerticesCsv(const string& fileName) const { const AssemblyGraph2& graph = *this; ofstream csv(fileName); csv << "VertexId0\n"; BGL_FORALL_VERTICES(v, graph, AssemblyGraph2) { csv << graph[v].markerGraphVertexId << "\n"; } } void AssemblyGraph2::writeEdgesCsv(const string& fileName) const { const AssemblyGraph2& graph = *this; ofstream csv(fileName); csv << "VertexId0,VertexId1\n"; BGL_FORALL_EDGES(e, graph, AssemblyGraph2) { const vertex_descriptor v0 = source(e, graph); const vertex_descriptor v1 = target(e, graph); csv << graph[v0].markerGraphVertexId << ","; csv << graph[v1].markerGraphVertexId << "\n"; } } void AssemblyGraph2::writeEdgeDetailsCsv(const string& fileName) const { const G& g = *this; ofstream csv(fileName); csv << "FirstVertexId,LastVertexId,Branch,Position,EdgeId,VertexId0,VertexId1\n"; // Loop over edges. BGL_FORALL_EDGES(e, g, G) { const E& edge = g[e]; const vertex_descriptor v0 = source(e, g); const vertex_descriptor v1 = target(e, g); const MarkerGraph::VertexId vertexId0 = g[v0].markerGraphVertexId; const MarkerGraph::VertexId vertexId1 = g[v1].markerGraphVertexId; // Loop over branches of this edge. for(uint64_t branchId=0; branchId<edge.ploidy(); branchId++) { const E::Branch& branch = edge.branches[branchId]; const MarkerGraphPath& path = branch.path; for(uint64_t j=0; j<path.size(); j++) { const MarkerGraph::EdgeId edgeId = path[j]; const MarkerGraph::Edge& edge = markerGraph.edges[edgeId]; csv << vertexId0 << ","; csv << vertexId1 << ","; csv << branchId << ","; csv << j << ","; csv << edgeId << ","; csv << edge.source << ","; csv << edge.target << "\n"; } } } } // Assemble sequence for every marker graph path of every edge. void AssemblyGraph2::assemble() { G& g = *this; cout << timestamp << "assemble begins." << endl; // Use assembled sequence from the marker graph to obtain // assembled sequence for all edges. BGL_FORALL_EDGES(e, g, G) { assemble(e); } cout << timestamp << "assemble ends." << endl; } // Assemble sequence for every marker graph path of a given edge. void AssemblyGraph2::assemble(edge_descriptor e) { G& g = *this; E& edge = g[e]; for(E::Branch& branch: edge.branches) { const MarkerGraphPath& path = branch.path; AssembledSegment assembledSegment; MarkerGraph::EdgeId const * const begin = &path[0]; MarkerGraph::EdgeId const * const end = begin + path.size(); const span<const MarkerGraph::EdgeId> pathSpan(begin, end); assembleMarkerGraphPath(readRepresentation, k, markers, markerGraph, pathSpan, false, assembledSegment); // Store the sequence, excluding the first and last k/2 RLE bases. // Compute the number of raw bases to skip at the beginning. const uint64_t beginSkip = std::accumulate( assembledSegment.repeatCounts.begin(), assembledSegment.repeatCounts.begin() + k/2, 0ULL); // Compute the number of raw bases to skip at the end. const uint64_t endSkip = std::accumulate( assembledSegment.repeatCounts.end() - k/2, assembledSegment.repeatCounts.end(), 0ULL); // Copy the raw bases, excluding those corresponding to the first and last // k/2 RLE bases. branch.rawSequence.resize(assembledSegment.rawSequence.size() - beginSkip - endSkip); copy( assembledSegment.rawSequence.begin() + beginSkip, assembledSegment.rawSequence.end() - endSkip, branch.rawSequence.begin()); } } // Finds edges that form bubbles, then combine // each of them into a single edge with multiple paths. void AssemblyGraph2::gatherBubbles(bool findStrongestBranch) { G& g = *this; // Look for sets of parallel edges v0->v1. BGL_FORALL_VERTICES(v0, g, G) { // Map keyed by child vertex v1, and containing for each v1 // a vector of all the edges v0->v1. std::map< vertex_descriptor, vector<edge_descriptor> > successorMap; BGL_FORALL_OUTEDGES(v0, e01, g, G) { const vertex_descriptor v1 = target(e01, g); successorMap[v1].push_back(e01); } // Process each set with the same v1. for(const auto& p: successorMap) { // Get the edges v0->v1. const vector<edge_descriptor>& edges01= p.second; const uint64_t ploidy = edges01.size(); // If less than two edges, it is not a bubble, so there is // nothing to do. if(ploidy < 2) { continue; } const vertex_descriptor v1 = p.first; // Create the bubble remove these edges. createBubble(v0, v1, edges01, findStrongestBranch); } } } void AssemblyGraph2::writePloidyHistogram(ostream& s) const { const G& g = *this; vector<uint64_t> ploidyHistogram; BGL_FORALL_EDGES(e, g, G) { const uint64_t ploidy = g[e].ploidy(); if(ploidy >= ploidyHistogram.size()) { ploidyHistogram.resize(ploidy + 1); } ++ploidyHistogram[ploidy]; } s << "Ploidy histogram:" << endl; for(uint64_t ploidy=1; ploidy<ploidyHistogram.size(); ploidy++) { s << "Ploidy " << ploidy << ": " << ploidyHistogram[ploidy] << " edges." << endl; } } AssemblyGraph2::edge_descriptor AssemblyGraph2::createBubble( vertex_descriptor v0, vertex_descriptor v1, const vector<edge_descriptor>& edges01, bool findStrongestBranch) { G& g = *this; // Sanity check. for(const edge_descriptor e01: edges01) { SHASTA_ASSERT(source(e01, g) == v0); SHASTA_ASSERT(target(e01, g) == v1); SHASTA_ASSERT(g[e01].ploidy() == 1); } // Create the new edge to replace the old ones. edge_descriptor eNew; bool edgeWasAdded = false; tie(eNew, edgeWasAdded) = add_edge(v0, v1, E(nextId++), g); SHASTA_ASSERT(edgeWasAdded); E& edgeNew = g[eNew]; // Copy the branches to the new edge and remove the old edges. for(const edge_descriptor e01: edges01) { const E& edge01 = g[e01]; copy(edge01.branches.begin(), edge01.branches.end(), back_inserter(edgeNew.branches)); boost::remove_edge(e01, g); } if(findStrongestBranch) { edgeNew.findStrongestBranch(); } return eNew; } // Find bubbles caused by copy number changes in repeats // with period up to maxPeriod. void AssemblyGraph2::findCopyNumberBubbles(uint64_t maxPeriod) { cout << timestamp << "findCopyNumberBubbles begins." << endl; G& g = *this; uint64_t totalCount = 0; uint64_t bubbleCount = 0; uint64_t copyNumberCount = 0; BGL_FORALL_EDGES(e, g, G) { E& edge = g[e]; ++totalCount; if(not edge.isBubble()) { continue; } ++bubbleCount; edge.computeCopyNumberDifferencePeriod(maxPeriod); if(edge.period == 0) { continue; } ++copyNumberCount; /* cout << "Bubble " << edge.id << " of ploidy " << edge.ploidy() << " is a copy number bubble with period " << period << endl; */ } cout << "Total number of assembly graph edges " << totalCount << endl; cout << "Number of bubbles " << bubbleCount << endl; cout << "Number of copy number bubbles " << copyNumberCount << endl; cout << timestamp << "findCopyNumberBubbles ends." << endl; } // Remove bubbles caused by copy number changes. void AssemblyGraph2::removeCopyNumberBubbles() { G& g = *this; uint64_t totalCount = 0; uint64_t removedCount = 0; BGL_FORALL_EDGES(e, g, G) { ++totalCount; E& edge = g[e]; if(edge.period != 0) { edge.removeAllBranchesExceptStrongest(); ++removedCount; } } cout << "Cleaned up " << removedCount << " bubbles caused by repeat counts out of " << totalCount << " total." << endl; } // The first two bool flags work as follows: // - writeSequence=false, writeSequenceLengthInMarkers=false: // No sequence output (sequence is written as * instead), // and sequence length is expressed in bases. // This can only be called after storeGfaSequence has been called. // - writeSequence=false, writeSequenceLengthInMarkers=true: // No sequence output (sequence is written as * instead), // and sequence length is expressed in markers. // This does not use the stored gfa sequences and // so can be called early, before storeGfaSequence has been called. // - writeSequence=true, writeSequenceLengthInMarkers=false: // Complete output of sequence, with length in bases. // This can only be called after storeGfaSequence has been called. // - writeSequence=true, writeSequenceLengthInMarkers=true: // This comnbination is illegal and causes an assertion. void AssemblyGraph2::writeDetailed( const string& baseName, bool writeSequence, bool writeSequenceLengthInMarkers, bool writeCsv, bool writeGfa, bool writeFasta) const { // Check that we are not called with the forbidden combination // (see above comments). SHASTA_ASSERT(not(writeSequence and writeSequenceLengthInMarkers)); cout << timestamp << "writeDetailed begins." << endl; const G& g = *this; // Open the accompanying csv file and write the header. ofstream csv; if(writeCsv) { csv.open(baseName + ".csv"); csv << "Name,Component,Phase,Unphased strength,Color," "First marker graph vertex,Last marker graph vertex," "First marker graph edge,Last marker graph edge," "Length in markers," "Length in bases," "Secondary,Period," "Minimum marker graph edge coverage,Average marker graph edge coverage,Number of distinct oriented reads,"; if(writeSequence) { csv << "Sequence,"; } csv << "\n"; } // Open the fasta file. ofstream fasta; if(writeFasta) { fasta.open(baseName + ".fasta"); } // Create a GFA with a segment for each branch, then write it out. GfaAssemblyGraph<vertex_descriptor> gfa; BGL_FORALL_EDGES(e, g, G) { const E& edge = g[e]; const vertex_descriptor v0 = source(e, g); const vertex_descriptor v1 = target(e, g); for(uint64_t branchId=0; branchId<edge.ploidy(); branchId++) { const E::Branch& branch = edge.branches[branchId]; if(writeGfa) { if(writeSequence) { gfa.addSegment(edge.pathId(branchId), v0, v1, branch.gfaSequence); } else { if(writeSequenceLengthInMarkers) { gfa.addSegment(edge.pathId(branchId), v0, v1, branch.path.size()); } else { gfa.addSegment(edge.pathId(branchId), v0, v1, branch.gfaSequence.size()); } } } if(writeFasta) { fasta << ">" << edge.pathId(branchId) << " " << branch.gfaSequence.size() << "\n"; copy(branch.gfaSequence.begin(), branch.gfaSequence.end(), ostream_iterator<Base>(fasta)); fasta << "\n"; } // Write a line for this segment to the csv file. if(writeCsv) { // Get some information we need below. const uint64_t lengthInMarkers = branch.path.size(); SHASTA_ASSERT(lengthInMarkers > 0); const MarkerGraphEdgeId firstMarkerGraphEdgeId = branch.path.front(); const MarkerGraphEdgeId lastMarkerGraphEdgeId = branch.path.back(); const MarkerGraphVertexId firstMarkerGraphVertexId = markerGraph.edges[firstMarkerGraphEdgeId].source; const MarkerGraphVertexId lastMarkerGraphVertexId = markerGraph.edges[lastMarkerGraphEdgeId].target; const string color = edge.color(branchId); csv << edge.pathId(branchId) << ","; if(edge.componentId != std::numeric_limits<uint64_t>::max()) { csv << edge.componentId; } csv << ","; if(edge.phase != std::numeric_limits<uint64_t>::max()) { csv << (branchId == edge.phase ? 0 : 1); } csv << ","; if(edge.isBubble() and (edge.isBad or edge.phase == std::numeric_limits<uint64_t>::max())) { if(branchId == edge.strongestBranchId) { csv << "Strong"; } else { csv << "Weak"; } } csv << ","; csv << color << "," << firstMarkerGraphVertexId << "," << lastMarkerGraphVertexId << "," << firstMarkerGraphEdgeId << "," << lastMarkerGraphEdgeId << "," << lengthInMarkers << ","; if(writeSequence or (not writeSequenceLengthInMarkers)) { csv << branch.gfaSequence.size(); } csv << ","; csv << (branch.containsSecondaryEdges ? "S" : "") << "," << (edge.period ? to_string(edge.period) : string()) << "," << branch.minimumCoverage << "," << branch.averageCoverage() << "," << branch.orientedReadIds.size() << ","; if(writeSequence) { if(branch.gfaSequence.size() == 0) { csv << "-"; } else if(branch.gfaSequence.size() <= 6) { copy(branch.gfaSequence.begin(), branch.gfaSequence.end(), ostream_iterator<Base>(csv)); } else { csv << "..."; } csv << ","; } csv << "\n"; } } } // Add paths. if(writeGfa) { for(uint64_t bubbleChainId=0; bubbleChainId<uint64_t(bubbleChains.size()); bubbleChainId++) { const BubbleChain& bubbleChain = bubbleChains[bubbleChainId]; for(uint64_t phasingRegionId=0; phasingRegionId<uint64_t(bubbleChain.phasingRegions.size()); phasingRegionId++) { const auto& phasingRegion = bubbleChain.phasingRegions[phasingRegionId]; vector<string> path0; vector<string> path1; for(uint64_t position=phasingRegion.firstPosition; position<=phasingRegion.lastPosition; position++) { const edge_descriptor e = bubbleChain.edges[position]; const E& edge = g[e]; if(edge.componentId == std::numeric_limits<uint64_t>::max()) { // This edge is homozygous or unphased. const string segmentName = edge.pathId(edge.strongestBranchId); path0.push_back(segmentName); path1.push_back(segmentName); } else { // This edge is diploid and phased. SHASTA_ASSERT(edge.ploidy() == 2); SHASTA_ASSERT(edge.componentId == phasingRegion.componentId); string segmentName0 = edge.pathId(0); string segmentName1 = edge.pathId(1); if(edge.phase == 0) { path0.push_back(segmentName0); path1.push_back(segmentName1); } else { path0.push_back(segmentName1); path1.push_back(segmentName0); } } } // Each phased (diploid) region generates two paths. // Each unphased (haploid) region generates one path. if(phasingRegion.isPhased) { const string idPrefix = "PR." + to_string(bubbleChainId) + "." + to_string(phasingRegionId) + "." + to_string(phasingRegion.componentId) + "."; gfa.addPath(idPrefix + "0", path0); gfa.addPath(idPrefix + "1", path1); } else { SHASTA_ASSERT(path0 == path1); const string idString = "UR." + to_string(bubbleChainId) + "." + to_string(phasingRegionId); gfa.addPath(idString, path0); } } } } // Write out the GFA. if(writeGfa) { gfa.write(baseName + ".gfa"); } cout << timestamp << "writeDetailed ends." << endl; } void AssemblyGraph2::writeDetailedEarly(const string& baseName) { const bool writeSequence = false; const bool writeSequenceLengthInMarkers = true; const bool writeCsv = true; const bool writeGfa = true; const bool writeFasta = false; writeDetailed(baseName, writeSequence, writeSequenceLengthInMarkers, writeCsv, writeGfa, writeFasta); } void AssemblyGraph2::writeHaploid( const string& baseName, bool writeSequence, bool writeCsv, bool writeGfa, bool writeFasta) const { cout << timestamp << "writeHaploid begins." << endl; const G& g = *this; vector<uint64_t> bubbleChainLengths; uint64_t totalNonBubbleChainLength = 0; // Open the fasta file. ofstream fasta; if(writeFasta) { fasta.open(baseName + ".fasta"); } // Create a GFA and add a segment for each edge that is not part // of a bubble chain. GfaAssemblyGraph<vertex_descriptor> gfa; BGL_FORALL_EDGES(e, g, G) { const E& edge = g[e]; if(edge.bubbleChain.first) { continue; } const vertex_descriptor v0 = source(e, g); const vertex_descriptor v1 = target(e, g); for(uint64_t branchId=0; branchId<edge.ploidy(); branchId++) { const E::Branch& branch = edge.branches[branchId]; totalNonBubbleChainLength += branch.gfaSequence.size(); if(writeGfa) { if(writeSequence) { gfa.addSegment(edge.pathId(branchId), v0, v1, branch.gfaSequence); } else { gfa.addSegment(edge.pathId(branchId), v0, v1, branch.gfaSequence.size()); } } if(writeFasta) { fasta << ">" << edge.pathId(branchId) << " " << branch.gfaSequence.size() << "\n"; copy(branch.gfaSequence.begin(), branch.gfaSequence.end(), ostream_iterator<Base>(fasta)); fasta << "\n"; } } } // Add a segment for each bubble chain. for(uint64_t bubbleChainId=0; bubbleChainId<uint64_t(bubbleChains.size()); bubbleChainId++) { const BubbleChain& bubbleChain = bubbleChains[bubbleChainId]; const vertex_descriptor v0 = source(bubbleChain.edges.front(), g); const vertex_descriptor v1 = target(bubbleChain.edges.back(), g); vector<Base> sequence; computeBubbleChainGfaSequence(bubbleChain, sequence); bubbleChainLengths.push_back(uint64_t(sequence.size())); const string idString = "BC." + to_string(bubbleChainId); if(writeGfa) { if(writeSequence) { gfa.addSegment(idString, v0, v1, sequence); } else { gfa.addSegment(idString, v0, v1, sequence.size()); } } if(writeFasta) { fasta << ">" << idString << " " << sequence.size() << "\n"; copy(sequence.begin(), sequence.end(), ostream_iterator<Base>(fasta)); fasta << "\n"; } } // Write the GFA. if(writeGfa) { gfa.write(baseName + ".gfa"); } // Also write a csv file that can be used in Bandage. if(writeCsv) { ofstream csv(baseName + ".csv"); csv << "Name,ComponentId,Phase,Color,First marker graph edge,Last marker graph edge," "Secondary,Period," "Minimum edge coverage,Average edge coverage,Number of distinct oriented reads,\n"; // Write a line to csv for each edge that is not part of a bubble chain. BGL_FORALL_EDGES(e, g, G) { const E& edge = g[e]; if(edge.bubbleChain.first) { continue; } for(uint64_t branchId=0; branchId<edge.ploidy(); branchId++) { const E::Branch& branch = edge.branches[branchId]; const string color = edge.color(branchId); csv << edge.pathId(branchId) << ","; if(edge.componentId != std::numeric_limits<uint64_t>::max()) { csv << edge.componentId; } csv << ","; if(edge.phase != std::numeric_limits<uint64_t>::max()) { csv << (branchId == edge.phase ? 0 : 1); } csv << "," << color << "," << branch.path.front() << "," << branch.path.back() << "," << (branch.containsSecondaryEdges ? "S" : "") << "," << (edge.period ? to_string(edge.period) : string()) << "," << branch.minimumCoverage << "," << branch.averageCoverage() << "," << branch.orientedReadIds.size() << "\n"; } } // Write a line to csv for each bubble chain. for(uint64_t bubbleChainId=0; bubbleChainId<uint64_t(bubbleChains.size()); bubbleChainId++) { const string idString = "BC." + to_string(bubbleChainId); csv << idString << ",,,Cyan\n"; } // Statistics. const uint64_t totalLength = accumulate(bubbleChainLengths.begin(), bubbleChainLengths.end(), 0ULL); sort(bubbleChainLengths.begin(), bubbleChainLengths.end(), std::greater<uint64_t>()); uint64_t n50 = 0; uint64_t cumulativeLength = 0; for(const uint64_t length: bubbleChainLengths) { cumulativeLength += length; if(cumulativeLength >= totalLength/2) { n50 = length; break; } } cout << "Total length of bubble chains " << totalLength << ", N50 " << n50 << endl; cout << "Total length outside of bubble chains " << totalNonBubbleChainLength << endl; } cout << timestamp << "writeHaploid ends." << endl; } void AssemblyGraph2::writePhased( const string& baseName, bool writeSequence, bool writeCsv, bool writeGfa, bool writeFasta) const { cout << timestamp << "writePhased begins." << endl; const G& g = *this; // Length statistics. uint64_t totalHaploidBases = 0; uint64_t totalDiploidBases = 0; uint64_t totalNonBubbleChainBases = 0; // Tables used to compute N50 for diploid and haploid segments // that are part of bubble chains. vector<uint64_t> haploidLengths; vector<uint64_t> diploidLengths; // Also write a csv file that can be used in Bandage. ofstream csv; if(writeCsv) { csv.open(baseName + ".csv"); csv << "Name,Position in bubble chain,Ploidy,Bubble chain,Component,Haplotype,Length,Color\n"; } // Open the fasta file. ofstream fasta; if(writeFasta) { fasta.open(baseName + ".fasta"); } // Create a GFA and add a segment for each edge that is not part // of a bubble chain. GfaAssemblyGraph<vertex_descriptor> gfa; BGL_FORALL_EDGES(e, g, G) { const E& edge = g[e]; if(edge.bubbleChain.first) { continue; } const vertex_descriptor v0 = source(e, g); const vertex_descriptor v1 = target(e, g); for(uint64_t branchId=0; branchId<edge.ploidy(); branchId++) { const E::Branch& branch = edge.branches[branchId]; const string segmentId = edge.pathId(branchId); if(writeGfa) { if(writeSequence) { gfa.addSegment(segmentId, v0, v1, branch.gfaSequence); } else { gfa.addSegment(segmentId, v0, v1, branch.gfaSequence.size()); } } if(writeFasta) { fasta << ">" << segmentId << " " << branch.gfaSequence.size() << "\n"; copy(branch.gfaSequence.begin(), branch.gfaSequence.end(), ostream_iterator<Base>(fasta)); fasta << "\n"; } if(writeCsv) { csv << segmentId << ",,,,,,,#808080\n"; } totalNonBubbleChainBases += uint64_t(branch.gfaSequence.size()); } } // Add one or two segments, depending on ploidy, for each phasing region // of each bubble chain. vector<Base> sequence; for(uint64_t bubbleChainId=0; bubbleChainId<uint64_t(bubbleChains.size()); bubbleChainId++) { const BubbleChain& bubbleChain = bubbleChains[bubbleChainId]; for(uint64_t phasingRegionId=0; phasingRegionId<uint64_t(bubbleChain.phasingRegions.size()); phasingRegionId++) { const auto& phasingRegion = bubbleChain.phasingRegions[phasingRegionId]; const vertex_descriptor v0 = source(bubbleChain.edges[phasingRegion.firstPosition], g); const vertex_descriptor v1 = target(bubbleChain.edges[phasingRegion.lastPosition], g); if(phasingRegion.isPhased) { const string namePrefix = "PR." + to_string(bubbleChainId) + "." + to_string(phasingRegionId) + "." + to_string(phasingRegion.componentId) + "."; const string name0 = namePrefix + "0"; computePhasedRegionGfaSequence(bubbleChain, phasingRegion, 0, sequence); if(writeGfa) { if(writeSequence) { gfa.addSegment(name0, v0, v1, sequence); } else { gfa.addSegment(name0, v0, v1, sequence.size()); } } if(writeFasta) { fasta << ">" << name0 << " " << sequence.size() << "\n"; copy(sequence.begin(), sequence.end(), ostream_iterator<Base>(fasta)); fasta << "\n"; } totalDiploidBases += uint64_t(sequence.size()); diploidLengths.push_back(uint64_t(sequence.size())); if(writeCsv) { csv << name0 << "," << phasingRegionId << "," << "2," << bubbleChainId << "," << phasingRegion.componentId << "," << "0," << sequence.size() << "," "Green\n"; } const string name1 = namePrefix + "1"; computePhasedRegionGfaSequence(bubbleChain, phasingRegion, 1, sequence); if(writeGfa) { if(writeSequence) { gfa.addSegment(name1, v0, v1, sequence); } else { gfa.addSegment(name1, v0, v1, sequence.size()); } } if(writeFasta) { fasta << ">" << name1 << " " << sequence.size() << "\n"; copy(sequence.begin(), sequence.end(), ostream_iterator<Base>(fasta)); fasta << "\n"; } totalDiploidBases += uint64_t(sequence.size()); diploidLengths.push_back(uint64_t(sequence.size())); if(writeCsv) { csv << name1 << "," << phasingRegionId << "," << "2," << bubbleChainId << "," << phasingRegion.componentId << "," << "1," << sequence.size() << "," "Green\n"; } } else { computeUnphasedRegionGfaSequence(bubbleChain, phasingRegion, sequence); const string name = "UR." + to_string(bubbleChainId) + "." + to_string(phasingRegionId); if(writeGfa) { if(writeSequence) { gfa.addSegment(name, v0, v1, sequence); } else { gfa.addSegment(name, v0, v1, sequence.size()); } } totalHaploidBases += uint64_t(sequence.size()); haploidLengths.push_back(uint64_t(sequence.size())); if(writeFasta) { fasta << ">" << name << " " << sequence.size() << "\n"; copy(sequence.begin(), sequence.end(), ostream_iterator<Base>(fasta)); fasta << "\n"; } if(writeCsv) { csv << name << "," << phasingRegionId << "," << "1," << bubbleChainId << "," << "," << "," << sequence.size() << "," "#eb4034\n"; // Near red. } } } } // Write the GFA. if(writeGfa) { gfa.write(baseName + ".gfa"); } if(writeCsv) { // Compute N50 for regions assembled diploid and phased. sort(diploidLengths.begin(), diploidLengths.end(), std::greater<uint64_t>()); /* cout << "Diploid lengths: "; copy(diploidLengths.begin(), diploidLengths.end(), ostream_iterator<uint64_t>(cout, " ")); cout << endl; */ uint64_t diploidN50 = 0; uint64_t cumulativeDiploidLength = 0; for(const uint64_t length: diploidLengths) { cumulativeDiploidLength += length; if(cumulativeDiploidLength >= totalDiploidBases/2) { diploidN50 = length; break; } } // Compute N50 for regions assembled haploid in bubble chains sort(haploidLengths.begin(), haploidLengths.end(), std::greater<uint64_t>()); /* cout << "Haploid lengths: "; copy(haploidLengths.begin(), haploidLengths.end(), ostream_iterator<uint64_t>(cout, " ")); cout << endl; */ uint64_t haploidN50 = 0; uint64_t cumulativeHaploidLength = 0; for(const uint64_t length: haploidLengths) { cumulativeHaploidLength += length; if(cumulativeHaploidLength >= totalHaploidBases/2) { haploidN50 = length; break; } } cout << "Assembled diploid in bubble chains and phased: total " << totalDiploidBases << " (" << totalDiploidBases/2 << " per haplotype), N50 " << diploidN50 << "." << endl; cout << "Total length assembled haploid in bubble chains: " << totalHaploidBases << ", N50 " << haploidN50 << "." << endl; cout << "Total genome length assembled in bubble chains, averaged over haplotypes: " << totalDiploidBases/2 + totalHaploidBases << endl; cout << "Total length assembled outside bubble chains: " << totalNonBubbleChainBases << endl; } cout << timestamp << "writePhased ends." << endl; } // Compute the gfa sequence of a bubble chain // by concatenating gfa sequence of the strongest branch of // each of tis edges. void AssemblyGraph2::computeBubbleChainGfaSequence( const BubbleChain& bubbleChain, vector<Base>& sequence ) const { const G& g = *this; sequence.clear(); for(const edge_descriptor e: bubbleChain.edges) { const E& edge = g[e]; const E::Branch& branch = edge.branches[edge.strongestBranchId]; copy(branch.gfaSequence.begin(), branch.gfaSequence.end(), back_inserter(sequence)); } } // Compute the gfa sequence of an unphased region // by concatenating gfa sequence of the strongest branch of // each of this edges. void AssemblyGraph2::computeUnphasedRegionGfaSequence( const BubbleChain& bubbleChain, const BubbleChain::PhasingRegion& phasingRegion, vector<Base>& sequence ) const { const G& g = *this; sequence.clear(); for(uint64_t position=phasingRegion.firstPosition; position<=phasingRegion.lastPosition; position++) { const edge_descriptor e = bubbleChain.edges[position]; const E& edge = g[e]; const E::Branch& branch = edge.branches[edge.strongestBranchId]; copy(branch.gfaSequence.begin(), branch.gfaSequence.end(), back_inserter(sequence)); } } // Compute the gfa sequence of an haplotype of a phased region. void AssemblyGraph2::computePhasedRegionGfaSequence( const BubbleChain& bubbleChain, const BubbleChain::PhasingRegion& phasingRegion, uint64_t haplotype, vector<Base>& sequence ) const { const G& g = *this; sequence.clear(); for(uint64_t position=phasingRegion.firstPosition; position<=phasingRegion.lastPosition; position++) { const edge_descriptor e = bubbleChain.edges[position]; const E& edge = g[e]; if(edge.componentId == std::numeric_limits<uint64_t>::max()) { // This edge is homozygous or unphased. const E::Branch& branch = edge.branches[edge.strongestBranchId]; copy(branch.gfaSequence.begin(), branch.gfaSequence.end(), back_inserter(sequence)); } else { // This edge is diploid and phased. SHASTA_ASSERT(edge.ploidy() == 2); SHASTA_ASSERT(edge.componentId == phasingRegion.componentId); // Figure out which branch we need. uint64_t branchId = 0; if(edge.phase != haplotype) { branchId = 1; } const E::Branch& branch = edge.branches[branchId]; copy(branch.gfaSequence.begin(), branch.gfaSequence.end(), back_inserter(sequence)); } } } string AssemblyGraph2Edge::color(uint64_t branchId) const { if(isBubble()) { // A bad or unphased bubble is grey - darker on the strongest branch. if(isBad or phase == std::numeric_limits<uint64_t>::max()) { if(branchId == strongestBranchId) { return "#808080"; } else { return "#C0C0C0"; } } if(branchId == phase) { return "#bf4040"; // HSL(0,50%,50%) Pink } else { return "#4040bf"; // HSL(240,50%,50%) Blue } } else { // It is not a bubble. return "#808080"; } } // For each bubble edge, compute the number of raw sequence bases // transferred in each direction for gfa output. void AssemblyGraph2::countTransferredBases() { G& g = *this; BGL_FORALL_EDGES(e, g, G) { E& edge = g[e]; edge.backwardTransferCount = 0; edge.forwardTransferCount = 0; // To transfer any bases, the edge // must be a bubble preceded and followed by a single non-bubble. // If these conditions are not satisfied, leave the numbers // of transfered bases at 0. // The edge must be a bubble. if(not edge.isBubble()) { continue; } // v0 must have in-degree and out-degree 1. const vertex_descriptor v0 = source(e, g); if(in_degree(v0, g) != 1) { continue; } if(out_degree(v0, g) != 1) { continue; } // v1 must have in-degree and out-degree 1. const vertex_descriptor v1 = target(e, g); if(in_degree(v1, g) != 1) { continue; } if(out_degree(v1, g) != 1) { continue; } // The previous edge must not be a bubble. in_edge_iterator itPrevious; tie(itPrevious, ignore) = in_edges(v0, g); const E& previousEdge = g[*itPrevious]; if(previousEdge.isBubble()) { continue; } // The next edge must not be a bubble. out_edge_iterator itNext; tie(itNext, ignore) = out_edges(v1, g); const E& nextEdge = g[*itNext]; if(nextEdge.isBubble()) { continue; } // All conditions are satisfied. // Set the number of transfered bases equal to the number // of common identical prefix/suffix bases for all the // branches of this bubble. edge.backwardTransferCount = edge.countCommonPrefixBases(); edge.forwardTransferCount = edge.countCommonSuffixBases(); // Make sure we don't transfer more than the length of the // shortest branch of this edge. uint64_t shortestBranchLength = std::numeric_limits<uint64_t>::max(); for(const E::Branch& branch:edge.branches) { shortestBranchLength = min(shortestBranchLength, uint64_t(branch.rawSequence.size())); } while(true) { if(edge.backwardTransferCount + edge.forwardTransferCount <= shortestBranchLength) { break; } --edge.backwardTransferCount; if(edge.backwardTransferCount + edge.forwardTransferCount <= shortestBranchLength) { break; } --edge.forwardTransferCount; } } } // Store GFA sequence in each edge. // It is obtained from raw sequence by transferring identical bases // of common sequence between all branches of a bubble to the // preceding or following non-bubble edge. void AssemblyGraph2::storeGfaSequence() { cout << timestamp << "storeGfaSequence begins." << endl; G& g = *this; // Count the number of sequence bases transferred forward/backward // from each bubble edge to adjacent non-bubble edges. countTransferredBases(); BGL_FORALL_EDGES(e, g, G) { E& edge = g[e]; const vertex_descriptor v0 = source(e, g); const vertex_descriptor v1 = target(e, g); for(uint64_t branchId=0; branchId<edge.ploidy(); branchId++) { E::Branch& branch = edge.branches[branchId]; branch.gfaSequence.clear(); // Add the sequence transferred forward by the preceding bubble, if appropriate. if(not edge.isBubble()) { if(in_degree(v0, g)==1 and out_degree(v0, g)==1) { in_edge_iterator it; tie(it, ignore) = in_edges(v0, g); const E& previousEdge = g[*it]; if(previousEdge.isBubble()) { const vector<Base>& s = previousEdge.branches.front().rawSequence; copy(s.end() - previousEdge.forwardTransferCount, s.end(), back_inserter(branch.gfaSequence)); } } } // Add the sequence of this branch, excluding sequence // that was transferred backward or forward. copy( branch.rawSequence.begin() + edge.backwardTransferCount, branch.rawSequence.end() - edge.forwardTransferCount, back_inserter(branch.gfaSequence)); // Add the sequence transferred backward by the following bubble, if appropriate. if(not edge.isBubble()) { if(in_degree(v1, g)==1 and out_degree(v1, g)==1) { out_edge_iterator it; tie(it, ignore) = out_edges(v1, g); const E& nextEdge = g[*it]; if(nextEdge.isBubble()) { const vector<Base>& s = nextEdge.branches.front().rawSequence; copy(s.begin(), s.begin() + nextEdge.backwardTransferCount, back_inserter(branch.gfaSequence)); } } } } } cout << timestamp << "storeGfaSequence ends." << endl; } // Return the number of raw bases of sequence identical between // all branches at the beginning. uint64_t AssemblyGraph2Edge::countCommonPrefixBases() const { SHASTA_ASSERT(isBubble()); const vector<Base>& firstRawSequence = branches.front().rawSequence; for(uint64_t position=0; position<firstRawSequence.size(); position++) { const Base base = firstRawSequence[position]; for(uint64_t branchId=1; branchId<branches.size(); branchId++) { const vector<Base>& rawSequence = branches[branchId].rawSequence; if(position == rawSequence.size()) { return position; } if(rawSequence[position] != base) { return position; } } } return firstRawSequence.size(); } // Return the number of raw bases of sequence identical between // all branches at the end. uint64_t AssemblyGraph2Edge::countCommonSuffixBases() const { SHASTA_ASSERT(isBubble()); const vector<Base>& firstRawSequence = branches.front().rawSequence; for(uint64_t position=0; position<firstRawSequence.size(); position++) { const Base base = firstRawSequence[firstRawSequence.size() - 1 - position]; for(uint64_t branchId=1; branchId<branches.size(); branchId++) { const vector<Base>& rawSequence = branches[branchId].rawSequence; if(position == rawSequence.size()) { return position; } if(rawSequence[rawSequence.size() - 1 - position] != base) { return position; } } } return firstRawSequence.size(); } // Figure out if this is a bubble is caused by copy number // differences in repeats of period up to maxPeriod. // If this is the case, returns the shortest period for which this is true. // Otherwise, returns 0. void AssemblyGraph2Edge::computeCopyNumberDifferencePeriod(uint64_t maxPeriod) { if(not isBubble()) { period = 0; } // Check all pairs of branches. vector<uint64_t> periods; for(uint64_t i=0; i<branches.size()-1; i++) { const vector<Base>& iSequence = branches[i].rawSequence; for(uint64_t j=i+1; j<branches.size(); j++) { const vector<Base>& jSequence = branches[j].rawSequence; const uint64_t pairPeriod = shasta::isCopyNumberDifference(iSequence, jSequence, maxPeriod); if(pairPeriod == 0) { period = 0; return; } periods.push_back(pairPeriod); } } deduplicate(periods); if(periods.size() == 1) { period = periods.front(); } else { period = 0; } } // Fill in orientedReads and average/minimum coverage. void AssemblyGraph2Edge::Branch::storeReadInformation(const MarkerGraph& markerGraph) { minimumCoverage = std::numeric_limits<uint64_t>::max(); coverageSum = 0; orientedReadIds.clear(); // Loop over the marker graph path of this branch. for(MarkerGraph::EdgeId edgeId: path) { // Loop over the marker intervals of this edge. const span<const MarkerInterval> markerIntervals = markerGraph.edgeMarkerIntervals[edgeId]; for(const MarkerInterval& markerInterval: markerIntervals) { orientedReadIds.push_back(markerInterval.orientedReadId); } // Update coverage. minimumCoverage = min(minimumCoverage, uint64_t(markerIntervals.size())); coverageSum += markerIntervals.size(); } deduplicate(orientedReadIds); } // Store read information on all edges. void AssemblyGraph2::storeReadInformation() { cout << timestamp << "storeReadInformation begins." << endl; G& g = *this; BGL_FORALL_EDGES(e, g, G) { g[e].storeReadInformation(markerGraph); } cout << timestamp << "storeReadInformation ends." << endl; } // Store read information on all branches. void AssemblyGraph2Edge::storeReadInformation(const MarkerGraph& markerGraph) { for(Branch& branch: branches) { branch.storeReadInformation(markerGraph); } findStrongestBranch(); } void AssemblyGraph2Edge::findStrongestBranch() { SHASTA_ASSERT(not branches.empty()); strongestBranchId = 0; uint64_t strongestBranchCoverage = branches.front().averageCoverage(); for(uint64_t branchId=0; branchId<branches.size(); branchId++) { const uint64_t coverage = branches[branchId].averageCoverage(); if (coverage > strongestBranchCoverage) { strongestBranchId = branchId; strongestBranchCoverage = coverage; } } } void AssemblyGraph2::createBubbleGraph( uint64_t readCount, uint64_t phasingMinReadCount, size_t threadCount) { cout << timestamp << "createBubbleGraph begins." << endl; G& g = *this; // Each diploid bubble in the AssemblyGraph2 generates a vertex, // except for the repeat count bubbles. BGL_FORALL_EDGES(e, g, G) { const E& edge = g[e]; // If this is not a diploid bubble, skip. if(edge.ploidy() != 2) { continue; } // If this is a repeat count bubble, skip. if(edge.period != 0) { continue; } // If this is a degenerate bubble, skip. if(edge.branches[0].rawSequence == edge.branches[1].rawSequence) { continue; } add_vertex(BubbleGraphVertex(e, edge), bubbleGraph); } cout << timestamp << "Creating the oriented reads table." << endl; bubbleGraph.createOrientedReadsTable(readCount); cout << timestamp << "Creating bubble graph edges." << endl; // bubbleGraph.createEdges(phasingMinReadCount); bubbleGraph.createEdgesParallel(phasingMinReadCount, threadCount); bubbleGraph.orientedReadsTable.clear(); cout << timestamp << "createBubbleGraph ends." << endl; } AssemblyGraph2::BubbleGraphVertex::BubbleGraphVertex( AssemblyGraph2::edge_descriptor e, const AssemblyGraph2Edge& edge) : e(e), id(edge.id) { SHASTA_ASSERT(edge.ploidy() == 2); const vector<OrientedReadId>& orientedReadIds0 = edge.branches[0].orientedReadIds; const vector<OrientedReadId>& orientedReadIds1 = edge.branches[1].orientedReadIds; // Joint loop over the OrientedReadIds of the two sides. const auto begin0 = orientedReadIds0.begin(); const auto begin1 = orientedReadIds1.begin(); const auto end0 = orientedReadIds0.end(); const auto end1 = orientedReadIds1.end(); auto it0 = begin0; auto it1 = begin1; while(true) { // If both at end, break. if(it0 == end0 and it1 == end1) { break; } // If 1 at end but 0 is not, add all remaining orientedReadIds0. if(it1==end1) { for(; it0 != end0; ++it0) { orientedReadIds.push_back(make_pair(*it0, 0)); } break; } // If 0 at end but 1 is not, add all remaining orientedReadIds1. if(it0==end0) { for(; it1 != end1; ++it1) { orientedReadIds.push_back(make_pair(*it1, 1)); } break; } // Neither of them is at end. if(*it0 < *it1) { orientedReadIds.push_back(make_pair(*it0, 0)); ++it0; } else if(*it1 < *it0) { orientedReadIds.push_back(make_pair(*it1, 1)); ++it1; } else { // It is on both sides. don't store it. ++it0; ++it1; } } } void AssemblyGraph2::BubbleGraph::createOrientedReadsTable(uint64_t readCount) { BubbleGraph& bubbleGraph = *this; orientedReadsTable.clear(); orientedReadsTable.resize(readCount * 2); BGL_FORALL_VERTICES(v, bubbleGraph, BubbleGraph) { for(const auto& p: bubbleGraph[v].orientedReadIds) { const OrientedReadId orientedReadId = p.first; const uint64_t side = p.second; orientedReadsTable[orientedReadId.getValue()].push_back(make_pair(v, side)); } } } void AssemblyGraph2::BubbleGraph::createDynamicOrientedReadsTable(uint64_t readCount) { BubbleGraph& bubbleGraph = *this; dynamicOrientedReadsTable.clear(); dynamicOrientedReadsTable.resize(readCount * 2); BGL_FORALL_VERTICES(v, bubbleGraph, BubbleGraph) { for(const auto& p: bubbleGraph[v].orientedReadIds) { const OrientedReadId orientedReadId = p.first; const uint64_t side = p.second; dynamicOrientedReadsTable[orientedReadId.getValue()].insert(make_pair(v, side)); } } } void AssemblyGraph2::BubbleGraph::updateDynamicOrientedReadsTableForRemoval( BubbleGraph::vertex_descriptor v) { BubbleGraph& bubbleGraph = *this; for(const auto& p: bubbleGraph[v].orientedReadIds) { const OrientedReadId orientedReadId = p.first; const uint64_t side = p.second; dynamicOrientedReadsTable[orientedReadId.getValue()].erase(make_pair(v, side)); } } void AssemblyGraph2::BubbleGraph::updateDynamicOrientedReadsTableForAddition( BubbleGraph::vertex_descriptor v) { BubbleGraph& bubbleGraph = *this; for(const auto& p: bubbleGraph[v].orientedReadIds) { const OrientedReadId orientedReadId = p.first; const uint64_t side = p.second; dynamicOrientedReadsTable[orientedReadId.getValue()].insert(make_pair(v, side)); } } // Use the dynamic oriented reads table to create edges // for a newly added vertex. void AssemblyGraph2::BubbleGraph::createNewEdges( BubbleGraph::vertex_descriptor v0, uint64_t phasingMinReadCount) { BubbleGraph& bubbleGraph = *this; SHASTA_ASSERT(out_degree(v0, bubbleGraph) == 0); const BubbleGraphVertex& vertex0 = bubbleGraph[v0]; // Edge candidates and their phasing matrix. using Matrix = array<array<uint64_t, 2>, 2>; Matrix zeroMatrix; zeroMatrix[0] = {0, 0}; zeroMatrix[1] = {0, 0}; std::map<vertex_descriptor, Matrix> edgeCandidates; // To find edge candidates, loop over oriented reads of this vertex. for(const auto& p0: vertex0.orientedReadIds) { const OrientedReadId orientedReadId = p0.first; const uint64_t side0 = p0.second; for(const auto& p1: dynamicOrientedReadsTable[orientedReadId.getValue()]) { const vertex_descriptor v1 = p1.first; if(v1 == v0) { continue; } const uint64_t side1 = p1.second; auto it = edgeCandidates.find(v1); if(it == edgeCandidates.end()) { tie(it, ignore) = edgeCandidates.insert(make_pair(v1, zeroMatrix)); } Matrix& matrix = it->second; ++matrix[side0][side1]; } } // Loop over edge candidates. for(const auto& p: edgeCandidates) { const vertex_descriptor v1 = p.first; const Matrix& matrix = p.second; // Check that we have enough supporting reads. const uint64_t sum = matrix[0][0] + matrix[0][1] + matrix[1][0] + matrix[1][1]; if(sum < phasingMinReadCount) { continue; } // Create the new edge. BubbleGraphEdge edge; edge.matrix = matrix; add_edge(v0, v1, edge, bubbleGraph); } } void AssemblyGraph2::BubbleGraph::createEdges(uint64_t phasingMinReadCount) { BubbleGraph& bubbleGraph = *this; BGL_FORALL_VERTICES(vA, bubbleGraph, BubbleGraph) { const BubbleGraphVertex& vertexA = bubbleGraph[vA]; const uint64_t idA = vertexA.id; for(const auto& p: vertexA.orientedReadIds) { const OrientedReadId orientedReadId = p.first; const uint64_t sideA = p.second; const auto& v = orientedReadsTable[orientedReadId.getValue()]; for(const auto& p: v) { const vertex_descriptor vB = p.first; const BubbleGraphVertex& vertexB = bubbleGraph[vB]; const uint64_t idB = vertexB.id; // Don't add it twice. if(idB <= idA) { continue; } const uint64_t sideB = p.second; // Locate the edge between these two bubbles, // creating it if necessary. BubbleGraph::edge_descriptor e; bool edgeWasFound = false; tie(e, edgeWasFound) = edge(vA, vB, bubbleGraph); if(not edgeWasFound) { tie(e, edgeWasFound) = add_edge(vA, vB, bubbleGraph); } SHASTA_ASSERT(edgeWasFound); // Update the matrix. BubbleGraphEdge& edge = bubbleGraph[e]; ++edge.matrix[sideA][sideB]; } } } removeWeakEdges(phasingMinReadCount); } // Stil sequential for now. void AssemblyGraph2::BubbleGraph::createEdgesParallel( uint64_t phasingMinReadCount, size_t threadCount) { BubbleGraph& bubbleGraph = *this; // Create a vector of all vertices, to be processed // one by one in parallel. createEdgesParallelData.allVertices.clear(); BGL_FORALL_VERTICES(vA, bubbleGraph, BubbleGraph) { createEdgesParallelData.allVertices.push_back(vA); } createEdgesParallelData.phasingMinReadCount = phasingMinReadCount; // Process all vertices in parallel. const uint64_t batchSize = 1000; setupLoadBalancing(createEdgesParallelData.allVertices.size(), batchSize); runThreads(&BubbleGraph::createEdgesParallelThreadFunction, threadCount); } void AssemblyGraph2::BubbleGraph::createEdgesParallelThreadFunction(size_t threadId) { const uint64_t phasingMinReadCount = createEdgesParallelData.phasingMinReadCount; vector<CreateEdgesParallelData::EdgeData> edgeData; // Loop over all batches assigned to this thread. uint64_t begin, end; while(getNextBatch(begin, end)) { // Loop over all vertices assigned to this batch. for(uint64_t i=begin; i!=end; ++i) { createEdges(createEdgesParallelData.allVertices[i], phasingMinReadCount, edgeData); } } } // Create edges between vertex vA and vertices vB with id greater // that the id of vA. void AssemblyGraph2::BubbleGraph::createEdges( BubbleGraph::vertex_descriptor vA, uint64_t phasingMinReadCount, vector<CreateEdgesParallelData::EdgeData>& edgeData) { BubbleGraph& bubbleGraph = *this; const BubbleGraphVertex& vertexA = bubbleGraph[vA]; const uint64_t idA = vertexA.id; // Gather EdgeData for this vA. edgeData.clear(); for(const auto& p: vertexA.orientedReadIds) { const OrientedReadId orientedReadId = p.first; const uint64_t sideA = p.second; const auto& v = orientedReadsTable[orientedReadId.getValue()]; for(const auto& p: v) { const vertex_descriptor vB = p.first; const BubbleGraphVertex& vertexB = bubbleGraph[vB]; const uint64_t idB = vertexB.id; // Don't add it twice. if(idB <= idA) { continue; } const uint64_t sideB = p.second; edgeData.push_back({vB, sideA, sideB}); } } // Sort the EdgeData by vB. sort(edgeData.begin(), edgeData.end()); // Each streak with the same vB generates an edge, if there // is a sufficient number of reads. for(auto it=edgeData.begin(); it!=edgeData.end(); /* Increment later */) { auto streakBegin = it; auto streakEnd = streakBegin; const BubbleGraph::vertex_descriptor vB = streakBegin->vB; while((streakEnd != edgeData.end()) and (streakEnd->vB == vB)) { ++streakEnd; } // If this streak is sufficiently long, it generates an edge. const uint64_t streakLength = uint64_t(streakEnd - streakBegin); if(streakLength >= phasingMinReadCount) { BubbleGraphEdge edge; for(auto jt=streakBegin; jt!=streakEnd; ++jt) { ++edge.matrix[jt->sideA][jt->sideB]; } std::lock_guard<std::mutex> lock(mutex); add_edge(vA, vB, edge, bubbleGraph); } // Prepare to process the next streak. it = streakEnd; } } // Remove edges with too few reads. void AssemblyGraph2::BubbleGraph::removeWeakEdges(uint64_t minReadCount) { BubbleGraph& bubbleGraph = *this; vector<BubbleGraph::edge_descriptor> edgesToBeRemoved; BGL_FORALL_EDGES(e, bubbleGraph, BubbleGraph) { if(bubbleGraph[e].totalCount() < minReadCount) { edgesToBeRemoved.push_back(e); } } for(const BubbleGraph::edge_descriptor e: edgesToBeRemoved) { boost::remove_edge(e, bubbleGraph); } } void AssemblyGraph2::BubbleGraph::computeConnectedComponents() { using boost::connected_components; using boost::get; using boost::color_map; using G = BubbleGraph; G& g = *this; std::map<vertex_descriptor, uint64_t> colorMap; connected_components(g, get(&BubbleGraphVertex::componentId, g), color_map(boost::make_assoc_property_map(colorMap))); // Gather the vertices in each connected component. std::map<uint64_t, vector<vertex_descriptor> > componentMap; BGL_FORALL_VERTICES(v, g, G) { componentMap[g[v].componentId].push_back(v); } cout << "The BubbleGraph has " << componentMap.size() << " connected components of sizes:"; connectedComponents.clear(); for(const auto& p: componentMap) { cout << " " << p.second.size(); connectedComponents.push_back(p.second); } cout << endl; } void AssemblyGraph2::BubbleGraph::writeHtml(const string& fileName) { using G = BubbleGraph; G& g = *this; /* // Create a filtered BubbleGraph, containing only the edges // with relativePhase() >= minRelativePhase. const double minRelativePhase = 0.; using FilteredGraph = boost::filtered_graph<G, BubbleGraphEdgePredicate1>; FilteredGraph filteredGraph(g, BubbleGraphEdgePredicate1(g, minRelativePhase)); // Compute the layout of the filtered graph. std::map<FilteredGraph::vertex_descriptor, array<double, 2> > positionMap; SHASTA_ASSERT(computeLayout(filteredGraph, "sfdp", 600., positionMap) == ComputeLayoutReturnCode::Success); BGL_FORALL_VERTICES(v, filteredGraph, FilteredGraph) { filteredGraph[v].position = positionMap[v]; } */ // Compute the layout. std::map<BubbleGraph::vertex_descriptor, array<double, 2> > positionMap; SHASTA_ASSERT(computeLayout(g, "sfdp", 600., positionMap) == ComputeLayoutReturnCode::Success); BGL_FORALL_VERTICES(v, g, G) { g[v].position = positionMap[v]; } // Graphics scaling. double xMin = std::numeric_limits<double>::max(); double xMax = std::numeric_limits<double>::min(); double yMin = std::numeric_limits<double>::max(); double yMax = std::numeric_limits<double>::min(); BGL_FORALL_VERTICES_T(v, g, G) { const auto& position = g[v].position; xMin = min(xMin, position[0]); xMax = max(xMax, position[0]); yMin = min(yMin, position[1]); yMax = max(yMax, position[1]); } const double xyRange = max(xMax-xMin, yMax-yMin); const int svgSize = 10000; const double vertexRadiusPixels = 3.; const double vertexRadius = vertexRadiusPixels * xyRange / double(svgSize); const double edgeThicknessPixels = 1.; const double edgeThickness = edgeThicknessPixels * xyRange / double(svgSize); // Vertex attributes. Color by discordant ratio. std::map<G::vertex_descriptor, WriteGraph::VertexAttributes> vertexAttributes; BGL_FORALL_VERTICES(v, g, G) { const double d = discordantRatio(v); const double dRed = 0.3; const double hue = max(0., 120. * (1. - d / dRed)); // d=0: green, d=dRed:red auto& attributes = vertexAttributes[v]; attributes.color = "hsl(" + to_string(int(hue)) + ",50%,50%)"; attributes.radius = vertexRadius; attributes.tooltip = to_string(g[v].id); } // Edge attributes. Color by ambiguity. std::map<G::edge_descriptor, WriteGraph::EdgeAttributes> edgeAttributes; BGL_FORALL_EDGES(e, g, G) { const BubbleGraphEdge& edge = g[e]; const double ambiguity = edge.ambiguity(); const double hue = (1. - ambiguity) * 120.; /// Goes from 0 (red) to 120 (green). auto& attributes = edgeAttributes[e]; attributes.color = "hsl(" + to_string(int(hue)) + ",50%,50%)"; attributes.thickness = edgeThickness; } // Write it out as svg in html. ofstream out(fileName); out << "<html><body>"; WriteGraph::writeSvg( g, "BubbleGraph", svgSize, svgSize, vertexAttributes, edgeAttributes, out); out << "</body></html>"; } void AssemblyGraph2::BubbleGraph::writeGraphviz(const string& fileName) const { const BubbleGraph& bubbleGraph = *this; ofstream out(fileName); out << "graph BubbleGraph {\n" "node [shape=point];\n"; // Vertices, colored by discordant ratio. // Green if discordant ratio is 0. // Red if redDiscordantRatio or more. // const double redDiscordantRatio = 0.3; BGL_FORALL_VERTICES(v, bubbleGraph, BubbleGraph) { const BubbleGraphVertex& vertex = bubbleGraph[v]; // const double d = bubbleGraph.discordantRatio(v); // const double hue = max(0., (1. - d / redDiscordantRatio) / 3.); out << vertex.id << // " [color=\"" << hue << " 1 1\"]" ";\n"; } // Edges, colored by ambiguity and semi-transparent. // Green if ambiguity is 0. // Red if ambiguity is redAmbiguity or more. const double redAmbiguity = 0.5; BGL_FORALL_EDGES(e, bubbleGraph, BubbleGraph) { const BubbleGraphEdge& edge = bubbleGraph[e]; const vertex_descriptor v0 = source(e, bubbleGraph); const vertex_descriptor v1 = target(e, bubbleGraph); const double ambiguity = edge.ambiguity(); const double hue = max(0., (1. - ambiguity / redAmbiguity) / 3.); out << bubbleGraph[v0].id << "--" << bubbleGraph[v1].id << " [color=\"" << hue << " 1 1 0.5\"" " tooltip=\"" << bubbleGraph[v0].id << " " << bubbleGraph[v1].id << " " << ambiguity << "\"];\n"; } out << "}\n"; } // Post-phasing. void AssemblyGraph2::BubbleGraph::writeHtml( const string& fileName, const std::set<edge_descriptor>& treeEdges, bool onlyShowUnhappyEdges) { BubbleGraph& g = *this; // Create a filtered BubbleGraph, containing only the tree edges // and the edges with relativePhase() >= minRelativePhase. const double minRelativePhase = 0.; using FilteredGraph = boost::filtered_graph<BubbleGraph, BubbleGraphEdgePredicate2>; FilteredGraph filteredGraph(g, BubbleGraphEdgePredicate2(g, minRelativePhase, treeEdges)); // Compute the layout of the filtered graph. // This should mostly separate the two phases. std::map<FilteredGraph::vertex_descriptor, array<double, 2> > positionMap; SHASTA_ASSERT(computeLayout(filteredGraph, "sfdp", 600., positionMap) == ComputeLayoutReturnCode::Success); BGL_FORALL_VERTICES(v, filteredGraph, FilteredGraph) { filteredGraph[v].position = positionMap[v]; } // Graphics scaling. double xMin = std::numeric_limits<double>::max(); double xMax = std::numeric_limits<double>::min(); double yMin = std::numeric_limits<double>::max(); double yMax = std::numeric_limits<double>::min(); BGL_FORALL_VERTICES_T(v, g, G) { const auto& position = g[v].position; xMin = min(xMin, position[0]); xMax = max(xMax, position[0]); yMin = min(yMin, position[1]); yMax = max(yMax, position[1]); } const double xyRange = max(xMax-xMin, yMax-yMin); const int svgSize = 1600; const double vertexRadiusPixels = 3.; const double vertexRadius = vertexRadiusPixels * xyRange / double(svgSize); const double edgeThicknessPixels = 0.3; const double edgeThickness = edgeThicknessPixels * xyRange / double(svgSize); // Vertex attributes. Color by phase. std::map<G::vertex_descriptor, WriteGraph::VertexAttributes> vertexAttributes; BGL_FORALL_VERTICES(v, g, BubbleGraph) { auto& attributes = vertexAttributes[v]; if(g[v].phase == 0) { attributes.color = "hsl(240,50%,50%)"; } else { attributes.color = "hsl(300,50%,50%)"; } attributes.radius = vertexRadius; attributes.tooltip = to_string(g[v].id); } // Edge attributes. std::map<BubbleGraph::edge_descriptor, WriteGraph::EdgeAttributes> edgeAttributes; BGL_FORALL_EDGES(e, g, BubbleGraph) { const double relativePhase = g[e].relativePhase(); const double hue = (1. + relativePhase) * 60.; /// Goes from 0 (red) to 120 (green). auto& attributes = edgeAttributes[e]; attributes.color = "hsla(" + to_string(int(hue)) + ",50%,50%,50%)"; attributes.thickness = edgeThickness; if(onlyShowUnhappyEdges) { if(g.edgeIsHappy(e)) { attributes.color = "hsla(" + to_string(int(hue)) + ",50%,50%,0%)"; } else { attributes.thickness *= 20.; } } } // Write it out as svg in html. ofstream out(fileName); out << "<html><body>"; WriteGraph::writeSvg( g, "BubbleGraph", svgSize, svgSize, vertexAttributes, edgeAttributes, out); out << "</body></html>"; } // Return true if the give edge has relative phase consistent // with the phases assigned to its two vertices. bool AssemblyGraph2::BubbleGraph::edgeIsHappy(BubbleGraph::edge_descriptor e) const { const BubbleGraph& g = *this; const vertex_descriptor v0 = source(e, g); const vertex_descriptor v1 = target(e, g); const uint64_t phase0 = g[v0].phase; const uint64_t phase1 = g[v1].phase; const double relativePhase = g[e].relativePhase(); if(phase0 == phase1) { return relativePhase > 0.; } else { return relativePhase < 0.; } } double AssemblyGraph2::BubbleGraph::discordantRatio(vertex_descriptor v) const { const BubbleGraph& bubbleGraph = *this; uint64_t concordantSum = 0; uint64_t discordantSum = 0; BGL_FORALL_OUTEDGES(v, e, bubbleGraph, BubbleGraph) { const BubbleGraphEdge& edge = bubbleGraph[e]; concordantSum += edge.concordantCount(); discordantSum += edge.discordantCount(); } const double denominator = double(concordantSum + discordantSum); if(denominator == 0.) { return 0.; } else { return double(discordantSum) / denominator; } } void AssemblyGraph2::BubbleGraph::removeWeakVertices( double discordantRatioThreshold, vector<AssemblyGraph2::edge_descriptor>& badBubbles) { BubbleGraph& bubbleGraph = *this; const bool debug = false; vector<BubbleGraph::vertex_descriptor> verticesToBeRemoved; badBubbles.clear(); BGL_FORALL_VERTICES(v, bubbleGraph, BubbleGraph) { const double ratio = discordantRatio(v); if(ratio > discordantRatioThreshold) { verticesToBeRemoved.push_back(v); badBubbles.push_back(bubbleGraph[v].e); if(debug) { cout << "Removed bubble " << bubbleGraph[v].id << " with discordant ratio " << ratio << endl; } } } for(const BubbleGraph::vertex_descriptor v: verticesToBeRemoved) { clear_vertex(v, bubbleGraph); remove_vertex(v, bubbleGraph); } } void AssemblyGraph2::BubbleGraph::writeVerticesCsv(const string& fileName) const { const BubbleGraph& bubbleGraph = *this; ofstream csv(fileName); csv << "BubbleId\n"; BGL_FORALL_VERTICES(v, bubbleGraph, BubbleGraph) { csv << bubbleGraph[v].id << "\n"; } } void AssemblyGraph2::BubbleGraph::writeEdgesCsv(const string& fileName) const { const BubbleGraph& bubbleGraph = *this; ofstream csv(fileName); csv << "BubbleIdA,BubbleIdB,m00,m11,m01,m10\n"; BGL_FORALL_EDGES(e, bubbleGraph, BubbleGraph) { const BubbleGraphEdge& edge = bubbleGraph[e]; uint64_t idA = bubbleGraph[source(e, bubbleGraph)].id; uint64_t idB = bubbleGraph[target(e, bubbleGraph)].id; if(idB < idA) { std::swap(idA, idB); } csv << idA << ","; csv << idB << ","; csv << edge.matrix[0][0] << ","; csv << edge.matrix[1][1] << ","; csv << edge.matrix[0][1] << ","; csv << edge.matrix[1][0] << "\n"; } } // Create a new BubbleGraph from a given connected component. void AssemblyGraph2::BubbleGraph::extractComponent( uint64_t componentId, BubbleGraph& componentGraph) const { const BubbleGraph& bubbleGraph = *this; SHASTA_ASSERT(componentId < connectedComponents.size()); const vector<vertex_descriptor>& componentVertices = connectedComponents[componentId]; SHASTA_ASSERT(num_vertices(componentGraph) == 0); SHASTA_ASSERT(num_edges(componentGraph) == 0); // Map with: // Key = vertex_descriptor in the full graph. // Value = vertex descriptor in the component graph. std::map<vertex_descriptor, vertex_descriptor> vertexMap; // Create the vertices. for(const vertex_descriptor v: componentVertices) { const vertex_descriptor vc = add_vertex(bubbleGraph[v], componentGraph); vertexMap.insert(make_pair(v, vc)); } // Create the edges. for(const vertex_descriptor v0: componentVertices) { const auto it0 = vertexMap.find(v0); SHASTA_ASSERT(it0 != vertexMap.end()); const vertex_descriptor vc0 = it0->second; BGL_FORALL_OUTEDGES(v0, e01, bubbleGraph, BubbleGraph) { const vertex_descriptor v1 = target(e01, bubbleGraph); if(bubbleGraph[v0].id < bubbleGraph[v1].id) { const auto it1 = vertexMap.find(v1); SHASTA_ASSERT(it1 != vertexMap.end()); const vertex_descriptor vc1 = it1->second; add_edge(vc0, vc1, bubbleGraph[e01], componentGraph); } } } } // Use each connected component of the bubble graph to phase the bubbles. void AssemblyGraph2::phase(size_t threadCount) { cout << timestamp << "phase begins." << endl; cout << "The bubble graph has " << num_vertices(bubbleGraph) << " vertices." << endl; // In parallel, phase each connected component of the BubbleGraph. // each thread writes the results in its portion of the global BubbleGraph. const uint64_t batchSize = 1; setupLoadBalancing(bubbleGraph.connectedComponents.size(), batchSize); cout << timestamp << "Multithreaded phasing for " << bubbleGraph.connectedComponents.size() << " connected components of the bubble graph." << endl; runThreads(&AssemblyGraph2::phaseThreadFunction, threadCount); cout << timestamp << "Multithreaded phasing ends." << endl; // Check that all vertices of the global BubbleGraph are phased // and copy the phasing information to the AssemvblyGraph2Edges. BGL_FORALL_VERTICES(v, bubbleGraph, BubbleGraph) { const BubbleGraphVertex& bubbleGraphVertex = bubbleGraph[v]; const uint64_t componentId = bubbleGraphVertex.componentId; SHASTA_ASSERT(componentId != std::numeric_limits<uint64_t>::max()); const uint64_t phase = bubbleGraphVertex.phase; SHASTA_ASSERT(phase != BubbleGraphVertex::invalidPhase); AssemblyGraph2Edge& assemblyGraph2Edge = (*this)[bubbleGraphVertex.e]; assemblyGraph2Edge.componentId = componentId; assemblyGraph2Edge.phase = phase; } cout << timestamp << "phase ends." << endl; } void AssemblyGraph2::phaseThreadFunction(size_t threadId) { // Loop over batchEs assigned to this thread. uint64_t begin, end; while(getNextBatch(begin, end)) { // Loop over BubbleGraph connected components that belong to this batch. for(uint64_t componentId=begin; componentId!=end; componentId++) { phaseBubbleGraphComponent(componentId); } } } void AssemblyGraph2::phaseBubbleGraphComponent(uint64_t componentId) { const bool debug = false; BubbleGraph componentGraph; bubbleGraph.extractComponent(componentId, componentGraph); if(debug) { std::lock_guard<std::mutex> lock(mutex); cout << "Processing connected component " << componentId << " with " << num_vertices(componentGraph) << " vertices and " << num_edges(componentGraph) << " edges." << endl; componentGraph.writeGraphviz("Component-" + to_string(componentId) + ".dot"); } // Compute an index map, needed below, which maps vertices to integers. std::map<BubbleGraph::vertex_descriptor, uint64_t> indexMap; uint64_t vertexIndex = 0; BGL_FORALL_VERTICES(v, componentGraph, BubbleGraph) { indexMap.insert(make_pair(v, vertexIndex++)); } // Compute a minimal spanning tree that minimizes // the sum of edge weights defined as // difference discordantCount() - concordantCount() std::map<BubbleGraph::edge_descriptor, int64_t> weightMap; BGL_FORALL_EDGES(e, componentGraph, BubbleGraph) { const BubbleGraphEdge& edge = componentGraph[e]; const int64_t weight = int64_t(edge.discordantCount()) - int64_t(edge.concordantCount()); weightMap.insert(make_pair(e, weight)); } std::set<BubbleGraph::edge_descriptor> treeEdges; boost::kruskal_minimum_spanning_tree(componentGraph, std::inserter(treeEdges, treeEdges.begin()), weight_map(boost::make_assoc_property_map(weightMap)). vertex_index_map(boost::make_assoc_property_map(indexMap))); SHASTA_ASSERT(treeEdges.size() == indexMap.size() - 1); // Write out the tree edges to csv. if(debug) { ofstream csv("Component-" + to_string(componentId) + "-TreeEdges.csv"); csv << "BubbleId0,BubbleId1,Diagonal,OffDiagonal,Concordant,Discordant,Weight\n"; for(const BubbleGraph::edge_descriptor e: treeEdges) { const BubbleGraphEdge& edge = componentGraph[e]; const BubbleGraph::vertex_descriptor v0 = source(e, bubbleGraph); const BubbleGraph::vertex_descriptor v1 = target(e, bubbleGraph); csv << bubbleGraph[v0].id << ","; csv << bubbleGraph[v1].id << ","; csv << edge.diagonalCount() << ","; csv << edge.offDiagonalCount() << ","; csv << edge.concordantCount() << ","; csv << edge.discordantCount() << ","; csv << edge.concordantCount() - edge.discordantCount() << "\n"; } } // To phase, do a BFS on the spanning tree of the componentGraph. // Assign phases consistent with the spanning tree edges. std::queue<BubbleGraph::vertex_descriptor> q; BubbleGraph::vertex_iterator it; tie(it, ignore) = vertices(componentGraph); BubbleGraph::vertex_descriptor vStart = *it; q.push(vStart); componentGraph[vStart].phase = 0; while(not q.empty()) { // Dequeue a vertex. const BubbleGraph::vertex_descriptor v0 = q.front(); // cout << "Dequeued " << (*this)[componentGraph[v0].e].id << " " << componentGraph[v0].phase << endl; q.pop(); const uint64_t phase0 = componentGraph[v0].phase; SHASTA_ASSERT(phase0 != BubbleGraphVertex::invalidPhase); // Loop over tree edges. BGL_FORALL_OUTEDGES(v0, e01, componentGraph, BubbleGraph) { if(treeEdges.find(e01) == treeEdges.end()) { continue; } const double relativePhase = componentGraph[e01].relativePhase(); const BubbleGraph::vertex_descriptor v1 = target(e01, componentGraph); // cout << "Found " << (*this)[componentGraph[v1].e].id << " " << componentGraph[v1].phase << endl; // cout << "Relative phase " << relativePhase << endl; uint64_t& phase1 = componentGraph[v1].phase; if(phase1 == BubbleGraphVertex::invalidPhase) { if(relativePhase > 0.) { phase1 = phase0; } else { phase1 = 1 - phase0; } q.push(v1); // cout << "Enqueued " << (*this)[componentGraph[v1].e].id << " " << componentGraph[v1].phase << endl; } else { // We already encountered this vertex. Just check // that its phase is consistent with the edge. const uint64_t& phase1 = componentGraph[v1].phase; if(relativePhase > 0.) { SHASTA_ASSERT(phase1 == phase0); } else { SHASTA_ASSERT(phase1 == 1 - phase0); } } } } uint64_t unhappyCount = 0; uint64_t totalCount = 0; BGL_FORALL_EDGES(e, componentGraph, BubbleGraph) { ++totalCount; if(not componentGraph.edgeIsHappy(e)) { ++unhappyCount; } } if(debug) { std::lock_guard<std::mutex> lock(mutex); cout << "Found " << unhappyCount << " edges inconsistent with computed bubble phasing " " out of " << totalCount << " edges in connected component " << componentId << endl; componentGraph.writeHtml("Component-" + to_string(componentId) + ".html", treeEdges, false); componentGraph.writeHtml("Component-" + to_string(componentId) + "-Unhappy.html", treeEdges, true); } // Copy the phasing to the global bubble graph. { std::lock_guard<std::mutex> lock(mutex); uint64_t i = 0; BGL_FORALL_VERTICES(v, componentGraph, BubbleGraph) { BubbleGraph::vertex_descriptor vGlobal = bubbleGraph.connectedComponents[componentId][i++]; bubbleGraph[vGlobal].phase = bubbleGraph[v].phase; SHASTA_ASSERT(bubbleGraph[vGlobal].componentId == componentId); } } } void AssemblyGraph2::removeSecondaryBubbles(uint64_t secondaryEdgeCleanupThreshold) { G& g = *this; // Loop over edges. BGL_FORALL_EDGES(e, g, G) { // If not a bubble, do nothing. E& edge = g[e]; if(not edge.isBubble()) { continue; } // See how many secondary branches we have. uint64_t secondaryCount = 0; for(const E::Branch& branch: edge.branches) { if(branch.containsSecondaryEdges) { ++secondaryCount; } } // If there are no secondary branches, do nothing. if(secondaryCount == 0) { continue; } const uint64_t primaryCount = edge.ploidy() - secondaryCount; // If any branches are long, skip it. bool isLong = false; for(const E::Branch& branch: edge.branches) { if(branch.path.size() > secondaryEdgeCleanupThreshold) { isLong = true; break; } } if(isLong) { continue; } // Remove secondary branches, keeping at most one. if(primaryCount > 0) { // There is at least one primary branch, so we can // remove all the secondary ones. edge.removeAllSecondaryBranches(); edge.findStrongestBranch(); } else { // There are no primary branches. // Remove all secondary branches except the strongest. edge.removeAllBranchesExceptStrongest(); edge.findStrongestBranch(); } } } void AssemblyGraph2::removeWeakBranches(uint64_t strongBranchThreshold) { G& g = *this; // Loop over edges. BGL_FORALL_EDGES(e, g, G) { // If not a bubble, do nothing. E& edge = g[e]; if(not edge.isBubble()) { continue; } edge.findStrongestBranch(); // Find the weak branches. std::set<uint64_t> weakBranches; for(uint64_t branchId=0; branchId<edge.ploidy(); branchId++) { const E::Branch& branch = edge.branches[branchId]; if( (branchId != edge.strongestBranchId) and (uint64_t(branch.orientedReadIds.size()) < strongBranchThreshold)) { weakBranches.insert(branchId); } } // Remove them. if(not weakBranches.empty()) { vector<E::Branch> branches; for(uint64_t branchId=0; branchId<edge.ploidy(); branchId++) { if(weakBranches.find(branchId) == weakBranches.end()) { const E::Branch& branch = edge.branches[branchId]; branches.push_back(branch); } } edge.branches.swap(branches); edge.findStrongestBranch(); } } } void AssemblyGraph2Edge::removeAllSecondaryBranches() { vector<Branch> newBranches; for(const Branch& branch: branches) { if(not branch.containsSecondaryEdges) { newBranches.push_back(branch); } } branches.swap(newBranches); } void AssemblyGraph2Edge::removeAllBranchesExceptStrongest() { vector<Branch> newBranches(1, branches[strongestBranchId]); branches.swap(newBranches); strongestBranchId = 0; } // Remove degenerate branches. void AssemblyGraph2::removeDegenerateBranches() { G& g = *this; BGL_FORALL_EDGES(e, g, G) { E& edge = g[e]; const uint64_t ploidy = edge.ploidy(); if(ploidy == 1) { continue; } if(ploidy == 2) { if(edge.isDegenerateBubble()) { edge.removeAllBranchesExceptStrongest(); } continue; } // General case of ploidy 3 or more. // Gather branches that have the same sequence. // Map with: // Key = raw sequence. // Value = (average edge coverage, branchId). std::map<vector<shasta::Base>, vector<uint64_t> > branchMap; for(uint64_t branchId=0; branchId<edge.branches.size(); branchId++) { const E::Branch& branch = edge.branches[branchId]; branchMap[branch.rawSequence].push_back(branchId); } // For each set of branches with identical sequence, only keep the strongest. vector<uint64_t> keep; for(const auto& p: branchMap) { const vector<uint64_t>& branchIds = p.second; if(branchIds.size() == 1) { // There is only one branch with this sequence. Keep it. keep.push_back(branchIds.front()); continue; } // Find the one with the most coverage. uint64_t bestBranchId = branchIds.front(); uint64_t bestCoverage = edge.branches[bestBranchId].averageCoverage(); for(uint64_t branchId: branchIds) { const uint64_t branchCoverage = edge.branches[branchId].averageCoverage(); if(branchCoverage > bestCoverage) { bestBranchId = branchId; bestCoverage = branchCoverage; } } SHASTA_ASSERT(bestBranchId < ploidy); keep.push_back(bestBranchId); } // Only keep the branches we marked to keep. vector<E::Branch> newBranches; for(uint64_t branchId: keep) { newBranches.push_back(edge.branches[branchId]); } edge.branches.swap(newBranches); edge.findStrongestBranch(); } } void AssemblyGraph2::hetSnpStatistics( uint64_t& transitionCount, uint64_t& transversionCount ) const { using shasta::Base; const G& g = *this; transitionCount = 0; transversionCount= 0; BGL_FORALL_EDGES(e, g, G) { const E& edge = g[e]; if(edge.ploidy() != 2) { continue; } const auto& s0 = edge.branches[0].gfaSequence; const auto& s1 = edge.branches[1].gfaSequence; if(s0.size() != 1) { continue; } if(s1.size() != 1) { continue; } const Base b0 = s0.front(); const Base b1 = s1.front(); const bool isPurine0 = (b0.value % 2) == 0; const bool isPurine1 = (b1.value % 2) == 0; const bool isTransition = (isPurine0 == isPurine1); if(isTransition) { ++transitionCount; } else { ++transversionCount; } } } // Remove bubbles marked isBad during phasing. // Only keep the strongest branch for each. void AssemblyGraph2::removeBadBubbles() { cout << timestamp << "removeBadBubbles begins." << endl; G& g = *this; uint64_t totalCount = 0; uint64_t removedCount = 0; BGL_FORALL_EDGES(e, g, G) { ++totalCount; E& edge = g[e]; if(edge.isBad) { edge.removeAllBranchesExceptStrongest(); ++removedCount; } } cout << "Cleaned up " << removedCount << " bad bubbles out of " << totalCount << " edges total." << endl; cout << timestamp << "removeBadBubbles ends." << endl; } // Merge consecutive non-bubbles, when possible. void AssemblyGraph2::merge( bool storeReadInformation, // If true, store read information for merged edges. bool assemble // If true, assemble merged edges. ) { // Find linear chains of non-bubbles. vector< vector<edge_descriptor> > chains; findNonBubbleLinearChains(chains); /* cout << "Found the following linear chains that will be merged:" << endl; for(const auto& chain: chains) { cout << "Chain"; for(const edge_descriptor e: chain) { cout << " " << (*this)[e].id; } cout << endl; } */ // Merge each chain. for(const vector<edge_descriptor>& chain: chains) { merge(chain, storeReadInformation, assemble); } } AssemblyGraph2::edge_descriptor AssemblyGraph2::merge( const vector<edge_descriptor>& chain, bool storeReadInformation, // If true, store read information for merged edges. bool assemble // If true, assemble merged edges. ) { G& g = *this; /* cout << "Merging linear chain "; for(const edge_descriptor e: chain) { cout << " " << g[e].id; } cout << endl; */ // Sanity checks. // Must be more than one edge. SHASTA_ASSERT(chain.size() > 1); // There must be no bubbles. for(const edge_descriptor e: chain) { SHASTA_ASSERT(not g[e].isBubble()); } // It must be a path. for(uint64_t i=1; i<chain.size(); i++) { SHASTA_ASSERT(target(chain[i-1], g) == source(chain[i], g)); } // Check the degrees of internal vertices. // It must be a linear chain. for(uint64_t i=1; i<chain.size(); i++) { const vertex_descriptor v = source(chain[i], g); SHASTA_ASSERT(in_degree(v, g) == 1); SHASTA_ASSERT(out_degree(v, g) == 1); } // Create the merged marker graph path. MarkerGraphPath newPath; bool containsSecondaryEdges = false; for(const edge_descriptor e: chain) { const AssemblyGraph2Edge::Branch& branch = g[e].branches.front(); const MarkerGraphPath& path = g[e].branches.front().path; newPath.insert(newPath.end(), path.begin(), path.end()); containsSecondaryEdges = containsSecondaryEdges or branch.containsSecondaryEdges; } // Add the new edge. const edge_descriptor eNew = addEdge(newPath, containsSecondaryEdges); if(storeReadInformation) { g[eNew].storeReadInformation(markerGraph); } if(assemble) { AssemblyGraph2::assemble(eNew); } // Gather the vertices in between, which will be removed. vector<vertex_descriptor> verticesToBeRemoved; for(uint64_t i=1; i<chain.size(); i++) { verticesToBeRemoved.push_back(source(chain[i], g)); } // Remove the old edges. for(const edge_descriptor e: chain) { boost::remove_edge(e, g); } // Remove the vertices in between. for(const vertex_descriptor v: verticesToBeRemoved) { SHASTA_ASSERT(in_degree(v, g) == 0); SHASTA_ASSERT(out_degree(v, g) == 0); boost::remove_vertex(v, g); } return eNew; } // Merge an edge with the previous edge, if possible. AssemblyGraph2::edge_descriptor AssemblyGraph2::mergeWithPreviousIfPossible(edge_descriptor e) { AssemblyGraph2& g = *this; // This edge cannot be a bubble. if(g[e].isBubble()) { return e; } // The source vertex of e must have in-degree and out-degree 1. const vertex_descriptor v0 = source(e, g); if(in_degree(v0, g) != 1) { return e; } if(out_degree(v0, g) != 1) { return e; } // Locate the one and only previous edge. in_edge_iterator it; tie(it, ignore) = in_edges(v0, g); const edge_descriptor ePrevious = *it; // The previous edge cannot be a bubble. if(g[ePrevious].isBubble()) { return e; } // If getting here, we can merge. // Create the new edge. edge_descriptor eNew; tie(eNew, ignore) = add_edge(source(ePrevious, g), target(e, g), E(nextId++), g); g[eNew].branches.resize(1); g[eNew].strongestBranchId = 0; // Access the branches we are working with. const AssemblyGraph2Edge::Branch& branch = g[e].branches.front(); const AssemblyGraph2Edge::Branch& previousBranch = g[ePrevious].branches.front(); AssemblyGraph2Edge::Branch& newBranch = g[eNew].branches.front(); // Create the combined marker graph path. newBranch.path = previousBranch.path; copy(branch.path.begin(), branch.path.end(), back_inserter(newBranch.path)); newBranch.containsSecondaryEdges = branch.containsSecondaryEdges or previousBranch.containsSecondaryEdges; // Recompute read support for the merged branch. newBranch.storeReadInformation(markerGraph); // Compute sequence for the updated edge. assemble(eNew); // Remove the edges we are merging. boost::remove_edge(e, g); boost::remove_edge(ePrevious, g); // Remove the vertex in between. SHASTA_ASSERT(in_degree(v0, g) == 0); SHASTA_ASSERT(out_degree(v0, g) == 0); remove_vertex(v0, g); // Done. return eNew; } // Merge an edge with the following edge, if possible. AssemblyGraph2::edge_descriptor AssemblyGraph2::mergeWithFollowingIfPossible(edge_descriptor e) { AssemblyGraph2& g = *this; // This edge cannot be a bubble. if(g[e].isBubble()) { return e; } // The target vertex of e must have in-degree and out-degree 1. const vertex_descriptor v1 = target(e, g); if(in_degree(v1, g) != 1) { return e; } if(out_degree(v1, g) != 1) { return e; } // Locate the one and only following edge. out_edge_iterator it; tie(it, ignore) = out_edges(v1, g); const edge_descriptor eFollowing = *it; // The following edge cannot be a bubble. if(g[eFollowing].isBubble()) { return e; } // If getting here, we can merge. // Create the new edge. edge_descriptor eNew; tie(eNew, ignore) = add_edge(source(e, g), target(eFollowing, g), E(nextId++), g); g[eNew].branches.resize(1); g[eNew].strongestBranchId = 0; // Access the branches we are working with. const AssemblyGraph2Edge::Branch& branch = g[e].branches.front(); const AssemblyGraph2Edge::Branch& followingBranch = g[eFollowing].branches.front(); AssemblyGraph2Edge::Branch& newBranch = g[eNew].branches.front(); // Create the combined marker graph path. newBranch.path = branch.path; copy(followingBranch.path.begin(), followingBranch.path.end(), back_inserter(newBranch.path)); newBranch.containsSecondaryEdges = branch.containsSecondaryEdges or followingBranch.containsSecondaryEdges; // Recompute read support for the merged branch. newBranch.storeReadInformation(markerGraph); // Compute sequence for the updated edge. assemble(eNew); // Remove the edges we are merging. boost::remove_edge(e, g); boost::remove_edge(eFollowing, g); // Remove the vertex in between. SHASTA_ASSERT(in_degree(v1, g) == 0); SHASTA_ASSERT(out_degree(v1, g) == 0); remove_vertex(v1, g); // Done. return eNew; } // Find linear chains of adjacent non-bubbles. // Used by merge. void AssemblyGraph2::findNonBubbleLinearChains( vector< vector<edge_descriptor> >& chains) const { const G& g = *this; // The edges we have already encountered. std::set<edge_descriptor> edgesFound; // Start with no chains. chains.clear(); // Work vectors used in the main loop below. vector<edge_descriptor> forwardPath; vector<edge_descriptor> backwardPath; // Consider all possible start edges for the chain. BGL_FORALL_EDGES_T(eStart, g, G) { // If this is a bubble, skip it. if(g[eStart].isBubble()) { continue; } // If we already assigned this edge to a chain, skip it. if(edgesFound.find(eStart) != edgesFound.end()) { continue; } edgesFound.insert(eStart); // Extend forward. forwardPath.clear(); bool isCircular = false; edge_descriptor e = eStart; while(true) { const vertex_descriptor v = target(e, g); if(in_degree(v, g) != 1) { break; } if(out_degree(v, g) != 1) { break; } BGL_FORALL_OUTEDGES_T(v, eNext, g, G) { e = eNext; break; } if(g[e].isBubble()) { break; } if(e == eStart) { isCircular = true; break; } forwardPath.push_back(e); SHASTA_ASSERT(edgesFound.find(e) == edgesFound.end()); edgesFound.insert(e); } // Extend backward. backwardPath.clear(); if(not isCircular) { edge_descriptor e = eStart; while(true) { const vertex_descriptor v = source(e, g); if(in_degree(v, g) != 1) { break; } if(out_degree(v, g) != 1) { break; } BGL_FORALL_INEDGES_T(v, ePrevious, g, G) { e = ePrevious; break; } if(g[e].isBubble()) { break; } if(e == eStart) { isCircular = true; break; } backwardPath.push_back(e); SHASTA_ASSERT(edgesFound.find(e) == edgesFound.end()); edgesFound.insert(e); } } // If the chain is too short, get rid of it. if(backwardPath.size() + 1 + forwardPath.size() < 2) { continue; } // Store it. chains.resize(chains.size() + 1); vector<edge_descriptor>& chain = chains.back(); copy(backwardPath.rbegin(), backwardPath.rend(), back_inserter(chain)); chain.push_back(eStart); copy(forwardPath.begin(), forwardPath.end(), back_inserter(chain)); } // Check that all non-bubble edges were found. BGL_FORALL_EDGES_T(e, g, G) { if(not g[e].isBubble()) { SHASTA_ASSERT(edgesFound.find(e) != edgesFound.end()); } } } void AssemblyGraph2::findBubbleChains() { G& g = *this; vector< vector<edge_descriptor> > linearChains; findLinearChains(*this, 2, linearChains); bubbleChains.clear(); bubbleChains.resize(linearChains.size()); for(uint64_t i=0; i<linearChains.size(); i++) { BubbleChain& bubbleChain = bubbleChains[i]; bubbleChain.edges.swap(linearChains[i]); } cout << "Found " << bubbleChains.size() << " bubble chains with the following numbers of edges:"; for(const auto& bubbleChain: bubbleChains) { cout << " " << bubbleChain.edges.size(); } cout << endl; // Store pointers in the begin/end vertices. BGL_FORALL_VERTICES(v, g, G) { V& vertex = g[v]; vertex.bubbleChainsBeginningHere.clear(); vertex.bubbleChainsEndingHere.clear(); } for(const BubbleChain& bubbleChain: bubbleChains) { SHASTA_ASSERT(not bubbleChain.edges.empty()); const vertex_descriptor vBegin = source(bubbleChain.edges.front(), g); const vertex_descriptor vEnd = target(bubbleChain.edges.back(), g); g[vBegin].bubbleChainsBeginningHere.push_back(&bubbleChain); g[vEnd].bubbleChainsEndingHere.push_back(&bubbleChain); } // Stores pointers in edges. BGL_FORALL_EDGES(e, g, G) { g[e].bubbleChain = {0, 0}; } for(const BubbleChain& bubbleChain: bubbleChains) { for(uint64_t position=0; position<bubbleChain.edges.size(); position++) { const edge_descriptor e = bubbleChain.edges[position]; g[e].bubbleChain = make_pair(&bubbleChain, position); } } } // Find PhasingRegions within BubbleChains. void AssemblyGraph2::findPhasingRegions() { for(BubbleChain& bubbleChain: bubbleChains) { findPhasingRegions(bubbleChain); } } void AssemblyGraph2::findPhasingRegions(BubbleChain& bubbleChain) { const G& g = *this; const auto& edges = bubbleChain.edges; // cout << "findPhasingRegions begins for bubble chain " << bubbleChain.id << endl; // Gather all the positions that have a defined componentId. vector< pair<uint64_t, uint64_t> > bubbleChainTable; for(uint64_t position=0; position<edges.size(); position++) { const AssemblyGraph2Edge& edge = g[edges[position]]; const uint64_t componentId = edge.componentId; if(componentId != std::numeric_limits<uint64_t>::max()) { bubbleChainTable.push_back(make_pair(position, componentId)); } } // Use this table to find the boundaries of the phased regions. vector<uint64_t> firstPositions; vector<uint64_t> lastPositions; for(uint64_t i=0; i<bubbleChainTable.size(); i++) { const auto& p = bubbleChainTable[i]; const uint64_t position = p.first; const uint64_t componentId = p.second; if(i==0 or componentId != bubbleChainTable[i-1].second) { firstPositions.push_back(position); } if(i==bubbleChainTable.size()-1 or componentId != bubbleChainTable[i+1].second) { lastPositions.push_back(position); } } // Now we can create the phased regions. bubbleChain.phasingRegions.clear(); // If nothing was phased, generate a single phasing region for the entire bubble chain. SHASTA_ASSERT(firstPositions.size() == lastPositions.size()); if(firstPositions.empty()) { BubbleChain::PhasingRegion unphasedRegion; unphasedRegion.firstPosition = 0; unphasedRegion.lastPosition = edges.size() - 1; unphasedRegion.isPhased = false; bubbleChain.phasingRegions.push_back(unphasedRegion); return; } // Create an initial unphased region, if necessary. if(firstPositions.front() != 0) { BubbleChain::PhasingRegion unphasedRegion; unphasedRegion.firstPosition = 0; unphasedRegion.lastPosition = firstPositions.front() - 1; unphasedRegion.isPhased = false; bubbleChain.phasingRegions.push_back(unphasedRegion); } for(uint64_t i=0; i<firstPositions.size(); i++) { // Add a phased region. BubbleChain::PhasingRegion phasedRegion; phasedRegion.firstPosition = firstPositions[i]; phasedRegion.lastPosition = lastPositions[i]; phasedRegion.isPhased = true; phasedRegion.componentId = g[edges[firstPositions[i]]].componentId; bubbleChain.phasingRegions.push_back(phasedRegion); // If necessary, add an unphased region to bridge the gap to the // next phased region. if(i != firstPositions.size() - 1 ) { if(firstPositions[i + 1] != lastPositions[i] + 1) { BubbleChain::PhasingRegion unphasedRegion; unphasedRegion.firstPosition = lastPositions[i] + 1; unphasedRegion.lastPosition = firstPositions[i + 1] - 1; unphasedRegion.isPhased = false; bubbleChain.phasingRegions.push_back(unphasedRegion); } } } // Create a final unphased region, if necessary. if(lastPositions.back() != edges.size()-1) { BubbleChain::PhasingRegion unphasedRegion; unphasedRegion.firstPosition = lastPositions.back() + 1; unphasedRegion.lastPosition = edges.size()-1; unphasedRegion.isPhased = false; bubbleChain.phasingRegions.push_back(unphasedRegion); } } void AssemblyGraph2::writePhasingRegions() { ofstream csv("PhasingRegions.csv"); csv << "Bubble chain id,Phasing region id,First position,Last position,Phased,Component,\n"; for(uint64_t bubbleChainId=0; bubbleChainId<uint64_t(bubbleChains.size()); bubbleChainId++) { const BubbleChain& bubbleChain = bubbleChains[bubbleChainId]; for(uint64_t phasingRegionId=0; phasingRegionId<uint64_t(bubbleChain.phasingRegions.size()); phasingRegionId++) { const auto& phasingRegion = bubbleChain.phasingRegions[phasingRegionId]; csv << bubbleChainId << "," << phasingRegionId << "," << phasingRegion.firstPosition << "," << phasingRegion.lastPosition << ","; if(phasingRegion.isPhased) { csv << "Yes," << phasingRegion.componentId << ","; } else { csv << "No,,"; } csv << "\n"; } } } void AssemblyGraph2::writeBubbleChains() { G& g = *this; ofstream csv("BubbleChains.csv"); csv << "Bubble chain,Position,Edge,Ploidy,Component,\n"; for(uint64_t bubbleChainId=0; bubbleChainId<uint64_t(bubbleChains.size()); bubbleChainId++) { const BubbleChain& bubbleChain = bubbleChains[bubbleChainId]; const vector<edge_descriptor>& edges = bubbleChain.edges; for(uint64_t position=0; position<uint64_t(edges.size()); position++) { const edge_descriptor e = edges[position]; const AssemblyGraph2Edge& edge = g[e]; csv << bubbleChainId << ","; csv << position << ","; csv << edge.id << ","; csv << edge.ploidy() << ","; if(edge.componentId != std::numeric_limits<uint64_t>::max()){ csv << edge.componentId; } csv << ","; csv << "\n"; } } } void AssemblyGraph2::handleSuperbubbles(uint64_t edgeLengthThreshold) { G& g = *this; // We cannot use boost::connected_components because it // only works for undirected graphs. // Map vertices to integers. std::map<vertex_descriptor, uint64_t> vertexMap; uint64_t vertexIndex = 0; BGL_FORALL_VERTICES(v, g, G) { vertexMap.insert(make_pair(v, vertexIndex++)); } const uint64_t n = uint64_t(vertexMap.size()); // Initialize the disjoint sets data structure. vector<uint64_t> rank(n); vector<uint64_t> parent(n); boost::disjoint_sets<uint64_t*, uint64_t*> disjointSets(&rank[0], &parent[0]); for(uint32_t i=0; i<n; i++) { disjointSets.make_set(i); } // Main loop over short edges. BGL_FORALL_EDGES(e, g, G) { const E& edge = g[e]; if(edge.maximumPathLength() <= edgeLengthThreshold) { const vertex_descriptor v0 = source(e, g); const vertex_descriptor v1 = target(e, g); disjointSets.union_set(vertexMap[v0], vertexMap[v1]); } } // Gather the vertices in each connected component. std::map<uint64_t, vector<vertex_descriptor> > components; BGL_FORALL_VERTICES(v, g, G) { const uint64_t component = disjointSets.find_set(vertexMap[v]); components[component].push_back(v); } // Process one components one at a time. // Each component is used to create a superbubble. for(const auto& p: components) { const vector<vertex_descriptor>& componentVertices = p.second; // Create a superbubble with this component. Superbubble superbubble(g, componentVertices, edgeLengthThreshold); // Process it. handleSuperbubble1(superbubble); } } // This does path enumeration on the entire superbubble. // It can be problematic for large superbubbles. void AssemblyGraph2::handleSuperbubble0(Superbubble& superbubble) { G& g = *this; const bool debug = true; // If there are no edges, don't do anything. if(num_edges(superbubble) == 0) { return; } // If just a simple linear chain, don't do anything. if(superbubble.isSimpleLinearChain()) { return; } if(debug) { cout << "Processing a non-trivial superbubble with " << superbubble.entrances.size() << " entrances, " << superbubble.exits.size() << " exits, " << num_vertices(superbubble) << " vertices, and " << num_edges(superbubble) << " edges:\n"; superbubble.writeGraphviz(cout, g); } // Ignore superbubbles that don't have exactly one entrance and one exit. if((superbubble.entrances.size() != 1) or (superbubble.exits.size() != 1)) { cout << "Superbubble ignored because does not have exactly one entrance and one exit." << endl; return; } // Enumerate paths from the entrance to the exit. superbubble.enumeratePaths(); if(debug) { cout << "Found " << superbubble.paths.size() << " paths:" << endl; for(const vector<Superbubble::edge_descriptor>& path: superbubble.paths) { for(const Superbubble::edge_descriptor se: path) { const SuperbubbleEdge& sEdge = superbubble[se]; const AssemblyGraph2::edge_descriptor ae = sEdge.ae; const uint64_t branchId = sEdge.branchId; cout << " " << g[ae].pathId(branchId); } cout << endl; } } // Create a new edge and add a branch for each path. const AssemblyGraph2::vertex_descriptor v0 = superbubble[superbubble.entrances.front()].av; const AssemblyGraph2::vertex_descriptor v1 = superbubble[superbubble.exits.front()].av; AssemblyGraph2::edge_descriptor eNew; bool edgeWasAdded = false; tie(eNew, edgeWasAdded)= add_edge(v0, v1, E(nextId++), g); SHASTA_ASSERT(edgeWasAdded); E& newEdge = g[eNew]; for(const vector<Superbubble::edge_descriptor>& path: superbubble.paths) { // Construct the marker graph path. MarkerGraphPath markerGraphPath; bool containsSecondaryEdges = false; for(const Superbubble::edge_descriptor se: path) { const SuperbubbleEdge sEdge = superbubble[se]; const AssemblyGraph2::edge_descriptor ae = sEdge.ae; const uint64_t branchId = sEdge.branchId; const E& edge = g[ae]; const E::Branch& branch = edge.branches[branchId]; copy(branch.path.begin(), branch.path.end(), back_inserter(markerGraphPath)); if(branch.containsSecondaryEdges) { containsSecondaryEdges = true; } } // Add the branch. newEdge.branches.push_back(E::Branch(markerGraphPath, containsSecondaryEdges)); } // Now remove all the edges internal to the superbubble. BGL_FORALL_EDGES(se, superbubble, Superbubble) { const SuperbubbleEdge& sEdge = superbubble[se]; if(sEdge.branchId == 0) { boost::remove_edge(sEdge.ae, g); } } // Also remove any vertices that have been left isolated. BGL_FORALL_VERTICES(sv, superbubble, Superbubble) { AssemblyGraph2::vertex_descriptor av = superbubble[sv].av; if(in_degree(av, g)==0 and out_degree(av, g)==0) { remove_vertex(av, g); } } } /******************************************************************************* Better version that avoids enumerating paths over the entire superbubble. For a superbubble with exactly one entrance and one exit, this uses a dominator tree to divide the superbubble in chunks, and then does path enumeration over each chunk separately. Some nomenclature: - On the dominator tree, there is only one path between the entrance and the exit. We call this the critical path. This does not necessarily corresponds to a path in the superbubble. - The vertices on the critical path are called the choke points. They are numbered consecutively starting at 0. The entrance is choke point 0. - Vertices that are not in the dominator tree are unreachable from the entrance. We call these the unreachable vertices. The remaining vertices are the reachable vertices. - Superbubble edges for which the source vertex is reachable are called reachable. Superbubble edges for which the source vertex is unreachable are called unreachable. - From each reachable vertex, we can follow the dominator tree up until we encounter the first choke point. This choke point is called the parent choke point of the vertex that we started from. - For each reachable edge, the parent choke point of the source vertex of the edge is called the parent choke point of the edge. - A chunk is the set of all reachable edges with the same parent choke point. That common parent choke point is the called the source of the chunk. The next choke point on the critical path is called the target of the chunk. - A chunk is called trivial if all of its edges have as source the source of the chunk and as target the target of the chunk. With these definitions, a superbubble with exactly one entrance and one exit is processed as follows: - The AssemblyGraph2 edges corresponding to all unreachable edges are removed from the AssemblyGraph2. - For trivial chunks, no processing takes place. - For non-trivial chunks: * We do path enumeration from the source to the target of the chunk and keep only the two strongest paths. These are used to generate a new bubble in the AssemblyGraph2. * All AssemblyGraph2 edges corresponding to edges in the chunk are removed. *******************************************************************************/ void AssemblyGraph2::handleSuperbubble1(Superbubble& superbubble) { G& g = *this; const bool debug = false; // If there are no edges, don't do anything. if(num_edges(superbubble) == 0) { return; } // If just a simple linear chain, don't do anything. if(superbubble.isSimpleLinearChain()) { return; } if(debug) { cout << "Processing a non-trivial superbubble with " << superbubble.entrances.size() << " entrances, " << superbubble.exits.size() << " exits, " << num_vertices(superbubble) << " vertices, and " << num_edges(superbubble) << " edges:\n"; superbubble.writeGraphviz(cout, g); } // Ignore superbubbles that don't have exactly one entrance and one exit. if((superbubble.entrances.size() != 1) or (superbubble.exits.size() != 1)) { cout << "Superbubble ignored because does not have exactly one entrance and one exit." << endl; return; } const Superbubble::vertex_descriptor entrance = superbubble.entrances.front(); const Superbubble::vertex_descriptor exit = superbubble.exits.front(); // Compute the forward dominator tree. // Use the shasta version which includes a bug fix // (see dominatorTree.hpp). shasta::lengauer_tarjan_dominator_tree( superbubble, entrance, boost::get(&SuperbubbleVertex::immediateDominator0, superbubble)); // Compute the backward dominator tree. shasta::lengauer_tarjan_dominator_tree( boost::reverse_graph<Superbubble>(superbubble), exit, boost::get(&SuperbubbleVertex::immediateDominator1, superbubble)); if(debug) { cout << "Forward dominator tree:" << endl; BGL_FORALL_VERTICES (sv0, superbubble, Superbubble) { const AssemblyGraph2::vertex_descriptor av0 = superbubble[sv0].av; const AssemblyGraph2Vertex& aVertex0 = g[av0]; cout << aVertex0.markerGraphVertexId; if(sv0 == entrance) { cout << " entrance" << endl; } else { const Superbubble::vertex_descriptor sv1 = superbubble[sv0].immediateDominator0; if(sv1 == Superbubble::null_vertex()) { cout << " unreachable" << endl; } else { const AssemblyGraph2::vertex_descriptor av1 = superbubble[sv1].av; const AssemblyGraph2Vertex& aVertex1 = g[av1]; cout << " parent is " << aVertex1.markerGraphVertexId << endl; } } } cout << "Backward dominator tree:" << endl; BGL_FORALL_VERTICES (sv0, superbubble, Superbubble) { const AssemblyGraph2::vertex_descriptor av0 = superbubble[sv0].av; const AssemblyGraph2Vertex& aVertex0 = g[av0]; cout << aVertex0.markerGraphVertexId; if(sv0 == exit) { cout << " exit" << endl; } else { const Superbubble::vertex_descriptor sv1 = superbubble[sv0].immediateDominator1; if(sv1 == Superbubble::null_vertex()) { cout << " unreachable" << endl; } else { const AssemblyGraph2::vertex_descriptor av1 = superbubble[sv1].av; const AssemblyGraph2Vertex& aVertex1 = g[av1]; cout << " parent is " << aVertex1.markerGraphVertexId << endl; } } } } // In the exceptional case that the exit is unreachable from entrance, // do nothing. if( superbubble[exit].immediateDominator0 == Superbubble::null_vertex() or superbubble[entrance].immediateDominator1 == Superbubble::null_vertex()) { return; } // Construct the critical path. superbubble.computeCriticalPath(); if(debug) { cout << "Critical path:" << endl; for(const auto sv: superbubble.criticalPath) { const AssemblyGraph2::vertex_descriptor av = superbubble[sv].av; const AssemblyGraph2Vertex& aVertex = g[av]; cout << aVertex.markerGraphVertexId << endl; } } // Assign edges to chunks. superbubble.findChunks(); if(debug) { for(uint64_t chunk=0; chunk<superbubble.chunkEdges.size(); chunk++) { cout << "Chunk " << chunk; for(const Superbubble::edge_descriptor se: superbubble.chunkEdges[chunk]) { const SuperbubbleEdge& sEdge = superbubble[se]; cout << " " << g[sEdge.ae].pathId(sEdge.branchId); } cout << endl; } } // Remove edges not assigned to a chunk from both the Superbubble and the AssemblyGraph2. // These edges cannot belong to any path between the entrance and the exit. vector<Superbubble::edge_descriptor> edgesToBeRemoved; BGL_FORALL_EDGES(e, superbubble, Superbubble) { const SuperbubbleEdge& edge = superbubble[e]; if(edge.chunk == std::numeric_limits<uint64_t>::max()) { edgesToBeRemoved.push_back(e); } } for(const Superbubble::edge_descriptor se: edgesToBeRemoved) { const SuperbubbleEdge& sEdge = superbubble[se]; if(debug) { cout << "Removing edge " << g[sEdge.ae].pathId(sEdge.branchId) << endl; } if(sEdge.branchId==0) { boost::remove_edge(sEdge.ae, g); } boost::remove_edge(se, superbubble); } // Loop over the chunks. // Chunk chunkId consists of all edges reachable forward from choke point chunkId // and backward from choke point chunkId+1. for(uint64_t chunkId=0; chunkId<superbubble.criticalPath.size()-1; chunkId++) { const Superbubble::vertex_descriptor chunkEntrance = superbubble.criticalPath[chunkId]; const Superbubble::vertex_descriptor chunkExit = superbubble.criticalPath[chunkId+1]; if(debug) { cout << "Working on chunk " << chunkId << endl; cout << "Chunk entrance " << g[superbubble[chunkEntrance].av].markerGraphVertexId << endl; cout << "Chunk exit " << g[superbubble[chunkExit].av].markerGraphVertexId << endl; } // If this is a trivial chunk, skip it. // A chunk is trivial if all out-edges of chunkEntrance have chunkExit // as their target vertex. bool isNonTrivial = false; BGL_FORALL_OUTEDGES(chunkEntrance, e, superbubble, Superbubble) { if(target(e, superbubble) != chunkExit) { isNonTrivial = true; break; } } if(not isNonTrivial) { if(debug) { cout << "This chunk is trivial. Nothing done." << endl; } continue; } // If getting here, we have a non-trivial chunk. // At this stage, read support has not yet been computed. // So let's compute it for the edges in this chunk. for(const Superbubble::edge_descriptor se: superbubble.chunkEdges[chunkId]) { const SuperbubbleEdge& sEdge = superbubble[se]; const AssemblyGraph2::edge_descriptor ae = sEdge.ae; AssemblyGraph2Edge& aEdge = g[ae]; AssemblyGraph2Edge::Branch& branch = aEdge.branches[sEdge.branchId]; branch.storeReadInformation(markerGraph); } // Enumerate paths between chunkEntrance and chunkExit. superbubble.enumeratePaths(chunkEntrance, chunkExit); if(debug) { cout << "Found " << superbubble.paths.size() << " paths for this chunk:" << endl; for(const vector<Superbubble::edge_descriptor>& path: superbubble.paths) { uint64_t coverageSum = 0; uint64_t lengthSum = 0; for(const Superbubble::edge_descriptor se: path) { const SuperbubbleEdge& sEdge = superbubble[se]; const AssemblyGraph2::edge_descriptor ae = sEdge.ae; const uint64_t branchId = sEdge.branchId; const auto& branch = g[ae].branches[branchId]; cout << " " << g[ae].pathId(branchId); coverageSum += branch.coverageSum; lengthSum += branch.path.size(); } cout << " average coverage " << double(coverageSum) / double(lengthSum); cout << endl; } } // Compute average coverage for each path. SHASTA_ASSERT(superbubble.paths.size() > 1); vector< pair<uint64_t, double> > pathCoverageTable; for(uint64_t i=0 ; i<superbubble.paths.size(); i++) { const auto& path = superbubble.paths[i]; uint64_t coverageSum = 0; uint64_t lengthSum = 0; for(const Superbubble::edge_descriptor se: path) { const SuperbubbleEdge& sEdge = superbubble[se]; const AssemblyGraph2::edge_descriptor ae = sEdge.ae; const uint64_t branchId = sEdge.branchId; const auto& branch = g[ae].branches[branchId]; coverageSum += branch.coverageSum; lengthSum += branch.path.size(); } const double averageCoverage = double(coverageSum) / double(lengthSum); pathCoverageTable.push_back(make_pair(i, averageCoverage)); } sort(pathCoverageTable.begin(), pathCoverageTable.end(), OrderPairsBySecondOnlyGreater<uint64_t, double>()); const array<vector<Superbubble::edge_descriptor>, 2> bestPaths = { superbubble.paths[pathCoverageTable[0].first], superbubble.paths[pathCoverageTable[1].first]}; if(debug) { cout << "Best paths for this chunk:" << endl; for(const vector<Superbubble::edge_descriptor>& path: bestPaths) { for(const Superbubble::edge_descriptor se: path) { const SuperbubbleEdge& sEdge = superbubble[se]; const AssemblyGraph2::edge_descriptor ae = sEdge.ae; const uint64_t branchId = sEdge.branchId; cout << " " << g[ae].pathId(branchId); } cout << endl; } } // The two best paths could have a common portion at their begin or end. // Find the length of the common portions. const uint64_t prefixLength = commonPrefixLength(bestPaths[0], bestPaths[1]); const uint64_t suffixLength = commonSuffixLength(bestPaths[0], bestPaths[1]); if(debug) { if(prefixLength) { cout << "The two best path have a common prefix of length " << prefixLength << endl; } if(suffixLength) { cout << "The two best path have a common suffix of length " << suffixLength << endl; } } // If there is a common prefix, generate a new haploid edge of the AssemblyGraph2. if(prefixLength) { const auto begin = bestPaths[0].begin(); const auto end = begin + prefixLength; // Construct the marker graph path. MarkerGraphPath markerGraphPath; bool containsSecondaryEdges = false; for(auto it=begin; it!=end; ++it) { const Superbubble::edge_descriptor se = *it; const SuperbubbleEdge& sEdge = superbubble[se]; const AssemblyGraph2::edge_descriptor ae = sEdge.ae; const AssemblyGraph2Edge& aEdge = g[ae]; const AssemblyGraph2Edge::Branch& branch = aEdge.branches[sEdge.branchId]; copy(branch.path.begin(), branch.path.end(), back_inserter(markerGraphPath)); if(branch.containsSecondaryEdges) { containsSecondaryEdges = true; } } // Create a new haploid edge with this path. addEdge(markerGraphPath, containsSecondaryEdges); } // Create a new AssemblyGraph2 edge to represent a bubble with the // two best paths, excluding their common prefix and suffix. if( (prefixLength + suffixLength < bestPaths[0].size()) and (prefixLength + suffixLength < bestPaths[1].size())) { const auto begin0 = bestPaths[0].begin() + prefixLength; const auto end0 = bestPaths[0].end() - suffixLength; const auto begin1 = bestPaths[1].begin() + prefixLength; const auto end1 = bestPaths[1].end() - suffixLength; const Superbubble::edge_descriptor first0 = *begin0; const Superbubble::edge_descriptor last0 = *(end0 - 1); const Superbubble::edge_descriptor first1 = *begin1; const Superbubble::edge_descriptor last1 = *(end1 - 1); // Find the source and target vertices. const Superbubble::vertex_descriptor sv0 = source(first0, superbubble); SHASTA_ASSERT(sv0 == source(first1, superbubble)); const Superbubble::vertex_descriptor sv1 = target(last0, superbubble); SHASTA_ASSERT(sv1 == target(last1, superbubble)); const AssemblyGraph2::vertex_descriptor av0 = superbubble[sv0].av; const AssemblyGraph2::vertex_descriptor av1 = superbubble[sv1].av; // Create the new edge with two branches, one for each of our best paths. MarkerGraphPath markerGraphPath0; bool containsSecondaryEdges0 = false; for(auto it=begin0; it!=end0; ++it) { const Superbubble::edge_descriptor se = *it; const SuperbubbleEdge& sEdge = superbubble[se]; const AssemblyGraph2::edge_descriptor ae = sEdge.ae; const AssemblyGraph2Edge& aEdge = g[ae]; const AssemblyGraph2Edge::Branch& branch = aEdge.branches[sEdge.branchId]; copy(branch.path.begin(), branch.path.end(), back_inserter(markerGraphPath0)); if(branch.containsSecondaryEdges) { containsSecondaryEdges0 = true; } } MarkerGraphPath markerGraphPath1; bool containsSecondaryEdges1 = false; for(auto it=begin1; it!=end1; ++it) { const Superbubble::edge_descriptor se = *it; const SuperbubbleEdge& sEdge = superbubble[se]; const AssemblyGraph2::edge_descriptor ae = sEdge.ae; const AssemblyGraph2Edge& aEdge = g[ae]; const AssemblyGraph2Edge::Branch& branch = aEdge.branches[sEdge.branchId]; copy(branch.path.begin(), branch.path.end(), back_inserter(markerGraphPath1)); if(branch.containsSecondaryEdges) { containsSecondaryEdges1 = true; } } bool edgeWasAdded = false; tie(ignore, edgeWasAdded) = add_edge(av0, av1, E(nextId++, markerGraphPath0, containsSecondaryEdges0, markerGraphPath1, containsSecondaryEdges1), g); SHASTA_ASSERT(edgeWasAdded); } // If there is a common suffix, generate a new haploid edge of the AssemblyGraph2. if(suffixLength) { const auto begin = bestPaths[0].end() - suffixLength; const auto end = bestPaths[0].end(); // Construct the marker graph path. MarkerGraphPath markerGraphPath; bool containsSecondaryEdges = false; for(auto it=begin; it!=end; ++it) { const Superbubble::edge_descriptor se = *it; const SuperbubbleEdge& sEdge = superbubble[se]; const AssemblyGraph2::edge_descriptor ae = sEdge.ae; const AssemblyGraph2Edge& aEdge = g[ae]; const AssemblyGraph2Edge::Branch& branch = aEdge.branches[sEdge.branchId]; copy(branch.path.begin(), branch.path.end(), back_inserter(markerGraphPath)); if(branch.containsSecondaryEdges) { containsSecondaryEdges = true; } } // Create a new haploid edge with this path. addEdge(markerGraphPath, containsSecondaryEdges); } // Now we can remove all the chunk edges from the assembly graph. for(const Superbubble::edge_descriptor se: superbubble.chunkEdges[chunkId]) { const SuperbubbleEdge& sEdge = superbubble[se]; if(sEdge.branchId == 0) { boost::remove_edge(sEdge.ae, g); } } } if(debug) { superbubble.writeGraphviz1(cout, g); } } // Find the chunk that each edge belongs to. // This must be called after the dominator trees // and the critical path are computed. void AssemblyGraph2::Superbubble::findChunks() { Superbubble& superbubble = *this; SHASTA_ASSERT(entrances.size() == 1); SHASTA_ASSERT(exits.size() == 1); chunkEdges.clear(); const uint64_t chunkCount = superbubble[exits.front()].positionInCriticalPath; chunkEdges.resize(chunkCount); BGL_FORALL_EDGES(e, superbubble, Superbubble) { findChunk(e); const uint64_t chunk = superbubble[e].chunk; if(chunk != std::numeric_limits<uint64_t>::max()) { chunkEdges[chunk].push_back(e); } } } void AssemblyGraph2::Superbubble::findChunk(edge_descriptor e) { Superbubble& superbubble = *this; vertex_descriptor v0 = source(e, superbubble); vertex_descriptor v1 = target(e, superbubble); // Walk the forward dominator tree up starting at v0 // and until we get on the critical path. uint64_t chunk; while(true) { if(superbubble[v0].positionInCriticalPath != std::numeric_limits<uint64_t>::max()) { chunk = superbubble[v0].positionInCriticalPath; break; } v0 = superbubble[v0].immediateDominator0; if(v0 == null_vertex()) { return; } } // Do the same in the opposite direction. uint64_t nextChunk; while(true) { if(superbubble[v1].positionInCriticalPath != std::numeric_limits<uint64_t>::max()) { nextChunk = superbubble[v1].positionInCriticalPath; break; } v1 = superbubble[v1].immediateDominator1; if(v1 == null_vertex()) { return; } } if(nextChunk == chunk + 1) { superbubble[e].chunk = chunk; } } // This computes the critical path from the entrance to the exit // for a superbubble with a single entrance and exit. // This assumes that the dominator tree were already computed. void AssemblyGraph2::Superbubble::computeCriticalPath() { Superbubble& superbubble = *this; SHASTA_ASSERT(entrances.size() == 1); SHASTA_ASSERT(exits.size() == 1); const vertex_descriptor entrance = entrances.front(); const vertex_descriptor exit = exits.front(); // Compute the critical path using the forward dominator tree. criticalPath.clear(); for(Superbubble::vertex_descriptor v = exit; ; ) { superbubble.criticalPath.push_back(v); if(v == entrance) { break; } v = superbubble[v].immediateDominator0; } reverse(superbubble.criticalPath.begin(), superbubble.criticalPath.end()); // Also compute the critical path using the fbackward dominator tree // and check that we get the same result. vector<vertex_descriptor> criticalPathCheck; for(Superbubble::vertex_descriptor v = entrance; ; ) { criticalPathCheck.push_back(v); if(v == exit) { break; } v = superbubble[v].immediateDominator1; } SHASTA_ASSERT(criticalPathCheck == criticalPath); // Store positions in the critical path in the critical path vertices. for(uint64_t i=0; i<criticalPath.size(); i++) { const auto v = criticalPath[i]; superbubble[v].positionInCriticalPath = i; } } AssemblyGraph2::Superbubble::Superbubble( const AssemblyGraph2& g, const vector<AssemblyGraph2::vertex_descriptor>& aVertices, uint64_t edgeLengthThreshold) { Superbubble& superbubble = *this; // Create the vertices. std::map<AssemblyGraph2::vertex_descriptor, Superbubble::vertex_descriptor> vertexMap; for(const AssemblyGraph2::vertex_descriptor av: aVertices) { Superbubble::vertex_descriptor sv = boost::add_vertex(SuperbubbleVertex(av), superbubble); vertexMap.insert(make_pair(av, sv)); } /* cout << "Vertex map:" << endl; for(const auto& p: vertexMap) { cout << p.second << " (" << p.first << ")" << endl; } */ // Create the edges. // For an edge to be part of the superbubble: // - Both its source and target vertices must be part of the superbubble. // - It must be a short edge (maximumPathLength() <= edgeLengthThreshold). BGL_FORALL_VERTICES(sv0, superbubble, Superbubble) { const AssemblyGraph2::vertex_descriptor av0 = superbubble[sv0].av; BGL_FORALL_OUTEDGES(av0, ae, g, G) { const AssemblyGraph2::vertex_descriptor av1 = target(ae, g); auto it = vertexMap.find(av1); if(it != vertexMap.end()) { const E& aEdge = g[ae]; if(aEdge.maximumPathLength() <= edgeLengthThreshold) { const Superbubble::vertex_descriptor sv1 = it->second; for(uint64_t branchId=0; branchId<aEdge.ploidy(); branchId++) { add_edge(sv0, sv1, SuperbubbleEdge(ae, branchId), superbubble); } } } } } // Find the entrances and exits. // An entrance has: // - At least one in-edge from a vertex outside the superbubble. // - At least one out-edge to a vertex inside the superbubble. // An exit has: // - At least one in-edge from a vertex inside the superbubble. // - At least one out-edge to a vertex outside the superbubble. BGL_FORALL_VERTICES(sv0, superbubble, Superbubble) { const AssemblyGraph2::vertex_descriptor av0 = superbubble[sv0].av; // Check in-edges. bool hasInedgesFromOutside = false; bool hasInedgesFromInside = false; BGL_FORALL_INEDGES(av0, ae, g, G) { const AssemblyGraph2::vertex_descriptor av1 = source(ae, g); if(av1 == av0) { continue; } if(vertexMap.find(av1) == vertexMap.end()) { hasInedgesFromOutside = true; } else { hasInedgesFromInside = true; } } // Check out-edges. bool hasOutedgesToOutside = false; bool hasOutedgesToInside = false; BGL_FORALL_OUTEDGES(av0, ae, g, G) { const AssemblyGraph2::vertex_descriptor av1 = target(ae, g); if(av1 == av0) { continue; } if(vertexMap.find(av1) == vertexMap.end()) { hasOutedgesToOutside = true; } else { hasOutedgesToInside = true; } } if(hasInedgesFromOutside and hasOutedgesToInside) { entrances.push_back(sv0); } if(hasInedgesFromInside and hasOutedgesToOutside) { exits.push_back(sv0); } } } void AssemblyGraph2::Superbubble::writeGraphviz( ostream& out, const AssemblyGraph2& g) const { const Superbubble& superbubble = *this; out << "digraph Superbubble {" << endl; BGL_FORALL_VERTICES(sv, superbubble, Superbubble) { const AssemblyGraph2::vertex_descriptor av = superbubble[sv].av; const AssemblyGraph2Vertex& aVertex = g[av]; out << aVertex.markerGraphVertexId << ";\n"; } BGL_FORALL_EDGES(se, superbubble, Superbubble) { const SuperbubbleEdge sEdge = superbubble[se]; const AssemblyGraph2::edge_descriptor ae = sEdge.ae; const uint64_t branchId = sEdge.branchId; const Superbubble::vertex_descriptor sv0 = source(se, superbubble); const Superbubble::vertex_descriptor sv1 = target(se, superbubble); const AssemblyGraph2::vertex_descriptor av0 = superbubble[sv0].av; const AssemblyGraph2::vertex_descriptor av1 = superbubble[sv1].av; const AssemblyGraph2Vertex& aVertex0 = g[av0]; const AssemblyGraph2Vertex& aVertex1 = g[av1]; out << aVertex0.markerGraphVertexId << "->" << aVertex1.markerGraphVertexId << " [label=\"" << g[ae].pathId(branchId) << "\"];\n"; } out << "}" << endl; } // This assumes that there is exactly one entrance and one exit, // and that the data structures created by handleSuperbubble1 // are available. void AssemblyGraph2::Superbubble::writeGraphviz1( ostream& out, const AssemblyGraph2& g) const { const Superbubble& superbubble = *this; SHASTA_ASSERT(entrances.size() == 1); SHASTA_ASSERT(exits.size() == 1); out << "digraph Superbubble {" << endl; BGL_FORALL_VERTICES(sv, superbubble, Superbubble) { const AssemblyGraph2::vertex_descriptor av = superbubble[sv].av; const AssemblyGraph2Vertex& aVertex = g[av]; const uint64_t positionInCriticalPath = superbubble[sv].positionInCriticalPath; out << aVertex.markerGraphVertexId; out << "["; // Label. out << "label=\"" << aVertex.markerGraphVertexId; if(positionInCriticalPath != std::numeric_limits<uint64_t>::max()) { out << "\\n" << positionInCriticalPath; } out << "\""; // Color. if(sv == entrances.front()) { out << " style=filled fillcolor=green"; } else if(sv == exits.front()) { out << " style=filled fillcolor=red"; } else { if(positionInCriticalPath != std::numeric_limits<uint64_t>::max()) { out << " style=filled fillcolor=cyan"; } } out << "];\n"; } BGL_FORALL_EDGES(se, superbubble, Superbubble) { const SuperbubbleEdge sEdge = superbubble[se]; const AssemblyGraph2::edge_descriptor ae = sEdge.ae; const uint64_t branchId = sEdge.branchId; const Superbubble::vertex_descriptor sv0 = source(se, superbubble); const Superbubble::vertex_descriptor sv1 = target(se, superbubble); const AssemblyGraph2::vertex_descriptor av0 = superbubble[sv0].av; const AssemblyGraph2::vertex_descriptor av1 = superbubble[sv1].av; const AssemblyGraph2Vertex& aVertex0 = g[av0]; const AssemblyGraph2Vertex& aVertex1 = g[av1]; out << aVertex0.markerGraphVertexId << "->" << aVertex1.markerGraphVertexId << " [label=\"" << g[ae].pathId(branchId); if(sEdge.chunk != std::numeric_limits<uint64_t>::max()) { out << "\\n" << sEdge.chunk; } out << "\"];\n"; } out << "}" << endl; } // Return true if the superbubble corresponds to a simple linear chain // in the AssemblyGraph2. bool AssemblyGraph2::Superbubble::isSimpleLinearChain() const { const Superbubble& superbubble = *this; // A simple linear chain must have exactly one entrance and one exit. if(entrances.size() != 1) { return false; } if(exits.size() != 1) { return false; } // The entrance must have in_degree 0 and out_degree 1. const vertex_descriptor sEntrance = entrances.front(); if(originalInDegree(sEntrance) != 0) { return false; } if(originalOutDegree(sEntrance) != 1) { return false; } // The exit must have in_degree 1 and out_degree 0. const vertex_descriptor sExit = exits.front(); if(originalInDegree(sExit) != 1) { return false; } if(originalOutDegree(sExit) != 0) { return false; } // All other vertices must have in_degree and out_degree 1. BGL_FORALL_VERTICES(sv, superbubble, Superbubble) { if(sv == sEntrance) { continue; } if(sv == sExit) { continue; } if(originalInDegree(sv) != 1) { return false; } if(originalOutDegree(sv) != 1) { return false; } } // If getting here, all conditions for a simple linear chains are satisfied. return true; } // Return the number of distinct AssemblyGraph2 edges // that begin/end at a given vertex. uint64_t AssemblyGraph2::Superbubble::originalInDegree(vertex_descriptor v) const { const Superbubble& superbubble = *this; uint64_t n = 0; BGL_FORALL_INEDGES(v, e, superbubble, Superbubble) { if(superbubble[e].branchId == 0) { ++n; } } return n; } uint64_t AssemblyGraph2::Superbubble::originalOutDegree(vertex_descriptor v) const { const Superbubble& superbubble = *this; uint64_t n = 0; BGL_FORALL_OUTEDGES(v, e, superbubble, Superbubble) { if(superbubble[e].branchId == 0) { ++n; } } return n; } // Enumerate paths from the entrance to the exit. // There must be exactly one entrance and one exit. void AssemblyGraph2::Superbubble::enumeratePaths() { SHASTA_ASSERT(entrances.size() == 1); SHASTA_ASSERT(exits.size() == 1); const vertex_descriptor entrance = entrances.front(); const vertex_descriptor exit = exits.front(); enumeratePaths(entrance, exit); } // Enumerate paths from an entrance to an exit. void AssemblyGraph2::Superbubble::enumeratePaths( vertex_descriptor entrance, vertex_descriptor exit) { enumerateSelfAvoidingPaths(*this, entrance, exit, paths); }
33.287554
131
0.602069
chanzuckerberg
ba707d265066148b6a3f557cbb2b7c5a3adddfe2
873
hpp
C++
include/paddyutils/functions/additiveMerge.hpp
paddy74/paddyutils
e2be1cbee56fffbb225588b391d4efac2a287a1c
[ "MIT" ]
null
null
null
include/paddyutils/functions/additiveMerge.hpp
paddy74/paddyutils
e2be1cbee56fffbb225588b391d4efac2a287a1c
[ "MIT" ]
null
null
null
include/paddyutils/functions/additiveMerge.hpp
paddy74/paddyutils
e2be1cbee56fffbb225588b391d4efac2a287a1c
[ "MIT" ]
null
null
null
#pragma once namespace paddyutils { /** * @brief Merge b into a (inplace). The values of matching keys are summed. * * @tparam KEY_T * @tparam VALUE_T * @param a * @param b */ template <typename KEY_T, typename VALUE_T> void additiveMergeInplace( std::unordered_map<KEY_T, VALUE_T> & a, std::unordered_map<KEY_T, VALUE_T> const & b) { for (auto const & [key, value] : b) a[key] += value; } /** * @brief Merge b into a new copy of a. The values of matching keys are summed. * * @tparam KEY_T * @tparam VALUE_T * @param a * @param b * @return std::unordered_map<KEY_T, VALUE_T> */ template <typename KEY_T, typename VALUE_T> std::unordered_map<KEY_T, VALUE_T> additiveMerge( std::unordered_map<KEY_T, VALUE_T> a, std::unordered_map<KEY_T, VALUE_T> const & b) { additiveMergeInplace(a, b); return a; } } // namespace paddyutils
21.292683
79
0.674685
paddy74
ba73f6f983e7e46de5f0c98120b919f6002d14b7
2,807
hpp
C++
10-riscv/_more/mini_riscv/02/riscv.hpp
al2698/sp
fceabadef49ffe6ed25dfef38e3dc418f309e128
[ "MIT" ]
null
null
null
10-riscv/_more/mini_riscv/02/riscv.hpp
al2698/sp
fceabadef49ffe6ed25dfef38e3dc418f309e128
[ "MIT" ]
null
null
null
10-riscv/_more/mini_riscv/02/riscv.hpp
al2698/sp
fceabadef49ffe6ed25dfef38e3dc418f309e128
[ "MIT" ]
null
null
null
#ifndef __RISCV_H__ #define __RISCV_H__ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <stddef.h> #include <assert.h> #include <iostream> #include <map> using namespace std; #define SMAX 100 #define LMAX 256 #define TMAX 10000 #define MMAX 32768 typedef struct _Op { string name; char type; uint32_t op, f3, f7; } Op; extern Op oNull,oSll,oSlli,oSrl,oSrli,oSra,oSrai,oAdd,oAddi,oSub,oLui,oAuipc, oXor,oXori,oOr,oOri,oAnd,oAndi,oSlt,oSlti,oSltu,oSltiu,oBeq,oBne,oBlt,oBge,oBltu, oBgeu,oJal,oJalr,oFence,oFenceI,oEcall,oEbreak,oCsrrw,oCsrrs,oCsrrc,oCsrrwi,oCsrrsi, oCsrrci,oLb,oLh,oLw,oLbu,oLhu,oSb,oSh,oSw; extern map<string, Op> opMap; extern map<string, int> rMap; extern map<string, int> csrMap; #define BITS(x, from, to) ((uint32_t)(x)<<(32-(to+1)))>>(32-(to-from+1)) // 包含 to, 用 BITS(x, 1, 30) 去思考 #define SGN(x, i) (BITS(x,i,i)==0)? x : (-(1<<i)+(int32_t)BITS(x, 0, i-1))+1 // x[i] 為 sign bit,轉為整數。 extern int mapFind(map<string, int> *iMap, char *name); extern void mapDump(map<string, int> *map); extern Op opFind(char *name); extern int rFind(char *name); extern void wordToBytes(uint32_t word, uint8_t bytes[]); uint32_t bytesToWord(uint8_t bytes[]); #endif /* 指令型態 | R, I, S, B, U, J --|-------------------------------------------- R | f7 rs2 rs1 f3 rd op I | i12 rs1 f3 rd op S | i7 rs2 rs1 f3 i5 op i7=i[11:5] i5=i[4:0] B | i7 rs2 rs1 f3 i5 op i7=i[12|10:5] i5=i[4:1|11] U | i20 rd op i20=i[31:12] J | i20 rd op i20=i[20|10:1|11|19:12] */ /* 指令表 U: lui rd,imm`: `rd = imm * 2^12; pc = pc + 4` with `-2^19 <= imm < 2^19` I: addi rd,rs1,imm`: `rd = rs1 + imm; pc = pc + 4` with `-2^11 <= imm < 2^11` I: lw?? ld rd,imm(rs1)`: `rd = memory[rs1 + imm]; pc = pc + 4` with `-2^11 <= imm < 2^11` I: sw?? sd rs2,imm(rs1)`: `memory[rs1 + imm] = rs2; pc = pc + 4` with `-2^11 <= imm < 2^11` R: add rd,rs1,rs2`: `rd = rs1 + rs2; pc = pc + 4` op:0110011 f7:0000000 R: sub rd,rs1,rs2`: `rd = rs1 - rs2; pc = pc + 4` op:0110011 f7:0100000 R: mul rd,rs1,rs2`: `rd = rs1 * rs2; pc = pc + 4` R: divu rd,rs1,rs2`: `rd = rs1 / rs2; pc = pc + 4` where `rs1` and `rs2` are unsigned integers. R: remu rd,rs1,rs2`: `rd = rs1 % rs2; pc = pc + 4` where `rs1` and `rs2` are unsigned integers. R: sltu rd,rs1,rs2`: `if (rs1 < rs2) { rd = 1 } else { rd = 0 } pc = pc + 4` where `rs1` and `rs2` are unsigned integers. B: beq rs1,rs2,imm`: `if (rs1 == rs2) { pc = pc + imm } else { pc = pc + 4 }` with `-2^12 <= imm < 2^12` and `imm % 2 == 0` J: jal rd,imm`: `rd = pc + 4; pc = pc + imm` with `-2^20 <= imm < 2^20` and `imm % 2 == 0` I: jalr rd,imm(rs1)`: `tmp = ((rs1 + imm) / 2) * 2; rd = pc + 4; pc = tmp` with `-2^11 <= imm < 2^11` I: ecall`: system call number is in `a7`, parameters are in `a0-a2`, return value is in `a0`. */
37.932432
123
0.599572
al2698
ba77177dbb28c549f71f4369a29bfedac9bcf97f
11,728
hpp
C++
libraries/chain/include/graphene/chain/content_object.hpp
VIZ-World/viz-core
634825fcfff9e392a26789f8e23c4cfab2952b71
[ "MIT" ]
7
2018-03-21T12:56:32.000Z
2018-04-02T16:06:24.000Z
libraries/chain/include/graphene/chain/content_object.hpp
VIZ-World/viz-core
634825fcfff9e392a26789f8e23c4cfab2952b71
[ "MIT" ]
18
2018-03-21T13:29:46.000Z
2018-05-18T10:56:43.000Z
libraries/chain/include/graphene/chain/content_object.hpp
VIZ-World/VIZ.Core
634825fcfff9e392a26789f8e23c4cfab2952b71
[ "MIT" ]
9
2018-10-17T19:02:40.000Z
2019-02-14T10:35:00.000Z
#pragma once #include <graphene/protocol/authority.hpp> #include <graphene/protocol/chain_operations.hpp> #include <graphene/chain/chain_object_types.hpp> #include <graphene/chain/witness_objects.hpp> #include <boost/multi_index/composite_key.hpp> namespace graphene { namespace chain { namespace bip = boost::interprocess; struct strcmp_less { bool operator()(const shared_string &a, const shared_string &b) const { return less(a.c_str(), b.c_str()); } bool operator()(const shared_string &a, const string &b) const { return less(a.c_str(), b.c_str()); } bool operator()(const string &a, const shared_string &b) const { return less(a.c_str(), b.c_str()); } private: inline bool less(const char *a, const char *b) const { return std::strcmp(a, b) < 0; } }; class content_type_object : public object<content_type_object_type, content_type_object> { public: content_type_object() = delete; template<typename Constructor, typename Allocator> content_type_object(Constructor &&c, allocator <Allocator> a) :title(a), body(a), json_metadata(a) { c(*this); } id_type id; content_id_type content; shared_string title; shared_string body; shared_string json_metadata; }; class content_object : public object<content_object_type, content_object> { public: content_object() = delete; template<typename Constructor, typename Allocator> content_object(Constructor &&c, allocator <Allocator> a) :parent_permlink(a), permlink(a), beneficiaries(a) { c(*this); } id_type id; account_name_type parent_author; shared_string parent_permlink; account_name_type author; shared_string permlink; time_point_sec last_update; time_point_sec created; time_point_sec active; ///< the last time this post was "touched" by voting or reply time_point_sec last_payout; uint16_t depth = 0; ///< used to track max nested depth uint32_t children = 0; ///< used to track the total number of children, grandchildren, etc... /** * Used to track the total rshares^2 of all children, this is used for indexing purposes. A discussion * that has a nested content of high value should promote the entire discussion so that the content can * be reviewed. */ fc::uint128_t children_rshares; /// index on pending_payout for "things happning now... needs moderation" /// TRENDING = UNCLAIMED + PENDING share_type net_rshares; // reward is proportional to rshares^2, this is the sum of all votes (positive and negative) share_type abs_rshares; /// this is used to track the total abs(weight) of votes for the purpose of calculating cashout_time share_type vote_rshares; /// Total positive rshares from all votes. Used to calculate delta weights. Needed to handle vote changing and removal. time_point_sec cashout_time; /// 24 hours from the weighted average of vote time uint64_t total_vote_weight = 0; /// the total weight of voting rewards, used to calculate pro-rata share of curation payouts int16_t curation_percent = 0; int16_t consensus_curation_percent = 0; /** tracks the total payout this content has received over time, measured in VIZ */ asset payout_value = asset(0, TOKEN_SYMBOL); asset shares_payout_value = asset(0, SHARES_SYMBOL); asset curator_payout_value = asset(0, SHARES_SYMBOL); asset beneficiary_payout_value = asset(0, SHARES_SYMBOL); share_type author_rewards = 0; int32_t net_votes = 0; id_type root_content; bip::vector <protocol::beneficiary_route_type, allocator<protocol::beneficiary_route_type>> beneficiaries; }; /** * This index maintains the set of voter/content pairs that have been used, voters cannot * vote on the same content more than once per payout period. */ class content_vote_object : public object<content_vote_object_type, content_vote_object> { public: template<typename Constructor, typename Allocator> content_vote_object(Constructor &&c, allocator <Allocator> a) { c(*this); } id_type id; account_id_type voter; content_id_type content; uint64_t weight = 0; ///< defines the score this vote receives, used by vote payout calc. 0 if a negative vote or changed votes. int64_t rshares = 0; ///< The number of rshares this vote is responsible for int16_t vote_percent = 0; ///< The percent weight of the vote time_point_sec last_update; ///< The time of the last update of the vote int8_t num_changes = 0; }; struct by_content_voter; struct by_voter_content; struct by_content_weight_voter; struct by_voter_last_update; typedef multi_index_container < content_vote_object, indexed_by< ordered_unique < tag < by_id>, member<content_vote_object, content_vote_id_type, &content_vote_object::id>>, ordered_unique <tag<by_content_voter>, composite_key<content_vote_object, member < content_vote_object, content_id_type, &content_vote_object::content>, member<content_vote_object, account_id_type, &content_vote_object::voter> > >, ordered_unique <tag<by_voter_content>, composite_key<content_vote_object, member < content_vote_object, account_id_type, &content_vote_object::voter>, member<content_vote_object, content_id_type, &content_vote_object::content> > >, ordered_unique <tag<by_voter_last_update>, composite_key<content_vote_object, member < content_vote_object, account_id_type, &content_vote_object::voter>, member<content_vote_object, time_point_sec, &content_vote_object::last_update>, member<content_vote_object, content_id_type, &content_vote_object::content> >, composite_key_compare <std::less<account_id_type>, std::greater<time_point_sec>, std::less<content_id_type>> >, ordered_unique <tag<by_content_weight_voter>, composite_key<content_vote_object, member < content_vote_object, content_id_type, &content_vote_object::content>, member<content_vote_object, uint64_t, &content_vote_object::weight>, member<content_vote_object, account_id_type, &content_vote_object::voter> >, composite_key_compare <std::less<content_id_type>, std::greater<uint64_t>, std::less<account_id_type>> > >, allocator <content_vote_object> > content_vote_index; struct by_cashout_time; /// cashout_time struct by_permlink; /// author, perm struct by_root; struct by_parent; struct by_last_update; /// parent_auth, last_update struct by_author_last_update; /** * @ingroup object_index */ typedef multi_index_container < content_object, indexed_by< /// CONSENUSS INDICIES - used by evaluators ordered_unique < tag <by_id>, member<content_object, content_id_type, &content_object::id>>, ordered_unique < tag<by_cashout_time>, composite_key<content_object, member <content_object, time_point_sec, &content_object::cashout_time>, member<content_object, content_id_type, &content_object::id>>>, ordered_unique < tag<by_permlink>, /// used by consensus to find posts referenced in ops composite_key<content_object, member <content_object, account_name_type, &content_object::author>, member<content_object, shared_string, &content_object::permlink>>, composite_key_compare <std::less<account_name_type>, strcmp_less>>, ordered_unique < tag<by_root>, composite_key<content_object, member <content_object, content_id_type, &content_object::root_content>, member<content_object, content_id_type, &content_object::id>>>, ordered_unique < tag<by_parent>, /// used by consensus to find posts referenced in ops composite_key<content_object, member <content_object, account_name_type, &content_object::parent_author>, member<content_object, shared_string, &content_object::parent_permlink>, member<content_object, content_id_type, &content_object::id>>, composite_key_compare <std::less<account_name_type>, strcmp_less, std::less<content_id_type>> > /// NON_CONSENSUS INDICIES - used by APIs #ifndef IS_LOW_MEM , ordered_unique < tag<by_last_update>, composite_key<content_object, member <content_object, account_name_type, &content_object::parent_author>, member<content_object, time_point_sec, &content_object::last_update>, member<content_object, content_id_type, &content_object::id>>, composite_key_compare <std::less<account_name_type>, std::greater<time_point_sec>, std::less<content_id_type>>>, ordered_unique < tag<by_author_last_update>, composite_key<content_object, member <content_object, account_name_type, &content_object::author>, member<content_object, time_point_sec, &content_object::last_update>, member<content_object, content_id_type, &content_object::id>>, composite_key_compare <std::less<account_name_type>, std::greater<time_point_sec>, std::less<content_id_type>>> #endif >, allocator <content_object> > content_index; struct by_content; typedef multi_index_container< content_type_object, indexed_by< ordered_unique< tag< by_id >, member< content_type_object, content_type_id_type, &content_type_object::id > >, ordered_unique< tag< by_content >, member< content_type_object, content_id_type, &content_type_object::content > > >, allocator< content_type_object > > content_type_index; } } // graphene::chain CHAINBASE_SET_INDEX_TYPE(graphene::chain::content_object, graphene::chain::content_index) CHAINBASE_SET_INDEX_TYPE(graphene::chain::content_type_object, graphene::chain::content_type_index) CHAINBASE_SET_INDEX_TYPE(graphene::chain::content_vote_object, graphene::chain::content_vote_index)
43.437037
156
0.617667
VIZ-World
ba7f9691d1d64b71f076c993b28ffcf730e901e5
1,167
hpp
C++
Abzynt/Abzynt/sdk/memory/memory.hpp
patrykkolodziej/Abzynt-Cheat
862c72514f868fe24728ae83278647bcc3092180
[ "MIT" ]
14
2019-04-11T19:09:26.000Z
2021-03-27T06:18:02.000Z
Abzynt/Abzynt/sdk/memory/memory.hpp
patrykkolodziej/Abzynt-Cheat
862c72514f868fe24728ae83278647bcc3092180
[ "MIT" ]
2
2019-05-01T09:19:31.000Z
2019-08-23T01:20:20.000Z
Abzynt/Abzynt/sdk/memory/memory.hpp
patrykkolodziej/Abzynt-Cheat
862c72514f868fe24728ae83278647bcc3092180
[ "MIT" ]
7
2019-04-16T12:49:30.000Z
2020-09-27T01:53:49.000Z
#pragma once #include "../sdk.hpp" class c_memory { private: uint32_t process_id; HANDLE process_handle; public: ~c_memory(); bool get_process_id(const std::string process_name); bool get_handle(const std::string process_name); uint32_t get_module(const std::string module_name); bool free_memory(const uint32_t address, const size_t size); uint32_t allocate_memory(const size_t size); template<typename t> t read(const uint32_t address) { t out; ReadProcessMemory(process_handle, reinterpret_cast<LPCVOID>(address), &out, sizeof(t), NULL); return out; } template<typename t> void write(const uint32_t address, const t in) { WriteProcessMemory(process_handle, reinterpret_cast<LPVOID>(address), &in, sizeof(t), NULL); } template<typename t> void write_protected(const uint32_t address, const t in) { uint32_t old; VirtualProtectEx(process_handle, reinterpret_cast<LPCVOID>(address), sizeof(t), PAGE_EXECUTE_READWRITE, &old); write(address, in); VirtualProtectEx(process_handle, reinterpret_cast<LPCVOID>(address), sizeof(t), old, NULL); } }; extern std::unique_ptr<c_memory> g_pmemory;
28.463415
113
0.736075
patrykkolodziej
ba811925ae9946aefdcc396a64614f0952d96149
6,669
cpp
C++
ft32/ConfigHandler.cpp
josephpal/ft32
9e7e87254687c25dd6aa0ace8623601019d9467c
[ "Apache-2.0" ]
3
2017-12-11T15:51:25.000Z
2021-11-11T13:08:41.000Z
ft32/ConfigHandler.cpp
josephpal/ft32
9e7e87254687c25dd6aa0ace8623601019d9467c
[ "Apache-2.0" ]
4
2018-02-26T11:30:26.000Z
2021-02-20T14:17:44.000Z
ft32/ConfigHandler.cpp
josephpal/ft32
9e7e87254687c25dd6aa0ace8623601019d9467c
[ "Apache-2.0" ]
4
2017-12-11T13:46:22.000Z
2020-11-21T15:55:41.000Z
/* * ConfigHandler.cpp * * Created on: Feb 28, 2019 * Author: joseph */ #include "ConfigHandler.h" ConfigHandler::ConfigHandler(SHM *ptr) { mPtr = ptr; } ConfigHandler::~ConfigHandler() { } void ConfigHandler::checkup() { // check (and correct if needed) for "/spiffs-cody-storage.txt" (cody program backup) file bool spiffsCodyStorageFileExists = checkSpiffsCodyStorageFile(); if(spiffsCodyStorageFileExists && mSpiffsStorage.getFileSize("/spiffs-cody-storage.txt") > 0) { #ifdef CONFIGHANDLER_DEBUG Serial.println("[cfg] spiffs-cody-storage.txt found and not empty!"); #endif mSpiffsStorage.getStr(&(mPtr->webData.data)); mPtr->webData.contentLength = mPtr->webData.data.length(); #ifdef CONFIGHANDLER_DEBUG Serial.println("[cfg] Loading content into shared memory (queue data): " + mPtr->webData.data); #endif } else if (spiffsCodyStorageFileExists && mSpiffsStorage.getFileSize("/spiffs-cody-storage.txt") == 0) { mPtr->webData.data = ";"; mPtr->webData.contentLength = 1; mSpiffsStorage.save(";"); #ifdef CONFIGHANDLER_DEBUG Serial.println("[cfg] spiffs-cody-storage.txt found and empty! Preparing ..."); #endif } // check (and correct if needed) for codypp webfiles (frontend) bool codyppWebFilesExists = checkWebFiles(); if (!codyppWebFilesExists) { #ifdef CONFIGHANDLER_DEBUG Serial.println("[cfg] Error: Codypp frontend won't work correctly. Please reflash spiffs!"); #endif } // check (and correct if needed) for "/wlanConfiguration.txt" bool networkConfigurationFileExists = checkNetworkConfigurationFile(); if (!networkConfigurationFileExists) { #ifdef CONFIGHANDLER_DEBUG Serial.println("[cfg] Error: wlanConfiguration.txt does not exists. Creating file ..."); #endif mSpiffsStorage.getSpiffs().writeFile(SPIFFS, "/wlanConfiguration.txt", "\n"); } else { } } void ConfigHandler::setCipherKey(char * key) { cipher.setKey(key); } bool ConfigHandler::checkSpiffsCodyStorageFile() { bool returnCondition = mSpiffsStorage.fileExists("/spiffs-cody-storage.txt"); #ifdef CONFIGHANDLER_DEBUG Serial.print("[cfg] Checking for /spiffs-cody-storage.txt"); if(returnCondition) { Serial.println(" -> OK"); } else { Serial.println(" -> FAIL"); } #endif return returnCondition; } bool ConfigHandler::checkNetworkConfigurationFile() { bool returnCondition = mSpiffsStorage.fileExists("/wlanConfiguration.txt"); #ifdef CONFIGHANDLER_DEBUG Serial.print("[cfg] Checking for /wlanConfiguration.txt"); if(returnCondition) { Serial.println(" -> OK"); } else { Serial.println(" -> FAIL"); } #endif return returnCondition; } bool ConfigHandler::decipherNetworkConfigurationFile(String (& array) [2]) { String cipheredConfigFileContent = mSpiffsStorage.getSpiffs().getFile(SPIFFS, "/wlanConfiguration.txt"); String cipheredSsid = cipheredConfigFileContent.substring(0, cipheredConfigFileContent.indexOf('\n')); String cipheredPassword = cipheredConfigFileContent.substring(cipheredConfigFileContent.indexOf('\n') + 1); array[0] = cipher.decryptString(cipheredSsid); array[1] = cipher.decryptString(cipheredPassword); #ifdef CONFIGHANDLER_DEBUG Serial.println("|cfg] config file content found:"); Serial.println("[cfg] -> ciphered ssid: " + cipheredSsid); Serial.println("[cfg] -> ciphered password: " + cipheredPassword); //Serial.println("[cfg] deciphered ssid: " + array[0]); //Serial.println("[cfg] deciphered password: " + array[1]); #endif return true; } bool ConfigHandler::cipherNetworkConfigurationFile(String *configData) { bool returnCondition = false; String decipheredSsid = configData->substring(0, configData->indexOf('\n')); String decipheredPassword = configData->substring(configData->indexOf('\n') + 1); String cipheredSsid = cipher.encryptString(decipheredSsid); String cipheredPassword = cipher.encryptString(decipheredPassword); String cipheredConfig = cipheredSsid + "\n" + cipheredPassword; #ifdef CONFIGHANDLER_DEBUG /*Serial.print("[cfg] configData: "); Serial.println(*configData); Serial.print("[cfg] cipher key: "); Serial.println(cipher.getKey()); Serial.println("[cfg] deciphered ssid: " + decipheredSsid); Serial.println("[cfg] deciphered password: " + decipheredPassword);*/ Serial.println("[cfg] ciphered ssid: " + cipheredSsid); Serial.println("[cfg] ciphered password: " + cipheredPassword); //Serial.println("[cfg] deciphered ssid: " + cipher.decryptString(cipheredSsid)); //Serial.println("[cfg] deciphered password: " + cipher.decryptString(cipheredPassword)); #endif if( checkNetworkConfigurationFile() ) { int fileStatus = mSpiffsStorage.getSpiffs().writeFile(SPIFFS, "/wlanConfiguration.txt", cipheredConfig); switch(fileStatus) { case -1: returnCondition = false; break; case 0: returnCondition = true; break; case 1: returnCondition = false; break; } } else { returnCondition = false; } return returnCondition; } bool ConfigHandler::checkWebFiles() { bool returnCondition = false; int errorCounter = 0; #ifdef CONFIGHANDLER_DEBUG Serial.println("[cfg] Checking for codypp web files ..."); #endif if( !mSpiffsStorage.fileExists("/index.html") ) { errorCounter++; #ifdef CONFIGHANDLER_DEBUG Serial.println("[cfg] Error: index.html is missing."); #endif } if( !mSpiffsStorage.fileExists("/main.css") ) { errorCounter++; #ifdef CONFIGHANDLER_DEBUG Serial.println("[cfg] Error: main.css is missing."); #endif } if( !mSpiffsStorage.fileExists("/main.js.gz") ) { errorCounter++; #ifdef CONFIGHANDLER_DEBUG Serial.println("[cfg] Error: main.js.gz is missing."); #endif } if( !mSpiffsStorage.fileExists("/manifest.js") ) { errorCounter++; #ifdef CONFIGHANDLER_DEBUG Serial.println("[cfg] Error: manifest.js is missing."); #endif } if( !mSpiffsStorage.fileExists("/vendor.js.gz") ) { errorCounter++; #ifdef CONFIGHANDLER_DEBUG Serial.println("[cfg] Error: vendor.js.gz is missing."); #endif } if(errorCounter > 0) { returnCondition = false; #ifdef CONFIGHANDLER_DEBUG Serial.println("[cfg] Checking for codypp web files ... -> FAIL"); #endif } else { returnCondition = true; #ifdef CONFIGHANDLER_DEBUG Serial.println("[cfg] Checking for codypp web files ... -> OK"); #endif } return returnCondition; }
28.74569
109
0.683461
josephpal
ba816a2fd5284a2f31fac8abd767bb2fb21316f2
1,975
cpp
C++
source/threads/thread_worker.cpp
zeplaz/s_liz_rz
612ebd97be4d0624b967b1968c45f092ea1c8ddb
[ "MIT" ]
null
null
null
source/threads/thread_worker.cpp
zeplaz/s_liz_rz
612ebd97be4d0624b967b1968c45f092ea1c8ddb
[ "MIT" ]
null
null
null
source/threads/thread_worker.cpp
zeplaz/s_liz_rz
612ebd97be4d0624b967b1968c45f092ea1c8ddb
[ "MIT" ]
null
null
null
///thread_worker.cpp #include "thread_worker.hpp" thread_worker::thread_worker() { work_que.store(new std::queue<work_request>); } thread_worker::~thread_worker() { delete work_que.load(); } void thread_worker::process_next() { unsigned int size = work_que.load()->size(); fmt::print("quote_requester::process_next()size::{} \n", size); work_request* qr = &work_que.load()->front(); work_que.load()->pop(); //fmt::print("quote_requester:AFTER POP)size::{} \n", size; exmpdata d = qr->edat; d.someotherdata =+(double) (rand() % 10 + 1); //fmt::print("loeading key::") qr->des_bank.load()->update_data(d.samkey,d); } Key thread_worker::create_request(std::atomic<contaner_02*>& des_bank, exmpdata edat) { work_request wr(des_bank, edat); work_que.load()->push(std::move(wr)); des_bank.load()->registar(edat.samkey); are_pending(); return edat.samkey; } void thread_worker::shutdown() { fmt::print("shutdown single.. lol should THIS BE ATTOMIC I THINK SO!\n"); shutdown_signa = true; cv.notify_all(); } void thread_worker::operator()() { while(!shutdown_signa) { fmt::print("while(!q_requester.shutdown_signa)\n"); std::unique_lock<std::mutex> lck(mtx); cv.wait(lck,[&]{ fmt::print("q_requester.work_pending.load(){} ||||| q_requester.shutdown_signa{} \n",work_pending.load(), shutdown_signa); bool val = work_pending.load() || shutdown_signa; return val;}); fmt::print("q_requester.cv.wait)\n"); while(are_pending()) { fmt::print("inside are pending...num pending:{}\n",work_que.load()->size()); process_next(); } fmt::print("threadwork)\n"); lck.unlock(); } }
27.430556
138
0.559494
zeplaz
ba81edbb5e9c8ef57afb2428f9387c6aefeda48f
2,928
cpp
C++
uebungen/0x02/harkshire.cpp
pblan/fha-cpp
5008f54133cf4913f0ca558a3817b01b10d04494
[ "CECILL-B" ]
null
null
null
uebungen/0x02/harkshire.cpp
pblan/fha-cpp
5008f54133cf4913f0ca558a3817b01b10d04494
[ "CECILL-B" ]
null
null
null
uebungen/0x02/harkshire.cpp
pblan/fha-cpp
5008f54133cf4913f0ca558a3817b01b10d04494
[ "CECILL-B" ]
null
null
null
#include <iostream> const size_t stack_dim{3}; // Beispielstruktur 'stack': // Informieren Sie sich, wie ein 'Stack' funkt. // https://de.wikipedia.org/wiki/Stapelspeicher // Definieren Sie eine Struktur 'stack', die ein Feld fester Länge (z.B. 3) von // 'int' enthält, sowie eine Variable 'next' für die nächste freie Position im // Feld. struct stack { int buffer[stack_dim]; size_t next{0}; }; std::ostream &operator<<(std::ostream &os, const stack &st) { std::string delim; // (A) for (size_t i = 0; i < stack_dim; i++) { // (B) os << delim << st.buffer[i]; delim = ", "; } return os; } // Erweiterung: // Werfen Sie eine eigene Exception, wenn der Stack voll ist. struct stack_exception { std::string what; char level; }; int pop(stack &st); void push(stack &st, int n); void reset(stack &st); int main() { // Schreiben Sie aussagekräftigen Testcode. stack st; std::cout << "st: " << st << std::endl; reset(st); std::cout << "st after reset: " << st << std::endl; try { push(st, 2); std::cout << "st: " << st << std::endl; push(st, 3); std::cout << "st: " << st << std::endl; push(st, 5); std::cout << "st: " << st << std::endl; push(st, 7); std::cout << "st: " << st << std::endl; } catch (const stack_exception &e) { std::cerr << e.what << std::endl; } int num; try { num = pop(st); std::cout << "st: " << st << ", num: " << num << std::endl; num = pop(st); std::cout << "st: " << st << ", num: " << num << std::endl; num = pop(st); std::cout << "st: " << st << ", num: " << num << std::endl; num = pop(st); std::cout << "st: " << st << ", num: " << num << std::endl; } catch (const stack_exception &e) { std::cerr << e.what << std::endl; } } // Implementieren Sie Funktionen 'pop' und 'push', die Daten vom Stack holen, // bzw. dort ablegen (wenn Platz ist). int pop(stack &st) { if (st.next <= 0) { throw stack_exception{"stack empty", 'E'}; } return st.buffer[--st.next]; } void push(stack &st, int n) { if (st.next >= stack_dim) { throw stack_exception{"stack full", 'E'}; } st.buffer[st.next++] = n; } void reset(stack &st) { for (size_t i = 0; i < stack_dim; ++i) { st.buffer[i] = 0; } } /* Kommentierung * * (A) Per default wird ein std::string mit "" initialisiert. * std::string delim = ""; * wuerde natuerlich funktionieren, wird aber nicht empfohlen. * * Siehe dazu auch: * https://clang.llvm.org/extra/clang-tidy/checks/fuchsia-overloaded-operator.html * * (B) Generell sind ranged-based for-loops zu bevorzugen. Das spielt hier aber * erstmal eine geringere Rolle. * * Siehe dazu auch: * https://clang.llvm.org/extra/clang-tidy/checks/modernize-loop-convert.html */
25.684211
83
0.554986
pblan
ba84f2773de782f37cbd01ec2112889b21ca28e7
1,690
cpp
C++
networkit/cpp/graph/test/SpanningGTest.cpp
kmc-kk/networkit
28c1208104acae8ef70911340bf88b3e3dd08db7
[ "MIT" ]
null
null
null
networkit/cpp/graph/test/SpanningGTest.cpp
kmc-kk/networkit
28c1208104acae8ef70911340bf88b3e3dd08db7
[ "MIT" ]
1
2019-11-29T08:57:52.000Z
2019-11-29T08:57:52.000Z
networkit/cpp/graph/test/SpanningGTest.cpp
kmc-kk/networkit
28c1208104acae8ef70911340bf88b3e3dd08db7
[ "MIT" ]
1
2020-02-05T17:39:47.000Z
2020-02-05T17:39:47.000Z
/* * SpanningGTest.cpp * * Created on: 03.09.2015 * Author: Henning */ #include <gtest/gtest.h> #include <networkit/auxiliary/Log.hpp> #include <networkit/graph/KruskalMSF.hpp> #include <networkit/graph/SpanningForest.hpp> #include <networkit/io/METISGraphReader.hpp> namespace NetworKit { class SpanningGTest: public testing::Test {}; TEST_F(SpanningGTest, testKruskalMinSpanningForest) { METISGraphReader reader; std::vector<std::string> graphs = {"karate", "jazz", "celegans_metabolic"}; for (auto graphname: graphs) { std::string filename = "input/" + graphname + ".graph"; Graph G = reader.read(filename); KruskalMSF msf(G); msf.run(); Graph T = msf.getForest(); // check that each node has an edge in the spanning tree (if it had one before) T.forNodes([&](node u) { EXPECT_TRUE(T.degree(u) > 0 || G.degree(u) == 0); }); } } TEST_F(SpanningGTest, testSpanningForest) { METISGraphReader reader; std::vector<std::string> graphs = {"karate", "jazz", "celegans_metabolic"}; for (auto graphname: graphs) { std::string filename = "input/" + graphname + ".graph"; Graph G = reader.read(filename); SpanningForest msf(G); Graph T = msf.generate(); INFO("tree / graph edges: ", T.numberOfEdges(), " / ", G.numberOfEdges()); // check that each node has an edge in the spanning tree (if it had one before) T.forNodes([&](node u) { // INFO("tree/graph node degree: ", T.degree(u), " / ", G.degree(u)); EXPECT_TRUE(T.degree(u) > 0 || G.degree(u) == 0); }); } } } /* namespace NetworKit */
29.137931
87
0.611243
kmc-kk
ba883986a6e743edd41d05845b9216cdca1cf0f5
11,262
cpp
C++
src/utils/QCImporter.cpp
avasq011/FinalProject_OpenMS_76ers
6c9e2c295df6ec0eb296a3badfcdff245a869d59
[ "BSL-1.0", "Zlib", "Apache-2.0" ]
1
2019-06-11T13:03:08.000Z
2019-06-11T13:03:08.000Z
src/utils/QCImporter.cpp
avasq011/FinalProject_OpenMS_76ers
6c9e2c295df6ec0eb296a3badfcdff245a869d59
[ "BSL-1.0", "Zlib", "Apache-2.0" ]
1
2017-05-05T21:20:12.000Z
2017-05-05T21:20:12.000Z
src/utils/QCImporter.cpp
avasq011/FinalProject_OpenMS_76ers
6c9e2c295df6ec0eb296a3badfcdff245a869d59
[ "BSL-1.0", "Zlib", "Apache-2.0" ]
null
null
null
// -------------------------------------------------------------------------- // OpenMS -- Open-Source Mass Spectrometry // -------------------------------------------------------------------------- // Copyright The OpenMS Team -- Eberhard Karls University Tuebingen, // ETH Zurich, and Freie Universitaet Berlin 2002-2018. // // This software is released under a three-clause BSD license: // * 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 any author or any participating institution // may be used to endorse or promote products derived from this software // without specific prior written permission. // For a full list of authors, refer to the file AUTHORS. // -------------------------------------------------------------------------- // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING // INSTITUTIONS 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. // // -------------------------------------------------------------------------- // $Maintainer: Mathias Walzer $ // $Author: Mathias Walzer $ // -------------------------------------------------------------------------- #include <OpenMS/APPLICATIONS/TOPPBase.h> #include <OpenMS/FORMAT/CsvFile.h> #include <OpenMS/KERNEL/StandardTypes.h> #include <OpenMS/DATASTRUCTURES/String.h> #include <OpenMS/FORMAT/QcMLFile.h> #include <OpenMS/FORMAT/ControlledVocabulary.h> #include <OpenMS/SYSTEM/File.h> #include <OpenMS/CONCEPT/UniqueIdGenerator.h> #include <QByteArray> #include <QFile> #include <QString> #include <QFileInfo> //~ #include <QIODevice> #include <iostream> #include <fstream> #include <vector> #include <map> using namespace OpenMS; using namespace std; //------------------------------------------------------------- //Doxygen docu //------------------------------------------------------------- /** @page UTILS_QCImporter QCImporter @brief Will import several quality parameter from a tabular (text) format into a qcML file - counterpart to QCExporter. <CENTER> <table> <tr> <td ALIGN = "center" BGCOLOR="#EBEBEB"> pot. predecessor tools </td> <td VALIGN="middle" ROWSPAN=3> \f$ \longrightarrow \f$ QCEmbedder \f$ \longrightarrow \f$</td> <td ALIGN = "center" BGCOLOR="#EBEBEB"> pot. successor tools </td> </tr> <tr> <td VALIGN="middle" ALIGN = "center" ROWSPAN=1> @ref UTILS_QCExporter </td> <td VALIGN="middle" ALIGN = "center" ROWSPAN=1> @ref UTILS_QCMerger </td> </tr> <tr> <td VALIGN="middle" ALIGN = "center" ROWSPAN=1> @ref TOPP_XTandemAdapter </td> <td VALIGN="middle" ALIGN = "center" ROWSPAN=1> @ref UTILS_QCShrinker </td> </tr> </table> </CENTER> If there is additional data from external tools in tabular format containing additional quality parameter (qp) to runs or sets, or even new runs, these can be imported into the qcML file. For an example see the examples in the share directory. - @p table The table containing the additional qp values in the columns. First row is considered containing the header. The target run or set names/ids are indicated by column "raw data file", so each row after the header will contain the values of qps for that run. - @p mapping The mapping of the table header to the according qp cvs, also in csv format. The first row is considered containing the headers as in the table. The second row is considered the according qp cv accessions. <B>The command line parameters of this tool are:</B> @verbinclude UTILS_QCImporter.cli <B>INI file documentation of this tool:</B> @htmlinclude UTILS_QCImporter.html */ // We do not want this class to show up in the docu: /// @cond TOPPCLASSES class TOPPQCImporter : public TOPPBase { public: TOPPQCImporter() : TOPPBase("QCImporter", "Imports tables with quality control parameters into qcml files.", false, {{ "Walzer M, Pernas LE, Nasso S, Bittremieux W, Nahnsen S, Kelchtermans P, Martens, L", "qcML: An Exchange Format for Quality Control Metrics from Mass Spectrometry Experiments", "Molecular & Cellular Proteomics 2014; 13(8)" , "10.1074/mcp.M113.035907"}}) { } protected: void registerOptionsAndFlags_() override { registerInputFile_("in", "<file>", "", "Input qcml file", false); setValidFormats_("in", ListUtils::create<String>("qcML")); registerInputFile_("table", "<file>", "", "The table containing the additional qp values in the columns. First row is considered containing the header. The target run or set names/ids are indicated by column \"raw data file\", so each row after the header will contain the values of qps for that run. (csv without \"!)", true); setValidFormats_("table", ListUtils::create<String>("csv")); registerInputFile_("mapping", "<file>", "", "The mapping of the table header to the according qp cvs, also in csv format. The first row is considered containing the headers as in the table. The second row is considered the according qp cv accessions. (csv without \"!)", true); setValidFormats_("mapping", ListUtils::create<String>("csv")); registerOutputFile_("out", "<file>", "", "Output extended qcML file", true); setValidFormats_("out", ListUtils::create<String>("qcML")); } ExitCodes main_(int, const char**) override { //------------------------------------------------------------- // parsing parameters //------------------------------------------------------------- String in = getStringOption_("in"); String out = getStringOption_("out"); String mappi = getStringOption_("mapping"); String tab = getStringOption_("table"); ControlledVocabulary cv; cv.loadFromOBO("PSI-MS", File::find("/CV/psi-ms.obo")); cv.loadFromOBO("QC", File::find("/CV/qc-cv.obo")); //------------------------------------------------------------- // reading input //------------------------------------------------------------ QcMLFile qcmlfile; if (in != "") { qcmlfile.load(in); } if (mappi != "" && tab != "") { CsvFile csv_file(tab); CsvFile map_file(mappi); if (map_file.rowCount() < 2) //assumed that first row is the header of table and second row is the according qc { cerr << "Error: You have to give a mapping of your table (first row is the header of table and second row is the according qc). Aborting!" << endl; return ILLEGAL_PARAMETERS; } StringList header, according; map_file.getRow(0, header); map_file.getRow(1, according); if (header.size() != according.size()) { cerr << "Error: You have to give a mapping of your table (first row is the header of table and second row is the according qc). Aborting!" << endl; return ILLEGAL_PARAMETERS; } //~ std::map<String,String> mapping; //~ std::transform( header.begin(), header.end(), according.begin(), std::inserter(mapping, mapping.end() ), std::make_pair<String,String> ); int runset_col = -1; for (Size i = 0; i < according.size(); ++i) { if (!cv.exists(according[i])) { try { const ControlledVocabulary::CVTerm& term = cv.getTermByName(according[i]); header[i] = term.name; according[i] = term.id; } catch (...) { cerr << "Error: You have to specify a correct cv with accession or name in col " << String(i) << ". Aborting!" << endl; //~ cerr << "Header was: "<< header[i] << " , according value was: " << according[i] << endl; return ILLEGAL_PARAMETERS; } } else { const ControlledVocabulary::CVTerm& term = cv.getTerm(according[i]); header[i] = term.name; } if (header[i] == "raw data file") //TODO add set name as possibility! { runset_col = i; } } if (runset_col < 0) { cerr << "Error: You have to give a mapping of your table - rows to runs/sets. Aborting!" << endl; return ILLEGAL_PARAMETERS; } if (csv_file.rowCount() > 1) { StringList li; for (Size i = 1; i < csv_file.rowCount(); ++i) { StringList li; csv_file.getRow(i, li); if (li.size() < according.size()) { cerr << "Error: You have to give a correct mapping of your table - row " << String(i + 1) << " is too short. Aborting!" << endl; return ILLEGAL_PARAMETERS; } std::vector<QcMLFile::QualityParameter> qps; String id; bool set = false; for (Size j = 0; j < li.size(); ++j) { if (j == static_cast<Size>(runset_col)) { if (qcmlfile.existsRun(li[j])) //TODO this only works for real run IDs { id = li[j]; } else if (qcmlfile.existsSet(li[j])) //TODO this only works for real set IDs { id = li[j]; set = true; } else { id = li[j]; qcmlfile.registerRun(id, id); //TODO warn that if this was supposed to be a set - now it is not! } } QcMLFile::QualityParameter def; def.name = header[j]; ///< Name def.id = String(UniqueIdGenerator::getUniqueId()); def.cvRef = "QC"; ///< cv reference ('full name') def.cvAcc = according[j]; def.value = li[j]; qps.push_back(def); } if (id != "") { for (std::vector<QcMLFile::QualityParameter>::const_iterator qit = qps.begin(); qit != qps.end(); ++qit) { if (!set) { qcmlfile.addRunQualityParameter(id, *qit); } else { qcmlfile.addSetQualityParameter(id, *qit); } } } } } } qcmlfile.store(out); return EXECUTION_OK; } }; int main(int argc, const char** argv) { TOPPQCImporter tool; return tool.main(argc, argv); } /// @endcond
41.404412
358
0.580448
avasq011
ba8846bc029a3762e8fe6a2177d813a26897f75e
41,993
cpp
C++
src/engine/components/vgui2/dme_controls/particlesystempropertiespanel.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
6
2022-01-23T09:40:33.000Z
2022-03-20T20:53:25.000Z
src/engine/components/vgui2/dme_controls/particlesystempropertiespanel.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
null
null
null
src/engine/components/vgui2/dme_controls/particlesystempropertiespanel.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
1
2022-02-06T21:05:23.000Z
2022-02-06T21:05:23.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: Dialog used to edit properties of a particle system definition // //===========================================================================// #include "dme_controls/ParticleSystemPropertiesPanel.h" #include "tier1/KeyValues.h" #include "tier1/utlbuffer.h" #include "vgui/IVGui.h" #include "vgui_controls/button.h" #include "vgui_controls/listpanel.h" #include "vgui_controls/splitter.h" #include "vgui_controls/messagebox.h" #include "vgui_controls/combobox.h" #include "datamodel/dmelement.h" #include "movieobjects/dmeparticlesystemdefinition.h" #include "dme_controls/elementpropertiestree.h" #include "matsys_controls/picker.h" #include "dme_controls/dmecontrols_utils.h" #include "dme_controls/particlesystempanel.h" #include "dme_controls/dmepanel.h" // memdbgon must be the last include file in a .cpp file!!! #include <tier0/memdbgon.h> using namespace vgui; //----------------------------------------------------------------------------- // // Purpose: Picker for particle functions // //----------------------------------------------------------------------------- class CParticleFunctionPickerFrame : public vgui::Frame { DECLARE_CLASS_SIMPLE(CParticleFunctionPickerFrame, vgui::Frame); public: CParticleFunctionPickerFrame(vgui::Panel *pParent, const char *pTitle); ~CParticleFunctionPickerFrame(); // Sets the current scene + animation list void DoModal(CDmeParticleSystemDefinition *pParticleSystem, ParticleFunctionType_t type, KeyValues *pContextKeyValues); // Inherited from Frame virtual void OnCommand(const char *pCommand); private: // Refreshes the list of particle functions void RefreshParticleFunctions(CDmeParticleSystemDefinition *pDefinition, ParticleFunctionType_t type); void CleanUpMessage(); vgui::ListPanel *m_pFunctionList; vgui::Button *m_pOpenButton; vgui::Button *m_pCancelButton; KeyValues *m_pContextKeyValues; }; static int __cdecl ParticleFunctionNameSortFunc(vgui::ListPanel *pPanel, const vgui::ListPanelItem &item1, const vgui::ListPanelItem &item2) { const char *string1 = item1.kv->GetString("name"); const char *string2 = item2.kv->GetString("name"); return Q_stricmp(string1, string2); } CParticleFunctionPickerFrame::CParticleFunctionPickerFrame(vgui::Panel *pParent, const char *pTitle) : BaseClass(pParent, "ParticleFunctionPickerFrame") { SetDeleteSelfOnClose(true); m_pContextKeyValues = NULL; m_pFunctionList = new vgui::ListPanel(this, "ParticleFunctionList"); m_pFunctionList->AddColumnHeader(0, "name", "Particle Function Name", 52, 0); m_pFunctionList->SetSelectIndividualCells(false); m_pFunctionList->SetMultiselectEnabled(false); m_pFunctionList->SetEmptyListText("No particle functions"); m_pFunctionList->AddActionSignalTarget(this); m_pFunctionList->SetSortFunc(0, ParticleFunctionNameSortFunc); m_pFunctionList->SetSortColumn(0); m_pOpenButton = new vgui::Button(this, "OkButton", "#MessageBox_OK", this, "Ok"); m_pCancelButton = new vgui::Button(this, "CancelButton", "#MessageBox_Cancel", this, "Cancel"); SetBlockDragChaining(true); LoadControlSettingsAndUserConfig("resource/particlefunctionpicker.res"); SetTitle(pTitle, false); } CParticleFunctionPickerFrame::~CParticleFunctionPickerFrame() { CleanUpMessage(); } //----------------------------------------------------------------------------- // Refreshes the list of raw controls //----------------------------------------------------------------------------- void CParticleFunctionPickerFrame::RefreshParticleFunctions(CDmeParticleSystemDefinition *pParticleSystem, ParticleFunctionType_t type) { m_pFunctionList->RemoveAll(); if (!pParticleSystem) return; CUtlVector<IParticleOperatorDefinition *> &list = g_pParticleSystemMgr->GetAvailableParticleOperatorList(type); int nCount = list.Count(); // Build a list of used operator IDs bool pUsedIDs[OPERATOR_ID_COUNT]; memset(pUsedIDs, 0, sizeof(pUsedIDs)); int nFunctionCount = pParticleSystem->GetParticleFunctionCount(type); for (int i = 0; i < nFunctionCount; ++i) { const char *pFunctionName = pParticleSystem->GetParticleFunction(type, i)->GetName(); for (int j = 0; j < nCount; ++j) { if (Q_stricmp(pFunctionName, list[j]->GetName())) continue; if (list[j]->GetId() >= 0) { pUsedIDs[list[j]->GetId()] = true; } break; } } for (int i = 0; i < nCount; ++i) { const char *pFunctionName = list[i]->GetName(); // Look to see if this is in a special operator group if (list[i]->GetId() >= 0) { // Don't display ones that are already in the particle system if (pUsedIDs[list[i]->GetId()]) continue; } if (list[i]->GetId() == OPERATOR_SINGLETON) { // Don't display ones that are already in the particle system if (pParticleSystem->FindFunction(type, pFunctionName) >= 0) continue; } // Don't display obsolete operators if (list[i]->IsObsolete()) continue; KeyValues *kv = new KeyValues("node", "name", pFunctionName); m_pFunctionList->AddItem(kv, 0, false, false); } m_pFunctionList->SortList(); } //----------------------------------------------------------------------------- // Deletes the message //----------------------------------------------------------------------------- void CParticleFunctionPickerFrame::CleanUpMessage() { if (m_pContextKeyValues) { m_pContextKeyValues->deleteThis(); m_pContextKeyValues = NULL; } } //----------------------------------------------------------------------------- // Sets the current scene + animation list //----------------------------------------------------------------------------- void CParticleFunctionPickerFrame::DoModal(CDmeParticleSystemDefinition *pParticleSystem, ParticleFunctionType_t type, KeyValues *pContextKeyValues) { CleanUpMessage(); RefreshParticleFunctions(pParticleSystem, type); m_pContextKeyValues = pContextKeyValues; BaseClass::DoModal(); } //----------------------------------------------------------------------------- // On command //----------------------------------------------------------------------------- void CParticleFunctionPickerFrame::OnCommand(const char *pCommand) { if (!Q_stricmp(pCommand, "Ok")) { int nSelectedItemCount = m_pFunctionList->GetSelectedItemsCount(); if (nSelectedItemCount == 0) return; Assert(nSelectedItemCount == 1); int nItemID = m_pFunctionList->GetSelectedItem(0); KeyValues *pKeyValues = m_pFunctionList->GetItem(nItemID); KeyValues *pActionKeys = new KeyValues("ParticleFunctionPicked"); pActionKeys->SetString("name", pKeyValues->GetString("name")); if (m_pContextKeyValues) { pActionKeys->AddSubKey(m_pContextKeyValues); // This prevents them from being deleted later m_pContextKeyValues = NULL; } PostActionSignal(pActionKeys); CloseModal(); return; } if (!Q_stricmp(pCommand, "Cancel")) { CloseModal(); return; } BaseClass::OnCommand(pCommand); } //----------------------------------------------------------------------------- // // Purpose: Picker for child particle systems // //----------------------------------------------------------------------------- class CParticleChildrenPickerFrame : public vgui::Frame { DECLARE_CLASS_SIMPLE(CParticleChildrenPickerFrame, vgui::Frame); public: CParticleChildrenPickerFrame(vgui::Panel *pParent, const char *pTitle, IParticleSystemPropertiesPanelQuery *pQuery); ~CParticleChildrenPickerFrame(); // Sets the current scene + animation list void DoModal(CDmeParticleSystemDefinition *pParticleSystem, KeyValues *pContextKeyValues); // Inherited from Frame virtual void OnCommand(const char *pCommand); private: // Refreshes the list of children particle systems void RefreshChildrenList(CDmeParticleSystemDefinition *pDefinition); void CleanUpMessage(); IParticleSystemPropertiesPanelQuery *m_pQuery; vgui::ListPanel *m_pChildrenList; vgui::Button *m_pOpenButton; vgui::Button *m_pCancelButton; KeyValues *m_pContextKeyValues; }; static int __cdecl ParticleChildrenNameSortFunc(vgui::ListPanel *pPanel, const vgui::ListPanelItem &item1, const vgui::ListPanelItem &item2) { const char *string1 = item1.kv->GetString("name"); const char *string2 = item2.kv->GetString("name"); return Q_stricmp(string1, string2); } CParticleChildrenPickerFrame::CParticleChildrenPickerFrame(vgui::Panel *pParent, const char *pTitle, IParticleSystemPropertiesPanelQuery *pQuery) : BaseClass(pParent, "ParticleChildrenPickerFrame"), m_pQuery(pQuery) { SetDeleteSelfOnClose(true); m_pContextKeyValues = NULL; m_pChildrenList = new vgui::ListPanel(this, "ParticleChildrenList"); m_pChildrenList->AddColumnHeader(0, "name", "Particle System Name", 52, 0); m_pChildrenList->SetSelectIndividualCells(false); m_pChildrenList->SetMultiselectEnabled(false); m_pChildrenList->SetEmptyListText("No particle systems"); m_pChildrenList->AddActionSignalTarget(this); m_pChildrenList->SetSortFunc(0, ParticleChildrenNameSortFunc); m_pChildrenList->SetSortColumn(0); m_pOpenButton = new vgui::Button(this, "OkButton", "#MessageBox_OK", this, "Ok"); m_pCancelButton = new vgui::Button(this, "CancelButton", "#MessageBox_Cancel", this, "Cancel"); SetBlockDragChaining(true); LoadControlSettingsAndUserConfig("resource/particlechildrenpicker.res"); SetTitle(pTitle, false); } CParticleChildrenPickerFrame::~CParticleChildrenPickerFrame() { CleanUpMessage(); } //----------------------------------------------------------------------------- // Refreshes the list of raw controls //----------------------------------------------------------------------------- void CParticleChildrenPickerFrame::RefreshChildrenList(CDmeParticleSystemDefinition *pCurrentParticleSystem) { m_pChildrenList->RemoveAll(); CUtlVector<CDmeParticleSystemDefinition *> definitions; if (m_pQuery) { m_pQuery->GetKnownParticleDefinitions(definitions); } int nCount = definitions.Count(); if (nCount == 0) return; for (int i = 0; i < nCount; ++i) { CDmeParticleSystemDefinition *pParticleSystem = definitions[i]; if (pParticleSystem == pCurrentParticleSystem) continue; const char *pName = pParticleSystem->GetName(); if (!pName || !pName[0]) { pName = "<no name>"; } KeyValues *kv = new KeyValues("node"); kv->SetString("name", pName); SetElementKeyValue(kv, "particleSystem", pParticleSystem); m_pChildrenList->AddItem(kv, 0, false, false); } m_pChildrenList->SortList(); } //----------------------------------------------------------------------------- // Deletes the message //----------------------------------------------------------------------------- void CParticleChildrenPickerFrame::CleanUpMessage() { if (m_pContextKeyValues) { m_pContextKeyValues->deleteThis(); m_pContextKeyValues = NULL; } } //----------------------------------------------------------------------------- // Sets the current scene + animation list //----------------------------------------------------------------------------- void CParticleChildrenPickerFrame::DoModal(CDmeParticleSystemDefinition *pParticleSystem, KeyValues *pContextKeyValues) { CleanUpMessage(); RefreshChildrenList(pParticleSystem); m_pContextKeyValues = pContextKeyValues; BaseClass::DoModal(); } //----------------------------------------------------------------------------- // On command //----------------------------------------------------------------------------- void CParticleChildrenPickerFrame::OnCommand(const char *pCommand) { if (!Q_stricmp(pCommand, "Ok")) { int nSelectedItemCount = m_pChildrenList->GetSelectedItemsCount(); if (nSelectedItemCount == 0) return; Assert(nSelectedItemCount == 1); int nItemID = m_pChildrenList->GetSelectedItem(0); KeyValues *pKeyValues = m_pChildrenList->GetItem(nItemID); CDmeParticleSystemDefinition *pParticleSystem = GetElementKeyValue<CDmeParticleSystemDefinition>(pKeyValues, "particleSystem"); KeyValues *pActionKeys = new KeyValues("ParticleChildPicked"); SetElementKeyValue(pActionKeys, "particleSystem", pParticleSystem); if (m_pContextKeyValues) { pActionKeys->AddSubKey(m_pContextKeyValues); // This prevents them from being deleted later m_pContextKeyValues = NULL; } PostActionSignal(pActionKeys); CloseModal(); return; } if (!Q_stricmp(pCommand, "Cancel")) { CloseModal(); return; } BaseClass::OnCommand(pCommand); } //----------------------------------------------------------------------------- // Browser of various particle functions //----------------------------------------------------------------------------- class CParticleFunctionBrowser : public vgui::EditablePanel { DECLARE_CLASS_SIMPLE(CParticleFunctionBrowser, vgui::EditablePanel); public: // constructor, destructor CParticleFunctionBrowser(vgui::Panel *pParent, const char *pName, ParticleFunctionType_t type, IParticleSystemPropertiesPanelQuery *pQuery); virtual ~CParticleFunctionBrowser(); // Inherited from Panel virtual void OnKeyCodeTyped(vgui::KeyCode code); void SetParticleFunctionProperties(CDmeElementPanel *pPanel); void SetParticleSystem(CDmeParticleSystemDefinition *pOp); void RefreshParticleFunctionList(); void SelectDefaultFunction(); // Called when a list panel's selection changes void RefreshParticleFunctionProperties(); private: MESSAGE_FUNC_PARAMS(OnOpenContextMenu, "OpenContextMenu", kv); MESSAGE_FUNC_PARAMS(OnItemSelected, "ItemSelected", kv); MESSAGE_FUNC_PARAMS(OnItemDeselected, "ItemDeselected", kv); MESSAGE_FUNC(OnAdd, "Add"); MESSAGE_FUNC(OnRemove, "Remove"); MESSAGE_FUNC(OnRename, "Rename"); MESSAGE_FUNC(OnMoveUp, "MoveUp"); MESSAGE_FUNC(OnMoveDown, "MoveDown"); MESSAGE_FUNC_PARAMS(OnInputCompleted, "InputCompleted", kv); MESSAGE_FUNC_PARAMS(OnParticleFunctionPicked, "ParticleFunctionPicked", kv); MESSAGE_FUNC_PARAMS(OnParticleChildPicked, "ParticleChildPicked", kv); // Cleans up the context menu void CleanupContextMenu(); // Returns the selected particle function CDmeParticleFunction *GetSelectedFunction(); // Returns the selected particle function CDmeParticleFunction *GetSelectedFunction(int nIndex); // Select a particular particle function void SelectParticleFunction(CDmeParticleFunction *pFind); IParticleSystemPropertiesPanelQuery *m_pQuery; CDmeHandle<CDmeParticleSystemDefinition> m_hParticleSystem; vgui::ListPanel *m_pFunctionList; ParticleFunctionType_t m_FuncType; vgui::DHANDLE<vgui::Menu> m_hContextMenu; CDmeElementPanel *m_pParticleFunctionProperties; }; //----------------------------------------------------------------------------- // Sort functions for list panel //----------------------------------------------------------------------------- static int __cdecl ParticleFunctionSortFunc(vgui::ListPanel *pPanel, const vgui::ListPanelItem &item1, const vgui::ListPanelItem &item2) { int i1 = item1.kv->GetInt("index"); int i2 = item2.kv->GetInt("index"); return i1 - i2; } //----------------------------------------------------------------------------- // constructor, destructor //----------------------------------------------------------------------------- CParticleFunctionBrowser::CParticleFunctionBrowser(vgui::Panel *pParent, const char *pName, ParticleFunctionType_t type, IParticleSystemPropertiesPanelQuery *pQuery) : BaseClass(pParent, pName), m_pQuery(pQuery) { SetKeyBoardInputEnabled(true); m_FuncType = type; m_pFunctionList = new vgui::ListPanel(this, "FunctionList"); if (m_FuncType != FUNCTION_CHILDREN) { m_pFunctionList->AddColumnHeader(0, "name", "Function Name", 150, 0); m_pFunctionList->AddColumnHeader(1, "type", "Function Type", 150, 0); m_pFunctionList->SetEmptyListText("No particle functions"); } else { m_pFunctionList->AddColumnHeader(0, "name", "Label", 150, 0); m_pFunctionList->AddColumnHeader(1, "type", "Child Name", 150, 0); m_pFunctionList->SetEmptyListText("No children"); } m_pFunctionList->SetSelectIndividualCells(false); m_pFunctionList->SetMultiselectEnabled(true); m_pFunctionList->AddActionSignalTarget(this); m_pFunctionList->SetSortFunc(0, ParticleFunctionSortFunc); m_pFunctionList->SetSortColumn(0); m_pFunctionList->AddActionSignalTarget(this); LoadControlSettings("resource/particlefunctionbrowser.res"); } CParticleFunctionBrowser::~CParticleFunctionBrowser() { CleanupContextMenu(); SaveUserConfig(); } //----------------------------------------------------------------------------- // Cleans up the context menu //----------------------------------------------------------------------------- void CParticleFunctionBrowser::CleanupContextMenu() { if (m_hContextMenu.Get()) { m_hContextMenu->MarkForDeletion(); m_hContextMenu = NULL; } } //----------------------------------------------------------------------------- // Selects a particular function by default //----------------------------------------------------------------------------- void CParticleFunctionBrowser::SelectDefaultFunction() { if (m_pFunctionList->GetSelectedItemsCount() == 0 && m_pFunctionList->GetItemCount() > 0) { int nItemID = m_pFunctionList->GetItemIDFromRow(0); m_pFunctionList->SetSingleSelectedItem(nItemID); } } //----------------------------------------------------------------------------- // Sets the particle system properties panel //----------------------------------------------------------------------------- void CParticleFunctionBrowser::SetParticleFunctionProperties(CDmeElementPanel *pPanel) { m_pParticleFunctionProperties = pPanel; } //----------------------------------------------------------------------------- // Sets/gets the particle system //----------------------------------------------------------------------------- void CParticleFunctionBrowser::SetParticleSystem(CDmeParticleSystemDefinition *pParticleSystem) { if (pParticleSystem != m_hParticleSystem.Get()) { m_hParticleSystem = pParticleSystem; RefreshParticleFunctionList(); SelectDefaultFunction(); } } //----------------------------------------------------------------------------- // Builds the particle function list for the particle system //----------------------------------------------------------------------------- void CParticleFunctionBrowser::RefreshParticleFunctionList() { if (!m_hParticleSystem.Get()) return; // Maintain selection if possible CUtlVector<CDmeParticleFunction *> selectedItems; int nCount = m_pFunctionList->GetSelectedItemsCount(); for (int i = 0; i < nCount; ++i) { selectedItems.AddToTail(GetSelectedFunction(i)); } m_pFunctionList->RemoveAll(); int nSelectedCount = selectedItems.Count(); nCount = m_hParticleSystem->GetParticleFunctionCount(m_FuncType); for (int i = 0; i < nCount; ++i) { CDmeParticleFunction *pFunction = m_hParticleSystem->GetParticleFunction(m_FuncType, i); KeyValues *kv = new KeyValues("node", "name", pFunction->GetName()); kv->SetString("type", pFunction->GetFunctionType()); kv->SetInt("index", i); SetElementKeyValue(kv, "particleFunction", pFunction); int nItemID = m_pFunctionList->AddItem(kv, 0, false, false); for (int j = 0; j < nSelectedCount; ++j) { if (selectedItems[j] == pFunction) { m_pFunctionList->AddSelectedItem(nItemID); selectedItems.FastRemove(j); --nSelectedCount; break; } } } m_pFunctionList->SortList(); } //----------------------------------------------------------------------------- // Returns the selected particle function //----------------------------------------------------------------------------- CDmeParticleFunction *CParticleFunctionBrowser::GetSelectedFunction(int nIndex) { if (!m_hParticleSystem.Get()) return NULL; int nSelectedItemCount = m_pFunctionList->GetSelectedItemsCount(); if (nSelectedItemCount <= nIndex) return NULL; int nItemID = m_pFunctionList->GetSelectedItem(nIndex); KeyValues *pKeyValues = m_pFunctionList->GetItem(nItemID); return GetElementKeyValue<CDmeParticleFunction>(pKeyValues, "particleFunction"); } //----------------------------------------------------------------------------- // Returns the selected particle function //----------------------------------------------------------------------------- CDmeParticleFunction *CParticleFunctionBrowser::GetSelectedFunction() { if (!m_hParticleSystem.Get()) return NULL; int nSelectedItemCount = m_pFunctionList->GetSelectedItemsCount(); if (nSelectedItemCount != 1) return NULL; int nItemID = m_pFunctionList->GetSelectedItem(0); KeyValues *pKeyValues = m_pFunctionList->GetItem(nItemID); return GetElementKeyValue<CDmeParticleFunction>(pKeyValues, "particleFunction"); } void CParticleFunctionBrowser::OnMoveUp() { CDmeParticleFunction *pFunction = GetSelectedFunction(); if (!pFunction) return; { CUndoScopeGuard guard(0, NOTIFY_SETDIRTYFLAG, "Move Function Up", "Move Function Up"); m_hParticleSystem->MoveFunctionUp(m_FuncType, pFunction); } PostActionSignal(new KeyValues("ParticleSystemModified")); } void CParticleFunctionBrowser::OnMoveDown() { CDmeParticleFunction *pFunction = GetSelectedFunction(); if (!pFunction) return; { CUndoScopeGuard guard(0, NOTIFY_SETDIRTYFLAG, "Move Function Down", "Move Function Down"); m_hParticleSystem->MoveFunctionDown(m_FuncType, pFunction); } PostActionSignal(new KeyValues("ParticleSystemModified")); } //----------------------------------------------------------------------------- // Select a particular particle function //----------------------------------------------------------------------------- void CParticleFunctionBrowser::SelectParticleFunction(CDmeParticleFunction *pFind) { m_pFunctionList->ClearSelectedItems(); for (int nItemID = m_pFunctionList->FirstItem(); nItemID != m_pFunctionList->InvalidItemID(); nItemID = m_pFunctionList->NextItem(nItemID)) { KeyValues *kv = m_pFunctionList->GetItem(nItemID); CDmeParticleFunction *pFunction = GetElementKeyValue<CDmeParticleFunction>(kv, "particleFunction"); if (pFunction == pFind) { m_pFunctionList->AddSelectedItem(nItemID); break; } } } //----------------------------------------------------------------------------- // Add/remove functions //----------------------------------------------------------------------------- void CParticleFunctionBrowser::OnParticleChildPicked(KeyValues *pKeyValues) { CDmeParticleSystemDefinition *pParticleSystem = GetElementKeyValue<CDmeParticleSystemDefinition>(pKeyValues, "particleSystem"); if (!pParticleSystem || (m_FuncType != FUNCTION_CHILDREN)) return; CDmeParticleFunction *pFunction; { CUndoScopeGuard guard(0, NOTIFY_SETDIRTYFLAG, "Add Particle System Child", "Add Particle System Child"); pFunction = m_hParticleSystem->AddChild(pParticleSystem); } PostActionSignal(new KeyValues("ParticleSystemModified")); SelectParticleFunction(pFunction); } void CParticleFunctionBrowser::OnParticleFunctionPicked(KeyValues *pKeyValues) { if (m_FuncType == FUNCTION_CHILDREN) return; const char *pParticleFuncName = pKeyValues->GetString("name"); CDmeParticleFunction *pFunction; { CUndoScopeGuard guard(0, NOTIFY_SETDIRTYFLAG, "Add Particle Function", "Add Particle Function"); pFunction = m_hParticleSystem->AddOperator(m_FuncType, pParticleFuncName); } PostActionSignal(new KeyValues("ParticleSystemModified")); SelectParticleFunction(pFunction); } void CParticleFunctionBrowser::OnAdd() { if (m_FuncType != FUNCTION_CHILDREN) { CParticleFunctionPickerFrame *pPicker = new CParticleFunctionPickerFrame(this, "Select Particle Function"); pPicker->DoModal(m_hParticleSystem, m_FuncType, NULL); } else { CParticleChildrenPickerFrame *pPicker = new CParticleChildrenPickerFrame(this, "Select Child Particle Systems", m_pQuery); pPicker->DoModal(m_hParticleSystem, NULL); } } void CParticleFunctionBrowser::OnRemove() { int iSel = m_pFunctionList->GetSelectedItem(0); int nRow = m_pFunctionList->GetItemCurrentRow(iSel) - 1; { CUndoScopeGuard guard(0, NOTIFY_SETDIRTYFLAG, "Remove Particle Function", "Remove Particle Function"); // // Build a list of objects to delete. // CUtlVector<CDmeParticleFunction *> itemsToDelete; int nCount = m_pFunctionList->GetSelectedItemsCount(); for (int i = 0; i < nCount; i++) { CDmeParticleFunction *pParticleFunction = GetSelectedFunction(i); if (pParticleFunction) { itemsToDelete.AddToTail(pParticleFunction); } } nCount = itemsToDelete.Count(); for (int i = 0; i < nCount; ++i) { m_hParticleSystem->RemoveFunction(m_FuncType, itemsToDelete[i]); } } PostActionSignal(new KeyValues("ParticleSystemModified")); // Update the list box selection. if (m_pFunctionList->GetItemCount() > 0) { if (nRow < 0) { nRow = 0; } else if (nRow >= m_pFunctionList->GetItemCount()) { nRow = m_pFunctionList->GetItemCount() - 1; } iSel = m_pFunctionList->GetItemIDFromRow(nRow); m_pFunctionList->SetSingleSelectedItem(iSel); } else { m_pFunctionList->ClearSelectedItems(); } } //----------------------------------------------------------------------------- // Rename a particle function //----------------------------------------------------------------------------- void CParticleFunctionBrowser::OnInputCompleted(KeyValues *pKeyValues) { const char *pName = pKeyValues->GetString("text"); CDmeParticleFunction *pFunction = GetSelectedFunction(); { CUndoScopeGuard guard(0, NOTIFY_SETDIRTYFLAG, "Rename Particle Function", "Rename Particle Function"); pFunction->SetName(pName); } PostActionSignal(new KeyValues("ParticleSystemModified")); } //----------------------------------------------------------------------------- // Rename a particle function //----------------------------------------------------------------------------- void CParticleFunctionBrowser::OnRename() { int nSelectedItemCount = m_pFunctionList->GetSelectedItemsCount(); if (nSelectedItemCount != 1) return; vgui::InputDialog *pInput = new vgui::InputDialog(this, "Rename Particle Function", "Enter new name of particle function"); pInput->SetMultiline(false); pInput->DoModal(); } //----------------------------------------------------------------------------- // Called when a list panel's selection changes //----------------------------------------------------------------------------- void CParticleFunctionBrowser::RefreshParticleFunctionProperties() { if (IsVisible()) { CDmeParticleFunction *pFunction = GetSelectedFunction(); if (pFunction) { m_pParticleFunctionProperties->SetTypeDictionary(pFunction->GetEditorTypeDictionary()); } m_pParticleFunctionProperties->SetDmeElement(pFunction); // Notify the outside world so we can get helpers to render correctly in the preview KeyValues *pMessage = new KeyValues("ParticleFunctionSelChanged"); SetElementKeyValue(pMessage, "function", pFunction); PostActionSignal(pMessage); } } //----------------------------------------------------------------------------- // Called when a list panel's selection changes //----------------------------------------------------------------------------- void CParticleFunctionBrowser::OnItemSelected(KeyValues *kv) { Panel * pPanel = (Panel *) kv->GetPtr("panel", NULL); if (pPanel == m_pFunctionList) { RefreshParticleFunctionProperties(); return; } } //----------------------------------------------------------------------------- // Called when a list panel's selection changes //----------------------------------------------------------------------------- void CParticleFunctionBrowser::OnItemDeselected(KeyValues *kv) { Panel * pPanel = (Panel *) kv->GetPtr("panel", NULL); if (pPanel == m_pFunctionList) { RefreshParticleFunctionProperties(); return; } } //----------------------------------------------------------------------------- // Called to open a context-sensitive menu for a particular menu item //----------------------------------------------------------------------------- void CParticleFunctionBrowser::OnOpenContextMenu(KeyValues *kv) { CleanupContextMenu(); if (!m_hParticleSystem.Get()) return; Panel * pPanel = (Panel *) kv->GetPtr("panel", NULL); if (pPanel != m_pFunctionList) return; int nSelectedItemCount = m_pFunctionList->GetSelectedItemsCount(); m_hContextMenu = new vgui::Menu(this, "ActionMenu"); m_hContextMenu->AddMenuItem("#ParticleFunctionBrowser_Add", new KeyValues("Add"), this); if (nSelectedItemCount >= 1) { m_hContextMenu->AddMenuItem("#ParticleFunctionBrowser_Remove", new KeyValues("Remove"), this); } if (nSelectedItemCount == 1) { m_hContextMenu->AddMenuItem("#ParticleFunctionBrowser_Rename", new KeyValues("Rename"), this); m_hContextMenu->AddSeparator(); m_hContextMenu->AddMenuItem("#ParticleFunctionBrowser_MoveUp", new KeyValues("MoveUp"), this); m_hContextMenu->AddMenuItem("#ParticleFunctionBrowser_MoveDown", new KeyValues("MoveDown"), this); } vgui::Menu::PlaceContextMenu(this, m_hContextMenu.Get()); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CParticleFunctionBrowser::OnKeyCodeTyped(vgui::KeyCode code) { if (code == KEY_DELETE) { OnRemove(); } else { BaseClass::OnKeyCodeTyped(code); } } //----------------------------------------------------------------------------- // Strings //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Constructor //----------------------------------------------------------------------------- CParticleSystemPropertiesPanel::CParticleSystemPropertiesPanel(IParticleSystemPropertiesPanelQuery *pQuery, vgui::Panel *pParent) : BaseClass(pParent, "ParticleSystemPropertiesPanel"), m_pQuery(pQuery) { SetKeyBoardInputEnabled(true); m_pSplitter = new vgui::Splitter(this, "Splitter", vgui::SPLITTER_MODE_VERTICAL, 1); vgui::Panel * pSplitterLeftSide = m_pSplitter->GetChild(0); vgui::Panel * pSplitterRightSide = m_pSplitter->GetChild(1); m_pFunctionBrowserArea = new vgui::EditablePanel(pSplitterLeftSide, "FunctionBrowserArea"); m_pFunctionTypeCombo = new vgui::ComboBox(pSplitterLeftSide, "FunctionTypeCombo", PARTICLE_FUNCTION_COUNT + 1, false); m_pFunctionTypeCombo->AddItem("Properties", new KeyValues("choice", "index", -1)); m_pFunctionTypeCombo->AddActionSignalTarget(this); m_pParticleFunctionProperties = new CDmeElementPanel(pSplitterRightSide, "FunctionProperties"); m_pParticleFunctionProperties->SetAutoResize(vgui::Panel::PIN_TOPLEFT, vgui::Panel::AUTORESIZE_DOWNANDRIGHT, 6, 6, -6, -6); m_pParticleFunctionProperties->AddActionSignalTarget(this); for (int i = 0; i < PARTICLE_FUNCTION_COUNT; ++i) { const char *pTypeName = GetParticleFunctionTypeName((ParticleFunctionType_t) i); m_pFunctionTypeCombo->AddItem(pTypeName, new KeyValues("choice", "index", i)); m_pParticleFunctionBrowser[i] = new CParticleFunctionBrowser(m_pFunctionBrowserArea, "FunctionBrowser", (ParticleFunctionType_t) i, m_pQuery); m_pParticleFunctionBrowser[i]->SetParticleFunctionProperties(m_pParticleFunctionProperties); m_pParticleFunctionBrowser[i]->AddActionSignalTarget(this); } m_pFunctionTypeCombo->ActivateItemByRow(0); LoadControlSettings("resource/particlesystempropertiespanel.res"); } //----------------------------------------------------------------------------- // Sets the particle system to look at //----------------------------------------------------------------------------- void CParticleSystemPropertiesPanel::SetParticleSystem(CDmeParticleSystemDefinition *pParticleSystem) { m_hParticleSystem = pParticleSystem; for (int i = 0; i < PARTICLE_FUNCTION_COUNT; ++i) { m_pParticleFunctionBrowser[i]->SetParticleSystem(pParticleSystem); } KeyValues *pKeyValues = m_pFunctionTypeCombo->GetActiveItemUserData(); int nPage = pKeyValues->GetInt("index"); if (nPage < 0) { if (m_hParticleSystem.Get()) { m_pParticleFunctionProperties->SetTypeDictionary(m_hParticleSystem->GetEditorTypeDictionary()); } m_pParticleFunctionProperties->SetDmeElement(m_hParticleSystem); } } //----------------------------------------------------------------------------- // Called when something changes in the dmeelement panel //----------------------------------------------------------------------------- void CParticleSystemPropertiesPanel::OnDmeElementChanged(KeyValues *pKeyValues) { int nNotifyFlags = pKeyValues->GetInt("notifyFlags"); OnParticleSystemModified(); if (nNotifyFlags & (NOTIFY_CHANGE_TOPOLOGICAL | NOTIFY_CHANGE_ATTRIBUTE_ARRAY_SIZE)) { for (int i = 0; i < PARTICLE_FUNCTION_COUNT; ++i) { m_pParticleFunctionBrowser[i]->RefreshParticleFunctionList(); } } PostActionSignal(new KeyValues("ParticleSystemModified")); } void CParticleSystemPropertiesPanel::OnParticleSystemModifiedInternal() { OnParticleSystemModified(); Refresh(false); PostActionSignal(new KeyValues("ParticleSystemModified")); } void CParticleSystemPropertiesPanel::OnParticleFunctionSelChanged(KeyValues *pParams) { // Notify the outside world so we can get helpers to render correctly in the preview CDmeParticleFunction *pFunction = GetElementKeyValue<CDmeParticleFunction>(pParams, "function"); KeyValues *pMessage = new KeyValues("ParticleFunctionSelChanged"); SetElementKeyValue(pMessage, "function", pFunction); PostActionSignal(pMessage); } //----------------------------------------------------------------------------- // Refreshes display //----------------------------------------------------------------------------- void CParticleSystemPropertiesPanel::Refresh(bool bValuesOnly) { for (int i = 0; i < PARTICLE_FUNCTION_COUNT; ++i) { m_pParticleFunctionBrowser[i]->RefreshParticleFunctionList(); } m_pParticleFunctionProperties->Refresh(bValuesOnly ? CElementPropertiesTreeInternal::REFRESH_VALUES_ONLY : CElementPropertiesTreeInternal::REFRESH_TREE_VIEW); } //----------------------------------------------------------------------------- // Purpose: Called when a page is shown //----------------------------------------------------------------------------- void CParticleSystemPropertiesPanel::OnTextChanged() { for (int i = 0; i < PARTICLE_FUNCTION_COUNT; ++i) { m_pParticleFunctionBrowser[i]->SetVisible(false); } KeyValues *pKeyValues = m_pFunctionTypeCombo->GetActiveItemUserData(); int nPage = pKeyValues->GetInt("index"); if (nPage < 0) { if (m_hParticleSystem.Get()) { m_pParticleFunctionProperties->SetTypeDictionary(m_hParticleSystem->GetEditorTypeDictionary()); } m_pParticleFunctionProperties->SetDmeElement(m_hParticleSystem); return; } m_pParticleFunctionBrowser[nPage]->SetVisible(true); m_pParticleFunctionBrowser[nPage]->SelectDefaultFunction(); m_pParticleFunctionBrowser[nPage]->RefreshParticleFunctionProperties(); } //----------------------------------------------------------------------------- // A little panel used as a DmePanel for particle systems //----------------------------------------------------------------------------- class CParticleSystemDmePanel : public vgui::EditablePanel { DECLARE_CLASS_SIMPLE(CParticleSystemDmePanel, vgui::EditablePanel); public: // constructor, destructor CParticleSystemDmePanel(vgui::Panel *pParent, const char *pName); virtual ~CParticleSystemDmePanel(); // Set the material to draw void SetDmeElement(CDmeParticleSystemDefinition *pDef); private: MESSAGE_FUNC_INT(OnElementChangedExternally, "ElementChangedExternally", valuesOnly); MESSAGE_FUNC(OnParticleSystemModified, "ParticleSystemModified"); MESSAGE_FUNC_PARAMS(OnParticleFunctionSelChanged, "ParticleFunctionSelChanged", params); vgui::Splitter *m_Splitter; CParticleSystemPropertiesPanel *m_pProperties; CParticleSystemPreviewPanel *m_pPreview; }; //----------------------------------------------------------------------------- // Dme panel connection //----------------------------------------------------------------------------- IMPLEMENT_DMEPANEL_FACTORY(CParticleSystemDmePanel, DmeParticleSystemDefinition, "DmeParticleSystemDefinitionEditor", "Particle System Editor", true); //----------------------------------------------------------------------------- // constructor, destructor //----------------------------------------------------------------------------- CParticleSystemDmePanel::CParticleSystemDmePanel(vgui::Panel *pParent, const char *pName) : BaseClass(pParent, pName) { m_Splitter = new vgui::Splitter(this, "Splitter", SPLITTER_MODE_HORIZONTAL, 1); vgui::Panel * pSplitterTopSide = m_Splitter->GetChild(0); vgui::Panel * pSplitterBottomSide = m_Splitter->GetChild(1); m_Splitter->SetAutoResize(PIN_TOPLEFT, AUTORESIZE_DOWNANDRIGHT, 0, 0, 0, 0); m_pProperties = new CParticleSystemPropertiesPanel(NULL, pSplitterBottomSide); m_pProperties->AddActionSignalTarget(this); m_pProperties->SetAutoResize(PIN_TOPLEFT, AUTORESIZE_DOWNANDRIGHT, 0, 0, 0, 0); m_pPreview = new CParticleSystemPreviewPanel(pSplitterTopSide, "Preview"); m_pPreview->SetAutoResize(PIN_TOPLEFT, AUTORESIZE_DOWNANDRIGHT, 0, 0, 0, 0); } CParticleSystemDmePanel::~CParticleSystemDmePanel() { } //----------------------------------------------------------------------------- // Layout //----------------------------------------------------------------------------- void CParticleSystemDmePanel::SetDmeElement(CDmeParticleSystemDefinition *pDef) { m_pProperties->SetParticleSystem(pDef); m_pPreview->SetParticleSystem(pDef); } //----------------------------------------------------------------------------- // Particle system modified externally to the editor //----------------------------------------------------------------------------- void CParticleSystemDmePanel::OnElementChangedExternally(int valuesOnly) { m_pProperties->Refresh(valuesOnly != 0); } //----------------------------------------------------------------------------- // Called when the selected particle function changes //----------------------------------------------------------------------------- void CParticleSystemDmePanel::OnParticleFunctionSelChanged(KeyValues *pParams) { CDmeParticleFunction *pFunction = GetElementKeyValue<CDmeParticleFunction>(pParams, "function"); m_pPreview->SetParticleFunction(pFunction); } //----------------------------------------------------------------------------- // Communicate to the owning DmePanel //----------------------------------------------------------------------------- void CParticleSystemDmePanel::OnParticleSystemModified() { PostActionSignal(new KeyValues("DmeElementChanged")); }
39.136067
123
0.586145
cstom4994
ba9029fc3d027c284d5ff8f48df412f56becc9f3
2,697
cpp
C++
src/software/ai/primitive/chip_primitive_test.cpp
scveloso/Software
ac882d3df0aa0d108e5157c076c82c030d023e12
[ "MIT" ]
null
null
null
src/software/ai/primitive/chip_primitive_test.cpp
scveloso/Software
ac882d3df0aa0d108e5157c076c82c030d023e12
[ "MIT" ]
null
null
null
src/software/ai/primitive/chip_primitive_test.cpp
scveloso/Software
ac882d3df0aa0d108e5157c076c82c030d023e12
[ "MIT" ]
null
null
null
/** * This file contains the unit tests for the ChipPrimitive class */ #include "software/ai/primitive/chip_primitive.h" #include <gtest/gtest.h> #include <string.h> TEST(ChipPrimTest, primitive_name_test) { ChipPrimitive chip_prim = ChipPrimitive(0, Point(), Angle(), 0.0); EXPECT_EQ("Chip Primitive", chip_prim.getPrimitiveName()); } TEST(ChipPrimTest, get_robot_id_test) { unsigned int robot_id = 2U; ChipPrimitive chip_prim = ChipPrimitive(robot_id, Point(), Angle(), 0.0); EXPECT_EQ(robot_id, chip_prim.getRobotId()); } TEST(ChipPrimTest, get_chip_origin_test) { const Point chip_origin = Point(3, 5); ChipPrimitive chip_prim = ChipPrimitive(0, chip_origin, Angle(), 0.0); EXPECT_EQ(chip_prim.getChipOrigin(), chip_origin); } TEST(ChipPrimTest, get_chip_direction_test) { const Angle chip_direction = Angle::ofRadians(1.35); ChipPrimitive chip_prim = ChipPrimitive(0, Point(), chip_direction, 0.0); EXPECT_EQ(chip_prim.getChipDirection(), chip_direction); } TEST(ChipPrimTest, get_chip_distance_test) { const double chip_distance_meters = 1.23; ChipPrimitive chip_prim = ChipPrimitive(0, Point(), Angle(), chip_distance_meters); EXPECT_DOUBLE_EQ(chip_prim.getChipDistance(), chip_distance_meters); } TEST(ChipPrimitiveTest, test_equality_operator_primitives_equal) { ChipPrimitive chip_prim = ChipPrimitive(0, Point(), Angle(), 0.0); ChipPrimitive chip_prim_other = ChipPrimitive(0, Point(), Angle(), 0.0); EXPECT_EQ(chip_prim, chip_prim_other); } TEST(ChipPrimitiveTest, test_inequality_operator_with_mismatched_robot_ids) { ChipPrimitive chip_prim = ChipPrimitive(1, Point(), Angle(), 0.0); ChipPrimitive chip_prim_other = ChipPrimitive(4, Point(), Angle(), 0.0); EXPECT_NE(chip_prim, chip_prim_other); } TEST(ChipPrimitiveTest, test_inequality_operator_with_mismatched_chip_origins) { ChipPrimitive chip_prim = ChipPrimitive(0, Point(), Angle(), 0.0); ChipPrimitive chip_prim_other = ChipPrimitive(0, Point(1, -5), Angle(), 0.0); EXPECT_NE(chip_prim, chip_prim_other); } TEST(ChipPrimitiveTest, test_inequality_operator_with_mismatched_chip_directions) { ChipPrimitive chip_prim = ChipPrimitive(0, Point(), Angle::quarter(), 0.0); ChipPrimitive chip_prim_other = ChipPrimitive(0, Point(), Angle::half(), 0.0); EXPECT_NE(chip_prim, chip_prim_other); } TEST(ChipPrimitiveTest, test_inequality_operator_with_mismatched_chip_distance) { ChipPrimitive chip_prim = ChipPrimitive(0, Point(), Angle(), 1.0); ChipPrimitive chip_prim_other = ChipPrimitive(0, Point(), Angle(), 3.14); EXPECT_NE(chip_prim, chip_prim_other); }
29.315217
87
0.737486
scveloso
ba9295ce2e0d37f48f486fd07175b7e7e912fe00
7,716
cpp
C++
src/io/bin.cpp
arnocandel/LightGBM
19e085c9925ac039cf2ce17649013b1ef69385ee
[ "MIT" ]
1
2016-12-27T07:50:44.000Z
2016-12-27T07:50:44.000Z
src/io/bin.cpp
arnocandel/LightGBM
19e085c9925ac039cf2ce17649013b1ef69385ee
[ "MIT" ]
null
null
null
src/io/bin.cpp
arnocandel/LightGBM
19e085c9925ac039cf2ce17649013b1ef69385ee
[ "MIT" ]
1
2020-02-12T16:47:06.000Z
2020-02-12T16:47:06.000Z
#include <LightGBM/utils/common.h> #include <LightGBM/bin.h> #include "dense_bin.hpp" #include "sparse_bin.hpp" #include "ordered_sparse_bin.hpp" #include <cmath> #include <cstring> #include <cstdint> #include <limits> #include <vector> #include <algorithm> namespace LightGBM { BinMapper::BinMapper() { } // deep copy function for BinMapper BinMapper::BinMapper(const BinMapper& other) { num_bin_ = other.num_bin_; is_trival_ = other.is_trival_; sparse_rate_ = other.sparse_rate_; bin_upper_bound_ = std::vector<double>(num_bin_); for (int i = 0; i < num_bin_; ++i) { bin_upper_bound_[i] = other.bin_upper_bound_[i]; } } BinMapper::BinMapper(const void* memory) { CopyFrom(reinterpret_cast<const char*>(memory)); } BinMapper::~BinMapper() { } void BinMapper::FindBin(std::vector<double>* values, size_t total_sample_cnt, int max_bin) { std::vector<double>& ref_values = (*values); size_t sample_size = total_sample_cnt; int zero_cnt = static_cast<int>(total_sample_cnt - ref_values.size()); // find distinct_values first std::vector<double> distinct_values; std::vector<int> counts; std::sort(ref_values.begin(), ref_values.end()); // push zero in the front if (ref_values.size() == 0 || (ref_values[0] > 0.0f && zero_cnt > 0)) { distinct_values.push_back(0); counts.push_back(zero_cnt); } if (ref_values.size() > 0) { distinct_values.push_back(ref_values[0]); counts.push_back(1); } for (size_t i = 1; i < ref_values.size(); ++i) { if (ref_values[i] != ref_values[i - 1]) { if (ref_values[i - 1] == 0.0f) { counts.back() += zero_cnt; } else if (ref_values[i - 1] < 0.0f && ref_values[i] > 0.0f) { distinct_values.push_back(0); counts.push_back(zero_cnt); } distinct_values.push_back(ref_values[i]); counts.push_back(1); } else { ++counts.back(); } } // push zero in the back if (ref_values.size() > 0 && ref_values.back() < 0.0f && zero_cnt > 0) { distinct_values.push_back(0); counts.push_back(zero_cnt); } int num_values = static_cast<int>(distinct_values.size()); int cnt_in_bin0 = 0; if (num_values <= max_bin) { std::sort(distinct_values.begin(), distinct_values.end()); // use distinct value is enough num_bin_ = num_values; bin_upper_bound_ = std::vector<double>(num_values); for (int i = 0; i < num_values - 1; ++i) { bin_upper_bound_[i] = (distinct_values[i] + distinct_values[i + 1]) / 2; } cnt_in_bin0 = counts[0]; bin_upper_bound_[num_values - 1] = std::numeric_limits<double>::infinity(); } else { // mean size for one bin double mean_bin_size = sample_size / static_cast<double>(max_bin); int rest_bin_cnt = max_bin; int rest_sample_cnt = static_cast<int>(sample_size); std::vector<bool> is_big_count_value(num_values, false); for (int i = 0; i < num_values; ++i) { if (counts[i] >= mean_bin_size) { is_big_count_value[i] = true; --rest_bin_cnt; rest_sample_cnt -= counts[i]; } } mean_bin_size = rest_sample_cnt / static_cast<double>(rest_bin_cnt); std::vector<double> upper_bounds(max_bin, std::numeric_limits<double>::infinity()); std::vector<double> lower_bounds(max_bin, std::numeric_limits<double>::infinity()); int bin_cnt = 0; lower_bounds[bin_cnt] = distinct_values[0]; int cur_cnt_inbin = 0; for (int i = 0; i < num_values - 1; ++i) { if (!is_big_count_value[i]) { rest_sample_cnt -= counts[i]; } cur_cnt_inbin += counts[i]; // need a new bin if (is_big_count_value[i] || cur_cnt_inbin >= mean_bin_size || (is_big_count_value[i + 1] && cur_cnt_inbin >= std::max(1.0, mean_bin_size * 0.5f))) { upper_bounds[bin_cnt] = distinct_values[i]; if (bin_cnt == 0) { cnt_in_bin0 = cur_cnt_inbin; } ++bin_cnt; lower_bounds[bin_cnt] = distinct_values[i + 1]; if (bin_cnt >= max_bin - 1) { break; } cur_cnt_inbin = 0; if (!is_big_count_value[i]) { --rest_bin_cnt; mean_bin_size = rest_sample_cnt / static_cast<double>(rest_bin_cnt); } } } // ++bin_cnt; // update bin upper bound bin_upper_bound_ = std::vector<double>(bin_cnt); num_bin_ = bin_cnt; for (int i = 0; i < bin_cnt - 1; ++i) { bin_upper_bound_[i] = (upper_bounds[i] + lower_bounds[i + 1]) / 2.0f; } // last bin upper bound bin_upper_bound_[bin_cnt - 1] = std::numeric_limits<double>::infinity(); } // check trival(num_bin_ == 1) feature if (num_bin_ <= 1) { is_trival_ = true; } else { is_trival_ = false; } // calculate sparse rate sparse_rate_ = static_cast<double>(cnt_in_bin0) / static_cast<double>(sample_size); } int BinMapper::SizeForSpecificBin(int bin) { int size = 0; size += sizeof(int); size += sizeof(bool); size += sizeof(double); size += bin * sizeof(double); return size; } void BinMapper::CopyTo(char * buffer) { std::memcpy(buffer, &num_bin_, sizeof(num_bin_)); buffer += sizeof(num_bin_); std::memcpy(buffer, &is_trival_, sizeof(is_trival_)); buffer += sizeof(is_trival_); std::memcpy(buffer, &sparse_rate_, sizeof(sparse_rate_)); buffer += sizeof(sparse_rate_); std::memcpy(buffer, bin_upper_bound_.data(), num_bin_ * sizeof(double)); } void BinMapper::CopyFrom(const char * buffer) { std::memcpy(&num_bin_, buffer, sizeof(num_bin_)); buffer += sizeof(num_bin_); std::memcpy(&is_trival_, buffer, sizeof(is_trival_)); buffer += sizeof(is_trival_); std::memcpy(&sparse_rate_, buffer, sizeof(sparse_rate_)); buffer += sizeof(sparse_rate_); bin_upper_bound_ = std::vector<double>(num_bin_); std::memcpy(bin_upper_bound_.data(), buffer, num_bin_ * sizeof(double)); } void BinMapper::SaveBinaryToFile(FILE* file) const { fwrite(&num_bin_, sizeof(num_bin_), 1, file); fwrite(&is_trival_, sizeof(is_trival_), 1, file); fwrite(&sparse_rate_, sizeof(sparse_rate_), 1, file); fwrite(bin_upper_bound_.data(), sizeof(double), num_bin_, file); } size_t BinMapper::SizesInByte() const { return sizeof(num_bin_) + sizeof(is_trival_) + sizeof(sparse_rate_) + sizeof(double) * num_bin_; } template class DenseBin<uint8_t>; template class DenseBin<uint16_t>; template class DenseBin<uint32_t>; template class SparseBin<uint8_t>; template class SparseBin<uint16_t>; template class SparseBin<uint32_t>; template class OrderedSparseBin<uint8_t>; template class OrderedSparseBin<uint16_t>; template class OrderedSparseBin<uint32_t>; Bin* Bin::CreateBin(data_size_t num_data, int num_bin, double sparse_rate, bool is_enable_sparse, bool* is_sparse, int default_bin) { // sparse threshold const double kSparseThreshold = 0.8f; if (sparse_rate >= kSparseThreshold && is_enable_sparse) { *is_sparse = true; return CreateSparseBin(num_data, num_bin, default_bin); } else { *is_sparse = false; return CreateDenseBin(num_data, num_bin, default_bin); } } Bin* Bin::CreateDenseBin(data_size_t num_data, int num_bin, int default_bin) { if (num_bin <= 256) { return new DenseBin<uint8_t>(num_data, default_bin); } else if (num_bin <= 65536) { return new DenseBin<uint16_t>(num_data, default_bin); } else { return new DenseBin<uint32_t>(num_data, default_bin); } } Bin* Bin::CreateSparseBin(data_size_t num_data, int num_bin, int default_bin) { if (num_bin <= 256) { return new SparseBin<uint8_t>(num_data, default_bin); } else if (num_bin <= 65536) { return new SparseBin<uint16_t>(num_data, default_bin); } else { return new SparseBin<uint32_t>(num_data, default_bin); } } } // namespace LightGBM
31.365854
133
0.670555
arnocandel
ba949495d5bb239bd15d802a48dc9df345793881
2,866
cc
C++
crawl/tests/httpget.cc
chanchann/WfCrawl
9c1d4f91a107e90099eaf62bdc8da1091b9dd793
[ "MIT" ]
null
null
null
crawl/tests/httpget.cc
chanchann/WfCrawl
9c1d4f91a107e90099eaf62bdc8da1091b9dd793
[ "MIT" ]
null
null
null
crawl/tests/httpget.cc
chanchann/WfCrawl
9c1d4f91a107e90099eaf62bdc8da1091b9dd793
[ "MIT" ]
null
null
null
#include <netdb.h> #include <signal.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <string> #include "workflow/HttpMessage.h" #include "workflow/HttpUtil.h" #include "workflow/WFTaskFactory.h" #include "workflow/WFFacilities.h" #define REDIRECT_MAX 5 #define RETRY_MAX 2 void wget_callback(WFHttpTask *task) { protocol::HttpRequest *req = task->get_req(); protocol::HttpResponse *resp = task->get_resp(); int state = task->get_state(); int error = task->get_error(); switch (state) { case WFT_STATE_SYS_ERROR: fprintf(stderr, "system error: %s\n", strerror(error)); break; case WFT_STATE_DNS_ERROR: fprintf(stderr, "DNS error: %s\n", gai_strerror(error)); break; case WFT_STATE_SSL_ERROR: fprintf(stderr, "SSL error: %d\n", error); break; case WFT_STATE_TASK_ERROR: fprintf(stderr, "Task error: %d\n", error); break; case WFT_STATE_SUCCESS: break; } if (state != WFT_STATE_SUCCESS) { fprintf(stderr, "Failed. Press Ctrl-C to exit.\n"); return; } std::string name; std::string value; /* Print request. */ fprintf(stderr, "%s %s %s\r\n", req->get_method(), req->get_http_version(), req->get_request_uri()); protocol::HttpHeaderCursor req_cursor(req); while (req_cursor.next(name, value)) fprintf(stderr, "%s: %s\r\n", name.c_str(), value.c_str()); fprintf(stderr, "\r\n"); /* Print response header. */ fprintf(stderr, "%s %s %s\r\n", resp->get_http_version(), resp->get_status_code(), resp->get_reason_phrase()); protocol::HttpHeaderCursor resp_cursor(resp); while (resp_cursor.next(name, value)) fprintf(stderr, "%s: %s\r\n", name.c_str(), value.c_str()); fprintf(stderr, "\r\n"); /* Print response body. */ const void *body; size_t body_len; resp->get_parsed_body(&body, &body_len); fwrite(body, 1, body_len, stdout); fflush(stdout); fprintf(stderr, "\nSuccess. Press Ctrl-C to exit.\n"); } static WFFacilities::WaitGroup wait_group(1); void sig_handler(int signo) { wait_group.done(); } int main(int argc, char *argv[]) { WFHttpTask *task; std::string url = "www.baidu.com"; signal(SIGINT, sig_handler); if (strncasecmp(url.c_str(), "http://", 7) != 0 && strncasecmp(url.c_str(), "https://", 8) != 0) { url = "http://" + url; } task = WFTaskFactory::create_http_task(url, REDIRECT_MAX, RETRY_MAX, wget_callback); protocol::HttpRequest *req = task->get_req(); req->add_header_pair("Accept", "*/*"); req->add_header_pair("User-Agent", "Wget/1.14 (linux-gnu)"); req->add_header_pair("Connection", "close"); task->start(); wait_group.wait(); return 0; }
25.362832
68
0.613747
chanchann
baa465d8c5d414d461248dac6219c099a9f70dd8
305
hpp
C++
Chap_7/7.5/Point.hpp
DrC0okie/Exercices
40bb8040ff3bda218850fa348ceb9a7079eaaef0
[ "MIT" ]
1
2022-02-21T18:54:28.000Z
2022-02-21T18:54:28.000Z
Chap_7/7.5/Point.hpp
DrC0okie/HEIG_PRG1_Exercices
40bb8040ff3bda218850fa348ceb9a7079eaaef0
[ "MIT" ]
null
null
null
Chap_7/7.5/Point.hpp
DrC0okie/HEIG_PRG1_Exercices
40bb8040ff3bda218850fa348ceb9a7079eaaef0
[ "MIT" ]
null
null
null
#ifndef POINT_HPP #define POINT_HPP class Point { private: float x, y; public: Point(float x, float y); void deplacer(float translation_x, float translation_y); float abscisse() const; float ordonnee() const; Point operator+(const Point &droite) const; }; #endif
17.941176
61
0.655738
DrC0okie
baa488e25854c5926c5ce5ee5aa12e42a423db5c
6,226
hpp
C++
include/Zenject/KeyedFactory_6.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/Zenject/KeyedFactory_6.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/Zenject/KeyedFactory_6.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: Zenject.KeyedFactoryBase`2 #include "Zenject/KeyedFactoryBase_2.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" #include "beatsaber-hook/shared/utils/typedefs-array.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System::Collections::Generic namespace System::Collections::Generic { // Forward declaring type: IEnumerable`1<T> template<typename T> class IEnumerable_1; } // Forward declaring namespace: System namespace System { // Forward declaring type: Type class Type; } // Forward declaring namespace: Zenject namespace Zenject { // Forward declaring type: InjectTypeInfo class InjectTypeInfo; } // Completed forward declares // Type namespace: Zenject namespace Zenject { // Forward declaring type: KeyedFactory`6<TBase, TKey, TParam1, TParam2, TParam3, TParam4> template<typename TBase, typename TKey, typename TParam1, typename TParam2, typename TParam3, typename TParam4> class KeyedFactory_6; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE_GENERIC_CLASS(::Zenject::KeyedFactory_6, "Zenject", "KeyedFactory`6"); // Type namespace: Zenject namespace Zenject { // WARNING Size may be invalid! // Autogenerated type: Zenject.KeyedFactory`6 // [TokenAttribute] Offset: FFFFFFFF template<typename TBase, typename TKey, typename TParam1, typename TParam2, typename TParam3, typename TParam4> class KeyedFactory_6 : public ::Zenject::KeyedFactoryBase_2<TBase, TKey> { public: // public TBase Create(TKey key, TParam1 param1, TParam2 param2, TParam3 param3, TParam4 param4) // Offset: 0xFFFFFFFFFFFFFFFF TBase Create(TKey key, TParam1 param1, TParam2 param2, TParam3 param3, TParam4 param4) { static auto ___internal__logger = ::Logger::get().WithContext("::Zenject::KeyedFactory_6::Create"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Create", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(key), ::il2cpp_utils::ExtractType(param1), ::il2cpp_utils::ExtractType(param2), ::il2cpp_utils::ExtractType(param3), ::il2cpp_utils::ExtractType(param4)}))); return ::il2cpp_utils::RunMethodRethrow<TBase, false>(this, ___internal__method, key, param1, param2, param3, param4); } // static private System.Object __zenCreate(System.Object[] P_0) // Offset: 0xFFFFFFFFFFFFFFFF static ::Il2CppObject* __zenCreate(::ArrayW<::Il2CppObject*> P_0) { static auto ___internal__logger = ::Logger::get().WithContext("::Zenject::KeyedFactory_6::__zenCreate"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<KeyedFactory_6<TBase, TKey, TParam1, TParam2, TParam3, TParam4>*>::get(), "__zenCreate", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(P_0)}))); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, P_0); } // protected override System.Collections.Generic.IEnumerable`1<System.Type> get_ProvidedTypes() // Offset: 0xFFFFFFFFFFFFFFFF // Implemented from: Zenject.KeyedFactoryBase`2 // Base method: System.Collections.Generic.IEnumerable`1<System.Type> KeyedFactoryBase_2::get_ProvidedTypes() ::System::Collections::Generic::IEnumerable_1<::System::Type*>* get_ProvidedTypes() { static auto ___internal__logger = ::Logger::get().WithContext("::Zenject::KeyedFactory_6::get_ProvidedTypes"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_ProvidedTypes", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodRethrow<::System::Collections::Generic::IEnumerable_1<::System::Type*>*, false>(this, ___internal__method); } // public System.Void .ctor() // Offset: 0xFFFFFFFFFFFFFFFF // Implemented from: Zenject.KeyedFactoryBase`2 // Base method: System.Void KeyedFactoryBase_2::.ctor() // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static KeyedFactory_6<TBase, TKey, TParam1, TParam2, TParam3, TParam4>* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::Zenject::KeyedFactory_6::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<KeyedFactory_6<TBase, TKey, TParam1, TParam2, TParam3, TParam4>*, creationType>())); } // static private Zenject.InjectTypeInfo __zenCreateInjectTypeInfo() // Offset: 0xFFFFFFFFFFFFFFFF // Implemented from: Zenject.KeyedFactoryBase`2 // Base method: Zenject.InjectTypeInfo KeyedFactoryBase_2::__zenCreateInjectTypeInfo() static ::Zenject::InjectTypeInfo* __zenCreateInjectTypeInfo() { static auto ___internal__logger = ::Logger::get().WithContext("::Zenject::KeyedFactory_6::__zenCreateInjectTypeInfo"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<KeyedFactory_6<TBase, TKey, TParam1, TParam2, TParam3, TParam4>*>::get(), "__zenCreateInjectTypeInfo", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodRethrow<::Zenject::InjectTypeInfo*, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method); } }; // Zenject.KeyedFactory`6 // Could not write size check! Type: Zenject.KeyedFactory`6 is generic, or has no fields that are valid for size checks! } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
64.854167
339
0.732734
RedBrumbler
baa60292e3dfa79d325d6c40162c3f5200f70fe1
5,627
cpp
C++
unittests/clangd/TweakTests.cpp
Szelethus/clang-tools-extra
4bff9e7bc96ac495d7b6b2e8cc6c6f629e824022
[ "Apache-2.0" ]
null
null
null
unittests/clangd/TweakTests.cpp
Szelethus/clang-tools-extra
4bff9e7bc96ac495d7b6b2e8cc6c6f629e824022
[ "Apache-2.0" ]
2
2019-01-24T00:38:27.000Z
2019-02-28T00:23:56.000Z
unittests/clangd/TweakTests.cpp
Szelethus/clang-tools-extra
4bff9e7bc96ac495d7b6b2e8cc6c6f629e824022
[ "Apache-2.0" ]
null
null
null
//===-- TweakTests.cpp ------------------------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "Annotations.h" #include "SourceCode.h" #include "TestTU.h" #include "refactor/Tweak.h" #include "clang/AST/Expr.h" #include "clang/Rewrite/Core/Rewriter.h" #include "clang/Tooling/Core/Replacement.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/Error.h" #include "llvm/Testing/Support/Error.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include <cassert> using llvm::Failed; using llvm::HasValue; using llvm::Succeeded; namespace clang { namespace clangd { namespace { std::string markRange(llvm::StringRef Code, Range R) { size_t Begin = llvm::cantFail(positionToOffset(Code, R.start)); size_t End = llvm::cantFail(positionToOffset(Code, R.end)); assert(Begin <= End); if (Begin == End) // Mark a single point. return (Code.substr(0, Begin) + "^" + Code.substr(Begin)).str(); // Mark a range. return (Code.substr(0, Begin) + "[[" + Code.substr(Begin, End - Begin) + "]]" + Code.substr(End)) .str(); } void checkAvailable(StringRef ID, llvm::StringRef Input, bool Available) { Annotations Code(Input); ASSERT_TRUE(0 < Code.points().size() || 0 < Code.ranges().size()) << "no points of interest specified"; TestTU TU; TU.Filename = "foo.cpp"; TU.Code = Code.code(); ParsedAST AST = TU.build(); auto CheckOver = [&](Range Selection) { unsigned Begin = cantFail(positionToOffset(Code.code(), Selection.start)); unsigned End = cantFail(positionToOffset(Code.code(), Selection.end)); auto T = prepareTweak(ID, Tweak::Selection(AST, Begin, End)); if (Available) EXPECT_THAT_EXPECTED(T, Succeeded()) << "code is " << markRange(Code.code(), Selection); else EXPECT_THAT_EXPECTED(T, Failed()) << "code is " << markRange(Code.code(), Selection); }; for (auto P : Code.points()) CheckOver(Range{P, P}); for (auto R : Code.ranges()) CheckOver(R); } /// Checks action is available at every point and range marked in \p Input. void checkAvailable(StringRef ID, llvm::StringRef Input) { return checkAvailable(ID, Input, /*Available=*/true); } /// Same as checkAvailable, but checks the action is not available. void checkNotAvailable(StringRef ID, llvm::StringRef Input) { return checkAvailable(ID, Input, /*Available=*/false); } llvm::Expected<std::string> apply(StringRef ID, llvm::StringRef Input) { Annotations Code(Input); Range SelectionRng; if (Code.points().size() != 0) { assert(Code.ranges().size() == 0 && "both a cursor point and a selection range were specified"); SelectionRng = Range{Code.point(), Code.point()}; } else { SelectionRng = Code.range(); } TestTU TU; TU.Filename = "foo.cpp"; TU.Code = Code.code(); ParsedAST AST = TU.build(); unsigned Begin = cantFail(positionToOffset(Code.code(), SelectionRng.start)); unsigned End = cantFail(positionToOffset(Code.code(), SelectionRng.end)); Tweak::Selection S(AST, Begin, End); auto T = prepareTweak(ID, S); if (!T) return T.takeError(); auto Replacements = (*T)->apply(S); if (!Replacements) return Replacements.takeError(); return applyAllReplacements(Code.code(), *Replacements); } void checkTransform(llvm::StringRef ID, llvm::StringRef Input, llvm::StringRef Output) { EXPECT_THAT_EXPECTED(apply(ID, Input), HasValue(Output)) << "action id is" << ID; } TEST(TweakTest, SwapIfBranches) { llvm::StringLiteral ID = "SwapIfBranches"; checkAvailable(ID, R"cpp( void test() { ^i^f^^(^t^r^u^e^) { return 100; } ^e^l^s^e^ { continue; } } )cpp"); checkNotAvailable(ID, R"cpp( void test() { if (true) {^return ^100;^ } else { ^continue^;^ } } )cpp"); llvm::StringLiteral Input = R"cpp( void test() { ^if (true) { return 100; } else { continue; } } )cpp"; llvm::StringLiteral Output = R"cpp( void test() { if (true) { continue; } else { return 100; } } )cpp"; checkTransform(ID, Input, Output); Input = R"cpp( void test() { ^if () { return 100; } else { continue; } } )cpp"; Output = R"cpp( void test() { if () { continue; } else { return 100; } } )cpp"; checkTransform(ID, Input, Output); // Available in subexpressions of the condition. checkAvailable(ID, R"cpp( void test() { if(2 + [[2]] + 2) { return 2 + 2 + 2; } else { continue; } } )cpp"); // But not as part of the branches. checkNotAvailable(ID, R"cpp( void test() { if(2 + 2 + 2) { return 2 + [[2]] + 2; } else { continue; } } )cpp"); // Range covers the "else" token, so available. checkAvailable(ID, R"cpp( void test() { if(2 + 2 + 2) { return 2 + [[2 + 2; } else { continue;]] } } )cpp"); // Not available in compound statements in condition. checkNotAvailable(ID, R"cpp( void test() { if([]{return [[true]];}()) { return 2 + 2 + 2; } else { continue; } } )cpp"); // Not available if both sides aren't braced. checkNotAvailable(ID, R"cpp( void test() { ^if (1) return; else { return; } } )cpp"); // Only one if statement is supported! checkNotAvailable(ID, R"cpp( [[if(1){}else{}if(2){}else{}]] )cpp"); } } // namespace } // namespace clangd } // namespace clang
29.460733
80
0.612582
Szelethus
bab1e315ea6dec0a9de3860a1c1d647c71ebee39
2,453
hpp
C++
src/boost/system/detail/system_category_impl.hpp
107-systems/107-Arduino-BoostUnits
fc3677ae79c1e75c99b3aa7813eb6ec83124b944
[ "MIT" ]
null
null
null
src/boost/system/detail/system_category_impl.hpp
107-systems/107-Arduino-BoostUnits
fc3677ae79c1e75c99b3aa7813eb6ec83124b944
[ "MIT" ]
1
2021-08-30T18:02:49.000Z
2021-08-30T18:02:49.000Z
src/boost/system/detail/system_category_impl.hpp
107-systems/107-Arduino-BoostUnits
fc3677ae79c1e75c99b3aa7813eb6ec83124b944
[ "MIT" ]
null
null
null
#ifndef BOOST_SYSTEM_DETAIL_SYSTEM_CATEGORY_IMPL_HPP_INCLUDED #define BOOST_SYSTEM_DETAIL_SYSTEM_CATEGORY_IMPL_HPP_INCLUDED // Copyright Beman Dawes 2006, 2007 // Copyright Christoper Kohlhoff 2007 // Copyright Peter Dimov 2017, 2018, 2020 // // 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) // // See library home page at http://www.boost.org/libs/system #include "boost/system/detail/system_category.hpp" #include "boost/system/detail/error_condition.hpp" #include "boost/system/api_config.hpp" #if !defined(BOOST_POSIX_API) && !defined(BOOST_WINDOWS_API) # error BOOST_POSIX_API or BOOST_WINDOWS_API must be defined #endif // system_error_category implementation #if defined(BOOST_WINDOWS_API) #include "boost/system/detail/system_category_message_win32.hpp" #include "boost/system/detail/system_category_condition_win32.hpp" inline boost::system::error_condition boost::system::detail::system_error_category::default_error_condition( int ev ) const BOOST_NOEXCEPT { int e2 = system_category_condition_win32( ev ); if( e2 == -1 ) { return error_condition( ev, *this ); } else { return error_condition( boost::system::detail::generic_value_tag( e2 ) ); } } inline std::string boost::system::detail::system_error_category::message( int ev ) const { return system_category_message_win32( ev ); } inline char const * boost::system::detail::system_error_category::message( int ev, char * buffer, std::size_t len ) const BOOST_NOEXCEPT { return system_category_message_win32( ev, buffer, len ); } #else // #if defined(BOOST_WINDOWS_API) #include "boost/system/detail/generic_category_message.hpp" inline boost::system::error_condition boost::system::detail::system_error_category::default_error_condition( int ev ) const BOOST_NOEXCEPT { return error_condition( boost::system::detail::generic_value_tag( ev ) ); } inline std::string boost::system::detail::system_error_category::message( int ev ) const { return generic_error_category_message( ev ); } inline char const * boost::system::detail::system_error_category::message( int ev, char * buffer, std::size_t len ) const BOOST_NOEXCEPT { return generic_error_category_message( ev, buffer, len ); } #endif // #if defined(BOOST_WINDOWS_API) #endif // #ifndef BOOST_SYSTEM_DETAIL_SYSTEM_CATEGORY_IMPL_HPP_INCLUDED
33.148649
138
0.767631
107-systems
bab474e2935e1e8e5e2d0a216e9a728bc260df59
1,910
cpp
C++
6. Linked List/8_Merge_sort_over_ll.cpp
manishhedau/Data-Structure-Algorithm
d45de87aa44d3af18d58fd59491993cf98dbe6fc
[ "MIT" ]
3
2021-02-01T07:56:21.000Z
2021-02-01T11:56:50.000Z
6. Linked List/8_Merge_sort_over_ll.cpp
manishhedau/Data-Structure-Algorithm
d45de87aa44d3af18d58fd59491993cf98dbe6fc
[ "MIT" ]
null
null
null
6. Linked List/8_Merge_sort_over_ll.cpp
manishhedau/Data-Structure-Algorithm
d45de87aa44d3af18d58fd59491993cf98dbe6fc
[ "MIT" ]
null
null
null
// Code By - Manish Hedau #include<bits/stdc++.h> using namespace std; class node { public: int data; node *next; // constructor node(int d) { data = d; next = NULL; } }; void insertHead(node *&head, int data) { // check if ll is empty if (head == NULL) { head = new node(data); return; } node *new_bucket = new node(data); new_bucket->next = head; head = new_bucket; } void printNode(node *head) { while (head != NULL) { cout << head->data << " -> "; head = head->next; } cout << endl; } void take_input(node *&head) { int data; cin >> data; while (data != -1) { insertHead(head, data); cin >> data; } } node *midPoint(node *head) { node *slow = head; node *fast = head->next; while (fast != NULL and fast->next != NULL) { fast = fast->next->next; slow = slow->next; } return slow; } node *merge(node *head1, node *head2) { // base case if (head1 == NULL) { return head2; } if (head2 == NULL) { return head1; } node *temp = NULL; if (head1->data < head2->data) { temp = head1; temp->next = merge(head1->next, head2); } else { temp = head2; temp->next = merge(head1, head2->next); } return temp; } // Time complexity - O(N logN) // Space complexity - O(N) node *merge_sort(node *head) { // base case if (head == NULL or head->next == NULL) { return head; } // Recursive case // 1. Break node *mid = midPoint(head); node * first = head; node * second = mid->next; mid->next = NULL; // 2. Recursive sort the linked list first = merge_sort(first); second = merge_sort(second); return merge(first, second); } int main() { node *head = NULL; take_input(head); printNode(head); cout << "Sorting the Linked List : " << endl; head = merge_sort(head); printNode(head); return 0; } /* Input :- -------- 5 6 8 2 1 -1 Output :- --------- 1 -> 2 -> 8 -> 6 -> 5 -> Sorting the Linked List : 1 -> 2 -> 5 -> 6 -> 8 -> */
15.785124
46
0.587958
manishhedau
3bf8c29c924c4808f7388ca5748905a761d121d3
22,324
cpp
C++
Fuji/Source/MFPrimitive.cpp
TurkeyMan/fuji
afd6a26c710ce23965b088ad158fe916d6a1a091
[ "BSD-2-Clause" ]
35
2015-01-19T22:07:48.000Z
2022-02-21T22:17:53.000Z
Fuji/Source/MFPrimitive.cpp
TurkeyMan/fuji
afd6a26c710ce23965b088ad158fe916d6a1a091
[ "BSD-2-Clause" ]
1
2022-02-23T09:34:15.000Z
2022-02-23T09:34:15.000Z
Fuji/Source/MFPrimitive.cpp
TurkeyMan/fuji
afd6a26c710ce23965b088ad158fe916d6a1a091
[ "BSD-2-Clause" ]
4
2015-05-11T03:31:35.000Z
2018-09-27T04:55:57.000Z
/**** Defines ****/ /**** Includes ****/ #include "Fuji_Internal.h" #include "MFDisplay.h" #include "MFView.h" #include "MFPrimitive.h" /**** Globals ****/ /**** Functions ****/ MF_API void MFPrimitive_BlitRect(int x, int y, const MFRect &uvs) { MFPrimitive_Blit(x, y, (int)uvs.x, (int)uvs.y, (int)uvs.width, (int)uvs.height); } MF_API void MFPrimitive_StretchBlitRect(int x, int y, int w, int h, const MFRect &uvs) { MFPrimitive_StretchBlit(x, y, w, h, (int)uvs.x, (int)uvs.y, (int)uvs.width, (int)uvs.height); } MF_API void MFPrimitive_DrawQuad(float x, float y, float w, float h, const MFVector& colour, float su, float sv, float du, float dv, const MFMatrix &mat) { MFCALLSTACK; // D3DDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_FALSE); // D3DDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE); MFPrimitive(PT_TriStrip | PT_Prelit); MFSetMatrix(mat); MFBegin(4); MFSetColourV(colour); MFSetTexCoord1(su, sv); MFSetPosition(x, y, 0); MFSetTexCoord1(du, sv); MFSetPosition(x+w, y, 0); MFSetTexCoord1(su, dv); MFSetPosition(x, y+h, 0); MFSetTexCoord1(du, dv); MFSetPosition(x+w, y+h, 0); MFEnd(); // D3DDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE); // D3DDevice->SetRenderState(D3DRS_ZWRITEENABLE, TRUE); } MF_API void MFPrimitive_DrawQuadV(const MFVector &min, const MFVector &max, const MFVector& colour, float su, float sv, float du, float dv, const MFMatrix &mat) { MFCALLSTACK; // D3DDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_FALSE); // D3DDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE); MFPrimitive(PT_TriStrip | PT_Prelit); MFSetMatrix(mat); MFBegin(4); MFSetColourV(colour); MFSetTexCoord1(su, sv); MFSetPosition(min.x, min.y, min.z); MFSetTexCoord1(du, sv); MFSetPosition(max.x, min.y, min.z); MFSetTexCoord1(su, dv); MFSetPosition(min.x, max.y, min.z); MFSetTexCoord1(du, dv); MFSetPosition(max.x, max.y, min.z); MFEnd(); // D3DDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE); // D3DDevice->SetRenderState(D3DRS_ZWRITEENABLE, TRUE); } MF_API void MFPrimitive_DrawUntexturedQuad(float x, float y, float w, float h, const MFVector& colour, const MFMatrix &mat) { MFCALLSTACK; // D3DDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_FALSE); // D3DDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE); MFPrimitive(PT_TriStrip | PT_Prelit | PT_Untextured); MFSetMatrix(mat); MFBegin(4); MFSetColourV(colour); MFSetPosition(x, y, 0); MFSetPosition(x+w, y, 0); MFSetPosition(x, y+h, 0); MFSetPosition(x+w, y+h, 0); MFEnd(); // D3DDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE); // D3DDevice->SetRenderState(D3DRS_ZWRITEENABLE, TRUE); } MF_API void MFPrimitive_DrawUntexturedQuadV(const MFVector &min, const MFVector &max, const MFVector& colour, const MFMatrix &mat) { MFCALLSTACK; // D3DDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_FALSE); // D3DDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE); MFPrimitive(PT_TriStrip | PT_Prelit | PT_Untextured); MFSetMatrix(mat); MFBegin(4); MFSetColourV(colour); MFSetPosition(min.x, min.y, min.z); MFSetPosition(max.x, min.y, min.z); MFSetPosition(min.x, max.y, min.z); MFSetPosition(max.x, max.y, min.z); MFEnd(); // D3DDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE); // D3DDevice->SetRenderState(D3DRS_ZWRITEENABLE, TRUE); } // draw a box from a min and a max MF_API void MFPrimitive_DrawBox(const MFVector &boxMin, const MFVector &boxMax, const MFVector& colour, const MFMatrix &mat, bool wireframe) { MFCALLSTACK; if(wireframe) { MFPrimitive(PT_LineList|PT_Prelit|PT_Untextured); MFSetMatrix(mat); MFBegin(24); MFSetColourV(colour); MFSetPosition(boxMin.x, boxMin.y, boxMin.z); MFSetPosition(boxMax.x, boxMin.y, boxMin.z); MFSetPosition(boxMin.x, boxMax.y, boxMin.z); MFSetPosition(boxMax.x, boxMax.y, boxMin.z); MFSetPosition(boxMin.x, boxMin.y, boxMax.z); MFSetPosition(boxMax.x, boxMin.y, boxMax.z); MFSetPosition(boxMin.x, boxMax.y, boxMax.z); MFSetPosition(boxMax.x, boxMax.y, boxMax.z); MFSetPosition(boxMin.x, boxMin.y, boxMin.z); MFSetPosition(boxMin.x, boxMax.y, boxMin.z); MFSetPosition(boxMax.x, boxMin.y, boxMin.z); MFSetPosition(boxMax.x, boxMax.y, boxMin.z); MFSetPosition(boxMin.x, boxMin.y, boxMax.z); MFSetPosition(boxMin.x, boxMax.y, boxMax.z); MFSetPosition(boxMax.x, boxMin.y, boxMax.z); MFSetPosition(boxMax.x, boxMax.y, boxMax.z); MFSetPosition(boxMin.x, boxMin.y, boxMin.z); MFSetPosition(boxMin.x, boxMin.y, boxMax.z); MFSetPosition(boxMax.x, boxMin.y, boxMin.z); MFSetPosition(boxMax.x, boxMin.y, boxMax.z); MFSetPosition(boxMin.x, boxMax.y, boxMin.z); MFSetPosition(boxMin.x, boxMax.y, boxMax.z); MFSetPosition(boxMax.x, boxMax.y, boxMin.z); MFSetPosition(boxMax.x, boxMax.y, boxMax.z); MFEnd(); MFVector center = boxMin + ((boxMax-boxMin)*0.5f); // draw the axii's MFBegin(2); MFSetColourV(MFVector::green); MFSetPosition(center.x, center.y + 10.0f, center.z); MFSetPosition(center.x, center.y, center.z); MFEnd(); MFBegin(2); MFSetColourV(MFVector::red); MFSetPosition(center.x, center.y, center.z); MFSetPosition(center.x + 10.0f, center.y, center.z); MFEnd(); MFBegin(2); MFSetColourV(MFVector::blue); MFSetPosition(center.x, center.y, center.z); MFSetPosition(center.x, center.y, center.z + 10.0f); MFEnd(); } else { MFPrimitive(PT_TriStrip|PT_Untextured); MFSetMatrix(mat); MFBegin(34); MFSetColourV(colour); MFSetNormal(0.0f,0.0f,-1.0f); MFSetPosition(boxMin.x, boxMax.y, boxMin.z); // front MFSetPosition(boxMax.x, boxMax.y, boxMin.z); MFSetPosition(boxMin.x, boxMin.y, boxMin.z); MFSetPosition(boxMax.x, boxMin.y, boxMin.z); MFSetPosition(boxMax.x, boxMin.y, boxMin.z); // degenerates MFSetPosition(boxMin.x, boxMin.y, boxMin.z); MFSetNormal(0.0f,-1.0f,0.0f); MFSetPosition(boxMin.x, boxMin.y, boxMin.z); // bottom MFSetPosition(boxMax.x, boxMin.y, boxMin.z); MFSetPosition(boxMin.x, boxMin.y, boxMax.z); MFSetPosition(boxMax.x, boxMin.y, boxMax.z); MFSetPosition(boxMax.x, boxMin.y, boxMax.z); // degenerates MFSetPosition(boxMin.x, boxMin.y, boxMax.z); MFSetNormal(0.0f,0.0f,1.0f); MFSetPosition(boxMin.x, boxMin.y, boxMax.z); // back MFSetPosition(boxMax.x, boxMin.y, boxMax.z); MFSetPosition(boxMin.x, boxMax.y, boxMax.z); MFSetPosition(boxMax.x, boxMax.y, boxMax.z); MFSetPosition(boxMax.x, boxMax.y, boxMax.z); // degenerates MFSetPosition(boxMin.x, boxMax.y, boxMax.z); MFSetNormal(0.0f,1.0f,0.0f); MFSetPosition(boxMin.x, boxMax.y, boxMax.z); // top MFSetPosition(boxMax.x, boxMax.y, boxMax.z); MFSetPosition(boxMin.x, boxMax.y, boxMin.z); MFSetPosition(boxMax.x, boxMax.y, boxMin.z); MFSetPosition(boxMax.x, boxMax.y, boxMin.z); // degenerates MFSetPosition(boxMin.x, boxMax.y, boxMax.z); MFSetNormal(-1.0f,0.0f,0.0f); MFSetPosition(boxMin.x, boxMax.y, boxMax.z); // left MFSetPosition(boxMin.x, boxMax.y, boxMin.z); MFSetPosition(boxMin.x, boxMin.y, boxMax.z); MFSetPosition(boxMin.x, boxMin.y, boxMin.z); MFSetPosition(boxMin.x, boxMin.y, boxMin.z); // degenerates MFSetPosition(boxMax.x, boxMax.y, boxMin.z); MFSetNormal(1.0f,0.0f,0.0f); MFSetPosition(boxMax.x, boxMax.y, boxMin.z); // right MFSetPosition(boxMax.x, boxMax.y, boxMax.z); MFSetPosition(boxMax.x, boxMin.y, boxMin.z); MFSetPosition(boxMax.x, boxMin.y, boxMax.z); MFEnd(); } } // draw's a sphere .. position.w defines position.w MF_API void MFPrimitive_DrawSphere(const MFVector &position, float radius, int segments, int slices, const MFVector& colour, const MFMatrix &mat, bool wireframe) { MFCALLSTACK; MFDebug_Assert(segments >= 3, "DrawSphere requires at least 3 segments!"); MFDebug_Assert(slices >= 1, "DrawSphere requires at least 1 slices!"); int i, j, inc; float around = 0.0f, aroundInc = (MFPI*2.0f)/(float)segments; float yWave=0.0f, yWaveInc = MFPI/((float)slices+1.0f); float siny; MFPrimitive(PT_LineStrip|PT_Prelit|PT_Untextured); MFSetMatrix(mat); MFBegin(segments*(slices+1)+1); MFSetColourV(colour); for(i=0, j=0, inc=1; j<segments;) { siny = MFSin(yWave); MFSetPosition(position.x + (MFSin(around)*radius) * siny, position.y + MFCos(yWave)*radius, position.z + (MFCos(around)*radius) * siny); yWave += yWaveInc; i+=inc; if(i==0 || i==slices+1) { inc = -inc; yWaveInc = -yWaveInc; j++; around += aroundInc; } } siny = MFSin(yWave); MFSetPosition(position.x + (MFSin(around)*radius) * siny, position.y + MFCos(yWave)*radius, position.z + (MFCos(around)*radius) * siny); MFEnd(); yWaveInc = MFAbs(yWaveInc); yWave = yWaveInc; for(i=0; i<slices; i++) { float cosy = MFCos(yWave)*radius; siny = MFSin(yWave); around = 0.0f; MFBegin(segments+1); MFSetColourV(colour); for(j=0; j<segments+1; j++) { MFSetPosition(position.x + (MFSin(around)*radius)*siny, position.y + cosy, position.z + (MFCos(around)*radius)*siny); around += aroundInc; } MFEnd(); yWave += yWaveInc; } // draw the axii's MFBegin(2); MFSetColourV(MFVector::green); MFSetPosition(position.x, position.y + radius * 0.5f, position.z); MFSetPosition(position.x, position.y, position.z); MFEnd(); MFBegin(2); MFSetColourV(MFVector::red); MFSetPosition(position.x, position.y, position.z); MFSetPosition(position.x + radius * 0.5f, position.y, position.z); MFEnd(); MFBegin(2); MFSetColourV(MFVector::blue); MFSetPosition(position.x, position.y, position.z); MFSetPosition(position.x, position.y, position.z + radius * 0.5f); MFEnd(); } // draw's a capsule from a start and end point and a position.w MF_API void MFPrimitive_DrawCapsule(const MFVector &startPoint, const MFVector &endPoint, float radius, int segments, int slices, const MFVector& colour, const MFMatrix &mat, bool wireframe) { MFCALLSTACK; slices += 1 - (slices&0x1); MFDebug_Assert(segments >= 3, "DrawCapsule requires at least 3 segments!"); MFDebug_Assert(slices >= 1, "DrawCapsule requires at least 1 slices!"); MFMatrix m, m2 = mat; MFVector t = endPoint-startPoint; float len = t.Magnitude3(); t *= 1.0f/len; // if capsule has no length .. might as well just draw a sphere .. if(len<0.1f) { MFPrimitive_DrawSphere(startPoint, radius, segments, slices, colour, mat, wireframe); return; } m.SetYAxis3(t); m.SetZAxis3(m.GetYAxis().Cross3(MakeVector(13.67f, 3.72f, 0.0f)).Normalise3()); // cross product with a magic vector m.SetXAxis3(m.GetZAxis().Cross3(m.GetYAxis()).Normalise3()); m.SetTrans3(startPoint); m.ClearW(); m2.Multiply(m, m2); int i, j, inc; float around = 0.0f, aroundInc = (MFPI*2.0f)/(float)segments; float yWave=0.0f, yWaveInc = MFPI/((float)slices+1.0f); float yAdd = len; float siny; MFPrimitive(PT_LineStrip|PT_Prelit|PT_Untextured); MFSetMatrix(m2); MFBegin(segments*(slices+2)+1); MFSetColourV(colour); for(i=0, j=0, inc=1; j<segments;) { siny = MFSin(yWave); MFSetPosition(MFSin(around)*radius * siny, MFCos(yWave)*radius + yAdd, MFCos(around)*radius * siny); if(i == (slices+1)/2) { yAdd -= len * (float)inc; MFSetPosition(MFSin(around)*radius * siny, MFCos(yWave)*radius + yAdd, MFCos(around)*radius * siny); } yWave += yWaveInc; i+=inc; if(i==0 || i==slices+1) { inc = -inc; yWaveInc = -yWaveInc; j++; around += aroundInc; } } siny = MFSin(yWave); MFSetPosition(MFSin(around)*radius * siny, MFCos(yWave)*radius + yAdd, MFCos(around)*radius * siny); MFEnd(); yWaveInc = MFAbs(yWaveInc); yWave = yWaveInc; yAdd = len; for(i=0; i<slices; i++) { float cosy = MFCos(yWave)*radius; siny = MFSin(yWave); around = 0.0f; if(i == (slices+1)/2) { yAdd -= len; } MFBegin(segments+1); MFSetColourV(colour); for(j=0; j<segments+1; j++) { MFSetPosition(MFSin(around)*radius*siny, cosy + yAdd, MFCos(around)*radius*siny); around += aroundInc; } MFEnd(); yWave += yWaveInc; } int centerSegs = (int)(len / ((radius*2)/(float)slices)); yAdd = 0.0f; for(i=0; i<centerSegs; i++) { around = 0.0f; MFBegin(segments+1); MFSetColourV(colour); for(j=0; j<segments+1; j++) { MFSetPosition(MFSin(around)*radius, yAdd, MFCos(around)*radius); around += aroundInc; } MFEnd(); yAdd+=len/(float)centerSegs; } m2=mat; m.SetIdentity(); m.SetTrans3(startPoint); m2.Multiply(m, m2); MFSetMatrix(m2); // draw the axii's MFBegin(2); MFSetColourV(MFVector::green); MFSetPosition(0.0f, radius * 0.5f, 0.0f); MFSetPosition(0.0f, 0.0f, 0.0f); MFEnd(); MFBegin(2); MFSetColourV(MFVector::red); MFSetPosition(0.0f, 0.0f, 0.0f); MFSetPosition(radius * 0.5f, 0.0f, 0.0f); MFEnd(); MFBegin(2); MFSetColourV(MFVector::blue); MFSetPosition(0.0f, 0.0f, 0.0f); MFSetPosition(0.0f, 0.0f, radius * 0.5f); MFEnd(); } // draw's a cylinder from a position position.w and height MF_API void MFPrimitive_DrawCylinder(const MFVector &startPoint, const MFVector &endPoint, float radius, int segments, int slices, const MFVector& colour, const MFMatrix &mat, bool wireframe) { MFCALLSTACK; MFDebug_Assert(segments >= 3, "DrawCylinder requires at least 3 segments!"); MFMatrix m, m2 = mat; MFVector t = endPoint-startPoint; float len = t.Magnitude3(); t *= 1.0f/len; m.SetYAxis3(t); m.SetZAxis3(m.GetYAxis().Cross3(MakeVector(13.67f, 3.72f, 0.0f)).Normalise3()); // cross product with a magic vector m.SetXAxis3(m.GetZAxis().Cross3(m.GetYAxis()).Normalise3()); m.SetTrans3(startPoint); m.ClearW(); m2.Multiply(m, m2); int i, j, inc; float aroundInc = (MFPI*2.0f)/(float)segments; float around = 0.0f; if(wireframe) { around = -aroundInc; MFPrimitive(PT_LineStrip|PT_Prelit|PT_Untextured); MFSetMatrix(m2); MFBegin(segments*3 + 1); MFSetColourV(colour); for(i=0, j=-1, inc=-1; j<segments; i+=inc) { // tests weather number is zero or 3 .. if(!i || i==3) { MFSetPosition(0.0f, (i&2)?len:0.0f, 0.0f); inc = -inc; j++; around += aroundInc; } else { MFSetPosition(MFSin(around)*radius, (i&2)?len:0.0f, MFCos(around)*radius); } } MFEnd(); slices+=2; float yOffset = 0.0f, yInc = len/(float)(slices-1); for(i=0; i<slices; i++) { around = 0.0f; MFBegin(segments+1); MFSetColourV(colour); for(j=0; j<segments+1; j++) { MFSetPosition(MFSin(around)*radius, yOffset, MFCos(around)*radius); around += aroundInc; } MFEnd(); yOffset += yInc; } m2=mat; m.SetIdentity(); m.SetTrans3(startPoint); m2.Multiply(m, m2); MFSetMatrix(m2); // draw the axii's MFBegin(2); MFSetColourV(MFVector::green); MFSetPosition(0.0f, radius * 0.5f, 0.0f); MFSetPosition(0.0f, 0.0f, 0.0f); MFEnd(); MFBegin(2); MFSetColourV(MFVector::red); MFSetPosition(0.0f, 0.0f, 0.0f); MFSetPosition(radius * 0.5f, 0.0f, 0.0f); MFEnd(); MFBegin(2); MFSetColourV(MFVector::blue); MFSetPosition(0.0f, 0.0f, 0.0f); MFSetPosition(0.0f, 0.0f, radius * 0.5f); MFEnd(); } else { MFPrimitive(PT_TriStrip|PT_Prelit|PT_Untextured); MFSetMatrix(m2); // bottom cap MFBegin((segments+1)*2); MFSetColourV(colour); MFSetNormal(0.0f,1.0f,0.0f); MFSetPosition(0.0f, len, 0.0f); for(i=0; i<segments; i++) { MFSetPosition(MFSin(around)*radius, len, MFCos(around)*radius); MFSetPosition(0.0f, len, 0.0f); around += aroundInc; } MFSetPosition(0.0f, len, radius); MFEnd(); // top cap around = MFPI*2; MFBegin((segments+1)*2); MFSetColourV(colour); MFSetNormal(0.0f,-1.0f,0.0f); MFSetPosition(0.0f, 0.0f, 0.0f); for(i=0; i<segments; i++) { MFSetPosition(MFSin(around)*radius, 0.0f, MFCos(around)*radius); MFSetPosition(0.0f, 0.0f, 0.0f); around -= aroundInc; } MFSetPosition(0.0f, 0.0f, radius); MFEnd(); // surface MFPrimitive(PT_TriStrip|PT_Prelit|PT_Untextured); MFSetMatrix(m2); MFBegin((segments+1)*2); MFSetColourV(colour); around = 0.0f; for(i=0; i<segments; i++) { float s = MFSin(around), c=MFCos(around); MFSetNormal(s,0.0f,c); MFSetPosition(s*radius, len, c*radius); MFSetPosition(s*radius, 0.0f, c*radius); around += aroundInc; } MFSetPosition(0.0f, len, radius); MFSetPosition(0.0f, 0.0f, radius); MFEnd(); } } // draw's a plane from a position normal and span MF_API void MFPrimitive_DrawPlane(const MFVector &point, const MFVector &normal, float span, const MFVector& colour, const MFMatrix &mat, bool wireframe) { MFCALLSTACK; int segments = 12; MFMatrix m, m2 = mat; m.SetYAxis3(normal); m.SetZAxis3(m.GetYAxis().Cross3(MakeVector(13.67f, 3.72f, 0.0f)).Normalise3()); // cross product with a magic vector m.SetXAxis3(m.GetZAxis().Cross3(m.GetYAxis()).Normalise3()); m.SetTrans3(point); m.ClearW(); m2.Multiply(m, m2); int i; float aroundInc = (MFPI*2.0f)/(float)segments; float around = -aroundInc; MFPrimitive(PT_LineList|PT_Prelit|PT_Untextured); MFSetMatrix(m2); MFBegin(segments*2+6); MFSetColourV(colour); for(i=0; i<segments; i++) { MFSetPosition(0.0f, 0.0f, 0.0f); MFSetPosition(MFSin(around)*span, 0.0f, MFCos(around)*span); around += aroundInc; } float normalLen = span*0.25f; MFSetColourV(MakeVector(1,1,0,colour.w)); MFSetPosition(0.0f, 0.0f, 0.0f); MFSetPosition(0.0f, normalLen, 0.0f); MFSetPosition(0.0f, normalLen, 0.0f); MFSetPosition(-normalLen*0.15f, normalLen - normalLen*0.25f, 0.0f); MFSetPosition(0.0f, normalLen, 0.0f); MFSetPosition(normalLen*0.15f, normalLen - normalLen*0.25f, 0.0f); MFEnd(); MFPrimitive(PT_LineStrip|PT_Prelit|PT_Untextured); MFSetMatrix(m2); around = 0.0f; MFBegin(segments+1); MFSetColourV(colour); for(int j=0; j<segments+1; j++) { MFSetPosition(MFSin(around)*span, 0.0f, MFCos(around)*span); around += aroundInc; } MFEnd(); } MF_API void MFPrimitive_DrawCone(const MFVector &base, const MFVector &point, float radius, int segments, const MFVector& colour, const MFMatrix &mat, bool wireframe) { MFCALLSTACK; MFDebug_Assert(segments >= 3, "DrawCylinder requires at least 3 segments!"); MFMatrix m, m2 = mat; MFVector t = point-base; float height = t.Magnitude3(); t *= 1.0f/height; m.SetYAxis3(t); m.SetZAxis3(m.GetYAxis().Cross3(MakeVector(13.67f, 3.72f, 0.0f)).Normalise3()); // cross product with a magic vector m.SetXAxis3(m.GetZAxis().Cross3(m.GetYAxis()).Normalise3()); m.SetTrans3(base); m.ClearW(); m2.Multiply(m, m2); int i; float aroundInc = (MFPI*2.0f)/(float)segments; float around = 0.0f; if(wireframe) MFPrimitive(PT_LineList|PT_Prelit|PT_Untextured); else MFPrimitive(PT_TriStrip|PT_Prelit|PT_Untextured); MFSetMatrix(m2); MFBegin(wireframe?segments*4:(segments+1)*2); MFSetColourV(colour); if(!wireframe) { MFSetNormal(0.0f, 1.0f, 0.0f); MFSetPosition(0.0f, height, 0.0f); } for(i=0; i<segments; i++) { float s=MFSin(around), c=MFCos(around); if(wireframe) { if(i) MFSetPosition(s*radius, 0.0f, c*radius); MFSetPosition(0.0f, height, 0.0f); MFSetPosition(s*radius, 0.0f, c*radius); MFSetPosition(s*radius, 0.0f, c*radius); } else { MFSetPosition(s*radius, 0.0f, c*radius); MFSetPosition(0.0f, height, 0.0f); } around += aroundInc; } MFSetPosition(0.0f, 0.0f, radius); MFEnd(); // draw base MFBegin(wireframe?segments*2:(segments+1)*2); MFSetColourV(colour); around = MFPI*2.0f; if(!wireframe) { MFSetPosition(0.0f, 0.0f, 0.0f); } for(i=0; i<segments; i++) { MFSetPosition(MFSin(around)*radius, 0.0f, MFCos(around)*radius); MFSetPosition(0.0f, 0.0f, 0.0f); around -= aroundInc; } if(!wireframe) MFSetPosition(0.0f, 0.0f, radius); MFEnd(); } MF_API void MFPrimitive_DrawArrow(const MFVector& pos, const MFVector& dir, float length, float radius, const MFVector& colour, const MFMatrix &mat, bool wireframe) { MFCALLSTACK; MFVector v = dir; v.Normalise3(); v*= length * 0.7f; if(radius == 0.0f) { MFPrimitive(PT_LineList|PT_Prelit|PT_Untextured); MFSetMatrix(mat); MFBegin(2); MFSetColourV(colour); MFSetPositionV(pos); MFSetPositionV(pos+v); MFEnd(); } else MFPrimitive_DrawCylinder(pos, pos+v, radius, 5, 0, colour, mat, wireframe); MFPrimitive_DrawCone(pos+v, pos+v+v*0.25f, length*0.03f + radius*2.0f, 5, colour, mat, wireframe); } MF_API void MFPrimitive_DrawTransform(const MFMatrix& _mat, float scale, bool lite) { MFCALLSTACK; if(lite) { MFPrimitive(PT_LineList|PT_Prelit|PT_Untextured); MFSetMatrix(_mat); MFBegin(6); MFSetColourV(MFVector::red); MFSetPosition(0.0f,0.0f,0.0f); MFSetPosition(scale*0.8f,0.0f,0.0f); MFSetColourV(MFVector::green); MFSetPosition(0.0f,0.0f,0.0f); MFSetPosition(0.0f,scale*0.8f,0.0f); MFSetColourV(MFVector::blue); MFSetPosition(0.0f,0.0f,0.0f); MFSetPosition(0.0f,0.0f,scale*0.8f); MFEnd(); //MFPrimitive_DrawCone(MakeVector(scale*0.8f,0.0f,0.0f), MakeVector(scale,0.0f,0.0f), scale*0.04f, 5, MakeVector(1.0f, 0.0f, 0.0f, 1.0f), _mat); //MFPrimitive_DrawCone(MakeVector(0.0f, scale*0.8f,0.0f), MakeVector(0.0f,scale,0.0f), scale*0.04f, 5, MakeVector(0.0f, 1.0f, 0.0f, 1.0f), _mat); //MFPrimitive_DrawCone(MakeVector(0.0f, 0.0f, scale*0.8f), MakeVector(0.0f,0.0f,scale), scale*0.04f, 5, MakeVector(0.0f, 0.0f, 1.0f, 1.0f), _mat); } else { MFPrimitive_DrawArrow(MFVector::zero, MakeVector(1.0f,0.0f,0.0f), scale, scale * 0.02f, MFVector::red, _mat); MFPrimitive_DrawArrow(MFVector::zero, MakeVector(0.0f,1.0f,0.0f), scale, scale * 0.02f, MFVector::green, _mat); MFPrimitive_DrawArrow(MFVector::zero, MakeVector(0.0f,0.0f,1.0f), scale, scale * 0.02f, MFVector::blue, _mat); } }
25.897912
192
0.660276
TurkeyMan
3bfc8e639185323a3809ca82c09428b3b1b8afe5
5,137
cpp
C++
3rdparty/libprocess/3rdparty/stout/tests/json_tests.cpp
tillt/mesos
3031114c7bb93853b526fa62e4735a96bc8a9150
[ "Apache-2.0" ]
1
2015-11-06T09:33:10.000Z
2015-11-06T09:33:10.000Z
3rdparty/libprocess/3rdparty/stout/tests/json_tests.cpp
yuzhu/mesos-akaros
6a905943542cd93e1f71069ea6c228b7085533b7
[ "Apache-2.0" ]
1
2015-12-21T23:47:34.000Z
2015-12-21T23:47:47.000Z
3rdparty/libprocess/3rdparty/stout/tests/json_tests.cpp
tillt/mesos
3031114c7bb93853b526fa62e4735a96bc8a9150
[ "Apache-2.0" ]
null
null
null
#include <gtest/gtest.h> #include <gmock/gmock.h> #include <stdint.h> #include <sys/stat.h> #include <string> #include <stout/gtest.hpp> #include <stout/json.hpp> #include <stout/stringify.hpp> #include <stout/strings.hpp> using std::string; using boost::get; TEST(JsonTest, DefaultValueIsNull) { JSON::Value v; EXPECT_EQ("null", stringify(v)); } TEST(JsonTest, BinaryData) { JSON::String s(string("\"\\/\b\f\n\r\t\x00\x19 !#[]\x7F\xFF", 17)); EXPECT_EQ("\"\\\"\\\\\\/\\b\\f\\n\\r\\t\\u0000\\u0019 !#[]\\u007F\\u00FF\"", stringify(s)); } TEST(JsonTest, NumberFormat) { // Test whole numbers. EXPECT_EQ("0", stringify(JSON::Number(0.0))); EXPECT_EQ("1", stringify(JSON::Number(1.0))); // Negative. EXPECT_EQ("-1", stringify(JSON::Number(-1.0))); // Expect at least 15 digits of precision. EXPECT_EQ("1234567890.12345", stringify(JSON::Number(1234567890.12345))); } TEST(JsonTest, BooleanFormat) { EXPECT_EQ("false", stringify(JSON::False())); EXPECT_EQ("true", stringify(JSON::True())); EXPECT_EQ("true", stringify(JSON::Boolean(true))); EXPECT_EQ("false", stringify(JSON::Boolean(false))); EXPECT_EQ("true", stringify(JSON::Value(true))); EXPECT_EQ("false", stringify(JSON::Value(false))); } TEST(JsonTest, BooleanAssignement) { JSON::Value v = true; EXPECT_TRUE(get<JSON::Boolean>(v).value); v = false; EXPECT_FALSE(get<JSON::Boolean>(v).value); JSON::Boolean b = true; EXPECT_TRUE(b.value); b = false; EXPECT_FALSE(b.value); } TEST(JsonTest, CStringAssignment) { JSON::Value v = "test"; JSON::String s = "test"; EXPECT_EQ(get<JSON::String>(v).value, "test"); EXPECT_EQ(s.value, "test"); v = "123"; s = "123"; EXPECT_EQ(get<JSON::String>(v).value, "123"); EXPECT_EQ(s.value, "123"); char buf[1000]; v = strcpy(buf, "bar"); s = strcpy(buf, "bar"); EXPECT_EQ(get<JSON::String>(v).value, "bar"); EXPECT_EQ(s.value, "bar"); } TEST(JsonTest, NumericAssignment) { // Just using this to get various numeric datatypes that // are used by clients of stout. struct stat s; s.st_nlink = 1; JSON::Value v = s.st_nlink; JSON::Number d = s.st_nlink; EXPECT_EQ(get<JSON::Number>(v).value, 1.0); EXPECT_EQ(d.value, 1.0); s.st_size = 2; v = s.st_size; d = s.st_size; EXPECT_EQ(get<JSON::Number>(v).value, 2.0); EXPECT_EQ(d.value, 2.0); s.st_mtime = 3; v = s.st_mtime; d = s.st_mtime; EXPECT_EQ(get<JSON::Number>(v).value, 3.0); EXPECT_EQ(d.value, 3.0); size_t st = 4; v = st; d = st; EXPECT_EQ(get<JSON::Number>(v).value, 4.0); EXPECT_EQ(d.value, 4.0); uint64_t ui64 = 5; v = ui64; d = ui64; EXPECT_EQ(get<JSON::Number>(v).value, 5.0); EXPECT_EQ(d.value, 5.0); const unsigned int ui = 6; v = ui; d = ui; EXPECT_EQ(get<JSON::Number>(v).value, 6.0); EXPECT_EQ(d.value, 6.0); int i = 7; v = i; d = i; EXPECT_EQ(get<JSON::Number>(v).value, 7.0); EXPECT_EQ(d.value, 7.0); } TEST(JsonTest, parse) { JSON::Object object; object.values["strings"] = "string"; object.values["integer1"] = 1; object.values["integer2"] = -1; object.values["double1"] = 1; object.values["double2"] = -1; object.values["double3"] = -1.42; JSON::Object nested; nested.values["string"] = "string"; EXPECT_SOME_EQ(nested, JSON::parse<JSON::Object>(stringify(nested))); object.values["nested"] = nested; JSON::Array array; array.values.push_back(nested); EXPECT_SOME_EQ(array, JSON::parse<JSON::Array>(stringify(array))); object.values["array"] = array; EXPECT_SOME_EQ(object, JSON::parse(stringify(object))); } TEST(JsonTest, Find) { JSON::Object object; JSON::Object nested1; JSON::Object nested2; nested2.values["string"] = "string"; nested2.values["integer"] = -1; nested2.values["double"] = -1.42; nested2.values["null"] = JSON::Null(); JSON::Array array; array.values.push_back("hello"); nested2.values["array"] = array; nested1.values["nested2"] = nested2; object.values["nested1"] = nested1; ASSERT_NONE(object.find<JSON::String>("nested.nested.string")); ASSERT_NONE(object.find<JSON::String>("nested1.nested2.none")); ASSERT_ERROR(object.find<JSON::String>("nested1.nested2.array")); ASSERT_ERROR(object.find<JSON::String>("nested1.nested2.array.foo")); ASSERT_SOME_EQ( JSON::String("string"), object.find<JSON::String>("nested1.nested2.string")); ASSERT_SOME_EQ( JSON::Number(-1), object.find<JSON::Number>("nested1.nested2.integer")); ASSERT_SOME_EQ( JSON::Number(-1.42), object.find<JSON::Number>("nested1.nested2.double")); ASSERT_SOME_EQ( JSON::Null(), object.find<JSON::Null>("nested1.nested2.null")); Result<JSON::Array> result = object.find<JSON::Array>("nested1.nested2.array"); ASSERT_SOME(result); ASSERT_FALSE(result.get().values.empty()); ASSERT_TRUE(result.get().values.front().is<JSON::String>()); ASSERT_EQ("hello", result.get().values.front().as<JSON::String>()); // Also test getting JSON::Value when you don't know the type. ASSERT_SOME(object.find<JSON::Value>("nested1.nested2.null")); }
21.952991
78
0.64707
tillt
3bfced874a27779e4b731e074247da3dd036426c
30,993
hpp
C++
Headers/InteractionEntities.hpp
RealTimeChris/DiscordCoreAPI
8286783c8fa220c72ec9c9bb2d5f35076233d1ee
[ "Apache-2.0" ]
107
2021-06-12T07:07:33.000Z
2022-03-29T05:53:17.000Z
Headers/InteractionEntities.hpp
RealTimeChris/DiscordCoreAPI
8286783c8fa220c72ec9c9bb2d5f35076233d1ee
[ "Apache-2.0" ]
4
2022-01-21T23:32:46.000Z
2022-02-25T17:53:05.000Z
Headers/InteractionEntities.hpp
RealTimeChris/DiscordCoreAPI
8286783c8fa220c72ec9c9bb2d5f35076233d1ee
[ "Apache-2.0" ]
21
2021-06-11T02:01:39.000Z
2022-03-29T06:08:56.000Z
// InteractionEntities.hpp - Header for the interaction related classes and structs. // May 28, 2021 // Chris M. // https://github.com/RealTimeChris #pragma once #include "IndexInitial.hpp" #include "FoundationEntities.hpp" #include "JSONIFier.hpp" #include "MessageEntities.hpp" namespace DiscordCoreAPI { /** * \addtogroup foundation_entities * @{ */ class DiscordCoreAPI_Dll InteractionResponse { public: /// Adds a button to the response Message. \brief Adds a button to the response Message. /// \param disabled Whether the button is active or not. /// \param customId A custom id to give for identifying the button. /// \param buttonLabel A visible label for the button. /// \param buttonStyle The style of the button. /// \param emojiName An emoji name, if desired. /// \param emojiId An emoji id, if desired. /// \param url A url, if applicable. void addButton(bool disabled, string customId, string buttonLabel, ButtonStyle buttonStyle, string emojiName = "", string emojiId = "", string url = "") { if (this->data.data.components.size() == 0) { ActionRowData actionRowData; this->data.data.components.push_back(actionRowData); } if (this->data.data.components.size() < 5) { if (this->data.data.components.at(this->data.data.components.size() - 1).components.size() < 5) { ComponentData component; component.type = ComponentType::Button; component.emoji.name = emojiName; component.label = buttonLabel; component.style = buttonStyle; component.customId = customId; component.disabled = disabled; component.emoji.id = emojiId; component.url = url; this->data.data.components.at(this->data.data.components.size() - 1).components.push_back(component); } else if (this->data.data.components.at(this->data.data.components.size() - 1).components.size() == 5) { ActionRowData actionRowData; this->data.data.components.push_back(actionRowData); } } } /// Adds a select-menu to the response Message. \brief Adds a select-menu to the response Message. /// \param disabled Whether the select-menu is active or not. /// \param customId A custom id to give for identifying the select-menu. /// \param options A vector of select-menu-options to offer. /// \param placeholder Custom placeholder text if nothing is selected, max 100 characters. /// \param maxValues Maximum number of selections that are possible. /// \param minValues Minimum required number of selections that are required. void addSelectMenu(bool disabled, string customId, vector<SelectOptionData> options, string placeholder, int32_t maxValues, int32_t minValues) { if (this->data.data.components.size() == 0) { ActionRowData actionRowData; this->data.data.components.push_back(actionRowData); } if (this->data.data.components.size() < 5) { if (this->data.data.components.at(this->data.data.components.size() - 1).components.size() < 5) { ComponentData componentData; componentData.type = ComponentType::SelectMenu; componentData.placeholder = placeholder; componentData.maxValues = maxValues; componentData.minValues = minValues; componentData.disabled = disabled; componentData.customId = customId; componentData.options = options; this->data.data.components.at(this->data.data.components.size() - 1).components.push_back(componentData); } else if (this->data.data.components.at(this->data.data.components.size() - 1).components.size() == 5) { ActionRowData actionRowData; this->data.data.components.push_back(actionRowData); } } } /// For setting the allowable mentions in a response. \brief For setting the allowable mentions in a response. /// \param dataPackage An AllowedMentionsData structure. void addAllowedMentions(AllowedMentionsData dataPackage) { this->data.data.allowedMentions = dataPackage; } /// For setting the components in a response. \brief For setting the components in a response. /// \param dataPackage An ActionRowData structure. void addComponentRow(ActionRowData dataPackage) { this->data.data.components.push_back(dataPackage); } /// Sets the response type of the current Message. \brief Sets the response type of the current Message. /// \param type Interaction callback type. void setResponseType(InteractionCallbackType type) { this->data.type = type; } /// For setting the embeds in a response. \brief For setting the embeds in a response. /// \param dataPackage An EmbedData structure. void addMessageEmbed(EmbedData dataPackage) { this->data.data.embeds.push_back(dataPackage); } /// For setting the Message content in a response. \brief For setting the Message content in a response. /// \param dataPackage A string, containing the content. void addContent(string dataPackage) { this->data.data.content = dataPackage; } /// For setting the tts status of a response. \brief For setting the tts status of a response. /// \param enabledTTs A bool. void setTTSStatus(bool enabledTTs) { this->data.data.tts = enabledTTs; } virtual ~InteractionResponse() {}; protected: InteractionPackageData interactionPackage{}; MessagePackageData messagePackage{}; InteractionResponseData data{}; string requesterId{ "" }; }; /// For deferring a component response. \brief For deferring a component response. class DiscordCoreAPI_Dll DeferComponentResponseData : public InteractionResponse { public: friend class CreateInteractionResponseData; friend class InputEvents; DeferComponentResponseData(RespondToInputEventData dataPackage) { this->interactionPackage.interactionToken = dataPackage.interactionToken; this->responseType = InputEventResponseType::DeferredResponse; this->interactionPackage.applicationId = dataPackage.applicationId; this->interactionPackage.interactionId = dataPackage.interactionId; this->type = InteractionCallbackType::DeferredUpdateMessage; } virtual ~DeferComponentResponseData() {}; protected: InputEventResponseType responseType{}; InteractionCallbackType type{}; }; /// For creating an ephemeral Interaction response. \brief For creating an ephemeral Interaction response. class DiscordCoreAPI_Dll CreateEphemeralInteractionResponseData : public InteractionResponse { public: friend class CreateInteractionResponseData; friend class Interactions; friend class InputEvents; CreateEphemeralInteractionResponseData(RespondToInputEventData dataPackage) { this->interactionPackage.interactionToken = dataPackage.interactionToken; if (dataPackage.eventType == InteractionType::MESSAGE_COMPONENT) { this->data.type = InteractionCallbackType::UpdateMessage; } else { this->data.type = InteractionCallbackType::ChannelMessageWithSource; } this->interactionPackage.applicationId = dataPackage.applicationId; this->interactionPackage.interactionId = dataPackage.interactionId; this->data.data.allowedMentions = dataPackage.allowedMentions; this->data.data.components = dataPackage.components; this->data.data.content = dataPackage.content; this->data.data.embeds = dataPackage.embeds; this->requesterId = dataPackage.requesterId; this->data.data.tts = dataPackage.tts; this->data.data.flags = 64; } virtual ~CreateEphemeralInteractionResponseData() {}; }; /// For creating an Interaction response. \brief For creating an Interaction response. class DiscordCoreAPI_Dll CreateInteractionResponseData : public InteractionResponse { public: friend string DiscordCoreInternal::JSONIFY(CreateInteractionResponseData dataPackage); friend class SelectMenuCollector; friend class ButtonCollector; friend class Interactions; friend class InputEvents; CreateInteractionResponseData(DeferComponentResponseData dataPackage) { this->interactionPackage.interactionToken = dataPackage.interactionPackage.interactionToken; this->interactionPackage.interactionId = dataPackage.interactionPackage.interactionId; this->interactionPackage.applicationId = dataPackage.interactionPackage.applicationId; this->data.type = dataPackage.type; } CreateInteractionResponseData(CreateEphemeralInteractionResponseData dataPackage) { this->interactionPackage.interactionToken = dataPackage.interactionPackage.interactionToken; this->interactionPackage.applicationId = dataPackage.interactionPackage.applicationId; this->interactionPackage.interactionId = dataPackage.interactionPackage.interactionId; this->data.data.components = dataPackage.data.data.components; this->requesterId = dataPackage.requesterId; this->data.type = dataPackage.data.type; this->data = dataPackage.data; this->data.data.flags = 64; } CreateInteractionResponseData(RespondToInputEventData dataPackage) { this->interactionPackage.interactionToken = dataPackage.interactionToken; if (dataPackage.eventType == InteractionType::MESSAGE_COMPONENT) { this->data.type = InteractionCallbackType::UpdateMessage; } else { this->data.type = InteractionCallbackType::ChannelMessageWithSource; } this->interactionPackage.applicationId = dataPackage.applicationId; this->interactionPackage.interactionId = dataPackage.interactionId; this->data.data.allowedMentions = dataPackage.allowedMentions; this->data.data.components = dataPackage.components; this->data.data.content = dataPackage.content; this->data.data.embeds = dataPackage.embeds; this->requesterId = dataPackage.requesterId; this->data.data.flags = dataPackage.flags; this->data.data.tts = dataPackage.tts; } CreateInteractionResponseData(InteractionData dataPackage) { if (dataPackage.type == InteractionType::MESSAGE_COMPONENT) { this->data.type = InteractionCallbackType::UpdateMessage; } else { this->data.type = InteractionCallbackType::ChannelMessageWithSource; } this->interactionPackage.interactionToken = dataPackage.token; this->interactionPackage.interactionId = dataPackage.id; if (dataPackage.member.user.id != "") { this->requesterId = dataPackage.message.member.user.id; } else { this->requesterId = dataPackage.user.id; } } virtual ~CreateInteractionResponseData() {}; }; /// For creating a deferred Interaction response. \brief For creating a deferred Interaction response. class DiscordCoreAPI_Dll CreateDeferredInteractionResponseData : public InteractionResponse { public: friend string DiscordCoreInternal::JSONIFY(CreateDeferredInteractionResponseData dataPackage); friend class Interactions; friend class InputEvents; CreateDeferredInteractionResponseData(RespondToInputEventData dataPackage) { if (dataPackage.eventType == InteractionType::MESSAGE_COMPONENT) { this->data.type = InteractionCallbackType::DeferredUpdateMessage; } else { this->data.type = InteractionCallbackType::DeferredChannelMessageWithSource; } this->interactionPackage.interactionToken = dataPackage.interactionToken; this->interactionPackage.applicationId = dataPackage.applicationId; this->interactionPackage.interactionId = dataPackage.interactionId; this->data.data.allowedMentions = dataPackage.allowedMentions; this->data.data.components = dataPackage.components; this->data.data.content = dataPackage.content; this->data.data.embeds = dataPackage.embeds; this->requesterId = dataPackage.requesterId; this->data.data.flags = dataPackage.flags; this->data.data.tts = dataPackage.tts; } virtual ~CreateDeferredInteractionResponseData() {}; protected: string channelId{ "" }; }; /// For getting an Interaction response. \brief For getting an Interaction response. struct DiscordCoreAPI_Dll GetInteractionResponseData { string interactionToken{ "" }; ///< Interaction token. string applicationId{ "" }; ///< application id. }; /// For editing an Interaction response. \brief For editing an Interaction response. class DiscordCoreAPI_Dll EditInteractionResponseData : public InteractionResponse { public: friend string DiscordCoreInternal::JSONIFY(EditInteractionResponseData dataPackage); friend class Interactions; friend class InputEvents; EditInteractionResponseData(RespondToInputEventData dataPackage) { this->interactionPackage.interactionToken = dataPackage.interactionToken; this->interactionPackage.applicationId = dataPackage.applicationId; this->interactionPackage.interactionId = dataPackage.interactionId; this->data.data.allowedMentions = dataPackage.allowedMentions; this->data.type = InteractionCallbackType::UpdateMessage; this->data.data.components = dataPackage.components; this->data.data.content = dataPackage.content; this->data.data.embeds = dataPackage.embeds; this->requesterId = dataPackage.requesterId; this->data.data.flags = dataPackage.flags; this->data.data.tts = dataPackage.tts; } virtual ~EditInteractionResponseData() {}; }; /// For deleting an Interaction response. \brief For deleting an Interaction response. struct DiscordCoreAPI_Dll DeleteInteractionResponseData { friend void deleteInteractionResponseToBeWrapped(DeleteInteractionResponseData dataPackage); friend class InputEvents; friend class Interactions; DeleteInteractionResponseData(RespondToInputEventData dataPackage) { this->interactionPackage.interactionToken = dataPackage.interactionToken; this->interactionPackage.applicationId = dataPackage.applicationId; this->interactionPackage.interactionId = dataPackage.interactionId; } protected: InteractionPackageData interactionPackage{}; uint32_t timeDelay{ 0 }; }; /// For creating an ephemeral follow up Message. \brief For creating an ephemeral follow up Message. class DiscordCoreAPI_Dll CreateEphemeralFollowUpMessageData : public InteractionResponse { public: friend class CreateFollowUpMessageData; friend class Interactions; friend class InputEvents; CreateEphemeralFollowUpMessageData(RespondToInputEventData dataPackage) { this->interactionPackage.interactionToken = dataPackage.interactionToken; if (dataPackage.eventType == InteractionType::MESSAGE_COMPONENT) { this->data.type = InteractionCallbackType::UpdateMessage; } else { this->data.type = InteractionCallbackType::ChannelMessageWithSource; } this->interactionPackage.applicationId = dataPackage.applicationId; this->interactionPackage.interactionId = dataPackage.interactionId; this->data.data.allowedMentions = dataPackage.allowedMentions; this->data.data.components = dataPackage.components; this->data.data.content = dataPackage.content; this->data.data.embeds = dataPackage.embeds; this->requesterId = dataPackage.requesterId; this->data.data.tts = dataPackage.tts; this->data.data.flags = 64; } virtual ~CreateEphemeralFollowUpMessageData() {}; }; /// For creating a follow up Message. \brief For creating a follow up Message. class DiscordCoreAPI_Dll CreateFollowUpMessageData : public InteractionResponse { public: friend string DiscordCoreInternal::JSONIFY(CreateFollowUpMessageData dataPackage); friend class Interactions; friend class InputEvents; CreateFollowUpMessageData(CreateEphemeralFollowUpMessageData dataPackage) { this->interactionPackage = dataPackage.interactionPackage; this->requesterId = dataPackage.requesterId; this->data = dataPackage.data; } CreateFollowUpMessageData(RespondToInputEventData dataPackage) { this->interactionPackage.interactionToken = dataPackage.interactionToken; if (dataPackage.eventType == InteractionType::MESSAGE_COMPONENT) { this->data.type = InteractionCallbackType::UpdateMessage; } else { this->data.type = InteractionCallbackType::ChannelMessageWithSource; } this->interactionPackage.applicationId = dataPackage.applicationId; this->interactionPackage.interactionId = dataPackage.interactionId; this->data.data.allowedMentions = dataPackage.allowedMentions; this->data.data.components = dataPackage.components; this->data.data.content = dataPackage.content; this->data.data.embeds = dataPackage.embeds; this->requesterId = dataPackage.requesterId; this->data.data.flags = dataPackage.flags; this->data.data.tts = dataPackage.tts; } virtual ~CreateFollowUpMessageData() {}; }; /// For getting a follow-up Message. \brief For getting a follow-up Message. struct DiscordCoreAPI_Dll GetFollowUpMessageData { string messageId{ "" };///< Message id. string interactionToken{ "" }; ///< Interaction token. string applicationId{ "" }; ///< application id. }; /// For editing a follow up Message. \brief For editing a follow up Message. class DiscordCoreAPI_Dll EditFollowUpMessageData : public InteractionResponse { public: friend string DiscordCoreInternal::JSONIFY(EditFollowUpMessageData dataPackage); friend class Interactions; friend class InputEvents; EditFollowUpMessageData(RespondToInputEventData dataPackage) { this->interactionPackage.interactionToken = dataPackage.interactionToken; this->interactionPackage.applicationId = dataPackage.applicationId; this->interactionPackage.interactionId = dataPackage.interactionId; this->data.data.allowedMentions = dataPackage.allowedMentions; if (dataPackage.eventType == InteractionType::MESSAGE_COMPONENT) { this->data.type = InteractionCallbackType::UpdateMessage; } else { this->data.type = InteractionCallbackType::ChannelMessageWithSource; } this->messagePackage.channelId = dataPackage.channelId; this->messagePackage.messageId = dataPackage.messageId; this->data.data.components = dataPackage.components; this->data.data.content = dataPackage.content; this->data.data.embeds = dataPackage.embeds; this->requesterId = dataPackage.requesterId; this->data.data.flags = dataPackage.flags; this->data.data.tts = dataPackage.tts; } virtual ~EditFollowUpMessageData() {}; }; /// For deleting a follow up Message. \brief For deleting a follow up Message. struct DiscordCoreAPI_Dll DeleteFollowUpMessageData { friend void deleteFollowUpMessageToBeWrapped(DeleteFollowUpMessageData dataPackage); friend class InputEvents; friend class Interactions; DeleteFollowUpMessageData(RespondToInputEventData dataPackage) { this->interactionPackage.interactionToken = dataPackage.interactionToken; this->interactionPackage.applicationId = dataPackage.applicationId; this->interactionPackage.interactionId = dataPackage.interactionId; this->messagePackage.messageId = dataPackage.messageId; } protected: InteractionPackageData interactionPackage{}; MessagePackageData messagePackage{}; uint32_t timeDelay{ 0 }; }; /// A single Interaction. struct DiscordCoreAPI_Dll Interaction : public InteractionData { public: Interaction(InteractionData dataPackage); virtual ~Interaction() {}; }; /**@}*/ /** * \addtogroup main_endpoints * @{ */ /// An interface class for the Interaction related Discord endpoints. \brief An interface class for the Interaction related Discord endpoints. class DiscordCoreAPI_Dll Interactions { public: friend class DiscordCoreInternal::BaseSocketAgent; friend class DiscordCoreClient; friend class EventHandler; friend class EventManager; /// Creates a deferred response to an input Interaction. \brief Creates a deferred response to an input Interaction. /// \param dataPackage A CreateDeferredInteractionResponseData structure. /// \returns A CoRoutine containing void. static CoRoutine<void> createDeferredInteractionResponseAsync(CreateDeferredInteractionResponseData dataPackage); /// Creates a response to an input Interaction. \brief Creates a response to an input Interaction. /// \param dataPackage A CreateInteractionResponseData structure. /// \returns A CoRoutine containing a MessageData. static CoRoutine<Message> createInteractionResponseAsync(CreateInteractionResponseData dataPackage); /// Collects an Interaction response. \brief Collects an Interaction response. /// \param dataPackage A GetInteractionResponseData structure. /// \returns A CoRoutine containing an InteractionResponseData. static CoRoutine<InteractionResponseData> getInteractionResponseAsync(GetInteractionResponseData dataPackage); /// Edits an Interaction response. \brief Edits an Interaction response. /// \param dataPackage A EditInteractionResponseData structure. /// \returns A CoRoutine containing a MessageData. static CoRoutine<Message> editInteractionResponseAsync(EditInteractionResponseData dataPackage); /// Deletes an Interaction respnose. \brief Deletes an Interaction respnose. /// \param dataPackage A DeleteInteractionResponseData structure. /// \returns A CoRoutine containing void. static CoRoutine<void> deleteInteractionResponseAsync(DeleteInteractionResponseData dataPackage); /// Creates a follow up Message to an input Interaction. \brief Creates a follow up Message to an input Interaction. /// \param dataPackage A CreateFollowUpMessageData structure. /// \returns A CoRoutine containing a MessageData. static CoRoutine<Message> createFollowUpMessageAsync(CreateFollowUpMessageData dataPackage); /// Creates a follow up Message to an input Interaction. \brief Creates a follow up Message to an input Interaction. /// \param dataPackage A CreateFollowUpMessageData structure. /// \returns A CoRoutine containing a MessageData. static CoRoutine<Message> getFollowUpMessageAsync(GetFollowUpMessageData dataPackage); /// Edits a follow up Message. \brief Edits a follow up Message. /// \param dataPackage A EditFollowUpMessageData structure. /// \returns A CoRoutine containing a MessageData. static CoRoutine<Message> editFollowUpMessageAsync(EditFollowUpMessageData dataPackage); /// Deletes a follow up Message. \brief Deletes a follow up Message. /// \param dataPackage A DeleteFollowUpMessageData structure. /// \returns A CoRoutine containing void. static CoRoutine<void> deleteFollowUpMessageAsync(DeleteFollowUpMessageData dataPackage); protected: static unordered_map<string, unique_ptr<UnboundedMessageBlock<MessageData>>> collectMessageDataBuffers; }; /**@}*/ /** * \addtogroup utilities * @{ */ /// Select menu response data. \brief Select menu response data. struct DiscordCoreAPI_Dll SelectMenuResponseData { InteractionData interactionData{};///< Interaction data. string selectionId{ "" };///< Selection id. vector<string> values{};///< A vector of the chosen values. string channelId{ "" };///< The Channel id where it took place. string messageId{ "" };///< The Message id where it took place. string userId{ "" };///< The User id who selected the menu options. }; /// SelectMenuCollector, for collecting select-menu input from one or more Users. \brief SelectMenuCollector, for collecting select-menu input from one or more Users. class DiscordCoreAPI_Dll SelectMenuCollector { public: friend class DiscordCoreClient; static unordered_map<string, UnboundedMessageBlock<InteractionData>*>selectMenuInteractionBufferMap; /// Constructor. \brief Constructor. /// \param dataPackage An InputEventData structure, from the response that came from the submitted select-menu. SelectMenuCollector(InputEventData dataPackage); /// Used to collect the select-menu inputs from one or more users. \brief Used to collect the select-menu inputs from one or more users. /// \param getSelectMenuDataForAllNew Whether or not to collect select-menu input from a single target User or all potential users. /// \param maxWaitTimeInMsNew The maximum amount of time to wait for new inputs, in milliseconds. /// \param maxCollectedSelectMenuCountNew The maximum number of inputs to collect before stopping /// \param targetUserId The id of the single User to collect inputs from, if getSelectMenuDataForAllNew is set to false. /// \returns A vector of SelectMenuResponseData. CoRoutine<vector<SelectMenuResponseData>>collectSelectMenuData(bool getSelectMenuDataForAllNew, int32_t maxWaitTimeInMsNew, int32_t maxCollectedSelectMenuCountNew, string targetUserId = ""); ~SelectMenuCollector(); protected: unique_ptr<UnboundedMessageBlock<InteractionData>> selectMenuIncomingInteractionBuffer{ nullptr }; InteractionData interactionData{}; vector<SelectMenuResponseData> responseVector{}; int32_t currentCollectedSelectMenuCount{ 0 }; int32_t maxCollectedSelectMenuCount{ 0 }; bool getSelectMenuDataForAll{ false }; uint32_t maxTimeInMs{ 0 }; string selectMenuId{ "" }; vector<string> values{}; bool doWeQuit{ false }; string channelId{ "" }; string messageId{ "" }; string userId{ "" }; void run(); }; /// Button response data. \brief Button response data. struct DiscordCoreAPI_Dll ButtonResponseData { operator InteractionData() { return this->interactionData; } InteractionData interactionData{};///< Interaction data. string emojiName{ "" };///< The emoji name, if applicable. string channelId{ "" };///< The Channel id where it took place. string messageId{ "" };///< The Message id where it took place. string buttonId{ "" };///< The id of the button, for identification. string userId{ "" };///< The User id who selected the menu options. }; /// ButtonCollector, for collecting button input from one or more Users. \brief ButtonCollector, for collecting button input from one or more Users. class DiscordCoreAPI_Dll ButtonCollector { public: friend class DiscordCoreClient; static unordered_map<string, UnboundedMessageBlock<InteractionData>*> buttonInteractionBufferMap; /// Constructor. \brief Constructor. /// \param dataPackage An InputEventData structure, from the response that came from the submitted button. ButtonCollector(InputEventData dataPackage); /// Used to collect the button inputs from one or more users. \brief Used to collect the button inputs from one or more users. /// \param getButtonDataForAllNew Whether or not to collect input from a single target User or all potential users. /// \param maxWaitTimeInMsNew The maximum amount of time to wait for new inputs, in milliseconds. /// \param maxNumberOfPressesNew The maximum number of inputs to collect before stopping. /// \param targetUserId The id of the single User to collect inputs from, if getButtonDataForAllNew is set to false. /// \returns A vector of ButtonResponseData. CoRoutine<vector<ButtonResponseData>> collectButtonData(bool getButtonDataForAllNew, int32_t maxWaitTimeInMsNew, int32_t maxNumberOfPressesNew, string targetUserId = ""); ~ButtonCollector(); protected: unique_ptr<UnboundedMessageBlock<InteractionData>> buttonIncomingInteractionBuffer{ nullptr }; InteractionData interactionData{}; vector<ButtonResponseData> responseVector{}; int32_t currentCollectedButtonCount{ 0 }; int32_t maxCollectedButtonCount{ 0 }; bool getButtonDataForAll{ false }; uint32_t maxTimeInMs{ 0 }; vector<string> values{}; bool doWeQuit{ false }; string channelId{ "" }; string messageId{ "" }; string buttonId{ "" }; string userId{ "" }; void run(); }; /**@}*/ };
47.755008
198
0.675669
RealTimeChris
3bff378fa2a78c0f7e4d42f136c915168b7d0954
1,095
cpp
C++
categories/BEGINNER/1061/event-time.cpp
JonathaCLima/uri-online-judge
3bfe7e0512daf1dbba608c94fc1e5b64e13b2a79
[ "MIT" ]
4
2022-01-23T07:55:52.000Z
2022-02-19T15:26:20.000Z
categories/BEGINNER/1061/event-time.cpp
JonathaCLima/Beecrowd
f7208ec4bd73ac2804a9f2427c00b2baad96d13d
[ "MIT" ]
null
null
null
categories/BEGINNER/1061/event-time.cpp
JonathaCLima/Beecrowd
f7208ec4bd73ac2804a9f2427c00b2baad96d13d
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { string colon, day; int start_day, start_hour, start_minute, start_second; int end_day, end_hour, end_minute, end_second; cin >> day >> start_day; cin >> start_hour >> colon >> start_minute >> colon >> start_second; cin >> day >> end_day; cin >> end_hour >> colon >> end_minute >> colon >> end_second; int duration_day {end_day - start_day}; int duration_hour {end_hour - start_hour}; int duration_minute {end_minute - start_minute}; int duration_second {end_second - start_second}; if (duration_second < 0) { duration_second += 60; duration_minute--; } if (duration_minute < 0) { duration_minute += 60; duration_hour--; } if (duration_hour < 0) { duration_hour += 24; duration_day--; } cout << duration_day << " dia(s)" << endl; cout << duration_hour << " hora(s)" << endl; cout << duration_minute << " minuto(s)" << endl; cout << duration_second << " segundo(s)" << endl; return 0; }
24.333333
72
0.6
JonathaCLima
ce0052b34cc5da4814b3f1e7828a258de0bbf560
2,926
cpp
C++
3. Red/1 Week/4. Update Field Macros/update_field.cpp
freeraisor/yandexcplusplus
9708fdb6cd7e039672ebc2e77f131fbc7a765750
[ "MIT" ]
14
2019-08-29T12:34:07.000Z
2022-03-09T13:31:18.000Z
3. Red/1 Week/4. Update Field Macros/update_field.cpp
freeraisor/yandexcplusplus
9708fdb6cd7e039672ebc2e77f131fbc7a765750
[ "MIT" ]
null
null
null
3. Red/1 Week/4. Update Field Macros/update_field.cpp
freeraisor/yandexcplusplus
9708fdb6cd7e039672ebc2e77f131fbc7a765750
[ "MIT" ]
8
2020-09-10T11:40:03.000Z
2022-03-24T00:34:38.000Z
#include "airline_ticket.h" //#include "../../../Utils/MyTestFramework/TestFramework.h" #include <map> #include <sstream> #include <iostream> bool operator<(const Date& lhs, const Date& rhs) { return std::tie(lhs.year, lhs.month, lhs.day) < std::tie(rhs.year, rhs.month, rhs.day); } bool operator<(const Time& lhs, const Time& rhs) { return std::tie(lhs.hours, lhs.minutes) < std::tie(rhs.hours, rhs.minutes); } bool operator==(const Date& lhs, const Date& rhs) { return std::tie(lhs.year, lhs.month, lhs.day) == std::tie(rhs.year, rhs.month, rhs.day); } bool operator==(const Time& lhs, const Time& rhs) { return std::tie(lhs.hours, lhs.minutes) == std::tie(rhs.hours, rhs.minutes); } std::ostream& operator<<(std::ostream& out, const Date& rhs) { out << rhs.year << "-" << rhs.month << "-" << rhs.day; return out; } std::ostream& operator<<(std::ostream& out, const Time& rhs) { out << rhs.hours << ":" << rhs.minutes; return out; } std::istream& operator>>(std::istream& is, Date& d) { is >> d.year; is.ignore(1); is >> d.month; is.ignore(1); is >> d.day; return is; } std::istream& operator>>(std::istream& is, Time& t) { is >> t.hours; is.ignore(1); is >> t.minutes; return is; } #define UPDATE_FIELD(ticket, field, values) \ { \ auto it = values.find(#field); \ if (it != values.end()) { \ istringstream is(it->second); \ is >> ticket.field; \ } \ } #define UPDATE_FIELD(ticket, field, values) \ { \ auto it = values.find(#field); \ if (it != values.end()) \ Assign(ticket.field, it->second); \ } /* void TestUpdate() { AirlineTicket t; t.price = 0; const std::map<string, string> updates1 = { {"departure_date", "2018-2-28"}, {"departure_time", "17:40"}, }; UPDATE_FIELD(t, departure_date, updates1); UPDATE_FIELD(t, departure_time, updates1); UPDATE_FIELD(t, price, updates1); ASSERT_EQUAL(t.departure_date, (Date{2018, 2, 28})); ASSERT_EQUAL(t.departure_time, (Time{17, 40})); ASSERT_EQUAL(t.price, 0); const std::map<string, string> updates2 = { {"price", "12550"}, {"arrival_time", "20:33"}, }; UPDATE_FIELD(t, departure_date, updates2); UPDATE_FIELD(t, departure_time, updates2); UPDATE_FIELD(t, arrival_time, updates2); UPDATE_FIELD(t, price, updates2); // updates2 не содержит ключей "departure_date" и "departure_time", поэтому // значения этих полей не должны измениться ASSERT_EQUAL(t.departure_date, (Date{2018, 2, 28})); ASSERT_EQUAL(t.departure_time, (Time{17, 40})); ASSERT_EQUAL(t.price, 12550); ASSERT_EQUAL(t.arrival_time, (Time{20, 33})); } int main() { TestRunner tr; RUN_TEST(tr, TestUpdate); } */
26.844037
77
0.586466
freeraisor
ce05970bb26171b733f8dd710be4df45ae5c0d5d
5,004
cpp
C++
Sandbox/src/Application.cpp
Ckyre/brio
77a41a2a9d16c20542b60b2425e44525d3f4eef8
[ "Apache-2.0" ]
null
null
null
Sandbox/src/Application.cpp
Ckyre/brio
77a41a2a9d16c20542b60b2425e44525d3f4eef8
[ "Apache-2.0" ]
null
null
null
Sandbox/src/Application.cpp
Ckyre/brio
77a41a2a9d16c20542b60b2425e44525d3f4eef8
[ "Apache-2.0" ]
null
null
null
#include <Brio.h> #include <Brio/Core/EntryPoint.h> #include "Platform/OpenGL/OpenGLShader.h" #include "imgui/imgui.h" #include "glm/gtc/type_ptr.hpp" #include <GLFW/include/GLFW/glfw3.h> class ExampleLayer : public Brio::Layer { public: ExampleLayer() : Layer("Example"), m_CameraController(55.0f, 1280.0f / 720.0f, true) { // Shaders Brio::Ref<Brio::Shader> flatShader = Brio::MaterialLibrary::CreateShader("FlatColorShader", "E:/Dev/Brio/Sandbox/assets/Shaders/FlatColor.glsl"); Brio::Ref<Brio::Shader> diffuseShader = Brio::MaterialLibrary::CreateShader("DiffuseShader", "E:/Dev/Brio/Sandbox/assets/Shaders/Diffuse.glsl"); // Textures albedoMap = Brio::Texture2D::Create("E:/Dev/Brio/Sandbox/assets/Textures/CrateAlbedo.png"); specularMap = Brio::Texture2D::Create("E:/Dev/Brio/Sandbox/assets/Textures/CrateSpecular.png"); // Materials Brio::MaterialLibrary::CreateMaterial("FlatColorMat", flatShader); Brio::Ref<Brio::Material> diffuseMat = Brio::MaterialLibrary::CreateMaterial("DiffuseMat", diffuseShader); diffuseMat->Uniforms()->Set("material.diffuse", albedoMap); diffuseMat->Uniforms()->Set("material.specular", specularMap); // Set up scene for Renderer Brio::Renderer::SetupScene(m_CameraController.GetCamera(), glm::vec3(0.0f)); } void OnUpdate(Brio::Timestep ts) override { // Update logic timeStep = ts.GetMiliseconds(); m_CameraController.OnUpdate(ts); // Update renderer Brio::RenderCommand::SetClearColor({ 0.1f, 0.1f, 0.1f, 0.1f }); Brio::RenderCommand::Clear(); glm::vec3 lightPos = glm::vec3(glm::sin(glfwGetTime()), 1.0f, 0.0f); Brio::Renderer::BeginScene(m_CameraController.GetCamera(), lightPos); { // Light { Brio::Transform cubeTransform(lightPos, glm::vec3(0.0f), glm::vec3(0.05f, 0.05f, 0.05f)); Brio::MaterialLibrary::GetMaterial("FlatColorMat")->Uniforms()->Set("u_Color", glm::vec3(0.8f, 0.4f, 0.2f)); Brio::Renderer::Submit(Brio::MaterialLibrary::GetMaterial("FlatColorMat"), CubeMesh, cubeTransform); } // Crate { Brio::Transform carTransform(glm::vec3(0.0f), glm::vec3(0.0f), glm::vec3(0.5f, 0.5f, 0.5f)); // Material Brio::Ref<Brio::Material> sphereMaterial = Brio::MaterialLibrary::GetMaterial("DiffuseMat"); sphereMaterial->Uniforms()->Set("material.shininess", 32.0f); // Point light { sphereMaterial->Uniforms()->Set("pointLight.ambient", glm::vec3(0.2f, 0.2f, 0.2f)); sphereMaterial->Uniforms()->Set("pointLight.diffuse", glm::vec3(0.5f, 0.5f, 0.5f)); sphereMaterial->Uniforms()->Set("pointLight.specular", glm::vec3(1.0f, 1.0f, 1.0f)); sphereMaterial->Uniforms()->Set("pointLight.constant", 1.0f); sphereMaterial->Uniforms()->Set("pointLight.linear", 0.09f); sphereMaterial->Uniforms()->Set("pointLight.quadratic", 0.032f); } // Directional light { sphereMaterial->Uniforms()->Set("dirLight.direction", glm::vec3(0.6f, -0.8f, 0.3f)); sphereMaterial->Uniforms()->Set("dirLight.ambient", glm::vec3(0.2f, 0.2f, 0.2f)); sphereMaterial->Uniforms()->Set("dirLight.diffuse", glm::vec3(0.5f, 0.5f, 0.5f)); sphereMaterial->Uniforms()->Set("dirLight.specular", glm::vec3(1.0f, 1.0f, 1.0f)); } // Spot light { sphereMaterial->Uniforms()->Set("spotLight.position", m_CameraController.GetCamera().GetPosition()); sphereMaterial->Uniforms()->Set("spotLight.direction", m_CameraController.GetCamera().GetForward()); sphereMaterial->Uniforms()->Set("spotLight.cutOff", glm::cos(glm::radians(0.0f))); sphereMaterial->Uniforms()->Set("spotLight.outerCutOff", glm::cos(glm::radians(0.0f))); sphereMaterial->Uniforms()->Set("spotLight.ambient", glm::vec3(0.2f, 0.2f, 0.2f)); sphereMaterial->Uniforms()->Set("spotLight.diffuse", glm::vec3(0.5f, 0.5f, 0.5f)); sphereMaterial->Uniforms()->Set("spotLight.specular", glm::vec3(1.0f, 1.0f, 1.0f)); sphereMaterial->Uniforms()->Set("spotLight.constant", 1.0f); sphereMaterial->Uniforms()->Set("spotLight.linear", 0.09f); sphereMaterial->Uniforms()->Set("spotLight.quadratic", 0.032f); } // Render Brio::Renderer::Submit(sphereMaterial, CubeMesh, carTransform); } Skybox.Draw(m_CameraController.GetCamera()); } Brio::Renderer::EndScene(); } virtual void OnImGuiRender() override { } void OnEvent(Brio::Event& event) override { m_CameraController.OnEvent(event); } private: float timeStep = 0.0f; Brio::PerspectiveCameraController m_CameraController; Brio::Mesh CubeMesh = Brio::Mesh("E:/Dev/Brio/Sandbox/assets/Meshs/Cube.obj"); Brio::Ref<Brio::Texture2D> albedoMap, specularMap; Brio::Skybox Skybox = Brio::Skybox("E:/Dev/Brio/Sandbox/assets/Textures/", { "right.jpg", "left.jpg", "top.jpg", "bottom.jpg", "front.jpg", "back.jpg" }); }; class Sandbox : public Brio::Application { public: Sandbox() { PushLayer(new ExampleLayer()); } ~Sandbox() { } }; Brio::Application* Brio::CreateApplication() { return new Sandbox(); }
32.076923
147
0.684053
Ckyre
ce0b77aea957fe218fa00581de2f6bd6bf0dde8e
3,886
cpp
C++
tests/Unit/DataStructures/Test_SliceTensorToVariables.cpp
nilsvu/spectre
1455b9a8d7e92db8ad600c66f54795c29c3052ee
[ "MIT" ]
117
2017-04-08T22:52:48.000Z
2022-03-25T07:23:36.000Z
tests/Unit/DataStructures/Test_SliceTensorToVariables.cpp
GitHimanshuc/spectre
4de4033ba36547113293fe4dbdd77591485a4aee
[ "MIT" ]
3,177
2017-04-07T21:10:18.000Z
2022-03-31T23:55:59.000Z
tests/Unit/DataStructures/Test_SliceTensorToVariables.cpp
geoffrey4444/spectre
9350d61830b360e2d5b273fdd176dcc841dbefb0
[ "MIT" ]
85
2017-04-07T19:36:13.000Z
2022-03-01T10:21:00.000Z
// Distributed under the MIT License. // See LICENSE.txt for details. #include "Framework/TestingFramework.hpp" #include <algorithm> #include <array> #include <cstddef> #include <string> #include "DataStructures/ComplexDataVector.hpp" #include "DataStructures/ComplexModalVector.hpp" #include "DataStructures/DataVector.hpp" #include "DataStructures/ModalVector.hpp" #include "DataStructures/SliceTensorToVariables.hpp" #include "DataStructures/Tensor/Tensor.hpp" #include "DataStructures/Variables.hpp" #include "Framework/TestHelpers.hpp" #include "Helpers/DataStructures/MakeWithRandomValues.hpp" #include "Helpers/DataStructures/TestTags.hpp" #include "Utilities/TMPL.hpp" #include "Utilities/TypeTraits.hpp" namespace { template <typename VectorType> void test_variables_slice() { MAKE_GENERATOR(gen); UniformCustomDistribution<size_t> sdist{5, 10}; const size_t x_extents = sdist(gen); const size_t y_extents = sdist(gen); const size_t z_extents = sdist(gen); Variables<tmpl::list<TestHelpers::Tags::Vector<VectorType>>> vars{ x_extents * y_extents * z_extents}; const size_t tensor_size = TestHelpers::Tags::Vector<VectorType>::type::size(); Index<3> extents(x_extents, y_extents, z_extents); // Test data_on_slice function by using a predictable data set where each // entry is assigned a value equal to its index for (size_t s = 0; s < vars.size(); ++s) { // clang-tidy: do not use pointer arithmetic vars.data()[s] = s; // NOLINT } Variables<tmpl::list<TestHelpers::Tags::Vector<VectorType>>> expected_vars_sliced_in_x(y_extents * z_extents, 0.); Variables<tmpl::list<TestHelpers::Tags::Vector<VectorType>>> expected_vars_sliced_in_y(x_extents * z_extents, 0.); Variables<tmpl::list<TestHelpers::Tags::Vector<VectorType>>> expected_vars_sliced_in_z(x_extents * y_extents, 0.); const size_t x_offset = sdist(gen) % x_extents; const size_t y_offset = sdist(gen) % y_extents; const size_t z_offset = sdist(gen) % z_extents; for (size_t s = 0; s < expected_vars_sliced_in_x.size(); ++s) { // clang-tidy: do not use pointer arithmetic expected_vars_sliced_in_x.data()[s] = x_offset + s * x_extents; // NOLINT } for (size_t i = 0; i < tensor_size; ++i) { for (size_t x = 0; x < x_extents; ++x) { for (size_t z = 0; z < z_extents; ++z) { // clang-tidy: do not use pointer arithmetic expected_vars_sliced_in_y .data()[x + x_extents * (z + z_extents * i)] = // NOLINT i * extents.product() + x + x_extents * (y_offset + z * y_extents); } } } for (size_t i = 0; i < tensor_size; ++i) { for (size_t x = 0; x < x_extents; ++x) { for (size_t y = 0; y < y_extents; ++y) { // clang-tidy: do not use pointer arithmetic expected_vars_sliced_in_z .data()[x + x_extents * (y + y_extents * i)] = // NOLINT i * extents.product() + x + x_extents * (y + y_extents * z_offset); } } } CHECK(data_on_slice<TestHelpers::Tags::Vector<VectorType>>( extents, 0, x_offset, get<TestHelpers::Tags::Vector<VectorType>>(vars)) == expected_vars_sliced_in_x); CHECK(data_on_slice<TestHelpers::Tags::Vector<VectorType>>( extents, 1, y_offset, get<TestHelpers::Tags::Vector<VectorType>>(vars)) == expected_vars_sliced_in_y); CHECK(data_on_slice<TestHelpers::Tags::Vector<VectorType>>( extents, 2, z_offset, get<TestHelpers::Tags::Vector<VectorType>>(vars)) == expected_vars_sliced_in_z); } SPECTRE_TEST_CASE("Unit.DataStructures.SliceTensorToVariables", "[DataStructures][Unit]") { test_variables_slice<ComplexDataVector>(); test_variables_slice<ComplexModalVector>(); test_variables_slice<DataVector>(); test_variables_slice<ModalVector>(); } } // namespace
38.098039
79
0.681163
nilsvu
ce0fc12011a8abe155b51ff36f6b6a2fea948ce7
5,467
hpp
C++
oss_src/fault/sockets/async_reply_socket.hpp
parquette/ParFrame
0522aa6afdf529b3e91505b70e918f1500aae886
[ "BSD-3-Clause" ]
null
null
null
oss_src/fault/sockets/async_reply_socket.hpp
parquette/ParFrame
0522aa6afdf529b3e91505b70e918f1500aae886
[ "BSD-3-Clause" ]
null
null
null
oss_src/fault/sockets/async_reply_socket.hpp
parquette/ParFrame
0522aa6afdf529b3e91505b70e918f1500aae886
[ "BSD-3-Clause" ]
null
null
null
/** * Copyright (C) 2015 Dato, Inc. * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD license. See the LICENSE file for details. */ #ifndef FAULT_SOCKETS_ASYNC_REPLY_SOCKET_HPP #define FAULT_SOCKETS_ASYNC_REPLY_SOCKET_HPP #include <string> #include <vector> #include <set> #include <queue> #include <zmq.h> #include <boost/function.hpp> #include <boost/thread/condition_variable.hpp> #include <boost/thread/mutex.hpp> #include <fault/zmq/zmq_msg_vector.hpp> #include <fault/sockets/socket_receive_pollset.hpp> #include <export.hpp> namespace graphlab { namespace zookeeper_util { class key_value; } } namespace libfault { /** * \ingroup fault * Constructs a zookeeper backed asynchronous reply socket. * Will automatically retry sockets. * * This object works together with the socket_receive_pollset(). * The general construction is to * - Create a async_reply_socket * - Create a socket_receive_pollset * - Register the keys this socket should listen on (register_key() ) * - register this reply_socket with the pollset * (add_to_pollset()) * - start the pollset ( socket_receive_pollset::start_poll_thread() ) * * \note * The first part of the message must be a key. This must be a key the * current client is registered for. */ class EXPORT async_reply_socket { public: /** * Returns true if there are contents to reply. * Returns false otherwise. * If the reply socket is connected to a request socket, * this must always return true. * \note There is no provided way to figure out if a reply is necessary. * This must be managed on a higher protocol layer. */ typedef boost::function<bool (zmq_msg_vector& recv, zmq_msg_vector& reply)> callback_type; /** * Constructs a reply socket. * \param zmq_ctx A zeroMQ Context * \param keyval A zookeeper key_value object to bind to * \param callback The function used to process replies. Multiple * threads may call the callback simultaneously * \param nthreads The maximum number of threads to use * \param alternate_bind_address If set, this will be address to bind to. * Otherwise, binds to a free tcp address. * * keyval can be NULL, in which case, the alternate_bind_address must be * provided, in which case this socket behaves like a simple * messaging wrapper around ZeroMQ which provides asynchronous messaging * capabilities. */ async_reply_socket(void* zmq_ctx, graphlab::zookeeper_util::key_value* keyval, callback_type callback, size_t nthreads = 4, std::string alternate_bind_address = "", std::string secret_key = ""); /** * Closes the socket. Once closed. It cannot be opened again */ void close(); /** * Tries to register this socket under a given object key. * Returns true on success and false on failure. */ bool register_key(std::string key); /** * Like register, but sets the key to an empty value. * Reserves ownership of the key, but prohibits people from joining */ bool reserve_key(std::string key); /** * Tries to unregister this socket from a given object key. * Returns true on success and false on failure */ bool unregister_key(std::string key); /** * Unregisters all keys this socket was registered under */ void unregister_all_keys(); /** * Registers this socket with the pollset * This socket should only registered with one pollset. */ void add_to_pollset(socket_receive_pollset* pollset); /** * Unregisters this socket with the pollset */ void remove_from_pollset(); /** * Returns the address the socket is bound to */ std::string get_bound_address(); ~async_reply_socket(); private: void* z_ctx; void* z_socket; std::string local_address; std::string secret_key; graphlab::zookeeper_util::key_value* zk_keyval; callback_type callback; socket_receive_pollset* associated_pollset; std::set<std::string> registered_keys; // some thought went into the decision whether to use a condition variable // or to use the DEALER-REP pattern. I decided that the condition variable // is better in this case since the DEALER's distribution pattern is not // exactly what we want here. If a callback takes a long time, the DEALER-REP // pattern could queue additional messages on that thread rather than // distributing it to other available threads. // for now, we use a single queue, but we could use multiple queues + // work stealing later if this turns out to block too heavily. std::queue<zmq_msg_vector*> jobqueue; boost::mutex queuelock; boost::condition_variable queuecond; void* inproc_pull_socket; bool queue_terminate; // false initially. If true, all threads die. // replies however have to go through the PUSH-PULL pattern. struct thread_data { async_reply_socket* parent; void* inproc_push_socket; boost::thread* thread; }; void thread_function(thread_data* data); void process_job(thread_data* data, zmq_msg_vector* msg); std::vector<thread_data> threads; void wrapped_callback(socket_receive_pollset* unused, const zmq_pollitem_t& unused2); void pull_socket_callback(socket_receive_pollset* unused, const zmq_pollitem_t& data); }; } // libfault #endif
31.601156
88
0.706603
parquette
ce166383e1c89655de44926c35f688ac7cc7e293
3,901
cpp
C++
SpatialGDK/Source/SpatialGDK/Private/EngineClasses/SpatialNetDriverAuthorityDebugger.cpp
cyberbibby/UnrealGDK
9502a1ba11d21b3cb64978ba7ea178c63371cdd0
[ "MIT" ]
null
null
null
SpatialGDK/Source/SpatialGDK/Private/EngineClasses/SpatialNetDriverAuthorityDebugger.cpp
cyberbibby/UnrealGDK
9502a1ba11d21b3cb64978ba7ea178c63371cdd0
[ "MIT" ]
null
null
null
SpatialGDK/Source/SpatialGDK/Private/EngineClasses/SpatialNetDriverAuthorityDebugger.cpp
cyberbibby/UnrealGDK
9502a1ba11d21b3cb64978ba7ea178c63371cdd0
[ "MIT" ]
null
null
null
// Copyright (c) Improbable Worlds Ltd, All Rights Reserved #include "EngineClasses/SpatialNetDriverAuthorityDebugger.h" #include "EngineClasses/SpatialNetDriver.h" #include "EngineClasses/SpatialPackageMapClient.h" #include "EngineClasses/SpatialShadowActor.h" DEFINE_LOG_CATEGORY(LogSpatialNetDriverAuthorityDebugger); const TArray<FName> USpatialNetDriverAuthorityDebugger::SuppressedActors = { TEXT("SpatialFunctionalTestFlowController"), // OwningTest TEXT("LockingPlayerController_C"), // Multiple TEXT("TestPossessionPlayerController"), // Multiple TEXT("GameplayDebuggerCategoryReplicator"), // CurrentServerWorkerId TEXT("PlayerController"), // Multiple TEXT("Character"), // Multiple TEXT("ReplicatedStartupActorPlayerController"), // Multiple TEXT("TestMovementCharacter"), // Multiple TEXT("SpatialTestRepNotifyActor"), // Multiple TEXT("SpatialTestSingleServerDynamicComponents"), TEXT("PlayerDisconnectController"), // Multiple TEXT("AlwaysInterestedTest"), // OtherInterestedInThisReplicatedActor TEXT("CubeWithReferences") // Multiple }; const TArray<FName> USpatialNetDriverAuthorityDebugger::SuppressedProperties = { TEXT("Controller"), // Multiple - BP_EventTracerCharacter_C, TestPawnBase_RepGraphAlwaysReplicate, TestPossessionPawn TEXT("ReplicatedWorldTimeSeconds"), // Multiple - GameStateBase, SpatialAuthorityTestGameState TEXT("Owner"), // CrossServerAndClientOrchestrationFlowController TEXT("CurrentStepIndex"), // Multiple TEXT("bActorEnableCollision"), // SpatialWorldSettings TEXT("PlayerState"), // Multiple - BP_EventTracerCharacter_C, TestPawnBase_RepGraphAlwaysReplicate, DefaultPawn TEXT("Role"), // Multiple - all actors TEXT("RemoteRole") // Multiple - all actors }; const TArray<FName> USpatialNetDriverAuthorityDebugger::SuppressedAutonomousProperties = { TEXT("Pawn"), // Controllers }; void USpatialNetDriverAuthorityDebugger::Init(USpatialNetDriver& InNetDriver) { NetDriver = &InNetDriver; } void USpatialNetDriverAuthorityDebugger::CheckUnauthorisedDataChanges() { for (auto It = SpatialShadowActors.CreateIterator(); It; ++It) { It.Value()->CheckUnauthorisedDataChanges(NetDriver->GetNetMode()); } } void USpatialNetDriverAuthorityDebugger::AddSpatialShadowActor(const Worker_EntityId_Key EntityId) { AActor* Actor = Cast<AActor>(NetDriver->PackageMap->GetObjectFromEntityId(EntityId)); if (!IsValid(Actor) || Actor->IsPendingKillOrUnreachable()) { return; } if (SpatialShadowActors.Contains(EntityId)) { UE_LOG(LogSpatialNetDriverAuthorityDebugger, Error, TEXT("Should only be adding a SpatialShadowActor once for each entity, EntityID %i"), EntityId); } else { USpatialShadowActor* SpatialShadowActor(NewObject<USpatialShadowActor>()); SpatialShadowActor->Init(*Actor); SpatialShadowActors.Emplace(EntityId, SpatialShadowActor); } } void USpatialNetDriverAuthorityDebugger::RemoveSpatialShadowActor(const Worker_EntityId_Key EntityId) { SpatialShadowActors.Remove(EntityId); } void USpatialNetDriverAuthorityDebugger::UpdateSpatialShadowActor(const Worker_EntityId_Key EntityId) { USpatialShadowActor** SpatialShadowActor = SpatialShadowActors.Find(EntityId); if (SpatialShadowActor == nullptr) { // We can receive updates without receiving adds - in this case create the SpatialShadowActor AddSpatialShadowActor(EntityId); return; } (*SpatialShadowActor)->Update(); } bool USpatialNetDriverAuthorityDebugger::IsSuppressedActor(const AActor& Actor) { return SuppressedActors.Contains(Actor.GetClass()->GetFName()); } bool USpatialNetDriverAuthorityDebugger::IsSuppressedProperty(const FProperty& Property, const AActor& Actor) { if (SuppressedProperties.Contains(Property.GetFName())) { return true; } return (Actor.Role == ROLE_AutonomousProxy && SuppressedAutonomousProperties.Contains(Property.GetFName())); }
36.457944
122
0.791336
cyberbibby
ce1a15173a687edda0f5b453a829a4a73a26c0f2
428
cpp
C++
c++/containers/array.cpp
DevNaga/c_cpp_book
c08ac6c62a98c701d512ac432df77385b51af97b
[ "Apache-2.0" ]
1
2020-11-25T02:06:23.000Z
2020-11-25T02:06:23.000Z
c++/containers/array.cpp
madmax440/c_cpp_book
c08ac6c62a98c701d512ac432df77385b51af97b
[ "Apache-2.0" ]
null
null
null
c++/containers/array.cpp
madmax440/c_cpp_book
c08ac6c62a98c701d512ac432df77385b51af97b
[ "Apache-2.0" ]
null
null
null
/** * Author Devendra Naga (devendra.aaru@gmail.com) * * License Apache */ #include <iostream> #include <array> int main() { std::array <int, 4> a; int i; for (i = 0; i < 4; i ++) { a[i] = i; } std::array <int, 4> :: const_iterator it; i = 0; for (it = a.begin(); it != a.end(); it ++) { std::cout << " array[" << i << "]" << " " << *it << std::endl; } return 0; }
15.285714
71
0.446262
DevNaga
ce1a17c9fdc8c602f409dbca93c81d8a9681109f
2,856
cpp
C++
Final/Dataset/B2016_Z3_Z1/student3756.cpp
Team-PyRated/PyRated
1df171c8a5a98977b7a96ee298a288314d1b1b96
[ "MIT" ]
null
null
null
Final/Dataset/B2016_Z3_Z1/student3756.cpp
Team-PyRated/PyRated
1df171c8a5a98977b7a96ee298a288314d1b1b96
[ "MIT" ]
null
null
null
Final/Dataset/B2016_Z3_Z1/student3756.cpp
Team-PyRated/PyRated
1df171c8a5a98977b7a96ee298a288314d1b1b96
[ "MIT" ]
null
null
null
/B2016/2017: Zadaća 3, Zadatak 1 //Autotestovi by Enil Pajic (epajic1@etf.unsa.ba) #include <iostream> #include <vector> #include <utility> #include <cmath> #include <functional> double f(double x){ return (x*x)+std::sin(x); } double w(std::vector<std::pair<double,double>>v,const int d,int i){ double suma=0; int vel=v.size(); for(int k=std::max(1,i-d);k<=std::min(i,(vel)-d);k++) { double broj=1; suma=suma+pow(-1,k-1); for(int j=k;j<=k+d;j++){ if(j!=i && i<vel && j<vel && i>0 && j>0){ broj=broj*(1./(v[i-1].first-v[j-1].first));} } suma=suma*broj; } return suma; } std::function<double(double)> BaricentricnaInterpolacija(std::vector<std::pair<double,double>> v, int d){ return[v,d](double arg){ int vel=v.size(); double suma=0; for(int i=0;i<vel;i++) if(v[i].first==arg) return v[i].second; for(int i=1;i<=vel;i++){ if(i-1<vel) suma=suma+(w(v,d,i)*v[i-1].second)/(arg-v[i-1].first); } double suma1=0; for(int i=1;i<=vel;i++){ if(i-1<vel) suma1=suma1+(w(v,d,i)/(arg-v[i-1].first)); } return suma/suma1;}; } std::function<double(double)> BaricentricnaInterpolacija(std::function<double(double)>f,double xmin, double xmax, double dx, int d){ std::vector<std::pair<double,double>> v; while(xmin<=xmax){ v.push_back({xmin,f(xmin)}); xmin=xmin+dx; } return BaricentricnaInterpolacija(v,d); } int main () { int x; std::cout<<"Odaberite opciju (1 - unos cvorova, 2 - aproksimacija): "; std::cin>>x; if(x==1){ int n; std::cout<<"\nUnesite broj cvorova: "; std::cin>>n; std::cout<<"Unesite cvorove kao parove x y: "; std::vector<std::pair<double,double>> v(n); for(int i=0;i<n;i++){ double a,b; std::cin>>a>>b; v[i].first=a; v[i].second=b; } int d; std::cout<<"\nUnesite red interpolacije: "; std::cin>>d; do{ double arg; std::cout<<"\nUnesite argument (ili 'kraj' za kraj): "; std::cin>>arg; if(!std::cin) return 0; std::cout<<"f("<<arg<<") = "<<BaricentricnaInterpolacija(v,d)(arg)<<"\n"; }while(std::cin); } else if(x==2){ int a,b; double korak; std::cout<<"Unesite krajeve intervala i korak: "; std::cin>>a>>b>>korak; int red; std::cout<<"\nUnesite red interpolacije: "; std::cin>>red; double arg; std::cout<<"\nUnesite argument (ili 'kraj' za kraj): "; std::cin>>arg; std::cout<<"f("<<arg<<") = "<<f(arg)<<" fapprox("<<arg<<") = "<<BaricentricnaInterpolacija(f,a,b,korak,red)(arg); } return 0; }
26.691589
134
0.518557
Team-PyRated
ce1bf0f7250af4b7e6bf59e946ee5d9892f34e80
4,452
ipp
C++
Siv3D/include/Siv3D/detail/Math.ipp
Siv3D/siv6
090e82b2f6398640638dfa43da3f829ba977d0e2
[ "MIT" ]
2
2020-07-26T05:14:33.000Z
2020-08-11T08:00:54.000Z
Siv3D/include/Siv3D/detail/Math.ipp
Siv3D/siv6
090e82b2f6398640638dfa43da3f829ba977d0e2
[ "MIT" ]
6
2020-03-03T04:01:10.000Z
2020-09-27T14:33:19.000Z
Siv3D/include/Siv3D/detail/Math.ipp
Siv3D/siv6
090e82b2f6398640638dfa43da3f829ba977d0e2
[ "MIT" ]
5
2020-03-03T03:34:27.000Z
2020-09-05T18:42:55.000Z
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2020 Ryo Suzuki // Copyright (c) 2016-2020 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # pragma once # define SIV3D_MATH_FUNCTION_XY(FUNC) \ inline Float2 FUNC(const Float2 v1, const Float2 v2) noexcept \ { \ return{ FUNC(v1.x, v2.x), FUNC(v1.y, v2.y) }; \ } \ inline Float3 FUNC(const Float3 v1, const Float3 v2) noexcept \ { \ return{ FUNC(v1.x, v2.x), FUNC(v1.y, v2.y), FUNC(v1.z, v2.z) }; \ } \ inline Float4 FUNC(const Float4 v1, const Float4 v2) noexcept \ { \ return{ FUNC(v1.x, v2.x), FUNC(v1.y, v2.y), FUNC(v1.z, v2.z), FUNC(v1.w, v2.w) }; \ } \ inline Vec2 FUNC(const Vec2 v1, const Vec2 v2) noexcept \ { \ return{ FUNC(v1.x, v2.x), FUNC(v1.y, v2.y) }; \ } \ inline Vec3 FUNC(const Vec3 v1, const Vec3 v2) noexcept \ { \ return{ FUNC(v1.x, v2.x), FUNC(v1.y, v2.y), FUNC(v1.z, v2.z) }; \ } \ inline Vec4 FUNC(const Vec4 v1, const Vec4 v2) noexcept \ { \ return{ FUNC(v1.x, v2.x), FUNC(v1.y, v2.y), FUNC(v1.z, v2.z), FUNC(v1.w, v2.w) }; \ } \ template <class T, class U, class R> \ inline R FUNC(const T x, const U y) noexcept \ { \ return FUNC(static_cast<R>(x), static_cast<R>(y)); \ } # define SIV3D_MATH_FUNCTION_X(FUNC) \ inline Float2 FUNC(const Float2 v) noexcept \ { \ return{ FUNC(v.x), FUNC(v.y) }; \ } \ inline Float3 FUNC(const Float3 v) noexcept \ { \ return{ FUNC(v.x), FUNC(v.y), FUNC(v.z) }; \ } \ inline Float4 FUNC(const Float4 v) noexcept \ { \ return{ FUNC(v.x), FUNC(v.y), FUNC(v.z), FUNC(v.w) }; \ } \ inline Vec2 FUNC(const Vec2 v) noexcept \ { \ return{ FUNC(v.x), FUNC(v.y) }; \ } \ inline Vec3 FUNC(const Vec3 v) noexcept \ { \ return{ FUNC(v.x), FUNC(v.y), FUNC(v.z) }; \ } \ inline Vec4 FUNC(const Vec4 v) noexcept \ { \ return{ FUNC(v.x), FUNC(v.y), FUNC(v.z), FUNC(v.w) }; \ } # define SIV3D_MATH_FUNCTION_CX(FUNC) \ inline constexpr Float2 FUNC(const Float2 v) noexcept \ { \ return{ FUNC(v.x), FUNC(v.y) }; \ } \ inline constexpr Float3 FUNC(const Float3 v) noexcept \ { \ return{ FUNC(v.x), FUNC(v.y), FUNC(v.z) }; \ } \ inline constexpr Float4 FUNC(const Float4 v) noexcept \ { \ return{ FUNC(v.x), FUNC(v.y), FUNC(v.z), FUNC(v.w) }; \ } \ inline constexpr Vec2 FUNC(const Vec2 v) noexcept \ { \ return{ FUNC(v.x), FUNC(v.y) }; \ } \ inline constexpr Vec3 FUNC(const Vec3 v) noexcept \ { \ return{ FUNC(v.x), FUNC(v.y), FUNC(v.z) }; \ } \ inline constexpr Vec4 FUNC(const Vec4 v) noexcept \ { \ return{ FUNC(v.x), FUNC(v.y), FUNC(v.z), FUNC(v.w) }; \ } namespace s3d { namespace Math { inline float Fmod(const float x, const float y) noexcept { return std::fmod(x, y); } inline double Fmod(const double x, const double y) noexcept { return std::fmod(x, y); } SIV3D_MATH_FUNCTION_XY(Fmod) inline float Fraction(const float x) noexcept { return (x - std::floor(x)); } inline double Fraction(const double x) noexcept { return (x - std::floor(x)); } SIV3D_MATH_FUNCTION_X(Fraction) inline float Exp(const float x) noexcept { return std::exp(x); } inline double Exp(const double x) noexcept { return std::exp(x); } SIV3D_MATH_FUNCTION_X(Exp) inline constexpr float Square(const float x) noexcept { return (x * x); } inline constexpr double Square(const double x) noexcept { return (x * x); } SIV3D_CONCEPT_ARITHMETIC_ inline constexpr Arithmetic Square(const Arithmetic x) noexcept { return (x * x); } SIV3D_MATH_FUNCTION_CX(Square) } } # undef SIV3D_MATH_FUNCTION_XYA
27.146341
84
0.504942
Siv3D
ce1d0372ff953d6de49db5fcc4289fed1d20e667
7,005
cpp
C++
tests/src/deviceLib/hipSimpleAtomicsTest.cpp
pzins/HIP
ab7e727fa241d998b9f2bca23b0d82dfb64c9a05
[ "MIT" ]
1
2021-12-15T15:09:07.000Z
2021-12-15T15:09:07.000Z
tests/src/deviceLib/hipSimpleAtomicsTest.cpp
rahulmula/Gladiator_Hip
fcede25343a79f5005f5a4d88a8c0e41205dc08f
[ "MIT" ]
null
null
null
tests/src/deviceLib/hipSimpleAtomicsTest.cpp
rahulmula/Gladiator_Hip
fcede25343a79f5005f5a4d88a8c0e41205dc08f
[ "MIT" ]
1
2019-07-04T00:48:48.000Z
2019-07-04T00:48:48.000Z
/* Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* HIT_START * BUILD: %t %s ../test_common.cpp * RUN: %t * HIT_END */ // includes, system #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> // Includes HIP Runtime #include "hip/hip_runtime.h" #include <test_common.h> #define EXIT_WAIVED 2 const char* sampleName = "hipSimpleAtomicsTest"; //////////////////////////////////////////////////////////////////////////////// // Auto-Verification Code bool testResult = true; //////////////////////////////////////////////////////////////////////////////// // Declaration, forward void runTest(int argc, char** argv); #define min(a, b) (a) < (b) ? (a) : (b) #define max(a, b) (a) > (b) ? (a) : (b) int computeGold(int* gpuData, const int len) { int val = 0; for (int i = 0; i < len; ++i) { val += 10; } if (val != gpuData[0]) { printf("atomicAdd failed\n"); return false; } val = 0; for (int i = 0; i < len; ++i) { val -= 10; } if (val != gpuData[1]) { printf("atomicSub failed\n"); return false; } bool found = false; for (int i = 0; i < len; ++i) { // third element should be a member of [0, len) if (i == gpuData[2]) { found = true; break; } } if (!found) { printf("atomicExch failed\n"); return false; } val = -(1 << 8); for (int i = 0; i < len; ++i) { // fourth element should be len-1 val = max(val, i); } if (val != gpuData[3]) { printf("atomicMax failed\n"); return false; } val = 1 << 8; for (int i = 0; i < len; ++i) { val = min(val, i); } if (val != gpuData[4]) { printf("atomicMin failed\n"); return false; } int limit = 17; val = 0; for (int i = 0; i < len; ++i) { val = (val >= limit) ? 0 : val + 1; } if (val != gpuData[5]) { printf("atomicInc failed\n"); return false; } limit = 137; val = 0; for (int i = 0; i < len; ++i) { val = ((val == 0) || (val > limit)) ? limit : val - 1; } if (val != gpuData[6]) { printf("atomicDec failed\n"); return false; } found = false; for (int i = 0; i < len; ++i) { // eighth element should be a member of [0, len) if (i == gpuData[7]) { found = true; break; } } if (!found) { printf("atomicCAS failed\n"); return false; } val = 0xff; for (int i = 0; i < len; ++i) { // 9th element should be 1 val &= (2 * i + 7); } if (val != gpuData[8]) { printf("atomicAnd failed\n"); return false; } val = 0; for (int i = 0; i < len; ++i) { // 10th element should be 0xff val |= (1 << i); } if (val != gpuData[9]) { printf("atomicOr failed\n"); return false; } val = 0xff; for (int i = 0; i < len; ++i) { // 11th element should be 0xff val ^= i; } if (val != gpuData[10]) { printf("atomicXor failed\n"); return false; } return true; } __global__ void testKernel(hipLaunchParm lp, int* g_odata) { // access thread id const unsigned int tid = blockDim.x * blockIdx.x + threadIdx.x; // Test various atomic instructions // Arithmetic atomic instructions // Atomic addition atomicAdd(&g_odata[0], 10); // Atomic subtraction (final should be 0) atomicSub(&g_odata[1], 10); // Atomic exchange atomicExch(&g_odata[2], tid); // Atomic maximum atomicMax(&g_odata[3], tid); // Atomic minimum atomicMin(&g_odata[4], tid); // Atomic increment (modulo 17+1) atomicInc((unsigned int*)&g_odata[5], 17); // Atomic decrement atomicDec((unsigned int*)&g_odata[6], 137); // Atomic compare-and-swap atomicCAS(&g_odata[7], tid - 1, tid); // Bitwise atomic instructions // Atomic AND atomicAnd(&g_odata[8], 2 * tid + 7); // Atomic OR atomicOr(&g_odata[9], 1 << tid); // Atomic XOR atomicXor(&g_odata[10], tid); } int main(int argc, char** argv) { printf("%s starting...\n", sampleName); runTest(argc, argv); hipDeviceReset(); printf("%s completed, returned %s\n", sampleName, testResult ? "OK" : "ERROR!"); exit(testResult ? EXIT_SUCCESS : EXIT_FAILURE); } void runTest(int argc, char** argv) { hipDeviceProp_t deviceProp; deviceProp.major = 0; deviceProp.minor = 0; int dev = 0; hipGetDeviceProperties(&deviceProp, dev); // Statistics about the GPU device printf( "> GPU device has %d Multi-Processors, " "SM %d.%d compute capabilities\n\n", deviceProp.multiProcessorCount, deviceProp.major, deviceProp.minor); unsigned int numThreads = 256; unsigned int numBlocks = 64; unsigned int numData = 11; unsigned int memSize = sizeof(int) * numData; // allocate mem for the result on host side int* hOData = (int*)malloc(memSize); // initialize the memory for (unsigned int i = 0; i < numData; i++) hOData[i] = 0; // To make the AND and XOR tests generate something other than 0... hOData[8] = hOData[10] = 0xff; // allocate device memory for result int* dOData; hipMalloc((void**)&dOData, memSize); // copy host memory to device to initialize to zero hipMemcpy(dOData, hOData, memSize, hipMemcpyHostToDevice); // execute the kernel hipLaunchKernel(testKernel, dim3(numBlocks), dim3(numThreads), 0, 0, dOData); // Copy result from device to host hipMemcpy(hOData, dOData, memSize, hipMemcpyDeviceToHost); // Compute reference solution testResult = computeGold(hOData, numThreads * numBlocks); // Cleanup memory free(hOData); hipFree(dOData); passed(); }
23.585859
84
0.574732
pzins
ce1d54a40ddd0e8cc546a9f2ecc8fa162264d806
5,201
cpp
C++
aws-cpp-sdk-securityhub/source/model/ThreatIntelIndicatorType.cpp
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
2
2019-03-11T15:50:55.000Z
2020-02-27T11:40:27.000Z
aws-cpp-sdk-securityhub/source/model/ThreatIntelIndicatorType.cpp
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-securityhub/source/model/ThreatIntelIndicatorType.cpp
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/securityhub/model/ThreatIntelIndicatorType.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace SecurityHub { namespace Model { namespace ThreatIntelIndicatorTypeMapper { static const int DOMAIN__HASH = HashingUtils::HashString("DOMAIN"); static const int EMAIL_ADDRESS_HASH = HashingUtils::HashString("EMAIL_ADDRESS"); static const int HASH_MD5_HASH = HashingUtils::HashString("HASH_MD5"); static const int HASH_SHA1_HASH = HashingUtils::HashString("HASH_SHA1"); static const int HASH_SHA256_HASH = HashingUtils::HashString("HASH_SHA256"); static const int HASH_SHA512_HASH = HashingUtils::HashString("HASH_SHA512"); static const int IPV4_ADDRESS_HASH = HashingUtils::HashString("IPV4_ADDRESS"); static const int IPV6_ADDRESS_HASH = HashingUtils::HashString("IPV6_ADDRESS"); static const int MUTEX_HASH = HashingUtils::HashString("MUTEX"); static const int PROCESS_HASH = HashingUtils::HashString("PROCESS"); static const int URL_HASH = HashingUtils::HashString("URL"); ThreatIntelIndicatorType GetThreatIntelIndicatorTypeForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == DOMAIN__HASH) { return ThreatIntelIndicatorType::DOMAIN_; } else if (hashCode == EMAIL_ADDRESS_HASH) { return ThreatIntelIndicatorType::EMAIL_ADDRESS; } else if (hashCode == HASH_MD5_HASH) { return ThreatIntelIndicatorType::HASH_MD5; } else if (hashCode == HASH_SHA1_HASH) { return ThreatIntelIndicatorType::HASH_SHA1; } else if (hashCode == HASH_SHA256_HASH) { return ThreatIntelIndicatorType::HASH_SHA256; } else if (hashCode == HASH_SHA512_HASH) { return ThreatIntelIndicatorType::HASH_SHA512; } else if (hashCode == IPV4_ADDRESS_HASH) { return ThreatIntelIndicatorType::IPV4_ADDRESS; } else if (hashCode == IPV6_ADDRESS_HASH) { return ThreatIntelIndicatorType::IPV6_ADDRESS; } else if (hashCode == MUTEX_HASH) { return ThreatIntelIndicatorType::MUTEX; } else if (hashCode == PROCESS_HASH) { return ThreatIntelIndicatorType::PROCESS; } else if (hashCode == URL_HASH) { return ThreatIntelIndicatorType::URL; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<ThreatIntelIndicatorType>(hashCode); } return ThreatIntelIndicatorType::NOT_SET; } Aws::String GetNameForThreatIntelIndicatorType(ThreatIntelIndicatorType enumValue) { switch(enumValue) { case ThreatIntelIndicatorType::DOMAIN_: return "DOMAIN"; case ThreatIntelIndicatorType::EMAIL_ADDRESS: return "EMAIL_ADDRESS"; case ThreatIntelIndicatorType::HASH_MD5: return "HASH_MD5"; case ThreatIntelIndicatorType::HASH_SHA1: return "HASH_SHA1"; case ThreatIntelIndicatorType::HASH_SHA256: return "HASH_SHA256"; case ThreatIntelIndicatorType::HASH_SHA512: return "HASH_SHA512"; case ThreatIntelIndicatorType::IPV4_ADDRESS: return "IPV4_ADDRESS"; case ThreatIntelIndicatorType::IPV6_ADDRESS: return "IPV6_ADDRESS"; case ThreatIntelIndicatorType::MUTEX: return "MUTEX"; case ThreatIntelIndicatorType::PROCESS: return "PROCESS"; case ThreatIntelIndicatorType::URL: return "URL"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return {}; } } } // namespace ThreatIntelIndicatorTypeMapper } // namespace Model } // namespace SecurityHub } // namespace Aws
36.118056
92
0.636032
curiousjgeorge
ce1f2cc4786ee904811e2ebfb3bbad3b03e85c33
1,245
hpp
C++
include/boost/simd/function/cosd.hpp
yaeldarmon/boost.simd
561316cc54bdc6353ca78f3b6d7e9120acd11144
[ "BSL-1.0" ]
null
null
null
include/boost/simd/function/cosd.hpp
yaeldarmon/boost.simd
561316cc54bdc6353ca78f3b6d7e9120acd11144
[ "BSL-1.0" ]
null
null
null
include/boost/simd/function/cosd.hpp
yaeldarmon/boost.simd
561316cc54bdc6353ca78f3b6d7e9120acd11144
[ "BSL-1.0" ]
null
null
null
//================================================================================================== /*! @file @copyright 2016 NumScale SAS @copyright 2016 J.T. Lapreste Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ //================================================================================================== #ifndef BOOST_SIMD_FUNCTION_COSD_HPP_INCLUDED #define BOOST_SIMD_FUNCTION_COSD_HPP_INCLUDED #if defined(DOXYGEN_ONLY) namespace boost { namespace simd { /*! @ingroup group-trigonometric Function object implementing cosd capabilities cosine of the input in degree. @par Semantic: For every parameter of floating type T @code T r = cosd(x); @endcode is similar to: @code T r = cos(inrad(x)); @endcode As other cosine functions cosd can be used with two parameters as @code T r = cos(x, range_); @endcode see @ref cos for further details @see sincosd, cos, cospi **/ const boost::dispatch::functor<tag::cosd_> cosd = {}; } } #endif #include <boost/simd/function/scalar/cosd.hpp> #include <boost/simd/function/simd/cosd.hpp> #endif
21.465517
100
0.578313
yaeldarmon
ce2158f93c4cbf503350cd1316b4b09ce66e2cfb
2,827
cc
C++
lib/src/facts/linux/disk_resolver.cc
whopper/cfacter
f489f62e19a161e2d909199aebd896e323dac0e8
[ "Apache-2.0" ]
null
null
null
lib/src/facts/linux/disk_resolver.cc
whopper/cfacter
f489f62e19a161e2d909199aebd896e323dac0e8
[ "Apache-2.0" ]
null
null
null
lib/src/facts/linux/disk_resolver.cc
whopper/cfacter
f489f62e19a161e2d909199aebd896e323dac0e8
[ "Apache-2.0" ]
null
null
null
#include <facter/facts/linux/disk_resolver.hpp> #include <facter/logging/logging.hpp> #include <facter/util/file.hpp> #include <facter/util/directory.hpp> #include <boost/lexical_cast.hpp> #include <boost/filesystem.hpp> #include <boost/algorithm/string.hpp> using namespace std; using namespace facter::util; using namespace boost::filesystem; using boost::lexical_cast; using boost::bad_lexical_cast; #ifdef LOG_NAMESPACE #undef LOG_NAMESPACE #endif #define LOG_NAMESPACE "facts.linux.disk" namespace facter { namespace facts { namespace linux { disk_resolver::data disk_resolver::collect_data(collection& facts) { static string root_directory = "/sys/block"; // The size of the block devices is in 512 byte blocks const int block_size = 512; data result; boost::system::error_code ec; if (!is_directory(root_directory, ec)) { LOG_DEBUG("%1%: %2%: disk facts are unavailable.", root_directory, ec.message()); return result; } directory::each_subdirectory(root_directory, [&](string const& dir) { path device_directory(dir); disk d; d.name = device_directory.filename().string(); // Check for the device subdirectory's existence path device_subdirectory = device_directory / "device"; boost::system::error_code ec; if (!is_directory(device_subdirectory, ec)) { return true; } string size_file_path = (device_directory / "size").string(); string vendor_file_path = (device_subdirectory / "vendor").string(); string model_file_path = (device_subdirectory / "model").string(); // Read the size of the block device // The size is in 512 byte blocks if (is_regular_file(size_file_path, ec)) { try { string blocks = file::read(size_file_path); boost::trim(blocks); d.size = lexical_cast<uint64_t>(blocks) * block_size; } catch (bad_lexical_cast& ex) { LOG_DEBUG("size of disk %1% is invalid: size information is unavailable.", d.name); } } // Read the vendor fact if (is_regular_file(vendor_file_path, ec)) { d.vendor = file::read(vendor_file_path); boost::trim(d.vendor); } // Read the model fact if (is_regular_file(model_file_path, ec)) { d.model = file::read(model_file_path); boost::trim(d.model); } result.disks.emplace_back(move(d)); return true; }); return result; } }}} // namespace facter::facts::linux
33.258824
103
0.591793
whopper
ce24fce1b43c0a2a12db333d20be28e760da996f
2,340
cc
C++
libtransport/src/protocols/reassembly.cc
srene/hicn
354f916b5ec7a2b7d63d29d9019fc3e7fa2d1b89
[ "Apache-2.0" ]
47
2019-02-18T13:54:34.000Z
2022-03-03T04:46:50.000Z
libtransport/src/protocols/reassembly.cc
srene/hicn
354f916b5ec7a2b7d63d29d9019fc3e7fa2d1b89
[ "Apache-2.0" ]
1
2019-09-09T09:14:43.000Z
2019-09-09T09:14:43.000Z
libtransport/src/protocols/reassembly.cc
srene/hicn
354f916b5ec7a2b7d63d29d9019fc3e7fa2d1b89
[ "Apache-2.0" ]
28
2019-02-22T17:40:03.000Z
2021-08-18T02:39:40.000Z
/* * Copyright (c) 2017-2019 Cisco and/or its affiliates. * 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 <hicn/transport/interfaces/socket_consumer.h> #include <hicn/transport/utils/array.h> #include <hicn/transport/utils/membuf.h> #include <implementation/socket_consumer.h> #include <protocols/errors.h> #include <protocols/indexer.h> #include <protocols/reassembly.h> namespace transport { namespace protocol { void Reassembly::notifyApplication() { interface::ConsumerSocket::ReadCallback *read_callback = nullptr; reassembly_consumer_socket_->getSocketOption( interface::ConsumerCallbacksOptions::READ_CALLBACK, &read_callback); if (TRANSPORT_EXPECT_FALSE(!read_callback)) { LOG(ERROR) << "Read callback not installed!"; return; } if (read_callback->isBufferMovable()) { // No need to perform an additional copy. The whole buffer will be // tranferred to the application. read_callback->readBufferAvailable(std::move(read_buffer_)); read_buffer_ = utils::MemBuf::create(read_callback->maxBufferSize()); } else { // The buffer will be copied into the application-provided buffer uint8_t *buffer; std::size_t length; std::size_t total_length = read_buffer_->length(); while (read_buffer_->length()) { buffer = nullptr; length = 0; read_callback->getReadBuffer(&buffer, &length); if (!buffer || !length) { throw errors::RuntimeException( "Invalid buffer provided by the application."); } auto to_copy = std::min(read_buffer_->length(), length); std::memcpy(buffer, read_buffer_->data(), to_copy); read_buffer_->trimStart(to_copy); } read_callback->readDataAvailable(total_length); read_buffer_->clear(); } } } // namespace protocol } // namespace transport
32.5
75
0.714103
srene
ce265d5b157d721ebc003a1905e55cfbaa3b5886
7,289
cpp
C++
tests/eig17.cpp
tweber-ill/ill_mirror-takin2-tlibs2
669fd34c306625fd306da278a5b29fb6aae16a87
[ "BSD-3-Clause-Open-MPI" ]
null
null
null
tests/eig17.cpp
tweber-ill/ill_mirror-takin2-tlibs2
669fd34c306625fd306da278a5b29fb6aae16a87
[ "BSD-3-Clause-Open-MPI" ]
null
null
null
tests/eig17.cpp
tweber-ill/ill_mirror-takin2-tlibs2
669fd34c306625fd306da278a5b29fb6aae16a87
[ "BSD-3-Clause-Open-MPI" ]
1
2021-09-20T19:30:13.000Z
2021-09-20T19:30:13.000Z
/** * test eigensystem calculation * @author Tobias Weber <tweber@ill.fr> * @date 11-aug-20 * @license GPLv3, see 'LICENSE' file * * g++ -std=c++17 -DUSE_LAPACK -I.. -I/usr/include/lapacke -Iext/lapacke/include -Lext/lapacke/lib -o eig17 eig17.cpp ../libs/log.cpp -llapacke * * ---------------------------------------------------------------------------- * tlibs * Copyright (C) 2017-2021 Tobias WEBER (Institut Laue-Langevin (ILL), * Grenoble, France). * Copyright (C) 2015-2017 Tobias WEBER (Technische Universitaet Muenchen * (TUM), Garching, Germany). * * 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, version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ---------------------------------------------------------------------------- */ #include <iostream> #include <vector> #include <random> #include "libs/math17.h" using t_real = double; using t_mat = ublas::matrix<t_real>; using t_vec = ublas::vector<t_real>; using t_cplx = std::complex<double>; using t_mat_cplx = ublas::matrix<t_cplx>; using t_vec_cplx = ublas::vector<t_cplx>; std::size_t tst_real() { t_real eps = 1e-4; std::size_t dim = 3; std::mt19937 rndgen{tl2::epoch<unsigned int>()}; std::uniform_real_distribution<t_real> rnddist{-100, 100}; auto mat = tl2::zero_matrix<t_mat>(dim, dim); for(std::size_t i=0; i<dim; ++i) for(std::size_t j=0; j<dim; ++j) mat(i,j) = rnddist(rndgen); std::cout << mat << std::endl; std::vector<t_vec> evecs_re, evecs_im; std::vector<t_real> evals_re, evals_im; std::cout << std::boolalpha << tl2::eigenvec( mat, evecs_re, evecs_im, evals_re, evals_im, false) << std::endl; for(t_real val : evals_re) std::cout << "Re{eval}: " << val << std::endl; for(t_real val : evals_im) std::cout << "Im{eval}: " << val << std::endl; for(const t_vec& vec : evecs_re) std::cout << "Re{evec}: " << vec << std::endl; for(const t_vec& vec : evecs_im) std::cout << "Im{evec}: " << vec << std::endl; t_mat_cplx mat_cplx = tl2::zero_matrix<t_mat_cplx>(dim, dim); for(std::size_t i=0; i<dim; ++i) for(std::size_t j=0; j<dim; ++j) mat_cplx(i,j) = mat(i,j); std::size_t failures = 0; for(std::size_t i=0; i<dim; ++i) { t_cplx eval = t_cplx{evals_re[i], evals_im[i]}; t_vec_cplx evec = tl2::zero_vector<t_vec_cplx>(dim); for(std::size_t j=0; j<dim; ++j) evec[j] = t_cplx{evecs_re[i][j], evecs_im[i][j]}; auto tstvec1 = tl2::prod_mv(mat_cplx, evec); auto tstvec2 = eval * evec; bool is_equal = tl2::vec_equal<t_vec_cplx>(tstvec1, tstvec2, eps); std::cout << tstvec1 << " == " << tstvec2 << ": " << std::boolalpha << is_equal << std::endl; } return failures; } std::size_t tst_cplx() { t_real eps = 1e-4; std::size_t dim = 3; std::mt19937 rndgen{tl2::epoch<unsigned int>()}; std::uniform_real_distribution<t_real> rnddist{-100, 100}; auto mat = tl2::zero_matrix<t_mat_cplx>(dim, dim); for(std::size_t i=0; i<dim; ++i) for(std::size_t j=0; j<dim; ++j) mat(i,j) = rnddist(rndgen) + rnddist(rndgen)*t_cplx{0, 1}; std::cout << mat << std::endl; std::vector<t_vec_cplx> evecs; std::vector<t_cplx> evals; std::cout << std::boolalpha << tl2::eigenvec_cplx(mat, evecs, evals, false) << std::endl; for(const t_cplx& val : evals) std::cout << "eval: " << val << std::endl; for(const t_vec_cplx& vec : evecs) std::cout << "evec: " << vec << std::endl; std::size_t failures = 0; for(std::size_t i=0; i<dim; ++i) { auto tstvec1 = tl2::prod_mv(mat, evecs[i]); auto tstvec2 = evals[i]*evecs[i]; bool is_equal = tl2::vec_equal<t_vec_cplx>(tstvec1, tstvec2, eps); if(!is_equal) ++failures; std::cout << tstvec1 << " == " << tstvec2 << ": " << std::boolalpha << is_equal << std::endl; } return failures; } std::size_t tst_herm() { t_real eps = 1e-4; std::size_t dim = 3; std::mt19937 rndgen{tl2::epoch<unsigned int>()}; std::uniform_real_distribution<t_real> rnddist{-100, 100}; auto mat = tl2::zero_matrix<t_mat_cplx>(dim, dim); for(std::size_t i=0; i<dim; ++i) { for(std::size_t j=i+1; j<dim; ++j) { mat(i,j) = rnddist(rndgen) + rnddist(rndgen)*t_cplx{0, 1}; mat(j,i) = std::conj(mat(i,j)); } } for(std::size_t i=0; i<dim; ++i) mat(i,i) = rnddist(rndgen); std::cout << mat << std::endl; std::vector<t_vec_cplx> evecs; std::vector<t_real> evals; std::cout << std::boolalpha << tl2::eigenvec_herm(mat, evecs, evals, false) << std::endl; for(t_real val : evals) std::cout << "eval: " << val << std::endl; for(const t_vec_cplx& vec : evecs) std::cout << "evec: " << vec << std::endl; std::size_t failures = 0; for(std::size_t i=0; i<dim; ++i) { auto tstvec1 = tl2::prod_mv(mat, evecs[i]); auto tstvec2 = evals[i]*evecs[i]; bool is_equal = tl2::vec_equal<t_vec_cplx>(tstvec1, tstvec2, eps); if(!is_equal) ++failures; std::cout << tstvec1 << " == " << tstvec2 << ": " << std::boolalpha << is_equal << std::endl; } return failures; } std::size_t tst_herm_sel() { t_real eps = 1e-4; std::size_t dim = 3; std::mt19937 rndgen{tl2::epoch<unsigned int>()}; std::uniform_real_distribution<t_real> rnddist{-100, 100}; auto mat = tl2::zero_matrix<t_mat_cplx>(dim, dim); for(std::size_t i=0; i<dim; ++i) { for(std::size_t j=i+1; j<dim; ++j) { mat(i,j) = rnddist(rndgen) + rnddist(rndgen)*t_cplx{0, 1}; mat(j,i) = std::conj(mat(i,j)); } } for(std::size_t i=0; i<dim; ++i) mat(i,i) = rnddist(rndgen); std::cout << mat << std::endl; std::vector<t_vec_cplx> evecs; std::vector<t_real> evals; std::cout << std::boolalpha << tl2::eigenvecsel_herm(mat, evecs, evals, false) << std::endl; for(t_real val : evals) std::cout << "eval: " << val << std::endl; for(const t_vec_cplx& vec : evecs) std::cout << "evec: " << vec << std::endl; std::size_t failures = 0; for(std::size_t i=0; i<dim; ++i) { auto tstvec1 = tl2::prod_mv(mat, evecs[i]); auto tstvec2 = evals[i]*evecs[i]; bool is_equal = tl2::vec_equal<t_vec_cplx>(tstvec1, tstvec2, eps); if(!is_equal) ++failures; std::cout << tstvec1 << " == " << tstvec2 << ": " << std::boolalpha << is_equal << std::endl; } return failures; } int main() { std::cout << "General real matrix" << std::endl; std::size_t failures = tst_real(); std::cerr << "Failures: " << failures << std::endl; std::cout << "\nGeneral complex matrix" << std::endl; failures = tst_cplx(); std::cerr << "Failures: " << failures << std::endl; std::cout << "\nHermitian, selected values" << std::endl; failures = tst_herm_sel(); std::cerr << "Failures: " << failures << std::endl; // there seems to be a bug in lapacke: https://github.com/Reference-LAPACK/lapack/issues/379 std::cout << "\nHermitian" << std::endl; failures = tst_herm(); std::cerr << "Failures: " << failures << std::endl; return 0; }
28.142857
143
0.619289
tweber-ill
ce283973201ba5108e758cca0aa51a144fdc600c
265
cpp
C++
src/CellularAutomaton.cpp
MaxMutantMayer/wolfram_r184
3ba55e4c10f071384dc174d348d0556c4f462688
[ "MIT" ]
null
null
null
src/CellularAutomaton.cpp
MaxMutantMayer/wolfram_r184
3ba55e4c10f071384dc174d348d0556c4f462688
[ "MIT" ]
null
null
null
src/CellularAutomaton.cpp
MaxMutantMayer/wolfram_r184
3ba55e4c10f071384dc174d348d0556c4f462688
[ "MIT" ]
null
null
null
#include "CellularAutomaton.hpp" namespace wolfram_r184 { void CellularAutomaton::Run(size_t numberOfTransitions) { m_grid.Print(); for (size_t i = 0; i < numberOfTransitions; ++i) { m_grid.DoTransition(); m_grid.Print(); } } } // namespace wolfram_r184
15.588235
55
0.716981
MaxMutantMayer
ce2c7ea712fd98560f0c8e134724ce51a127449b
83
hh
C++
build/ARM/mem/protocol/RubyRequest.hh
zhoushuxin/impl_of_HPCA2018
594d807fb0c0712bb7766122c4efe3321d012687
[ "BSD-3-Clause" ]
5
2019-12-12T16:26:09.000Z
2022-03-17T03:23:33.000Z
build/ARM/mem/protocol/RubyRequest.hh
zhoushuxin/impl_of_HPCA2018
594d807fb0c0712bb7766122c4efe3321d012687
[ "BSD-3-Clause" ]
null
null
null
build/ARM/mem/protocol/RubyRequest.hh
zhoushuxin/impl_of_HPCA2018
594d807fb0c0712bb7766122c4efe3321d012687
[ "BSD-3-Clause" ]
null
null
null
#include "/home/zhoushuxin/gem5/build/ARM/mem/ruby/slicc_interface/RubyRequest.hh"
41.5
82
0.819277
zhoushuxin
ce2fc881c4d515e083889d7e9da3efd08a10a089
644
hh
C++
include/syslog_interface.hh
Quicr/qmedia
96408d740bf35e6a845f61c40cc9f9ff859a9955
[ "BSD-2-Clause" ]
null
null
null
include/syslog_interface.hh
Quicr/qmedia
96408d740bf35e6a845f61c40cc9f9ff859a9955
[ "BSD-2-Clause" ]
1
2021-12-29T03:37:51.000Z
2022-03-16T05:59:11.000Z
include/syslog_interface.hh
Quicr/qmedia
96408d740bf35e6a845f61c40cc9f9ff859a9955
[ "BSD-2-Clause" ]
null
null
null
#pragma once #ifndef _WIN32 #include <syslog.h> #endif // Syslog interface declaration class SyslogInterface { public: virtual ~SyslogInterface() {} virtual void openlog(const char *ident, int option, int facility) { #ifndef _WIN32 ::openlog(ident, option, facility); #endif } virtual void closelog(void) { #ifndef _WIN32 ::closelog(); #endif } // Note: C++ will now allow the following to be a virtual function template <typename... Args> void syslog(int priority, const char *format, Args... args) { #ifndef _WIN32 ::syslog(priority, format, args...); #endif } };
17.405405
70
0.639752
Quicr
ce38e66ec453c1b9b786c930fe9d41526d651ec4
477
cpp
C++
test/stdio/input.cpp
UnknownBugs/UEFIWrapper
113d24ac414fe5ab6c782b908779508d279b7a6d
[ "MIT" ]
1
2022-01-23T19:08:21.000Z
2022-01-23T19:08:21.000Z
test/stdio/input.cpp
UnknownBugs/UEFIWrapper
113d24ac414fe5ab6c782b908779508d279b7a6d
[ "MIT" ]
6
2021-12-15T10:36:48.000Z
2022-03-14T12:56:16.000Z
test/stdio/input.cpp
UnknownBugs/UEFIWrapper
113d24ac414fe5ab6c782b908779508d279b7a6d
[ "MIT" ]
null
null
null
#include <UEFIWrapper.hpp> using namespace UEFIWrapper; extern "C" void efi_main(void *ImageHandle __attribute__((unused)), SystemTable::ESystemTable *systemTable) { SystemTable::init(systemTable); SystemTable::clearScreen(); IO::Output cout; cout.init(); IO::Input cin; cin.init(); cout << " Test GetChar --> " << IO::endl; char c; int cnt = 0; while (cin >> c && c != 'q') { cout << c << " ; cnt = " << cnt++ << IO::endl; } }
22.714286
93
0.584906
UnknownBugs
ce3caa949ff81bfad09a00f052c4ea0f4449a4bd
1,677
cpp
C++
cpp/struct_lua.cpp
zsuzuki/structbuilder
d39508f39413e3ffecc2a22ef0b7a8ba142a915c
[ "MIT" ]
null
null
null
cpp/struct_lua.cpp
zsuzuki/structbuilder
d39508f39413e3ffecc2a22ef0b7a8ba142a915c
[ "MIT" ]
null
null
null
cpp/struct_lua.cpp
zsuzuki/structbuilder
d39508f39413e3ffecc2a22ef0b7a8ba142a915c
[ "MIT" ]
null
null
null
// // this file is auto generated // by structbuilder<https://github.com/zsuzuki/structbuilder> // #include <sol/sol.hpp> #include "struct.hpp" namespace Sample { void Test::setLUA(sol::state& lua) { lua.new_usertype<Note>( "TestNote", "page", &Note::page, "line", &Note::line, "copyFrom", &Note::copyFrom); lua.new_usertype<Child>( "TestChild", "age", sol::property(&Child::getAge, &Child::setAge), "step", sol::property(&Child::getStep, &Child::setStep), "name", &Child::name, "copyFrom", &Child::copyFrom); lua.new_usertype<Entry>( "TestEntry", "name", &Entry::name, "country", &Entry::country, "point", &Entry::point, "wins", &Entry::wins, "copyFrom", &Entry::copyFrom); lua.new_usertype<Test>( "Test", "index", sol::property(&Test::getIndex, &Test::setIndex), "beer_type", sol::property(&Test::getBeerType, &Test::setBeerType), "generation", sol::property(&Test::getGeneration, &Test::setGeneration), "enabled", sol::property(&Test::getEnabled, &Test::setEnabled), "count", &Test::count, "max_speed", &Test::max_speed, "ranking", &Test::ranking, "line", &Test::line, "line2", &Test::line2, "note", &Test::note, "child", &Test::child, "entry_list", &Test::entry_list, "copyFrom", &Test::copyFrom); sol::table t_BeerType = lua.create_table_with(); t_BeerType["Ales"] = (int)BeerType::Ales; t_BeerType["Larger"] = (int)BeerType::Larger; t_BeerType["Pilsner"] = (int)BeerType::Pilsner; t_BeerType["Lambic"] = (int)BeerType::Lambic; t_BeerType["IPA"] = (int)BeerType::IPA; lua["Test"]["BeerType"] = t_BeerType; } } // namespace Sample
29.946429
76
0.633274
zsuzuki
ce46d6a16f3f7d626fe10599769888eff7990fda
10,235
cpp
C++
python/geometry/geometry.cpp
AKreutz/bark
46c01339172b978fabc37aedebb7a67b7fa04449
[ "MIT" ]
null
null
null
python/geometry/geometry.cpp
AKreutz/bark
46c01339172b978fabc37aedebb7a67b7fa04449
[ "MIT" ]
null
null
null
python/geometry/geometry.cpp
AKreutz/bark
46c01339172b978fabc37aedebb7a67b7fa04449
[ "MIT" ]
null
null
null
// Copyright (c) 2019 fortiss GmbH, Julian Bernhard, Klemens Esterle, Patrick Hart, Tobias Kessler // // This work is licensed under the terms of the MIT license. // For a copy, see <https://opensource.org/licenses/MIT>. #include <vector> #include "geometry.hpp" #include "modules/geometry/geometry.hpp" namespace py = pybind11; // using namespace modules; // using namespace modules::commons; // using namespace modules::geometry; void python_standard_shapes(py::module m) { m.def("CarLimousine", &modules::geometry::standard_shapes::CarLimousine); } void python_geometry(py::module m) { py::class_<modules::geometry::Point2d>(m, "Point2d") .def(py::init<float, float>()) .def("__repr__", [](const modules::geometry::Point2d &p) { return modules::geometry::print(p); }) .def("x", [](modules::geometry::Point2d &p) { return p.get<0>(); }) .def("y", [](modules::geometry::Point2d &p) { return p.get<1>(); }) .def(py::pickle( [](const modules::geometry::Point2d& p) { // __getstate__ /* Return a tuple that fully encodes the state of the object */ return py::make_tuple(p.get<0>(), p.get<1>()); }, [](py::tuple t) { // __setstate__ if (t.size() != 2) throw std::runtime_error("Invalid point state!"); return modules::geometry::Point2d(t[0].cast<float>(), t[1].cast<float>()); })); m.def("distance", py::overload_cast<const modules::geometry::Point2d &, const modules::geometry::Point2d &>(&modules::geometry::distance), "Returns euclidean distance between two modules::geometry::Point2d."); m.def("distance", py::overload_cast<const modules::geometry::Line &, const modules::geometry::Point2d &>(&modules::geometry::distance), "Returns euclidean distance between modules::geometry::Line2d and modules::geometry::Point2d."); m.def("distance", py::overload_cast<const modules::geometry::Line &, const modules::geometry::Line &>(&modules::geometry::distance), "Returns euclidean distance between modules::geometry::Line2d and modules::geometry::Point2d."); m.def("distance", py::overload_cast<const modules::geometry::Polygon &, const modules::geometry::Polygon &>(&modules::geometry::distance), "Returns euclidean distance between polygon and polygon."); m.def("distance", py::overload_cast<const modules::geometry::Polygon &, const modules::geometry::Line &>(&modules::geometry::distance), "Returns euclidean distance between polygon and line2d."); m.def("distance", py::overload_cast<const modules::geometry::Polygon &, const modules::geometry::Point2d &>(&modules::geometry::distance), "Returns euclidean distance between polygon and point2d."); m.def("get_nearest_point", &modules::geometry::get_nearest_point, "get the nearest point from point to a line."); m.def("get_nearest_s", &modules::geometry::get_nearest_s, "get the nearest s value from point to a line."); m.def("get_point_at_s", &modules::geometry::get_point_at_s, "get the Point2d at position s of the line"); m.def("get_tangent_angle_at_s", &modules::geometry::get_tangent_angle_at_s, "get the angle at position s of the line"); m.def("get_nearest_point_and_s", &modules::geometry::get_nearest_point_and_s, "get the point nearest to another point and its position on the line s "); m.def("get_line_from_s_interval", &modules::geometry::get_line_from_s_interval, "get line between specified interval."); m.def("merge_bounding_boxes", &modules::geometry::merge_bounding_boxes<modules::geometry::Point2d>, "merge two bounding boxes consisting of pairs of min and max corners"); m.def("compute_center_line", &modules::geometry::ComputeCenterLine, "computes the center line."); py::class_<modules::geometry::Line, std::shared_ptr<modules::geometry::Line>>(m, "Line2d") .def(py::init<>(), "Create empty line") .def("addPoint", &modules::geometry::Line::add_point, "add a point") .def("addPoint", [](modules::geometry::Line &line, py::list list) { if (list.size() != 2) { printf("Error: List size of two required."); return; } line.add_point(modules::geometry::Point2d(list[0].cast<float>(), list[1].cast<float>())); }) .def("__repr__", [](const modules::geometry::Line &l) { std::stringstream ss; ss << "<bark.Line2d> Points: "; ss << l.ShapeToString(); return ss.str(); }) .def("toArray", &modules::geometry::Line::toArray, "returns numpy array.") .def("valid", &modules::geometry::Line::Valid, "checks if line is valid.") .def("rotate", &modules::geometry::Line::rotate, "rotates object around center point.") .def("translate", &modules::geometry::Line::translate, "translates object.") .def("transform", &modules::geometry::Line::transform, "translates and rotates object.") .def("length", &modules::geometry::Line::length, "calculates length of line.") .def("reverse", &modules::geometry::Line::reverse, "reverse linestring in place") .def("append_linestring", &modules::geometry::Line::append_linestring, "append linestrings in place") .def("concatenate_linestring", &modules::geometry::Line::ConcatenateLinestring, "concatenate linestrings in place") .def_property_readonly("bounding_box", &modules::geometry::Line::bounding_box) .def_readwrite("center", &modules::geometry::Line::center_, "center point.") .def(py::pickle( [](const modules::geometry::Line& l) -> py::tuple { // __getstate__ /* Return a tuple that fully encodes the state of the object */ return py::make_tuple(l.toArray()); }, [](const py::tuple& t) { // __setstate__ if (t.size() != 1) throw std::runtime_error("Invalid line state!"); modules::geometry::Line l; auto points = t[0].cast<Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic>>(); for(int i = 0; i < points.rows(); ++i) { l.add_point(modules::geometry::Point2d(points(i,0), points(i,1))); } return l; })); py::class_<modules::geometry::Polygon, std::shared_ptr<modules::geometry::Polygon>>(m, "Polygon2d") .def(py::init<>(), "Create empty polygon") .def(py::init<modules::geometry::Pose, std::vector<modules::geometry::Point2d>>(), "Create polygon with center point and point list") .def(py::init<modules::geometry::Pose, const Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> &>(), "Create polygon with center point and point list") .def(py::init<modules::geometry::Pose, const modules::geometry::Line&>(), "Create polygon with center point and line enclosing polygon") .def("addPoint", &modules::geometry::Polygon::add_point, "add a point") .def("addPoint", [](modules::geometry::Polygon &polygon, py::list list) { if (list.size() != 2) { printf("Error: List size of two required."); return; } polygon.add_point(modules::geometry::Point2d(list[0].cast<float>(), list[1].cast<float>())); }) .def("__repr__", [](const modules::geometry::Polygon &p) { std::stringstream ss; ss << "<bark.Polygon2d> Points: "; ss << p.ShapeToString(); return ss.str(); }) .def("toArray", &modules::geometry::Polygon::toArray, "returns numpy array") .def("valid", &modules::geometry::Polygon::Valid, "checks if polygong is valid.") .def("rotate", &modules::geometry::Polygon::rotate, "rotates object around center point.") .def("translate", &modules::geometry::Polygon::translate, "translates center point.") .def("transform", &modules::geometry::Polygon::transform, "translates and rotates object.") .def_readonly("center", &modules::geometry::Polygon::center_, "center point.") .def_readonly("right_dist", &modules::geometry::Polygon::right_dist_, "center point.") .def_readonly("left_dist", &modules::geometry::Polygon::left_dist_, "center point.") .def_readonly("front_dist", &modules::geometry::Polygon::front_dist_, "center point.") .def_readonly("rear_dist", &modules::geometry::Polygon::rear_dist_, "center point.") .def_property_readonly("bounding_box", &modules::geometry::Polygon::bounding_box) .def(py::pickle( [](const modules::geometry::Polygon& p) -> py::tuple { // __getstate__ /* Return a tuple that fully encodes the state of the object */ return py::make_tuple(p.toArray(), p.center_); }, [](py::tuple &t) { // __setstate__ if (t.size() != 2) throw std::runtime_error("Invalid point state!"); modules::geometry::Polygon p; auto points = t[0].cast<Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic>>(); for(int i = 0; i < points.rows(); ++i) { p.add_point(modules::geometry::Point2d(points(i,0), points(i,1))); } p.center_ = t[1].cast<modules::geometry::Pose>(); return p; })); python_standard_shapes(m.def_submodule("standard_shapes", "Define several standard car, pedestrians,... shapes")); py::class_<modules::geometry::Model3D>(m, "Model3d") .def(py::init<>(), "Create none 3d model") .def(py::init<modules::geometry::Model3D::Type>(), "Create 3D model with specific type ") .def_property_readonly("type",&modules::geometry::Model3D::get_type); py::enum_<modules::geometry::Model3D::Type>(m, "modules::geometry::Model3DType", py::arithmetic()) .value("NONE", modules::geometry::Model3D::Type::NONE) .value("ROAD", modules::geometry::Model3D::Type::ROAD) .value("LIMOUSINE", modules::geometry::Model3D::Type::LIMOUSINE) .value("PEDESTRIAN", modules::geometry::Model3D::Type::PEDESTRIAN) .export_values(); }
52.219388
140
0.628334
AKreutz
ce4809a1702f0a39840c7ef71068dbc90c66a199
30,379
cpp
C++
src/Shape.cpp
Felipeasg/heekscad
0b70cbeb998e864b1ea0af0685863f5a90da1504
[ "BSD-3-Clause" ]
2
2019-09-15T15:22:32.000Z
2021-01-22T10:20:42.000Z
src/Shape.cpp
Felipeasg/HeeksCAD
0b70cbeb998e864b1ea0af0685863f5a90da1504
[ "BSD-3-Clause" ]
null
null
null
src/Shape.cpp
Felipeasg/HeeksCAD
0b70cbeb998e864b1ea0af0685863f5a90da1504
[ "BSD-3-Clause" ]
null
null
null
// Shape.cpp // Copyright (c) 2009, Dan Heeks // This program is released under the BSD license. See the file COPYING for details. #include "stdafx.h" #include "Shape.h" #include "Solid.h" #include "Wire.h" #include "Group.h" #include "Face.h" #include "Edge.h" #include "Vertex.h" #include "Loop.h" #include "Cylinder.h" #include "Cuboid.h" #include "Sphere.h" #include "Cone.h" #include "HeeksFrame.h" #include "MarkedList.h" #include "../interface/Tool.h" #include "HeeksConfig.h" #include "../interface/MarkedObject.h" #include "../interface/PropertyDouble.h" #include "../interface/PropertyVertex.h" #include "../interface/PropertyCheck.h" #include <locale.h> #include <BRepBuilderAPI_MakeSolid.hxx> // static member variable bool CShape::m_solids_found = false; CShape::CShape():m_face_gl_list(0), m_edge_gl_list(0), m_opacity(1.0), m_title(_T("")), m_color(0, 0, 0), m_picked_face(NULL), m_volume_found(false) { Init(); } CShape::CShape(const TopoDS_Shape &shape, const wxChar* title, const HeeksColor& col, float opacity):m_face_gl_list(0), m_edge_gl_list(0), m_shape(shape), m_opacity(opacity), m_title(title), m_color(col), m_picked_face(NULL), m_volume_found(false) { Init(); } CShape::CShape(const CShape& s):m_face_gl_list(0), m_edge_gl_list(0), m_picked_face(NULL), m_volume_found(false) { // the faces, edges, vertices children are not copied, because we don't need them for copies in the undo engine m_faces = NULL; m_edges = NULL; m_vertices = NULL; operator=(s); } CShape::~CShape() { KillGLLists(); delete_faces_and_edges(); } const CShape& CShape::operator=(const CShape& s) { HeeksObj::operator = (s); // don't copy id delete_faces_and_edges(); m_box = s.m_box; m_shape = s.m_shape; m_title = s.m_title; m_color = s.m_color; m_creation_time = s.m_creation_time; m_opacity = s.m_opacity; m_volume_found = s.m_volume_found; if(m_volume_found)m_volume = s.m_volume; KillGLLists(); return *this; } bool CShape::IsDifferent(HeeksObj* other) { CShape* shape = (CShape*)other; if(shape->m_color.COLORREF_color() != m_color.COLORREF_color() || shape->m_title.CompareTo(m_title)) return true; if(m_creation_time != shape->m_creation_time) return true; return false; // don't check all the faces and edges ( m_creation_time should be enough ) return ObjList::IsDifferent(other); } void CShape::Init() { m_creation_time = wxGetLocalTimeMillis(); m_faces = new CFaceList; m_edges = new CEdgeList; m_vertices = new CVertexList; Add(m_faces, NULL); Add(m_edges, NULL); Add(m_vertices, NULL); create_faces_and_edges(); } void CShape::KillGLLists() { if (m_face_gl_list) { glDeleteLists(m_face_gl_list, 1); m_face_gl_list = 0; } if (m_edge_gl_list) { glDeleteLists(m_edge_gl_list, 1); m_edge_gl_list = 0; } m_box = CBox(); if(m_faces) { for(HeeksObj* object = m_faces->GetFirstChild(); object; object = m_faces->GetNextChild()) { CFace* f = (CFace*)object; f->KillMarkingGLList(); } } } void CShape::create_faces_and_edges() { if(m_faces == NULL) { m_faces = new CFaceList; m_edges = new CEdgeList; m_vertices = new CVertexList; Add(m_faces, NULL); Add(m_edges, NULL); Add(m_vertices, NULL); } CreateFacesAndEdges(m_shape, m_faces, m_edges, m_vertices); m_creation_time = wxGetLocalTimeMillis(); } void CShape::delete_faces_and_edges() { if(m_faces)m_faces->Clear(); if(m_edges)m_edges->Clear(); if(m_vertices)m_vertices->Clear(); } void CShape::CallMesh() { double pixels_per_mm = wxGetApp().GetPixelScale(); BRepTools::Clean(m_shape); //BRepMesh::Mesh(m_shape, 1/pixels_per_mm); BRepMesh_IncrementalMesh(m_shape, 1/pixels_per_mm); } void CShape::glCommands(bool select, bool marked, bool no_color) { bool mesh_called = false; bool draw_faces = (wxGetApp().m_solid_view_mode == SolidViewFacesAndEdges || wxGetApp().m_solid_view_mode == SolidViewFacesOnly); bool draw_edges = (wxGetApp().m_solid_view_mode == SolidViewFacesAndEdges || wxGetApp().m_solid_view_mode == SolidViewEdgesOnly); if(draw_faces) { for(HeeksObj* object = m_faces->GetFirstChild(); object; object = m_faces->GetNextChild()) { CFace* f = (CFace*)object; f->MakeSureMarkingGLListExists(); } if(!m_face_gl_list) { if(!mesh_called) { CallMesh(); mesh_called = true; } // make the display list m_face_gl_list = glGenLists(1); glNewList(m_face_gl_list, GL_COMPILE); // render all the faces m_faces->glCommands(true, marked, no_color); glEndList(); } // update faces marking display list GLint currentListIndex; glGetIntegerv(GL_LIST_INDEX, &currentListIndex); if(currentListIndex == 0){ for(HeeksObj* object = m_faces->GetFirstChild(); object; object = m_faces->GetNextChild()) { CFace* f = (CFace*)object; f->UpdateMarkingGLList(wxGetApp().m_marked_list->ObjectMarked(f)); } } } if(draw_edges && !m_edge_gl_list) { if(!mesh_called) { CallMesh(); mesh_called = true; } // make the display list m_edge_gl_list = glGenLists(1); glNewList(m_edge_gl_list, GL_COMPILE); // render all the edges m_edges->glCommands(true, marked, no_color); // render all the vertices m_vertices->glCommands(true, false, false); glEndList(); } if(draw_faces && m_face_gl_list) { // draw the face display list glEnable(GL_LIGHTING); glShadeModel(GL_SMOOTH); glCallList(m_face_gl_list); glDisable(GL_LIGHTING); glShadeModel(GL_FLAT); } { // turn off transparency glDisable(GL_BLEND); glDepthMask(1); } if(draw_edges && m_edge_gl_list) { // draw the edge display list glCallList(m_edge_gl_list); } } void CShape::GetBox(CBox &box) { if(!m_box.m_valid) { if(m_faces == NULL)create_faces_and_edges(); BRepTools::Clean(m_shape); //BRepMesh::Mesh(m_shape, 1.0); BRepMesh_IncrementalMesh(m_shape, 1.0); if(m_faces)m_faces->GetBox(m_box); } box.Insert(m_box); } static CShape* shape_for_tools = NULL; class OffsetShapeTool:public Tool{ public: // Tool's virtual functions void Run(){ double offset_value = 2.0; HeeksConfig config; config.Read(_T("OffsetShapeValue"), &offset_value); if(wxGetApp().InputLength(_("Enter Offset Value, + for making bigger, - for making smaller"), _("Offset value"), offset_value)) { try { TopoDS_Shape new_shape = BRepOffsetAPI_MakeOffsetShape(shape_for_tools->Shape(), offset_value, wxGetApp().m_geom_tol); #ifdef TESTNEWSHAPE //This will end up throwing 90% of the exceptions caused by a bad offset BRepTools::Clean(new_shape); //BRepMesh::Mesh(new_shape, 1.0); BRepMesh_IncrementalMesh(new_shape, 1.0); #endif HeeksObj* new_object = CShape::MakeObject(new_shape, _("Result of 'Offset Shape'"), SOLID_TYPE_UNKNOWN, shape_for_tools->m_color, shape_for_tools->GetOpacity()); shape_for_tools->HEEKSOBJ_OWNER->Add(new_object, NULL); shape_for_tools->HEEKSOBJ_OWNER->Remove(shape_for_tools); config.Write(_T("OffsetShapeValue"), offset_value); } catch (Standard_Failure) { Handle_Standard_Failure e = Standard_Failure::Caught(); wxMessageBox(wxString(_("Error making offset")) + _T(": ") + Ctt(e->GetMessageString())); } } } const wxChar* GetTitle(){ return _("Offset Shape");} wxString BitmapPath(){return _T("offsetsolid");} }; static OffsetShapeTool offset_shape_tool; void CShape::GetTools(std::list<Tool*>* t_list, const wxPoint* p) { shape_for_tools = this; if(!wxGetApp().m_no_creation_mode)t_list->push_back(&offset_shape_tool); } void CShape::MakeTransformedShape(const gp_Trsf &mat) { BRepBuilderAPI_Transform myBRepTransformation(m_shape,mat); m_shape = myBRepTransformation.Shape(); } wxString CShape::StretchedName() { return _("Stretched Shape"); } void CShape::ModifyByMatrix(const double* m){ gp_Trsf mat = make_matrix(m); if(IsMatrixDifferentialScale(mat)) { gp_GTrsf gm(mat); BRepBuilderAPI_GTransform t(m_shape, gm); m_shape = t.Shape(); } else { MakeTransformedShape(mat); } delete_faces_and_edges(); KillGLLists(); create_faces_and_edges(); } void CShape::OnEditString(const wxChar* str){ m_title.assign(str); } // static member function HeeksObj* CShape::MakeObject(const TopoDS_Shape &shape, const wxChar* title, SolidTypeEnum solid_type, const HeeksColor& col, float opacity){ if(shape.IsNull())return NULL; switch(shape.ShapeType()){ case TopAbs_FACE: { return new CFace(TopoDS::Face(shape)); } case TopAbs_WIRE: { return new CWire(TopoDS::Wire(shape), title); } case TopAbs_EDGE: { return new CEdge(TopoDS::Edge(shape)); } case TopAbs_VERTEX: return NULL; case TopAbs_COMPOUND: case TopAbs_COMPSOLID: case TopAbs_SOLID: case TopAbs_SHELL: case TopAbs_SHAPE: { switch(solid_type) { case SOLID_TYPE_SPHERE: return new CSphere(*((TopoDS_Solid*)(&shape)), title, col, opacity); case SOLID_TYPE_CYLINDER: return new CCylinder(*((TopoDS_Solid*)(&shape)), title, col, opacity); case SOLID_TYPE_CUBOID: return new CCuboid(*((TopoDS_Solid*)(&shape)), title, col, opacity); case SOLID_TYPE_CONE: return new CCone(*((TopoDS_Solid*)(&shape)), title, col, opacity); default: // check there are some faces if(TopExp_Explorer(shape, TopAbs_FACE).More()) return new CSolid(*((TopoDS_Solid*)(&shape)), title, col, opacity); return NULL; } } } return NULL; } static bool Cut(const std::list<TopoDS_Shape> &shapes, TopoDS_Shape& new_shape){ if(shapes.size() < 2)return false; try { std::list<TopoDS_Shape>::const_iterator It = shapes.begin(); TopoDS_Shape current_shape = *It; It++; while(It != shapes.end()) { const TopoDS_Shape &cutting_shape = *It; current_shape = BRepAlgoAPI_Cut(current_shape, cutting_shape); It++; } new_shape = current_shape; return true; } catch (Standard_Failure) { Handle_Standard_Failure e = Standard_Failure::Caught(); wxMessageBox(wxString(_("Error with cut operation")) + _T(": ") + Ctt(e->GetMessageString())); return false; } } static HeeksObj* Fuse(HeeksObj* s1, HeeksObj* s2){ try { TopoDS_Shape sh1, sh2; TopoDS_Shape new_shape; if(wxGetApp().useOldFuse)new_shape = BRepAlgo_Fuse(((CShape*)s1)->Shape(), ((CShape*)s2)->Shape()); else new_shape = BRepAlgoAPI_Fuse(((CShape*)s1)->Shape(), ((CShape*)s2)->Shape()); HeeksObj* new_object = CShape::MakeObject(new_shape, _("Result of Fuse Operation"), SOLID_TYPE_UNKNOWN, ((CShape*)s1)->m_color, ((CShape*)s1)->GetOpacity()); wxGetApp().Add(new_object, NULL); wxGetApp().Remove(s1); wxGetApp().Remove(s2); return new_object; } catch (Standard_Failure) { Handle_Standard_Failure e = Standard_Failure::Caught(); wxMessageBox(wxString(_("Error with fuse operation")) + _T(": ") + Ctt(e->GetMessageString())); return NULL; } } static HeeksObj* Common(HeeksObj* s1, HeeksObj* s2){ if(s1 == NULL) { wxGetApp().Remove(s2); return NULL; } try { TopoDS_Shape sh1, sh2; TopoDS_Shape new_shape = BRepAlgoAPI_Common(((CShape*)s1)->Shape(), ((CShape*)s2)->Shape()); HeeksObj* new_object = CShape::MakeObject(new_shape, _("Result of Common Operation"), SOLID_TYPE_UNKNOWN, ((CShape*)s1)->m_color, ((CShape*)s1)->GetOpacity()); wxGetApp().Add(new_object, NULL); wxGetApp().Remove(s1); wxGetApp().Remove(s2); return new_object; } catch (Standard_Failure) { Handle_Standard_Failure e = Standard_Failure::Caught(); wxMessageBox(wxString(_("Error with common operation")) + _T(": ") + Ctt(e->GetMessageString())); return NULL; } } CFace* CShape::find(const TopoDS_Face &face) { for(HeeksObj* object = m_faces->GetFirstChild(); object; object = m_faces->GetNextChild()) { CFace* f = (CFace*)object; if(f->Face() == face)return f; } return NULL; } bool CShape::GetExtents(double* extents, const double* orig, const double* xdir, const double* ydir, const double* zdir) { gp_Pnt p_orig(0, 0, 0); if(orig)p_orig = gp_Pnt(orig[0], orig[1], orig[2]); gp_Vec v_x(1, 0, 0); if(xdir)v_x = gp_Vec(xdir[0], xdir[1], xdir[2]); gp_Vec v_y(0, 1, 0); if(ydir)v_y = gp_Vec(ydir[0], ydir[1], ydir[2]); gp_Vec v_z(0, 0, 1); if(zdir)v_z = gp_Vec(zdir[0], zdir[1], zdir[2]); BRepPrimAPI_MakeBox cuboid_plus_x(gp_Ax2(gp_Pnt(p_orig.XYZ() + 2000000 * v_x.XYZ() + (-1000000) * v_z.XYZ() + (-1000000) * v_y.XYZ()), v_x, v_y), 1000000, 1000000, 1000000); BRepPrimAPI_MakeBox cuboid_minus_x(gp_Ax2(gp_Pnt(p_orig.XYZ() + (-2000000) * v_x.XYZ() + (-1000000) * v_z.XYZ() + (-1000000) * v_y.XYZ()), -v_x, v_z), 1000000, 1000000, 1000000); BRepPrimAPI_MakeBox cuboid_plus_y(gp_Ax2(gp_Pnt(p_orig.XYZ() + 2000000 * v_y.XYZ() + (-1000000) * v_z.XYZ() + (-1000000) * v_x.XYZ()), v_y, v_z), 1000000, 1000000, 1000000); BRepPrimAPI_MakeBox cuboid_minus_y(gp_Ax2(gp_Pnt(p_orig.XYZ() + (-2000000) * v_y.XYZ() + (-1000000) * v_z.XYZ() + (-1000000) * v_x.XYZ()), -v_y, v_x), 1000000, 1000000, 1000000); BRepPrimAPI_MakeBox cuboid_plus_z(gp_Ax2(gp_Pnt(p_orig.XYZ() + 2000000 * v_z.XYZ() + (-1000000) * v_x.XYZ() + (-1000000) * v_y.XYZ()), v_z, v_x), 1000000, 1000000, 1000000); BRepPrimAPI_MakeBox cuboid_minus_z(gp_Ax2(gp_Pnt(p_orig.XYZ() + (-2000000) * v_z.XYZ() + (-1000000) * v_x.XYZ() + (-1000000) * v_y.XYZ()), -v_z, v_y), 1000000, 1000000, 1000000); gp_Vec v_orig(p_orig.XYZ()); TopoDS_Solid shape[6] = { cuboid_minus_x, cuboid_minus_y, cuboid_minus_z, cuboid_plus_x, cuboid_plus_y, cuboid_plus_z }; gp_Vec vector[6] = { v_x, v_y, v_z, v_x, v_y, v_z }; for(int i = 0; i<6; i++){ BRepExtrema_DistShapeShape extrema(m_shape, shape[i]); extrema.Perform(); gp_Pnt p = extrema.PointOnShape1(1); gp_Vec v(p.XYZ()); double dp = v * vector[i]; double dp_o = v_orig * vector[i]; extents[i] = dp - dp_o; } return true; } void CShape::CopyIDsFrom(const CShape* shape_from) { SetID(shape_from->m_id); HeeksObj* face_from = shape_from->m_faces->GetFirstChild(); for(HeeksObj* face_to = m_faces->GetFirstChild(); face_from && face_to; face_from = shape_from->m_faces->GetNextChild(), face_to = m_faces->GetNextChild()) { face_to->SetID(face_from->m_id); } HeeksObj* edge_from = shape_from->m_edges->GetFirstChild(); for(HeeksObj* edge_to = m_edges->GetFirstChild(); edge_from && edge_to; edge_from = shape_from->m_edges->GetNextChild(), edge_to = m_edges->GetNextChild()) { edge_to->SetID(edge_from->m_id); } HeeksObj* v_from = shape_from->m_vertices->GetFirstChild(); for(HeeksObj* v_to = m_vertices->GetFirstChild(); v_from && v_to; v_from = shape_from->m_vertices->GetNextChild(), v_to = m_vertices->GetNextChild()) { v_to->SetID(v_from->m_id); } } HeeksObj* CShape::CutShapes(std::list<HeeksObj*> &list_in, bool dodelete) { if(list_in.front()->GetType() == GroupType) { CGroup* group = (CGroup*)list_in.front(); CGroup* newgroup = new CGroup(); group->HEEKSOBJ_OWNER->Add(newgroup,NULL); std::list<HeeksObj*> children; HeeksObj* child = group->GetFirstChild(); while(child) { children.push_back(child); child = group->GetNextChild(); } std::list<HeeksObj*>::iterator iter = children.begin(); while(iter != children.end()) { std::list<HeeksObj*> newlist; std::list<HeeksObj*>::const_iterator it = list_in.begin(); while(it!=list_in.end()) { newlist.push_back(*it); ++it; } newlist.pop_front(); newlist.push_front(*iter); HeeksObj* newshape = CutShapes(newlist,false); newshape->HEEKSOBJ_OWNER->Remove(newshape); newgroup->Add(newshape,NULL); ++iter; } group->HEEKSOBJ_OWNER->Remove(group); wxGetApp().Remove(list_in); return newgroup; } // subtract from the first one in the list all the others std::list<TopoDS_Shape> shapes; std::list<HeeksObj*> delete_list; HeeksObj* first_solid = NULL; for(std::list<HeeksObj*>::const_iterator It = list_in.begin(); It != list_in.end(); It++){ HeeksObj* object = *It; if(object->GetType() == SolidType) { shapes.push_back(((CSolid*)object)->Shape()); if(first_solid == NULL)first_solid = object; delete_list.push_back(object); } else if(object->GetType() == FaceType) { shapes.push_back(((CFace*)object)->Face()); if(first_solid == NULL)first_solid = object; delete_list.push_back(object); } } TopoDS_Shape new_shape; if(Cut(shapes, new_shape)) { HeeksObj* new_object = CShape::MakeObject(new_shape, _("Result of Cut Operation"), SOLID_TYPE_UNKNOWN, ((CShape*)first_solid)->m_color, ((CShape*)first_solid)->m_opacity); wxGetApp().Add(new_object, NULL); if(dodelete) { wxGetApp().Remove(delete_list); wxGetApp().Repaint(); } return new_object; } return first_solid; } HeeksObj* CShape::FuseShapes(std::list<HeeksObj*> &list_in) { // fuse with the first one in the list all the others HeeksObj* s1 = NULL; std::list<HeeksObj*> list = list_in; for(std::list<HeeksObj*>::const_iterator It = list.begin(); It != list.end(); It++){ HeeksObj* object = *It; if(object->GetType() == SolidType || object->GetType() == FaceType) { if(s1 == NULL)s1 = object; else{ s1 = Fuse(s1, object); } } } wxGetApp().Repaint(); return s1; } HeeksObj* CShape::CommonShapes(std::list<HeeksObj*> &list_in) { // find common solid ( intersect ) with the first one in the list all the others HeeksObj* s1 = NULL; bool s1_set = false; std::list<HeeksObj*> list = list_in; for(std::list<HeeksObj*>::const_iterator It = list.begin(); It != list.end(); It++){ HeeksObj* object = *It; if(object->GetType() == SolidType || object->GetType() == FaceType) { if(!s1_set) { s1 = object; s1_set = true; } else{ s1 = Common(s1, object); } } } wxGetApp().Repaint(); return s1; } void CShape::FilletOrChamferEdges(std::list<HeeksObj*> &list, double radius, bool chamfer_not_fillet) { // make a map with a list of edges for each solid std::map< HeeksObj*, std::list< HeeksObj* > > solid_edge_map; for(std::list<HeeksObj*>::const_iterator It = list.begin(); It != list.end(); It++){ HeeksObj* edge = *It; if(edge->GetType() == EdgeType) { HeeksObj* solid = edge->HEEKSOBJ_OWNER->HEEKSOBJ_OWNER; if(solid && solid->GetType() == SolidType) { std::map< HeeksObj*, std::list< HeeksObj* > >::iterator FindIt = solid_edge_map.find(solid); if(FindIt == solid_edge_map.end()) { std::list< HeeksObj* > empty_list; solid_edge_map.insert( make_pair(solid, empty_list) ); FindIt = solid_edge_map.find(solid); } std::list< HeeksObj* > &list = FindIt->second; list.push_back(edge); } } } // do each solid for(std::map< HeeksObj*, std::list< HeeksObj* > >::iterator It = solid_edge_map.begin(); It != solid_edge_map.end(); It++) { HeeksObj* solid = It->first; std::list< HeeksObj* > &list = It->second; try{ if(chamfer_not_fillet) { BRepFilletAPI_MakeChamfer chamfer(((CShape*)solid)->Shape()); for(std::list< HeeksObj* >::iterator It2 = list.begin(); It2 != list.end(); It2++) { CEdge* edge = (CEdge*)(*It2); for(CFace* face = (CFace*)(edge->GetFirstFace()); face; face = (CFace*)(edge->GetNextFace())) { chamfer.Add(radius, TopoDS::Edge(edge->Edge()), TopoDS::Face(face->Face())); } } TopoDS_Shape new_shape = chamfer.Shape(); wxGetApp().Add(new CSolid(*((TopoDS_Solid*)(&new_shape)), _("Solid with edge blend"), *(solid->GetColor()), ((CShape*)solid)->m_opacity), NULL); wxGetApp().Remove(solid); } else { BRepFilletAPI_MakeFillet fillet(((CShape*)solid)->Shape()); for(std::list< HeeksObj* >::iterator It2 = list.begin(); It2 != list.end(); It2++) { fillet.Add(radius, TopoDS::Edge(((CEdge*)(*It2))->Edge())); } TopoDS_Shape new_shape = fillet.Shape(); wxGetApp().Add(new CSolid(*((TopoDS_Solid*)(&new_shape)), _("Solid with edge blend"), *(solid->GetColor()), ((CShape*)solid)->m_opacity), NULL); wxGetApp().Remove(solid); } } catch (Standard_Failure) { Handle_Standard_Failure e = Standard_Failure::Caught(); wxMessageBox(wxString(_("Error making fillet")) + _T(": ") + Ctt(e->GetMessageString())); } catch(...) { wxMessageBox(_("A fatal error happened during Blend")); } } wxGetApp().Repaint(); } static double GetVolume(TopoDS_Shape shape) // http://www.opencascade.org/org/forum/thread_15471/ { GProp_GProps System; BRepGProp::VolumeProperties(shape, System); return System.Mass(); } bool CShape::ImportSolidsFile(const wxChar* filepath, std::map<int, CShapeData> *index_map, HeeksObj* paste_into) { // only allow paste of solids at top level or to groups if(paste_into && paste_into->GetType() != GroupType)return false; // returns true, if suffix handled wxString wf(filepath); HeeksObj* add_to = &wxGetApp(); if(paste_into)add_to = paste_into; if(wf.EndsWith(_T(".stp")) || wf.EndsWith(_T(".STP")) || wf.EndsWith(_T(".step")) || wf.EndsWith(_T(".STEP"))) { char oldlocale[1000]; strcpy(oldlocale, setlocale(LC_NUMERIC, "C")); Standard_CString aFileName = (Standard_CString) (Ttc(filepath)); STEPControl_Reader Reader; int status = Reader.ReadFile( aFileName ); if ( status == IFSelect_RetDone ) { int num = Reader.NbRootsForTransfer(); for(int i = 1; i<=num; i++) { Handle_Standard_Transient root = Reader.RootForTransfer(i); Reader.TransferEntity(root); TopoDS_Shape rShape = Reader.Shape(i); if(index_map) { // change the id ( and any other data ), to the one in the step file index std::map<int, CShapeData>::iterator FindIt = index_map->find(i); if(FindIt != index_map->end()) { CShapeData& shape_data = FindIt->second; HeeksObj* new_object = MakeObject(rShape, _("STEP solid"), shape_data.m_solid_type, HeeksColor(191, 191, 191), 1.0f); if(new_object) { add_to->Add(new_object, NULL); shape_data.SetShape((CShape*)new_object); } } } else { HeeksObj* new_object = MakeObject(rShape, _("STEP solid"), SOLID_TYPE_UNKNOWN, HeeksColor(191, 191, 191), 1.0f); add_to->Add(new_object, NULL); } } } else{ wxMessageBox(_("STEP import not done!")); } setlocale(LC_NUMERIC, oldlocale); return true; } else if(wf.EndsWith(_T(".igs")) || wf.EndsWith(_T(".IGS")) || wf.EndsWith(_T(".iges")) || wf.EndsWith(_T(".IGES"))) { char oldlocale[1000]; strcpy(oldlocale, setlocale(LC_NUMERIC, "C")); Standard_CString aFileName = (Standard_CString) (Ttc(filepath)); // //#ifdef WIN32 //#ifdef UNICODE // // if the const char* filename is different to the original unicode filename, then copy the file to a temporary file with a simple name // if(stricmp(Ctt(aFileName), filepath)) // { // wxStandardPaths standard_paths; // wxFileName path( standard_paths.GetTempDir().c_str(), _("temp_iges.igs")); // copy_file; // to do // m_backup_file_name = path.GetFullPath(); //#endif //#endif IGESControl_Reader Reader; int status = Reader.ReadFile( aFileName ); if ( status == IFSelect_RetDone ) { int num = Reader.NbRootsForTransfer(); for(int i = 1; i<=num; i++) { Handle_Standard_Transient root = Reader.RootForTransfer(i); Reader.TransferEntity(root); TopoDS_Shape rShape = Reader.Shape(i); int shapes_added_for_sewing = 0; BRepOffsetAPI_Sewing face_sewing (0.001); for (TopExp_Explorer explorer(rShape, TopAbs_FACE); explorer.More(); explorer.Next()) { face_sewing.Add (explorer.Current()); shapes_added_for_sewing++; } bool sewed_shape_added = false; try{ if(shapes_added_for_sewing > 0) { face_sewing.Perform (); if(!face_sewing.SewedShape().IsNull()) { BRepBuilderAPI_MakeSolid solid_maker; solid_maker.Add(TopoDS::Shell(face_sewing.SewedShape())); TopoDS_Shape solid = solid_maker.Solid(); if (GetVolume(solid) < 0.0) solid.Reverse(); HeeksObj* new_object = MakeObject(solid, _("sewed IGES solid"), SOLID_TYPE_UNKNOWN, HeeksColor(191, 191, 191), 1.0f); add_to->Add(new_object, NULL); sewed_shape_added = true; } } } catch(...) { } if(!sewed_shape_added) { // add the original HeeksObj* new_object = MakeObject(rShape, _("IGES shape"), SOLID_TYPE_UNKNOWN, HeeksColor(191, 191, 191), 1.0f); add_to->Add(new_object, NULL); } } } else{ wxMessageBox(_("IGES import not done!")); } setlocale(LC_NUMERIC, oldlocale); return true; } else if(wf.EndsWith(_T(".brep")) || wf.EndsWith(_T(".BREP"))) { char oldlocale[1000]; strcpy(oldlocale, setlocale(LC_NUMERIC, "C")); TopoDS_Shape shape; BRep_Builder builder; Standard_Boolean result = BRepTools::Read( shape,(char *) Ttc(filepath), builder ); if(result) { HeeksObj* new_object = MakeObject(shape, _("BREP solid"), SOLID_TYPE_UNKNOWN, HeeksColor(191, 191, 191), 1.0f); add_to->Add(new_object, NULL); } else{ wxMessageBox(_("STEP import not done!")); } setlocale(LC_NUMERIC, oldlocale); return true; } return false; } static void WriteShapeOrGroup(STEPControl_Writer &writer, HeeksObj* object, std::map<int, CShapeData> *index_map, int &i) { if(CShape::IsTypeAShape(object->GetType())){ if(index_map)index_map->insert( std::pair<int, CShapeData>(i, CShapeData((CShape*)object)) ); i++; writer.Transfer(((CSolid*)object)->Shape(), STEPControl_AsIs); } if(object->GetType() == GroupType) { for(HeeksObj* o = object->GetFirstChild(); o; o = object->GetNextChild()) { WriteShapeOrGroup(writer, o, index_map, i); } } } bool CShape::ExportSolidsFile(const std::list<HeeksObj*>& objects, const wxChar* filepath, std::map<int, CShapeData> *index_map) { // returns true, if suffix handled wxString wf(filepath); wf.LowerCase(); if(wf.EndsWith(_T(".stp")) || wf.EndsWith(_T(".step"))) { char oldlocale[1000]; strcpy(oldlocale, setlocale(LC_NUMERIC, "C")); Standard_CString aFileName = (Standard_CString) (Ttc(filepath)); STEPControl_Writer writer; // add all the solids int i = 1; for(std::list<HeeksObj*>::const_iterator It = objects.begin(); It != objects.end(); It++) { HeeksObj* object = *It; WriteShapeOrGroup(writer, object, index_map, i); } writer.Write(aFileName); setlocale(LC_NUMERIC, oldlocale); return true; } else if(wf.EndsWith(_T(".igs")) || wf.EndsWith(_T(".iges"))) { char oldlocale[1000]; strcpy(oldlocale, setlocale(LC_NUMERIC, "C")); Standard_CString aFileName = (Standard_CString) (Ttc(filepath)); IGESControl_Controller::Init(); IGESControl_Writer writer; // add all the solids for(std::list<HeeksObj*>::const_iterator It = objects.begin(); It != objects.end(); It++) { HeeksObj* object = *It; if(CShape::IsTypeAShape(object->GetType())){ writer.AddShape(((CShape*)object)->Shape()); } else if(object->GetType() == WireType){ writer.AddShape(((CWire*)object)->Shape()); } } writer.Write(aFileName); setlocale(LC_NUMERIC, oldlocale); return true; } else if(wf.EndsWith(_T(".brep"))) { #ifdef __WXMSW__ ofstream ofs(filepath); #else ofstream ofs(Ttc(filepath)); #endif for(std::list<HeeksObj*>::const_iterator It = objects.begin(); It != objects.end(); It++) { HeeksObj* object = *It; if(CShape::IsTypeAShape(object->GetType())){ BRepTools::Write(((CShape*)object)->Shape(), ofs); } } } return false; } void CShape::GetTriangles(void(*callbackfunc)(const double* x, const double* n), double cusp, bool just_one_average_normal){ BRepTools::Clean(m_shape); //BRepMesh::Mesh(m_shape, cusp); BRepMesh_IncrementalMesh(m_shape, cusp); return ObjList::GetTriangles(callbackfunc, cusp, just_one_average_normal); } double CShape::Area()const{ double area = 0.0; for(HeeksObj* object = m_faces->GetFirstChild(); object; object = m_faces->GetNextChild()) { CFace* f = (CFace*)object; area += f->Area(); } return area; } // static member function bool CShape::IsTypeAShape(int t){ switch(t){ case SolidType: case WireType: return true; default: return false; } } // static bool CShape::IsMatrixDifferentialScale(const gp_Trsf& trsf) { double scalex = gp_Vec(1, 0, 0).Transformed(trsf).Magnitude(); double scaley = gp_Vec(0, 1, 0).Transformed(trsf).Magnitude(); double scalez = gp_Vec(0, 0, 1).Transformed(trsf).Magnitude(); if(fabs(scalex - scaley) > 0.000000000001)return true; if(fabs(scalex - scalez) > 0.000000000001)return true; return false; } void CShape::CopyFrom(const HeeksObj* object) { *this = *((CShape*)object); } void CShape::WriteXML(TiXmlNode *root) { CShape::m_solids_found = true; } void CShape::SetClickMarkPoint(MarkedObject* marked_object, const double* ray_start, const double* ray_direction) { // set picked face m_picked_face = NULL; if(marked_object->m_map.size() > 0) { MarkedObject* sub_marked_object = marked_object->m_map.begin()->second; if(sub_marked_object) { if(sub_marked_object->m_map.size() > 0) { HeeksObj* object = sub_marked_object->m_map.begin()->first; if(object && object->GetType() == FaceType) { m_picked_face = (CFace*)object; } } } } } float CShape::GetOpacity() { return m_opacity; } void CShape::SetOpacity(float opacity) { m_opacity = opacity; if(m_opacity < 0.0)m_opacity = 0.0f; if(m_opacity > 1.0)m_opacity = 1.0f; } static void on_set_opacity(double value, HeeksObj* object){ ((CShape*)object)->SetOpacity((float)value); } static void on_calculate_volume(bool value, HeeksObj* object){ ((CShape*)object)->CalculateVolumeAndCentre(); wxGetApp().m_frame->RefreshProperties(); } void CShape::CalculateVolumeAndCentre() { GProp_GProps System; BRepGProp::VolumeProperties(m_shape, System); m_volume = System.Mass(); m_centre_of_mass = System.CentreOfMass(); m_volume_found = true; } void CShape::GetProperties(std::list<Property *> *list) { list->push_back(new PropertyDouble(_("opacity"), m_opacity, this, on_set_opacity)); if(m_volume_found) { double volume = this->m_volume; volume /= (pow(wxGetApp().m_view_units, 3)); // convert volume to cubic units list->push_back(new PropertyDouble(_("volume"), volume, this)); double p[3]; extract(m_centre_of_mass, p); list->push_back(new PropertyVertex(_("centre of gravity"), p, this)); } else { list->push_back(new PropertyCheck(_("calculate volume"), false, this, on_calculate_volume)); } ObjList::GetProperties(list); }
27.124107
247
0.681359
Felipeasg
ce483a3d9b411c3e6db008c2ed48ee40d75ce085
7,947
cpp
C++
cpp/source/endpoint/device/actions/RadioCalibAction.cpp
skydiveuas/skydive
6a3ddb20210c7feec93c2124c99a764e91f13701
[ "MIT" ]
2
2017-12-09T22:44:35.000Z
2018-04-08T11:51:53.000Z
cpp/source/endpoint/device/actions/RadioCalibAction.cpp
skydiveuas/skydive
6a3ddb20210c7feec93c2124c99a764e91f13701
[ "MIT" ]
1
2018-04-08T12:15:23.000Z
2018-04-08T12:15:23.000Z
cpp/source/endpoint/device/actions/RadioCalibAction.cpp
skydiveuas/skydive
6a3ddb20210c7feec93c2124c99a764e91f13701
[ "MIT" ]
1
2018-04-08T11:50:43.000Z
2018-04-08T11:50:43.000Z
#include "endpoint/device/actions/RadioCalibAction.hpp" #include "endpoint/device/actions/AppAction.hpp" #include "endpoint/device/PilotEvent.hpp" RadioCalibAction::RadioCalibAction(Listener* const _listener): ISkyDeviceAction(_listener) { state = IDLE; } void RadioCalibAction::start(void) { current = 0; monitor->trace("Calibrate radio procedure requested"); state = INITIAL_COMMAND; sendSignal(SignalData::CALIBRATE_RADIO, SignalData::START); } IMessage::MessageType RadioCalibAction::getExpectedControlMessageType(void) const { return IMessage::CONTROL_DATA; } bool RadioCalibAction::isActionDone(void) const { return IDLE == state; } ISkyDeviceAction::Type RadioCalibAction::getType(void) const { return RADIO_CALIB; } std::string RadioCalibAction::getStateName(void) const { switch (state) { case IDLE: return "IDLE"; case INITIAL_COMMAND: return "INITIAL_COMMAND"; case CALIBRATION_COMMAND: return "CALIBRATION_COMMAND"; case BREAKING: return "BREAKING"; case CHECK: return "CHECK"; case CALIBRATION_RESPONSE: return "CALIBRATION_RESPONSE"; case FINAL_COMMAND: return "FINAL_COMMAND"; case CALIBRATION_RECEPTION: return "CALIBRATION_RECEPTION"; default: throw std::runtime_error("RadioCalibAction::getStateName::Unexpected state"); } } void RadioCalibAction::handleReception(const IMessage& message) { switch (state) { case IDLE: case INITIAL_COMMAND: handleIdleReception(message); break; case FINAL_COMMAND: case CHECK: if (IMessage::CONTROL_DATA == message.getMessageType()) { monitor->notifyDeviceEvent(new DeviceEventReceived(message)); } else { except("Unexpeted message received", message); } break; case CALIBRATION_RECEPTION: if (IMessage::CALIBRATION_SETTINGS == message.getMessageType()) { monitor->trace("Calibration settings received, radio calibration successfull"); monitor->notifyDeviceEvent(new DeviceEventReceived(message)); monitor->notifyDeviceEvent(new DeviceEvent(DeviceEvent::CALIBRATE_RADIO_ENDED)); monitor->notifyDeviceEvent(new DeviceEventMessage(DeviceEventMessage::INFO, "Radio receiver calibration successfull.")); state = IDLE; listener->startAction(new AppAction(listener)); } else { except("Unexpeted message received", message); } break; default: except("Message received in unexpected state", message); } } void RadioCalibAction::handleSignalReception(const Parameter parameter) { switch (state) { case INITIAL_COMMAND: switch (parameter) { case SignalData::ACK: monitor->trace("Calibrate radio procedure started"); monitor->notifyDeviceEvent(new DeviceEvent(DeviceEvent::CALIBRATE_RADIO_STARTED)); state = CALIBRATION_COMMAND; break; case SignalData::NOT_ALLOWED: monitor->trace("Calibrate radio not allowed, breaking"); monitor->notifyDeviceEvent(new DeviceEvent(DeviceEvent::CALIBRATE_RADIO_NOT_ALLOWED)); state = IDLE; listener->startAction(new AppAction(listener)); break; default: except("Unexpected signal parameter message received", parameter); } break; case CALIBRATION_RESPONSE: switch (parameter) { case SignalData::ACK: current++; monitor->trace("Calibrate radio response: ACK, chanel: " + std::to_string(current)); monitor->notifyDeviceEvent(new DeviceEvent(DeviceEvent::CALIBRATE_RADIO_ACK)); if (current >= 8) { monitor->trace("Switching to CHECK"); state = CHECK; } else { state = CALIBRATION_COMMAND; } break; case SignalData::FAIL: monitor->trace("Calibrate radio response: FAIL"); monitor->notifyDeviceEvent(new DeviceEvent(DeviceEvent::CALIBRATE_RADIO_FAIL)); state = CALIBRATION_COMMAND; break; default: except("Unexpected signal parameter message received", parameter); } break; case BREAKING: switch (parameter) { case SignalData::BREAK_ACK: monitor->trace("Radio calibration broken"); monitor->notifyDeviceEvent(new DeviceEvent(DeviceEvent::CALIBRATE_RADIO_ENDED)); state = IDLE; listener->startAction(new AppAction(listener)); break; default: except("Unexpected signal parameter message received", parameter); } break; case FINAL_COMMAND: switch (parameter) { case SignalData::ACK: monitor->trace("Radio calibration final command ACK"); state = CALIBRATION_RECEPTION; initializeSignalPayloadReception(SignalData::CALIBRATION_SETTINGS); break; case SignalData::BREAK_FAIL: monitor->trace("Radio calibration final command FAIL"); monitor->notifyDeviceEvent(new DeviceEvent(DeviceEvent::CALIBRATE_RADIO_ENDED)); monitor->notifyDeviceEvent(new DeviceEventMessage(DeviceEventMessage::WARNING, "Error while safing data to internal memory." "Calibration results discarded.")); state = IDLE; listener->startAction(new AppAction(listener)); break; case SignalData::BREAK_ACK: monitor->trace("Radio calibration final command BREAK_ACK"); monitor->notifyDeviceEvent(new DeviceEvent(DeviceEvent::CALIBRATE_RADIO_ENDED)); monitor->notifyDeviceEvent(new DeviceEventMessage(DeviceEventMessage::INFO, "Calibration results discarded.")); state = IDLE; listener->startAction(new AppAction(listener)); break; default: except("Unexpected signal parameter message received", parameter); } break; default: except("Signal parameter in unexpected state", parameter); } } void RadioCalibAction::handleUserEvent(const PilotEvent& event) { switch (state) { case CALIBRATION_COMMAND: switch (event.getType()) { case PilotEvent::RADIO_CALIBRATION_DONE: state = CALIBRATION_RESPONSE; sendSignal(SignalData::CALIBRATE_RADIO, SignalData::DONE); break; case PilotEvent::RADIO_CALIBRATION_SKIP: state = CALIBRATION_RESPONSE; sendSignal(SignalData::CALIBRATE_RADIO, SignalData::SKIP); break; case PilotEvent::RADIO_CALIBRATION_BREAK: state = BREAKING; sendSignal(SignalData::CALIBRATE_RADIO, SignalData::BREAK); break; default: except("Unexpected user uav event received"); } break; case CHECK: switch (event.getType()) { case PilotEvent::RADIO_CALIBRATION_DONE: state = FINAL_COMMAND; sendSignal(SignalData::CALIBRATE_RADIO, SignalData::BREAK); break; case PilotEvent::RADIO_CALIBRATION_SKIP: state = FINAL_COMMAND; sendSignal(SignalData::CALIBRATE_RADIO, SignalData::BREAK_FAIL); break; default: except("Unexpected user uav event received"); } break; default: except("Uav event received at unexpected state"); } }
31.287402
107
0.611929
skydiveuas
ce4d75add058bf131018217162ac1086de6b73e0
5,953
cpp
C++
NorthstarDedicatedTest/hooks.cpp
connieprice/NorthstarLauncher
9ede30f65e0c0a43fec711c7476c8e91c5ebbbb0
[ "MIT" ]
null
null
null
NorthstarDedicatedTest/hooks.cpp
connieprice/NorthstarLauncher
9ede30f65e0c0a43fec711c7476c8e91c5ebbbb0
[ "MIT" ]
null
null
null
NorthstarDedicatedTest/hooks.cpp
connieprice/NorthstarLauncher
9ede30f65e0c0a43fec711c7476c8e91c5ebbbb0
[ "MIT" ]
null
null
null
#include "pch.h" #include "hooks.h" #include "hookutils.h" #include "sigscanning.h" #include <wchar.h> #include <iostream> #include <vector> #include <fstream> #include <sstream> #include <filesystem> #include <Psapi.h> typedef LPSTR(*GetCommandLineAType)(); LPSTR GetCommandLineAHook(); typedef HMODULE(*LoadLibraryExAType)(LPCSTR lpLibFileName, HANDLE hFile, DWORD dwFlags); HMODULE LoadLibraryExAHook(LPCSTR lpLibFileName, HANDLE hFile, DWORD dwFlags); typedef HMODULE(*LoadLibraryAType)(LPCSTR lpLibFileName); HMODULE LoadLibraryAHook(LPCSTR lpLibFileName); typedef HMODULE(*LoadLibraryExWType)(LPCWSTR lpLibFileName, HANDLE hFile, DWORD dwFlags); HMODULE LoadLibraryExWHook(LPCWSTR lpLibFileName, HANDLE hFile, DWORD dwFlags); typedef HMODULE(*LoadLibraryWType)(LPCWSTR lpLibFileName); HMODULE LoadLibraryWHook(LPCWSTR lpLibFileName); GetCommandLineAType GetCommandLineAOriginal; LoadLibraryExAType LoadLibraryExAOriginal; LoadLibraryAType LoadLibraryAOriginal; LoadLibraryExWType LoadLibraryExWOriginal; LoadLibraryWType LoadLibraryWOriginal; void InstallInitialHooks() { if (MH_Initialize() != MH_OK) spdlog::error("MH_Initialize failed"); HookEnabler hook; ENABLER_CREATEHOOK(hook, &GetCommandLineA, &GetCommandLineAHook, reinterpret_cast<LPVOID*>(&GetCommandLineAOriginal)); ENABLER_CREATEHOOK(hook, &LoadLibraryExA, &LoadLibraryExAHook, reinterpret_cast<LPVOID*>(&LoadLibraryExAOriginal)); ENABLER_CREATEHOOK(hook, &LoadLibraryA, &LoadLibraryAHook, reinterpret_cast<LPVOID*>(&LoadLibraryAOriginal)); ENABLER_CREATEHOOK(hook, &LoadLibraryExW, &LoadLibraryExWHook, reinterpret_cast<LPVOID*>(&LoadLibraryExWOriginal)); ENABLER_CREATEHOOK(hook, &LoadLibraryW, &LoadLibraryWHook, reinterpret_cast<LPVOID*>(&LoadLibraryWOriginal)); } LPSTR GetCommandLineAHook() { static char* cmdlineModified; static char* cmdlineOrg; if (cmdlineOrg == nullptr || cmdlineModified == nullptr) { cmdlineOrg = GetCommandLineAOriginal(); bool isDedi = strstr(cmdlineOrg, "-dedicated"); // well, this one has to be a real argument std::string args; std::ifstream cmdlineArgFile; // it looks like CommandLine() prioritizes parameters apprearing first, so we want the real commandline to take priority // not to mention that cmdlineOrg starts with the EXE path args.append(cmdlineOrg); args.append(" "); // append those from the file cmdlineArgFile = std::ifstream(!isDedi ? "ns_startup_args.txt" : "ns_startup_args_dedi.txt"); if (cmdlineArgFile) { std::stringstream argBuffer; argBuffer << cmdlineArgFile.rdbuf(); cmdlineArgFile.close(); args.append(argBuffer.str()); } auto len = args.length(); cmdlineModified = new char[len + 1]; if (!cmdlineModified) { spdlog::error("malloc failed for command line"); return cmdlineOrg; } memcpy(cmdlineModified, args.c_str(), len + 1); spdlog::info("Command line: {}", cmdlineModified); } return cmdlineModified; } // dll load callback stuff // this allows for code to register callbacks to be run as soon as a dll is loaded, mainly to allow for patches to be made on dll load struct DllLoadCallback { std::string dll; DllLoadCallbackFuncType callback; bool called; }; std::vector<DllLoadCallback*> dllLoadCallbacks; void AddDllLoadCallback(std::string dll, DllLoadCallbackFuncType callback) { DllLoadCallback* callbackStruct = new DllLoadCallback; callbackStruct->dll = dll; callbackStruct->callback = callback; callbackStruct->called = false; dllLoadCallbacks.push_back(callbackStruct); } void CallLoadLibraryACallbacks(LPCSTR lpLibFileName, HMODULE moduleAddress) { for (auto& callbackStruct : dllLoadCallbacks) { if (!callbackStruct->called && strstr(lpLibFileName + (strlen(lpLibFileName) - callbackStruct->dll.length()), callbackStruct->dll.c_str()) != nullptr) { callbackStruct->callback(moduleAddress); callbackStruct->called = true; } } } void CallLoadLibraryWCallbacks(LPCWSTR lpLibFileName, HMODULE moduleAddress) { for (auto& callbackStruct : dllLoadCallbacks) { std::wstring wcharStrDll = std::wstring(callbackStruct->dll.begin(), callbackStruct->dll.end()); const wchar_t* callbackDll = wcharStrDll.c_str(); if (!callbackStruct->called && wcsstr(lpLibFileName + (wcslen(lpLibFileName) - wcharStrDll.length()), callbackDll) != nullptr) { callbackStruct->callback(moduleAddress); callbackStruct->called = true; } } } void CallAllPendingDLLLoadCallbacks() { HMODULE hMods[1024]; HANDLE hProcess = GetCurrentProcess(); DWORD cbNeeded; unsigned int i; // Get a list of all the modules in this process. if (EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded)) { for (i = 0; i < (cbNeeded / sizeof(HMODULE)); i++) { wchar_t szModName[MAX_PATH]; // Get the full path to the module's file. if (GetModuleFileNameExW(hProcess, hMods[i], szModName, sizeof(szModName) / sizeof(TCHAR))) { CallLoadLibraryWCallbacks(szModName, hMods[i]); } } } } HMODULE LoadLibraryExAHook(LPCSTR lpLibFileName, HANDLE hFile, DWORD dwFlags) { HMODULE moduleAddress = LoadLibraryExAOriginal(lpLibFileName, hFile, dwFlags); if (moduleAddress) { CallLoadLibraryACallbacks(lpLibFileName, moduleAddress); } return moduleAddress; } HMODULE LoadLibraryAHook(LPCSTR lpLibFileName) { HMODULE moduleAddress = LoadLibraryAOriginal(lpLibFileName); if (moduleAddress) { CallLoadLibraryACallbacks(lpLibFileName, moduleAddress); } return moduleAddress; } HMODULE LoadLibraryExWHook(LPCWSTR lpLibFileName, HANDLE hFile, DWORD dwFlags) { HMODULE moduleAddress = LoadLibraryExWOriginal(lpLibFileName, hFile, dwFlags); if (moduleAddress) { CallLoadLibraryWCallbacks(lpLibFileName, moduleAddress); } return moduleAddress; } HMODULE LoadLibraryWHook(LPCWSTR lpLibFileName) { HMODULE moduleAddress = LoadLibraryWOriginal(lpLibFileName); if (moduleAddress) { CallLoadLibraryWCallbacks(lpLibFileName, moduleAddress); } return moduleAddress; }
28.347619
152
0.767848
connieprice
ce554d43ad550908b31398c8b3f8fdad0d5ef726
7,942
cpp
C++
src/engine/audio/private/VBRHeader.cpp
DeadZoneLuna/csso-src
6c978ea304ee2df3796bc9c0d2916bac550050d5
[ "Unlicense" ]
4
2021-10-03T05:16:55.000Z
2021-12-28T16:49:27.000Z
src/engine/audio/private/VBRHeader.cpp
cafeed28/what
08e51d077f0eae50afe3b592543ffa07538126f5
[ "Unlicense" ]
null
null
null
src/engine/audio/private/VBRHeader.cpp
cafeed28/what
08e51d077f0eae50afe3b592543ffa07538126f5
[ "Unlicense" ]
3
2022-02-02T18:09:58.000Z
2022-03-06T18:54:39.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // //============================================================================= #include "audio_pch.h" #include "tier0/platform.h" #include "MPAFile.h" // also includes vbrheader.h #include "tier0/dbg.h" #ifndef MAKEFOURCC #define MAKEFOURCC(ch0, ch1, ch2, ch3) \ ((uint32)(BYTE)(ch0) | ((uint32)(BYTE)(ch1) << 8) | \ ((uint32)(BYTE)(ch2) << 16) | ((uint32)(BYTE)(ch3) << 24 )) #endif //defined(MAKEFOURCC) // XING Header offset: 1. index = lsf, 2. index = mono uint32 CVBRHeader::m_dwXINGOffsets[2][2] = { // MPEG 1 (not mono, mono) { 32 + MPA_HEADER_SIZE, 17 + MPA_HEADER_SIZE }, // MPEG 2/2.5 { 17 + MPA_HEADER_SIZE, 9 + MPA_HEADER_SIZE } }; // first test with this static method, if it does exist bool CVBRHeader::IsVBRHeaderAvailable( CMPAFile* pMPAFile, VBRHeaderType& HeaderType, uint32& dwOffset ) { Assert(pMPAFile); // where does VBR header begin (XING) uint32 dwNewOffset = dwOffset + m_dwXINGOffsets[pMPAFile->m_pMPAHeader->IsLSF()][pMPAFile->m_pMPAHeader->IsMono()]; // check for XING header first if( CheckXING( pMPAFile, dwNewOffset ) ) { HeaderType = XINGHeader; // seek offset back to header begin dwOffset = dwNewOffset - 4; return true; } // VBRI header always at fixed offset dwNewOffset = dwOffset + 32 + MPA_HEADER_SIZE; if( CheckVBRI( pMPAFile, dwNewOffset ) ) { HeaderType = VBRIHeader; // seek offset back to header begin dwOffset = dwNewOffset - 4; return true; } HeaderType = NoHeader; return false; } CVBRHeader::CVBRHeader( CMPAFile* pMPAFile, VBRHeaderType HeaderType, uint32 dwOffset ) : m_pMPAFile( pMPAFile ), m_pnToc(NULL), m_HeaderType( HeaderType ), m_dwOffset(dwOffset), m_dwFrames(0), m_dwBytes(0) { switch( m_HeaderType ) { case NoHeader: // no Header found throw CMPAException( CMPAException::NoVBRHeader, pMPAFile->GetFilename(), NULL, false ); break; case XINGHeader: if( !ExtractXINGHeader( m_dwOffset ) ) throw CMPAException( CMPAException::NoVBRHeader, pMPAFile->GetFilename(), NULL, false ); break; case VBRIHeader: if( !ExtractVBRIHeader( m_dwOffset ) ) throw CMPAException( CMPAException::NoVBRHeader, pMPAFile->GetFilename(), NULL, false ); break; } // calc bitrate if( m_dwBytes > 0 && m_dwFrames > 0 ) { // calc number of seconds m_dwBytesPerSec = m_pMPAFile->m_pMPAHeader->GetBytesPerSecond( m_dwFrames, m_dwBytes ); } else // incomplete header found { throw CMPAException( CMPAException::IncompleteVBRHeader, pMPAFile->GetFilename(), NULL, false ); } } bool CVBRHeader::CheckID( CMPAFile* pMPAFile, char ch0, char ch1, char ch2, char ch3, uint32& dwOffset ) { return ( pMPAFile->ExtractBytes( dwOffset, 4 ) == MAKEFOURCC( ch3, ch2, ch1, ch0 ) ); } bool CVBRHeader::CheckXING( CMPAFile* pMPAFile, uint32& dwOffset ) { // XING ID found? if( !CheckID( pMPAFile, 'X', 'i', 'n', 'g', dwOffset) && !CheckID( pMPAFile, 'I', 'n', 'f', 'o', dwOffset) ) return false; return true; } bool CVBRHeader::CheckVBRI( CMPAFile* pMPAFile, uint32& dwOffset ) { // VBRI ID found? if( !CheckID( pMPAFile, 'V', 'B', 'R', 'I', dwOffset ) ) return false; return true; } // currently not used bool CVBRHeader::ExtractLAMETag( uint32 dwOffset ) { // LAME ID found? if( !CheckID( m_pMPAFile, 'L', 'A', 'M', 'E', dwOffset ) && !CheckID( m_pMPAFile, 'G', 'O', 'G', 'O', dwOffset ) ) return false; return true; } bool CVBRHeader::ExtractXINGHeader( uint32 dwOffset ) { /* XING VBR-Header size description 4 'Xing' or 'Info' 4 flags (indicates which fields are used) 4 frames (optional) 4 bytes (optional) 100 toc (optional) 4 a VBR quality indicator: 0=best 100=worst (optional) */ if( !CheckXING( m_pMPAFile, dwOffset ) ) return false; uint32 dwFlags; // get flags (mandatory in XING header) dwFlags = m_pMPAFile->ExtractBytes( dwOffset, 4 ); // extract total number of frames in file if(dwFlags & FRAMES_FLAG) m_dwFrames = m_pMPAFile->ExtractBytes(dwOffset,4); // extract total number of bytes in file if(dwFlags & BYTES_FLAG) m_dwBytes = m_pMPAFile->ExtractBytes(dwOffset,4); // extract TOC (for more accurate seeking) if (dwFlags & TOC_FLAG) { m_dwTableSize = 100; m_pnToc = new int[m_dwTableSize]; if( m_pnToc ) { for(uint32 i=0;i<m_dwTableSize;i++) m_pnToc[i] = m_pMPAFile->ExtractBytes( dwOffset, 1 ); } } m_dwQuality = (uint32)-1; if(dwFlags & VBR_SCALE_FLAG ) m_dwQuality = m_pMPAFile->ExtractBytes(dwOffset, 4); return true; } bool CVBRHeader::ExtractVBRIHeader( uint32 dwOffset ) { /* FhG VBRI Header size description 4 'VBRI' (ID) 2 version 2 delay 2 quality 4 # bytes 4 # frames 2 table size (for TOC) 2 table scale (for TOC) 2 size of table entry (max. size = 4 byte (must be stored in an integer)) 2 frames per table entry ?? dynamic table consisting out of frames with size 1-4 whole length in table size! (for TOC) */ if( !CheckVBRI( m_pMPAFile, dwOffset ) ) return false; // extract all fields from header (all mandatory) m_dwVersion = m_pMPAFile->ExtractBytes(dwOffset, 2 ); m_fDelay = (float)m_pMPAFile->ExtractBytes(dwOffset, 2 ); m_dwQuality = m_pMPAFile->ExtractBytes(dwOffset, 2 ); m_dwBytes = m_pMPAFile->ExtractBytes(dwOffset, 4 ); m_dwFrames = m_pMPAFile->ExtractBytes(dwOffset, 4 ); m_dwTableSize = m_pMPAFile->ExtractBytes(dwOffset, 2 ) + 1; //!!! m_dwTableScale = m_pMPAFile->ExtractBytes(dwOffset, 2 ); m_dwBytesPerEntry = m_pMPAFile->ExtractBytes(dwOffset, 2 ); m_dwFramesPerEntry = m_pMPAFile->ExtractBytes(dwOffset, 2 ); // extract TOC (for more accurate seeking) m_pnToc = new int[m_dwTableSize]; if( m_pnToc ) { for ( unsigned int i = 0 ; i < m_dwTableSize ; i++) { m_pnToc[i] = m_pMPAFile->ExtractBytes(dwOffset, m_dwBytesPerEntry ); } } return true; } CVBRHeader::~CVBRHeader(void) { if( m_pnToc ) delete[] m_pnToc; } // get byte position for percentage value (fPercent) of file bool CVBRHeader::SeekPoint(float fPercent, uint32& dwSeekPoint) { if( !m_pnToc || m_dwBytes == 0 ) return false; if( fPercent < 0.0f ) fPercent = 0.0f; if( fPercent > 100.0f ) fPercent = 100.0f; switch( m_HeaderType ) { case XINGHeader: dwSeekPoint = SeekPointXING( fPercent ); break; case VBRIHeader: dwSeekPoint = SeekPointVBRI( fPercent ); break; } return true; } uint32 CVBRHeader::SeekPointXING(float fPercent) const { // interpolate in TOC to get file seek point in bytes int a; float fa, fb, fx; a = (int)fPercent; if( a > 99 ) a = 99; fa = (float)m_pnToc[a]; if( a < 99 ) { fb = (float)m_pnToc[a+1]; } else { fb = 256.0f; } fx = fa + (fb-fa)*(fPercent-a); uint32 dwSeekpoint = (int)((1.0f/256.0f)*fx*m_dwBytes); return dwSeekpoint; } uint32 CVBRHeader::SeekPointVBRI(float fPercent) const { return SeekPointByTimeVBRI( (fPercent/100.0f) * m_pMPAFile->m_pMPAHeader->GetLengthSecond( m_dwFrames ) * 1000.0f ); } uint32 CVBRHeader::SeekPointByTimeVBRI(float fEntryTimeMS) const { unsigned int i=0, fraction = 0; uint32 dwSeekPoint = 0; float fLengthMS; float fLengthMSPerTOCEntry; float fAccumulatedTimeMS = 0.0f ; fLengthMS = (float)m_pMPAFile->m_pMPAHeader->GetLengthSecond( m_dwFrames ) * 1000.0f ; fLengthMSPerTOCEntry = fLengthMS / (float)m_dwTableSize; if ( fEntryTimeMS > fLengthMS ) fEntryTimeMS = fLengthMS; while ( fAccumulatedTimeMS <= fEntryTimeMS ) { dwSeekPoint += m_pnToc[i++]; fAccumulatedTimeMS += fLengthMSPerTOCEntry; } // Searched too far; correct result fraction = ( (int)(((( fAccumulatedTimeMS - fEntryTimeMS ) / fLengthMSPerTOCEntry ) + (1.0f/(2.0f*(float)m_dwFramesPerEntry))) * (float)m_dwFramesPerEntry)); dwSeekPoint -= (uint32)((float)m_pnToc[i-1] * (float)(fraction) / (float)m_dwFramesPerEntry); return dwSeekPoint; }
26.039344
117
0.675648
DeadZoneLuna
ce557156af0303d9baa1ae176ec3eb0821f090e6
2,281
cpp
C++
src/pub_main.cpp
shivaang12/beginner_tutorials
e0a5fded4efdd639eae0019e3aa84765d6fa0b8a
[ "MIT" ]
null
null
null
src/pub_main.cpp
shivaang12/beginner_tutorials
e0a5fded4efdd639eae0019e3aa84765d6fa0b8a
[ "MIT" ]
null
null
null
src/pub_main.cpp
shivaang12/beginner_tutorials
e0a5fded4efdd639eae0019e3aa84765d6fa0b8a
[ "MIT" ]
null
null
null
// MIT License // Copyright (c) 2018 Shivang Patel // 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. /** * @file pub_main.cpp * @author Shivang Patel * @copyright MIT License (c) 2018 Shivang Patel * * @brief DESCRIPTION * Main file for the publisher node. Initializes node, initializes the string * being published, starts the server for the service change_text, and publish * the string. * */ #include <string> #include "publisher.hpp" int main(int argc, char **argv) { // Create publisher node ros::init(argc, argv, "publisher"); // Inform that the publisher node is started ROS_INFO_STREAM("Initializing node: publisher..."); // Initiate the string to be published std::string str = "Welcome to ENPM808X, Fall 2018!"; if (argc > 1) { // Initialize the message with string coming from launch file str = argv[1]; } // Node handle for publisher node ros::NodeHandle nh; // Create the Publisher object Publisher pub(str); // Create server for service change_text ros::ServiceServer server = nh.advertiseService("change_text", &Publisher::changeText, &pub); // Inform that service is started ROS_INFO_STREAM("Service started: change_text"); // Publish the message pub.publish(); return 0; }
35.640625
81
0.732573
shivaang12
ce5847dd0f6bdc3ef31495591af5330c413ce013
2,062
cpp
C++
10.02_group_anagrams/group_anagrams.cpp
Mengsen-W/algorithm
66216b8601e416343a2cc191bd0f2f12eb282262
[ "BSD-3-Clause" ]
null
null
null
10.02_group_anagrams/group_anagrams.cpp
Mengsen-W/algorithm
66216b8601e416343a2cc191bd0f2f12eb282262
[ "BSD-3-Clause" ]
null
null
null
10.02_group_anagrams/group_anagrams.cpp
Mengsen-W/algorithm
66216b8601e416343a2cc191bd0f2f12eb282262
[ "BSD-3-Clause" ]
null
null
null
/* * @Date: 2021-07-18 16:52:34 * @Author: Mengsen Wang * @LastEditors: Mengsen Wang * @LastEditTime: 2021-07-18 19:12:49 */ #include <cassert> #include <iostream> #include <numeric> #include <string> #include <unordered_map> #include <vector> using namespace std; class Solution { public: vector<vector<string>> groupAnagrams(vector<string>& strs) { // 自定义对 array<int, 26> 类型的哈希函数 auto arrayHash = [fn = hash<int>{}](const array<int, 26>& arr) -> size_t { return accumulate(arr.begin(), arr.end(), 0u, [&](size_t acc, int num) { return (acc << 1) ^ fn(num); }); }; unordered_map<array<int, 26>, vector<string>, decltype(arrayHash)> mp( 0, arrayHash); for (string& str : strs) { array<int, 26> counts{}; int length = str.length(); for (int i = 0; i < length; ++i) { counts[str[i] - 'a']++; } mp[counts].emplace_back(str); } vector<vector<string>> ans; for (auto it = mp.begin(); it != mp.end(); ++it) { ans.emplace_back(it->second); } return ans; } }; class Solution_2 { public: vector<vector<string>> groupAnagrams(vector<string>& strs) { unordered_map<uint64_t, vector<string>> m; uint64_t pf[26] = {1}, b = 97755331; for (int i = 1; i < 26; ++i) pf[i] = pf[i - 1] * b; for (auto& t : strs) { uint64_t hash = 0; for (char c : t) hash += c * pf[c - 'a']; m[hash].push_back(t); } vector<vector<string>> ans; for (auto& [_, vs] : m) ans.emplace_back(move(vs)); return ans; } }; int main() { { vector<string> strs{"eat", "tea", "tan", "ate", "nat", "bat"}; for (vector<string>& group_str : Solution().groupAnagrams(strs)) { for (string& s : group_str) { cout << s << ", "; } cout << endl; } } { vector<string> strs{"eat", "tea", "tan", "ate", "nat", "bat"}; for (vector<string>& group_str : Solution_2().groupAnagrams(strs)) { for (string& s : group_str) { cout << s << ", "; } cout << endl; } } }
25.45679
78
0.547527
Mengsen-W
ce5a600d3680044118357647e9bcc0f448b20700
6,545
cpp
C++
Trace_yourself_for_fun_and_profit/secret_application.cpp
dermojo/presentations
4f4da0e60c144e735c98bb4c77ce7ccb055bd20b
[ "MIT" ]
3
2017-07-07T13:32:28.000Z
2020-01-09T20:33:02.000Z
Trace_yourself_for_fun_and_profit/secret_application.cpp
dermojo/presentations
4f4da0e60c144e735c98bb4c77ce7ccb055bd20b
[ "MIT" ]
null
null
null
Trace_yourself_for_fun_and_profit/secret_application.cpp
dermojo/presentations
4f4da0e60c144e735c98bb4c77ce7ccb055bd20b
[ "MIT" ]
null
null
null
/** * @file secret_application.cpp * @brief a program that unveils its real functionality only to those who the secret passphrase... */ #include <fstream> #include <iostream> #include <cerrno> #include <cstring> #include <termios.h> #include <unistd.h> #include <sys/prctl.h> #include <sys/ptrace.h> #include <sys/reg.h> #include <sys/syscall.h> #include <sys/wait.h> #include <openssl/sha.h> #include <boost/algorithm/string.hpp> #include "syscalltable.hpp" static bool debug = false; static std::string queryPassphrase() { std::cerr << "Password: "; // get current terminal attributes struct termios tty_attr; if (tcgetattr(STDIN_FILENO, &tty_attr) < 0) throw std::runtime_error("tcgetattr failed: " + std::string(strerror(errno))); // remember the current flags (to restore them later) const tcflag_t c_lflag = tty_attr.c_lflag; // disable echoing tty_attr.c_lflag &= ~ECHO; if (tcsetattr(STDIN_FILENO, 0, &tty_attr) < 0) throw std::runtime_error("tcsetattr failed: " + std::string(strerror(errno))); // now get the passphrase std::string input; std::getline(std::cin, input); std::cerr << "\n"; // restore the terminal's old state tty_attr.c_lflag = c_lflag; if (tcsetattr(STDIN_FILENO, 0, &tty_attr) < 0) throw std::runtime_error("tcsetattr failed: " + std::string(strerror(errno))); return input; } static std::string sha256(const std::string& input) { unsigned char hash[SHA256_DIGEST_LENGTH]; SHA256_CTX sha256; if (SHA256_Init(&sha256) != 1) throw std::runtime_error("SHA256_Init failed!"); if (SHA256_Update(&sha256, input.data(), input.size()) != 1) throw std::runtime_error("SHA256_Update failed!"); if (SHA256_Final(hash, &sha256) != 1) throw std::runtime_error("SHA256_Final failed!"); // turn the binary data into a hex string (so we can print it) return std::string((const char*)hash, sizeof(hash)); } #ifdef CHECK_FOR_DEBUGGER /** * Check if a debugger is attached to this process. * @return @c true if debugged */ static bool isDebuggerAttached() { // this only checks for a tracer *right now*, so this is actually a race condition... // -> use // prctl(PR_SET_DUMPABLE, 0); // to disable tracing first, then the check makes sense... std::ifstream status("/proc/self/status"); std::string line; while (std::getline(status, line)) { if (boost::starts_with(line, "TracerPid:")) { line.erase(0, 10); boost::trim(line); // PID 0 is fine - no-one attached return line != "0"; } } throw std::runtime_error("broken OS!"); } #endif // CHECK_FOR_DEBUGGER #ifdef PTRACE_MYSELF static bool waitForSyscall(const pid_t pid) { while (true) { ptrace(PTRACE_SYSCALL, pid, 0, 0); int status = 0; waitpid(pid, &status, 0); // check for 0x80 in the signal number (set due to PTRACE_O_TRACESYSGOOD) if (WIFSTOPPED(status) && (WSTOPSIG(status) & 0x80)) return true; // process exited? if (WIFEXITED(status)) return false; } } static void startPtrace() { SyscallTable syscallTable; // to be more useful, parse syscall names from the installed headers if (debug) syscallTable.load("/usr/include/x86_64-linux-gnu/asm/unistd_64.h"); // fork of a child process and trace it auto pid = fork(); if (pid < 0) { perror("fork"); exit(1); } if (pid == 0) { // child: allow the parent to start tracing here if (ptrace(PTRACE_TRACEME) == -1) { // this may happen when running under a debugger // (e.g. try "strace -f ./secret_application_trace) std::cerr << "PTRACE_TRACEME failed!!! (" << strerror(errno) << "\n"; exit(-1); } // stop the current process, so that we wait for the parent to start tracing kill(getpid(), SIGSTOP); return; } // parent: wait for the child int status = 0; waitpid(pid, &status, 0); // configure tracing // (1) kill the child when this process exits ptrace(PTRACE_SETOPTIONS, pid, 0, PTRACE_O_EXITKILL); // (2) when the child stops due to a syscall, deliver SIGTRAP|0x80 so that we know ptrace(PTRACE_SETOPTIONS, pid, 0, PTRACE_O_TRACESYSGOOD); if (debug) std::cout << "+++ Starting trace loop\n"; while (true) { // wait for the child's next syscall or its termination if (!waitForSyscall(pid)) break; // determine the syscall by reading the child's EAX (RAX for x86_64) // (the EAX register has been overwritten by the kernel for various reasons, // but there is a backup copy we can use) long syscall = ptrace(PTRACE_PEEKUSER, pid, sizeof(long) * ORIG_RAX); const auto name = syscallTable.getSyscallName(syscall); if (!waitForSyscall(pid)) break; // wait again for the syscall to return long retval = ptrace(PTRACE_PEEKUSER, pid, sizeof(long) * RAX); if (debug) std::cout << "+++ " << name << " returned with rc=" << retval << '\n'; } if (debug) std::cout << "+++ Tracing done\n"; exit(0); } #endif // PTRACE_MYSELF /// SHA256 hash of the secret passphrase ("mellon") static const char passphrase[] = "\x83\x00\x6a\x43\x8f\x94\xda\xf3\xa7\xdd\x9c\x7b\x27\xf7\x0c\x15" "\xe4\x43\xc0\xca\x55\xd5\x8f\xcd\xfa\x76\x89\x9a\xe4\x66\xb4\x55"; /** * Queries the user for a passphrase. * @return @c true if the passphrase is correct */ static bool checkAccess() { // query the password first const std::string input = queryPassphrase(); // hash the password const std::string hash = sha256(input); return hash == std::string(passphrase, sizeof(passphrase) - 1); } static void secretFunc() { std::cout << "You got it!\n"; } int main(int argc, const char** argv) { for (int i = 1; i < argc; ++i) if (strcmp(argv[i], "--debug") == 0) debug = true; #ifdef CHECK_FOR_DEBUGGER if (isDebuggerAttached()) { std::cout << "detected attached debugging tool!\n"; } #endif // CHECK_FOR_DEBUGGER #ifdef PTRACE_MYSELF startPtrace(); #endif // PTRACE_MYSELF if (checkAccess()) secretFunc(); else std::cerr << "Access denied!\n"; return 0; }
27.733051
100
0.613293
dermojo
ce5b7c66bb343ac7aedabf73b77076b8a3d900fb
7,709
hpp
C++
include/UnityEngine/ProBuilder/WingedEdgeEnumerator.hpp
marksteward/BeatSaber-Quest-Codegen
a76f063f71cef207a9f048ad7613835f554911a7
[ "Unlicense" ]
null
null
null
include/UnityEngine/ProBuilder/WingedEdgeEnumerator.hpp
marksteward/BeatSaber-Quest-Codegen
a76f063f71cef207a9f048ad7613835f554911a7
[ "Unlicense" ]
null
null
null
include/UnityEngine/ProBuilder/WingedEdgeEnumerator.hpp
marksteward/BeatSaber-Quest-Codegen
a76f063f71cef207a9f048ad7613835f554911a7
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Including type: System.Collections.Generic.IEnumerator`1 #include "System/Collections/Generic/IEnumerator_1.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: UnityEngine::ProBuilder namespace UnityEngine::ProBuilder { // Forward declaring type: WingedEdge class WingedEdge; } // Completed forward declares // Type namespace: UnityEngine.ProBuilder namespace UnityEngine::ProBuilder { // Size: 0x20 #pragma pack(push, 1) // Autogenerated type: UnityEngine.ProBuilder.WingedEdgeEnumerator // [TokenAttribute] Offset: FFFFFFFF class WingedEdgeEnumerator : public ::Il2CppObject/*, public System::Collections::Generic::IEnumerator_1<UnityEngine::ProBuilder::WingedEdge*>*/ { public: // private UnityEngine.ProBuilder.WingedEdge m_Start // Size: 0x8 // Offset: 0x10 UnityEngine::ProBuilder::WingedEdge* m_Start; // Field size check static_assert(sizeof(UnityEngine::ProBuilder::WingedEdge*) == 0x8); // private UnityEngine.ProBuilder.WingedEdge m_Current // Size: 0x8 // Offset: 0x18 UnityEngine::ProBuilder::WingedEdge* m_Current; // Field size check static_assert(sizeof(UnityEngine::ProBuilder::WingedEdge*) == 0x8); // Creating value type constructor for type: WingedEdgeEnumerator WingedEdgeEnumerator(UnityEngine::ProBuilder::WingedEdge* m_Start_ = {}, UnityEngine::ProBuilder::WingedEdge* m_Current_ = {}) noexcept : m_Start{m_Start_}, m_Current{m_Current_} {} // Creating interface conversion operator: operator System::Collections::Generic::IEnumerator_1<UnityEngine::ProBuilder::WingedEdge*> operator System::Collections::Generic::IEnumerator_1<UnityEngine::ProBuilder::WingedEdge*>() noexcept { return *reinterpret_cast<System::Collections::Generic::IEnumerator_1<UnityEngine::ProBuilder::WingedEdge*>*>(this); } // Get instance field: private UnityEngine.ProBuilder.WingedEdge m_Start UnityEngine::ProBuilder::WingedEdge* _get_m_Start(); // Set instance field: private UnityEngine.ProBuilder.WingedEdge m_Start void _set_m_Start(UnityEngine::ProBuilder::WingedEdge* value); // Get instance field: private UnityEngine.ProBuilder.WingedEdge m_Current UnityEngine::ProBuilder::WingedEdge* _get_m_Current(); // Set instance field: private UnityEngine.ProBuilder.WingedEdge m_Current void _set_m_Current(UnityEngine::ProBuilder::WingedEdge* value); // public UnityEngine.ProBuilder.WingedEdge get_Current() // Offset: 0x1D78848 UnityEngine::ProBuilder::WingedEdge* get_Current(); // private System.Object System.Collections.IEnumerator.get_Current() // Offset: 0x1D84AA4 ::Il2CppObject* System_Collections_IEnumerator_get_Current(); // public System.Void .ctor(UnityEngine.ProBuilder.WingedEdge start) // Offset: 0x1D7881C template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static WingedEdgeEnumerator* New_ctor(UnityEngine::ProBuilder::WingedEdge* start) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::ProBuilder::WingedEdgeEnumerator::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<WingedEdgeEnumerator*, creationType>(start))); } // public System.Boolean MoveNext() // Offset: 0x1D78B28 bool MoveNext(); // public System.Void Reset() // Offset: 0x1D84A9C void Reset(); // public System.Void Dispose() // Offset: 0x1D84AE8 void Dispose(); }; // UnityEngine.ProBuilder.WingedEdgeEnumerator #pragma pack(pop) static check_size<sizeof(WingedEdgeEnumerator), 24 + sizeof(UnityEngine::ProBuilder::WingedEdge*)> __UnityEngine_ProBuilder_WingedEdgeEnumeratorSizeCheck; static_assert(sizeof(WingedEdgeEnumerator) == 0x20); } DEFINE_IL2CPP_ARG_TYPE(UnityEngine::ProBuilder::WingedEdgeEnumerator*, "UnityEngine.ProBuilder", "WingedEdgeEnumerator"); #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: UnityEngine::ProBuilder::WingedEdgeEnumerator::get_Current // Il2CppName: get_Current template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<UnityEngine::ProBuilder::WingedEdge* (UnityEngine::ProBuilder::WingedEdgeEnumerator::*)()>(&UnityEngine::ProBuilder::WingedEdgeEnumerator::get_Current)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::ProBuilder::WingedEdgeEnumerator*), "get_Current", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::ProBuilder::WingedEdgeEnumerator::System_Collections_IEnumerator_get_Current // Il2CppName: System.Collections.IEnumerator.get_Current template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppObject* (UnityEngine::ProBuilder::WingedEdgeEnumerator::*)()>(&UnityEngine::ProBuilder::WingedEdgeEnumerator::System_Collections_IEnumerator_get_Current)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::ProBuilder::WingedEdgeEnumerator*), "System.Collections.IEnumerator.get_Current", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::ProBuilder::WingedEdgeEnumerator::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: UnityEngine::ProBuilder::WingedEdgeEnumerator::MoveNext // Il2CppName: MoveNext template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (UnityEngine::ProBuilder::WingedEdgeEnumerator::*)()>(&UnityEngine::ProBuilder::WingedEdgeEnumerator::MoveNext)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::ProBuilder::WingedEdgeEnumerator*), "MoveNext", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::ProBuilder::WingedEdgeEnumerator::Reset // Il2CppName: Reset template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::ProBuilder::WingedEdgeEnumerator::*)()>(&UnityEngine::ProBuilder::WingedEdgeEnumerator::Reset)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::ProBuilder::WingedEdgeEnumerator*), "Reset", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::ProBuilder::WingedEdgeEnumerator::Dispose // Il2CppName: Dispose template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::ProBuilder::WingedEdgeEnumerator::*)()>(&UnityEngine::ProBuilder::WingedEdgeEnumerator::Dispose)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::ProBuilder::WingedEdgeEnumerator*), "Dispose", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } };
59.75969
234
0.750292
marksteward