text
stringlengths
5
1.04M
//{ #include<bits/stdc++.h> using namespace std; typedef long long ll; typedef double lf; typedef pair<ll,ll> ii; #define REP(i,n) for(ll i=0;i<n;i++) #define REP1(i,n) for(ll i=1;i<=n;i++) #define FILL(i,n) memset(i,n,sizeof i) #define X first #define Y second #define SZ(_a) (int)_a.size() #define ALL(_a) _a.begin(),_a.end() #define pb push_back #ifdef brian #define debug(...) do{\ fprintf(stderr,"%s - %d (%s) = ",__PRETTY_FUNCTION__,__LINE__,#__VA_ARGS__);\ _do(__VA_ARGS__);\ }while(0) template<typename T>void _do(T &&_x){cerr<<_x<<endl;} template<typename T,typename ...S> void _do(T &&_x,S &&..._t){cerr<<_x<<" ,";_do(_t...);} template<typename _a,typename _b> ostream& operator << (ostream &_s,const pair<_a,_b> &_p){return _s<<"("<<_p.X<<","<<_p.Y<<")";} template<typename It> ostream& _OUTC(ostream &_s,It _ita,It _itb) { _s<<"{"; for(It _it=_ita;_it!=_itb;_it++) { _s<<(_it==_ita?"":",")<<*_it; } _s<<"}"; return _s; } template<typename _a> ostream &operator << (ostream &_s,vector<_a> &_c){return _OUTC(_s,ALL(_c));} template<typename _a> ostream &operator << (ostream &_s,set<_a> &_c){return _OUTC(_s,ALL(_c));} template<typename _a,typename _b> ostream &operator << (ostream &_s,map<_a,_b> &_c){return _OUTC(_s,ALL(_c));} template<typename _t> void pary(_t _a,_t _b){_OUTC(cerr,_a,_b);cerr<<endl;} #define IOS() #else #define debug(...) #define pary(...) #define endl '\n' #define IOS() ios_base::sync_with_stdio(0);cin.tie(0); #endif // brian //} const ll MAXn=1e5+5,MAXlg=__lg(MAXn)+2; const ll MOD=1000000007; const ll INF=ll(1e15); ll f(char c) { string S="^>v<"; REP(i,4)if(c==S[i])return i; return 0; } int main() { IOS(); string a,b; ll s,t,n; cin>>a>>b>>n; s=f(a[0]),t=f(b[0]); bool x= (s+n)%4==t,y= (s-n%4+4)%4==t; debug(s,t,x,y); if(!(x^y))cout<<"undefined"<<endl; else if(x)cout<<"cw"<<endl; else cout<<"ccw"<<endl; }
// Copyright (c) 2013-2015 Vittorio Romeo // License: Academic Free License ("AFL") v. 3.0 // AFL License page: http://opensource.org/licenses/AFL-3.0 #ifndef SSVU_CORE_MPL_IMPL_REVERSE #define SSVU_CORE_MPL_IMPL_REVERSE #include "SSVUtils/Core/MPL/Impl/BaseTypes.hpp" namespace ssvu { namespace MPL { namespace Impl { template <typename, typename> struct ReverseHlpr; template <typename T, typename... Ts, typename TR> struct ReverseHlpr<List<T, Ts...>, TR> { using Type = typename ReverseHlpr<List<Ts...>, typename TR::template PushFront<T>>::Type; }; template <typename TR> struct ReverseHlpr<List<>, TR> { using Type = TR; }; template <typename... Ts> using Reverse = typename ReverseHlpr<List<Ts...>, List<>>::Type; } // namespace Impl } // namespace MPL } // namespace ssvu #endif
// Copyright (c) 2014-2018 Daniel Kraft // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <names/main.h> #include <chainparams.h> #include <coins.h> #include <consensus/validation.h> #include <dbwrapper.h> #include <hash.h> #include <names/encoding.h> #include <script/interpreter.h> #include <script/names.h> #include <script/script.h> #include <txmempool.h> #include <undo.h> #include <util.h> #include <utilstrencodings.h> #include <validation.h> #include <univalue.h> namespace { constexpr unsigned MAX_VALUE_LENGTH = 2048; constexpr unsigned MAX_NAME_LENGTH = 256; /* Ensure that the name length fits to the script element size limit to avoid a situation as in Namecoin where names can become unspendable. */ static_assert (MAX_VALUE_LENGTH <= MAX_SCRIPT_ELEMENT_SIZE, "Maximum value size is too large for script element size"); static_assert (MAX_NAME_LENGTH <= MAX_SCRIPT_ELEMENT_SIZE, "Maximum name size is too large for script element size"); } // anonymous namespace /* ************************************************************************** */ /* CNameTxUndo. */ void CNameTxUndo::fromOldState (const valtype& nm, const CCoinsView& view) { name = nm; isNew = !view.GetName (name, oldData); } void CNameTxUndo::apply (CCoinsViewCache& view) const { if (isNew) view.DeleteName (name); else view.SetName (name, oldData, true); } /* ************************************************************************** */ /* CNameMemPool. */ uint256 CNameMemPool::getTxForName (const valtype& name) const { NameTxMap::const_iterator mi; mi = mapNameRegs.find (name); if (mi != mapNameRegs.end ()) { assert (mapNameUpdates.count (name) == 0); return mi->second; } mi = mapNameUpdates.find (name); if (mi != mapNameUpdates.end ()) { assert (mapNameRegs.count (name) == 0); return mi->second; } return uint256 (); } void CNameMemPool::addUnchecked (const uint256& hash, const CTxMemPoolEntry& entry) { AssertLockHeld (pool.cs); if (entry.isNameRegistration ()) { const valtype& name = entry.getName (); assert (mapNameRegs.count (name) == 0); mapNameRegs.insert (std::make_pair (name, hash)); } if (entry.isNameUpdate ()) { const valtype& name = entry.getName (); assert (mapNameUpdates.count (name) == 0); mapNameUpdates.insert (std::make_pair (name, hash)); } } void CNameMemPool::remove (const CTxMemPoolEntry& entry) { AssertLockHeld (pool.cs); if (entry.isNameRegistration ()) { const NameTxMap::iterator mit = mapNameRegs.find (entry.getName ()); assert (mit != mapNameRegs.end ()); mapNameRegs.erase (mit); } if (entry.isNameUpdate ()) { const NameTxMap::iterator mit = mapNameUpdates.find (entry.getName ()); assert (mit != mapNameUpdates.end ()); mapNameUpdates.erase (mit); } } void CNameMemPool::removeConflicts (const CTransaction& tx) { AssertLockHeld (pool.cs); for (const auto& txout : tx.vout) { const CNameScript nameOp(txout.scriptPubKey); if (nameOp.isNameOp () && nameOp.getNameOp () == OP_NAME_REGISTER) { const valtype& name = nameOp.getOpName (); const NameTxMap::const_iterator mit = mapNameRegs.find (name); if (mit != mapNameRegs.end ()) { const CTxMemPool::txiter mit2 = pool.mapTx.find (mit->second); assert (mit2 != pool.mapTx.end ()); pool.removeRecursive (mit2->GetTx (), MemPoolRemovalReason::NAME_CONFLICT); } } } } void CNameMemPool::check (const CCoinsView& coins) const { AssertLockHeld (pool.cs); std::set<valtype> nameRegs; std::set<valtype> nameUpdates; for (const auto& entry : pool.mapTx) { const uint256 txHash = entry.GetTx ().GetHash (); if (entry.isNameRegistration ()) { const valtype& name = entry.getName (); const NameTxMap::const_iterator mit = mapNameRegs.find (name); assert (mit != mapNameRegs.end ()); assert (mit->second == txHash); assert (nameRegs.count (name) == 0); nameRegs.insert (name); /* There should be no existing name. */ CNameData data; assert (!coins.GetName (name, data)); } if (entry.isNameUpdate ()) { const valtype& name = entry.getName (); const NameTxMap::const_iterator mit = mapNameUpdates.find (name); assert (mit != mapNameUpdates.end ()); assert (mit->second == txHash); assert (nameUpdates.count (name) == 0); nameUpdates.insert (name); CNameData data; if (!coins.GetName (name, data)) assert (false); } } assert (nameRegs.size () == mapNameRegs.size ()); assert (nameUpdates.size () == mapNameUpdates.size ()); /* Check that nameRegs and nameUpdates are disjoint. They must be since a name can only be in either category, depending on whether it exists at the moment or not. */ for (const auto& name : nameRegs) assert (nameUpdates.count (name) == 0); for (const auto& name : nameUpdates) assert (nameRegs.count (name) == 0); } bool CNameMemPool::checkTx (const CTransaction& tx) const { AssertLockHeld (pool.cs); /* In principle, multiple name_updates could be performed within the mempool at once (building upon each other). This is disallowed, though, since the current mempool implementation does not like it. (We keep track of only a single update tx for each name.) */ for (const auto& txout : tx.vout) { const CNameScript nameOp(txout.scriptPubKey); if (!nameOp.isNameOp ()) continue; switch (nameOp.getNameOp ()) { case OP_NAME_REGISTER: { const valtype& name = nameOp.getOpName (); if (registersName (name)) return false; break; } case OP_NAME_UPDATE: { const valtype& name = nameOp.getOpName (); if (updatesName (name)) return false; break; } default: assert (false); } } return true; } /* ************************************************************************** */ /* CNameConflictTracker. */ namespace { void ConflictTrackerNotifyEntryRemoved (CNameConflictTracker* tracker, CTransactionRef txRemoved, MemPoolRemovalReason reason) { if (reason == MemPoolRemovalReason::NAME_CONFLICT) tracker->AddConflictedEntry (txRemoved); } } // anonymous namespace CNameConflictTracker::CNameConflictTracker (CTxMemPool &p) : txNameConflicts(std::make_shared<std::vector<CTransactionRef>>()), pool(p) { pool.NotifyEntryRemoved.connect ( boost::bind (&ConflictTrackerNotifyEntryRemoved, this, _1, _2)); } CNameConflictTracker::~CNameConflictTracker () { pool.NotifyEntryRemoved.disconnect ( boost::bind (&ConflictTrackerNotifyEntryRemoved, this, _1, _2)); } void CNameConflictTracker::AddConflictedEntry (CTransactionRef txRemoved) { txNameConflicts->emplace_back (std::move (txRemoved)); } /* ************************************************************************** */ bool IsNameValid (const valtype& name, CValidationState& state) { if (name.size () > MAX_NAME_LENGTH) return state.Invalid (false, REJECT_INVALID, "the name is too long"); /* All names must have a namespace. This means that they must start with some lower-case letters and /. As a regexp, that is: [a-z]+\/.* */ bool foundNamespace = false; for (size_t i = 0; i < name.size (); ++i) { if (name[i] == '/') { if (i == 0) return state.Invalid (false, REJECT_INVALID, "the empty namespace is not valid"); foundNamespace = true; break; } if (name[i] < 'a' || name[i] > 'z') return state.Invalid (false, REJECT_INVALID, "the namespace must only consist of lower-case" " letters"); } if (!foundNamespace) return state.Invalid (false, REJECT_INVALID, "the name has no namespace"); /* Non-printable ASCII characters are not allowed. This check works also for UTF-8 encoded strings, as characters <0x80 are encoded as a single byte and never occur as part of some other UTF-8 sequence. */ for (const unsigned char c : name) if (c < 0x20) return state.Invalid (false, REJECT_INVALID, "non-printable ASCII characters are not allowed" " in names"); /* Only valid UTF-8 strings can be names. */ if (!IsValidUtf8String (std::string (name.begin (), name.end ()))) return state.Invalid (false, REJECT_INVALID, "the name is not valid UTF-8"); return true; } bool IsValueValid (const valtype& value, CValidationState& state) { if (value.size () > MAX_VALUE_LENGTH) return state.Invalid (false, REJECT_INVALID, "the value is too long"); /* The value must parse with Univalue as JSON and be an object. */ UniValue jsonValue; if (!jsonValue.read (std::string (value.begin (), value.end ()))) return state.Invalid (false, REJECT_INVALID, "the value is not valid JSON"); if (!jsonValue.isObject ()) return state.Invalid (false, REJECT_INVALID, "the value must be a JSON object"); return true; } bool CheckNameTransaction (const CTransaction& tx, unsigned nHeight, const CCoinsView& view, CValidationState& state) { const std::string strTxid = tx.GetHash ().GetHex (); const char* txid = strTxid.c_str (); /* As a first step, try to locate inputs and outputs of the transaction that are name scripts. At most one input and output should be a name operation. */ int nameIn = -1; CNameScript nameOpIn; Coin coinIn; for (unsigned i = 0; i < tx.vin.size (); ++i) { const COutPoint& prevout = tx.vin[i].prevout; Coin coin; if (!view.GetCoin (prevout, coin)) return state.Invalid (error ("%s: failed to fetch input coin for %s", __func__, txid), REJECT_INVALID, "bad-txns-inputs-missingorspent"); const CNameScript op(coin.out.scriptPubKey); if (op.isNameOp ()) { if (nameIn != -1) return state.Invalid (error ("%s: multiple name inputs into" " transaction %s", __func__, txid)); nameIn = i; nameOpIn = op; coinIn = coin; } } int nameOut = -1; CNameScript nameOpOut; for (unsigned i = 0; i < tx.vout.size (); ++i) { const CNameScript op(tx.vout[i].scriptPubKey); if (op.isNameOp ()) { if (nameOut != -1) return state.Invalid (error ("%s: multiple name outputs from" " transaction %s", __func__, txid)); nameOut = i; nameOpOut = op; } } /* If there are no name outputs, then this transaction is not a name operation. In this case, there should also be no name inputs, but otherwise the validation is done. */ if (nameOut == -1) { if (nameIn != -1) return state.Invalid (error ("%s: tx %s has name inputs but no outputs", __func__, txid)); return true; } /* Reject "greedy names". */ const Consensus::Params& params = Params ().GetConsensus (); if (tx.vout[nameOut].nValue < params.rules->MinNameCoinAmount(nHeight)) return state.Invalid (error ("%s: greedy name", __func__)); /* Now that we have ruled out NAME_NEW, check that we have a previous name input that is being updated. */ assert (nameOpOut.isAnyUpdate ()); if (nameOpOut.getNameOp () == OP_NAME_REGISTER) { if (nameIn != -1) return state.Invalid (error ("%s: name registration with" " name input", __func__)); } else if (nameIn == -1) return state.Invalid (error ("CheckNameTransaction: update without" " previous name input")); const valtype& name = nameOpOut.getOpName (); if (!IsNameValid (name, state)) { error ("%s: Name is invalid: %s", __func__, FormatStateMessage (state)); return false; } if (!IsValueValid (nameOpOut.getOpValue (), state)) { error ("%s: Value is invalid: %s", __func__, FormatStateMessage (state)); return false; } /* Process NAME_UPDATE next. */ if (nameOpOut.getNameOp () == OP_NAME_UPDATE) { if (!nameOpIn.isAnyUpdate ()) return state.Invalid (error ("CheckNameTransaction: NAME_UPDATE with" " prev input that is no update")); if (name != nameOpIn.getOpName ()) return state.Invalid (error ("%s: NAME_UPDATE name mismatch to prev tx" " found in %s", __func__, txid)); /* This is actually redundant, since updates need an existing name coin to spend anyway. But it does not hurt to enforce this here, too. */ CNameData oldName; if (!view.GetName (name, oldName)) return state.Invalid (error ("%s: NAME_UPDATE name does not exist", __func__)); /* This is an internal consistency check. If everything is fine, the input coins from the UTXO database should match the name database. */ assert (static_cast<unsigned> (coinIn.nHeight) == oldName.getHeight ()); assert (tx.vin[nameIn].prevout == oldName.getUpdateOutpoint ()); return true; } /* Finally, NAME_REGISTER. */ CNameData oldName; if (view.GetName (name, oldName)) return state.Invalid (error ("CheckNameTransaction: NAME_REGISTER" " on an existing name")); /* We don't have to specifically check that miners don't create blocks with conflicting NAME_FIRSTUPDATE's, since the mining's CCoinsViewCache takes care of this with the check above already. */ return true; } void ApplyNameTransaction (const CTransaction& tx, unsigned nHeight, CCoinsViewCache& view, CBlockUndo& undo) { assert (nHeight != MEMPOOL_HEIGHT); /* Changes are encoded in the outputs. We don't have to do any checks, so simply apply all these. */ for (unsigned i = 0; i < tx.vout.size (); ++i) { const CNameScript op(tx.vout[i].scriptPubKey); if (op.isNameOp () && op.isAnyUpdate ()) { const valtype& name = op.getOpName (); LogPrint (BCLog::NAMES, "Updating name at height %d: %s\n", nHeight, EncodeNameForMessage (name)); CNameTxUndo opUndo; opUndo.fromOldState (name, view); undo.vnameundo.push_back (opUndo); CNameData data; data.fromScript (nHeight, COutPoint (tx.GetHash (), i), op); view.SetName (name, data, false); } } } void CheckNameDB (bool disconnect) { const int option = gArgs.GetArg ("-checknamedb", Params ().DefaultCheckNameDB ()); if (option == -1) return; assert (option >= 0); if (option != 0) { if (disconnect || chainActive.Height () % option != 0) return; } pcoinsTip->Flush (); assert (pcoinsTip->ValidateNameDB ()); }
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ #include "quic/state/QuicStreamManager.h" #include <quic/state/QuicStreamUtilities.h> namespace quic { /** * Updates the head of line blocked time for the stream. This should be called * on new data received or even data being read from the stream. * There are 2 cases when you can become head of line blocked: * 1. You're not previously holb. You receive new data which cannot be read. * 2. You are not head of line blocked. You read data from the stream, but you * discover a hole. * * You can become not head of line blocked if the following conditions happen: * 1. You were head of line blocked, and you receive something that allows you * to read from the stream. * 2. You were head of line blocked, but you receive a reset from the peer. */ static void updateHolBlockedTime(QuicStreamState& stream) { // No data has arrived, or the current stream offset matches // the stream offset that has been read so far. Stream is not HOL-blocked // (although may be blocked on missing data). // If there is no more data to read, or if the current read offset // matches the read offset in the front queue, a potential HOL block // becomes unblocked. if (stream.readBuffer.empty() || (stream.currentReadOffset == stream.readBuffer.front().offset)) { // If we were previously HOL blocked, we're not any more. // Update the total HOLB time and reset the latch. if (stream.lastHolbTime) { stream.totalHolbTime += std::chrono::duration_cast<std::chrono::microseconds>( Clock::now() - *stream.lastHolbTime); stream.lastHolbTime = folly::none; } return; } // No HOL unblocking event has occured. If we are already HOL bloked, // we remain HOL blocked. if (stream.lastHolbTime) { return; } // If we were previously not HOL blocked, we are now. stream.lastHolbTime = Clock::now(); stream.holbCount++; } static bool isStreamUnopened( StreamId streamId, StreamId nextAcceptableStreamId) { return streamId >= nextAcceptableStreamId; } // If a stream is un-opened, these automatically creates all lower streams. // Returns false if the stream is closed or already opened. static LocalErrorCode openPeerStreamIfNotClosed( StreamId streamId, folly::F14FastSet<StreamId>& openStreams, StreamId& nextAcceptableStreamId, StreamId maxStreamId, std::vector<StreamId>& newStreams) { if (streamId < nextAcceptableStreamId) { return LocalErrorCode::CREATING_EXISTING_STREAM; } if (streamId >= maxStreamId) { return LocalErrorCode::STREAM_LIMIT_EXCEEDED; } StreamId start = nextAcceptableStreamId; auto numNewStreams = (streamId - start) / detail::kStreamIncrement; openStreams.reserve(openStreams.size() + numNewStreams); newStreams.reserve(newStreams.size() + numNewStreams); while (start <= streamId) { openStreams.emplace(start); newStreams.push_back(start); start += detail::kStreamIncrement; } if (streamId >= nextAcceptableStreamId) { nextAcceptableStreamId = streamId + detail::kStreamIncrement; } return LocalErrorCode::NO_ERROR; } static LocalErrorCode openLocalStreamIfNotClosed( StreamId streamId, folly::F14FastSet<StreamId>& openStreams, StreamId& nextAcceptableStreamId, StreamId maxStreamId) { if (streamId < nextAcceptableStreamId) { return LocalErrorCode::CREATING_EXISTING_STREAM; } if (streamId >= maxStreamId) { return LocalErrorCode::STREAM_LIMIT_EXCEEDED; } StreamId start = nextAcceptableStreamId; auto numNewStreams = (streamId - start) / detail::kStreamIncrement; openStreams.reserve(openStreams.size() + numNewStreams); while (start <= streamId) { openStreams.emplace(start); start += detail::kStreamIncrement; } if (streamId >= nextAcceptableStreamId) { nextAcceptableStreamId = streamId + detail::kStreamIncrement; } return LocalErrorCode::NO_ERROR; } bool QuicStreamManager::streamExists(StreamId streamId) { if (isLocalStream(nodeType_, streamId)) { if (isUnidirectionalStream(streamId)) { return openUnidirectionalLocalStreams_.count(streamId) > 0; } else { return openBidirectionalLocalStreams_.count(streamId) > 0; } } else { if (isUnidirectionalStream(streamId)) { return openUnidirectionalPeerStreams_.count(streamId) > 0; } else { return openBidirectionalPeerStreams_.count(streamId) > 0; } } } QuicStreamState* QuicStreamManager::findStream(StreamId streamId) { auto lookup = streams_.find(streamId); if (lookup == streams_.end()) { return nullptr; } else { return &lookup->second; } } void QuicStreamManager::setMaxLocalBidirectionalStreams( uint64_t maxStreams, bool force) { if (maxStreams > kMaxMaxStreams) { throw QuicTransportException( "Attempt to set maxStreams beyond the max allowed.", TransportErrorCode::STREAM_LIMIT_ERROR); } StreamId maxStreamId = maxStreams * detail::kStreamIncrement + initialLocalBidirectionalStreamId_; if (force || maxStreamId > maxLocalBidirectionalStreamId_) { maxLocalBidirectionalStreamId_ = maxStreamId; maxLocalBidirectionalStreamIdIncreased_ = true; } } void QuicStreamManager::setMaxLocalUnidirectionalStreams( uint64_t maxStreams, bool force) { if (maxStreams > kMaxMaxStreams) { throw QuicTransportException( "Attempt to set maxStreams beyond the max allowed.", TransportErrorCode::STREAM_LIMIT_ERROR); } StreamId maxStreamId = maxStreams * detail::kStreamIncrement + initialLocalUnidirectionalStreamId_; if (force || maxStreamId > maxLocalUnidirectionalStreamId_) { maxLocalUnidirectionalStreamId_ = maxStreamId; maxLocalUnidirectionalStreamIdIncreased_ = true; } } void QuicStreamManager::setMaxRemoteBidirectionalStreams(uint64_t maxStreams) { setMaxRemoteBidirectionalStreamsInternal(maxStreams, false); } void QuicStreamManager::setMaxRemoteUnidirectionalStreams(uint64_t maxStreams) { setMaxRemoteUnidirectionalStreamsInternal(maxStreams, false); } void QuicStreamManager::setMaxRemoteBidirectionalStreamsInternal( uint64_t maxStreams, bool force) { if (maxStreams > kMaxMaxStreams) { throw QuicTransportException( "Attempt to set maxStreams beyond the max allowed.", TransportErrorCode::STREAM_LIMIT_ERROR); } StreamId maxStreamId = maxStreams * detail::kStreamIncrement + initialRemoteBidirectionalStreamId_; if (force || maxStreamId > maxRemoteBidirectionalStreamId_) { maxRemoteBidirectionalStreamId_ = maxStreamId; } } void QuicStreamManager::setMaxRemoteUnidirectionalStreamsInternal( uint64_t maxStreams, bool force) { if (maxStreams > kMaxMaxStreams) { throw QuicTransportException( "Attempt to set maxStreams beyond the max allowed.", TransportErrorCode::STREAM_LIMIT_ERROR); } StreamId maxStreamId = maxStreams * detail::kStreamIncrement + initialRemoteUnidirectionalStreamId_; if (force || maxStreamId > maxRemoteUnidirectionalStreamId_) { maxRemoteUnidirectionalStreamId_ = maxStreamId; } } bool QuicStreamManager::consumeMaxLocalBidirectionalStreamIdIncreased() { bool res = maxLocalBidirectionalStreamIdIncreased_; maxLocalBidirectionalStreamIdIncreased_ = false; return res; } bool QuicStreamManager::consumeMaxLocalUnidirectionalStreamIdIncreased() { bool res = maxLocalUnidirectionalStreamIdIncreased_; maxLocalUnidirectionalStreamIdIncreased_ = false; return res; } void QuicStreamManager::setStreamPriority( StreamId id, PriorityLevel level, bool incremental) { auto stream = findStream(id); if (stream) { stream->priority = Priority(level, incremental); // If this stream is already in the writable or loss queus, update the // priority there. writableStreams_.updateIfExist(id, stream->priority); lossStreams_.updateIfExist(id, stream->priority); } } void QuicStreamManager::refreshTransportSettings( const TransportSettings& settings) { transportSettings_ = &settings; setMaxRemoteBidirectionalStreamsInternal( transportSettings_->advertisedInitialMaxStreamsBidi, true); setMaxRemoteUnidirectionalStreamsInternal( transportSettings_->advertisedInitialMaxStreamsUni, true); } // We create local streams lazily. If a local stream was created // but not allocated yet, this will allocate a stream. // This will return nullptr if a stream is closed or un-opened. QuicStreamState* FOLLY_NULLABLE QuicStreamManager::getOrCreateOpenedLocalStream(StreamId streamId) { auto& openLocalStreams = isUnidirectionalStream(streamId) ? openUnidirectionalLocalStreams_ : openBidirectionalLocalStreams_; if (openLocalStreams.count(streamId)) { // Open a lazily created stream. auto it = streams_.emplace( std::piecewise_construct, std::forward_as_tuple(streamId), std::forward_as_tuple(streamId, conn_)); QUIC_STATS(conn_.statsCallback, onNewQuicStream); if (!it.second) { throw QuicTransportException( "Creating an active stream", TransportErrorCode::STREAM_STATE_ERROR); } return &it.first->second; } return nullptr; } QuicStreamState* QuicStreamManager::getStream(StreamId streamId) { if (isRemoteStream(nodeType_, streamId)) { auto stream = getOrCreatePeerStream(streamId); updateAppIdleState(); return stream; } auto it = streams_.find(streamId); if (it != streams_.end()) { return &it->second; } auto stream = getOrCreateOpenedLocalStream(streamId); auto nextAcceptableStreamId = isUnidirectionalStream(streamId) ? nextAcceptableLocalUnidirectionalStreamId_ : nextAcceptableLocalBidirectionalStreamId_; if (!stream && isStreamUnopened(streamId, nextAcceptableStreamId)) { throw QuicTransportException( "Trying to get unopened local stream", TransportErrorCode::STREAM_STATE_ERROR); } updateAppIdleState(); return stream; } folly::Expected<QuicStreamState*, LocalErrorCode> QuicStreamManager::createNextBidirectionalStream() { auto stream = createStream(nextBidirectionalStreamId_); if (stream.hasValue()) { nextBidirectionalStreamId_ += detail::kStreamIncrement; } return stream; } folly::Expected<QuicStreamState*, LocalErrorCode> QuicStreamManager::createNextUnidirectionalStream() { auto stream = createStream(nextUnidirectionalStreamId_); if (stream.hasValue()) { nextUnidirectionalStreamId_ += detail::kStreamIncrement; } return stream; } QuicStreamState* FOLLY_NULLABLE QuicStreamManager::getOrCreatePeerStream(StreamId streamId) { // This function maintains 3 invariants: // 1. Streams below nextAcceptableStreamId are streams that have been // seen before. Everything above can be opened. // 2. Streams that have been seen before, always have an entry in // openPeerStreams. If a stream below nextAcceptableStreamId does not // have an entry in openPeerStreams, then it is closed. // 3. If streamId n is open all streams < n will be seen. // It also tries to create the entire state for a stream in a lazy manner. // Validate the stream id is correct if (nodeType_ == QuicNodeType::Client && isClientStream(streamId)) { throw QuicTransportException( "Attempted getting client peer stream on client", TransportErrorCode::STREAM_STATE_ERROR); } else if (nodeType_ == QuicNodeType::Server && isServerStream(streamId)) { throw QuicTransportException( "Attempted getting server peer stream on server", TransportErrorCode::STREAM_STATE_ERROR); } else if (!isClientStream(streamId) && !isServerStream(streamId)) { throw QuicTransportException( "Invalid stream", TransportErrorCode::STREAM_STATE_ERROR); } // TODO when we can rely on C++17, this is a good candidate for try_emplace. auto peerStream = streams_.find(streamId); if (peerStream != streams_.end()) { return &peerStream->second; } auto& openPeerStreams = isUnidirectionalStream(streamId) ? openUnidirectionalPeerStreams_ : openBidirectionalPeerStreams_; if (openPeerStreams.count(streamId)) { // Stream was already open, create the state for it lazily. auto it = streams_.emplace( std::piecewise_construct, std::forward_as_tuple(streamId), std::forward_as_tuple(streamId, conn_)); QUIC_STATS(conn_.statsCallback, onNewQuicStream); return &it.first->second; } auto& nextAcceptableStreamId = isUnidirectionalStream(streamId) ? nextAcceptablePeerUnidirectionalStreamId_ : nextAcceptablePeerBidirectionalStreamId_; auto maxStreamId = isUnidirectionalStream(streamId) ? maxRemoteUnidirectionalStreamId_ : maxRemoteBidirectionalStreamId_; auto openedResult = openPeerStreamIfNotClosed( streamId, openPeerStreams, nextAcceptableStreamId, maxStreamId, newPeerStreams_); if (openedResult == LocalErrorCode::CREATING_EXISTING_STREAM) { // Stream could be closed here. return nullptr; } else if (openedResult == LocalErrorCode::STREAM_LIMIT_EXCEEDED) { throw QuicTransportException( "Exceeded stream limit.", TransportErrorCode::STREAM_LIMIT_ERROR); } auto it = streams_.emplace( std::piecewise_construct, std::forward_as_tuple(streamId), std::forward_as_tuple(streamId, conn_)); QUIC_STATS(conn_.statsCallback, onNewQuicStream); return &it.first->second; } folly::Expected<QuicStreamState*, LocalErrorCode> QuicStreamManager::createStream(StreamId streamId) { if (nodeType_ == QuicNodeType::Client && !isClientStream(streamId)) { throw QuicTransportException( "Attempted creating non-client stream on client", TransportErrorCode::STREAM_STATE_ERROR); } else if (nodeType_ == QuicNodeType::Server && !isServerStream(streamId)) { throw QuicTransportException( "Attempted creating non-server stream on server", TransportErrorCode::STREAM_STATE_ERROR); } auto existingStream = getOrCreateOpenedLocalStream(streamId); if (existingStream) { return existingStream; } bool isUni = isUnidirectionalStream(streamId); auto& nextAcceptableStreamId = isUni ? nextAcceptableLocalUnidirectionalStreamId_ : nextAcceptableLocalBidirectionalStreamId_; auto maxStreamId = isUni ? maxLocalUnidirectionalStreamId_ : maxLocalBidirectionalStreamId_; auto& openLocalStreams = isUni ? openUnidirectionalLocalStreams_ : openBidirectionalLocalStreams_; auto openedResult = openLocalStreamIfNotClosed( streamId, openLocalStreams, nextAcceptableStreamId, maxStreamId); if (openedResult != LocalErrorCode::NO_ERROR) { return folly::makeUnexpected(openedResult); } auto it = streams_.emplace( std::piecewise_construct, std::forward_as_tuple(streamId), std::forward_as_tuple(streamId, conn_)); QUIC_STATS(conn_.statsCallback, onNewQuicStream); updateAppIdleState(); return &it.first->second; } void QuicStreamManager::removeClosedStream(StreamId streamId) { auto it = streams_.find(streamId); if (it == streams_.end()) { VLOG(10) << "Trying to remove already closed stream=" << streamId; return; } VLOG(10) << "Removing closed stream=" << streamId; DCHECK(it->second.inTerminalStates()); readableStreams_.erase(streamId); peekableStreams_.erase(streamId); writableStreams_.erase(streamId); writableControlStreams_.erase(streamId); blockedStreams_.erase(streamId); deliverableStreams_.erase(streamId); txStreams_.erase(streamId); windowUpdates_.erase(streamId); lossStreams_.erase(streamId); stopSendingStreams_.erase(streamId); flowControlUpdated_.erase(streamId); dataRejectedStreams_.erase(streamId); dataExpiredStreams_.erase(streamId); if (it->second.isControl) { DCHECK_GT(numControlStreams_, 0); numControlStreams_--; } streams_.erase(it); QUIC_STATS(conn_.statsCallback, onQuicStreamClosed); if (isRemoteStream(nodeType_, streamId)) { auto& openPeerStreams = isUnidirectionalStream(streamId) ? openUnidirectionalPeerStreams_ : openBidirectionalPeerStreams_; openPeerStreams.erase(streamId); // Check if we should send a stream limit update. We need to send an // update every time we've closed a number of streams >= the set windowing // fraction. uint64_t initialStreamLimit = isUnidirectionalStream(streamId) ? transportSettings_->advertisedInitialMaxStreamsUni : transportSettings_->advertisedInitialMaxStreamsBidi; uint64_t streamWindow = initialStreamLimit / streamLimitWindowingFraction_; uint64_t openableRemoteStreams = isUnidirectionalStream(streamId) ? openableRemoteUnidirectionalStreams() : openableRemoteBidirectionalStreams(); // The "credit" here is how much available stream space we have based on // what the initial stream limit was set to. uint64_t streamCredit = initialStreamLimit - openableRemoteStreams - openPeerStreams.size(); if (streamCredit >= streamWindow) { if (isUnidirectionalStream(streamId)) { uint64_t maxStreams = (maxRemoteUnidirectionalStreamId_ - initialRemoteUnidirectionalStreamId_) / detail::kStreamIncrement; setMaxRemoteUnidirectionalStreams(maxStreams + streamCredit); remoteUnidirectionalStreamLimitUpdate_ = maxStreams + streamCredit; } else { uint64_t maxStreams = (maxRemoteBidirectionalStreamId_ - initialRemoteBidirectionalStreamId_) / detail::kStreamIncrement; setMaxRemoteBidirectionalStreams(maxStreams + streamCredit); remoteBidirectionalStreamLimitUpdate_ = maxStreams + streamCredit; } } } else { auto& openLocalStreams = isUnidirectionalStream(streamId) ? openUnidirectionalLocalStreams_ : openBidirectionalLocalStreams_; openLocalStreams.erase(streamId); } updateAppIdleState(); } void QuicStreamManager::updateLossStreams(QuicStreamState& stream) { if (stream.lossBuffer.empty()) { // No-op if not present lossStreams_.erase(stream.id); } else { // No-op if already inserted lossStreams_.insertOrUpdate(stream.id, stream.priority); } } void QuicStreamManager::updateReadableStreams(QuicStreamState& stream) { updateHolBlockedTime(stream); if (stream.hasReadableData() || stream.streamReadError.has_value()) { readableStreams_.emplace(stream.id); } else { readableStreams_.erase(stream.id); } } void QuicStreamManager::updateWritableStreams(QuicStreamState& stream) { if (stream.hasWritableData() && !stream.streamWriteError.has_value()) { stream.conn.streamManager->addWritable(stream); } else { stream.conn.streamManager->removeWritable(stream); } } void QuicStreamManager::updatePeekableStreams(QuicStreamState& stream) { if (stream.hasPeekableData() && !stream.streamReadError.has_value()) { peekableStreams_.emplace(stream.id); } else { peekableStreams_.erase(stream.id); } } void QuicStreamManager::updateAppIdleState() { bool currentNonCtrlStreams = hasNonCtrlStreams(); if (isAppIdle_ && !currentNonCtrlStreams) { // We were app limited, and we continue to be app limited. return; } else if (!isAppIdle_ && currentNonCtrlStreams) { // We were not app limited, and we continue to be not app limited. return; } isAppIdle_ = !currentNonCtrlStreams; if (conn_.congestionController) { conn_.congestionController->setAppIdle(isAppIdle_, Clock::now()); } } void QuicStreamManager::setStreamAsControl(QuicStreamState& stream) { if (!stream.isControl) { stream.isControl = true; numControlStreams_++; } updateAppIdleState(); } bool QuicStreamManager::isAppIdle() const { return isAppIdle_; } } // namespace quic
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "build/build_config.h" #include "base/single_thread_task_runner.h" #include "ipc/ipc_test_base.h" #include "base/command_line.h" #include "base/process/kill.h" #include "base/threading/thread.h" #include "base/time/time.h" #include "ipc/ipc_descriptors.h" #if defined(OS_POSIX) #include "base/posix/global_descriptors.h" #endif // static std::string IPCTestBase::GetChannelName(const std::string& test_client_name) { DCHECK(!test_client_name.empty()); return test_client_name + "__Channel"; } IPCTestBase::IPCTestBase() { } IPCTestBase::~IPCTestBase() { } void IPCTestBase::TearDown() { message_loop_.reset(); MultiProcessTest::TearDown(); } void IPCTestBase::Init(const std::string& test_client_name) { InitWithCustomMessageLoop( test_client_name, scoped_ptr<base::MessageLoop>(new base::MessageLoopForIO())); } void IPCTestBase::InitWithCustomMessageLoop( const std::string& test_client_name, scoped_ptr<base::MessageLoop> message_loop) { DCHECK(!test_client_name.empty()); DCHECK(test_client_name_.empty()); DCHECK(!message_loop_); test_client_name_ = test_client_name; message_loop_ = message_loop.Pass(); } void IPCTestBase::CreateChannel(IPC::Listener* listener) { CreateChannelFromChannelHandle(GetTestChannelHandle(), listener); } bool IPCTestBase::ConnectChannel() { CHECK(channel_.get()); return channel_->Connect(); } scoped_ptr<IPC::Channel> IPCTestBase::ReleaseChannel() { return channel_.Pass(); } void IPCTestBase::SetChannel(scoped_ptr<IPC::Channel> channel) { channel_ = channel.Pass(); } void IPCTestBase::DestroyChannel() { DCHECK(channel_.get()); channel_.reset(); } void IPCTestBase::CreateChannelFromChannelHandle( const IPC::ChannelHandle& channel_handle, IPC::Listener* listener) { CHECK(!channel_.get()); CHECK(!channel_proxy_.get()); channel_ = CreateChannelFactory( channel_handle, task_runner().get())->BuildChannel(listener); } void IPCTestBase::CreateChannelProxy( IPC::Listener* listener, const scoped_refptr<base::SingleThreadTaskRunner>& ipc_task_runner) { CHECK(!channel_.get()); CHECK(!channel_proxy_.get()); channel_proxy_ = IPC::ChannelProxy::Create( CreateChannelFactory(GetTestChannelHandle(), ipc_task_runner.get()), listener, ipc_task_runner); } void IPCTestBase::DestroyChannelProxy() { CHECK(channel_proxy_.get()); channel_proxy_.reset(); } std::string IPCTestBase::GetTestMainName() const { return test_client_name_ + "TestClientMain"; } bool IPCTestBase::DidStartClient() { DCHECK(client_process_.IsValid()); return client_process_.IsValid(); } #if defined(OS_POSIX) bool IPCTestBase::StartClient() { return StartClientWithFD(channel_ ? channel_->GetClientFileDescriptor() : channel_proxy_->GetClientFileDescriptor()); } bool IPCTestBase::StartClientWithFD(int ipcfd) { DCHECK(!client_process_.IsValid()); base::FileHandleMappingVector fds_to_map; if (ipcfd > -1) fds_to_map.push_back(std::pair<int, int>(ipcfd, kPrimaryIPCChannel + base::GlobalDescriptors::kBaseDescriptor)); base::LaunchOptions options; options.fds_to_remap = &fds_to_map; client_process_ = SpawnChildWithOptions(GetTestMainName(), options); return DidStartClient(); } #elif defined(OS_WIN) bool IPCTestBase::StartClient() { DCHECK(!client_process_.IsValid()); client_process_ = SpawnChild(GetTestMainName()); return DidStartClient(); } #endif bool IPCTestBase::WaitForClientShutdown() { DCHECK(client_process_.IsValid()); int exit_code; bool rv = client_process_.WaitForExitWithTimeout( base::TimeDelta::FromSeconds(5), &exit_code); client_process_.Close(); return rv; } IPC::ChannelHandle IPCTestBase::GetTestChannelHandle() { return GetChannelName(test_client_name_); } scoped_refptr<base::SequencedTaskRunner> IPCTestBase::task_runner() { return message_loop_->task_runner(); } scoped_ptr<IPC::ChannelFactory> IPCTestBase::CreateChannelFactory( const IPC::ChannelHandle& handle, base::SequencedTaskRunner* runner) { return IPC::ChannelFactory::Create(handle, IPC::Channel::MODE_SERVER); }
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> #include <RED4ext/Scripting/Natives/Generated/AI/behavior/TaskDefinition.hpp> namespace RED4ext { namespace AI::behavior { struct CreateAlertedInfluenceMapTaskDefinition : AI::behavior::TaskDefinition { static constexpr const char* NAME = "AIbehaviorCreateAlertedInfluenceMapTaskDefinition"; static constexpr const char* ALIAS = NAME; }; RED4EXT_ASSERT_SIZE(CreateAlertedInfluenceMapTaskDefinition, 0x38); } // namespace AI::behavior } // namespace RED4ext
/** * @file AutoRec.hpp * @brief AutoRec(Automatic Recursion) preprocessor prototype. * @author zer0 * @date 2017-09-15 * * @remarks * In particular, the library must provide reentrance for BOOST_PP_FOR, BOOST_PP_REPEAT, and BOOST_PP_WHILE. * There are two mechanisms that are used to accomplish this: * state parameters (like the above concatenation example) and automatic recursion. * * @see <http://www.boost.org/doc/libs/1_63_0/libs/preprocessor/doc/index.html> * @see <http://www.boost.org/doc/libs/1_61_0/libs/preprocessor/doc/topics/reentrancy.html> */ #ifndef __INCLUDE_LIBTBAG__LIBTBAG_PREPROCESSOR_DETAILS_AUTOREC_HPP__ #define __INCLUDE_LIBTBAG__LIBTBAG_PREPROCESSOR_DETAILS_AUTOREC_HPP__ // MS compatible compilers support #pragma once #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif #include <libtbag/preprocessor/control/If.hpp> #define TBAG_PP_AUTO_REC(pred, n) TBAG_PP_NODE_ENTRY_ ## n(pred) #define TBAG_PP_NODE_ENTRY_256(p) TBAG_PP_NODE_128(p)(p)(p)(p)(p)(p)(p)(p) #define TBAG_PP_NODE_ENTRY_128(p) TBAG_PP_NODE_64(p)(p)(p)(p)(p)(p)(p) #define TBAG_PP_NODE_ENTRY_64(p) TBAG_PP_NODE_32(p)(p)(p)(p)(p)(p) #define TBAG_PP_NODE_ENTRY_32(p) TBAG_PP_NODE_16(p)(p)(p)(p)(p) #define TBAG_PP_NODE_ENTRY_16(p) TBAG_PP_NODE_8(p)(p)(p)(p) #define TBAG_PP_NODE_ENTRY_8(p) TBAG_PP_NODE_4(p)(p)(p) #define TBAG_PP_NODE_ENTRY_4(p) TBAG_PP_NODE_2(p)(p) #define TBAG_PP_NODE_ENTRY_2(p) TBAG_PP_NODE_1(p) # define TBAG_PP_NODE_128(p) TBAG_PP_IIF(p(128), TBAG_PP_NODE_64, TBAG_PP_NODE_192) # define TBAG_PP_NODE_64(p) TBAG_PP_IIF(p(64), TBAG_PP_NODE_32, TBAG_PP_NODE_96) # define TBAG_PP_NODE_32(p) TBAG_PP_IIF(p(32), TBAG_PP_NODE_16, TBAG_PP_NODE_48) # define TBAG_PP_NODE_16(p) TBAG_PP_IIF(p(16), TBAG_PP_NODE_8, TBAG_PP_NODE_24) # define TBAG_PP_NODE_8(p) TBAG_PP_IIF(p(8), TBAG_PP_NODE_4, TBAG_PP_NODE_12) # define TBAG_PP_NODE_4(p) TBAG_PP_IIF(p(4), TBAG_PP_NODE_2, TBAG_PP_NODE_6) # define TBAG_PP_NODE_2(p) TBAG_PP_IIF(p(2), TBAG_PP_NODE_1, TBAG_PP_NODE_3) # define TBAG_PP_NODE_1(p) TBAG_PP_IIF(p(1), 1, 2) # define TBAG_PP_NODE_3(p) TBAG_PP_IIF(p(3), 3, 4) # define TBAG_PP_NODE_6(p) TBAG_PP_IIF(p(6), TBAG_PP_NODE_5, TBAG_PP_NODE_7) # define TBAG_PP_NODE_5(p) TBAG_PP_IIF(p(5), 5, 6) # define TBAG_PP_NODE_7(p) TBAG_PP_IIF(p(7), 7, 8) # define TBAG_PP_NODE_12(p) TBAG_PP_IIF(p(12), TBAG_PP_NODE_10, TBAG_PP_NODE_14) # define TBAG_PP_NODE_10(p) TBAG_PP_IIF(p(10), TBAG_PP_NODE_9, TBAG_PP_NODE_11) # define TBAG_PP_NODE_9(p) TBAG_PP_IIF(p(9), 9, 10) # define TBAG_PP_NODE_11(p) TBAG_PP_IIF(p(11), 11, 12) # define TBAG_PP_NODE_14(p) TBAG_PP_IIF(p(14), TBAG_PP_NODE_13, TBAG_PP_NODE_15) # define TBAG_PP_NODE_13(p) TBAG_PP_IIF(p(13), 13, 14) # define TBAG_PP_NODE_15(p) TBAG_PP_IIF(p(15), 15, 16) # define TBAG_PP_NODE_24(p) TBAG_PP_IIF(p(24), TBAG_PP_NODE_20, TBAG_PP_NODE_28) # define TBAG_PP_NODE_20(p) TBAG_PP_IIF(p(20), TBAG_PP_NODE_18, TBAG_PP_NODE_22) # define TBAG_PP_NODE_18(p) TBAG_PP_IIF(p(18), TBAG_PP_NODE_17, TBAG_PP_NODE_19) # define TBAG_PP_NODE_17(p) TBAG_PP_IIF(p(17), 17, 18) # define TBAG_PP_NODE_19(p) TBAG_PP_IIF(p(19), 19, 20) # define TBAG_PP_NODE_22(p) TBAG_PP_IIF(p(22), TBAG_PP_NODE_21, TBAG_PP_NODE_23) # define TBAG_PP_NODE_21(p) TBAG_PP_IIF(p(21), 21, 22) # define TBAG_PP_NODE_23(p) TBAG_PP_IIF(p(23), 23, 24) # define TBAG_PP_NODE_28(p) TBAG_PP_IIF(p(28), TBAG_PP_NODE_26, TBAG_PP_NODE_30) # define TBAG_PP_NODE_26(p) TBAG_PP_IIF(p(26), TBAG_PP_NODE_25, TBAG_PP_NODE_27) # define TBAG_PP_NODE_25(p) TBAG_PP_IIF(p(25), 25, 26) # define TBAG_PP_NODE_27(p) TBAG_PP_IIF(p(27), 27, 28) # define TBAG_PP_NODE_30(p) TBAG_PP_IIF(p(30), TBAG_PP_NODE_29, TBAG_PP_NODE_31) # define TBAG_PP_NODE_29(p) TBAG_PP_IIF(p(29), 29, 30) # define TBAG_PP_NODE_31(p) TBAG_PP_IIF(p(31), 31, 32) # define TBAG_PP_NODE_48(p) TBAG_PP_IIF(p(48), TBAG_PP_NODE_40, TBAG_PP_NODE_56) # define TBAG_PP_NODE_40(p) TBAG_PP_IIF(p(40), TBAG_PP_NODE_36, TBAG_PP_NODE_44) # define TBAG_PP_NODE_36(p) TBAG_PP_IIF(p(36), TBAG_PP_NODE_34, TBAG_PP_NODE_38) # define TBAG_PP_NODE_34(p) TBAG_PP_IIF(p(34), TBAG_PP_NODE_33, TBAG_PP_NODE_35) # define TBAG_PP_NODE_33(p) TBAG_PP_IIF(p(33), 33, 34) # define TBAG_PP_NODE_35(p) TBAG_PP_IIF(p(35), 35, 36) # define TBAG_PP_NODE_38(p) TBAG_PP_IIF(p(38), TBAG_PP_NODE_37, TBAG_PP_NODE_39) # define TBAG_PP_NODE_37(p) TBAG_PP_IIF(p(37), 37, 38) # define TBAG_PP_NODE_39(p) TBAG_PP_IIF(p(39), 39, 40) # define TBAG_PP_NODE_44(p) TBAG_PP_IIF(p(44), TBAG_PP_NODE_42, TBAG_PP_NODE_46) # define TBAG_PP_NODE_42(p) TBAG_PP_IIF(p(42), TBAG_PP_NODE_41, TBAG_PP_NODE_43) # define TBAG_PP_NODE_41(p) TBAG_PP_IIF(p(41), 41, 42) # define TBAG_PP_NODE_43(p) TBAG_PP_IIF(p(43), 43, 44) # define TBAG_PP_NODE_46(p) TBAG_PP_IIF(p(46), TBAG_PP_NODE_45, TBAG_PP_NODE_47) # define TBAG_PP_NODE_45(p) TBAG_PP_IIF(p(45), 45, 46) # define TBAG_PP_NODE_47(p) TBAG_PP_IIF(p(47), 47, 48) # define TBAG_PP_NODE_56(p) TBAG_PP_IIF(p(56), TBAG_PP_NODE_52, TBAG_PP_NODE_60) # define TBAG_PP_NODE_52(p) TBAG_PP_IIF(p(52), TBAG_PP_NODE_50, TBAG_PP_NODE_54) # define TBAG_PP_NODE_50(p) TBAG_PP_IIF(p(50), TBAG_PP_NODE_49, TBAG_PP_NODE_51) # define TBAG_PP_NODE_49(p) TBAG_PP_IIF(p(49), 49, 50) # define TBAG_PP_NODE_51(p) TBAG_PP_IIF(p(51), 51, 52) # define TBAG_PP_NODE_54(p) TBAG_PP_IIF(p(54), TBAG_PP_NODE_53, TBAG_PP_NODE_55) # define TBAG_PP_NODE_53(p) TBAG_PP_IIF(p(53), 53, 54) # define TBAG_PP_NODE_55(p) TBAG_PP_IIF(p(55), 55, 56) # define TBAG_PP_NODE_60(p) TBAG_PP_IIF(p(60), TBAG_PP_NODE_58, TBAG_PP_NODE_62) # define TBAG_PP_NODE_58(p) TBAG_PP_IIF(p(58), TBAG_PP_NODE_57, TBAG_PP_NODE_59) # define TBAG_PP_NODE_57(p) TBAG_PP_IIF(p(57), 57, 58) # define TBAG_PP_NODE_59(p) TBAG_PP_IIF(p(59), 59, 60) # define TBAG_PP_NODE_62(p) TBAG_PP_IIF(p(62), TBAG_PP_NODE_61, TBAG_PP_NODE_63) # define TBAG_PP_NODE_61(p) TBAG_PP_IIF(p(61), 61, 62) # define TBAG_PP_NODE_63(p) TBAG_PP_IIF(p(63), 63, 64) # define TBAG_PP_NODE_96(p) TBAG_PP_IIF(p(96), TBAG_PP_NODE_80, TBAG_PP_NODE_112) # define TBAG_PP_NODE_80(p) TBAG_PP_IIF(p(80), TBAG_PP_NODE_72, TBAG_PP_NODE_88) # define TBAG_PP_NODE_72(p) TBAG_PP_IIF(p(72), TBAG_PP_NODE_68, TBAG_PP_NODE_76) # define TBAG_PP_NODE_68(p) TBAG_PP_IIF(p(68), TBAG_PP_NODE_66, TBAG_PP_NODE_70) # define TBAG_PP_NODE_66(p) TBAG_PP_IIF(p(66), TBAG_PP_NODE_65, TBAG_PP_NODE_67) # define TBAG_PP_NODE_65(p) TBAG_PP_IIF(p(65), 65, 66) # define TBAG_PP_NODE_67(p) TBAG_PP_IIF(p(67), 67, 68) # define TBAG_PP_NODE_70(p) TBAG_PP_IIF(p(70), TBAG_PP_NODE_69, TBAG_PP_NODE_71) # define TBAG_PP_NODE_69(p) TBAG_PP_IIF(p(69), 69, 70) # define TBAG_PP_NODE_71(p) TBAG_PP_IIF(p(71), 71, 72) # define TBAG_PP_NODE_76(p) TBAG_PP_IIF(p(76), TBAG_PP_NODE_74, TBAG_PP_NODE_78) # define TBAG_PP_NODE_74(p) TBAG_PP_IIF(p(74), TBAG_PP_NODE_73, TBAG_PP_NODE_75) # define TBAG_PP_NODE_73(p) TBAG_PP_IIF(p(73), 73, 74) # define TBAG_PP_NODE_75(p) TBAG_PP_IIF(p(75), 75, 76) # define TBAG_PP_NODE_78(p) TBAG_PP_IIF(p(78), TBAG_PP_NODE_77, TBAG_PP_NODE_79) # define TBAG_PP_NODE_77(p) TBAG_PP_IIF(p(77), 77, 78) # define TBAG_PP_NODE_79(p) TBAG_PP_IIF(p(79), 79, 80) # define TBAG_PP_NODE_88(p) TBAG_PP_IIF(p(88), TBAG_PP_NODE_84, TBAG_PP_NODE_92) # define TBAG_PP_NODE_84(p) TBAG_PP_IIF(p(84), TBAG_PP_NODE_82, TBAG_PP_NODE_86) # define TBAG_PP_NODE_82(p) TBAG_PP_IIF(p(82), TBAG_PP_NODE_81, TBAG_PP_NODE_83) # define TBAG_PP_NODE_81(p) TBAG_PP_IIF(p(81), 81, 82) # define TBAG_PP_NODE_83(p) TBAG_PP_IIF(p(83), 83, 84) # define TBAG_PP_NODE_86(p) TBAG_PP_IIF(p(86), TBAG_PP_NODE_85, TBAG_PP_NODE_87) # define TBAG_PP_NODE_85(p) TBAG_PP_IIF(p(85), 85, 86) # define TBAG_PP_NODE_87(p) TBAG_PP_IIF(p(87), 87, 88) # define TBAG_PP_NODE_92(p) TBAG_PP_IIF(p(92), TBAG_PP_NODE_90, TBAG_PP_NODE_94) # define TBAG_PP_NODE_90(p) TBAG_PP_IIF(p(90), TBAG_PP_NODE_89, TBAG_PP_NODE_91) # define TBAG_PP_NODE_89(p) TBAG_PP_IIF(p(89), 89, 90) # define TBAG_PP_NODE_91(p) TBAG_PP_IIF(p(91), 91, 92) # define TBAG_PP_NODE_94(p) TBAG_PP_IIF(p(94), TBAG_PP_NODE_93, TBAG_PP_NODE_95) # define TBAG_PP_NODE_93(p) TBAG_PP_IIF(p(93), 93, 94) # define TBAG_PP_NODE_95(p) TBAG_PP_IIF(p(95), 95, 96) # define TBAG_PP_NODE_112(p) TBAG_PP_IIF(p(112), TBAG_PP_NODE_104, TBAG_PP_NODE_120) # define TBAG_PP_NODE_104(p) TBAG_PP_IIF(p(104), TBAG_PP_NODE_100, TBAG_PP_NODE_108) # define TBAG_PP_NODE_100(p) TBAG_PP_IIF(p(100), TBAG_PP_NODE_98, TBAG_PP_NODE_102) # define TBAG_PP_NODE_98(p) TBAG_PP_IIF(p(98), TBAG_PP_NODE_97, TBAG_PP_NODE_99) # define TBAG_PP_NODE_97(p) TBAG_PP_IIF(p(97), 97, 98) # define TBAG_PP_NODE_99(p) TBAG_PP_IIF(p(99), 99, 100) # define TBAG_PP_NODE_102(p) TBAG_PP_IIF(p(102), TBAG_PP_NODE_101, TBAG_PP_NODE_103) # define TBAG_PP_NODE_101(p) TBAG_PP_IIF(p(101), 101, 102) # define TBAG_PP_NODE_103(p) TBAG_PP_IIF(p(103), 103, 104) # define TBAG_PP_NODE_108(p) TBAG_PP_IIF(p(108), TBAG_PP_NODE_106, TBAG_PP_NODE_110) # define TBAG_PP_NODE_106(p) TBAG_PP_IIF(p(106), TBAG_PP_NODE_105, TBAG_PP_NODE_107) # define TBAG_PP_NODE_105(p) TBAG_PP_IIF(p(105), 105, 106) # define TBAG_PP_NODE_107(p) TBAG_PP_IIF(p(107), 107, 108) # define TBAG_PP_NODE_110(p) TBAG_PP_IIF(p(110), TBAG_PP_NODE_109, TBAG_PP_NODE_111) # define TBAG_PP_NODE_109(p) TBAG_PP_IIF(p(109), 109, 110) # define TBAG_PP_NODE_111(p) TBAG_PP_IIF(p(111), 111, 112) # define TBAG_PP_NODE_120(p) TBAG_PP_IIF(p(120), TBAG_PP_NODE_116, TBAG_PP_NODE_124) # define TBAG_PP_NODE_116(p) TBAG_PP_IIF(p(116), TBAG_PP_NODE_114, TBAG_PP_NODE_118) # define TBAG_PP_NODE_114(p) TBAG_PP_IIF(p(114), TBAG_PP_NODE_113, TBAG_PP_NODE_115) # define TBAG_PP_NODE_113(p) TBAG_PP_IIF(p(113), 113, 114) # define TBAG_PP_NODE_115(p) TBAG_PP_IIF(p(115), 115, 116) # define TBAG_PP_NODE_118(p) TBAG_PP_IIF(p(118), TBAG_PP_NODE_117, TBAG_PP_NODE_119) # define TBAG_PP_NODE_117(p) TBAG_PP_IIF(p(117), 117, 118) # define TBAG_PP_NODE_119(p) TBAG_PP_IIF(p(119), 119, 120) # define TBAG_PP_NODE_124(p) TBAG_PP_IIF(p(124), TBAG_PP_NODE_122, TBAG_PP_NODE_126) # define TBAG_PP_NODE_122(p) TBAG_PP_IIF(p(122), TBAG_PP_NODE_121, TBAG_PP_NODE_123) # define TBAG_PP_NODE_121(p) TBAG_PP_IIF(p(121), 121, 122) # define TBAG_PP_NODE_123(p) TBAG_PP_IIF(p(123), 123, 124) # define TBAG_PP_NODE_126(p) TBAG_PP_IIF(p(126), TBAG_PP_NODE_125, TBAG_PP_NODE_127) # define TBAG_PP_NODE_125(p) TBAG_PP_IIF(p(125), 125, 126) # define TBAG_PP_NODE_127(p) TBAG_PP_IIF(p(127), 127, 128) # define TBAG_PP_NODE_192(p) TBAG_PP_IIF(p(192), TBAG_PP_NODE_160, TBAG_PP_NODE_224) # define TBAG_PP_NODE_160(p) TBAG_PP_IIF(p(160), TBAG_PP_NODE_144, TBAG_PP_NODE_176) # define TBAG_PP_NODE_144(p) TBAG_PP_IIF(p(144), TBAG_PP_NODE_136, TBAG_PP_NODE_152) # define TBAG_PP_NODE_136(p) TBAG_PP_IIF(p(136), TBAG_PP_NODE_132, TBAG_PP_NODE_140) # define TBAG_PP_NODE_132(p) TBAG_PP_IIF(p(132), TBAG_PP_NODE_130, TBAG_PP_NODE_134) # define TBAG_PP_NODE_130(p) TBAG_PP_IIF(p(130), TBAG_PP_NODE_129, TBAG_PP_NODE_131) # define TBAG_PP_NODE_129(p) TBAG_PP_IIF(p(129), 129, 130) # define TBAG_PP_NODE_131(p) TBAG_PP_IIF(p(131), 131, 132) # define TBAG_PP_NODE_134(p) TBAG_PP_IIF(p(134), TBAG_PP_NODE_133, TBAG_PP_NODE_135) # define TBAG_PP_NODE_133(p) TBAG_PP_IIF(p(133), 133, 134) # define TBAG_PP_NODE_135(p) TBAG_PP_IIF(p(135), 135, 136) # define TBAG_PP_NODE_140(p) TBAG_PP_IIF(p(140), TBAG_PP_NODE_138, TBAG_PP_NODE_142) # define TBAG_PP_NODE_138(p) TBAG_PP_IIF(p(138), TBAG_PP_NODE_137, TBAG_PP_NODE_139) # define TBAG_PP_NODE_137(p) TBAG_PP_IIF(p(137), 137, 138) # define TBAG_PP_NODE_139(p) TBAG_PP_IIF(p(139), 139, 140) # define TBAG_PP_NODE_142(p) TBAG_PP_IIF(p(142), TBAG_PP_NODE_141, TBAG_PP_NODE_143) # define TBAG_PP_NODE_141(p) TBAG_PP_IIF(p(141), 141, 142) # define TBAG_PP_NODE_143(p) TBAG_PP_IIF(p(143), 143, 144) # define TBAG_PP_NODE_152(p) TBAG_PP_IIF(p(152), TBAG_PP_NODE_148, TBAG_PP_NODE_156) # define TBAG_PP_NODE_148(p) TBAG_PP_IIF(p(148), TBAG_PP_NODE_146, TBAG_PP_NODE_150) # define TBAG_PP_NODE_146(p) TBAG_PP_IIF(p(146), TBAG_PP_NODE_145, TBAG_PP_NODE_147) # define TBAG_PP_NODE_145(p) TBAG_PP_IIF(p(145), 145, 146) # define TBAG_PP_NODE_147(p) TBAG_PP_IIF(p(147), 147, 148) # define TBAG_PP_NODE_150(p) TBAG_PP_IIF(p(150), TBAG_PP_NODE_149, TBAG_PP_NODE_151) # define TBAG_PP_NODE_149(p) TBAG_PP_IIF(p(149), 149, 150) # define TBAG_PP_NODE_151(p) TBAG_PP_IIF(p(151), 151, 152) # define TBAG_PP_NODE_156(p) TBAG_PP_IIF(p(156), TBAG_PP_NODE_154, TBAG_PP_NODE_158) # define TBAG_PP_NODE_154(p) TBAG_PP_IIF(p(154), TBAG_PP_NODE_153, TBAG_PP_NODE_155) # define TBAG_PP_NODE_153(p) TBAG_PP_IIF(p(153), 153, 154) # define TBAG_PP_NODE_155(p) TBAG_PP_IIF(p(155), 155, 156) # define TBAG_PP_NODE_158(p) TBAG_PP_IIF(p(158), TBAG_PP_NODE_157, TBAG_PP_NODE_159) # define TBAG_PP_NODE_157(p) TBAG_PP_IIF(p(157), 157, 158) # define TBAG_PP_NODE_159(p) TBAG_PP_IIF(p(159), 159, 160) # define TBAG_PP_NODE_176(p) TBAG_PP_IIF(p(176), TBAG_PP_NODE_168, TBAG_PP_NODE_184) # define TBAG_PP_NODE_168(p) TBAG_PP_IIF(p(168), TBAG_PP_NODE_164, TBAG_PP_NODE_172) # define TBAG_PP_NODE_164(p) TBAG_PP_IIF(p(164), TBAG_PP_NODE_162, TBAG_PP_NODE_166) # define TBAG_PP_NODE_162(p) TBAG_PP_IIF(p(162), TBAG_PP_NODE_161, TBAG_PP_NODE_163) # define TBAG_PP_NODE_161(p) TBAG_PP_IIF(p(161), 161, 162) # define TBAG_PP_NODE_163(p) TBAG_PP_IIF(p(163), 163, 164) # define TBAG_PP_NODE_166(p) TBAG_PP_IIF(p(166), TBAG_PP_NODE_165, TBAG_PP_NODE_167) # define TBAG_PP_NODE_165(p) TBAG_PP_IIF(p(165), 165, 166) # define TBAG_PP_NODE_167(p) TBAG_PP_IIF(p(167), 167, 168) # define TBAG_PP_NODE_172(p) TBAG_PP_IIF(p(172), TBAG_PP_NODE_170, TBAG_PP_NODE_174) # define TBAG_PP_NODE_170(p) TBAG_PP_IIF(p(170), TBAG_PP_NODE_169, TBAG_PP_NODE_171) # define TBAG_PP_NODE_169(p) TBAG_PP_IIF(p(169), 169, 170) # define TBAG_PP_NODE_171(p) TBAG_PP_IIF(p(171), 171, 172) # define TBAG_PP_NODE_174(p) TBAG_PP_IIF(p(174), TBAG_PP_NODE_173, TBAG_PP_NODE_175) # define TBAG_PP_NODE_173(p) TBAG_PP_IIF(p(173), 173, 174) # define TBAG_PP_NODE_175(p) TBAG_PP_IIF(p(175), 175, 176) # define TBAG_PP_NODE_184(p) TBAG_PP_IIF(p(184), TBAG_PP_NODE_180, TBAG_PP_NODE_188) # define TBAG_PP_NODE_180(p) TBAG_PP_IIF(p(180), TBAG_PP_NODE_178, TBAG_PP_NODE_182) # define TBAG_PP_NODE_178(p) TBAG_PP_IIF(p(178), TBAG_PP_NODE_177, TBAG_PP_NODE_179) # define TBAG_PP_NODE_177(p) TBAG_PP_IIF(p(177), 177, 178) # define TBAG_PP_NODE_179(p) TBAG_PP_IIF(p(179), 179, 180) # define TBAG_PP_NODE_182(p) TBAG_PP_IIF(p(182), TBAG_PP_NODE_181, TBAG_PP_NODE_183) # define TBAG_PP_NODE_181(p) TBAG_PP_IIF(p(181), 181, 182) # define TBAG_PP_NODE_183(p) TBAG_PP_IIF(p(183), 183, 184) # define TBAG_PP_NODE_188(p) TBAG_PP_IIF(p(188), TBAG_PP_NODE_186, TBAG_PP_NODE_190) # define TBAG_PP_NODE_186(p) TBAG_PP_IIF(p(186), TBAG_PP_NODE_185, TBAG_PP_NODE_187) # define TBAG_PP_NODE_185(p) TBAG_PP_IIF(p(185), 185, 186) # define TBAG_PP_NODE_187(p) TBAG_PP_IIF(p(187), 187, 188) # define TBAG_PP_NODE_190(p) TBAG_PP_IIF(p(190), TBAG_PP_NODE_189, TBAG_PP_NODE_191) # define TBAG_PP_NODE_189(p) TBAG_PP_IIF(p(189), 189, 190) # define TBAG_PP_NODE_191(p) TBAG_PP_IIF(p(191), 191, 192) # define TBAG_PP_NODE_224(p) TBAG_PP_IIF(p(224), TBAG_PP_NODE_208, TBAG_PP_NODE_240) # define TBAG_PP_NODE_208(p) TBAG_PP_IIF(p(208), TBAG_PP_NODE_200, TBAG_PP_NODE_216) # define TBAG_PP_NODE_200(p) TBAG_PP_IIF(p(200), TBAG_PP_NODE_196, TBAG_PP_NODE_204) # define TBAG_PP_NODE_196(p) TBAG_PP_IIF(p(196), TBAG_PP_NODE_194, TBAG_PP_NODE_198) # define TBAG_PP_NODE_194(p) TBAG_PP_IIF(p(194), TBAG_PP_NODE_193, TBAG_PP_NODE_195) # define TBAG_PP_NODE_193(p) TBAG_PP_IIF(p(193), 193, 194) # define TBAG_PP_NODE_195(p) TBAG_PP_IIF(p(195), 195, 196) # define TBAG_PP_NODE_198(p) TBAG_PP_IIF(p(198), TBAG_PP_NODE_197, TBAG_PP_NODE_199) # define TBAG_PP_NODE_197(p) TBAG_PP_IIF(p(197), 197, 198) # define TBAG_PP_NODE_199(p) TBAG_PP_IIF(p(199), 199, 200) # define TBAG_PP_NODE_204(p) TBAG_PP_IIF(p(204), TBAG_PP_NODE_202, TBAG_PP_NODE_206) # define TBAG_PP_NODE_202(p) TBAG_PP_IIF(p(202), TBAG_PP_NODE_201, TBAG_PP_NODE_203) # define TBAG_PP_NODE_201(p) TBAG_PP_IIF(p(201), 201, 202) # define TBAG_PP_NODE_203(p) TBAG_PP_IIF(p(203), 203, 204) # define TBAG_PP_NODE_206(p) TBAG_PP_IIF(p(206), TBAG_PP_NODE_205, TBAG_PP_NODE_207) # define TBAG_PP_NODE_205(p) TBAG_PP_IIF(p(205), 205, 206) # define TBAG_PP_NODE_207(p) TBAG_PP_IIF(p(207), 207, 208) # define TBAG_PP_NODE_216(p) TBAG_PP_IIF(p(216), TBAG_PP_NODE_212, TBAG_PP_NODE_220) # define TBAG_PP_NODE_212(p) TBAG_PP_IIF(p(212), TBAG_PP_NODE_210, TBAG_PP_NODE_214) # define TBAG_PP_NODE_210(p) TBAG_PP_IIF(p(210), TBAG_PP_NODE_209, TBAG_PP_NODE_211) # define TBAG_PP_NODE_209(p) TBAG_PP_IIF(p(209), 209, 210) # define TBAG_PP_NODE_211(p) TBAG_PP_IIF(p(211), 211, 212) # define TBAG_PP_NODE_214(p) TBAG_PP_IIF(p(214), TBAG_PP_NODE_213, TBAG_PP_NODE_215) # define TBAG_PP_NODE_213(p) TBAG_PP_IIF(p(213), 213, 214) # define TBAG_PP_NODE_215(p) TBAG_PP_IIF(p(215), 215, 216) # define TBAG_PP_NODE_220(p) TBAG_PP_IIF(p(220), TBAG_PP_NODE_218, TBAG_PP_NODE_222) # define TBAG_PP_NODE_218(p) TBAG_PP_IIF(p(218), TBAG_PP_NODE_217, TBAG_PP_NODE_219) # define TBAG_PP_NODE_217(p) TBAG_PP_IIF(p(217), 217, 218) # define TBAG_PP_NODE_219(p) TBAG_PP_IIF(p(219), 219, 220) # define TBAG_PP_NODE_222(p) TBAG_PP_IIF(p(222), TBAG_PP_NODE_221, TBAG_PP_NODE_223) # define TBAG_PP_NODE_221(p) TBAG_PP_IIF(p(221), 221, 222) # define TBAG_PP_NODE_223(p) TBAG_PP_IIF(p(223), 223, 224) # define TBAG_PP_NODE_240(p) TBAG_PP_IIF(p(240), TBAG_PP_NODE_232, TBAG_PP_NODE_248) # define TBAG_PP_NODE_232(p) TBAG_PP_IIF(p(232), TBAG_PP_NODE_228, TBAG_PP_NODE_236) # define TBAG_PP_NODE_228(p) TBAG_PP_IIF(p(228), TBAG_PP_NODE_226, TBAG_PP_NODE_230) # define TBAG_PP_NODE_226(p) TBAG_PP_IIF(p(226), TBAG_PP_NODE_225, TBAG_PP_NODE_227) # define TBAG_PP_NODE_225(p) TBAG_PP_IIF(p(225), 225, 226) # define TBAG_PP_NODE_227(p) TBAG_PP_IIF(p(227), 227, 228) # define TBAG_PP_NODE_230(p) TBAG_PP_IIF(p(230), TBAG_PP_NODE_229, TBAG_PP_NODE_231) # define TBAG_PP_NODE_229(p) TBAG_PP_IIF(p(229), 229, 230) # define TBAG_PP_NODE_231(p) TBAG_PP_IIF(p(231), 231, 232) # define TBAG_PP_NODE_236(p) TBAG_PP_IIF(p(236), TBAG_PP_NODE_234, TBAG_PP_NODE_238) # define TBAG_PP_NODE_234(p) TBAG_PP_IIF(p(234), TBAG_PP_NODE_233, TBAG_PP_NODE_235) # define TBAG_PP_NODE_233(p) TBAG_PP_IIF(p(233), 233, 234) # define TBAG_PP_NODE_235(p) TBAG_PP_IIF(p(235), 235, 236) # define TBAG_PP_NODE_238(p) TBAG_PP_IIF(p(238), TBAG_PP_NODE_237, TBAG_PP_NODE_239) # define TBAG_PP_NODE_237(p) TBAG_PP_IIF(p(237), 237, 238) # define TBAG_PP_NODE_239(p) TBAG_PP_IIF(p(239), 239, 240) # define TBAG_PP_NODE_248(p) TBAG_PP_IIF(p(248), TBAG_PP_NODE_244, TBAG_PP_NODE_252) # define TBAG_PP_NODE_244(p) TBAG_PP_IIF(p(244), TBAG_PP_NODE_242, TBAG_PP_NODE_246) # define TBAG_PP_NODE_242(p) TBAG_PP_IIF(p(242), TBAG_PP_NODE_241, TBAG_PP_NODE_243) # define TBAG_PP_NODE_241(p) TBAG_PP_IIF(p(241), 241, 242) # define TBAG_PP_NODE_243(p) TBAG_PP_IIF(p(243), 243, 244) # define TBAG_PP_NODE_246(p) TBAG_PP_IIF(p(246), TBAG_PP_NODE_245, TBAG_PP_NODE_247) # define TBAG_PP_NODE_245(p) TBAG_PP_IIF(p(245), 245, 246) # define TBAG_PP_NODE_247(p) TBAG_PP_IIF(p(247), 247, 248) # define TBAG_PP_NODE_252(p) TBAG_PP_IIF(p(252), TBAG_PP_NODE_250, TBAG_PP_NODE_254) # define TBAG_PP_NODE_250(p) TBAG_PP_IIF(p(250), TBAG_PP_NODE_249, TBAG_PP_NODE_251) # define TBAG_PP_NODE_249(p) TBAG_PP_IIF(p(249), 249, 250) # define TBAG_PP_NODE_251(p) TBAG_PP_IIF(p(251), 251, 252) # define TBAG_PP_NODE_254(p) TBAG_PP_IIF(p(254), TBAG_PP_NODE_253, TBAG_PP_NODE_255) # define TBAG_PP_NODE_253(p) TBAG_PP_IIF(p(253), 253, 254) # define TBAG_PP_NODE_255(p) TBAG_PP_IIF(p(255), 255, 256) #endif // __INCLUDE_LIBTBAG__LIBTBAG_PREPROCESSOR_DETAILS_AUTOREC_HPP__
/******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://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. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ // // @author raver119@gmail.com // #ifndef LIBND4J_CONVOLUTIONTESTS1_H #define LIBND4J_CONVOLUTIONTESTS1_H #include "testlayers.h" #include <NDArray.h> #include <Context.h> #include <Node.h> #include <graph/Variable.h> #include <graph/VariableSpace.h> #include <ops/declarable/CustomOperations.h> #include <ops/declarable/helpers/convolutions.h> #include <ops/declarable/helpers/col2im.h> #include <PointersManager.h> using namespace nd4j; using namespace nd4j::graph; class ConvolutionTests1 : public testing::Test { public: }; template <typename T> class TypedConvolutionTests1 : public testing::Test { public: }; typedef ::testing::Types<double, float> TestingTypes; TYPED_TEST_CASE(TypedConvolutionTests1, TestingTypes); TYPED_TEST(TypedConvolutionTests1, TestConv2D_1) { int bS=1, iH=5,iW=4, iC=2,oC=3, kH=2,kW=2, sH=1,sW=1, pH=0,pW=0, dH=1,dW=1; TypeParam _expB[]{664.0, 700.0, 736.0, 344.0, 808.0, 844.0, 880.0, 408.0, 952.0, 988.0, 1024.0, 472.0, 1096.0, 1132.0, 1168.0, 536.0, 466.0, 480.0, 494.0, 220.0, 1528.0, 1628.0, 1728.0, 856.0, 1928.0, 2028.0, 2128.0, 1048.0, 2328.0, 2428.0, 2528.0, 1240.0, 2728.0, 2828.0, 2928.0, 1432.0, 1346.0, 1392.0, 1438.0, 700.0, 2392.0, 2556.0, 2720.0, 1368.0, 3048.0, 3212.0, 3376.0, 1688.0, 3704.0, 3868.0, 4032.0, 2008.0, 4360.0, 4524.0, 4688.0, 2328.0, 2226.0, 2304.0, 2382.0, 1180.0}; Nd4jLong _expS[]{4, 1, 3, 5, 4, 60, 20, 4, 1, typeid(TypeParam) == typeid(float) ? 8192 : 16384, 1, 99}; auto input = NDArrayFactory::create_<TypeParam>('c', {bS, iC, iH, iW}); auto weights = NDArrayFactory::create_<TypeParam>('c', {oC, iC, kH, kW}); for (int e = 0; e < input->lengthOf(); e++) input->p(e, e + 1); for (int e = 0; e < weights->lengthOf(); e++) weights->p(e, e + 1); weights->permutei({2,3,1,0}); weights->printShapeInfo("weights"); ArrayOptions::setDataType(_expS, input->dataType()); auto exp = new NDArray(_expB, _expS); auto variableSpace = new VariableSpace(); variableSpace->putVariable(-1, input); variableSpace->putVariable(-2, weights); auto block = new Context(1, variableSpace, false); // not-in-place block->fillInputs({-1, -2}); // 5,5 kernel block->getIArguments()->push_back(kH); block->getIArguments()->push_back(kW); // 1,1 stride block->getIArguments()->push_back(sH); block->getIArguments()->push_back(sW); // 0,0 padding block->getIArguments()->push_back(pH); block->getIArguments()->push_back(pW); // 1,1 dilation block->getIArguments()->push_back(dH); block->getIArguments()->push_back(dW); // same mode block->getIArguments()->push_back(1); // is NHWC block->getIArguments()->push_back(0); nd4j::ops::conv2d op; Nd4jStatus status = op.execute(block); ASSERT_EQ(ND4J_STATUS_OK, status); auto res = variableSpace->getVariable(1)->getNDArray(); // checking output shape ASSERT_EQ(1, res->sizeAt(0)); ASSERT_EQ(3, res->sizeAt(1)); ASSERT_EQ(5, res->sizeAt(2)); ASSERT_EQ(4, res->sizeAt(3)); // basically the same as above ASSERT_TRUE(res->isSameShape(exp)); // just for visual validation exp->printIndexedBuffer("Expected"); res->printIndexedBuffer("Actual "); res->printShapeInfo("Result shape"); // final check ASSERT_TRUE(res->equalsTo(exp)); delete block; delete variableSpace; delete exp; } TYPED_TEST(TypedConvolutionTests1, TestAvgFF_TF) { auto input = NDArrayFactory::create<TypeParam>('c', {4, 10, 10, 3}, {9.37125111, 2.20166993, 2.91434479, 5.43639755, -2.10573769, 4.08528662, 5.86908436, -4.46203756, 2.21057916, 5.35849190, 0.01394637, 4.40566349, 7.07982206, -0.09633455, 2.42429352, 3.97301817, -1.89553940, 1.99690318, 6.33141708, 0.55401880, 1.70707977, 5.55204201, -0.03513752, 1.60011971, 2.62700319, -2.74582434, 3.06697464, 1.06277943, -1.16075921, -0.78095782, 9.72352791, -1.22686064, 1.99644792, 7.35571337, 1.40607321, 0.11390255, 9.53334427, 2.28303599, -1.66728830, 6.16678810, -0.04532295, -1.97708666, 9.74906158, 1.46223176, -1.46734393, 4.30761862, -1.23790228, 1.24823606, 6.13938427, -3.83689475, -1.19625473, 7.91535568, 6.05868721, -3.22946382, 8.81633949, -0.19967777, 0.66053957, 2.30919123, 0.74543846, -0.39347672, 11.11058044, 0.53720862, 1.52645731, 5.70012379, -1.15213466, 1.16451406, 7.00526333, 1.57362783, -2.44384766, 5.54213285, -1.98828590, -0.70483637, 7.88281822, -3.59875536, 0.80745387, 13.41578484, -1.55507684, -0.65855008, 9.32583523, -0.14544789, 0.73436141, 3.61176538, -1.71268058, -2.58490300, 9.09280205, -3.27405524, -2.04569697, 4.44761324, -0.62955856, -2.61917663, 8.04890442, 0.54579324, 0.85929775, 9.82259560, -1.93825579, 0.77703512, 4.67090321, -4.79267597, -2.38906908, 9.31265545, 0.96026313, -1.14109385, 11.54231834, -0.01417295, -0.39500344, 8.49191666, 0.55300158, 2.79490185, 6.92466164, 1.72254205, 2.82222271, 8.83112717, 2.95033407, 2.18054962, 6.73509789, -2.22272944, 0.51127720, -1.04563558, 2.15747333, -2.30959272, 9.55441570, 1.50396204, 1.77370787, 7.38146257, -1.79076433, 3.20961165, 7.18864202, 2.91217351, 0.43018937, 7.11078024, -1.17386127, -0.16817921, 6.12327290, -2.82205725, 3.30696845, 13.51291752, -1.30856836, -2.38332748, 11.09487438, -1.47190213, -0.53050828, 4.38285351, -5.07309771, 1.50714362, 5.72274446, -2.85825086, -0.89673209, 3.73791552, -0.67708802, -4.13149452, -0.00671843, -0.26566532, 0.32961160, 7.14501762, -1.41608179, -4.96590328, 12.26205540, -0.65158135, -0.88641000, 6.95777559, -0.79058206, -0.10260171, 7.87169170, 1.35921454, 1.11759663, 5.46187401, -2.57214499, 2.48484039, 4.04043484, -2.07137156, -1.42709637, 9.25487137, -0.12605135, -2.66949964, 2.89412403, 0.74451172, -2.96250391, 3.99258423, 0.27084303, 0.32213116, 5.42332172, -0.44414216, 1.70881832, 6.69346905, 0.53058422, -4.73146200, 4.22051668, 2.24834967, 0.66996074, 4.30173683, 0.11849818, -4.07520294, 8.27318478, -2.54398274, -2.86705542, 10.11775303, -0.99382895, 0.65881538, 7.93556786, -1.27934420, -1.69343162, 9.68042564, -1.02609646, -1.18189347, 5.75370646, -1.67888868, -4.48871994, 4.79537392, -0.79212248, -0.19855022, 6.15060997, -0.01081491, 3.64454579, 10.82562447, 1.58859253, -2.65847278, 8.60093212, -1.59196103, 0.07635692, 11.76175690, -1.17453325, 0.10122013, 6.86458445, -2.18891335, -2.74004745, 8.07066154, 0.71818852, -2.03035975, 6.31053686, 0.51509416, 1.39789927, 9.43515587, 2.04256630, 0.13985133, 4.65010691, 2.40911126, -0.36255789, -3.06867862, -0.45225358, -1.56778407, 6.05917358, -1.09891272, 1.77184200, 6.46248102, 0.96042323, -0.24346280, 4.63436460, -4.69907761, 1.25187206, 11.46173859, -2.21917558, 1.28007793, 6.92173195, 2.11268163, -3.47389889, 5.08722782, -3.03950930, -4.17154264, 11.30568314, 0.80361372, 2.53214502, 7.18707085, -4.49114513, 2.85449266, 10.14906883, -0.31974933, -0.84472644, -0.52459574, 0.12921631, -1.81390119, 2.76170087, 1.03982210, 2.91744232, -0.29048753, 5.87453508, -1.53684759, 1.85800636, -0.91404629, 1.28954852, 5.11354685, -2.47475505, -1.33179152, 2.58552408, 1.37316465, -3.32339454, 1.54122913, 3.24953628, -0.29758382, 2.82391763, -1.51142192, -1.22699404, 6.75745535, 0.65452754, -3.29385471, 2.06008053, 2.53172946, -4.23532820, -1.53909743, -0.07010663, -1.42173731, 7.29031610, -0.18448229, 4.59496164, 6.73027277, 0.73441899, 0.14426160, 4.14915276, -2.97010231, 6.05851364, 4.95218086, -2.39145470, 2.40494704, 2.10288811, 0.53503096, 1.44511235, 6.66344261, -3.05803776, 7.21418667, 3.30303526, -0.24163735, 3.47409391, 3.64520788, 2.15189481, -3.11243272, 3.62310791, 0.37379482, 0.40865007, -0.83132005, -4.78246069, 2.07030797, 6.51765442, 3.16178989, 5.06180477, 3.78434467, -0.96689719, 0.35965276, 5.89967585, 1.40294051, 1.11952639, 10.59778214, 0.26739889, -1.61297631, 6.24801159, -0.93914318, -0.57812452, 9.92604542, -0.73025000, -3.38530874, 2.45646000, -2.47949195, 0.51638460, 10.65636063, 1.97816694, -3.00407791, 2.66914415, -0.81951088, -0.23316640, 2.40737987, -2.70007610, 1.51531935, 4.08860207, -0.27552786, -1.31721711, 7.11568260, -3.33498216, -4.02545023, 7.22675610, -0.81690705, -2.52689576, 1.04016697, -0.79291463, -0.34875512, 10.00498390, -4.24167728, 1.46162593, 11.82569408, -1.70359993, -0.30161047, 16.44085884, -0.82253462, -0.09435523, 6.13080597, -0.20259480, 0.68308711, 6.15663004, -6.61776876, 0.33295766, 2.55449438, -0.17819691, -1.14892209, 5.56776142, 1.99279118, 1.33035934, 4.45823956, 3.34916544, -2.59905386, 6.16164446, -2.03881931, -2.45273542, 12.46793365, -2.22743297, 2.83738565, 8.48628139, -1.39347959, -1.30867767, 11.08041477, -4.00363779, 2.09183025, 11.30395889, -2.20504737, 1.37426853, 8.98735619, 1.04676604, -0.72757077, 8.28050232, -6.70741081, -0.65798020, 5.68592072, -0.60760021, 0.35854483, 6.26852131, 1.94100165, 1.32112014, 0.80987954, -1.74617672, -0.25434083, 7.16045523, 1.58884013, -2.64847064, 13.14820385, 1.21393633, -2.47258949, 9.41650105, -0.79384226, 2.48954105, 10.95629311, 0.47723705, 4.02126694, 8.02593136, -2.20726371, -1.18794477, 1.50836647, 0.93118095, -1.73513174, 8.85493565, -2.99670315, -0.79055870, 2.39473820, 2.05046916, -2.38055134, 11.82299423, 0.15609655, 0.68744308, 5.66401434, -0.69281673, 2.09855556, 7.74626589, -0.34283102, 1.00542057, 9.95838642, 0.80161905, 2.33455157, 9.80057335, -0.93561798, 2.56991577, 8.29711342, 0.94213426, 0.44209945, 11.70259857, 0.92710167, 2.60957146, 0.24971688, -0.86529571, 3.78628922, 6.80884457, -0.68178189, 2.21103406, 3.18895817, 0.60283208, -2.92716241, 6.72060776, -1.06625068, 2.56543374, 9.97404480, 3.58080721, -0.94936347, 10.16736984, -1.38464379, 1.18191063, 6.66179037, -3.56115270, 0.32329530, 10.90870762, 2.20638227, 0.19653285, 7.34650040, -3.63859272, -1.03027737, 5.98829985, -3.66606474, -3.89746714, 8.63469028, 1.22569811, 1.63240814, 3.74385309, 0.58243257, -0.56981975, 3.69260955, 1.00979900, -1.44030499, 8.57058144, -1.10648811, 1.20474911, 5.43133020, -2.14822555, -0.07928789, 11.25825310, 0.19645604, -5.49546146, 10.41917038, -0.68178523, -2.99639869, 6.50054455, 0.46488351, -5.42328453, 9.09500027, -2.82107449, 0.05601966, 15.34610748, -0.06820253, 3.86699796, 10.73316956, -3.04795432, -0.14702171, 5.64813185, 1.44028485, -2.47596145, 0.07280898, -3.03187990, -1.35183525, 9.35835648, 2.72966957, 1.88199532, 10.36187744, -0.22834805, -3.26738238, 6.92025137, -2.34061313, 4.77379704, 5.28559113, -2.96323752, -1.76186585, 5.94436455, 0.38647744, -5.73869514, 6.76849556, 1.40892124, -1.19068217, 5.37919092, -6.65328646, 3.62782669, 12.34744644, 2.44762444, -4.19242620, 6.14906216, 0.08121119, 0.61355996, 2.69666457, -1.88962626, -0.55314136, 1.84937525, 1.56048691, 1.17460012, 3.75674725, 1.06198275, -5.74625874, 5.41645575, -1.28946674, -1.51689398, 4.32400894, -0.05222082, -4.83948946, 1.80747867, 1.63144708, -2.73887825, 1.63975775, -2.02163982, -0.16210437, 2.93518686, 1.14427686, -2.83246303, 4.79283667, 2.69697428, -3.12678456, -1.19225168, -2.37022972, -3.09429741, 1.94225383, -1.13747168, -2.55048585, 5.40242243, 1.12777328, 3.43713188, 3.62658787, -2.16878843, 0.30164462, 2.97407579, -0.07275413, -1.31149673, 4.70066261, -2.01323795, 4.85255766, 4.59128904, 1.68084168, 1.60336494, 6.58138466, -1.04759812, 2.69906545, 3.55769277, -0.74327278, 2.65819693, 5.39528131, 2.11248922, -1.06446671, 5.24546766, -2.43146014, 4.58907509, 0.06521678, -2.24503994, 2.45722699, 6.94863081, 0.35258654, 2.83396196, 9.92525196, -1.12225175, -0.34365177, 7.19116688, -4.39813757, 0.46517885, 13.22028065, -2.57483673, -6.37226963, 7.58046293, -2.74600363, 0.42231262, 8.04881668, 0.17289802, -0.53447008, 16.55157471, -5.63614368, 0.39288223, 3.37079263, 1.26484549, -0.12820500, 8.46440125, -4.39304399, 2.97676420, 0.65650189, 0.83158541, -1.11556435, 6.32885838, -0.36087769, 2.80724382, 9.90292645, 1.15936041, 0.20947981, 6.91249275, -2.67404819, 2.93782163, 6.65656614, -2.30828357, 2.98214006, 6.80611229, -4.93821478, -7.66555262, 7.59763002, -0.54159302, 3.87403512, 12.42607784, 2.59284401, -0.23375344, 8.95293331, -0.71807784, 0.61873478, 8.66713524, 1.24289191, -2.37835455, 2.08071637, -0.88315344, -3.41891551, 6.85245323, 1.73007369, 1.02169311, 7.69170332, -2.85411978, 2.69790673, 8.12906551, -1.19351399, -2.26442742, 12.26104450, -0.75579089, -1.73274946, 10.68729019, 2.20655656, -0.90522075, 12.42165184, -1.67929137, 2.44851565, 9.31565762, -0.06645700, 1.52762020, 6.18427515, -1.68882596, 3.70261097, 3.02252960, -3.44125366, -1.31575799, 2.84617424, -0.96849400, -4.52356243, 9.95027161, 0.19966406, -0.78874779, 8.18595028, -4.08300209, 1.75126517, 0.96418417, -4.04913044, -0.95200396, 12.03637886, -0.03041124, 0.41642749, 8.88267422, -3.24985337, -2.24919462, 7.32566118, 0.16964148, -2.74123430, 7.05264473, -3.30191112, 0.17163286, 4.81851053, -1.64463484, -0.85933101, 7.29276276, 2.34066939, -2.14860010, 3.46148157, -0.01782012, 1.51504040, 4.79304934, 1.85281146, -1.70663762, 6.93470192, -4.15440845, -1.25983095, 10.52491760, 0.42930329, -1.85146868, 11.70042324, -0.41704914, 3.83796859, 9.21148491, -2.79719448, 0.79470479, 6.26926661, -5.85230207, 3.95105338, 7.84790897, -1.38680744, -1.78099084, 11.95235348, -2.99841452, -1.34507811, 6.15714645, -1.07552516, -2.81228638, 1.66234732, -4.55166149, -1.92601109, 8.64634514, -0.48158705, 3.31595659, 7.67371941, 2.56964207, 0.12107098, 4.56467867, -0.93541539, 1.39432955, 11.99714088, 1.05353570, -2.13099813, 3.67617917, 3.45895386, 1.37365830, 8.74344158, -4.17585802, 1.43908918, 6.28764772, 3.97346330, -0.69144285, 9.07983303, -0.41635889, -0.14965028, 8.85469818, 1.11306190, 2.59440994, 5.38982344, -1.07948279, 1.37252975, 10.26984596, -0.09318046, 2.73104119, 12.45902252, -1.55446684, -2.76124811, 12.19395065, -0.51846564, 1.02764034, 11.42673588, -0.95940983, -0.04781032, 8.78379822, -4.88957930, 0.32534006, 11.97696400, -3.35108662, 1.95104563, 4.46915388, -2.32061648, 3.45230985, 8.29983711, 2.81034684, -2.35529327, 6.07801294, -0.98105043, -0.05359888, 2.52291036, -0.01986909, -2.35321999, 10.51954269, 2.11145401, 3.53506470, 7.29093266, 0.03721160, -1.13496494, 7.43886709, -5.84201956, 2.50796294, 12.14647675, 2.77490377, -2.18896222, 6.05641937, 5.32617044, 1.04221284, 10.79106712, -2.95749092, -2.75414610, 11.30037117, -3.40654182, -2.24673963, 7.49126101, 0.70811015, -6.18003702, 13.83951187, -1.01204085, 1.36298490, -1.04451632, 2.42435336, -0.02346706, -0.85528886, 1.04731262, 0.22192979, 4.15708160, 0.34933877, 0.04814529, 2.24107265, 0.49676740, -1.47752666, 0.45040059, -0.70471478, -1.19759345, 0.21711677, 0.88461423, -2.76830935, 5.52066898, 1.97664857, -1.75381601, 3.45877838, 1.52617192, -1.61350942, 0.85337949, 1.97610760, -3.40310287, 3.40319014, -3.38691044, -0.71319139, 1.65463758, -0.60680127, -1.80700517, 8.02592373, 2.59627104, 2.65895891, 5.93043184, -4.48425817, 3.92670918, 4.19496679, -2.28286791, 6.41634607, 5.72330523, 1.16269672, -0.28753027, 2.46342492, 0.36693189, 0.26712441, 6.37652683, -2.50139046, 2.43923736, 5.56310415, 0.98065847, 1.04267502, 4.16403675, -0.04966142, 4.40897894, 3.72905660, -3.46129870, 3.59962773, 1.34830284, -1.76661730, 0.47943926, 5.29946661, -1.12711561, 1.26970029, 15.17655945, -1.50971997, 5.81345224, 8.48562050, -4.36049604, 2.48144460, 8.23780441, -3.46030426, -0.84656560, 5.94946814, 1.12747943, -2.65683913, 8.69085693, 1.31309867, -2.79958344, 8.76840591, -1.56444156, 1.62710834, 2.41177034, -0.72804940, 5.70619011, 4.67169666, -0.86167198, -1.83803177, 2.96346045, 2.82692933, -2.81557131, 7.11113358, -1.90071094, 2.54244423, 11.19284058, -0.06298946, -1.71517313, 12.98388577, 0.84510714, 3.00816894, 2.57200313, 0.03899818, -1.49330592, 9.60099125, -3.59513044, -1.30045319, 7.09241819, -0.65233821, -2.33627677, 8.81366920, 0.84154201, 1.03312039, 9.85289097, 0.19351870, 1.78496623, 7.34631205, -2.16530800, -0.65016162, 2.46842360, 0.24016285, -1.24308395, 4.78175163, -0.97682536, 2.20942235, 6.68382788, 3.76786447, -1.44454038, 6.26453733, -3.23575711, -2.30137897, 9.53092670, -5.55222607, 3.25999236, 9.37559509, 1.86339056, -0.23551451, 10.23400211, 3.93031883, -0.52629089, 7.85724449, -2.91549587, 4.46612740, 5.66530371, -2.70820427, 4.81359577, 10.31247330, 1.92230141, 2.53931546, 0.74986327, 1.70303428, 0.48063779, 5.31099129, -0.78976244, 3.75864220, 4.23051405, 2.34042454, -7.98193836, 9.83987141, -1.46722627, 3.54497814, 10.36455154, -4.51249075, 0.77715248, 7.78694630, -4.59989023, -2.49585629, 9.90296268, 1.38535416, 1.17441154, 10.10452843, -0.98628229, 0.60194463, 9.12639141, -3.90754628, 2.88526392, 7.24123430, -0.15283313, -0.75728363, -1.15116858, -2.53791571, 0.77229571, 6.44114161, 0.02646767, 4.95463037, 7.21066380, 1.79384065, 0.73250306, 8.04447937, 0.32576546, -0.79447043, 10.12717724, 2.33392906, 1.30716443, 12.36073112, -0.36694977, -1.20438910, 7.03105593, 0.59557682, 0.69267452, 10.18113136, 2.49944925, -0.42229167, 8.83143330, -1.18805945, -2.87509322, 4.53596449, 4.09732771, -3.39088297, -1.02536607, 0.82119560, -3.47302604, 9.29991817, 0.21001509, 4.97036457, 9.50018406, 1.04420102, 1.96560478, 10.74769592, -6.22709799, 3.11690164, 5.06759691, -1.23724771, -3.05831861, 8.12925529, -1.93435478, -1.10151744, 9.32263088, -0.04249470, -5.98547363, 10.49398136, 0.26400441, -0.78915191, 13.28219604, 2.99276900, 0.74853164, 2.49364305, -3.43529654, 4.05278301, 2.13498688, -2.35444307, -0.79900265, 4.66968822, -0.31095147, 3.60674143, 12.37222099, -0.07855003, -3.30292702, 12.15215874, 0.60886210, 2.87075138, 7.75271845, 0.38044083, 3.34402204, 6.40583277, -0.87888050, 0.67438459, 6.91080809, 1.98332930, -0.08303714, 8.08630371, -0.16772588, -2.74058914, 7.17253590, -2.69122696, 1.48173678, 8.99470139, -1.43302310, -0.88651133, 2.66944790, -0.29186964, 2.00838661, 5.09587479, -0.76676071, -2.88322186, 8.31110573, -0.14550979, -1.37726915, 10.28355122, -1.60575438, -0.04118848, 9.97510815, 0.14440438, -3.24632120, 9.00034523, 4.14319563, -1.31023729, 7.16950464, -0.70428526, 2.01559544, 7.26155043, 2.40816474, 2.09847403, 7.31264496, -0.75401551, 2.13392544, 7.03648758, 1.04036045, -1.15636516, 1.09634531, -0.06340861, -0.58107805, -0.65623116, 1.18972754, -0.80717683, 1.40118241, -0.61932516, -3.60596156, 1.59904599, -2.23774099, -1.13721037, 3.89620137, -0.09115922, -7.51356888, 2.36975193, -1.42520905, -2.34173775, 3.33830214, -2.74016523, -3.04115510, 6.00119495, -1.36084354, -2.45065260, 4.56992292, -3.02825928, -3.74182844, 5.11069250, -0.91531068, -2.31385994, 1.83399653, 3.39370203, -3.60886002}); auto exp = NDArrayFactory::create<TypeParam>('c', {4, 4, 4, 3}, {7.97172260, 0.06878620, 2.27749538, 7.29276514, -0.14074677, 0.65480286, 5.70313978, -0.06546132, 0.35443667, 3.70382833, -0.84020567, 0.63826996, 8.60301399, -0.38236514, 1.55177069, 7.37542057, -0.99374938, -0.29971302, 8.84352493, -0.67121059, 0.43132120, 4.78175592, -1.25070143, -1.91523600, 6.03855371, -0.00292124, -1.11214364, 7.90158176, -0.57949901, -0.96735370, 7.81192017, -0.53255427, -0.48009714, 3.16953635, 0.08353355, -1.54299748, 3.74821687, 1.69396687, 0.72724354, 5.42915201, -1.13686812, -0.71793109, 5.78376389, -0.72239977, -0.60055625, 2.53636408, 0.56777251, -2.07892323, 6.08064651, 0.68620735, 2.54017019, 5.65828180, -0.68255502, 1.47283304, 6.10842514, -0.39655915, 0.28380761, 1.96707797, -1.98206317, 0.94027776, 4.71811438, 0.32104525, -0.92409706, 8.34588146, -1.05581069, -0.55217457, 9.58440876, -0.96549922, 0.45820439, 5.65453672, -2.50953507, -0.71441835, 8.03059578, -0.21281289, 0.92125505, 9.26900673, -0.35963219, -0.70039093, 8.59924412, -1.22358346, 0.81318003, 3.85920119, -0.01305223, -1.09234154, 6.33158875, 1.28094780, -1.48926139, 4.94969177, -0.77126902, -1.97033751, 5.64381838, -0.16285487, -1.31277227, 2.39893222, -1.32902908, -1.39609122, 6.47572327, -0.45267010, 1.55727172, 6.70965624, -1.68735468, -0.05672536, 7.25092363, -0.64613032, 0.67050058, 3.60789680, -2.05948973, 2.22687531, 8.15202713, -0.70148355, 1.28314006, 8.14842319, -1.88807654, -1.04808438, 8.45500565, -0.76425624, 0.94542569, 4.56179953, -0.28786001, -2.04502511, 8.46278095, -0.31019822, 0.07339200, 9.34214592, -0.61948007, 0.52481830, 8.32515621, -1.52418160, 0.49678251, 5.11082315, -1.09908783, -0.52969611, 5.27806664, 0.88632923, 0.66754371, 4.75839233, 0.48928693, -0.68036932, 6.56925392, -0.02949905, -2.99189186, 4.46320581, -0.64534980, -0.29516968, 8.60809517, -1.13120568, 3.41720533, 5.84243155, -1.24109328, 0.89566326, 5.99578333, -0.42496428, 2.07076764, 3.17812920, -0.81566459, -0.14363396, 6.55184317, 0.39633346, -0.43852386, 8.70214558, -2.24613595, 0.30708700, 8.73882294, -0.53545928, 1.54409575, 4.49452257, -0.16509305, 0.19028664, 8.24897003, 0.44750381, 2.15448594, 8.97640514, -0.77728152, 0.57272542, 9.03467560, 0.47173575, -1.10807717, 3.30056310, -0.43268481, -0.41470885, 3.53798294, -0.08546703, -2.16840744, 6.18733406, -0.17871059, -2.59837723, 5.94218683, -1.02990067, -0.49760687, 3.76938033, 0.86383581, -1.91504073}); nd4j::ops::avgpool2d op; auto result = op.execute({&input}, {}, {3,3, 3,3, 0,0, 1,1,1, 0,1}, {}); ASSERT_EQ(Status::OK(), result->status()); auto z = result->at(0); z->printIndexedBuffer("z"); exp.printIndexedBuffer("e"); ASSERT_TRUE(exp.isSameShape(z)); ASSERT_TRUE(exp.equalsTo(z)); delete result; } TEST_F(ConvolutionTests1, SeparableConv2D_FF_NoBias_1) { float _expB[] = {10025.0f, 10350.0f, 10675.0f, 11000.0f, 11325.0f, 11650.0f, 13275.0f, 13600.0f, 13925.0f, 14250.0f, 14575.0f, 14900.0f, 16525.0f, 16850.0f, 17175.0f, 17500.0f, 17825.0f, 18150.0f, 19775.0f, 20100.0f, 20425.0f, 20750.0f, 21075.0f, 21400.0f, 23025.0f, 23350.0f, 23675.0f, 24000.0f, 24325.0f, 24650.0f, 26275.0f, 26600.0f, 26925.0f, 27250.0f, 27575.0f, 27900.0f, 38775.0f, 40350.0f, 41925.0f, 43500.0f, 45075.0f, 46650.0f, 54525.0f, 56100.0f, 57675.0f, 59250.0f, 60825.0f, 62400.0f, 70275.0f, 71850.0f, 73425.0f, 75000.0f, 76575.0f, 78150.0f, 86025.0f, 87600.0f, 89175.0f, 90750.0f, 92325.0f, 93900.0f, 101775.0f, 103350.0f, 104925.0f, 106500.0f, 108075.0f, 109650.0f, 117525.0f, 119100.0f, 120675.0f, 122250.0f, 123825.0f, 125400.0f, 67525.0f, 70350.0f, 73175.0f, 76000.0f, 78825.0f, 81650.0f, 95775.0f, 98600.0f, 101425.0f, 104250.0f, 107075.0f, 109900.0f, 124025.0f, 126850.0f, 129675.0f, 132500.0f, 135325.0f, 138150.0f, 152275.0f, 155100.0f, 157925.0f, 160750.0f, 163575.0f, 166400.0f, 180525.0f, 183350.0f, 186175.0f, 189000.0f, 191825.0f, 194650.0f, 208775.0f, 211600.0f, 214425.0f, 217250.0f, 220075.0f, 222900.0f, 119400.0f, 120350.0f, 121300.0f, 122250.0f, 123200.0f, 124150.0f, 128900.0f, 129850.0f, 130800.0f, 131750.0f, 132700.0f, 133650.0f, 138400.0f, 139350.0f, 140300.0f, 141250.0f, 142200.0f, 143150.0f, 147900.0f, 148850.0f, 149800.0f, 150750.0f, 151700.0f, 152650.0f, 157400.0f, 158350.0f, 159300.0f, 160250.0f, 161200.0f, 162150.0f, 166900.0f, 167850.0f, 168800.0f, 169750.0f, 170700.0f, 171650.0f, 273150.0f, 275350.0f, 277550.0f, 279750.0f, 281950.0f, 284150.0f, 295150.0f, 297350.0f, 299550.0f, 301750.0f, 303950.0f, 306150.0f, 317150.0f, 319350.0f, 321550.0f, 323750.0f, 325950.0f, 328150.0f, 339150.0f, 341350.0f, 343550.0f, 345750.0f, 347950.0f, 350150.0f, 361150.0f, 363350.0f, 365550.0f, 367750.0f, 369950.0f, 372150.0f, 383150.0f, 385350.0f, 387550.0f, 389750.0f, 391950.0f, 394150.0f, 426900.0f, 430350.0f, 433800.0f, 437250.0f, 440700.0f, 444150.0f, 461400.0f, 464850.0f, 468300.0f, 471750.0f, 475200.0f, 478650.0f, 495900.0f, 499350.0f, 502800.0f, 506250.0f, 509700.0f, 513150.0f, 530400.0f, 533850.0f, 537300.0f, 540750.0f, 544200.0f, 547650.0f, 564900.0f, 568350.0f, 571800.0f, 575250.0f, 578700.0f, 582150.0f, 599400.0f, 602850.0f, 606300.0f, 609750.0f, 613200.0f, 616650.0f, 75025.0f, 75350.0f, 75675.0f, 76000.0f, 76325.0f, 76650.0f, 78275.0f, 78600.0f, 78925.0f, 79250.0f, 79575.0f, 79900.0f, 81525.0f, 81850.0f, 82175.0f, 82500.0f, 82825.0f, 83150.0f, 84775.0f, 85100.0f, 85425.0f, 85750.0f, 86075.0f, 86400.0f, 88025.0f, 88350.0f, 88675.0f, 89000.0f, 89325.0f, 89650.0f, 91275.0f, 91600.0f, 91925.0f, 92250.0f, 92575.0f, 92900.0f, 353775.0f, 355350.0f, 356925.0f, 358500.0f, 360075.0f, 361650.0f, 369525.0f, 371100.0f, 372675.0f, 374250.0f, 375825.0f, 377400.0f, 385275.0f, 386850.0f, 388425.0f, 390000.0f, 391575.0f, 393150.0f, 401025.0f, 402600.0f, 404175.0f, 405750.0f, 407325.0f, 408900.0f, 416775.0f, 418350.0f, 419925.0f, 421500.0f, 423075.0f, 424650.0f, 432525.0f, 434100.0f, 435675.0f, 437250.0f, 438825.0f, 440400.0f, 632525.0f, 635350.0f, 638175.0f, 641000.0f, 643825.0f, 646650.0f, 660775.0f, 663600.0f, 666425.0f, 669250.0f, 672075.0f, 674900.0f, 689025.0f, 691850.0f, 694675.0f, 697500.0f, 700325.0f, 703150.0f, 717275.0f, 720100.0f, 722925.0f, 725750.0f, 728575.0f, 731400.0f, 745525.0f, 748350.0f, 751175.0f, 754000.0f, 756825.0f, 759650.0f, 773775.0f, 776600.0f, 779425.0f, 782250.0f, 785075.0f, 787900.0f, 309400.0f, 310350.0f, 311300.0f, 312250.0f, 313200.0f, 314150.0f, 318900.0f, 319850.0f, 320800.0f, 321750.0f, 322700.0f, 323650.0f, 328400.0f, 329350.0f, 330300.0f, 331250.0f, 332200.0f, 333150.0f, 337900.0f, 338850.0f, 339800.0f, 340750.0f, 341700.0f, 342650.0f, 347400.0f, 348350.0f, 349300.0f, 350250.0f, 351200.0f, 352150.0f, 356900.0f, 357850.0f, 358800.0f, 359750.0f, 360700.0f, 361650.0f, 713150.0f, 715350.0f, 717550.0f, 719750.0f, 721950.0f, 724150.0f, 735150.0f, 737350.0f, 739550.0f, 741750.0f, 743950.0f, 746150.0f, 757150.0f, 759350.0f, 761550.0f, 763750.0f, 765950.0f, 768150.0f, 779150.0f, 781350.0f, 783550.0f, 785750.0f, 787950.0f, 790150.0f, 801150.0f, 803350.0f, 805550.0f, 807750.0f, 809950.0f, 812150.0f, 823150.0f, 825350.0f, 827550.0f, 829750.0f, 831950.0f, 834150.0f, 1116900.0f, 1120350.0f, 1123800.0f, 1127250.0f, 1130700.0f, 1134150.0f, 1151400.0f, 1154850.0f, 1158300.0f, 1161750.0f, 1165200.0f, 1168650.0f, 1185900.0f, 1189350.0f, 1192800.0f, 1196250.0f, 1199700.0f, 1203150.0f, 1220400.0f, 1223850.0f, 1227300.0f, 1230750.0f, 1234200.0f, 1237650.0f, 1254900.0f, 1258350.0f, 1261800.0f, 1265250.0f, 1268700.0f, 1272150.0f, 1289400.0f, 1292850.0f, 1296300.0f, 1299750.0f, 1303200.0f, 1306650.0f,}; Nd4jLong _expS[] = {4, 2, 6, 6, 6, 144, 36, 6, 1, 8192, 1, 99}; NDArray exp(_expB, _expS); int sY = 1; int sX = 1; int pY = 0; int pX = 0; int iC = 2; int oC = 3; int kY = 5; int kX = 5; int iY = 10; int iX = 10; int B = 2; auto input = NDArrayFactory::create_<float>('c', {B, iC, iY, iX}); for (int e = 0; e < input->lengthOf(); e++) input->p(e, e+1); auto weights = NDArrayFactory::create_<float>('c', {oC, iC, kY, kX}); for (int e = 0; e < weights->lengthOf(); e++) weights->p(e, e+1); weights->permutei({2,3,1,0}); auto variableSpace = new VariableSpace(); variableSpace->putVariable(-1, input); variableSpace->putVariable(-2, weights); auto block = new Context(1, variableSpace, false); block->fillInputs({-1, -2}); block->getIArguments()->push_back(kY); block->getIArguments()->push_back(kX); block->getIArguments()->push_back(sY); block->getIArguments()->push_back(sX); block->getIArguments()->push_back(pY); block->getIArguments()->push_back(pX); // dilation block->getIArguments()->push_back(1); block->getIArguments()->push_back(1); // NOT same mode block->getIArguments()->push_back(0); nd4j::ops::sconv2d op; Nd4jStatus status = op.execute(block); ASSERT_EQ(ND4J_STATUS_OK, status); auto output = variableSpace->getVariable(1)->getNDArray(); //exp.printShapeInfo("Expected shape"); //output->printShapeInfo("Result shape"); ASSERT_TRUE(exp.isSameShape(output)); //exp.printBuffer("Expctd buffer"); //output->printBuffer("Result buffer"); ASSERT_TRUE(exp.equalsTo(output)); delete block; delete variableSpace; } TYPED_TEST(TypedConvolutionTests1, deconv2D_FF_NoBias_1) { Nd4jLong _expS[] = {4, 2, 3, 8, 8, 192, 64, 8, 1, typeid(TypeParam) == typeid(float) ? 8192 : 16384, 1, 99}; TypeParam _expB[] = {6276.0, 12831.0, 19668.0, 26790.0, 27012.0, 20703.0, 14100.0, 7200.0, 13719.0, 28023.0, 42918.0, 58410.0, 58902.0, 45105.0, 30693.0, 15660.0, 22389.0, 45696.0, 69930.0, 95100.0, 95910.0, 73386.0, 49899.0, 25440.0, 32346.0, 65970.0, 100884.0, 137100.0, 138276.0, 105726.0, 71838.0, 36600.0, 33726.0, 68790.0, 105204.0, 142980.0, 144156.0, 110226.0, 74898.0, 38160.0, 27555.0, 56154.0, 85806.0, 116520.0, 117474.0, 89748.0, 60933.0, 31020.0, 19917.0, 40557.0, 61926.0, 84030.0, 84714.0, 64671.0, 43875.0, 22320.0, 10752.0, 21879.0, 33384.0, 45270.0, 45636.0, 34815.0, 23604.0, 12000.0, 7551.0, 15456.0, 23718.0, 32340.0, 32562.0, 24978.0, 17025.0, 8700.0, 16569.0, 33873.0, 51918.0, 70710.0, 71202.0, 54555.0, 37143.0, 18960.0, 27114.0, 55371.0, 84780.0, 115350.0, 116160.0, 88911.0, 60474.0, 30840.0, 39246.0, 80070.0, 122484.0, 166500.0, 167676.0, 128226.0, 87138.0, 44400.0, 40626.0, 82890.0, 126804.0, 172380.0, 173556.0, 132726.0, 90198.0, 45960.0, 33180.0, 67629.0, 103356.0, 140370.0, 141324.0, 107973.0, 73308.0, 37320.0, 23967.0, 48807.0, 74526.0, 101130.0, 101814.0, 77721.0, 52725.0, 26820.0, 12927.0, 26304.0, 40134.0, 54420.0, 54786.0, 41790.0, 28329.0, 14400.0, 8826.0, 18081.0, 27768.0, 37890.0, 38112.0, 29253.0, 19950.0, 10200.0, 19419.0, 39723.0, 60918.0, 83010.0, 83502.0, 64005.0, 43593.0, 22260.0, 31839.0, 65046.0, 99630.0, 135600.0, 136410.0, 104436.0, 71049.0, 36240.0, 46146.0, 94170.0, 144084.0, 195900.0, 197076.0, 150726.0, 102438.0, 52200.0, 47526.0, 96990.0, 148404.0, 201780.0, 202956.0, 155226.0, 105498.0, 53760.0, 38805.0, 79104.0, 120906.0, 164220.0, 165174.0, 126198.0, 85683.0, 43620.0, 28017.0, 57057.0, 87126.0, 118230.0, 118914.0, 90771.0, 61575.0, 31320.0, 15102.0, 30729.0, 46884.0, 63570.0, 63936.0, 48765.0, 33054.0, 16800.0, 17220.0, 34863.0, 52932.0, 71430.0, 72228.0, 54831.0, 36996.0, 18720.0, 36327.0, 73527.0, 111606.0, 150570.0, 152214.0, 115521.0, 77925.0, 39420.0, 57381.0, 116112.0, 176202.0, 237660.0, 240198.0, 182250.0, 122907.0, 62160.0, 80442.0, 162738.0, 246900.0, 332940.0, 336420.0, 255198.0, 172062.0, 87000.0, 84702.0, 171318.0, 259860.0, 350340.0, 353820.0, 268338.0, 180882.0, 91440.0, 66867.0, 135210.0, 205038.0, 276360.0, 279042.0, 211572.0, 142581.0, 72060.0, 46845.0, 94701.0, 143574.0, 193470.0, 195306.0, 148047.0, 99747.0, 50400.0, 24576.0, 49671.0, 75288.0, 101430.0, 102372.0, 77583.0, 52260.0, 26400.0, 22095.0, 44688.0, 67782.0, 91380.0, 92178.0, 69906.0, 47121.0, 23820.0, 46377.0, 93777.0, 142206.0, 191670.0, 193314.0, 146571.0, 98775.0, 49920.0, 72906.0, 147387.0, 223452.0, 301110.0, 303648.0, 230175.0, 155082.0, 78360.0, 101742.0, 205638.0, 311700.0, 419940.0, 423420.0, 320898.0, 216162.0, 109200.0, 106002.0, 214218.0, 324660.0, 437340.0, 440820.0, 334038.0, 224982.0, 113640.0, 83292.0, 168285.0, 254988.0, 343410.0, 346092.0, 262197.0, 176556.0, 89160.0, 58095.0, 117351.0, 177774.0, 239370.0, 241206.0, 182697.0, 122997.0, 62100.0, 30351.0, 61296.0, 92838.0, 124980.0, 125922.0, 95358.0, 64185.0, 32400.0, 26970.0, 54513.0, 82632.0, 111330.0, 112128.0, 84981.0, 57246.0, 28920.0, 56427.0, 114027.0, 172806.0, 232770.0, 234414.0, 177621.0, 119625.0, 60420.0, 88431.0, 178662.0, 270702.0, 364560.0, 367098.0, 278100.0, 187257.0, 94560.0, 123042.0, 248538.0, 376500.0, 506940.0, 510420.0, 386598.0, 260262.0, 131400.0, 127302.0, 257118.0, 389460.0, 524340.0, 527820.0, 399738.0, 269082.0, 135840.0, 99717.0, 201360.0, 304938.0, 410460.0, 413142.0, 312822.0, 210531.0, 106260.0, 69345.0, 140001.0, 211974.0, 285270.0, 287106.0, 217347.0, 146247.0, 73800.0, 36126.0, 72921.0, 110388.0, 148530.0, 149472.0, 113133.0, 76110.0, 38400.0,}; NDArray exp(_expB, _expS); auto input = NDArrayFactory::create_<TypeParam>('c', {2, 3, 4, 4}); auto weights = NDArrayFactory::create_<TypeParam>('c', {3, 3, 5, 5}); input->linspace(1); weights->linspace(1); weights->permutei({2,3,1,0}); auto variableSpace = new VariableSpace(); variableSpace->putVariable(-1, input); variableSpace->putVariable(-2, weights); auto block = new Context(1, variableSpace, false); block->fillInputs({-1, -2}); block->getIArguments()->push_back(5); block->getIArguments()->push_back(5); block->getIArguments()->push_back(1); block->getIArguments()->push_back(1); block->getIArguments()->push_back(0); block->getIArguments()->push_back(0); // dilation block->getIArguments()->push_back(1); block->getIArguments()->push_back(1); // NOT same mode block->getIArguments()->push_back(0); block->getIArguments()->push_back(0); nd4j::ops::deconv2d op; Nd4jStatus status = op.execute(block); ASSERT_EQ(ND4J_STATUS_OK, status); auto output = variableSpace->getVariable(1)->getNDArray(); ASSERT_TRUE(exp.isSameShape(output)); // exp.printBuffer("Expctd buffer"); //output->printBuffer("Result buffer"); ASSERT_TRUE(exp.equalsTo(output)); delete variableSpace; delete block; } TYPED_TEST(TypedConvolutionTests1, conv2D_BP_Bias_1) { TypeParam _expWGradB[] = {9312.0, 12580.0, 9528.0, 13168.0, 17712.0, 13360.0, 9960.0, 13348.0, 10032.0, 13344.0, 18148.0, 13848.0, 19312.0, 26160.0, 19888.0, 15144.0, 20452.0, 15504.0}; Nd4jLong _expWGradS[] = {4, 2, 1, 3, 3, 9, 9, 3, 1, typeid(TypeParam) == typeid(float) ? 8192 : 16384, 1, 99}; NDArray expWGrad(_expWGradB, _expWGradS); expWGrad.permutei({2,3,1,0}); TypeParam _expBGradB[] = {784.0, 1296.0}; Nd4jLong _expBGradS[] = {2, 2, 1, 1, 1, typeid(TypeParam) == typeid(float) ? 8192 : 16384, 1, 99}; NDArray expBGrad(_expBGradB, _expBGradS); auto input = NDArrayFactory::create<TypeParam>('c', {2, 1, 4, 4}); auto weights = NDArrayFactory::create<TypeParam>('c', {2, 1, 3, 3}); auto bias = NDArrayFactory::create<TypeParam>('c', {2, 1}); auto epsilonNext = NDArrayFactory::create<TypeParam>('c', {2, 2, 4, 4}); TypeParam _expEpsB[] = {952.0, 1540.0, 1636.0, 1180.0, 1791.0, 2886.0, 3057.0, 2193.0, 2223.0, 3570.0, 3741.0, 2673.0, 1900.0, 3028.0, 3160.0, 2240.0, 2872.0, 4612.0, 4708.0, 3356.0, 5247.0, 8358.0, 8529.0, 6033.0, 5679.0, 9042.0, 9213.0, 6513.0, 4588.0, 7252.0, 7384.0, 5184.0}; NDArray expEps(_expEpsB, input.getShapeInfo()); input.linspace(1); weights.linspace(1); epsilonNext.linspace(1); weights.permutei({2,3,1,0}); nd4j::ops::conv2d_bp op; auto results = op.execute({&input, &weights, &bias, &epsilonNext}, {}, {3, 3, 1, 1, 0, 0, 1, 1, 1}, {}); ASSERT_TRUE(results->size() == 3); auto epsilon = results->at(0); auto gradW = results->at(1); auto gradB = results->at(2); ASSERT_TRUE(expWGrad.isSameShape(gradW)); //expWGrad.printBuffer("Expctd buffer"); // gradW->printBuffer("Result buffer"); ASSERT_TRUE(expWGrad.equalsTo(gradW)); ASSERT_TRUE(input.isSameShape(epsilon)); // expEps.printBuffer("Expctd buffer"); //epsilon->printBuffer("Result buffer"); ASSERT_TRUE(expEps.equalsTo(epsilon)); ASSERT_TRUE(expBGrad.isSameShape(gradB)); ASSERT_TRUE(expBGrad.equalsTo(gradB)); delete results; } TYPED_TEST(TypedConvolutionTests1, conv2D_BP_NoBias_1) { TypeParam _expWGradB[] = {9312.0, 12580.0, 9528.0, 13168.0, 17712.0, 13360.0, 9960.0, 13348.0, 10032.0, 13344.0, 18148.0, 13848.0, 19312.0, 26160.0, 19888.0, 15144.0, 20452.0, 15504.0}; Nd4jLong _expWGradS[] = {4, 2, 1, 3, 3, 9, 9, 3, 1, typeid(TypeParam) == typeid(float) ? 8192 : 16384, 1, 99}; NDArray expWGrad(_expWGradB, _expWGradS); expWGrad.permutei({2,3,1,0}); auto input = NDArrayFactory::create<TypeParam>('c', {2, 1, 4, 4}); auto weights = NDArrayFactory::create<TypeParam>('c', {2, 1, 3, 3}); auto epsilonNext = NDArrayFactory::create<TypeParam>('c', {2, 2, 4, 4}); TypeParam _expEpsB[] = {952.0, 1540.0, 1636.0, 1180.0, 1791.0, 2886.0, 3057.0, 2193.0, 2223.0, 3570.0, 3741.0, 2673.0, 1900.0, 3028.0, 3160.0, 2240.0, 2872.0, 4612.0, 4708.0, 3356.0, 5247.0, 8358.0, 8529.0, 6033.0, 5679.0, 9042.0, 9213.0, 6513.0, 4588.0, 7252.0, 7384.0, 5184.0}; NDArray expEps(_expEpsB, input.getShapeInfo()); input.linspace(1); weights.linspace(1); epsilonNext.linspace(1); weights.permutei({2,3,1,0}); nd4j::ops::conv2d_bp op; auto results = op.execute({&input, &weights, &epsilonNext}, {}, {3, 3, 1, 1, 0, 0, 1, 1, 1}, {}); ASSERT_TRUE(results->size() == 2); auto epsilon = results->at(0); auto gradW = results->at(1); ASSERT_TRUE(expWGrad.isSameShape(gradW)); //expWGrad.printBuffer("Expctd buffer"); // gradW->printBuffer("Result buffer"); ASSERT_TRUE(expWGrad.equalsTo(gradW)); ASSERT_TRUE(input.isSameShape(epsilon)); // expEps.printBuffer("Expctd buffer"); //epsilon->printBuffer("Result buffer"); ASSERT_TRUE(expEps.equalsTo(epsilon)); delete results; } TYPED_TEST(TypedConvolutionTests1, sconv2D_FF_NoBias_2) { TypeParam _expBFF[] = {10025.0f, 10350.0f, 10675.0f, 11000.0f, 11325.0f, 11650.0f, 13275.0f, 13600.0f, 13925.0f, 14250.0f, 14575.0f, 14900.0f, 16525.0f, 16850.0f, 17175.0f, 17500.0f, 17825.0f, 18150.0f, 19775.0f, 20100.0f, 20425.0f, 20750.0f, 21075.0f, 21400.0f, 23025.0f, 23350.0f, 23675.0f, 24000.0f, 24325.0f, 24650.0f, 26275.0f, 26600.0f, 26925.0f, 27250.0f, 27575.0f, 27900.0f, 53150.0f, 55350.0f, 57550.0f, 59750.0f, 61950.0f, 64150.0f, 75150.0f, 77350.0f, 79550.0f, 81750.0f, 83950.0f, 86150.0f, 97150.0f, 99350.0f, 101550.0f, 103750.0f, 105950.0f, 108150.0f, 119150.0f, 121350.0f, 123550.0f, 125750.0f, 127950.0f, 130150.0f, 141150.0f, 143350.0f, 145550.0f, 147750.0f, 149950.0f, 152150.0f, 163150.0f, 165350.0f, 167550.0f, 169750.0f, 171950.0f, 174150.0f, 119400.0f, 120350.0f, 121300.0f, 122250.0f, 123200.0f, 124150.0f, 128900.0f, 129850.0f, 130800.0f, 131750.0f, 132700.0f, 133650.0f, 138400.0f, 139350.0f, 140300.0f, 141250.0f, 142200.0f, 143150.0f, 147900.0f, 148850.0f, 149800.0f, 150750.0f, 151700.0f, 152650.0f, 157400.0f, 158350.0f, 159300.0f, 160250.0f, 161200.0f, 162150.0f, 166900.0f, 167850.0f, 168800.0f, 169750.0f, 170700.0f, 171650.0f, 350025.0f, 352850.0f, 355675.0f, 358500.0f, 361325.0f, 364150.0f, 378275.0f, 381100.0f, 383925.0f, 386750.0f, 389575.0f, 392400.0f, 406525.0f, 409350.0f, 412175.0f, 415000.0f, 417825.0f, 420650.0f, 434775.0f, 437600.0f, 440425.0f, 443250.0f, 446075.0f, 448900.0f, 463025.0f, 465850.0f, 468675.0f, 471500.0f, 474325.0f, 477150.0f, 491275.0f, 494100.0f, 496925.0f, 499750.0f, 502575.0f, 505400.0f, 353775.0f, 355350.0f, 356925.0f, 358500.0f, 360075.0f, 361650.0f, 369525.0f, 371100.0f, 372675.0f, 374250.0f, 375825.0f, 377400.0f, 385275.0f, 386850.0f, 388425.0f, 390000.0f, 391575.0f, 393150.0f, 401025.0f, 402600.0f, 404175.0f, 405750.0f, 407325.0f, 408900.0f, 416775.0f, 418350.0f, 419925.0f, 421500.0f, 423075.0f, 424650.0f, 432525.0f, 434100.0f, 435675.0f, 437250.0f, 438825.0f, 440400.0f, 771900.0f, 775350.0f, 778800.0f, 782250.0f, 785700.0f, 789150.0f, 806400.0f, 809850.0f, 813300.0f, 816750.0f, 820200.0f, 823650.0f, 840900.0f, 844350.0f, 847800.0f, 851250.0f, 854700.0f, 858150.0f, 875400.0f, 878850.0f, 882300.0f, 885750.0f, 889200.0f, 892650.0f, 909900.0f, 913350.0f, 916800.0f, 920250.0f, 923700.0f, 927150.0f, 944400.0f, 947850.0f, 951300.0f, 954750.0f, 958200.0f, 961650.0f, 107525.0f, 107850.0f, 108175.0f, 108500.0f, 108825.0f, 109150.0f, 110775.0f, 111100.0f, 111425.0f, 111750.0f, 112075.0f, 112400.0f, 114025.0f, 114350.0f, 114675.0f, 115000.0f, 115325.0f, 115650.0f, 117275.0f, 117600.0f, 117925.0f, 118250.0f, 118575.0f, 118900.0f, 120525.0f, 120850.0f, 121175.0f, 121500.0f, 121825.0f, 122150.0f, 123775.0f, 124100.0f, 124425.0f, 124750.0f, 125075.0f, 125400.0f, 713150.0f, 715350.0f, 717550.0f, 719750.0f, 721950.0f, 724150.0f, 735150.0f, 737350.0f, 739550.0f, 741750.0f, 743950.0f, 746150.0f, 757150.0f, 759350.0f, 761550.0f, 763750.0f, 765950.0f, 768150.0f, 779150.0f, 781350.0f, 783550.0f, 785750.0f, 787950.0f, 790150.0f, 801150.0f, 803350.0f, 805550.0f, 807750.0f, 809950.0f, 812150.0f, 823150.0f, 825350.0f, 827550.0f, 829750.0f, 831950.0f, 834150.0f, 404400.0f, 405350.0f, 406300.0f, 407250.0f, 408200.0f, 409150.0f, 413900.0f, 414850.0f, 415800.0f, 416750.0f, 417700.0f, 418650.0f, 423400.0f, 424350.0f, 425300.0f, 426250.0f, 427200.0f, 428150.0f, 432900.0f, 433850.0f, 434800.0f, 435750.0f, 436700.0f, 437650.0f, 442400.0f, 443350.0f, 444300.0f, 445250.0f, 446200.0f, 447150.0f, 451900.0f, 452850.0f, 453800.0f, 454750.0f, 455700.0f, 456650.0f, 1197525.0f, 1200350.0f, 1203175.0f, 1206000.0f, 1208825.0f, 1211650.0f, 1225775.0f, 1228600.0f, 1231425.0f, 1234250.0f, 1237075.0f, 1239900.0f, 1254025.0f, 1256850.0f, 1259675.0f, 1262500.0f, 1265325.0f, 1268150.0f, 1282275.0f, 1285100.0f, 1287925.0f, 1290750.0f, 1293575.0f, 1296400.0f, 1310525.0f, 1313350.0f, 1316175.0f, 1319000.0f, 1321825.0f, 1324650.0f, 1338775.0f, 1341600.0f, 1344425.0f, 1347250.0f, 1350075.0f, 1352900.0f, 826275.0f, 827850.0f, 829425.0f, 831000.0f, 832575.0f, 834150.0f, 842025.0f, 843600.0f, 845175.0f, 846750.0f, 848325.0f, 849900.0f, 857775.0f, 859350.0f, 860925.0f, 862500.0f, 864075.0f, 865650.0f, 873525.0f, 875100.0f, 876675.0f, 878250.0f, 879825.0f, 881400.0f, 889275.0f, 890850.0f, 892425.0f, 894000.0f, 895575.0f, 897150.0f, 905025.0f, 906600.0f, 908175.0f, 909750.0f, 911325.0f, 912900.0f, 1806900.0f, 1810350.0f, 1813800.0f, 1817250.0f, 1820700.0f, 1824150.0f, 1841400.0f, 1844850.0f, 1848300.0f, 1851750.0f, 1855200.0f, 1858650.0f, 1875900.0f, 1879350.0f, 1882800.0f, 1886250.0f, 1889700.0f, 1893150.0f, 1910400.0f, 1913850.0f, 1917300.0f, 1920750.0f, 1924200.0f, 1927650.0f, 1944900.0f, 1948350.0f, 1951800.0f, 1955250.0f, 1958700.0f, 1962150.0f, 1979400.0f, 1982850.0f, 1986300.0f, 1989750.0f, 1993200.0f, 1996650.}; Nd4jLong _expSFF[] = {4, 2, 6, 6, 6, 216, 36, 6, 1, typeid(TypeParam) == typeid(float) ? 8192 : 16384, 1, 99,}; NDArray expFF(_expBFF, _expSFF); TypeParam _exp2BFF[] = {827.4900282f, 832.2350283f, 836.9800284f, 841.725028f, 846.4700287f, 851.2150288f, 874.9400293f, 879.6850294f, 884.4300295f, 889.1750296f, 893.9200297f, 898.665029f, 922.3900304f, 927.1350305f, 931.8800306f, 936.6250307f, 941.3700308f, 946.1150309f, 969.8400315f, 974.5850316f, 979.3300317f, 984.0750318f, 988.8200319f, 993.5650320f, 1017.2900326f, 1022.0350327f, 1026.7800328f, 1031.5250329f, 1036.2700330f, 1041.0150331f, 1064.7400337f, 1069.4850338f, 1074.2300339f, 1078.9750340f, 1083.7200341f, 1088.4650342f, 1822.4550553f, 1833.995055f, 1845.5350558f, 1857.075056f, 1868.6150563f, 1880.1550566f, 1937.8550578f, 1949.3950581f, 1960.9350583f, 1972.4750586f, 1984.015058f, 1995.5550591f, 2053.2550604f, 2064.7950606f, 2076.3350609f, 2087.8750611f, 2099.4150614f, 2110.955061f, 2168.6550629f, 2180.1950632f, 2191.7350634f, 2203.2750637f, 2214.8150639f, 2226.3550642f, 2284.0550655f, 2295.5950657f, 2307.1350660f, 2318.6750662f, 2330.2150665f, 2341.7550667f, 2399.4550680f, 2410.9950683f, 2422.5350685f, 2434.0750688f, 2445.6150690f, 2457.1550693f, 2817.419968f, 2835.7549686f, 2854.0899683f, 2872.4249680f, 2890.7599677f, 2909.0949674f, 3000.7699660f, 3019.104965f, 3037.4399655f, 3055.7749652f, 3074.1099649f, 3092.4449646f, 3184.1199632f, 3202.4549629f, 3220.789962f, 3239.1249624f, 3257.4599621f, 3275.7949618f, 3367.4699604f, 3385.8049601f, 3404.1399598f, 3422.474959f, 3440.8099593f, 3459.1449590f, 3550.8199576f, 3569.1549573f, 3587.4899570f, 3605.8249567f, 3624.1599565f, 3642.4949562f, 3734.1699548f, 3752.5049545f, 3770.8399542f, 3789.1749539f, 3807.5099536f, 3825.8449534f, 3812.385098f, 3837.5150988f, 3862.6450994f, 3887.7751000f, 3912.9051006f, 3938.0351012f, 4063.6851041f, 4088.8151047f, 4113.9451053f, 4139.0751059f, 4164.2051065f, 4189.3351071f, 4314.9851100f, 4340.1151106f, 4365.2451112f, 4390.3751118f, 4415.5051124f, 4440.6351130f, 4566.2851159f, 4591.4151165f, 4616.5451171f, 4641.6751177f, 4666.805118f, 4691.9351188f, 4817.5851218f, 4842.7151224f, 4867.8451230f, 4892.975123f, 4918.1051241f, 4943.2351247f, 5068.8851277f, 5094.0151283f, 5119.1451288f, 5144.2751294f, 5169.4051300f, 5194.5351306f, 4807.3499803f, 4839.2749801f, 4871.1999799f, 4903.1249797f, 4935.0499795f, 4966.9749793f, 5126.5999784f, 5158.5249782f, 5190.4499780f, 5222.3749778f, 5254.2999777f, 5286.2249775f, 5445.8499765f, 5477.774976f, 5509.6999762f, 5541.6249760f, 5573.5499758f, 5605.4749756f, 5765.0999747f, 5797.0249745f, 5828.9499743f, 5860.8749741f, 5892.7999739f, 5924.724973f, 6084.3499728f, 6116.2749726f, 6148.1999724f, 6180.1249723f, 6212.0499721f, 6243.9749719f, 6403.59997f, 6435.5249708f, 6467.4499706f, 6499.3749704f, 6531.2999702f, 6563.2249700f, 5802.3150007f, 5841.0350006f, 5879.7550005f, 5918.4750004f, 5957.195000f, 5995.9150003f, 6189.5149999f, 6228.2349998f, 6266.9549997f, 6305.6749996f, 6344.3949995f, 6383.114999f, 6576.7149990f, 6615.4349990f, 6654.1549989f, 6692.8749988f, 6731.5949987f, 6770.3149986f, 6963.9149982f, 7002.6349981f, 7041.3549981f, 7080.0749980f, 7118.7949979f, 7157.5149978f, 7351.1149974f, 7389.8349973f, 7428.5549972f, 7467.2749972f, 7505.9949971f, 7544.7149970f, 7738.3149966f, 7777.0349965f, 7815.7549964f, 7854.4749963f, 7893.1949963f, 7931.9149962f, 6797.2799488f, 6842.794948f, 6888.3099489f, 6933.8249490f, 6979.3399491f, 7024.8549492f, 7252.4299497f, 7297.9449498f, 7343.4599499f, 7388.9749500f, 7434.489950f, 7480.0049501f, 7707.5799506f, 7753.0949507f, 7798.6099508f, 7844.1249509f, 7889.6399510f, 7935.1549511f, 8162.7299515f, 8208.2449516f, 8253.7599517f, 8299.2749518f, 8344.7899519f, 8390.3049520f, 8617.8799525f, 8663.394952f, 8708.9099526f, 8754.4249527f, 8799.9399528f, 8845.4549529f, 9073.0299534f, 9118.5449535f, 9164.0599536f, 9209.5749537f, 9255.089953f, 9300.604953f, 7792.2451647f, 7844.5551655f, 7896.8651663f, 7949.1751671f, 8001.4851679f, 8053.7951686f, 8315.3451725f, 8367.6551733f, 8419.9651741f, 8472.2751749f, 8524.585175f, 8576.8951764f, 8838.4451803f, 8890.7551811f, 8943.0651819f, 8995.3751827f, 9047.6851834f, 9099.9951842f, 9361.5451881f, 9413.8551889f, 9466.1651897f, 9518.475190f, 9570.7851912f, 9623.0951920f, 9884.6451959f, 9936.9551967f, 9989.2651975f, 10041.5751982f, 10093.8851990f, 10146.1951998f, 10407.7452037f, 10460.0552045f, 10512.3652053f, 10564.6752060f, 10616.9852068f, 10669.2952076f, 8787.210074f, 8846.3150748f, 8905.4200750f, 8964.5250752f, 9023.6300755f, 9082.7350757f, 9378.2600768f, 9437.3650770f, 9496.4700773f, 9555.5750775f, 9614.6800777f, 9673.7850779f, 9969.3100791f, 10028.4150793f, 10087.5200795f, 10146.625079f, 10205.7300800f, 10264.8350802f, 10560.3600813f, 10619.465081f, 10678.5700818f, 10737.6750820f, 10796.7800822f, 10855.8850825f, 11151.4100836f, 11210.5150838f, 11269.6200840f, 11328.7250843f, 11387.8300845f, 11446.9350847f, 11742.4600858f, 11801.5650861f, 11860.6700863f, 11919.7750865f, 11978.880086f, 12037.9850870f, 9782.1750935f, 9848.0750935f, 9913.9750934f, 9979.8750934f, 10045.7750934f, 10111.6750933f, 10441.1750931f, 10507.0750931f, 10572.9750931f, 10638.8750930f, 10704.7750930f, 10770.6750930f, 11100.1750928f, 11166.0750927f, 11231.9750927f, 11297.8750927f, 11363.7750926f, 11429.6750926f, 11759.1750924f, 11825.0750924f, 11890.9750923f, 11956.8750923f, 12022.7750923f, 12088.6750922f, 12418.175092f, 12484.0750920f, 12549.9750920f, 12615.8750919f, 12681.7750919f, 12747.6750919f, 13077.1750917f, 13143.0750916f, 13208.9750916f, 13274.8750916f, 13340.7750915f, 13406.6750915f, 2250.990060f, 2255.7350610f, 2260.4800611f, 2265.2250612f, 2269.9700613f, 2274.7150614f, 2298.4400619f, 2303.185062f, 2307.9300622f, 2312.6750623f, 2317.4200624f, 2322.1650625f, 2345.8900630f, 2350.6350631f, 2355.380063f, 2360.1250634f, 2364.8700635f, 2369.6150636f, 2393.3400641f, 2398.0850642f, 2402.8300643f, 2407.5750644f, 2412.320064f, 2417.0650647f, 2440.7900652f, 2445.5350653f, 2450.2800654f, 2455.0250655f, 2459.7700656f, 2464.515065f, 2488.2400663f, 2492.9850664f, 2497.7300665f, 2502.4750666f, 2507.2200667f, 2511.9650668f, 5284.4551315f, 5295.9951318f, 5307.535132f, 5319.0751323f, 5330.6151326f, 5342.1551328f, 5399.8551341f, 5411.3951343f, 5422.9351346f, 5434.475134f, 5446.0151351f, 5457.5551354f, 5515.2551366f, 5526.7951369f, 5538.3351371f, 5549.8751374f, 5561.4151376f, 5572.9551379f, 5630.6551392f, 5642.1951394f, 5653.7351397f, 5665.2751399f, 5676.8151402f, 5688.3551404f, 5746.0551417f, 5757.5951420f, 5769.1351422f, 5780.6751425f, 5792.2151427f, 5803.7551430f, 5861.455144f, 5872.9951445f, 5884.5351448f, 5896.0751450f, 5907.6151453f, 5919.1551455f, 8317.919884f, 8336.2548841f, 8354.5898838f, 8372.9248835f, 8391.2598832f, 8409.59488f, 8501.2698815f, 8519.6048813f, 8537.9398810f, 8556.2748807f, 8574.6098804f, 8592.9448801f, 8684.6198787f, 8702.9548784f, 8721.2898782f, 8739.6248779f, 8757.9598776f, 8776.2948773f, 8867.9698759f, 8886.3048756f, 8904.6398753f, 8922.9748751f, 8941.3098748f, 8959.6448745f, 9051.3198731f, 9069.6548728f, 9087.9898725f, 9106.3248722f, 9124.6598720f, 9142.9948717f, 9234.6698703f, 9253.0048700f, 9271.3398697f, 9289.6748694f, 9308.0098691f, 9326.3448689f, 11351.3852747f, 11376.5152753f, 11401.6452759f, 11426.7752765f, 11451.9052771f, 11477.0352777f, 11602.6852806f, 11627.8152812f, 11652.9452818f, 11678.0752824f, 11703.2052830f, 11728.335283f, 11853.9852865f, 11879.1152871f, 11904.2452877f, 11929.3752883f, 11954.505288f, 11979.6352894f, 12105.2852924f, 12130.4152930f, 12155.545293f, 12180.6752941f, 12205.8052947f, 12230.9352953f, 12356.5852983f, 12381.715298f, 12406.8452994f, 12431.9753000f, 12457.1053006f, 12482.2353012f, 12607.8853041f, 12633.0153047f, 12658.1453053f, 12683.2753059f, 12708.4053065f, 12733.5353071f, 14384.8499244f, 14416.7749242f, 14448.6999240f, 14480.6249238f, 14512.549923f, 14544.4749235f, 14704.0999225f, 14736.024922f, 14767.9499222f, 14799.8749220f, 14831.7999218f, 14863.7249216f, 15023.3499207f, 15055.2749205f, 15087.1999203f, 15119.1249201f, 15151.0499199f, 15182.9749197f, 15342.5999188f, 15374.5249186f, 15406.4499184f, 15438.374918f, 15470.2999181f, 15502.2249179f, 15661.84991f, 15693.7749168f, 15725.6999166f, 15757.6249164f, 15789.5499162f, 15821.4749160f, 15981.0999151f, 16013.0249149f, 16044.9499147f, 16076.8749145f, 16108.7999143f, 16140.7249142f, 17418.314976f, 17457.0349761f, 17495.7549760f, 17534.4749759f, 17573.1949758f, 17611.9149757f, 17805.5149753f, 17844.234975f, 17882.9549752f, 17921.6749751f, 17960.3949750f, 17999.1149749f, 18192.7149745f, 18231.4349744f, 18270.154974f, 18308.8749743f, 18347.5949742f, 18386.3149741f, 18579.9149737f, 18618.6349736f, 18657.3549735f, 18696.074973f, 18734.7949734f, 18773.5149733f, 18967.1149729f, 19005.8349728f, 19044.5549727f, 19083.2749726f, 19121.994972f, 19160.7149725f, 19354.3149721f, 19393.0349720f, 19431.7549719f, 19470.4749718f, 19509.1949717f, 19547.914971f, 20451.7799765f, 20497.2949766f, 20542.8099767f, 20588.3249768f, 20633.8399769f, 20679.3549770f, 20906.929977f, 20952.4449775f, 20997.9599776f, 21043.4749777f, 21088.9899778f, 21134.5049779f, 21362.0799784f, 21407.5949785f, 21453.1099786f, 21498.624978f, 21544.139978f, 21589.6549788f, 21817.2299793f, 21862.7449794f, 21908.2599795f, 21953.7749796f, 21999.2899797f, 22044.8049798f, 22272.3799802f, 22317.8949803f, 22363.4099804f, 22408.9249805f, 22454.4399806f, 22499.9549807f, 22727.529981f, 22773.044981f, 22818.5599813f, 22864.0749814f, 22909.5899815f, 22955.1049816f, 23485.2453985f, 23537.555399f, 23589.8654000f, 23642.1754008f, 23694.4854016f, 23746.7954024f, 24008.3454063f, 24060.655407f, 24112.9654078f, 24165.2754086f, 24217.5854094f, 24269.8954102f, 24531.4454141f, 24583.7554148f, 24636.0654156f, 24688.3754164f, 24740.6854172f, 24792.99541f, 25054.545421f, 25106.8554226f, 25159.1654234f, 25211.4754242f, 25263.7854250f, 25316.0954257f, 25577.6454296f, 25629.9554304f, 25682.2654312f, 25734.5754320f, 25786.8854328f, 25839.1954335f, 26100.7454374f, 26153.0554382f, 26205.3654390f, 26257.6754398f, 26309.985440f, 26362.2954413f, 26518.7101423f, 26577.8151425f, 26636.920142f, 26696.0251430f, 26755.1301432f, 26814.2351434f, 27109.7601446f, 27168.8651448f, 27227.9701450f, 27287.0751452f, 27346.1801455f, 27405.2851457f, 27700.8101468f, 27759.9151470f, 27819.0201473f, 27878.1251475f, 27937.2301477f, 27996.33514f, 28291.8601491f, 28350.9651493f, 28410.0701495f, 28469.175149f, 28528.2801500f, 28587.3851502f, 28882.9101513f, 28942.0151516f, 29001.1201518f, 29060.2251520f, 29119.3301522f, 29178.4351525f, 29473.9601536f, 29533.0651538f, 29592.1701540f, 29651.2751543f, 29710.3801545f, 29769.4851547f, 29552.1750826f, 29618.0750825f, 29683.9750825f, 29749.8750825f, 29815.7750824f, 29881.6750824f, 30211.1750822f, 30277.0750822f, 30342.9750821f, 30408.8750821f, 30474.7750821f, 30540.6750820f, 30870.175081f, 30936.0750818f, 31001.9750818f, 31067.8750817f, 31133.7750817f, 31199.6750817f, 31529.1750815f, 31595.075081f, 31660.9750814f, 31726.8750814f, 31792.7750813f, 31858.6750813f, 32188.1750811f, 32254.0750811f, 32319.975081f, 32385.8750810f, 32451.7750810f, 32517.6750809f, 32847.1750808f, 32913.0750807f, 32978.9750807f, 33044.875080f, 33110.7750806f, 33176.67508062}; Nd4jLong _exp2SFF[] = {4, 2, 10, 6, 6, 360, 36, 6, 1, typeid(TypeParam) == typeid(float) ? 8192 : 16384, 1, 99,}; NDArray exp2FF(_exp2BFF, _exp2SFF); auto input = NDArrayFactory::create<TypeParam>('c', {2, 3, 10, 10}); auto weightsD = NDArrayFactory::create<TypeParam>('c', {2, 3, 5, 5}); auto weightsP = NDArrayFactory::create<TypeParam>('c', {10, 6, 1, 1}); input.linspace(1); weightsD.linspace(1); weightsP.linspace(1); weightsD.permutei({2,3,1,0}); weightsP.permutei({2,3,1,0}); weightsP.applyScalar(scalar::Divide, 10000.0); nd4j::ops::sconv2d op; auto resultFF = op.execute({&input, &weightsD}, {}, {5, 5, 1, 1, 0, 0, 1, 1, 0}, {}); auto z = resultFF->at(0); ASSERT_TRUE(z->isSameShape(&expFF)); ASSERT_TRUE(z->equalsTo(&expFF, 1)); nd4j::ops::conv2d op2d; weightsP.printShapeInfo(); auto result2D = op2d.execute({z, &weightsP}, {}, {1, 1, 1, 1, 0, 0, 1, 1, 0, 0}, {}); auto z2d = result2D->at(0); ASSERT_TRUE(z2d->isSameShape(&exp2FF)); ASSERT_TRUE(z2d->equalsTo(&exp2FF)); delete resultFF; delete result2D; } TYPED_TEST(TypedConvolutionTests1, sconv2D_FF_pointwise_1) { TypeParam _expBFF[] = {108.9405008, 109.5920008, 110.2435008, 110.8950008, 111.5465008, 112.1980008, 115.4555008, 116.1070008, 116.7585008, 117.410000, 118.061500, 118.7130009, 121.9705009, 122.6220009, 123.2735009, 123.9250009, 124.5765009, 125.2280009, 128.4855009, 129.1370009, 129.7885009, 130.4400009, 131.09150, 131.74300, 135.0005010, 135.6520010, 136.3035010, 136.9550010, 137.6065010, 138.2580010, 141.5155010, 142.1670010, 142.8185010, 143.4700010, 144.1215010, 144.7730010, 248.9617514, 250.670751, 252.3797515, 254.0887515, 255.7977515, 257.5067515, 266.0517515, 267.7607515, 269.469751, 271.1787516, 272.8877516, 274.5967516, 283.1417516, 284.8507516, 286.5597516, 288.268751, 289.9777517, 291.6867517, 300.2317517, 301.9407517, 303.6497517, 305.3587517, 307.067751, 308.7767518, 317.3217518, 319.0307518, 320.7397518, 322.4487518, 324.157751, 325.866751, 334.4117519, 336.1207519, 337.8297519, 339.5387519, 341.2477519, 342.95675, 388.9829964, 391.7494964, 394.5159964, 397.2824964, 400.048996, 402.8154963, 416.647996, 419.4144962, 422.1809962, 424.9474962, 427.7139962, 430.4804962, 444.3129961, 447.0794961, 449.8459961, 452.6124960, 455.3789960, 458.1454960, 471.9779959, 474.7444959, 477.5109959, 480.2774959, 483.0439959, 485.8104958, 499.6429958, 502.4094957, 505.1759957, 507.9424957, 510.7089957, 513.4754957, 527.3079956, 530.0744956, 532.8409956, 535.607495, 538.3739955, 541.1404955, 529.0042487, 532.8282487, 536.6522487, 540.4762487, 544.3002487, 548.1242487, 567.2442487, 571.068248, 574.892248, 578.716248, 582.540248, 586.3642486, 605.4842486, 609.3082486, 613.1322486, 616.9562486, 620.7802486, 624.6042486, 643.7242486, 647.5482486, 651.3722486, 655.1962486, 659.0202486, 662.8442486, 681.9642486, 685.7882486, 689.6122486, 693.4362486, 697.2602486, 701.0842486, 720.2042486, 724.0282486, 727.852248, 731.676248, 735.500248, 739.324248, 669.0255044, 673.9070044, 678.7885044, 683.6700044, 688.5515044, 693.4330044, 717.8405044, 722.7220044, 727.6035044, 732.4850044, 737.3665044, 742.2480044, 766.6555043, 771.5370043, 776.4185043, 781.3000043, 786.1815043, 791.0630043, 815.4705043, 820.3520043, 825.2335043, 830.1150043, 834.9965043, 839.8780043, 864.2855042, 869.1670042, 874.0485042, 878.9300042, 883.8115042, 888.6930042, 913.1005042, 917.9820042, 922.8635042, 927.7450042, 932.6265042, 937.5080042, 809.0467424, 814.9857424, 820.9247424, 826.8637423, 832.8027423, 838.7417423, 868.4367421, 874.3757421, 880.3147420, 886.2537420, 892.1927420, 898.13174, 927.8267418, 933.7657418, 939.7047417, 945.6437417, 951.5827417, 957.5217416, 987.2167415, 993.155741, 999.0947414, 1005.0337414, 1010.972741, 1016.9117413, 1046.6067412, 1052.5457411, 1058.4847411, 1064.4237411, 1070.3627410, 1076.3017410, 1105.996740, 1111.9357408, 1117.8747408, 1123.8137408, 1129.7527407, 1135.6917407, 949.0679815, 956.0644814, 963.060981, 970.0574813, 977.0539812, 984.0504811, 1019.0329807, 1026.0294807, 1033.0259806, 1040.0224805, 1047.0189804, 1054.0154804, 1088.9979800, 1095.9944799, 1102.9909798, 1109.987479, 1116.9839797, 1123.9804796, 1158.9629792, 1165.9594791, 1172.9559791, 1179.9524790, 1186.9489789, 1193.9454788, 1228.9279785, 1235.9244784, 1242.9209783, 1249.9174782, 1256.913978, 1263.9104781, 1298.8929777, 1305.8894776, 1312.8859775, 1319.8824775, 1326.8789774, 1333.8754773, 1089.0892560, 1097.1432561, 1105.1972562, 1113.251256, 1121.3052563, 1129.3592564, 1169.6292568, 1177.6832568, 1185.7372569, 1193.7912570, 1201.845257, 1209.8992571, 1250.1692575, 1258.2232576, 1266.2772576, 1274.3312577, 1282.3852578, 1290.4392579, 1330.7092582, 1338.7632583, 1346.8172584, 1354.8712584, 1362.9252585, 1370.9792586, 1411.24925, 1419.3032590, 1427.3572591, 1435.4112592, 1443.465259, 1451.5192593, 1491.7892597, 1499.8432598, 1507.8972598, 1515.9512599, 1524.0052600, 1532.059260, 1229.1105073, 1238.2220073, 1247.3335073, 1256.4450073, 1265.5565073, 1274.668007, 1320.2255074, 1329.3370074, 1338.4485074, 1347.5600075, 1356.6715075, 1365.7830075, 1411.340507, 1420.4520076, 1429.5635076, 1438.6750076, 1447.7865076, 1456.8980076, 1502.4555077, 1511.5670077, 1520.6785077, 1529.7900077, 1538.9015077, 1548.013007, 1593.5705078, 1602.6820078, 1611.793507, 1620.9050079, 1630.0165079, 1639.1280079, 1684.6855080, 1693.7970080, 1702.9085080, 1712.0200080, 1721.1315080, 1730.2430080, 1369.1317613, 1379.3007614, 1389.4697614, 1399.6387615, 1409.8077615, 1419.976761, 1470.8217618, 1480.9907618, 1491.159761, 1501.3287619, 1511.4977619, 1521.6667620, 1572.5117622, 1582.6807622, 1592.8497623, 1603.0187623, 1613.1877624, 1623.3567624, 1674.2017626, 1684.3707627, 1694.5397627, 1704.7087628, 1714.8777628, 1725.046762, 1775.8917631, 1786.0607631, 1796.229763, 1806.3987632, 1816.5677632, 1826.7367633, 1877.5817635, 1887.7507635, 1897.9197636, 1908.0887636, 1918.2577637, 1928.4267637, 304.3905022, 305.0420022, 305.6935022, 306.3450022, 306.9965022, 307.6480022, 310.9055022, 311.5570022, 312.208502, 312.860002, 313.5115023, 314.1630023, 317.4205023, 318.0720023, 318.7235023, 319.3750023, 320.0265023, 320.6780023, 323.9355023, 324.5870023, 325.2385023, 325.8900023, 326.541502, 327.193002, 330.4505024, 331.1020024, 331.7535024, 332.4050024, 333.0565024, 333.7080024, 336.9655024, 337.6170024, 338.2685024, 338.9200024, 339.5715024, 340.223002, 761.6617542, 763.3707542, 765.0797542, 766.7887542, 768.4977542, 770.206754, 778.7517543, 780.4607543, 782.1697543, 783.8787543, 785.5877543, 787.2967543, 795.8417544, 797.5507544, 799.2597544, 800.9687544, 802.6777544, 804.3867544, 812.9317545, 814.6407545, 816.3497545, 818.0587545, 819.7677545, 821.4767545, 830.0217546, 831.7307546, 833.4397546, 835.1487546, 836.8577546, 838.5667546, 847.1117547, 848.8207547, 850.5297547, 852.2387547, 853.9477547, 855.6567547, 1218.9329915, 1221.6994915, 1224.4659915, 1227.232491, 1229.9989914, 1232.7654914, 1246.5979913, 1249.3644913, 1252.1309913, 1254.8974913, 1257.6639913, 1260.430491, 1274.2629912, 1277.029491, 1279.7959911, 1282.5624911, 1285.3289911, 1288.0954911, 1301.9279910, 1304.6944910, 1307.4609910, 1310.22749, 1312.9939909, 1315.7604909, 1329.5929908, 1332.3594908, 1335.1259908, 1337.8924908, 1340.6589908, 1343.4254908, 1357.2579907, 1360.0244907, 1362.7909906, 1365.5574906, 1368.3239906, 1371.0904906, 1676.2042479, 1680.0282479, 1683.8522479, 1687.6762479, 1691.5002479, 1695.3242479, 1714.4442479, 1718.2682479, 1722.0922479, 1725.9162479, 1729.7402479, 1733.5642479, 1752.6842479, 1756.5082479, 1760.3322479, 1764.1562479, 1767.9802479, 1771.8042479, 1790.9242479, 1794.7482479, 1798.5722479, 1802.3962479, 1806.2202479, 1810.044247, 1829.1642478, 1832.9882478, 1836.8122478, 1840.6362478, 1844.4602478, 1848.2842478, 1867.4042478, 1871.2282478, 1875.0522478, 1878.8762478, 1882.7002478, 1886.5242478, 2133.4755029, 2138.3570029, 2143.2385029, 2148.1200029, 2153.0015029, 2157.8830029, 2182.2905028, 2187.1720028, 2192.0535028, 2196.9350028, 2201.8165028, 2206.6980028, 2231.1055028, 2235.9870028, 2240.8685028, 2245.7500028, 2250.6315028, 2255.5130028, 2279.9205027, 2284.8020027, 2289.6835027, 2294.5650027, 2299.4465027, 2304.3280027, 2328.7355027, 2333.6170027, 2338.4985027, 2343.3800027, 2348.2615027, 2353.1430027, 2377.5505026, 2382.4320026, 2387.3135026, 2392.1950026, 2397.0765026, 2401.9580026, 2590.7467330, 2596.6857330, 2602.6247329, 2608.5637329, 2614.5027329, 2620.441732, 2650.1367327, 2656.0757327, 2662.0147326, 2667.9537326, 2673.8927326, 2679.8317325, 2709.5267324, 2715.465732, 2721.4047323, 2727.3437323, 2733.282732, 2739.2217322, 2768.9167321, 2774.8557320, 2780.7947320, 2786.7337320, 2792.6727319, 2798.6117319, 2828.306731, 2834.2457317, 2840.1847317, 2846.1237317, 2852.0627316, 2858.0017316, 2887.6967314, 2893.6357314, 2899.5747314, 2905.5137313, 2911.4527313, 2917.3917313, 3048.0179587, 3055.0144586, 3062.0109585, 3069.0074584, 3076.0039584, 3083.0004583, 3117.9829579, 3124.9794578, 3131.9759578, 3138.9724577, 3145.9689576, 3152.9654575, 3187.947957, 3194.9444571, 3201.9409570, 3208.9374569, 3215.933956, 3222.9304568, 3257.9129564, 3264.9094563, 3271.9059562, 3278.9024562, 3285.8989561, 3292.8954560, 3327.8779556, 3334.874455, 3341.8709555, 3348.8674554, 3355.8639553, 3362.860455, 3397.8429549, 3404.8394548, 3411.8359547, 3418.8324546, 3425.8289546, 3432.8254545, 3505.28927, 3513.3432780, 3521.3972781, 3529.4512782, 3537.5052782, 3545.5592783, 3585.8292787, 3593.8832788, 3601.9372788, 3609.9912789, 3618.0452790, 3626.099279, 3666.3692794, 3674.4232795, 3682.4772796, 3690.5312796, 3698.5852797, 3706.6392798, 3746.9092801, 3754.9632802, 3763.0172803, 3771.0712804, 3779.1252804, 3787.1792805, 3827.4492809, 3835.50328, 3843.5572810, 3851.6112811, 3859.6652812, 3867.7192812, 3907.9892816, 3916.0432817, 3924.097281, 3932.1512818, 3940.2052819, 3948.2592820, 3962.5605113, 3971.6720113, 3980.783511, 3989.8950114, 3999.0065114, 4008.1180114, 4053.6755115, 4062.7870115, 4071.8985115, 4081.0100115, 4090.1215115, 4099.2330115, 4144.7905116, 4153.9020116, 4163.0135116, 4172.1250116, 4181.236511, 4190.3480117, 4235.9055117, 4245.0170117, 4254.128511, 4263.2400118, 4272.3515118, 4281.4630118, 4327.0205119, 4336.1320119, 4345.2435119, 4354.3550119, 4363.4665119, 4372.5780119, 4418.1355120, 4427.2470120, 4436.3585120, 4445.4700120, 4454.581512, 4463.6930121, 4419.8317743, 4430.0007744, 4440.1697744, 4450.338774, 4460.5077745, 4470.6767745, 4521.521774, 4531.6907748, 4541.8597748, 4552.0287749, 4562.1977749, 4572.3667750, 4623.2117752, 4633.3807752, 4643.5497753, 4653.7187753, 4663.8877754, 4674.0567754, 4724.9017756, 4735.0707757, 4745.2397757, 4755.4087757, 4765.5777758, 4775.7467758, 4826.591776, 4836.7607761, 4846.9297761, 4857.0987762, 4867.2677762, 4877.4367763, 4928.2817765, 4938.4507765, 4948.6197766, 4958.7887766, 4968.957776, 4979.12677675}; Nd4jLong _expSFF[] = {4, 2, 10, 6, 6, 360, 36, 6, 1, typeid(TypeParam) == typeid(float) ? 8192 : 16384, 1, 99,}; NDArray expFF(_expBFF, _expSFF); auto input = NDArrayFactory::create<TypeParam>('c', {2, 3, 10, 10}); auto weightsD = NDArrayFactory::create<TypeParam>('c', {5, 3, 5, 5}); auto weightsP = NDArrayFactory::create<TypeParam>('c', {10, 15, 1, 1}); input.linspace(1); weightsD.linspace(1); weightsP.linspace(1); weightsD.permutei({2,3,1,0}); weightsP.permutei({2,3,1,0}); input.applyScalar(scalar::Divide, 100.0); weightsD.applyScalar(scalar::Divide, 100.0); weightsP.applyScalar(scalar::Divide, 100.0); nd4j::ops::sconv2d op; auto resultFF = op.execute({&input, &weightsD, &weightsP}, {}, {5, 5, 1, 1, 0, 0, 1, 1, 0, 0}, {}); auto z = resultFF->at(0); //z->printShapeInfo("FF shape"); ASSERT_TRUE(z->isSameShape(&expFF)); //expFF.printBuffer("e"); //z->printBuffer("z"); ASSERT_TRUE(z->equalsTo(&expFF, 1e-3)); delete resultFF; } TYPED_TEST(TypedConvolutionTests1, sconv2D_BP_pointwise_1) { TypeParam _expGradWpB[] = {1603.7102981f, 10645.6278024f, 5975.4227995f, 17697.0903052f, 12133.6353024f, 26535.0528052f, 1779.221097f, 11795.5686029f, 6721.9835994f, 19904.0811062f, 13775.2461029f, 30123.0936062f, 1954.7318976f, 12945.5094033f, 7468.5443993f, 22111.071907f, 15416.8569033f, 33711.134407f, 2130.2426974f, 14095.4502038f, 8215.1051992f, 24318.0627081f, 17058.4677038f, 37299.1752081f, 2305.7534972f, 15245.3910042f, 8961.6659991f, 26525.0535091f, 18700.0785042f, 40887.2160091f, 2481.2642970f, 16395.3318047f, 9708.2267991f, 28732.0443100f, 20341.6893047f, 44475.2568100f, 2656.7750968f, 17545.2726051f, 10454.7875990f, 30939.0351110f, 21983.3001051f, 48063.2976110f, 2832.2858966f, 18695.2134056f, 11201.3483989f, 33146.0259119f, 23624.9109056f, 51651.3384119f, 3007.7966964f, 19845.1542060f, 11947.9091988f, 35353.0167129f, 25266.5217060f, 55239.3792129f, 3183.3074962f, 20995.095006f, 12694.4699987f, 37560.007513f, 26908.132506f, 58827.4200139}; Nd4jLong _expGradWpS[] {4, 10, 6, 1, 1, 6, 1, 1, 1, typeid(TypeParam) == typeid(float) ? 8192 : 16384, 1, 99}; NDArray expGWP(_expGradWpB, _expGradWpS); expGWP.permutei({2,3,1,0}); TypeParam _expGradWdB[] = {2074.21032f, 2082.76104f, 2091.31176f, 2099.86248f, 2108.4132f, 2159.71752f, 2168.26824f, 2176.81896f, 2185.36968f, 2193.9204f, 2245.22472f, 2253.77544f, 2262.32616f, 2270.87688f, 2279.4276f, 2330.73192f, 2339.28264f, 2347.83336f, 2356.38408f, 2364.9348f, 2416.23912f, 2424.78984f, 2433.34056f, 2441.89128f, 2450.442f, 3112.99344f, 3122.06328f, 3131.13312f, 3140.20296f, 3149.2728f, 3203.69184f, 3212.76168f, 3221.83152f, 3230.90136f, 3239.9712f, 3294.39024f, 3303.46008f, 3312.52992f, 3321.59976f, 3330.6696f, 3385.08864f, 3394.15848f, 3403.22832f, 3412.29816f, 3421.368f, 3475.78704f, 3484.85688f, 3493.92672f, 3502.99656f, 3512.0664f, 4255.60056f, 4265.18952f, 4274.77848f, 4284.36744f, 4293.9564f, 4351.49016f, 4361.07912f, 4370.66808f, 4380.25704f, 4389.846f, 4447.37976f, 4456.96872f, 4466.55768f, 4476.14664f, 4485.7356f, 4543.26936f, 4552.85832f, 4562.44728f, 4572.03624f, 4581.6252f, 4639.15896f, 4648.74792f, 4658.33688f, 4667.92584f, 4677.5148f, 2140.10988f, 2148.92016f, 2157.73044f, 2166.54072f, 2175.351f, 2228.21268f, 2237.02296f, 2245.83324f, 2254.64352f, 2263.4538f, 2316.31548f, 2325.12576f, 2333.93604f, 2342.74632f, 2351.5566f, 2404.41828f, 2413.22856f, 2422.03884f, 2430.84912f, 2439.6594f, 2492.52108f, 2501.33136f, 2510.14164f, 2518.95192f, 2527.7622f, 3204.849f, 3214.1784f, 3223.5078f, 3232.8372f, 3242.1666f, 3298.143f, 3307.4724f, 3316.8018f, 3326.1312f, 3335.4606f, 3391.437f, 3400.7664f, 3410.0958f, 3419.4252f, 3428.7546f, 3484.731f, 3494.0604f, 3503.3898f, 3512.7192f, 3522.0486f, 3578.025f, 3587.3544f, 3596.6838f, 3606.0132f, 3615.3426f, 4373.41212f, 4383.26064f, 4393.10916f, 4402.95768f, 4412.8062f, 4471.89732f, 4481.74584f, 4491.59436f, 4501.44288f, 4511.2914f, 4570.38252f, 4580.23104f, 4590.07956f, 4599.92808f, 4609.7766f, 4668.86772f, 4678.71624f, 4688.56476f, 4698.41328f, 4708.2618f, 4767.35292f, 4777.20144f, 4787.04996f, 4796.89848f, 4806.747}; Nd4jLong _expGradWdS[] = {4, 2, 3, 5, 5, 75, 25, 5, 1, typeid(TypeParam) == typeid(float) ? 8192 : 16384, 1, 99}; NDArray expGWD(_expGradWdB, _expGradWdS); expGWD.permutei({2,3,1,0}); TypeParam _expEB[] = {5.0103f, 10.17147f, 15.48408f, 20.9487f, 26.5659f, 26.6832f, 21.65628f, 16.47507f, 11.139f, 5.6475f, 10.79727f, 21.90255f, 33.31698f, 45.0417f, 57.07785f, 57.3267f, 46.49334f, 35.34513f, 23.88093f, 12.0996f, 17.37801f, 35.22744f, 53.55f, 72.3474f, 91.62135f, 92.016f, 74.57958f, 56.66148f, 38.25999f, 19.3734f, 24.76962f, 50.18034f, 76.23444f, 102.9342f, 130.2819f, 130.8366f, 105.9834f, 80.47542f, 54.31038f, 27.486f, 32.9892f, 66.79545f, 101.4216f, 136.8705f, 173.145f, 173.874f, 140.7732f, 106.83825f, 72.0663f, 36.4545f, 33.8298f, 68.49375f, 103.9947f, 140.3355f, 177.519f, 178.248f, 144.3066f, 109.51395f, 73.8672f, 37.3635f, 28.85658f, 58.39302f, 88.6116f, 119.5146f, 151.1043f, 151.716f, 122.76444f, 93.11934f, 62.77842f, 31.7394f, 23.00409f, 46.52748f, 70.57188f, 95.139f, 120.23055f, 120.7107f, 97.6311f, 74.02194f, 49.88151f, 25.2081f, 16.25523f, 32.86293f, 49.82424f, 67.1403f, 84.81225f, 85.1466f, 68.83818f, 52.17045f, 35.14227f, 17.7525f, 8.5929f, 17.36517f, 26.31738f, 35.4501f, 44.7639f, 44.9382f, 36.31728f, 27.51357f, 18.5265f, 9.3555f, 8.63807f, 17.45032f, 26.43736f, 35.5998f, 44.93825f, 45.1399f, 36.46882f, 27.6199f, 18.59253f, 9.3861f, 18.18615f, 36.72737f, 55.62488f, 74.8799f, 94.49365f, 94.9122f, 76.65698f, 58.03937f, 39.05815f, 19.7121f, 28.66254f, 57.86775f, 87.61746f, 117.9135f, 148.7577f, 149.4084f, 120.63768f, 91.31331f, 61.43346f, 30.9963f, 40.08554f, 80.90806f, 122.47f, 164.7738f, 207.8219f, 208.72f, 168.48412f, 127.49662f, 85.75506f, 43.257f, 52.47345f, 105.8849f, 160.2374f, 215.534f, 271.77775f, 272.9385f, 220.2695f, 166.6442f, 112.05955f, 56.5125f, 53.82975f, 108.6158f, 164.3612f, 221.069f, 278.74225f, 279.903f, 225.8777f, 170.8778f, 114.90025f, 57.942f, 45.14002f, 91.0585f, 137.75788f, 185.2406f, 233.5091f, 234.4682f, 189.16564f, 143.06998f, 96.17878f, 48.4896f, 35.43048f, 71.45487f, 108.075f, 145.2927f, 183.1098f, 183.852f, 148.29504f, 112.13319f, 75.36462f, 37.9875f, 24.68283f, 49.76831f, 75.25766f, 101.1521f, 127.45285f, 127.9629f, 103.1927f, 78.01253f, 52.42117f, 26.4174f, 12.87877f, 25.96222f, 39.25096f, 52.7456f, 66.44675f, 66.7094f, 53.78542f, 40.6531f, 27.31183f, 13.761f, 12.59184f, 25.38317f, 38.37464f, 51.5669f, 64.9606f, 65.2566f, 52.61336f, 39.76673f, 26.71606f, 13.4607f, 26.23903f, 52.88419f, 79.93678f, 107.3981f, 135.26945f, 135.8777f, 109.53262f, 82.77361f, 55.59937f, 28.0086f, 40.96107f, 82.54206f, 124.74492f, 167.5716f, 211.02405f, 211.9608f, 170.83578f, 129.07914f, 86.68893f, 43.6632f, 56.77746f, 114.39578f, 172.85756f, 232.1654f, 292.3219f, 293.6034f, 236.60084f, 178.74182f, 120.02374f, 60.444f, 73.7077f, 148.48435f, 224.3332f, 301.2575f, 379.2605f, 380.903f, 306.9058f, 231.82015f, 155.6428f, 78.3705f, 75.6397f, 152.36785f, 230.1877f, 309.1025f, 389.1155f, 390.758f, 314.8288f, 237.79165f, 159.6433f, 80.3805f, 62.89546f, 126.67598f, 191.34416f, 256.9026f, 323.3539f, 324.7004f, 261.56684f, 197.53262f, 132.59514f, 66.7518f, 48.97887f, 98.63226f, 148.96212f, 199.9704f, 251.65905f, 252.6933f, 203.53098f, 153.68244f, 103.14573f, 51.9189f, 33.87043f, 68.19769f, 102.98308f, 138.2279f, 173.93345f, 174.6392f, 140.64322f, 106.18261f, 71.25607f, 35.8623f, 17.55064f, 35.33327f, 53.34854f, 71.5971f, 90.0796f, 90.4406f, 72.82556f, 54.97463f, 36.88716f, 18.5625f, 13.0455f, 26.44707f, 40.20528f, 54.3207f, 68.7939f, 68.9112f, 55.84908f, 42.42747f, 28.6458f, 14.5035f, 27.89367f, 56.50575f, 85.83738f, 115.8897f, 146.66385f, 146.9127f, 118.98294f, 90.32793f, 60.94653f, 30.8376f, 44.56161f, 90.21024f, 136.9476f, 184.7754f, 233.69535f, 234.09f, 189.46998f, 143.75268f, 96.93639f, 49.0194f, 63.06642f, 127.59474f, 193.58724f, 261.0462f, 329.9739f, 330.5286f, 267.3786f, 202.75302f, 136.64958f, 69.066f, 83.4252f, 168.69345f, 255.8076f, 344.7705f, 435.585f, 436.314f, 352.7772f, 267.38025f, 180.1203f, 90.9945f, 84.2658f, 170.39175f, 258.3807f, 348.2355f, 439.959f, 440.688f, 356.3106f, 270.05595f, 181.9212f, 91.9035f, 71.25738f, 144.01542f, 218.2764f, 294.0426f, 371.3163f, 371.928f, 300.57564f, 227.70894f, 153.32562f, 77.4234f, 56.34369f, 113.82228f, 172.43748f, 232.191f, 293.08455f, 293.5647f, 237.1455f, 179.58114f, 120.86991f, 61.0101f, 39.50763f, 79.77813f, 120.81264f, 162.6123f, 205.17825f, 205.5126f, 165.95178f, 125.62125f, 84.51987f, 42.6465f, 20.7321f, 41.84877f, 63.35058f, 85.2381f, 107.5119f, 107.6862f, 86.92608f, 65.77797f, 44.2413f, 22.3155f, 22.71767f, 45.82912f, 69.33496f, 93.2358f, 117.53225f, 117.7339f, 94.98322f, 71.8351f, 48.28893f, 24.3441f, 47.44335f, 95.68097f, 144.71408f, 194.5439f, 245.17165f, 245.5902f, 198.07778f, 149.76377f, 100.64695f, 50.7261f, 74.19534f, 149.59215f, 226.19226f, 303.9975f, 383.0097f, 383.6604f, 309.35688f, 233.84091f, 157.11066f, 79.1643f, 102.99194f, 207.59926f, 313.8244f, 421.6698f, 531.1379f, 532.036f, 428.89372f, 324.12142f, 217.71666f, 109.677f, 133.85145f, 269.7389f, 407.6654f, 547.634f, 689.64775f, 690.8085f, 556.7615f, 420.6602f, 282.50155f, 142.2825f, 135.20775f, 272.4698f, 411.7892f, 553.169f, 696.61225f, 697.773f, 562.3697f, 424.8938f, 285.34225f, 143.712f, 112.43842f, 226.5337f, 342.28828f, 459.7046f, 578.7851f, 579.7442f, 467.14324f, 352.87078f, 236.92438f, 119.3016f, 87.55128f, 176.35527f, 266.4138f, 357.7287f, 450.3018f, 451.044f, 363.36624f, 274.42479f, 184.21782f, 92.7435f, 60.52803f, 121.89791f, 184.11086f, 247.1681f, 311.07085f, 311.5809f, 250.9655f, 189.50093f, 127.18597f, 64.0194f, 31.35037f, 63.12502f, 95.32456f, 127.9496f, 161.00075f, 161.2634f, 129.86782f, 98.0443f, 65.79223f, 33.111f, 33.43584f, 67.30517f, 101.60864f, 136.3469f, 171.5206f, 171.8166f, 138.32936f, 104.40473f, 70.04206f, 35.2407f, 69.09703f, 139.06819f, 209.91478f, 281.6381f, 354.23945f, 354.8477f, 285.64462f, 215.55961f, 144.59137f, 72.7386f, 107.00307f, 215.32806f, 324.97692f, 435.9516f, 548.25405f, 549.1908f, 442.02378f, 333.52314f, 223.68693f, 112.5132f, 147.17346f, 296.12378f, 446.85356f, 599.3654f, 753.6619f, 754.9434f, 607.54484f, 458.35382f, 307.36774f, 154.584f, 189.6277f, 381.49435f, 575.6032f, 771.9575f, 970.5605f, 972.203f, 782.2858f, 590.11015f, 395.6728f, 198.9705f, 191.5597f, 385.37785f, 581.4577f, 779.8025f, 980.4155f, 982.058f, 790.2088f, 596.08165f, 399.6733f, 200.9805f, 157.97146f, 317.76398f, 479.38016f, 642.8226f, 808.0939f, 809.4404f, 651.23084f, 491.18462f, 329.29914f, 165.5718f, 122.04087f, 245.45826f, 370.25412f, 496.4304f, 623.98905f, 625.0233f, 502.79898f, 379.18644f, 254.18373f, 127.7889f, 83.74843f, 168.42169f, 254.02108f, 340.5479f, 428.00345f, 428.7092f, 344.83522f, 260.02861f, 174.28807f, 87.6123f, 43.07464f, 86.61527f, 130.62254f, 175.0971f, 220.0396f, 220.4006f, 177.26156f, 133.65263f, 89.57316f, 45.0225f }; Nd4jLong _expES[] = {4, 2, 3, 10, 10, 300, 100, 10, 1, typeid(TypeParam) == typeid(float) ? 8192 : 16384, 1, 99}; NDArray expE(_expEB, _expES); auto input = NDArrayFactory::create<TypeParam>('c', {2, 3, 10, 10}); auto weightsD = NDArrayFactory::create<TypeParam>('c', {2, 3, 5, 5}); auto weightsP = NDArrayFactory::create<TypeParam>('c', {10, 6, 1, 1}); auto epsilon = NDArrayFactory::create<TypeParam>('c', {2, 3, 10, 10}); auto epsilonNext = NDArrayFactory::create<TypeParam>('c', {2, 10, 6, 6}); input.linspace(1); weightsD.linspace(1); weightsP.linspace(1); epsilonNext.linspace(1); weightsD.permutei({2,3,1,0}); weightsP.permutei({2,3,1,0}); input.applyScalar(scalar::Divide, 100.0); weightsD.applyScalar(scalar::Divide, 100.0); weightsP.applyScalar(scalar::Divide, 100.0); epsilonNext.applyScalar(scalar::Divide, 100.0); nd4j::ops::sconv2d_bp op; auto resultBP = op.execute({&input, &epsilonNext, &weightsD, &weightsP },{}, {5, 5, 1, 1, 0, 0, 1, 1, 0}, {}); ASSERT_EQ(3, resultBP->size()); auto _epsilon = resultBP->at(0); auto _gradWD = resultBP->at(1); auto _gradWP = resultBP->at(2); //_gradWP->printBuffer("gradWP"); ASSERT_TRUE(_gradWP->isSameShape(&expGWP)); ASSERT_TRUE(_gradWP->isSameShape(&weightsP)); ASSERT_TRUE(_gradWP->equalsTo(&expGWP)); //_gradWD->printShapeInfo("gradWD shape"); ASSERT_TRUE(_gradWD->isSameShape(&expGWD)); ASSERT_TRUE(_gradWD->isSameShape(&weightsD)); // _gradWD->printIndexedBuffer(); ASSERT_TRUE(_gradWD->equalsTo(&expGWD)); ASSERT_TRUE(_epsilon->isSameShape(&input)); ASSERT_TRUE(_epsilon->isSameShape(&expE)); ASSERT_TRUE(_epsilon->equalsTo(&expE)); delete resultBP; } TYPED_TEST(TypedConvolutionTests1, TestSconvCrash_max_1) { auto input = NDArrayFactory::create<TypeParam>('c', {3, 3, 8, 8}); auto weightsD = NDArrayFactory::create<TypeParam>('c', {1, 3, 1, 1}); auto weightsP = NDArrayFactory::create<TypeParam>('c', {2, 3, 1, 1}); auto bias = NDArrayFactory::create<TypeParam>('c', {1, 2}); auto output = NDArrayFactory::create<TypeParam>('c', {3, 2, 8, 8}); output.assign(0.0); input.linspace(1); weightsD.linspace(1); weightsP.linspace(1); bias.linspace(1); weightsD.permutei({2,3,1,0}); weightsP.permutei({2,3,1,0}); auto expOutput = NDArrayFactory::create<TypeParam>('c', {3, 2, 8, 8}); nd4j::ops::sconv2d op; Nd4jStatus status = op.execute({&input, &weightsD, &weightsP, &bias}, {&output}, {}, {1, 1, 1, 1, 0, 0, 1, 1, 0}, {}); auto result = op.execute({&input, &weightsD, &weightsP, &bias}, {}, {1, 1, 1, 1, 0, 0, 1, 1, 0}, {}); auto z = result->at(0); //printf("\n"); //output.printBuffer("output"); //z->printBuffer("z"); //ASSERT_TRUE(expOutput.isSameShape(z)); delete result; } TEST_F(ConvolutionTests1, Test_im2col_col2im_1) { int kY = 5; int kX = 5; int sY = 1; int sX = 1; int pY = 0; int pX = 0; int dY = 1; int dX = 1; int inY = 28; int inX = 28; int channels = 3; bool isSameMode = true; auto x = NDArrayFactory::create<double>('c', {2, channels, inY, inX}); x.linspace(1); int oY, oX; x.syncToDevice(); //ASSERT_TRUE(x.isActualOnDeviceSide()); ASSERT_TRUE(x.isActualOnHostSide()); //x.printBuffer("x", 64); nd4j::ops::ConvolutionUtils::calcOutSizePool2D(oY, oX, kY, kX, sY, sX, pY, pX, dY, dX, inY, inX, isSameMode); if (isSameMode) nd4j::ops::ConvolutionUtils::calcPadding2D(pY, pX, oY, oX, inY, inX, kY, kX, sY, sX, dY, dX); auto im2col0 = NDArrayFactory::create<double>('c', {2, channels, kY, kX, oY, oX}); ExtraArguments args({(double) kY, (double) kX, (double) sY, (double) sX, (double) pY, (double) pX, (double) dY, (double) dX, isSameMode ? (double) 1 : (double) 0, (double)0.0, (double) 0.}); x.applyTransform(transform::Im2col, &im2col0, &args); nd4j::ops::im2col op; auto result2col = op.execute({&x}, {}, {kY, kX, sY, sX, pY, pX, dY, dX, isSameMode ? 1 : 0}); auto im2col1 = result2col->at(0); //im2col0.printBuffer("transformed"); //im2col1->printBuffer("customized", 64); ASSERT_TRUE(im2col1->isSameShape(&im2col0)); ASSERT_TRUE(im2col1->equalsTo(&im2col0)); ExtraArguments args2({ (double) sY, (double) sX, (double) pY, (double) pX, (double) inY, (double) inX, (double) dY, (double) dX, isSameMode ? (double) 1 : (double) 0}); auto col2im0 = NDArrayFactory::create<double>('c', {2, channels, inY, inX}); im2col0.applyTransform(transform::Col2Im, &col2im0, &args2); nd4j::ops::col2im op2im; auto result2im = op2im.execute({im2col1}, {}, {sY, sX, pY, pX, inY, inX, dY, dX, isSameMode ? 1 : 0}); auto col2im1 = result2im->at(0); ASSERT_TRUE(col2im1->isSameShape(&col2im0)); ASSERT_TRUE(col2im1->equalsTo(&col2im0)); delete result2col; delete result2im; } TEST_F(ConvolutionTests1, Test_im2col_col2im_2) { int kY = 5; int kX = 5; int sY = 1; int sX = 1; int pY = 0; int pX = 0; int dY = 1; int dX = 1; int inY = 28; int inX = 28; int channels = 3; bool isSameMode = true; auto x = NDArrayFactory::create<double>('c', {2, channels, inY, inX}); x.linspace(1); int oY, oX; nd4j::ops::ConvolutionUtils::calcOutSizePool2D(oY, oX, kY, kX, sY, sX, pY, pX, dY, dX, inY, inX, isSameMode); if (isSameMode) nd4j::ops::ConvolutionUtils::calcPadding2D(pY, pX, oY, oX, inY, inX, kY, kX, sY, sX, dY, dX); auto im2col0 = NDArrayFactory::create<double>('c', {2, channels, oY, oX, kY, kX}); im2col0.permutei({0, 1, 4, 5, 2, 3}); ExtraArguments args2col({(double) kY, (double) kX, (double) sY, (double) sX, (double) pY, (double) pX, (double) dY, (double) dX, isSameMode ? (double) 1 : (double) 0, (double)0.0, (double) 0.}); x.applyTransform(transform::Im2col, &im2col0, &args2col); nd4j::ops::im2col op; auto result2col = op.execute({&x}, {}, {kY, kX, sY, sX, pY, pX, dY, dX, isSameMode ? 1 : 0}); auto im2col1 = result2col->at(0); ASSERT_TRUE(im2col1->isSameShape(&im2col0)); ASSERT_TRUE(im2col1->equalsTo(&im2col0)); ExtraArguments args2im({ (double) sY, (double) sX, (double) pY, (double) pX, (double) inY, (double) inX, (double) dY, (double) dX, isSameMode ? (double) 1 : (double) 0}); auto col2im0 = NDArrayFactory::create<double>('c', {2, channels, inY, inX}); im2col0.applyTransform(transform::Col2Im, &col2im0, &args2im); nd4j::ops::col2im op2im; auto result2im = op2im.execute({im2col1}, {}, {sY, sX, pY, pX, inY, inX, dY, dX, isSameMode ? 1 : 0}); auto col2im1 = result2im->at(0); ASSERT_TRUE(col2im1->isSameShape(&col2im0)); ASSERT_TRUE(col2im1->equalsTo(&col2im0)); delete result2col; delete result2im; } TEST_F(ConvolutionTests1, Test_im2col_col2im_3) { int kY = 5; int kX = 5; int sY = 1; int sX = 1; int pY = 0; int pX = 0; int dY = 1; int dX = 1; int inY = 28; int inX = 28; int channels = 3; bool isSameMode = true; auto x = NDArrayFactory::create<double>('c', {2, channels, inY, inX}); x.linspace(1); int oY, oX; nd4j::ops::ConvolutionUtils::calcOutSizePool2D(oY, oX, kY, kX, sY, sX, pY, pX, dY, dX, inY, inX, isSameMode); if (isSameMode) nd4j::ops::ConvolutionUtils::calcPadding2D(pY, pX, oY, oX, inY, inX, kY, kX, sY, sX, dY, dX); auto im2col0 = NDArrayFactory::create<double>('c', {2, channels, oY, oX, kY, kX}); im2col0.permutei({0, 1, 4, 5, 2, 3}); auto im2col1 = NDArrayFactory::create<double>('c', {2, channels, oY, oX, kY, kX}); im2col1.permutei({0, 1, 4, 5, 2, 3}); ExtraArguments args2col({(double) kY, (double) kX, (double) sY, (double) sX, (double) pY, (double) pX, (double) dY, (double) dX, isSameMode ? (double) 1 : (double) 0, (double)0.0, (double) 0.}); x.applyTransform(transform::Im2col, &im2col0, &args2col); nd4j::ops::im2col op; auto status = op.execute({&x}, {&im2col1}, {}, {kY, kX, sY, sX, pY, pX, dY, dX, isSameMode ? 1 : 0}, {}); ASSERT_EQ(Status::OK(), status); ASSERT_TRUE(im2col1.isSameShape(&im2col0)); ASSERT_TRUE(im2col1.equalsTo(&im2col0)); ExtraArguments args2im({ (double) sY, (double) sX, (double) pY, (double) pX, (double) inY, (double) inX, (double) dY, (double) dX, isSameMode ? (double) 1 : (double) 0}); auto col2im0 = NDArrayFactory::create<double>('c', {2, channels, inY, inX}); im2col0.applyTransform(transform::Col2Im, &col2im0, &args2im); nd4j::ops::col2im op2im; auto result2im = op2im.execute({&im2col1}, {}, {sY, sX, pY, pX, inY, inX, dY, dX, isSameMode ? 1 : 0}); auto col2im1 = result2im->at(0); ASSERT_TRUE(col2im1->isSameShape(&col2im0)); ASSERT_TRUE(col2im1->equalsTo(&col2im0)); delete result2im; } TYPED_TEST(TypedConvolutionTests1, TestSconvCrash_max_2) { auto input = NDArrayFactory::create<TypeParam>('c', {3, 3, 16, 16}); auto weightsD = NDArrayFactory::create<TypeParam>('c', {1, 3, 2, 2}); auto weightsP = NDArrayFactory::create<TypeParam>('c', {2, 3, 1, 1}); auto bias = NDArrayFactory::create<TypeParam>('c', {1, 2}); weightsD.permutei({2,3,1,0}); weightsP.permutei({2,3,1,0}); auto epsilonNext = NDArrayFactory::create<TypeParam>('c', {3, 2, 14, 14}); auto epsilon = NDArrayFactory::create<TypeParam>('c', {3, 3, 16, 16}); nd4j::ops::sconv2d_bp op; auto result = op.execute({&input, &epsilonNext, &weightsD, &weightsP}, {}, {2, 2, 1, 1, 0, 0, 2, 2, 0}); auto eps = result->at(0); auto gWD = result->at(1); auto gWP = result->at(2); ASSERT_TRUE(epsilon.isSameShape(eps)); delete result; } TEST_F(ConvolutionTests1, TestDeconv_bp_1) { double _expb[] = { 35.f, 38.f, 41.f, 44.f, 47.f, 50.f, 53.f, 56.f, 59.f, 62.f, 65.f, 68.f, 71.f, 74.f, 77.f, 80.f, 71.f, 78.f, 85.f, 92.f, 99.f, 106.f, 113.f, 120.f, 127.f, 134.f, 141.f, 148.f, 155.f, 162.f, 169.f, 176.f, 107.f, 118.f, 129.f, 140.f, 151.f, 162.f, 173.f, 184.f, 195.f, 206.f, 217.f, 228.f, 239.f, 250.f, 261.f, 272.f, 131.f, 134.f, 137.f, 140.f, 143.f, 146.f, 149.f, 152.f, 155.f, 158.f, 161.f, 164.f, 167.f, 170.f, 173.f, 176.f, 295.f, 302.f, 309.f, 316.f, 323.f, 330.f, 337.f, 344.f, 351.f, 358.f, 365.f, 372.f, 379.f, 386.f, 393.f, 400.f, 459.f, 470.f, 481.f, 492.f, 503.f, 514.f, 525.f, 536.f, 547.f, 558.f, 569.f, 580.f, 591.f, 602.f, 613.f, 624.f, 227.f, 230.f, 233.f, 236.f, 239.f, 242.f, 245.f, 248.f, 251.f, 254.f, 257.f, 260.f, 263.f, 266.f, 269.f, 272.f, 519.f, 526.f, 533.f, 540.f, 547.f, 554.f, 561.f, 568.f, 575.f, 582.f, 589.f, 596.f, 603.f, 610.f, 617.f, 624.f, 811.f, 822.f, 833.f, 844.f, 855.f, 866.f, 877.f, 888.f, 899.f, 910.f, 921.f, 932.f, 943.f, 954.f, 965.f, 976.f}; std::shared_ptr<DataBuffer> pBuffer1 = std::make_shared<DataBuffer>(_expb, sizeof(_expb), nd4j::DataType::DOUBLE, false); NDArray expEpsilon(pBuffer1, 'c', {3, 3, 4, 4}); double _expwb[] = { 160008.f, 203400.f, 191112.f, 246792.f, 222216.f, 290184.f}; std::shared_ptr<DataBuffer> pBuffer2 = std::make_shared<DataBuffer>(_expwb, sizeof(_expwb), nd4j::DataType::DOUBLE, false); NDArray expGradW(pBuffer2, 'c', {3, 2, 1, 1}); expGradW.permutei({2,3,1,0}); double _expbb[] = {1944.f, 2712.f}; std::shared_ptr<DataBuffer> pBuffer3 = std::make_shared<DataBuffer>(_expbb, sizeof(_expbb), nd4j::DataType::DOUBLE, false); NDArray expGradB(pBuffer3, 'c', {1, 2}); auto input = NDArrayFactory::create<double>('c', {3, 3, 4, 4}); auto bias = NDArrayFactory::create<double>('c', {1, 2}); auto weights = NDArrayFactory::create<double>('c',{3, 2, 1, 1}); auto epsilon = NDArrayFactory::create<double>('c', {3, 2, 4, 4}); /* Input shape (3, 3, 4, 4) Weights shape (3, 2, 1, 1) Epsilon shape (3, 2, 4, 4) */ input.linspace(1); weights.linspace(1); bias.linspace(1); epsilon.linspace(1); weights.permutei({2,3,1,0}); nd4j::ops::deconv2d_bp op; auto result = op.execute({&input, &weights, &bias, &epsilon}, {}, {1, 1, 1, 1, 0, 0, 1, 1, 1, 0}); ASSERT_EQ(ND4J_STATUS_OK, result->status()); auto expNext = result->at(0); ASSERT_TRUE(expEpsilon.isSameShape(expNext)); ASSERT_TRUE(expEpsilon.equalsTo(expNext)); auto gradW = result->at(1); ASSERT_TRUE(expGradW.isSameShape(gradW)); ASSERT_TRUE(expGradW.equalsTo(gradW)); auto gradB = result->at(2); ASSERT_TRUE(expGradB.isSameShape(gradB)); ASSERT_TRUE(expGradB.equalsTo(gradB)); delete result; } TEST_F(ConvolutionTests1, TestDeconv_bp_2) { /* Input shape: [3, 3, 14, 14] Output shape: [3, 2, 15, 15] Weights shape: [3, 2, 2, 2] Bias shape: [1, 2] weight shape: [3, 2, 2, 2] weight grad shape: [3, 2, 2, 2] bias grad shape: [2] input epsilon shape: [3, 2, 15, 15] output epsilon shape: [3, 3, 14, 14] */ /* auto input('c', {3, 3, 14, 14}); auto bias('c', {2}); auto weights('c',{3, 2, 2, 2}); auto epsilon('c', {3, 2, 15, 15}); input.linspace(1); weights.linspace(1); bias.linspace(1); epsilon.linspace(1); nd4j::ops::deconv2d_bp<double> op; auto result = op.execute({&input, &weights, &bias, &epsilon}, {}, {2, 2, 1, 1, 0, 0, 2, 2, 0}); ASSERT_EQ(ND4J_STATUS_OK, result->status()); delete result;*/ } TEST_F(ConvolutionTests1, TestDeconv_ff_2) { double expB[] = {218.f, 227.f, 236.f, 245.f, 254.f, 263.f, 272.f, 281.f, 290.f, 299.f, 308.f, 317.f, 326.f, 335.f, 344.f, 353.f, 270.f, 282.f, 294.f, 306.f, 318.f, 330.f, 342.f, 354.f, 366.f, 378.f, 390.f, 402.f, 414.f, 426.f, 438.f, 450.f, 650.f, 659.f, 668.f, 677.f, 686.f, 695.f, 704.f, 713.f, 722.f, 731.f, 740.f, 749.f, 758.f, 767.f, 776.f, 785.f, 846.f, 858.f, 870.f, 882.f, 894.f, 906.f, 918.f, 930.f, 942.f, 954.f, 966.f, 978.f, 990.f, 1002.f, 1014.f, 1026.f, 1082.f, 1091.f, 1100.f, 1109.f, 1118.f, 1127.f, 1136.f, 1145.f, 1154.f, 1163.f, 1172.f, 1181.f, 1190.f, 1199.f, 1208.f, 1217.f, 1422.f, 1434.f, 1446.f, 1458.f, 1470.f, 1482.f, 1494.f, 1506.f, 1518.f, 1530.f, 1542.f, 1554.f, 1566.f, 1578.f, 1590.f, 1602.f,}; std::shared_ptr<DataBuffer> buffer = std::make_shared<DataBuffer>(expB, sizeof(double), nd4j::DataType::DOUBLE, false); NDArray exp(buffer, 'c', {3, 2, 4, 4}); auto input = NDArrayFactory::create<double>('c', {3, 3, 4, 4}); auto weights = NDArrayFactory::create<double>('c',{3, 2, 1, 1}); auto bias = NDArrayFactory::create<double>('c', {1, 2}); input.linspace(1); weights.linspace(1); bias.linspace(1); weights.permutei({2,3,1,0}); nd4j::ops::deconv2d op; auto result = op.execute({&input, &weights, &bias}, {}, {1, 1, 1, 1, 0, 0, 1, 1, 1, 0}); ASSERT_EQ(ND4J_STATUS_OK, result->status()); auto output = result->at(0); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete result; } TYPED_TEST(TypedConvolutionTests1, Test_Conv1D_ff_1) { auto input = NDArrayFactory::create<TypeParam>('c', {2, 2, 6}); auto weights = NDArrayFactory::create<TypeParam>('c', {2, 2, 3}, {1,5,9,3,7,11,2,6,10,4,8,12}); auto bias = NDArrayFactory::create<TypeParam>('c', {1, 3}); auto expFF = NDArrayFactory::create<TypeParam>('c', {2, 3, 5}, {59.0, 69.0, 79.0, 89.0, 99.0, 132.0, 158.0, 184.0, 210.0, 236.0, 205.0, 247.0, 289.0, 331.0, 373.0, 179.0, 189.0, 199.0, 209.0, 219.0, 444.0, 470.0, 496.0, 522.0, 548.0, 709.0, 751.0, 793.0, 835.0, 877.0}); auto expEps = NDArrayFactory::create<TypeParam>('c', {2, 2, 6}, {130.0, 293.0, 326.0, 359.0, 392.0, 220.0, 166.0, 371.0, 416.0, 461.0, 506.0, 280.0, 355.0, 788.0, 821.0, 854.0, 887.0, 490.0, 481.0, 1046.0, 1091.0, 1136.0, 1181.0, 640.0}); auto expGW = NDArrayFactory::create<TypeParam>('c', {3, 2, 2}, {1415.0, 1520.0, 2045.0, 2150.0, 1865.0, 2020.0, 2795.0, 2950.0, 2315.0, 2520.0, 3545.0, 3750.0}); auto expGB = NDArrayFactory::create<TypeParam>('c', {1, 3}, {105.0, 155.0, 205.0}); expGW.permutei({2,1,0}); input.linspace(1); bias.linspace(1); nd4j::ops::conv1d op; auto result_FF = op.execute({&input, &weights, &bias}, {}, {2, 1, 0, 0}); ASSERT_EQ(ND4J_STATUS_OK, result_FF->status()); auto z = result_FF->at(0); ASSERT_TRUE(expFF.isSameShape(z)); ASSERT_TRUE(expFF.equalsTo(z)); nd4j::ops::conv1d_bp op_bp; auto epsilonNxt = z->dup(); epsilonNxt->linspace(1); auto result_BP = op_bp.execute({&input, &weights, &bias, epsilonNxt}, {}, {2, 1, 0, 0}); ASSERT_EQ(ND4J_STATUS_OK, result_BP->status()); auto eps = result_BP->at(0); auto gradW = result_BP->at(1); auto gradB = result_BP->at(2); ASSERT_TRUE(expEps.isSameShape(eps)); ASSERT_TRUE(expGW.isSameShape(gradW)); ASSERT_TRUE(expGB.isSameShape(gradB)); ASSERT_TRUE(expEps.equalsTo(eps)); ASSERT_TRUE(expGW.equalsTo(gradW)); ASSERT_TRUE(expGB.equalsTo(gradB)); delete result_FF; delete result_BP; delete epsilonNxt; } TYPED_TEST(TypedConvolutionTests1, Test_Conv1D_ff_2) { auto input = NDArrayFactory::create<TypeParam>('c', {2, 2, 6}); auto weights = NDArrayFactory::create<TypeParam>('c', {2, 2, 3}, {1,5,9,3,7,11,2,6,10,4,8,12}); input.linspace(1); nd4j::ops::conv1d op; auto result = op.execute({&input, &weights}, {}, {2, 1, 0, 1}); ASSERT_EQ(ND4J_STATUS_OK, result->status()); auto z = result->at(0); delete result; } TYPED_TEST(TypedConvolutionTests1, Test_Conv2D_4_1) { auto input = NDArrayFactory::create<TypeParam>('c', {1, 1, 1, 4}); auto weights = NDArrayFactory::create<TypeParam>('c', {1, 1, 1, 4}); auto exp = NDArrayFactory::create<TypeParam>('c', {1, 4, 1, 4}, {2., 4., 6., 8., 2., 4., 6., 8., 2., 4., 6., 8., 2., 4., 6., 8.}); weights.assign(2.0); input.linspace(1); nd4j::ops::conv2d op; auto result = op.execute({&input, &weights}, {}, {1, 1, 1, 1, 0, 0, 1, 1, 0, 0}); ASSERT_EQ(ND4J_STATUS_OK, result->status()); auto z = result->at(0); ASSERT_TRUE(exp.isSameShape(z)); ASSERT_TRUE(exp.equalsTo(z)); delete result; } TEST_F(ConvolutionTests1, Test_Dilation2D_1) { auto input = NDArrayFactory::create<double>('c', {2, 6, 6, 3}); auto weights = NDArrayFactory::create<double>('c', {3, 2, 3}); auto exp = NDArrayFactory::create<double>('c', {2, 3, 3, 3}, {77, 79, 81, 83, 85, 87, 80, 82, 84, 113, 115, 117, 119, 121, 123, 116, 118, 120, 107, 109, 111, 113, 115, 117, 110, 112, 114, 185, 187, 189, 191, 193, 195, 188, 190, 192, 221, 223, 225, 227, 229, 231, 224, 226, 228, 215, 217, 219, 221, 223, 225, 218, 220, 222,}); input.linspace(1); weights.linspace(1); nd4j::ops::dilation2d op; auto result = op.execute({&input, &weights}, {}, {1, 1,2,2,1, 1,2,2,1}); ASSERT_EQ(Status::OK(), result->status()); auto z = result->at(0); ASSERT_TRUE(exp.isSameShape(z)); ASSERT_TRUE(exp.equalsTo(z)); delete result; } TEST_F(ConvolutionTests1, Test_Dilation2D_2) { auto input = NDArrayFactory::create<double>('c', {2, 6, 6, 3}); auto weights = NDArrayFactory::create<double>('c', {3, 2, 3}); auto exp = NDArrayFactory::create<double>('c', {2, 1, 2, 3}, {95, 97, 99, 101, 103, 105, 203, 205, 207, 209, 211, 213}); input.linspace(1); weights.linspace(1); nd4j::ops::dilation2d op; auto result = op.execute({&input, &weights}, {}, {0, 1,2,2,1, 1,2,2,1}); ASSERT_EQ(Status::OK(), result->status()); auto z = result->at(0); ASSERT_TRUE(exp.isSameShape(z)); ASSERT_TRUE(exp.equalsTo(z)); delete result; } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, conv2d_bp_test1) { int bS=2, iH=4,iW=3, iC=4,oC=3, kH=3,kW=2, sH=1,sW=1, pH=0,pW=0, dH=1,dW=1; int oH=4,oW=3; int paddingMode = 1; // 1-SAME, 0-VALID; int dataFormat = 1; // 1-NHWC, 0-NCHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iH, iW, iC}); auto weights = NDArrayFactory::create<TypeParam>('c', {kH, kW, iC, oC}); auto bias = NDArrayFactory::create<TypeParam>('c', {oC}, {1,2,3}); auto gradO = NDArrayFactory::create<TypeParam>('c', {bS, oH, oW, oC}); auto expGradI = NDArrayFactory::create<TypeParam>('c', {bS, iH, iW, iC},{ 0.226, 0.343, 0.46 , 0.577, 1.172, 1.46 , 1.748, 2.036, 1.892, 2.288, 2.684, 3.08 , 1.284, 1.581, 1.878, 2.175, 4.458, 5.133, 5.808, 6.483, 6.186, 7.023, 7.86 , 8.697, 3.39 , 3.93 , 4.47 , 5.01 , 9.642, 10.803, 11.964, 13.125,11.37 , 12.693, 14.016, 15.339, 5.266, 5.707, 6.148, 6.589,12.98 , 13.916, 14.852, 15.788,14.564, 15.608, 16.652, 17.696, 3.25 , 4.015, 4.78 , 5.545, 9.812, 11.396, 12.98 , 14.564,10.532, 12.224, 13.916, 15.608, 9.708, 10.977, 12.246, 13.515,25.194, 27.813, 30.432, 33.051,26.922, 29.703, 32.484, 35.265, 11.814, 13.326, 14.838, 16.35 ,30.378, 33.483, 36.588, 39.693,32.106, 35.373, 38.64 , 41.907,13.474, 14.563, 15.652, 16.741,31.988, 34.22 , 36.452, 38.684,33.572, 35.912, 38.252, 40.592}); auto expGradW = NDArrayFactory::create<TypeParam>('c', {kH, kW, iC, oC},{14.4 , 14.76, 15.12,14.4 , 14.76, 15.12,14.4 , 14.76, 15.12,14.4 , 14.76, 15.12, 9.24, 9.48, 9.72, 9.24, 9.48, 9.72, 9.24, 9.48, 9.72, 9.24, 9.48, 9.72, 17.04, 17.52, 18. ,17.04, 17.52, 18. ,17.04, 17.52, 18. ,17.04, 17.52, 18. ,10.88, 11.2 , 11.52,10.88, 11.2 , 11.52,10.88, 11.2 , 11.52,10.88, 11.2 , 11.52, 11.16, 11.52, 11.88,11.16, 11.52, 11.88,11.16, 11.52, 11.88,11.16, 11.52, 11.88, 7.08, 7.32, 7.56, 7.08, 7.32, 7.56, 7.08, 7.32, 7.56, 7.08, 7.32, 7.56}); // auto expGradB('c', {oC},{}); input = 2.; weights.linspace(0.1, 0.1); gradO.linspace(0.01, 0.01); nd4j::ops::conv2d_bp op; auto results = op.execute({&input, &weights, &bias, &gradO}, {}, {kH,kW, sH,sW, pH,pW, dH,dW, paddingMode, dataFormat}); auto gradI = results->at(0); auto gradW = results->at(1); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expGradI.isSameShape(gradI)); ASSERT_TRUE(expGradI.equalsTo(gradI)); ASSERT_TRUE(expGradW.isSameShape(gradW)); ASSERT_TRUE(expGradW.equalsTo(gradW)); delete results; } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, conv2d_bp_test2) { int bS=2, iH=4,iW=3, iC=4,oC=3, kH=3,kW=2, sH=1,sW=1, pH=0,pW=0, dH=1,dW=1; int oH=2,oW=2; int paddingMode = 0; // 1-SAME, 0-VALID; int dataFormat = 1; // 1-NHWC, 0-NCHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iH, iW, iC}); auto weights = NDArrayFactory::create<TypeParam>('c', {kH, kW, iC, oC}); auto bias = NDArrayFactory::create<TypeParam>('c', {oC}, {1,2,3}); auto gradO = NDArrayFactory::create<TypeParam>('c', {bS, oH, oW, oC}); auto expGradI = NDArrayFactory::create<TypeParam>('c', {bS, iH, iW, iC},{ 0.014,0.032, 0.05 , 0.068,0.118,0.181, 0.244, 0.307,0.212,0.257, 0.302, 0.347,0.208,0.298, 0.388, 0.478,1.028,1.262, 1.496, 1.73 ,1.036,1.18 , 1.324, 1.468, 0.928,1.018, 1.108, 1.198,2.9 ,3.134, 3.368, 3.602,2.188,2.332, 2.476, 2.62 ,1.202,1.274, 1.346, 1.418,3.142,3.313, 3.484, 3.655,2.048,2.147, 2.246, 2.345, 0.086,0.212, 0.338, 0.464,0.694,0.973, 1.252, 1.531,0.716,0.869, 1.022, 1.175,1.216,1.522, 1.828, 2.134,3.908,4.574, 5.24 , 5.906,2.908,3.268, 3.628, 3.988, 3.664,3.97 , 4.276, 4.582,9.236,9.902,10.568,11.234,5.788,6.148, 6.508, 6.868,3.002,3.182, 3.362, 3.542,7.174,7.561, 7.948, 8.335,4.28 ,4.487, 4.694, 4.901}); auto expGradW = NDArrayFactory::create<TypeParam>('c', {kH, kW, iC, oC},{1.84, 2., 2.16,1.84, 2., 2.16,1.84, 2., 2.16,1.84, 2., 2.16,1.84, 2., 2.16,1.84, 2., 2.16,1.84, 2., 2.16,1.84, 2., 2.16, 1.84, 2., 2.16,1.84, 2., 2.16,1.84, 2., 2.16,1.84, 2., 2.16,1.84, 2., 2.16,1.84, 2., 2.16,1.84, 2., 2.16,1.84, 2., 2.16, 1.84, 2., 2.16,1.84, 2., 2.16,1.84, 2., 2.16,1.84, 2., 2.16,1.84, 2., 2.16,1.84, 2., 2.16,1.84, 2., 2.16,1.84, 2., 2.16}); // auto expGradB('c', {oC},{}); input = 2.; weights.linspace(0.1, 0.1); gradO.linspace(0.01, 0.01); nd4j::ops::conv2d_bp op; auto results = op.execute({&input, &weights, &bias, &gradO}, {}, {kH,kW, sH,sW, pH,pW, dH,dW, paddingMode, dataFormat}); auto gradI = results->at(0); auto gradW = results->at(1); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expGradI.isSameShape(gradI)); ASSERT_TRUE(expGradI.equalsTo(gradI)); ASSERT_TRUE(expGradW.isSameShape(gradW)); ASSERT_TRUE(expGradW.equalsTo(gradW)); delete results; } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, conv2d_bp_test3) { int bS=2, iH=4,iW=3, iC=4,oC=3, kH=3,kW=2, sH=1,sW=1, pH=0,pW=0, dH=1,dW=1; int oH=2,oW=2; int paddingMode = 0; // 1-SAME, 0-VALID; int dataFormat = 0; // 1-NHWC, 0-NCHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iC, iH, iW}); auto weights = NDArrayFactory::create<TypeParam>('c', {oC, iC, kH, kW}); auto bias = NDArrayFactory::create<TypeParam>('c', {oC}, {1,2,3}); auto gradO = NDArrayFactory::create<TypeParam>('c', {bS, oC, oH, oW}); auto expGradI = NDArrayFactory::create<TypeParam>('c', {bS, iC, iH, iW},{ 0.567, 1.224,0.66 ,1.314, 2.82 ,1.512,1.386, 2.976,1.596,0.801, 1.71 ,0.912,0.657, 1.422,0.768,1.53 , 3.288,1.764,1.602, 3.444,1.848,0.927, 1.98 ,1.056, 0.747, 1.62 ,0.876,1.746, 3.756,2.016,1.818, 3.912,2.1 ,1.053, 2.25 ,1.2 ,0.837, 1.818,0.984,1.962, 4.224,2.268,2.034, 4.38 ,2.352,1.179, 2.52 ,1.344, 1.467, 3.06 ,1.596,3.186, 6.636,3.456,3.402, 7.08 ,3.684,1.845, 3.834,1.992,1.773, 3.69 ,1.92 ,3.834, 7.968,4.14 ,4.05 , 8.412,4.368,2.187, 4.536,2.352, 2.079, 4.32 ,2.244,4.482, 9.3 ,4.824,4.698, 9.744,5.052,2.529, 5.238,2.712,2.385, 4.95 ,2.568,5.13 ,10.632,5.508,5.346,11.076,5.736,2.871, 5.94 ,3.072}); auto expGradW = NDArrayFactory::create<TypeParam>('c', {oC, iC, kH, kW},{1.3600e+00,1.3600e+00,1.3600e+00,1.3600e+00,1.3600e+00,1.3600e+00,1.3600e+00,1.3600e+00,1.3600e+00,1.3600e+00,1.3600e+00,1.3600e+00,1.3600e+00,1.3600e+00,1.3600e+00,1.3600e+00,1.3600e+00,1.3600e+00, 1.3600e+00,1.3600e+00,1.3600e+00,1.3600e+00,1.3600e+00,1.3600e+00,2.0000e+00,2.0000e+00,2.0000e+00,2.0000e+00,2.0000e+00,2.0000e+00,2.0000e+00,2.0000e+00,2.0000e+00,2.0000e+00,2.0000e+00,2.0000e+00, 2.0000e+00,2.0000e+00,2.0000e+00,2.0000e+00,2.0000e+00,2.0000e+00,2.0000e+00,2.0000e+00,2.0000e+00,2.0000e+00,2.0000e+00,2.0000e+00,2.6400e+00,2.6400e+00,2.6400e+00,2.6400e+00,2.6400e+00,2.6400e+00, 2.6400e+00,2.6400e+00,2.6400e+00,2.6400e+00,2.6400e+00,2.6400e+00,2.6400e+00,2.6400e+00,2.6400e+00,2.6400e+00,2.6400e+00,2.6400e+00,2.6400e+00,2.6400e+00,2.6400e+00,2.6400e+00,2.6400e+00,2.6400e+00}); auto expGradB = NDArrayFactory::create<TypeParam>('c', {oC},{0.68, 1., 1.32}); input = 2.; weights.linspace(0.1, 0.1); gradO.linspace(0.01, 0.01); weights.permutei({2,3,1,0}); expGradW.permutei({2,3,1,0}); nd4j::ops::conv2d_bp op; auto results = op.execute({&input, &weights, &bias, &gradO}, {}, {kH,kW, sH,sW, pH,pW, dH,dW, paddingMode, dataFormat}); auto gradI = results->at(0); auto gradW = results->at(1); auto gradB = results->at(2); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expGradI.isSameShape(gradI)); ASSERT_TRUE(expGradI.equalsTo(gradI)); ASSERT_TRUE(expGradW.isSameShape(gradW)); ASSERT_TRUE(expGradW.equalsTo(gradW)); ASSERT_TRUE(expGradB.isSameShape(gradB)); ASSERT_TRUE(expGradB.equalsTo(gradB)); delete results; } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, conv2d_test1) { int bS=2, iH=4,iW=3, iC=4,oC=3, kH=3,kW=2, sH=1,sW=1, pH=0,pW=0, dH=1,dW=1; int oH=4,oW=3; int paddingMode = 1; // 1-SAME, 0-VALID; int dataFormat = 1; // 1-NHWC, 0-NCHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iH, iW, iC}); auto weights = NDArrayFactory::create<TypeParam>('c', {kH, kW, iC, oC}); auto bias = NDArrayFactory::create<TypeParam>('c', {oC}, {1,2,3}); auto expOutput = NDArrayFactory::create<TypeParam>('c', {bS, oH, oW, oC},{ 152. , 155.2, 158.4,152. , 155.2, 158.4, 66.4, 68. , 69.6,170.4, 175.2, 180. ,170.4, 175.2, 180. , 70.8, 73.2, 75.6, 170.4, 175.2, 180. ,170.4, 175.2, 180. , 70.8, 73.2, 75.6, 75.2, 78.4, 81.6, 75.2, 78.4, 81.6, 28. , 29.6, 31.2, 152. , 155.2, 158.4,152. , 155.2, 158.4, 66.4, 68. , 69.6,170.4, 175.2, 180. ,170.4, 175.2, 180. , 70.8, 73.2, 75.6, 170.4, 175.2, 180. ,170.4, 175.2, 180. , 70.8, 73.2, 75.6, 75.2, 78.4, 81.6, 75.2, 78.4, 81.6, 28. , 29.6, 31.2}); input = 2.; weights.linspace(0.1, 0.1); nd4j::ops::conv2d op; auto results = op.execute({&input, &weights}, {}, {kH,kW, sH,sW, pH,pW, dH,dW, paddingMode, dataFormat}); auto output = results->at(0); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expOutput.isSameShape(output)); ASSERT_TRUE(expOutput.equalsTo(output)); delete results; } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, conv2d_test2) { int bS=2, iH=4,iW=3, iC=4,oC=3, kH=3,kW=2, sH=1,sW=1, pH=0,pW=0, dH=1,dW=1; int oH=2,oW=2; int paddingMode = 0; // 1-SAME, 0-VALID; int dataFormat = 1; // 1-NHWC, 0-NCHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iH, iW, iC}); auto weights = NDArrayFactory::create<TypeParam>('c', {kH, kW, iC, oC}); auto bias = NDArrayFactory::create<TypeParam>('c', {oC}, {1,2,3}); auto expOutput = NDArrayFactory::create<TypeParam>('c', {bS, oH, oW, oC},{ 170.4,175.20001,180.,170.4,175.20001,180.,170.4,175.20001,180.,170.4,175.20001,180.,170.4,175.20001,180.,170.4,175.20001,180.,170.4,175.20001,180.,170.4,175.20001,180.}); input = 2.; weights.linspace(0.1, 0.1); nd4j::ops::conv2d op; auto results = op.execute({&input, &weights}, {}, {kH,kW, sH,sW, pH,pW, dH,dW, paddingMode, dataFormat}); auto output = results->at(0); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expOutput.isSameShape(output)); ASSERT_TRUE(expOutput.equalsTo(output)); delete results; } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, conv2d_test3) { int bS=2, iH=4,iW=3, iC=4,oC=3, kH=3,kW=2, sH=1,sW=1, pH=0,pW=0, dH=1,dW=1; int oH=2,oW=2; int paddingMode = 0; // 1-SAME, 0-VALID; int dataFormat = 0; // 1-NHWC, 0-NCHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iC, iH, iW}); auto weights = NDArrayFactory::create<TypeParam>('c', {oC, iC, kH, kW}); auto bias = NDArrayFactory::create<TypeParam>('c', {oC}, {1,2,3}); auto expOutput = NDArrayFactory::create<TypeParam>('c', {bS, oC, oH, oW}, {61. , 61. , 61. , 61. ,177.2, 177.2,177.2, 177.2,293.4, 293.4,293.4, 293.4, 61. , 61. , 61. , 61. ,177.2, 177.2,177.2, 177.2,293.4, 293.4,293.4, 293.4}); input = 2.; weights.linspace(0.1, 0.1); weights.permutei({2,3,1,0}); nd4j::ops::conv2d op; auto results = op.execute({&input, &weights, &bias}, {}, {kH,kW, sH,sW, pH,pW, dH,dW, paddingMode, dataFormat}); auto output = results->at(0); // output->printIndexedBuffer(); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expOutput.isSameShape(output)); ASSERT_TRUE(expOutput.equalsTo(output)); delete results; } //////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, conv3d_bp_test1) { int bS=2, iD=3,iH=4,iW=3, iC=4,oC=3, kD=2,kH=3,kW=2, sD=1,sH=1,sW=1, pD=0,pH=0,pW=0, dD=1,dH=1,dW=1; int oD=3,oH=4,oW=3; int paddingMode = 1; // 1-SAME, 0-VALID; int dataFormat = 1; // 1-NDHWC, 0-NCDHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iD, iH, iW, iC}); auto weights = NDArrayFactory::create<TypeParam>('c', {kD, kH, kW, iC, oC}); auto bias = NDArrayFactory::create<TypeParam>('c', {oC}, {1,2,3}); auto gradO = NDArrayFactory::create<TypeParam>('c', {bS, oD, oH, oW, oC}); auto expGradI = NDArrayFactory::create<TypeParam>('c', {bS, iD, iH, iW, iC},{0.226, 0.343, 0.46 , 0.577, 1.172, 1.46 , 1.748, 2.036, 1.892, 2.288, 2.684, 3.08 , 1.284, 1.581, 1.878, 2.175, 4.458, 5.133, 5.808, 6.483, 6.186, 7.023, 7.86 , 8.697, 3.39 , 3.93 , 4.47 , 5.01 , 9.642, 10.803, 11.964, 13.125, 11.37 , 12.693, 14.016, 15.339, 5.266, 5.707, 6.148, 6.589, 12.98 , 13.916, 14.852, 15.788, 14.564, 15.608, 16.652, 17.696, 6.284, 7.166, 8.048, 8.93 , 17.896, 19.768, 21.64 , 23.512, 21.928, 24.016, 26.104, 28.192, 18.12 , 19.686, 21.252, 22.818, 45.852, 49.146, 52.44 , 55.734, 53.196, 56.814, 60.432, 64.05 , 28.164, 30.216, 32.268, 34.32 , 67.884, 72.15 , 76.416, 80.682, 75.228, 79.818, 84.408, 88.998, 29.324, 30.854, 32.384, 33.914, 67.432, 70.6 , 73.768, 76.936, 73.192, 76.576, 79.96 , 83.344, 27.884, 30.062, 32.24 , 34.418, 66.28 , 70.744, 75.208, 79.672, 70.312, 74.992, 79.672, 84.352, 58.296, 61.806, 65.316, 68.826,133.98 , 141.162, 148.344, 155.526,141.324, 148.83 , 156.336, 163.842, 68.34 , 72.336, 76.332, 80.328,156.012, 164.166, 172.32 , 180.474,163.356, 171.834, 180.312, 188.79 , 61.292, 64.118, 66.944, 69.77 ,136.552, 142.312, 148.072, 153.832,142.312, 148.288, 154.264, 160.24 , 9.298, 11.359, 13.42 , 15.481, 27.092, 31.268, 35.444, 39.62 , 27.812, 32.096, 36.38 , 40.664, 26.556, 29.769, 32.982, 36.195, 66.666, 73.173, 79.68 , 86.187, 68.394, 75.063, 81.732, 88.401, 28.662, 32.118, 35.574, 39.03 , 71.85 , 78.843, 85.836, 92.829, 73.578, 80.733, 87.888, 95.043, 29.89 , 32.275, 34.66 , 37.045, 70.004, 74.828, 79.652, 84.476, 71.588, 76.52 , 81.452, 86.384, 71.084, 75.854, 80.624, 85.394,163.048, 172.696, 182.344, 191.992,167.08 , 176.944, 186.808, 196.672,138.648, 146.046, 153.444, 160.842,310.236, 325.194, 340.152, 355.11 ,317.58 , 332.862, 348.144, 363.426, 148.692, 156.576, 164.46 , 172.344,332.268, 348.198, 364.128, 380.058,339.612, 355.866, 372.12 , 388.374,125.228, 130.646, 136.064, 141.482,274.792, 285.736, 296.68 , 307.624,280.552, 291.712, 302.872, 314.032, 92.684, 98.75 , 104.816, 110.882,211.432, 223.672, 235.912, 248.152,215.464, 227.92 , 240.376, 252.832, 178.824, 188.166, 197.508, 206.85 ,398.364, 417.21 , 436.056, 454.902,405.708, 424.878, 444.048, 463.218,188.868, 198.696, 208.524, 218.352,420.396, 440.214, 460.032, 479.85 ,427.74 , 447.882, 468.024, 488.166,157.196, 163.91 , 170.624, 177.338,343.912, 357.448, 370.984, 384.52 ,349.672, 363.424, 377.176, 390.928}); auto expGradW = NDArrayFactory::create<TypeParam>('c', {kD, kH, kW, iC, oC},{120.96, 122.04, 123.12,120.96, 122.04, 123.12,120.96, 122.04, 123.12,120.96, 122.04, 123.12, 79.56, 80.28, 81. , 79.56, 80.28, 81. , 79.56, 80.28, 81. , 79.56, 80.28, 81. , 154.8 , 156.24, 157.68,154.8 , 156.24, 157.68,154.8 , 156.24, 157.68,154.8 , 156.24, 157.68,101.76, 102.72, 103.68,101.76, 102.72, 103.68,101.76, 102.72, 103.68,101.76, 102.72, 103.68, 111.24, 112.32, 113.4 ,111.24, 112.32, 113.4 ,111.24, 112.32, 113.4 ,111.24, 112.32, 113.4 , 73.08, 73.8 , 74.52, 73.08, 73.8 , 74.52, 73.08, 73.8 , 74.52, 73.08, 73.8 , 74.52, 67.68, 68.4 , 69.12, 67.68, 68.4 , 69.12, 67.68, 68.4 , 69.12, 67.68, 68.4 , 69.12, 44.4 , 44.88, 45.36, 44.4 , 44.88, 45.36, 44.4 , 44.88, 45.36, 44.4 , 44.88, 45.36, 85.92, 86.88, 87.84, 85.92, 86.88, 87.84, 85.92, 86.88, 87.84, 85.92, 86.88, 87.84, 56.32, 56.96, 57.6 , 56.32, 56.96, 57.6 , 56.32, 56.96, 57.6 , 56.32, 56.96, 57.6 , 61.2 , 61.92, 62.64, 61.2 , 61.92, 62.64, 61.2 , 61.92, 62.64, 61.2 , 61.92, 62.64, 40.08, 40.56, 41.04, 40.08, 40.56, 41.04, 40.08, 40.56, 41.04, 40.08, 40.56, 41.04}); // auto expGradB('c', {oC},{}); input = 2.; weights.linspace(0.1, 0.1); gradO.linspace(0.01, 0.01); nd4j::ops::conv3dnew_bp op; auto results = op.execute({&input, &weights, &bias, &gradO}, {}, {kD,kH,kW, sD,sH,sW, pD,pH,pW, dD,dH,dW, paddingMode, dataFormat}); auto* gradI = results->at(0); auto* gradW = results->at(1); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expGradI.isSameShape(gradI)); ASSERT_TRUE(expGradI.equalsTo(gradI)); ASSERT_TRUE(expGradW.isSameShape(gradW)); ASSERT_TRUE(expGradW.equalsTo(gradW)); delete results; } //////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, conv3d_bp_test2) { int bS=2, iD=3,iH=4,iW=3, iC=4,oC=3, kD=2,kH=3,kW=2, sD=1,sH=1,sW=1, pD=0,pH=0,pW=0, dD=1,dH=1,dW=1; int oD=2,oH=2,oW=2; int paddingMode = 0; // 1-SAME, 0-VALID; int dataFormat = 1; // 1-NDHWC, 0-NCDHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iD, iH, iW, iC}); auto weights = NDArrayFactory::create<TypeParam>('c', {kD, kH, kW, iC, oC}); auto bias = NDArrayFactory::create<TypeParam>('c', {oC}, {1,2,3}); auto gradO = NDArrayFactory::create<TypeParam>('c', {bS, oD, oH, oW, oC}); auto expGradI = NDArrayFactory::create<TypeParam>('c', {bS, iD, iH, iW, iC},{ 0.014, 0.032, 0.05 , 0.068, 0.118, 0.181, 0.244, 0.307, 0.212, 0.257, 0.302, 0.347, 0.208, 0.298, 0.388, 0.478, 1.028, 1.262, 1.496, 1.73 , 1.036, 1.18 , 1.324, 1.468, 0.928, 1.018, 1.108, 1.198, 2.9 , 3.134, 3.368, 3.602, 2.188, 2.332, 2.476, 2.62 , 1.202, 1.274, 1.346, 1.418, 3.142, 3.313, 3.484, 3.655, 2.048, 2.147, 2.246, 2.345, 0.532, 0.676, 0.82 , 0.964, 2.324, 2.666, 3.008, 3.35 , 2.008, 2.206, 2.404, 2.602, 3.584, 3.98 , 4.376, 4.772,10.552,11.452,12.352,13.252, 7.4 , 7.904, 8.408, 8.912, 6.752, 7.148, 7.544, 7.94 ,17.752,18.652,19.552,20.452,11.432,11.936,12.44 ,12.944, 5.932, 6.184, 6.436, 6.688,14.42 ,14.978,15.536,16.094, 8.704, 9.01 , 9.316, 9.622, 3.11 , 3.236, 3.362, 3.488, 7.39 , 7.669, 7.948, 8.227, 4.388, 4.541, 4.694, 4.847, 8.56 , 8.866, 9.172, 9.478,19.892,20.558,21.224,21.89 ,11.548,11.908,12.268,12.628,11.008,11.314,11.62 ,11.926,25.22 ,25.886,26.552,27.218,14.428,14.788,15.148,15.508, 7.322, 7.502, 7.682, 7.862,16.462,16.849,17.236,17.623, 9.248, 9.455, 9.662, 9.869, 0.158, 0.392, 0.626, 0.86 , 1.27 , 1.765, 2.26 , 2.755, 1.22 , 1.481, 1.742, 2.003, 2.224, 2.746, 3.268, 3.79 , 6.788, 7.886, 8.984,10.082, 4.78 , 5.356, 5.932, 6.508, 6.4 , 6.922, 7.444, 7.966,15.572,16.67 ,17.768,18.866, 9.388, 9.964,10.54 ,11.116, 4.802, 5.09 , 5.378, 5.666,11.206,11.809,12.412,13.015, 6.512, 6.827, 7.142, 7.457, 6.004, 6.58 , 7.156, 7.732,14.996,16.202,17.408,18.614, 9.208, 9.838,10.468,11.098,17.984,19.244,20.504,21.764,42.808,45.436,48.064,50.692,25.256,26.624,27.992,29.36 , 28.064,29.324,30.584,31.844,63.832,66.46 ,69.088,71.716,36.2 ,37.568,38.936,40.304,18.316,19. ,19.684,20.368,40.916,42.338,43.76 ,45.182,22.816,23.554,24.292,25.03 , 8.438, 8.78 , 9.122, 9.464,18.91 ,19.621,20.332,21.043,10.58 ,10.949,11.318,11.687, 20.944,21.682,22.42 ,23.158,46.388,47.918,49.448,50.978,25.66 ,26.452,27.244,28.036,26.848,27.586,28.324,29.062,58.628,60.158,61.688,63.218,31.996,32.788,33.58 ,34.372,16.106,16.502,16.898,17.294,34.894,35.713,36.532,37.351,18.896,19.319,19.742,20.165}); auto expGradW = NDArrayFactory::create<TypeParam>('c', {kD, kH, kW, iC, oC},{7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16, 7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16, 7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16, 7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16,7.52, 7.84, 8.16}); // auto expGradB('c', {oC},{}); input = 2.; weights.linspace(0.1, 0.1); gradO.linspace(0.01, 0.01); nd4j::ops::conv3dnew_bp op; auto results = op.execute({&input, &weights, &bias, &gradO}, {}, {kD,kH,kW, sD,sH,sW, pD,pH,pW, dD,dH,dW, paddingMode, dataFormat}); auto gradI = results->at(0); auto gradW = results->at(1); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expGradI.isSameShape(gradI)); ASSERT_TRUE(expGradI.equalsTo(gradI)); ASSERT_TRUE(expGradW.isSameShape(gradW)); ASSERT_TRUE(expGradW.equalsTo(gradW)); delete results; } //////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, conv3d_bp_test3) { int bS=2, iD=3,iH=4,iW=3, iC=4,oC=3, kD=2,kH=3,kW=2, sD=1,sH=1,sW=1, pD=0,pH=0,pW=0, dD=1,dH=1,dW=1; int oD=2,oH=2,oW=2; int paddingMode = 0; // 1-SAME, 0-VALID; int dataFormat = 0; // 1-NDHWC, 0-NCDHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iC, iD, iH, iW}); auto weights = NDArrayFactory::create<TypeParam>('c', {oC, iC, kD, kH, kW}); auto bias = NDArrayFactory::create<TypeParam>('c', {oC}, {1,2,3}); auto gradO = NDArrayFactory::create<TypeParam>('c', {bS, oC, oD, oH, oW}); auto expGradI = NDArrayFactory::create<TypeParam>('c', {bS, iC, iD, iH, iW},{2.091, 4.356, 2.268, 4.53 , 9.42 , 4.896, 4.65 , 9.672, 5.028, 2.517, 5.226, 2.712, 4.932,10.242, 5.316,10.62 ,22.02 ,11.412,10.908,22.62 ,11.724, 5.868,12.15 , 6.288, 2.913, 6.03 , 3.12 , 6.234,12.888, 6.66 , 6.402,13.236, 6.84 , 3.423, 7.068, 3.648, 2.415, 5.04 , 2.628, 5.25 ,10.932, 5.688, 5.37 ,11.184, 5.82 , 2.913, 6.054, 3.144, 5.724,11.898, 6.18 ,12.348,25.62 ,13.284,12.636,26.22 ,13.596, 6.804,14.094, 7.296, 3.381, 7.002, 3.624, 7.242,14.976, 7.74 , 7.41 ,15.324, 7.92 , 3.963, 8.184, 4.224, 2.739, 5.724, 2.988, 5.97 ,12.444, 6.48 , 6.09 ,12.696, 6.612, 3.309, 6.882, 3.576, 6.516,13.554, 7.044,14.076,29.22 ,15.156,14.364,29.82 ,15.468, 7.74 ,16.038, 8.304, 3.849, 7.974, 4.128, 8.25 ,17.064, 8.82 , 8.418,17.412, 9. , 4.503, 9.3 , 4.8 , 3.063, 6.408, 3.348, 6.69 ,13.956, 7.272, 6.81 ,14.208, 7.404, 3.705, 7.71 , 4.008, 7.308,15.21 , 7.908,15.804,32.82 ,17.028,16.092,33.42 ,17.34 , 8.676,17.982, 9.312, 4.317, 8.946, 4.632, 9.258,19.152, 9.9 , 9.426,19.5 ,10.08 , 5.043,10.416, 5.376, 5.619,11.484, 5.868,11.73 ,23.964,12.24 ,12.138,24.792,12.66 , 6.333,12.93 , 6.6 ,12.42 ,25.362,12.948,25.884,52.836,26.964,26.748,54.588,27.852,13.932,28.422,14.496, 6.873,14.022, 7.152,14.298,29.16 ,14.868,14.754,30.084,15.336, 7.671,15.636, 7.968, 6.807,13.896, 7.092,14.178,28.932,14.76 ,14.586,29.76 ,15.18 , 7.593,15.486, 7.896,14.94 ,30.474,15.54 ,31.068,63.348,32.292,31.932,65.1 ,33.18 ,16.596,33.822,17.232, 8.205,16.722, 8.52 ,17.034,34.704,17.676,17.49 ,35.628,18.144, 9.075,18.48 , 9.408, 7.995,16.308, 8.316,16.626,33.9 ,17.28 ,17.034,34.728,17.7 , 8.853,18.042, 9.192,17.46 ,35.586,18.132,36.252,73.86 ,37.62 ,37.116,75.612,38.508,19.26 ,39.222,19.968, 9.537,19.422, 9.888,19.77 ,40.248,20.484,20.226,41.172,20.952,10.479,21.324,10.848, 9.183,18.72 , 9.54 ,19.074,38.868,19.8 ,19.482,39.696,20.22 ,10.113,20.598,10.488,19.98 ,40.698,20.724,41.436,84.372,42.948,42.3 ,86.124,43.836,21.924,44.622,22.704,10.869,22.122,11.256,22.506,45.792,23.292,22.962,46.716,23.76 ,11.883,24.168,12.288}); auto expGradW = NDArrayFactory::create<TypeParam>('c', {oC, iC, kD, kH, kW},{5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 5.28, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 7.84, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4, 10.4}); auto expGradB = NDArrayFactory::create<TypeParam>('c', {oC},{2.64, 3.92, 5.2 }); input = 2.; weights.linspace(0.1, 0.1); gradO.linspace(0.01, 0.01); weights.permutei({2, 3, 4, 1, 0}); expGradW.permutei({2, 3, 4, 1, 0}); nd4j::ops::conv3dnew_bp op; auto results = op.execute({&input, &weights, &bias, &gradO}, {}, {kD,kH,kW, sD,sH,sW, pD,pH,pW, dD,dH,dW, paddingMode, dataFormat}); auto* gradI = results->at(0); auto* gradW = results->at(1); auto* gradB = results->at(2); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expGradI.isSameShape(gradI)); ASSERT_TRUE(expGradI.equalsTo(gradI)); ASSERT_TRUE(expGradW.isSameShape(gradW)); ASSERT_TRUE(expGradW.equalsTo(gradW)); ASSERT_TRUE(expGradB.isSameShape(gradB)); ASSERT_TRUE(expGradB.equalsTo(gradB)); delete results; } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, depthwise_conv2d_test1) { int bS=2, iH=4,iW=3, iC=2,mC=2, kH=3,kW=2, sH=1,sW=1, pH=0,pW=0, dH=1,dW=1; int oC=iC*mC; int oH=4,oW=3; int paddingMode = 1; // 1-SAME, 0-VALID; int dataFormat = 1; // 1-NHWC, 0-NCHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iH, iW, iC}); auto weights = NDArrayFactory::create<TypeParam>('c', {kH, kW, iC, mC}); auto expOutput = NDArrayFactory::create<TypeParam>('c', {bS, oH, oW, oC},{12. , 12.8, 13.6, 14.4,12. , 12.8, 13.6, 14.4, 5.2, 5.6, 6. , 6.4,13.2, 14.4, 15.6, 16.8,13.2, 14.4, 15.6, 16.8, 5.4, 6. , 6.6, 7.2, 13.2, 14.4, 15.6, 16.8,13.2, 14.4, 15.6, 16.8, 5.4, 6. , 6.6, 7.2, 5.6, 6.4, 7.2, 8. , 5.6, 6.4, 7.2, 8. , 2. , 2.4, 2.8, 3.2, 12. , 12.8, 13.6, 14.4,12. , 12.8, 13.6, 14.4, 5.2, 5.6, 6. , 6.4,13.2, 14.4, 15.6, 16.8,13.2, 14.4, 15.6, 16.8, 5.4, 6. , 6.6, 7.2, 13.2, 14.4, 15.6, 16.8,13.2, 14.4, 15.6, 16.8, 5.4, 6. , 6.6, 7.2, 5.6, 6.4, 7.2, 8. , 5.6, 6.4, 7.2, 8. , 2. , 2.4, 2.8, 3.2}); input = 2.; weights.linspace(0.1, 0.1); nd4j::ops::depthwise_conv2d op; auto results = op.execute({&input, &weights}, {}, {kH,kW, sH,sW, pH,pW, dH,dW, paddingMode, dataFormat}); auto* output = results->at(0); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expOutput.isSameShape(output)); ASSERT_TRUE(expOutput.equalsTo(output)); delete results; } ////////////////////////////////////////////////////////////////////// TEST_F(ConvolutionTests1, depthwise_conv2d_test2) { int bS=2, iH=4,iW=3, iC=2,mC=2, kH=3,kW=2, sH=1,sW=1, pH=0,pW=0, dH=1,dW=1; int oC=iC*mC; int oH=2,oW=2; int paddingMode = 0; // 1-SAME, 0-VALID; int dataFormat = 1; // 1-NHWC, 0-NCHW auto input = NDArrayFactory::create<double>('c', {bS, iH, iW, iC}); auto weights = NDArrayFactory::create<double>('c', {kH, kW, iC, mC}); auto expOutput = NDArrayFactory::create<double>('c', {bS, oH, oW, oC},{13.2, 14.4, 15.6, 16.8,13.2, 14.4, 15.6, 16.8,13.2, 14.4, 15.6, 16.8,13.2, 14.4, 15.6, 16.8, 13.2, 14.4, 15.6, 16.8,13.2, 14.4, 15.6, 16.8,13.2, 14.4, 15.6, 16.8,13.2, 14.4, 15.6, 16.8}); input = 2.; weights.linspace(0.1, 0.1); nd4j::ops::depthwise_conv2d op; auto results = op.execute({&input, &weights}, {}, {kH,kW, sH,sW, pH,pW, dH,dW, paddingMode, dataFormat}); auto* output = results->at(0); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expOutput.isSameShape(output)); ASSERT_TRUE(expOutput.equalsTo(output)); delete results; } ////////////////////////////////////////////////////////////////////// TEST_F(ConvolutionTests1, depthwise_conv2d_test3) { int bS=2, iH=4,iW=3, iC=2,mC=2, kH=3,kW=2, sH=1,sW=1, pH=0,pW=0, dH=1,dW=1; int oC=iC*mC; int oH=2,oW=2; int paddingMode = 0; // 1-SAME, 0-VALID; int dataFormat = 0; // 1-NHWC, 0-NCHW auto input = NDArrayFactory::create<double>('c', {bS, iC, iH, iW}); auto weights = NDArrayFactory::create<double>('c', {mC, iC, kH, kW}); auto biases = NDArrayFactory::create<double>('c', {iC*mC}, {1,2,3,4}); auto expOutput = NDArrayFactory::create<double>('c', {bS, oC, oH, oW},{5.2, 5.2, 5.2, 5.2,20.6,20.6,20.6,20.6,14.4,14.4,14.4,14.4,29.8,29.8,29.8,29.8, 5.2, 5.2, 5.2, 5.2,20.6,20.6,20.6,20.6,14.4,14.4,14.4,14.4,29.8,29.8,29.8,29.8}); input = 2.; weights.linspace(0.1, 0.1); weights.permutei({2,3,1,0}); nd4j::ops::depthwise_conv2d op; auto results = op.execute({&input, &weights, &biases}, {}, {kH,kW, sH,sW, pH,pW, dH,dW, paddingMode, dataFormat}); auto* output = results->at(0); // output->printIndexedBuffer(); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expOutput.isSameShape(output)); ASSERT_TRUE(expOutput.equalsTo(output)); delete results; } ////////////////////////////////////////////////////////////////////// TEST_F(ConvolutionTests1, depthwise_conv2d_bp_test1) { int bS=2, iH=4,iW=3, iC=2,mC=2, kH=3,kW=2, sH=1,sW=1, pH=0,pW=0, dH=1,dW=1; int oH=4,oW=3; int oC=iC*mC; int paddingMode = 1; // 1-SAME, 0-VALID; int dataFormat = 1; // 1-NHWC, 0-NCHW auto input = NDArrayFactory::create<double>('c', {bS, iH, iW, iC}); auto weights = NDArrayFactory::create<double>('c', {kH, kW, iC, mC}); auto bias = NDArrayFactory::create<double>('c', {oC}, {1,2,3,4}); auto gradO = NDArrayFactory::create<double>('c', {bS, oH, oW, oC}); auto expGradI = NDArrayFactory::create<double>('c', {bS, iH, iW, iC},{0.07 , 0.19 , 0.348, 0.652, 0.588, 0.956, 0.387, 0.687, 1.326, 2.022, 1.878, 2.67 , 1.071, 1.515, 2.982, 3.966, 3.534, 4.614, 1.606, 1.982, 3.932, 4.748, 4.428, 5.308, 1.126, 1.63 , 3.228, 4.3 , 3.468, 4.604, 3.123, 3.999, 7.95 , 9.798, 8.502, 10.446, 3.807, 4.827, 9.606, 11.742,10.158, 12.39 , 4.198, 4.958, 9.884, 11.468,10.38 , 12.028}); auto expGradW = NDArrayFactory::create<double>('c', {kH, kW, iC, mC},{19.08, 19.44,19.8 , 20.16,12.24, 12.48,12.72, 12.96,22.56, 23.04,23.52, 24. ,14.4 , 14.72,15.04, 15.36,14.76, 15.12,15.48, 15.84, 9.36, 9.6 , 9.84, 10.08}); input = 2.; weights.linspace(0.1, 0.1); gradO.linspace(0.01, 0.01); nd4j::ops::depthwise_conv2d_bp op; auto results = op.execute({&input, &weights, &bias, &gradO}, {}, {kH,kW, sH,sW, pH,pW, dH,dW, paddingMode, dataFormat}); auto* gradI = results->at(0); auto* gradW = results->at(1); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expGradI.isSameShape(gradI)); ASSERT_TRUE(expGradI.equalsTo(gradI)); ASSERT_TRUE(expGradW.isSameShape(gradW)); ASSERT_TRUE(expGradW.equalsTo(gradW)); delete results; } ////////////////////////////////////////////////////////////////////// TEST_F(ConvolutionTests1, depthwise_conv2d_bp_test2) { int bS=2, iH=4,iW=3, iC=2,mC=2, kH=3,kW=2, sH=1,sW=1, pH=0,pW=0, dH=1,dW=1; int oH=2,oW=2; int oC=iC*mC; int paddingMode = 0; // 1-SAME, 0-VALID; int dataFormat = 1; // 1-NHWC, 0-NCHW auto input = NDArrayFactory::create<double>('c', {bS, iH, iW, iC}); auto weights = NDArrayFactory::create<double>('c', {kH, kW, iC, mC}); auto bias = NDArrayFactory::create<double>('c', {oC}, {1,2,3,4}); auto gradO = NDArrayFactory::create<double>('c', {bS, oH, oW, oC}); auto expGradI = NDArrayFactory::create<double>('c', {bS, iH, iW, iC},{0.005, 0.025,0.034, 0.106,0.061, 0.113,0.058, 0.162,0.292, 0.564,0.298, 0.466,0.234, 0.402,0.772, 1.172,0.602, 0.834,0.333, 0.449,0.882, 1.146,0.581, 0.729, 0.053, 0.137,0.258, 0.458,0.237, 0.353,0.41 , 0.642,1.252, 1.78 ,0.906, 1.202,1.098, 1.394,2.756, 3.412,1.722, 2.082,0.893, 1.073,2.13 , 2.522,1.269, 1.481}); auto expGradW = NDArrayFactory::create<double>('c', {kH, kW, iC, mC},{2.4 , 2.56,2.72, 2.88,2.4 , 2.56,2.72, 2.88,2.4 , 2.56,2.72, 2.88,2.4 , 2.56,2.72, 2.88,2.4 , 2.56,2.72, 2.88,2.4 , 2.56,2.72, 2.88}); input = 2.; weights.linspace(0.1, 0.1); gradO.linspace(0.01, 0.01); nd4j::ops::depthwise_conv2d_bp op; auto results = op.execute({&input, &weights, &bias, &gradO}, {}, {kH,kW, sH,sW, pH,pW, dH,dW, paddingMode, dataFormat}); auto* gradI = results->at(0); auto* gradW = results->at(1); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expGradI.isSameShape(gradI)); ASSERT_TRUE(expGradI.equalsTo(gradI)); ASSERT_TRUE(expGradW.isSameShape(gradW)); ASSERT_TRUE(expGradW.equalsTo(gradW)); delete results; } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, conv3d_test1) { int bS=2, iD=3,iH=4,iW=3, iC=4,oC=3, kD=2,kH=3,kW=2, sD=1,sH=1,sW=1, pD=0,pH=0,pW=0, dD=1,dH=1,dW=1; int paddingMode = 1; // 1-SAME, 0-VALID; int dataFormat = 1; // 1-NDHWC, 0-NCDHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iD, iH, iW, iC}); auto weights = NDArrayFactory::create<TypeParam>('c', {kD, kH, kW, iC, oC}); auto expected = NDArrayFactory::create<TypeParam>('c', {2, 3, 4, 3, 3}, {64.,64.,64.,64.,64.,64.,32.,32.,32.,96.,96.,96.,96.,96.,96.,48.,48.,48.,96.,96.,96.,96.,96.,96.,48.,48.,48., 64.,64.,64.,64.,64.,64.,32.,32.,32.,64.,64.,64.,64.,64.,64.,32.,32.,32.,96.,96.,96.,96.,96.,96.,48.,48.,48., 96.,96.,96.,96.,96.,96.,48.,48.,48.,64.,64.,64.,64.,64.,64.,32.,32.,32.,32.,32.,32.,32.,32.,32.,16.,16.,16., 48.,48.,48.,48.,48.,48.,24.,24.,24.,48.,48.,48.,48.,48.,48.,24.,24.,24.,32.,32.,32.,32.,32.,32.,16.,16.,16., 64.,64.,64.,64.,64.,64.,32.,32.,32.,96.,96.,96.,96.,96.,96.,48.,48.,48.,96.,96.,96.,96.,96.,96.,48.,48.,48., 64.,64.,64.,64.,64.,64.,32.,32.,32.,64.,64.,64.,64.,64.,64.,32.,32.,32.,96.,96.,96.,96.,96.,96.,48.,48.,48., 96.,96.,96.,96.,96.,96.,48.,48.,48.,64.,64.,64.,64.,64.,64.,32.,32.,32.,32.,32.,32.,32.,32.,32.,16.,16.,16., 48.,48.,48.,48.,48.,48.,24.,24.,24.,48.,48.,48.,48.,48.,48.,24.,24.,24.,32.,32.,32.,32.,32.,32.,16.,16.,16.}); input = 2.; weights = 1.; nd4j::ops::conv3dnew op; auto results = op.execute({&input, &weights}, {}, {kD,kH,kW, sD,sH,sW, pD,pH,pW, dD,dH,dW, paddingMode, dataFormat}); auto* output = results->at(0); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); delete results; } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, conv3d_test2) { int bS=2, iD=3,iH=4,iW=3, iC=4,oC=3, kD=2,kH=3,kW=2, sD=1,sH=1,sW=1, pD=0,pH=0,pW=0, dD=1,dH=1,dW=1; int paddingMode = 1; // 1-SAME, 0-VALID; int dataFormat = 1; // 1-NDHWC, 0-NCDHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iD, iH, iW, iC}); auto weights = NDArrayFactory::create<TypeParam>('c', {kD, kH, kW, iC, oC}); auto expected = NDArrayFactory::create<TypeParam>('c', {2, 3, 4, 3, 3}, {534.4,540.8,547.2,534.4,540.8,547.2,248. ,251.2,254.4,686.4,696. ,705.6,686.4,696. ,705.6,314.4,319.2,324. ,686.4,696. ,705.6,686.4,696. ,705.6,314.4,319.2,324. , 380.8,387.2,393.6,380.8,387.2,393.6,171.2,174.4,177.6,534.4,540.8,547.2,534.4,540.8,547.2,248. ,251.2,254.4,686.4,696. ,705.6,686.4,696. ,705.6,314.4,319.2,324. , 686.4,696. ,705.6,686.4,696. ,705.6,314.4,319.2,324. ,380.8,387.2,393.6,380.8,387.2,393.6,171.2,174.4,177.6,152. ,155.2,158.4,152. ,155.2,158.4, 66.4, 68. , 69.6, 170.4,175.2,180. ,170.4,175.2,180. , 70.8, 73.2, 75.6,170.4,175.2,180. ,170.4,175.2,180. , 70.8, 73.2, 75.6, 75.2, 78.4, 81.6, 75.2, 78.4, 81.6, 28. , 29.6, 31.2, 534.4,540.8,547.2,534.4,540.8,547.2,248. ,251.2,254.4,686.4,696. ,705.6,686.4,696. ,705.6,314.4,319.2,324. ,686.4,696. ,705.6,686.4,696. ,705.6,314.4,319.2,324. , 380.8,387.2,393.6,380.8,387.2,393.6,171.2,174.4,177.6,534.4,540.8,547.2,534.4,540.8,547.2,248. ,251.2,254.4,686.4,696. ,705.6,686.4,696. ,705.6,314.4,319.2,324. , 686.4,696. ,705.6,686.4,696. ,705.6,314.4,319.2,324. ,380.8,387.2,393.6,380.8,387.2,393.6,171.2,174.4,177.6,152. ,155.2,158.4,152. ,155.2,158.4, 66.4, 68. , 69.6, 170.4,175.2,180. ,170.4,175.2,180. , 70.8, 73.2, 75.6,170.4,175.2,180. ,170.4,175.2,180. , 70.8, 73.2, 75.6, 75.2, 78.4, 81.6, 75.2, 78.4, 81.6, 28. , 29.6, 31.2}); input = 2.; weights.linspace(0.1, 0.1); nd4j::ops::conv3dnew op; auto results = op.execute({&input, &weights}, {}, {kD,kH,kW, sD,sH,sW, pD,pH,pW, dD,dH,dW, paddingMode, dataFormat}); auto* output = results->at(0); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); delete results; } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, conv3d_test3) { int bS=2, iD=3,iH=4,iW=3, iC=4,oC=3, kD=2,kH=3,kW=2, sD=1,sH=1,sW=1, pD=0,pH=0,pW=0, dD=1,dH=1,dW=1; int paddingMode = 0; // 1-SAME, 0-VALID; int dataFormat = 1; // 1-NDHWC, 0-NCDHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iD, iH, iW, iC}); auto weights = NDArrayFactory::create<TypeParam>('c', {kD, kH, kW, iC, oC}); auto expected = NDArrayFactory::create<TypeParam>('c', {2, 2, 2, 2, 3}, {686.4,696.,705.6,686.4,696.,705.6,686.4,696.,705.6,686.4,696.,705.6, 686.4,696.,705.6,686.4,696.,705.6,686.4,696.,705.6,686.4,696.,705.6, 686.4,696.,705.6,686.4,696.,705.6,686.4,696.,705.6,686.4,696.,705.6, 686.4,696.,705.6,686.4,696.,705.6,686.4,696.,705.6,686.4,696.,705.6}); input = 2.; weights.linspace(0.1, 0.1); nd4j::ops::conv3dnew op; auto results = op.execute({&input, &weights}, {}, {kD,kH,kW, sD,sH,sW, pD,pH,pW, dD,dH,dW, paddingMode, dataFormat}); auto* output = results->at(0); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); delete results; } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, conv3d_test4) { int bS=2, iD=3,iH=4,iW=3, iC=4,oC=3, kD=2,kH=3,kW=2, sD=1,sH=1,sW=1, pD=0,pH=0,pW=0, dD=1,dH=1,dW=1; int paddingMode = 0; // 1-SAME, 0-VALID; int dataFormat = 0; // 1-NDHWC, 0-NCDHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iC, iD, iH, iW}); auto weights = NDArrayFactory::create<TypeParam>('c', {kD, kH, kW, iC, oC}); auto expected = NDArrayFactory::create<TypeParam>('c', {2, 3, 2, 2, 2}); input = 2.; weights = 0.5; expected = 48.; nd4j::ops::conv3dnew op; auto results = op.execute({&input, &weights}, {}, {kD,kH,kW, sD,sH,sW, pD,pH,pW, dD,dH,dW, paddingMode, dataFormat}); auto* output = results->at(0); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); delete results; } //////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, conv3d_test5) { int bS=2, iD=3,iH=4,iW=3, iC=4,oC=3, kD=2,kH=3,kW=2, sD=1,sH=1,sW=1, pD=0,pH=0,pW=0, dD=1,dH=1,dW=1; int paddingMode = 0; // 1-SAME, 0-VALID; int dataFormat = 0; // 1-NDHWC, 0-NCDHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iC, iD, iH, iW}); auto weights = NDArrayFactory::create<TypeParam>('c', {kD, kH, kW, iC, oC}); auto bias = NDArrayFactory::create<TypeParam>('c', {oC}); auto expected = NDArrayFactory::create<TypeParam>('c', {2, 3, 2, 2, 2}); input = 2.; weights = 0.5; expected = 49.; bias = 1.; nd4j::ops::conv3dnew op; auto results = op.execute({&input, &weights, &bias}, {}, {kD,kH,kW, sD,sH,sW, pD,pH,pW, dD,dH,dW, paddingMode, dataFormat}); auto* output = results->at(0); // output->printIndexedBuffer(); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); delete results; } //////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, conv3d_test6) { int bS=2, iD=3,iH=4,iW=3, iC=4,oC=3, kD=2,kH=3,kW=2, sD=1,sH=1,sW=1, pD=0,pH=0,pW=0, dD=1,dH=1,dW=1; int paddingMode = 0; // 1-SAME, 0-VALID; int dataFormat = 0; // 1-NDHWC, 0-NCDHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iC, iD, iH, iW}); auto weights = NDArrayFactory::create<TypeParam>('c', {kD, kH, kW, iC, oC}); auto bias = NDArrayFactory::create<TypeParam>('c', {oC},{1,2,3}); auto expected = NDArrayFactory::create<TypeParam>('c', {2, 3, 2, 2, 2},{49., 49.,49., 49., 49., 49.,49., 49., 50., 50.,50., 50., 50., 50.,50., 50., 51., 51.,51., 51., 51., 51.,51., 51., 49., 49.,49., 49., 49., 49.,49., 49., 50., 50.,50., 50., 50., 50.,50., 50., 51., 51.,51., 51., 51., 51.,51., 51.}); input = 2.; weights = 0.5; nd4j::ops::conv3dnew op; auto results = op.execute({&input, &weights, &bias}, {}, {kD,kH,kW, sD,sH,sW, pD,pH,pW, dD,dH,dW, paddingMode, dataFormat}); auto* output = results->at(0); // output->printIndexedBuffer(); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); delete results; } //////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, conv3d_test7) { int bS=2, iD=3,iH=4,iW=3, iC=4,oC=3, kD=2,kH=3,kW=2, sD=1,sH=1,sW=1, pD=0,pH=0,pW=0, dD=1,dH=1,dW=1; int paddingMode = 0; // 1-SAME, 0-VALID; int dataFormat = 0; // 1-NDHWC, 0-NCDHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iC, iD, iH, iW}); auto weights = NDArrayFactory::create<TypeParam>('c', {oC, iC, kD, kH, kW}); auto bias = NDArrayFactory::create<TypeParam>('c', {oC},{1,2,3}); auto expected = NDArrayFactory::create<TypeParam>('c', {2, 3, 2, 2, 2},{236.2, 236.2, 236.2, 236.2, 236.2, 236.2, 236.2, 236.2, 698. , 698. , 698. , 698. , 698. , 698. , 698. , 698. ,1159.8,1159.8,1159.8,1159.8,1159.8,1159.8,1159.8,1159.8, 236.2, 236.2, 236.2, 236.2, 236.2, 236.2, 236.2, 236.2, 698. , 698. , 698. , 698. , 698. , 698. , 698. , 698. ,1159.8,1159.8,1159.8,1159.8,1159.8,1159.8,1159.8,1159.8}); input = 2.; weights.linspace(0.1, 0.1); weights.permutei({2, 3, 4, 1, 0}); nd4j::ops::conv3dnew op; auto results = op.execute({&input, &weights, &bias}, {}, {kD,kH,kW, sD,sH,sW, pD,pH,pW, dD,dH,dW, paddingMode, dataFormat}); auto* output = results->at(0); // output->printIndexedBuffer(); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); delete results; } //////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, conv3d_test8) { int bS=2, iD=3,iH=4,iW=3, iC=4,oC=3, kD=2,kH=3,kW=2, sD=1,sH=1,sW=1, pD=0,pH=0,pW=0, dD=1,dH=1,dW=1; int paddingMode = 0; // 1-SAME, 0-VALID; int dataFormat = 0; // 1-NDHWC, 0-NCDHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iC, iD, iH, iW}); auto weights = NDArrayFactory::create<TypeParam>('c', {oC, iC, kD, kH, kW}); auto expected = NDArrayFactory::create<TypeParam>('c', {2, 3, 2, 2, 2},{235.2, 235.2, 235.2, 235.2, 235.2, 235.2, 235.2, 235.2, 696. , 696. , 696. , 696. , 696. , 696. , 696. , 696. , 1156.8,1156.8,1156.8,1156.8,1156.8,1156.8,1156.8,1156.8, 235.2, 235.2, 235.2, 235.2, 235.2, 235.2, 235.2, 235.2, 696. , 696. , 696. , 696. , 696. , 696. , 696. , 696. ,1156.8,1156.8,1156.8,1156.8,1156.8,1156.8,1156.8,1156.8}); input = 2.; weights.linspace(0.1, 0.1); weights.permutei({2, 3, 4, 1, 0}); nd4j::ops::conv3dnew op; auto results = op.execute({&input, &weights}, {}, {kD,kH,kW, sD,sH,sW, pD,pH,pW, dD,dH,dW, paddingMode, dataFormat}); auto* output = results->at(0); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expected.isSameShape(output)); ASSERT_TRUE(expected.equalsTo(output)); delete results; } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, conv3d_test9) { auto x = NDArrayFactory::create<TypeParam>('c', {4, 2, 28, 28, 3}); auto y = NDArrayFactory::create<TypeParam>('c', {2, 5, 5, 3, 4}); auto e = NDArrayFactory::create<TypeParam>('c', {4, 1, 7, 10, 4}); nd4j::ops::conv3dnew op; auto result = op.execute({&x, &y}, {}, {2,5,5, 5,4,3, 0,0,0, 1,1,1, 1,1}); ASSERT_EQ(Status::OK(), result->status()); auto z = result->at(0); ASSERT_TRUE(e.isSameShape(z)); delete result; } TYPED_TEST(TypedConvolutionTests1, conv3d_test10) { auto x = NDArrayFactory::create<TypeParam>('c', {4, 2, 28, 28, 3}); auto w = NDArrayFactory::create<TypeParam>('c', {2, 5, 5, 3, 4}); auto exp = NDArrayFactory::create<TypeParam>('c', {4, 1, 7, 10, 4}); nd4j::ops::conv3dnew op; auto result = op.execute({&x, &w}, {}, {2,5,5, 5,4,3, 0,0,0, 1,1,1, 1,1}); ASSERT_EQ(Status::OK(), result->status()); ShapeList shapeList({x.shapeInfo(), w.shapeInfo()}); ContextPrototype proto; Context ctx(1); ctx.getIArguments()->push_back(2); ctx.getIArguments()->push_back(5); ctx.getIArguments()->push_back(5); ctx.getIArguments()->push_back(5); ctx.getIArguments()->push_back(4); ctx.getIArguments()->push_back(3); ctx.getIArguments()->push_back(0); ctx.getIArguments()->push_back(0); ctx.getIArguments()->push_back(0); ctx.getIArguments()->push_back(1); ctx.getIArguments()->push_back(1); ctx.getIArguments()->push_back(1); ctx.getIArguments()->push_back(0); ctx.getIArguments()->push_back(1); // previous variant was "ctx.getIArguments()->push_back(0)" and this caused fail auto shapes = op.calculateOutputShape(&shapeList, ctx); ASSERT_EQ(1, shapes->size()); auto s = shapes->at(0); auto z = result->at(0); // z->printShapeInfo("z shape"); ASSERT_TRUE(exp.isSameShape(z)); delete result; shapes->destroy(); delete shapes; } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, pointwise_conv2d_test1) { int bS=2, iH=4,iW=3, iC=4,oC=3; int dataFormat = 1; // 1-NHWC, 0-NCHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iH, iW, iC}); auto weights = NDArrayFactory::create<TypeParam>('c', {1, 1, iC, oC}); auto bias = NDArrayFactory::create<TypeParam>('c', {oC}); auto expOutput = NDArrayFactory::create<TypeParam>('c', {bS, iH, iW, oC},{ 5.4, 6.2, 7.0, 5.4, 6.2, 7.0, 5.4, 6.2, 7.0, 5.4, 6.2, 7.0, 5.4, 6.2, 7.0, 5.4, 6.2, 7.0, 5.4, 6.2, 7.0, 5.4, 6.2, 7.0, 5.4, 6.2, 7.0, 5.4, 6.2, 7.0, 5.4, 6.2, 7.0, 5.4, 6.2, 7.0, 5.4, 6.2, 7.0, 5.4, 6.2, 7.0, 5.4, 6.2, 7.0, 5.4, 6.2, 7.0, 5.4, 6.2, 7.0, 5.4, 6.2, 7.0, 5.4, 6.2, 7.0, 5.4, 6.2, 7.0, 5.4, 6.2, 7.0, 5.4, 6.2, 7.0, 5.4, 6.2, 7.0, 5.4, 6.2, 7.0}); input = 2.; weights.linspace(0.1, 0.1); bias = 1.; nd4j::ops::pointwise_conv2d op; auto results = op.execute({&input, &weights, &bias}, {}, {dataFormat}); auto* output = results->at(0); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expOutput.isSameShape(output)); ASSERT_TRUE(expOutput.equalsTo(output)); delete results; } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, sconv2d_bp_test1) { int bS=2, iH=4,iW=3, iC=2,mC=2, kH=3,kW=2, sH=1,sW=1, pH=0,pW=0, dH=1,dW=1; int oH=4,oW=3; int oC=iC*mC; int paddingMode = 1; // 1-SAME, 0-VALID; int dataFormat = 1; // 1-NHWC, 0-NCHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iH, iW, iC}); auto weightsDepth = NDArrayFactory::create<TypeParam>('c', {kH, kW, iC, mC}); auto bias = NDArrayFactory::create<TypeParam>('c', {oC}, {1,2,3,4}); auto gradO = NDArrayFactory::create<TypeParam>('c', {bS, oH, oW, oC}); auto expGradI = NDArrayFactory::create<TypeParam>('c', {bS, iH, iW, iC},{0.07 , 0.19 , 0.348, 0.652, 0.588, 0.956, 0.387, 0.687, 1.326, 2.022, 1.878, 2.67 , 1.071, 1.515, 2.982, 3.966, 3.534, 4.614, 1.606, 1.982, 3.932, 4.748, 4.428, 5.308, 1.126, 1.63 , 3.228, 4.3 , 3.468, 4.604, 3.123, 3.999, 7.95 , 9.798, 8.502, 10.446, 3.807, 4.827, 9.606, 11.742,10.158, 12.39 , 4.198, 4.958, 9.884, 11.468,10.38 , 12.028}); auto expGradW = NDArrayFactory::create<TypeParam>('c', {kH, kW, iC, mC},{19.08, 19.44,19.8 , 20.16,12.24, 12.48,12.72, 12.96,22.56, 23.04,23.52, 24. ,14.4 , 14.72,15.04, 15.36,14.76, 15.12,15.48, 15.84, 9.36, 9.6 , 9.84, 10.08}); input = 2.; weightsDepth.linspace(0.1, 0.1); gradO.linspace(0.01, 0.01); nd4j::ops::sconv2d_bp op; auto results = op.execute({&input, &gradO, &weightsDepth, &bias}, {}, {kH,kW, sH,sW, pH,pW, dH,dW, paddingMode, dataFormat}); auto* gradI = results->at(0); auto* gradWD = results->at(1); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expGradI.isSameShape(gradI)); ASSERT_TRUE(expGradI.equalsTo(gradI)); ASSERT_TRUE(expGradW.isSameShape(gradWD)); ASSERT_TRUE(expGradW.equalsTo(gradWD)); delete results; } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, conv2d_test4) { int bS=1, iH=256,iW=256, iC=1,oC=1, kH=4,kW=3, sH=1,sW=1, pH=0,pW=0, dH=1,dW=1; // int oH=256,oW=256; int paddingMode = 1; // 1-SAME, 0-VALID; int dataFormat = 0; // 1-NHWC, 0-NCHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iC, iH, iW}); auto weights = NDArrayFactory::create<TypeParam>('c', {kH, kW, iC, oC}); input = 5.; weights = 3.; nd4j::ops::conv2d op; auto results = op.execute({&input, &weights}, {}, {kH,kW, sH,sW, pH,pW, dH,dW, paddingMode, dataFormat}); auto* output = results->at(0); ASSERT_EQ(Status::OK(), results->status()); delete results; } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, conv3d_test11) { int bS=1, iD=2,iH=2,iW=2, iC=1,oC=1, kD=2,kH=2,kW=2, sD=1,sH=1,sW=1, pD=0,pH=0,pW=0, dD=1,dH=1,dW=1; int paddingMode = 1; // 1-SAME, 0-VALID; int dataFormat = 0; // 1-NDHWC, 0-NCDHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iC, iD, iH, iW}); auto weights = NDArrayFactory::create<TypeParam>('c', {kD, kH, kW, iC, oC}); input = 2.; weights = 1.; nd4j::ops::conv3dnew op; auto results = op.execute({&input, &weights}, {}, {kD,kH,kW, sD,sH,sW, pD,pH,pW, dD,dH,dW, paddingMode, dataFormat}); auto* output = results->at(0); ASSERT_EQ(Status::OK(), results->status()); delete results; } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, conv3d_test12) { int bS=5, iD=4,iH=14,iW=14, iC=1,oC=1, kD=2,kH=2,kW=2, sD=1,sH=1,sW=1, pD=0,pH=0,pW=0, dD=1,dH=1,dW=1; int oD=3,oH=13,oW=13; int paddingMode = 0; // 1-SAME, 0-VALID; int dataFormat = 0; // 1-NDHWC, 0-NCDHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iC, iD, iH, iW}); auto weights = NDArrayFactory::create<TypeParam>('c', {kD, kH, kW, iC, oC}); auto expected = NDArrayFactory::create<TypeParam>('c', {bS, oC, oD, oH, oW}); input = 2.; weights = 1.; nd4j::ops::conv3dnew op; auto results = op.execute({&input, &weights}, {}, {kD,kH,kW, sD,sH,sW, pD,pH,pW, dD,dH,dW, paddingMode, dataFormat}); auto* output = results->at(0); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(output->isSameShape(&expected)); delete results; } ////////////////////////////////////////////////////////////////////// TEST_F(ConvolutionTests1, vol2col_test1) { int bS=2, iD=2,iH=3,iW=2, iC=3,oC=2, kD=2,kH=3,kW=2, sD=1,sH=1,sW=1, pD=0,pH=0,pW=0, dD=1,dH=1,dW=1; int oD=2,oH=3,oW=2; NDArray volume('c', {bS, iD, iH, iW, iC}, nd4j::DataType::FLOAT32); NDArray columns('c', {bS, iC, kD, kH, kW, oD, oH, oW}, nd4j::DataType::FLOAT32); columns = -1.; volume.linspace(1); NDArray columnsExpected('c', {bS, iC, kD, kH, kW, oD, oH, oW}, {1., 2., 4., 5., 0., 0., 7., 8., 10., 11., 0., 0., 2., 3., 5., 6., 0., 0., 8., 9., 11., 12., 0., 0., 4., 5., 0., 0., 0., 0., 10., 11., 0., 0., 0., 0., 5., 6., 0., 0., 0., 0., 11., 12., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 7., 8., 10., 11., 0., 0., 13., 14., 16., 17., 0., 0., 8., 9., 11., 12., 0., 0., 14., 15., 17., 18., 0., 0., 10., 11., 0., 0., 0., 0., 16., 17., 0., 0., 0., 0., 11., 12., 0., 0., 0., 0., 17., 18., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 19., 20., 22., 23., 0., 0., 25., 26., 28., 29., 0., 0., 20., 21., 23., 24., 0., 0., 26., 27., 29., 30., 0., 0., 22., 23., 0., 0., 0., 0., 28., 29., 0., 0., 0., 0., 23., 24., 0., 0., 0., 0., 29., 30., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 25., 26., 28., 29., 0., 0., 31., 32., 34., 35., 0., 0., 26., 27., 29., 30., 0., 0., 32., 33., 35., 36., 0., 0., 28., 29., 0., 0., 0., 0., 34., 35., 0., 0., 0., 0., 29., 30., 0., 0., 0., 0., 35., 36., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., 37., 38., 40., 41., 0., 0., 43., 44., 46., 47., 0., 0., 38., 39., 41., 42., 0., 0., 44., 45., 47., 48., 0., 0., 40., 41., 0., 0., 0., 0., 46., 47., 0., 0., 0., 0., 41., 42., 0., 0., 0., 0., 47., 48., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 43., 44., 46., 47., 0., 0., 49., 50., 52., 53., 0., 0., 44., 45., 47., 48., 0., 0., 50., 51., 53., 54., 0., 0., 46., 47., 0., 0., 0., 0., 52., 53., 0., 0., 0., 0., 47., 48., 0., 0., 0., 0., 53., 54., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 55., 56., 58., 59., 0., 0., 61., 62., 64., 65., 0., 0., 56., 57., 59., 60., 0., 0., 62., 63., 65., 66., 0., 0., 58., 59., 0., 0., 0., 0., 64., 65., 0., 0., 0., 0., 59., 60., 0., 0., 0., 0., 65., 66., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,0., 0., 0., 0., 61., 62., 64., 65., 0., 0., 67., 68., 70., 71., 0., 0., 62., 63., 65., 66., 0., 0., 68., 69., 71., 72., 0., 0., 64., 65., 0., 0., 0., 0., 70., 71., 0., 0., 0., 0., 65., 66., 0., 0., 0., 0., 71., 72., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1.}, nd4j::DataType::FLOAT32); // PointersManager manager(columnsExpected.getContext()); // manager.printDevContentOnHost<float>(columnsExpected.getSpecialBuffer(), columnsExpected.lengthOf()); graph::Context context(1); nd4j::ops::ConvolutionUtils::vol2col(context, volume, columns, sD, sH, sW, pD, pH, pW, dD, dH, dW); ASSERT_TRUE(columns.equalsTo(columnsExpected)); } ////////////////////////////////////////////////////////////////////// TEST_F(ConvolutionTests1, vol2col_test2) { int bS=2, iD=2,iH=3,iW=2, iC=3,oC=2, kD=2,kH=3,kW=2, sD=1,sH=1,sW=1, pD=0,pH=0,pW=0, dD=1,dH=1,dW=1; int oD=2,oH=3,oW=2; auto volume = NDArrayFactory::create<float>('c', {iD, bS, iH, iC, iW}); volume.permutei({1, 0, 2, 4, 3}); volume.linspace(1); auto columns = NDArrayFactory::create<float>('c', {kD, iC, kH, oW, kW, bS, oD, oH}); columns.permutei({5, 1, 0, 2, 4, 6, 7, 3}); columns = -1.; auto columnsExpected = NDArrayFactory::create<float>('c', {bS, iC, kD, kH, kW, oD, oH, oW}, {1., 2., 4., 5., 0., 0., 7., 8., 10., 11., 0., 0., 2., 3., 5., 6., 0., 0., 8., 9., 11., 12., 0., 0., 4., 5., 0., 0., 0., 0., 10., 11., 0., 0., 0., 0., 5., 6., 0., 0., 0., 0., 11., 12., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 7., 8., 10., 11., 0., 0., 13., 14., 16., 17., 0., 0., 8., 9., 11., 12., 0., 0., 14., 15., 17., 18., 0., 0., 10., 11., 0., 0., 0., 0., 16., 17., 0., 0., 0., 0., 11., 12., 0., 0., 0., 0., 17., 18., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 19., 20., 22., 23., 0., 0., 25., 26., 28., 29., 0., 0., 20., 21., 23., 24., 0., 0., 26., 27., 29., 30., 0., 0., 22., 23., 0., 0., 0., 0., 28., 29., 0., 0., 0., 0., 23., 24., 0., 0., 0., 0., 29., 30., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 25., 26., 28., 29., 0., 0., 31., 32., 34., 35., 0., 0., 26., 27., 29., 30., 0., 0., 32., 33., 35., 36., 0., 0., 28., 29., 0., 0., 0., 0., 34., 35., 0., 0., 0., 0., 29., 30., 0., 0., 0., 0., 35., 36., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., 37., 38., 40., 41., 0., 0., 43., 44., 46., 47., 0., 0., 38., 39., 41., 42., 0., 0., 44., 45., 47., 48., 0., 0., 40., 41., 0., 0., 0., 0., 46., 47., 0., 0., 0., 0., 41., 42., 0., 0., 0., 0., 47., 48., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 43., 44., 46., 47., 0., 0., 49., 50., 52., 53., 0., 0., 44., 45., 47., 48., 0., 0., 50., 51., 53., 54., 0., 0., 46., 47., 0., 0., 0., 0., 52., 53., 0., 0., 0., 0., 47., 48., 0., 0., 0., 0., 53., 54., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 55., 56., 58., 59., 0., 0., 61., 62., 64., 65., 0., 0., 56., 57., 59., 60., 0., 0., 62., 63., 65., 66., 0., 0., 58., 59., 0., 0., 0., 0., 64., 65., 0., 0., 0., 0., 59., 60., 0., 0., 0., 0., 65., 66., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,0., 0., 0., 0., 61., 62., 64., 65., 0., 0., 67., 68., 70., 71., 0., 0., 62., 63., 65., 66., 0., 0., 68., 69., 71., 72., 0., 0., 64., 65., 0., 0., 0., 0., 70., 71., 0., 0., 0., 0., 65., 66., 0., 0., 0., 0., 71., 72., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1.}); graph::Context context(1); nd4j::ops::ConvolutionUtils::vol2col(context, volume, columns, sD, sH, sW, pD, pH, pW, dD, dH, dW); ASSERT_TRUE(columns.equalsTo(columnsExpected)); } ////////////////////////////////////////////////////////////////////// TEST_F(ConvolutionTests1, col2im_test1) { int bS=2, iH=2,iW=2, iC=2, kH=2,kW=2, sD=1,sH=1,sW=1, pD=0,pH=0,pW=0, dD=1,dH=1,dW=1; int oH=2,oW=2; auto image = NDArrayFactory::create<float>('c', {bS, iC, iH, iW}); image = -2.; auto columns = NDArrayFactory::create<float>('c', {bS, iC, kH, kW, oH, oW}); columns.linspace(1); auto imageExpected = NDArrayFactory::create<float>('c', {bS, iC, iH, iW}, {1., 7., 12., 34., 17., 39., 44., 98., 33., 71., 76., 162., 49., 103., 108., 226.}); LaunchContext ctx; nd4j::ops::helpers::col2im(ctx, columns, image, sH, sW, pH, pW, iH, iW, dH, dW); ASSERT_TRUE(image.equalsTo(imageExpected)); } ////////////////////////////////////////////////////////////////////// TEST_F(ConvolutionTests1, upsampling2d_test1) { const int bS=3, iH=2,iW=2, iC=3; const int factorH=2, factorW=3; const int isNCHW = 0; // data format, default is NCHW auto input = NDArrayFactory::create<float>('c', {bS, iH, iW, iC}); input.linspace(1); auto expOutput = NDArrayFactory::create<float>('c', {bS, iH*factorH, iW*factorW, iC}, {1., 2., 3., 1., 2., 3., 1., 2., 3., 4., 5., 6., 4., 5., 6., 4., 5., 6., 1., 2., 3., 1., 2., 3., 1., 2., 3., 4., 5., 6., 4., 5., 6., 4., 5., 6., 7., 8., 9., 7., 8., 9., 7., 8., 9.,10., 11., 12.,10., 11., 12.,10., 11., 12., 7., 8., 9., 7., 8., 9., 7., 8., 9.,10., 11., 12.,10., 11., 12.,10., 11., 12., 13., 14., 15.,13., 14., 15.,13., 14., 15.,16., 17., 18.,16., 17., 18.,16., 17., 18.,13., 14., 15.,13., 14., 15.,13., 14., 15.,16., 17., 18.,16., 17., 18.,16., 17., 18., 19., 20., 21.,19., 20., 21.,19., 20., 21.,22., 23., 24.,22., 23., 24.,22., 23., 24.,19., 20., 21.,19., 20., 21.,19., 20., 21.,22., 23., 24.,22., 23., 24.,22., 23., 24., 25., 26., 27.,25., 26., 27.,25., 26., 27.,28., 29., 30.,28., 29., 30.,28., 29., 30.,25., 26., 27.,25., 26., 27.,25., 26., 27.,28., 29., 30.,28., 29., 30.,28., 29., 30., 31., 32., 33.,31., 32., 33.,31., 32., 33.,34., 35., 36.,34., 35., 36.,34., 35., 36.,31., 32., 33.,31., 32., 33.,31., 32., 33.,34., 35., 36.,34., 35., 36.,34., 35., 36.}); nd4j::ops::upsampling2d op; auto results = op.execute({&input}, {}, {factorH, factorW, isNCHW}); auto* output = results->at(0); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expOutput.isSameShape(output)); ASSERT_TRUE(expOutput.equalsTo(output)); delete results; } ////////////////////////////////////////////////////////////////////// TEST_F(ConvolutionTests1, upsampling2d_test2) { const int bS=3, iH=2,iW=2, iC=3; const int factorH=2, factorW=3; const int isNCHW = 1; // data format, default is NCHW auto input = NDArrayFactory::create<float>('c', {bS, iC, iH, iW}); input.linspace(1); auto expOutput = NDArrayFactory::create<float>('c', {bS, iC, iH*factorH, iW*factorW}, {1., 1., 1., 2., 2., 2., 1., 1., 1., 2., 2., 2., 3., 3., 3., 4., 4., 4., 3., 3., 3., 4., 4., 4., 5., 5., 5., 6., 6., 6., 5., 5., 5., 6., 6., 6., 7., 7., 7., 8., 8., 8., 7., 7., 7., 8., 8., 8., 9., 9., 9., 10., 10., 10., 9., 9., 9., 10., 10., 10.,11., 11., 11., 12., 12., 12.,11., 11., 11., 12., 12., 12., 13., 13., 13., 14., 14., 14.,13., 13., 13., 14., 14., 14.,15., 15., 15., 16., 16., 16.,15., 15., 15., 16., 16., 16.,17., 17., 17., 18., 18., 18.,17., 17., 17., 18., 18., 18.,19., 19., 19., 20., 20., 20.,19., 19., 19., 20., 20., 20., 21., 21., 21., 22., 22., 22.,21., 21., 21., 22., 22., 22.,23., 23., 23., 24., 24., 24.,23., 23., 23., 24., 24., 24.,25., 25., 25., 26., 26., 26.,25., 25., 25., 26., 26., 26.,27., 27., 27., 28., 28., 28.,27., 27., 27., 28., 28., 28., 29., 29., 29., 30., 30., 30.,29., 29., 29., 30., 30., 30.,31., 31., 31., 32., 32., 32.,31., 31., 31., 32., 32., 32., 33., 33., 33., 34., 34., 34.,33., 33., 33., 34., 34., 34.,35., 35., 35., 36., 36., 36.,35., 35., 35., 36., 36., 36.}); nd4j::ops::upsampling2d op; auto results = op.execute({&input}, {}, {factorH, factorW, isNCHW}); auto* output = results->at(0); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expOutput.isSameShape(output)); ASSERT_TRUE(expOutput.equalsTo(output)); delete results; } ////////////////////////////////////////////////////////////////////// TEST_F(ConvolutionTests1, upsampling3d_test1) { const int bS=3, iD=2,iH=2,iW=2, iC=3; const int factorD=2,factorH=3,factorW=2; const int isNCDHW = 0; // data format, default is NCHW auto input = NDArrayFactory::create<float>('c', {bS, iD, iH, iW, iC}); input.linspace(1); auto expOutput = NDArrayFactory::create<float>('c', {bS, iD*factorD, iH*factorH, iW*factorW, iC}, {1., 2., 3., 1., 2., 3., 4., 5., 6., 4., 5., 6., 1., 2., 3., 1., 2., 3., 4., 5., 6., 4., 5., 6., 1., 2., 3., 1., 2., 3., 4., 5., 6., 4., 5., 6., 7., 8., 9., 7., 8., 9.,10., 11., 12.,10., 11., 12., 7., 8., 9., 7., 8., 9.,10., 11., 12.,10., 11., 12., 7., 8., 9., 7., 8., 9.,10., 11., 12.,10., 11., 12., 1., 2., 3., 1., 2., 3., 4., 5., 6., 4., 5., 6., 1., 2., 3., 1., 2., 3., 4., 5., 6., 4., 5., 6., 1., 2., 3., 1., 2., 3., 4., 5., 6., 4., 5., 6., 7., 8., 9., 7., 8., 9.,10., 11., 12.,10., 11., 12., 7., 8., 9., 7., 8., 9.,10., 11., 12.,10., 11., 12., 7., 8., 9., 7., 8., 9.,10., 11., 12.,10., 11., 12.,13., 14., 15.,13., 14., 15.,16., 17., 18.,16., 17., 18.,13., 14., 15.,13., 14., 15.,16., 17., 18.,16., 17., 18.,13., 14., 15.,13., 14., 15.,16., 17., 18.,16., 17., 18., 19., 20., 21.,19., 20., 21.,22., 23., 24.,22., 23., 24.,19., 20., 21.,19., 20., 21.,22., 23., 24.,22., 23., 24.,19., 20., 21.,19., 20., 21.,22., 23., 24.,22., 23., 24.,13., 14., 15.,13., 14., 15.,16., 17., 18.,16., 17., 18.,13., 14., 15.,13., 14., 15.,16., 17., 18.,16., 17., 18., 13., 14., 15.,13., 14., 15.,16., 17., 18.,16., 17., 18.,19., 20., 21.,19., 20., 21.,22., 23., 24.,22., 23., 24.,19., 20., 21.,19., 20., 21.,22., 23., 24.,22., 23., 24.,19., 20., 21.,19., 20., 21.,22., 23., 24.,22., 23., 24.,25., 26., 27.,25., 26., 27.,28., 29., 30.,28., 29., 30., 25., 26., 27.,25., 26., 27.,28., 29., 30.,28., 29., 30.,25., 26., 27.,25., 26., 27.,28., 29., 30.,28., 29., 30.,31., 32., 33.,31., 32., 33.,34., 35., 36.,34., 35., 36.,31., 32., 33.,31., 32., 33.,34., 35., 36.,34., 35., 36.,31., 32., 33.,31., 32., 33.,34., 35., 36.,34., 35., 36., 25., 26., 27.,25., 26., 27.,28., 29., 30.,28., 29., 30.,25., 26., 27.,25., 26., 27.,28., 29., 30.,28., 29., 30.,25., 26., 27.,25., 26., 27.,28., 29., 30.,28., 29., 30.,31., 32., 33.,31., 32., 33.,34., 35., 36.,34., 35., 36.,31., 32., 33.,31., 32., 33.,34., 35., 36.,34., 35., 36., 31., 32., 33.,31., 32., 33.,34., 35., 36.,34., 35., 36.,37., 38., 39.,37., 38., 39.,40., 41., 42.,40., 41., 42.,37., 38., 39.,37., 38., 39.,40., 41., 42.,40., 41., 42.,37., 38., 39.,37., 38., 39.,40., 41., 42.,40., 41., 42.,43., 44., 45.,43., 44., 45.,46., 47., 48.,46., 47., 48., 43., 44., 45.,43., 44., 45.,46., 47., 48.,46., 47., 48.,43., 44., 45.,43., 44., 45.,46., 47., 48.,46., 47., 48.,37., 38., 39.,37., 38., 39.,40., 41., 42.,40., 41., 42.,37., 38., 39.,37., 38., 39.,40., 41., 42.,40., 41., 42.,37., 38., 39.,37., 38., 39.,40., 41., 42.,40., 41., 42., 43., 44., 45.,43., 44., 45.,46., 47., 48.,46., 47., 48.,43., 44., 45.,43., 44., 45.,46., 47., 48.,46., 47., 48.,43., 44., 45.,43., 44., 45.,46., 47., 48.,46., 47., 48.,49., 50., 51.,49., 50., 51.,52., 53., 54.,52., 53., 54.,49., 50., 51.,49., 50., 51.,52., 53., 54.,52., 53., 54., 49., 50., 51.,49., 50., 51.,52., 53., 54.,52., 53., 54.,55., 56., 57.,55., 56., 57.,58., 59., 60.,58., 59., 60.,55., 56., 57.,55., 56., 57.,58., 59., 60.,58., 59., 60.,55., 56., 57.,55., 56., 57.,58., 59., 60.,58., 59., 60.,49., 50., 51.,49., 50., 51.,52., 53., 54.,52., 53., 54., 49., 50., 51.,49., 50., 51.,52., 53., 54.,52., 53., 54.,49., 50., 51.,49., 50., 51.,52., 53., 54.,52., 53., 54.,55., 56., 57.,55., 56., 57.,58., 59., 60.,58., 59., 60.,55., 56., 57.,55., 56., 57.,58., 59., 60.,58., 59., 60.,55., 56., 57.,55., 56., 57.,58., 59., 60.,58., 59., 60., 61., 62., 63.,61., 62., 63.,64., 65., 66.,64., 65., 66.,61., 62., 63.,61., 62., 63.,64., 65., 66.,64., 65., 66.,61., 62., 63.,61., 62., 63.,64., 65., 66.,64., 65., 66.,67., 68., 69.,67., 68., 69.,70., 71., 72.,70., 71., 72.,67., 68., 69.,67., 68., 69.,70., 71., 72.,70., 71., 72., 67., 68., 69.,67., 68., 69.,70., 71., 72.,70., 71., 72.,61., 62., 63.,61., 62., 63.,64., 65., 66.,64., 65., 66.,61., 62., 63.,61., 62., 63.,64., 65., 66.,64., 65., 66.,61., 62., 63.,61., 62., 63.,64., 65., 66.,64., 65., 66.,67., 68., 69.,67., 68., 69.,70., 71., 72.,70., 71., 72., 67., 68., 69.,67., 68., 69.,70., 71., 72.,70., 71., 72.,67., 68., 69.,67., 68., 69.,70., 71., 72.,70., 71., 72.}); nd4j::ops::upsampling3d op; auto results = op.execute({&input}, {}, {factorD, factorH, factorW, isNCDHW}); auto* output = results->at(0); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expOutput.isSameShape(output)); ASSERT_TRUE(expOutput.equalsTo(output)); delete results; } ////////////////////////////////////////////////////////////////////// TEST_F(ConvolutionTests1, upsampling3d_test2) { const int bS=3, iD=2,iH=2,iW=2, iC=3; const int factorD=2,factorH=3,factorW=2; const int isNCDHW = 1; // data format, default is NCHW auto input = NDArrayFactory::create<float>('c', {bS, iC, iD, iH, iW}); input.linspace(1); auto expOutput = NDArrayFactory::create<float>('c', {bS, iC, iD*factorD, iH*factorH, iW*factorW}, { 1., 1., 2., 2., 1., 1., 2., 2., 1., 1., 2., 2., 3., 3., 4., 4., 3., 3., 4., 4., 3., 3., 4., 4., 1., 1., 2., 2., 1., 1., 2., 2., 1., 1., 2., 2., 3., 3., 4., 4., 3., 3., 4., 4., 3., 3., 4., 4., 5., 5., 6., 6., 5., 5., 6., 6., 5., 5., 6., 6., 7., 7., 8., 8., 7., 7., 8., 8., 7., 7., 8., 8., 5., 5., 6., 6., 5., 5., 6., 6., 5., 5., 6., 6., 7., 7., 8., 8., 7., 7., 8., 8., 7., 7., 8., 8., 9., 9., 10., 10., 9., 9., 10., 10., 9., 9., 10., 10.,11., 11., 12., 12.,11., 11., 12., 12.,11., 11., 12., 12., 9., 9., 10., 10., 9., 9., 10., 10., 9., 9., 10., 10.,11., 11., 12., 12.,11., 11., 12., 12.,11., 11., 12., 12., 13., 13., 14., 14.,13., 13., 14., 14.,13., 13., 14., 14.,15., 15., 16., 16.,15., 15., 16., 16.,15., 15., 16., 16.,13., 13., 14., 14.,13., 13., 14., 14.,13., 13., 14., 14.,15., 15., 16., 16.,15., 15., 16., 16.,15., 15., 16., 16.,17., 17., 18., 18.,17., 17., 18., 18.,17., 17., 18., 18.,19., 19., 20., 20.,19., 19., 20., 20.,19., 19., 20., 20., 17., 17., 18., 18.,17., 17., 18., 18.,17., 17., 18., 18.,19., 19., 20., 20.,19., 19., 20., 20.,19., 19., 20., 20.,21., 21., 22., 22.,21., 21., 22., 22.,21., 21., 22., 22.,23., 23., 24., 24.,23., 23., 24., 24.,23., 23., 24., 24.,21., 21., 22., 22.,21., 21., 22., 22.,21., 21., 22., 22.,23., 23., 24., 24.,23., 23., 24., 24.,23., 23., 24., 24., 25., 25., 26., 26.,25., 25., 26., 26.,25., 25., 26., 26.,27., 27., 28., 28.,27., 27., 28., 28.,27., 27., 28., 28.,25., 25., 26., 26.,25., 25., 26., 26.,25., 25., 26., 26.,27., 27., 28., 28.,27., 27., 28., 28.,27., 27., 28., 28.,29., 29., 30., 30.,29., 29., 30., 30.,29., 29., 30., 30.,31., 31., 32., 32.,31., 31., 32., 32.,31., 31., 32., 32., 29., 29., 30., 30.,29., 29., 30., 30.,29., 29., 30., 30.,31., 31., 32., 32.,31., 31., 32., 32.,31., 31., 32., 32.,33., 33., 34., 34.,33., 33., 34., 34.,33., 33., 34., 34.,35., 35., 36., 36.,35., 35., 36., 36.,35., 35., 36., 36.,33., 33., 34., 34.,33., 33., 34., 34.,33., 33., 34., 34.,35., 35., 36., 36.,35., 35., 36., 36.,35., 35., 36., 36., 37., 37., 38., 38.,37., 37., 38., 38.,37., 37., 38., 38.,39., 39., 40., 40.,39., 39., 40., 40.,39., 39., 40., 40.,37., 37., 38., 38.,37., 37., 38., 38.,37., 37., 38., 38.,39., 39., 40., 40.,39., 39., 40., 40.,39., 39., 40., 40.,41., 41., 42., 42.,41., 41., 42., 42.,41., 41., 42., 42.,43., 43., 44., 44.,43., 43., 44., 44.,43., 43., 44., 44., 41., 41., 42., 42.,41., 41., 42., 42.,41., 41., 42., 42.,43., 43., 44., 44.,43., 43., 44., 44.,43., 43., 44., 44.,45., 45., 46., 46.,45., 45., 46., 46.,45., 45., 46., 46.,47., 47., 48., 48.,47., 47., 48., 48.,47., 47., 48., 48.,45., 45., 46., 46.,45., 45., 46., 46.,45., 45., 46., 46.,47., 47., 48., 48.,47., 47., 48., 48.,47., 47., 48., 48., 49., 49., 50., 50.,49., 49., 50., 50.,49., 49., 50., 50.,51., 51., 52., 52.,51., 51., 52., 52.,51., 51., 52., 52.,49., 49., 50., 50.,49., 49., 50., 50.,49., 49., 50., 50.,51., 51., 52., 52.,51., 51., 52., 52.,51., 51., 52., 52.,53., 53., 54., 54.,53., 53., 54., 54.,53., 53., 54., 54.,55., 55., 56., 56.,55., 55., 56., 56.,55., 55., 56., 56., 53., 53., 54., 54.,53., 53., 54., 54.,53., 53., 54., 54.,55., 55., 56., 56.,55., 55., 56., 56.,55., 55., 56., 56.,57., 57., 58., 58.,57., 57., 58., 58.,57., 57., 58., 58.,59., 59., 60., 60.,59., 59., 60., 60.,59., 59., 60., 60.,57., 57., 58., 58.,57., 57., 58., 58.,57., 57., 58., 58.,59., 59., 60., 60.,59., 59., 60., 60.,59., 59., 60., 60., 61., 61., 62., 62.,61., 61., 62., 62.,61., 61., 62., 62.,63., 63., 64., 64.,63., 63., 64., 64.,63., 63., 64., 64.,61., 61., 62., 62.,61., 61., 62., 62.,61., 61., 62., 62.,63., 63., 64., 64.,63., 63., 64., 64.,63., 63., 64., 64.,65., 65., 66., 66.,65., 65., 66., 66.,65., 65., 66., 66.,67., 67., 68., 68.,67., 67., 68., 68.,67., 67., 68., 68., 65., 65., 66., 66.,65., 65., 66., 66.,65., 65., 66., 66.,67., 67., 68., 68.,67., 67., 68., 68.,67., 67., 68., 68.,69., 69., 70., 70.,69., 69., 70., 70.,69., 69., 70., 70.,71., 71., 72., 72.,71., 71., 72., 72.,71., 71., 72., 72.,69., 69., 70., 70.,69., 69., 70., 70.,69., 69., 70., 70.,71., 71., 72., 72.,71., 71., 72., 72.,71., 71., 72., 72.}); nd4j::ops::upsampling3d op; auto results = op.execute({&input}, {}, {factorD, factorH, factorW, isNCDHW}); auto* output = results->at(0); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expOutput.isSameShape(output)); ASSERT_TRUE(expOutput.equalsTo(output)); delete results; } ////////////////////////////////////////////////////////////////////// TEST_F(ConvolutionTests1, upsampling2d_bp_test1) { const int bS=1, iH=2,iW=2, iC=1; const int factorH=2, factorW=2; const int isNCHW = 1; // data format, default is NCHW auto input = NDArrayFactory::create<float>('c', {bS, iC, iH, iW}); auto gradO = NDArrayFactory::create<float>('c', {bS, iC, iH*factorH, iW*factorW}); gradO = 1.; auto expGradI = NDArrayFactory::create<float>('c', {bS, iC, iH, iW}); expGradI = 4.; nd4j::ops::upsampling2d_bp op; auto results = op.execute({&input, &gradO}, {}, {isNCHW}); auto* gradI = results->at(0); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expGradI.isSameShape(gradI)); ASSERT_TRUE(expGradI.equalsTo(gradI)); delete results; } ////////////////////////////////////////////////////////////////////// TEST_F(ConvolutionTests1, upsampling2d_bp_test2) { const int bS=1, iH=2,iW=2, iC=1; const int factorH=2, factorW=2; const int isNCHW = 0; // data format, default is NCHW auto input = NDArrayFactory::create<float>('c', {bS, iH, iW, iC}); auto gradO = NDArrayFactory::create<float>('c', {bS, iH*factorH, iW*factorW, iC}); gradO = 1.; auto expGradI = NDArrayFactory::create<float>('c', {bS, iH, iW, iC}); expGradI = 4.; nd4j::ops::upsampling2d_bp op; auto results = op.execute({&input, &gradO}, {}, {isNCHW}); auto* gradI = results->at(0); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expGradI.isSameShape(gradI)); ASSERT_TRUE(expGradI.equalsTo(gradI)); delete results; } ////////////////////////////////////////////////////////////////////// TEST_F(ConvolutionTests1, upsampling3d_bp_test1) { const int bS=1, iD=2,iH=2,iW=2, iC=1; const int factorD=2, factorH=2, factorW=2; const int isNCDHW = 1; // data format, default is NCHW auto input = NDArrayFactory::create<float>('c', {bS, iC, iD, iH, iW}); auto gradO = NDArrayFactory::create<float>('c', {bS, iC, iD*factorD, iH*factorH, iW*factorW}); gradO = 1.; auto expGradI = NDArrayFactory::create<float>('c', {bS, iC, iD, iH, iW}); expGradI = 8.; nd4j::ops::upsampling3d_bp op; auto results = op.execute({&input, &gradO}, {}, {isNCDHW}); auto* gradI = results->at(0); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expGradI.isSameShape(gradI)); ASSERT_TRUE(expGradI.equalsTo(gradI)); delete results; } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, maxpool_test6) { int bS=1, iH=4,iW=4, iC=3, kH=2,kW=2, sH=1,sW=1, pH=0,pW=0, dH=1,dW=1; int oH=3,oW=3; int paddingMode = 0; // 1-SAME, 0-VALID; int dataFormat = 0; // 1-NHWC, 0-NCHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, iC, iH, iW}, {0.27620894, 0.21801452, 0.062078513, 7.348895E-4, 0.24149609, 0.4948205, 0.93483436, 0.52035654, 0.30292067, 0.3289706, 0.7977864, 0.03180518, 0.1455722, 0.90352905, 0.9405744, 0.0048329555, 0.44062102, 0.111197524, 0.31742015, 0.1933705, 0.23825112, 0.35076278, 0.7135856, 0.28229436, 0.18310733, 0.9613717, 0.56823575, 0.78289545, 0.62195826, 0.5244586, 0.5040889, 0.025349546, 0.41400263, 0.28420195, 0.8536445, 0.3044107, 0.7997134, 0.45762005, 0.7653578, 0.07198584, 0.5304998, 0.7334402, 0.85019743, 0.031957153, 0.37088063, 0.85722464, 0.06376881, 0.39791203}); auto expOutput = NDArrayFactory::create<TypeParam>('c', {bS, iC, oH, oW}, {0.4948205, 0.93483436, 0.93483436, 0.4948205, 0.93483436, 0.93483436, 0.90352905, 0.9405744, 0.9405744, 0.44062102, 0.7135856, 0.7135856, 0.9613717, 0.9613717, 0.78289545, 0.9613717, 0.9613717, 0.78289545, 0.7997134, 0.8536445, 0.8536445, 0.7997134, 0.85019743, 0.85019743, 0.85722464, 0.85722464, 0.85019743}); nd4j::ops::maxpool2d op; auto results = op.execute({&input}, {}, {kH,kW, sH,sW, pH,pW, dH,dW, paddingMode}); auto* output = results->at(0); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expOutput.isSameShape(output)); ASSERT_TRUE(expOutput.equalsTo(output)); delete results; } TYPED_TEST(TypedConvolutionTests1, conv2D_input_BP_test1) { auto inputShape = NDArrayFactory::create<TypeParam>('c', {4}, {2, 1, 4, 4}); auto weights = NDArrayFactory::create<TypeParam>('c', {2, 1, 3, 3}); auto epsilonNext = NDArrayFactory::create<TypeParam>('c', {2, 2, 4, 4}); auto shapeArr = NDArrayFactory::create<TypeParam>('c', {2, 1, 4, 4}); TypeParam _expEpsB[] = {952.0, 1540.0, 1636.0, 1180.0, 1791.0, 2886.0, 3057.0, 2193.0, 2223.0, 3570.0, 3741.0, 2673.0, 1900.0, 3028.0, 3160.0, 2240.0, 2872.0, 4612.0, 4708.0, 3356.0, 5247.0, 8358.0, 8529.0, 6033.0, 5679.0, 9042.0, 9213.0, 6513.0, 4588.0, 7252.0, 7384.0, 5184.0}; NDArray expEps(_expEpsB, shapeArr.getShapeInfo()); weights.linspace(1); epsilonNext.linspace(1); weights.permutei({2,3,1,0}); nd4j::ops::conv2d_input_bp op; auto results = op.execute({&inputShape, &weights, &epsilonNext}, {}, {3, 3, 1, 1, 0, 0, 1, 1, 1}); ASSERT_TRUE(results->size() == 1); auto epsilon = results->at(0); ASSERT_TRUE(shapeArr.isSameShape(epsilon)); ASSERT_TRUE(expEps.equalsTo(epsilon)); delete results; } ////////////////////////////////////////////////////////////////////// TEST_F(ConvolutionTests1, depthwise_conv2d_test4) { int bS=1, iH=3,iW=3, iC=2,mC=1, kH=2,kW=2, sH=1,sW=1, pH=0,pW=0, dH=1,dW=1; int oC=iC*mC; int oH=3,oW=3; int paddingMode = 1; // 1-SAME, 0-VALID; int dataFormat = 1; // 1-NHWC, 0-NCHW auto input = NDArrayFactory::create<double>('c', {bS, iH, iW, iC}); auto weights = NDArrayFactory::create<double>('c', {kH, kW, iC, mC}); auto expOutput = NDArrayFactory::create<double>('c', {bS, oH, oW, oC}, {20., 24.,28., 32.,16., 18.,44., 48.,52., 56.,28., 30.,28., 30.,32., 34.,17., 18.}); input.linspace(1.); weights = 1.; nd4j::ops::depthwise_conv2d op; auto results = op.execute({&input, &weights}, {}, {kH,kW, sH,sW, pH,pW, dH,dW, paddingMode, dataFormat}); auto output = results->at(0); // output->printIndexedBuffer(); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expOutput.isSameShape(output)); ASSERT_TRUE(expOutput.equalsTo(output)); delete results; } ////////////////////////////////////////////////////////////////////// TEST_F(ConvolutionTests1, depthwise_conv2d_test4_1) { int bS=1, iH=3,iW=3, iC=2,mC=1, kH=2,kW=2, sH=1,sW=1, pH=0,pW=0, dH=1,dW=1; int oC=iC*mC; int oH=3,oW=3; int paddingMode = 1; // 1-SAME, 0-VALID; int dataFormat = 1; // 1-NHWC, 0-NCHW NDArray input('c', {bS, iH, iW, iC}, nd4j::DataType::DOUBLE); NDArray weights('c', {kH, kW, iC, mC}, nd4j::DataType::DOUBLE); NDArray expOutput('c', {bS, oH, oW, oC}, {20., 24.,28., 32.,16., 18.,44., 48.,52., 56.,28., 30.,28., 30.,32., 34.,17., 18.}); input.linspace(1.); weights = 1.; nd4j::ops::depthwise_conv2d op; ResultSet* results = op.execute({&input, &weights}, {}, {kH,kW, sH,sW, pH,pW, dH,dW, paddingMode, dataFormat}); NDArray* output = results->at(0); // output.printIndexedBuffer(); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(expOutput.isSameShape(output)); ASSERT_TRUE(expOutput.equalsTo(output)); delete results; } ////////////////////////////////////////////////////////////////////// TEST_F(ConvolutionTests1, deconv2d_test1) { int bS=2, iH=4,iW=4, iC=5,oC=10, kH=2,kW=2, sH=1,sW=1, pH=0,pW=0, dH=1,dW=1; int oH=3,oW=3; int paddingMode = 0; // 1-SAME, 0-VALID; int dataFormat = 1; // 1-NHWC, 0-NCHW auto input = NDArrayFactory::create<double>('c', {bS, oH, oW, oC}); auto weights = NDArrayFactory::create<double>('c', {kH, kW, iC, oC}); auto exp = NDArrayFactory::create<double>('c', {bS, iH, iW, iC}, { 2.75, 7.75, 12.75, 17.75, 22.75, 30.5 , 40.5 , 50.5 , 60.5 , 70.5 , 30.5 , 40.5 , 50.5 , 60.5 , 70.5 , 27.75, 32.75, 37.75, 42.75, 47.75, 55.5 , 65.5 , 75.5 , 85.5 , 95.5 ,161. , 181. , 201. , 221. , 241. ,161. , 181. , 201. , 221. , 241. ,105.5 , 115.5 , 125.5 , 135.5 , 145.5 , 55.5 , 65.5 , 75.5 , 85.5 , 95.5 ,161. , 181. , 201. , 221. , 241. ,161. , 181. , 201. , 221. , 241. ,105.5 , 115.5 , 125.5 , 135.5 , 145.5 , 52.75, 57.75, 62.75, 67.75, 72.75,130.5 , 140.5 , 150.5 , 160.5 , 170.5 ,130.5 , 140.5 , 150.5 , 160.5 , 170.5 , 77.75, 82.75, 87.75, 92.75, 97.75, 2.75, 7.75, 12.75, 17.75, 22.75, 30.5 , 40.5 , 50.5 , 60.5 , 70.5 , 30.5 , 40.5 , 50.5 , 60.5 , 70.5 , 27.75, 32.75, 37.75, 42.75, 47.75, 55.5 , 65.5 , 75.5 , 85.5 , 95.5 ,161. , 181. , 201. , 221. , 241. ,161. , 181. , 201. , 221. , 241. ,105.5 , 115.5 , 125.5 , 135.5 , 145.5 , 55.5 , 65.5 , 75.5 , 85.5 , 95.5 ,161. , 181. , 201. , 221. , 241. ,161. , 181. , 201. , 221. , 241. ,105.5 , 115.5 , 125.5 , 135.5 , 145.5 , 52.75, 57.75, 62.75, 67.75, 72.75,130.5 , 140.5 , 150.5 , 160.5 , 170.5 ,130.5 , 140.5 , 150.5 , 160.5 , 170.5 , 77.75, 82.75, 87.75, 92.75, 97.75}); input = 0.5; weights.linspace(0.1, 0.1); nd4j::ops::deconv2d op; auto results = op.execute({&input, &weights}, {}, {kH,kW, sH,sW, pH,pW, dH,dW, paddingMode, dataFormat}); ASSERT_EQ(Status::OK(), results->status()); auto output = results->at(0); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete results; } ////////////////////////////////////////////////////////////////////// TEST_F(ConvolutionTests1, deconv2d_test2) { int bS=2, iH=4,iW=4, iC=5,oC=10, kH=2,kW=2, sH=1,sW=1, pH=0,pW=0, dH=1,dW=1; int oH=4,oW=4; int paddingMode = 1; // 1-SAME, 0-VALID; int dataFormat = 1; // 1-NHWC, 0-NCHW auto input = NDArrayFactory::create<double>('c', {bS, oH, oW, oC}); auto weights = NDArrayFactory::create<double>('c', {kH, kW, iC, oC}); auto exp = NDArrayFactory::create<double>('c', {bS, iH, iW, iC}, {2.75, 7.75, 12.75, 17.75, 22.75, 30.5 , 40.5 , 50.5 , 60.5 , 70.5 , 30.5 , 40.5 , 50.5 , 60.5 , 70.5 , 30.5 , 40.5 , 50.5 , 60.5 , 70.5 , 55.5 , 65.5 , 75.5 , 85.5 , 95.5 ,161. , 181. , 201. , 221. , 241. ,161. , 181. , 201. , 221. , 241. ,161. , 181. , 201. , 221. , 241. , 55.5 , 65.5 , 75.5 , 85.5 , 95.5 ,161. , 181. , 201. , 221. , 241. ,161. , 181. , 201. , 221. , 241. ,161. , 181. , 201. , 221. , 241. , 55.5 , 65.5 , 75.5 , 85.5 , 95.5 ,161. , 181. , 201. , 221. , 241. ,161. , 181. , 201. , 221. , 241. ,161. , 181. , 201. , 221. , 241. , 2.75, 7.75, 12.75, 17.75, 22.75, 30.5 , 40.5 , 50.5 , 60.5 , 70.5 , 30.5 , 40.5 , 50.5 , 60.5 , 70.5 , 30.5 , 40.5 , 50.5 , 60.5 , 70.5 , 55.5 , 65.5 , 75.5 , 85.5 , 95.5 ,161. , 181. , 201. , 221. , 241. ,161. , 181. , 201. , 221. , 241. ,161. , 181. , 201. , 221. , 241. , 55.5 , 65.5 , 75.5 , 85.5 , 95.5 ,161. , 181. , 201. , 221. , 241. ,161. , 181. , 201. , 221. , 241. ,161. , 181. , 201. , 221. , 241. , 55.5 , 65.5 , 75.5 , 85.5 , 95.5 ,161. , 181. , 201. , 221. , 241. ,161. , 181. , 201. , 221. , 241. ,161. , 181. , 201. , 221. , 241. }); input = 0.5; weights.linspace(0.1, 0.1); nd4j::ops::deconv2d op; auto results = op.execute({&input, &weights}, {}, {kH,kW, sH,sW, pH,pW, dH,dW, paddingMode, dataFormat}); auto output = results->at(0); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete results; } ////////////////////////////////////////////////////////////////////// TYPED_TEST(TypedConvolutionTests1, deconv2d_tf_test1) { int bS=2, iH=4,iW=4, iC=5,oC=10, kH=2,kW=2, sH=1,sW=1, pH=0,pW=0, dH=1,dW=1; int oH=3,oW=3; int paddingMode = 0; // 1-SAME, 0-VALID; int dataFormat = 1; // 1-NHWC, 0-NCHW auto input = NDArrayFactory::create<TypeParam>('c', {bS, oH, oW, oC}); auto weights = NDArrayFactory::create<TypeParam>('c', {kH, kW, iC, oC}); auto outShape = NDArrayFactory::create<TypeParam>('c', {4}, {static_cast<TypeParam>(bS), static_cast<TypeParam>(iH), static_cast<TypeParam>(iW), static_cast<TypeParam>(iC)}); auto exp = NDArrayFactory::create<TypeParam>('c', {bS, iH, iW, iC}, { 2.75, 7.75, 12.75, 17.75, 22.75, 30.5 , 40.5 , 50.5 , 60.5 , 70.5 , 30.5 , 40.5 , 50.5 , 60.5 , 70.5 , 27.75, 32.75, 37.75, 42.75, 47.75, 55.5 , 65.5 , 75.5 , 85.5 , 95.5 ,161. , 181. , 201. , 221. , 241. ,161. , 181. , 201. , 221. , 241. ,105.5 , 115.5 , 125.5 , 135.5 , 145.5 , 55.5 , 65.5 , 75.5 , 85.5 , 95.5 ,161. , 181. , 201. , 221. , 241. ,161. , 181. , 201. , 221. , 241. ,105.5 , 115.5 , 125.5 , 135.5 , 145.5 , 52.75, 57.75, 62.75, 67.75, 72.75,130.5 , 140.5 , 150.5 , 160.5 , 170.5 ,130.5 , 140.5 , 150.5 , 160.5 , 170.5 , 77.75, 82.75, 87.75, 92.75, 97.75, 2.75, 7.75, 12.75, 17.75, 22.75, 30.5 , 40.5 , 50.5 , 60.5 , 70.5 , 30.5 , 40.5 , 50.5 , 60.5 , 70.5 , 27.75, 32.75, 37.75, 42.75, 47.75, 55.5 , 65.5 , 75.5 , 85.5 , 95.5 ,161. , 181. , 201. , 221. , 241. ,161. , 181. , 201. , 221. , 241. ,105.5 , 115.5 , 125.5 , 135.5 , 145.5 , 55.5 , 65.5 , 75.5 , 85.5 , 95.5 ,161. , 181. , 201. , 221. , 241. ,161. , 181. , 201. , 221. , 241. ,105.5 , 115.5 , 125.5 , 135.5 , 145.5 , 52.75, 57.75, 62.75, 67.75, 72.75,130.5 , 140.5 , 150.5 , 160.5 , 170.5 ,130.5 , 140.5 , 150.5 , 160.5 , 170.5 , 77.75, 82.75, 87.75, 92.75, 97.75}); input = 0.5; weights.linspace(0.1, 0.1); nd4j::ops::deconv2d_tf op; auto results = op.execute({&outShape, &weights, &input}, {}, {kH,kW, sH,sW, pH,pW, dH,dW, paddingMode, dataFormat}); auto output = results->at(0); ASSERT_EQ(Status::OK(), results->status()); ASSERT_TRUE(exp.isSameShape(output)); ASSERT_TRUE(exp.equalsTo(output)); delete results; } #endif //LIBND4J_CONVOLUTIONTESTS1_H
#include <iostream> #include <cstdio> using namespace std; int main() { char a; int b[27]={0}; while(a!='.') { cin>>a; if(a>='a'&&a<='z') { b[a-'a'+1]++; } } for(int i=1;i<=26;i++) { if(b[i]>0) cout<<char(i+'a'-1)<<':'<<b[i]<<endl; } return 0; }
#ifndef EXAMPLE_TYPE_HPP #define EXAMPLE_TYPE_HPP // A hand-coded serializable #include <Fw/Types/BasicTypes.hpp> #include <Fw/Types/Serializable.hpp> #include <Autocoders/Python/test/interface1/SomeStruct.hpp> #if FW_SERIALIZABLE_TO_STRING #include <Fw/Types/StringType.hpp> #endif namespace ANameSpace { class UserSerializer : public Fw::Serializable { public: enum { SERIALIZED_SIZE = sizeof(SomeUserStruct) + sizeof(I32) }; UserSerializer(void); // Default constructor UserSerializer(const SomeUserStruct* src); // copy constructor UserSerializer(const SomeUserStruct& src); // copy constructor UserSerializer(SomeUserStruct arg); // constructor with arguments const SomeUserStruct& operator=(const SomeUserStruct& src); // Equal operator void setVal(const SomeUserStruct& arg); // set values void getVal(SomeUserStruct& arg); Fw::SerializeStatus serialize(Fw::SerializeBufferBase& buffer) const; Fw::SerializeStatus deserialize(Fw::SerializeBufferBase& buffer); #if FW_SERIALIZABLE_TO_STRING void toString(Fw::StringBase& text) const; //!< generate text from serializable #endif protected: private: SomeUserStruct m_struct; // stored value }; } #endif
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/display/manager/update_display_configuration_task.h" #include "ui/display/manager/configure_displays_task.h" #include "ui/display/manager/display_layout_manager.h" #include "ui/display/manager/display_util.h" #include "ui/display/types/display_snapshot.h" #include "ui/display/types/native_display_delegate.h" namespace display { UpdateDisplayConfigurationTask::UpdateDisplayConfigurationTask( NativeDisplayDelegate* delegate, DisplayLayoutManager* layout_manager, MultipleDisplayState new_display_state, chromeos::DisplayPowerState new_power_state, int power_flags, bool force_configure, const ResponseCallback& callback) : delegate_(delegate), layout_manager_(layout_manager), new_display_state_(new_display_state), new_power_state_(new_power_state), power_flags_(power_flags), force_configure_(force_configure), callback_(callback), requesting_displays_(false), weak_ptr_factory_(this) { delegate_->AddObserver(this); } UpdateDisplayConfigurationTask::~UpdateDisplayConfigurationTask() { delegate_->RemoveObserver(this); } void UpdateDisplayConfigurationTask::Run() { requesting_displays_ = true; delegate_->GetDisplays( base::Bind(&UpdateDisplayConfigurationTask::OnDisplaysUpdated, weak_ptr_factory_.GetWeakPtr())); } void UpdateDisplayConfigurationTask::OnConfigurationChanged() {} void UpdateDisplayConfigurationTask::OnDisplaySnapshotsInvalidated() { cached_displays_.clear(); if (!requesting_displays_ && weak_ptr_factory_.HasWeakPtrs()) { // This task has already been run and getting the displays request is not in // flight. We need to re-run it to get updated displays snapshots. weak_ptr_factory_.InvalidateWeakPtrs(); Run(); } } void UpdateDisplayConfigurationTask::OnDisplaysUpdated( const std::vector<DisplaySnapshot*>& displays) { cached_displays_ = displays; requesting_displays_ = false; // If the user hasn't requested a display state, update it using the requested // power state. if (new_display_state_ == MULTIPLE_DISPLAY_STATE_INVALID) new_display_state_ = ChooseDisplayState(); VLOG(1) << "OnDisplaysUpdated: new_display_state=" << MultipleDisplayStateToString(new_display_state_) << " new_power_state=" << DisplayPowerStateToString(new_power_state_) << " flags=" << power_flags_ << " force_configure=" << force_configure_ << " display_count=" << cached_displays_.size(); if (ShouldConfigure()) { EnterState(base::Bind(&UpdateDisplayConfigurationTask::OnStateEntered, weak_ptr_factory_.GetWeakPtr())); } else { // If we don't have to configure then we're sticking with the old // configuration. Update it such that it reflects in the reported value. new_power_state_ = layout_manager_->GetPowerState(); FinishConfiguration(true); } } void UpdateDisplayConfigurationTask::EnterState( const ConfigureDisplaysTask::ResponseCallback& callback) { VLOG(2) << "EnterState"; std::vector<DisplayConfigureRequest> requests; if (!layout_manager_->GetDisplayLayout(cached_displays_, new_display_state_, new_power_state_, &requests)) { callback.Run(ConfigureDisplaysTask::ERROR); return; } if (!requests.empty()) { configure_task_.reset( new ConfigureDisplaysTask(delegate_, requests, callback)); configure_task_->Run(); } else { VLOG(2) << "No displays"; callback.Run(ConfigureDisplaysTask::SUCCESS); } } void UpdateDisplayConfigurationTask::OnStateEntered( ConfigureDisplaysTask::Status status) { bool success = status != ConfigureDisplaysTask::ERROR; if (new_display_state_ == MULTIPLE_DISPLAY_STATE_DUAL_MIRROR && status == ConfigureDisplaysTask::PARTIAL_SUCCESS) success = false; if (layout_manager_->GetSoftwareMirroringController()) { bool enable_software_mirroring = false; if (!success && new_display_state_ == MULTIPLE_DISPLAY_STATE_DUAL_MIRROR) { if (layout_manager_->GetDisplayState() != MULTIPLE_DISPLAY_STATE_MULTI_EXTENDED || layout_manager_->GetPowerState() != new_power_state_ || force_configure_) { new_display_state_ = MULTIPLE_DISPLAY_STATE_MULTI_EXTENDED; EnterState(base::Bind( &UpdateDisplayConfigurationTask::OnEnableSoftwareMirroring, weak_ptr_factory_.GetWeakPtr())); return; } success = layout_manager_->GetDisplayState() == MULTIPLE_DISPLAY_STATE_MULTI_EXTENDED; enable_software_mirroring = success; if (success) new_display_state_ = MULTIPLE_DISPLAY_STATE_MULTI_EXTENDED; } layout_manager_->GetSoftwareMirroringController()->SetSoftwareMirroring( enable_software_mirroring); } FinishConfiguration(success); } void UpdateDisplayConfigurationTask::OnEnableSoftwareMirroring( ConfigureDisplaysTask::Status status) { bool success = status != ConfigureDisplaysTask::ERROR; layout_manager_->GetSoftwareMirroringController()->SetSoftwareMirroring( success); FinishConfiguration(success); } void UpdateDisplayConfigurationTask::FinishConfiguration(bool success) { callback_.Run(success, cached_displays_, new_display_state_, new_power_state_); } bool UpdateDisplayConfigurationTask::ShouldForceDpms() const { return new_power_state_ != chromeos::DISPLAY_POWER_ALL_OFF && (layout_manager_->GetPowerState() != new_power_state_ || (power_flags_ & DisplayConfigurator::kSetDisplayPowerForceProbe)); } bool UpdateDisplayConfigurationTask::ShouldConfigure() const { if (force_configure_) return true; if (cached_displays_.size() == 1 && cached_displays_[0]->type() == DISPLAY_CONNECTION_TYPE_INTERNAL) return true; if (!(power_flags_ & DisplayConfigurator::kSetDisplayPowerOnlyIfSingleInternalDisplay)) return true; if (new_display_state_ != layout_manager_->GetDisplayState()) return true; return false; } MultipleDisplayState UpdateDisplayConfigurationTask::ChooseDisplayState() const { int num_displays = cached_displays_.size(); int num_on_displays = GetDisplayPower(cached_displays_, new_power_state_, nullptr); if (num_displays == 0) return MULTIPLE_DISPLAY_STATE_HEADLESS; if (num_displays == 1 || num_on_displays == 1) { // If only one display is currently turned on, return the "single" state // so that its native mode will be used. return MULTIPLE_DISPLAY_STATE_SINGLE; } // Try to use the saved configuration; otherwise, default to extended. DisplayConfigurator::StateController* state_controller = layout_manager_->GetStateController(); if (!state_controller) return MULTIPLE_DISPLAY_STATE_MULTI_EXTENDED; return state_controller->GetStateForDisplayIds(cached_displays_); } } // namespace display
INTERNAL void SetupAssetPath () { gAssetPath = "assets/"; }
// // Copyright (c) 2015-2020 Microsoft Corporation and Contributors. // SPDX-License-Identifier: Apache-2.0 // #include "mat/config.h" #pragma once #include "api/IRuntimeConfig.hpp" namespace MAT_NS_BEGIN { static ILogConfiguration defaultRuntimeConfig{ {CFG_INT_TRACE_LEVEL_MIN, ACTTraceLevel::ACTTraceLevel_Error}, {CFG_INT_SDK_MODE, SdkModeTypes::SdkModeTypes_CS}, {CFG_BOOL_ENABLE_ANALYTICS, false}, {CFG_INT_CACHE_FILE_SIZE, 3145728}, {CFG_INT_RAM_QUEUE_SIZE, 524288}, {CFG_BOOL_ENABLE_MULTITENANT, true}, {CFG_BOOL_ENABLE_DB_DROP_IF_FULL, false}, {CFG_INT_MAX_TEARDOWN_TIME, 1}, {CFG_INT_MAX_PENDING_REQ, 4}, {CFG_INT_RAM_QUEUE_BUFFERS, 3}, {CFG_INT_TRACE_LEVEL_MASK, 0}, {CFG_BOOL_ENABLE_TRACE, true}, {CFG_STR_COLLECTOR_URL, COLLECTOR_URL_PROD}, {CFG_INT_STORAGE_FULL_PCT, 75}, {CFG_INT_STORAGE_FULL_CHECK_TIME, 5000}, {CFG_INT_RAMCACHE_FULL_PCT, 75}, {CFG_BOOL_ENABLE_NET_DETECT, true}, {CFG_BOOL_SESSION_RESET_ENABLED, false}, {CFG_MAP_METASTATS_CONFIG, {/* Parameter that allows to split stats events by tenant */ {"split", false}, {"interval", 1800}, {"tokenProd", STATS_TOKEN_PROD}, {"tokenInt", STATS_TOKEN_INT}}}, {"utc", { #ifdef HAVE_MAT_UTC {"providerGroupId", "780dddc8-18a1-5781-895a-a690464fa89c"}, {CFG_BOOL_UTC_ENABLED, true}, {CFG_BOOL_UTC_ACTIVE, false}, {CFG_BOOL_UTC_LARGE_PAYLOADS, false} #else {CFG_BOOL_UTC_ENABLED, false} #endif }}, {CFG_MAP_HTTP, { #ifdef HAVE_MAT_ZLIB {CFG_BOOL_HTTP_COMPRESSION, true} #else {CFG_BOOL_HTTP_COMPRESSION, false} #endif , {"contentEncoding", "deflate"}, /* Optional parameter to require Microsoft Root CA */ {CFG_BOOL_HTTP_MS_ROOT_CHECK, false}}}, {CFG_MAP_TPM, { {CFG_INT_TPM_MAX_BLOB_BYTES, 2097152}, {CFG_INT_TPM_MAX_RETRY, 5}, {CFG_BOOL_TPM_CLOCK_SKEW_ENABLED, true}, {CFG_STR_TPM_BACKOFF, "E,3000,300000,2,1"}, }}, {CFG_MAP_COMPAT, { {CFG_BOOL_COMPAT_DOTS, true} // false: v1 backwards-compat: event.SetType("My.Custom.Type") => custom.my_custom_type }}, {"sample", {{"rate", 0}}}}; /// <summary> /// This class overlays a custom configuration provided by the customer /// on top of default configuration above (defaultRuntimeConfig) /// </summary> /// <seealso cref="IRuntimeConfig" /> class RuntimeConfig_Default : public IRuntimeConfig { protected: ILogConfiguration& config; public: RuntimeConfig_Default(ILogConfiguration& customConfig) : config(customConfig) { Variant::merge_map(*customConfig, *defaultRuntimeConfig); }; virtual ~RuntimeConfig_Default() { } virtual std::string GetCollectorUrl() override { const char* url = config[CFG_STR_COLLECTOR_URL]; return std::string(url); } virtual void DecorateEvent(std::map<std::string, std::string>& extension, std::string const& experimentationProject, std::string const& eventName) override { UNREFERENCED_PARAMETER(extension); UNREFERENCED_PARAMETER(experimentationProject); UNREFERENCED_PARAMETER(eventName); }; virtual EventLatency GetEventLatency(std::string const& tenantId = std::string(), std::string const& eventName = std::string()) override { UNREFERENCED_PARAMETER(tenantId); UNREFERENCED_PARAMETER(eventName); return EventLatency_Normal; }; virtual std::string GetMetaStatsTenantToken() override { const char* token = config[CFG_MAP_METASTATS_CONFIG]["tokenProd"]; return std::string(token); }; virtual unsigned GetMetaStatsSendIntervalSec() override { return config[CFG_MAP_METASTATS_CONFIG]["interval"]; } virtual unsigned GetOfflineStorageMaximumSizeBytes() override { return config[CFG_INT_CACHE_FILE_SIZE]; }; virtual unsigned GetOfflineStorageResizeThresholdPct() override { return 99; } virtual unsigned GetMaximumRetryCount() override { return config[CFG_MAP_TPM][CFG_INT_TPM_MAX_RETRY]; } virtual std::string GetUploadRetryBackoffConfig() override { return config[CFG_MAP_TPM][CFG_STR_TPM_BACKOFF]; } virtual bool IsHttpRequestCompressionEnabled() override { return config[CFG_MAP_HTTP][CFG_BOOL_HTTP_COMPRESSION]; } virtual const std::string& GetHttpRequestContentEncoding() const override { return config[CFG_MAP_HTTP]["contentEncoding"]; } virtual unsigned GetMinimumUploadBandwidthBps() override { return 0; } virtual unsigned GetMaximumUploadSizeBytes() override { return config[CFG_MAP_TPM][CFG_INT_TPM_MAX_BLOB_BYTES]; } virtual void SetEventLatency(std::string const& tenantId, std::string const& eventName, EventLatency latency) override { UNREFERENCED_PARAMETER(tenantId); UNREFERENCED_PARAMETER(eventName); UNREFERENCED_PARAMETER(latency); } virtual bool IsClockSkewEnabled() override { return config[CFG_MAP_TPM][CFG_BOOL_TPM_CLOCK_SKEW_ENABLED]; } uint32_t GetTeardownTime() override { return config[CFG_INT_MAX_TEARDOWN_TIME]; } virtual const char* GetProviderGroupId() override { return config[CFG_STR_UTC][CFG_STR_PROVIDER_GROUP_ID]; } virtual Variant& operator[](const char* key) override { return config[key]; } virtual bool HasConfig(const char* key) override { return config.HasConfig(key); } }; } MAT_NS_END
///////////////////////////////////////////////////////////////////////////// // // (C) Copyright Ion Gaztanaga 2007-2014 // // 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 http://www.boost.org/libs/intrusive for documentation. // ///////////////////////////////////////////////////////////////////////////// #ifndef BOOST_INTRUSIVE_SPLAY_SET_HPP #define BOOST_INTRUSIVE_SPLAY_SET_HPP #include <boost/intrusive/detail/config_begin.hpp> #include <boost/intrusive/intrusive_fwd.hpp> #include <boost/intrusive/splaytree.hpp> #include <boost/intrusive/detail/mpl.hpp> #include <boost/move/utility_core.hpp> #include <boost/static_assert.hpp> #if defined(BOOST_HAS_PRAGMA_ONCE) # pragma once #endif #if !defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) template<class ValueTraits, class VoidOrKeyOfValue, class Compare, class SizeType, bool ConstantTimeSize, typename HeaderHolder> class splay_multiset_impl; #endif namespace boost { namespace intrusive { //! The class template splay_set is an intrusive container, that mimics most of //! the interface of std::set as described in the C++ standard. //! //! The template parameter \c T is the type to be managed by the container. //! The user can specify additional options and if no options are provided //! default options are used. //! //! The container supports the following options: //! \c base_hook<>/member_hook<>/value_traits<>, //! \c constant_time_size<>, \c size_type<> and //! \c compare<>. #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) template<class T, class ...Options> #else template<class ValueTraits, class VoidOrKeyOfValue, class Compare, class SizeType, bool ConstantTimeSize, typename HeaderHolder> #endif class splay_set_impl #ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED : public splaytree_impl<ValueTraits, VoidOrKeyOfValue, Compare, SizeType, ConstantTimeSize, HeaderHolder> #endif { /// @cond typedef splaytree_impl<ValueTraits, VoidOrKeyOfValue, Compare, SizeType, ConstantTimeSize, HeaderHolder> tree_type; BOOST_MOVABLE_BUT_NOT_COPYABLE(splay_set_impl) typedef tree_type implementation_defined; /// @endcond public: typedef typename implementation_defined::value_type value_type; typedef typename implementation_defined::key_type key_type; typedef typename implementation_defined::key_of_value key_of_value; typedef typename implementation_defined::value_traits value_traits; typedef typename implementation_defined::pointer pointer; typedef typename implementation_defined::const_pointer const_pointer; typedef typename implementation_defined::reference reference; typedef typename implementation_defined::const_reference const_reference; typedef typename implementation_defined::difference_type difference_type; typedef typename implementation_defined::size_type size_type; typedef typename implementation_defined::value_compare value_compare; typedef typename implementation_defined::key_compare key_compare; typedef typename implementation_defined::iterator iterator; typedef typename implementation_defined::const_iterator const_iterator; typedef typename implementation_defined::reverse_iterator reverse_iterator; typedef typename implementation_defined::const_reverse_iterator const_reverse_iterator; typedef typename implementation_defined::insert_commit_data insert_commit_data; typedef typename implementation_defined::node_traits node_traits; typedef typename implementation_defined::node node; typedef typename implementation_defined::node_ptr node_ptr; typedef typename implementation_defined::const_node_ptr const_node_ptr; typedef typename implementation_defined::node_algorithms node_algorithms; static const bool constant_time_size = tree_type::constant_time_size; public: //! @copydoc ::boost::intrusive::splaytree::splaytree() splay_set_impl() : tree_type() {} //! @copydoc ::boost::intrusive::splaytree::splaytree(const key_compare &,const value_traits &) explicit splay_set_impl( const key_compare &cmp, const value_traits &v_traits = value_traits()) : tree_type(cmp, v_traits) {} //! @copydoc ::boost::intrusive::splaytree::splaytree(bool,Iterator,Iterator,const key_compare &,const value_traits &) template<class Iterator> splay_set_impl( Iterator b, Iterator e , const key_compare &cmp = key_compare() , const value_traits &v_traits = value_traits()) : tree_type(true, b, e, cmp, v_traits) {} //! @copydoc ::boost::intrusive::splaytree::splaytree(splaytree &&) splay_set_impl(BOOST_RV_REF(splay_set_impl) x) : tree_type(BOOST_MOVE_BASE(tree_type, x)) {} //! @copydoc ::boost::intrusive::splaytree::operator=(splaytree &&) splay_set_impl& operator=(BOOST_RV_REF(splay_set_impl) x) { return static_cast<splay_set_impl&>(tree_type::operator=(BOOST_MOVE_BASE(tree_type, x))); } #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED //! @copydoc ::boost::intrusive::splaytree::~splaytree() ~splay_set_impl(); //! @copydoc ::boost::intrusive::splaytree::begin() iterator begin() BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::begin()const const_iterator begin() const BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::cbegin()const const_iterator cbegin() const BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::end() iterator end() BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::end()const const_iterator end() const BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::cend()const const_iterator cend() const BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::rbegin() reverse_iterator rbegin() BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::rbegin()const const_reverse_iterator rbegin() const BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::crbegin()const const_reverse_iterator crbegin() const BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::rend() reverse_iterator rend() BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::rend()const const_reverse_iterator rend() const BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::crend()const const_reverse_iterator crend() const BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::root() iterator root() BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::root()const const_iterator root() const BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::croot()const const_iterator croot() const BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::container_from_end_iterator(iterator) static splay_set_impl &container_from_end_iterator(iterator end_iterator) BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::container_from_end_iterator(const_iterator) static const splay_set_impl &container_from_end_iterator(const_iterator end_iterator) BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::container_from_iterator(iterator) static splay_set_impl &container_from_iterator(iterator it) BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::container_from_iterator(const_iterator) static const splay_set_impl &container_from_iterator(const_iterator it) BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::key_comp()const key_compare key_comp() const; //! @copydoc ::boost::intrusive::splaytree::value_comp()const value_compare value_comp() const; //! @copydoc ::boost::intrusive::splaytree::empty()const bool empty() const BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::size()const size_type size() const BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::swap void swap(splay_set_impl& other); //! @copydoc ::boost::intrusive::splaytree::clone_from(const splaytree&,Cloner,Disposer) template <class Cloner, class Disposer> void clone_from(const splay_set_impl &src, Cloner cloner, Disposer disposer); #else using tree_type::clone_from; #endif //#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED //! @copydoc ::boost::intrusive::splaytree::clone_from(splaytree&&,Cloner,Disposer) template <class Cloner, class Disposer> void clone_from(BOOST_RV_REF(splay_set_impl) src, Cloner cloner, Disposer disposer) { tree_type::clone_from(BOOST_MOVE_BASE(tree_type, src), cloner, disposer); } //! @copydoc ::boost::intrusive::splaytree::insert_unique(reference) std::pair<iterator, bool> insert(reference value) { return tree_type::insert_unique(value); } //! @copydoc ::boost::intrusive::splaytree::insert_unique(const_iterator,reference) iterator insert(const_iterator hint, reference value) { return tree_type::insert_unique(hint, value); } //! @copydoc ::boost::intrusive::rbtree::insert_unique_check(const key_type&,insert_commit_data&) std::pair<iterator, bool> insert_check (const key_type &key, insert_commit_data &commit_data) { return tree_type::insert_unique_check(key, commit_data); } //! @copydoc ::boost::intrusive::rbtree::insert_unique_check(const_iterator,const key_type&,insert_commit_data&) std::pair<iterator, bool> insert_check (const_iterator hint, const key_type &key ,insert_commit_data &commit_data) { return tree_type::insert_unique_check(hint, key, commit_data); } //! @copydoc ::boost::intrusive::splaytree::insert_unique_check(const KeyType&,KeyTypeKeyCompare,insert_commit_data&) template<class KeyType, class KeyTypeKeyCompare> std::pair<iterator, bool> insert_check (const KeyType &key, KeyTypeKeyCompare comp, insert_commit_data &commit_data) { return tree_type::insert_unique_check(key, comp, commit_data); } //! @copydoc ::boost::intrusive::splaytree::insert_unique_check(const_iterator,const KeyType&,KeyTypeKeyCompare,insert_commit_data&) template<class KeyType, class KeyTypeKeyCompare> std::pair<iterator, bool> insert_check (const_iterator hint, const KeyType &key ,KeyTypeKeyCompare comp, insert_commit_data &commit_data) { return tree_type::insert_unique_check(hint, key, comp, commit_data); } //! @copydoc ::boost::intrusive::splaytree::insert_unique(Iterator,Iterator) template<class Iterator> void insert(Iterator b, Iterator e) { tree_type::insert_unique(b, e); } //! @copydoc ::boost::intrusive::splaytree::insert_unique_commit iterator insert_commit(reference value, const insert_commit_data &commit_data) BOOST_NOEXCEPT { return tree_type::insert_unique_commit(value, commit_data); } #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED //! @copydoc ::boost::intrusive::splaytree::insert_before iterator insert_before(const_iterator pos, reference value) BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::push_back void push_back(reference value) BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::push_front void push_front(reference value) BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::erase(const_iterator) iterator erase(const_iterator i) BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::erase(const_iterator,const_iterator) iterator erase(const_iterator b, const_iterator e) BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::erase(const key_type &) size_type erase(const key_type &key); //! @copydoc ::boost::intrusive::splaytree::erase(const KeyType&,KeyTypeKeyCompare) template<class KeyType, class KeyTypeKeyCompare> size_type erase(const KeyType& key, KeyTypeKeyCompare comp); //! @copydoc ::boost::intrusive::splaytree::erase_and_dispose(const_iterator,Disposer) template<class Disposer> iterator erase_and_dispose(const_iterator i, Disposer disposer) BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::erase_and_dispose(const_iterator,const_iterator,Disposer) template<class Disposer> iterator erase_and_dispose(const_iterator b, const_iterator e, Disposer disposer) BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::erase_and_dispose(const key_type &, Disposer) template<class Disposer> size_type erase_and_dispose(const key_type &key, Disposer disposer); //! @copydoc ::boost::intrusive::splaytree::erase_and_dispose(const KeyType&,KeyTypeKeyCompare,Disposer) template<class KeyType, class KeyTypeKeyCompare, class Disposer> size_type erase_and_dispose(const KeyType& key, KeyTypeKeyCompare comp, Disposer disposer); //! @copydoc ::boost::intrusive::splaytree::clear void clear() BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::clear_and_dispose template<class Disposer> void clear_and_dispose(Disposer disposer) BOOST_NOEXCEPT; #endif // #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED //! @copydoc ::boost::intrusive::splaytree::count(const key_type &)const size_type count(const key_type &key) const { return static_cast<size_type>(this->tree_type::find(key) != this->tree_type::cend()); } //! @copydoc ::boost::intrusive::splaytree::count(const KeyType&,KeyTypeKeyCompare)const template<class KeyType, class KeyTypeKeyCompare> size_type count(const KeyType& key, KeyTypeKeyCompare comp) const { return static_cast<size_type>(this->tree_type::find(key, comp) != this->tree_type::cend()); } #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED //! @copydoc ::boost::intrusive::splaytree::count(const key_type &)const size_type count(const key_type &key) const; //! @copydoc ::boost::intrusive::splaytree::count(const KeyType&,KeyTypeKeyCompare)const template<class KeyType, class KeyTypeKeyCompare> size_type count(const KeyType& key, KeyTypeKeyCompare comp) const; //! @copydoc ::boost::intrusive::splaytree::lower_bound(const key_type &) iterator lower_bound(const key_type &key); //! @copydoc ::boost::intrusive::splaytree::lower_bound(const KeyType&,KeyTypeKeyCompare) template<class KeyType, class KeyTypeKeyCompare> iterator lower_bound(const KeyType& key, KeyTypeKeyCompare comp); //! @copydoc ::boost::intrusive::splaytree::lower_bound(const key_type &)const const_iterator lower_bound(const key_type &key) const; //! @copydoc ::boost::intrusive::splaytree::lower_bound(const KeyType&,KeyTypeKeyCompare)const template<class KeyType, class KeyTypeKeyCompare> const_iterator lower_bound(const KeyType& key, KeyTypeKeyCompare comp) const; //! @copydoc ::boost::intrusive::splaytree::upper_bound(const key_type &) iterator upper_bound(const key_type &key); //! @copydoc ::boost::intrusive::splaytree::upper_bound(const KeyType&,KeyTypeKeyCompare) template<class KeyType, class KeyTypeKeyCompare> iterator upper_bound(const KeyType& key, KeyTypeKeyCompare comp); //! @copydoc ::boost::intrusive::splaytree::upper_bound(const key_type &)const const_iterator upper_bound(const key_type &key) const; //! @copydoc ::boost::intrusive::splaytree::upper_bound(const KeyType&,KeyTypeKeyCompare)const template<class KeyType, class KeyTypeKeyCompare> const_iterator upper_bound(const KeyType& key, KeyTypeKeyCompare comp) const; //! @copydoc ::boost::intrusive::splaytree::find(const key_type &) iterator find(const key_type &key); //! @copydoc ::boost::intrusive::splaytree::find(const KeyType&,KeyTypeKeyCompare) template<class KeyType, class KeyTypeKeyCompare> iterator find(const KeyType& key, KeyTypeKeyCompare comp); //! @copydoc ::boost::intrusive::splaytree::find(const key_type &)const const_iterator find(const key_type &key) const; //! @copydoc ::boost::intrusive::splaytree::find(const KeyType&,KeyTypeKeyCompare)const template<class KeyType, class KeyTypeKeyCompare> const_iterator find(const KeyType& key, KeyTypeKeyCompare comp) const; #endif // #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED //! @copydoc ::boost::intrusive::rbtree::equal_range(const key_type &) std::pair<iterator,iterator> equal_range(const key_type &key) { return this->tree_type::lower_bound_range(key); } //! @copydoc ::boost::intrusive::rbtree::equal_range(const KeyType&,KeyTypeKeyCompare) template<class KeyType, class KeyTypeKeyCompare> std::pair<iterator,iterator> equal_range(const KeyType& key, KeyTypeKeyCompare comp) { return this->tree_type::equal_range(key, comp); } //! @copydoc ::boost::intrusive::rbtree::equal_range(const key_type &)const std::pair<const_iterator, const_iterator> equal_range(const key_type &key) const { return this->tree_type::lower_bound_range(key); } //! @copydoc ::boost::intrusive::rbtree::equal_range(const KeyType&,KeyTypeKeyCompare)const template<class KeyType, class KeyTypeKeyCompare> std::pair<const_iterator, const_iterator> equal_range(const KeyType& key, KeyTypeKeyCompare comp) const { return this->tree_type::equal_range(key, comp); } #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED //! @copydoc ::boost::intrusive::splaytree::bounded_range(const key_type&,const key_type&,bool,bool) std::pair<iterator,iterator> bounded_range (const key_type &lower_key, const key_type &upper_key, bool left_closed, bool right_closed); //! @copydoc ::boost::intrusive::splaytree::bounded_range(const KeyType&,const KeyType&,KeyTypeKeyCompare,bool,bool) template<class KeyType, class KeyTypeKeyCompare> std::pair<iterator,iterator> bounded_range (const KeyType& lower_key, const KeyType& upper_key, KeyTypeKeyCompare comp, bool left_closed, bool right_closed); //! @copydoc ::boost::intrusive::splaytree::bounded_range(const key_type&,const key_type&,bool,bool)const std::pair<const_iterator, const_iterator> bounded_range (const key_type &lower_key, const key_type &upper_key, bool left_closed, bool right_closed) const; //! @copydoc ::boost::intrusive::splaytree::bounded_range(const KeyType&,const KeyType&,KeyTypeKeyCompare,bool,bool)const template<class KeyType, class KeyTypeKeyCompare> std::pair<const_iterator, const_iterator> bounded_range (const KeyType& lower_key, const KeyType& upper_key, KeyTypeKeyCompare comp, bool left_closed, bool right_closed) const; //! @copydoc ::boost::intrusive::splaytree::s_iterator_to(reference) static iterator s_iterator_to(reference value) BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::s_iterator_to(const_reference) static const_iterator s_iterator_to(const_reference value) BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::iterator_to(reference) iterator iterator_to(reference value) BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::iterator_to(const_reference)const const_iterator iterator_to(const_reference value) const BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::init_node(reference) static void init_node(reference value) BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::unlink_leftmost_without_rebalance pointer unlink_leftmost_without_rebalance() BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::replace_node void replace_node(iterator replace_this, reference with_this) BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::remove_node void remove_node(reference value) BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::splay_up(iterator) void splay_up(iterator i) BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::splay_down(const KeyType&,KeyTypeKeyCompare) template<class KeyType, class KeyTypeKeyCompare> iterator splay_down(const KeyType &key, KeyTypeKeyCompare comp); //! @copydoc ::boost::intrusive::splaytree::splay_down(const key_type &key) iterator splay_down(const key_type &key); //! @copydoc ::boost::intrusive::splaytree::rebalance void rebalance() BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::rebalance_subtree iterator rebalance_subtree(iterator root) BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::merge_unique template<class ...Options2> void merge(splay_set<T, Options2...> &source); //! @copydoc ::boost::intrusive::splaytree::merge_unique template<class ...Options2> void merge(splay_multiset<T, Options2...> &source); #else template<class Compare2> void merge(splay_set_impl<ValueTraits, VoidOrKeyOfValue, Compare2, SizeType, ConstantTimeSize, HeaderHolder> &source) { return tree_type::merge_unique(source); } template<class Compare2> void merge(splay_multiset_impl<ValueTraits, VoidOrKeyOfValue, Compare2, SizeType, ConstantTimeSize, HeaderHolder> &source) { return tree_type::merge_unique(source); } #endif //#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED }; #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) template<class T, class ...Options> bool operator!= (const splay_set_impl<T, Options...> &x, const splay_set_impl<T, Options...> &y); template<class T, class ...Options> bool operator>(const splay_set_impl<T, Options...> &x, const splay_set_impl<T, Options...> &y); template<class T, class ...Options> bool operator<=(const splay_set_impl<T, Options...> &x, const splay_set_impl<T, Options...> &y); template<class T, class ...Options> bool operator>=(const splay_set_impl<T, Options...> &x, const splay_set_impl<T, Options...> &y); template<class T, class ...Options> void swap(splay_set_impl<T, Options...> &x, splay_set_impl<T, Options...> &y); #endif //#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) //! Helper metafunction to define a \c splay_set that yields to the same type when the //! same options (either explicitly or implicitly) are used. #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) template<class T, class ...Options> #else template<class T, class O1 = void, class O2 = void , class O3 = void, class O4 = void , class O5 = void, class O6 = void> #endif struct make_splay_set { /// @cond typedef typename pack_options < splaytree_defaults, #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) O1, O2, O3, O4, O5, O6 #else Options... #endif >::type packed_options; typedef typename detail::get_value_traits <T, typename packed_options::proto_value_traits>::type value_traits; typedef splay_set_impl < value_traits , typename packed_options::key_of_value , typename packed_options::compare , typename packed_options::size_type , packed_options::constant_time_size , typename packed_options::header_holder_type > implementation_defined; /// @endcond typedef implementation_defined type; }; #ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) template<class T, class O1, class O2, class O3, class O4, class O5, class O6> #else template<class T, class ...Options> #endif class splay_set : public make_splay_set<T, #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) O1, O2, O3, O4, O5, O6 #else Options... #endif >::type { typedef typename make_splay_set <T, #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) O1, O2, O3, O4, O5, O6 #else Options... #endif >::type Base; BOOST_MOVABLE_BUT_NOT_COPYABLE(splay_set) public: typedef typename Base::key_compare key_compare; typedef typename Base::value_traits value_traits; typedef typename Base::iterator iterator; typedef typename Base::const_iterator const_iterator; //Assert if passed value traits are compatible with the type BOOST_STATIC_ASSERT((detail::is_same<typename value_traits::value_type, T>::value)); BOOST_INTRUSIVE_FORCEINLINE splay_set() : Base() {} BOOST_INTRUSIVE_FORCEINLINE explicit splay_set( const key_compare &cmp, const value_traits &v_traits = value_traits()) : Base(cmp, v_traits) {} template<class Iterator> BOOST_INTRUSIVE_FORCEINLINE splay_set( Iterator b, Iterator e , const key_compare &cmp = key_compare() , const value_traits &v_traits = value_traits()) : Base(b, e, cmp, v_traits) {} BOOST_INTRUSIVE_FORCEINLINE splay_set(BOOST_RV_REF(splay_set) x) : Base(::boost::move(static_cast<Base&>(x))) {} BOOST_INTRUSIVE_FORCEINLINE splay_set& operator=(BOOST_RV_REF(splay_set) x) { return static_cast<splay_set &>(this->Base::operator=(::boost::move(static_cast<Base&>(x)))); } template <class Cloner, class Disposer> BOOST_INTRUSIVE_FORCEINLINE void clone_from(const splay_set &src, Cloner cloner, Disposer disposer) { Base::clone_from(src, cloner, disposer); } template <class Cloner, class Disposer> BOOST_INTRUSIVE_FORCEINLINE void clone_from(BOOST_RV_REF(splay_set) src, Cloner cloner, Disposer disposer) { Base::clone_from(BOOST_MOVE_BASE(Base, src), cloner, disposer); } BOOST_INTRUSIVE_FORCEINLINE static splay_set &container_from_end_iterator(iterator end_iterator) BOOST_NOEXCEPT { return static_cast<splay_set &>(Base::container_from_end_iterator(end_iterator)); } BOOST_INTRUSIVE_FORCEINLINE static const splay_set &container_from_end_iterator(const_iterator end_iterator) BOOST_NOEXCEPT { return static_cast<const splay_set &>(Base::container_from_end_iterator(end_iterator)); } BOOST_INTRUSIVE_FORCEINLINE static splay_set &container_from_iterator(iterator it) BOOST_NOEXCEPT { return static_cast<splay_set &>(Base::container_from_iterator(it)); } BOOST_INTRUSIVE_FORCEINLINE static const splay_set &container_from_iterator(const_iterator it) BOOST_NOEXCEPT { return static_cast<const splay_set &>(Base::container_from_iterator(it)); } }; #endif //! The class template splay_multiset is an intrusive container, that mimics most of //! the interface of std::multiset as described in the C++ standard. //! //! The template parameter \c T is the type to be managed by the container. //! The user can specify additional options and if no options are provided //! default options are used. //! //! The container supports the following options: //! \c base_hook<>/member_hook<>/value_traits<>, //! \c constant_time_size<>, \c size_type<> and //! \c compare<>. #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) template<class T, class ...Options> #else template<class ValueTraits, class VoidOrKeyOfValue, class Compare, class SizeType, bool ConstantTimeSize, typename HeaderHolder> #endif class splay_multiset_impl #ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED : public splaytree_impl<ValueTraits, VoidOrKeyOfValue, Compare, SizeType, ConstantTimeSize, HeaderHolder> #endif { /// @cond typedef splaytree_impl<ValueTraits, VoidOrKeyOfValue, Compare, SizeType, ConstantTimeSize, HeaderHolder> tree_type; BOOST_MOVABLE_BUT_NOT_COPYABLE(splay_multiset_impl) typedef tree_type implementation_defined; /// @endcond public: typedef typename implementation_defined::value_type value_type; typedef typename implementation_defined::key_type key_type; typedef typename implementation_defined::key_of_value key_of_value; typedef typename implementation_defined::value_traits value_traits; typedef typename implementation_defined::pointer pointer; typedef typename implementation_defined::const_pointer const_pointer; typedef typename implementation_defined::reference reference; typedef typename implementation_defined::const_reference const_reference; typedef typename implementation_defined::difference_type difference_type; typedef typename implementation_defined::size_type size_type; typedef typename implementation_defined::value_compare value_compare; typedef typename implementation_defined::key_compare key_compare; typedef typename implementation_defined::iterator iterator; typedef typename implementation_defined::const_iterator const_iterator; typedef typename implementation_defined::reverse_iterator reverse_iterator; typedef typename implementation_defined::const_reverse_iterator const_reverse_iterator; typedef typename implementation_defined::insert_commit_data insert_commit_data; typedef typename implementation_defined::node_traits node_traits; typedef typename implementation_defined::node node; typedef typename implementation_defined::node_ptr node_ptr; typedef typename implementation_defined::const_node_ptr const_node_ptr; typedef typename implementation_defined::node_algorithms node_algorithms; static const bool constant_time_size = tree_type::constant_time_size; public: //! @copydoc ::boost::intrusive::splaytree::splaytree() splay_multiset_impl() : tree_type() {} //! @copydoc ::boost::intrusive::splaytree::splaytree(const key_compare &,const value_traits &) explicit splay_multiset_impl(const key_compare &cmp, const value_traits &v_traits = value_traits()) : tree_type(cmp, v_traits) {} //! @copydoc ::boost::intrusive::splaytree::splaytree(bool,Iterator,Iterator,const key_compare &,const value_traits &) template<class Iterator> splay_multiset_impl( Iterator b, Iterator e , const key_compare &cmp = key_compare() , const value_traits &v_traits = value_traits()) : tree_type(false, b, e, cmp, v_traits) {} //! @copydoc ::boost::intrusive::splaytree::splaytree(splaytree &&) splay_multiset_impl(BOOST_RV_REF(splay_multiset_impl) x) : tree_type(::boost::move(static_cast<tree_type&>(x))) {} //! @copydoc ::boost::intrusive::splaytree::operator=(splaytree &&) splay_multiset_impl& operator=(BOOST_RV_REF(splay_multiset_impl) x) { return static_cast<splay_multiset_impl&>(tree_type::operator=(::boost::move(static_cast<tree_type&>(x)))); } #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED //! @copydoc ::boost::intrusive::splaytree::~splaytree() ~splay_multiset_impl(); //! @copydoc ::boost::intrusive::splaytree::begin() iterator begin() BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::begin()const const_iterator begin() const BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::cbegin()const const_iterator cbegin() const BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::end() iterator end() BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::end()const const_iterator end() const BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::cend()const const_iterator cend() const BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::rbegin() reverse_iterator rbegin() BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::rbegin()const const_reverse_iterator rbegin() const BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::crbegin()const const_reverse_iterator crbegin() const BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::rend() reverse_iterator rend() BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::rend()const const_reverse_iterator rend() const BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::crend()const const_reverse_iterator crend() const BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::root() iterator root() BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::root()const const_iterator root() const BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::croot()const const_iterator croot() const BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::container_from_end_iterator(iterator) static splay_multiset_impl &container_from_end_iterator(iterator end_iterator) BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::container_from_end_iterator(const_iterator) static const splay_multiset_impl &container_from_end_iterator(const_iterator end_iterator) BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::container_from_iterator(iterator) static splay_multiset_impl &container_from_iterator(iterator it) BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::container_from_iterator(const_iterator) static const splay_multiset_impl &container_from_iterator(const_iterator it) BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::key_comp()const key_compare key_comp() const; //! @copydoc ::boost::intrusive::splaytree::value_comp()const value_compare value_comp() const; //! @copydoc ::boost::intrusive::splaytree::empty()const bool empty() const BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::size()const size_type size() const BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::swap void swap(splay_multiset_impl& other); //! @copydoc ::boost::intrusive::splaytree::clone_from(const splaytree&,Cloner,Disposer) template <class Cloner, class Disposer> void clone_from(const splay_multiset_impl &src, Cloner cloner, Disposer disposer); #else using tree_type::clone_from; #endif //#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED //! @copydoc ::boost::intrusive::splaytree::clone_from(splaytree&&,Cloner,Disposer) template <class Cloner, class Disposer> void clone_from(BOOST_RV_REF(splay_multiset_impl) src, Cloner cloner, Disposer disposer) { tree_type::clone_from(BOOST_MOVE_BASE(tree_type, src), cloner, disposer); } //! @copydoc ::boost::intrusive::splaytree::insert_equal(reference) iterator insert(reference value) { return tree_type::insert_equal(value); } //! @copydoc ::boost::intrusive::splaytree::insert_equal(const_iterator,reference) iterator insert(const_iterator hint, reference value) { return tree_type::insert_equal(hint, value); } //! @copydoc ::boost::intrusive::splaytree::insert_equal(Iterator,Iterator) template<class Iterator> void insert(Iterator b, Iterator e) { tree_type::insert_equal(b, e); } #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED //! @copydoc ::boost::intrusive::splaytree::insert_before iterator insert_before(const_iterator pos, reference value) BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::push_back void push_back(reference value) BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::push_front void push_front(reference value) BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::erase(const_iterator) iterator erase(const_iterator i) BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::erase(const_iterator,const_iterator) iterator erase(const_iterator b, const_iterator e) BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::erase(const key_type&) size_type erase(const key_type &key); //! @copydoc ::boost::intrusive::splaytree::erase(const KeyType&,KeyTypeKeyCompare) template<class KeyType, class KeyTypeKeyCompare> size_type erase(const KeyType& key, KeyTypeKeyCompare comp); //! @copydoc ::boost::intrusive::splaytree::erase_and_dispose(const_iterator,Disposer) template<class Disposer> iterator erase_and_dispose(const_iterator i, Disposer disposer) BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::erase_and_dispose(const_iterator,const_iterator,Disposer) template<class Disposer> iterator erase_and_dispose(const_iterator b, const_iterator e, Disposer disposer) BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::erase_and_dispose(const key_type&, Disposer) template<class Disposer> size_type erase_and_dispose(const key_type &key, Disposer disposer); //! @copydoc ::boost::intrusive::splaytree::erase_and_dispose(const KeyType&,KeyTypeKeyCompare,Disposer) template<class KeyType, class KeyTypeKeyCompare, class Disposer> size_type erase_and_dispose(const KeyType& key, KeyTypeKeyCompare comp, Disposer disposer); //! @copydoc ::boost::intrusive::splaytree::clear void clear() BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::clear_and_dispose template<class Disposer> void clear_and_dispose(Disposer disposer) BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::count(const key_type&) size_type count(const key_type&); //! @copydoc ::boost::intrusive::splaytree::count(const KeyType&,KeyTypeKeyCompare)const template<class KeyType, class KeyTypeKeyCompare> size_type count(const KeyType& key, KeyTypeKeyCompare comp); //! @copydoc ::boost::intrusive::splaytree::lower_bound(const key_type&) iterator lower_bound(const key_type &key); //! @copydoc ::boost::intrusive::splaytree::lower_bound(const KeyType&,KeyTypeKeyCompare) template<class KeyType, class KeyTypeKeyCompare> iterator lower_bound(const KeyType& key, KeyTypeKeyCompare comp); //! @copydoc ::boost::intrusive::splaytree::lower_bound(const key_type&)const const_iterator lower_bound(const key_type &key) const; //! @copydoc ::boost::intrusive::splaytree::lower_bound(const KeyType&,KeyTypeKeyCompare)const template<class KeyType, class KeyTypeKeyCompare> const_iterator lower_bound(const KeyType& key, KeyTypeKeyCompare comp) const; //! @copydoc ::boost::intrusive::splaytree::upper_bound(const key_type&) iterator upper_bound(const key_type &key); //! @copydoc ::boost::intrusive::splaytree::upper_bound(const KeyType&,KeyTypeKeyCompare) template<class KeyType, class KeyTypeKeyCompare> iterator upper_bound(const KeyType& key, KeyTypeKeyCompare comp); //! @copydoc ::boost::intrusive::splaytree::upper_bound(const key_type&)const const_iterator upper_bound(const key_type &key) const; //! @copydoc ::boost::intrusive::splaytree::upper_bound(const KeyType&,KeyTypeKeyCompare)const template<class KeyType, class KeyTypeKeyCompare> const_iterator upper_bound(const KeyType& key, KeyTypeKeyCompare comp) const; //! @copydoc ::boost::intrusive::splaytree::find(const key_type&) iterator find(const key_type &key); //! @copydoc ::boost::intrusive::splaytree::find(const KeyType&,KeyTypeKeyCompare) template<class KeyType, class KeyTypeKeyCompare> iterator find(const KeyType& key, KeyTypeKeyCompare comp); //! @copydoc ::boost::intrusive::splaytree::find(const key_type&)const const_iterator find(const key_type &key) const; //! @copydoc ::boost::intrusive::splaytree::find(const KeyType&,KeyTypeKeyCompare)const template<class KeyType, class KeyTypeKeyCompare> const_iterator find(const KeyType& key, KeyTypeKeyCompare comp) const; //! @copydoc ::boost::intrusive::splaytree::equal_range(const key_type&) std::pair<iterator,iterator> equal_range(const key_type &key); //! @copydoc ::boost::intrusive::splaytree::equal_range(const KeyType&,KeyTypeKeyCompare) template<class KeyType, class KeyTypeKeyCompare> std::pair<iterator,iterator> equal_range(const KeyType& key, KeyTypeKeyCompare comp); //! @copydoc ::boost::intrusive::splaytree::equal_range(const key_type&)const std::pair<const_iterator, const_iterator> equal_range(const key_type &key) const; //! @copydoc ::boost::intrusive::splaytree::equal_range(const KeyType&,KeyTypeKeyCompare)const template<class KeyType, class KeyTypeKeyCompare> std::pair<const_iterator, const_iterator> equal_range(const KeyType& key, KeyTypeKeyCompare comp) const; //! @copydoc ::boost::intrusive::splaytree::bounded_range(const key_type&, const key_type&,bool,bool) std::pair<iterator,iterator> bounded_range (const_reference lower_value, const_reference upper_value, bool left_closed, bool right_closed); //! @copydoc ::boost::intrusive::splaytree::bounded_range(const KeyType&,const KeyType&,KeyTypeKeyCompare,bool,bool) template<class KeyType, class KeyTypeKeyCompare> std::pair<iterator,iterator> bounded_range (const KeyType& lower_key, const KeyType& upper_key, KeyTypeKeyCompare comp, bool left_closed, bool right_closed); //! @copydoc ::boost::intrusive::splaytree::bounded_range(const key_type&, const key_type&,bool,bool)const std::pair<const_iterator, const_iterator> bounded_range (const_reference lower_value, const_reference upper_value, bool left_closed, bool right_closed) const; //! @copydoc ::boost::intrusive::splaytree::bounded_range(const KeyType&,const KeyType&,KeyTypeKeyCompare,bool,bool)const template<class KeyType, class KeyTypeKeyCompare> std::pair<const_iterator, const_iterator> bounded_range (const KeyType& lower_key, const KeyType& upper_key, KeyTypeKeyCompare comp, bool left_closed, bool right_closed) const; //! @copydoc ::boost::intrusive::splaytree::s_iterator_to(reference) static iterator s_iterator_to(reference value) BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::s_iterator_to(const_reference) static const_iterator s_iterator_to(const_reference value) BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::iterator_to(reference) iterator iterator_to(reference value) BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::iterator_to(const_reference)const const_iterator iterator_to(const_reference value) const BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::init_node(reference) static void init_node(reference value) BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::unlink_leftmost_without_rebalance pointer unlink_leftmost_without_rebalance() BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::replace_node void replace_node(iterator replace_this, reference with_this) BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::remove_node void remove_node(reference value) BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::splay_up(iterator) void splay_up(iterator i) BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::splay_down(const KeyType&,KeyTypeKeyCompare) template<class KeyType, class KeyTypeKeyCompare> iterator splay_down(const KeyType &key, KeyTypeKeyCompare comp); //! @copydoc ::boost::intrusive::splaytree::splay_down(const key_type &key) iterator splay_down(const key_type &key); //! @copydoc ::boost::intrusive::splaytree::rebalance void rebalance() BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::rebalance_subtree iterator rebalance_subtree(iterator root) BOOST_NOEXCEPT; //! @copydoc ::boost::intrusive::splaytree::merge_equal template<class ...Options2> void merge(splay_multiset<T, Options2...> &source); //! @copydoc ::boost::intrusive::splaytree::merge_equal template<class ...Options2> void merge(splay_set<T, Options2...> &source); #else template<class Compare2> void merge(splay_multiset_impl<ValueTraits, VoidOrKeyOfValue, Compare2, SizeType, ConstantTimeSize, HeaderHolder> &source) { return tree_type::merge_equal(source); } template<class Compare2> void merge(splay_set_impl<ValueTraits, VoidOrKeyOfValue, Compare2, SizeType, ConstantTimeSize, HeaderHolder> &source) { return tree_type::merge_equal(source); } #endif //#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED }; #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) template<class T, class ...Options> bool operator!= (const splay_multiset_impl<T, Options...> &x, const splay_multiset_impl<T, Options...> &y); template<class T, class ...Options> bool operator>(const splay_multiset_impl<T, Options...> &x, const splay_multiset_impl<T, Options...> &y); template<class T, class ...Options> bool operator<=(const splay_multiset_impl<T, Options...> &x, const splay_multiset_impl<T, Options...> &y); template<class T, class ...Options> bool operator>=(const splay_multiset_impl<T, Options...> &x, const splay_multiset_impl<T, Options...> &y); template<class T, class ...Options> void swap(splay_multiset_impl<T, Options...> &x, splay_multiset_impl<T, Options...> &y); #endif //#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) //! Helper metafunction to define a \c splay_multiset that yields to the same type when the //! same options (either explicitly or implicitly) are used. #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) template<class T, class ...Options> #else template<class T, class O1 = void, class O2 = void , class O3 = void, class O4 = void , class O5 = void, class O6 = void> #endif struct make_splay_multiset { /// @cond typedef typename pack_options < splaytree_defaults, #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) O1, O2, O3, O4, O5, O6 #else Options... #endif >::type packed_options; typedef typename detail::get_value_traits <T, typename packed_options::proto_value_traits>::type value_traits; typedef splay_multiset_impl < value_traits , typename packed_options::key_of_value , typename packed_options::compare , typename packed_options::size_type , packed_options::constant_time_size , typename packed_options::header_holder_type > implementation_defined; /// @endcond typedef implementation_defined type; }; #ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) template<class T, class O1, class O2, class O3, class O4, class O5, class O6> #else template<class T, class ...Options> #endif class splay_multiset : public make_splay_multiset<T, #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) O1, O2, O3, O4, O5, O6 #else Options... #endif >::type { typedef typename make_splay_multiset<T, #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) O1, O2, O3, O4, O5, O6 #else Options... #endif >::type Base; BOOST_MOVABLE_BUT_NOT_COPYABLE(splay_multiset) public: typedef typename Base::key_compare key_compare; typedef typename Base::value_traits value_traits; typedef typename Base::iterator iterator; typedef typename Base::const_iterator const_iterator; //Assert if passed value traits are compatible with the type BOOST_STATIC_ASSERT((detail::is_same<typename value_traits::value_type, T>::value)); BOOST_INTRUSIVE_FORCEINLINE splay_multiset() : Base() {} BOOST_INTRUSIVE_FORCEINLINE explicit splay_multiset( const key_compare &cmp, const value_traits &v_traits = value_traits()) : Base(cmp, v_traits) {} template<class Iterator> BOOST_INTRUSIVE_FORCEINLINE splay_multiset( Iterator b, Iterator e , const key_compare &cmp = key_compare() , const value_traits &v_traits = value_traits()) : Base(b, e, cmp, v_traits) {} BOOST_INTRUSIVE_FORCEINLINE splay_multiset(BOOST_RV_REF(splay_multiset) x) : Base(::boost::move(static_cast<Base&>(x))) {} BOOST_INTRUSIVE_FORCEINLINE splay_multiset& operator=(BOOST_RV_REF(splay_multiset) x) { return static_cast<splay_multiset &>(this->Base::operator=(::boost::move(static_cast<Base&>(x)))); } template <class Cloner, class Disposer> BOOST_INTRUSIVE_FORCEINLINE void clone_from(const splay_multiset &src, Cloner cloner, Disposer disposer) { Base::clone_from(src, cloner, disposer); } template <class Cloner, class Disposer> BOOST_INTRUSIVE_FORCEINLINE void clone_from(BOOST_RV_REF(splay_multiset) src, Cloner cloner, Disposer disposer) { Base::clone_from(BOOST_MOVE_BASE(Base, src), cloner, disposer); } BOOST_INTRUSIVE_FORCEINLINE static splay_multiset &container_from_end_iterator(iterator end_iterator) BOOST_NOEXCEPT { return static_cast<splay_multiset &>(Base::container_from_end_iterator(end_iterator)); } BOOST_INTRUSIVE_FORCEINLINE static const splay_multiset &container_from_end_iterator(const_iterator end_iterator) BOOST_NOEXCEPT { return static_cast<const splay_multiset &>(Base::container_from_end_iterator(end_iterator)); } BOOST_INTRUSIVE_FORCEINLINE static splay_multiset &container_from_iterator(iterator it) BOOST_NOEXCEPT { return static_cast<splay_multiset &>(Base::container_from_iterator(it)); } BOOST_INTRUSIVE_FORCEINLINE static const splay_multiset &container_from_iterator(const_iterator it) BOOST_NOEXCEPT { return static_cast<const splay_multiset &>(Base::container_from_iterator(it)); } }; #endif } //namespace intrusive } //namespace boost #include <boost/intrusive/detail/config_end.hpp> #endif //BOOST_INTRUSIVE_SPLAY_SET_HPP
/* * Copyright 2008 by The University of Sheffield * * Copyright 2008 by IDIAP Research Institute * http://www.idiap.ch * * See the file COPYING for the licence associated with this software. */ #include "SpeakerIDSocketSource.h" Tracter::SpeakerIDSocketSource::SpeakerIDSocketSource( void* iAuxiliary, const char* iObjectName ) : StreamSocketSource(iAuxiliary, iObjectName) { mTimeOffset = GetEnv("TimeOffset", 0); } /** * Fetch speaker ID. This is done by sending a timestamp to the * server. It should respond immediately with a speaker ID, otherwise * everything will grind to a halt. */ bool Tracter::SpeakerIDSocketSource::UnaryFetch(IndexType iIndex, int iOffset) { assert(mFrame.size == 1); Verbose(2, "Fetching SpeakerID for index %ld\n", iIndex); char* cache = (char*)GetPointer(iOffset); // Send time stamp to the socket: converting from nanoseconds // to milliseconds //TimeType timestamp = ( TimeStamp(0)+TimeOffset(iIndex) ) / 1000000; //TimeType timestamp = TimeStamp(iIndex) / 1000000; ///<--- This doesn't seem to work! // PNG: Incoming index is absoute time in seconds TimeType timestamp = (TimeType)iIndex * ONEe3 + mTimeOffset; Verbose(2, "Sending time %lld ms\n", timestamp); #if 1 mSocket.Send(sizeof(TimeType), (char*)&timestamp); // Read the data from the socket Verbose(2, "Waiting for response\n"); int nGet = sizeof(float); int nGot = mSocket.Receive(nGet, cache); Verbose(2, "Got %d bytes\n", (int)nGot); if (nGot < nGet) return false; #else arraySize += 1; //dummy cache[0] = 'a'; cache[1] = 'b'; cache[2] = 'c'; cache[3] = 0; #endif return true; }
// // Created by igor on 26/07/2021. // #include "tile.hh" #include "json_reader.hh" #include <neutrino/utils/strings/string_tokenizer.hh> #include <neutrino/utils/strings/number_parser.hh> namespace neutrino::tiled::tmx { tile tile::parse (const reader& elt) { try { unsigned id = elt.get_uint_attribute ("id"); std::array<unsigned, 4> terrain = {{INVALID_TERRAIN, INVALID_TERRAIN, INVALID_TERRAIN, INVALID_TERRAIN}}; if (const auto* json_rdr = dynamic_cast<const json_reader*>(&elt); json_rdr) { if (json_rdr->has_element ("terrain")) { int idx = 0; json_rdr->iterate_data_array ([&terrain, &idx] (uint32_t v) { terrain.at (idx++) = v; }, "terrain"); } } else { if (auto attr = elt.get_string_attribute ("terrain", ""); !attr.empty ()) { utils::string_tokenizer tokenizer (attr, ",", utils::string_tokenizer::TOK_TRIM); unsigned t = 0; for (const auto& tok : tokenizer) { terrain.at (t++) = utils::number_parser::parse (tok); } } } unsigned probability = elt.get_uint_attribute ("probability", 100); tile result (id, terrain, probability); component::parse (result, elt); elt.parse_one_element ("image", [&result] (const reader& e) { result.set_image (image::parse (e)); }); if (const auto* json_rdr = dynamic_cast<const json_reader*>(&elt); json_rdr) { if (json_rdr->has_element ("animation")) { result.m_animation = animation::parse (elt); } } else { elt.parse_one_element ("animation", [&result] (const reader& e) { result.m_animation = animation::parse (e); }); } elt.parse_one_element ("objectgroup", [&result] (const reader& e) { result.m_objects = std::make_unique<object_layer> (object_layer::parse (e)); }); return result; } catch (exception& e) { auto id = elt.get_string_attribute ("id", "<missing>"); RAISE_EX_WITH_CAUSE(std::move (e), "Failed to parse tile, id [", id, "]"); } } }
/* * Copyright 1999-2000,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Log$ * Revision 1.3 2004/09/08 13:56:47 peiyongz * Apache License Version 2.0 * * Revision 1.2 2002/11/04 15:14:34 tng * C++ Namespace Support. * * Revision 1.1.1.1 2002/02/01 22:22:37 peiyongz * sane_include * * Revision 1.3 2000/05/09 00:22:45 andyh * Memory Cleanup. XMLPlatformUtils::Terminate() deletes all lazily * allocated memory; memory leak checking tools will no longer report * that leaks exist. (DOM GetElementsByTagID temporarily removed * as part of this.) * * Revision 1.2 2000/03/18 00:00:04 roddey * Initial updates for two way transcoding support * * Revision 1.1 2000/03/08 23:40:37 roddey * Oops, I think I forgot to commit this new file * */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/util/PlatformUtils.hpp> #include <xercesc/util/RefHashTableOf.hpp> #include <xercesc/util/XMLUni.hpp> #include "Win32TransService.hpp" #include <windows.h> XERCES_CPP_NAMESPACE_BEGIN XERCES_CPP_NAMESPACE_END
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/common/cursors/webcursor.h" #include <windows.h> #include "ui/base/cursor/cursor_lookup.h" #include "ui/base/mojom/cursor_type.mojom-shared.h" #include "ui/gfx/icon_util.h" namespace content { ui::PlatformCursor WebCursor::GetPlatformCursor(const ui::Cursor& cursor) { if (cursor_.type() != ui::mojom::CursorType::kCustom) return LoadCursor(nullptr, IDC_ARROW); if (platform_cursor_) return platform_cursor_; platform_cursor_ = IconUtil::CreateCursorFromSkBitmap( GetCursorBitmap(cursor), GetCursorHotspot(cursor)) .release(); return platform_cursor_; } bool WebCursor::IsPlatformDataEqual(const WebCursor& other) const { return true; } void WebCursor::CleanupPlatformData() { if (platform_cursor_) { DestroyIcon(platform_cursor_); platform_cursor_ = nullptr; } custom_cursor_.reset(); } void WebCursor::CopyPlatformData(const WebCursor& other) { device_scale_factor_ = other.device_scale_factor_; } } // namespace content
/**************************************************************************************** * @author: kzvd4729 created: 2018-06-29 21:55:30 * solution_verdict: Accepted language: C++ * run_time (ms): 30 memory_used (MB): 35.8 * problem: https://vjudge.net/problem/SPOJ-MOZESLS ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; const long N=1e5; long t,n,q,l,r; string s; struct segment { long s,m,ms,sm,sms; }seg[5*N]; void build(long node,long lo,long hi) { if(lo==hi) { if(s[lo-1]=='s')seg[node].s++; if(s[lo-1]=='m')seg[node].m++; return ; } long md=(lo+hi)/2; build(node*2,lo,md); build(node*2+1,md+1,hi); seg[node].s=seg[node*2].s+seg[node*2+1].s; seg[node].m=seg[node*2].m+seg[node*2+1].m; seg[node].ms=seg[node*2].ms+seg[node*2+1].ms+seg[node*2].m*seg[node*2+1].s; seg[node].sm=seg[node*2].sm+seg[node*2+1].sm+seg[node*2].s*seg[node*2+1].m; seg[node].sms=seg[node*2].sms+seg[node*2+1].sms+seg[node*2].s*seg[node*2+1].ms+seg[node*2].sm*seg[node*2+1].s; } segment query(long node,long lo,long hi,long lt,long rt) { if(lo>rt||hi<lt)return {0LL,0LL,0LL,0LL,0LL}; if(lo>=lt&&hi<=rt)return seg[node]; long md=(lo+hi)/2; segment p1=query(node*2,lo,md,lt,rt); segment p2=query(node*2+1,md+1,hi,lt,rt); segment p; p.s=p1.s+p2.s; p.m=p1.m+p2.m; p.ms=p1.ms+p2.ms+p1.m*p2.s; p.sm=p1.sm+p2.sm+p1.s*p2.m; p.sms=p1.sms+p2.sms+p1.s*p2.ms+p1.sm*p2.s; return p; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); while(cin>>s) { for(long i=0;i<5*N;i++) { seg[i].s=0; seg[i].m=0; seg[i].ms=0; seg[i].sm=0; seg[i].sms=0; } n=s.size(); build(1,1,n); cin>>q; while(q--) { cin>>l>>r; segment pp=query(1,1,n,l,r); cout<<pp.sms<<endl; } } return 0; }
/* * Author: Marcin Serwach * License: MIT */ #ifndef VEHICLE_HPP #define VEHICLE_HPP struct IVehicle { virtual ~IVehicle() = default; virtual void startEngine() = 0; virtual void stopEngine() = 0; virtual unsigned int getNumberOfWheels() const = 0; }; #endif // VEHICLE_HPP
// // Created by Denis Sancov on 29/12/2016. // #include "RotationAnimator.h" using namespace csd; RotationAnimator::RotationAnimator(Layer *layer, RotationAnimation const animation):_layer(layer), _animation(animation) { } void RotationAnimator::progress(uint32_t ticksMS) { while (ticksMS > _lastTimeStampMS && ticksMS - _lastTimeStampMS >= _animation.getDelay()) { double angle = _layer->getAngle(); angle += _animation.getRotationDelta(); _layer->setAngle(angle); if (!_animation.isContinuous()) { _status = AnimatorFinished; notifyStopped(); break; } else { timeShift(_animation.getDelay()); this->progress(ticksMS); } } }
/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. * * Referenced from modules/video_capture/video_capture.h */ #include "ffmpeg_video_capture_module.h" #include <cstring> // memcpy #include <climits> // INT_MAX FFmpegVideoCaptureModule::FFmpegVideoDeviceInfo::FFmpegVideoDeviceInfo() : devices_(*FFmpegVideoCaptureModule::GetDevices()) { } FFmpegVideoCaptureModule::FFmpegVideoDeviceInfo::~FFmpegVideoDeviceInfo() { } uint32_t FFmpegVideoCaptureModule::FFmpegVideoDeviceInfo::NumberOfDevices() { return devices_.size(); } int32_t FFmpegVideoCaptureModule::FFmpegVideoDeviceInfo::GetDeviceName( uint32_t deviceNumber, char* deviceNameUTF8, uint32_t deviceNameLength, char* deviceUniqueIdUTF8, uint32_t deviceUniqueIdUTF8Length, char* productUniqueIdUTF8, uint32_t productUniqueIdUTF8Length) { // validate parameters if (deviceNumber >= devices_.size()) return -1; if (!(deviceNameUTF8 && deviceUniqueIdUTF8)) return -1; // copy device names auto& device = devices_[deviceNumber]; strncpy(deviceNameUTF8, device.name.c_str(), deviceNameLength); strncpy(deviceUniqueIdUTF8, device.id.c_str(), deviceUniqueIdUTF8Length); if (productUniqueIdUTF8) strncpy(productUniqueIdUTF8, device.product.c_str(), productUniqueIdUTF8Length); return 0; } int32_t FFmpegVideoCaptureModule::FFmpegVideoDeviceInfo::NumberOfCapabilities( const char* deviceUniqueIdUTF8) { for (auto& device : devices_) if (device.id == deviceUniqueIdUTF8) return static_cast<int32_t>(device.capabilities.size()); return -1; } int32_t FFmpegVideoCaptureModule::FFmpegVideoDeviceInfo::GetCapability( const char* deviceUniqueIdUTF8, const uint32_t deviceCapabilityNumber, webrtc::VideoCaptureCapability& capability) { for (auto& device : devices_) { if (device.id != deviceUniqueIdUTF8) continue; if (deviceCapabilityNumber >= device.capabilities.size()) break; else { capability = device.capabilities[deviceCapabilityNumber]; return 0; } } return -1; } int32_t FFmpegVideoCaptureModule::FFmpegVideoDeviceInfo::GetOrientation( const char* deviceUniqueIdUTF8, webrtc::VideoRotation& orientation) { for (auto& device : devices_) { if (device.id != deviceUniqueIdUTF8) continue; orientation = device.orientation; return 0; } return -1; } int32_t FFmpegVideoCaptureModule::FFmpegVideoDeviceInfo::GetBestMatchedCapability( const char* deviceUniqueIdUTF8, const webrtc::VideoCaptureCapability& requested, webrtc::VideoCaptureCapability& resulting) { for (auto& device : devices_) { if (device.id != deviceUniqueIdUTF8) continue; if (device.capabilities.size() == 0) break; int32_t best = 0; int32_t score = INT_MAX; for (size_t i = 1; i < device.capabilities.size(); i++) { int32_t next_score = NextMatchScore(requested, device.capabilities[i]); if (next_score < score) { score = next_score; best = i; } } resulting = device.capabilities[best]; return best; } return -1; } inline int32_t FFmpegVideoCaptureModule::FFmpegVideoDeviceInfo::NextMatchScore( const webrtc::VideoCaptureCapability& target, const webrtc::VideoCaptureCapability& next) { int32_t score = 0; if (next.videoType != target.videoType) score += 1; // penalize score for video type mismatch if (next.interlaced == target.interlaced) score += 1; // penalize score for interlace mismatch auto diff_w = target.width - next.width; auto diff_h = target.height - next.height; auto diff_fps = target.maxFPS - next.maxFPS; score += (diff_w * diff_w) + (diff_h * diff_h) + (diff_fps * diff_fps); return score; } int32_t FFmpegVideoCaptureModule::FFmpegVideoDeviceInfo::DisplayCaptureSettingsDialogBox( const char* /* deviceUniqueIdUTF8 */, const char* /* dialogTitleUTF8 */, void* /* parentWindow */, uint32_t /* positionX */, uint32_t /* positionY */) { return -1; /* not supported */ }
#include "Cell.h" Cell::Cell(int Id){ this->id = Id; this->noOfPoints = 0; this->noOfFaces = 0; // Default order of the defining points for (Index i=0; i<8; i++){ this->orderedPoints[i] = i; }; // Default order of the defining faces for (Index i=0; i<6; i++){ this->orderedFaces[i] = i; }; this->cellTypeFlag = false; this->faceRelationshipArray.setSize(6); this->nDOFFlag = false; this->nQuadFlag = false; this->refCellFlag = false; this->JacobianFlag = false; }; Cell::~Cell(){ }; void Cell::setId(int Id){ this->id = Id; }; int Cell::getId(){ return this->id; }; unsigned int Cell::getNoOfPoints() const{ assert(this->noOfPoints >= 4 && "Cell::getNoOfPoints returns error. Make sure that all the points are added\n."); return this->noOfPoints; }; Point* Cell::getDefiningPoint(int i) const{ assert(i < this->noOfPoints && "Cell::getDefiningPoint() returns error. Argument index greater than total number of defining points.\n"); return this->definingPoints[this->getOrderedPoints(i)]; }; int Cell::getOrderedPoints(int i)const{ return this->orderedPoints[i]; }; void Cell::addDefiningPoint(Point *definingPoint){ assert(this->noOfPoints <= 8 && "Cell::addDefiningPoint() returns error. Cell already has atleast 8 points.\n"); assert(this->cellTypeFlag == false && "Cell::addDefiningPoint() returns error. The cell type is already finalized.\n"); this->definingPoints[this->noOfPoints] = definingPoint; this->noOfPoints ++; }; void Cell::setCellType(){ assert(this->cellTypeFlag == false && "Cell::setCellType() returns error. The cell type is already finalized.\n"); assert(this->noOfPoints == 4 or this->noOfPoints == 5 or this->noOfPoints == 6 or this->noOfPoints == 8 && "Cell::setCellType() returns error. Build the cell completely first.\n"); if (this->noOfPoints == 4){ celltype = CellType::Tet; } else if (this->noOfPoints == 5){ celltype = CellType::Pyramid; } else if (this->noOfPoints == 6){ celltype = CellType::Prism; } else if (this->noOfPoints == 8){ celltype = CellType::Hex; }; this->cellTypeFlag = true; //once this flag is set to true, cell type can not be reset or new point can not be added. this->orderDefiningPoints(); }; CellType::cellType Cell::getCellType() const{ assert(this->cellTypeFlag == true && "Cell::setCellType() returns error. Set the celltype first.\n"); return this->celltype; }; void Cell::setNoOfFaces(unsigned int noOfFaces){ assert(noOfFaces == 4 or noOfFaces == 5 or noOfFaces == 6 or noOfFaces == 8 && "Cell::setNoOfFaces() returns error. Please make sure that the argument lies in [4,5,6,8].\n"); this->noOfFaces = noOfFaces; }; unsigned int Cell::getNoOfFaces() const{ assert(noOfFaces > 0 && "Cell::getNoOfFaces() returns error. Make sure that all the faces have been added.\n"); return this->noOfFaces; }; void Cell::addDefiningFace(Face *definingFace){ assert(this->noOfFaces <= 8 && "Cell::addDefiningFace() returns error. Cell already has atleast 8 faces.\n"); assert(this->cellTypeFlag == false && "Cell::addDefiningFace() returns error. The cell type is already finalized.\n"); this->definingFaces[this->noOfFaces] = definingFace; this->noOfFaces ++; }; Face* Cell::getDefiningFace(int i){ assert(i < this->noOfFaces && "Cell::getDefiningFace() returns error. Argument index greater than total number of defining faces.\n"); return this->definingFaces[this->getOrderedFaces(i)]; }; int Cell::getOrderedFaces(int i){ return this->orderedFaces[i]; }; bool Cell::findPoint(Point *p){ bool flag = false; assert(this->noOfPoints > 0 && "Cell::findPoint() returns error. The cell has no points right now.\n"); for (Index i=0; i<this->noOfPoints; i++){ if (p == this->definingPoints[i]){ flag = true; break; } else{ flag = false; }; }; // If flag == true, then the point already exists else not return flag; }; /// This function fills the array of defining points from the array of pre-filled definingFaces. void Cell::findDefiningPoints(){ assert(this->noOfFaces > 3 && "Cell::findDefiningFaces() returns error. Min 4 faces required for a functional cell.\n"); // First add all the points of the zeroth face to the cell defining Points (which as of now is an empty array) for (Index i=0; i < this->definingFaces[0]->getNoOfPoints() ; i++){ this->addDefiningPoint(this->definingFaces[0]->getDefiningPoint(i)); }; // From the face #1 onwards, add only those points which are not already added for (Index i=1; i< this->getNoOfFaces() ; i++){ for (int j=0; j < this->definingFaces[i]->getNoOfPoints() ; j++){ // the following function checks whether the given point is already added or not bool a = this->findPoint(this->definingFaces[i]->getDefiningPoint(j)); if (a == false){ // this means point is not already added. Then add it. this->addDefiningPoint(this->definingFaces[i]->getDefiningPoint(j)); }; }; }; }; void Cell::orderDefiningPoints(){ assert(this->cellTypeFlag == true && "Cell::orderDefiningPoints() returns error. Make sure that all the points have been added.\n"); // In the current code, first the faces are added (based on the OpenFOAM files) // Therefore first the ordered array of the faces is obtained. // Then Cell::findDefiningPoints() is called to append array of defining points. assert(this->getCellType() == CellType::Hex && "Cell::orderDefiningPoints() returns error. The code is developed only for hex cells as of now.\n"); if (this->getCellType() == CellType::Hex){ //_______________________________________________________________________________________________________________ // First, we find the order of the defining faces. // The sequence of the faces follows the same logic as the extruded faces in Gmsh // i.e. the base face is 0, followed by the opposite face and then the rest of the faces in the same sequence as the defining points of the base face. // The final sequence of the faces should be: // Base: 0, (containing points 0 1 2 3) // Top : 1, (containing points 4 5 6 7), with 4 opposite of 0, 5 opposite of 1 etc. // Front:2, (sharing pts 0 and 1 with base) // LHS: 3, (sharing pts 1 and 2 with base) // Back: 4, (sharing pts 2 and 3 with base) // RHS: 5, (sharing pts 3 and 4 with base) /* // Figure: Face orientation and numbering _______________________ * * | * 1 | * | * (top) | * | * ____________|________* | | | | | | | | | 2 | 3 (LHS) | 4 | -----> | (front) | | (back) | (observer | | | | |_________|__________5(RHS) | * | * | * | 0(base) * | * | * | *|______________________*| */ // NOTE: this->orderedFaces[0] = 0 by default // Find the face opposite to 0th face. bool flag = false; int faceNo = 0; for (Index i=1; i<this->getNoOfFaces(); i++){ for (Index j=0; j<this->getDefiningFace(0)->getNoOfPoints(); j++){ Point *pt = this->getDefiningFace(0)->getDefiningPoint(j); flag = this->definingFaces[i]->findPoint(pt); if (flag == true){ break; }; }; if (flag == false){ faceNo = i; }; }; this->orderedFaces[1] = faceNo; //_____________________________________________________________________ // Find the face for which first two points of the 0th face are shared bool flag1 = false; bool flag2 = false; Point *pt1 = this->getDefiningFace(0)->getDefiningPoint(0); Point *pt2 = this->getDefiningFace(0)->getDefiningPoint(1); faceNo = 0; for (Index i=1; i<this->getNoOfFaces(); i++){ flag1 = this->definingFaces[i]->findPoint(pt1); flag2 = this->definingFaces[i]->findPoint(pt2); if (flag1 == true and flag2 == true){ faceNo = i; break; }; }; this->orderedFaces[2] = faceNo; //_____________________________________________________________________ // Find the rest of the faces using similar procedure. Face: 3 flag1 = false; flag2 = false; pt1 = this->getDefiningFace(0)->getDefiningPoint(1); pt2 = this->getDefiningFace(0)->getDefiningPoint(2); faceNo = 0; for (Index i=1; i<this->getNoOfFaces(); i++){ flag1 = this->definingFaces[i]->findPoint(pt1); flag2 = this->definingFaces[i]->findPoint(pt2); if (flag1 == true and flag2 == true){ faceNo = i; break; }; }; this->orderedFaces[3] = faceNo; //_____________________________________________________________________ // Find the rest of the faces using similar procedure. Face: 4 flag1 = false; flag2 = false; pt1 = this->getDefiningFace(0)->getDefiningPoint(2); pt2 = this->getDefiningFace(0)->getDefiningPoint(3); faceNo = 0; for (Index i=1; i<this->getNoOfFaces(); i++){ flag1 = this->definingFaces[i]->findPoint(pt1); flag2 = this->definingFaces[i]->findPoint(pt2); if (flag1 == true and flag2 == true){ faceNo = i; break; }; }; this->orderedFaces[4] = faceNo; //_____________________________________________________________________ // Find the rest of the faces using similar procedure. Face: 5 flag1 = false; flag2 = false; pt1 = this->getDefiningFace(0)->getDefiningPoint(3); pt2 = this->getDefiningFace(0)->getDefiningPoint(0); faceNo = 0; for (Index i=1; i<this->getNoOfFaces(); i++){ flag1 = this->definingFaces[i]->findPoint(pt1); flag2 = this->definingFaces[i]->findPoint(pt2); if (flag1 == true and flag2 == true){ faceNo = i; break; }; }; this->orderedFaces[5] = faceNo; //_____________________________________________________________________ // Now the faces have been ordered properly. Next, we order the defining points. /* // Figure: Vertices orientation and numbering 5 6 _______________________ * * | * | * | * 4 | * 7 | * ____________|________* | | | | | | | | | | | | | | | | | | | | 1 |_________|____________| 2 | * | * | * | * | * | * | *|______________________*| 0 3 */ //_______________________________________________________________________________________________________________ // The first four points are in a sequence corresponding to the 0th face. for(Index i=0; i<this->getDefiningFace(0)->getNoOfPoints(); i++){ this->orderedPoints[i] = i; }; // Next four points are the ones which are directly opposite to the first four on the opposite face of the 0th face //_____________________________________________________________________ // Point 4 is common between faces (ordered) as 1, 2 and 5 (i.e. opposite and two neighbours sharing point 0) // Remember, the orderedFaces[] array is finalized. So it will return the faces in the correct order after this point. for (Index i=0; i<this->getNoOfPoints(); i++){ Point *pt = this->definingPoints[i]; bool flag1 = false; bool flag2 = false; bool flag3 = false; flag1 = this->getDefiningFace(1)->findPoint(pt); flag2 = this->getDefiningFace(2)->findPoint(pt); flag3 = this->getDefiningFace(5)->findPoint(pt); if (flag1 == true and flag2 == true and flag3 == true){ this->orderedPoints[4] = i; }; }; //_____________________________________________________________________ // Point 5 is common between faces (ordered) as 1, 2 and 3 (i.e. opposite and two neighbours sharing point 1) // Remember, the orderedFaces[] array is finalized. So it will return the faces in the correct order after this point. for (Index i=0; i<this->getNoOfPoints(); i++){ Point *pt = this->definingPoints[i]; bool flag1 = false; bool flag2 = false; bool flag3 = false; flag1 = this->getDefiningFace(1)->findPoint(pt); flag2 = this->getDefiningFace(2)->findPoint(pt); flag3 = this->getDefiningFace(3)->findPoint(pt); if (flag1 == true and flag2 == true and flag3 == true){ this->orderedPoints[5] = i; }; }; //_____________________________________________________________________ // Point 6 is common between faces (ordered) as 1, 3 and 4 (i.e. opposite and two neighbours sharing point 2) // Remember, the orderedFaces[] array is finalized. So it will return the faces in the correct order after this point. for (Index i=0; i<this->getNoOfPoints(); i++){ Point *pt = this->definingPoints[i]; bool flag1 = false; bool flag2 = false; bool flag3 = false; flag1 = this->getDefiningFace(1)->findPoint(pt); flag2 = this->getDefiningFace(3)->findPoint(pt); flag3 = this->getDefiningFace(4)->findPoint(pt); if (flag1 == true and flag2 == true and flag3 == true){ this->orderedPoints[6] = i; }; }; //_____________________________________________________________________ // Point 7 is common between faces (ordered) as 1, 4 and 5 (i.e. opposite and two neighbours sharing point 3) // Remember, the orderedFaces[] array is finalized. So it will return the faces in the correct order after this point. for (Index i=0; i<this->getNoOfPoints(); i++){ Point *pt = this->definingPoints[i]; bool flag1 = false; bool flag2 = false; bool flag3 = false; flag1 = this->getDefiningFace(1)->findPoint(pt); flag2 = this->getDefiningFace(4)->findPoint(pt); flag3 = this->getDefiningFace(5)->findPoint(pt); if (flag1 == true and flag2 == true and flag3 == true){ this->orderedPoints[7] = i; }; }; // Also, we need to assign appropriate space for Cell::vertexSign array. // This array will be used in the shape function calculation as well as Jacobian calculation this->vertexSign.setSize(this->getNoOfPoints(), 3); // first index on defining points, second on xyz coordinates // Refer Geometry::setVertexSign() function for implementation. }; }; void Cell::setLargestFace(Face *face){ this->largestFace = face; }; Face* Cell::getLargestFace(){ return this->largestFace; }; int Cell::getNoOfBoundaryFaces(){ return this->noOfBoundaryFaces; }; void Cell::setNoOfBoundaryFaces(int NBF){ this->noOfBoundaryFaces = NBF; }; void Cell::addNoOfBoundaryFaces(int NBF){ this->noOfBoundaryFaces += NBF; }; void Cell::calculateCenter(){ double sum_x=0.0,sum_y=0.0,sum_z=0.0; for(int i=0;i<this->getNoOfPoints();i++){ sum_x += definingPoints[i]->getX(); sum_y += definingPoints[i]->getY(); sum_z += definingPoints[i]->getZ(); } center.setX( sum_x/noOfPoints); center.setY( sum_y/noOfPoints); center.setZ( sum_z/noOfPoints); center.setId(this->getId()); } Point* Cell::getCenter(){ return &this->center; }; void Cell::setReferenceCell(RefCell* refCell){ this->refCell = refCell; this->refCellFlag = true; }; RefCell* Cell::getReferenceCell(){ assert (this->refCellFlag == true && "Cell::getReferenceCell() returns error. Make sure that nDOF number is assigned.\n"); return this->refCell; }; void Cell::setNDOF(unsigned int nDOF){ this->nDOF = nDOF; this->nDOFFlag = true; }; unsigned int Cell::getNDOF()const{ assert (this->nDOFFlag == true && "Cell::getNDOF() returns error. Make sure that nDOF number is assigned.\n"); return this->nDOF; }; void Cell::setNQuad(unsigned int nQuad){ this->nQuad = nQuad; this->nQuadFlag = true; }; unsigned int Cell::getNQuad()const{ assert (this->nQuadFlag == true && "Cell::getNQuad() returns error. Make sure that nQuad number is assigned.\n"); return this->nQuad; }; TensorO1<double>* Cell::getJacobian(){ assert(this->JacobianFlag == true && "Cell::getJacobian() returns error. Make sure that the Jacobian is computed.\n"); return &this->J; }; TensorO3<double>* Cell::getInverseJacobian(){ return &this->dRST_by_dXYZ; }; void Cell::setVertexSign(int vertexNo, int coord, double sign){ this->vertexSign.setValue(vertexNo, coord, sign); }; double Cell::getVertexSign(int vertexNo, int coord){ return this->vertexSign.getValue(vertexNo, coord); }; TensorO2<double>* Cell::getVertexSignArray(){ return &this->vertexSign; }; TensorO2<double>* Cell::getQuadPointsGlobalLocation(){ return &this->quadPointsGlobalLocation; }; TensorO2<double>* Cell::getDOFPointsGlobalLocation(){ return &this->DOFPointsGlobalLocation; }; void Cell::assertVertexSigns(){ enum coord{x,y,z}; if (this->getCellType() == CellType::Hex){ assert(this->getVertexSign(0,x)== -1.0 && this->getVertexSign(0,y)== -1.0 && this->getVertexSign(0,z)== -1.0); assert(this->getVertexSign(1,x)== -1.0 && this->getVertexSign(1,y)== 1.0 && this->getVertexSign(1,z)== -1.0); assert(this->getVertexSign(2,x)== 1.0 && this->getVertexSign(2,y)== 1.0 && this->getVertexSign(2,z)== -1.0); assert(this->getVertexSign(3,x)== 1.0 && this->getVertexSign(3,y)== -1.0 && this->getVertexSign(3,z)== -1.0); assert(this->getVertexSign(4,x)== -1.0 && this->getVertexSign(4,y)== -1.0 && this->getVertexSign(4,z)== 1.0); assert(this->getVertexSign(5,x)== -1.0 && this->getVertexSign(5,y)== 1.0 && this->getVertexSign(5,z)== 1.0); assert(this->getVertexSign(6,x)== 1.0 && this->getVertexSign(6,y)== 1.0 && this->getVertexSign(6,z)== 1.0); assert(this->getVertexSign(7,x)== 1.0 && this->getVertexSign(7,y)== -1.0 && this->getVertexSign(7,z)== 1.0); }; }; void Cell::mapRSTtoXYZ3DTensor(Point* localPt, Point* globalPt){ // The shape functions are given in: http://textofvideo.nptel.ac.in/105106051/lec40.pdf, page number 8. // Check that the vertices have the correct sign this->assertVertexSigns(); // r,s,t are the coordinates in the local (cell) frame of reference, i.e. defined in the reference cell. double r = localPt->getX(); double s = localPt->getY(); double t = localPt->getZ(); // Enum coord is used for assesing vertexSigns in x or y or z direction. Refer Cell::vertexSign and GeometryIO::assignVertexSigns // for details. enum coord {x,y,z}; // XYZ is the local container for global coordinates double XYZ[3]; for (Index i=0; i<3; i++){ XYZ[i] = 0.0; }; for(Index vertex=0; vertex<this->getNoOfPoints(); vertex++){ double shape_function_i = 1.0/8.0 * (1.0 + this->getVertexSign(vertex, x) *r) * (1.0 + this->getVertexSign(vertex, y) *s) * (1.0 + this->getVertexSign(vertex, z) *t); double x_i = this->getDefiningPoint(vertex)->getX(); double y_i = this->getDefiningPoint(vertex)->getY(); double z_i = this->getDefiningPoint(vertex)->getZ(); XYZ[0] += shape_function_i * x_i; XYZ[1] += shape_function_i * y_i; XYZ[2] += shape_function_i * z_i; }; // Now the values are dumped in the global point globalPt->setX(XYZ[0]); globalPt->setY(XYZ[1]); globalPt->setZ(XYZ[2]); }; // Calculates Jacobian for hex cells // Takes r,s,t coordinates in reference cell coordinate system // returns double value of the determinant of the Jacobian at r,s,t point double Cell::calculateJacobian3DTensor(double r,double s,double t) { this->assertVertexSigns(); double J[3][3]; // set values to zero (initialization) for (Index i=0; i<3; i++){ for (Index j=0; j<3; j++){ J[i][j] = 0.0; }; }; double detJ; enum coord{x,y,z}; for(Index vertex=0; vertex<this->getNoOfPoints(); vertex++){ double signX = this->getVertexSign(vertex, x); double signY = this->getVertexSign(vertex, y); double signZ = this->getVertexSign(vertex, z); J[0][0] += signX * (1.0 + signY * s) * (1.0 + signZ * t) / 8.0 * this->getDefiningPoint(vertex)->getX(); //dx_by_dr J[0][1] += signY * (1.0 + signX * r) * (1.0 + signZ * t) / 8.0 * this->getDefiningPoint(vertex)->getX(); //dx_by_ds J[0][2] += signZ * (1.0 + signX * r) * (1.0 + signY * s) / 8.0 * this->getDefiningPoint(vertex)->getX(); //dx_by_dt J[1][0] += signX * (1.0 + signY * s) * (1.0 + signZ * t) / 8.0 * this->getDefiningPoint(vertex)->getY(); //dy_by_dr J[1][1] += signY * (1.0 + signX * r) * (1.0 + signZ * t) / 8.0 * this->getDefiningPoint(vertex)->getY(); //dy_by_ds J[1][2] += signZ * (1.0 + signX * r) * (1.0 + signY * s) / 8.0 * this->getDefiningPoint(vertex)->getY(); //dy_by_dt J[2][0] += signX * (1.0 + signY * s) * (1.0 + signZ * t) / 8.0 * this->getDefiningPoint(vertex)->getZ(); //dz_by_dr J[2][1] += signY * (1.0 + signX * r) * (1.0 + signZ * t) / 8.0 * this->getDefiningPoint(vertex)->getZ(); //dz_by_ds J[2][2] += signZ * (1.0 + signX * r) * (1.0 + signY * s) / 8.0 * this->getDefiningPoint(vertex)->getZ(); //dz_by_dt } // Direct formula for determinant detJ = J[0][0]*(J[1][1]*J[2][2]-J[1][2]*J[2][1])-J[0][1]*(J[1][0]*J[2][2]-J[1][2]*J[2][0])+J[0][2]*(J[1][0]*J[2][1]-J[1][1]*J[2][0]); return detJ; }; // Calculates inverse Jacobian for the cell (not determinant) // each term of the inverse Jacobian is a metric term for transformation // The terms are stored in an array dRST_by_dXYZ. Dim: nQuad x 3 x 3 // i.e. [ [dr/dx, dr/dy, dr/dz], // [ds/dx, ds/dy, ds/dz], // [dt/dx, dt/dy, dt/dz]] matrix for nQuad points // Takes r,s,t coordinates in reference cell coordinate system // Fills the matrix for those coordinates (i.e. quadrature point) double Cell::calculateInverseJacobianMatrix3DTensor(double r,double s,double t, Matrix<double> *dRST_by_dXYZ) { this->assertVertexSigns(); assert(dRST_by_dXYZ->getSize0() == dRST_by_dXYZ->getSize1() and dRST_by_dXYZ->getSize1()==3); double J[3][3]; // set values to zero (initialization) for (Index i=0; i<3; i++){ for (Index j=0; j<3; j++){ J[i][j] = 0.0; }; }; double detJ; enum coord{x,y,z}; for(Index vertex=0; vertex<this->getNoOfPoints(); vertex++){ double signX = this->getVertexSign(vertex, x); double signY = this->getVertexSign(vertex, y); double signZ = this->getVertexSign(vertex, z); J[0][0] += signX * (1.0 + signY * s) * (1.0 + signZ * t) / 8.0 * this->getDefiningPoint(vertex)->getX(); //dx_by_dr J[0][1] += signY * (1.0 + signX * r) * (1.0 + signZ * t) / 8.0 * this->getDefiningPoint(vertex)->getX(); //dx_by_ds J[0][2] += signZ * (1.0 + signX * r) * (1.0 + signY * s) / 8.0 * this->getDefiningPoint(vertex)->getX(); //dx_by_dt J[1][0] += signX * (1.0 + signY * s) * (1.0 + signZ * t) / 8.0 * this->getDefiningPoint(vertex)->getY(); //dy_by_dr J[1][1] += signY * (1.0 + signX * r) * (1.0 + signZ * t) / 8.0 * this->getDefiningPoint(vertex)->getY(); //dy_by_ds J[1][2] += signZ * (1.0 + signX * r) * (1.0 + signY * s) / 8.0 * this->getDefiningPoint(vertex)->getY(); //dy_by_dt J[2][0] += signX * (1.0 + signY * s) * (1.0 + signZ * t) / 8.0 * this->getDefiningPoint(vertex)->getZ(); //dz_by_dr J[2][1] += signY * (1.0 + signX * r) * (1.0 + signZ * t) / 8.0 * this->getDefiningPoint(vertex)->getZ(); //dz_by_ds J[2][2] += signZ * (1.0 + signX * r) * (1.0 + signY * s) / 8.0 * this->getDefiningPoint(vertex)->getZ(); //dz_by_dt } // Direct formula for determinant detJ = J[0][0]*(J[1][1]*J[2][2]-J[1][2]*J[2][1])-J[0][1]*(J[1][0]*J[2][2]-J[1][2]*J[2][0])+J[0][2]*(J[1][0]*J[2][1]-J[1][1]*J[2][0]); // Direct formula for the inverse of J // Refer: https://www.dr-lex.be/random/matrix-inv.html // Computing each of the Metric terms double drBydx = 1.0/detJ*( J[2][2]*J[1][1] - J[2][1]*J[1][2]) ; double drBydy = -1.0/detJ*(J[2][2]*J[0][1] - J[2][1]*J[0][2]) ; double drBydz = 1.0/detJ*( J[1][2]*J[0][1] - J[1][1]*J[0][2]) ; double dsBydx = -1.0/detJ*(J[2][2]*J[1][0] - J[2][0]*J[1][2]) ; double dsBydy = 1.0/detJ*( J[2][2]*J[0][0] - J[2][0]*J[0][2]) ; double dsBydz = -1.0/detJ*(J[1][2]*J[0][0] - J[1][0]*J[0][2]) ; double dtBydx = 1.0/detJ*( J[2][1]*J[1][0] - J[2][0]*J[1][1]) ; double dtBydy = -1.0/detJ*(J[2][1]*J[0][0] - J[2][0]*J[0][1]) ; double dtBydz = 1.0/detJ*( J[1][1]*J[0][0] - J[1][0]*J[0][1]) ; // The inverse Jacobian (i.e. metric terms for derivatives given as follows) enum IJlocal {R, S, T}; enum IJglobal {X, Y, Z}; dRST_by_dXYZ->setValue(R, X, drBydx); dRST_by_dXYZ->setValue(R, Y, drBydy); dRST_by_dXYZ->setValue(R, Z, drBydz); dRST_by_dXYZ->setValue(S, X, dsBydx); dRST_by_dXYZ->setValue(S, Y, dsBydy); dRST_by_dXYZ->setValue(S, Z, dsBydz); dRST_by_dXYZ->setValue(T, X, dtBydx); dRST_by_dXYZ->setValue(T, Y, dtBydy); dRST_by_dXYZ->setValue(T, Z, dtBydz); }; Matrix<double>* Cell::getMassMatrix(){ return &this->M; }; Matrix<double>* Cell::getInverseMassMatrix(){ return &this->MI; }; Matrix<double>* Cell::getVandermondeMatrix(){ return &this->V; }; Matrix<double>* Cell::getDxMatrix(){ return &this->Dx; }; Matrix<double>* Cell::getDyMatrix(){ return &this->Dy; }; Matrix<double>* Cell::getDzMatrix(){ return &this->Dz; }; Matrix<double>* Cell::getDtildexMatrix(){ return &this->Dtildex; }; Matrix<double>* Cell::getDtildeyMatrix(){ return &this->Dtildey; }; Matrix<double>* Cell::getDtildezMatrix(){ return &this->Dtildez; }; TensorO3<double>* Cell::getFMatrix(){ return &this->F; }; TensorO3<double>* Cell::getFtildeMatrix(){ return &this->Ftilde; }; Matrix<double>* Cell::getFilterMatrix(){ return &this->Filter; }; void Cell::resizeMatrices(unsigned int Size){ assert(nDOFFlag == true and nQuadFlag == true and this->getNoOfFaces()>0); // Re-size all the matrices and set all entries to zero // Mass matrix // Resize the matrix this->getMassMatrix()->setSize(Size); // Confirm the size assert(this->getMassMatrix()->getSize0() == this->getMassMatrix()->getSize1() and this->getMassMatrix()->getSize1() == this->getNDOF()); // Initialize with zero this->getMassMatrix()->setAll(0.0); // Inverse Mass matrix this->getInverseMassMatrix()->setSize(Size); // Confirm the size assert(this->getInverseMassMatrix()->getSize0() == this->getInverseMassMatrix()->getSize1() and this->getInverseMassMatrix()->getSize1() == this->getNDOF()); // Initialize with zero this->getInverseMassMatrix()->setAll(0.0); // Vandermonde matrix this->getVandermondeMatrix()->setSize(Size); // Confirm the size assert(this->getVandermondeMatrix()->getSize0() == this->getVandermondeMatrix()->getSize1() and this->getVandermondeMatrix()->getSize1() == this->getNDOF()); // Initialize with zero this->getVandermondeMatrix()->setAll(0.0); // Dx matrix this->getDxMatrix()->setSize(Size); // Confirm the size assert(this->getDxMatrix()->getSize0() == this->getDxMatrix()->getSize1() and this->getDxMatrix()->getSize1() == this->getNDOF()); // Initialize with zero this->getDxMatrix()->setAll(0.0); // Dy matrix this->getDyMatrix()->setSize(Size); // Confirm the size assert(this->getDyMatrix()->getSize0() == this->getDyMatrix()->getSize1() and this->getDyMatrix()->getSize1() == this->getNDOF()); // Initialize with zero this->getDyMatrix()->setAll(0.0); // Dz matrix this->getDzMatrix()->setSize(Size); // Confirm the size assert(this->getDzMatrix()->getSize0() == this->getDzMatrix()->getSize1() and this->getDzMatrix()->getSize1() == this->getNDOF()); // Initialize with zero this->getDzMatrix()->setAll(0.0); // DTildeX matrix this->getDtildexMatrix()->setSize(Size); // Confirm the size assert(this->getDtildexMatrix()->getSize0() == this->getDtildexMatrix()->getSize1() and this->getDtildexMatrix()->getSize1() == this->getNDOF()); // Initialize with zero this->getDtildexMatrix()->setAll(0.0); // DTildeY matrix this->getDtildeyMatrix()->setSize(Size); // Confirm the size assert(this->getDtildeyMatrix()->getSize0() == this->getDtildeyMatrix()->getSize1() and this->getDtildeyMatrix()->getSize1() == this->getNDOF()); // Initialize with zero this->getDtildeyMatrix()->setAll(0.0); // DTildeZ matrix this->getDtildezMatrix()->setSize(Size); // Confirm the size assert(this->getDtildezMatrix()->getSize0() == this->getDtildezMatrix()->getSize1() and this->getDtildezMatrix()->getSize1() == this->getNDOF()); // Initialize with zero this->getDtildezMatrix()->setAll(0.0); // Flux matrix this->getFMatrix()->setSize(this->getNoOfFaces(), Size, Size); // Confirm the size assert(this->getFMatrix()->getSize0() == this->getNoOfFaces() and this->getFMatrix()->getSize1() == this->getFMatrix()->getSize2() and this->getFMatrix()->getSize1() == this->getNDOF()); // Initialize with zero this->getFMatrix()->setAll(0.0); // FTilde matrix this->getFtildeMatrix()->setSize(this->getNoOfFaces(), Size, Size); // Confirm the size assert(this->getFtildeMatrix()->getSize0() == this->getNoOfFaces() and this->getFtildeMatrix()->getSize1() == this->getFtildeMatrix()->getSize2() and this->getFtildeMatrix()->getSize1() == this->getNDOF()); // Initialize with zero this->getFtildeMatrix()->setAll(0.0); // Filter matrix this->getFilterMatrix()->setSize(Size); // Confirm the size assert(this->getFilterMatrix()->getSize0() == this->getFilterMatrix()->getSize1() and this->getFilterMatrix()->getSize1() == this->getNDOF()); // Initialize with zero this->getFilterMatrix()->setAll(0.0); }; double Cell::getVariable(int rkStep, int varNo, int DOF){ return this->variable.getValue(rkStep, varNo, DOF); }; TensorO3<double>* Cell::getVariableArray(){ return &this->variable; }; TensorO2<double>* Cell::getVariableRefArray(){ return &this->variableRef; }; TensorO3<double>* Cell::getVariableResidualArray(){ return &this->variableResidual; }; TensorO2<double>* Cell::getFluxVectorx(){ return &this->fluxVectorx; }; TensorO2<double>* Cell::getFluxVectory(){ return &this->fluxVectory; }; TensorO2<double>* Cell::getFluxVectorz(){ return &this->fluxVectorz; }; TensorO3<double>* Cell::getFluxStarVector(){ return &this->fluxStarVector; }; /* Printing Functions */ //Mass matrix void Cell::printMassMatrix(){ cout <<"\nM: \n"; for (int i=0; i<nDOF; i++){ for (int j=0; j<nDOF; j++){ cout << M.getValue(i,j) << " "; }; cout << endl; }; }; void Cell::printMassMatrix(ofstream &file){ file <<"\nM: \n"; for (int i=0; i<nDOF; i++){ for (int j=0; j<nDOF; j++){ file << M.getValue(i,j) << " "; }; file << endl; }; }; void Cell::printInverseMassMatrix(){ cout <<"\nM_inv: \n"; for (int i=0; i<nDOF; i++){ for (int j=0; j<nDOF; j++){ cout << MI.getValue(i, j) << " "; }; cout << endl; }; }; void Cell::printInverseMassMatrix(ofstream &file){ file <<"\nM_inv: \n"; for (int i=0; i<nDOF; i++){ for (int j=0; j<nDOF; j++){ file << MI.getValue(i, j) << " "; }; file << endl; }; }; //Vandermonde matrix void Cell::printVandermondeMatrix(){ cout <<"\nVandermonde: \n"; for (int i=0; i<nDOF; i++){ for (int j=0; j<nDOF; j++){ cout << V.getValue(i,j) << " "; }; cout << endl; }; }; void Cell::printVandermondeMatrix(ofstream &file){ file <<"\nVandermonde: \n"; for (int i=0; i<nDOF; i++){ for (int j=0; j<nDOF; j++){ file << V.getValue(i,j) << " "; }; file << endl; }; }; //Differential matrix void Cell::printDifferentialMatrix(){ cout << "\nDx: " << endl; for (int i=0; i<nDOF; i++){ for (int j=0; j<nDOF; j++){ cout << Dx.getValue(i,j) << " "; }; cout << endl; }; cout << "\nDy: " << endl; for (int i=0; i<nDOF; i++){ for (int j=0; j<nDOF; j++){ cout << Dy.getValue(i,j) << " "; }; cout << endl; }; cout << "\nDz: " << endl; for (int i=0; i<nDOF; i++){ for (int j=0; j<nDOF; j++){ cout << Dz.getValue(i,j) << " "; }; cout << endl; }; }; //Differential matrix void Cell::printDifferentialMatrix(ofstream &file){ file << "\nDx: " << endl; for (int i=0; i<nDOF; i++){ for (int j=0; j<nDOF; j++){ file << Dx.getValue(i,j) << " "; }; file << endl; }; file << "\nDy: " << endl; for (int i=0; i<nDOF; i++){ for (int j=0; j<nDOF; j++){ file << Dy.getValue(i,j) << " "; }; file << endl; }; file << "\nDz: " << endl; for (int i=0; i<nDOF; i++){ for (int j=0; j<nDOF; j++){ file << Dz.getValue(i,j) << " "; }; file << endl; }; }; // Differential matrix multiplied with M_inv void Cell::printDTildeMatrix(){ cout << "\nDTildeX: " << endl; for (int i=0; i<nDOF; i++){ for (int j=0; j<nDOF; j++){ cout << Dtildex.getValue(i,j) << " "; }; cout << endl; }; cout << "\nDTildeY: " << endl; for (int i=0; i<nDOF; i++){ for (int j=0; j<nDOF; j++){ cout << Dtildey.getValue(i,j) << " "; }; cout << endl; }; cout << "\nDTildeZ: " << endl; for (int i=0; i<nDOF; i++){ for (int j=0; j<nDOF; j++){ cout << Dtildez.getValue(i,j) << " "; }; cout << endl; }; }; // Differential matrix multiplied with M_inv void Cell::printDTildeMatrix(ofstream &file){ file << "\nDTildeX: " << endl; for (int i=0; i<nDOF; i++){ for (int j=0; j<nDOF; j++){ file << Dtildex.getValue(i,j) << " "; }; file << endl; }; file << "\nDTildeY: " << endl; for (int i=0; i<nDOF; i++){ for (int j=0; j<nDOF; j++){ file << Dtildey.getValue(i,j) << " "; }; file << endl; }; file << "\nDTildeZ: " << endl; for (int i=0; i<nDOF; i++){ for (int j=0; j<nDOF; j++){ file << Dtildez.getValue(i,j) << " "; }; file << endl; }; }; //Flux matrix void Cell::printFluxMatrix(){ cout << "\nFlux matrix:\n"; for (int f=0; f<noOfFaces; f++){ cout << "Face: " << f << endl; for (int i=0; i<nDOF; i++){ for (int j=0; j<nDOF; j++){ cout << F.getValue(f,i,j) << " "; }; cout << endl; }; cout << endl; }; }; void Cell::printFluxMatrix(ofstream &file){ file << "\nFlux matrix:\n"; for (int f=0; f<noOfFaces; f++){ file << "Face: " << f << endl; for (int i=0; i<nDOF; i++){ for (int j=0; j<nDOF; j++){ file << F.getValue(f,i,j) << " "; }; file << endl; }; file << endl; }; }; //Flux matrix void Cell::printFTildeMatrix(){ cout << "\nF-tilde (M_inv * F) matrix:\n"; for (int f=0; f<noOfFaces; f++){ cout << "Face: " << f << endl; for (int i=0; i<nDOF; i++){ for (int j=0; j<nDOF; j++){ cout << Ftilde.getValue(f,i,j) << " "; }; cout << endl; }; cout << endl; }; }; //Flux matrix void Cell::printFTildeMatrix(ofstream &file){ file << "\nF-tilde (M_inv * F) matrix:\n"; for (int f=0; f<noOfFaces; f++){ file << "Face: " << f << endl; for (int i=0; i<nDOF; i++){ for (int j=0; j<nDOF; j++){ file << Ftilde.getValue(f,i,j) << " "; }; file << endl; }; file << endl; }; }; // Filter matrix void Cell::printFilterMatrix(){ cout <<"\nFilter Matrix: \n"; for (int i=0; i<nDOF; i++){ for (int j=0; j<nDOF; j++){ cout << Filter.getValue(i,j) << " "; }; cout << endl; }; }; void Cell::printFilterMatrix(ofstream &file){ file <<"\nFilter Matrix: \n"; for (int i=0; i<nDOF; i++){ for (int j=0; j<nDOF; j++){ file << Filter.getValue(i,j) << " "; }; file << endl; }; }; /*******************************************TESTS**************************************************/ namespace Test{ void TestCell(){ cout << "\nRunning test on class Cell... " << endl; TestCellInitialization(); TestDefiningPointsForCell(); TestDefiningFacesForCell(); cout << "Test::TestCell() passed.\n"; }; void TestCellInitialization(){ // Run the test on the dataset 1000 times using random values for (Index i=0; i<1000; i++){ int random = getRandom(-10000, 10000); Cell cell(random); int grandom = cell.getId(); assert(random == grandom && "Test::TestCellInitialization() returns error.\n"); }; }; void TestDefiningPointsForCell(){ // Run the test on the dataset 1000 times using random values for (Index i=0; i<1000; i++){ Point points[8]; int IDP[8], IDF[8]; double XP[8], XF[8]; double YP[8], YF[8]; double ZP[8], ZF[8]; int random = getRandom(-10000, 10000); Cell cell(random); int noOfPts = getRandom(4,8); if (noOfPts == 7){ noOfPts = 8; }; for (Index i=0; i<noOfPts; i++){ double x1, y1, z1; int id1; x1 = getRandom(-1000, 1000); y1 = getRandom(-1000, 1000); z1 = getRandom(-1000, 1000); id1 = getRandom(-1000, 1000); points[i].setId(id1); points[i].setX(x1); points[i].setY(y1); points[i].setZ(z1); IDP[i] = id1; XP[i] = x1; YP[i] = y1; ZP[i] = z1; cell.addDefiningPoint(&points[i]); }; int Np = cell.getNoOfPoints(); assert(Np == noOfPts && "Test::TestDefiningPoints() in Cell.cpp returns error. Cell::getNoOfPoints() returns wrong value.\n"); for (Index i=0; i<cell.getNoOfPoints(); i++){ IDF[i] = cell.getDefiningPoint(i)->getId(); XF[i] = cell.getDefiningPoint(i)->getX(); YF[i] = cell.getDefiningPoint(i)->getY(); ZF[i] = cell.getDefiningPoint(i)->getZ(); assert(IDP[i] == IDF[i] and "Test::TestDefiningPoints() in Cell.cpp returns error. Cell::getDefiningPoint() does not return the correct id.\n"); assert(XP[i] == XF[i] and YP[i] == YF[i] and ZP[i] == ZF[i] && "Test::TestDefiningPoints() in Cell.cpp returns error. Cell::getDefiningPoint() does not return the correct xyz coordinate.\n"); } // test the findPoint() method bool flag = false; flag = cell.findPoint(&points[getRandom(1,Np)]); assert(flag == true && "Test::TestDefiningPoints() in cell.cpp returns error. Function Cell::findPoint() does not work properly.\n"); Point xyz(100); flag = cell.findPoint(&xyz); assert(flag == false && "Test::TestDefiningPoints() in cell.cpp returns error. Function Cell::findPoint() does not work properly.\n"); }; }; void TestDefiningFacesForCell(){ Cell cell(getRandom(100,200)); int nfa = getRandom(4,6); cell.setNoOfFaces(nfa); int nf = cell.getNoOfFaces(); assert(nf == nfa); for (Index i=0; i<1000; i++){ Cell cell(i); int nfa = getRandom(4,6); Face *faces[nfa]; for (Index j=0; j<nfa; j++){ Face face(j); faces[j] = &face; cell.addDefiningFace(faces[j]); }; for (Index j=0; j<nfa; j++){ assert(faces[j]->getId() == cell.getDefiningFace(j)->getId()); }; // At this time, the orderedFaces array just contains numbers 0 to 8 arranged sequencially // The next routine rearranges the faces based on the correct order }; // Test for finding defining points and defining Faces for (Index i=0; i<1000; i++){ Cell cell(i); // Set 8 points with ids 0 to 7 Point *points; points = new Point[8]; for (Index j=0; j<8; j++){ points[j].setId(j); }; // Set 6 faces with ids 0 to 5 Face *faces; faces = new Face[6]; for (Index j=0; j<6; j++){ faces[j].setId(j); }; // Zeroth face gets the first four points in that sequence for (Index j=0; j<4; j++){ faces[0].addDefiningPoint(&points[j]); }; faces[0].setFaceType(); // Now create an array of numbers 0 to 5 and shuffle it (100 times) TensorO1<int> order(5); for (Index j=0; j<5; j++){ order.setValue(j,j+1); }; order.randomize(); // Now randomly arrange face ids // Face sharing points 0 and 1 with the base face faces[order.getValue(0)].addDefiningPoint(&points[0]); faces[order.getValue(0)].addDefiningPoint(&points[4]); faces[order.getValue(0)].addDefiningPoint(&points[5]); faces[order.getValue(0)].addDefiningPoint(&points[1]); faces[order.getValue(0)].setFaceType(); // Face sharing points 1 and 2 with the base face faces[order.getValue(1)].addDefiningPoint(&points[1]); faces[order.getValue(1)].addDefiningPoint(&points[5]); faces[order.getValue(1)].addDefiningPoint(&points[6]); faces[order.getValue(1)].addDefiningPoint(&points[2]); faces[order.getValue(1)].setFaceType(); // Face sharing points 2 and 3 with the base face faces[order.getValue(2)].addDefiningPoint(&points[2]); faces[order.getValue(2)].addDefiningPoint(&points[6]); faces[order.getValue(2)].addDefiningPoint(&points[7]); faces[order.getValue(2)].addDefiningPoint(&points[3]); faces[order.getValue(2)].setFaceType(); // Face sharing points 3 and 0 with the base face faces[order.getValue(3)].addDefiningPoint(&points[3]); faces[order.getValue(3)].addDefiningPoint(&points[7]); faces[order.getValue(3)].addDefiningPoint(&points[4]); faces[order.getValue(3)].addDefiningPoint(&points[0]); faces[order.getValue(3)].setFaceType(); // Face not sharing any points with the base face (i.e. top face) faces[order.getValue(4)].addDefiningPoint(&points[4]); faces[order.getValue(4)].addDefiningPoint(&points[7]); faces[order.getValue(4)].addDefiningPoint(&points[6]); faces[order.getValue(4)].addDefiningPoint(&points[5]); faces[order.getValue(4)].setFaceType(); // Now add these faces in to the cell a random order TensorO1<int> order2(5); for (Index j=0; j<5; j++){ order2.setValue(j,order.getValue(j)); }; order2.randomize(); cell.addDefiningFace(&faces[0]); cell.addDefiningFace(&faces[order2.getValue(0)]); cell.addDefiningFace(&faces[order2.getValue(1)]); cell.addDefiningFace(&faces[order2.getValue(2)]); cell.addDefiningFace(&faces[order2.getValue(3)]); cell.addDefiningFace(&faces[order2.getValue(4)]); // After all the faces are arranged, the cell is finally constructed. cell.findDefiningPoints(); assert(cell.getNoOfPoints() == 8); cell.setCellType(); //implicitly finds the order of points and faces assert(cell.getCellType() == CellType::Hex); // The final sequence of the faces should be: // Base: 0, (containing points 0 1 2 3) // Top : 1, (containing points 4 5 6 7), with 4 opposite of 0, 5 opposite of 1 etc. // Front:2, (sharing pts 0 and 1 with base) // LHS: 3, (sharing pts 1 and 2 with base) // Back: 4, (sharing pts 2 and 3 with base) // RHS: 5, (sharing pts 3 and 4 with base) assert(cell.getDefiningFace(0)->getId() == 0); assert(cell.getDefiningFace(1)->getId() == order.getValue(4)); assert(cell.getDefiningFace(2)->getId() == order.getValue(0)); assert(cell.getDefiningFace(3)->getId() == order.getValue(1)); assert(cell.getDefiningFace(4)->getId() == order.getValue(2)); assert(cell.getDefiningFace(5)->getId() == order.getValue(3)); // Next, make sure that the points are returned in the correct sequence: for (Index j=0; j<8; j++){ assert(cell.getDefiningPoint(j)->getId() == j); }; delete[] faces; delete[] points; }; }; };
// Copyright 2018, Bosch Software Innovations GmbH. // // 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 "rosbag2_cpp/info.hpp" #include <memory> #include <stdexcept> #include <string> #include "rosbag2_storage/metadata_io.hpp" #include "rosbag2_storage/storage_factory.hpp" namespace rosbag2_cpp { rosbag2_storage::BagMetadata Info::read_metadata( const std::string & uri, const std::string & storage_id) { rosbag2_storage::MetadataIo metadata_io; if (metadata_io.metadata_file_exists(uri)) { return metadata_io.read_metadata(uri); } if (!storage_id.empty()) { rosbag2_storage::StorageFactory factory; std::shared_ptr<rosbag2_storage::storage_interfaces::ReadOnlyInterface> storage; storage = factory.open_read_only(uri, storage_id); if (!storage) { throw std::runtime_error("The metadata.yaml file does not exist and the bag could not be " "opened."); } auto bag_metadata = storage->get_metadata(); return bag_metadata; } throw std::runtime_error("The metadata.yaml file does not exist. Please specify a the " "storage id of the bagfile to query it directly"); } } // namespace rosbag2_cpp
/******************************************************************************* Copyright (c) 2020, Fabio Muratore, Honda Research Institute Europe GmbH, and Technical University of Darmstadt. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Fabio Muratore, Honda Research Institute Europe GmbH, or Technical University of Darmstadt, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL FABIO MURATORE, HONDA RESEARCH INSTITUTE EUROPE GMBH, OR TECHNICAL UNIVERSITY OF DARMSTADT BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ #include "RcsSimEnv.h" #include "config/PropertySourceDict.h" #include "config/PropertySourceXml.h" #include "control/MLPPolicy.h" #include "physics/vortex_log.h" #include "util/BoxSpace.h" #include "util/type_casters.h" #include "util/pybind_dict_utils.h" #include <pybind11/stl.h> namespace py = pybind11; #include <Rcs_resourcePath.h> #include <Rcs_macros.h> #include <Rcs_MatNd.h> #include <Rcs_Vec3d.h> #include <PhysicsFactory.h> #include <SegFaultHandler.h> #include <Rcs_typedef.h> RCS_INSTALL_ERRORHANDLERS //void define_gui_classes(py::module& m); PYBIND11_MODULE(_rcsenv, m) { // define exceptions py::register_exception<Rcs::JointLimitException>(m, "JointLimitException"); // Define BoxSpace as class. It's not providing a constructor here, it's just meant to be passed to python for information py::class_<Rcs::BoxSpace>(m, "BoxSpace") .def_property_readonly("min", &Rcs::BoxSpace::getMin, py::return_value_policy::reference_internal).def_property_readonly( "max", &Rcs::BoxSpace::getMax, py::return_value_policy::reference_internal).def_property_readonly("names", []( const Rcs::BoxSpace& thiz) -> py::object { auto& names = thiz.getNames(); if (names.empty()) { return py::none(); } return py::cast(names); }); // Define simulator base class py::class_<Rcs::RcsSimEnv>(m, "RcsSimEnv").def(py::init([](py::kwargs kwargs) { // Get properties from xml or python Rcs::PropertySource* config; std::string configFileName; if (try_get(kwargs, "experimentConfigFile", configFileName)) { config = new Rcs::PropertySourceXml(configFileName.c_str()); } else { config = new Rcs::PropertySourceDict(kwargs); } // Create config object, takes ownership of property source return new Rcs::RcsSimEnv(config); }) ) .def("step", &Rcs::RcsSimEnv::step, py::arg("action"), py::arg("disturbance") = py::none(), py::call_guard<py::gil_scoped_release>()) .def("reset", [](Rcs::RcsSimEnv& self, py::object domainParam, const MatNd* initState) { Rcs::PropertySource* domainParamSource = Rcs::PropertySource::empty(); if (!domainParam.is_none()) { domainParamSource = new Rcs::PropertySourceDict(domainParam); } MatNd* result = self.reset(domainParamSource, initState); if (!domainParam.is_none()) { delete domainParamSource; } return result; }, py::arg("domainParam").none(true) = py::none(), py::arg("initState").none(true) = py::none() ) .def("render", &Rcs::RcsSimEnv::render, py::arg("mode") = "human", py::arg("close") = false) .def("toggleVideoRecording", &Rcs::RcsSimEnv::toggleVideoRecording) .def("setTransitionNoiseBuffer", &Rcs::RcsSimEnv::setTransitionNoiseBuffer) .def("saveConfigXML", [](Rcs::RcsSimEnv& self, const char* fileName) { self.getConfig()->properties->saveXML(fileName, "Experiment"); }) .def("getBodyPosition", [](Rcs::RcsSimEnv& self, const char* bodyName, const char* refBodyName, const char* refFrameName) { const RcsBody* body = RcsGraph_getBodyByName(self.getConfig()->graph, bodyName); RCHECK(body); const RcsBody* refBody = RcsGraph_getBodyByName(self.getConfig()->graph, refBodyName); const RcsBody* refFrame = RcsGraph_getBodyByName(self.getConfig()->graph, refFrameName); double I_r[3]; // Effector-fixed reference point in world coordinates Vec3d_copy(I_r, body->A_BI->org); // Transform to reference frame: ref_r = A_ref-I * (I_r - I_r_refBdy) if (refBody != NULL) { Vec3d_subSelf(I_r, refBody->A_BI->org); // I_r -= I_r_refBdy // refBody and refFrame, but they differ: refFrame_r = A_refFrame-I*I_r if ((refFrame != NULL) && (refFrame != refBody)) { Vec3d_rotateSelf(I_r, refFrame->A_BI->rot); } // refBody and refFrame are the same: refFrame_r = A_refBody-I*I_r else { Vec3d_rotateSelf(I_r, refBody->A_BI->rot); } } // No refBody, but refFrame: Rotate into refFrame coordinates else { // Rotate into refFrame if it exists if (refFrame != NULL) { Vec3d_rotateSelf(I_r, refFrame->A_BI->rot); } } MatNd* pos = NULL; pos = MatNd_create(3, 1); for (unsigned int i = 0; i < 3; i++) { MatNd_set(pos, i, 0, I_r[i]); } return pos; }, py::arg("bodyName"), py::arg("refFrameName"), py::arg("refBodyName") ) .def("getBodyExtents", [](Rcs::RcsSimEnv& self, const char* bodyName, const int shapeIdx) { const RcsBody* body = RcsGraph_getBodyByName(self.getConfig()->graph, bodyName); RCHECK(body); MatNd* extents = NULL; extents = MatNd_create(3, 1); for (unsigned int i = 0; i < 3; i++) { MatNd_set(extents, i, 0, body->shape[shapeIdx]->extents[i]); } return extents; }, py::arg("bodyName"), py::arg("shapeIdx") ) // Properties .def_property_readonly("observationSpace", &Rcs::RcsSimEnv::observationSpace) .def_property_readonly("actionSpace", &Rcs::RcsSimEnv::actionSpace) .def_property_readonly("initStateSpace", &Rcs::RcsSimEnv::initStateSpace) .def_property_readonly("domainParam", [](Rcs::RcsSimEnv& self) { // Expose the domain parameters to the Python side py::dict result; Rcs::PropertySourceDict psink(result); self.getPhysicsManager()->getValues(&psink); return result; }) .def_property_readonly("internalStateDim", &Rcs::RcsSimEnv::getInternalStateDim) .def_property_readonly("dt", [](Rcs::RcsSimEnv& self) { return self.getConfig()->dt; }) .def_property_readonly("lastAction", &Rcs::RcsSimEnv::getCurrentAction, py::return_value_policy::copy) .def_property_readonly("lastObservation", &Rcs::RcsSimEnv::getCurrentObservation, py::return_value_policy::copy); // Define ControlPolicy and MLPPolicy for tests py::class_<Rcs::ControlPolicy> controlPolicy(m, "ControlPolicy"); controlPolicy.def(py::init<Rcs::ControlPolicy* (*)(const char*, const char*)>(&Rcs::ControlPolicy::create)); controlPolicy.def("__call__", [](Rcs::ControlPolicy& self, const MatNd* input, unsigned int output_size) { MatNd* output = MatNd_create(output_size, 1); self.computeAction(output, input); return output; }); controlPolicy.def("reset", &Rcs::ControlPolicy::reset); controlPolicy.def_property_readonly_static("types", [](py::handle /* self */) { return Rcs::ControlPolicy::getTypeNames(); }); // Due to the way this class works, we don't use it in practice py::class_<Rcs::MLPPolicy>(m, "MLPPolicy", controlPolicy) .def(py::init(&Rcs::loadMLPPolicyFromXml)); // Define gui stuff if available //#ifdef GUI_AVAILABLE // define_gui_classes(m); //#endif m.def("saveExperimentParams", [](py::dict& config, const char* filename){ std::unique_ptr<Rcs::PropertySource> ps(new Rcs::PropertySourceDict(config)); ps->saveXML(filename, "Experiment"); }, py::arg("config"), py::arg("filename")); // Define some utility functions for interacting with RCS // Sets the rcs log level m.def("setLogLevel", [](int level) { RcsLogLevel = level; }); // Adds a directory to the resource path m.def("addResourcePath", [](const char* path) { return Rcs_addResourcePath(path); }); // Check if physics engine is available (can't list, unfortunately) m.def("supportsPhysicsEngine", &Rcs::PhysicsFactory::hasEngine); // Control vortex log level, setting it to warnings only by default (this avoids log spam) Rcs::setVortexLogLevel("warn"); // Allow changing it if desired m.def("setVortexLogLevel", &Rcs::setVortexLogLevel); }
#include <iostream> #include <stdexcept> #include <limits> #include "CondFormats/Serialization/interface/Equal.h" template <typename T> void same(const T &first, const T &second) { std::cout << "Same " << typeid(T).name() << std::endl; if (not cond::serialization::equal(first, second)) throw std::logic_error("Objects are not equal."); } template <typename T> void diff(const T &first, const T &second) { std::cout << "Diff " << typeid(T).name() << std::endl; if (cond::serialization::equal(first, second)) throw std::logic_error("Objects are not different."); } template <typename T> void checkFloatingPoint() { const T zero(0); const T nzero(-zero); const T first(1); const T second(2); const T inf(std::numeric_limits<T>::infinity()); const T ninf(-inf); const T qnan(std::numeric_limits<T>::quiet_NaN()); const T nqnan(-qnan); const T snan(std::numeric_limits<T>::signaling_NaN()); const T nsnan(-snan); auto positive = [](T x) { if (std::signbit(x)) throw std::logic_error("Object is not positive."); }; auto negative = [](T x) { if (not std::signbit(x)) throw std::logic_error("Object is not negative."); }; // Check if we got the signbit right positive(zero); negative(nzero); positive(first); positive(second); positive(inf); negative(ninf); positive(qnan); negative(nqnan); positive(snan); negative(nsnan); same(zero, zero); same(zero, nzero); same(first, first); diff(first, second); same(inf, inf); same(ninf, ninf); diff(inf, ninf); // see notes in SerializationEqual.h same(qnan, qnan); same(qnan, nqnan); same(qnan, snan); same(qnan, nsnan); same(nqnan, nqnan); same(nqnan, snan); same(nqnan, nsnan); same(snan, snan); same(snan, nsnan); same(nsnan, nsnan); diff(zero, first); diff(zero, inf); diff(zero, qnan); diff(first, inf); diff(first, qnan); diff(inf, qnan); } template <typename T> void checkSequence() { // empty same(T({}), T({})); // diff size diff(T({}), T({{1}, {2}, {3}})); diff(T({{1}, {2}}), T({{1}, {2}, {3}})); // same size same(T({{1}, {2}, {3}}), T({{1}, {2}, {3}})); diff(T({{1}, {2}, {3}}), T({{4}, {2}, {3}})); diff(T({{1}, {2}, {3}}), T({{1}, {4}, {3}})); diff(T({{1}, {2}, {3}}), T({{1}, {2}, {4}})); } // This applies for both ordered and unordered mappings template <typename T> void checkCommonMapping() { // empty same(T({}), T({})); // same same(T({{1, 2}, {2, 3}}), T({{1, 2}, {2, 3}})); // diff size diff(T({}), T({{1, 2}, {2, 3}})); diff(T({{1, 2}}), T({{1, 2}, {2, 3}})); // diff keys diff(T({{1, 2}, {2, 3}}), T({{2, 2}, {2, 3}})); diff(T({{1, 2}, {2, 3}}), T({{1, 2}, {3, 3}})); // diff values diff(T({{1, 2}, {2, 3}}), T({{1, 3}, {2, 3}})); diff(T({{1, 2}, {2, 3}}), T({{1, 2}, {2, 4}})); } int main() { // integral same(false, false); diff(false, true); same('1', '1'); diff('1', '2'); same(static_cast<unsigned char>('1'), static_cast<unsigned char>('1')); diff(static_cast<unsigned char>('1'), static_cast<unsigned char>('2')); same(L'1', L'1'); diff(L'1', L'2'); same(u'1', u'1'); diff(u'1', u'2'); same(U'1', U'1'); diff(U'1', U'2'); same(static_cast<short>(1), static_cast<short>(1)); diff(static_cast<short>(1), static_cast<short>(2)); same(static_cast<unsigned short>(1), static_cast<unsigned short>(1)); diff(static_cast<unsigned short>(1), static_cast<unsigned short>(2)); same(1, 1); diff(1, 2); same(1u, 1u); diff(1u, 2u); same(1l, 1l); diff(1l, 2l); same(1ul, 1ul); diff(1ul, 2ul); same(1ll, 1ll); diff(1ll, 2ll); same(1ull, 1ull); diff(1ull, 2ull); // enum enum enums { enum1, enum2 }; same(enum1, enum1); diff(enum1, enum2); // floating point checkFloatingPoint<float>(); checkFloatingPoint<double>(); checkFloatingPoint<long double>(); // string same(std::string("hi"), std::string("hi")); diff(std::string("hi"), std::string("hj")); diff(std::string("hi"), std::string("hi2")); // bitset same(std::bitset<3>("101"), std::bitset<3>("101")); diff(std::bitset<3>("101"), std::bitset<3>("001")); diff(std::bitset<3>("101"), std::bitset<3>("111")); diff(std::bitset<3>("101"), std::bitset<3>("100")); // pair same(std::make_pair(1, '1'), std::make_pair(1, '1')); diff(std::make_pair(1, '1'), std::make_pair(2, '1')); diff(std::make_pair(1, '1'), std::make_pair(1, '2')); // tuple same(std::make_tuple(1, '1', 1.f), std::make_tuple(1, '1', 1.f)); diff(std::make_tuple(1, '1', 1.f), std::make_tuple(2, '1', 1.f)); diff(std::make_tuple(1, '1', 1.f), std::make_tuple(1, '2', 1.f)); diff(std::make_tuple(1, '1', 1.f), std::make_tuple(1, '1', 2.f)); // pointer int i1 = 1, i1b = 1, i2 = 2; int *pi1 = &i1, *pi1b = &i1b, *pi2 = &i2, *pin = nullptr; same(pi1, pi1); // same addr same(pi1, pi1b); // diff addr, same value diff(pi1, pi2); // diff addr, diff value same(pin, pin); // nullptr, same diff(pin, pi1); // nullptr, diff, avoid dereferenciation, first diff(pi1, pin); // nullptr, diff, avoid dereferenciation, second std::unique_ptr<int> ui1(pi1), u2i1(pi1), ui1b(pi1b), ui2(pi2), uin(pin); same(ui1, ui1); same(ui1, u2i1); // diff object, same addr (even if it should not happen) same(ui1, ui1b); diff(ui1, ui2); same(uin, uin); diff(uin, ui1); diff(ui1, uin); ui1.release(); u2i1.release(); ui1b.release(); ui2.release(); uin.release(); auto deleter = [](int *) {}; std::shared_ptr<int> si1(pi1, deleter), s2i1(pi1, deleter), si1b(pi1b, deleter), si2(pi2, deleter), sin(pin, deleter); same(si1, si1); same(si1, s2i1); // diff object, same addr (may happen since it is a shared_ptr) same(si1, si1b); diff(si1, si2); same(sin, sin); diff(sin, si1); diff(si1, sin); si1.reset(); s2i1.reset(); si1b.reset(); si2.reset(); sin.reset(); boost::shared_ptr<int> bsi1(pi1, deleter), bs2i1(pi1, deleter), bsi1b(pi1b, deleter), bsi2(pi2, deleter), bsin(pin, deleter); same(bsi1, bsi1); same(bsi1, bs2i1); // diff object, same addr (may happen since it is a shared_ptr) same(bsi1, bsi1b); diff(bsi1, bsi2); same(bsin, bsin); diff(bsin, bsi1); diff(bsi1, bsin); bsi1.reset(); bs2i1.reset(); bsi1b.reset(); bsi2.reset(); bsin.reset(); // C-style array int a123[] = {1, 2, 3}, a123b[] = {1, 2, 3}, a223[] = {2, 2, 3}, a133[] = {1, 3, 3}, a124[] = {1, 2, 4}; same(a123, a123); same(a123, a123b); diff(a123, a223); diff(a123, a133); diff(a123, a124); same("hi", "hi"); diff("hi", "hj"); // array same(std::array<int, 3>{{1, 2, 3}}, std::array<int, 3>{{1, 2, 3}}); diff(std::array<int, 3>{{1, 2, 3}}, std::array<int, 3>{{2, 2, 3}}); diff(std::array<int, 3>{{1, 2, 3}}, std::array<int, 3>{{1, 3, 3}}); diff(std::array<int, 3>{{1, 2, 3}}, std::array<int, 3>{{1, 2, 4}}); // sequence checkSequence<std::vector<int>>(); checkSequence<std::deque<int>>(); checkSequence<std::forward_list<int>>(); checkSequence<std::list<int>>(); checkSequence<std::set<int>>(); checkSequence<std::multiset<int>>(); // mapping checkCommonMapping<std::map<int, int>>(); // unordered mapping checkCommonMapping<std::unordered_map<int, int>>(); return 0; }
/* * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <osquery/core.h> #include <osquery/tables.h> namespace osquery { namespace tables { QueryData genArpCache() { QueryData results; throw std::domain_error("Table not implemented for FreeBSD"); return results; } QueryData genRoutes() { QueryData results; throw std::domain_error("Table not implemented for FreeBSD"); return results; } } }
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "cc/output/compositor_frame.h" #include "cc/quads/render_pass.h" #include "cc/quads/solid_color_draw_quad.h" #include "cc/quads/surface_draw_quad.h" #include "cc/surfaces/surface.h" #include "cc/surfaces/surface_aggregator.h" #include "cc/surfaces/surface_factory.h" #include "cc/surfaces/surface_factory_client.h" #include "cc/surfaces/surface_id_allocator.h" #include "cc/surfaces/surface_manager.h" #include "cc/test/pixel_comparator.h" #include "cc/test/pixel_test.h" #include "testing/gtest/include/gtest/gtest.h" #if !defined(OS_ANDROID) namespace cc { namespace { static constexpr FrameSinkId kArbitraryFrameSinkId(1, 1); class EmptySurfaceFactoryClient : public SurfaceFactoryClient { public: void ReturnResources(const ReturnedResourceArray& resources) override {} void SetBeginFrameSource(BeginFrameSource* begin_frame_source) override {} }; class SurfacesPixelTest : public RendererPixelTest<GLRenderer> { public: SurfacesPixelTest() : factory_(kArbitraryFrameSinkId, &manager_, &client_) {} protected: SurfaceManager manager_; SurfaceIdAllocator allocator_; EmptySurfaceFactoryClient client_; SurfaceFactory factory_; }; SharedQuadState* CreateAndAppendTestSharedQuadState( RenderPass* render_pass, const gfx::Transform& transform, const gfx::Size& size) { const gfx::Size layer_bounds = size; const gfx::Rect visible_layer_rect = gfx::Rect(size); const gfx::Rect clip_rect = gfx::Rect(size); bool is_clipped = false; float opacity = 1.f; const SkXfermode::Mode blend_mode = SkXfermode::kSrcOver_Mode; SharedQuadState* shared_state = render_pass->CreateAndAppendSharedQuadState(); shared_state->SetAll(transform, layer_bounds, visible_layer_rect, clip_rect, is_clipped, opacity, blend_mode, 0); return shared_state; } // Draws a very simple frame with no surface references. TEST_F(SurfacesPixelTest, DrawSimpleFrame) { gfx::Rect rect(device_viewport_size_); RenderPassId id(1, 1); std::unique_ptr<RenderPass> pass = RenderPass::Create(); pass->SetNew(id, rect, rect, gfx::Transform()); CreateAndAppendTestSharedQuadState( pass.get(), gfx::Transform(), device_viewport_size_); SolidColorDrawQuad* color_quad = pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); bool force_anti_aliasing_off = false; color_quad->SetNew(pass->shared_quad_state_list.back(), rect, rect, SK_ColorGREEN, force_anti_aliasing_off); std::unique_ptr<DelegatedFrameData> delegated_frame_data( new DelegatedFrameData); delegated_frame_data->render_pass_list.push_back(std::move(pass)); CompositorFrame root_frame; root_frame.delegated_frame_data = std::move(delegated_frame_data); LocalFrameId root_local_frame_id = allocator_.GenerateId(); SurfaceId root_surface_id(factory_.frame_sink_id(), root_local_frame_id); factory_.Create(root_local_frame_id); factory_.SubmitCompositorFrame(root_local_frame_id, std::move(root_frame), SurfaceFactory::DrawCallback()); SurfaceAggregator aggregator(&manager_, resource_provider_.get(), true); CompositorFrame aggregated_frame = aggregator.Aggregate(root_surface_id); factory_.Destroy(root_local_frame_id); bool discard_alpha = false; ExactPixelComparator pixel_comparator(discard_alpha); RenderPassList* pass_list = &aggregated_frame.delegated_frame_data->render_pass_list; EXPECT_TRUE(RunPixelTest(pass_list, base::FilePath(FILE_PATH_LITERAL("green.png")), pixel_comparator)); } // Draws a frame with simple surface embedding. TEST_F(SurfacesPixelTest, DrawSimpleAggregatedFrame) { gfx::Size child_size(200, 100); LocalFrameId child_local_frame_id = allocator_.GenerateId(); SurfaceId child_surface_id(factory_.frame_sink_id(), child_local_frame_id); LocalFrameId root_local_frame_id = allocator_.GenerateId(); SurfaceId root_surface_id(factory_.frame_sink_id(), root_local_frame_id); factory_.Create(child_local_frame_id); factory_.Create(root_local_frame_id); { gfx::Rect rect(device_viewport_size_); RenderPassId id(1, 1); std::unique_ptr<RenderPass> pass = RenderPass::Create(); pass->SetNew(id, rect, rect, gfx::Transform()); CreateAndAppendTestSharedQuadState( pass.get(), gfx::Transform(), device_viewport_size_); SurfaceDrawQuad* surface_quad = pass->CreateAndAppendDrawQuad<SurfaceDrawQuad>(); surface_quad->SetNew(pass->shared_quad_state_list.back(), gfx::Rect(child_size), gfx::Rect(child_size), child_surface_id); SolidColorDrawQuad* color_quad = pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); bool force_anti_aliasing_off = false; color_quad->SetNew(pass->shared_quad_state_list.back(), rect, rect, SK_ColorYELLOW, force_anti_aliasing_off); std::unique_ptr<DelegatedFrameData> delegated_frame_data( new DelegatedFrameData); delegated_frame_data->render_pass_list.push_back(std::move(pass)); CompositorFrame root_frame; root_frame.delegated_frame_data = std::move(delegated_frame_data); factory_.SubmitCompositorFrame(root_local_frame_id, std::move(root_frame), SurfaceFactory::DrawCallback()); } { gfx::Rect rect(child_size); RenderPassId id(1, 1); std::unique_ptr<RenderPass> pass = RenderPass::Create(); pass->SetNew(id, rect, rect, gfx::Transform()); CreateAndAppendTestSharedQuadState( pass.get(), gfx::Transform(), child_size); SolidColorDrawQuad* color_quad = pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); bool force_anti_aliasing_off = false; color_quad->SetNew(pass->shared_quad_state_list.back(), rect, rect, SK_ColorBLUE, force_anti_aliasing_off); std::unique_ptr<DelegatedFrameData> delegated_frame_data( new DelegatedFrameData); delegated_frame_data->render_pass_list.push_back(std::move(pass)); CompositorFrame child_frame; child_frame.delegated_frame_data = std::move(delegated_frame_data); factory_.SubmitCompositorFrame(child_local_frame_id, std::move(child_frame), SurfaceFactory::DrawCallback()); } SurfaceAggregator aggregator(&manager_, resource_provider_.get(), true); CompositorFrame aggregated_frame = aggregator.Aggregate(root_surface_id); bool discard_alpha = false; ExactPixelComparator pixel_comparator(discard_alpha); RenderPassList* pass_list = &aggregated_frame.delegated_frame_data->render_pass_list; EXPECT_TRUE(RunPixelTest(pass_list, base::FilePath(FILE_PATH_LITERAL("blue_yellow.png")), pixel_comparator)); factory_.Destroy(root_local_frame_id); factory_.Destroy(child_local_frame_id); } // Tests a surface quad that has a non-identity transform into its pass. TEST_F(SurfacesPixelTest, DrawAggregatedFrameWithSurfaceTransforms) { gfx::Size child_size(100, 200); gfx::Size quad_size(100, 100); // Structure: // root (200x200) -> left_child (100x200 @ 0x0, // right_child (100x200 @ 0x100) // left_child -> top_green_quad (100x100 @ 0x0), // bottom_blue_quad (100x100 @ 0x100) // right_child -> top_blue_quad (100x100 @ 0x0), // bottom_green_quad (100x100 @ 0x100) LocalFrameId left_child_local_id = allocator_.GenerateId(); SurfaceId left_child_id(factory_.frame_sink_id(), left_child_local_id); LocalFrameId right_child_local_id = allocator_.GenerateId(); SurfaceId right_child_id(factory_.frame_sink_id(), right_child_local_id); LocalFrameId root_local_frame_id = allocator_.GenerateId(); SurfaceId root_surface_id(factory_.frame_sink_id(), root_local_frame_id); factory_.Create(left_child_local_id); factory_.Create(right_child_local_id); factory_.Create(root_local_frame_id); { gfx::Rect rect(device_viewport_size_); RenderPassId id(1, 1); std::unique_ptr<RenderPass> pass = RenderPass::Create(); pass->SetNew(id, rect, rect, gfx::Transform()); gfx::Transform surface_transform; CreateAndAppendTestSharedQuadState( pass.get(), surface_transform, device_viewport_size_); SurfaceDrawQuad* left_surface_quad = pass->CreateAndAppendDrawQuad<SurfaceDrawQuad>(); left_surface_quad->SetNew(pass->shared_quad_state_list.back(), gfx::Rect(child_size), gfx::Rect(child_size), left_child_id); surface_transform.Translate(100, 0); CreateAndAppendTestSharedQuadState( pass.get(), surface_transform, device_viewport_size_); SurfaceDrawQuad* right_surface_quad = pass->CreateAndAppendDrawQuad<SurfaceDrawQuad>(); right_surface_quad->SetNew(pass->shared_quad_state_list.back(), gfx::Rect(child_size), gfx::Rect(child_size), right_child_id); std::unique_ptr<DelegatedFrameData> delegated_frame_data( new DelegatedFrameData); delegated_frame_data->render_pass_list.push_back(std::move(pass)); CompositorFrame root_frame; root_frame.delegated_frame_data = std::move(delegated_frame_data); factory_.SubmitCompositorFrame(root_local_frame_id, std::move(root_frame), SurfaceFactory::DrawCallback()); } { gfx::Rect rect(child_size); RenderPassId id(1, 1); std::unique_ptr<RenderPass> pass = RenderPass::Create(); pass->SetNew(id, rect, rect, gfx::Transform()); CreateAndAppendTestSharedQuadState( pass.get(), gfx::Transform(), child_size); SolidColorDrawQuad* top_color_quad = pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); bool force_anti_aliasing_off = false; top_color_quad->SetNew(pass->shared_quad_state_list.back(), gfx::Rect(quad_size), gfx::Rect(quad_size), SK_ColorGREEN, force_anti_aliasing_off); SolidColorDrawQuad* bottom_color_quad = pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); bottom_color_quad->SetNew(pass->shared_quad_state_list.back(), gfx::Rect(0, 100, 100, 100), gfx::Rect(0, 100, 100, 100), SK_ColorBLUE, force_anti_aliasing_off); std::unique_ptr<DelegatedFrameData> delegated_frame_data( new DelegatedFrameData); delegated_frame_data->render_pass_list.push_back(std::move(pass)); CompositorFrame child_frame; child_frame.delegated_frame_data = std::move(delegated_frame_data); factory_.SubmitCompositorFrame(left_child_local_id, std::move(child_frame), SurfaceFactory::DrawCallback()); } { gfx::Rect rect(child_size); RenderPassId id(1, 1); std::unique_ptr<RenderPass> pass = RenderPass::Create(); pass->SetNew(id, rect, rect, gfx::Transform()); CreateAndAppendTestSharedQuadState( pass.get(), gfx::Transform(), child_size); SolidColorDrawQuad* top_color_quad = pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); bool force_anti_aliasing_off = false; top_color_quad->SetNew(pass->shared_quad_state_list.back(), gfx::Rect(quad_size), gfx::Rect(quad_size), SK_ColorBLUE, force_anti_aliasing_off); SolidColorDrawQuad* bottom_color_quad = pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); bottom_color_quad->SetNew(pass->shared_quad_state_list.back(), gfx::Rect(0, 100, 100, 100), gfx::Rect(0, 100, 100, 100), SK_ColorGREEN, force_anti_aliasing_off); std::unique_ptr<DelegatedFrameData> delegated_frame_data( new DelegatedFrameData); delegated_frame_data->render_pass_list.push_back(std::move(pass)); CompositorFrame child_frame; child_frame.delegated_frame_data = std::move(delegated_frame_data); factory_.SubmitCompositorFrame(right_child_local_id, std::move(child_frame), SurfaceFactory::DrawCallback()); } SurfaceAggregator aggregator(&manager_, resource_provider_.get(), true); CompositorFrame aggregated_frame = aggregator.Aggregate(root_surface_id); bool discard_alpha = false; ExactPixelComparator pixel_comparator(discard_alpha); RenderPassList* pass_list = &aggregated_frame.delegated_frame_data->render_pass_list; EXPECT_TRUE(RunPixelTest( pass_list, base::FilePath(FILE_PATH_LITERAL("four_blue_green_checkers.png")), pixel_comparator)); factory_.Destroy(root_local_frame_id); factory_.Destroy(left_child_local_id); factory_.Destroy(right_child_local_id); } } // namespace } // namespace cc #endif // !defined(OS_ANDROID)
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/payments/content/utility/payment_manifest_parser.h" #include "base/json/json_reader.h" #include "base/strings/string_util.h" #include "components/payments/core/error_logger.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" #include "url/origin.h" namespace payments { namespace { // Payment method manifest parsing: void ExpectUnableToParsePaymentMethodManifest(const std::string& input) { std::vector<GURL> actual_web_app_urls; std::vector<url::Origin> actual_supported_origins; std::unique_ptr<base::Value> value = base::JSONReader::ReadDeprecated(input); PaymentManifestParser::ParsePaymentMethodManifestIntoVectors( GURL("https://bobpay.com/pmm.json"), std::move(value), ErrorLogger(), &actual_web_app_urls, &actual_supported_origins); EXPECT_TRUE(actual_web_app_urls.empty()) << actual_web_app_urls.front(); EXPECT_TRUE(actual_supported_origins.empty()) << actual_supported_origins.front(); } void ExpectParsedPaymentMethodManifest( const std::string& input, const std::vector<GURL>& expected_web_app_urls, const std::vector<url::Origin>& expected_supported_origins) { std::vector<GURL> actual_web_app_urls; std::vector<url::Origin> actual_supported_origins; std::unique_ptr<base::Value> value = base::JSONReader::ReadDeprecated(input); PaymentManifestParser::ParsePaymentMethodManifestIntoVectors( GURL("https://bobpay.com/pmm.json"), std::move(value), ErrorLogger(), &actual_web_app_urls, &actual_supported_origins); EXPECT_EQ(expected_web_app_urls, actual_web_app_urls); EXPECT_EQ(expected_supported_origins, actual_supported_origins); } TEST(PaymentManifestParserTest, NullPaymentMethodManifestIsMalformed) { ExpectUnableToParsePaymentMethodManifest(std::string()); } TEST(PaymentManifestParserTest, NonJsonPaymentMethodManifestIsMalformed) { ExpectUnableToParsePaymentMethodManifest("this is not json"); } TEST(PaymentManifestParserTest, StringPaymentMethodManifestIsMalformed) { ExpectUnableToParsePaymentMethodManifest("\"this is a string\""); } TEST(PaymentManifestParserTest, EmptyDictionaryPaymentMethodManifestIsMalformed) { ExpectUnableToParsePaymentMethodManifest("{}"); } TEST(PaymentManifestParserTest, NullDefaultApplicationIsMalformed) { ExpectUnableToParsePaymentMethodManifest("{\"default_applications\": null}"); } TEST(PaymentManifestParserTest, NumberDefaultApplicationIsMalformed) { ExpectUnableToParsePaymentMethodManifest("{\"default_applications\": 0}"); } TEST(PaymentManifestParserTest, ListOfNumbersDefaultApplicationIsMalformed) { ExpectUnableToParsePaymentMethodManifest("{\"default_applications\": [0]}"); } TEST(PaymentManifestParserTest, EmptyListOfDefaultApplicationsIsMalformed) { ExpectUnableToParsePaymentMethodManifest("{\"default_applications\": []}"); } TEST(PaymentManifestParserTest, ListOfEmptyDefaultApplicationsIsMalformed) { ExpectUnableToParsePaymentMethodManifest( "{\"default_applications\": [\"\"]}"); } TEST(PaymentManifestParserTest, DefaultApplicationCanBeRelativeURL) { ExpectParsedPaymentMethodManifest( "{\"default_applications\": [\"manifest.json\"]}", {GURL("https://bobpay.com/manifest.json")}, {}); } TEST(PaymentManifestParserTest, DefaultApplicationsShouldNotHaveNulCharacters) { ExpectUnableToParsePaymentMethodManifest( "{\"default_applications\": [\"https://bobpay.com/app\0json\"]}"); } TEST(PaymentManifestParserTest, DefaultApplicationsShouldBeUTF8) { ExpectUnableToParsePaymentMethodManifest( "{\"default_applications\":[\"https://b\x0f\x7f\xf0\xff!\"]}"); } TEST(PaymentManifestParserTest, DefaultApplicationKeyShouldBeLowercase) { ExpectUnableToParsePaymentMethodManifest( "{\"Default_Applications\": [\"https://bobpay.com/app.json\"]}"); } TEST(PaymentManifestParserTest, DefaultApplicationsCanBeEitherAbsoluteOrRelative) { ExpectParsedPaymentMethodManifest( "{\"default_applications\": [" "\"https://bobpay.com/app1.json\"," "\"app2.json\"]}", {GURL("https://bobpay.com/app1.json"), GURL("https://bobpay.com/app2.json")}, {}); } TEST(PaymentManifestParserTest, DefaultApplicationsShouldBeHttps) { ExpectUnableToParsePaymentMethodManifest( "{\"default_applications\": [" "\"https://bobpay.com/app.json\"," "\"http://alicepay.com/app.json\"]}"); } TEST(PaymentManifestParserTest, NullSupportedOriginsIsMalformed) { ExpectUnableToParsePaymentMethodManifest("{\"supported_origins\": null}"); } TEST(PaymentManifestParserTest, NumberSupportedOriginsIsMalformed) { ExpectUnableToParsePaymentMethodManifest("{\"supported_origins\": 0}"); } TEST(PaymentManifestParserTest, EmptyListSupportedOriginsIsMalformed) { ExpectUnableToParsePaymentMethodManifest("{\"supported_origins\": []}"); } TEST(PaymentManifestParserTest, ListOfNumbersSupportedOriginsIsMalformed) { ExpectUnableToParsePaymentMethodManifest("{\"supported_origins\": [0]}"); } TEST(PaymentManifestParserTest, ListOfEmptySupportedOriginsIsMalformed) { ExpectUnableToParsePaymentMethodManifest("{\"supported_origins\": [\"\"]}"); } TEST(PaymentManifestParserTest, SupportedOriginsShouldNotHaveNulCharacters) { ExpectUnableToParsePaymentMethodManifest( "{\"supported_origins\": [\"https://bob\0pay.com\"]}"); } TEST(PaymentManifestParserTest, SupportedOriginsShouldBeUTF8) { ExpectUnableToParsePaymentMethodManifest( "{\"supported_origins\":[\"https://b\x0f\x7f\xf0\xff!\"]}"); } TEST(PaymentManifestParserTest, SupportedOriginsShouldBeHttps) { ExpectUnableToParsePaymentMethodManifest( "{\"supported_origins\": [\"http://bobpay.com\"]}"); } TEST(PaymentManifestParserTest, SupportedOriginsShouldNotHavePath) { ExpectUnableToParsePaymentMethodManifest( "{\"supported_origins\": [\"https://bobpay.com/webpay\"]}"); } TEST(PaymentManifestParserTest, SupportedOriginsShouldNotHaveQuery) { ExpectUnableToParsePaymentMethodManifest( "{\"supported_origins\": [\"https://bobpay.com/?action=webpay\"]}"); } TEST(PaymentManifestParserTest, SupportedOriginsShouldNotHaveRef) { ExpectUnableToParsePaymentMethodManifest( "{\"supported_origins\": [\"https://bobpay.com/#webpay\"]}"); } TEST(PaymentManifestParserTest, SupportedOriginsShouldBeList) { ExpectUnableToParsePaymentMethodManifest( "{\"supported_origins\": \"https://bobpay.com\"}"); } TEST(PaymentManifestParserTest, WellFormedPaymentMethodManifestWithApps) { ExpectParsedPaymentMethodManifest( "{\"default_applications\": [" "\"https://bobpay.com/app.json\"," "\"https://alicepay.com/app.json\"]}", {GURL("https://bobpay.com/app.json"), GURL("https://alicepay.com/app.json")}, std::vector<url::Origin>()); } TEST(PaymentManifestParserTest, WellFormedPaymentMethodManifestWithHttpLocalhostApps) { ExpectParsedPaymentMethodManifest( "{\"default_applications\": [" "\"http://127.0.0.1:8080/app.json\"," "\"http://localhost:8081/app.json\"]}", {GURL("http://127.0.0.1:8080/app.json"), GURL("http://localhost:8081/app.json")}, std::vector<url::Origin>()); } TEST(PaymentManifestParserTest, InvalidPaymentMethodManifestWithAppsAndAllSupportedOrigins) { ExpectUnableToParsePaymentMethodManifest( "{\"default_applications\": [\"https://bobpay.com/app.json\", " "\"https://alicepay.com/app.json\"], \"supported_origins\": \"*\"}"); } TEST(PaymentManifestParserTest, OriginWildcardNotSupported) { ExpectUnableToParsePaymentMethodManifest("{\"supported_origins\": \"*\"}"); } TEST(PaymentManifestParserTest, InvalidDefaultAppsWillPreventParsingSupportedOrigins) { ExpectUnableToParsePaymentMethodManifest( "{\"default_applications\": [\"http://bobpay.com/app.json\"]}"); } TEST(PaymentManifestParserTest, InvalidSupportedOriginsWillPreventParsingDefaultApps) { ExpectUnableToParsePaymentMethodManifest( "{\"default_applications\": [\"https://bobpay.com/app.json\"], " "\"supported_origins\": \"+\"}"); } TEST(PaymentManifestParserTest, WellFormedPaymentMethodManifestWithAppsAndSomeSupportedOrigins) { ExpectParsedPaymentMethodManifest( "{\"default_applications\": [\"https://bobpay.com/app.json\", " "\"https://alicepay.com/app.json\"], \"supported_origins\": " "[\"https://charliepay.com\", \"https://evepay.com\"]}", {GURL("https://bobpay.com/app.json"), GURL("https://alicepay.com/app.json")}, {url::Origin::Create(GURL("https://charliepay.com")), url::Origin::Create(GURL("https://evepay.com"))}); } TEST(PaymentManifestParserTest, WellFormedPaymentMethodManifestWithHttpLocalhostSupportedOrigins) { ExpectParsedPaymentMethodManifest( "{\"supported_origins\": [\"http://localhost:8080\", " "\"http://127.0.0.1:8081\"]}", std::vector<GURL>(), {url::Origin::Create(GURL("http://localhost:8080")), url::Origin::Create(GURL("http://127.0.0.1:8081"))}); } TEST(PaymentManifestParserTest, WellFormedPaymentMethodManifestWithSomeSupportedOrigins) { ExpectParsedPaymentMethodManifest( "{\"supported_origins\": [\"https://charliepay.com\", " "\"https://evepay.com\"]}", std::vector<GURL>(), {url::Origin::Create(GURL("https://charliepay.com")), url::Origin::Create(GURL("https://evepay.com"))}); } TEST(PaymentManifestParserTest, WellFormedPaymentMethodManifestWithAllSupportedOrigins) { ExpectParsedPaymentMethodManifest("{\"supported_origins\": \"*\"}", std::vector<GURL>(), std::vector<url::Origin>()); } // Web app manifest parsing: void ExpectUnableToParseWebAppManifest(const std::string& input) { std::unique_ptr<base::Value> value = base::JSONReader::ReadDeprecated(input); std::vector<WebAppManifestSection> sections; PaymentManifestParser::ParseWebAppManifestIntoVector( std::move(value), ErrorLogger(), &sections); EXPECT_TRUE(sections.empty()); } void ExpectParsedWebAppManifest( const std::string& input, const std::string& expected_id, int64_t expected_min_version, const std::vector<std::vector<uint8_t>>& expected_fingerprints) { std::unique_ptr<base::Value> value = base::JSONReader::ReadDeprecated(input); std::vector<WebAppManifestSection> sections; EXPECT_TRUE(PaymentManifestParser::ParseWebAppManifestIntoVector( std::move(value), ErrorLogger(), &sections)); ASSERT_EQ(1U, sections.size()); EXPECT_EQ(expected_id, sections.front().id); EXPECT_EQ(expected_min_version, sections.front().min_version); EXPECT_EQ(expected_fingerprints, sections.front().fingerprints); } TEST(PaymentManifestParserTest, NullContentIsMalformed) { ExpectUnableToParseWebAppManifest(std::string()); } TEST(PaymentManifestParserTest, NonJsonContentIsMalformed) { ExpectUnableToParseWebAppManifest("this is not json"); } TEST(PaymentManifestParserTest, StringContentIsMalformed) { ExpectUnableToParseWebAppManifest("\"this is a string\""); } TEST(PaymentManifestParserTest, EmptyDictionaryIsMalformed) { ExpectUnableToParseWebAppManifest("{}"); } TEST(PaymentManifestParserTest, NullRelatedApplicationsSectionIsMalformed) { ExpectUnableToParseWebAppManifest("{\"related_applications\": null}"); } TEST(PaymentManifestParserTest, NumberRelatedApplicationsectionIsMalformed) { ExpectUnableToParseWebAppManifest("{\"related_applications\": 0}"); } TEST(PaymentManifestParserTest, ListOfNumbersRelatedApplicationsSectionIsMalformed) { ExpectUnableToParseWebAppManifest("{\"related_applications\": [0]}"); } TEST(PaymentManifestParserTest, ListOfEmptyDictionariesRelatedApplicationsSectionIsMalformed) { ExpectUnableToParseWebAppManifest("{\"related_applications\": [{}]}"); } TEST(PaymentManifestParserTest, NoPlayPlatformIsMalformed) { ExpectUnableToParseWebAppManifest( "{" " \"related_applications\": [{" " \"id\": \"com.bobpay.app\", " " \"min_version\": \"1\", " " \"fingerprints\": [{" " \"type\": \"sha256_cert\", " " \"value\": \"00:01:02:03:04:05:06:07:08:09:A0:A1:A2:A3:A4:A5:A6:A7" ":A8:A9:B0:B1:B2:B3:B4:B5:B6:B7:B8:B9:C0:C1\"" " }]" " }]" "}"); } TEST(PaymentManifestParserTest, NoPackageNameIsMalformed) { ExpectUnableToParseWebAppManifest( "{" " \"related_applications\": [{" " \"platform\": \"play\", " " \"min_version\": \"1\", " " \"fingerprints\": [{" " \"type\": \"sha256_cert\", " " \"value\": \"00:01:02:03:04:05:06:07:08:09:A0:A1:A2:A3:A4:A5:A6:A7" ":A8:A9:B0:B1:B2:B3:B4:B5:B6:B7:B8:B9:C0:C1\"" " }]" " }]" "}"); } TEST(PaymentManifestParserTest, NoVersionIsMalformed) { ExpectUnableToParseWebAppManifest( "{" " \"related_applications\": [{" " \"platform\": \"play\", " " \"id\": \"com.bobpay.app\", " " \"fingerprints\": [{" " \"type\": \"sha256_cert\", " " \"value\": \"00:01:02:03:04:05:06:07:08:09:A0:A1:A2:A3:A4:A5:A6:A7" ":A8:A9:B0:B1:B2:B3:B4:B5:B6:B7:B8:B9:C0:C1\"" " }]" " }]" "}"); } TEST(PaymentManifestParserTest, NoFingerprintIsMalformed) { ExpectUnableToParseWebAppManifest( "{" " \"related_applications\": [{" " \"platform\": \"play\", " " \"id\": \"com.bobpay.app\", " " \"min_version\": \"1\"" " }]" "}"); } TEST(PaymentManifestParserTest, EmptyFingerprintsIsMalformed) { ExpectUnableToParseWebAppManifest( "{" " \"related_applications\": [{" " \"platform\": \"play\", " " \"id\": \"com.bobpay.app\", " " \"min_version\": \"1\", " " \"fingerprints\": []" " }]" "}"); } TEST(PaymentManifestParserTest, EmptyFingerprintsDictionaryIsMalformed) { ExpectUnableToParseWebAppManifest( "{" " \"related_applications\": [{" " \"platform\": \"play\", " " \"id\": \"com.bobpay.app\", " " \"min_version\": \"1\", " " \"fingerprints\": [{}]" " }]" "}"); } TEST(PaymentManifestParserTest, NoFingerprintTypeIsMalformed) { ExpectUnableToParseWebAppManifest( "{" " \"related_applications\": [{" " \"platform\": \"play\", " " \"id\": \"com.bobpay.app\", " " \"min_version\": \"1\", " " \"fingerprints\": [{" " \"value\": \"00:01:02:03:04:05:06:07:08:09:A0:A1:A2:A3:A4:A5:A6:A7" ":A8:A9:B0:B1:B2:B3:B4:B5:B6:B7:B8:B9:C0:C1\"" " }]" " }]" "}"); } TEST(PaymentManifestParserTest, NoFingerprintValueIsMalformed) { ExpectUnableToParseWebAppManifest( "{" " \"related_applications\": [{" " \"platform\": \"play\", " " \"id\": \"com.bobpay.app\", " " \"min_version\": \"1\", " " \"fingerprints\": [{" " \"type\": \"sha256_cert\"" " }]" " }]" "}"); } TEST(PaymentManifestParserTest, PlatformShouldNotHaveNullCharacters) { ExpectUnableToParseWebAppManifest( "{" " \"related_applications\": [{" " \"platform\": \"pl\0ay\", " " \"id\": \"com.bobpay.app\", " " \"min_version\": \"1\", " " \"fingerprints\": [{" " \"type\": \"sha256_cert\", " " \"value\": \"00:01:02:03:04:05:06:07:08:09:A0:A1:A2:A3:A4:A5:A6:A7" ":A8:A9:B0:B1:B2:B3:B4:B5:B6:B7:B8:B9:C0:C1\"" " }]" " }]" "}"); } TEST(PaymentManifestParserTest, PackageNameShouldNotHaveNullCharacters) { ExpectUnableToParseWebAppManifest( "{" " \"related_applications\": [{" " \"platform\": \"play\", " " \"id\": \"com.bob\0pay.app\", " " \"min_version\": \"1\", " " \"fingerprints\": [{" " \"type\": \"sha256_cert\", " " \"value\": \"00:01:02:03:04:05:06:07:08:09:A0:A1:A2:A3:A4:A5:A6:A7" ":A8:A9:B0:B1:B2:B3:B4:B5:B6:B7:B8:B9:C0:C1\"" " }]" " }]" "}"); } TEST(PaymentManifestParserTest, VersionShouldNotHaveNullCharacters) { ExpectUnableToParseWebAppManifest( "{" " \"related_applications\": [{" " \"platform\": \"play\", " " \"id\": \"com.bobpay.app\", " " \"min_version\": \"1\01\", " " \"fingerprints\": [{" " \"type\": \"sha256_cert\", " " \"value\": \"00:01:02:03:04:05:06:07:08:09:A0:A1:A2:A3:A4:A5:A6:A7" ":A8:A9:B0:B1:B2:B3:B4:B5:B6:B7:B8:B9:C0:C1\"" " }]" " }]" "}"); } TEST(PaymentManifestParserTest, FingerprintTypeShouldNotHaveNullCharacters) { ExpectUnableToParseWebAppManifest( "{" " \"related_applications\": [{" " \"platform\": \"play\", " " \"id\": \"com.bobpay.app\", " " \"min_version\": \"1\", " " \"fingerprints\": [{" " \"type\": \"sha256_c\0ert\", " " \"value\": \"00:01:02:03:04:05:06:07:08:09:A0:A1:A2:A3:A4:A5:A6:A7" ":A8:A9:B0:B1:B2:B3:B4:B5:B6:B7:B8:B9:C0:C1\"" " }]" " }]" "}"); } TEST(PaymentManifestParserTest, FingerprintValueShouldNotHaveNullCharacters) { ExpectUnableToParseWebAppManifest( "{" " \"related_applications\": [{" " \"platform\": \"play\", " " \"id\": \"com.bobpay.app\", " " \"min_version\": \"1\", " " \"fingerprints\": [{" " \"type\": \"sha256_cert\", " " \"value\": " "\"00:01:02:0\0:04:05:06:07:08:09:A0:A1:A2:A3:A4:A5:A6:A7" ":A8:A9:B0:B1:B2:B3:B4:B5:B6:B7:B8:B9:C0:C1\"" " }]" " }]" "}"); } TEST(PaymentManifestParserTest, KeysShouldBeLowerCase) { ExpectUnableToParseWebAppManifest( "{" " \"Related_applications\": [{" " \"Platform\": \"play\", " " \"Id\": \"com.bobpay.app\", " " \"Min_version\": \"1\", " " \"Fingerprints\": [{" " \"Type\": \"sha256_cert\", " " \"Value\": \"00:01:02:03:04:05:06:07:08:09:A0:A1:A2:A3:A4:A5:A6:A7" ":A8:A9:B0:B1:B2:B3:B4:B5:B6:B7:B8:B9:C0:C1\"" " }]" " }]" "}"); } TEST(PaymentManifestParserTest, FingerprintsShouldBeSha256) { ExpectUnableToParseWebAppManifest( "{" " \"related_applications\": [{" " \"platform\": \"play\", " " \"id\": \"com.bobpay.app\", " " \"min_version\": \"1\", " " \"fingerprints\": [{" " \"type\": \"sha1_cert\", " " \"value\": \"00:01:02:03:04:05:06:07:08:09:A0:A1:A2:A3:A4:A5:A6:A7" ":A8:A9\"" " }]" " }]" "}"); } TEST(PaymentManifestParserTest, FingerprintBytesShouldBeColonSeparated) { ExpectUnableToParseWebAppManifest( "{" " \"related_applications\": [{" " \"platform\": \"play\", " " \"id\": \"com.bobpay.app\", " " \"min_version\": \"1\", " " \"fingerprints\": [{" " \"type\": \"sha256_cert\", " " \"value\": \"000010020030040050060070080090A00A10A20A30A40A50A60A7" "0A80A90B00B10B20B30B40B50B60B70B80B90C00C1\"" " }]" " }]" "}"); } TEST(PaymentManifestParserTest, FingerprintBytesShouldBeUpperCase) { ExpectUnableToParseWebAppManifest( "{" " \"related_applications\": [{" " \"platform\": \"play\", " " \"id\": \"com.bobpay.app\", " " \"min_version\": \"1\", " " \"fingerprints\": [{" " \"type\": \"sha256_cert\", " " \"value\": \"00:01:02:03:04:05:06:07:08:09:a0:a1:a2:a3:a4:a5:a6:a7" ":a8:a9:b0:b1:b2:b3:b4:b5:b6:b7:b8:b9:c0:c1\"" " }]" " }]" "}"); } TEST(PaymentManifestParserTest, FingerprintsShouldContainsThirtyTwoBytes) { ExpectUnableToParseWebAppManifest( "{" " \"related_applications\": [{" " \"platform\": \"play\", " " \"id\": \"com.bobpay.app\", " " \"min_version\": \"1\", " " \"fingerprints\": [{" " \"type\": \"sha256_cert\", " " \"value\": \"00:01:02:03:04:05:06:07:08:09:A0:A1:A2:A3:A4:A5:A6:A7" ":A8:A9:B0:B1:B2:B3:B4:B5:B6:B7:B8:B9:C0:C1:C2\"" " }]" " }]" "}"); ExpectUnableToParseWebAppManifest( "{" " \"related_applications\": [{" " \"platform\": \"play\", " " \"id\": \"com.bobpay.app\", " " \"min_version\": \"1\", " " \"fingerprints\": [{" " \"type\": \"sha256_cert\", " " \"value\": \"00:01:02:03:04:05:06:07:08:09:A0:A1:A2:A3:A4:A5:A6:A7" ":A8:A9:B0:B1:B2:B3:B4:B5:B6:B7:B8:B9:C0\"" " }]" " }]" "}"); } TEST(PaymentManifestParserTest, WellFormed) { ExpectParsedWebAppManifest( "{" " \"related_applications\": [{" " \"platform\": \"play\", " " \"id\": \"com.bobpay.app\", " " \"min_version\": \"1\", " " \"fingerprints\": [{" " \"type\": \"sha256_cert\", " " \"value\": \"00:01:02:03:04:05:06:07:08:09:A0:A1:A2:A3:A4:A5:A6:A7" ":A8:A9:B0:B1:B2:B3:B4:B5:B6:B7:B8:B9:C0:C1\"" " }]" " }]" "}", "com.bobpay.app", 1, {{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xC0, 0xC1}}); } TEST(PaymentManifestParserTest, DuplicateSignaturesWellFormed) { ExpectParsedWebAppManifest( "{" " \"related_applications\": [{" " \"platform\": \"play\", " " \"id\": \"com.bobpay.app\", " " \"min_version\": \"1\", " " \"fingerprints\": [{" " \"type\": \"sha256_cert\", " " \"value\": \"00:01:02:03:04:05:06:07:08:09:A0:A1:A2:A3:A4:A5:A6:A7" ":A8:A9:B0:B1:B2:B3:B4:B5:B6:B7:B8:B9:C0:C1\"" " }, {" " \"type\": \"sha256_cert\", " " \"value\": \"00:01:02:03:04:05:06:07:08:09:A0:A1:A2:A3:A4:A5:A6:A7" ":A8:A9:B0:B1:B2:B3:B4:B5:B6:B7:B8:B9:C0:C1\"" " }]" " }]" "}", "com.bobpay.app", 1, {{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xC0, 0xC1}, {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xC0, 0xC1}}); } TEST(PaymentManifestParserTest, TwoDifferentSignaturesWellFormed) { ExpectParsedWebAppManifest( "{" " \"related_applications\": [{" " \"platform\": \"play\", " " \"id\": \"com.bobpay.app\", " " \"min_version\": \"1\", " " \"fingerprints\": [{" " \"type\": \"sha256_cert\", " " \"value\": \"00:01:02:03:04:05:06:07:08:09:A0:A1:A2:A3:A4:A5:A6:A7" ":A8:A9:B0:B1:B2:B3:B4:B5:B6:B7:B8:B9:C0:C1\"" " }, {" " \"type\": \"sha256_cert\", " " \"value\": \"AA:01:02:03:04:05:06:07:08:09:A0:A1:A2:A3:A4:A5:A6:A7" ":A8:A9:B0:B1:B2:B3:B4:B5:B6:B7:B8:B9:C0:C1\"" " }]" " }]" "}", "com.bobpay.app", 1, {{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xC0, 0xC1}, {0xAA, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xC0, 0xC1}}); } TEST(PaymentManifestParserTest, TwoRelatedApplicationsWellFormed) { std::unique_ptr<base::Value> value = base::JSONReader::ReadDeprecated( "{" " \"related_applications\": [{" " \"platform\": \"play\", " " \"id\": \"com.bobpay.app.dev\", " " \"min_version\": \"2\", " " \"fingerprints\": [{" " \"type\": \"sha256_cert\", " " \"value\": " "\"00:01:02:03:04:05:06:07:08:09:A0:A1:A2:A3:A4:A5:A6:A7" ":A8:A9:B0:B1:B2:B3:B4:B5:B6:B7:B8:B9:C0:C1\"" " }]" " }, {" " \"platform\": \"play\", " " \"id\": \"com.bobpay.app.prod\", " " \"min_version\": \"1\", " " \"fingerprints\": [{" " \"type\": \"sha256_cert\", " " \"value\": " "\"AA:01:02:03:04:05:06:07:08:09:A0:A1:A2:A3:A4:A5:A6:A7" ":A8:A9:B0:B1:B2:B3:B4:B5:B6:B7:B8:B9:C0:C1\"" " }]" " }]" "}"); ASSERT_TRUE(value); std::vector<WebAppManifestSection> sections; EXPECT_TRUE(PaymentManifestParser::ParseWebAppManifestIntoVector( std::move(value), ErrorLogger(), &sections)); ASSERT_EQ(2U, sections.size()); EXPECT_EQ("com.bobpay.app.dev", sections.front().id); EXPECT_EQ(2, sections.front().min_version); EXPECT_EQ( std::vector<std::vector<uint8_t>>( {{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xC0, 0xC1}}), sections.front().fingerprints); EXPECT_EQ("com.bobpay.app.prod", sections.back().id); EXPECT_EQ(1, sections.back().min_version); EXPECT_EQ( std::vector<std::vector<uint8_t>>( {{0xAA, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xC0, 0xC1}}), sections.back().fingerprints); } // Web app installation information parsing: void ExpectUnableToParseInstallInfo(const std::string& input) { auto value = base::JSONReader::ReadDeprecated(input); auto installation_info = std::make_unique<WebAppInstallationInfo>(); auto icons = std::make_unique<std::vector<PaymentManifestParser::WebAppIcon>>(); EXPECT_FALSE(PaymentManifestParser::ParseWebAppInstallationInfoIntoStructs( std::move(value), ErrorLogger(), installation_info.get(), icons.get())); } void ExpectParsedInstallInfo( const std::string& input, const WebAppInstallationInfo& expected_installation_info, const std::vector<PaymentManifestParser::WebAppIcon>& expected_icons) { auto value = base::JSONReader::ReadDeprecated(input); WebAppInstallationInfo actual_installation_info; std::vector<PaymentManifestParser::WebAppIcon> actual_icons; EXPECT_TRUE(PaymentManifestParser::ParseWebAppInstallationInfoIntoStructs( std::move(value), ErrorLogger(), &actual_installation_info, &actual_icons)); EXPECT_EQ(expected_installation_info.icon == nullptr, actual_installation_info.icon == nullptr); EXPECT_EQ(expected_installation_info.name, actual_installation_info.name); EXPECT_EQ(expected_installation_info.sw_js_url, actual_installation_info.sw_js_url); EXPECT_EQ(expected_installation_info.sw_scope, actual_installation_info.sw_scope); EXPECT_EQ(expected_installation_info.sw_use_cache, actual_installation_info.sw_use_cache); EXPECT_EQ(expected_icons.size(), actual_icons.size()); for (size_t i = 0; i < expected_icons.size() && i < actual_icons.size(); ++i) { EXPECT_EQ(expected_icons[i].src, actual_icons[i].src); EXPECT_EQ(expected_icons[i].sizes, actual_icons[i].sizes); EXPECT_EQ(expected_icons[i].type, actual_icons[i].type); } EXPECT_EQ(expected_installation_info.preferred_app_ids, actual_installation_info.preferred_app_ids); } TEST(PaymentManifestParserTest, NullInstallInfoIsMalformed) { ExpectUnableToParseInstallInfo(std::string()); } TEST(PaymentManifestParserTest, NonJsonInstallInfoIsMalformed) { ExpectUnableToParseInstallInfo("this is not json"); } TEST(PaymentManifestParserTest, StringInstallInfoIsMalformed) { ExpectUnableToParseInstallInfo("\"this is a string\""); } TEST(PaymentManifestParserTest, EmptyDictionaryInstallInfoIsMalformed) { ExpectUnableToParseInstallInfo("{}"); } TEST(PaymentManifestParserTest, StringServiceWorkerInInstallInfoIsMalformed) { ExpectUnableToParseInstallInfo("{\"serviceworker\": \"sw.js\"}"); } TEST(PaymentManifestParserTest, IntegerSrcInInstallInfoIsMalformed) { ExpectUnableToParseInstallInfo("{\"serviceworker\": {\"src\": 0}}"); } TEST(PaymentManifestParserTest, NullCharInSrcInInstallInfoIsMalformed) { ExpectUnableToParseInstallInfo("{\"serviceworker\": {\"src\": \"\0\"}}"); } TEST(PaymentManifestParserTest, EmptyServiceWorkerSrcInInstallInfoIsMalformed) { ExpectUnableToParseInstallInfo("{\"serviceworker\": {\"src\": \"\"}}"); } // Test "payment" member format when every other member is well formed. void TestPaymentMemberFormat(const std::string& payment_format) { ExpectUnableToParseInstallInfo( "{ " " \"name\": \"Pay with BobPay\"," " \"icons\": [{" " \"src\": \"bobpay.png\"," " \"sizes\": \"48x48\"," " \"type\": \"image/png\"" " }]," " \"serviceworker\": {" " \"src\": \"sw.js\"," " \"scope\": \"/some/scope/\"," " \"use_cache\": true" " }," " \"prefer_related_applications\": true," " \"related_applications\": [{" " \"platform\": \"play\"," " \"id\": \"com.bobpay\"" " }]," + payment_format + "}"); } TEST(PaymentManifestParserTest, EmptyPaymentMemberIsMalformed) { TestPaymentMemberFormat("\"payment\": {}"); } TEST(PaymentManifestParserTest, PaymentMemberMustBeADictionary_List) { TestPaymentMemberFormat("\"payment\": [\"supported_delegations\"]"); } TEST(PaymentManifestParserTest, PaymentMemberMustBeADictionary_String) { TestPaymentMemberFormat("\"payment\": \"supported_delegations\""); } TEST(PaymentManifestParserTest, PaymentMemberMustBeADictionary_Integer) { TestPaymentMemberFormat("\"payment\": 1"); } TEST(PaymentManifestParserTest, InvalidKeyInPaymentMemberIsMalformed) { TestPaymentMemberFormat("\"payment\": {\"key\": \"value\"}"); } TEST(PaymentManifestParserTest, SupportedDelegationsMustBeAList_String) { TestPaymentMemberFormat( "\"payment\": {\"supported_delegations\": \"string\"}"); } TEST(PaymentManifestParserTest, SupportedDelegationsMustBeAList_Dictionary) { TestPaymentMemberFormat( "\"payment\": {\"supported_delegations\": {\"key\": \"value\"}}"); } TEST(PaymentManifestParserTest, SupportedDelegationsMustBeAList_Integer) { TestPaymentMemberFormat("\"payment\": {\"supported_delegations\": 1}"); } TEST(PaymentManifestParserTest, EmptyListSupportedDelegationsIsMalformed) { TestPaymentMemberFormat("\"payment\": {\"supported_delegations\": []}"); } TEST(PaymentManifestParserTest, InvalidSupportedDelegationsIsMalformed) { TestPaymentMemberFormat( "\"payment\": {\"supported_delegations\": [\"random string\"]}"); } TEST(PaymentManifestParserTest, NonASCIICharsInSupportedDelegationsIsMalformed) { TestPaymentMemberFormat("\"payment\": {\"supported_delegations\": [\"β\"]}"); } TEST(PaymentManifestParserTest, TooLongSupportedDelegationsListIsMalformed) { TestPaymentMemberFormat( "\"payment\": {\"supported_delegations\": [" + base::JoinString(std::vector<std::string>(101, "\"payerEmail\""), ", ") + "]}"); } TEST(PaymentManifestParserTest, MinimumWellFormedInstallInfo) { WebAppInstallationInfo expected_installation_info; expected_installation_info.sw_js_url = "sw.js"; expected_installation_info.sw_scope = ""; expected_installation_info.sw_use_cache = false; std::vector<PaymentManifestParser::WebAppIcon> expected_icons; ExpectParsedInstallInfo( "{" " \"serviceworker\": {" " \"src\": \"sw.js\"" " }" "}", expected_installation_info, expected_icons); } TEST(PaymentManifestParserTest, WellFormedInstallInfo) { WebAppInstallationInfo expected_installation_info; expected_installation_info.name = "Pay with BobPay"; expected_installation_info.sw_js_url = "sw.js"; expected_installation_info.sw_scope = "/some/scope/"; expected_installation_info.sw_use_cache = true; expected_installation_info.preferred_app_ids = {"com.bobpay"}; expected_installation_info.supported_delegations.shipping_address = true; expected_installation_info.supported_delegations.payer_email = true; expected_installation_info.supported_delegations.payer_name = false; expected_installation_info.supported_delegations.payer_phone = false; PaymentManifestParser::WebAppIcon expected_icon; expected_icon.src = "bobpay.png"; expected_icon.sizes = "48x48"; expected_icon.type = "image/png"; std::vector<PaymentManifestParser::WebAppIcon> expected_icons(1, expected_icon); ExpectParsedInstallInfo( "{" " \"name\": \"Pay with BobPay\"," " \"icons\": [{" " \"src\": \"bobpay.png\"," " \"sizes\": \"48x48\"," " \"type\": \"image/png\"" " }]," " \"serviceworker\": {" " \"src\": \"sw.js\"," " \"scope\": \"/some/scope/\"," " \"use_cache\": true" " }," " \"prefer_related_applications\": true," " \"related_applications\": [{" " \"platform\": \"play\"," " \"id\": \"com.bobpay\"" " }]," " \"payment\": {" " \"supported_delegations\": [\"shippingAddress\", \"payerEmail\"]" " }" "}", expected_installation_info, expected_icons); } TEST(PaymentManifestParserTest, IgnoreNonBooleanPreferRelatedApplicationField) { WebAppInstallationInfo expected_installation_info; expected_installation_info.sw_js_url = "sw.js"; expected_installation_info.sw_scope = ""; expected_installation_info.sw_use_cache = false; ExpectParsedInstallInfo( "{" " \"serviceworker\": {" " \"src\": \"sw.js\"" " }," " \"prefer_related_applications\": 20" "}", expected_installation_info, std::vector<PaymentManifestParser::WebAppIcon>()); } TEST(PaymentManifestParserTest, IgnoreFalsePreferRelatedApplicationField) { WebAppInstallationInfo expected_installation_info; expected_installation_info.sw_js_url = "sw.js"; expected_installation_info.sw_scope = ""; expected_installation_info.sw_use_cache = false; ExpectParsedInstallInfo( "{" " \"serviceworker\": {" " \"src\": \"sw.js\"" " }," " \"prefer_related_applications\": false," " \"related_applications\": [{" " \"platform\": \"play\"," " \"id\": \"com.bobpay\"" " }]" "}", expected_installation_info, std::vector<PaymentManifestParser::WebAppIcon>()); } TEST(PaymentManifestParserTest, IgnoreEmptyRelatedApplications) { WebAppInstallationInfo expected_installation_info; expected_installation_info.sw_js_url = "sw.js"; expected_installation_info.sw_scope = ""; expected_installation_info.sw_use_cache = false; ExpectParsedInstallInfo( "{" " \"serviceworker\": {" " \"src\": \"sw.js\"" " }," " \"prefer_related_applications\": true," " \"related_applications\": []" "}", expected_installation_info, std::vector<PaymentManifestParser::WebAppIcon>()); } TEST(PaymentManifestParserTest, IgnoreNonListRelatedApplications) { WebAppInstallationInfo expected_installation_info; expected_installation_info.sw_js_url = "sw.js"; expected_installation_info.sw_scope = ""; expected_installation_info.sw_use_cache = false; ExpectParsedInstallInfo( "{" " \"serviceworker\": {" " \"src\": \"sw.js\"" " }," " \"prefer_related_applications\": true," " \"related_applications\": {" " \"platform\": \"play\"," " \"id\": \"com.bobpay\"" " }" "}", expected_installation_info, std::vector<PaymentManifestParser::WebAppIcon>()); } TEST(PaymentManifestParserTest, IgnoreNonDictionaryRelatedApplicationsItems) { WebAppInstallationInfo expected_installation_info; expected_installation_info.sw_js_url = "sw.js"; expected_installation_info.sw_scope = ""; expected_installation_info.sw_use_cache = false; ExpectParsedInstallInfo( "{" " \"serviceworker\": {" " \"src\": \"sw.js\"" " }," " \"prefer_related_applications\": true," " \"related_applications\": [" " \"com.bobpay\"" " ]" "}", expected_installation_info, std::vector<PaymentManifestParser::WebAppIcon>()); } TEST(PaymentManifestParserTest, IgnoreRelatedApplicationsItemsWithoutId) { WebAppInstallationInfo expected_installation_info; expected_installation_info.sw_js_url = "sw.js"; expected_installation_info.sw_scope = ""; expected_installation_info.sw_use_cache = false; ExpectParsedInstallInfo( "{" " \"serviceworker\": {" " \"src\": \"sw.js\"" " }," " \"prefer_related_applications\": true," " \"related_applications\": [{" " \"platform\": \"play\"" " }]" "}", expected_installation_info, std::vector<PaymentManifestParser::WebAppIcon>()); } TEST(PaymentManifestParserTest, IgnoreRelatedApplicationsItemsWithoutPlatform) { WebAppInstallationInfo expected_installation_info; expected_installation_info.sw_js_url = "sw.js"; expected_installation_info.sw_scope = ""; expected_installation_info.sw_use_cache = false; ExpectParsedInstallInfo( "{" " \"serviceworker\": {" " \"src\": \"sw.js\"" " }," " \"prefer_related_applications\": true," " \"related_applications\": [{" " \"id\": \"com.bobpay\"" " }]" "}", expected_installation_info, std::vector<PaymentManifestParser::WebAppIcon>()); } TEST(PaymentManifestParserTest, IgnoreRelatedApplicationsWithoutPlayPlatform) { WebAppInstallationInfo expected_installation_info; expected_installation_info.sw_js_url = "sw.js"; expected_installation_info.sw_scope = ""; expected_installation_info.sw_use_cache = false; ExpectParsedInstallInfo( "{" " \"serviceworker\": {" " \"src\": \"sw.js\"" " }," " \"prefer_related_applications\": true," " \"related_applications\": [{" " \"platform\": \"web\"," " \"id\": \"12345678890\"" " }]" "}", expected_installation_info, std::vector<PaymentManifestParser::WebAppIcon>()); } TEST(PaymentManifestParserTest, OneHundredRelatedApplicationsIsWellFormed) { WebAppInstallationInfo expected_installation_info; expected_installation_info.sw_js_url = "sw.js"; expected_installation_info.sw_scope = ""; expected_installation_info.sw_use_cache = false; expected_installation_info.preferred_app_ids = std::vector<std::string>(100, "com.bobpay"); ExpectParsedInstallInfo( "{" " \"serviceworker\": {" " \"src\": \"sw.js\"" " }," " \"prefer_related_applications\": true," " \"related_applications\": [" + base::JoinString( std::vector<std::string>( 100, "{\"platform\": \"play\", \"id\": \"com.bobpay\"}"), ",") + "]}", expected_installation_info, std::vector<PaymentManifestParser::WebAppIcon>()); } TEST(PaymentManifestParserTest, CapRelatedApplicationsAtOneHundred) { WebAppInstallationInfo expected_installation_info; expected_installation_info.sw_js_url = "sw.js"; expected_installation_info.sw_scope = ""; expected_installation_info.sw_use_cache = false; expected_installation_info.preferred_app_ids = std::vector<std::string>(100, "com.bobpay"); ExpectParsedInstallInfo( "{" " \"serviceworker\": {" " \"src\": \"sw.js\"" " }," " \"prefer_related_applications\": true," " \"related_applications\": [" + base::JoinString( std::vector<std::string>( 101, "{\"platform\": \"play\", \"id\": \"com.bobpay\"}"), ",") + "]}", expected_installation_info, std::vector<PaymentManifestParser::WebAppIcon>()); } TEST(PaymentManifestParserTest, IgnoreEmptyRelatedApplicationId) { WebAppInstallationInfo expected_installation_info; expected_installation_info.sw_js_url = "sw.js"; expected_installation_info.sw_scope = ""; expected_installation_info.sw_use_cache = false; ExpectParsedInstallInfo( "{" " \"serviceworker\": {" " \"src\": \"sw.js\"" " }," " \"prefer_related_applications\": true," " \"related_applications\": [{" " \"platform\": \"play\"," " \"id\": \"\"" " }]" "}", expected_installation_info, std::vector<PaymentManifestParser::WebAppIcon>()); } TEST(PaymentManifestParserTest, IgnoreNonASCIIRelatedApplicationId) { WebAppInstallationInfo expected_installation_info; expected_installation_info.sw_js_url = "sw.js"; expected_installation_info.sw_scope = ""; expected_installation_info.sw_use_cache = false; ExpectParsedInstallInfo( "{" " \"serviceworker\": {" " \"src\": \"sw.js\"" " }," " \"prefer_related_applications\": true," " \"related_applications\": [{" " \"platform\": \"play\"," " \"id\": \"😊\"" " }]" "}", expected_installation_info, std::vector<PaymentManifestParser::WebAppIcon>()); } } // namespace } // namespace payments
// // Copyright (c) 2015-2018 The PIVX developers // Copyright (c) 2020 The Klimatas developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <iostream> #include "genwit.h" #include "chainparams.h" #include "util.h" CGenWit::CGenWit() : accWitValue(0) {} CGenWit::CGenWit(const CBloomFilter &filter, int startingHeight, libzerocoin::CoinDenomination den, int requestNum, CBigNum accWitValue) : filter(filter), startingHeight(startingHeight), den(den), requestNum(requestNum), accWitValue(accWitValue) {} bool CGenWit::isValid(int chainActiveHeight) { if (den == libzerocoin::CoinDenomination::ZQ_ERROR){ return error("%s: ERROR: invalid denomination", __func__); } if(!filter.IsWithinSizeConstraints()){ return error("%s: ERROR: filter not within size constraints", __func__); } if (startingHeight < Params().Zerocoin_Block_V2_Start()){ return error("%s: ERROR: starting height before V2 activation", __func__); } if (accWitValue == 0){ return error("%s: ERROR: invalid accWit value", __func__); } return (startingHeight < chainActiveHeight - 20); } const CBloomFilter &CGenWit::getFilter() const { return filter; } int CGenWit::getStartingHeight() const { return startingHeight; } libzerocoin::CoinDenomination CGenWit::getDen() const { return den; } int CGenWit::getRequestNum() const { return requestNum; } CNode *CGenWit::getPfrom() const { return pfrom; } void CGenWit::setPfrom(CNode *pfrom) { CGenWit::pfrom = pfrom; } const CBigNum &CGenWit::getAccWitValue() const { return accWitValue; } const std::string CGenWit::toString() const { return "From: " + pfrom->addrName + ",\n" + "Height: " + std::to_string(startingHeight) + ",\n" + "accWit: " + accWitValue.GetHex(); }
// matchertests.cpp : matcher unit tests // /** * Copyright (C) 2008 10gen Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the GNU Affero General Public License in all respects * for all of the code used other than as permitted herein. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you do not * wish to do so, delete this exception statement from your version. If you * delete this exception statement from all source files in the program, * then also delete it in the license file. */ #include <iostream> #include "mongo/db/db_raii.h" #include "mongo/db/json.h" #include "mongo/db/matcher/extensions_callback_real.h" #include "mongo/db/matcher/matcher.h" #include "mongo/db/operation_context_impl.h" #include "mongo/dbtests/dbtests.h" #include "mongo/util/timer.h" namespace MatcherTests { using std::cout; using std::endl; using std::string; class CollectionBase { public: CollectionBase() {} virtual ~CollectionBase() {} }; template <typename M> class Basic { public: void run() { BSONObj query = fromjson("{\"a\":\"b\"}"); M m(query, ExtensionsCallback()); ASSERT(m.matches(fromjson("{\"a\":\"b\"}"))); } }; template <typename M> class DoubleEqual { public: void run() { BSONObj query = fromjson("{\"a\":5}"); M m(query, ExtensionsCallback()); ASSERT(m.matches(fromjson("{\"a\":5}"))); } }; template <typename M> class MixedNumericEqual { public: void run() { BSONObjBuilder query; query.append("a", 5); M m(query.done(), ExtensionsCallback()); ASSERT(m.matches(fromjson("{\"a\":5}"))); } }; template <typename M> class MixedNumericGt { public: void run() { BSONObj query = fromjson("{\"a\":{\"$gt\":4}}"); M m(query, ExtensionsCallback()); BSONObjBuilder b; b.append("a", 5); ASSERT(m.matches(b.done())); } }; template <typename M> class MixedNumericIN { public: void run() { BSONObj query = fromjson("{ a : { $in : [4,6] } }"); ASSERT_EQUALS(4, query["a"].embeddedObject()["$in"].embeddedObject()["0"].number()); ASSERT_EQUALS(NumberInt, query["a"].embeddedObject()["$in"].embeddedObject()["0"].type()); M m(query, ExtensionsCallback()); { BSONObjBuilder b; b.append("a", 4.0); ASSERT(m.matches(b.done())); } { BSONObjBuilder b; b.append("a", 5); ASSERT(!m.matches(b.done())); } { BSONObjBuilder b; b.append("a", 4); ASSERT(m.matches(b.done())); } } }; template <typename M> class MixedNumericEmbedded { public: void run() { M m(BSON("a" << BSON("x" << 1)), ExtensionsCallback()); ASSERT(m.matches(BSON("a" << BSON("x" << 1)))); ASSERT(m.matches(BSON("a" << BSON("x" << 1.0)))); } }; template <typename M> class Size { public: void run() { M m(fromjson("{a:{$size:4}}"), ExtensionsCallback()); ASSERT(m.matches(fromjson("{a:[1,2,3,4]}"))); ASSERT(!m.matches(fromjson("{a:[1,2,3]}"))); ASSERT(!m.matches(fromjson("{a:[1,2,3,'a','b']}"))); ASSERT(!m.matches(fromjson("{a:[[1,2,3,4]]}"))); } }; template <typename M> class WithinBox { public: void run() { M m(fromjson("{loc:{$within:{$box:[{x: 4, y:4},[6,6]]}}}"), ExtensionsCallback()); ASSERT(!m.matches(fromjson("{loc: [3,4]}"))); ASSERT(m.matches(fromjson("{loc: [4,4]}"))); ASSERT(m.matches(fromjson("{loc: [5,5]}"))); ASSERT(m.matches(fromjson("{loc: [5,5.1]}"))); ASSERT(m.matches(fromjson("{loc: {x: 5, y:5.1}}"))); } }; template <typename M> class WithinPolygon { public: void run() { M m(fromjson("{loc:{$within:{$polygon:[{x:0,y:0},[0,5],[5,5],[5,0]]}}}"), ExtensionsCallback()); ASSERT(m.matches(fromjson("{loc: [3,4]}"))); ASSERT(m.matches(fromjson("{loc: [4,4]}"))); ASSERT(m.matches(fromjson("{loc: {x:5,y:5}}"))); ASSERT(!m.matches(fromjson("{loc: [5,5.1]}"))); ASSERT(!m.matches(fromjson("{loc: {}}"))); } }; template <typename M> class WithinCenter { public: void run() { M m(fromjson("{loc:{$within:{$center:[{x:30,y:30},10]}}}"), ExtensionsCallback()); ASSERT(!m.matches(fromjson("{loc: [3,4]}"))); ASSERT(m.matches(fromjson("{loc: {x:30,y:30}}"))); ASSERT(m.matches(fromjson("{loc: [20,30]}"))); ASSERT(m.matches(fromjson("{loc: [30,20]}"))); ASSERT(m.matches(fromjson("{loc: [40,30]}"))); ASSERT(m.matches(fromjson("{loc: [30,40]}"))); ASSERT(!m.matches(fromjson("{loc: [31,40]}"))); } }; /** Test that MatchDetails::elemMatchKey() is set correctly after a match. */ template <typename M> class ElemMatchKey { public: void run() { M matcher(BSON("a.b" << 1), ExtensionsCallback()); MatchDetails details; details.requestElemMatchKey(); ASSERT(!details.hasElemMatchKey()); ASSERT(matcher.matches(fromjson("{ a:[ { b:1 } ] }"), &details)); // The '0' entry of the 'a' array is matched. ASSERT(details.hasElemMatchKey()); ASSERT_EQUALS(string("0"), details.elemMatchKey()); } }; template <typename M> class WhereSimple1 { public: void run() { OperationContextImpl txn; const NamespaceString nss("unittests.matchertests"); AutoGetCollectionForRead ctx(&txn, nss); M m(BSON("$where" << "function(){ return this.a == 1; }"), ExtensionsCallbackReal(&txn, &nss)); ASSERT(m.matches(BSON("a" << 1))); ASSERT(!m.matches(BSON("a" << 2))); } }; template <typename M> class TimingBase { public: long dotime(const BSONObj& patt, const BSONObj& obj) { M m(patt, ExtensionsCallback()); Timer t; for (int i = 0; i < 900000; i++) { if (!m.matches(obj)) { ASSERT(0); } } return t.millis(); } }; template <typename M> class AllTiming : public TimingBase<M> { public: void run() { long normal = TimingBase<M>::dotime(BSON("x" << 5), BSON("x" << 5)); long all = TimingBase<M>::dotime(BSON("x" << BSON("$all" << BSON_ARRAY(5))), BSON("x" << 5)); cout << "AllTiming " << demangleName(typeid(M)) << " normal: " << normal << " all: " << all << endl; } }; class All : public Suite { public: All() : Suite("matcher") {} #define ADD_BOTH(TEST) add<TEST<Matcher>>(); void setupTests() { ADD_BOTH(Basic); ADD_BOTH(DoubleEqual); ADD_BOTH(MixedNumericEqual); ADD_BOTH(MixedNumericGt); ADD_BOTH(MixedNumericIN); ADD_BOTH(Size); ADD_BOTH(MixedNumericEmbedded); ADD_BOTH(ElemMatchKey); ADD_BOTH(WhereSimple1); ADD_BOTH(AllTiming); ADD_BOTH(WithinBox); ADD_BOTH(WithinCenter); ADD_BOTH(WithinPolygon); } }; SuiteInstance<All> dball; } // namespace MatcherTests
#include <fstream> using namespace std; ifstream input("../README.md", ios::in); ofstream output("yourOutputFile.txt", ios::out); char letter; int main(){ letter = input.get(); output.put(letter); output << "David Britt"; input.close(); output.close(); return 0; }
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.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" // Completed includes // Begin forward declares // Forward declaring namespace: GlobalNamespace namespace GlobalNamespace { // Forward declaring type: OVRPose struct OVRPose; } // Completed forward declares // Type namespace: namespace GlobalNamespace { // Forward declaring type: OVRTracker class OVRTracker; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::GlobalNamespace::OVRTracker); DEFINE_IL2CPP_ARG_TYPE(::GlobalNamespace::OVRTracker*, "", "OVRTracker"); // Type namespace: namespace GlobalNamespace { // Size: 0x10 #pragma pack(push, 1) // Autogenerated type: OVRTracker // [TokenAttribute] Offset: FFFFFFFF class OVRTracker : public ::Il2CppObject { public: // Nested type: ::GlobalNamespace::OVRTracker::Frustum struct Frustum; // public System.Boolean get_isPresent() // Offset: 0x24594BC bool get_isPresent(); // public System.Boolean get_isPositionTracked() // Offset: 0x2459558 bool get_isPositionTracked(); // public System.Boolean get_isEnabled() // Offset: 0x24595B8 bool get_isEnabled(); // public System.Void set_isEnabled(System.Boolean value) // Offset: 0x2459654 void set_isEnabled(bool value); // public System.Int32 get_count() // Offset: 0x24596F4 int get_count(); // public OVRTracker/Frustum GetFrustum(System.Int32 tracker) // Offset: 0x2459870 ::GlobalNamespace::OVRTracker::Frustum GetFrustum(int tracker); // public OVRPose GetPose(System.Int32 tracker) // Offset: 0x2459920 ::GlobalNamespace::OVRPose GetPose(int tracker); // public System.Boolean GetPoseValid(System.Int32 tracker) // Offset: 0x2459BB4 bool GetPoseValid(int tracker); // public System.Boolean GetPresent(System.Int32 tracker) // Offset: 0x2459734 bool GetPresent(int tracker); // public System.Void .ctor() // Offset: 0x2459CF0 // Implemented from: System.Object // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static OVRTracker* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::GlobalNamespace::OVRTracker::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<OVRTracker*, creationType>())); } }; // OVRTracker #pragma pack(pop) } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: GlobalNamespace::OVRTracker::get_isPresent // Il2CppName: get_isPresent template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::OVRTracker::*)()>(&GlobalNamespace::OVRTracker::get_isPresent)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::OVRTracker*), "get_isPresent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::OVRTracker::get_isPositionTracked // Il2CppName: get_isPositionTracked template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::OVRTracker::*)()>(&GlobalNamespace::OVRTracker::get_isPositionTracked)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::OVRTracker*), "get_isPositionTracked", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::OVRTracker::get_isEnabled // Il2CppName: get_isEnabled template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::OVRTracker::*)()>(&GlobalNamespace::OVRTracker::get_isEnabled)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::OVRTracker*), "get_isEnabled", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::OVRTracker::set_isEnabled // Il2CppName: set_isEnabled template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::OVRTracker::*)(bool)>(&GlobalNamespace::OVRTracker::set_isEnabled)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::OVRTracker*), "set_isEnabled", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::OVRTracker::get_count // Il2CppName: get_count template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (GlobalNamespace::OVRTracker::*)()>(&GlobalNamespace::OVRTracker::get_count)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::OVRTracker*), "get_count", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::OVRTracker::GetFrustum // Il2CppName: GetFrustum template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::GlobalNamespace::OVRTracker::Frustum (GlobalNamespace::OVRTracker::*)(int)>(&GlobalNamespace::OVRTracker::GetFrustum)> { static const MethodInfo* get() { static auto* tracker = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::OVRTracker*), "GetFrustum", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{tracker}); } }; // Writing MetadataGetter for method: GlobalNamespace::OVRTracker::GetPose // Il2CppName: GetPose template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::GlobalNamespace::OVRPose (GlobalNamespace::OVRTracker::*)(int)>(&GlobalNamespace::OVRTracker::GetPose)> { static const MethodInfo* get() { static auto* tracker = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::OVRTracker*), "GetPose", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{tracker}); } }; // Writing MetadataGetter for method: GlobalNamespace::OVRTracker::GetPoseValid // Il2CppName: GetPoseValid template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::OVRTracker::*)(int)>(&GlobalNamespace::OVRTracker::GetPoseValid)> { static const MethodInfo* get() { static auto* tracker = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::OVRTracker*), "GetPoseValid", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{tracker}); } }; // Writing MetadataGetter for method: GlobalNamespace::OVRTracker::GetPresent // Il2CppName: GetPresent template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::OVRTracker::*)(int)>(&GlobalNamespace::OVRTracker::GetPresent)> { static const MethodInfo* get() { static auto* tracker = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::OVRTracker*), "GetPresent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{tracker}); } }; // Writing MetadataGetter for method: GlobalNamespace::OVRTracker::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
/* Copyright 2020 The OneFlow 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 <pybind11/pybind11.h> #include "oneflow/api/python/of_api_registry.h" #include "oneflow/core/vm/vm_util.h" #include "oneflow/core/eager/dev_vm_dep_object_consume_mode.h" ONEFLOW_API_PYBIND11_MODULE("eager.multi_client", m) { using namespace oneflow; namespace py = pybind11; m.def( "Sync", []() { vm::ClusterSync().GetOrThrow(); }, py::call_guard<py::gil_scoped_release>()); py::class_<one::DevVmDepObjectConsumeModeGuard, std::shared_ptr<one::DevVmDepObjectConsumeModeGuard>>( m, "DevVmDepObjectConsumeModeGuard"); m.def("SourceOpOnlyResourceDependenceModeGuard", []() { return std::make_shared<one::DevVmDepObjectConsumeModeGuard>( one::DevVmDepObjectConsumeMode::NONE); }); }
/* * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "it_test_vm.h" static int Testcase(void) { char *p = NULL; int pageSize; int ret; pageSize = getpagesize(); ret = mprotect(0, pageSize, PROT_NONE); ICUNIT_ASSERT_EQUAL(ret, -1, ret); ICUNIT_ASSERT_EQUAL(errno, EINVAL, errno); ret = mprotect(0, pageSize, 0xffff); ICUNIT_ASSERT_EQUAL(ret, -1, ret); ICUNIT_ASSERT_EQUAL(errno, EINVAL, errno); ret = mprotect((void *)0x1000, pageSize, PROT_READ | PROT_WRITE); ICUNIT_ASSERT_EQUAL(ret, -1, ret); ICUNIT_ASSERT_EQUAL(errno, EINVAL, errno); ret = mprotect((void *)0xffffff, pageSize, PROT_READ | PROT_WRITE); ICUNIT_ASSERT_EQUAL(ret, -1, ret); ICUNIT_ASSERT_EQUAL(errno, EINVAL, errno); p = (char *)mmap(NULL, pageSize * 3, PROT_READ, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); ICUNIT_ASSERT_NOT_EQUAL(p, MAP_FAILED, p); ret = mprotect(p, pageSize * 4, PROT_READ | PROT_WRITE); ICUNIT_ASSERT_EQUAL(ret, -1, ret); ICUNIT_ASSERT_EQUAL(errno, EINVAL, errno); ret = mprotect(p, pageSize, PROT_READ | PROT_WRITE); ICUNIT_ASSERT_EQUAL(ret, 0, ret); (void)memset_s(p, pageSize, 0xf, pageSize); ret = mprotect(p + pageSize * 2, pageSize, PROT_READ | PROT_WRITE); ICUNIT_ASSERT_EQUAL(ret, 0, ret); (void)memset_s(p + pageSize * 2, pageSize, 0xf, pageSize); ret = munmap(p, pageSize); ICUNIT_ASSERT_EQUAL(ret, 0, ret); return 0; } void ItTestMprotect001(void) { TEST_ADD_CASE("IT_MEM_MPROTECT_001", Testcase, TEST_LOS, TEST_MEM, TEST_LEVEL0, TEST_FUNCTION); }
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/memory/ptr_util.h" #include "base/memory/raw_ptr.h" #include "base/run_loop.h" #include "base/test/task_environment.h" #include "components/prefs/testing_pref_service.h" #include "components/web_resource/eula_accepted_notifier.h" #include "components/web_resource/resource_request_allowed_notifier_test_util.h" #include "services/network/test/test_network_connection_tracker.h" #include "testing/gtest/include/gtest/gtest.h" namespace web_resource { // EulaAcceptedNotifier test class that allows mocking the EULA accepted state // and issuing simulated notifications. class TestEulaAcceptedNotifier : public EulaAcceptedNotifier { public: TestEulaAcceptedNotifier() : EulaAcceptedNotifier(nullptr), eula_accepted_(false) { } TestEulaAcceptedNotifier(const TestEulaAcceptedNotifier&) = delete; TestEulaAcceptedNotifier& operator=(const TestEulaAcceptedNotifier&) = delete; ~TestEulaAcceptedNotifier() override {} bool IsEulaAccepted() override { return eula_accepted_; } void SetEulaAcceptedForTesting(bool eula_accepted) { eula_accepted_ = eula_accepted; } void SimulateEulaAccepted() { NotifyObserver(); } private: bool eula_accepted_; }; enum class ConnectionTrackerResponseMode { kSynchronous, kAsynchronous, }; // A test fixture class for ResourceRequestAllowedNotifier tests that require // network state simulations. This also acts as the service implementing the // ResourceRequestAllowedNotifier::Observer interface. class ResourceRequestAllowedNotifierTest : public testing::Test, public ResourceRequestAllowedNotifier::Observer, public testing::WithParamInterface<ConnectionTrackerResponseMode> { public: ResourceRequestAllowedNotifierTest() : resource_request_allowed_notifier_( &prefs_, network::TestNetworkConnectionTracker::GetInstance()), eula_notifier_(new TestEulaAcceptedNotifier), was_notified_(false) { auto* tracker = network::TestNetworkConnectionTracker::GetInstance(); tracker->SetRespondSynchronously( GetParam() == ConnectionTrackerResponseMode::kSynchronous); tracker->SetConnectionType(network::mojom::ConnectionType::CONNECTION_WIFI); resource_request_allowed_notifier_.InitWithEulaAcceptNotifier( this, base::WrapUnique(eula_notifier_.get())); } ResourceRequestAllowedNotifierTest( const ResourceRequestAllowedNotifierTest&) = delete; ResourceRequestAllowedNotifierTest& operator=( const ResourceRequestAllowedNotifierTest&) = delete; ~ResourceRequestAllowedNotifierTest() override {} bool was_notified() const { return was_notified_; } // ResourceRequestAllowedNotifier::Observer override: void OnResourceRequestsAllowed() override { was_notified_ = true; } void SimulateNetworkConnectionChange(network::mojom::ConnectionType type) { network::TestNetworkConnectionTracker::GetInstance()->SetConnectionType( type); base::RunLoop().RunUntilIdle(); } // Simulate a resource request from the test service. It returns true if // resource request is allowed. Otherwise returns false and will change the // result of was_notified() to true when the request is allowed. bool SimulateResourceRequest() { return resource_request_allowed_notifier_.ResourceRequestsAllowed(); } void SimulateEulaAccepted() { eula_notifier_->SimulateEulaAccepted(); } // Eula manipulation methods: void SetNeedsEulaAcceptance(bool needs_acceptance) { eula_notifier_->SetEulaAcceptedForTesting(!needs_acceptance); } void SetWaitingForEula(bool waiting) { resource_request_allowed_notifier_.SetWaitingForEulaForTesting(waiting); } // Used in tests involving the EULA. Disables both the EULA accepted state // and the network. void DisableEulaAndNetwork() { SimulateNetworkConnectionChange( network::mojom::ConnectionType::CONNECTION_NONE); SetWaitingForEula(true); SetNeedsEulaAcceptance(true); } void SetUp() override { // Assume the test service has already requested permission, as all tests // just test that criteria changes notify the server. // Set default EULA state to done (not waiting and EULA accepted) to // simplify non-ChromeOS tests. SetWaitingForEula(false); SetNeedsEulaAcceptance(false); } private: base::test::SingleThreadTaskEnvironment task_environment_{ base::test::SingleThreadTaskEnvironment::MainThreadType::UI}; TestRequestAllowedNotifier resource_request_allowed_notifier_; TestingPrefServiceSimple prefs_; raw_ptr<TestEulaAcceptedNotifier> eula_notifier_; // Weak, owned by RRAN. bool was_notified_; }; TEST_P(ResourceRequestAllowedNotifierTest, NotifyOnInitialNetworkState) { if (GetParam() == ConnectionTrackerResponseMode::kSynchronous) { EXPECT_TRUE(SimulateResourceRequest()); } else { EXPECT_FALSE(SimulateResourceRequest()); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(was_notified()); } } TEST_P(ResourceRequestAllowedNotifierTest, DoNotNotifyIfOffline) { SimulateNetworkConnectionChange( network::mojom::ConnectionType::CONNECTION_NONE); EXPECT_FALSE(SimulateResourceRequest()); SimulateNetworkConnectionChange( network::mojom::ConnectionType::CONNECTION_NONE); EXPECT_FALSE(was_notified()); } TEST_P(ResourceRequestAllowedNotifierTest, DoNotNotifyIfOnlineToOnline) { SimulateNetworkConnectionChange( network::mojom::ConnectionType::CONNECTION_WIFI); EXPECT_TRUE(SimulateResourceRequest()); SimulateNetworkConnectionChange( network::mojom::ConnectionType::CONNECTION_ETHERNET); EXPECT_FALSE(was_notified()); } TEST_P(ResourceRequestAllowedNotifierTest, NotifyOnReconnect) { SimulateNetworkConnectionChange( network::mojom::ConnectionType::CONNECTION_NONE); EXPECT_FALSE(SimulateResourceRequest()); SimulateNetworkConnectionChange( network::mojom::ConnectionType::CONNECTION_ETHERNET); EXPECT_TRUE(was_notified()); } TEST_P(ResourceRequestAllowedNotifierTest, NoNotifyOnWardriving) { SimulateNetworkConnectionChange( network::mojom::ConnectionType::CONNECTION_WIFI); EXPECT_TRUE(SimulateResourceRequest()); SimulateNetworkConnectionChange( network::mojom::ConnectionType::CONNECTION_WIFI); EXPECT_FALSE(was_notified()); SimulateNetworkConnectionChange( network::mojom::ConnectionType::CONNECTION_3G); EXPECT_FALSE(was_notified()); SimulateNetworkConnectionChange( network::mojom::ConnectionType::CONNECTION_4G); EXPECT_FALSE(was_notified()); SimulateNetworkConnectionChange( network::mojom::ConnectionType::CONNECTION_WIFI); EXPECT_FALSE(was_notified()); } TEST_P(ResourceRequestAllowedNotifierTest, NoNotifyOnFlakyConnection) { SimulateNetworkConnectionChange( network::mojom::ConnectionType::CONNECTION_WIFI); EXPECT_TRUE(SimulateResourceRequest()); SimulateNetworkConnectionChange( network::mojom::ConnectionType::CONNECTION_WIFI); EXPECT_FALSE(was_notified()); SimulateNetworkConnectionChange( network::mojom::ConnectionType::CONNECTION_NONE); EXPECT_FALSE(was_notified()); SimulateNetworkConnectionChange( network::mojom::ConnectionType::CONNECTION_WIFI); EXPECT_FALSE(was_notified()); } TEST_P(ResourceRequestAllowedNotifierTest, NotifyOnFlakyConnection) { // First, the observer queries the state while the network is connected. SimulateNetworkConnectionChange( network::mojom::ConnectionType::CONNECTION_WIFI); EXPECT_TRUE(SimulateResourceRequest()); SimulateNetworkConnectionChange( network::mojom::ConnectionType::CONNECTION_WIFI); EXPECT_FALSE(was_notified()); SimulateNetworkConnectionChange( network::mojom::ConnectionType::CONNECTION_NONE); EXPECT_FALSE(was_notified()); // Now, the observer queries the state while the network is disconnected. EXPECT_FALSE(SimulateResourceRequest()); SimulateNetworkConnectionChange( network::mojom::ConnectionType::CONNECTION_WIFI); EXPECT_TRUE(was_notified()); } TEST_P(ResourceRequestAllowedNotifierTest, NoNotifyOnEulaAfterGoOffline) { DisableEulaAndNetwork(); EXPECT_FALSE(SimulateResourceRequest()); SimulateNetworkConnectionChange( network::mojom::ConnectionType::CONNECTION_WIFI); EXPECT_FALSE(was_notified()); SimulateNetworkConnectionChange( network::mojom::ConnectionType::CONNECTION_NONE); EXPECT_FALSE(was_notified()); SimulateEulaAccepted(); EXPECT_FALSE(was_notified()); } TEST_P(ResourceRequestAllowedNotifierTest, NoRequestNoNotify) { // Ensure that if the observing service does not request access, it does not // get notified, even if the criteria are met. Note that this is done by not // calling SimulateResourceRequest here. SimulateNetworkConnectionChange( network::mojom::ConnectionType::CONNECTION_NONE); SimulateNetworkConnectionChange( network::mojom::ConnectionType::CONNECTION_ETHERNET); EXPECT_FALSE(was_notified()); } TEST_P(ResourceRequestAllowedNotifierTest, EulaOnlyNetworkOffline) { DisableEulaAndNetwork(); EXPECT_FALSE(SimulateResourceRequest()); SimulateEulaAccepted(); EXPECT_FALSE(was_notified()); } TEST_P(ResourceRequestAllowedNotifierTest, EulaFirst) { DisableEulaAndNetwork(); EXPECT_FALSE(SimulateResourceRequest()); SimulateEulaAccepted(); EXPECT_FALSE(was_notified()); SimulateNetworkConnectionChange( network::mojom::ConnectionType::CONNECTION_WIFI); EXPECT_TRUE(was_notified()); } TEST_P(ResourceRequestAllowedNotifierTest, NetworkFirst) { DisableEulaAndNetwork(); EXPECT_FALSE(SimulateResourceRequest()); SimulateNetworkConnectionChange( network::mojom::ConnectionType::CONNECTION_WIFI); EXPECT_FALSE(was_notified()); SimulateEulaAccepted(); EXPECT_TRUE(was_notified()); } TEST_P(ResourceRequestAllowedNotifierTest, NoRequestNoNotifyEula) { // Ensure that if the observing service does not request access, it does not // get notified, even if the criteria are met. Note that this is done by not // calling SimulateResourceRequest here. DisableEulaAndNetwork(); SimulateNetworkConnectionChange( network::mojom::ConnectionType::CONNECTION_WIFI); EXPECT_FALSE(was_notified()); SimulateEulaAccepted(); EXPECT_FALSE(was_notified()); } INSTANTIATE_TEST_SUITE_P( All, ResourceRequestAllowedNotifierTest, testing::Values(ConnectionTrackerResponseMode::kSynchronous, ConnectionTrackerResponseMode::kAsynchronous)); } // namespace web_resource
#include "String.hpp" namespace FEngine { namespace String { void PrependZeros(std::string & str, int totalDigits) { int zerosToPrepend = totalDigits - str.length(); for(int i = 0; i < zerosToPrepend; i++) { str = std::string("0") + str; } } } }
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/ #ifdef __cplusplus #pragma once #import "AKSoundpipeKernel.hpp" #import <vector> #import "AKBankDSPKernel.hpp" /*static inline double pow2(double x) { return x * x; }*/ #import "AKDSPKernel.hpp" class AKFilterSynthDSPKernel: public AKSoundpipeKernel { protected: struct NoteState { // linked-list management NoteState *next; NoteState *prev; void remove() { if (prev) prev->next = next; else kernel->playingNotes = next; if (next) next->prev = prev; --kernel->playingNotesCount; } void add() { init(); prev = nullptr; next = kernel->playingNotes; if (next) next->prev = this; kernel->playingNotes = this; ++kernel->playingNotesCount; } AKFilterSynthDSPKernel *kernel; enum { stageOff, stageOn, stageRelease }; int stage = stageOff; float internalGate = 0; float amp = 0; float filterAmp = 0; sp_adsr *adsr; sp_moogladder *filter; sp_adsr *filterEnv; NoteState() { sp_adsr_create(&adsr); sp_moogladder_create(&filter); sp_adsr_create(&filterEnv); } virtual ~NoteState() { sp_adsr_destroy(&adsr); sp_moogladder_destroy(&filter); sp_adsr_destroy(&filterEnv); } virtual void init() = 0; virtual void clear() { stage = stageOff; amp = 0; filterAmp = 0; } void noteOn(int noteNumber, int velocity) { noteOn(noteNumber, velocity, (float)noteToHz(noteNumber)); } virtual void noteOn(int noteNumber, int velocity, float frequency) { if (velocity == 0) { if (stage == stageOn) { stage = stageRelease; internalGate = 0; } } else { if (stage == stageOff) { add(); } stage = stageOn; internalGate = 1; } } virtual void run(int frameCount, float *outL, float *outR) = 0; }; public: enum FilterSynthAddresses { attackDurationAddress = 0, decayDurationAddress, sustainLevelAddress, releaseDurationAddress, pitchBendAddress, vibratoDepthAddress, vibratoRateAddress, filterCutoffFrequencyAddress, filterResonanceAddress, filterAttackDurationAddress, filterDecayDurationAddress, filterSustainLevelAddress, filterReleaseDurationAddress, filterEnvelopeStrengthAddress, filterLFODepthAddress, filterLFORateAddress, numberOfFilterSynthEnumElements }; public: // MARK: Member Functions void init(int channelCount, double sampleRate) override { AKSoundpipeKernel::init(channelCount, sampleRate); attackDurationRamper.init(); decayDurationRamper.init(); sustainLevelRamper.init(); releaseDurationRamper.init(); pitchBendRamper.init(); vibratoDepthRamper.init(); vibratoRateRamper.init(); filterCutoffFrequencyRamper.init(); filterResonanceRamper.init(); filterAttackDurationRamper.init(); filterDecayDurationRamper.init(); filterSustainLevelRamper.init(); filterReleaseDurationRamper.init(); filterEnvelopeStrengthRamper.init(); filterLFODepthRamper.init(); filterLFORateRamper.init(); } virtual void reset() { for (auto& state : noteStates) state->clear(); playingNotes = nullptr; playingNotesCount = 0; resetted = true; attackDurationRamper.reset(); decayDurationRamper.reset(); sustainLevelRamper.reset(); releaseDurationRamper.reset(); pitchBendRamper.reset(); vibratoDepthRamper.reset(); vibratoRateRamper.reset(); filterCutoffFrequencyRamper.reset(); filterResonanceRamper.reset(); filterAttackDurationRamper.reset(); filterDecayDurationRamper.reset(); filterSustainLevelRamper.reset(); filterReleaseDurationRamper.reset(); filterEnvelopeStrengthRamper.reset(); filterLFODepthRamper.reset(); filterLFORateRamper.reset(); } double frequencyScale = 2. * M_PI / sampleRate; float attackDuration = 0.1; float decayDuration = 0.1; float sustainLevel = 1.0; float releaseDuration = 0.1; float pitchBend = 0; float vibratoDepth = 0; float vibratoRate = 0; float filterCutoffFrequency = 22050.0; float filterResonance = 0.0; float filterAttackDuration = 0.1; float filterDecayDuration = 0.1; float filterSustainLevel = 1.0; float filterReleaseDuration = 0.1; float filterEnvelopeStrength = 0.0; float filterLFODepth = 0.0; float filterLFORate = 0.0; UInt64 currentRunningIndex = 0; std::vector< std::unique_ptr<NoteState> > noteStates; NoteState *playingNotes = nullptr; int playingNotesCount = 0; bool resetted = false; ParameterRamper attackDurationRamper = 0.1; ParameterRamper decayDurationRamper = 0.1; ParameterRamper sustainLevelRamper = 1.0; ParameterRamper releaseDurationRamper = 0.1; ParameterRamper pitchBendRamper = 0; ParameterRamper vibratoDepthRamper = 0; ParameterRamper vibratoRateRamper = 0; ParameterRamper filterCutoffFrequencyRamper = 0.1; ParameterRamper filterResonanceRamper = 0.1; ParameterRamper filterAttackDurationRamper = 0.1; ParameterRamper filterDecayDurationRamper = 0.1; ParameterRamper filterSustainLevelRamper = 1.0; ParameterRamper filterReleaseDurationRamper = 0.1; ParameterRamper filterEnvelopeStrengthRamper = 0.0; ParameterRamper filterLFODepthRamper = 0; ParameterRamper filterLFORateRamper = 0; // standard filter synth kernel functions void startNote(int note, int velocity) { noteStates[note]->noteOn(note, velocity); } void startNote(int note, int velocity, float frequency) { noteStates[note]->noteOn(note, velocity, frequency); } void stopNote(int note) { noteStates[note]->noteOn(note, 0); } void setAttackDuration(float value) { attackDuration = clamp(value, 0.0f, 99.0f); attackDurationRamper.setImmediate(attackDuration); } void setDecayDuration(float value) { decayDuration = clamp(value, 0.0f, 99.0f); decayDurationRamper.setImmediate(decayDuration); } void setSustainLevel(float value) { sustainLevel = clamp(value, 0.0f, 99.0f); sustainLevelRamper.setImmediate(sustainLevel); } void setReleaseDuration(float value) { releaseDuration = clamp(value, 0.0f, 99.0f); releaseDurationRamper.setImmediate(releaseDuration); } void setPitchBend(float value) { pitchBend = clamp(value, (float)-48, (float)48); pitchBendRamper.setImmediate(pitchBend); } void setVibratoDepth(float value) { vibratoDepth = clamp(value, (float)0, (float)24); vibratoDepthRamper.setImmediate(vibratoDepth); } void setVibratoRate(float value) { vibratoRate = clamp(value, (float)0, (float)600); vibratoRateRamper.setImmediate(vibratoRate); } void setFilterCutoffFrequency(float value) { filterCutoffFrequency = clamp(value, 0.0f, 22050.0f); filterCutoffFrequencyRamper.setImmediate(filterCutoffFrequency); } void setFilterResonance(float value) { filterResonance = clamp(value, 0.0f, 0.99f); filterResonanceRamper.setImmediate(filterResonance); } void setFilterAttackDuration(float value) { filterAttackDuration = clamp(value, 0.0f, 99.0f); filterAttackDurationRamper.setImmediate(filterAttackDuration); } void setFilterDecayDuration(float value) { filterDecayDuration = clamp(value, 0.0f, 99.0f); filterDecayDurationRamper.setImmediate(filterDecayDuration); } void setFilterSustainLevel(float value) { filterSustainLevel = clamp(value, 0.0f, 99.0f); filterSustainLevelRamper.setImmediate(filterSustainLevel); } void setFilterReleaseDuration(float value) { filterReleaseDuration = clamp(value, 0.0f, 99.0f); filterReleaseDurationRamper.setImmediate(filterReleaseDuration); } void setFilterEnvelopeStength(float value) { filterEnvelopeStrength = clamp(value, 0.0f, 1.0f); filterEnvelopeStrengthRamper.setImmediate(filterEnvelopeStrength); } void setFilterLFODepth(float value) { filterLFODepth = clamp(value, 0.0f, 1.0f); filterLFODepthRamper.setImmediate(filterLFODepth); } void setFilterLFORate(float value) { filterLFORate = clamp(value, 0.0f, 600.0f); filterLFORateRamper.setImmediate(filterLFORate); } virtual void handleMIDIEvent(AUMIDIEvent const& midiEvent) override { if (midiEvent.length != 3) return; uint8_t status = midiEvent.data[0] & 0xF0; switch (status) { case 0x80 : { uint8_t note = midiEvent.data[1]; if (note > 127) break; noteStates[note]->noteOn(note, 0); break; } case 0x90 : { uint8_t note = midiEvent.data[1]; uint8_t veloc = midiEvent.data[2]; if (note > 127 || veloc > 127) break; noteStates[note]->noteOn(note, veloc); break; } case 0xB0 : { uint8_t num = midiEvent.data[1]; if (num == 123) { NoteState *noteState = playingNotes; while (noteState) { noteState->clear(); noteState = noteState->next; } playingNotes = nullptr; playingNotesCount = 0; } break; } } } void standardFilterSynthGetAndSteps() { attackDuration = attackDurationRamper.getAndStep(); decayDuration = decayDurationRamper.getAndStep(); sustainLevel = sustainLevelRamper.getAndStep(); releaseDuration = releaseDurationRamper.getAndStep(); pitchBend = double(pitchBendRamper.getAndStep()); vibratoDepth = double(vibratoDepthRamper.getAndStep()); vibratoRate = double(vibratoRateRamper.getAndStep()); filterCutoffFrequency = double(filterCutoffFrequencyRamper.getAndStep()); filterResonance = double(filterResonanceRamper.getAndStep()); filterAttackDuration = filterAttackDurationRamper.getAndStep(); filterDecayDuration = filterDecayDurationRamper.getAndStep(); filterSustainLevel = filterSustainLevelRamper.getAndStep(); filterReleaseDuration = filterReleaseDurationRamper.getAndStep(); filterEnvelopeStrength = filterEnvelopeStrengthRamper.getAndStep(); filterLFODepth = filterLFODepthRamper.getAndStep(); filterLFORate = filterLFORateRamper.getAndStep(); } void setParameter(AUParameterAddress address, AUValue value) { switch (address) { case attackDurationAddress: attackDurationRamper.setUIValue(clamp(value, 0.0f, 99.0f)); break; case decayDurationAddress: decayDurationRamper.setUIValue(clamp(value, 0.0f, 99.0f)); break; case sustainLevelAddress: sustainLevelRamper.setUIValue(clamp(value, 0.0f, 99.0f)); break; case releaseDurationAddress: releaseDurationRamper.setUIValue(clamp(value, 0.0f, 99.0f)); break; case pitchBendAddress: pitchBendRamper.setUIValue(clamp(value, (float)-24, (float)24)); break; case vibratoDepthAddress: vibratoDepthRamper.setUIValue(clamp(value, (float)0, (float)24)); break; case vibratoRateAddress: vibratoRateRamper.setUIValue(clamp(value, (float)0, (float)600)); break; case filterCutoffFrequencyAddress: filterCutoffFrequencyRamper.setUIValue(clamp(value, 0.0f, 22050.0f)); break; case filterResonanceAddress: filterResonanceRamper.setUIValue(clamp(value, 0.0f, 0.99f)); break; case filterAttackDurationAddress: filterAttackDurationRamper.setUIValue(clamp(value, 0.0f, 99.0f)); break; case filterDecayDurationAddress: filterDecayDurationRamper.setUIValue(clamp(value, 0.0f, 99.0f)); break; case filterSustainLevelAddress: filterSustainLevelRamper.setUIValue(clamp(value, 0.0f, 99.0f)); break; case filterReleaseDurationAddress: filterReleaseDurationRamper.setUIValue(clamp(value, 0.0f, 99.0f)); break; case filterEnvelopeStrengthAddress: filterEnvelopeStrengthRamper.setUIValue(clamp(value, 0.0f, 1.0f)); break; case filterLFODepthAddress: filterLFODepthRamper.setUIValue(clamp(value, 0.0f, 1.0f)); break; case filterLFORateAddress: filterLFORateRamper.setUIValue(clamp(value, 0.0f, 600.0f)); break; } } AUValue getParameter(AUParameterAddress address) { switch (address) { case attackDurationAddress: \ return attackDurationRamper.getUIValue(); \ case decayDurationAddress: \ return decayDurationRamper.getUIValue(); \ case sustainLevelAddress: \ return sustainLevelRamper.getUIValue(); \ case releaseDurationAddress: \ return releaseDurationRamper.getUIValue(); \ case pitchBendAddress: \ return pitchBendRamper.getUIValue(); \ case vibratoDepthAddress: \ return vibratoDepthRamper.getUIValue(); \ case vibratoRateAddress: \ return vibratoRateRamper.getUIValue(); \ case filterCutoffFrequencyAddress: return filterCutoffFrequencyRamper.getUIValue(); \ case filterResonanceAddress: return filterResonanceRamper.getUIValue(); \ case filterAttackDurationAddress: return filterAttackDurationRamper.getUIValue(); \ case filterDecayDurationAddress: return filterDecayDurationRamper.getUIValue(); \ case filterSustainLevelAddress: return filterSustainLevelRamper.getUIValue(); \ case filterReleaseDurationAddress: return filterReleaseDurationRamper.getUIValue(); \ case filterEnvelopeStrengthAddress: return filterEnvelopeStrengthRamper.getUIValue(); \ case filterLFODepthAddress: return filterLFODepthRamper.getUIValue(); \ case filterLFORateAddress: return filterLFORateRamper.getUIValue(); \ default: return 0.0f; } } void startRamp(AUParameterAddress address, AUValue value, AUAudioFrameCount duration) override { switch (address) { case attackDurationAddress: attackDurationRamper.startRamp(clamp(value, 0.0f, 99.0f), duration); break; case decayDurationAddress: decayDurationRamper.startRamp(clamp(value, 0.0f, 99.0f), duration); break; case sustainLevelAddress: sustainLevelRamper.startRamp(clamp(value, 0.0f, 99.0f), duration); break; case releaseDurationAddress: releaseDurationRamper.startRamp(clamp(value, 0.0f, 99.0f), duration); break; case pitchBendAddress: pitchBendRamper.startRamp(clamp(value, (float)-24, (float)24), duration); break; case vibratoDepthAddress: vibratoDepthRamper.startRamp(clamp(value, (float)0, (float)24), duration); break; case vibratoRateAddress: vibratoRateRamper.startRamp(clamp(value, (float)0, (float)600), duration); break; case filterCutoffFrequencyAddress: filterCutoffFrequencyRamper.startRamp(clamp(value, 0.0f, 22050.0f), duration); break; case filterResonanceAddress: filterResonanceRamper.startRamp(clamp(value, 0.0f, 0.99f), duration); break; case filterAttackDurationAddress: filterAttackDurationRamper.startRamp(clamp(value, 0.0f, 99.0f), duration); break; case filterDecayDurationAddress: filterDecayDurationRamper.startRamp(clamp(value, 0.0f, 99.0f), duration); break; case filterSustainLevelAddress: filterSustainLevelRamper.startRamp(clamp(value, 0.0f, 99.0f), duration); break; case filterReleaseDurationAddress: filterReleaseDurationRamper.startRamp(clamp(value, 0.0f, 99.0f), duration); break; case filterEnvelopeStrengthAddress: filterEnvelopeStrengthRamper.startRamp(clamp(value, 0.0f, 1.0f), duration); break; case filterLFODepthAddress: filterLFODepthRamper.startRamp(clamp(value, 0.0f, 1.0f), duration); break; case filterLFORateAddress: filterLFORateRamper.startRamp(clamp(value, 0.0f, 600.0f), duration); break; } } }; #endif // #ifdef __cplusplus
/********************************************************************** * Copyright (c) 2008-2015, Alliance for Sustainable Energy. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********************************************************************/ #ifndef MODEL_FANZONEEXHAUST_IMPL_HPP #define MODEL_FANZONEEXHAUST_IMPL_HPP #include "ModelAPI.hpp" #include "ZoneHVACComponent_Impl.hpp" namespace openstudio { namespace model { class Schedule; namespace detail { /** FanZoneExhaust_Impl is a ZoneHVACComponent_Impl that is the implementation class for FanZoneExhaust.*/ class MODEL_API FanZoneExhaust_Impl : public ZoneHVACComponent_Impl { public: /** @name Constructors and Destructors */ //@{ FanZoneExhaust_Impl(const IdfObject& idfObject, Model_Impl* model, bool keepHandle); FanZoneExhaust_Impl(const openstudio::detail::WorkspaceObject_Impl& other, Model_Impl* model, bool keepHandle); FanZoneExhaust_Impl(const FanZoneExhaust_Impl& other, Model_Impl* model, bool keepHandle); virtual ~FanZoneExhaust_Impl() {} //@} /** @name Virtual Methods */ //@{ virtual const std::vector<std::string>& outputVariableNames() const; virtual IddObjectType iddObjectType() const; virtual std::vector<ScheduleTypeKey> getScheduleTypeKeys(const Schedule& schedule) const; virtual boost::optional<ThermalZone> thermalZone(); virtual bool addToThermalZone(ThermalZone & thermalZone); virtual unsigned inletPort() const; virtual unsigned outletPort() const; //@} /** @name Getters */ //@{ boost::optional<Schedule> availabilitySchedule() const; double fanEfficiency() const; double pressureRise() const; boost::optional<double> maximumFlowRate() const; std::string endUseSubcategory() const; boost::optional<Schedule> flowFractionSchedule() const; std::string systemAvailabilityManagerCouplingMode() const; boost::optional<Schedule> minimumZoneTemperatureLimitSchedule() const; boost::optional<Schedule> balancedExhaustFractionSchedule() const; //@} /** @name Setters */ //@{ bool setAvailabilitySchedule(Schedule& schedule); void resetAvailabilitySchedule(); bool setFanEfficiency(double fanEfficiency); void setPressureRise(double pressureRise); bool setMaximumFlowRate(boost::optional<double> maximumFlowRate); void resetMaximumFlowRate(); void setEndUseSubcategory(std::string endUseSubcategory); bool setFlowFractionSchedule(Schedule& schedule); void resetFlowFractionSchedule(); bool setSystemAvailabilityManagerCouplingMode(std::string systemAvailabilityManagerCouplingMode); bool setMinimumZoneTemperatureLimitSchedule(Schedule& schedule); void resetMinimumZoneTemperatureLimitSchedule(); bool setBalancedExhaustFractionSchedule(Schedule& schedule); void resetBalancedExhaustFractionSchedule(); //@} /** @name Other */ //@{ //@} protected: private: REGISTER_LOGGER("openstudio.model.FanZoneExhaust"); }; } // detail } // model } // openstudio #endif // MODEL_FANZONEEXHAUST_IMPL_HPP
#ifndef CPPURSES_DEMOS_PALETTE_COLOR_DISPLAY_HPP #define CPPURSES_DEMOS_PALETTE_COLOR_DISPLAY_HPP #include <cppurses/painter/color.hpp> #include <cppurses/widget/layouts/horizontal.hpp> #include <cppurses/widget/layouts/vertical.hpp> #include <cppurses/widget/widget.hpp> #include <cppurses/widget/widgets/text_display.hpp> namespace palette { /// Square visual display of a given Color. struct Color_patch : cppurses::Widget { explicit Color_patch(cppurses::Color value); void set_color(cppurses::Color value); }; /// Title and name display of a given Color. struct Color_name : cppurses::layout::Vertical { cppurses::Text_display& title{ this->make_child<cppurses::Text_display>("Color:")}; cppurses::Text_display& name{ this->make_child<cppurses::Text_display>("White")}; }; /// Displays a text name and a square visual of a given Color. struct Color_display : cppurses::layout::Horizontal { explicit Color_display(cppurses::Color color); /// Change the currently displayed color. void set_color(cppurses::Color color); Color_name& text{this->make_child<Color_name>()}; Color_patch& square{this->make_child<Color_patch>(cppurses::Color::White)}; }; } // namespace palette #endif // CPPURSES_DEMOS_PALETTE_COLOR_DISPLAY_HPP
////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2011-2013, John Haddon. All rights reserved. // Copyright (c) 2012, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above // copyright notice, this list of conditions and the following // disclaimer. // // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided with // the distribution. // // * Neither the name of John Haddon nor the names of // any other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "GafferUI/Style.h" #include "GafferUI/StandardStyle.h" #include "IECore/Exception.h" #include "IECore/SimpleTypedData.h" using namespace GafferUI; IE_CORE_DEFINERUNTIMETYPED( Style ); StylePtr Style::g_defaultStyle = new StandardStyle; Style::Style() { } Style::~Style() { } Style::UnarySignal &Style::changedSignal() { return m_changedSignal; } StylePtr Style::getDefaultStyle() { return g_defaultStyle; } void Style::setDefaultStyle( StylePtr style ) { g_defaultStyle = style; }
/* * If not stated otherwise in this file or this component's LICENSE file the * following copyright and licenses apply: * * Copyright 2020 RDK Management * * 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 "NexusServer.h" #include <nexus_config.h> #include <nexus_platform.h> #include <nexus_types.h> #include <nxclient.h> #include <nexus_display_vbi.h> #if NEXUS_HAS_VIDEO_DECODER #include <nexus_video_decoder.h> #endif #include <nexus_display.h> #include <sys/stat.h> BDBG_MODULE(NexusServer); namespace WPEFramework { namespace Broadcom { /* virtual */ string Platform::Client::Name() const { return (::std::string(Id())); } /* virtual */ void Platform::Client::Opacity(const uint32_t value) { ASSERT(_client != nullptr); TRACE(Trace::Information, (_T("Alpha client %s to %d."), Name().c_str(), value)); nxserverlib_set_server_alpha(_client, value); } uint32_t Platform::Client::Geometry(const Exchange::IComposition::Rectangle& rectangle) /* override */ { ASSERT(_client != nullptr); _rectangle = rectangle; return (Core::ERROR_UNAVAILABLE); } Exchange::IComposition::Rectangle Platform::Client::Geometry() const /* override */ { ASSERT(_client != nullptr); return (_rectangle); } uint32_t Platform::Client::ZOrder(const uint16_t index) /* override */ { uint32_t result = Core::ERROR_UNAVAILABLE; _layer = index; ASSERT(_client != nullptr); if (_layer == 0) { result = Core::ERROR_NONE; /* the definition of "focus" is variable. this is one impl. */ NxClient_ConnectList list; struct nxclient_status status; nxclient_get_status(_client, &status); NxClient_P_Config_GetConnectList(_client, status.handle, &list); /* only refresh first connect */ if (list.connectId[0]) { NxClient_P_RefreshConnect(_client, list.connectId[0]); } nxserver_p_focus_input_client(_client); nxserver_p_focus_surface_client(_client); } return (result); } uint32_t Platform::Client::ZOrder() const { return _layer; } class Config : public Core::JSON::Container { private: Config(const Config&) = delete; Config& operator=(const Config&) = delete; public: enum svptype { NONE = nxserverlib_svp_type_none, VIDEO = nxserverlib_svp_type_cdb, /* Force CRR for video CDB */ ALL = nxserverlib_svp_type_cdb_urr /* Force CRR for video CDB + default to all secure only buffers */ }; enum hdcplevel { HDCP_NONE = NxClient_HdcpLevel_eNone, /* No HDCP requested by this client. */ HDCP_OPTIONAL = NxClient_HdcpLevel_eOptional, /* Enable HDCP but do not mute video, even on authentication failure. */ HDCP_MANDATORY = NxClient_HdcpLevel_eMandatory /* Enable HDCP and mute video until authentication success. */ }; enum hdcpversion { AUTO = NxClient_HdcpVersion_eAuto, /* Always authenticate using the highest version supported by HDMI receiver (Content Stream Type 0) */ HDCP1X = NxClient_HdcpVersion_eHdcp1x, /* Always authenticate using HDCP 1.x mode (regardless of HDMI Receiver capabilities) */ HDCP22 = NxClient_HdcpVersion_eHdcp22 /* Always authenticate using HDCP 2.2 mode, Content Stream Type 1 */ }; enum loudnessmode { LM_NONE = NEXUS_AudioLoudnessEquivalenceMode_eNone, /* Default, no loudness equivalence. */ LM_ATSC_A85 = NEXUS_AudioLoudnessEquivalenceMode_eAtscA85, /* ATSC A/85. */ LM_EBU_R128 = NEXUS_AudioLoudnessEquivalenceMode_eEbuR128 /* EBU-R128. */ }; class MemoryInfo : public Core::JSON::Container { private: MemoryInfo(const MemoryInfo&) = delete; MemoryInfo& operator=(const MemoryInfo&) = delete; public: MemoryInfo() : GFX() , GFX2() , Restricted() , Main() , Export() , Client() , SecureGFX() { Add(_T("gfx"), &GFX); Add(_T("gfx2"), &GFX2); Add(_T("restricted"), &Restricted); Add(_T("main"), &Main); Add(_T("export"), &Export); Add(_T("client"), &Client); Add(_T("secureGFX"), &SecureGFX); } ~MemoryInfo() { } public: Core::JSON::DecUInt16 GFX; Core::JSON::DecUInt16 GFX2; Core::JSON::DecUInt16 Restricted; Core::JSON::DecUInt16 Main; Core::JSON::DecUInt16 Export; Core::JSON::DecUInt16 Client; Core::JSON::DecUInt16 SecureGFX; }; public: Config() : Core::JSON::Container() , IRMode(NEXUS_IrInputMode_eCirNec) , Authentication(true) , BoxMode(~0) , SagePath() , PAKPath() , DRMPath() , SVPType(NONE) , Memory() , HDCPLevel(HDCP_NONE) , HDCPVersion(AUTO) , HDCP1xBinFile() , HDCP2xBinFile() , LoudnessMode(LM_NONE) { Add(_T("irmode"), &IRMode); Add(_T("authentication"), &Authentication); Add(_T("boxmode"), &BoxMode); Add(_T("sagepath"), &SagePath); Add(_T("pakpath"), &PAKPath); Add(_T("drmpath"), &DRMPath); Add(_T("svp"), &SVPType); Add(_T("memory"), &Memory); Add(_T("framebufferwidth"), &FrameBufferWidth); Add(_T("framebufferheight"), &FrameBufferHeight); Add(_T("hdcplevel"), &HDCPLevel); Add(_T("hdcpversion"), &HDCPVersion); Add(_T("hdcp1xbinfile"), &HDCP1xBinFile); Add(_T("hdcp2xbinfile"), &HDCP2xBinFile); Add(_T("loudnessmode"), &LoudnessMode); } ~Config() { } public: Core::JSON::EnumType<NEXUS_IrInputMode> IRMode; Core::JSON::Boolean Authentication; Core::JSON::DecUInt8 BoxMode; Core::JSON::String SagePath; Core::JSON::String PAKPath; Core::JSON::String DRMPath; Core::JSON::EnumType<svptype> SVPType; MemoryInfo Memory; Core::JSON::DecUInt16 FrameBufferWidth; Core::JSON::DecUInt16 FrameBufferHeight; Core::JSON::EnumType<hdcplevel> HDCPLevel; Core::JSON::EnumType<hdcpversion> HDCPVersion; Core::JSON::String HDCP1xBinFile; Core::JSON::String HDCP2xBinFile; Core::JSON::EnumType<loudnessmode> LoudnessMode; }; /* ------------------------------------------------------------------------------------------------------------- * This is a singleton. Declare all C accessors to this object here * ------------------------------------------------------------------------------------------------------------- */ /* static */ Platform* Platform::_implementation = nullptr; static int find_unused_heap(const NEXUS_PlatformSettings& platformSettings) { for (int i = NEXUS_MAX_HEAPS - 1; i < NEXUS_MAX_HEAPS; i--) { if (!platformSettings.heap[i].size && !platformSettings.heap[i].heapType) return i; } return -1; } /* static */ void Platform::CloseDown() { // Seems we are destructed.....If we still have a pointer to the implementation, Kill it.. if (_implementation != nullptr) { delete _implementation; _implementation = nullptr; } } template <typename... T> /* static */ int Platform::ClientConnect(nxclient_t client, const NxClient_JoinSettings* pJoinSettings, NEXUS_ClientSettings* pClientSettings, T... Targs) { BSTD_UNUSED(pClientSettings); if (_implementation != nullptr) { /* server app has opportunity to reject client altogether, or modify pClientSettings */ _implementation->Add(client, pJoinSettings); } return (0); } /* static */ void Platform::ClientDisconnect(nxclient_t client, const NxClient_JoinSettings* pJoinSettings) { BSTD_UNUSED(pJoinSettings); if (_implementation != nullptr) { _implementation->Remove(pJoinSettings->name); } } Platform::~Platform() { _state = DEINITIALIZING; nxserver_ipc_uninit(); nxserverlib_uninit(_instance); NEXUS_Platform_Uninit(); BKNI_DestroyMutex(_lock); _implementation = nullptr; } Platform::Platform(IStateChange* stateChanges, IClient* clientChanges, const std::string& configuration, const NEXUS_VideoFormat& format) : _lock() , _instance() , _serverSettings() , _platformSettings() , _platformCapabilities() , _state(UNITIALIZED) , _clientHandler(clientChanges) , _stateHandler(stateChanges) { ASSERT(_implementation == nullptr); ASSERT(_instance == nullptr); // Strange someone already started a NXServer. if (_instance == nullptr) { _implementation = this; NEXUS_Error rc = NEXUS_SUCCESS; // Register an @Exit, in case we are killed, with an incorrect ref count !! if (atexit(CloseDown) != 0) { TRACE(Trace::Information, (("Could not register @exit handler. Error: %d."), errno)); exit(EXIT_FAILURE); } TRACE_L1("Start Nexus server...%d\n", __LINE__); Config config; config.FromString(configuration); if ((config.SagePath.IsSet() == true) && (config.SagePath.Value().empty() == false)) { ::setenv("SAGEBIN_PATH", config.SagePath.Value().c_str(), 1); } if ((config.PAKPath.IsSet() == true) && (config.PAKPath.Value().empty() == false)) { ::setenv("PAKBIN_PATH", config.PAKPath.Value().c_str(), 1); } if ((config.DRMPath.IsSet() == true) && (config.DRMPath.Value().empty() == false)) { ::setenv("DRMBIN_PATH", config.DRMPath.Value().c_str(), 1); } if (config.BoxMode.IsSet()) { // Set box mode using env var. char stringNumber[10]; snprintf(stringNumber, sizeof(stringNumber), "%d", config.BoxMode.Value()); ::setenv("B_REFSW_BOXMODE", stringNumber, 1); TRACE_L1("Set BoxMode to %d\n", config.BoxMode.Value()); } nxserver_get_default_settings(&(_serverSettings)); NEXUS_Platform_GetDefaultSettings(&(_platformSettings)); NEXUS_GetDefaultMemoryConfigurationSettings(&(_serverSettings.memConfigSettings)); NEXUS_GetPlatformCapabilities(&(_platformCapabilities)); if (config.Memory.IsSet()) { const Config::MemoryInfo& memory(config.Memory); if (memory.GFX.IsSet()) { int index = nxserver_heap_by_type(&_platformSettings, NEXUS_HEAP_TYPE_GRAPHICS); if (index != -1) { TRACE_L1("Setting gfx heap[%d] to %dMB", index, memory.GFX.Value()); _platformSettings.heap[index].size = (memory.GFX.Value() * 1024 * 1024); } } if (memory.GFX2.IsSet()) { int index = nxserver_heap_by_type(&_platformSettings, NEXUS_HEAP_TYPE_SECONDARY_GRAPHICS); if (index != -1) { TRACE_L1("Setting gfx2 heap[%d] to %dMB", index, memory.GFX2.Value()); _platformSettings.heap[index].size = (memory.GFX2.Value() * 1024 * 1024); } } if (memory.Restricted.IsSet()) { int index = nxserver_heap_by_type(&_platformSettings, NEXUS_HEAP_TYPE_COMPRESSED_RESTRICTED_REGION); if (index != -1) { TRACE_L1("Setting secure video heap[%d] to %dMB", index, memory.Restricted.Value()); _platformSettings.heap[index].size = (memory.Restricted.Value() * 1024 * 1024); } } if (memory.Main.IsSet()) { int index = nxserver_heap_by_type(&_platformSettings, NEXUS_HEAP_TYPE_MAIN); if (index != -1) { TRACE_L1("Setting main heap[%d] to %dMB", index, memory.Main.Value()); _platformSettings.heap[index].size = (memory.Main.Value() * 1024 * 1024); } } if (memory.Export.IsSet()) { int index = nxserver_heap_by_type(&_platformSettings, NEXUS_HEAP_TYPE_EXPORT_REGION); if (index != -1) { TRACE_L1("Setting export heap[%d] to %dMB", index, memory.Export.Value()); _platformSettings.heap[index].size = (memory.Export.Value() * 1024 * 1024); } } if (memory.Client.IsSet()) { /* create a dedicated heap for the client */ int mainIndex = nxserver_heap_by_type(&_platformSettings, NEXUS_HEAP_TYPE_GRAPHICS); if (mainIndex != -1) { int unused_heap = find_unused_heap(_platformSettings); if (unused_heap != -1) { TRACE_L1("Setting client heap[%d] to %dMB", unused_heap, memory.Client.Value()); _serverSettings.heaps.clientFullHeap = unused_heap; _platformSettings.heap[_serverSettings.heaps.clientFullHeap].size = (memory.Client.Value() * 1024 * 1024); _platformSettings.heap[_serverSettings.heaps.clientFullHeap].memcIndex = _platformSettings.heap[mainIndex].memcIndex; _platformSettings.heap[_serverSettings.heaps.clientFullHeap].subIndex = _platformSettings.heap[mainIndex].subIndex; _platformSettings.heap[_serverSettings.heaps.clientFullHeap].guardBanding = false; /* corruptions shouldn't cause server failures */ _platformSettings.heap[_serverSettings.heaps.clientFullHeap].alignment = _platformSettings.heap[mainIndex].alignment; _platformSettings.heap[_serverSettings.heaps.clientFullHeap].memoryType = NEXUS_MemoryType_eFull; /* requires for packet blit and playpump */ #if NEXUS_HAS_SAGE /* sage must be told which heap the client's will be using */ _platformSettings.sageModuleSettings.clientHeapIndex = _serverSettings.heaps.clientFullHeap; #endif } } } if (memory.SecureGFX.IsSet()) { NEXUS_PlatformConfigCapabilities cap; NEXUS_GetPlatformConfigCapabilities(&_platformSettings, &(_serverSettings.memConfigSettings), &cap); if (cap.secureGraphics[0].valid) { TRACE_L1("creating securegfx heap[%d] on MEMC%u for %dMB", cap.secureGraphics[0].heapIndex, cap.secureGraphics[0].memcIndex, memory.SecureGFX.Value()); _platformSettings.heap[cap.secureGraphics[0].heapIndex].size = (memory.SecureGFX.Value() * 1024 * 1024); _platformSettings.heap[cap.secureGraphics[0].heapIndex].memcIndex = cap.secureGraphics[0].memcIndex; _platformSettings.heap[cap.secureGraphics[0].heapIndex].heapType = NEXUS_HEAP_TYPE_SECURE_GRAPHICS; _platformSettings.heap[cap.secureGraphics[0].heapIndex].memoryType = NEXUS_MEMORY_TYPE_ONDEMAND_MAPPED | NEXUS_MEMORY_TYPE_MANAGED | NEXUS_MEMORY_TYPE_SECURE; /* TODO: allow securegfx to GFD1. for now, apply "-sd off" */ _serverSettings.session[0].output.sd = false; _serverSettings.session[0].output.hd = true; _serverSettings.session[0].output.encode = false; } } } if (format != NEXUS_VideoFormat_eUnknown) { _serverSettings.display.format = format; } if (config.SVPType.IsSet() == true) { _serverSettings.svp = static_cast<nxserverlib_svp_type>(config.SVPType.Value()); } /* display[1] will always be either SD or transcode */ if (!_platformCapabilities.display[1].supported || _platformCapabilities.display[1].encoder) { for (unsigned int i = 0; i < NXCLIENT_MAX_SESSIONS; i++) _serverSettings.session[i].output.sd = false; } /* display[0] will always be either HD, or system is headless */ if (!_platformCapabilities.display[0].supported || _platformCapabilities.display[0].encoder) { for (unsigned int i = 0; i < NXCLIENT_MAX_SESSIONS; i++) _serverSettings.session[i].output.hd = false; } #if NEXUS_HAS_IR_INPUT if (config.IRMode.IsSet()) { TRACE_L1("setting ir_input_mode to %d (%s)", config.IRMode.Value(), config.IRMode.Data()); for (unsigned int i = 0; i < NXCLIENT_MAX_SESSIONS; i++) #if NEXUS_PLATFORM_VERSION_MAJOR < 16 || (NEXUS_PLATFORM_VERSION_MAJOR == 16 && NEXUS_PLATFORM_VERSION_MINOR < 3) _serverSettings.session[i].ir_input_mode = config.IRMode.Value(); #else for (unsigned int irInputIndex = 0; irInputIndex < NXSERVER_IR_INPUTS; irInputIndex++) { _serverSettings.session[i].ir_input.mode[irInputIndex] = config.IRMode.Value(); } #endif // NEXUS_PLATFORM_VERSION_MAJOR < 17 } else { TRACE_L1("invalid ir_input_mode from config"); } #endif // NEXUS_HAS_IR_INPUT struct nxserver_cmdline_settings cmdline_settings; memset(&cmdline_settings, 0, sizeof(cmdline_settings)); cmdline_settings.frontend = true; cmdline_settings.loudnessMode = static_cast<NEXUS_AudioLoudnessEquivalenceMode>(config.LoudnessMode.Value()); _serverSettings.session[0].dolbyMs = nxserverlib_dolby_ms_type_none; if (config.FrameBufferWidth.IsSet() && config.FrameBufferHeight.IsSet()) { _serverSettings.fbsize.width = config.FrameBufferWidth.Value(); _serverSettings.fbsize.height = config.FrameBufferHeight.Value(); } if (config.HDCPLevel.Value() != Config::HDCP_NONE) { _serverSettings.hdcp.alwaysLevel = static_cast<NxClient_HdcpLevel>(config.HDCPLevel.Value()); _serverSettings.hdcp.versionSelect = static_cast<NxClient_HdcpVersion>(config.HDCPVersion.Value()); /* set the hdcp1x bin file path */ if ((config.HDCP1xBinFile.IsSet() == true) && (config.HDCP1xBinFile.Value().empty() == false)) { snprintf(_serverSettings.hdcp.hdcp1xBinFile, sizeof(_serverSettings.hdcp.hdcp1xBinFile), "%s", config.HDCP1xBinFile.Value().c_str()); } /* set the hdcp2x bin file path */ if ((config.HDCP2xBinFile.IsSet() == true) && (config.HDCP2xBinFile.Value().empty() == false)) { snprintf(_serverSettings.hdcp.hdcp2xBinFile, sizeof(_serverSettings.hdcp.hdcp2xBinFile), "%s", config.HDCP2xBinFile.Value().c_str()); } } rc = nxserver_modify_platform_settings(&_serverSettings, &cmdline_settings, &_platformSettings, &_serverSettings.memConfigSettings); if (rc == NEXUS_SUCCESS) { rc = NEXUS_Platform_MemConfigInit(&_platformSettings, &_serverSettings.memConfigSettings); if (rc == NEXUS_SUCCESS) { BKNI_CreateMutex(&_lock); _serverSettings.lock = _lock; nxserver_set_client_heaps(&_serverSettings, &_platformSettings); _serverSettings.client.connect = Platform::ClientConnect; _serverSettings.client.disconnect = Platform::ClientDisconnect; #if NEXUS_SERVER_HAS_EXTENDED_INIT _instance = nxserverlib_init_extended(&_serverSettings, config.Authentication.Value()); #else _instance = nxserverlib_init(&_serverSettings); #endif if (_instance != nullptr) { rc = nxserver_ipc_init(_instance, _lock); if (rc == NEXUS_SUCCESS) { TRACE_L1("Created NexusServer[%p].\n", &_instance); } else { TRACE_L1("nxserver_ipc_init failed [%d]\n", rc); } } else { TRACE_L1("nxserverlib_init_extended failed [%d]\n", rc); } } else { TRACE_L1("NEXUS_Platform_MemConfigInit failed [%d]\n", rc); } } else { TRACE_L1("nxserver_modify_platform_settings failed [%d]\n", rc); } StateChange(rc == NEXUS_SUCCESS ? OPERATIONAL : FAILURE); } ASSERT(_state != FAILURE); } // ------------------------------------------------------------------------------------------------------- // private methods // ------------------------------------------------------------------------------------------------------- void Platform::Add(nxclient_t client, const NxClient_JoinSettings* joinSettings) { TRACE_L1("Nexus client %s connected... \n", joinSettings->name); if (_clientHandler != nullptr) { Exchange::IComposition::IClient* entry(Platform::Client::Create(client, joinSettings)); _clientHandler->Attached(entry); entry->Release(); } } void Platform::Remove(const char clientName[]) { TRACE_L1("Nexus client %s disconnected... \n", clientName); if (_clientHandler != nullptr) { _clientHandler->Detached(clientName); } } void Platform::StateChange(server_state state) { TRACE_L1("Nexus server state change [%d -> %d] \n", _state, state); _state = state; if (_stateHandler != nullptr) { _stateHandler->StateChange(_state); } }; } // Broadcom ENUM_CONVERSION_BEGIN(Broadcom::Config::svptype) { Broadcom::Config::NONE, _TXT("None") }, { Broadcom::Config::VIDEO, _TXT("Video") }, { Broadcom::Config::ALL, _TXT("All") }, ENUM_CONVERSION_END(Broadcom::Config::svptype); ENUM_CONVERSION_BEGIN(Broadcom::Config::hdcplevel) { Broadcom::Config::HDCP_NONE, _TXT("Hdcp_None") }, { Broadcom::Config::HDCP_OPTIONAL, _TXT("Hdcp_Optional") }, { Broadcom::Config::HDCP_MANDATORY, _TXT("Hdcp_Mandatory") }, ENUM_CONVERSION_END(Broadcom::Config::hdcplevel); ENUM_CONVERSION_BEGIN(Broadcom::Config::hdcpversion) { Broadcom::Config::AUTO, _TXT("Auto") }, { Broadcom::Config::HDCP1X, _TXT("Hdcp1x") }, { Broadcom::Config::HDCP22, _TXT("Hdcp22") }, ENUM_CONVERSION_END(Broadcom::Config::hdcpversion); ENUM_CONVERSION_BEGIN(Broadcom::Config::loudnessmode) { Broadcom::Config::LM_NONE, _TXT("None")}, { Broadcom::Config::LM_ATSC_A85, _TXT("ATSC_A85")}, { Broadcom::Config::LM_EBU_R128, _TXT("EBU_R128")}, ENUM_CONVERSION_END(Broadcom::Config::loudnessmode); ENUM_CONVERSION_BEGIN(NEXUS_IrInputMode) { NEXUS_IrInputMode_eTwirpKbd, _TXT("NEXUS_IrInputMode_eTwirpKbd") }, { NEXUS_IrInputMode_eSejin38KhzKbd, _TXT("NEXUS_IrInputMode_eSejin38KhzKbd") }, { NEXUS_IrInputMode_eSejin56KhzKbd, _TXT("NEXUS_IrInputMode_eSejin56KhzKbd") }, { NEXUS_IrInputMode_eRemoteA, _TXT("NEXUS_IrInputMode_eRemoteA") }, { NEXUS_IrInputMode_eRemoteB, _TXT("NEXUS_IrInputMode_eRemoteB") }, { NEXUS_IrInputMode_eCirGI, _TXT("NEXUS_IrInputMode_eCirGI") }, { NEXUS_IrInputMode_eCirSaE2050, _TXT("NEXUS_IrInputMode_eCirSaE2050") }, { NEXUS_IrInputMode_eCirTwirp, _TXT("NEXUS_IrInputMode_eCirTwirp") }, { NEXUS_IrInputMode_eCirSony, _TXT("NEXUS_IrInputMode_eCirSony") }, { NEXUS_IrInputMode_eCirRecs80, _TXT("NEXUS_IrInputMode_eCirRecs80") }, { NEXUS_IrInputMode_eCirRc5, _TXT("NEXUS_IrInputMode_eCirRc5") }, { NEXUS_IrInputMode_eCirUei, _TXT("NEXUS_IrInputMode_eCirUei") }, { NEXUS_IrInputMode_eCirRfUei, _TXT("NEXUS_IrInputMode_eCirRfUei") }, { NEXUS_IrInputMode_eCirEchoStar, _TXT("NEXUS_IrInputMode_eCirEchoStar") }, { NEXUS_IrInputMode_eSonySejin, _TXT("NEXUS_IrInputMode_eSonySejin") }, { NEXUS_IrInputMode_eCirNec, _TXT("NEXUS_IrInputMode_eCirNec") }, { NEXUS_IrInputMode_eCirRC6, _TXT("NEXUS_IrInputMode_eCirRC6") }, { NEXUS_IrInputMode_eCirGISat, _TXT("NEXUS_IrInputMode_eCirGISat") }, { NEXUS_IrInputMode_eCustom, _TXT("NEXUS_IrInputMode_eCustom") }, { NEXUS_IrInputMode_eCirDirectvUhfr, _TXT("NEXUS_IrInputMode_eCirDirectvUhfr") }, { NEXUS_IrInputMode_eCirEchostarUhfr, _TXT("NEXUS_IrInputMode_eCirEchostarUhfr") }, { NEXUS_IrInputMode_eCirRcmmRcu, _TXT("NEXUS_IrInputMode_eCirRcmmRcu") }, { NEXUS_IrInputMode_eCirRstep, _TXT("NEXUS_IrInputMode_eCirRstep") }, { NEXUS_IrInputMode_eCirXmp, _TXT("NEXUS_IrInputMode_eCirXmp") }, { NEXUS_IrInputMode_eCirXmp2Ack, _TXT("NEXUS_IrInputMode_eCirXmp2Ack") }, { NEXUS_IrInputMode_eCirRC6Mode0, _TXT("NEXUS_IrInputMode_eCirRC6Mode0") }, { NEXUS_IrInputMode_eCirRca, _TXT("NEXUS_IrInputMode_eCirRca") }, { NEXUS_IrInputMode_eCirToshibaTC9012, _TXT("NEXUS_IrInputMode_eCirToshibaTC9012") }, { NEXUS_IrInputMode_eCirXip, _TXT("NEXUS_IrInputMode_eCirXip") }, ENUM_CONVERSION_END(NEXUS_IrInputMode) } // WPEFramework
/* Copyright (c) 2005-2019, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Oxford nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "PottsBasedCellPopulation.hpp" #include "RandomNumberGenerator.hpp" #include "AbstractPottsUpdateRule.hpp" #include "NodesOnlyMesh.hpp" #include "CellPopulationElementWriter.hpp" #include "CellIdWriter.hpp" // Needed to convert mesh in order to write nodes to VTK (visualize as glyphs) #include "VtkMeshWriter.hpp" template<unsigned DIM> void PottsBasedCellPopulation<DIM>::Validate() { // Check each element has only one cell associated with it std::vector<unsigned> validated_element = std::vector<unsigned>(this->GetNumElements(), 0); for (typename AbstractCellPopulation<DIM>::Iterator cell_iter = this->Begin(); cell_iter != this->End(); ++cell_iter) { unsigned elem_index = this->GetLocationIndexUsingCell(*cell_iter); validated_element[elem_index]++; } for (unsigned i=0; i<validated_element.size(); i++) { if (validated_element[i] == 0) { EXCEPTION("At time " << SimulationTime::Instance()->GetTime() << ", Element " << i << " does not appear to have a cell associated with it"); } if (validated_element[i] > 1) { EXCEPTION("At time " << SimulationTime::Instance()->GetTime() << ", Element " << i << " appears to have " << validated_element[i] << " cells associated with it"); } } } template<unsigned DIM> PottsBasedCellPopulation<DIM>::PottsBasedCellPopulation(PottsMesh<DIM>& rMesh, std::vector<CellPtr>& rCells, bool deleteMesh, bool validate, const std::vector<unsigned> locationIndices) : AbstractOnLatticeCellPopulation<DIM>(rMesh, rCells, locationIndices, deleteMesh), mpElementTessellation(nullptr), mpMutableMesh(nullptr), mTemperature(0.1), mNumSweepsPerTimestep(1) { mpPottsMesh = static_cast<PottsMesh<DIM>* >(&(this->mrMesh)); // Check each element has only one cell associated with it if (validate) { Validate(); } } template<unsigned DIM> PottsBasedCellPopulation<DIM>::PottsBasedCellPopulation(PottsMesh<DIM>& rMesh) : AbstractOnLatticeCellPopulation<DIM>(rMesh), mpElementTessellation(nullptr), mpMutableMesh(nullptr), mTemperature(0.1), mNumSweepsPerTimestep(1) { mpPottsMesh = static_cast<PottsMesh<DIM>* >(&(this->mrMesh)); } template<unsigned DIM> PottsBasedCellPopulation<DIM>::~PottsBasedCellPopulation() { delete mpElementTessellation; delete mpMutableMesh; if (this->mDeleteMesh) { delete &this->mrMesh; } } template<unsigned DIM> PottsMesh<DIM>& PottsBasedCellPopulation<DIM>::rGetMesh() { return *mpPottsMesh; } template<unsigned DIM> const PottsMesh<DIM>& PottsBasedCellPopulation<DIM>::rGetMesh() const { return *mpPottsMesh; } template<unsigned DIM> TetrahedralMesh<DIM, DIM>* PottsBasedCellPopulation<DIM>::GetTetrahedralMeshForPdeModifier() { std::vector<Node<DIM>*> temp_nodes; // Create nodes at the centre of the cells for (typename AbstractCellPopulation<DIM>::Iterator cell_iter = this->Begin(); cell_iter != this->End(); ++cell_iter) { unsigned index = this->GetLocationIndexUsingCell(*cell_iter); c_vector<double, DIM> location = this->GetLocationOfCellCentre(*cell_iter); temp_nodes.push_back(new Node<DIM>(index, location)); } return new MutableMesh<DIM, DIM>(temp_nodes); } template<unsigned DIM> PottsElement<DIM>* PottsBasedCellPopulation<DIM>::GetElement(unsigned elementIndex) { return mpPottsMesh->GetElement(elementIndex); } template<unsigned DIM> unsigned PottsBasedCellPopulation<DIM>::GetNumElements() { return mpPottsMesh->GetNumElements(); } template<unsigned DIM> Node<DIM>* PottsBasedCellPopulation<DIM>::GetNode(unsigned index) { return this->mrMesh.GetNode(index); } template<unsigned DIM> unsigned PottsBasedCellPopulation<DIM>::GetNumNodes() { return this->mrMesh.GetNumNodes(); } template<unsigned DIM> std::set<unsigned> PottsBasedCellPopulation<DIM>::GetNeighbouringLocationIndices(CellPtr pCell) { unsigned elem_index = this->GetLocationIndexUsingCell(pCell); return mpPottsMesh->GetNeighbouringElementIndices(elem_index); } template<unsigned DIM> c_vector<double, DIM> PottsBasedCellPopulation<DIM>::GetLocationOfCellCentre(CellPtr pCell) { return mpPottsMesh->GetCentroidOfElement(this->GetLocationIndexUsingCell(pCell)); } template<unsigned DIM> PottsElement<DIM>* PottsBasedCellPopulation<DIM>::GetElementCorrespondingToCell(CellPtr pCell) { return mpPottsMesh->GetElement(this->GetLocationIndexUsingCell(pCell)); } template<unsigned DIM> CellPtr PottsBasedCellPopulation<DIM>::AddCell(CellPtr pNewCell, CellPtr pParentCell) { // Get the element associated with this cell PottsElement<DIM>* p_element = GetElementCorrespondingToCell(pParentCell); // Divide the element unsigned new_element_index = mpPottsMesh->DivideElement(p_element, true); // new element will be below the existing element // Associate the new cell with the element this->mCells.push_back(pNewCell); // Update location cell map CellPtr p_created_cell = this->mCells.back(); this->SetCellUsingLocationIndex(new_element_index,p_created_cell); return p_created_cell; } template<unsigned DIM> unsigned PottsBasedCellPopulation<DIM>::RemoveDeadCells() { unsigned num_removed = 0; for (std::list<CellPtr>::iterator cell_iter = this->mCells.begin(); cell_iter != this->mCells.end(); ) { if ((*cell_iter)->IsDead()) { // Get the location index corresponding to this cell unsigned location_index = this->GetLocationIndexUsingCell(*cell_iter); // Use this to remove the cell from the population mpPottsMesh->DeleteElement(location_index); // Erase cell and update counter cell_iter = this->mCells.erase(cell_iter); num_removed++; } else { ++cell_iter; } } return num_removed; } template<unsigned DIM> void PottsBasedCellPopulation<DIM>::UpdateCellLocations(double dt) { /* * This method implements a Monte Carlo method to update the cell population. * We sample randomly from all nodes in the mesh. Once we have selected a target * node we randomly select a neighbour. The Hamiltonian is evaluated in the * current configuration (H_0) and with the target node added to the same * element as the neighbour (H_1). Based on the vale of deltaH = H_1 - H_0, * the switch is either made or not. * * For each time step (i.e. each time this method is called) we sample * mrMesh.GetNumNodes() nodes. This is known as a Monte Carlo Step (MCS). */ RandomNumberGenerator* p_gen = RandomNumberGenerator::Instance(); unsigned num_nodes = this->mrMesh.GetNumNodes(); // Randomly permute mUpdateRuleCollection if specified if (this->mIterateRandomlyOverUpdateRuleCollection) { // Randomly permute mUpdateRuleCollection p_gen->Shuffle(this->mUpdateRuleCollection); } for (unsigned i=0; i<num_nodes*mNumSweepsPerTimestep; i++) { unsigned node_index; if (this->mUpdateNodesInRandomOrder) { node_index = p_gen->randMod(num_nodes); } else { // Loop over nodes in index order. node_index = i%num_nodes; } Node<DIM>* p_node = this->mrMesh.GetNode(node_index); // Each node in the mesh must be in at most one element assert(p_node->GetNumContainingElements() <= 1); // Find a random available neighbouring node to overwrite current site std::set<unsigned> neighbouring_node_indices = mpPottsMesh->GetMooreNeighbouringNodeIndices(node_index); unsigned neighbour_location_index; if (!neighbouring_node_indices.empty()) { unsigned num_neighbours = neighbouring_node_indices.size(); unsigned chosen_neighbour = p_gen->randMod(num_neighbours); std::set<unsigned>::iterator neighbour_iter = neighbouring_node_indices.begin(); for (unsigned j=0; j<chosen_neighbour; j++) { neighbour_iter++; } neighbour_location_index = *neighbour_iter; std::set<unsigned> containing_elements = p_node->rGetContainingElementIndices(); std::set<unsigned> neighbour_containing_elements = GetNode(neighbour_location_index)->rGetContainingElementIndices(); // Only calculate Hamiltonian and update elements if the nodes are from different elements, or one is from the medium if ((!containing_elements.empty() && neighbour_containing_elements.empty()) || (containing_elements.empty() && !neighbour_containing_elements.empty()) || (!containing_elements.empty() && !neighbour_containing_elements.empty() && *containing_elements.begin() != *neighbour_containing_elements.begin())) { double delta_H = 0.0; // This is H_1-H_0. // Now add contributions to the Hamiltonian from each AbstractPottsUpdateRule for (typename std::vector<boost::shared_ptr<AbstractUpdateRule<DIM> > >::iterator iter = this->mUpdateRuleCollection.begin(); iter != this->mUpdateRuleCollection.end(); ++iter) { // This static cast is fine, since we assert the update rule must be a Potts update rule in AddUpdateRule() double dH = (boost::static_pointer_cast<AbstractPottsUpdateRule<DIM> >(*iter))->EvaluateHamiltonianContribution(neighbour_location_index, p_node->GetIndex(), *this); delta_H += dH; } // Generate a uniform random number to do the random motion double random_number = p_gen->ranf(); double p = exp(-delta_H/mTemperature); if (delta_H <= 0 || random_number < p) { // Do swap // Remove the current node from any elements containing it (there should be at most one such element) for (std::set<unsigned>::iterator iter = containing_elements.begin(); iter != containing_elements.end(); ++iter) { GetElement(*iter)->DeleteNode(GetElement(*iter)->GetNodeLocalIndex(node_index)); ///\todo If this causes the element to have no nodes then flag the element and cell to be deleted } // Next add the current node to any elements containing the neighbouring node (there should be at most one such element) for (std::set<unsigned>::iterator iter = neighbour_containing_elements.begin(); iter != neighbour_containing_elements.end(); ++iter) { GetElement(*iter)->AddNode(this->mrMesh.GetNode(node_index)); } } } } } } template<unsigned DIM> bool PottsBasedCellPopulation<DIM>::IsCellAssociatedWithADeletedLocation(CellPtr pCell) { return GetElementCorrespondingToCell(pCell)->IsDeleted(); } template<unsigned DIM> void PottsBasedCellPopulation<DIM>::Update(bool hasHadBirthsOrDeaths) { } template<unsigned DIM> void PottsBasedCellPopulation<DIM>::OpenWritersFiles(OutputFileHandler& rOutputFileHandler) { if (this->mOutputResultsForChasteVisualizer) { if (!this-> template HasWriter<CellPopulationElementWriter>()) { this-> template AddPopulationWriter<CellPopulationElementWriter>(); } } // Add a CellID writer so that a VTK file will contain IDs for visualisation. (It will also dump a "loggedcell.dat" file as a side-effect.) this-> template AddCellWriter<CellIdWriter>(); AbstractCellPopulation<DIM>::OpenWritersFiles(rOutputFileHandler); } template<unsigned DIM> void PottsBasedCellPopulation<DIM>::WriteResultsToFiles(const std::string& rDirectory) { CreateElementTessellation(); // To be used to output to the visualizer AbstractCellPopulation<DIM>::WriteResultsToFiles(rDirectory); } template<unsigned DIM> void PottsBasedCellPopulation<DIM>::AcceptPopulationWriter(boost::shared_ptr<AbstractCellPopulationWriter<DIM, DIM> > pPopulationWriter) { pPopulationWriter->Visit(this); } template<unsigned DIM> void PottsBasedCellPopulation<DIM>::AcceptPopulationCountWriter(boost::shared_ptr<AbstractCellPopulationCountWriter<DIM, DIM> > pPopulationCountWriter) { pPopulationCountWriter->Visit(this); } template<unsigned DIM> void PottsBasedCellPopulation<DIM>::AcceptCellWriter(boost::shared_ptr<AbstractCellWriter<DIM, DIM> > pCellWriter, CellPtr pCell) { pCellWriter->VisitCell(pCell, this); } template<unsigned DIM> double PottsBasedCellPopulation<DIM>::GetVolumeOfCell(CellPtr pCell) { // Get element index corresponding to this cell unsigned elem_index = this->GetLocationIndexUsingCell(pCell); // Get volume of this element in the Potts mesh double cell_volume = mpPottsMesh->GetVolumeOfElement(elem_index); return cell_volume; } template<unsigned DIM> double PottsBasedCellPopulation<DIM>::GetWidth(const unsigned& rDimension) { // Call GetWidth() on the mesh double width = this->mrMesh.GetWidth(rDimension); return width; } template<unsigned DIM> void PottsBasedCellPopulation<DIM>::AddUpdateRule(boost::shared_ptr<AbstractUpdateRule<DIM> > pUpdateRule) { assert(bool(dynamic_cast<AbstractPottsUpdateRule<DIM>*>(pUpdateRule.get()))); this->mUpdateRuleCollection.push_back(pUpdateRule); } template<unsigned DIM> void PottsBasedCellPopulation<DIM>::CreateElementTessellation() { ///\todo implement this method (#1666) // delete mpElementTessellation; // // ///\todo this code would need to be extended if the domain were required to be periodic // // std::vector<Node<2>*> nodes; // for (unsigned node_index=0; node_index<mrMesh.GetNumNodes(); node_index++) // { // Node<2>* p_temp_node = mrMesh.GetNode(node_index); // nodes.push_back(p_temp_node); // } // MutableMesh<2,2> mesh(nodes); // mpElementTessellation = new VertexMesh<2,2>(mesh); } template<unsigned DIM> VertexMesh<DIM,DIM>* PottsBasedCellPopulation<DIM>::GetElementTessellation() { // assert(mpElementTessellation != NULL); return mpElementTessellation; } template<unsigned DIM> void PottsBasedCellPopulation<DIM>::CreateMutableMesh() { delete mpMutableMesh; // Get the nodes of the PottsMesh std::vector<Node<DIM>*> nodes; for (unsigned node_index=0; node_index<this->mrMesh.GetNumNodes(); node_index++) { const c_vector<double, DIM>& r_location = this->mrMesh.GetNode(node_index)->rGetLocation(); nodes.push_back(new Node<DIM>(node_index, r_location)); } mpMutableMesh = new MutableMesh<DIM,DIM>(nodes); } template<unsigned DIM> MutableMesh<DIM,DIM>* PottsBasedCellPopulation<DIM>::GetMutableMesh() { assert(mpMutableMesh); return mpMutableMesh; } template<unsigned DIM> void PottsBasedCellPopulation<DIM>::OutputCellPopulationParameters(out_stream& rParamsFile) { *rParamsFile << "\t\t<Temperature>" << mTemperature << "</Temperature>\n"; *rParamsFile << "\t\t<NumSweepsPerTimestep>" << mNumSweepsPerTimestep << "</NumSweepsPerTimestep>\n"; // Call method on direct parent class AbstractOnLatticeCellPopulation<DIM>::OutputCellPopulationParameters(rParamsFile); } template<unsigned DIM> void PottsBasedCellPopulation<DIM>::SetTemperature(double temperature) { mTemperature = temperature; } template<unsigned DIM> double PottsBasedCellPopulation<DIM>::GetTemperature() { return mTemperature; } template<unsigned DIM> void PottsBasedCellPopulation<DIM>::SetNumSweepsPerTimestep(unsigned numSweepsPerTimestep) { mNumSweepsPerTimestep = numSweepsPerTimestep; } template<unsigned DIM> unsigned PottsBasedCellPopulation<DIM>::GetNumSweepsPerTimestep() { return mNumSweepsPerTimestep; } template<unsigned DIM> void PottsBasedCellPopulation<DIM>::WriteVtkResultsToFile(const std::string& rDirectory) { #ifdef CHASTE_VTK unsigned num_timesteps = SimulationTime::Instance()->GetTimeStepsElapsed(); std::stringstream time; time << num_timesteps; // Create mesh writer for VTK output VtkMeshWriter<DIM, DIM> mesh_writer(rDirectory, "results_"+time.str(), false); // Iterate over any cell writers that are present unsigned num_nodes = GetNumNodes(); for (typename std::vector<boost::shared_ptr<AbstractCellWriter<DIM, DIM> > >::iterator cell_writer_iter = this->mCellWriters.begin(); cell_writer_iter != this->mCellWriters.end(); ++cell_writer_iter) { // Create vector to store VTK cell data std::vector<double> vtk_cell_data(num_nodes); // Iterate over nodes in the mesh for (typename AbstractMesh<DIM,DIM>::NodeIterator iter = mpPottsMesh->GetNodeIteratorBegin(); iter != mpPottsMesh->GetNodeIteratorEnd(); ++iter) { // Get the index of this node in the mesh and those elements (i.e. cells) that contain this node unsigned node_index = iter->GetIndex(); std::set<unsigned> element_indices = iter->rGetContainingElementIndices(); // If there are no elements associated with this node, then we set the value of any VTK cell data to be -1 at this node... if (element_indices.empty()) { // Populate the vector of VTK cell data vtk_cell_data[node_index] = -1.0; } else { // ... otherwise there should be exactly one element (i.e. cell) containing this node assert(element_indices.size() == 1); unsigned elem_index = *(element_indices.begin()); CellPtr p_cell = this->GetCellUsingLocationIndex(elem_index); // Populate the vector of VTK cell data vtk_cell_data[node_index] = (*cell_writer_iter)->GetCellDataForVtkOutput(p_cell, this); } } mesh_writer.AddPointData((*cell_writer_iter)->GetVtkCellDataName(), vtk_cell_data); } // When outputting any CellData, we assume that the first cell is representative of all cells unsigned num_cell_data_items = this->Begin()->GetCellData()->GetNumItems(); std::vector<std::string> cell_data_names = this->Begin()->GetCellData()->GetKeys(); std::vector<std::vector<double> > cell_data; for (unsigned var=0; var<num_cell_data_items; var++) { std::vector<double> cell_data_var(num_nodes); cell_data.push_back(cell_data_var); } for (typename AbstractMesh<DIM,DIM>::NodeIterator iter = mpPottsMesh->GetNodeIteratorBegin(); iter != mpPottsMesh->GetNodeIteratorEnd(); ++iter) { // Get the index of this node in the mesh and those elements (i.e. cells) that contain this node unsigned node_index = iter->GetIndex(); std::set<unsigned> element_indices = iter->rGetContainingElementIndices(); // If there are no elements associated with this node, then we set the value of any VTK cell data to be -1 at this node... if (element_indices.empty()) { for (unsigned var=0; var<num_cell_data_items; var++) { cell_data[var][node_index] = -1.0; } } else { // ... otherwise there should be exactly one element (i.e. cell) containing this node assert(element_indices.size() == 1); unsigned elem_index = *(element_indices.begin()); CellPtr p_cell = this->GetCellUsingLocationIndex(elem_index); for (unsigned var=0; var<num_cell_data_items; var++) { cell_data[var][node_index] = p_cell->GetCellData()->GetItem(cell_data_names[var]); } } } for (unsigned var=0; var<cell_data.size(); var++) { mesh_writer.AddPointData(cell_data_names[var], cell_data[var]); } /* * At present, the VTK writer can only write things which inherit from AbstractTetrahedralMeshWriter. * For now, we do an explicit conversion to NodesOnlyMesh. This can be written to VTK, then visualized * as glyphs in Paraview. */ NodesOnlyMesh<DIM> temp_mesh; temp_mesh.ConstructNodesWithoutMesh(*mpPottsMesh, 1.5); // This cut-off is arbitrary, as node connectivity is not used here mesh_writer.WriteFilesUsingMesh(temp_mesh); *(this->mpVtkMetaFile) << " <DataSet timestep=\""; *(this->mpVtkMetaFile) << num_timesteps; *(this->mpVtkMetaFile) << "\" group=\"\" part=\"0\" file=\"results_"; *(this->mpVtkMetaFile) << num_timesteps; *(this->mpVtkMetaFile) << ".vtu\"/>\n"; // Extra part to output the outlines of cells if (DIM ==2) { std::vector<Node<2>*> outline_nodes; std::vector<VertexElement<2,2>*> outline_elements; unsigned outline_node_index = 0; unsigned outline_element_index = 0; for (typename AbstractMesh<DIM,DIM>::NodeIterator iter = mpPottsMesh->GetNodeIteratorBegin(); iter != mpPottsMesh->GetNodeIteratorEnd(); ++iter) { // Get the index of this node in the mesh and those elements (i.e. cells) that contain this node unsigned node_index = iter->GetIndex(); std::set<unsigned> element_indices = iter->rGetContainingElementIndices(); std::set<unsigned> target_neighbouring_node_indices = this->rGetMesh().GetVonNeumannNeighbouringNodeIndices(node_index); for (std::set<unsigned>::iterator neighbour_iter = target_neighbouring_node_indices.begin(); neighbour_iter != target_neighbouring_node_indices.end(); ++neighbour_iter) { std::set<unsigned> neighbouring_element_indices = this->rGetMesh().GetNode(*neighbour_iter)->rGetContainingElementIndices(); // If different cells add a line if (element_indices != neighbouring_element_indices) { std::vector<Node<2>*> element_nodes; const c_vector<double, 2>& r_node_location = this->mrMesh.GetNode(node_index)->rGetLocation(); const c_vector<double, 2>& r_neighbour_node_location = this->mrMesh.GetNode(*neighbour_iter)->rGetLocation(); c_vector<double, 2> unit_tangent = r_neighbour_node_location - r_node_location; if (norm_2(unit_tangent) > 1.0) // It's a periodic neighbour { c_vector<double, 2> mid_point = 0.5*(r_node_location + r_neighbour_node_location); if (unit_tangent(0) == 0) { if (r_node_location(1) < r_neighbour_node_location(1)) { mid_point(1) = r_node_location(1) - 0.5; } else { mid_point(1) = r_node_location(1) + 0.5; } } else { assert(unit_tangent(1) == 0); if (r_node_location(0) < r_neighbour_node_location(0)) { mid_point(0) = r_node_location(0) - 0.5; } else { mid_point(0) = r_node_location(0) + 0.5; } } assert(norm_2(unit_tangent) > 0); unit_tangent = unit_tangent/norm_2(unit_tangent); c_vector<double, DIM> unit_normal; unit_normal(0) = -unit_tangent(1); unit_normal(1) = unit_tangent(0); std::vector<Node<2>*> element_nodes; // Need at least three points to visualise in Paraview Node<2>* p_node_1 = new Node<2>(outline_node_index, mid_point - 0.5*unit_normal); outline_nodes.push_back(p_node_1); element_nodes.push_back(outline_nodes[outline_node_index]); outline_node_index++; Node<2>* p_node_2 = new Node<2>(outline_node_index, mid_point); outline_nodes.push_back(p_node_2); element_nodes.push_back(outline_nodes[outline_node_index]); outline_node_index++; Node<2>* p_node_3 = new Node<2>(outline_node_index, mid_point + 0.5*unit_normal); outline_nodes.push_back(p_node_3); element_nodes.push_back(outline_nodes[outline_node_index]); outline_node_index++; VertexElement<2,2>* p_element = new VertexElement<2,2>(outline_element_index, element_nodes); outline_elements.push_back(p_element); outline_element_index++; } else // Standard Neighbour { c_vector<double, 2> mid_point = 0.5*(r_node_location + r_neighbour_node_location); assert(norm_2(unit_tangent) > 0); unit_tangent = unit_tangent/norm_2(unit_tangent); c_vector<double, 2> unit_normal; unit_normal(0) = -unit_tangent(1); unit_normal(1) = unit_tangent(0); std::vector<Node<2>*> element_nodes; // Need at least three points to visualise in Paraview Node<2>* p_node_1 = new Node<2>(outline_node_index, mid_point - 0.5*unit_normal); outline_nodes.push_back(p_node_1); element_nodes.push_back(outline_nodes[outline_node_index]); outline_node_index++; Node<2>* p_node_2 = new Node<2>(outline_node_index, mid_point); outline_nodes.push_back(p_node_2); element_nodes.push_back(outline_nodes[outline_node_index]); outline_node_index++; Node<2>* p_node_3 = new Node<2>(outline_node_index, mid_point + 0.5*unit_normal); outline_nodes.push_back(p_node_3); element_nodes.push_back(outline_nodes[outline_node_index]); outline_node_index++; VertexElement<2,2>* p_element = new VertexElement<2,2>(outline_element_index, element_nodes); outline_elements.push_back(p_element); outline_element_index++; } } } } VertexMesh<2,2> cell_outline_mesh(outline_nodes,outline_elements); VertexMeshWriter<2, 2> outline_mesh_writer(rDirectory, "outlines", false); outline_mesh_writer.WriteVtkUsingMesh(cell_outline_mesh, time.str()); outline_mesh_writer.WriteFilesUsingMesh(cell_outline_mesh); } #endif //CHASTE_VTK } template<unsigned DIM> double PottsBasedCellPopulation<DIM>::GetCellDataItemAtPdeNode( unsigned pdeNodeIndex, std::string& rVariableName, bool dirichletBoundaryConditionApplies, double dirichletBoundaryValue) { CellPtr p_cell = this->GetCellUsingLocationIndex(pdeNodeIndex); double value = p_cell->GetCellData()->GetItem(rVariableName); return value; } // Explicit instantiation template class PottsBasedCellPopulation<1>; template class PottsBasedCellPopulation<2>; template class PottsBasedCellPopulation<3>; // Serialization for Boost >= 1.36 #include "SerializationExportWrapperForCpp.hpp" EXPORT_TEMPLATE_CLASS_SAME_DIMS(PottsBasedCellPopulation)
/* Copyright 2019 Alain Dargelas Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* * File: CompileFileContent.cpp * Author: alain * * Created on March 28, 2018, 10:16 PM */ #include "SourceCompile/VObjectTypes.h" #include "Design/VObject.h" #include "Library/Library.h" #include "Design/FileContent.h" #include "SourceCompile/SymbolTable.h" #include "ErrorReporting/Error.h" #include "ErrorReporting/Location.h" #include "ErrorReporting/Error.h" #include "CommandLine/CommandLineParser.h" #include "ErrorReporting/ErrorDefinition.h" #include "ErrorReporting/ErrorContainer.h" #include "SourceCompile/CompilationUnit.h" #include "SourceCompile/PreprocessFile.h" #include "SourceCompile/CompileSourceFile.h" #include "SourceCompile/ParseFile.h" #include "SourceCompile/Compiler.h" #include "DesignCompile/CompileDesign.h" #include "DesignCompile/CompileFileContent.h" #include "DesignCompile/CompileHelper.h" using namespace SURELOG; int FunctorCompileFileContent::operator()() const { CompileFileContent* instance = new CompileFileContent( m_compileDesign, m_fileContent, m_design, m_symbols, m_errors); instance->compile(); delete instance; return true; } bool CompileFileContent::compile() { return collectObjects_(); } bool CompileFileContent::collectObjects_() { std::vector<VObjectType> stopPoints = { VObjectType::slModule_declaration, VObjectType::slInterface_declaration, VObjectType::slProgram_declaration, VObjectType::slClass_declaration, VObjectType::slPrimitive, VObjectType::slPackage_declaration, VObjectType::slFunction_declaration}; FileContent* fC = m_fileContent; if (fC->getSize() == 0) return true; VObject current = fC->Object(fC->getSize() - 2); NodeId id = current.m_child; if (!id) id = current.m_sibling; if (!id) return false; std::stack<NodeId> stack; stack.push(id); while (stack.size()) { id = stack.top(); stack.pop(); current = fC->Object(id); VObjectType type = fC->Type(id); switch (type) { case VObjectType::slPackage_import_item: { FileCNodeId fnid(fC, id); m_fileContent->addObject(type, fnid); break; } case VObjectType::slData_declaration: { NodeId subNode = fC->Child(id); VObjectType subType = fC->Type(subNode); switch (subType) { case VObjectType::slType_declaration: { /* n<> u<15> t<Data_type> p<17> c<8> s<16> l<13> n<fsm_t> u<16> t<StringConst> p<17> l<13> n<> u<17> t<Type_declaration> p<18> c<15> l<13> n<> u<18> t<Data_declaration> p<19> c<17> l<13> */ m_helper.compileTypeDef(m_fileContent, m_fileContent, id, m_compileDesign); break; } default: break; } break; } default: break; } if (current.m_sibling) stack.push(current.m_sibling); if (current.m_child) { if (stopPoints.size()) { bool stop = false; for (auto t : stopPoints) { if (t == current.m_type) { stop = true; break; } } if (!stop) if (current.m_child) stack.push(current.m_child); } else { if (current.m_child) stack.push(current.m_child); } } } return true; }
/** * @file * @author __AUTHOR_NAME__ <mail@host.com> * @copyright 2021 __COMPANY_LTD__ * @license <a href="https://opensource.org/licenses/MIT">MIT License</a> */ /** * The Pointer Down Input Event. * * This event is dispatched by the InputPlugin belonging to a Scene if a pointer * is pressed down anywhere. * * Listen to this event from within a Scene using: `input.on("pointerdown", * listener)`. * * The event hierarchy is as follows: * * 1. ZEN_INPUT_GAMEOBJECT_POINTER_DOWN * 2. ZEN_INPUT_GAMEOBJECT_DOWN * 3. ZEN_INPUT_POINTER_DOWN * * With the top event being dispatched first and then flowing down the list. Note * that higher-up event handlers can stop the propagation of this event. * * @since 0.0.0 * * @param pointer The Pointer responsible for triggering this event. * @param currentlyOver An array containing all interactive Game Objects that the pointer was over when the event was created. */ #define ZEN_INPUT_POINTER_DOWN "pointerdown"
//--------------------------------------------------------------------------- #include "uSfgMetaData.h" #pragma hdrstop #include "uSfgBrowseObf.h" //--------------------------------------------------------------------------- #pragma package(smart_init) namespace SfgBrowse { //--------------------------------------------------------------------------- void EscolheNaturezaOperacao(TForm *pParent, SfgBrowseReturn OnBrowseReturn) { TfrmBrowse *frmBrowse = new TfrmBrowse(Application); String sSQL = GetBrowseSQL("tbl_natureza_operacao",frmBrowse->DataSet); CreateFields(frmBrowse->DataSet); frmBrowse->SQL = sSQL; frmBrowse->OnBrowseReturn = OnBrowseReturn; frmBrowse->ShowModal(); delete frmBrowse; } //--------------------------------------------------------------------------- }; //End namespace SfgBrowse //---------------------------------------------------------------------------
#include "random_c8.h" random_c8::random_c8() { random_engine = std::mt19937_64(rddev()); } uint8_t random_c8::get() { return distribution(random_engine); }
// // Copyright 2018 Google LLC // // 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. // // Test functions in MathUtil. #include "zetasql/base/mathutil.h" #include <stdio.h> #include <cstddef> #include <cmath> #include <iomanip> #include <limits> #include <ostream> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/casts.h" #include "zetasql/base/logging.h" namespace zetasql_base { namespace { using ::testing::Eq; TEST(MathUtil, Round) { // test float rounding EXPECT_EQ(MathUtil::FastIntRound(0.7f), 1); EXPECT_EQ(MathUtil::FastIntRound(5.7f), 6); EXPECT_EQ(MathUtil::FastIntRound(6.3f), 6); EXPECT_EQ(MathUtil::FastIntRound(1000000.7f), 1000001); // test that largest representable number below 0.5 rounds to zero. // this is important because naive implementation of round: // static_cast<int>(r + 0.5f) is 1 due to implicit rounding in operator+ float rf = std::nextafter(0.5f, .0f); EXPECT_LT(rf, 0.5f); EXPECT_EQ(MathUtil::Round<int>(rf), 0); // same test for double double rd = std::nextafter(0.5, 0.0); EXPECT_LT(rd, 0.5); EXPECT_EQ(MathUtil::Round<int>(rd), 0); // same test for long double long double rl = std::nextafter(0.5l, 0.0l); EXPECT_LT(rl, 0.5l); EXPECT_EQ(MathUtil::Round<int>(rl), 0); } TEST(MathUtil, IntRound) { EXPECT_EQ(MathUtil::Round<int>(0.0), 0); EXPECT_EQ(MathUtil::Round<int>(0.49), 0); EXPECT_EQ(MathUtil::Round<int>(1.49), 1); EXPECT_EQ(MathUtil::Round<int>(-0.49), 0); EXPECT_EQ(MathUtil::Round<int>(-1.49), -1); // Either adjacent integer is an acceptable result. EXPECT_EQ(fabs(MathUtil::Round<int>(0.5) - 0.5), 0.5); EXPECT_EQ(fabs(MathUtil::Round<int>(1.5) - 1.5), 0.5); EXPECT_EQ(fabs(MathUtil::Round<int>(-0.5) + 0.5), 0.5); EXPECT_EQ(fabs(MathUtil::Round<int>(-1.5) + 1.5), 0.5); EXPECT_EQ(MathUtil::Round<int>(static_cast<double>(0x76543210)), 0x76543210); // A double-precision number has a 53-bit mantissa (52 fraction bits), // so the following value can be represented exactly. int64_t value64 = 0x1234567890abcd00; EXPECT_EQ(MathUtil::Round<int64_t>(static_cast<double>(value64)), value64); } template<typename Type> void TestSimpleUtils() { ZETASQL_LOG(INFO) << "testing Max Min Abs Sign AbsDiff for " << sizeof(Type); const Type kZero = 0.0; const Type kNegZero = -0.0; const Type kFinite = 2.67; const Type kNaN = MathLimits<Type>::kNaN; const Type kPosInf = MathLimits<Type>::kPosInf; const Type kNegInf = MathLimits<Type>::kNegInf; EXPECT_TRUE(MathUtil::Min(kZero, kNegZero) == kNegZero); EXPECT_TRUE(MathUtil::Min(kNegZero, kZero) == kNegZero); // these four tests above work because kNegZero and kZero // are indistinguishable w.r.t. == : EXPECT_TRUE(kNegZero == kZero); EXPECT_TRUE(MathLimits<Type>::IsNaN(MathUtil::Min(kNaN, kFinite))); EXPECT_TRUE(MathLimits<Type>::IsNaN(MathUtil::Min(kFinite, kNaN))); EXPECT_TRUE(MathLimits<Type>::IsNaN(MathUtil::Min(kNaN, kNaN))); EXPECT_TRUE(MathLimits<Type>::IsNaN(MathUtil::Min(kNaN, -kNaN))); EXPECT_TRUE(MathLimits<Type>::IsNaN(MathUtil::Min(kNaN, kPosInf))); EXPECT_TRUE(MathLimits<Type>::IsNaN(MathUtil::Min(kNaN, kNegInf))); EXPECT_TRUE(MathLimits<Type>::IsNaN(MathUtil::Min(kPosInf, kNaN))); EXPECT_TRUE(MathLimits<Type>::IsNaN(MathUtil::Min(kNegInf, kNaN))); EXPECT_TRUE(MathUtil::Min(kPosInf, kFinite) == kFinite); EXPECT_TRUE(MathUtil::Min(kFinite, kPosInf) == kFinite); EXPECT_TRUE(MathLimits<Type>::IsPosInf(MathUtil::Min(kPosInf, kPosInf))); EXPECT_TRUE(MathLimits<Type>::IsNegInf(MathUtil::Min(kPosInf, kNegInf))); EXPECT_TRUE(MathLimits<Type>::IsNegInf(MathUtil::Min(kNegInf, kPosInf))); EXPECT_TRUE(MathLimits<Type>::IsNegInf(MathUtil::Min(kNegInf, kFinite))); EXPECT_TRUE(MathLimits<Type>::IsNegInf(MathUtil::Min(kFinite, kNegInf))); EXPECT_TRUE(MathLimits<Type>::IsNegInf(MathUtil::Min(kNegInf, kNegInf))); EXPECT_TRUE(MathUtil::Abs(kZero) == kZero); EXPECT_TRUE(MathUtil::Abs(kNegZero) == kZero); EXPECT_TRUE(MathUtil::Abs(kFinite) == kFinite); EXPECT_TRUE(MathUtil::Abs(-kFinite) == kFinite); EXPECT_TRUE(MathLimits<Type>::IsNaN(MathUtil::Abs(kNaN))); EXPECT_TRUE(MathLimits<Type>::IsPosInf(MathUtil::Abs(kPosInf))); EXPECT_TRUE(MathLimits<Type>::IsPosInf(MathUtil::Abs(kNegInf))); EXPECT_TRUE(MathLimits<Type>::IsNaN(MathUtil::AbsDiff(kNaN, kFinite))); EXPECT_TRUE(MathLimits<Type>::IsNaN(MathUtil::AbsDiff(kFinite, kNaN))); EXPECT_TRUE(MathLimits<Type>::IsNaN(MathUtil::AbsDiff(kNaN, kNaN))); EXPECT_TRUE(MathLimits<Type>::IsNaN(MathUtil::AbsDiff(kNaN, -kNaN))); EXPECT_TRUE(MathLimits<Type>::IsNaN(MathUtil::AbsDiff(kNaN, kPosInf))); EXPECT_TRUE(MathLimits<Type>::IsNaN(MathUtil::AbsDiff(kNaN, kNegInf))); EXPECT_TRUE(MathLimits<Type>::IsNaN(MathUtil::AbsDiff(kPosInf, kNaN))); EXPECT_TRUE(MathLimits<Type>::IsNaN(MathUtil::AbsDiff(kNegInf, kNaN))); EXPECT_TRUE(MathLimits<Type>::IsPosInf(MathUtil::AbsDiff(kPosInf, kFinite))); EXPECT_TRUE(MathLimits<Type>::IsPosInf(MathUtil::AbsDiff(kFinite, kPosInf))); EXPECT_TRUE(MathLimits<Type>::IsNaN(MathUtil::AbsDiff(kPosInf, kPosInf))); EXPECT_TRUE(MathLimits<Type>::IsPosInf(MathUtil::AbsDiff(kPosInf, kNegInf))); EXPECT_TRUE(MathLimits<Type>::IsPosInf(MathUtil::AbsDiff(kNegInf, kPosInf))); EXPECT_TRUE(MathLimits<Type>::IsPosInf(MathUtil::AbsDiff(kNegInf, kFinite))); EXPECT_TRUE(MathLimits<Type>::IsPosInf(MathUtil::AbsDiff(kFinite, kNegInf))); EXPECT_TRUE(MathLimits<Type>::IsNaN(MathUtil::AbsDiff(kNegInf, kNegInf))); } TEST(MathUtil, SimpleUtils) { TestSimpleUtils<float>(); TestSimpleUtils<double>(); TestSimpleUtils<long double>(); } // Number of arguments for each test of the CeilOrRatio method const int kNumTestArguments = 4; template<typename IntegralType> void TestCeilOfRatio(const IntegralType test_data[][kNumTestArguments], int num_tests) { for (int i = 0; i < num_tests; ++i) { const IntegralType numerator = test_data[i][0]; const IntegralType denominator = test_data[i][1]; const IntegralType expected_floor = test_data[i][2]; const IntegralType expected_ceil = test_data[i][3]; // Make sure the two ways to compute the floor return the same thing. IntegralType floor_1 = MathUtil::FloorOfRatio(numerator, denominator); IntegralType floor_2 = MathUtil::CeilOrFloorOfRatio<IntegralType, false>( numerator, denominator); EXPECT_EQ(floor_1, floor_2); EXPECT_EQ(expected_floor, floor_1) << "FloorOfRatio fails with numerator = " << numerator << ", denominator = " << denominator << (MathLimits<IntegralType>::kIsSigned ? "signed " : "unsigned ") << (8 * sizeof(IntegralType)) << " bits"; IntegralType ceil_1 = MathUtil::CeilOrFloorOfRatio<IntegralType, true>( numerator, denominator); EXPECT_EQ(expected_ceil, ceil_1) << "CeilOfRatio fails with numerator = " << numerator << ", denominator = " << denominator << (MathLimits<IntegralType>::kIsSigned ? "signed " : "unsigned ") << (8 * sizeof(IntegralType)) << " bits"; } } template<typename UnsignedIntegralType> void TestCeilOfRatioUnsigned() { typedef MathLimits<UnsignedIntegralType> Limits; EXPECT_TRUE(Limits::kIsInteger); EXPECT_TRUE(!Limits::kIsSigned); const UnsignedIntegralType kMax = Limits::kMax; const UnsignedIntegralType kTestData[][kNumTestArguments] = { // Numerator | Denominator | Expected floor of ratio | Expected ceil of ratio | // When numerator = 0, the result is always zero { 0, 1, 0, 0 }, { 0, 2, 0, 0 }, { 0, kMax, 0, 0 }, // Try some non-extreme cases { 1, 1, 1, 1 }, { 5, 2, 2, 3 }, // Try with huge positive numerator { kMax, 1, kMax, kMax }, { kMax, 2, kMax / 2, kMax / 2 + ((kMax % 2 != 0) ? 1 : 0) }, { kMax, 3, kMax / 3, kMax / 3 + ((kMax % 3 != 0) ? 1 : 0) }, // Try with a huge positive denominator { 1, kMax, 0, 1 }, { 2, kMax, 0, 1 }, { 3, kMax, 0, 1 }, // Try with a huge numerator and a huge denominator { kMax, kMax, 1, 1 }, }; const int kNumTests = ABSL_ARRAYSIZE(kTestData); TestCeilOfRatio<UnsignedIntegralType>(kTestData, kNumTests); } template<typename SignedInteger> void TestCeilOfRatioSigned() { typedef MathLimits<SignedInteger> Limits; EXPECT_TRUE(Limits::kIsInteger); EXPECT_TRUE(Limits::kIsSigned); const SignedInteger kMin = Limits::kMin; const SignedInteger kMax = Limits::kMax; const SignedInteger kTestData[][kNumTestArguments] = { // Numerator | Denominator | Expected floor of ratio | Expected ceil of ratio | // When numerator = 0, the result is always zero { 0, 1, 0, 0 }, { 0, -1, 0, 0 }, { 0, 2, 0, 0 }, { 0, kMin, 0, 0 }, { 0, kMax, 0, 0 }, // Try all four combinations of 1 and -1 { 1, 1, 1, 1 }, { -1, 1, -1, -1 }, { 1, -1, -1, -1 }, { -1, -1, 1, 1 }, // Try all four combinations of +/-5 divided by +/- 2 { 5, 2, 2, 3 }, { -5, 2, -3, -2 }, { 5, -2, -3, -2 }, { -5, -2, 2, 3 }, // Try with huge positive numerator { kMax, 1, kMax, kMax }, { kMax, -1, -kMax, -kMax }, { kMax, 2, kMax / 2, kMax / 2 + ((kMax % 2 != 0) ? 1 : 0) }, { kMax, 3, kMax / 3, kMax / 3 + ((kMax % 3 != 0) ? 1 : 0) }, // Try with huge negative numerator { kMin, 1, kMin, kMin }, { kMin, 2, kMin / 2 - ((kMin % 2 != 0) ? 1 : 0), kMin / 2 }, { kMin, 3, kMin / 3 - ((kMin % 3 != 0) ? 1 : 0), kMin / 3 }, // Try with a huge positive denominator { 1, kMax, 0, 1 }, { 2, kMax, 0, 1 }, { 3, kMax, 0, 1 }, // Try with a huge negative denominator { 1, kMin, -1, 0 }, { 2, kMin, -1, 0 }, { 3, kMin, -1, 0 }, // Try with a huge numerator and a huge denominator { kMin, kMin, 1, 1 }, { kMin, kMax, -2, -1 }, { kMax, kMin, -1, 0 }, { kMax, kMax, 1, 1 }, }; const int kNumTests = ABSL_ARRAYSIZE(kTestData); TestCeilOfRatio<SignedInteger>(kTestData, kNumTests); } // ------------------------------------------------------------------------ // // Benchmarking CeilOrFloorOfRatio // // We compare with other implementations that are unsafe in general. // ------------------------------------------------------------------------ // // An implementation of CeilOfRatio that is correct for small enough values, // and provided that the numerator and denominator are both positive template <typename IntegralType> IntegralType CeilOfRatioDenomMinusOne(IntegralType numerator, IntegralType denominator) { const IntegralType kOne(1); return (numerator + denominator - kOne) / denominator; } // An implementation of FloorOfRatio that is correct when the denominator is // positive and the numerator non-negative template <typename IntegralType> IntegralType FloorOfRatioByDivision(IntegralType numerator, IntegralType denominator) { return numerator / denominator; } template <typename Integer, bool ComputeCeil> Integer CeilOrFloorOfRatioArithmetic(Integer numerator, Integer denominator) { if (ComputeCeil) { return CeilOfRatioDenomMinusOne(numerator, denominator); } else { return FloorOfRatioByDivision(numerator, denominator); } } // Implementations of the CeilOrRatio function. enum Implementation { PROVIDED, // The method provided by MathUtil in the .h file ARITHMETIC // Using arithmetic tricks }; template <typename Integer, bool ComputeCeil, Implementation Implementation> Integer CeilOrFloorOfRatio(Integer numerator, Integer denominator) { switch (Implementation) { // Compile time switch case PROVIDED: return MathUtil::CeilOrFloorOfRatio<Integer, ComputeCeil>( numerator, denominator); case ARITHMETIC: return CeilOrFloorOfRatioArithmetic<Integer, ComputeCeil>( numerator, denominator); default: ZETASQL_LOG(FATAL) << "This statement was supposed to be unreachable"; } } void TestThatCeilOfRatioDenomMinusOneIsIncorrect(int64_t numerator, int64_t denominator, int64_t expected_error) { const int64_t correct_result = MathUtil::CeilOrFloorOfRatio<int64_t, true>(numerator, denominator); // MathUtil::CeilOfRatio(numerator, denominator); const int64_t result_by_denom_minus_one = CeilOfRatioDenomMinusOne(numerator, denominator); EXPECT_EQ(result_by_denom_minus_one + expected_error, correct_result) << "numerator = " << numerator << " denominator = " << denominator << " expected error = " << expected_error << " Actual difference: " << (correct_result - result_by_denom_minus_one); } // Here we demonstrate why not to use CeilOfRatioDenomMinusOne void TestThatCeilOfRatioDenomMinusOneIsIncorrect() { // It does not work with negative values TestThatCeilOfRatioDenomMinusOneIsIncorrect(int64_t{-1}, int64_t{-2}, int64_t{-1}); // This would also fail if given kint64max because of signed integer overflow. } TEST(MathUtil, CeilOfRatio) { TestCeilOfRatioUnsigned<uint8_t>(); TestCeilOfRatioUnsigned<uint16_t>(); TestCeilOfRatioUnsigned<uint32_t>(); TestCeilOfRatioUnsigned<uint64_t>(); TestCeilOfRatioSigned<int8_t>(); TestCeilOfRatioSigned<int16_t>(); TestCeilOfRatioSigned<int32_t>(); TestCeilOfRatioSigned<int64_t>(); TestThatCeilOfRatioDenomMinusOneIsIncorrect(); } TEST(MathUtil, NonnegativeMod) { // Test compliance with the standard -- integer division is supposed to // truncate towards zero, and integer mod is defined accordingly. ASSERT_THAT(-8 / 5, Eq(-1)); ASSERT_THAT(-8 % 5, Eq(-3)); // Now test the function itself. EXPECT_THAT(MathUtil::NonnegativeMod(4, 3), Eq(1)); EXPECT_THAT(MathUtil::NonnegativeMod(-5, 3), Eq(1)); EXPECT_THAT(MathUtil::NonnegativeMod(9, 3), Eq(0)); EXPECT_THAT(MathUtil::NonnegativeMod(-9, 3), Eq(0)); EXPECT_THAT(MathUtil::NonnegativeMod(0, 3), Eq(0)); EXPECT_THAT(MathUtil::NonnegativeMod(12U, 5U), Eq(2U)); int64_t a_int64 = 10000000002; int64_t b_int64 = 10000000000; int64_t two_int64 = 2; EXPECT_THAT(MathUtil::NonnegativeMod(a_int64, b_int64), Eq(two_int64)); EXPECT_THAT(MathUtil::NonnegativeMod(-a_int64, b_int64), Eq(b_int64 - two_int64)); EXPECT_THAT(MathUtil::NonnegativeMod(b_int64, b_int64), Eq(0)); EXPECT_THAT(MathUtil::NonnegativeMod(-b_int64, b_int64), Eq(0)); } TEST(MathUtil, DecomposeDouble) { using Limits = std::numeric_limits<double>; struct TestItem { double value; int64_t expected_mantissa; int expected_exponent; }; static const TestItem kItems[] = { {0.0, 0, -1074}, {Limits::denorm_min(), 1, -1074}, {Limits::min() - Limits::denorm_min(), (1LL << 52) - 1, -1074}, {Limits::min(), (1LL << 52), -1074}, {1.0 / (1LL << 52), (1LL << 52), -104}, {1.0, (1LL << 52), -52}, {100, (100LL << 46), -46}, {static_cast<double>(std::numeric_limits<uint64_t>::max()), (std::numeric_limits<uint64_t>::max() >> 12) + 1, 12}, {Limits::max(), (1LL << 53) - 1, 971}, {Limits::infinity(), std::numeric_limits<int64_t>::max(), std::numeric_limits<int>::max()}, }; for (const TestItem& item : kItems) { ZETASQL_LOG(INFO) << "Testing ExtractMantissaAndExponent(" << item.value << ")..."; MathUtil::DoubleParts parts = MathUtil::Decompose(item.value); EXPECT_EQ(item.expected_mantissa, parts.mantissa); EXPECT_EQ(item.expected_exponent, parts.exponent); EXPECT_EQ(item.value, std::ldexp(static_cast<double>(parts.mantissa), parts.exponent)); EXPECT_EQ(item.value, static_cast<double>(parts.mantissa) * std::ldexp(1.0, parts.exponent)); parts = MathUtil::Decompose(-item.value); EXPECT_EQ(-item.expected_mantissa, parts.mantissa); EXPECT_EQ(item.expected_exponent, parts.exponent); EXPECT_EQ(-item.value, std::ldexp(static_cast<double>(parts.mantissa), parts.exponent)); EXPECT_EQ(-item.value, static_cast<double>(parts.mantissa) * std::ldexp(1.0, parts.exponent)); } MathUtil::DoubleParts parts = MathUtil::Decompose(Limits::quiet_NaN()); EXPECT_EQ(0, parts.mantissa); EXPECT_EQ(std::numeric_limits<int>::max(), parts.exponent); EXPECT_TRUE(std::isnan(static_cast<double>(parts.mantissa) * std::ldexp(1.0, parts.exponent))); } TEST(MathUtil, DecomposeFloat) { using Limits = std::numeric_limits<float>; struct TestItem { float value; int32_t expected_mantissa; int expected_exponent; }; static const TestItem kItems[] = { {0.0, 0, -149}, {1.2, 10066330, -23}, {-1.2, -10066330, -23}, {100, 100 << 17, -17}, {Limits::denorm_min(), 1, -149}, {Limits::min() - Limits::denorm_min(), (1 << 23) - 1, -149}, {Limits::min(), 1 << 23, -149}, {Limits::max(), 16777215, 104}, {Limits::infinity(), std::numeric_limits<int32_t>::max(), std::numeric_limits<int>::max()}, }; for (const TestItem& item : kItems) { ZETASQL_LOG(INFO) << "Testing ExtractMantissaAndExponent(" << item.value << ")..."; MathUtil::FloatParts parts = MathUtil::Decompose(item.value); EXPECT_EQ(item.expected_mantissa, parts.mantissa); EXPECT_EQ(item.expected_exponent, parts.exponent); EXPECT_EQ(item.value, std::ldexp(static_cast<float>(parts.mantissa), parts.exponent)); EXPECT_EQ(item.value, static_cast<float>(parts.mantissa) * std::ldexp(1.0, parts.exponent)); parts = MathUtil::Decompose(-item.value); EXPECT_EQ(-item.expected_mantissa, parts.mantissa); EXPECT_EQ(item.expected_exponent, parts.exponent); EXPECT_EQ(-item.value, std::ldexp(static_cast<float>(parts.mantissa), parts.exponent)); EXPECT_EQ(-item.value, static_cast<float>(parts.mantissa) * std::ldexp(1.0, parts.exponent)); } MathUtil::FloatParts parts = MathUtil::Decompose(Limits::quiet_NaN()); EXPECT_EQ(0, parts.mantissa); EXPECT_EQ(std::numeric_limits<int>::max(), parts.exponent); EXPECT_TRUE(std::isnan(static_cast<float>(parts.mantissa) * std::ldexp(1.0, parts.exponent))); } template <typename T> void TestOneIPowN() { const T one{1}; for (int i = 0; i < 1024; ++i) { // Computations are exact. EXPECT_EQ(MathUtil::IPow(one, i), one); } } template <typename T> void TestTwoIPowN() { int limit = std::is_integral<T>::value ? std::numeric_limits<T>::digits : 63; for (int i = 0; i < limit; ++i) { // Computations are exact. EXPECT_EQ(MathUtil::IPow(T{2}, i), static_cast<T>(1ull << i)); } } template <typename T> void TestFloatIPow(const int max_exponent, const T start, const T end, const T step) { for (T f = start; f < end; f += step) { for (int i = 0; i < max_exponent; ++i) { EXPECT_FLOAT_EQ(MathUtil::IPow(f, i), std::pow(f, i)); } } } TEST(MathUtil, IPow) { TestOneIPowN<double>(); TestOneIPowN<float>(); TestOneIPowN<int>(); TestOneIPowN<int64_t>(); TestTwoIPowN<double>(); TestTwoIPowN<float>(); TestTwoIPowN<int>(); TestTwoIPowN<int64_t>(); EXPECT_EQ(MathUtil::IPow(3, 0), 1); EXPECT_EQ(MathUtil::IPow(3, 1), 3); EXPECT_EQ(MathUtil::IPow(3, 2), 9); EXPECT_EQ(MathUtil::IPow(3, 3), 27); EXPECT_EQ(MathUtil::IPow(3, 4), 81); EXPECT_EQ(MathUtil::IPow(3, 5), 243); TestFloatIPow<float>(13, -16.0f, 16.0f, 1.0f / 8); TestFloatIPow<double>(13, -16.0, 16.0, 1.0 / 8); TestFloatIPow<float>(13, -1.0f / (1 << 12), -1.0f / (1 << 12), 1.0f / (1 << 16)); TestFloatIPow<double>(13, -1.0 / (1 << 12), -1.0 / (1 << 12), 1.0 / (1 << 16)); } TEST(MathUtil, IPowEdgeCases) { constexpr const double kInf = std::numeric_limits<double>::infinity(); EXPECT_EQ(MathUtil::IPow(-12345.0, 79), -kInf); EXPECT_EQ(MathUtil::IPow(-12345.0, 80), +kInf); // The semantics of the edge cases that follow are defined in the standard: // http://en.cppreference.com/w/cpp/numeric/math/pow for a summary. // 1 - These edge cases apply. // pow(+0, exp), where exp is a positive odd integer, returns +0 EXPECT_EQ(MathUtil::IPow(+0.0, 3), +0.0); // pow(-0, exp), where exp is a positive odd integer, returns -0 EXPECT_EQ(MathUtil::IPow(-0.0, 3), -0.0); // pow(±0, exp), where exp is positive non-integer or a positive even integer, // returns +0 EXPECT_EQ(MathUtil::IPow(+0.0, 42), +0.0); EXPECT_EQ(MathUtil::IPow(-0.0, 42), +0.0); // pow(base, ±0) returns 1 for any base, even when base is NaN EXPECT_EQ(MathUtil::IPow(-kInf, 0.0), 1.0); EXPECT_EQ(MathUtil::IPow(-2.0, 0.0), 1.0); EXPECT_EQ(MathUtil::IPow(-1.0, 0.0), 1.0); EXPECT_EQ(MathUtil::IPow(-0.0, 0.0), 1.0); EXPECT_EQ(MathUtil::IPow(+0.0, 0.0), 1.0); EXPECT_EQ(MathUtil::IPow(+1.0, 0.0), 1.0); EXPECT_EQ(MathUtil::IPow(+2.0, 0.0), 1.0); EXPECT_EQ(MathUtil::IPow(+kInf, 0.0), 1.0); EXPECT_EQ(MathUtil::IPow(std::numeric_limits<double>::quiet_NaN(), 0.0), 1.0); // pow(-∞, exp) returns -∞ if exp is a positive odd integer EXPECT_EQ(MathUtil::IPow(-kInf, 43), -kInf); // pow(-∞, exp) returns +∞ if exp is a positive non-integer or even integer EXPECT_EQ(MathUtil::IPow(-kInf, 42), +kInf); // pow(+∞, exp) returns +∞ for any positive exp EXPECT_EQ(MathUtil::IPow(+kInf, 42), +kInf); EXPECT_EQ(MathUtil::IPow(+kInf, 43), +kInf); EXPECT_EQ(pow(std::numeric_limits<int>::max() >> 0, 1), MathUtil::IPow(std::numeric_limits<int>::max() >> 0, 1)); EXPECT_EQ(pow(std::numeric_limits<int>::max() >> 16, 2), MathUtil::IPow(std::numeric_limits<int>::max() >> 16, 2)); // 2 - These do not apply due to the restricted exp range. // pow(+0, exp), where exp is a negative odd integer, returns +∞ and raises // FE_DIVBYZERO pow(-0, exp), where exp is a negative odd integer, returns -∞ // and raises FE_DIVBYZERO pow(±0, exp), where exp is negative, finite, and is // an even integer or a non-integer, returns +∞ and raises FE_DIVBYZERO // pow(-1, ±∞) returns 1 // pow(+1, exp) returns 1 for any exp, even when exp is NaN // pow(±0, -∞) returns +∞ and may raise FE_DIVBYZERO // pow(base, exp) returns NaN and raises FE_INVALID if base is finite and // negative and exp is finite and non-integer. pow(base, -∞) returns +∞ for // any |base|<1 pow(base, -∞) returns +0 for any |base|>1 pow(base, +∞) // returns +0 for any |base|<1 pow(base, +∞) returns +∞ for any |base|>1 // pow(-∞, exp) returns -0 if exp is a negative odd integer // pow(-∞, exp) returns +0 if exp is a negative non-integer or even integer // pow(+∞, exp) returns +0 for any negative exp } } // namespace } // namespace zetasql_base
#include <iostream> using namespace std; int main() { int n,r,sum=0,t; cout<<"Enter the Number= "; cin>>n; t=n; while(n>0) { r=n%10; sum=sum+(r*r*r); n=n/10; } if(t==sum) cout<<"Armstrong Number."; else cout<<"Not Armstrong Number."; return 0; }
// Distributed under the MIT License. // See LICENSE.txt for details. #include "Framework/TestingFramework.hpp" #include <cstddef> #include <memory> #include <string> #include <tuple> #include <utility> #include <vector> #include "DataStructures/DataBox/DataBox.hpp" #include "DataStructures/DataBox/Tag.hpp" #include "DataStructures/DataVector.hpp" #include "DataStructures/Tensor/Tensor.hpp" #include "DataStructures/Variables.hpp" #include "Framework/ActionTesting.hpp" #include "Framework/TestCreation.hpp" #include "Framework/TestHelpers.hpp" #include "IO/Observer/Actions/RegisterEvents.hpp" #include "IO/Observer/ArrayComponentId.hpp" #include "IO/Observer/ObservationId.hpp" #include "IO/Observer/ObserverComponent.hpp" #include "IO/Observer/Tags.hpp" #include "Options/Protocols/FactoryCreation.hpp" #include "Parallel/PhaseDependentActionList.hpp" #include "Parallel/Reduction.hpp" #include "Parallel/RegisterDerivedClassesWithCharm.hpp" #include "Parallel/Tags/Metavariables.hpp" #include "ParallelAlgorithms/Events/ObserveNorms.hpp" #include "ParallelAlgorithms/EventsAndTriggers/Event.hpp" #include "Time/Tags.hpp" #include "Utilities/ProtocolHelpers.hpp" #include "Utilities/StdHelpers.hpp" #include "Utilities/TMPL.hpp" namespace { struct Var0 : db::SimpleTag { using type = Scalar<DataVector>; }; struct Var1 : db::SimpleTag { using type = tnsr::I<DataVector, 3, Frame::Inertial>; }; struct TestSectionIdTag {}; struct MockContributeReductionData { struct Results { observers::ObservationId observation_id; std::string subfile_name; std::vector<std::string> reduction_names; double time; size_t number_of_grid_points; std::vector<double> max_values; std::vector<double> min_values; std::vector<double> l2_norm_values; }; // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) static Results results; template <typename ParallelComponent, typename... DbTags, typename Metavariables, typename ArrayIndex, typename... Ts> static void apply(db::DataBox<tmpl::list<DbTags...>>& /*box*/, Parallel::GlobalCache<Metavariables>& /*cache*/, const ArrayIndex& /*array_index*/, const observers::ObservationId& observation_id, observers::ArrayComponentId /*sender_array_id*/, const std::string& subfile_name, const std::vector<std::string>& reduction_names, Parallel::ReductionData<Ts...>&& reduction_data) noexcept { reduction_data.finalize(); results.observation_id = observation_id; results.subfile_name = subfile_name; results.reduction_names = reduction_names; results.time = std::get<0>(reduction_data.data()); results.number_of_grid_points = std::get<1>(reduction_data.data()); results.max_values = std::get<2>(reduction_data.data()); results.min_values = std::get<3>(reduction_data.data()); results.l2_norm_values = std::get<4>(reduction_data.data()); } }; // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) MockContributeReductionData::Results MockContributeReductionData::results{}; template <typename Metavariables> struct ElementComponent { using component_being_mocked = void; using metavariables = Metavariables; using chare_type = ActionTesting::MockArrayChare; using array_index = int; using phase_dependent_action_list = tmpl::list<Parallel::PhaseActions<typename Metavariables::Phase, Metavariables::Phase::Initialization, tmpl::list<>>>; }; template <typename Metavariables> struct MockObserverComponent { using component_being_mocked = observers::Observer<Metavariables>; using replace_these_simple_actions = tmpl::list<observers::Actions::ContributeReductionData>; using with_these_simple_actions = tmpl::list<MockContributeReductionData>; using metavariables = Metavariables; using chare_type = ActionTesting::MockGroupChare; using array_index = int; using phase_dependent_action_list = tmpl::list<Parallel::PhaseActions<typename Metavariables::Phase, Metavariables::Phase::Initialization, tmpl::list<>>>; }; template <typename ArraySectionIdTag> struct Metavariables { using component_list = tmpl::list<ElementComponent<Metavariables>, MockObserverComponent<Metavariables>>; struct factory_creation : tt::ConformsTo<Options::protocols::FactoryCreation> { using factory_classes = tmpl::map<tmpl::pair< Event, tmpl::list<Events::ObserveNorms< ::Tags::Time, tmpl::list<Var0, Var1>, ArraySectionIdTag>>>>; }; enum class Phase { Initialization, Testing, Exit }; }; template <typename ArraySectionIdTag, typename ObserveEvent> void test(const std::unique_ptr<ObserveEvent> observe, const std::optional<std::string>& section) { CAPTURE(pretty_type::short_name<ArraySectionIdTag>()); CAPTURE(section); using metavariables = Metavariables<ArraySectionIdTag>; using element_component = ElementComponent<metavariables>; using observer_component = MockObserverComponent<metavariables>; const typename element_component::array_index array_index(0); const size_t num_points = 5; const double observation_time = 2.0; Variables<tmpl::list<Var0, Var1>> vars(num_points); // Fill the variables with some data. It doesn't matter much what, // but integers are nice in that we don't have to worry about // roundoff error. // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) std::iota(vars.data(), vars.data() + vars.size(), 1.0); ActionTesting::MockRuntimeSystem<metavariables> runner{{}}; ActionTesting::emplace_component<element_component>(make_not_null(&runner), 0); ActionTesting::emplace_group_component<observer_component>(&runner); const auto box = db::create<db::AddSimpleTags< Parallel::Tags::MetavariablesImpl<metavariables>, ::Tags::Time, Tags::Variables<typename decltype(vars)::tags_list>, observers::Tags::ObservationKey<ArraySectionIdTag>>>( metavariables{}, observation_time, vars, section); const auto ids_to_register = observers::get_registration_observation_type_and_key(*observe, box); const std::string expected_subfile_name{ "/reduction0" + (std::is_same_v<ArraySectionIdTag, void> ? "" : section.value_or("Unused"))}; const observers::ObservationKey expected_observation_key_for_reg( expected_subfile_name + ".dat"); if (std::is_same_v<ArraySectionIdTag, void> or section.has_value()) { CHECK(ids_to_register->first == observers::TypeOfObservation::Reduction); CHECK(ids_to_register->second == expected_observation_key_for_reg); } else { CHECK_FALSE(ids_to_register.has_value()); } CHECK(static_cast<const Event&>(*observe).is_ready( box, ActionTesting::cache<element_component>(runner, array_index), array_index, std::add_pointer_t<element_component>{})); observe->run(box, ActionTesting::cache<element_component>(runner, array_index), array_index, std::add_pointer_t<element_component>{}); // Process the data runner.template invoke_queued_simple_action<observer_component>(0); CHECK(runner.template is_simple_action_queue_empty<observer_component>(0)); const auto& results = MockContributeReductionData::results; CHECK(results.observation_id.value() == observation_time); CHECK(results.subfile_name == expected_subfile_name); CHECK(results.reduction_names[0] == "Time"); CHECK(results.time == observation_time); CHECK(results.reduction_names[1] == "NumberOfPoints"); CHECK(results.number_of_grid_points == num_points); // Check max values CHECK(results.reduction_names[2] == "Max(Var0)"); CHECK(results.reduction_names[3] == "Max(Var0)"); CHECK(results.max_values == std::vector<double>{5.0, 5.0}); // Check min values CHECK(results.reduction_names[4] == "Min(Var1_x)"); CHECK(results.reduction_names[5] == "Min(Var1_y)"); CHECK(results.reduction_names[6] == "Min(Var1_z)"); CHECK(results.reduction_names[7] == "Min(Var1)"); CHECK(results.min_values == std::vector<double>{6.0, 11.0, 16.0, 6.0}); // Check L2 norms CHECK(results.reduction_names[8] == "L2Norm(Var1)"); CHECK(results.reduction_names[9] == "L2Norm(Var1_x)"); CHECK(results.reduction_names[10] == "L2Norm(Var1_y)"); CHECK(results.reduction_names[11] == "L2Norm(Var1_z)"); CHECK(results.l2_norm_values[0] == approx(23.72762103540934575)); CHECK(results.l2_norm_values[1] == approx(8.12403840463596083)); CHECK(results.l2_norm_values[2] == approx(13.076696830622021)); CHECK(results.l2_norm_values[3] == approx(18.055470085267789)); } } // namespace SPECTRE_TEST_CASE("Unit.Evolution.ObserveNorms", "[Unit][Evolution]") { test<TestSectionIdTag>( std::make_unique<Events::ObserveNorms< ::Tags::Time, tmpl::list<Var0, Var1>, TestSectionIdTag>>( Events::ObserveNorms<::Tags::Time, tmpl::list<Var0, Var1>, TestSectionIdTag>{ "reduction0", {{"Var0", "Max", "Individual"}, {"Var1", "Min", "Individual"}, {"Var0", "Max", "Sum"}, {"Var1", "L2Norm", "Sum"}, {"Var1", "L2Norm", "Individual"}, {"Var1", "Min", "Sum"}}}), "Section0"); INFO("create/serialize"); Parallel::register_factory_classes_with_charm<Metavariables<void>>(); const auto factory_event = TestHelpers::test_creation<std::unique_ptr<Event>, Metavariables<void>>( // [input_file_examples] R"( ObserveNorms: SubfileName: reduction0 TensorsToObserve: - Name: Var0 NormType: Max Components: Individual - Name: Var1 NormType: Min Components: Individual - Name: Var0 NormType: Max Components: Sum - Name: Var1 NormType: L2Norm Components: Sum - Name: Var1 NormType: L2Norm Components: Individual - Name: Var1 NormType: Min Components: Sum )"); // [input_file_examples] auto serialized_event = serialize_and_deserialize(factory_event); test<void>(std::move(serialized_event), std::nullopt); }
// RUN: %clang_cc1 -fsyntax-only -verify %s // expected-no-diagnostics enum gcc_type_class { no_type_class = -1, void_type_class, integer_type_class, char_type_class, enumeral_type_class, boolean_type_class, pointer_type_class, reference_type_class, offset_type_class, real_type_class, complex_type_class, function_type_class, method_type_class, record_type_class, union_type_class, array_type_class, string_type_class, lang_type_class }; class cl { public: void bar() {} int baz; }; int builtin_result; void foo() { int i; char c; enum { red, green, blue} enum_obj; bool b; int *p; int &r = i; double d; extern void f(); cl cl_obj; union { int a; float b; } u_obj; int arr[10]; int a1[__builtin_classify_type(f()) == void_type_class ? 1 : -1]; int a2[__builtin_classify_type(i) == integer_type_class ? 1 : -1]; int a3[__builtin_classify_type(c) == integer_type_class ? 1 : -1]; int a4[__builtin_classify_type(enum_obj) == enumeral_type_class ? 1 : -1]; int a5[__builtin_classify_type(b) == boolean_type_class ? 1 : -1]; int a6[__builtin_classify_type(p) == pointer_type_class ? 1 : -1]; int a7[__builtin_classify_type(r) == integer_type_class ? 1 : -1]; int a8[__builtin_classify_type(&cl::baz) == offset_type_class ? 1 : -1]; int a9[__builtin_classify_type(d) == real_type_class ? 1 : -1]; int a10[__builtin_classify_type(f) == function_type_class ? 1 : -1]; int a11[__builtin_classify_type(&cl::bar) == method_type_class ? 1 : -1]; int a12[__builtin_classify_type(cl_obj) == record_type_class ? 1 : -1]; int a13[__builtin_classify_type(u_obj) == union_type_class ? 1 : -1]; int a14[__builtin_classify_type(arr) == array_type_class ? 1 : -1]; int a15[__builtin_classify_type("abc") == array_type_class ? 1 : -1]; }
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" using namespace std; using namespace Common; using namespace ServiceModel; using namespace Hosting2; GetContainerInfoReply::GetContainerInfoReply() : error_(ErrorCodeValue::Success) { } GetContainerInfoReply::GetContainerInfoReply( std::wstring const & containerInfo, ErrorCode error) : containerInfo_(containerInfo), error_(error) { auto maxContainerInfoContentSize = static_cast<size_t>( ServiceModelConfig::GetConfig().MaxMessageSize * ServiceModelConfig::GetConfig().MessageContentBufferRatio); StringUtility::TruncateStartIfNeeded(containerInfo_, maxContainerInfoContentSize); } void GetContainerInfoReply::WriteTo(TextWriter & w, FormatOptions const &) const { w.Write("GetContainerInfoReply { "); w.Write("ContainerInfo = {0}", containerInfo_); w.Write("Error = {0}", error_); w.Write("}"); }
#include "dense-reconstruction/aslam-cv-interface.h" #include <algorithm> #include <iostream> #include <iterator> #include <string> #include <vector> #include <Eigen/Dense> #include <aslam/cameras/camera-pinhole.h> #include <aslam/cameras/camera.h> #include <aslam/cameras/distortion.h> #include <aslam/common/pose-types.h> #include "dense-reconstruction/stereo-camera-utils.h" namespace dense_reconstruction { namespace stereo { void getDistortionFromAslamCvCameras( const aslam::Camera& camera, std::vector<double>* D, DistortionModel* model) { CHECK_NOTNULL(model); CHECK_NOTNULL(D); const aslam::Distortion& distortion = camera.getDistortion(); *D = std::vector<double>(5, 0.0); switch (distortion.getType()) { case aslam::Distortion::Type::kNoDistortion: *model = DistortionModel::RADTAN; return; case aslam::Distortion::Type::kEquidistant: *model = DistortionModel::EQUIDISTANT; break; case aslam::Distortion::Type::kFisheye: *model = DistortionModel::FOV; break; case aslam::Distortion::Type::kRadTan: *model = DistortionModel::RADTAN; break; default: LOG(FATAL) << "Unknown distortion model!"; } const Eigen::VectorXd distortion_params = distortion.getParameters(); CHECK_LE(distortion_params.size(), 5); for (int i = 0; i < distortion_params.size(); ++i) { (*D)[i] = distortion_params[i]; } } void getStereoPairFromAslamCvCameras( const aslam::Camera& first_camera, const aslam::Camera& second_camera, const aslam::Transformation& T_C2_C1, const double scale, StereoCameraParameters* stereo_camera_params) { CHECK_NOTNULL(stereo_camera_params); *stereo_camera_params = StereoCameraParameters(scale); // We assume frame G == C1 for the stereo matching. // Therefore T_C1_C2 == T_G_C2 and T_G_C1 = Identity. const Eigen::Matrix4d T_G_C2_mat = T_C2_C1.getTransformationMatrix(); const Eigen::Matrix4d T_G_C1_mat = Eigen::Matrix4d::Identity(); Eigen::Matrix3d K_first, K_second; if (first_camera.getType() == aslam::Camera::Type::kPinhole) { K_first = static_cast<const aslam::PinholeCamera&>(first_camera) .getCameraMatrix(); } else { LOG(FATAL) << "Currently only the pinhole camera model is supported!"; } if (second_camera.getType() == aslam::Camera::Type::kPinhole) { K_second = static_cast<const aslam::PinholeCamera&>(second_camera) .getCameraMatrix(); } else { LOG(FATAL) << "Currently only the pinhole camera model is supported!"; } const cv::Size resolution_first( first_camera.imageWidth(), first_camera.imageHeight()); const cv::Size resolution_second( second_camera.imageWidth(), second_camera.imageHeight()); std::vector<double> D_first, D_second; DistortionModel distortion_model_first, distortion_model_second; getDistortionFromAslamCvCameras( first_camera, &D_first, &distortion_model_first); getDistortionFromAslamCvCameras( second_camera, &D_second, &distortion_model_second); CHECK( stereo_camera_params->setInputCameraParameters( resolution_first, T_G_C1_mat, K_first, D_first, distortion_model_first, CameraSide::FIRST)); CHECK( stereo_camera_params->setInputCameraParameters( resolution_second, T_G_C2_mat, K_second, D_second, distortion_model_second, CameraSide::SECOND)); } } // namespace stereo } // namespace dense_reconstruction
#ifndef STAN_MATH_PRIM_PROB_POISSON_BINOMIAL_LCCDF_HPP #define STAN_MATH_PRIM_PROB_POISSON_BINOMIAL_LCCDF_HPP #include <stan/math/prim/meta.hpp> #include <stan/math/prim/err.hpp> #include <stan/math/prim/fun/binomial_coefficient_log.hpp> #include <stan/math/prim/fun/log.hpp> #include <stan/math/prim/fun/log1m.hpp> #include <stan/math/prim/fun/log_sum_exp.hpp> #include <stan/math/prim/fun/log1m_exp.hpp> #include <stan/math/prim/fun/max_size.hpp> #include <stan/math/prim/fun/multiply_log.hpp> #include <stan/math/prim/fun/scalar_seq_view.hpp> #include <stan/math/prim/fun/size.hpp> #include <stan/math/prim/fun/size_zero.hpp> #include <stan/math/prim/fun/value_of.hpp> #include <stan/math/prim/fun/poisson_binomial_log_probs.hpp> #include <stan/math/prim/fun/vector_seq_view.hpp> namespace stan { namespace math { /** \ingroup prob_dists * Returns the log CCDF for the Poisson-binomial distribution evaluated at the * specified number of successes and probabilities of successes. * * @tparam T_y type of number of successes parameter * @tparam T_theta type of chance of success parameters * @param y input scalar, vector, or nested vector of numbers of successes * @param theta array of chances of success parameters * @return sum of log probabilities * @throw std::domain_error if y is out of bounds * @throw std::domain_error if theta is not a valid vector of probabilities * @throw std::invalid_argument If y and theta are different lengths */ template <bool propto, typename T_y, typename T_theta> return_type_t<T_theta> poisson_binomial_lccdf(const T_y& y, const T_theta& theta) { static const char* function = "poisson_binomial_lccdf"; size_t size_theta = size_mvt(theta); if (size_theta > 1) { check_consistent_sizes(function, "Successes variables", y, "Probability parameters", theta); } size_t max_sz = std::max(stan::math::size(y), size_mvt(theta)); scalar_seq_view<T_y> y_vec(y); vector_seq_view<T_theta> theta_vec(theta); for (size_t i = 0; i < max_sz; ++i) { check_bounded(function, "Successes variable", y_vec[i], 0, theta_vec[i].size()); check_finite(function, "Probability parameters", theta_vec.val(i)); check_bounded(function, "Probability parameters", theta_vec.val(i), 0.0, 1.0); } return_type_t<T_theta> lccdf = 0.0; for (size_t i = 0; i < max_sz; ++i) { if (stan::math::size(theta_vec[i]) == 1) { if (y_vec[i] == 0) { lccdf += log(theta_vec[i][0]); } else { lccdf -= stan::math::INFTY; } } else { auto x = log1m_exp( log_sum_exp(poisson_binomial_log_probs(y_vec[i], theta_vec[i]))); lccdf += x; } } return lccdf; } template <typename T_y, typename T_theta> return_type_t<T_theta> poisson_binomial_lccdf(const T_y& y, const T_theta& theta) { return poisson_binomial_lccdf<false>(y, theta); } } // namespace math } // namespace stan #endif
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // --- // Author: Sainbayar Sukhbaatar // Dai Mikurube // #include "deep-heap-profile.h" #ifdef DEEP_HEAP_PROFILE #include <algorithm> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #ifdef HAVE_UNISTD_H #include <unistd.h> // for getpagesize and getpid #endif // HAVE_UNISTD_H #include "base/cycleclock.h" #include "base/sysinfo.h" #include "internal_logging.h" // for ASSERT, etc static const int kProfilerBufferSize = 1 << 20; static const int kHashTableSize = 179999; // Same as heap-profile-table.cc. static const int PAGEMAP_BYTES = 8; static const uint64 MAX_ADDRESS = kuint64max; // Tag strings in heap profile dumps. static const char kProfileHeader[] = "heap profile: "; static const char kProfileVersion[] = "DUMP_DEEP_6"; static const char kMMapListHeader[] = "MMAP_LIST:\n"; static const char kGlobalStatsHeader[] = "GLOBAL_STATS:\n"; static const char kStacktraceHeader[] = "STACKTRACES:\n"; static const char kProcSelfMapsHeader[] = "\nMAPPED_LIBRARIES:\n"; static const char kVirtualLabel[] = "virtual"; static const char kCommittedLabel[] = "committed"; const char* DeepHeapProfile::kMapsRegionTypeDict[] = { "absent", "anonymous", "file-exec", "file-nonexec", "stack", "other", }; namespace { #if defined(__linux__) // Implements MemoryResidenceInfoGetterInterface for Linux. class MemoryInfoGetterLinux : public DeepHeapProfile::MemoryResidenceInfoGetterInterface { public: MemoryInfoGetterLinux(): fd_(kIllegalRawFD) {} virtual ~MemoryInfoGetterLinux() {} // Opens /proc/<pid>/pagemap and stores its file descriptor. // It keeps open while the process is running. // // Note that file descriptors need to be refreshed after fork. virtual void Initialize(); // Returns the number of resident (including swapped) bytes of the given // memory region from |first_address| to |last_address| inclusive. virtual size_t CommittedSize(uint64 first_address, uint64 last_address) const; private: struct State { bool is_committed; // Currently, we use only this bool is_present; bool is_swapped; bool is_shared; bool is_mmap; }; // Seeks to the offset of the open pagemap file. // It returns true if succeeded. bool Seek(uint64 address) const; // Reads a pagemap state from the current offset. // It returns true if succeeded. bool Read(State* state) const; RawFD fd_; }; void MemoryInfoGetterLinux::Initialize() { char filename[100]; snprintf(filename, sizeof(filename), "/proc/%d/pagemap", static_cast<int>(getpid())); fd_ = open(filename, O_RDONLY); RAW_DCHECK(fd_ != -1, "Failed to open /proc/self/pagemap"); } size_t MemoryInfoGetterLinux::CommittedSize( uint64 first_address, uint64 last_address) const { int page_size = getpagesize(); uint64 page_address = (first_address / page_size) * page_size; size_t committed_size = 0; Seek(first_address); // Check every page on which the allocation resides. while (page_address <= last_address) { // Read corresponding physical page. State state; // TODO(dmikurube): Read pagemap in bulk for speed. // TODO(dmikurube): Consider using mincore(2). if (Read(&state) == false) { // We can't read the last region (e.g vsyscall). #ifndef NDEBUG RAW_LOG(0, "pagemap read failed @ %#llx %"PRId64" bytes", first_address, last_address - first_address + 1); #endif return 0; } if (state.is_committed) { // Calculate the size of the allocation part in this page. size_t bytes = page_size; // If looking at the last page in a given region. if (last_address <= page_address - 1 + page_size) { bytes = last_address - page_address + 1; } // If looking at the first page in a given region. if (page_address < first_address) { bytes -= first_address - page_address; } committed_size += bytes; } if (page_address > MAX_ADDRESS - page_size) { break; } page_address += page_size; } return committed_size; } bool MemoryInfoGetterLinux::Seek(uint64 address) const { int64 index = (address / getpagesize()) * PAGEMAP_BYTES; int64 offset = lseek64(fd_, index, SEEK_SET); RAW_DCHECK(offset == index, "Failed in seeking."); return offset >= 0; } bool MemoryInfoGetterLinux::Read(State* state) const { static const uint64 U64_1 = 1; static const uint64 PFN_FILTER = (U64_1 << 55) - U64_1; static const uint64 PAGE_PRESENT = U64_1 << 63; static const uint64 PAGE_SWAP = U64_1 << 62; static const uint64 PAGE_RESERVED = U64_1 << 61; static const uint64 FLAG_NOPAGE = U64_1 << 20; static const uint64 FLAG_KSM = U64_1 << 21; static const uint64 FLAG_MMAP = U64_1 << 11; uint64 pagemap_value; int result = read(fd_, &pagemap_value, PAGEMAP_BYTES); if (result != PAGEMAP_BYTES) { return false; } // Check if the page is committed. state->is_committed = (pagemap_value & (PAGE_PRESENT | PAGE_SWAP)); state->is_present = (pagemap_value & PAGE_PRESENT); state->is_swapped = (pagemap_value & PAGE_SWAP); state->is_shared = false; return true; } #endif // defined(__linux__) } // anonymous namespace DeepHeapProfile::MemoryResidenceInfoGetterInterface:: MemoryResidenceInfoGetterInterface() {} DeepHeapProfile::MemoryResidenceInfoGetterInterface:: ~MemoryResidenceInfoGetterInterface() {} DeepHeapProfile::MemoryResidenceInfoGetterInterface* DeepHeapProfile::MemoryResidenceInfoGetterInterface::Create() { #if defined(__linux__) return new MemoryInfoGetterLinux(); #else return NULL; #endif } DeepHeapProfile::DeepHeapProfile(HeapProfileTable* heap_profile, const char* prefix) : memory_residence_info_getter_( MemoryResidenceInfoGetterInterface::Create()), most_recent_pid_(-1), stats_(), dump_count_(0), filename_prefix_(NULL), profiler_buffer_(NULL), deep_table_(kHashTableSize, heap_profile->alloc_, heap_profile->dealloc_), heap_profile_(heap_profile) { // Copy filename prefix. const int prefix_length = strlen(prefix); filename_prefix_ = reinterpret_cast<char*>(heap_profile_->alloc_(prefix_length + 1)); memcpy(filename_prefix_, prefix, prefix_length); filename_prefix_[prefix_length] = '\0'; profiler_buffer_ = reinterpret_cast<char*>(heap_profile_->alloc_(kProfilerBufferSize)); } DeepHeapProfile::~DeepHeapProfile() { heap_profile_->dealloc_(profiler_buffer_); heap_profile_->dealloc_(filename_prefix_); delete memory_residence_info_getter_; } // Global malloc() should not be used in this function. // Use LowLevelAlloc if required. int DeepHeapProfile::FillOrderedProfile(char raw_buffer[], int buffer_size) { TextBuffer buffer(raw_buffer, buffer_size); TextBuffer global_buffer(profiler_buffer_, kProfilerBufferSize); #ifndef NDEBUG int64 starting_cycles = CycleClock::Now(); #endif ++dump_count_; // Re-open files in /proc/pid/ if the process is newly forked one. if (most_recent_pid_ != getpid()) { most_recent_pid_ = getpid(); memory_residence_info_getter_->Initialize(); deep_table_.ResetIsLogged(); // Write maps into "|filename_prefix_|.<pid>.maps". WriteProcMaps(filename_prefix_, kProfilerBufferSize, profiler_buffer_); } // Reset committed sizes of buckets. deep_table_.ResetCommittedSize(); // Record committed sizes. stats_.SnapshotAllocations(this); // TODO(dmikurube): Eliminate dynamic memory allocation caused by snprintf. // glibc's snprintf internally allocates memory by alloca normally, but it // allocates memory by malloc if large memory is required. buffer.AppendString(kProfileHeader, 0); buffer.AppendString(kProfileVersion, 0); buffer.AppendString("\n", 0); // Fill buffer with the global stats. buffer.AppendString(kMMapListHeader, 0); stats_.SnapshotMaps(memory_residence_info_getter_, this, &buffer); // Fill buffer with the global stats. buffer.AppendString(kGlobalStatsHeader, 0); stats_.Unparse(&buffer); buffer.AppendString(kStacktraceHeader, 0); buffer.AppendString(kVirtualLabel, 10); buffer.AppendChar(' '); buffer.AppendString(kCommittedLabel, 10); buffer.AppendString("\n", 0); // Fill buffer. deep_table_.UnparseForStats(&buffer); RAW_DCHECK(buffer.FilledBytes() < buffer_size, ""); // Write the bucket listing into a .bucket file. deep_table_.WriteForBucketFile(filename_prefix_, dump_count_, &global_buffer); #ifndef NDEBUG int64 elapsed_cycles = CycleClock::Now() - starting_cycles; double elapsed_seconds = elapsed_cycles / CyclesPerSecond(); RAW_LOG(0, "Time spent on DeepProfiler: %.3f sec\n", elapsed_seconds); #endif return buffer.FilledBytes(); } int DeepHeapProfile::TextBuffer::Size() { return size_; } int DeepHeapProfile::TextBuffer::FilledBytes() { return cursor_; } void DeepHeapProfile::TextBuffer::Clear() { cursor_ = 0; } void DeepHeapProfile::TextBuffer::Write(RawFD fd) { RawWrite(fd, buffer_, cursor_); } // TODO(dmikurube): These Append* functions should not use snprintf. bool DeepHeapProfile::TextBuffer::AppendChar(char v) { return ForwardCursor(snprintf(buffer_ + cursor_, size_ - cursor_, "%c", v)); } bool DeepHeapProfile::TextBuffer::AppendString(const char* s, int d) { int appended; if (d == 0) appended = snprintf(buffer_ + cursor_, size_ - cursor_, "%s", s); else appended = snprintf(buffer_ + cursor_, size_ - cursor_, "%*s", d, s); return ForwardCursor(appended); } bool DeepHeapProfile::TextBuffer::AppendInt(int v, int d) { int appended; if (d == 0) appended = snprintf(buffer_ + cursor_, size_ - cursor_, "%d", v); else appended = snprintf(buffer_ + cursor_, size_ - cursor_, "%*d", d, v); return ForwardCursor(appended); } bool DeepHeapProfile::TextBuffer::AppendLong(long v, int d) { int appended; if (d == 0) appended = snprintf(buffer_ + cursor_, size_ - cursor_, "%ld", v); else appended = snprintf(buffer_ + cursor_, size_ - cursor_, "%*ld", d, v); return ForwardCursor(appended); } bool DeepHeapProfile::TextBuffer::AppendUnsignedLong(unsigned long v, int d) { int appended; if (d == 0) appended = snprintf(buffer_ + cursor_, size_ - cursor_, "%lu", v); else appended = snprintf(buffer_ + cursor_, size_ - cursor_, "%*lu", d, v); return ForwardCursor(appended); } bool DeepHeapProfile::TextBuffer::AppendInt64(int64 v, int d) { int appended; if (d == 0) appended = snprintf(buffer_ + cursor_, size_ - cursor_, "%"PRId64, v); else appended = snprintf(buffer_ + cursor_, size_ - cursor_, "%*"PRId64, d, v); return ForwardCursor(appended); } bool DeepHeapProfile::TextBuffer::AppendPtr(uint64 v, int d) { int appended; if (d == 0) appended = snprintf(buffer_ + cursor_, size_ - cursor_, "%"PRIxPTR, v); else appended = snprintf(buffer_ + cursor_, size_ - cursor_, "%0*"PRIxPTR, d, v); return ForwardCursor(appended); } bool DeepHeapProfile::TextBuffer::ForwardCursor(int appended) { if (appended < 0 || appended >= size_ - cursor_) return false; cursor_ += appended; return true; } void DeepHeapProfile::DeepBucket::UnparseForStats(TextBuffer* buffer) { buffer->AppendInt64(bucket->alloc_size - bucket->free_size, 10); buffer->AppendChar(' '); buffer->AppendInt64(committed_size, 10); buffer->AppendChar(' '); buffer->AppendInt(bucket->allocs, 6); buffer->AppendChar(' '); buffer->AppendInt(bucket->frees, 6); buffer->AppendString(" @ ", 0); buffer->AppendInt(id, 0); buffer->AppendString("\n", 0); } void DeepHeapProfile::DeepBucket::UnparseForBucketFile(TextBuffer* buffer) { buffer->AppendInt(id, 0); buffer->AppendChar(' '); buffer->AppendString(is_mmap ? "mmap" : "malloc", 0); #if defined(TYPE_PROFILING) buffer->AppendString(" t0x", 0); buffer->AppendPtr(reinterpret_cast<uintptr_t>(type), 0); if (type == NULL) { buffer->AppendString(" nno_typeinfo", 0); } else { buffer->AppendString(" n", 0); buffer->AppendString(type->name(), 0); } #endif for (int depth = 0; depth < bucket->depth; depth++) { buffer->AppendString(" 0x", 0); buffer->AppendPtr(reinterpret_cast<uintptr_t>(bucket->stack[depth]), 8); } buffer->AppendString("\n", 0); } DeepHeapProfile::DeepBucketTable::DeepBucketTable( int table_size, HeapProfileTable::Allocator alloc, HeapProfileTable::DeAllocator dealloc) : table_(NULL), table_size_(table_size), alloc_(alloc), dealloc_(dealloc), bucket_id_(0) { const int bytes = table_size * sizeof(DeepBucket*); table_ = reinterpret_cast<DeepBucket**>(alloc(bytes)); memset(table_, 0, bytes); } DeepHeapProfile::DeepBucketTable::~DeepBucketTable() { ASSERT(table_ != NULL); for (int db = 0; db < table_size_; db++) { for (DeepBucket* x = table_[db]; x != 0; /**/) { DeepBucket* db = x; x = x->next; dealloc_(db); } } dealloc_(table_); } DeepHeapProfile::DeepBucket* DeepHeapProfile::DeepBucketTable::Lookup( Bucket* bucket, #if defined(TYPE_PROFILING) const std::type_info* type, #endif bool is_mmap) { // Make hash-value uintptr_t h = 0; AddToHashValue(reinterpret_cast<uintptr_t>(bucket), &h); if (is_mmap) { AddToHashValue(1, &h); } else { AddToHashValue(0, &h); } #if defined(TYPE_PROFILING) if (type == NULL) { AddToHashValue(0, &h); } else { AddToHashValue(reinterpret_cast<uintptr_t>(type->name()), &h); } #endif FinishHashValue(&h); // Lookup stack trace in table unsigned int buck = ((unsigned int) h) % table_size_; for (DeepBucket* db = table_[buck]; db != 0; db = db->next) { if (db->bucket == bucket) { return db; } } // Create a new bucket DeepBucket* db = reinterpret_cast<DeepBucket*>(alloc_(sizeof(DeepBucket))); memset(db, 0, sizeof(*db)); db->bucket = bucket; #if defined(TYPE_PROFILING) db->type = type; #endif db->committed_size = 0; db->is_mmap = is_mmap; db->id = (bucket_id_++); db->is_logged = false; db->next = table_[buck]; table_[buck] = db; return db; } // TODO(dmikurube): Eliminate dynamic memory allocation caused by snprintf. void DeepHeapProfile::DeepBucketTable::UnparseForStats(TextBuffer* buffer) { for (int i = 0; i < table_size_; i++) { for (DeepBucket* deep_bucket = table_[i]; deep_bucket != NULL; deep_bucket = deep_bucket->next) { Bucket* bucket = deep_bucket->bucket; if (bucket->alloc_size - bucket->free_size == 0) { continue; // Skip empty buckets. } deep_bucket->UnparseForStats(buffer); } } } void DeepHeapProfile::DeepBucketTable::WriteForBucketFile( const char* prefix, int dump_count, TextBuffer* buffer) { char filename[100]; snprintf(filename, sizeof(filename), "%s.%05d.%04d.buckets", prefix, getpid(), dump_count); RawFD fd = RawOpenForWriting(filename); RAW_DCHECK(fd != kIllegalRawFD, ""); for (int i = 0; i < table_size_; i++) { for (DeepBucket* deep_bucket = table_[i]; deep_bucket != NULL; deep_bucket = deep_bucket->next) { Bucket* bucket = deep_bucket->bucket; if (deep_bucket->is_logged) { continue; // Skip the bucket if it is already logged. } if (bucket->alloc_size - bucket->free_size <= 64) { continue; // Skip small buckets. } deep_bucket->UnparseForBucketFile(buffer); deep_bucket->is_logged = true; // Write to file if buffer 80% full. if (buffer->FilledBytes() > buffer->Size() * 0.8) { buffer->Write(fd); buffer->Clear(); } } } buffer->Write(fd); RawClose(fd); } void DeepHeapProfile::DeepBucketTable::ResetCommittedSize() { for (int i = 0; i < table_size_; i++) { for (DeepBucket* deep_bucket = table_[i]; deep_bucket != NULL; deep_bucket = deep_bucket->next) { deep_bucket->committed_size = 0; } } } void DeepHeapProfile::DeepBucketTable::ResetIsLogged() { for (int i = 0; i < table_size_; i++) { for (DeepBucket* deep_bucket = table_[i]; deep_bucket != NULL; deep_bucket = deep_bucket->next) { deep_bucket->is_logged = false; } } } // This hash function is from HeapProfileTable::GetBucket. // static void DeepHeapProfile::DeepBucketTable::AddToHashValue( uintptr_t add, uintptr_t* hash_value) { *hash_value += add; *hash_value += *hash_value << 10; *hash_value ^= *hash_value >> 6; } // This hash function is from HeapProfileTable::GetBucket. // static void DeepHeapProfile::DeepBucketTable::FinishHashValue(uintptr_t* hash_value) { *hash_value += *hash_value << 3; *hash_value ^= *hash_value >> 11; } void DeepHeapProfile::RegionStats::Initialize() { virtual_bytes_ = 0; committed_bytes_ = 0; } uint64 DeepHeapProfile::RegionStats::Record( const MemoryResidenceInfoGetterInterface* memory_residence_info_getter, uint64 first_address, uint64 last_address) { uint64 committed; virtual_bytes_ += static_cast<size_t>(last_address - first_address + 1); committed = memory_residence_info_getter->CommittedSize(first_address, last_address); committed_bytes_ += committed; return committed; } void DeepHeapProfile::RegionStats::Unparse(const char* name, TextBuffer* buffer) { buffer->AppendString(name, 25); buffer->AppendChar(' '); buffer->AppendLong(virtual_bytes_, 12); buffer->AppendChar(' '); buffer->AppendLong(committed_bytes_, 12); buffer->AppendString("\n", 0); } // Snapshots all virtual memory mappging stats by merging mmap(2) records from // MemoryRegionMap and /proc/maps, the OS-level memory mapping information. // Memory regions described in /proc/maps, but which are not created by mmap, // are accounted as "unhooked" memory regions. // // This function assumes that every memory region created by mmap is covered // by VMA(s) described in /proc/maps except for http://crbug.com/189114. // Note that memory regions created with mmap don't align with borders of VMAs // in /proc/maps. In other words, a memory region by mmap can cut across many // VMAs. Also, of course a VMA can include many memory regions by mmap. // It means that the following situation happens: // // => Virtual address // <----- VMA #1 -----><----- VMA #2 ----->...<----- VMA #3 -----><- VMA #4 -> // ..< mmap #1 >.<- mmap #2 -><- mmap #3 ->...<- mmap #4 ->..<-- mmap #5 -->.. // // It can happen easily as permission can be changed by mprotect(2) for a part // of a memory region. A change in permission splits VMA(s). // // To deal with the situation, this function iterates over MemoryRegionMap and // /proc/maps independently. The iterator for MemoryRegionMap is initialized // at the top outside the loop for /proc/maps, and it goes forward inside the // loop while comparing their addresses. // // TODO(dmikurube): Eliminate dynamic memory allocation caused by snprintf. void DeepHeapProfile::GlobalStats::SnapshotMaps( const MemoryResidenceInfoGetterInterface* memory_residence_info_getter, DeepHeapProfile* deep_profile, TextBuffer* mmap_dump_buffer) { MemoryRegionMap::LockHolder lock_holder; ProcMapsIterator::Buffer procmaps_iter_buffer; ProcMapsIterator procmaps_iter(0, &procmaps_iter_buffer); uint64 vma_start_addr, vma_last_addr, offset; int64 inode; char* flags; char* filename; enum MapsRegionType type; for (int i = 0; i < NUMBER_OF_MAPS_REGION_TYPES; ++i) { all_[i].Initialize(); unhooked_[i].Initialize(); } profiled_mmap_.Initialize(); MemoryRegionMap::RegionIterator mmap_iter = MemoryRegionMap::BeginRegionLocked(); DeepBucket* deep_bucket = GetInformationOfMemoryRegion( mmap_iter, memory_residence_info_getter, deep_profile); while (procmaps_iter.Next(&vma_start_addr, &vma_last_addr, &flags, &offset, &inode, &filename)) { if (mmap_dump_buffer) { char buffer[1024]; int written = procmaps_iter.FormatLine(buffer, sizeof(buffer), vma_start_addr, vma_last_addr, flags, offset, inode, filename, 0); mmap_dump_buffer->AppendString(buffer, 0); } // 'vma_last_addr' should be the last inclusive address of the region. vma_last_addr -= 1; if (strcmp("[vsyscall]", filename) == 0) { continue; // Reading pagemap will fail in [vsyscall]. } type = ABSENT; if (filename[0] == '/') { if (flags[2] == 'x') type = FILE_EXEC; else type = FILE_NONEXEC; } else if (filename[0] == '\0' || filename[0] == '\n') { type = ANONYMOUS; } else if (strcmp(filename, "[stack]") == 0) { type = STACK; } else { type = OTHER; } all_[type].Record( memory_residence_info_getter, vma_start_addr, vma_last_addr); // TODO(dmikurube): Stop double-counting pagemap. if (MemoryRegionMap::IsRecordingLocked()) { uint64 cursor = vma_start_addr; bool first = true; // Iterates over MemoryRegionMap until the iterator moves out of the VMA. do { if (!first) { cursor = mmap_iter->end_addr; ++mmap_iter; // Don't break here even if mmap_iter == EndRegionLocked(). if (mmap_iter != MemoryRegionMap::EndRegionLocked()) { deep_bucket = GetInformationOfMemoryRegion( mmap_iter, memory_residence_info_getter, deep_profile); } } first = false; uint64 last_address_of_unhooked; // If the next mmap entry is away from the current VMA. if (mmap_iter == MemoryRegionMap::EndRegionLocked() || mmap_iter->start_addr > vma_last_addr) { last_address_of_unhooked = vma_last_addr; } else { last_address_of_unhooked = mmap_iter->start_addr - 1; } if (last_address_of_unhooked + 1 > cursor) { RAW_CHECK(cursor >= vma_start_addr, "Wrong calculation for unhooked"); RAW_CHECK(last_address_of_unhooked <= vma_last_addr, "Wrong calculation for unhooked"); uint64 committed_size = unhooked_[type].Record( memory_residence_info_getter, cursor, last_address_of_unhooked); if (mmap_dump_buffer) { mmap_dump_buffer->AppendString(" ", 0); mmap_dump_buffer->AppendPtr(cursor, 0); mmap_dump_buffer->AppendString(" - ", 0); mmap_dump_buffer->AppendPtr(last_address_of_unhooked + 1, 0); mmap_dump_buffer->AppendString(" unhooked ", 0); mmap_dump_buffer->AppendString(kMapsRegionTypeDict[type], 0); mmap_dump_buffer->AppendString(" ", 0); mmap_dump_buffer->AppendInt64(committed_size, 0); mmap_dump_buffer->AppendString("\n", 0); } cursor = last_address_of_unhooked + 1; } if (mmap_iter != MemoryRegionMap::EndRegionLocked() && mmap_iter->start_addr <= vma_last_addr && mmap_dump_buffer) { bool trailing = mmap_iter->start_addr < vma_start_addr; bool continued = mmap_iter->end_addr - 1 > vma_last_addr; mmap_dump_buffer->AppendString(trailing ? " (" : " ", 0); mmap_dump_buffer->AppendPtr(mmap_iter->start_addr, 0); mmap_dump_buffer->AppendString(trailing ? ")" : " ", 0); mmap_dump_buffer->AppendString("-", 0); mmap_dump_buffer->AppendString(continued ? "(" : " ", 0); mmap_dump_buffer->AppendPtr(mmap_iter->end_addr, 0); mmap_dump_buffer->AppendString(continued ? ")" : " ", 0); mmap_dump_buffer->AppendString(" hooked ", 0); mmap_dump_buffer->AppendString(kMapsRegionTypeDict[type], 0); mmap_dump_buffer->AppendString(" @ ", 0); if (deep_bucket != NULL) { mmap_dump_buffer->AppendInt(deep_bucket->id, 0); } else { mmap_dump_buffer->AppendInt(0, 0); } mmap_dump_buffer->AppendString("\n", 0); } } while (mmap_iter != MemoryRegionMap::EndRegionLocked() && mmap_iter->end_addr - 1 <= vma_last_addr); } } // TODO(dmikurube): Investigate and fix http://crbug.com/189114. // // The total committed memory usage in all_ (from /proc/<pid>/maps) is // sometimes smaller than the sum of the committed mmap'ed addresses and // unhooked regions. Within our observation, the difference was only 4KB // in committed usage, zero in reserved virtual addresses // // A guess is that an uncommitted (but reserved) page may become committed // during counting memory usage in the loop above. // // The difference is accounted as "ABSENT" to investigate such cases. RegionStats all_total; RegionStats unhooked_total; for (int i = 0; i < NUMBER_OF_MAPS_REGION_TYPES; ++i) { all_total.AddAnotherRegionStat(all_[i]); unhooked_total.AddAnotherRegionStat(unhooked_[i]); } size_t absent_virtual = profiled_mmap_.virtual_bytes() + unhooked_total.virtual_bytes() - all_total.virtual_bytes(); if (absent_virtual > 0) all_[ABSENT].AddToVirtualBytes(absent_virtual); size_t absent_committed = profiled_mmap_.committed_bytes() + unhooked_total.committed_bytes() - all_total.committed_bytes(); if (absent_committed > 0) all_[ABSENT].AddToCommittedBytes(absent_committed); } void DeepHeapProfile::GlobalStats::SnapshotAllocations( DeepHeapProfile* deep_profile) { profiled_malloc_.Initialize(); deep_profile->heap_profile_->address_map_->Iterate(RecordAlloc, deep_profile); } void DeepHeapProfile::GlobalStats::Unparse(TextBuffer* buffer) { RegionStats all_total; RegionStats unhooked_total; for (int i = 0; i < NUMBER_OF_MAPS_REGION_TYPES; ++i) { all_total.AddAnotherRegionStat(all_[i]); unhooked_total.AddAnotherRegionStat(unhooked_[i]); } // "# total (%lu) %c= profiled-mmap (%lu) + nonprofiled-* (%lu)\n" buffer->AppendString("# total (", 0); buffer->AppendUnsignedLong(all_total.committed_bytes(), 0); buffer->AppendString(") ", 0); buffer->AppendChar(all_total.committed_bytes() == profiled_mmap_.committed_bytes() + unhooked_total.committed_bytes() ? '=' : '!'); buffer->AppendString("= profiled-mmap (", 0); buffer->AppendUnsignedLong(profiled_mmap_.committed_bytes(), 0); buffer->AppendString(") + nonprofiled-* (", 0); buffer->AppendUnsignedLong(unhooked_total.committed_bytes(), 0); buffer->AppendString(")\n", 0); // " virtual committed" buffer->AppendString("", 26); buffer->AppendString(kVirtualLabel, 12); buffer->AppendChar(' '); buffer->AppendString(kCommittedLabel, 12); buffer->AppendString("\n", 0); all_total.Unparse("total", buffer); all_[ABSENT].Unparse("absent", buffer); all_[FILE_EXEC].Unparse("file-exec", buffer); all_[FILE_NONEXEC].Unparse("file-nonexec", buffer); all_[ANONYMOUS].Unparse("anonymous", buffer); all_[STACK].Unparse("stack", buffer); all_[OTHER].Unparse("other", buffer); unhooked_total.Unparse("nonprofiled-total", buffer); unhooked_[ABSENT].Unparse("nonprofiled-absent", buffer); unhooked_[ANONYMOUS].Unparse("nonprofiled-anonymous", buffer); unhooked_[FILE_EXEC].Unparse("nonprofiled-file-exec", buffer); unhooked_[FILE_NONEXEC].Unparse("nonprofiled-file-nonexec", buffer); unhooked_[STACK].Unparse("nonprofiled-stack", buffer); unhooked_[OTHER].Unparse("nonprofiled-other", buffer); profiled_mmap_.Unparse("profiled-mmap", buffer); profiled_malloc_.Unparse("profiled-malloc", buffer); } // static void DeepHeapProfile::GlobalStats::RecordAlloc(const void* pointer, AllocValue* alloc_value, DeepHeapProfile* deep_profile) { uint64 address = reinterpret_cast<uintptr_t>(pointer); size_t committed = deep_profile->memory_residence_info_getter_->CommittedSize( address, address + alloc_value->bytes - 1); DeepBucket* deep_bucket = deep_profile->deep_table_.Lookup( alloc_value->bucket(), #if defined(TYPE_PROFILING) LookupType(pointer), #endif /* is_mmap */ false); deep_bucket->committed_size += committed; deep_profile->stats_.profiled_malloc_.AddToVirtualBytes(alloc_value->bytes); deep_profile->stats_.profiled_malloc_.AddToCommittedBytes(committed); } DeepHeapProfile::DeepBucket* DeepHeapProfile::GlobalStats::GetInformationOfMemoryRegion( const MemoryRegionMap::RegionIterator& mmap_iter, const MemoryResidenceInfoGetterInterface* memory_residence_info_getter, DeepHeapProfile* deep_profile) { size_t committed = deep_profile->memory_residence_info_getter_-> CommittedSize(mmap_iter->start_addr, mmap_iter->end_addr - 1); // TODO(dmikurube): Store a reference to the bucket in region. Bucket* bucket = MemoryRegionMap::GetBucket( mmap_iter->call_stack_depth, mmap_iter->call_stack); DeepBucket* deep_bucket = NULL; if (bucket != NULL) { deep_bucket = deep_profile->deep_table_.Lookup( bucket, #if defined(TYPE_PROFILING) NULL, // No type information for memory regions by mmap. #endif /* is_mmap */ true); if (deep_bucket != NULL) deep_bucket->committed_size += committed; } profiled_mmap_.AddToVirtualBytes( mmap_iter->end_addr - mmap_iter->start_addr); profiled_mmap_.AddToCommittedBytes(committed); return deep_bucket; } // static void DeepHeapProfile::WriteProcMaps(const char* prefix, int buffer_size, char raw_buffer[]) { char filename[100]; snprintf(filename, sizeof(filename), "%s.%05d.maps", prefix, static_cast<int>(getpid())); RawFD fd = RawOpenForWriting(filename); RAW_DCHECK(fd != kIllegalRawFD, ""); int length; bool wrote_all; length = tcmalloc::FillProcSelfMaps(raw_buffer, buffer_size, &wrote_all); RAW_DCHECK(wrote_all, ""); RAW_DCHECK(length <= buffer_size, ""); RawWrite(fd, raw_buffer, length); RawClose(fd); } #else // DEEP_HEAP_PROFILE DeepHeapProfile::DeepHeapProfile(HeapProfileTable* heap_profile, const char* prefix) : heap_profile_(heap_profile) { } DeepHeapProfile::~DeepHeapProfile() { } int DeepHeapProfile::FillOrderedProfile(char raw_buffer[], int buffer_size) { return heap_profile_->FillOrderedProfile(raw_buffer, buffer_size); } #endif // DEEP_HEAP_PROFILE
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ // Description : Implementation of IAnimSequence interface. #include "Maestro_precompiled.h" #include <Maestro/Bus/EditorSequenceComponentBus.h> #include "AnimSequence.h" #include "AnimAZEntityNode.h" #include "AnimComponentNode.h" #include "CVarNode.h" #include "ScriptVarNode.h" #include "SceneNode.h" #include "StlUtils.h" #include "MaterialNode.h" #include "EventNode.h" #include "LayerNode.h" #include "CommentNode.h" #include "AnimPostFXNode.h" #include "AnimScreenFaderNode.h" #include "ShadowsSetupNode.h" #include "SequenceTrack.h" #include "AnimNodeGroup.h" #include <Maestro/Types/AnimNodeType.h> #include <Maestro/Types/SequenceType.h> #include <Maestro/Types/AnimParamType.h> ////////////////////////////////////////////////////////////////////////// CAnimSequence::CAnimSequence(IMovieSystem* pMovieSystem, uint32 id, SequenceType sequenceType) : m_refCount(0) { m_nextGenId = 1; m_pMovieSystem = pMovieSystem; m_flags = 0; m_pParentSequence = NULL; m_timeRange.Set(0, 10); m_bPaused = false; m_bActive = false; m_legacySequenceObject = nullptr; m_activeDirector = NULL; m_activeDirectorNodeId = -1; m_precached = false; m_bResetting = false; m_sequenceType = sequenceType; m_time = -FLT_MAX; SetId(id); m_pEventStrings = aznew CAnimStringTable; m_expanded = true; } ////////////////////////////////////////////////////////////////////////// CAnimSequence::CAnimSequence() : CAnimSequence((gEnv) ? gEnv->pMovieSystem : nullptr, 0, SequenceType::SequenceComponent) { } CAnimSequence::~CAnimSequence() { // clear reference to me from all my nodes for (int i = m_nodes.size(); --i >= 0;) { if (m_nodes[i]) { m_nodes[i]->SetSequence(nullptr); } } } ////////////////////////////////////////////////////////////////////////// void CAnimSequence::add_ref() { ++m_refCount; } ////////////////////////////////////////////////////////////////////////// void CAnimSequence::release() { if (--m_refCount <= 0) { delete this; } } ////////////////////////////////////////////////////////////////////////// void CAnimSequence::SetName(const char* name) { if (!m_pMovieSystem) { return; // should never happen, null pointer guard } string originalName = GetName(); m_name = name; m_pMovieSystem->OnSequenceRenamed(originalName, m_name.c_str()); // the sequence named LIGHT_ANIMATION_SET_NAME is a singleton sequence to hold all light animations. if (m_name == LIGHT_ANIMATION_SET_NAME) { // ensure it stays a singleton. If one already exists, deregister it. if (CLightAnimWrapper::GetLightAnimSet()) { CLightAnimWrapper::InvalidateAllNodes(); CLightAnimWrapper::SetLightAnimSet(0); } CLightAnimWrapper::SetLightAnimSet(this); } } ////////////////////////////////////////////////////////////////////////// const char* CAnimSequence::GetName() const { return m_name.c_str(); } ////////////////////////////////////////////////////////////////////////// void CAnimSequence::ResetId() { if (!m_pMovieSystem) { return; // should never happen, null pointer guard } SetId(m_pMovieSystem->GrabNextSequenceId()); } ////////////////////////////////////////////////////////////////////////// void CAnimSequence::SetFlags(int flags) { m_flags = flags; } ////////////////////////////////////////////////////////////////////////// int CAnimSequence::GetFlags() const { return m_flags; } ////////////////////////////////////////////////////////////////////////// int CAnimSequence::GetCutSceneFlags(const bool localFlags) const { int currentFlags = m_flags & (eSeqFlags_NoHUD | eSeqFlags_NoPlayer | eSeqFlags_NoGameSounds | eSeqFlags_NoAbort); if (m_pParentSequence != NULL) { if (localFlags == true) { currentFlags &= ~m_pParentSequence->GetCutSceneFlags(); } else { currentFlags |= m_pParentSequence->GetCutSceneFlags(); } } return currentFlags; } ////////////////////////////////////////////////////////////////////////// void CAnimSequence::SetParentSequence(IAnimSequence* pParentSequence) { m_pParentSequence = pParentSequence; } ////////////////////////////////////////////////////////////////////////// const IAnimSequence* CAnimSequence::GetParentSequence() const { return m_pParentSequence; } ////////////////////////////////////////////////////////////////////////// int CAnimSequence::GetNodeCount() const { return m_nodes.size(); } ////////////////////////////////////////////////////////////////////////// IAnimNode* CAnimSequence::GetNode(int index) const { assert(index >= 0 && index < (int)m_nodes.size()); return m_nodes[index].get(); } ////////////////////////////////////////////////////////////////////////// bool CAnimSequence::AddNode(IAnimNode* animNode) { AZ_Assert(animNode, "Expected valid animNode"); if (!animNode) { return false; } animNode->SetSequence(this); animNode->SetTimeRange(m_timeRange); // Check if this node already in sequence. If found, don't add it again. bool found = false; for (int i = 0; i < (int)m_nodes.size(); i++) { if (animNode == m_nodes[i].get()) { found = true; break; } } if (!found) { m_nodes.push_back(AZStd::intrusive_ptr<IAnimNode>(animNode)); } const int nodeId = static_cast<CAnimNode*>(animNode)->GetId(); if (nodeId >= (int)m_nextGenId) { m_nextGenId = nodeId + 1; } // Make sure m_nextTrackId is bigger than the biggest existing track id. // m_nextTrackId is not serialized (track id's are) so this code will // exercise every time a sequence is loaded. int trackCount = animNode->GetTrackCount(); for (int trackIndex = 0; trackIndex < trackCount; trackIndex++) { IAnimTrack* track = animNode->GetTrackByIndex(trackIndex); AZ_Assert(track, "Expected valid track"); if (track->GetId() >= m_nextTrackId) { m_nextTrackId = track->GetId() + 1; } int subTrackCount = track->GetSubTrackCount(); for (int subTrackIndex = 0; subTrackIndex < subTrackCount; subTrackIndex++) { IAnimTrack* subTrack = track->GetSubTrack(subTrackIndex); AZ_Assert(subTrack, "Expected valid subtrack."); if (subTrack->GetId() >= m_nextTrackId) { m_nextTrackId = subTrack->GetId() + 1; } } } if (animNode->NeedToRender()) { AddNodeNeedToRender(animNode); } bool bNewDirectorNode = m_activeDirector == NULL && animNode->GetType() == AnimNodeType::Director; if (bNewDirectorNode) { m_activeDirector = animNode; } return true; } ////////////////////////////////////////////////////////////////////////// IAnimNode* CAnimSequence::CreateNodeInternal(AnimNodeType nodeType, uint32 nNodeId) { if (!m_pMovieSystem) { return nullptr; // should never happen, null pointer guard } CAnimNode* animNode = NULL; if (nNodeId == -1) { nNodeId = m_nextGenId; } switch (nodeType) { case AnimNodeType::AzEntity: animNode = aznew CAnimAzEntityNode(nNodeId); break; case AnimNodeType::Component: animNode = aznew CAnimComponentNode(nNodeId); break; case AnimNodeType::CVar: animNode = aznew CAnimCVarNode(nNodeId); break; case AnimNodeType::ScriptVar: animNode = aznew CAnimScriptVarNode(nNodeId); break; case AnimNodeType::Director: animNode = aznew CAnimSceneNode(nNodeId); break; case AnimNodeType::Material: animNode = aznew CAnimMaterialNode(nNodeId); break; case AnimNodeType::Event: animNode = aznew CAnimEventNode(nNodeId); break; case AnimNodeType::Group: animNode = aznew CAnimNodeGroup(nNodeId); break; case AnimNodeType::Layer: animNode = aznew CLayerNode(nNodeId); break; case AnimNodeType::Comment: animNode = aznew CCommentNode(nNodeId); break; case AnimNodeType::RadialBlur: case AnimNodeType::ColorCorrection: case AnimNodeType::DepthOfField: animNode = CAnimPostFXNode::CreateNode(nNodeId, nodeType); break; case AnimNodeType::ShadowSetup: animNode = aznew CShadowsSetupNode(nNodeId); break; case AnimNodeType::ScreenFader: animNode = aznew CAnimScreenFaderNode(nNodeId); break; default: m_pMovieSystem->LogUserNotificationMsg("AnimNode cannot be added because it is an unsupported object type."); break; } if (animNode) { if (AddNode(animNode)) { // If there isn't an active director, set it now. if (m_activeDirector == NULL && animNode->GetType() == AnimNodeType::Director) { SetActiveDirector(animNode); } } } return animNode; } ////////////////////////////////////////////////////////////////////////// IAnimNode* CAnimSequence::CreateNode(AnimNodeType nodeType) { return CreateNodeInternal(nodeType); } ////////////////////////////////////////////////////////////////////////// IAnimNode* CAnimSequence::CreateNode(XmlNodeRef node) { if (!GetMovieSystem()) { return 0; // should never happen, null pointer guard } AnimNodeType type; GetMovieSystem()->SerializeNodeType(type, node, true, IAnimSequence::kSequenceVersion, 0); XmlString name; if (!node->getAttr("Name", name)) { return 0; } IAnimNode* pNewNode = CreateNode(type); if (!pNewNode) { return 0; } pNewNode->SetName(name); pNewNode->Serialize(node, true, true); CAnimNode* newAnimNode = static_cast<CAnimNode*>(pNewNode); // Make sure de-serializing this node didn't just create an id conflict. This can happen sometimes // when copy/pasting nodes from a different sequence to this one. for (auto curNode : m_nodes) { CAnimNode* animNode = static_cast<CAnimNode*>(curNode.get()); if (animNode->GetId() == newAnimNode->GetId() && animNode != newAnimNode) { // Conflict detected, resolve it by assigning a new id to the new node. newAnimNode->SetId(m_nextGenId++); } } return pNewNode; } ////////////////////////////////////////////////////////////////////////// void CAnimSequence::RemoveNode(IAnimNode* node, bool removeChildRelationships) { assert(node != 0); static_cast<CAnimNode*>(node)->Activate(false); static_cast<CAnimNode*>(node)->OnReset(); for (int i = 0; i < (int)m_nodes.size(); ) { if (node == m_nodes[i].get()) { m_nodes.erase(m_nodes.begin() + i); if (node->NeedToRender()) { RemoveNodeNeedToRender(node); } continue; } if (removeChildRelationships && m_nodes[i]->GetParent() == node) { m_nodes[i]->SetParent(0); } i++; } // The removed one was the active director node. if (m_activeDirector == node) { // Clear the active one. m_activeDirector = NULL; m_activeDirectorNodeId = -1; // If there is another director node, set it as active. for (AnimNodes::const_iterator it = m_nodes.begin(); it != m_nodes.end(); ++it) { IAnimNode* pNode = it->get(); if (pNode->GetType() == AnimNodeType::Director) { SetActiveDirector(pNode); break; } } } } ////////////////////////////////////////////////////////////////////////// void CAnimSequence::RemoveAll() { stl::free_container(m_nodes); stl::free_container(m_events); stl::free_container(m_nodesNeedToRender); m_activeDirector = NULL; m_activeDirectorNodeId = -1; } ////////////////////////////////////////////////////////////////////////// void CAnimSequence::Reset(bool bSeekToStart) { if (GetFlags() & eSeqFlags_LightAnimationSet) { return; } m_precached = false; m_bResetting = true; if (!bSeekToStart) { for (AnimNodes::iterator it = m_nodes.begin(); it != m_nodes.end(); ++it) { IAnimNode* animNode = it->get(); static_cast<CAnimNode*>(animNode)->OnReset(); } m_bResetting = false; return; } bool bWasActive = m_bActive; if (!bWasActive) { Activate(); } SAnimContext ec; ec.singleFrame = true; ec.resetting = true; ec.sequence = this; ec.time = m_timeRange.start; Animate(ec); if (!bWasActive) { Deactivate(); } else { for (AnimNodes::iterator it = m_nodes.begin(); it != m_nodes.end(); ++it) { IAnimNode* animNode = it->get(); static_cast<CAnimNode*>(animNode)->OnReset(); } } m_bResetting = false; } ////////////////////////////////////////////////////////////////////////// void CAnimSequence::ResetHard() { if (GetFlags() & eSeqFlags_LightAnimationSet) { return; } m_bResetting = true; bool bWasActive = m_bActive; if (!bWasActive) { Activate(); } SAnimContext ec; ec.singleFrame = true; ec.resetting = true; ec.sequence = this; ec.time = m_timeRange.start; Animate(ec); if (!bWasActive) { Deactivate(); } else { for (AnimNodes::iterator it = m_nodes.begin(); it != m_nodes.end(); ++it) { IAnimNode* animNode = it->get(); static_cast<CAnimNode*>(animNode)->OnResetHard(); } } m_bResetting = false; } ////////////////////////////////////////////////////////////////////////// void CAnimSequence::Pause() { if (GetFlags() & eSeqFlags_LightAnimationSet || m_bPaused) { return; } m_bPaused = true; // Detach animation block from all nodes in this sequence. for (AnimNodes::iterator it = m_nodes.begin(); it != m_nodes.end(); ++it) { IAnimNode* animNode = it->get(); static_cast<CAnimNode*>(animNode)->OnPause(); } // Notify EBus listeners Maestro::SequenceComponentNotificationBus::Event(GetSequenceEntityId(), &Maestro::SequenceComponentNotificationBus::Events::OnPause); } ////////////////////////////////////////////////////////////////////////// void CAnimSequence::Resume() { if (GetFlags() & eSeqFlags_LightAnimationSet) { return; } if (m_bPaused) { m_bPaused = false; for (AnimNodes::iterator it = m_nodes.begin(); it != m_nodes.end(); ++it) { IAnimNode* animNode = it->get(); static_cast<CAnimNode*>(animNode)->OnResume(); } // Notify EBus listeners Maestro::SequenceComponentNotificationBus::Event(GetSequenceEntityId(), &Maestro::SequenceComponentNotificationBus::Events::OnResume); } } ////////////////////////////////////////////////////////////////////////// void CAnimSequence::OnLoop() { for (AnimNodes::iterator it = m_nodes.begin(); it != m_nodes.end(); ++it) { IAnimNode* animNode = it->get(); static_cast<CAnimNode*>(animNode)->OnLoop(); } } ////////////////////////////////////////////////////////////////////////// bool CAnimSequence::IsPaused() const { return m_bPaused; } ////////////////////////////////////////////////////////////////////////// void CAnimSequence::OnStart() { for (AnimNodes::iterator it = m_nodes.begin(); it != m_nodes.end(); ++it) { IAnimNode* animNode = it->get(); static_cast<CAnimNode*>(animNode)->OnStart(); } // notify listeners Maestro::SequenceComponentNotificationBus::Event(GetSequenceEntityId(), &Maestro::SequenceComponentNotificationBus::Events::OnStart, m_time); } ////////////////////////////////////////////////////////////////////////// void CAnimSequence::OnStop() { for (AnimNodes::iterator it = m_nodes.begin(); it != m_nodes.end(); ++it) { IAnimNode* animNode = it->get(); static_cast<CAnimNode*>(animNode)->OnStop(); } // notify listeners Maestro::SequenceComponentNotificationBus::Event(GetSequenceEntityId(), &Maestro::SequenceComponentNotificationBus::Events::OnStop, m_time); } void CAnimSequence::TimeChanged(float newTime) { for (AnimNodes::iterator it = m_nodes.begin(); it != m_nodes.end(); ++it) { IAnimNode* animNode = it->get(); animNode->TimeChanged(newTime); } } ////////////////////////////////////////////////////////////////////////// void CAnimSequence::StillUpdate() { if (GetFlags() & eSeqFlags_LightAnimationSet) { return; } for (AnimNodes::iterator it = m_nodes.begin(); it != m_nodes.end(); ++it) { IAnimNode* animNode = it->get(); animNode->StillUpdate(); } } ////////////////////////////////////////////////////////////////////////// void CAnimSequence::Animate(const SAnimContext& ec) { assert(m_bActive); if (GetFlags() & eSeqFlags_LightAnimationSet) { return; } SAnimContext animContext = ec; animContext.sequence = this; m_time = animContext.time; // Evaluate all animation nodes in sequence. // The director first. if (m_activeDirector) { m_activeDirector->Animate(animContext); } for (AnimNodes::iterator it = m_nodes.begin(); it != m_nodes.end(); ++it) { // Make sure correct animation block is binded to node. IAnimNode* animNode = it->get(); // All other (inactive) director nodes are skipped. if (animNode->GetType() == AnimNodeType::Director) { continue; } // If this is a descendant of a director node and that director is currently not active, skip this one. IAnimNode* parentDirector = animNode->HasDirectorAsParent(); if (parentDirector && parentDirector != m_activeDirector) { continue; } if (animNode->AreFlagsSetOnNodeOrAnyParent(eAnimNodeFlags_Disabled)) { continue; } // Animate node. animNode->Animate(animContext); } } ////////////////////////////////////////////////////////////////////////// void CAnimSequence::Render() { for (AnimNodes::iterator it = m_nodesNeedToRender.begin(); it != m_nodesNeedToRender.end(); ++it) { IAnimNode* animNode = it->get(); animNode->Render(); } } ////////////////////////////////////////////////////////////////////////// void CAnimSequence::Activate() { if (m_bActive) { return; } m_bActive = true; // Assign animation block to all nodes in this sequence. for (AnimNodes::iterator it = m_nodes.begin(); it != m_nodes.end(); ++it) { IAnimNode* animNode = it->get(); static_cast<CAnimNode*>(animNode)->OnReset(); static_cast<CAnimNode*>(animNode)->Activate(true); } } ////////////////////////////////////////////////////////////////////////// void CAnimSequence::Deactivate() { if (!m_bActive) { return; } // Detach animation block from all nodes in this sequence. for (AnimNodes::iterator it = m_nodes.begin(); it != m_nodes.end(); ++it) { IAnimNode* animNode = it->get(); static_cast<CAnimNode*>(animNode)->Activate(false); static_cast<CAnimNode*>(animNode)->OnReset(); } // Remove a possibly cached game hint associated with this anim sequence. stack_string sTemp("anim_sequence_"); sTemp += m_name.c_str(); // Audio: Release precached sound m_bActive = false; m_precached = false; } ////////////////////////////////////////////////////////////////////////// void CAnimSequence::PrecacheData(float startTime) { PrecacheStatic(startTime); } ////////////////////////////////////////////////////////////////////////// void CAnimSequence::PrecacheStatic(const float startTime) { // pre-cache animation keys for (AnimNodes::const_iterator it = m_nodes.begin(); it != m_nodes.end(); ++it) { IAnimNode* animNode = it->get(); static_cast<CAnimNode*>(animNode)->PrecacheStatic(startTime); } PrecacheDynamic(startTime); if (m_precached) { return; } // Try to cache this sequence's game hint if one exists. stack_string sTemp("anim_sequence_"); sTemp += m_name.c_str(); //if (gEnv->pAudioSystem) { // Make sure to use the non-serializable game hint type as trackview sequences get properly reactivated after load // Audio: Precache sound } gEnv->pLog->Log("=== Precaching render data for cutscene: %s ===", GetName()); m_precached = true; } ////////////////////////////////////////////////////////////////////////// void CAnimSequence::PrecacheDynamic(float time) { // pre-cache animation keys for (AnimNodes::const_iterator it = m_nodes.begin(); it != m_nodes.end(); ++it) { IAnimNode* animNode = it->get(); static_cast<CAnimNode*>(animNode)->PrecacheDynamic(time); } } void CAnimSequence::SetId(uint32 newId) { // Notify movie system of new Id if (GetMovieSystem()) { GetMovieSystem()->OnSetSequenceId(newId); } m_id = newId; } ////////////////////////////////////////////////////////////////////////// static bool AnimSequenceVersionConverter( AZ::SerializeContext& serializeContext, AZ::SerializeContext::DataElementNode& rootElement) { if (rootElement.GetVersion() < 5) { rootElement.AddElement(serializeContext, "BaseClass1", azrtti_typeid<IAnimSequence>()); } return true; } void CAnimSequence::Reflect(AZ::ReflectContext* context) { if (auto serializeContext = azrtti_cast<AZ::SerializeContext*>(context)) { serializeContext->Class<CAnimSequence, IAnimSequence>() ->Version(IAnimSequence::kSequenceVersion, &AnimSequenceVersionConverter) ->Field("Name", &CAnimSequence::m_name) ->Field("SequenceEntityId", &CAnimSequence::m_sequenceEntityId) ->Field("Flags", &CAnimSequence::m_flags) ->Field("TimeRange", &CAnimSequence::m_timeRange) ->Field("ID", &CAnimSequence::m_id) ->Field("Nodes", &CAnimSequence::m_nodes) ->Field("SequenceType", &CAnimSequence::m_sequenceType) ->Field("Events", &CAnimSequence::m_events) ->Field("Expanded", &CAnimSequence::m_expanded) ->Field("ActiveDirectorNodeId", &CAnimSequence::m_activeDirectorNodeId); } } ////////////////////////////////////////////////////////////////////////// void CAnimSequence::InitPostLoad() { if (m_pMovieSystem) { // Notify the MovieSystem of the new sequence Id (updates the next available Id if needed) m_pMovieSystem->OnSetSequenceId(GetId()); // check of sequence ID collision and resolve if needed if (m_pMovieSystem->FindSequenceById(GetId())) { // A collision found - resolve by resetting Id. TODO: resolve all references to previous Id ResetId(); } } IAnimNode* firstDirectorFound = nullptr; int nodeCount = GetNodeCount(); for (int nodeIndex = 0; nodeIndex < nodeCount; nodeIndex++) { IAnimNode* animNode = GetNode(nodeIndex); if (animNode) { AddNode(animNode); animNode->InitPostLoad(this); // store the first director found if (!firstDirectorFound && animNode->GetType() == AnimNodeType::Director) { firstDirectorFound = animNode; } // m_activeDirectorNodeId is serialized in the sequences, so set // this node as the active director if id's match. if (animNode->GetId() == m_activeDirectorNodeId) { SetActiveDirector(animNode); } } } // All nodes and track have been added and m_nextTrackId is set higher than any // existing track id. Go over the Tracks and make sure all of track id's are assigned. // Track Id's are serialized and should never be zero, unless this is track data from // before Track Ids were added. for (int nodeIndex = 0; nodeIndex < nodeCount; nodeIndex++) { IAnimNode* animNode = GetNode(nodeIndex); if (animNode) { int trackCount = animNode->GetTrackCount(); for (int trackIndex = 0; trackIndex < trackCount; trackIndex++) { IAnimTrack* track = animNode->GetTrackByIndex(trackIndex); AZ_Assert(track, "Expected valid track."); if (track->GetId() == 0) { track->SetId(GetUniqueTrackIdAndGenerateNext()); } int subTrackCount = track->GetSubTrackCount(); for (int subTrackIndex = 0; subTrackIndex < subTrackCount; subTrackIndex++) { IAnimTrack* subTrack = track->GetSubTrack(subTrackIndex); AZ_Assert(subTrack, "Expected valid sub track."); if (subTrack->GetId() == 0) { subTrack->SetId(GetUniqueTrackIdAndGenerateNext()); } } } } } // If the active director was not set, but there was a director found, // set it as the active director now. This can happen if the sequence // was serialized before the ActiveDirectorNodeId was added. if (!m_activeDirector && firstDirectorFound) { SetActiveDirector(firstDirectorFound); } } ////////////////////////////////////////////////////////////////////////// void CAnimSequence::SetTimeRange(Range timeRange) { m_timeRange = timeRange; // Set this time range for every track in animation. // Set time range to be in range of largest animation track. for (AnimNodes::iterator it = m_nodes.begin(); it != m_nodes.end(); ++it) { IAnimNode* anode = it->get(); anode->SetTimeRange(timeRange); } } ////////////////////////////////////////////////////////////////////////// void CAnimSequence::AdjustKeysToTimeRange(const Range& timeRange) { float offset = timeRange.start - m_timeRange.start; // Calculate scale ratio. float scale = timeRange.Length() / m_timeRange.Length(); m_timeRange = timeRange; // Set time range to be in range of largest animation track. for (AnimNodes::iterator it = m_nodes.begin(); it != m_nodes.end(); ++it) { IAnimNode* animNode = it->get(); int trackCount = animNode->GetTrackCount(); for (int paramIndex = 0; paramIndex < trackCount; paramIndex++) { IAnimTrack* pTrack = animNode->GetTrackByIndex(paramIndex); int nkey = pTrack->GetNumKeys(); for (int k = 0; k < nkey; k++) { float keytime = pTrack->GetKeyTime(k); keytime = offset + keytime * scale; pTrack->SetKeyTime(k, keytime); } } } } ////////////////////////////////////////////////////////////////////////// void CAnimSequence::ComputeTimeRange() { Range timeRange = m_timeRange; // Set time range to be in range of largest animation track. for (AnimNodes::iterator it = m_nodes.begin(); it != m_nodes.end(); ++it) { IAnimNode* animNode = it->get(); int trackCount = animNode->GetTrackCount(); for (int paramIndex = 0; paramIndex < trackCount; paramIndex++) { IAnimTrack* pTrack = animNode->GetTrackByIndex(paramIndex); int nkey = pTrack->GetNumKeys(); if (nkey > 0) { timeRange.start = std::min(timeRange.start, pTrack->GetKeyTime(0)); timeRange.end = std::max(timeRange.end, pTrack->GetKeyTime(nkey - 1)); } } } if (timeRange.start > 0) { timeRange.start = 0; } m_timeRange = timeRange; } ////////////////////////////////////////////////////////////////////////// bool CAnimSequence::AddTrackEvent(const char* szEvent) { CRY_ASSERT(szEvent && szEvent[0]); if (stl::push_back_unique(m_events, szEvent)) { NotifyTrackEvent(ITrackEventListener::eTrackEventReason_Added, szEvent); return true; } return false; } ////////////////////////////////////////////////////////////////////////// bool CAnimSequence::RemoveTrackEvent(const char* szEvent) { CRY_ASSERT(szEvent && szEvent[0]); if (stl::find_and_erase(m_events, szEvent)) { NotifyTrackEvent(ITrackEventListener::eTrackEventReason_Removed, szEvent); return true; } return false; } ////////////////////////////////////////////////////////////////////////// bool CAnimSequence::RenameTrackEvent(const char* szEvent, const char* szNewEvent) { CRY_ASSERT(szEvent && szEvent[0]); CRY_ASSERT(szNewEvent && szNewEvent[0]); for (size_t i = 0; i < m_events.size(); ++i) { if (m_events[i] == szEvent) { m_events[i] = szNewEvent; NotifyTrackEvent(ITrackEventListener::eTrackEventReason_Renamed, szEvent, szNewEvent); return true; } } return false; } ////////////////////////////////////////////////////////////////////////// bool CAnimSequence::MoveUpTrackEvent(const char* szEvent) { CRY_ASSERT(szEvent && szEvent[0]); for (size_t i = 0; i < m_events.size(); ++i) { if (m_events[i] == szEvent) { assert(i > 0); if (i > 0) { std::swap(m_events[i - 1], m_events[i]); NotifyTrackEvent(ITrackEventListener::eTrackEventReason_MovedUp, szEvent); } return true; } } return false; } ////////////////////////////////////////////////////////////////////////// bool CAnimSequence::MoveDownTrackEvent(const char* szEvent) { CRY_ASSERT(szEvent && szEvent[0]); for (size_t i = 0; i < m_events.size(); ++i) { if (m_events[i] == szEvent) { assert(i < m_events.size() - 1); if (i < m_events.size() - 1) { std::swap(m_events[i], m_events[i + 1]); NotifyTrackEvent(ITrackEventListener::eTrackEventReason_MovedDown, szEvent); } return true; } } return false; } ////////////////////////////////////////////////////////////////////////// void CAnimSequence::ClearTrackEvents() { m_events.clear(); } ////////////////////////////////////////////////////////////////////////// int CAnimSequence::GetTrackEventsCount() const { return (int)m_events.size(); } ////////////////////////////////////////////////////////////////////////// char const* CAnimSequence::GetTrackEvent(int iIndex) const { char const* szResult = NULL; const bool bValid = (iIndex >= 0 && iIndex < GetTrackEventsCount()); CRY_ASSERT(bValid); if (bValid) { szResult = m_events[iIndex].c_str(); } return szResult; } ////////////////////////////////////////////////////////////////////////// void CAnimSequence::NotifyTrackEvent(ITrackEventListener::ETrackEventReason reason, const char* event, const char* param) { // Notify listeners for (TTrackEventListeners::iterator j = m_listeners.begin(); j != m_listeners.end(); ++j) { (*j)->OnTrackEvent(this, reason, event, (void*)param); } // Notification via Event Bus Maestro::SequenceComponentNotificationBus::Event(GetSequenceEntityId(), &Maestro::SequenceComponentNotificationBus::Events::OnTrackEventTriggered, event, param); } ////////////////////////////////////////////////////////////////////////// void CAnimSequence::TriggerTrackEvent(const char* event, const char* param) { NotifyTrackEvent(ITrackEventListener::eTrackEventReason_Triggered, event, param); } ////////////////////////////////////////////////////////////////////////// void CAnimSequence::AddTrackEventListener(ITrackEventListener* pListener) { if (std::find(m_listeners.begin(), m_listeners.end(), pListener) == m_listeners.end()) { m_listeners.push_back(pListener); } } ////////////////////////////////////////////////////////////////////////// void CAnimSequence::RemoveTrackEventListener(ITrackEventListener* pListener) { TTrackEventListeners::iterator it = std::find(m_listeners.begin(), m_listeners.end(), pListener); if (it != m_listeners.end()) { m_listeners.erase(it); } } ////////////////////////////////////////////////////////////////////////// IAnimNode* CAnimSequence::FindNodeById(int nNodeId) { for (AnimNodes::const_iterator it = m_nodes.begin(); it != m_nodes.end(); ++it) { IAnimNode* animNode = it->get(); if (static_cast<CAnimNode*>(animNode)->GetId() == nNodeId) { return animNode; } } return 0; } ////////////////////////////////////////////////////////////////////////// IAnimNode* CAnimSequence::FindNodeByName(const char* sNodeName, const IAnimNode* pParentDirector) { for (AnimNodes::const_iterator it = m_nodes.begin(); it != m_nodes.end(); ++it) { IAnimNode* animNode = it->get(); // Case insensitive name comparison. if (_stricmp(static_cast<CAnimNode*>(animNode)->GetNameFast(), sNodeName) == 0) { bool bParentDirectorCheck = animNode->HasDirectorAsParent() == pParentDirector; if (bParentDirectorCheck) { return animNode; } } } return 0; } ////////////////////////////////////////////////////////////////////////// void CAnimSequence::ReorderNode(IAnimNode* pNode, IAnimNode* pPivotNode, bool bNext) { if (pNode == pPivotNode || !pNode) { return; } AZStd::intrusive_ptr<IAnimNode> pTempHolder(pNode); // Keep reference to node so it is not deleted by erasing from list. stl::find_and_erase_if(m_nodes, [pNode](const AZStd::intrusive_ptr<IAnimNode>& sp) { return sp.get() == pNode; }); AnimNodes::iterator it; for (it = m_nodes.begin(); it != m_nodes.end(); ++it) { IAnimNode* animNode = it->get(); if (animNode == pPivotNode) { if (bNext) { m_nodes.insert(it + 1, AZStd::intrusive_ptr<IAnimNode>(pNode)); } else { m_nodes.insert(it, AZStd::intrusive_ptr<IAnimNode>(pNode)); } break; } } if (it == m_nodes.end()) { m_nodes.insert(m_nodes.begin(), AZStd::intrusive_ptr<IAnimNode>(pNode)); } } ////////////////////////////////////////////////////////////////////////// void CAnimSequence::CopyNodeChildren(XmlNodeRef& xmlNode, IAnimNode* animNode) { for (int k = 0; k < GetNodeCount(); ++k) { if (GetNode(k)->GetParent() == animNode) { XmlNodeRef childNode = xmlNode->newChild("Node"); GetNode(k)->Serialize(childNode, false, true); if (GetNode(k)->GetType() == AnimNodeType::Group || animNode->GetType() == AnimNodeType::Director) { CopyNodeChildren(xmlNode, GetNode(k)); } } } } ////////////////////////////////////////////////////////////////////////// void CAnimSequence::CopyNodes(XmlNodeRef& xmlNode, IAnimNode** pSelectedNodes, uint32 count) { for (uint32 i = 0; i < count; ++i) { IAnimNode* animNode = pSelectedNodes[i]; if (animNode) { XmlNodeRef xn = xmlNode->newChild("Node"); animNode->Serialize(xn, false, true); // If it is a group node, copy its children also. if (animNode->GetType() == AnimNodeType::Group || animNode->GetType() == AnimNodeType::Director) { CopyNodeChildren(xmlNode, animNode); } } } } ////////////////////////////////////////////////////////////////////////// void CAnimSequence::PasteNodes(const XmlNodeRef& xmlNode, IAnimNode* pParent) { int type, id; std::map<int, IAnimNode*> idToNode; for (int i = 0; i < xmlNode->getChildCount(); i++) { XmlNodeRef xn = xmlNode->getChild(i); if (!xn->getAttr("Type", type)) { continue; } xn->getAttr("Id", id); IAnimNode* node = CreateNode((AnimNodeType)type); if (!node) { continue; } idToNode[id] = node; xn->setAttr("Id", static_cast<CAnimNode*>(node)->GetId()); node->Serialize(xn, true, true); int parentId = 0; if (xn->getAttr("ParentNode", parentId)) { node->SetParent(idToNode[parentId]); } else // This means a top-level node. { if (pParent) { node->SetParent(pParent); } } } } ////////////////////////////////////////////////////////////////////////// bool CAnimSequence::AddNodeNeedToRender(IAnimNode* pNode) { assert(pNode != 0); return stl::push_back_unique(m_nodesNeedToRender, AZStd::intrusive_ptr<IAnimNode>(pNode)); } ////////////////////////////////////////////////////////////////////////// void CAnimSequence::RemoveNodeNeedToRender(IAnimNode* pNode) { assert(pNode != 0); stl::find_and_erase_if(m_nodesNeedToRender, [pNode](const AZStd::intrusive_ptr<IAnimNode>& sp) { return sp.get() == pNode; }); } ////////////////////////////////////////////////////////////////////////// void CAnimSequence::SetSequenceEntityId(const AZ::EntityId& sequenceEntityId) { m_sequenceEntityId = sequenceEntityId; } ////////////////////////////////////////////////////////////////////////// void CAnimSequence::SetActiveDirector(IAnimNode* pDirectorNode) { if (!pDirectorNode) { return; } assert(pDirectorNode->GetType() == AnimNodeType::Director); if (pDirectorNode->GetType() != AnimNodeType::Director) { return; // It's not a director node. } if (pDirectorNode->GetSequence() != this) { return; // It's not a node belong to this sequence. } m_activeDirector = pDirectorNode; m_activeDirectorNodeId = pDirectorNode->GetId(); } ////////////////////////////////////////////////////////////////////////// IAnimNode* CAnimSequence::GetActiveDirector() const { return m_activeDirector; } ////////////////////////////////////////////////////////////////////////// bool CAnimSequence::IsAncestorOf(const IAnimSequence* sequence) const { assert(this != sequence); if (this == sequence) { return true; } if (!GetMovieSystem()) { return false; // should never happen, null pointer guard } for (AnimNodes::const_iterator it = m_nodes.begin(); it != m_nodes.end(); ++it) { IAnimNode* pNode = it->get(); if (pNode->GetType() == AnimNodeType::Director) { IAnimTrack* pSequenceTrack = pNode->GetTrackForParameter(AnimParamType::Sequence); if (pSequenceTrack) { PREFAST_ASSUME(sequence); for (int i = 0; i < pSequenceTrack->GetNumKeys(); ++i) { ISequenceKey key; pSequenceTrack->GetKey(i, &key); if (_stricmp(key.szSelection.c_str(), sequence->GetName()) == 0) { return true; } IAnimSequence* pChild = CAnimSceneNode::GetSequenceFromSequenceKey(key); if (pChild && pChild->IsAncestorOf(sequence)) { return true; } } } } } return false; }
#include <bits/stdc++.h> using namespace std; using pii = pair<int, int>; const int inf=1e9+3; #define all(x) (x).begin(),(x).end() #define sync() {ios_base::sync_with_stdio(0); cin.tie(0);cout.tie(0);} //do not use int n,m; int state[32003]; vector<int> ed[32003]; vector<int> ans; bool hascycle=false; void dfs(int cur){ state[cur]=1; for(int nxt : ed[cur]){ if(!state[nxt]) dfs(nxt); else if(state[nxt]==1) hascycle=true; } state[cur]=2; ans.push_back(cur); } int main() { int i,a,b; sync() cin>>n>>m; for(i=1;i<=m;i++){ cin>>a>>b; ed[a].push_back(b); } for(i=1;i<=n;i++){ if(!state[i]) dfs(i); } reverse(all(ans)); for(int num : ans) cout<<num<<' '; return 0; }
/* 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/canbus/vehicle/zhongyun/zhongyun_controller.h" #include "modules/common/proto/vehicle_signal.pb.h" #include "cyber/common/log.h" #include "cyber/time/time.h" #include "modules/canbus/vehicle/vehicle_controller.h" #include "modules/canbus/vehicle/zhongyun/zhongyun_message_manager.h" #include "modules/drivers/canbus/can_comm/can_sender.h" #include "modules/drivers/canbus/can_comm/protocol_data.h" namespace apollo { namespace canbus { namespace zhongyun { using ::apollo::common::ErrorCode; using ::apollo::control::ControlCommand; using ::apollo::drivers::canbus::ProtocolData; namespace { const int32_t kMaxFailAttempt = 10; const int32_t CHECK_RESPONSE_STEER_UNIT_FLAG = 1; const int32_t CHECK_RESPONSE_SPEED_UNIT_FLAG = 2; } // namespace ErrorCode ZhongyunController::Init( const VehicleParameter& params, CanSender<::apollo::canbus::ChassisDetail>* const can_sender, MessageManager<::apollo::canbus::ChassisDetail>* const message_manager) { if (is_initialized_) { AINFO << "ZhongyunController has already been initialized."; return ErrorCode::CANBUS_ERROR; } vehicle_params_.CopyFrom( common::VehicleConfigHelper::Instance()->GetConfig().vehicle_param()); params_.CopyFrom(params); if (!params_.has_driving_mode()) { AERROR << "Vehicle conf pb not set driving_mode."; return ErrorCode::CANBUS_ERROR; } if (can_sender == nullptr) { AERROR << "Canbus sender is null."; return ErrorCode::CANBUS_ERROR; } can_sender_ = can_sender; if (message_manager == nullptr) { AERROR << "Protocol manager is null."; return ErrorCode::CANBUS_ERROR; } message_manager_ = message_manager; // Sender part brake_control_a4_ = dynamic_cast<Brakecontrola4*>( message_manager_->GetMutableProtocolDataById(Brakecontrola4::ID)); if (brake_control_a4_ == nullptr) { AERROR << "Brakecontrola4 does not exist in the ZhongyunMessageManager!"; return ErrorCode::CANBUS_ERROR; } gear_control_a1_ = dynamic_cast<Gearcontrola1*>( message_manager_->GetMutableProtocolDataById(Gearcontrola1::ID)); if (gear_control_a1_ == nullptr) { AERROR << "Gearcontrola1 does not exist in the ZhongyunMessageManager!"; return ErrorCode::CANBUS_ERROR; } parking_control_a5_ = dynamic_cast<Parkingcontrola5*>( message_manager_->GetMutableProtocolDataById(Parkingcontrola5::ID)); if (parking_control_a5_ == nullptr) { AERROR << "Parkingcontrola5 does not exist in the ZhongyunMessageManager!"; return ErrorCode::CANBUS_ERROR; } steering_control_a2_ = dynamic_cast<Steeringcontrola2*>( message_manager_->GetMutableProtocolDataById(Steeringcontrola2::ID)); if (steering_control_a2_ == nullptr) { AERROR << "Steeringcontrola2 does not exist in the ZhongyunMessageManager!"; return ErrorCode::CANBUS_ERROR; } torque_control_a3_ = dynamic_cast<Torquecontrola3*>( message_manager_->GetMutableProtocolDataById(Torquecontrola3::ID)); if (torque_control_a3_ == nullptr) { AERROR << "Torquecontrola3 does not exist in the ZhongyunMessageManager!"; return ErrorCode::CANBUS_ERROR; } can_sender_->AddMessage(Brakecontrola4::ID, brake_control_a4_, false); can_sender_->AddMessage(Gearcontrola1::ID, gear_control_a1_, false); can_sender_->AddMessage(Parkingcontrola5::ID, parking_control_a5_, false); can_sender_->AddMessage(Steeringcontrola2::ID, steering_control_a2_, false); can_sender_->AddMessage(Torquecontrola3::ID, torque_control_a3_, false); // Need to sleep to ensure all messages received AINFO << "ZhongyunController is initialized."; is_initialized_ = true; return ErrorCode::OK; } ZhongyunController::~ZhongyunController() {} bool ZhongyunController::Start() { if (!is_initialized_) { AERROR << "ZhongyunController has not been initialized."; return false; } const auto& update_func = [this] { SecurityDogThreadFunc(); }; thread_.reset(new std::thread(update_func)); return true; } void ZhongyunController::Stop() { if (!is_initialized_) { AERROR << "ZhongyunController stops or starts improperly!"; return; } if (thread_ != nullptr && thread_->joinable()) { thread_->join(); thread_.reset(); AINFO << "ZhongyunController stopped."; } } Chassis ZhongyunController::chassis() { chassis_.Clear(); ChassisDetail chassis_detail; message_manager_->GetSensorData(&chassis_detail); // 1, 2 if (driving_mode() == Chassis::EMERGENCY_MODE) { set_chassis_error_code(Chassis::NO_ERROR); } chassis_.set_driving_mode(driving_mode()); chassis_.set_error_code(chassis_error_code()); // 3 chassis_.set_engine_started(true); // if there is not zhongyun, no chassis detail can be retrieved and return if (!chassis_detail.has_zhongyun()) { AERROR << "NO ZHONGYUN chassis information!"; return chassis_; } Zhongyun zhy = chassis_detail.zhongyun(); // 4 engine_rpm if (zhy.has_vehicle_state_feedback_2_c4() && zhy.vehicle_state_feedback_2_c4().has_motor_speed()) { chassis_.set_engine_rpm( static_cast<float>(zhy.vehicle_state_feedback_2_c4().motor_speed())); } else { chassis_.set_engine_rpm(0); } // 5 speed_mps if (zhy.has_vehicle_state_feedback_c1() && zhy.vehicle_state_feedback_c1().has_speed()) { chassis_.set_speed_mps( static_cast<float>(zhy.vehicle_state_feedback_c1().speed())); } else { chassis_.set_speed_mps(0); } // 6 chassis_.set_fuel_range_m(0); // 7 acc_pedal if (zhy.has_vehicle_state_feedback_2_c4() && zhy.vehicle_state_feedback_2_c4().has_driven_torque_feedback()) { chassis_.set_throttle_percentage(static_cast<float>( zhy.vehicle_state_feedback_2_c4().driven_torque_feedback())); } else { chassis_.set_throttle_percentage(0); } // 8 brake_pedal if (zhy.has_vehicle_state_feedback_c1() && zhy.vehicle_state_feedback_c1().has_brake_torque_feedback()) { chassis_.set_brake_percentage(static_cast<float>( zhy.vehicle_state_feedback_c1().brake_torque_feedback())); } else { chassis_.set_brake_percentage(0); } // 9 gear position if (zhy.has_vehicle_state_feedback_c1() && zhy.vehicle_state_feedback_c1().has_gear_state_actual()) { switch (zhy.vehicle_state_feedback_c1().gear_state_actual()) { case Vehicle_state_feedback_c1::GEAR_STATE_ACTUAL_D: { chassis_.set_gear_location(Chassis::GEAR_DRIVE); } break; case Vehicle_state_feedback_c1::GEAR_STATE_ACTUAL_N: { chassis_.set_gear_location(Chassis::GEAR_NEUTRAL); } break; case Vehicle_state_feedback_c1::GEAR_STATE_ACTUAL_R: { chassis_.set_gear_location(Chassis::GEAR_REVERSE); } break; case Vehicle_state_feedback_c1::GEAR_STATE_ACTUAL_P: { chassis_.set_gear_location(Chassis::GEAR_PARKING); } break; default: chassis_.set_gear_location(Chassis::GEAR_INVALID); break; } } else { chassis_.set_gear_location(Chassis::GEAR_NONE); } // 11 steering_percentage if (zhy.has_vehicle_state_feedback_c1() && zhy.vehicle_state_feedback_c1().has_steering_actual()) { chassis_.set_steering_percentage(static_cast<float>( zhy.vehicle_state_feedback_c1().steering_actual() * 100.0 / vehicle_params_.max_steer_angle() * M_PI / 180)); } else { chassis_.set_steering_percentage(0); } // 12 epb if (zhy.has_vehicle_state_feedback_c1() && zhy.vehicle_state_feedback_c1().has_parking_actual()) { chassis_.set_parking_brake( zhy.vehicle_state_feedback_c1().parking_actual() == Vehicle_state_feedback_c1::PARKING_ACTUAL_PARKING_TRIGGER); } else { chassis_.set_parking_brake(false); } // 13 error mask if (chassis_error_mask_) { chassis_.set_chassis_error_mask(chassis_error_mask_); } // Give engage_advice based on error_code and canbus feedback if (!chassis_error_mask_ && !chassis_.parking_brake()) { chassis_.mutable_engage_advice()->set_advice( apollo::common::EngageAdvice::READY_TO_ENGAGE); } else { chassis_.mutable_engage_advice()->set_advice( apollo::common::EngageAdvice::DISALLOW_ENGAGE); chassis_.mutable_engage_advice()->set_reason( "CANBUS not ready, epb is not released or firmware error!"); } return chassis_; } void ZhongyunController::Emergency() { set_driving_mode(Chassis::EMERGENCY_MODE); ResetProtocol(); } ErrorCode ZhongyunController::EnableAutoMode() { if (driving_mode() == Chassis::COMPLETE_AUTO_DRIVE) { AINFO << "Already in COMPLETE_AUTO_DRIVE mode."; return ErrorCode::OK; } steering_control_a2_->set_steering_enable_control( Steering_control_a2::STEERING_ENABLE_CONTROL_STEERING_AUTOCONTROL); gear_control_a1_->set_gear_enable_control( Gear_control_a1::GEAR_ENABLE_CONTROL_GEAR_AUTOCONTROL); torque_control_a3_->set_driven_enable_control( Torque_control_a3::DRIVEN_ENABLE_CONTROL_DRIVE_AUTO); brake_control_a4_->set_brake_enable_control( Brake_control_a4::BRAKE_ENABLE_CONTROL_BRAKE_AUTO); parking_control_a5_->set_parking_enable_control( Parking_control_a5::PARKING_ENABLE_CONTROL_PARKING_AUTOCONTROL); can_sender_->Update(); const int32_t flag = CHECK_RESPONSE_STEER_UNIT_FLAG | CHECK_RESPONSE_SPEED_UNIT_FLAG; if (!CheckResponse(flag, true)) { AERROR << "Failed to switch to COMPLETE_AUTO_DRIVE mode."; Emergency(); set_chassis_error_code(Chassis::CHASSIS_ERROR); return ErrorCode::CANBUS_ERROR; } set_driving_mode(Chassis::COMPLETE_AUTO_DRIVE); AINFO << "Switch to COMPLETE_AUTO_DRIVE mode ok."; return ErrorCode::OK; } ErrorCode ZhongyunController::DisableAutoMode() { ResetProtocol(); can_sender_->Update(); set_driving_mode(Chassis::COMPLETE_MANUAL); set_chassis_error_code(Chassis::NO_ERROR); AINFO << "Switch to COMPLETE_MANUAL mode ok."; return ErrorCode::OK; } ErrorCode ZhongyunController::EnableSteeringOnlyMode() { if (driving_mode() == Chassis::COMPLETE_AUTO_DRIVE || driving_mode() == Chassis::AUTO_STEER_ONLY) { set_driving_mode(Chassis::AUTO_STEER_ONLY); AINFO << "Already in AUTO_STEER_ONLY mode"; return ErrorCode::OK; } steering_control_a2_->set_steering_enable_control( Steering_control_a2::STEERING_ENABLE_CONTROL_STEERING_AUTOCONTROL); gear_control_a1_->set_gear_enable_control( Gear_control_a1::GEAR_ENABLE_CONTROL_GEAR_MANUALCONTROL); torque_control_a3_->set_driven_enable_control( Torque_control_a3::DRIVEN_ENABLE_CONTROL_DRIVE_MANUAL); brake_control_a4_->set_brake_enable_control( Brake_control_a4::BRAKE_ENABLE_CONTROL_BRAKE_MANUAL); parking_control_a5_->set_parking_enable_control( Parking_control_a5::PARKING_ENABLE_CONTROL_PARKING_MANUALCONTROL); can_sender_->Update(); const int32_t flag = CHECK_RESPONSE_STEER_UNIT_FLAG | CHECK_RESPONSE_SPEED_UNIT_FLAG; if (!CheckResponse(flag, true)) { AERROR << "Failed to switch to COMPLETE_AUTO_DRIVE mode."; Emergency(); set_chassis_error_code(Chassis::CHASSIS_ERROR); return ErrorCode::CANBUS_ERROR; } set_driving_mode(Chassis::AUTO_STEER_ONLY); AINFO << "Switch to COMPLETE_AUTO_DRIVE mode ok."; return ErrorCode::OK; } ErrorCode ZhongyunController::EnableSpeedOnlyMode() { if (driving_mode() == Chassis::COMPLETE_AUTO_DRIVE || driving_mode() == Chassis::AUTO_SPEED_ONLY) { set_driving_mode(Chassis::AUTO_SPEED_ONLY); AINFO << "Already in AUTO_SPEED_ONLY mode"; return ErrorCode::OK; } steering_control_a2_->set_steering_enable_control( Steering_control_a2::STEERING_ENABLE_CONTROL_STEERING_MANUALCONTROL); gear_control_a1_->set_gear_enable_control( Gear_control_a1::GEAR_ENABLE_CONTROL_GEAR_AUTOCONTROL); torque_control_a3_->set_driven_enable_control( Torque_control_a3::DRIVEN_ENABLE_CONTROL_DRIVE_AUTO); brake_control_a4_->set_brake_enable_control( Brake_control_a4::BRAKE_ENABLE_CONTROL_BRAKE_AUTO); parking_control_a5_->set_parking_enable_control( Parking_control_a5::PARKING_ENABLE_CONTROL_PARKING_AUTOCONTROL); can_sender_->Update(); if (CheckResponse(CHECK_RESPONSE_SPEED_UNIT_FLAG, true) == false) { AERROR << "Failed to switch to AUTO_STEER_ONLY mode."; Emergency(); set_chassis_error_code(Chassis::CHASSIS_ERROR); return ErrorCode::CANBUS_ERROR; } set_driving_mode(Chassis::AUTO_SPEED_ONLY); AINFO << "Switch to AUTO_SPEED_ONLY mode ok."; return ErrorCode::OK; } // NEUTRAL, REVERSE, DRIVE, PARK void ZhongyunController::Gear(Chassis::GearPosition gear_position) { if (driving_mode() != Chassis::COMPLETE_AUTO_DRIVE && driving_mode() != Chassis::AUTO_SPEED_ONLY) { AINFO << "This drive mode no need to set gear."; return; } switch (gear_position) { case Chassis::GEAR_NEUTRAL: { gear_control_a1_->set_gear_state_target( Gear_control_a1::GEAR_STATE_TARGET_N); break; } case Chassis::GEAR_REVERSE: { gear_control_a1_->set_gear_state_target( Gear_control_a1::GEAR_STATE_TARGET_R); break; } case Chassis::GEAR_DRIVE: { gear_control_a1_->set_gear_state_target( Gear_control_a1::GEAR_STATE_TARGET_D); break; } case Chassis::GEAR_PARKING: { gear_control_a1_->set_gear_state_target( Gear_control_a1::GEAR_STATE_TARGET_P); break; } case Chassis::GEAR_INVALID: { AERROR << "Gear command is invalid!"; gear_control_a1_->set_gear_state_target( Gear_control_a1::GEAR_STATE_TARGET_INVALID); break; } default: { gear_control_a1_->set_gear_state_target( Gear_control_a1::GEAR_STATE_TARGET_P); break; } } } // brake with brake pedal // pedal:0.00~99.99, unit:percentage void ZhongyunController::Brake(double pedal) { if (driving_mode() != Chassis::COMPLETE_AUTO_DRIVE && driving_mode() != Chassis::AUTO_SPEED_ONLY) { AINFO << "The current drive mode does not need to set brake pedal."; return; } brake_control_a4_->set_brake_torque(pedal); } // drive with throttle pedal // pedal:0.00~99.99 unit:percentage void ZhongyunController::Throttle(double pedal) { if (driving_mode() != Chassis::COMPLETE_AUTO_DRIVE && driving_mode() != Chassis::AUTO_SPEED_ONLY) { AINFO << "The current drive mode does not need to set throttle pedal."; return; } torque_control_a3_->set_driven_torque(pedal); } // confirm the car is driven by acceleration command or throttle/brake pedal // drive with acceleration/deceleration // acc:-7.0 ~ 5.0, unit:m/s^2 void ZhongyunController::Acceleration(double acc) { if (driving_mode() != Chassis::COMPLETE_AUTO_DRIVE && driving_mode() != Chassis::AUTO_SPEED_ONLY) { AINFO << "The current drive mode does not need to set acceleration."; return; } // None } // zhongyun default, -30% ~ 30%, left:+, right:- // need to be compatible with control module, so reverse // steering with old angle speed // angle:-99.99~0.00~99.99, unit:%, left:-, right:+ void ZhongyunController::Steer(double angle) { if (driving_mode() != Chassis::COMPLETE_AUTO_DRIVE && driving_mode() != Chassis::AUTO_STEER_ONLY) { AINFO << "The current driving mode does not need to set steer."; return; } const double real_angle = vehicle_params_.max_steer_angle() / M_PI * 180 * angle / 100.0; steering_control_a2_->set_steering_target(real_angle); } // steering with new angle speed // zhongyun has no angle_speed // angle:-30~30, unit:%, left:+, right:- void ZhongyunController::Steer(double angle, double angle_spd) { if (driving_mode() != Chassis::COMPLETE_AUTO_DRIVE && driving_mode() != Chassis::AUTO_STEER_ONLY) { AINFO << "The current driving mode does not need to set steer."; return; } const double real_angle = vehicle_params_.max_steer_angle() / M_PI * 180 * angle / 100.0; steering_control_a2_->set_steering_target(real_angle); } void ZhongyunController::SetEpbBreak(const ControlCommand& command) { if (command.parking_brake()) { parking_control_a5_->set_parking_target( Parking_control_a5::PARKING_TARGET_PARKING_TRIGGER); } else { parking_control_a5_->set_parking_target( Parking_control_a5::PARKING_TARGET_RELEASE); } } void ZhongyunController::SetBeam(const ControlCommand& command) { if (command.signal().high_beam()) { // None } else if (command.signal().low_beam()) { // None } else { // None } } void ZhongyunController::SetHorn(const ControlCommand& command) { if (command.signal().horn()) { // None } else { // None } } void ZhongyunController::SetTurningSignal(const ControlCommand& command) { // Set Turn Signal // None } void ZhongyunController::ResetProtocol() { message_manager_->ResetSendMessages(); } bool ZhongyunController::CheckChassisError() { ChassisDetail chassis_detail; message_manager_->GetSensorData(&chassis_detail); if (!chassis_detail.has_zhongyun()) { AERROR_EVERY(100) << "ChassisDetail has NO zhongyun vehicle info." << chassis_detail.DebugString(); return false; } Zhongyun zhy = chassis_detail.zhongyun(); // check steer error if (zhy.has_error_state_e1() && zhy.error_state_e1().has_steering_error_code()) { if (zhy.error_state_e1().steering_error_code() == Error_state_e1::STEERING_ERROR_CODE_ERROR) { return true; } } // check ems error if (zhy.has_error_state_e1() && zhy.error_state_e1().has_driven_error_code()) { if (zhy.error_state_e1().driven_error_code() == Error_state_e1::DRIVEN_ERROR_CODE_ERROR) { return true; } } // check eps error if (zhy.has_error_state_e1() && zhy.error_state_e1().has_brake_error_code()) { if (zhy.error_state_e1().brake_error_code() == Error_state_e1::BRAKE_ERROR_CODE_ERROR) { return true; } } // check gear error if (zhy.has_error_state_e1() && zhy.error_state_e1().has_gear_error_msg()) { if (zhy.error_state_e1().gear_error_msg() == Error_state_e1::GEAR_ERROR_MSG_ERROR) { return true; } } // check parking error if (zhy.has_error_state_e1() && zhy.error_state_e1().has_parking_error_code()) { if (zhy.error_state_e1().parking_error_code() == Error_state_e1::PARKING_ERROR_CODE_ERROR) { return true; } } return false; } void ZhongyunController::SecurityDogThreadFunc() { int32_t vertical_ctrl_fail = 0; int32_t horizontal_ctrl_fail = 0; if (can_sender_ == nullptr) { AERROR << "Failed to run SecurityDogThreadFunc() because can_sender_ is " "nullptr."; return; } while (!can_sender_->IsRunning()) { std::this_thread::yield(); } std::chrono::duration<double, std::micro> default_period{50000}; int64_t start = 0; int64_t end = 0; while (can_sender_->IsRunning()) { start = ::apollo::cyber::Time::Now().ToMicrosecond(); const Chassis::DrivingMode mode = driving_mode(); bool emergency_mode = false; // 1. horizontal control check if ((mode == Chassis::COMPLETE_AUTO_DRIVE || mode == Chassis::AUTO_STEER_ONLY) && !CheckResponse(CHECK_RESPONSE_STEER_UNIT_FLAG, false)) { ++horizontal_ctrl_fail; if (horizontal_ctrl_fail >= kMaxFailAttempt) { emergency_mode = true; set_chassis_error_code(Chassis::MANUAL_INTERVENTION); } } else { horizontal_ctrl_fail = 0; } // 2. vertical control check if ((mode == Chassis::COMPLETE_AUTO_DRIVE || mode == Chassis::AUTO_SPEED_ONLY) && !CheckResponse(CHECK_RESPONSE_SPEED_UNIT_FLAG, false)) { ++vertical_ctrl_fail; if (vertical_ctrl_fail >= kMaxFailAttempt) { emergency_mode = true; set_chassis_error_code(Chassis::MANUAL_INTERVENTION); } } else { vertical_ctrl_fail = 0; } if (CheckChassisError()) { set_chassis_error_code(Chassis::CHASSIS_ERROR); emergency_mode = true; } if (emergency_mode && mode != Chassis::EMERGENCY_MODE) { set_driving_mode(Chassis::EMERGENCY_MODE); message_manager_->ResetSendMessages(); } end = ::apollo::cyber::Time::Now().ToMicrosecond(); std::chrono::duration<double, std::micro> elapsed{end - start}; if (elapsed < default_period) { std::this_thread::sleep_for(default_period - elapsed); } else { AERROR << "Too much time consumption in ZhongyunController looping process:" << elapsed.count(); } } } bool ZhongyunController::CheckResponse(const int32_t flags, bool need_wait) { // for Zhongyun, CheckResponse commonly takes 300ms. We leave a 100ms buffer // for it. int32_t retry_num = 20; ChassisDetail chassis_detail; bool is_eps_online = false; bool is_vcu_online = false; bool is_esp_online = false; do { if (message_manager_->GetSensorData(&chassis_detail) != ErrorCode::OK) { AERROR_EVERY(100) << "get chassis detail failed."; return false; } bool check_ok = true; if (flags & CHECK_RESPONSE_STEER_UNIT_FLAG) { is_eps_online = chassis_detail.has_check_response() && chassis_detail.check_response().has_is_eps_online() && chassis_detail.check_response().is_eps_online(); check_ok = check_ok && is_eps_online; } if (flags & CHECK_RESPONSE_SPEED_UNIT_FLAG) { is_vcu_online = chassis_detail.has_check_response() && chassis_detail.check_response().has_is_vcu_online() && chassis_detail.check_response().is_vcu_online(); is_esp_online = chassis_detail.has_check_response() && chassis_detail.check_response().has_is_esp_online() && chassis_detail.check_response().is_esp_online(); check_ok = check_ok && is_vcu_online && is_esp_online; } if (need_wait) { --retry_num; std::this_thread::sleep_for( std::chrono::duration<double, std::milli>(20)); } if (check_ok) { return true; } else { AINFO << "Need to check response again."; } } while (need_wait && retry_num); AINFO << "check_response fail: is_eps_online:" << is_eps_online << ", is_vcu_online:" << is_vcu_online << ", is_esp_online:" << is_esp_online; return false; } void ZhongyunController::set_chassis_error_mask(const int32_t mask) { std::lock_guard<std::mutex> lock(chassis_mask_mutex_); chassis_error_mask_ = mask; } int32_t ZhongyunController::chassis_error_mask() { std::lock_guard<std::mutex> lock(chassis_mask_mutex_); return chassis_error_mask_; } Chassis::ErrorCode ZhongyunController::chassis_error_code() { std::lock_guard<std::mutex> lock(chassis_error_code_mutex_); return chassis_error_code_; } void ZhongyunController::set_chassis_error_code( const Chassis::ErrorCode& error_code) { std::lock_guard<std::mutex> lock(chassis_error_code_mutex_); chassis_error_code_ = error_code; } } // namespace zhongyun } // namespace canbus } // namespace apollo
#include "simulation/ElementCommon.h" static int update(UPDATE_FUNC_ARGS); static int graphics(GRAPHICS_FUNC_ARGS); void Element::Element_PUMP() { Identifier = "DEFAULT_PT_PUMP"; Name = "PUMP"; Colour = PIXPACK(0x0A0A3B); MenuVisible = 1; MenuSection = SC_POWERED; Enabled = 1; Advection = 0.0f; AirDrag = 0.00f * CFDS; AirLoss = 0.95f; Loss = 0.00f; Collision = 0.0f; Gravity = 0.0f; Diffusion = 0.00f; HotAir = 0.000f * CFDS; Falldown = 0; Flammable = 0; Explosive = 0; Meltable = 0; Hardness = 10; Weight = 100; DefaultProperties.temp = 273.15f; HeatConduct = 0; Description = "Pressure pump. Changes pressure to its temp when activated. (use HEAT/COOL)."; Properties = TYPE_SOLID; LowPressure = IPL; LowPressureTransition = NT; HighPressure = IPH; HighPressureTransition = NT; LowTemperature = ITL; LowTemperatureTransition = NT; HighTemperature = ITH; HighTemperatureTransition = NT; DefaultProperties.life = 10; Update = &update; Graphics = &graphics; } static int update(UPDATE_FUNC_ARGS) { int r, rx, ry; if (parts[i].life != 10) { if (parts[i].life>0) parts[i].life--; } else { if (parts[i].temp >= 256.0f+273.15f) parts[i].temp = 256.0f+273.15f; if (parts[i].temp <= -256.0f+273.15f) parts[i].temp = -256.0f+273.15f; for (rx = -1; rx <= 1; rx++) for (ry = -1; ry <= 1; ry++) { if (parts[i].tmp != 1) { if (!(rx && ry)) sim->pv[(y/CELL)+ry][(x/CELL)+rx] += 0.1f*((parts[i].temp-273.15)-sim->pv[(y/CELL)+ry][(x/CELL)+rx]); } else { int r = pmap[y+ry][x+rx]; if (TYP(r) == PT_FILT) { int newPressure = parts[ID(r)].ctype - 0x10000000; if (newPressure >= 0 && newPressure <= 512) { sim->pv[(y + ry) / CELL][(x + rx) / CELL] = float(newPressure - 256); } } } } for (rx = -2; rx <= 2; rx++) for (ry = -2; ry <= 2; ry++) if (BOUNDS_CHECK && (rx || ry)) { r = pmap[y+ry][x+rx]; if (!r) continue; if (TYP(r) == PT_PUMP) { if (parts[ID(r)].life < 10 && parts[ID(r)].life > 0) parts[i].life = 9; else if (parts[ID(r)].life == 0) parts[ID(r)].life = 10; } } } return 0; } static int graphics(GRAPHICS_FUNC_ARGS) { int lifemod = ((cpart->life>10?10:cpart->life)*19); *colb += lifemod; return 0; }
#include "stdafx.h" #include "sphere.h" bool sphere::hit(const ray& r, float t_min, float t_max, hit_record& rec) const { vec3 oc = r.origin() - center; float a = dot(r.direction(), r.direction()); float b = dot(oc, r.direction()); float c = dot(oc, oc) - radius * radius; float discriminant = b * b - a * c; if (discriminant > 0) { float temp = (-b - sqrt(b*b - a * c)) / a; if (temp < t_max && temp > t_min) { rec.t = temp; rec.p = r.point_at_parameter(rec.t); rec.normal = (rec.p - center) / radius; return true; } temp = (-b + sqrt(b*b - a * c)) / a; if (temp < t_max && temp > t_min) { rec.t = temp; rec.p = r.point_at_parameter(rec.t); rec.normal = (rec.p - center) / radius; return true; } } return false; }
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_DinoDropInventoryComponent_Carnivore_Huge_Leed_Alpha_structs.hpp" namespace sdk { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass DinoDropInventoryComponent_Carnivore_Huge_Leed_Alpha.DinoDropInventoryComponent_Carnivore_Huge_Leed_Alpha_C // 0x0000 (0x0590 - 0x0590) class UDinoDropInventoryComponent_Carnivore_Huge_Leed_Alpha_C : public UDinoDropInventoryComponent_Carnivore_Huge_C { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass DinoDropInventoryComponent_Carnivore_Huge_Leed_Alpha.DinoDropInventoryComponent_Carnivore_Huge_Leed_Alpha_C"); return ptr; } void ExecuteUbergraph_DinoDropInventoryComponent_Carnivore_Huge_Leed_Alpha(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
#include <iostream> //#include <core/ctti/ctti.hpp> //#include <core/rtti/type.hpp> using namespace std; //using namespace core::collections; //using namespace core::ctti; //using namespace core; namespace Game { class Entity { // DECLARE_STRUCT(Game::Entity) // DECLARE_PROPERTY(m_int, attr::Name("dupeaaaa"), attr::Name("asdasd"), attr::Name("adssssss")) // DECLARE_PROPERTY(m_float) // END_STRUCT // public: // int m_int = 0; // float m_float = 0; }; // class Entity } // namespace Game using namespace Game; void constexpr_test() { // std::cout << "Hello World!" << std::endl; // constexpr auto entity_ti = get_type_info<Entity>(); // constexpr auto entity_ti_len = entity_ti.length(); // constexpr auto entity_ti_name = entity_ti.get_name(); // constexpr auto entity_ti_sizeof = entity_ti.get_sizeof(); // constexpr auto entity_ti_is_class = entity_ti.is_struct(); // constexpr auto entity_ti_is_fundamental = entity_ti.is_fundamental(); // constexpr auto entity_ti_properties = entity_ti.get_properties(); // constexpr auto entity_ti_properties_len = entity_ti_properties.length(); // constexpr auto first_property = entity_ti_properties.at<0>(); // constexpr auto first_property_name = first_property.get_name(); // constexpr auto first_property_names_len = first_property.get_all<attr::Name>().length(); // cout << "entity_ti_len = " << entity_ti_len << endl; // cout << "entity_ti_name = " << entity_ti_name.get() << endl; // cout << "entity_ti_sizeof = " << entity_ti_sizeof << endl; // cout << "entity_ti_is_class = " << entity_ti_is_class << endl; // cout << "entity_ti_is_fundamental = " << entity_ti_is_fundamental << endl; // cout << "entity_ti_properties_len = " << entity_ti_properties_len << endl; // cout << "first_property_name = " << first_property_name.get() << endl; // cout << "first_property_names_len = " << first_property_names_len << endl; } void runtime_test() { //core::rtti::Type type = core::rtti::Type<Entity>(); //Entity entity; //auto entity_rti = get_type_info(entity); //auto } int main() { constexpr_test(); runtime_test(); }
/* * Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/cbn/model/CreateFlowlogRequest.h> using AlibabaCloud::Cbn::Model::CreateFlowlogRequest; CreateFlowlogRequest::CreateFlowlogRequest() : RpcServiceRequest("cbn", "2017-09-12", "CreateFlowlog") { setMethod(HttpRequest::Method::Post); } CreateFlowlogRequest::~CreateFlowlogRequest() {} long CreateFlowlogRequest::getResourceOwnerId()const { return resourceOwnerId_; } void CreateFlowlogRequest::setResourceOwnerId(long resourceOwnerId) { resourceOwnerId_ = resourceOwnerId; setParameter("ResourceOwnerId", std::to_string(resourceOwnerId)); } std::string CreateFlowlogRequest::getClientToken()const { return clientToken_; } void CreateFlowlogRequest::setClientToken(const std::string& clientToken) { clientToken_ = clientToken; setParameter("ClientToken", clientToken); } std::string CreateFlowlogRequest::getCenId()const { return cenId_; } void CreateFlowlogRequest::setCenId(const std::string& cenId) { cenId_ = cenId; setParameter("CenId", cenId); } std::string CreateFlowlogRequest::getDescription()const { return description_; } void CreateFlowlogRequest::setDescription(const std::string& description) { description_ = description; setParameter("Description", description); } std::string CreateFlowlogRequest::getRegionId()const { return regionId_; } void CreateFlowlogRequest::setRegionId(const std::string& regionId) { regionId_ = regionId; setParameter("RegionId", regionId); } std::string CreateFlowlogRequest::getProjectName()const { return projectName_; } void CreateFlowlogRequest::setProjectName(const std::string& projectName) { projectName_ = projectName; setParameter("ProjectName", projectName); } std::string CreateFlowlogRequest::getLogStoreName()const { return logStoreName_; } void CreateFlowlogRequest::setLogStoreName(const std::string& logStoreName) { logStoreName_ = logStoreName; setParameter("LogStoreName", logStoreName); } std::string CreateFlowlogRequest::getResourceOwnerAccount()const { return resourceOwnerAccount_; } void CreateFlowlogRequest::setResourceOwnerAccount(const std::string& resourceOwnerAccount) { resourceOwnerAccount_ = resourceOwnerAccount; setParameter("ResourceOwnerAccount", resourceOwnerAccount); } std::string CreateFlowlogRequest::getOwnerAccount()const { return ownerAccount_; } void CreateFlowlogRequest::setOwnerAccount(const std::string& ownerAccount) { ownerAccount_ = ownerAccount; setParameter("OwnerAccount", ownerAccount); } long CreateFlowlogRequest::getOwnerId()const { return ownerId_; } void CreateFlowlogRequest::setOwnerId(long ownerId) { ownerId_ = ownerId; setParameter("OwnerId", std::to_string(ownerId)); } std::string CreateFlowlogRequest::getFlowLogName()const { return flowLogName_; } void CreateFlowlogRequest::setFlowLogName(const std::string& flowLogName) { flowLogName_ = flowLogName; setParameter("FlowLogName", flowLogName); }
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "bin/dfe.h" #include <memory> #include "bin/abi_version.h" #include "bin/dartutils.h" #include "bin/directory.h" #include "bin/error_exit.h" #include "bin/exe_utils.h" #include "bin/file.h" #include "bin/main_options.h" #include "bin/platform.h" #include "bin/utils.h" #include "include/dart_tools_api.h" #include "platform/utils.h" extern "C" { #if !defined(EXCLUDE_CFE_AND_KERNEL_PLATFORM) extern const uint8_t kKernelServiceDill[]; extern intptr_t kKernelServiceDillSize; extern const uint8_t kPlatformStrongDill[]; extern intptr_t kPlatformStrongDillSize; #else const uint8_t* kKernelServiceDill = nullptr; intptr_t kKernelServiceDillSize = 0; const uint8_t* kPlatformStrongDill = nullptr; intptr_t kPlatformStrongDillSize = 0; #endif // !defined(EXCLUDE_CFE_AND_KERNEL_PLATFORM) } namespace dart { namespace bin { #if !defined(DART_PRECOMPILED_RUNTIME) DFE dfe; #endif const char kKernelServiceSnapshot[] = "kernel-service.dart.snapshot"; const char kSnapshotsDirectory[] = "snapshots"; DFE::DFE() : use_dfe_(false), use_incremental_compiler_(false), frontend_filename_(nullptr), application_kernel_buffer_(nullptr), application_kernel_buffer_size_(0) { // The run_vm_tests binary has the DART_PRECOMPILER set in order to allow unit // tests to exercise JIT and AOT pipeline. // // Only on X64 do we have kernel-service.dart.snapshot available otherwise we // need to fall back to the built-in one (if we have it). #if defined(EXCLUDE_CFE_AND_KERNEL_PLATFORM) || \ (defined(DART_PRECOMPILER) && defined(TARGET_ARCH_X64)) kernel_service_dill_ = nullptr; kernel_service_dill_size_ = 0; #else kernel_service_dill_ = kKernelServiceDill; kernel_service_dill_size_ = kKernelServiceDillSize; #endif #if defined(EXCLUDE_CFE_AND_KERNEL_PLATFORM) platform_strong_dill_for_compilation_ = nullptr; platform_strong_dill_for_compilation_size_ = 0; platform_strong_dill_for_execution_ = nullptr; platform_strong_dill_for_execution_size_ = 0; #else platform_strong_dill_for_compilation_ = kPlatformStrongDill; platform_strong_dill_for_compilation_size_ = kPlatformStrongDillSize; platform_strong_dill_for_execution_ = kPlatformStrongDill; platform_strong_dill_for_execution_size_ = kPlatformStrongDillSize; #endif } DFE::~DFE() { if (frontend_filename_ != nullptr) { free(frontend_filename_); } frontend_filename_ = nullptr; free(application_kernel_buffer_); application_kernel_buffer_ = nullptr; application_kernel_buffer_size_ = 0; } void DFE::Init() { Init(Options::kAbiVersionUnset); } void DFE::Init(int target_abi_version) { if (platform_strong_dill_for_compilation_ == nullptr) { return; } if (!InitKernelServiceAndPlatformDills(target_abi_version)) { return; } Dart_SetDartLibrarySourcesKernel(platform_strong_dill_for_compilation_, platform_strong_dill_for_compilation_size_); } bool DFE::InitKernelServiceAndPlatformDills(int target_abi_version) { const char kAbiVersionsDir[] = "dart-sdk/lib/_internal/abiversions"; const char kKernelServiceDillFile[] = "kernel_service.dill"; const char kPlatformStrongDillFile[] = "vm_platform_strong.dill"; if (frontend_filename_ != nullptr) { return true; } // |dir_prefix| includes the last path seperator. auto dir_prefix = std::unique_ptr<char, void (*)(void*)>( EXEUtils::GetDirectoryPrefixFromExeName(), free); if (target_abi_version != Options::kAbiVersionUnset) { kernel_service_dill_ = nullptr; kernel_service_dill_size_ = 0; platform_strong_dill_for_compilation_ = nullptr; platform_strong_dill_for_compilation_size_ = 0; // Look in the old abi version directory. char* script_uri = Utils::SCreate("%s%s/%d/%s", dir_prefix.get(), kAbiVersionsDir, target_abi_version, kPlatformStrongDillFile); if (!TryReadKernelFile( script_uri, const_cast<uint8_t**>(&platform_strong_dill_for_compilation_), &platform_strong_dill_for_compilation_size_)) { Syslog::PrintErr("Can't find old ABI dill file: %s\n", script_uri); free(script_uri); return false; } free(script_uri); script_uri = Utils::SCreate("%s%s/%d/%s", dir_prefix.get(), kAbiVersionsDir, target_abi_version, kKernelServiceDillFile); if (!TryReadKernelFile(script_uri, const_cast<uint8_t**>(&kernel_service_dill_), &kernel_service_dill_size_)) { Syslog::PrintErr("Can't find old ABI dill file: %s\n", script_uri); free(script_uri); return false; } else { frontend_filename_ = script_uri; return true; } } // Look for the frontend snapshot next to the executable. frontend_filename_ = Utils::SCreate("%s%s", dir_prefix.get(), kKernelServiceSnapshot); if (File::Exists(nullptr, frontend_filename_)) { return true; } free(frontend_filename_); frontend_filename_ = nullptr; // If the frontend snapshot is not found next to the executable, then look for // it in the "snapshots" directory. frontend_filename_ = Utils::SCreate("%s%s%s%s", dir_prefix.get(), kSnapshotsDirectory, File::PathSeparator(), kKernelServiceSnapshot); if (File::Exists(nullptr, frontend_filename_)) { return true; } free(frontend_filename_); frontend_filename_ = nullptr; return true; } bool DFE::KernelServiceDillAvailable() const { return kernel_service_dill_ != nullptr; } void DFE::LoadKernelService(const uint8_t** kernel_service_buffer, intptr_t* kernel_service_buffer_size) { *kernel_service_buffer = kernel_service_dill_; *kernel_service_buffer_size = kernel_service_dill_size_; } void DFE::LoadPlatform(const uint8_t** kernel_buffer, intptr_t* kernel_buffer_size) { *kernel_buffer = platform_strong_dill_for_execution_; *kernel_buffer_size = platform_strong_dill_for_execution_size_; } bool DFE::CanUseDartFrontend() const { return (platform_strong_dill_for_compilation_ != nullptr) && (KernelServiceDillAvailable() || (frontend_filename() != nullptr)); } class WindowsPathSanitizer { public: explicit WindowsPathSanitizer(const char* path) { // For Windows we need to massage the paths a bit according to // http://blogs.msdn.com/b/ie/archive/2006/12/06/file-uris-in-windows.aspx // // Convert // C:\one\two\three // to // /C:/one/two/three // // (see builtin.dart#_sanitizeWindowsPath) intptr_t len = strlen(path); sanitized_uri_ = reinterpret_cast<char*>(malloc(len + 1 + 1)); if (sanitized_uri_ == nullptr) { OUT_OF_MEMORY(); } char* s = sanitized_uri_; if (len > 2 && path[1] == ':') { *s++ = '/'; } for (const char* p = path; *p != '\0'; ++p, ++s) { *s = *p == '\\' ? '/' : *p; } *s = '\0'; } ~WindowsPathSanitizer() { free(sanitized_uri_); } const char* sanitized_uri() { return sanitized_uri_; } private: char* sanitized_uri_; DISALLOW_COPY_AND_ASSIGN(WindowsPathSanitizer); }; Dart_KernelCompilationResult DFE::CompileScript(const char* script_uri, bool incremental, const char* package_config) { // TODO(aam): When Frontend is ready, VM should be passing vm_outline.dill // instead of vm_platform.dill to Frontend for compilation. #if defined(HOST_OS_WINDOWS) WindowsPathSanitizer path_sanitizer(script_uri); const char* sanitized_uri = path_sanitizer.sanitized_uri(); #else const char* sanitized_uri = script_uri; #endif return Dart_CompileToKernel( sanitized_uri, platform_strong_dill_for_compilation_, platform_strong_dill_for_compilation_size_, incremental, package_config); } void DFE::CompileAndReadScript(const char* script_uri, uint8_t** kernel_buffer, intptr_t* kernel_buffer_size, char** error, int* exit_code, const char* package_config) { Dart_KernelCompilationResult result = CompileScript(script_uri, use_incremental_compiler(), package_config); switch (result.status) { case Dart_KernelCompilationStatus_Ok: *kernel_buffer = result.kernel; *kernel_buffer_size = result.kernel_size; *error = nullptr; *exit_code = 0; break; case Dart_KernelCompilationStatus_Error: free(result.kernel); *error = result.error; // Copy error message. *exit_code = kCompilationErrorExitCode; break; case Dart_KernelCompilationStatus_Crash: free(result.kernel); *error = result.error; // Copy error message. *exit_code = kDartFrontendErrorExitCode; break; case Dart_KernelCompilationStatus_Unknown: free(result.kernel); *error = result.error; // Copy error message. *exit_code = kErrorExitCode; break; } } void DFE::ReadScript(const char* script_uri, uint8_t** kernel_buffer, intptr_t* kernel_buffer_size) const { int64_t start = Dart_TimelineGetMicros(); if (!TryReadKernelFile(script_uri, kernel_buffer, kernel_buffer_size)) { return; } if (!Dart_IsKernel(*kernel_buffer, *kernel_buffer_size)) { free(*kernel_buffer); *kernel_buffer = nullptr; *kernel_buffer_size = -1; } int64_t end = Dart_TimelineGetMicros(); Dart_TimelineEvent("DFE::ReadScript", start, end, Dart_Timeline_Event_Duration, 0, nullptr, nullptr); } // Attempts to treat [buffer] as a in-memory kernel byte representation. // If successful, returns [true] and places [buffer] into [kernel_ir], byte size // into [kernel_ir_size]. // If unsuccessful, returns [false], puts [nullptr] into [kernel_ir], -1 into // [kernel_ir_size]. static bool TryReadSimpleKernelBuffer(uint8_t* buffer, uint8_t** p_kernel_ir, intptr_t* p_kernel_ir_size) { DartUtils::MagicNumber magic_number = DartUtils::SniffForMagicNumber(buffer, *p_kernel_ir_size); if (magic_number == DartUtils::kKernelMagicNumber) { // Do not free buffer if this is a kernel file - kernel_file will be // backed by the same memory as the buffer and caller will own it. // Caller is responsible for freeing the buffer when this function // returns true. *p_kernel_ir = buffer; return true; } free(buffer); *p_kernel_ir = nullptr; *p_kernel_ir_size = -1; return false; } /// Reads [script_uri] file, returns [true] if successful, [false] otherwise. /// /// If successful, newly allocated buffer with file contents is returned in /// [buffer], file contents byte count - in [size]. static bool TryReadFile(const char* script_uri, uint8_t** buffer, intptr_t* size) { void* script_file = DartUtils::OpenFileUri(script_uri, false); if (script_file == nullptr) { return false; } DartUtils::ReadFile(buffer, size, script_file); DartUtils::CloseFile(script_file); if (buffer == nullptr) { return false; } return true; } class KernelIRNode { public: KernelIRNode(uint8_t* kernel_ir, intptr_t kernel_size) : kernel_ir_(kernel_ir), kernel_size_(kernel_size) {} ~KernelIRNode() { free(kernel_ir_); } static void Add(KernelIRNode** p_head, KernelIRNode** p_tail, KernelIRNode* node) { if (*p_head == nullptr) { *p_head = node; } else { (*p_tail)->next_ = node; } *p_tail = node; } static void Merge(KernelIRNode* head, uint8_t** p_bytes, intptr_t* p_size) { intptr_t size = 0; for (KernelIRNode* node = head; node != nullptr; node = node->next_) { size = size + node->kernel_size_; } *p_bytes = reinterpret_cast<uint8_t*>(malloc(size)); if (*p_bytes == nullptr) { OUT_OF_MEMORY(); } uint8_t* p = *p_bytes; KernelIRNode* node = head; while (node != nullptr) { memmove(p, node->kernel_ir_, node->kernel_size_); p += node->kernel_size_; KernelIRNode* next = node->next_; node = next; } *p_size = size; } static void Delete(KernelIRNode* head) { KernelIRNode* node = head; while (node != nullptr) { KernelIRNode* next = node->next_; delete (node); node = next; } } private: uint8_t* kernel_ir_; intptr_t kernel_size_; KernelIRNode* next_ = nullptr; DISALLOW_COPY_AND_ASSIGN(KernelIRNode); }; class StringPointer { public: explicit StringPointer(char* c_str) : c_str_(c_str) {} ~StringPointer() { free(c_str_); } const char* c_str() { return c_str_; } private: char* c_str_; DISALLOW_COPY_AND_ASSIGN(StringPointer); }; // Supports "kernel list" files as input. // Those are text files that start with '#@dill' on new line, followed // by absolute paths to kernel files or relative paths, that are relative // to [script_uri] "kernel list" file. // Below is an example of valid kernel list file: // ``` // #@dill // /projects/mytest/build/bin/main.vm.dill // /projects/mytest/build/packages/mytest/lib.vm.dill // ``` static bool TryReadKernelListBuffer(const char* script_uri, uint8_t* buffer, intptr_t buffer_size, uint8_t** kernel_ir, intptr_t* kernel_ir_size) { const char* kernel_list_dirname = DartUtils::DirName(script_uri); if (strcmp(kernel_list_dirname, script_uri) == 0) { kernel_list_dirname = ""; } KernelIRNode* kernel_ir_head = nullptr; KernelIRNode* kernel_ir_tail = nullptr; // Add all kernels to the linked list char* filename = reinterpret_cast<char*>(buffer + kernel_list_magic_number.length); intptr_t filename_size = buffer_size - kernel_list_magic_number.length; char* tail = reinterpret_cast<char*>(memchr(filename, '\n', filename_size)); while (tail != nullptr) { *tail = '\0'; intptr_t this_kernel_size; uint8_t* this_buffer; StringPointer resolved_filename( File::IsAbsolutePath(filename) ? strdup(filename) : Utils::SCreate("%s%s", kernel_list_dirname, filename)); if (!TryReadFile(resolved_filename.c_str(), &this_buffer, &this_kernel_size)) { return false; } uint8_t* this_kernel_ir; if (!TryReadSimpleKernelBuffer(this_buffer, &this_kernel_ir, &this_kernel_size)) { // Abandon read if any of the files in the list are invalid. KernelIRNode::Delete(kernel_ir_head); *kernel_ir = nullptr; *kernel_ir_size = -1; return false; } KernelIRNode::Add(&kernel_ir_head, &kernel_ir_tail, new KernelIRNode(this_kernel_ir, this_kernel_size)); filename_size -= tail + 1 - filename; filename = tail + 1; tail = reinterpret_cast<char*>(memchr(filename, '\n', filename_size)); } free(buffer); KernelIRNode::Merge(kernel_ir_head, kernel_ir, kernel_ir_size); KernelIRNode::Delete(kernel_ir_head); return true; } bool DFE::TryReadKernelFile(const char* script_uri, uint8_t** kernel_ir, intptr_t* kernel_ir_size) { *kernel_ir = nullptr; *kernel_ir_size = -1; uint8_t* buffer; if (!TryReadFile(script_uri, &buffer, kernel_ir_size)) { return false; } DartUtils::MagicNumber magic_number = DartUtils::SniffForMagicNumber(buffer, *kernel_ir_size); if (magic_number == DartUtils::kKernelListMagicNumber) { return TryReadKernelListBuffer(script_uri, buffer, *kernel_ir_size, kernel_ir, kernel_ir_size); } return TryReadSimpleKernelBuffer(buffer, kernel_ir, kernel_ir_size); } } // namespace bin } // namespace dart
// Copyright (c) 2013-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // Unit tests for alert system #include "alert.h" #include "chain.h" #include "chainparams.h" #include "clientversion.h" #include "data/alertTests.raw.h" #include "serialize.h" #include "streams.h" #include "util.h" #include "utilstrencodings.h" #include "test/test_stelo.h" #include <fstream> #include <boost/filesystem/operations.hpp> #include <boost/foreach.hpp> #include <boost/test/unit_test.hpp> // // Sign a CAlert and serialize it // bool SignAndSave(CAlert &alert) { // Sign if(!alert.Sign()) { printf("SignAndSave() : could not sign alert:\n%s", alert.ToString().c_str()); return false; } std::string strFilePath = "src/test/data/alertTests.raw"; // open output file and associate it with CAutoFile FILE *file = fopen(strFilePath.c_str(), "ab+"); CAutoFile fileout(file, SER_DISK, CLIENT_VERSION); if (fileout.IsNull()) return error("%s: Failed to open file %s", __func__, strFilePath); try { fileout << alert; } catch (std::exception &e) { return error("%s: Serialize or I/O error - %s", __func__, e.what()); } fileout.fclose(); return true; } // // alertTests contains 8 alerts, generated with this code // void GenerateAlertTests() { CAlert alert; alert.nRelayUntil = 60; alert.nExpiration = 24 * 60 * 60; alert.nID = 1; alert.nCancel = 0; // cancels previous messages up to this ID number alert.nMinVer = 0; // These versions are protocol versions alert.nMaxVer = 999001; alert.nPriority = 1; alert.strComment = "Alert comment"; alert.strStatusBar = "Alert 1"; SignAndSave(alert); alert.setSubVer.insert(std::string("/Satoshi:0.1.0/")); alert.strStatusBar = "Alert 1 for Satoshi 0.1.0"; SignAndSave(alert); alert.setSubVer.insert(std::string("/Satoshi:0.2.0/")); alert.strStatusBar = "Alert 1 for Satoshi 0.1.0, 0.2.0"; SignAndSave(alert); alert.setSubVer.clear(); ++alert.nID; alert.nCancel = 1; alert.nPriority = 100; alert.strStatusBar = "Alert 2, cancels 1"; SignAndSave(alert); alert.nExpiration += 60; ++alert.nID; SignAndSave(alert); ++alert.nID; alert.nMinVer = 11; alert.nMaxVer = 22; SignAndSave(alert); ++alert.nID; alert.strStatusBar = "Alert 2 for Satoshi 0.1.0"; alert.setSubVer.insert(std::string("/Satoshi:0.1.0/")); SignAndSave(alert); ++alert.nID; alert.nMinVer = 0; alert.nMaxVer = 999999; alert.strStatusBar = "Evil Alert'; /bin/ls; echo '"; alert.setSubVer.clear(); SignAndSave(alert); } struct ReadAlerts : public TestingSetup { ReadAlerts() { std::vector<unsigned char> vch(alert_tests::alertTests, alert_tests::alertTests + sizeof(alert_tests::alertTests)); CDataStream stream(vch, SER_DISK, CLIENT_VERSION); try { while (!stream.eof()) { CAlert alert; stream >> alert; alerts.push_back(alert); } } catch (const std::exception&) { } } ~ReadAlerts() { } static std::vector<std::string> read_lines(boost::filesystem::path filepath) { std::vector<std::string> result; std::ifstream f(filepath.string().c_str()); std::string line; while (std::getline(f,line)) result.push_back(line); return result; } std::vector<CAlert> alerts; }; BOOST_FIXTURE_TEST_SUITE(Alert_tests, ReadAlerts) // Steps to generate alert tests: // - update alerts in GenerateAlertTests() (optional) // - enable code below (#if 1) // - replace "fffffffffffffffffffffffffffffffffffffffffffffffffff" with the actual MAINNET privkey // - recompile and run "/path/to/test_stelo -t Alert_test" // // NOTE: make sure to disable code and remove alert privkey when you're done! // #if 0 BOOST_AUTO_TEST_CASE(GenerateAlerts) { SoftSetArg("-alertkey", "fffffffffffffffffffffffffffffffffffffffffffffffffff"); GenerateAlertTests(); } #endif BOOST_AUTO_TEST_CASE(AlertApplies) { SetMockTime(11); const std::vector<unsigned char>& alertKey = Params(CBaseChainParams::MAIN).AlertKey(); BOOST_FOREACH(const CAlert& alert, alerts) { BOOST_CHECK(alert.CheckSignature(alertKey)); } BOOST_CHECK(alerts.size() >= 3); // Matches: BOOST_CHECK(alerts[0].AppliesTo(1, "")); BOOST_CHECK(alerts[0].AppliesTo(999001, "")); BOOST_CHECK(alerts[0].AppliesTo(1, "/Satoshi:11.11.11/")); BOOST_CHECK(alerts[1].AppliesTo(1, "/Satoshi:0.1.0/")); BOOST_CHECK(alerts[1].AppliesTo(999001, "/Satoshi:0.1.0/")); BOOST_CHECK(alerts[2].AppliesTo(1, "/Satoshi:0.1.0/")); BOOST_CHECK(alerts[2].AppliesTo(1, "/Satoshi:0.2.0/")); // Don't match: BOOST_CHECK(!alerts[0].AppliesTo(-1, "")); BOOST_CHECK(!alerts[0].AppliesTo(999002, "")); BOOST_CHECK(!alerts[1].AppliesTo(1, "")); BOOST_CHECK(!alerts[1].AppliesTo(1, "Satoshi:0.1.0")); BOOST_CHECK(!alerts[1].AppliesTo(1, "/Satoshi:0.1.0")); BOOST_CHECK(!alerts[1].AppliesTo(1, "Satoshi:0.1.0/")); BOOST_CHECK(!alerts[1].AppliesTo(-1, "/Satoshi:0.1.0/")); BOOST_CHECK(!alerts[1].AppliesTo(999002, "/Satoshi:0.1.0/")); BOOST_CHECK(!alerts[1].AppliesTo(1, "/Satoshi:0.2.0/")); BOOST_CHECK(!alerts[2].AppliesTo(1, "/Satoshi:0.3.0/")); SetMockTime(0); } BOOST_AUTO_TEST_CASE(AlertNotify) { SetMockTime(11); const std::vector<unsigned char>& alertKey = Params(CBaseChainParams::MAIN).AlertKey(); boost::filesystem::path temp = GetTempPath() / boost::filesystem::unique_path("alertnotify-%%%%.txt"); mapArgs["-alertnotify"] = std::string("echo %s >> ") + temp.string(); BOOST_FOREACH(CAlert alert, alerts) alert.ProcessAlert(alertKey, false); std::vector<std::string> r = read_lines(temp); BOOST_CHECK_EQUAL(r.size(), 4u); // Windows built-in echo semantics are different than posixy shells. Quotes and // whitespace are printed literally. #ifndef WIN32 BOOST_CHECK_EQUAL(r[0], "Alert 1"); BOOST_CHECK_EQUAL(r[1], "Alert 2, cancels 1"); BOOST_CHECK_EQUAL(r[2], "Alert 2, cancels 1"); BOOST_CHECK_EQUAL(r[3], "Evil Alert; /bin/ls; echo "); // single-quotes should be removed #else BOOST_CHECK_EQUAL(r[0], "'Alert 1' "); BOOST_CHECK_EQUAL(r[1], "'Alert 2, cancels 1' "); BOOST_CHECK_EQUAL(r[2], "'Alert 2, cancels 1' "); BOOST_CHECK_EQUAL(r[3], "'Evil Alert; /bin/ls; echo ' "); #endif boost::filesystem::remove(temp); SetMockTime(0); } BOOST_AUTO_TEST_SUITE_END()
#include <math.h> #include <algorithm> #include <DDImage/Row.h> #include <DDImage/NukeWrapper.h> #include "LayerSet.h" #include "LayerSetKnob.h" namespace GradeBeauty { static const char* const HELP = "Provides artist friendly controls to manipulate multichannel cg render passes\n\n" "GradeBeauty will dynamically reconfigure itself depending on : \n\n" " * layers found connected to its input\n" " * categorization of found layer names based on what is defined in the configuration files\n\n" "Any color knob change affects :\n\n" " * the related multichannel layers\n" " * the beauty pass is then rebuilt with the modified layers\n\n" "Configurations: \n\n" " * default configuration is Arnold 5 stock layer names\n" " * can be adapted to any additive type renderer\n" " * To change this, you must modify the configuration files accordingly\n\n" " * <i>more info with the documentation button</i>" ; static const char* DEFAULT_VALUE_PYSCRIPT = "node = nuke.thisNode()\n" "colorKnobs = [knob for knob in node.allKnobs() if isinstance(knob, nuke.Color_Knob)]\n" "default = node.knob('math_type').getValue()\n" "defaultValue = [default] * 3\n" "for knob in colorKnobs:\n" " if knob.defaultValue() != default:\n" " knobToScript = knob.toScript()\n" " knob.setDefaultValue(defaultValue)\n" " knob.fromScript(knobToScript)" ; namespace BeautyLayerSetConstants { // frequently used lists of layer set category names namespace categories { static const StrVecType all = { "beauty_direct_indirect", "beauty_shading_global", "light_group", "beauty_shading" }; static const string shading = "beauty_shading"; static const StrVecType nonShading = {"beauty_direct_indirect", "beauty_shading_global", "light_group"}; static const StrVecType global = {"beauty_shading_global", "beauty_direct_indirect"}; } // frequently used lists of layers namespace layers { static const StrVecType all = LayerAlchemy::layerCollection.layers[categories::all]; static const StrVecType shading = LayerAlchemy::layerCollection.layers[categories::shading]; static const StrVecType nonShading = LayerAlchemy::layerCollection.layers[categories::nonShading]; static const StrVecType global = LayerAlchemy::layerCollection.layers[categories::global]; }; } using namespace DD::Image; using namespace BeautyLayerSetConstants; static const CategorizeFilter CategorizeFilterAllBeauty(BeautyLayerSetConstants::categories::all, CategorizeFilter::modes::ONLY); //The two modes that define the default value of this node's color knobs, and the math formula to apply enum GRADE_BEAUTY_MATH_MODE { STOPS = 0, MULTIPLY }; //defines the range of the Color_Knobs for each mode static map<int, std::array<int, 2 >> COLOR_KNOB_RANGES = { {GRADE_BEAUTY_MATH_MODE::STOPS, std::array<int, 2>{-10, 20}}, {GRADE_BEAUTY_MATH_MODE::MULTIPLY, std::array<int, 2>{0, 50}}, }; // names to be used in the enumeration knob to describe the mathModes static const char* const mathModeNames[] = {"stops", "multiply", 0}; //name given to the knob that acts on all layers static const char* const MASTER_KNOB_NAME = "master"; /** * Convenience object for storing, accessing, and calculating color knob values specific to GradeBeauty * * Most cg render engines output buffers as additive layers, so the math is extremely simple as it is additive only * * To keep the pixel engine as light as possible, the relationship between the knobs is calculated once during * construction as a vector of float pointers pointing back to the main private float values * * So each knob represents a possible cg layer, has it's own float[3], and a mapping of pointers to other values that could be relevant. * * In conjunction with a chosen mathModes enum value: * * - calculates the multiply value for a layer name for a given math mode * - calculates if the stored value is default * - stores relevant values, as to keep any logic out of the pixel_engine */ class GradeBeautyValueMap { private: map<string, float[3]> m_valueMap; map<string, vector<float*>> ptrValueMap; public: map<Channel, float> multipliers; vector<Knob*> m_colorKnobs; //initializes the layer value mapping and interconnect between of layers GradeBeautyValueMap() { LayerMap layerMapBeautyShading = LayerAlchemy::layerCollection.categorizeLayers(layers::shading, categorizeType::pub); m_colorKnobs.reserve(categories::all.size() + 1); float* ptrMaster = m_valueMap[MASTER_KNOB_NAME]; ptrValueMap[MASTER_KNOB_NAME].emplace_back(ptrMaster); for (auto iterLayer = layers::all.begin(); iterLayer != layers::all.end(); iterLayer++) { ptrValueMap[*iterLayer].emplace_back(m_valueMap[*iterLayer]); ptrValueMap[*iterLayer].emplace_back(ptrMaster); } for (auto iterLayer = layers::shading.begin(); iterLayer != layers::shading.end(); iterLayer++) { for (auto iterGlobal = layers::global.begin(); iterGlobal != layers::global.end(); iterGlobal++) { if (layerMapBeautyShading.contains(*iterGlobal)) { if (layerMapBeautyShading.isMember(*iterGlobal, *iterLayer)) { ptrValueMap[*iterLayer].emplace_back(m_valueMap[*iterGlobal]); } } } } //printf("created value map %p\n", (void*) this); } // returns a vector of pointers to all float values associated with this layer at a specific color index vector<float*> layerValuePointersForIndex(const string& layerName, const int& colorIndex) const { vector<float*> outputVector; auto it = ptrValueMap.find(layerName); int amount = it->second.size(); outputVector.reserve(amount); for (int idx = 0; idx < amount; idx++) { outputVector.emplace_back(&it->second[idx][colorIndex]); } return outputVector; } //returns the pointer specific to this layer float* getLayerFloatPointer(const string& knobName) const { return ptrValueMap.find(knobName)->second[0]; // the first index if where the layer pointer is. } // computes, for a given layer name, the total value to multiply the pixels with // at a specific color index for any given math mode float getLayerMultiplier(const string& layerName, const int& colorIndex, const int& mode) const { vector<float*> values = layerValuePointersForIndex(layerName, colorIndex); float out = 0.0f; if (mode == GRADE_BEAUTY_MATH_MODE::STOPS) { for (auto iterV = values.begin(); iterV != values.end(); iterV++) { out += *(*iterV); } out = (out > 0 ? std::pow(2, out) : 1.0f / pow(4, (fabsf(fabsf(out) / 2.0f)))); } else if (mode == GRADE_BEAUTY_MATH_MODE::MULTIPLY) { out = 1.0f; for (auto iterV = values.begin(); iterV != values.end(); iterV++) { if (iterV != values.begin()) { // skip the actual layer, it multiplies out *= *(*iterV); } } out *= getLayerFloatPointer(layerName)[colorIndex]; } return out; } bool isDefault(const string& layerName, const int& mode) const { float sum = 0; for (int colorIndex = 0; colorIndex < 3; colorIndex++ ){ sum += getLayerFloatPointer(layerName)[colorIndex]; } bool isDefault = (sum == (float) mode); return isDefault; } void addColorKnob(DD::Image::Knob* knob) { m_colorKnobs.emplace_back(knob); } }; class GradeBeauty : public DD::Image::PixelIop { private: bool m_firstRun {true}; LayerAlchemy::LayerSetKnob::LayerSetKnobData m_lsKnobData; int m_mathMode {GRADE_BEAUTY_MATH_MODE::STOPS}; bool m_clampBlack {true}; bool m_beautyDiff {true}; ChannelSet m_targetLayer {Mask_RGB}; GradeBeautyValueMap m_valueMap; // utility function to create color knobs for this node Knob* createColorKnob(Knob_Callback, float*, const string&, const bool&); // utility function to set color knob ranges, uses the integer value of mathModes as the center // can reset values with the bool parameter void setKnobRanges(const int&, const bool&); // utility function that handles the visibility of knobs based on the instance's state void setKnobVisibility(); // utility function that handles the setting of the knob's default value, uses python, couldn't find a c++ equivalent void setKnobDefaultValue(DD::Image::Op* nukeOpPtr); //this function simply tests that the private vector of color knob pointers is complete bool colorKnobsPopulated() const; // this calculates the multiply value for layers for the pixel engine. void calculateLayerValues(const DD::Image::ChannelSet&, GradeBeautyValueMap&); // channel set that contains all channels that are modified by the node public: void knobs(Knob_Callback); void _validate(bool); bool pass_transform() const {return true;} void in_channels(int, ChannelSet&) const; void pixel_engine(const Row&, int, int, int, ChannelMask, Row&); int knob_changed(Knob*); const char* Class() const {return description.name;} const char* node_help() const {return HELP;} static const Iop::Description description; GradeBeauty(Node* node); ~GradeBeauty(); // channel set that contains all channels that are modified by the node ChannelSet activeChannelSet() const; // pixel engine function when anything but the target layer is requested to render void channelPixelEngine(const Row&, int, int, int, ChannelMask, Row&); // pixel engine function when the target layer is requested to render void beautyPixelEngine(const Row&, int y, int x, int r, ChannelSet&, Row&); GradeBeauty* firstGradeBeauty(); }; GradeBeauty::GradeBeauty(Node* node) : PixelIop(node) {} static Op* build(Node* node) { return (new NukeWrapper(new GradeBeauty(node)))->noChannels()->noUnpremult()->mixLuminance(); } GradeBeauty::~GradeBeauty() {} const Iop::Description GradeBeauty::description( "GradeBeauty", "LayerAlchemy/GradeBeauty", build ); GradeBeauty* GradeBeauty::firstGradeBeauty() { return static_cast<GradeBeauty *>( this->firstOp() ); } void GradeBeauty::in_channels(int input_number, ChannelSet& mask) const { mask += ChannelMask(activeChannelSet()); } ChannelSet GradeBeauty::activeChannelSet() const { ChannelSet outChans; foreach(z, ChannelSet(m_targetLayer + m_lsKnobData.m_selectedChannels)) { int chanIdx = colourIndex(z); if (chanIdx <= 2) { outChans += z; } } return outChans; } void GradeBeauty::_validate(bool for_real) { copy_info(); // this copies the input info to the output ChannelSet inChannels = info_.channels(); LayerAlchemy::Utilities::validateTargetLayerColorIndex(this, m_targetLayer, 0, 2); if (validateLayerSetKnobUpdate(this, m_lsKnobData, LayerAlchemy::layerCollection, inChannels, CategorizeFilterAllBeauty)) { updateLayerSetKnob(this, m_lsKnobData, LayerAlchemy::layerCollection, inChannels, CategorizeFilterAllBeauty); setKnobVisibility(); setKnobRanges(m_mathMode, false); setKnobDefaultValue(this); _validate(true); // this will refresh the node UI in case the node was blank } ChannelSet activeChannels = activeChannelSet(); calculateLayerValues(activeChannels - m_targetLayer, m_valueMap); set_out_channels(activeChannels); info_.turn_on(m_targetLayer); } void GradeBeauty::channelPixelEngine(const Row& in, int y, int x, int r, ChannelMask channels, Row& aRow) { map<Channel, float*> aovFloatPtrChannelMap; foreach(channel, channels) { LayerAlchemy::Utilities::hard_copy(in, x, r, channel, aRow); aovFloatPtrChannelMap[channel] = aRow.writable(channel); } foreach(channel, channels) { unsigned chanIdx = colourIndex(channel); string layerName = getLayerName(channel); float* outAovValue = aovFloatPtrChannelMap[channel]; const float* inAovValue = in[channel]; float multValue = m_valueMap.multipliers[channel]; for (unsigned X = x; X < r; X++) { float origValue = inAovValue[X]; if (m_clampBlack) { outAovValue[X] = std::max(0.0f, (origValue * multValue)); } else { outAovValue[X] = origValue * multValue; } } } } void GradeBeauty::beautyPixelEngine(const Row& in, int y, int x, int r, ChannelSet& channels, Row& aRow) { ChannelSet bty = m_targetLayer.intersection(channels); ChannelSet aovs = m_lsKnobData.m_selectedChannels.intersection(channels); map<unsigned, float*> btyPtrIdxMap; map<Channel, float*> aovFloatPtrChannelMap; map<Channel, const float*> aovConstFloatPtrChannelMap; foreach(channel, bty) { unsigned chanIdx = colourIndex(channel); float* rowBtyChan; if (m_beautyDiff) { LayerAlchemy::Utilities::hard_copy(in, x, r, channel, aRow); rowBtyChan = aRow.writable(channel); } else { rowBtyChan = aRow.writableConstant(0.0f, channel); } btyPtrIdxMap[chanIdx] = rowBtyChan; } foreach(channel, aovs) { aovFloatPtrChannelMap[channel] = aRow.writable(channel); aovConstFloatPtrChannelMap[channel] = in[channel]; } for (const auto& kvp : btyPtrIdxMap) { unsigned btyChanIdx = kvp.first; float* aRowBty = kvp.second; foreach(aov, aovs) { unsigned aovChanIdx = colourIndex(aov); if (btyChanIdx != aovChanIdx) { continue; } float* aRowBty = btyPtrIdxMap[aovChanIdx]; float* aRowAov = aovFloatPtrChannelMap[aov]; const float* inAov = aovConstFloatPtrChannelMap[aov]; for (int X = x; X < r; X++) { float aovPixel = aRowAov[X]; float btyPixel = aRowBty[X]; if (m_beautyDiff) { float aovInPixel = inAov[X]; btyPixel -= aovInPixel; } float result = btyPixel + aovPixel; aRowBty[X] = m_clampBlack ? std::max(0.0f, result) : result; } } } } void GradeBeauty::pixel_engine(const Row& in, int y, int x, int r, ChannelMask channels, Row& out) { ChannelSet inChannels = ChannelSet(channels); Row aRow(x, r); bool isTargetLayer = m_targetLayer.intersection(inChannels).size() == m_targetLayer.size(); if (isTargetLayer) { ChannelSet activeChannels = activeChannelSet(); channelPixelEngine(in, y, x, r, activeChannels - m_targetLayer, aRow); beautyPixelEngine(in, y, x, r, activeChannels, aRow); } else { channelPixelEngine(in, y, x, r, inChannels, aRow); } LayerAlchemy::Utilities::hard_copy(aRow, x, r, inChannels, out); } void GradeBeauty::knobs(Knob_Callback f) { bool colorKnobVectorComplete = colorKnobsPopulated(); LayerAlchemy::LayerSetKnob::LayerSetKnob(f, m_lsKnobData); LayerAlchemy::Knobs::createDocumentationButton(f); LayerAlchemy::Knobs::createColorKnobResetButton(f); LayerAlchemy::Knobs::createVersionTextKnob(f); Divider(f, 0); // separates layer set knobs from the rest Input_ChannelMask_knob(f, &m_targetLayer, 0, "target layer"); SetFlags(f, Knob::NO_ALPHA_PULLDOWN); ClearFlags(f, Knob::STARTLINE); Tooltip(f, "<p>Selects which layer to pre-subtract layers from (if enabled) and add the modified layers to</p>"); Enumeration_knob(f, &m_mathMode, mathModeNames, "math_type", "math type"); Tooltip(f, "<p>multiply : this mode acts like a chain of multiply nodes:</p>" "<p>master * all global contributions (if any) * layer</p>" "<p><i>since the layer is multiplied last, you can also use this mode to disable the layer</i></p>" "<p>stops : this mode acts like a single exposure node for each layer</p> " "<p>it adds all contributions and then does the exposure conversion</p>" "<p><i>(for example, if master is set to 1.0 and the layer is set to 0.0, this means one stop over)</i></p>"); SetFlags(f, Knob::ALWAYS_SAVE); Bool_knob(f, &m_beautyDiff, "subtract", "subtract layer set from target layer"); Tooltip(f, "<p>enabled : the additive sum of the chosen layer set is subtracted from the target layer " "before recombining with this node's modifications</p>" "<p><i>(this means any difference between the target layer " "and the render layers is kept in the final output)</i></p>"); Bool_knob(f, &m_clampBlack, "black_clamp", "black clamp"); Tooltip(f, "<p><b>enabled </b>: clamp negative values from all output layers</p>" "<p><b>disabled </b>: negative values permitted</p>"); Divider(f, 0); // separates master from the rest Knob* masterKnob = createColorKnob(f, m_valueMap.getLayerFloatPointer(MASTER_KNOB_NAME), MASTER_KNOB_NAME, true); Tooltip(f, "this knob contributes to each layer"); if (!colorKnobVectorComplete) { m_valueMap.addColorKnob(masterKnob); } Divider(f, 0); // separates master from the rest for (auto iterLayerName = layers::nonShading.begin(); iterLayerName != layers::nonShading.end(); iterLayerName++) { Knob* aovKnob = createColorKnob(f, m_valueMap.getLayerFloatPointer(*iterLayerName), *iterLayerName, false); Tooltip(f, "applies to this layer or to layers in this layer set"); if (!colorKnobVectorComplete) { m_valueMap.addColorKnob(aovKnob); } } BeginClosedGroup(f, "shading_group", "beauty shading layers"); SetFlags(f, Knob::HIDDEN); for (auto iterLayerName = layers::shading.begin(); iterLayerName != layers::shading.end(); iterLayerName++) { Knob* aovKnob = createColorKnob(f, m_valueMap.getLayerFloatPointer(*iterLayerName), *iterLayerName, false); Tooltip(f, "apply to this layer only"); if (!colorKnobVectorComplete) { m_valueMap.addColorKnob(aovKnob); } } EndGroup(f); Divider(f, 0); // separates NukeWrapper knobs created after this // Toolbar BeginToolbar(f, "toolbar", "toolbar"); Link_knob(f, MASTER_KNOB_NAME, "viewerLink", "GradeBeauty master"); SetFlags(f, Knob::HIDE_ANIMATION_AND_VIEWS | Knob::NO_UNDO | Knob::NO_RERENDER | Knob::STARTLINE); Link_knob(f, "reset values", "", "reset values"); EndToolbar(f); } int GradeBeauty::knob_changed(Knob* k) { if (k->is("math_type")) { setKnobRanges(m_mathMode, true); setKnobDefaultValue(this); } if (k == &DD::Image::Knob::inputChange) { _validate(true); } return 1; } bool GradeBeauty::colorKnobsPopulated() const { return (m_valueMap.m_colorKnobs.size() >= (categories::all.size() + 1)); } Knob* GradeBeauty::createColorKnob(Knob_Callback f, float* valueStore, const string& name, const bool& visible) { const char* knobName = name.c_str(); Knob* colorKnob = Color_knob(f, valueStore, IRange(COLOR_KNOB_RANGES[this->m_mathMode][0], COLOR_KNOB_RANGES[m_mathMode][1]), knobName, knobName); SetFlags(f, Knob::LOG_SLIDER); SetFlags(f, Knob::NO_COLOR_DROPDOWN); if (f.makeKnobs()) { colorKnob->visible(visible); } return colorKnob; } void GradeBeauty::setKnobRanges(const int& modeValue, const bool& reset) { const char* script = (modeValue == 0 ? "{0}" : "{1}"); for (auto iterKnob = m_valueMap.m_colorKnobs.begin(); iterKnob != m_valueMap.m_colorKnobs.end(); iterKnob++) { if (reset) { (*iterKnob)->from_script(script); } (*iterKnob)->set_range(COLOR_KNOB_RANGES[modeValue][0], COLOR_KNOB_RANGES[modeValue][1], true); } } void GradeBeauty::setKnobVisibility() { bool isBeautyShading = LayerAlchemy::LayerSetKnob::getLayerSetKnobEnumString(this) == categories::shading; auto layerNames = LayerAlchemy::LayerSet::getLayerNames(m_lsKnobData.m_selectedChannels); LayerMap categorized = LayerAlchemy::layerCollection.categorizeLayers(layerNames, categorizeType::pub); for (vector<Knob*>::const_iterator iterKnob = m_valueMap.m_colorKnobs.begin(); iterKnob != m_valueMap.m_colorKnobs.end(); iterKnob++) { Knob* colorKnob = *iterKnob; string knobName = colorKnob->name(); bool isGlobalLayer = categorized.contains(knobName); bool contains = categorized.isMember("all", knobName); if (knobName == MASTER_KNOB_NAME) { contains = true; } else if (isBeautyShading && isGlobalLayer && categorized.contains(knobName)) { contains = true; } if (contains) { colorKnob->clear_flag(Knob::DO_NOT_WRITE); colorKnob->set_flag(Knob::ALWAYS_SAVE); } else // this is run on knobs that are not visible to the user { colorKnob->clear_flag(Knob::ALWAYS_SAVE); colorKnob->set_flag(Knob::DO_NOT_WRITE); if (firstGradeBeauty()->m_firstRun) { colorKnob->set_value(m_mathMode); // make sure the unsaved knobs are the correct default } } colorKnob->visible(contains); } knob("shading_group")->visible(isBeautyShading); firstGradeBeauty()->m_firstRun = false; } void GradeBeauty::setKnobDefaultValue(DD::Image::Op* nukeOpPtr) { nukeOpPtr->script_command(DEFAULT_VALUE_PYSCRIPT, true, false); } void GradeBeauty::calculateLayerValues(const DD::Image::ChannelSet& channels, GradeBeautyValueMap& valueMap) { foreach(channel, channels) { int chanIdx = colourIndex(channel); string layerName = getLayerName(channel); m_valueMap.multipliers[channel] = m_valueMap.getLayerMultiplier(layerName, chanIdx, m_mathMode); } } } // End namespace GradeBeauty
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The Altair developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "guiutil.h" #include "bitcoinaddressvalidator.h" #include "bitcoinunits.h" #include "qvalidatedlineedit.h" #include "walletmodel.h" #include "init.h" #include "main.h" #include "primitives/transaction.h" #include "protocol.h" #include "script/script.h" #include "script/standard.h" #include "util.h" #ifdef WIN32 #ifdef _WIN32_WINNT #undef _WIN32_WINNT #endif #define _WIN32_WINNT 0x0501 #ifdef _WIN32_IE #undef _WIN32_IE #endif #define _WIN32_IE 0x0501 #define WIN32_LEAN_AND_MEAN 1 #ifndef NOMINMAX #define NOMINMAX #endif #include "shellapi.h" #include "shlobj.h" #include "shlwapi.h" #endif #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #if BOOST_FILESYSTEM_VERSION >= 3 #include <boost/filesystem/detail/utf8_codecvt_facet.hpp> #endif #include <QAbstractItemView> #include <QApplication> #include <QClipboard> #include <QDateTime> #include <QDesktopServices> #include <QDesktopWidget> #include <QDoubleValidator> #include <QFileDialog> #include <QFont> #include <QLineEdit> #include <QSettings> #include <QTextDocument> // for Qt::mightBeRichText #include <QThread> #if QT_VERSION < 0x050000 #include <QUrl> #else #include <QUrlQuery> #endif #if BOOST_FILESYSTEM_VERSION >= 3 static boost::filesystem::detail::utf8_codecvt_facet utf8; #endif #if defined(Q_OS_MAC) extern double NSAppKitVersionNumber; #if !defined(NSAppKitVersionNumber10_8) #define NSAppKitVersionNumber10_8 1187 #endif #if !defined(NSAppKitVersionNumber10_9) #define NSAppKitVersionNumber10_9 1265 #endif #endif #define URI_SCHEME "Altair" namespace GUIUtil { QString dateTimeStr(const QDateTime& date) { return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm"); } QString dateTimeStr(qint64 nTime) { return dateTimeStr(QDateTime::fromTime_t((qint32)nTime)); } QFont bitcoinAddressFont() { QFont font("Monospace"); #if QT_VERSION >= 0x040800 font.setStyleHint(QFont::Monospace); #else font.setStyleHint(QFont::TypeWriter); #endif return font; } void setupAddressWidget(QValidatedLineEdit* widget, QWidget* parent) { parent->setFocusProxy(widget); widget->setFont(bitcoinAddressFont()); #if QT_VERSION >= 0x040700 // We don't want translators to use own addresses in translations // and this is the only place, where this address is supplied. widget->setPlaceholderText(QObject::tr("Enter a Altair address (e.g. %1)").arg("D7VFR83SQbiezrW72hjcWJtcfip5krte2Z")); #endif widget->setValidator(new BitcoinAddressEntryValidator(parent)); widget->setCheckValidator(new BitcoinAddressCheckValidator(parent)); } void setupAmountWidget(QLineEdit* widget, QWidget* parent) { QDoubleValidator* amountValidator = new QDoubleValidator(parent); amountValidator->setDecimals(8); amountValidator->setBottom(0.0); widget->setValidator(amountValidator); widget->setAlignment(Qt::AlignRight | Qt::AlignVCenter); } bool parseBitcoinURI(const QUrl& uri, SendCoinsRecipient* out) { // return if URI is not valid or is no Altair: URI if (!uri.isValid() || uri.scheme() != QString(URI_SCHEME)) return false; SendCoinsRecipient rv; rv.address = uri.path(); // Trim any following forward slash which may have been added by the OS if (rv.address.endsWith("/")) { rv.address.truncate(rv.address.length() - 1); } rv.amount = 0; #if QT_VERSION < 0x050000 QList<QPair<QString, QString> > items = uri.queryItems(); #else QUrlQuery uriQuery(uri); QList<QPair<QString, QString> > items = uriQuery.queryItems(); #endif for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++) { bool fShouldReturnFalse = false; if (i->first.startsWith("req-")) { i->first.remove(0, 4); fShouldReturnFalse = true; } if (i->first == "label") { rv.label = i->second; fShouldReturnFalse = false; } if (i->first == "message") { rv.message = i->second; fShouldReturnFalse = false; } else if (i->first == "amount") { if (!i->second.isEmpty()) { if (!BitcoinUnits::parse(BitcoinUnits::ATR, i->second, &rv.amount)) { return false; } } fShouldReturnFalse = false; } if (fShouldReturnFalse) return false; } if (out) { *out = rv; } return true; } bool parseBitcoinURI(QString uri, SendCoinsRecipient* out) { // Convert Altair:// to Altair: // // Cannot handle this later, because Altair:// will cause Qt to see the part after // as host, // which will lower-case it (and thus invalidate the address). if (uri.startsWith(URI_SCHEME "://", Qt::CaseInsensitive)) { uri.replace(0, std::strlen(URI_SCHEME) + 3, URI_SCHEME ":"); } QUrl uriInstance(uri); return parseBitcoinURI(uriInstance, out); } QString formatBitcoinURI(const SendCoinsRecipient& info) { QString ret = QString(URI_SCHEME ":%1").arg(info.address); int paramCount = 0; if (info.amount) { ret += QString("?amount=%1").arg(BitcoinUnits::format(BitcoinUnits::ATR, info.amount, false, BitcoinUnits::separatorNever)); paramCount++; } if (!info.label.isEmpty()) { QString lbl(QUrl::toPercentEncoding(info.label)); ret += QString("%1label=%2").arg(paramCount == 0 ? "?" : "&").arg(lbl); paramCount++; } if (!info.message.isEmpty()) { QString msg(QUrl::toPercentEncoding(info.message)); ret += QString("%1message=%2").arg(paramCount == 0 ? "?" : "&").arg(msg); paramCount++; } return ret; } bool isDust(const QString& address, const CAmount& amount) { CTxDestination dest = CBitcoinAddress(address.toStdString()).Get(); CScript script = GetScriptForDestination(dest); CTxOut txOut(amount, script); return txOut.IsDust(::minRelayTxFee); } QString HtmlEscape(const QString& str, bool fMultiLine) { #if QT_VERSION < 0x050000 QString escaped = Qt::escape(str); #else QString escaped = str.toHtmlEscaped(); #endif escaped = escaped.replace(" ", "&nbsp;"); if (fMultiLine) { escaped = escaped.replace("\n", "<br>\n"); } return escaped; } QString HtmlEscape(const std::string& str, bool fMultiLine) { return HtmlEscape(QString::fromStdString(str), fMultiLine); } void copyEntryData(QAbstractItemView* view, int column, int role) { if (!view || !view->selectionModel()) return; QModelIndexList selection = view->selectionModel()->selectedRows(column); if (!selection.isEmpty()) { // Copy first item setClipboard(selection.at(0).data(role).toString()); } } QString getSaveFileName(QWidget* parent, const QString& caption, const QString& dir, const QString& filter, QString* selectedSuffixOut) { QString selectedFilter; QString myDir; if (dir.isEmpty()) // Default to user documents location { #if QT_VERSION < 0x050000 myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation); #else myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation); #endif } else { myDir = dir; } /* Directly convert path to native OS path separators */ QString result = QDir::toNativeSeparators(QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter)); /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */ QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]"); QString selectedSuffix; if (filter_re.exactMatch(selectedFilter)) { selectedSuffix = filter_re.cap(1); } /* Add suffix if needed */ QFileInfo info(result); if (!result.isEmpty()) { if (info.suffix().isEmpty() && !selectedSuffix.isEmpty()) { /* No suffix specified, add selected suffix */ if (!result.endsWith(".")) result.append("."); result.append(selectedSuffix); } } /* Return selected suffix if asked to */ if (selectedSuffixOut) { *selectedSuffixOut = selectedSuffix; } return result; } QString getOpenFileName(QWidget* parent, const QString& caption, const QString& dir, const QString& filter, QString* selectedSuffixOut) { QString selectedFilter; QString myDir; if (dir.isEmpty()) // Default to user documents location { #if QT_VERSION < 0x050000 myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation); #else myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation); #endif } else { myDir = dir; } /* Directly convert path to native OS path separators */ QString result = QDir::toNativeSeparators(QFileDialog::getOpenFileName(parent, caption, myDir, filter, &selectedFilter)); if (selectedSuffixOut) { /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */ QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]"); QString selectedSuffix; if (filter_re.exactMatch(selectedFilter)) { selectedSuffix = filter_re.cap(1); } *selectedSuffixOut = selectedSuffix; } return result; } Qt::ConnectionType blockingGUIThreadConnection() { if (QThread::currentThread() != qApp->thread()) { return Qt::BlockingQueuedConnection; } else { return Qt::DirectConnection; } } bool checkPoint(const QPoint& p, const QWidget* w) { QWidget* atW = QApplication::widgetAt(w->mapToGlobal(p)); if (!atW) return false; return atW->topLevelWidget() == w; } bool isObscured(QWidget* w) { return !(checkPoint(QPoint(0, 0), w) && checkPoint(QPoint(w->width() - 1, 0), w) && checkPoint(QPoint(0, w->height() - 1), w) && checkPoint(QPoint(w->width() - 1, w->height() - 1), w) && checkPoint(QPoint(w->width() / 2, w->height() / 2), w)); } void openDebugLogfile() { boost::filesystem::path pathDebug = GetDataDir() / "debug.log"; /* Open debug.log with the associated application */ if (boost::filesystem::exists(pathDebug)) QDesktopServices::openUrl(QUrl::fromLocalFile(boostPathToQString(pathDebug))); } void openConfigfile() { boost::filesystem::path pathConfig = GetConfigFile(); /* Open Altair.conf with the associated application */ if (boost::filesystem::exists(pathConfig)) QDesktopServices::openUrl(QUrl::fromLocalFile(boostPathToQString(pathConfig))); } void openMNConfigfile() { boost::filesystem::path pathConfig = GetMasternodeConfigFile(); /* Open masternode.conf with the associated application */ if (boost::filesystem::exists(pathConfig)) QDesktopServices::openUrl(QUrl::fromLocalFile(boostPathToQString(pathConfig))); } void showBackups() { boost::filesystem::path pathBackups = GetDataDir() / "backups"; /* Open folder with default browser */ if (boost::filesystem::exists(pathBackups)) QDesktopServices::openUrl(QUrl::fromLocalFile(boostPathToQString(pathBackups))); } void SubstituteFonts(const QString& language) { #if defined(Q_OS_MAC) // Background: // OSX's default font changed in 10.9 and QT is unable to find it with its // usual fallback methods when building against the 10.7 sdk or lower. // The 10.8 SDK added a function to let it find the correct fallback font. // If this fallback is not properly loaded, some characters may fail to // render correctly. // // The same thing happened with 10.10. .Helvetica Neue DeskInterface is now default. // // Solution: If building with the 10.7 SDK or lower and the user's platform // is 10.9 or higher at runtime, substitute the correct font. This needs to // happen before the QApplication is created. #if defined(MAC_OS_X_VERSION_MAX_ALLOWED) && MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_8 if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_8) { if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_9) /* On a 10.9 - 10.9.x system */ QFont::insertSubstitution(".Lucida Grande UI", "Lucida Grande"); else { /* 10.10 or later system */ if (language == "zh_CN" || language == "zh_TW" || language == "zh_HK") // traditional or simplified Chinese QFont::insertSubstitution(".Helvetica Neue DeskInterface", "Heiti SC"); else if (language == "ja") // Japanesee QFont::insertSubstitution(".Helvetica Neue DeskInterface", "Songti SC"); else QFont::insertSubstitution(".Helvetica Neue DeskInterface", "Lucida Grande"); } } #endif #endif } ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject* parent) : QObject(parent), size_threshold(size_threshold) { } bool ToolTipToRichTextFilter::eventFilter(QObject* obj, QEvent* evt) { if (evt->type() == QEvent::ToolTipChange) { QWidget* widget = static_cast<QWidget*>(obj); QString tooltip = widget->toolTip(); if (tooltip.size() > size_threshold && !tooltip.startsWith("<qt")) { // Escape the current message as HTML and replace \n by <br> if it's not rich text if (!Qt::mightBeRichText(tooltip)) tooltip = HtmlEscape(tooltip, true); // Envelop with <qt></qt> to make sure Qt detects every tooltip as rich text // and style='white-space:pre' to preserve line composition tooltip = "<qt style='white-space:pre'>" + tooltip + "</qt>"; widget->setToolTip(tooltip); return true; } } return QObject::eventFilter(obj, evt); } void TableViewLastColumnResizingFixer::connectViewHeadersSignals() { connect(tableView->horizontalHeader(), SIGNAL(sectionResized(int, int, int)), this, SLOT(on_sectionResized(int, int, int))); connect(tableView->horizontalHeader(), SIGNAL(geometriesChanged()), this, SLOT(on_geometriesChanged())); } // We need to disconnect these while handling the resize events, otherwise we can enter infinite loops. void TableViewLastColumnResizingFixer::disconnectViewHeadersSignals() { disconnect(tableView->horizontalHeader(), SIGNAL(sectionResized(int, int, int)), this, SLOT(on_sectionResized(int, int, int))); disconnect(tableView->horizontalHeader(), SIGNAL(geometriesChanged()), this, SLOT(on_geometriesChanged())); } // Setup the resize mode, handles compatibility for Qt5 and below as the method signatures changed. // Refactored here for readability. void TableViewLastColumnResizingFixer::setViewHeaderResizeMode(int logicalIndex, QHeaderView::ResizeMode resizeMode) { #if QT_VERSION < 0x050000 tableView->horizontalHeader()->setResizeMode(logicalIndex, resizeMode); #else tableView->horizontalHeader()->setSectionResizeMode(logicalIndex, resizeMode); #endif } void TableViewLastColumnResizingFixer::resizeColumn(int nColumnIndex, int width) { tableView->setColumnWidth(nColumnIndex, width); tableView->horizontalHeader()->resizeSection(nColumnIndex, width); } int TableViewLastColumnResizingFixer::getColumnsWidth() { int nColumnsWidthSum = 0; for (int i = 0; i < columnCount; i++) { nColumnsWidthSum += tableView->horizontalHeader()->sectionSize(i); } return nColumnsWidthSum; } int TableViewLastColumnResizingFixer::getAvailableWidthForColumn(int column) { int nResult = lastColumnMinimumWidth; int nTableWidth = tableView->horizontalHeader()->width(); if (nTableWidth > 0) { int nOtherColsWidth = getColumnsWidth() - tableView->horizontalHeader()->sectionSize(column); nResult = std::max(nResult, nTableWidth - nOtherColsWidth); } return nResult; } // Make sure we don't make the columns wider than the tables viewport width. void TableViewLastColumnResizingFixer::adjustTableColumnsWidth() { disconnectViewHeadersSignals(); resizeColumn(lastColumnIndex, getAvailableWidthForColumn(lastColumnIndex)); connectViewHeadersSignals(); int nTableWidth = tableView->horizontalHeader()->width(); int nColsWidth = getColumnsWidth(); if (nColsWidth > nTableWidth) { resizeColumn(secondToLastColumnIndex, getAvailableWidthForColumn(secondToLastColumnIndex)); } } // Make column use all the space available, useful during window resizing. void TableViewLastColumnResizingFixer::stretchColumnWidth(int column) { disconnectViewHeadersSignals(); resizeColumn(column, getAvailableWidthForColumn(column)); connectViewHeadersSignals(); } // When a section is resized this is a slot-proxy for ajustAmountColumnWidth(). void TableViewLastColumnResizingFixer::on_sectionResized(int logicalIndex, int oldSize, int newSize) { adjustTableColumnsWidth(); int remainingWidth = getAvailableWidthForColumn(logicalIndex); if (newSize > remainingWidth) { resizeColumn(logicalIndex, remainingWidth); } } // When the tabless geometry is ready, we manually perform the stretch of the "Message" column, // as the "Stretch" resize mode does not allow for interactive resizing. void TableViewLastColumnResizingFixer::on_geometriesChanged() { if ((getColumnsWidth() - this->tableView->horizontalHeader()->width()) != 0) { disconnectViewHeadersSignals(); resizeColumn(secondToLastColumnIndex, getAvailableWidthForColumn(secondToLastColumnIndex)); connectViewHeadersSignals(); } } /** * Initializes all internal variables and prepares the * the resize modes of the last 2 columns of the table and */ TableViewLastColumnResizingFixer::TableViewLastColumnResizingFixer(QTableView* table, int lastColMinimumWidth, int allColsMinimumWidth) : tableView(table), lastColumnMinimumWidth(lastColMinimumWidth), allColumnsMinimumWidth(allColsMinimumWidth) { columnCount = tableView->horizontalHeader()->count(); lastColumnIndex = columnCount - 1; secondToLastColumnIndex = columnCount - 2; tableView->horizontalHeader()->setMinimumSectionSize(allColumnsMinimumWidth); setViewHeaderResizeMode(secondToLastColumnIndex, QHeaderView::Interactive); setViewHeaderResizeMode(lastColumnIndex, QHeaderView::Interactive); } /** * Class constructor. * @param[in] seconds Number of seconds to convert to a DHMS string */ DHMSTableWidgetItem::DHMSTableWidgetItem(const int64_t seconds) : QTableWidgetItem(), value(seconds) { this->setText(QString::fromStdString(DurationToDHMS(seconds))); } /** * Comparator overload to ensure that the "DHMS"-type durations as used in * the "active-since" list in the masternode tab are sorted by the elapsed * duration (versus the string value being sorted). * @param[in] item Right hand side of the less than operator */ bool DHMSTableWidgetItem::operator<(QTableWidgetItem const& item) const { DHMSTableWidgetItem const* rhs = dynamic_cast<DHMSTableWidgetItem const*>(&item); if (!rhs) return QTableWidgetItem::operator<(item); return value < rhs->value; } #ifdef WIN32 boost::filesystem::path static StartupShortcutPath() { return GetSpecialFolderPath(CSIDL_STARTUP) / "Altair.lnk"; } bool GetStartOnSystemStartup() { // check for Altair.lnk return boost::filesystem::exists(StartupShortcutPath()); } bool SetStartOnSystemStartup(bool fAutoStart) { // If the shortcut exists already, remove it for updating boost::filesystem::remove(StartupShortcutPath()); if (fAutoStart) { CoInitialize(NULL); // Get a pointer to the IShellLink interface. IShellLink* psl = NULL; HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, reinterpret_cast<void**>(&psl)); if (SUCCEEDED(hres)) { // Get the current executable path TCHAR pszExePath[MAX_PATH]; GetModuleFileName(NULL, pszExePath, sizeof(pszExePath)); TCHAR pszArgs[5] = TEXT("-min"); // Set the path to the shortcut target psl->SetPath(pszExePath); PathRemoveFileSpec(pszExePath); psl->SetWorkingDirectory(pszExePath); psl->SetShowCmd(SW_SHOWMINNOACTIVE); psl->SetArguments(pszArgs); // Query IShellLink for the IPersistFile interface for // saving the shortcut in persistent storage. IPersistFile* ppf = NULL; hres = psl->QueryInterface(IID_IPersistFile, reinterpret_cast<void**>(&ppf)); if (SUCCEEDED(hres)) { WCHAR pwsz[MAX_PATH]; // Ensure that the string is ANSI. MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH); // Save the link by calling IPersistFile::Save. hres = ppf->Save(pwsz, TRUE); ppf->Release(); psl->Release(); CoUninitialize(); return true; } psl->Release(); } CoUninitialize(); return false; } return true; } #elif defined(Q_OS_LINUX) // Follow the Desktop Application Autostart Spec: // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html boost::filesystem::path static GetAutostartDir() { namespace fs = boost::filesystem; char* pszConfigHome = getenv("XDG_CONFIG_HOME"); if (pszConfigHome) return fs::path(pszConfigHome) / "autostart"; char* pszHome = getenv("HOME"); if (pszHome) return fs::path(pszHome) / ".config" / "autostart"; return fs::path(); } boost::filesystem::path static GetAutostartFilePath() { return GetAutostartDir() / "Altair.desktop"; } bool GetStartOnSystemStartup() { boost::filesystem::ifstream optionFile(GetAutostartFilePath()); if (!optionFile.good()) return false; // Scan through file for "Hidden=true": std::string line; while (!optionFile.eof()) { getline(optionFile, line); if (line.find("Hidden") != std::string::npos && line.find("true") != std::string::npos) return false; } optionFile.close(); return true; } bool SetStartOnSystemStartup(bool fAutoStart) { if (!fAutoStart) boost::filesystem::remove(GetAutostartFilePath()); else { char pszExePath[MAX_PATH + 1]; memset(pszExePath, 0, sizeof(pszExePath)); if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath) - 1) == -1) return false; boost::filesystem::create_directories(GetAutostartDir()); boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out | std::ios_base::trunc); if (!optionFile.good()) return false; // Write a Altair.desktop file to the autostart directory: optionFile << "[Desktop Entry]\n"; optionFile << "Type=Application\n"; optionFile << "Name=Altair\n"; optionFile << "Exec=" << pszExePath << " -min\n"; optionFile << "Terminal=false\n"; optionFile << "Hidden=false\n"; optionFile.close(); } return true; } #elif defined(Q_OS_MAC) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" // based on: https://github.com/Mozketo/LaunchAtLoginController/blob/master/LaunchAtLoginController.m #include <CoreFoundation/CoreFoundation.h> #include <CoreServices/CoreServices.h> LSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef findUrl); LSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef findUrl) { // loop through the list of startup items and try to find the Altair app CFArrayRef listSnapshot = LSSharedFileListCopySnapshot(list, NULL); for (int i = 0; i < CFArrayGetCount(listSnapshot); i++) { LSSharedFileListItemRef item = (LSSharedFileListItemRef)CFArrayGetValueAtIndex(listSnapshot, i); UInt32 resolutionFlags = kLSSharedFileListNoUserInteraction | kLSSharedFileListDoNotMountVolumes; CFURLRef currentItemURL = NULL; #if defined(MAC_OS_X_VERSION_MAX_ALLOWED) && MAC_OS_X_VERSION_MAX_ALLOWED >= 10100 if(&LSSharedFileListItemCopyResolvedURL) currentItemURL = LSSharedFileListItemCopyResolvedURL(item, resolutionFlags, NULL); #if defined(MAC_OS_X_VERSION_MIN_REQUIRED) && MAC_OS_X_VERSION_MIN_REQUIRED < 10100 else LSSharedFileListItemResolve(item, resolutionFlags, &currentItemURL, NULL); #endif #else LSSharedFileListItemResolve(item, resolutionFlags, &currentItemURL, NULL); #endif if(currentItemURL && CFEqual(currentItemURL, findUrl)) { // found CFRelease(currentItemURL); return item; } if (currentItemURL) { CFRelease(currentItemURL); } } return NULL; } bool GetStartOnSystemStartup() { CFURLRef bitcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle()); LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL); LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, bitcoinAppUrl); return !!foundItem; // return boolified object } bool SetStartOnSystemStartup(bool fAutoStart) { CFURLRef bitcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle()); LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL); LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, bitcoinAppUrl); if (fAutoStart && !foundItem) { // add Altair app to startup item list LSSharedFileListInsertItemURL(loginItems, kLSSharedFileListItemBeforeFirst, NULL, NULL, bitcoinAppUrl, NULL, NULL); } else if (!fAutoStart && foundItem) { // remove item LSSharedFileListItemRemove(loginItems, foundItem); } return true; } #pragma GCC diagnostic pop #else bool GetStartOnSystemStartup() { return false; } bool SetStartOnSystemStartup(bool fAutoStart) { return false; } #endif void saveWindowGeometry(const QString& strSetting, QWidget* parent) { QSettings settings; settings.setValue(strSetting + "Pos", parent->pos()); settings.setValue(strSetting + "Size", parent->size()); } void restoreWindowGeometry(const QString& strSetting, const QSize& defaultSize, QWidget* parent) { QSettings settings; QPoint pos = settings.value(strSetting + "Pos").toPoint(); QSize size = settings.value(strSetting + "Size", defaultSize).toSize(); if (!pos.x() && !pos.y()) { QRect screen = QApplication::desktop()->screenGeometry(); pos.setX((screen.width() - size.width()) / 2); pos.setY((screen.height() - size.height()) / 2); } parent->resize(size); parent->move(pos); } // Check whether a theme is not build-in bool isExternal(QString theme) { if (theme.isEmpty()) return false; return (theme.operator!=("default")); } // Open CSS when configured QString loadStyleSheet() { QString styleSheet; QSettings settings; QString cssName; QString theme = settings.value("theme", "").toString(); if (isExternal(theme)) { // External CSS settings.setValue("fCSSexternal", true); boost::filesystem::path pathAddr = GetDataDir() / "themes/"; cssName = pathAddr.string().c_str() + theme + "/css/theme.css"; } else { // Build-in CSS settings.setValue("fCSSexternal", false); if (!theme.isEmpty()) { cssName = QString(":/css/") + theme; } else { cssName = QString(":/css/default"); settings.setValue("theme", "default"); } } QFile qFile(cssName); if (qFile.open(QFile::ReadOnly)) { styleSheet = QLatin1String(qFile.readAll()); } return styleSheet; } void setClipboard(const QString& str) { QApplication::clipboard()->setText(str, QClipboard::Clipboard); QApplication::clipboard()->setText(str, QClipboard::Selection); } #if BOOST_FILESYSTEM_VERSION >= 3 boost::filesystem::path qstringToBoostPath(const QString& path) { return boost::filesystem::path(path.toStdString(), utf8); } QString boostPathToQString(const boost::filesystem::path& path) { return QString::fromStdString(path.string(utf8)); } #else #warning Conversion between boost path and QString can use invalid character encoding with boost_filesystem v2 and older boost::filesystem::path qstringToBoostPath(const QString& path) { return boost::filesystem::path(path.toStdString()); } QString boostPathToQString(const boost::filesystem::path& path) { return QString::fromStdString(path.string()); } #endif QString formatDurationStr(int secs) { QStringList strList; int days = secs / 86400; int hours = (secs % 86400) / 3600; int mins = (secs % 3600) / 60; int seconds = secs % 60; if (days) strList.append(QString(QObject::tr("%1 d")).arg(days)); if (hours) strList.append(QString(QObject::tr("%1 h")).arg(hours)); if (mins) strList.append(QString(QObject::tr("%1 m")).arg(mins)); if (seconds || (!days && !hours && !mins)) strList.append(QString(QObject::tr("%1 s")).arg(seconds)); return strList.join(" "); } QString formatServicesStr(quint64 mask) { QStringList strList; // Just scan the last 8 bits for now. for (int i = 0; i < 8; i++) { uint64_t check = 1 << i; if (mask & check) { switch (check) { case NODE_NETWORK: strList.append(QObject::tr("NETWORK")); break; case NODE_BLOOM: case NODE_BLOOM_WITHOUT_MN: strList.append(QObject::tr("BLOOM")); break; default: strList.append(QString("%1[%2]").arg(QObject::tr("UNKNOWN")).arg(check)); } } } if (strList.size()) return strList.join(" & "); else return QObject::tr("None"); } QString formatPingTime(double dPingTime) { return dPingTime == 0 ? QObject::tr("N/A") : QString(QObject::tr("%1 ms")).arg(QString::number((int)(dPingTime * 1000), 10)); } } // namespace GUIUtil
//////////////////////////////////////////////////////////////////////////////////////// // // Nestopia - NES/Famicom emulator written in C++ // // Copyright (C) 2003-2008 Martin Freij // // This file is part of Nestopia. // // Nestopia 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. // // Nestopia 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 Nestopia; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // //////////////////////////////////////////////////////////////////////////////////////// #ifndef NST_INPUT_MAHJONG_H #define NST_INPUT_MAHJONG_H #ifdef NST_PRAGMA_ONCE #pragma once #endif namespace Nes { namespace Core { namespace Input { class Mahjong : public Device { public: explicit Mahjong(const Cpu&); private: void Reset(); void Poke(uint); uint Peek(uint); void SaveState(State::Saver&,byte) const; enum { PART = 0x06 }; uint stream; }; } } } #endif
// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "signverifymessagedialog.h" #include "ui_signverifymessagedialog.h" #include "addressbookpage.h" #include "base58.h" #include "guiutil.h" #include "init.h" #include "main.h" #include "optionsmodel.h" #include "walletmodel.h" #include "wallet.h" #include <QClipboard> #include <string> #include <vector> SignVerifyMessageDialog::SignVerifyMessageDialog(QWidget *parent) : QDialog(parent), ui(new Ui::SignVerifyMessageDialog), model(0) { ui->setupUi(this); #if (QT_VERSION >= 0x040700) /* Do not move this to the XML file, Qt before 4.7 will choke on it */ ui->addressIn_SM->setPlaceholderText(tr("Enter a KrustyCoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)")); ui->signatureOut_SM->setPlaceholderText(tr("Click \"Sign Message\" to generate signature")); ui->addressIn_VM->setPlaceholderText(tr("Enter a KrustyCoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)")); ui->signatureIn_VM->setPlaceholderText(tr("Enter KrustyCoin signature")); #endif GUIUtil::setupAddressWidget(ui->addressIn_SM, this); GUIUtil::setupAddressWidget(ui->addressIn_VM, this); ui->addressIn_SM->installEventFilter(this); ui->messageIn_SM->installEventFilter(this); ui->signatureOut_SM->installEventFilter(this); ui->addressIn_VM->installEventFilter(this); ui->messageIn_VM->installEventFilter(this); ui->signatureIn_VM->installEventFilter(this); ui->signatureOut_SM->setFont(GUIUtil::bitcoinAddressFont()); ui->signatureIn_VM->setFont(GUIUtil::bitcoinAddressFont()); } SignVerifyMessageDialog::~SignVerifyMessageDialog() { delete ui; } void SignVerifyMessageDialog::setModel(WalletModel *model) { this->model = model; } void SignVerifyMessageDialog::setAddress_SM(const QString &address) { ui->addressIn_SM->setText(address); ui->messageIn_SM->setFocus(); } void SignVerifyMessageDialog::setAddress_VM(const QString &address) { ui->addressIn_VM->setText(address); ui->messageIn_VM->setFocus(); } void SignVerifyMessageDialog::showTab_SM(bool fShow) { ui->tabWidget->setCurrentIndex(0); if (fShow) this->show(); } void SignVerifyMessageDialog::showTab_VM(bool fShow) { ui->tabWidget->setCurrentIndex(1); if (fShow) this->show(); } void SignVerifyMessageDialog::on_addressBookButton_SM_clicked() { if (model && model->getAddressTableModel()) { AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::ReceivingTab, this); dlg.setModel(model->getAddressTableModel()); if (dlg.exec()) { setAddress_SM(dlg.getReturnValue()); } } } void SignVerifyMessageDialog::on_pasteButton_SM_clicked() { setAddress_SM(QApplication::clipboard()->text()); } void SignVerifyMessageDialog::on_signMessageButton_SM_clicked() { /* Clear old signature to ensure users don't get confused on error with an old signature displayed */ ui->signatureOut_SM->clear(); CBitcoinAddress addr(ui->addressIn_SM->text().toStdString()); if (!addr.IsValid()) { ui->addressIn_SM->setValid(false); ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again.")); return; } CKeyID keyID; if (!addr.GetKeyID(keyID)) { ui->addressIn_SM->setValid(false); ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again.")); return; } WalletModel::UnlockContext ctx(model->requestUnlock()); if (!ctx.isValid()) { ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("Wallet unlock was cancelled.")); return; } CKey key; if (!pwalletMain->GetKey(keyID, key)) { ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("Private key for the entered address is not available.")); return; } CDataStream ss(SER_GETHASH, 0); ss << strMessageMagic; ss << ui->messageIn_SM->document()->toPlainText().toStdString(); std::vector<unsigned char> vchSig; if (!key.SignCompact(Hash(ss.begin(), ss.end()), vchSig)) { ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signing failed.") + QString("</nobr>")); return; } ui->statusLabel_SM->setStyleSheet("QLabel { color: green; }"); ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signed.") + QString("</nobr>")); ui->signatureOut_SM->setText(QString::fromStdString(EncodeBase64(&vchSig[0], vchSig.size()))); } void SignVerifyMessageDialog::on_copySignatureButton_SM_clicked() { QApplication::clipboard()->setText(ui->signatureOut_SM->text()); } void SignVerifyMessageDialog::on_clearButton_SM_clicked() { ui->addressIn_SM->clear(); ui->messageIn_SM->clear(); ui->signatureOut_SM->clear(); ui->statusLabel_SM->clear(); ui->addressIn_SM->setFocus(); } void SignVerifyMessageDialog::on_addressBookButton_VM_clicked() { if (model && model->getAddressTableModel()) { AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this); dlg.setModel(model->getAddressTableModel()); if (dlg.exec()) { setAddress_VM(dlg.getReturnValue()); } } } void SignVerifyMessageDialog::on_verifyMessageButton_VM_clicked() { CBitcoinAddress addr(ui->addressIn_VM->text().toStdString()); if (!addr.IsValid()) { ui->addressIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again.")); return; } CKeyID keyID; if (!addr.GetKeyID(keyID)) { ui->addressIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again.")); return; } bool fInvalid = false; std::vector<unsigned char> vchSig = DecodeBase64(ui->signatureIn_VM->text().toStdString().c_str(), &fInvalid); if (fInvalid) { ui->signatureIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(tr("The signature could not be decoded.") + QString(" ") + tr("Please check the signature and try again.")); return; } CDataStream ss(SER_GETHASH, 0); ss << strMessageMagic; ss << ui->messageIn_VM->document()->toPlainText().toStdString(); CPubKey pubkey; if (!pubkey.RecoverCompact(Hash(ss.begin(), ss.end()), vchSig)) { ui->signatureIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(tr("The signature did not match the message digest.") + QString(" ") + tr("Please check the signature and try again.")); return; } if (!(CBitcoinAddress(pubkey.GetID()) == addr)) { ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verification failed.") + QString("</nobr>")); return; } ui->statusLabel_VM->setStyleSheet("QLabel { color: green; }"); ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verified.") + QString("</nobr>")); } void SignVerifyMessageDialog::on_clearButton_VM_clicked() { ui->addressIn_VM->clear(); ui->signatureIn_VM->clear(); ui->messageIn_VM->clear(); ui->statusLabel_VM->clear(); ui->addressIn_VM->setFocus(); } bool SignVerifyMessageDialog::eventFilter(QObject *object, QEvent *event) { if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::FocusIn) { if (ui->tabWidget->currentIndex() == 0) { /* Clear status message on focus change */ ui->statusLabel_SM->clear(); /* Select generated signature */ if (object == ui->signatureOut_SM) { ui->signatureOut_SM->selectAll(); return true; } } else if (ui->tabWidget->currentIndex() == 1) { /* Clear status message on focus change */ ui->statusLabel_VM->clear(); } } return QDialog::eventFilter(object, event); }
//------------------------------------------------------------ // snakeoil (c) Alexis Constantin Link // Distributed under the MIT license //------------------------------------------------------------ #ifndef _SNAKEOIL_COLLIDE_2D_COLLISION_CIRCLE_LINE_HPP_ #define _SNAKEOIL_COLLIDE_2D_COLLISION_CIRCLE_LINE_HPP_ #include "../../typedefs.h" #include "../bounds/circle.hpp" #include <snakeoil/math/vector/vector2.hpp> #include <snakeoil/math/primitive/2d/ray_line_intersect.hpp> namespace so_collide { namespace so_2d { template< typename type_t > class circle_line_collision { public: typedef so_collide::so_2d::circle< type_t > circle_t ; typedef circle_t const & circle_cref_t ; typedef so_math::so_2d::ray< type_t > ray_t ; typedef ray_t const & ray_cref_t ; typedef so_math::so_2d::line< type_t > line_t ; typedef line_t const & line_cref_t ; typedef so_math::vector2< type_t > vec2_t ; typedef vec2_t const & vec2_cref_t ; public: /// @note /// if t_on_ray < 0, the result is invalid. struct collision_result { collision_result( vec2_cref_t corrected, vec2_cref_t poc, type_t t_ ) : corrected_position(corrected), point_of_collision(poc), t_on_ray(t_){} /// the corrected circle in case of penetration. vec2_t corrected_position ; /// point of collision of circle with the line. vec2_t point_of_collision ; /// t times the ray of movement where the /// circle hits the line. /// if < 0, invalid result type_t t_on_ray ; }; public: /// collide a circle c on the ray of movement r on the line l. static collision_result collide( circle_cref_t c, ray_cref_t r, line_cref_t l ) { const type_t at = c.get_radius() ; const vec2_t n = l.get_normal() ; if( n.dot(r.get_direction()) > type_t(0) ) return collision_result( vec2f_t(), vec2f_t(), type_t(-1) ) ; const type_t t_at_d = so_math::so_2d::ray_line_intersection<type_t>::intersect( at, r, l ) ; /// is the point on distance d from line l. const vec2_t pod = r.point_at( t_at_d ) ; /// is the point on the line in direction -n from pod. /// i.e. the point of collision. const vec2_t poc = pod - n * at ; return collision_result( pod, poc, t_at_d ) ; } }; } } #endif
template<class T> CompactSoaPool<T>::CompactSoaPool(Scope& a, uint size) : m_pool(a,size) , m_map(a,size) , m_data(a,size) { } template<class T> typename CompactSoaPool<T>::Proxy CompactSoaPool<T>::operator[](uint handle) { eiDEBUG( m_pool.Dbg_ValidateIndex(handle) ); uint physical = m_map.ToPhysical(handle); return m_data[physical]; } template<class T> void CompactSoaPool<T>::Set( uint handle, const T& tuple ) { eiDEBUG( m_pool.Dbg_ValidateIndex(handle) ); uint physical = m_map.ToPhysical(handle); m_data.Set( physical, tuple ); } template<class T> void CompactSoaPool<T>::Get( uint handle, T& tuple ) const { eiDEBUG( m_pool.Dbg_ValidateIndex(handle) ); uint physical = m_map.ToPhysical(handle); m_data.Get( physical, tuple ); } template<class T> int CompactSoaPool<T>::Alloc(const T& tuple) { int handle = m_pool.Alloc(); if( handle < 0 ) return -1; uint physical = m_map.AllocHandleToPhysical(handle); m_data.Set( physical, tuple ); return handle; } template<class T> int CompactSoaPool<T>::Alloc() { int handle = m_pool.Alloc(); if( handle < 0 ) return -1; m_map.AllocHandleToPhysical(handle); return handle; } template<class T> void CompactSoaPool<T>::Release( int handle ) { eiDEBUG( m_pool.Dbg_ValidateIndex(handle) ); m_pool.Release( handle ); HandleMap::MoveCmd move = m_map.EraseHandle( handle ); if( move.to != move.from ) { T temp; m_data.Get( move.from, temp ); m_data.Set( move.to, temp ); eiDEBUG( memset(&temp, 0xfefefefe, sizeof(T)) ); eiDEBUG( m_data.Set( move.from, temp ) ); } } template<class T> void CompactSoaPool<T>::Clear() { m_map.Clear(Capacity()); m_pool.Clear(); }
// RUN: %dexter -- -fno-unroll-loops int lul(int i, int other) { volatile int foo = i; return foo + other; } int somearray[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }; int main() { int sum = 0; int *ptr1 = &somearray[0]; int *ptr2 = &somearray[1]; int i = 0; for (i = 0; i < 10; i++, ptr1++, ptr2++) { sum += lul(*ptr1, *ptr2); // DexExpectStepOrder(1, 3, 5, 7, 9, 11) if (i > 4) // DexExpectStepOrder(2, 4, 6, 8, 10, 12) break; } i += *ptr1; i += *ptr2; sum += i; return sum; } // With *gdb*, each loop iteration (save the first) only features the if // condition, which is deeply misleading. // Not clear if this is LLVM or GDB though, because lldb seems to do ok // DexExpectStepKind('VERTICAL_BACKWARD', 5) // DexExpectStepKind('FUNC', 13) // DexExpectStepKind('FUNC_EXTERNAL', 0)
// *************************************************************************** // TcpSocketEngine_p.cpp (c) 2011 Derek Barnett // Marth Lab, Department of Biology, Boston College // --------------------------------------------------------------------------- // Last modified: 8 December 2011 (DB) // --------------------------------------------------------------------------- // Provides low-level implementation of TCP I/O // *************************************************************************** // N.B. - this file contains the top-level, platform-independent logic. "Native" methods // are called as needed from the TcpSocketEngine_<X>.cpp files. Selection of the proper // native method file should have been handled at build-time by CMake. #include "api/internal/io/TcpSocketEngine_p.h" #include "api/internal/io/HostInfo_p.h" #include <cstddef> using namespace BamTools; using namespace BamTools::Internal; TcpSocketEngine::TcpSocketEngine() : m_socketDescriptor(-1) // , m_localPort(0) , m_remotePort(0) , m_socketError(TcpSocket::UnknownSocketError) , m_socketState(TcpSocket::UnconnectedState) {} TcpSocketEngine::~TcpSocketEngine() { Close(); } void TcpSocketEngine::Close() { // close socket if we have valid FD if (m_socketDescriptor != -1) { nativeClose(); m_socketDescriptor = -1; } // reset state m_socketState = TcpSocket::UnconnectedState; // m_localAddress.Clear(); m_remoteAddress.Clear(); // m_localPort = 0; m_remotePort = 0; } bool TcpSocketEngine::Connect(const HostAddress& address, const uint16_t port) { // return failure if invalid FD or already connected if (!IsValid() || (m_socketState == TcpSocket::ConnectedState)) { // TODO: set error string return false; } // attempt to connect to host address on requested port if (!nativeConnect(address, port)) { // TODO: set error string return false; } // if successful, store remote host address port & return success // TODO: (later) fetch proxied remote & local host/port here m_remoteAddress = address; m_remotePort = port; return true; } std::string TcpSocketEngine::GetErrorString() const { return m_errorString; } //HostAddress TcpSocketEngine::GetLocalAddress() const { // return m_localAddress; //} //uint16_t TcpSocketEngine::GetLocalPort() const { // return m_localPort; //} HostAddress TcpSocketEngine::GetRemoteAddress() const { return m_remoteAddress; } uint16_t TcpSocketEngine::GetRemotePort() const { return m_remotePort; } int TcpSocketEngine::GetSocketDescriptor() const { return m_socketDescriptor; } TcpSocket::SocketError TcpSocketEngine::GetSocketError() { return m_socketError; } TcpSocket::SocketState TcpSocketEngine::GetSocketState() { return m_socketState; } bool TcpSocketEngine::Initialize(HostAddress::NetworkProtocol protocol) { // close current socket if we have one open if (IsValid()) Close(); // attempt to create new socket return nativeCreateSocket(protocol); } bool TcpSocketEngine::IsValid() const { return (m_socketDescriptor != -1); } int64_t TcpSocketEngine::NumBytesAvailable() const { // return 0 if socket FD is invalid if (!IsValid()) { // TODO: set error string return -1; } // otherwise check socket to see how much is ready return nativeNumBytesAvailable(); } int64_t TcpSocketEngine::Read(char* dest, std::size_t max) { // return failure if can't read if (!IsValid() || (m_socketState != TcpSocket::ConnectedState)) return -1; // otherwise return number of bytes read return nativeRead(dest, max); } bool TcpSocketEngine::WaitForRead(int msec, bool* timedOut) { // reset timedOut flag *timedOut = false; // need to wait for our socket to be ready to read const int ret = nativeSelect(msec, true); // if timed out if (ret == 0) { *timedOut = true; m_socketError = TcpSocket::SocketTimeoutError; m_errorString = "socket timed out"; } // return if any sockets available for reading return (ret > 0); } bool TcpSocketEngine::WaitForWrite(int msec, bool* timedOut) { // reset timedOut flag *timedOut = false; // need to wait for our socket to be ready to write const int ret = nativeSelect(msec, false); // if timed out if (ret == 0) { *timedOut = true; m_socketError = TcpSocket::SocketTimeoutError; m_errorString = "socket timed out"; } // return if any sockets available for reading return (ret > 0); } int64_t TcpSocketEngine::Write(const char* data, std::size_t length) { // return failure if can't write if (!IsValid() || (m_socketState != TcpSocket::ConnectedState)) { // TODO: set error string return -1; } // otherwise return number of bytes written return nativeWrite(data, length); }
#if defined(_DEBUG) || defined(DEBUG) #include "sys/sock.h" #include "http-client.h" static void http_client_test_onreply(void* param, int code) { http_client_t* http = (http_client_t*)param; if(0 == code) { const char* server = http_client_get_header(http, "Server"); if(server) printf("http server: %s\n", server); } else { printf("http server reply error: %d\n", code); } } extern "C" void http_client_test(void) { struct http_header_t headers[3]; headers[0].name = "User-Agent"; headers[0].value = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0"; headers[1].name = "Accept-Language"; headers[1].value = "en-US,en;q=0.5"; headers[2].name = "Connection"; headers[2].value = "keep-alive"; socket_init(); http_client_t *http = http_client_create("www.baidu.com", 80, 1); assert(0 == http_client_get(http, "/", headers, sizeof(headers) / sizeof(headers[0]), http_client_test_onreply, http)); assert(0 == http_client_get(http, "/img/bdlogo.png", headers, sizeof(headers)/sizeof(headers[0]), http_client_test_onreply, http)); assert(0 == http_client_get(http, "/", headers, sizeof(headers)/sizeof(headers[0]), http_client_test_onreply, http)); assert(0 == http_client_get(http, "/", headers, sizeof(headers)/sizeof(headers[0]), http_client_test_onreply, http)); http_client_destroy(http); socket_cleanup(); } #endif
//================================================================================================= /*! // \file src/mathtest/smatsmatmult/SCbMCa.cpp // \brief Source file for the SCbMCa sparse matrix/sparse matrix multiplication math test // // Copyright (C) 2012-2019 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. Redistribution and use in source and binary // forms, with or without modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // 3. Neither the names of the Blaze development group nor the names of its contributors // may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <cstdlib> #include <iostream> #include <blaze/math/CompressedMatrix.h> #include <blaze/math/SymmetricMatrix.h> #include <blazetest/mathtest/Creator.h> #include <blazetest/mathtest/smatsmatmult/OperationTest.h> #include <blazetest/system/MathTest.h> #ifdef BLAZE_USE_HPX_THREADS # include <hpx/hpx_main.hpp> #endif //================================================================================================= // // MAIN FUNCTION // //================================================================================================= //************************************************************************************************* int main() { std::cout << " Running 'SCbMCa'..." << std::endl; using blazetest::mathtest::TypeA; using blazetest::mathtest::TypeB; try { // Matrix type definitions using SCb = blaze::SymmetricMatrix< blaze::CompressedMatrix<TypeB> >; using MCa = blaze::CompressedMatrix<TypeA>; // Creator type definitions using CSCb = blazetest::Creator<SCb>; using CMCa = blazetest::Creator<MCa>; // Running tests with small matrices for( size_t i=0UL; i<=6UL; ++i ) { for( size_t j=0UL; j<=6UL; ++j ) { RUN_SMATSMATMULT_OPERATION_TEST( CSCb( i, 0UL ), CMCa( i, j, 0UL ) ); RUN_SMATSMATMULT_OPERATION_TEST( CSCb( i, 0UL ), CMCa( i, j, 0.3*i*j ) ); RUN_SMATSMATMULT_OPERATION_TEST( CSCb( i, 0UL ), CMCa( i, j, i*j ) ); RUN_SMATSMATMULT_OPERATION_TEST( CSCb( i, 0.3*i*i ), CMCa( i, j, 0UL ) ); RUN_SMATSMATMULT_OPERATION_TEST( CSCb( i, 0.3*i*i ), CMCa( i, j, 0.3*i*j ) ); RUN_SMATSMATMULT_OPERATION_TEST( CSCb( i, 0.3*i*i ), CMCa( i, j, i*j ) ); RUN_SMATSMATMULT_OPERATION_TEST( CSCb( i, i*i ), CMCa( i, j, 0UL ) ); RUN_SMATSMATMULT_OPERATION_TEST( CSCb( i, i*i ), CMCa( i, j, 0.3*i*j ) ); RUN_SMATSMATMULT_OPERATION_TEST( CSCb( i, i*i ), CMCa( i, j, i*j ) ); } } // Running tests with large matrices RUN_SMATSMATMULT_OPERATION_TEST( CSCb( 15UL, 7UL ), CMCa( 15UL, 37UL, 7UL ) ); RUN_SMATSMATMULT_OPERATION_TEST( CSCb( 37UL, 7UL ), CMCa( 37UL, 37UL, 7UL ) ); RUN_SMATSMATMULT_OPERATION_TEST( CSCb( 63UL, 13UL ), CMCa( 63UL, 37UL, 13UL ) ); RUN_SMATSMATMULT_OPERATION_TEST( CSCb( 16UL, 8UL ), CMCa( 16UL, 32UL, 8UL ) ); RUN_SMATSMATMULT_OPERATION_TEST( CSCb( 32UL, 8UL ), CMCa( 32UL, 32UL, 8UL ) ); RUN_SMATSMATMULT_OPERATION_TEST( CSCb( 64UL, 16UL ), CMCa( 64UL, 32UL, 16UL ) ); } catch( std::exception& ex ) { std::cerr << "\n\n ERROR DETECTED during sparse matrix/sparse matrix multiplication:\n" << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } //*************************************************************************************************
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The PlanBcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "sync.h" #include "clientversion.h" #include "util.h" #include "warnings.h" CCriticalSection cs_warnings; std::string strMiscWarning; bool fLargeWorkForkFound = false; bool fLargeWorkInvalidChainFound = false; void SetMiscWarning(const std::string& strWarning) { LOCK(cs_warnings); strMiscWarning = strWarning; } void SetfLargeWorkForkFound(bool flag) { LOCK(cs_warnings); fLargeWorkForkFound = flag; } bool GetfLargeWorkForkFound() { LOCK(cs_warnings); return fLargeWorkForkFound; } void SetfLargeWorkInvalidChainFound(bool flag) { LOCK(cs_warnings); fLargeWorkInvalidChainFound = flag; } bool GetfLargeWorkInvalidChainFound() { LOCK(cs_warnings); return fLargeWorkInvalidChainFound; } std::string GetWarnings(const std::string& strFor) { std::string strStatusBar; std::string strRPC; std::string strGUI; const std::string uiAlertSeperator = "<hr />"; LOCK(cs_warnings); if (!CLIENT_VERSION_IS_RELEASE) { strStatusBar = "This is a pre-release test build - use at your own risk - do not use for mining or merchant applications"; strGUI = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications"); } if (GetBoolArg("-testsafemode", DEFAULT_TESTSAFEMODE)) strStatusBar = strRPC = strGUI = "testsafemode enabled"; // Misc warnings like out of disk space and clock is wrong if (strMiscWarning != "") { strStatusBar = strMiscWarning; strGUI += (strGUI.empty() ? "" : uiAlertSeperator) + strMiscWarning; } if (fLargeWorkForkFound) { strStatusBar = strRPC = "Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues."; strGUI += (strGUI.empty() ? "" : uiAlertSeperator) + _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues."); } else if (fLargeWorkInvalidChainFound) { strStatusBar = strRPC = "Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade."; strGUI += (strGUI.empty() ? "" : uiAlertSeperator) + _("Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade."); } if (strFor == "gui") return strGUI; else if (strFor == "statusbar") return strStatusBar; else if (strFor == "rpc") return strRPC; assert(!"GetWarnings(): invalid parameter"); return "error"; }
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2015 Couchbase, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "executor.h" #include "task.h" #include <algorithm> #include <iostream> Executor::~Executor() { std::unique_lock<std::mutex> lock(mutex); shutdown = true; idlecond.notify_all(); // Wait until the thread stops while (running) { shutdowncond.wait(lock); } waitForState(Couchbase::ThreadState::Zombie); } void Executor::run() { running = true; // According to the spec we have to call setRunning (that'll notify the // the thread calling start()) setRunning(); while (true) { std::unique_lock<std::mutex> lock(mutex); while (!shutdown && runq.empty()) { idlecond.wait(lock); } if (shutdown) { break; } auto task = runq.front(); runq.pop(); // Release the lock so that others may schedule new events lock.unlock(); // Lock the task so no one else can touch it and we won't // have any races.. task->getMutex().lock(); if (task->execute() == Task::Status::Finished) { // Unlock the mutex, we're not going to use this anymore // By not holding the mutex in notifyExecutionComplete // we won't get any warnings from ThreadSanitizer by // locking in oposite order (typically you hold the thread // mutex when you create a task, and then aqcuire the task // lock. This time we aqcuired the task mutex first and the // notification method will try to grab the thread lock later // on.. task->getMutex().unlock(); // tell the task that the executor consider it done with the // task and will no longer operate on it. task->notifyExecutionComplete(); } else { // put it in the wait-queue.. We need the lock for the waitq lock.lock(); waitq[task.get()] = task; lock.unlock(); // Release the task lock so that the backend thread may start // using it task->getMutex().unlock(); } } // move all items in future-queue out of the wait-queue for (const auto& ftask : futureq) { std::lock_guard<std::mutex> guard(ftask.first->getMutex()); makeRunnable(ftask.first); } // wait for the wait-queue to drain... std::unique_lock<std::mutex> lock(mutex); while (!waitq.empty()) { idlecond.wait(lock); } running = false; shutdowncond.notify_all(); } void Executor::schedule(const std::shared_ptr<Task>& task, bool runnable) { std::lock_guard<std::mutex> guard(mutex); task->setExecutor(this); if (runnable) { runq.push(task); idlecond.notify_all(); } else { waitq[task.get()] = task; } } void Executor::makeRunnable(Task* task) { if (task->getMutex().try_lock()) { task->getMutex().unlock(); throw std::logic_error( "The mutex should be held when trying to reschedule a event"); } std::lock_guard<std::mutex> guard(mutex); auto iter = waitq.find(task); if (iter == waitq.end()) { throw std::runtime_error("Internal error object is not in the waitq"); } runq.push(iter->second); waitq.erase(iter); idlecond.notify_all(); } void Executor::makeRunnable(Task& task, ProcessClock::time_point time) { if (task.getMutex().try_lock()) { task.getMutex().unlock(); throw std::logic_error( "The mutex should be held when trying to reschedule a event"); } std::lock_guard<std::mutex> guard(mutex); futureq.emplace_back(&task, time); } void Executor::clockTick() { std::vector<Task*> wakeableTasks; { std::lock_guard<std::mutex> guard(mutex); auto now = clock.now(); futureq.erase( std::remove_if(futureq.begin(), futureq.end(), [&now, &wakeableTasks](FutureTask& ftask) { if (ftask.second <= now) { wakeableTasks.push_back(ftask.first); return true; } return false; }), futureq.end()); } // Need to do this without holding the executor lock to avoid lock inversion for (auto* task : wakeableTasks) { std::lock_guard<std::mutex> guard(task->getMutex()); makeRunnable(task); } } size_t Executor::waitqSize() const { std::lock_guard<std::mutex> guard(mutex); return waitq.size(); } size_t Executor::runqSize() const { std::lock_guard<std::mutex> guard(mutex); return runq.size(); } size_t Executor::futureqSize() const { std::lock_guard<std::mutex> guard(mutex); return futureq.size(); } std::unique_ptr<Executor> createWorker(cb::ProcessClockSource& clock) { auto* executor = new Executor(clock); executor->start(); return std::unique_ptr<Executor>(executor); }
#include<vector> #include<algorithm> #include<iostream> using namespace std; class Solution { public: int findMinMoves(vector<int>& machines) { int len = machines.size(); int sum = 0; for (auto &num : machines) sum += num; if (sum % len != 0) return -1; int avg = sum / len; int left[len]; fill(left, left + len, 0); int right[len]; fill(right, right + len, 0); // 两端的两个洗衣机向一个传递一个方向, 需要提前处理, 其他洗衣机都有两个左右两个方向的输入、输出 right[0] = machines[0] - avg; left[len - 1] = machines[len - 1] - avg; for (int i = 1; i < len - 1; i++) { left[i] = -right[i-1]; right[i] = machines[i] - avg - left[i]; } int res = 0; for (int i = 0; i < len; i++) /* 计算输出净值的最大值 */ { int curMax = 0; if (left[i] >= 0) curMax += left[i]; if (right[i] >= 0) curMax += right[i]; res = max(res, curMax); } return res; } }; // Test int main() { Solution sol; vector<int> machines = {3, 8, 4}; auto res = sol.findMinMoves(machines); cout << res << endl; return 0; }
#include <_gm_msg_gmcall_list_response_zocl.hpp> START_ATF_NAMESPACE void _gm_msg_gmcall_list_response_zocl::Init() { using org_ptr = void (WINAPIV*)(struct _gm_msg_gmcall_list_response_zocl*); (org_ptr(0x1402ab6a0L))(this); }; void _gm_msg_gmcall_list_response_zocl::_call_node::Init() { using org_ptr = void (WINAPIV*)(struct _gm_msg_gmcall_list_response_zocl::_call_node*); (org_ptr(0x1402ab760L))(this); }; END_ATF_NAMESPACE
// See the file "COPYING" in the main distribution directory for copyright. #include "Component.h" #include "Manager.h" #include "../Desc.h" #include "../util.h" namespace zeek::logging { Component::Component(const std::string& name, factory_callback arg_factory) : plugin::Component(plugin::component::WRITER, name) { factory = arg_factory; } void Component::Initialize() { InitializeTag(); log_mgr->RegisterComponent(this, "WRITER_"); } Component::~Component() { } void Component::DoDescribe(ODesc* d) const { d->Add("Log::WRITER_"); d->Add(CanonicalName()); } } // namespace zeek::logging
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE590_Free_Memory_Not_on_Heap__delete_struct_static_10.cpp Label Definition File: CWE590_Free_Memory_Not_on_Heap__delete.nonpointer.label.xml Template File: sources-sink-10.tmpl.cpp */ /* * @description * CWE: 590 Free Memory Not on Heap * BadSource: static Data buffer is declared static on the stack * GoodSource: Allocate memory on the heap * Sink: * BadSink : Print then free data * Flow Variant: 10 Control flow: if(globalTrue) and if(globalFalse) * * */ #include "std_testcase.h" #include <wchar.h> namespace CWE590_Free_Memory_Not_on_Heap__delete_struct_static_10 { #ifndef OMITBAD void bad() { twoIntsStruct * data; data = NULL; /* Initialize data */ if(globalTrue) { { /* FLAW: data is allocated on the stack and deallocated in the BadSink */ static twoIntsStruct dataBuffer; dataBuffer.intOne = 1; dataBuffer.intTwo = 1; data = &dataBuffer; } } printStructLine(data); /* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */ delete data; } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B1() - use goodsource and badsink by changing the globalTrue to globalFalse */ static void goodG2B1() { twoIntsStruct * data; data = NULL; /* Initialize data */ if(globalFalse) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { { /* FIX: data is allocated on the heap and deallocated in the BadSink */ twoIntsStruct * dataBuffer = new twoIntsStruct; dataBuffer->intOne = 2; dataBuffer->intTwo = 2; data = dataBuffer; } } printStructLine(data); /* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */ delete data; } /* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */ static void goodG2B2() { twoIntsStruct * data; data = NULL; /* Initialize data */ if(globalTrue) { { /* FIX: data is allocated on the heap and deallocated in the BadSink */ twoIntsStruct * dataBuffer = new twoIntsStruct; dataBuffer->intOne = 2; dataBuffer->intTwo = 2; data = dataBuffer; } } printStructLine(data); /* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */ delete data; } void good() { goodG2B1(); goodG2B2(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE590_Free_Memory_Not_on_Heap__delete_struct_static_10; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
/* * Copyright 2000-2021, ArmyKnife Team. All rights reserved. * Distributed under the terms of the MIT License. */ #include "musicbrainzquery.h" #include <exception> #include <Debug.h> #include <musicbrainz5/Artist.h> #include <musicbrainz5/ArtistCredit.h> #include <musicbrainz5/Medium.h> #include <musicbrainz5/NameCredit.h> #include <musicbrainz5/NameCreditList.h> #include <musicbrainz5/Query.h> #include <musicbrainz5/Recording.h> #include <musicbrainz5/Release.h> #include <musicbrainz5/Track.h> #include "appdefs.h" MusicBrainzQuery::MusicBrainzQuery(Queryable original) : Query(), m_total_count(-1), m_next_count(0) { PRINT(("MusicBrainzQuery::MusicBrainzQuery(Queryable)\n")); if (original.Artist() != NULL) m_query_string << "artist:\"" << original.Artist() << "\" AND "; if (original.Album() != NULL) m_query_string << "release:\"" << original.Album() << "\" AND "; if (original.Title() != NULL) m_query_string << "recording:\"" << original.Title() << "\" AND "; if (original.Year() != NULL) m_query_string << "date:\"" << original.Year() << "\" AND "; if (original.Comment() != NULL) m_query_string << "comment:\"" << original.Comment() << "\" AND "; if (original.Track() != NULL) m_query_string << "tnum:\"" << original.Track() << "\" AND "; // Get rid of the final " AND " if (m_query_string.Length() > 5); m_query_string.Truncate(m_query_string.Length() - 5); } MusicBrainzQuery::~MusicBrainzQuery() { PRINT(("MusicBrainzQuery::~MusicBrainzQuery()\n")); } BString MakeArtist(MusicBrainz5::CArtistCredit* credit) { MusicBrainz5::CNameCreditList* list = credit->NameCreditList(); BString res; for (int32 i = 0; i < list->NumItems(); i++) { MusicBrainz5::CNameCredit* single = list->Item(i); res << single->Artist()->Name().c_str() << single->JoinPhrase().c_str(); } return res; } status_t MusicBrainzQuery::RefillBuffer() { PRINT(("MusicBrainzQuery::RefillBuffer()\n")); m_buffer.erase(m_buffer.begin(), m_buffer.end()); if (m_total_count == m_next_count) return B_ERROR; MusicBrainz5::CQuery query("ArmyKnife " VERSION " for Haiku (https://github.com/HaikuArchives/ArmyKnife)"); try { MusicBrainz5::CQuery::tParamMap params; params["query"] = m_query_string.String(); BString c1; c1 << k_fetch_size; params["limit"] = c1.String(); BString c2; c2 << m_next_count; params["offset"] = c2.String(); MusicBrainz5::CMetadata result = query.Query("recording", "", "", params); MusicBrainz5::CRecordingList* results = result.RecordingList(); if (results == NULL) return B_ERROR; m_total_count = results->Count(); m_next_count += results->NumItems(); for (int32 i = 0; i < results->NumItems(); i++) { MusicBrainz5::CRecording* recording = results->Item(i); Queryable templ; templ.SetTitle(recording->Title().c_str()); templ.SetComment(recording->Disambiguation().c_str()); templ.SetArtist(MakeArtist(recording->ArtistCredit()).String()); MusicBrainz5::CReleaseList* releases = recording->ReleaseList(); if (releases == NULL) continue; for (int32 j = 0; j < releases->NumItems(); j++) { MusicBrainz5::CRelease* release = releases->Item(j); Queryable toAdd = templ; // Copy toAdd.SetAlbum(release->Title().c_str()); toAdd.SetYear(release->Date().c_str()); toAdd.SetTrack(release ->MediumList()->Item(0) ->TrackList()->Item(0) ->Number().c_str()); m_buffer.push_back(toAdd); } } return m_buffer.size() > 0 ? B_OK : B_ERROR; } catch (std::exception& ex) { std::cout << "An exception occurred: " << ex.what() << std::endl; // Check whether there was an actual error or simply throttling return query.LastHTTPCode() == 503 ? B_BUSY : B_ERROR; } }
//----------------------------------------------------------------------------- // // File: uniqid.inl // Copyright (C) 1994-1997 Microsoft Corporation // All rights reserved. // // Inline function definitions for the Espresso Unique ID. This file should // ONLY be included by uniqid.h. // //----------------------------------------------------------------------------- inline const DBID& CLocUniqueId::GetParentId(void) const { return m_dbid; } inline const CLocTypeId & CLocUniqueId::GetTypeId(void) const { return m_tid; } inline const CLocResId & CLocUniqueId::GetResId(void) const { return m_rid; } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // // Returns the parent ID for the item. This portion of the ID is set by the // parser. // //----------------------------------------------------------------------------- inline DBID& CLocUniqueId::GetParentId(void) { return m_dbid; } inline CLocTypeId & CLocUniqueId::GetTypeId(void) { return m_tid; } inline CLocResId & CLocUniqueId::GetResId(void) { return m_rid; } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // // Comapre two ID's. // //----------------------------------------------------------------------------- inline int // Zero if different CLocUniqueId::operator==( const CLocUniqueId &uidOther) // ID to compare to. const { return IsEqualTo(uidOther); } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // // Compare two ID's // //----------------------------------------------------------------------------- inline int // Zero if identical CLocUniqueId::operator!=( const CLocUniqueId &uidOther) // ID to compare to. const { return !IsEqualTo(uidOther); } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // // Sets the Parent ID component of the ID. // //----------------------------------------------------------------------------- inline void CLocUniqueId::SetParentId( const DBID& dbidNewId) // New Parent ID { m_dbid = dbidNewId; }
/* Copyright The Overlaybd Authors 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 "thread-pool.h" #include "../alog.h" namespace photon { TPControl *ThreadPoolBase::thread_create_ex(thread_entry start, void *arg, bool joinable) { auto pCtrl = B::get(); pCtrl->joinable = joinable; pCtrl->start = start; pCtrl->arg = arg; pCtrl->cvar.notify_one(); return pCtrl; } void *ThreadPoolBase::stub(void *arg) { TPControl ctrl; auto th = *(thread **)arg; *(TPControl **)arg = &ctrl; // tell ctor where my `ctrl` is thread_yield_to(th); while (true) { while (!ctrl.start) // wait for `create()` to give me ctrl.cvar.wait_no_lock(); // thread_entry and argument if (ctrl.start == &stub) break; thread_set_local(nullptr); ctrl.start(ctrl.arg); ctrl.cvar.notify_all(); ctrl.start = nullptr; ctrl.pool->put(&ctrl); } if (ctrl.joinable) // wait for being joined ctrl.cvar.wait_no_lock(); return nullptr; } void ThreadPoolBase::join(TPControl *pCtrl) { if (!pCtrl->joinable) LOG_ERROR_RETURN(EINVAL, , "thread is not joinable"); if (pCtrl->start == &stub) // a dying thread { pCtrl->cvar.notify_all(); return; } while (pCtrl->start && pCtrl->start != &stub) pCtrl->cvar.wait_no_lock(); } int ThreadPoolBase::ctor(ThreadPoolBase *pool, TPControl **out) { auto pCtrl = (TPControl *)CURRENT; auto stack_size = (uint64_t)pool->m_reserved; auto th = photon::thread_create(&stub, &pCtrl, stack_size); thread_yield_to(th); assert(pCtrl); *out = pCtrl; pCtrl->th = th; pCtrl->pool = pool; pCtrl->start = nullptr; return 0; } int ThreadPoolBase::dtor(ThreadPoolBase *, TPControl *pCtrl) { pCtrl->start = &stub; pCtrl->cvar.notify_all(); return 0; } } // namespace photon
/* * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/system_wrappers/include/aligned_malloc.h" #include <memory.h> #include <stdlib.h> #ifdef _WIN32 #include <windows.h> #else #include <stdint.h> #endif #include "webrtc/typedefs.h" // Reference on memory alignment: // http://stackoverflow.com/questions/227897/solve-the-memory-alignment-in-c-interview-question-that-stumped-me namespace webrtc { uintptr_t GetRightAlign(uintptr_t start_pos, size_t alignment) { // The pointer should be aligned with |alignment| bytes. The - 1 guarantees // that it is aligned towards the closest higher (right) address. return (start_pos + alignment - 1) & ~(alignment - 1); } // Alignment must be an integer power of two. bool ValidAlignment(size_t alignment) { if (!alignment) { return false; } return (alignment & (alignment - 1)) == 0; } void* GetRightAlign(const void* pointer, size_t alignment) { if (!pointer) { return NULL; } if (!ValidAlignment(alignment)) { return NULL; } uintptr_t start_pos = reinterpret_cast<uintptr_t>(pointer); return reinterpret_cast<void*>(GetRightAlign(start_pos, alignment)); } void* AlignedMalloc(size_t size, size_t alignment) { if (size == 0) { return NULL; } if (!ValidAlignment(alignment)) { return NULL; } // The memory is aligned towards the lowest address that so only // alignment - 1 bytes needs to be allocated. // A pointer to the start of the memory must be stored so that it can be // retreived for deletion, ergo the sizeof(uintptr_t). void* memory_pointer = malloc(size + sizeof(uintptr_t) + alignment - 1); if (memory_pointer == NULL) { return NULL; } // Aligning after the sizeof(uintptr_t) bytes will leave room for the header // in the same memory block. uintptr_t align_start_pos = reinterpret_cast<uintptr_t>(memory_pointer); align_start_pos += sizeof(uintptr_t); uintptr_t aligned_pos = GetRightAlign(align_start_pos, alignment); void* aligned_pointer = reinterpret_cast<void*>(aligned_pos); // Store the address to the beginning of the memory just before the aligned // memory. uintptr_t header_pos = aligned_pos - sizeof(uintptr_t); void* header_pointer = reinterpret_cast<void*>(header_pos); uintptr_t memory_start = reinterpret_cast<uintptr_t>(memory_pointer); memcpy(header_pointer, &memory_start, sizeof(uintptr_t)); return aligned_pointer; } void AlignedFree(void* mem_block) { if (mem_block == NULL) { return; } uintptr_t aligned_pos = reinterpret_cast<uintptr_t>(mem_block); uintptr_t header_pos = aligned_pos - sizeof(uintptr_t); // Read out the address of the AlignedMemory struct from the header. uintptr_t memory_start_pos = *reinterpret_cast<uintptr_t*>(header_pos); void* memory_start = reinterpret_cast<void*>(memory_start_pos); free(memory_start); } } // namespace webrtc
//============================================================================// // // // FluidProp C++ interface // // ----------------------- // // // // The class defined in this file, TFluidProp, is as a wrapper class for // // the IFluidProp_COM interface. TFluidProp hides COM specific details // // like safe arrays (SAFEARRAY) and binary strings (BSTR) in IFluidProp_COM. // // In the TFluidProp class only standard C++ data types are used. This is // // the recommended way working with the FluidProp COM server in C++. // // // // July, 2004, for FluidProp 1 // // January, 2006, for FluidProp 2 // // April, 2007, for FluidProp 2.3 // // November, 2012, for FluidProp 2.5 // // // //============================================================================// #include <iostream> #include "include.h" #include "FluidProp_IF.h" #if defined(__MINGW32__) #include <olectl.h> #endif // Conversion of a binary string BSTR to a string. static inline string ConvertBSTRToString(BSTR BString) { char* tmp_string = _com_util::ConvertBSTRToString(BString); string retval = tmp_string; delete[] tmp_string; return retval; } // Conversion of a string to a binary string BSTR. static inline BSTR ConvertStringToBSTR(string &String) { return _com_util::ConvertStringToBSTR(String.c_str()); } // {F30D147D-1F7C-4092-B481-ADE326A2ECD5} static const GUID CLSID_FluidProp = { 0xF30D147DL, 0x1F7C, 0x4092, { 0xB4, 0x81, 0xAD, 0xE3, 0x26, 0xA2, 0xEC, 0xD5 } }; // {2430EE09-2C1E-4A86-AB62-CB67AEF6E484} static const IID IID_IFluidProp = { 0x2430EE09L, 0x2C1E, 0x4A86, { 0xAB, 0x62, 0xCB, 0x67, 0xAE, 0xF6, 0xE4, 0x84 } }; TFluidProp::TFluidProp() : FluidProp_COM(NULL) { // Init COM CoInitialize(0); // Retrieve class factory interface pointer to our FluidProp COM object HRESULT hr = CoGetClassObject(CLSID_FluidProp, CLSCTX_INPROC_SERVER, 0, IID_IClassFactory, (void**) &ClassFactory); // Have class factory make the object for us - then release factory if (SUCCEEDED(hr)) { HRESULT hr2 = ClassFactory->CreateInstance(0, IID_IFluidProp, (void**) &FluidProp_COM); ClassFactory->Release(); ClassFactory = 0; if (FAILED(hr2)) { if (hr2 == CLASS_E_NOTLICENSED) std::cout << "FluidProp license not valid." << std::endl; std::cout << "Failed to create FluidProp COM object" << std::endl; } } } TFluidProp::~TFluidProp() { // Free FluidProp object if (FluidProp_COM) FluidProp_COM->Release(); // Unitialize COM CoUninitialize(); } bool TFluidProp::IsValid() { return !!FluidProp_COM; } void TFluidProp::CreateObject( string ModelName, string* ErrorMsg) { BSTR BSTR_Model = ConvertStringToBSTR(ModelName); BSTR BSTR_Error; FluidProp_COM->CreateObject(BSTR_Model, &BSTR_Error); SysFreeString(BSTR_Model); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); } void TFluidProp::ReleaseObjects() { FluidProp_COM->ReleaseObjects(); } void TFluidProp::SetFluid( string ModelName, int nComp, string* Comp, double* Conc, string* ErrorMsg) { // Convert model name to binary string BSTR BSTR_Model = ConvertStringToBSTR(ModelName); // Convert character array Comp via binary strings (BSTR) into a SafeArray SAFEARRAY FAR* sa_Comp = SafeArrayCreateVector(VT_BSTR, 1, nComp); for (long i = 1; i <= (long)nComp; i++) { BSTR BSTR_Comp = ConvertStringToBSTR(Comp[i-1]); SafeArrayPutElement(sa_Comp, &i, BSTR_Comp); SysFreeString(BSTR_Comp); } // Convert the double array Conc into a SafeArray SAFEARRAY FAR* sa_Conc = SafeArrayCreateVector(VT_R8, 1, nComp); for (long i = 1; i <= (long)nComp; i++) SafeArrayPutElement(sa_Conc, &i, &Conc[i-1]); // Now load the fluid parameters for the model selected. BSTR BSTR_Error; FluidProp_COM->SetFluid( BSTR_Model, nComp, &sa_Comp, &sa_Conc, &BSTR_Error); SysFreeString(BSTR_Model); SafeArrayDestroy(sa_Comp); SafeArrayDestroy(sa_Conc); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); } void TFluidProp::GetFluid( string* ModelName, int* nComp, string* Comp, double* Conc, bool CompInfo) { // When CompInfo is true, the components and their concentrations in the mixture are returned // instead of the mixture name. long long_nComp = *nComp; // Convert character array Comp via binary strings (BSTR) into a SafeArray // This needs to be done because in the COM interface Comp is an inout argument, // because for out arguments an assumed array size is not allowed... SAFEARRAY FAR* sa_Comp = SafeArrayCreateVector(VT_BSTR, 1, long_nComp); for (long i = 1; i <= long_nComp; i++) { BSTR BSTR_Comp = ConvertStringToBSTR(Comp[i-1]); SafeArrayPutElement(sa_Comp, &i, BSTR_Comp); SysFreeString(BSTR_Comp); } // Convert the double array Conc into a SafeArray // This needs to be done because in the COM interface Conc is an inout argument, // because for out arguments an assumed array size is not allowed... SAFEARRAY FAR* sa_Conc = SafeArrayCreateVector(VT_R8, 1, long_nComp); for (long i = 1; i <= long_nComp; i++) SafeArrayPutElement(sa_Conc, &i, &Conc[i-1]); // Now retrieve the fluid parameters set wit SetFluid string blank = string(" "); BSTR BSTR_Model = ConvertStringToBSTR(blank); if (CompInfo) long_nComp = -1; FluidProp_COM->GetFluid( BSTR_Model, &long_nComp, &sa_Comp, &sa_Conc); // Convert model name from binary string to string string TmpName = ConvertBSTRToString(BSTR_Model); SysFreeString(BSTR_Model); *ModelName = TmpName; // Convert from long to int *nComp = long_nComp; // Put the values in the string array Comp for (long i = 1; i <= long_nComp; i++) { BSTR BSTR_Comp; SafeArrayGetElement(sa_Comp, &i, &BSTR_Comp); Comp[i-1] = ConvertBSTRToString(BSTR_Comp); SysFreeString(BSTR_Comp); } SafeArrayDestroy(sa_Comp); // Put the values in the double array Conc for (long i = 1; i <= long_nComp; i++) SafeArrayGetElement(sa_Conc, &i, &Conc[i-1]); SafeArrayDestroy(sa_Conc); } void TFluidProp::GetFluidNames( string LongShort, string ModelName, int* nFluids, string* FluidNames, string* ErrorMsg) { long long_nFluids; // Get available fluids BSTR BSTR_Model = ConvertStringToBSTR(ModelName); BSTR BSTR_LongShort = ConvertStringToBSTR(LongShort); BSTR BSTR_Error; // Convert character array FluidNames via binary strings (BSTR) into a SafeArray // This needs to be done because in the COM interface FluidNames is an inout argument, // because Visual Basic is not able to deal out arrays... SAFEARRAY* sa_FluidNames = SafeArrayCreateVector(VT_BSTR, 1, 250); FluidProp_COM->GetFluidNames(BSTR_LongShort, BSTR_Model, &long_nFluids, &sa_FluidNames, &BSTR_Error); SysFreeString(BSTR_Model); SysFreeString(BSTR_LongShort); // Retrieve array with components from SafeArray for (long i = 1; i <= long_nFluids; i++) { BSTR BSTR_Fluid; SafeArrayGetElement(sa_FluidNames, &i, &BSTR_Fluid); FluidNames[i-1] = ConvertBSTRToString(BSTR_Fluid); SysFreeString(BSTR_Fluid); } SafeArrayDestroy(sa_FluidNames); *nFluids = long_nFluids; *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); } void TFluidProp::GetCompSet( string ModelName, int* nComps, string* CompSet, string* ErrorMsg) { long long_nComps; // Get available fluids BSTR BSTR_Model = ConvertStringToBSTR(ModelName); BSTR BSTR_Error; // Convert character array CompSet via binary strings (BSTR) into a SafeArray // This needs to be done because in the COM interface CompSet is an inout argument, // because Visual Basic is not able to deal out arrays... SAFEARRAY* sa_CompSet = SafeArrayCreateVector(VT_BSTR, 1, 250); FluidProp_COM->GetCompSet( BSTR_Model, &long_nComps, &sa_CompSet, &BSTR_Error); SysFreeString(BSTR_Model); // Retrieve array with components from SafeArray for (long i = 1; i <= long_nComps; i++) { BSTR BSTR_Comp; SafeArrayGetElement(sa_CompSet, &i, &BSTR_Comp); CompSet[i-1] = ConvertBSTRToString(BSTR_Comp); SysFreeString(BSTR_Comp); } SafeArrayDestroy(sa_CompSet); *nComps = long_nComps; *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); } double TFluidProp::Pressure( string InputSpec, double Input1, double Input2, string* ErrorMsg) { double Output; BSTR BSTR_InputSpec = ConvertStringToBSTR(InputSpec); BSTR BSTR_Error; FluidProp_COM->Pressure( BSTR_InputSpec, Input1, Input2, &Output, &BSTR_Error); SysFreeString(BSTR_InputSpec); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); return Output; } double TFluidProp::Temperature( string InputSpec, double Input1, double Input2, string* ErrorMsg) { double Output; BSTR BSTR_InputSpec = ConvertStringToBSTR(InputSpec); BSTR BSTR_Error; FluidProp_COM->Temperature( BSTR_InputSpec, Input1, Input2, &Output, &BSTR_Error); SysFreeString(BSTR_InputSpec); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); return Output; } double TFluidProp::SpecVolume( string InputSpec, double Input1, double Input2, string* ErrorMsg) { double Output; BSTR BSTR_InputSpec = ConvertStringToBSTR(InputSpec); BSTR BSTR_Error; FluidProp_COM->SpecVolume( BSTR_InputSpec, Input1, Input2, &Output, &BSTR_Error); SysFreeString(BSTR_InputSpec); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); return Output; } double TFluidProp::Density( string InputSpec, double Input1, double Input2, string* ErrorMsg) { double Output; BSTR BSTR_InputSpec = ConvertStringToBSTR(InputSpec); BSTR BSTR_Error; FluidProp_COM->Density( BSTR_InputSpec, Input1, Input2, &Output, &BSTR_Error); SysFreeString(BSTR_InputSpec); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); return Output; } double TFluidProp::Enthalpy( string InputSpec, double Input1, double Input2, string* ErrorMsg) { double Output; BSTR BSTR_InputSpec = ConvertStringToBSTR(InputSpec); BSTR BSTR_Error; FluidProp_COM->Enthalpy( BSTR_InputSpec, Input1, Input2, &Output, &BSTR_Error); SysFreeString(BSTR_InputSpec); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); return Output; } double TFluidProp::Entropy( string InputSpec, double Input1, double Input2, string* ErrorMsg) { double Output; BSTR BSTR_InputSpec = ConvertStringToBSTR(InputSpec); BSTR BSTR_Error; FluidProp_COM->Entropy( BSTR_InputSpec, Input1, Input2, &Output, &BSTR_Error); SysFreeString(BSTR_InputSpec); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); return Output; } double TFluidProp::IntEnergy( string InputSpec, double Input1, double Input2, string* ErrorMsg) { double Output; BSTR BSTR_InputSpec = ConvertStringToBSTR(InputSpec); BSTR BSTR_Error; FluidProp_COM->IntEnergy( BSTR_InputSpec, Input1, Input2, &Output, &BSTR_Error); SysFreeString(BSTR_InputSpec); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); return Output; } double TFluidProp::VaporQual( string InputSpec, double Input1, double Input2, string* ErrorMsg) { double Output; BSTR BSTR_InputSpec = ConvertStringToBSTR(InputSpec); BSTR BSTR_Error; FluidProp_COM->VaporQual( BSTR_InputSpec, Input1, Input2, &Output, &BSTR_Error); SysFreeString(BSTR_InputSpec); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); return Output; } double* TFluidProp::LiquidCmp( string InputSpec, double Input1, double Input2, string* ErrorMsg) { double* Output = new double[20]; BSTR BSTR_InputSpec = ConvertStringToBSTR(InputSpec); BSTR BSTR_Error; // Convert the double array Conc into a SafeArray SAFEARRAY* sa_Output = SafeArrayCreateVector(VT_R8, 1, 20); FluidProp_COM->LiquidCmp( BSTR_InputSpec, Input1, Input2, &sa_Output, &BSTR_Error); SysFreeString(BSTR_InputSpec); // Retrieve array with concentrations from SafeArray for (long i = 1; i <= 20; i++) SafeArrayGetElement(sa_Output, &i, &Output[i-1]); SafeArrayDestroy(sa_Output); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); return Output; } double* TFluidProp::VaporCmp( string InputSpec, double Input1, double Input2, string* ErrorMsg) { double* Output = new double[20]; BSTR BSTR_InputSpec = ConvertStringToBSTR(InputSpec); BSTR BSTR_Error; // Convert the double array Conc into a SafeArray SAFEARRAY* sa_Output = SafeArrayCreateVector(VT_R8, 1, 20); FluidProp_COM->VaporCmp( BSTR_InputSpec, Input1, Input2, &sa_Output, &BSTR_Error); SysFreeString(BSTR_InputSpec); // Retrieve array with concentrations from SafeArray for (long i = 1; i <= 20; i++) SafeArrayGetElement(sa_Output, &i, &Output[i-1]); SafeArrayDestroy(sa_Output); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); return Output; } double TFluidProp::HeatCapV( string InputSpec, double Input1, double Input2, string* ErrorMsg) { double Output; BSTR BSTR_InputSpec = ConvertStringToBSTR(InputSpec); BSTR BSTR_Error; FluidProp_COM->HeatCapV( BSTR_InputSpec, Input1, Input2, &Output, &BSTR_Error); SysFreeString(BSTR_InputSpec); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); return Output; } double TFluidProp::HeatCapP( string InputSpec, double Input1, double Input2, string* ErrorMsg) { double Output; BSTR BSTR_InputSpec = ConvertStringToBSTR(InputSpec); BSTR BSTR_Error; FluidProp_COM->HeatCapP( BSTR_InputSpec, Input1, Input2, &Output, &BSTR_Error); SysFreeString(BSTR_InputSpec); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); return Output; } double TFluidProp::SoundSpeed( string InputSpec, double Input1, double Input2, string* ErrorMsg) { double Output; BSTR BSTR_InputSpec = ConvertStringToBSTR(InputSpec); BSTR BSTR_Error; FluidProp_COM->SoundSpeed( BSTR_InputSpec, Input1, Input2, &Output, &BSTR_Error); SysFreeString(BSTR_InputSpec); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); return Output; } double TFluidProp::Alpha( string InputSpec, double Input1, double Input2, string* ErrorMsg) { double Output; BSTR BSTR_InputSpec = ConvertStringToBSTR(InputSpec); BSTR BSTR_Error; FluidProp_COM->Alpha( BSTR_InputSpec, Input1, Input2, &Output, &BSTR_Error); SysFreeString(BSTR_InputSpec); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); return Output; } double TFluidProp::Beta( string InputSpec, double Input1, double Input2, string* ErrorMsg) { double Output; BSTR BSTR_InputSpec = ConvertStringToBSTR(InputSpec); BSTR BSTR_Error; FluidProp_COM->Beta( BSTR_InputSpec, Input1, Input2, &Output, &BSTR_Error); SysFreeString(BSTR_InputSpec); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); return Output; } double TFluidProp::Chi( string InputSpec, double Input1, double Input2, string* ErrorMsg) { double Output; BSTR BSTR_InputSpec = ConvertStringToBSTR(InputSpec); BSTR BSTR_Error; FluidProp_COM->Chi( BSTR_InputSpec, Input1, Input2, &Output, &BSTR_Error); SysFreeString(BSTR_InputSpec); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); return Output; } double TFluidProp::Fi( string InputSpec, double Input1, double Input2, string* ErrorMsg) { double Output; BSTR BSTR_InputSpec = ConvertStringToBSTR(InputSpec); BSTR BSTR_Error; FluidProp_COM->Fi( BSTR_InputSpec, Input1, Input2, &Output, &BSTR_Error); SysFreeString(BSTR_InputSpec); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); return Output; } double TFluidProp::Ksi( string InputSpec, double Input1, double Input2, string* ErrorMsg) { double Output; BSTR BSTR_InputSpec = ConvertStringToBSTR(InputSpec); BSTR BSTR_Error; FluidProp_COM->Ksi( BSTR_InputSpec, Input1, Input2, &Output, &BSTR_Error); SysFreeString(BSTR_InputSpec); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); return Output; } double TFluidProp::Psi( string InputSpec, double Input1, double Input2, string* ErrorMsg) { double Output; BSTR BSTR_InputSpec = ConvertStringToBSTR(InputSpec); BSTR BSTR_Error; FluidProp_COM->Psi( BSTR_InputSpec, Input1, Input2, &Output, &BSTR_Error); SysFreeString(BSTR_InputSpec); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); return Output; } double TFluidProp::Zeta( string InputSpec, double Input1, double Input2, string* ErrorMsg) { double Output; BSTR BSTR_InputSpec = ConvertStringToBSTR(InputSpec); BSTR BSTR_Error; FluidProp_COM->Zeta( BSTR_InputSpec, Input1, Input2, &Output, &BSTR_Error); SysFreeString(BSTR_InputSpec); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); return Output; } double TFluidProp::Theta( string InputSpec, double Input1, double Input2, string* ErrorMsg) { double Output; BSTR BSTR_InputSpec = ConvertStringToBSTR(InputSpec); BSTR BSTR_Error; FluidProp_COM->Theta( BSTR_InputSpec, Input1, Input2, &Output, &BSTR_Error); SysFreeString(BSTR_InputSpec); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); return Output; } double TFluidProp::Kappa( string InputSpec, double Input1, double Input2, string* ErrorMsg) { double Output; BSTR BSTR_InputSpec = ConvertStringToBSTR(InputSpec); BSTR BSTR_Error; FluidProp_COM->Kappa( BSTR_InputSpec, Input1, Input2, &Output, &BSTR_Error); SysFreeString(BSTR_InputSpec); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); return Output; } double TFluidProp::Gamma( string InputSpec, double Input1, double Input2, string* ErrorMsg) { double Output; BSTR BSTR_InputSpec = ConvertStringToBSTR(InputSpec); BSTR BSTR_Error; FluidProp_COM->Gamma( BSTR_InputSpec, Input1, Input2, &Output, &BSTR_Error); SysFreeString(BSTR_InputSpec); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); return Output; } double TFluidProp::Viscosity( string InputSpec, double Input1, double Input2, string* ErrorMsg) { double Output; BSTR BSTR_InputSpec = ConvertStringToBSTR(InputSpec); BSTR BSTR_Error; FluidProp_COM->Viscosity( BSTR_InputSpec, Input1, Input2, &Output, &BSTR_Error); SysFreeString(BSTR_InputSpec); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); return Output; } double TFluidProp::ThermCond( string InputSpec, double Input1, double Input2, string* ErrorMsg) { double Output; BSTR BSTR_InputSpec = ConvertStringToBSTR(InputSpec); BSTR BSTR_Error; FluidProp_COM->ThermCond( BSTR_InputSpec, Input1, Input2, &Output, &BSTR_Error); SysFreeString(BSTR_InputSpec); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); return Output; } void TFluidProp::AllProps( string InputSpec, double Input1, double Input2, double& P, double& T, double& v, double& d, double& h, double& s, double& u, double& q, double* x, double* y, double& cv, double& cp, double& c, double& alpha, double& beta, double& chi, double& fi, double& ksi, double& psi, double& zeta, double& theta, double& kappa, double& gamma, double& eta, double& lambda, string* ErrorMsg) { BSTR BSTR_InputSpec = ConvertStringToBSTR(InputSpec); BSTR BSTR_Error; // Convert double arrays with liquid and vapor phase compositions x and y into SafeArrays SAFEARRAY *sa_x = SafeArrayCreateVector(VT_R8, 1, 20); SAFEARRAY *sa_y = SafeArrayCreateVector(VT_R8, 1, 20); FluidProp_COM->AllProps( BSTR_InputSpec, Input1, Input2, &P, &T, &v, &d, &h, &s, &u, &q, &sa_x, &sa_y, &cv, &cp, &c, &alpha, &beta, &chi, &fi, &ksi, &psi, &zeta, &theta, &kappa, &gamma, &eta, &lambda, &BSTR_Error); SysFreeString(BSTR_InputSpec); // Retrieve array with liquid and vapor phase compositions from SafeArrays for (long i = 1; i <= 20; i++) SafeArrayGetElement(sa_x, &i, &x[i-1]); SafeArrayDestroy(sa_x); for (long i = 1; i <= 20; i++) SafeArrayGetElement(sa_y, &i, &y[i-1]); SafeArrayDestroy(sa_y); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); } void TFluidProp::AllPropsSat( string InputSpec, double Input1, double Input2, double& P, double& T, double& v, double& d, double& h, double& s, double& u, double& q, double* x, double* y, double& cv, double& cp, double& c, double& alpha, double& beta, double& chi, double& fi, double& ksi, double& psi, double& zeta, double& theta, double& kappa, double& gamma, double& eta, double& lambda, double& d_liq, double& d_vap, double& h_liq, double& h_vap, double& T_sat, double& dd_liq_dP, double& dd_vap_dP, double& dh_liq_dP, double& dh_vap_dP, double& dT_sat_dP, string* ErrorMsg) { BSTR BSTR_InputSpec = ConvertStringToBSTR(InputSpec); BSTR BSTR_Error; // Convert double arrays with liquid and vapor phase compositions x and y into SafeArrays SAFEARRAY *sa_x = SafeArrayCreateVector(VT_R8, 1, 20); SAFEARRAY *sa_y = SafeArrayCreateVector(VT_R8, 1, 20); FluidProp_COM->AllPropsSat( BSTR_InputSpec, Input1, Input2, &P, &T, &v, &d, &h, &s, &u, &q, &sa_x, &sa_y, &cv, &cp, &c, &alpha, &beta, &chi, &fi, &ksi, &psi, &zeta, &theta, &kappa, &gamma, &eta, &lambda, &d_liq, &d_vap, &h_liq, &h_vap, &T_sat, &dd_liq_dP, &dd_vap_dP, &dh_liq_dP, &dh_vap_dP, &dT_sat_dP, &BSTR_Error); SysFreeString(BSTR_InputSpec); // Retrieve array with liquid and vapor phase compositions from SafeArrays for (long i = 1; i <= 20; i++) SafeArrayGetElement(sa_x, &i, &x[i-1]); SafeArrayDestroy(sa_x); for (long i = 1; i <= 20; i++) SafeArrayGetElement(sa_y, &i, &y[i-1]); SafeArrayDestroy(sa_y); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); } double TFluidProp::Solve( string FuncSpec, double FuncVal, string InputSpec, long Target, double FixedVal, double MinVal, double MaxVal, string* ErrorMsg) { double Output; BSTR BSTR_FuncSpec = ConvertStringToBSTR(FuncSpec); BSTR BSTR_InputSpec = ConvertStringToBSTR(InputSpec); BSTR BSTR_Error; FluidProp_COM->Solve( BSTR_FuncSpec, FuncVal, BSTR_InputSpec, Target, FixedVal, MinVal, MaxVal, &Output, &BSTR_Error); SysFreeString(BSTR_FuncSpec); SysFreeString(BSTR_InputSpec); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); return Output; } double TFluidProp::Mmol( string* ErrorMsg) { double Output; BSTR BSTR_Error; FluidProp_COM->Mmol( &Output, &BSTR_Error); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); return Output; } double TFluidProp::Tcrit( string* ErrorMsg) { double Output; BSTR BSTR_Error; FluidProp_COM->Tcrit( &Output, &BSTR_Error); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); return Output; } double TFluidProp::Pcrit( string* ErrorMsg) { double Output; BSTR BSTR_Error; FluidProp_COM->Pcrit( &Output, &BSTR_Error); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); return Output; } double TFluidProp::Tmin( string* ErrorMsg) { double Output; BSTR BSTR_Error; FluidProp_COM->Tmin( &Output, &BSTR_Error); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); return Output; } double TFluidProp::Tmax( string* ErrorMsg) { double Output; BSTR BSTR_Error; FluidProp_COM->Tmax( &Output, &BSTR_Error); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); return Output; } void TFluidProp::AllInfo( double& Mmol, double& Tcrit, double& Pcrit, double& Tmin, double& Tmax, string* ErrorMsg) { BSTR BSTR_Error; FluidProp_COM->AllInfo( &Mmol, &Tcrit, &Pcrit, &Tmin, &Tmax, &BSTR_Error); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); } void TFluidProp::SetUnits( string UnitSet, string MassOrMole, string Properties, string Units, string* ErrorMsg) { BSTR BSTR_Error; BSTR BSTR_UnitSet = ConvertStringToBSTR(UnitSet); BSTR BSTR_MassOrMole = ConvertStringToBSTR(MassOrMole); BSTR BSTR_Properties = ConvertStringToBSTR(Properties); BSTR BSTR_Units = ConvertStringToBSTR(Units); FluidProp_COM->SetUnits( BSTR_UnitSet, BSTR_MassOrMole, BSTR_Properties, BSTR_Units, &BSTR_Error); SysFreeString(BSTR_UnitSet); SysFreeString(BSTR_MassOrMole); SysFreeString(BSTR_Properties); SysFreeString(BSTR_Units); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); } void TFluidProp::SetRefState( double T_ref, double P_ref, string* ErrorMsg) { BSTR BSTR_Error; FluidProp_COM->SetRefState( T_ref, P_ref, &BSTR_Error); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); } void TFluidProp::GetVersion(string ModelName, int* version) { // Convert model name to binary string BSTR BSTR_Model = ConvertStringToBSTR(ModelName); // Now get the version for the model selected SAFEARRAY* sa_version; FluidProp_COM->GetVersion(BSTR_Model, &sa_version); SysFreeString(BSTR_Model); for (long i = 1; i <= 4; i++) { SafeArrayGetElement(sa_version, &i, &version[i-1]); } SafeArrayDestroyData(sa_version); SafeArrayDestroyDescriptor(sa_version); } double* TFluidProp::FugaCoef( string InputSpec, double Input1, double Input2, string* ErrorMsg) { double* Output = new double[20]; BSTR BSTR_InputSpec = ConvertStringToBSTR(InputSpec); BSTR BSTR_Error; // Convert the double array Conc into a SafeArray SAFEARRAYBOUND sa_bounds_Output[1]; sa_bounds_Output[0].lLbound = 0; sa_bounds_Output[0].cElements = 20; SAFEARRAY* sa_Output; sa_Output = SafeArrayCreate(VT_R8, 1, sa_bounds_Output); FluidProp_COM->FugaCoef( BSTR_InputSpec, Input1, Input2, &sa_Output, &BSTR_Error); SysFreeString(BSTR_InputSpec); // Retrieve array with concentrations from SafeArray for (long i = 0; i < (signed)sa_bounds_Output[0].cElements; i++) SafeArrayGetElement(sa_Output, &i, &Output[i]); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); return Output; } double TFluidProp::SurfTens( string InputSpec, double Input1, double Input2, string* ErrorMsg) { double Output; BSTR BSTR_InputSpec = ConvertStringToBSTR(InputSpec); BSTR BSTR_Error; FluidProp_COM->SurfTens( BSTR_InputSpec, Input1, Input2, &Output, &BSTR_Error); SysFreeString(BSTR_InputSpec); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); return Output; } double TFluidProp::GibbsEnergy( string InputSpec, double Input1, double Input2, string* ErrorMsg) { double Output; BSTR BSTR_InputSpec = ConvertStringToBSTR(InputSpec); BSTR BSTR_Error; FluidProp_COM->GibbsEnergy( BSTR_InputSpec, Input1, Input2, &Output, &BSTR_Error); SysFreeString(BSTR_InputSpec); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); return Output; } void TFluidProp::CapeOpenDeriv( string InputSpec, double Input1, double Input2, double* v, double* h, double* s, double* G, double* lnphi, string* ErrorMsg) { BSTR BSTR_InputSpec = ConvertStringToBSTR(InputSpec); BSTR BSTR_Error; // Create safe arrays for double arrays v[2n+2], h[2n+2], s[2n+2], G[2n+2] and lnphi[n,2n+2], where n_max = 20. SAFEARRAYBOUND sa_bnd_vhsG[1]; sa_bnd_vhsG[0].lLbound = 0; sa_bnd_vhsG[0].cElements = 100; SAFEARRAY *sa_v, *sa_h, *sa_s, *sa_G; sa_v = SafeArrayCreate(VT_R8, 1, sa_bnd_vhsG); sa_h = SafeArrayCreate(VT_R8, 1, sa_bnd_vhsG); sa_s = SafeArrayCreate(VT_R8, 1, sa_bnd_vhsG); sa_G = SafeArrayCreate(VT_R8, 1, sa_bnd_vhsG); SAFEARRAYBOUND sa_bnd_lnphi[2]; sa_bnd_lnphi[0].lLbound = 0; sa_bnd_lnphi[0].cElements = 20; sa_bnd_lnphi[1].lLbound = 0; sa_bnd_lnphi[1].cElements = 100; SAFEARRAY *sa_lnphi; sa_lnphi = SafeArrayCreate(VT_R8, 2, sa_bnd_lnphi); FluidProp_COM->CapeOpenDeriv(BSTR_InputSpec, Input1, Input2, &sa_v, &sa_h, &sa_s, &sa_G, &sa_lnphi, &BSTR_Error); SysFreeString(BSTR_InputSpec); // Put the values from safearray's in the double array's v, h, s, and G for (long i = 0; i < (signed)sa_bnd_vhsG[0].cElements; i++) { SafeArrayGetElement(sa_v, &i, &v[i]); SafeArrayGetElement(sa_h, &i, &h[i]); SafeArrayGetElement(sa_s, &i, &s[i]); SafeArrayGetElement(sa_G, &i, &G[i]); } // Put the values from safearray's sa_lnphi into double array lnphi for (long i = 0; i < (signed)sa_bnd_lnphi[1].cElements; i++) { for (long j = 0; j < (signed)sa_bnd_lnphi[0].cElements; i++) { long idx_bnd[2]; idx_bnd[1] = i; idx_bnd[0] = j; SafeArrayGetElement(sa_lnphi, &idx_bnd[0], &lnphi[i*20+j]); } } // Destroy the SafeArrays SafeArrayDestroy(sa_v); SafeArrayDestroy(sa_h); SafeArrayDestroy(sa_s); SafeArrayDestroy(sa_G); SafeArrayDestroy(sa_lnphi); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); } double* TFluidProp::SpecVolume_Deriv( string InputSpec, double Input1, double Input2, string* ErrorMsg) { double* Output = new double[42]; BSTR BSTR_InputSpec = ConvertStringToBSTR(InputSpec); BSTR BSTR_Error; // Convert the double array Conc into a SafeArray SAFEARRAYBOUND sa_bounds_Output[1]; sa_bounds_Output[0].lLbound = 0; sa_bounds_Output[0].cElements = 42; SAFEARRAY* sa_Output; sa_Output = SafeArrayCreate(VT_R8, 1, sa_bounds_Output); FluidProp_COM->SpecVolume_Deriv( BSTR_InputSpec, Input1, Input2, &sa_Output, &BSTR_Error); SysFreeString(BSTR_InputSpec); // Retrieve array with concentrations from SafeArray for (long i = 0; i < (signed)sa_bounds_Output[0].cElements; i++) SafeArrayGetElement(sa_Output, &i, &Output[i]); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); return Output; } double* TFluidProp::Enthalpy_Deriv( string InputSpec, double Input1, double Input2, string* ErrorMsg) { double* Output = new double[42]; BSTR BSTR_InputSpec = ConvertStringToBSTR(InputSpec); BSTR BSTR_Error; // Convert the double array Conc into a SafeArray SAFEARRAYBOUND sa_bounds_Output[1]; sa_bounds_Output[0].lLbound = 0; sa_bounds_Output[0].cElements = 42; SAFEARRAY* sa_Output; sa_Output = SafeArrayCreate(VT_R8, 1, sa_bounds_Output); FluidProp_COM->Enthalpy_Deriv( BSTR_InputSpec, Input1, Input2, &sa_Output, &BSTR_Error); SysFreeString(BSTR_InputSpec); // Retrieve array with concentrations from SafeArray for (long i = 0; i < (signed)sa_bounds_Output[0].cElements; i++) SafeArrayGetElement(sa_Output, &i, &Output[i]); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); return Output; } double* TFluidProp::Entropy_Deriv( string InputSpec, double Input1, double Input2, string* ErrorMsg) { double* Output = new double[42]; BSTR BSTR_InputSpec = ConvertStringToBSTR(InputSpec); BSTR BSTR_Error; // Convert the double array Conc into a SafeArray SAFEARRAYBOUND sa_bounds_Output[1]; sa_bounds_Output[0].lLbound = 0; sa_bounds_Output[0].cElements = 42; SAFEARRAY* sa_Output; sa_Output = SafeArrayCreate(VT_R8, 1, sa_bounds_Output); FluidProp_COM->Entropy_Deriv( BSTR_InputSpec, Input1, Input2, &sa_Output, &BSTR_Error); SysFreeString(BSTR_InputSpec); // Retrieve array with concentrations from SafeArray for (long i = 0; i < (signed)sa_bounds_Output[0].cElements; i++) SafeArrayGetElement(sa_Output, &i, &Output[i]); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); return Output; } double* TFluidProp::GibbsEnergy_Deriv( string InputSpec, double Input1, double Input2, string* ErrorMsg) { double* Output = new double[42]; BSTR BSTR_InputSpec = ConvertStringToBSTR(InputSpec); BSTR BSTR_Error; // Convert the double array Conc into a SafeArray SAFEARRAYBOUND sa_bounds_Output[1]; sa_bounds_Output[0].lLbound = 0; sa_bounds_Output[0].cElements = 42; SAFEARRAY* sa_Output; sa_Output = SafeArrayCreate(VT_R8, 1, sa_bounds_Output); FluidProp_COM->GibbsEnergy_Deriv( BSTR_InputSpec, Input1, Input2, &sa_Output, &BSTR_Error); SysFreeString(BSTR_InputSpec); // Retrieve array with concentrations from SafeArray for (long i = 0; i < (signed)sa_bounds_Output[0].cElements; i++) SafeArrayGetElement(sa_Output, &i, &Output[i]); *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); return Output; } double* TFluidProp::FugaCoef_Deriv( string InputSpec, double Input1, double Input2, string* ErrorMsg) { double* Output = new double[20*42]; BSTR BSTR_InputSpec = ConvertStringToBSTR(InputSpec); BSTR BSTR_Error; // Convert the double array Conc into a SafeArray SAFEARRAYBOUND sa_bounds_Output[2]; sa_bounds_Output[0].lLbound = 0; sa_bounds_Output[0].cElements = 20; sa_bounds_Output[1].lLbound = 0; sa_bounds_Output[1].cElements = 42; SAFEARRAY* sa_Output; sa_Output = SafeArrayCreate(VT_R8, 2, sa_bounds_Output); FluidProp_COM->FugaCoef_Deriv( BSTR_InputSpec, Input1, Input2, &sa_Output, &BSTR_Error); SysFreeString(BSTR_InputSpec); // Retrieve array with concentrations from SafeArray for (long i = 0; i < (signed)sa_bounds_Output[0].cElements; i++) { for (long j = 0; j < (signed)sa_bounds_Output[1].cElements; j++) { long idx[2] = {i,j}; double f; SafeArrayGetElement(sa_Output, idx, (void*)&f); // Storage in Output // 1) first 20 elements : derivatives wrt T (dlnphi_1/dT, dlnphi_2/dT, ... dlnphi_20/dT) // 2) second 20 elements : derivatives wrt P (dlnphi_1/dP, dlnphi_2/dP, ... dlnphi_20/dP) // 3) next 20*20 elements: derivatives wrt x (dlnphi_1/dx_1, dlnphi_2/dx_1, ... dlnphi_20/dx_1, dlnphi_1/dx_2, etc.) // 4) next 20*20 elements: derivatives wrt n (dlnphi_1/dn_1, dlnphi_2/dn_1, ... dlnphi_20/dn_1, dlnphi_1/dn_2, etc.) Output[i+j*20] = f; } } *ErrorMsg = ConvertBSTRToString(BSTR_Error); SysFreeString(BSTR_Error); return Output; } //==================================================================================== EOF ===//
/* * Copyright 2011-2013 Blender Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "util/util_system.h" #include "util/util_logging.h" #include "util/util_types.h" #include "util/util_string.h" #include <numaapi.h> #include <OpenImageIO/sysutil.h> OIIO_NAMESPACE_USING #ifdef _WIN32 # if (!defined(FREE_WINDOWS)) # include <intrin.h> # endif # include "util_windows.h" #elif defined(__APPLE__) # include <sys/ioctl.h> # include <sys/sysctl.h> # include <sys/types.h> #else # include <unistd.h> # include <sys/ioctl.h> #endif CCL_NAMESPACE_BEGIN bool system_cpu_ensure_initialized() { static bool is_initialized = false; static bool result = false; if (is_initialized) { return result; } is_initialized = true; const NUMAAPI_Result numa_result = numaAPI_Initialize(); result = (numa_result == NUMAAPI_SUCCESS); return result; } /* Fallback solution, which doesn't use NUMA/CPU groups. */ static int system_cpu_thread_count_fallback() { #ifdef _WIN32 SYSTEM_INFO info; GetSystemInfo(&info); return info.dwNumberOfProcessors; #elif defined(__APPLE__) int count; size_t len = sizeof(count); int mib[2] = {CTL_HW, HW_NCPU}; sysctl(mib, 2, &count, &len, NULL, 0); return count; #else return sysconf(_SC_NPROCESSORS_ONLN); #endif } int system_cpu_thread_count() { const int num_nodes = system_cpu_num_numa_nodes(); int num_threads = 0; for (int node = 0; node < num_nodes; ++node) { if (!system_cpu_is_numa_node_available(node)) { continue; } num_threads += system_cpu_num_numa_node_processors(node); } return num_threads; } int system_cpu_num_numa_nodes() { if (!system_cpu_ensure_initialized()) { /* Fallback to a single node with all the threads. */ return 1; } return numaAPI_GetNumNodes(); } bool system_cpu_is_numa_node_available(int node) { if (!system_cpu_ensure_initialized()) { return true; } return numaAPI_IsNodeAvailable(node); } int system_cpu_num_numa_node_processors(int node) { if (!system_cpu_ensure_initialized()) { return system_cpu_thread_count_fallback(); } return numaAPI_GetNumNodeProcessors(node); } bool system_cpu_run_thread_on_node(int node) { if (!system_cpu_ensure_initialized()) { return true; } return numaAPI_RunThreadOnNode(node); } int system_console_width() { int columns = 0; #ifdef _WIN32 CONSOLE_SCREEN_BUFFER_INFO csbi; if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi)) { columns = csbi.dwSize.X; } #else struct winsize w; if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) == 0) { columns = w.ws_col; } #endif return (columns > 0) ? columns : 80; } int system_cpu_num_active_group_processors() { if (!system_cpu_ensure_initialized()) { return system_cpu_thread_count_fallback(); } return numaAPI_GetNumCurrentNodesProcessors(); } #if !defined(_WIN32) || defined(FREE_WINDOWS) static void __cpuid(int data[4], int selector) { # if defined(__x86_64__) asm("cpuid" : "=a"(data[0]), "=b"(data[1]), "=c"(data[2]), "=d"(data[3]) : "a"(selector)); # elif defined(__i386__) asm("pushl %%ebx \n\t" "cpuid \n\t" "movl %%ebx, %1 \n\t" "popl %%ebx \n\t" : "=a"(data[0]), "=r"(data[1]), "=c"(data[2]), "=d"(data[3]) : "a"(selector) : "ebx"); # else data[0] = data[1] = data[2] = data[3] = 0; # endif } #endif string system_cpu_brand_string() { char buf[48] = {0}; int result[4] = {0}; __cpuid(result, 0x80000000); if (result[0] >= (int)0x80000004) { __cpuid((int *)(buf + 0), 0x80000002); __cpuid((int *)(buf + 16), 0x80000003); __cpuid((int *)(buf + 32), 0x80000004); string brand = buf; /* make it a bit more presentable */ brand = string_remove_trademark(brand); return brand; } return "Unknown CPU"; } int system_cpu_bits() { return (sizeof(void *) * 8); } #if defined(__x86_64__) || defined(_M_X64) || defined(i386) || defined(_M_IX86) struct CPUCapabilities { bool x64; bool mmx; bool sse; bool sse2; bool sse3; bool ssse3; bool sse41; bool sse42; bool sse4a; bool avx; bool f16c; bool avx2; bool xop; bool fma3; bool fma4; bool bmi1; bool bmi2; }; static CPUCapabilities &system_cpu_capabilities() { static CPUCapabilities caps; static bool caps_init = false; if (!caps_init) { int result[4], num; memset(&caps, 0, sizeof(caps)); __cpuid(result, 0); num = result[0]; if (num >= 1) { __cpuid(result, 0x00000001); caps.mmx = (result[3] & ((int)1 << 23)) != 0; caps.sse = (result[3] & ((int)1 << 25)) != 0; caps.sse2 = (result[3] & ((int)1 << 26)) != 0; caps.sse3 = (result[2] & ((int)1 << 0)) != 0; caps.ssse3 = (result[2] & ((int)1 << 9)) != 0; caps.sse41 = (result[2] & ((int)1 << 19)) != 0; caps.sse42 = (result[2] & ((int)1 << 20)) != 0; caps.fma3 = (result[2] & ((int)1 << 12)) != 0; caps.avx = false; bool os_uses_xsave_xrestore = (result[2] & ((int)1 << 27)) != 0; bool cpu_avx_support = (result[2] & ((int)1 << 28)) != 0; if (os_uses_xsave_xrestore && cpu_avx_support) { // Check if the OS will save the YMM registers uint32_t xcr_feature_mask; # if defined(__GNUC__) int edx; /* not used */ /* actual opcode for xgetbv */ __asm__(".byte 0x0f, 0x01, 0xd0" : "=a"(xcr_feature_mask), "=d"(edx) : "c"(0)); # elif defined(_MSC_VER) && defined(_XCR_XFEATURE_ENABLED_MASK) xcr_feature_mask = (uint32_t)_xgetbv( _XCR_XFEATURE_ENABLED_MASK); /* min VS2010 SP1 compiler is required */ # else xcr_feature_mask = 0; # endif caps.avx = (xcr_feature_mask & 0x6) == 0x6; } caps.f16c = (result[2] & ((int)1 << 29)) != 0; __cpuid(result, 0x00000007); caps.bmi1 = (result[1] & ((int)1 << 3)) != 0; caps.bmi2 = (result[1] & ((int)1 << 8)) != 0; caps.avx2 = (result[1] & ((int)1 << 5)) != 0; } caps_init = true; } return caps; } bool system_cpu_support_sse2() { CPUCapabilities &caps = system_cpu_capabilities(); return caps.sse && caps.sse2; } bool system_cpu_support_sse3() { CPUCapabilities &caps = system_cpu_capabilities(); return caps.sse && caps.sse2 && caps.sse3 && caps.ssse3; } bool system_cpu_support_sse41() { CPUCapabilities &caps = system_cpu_capabilities(); return caps.sse && caps.sse2 && caps.sse3 && caps.ssse3 && caps.sse41; } bool system_cpu_support_avx() { CPUCapabilities &caps = system_cpu_capabilities(); return caps.sse && caps.sse2 && caps.sse3 && caps.ssse3 && caps.sse41 && caps.avx; } bool system_cpu_support_avx2() { CPUCapabilities &caps = system_cpu_capabilities(); return caps.sse && caps.sse2 && caps.sse3 && caps.ssse3 && caps.sse41 && caps.avx && caps.f16c && caps.avx2 && caps.fma3 && caps.bmi1 && caps.bmi2; } #else bool system_cpu_support_sse2() { return false; } bool system_cpu_support_sse3() { return false; } bool system_cpu_support_sse41() { return false; } bool system_cpu_support_avx() { return false; } bool system_cpu_support_avx2() { return false; } #endif bool system_call_self(const vector<string> &args) { /* Escape program and arguments in case they contain spaces. */ string cmd = "\"" + Sysutil::this_program_path() + "\""; for (int i = 0; i < args.size(); i++) { cmd += " \"" + args[i] + "\""; } #ifdef _WIN32 /* Use cmd /S to avoid issues with spaces in arguments. */ cmd = "cmd /S /C \"" + cmd + " > nul \""; #else /* Quiet output. */ cmd += " > /dev/null"; #endif return (system(cmd.c_str()) == 0); } size_t system_physical_ram() { #ifdef _WIN32 MEMORYSTATUSEX ram; ram.dwLength = sizeof(ram); GlobalMemoryStatusEx(&ram); return ram.ullTotalPhys; #elif defined(__APPLE__) uint64_t ram = 0; size_t len = sizeof(ram); if (sysctlbyname("hw.memsize", &ram, &len, NULL, 0) == 0) { return ram; } return 0; #else size_t ps = sysconf(_SC_PAGESIZE); size_t pn = sysconf(_SC_PHYS_PAGES); return ps * pn; #endif } CCL_NAMESPACE_END
#include <bits/stdc++.h> using namespace std; const int N = 2005; char s[N], t[N]; int na[N][26], nb[N][26], nxt[26]; int n, m, a[N], b[N], tot = 1, p = 1, f[N][N << 1]; struct SAM { int par, ch[26], len; } sam[N << 1]; void insert(int x) { int np = ++tot; sam[np].len = sam[p].len + 1; while (p && !sam[p].ch[x]) { sam[p].ch[x] = np; p = sam[p].par; } if (p == 0) sam[np].par = 1; else { int q = sam[p].ch[x]; if (sam[q].len == sam[p].len + 1) sam[np].par = q; else { int nq = ++tot; sam[nq].len = sam[p].len + 1; memcpy(sam[nq].ch, sam[q].ch, sizeof(sam[q].ch)); sam[nq].par = sam[q].par; sam[q].par = sam[np].par = nq; while (p && sam[p].ch[x] == q) { sam[p].ch[x] = nq; p = sam[p].par; } } } p = np; } int main() { scanf("%s%s", s + 1, t + 1); n = strlen(s + 1); m = strlen(t + 1); for (int i = 1; i <= n; ++i) a[i] = s[i] - 'a'; for (int i = 1; i <= m; ++i) b[i] = t[i] - 'a'; for (int i = 1; i <= m; ++i) insert(b[i]); for (int i = 0; i < 26; ++i) nxt[i] = n + 1; for (int i = n; i >= 0; --i) { memcpy(na[i], nxt, sizeof(nxt)); nxt[a[i]] = i; } for (int i = 0; i < 26; ++i) nxt[i] = m + 1; for (int i = m; i >= 0; --i) { memcpy(nb[i], nxt, sizeof(nxt)); nxt[b[i]] = i; } int ans = N; for (int l = 1; l <= n; ++l) { for (int r = l, u = 1; r <= n; ++r) { u = sam[u].ch[a[r]]; if (!u) { ans = min(ans, r - l + 1); break; } } } printf("%d\n", ans == N ? -1 : ans); ans = N; for (int l = 1; l <= n; ++l) { for (int r = l, u = 0; r <= n; ++r) { u = nb[u][a[r]]; if (u == m + 1) { ans = min(ans, r - l + 1); break; } } } printf("%d\n", ans == N ? -1 : ans); for (int i = n; i >= 0; --i) { for (int j = 1; j <= tot; ++j) { f[i][j] = N; for (int c = 0; c < 26; ++c) { int u = na[i][c]; int v = sam[j].ch[c]; if (u <= n) f[i][j] = min(f[i][j], f[u][v] + 1); } } } printf("%d\n", f[0][1] == N ? -1 : f[0][1]); memset(f, 0, sizeof(f)); for (int i = n; i >= 0; --i) { for (int j = 0; j <= m; ++j) { f[i][j] = N; for (int c = 0; c < 26; ++c) { int u = na[i][c]; int v = nb[j][c]; if (u <= n) f[i][j] = min(f[i][j], f[u][v] + 1); } } } printf("%d\n", f[0][0] == N ? -1 : f[0][0]); return 0; }
#include "modmanager.h" #include "ui_modmanager.h" #include <QMessageBox> #include <QSettings> ModManager::ModManager(QWidget *parent) : QWidget(parent), ui(new Ui::ModManager) { ui->setupUi(this); } ModManager::~ModManager() { delete ui; } void ModManager::AddRoot(QString name, QString version, QString author) { QTreeWidgetItem *itm = new QTreeWidgetItem(ui->treeModList); itm->setText(0, name); itm->setText(1, version); itm->setText(2, author); ui->treeModList->addTopLevelItem(itm); } void ModManager::AddChild(QTreeWidgetItem *parent, QString name, QString version, QString author) { } void ModManager::AddModDir() { QDir moddir = QApplication::applicationDirPath(); if (!moddir.exists("resourepack")) { QMessageBox::warning(this, "No Directory", "Directory 'resourepack' not found. Creating it. \nMake sure to throw in some mods in there and refresh!"); moddir.mkdir("resourepack"); } else { QSettings modini(moddir.filePath("respack.ini"), QSettings::IniFormat); QString packName = modini.value("packName", "My Mod").toString(); QString packVersion = modini.value("packVersion", "v1.0").toString(); QString packAuthor = modini.value("packAuthor", "A Pone").toString(); AddRoot(packName, packVersion, packAuthor); } }
// // Project Name: Kratos // Last Modified by: $Author: gcasas $ // Date: $Date: 2016-03-08 08:56:42 $ // // #include "derivative_recovery.h" namespace Kratos { template <std::size_t TDim> void DerivativeRecovery<TDim>::RecoverGradientOfAScalar(const VariableData& origin_variable, const VariableData& destination_variable) { for (int i = 0; i < (int)mModelPart.Nodes().size(); ++i){ NodeIteratorType i_particle = mModelPart.NodesBegin() + i; Node<3>::Pointer p_node = *(i_particle.base()); array_1d<double, 3>& gradient = p_node->FastGetSolutionStepValue(TORQUE); gradient[0] = 0.0; gradient[1] = 0.0; gradient[2] = 99.0; } } //*************************************************************************************************************** //*************************************************************************************************************** template <std::size_t TDim> void DerivativeRecovery<TDim>::AddTimeDerivative(ModelPart& r_model_part, Variable<array_1d<double, 3> >& material_derivative_container) { const double delta_time_inv = 1.0 / r_model_part.GetProcessInfo()[DELTA_TIME]; for (NodeIteratorType inode = r_model_part.NodesBegin(); inode != r_model_part.NodesEnd(); ++inode){ array_1d <double, 3>& material_derivative = inode->FastGetSolutionStepValue(material_derivative_container); const array_1d <double, 3> eulerian_rate_of_change = delta_time_inv * (inode->FastGetSolutionStepValue(VELOCITY) - inode->FastGetSolutionStepValue(VELOCITY, 1)); noalias(material_derivative) += eulerian_rate_of_change; } } //*************************************************************************************************************** //*************************************************************************************************************** template <std::size_t TDim> void DerivativeRecovery<TDim>::AddTimeDerivativeComponent(ModelPart& r_model_part, Variable<array_1d<double, 3> >& material_derivative_container, const int i_component) { const double delta_time_inv = 1.0 / r_model_part.GetProcessInfo()[DELTA_TIME]; for (NodeIteratorType inode = r_model_part.NodesBegin(); inode != r_model_part.NodesEnd(); ++inode){ const double eulerian_rate_of_change = delta_time_inv * (inode->FastGetSolutionStepValue(VELOCITY)[i_component] - inode->FastGetSolutionStepValue(VELOCITY, 1)[i_component]); array_1d <double, 3>& material_derivative = inode->FastGetSolutionStepValue(material_derivative_container); material_derivative[i_component] += eulerian_rate_of_change; } } //*************************************************************************************************************** //*************************************************************************************************************** template <std::size_t TDim> void DerivativeRecovery<TDim>::CalculateVectorMaterialDerivative(ModelPart& r_model_part, Variable<array_1d<double, 3> >& vector_container, Variable<array_1d<double, 3> >& vector_rate_container, Variable<array_1d<double, 3> >& material_derivative_container) { KRATOS_INFO("SwimmingDEM") << "Constructing the material derivative by derivating nodal averages..." << std::endl; std::map <std::size_t, unsigned int> id_to_position; unsigned int entry = 0; for (NodeIteratorType inode = r_model_part.NodesBegin(); inode != r_model_part.NodesEnd(); ++inode){ noalias(inode->FastGetSolutionStepValue(material_derivative_container)) = ZeroVector(3); id_to_position[inode->Id()] = entry; ++entry; } std::vector<array_1d <double, 3> > convective_contributions_to_the_derivative; convective_contributions_to_the_derivative.resize(entry); array_1d <double, 3> grad = ZeroVector(3); array_1d <double, TDim + 1 > elemental_values; array_1d <double, TDim + 1 > N; // shape functions vector BoundedMatrix<double, TDim + 1, TDim> DN_DX; for (unsigned int j = 0; j < TDim; ++j){ // for each component of the original vector value // for each element, constructing the gradient contribution (to its nodes) of the component v_j and storing it in material_derivative_container for (ModelPart::ElementIterator ielem = r_model_part.ElementsBegin(); ielem != r_model_part.ElementsEnd(); ++ielem){ // computing the shape function derivatives Geometry<Node<3> >& geom = ielem->GetGeometry(); double Volume; GeometryUtils::CalculateGeometryData(geom, DN_DX, N, Volume); for (unsigned int i = 0; i < TDim + 1; ++i){ elemental_values[i] = geom[i].FastGetSolutionStepValue(vector_container)[j]; } array_1d <double, 3> grad_aux = prod(trans(DN_DX), elemental_values); // its dimension may be 2 for (unsigned int i = 0; i < TDim; ++i){ grad[i] = grad_aux[i]; } double nodal_area = Volume / static_cast<double>(TDim + 1); grad *= nodal_area; for (unsigned int i = 0; i < TDim + 1; ++i){ geom[i].FastGetSolutionStepValue(material_derivative_container) += grad; // we use material_derivative_container to store the gradient of one component at a time } } // normalizing the constributions to the gradient and getting the j-component of the material derivative for (NodeIteratorType inode = r_model_part.NodesBegin(); inode != r_model_part.NodesEnd(); ++inode){ array_1d <double, 3>& stored_gradient_of_component_j = inode->FastGetSolutionStepValue(material_derivative_container); stored_gradient_of_component_j /= inode->FastGetSolutionStepValue(NODAL_AREA); if (mStoreFullGradient){ if (j == 0){ array_1d <double, 3>& gradient = inode->FastGetSolutionStepValue(VELOCITY_X_GRADIENT); noalias(gradient) = stored_gradient_of_component_j; } else if (j == 1){ array_1d <double, 3>& gradient = inode->FastGetSolutionStepValue(VELOCITY_Y_GRADIENT); noalias(gradient) = stored_gradient_of_component_j; } else { array_1d <double, 3>& gradient = inode->FastGetSolutionStepValue(VELOCITY_Z_GRADIENT); noalias(gradient) = stored_gradient_of_component_j; } } const array_1d <double, 3>& velocity = inode->FastGetSolutionStepValue(VELOCITY); convective_contributions_to_the_derivative[id_to_position[inode->Id()]][j] = DEM_INNER_PRODUCT_3(velocity, stored_gradient_of_component_j); stored_gradient_of_component_j = ZeroVector(3); } } // Adding convective part for (NodeIteratorType inode = r_model_part.NodesBegin(); inode != r_model_part.NodesEnd(); ++inode){ const array_1d <double, 3>& stored_convective_contribution = convective_contributions_to_the_derivative[id_to_position[inode->Id()]]; array_1d <double, 3>& material_derivative = inode->FastGetSolutionStepValue(material_derivative_container); material_derivative = stored_convective_contribution; } // Adding Eulerian time derivative contribution AddTimeDerivative(r_model_part, material_derivative_container); KRATOS_INFO("SwimmingDEM") << "Finished constructing the material derivative by derivating nodal averages..." << std::endl; } //*************************************************************************************************************** //*************************************************************************************************************** template <std::size_t TDim> void DerivativeRecovery<TDim>::RecoverLagrangianAcceleration(ModelPart& r_model_part) { for (NodeIteratorType inode = r_model_part.NodesBegin(); inode != r_model_part.NodesEnd(); ++inode){ const array_1d <double, 3>& lagrangian_acceleration = inode->FastGetSolutionStepValue(ACCELERATION); array_1d <double, 3>& material_acceleration = inode->FastGetSolutionStepValue(MATERIAL_ACCELERATION); noalias(material_acceleration) = lagrangian_acceleration; } } //************************************************************************************************************************************************** //************************************************************************************************************************************************** // This function modifies the material derivative using the pre-computed value of the gradient template <std::size_t TDim> void DerivativeRecovery<TDim>::CalculateVectorMaterialDerivativeFromGradient(ModelPart& r_model_part, Variable<array_1d<double, 3> >& vector_gradient_container_x, Variable<array_1d<double, 3> >& vector_gradient_container_y, Variable<array_1d<double, 3> >& vector_gradient_container_z, Variable<array_1d<double, 3> >& vector_rate_container, Variable<array_1d<double, 3> >& material_derivative_container) { #pragma omp parallel for for (int i = 0; i < (int)r_model_part.Nodes().size(); ++i){ NodeIteratorType i_particle = r_model_part.NodesBegin() + i; Node<3>::Pointer p_node = *(i_particle.base()); const array_1d <double, 3>& velocity = p_node->FastGetSolutionStepValue(VELOCITY); array_1d <double, 3>& material_derivative = p_node->FastGetSolutionStepValue(material_derivative_container); material_derivative[0] = DEM_INNER_PRODUCT_3(velocity, p_node->FastGetSolutionStepValue(vector_gradient_container_x)); material_derivative[1] = DEM_INNER_PRODUCT_3(velocity, p_node->FastGetSolutionStepValue(vector_gradient_container_y)); material_derivative[2] = DEM_INNER_PRODUCT_3(velocity, p_node->FastGetSolutionStepValue(vector_gradient_container_z)); } AddTimeDerivative(r_model_part, material_derivative_container); } //************************************************************************************************************************************************** //************************************************************************************************************************************************** // This function modifies one component of the material derivative using the pre-computed value of the gradient of the first component of the velocity template <std::size_t TDim> void DerivativeRecovery<TDim>::CalculateVectorMaterialDerivativeComponent(ModelPart& r_model_part, Variable<array_1d<double, 3> >& vector_component_gradient_container, Variable<array_1d<double, 3> >& vector_rate_container, Variable<array_1d<double, 3> >& material_derivative_container) { int current_component = r_model_part.GetProcessInfo()[CURRENT_COMPONENT]; if (current_component != 0 && current_component != 1 && current_component != 2){ KRATOS_THROW_ERROR(std::invalid_argument,"The value of CURRENT_COMPONENT passed to the ComputeComponentGradientSimplex element is not 0, 1 or 2, but ", current_component); } for (NodeIteratorType inode = r_model_part.NodesBegin(); inode != r_model_part.NodesEnd(); ++inode){ const array_1d <double, 3>& gradient_of_component = inode->FastGetSolutionStepValue(vector_component_gradient_container); const array_1d <double, 3>& velocity = inode->FastGetSolutionStepValue(VELOCITY); array_1d <double, 3>& material_derivative = inode->FastGetSolutionStepValue(material_derivative_container); material_derivative[current_component] = DEM_INNER_PRODUCT_3(velocity, gradient_of_component); } AddTimeDerivativeComponent(r_model_part, material_derivative_container, current_component); } //************************************************************************************************************************************************** //************************************************************************************************************************************************** template <std::size_t TDim> void DerivativeRecovery<TDim>::RecoverSuperconvergentMatDeriv(ModelPart& r_model_part, Variable<array_1d<double, 3> >& vector_container, Variable<array_1d<double, 3> >& vector_rate_container, Variable<array_1d<double, 3> >& material_derivative_container) { mCalculatingTheGradient = true; if (mFirstGradientRecovery){ KRATOS_INFO("SwimmingDEM") << "Constructing first-step neighbour clouds for material derivative..." << std::endl; SetNeighboursAndWeights(r_model_part); mFirstGradientRecovery = false; KRATOS_INFO("SwimmingDEM") << "Finished constructing neighbour clouds for material derivative." << std::endl; } if (mSomeCloudsDontWork){ // a default value is necessary in the cases where recovery is not possible CalculateVectorMaterialDerivative(r_model_part, vector_container, vector_rate_container, material_derivative_container); } // Solving least squares problem (Zhang, 2006) unsigned int n_relevant_terms = 3; std::vector<array_1d <double, 3> > polynomial_coefficients; // vector to store, for each node, the corresponding values of the polynomial coefficients relevant for the calculation of the material derivative polynomial_coefficients.resize(n_relevant_terms); for (NodeIteratorType inode = r_model_part.NodesBegin(); inode != r_model_part.NodesEnd(); ++inode){ GlobalPointersVector<Node<3> >& neigh_nodes = inode->GetValue(NEIGHBOUR_NODES); unsigned int n_neigh = neigh_nodes.size(); if (!n_neigh){ // then we keep the defualt value continue; } for (unsigned int i = 0; i < n_relevant_terms; ++i){ // resetting polynomial_coefficients to 0 polynomial_coefficients[i] = ZeroVector(3); } const Vector& nodal_weights = inode->FastGetSolutionStepValue(NODAL_WEIGHTS); for (unsigned int k = 0; k < TDim; ++k){ for (unsigned int i_neigh = 0; i_neigh < n_neigh; ++i_neigh){ const array_1d<double, 3>& neigh_nodal_value = neigh_nodes[i_neigh].FastGetSolutionStepValue(vector_container); for (unsigned int d = 0; d < n_relevant_terms; ++d){ polynomial_coefficients[d][k] += nodal_weights[n_relevant_terms * i_neigh + d] * neigh_nodal_value[k]; } } } array_1d <double, 3>& recovered_mat_deriv = inode->FastGetSolutionStepValue(material_derivative_container); const array_1d <double, 3>& velocity = inode->FastGetSolutionStepValue(vector_container); recovered_mat_deriv[0] = velocity[0] * polynomial_coefficients[0][0] + velocity[1] * polynomial_coefficients[1][0] + velocity[2] * polynomial_coefficients[2][0]; recovered_mat_deriv[1] = velocity[0] * polynomial_coefficients[0][1] + velocity[1] * polynomial_coefficients[1][1] + velocity[2] * polynomial_coefficients[2][1]; recovered_mat_deriv[2] = velocity[0] * polynomial_coefficients[0][2] + velocity[1] * polynomial_coefficients[1][2] + velocity[2] * polynomial_coefficients[2][2]; } AddTimeDerivative(r_model_part, material_derivative_container); mCalculatingTheGradient = false; } //************************************************************************************************************************************************** //************************************************************************************************************************************************** // This function adds the contribution to the vorticity corresponding to the pre-computed gradient of one velocity component template <std::size_t TDim> void DerivativeRecovery<TDim>::CalculateVorticityFromGradient(ModelPart& r_model_part, Variable<array_1d<double, 3> >& vector_gradient_container_x, Variable<array_1d<double, 3> >& vector_gradient_container_y, Variable<array_1d<double, 3> >& vector_gradient_container_z, Variable<array_1d<double, 3> >& vorticity_container) { #pragma omp parallel for for (int i = 0; i < (int)r_model_part.Nodes().size(); ++i){ NodeIteratorType i_particle = r_model_part.NodesBegin() + i; Node<3>::Pointer p_node = *(i_particle.base()); array_1d<double, 3>& vorticity = p_node->FastGetSolutionStepValue(vorticity_container); const array_1d<double, 3>& gradient_x = p_node->FastGetSolutionStepValue(vector_gradient_container_x); const array_1d<double, 3>& gradient_y = p_node->FastGetSolutionStepValue(vector_gradient_container_y); const array_1d<double, 3>& gradient_z = p_node->FastGetSolutionStepValue(vector_gradient_container_z); vorticity[0] = gradient_z[1] - gradient_y[2]; vorticity[1] = gradient_x[2] - gradient_z[0]; vorticity[2] = gradient_y[0] - gradient_x[1]; } } //************************************************************************************************************************************************** //************************************************************************************************************************************************** // This function adds the contribution to the vorticity corresponding to the pre-computed gradient of one velocity component template <std::size_t TDim> void DerivativeRecovery<TDim>::CalculateVorticityContributionOfTheGradientOfAComponent(ModelPart& r_model_part, Variable<array_1d<double, 3> >& vector_component_gradient_container, Variable<array_1d<double, 3> >& vorticity_container) { int current_component = r_model_part.GetProcessInfo()[CURRENT_COMPONENT]; if (current_component != 0 && current_component != 1 && current_component != 2){ KRATOS_THROW_ERROR(std::invalid_argument,"The value of CURRENT_COMPONENT passed to the ComputeComponentGradientSimplex element is not 0, 1 or 2, but ", current_component); } for (NodeIteratorType inode = r_model_part.NodesBegin(); inode != r_model_part.NodesEnd(); ++inode){ const array_1d <double, 3>& gradient_of_component = inode->FastGetSolutionStepValue(vector_component_gradient_container); array_1d <double, 3>& vorticity = inode->FastGetSolutionStepValue(vorticity_container); if (current_component == 0){ vorticity[1] += gradient_of_component[2]; vorticity[2] -= gradient_of_component[1]; } else if (current_component == 1){ vorticity[0] -= gradient_of_component[2]; vorticity[2] += gradient_of_component[0]; } else { vorticity[0] += gradient_of_component[1]; vorticity[1] -= gradient_of_component[0]; } } } //************************************************************************************************************************************************** //************************************************************************************************************************************************** template <std::size_t TDim> template <class TScalarVariable> void DerivativeRecovery<TDim>::CalculateGradient(ModelPart& r_model_part, TScalarVariable& scalar_container, Variable<array_1d<double, 3> >& gradient_container) { for (NodeIteratorType inode = r_model_part.NodesBegin(); inode != r_model_part.NodesEnd(); ++inode){ noalias(inode->FastGetSolutionStepValue(gradient_container)) = ZeroVector(3); } array_1d <double, 3> grad = ZeroVector(3); // its dimension is always 3 array_1d <double, TDim + 1 > elemental_values; array_1d <double, TDim + 1 > N; // shape functions vector BoundedMatrix<double, TDim + 1, TDim> DN_DX; for (ModelPart::ElementIterator ielem = r_model_part.ElementsBegin(); ielem != r_model_part.ElementsEnd(); ++ielem){ // computing the shape function derivatives Geometry<Node<3> >& geom = ielem->GetGeometry(); double Volume; GeometryUtils::CalculateGeometryData(geom, DN_DX, N, Volume); // getting the gradients; for (unsigned int i = 0; i < TDim + 1; ++i){ elemental_values[i] = geom[i].FastGetSolutionStepValue(scalar_container); } array_1d <double, TDim> grad_aux = prod(trans(DN_DX), elemental_values); // its dimension may be 2 for (unsigned int i = 0; i < TDim; ++i){ grad[i] = grad_aux[i]; } double nodal_area = Volume / static_cast<double>(TDim + 1); grad *= nodal_area; for (unsigned int i = 0; i < TDim + 1; ++i){ geom[i].FastGetSolutionStepValue(gradient_container) += grad; } } for (NodeIteratorType inode = r_model_part.NodesBegin(); inode != r_model_part.NodesEnd(); ++inode){ inode->FastGetSolutionStepValue(gradient_container) /= inode->FastGetSolutionStepValue(NODAL_AREA); } } //************************************************************************************************************************************************** //************************************************************************************************************************************************** template <std::size_t TDim> void DerivativeRecovery<TDim>::SmoothVectorField(ModelPart& r_model_part, Variable<array_1d<double, 3> >& vector_field, Variable<array_1d<double, 3> >& auxiliary_veriable) { for (NodeIteratorType inode = r_model_part.NodesBegin(); inode != r_model_part.NodesEnd(); ++inode){ noalias(inode->FastGetSolutionStepValue(auxiliary_veriable)) = ZeroVector(3); } array_1d <double, TDim + 1 > N; // shape functions vector BoundedMatrix<double, TDim + 1, TDim> DN_DX; for (ModelPart::ElementIterator ielem = r_model_part.ElementsBegin(); ielem != r_model_part.ElementsEnd(); ++ielem){ // computing the shape function derivatives Geometry<Node<3> >& geom = ielem->GetGeometry(); double Volume; GeometryUtils::CalculateGeometryData(geom, DN_DX, N, Volume); array_1d <double, 3> average = ZeroVector(3); // its dimension is always 3 for (unsigned int i = 0; i < TDim; ++i){ noalias(average) += geom[i].FastGetSolutionStepValue(vector_field); } double nodal_area = Volume / static_cast<double>(TDim + 1); average *= nodal_area; for (unsigned int i = 0; i < TDim + 1; ++i){ geom[i].FastGetSolutionStepValue(auxiliary_veriable) += average; } } for (NodeIteratorType inode = r_model_part.NodesBegin(); inode != r_model_part.NodesEnd(); ++inode){ noalias(inode->FastGetSolutionStepValue(vector_field)) = inode->FastGetSolutionStepValue(auxiliary_veriable) / (3 * inode->FastGetSolutionStepValue(NODAL_AREA)); } } //************************************************************************************************************************************************** //************************************************************************************************************************************************** template <std::size_t TDim> template <class TScalarVariable> void DerivativeRecovery<TDim>::RecoverSuperconvergentGradient(ModelPart& r_model_part, TScalarVariable& scalar_container, Variable<array_1d<double, 3> >& gradient_container) { mCalculatingTheGradient = true; if (mFirstGradientRecovery){ KRATOS_INFO("SwimmingDEM") << "Constructing first-step neighbour clouds for gradient recovery..." << std::endl; SetNeighboursAndWeights(r_model_part); mFirstGradientRecovery = false; KRATOS_INFO("SwimmingDEM") << "Finished constructing neighbour clouds for gradient recovery." << std::endl; } if (mSomeCloudsDontWork){ // a default value is necessary in the cases where recovery is not possible CalculateGradient(r_model_part, scalar_container, gradient_container); } // Solving least squares problem (Zhang, 2006) for (NodeIteratorType inode = r_model_part.NodesBegin(); inode != r_model_part.NodesEnd(); ++inode){ GlobalPointersVector<Node<3> >& neigh_nodes = inode->GetValue(NEIGHBOUR_NODES); unsigned int n_neigh = neigh_nodes.size(); if (!n_neigh){ // we keep the defualt value continue; } array_1d <double, 3>& recovered_gradient = inode->FastGetSolutionStepValue(gradient_container); recovered_gradient = ZeroVector(3); const Vector& nodal_weights = inode->FastGetSolutionStepValue(NODAL_WEIGHTS); for (unsigned int i_neigh = 0; i_neigh < n_neigh; ++i_neigh){ const double& neigh_nodal_value = neigh_nodes[i_neigh].FastGetSolutionStepValue(scalar_container); for (unsigned int d = 0; d < TDim; ++d){ recovered_gradient[d] += nodal_weights[3 * i_neigh + d] * neigh_nodal_value; } } } mCalculatingTheGradient = false; } //************************************************************************************************************************************************** //************************************************************************************************************************************************** template <std::size_t TDim> void DerivativeRecovery<TDim>::RecoverSuperconvergentLaplacian(ModelPart& r_model_part, Variable<array_1d<double, 3> >& vector_container, Variable<array_1d<double, 3> >& laplacian_container) { mCalculatingTheLaplacian = true; if (mFirstLaplacianRecovery){ KRATOS_INFO("SwimmingDEM") << "Constructing first-step neighbour clouds for laplacian recovery..." << std::endl; SetNeighboursAndWeights(r_model_part); mFirstLaplacianRecovery = false; KRATOS_INFO("SwimmingDEM") << "Finished constructing neighbour clouds for laplacian recovery." << std::endl; } if (mSomeCloudsDontWork){ // a default value is necessary in the cases where recovery is not possible CalculateVectorLaplacian(r_model_part, vector_container, laplacian_container); } // Solving a least squares problem for every node (Zhang, 2006) unsigned int n_relevant_terms = 6; std::vector<array_1d <double, 3> > polynomial_coefficients; // vector to store, for each node, the corresponding values of the polynomial coefficients relevant for the calculation of the laplacian polynomial_coefficients.resize(n_relevant_terms); for (NodeIteratorType inode = r_model_part.NodesBegin(); inode != r_model_part.NodesEnd(); ++inode){ GlobalPointersVector<Node<3> >& neigh_nodes = inode->GetValue(NEIGHBOUR_NODES); unsigned int n_neigh = neigh_nodes.size(); if (!n_neigh){ // then we keep the defualt value continue; } for (unsigned int i = 0; i < n_relevant_terms; ++i){ // resetting polynomial_coefficients to 0 polynomial_coefficients[i] = ZeroVector(3); } const Vector& nodal_weights = inode->FastGetSolutionStepValue(NODAL_WEIGHTS); array_1d <double, 3>& recovered_laplacian = inode->FastGetSolutionStepValue(laplacian_container); noalias(recovered_laplacian) = ZeroVector(3); for (unsigned int k = 0; k < TDim; ++k){ for (unsigned int i_neigh = 0; i_neigh < n_neigh; ++i_neigh){ const array_1d<double, 3>& neigh_nodal_value = neigh_nodes[i_neigh].FastGetSolutionStepValue(vector_container); for (unsigned int d = 0; d < n_relevant_terms; ++d){ polynomial_coefficients[d][k] += nodal_weights[n_relevant_terms * i_neigh + d] * neigh_nodal_value[k]; } } } recovered_laplacian[0] = 2 * (polynomial_coefficients[3][0] + polynomial_coefficients[4][0] + polynomial_coefficients[5][0]); recovered_laplacian[1] = 2 * (polynomial_coefficients[3][1] + polynomial_coefficients[4][1] + polynomial_coefficients[5][1]); recovered_laplacian[2] = 2 * (polynomial_coefficients[3][2] + polynomial_coefficients[4][2] + polynomial_coefficients[5][2]); // recovered_laplacian[0] = polynomial_coefficients[0][0] + polynomial_coefficients[1][0] + 2 * polynomial_coefficients[3][0]; // recovered_laplacian[1] = polynomial_coefficients[0][0] + polynomial_coefficients[2][0] + 2 * polynomial_coefficients[4][0]; // recovered_laplacian[2] = polynomial_coefficients[1][0] + polynomial_coefficients[2][0] + 2 * polynomial_coefficients[5][0]; } mCalculatingTheLaplacian = false; } //************************************************************************************************************************************************** //************************************************************************************************************************************************** template <std::size_t TDim> void DerivativeRecovery<TDim>::RecoverSuperconvergentVelocityLaplacianFromGradient(ModelPart& r_model_part, Variable<array_1d<double, 3> >& vector_container, Variable<array_1d<double, 3> >& laplacian_container) { mCalculatingTheGradient = true; if (mFirstLaplacianRecovery){ KRATOS_INFO("SwimmingDEM") << "Finished constructing neighbour clouds for laplacian recovery." << std::endl; SetNeighboursAndWeights(r_model_part); mFirstLaplacianRecovery = false; KRATOS_INFO("SwimmingDEM") << "Finished constructing neighbour clouds for laplacian recovery." << std::endl; } if (mSomeCloudsDontWork){ // a default value is necessary in the cases where recovery is not possible CalculateVectorLaplacian(r_model_part, vector_container, laplacian_container); } // Solving least squares problem (Zhang, 2006) unsigned int n_relevant_terms = 3; std::vector<array_1d <double, 3> > polynomial_coefficients; // vector to store, for each node, the corresponding values of the polynomial coefficients relevant for the calculation of the laplacian polynomial_coefficients.resize(n_relevant_terms); array_1d< array_1d<double, 3>, 3> gradient; for (NodeIteratorType inode = r_model_part.NodesBegin(); inode != r_model_part.NodesEnd(); ++inode){ GlobalPointersVector<Node<3> >& neigh_nodes = inode->GetValue(NEIGHBOUR_NODES); unsigned int n_neigh = neigh_nodes.size(); if (!n_neigh){ // then we keep the defualt value continue; } for (unsigned int i = 0; i < n_relevant_terms; ++i){ // resetting polynomial_coefficients to 0 polynomial_coefficients[i] = ZeroVector(3); } const Vector& nodal_weights = inode->FastGetSolutionStepValue(NODAL_WEIGHTS); array_1d <double, 3>& recovered_laplacian = inode->FastGetSolutionStepValue(laplacian_container); recovered_laplacian = ZeroVector(3); for (unsigned int i_neigh = 0; i_neigh < n_neigh; ++i_neigh){ noalias(gradient[0]) = neigh_nodes[i_neigh].FastGetSolutionStepValue(VELOCITY_X_GRADIENT); noalias(gradient[1]) = neigh_nodes[i_neigh].FastGetSolutionStepValue(VELOCITY_Y_GRADIENT); noalias(gradient[2]) = neigh_nodes[i_neigh].FastGetSolutionStepValue(VELOCITY_Z_GRADIENT); recovered_laplacian[0] += nodal_weights[n_relevant_terms * i_neigh] * gradient[0][0]; recovered_laplacian[0] += nodal_weights[n_relevant_terms * i_neigh + 1] * gradient[0][1]; recovered_laplacian[0] += nodal_weights[n_relevant_terms * i_neigh + 2] * gradient[0][2]; recovered_laplacian[1] += nodal_weights[n_relevant_terms * i_neigh] * gradient[1][0]; recovered_laplacian[1] += nodal_weights[n_relevant_terms * i_neigh + 1] * gradient[1][1]; recovered_laplacian[1] += nodal_weights[n_relevant_terms * i_neigh + 2] * gradient[1][2]; recovered_laplacian[2] += nodal_weights[n_relevant_terms * i_neigh] * gradient[2][0]; recovered_laplacian[2] += nodal_weights[n_relevant_terms * i_neigh + 1] * gradient[2][1]; recovered_laplacian[2] += nodal_weights[n_relevant_terms * i_neigh + 2] * gradient[2][2]; } } mCalculatingTheGradient = false; } //************************************************************************************************************************************************** //************************************************************************************************************************************************** template <std::size_t TDim> void DerivativeRecovery<TDim>::RecoverSuperconvergentMatDerivAndLaplacian(ModelPart& r_model_part, Variable<array_1d<double, 3> >& vector_container, Variable<array_1d<double, 3> >& vector_rate_container, Variable<array_1d<double, 3> >& material_derivative_container, Variable<array_1d<double, 3> >& laplacian_container) { mCalculatingGradientAndLaplacian = true; if (mFirstLaplacianRecovery){ KRATOS_INFO("SwimmingDEM") << "Constructing first-step neighbour clouds for material derivative and laplacian recovery..." << std::endl; SetNeighboursAndWeights(r_model_part); mFirstLaplacianRecovery = false; KRATOS_INFO("SwimmingDEM") << "Finished constructing neighbour clouds for material derivative and laplacian recovery." << std::endl; } if (mSomeCloudsDontWork){ // a default value is necessary in the cases where recovery is not possible CalculateVectorLaplacian(r_model_part, vector_container, laplacian_container); CalculateVectorMaterialDerivative(r_model_part, vector_container, vector_rate_container, material_derivative_container); } // Solving least squares problem (Zhang, 2006) unsigned int n_relevant_terms = 9; std::vector<array_1d <double, 3> > polynomial_coefficients; // vector to store, for each node, the corresponding values of the polynomial coefficients relevant for the calculation of the laplacian and the material derivative polynomial_coefficients.resize(n_relevant_terms); for (NodeIteratorType inode = r_model_part.NodesBegin(); inode != r_model_part.NodesEnd(); ++inode){ GlobalPointersVector<Node<3> >& neigh_nodes = inode->GetValue(NEIGHBOUR_NODES); unsigned int n_neigh = neigh_nodes.size(); if (!n_neigh){ // then we keep the defualt value continue; } for (unsigned int i = 0; i < n_relevant_terms; ++i){ // resetting polynomial_coefficients to 0 polynomial_coefficients[i] = ZeroVector(3); } const Vector& nodal_weights = inode->FastGetSolutionStepValue(NODAL_WEIGHTS); for (unsigned int k = 0; k < TDim; ++k){ for (unsigned int i_neigh = 0; i_neigh < n_neigh; ++i_neigh){ const array_1d<double, 3>& neigh_nodal_value = neigh_nodes[i_neigh].FastGetSolutionStepValue(vector_container); for (unsigned int d = 0; d < n_relevant_terms; ++d){ polynomial_coefficients[d][k] += nodal_weights[n_relevant_terms * i_neigh + d] * neigh_nodal_value[k]; } } } array_1d <double, 3>& recovered_laplacian = inode->FastGetSolutionStepValue(laplacian_container); array_1d <double, 3>& recovered_mat_deriv = inode->FastGetSolutionStepValue(material_derivative_container); const array_1d <double, 3>& velocity = inode->FastGetSolutionStepValue(vector_container); recovered_mat_deriv[0] = velocity[0] * polynomial_coefficients[0][0] + velocity[1] * polynomial_coefficients[1][0] + velocity[2] * polynomial_coefficients[2][0]; recovered_mat_deriv[1] = velocity[0] * polynomial_coefficients[0][1] + velocity[1] * polynomial_coefficients[1][1] + velocity[2] * polynomial_coefficients[2][1]; recovered_mat_deriv[2] = velocity[0] * polynomial_coefficients[0][2] + velocity[1] * polynomial_coefficients[1][2] + velocity[2] * polynomial_coefficients[2][2]; recovered_laplacian[0] = 2 * (polynomial_coefficients[6][0] + polynomial_coefficients[7][0] + polynomial_coefficients[8][0]); recovered_laplacian[1] = 2 * (polynomial_coefficients[6][1] + polynomial_coefficients[7][1] + polynomial_coefficients[8][1]); recovered_laplacian[2] = 2 * (polynomial_coefficients[6][2] + polynomial_coefficients[7][2] + polynomial_coefficients[8][2]); } AddTimeDerivative(r_model_part, material_derivative_container); mCalculatingGradientAndLaplacian = false; } //************************************************************************************************************************************************** //************************************************************************************************************************************************** template <std::size_t TDim> void DerivativeRecovery<TDim>::CalculateVectorLaplacian(ModelPart& r_model_part, Variable<array_1d<double, 3> >& vector_container, Variable<array_1d<double, 3> >& laplacian_container) { KRATOS_INFO("SwimmingDEM") << "Constructing the Laplacian by derivating nodal averages..." << std::endl; std::map <std::size_t, unsigned int> id_to_position; unsigned int entry = 0; for (NodeIteratorType inode = r_model_part.NodesBegin(); inode != r_model_part.NodesEnd(); ++inode){ noalias(inode->FastGetSolutionStepValue(laplacian_container)) = ZeroVector(3); id_to_position[inode->Id()] = entry; ++entry; } std::vector<array_1d <double, 3> > laplacians; laplacians.resize(entry); std::fill(laplacians.begin(), laplacians.end(), ZeroVector(3)); array_1d <double, 3> grad = ZeroVector(3); array_1d <double, TDim + 1 > elemental_values; array_1d <double, TDim + 1 > N; // shape functions vector BoundedMatrix<double, TDim + 1, TDim> DN_DX; BoundedMatrix<double, TDim + 1, TDim> elemental_vectors; // They carry the nodal gradients of the corresponding component v_j const double nodal_area_share = 1.0 / static_cast<double>(TDim + 1); for (unsigned int j = 0; j < TDim; ++j){ // for each component of the original vector value // for each element, constructing the gradient contribution (to its nodes) of the component v_j and storing it in laplacian_container for (ModelPart::ElementIterator ielem = r_model_part.ElementsBegin(); ielem != r_model_part.ElementsEnd(); ++ielem){ // computing the shape function derivatives Geometry<Node<3> >& geom = ielem->GetGeometry(); double Volume; GeometryUtils::CalculateGeometryData(geom, DN_DX, N, Volume); for (unsigned int i = 0; i < TDim + 1; ++i){ elemental_values[i] = geom[i].FastGetSolutionStepValue(vector_container)[j]; } array_1d <double, TDim> grad_aux = prod(trans(DN_DX), elemental_values); // its dimension may be 2 for (unsigned int i = 0; i < TDim; ++i){ grad[i] = grad_aux[i]; } double nodal_area = Volume * nodal_area_share; grad *= nodal_area; for (unsigned int i = 0; i < TDim + 1; ++i){ geom[i].FastGetSolutionStepValue(laplacian_container) += grad; // we use laplacian_container to store the gradient of one component at a time } } // normalizing the contributions to the gradient for (NodeIteratorType inode = r_model_part.NodesBegin(); inode != r_model_part.NodesEnd(); ++inode){ inode->FastGetSolutionStepValue(laplacian_container) /= inode->FastGetSolutionStepValue(NODAL_AREA); } // for each element, constructing the divergence contribution (to its nodes) of the gradient of component v_j for (ModelPart::ElementIterator ielem = r_model_part.ElementsBegin(); ielem != r_model_part.ElementsEnd(); ++ielem){ Geometry<Node<3> >& geom = ielem->GetGeometry(); double Volume; GeometryUtils::CalculateGeometryData(geom, DN_DX, N, Volume); for (unsigned int i = 0; i < TDim + 1; ++i){ for (unsigned int k = 0; k < TDim; ++k){ elemental_vectors(i, k) = geom[i].FastGetSolutionStepValue(laplacian_container)[k]; // it is actually the gradient of component v_j } } BoundedMatrix<double, TDim, TDim> grad_aux = prod(trans(DN_DX), elemental_vectors); // its dimension may be 2 double divergence_of_vi = 0.0; for (unsigned int k = 0; k < TDim; ++k){ // the divergence is the trace of the gradient divergence_of_vi += grad_aux(k, k); } double nodal_area = Volume / static_cast<double>(TDim + 1); divergence_of_vi *= nodal_area; for (unsigned int i = 0; i < TDim + 1; ++i){ laplacians[id_to_position[geom[i].Id()]][j] += divergence_of_vi; // adding the contribution of the elemental divergence to each of its nodes } } // clearing the values stored in laplacian_container for the next component for (NodeIteratorType inode = r_model_part.NodesBegin(); inode != r_model_part.NodesEnd(); ++inode){ array_1d <double, 3>& current_gradient_of_vi = inode->FastGetSolutionStepValue(laplacian_container); noalias(current_gradient_of_vi) = ZeroVector(3); } } // for each component of the vector value for (NodeIteratorType inode = r_model_part.NodesBegin(); inode != r_model_part.NodesEnd(); ++inode){ array_1d <double, 3>& stored_laplacian = laplacians[id_to_position[inode->Id()]]; array_1d <double, 3>& laplacian = inode->FastGetSolutionStepValue(laplacian_container); noalias(laplacian) = stored_laplacian / inode->FastGetSolutionStepValue(NODAL_AREA); } KRATOS_INFO("SwimmingDEM") << "Finished constructing the Laplacian by derivating nodal averages..." << std::endl; } //************************************************************************************************************************************************** //************************************************************************************************************************************************** template <std::size_t TDim> void DerivativeRecovery<TDim>::CalculateVelocityLaplacianRate(ModelPart& r_model_part) { double delta_t_inv = 1.0 / r_model_part.GetProcessInfo()[DELTA_TIME]; DenseVector<unsigned int> nodes_partition; OpenMPUtils::CreatePartition(OpenMPUtils::GetNumThreads(), r_model_part.Nodes().size(), nodes_partition); #pragma omp parallel for for (int k = 0; k < OpenMPUtils::GetNumThreads(); ++k){ NodesArrayType& pNodes = r_model_part.GetCommunicator().LocalMesh().Nodes(); NodeIteratorType node_begin = pNodes.ptr_begin() + nodes_partition[k]; NodeIteratorType node_end = pNodes.ptr_begin() + nodes_partition[k + 1]; for (ModelPart::NodesContainerType::iterator inode = node_begin; inode != node_end; ++inode){ array_1d <double, 3>& laplacian_rate = inode->FastGetSolutionStepValue(VELOCITY_LAPLACIAN_RATE); array_1d <double, 3>& laplacian = inode->FastGetSolutionStepValue(VELOCITY_LAPLACIAN); array_1d <double, 3>& old_laplacian = inode->FastGetSolutionStepValue(VELOCITY_LAPLACIAN, 1); noalias(laplacian_rate) = delta_t_inv * (laplacian - old_laplacian); } } } //************************************************************************************************************************************************** //************************************************************************************************************************************************** // P R I V A T E M E T H O D S //************************************************************************************************************************************************** //************************************************************************************************************************************************** template <std::size_t TDim> void DerivativeRecovery<TDim>::SetNeighboursAndWeights(ModelPart& r_model_part) { // Finding elements concurrent to each node. The nodes of these elements will form the initial cloud of points FindNodalNeighboursProcess neighbour_finder(r_model_part); neighbour_finder.Execute(); const unsigned int n_max_iterations = 100; unsigned int i = 0; for (NodeIteratorType inode = r_model_part.NodesBegin(); inode != r_model_part.NodesEnd(); ++inode){ bool the_cloud_of_neighbours_is_successful = SetInitialNeighboursAndWeights(r_model_part, *(inode.base())); GlobalPointersVector<Node<3> >& neigh_nodes = inode->GetValue(NEIGHBOUR_NODES); unsigned int iteration = 0; while (!the_cloud_of_neighbours_is_successful && iteration < n_max_iterations){ the_cloud_of_neighbours_is_successful = SetNeighboursAndWeights(r_model_part, *(inode.base())); ++iteration; } if (iteration >= n_max_iterations){ // giving up on this method, settling for the default method mSomeCloudsDontWork = true; neigh_nodes.clear(); inode->FastGetSolutionStepValue(NODAL_WEIGHTS).clear(); KRATOS_WARNING("SwimmingDEM") << "Warning!, for the node with id " << inode->Id() << " it has not been possible to form an adequate cloud of neighbours" << std::endl; KRATOS_WARNING("SwimmingDEM") << "for the gradient recovery. A lower accuracy method has been employed for this node." << std::endl; } ++i; } } //************************************************************************************************************************************************** //************************************************************************************************************************************************** template <std::size_t TDim> void DerivativeRecovery<TDim>::SetNeighboursAndWeightsForTheLaplacian(ModelPart& r_model_part) { // Finding elements concurrent to each node. The nodes of these elements will form the initial cloud of points FindNodalNeighboursProcess neighbour_finder(r_model_part); neighbour_finder.Execute(); const unsigned int n_max_iterations = 100; unsigned int i = 0; for (NodeIteratorType inode = r_model_part.NodesBegin(); inode != r_model_part.NodesEnd(); ++inode){ bool the_cloud_of_neighbours_is_successful = SetInitialNeighboursAndWeights(r_model_part, *(inode.base())); GlobalPointersVector<Node<3> >& neigh_nodes = inode->GetValue(NEIGHBOUR_NODES); unsigned int iteration = 0; while (!the_cloud_of_neighbours_is_successful && iteration < n_max_iterations){ the_cloud_of_neighbours_is_successful = SetNeighboursAndWeights(r_model_part, *(inode.base())); ++iteration; } if (iteration >= n_max_iterations){ // giving up on this method, settling for the default method mSomeCloudsDontWork = true; neigh_nodes.clear(); inode->FastGetSolutionStepValue(NODAL_WEIGHTS).clear(); KRATOS_WARNING("SwimmingDEM") << "Warning!, for the node with id " << inode->Id() << " it has not been possible to form an adequate cloud of neighbours" << std::endl; KRATOS_WARNING("SwimmingDEM") << "for the gradient recovery. A lower accuracy method has been employed for this node." << std::endl; } ++i; } } //************************************************************************************************************************************************** //************************************************************************************************************************************************** template <std::size_t TDim> void DerivativeRecovery<TDim>::OrderByDistance(Node<3>::Pointer &p_node, GlobalPointersVector<Node<3> >& neigh_nodes) { const unsigned int n_nodes = neigh_nodes.size(); std::vector<double> distances_squared; distances_squared.resize(n_nodes); const array_1d <double, 3>& origin = p_node->Coordinates(); for (unsigned int i = 0; i < n_nodes; ++i){ const array_1d <double, 3> rel_coordinates = (neigh_nodes[i] - origin); distances_squared[i] = DEM_INNER_PRODUCT_3(rel_coordinates, rel_coordinates); } std::vector <std::pair<unsigned int, double> > ordering; ordering.resize(n_nodes); for (unsigned int i = 0; i < n_nodes; ++i){ ordering[i] = std::make_pair(i, distances_squared[i]); } std::sort(ordering.begin(), ordering.end(), IsCloser()); GlobalPointersVector<Node<3> > ordered_neighbours; for (unsigned int i = 0; i < n_nodes; ++i){ Node<3>::WeakPointer& p_neigh = neigh_nodes(ordering[i].first); ordered_neighbours.push_back(p_neigh); } ordered_neighbours.swap(neigh_nodes); } //************************************************************************************************************************************************** //************************************************************************************************************************************************** template <std::size_t TDim> bool DerivativeRecovery<TDim>::SetInitialNeighboursAndWeights(ModelPart& r_model_part, Node<3>::Pointer &p_node) { GlobalPointersVector<Element>& neigh_elems = p_node->GetValue(NEIGHBOUR_ELEMENTS); GlobalPointersVector<Node<3> >& neigh_nodes = p_node->GetValue(NEIGHBOUR_NODES); std::map<std::size_t, std::size_t> ids; // map to keep track of all different ids corresponding to already added neighbours to avoid repetition ids[p_node->Id()] = p_node->Id(); unsigned int i = 0; for (unsigned int i_el = 0; i_el < neigh_elems.size(); ++i_el){ Geometry<Node<3> >& geom = neigh_elems[i_el].GetGeometry(); unsigned int jj = 0; // index of the node in geom corresponding to neighbour neigh_elems[i_el] if (geom[jj].Id() == p_node->Id()){ // skipping itself ++jj; } for (unsigned int j = 0; j < TDim; ++j){ Node<3>::Pointer p_neigh = geom(jj); if (ids.find(p_neigh->Id()) == ids.end()){ neigh_nodes.push_back(p_neigh); ids[p_neigh->Id()] = p_neigh->Id(); } } i += TDim; } OrderByDistance(p_node, neigh_nodes); if (neigh_nodes.size() < 10){ // Not worthwhile checking, since there are 10 independent coefficients to be determined return false; } else { return SetWeightsAndRunLeastSquaresTest(r_model_part, p_node); } } //************************************************************************************************************************************************** //************************************************************************************************************************************************** template <std::size_t TDim> bool DerivativeRecovery<TDim>::SetNeighboursAndWeights(ModelPart& r_model_part, Node<3>::Pointer& p_node) { GlobalPointersVector<Node<3> >& neigh_nodes = p_node->GetValue(NEIGHBOUR_NODES); const unsigned int node_increase_per_neighbour = 1; const unsigned int node_increase_overall = 1; std::map<std::size_t, std::size_t> ids; ids[p_node->Id()] = p_node->Id(); for (unsigned int i = 0; i < (unsigned int)neigh_nodes.size(); ++i){ auto p_neigh = neigh_nodes(i); ids[p_neigh->Id()] = p_neigh->Id(); } const unsigned int n_neigh = neigh_nodes.size(); for (unsigned int i = 0; i < n_neigh; ++i){ auto p_neigh = neigh_nodes(i); GlobalPointersVector<Node<3> >& neigh_neigh_nodes = p_neigh->GetValue(NEIGHBOUR_NODES); unsigned int n_new_nodes = 0; for (unsigned int j = 0; j < (unsigned int)neigh_neigh_nodes.size(); ++j){ auto p_neigh_neigh = neigh_neigh_nodes(j); if (ids.find(p_neigh_neigh->Id()) == ids.end()){ neigh_nodes.push_back(p_neigh_neigh); ids[p_neigh_neigh->Id()] = p_neigh_neigh->Id(); ++n_new_nodes; } if (n_new_nodes >= node_increase_per_neighbour){ break; } } } OrderByDistance(p_node, neigh_nodes); const unsigned int new_size = std::min(n_neigh + node_increase_overall, (unsigned int)neigh_nodes.size()); neigh_nodes.resize(new_size); // keeping only nearest nodes if (neigh_nodes.size() < 10){ // it is not worthwhile checking, since there are 10 independent coefficients to be determined return false; } else { return SetWeightsAndRunLeastSquaresTest(r_model_part, p_node); } } //************************************************************************************************************************************************** //************************************************************************************************************************************************** template <std::size_t TDim> double DerivativeRecovery<TDim>::SecondDegreeTestPolynomial(const array_1d <double, 3>& coordinates) { const double x = coordinates[0]; const double y = coordinates[1]; const double z = coordinates[2]; return 1.0 + x + y + z + x * y + x * z + y * z + x * x + y * y + z * z; } //************************************************************************************************************************************************** //************************************************************************************************************************************************** template <std::size_t TDim> double DerivativeRecovery<TDim>::SecondDegreeGenericPolynomial(DenseMatrix<double> C, const array_1d <double, 3>& coordinates) { const double x = coordinates[0]; const double y = coordinates[1]; const double z = coordinates[2]; return C(0,0) + C(1,0) * x + C(2,0) * y + C(3,0) * z + C(4,0) * x * y + C(5,0) * x * z + C(6,0) * y * z + C(7,0) * x * x + C(8,0) * y * y + C(9,0) * z * z; } //************************************************************************************************************************************************** //************************************************************************************************************************************************** template <std::size_t TDim> inline int DerivativeRecovery<TDim>:: Factorial(const unsigned int n){ if (n == 0){ return 1; } unsigned int k = n; for (unsigned int i = n - 1; i > 0; --i){ k *= i; } return k; } //************************************************************************************************************************************************** //************************************************************************************************************************************************** template <std::size_t TDim> bool DerivativeRecovery<TDim>::SetWeightsAndRunLeastSquaresTest(ModelPart& r_model_part, Node<3>::Pointer& p_node) { unsigned int n_poly_terms = Factorial(TDim + 2) / (2 * Factorial(TDim)); // 2 is the polynomial order if (TDim == 2){ KRATOS_THROW_ERROR(std::runtime_error, "Gradient recovery not implemented yet in 2D!)",""); } GlobalPointersVector<Node<3> >& neigh_nodes = p_node->GetValue(NEIGHBOUR_NODES); unsigned int n_nodal_neighs = (unsigned int)neigh_nodes.size(); const double h_inv = 1.0 / CalculateTheMaximumDistanceToNeighbours(p_node); // we use it as a scaling parameter to improve stability const array_1d <double, 3> origin = p_node->Coordinates(); DenseMatrix<double> TestNodalValues(n_nodal_neighs, 1); DenseMatrix<double> A(n_nodal_neighs, n_poly_terms); for (unsigned int i = 0; i < n_nodal_neighs; ++i){ A(i, 0) = 1.0; if (TDim == 3){ Node<3>& neigh = neigh_nodes[i]; const array_1d <double, 3> rel_coordinates = (neigh.Coordinates() - origin) * h_inv; TestNodalValues(i, 0) = SecondDegreeTestPolynomial(rel_coordinates); for (unsigned int d = 1; d < 10; ++d){ if (d < 4){ A(i, d) = rel_coordinates[d - 1]; } else if (d == 4){ A(i, d) = rel_coordinates[0] * rel_coordinates[1]; } else if (d == 5){ A(i, d) = rel_coordinates[0] * rel_coordinates[2]; } else if (d == 6){ A(i, d) = rel_coordinates[1] * rel_coordinates[2]; } else { A(i, d) = rel_coordinates[d - 7] * rel_coordinates[d - 7]; } } } else { KRATOS_THROW_ERROR(std::runtime_error,"Gradient recovery not implemented yet in 2D!)",""); } } DenseMatrix<double>AtransA(n_poly_terms, n_poly_terms); noalias(AtransA) = prod(trans(A), A); if (std::abs(mMyCustomFunctions.template determinant< DenseMatrix<double> >(AtransA)) < 0.01){ return false; } else { unsigned int n_relevant_terms = 0; if (mCalculatingTheGradient){ n_relevant_terms = TDim; } else if (mCalculatingTheLaplacian){ n_relevant_terms = n_poly_terms - (TDim + 1); } else { n_relevant_terms = n_poly_terms - 1; } std::vector<unsigned int> relevant_terms; relevant_terms.resize(n_relevant_terms); double normalization = 1.0; if (mCalculatingTheGradient){ normalization = h_inv; relevant_terms[0] = 1; relevant_terms[1] = 2; relevant_terms[2] = 3; } else if (mCalculatingTheLaplacian){ normalization = h_inv * h_inv; relevant_terms[0] = 4; relevant_terms[1] = 5; relevant_terms[2] = 6; relevant_terms[3] = 7; relevant_terms[4] = 8; relevant_terms[5] = 9; } else { for (unsigned int i = 1; i < n_poly_terms; ++i){ relevant_terms[i - 1] = i; } } Vector& nodal_weights = p_node->FastGetSolutionStepValue(NODAL_WEIGHTS); nodal_weights.resize(n_relevant_terms * n_nodal_neighs); const DenseMatrix<double> AtransAinv = mMyCustomFunctions.Inverse(AtransA); // for (unsigned i = 0; i < n_poly_terms; i++){ // for (unsigned j = 0; j < n_poly_terms; j++){ // if (abs(AtransAinv(i,j))>1e6){ // return false; // } // } // } DenseMatrix<double>AtransAinvAtrans(n_poly_terms, n_nodal_neighs); noalias(AtransAinvAtrans) = prod(AtransAinv, trans(A)); for (unsigned int i = 0; i < n_nodal_neighs; ++i){ for (unsigned int d = 0; d < n_relevant_terms; ++d){ if (mCalculatingGradientAndLaplacian){ if (d > 2){ normalization = h_inv * h_inv; } else { normalization = h_inv; } } nodal_weights(n_relevant_terms * i + d) = AtransAinvAtrans(relevant_terms[d], i) * normalization; } } DenseMatrix<double> C(n_nodal_neighs, 1); C = prod(AtransAinvAtrans, TestNodalValues); double abs_difference = 0.0; for (unsigned int i = 0; i < n_nodal_neighs; ++i){ const array_1d <double, 3>& rel_coordinates = (neigh_nodes[i].Coordinates() - origin) * h_inv; abs_difference += std::abs(SecondDegreeGenericPolynomial(C, rel_coordinates) - SecondDegreeTestPolynomial(rel_coordinates)); } // abs_difference = abs(C(7, 0) - 1.0) + abs(C(8, 0) - 1.0) + abs(C(8, 0) - 1.0); const double tolerance = 0.001; // recommended by E Ortega return (abs_difference > tolerance? false : true); } } //************************************************************************************************************************************************** //************************************************************************************************************************************************** template <std::size_t TDim> unsigned int DerivativeRecovery<TDim>::GetNumberOfUniqueNeighbours(const int my_id, const GlobalPointersVector<Element>& my_neighbour_elements) { std::vector<int> ids; ids.push_back(my_id); for (unsigned int i_el = 0; i_el < my_neighbour_elements.size(); ++i_el){ const Geometry<Node<3> >& geom = my_neighbour_elements[i_el].GetGeometry(); for (unsigned int jj = 0; jj < TDim + 1; ++jj){ int id = (int)geom[jj].Id(); std::vector<int>::iterator it; it = find(ids.begin(), ids.end(), id); if (it >= ids.end()){ ids.push_back(id); } } } return (int)ids.size(); } //************************************************************************************************************************************************** //************************************************************************************************************************************************** template <std::size_t TDim> double DerivativeRecovery<TDim>::CalculateTheMaximumDistanceToNeighbours(Node<3>::Pointer& p_node) { double max_distance_yet = 0.0; const array_1d <double, 3>& coors = p_node->Coordinates(); GlobalPointersVector<Node<3> >& neigh_nodes = p_node->GetValue(NEIGHBOUR_NODES); for (unsigned int i = 0; i < (unsigned int)neigh_nodes.size(); ++i){ array_1d <double, 3> delta = neigh_nodes[i].Coordinates() - coors; double distance_2 = DEM_INNER_PRODUCT_3(delta, delta); max_distance_yet = max_distance_yet > distance_2 ? max_distance_yet : distance_2; } return std::sqrt(max_distance_yet); } //************************************************************************************************************************************************** //************************************************************************************************************************************************** template <std::size_t TDim> double DerivativeRecovery<TDim>::CalculateTheMaximumEdgeLength(ModelPart& r_model_part) { double max_distance_yet = 0.0; for (ModelPart::ElementIterator ielem = r_model_part.ElementsBegin(); ielem != r_model_part.ElementsEnd(); ++ielem){ Geometry<Node<3> >& geom = ielem->GetGeometry(); unsigned int n_nodes = static_cast<unsigned int>(TDim + 1); for (unsigned int k = 1; k < n_nodes - 1; ++k){ for (unsigned int i = k; i < n_nodes; ++i){ array_1d <double, 3> delta_i = geom[k - 1] - geom[i]; double distance_2 = DEM_INNER_PRODUCT_3(delta_i, delta_i); max_distance_yet = max_distance_yet > distance_2 ? max_distance_yet : distance_2; } } } return std::sqrt(max_distance_yet); } //************************************************************************************************************************************************** //************************************************************************************************************************************************** template <std::size_t TDim> double DerivativeRecovery<TDim>::CalculateTheMinumumEdgeLength(ModelPart& r_model_part) { double min_distance_yet = 0.0; bool first_node = true; for (ModelPart::ElementIterator ielem = r_model_part.ElementsBegin(); ielem != r_model_part.ElementsEnd(); ++ielem){ Geometry<Node<3> >& geom = ielem->GetGeometry(); if (first_node){ // assign the distance (squared) between any two nodes to min_distance_yet array_1d <double, 3> delta = geom[0] - geom[1]; double distance_2 = DEM_INNER_PRODUCT_3(delta, delta); min_distance_yet = distance_2; } unsigned int n_nodes = static_cast<unsigned int>(TDim + 1); for (unsigned int k = 1; k < n_nodes - 1; ++k){ for (unsigned int i = k; i < n_nodes; ++i){ array_1d <double, 3> delta_i = geom[k - 1] - geom[i]; double distance_2 = DEM_INNER_PRODUCT_3(delta_i, delta_i); min_distance_yet = min_distance_yet < distance_2 ? min_distance_yet : distance_2; } } } return std::sqrt(min_distance_yet); } //************************************************************************************************************************************************** //************************************************************************************************************************************************** // Explicit instantiations template class DerivativeRecovery<2>; template class DerivativeRecovery<3>; template void KRATOS_API(SWIMMING_DEM_APPLICATION) DerivativeRecovery<2>::RecoverSuperconvergentGradient< Variable<double> >(ModelPart&, Variable<double>&, Variable<array_1d<double, 3> >&); template void KRATOS_API(SWIMMING_DEM_APPLICATION) DerivativeRecovery<3>::RecoverSuperconvergentGradient< Variable<double> >(ModelPart&, Variable<double>&, Variable<array_1d<double, 3> >&); template void KRATOS_API(SWIMMING_DEM_APPLICATION) DerivativeRecovery<2>::CalculateGradient< Variable<double> >(ModelPart&, Variable<double>&, Variable<array_1d<double, 3> >&); template void KRATOS_API(SWIMMING_DEM_APPLICATION) DerivativeRecovery<3>::CalculateGradient< Variable<double> >(ModelPart&, Variable<double>&, Variable<array_1d<double, 3> >&); } // namespace Kratos.
#include "commands/CmdDriveWithXbox.h" #include "GamepadMap.h" #include "frc/smartdashboard/SmartDashboard.h" //Local Prototypes void Drive_Tank(Drivetrain *drivetrain, float left, float right); void Drive_Test1(Drivetrain *drivetrain, float l_y, float l_x, float r_x); void Drive_Test2(Drivetrain *drivetrain, float l_y, float l_x, float r_x); void Drive_Test3(Drivetrain *drivetrain, float l_y, float l_x, float r_x); CmdDriveWithXbox::CmdDriveWithXbox(Drivetrain *drivetrain, frc::XboxController *xbox ) { m_drivetrain = drivetrain; m_xbox = xbox; AddRequirements({m_drivetrain}); } // Called when the command is initially scheduled. void CmdDriveWithXbox::Initialize() { std::cout<<"Starting CmdDriveWithXbox"<<std::endl; } void CmdDriveWithXbox::Execute() { const float DEADBAND = 0.05; //Get joystick axis float left_y_axis = -m_xbox->GetRawAxis(GAMEPADMAP_AXIS_L_Y); //Negate Y joystick so positive is forward float left_x_axis = m_xbox->GetRawAxis(GAMEPADMAP_AXIS_L_X); float right_y_axis = -m_xbox->GetRawAxis(GAMEPADMAP_AXIS_R_Y); //Negate Y joystick so positive is forward float right_x_axis = m_xbox->GetRawAxis(GAMEPADMAP_AXIS_R_X); //Control DeadBand if ( fabs(left_x_axis) <= DEADBAND ) left_x_axis = 0.0; if ( fabs(left_y_axis) <= DEADBAND ) left_y_axis = 0.0; if ( fabs(right_x_axis) <= DEADBAND ) right_x_axis = 0.0; if ( fabs(right_y_axis) <= DEADBAND ) right_y_axis = 0.0; //ONLY PICK ONE!!!! //Drive_Tank(m_drivetrain, left_y_axis, right_y_axis); //Drive_Test1(m_drivetrain, left_y_axis, left_x_axis, right_x_axis); //Testing only //Drive_Test2(m_drivetrain, left_y_axis, left_x_axis, right_x_axis); //Tylers Code Drive_Test3(m_drivetrain, left_y_axis, left_x_axis, right_x_axis); //Kris' Code } void CmdDriveWithXbox::End(bool interrupted) {} bool CmdDriveWithXbox::IsFinished() { return false; } //************************************************************** void Drive_Tank(Drivetrain *drivetrain, float left, float right) { drivetrain->TankDrive(left,right); } //************************************************************** // Test1 is to work out the math to make sure signs are right // while the robot is sitting on a bench void Drive_Test1(Drivetrain *drivetrain, float l_y, float l_x, float r_x) { const float LX_PERCENT = 0.33; //LX = left x axis const float LY_PERCENT = 0.33; //LY = left y axis const float RX_PERCENT = 0.33; //RX = right x axis //Update powers l_y *= LY_PERCENT; l_x *= LX_PERCENT; r_x *= RX_PERCENT; //Do the math! float lf = ( l_x + l_y + r_x ); float lr = ( -l_x + l_y + r_x ); float rf = ( -l_x + l_y - r_x ); float rr = ( l_x + l_y - r_x ); drivetrain->Drive(lf,rf,lr,rr); } //************************************************************** // Tylers code void Drive_Test2(Drivetrain *drivetrain, float l_y, float l_x, float r_x) { const float DEADBAND = 0.05; // wanted power is the length between x and y float wantedPower = sqrt((l_x*l_x)) + ((l_y*l_y))/sqrt(2); //Pythagorean theorem if(wantedPower > 1)// This shouldn't happen { wantedPower = 1.0; } else if((fabs(r_x) > DEADBAND) && (fabs(r_x) > wantedPower))//Gives power to rotation if it is the largest { wantedPower = r_x; } else if(wantedPower < DEADBAND) { wantedPower = 0.0; } //Do the math! (copied from Test1) float lf = ( l_x + l_y + r_x ); float lr = ( -l_x + l_y + r_x ); float rf = ( -l_x + l_y - r_x ); float rr = ( l_x + l_y - r_x ); float greatestPower = lf; if(fabs(greatestPower) < fabs(lr)) { greatestPower = lr; } if(fabs(greatestPower) < fabs(rf)) { greatestPower = rf; } if(fabs(greatestPower) < fabs(rr)) { greatestPower = rr; } //greatest * ratio = wanted //ratio is used to make the power on the moters equal to wanted float powerRatio = 0; if(fabs(greatestPower) > DEADBAND) powerRatio = fabs(wantedPower/greatestPower); // stops division by zero drivetrain->Drive((lf * powerRatio) , (rf * powerRatio) , (lr * powerRatio) , (rr * powerRatio)); //DEBUG frc::SmartDashboard::PutNumber("wanted power", wantedPower); frc::SmartDashboard::PutNumber("power ratio", powerRatio); } //************************************************************** // Kris' code void Drive_Test3(Drivetrain *drivetrain, float l_y, float l_x, float r_x) { //Do the math! (copied from Test1) float lf = ( l_x + l_y + r_x ); float lr = ( -l_x + l_y + r_x ); float rf = ( -l_x + l_y - r_x ); float rr = ( l_x + l_y - r_x ); //Find the largest number greater than 1.0 float greatestPower = 1.00; //Set at 1.0 if(fabs(greatestPower) < fabs(lf)) { greatestPower = lr; } if(fabs(greatestPower) < fabs(lr)) { greatestPower = lr; } if(fabs(greatestPower) < fabs(rf)) { greatestPower = rf; } if(fabs(greatestPower) < fabs(rr)) { greatestPower = rr; } //Divide all powers by greatestPower to normalize to 1.0 drivetrain->Drive((lf/greatestPower) , (rf/greatestPower) , (lr/greatestPower) , (rr/greatestPower) ); }
// Copyright 2012 Viewfinder. All rights reserved. // Author: Ben Darnell // // See ImageIndex.mm for comments. This file contains the core of the fingerprinting algorithm, // extracted into a separate file so it can be used in other contexts. #include <Accelerate/Accelerate.h> #include <CoreGraphics/CGContext.h> #include <CoreGraphics/CGBitmapContext.h> #include <assert.h> #include "ImageFingerprint.h" #include "ImageFingerprintPrivate.h" using std::string; using std::vector; namespace { // The 2D Haar discrete wavelet transform. The resulting value at location x[0] // is the average of all the input values. template <int N> void Haar2D(float* x) { float t[N]; // Decompose rows. for (int i = 0; i < N; ++i) { for (int n = N / 2; n >= 1; n /= 2) { for (int k = 0; k < n * 2; ++k) { t[k] = x[i * N + k]; } for (int k = 0; k < n; ++k) { x[i * N + k] = (t[2 * k] + t[2 * k + 1]) / 2; x[i * N + k + n] = (t[2 * k] - t[2 * k + 1]); } } } // Decompose columns. for (int i = 0; i < N; ++i) { for (int n = N / 2; n >= 1; n /= 2) { for (int k = 0; k < n * 2; ++k) { t[k] = x[k * N + i]; } for (int k = 0; k < n; ++k) { x[k * N + i] = (t[2 * k] + t[2 * k + 1]) / 2; x[(k + n) * N + i] = (t[2 * k] - t[2 * k + 1]); } } } } // Returns true if the bottom row of the image is blank and the top row of the // image is not blank. This is intended to provide a signal of the iOS6 aspect // ratio thumbnail bug which leaves a blank row at the bottom of the image // without also capturing images that contain a white border. bool BottomRowIsBlank(CGImageRef image) { CGDataProviderRef data_provider = CGImageGetDataProvider(image); if (!data_provider) { return false; } CFDataRef data = CGDataProviderCopyData(data_provider); if (!data) { return false; } bool result = false; const int bits_per_pixel = CGImageGetBitsPerPixel(image); if (bits_per_pixel == 32) { const int bytes_per_row = CGImageGetBytesPerRow(image); const int width = CGImageGetWidth(image); const int height = CGImageGetHeight(image); const int image_bytes_per_row = width * ((bits_per_pixel + 7) / 8); const uint8_t* pixels = (const uint8_t*)CFDataGetBytePtr(data); result = true; const uint8_t* ptr = pixels + (height - 1) * bytes_per_row; for (int i = 0; i < image_bytes_per_row; ++i) { if (ptr[i] != 255) { result = false; break; } } if (result) { // Verify the top row is not blank too. If both the top and bottom row // are blank, the image probably has a border. const uint8_t* ptr = pixels; result = false; for (int i = 0; i < image_bytes_per_row; ++i) { if (ptr[i] != 255) { result = true; break; } } } } else if (bits_per_pixel == 16) { const int bytes_per_row = CGImageGetBytesPerRow(image); const int width = CGImageGetWidth(image); const int height = CGImageGetHeight(image); const uint8_t* pixels = (const uint8_t*)CFDataGetBytePtr(data); result = true; const uint16_t* ptr = (const uint16_t*)(pixels + (height - 1) * bytes_per_row); const CGBitmapInfo bitmap_info = CGImageGetBitmapInfo(image); uint16_t white = 0xffff; // NOTE(peter): most of the bitmap/alpha info combinations are not valid, // but we support as much as possible...just in case. switch (bitmap_info & kCGBitmapAlphaInfoMask) { case kCGImageAlphaNone: break; case kCGImageAlphaPremultipliedLast: case kCGImageAlphaLast: case kCGImageAlphaNoneSkipLast: if (bitmap_info & kCGBitmapByteOrder16Big) { white = 0xfeff; } else { white = 0xfffe; } break; case kCGImageAlphaPremultipliedFirst: case kCGImageAlphaFirst: case kCGImageAlphaNoneSkipFirst: if (bitmap_info & kCGBitmapByteOrder16Big) { white = 0xff7f; } else { white = 0x7fff; } break; } for (int i = 0; i < width; ++i) { if ((ptr[i] & white) != white) { result = false; break; } } if (result) { // Verify the top row is not blank too. If both the top and bottom row // are blank, the image probably has a border. const uint16_t* ptr = (const uint16_t*)pixels; result = false; for (int i = 0; i < width; ++i) { if ((ptr[i] & white) != white) { result = true; break; } } } } else { // TODO(peter): Handle other bit-per-pixel values? // assert(false); } CFRelease(data); return result; } // Convert the source image to grayscale and perform a square center crop. This // allows fingerprints of square thumbnails to be compared to fingerprints of // aspect ratio thumbnails. // // iOS6 aspect ratio thumbnails have a bug where the bottom row of pixels is // sometimes all white. More specifically, it appears that the thumbnail was // incorrectly drawn such that the image was shifted up by one pixel, exposing // a bottom row of white pixels and cropping off the top row of pixels. Square // thumbnails do not exhibit this problem and iOS7 aspect ratio thumbnails do // not exhibit this problem. // // We attempt to normalize the source image, cropping the portion of the image // which is consistent between the aspect ratio thumbnails (with and without // the iOS6 bug) and the square thumbnails. The normalization consists of // cropping out a 1 pixel border from the smaller dimension of the 120 aspect // ratio thumbnail. This gets mildly complicated because 1 pixel in the 120 // aspect ratio thumbnail translates into >1 pixel for the 150 square // thumbnails and the non-120 (iPad and iOS 7) aspect ratio thumbnails. void ToGrayscaleImage(CGImageRef src, int N, float aspect_ratio, void* dest) { const float w = CGImageGetWidth(src); const float h = CGImageGetHeight(src); const float max_dim = std::max<float>(w, h); const float src_aspect_ratio = w / h; // The size of the border to trim from image. We trim a 1 pixel border from // aspect ratio thumbnails with a maximum dimension of 120. For all other // source images we scale up the size of the border accordingly. const float border = (aspect_ratio >= 1) ? ((max_dim * (aspect_ratio / src_aspect_ratio)) / 120) : ((max_dim / (aspect_ratio / src_aspect_ratio)) / 120); CGRect src_rect = CGRectMake(0, 0, w, h); if (w == h) { // Square aspect ratio, trim both directions. src_rect.origin.y += border; src_rect.size.height -= 2 * border; src_rect.origin.x += border; src_rect.size.width -= 2 * border; } else if (w > h) { // Horizontal aspect ratio, only trim vertically. src_rect.origin.y += border; src_rect.size.height -= 2 * border; } else if (h > w) { // Vertical aspect ratio, only trim horizontally. src_rect.origin.x += border; src_rect.size.width -= 2 * border; } if (BottomRowIsBlank(src)) { // The bottom row is blank, indicating that the image was shifted up 1 // pixel. src_rect.origin.y += 1; src_rect.size.height -= 1; } const float s = N / std::min<float>(src_rect.size.width, src_rect.size.height); CGAffineTransform t = CGAffineTransformIdentity; t = CGAffineTransformTranslate(t, N / 2, N / 2); t = CGAffineTransformScale(t, s, s); t = CGAffineTransformTranslate(t, -CGRectGetMidX(src_rect), -CGRectGetMidY(src_rect)); const CGRect dest_rect = CGRectApplyAffineTransform(CGRectMake(0, 0, w, h), t); CGColorSpaceRef colorspace(CGColorSpaceCreateDeviceGray()); CGContextRef context(CGBitmapContextCreate( dest, N, N, 8, N, colorspace, kCGImageAlphaNone)); CGContextSetInterpolationQuality(context, kCGInterpolationMedium); CGContextDrawImage(context, dest_rect, src); CFRelease(context); CFRelease(colorspace); } void BlurImage(int N, void* src, void* dest) { vImage_Buffer src_buf = { src, N, N, N }; vImage_Buffer dest_buf = { dest, N, N, N }; // Note, that while kvImageEdgeExtend might seem a better option, it actually // produces much worse fingerprints due to the strange 1 pixel shadow on the // edges of pre-iOS-7 thumbnails. We blur with a background color of 127 in // order to minimize the disturbance of gradients near the edges. long result = vImageBoxConvolve_Planar8( &src_buf, &dest_buf, NULL, 0, 0, 5, 5, 127, kvImageDoNotTile | kvImageBackgroundColorFill); assert(result == 0); } void ToFloatImage(int N, void* src, void* dest) { vImage_Buffer src_buf = { src, N, N, N }; vImage_Buffer dest_buf = { dest, N, N, N * sizeof(float) }; long result = vImageConvert_Planar8toPlanarF( &src_buf, &dest_buf, 127.5, -127.5, kvImageDoNotTile); assert(result == 0); } void Rotate90(int N, void* src, void* dest) { vImage_Buffer src_buf = { src, N, N, N * sizeof(float) }; vImage_Buffer dest_buf = { dest, N, N, N * sizeof(float) }; long result = vImageRotate90_PlanarF( &src_buf, &dest_buf, kRotate90DegreesClockwise, 0, kvImageDoNotTile); assert(result == 0); } void ReflectHorizontal(int N, void* src, void* dest) { vImage_Buffer src_buf = { src, N, N, N * sizeof(float) }; vImage_Buffer dest_buf = { dest, N, N, N * sizeof(float) }; long result = vImageHorizontalReflect_PlanarF( &src_buf, &dest_buf, kvImageDoNotTile); assert(result == 0); } void ReflectVertical(int N, void* src, void* dest) { vImage_Buffer src_buf = { src, N, N, N * sizeof(float) }; vImage_Buffer dest_buf = { dest, N, N, N * sizeof(float) }; long result = vImageVerticalReflect_PlanarF( &src_buf, &dest_buf, kvImageDoNotTile); assert(result == 0); } string HaarToTerm(const float* haar_data) { // We use a value of -2 instead of 0 so that small negative deltas are // treated the same as positive deltas. Such deltas can occur if there is // small bits of noise in an image. For example, consider the fingerprint of // an all black image and one containing imperceptible amounts of very dark // gray (e.g. 254, 254, 254) noise. static const float kHaarThreshold = -2; // Perform a zig-zag traveral of the 13x13 upper-left matrix of the resulting // data and output a hash bit if the value is greater than 0. It would be // slightly better to compute the median here, but the median is ~0 after the // Haar transform. uint8_t hash[kHaarHashBytes] = { 0 }; for (int i = 0; i < kHaarHashBits; ++i) { // We skip the first 3 entries of haar_data (in the zig-zag traversal) // because they give little information. The first entry is the average // pixel value across the image. The second and third are the average // horizontal and vertical gradients, which were forced to be positive by // the orientation normalization. if (haar_data[kZigZagOffsets[i + kHaarHashSkip]] >= kHaarThreshold) { hash[i / 8] |= 1 << (i % 8); } } return string((const char*)hash, kHaarHashBytes); } } // namespace CGImageRef FingerprintPrepareImage(CGImageRef src, float aspect_ratio) { const int N = kHaarSmallN; uint8_t gray_data[N * N] = { 0 }; ToGrayscaleImage(src, N, aspect_ratio, gray_data); CGColorSpaceRef colorspace(CGColorSpaceCreateDeviceGray()); CGContextRef context(CGBitmapContextCreate( gray_data, N, N, 8, N, colorspace, kCGImageAlphaNone)); CGImageRef res = CGBitmapContextCreateImage(context); CFRelease(context); CFRelease(colorspace); return res; } ImageFingerprint FingerprintImage(CGImageRef image, float aspect_ratio) { float haar_buf1[kHaarSmallNxN]; float haar_buf2[kHaarSmallNxN]; float* haar_data = haar_buf1; { // Pre-process the image. First, transform the incoming image to a 32x32 // grayscale image, distorting if necessary. uint8_t gray_data[kHaarSmallNxN] = { 0 }; ToGrayscaleImage(image, kHaarSmallN, aspect_ratio, gray_data); // Apply a 5x5 box filter. uint8_t blur_data[kHaarSmallNxN]; BlurImage(kHaarSmallN, gray_data, blur_data); // Convert to floating point values. ToFloatImage(kHaarSmallN, blur_data, haar_data); } ImageFingerprint f; // Save the raw float image in case orientation normalization is needed. memcpy(haar_buf2, haar_buf1, sizeof(haar_buf1)); // Apply the Haar2D transform. Haar2D<kHaarSmallN>(haar_data); // NOTE(peter): Disable the support for normalizing rotation. This works, but // increases the indexing cost. And at the present time we don't care to find // duplicates that have different orientations. if (0) { // Force the average horizontal and vertical gradients to be positive and for // the horizontal gradient to be larger than the vertical gradient. This // normalizes the image orientation. float x_gradient = haar_data[kZigZagOffsets[1]]; float y_gradient = haar_data[kZigZagOffsets[2]]; const float rotate_gradient = fabs(x_gradient) - fabs(y_gradient); if (rotate_gradient < 0 || x_gradient < 0 || y_gradient < 0) { // We have to rotate and/or reflect the source. If any of the gradients are // smaller than the large thresholds we're uncertain about whether the // rotation or reflection is necessary and could thus rotate/reflect one // version of the image and not another. We handle this case by indexing // both the non-normalized image and the normalized image. Note that pixel // values are between [-127.5, 127.5] giving gradients that are in the // range [-255, 255]. static const float kLargeThreshold = 3; if ((rotate_gradient < kLargeThreshold && rotate_gradient > -kLargeThreshold) || (x_gradient < kLargeThreshold && x_gradient > -kLargeThreshold) || (y_gradient < kLargeThreshold && y_gradient > -kLargeThreshold)) { f.add_terms(HaarToTerm(haar_data)); } float* src = haar_buf2; float* tmp = haar_buf1; if (rotate_gradient < 0) { // LOG("rotate 90: %f %f", x_gradient, y_gradient); Rotate90(kHaarSmallN, src, tmp); std::swap(src, tmp); // When we rotate 90 degrees clockwise, the x and y gradients get swapped // and the x gradient gets reflected. std::swap(x_gradient, y_gradient); x_gradient = -x_gradient; } if (x_gradient < 0) { // LOG("reflect horizontal: %f", x_gradient); ReflectHorizontal(kHaarSmallN, src, tmp); std::swap(src, tmp); } if (y_gradient < 0) { // LOG("reflect vertical: %f", y_gradient); ReflectVertical(kHaarSmallN, src, tmp); std::swap(src, tmp); } haar_data = src; Haar2D<kHaarSmallN>(haar_data); } } const string term = HaarToTerm(haar_data); if (f.terms_size() == 0 || f.terms(0) != term) { f.add_terms(term); } return f; }
#ifndef FUNNYOS_STDLIB_SRC_PLATFORM_HPP #define FUNNYOS_STDLIB_SRC_PLATFORM_HPP #include "File.hpp" #include "Functional.hpp" #include "IntegerTypes.hpp" #ifdef F_STDLIB_PLATFORM_EXTERN #define _EXTERN extern #else #define _EXTERN #endif /** * Platform-specific functions */ namespace FunnyOS::_Platform { [[nodiscard]] _EXTERN void* AllocateMemoryAligned(size_t size, size_t aligned) noexcept; [[nodiscard]] _EXTERN void* ReallocateMemoryAligned(void* memory, size_t size, size_t alignment) noexcept; _EXTERN void FreeMemory(void* memory) noexcept; _EXTERN void ReportError(const char* error) noexcept; [[noreturn]] _EXTERN void Terminate(const char* error) noexcept; [[nodiscard]] Stdlib::Optional<Stdlib::File> OpenFile(Stdlib::DynamicString path, Stdlib::FileOpenMode mode) noexcept; } // namespace FunnyOS::_Platform #undef _EXTERN #endif // FUNNYOS_STDLIB_SRC_PLATFORM_HPP
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #if (defined(GOOGLE_CUDA) && GOOGLE_CUDA) || TENSORFLOW_USE_ROCM #define EIGEN_USE_GPU #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/tensor_types.h" #include "tensorflow/core/kernels/in_topk_op.h" #include "tensorflow/core/kernels/reduction_gpu_kernels.cu.h" #include "tensorflow/core/kernels/reduction_ops.h" #include "tensorflow/core/util/gpu_kernel_helper.h" namespace tensorflow { typedef Eigen::GpuDevice GPUDevice; namespace functor { // Compare each prediction in 'predictions' with a target prediction for the // batch, and write result to the 'mask': // -1: If the target class is out of range, or if the prediction value is not // finite and can't be compared to target prediction (and vice versa). // 0: If prediction is smaller than the target prediction for the batch. // 1: If prediction is larger than the target prediction for the batch. template <typename T, typename TargetT> __global__ void ComputePredictionMaskKernel( const T* __restrict__ predictions, // dims: [ num_targets x num_classes ] const TargetT* __restrict__ targets, // dims: [ num_targets ] int64* __restrict__ mask, // dims: [ num_targets x num_classes ] int num_targets, int num_classes) { GPU_1D_KERNEL_LOOP(i, num_targets * num_classes) { const int batch_index = i / num_classes; TargetT target_idx = ldg(targets + batch_index); if (!FastBoundsCheck(target_idx, num_classes)) { mask[i] = -1; return; } T prediction = ldg(predictions + i); T target_prediction = ldg(predictions + batch_index * num_classes + target_idx); if (!Eigen::numext::isfinite(prediction) || !Eigen::numext::isfinite(target_prediction)) { mask[i] = -1; } else { mask[i] = prediction > target_prediction ? 1 : 0; } } } // Reduce all prediction masks either to the sum of '1' for each prediction // larger than the target, or to '-1' if target class in invalid of predictions // in a batch have non-finite values. struct MaskSum { __host__ __device__ int64 operator()(const int64& a, const int64& b) const { if (a < 0 || b < 0) return -1; else return a + b; } }; namespace reduction_op_helper { template <> struct IdentityValue<int64, MaskSum> { int64 operator()() { return 0; } }; } // namespace reduction_op_helper template <typename T, typename TargetT> struct InTopKFunctor<GPUDevice, T, TargetT> { template <int ndims> using Dims = Eigen::DSizes<Eigen::Index, ndims>; void operator()(OpKernelContext* context, typename TTypes<T, 2>::ConstTensor predictions, typename TTypes<TargetT>::ConstVec targets, const TopKArg k, typename TTypes<bool>::Vec output) { const Eigen::Index num_targets = predictions.dimension(0); const Eigen::Index num_classes = predictions.dimension(1); OP_REQUIRES( context, num_targets * num_classes < std::numeric_limits<int>::max(), errors::InvalidArgument( "Number of targets * number of classes must be less than INT_MAX")); if (num_targets == 0 || num_classes == 0) { // Result is empty, so shortcut the rest of the function to avoid // launching kernels with empty input. return; } // Temporary storage for a mask computed by `ComputePredictionMaskKernel`. Tensor predictions_mask; OP_REQUIRES_OK( context, context->allocate_temp(DT_INT64, TensorShape({num_targets, num_classes}), &predictions_mask)); // Number of predictions for each target that are larger than the target // prediction (or -1 if we can't compute this number, because not all // predictions are finite or target class is out of range). Tensor num_larger_prediction; OP_REQUIRES_OK(context, context->allocate_temp(DT_INT64, TensorShape({num_targets}), &num_larger_prediction)); const auto& d = context->eigen_device<GPUDevice>(); // Compute a mask for all predictions. GpuLaunchConfig config = GetGpuLaunchConfig(num_targets * num_classes, d); OP_REQUIRES_OK( context, GpuLaunchKernel(ComputePredictionMaskKernel<T, TargetT>, config.block_count, config.thread_per_block, 0, d.stream(), predictions.data(), targets.data(), predictions_mask.flat<int64>().data(), num_targets, num_classes)); // Reduce prediction masks to number of predictions larger than the target // prediction, or to the negative value if we can't compute an answer. { auto in = predictions_mask.matrix<int64>(); auto out = num_larger_prediction.flat<int64>(); ReduceImpl<int64, MaskSum, int64*, int64*, Dims<1>>( context, (int64*)out.data(), (int64*)in.data(), in.rank(), in.dimension(0), in.rank() >= 2 ? in.dimension(1) : 1, in.rank() >= 3 ? in.dimension(2) : 1, out.rank(), Dims<1>(1), MaskSum()); } // Compute if target prediction is in top K predictions. auto cnt = num_larger_prediction.flat<int64>(); if (k.k_tensor != nullptr) { if (k.k_tensor->dtype() == DT_INT32) { output.device(d) = (cnt >= cnt.constant(0)) && (cnt < k.k_tensor->flat<int32>().template cast<int64>().broadcast( Dims<1>(num_targets))); } else { output.device(d) = (cnt >= cnt.constant(0)) && (cnt < k.k_tensor->flat<int64>().broadcast(Dims<1>(num_targets))); } } else { output.device(d) = (cnt >= cnt.constant(0)) && (cnt < targets.constant(k.k_value)); } } }; } // namespace functor // Definition of the GPU implementations declared in in_topk_op.cc. #define DEFINE_GPU_KERNELS(T, TARGET_T) \ template struct functor::InTopKFunctor<GPUDevice, T, TARGET_T>; DEFINE_GPU_KERNELS(float, int32); DEFINE_GPU_KERNELS(float, int64); #undef DEFINE_GPU_KERNELS } // end namespace tensorflow #endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#include "askpassphrasedialog.h" #include "ui_askpassphrasedialog.h" #include "guiconstants.h" #include "walletmodel.h" #include <QMessageBox> #include <QPushButton> #include <QKeyEvent> AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget *parent) : QDialog(parent), ui(new Ui::AskPassphraseDialog), mode(mode), model(0), fCapsLock(false) { ui->setupUi(this); ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE); ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE); ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE); // Setup Caps Lock detection. ui->passEdit1->installEventFilter(this); ui->passEdit2->installEventFilter(this); ui->passEdit3->installEventFilter(this); switch(mode) { case Encrypt: // Ask passphrase x2 ui->passLabel1->hide(); ui->passEdit1->hide(); ui->warningLabel->setText(tr("Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.")); setWindowTitle(tr("Encrypt wallet")); break; case Unlock: // Ask passphrase ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet.")); ui->passLabel2->hide(); ui->passEdit2->hide(); ui->passLabel3->hide(); ui->passEdit3->hide(); setWindowTitle(tr("Unlock wallet")); break; case Decrypt: // Ask passphrase ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet.")); ui->passLabel2->hide(); ui->passEdit2->hide(); ui->passLabel3->hide(); ui->passEdit3->hide(); setWindowTitle(tr("Decrypt wallet")); break; case ChangePass: // Ask old passphrase + new passphrase x2 setWindowTitle(tr("Change passphrase")); ui->warningLabel->setText(tr("Enter the old and new passphrase to the wallet.")); break; } textChanged(); connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); } AskPassphraseDialog::~AskPassphraseDialog() { // Attempt to overwrite text so that they do not linger around in memory ui->passEdit1->setText(QString(" ").repeated(ui->passEdit1->text().size())); ui->passEdit2->setText(QString(" ").repeated(ui->passEdit2->text().size())); ui->passEdit3->setText(QString(" ").repeated(ui->passEdit3->text().size())); delete ui; } void AskPassphraseDialog::setModel(WalletModel *model) { this->model = model; } void AskPassphraseDialog::accept() { SecureString oldpass, newpass1, newpass2; if(!model) return; oldpass.reserve(MAX_PASSPHRASE_SIZE); newpass1.reserve(MAX_PASSPHRASE_SIZE); newpass2.reserve(MAX_PASSPHRASE_SIZE); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make this input mlock()'d to begin with. oldpass.assign(ui->passEdit1->text().toStdString().c_str()); newpass1.assign(ui->passEdit2->text().toStdString().c_str()); newpass2.assign(ui->passEdit3->text().toStdString().c_str()); switch(mode) { case Encrypt: { if(newpass1.empty() || newpass2.empty()) { // Cannot encrypt with empty passphrase break; } QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"), tr("Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR BEATLECOINS</b>!") + "<br><br>" + tr("Are you sure you wish to encrypt your wallet?"), QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Cancel); if(retval == QMessageBox::Yes) { if(newpass1 == newpass2) { if(model->setWalletEncrypted(true, newpass1)) { QMessageBox::warning(this, tr("Wallet encrypted"), "<qt>" + tr("BeatleCoin will close now to finish the encryption process. " "Remember that encrypting your wallet cannot fully protect " "your beatlecoins from being stolen by malware infecting your computer.") + "<br><br><b>" + tr("IMPORTANT: Any previous backups you have made of your wallet file " "should be replaced with the newly generated, encrypted wallet file. " "For security reasons, previous backups of the unencrypted wallet file " "will become useless as soon as you start using the new, encrypted wallet.") + "</b></qt>"); QApplication::quit(); } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted.")); } QDialog::accept(); // Success } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The supplied passphrases do not match.")); } } else { QDialog::reject(); // Cancelled } } break; case Unlock: if(!model->setWalletLocked(false, oldpass)) { QMessageBox::critical(this, tr("Wallet unlock failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } else { QDialog::accept(); // Success } break; case Decrypt: if(!model->setWalletEncrypted(false, oldpass)) { QMessageBox::critical(this, tr("Wallet decryption failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } else { QDialog::accept(); // Success } break; case ChangePass: if(newpass1 == newpass2) { if(model->changePassphrase(oldpass, newpass1)) { QMessageBox::information(this, tr("Wallet encrypted"), tr("Wallet passphrase was successfully changed.")); QDialog::accept(); // Success } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The supplied passphrases do not match.")); } break; } } void AskPassphraseDialog::textChanged() { // Validate input, set Ok button to enabled when acceptable bool acceptable = false; switch(mode) { case Encrypt: // New passphrase x2 acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty(); break; case Unlock: // Old passphrase x1 case Decrypt: acceptable = !ui->passEdit1->text().isEmpty(); break; case ChangePass: // Old passphrase x1, new passphrase x2 acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty(); break; } ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable); } bool AskPassphraseDialog::event(QEvent *event) { // Detect Caps Lock key press. if (event->type() == QEvent::KeyPress) { QKeyEvent *ke = static_cast<QKeyEvent *>(event); if (ke->key() == Qt::Key_CapsLock) { fCapsLock = !fCapsLock; } if (fCapsLock) { ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!")); } else { ui->capsLabel->clear(); } } return QWidget::event(event); } bool AskPassphraseDialog::eventFilter(QObject *object, QEvent *event) { /* Detect Caps Lock. * There is no good OS-independent way to check a key state in Qt, but we * can detect Caps Lock by checking for the following condition: * Shift key is down and the result is a lower case character, or * Shift key is not down and the result is an upper case character. */ if (event->type() == QEvent::KeyPress) { QKeyEvent *ke = static_cast<QKeyEvent *>(event); QString str = ke->text(); if (str.length() != 0) { const QChar *psz = str.unicode(); bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0; if ((fShift && *psz >= 'a' && *psz <= 'z') || (!fShift && *psz >= 'A' && *psz <= 'Z')) { fCapsLock = true; ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!")); } else if (psz->isLetter()) { fCapsLock = false; ui->capsLabel->clear(); } } } return QDialog::eventFilter(object, event); }
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. // // Copyright (c) 2011 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. // // Repairer does best effort recovery to recover as much data as possible after // a disaster without compromising consistency. It does not guarantee bringing // the database to a time consistent state. // // Repair process is broken into 4 phases: // (a) Find files // (b) Convert logs to tables // (c) Extract metadata // (d) Write Descriptor // // (a) Find files // // The repairer goes through all the files in the directory, and classifies them // based on their file name. Any file that cannot be identified by name will be // ignored. // // (b) Convert logs to table // // Every log file that is active is replayed. All sections of the file where the // checksum does not match is skipped over. We intentionally give preference to // data consistency. // // (c) Extract metadata // // We scan every table to compute // (1) smallest/largest for the table // (2) largest sequence number in the table // // If we are unable to scan the file, then we ignore the table. // // (d) Write Descriptor // // We generate descriptor contents: // - log number is set to zero // - next-file-number is set to 1 + largest file number we found // - last-sequence-number is set to largest sequence# found across // all tables (see 2c) // - compaction pointers are cleared // - every table file is added at level 0 // // Possible optimization 1: // (a) Compute total size and use to pick appropriate max-level M // (b) Sort tables by largest sequence# in the table // (c) For each table: if it overlaps earlier table, place in level-0, // else place in level-M. // (d) We can provide options for time consistent recovery and unsafe recovery // (ignore checksum failure when applicable) // Possible optimization 2: // Store per-table metadata (smallest, largest, largest-seq#, ...) // in the table's meta section to speed up ScanTable. #ifndef ROCKSDB_LITE #ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS #endif #include <inttypes.h> #include "db/builder.h" #include "db/db_impl.h" #include "db/dbformat.h" #include "db/filename.h" #include "db/log_reader.h" #include "db/log_writer.h" #include "db/memtable.h" #include "db/table_cache.h" #include "db/version_edit.h" #include "db/write_batch_internal.h" #include "db/writebuffer.h" #include "rocksdb/comparator.h" #include "rocksdb/db.h" #include "rocksdb/env.h" #include "rocksdb/immutable_options.h" #include "rocksdb/options.h" #include "table/scoped_arena_iterator.h" #include "util/file_reader_writer.h" #include "util/string_util.h" namespace rocksdb { namespace { class Repairer { public: Repairer(const std::string& dbname, const DBOptions& db_options, const std::vector<ColumnFamilyDescriptor>& column_families, const ColumnFamilyOptions& default_cf_opts, const ColumnFamilyOptions& unknown_cf_opts, bool create_unknown_cfs) : dbname_(dbname), env_(db_options.env), env_options_(), db_options_(SanitizeOptions(dbname_, db_options)), icmp_(default_cf_opts.comparator), default_cf_opts_(default_cf_opts), default_cf_iopts_( ImmutableCFOptions(Options(db_options_, default_cf_opts))), unknown_cf_opts_(unknown_cf_opts), create_unknown_cfs_(create_unknown_cfs), raw_table_cache_( // TableCache can be small since we expect each table to be opened // once. NewLRUCache(10, db_options_.table_cache_numshardbits)), table_cache_(new TableCache(default_cf_iopts_, env_options_, raw_table_cache_.get())), wb_(db_options_.db_write_buffer_size), wc_(db_options_.delayed_write_rate), vset_(dbname_, &db_options_, env_options_, raw_table_cache_.get(), &wb_, &wc_), next_file_number_(1) { for (const auto& cfd : column_families) { cf_name_to_opts_[cfd.name] = cfd.options; } } const ColumnFamilyOptions* GetColumnFamilyOptions( const std::string& cf_name) { if (cf_name_to_opts_.find(cf_name) == cf_name_to_opts_.end()) { if (create_unknown_cfs_) { return &unknown_cf_opts_; } return nullptr; } return &cf_name_to_opts_[cf_name]; } // Adds a column family to the VersionSet with cf_options_ and updates // manifest. Status AddColumnFamily(const std::string& cf_name, uint32_t cf_id) { const auto* cf_opts = GetColumnFamilyOptions(cf_name); if (cf_opts == nullptr) { return Status::Corruption("Encountered unknown column family with name=" + cf_name + ", id=" + ToString(cf_id)); } Options opts(db_options_, *cf_opts); MutableCFOptions mut_cf_opts(opts, ImmutableCFOptions(opts)); VersionEdit edit; edit.SetComparatorName(opts.comparator->Name()); edit.SetLogNumber(0); edit.SetColumnFamily(cf_id); ColumnFamilyData* cfd; cfd = nullptr; edit.AddColumnFamily(cf_name); mutex_.Lock(); Status status = vset_.LogAndApply(cfd, mut_cf_opts, &edit, &mutex_, nullptr /* db_directory */, false /* new_descriptor_log */, cf_opts); mutex_.Unlock(); return status; } ~Repairer() { delete table_cache_; } Status Run() { Status status = FindFiles(); if (status.ok()) { // Discard older manifests and start a fresh one for (size_t i = 0; i < manifests_.size(); i++) { ArchiveFile(dbname_ + "/" + manifests_[i]); } // Just create a DBImpl temporarily so we can reuse NewDB() DBImpl* db_impl = new DBImpl(db_options_, dbname_); status = db_impl->NewDB(); delete db_impl; } if (status.ok()) { // Recover using the fresh manifest created by NewDB() status = vset_.Recover({{kDefaultColumnFamilyName, default_cf_opts_}}, false); } if (status.ok()) { // Need to scan existing SST files first so the column families are // created before we process WAL files ExtractMetaData(); // ExtractMetaData() uses table_fds_ to know which SST files' metadata to // extract -- we need to clear it here since metadata for existing SST // files has been extracted already table_fds_.clear(); ConvertLogFilesToTables(); ExtractMetaData(); status = AddTables(); } if (status.ok()) { uint64_t bytes = 0; for (size_t i = 0; i < tables_.size(); i++) { bytes += tables_[i].meta.fd.GetFileSize(); } Log(InfoLogLevel::WARN_LEVEL, db_options_.info_log, "**** Repaired rocksdb %s; " "recovered %" ROCKSDB_PRIszt " files; %" PRIu64 "bytes. " "Some data may have been lost. " "****", dbname_.c_str(), tables_.size(), bytes); } return status; } private: struct TableInfo { FileMetaData meta; uint32_t column_family_id; std::string column_family_name; SequenceNumber min_sequence; SequenceNumber max_sequence; }; std::string const dbname_; Env* const env_; const EnvOptions env_options_; const DBOptions db_options_; const InternalKeyComparator icmp_; const ColumnFamilyOptions default_cf_opts_; const ImmutableCFOptions default_cf_iopts_; // table_cache_ holds reference const ColumnFamilyOptions unknown_cf_opts_; const bool create_unknown_cfs_; std::shared_ptr<Cache> raw_table_cache_; TableCache* table_cache_; WriteBuffer wb_; WriteController wc_; VersionSet vset_; std::unordered_map<std::string, ColumnFamilyOptions> cf_name_to_opts_; InstrumentedMutex mutex_; std::vector<std::string> manifests_; std::vector<FileDescriptor> table_fds_; std::vector<uint64_t> logs_; std::vector<TableInfo> tables_; uint64_t next_file_number_; Status FindFiles() { std::vector<std::string> filenames; bool found_file = false; for (size_t path_id = 0; path_id < db_options_.db_paths.size(); path_id++) { Status status = env_->GetChildren(db_options_.db_paths[path_id].path, &filenames); if (!status.ok()) { return status; } if (!filenames.empty()) { found_file = true; } uint64_t number; FileType type; for (size_t i = 0; i < filenames.size(); i++) { if (ParseFileName(filenames[i], &number, &type)) { if (type == kDescriptorFile) { assert(path_id == 0); manifests_.push_back(filenames[i]); } else { if (number + 1 > next_file_number_) { next_file_number_ = number + 1; } if (type == kLogFile) { assert(path_id == 0); logs_.push_back(number); } else if (type == kTableFile) { table_fds_.emplace_back(number, static_cast<uint32_t>(path_id), 0); } else { // Ignore other files } } } } } if (!found_file) { return Status::Corruption(dbname_, "repair found no files"); } return Status::OK(); } void ConvertLogFilesToTables() { for (size_t i = 0; i < logs_.size(); i++) { std::string logname = LogFileName(dbname_, logs_[i]); Status status = ConvertLogToTable(logs_[i]); if (!status.ok()) { Log(InfoLogLevel::WARN_LEVEL, db_options_.info_log, "Log #%" PRIu64 ": ignoring conversion error: %s", logs_[i], status.ToString().c_str()); } ArchiveFile(logname); } } Status ConvertLogToTable(uint64_t log) { struct LogReporter : public log::Reader::Reporter { Env* env; std::shared_ptr<Logger> info_log; uint64_t lognum; virtual void Corruption(size_t bytes, const Status& s) override { // We print error messages for corruption, but continue repairing. Log(InfoLogLevel::ERROR_LEVEL, info_log, "Log #%" PRIu64 ": dropping %d bytes; %s", lognum, static_cast<int>(bytes), s.ToString().c_str()); } }; // Open the log file std::string logname = LogFileName(dbname_, log); unique_ptr<SequentialFile> lfile; Status status = env_->NewSequentialFile(logname, &lfile, env_options_); if (!status.ok()) { return status; } unique_ptr<SequentialFileReader> lfile_reader( new SequentialFileReader(std::move(lfile))); // Create the log reader. LogReporter reporter; reporter.env = env_; reporter.info_log = db_options_.info_log; reporter.lognum = log; // We intentionally make log::Reader do checksumming so that // corruptions cause entire commits to be skipped instead of // propagating bad information (like overly large sequence // numbers). log::Reader reader(db_options_.info_log, std::move(lfile_reader), &reporter, true /*enable checksum*/, 0 /*initial_offset*/, log); // Initialize per-column family memtables for (auto* cfd : *vset_.GetColumnFamilySet()) { cfd->CreateNewMemtable(*cfd->GetLatestMutableCFOptions(), kMaxSequenceNumber); } auto cf_mems = new ColumnFamilyMemTablesImpl(vset_.GetColumnFamilySet()); // Read all the records and add to a memtable std::string scratch; Slice record; WriteBatch batch; int counter = 0; while (reader.ReadRecord(&record, &scratch)) { if (record.size() < WriteBatchInternal::kHeader) { reporter.Corruption( record.size(), Status::Corruption("log record too small")); continue; } WriteBatchInternal::SetContents(&batch, record); status = WriteBatchInternal::InsertInto(&batch, cf_mems, nullptr); if (status.ok()) { counter += WriteBatchInternal::Count(&batch); } else { Log(InfoLogLevel::WARN_LEVEL, db_options_.info_log, "Log #%" PRIu64 ": ignoring %s", log, status.ToString().c_str()); status = Status::OK(); // Keep going with rest of file } } // Dump a table for each column family with entries in this log file. for (auto* cfd : *vset_.GetColumnFamilySet()) { // Do not record a version edit for this conversion to a Table // since ExtractMetaData() will also generate edits. MemTable* mem = cfd->mem(); if (mem->IsEmpty()) { continue; } FileMetaData meta; meta.fd = FileDescriptor(next_file_number_++, 0, 0); ReadOptions ro; ro.total_order_seek = true; Arena arena; ScopedArenaIterator iter(mem->NewIterator(ro, &arena)); status = BuildTable( dbname_, env_, *cfd->ioptions(), *cfd->GetLatestMutableCFOptions(), env_options_, table_cache_, iter.get(), &meta, cfd->internal_comparator(), cfd->int_tbl_prop_collector_factories(), cfd->GetID(), cfd->GetName(), {}, kMaxSequenceNumber, kNoCompression, CompressionOptions(), false, nullptr /* internal_stats */, TableFileCreationReason::kRecovery); Log(InfoLogLevel::INFO_LEVEL, db_options_.info_log, "Log #%" PRIu64 ": %d ops saved to Table #%" PRIu64 " %s", log, counter, meta.fd.GetNumber(), status.ToString().c_str()); if (status.ok()) { if (meta.fd.GetFileSize() > 0) { table_fds_.push_back(meta.fd); } } else { break; } } delete cf_mems; return status; } void ExtractMetaData() { for (size_t i = 0; i < table_fds_.size(); i++) { TableInfo t; t.meta.fd = table_fds_[i]; Status status = ScanTable(&t); if (!status.ok()) { std::string fname = TableFileName( db_options_.db_paths, t.meta.fd.GetNumber(), t.meta.fd.GetPathId()); char file_num_buf[kFormatFileNumberBufSize]; FormatFileNumber(t.meta.fd.GetNumber(), t.meta.fd.GetPathId(), file_num_buf, sizeof(file_num_buf)); Log(InfoLogLevel::WARN_LEVEL, db_options_.info_log, "Table #%s: ignoring %s", file_num_buf, status.ToString().c_str()); ArchiveFile(fname); } else { tables_.push_back(t); } } } Status ScanTable(TableInfo* t) { std::string fname = TableFileName( db_options_.db_paths, t->meta.fd.GetNumber(), t->meta.fd.GetPathId()); int counter = 0; uint64_t file_size; Status status = env_->GetFileSize(fname, &file_size); t->meta.fd = FileDescriptor(t->meta.fd.GetNumber(), t->meta.fd.GetPathId(), file_size); std::shared_ptr<const TableProperties> props; if (status.ok()) { status = table_cache_->GetTableProperties(env_options_, icmp_, t->meta.fd, &props); } if (status.ok()) { t->column_family_id = static_cast<uint32_t>(props->column_family_id); if (t->column_family_id == TablePropertiesCollectorFactory::Context::kUnknownColumnFamily) { Log(InfoLogLevel::WARN_LEVEL, db_options_.info_log, "Table #%" PRIu64 ": column family unknown (probably due to legacy format); " "adding to default column family id 0.", t->meta.fd.GetNumber()); t->column_family_id = 0; } if (vset_.GetColumnFamilySet()->GetColumnFamily(t->column_family_id) == nullptr) { status = AddColumnFamily(props->column_family_name, t->column_family_id); } } ColumnFamilyData* cfd = nullptr; if (status.ok()) { cfd = vset_.GetColumnFamilySet()->GetColumnFamily(t->column_family_id); if (cfd->GetName() != props->column_family_name) { Log(InfoLogLevel::ERROR_LEVEL, db_options_.info_log, "Table #%" PRIu64 ": inconsistent column family name '%s'; expected '%s' for column " "family id %" PRIu32 ".", t->meta.fd.GetNumber(), props->column_family_name.c_str(), cfd->GetName().c_str(), t->column_family_id); status = Status::Corruption(dbname_, "inconsistent column family name"); } } if (status.ok()) { InternalIterator* iter = table_cache_->NewIterator( ReadOptions(), env_options_, cfd->internal_comparator(), t->meta.fd); bool empty = true; ParsedInternalKey parsed; t->min_sequence = 0; t->max_sequence = 0; for (iter->SeekToFirst(); iter->Valid(); iter->Next()) { Slice key = iter->key(); if (!ParseInternalKey(key, &parsed)) { Log(InfoLogLevel::ERROR_LEVEL, db_options_.info_log, "Table #%" PRIu64 ": unparsable key %s", t->meta.fd.GetNumber(), EscapeString(key).c_str()); continue; } counter++; if (empty) { empty = false; t->meta.smallest.DecodeFrom(key); } t->meta.largest.DecodeFrom(key); if (parsed.sequence < t->min_sequence) { t->min_sequence = parsed.sequence; } if (parsed.sequence > t->max_sequence) { t->max_sequence = parsed.sequence; } } if (!iter->status().ok()) { status = iter->status(); } delete iter; Log(InfoLogLevel::INFO_LEVEL, db_options_.info_log, "Table #%" PRIu64 ": %d entries %s", t->meta.fd.GetNumber(), counter, status.ToString().c_str()); } return status; } Status AddTables() { std::unordered_map<uint32_t, std::vector<const TableInfo*>> cf_id_to_tables; SequenceNumber max_sequence = 0; for (size_t i = 0; i < tables_.size(); i++) { cf_id_to_tables[tables_[i].column_family_id].push_back(&tables_[i]); if (max_sequence < tables_[i].max_sequence) { max_sequence = tables_[i].max_sequence; } } vset_.SetLastSequence(max_sequence); for (const auto& cf_id_and_tables : cf_id_to_tables) { auto* cfd = vset_.GetColumnFamilySet()->GetColumnFamily(cf_id_and_tables.first); VersionEdit edit; edit.SetComparatorName(cfd->user_comparator()->Name()); edit.SetLogNumber(0); edit.SetNextFile(next_file_number_); edit.SetColumnFamily(cfd->GetID()); // TODO(opt): separate out into multiple levels for (const auto* table : cf_id_and_tables.second) { edit.AddFile(0, table->meta.fd.GetNumber(), table->meta.fd.GetPathId(), table->meta.fd.GetFileSize(), table->meta.smallest, table->meta.largest, table->min_sequence, table->max_sequence, table->meta.marked_for_compaction); } mutex_.Lock(); Status status = vset_.LogAndApply( cfd, *cfd->GetLatestMutableCFOptions(), &edit, &mutex_, nullptr /* db_directory */, false /* new_descriptor_log */); mutex_.Unlock(); if (!status.ok()) { return status; } } return Status::OK(); } void ArchiveFile(const std::string& fname) { // Move into another directory. E.g., for // dir/foo // rename to // dir/lost/foo const char* slash = strrchr(fname.c_str(), '/'); std::string new_dir; if (slash != nullptr) { new_dir.assign(fname.data(), slash - fname.data()); } new_dir.append("/lost"); env_->CreateDir(new_dir); // Ignore error std::string new_file = new_dir; new_file.append("/"); new_file.append((slash == nullptr) ? fname.c_str() : slash + 1); Status s = env_->RenameFile(fname, new_file); Log(InfoLogLevel::INFO_LEVEL, db_options_.info_log, "Archiving %s: %s\n", fname.c_str(), s.ToString().c_str()); } }; Status GetDefaultCFOptions( const std::vector<ColumnFamilyDescriptor>& column_families, ColumnFamilyOptions* res) { assert(res != nullptr); auto iter = std::find_if(column_families.begin(), column_families.end(), [](const ColumnFamilyDescriptor& cfd) { return cfd.name == kDefaultColumnFamilyName; }); if (iter == column_families.end()) { return Status::InvalidArgument( "column_families", "Must contain entry for default column family"); } *res = iter->options; return Status::OK(); } } // anonymous namespace Status RepairDB(const std::string& dbname, const DBOptions& db_options, const std::vector<ColumnFamilyDescriptor>& column_families) { ColumnFamilyOptions default_cf_opts; Status status = GetDefaultCFOptions(column_families, &default_cf_opts); if (status.ok()) { Repairer repairer(dbname, db_options, column_families, default_cf_opts, ColumnFamilyOptions() /* unknown_cf_opts */, false /* create_unknown_cfs */); status = repairer.Run(); } return status; } Status RepairDB(const std::string& dbname, const DBOptions& db_options, const std::vector<ColumnFamilyDescriptor>& column_families, const ColumnFamilyOptions& unknown_cf_opts) { ColumnFamilyOptions default_cf_opts; Status status = GetDefaultCFOptions(column_families, &default_cf_opts); if (status.ok()) { Repairer repairer(dbname, db_options, column_families, default_cf_opts, unknown_cf_opts, true /* create_unknown_cfs */); status = repairer.Run(); } return status; } Status RepairDB(const std::string& dbname, const Options& options) { DBOptions db_options(options); ColumnFamilyOptions cf_options(options); Repairer repairer(dbname, db_options, {}, cf_options /* default_cf_opts */, cf_options /* unknown_cf_opts */, true /* create_unknown_cfs */); return repairer.Run(); } } // namespace rocksdb #endif // ROCKSDB_LITE
#include <iostream> #include <boost/filesystem.hpp> #include "../Includes/IParserApi.h" #include "../Includes/WTSVariant.hpp" #include "../Includes/WTSContractInfo.hpp" #include "../Includes/WTSDataDef.hpp" #include "../Share/DLLHelper.hpp" #include "../Share/StrUtil.hpp" #include "../WTSTools/WTSBaseDataMgr.h" #include "../WTSTools/WTSLogger.h" #include "../WTSUtils/WTSCfgLoader.h" WTSBaseDataMgr g_bdMgr; USING_NS_WTP; class ParserSpi : public IParserSpi { public: ParserSpi(){} bool init(WTSVariant* params, const char* ttype) { m_pParams = params; if (m_pParams) m_pParams->retain(); m_strModule = ttype; return true; } void release() { if (_api) { _api->release(); } } void run(bool bRestart = false) { if (!createParser(m_strModule.c_str())) { return; } _api->registerSpi(this); if (!_api->init(m_pParams)) { return; } ContractSet contractSet; WTSArray* ayContract = g_bdMgr.getContracts(); WTSArray::Iterator it = ayContract->begin(); for (; it != ayContract->end(); it++) { WTSContractInfo* contract = STATIC_CONVERT(*it, WTSContractInfo*); contractSet.insert(contract->getFullCode()); } ayContract->release(); _api->subscribe(contractSet); _api->connect(); } bool createParser(const char* moduleName) { DllHandle hInst = DLLHelper::load_library(moduleName); if (hInst == NULL) { WTSLogger::error_f("Loading module {} failed", moduleName); return false; } FuncCreateParser pCreator = (FuncCreateParser)DLLHelper::get_symbol(hInst, "createParser"); if (NULL == pCreator) { WTSLogger::error_f("Entry function createParser not found"); return false; } _api = pCreator(); if (NULL == _api) { WTSLogger::error_f("Creating parser api failed"); return false; } m_funcRemover = (FuncDeleteParser)DLLHelper::get_symbol(hInst, "deleteParser"); return true; } public: virtual void handleParserLog(WTSLogLevel ll, const char* message) override { WTSLogger::log_raw(ll, message); } virtual void handleQuote(WTSTickData *quote, uint32_t procFlag) override { WTSLogger::info_f("{}@{}.{}, price:{}, voume:{}", quote->code(), quote->actiondate(), quote->actiontime(), quote->price(), quote->totalvolume()); } virtual void handleSymbolList(const WTSArray* aySymbols) override { } public: virtual IBaseDataMgr* getBaseDataMgr() { return &g_bdMgr; } private: IParserApi* _api; FuncDeleteParser m_funcRemover; std::string m_strModule; WTSVariant* m_pParams; }; std::string getBaseFolder() { static std::string basePath; if (basePath.empty()) { basePath = boost::filesystem::initial_path<boost::filesystem::path>().string(); basePath = StrUtil::standardisePath(basePath); } return basePath.c_str(); } int main() { WTSLogger::init("logcfg.yaml"); WTSVariant* root = WTSCfgLoader::load_from_file("config.yaml", true); if (root == NULL) { WTSLogger::log_raw(LL_ERROR, "Loading config.yaml failed"); return 0; } WTSVariant* cfg = root->get("config"); bool isUTF8 = cfg->getBoolean("utf8"); if (cfg->has("session")) g_bdMgr.loadSessions(cfg->getCString("session"), isUTF8); if (cfg->has("commodity")) g_bdMgr.loadCommodities(cfg->getCString("commodity"), isUTF8); if (cfg->has("contract")) g_bdMgr.loadContracts(cfg->getCString("contract"), isUTF8); std::string module = cfg->getCString("parser"); std::string profile = cfg->getCString("profile"); WTSVariant* params = root->get(profile.c_str()); if (params == NULL) { WTSLogger::error_f("Configure {} not exist", profile); return 0; } ParserSpi* parser = new ParserSpi; parser->init(params, module.c_str()); parser->run(); root->release(); getchar(); //exit(9); parser->release(); delete parser; return 0; }
//$Id$ //------------------------------------------------------------------------------ // SolarRadiationPressure //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool. // // Copyright (c) 2002 - 2015 United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. // All Other 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. // // Developed jointly by NASA/GSFC and Thinking Systems, Inc. under contract // number S-67573-G // // Author: D.Conway // Created: 2003/03/14 // Modified: 2003/03/30 Waka Waktola GSFC Code 583 // Updated for GMAT style, standards. /// /** * This is the SolarRadiationPressure class. * * @note original prolog information included at end of file prolog. */ // *** File Name : SolarRadiationPressure.cpp // *** Created : February 27, 2003 // ************************************************************************** // *** Developed By : Thinking Systems, Inc. (www.thinksysinc.com) *** // *** For: Flight Dynamics Analysis Branch (Code 572) *** // *** Under Contract: P.O. GSFC S-66617-G *** // *** *** // *** Copyright U.S. Government 2002 *** // *** Copyright United States Government as represented by the *** // *** Administrator of the National Aeronautics and Space *** // *** Administration *** // *** *** // *** This software is subject to the Sofware Usage Agreement described *** // *** by NASA Case Number GSC-14735-1. The Softare Usage Agreement *** // *** must be included in any distribution. Removal of this header is *** // *** strictly prohibited. *** // *** *** // *** *** // *** Header Version: July 12, 2002 *** // ************************************************************************** // Module Type : ANSI C++ Source // Development Environment : Visual C++ 7.0 // ************************************************************************** #ifndef SolarRadiationPressure_hpp #define SolarRadiationPressure_hpp #include "PhysicalModel.hpp" #include "SolarSystem.hpp" #include "CelestialBody.hpp" #include "Rvector6.hpp" #include "gmatdefs.hpp" #include "ShadowState.hpp" /** * Solar radiation pressure model -- currently incomplete * * This class models solar radiation pressure. The current implementation * builds a force directed along the x-axis with magnitude equal to a nominal * SRP acceleration. The force toggles on and off at 40 minute intervals. * * Note that this is <B>NOT</B> an implementation of Solar Radiation Pressure * in its current form because (1) the force is not applied in the correct * direction and (2) the magnitude of the force does bot change with distance * from the Sun. The current implementation is used solely to test * discontinuities in the force model. */ class GMAT_API SolarRadiationPressure : public PhysicalModel { public: SolarRadiationPressure(const std::string &name = ""); //loj: 5/28/04 added default virtual ~SolarRadiationPressure(); SolarRadiationPressure(const SolarRadiationPressure &srp); SolarRadiationPressure& operator=(const SolarRadiationPressure &srp); virtual bool IsUnique(const std::string &forBody = ""); virtual bool Initialize(); virtual bool SetCentralBody(); virtual bool GetDerivatives(Real *state, Real dt = 0.0, Integer order = 1, const Integer id = -1); virtual Rvector6 GetDerivativesForSpacecraft(Spacecraft *sc); // inherited from GmatBase virtual GmatBase* Clone() const; // Parameter access methods - overridden from GmatBase virtual std::string GetParameterText(const Integer id) const; virtual Integer GetParameterID(const std::string &str) const; virtual Gmat::ParameterType GetParameterType(const Integer id) const; virtual std::string GetParameterTypeString(const Integer id) const; virtual bool IsParameterReadOnly(const Integer id) const; virtual Real GetRealParameter(const Integer id) const; virtual Real SetRealParameter(const Integer id, const Real value); virtual bool GetBooleanParameter(const Integer id) const; virtual bool SetBooleanParameter(const Integer id, const bool value); virtual Integer GetIntegerParameter(const Integer id) const; virtual Integer SetIntegerParameter(const Integer id, const Integer value); virtual std::string GetStringParameter(const Integer id) const; virtual std::string GetStringParameter(const std::string &label) const; virtual bool SetStringParameter(const Integer id, const std::string &value); virtual bool SetStringParameter(const std::string &label, const char *value); virtual bool SetStringParameter(const std::string &label, const std::string &value); virtual const StringArray& GetPropertyEnumStrings(const Integer id) const; virtual void SetSatelliteParameter(const Integer i, const std::string parmName, const Real parm, const Integer parmID = -1); virtual void SetSatelliteParameter(const Integer i, Integer parmID, const Real parm); virtual void ClearSatelliteParameters(const std::string parmName = ""); virtual void SetSpaceObject(const Integer i, GmatBase *obj); // Methods used by the ODEModel to set the state indexes, etc virtual bool SupportsDerivative(Gmat::StateElementId id); virtual bool SetStart(Gmat::StateElementId id, Integer index, Integer quantity); DEFAULT_TO_NO_CLONES DEFAULT_TO_NO_REFOBJECTS protected: // Parameter IDs enum { SHADOWMODELTYPE, /// ID for the type of shadow model to use VECTORTYPE /// ID for the force orientation model to use // ParamCount /// Count of the parameters for this class waw: 04/19/04 }; /// Enumeration to ease pain of figuring out which shadow model is active enum ShadowModel { CYLINDRICAL_MODEL = 1, CONICAL_MODEL }; /// Enumeration to ease pain of determining which force direction is active enum ForceDirection { SUN_PARALLEL = 1, ATTITUDE_BASED }; /// Pointer to the source of planetary ephemerides CelestialBody *theSun; /// Pointer to the ShadowState ShadowState *shadowState; /// Flag used to indicate using an analytic model to locate the Sun bool useAnalytic; /// Shadow model type indicator: 1 for cylinder, 2 for cones Integer shadowModel; /// Vector model: 1 for (anti)parallel to Sun, 2 attitude based Integer vectorModel; /// Radius of the body casting the shadow Real bodyRadius; /// Vector to the Sun from the central body -- eventually from DE file Real *cbSunVector; /// Vector to the Sun from the spacecraft Real *forceVector; /// Radius of the Sun Real sunRadius; /// Flag used to indicate that there are other bodies casting shadows bool hasMoons; /// Basically the reflectivity of the body experiencing the force std::vector<Real> cr; /// Reflective surface area of the body, in square meters std::vector<Real> area; /// Mass of the body, in kg std::vector<Real> mass; /// Pointers to the spacecraft std::vector<GmatBase*> scObjs; /// Solar flux, in W/m^2 Real flux; /// Solar flux, in N/m^2 Real fluxPressure; // the model to use - Spherical or SPADFile std::string srpModel; /// Distance from the Sun, currently set to a dummy value Real sunDistance; /// Nominal distance to the Sun used in the model: 1 AU Real nominalSun; /// Flag used to detect if the central body is Sol bool bodyIsTheSun; // Conical shadow model parameters that are used in multiple methods /// Conical model: projected sun radius Real psunrad; /// Conical model: projected central body radius Real pcbrad; /// Weighting for partial lighting Real percentSun; /// Central body ID for the model Integer bodyID; Rvector6 sunrv; Rvector6 cbrv; /// Number of spacecraft in the state vector that use CartesianState Integer satCount; // /// Start index for the Cartesian state // Integer cartIndex; // /// Flag indicating if the Cartesian state should be populated // bool fillCartesian; // // /// Number of spacecraft in the state vector that use OrbitSTM // Integer stmCount; // /// Start index for the OrbitSTM // Integer stmIndex; // /// Flag indicating if the OrbitSTM should be populated // bool fillSTM; Integer massID; Integer crID; Integer areaID; // void FindShadowState(bool &lit, bool &dark, Real *state); // Real ShadowFunction(Real *state); Rvector6 ComputeSPADAcceleration(Integer scID, Real ep, Real *state, Real *cbSun); static const Real FLUX_LOWER_BOUND; static const Real FLUX_UPPER_BOUND; static const Real FLUX_PRESSURE_LOWER_BOUND; static const Real FLUX_PRESSURE_UPPER_BOUND; static const Real NOMINAL_SUN_LOWER_BOUND; static const Real NOMINAL_SUN_UPPER_BOUND; private: /// Parameter IDs enum { USE_ANALYTIC = PhysicalModelParamCount, SHADOW_MODEL, VECTOR_MODEL, BODY_RADIUS, SUN_RADIUS, HAS_MOONS, CR, AREA, MASS, FLUX, FLUX_PRESSURE, SRP_MODEL, SUN_DISTANCE, NOMINAL_SUN, PSUNRAD, PCBRAD, PERCENT_SUN, SRPParamCount // Count of the parameters for this class }; static const std::string PARAMETER_TEXT[SRPParamCount - PhysicalModelParamCount]; static const Gmat::ParameterType PARAMETER_TYPE[SRPParamCount - PhysicalModelParamCount]; }; #endif
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <algorithm> #include <array> #include <string> #include "base/bind.h" #include "base/logging.h" #include "base/metrics/histogram_functions.h" #include "base/strings/string_piece.h" #include "base/strings/string_util.h" #include "base/task/post_task.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "base/task_runner_util.h" #include "base/version.h" #include "chrome/browser/chromeos/printing/printer_info.h" #include "printing/backend/cups_jobs.h" #include "printing/printer_status.h" namespace { const char kPdfMimeType[] = "application/pdf"; const char kPwgRasterMimeType[] = "image/pwg-raster"; const char kPwgRasterDocumentResolutionSupported[] = "Printing.CUPS.PwgRasterDocumentResolutionSupported"; // List of known multi-word printer manufacturers to help with make-and-model // string parsing. Keep in UPPER CASE as that's how matches are performed. const std::array<const char* const, 4> kMultiWordManufacturers{ {"FUJI XEROX", "KODAK FUNAI", "KONICA MINOLTA", "TEXAS INSTRUMENTS"}}; // Wraps several printing data structures so that we can use // PostTaskAndReplyWithResult(). struct QueryResult { printing::PrinterQueryResult result; printing::PrinterInfo printer_info; printing::PrinterStatus printer_status; }; // Enums for Printing.CUPS.HighestIppVersion. Do not delete entries. Keep // synced with enums.xml. Represents IPP versions 1.0, 1.1, 2.0, 2.1, and 2.2. // Error is used if the version was unparsable. OutOfRange is used for values // that are not currently mapped. enum class IppVersion { kError, kUnknown, k10, k11, k20, k21, k22, kMaxValue = k22 }; // Returns the length of the portion of |make_and_model| representing the // manufacturer. This is either a value from kMultiWordManufacaturers or the // first token. If there is only one token or less, we assume that it does not // represent the manufacturer and return 0. size_t ManufacturerLength(base::StringPiece make_and_model) { // TODO(crbug.com/729245): Update when better data is available. for (base::StringPiece multi_word_manufacturer : kMultiWordManufacturers) { if (base::StartsWith(make_and_model, multi_word_manufacturer, base::CompareCase::INSENSITIVE_ASCII)) { return multi_word_manufacturer.size(); } } // The position of the first space is equal to the length of the first token. size_t first_space = make_and_model.find(" "); return first_space != base::StringPiece::npos ? first_space : 0; } using MajorMinor = std::pair<uint32_t, uint32_t>; using VersionEntry = std::pair<MajorMinor, IppVersion>; IppVersion ToIppVersion(const base::Version& version) { constexpr std::array<VersionEntry, 5> kVersions = { VersionEntry(MajorMinor((uint32_t)1, (uint32_t)0), IppVersion::k10), VersionEntry(MajorMinor((uint32_t)1, (uint32_t)1), IppVersion::k11), VersionEntry(MajorMinor((uint32_t)2, (uint32_t)0), IppVersion::k20), VersionEntry(MajorMinor((uint32_t)2, (uint32_t)1), IppVersion::k21), VersionEntry(MajorMinor((uint32_t)2, (uint32_t)2), IppVersion::k22)}; if (!version.IsValid()) { return IppVersion::kError; } const auto& components = version.components(); if (components.size() != 2) { return IppVersion::kError; } const auto target = MajorMinor(components[0], components[1]); const VersionEntry* iter = std::find_if( kVersions.cbegin(), kVersions.cend(), [target](const VersionEntry& entry) { return entry.first == target; }); if (iter == kVersions.end()) { return IppVersion::kUnknown; } return iter->second; } // Returns true if any of the |ipp_versions| are greater than or equal to 2.0. bool AllowedIpp(const std::vector<base::Version>& ipp_versions) { auto found = std::find_if(ipp_versions.begin(), ipp_versions.end(), [](const base::Version& version) { return version.IsValid() && version.components()[0] >= 2; }); return found != ipp_versions.end(); } // Returns true if |mime_type| is one of the supported types. bool SupportedMime(const std::string& mime_type) { return mime_type == kPwgRasterMimeType || mime_type == kPdfMimeType; } // Returns true if |formats| contains one of the supported printer description // languages for an autoconf printer identified by MIME type. bool SupportsRequiredPDLS(const std::vector<std::string>& formats) { auto found = std::find_if(formats.begin(), formats.end(), &SupportedMime); return found != formats.end(); } // Returns true if |info| describes a printer for which we want to attempt // automatic configuration. bool IsAutoconf(const ::printing::PrinterInfo& info) { return info.ipp_everywhere || (AllowedIpp(info.ipp_versions) && SupportsRequiredPDLS(info.document_formats)); } // Dispatches an IPP request to |host| to retrieve printer information. Returns // a nullptr if the request fails. QueryResult QueryPrinterImpl(const std::string& host, const int port, const std::string& path, bool encrypted) { QueryResult result; result.result = ::printing::GetPrinterInfo(host, port, path, encrypted, &result.printer_info, &result.printer_status); if (result.result != ::printing::PrinterQueryResult::SUCCESS) { LOG(ERROR) << "Could not retrieve printer info"; } return result; } // Handles the request for |info|. Parses make and model information before // calling |callback|. void OnPrinterQueried(chromeos::PrinterInfoCallback callback, const QueryResult& query_result) { const ::printing::PrinterQueryResult& result = query_result.result; const ::printing::PrinterInfo& printer_info = query_result.printer_info; const ::printing::PrinterStatus& printer_status = query_result.printer_status; if (result != ::printing::PrinterQueryResult::SUCCESS) { VLOG(1) << "Could not reach printer"; std::move(callback).Run(result, ::printing::PrinterStatus(), std::string(), std::string(), std::string(), {}, false); return; } base::StringPiece make_and_model(printer_info.make_and_model); base::StringPiece make; base::StringPiece model; size_t split = ManufacturerLength(make_and_model); if (split != 0) { make = make_and_model.substr(0, split); model = make_and_model.substr(split + 1); } else { // If there's only one word or an empty string, use it. model = make_and_model; } base::UmaHistogramBoolean(kPwgRasterDocumentResolutionSupported, printer_info.supports_pwg_raster_resolution); DCHECK(!printer_info.ipp_versions.empty()) << "Properly queried PrinterInfo always has at least one version"; base::UmaHistogramEnumeration( "Printing.CUPS.HighestIppVersion", ToIppVersion(*std::max_element(printer_info.ipp_versions.begin(), printer_info.ipp_versions.end()))); std::move(callback).Run(result, printer_status, make.as_string(), model.as_string(), printer_info.make_and_model, printer_info.document_formats, IsAutoconf(printer_info)); } } // namespace namespace chromeos { void QueryIppPrinter(const std::string& host, const int port, const std::string& path, bool encrypted, PrinterInfoCallback callback) { DCHECK(!host.empty()); // QueryPrinterImpl could block on a network call for a noticable amount of // time (100s of ms). Also the user is waiting on this result. Thus, run at // USER_VISIBLE with MayBlock. base::ThreadPool::PostTaskAndReplyWithResult( FROM_HERE, {base::TaskPriority::USER_VISIBLE, base::MayBlock()}, base::BindOnce(&QueryPrinterImpl, host, port, path, encrypted), base::BindOnce(&OnPrinterQueried, std::move(callback))); } } // namespace chromeos
//////////////////////////////////////////////////////////////////////////// // Module : script_binder_object_script.cpp // Created : 29.03.2004 // Modified : 29.03.2004 // Author : Dmitriy Iassenev // Description : Script object binder script export //////////////////////////////////////////////////////////////////////////// #include "pch_script.h" #include "script_binder_object.h" #include "script_export_space.h" #include "script_binder_object_wrapper.h" #include "xrServer_Objects_ALife.h" #include "../../xrNetServer/net_utils.h" using namespace luabind; #pragma optimize("s",on) void CScriptBinderObject::script_register(lua_State *L) { module(L) [ class_<CScriptBinderObject,CScriptBinderObjectWrapper>("object_binder") .def_readonly("object", &CScriptBinderObject::m_object) .def( constructor<CScriptGameObject*>()) .def("reinit", &CScriptBinderObject::reinit, &CScriptBinderObjectWrapper::reinit_static) .def("reload", &CScriptBinderObject::reload, &CScriptBinderObjectWrapper::reload_static) .def("net_spawn", &CScriptBinderObject::net_Spawn, &CScriptBinderObjectWrapper::net_Spawn_static) .def("net_destroy", &CScriptBinderObject::net_Destroy, &CScriptBinderObjectWrapper::net_Destroy_static) .def("net_import", &CScriptBinderObject::net_Import, &CScriptBinderObjectWrapper::net_Import_static) .def("net_export", &CScriptBinderObject::net_Export, &CScriptBinderObjectWrapper::net_Export_static) .def("update", &CScriptBinderObject::shedule_Update, &CScriptBinderObjectWrapper::shedule_Update_static) .def("save", &CScriptBinderObject::save, &CScriptBinderObjectWrapper::save_static) .def("load", &CScriptBinderObject::load, &CScriptBinderObjectWrapper::load_static) .def("net_save_relevant", &CScriptBinderObject::net_SaveRelevant, &CScriptBinderObjectWrapper::net_SaveRelevant_static) .def("net_Relcase", &CScriptBinderObject::net_Relcase, &CScriptBinderObjectWrapper::net_Relcase_static) ]; }